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
a9ee6c8eb954e5d1e228ddbd8dddbad0f1b81242
9dc8cecdf3c4634764a18254e94d43da07142918
/src/tactic/congrm.lean
37c7116e0ca1a9a63c5b7bc92ab9d892b66d58d0
[ "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
7,909
lean
/- Copyright (c) 2022 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Damiano Testa -/ import tactic.interactive /-! `congrm`: `congr` with pattern-matching `congrm e` gives to the use the functionality of using `congr` with an expression `e` "guiding" `congr` through the matching. This allows more flexibility than `congr' n`, which enters uniformly through `n` iterations. Instead, we can guide the matching deeper on some parts of the expression and stop earlier on other parts. ## Implementation notes ### Function underscores See the doc-string to `tactic.interactive.congrm` for more details. Here we describe how to add more "function underscores". The pattern for generating a function underscore is to define a "generic" `n`-ary function, for some number `n`. You can take a look at `tactic.congrm_fun_1, ..., tactic.congrm_fun_4`. These implement the "function underscores" `_₁, ..., _₄`. If you want a different arity for your function, simply introduce ```lean @[nolint unused_arguments] def congrm_fun_n {α₁ … αₙ ρ} {r : ρ} : α₁ → ⋯ → aₙ → ρ := λ _ … _, r notation `_ₙ` := congrm_fun_n ``` _Warning:_ `convert_to_explicit` checks that the first 18 characters in the name of `_ₙ` are identical to `tactic.congrm_fun_` to perform its job. Thus, if you want to implement "function underscores" with different arity, either make sure that their names begin with `tactic.congrm_fun_` or you should change `convert_to_explicit` accordingly. -/ namespace tactic /-- A generic function with one argument. It is the "function underscore" input to `congrm`. -/ @[nolint unused_arguments] def congrm_fun_1 {α ρ} {r : ρ} : α → ρ := λ _, r notation `_₁` := congrm_fun_1 /-- A generic function with two arguments. It is the "function underscore" input to `congrm`. -/ @[nolint unused_arguments] def congrm_fun_2 {α β ρ} {r : ρ} : α → β → ρ := λ _ _, r notation `_₂` := congrm_fun_2 /-- A generic function with three arguments. It is the "function underscore" input to `congrm`. -/ @[nolint unused_arguments] def congrm_fun_3 {α β γ ρ} {r : ρ} : α → β → γ → ρ := λ _ _ _, r notation `_₃` := congrm_fun_3 /-- A generic function with four arguments. It is the "function underscore" input to `congrm`. -/ @[nolint unused_arguments] def congrm_fun_4 {α β γ δ ρ} {r : ρ} : α → β → γ → δ → ρ := λ _ _ _ _, r notation `_₄` := congrm_fun_4 /-- Replaces a "function underscore" input to `congrm` into the correct expression, read off from the left-hand-side of the target expression. -/ meta def convert_to_explicit (pat lhs : expr) : tactic expr := if pat.get_app_fn.const_name.to_string.starts_with "tactic.congrm_fun_" then pat.list_explicit_args >>= lhs.replace_explicit_args else return pat /-- For each element of `list congr_arg_kind` that is `eq`, add a pair `(g, pat)` to the final list. Otherwise, discard an appropriate number of initial terms from each list (possibly none from the first) and repeat. `pat` is the given pattern-piece at the appropriate location, extracted from the last `list expr`. It appears to be the list of arguments of a function application. `g` is possibly the proof of an equality? It is extracted from the first `list expr`. -/ private meta def extract_subgoals : list expr → list congr_arg_kind → list expr → tactic (list (expr × expr)) | (_ :: _ :: g :: prf_args) (congr_arg_kind.eq :: kinds) (pat :: pat_args) := (λ rest, (g, pat) :: rest) <$> extract_subgoals prf_args kinds pat_args | (_ :: prf_args) (congr_arg_kind.fixed :: kinds) (_ :: pat_args) := extract_subgoals prf_args kinds pat_args | prf_args (congr_arg_kind.fixed_no_param :: kinds) (_ :: pat_args) := extract_subgoals prf_args kinds pat_args | (_ :: _ :: prf_args) (congr_arg_kind.cast :: kinds) (_ :: pat_args) := extract_subgoals prf_args kinds pat_args | _ _ [] := pure [] | _ _ _ := fail "unsupported congr lemma" /-- `equate_with_pattern_core pat` solves a single goal of the form `lhs = rhs` (assuming that `lhs` and `rhs` are unifiable with `pat`) by applying congruence lemmas until `pat` is a metavariable. Returns the list of metavariables for the new subgoals at the leafs. Calls `set_goals []` at the end. -/ meta def equate_with_pattern_core : expr → tactic (list expr) | pat := (applyc ``subsingleton.elim >> pure []) <|> (applyc ``rfl >> pure []) <|> if pat.is_mvar || pat.get_delayed_abstraction_locals.is_some then do try $ applyc ``_root_.propext, get_goals <* set_goals [] else match pat with | expr.app _ _ := do `(%%lhs = %%_) ← target, pat ← convert_to_explicit pat lhs, cl ← mk_specialized_congr_lemma pat, H_congr_lemma ← assertv `H_congr_lemma cl.type cl.proof, [prf] ← get_goals, apply H_congr_lemma <|> fail "could not apply congr_lemma", all_goals' $ try $ clear H_congr_lemma, -- given the `set_goals []` that follows, is this needed? set_goals [], prf ← instantiate_mvars prf, subgoals ← extract_subgoals prf.get_app_args cl.arg_kinds pat.get_app_args, subgoals ← subgoals.mmap (λ ⟨subgoal, subpat⟩, do set_goals [subgoal], equate_with_pattern_core subpat), pure subgoals.join | expr.lam _ _ _ body := do applyc ``_root_.funext, x ← intro pat.binding_name, equate_with_pattern_core $ body.instantiate_var x | expr.pi _ _ _ codomain := do applyc ``_root_.pi_congr, x ← intro pat.binding_name, equate_with_pattern_core $ codomain.instantiate_var x | _ := do pat ← pp pat, fail $ to_fmt "unsupported pattern:\n" ++ pat end /-- `equate_with_pattern pat` solves a single goal of the form `lhs = rhs` (assuming that `lhs` and `rhs` are unifiable with `pat`) by applying congruence lemmas until `pat` is a metavariable. The subgoals for the leafs are prepended to the goals. --/ meta def equate_with_pattern (pat : expr) : tactic unit := do congr_subgoals ← solve1 (equate_with_pattern_core pat), gs ← get_goals, set_goals $ congr_subgoals ++ gs end tactic namespace tactic.interactive open tactic interactive setup_tactic_parser /-- Assume that the goal is of the form `lhs = rhs` or `lhs ↔ rhs`. `congrm e` takes an expression `e` containing placeholders `_` and scans `e, lhs, rhs` in parallel. It matches both `lhs` and `rhs` to the pattern `e`, and produces one goal for each placeholder, stating that the corresponding subexpressions in `lhs` and `rhs` are equal. Examples: ```lean example {a b c d : ℕ} : nat.pred a.succ * (d + (c + a.pred)) = nat.pred b.succ * (b + (c + d.pred)) := begin congrm nat.pred (nat.succ _) * (_ + _), /- Goals left: ⊢ a = b ⊢ d = b ⊢ c + a.pred = c + d.pred -/ sorry, sorry, sorry, end example {a b : ℕ} (h : a = b) : (λ y : ℕ, ∀ z, a + a = z) = (λ x, ∀ z, b + a = z) := begin congrm λ x, ∀ w, _ + a = w, -- produces one goal for the underscore: ⊢ a = b exact h, end ``` The tactic also allows for "function underscores", denoted by `_₁, ..., _₄`. The index denotes the number of explicit arguments of the function to be matched. If `e` has a "function underscore" in a location, then the tactic reads off the function `f` that appears in `lhs` at the current location, replacing the *explicit* arguments of `f` by the user inputs to the "function underscore". After that, `congrm` continues with its matching. -/ meta def congrm (arg : parse texpr) : tactic unit := do try $ applyc ``_root_.eq.to_iff, `(@eq %%ty _ _) ← target | fail "congrm: goal must be an equality or iff", ta ← to_expr ``((%%arg : %%ty)) tt ff, equate_with_pattern ta add_tactic_doc { name := "congrm", category := doc_category.tactic, decl_names := [`tactic.interactive.congrm], tags := ["congruence"] } end tactic.interactive
acf2bbd96d461338ab0d114496495270dc75aaf7
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/tactic/nat.lean
6995bcc90412f954af35e0c7c97a89e47167128c
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,896
lean
import galois.nat.simplify_le namespace galois.tactic.nat open nat open tactic local attribute [simp] nat.succ_le_succ_iff local attribute [simp] nat.not_succ_le_zero theorem one_add_bit1 (x : ℕ) : 1 + bit1 x = bit0 (1 + x) := begin cases x, { simp, }, { simp [succ_add, bit1, bit0], }, end theorem bit0_add_one (x : ℕ) : bit0 x + 1 = bit1 x := begin simp [bit1], end theorem bit0_add_bit0 (x y : ℕ) : bit0 x + bit0 y = bit0 (x + y) := begin cases x, { simp [bit0], }, { simp [succ_add, add_succ, bit0], }, end theorem bit1_add_one (x : ℕ) : bit1 x + 1 = bit0 (x + 1) := begin cases x, { simp [bit0, bit1], }, { simp [succ_add, add_succ, bit1, bit0], }, end theorem bit1_add_bit1 (x y : ℕ) : bit1 x + bit1 y = bit0 (x + y + 1) := begin cases x, { simp [bit0, bit1], }, { simp [succ_add, add_succ, bit1, bit0], }, end theorem one_le_bit0 (x : ℕ) : (1 ≤ bit0 x) ↔ (1 ≤ x) := begin cases x, { simp [bit0], }, { simp [bit0, zero_le], }, end theorem one_le_bit1 (x : ℕ) : (1 ≤ bit1 x) ↔ true := begin cases x, { simp [bit0], }, { simp [bit0, bit1, add_succ, zero_le], }, end theorem bit0_le_bit0 (x y : ℕ) : (bit0 x ≤ bit0 y) ↔ (x ≤ y) := begin revert y, induction x with x ind, { simp [zero_le], }, { intro y, cases y with y, { simp [bit0, succ_add, not_succ_le_zero], }, { simp [bit0, succ_add, add_succ], simp [bit0] at ind, apply ind, }, }, end theorem bit0_le_bit1 (x y : ℕ) : (bit0 x ≤ bit1 y) ↔ (x ≤ y) := begin revert y, induction x with x ind, { simp [zero_le], }, { intro y, cases y with y, { simp [bit0, bit1, add_succ ], }, { simp [bit0, bit1, add_succ, succ_add], simp [bit0, bit1, add_succ] at ind, apply ind, } }, end theorem bit1_le_bit0 (x y : ℕ) : (bit1 x ≤ bit0 y) ↔ (x + 1 ≤ y) := begin revert y, induction x with x ind, { intro y, cases y with y, { simp [bit1, bit0], }, { simp [bit1, bit0, zero_le], }, }, { intro y, cases y with y, { simp [bit0, bit1, add_succ], }, { simp [bit0, bit1, add_succ, succ_add], simp [bit0, bit1, add_succ] at ind, apply ind, }, }, end theorem bit1_le_bit1 (x y : ℕ) : (bit1 x ≤ bit1 y) ↔ (x ≤ y) := begin revert y, induction x with x ind, { simp [zero_le, bit1, bit0, add_succ], }, { intro y, cases y with y, { simp [bit0, bit1, add_succ], }, { simp [bit0, bit1, add_succ, succ_add], simp [bit0, bit1, add_succ] at ind, apply ind, } }, end meta def nat_lit_le : tactic unit := do let lemmas : list expr := [ expr.const `norm_num.bin_zero_add [level.zero] , expr.const `norm_num.one_add_one [level.zero] , expr.const `norm_num.one_add_bit0 [level.zero] , expr.const `galois.tactic.nat.one_add_bit1 [] , expr.const `galois.tactic.nat.bit0_add_one [] , expr.const `galois.tactic.nat.bit0_add_bit0 [] , expr.const `norm_num.bit0_add_bit1 [level.zero] , expr.const `galois.tactic.nat.bit1_add_one [] , expr.const `norm_num.bit1_add_bit0 [level.zero] , expr.const `galois.tactic.nat.bit1_add_bit1 [] , expr.const `norm_num.mul_zero [level.zero] , expr.const `norm_num.mul_one [level.zero] , expr.const `norm_num.mul_bit0 [level.zero] , expr.const `norm_num.mul_bit1 [level.zero] , expr.const `nat.zero_le [] , expr.const `nat.le_refl [] , expr.const `galois.tactic.nat.one_le_bit0 [] , expr.const `galois.tactic.nat.one_le_bit1 [] , expr.const `galois.tactic.nat.bit0_le_bit0 [] , expr.const `galois.tactic.nat.bit0_le_bit1 [] , expr.const `galois.tactic.nat.bit1_le_bit0 [] , expr.const `galois.tactic.nat.bit1_le_bit1 [] ] in do s ← simp_lemmas.mk_default, s ← s.append lemmas, tactic.simp_target s, try tactic.triv open tactic open monad end galois.tactic.nat
806e7e9c1e3f1223ec68fd5877d8577be094f134
7007bb645068e0b6b859aab9da7cf5c1c79e98be
/library/init/meta/widget/html_cmd.lean
d84cf9c322288309c5a32ef6eb0de50c9c98b1f8
[ "Apache-2.0" ]
permissive
EdAyers/lean
7d3fb852380bc386545ebc119b7d03c128c3ce1c
be72c8dc527a062e243a408480f487a55b06cb0a
refs/heads/master
1,624,443,179,694
1,592,837,958,000
1,592,837,958,000
154,972,348
0
0
Apache-2.0
1,557,768,267,000
1,540,649,772,000
C++
UTF-8
Lean
false
false
1,001
lean
/- Copyright (c) E.W.Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: E.W.Ayers -/ prelude import init.meta.widget.basic import init.meta.lean.parser import init.meta.interactive_base import init.data.punit open lean open lean.parser open interactive open tactic open widget /-- Accepts terms with the type `component tactic_state string` or `html empty` and renders them interactively. -/ @[user_command] meta def show_widget_cmd (x : parse $ tk "#html") : parser unit := do ⟨l,c⟩ ← cur_pos, y ← parser.pexpr, comp ← parser.of_tactic ((do tactic.eval_pexpr (component tactic_state string) y ) <|> (do htm : html empty ← tactic.eval_pexpr (html empty) y, c : component unit empty ← pure $ component.stateless (λ _, [htm]), pure $ component.ignore_props $ component.ignore_action $ c )), save_widget ⟨l,c - ("#html").length - 1⟩ comp, trace "successfully rendered widget" pure () run_cmd skip
9c1bb32be32f621a2bf74b862ae37cfc084fd894
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/withAssignableSyntheticOpaqueBug.lean
a7e5d52129e55e374643cc2b9b79a3fe4ab9a03a
[ "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
623
lean
import Lean open Lean Meta def tst : MetaM Unit := do let (e, m) ← withLocalDeclD `x (mkConst ``Nat) fun x => do let m ← mkFreshExprMVar (mkConst ``Nat) .syntheticOpaque return (← mkLambdaFVars #[x] m, m) IO.println (← ppExpr e) lambdaTelescope e fun _ b => do assert! (← withAssignableSyntheticOpaque <| isDefEq b (mkNatLit 0)) let m' := b.getAppFn assert! m'.isMVar IO.println (← getExprMVarAssignment? m'.mvarId!) IO.println (← getExprMVarAssignment? m.mvarId!) IO.println (← ppExpr (← instantiateMVars b)) IO.println (← ppExpr m) return () #eval tst
9090520d88cbb21c87595f8cebca7161e0334d25
618003631150032a5676f229d13a079ac875ff77
/src/data/int/gcd.lean
ec27c84687cbf6759b0955046836d4d0d7e742fd
[ "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
5,151
lean
/- Copyright (c) 2018 Guy Leroy. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sangwoo Jo (aka Jason), Guy Leroy, Johannes Hölzl, Mario Carneiro -/ import data.nat.prime /-! # Extended GCD and divisibility over ℤ ## Main definitions * Given `x y : ℕ`, `xgcd x y` computes the pair of integers `(a, b)` such that `gcd x y = x * a + y * b`. `gcd_a x y` and `gcd_b x y` are defined to be `a` and `b`, respectively. ## Main statements * `gcd_eq_gcd_ab`: Bézout's lemma, given `x y : ℕ`, `gcd x y = x * gcd_a x y + y * gcd_b x y`. -/ /-! ### Extended Euclidean algorithm -/ namespace nat /-- Helper function for the extended GCD algorithm (`nat.xgcd`). -/ def xgcd_aux : ℕ → ℤ → ℤ → ℕ → ℤ → ℤ → ℕ × ℤ × ℤ | 0 s t r' s' t' := (r', s', t') | r@(succ _) s t r' s' t' := have r' % r < r, from mod_lt _ $ succ_pos _, let q := r' / r in xgcd_aux (r' % r) (s' - q * s) (t' - q * t) r s t @[simp] theorem xgcd_zero_left {s t r' s' t'} : xgcd_aux 0 s t r' s' t' = (r', s', t') := by simp [xgcd_aux] theorem xgcd_aux_rec {r s t r' s' t'} (h : 0 < r) : xgcd_aux r s t r' s' t' = xgcd_aux (r' % r) (s' - (r' / r) * s) (t' - (r' / r) * t) r s t := by cases r; [exact absurd h (lt_irrefl _), {simp only [xgcd_aux], refl}] /-- Use the extended GCD algorithm to generate the `a` and `b` values satisfying `gcd x y = x * a + y * b`. -/ def xgcd (x y : ℕ) : ℤ × ℤ := (xgcd_aux x 1 0 y 0 1).2 /-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_a (x y : ℕ) : ℤ := (xgcd x y).1 /-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_b (x y : ℕ) : ℤ := (xgcd x y).2 @[simp] theorem xgcd_aux_fst (x y) : ∀ s t s' t', (xgcd_aux x s t y s' t').1 = gcd x y := gcd.induction x y (by simp) (λ x y h IH s t s' t', by simp [xgcd_aux_rec, h, IH]; rw ← gcd_rec) theorem xgcd_aux_val (x y) : xgcd_aux x 1 0 y 0 1 = (gcd x y, xgcd x y) := by rw [xgcd, ← xgcd_aux_fst x y 1 0 0 1]; cases xgcd_aux x 1 0 y 0 1; refl theorem xgcd_val (x y) : xgcd x y = (gcd_a x y, gcd_b x y) := by unfold gcd_a gcd_b; cases xgcd x y; refl section parameters (x y : ℕ) private def P : ℕ × ℤ × ℤ → Prop | (r, s, t) := (r : ℤ) = x * s + y * t theorem xgcd_aux_P {r r'} : ∀ {s t s' t'}, P (r, s, t) → P (r', s', t') → P (xgcd_aux r s t r' s' t') := gcd.induction r r' (by simp) $ λ a b h IH s t s' t' p p', begin rw [xgcd_aux_rec h], refine IH _ p, dsimp [P] at *, rw [int.mod_def], generalize : (b / a : ℤ) = k, rw [p, p'], simp [mul_add, mul_comm, mul_left_comm, add_comm, add_left_comm, sub_eq_neg_add, mul_assoc] end /-- Bézout's lemma: given `x y : ℕ`, `gcd x y = x * a + y * b`, where `a = gcd_a x y` and `b = gcd_b x y` are computed by the extended Euclidean algorithm. -/ theorem gcd_eq_gcd_ab : (gcd x y : ℤ) = x * gcd_a x y + y * gcd_b x y := by have := @xgcd_aux_P x y x y 1 0 0 1 (by simp [P]) (by simp [P]); rwa [xgcd_aux_val, xgcd_val] at this end end nat /-! ### Divisibility over ℤ -/ namespace int theorem nat_abs_div (a b : ℤ) (H : b ∣ a) : nat_abs (a / b) = (nat_abs a) / (nat_abs b) := begin cases (nat.eq_zero_or_pos (nat_abs b)), {rw eq_zero_of_nat_abs_eq_zero h, simp [int.div_zero]}, calc nat_abs (a / b) = nat_abs (a / b) * 1 : by rw mul_one ... = nat_abs (a / b) * (nat_abs b / nat_abs b) : by rw nat.div_self h ... = nat_abs (a / b) * nat_abs b / nat_abs b : by rw (nat.mul_div_assoc _ (dvd_refl _)) ... = nat_abs (a / b * b) / nat_abs b : by rw (nat_abs_mul (a / b) b) ... = nat_abs a / nat_abs b : by rw int.div_mul_cancel H, end theorem nat_abs_dvd_abs_iff {i j : ℤ} : i.nat_abs ∣ j.nat_abs ↔ i ∣ j := ⟨assume (H : i.nat_abs ∣ j.nat_abs), dvd_nat_abs.mp (nat_abs_dvd.mp (coe_nat_dvd.mpr H)), assume H : (i ∣ j), coe_nat_dvd.mp (dvd_nat_abs.mpr (nat_abs_dvd.mpr H))⟩ lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : nat.prime p) {m n : ℤ} {k l : ℕ} (hpm : ↑(p ^ k) ∣ m) (hpn : ↑(p ^ l) ∣ n) (hpmn : ↑(p ^ (k+l+1)) ∣ m*n) : ↑(p ^ (k+1)) ∣ m ∨ ↑(p ^ (l+1)) ∣ n := have hpm' : p ^ k ∣ m.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpm, have hpn' : p ^ l ∣ n.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpn, have hpmn' : (p ^ (k+l+1)) ∣ m.nat_abs*n.nat_abs, by rw ←int.nat_abs_mul; apply (int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpmn), let hsd := nat.succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul p_prime hpm' hpn' hpmn' in hsd.elim (λ hsd1, or.inl begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd1 end) (λ hsd2, or.inr begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd2 end) theorem dvd_of_mul_dvd_mul_left {i j k : ℤ} (k_non_zero : k ≠ 0) (H : k * i ∣ k * j) : i ∣ j := dvd.elim H (λl H1, by rw mul_assoc at H1; exact ⟨_, eq_of_mul_eq_mul_left k_non_zero H1⟩) theorem dvd_of_mul_dvd_mul_right {i j k : ℤ} (k_non_zero : k ≠ 0) (H : i * k ∣ j * k) : i ∣ j := by rw [mul_comm i k, mul_comm j k] at H; exact dvd_of_mul_dvd_mul_left k_non_zero H end int
a5dd45a18edb23dc4f6c5746f4e007c7af1d01e7
9dc8cecdf3c4634764a18254e94d43da07142918
/src/meta/expr.lean
8072e982eb7032fdb769cec9e57f77951e4543b1
[ "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
49,224
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis, Floris van Doorn -/ import data.string.defs import tactic.derive_inhabited /-! # Additional operations on expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`. ## Tags expr, name, declaration, level, environment, meta, metaprogramming, tactic -/ open tactic attribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind namespace binder_info /-! ### Declarations about `binder_info` -/ instance : inhabited binder_info := ⟨ binder_info.default ⟩ /-- The brackets corresponding to a given binder_info. -/ def brackets : binder_info → string × string | binder_info.implicit := ("{", "}") | binder_info.strict_implicit := ("{{", "}}") | binder_info.inst_implicit := ("[", "]") | _ := ("(", ")") end binder_info namespace name /-! ### Declarations about `name` -/ /-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix with the value of `f n`. -/ def map_prefix (f : name → option name) : name → name | anonymous := anonymous | (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n') | (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n') /-- If `nm` is a simple name (having only one string component) starting with `_`, then `deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/ meta def deinternalize_field : name → name | (mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n /-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/ meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n /-- Auxiliary definition for `pop_nth_prefix` -/ private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) /-- Pops the top `n` prefixes from the given name. -/ meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n /-- Pop the prefix of a name -/ meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 /-- Auxiliary definition for `from_components` -/ private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : list string → name := from_components_aux name.anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p /-- Append a string to the last component of a name. -/ def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n /-- Update the last component of a name. -/ def update_last (f : string → string) : name → name | (mk_string s n) := mk_string (f s) n | n := n /-- `append_to_last nm s is_prefix` adds `s` to the last component of `nm`, either as prefix or as suffix (specified by `is_prefix`), separated by `_`. Used by `simps_add_projections`. -/ def append_to_last (nm : name) (s : string) (is_prefix : bool) : name := nm.update_last $ λ s', if is_prefix then s ++ "_" ++ s' else s' ++ "_" ++ s /-- The first component of a name, turning a number to a string -/ meta def head : name → string | (mk_string s anonymous) := s | (mk_string s p) := head p | (mk_numeral n p) := head p | anonymous := "[anonymous]" /-- Tests whether the first component of a name is `"_private"` -/ meta def is_private (n : name) : bool := n.head = "_private" /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ meta def length : name → ℕ | (mk_string s anonymous) := s.length | (mk_string s p) := s.length + 1 + p.length | (mk_numeral n p) := p.length | anonymous := "[anonymous]".length /-- Checks whether `nm` has a prefix (including itself) such that P is true -/ def has_prefix (P : name → bool) : name → bool | anonymous := ff | (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm | (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm /-- Appends `'` to the end of a name. -/ meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) /-- `last_string n` returns the rightmost component of `n`, ignoring numeral components. For example, ``last_string `a.b.c.33`` will return `` `c ``. -/ def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n /-- Like `++`, except that if the right argument starts with `_root_` the namespace will be ignored. ``` append_namespace `a.b `c.d = `a.b.c.d append_namespace `a.b `_root_.c.d = `c.d ``` -/ meta def append_namespace (ns : name) : name → name | (mk_string s anonymous) := if s = "_root_" then anonymous else mk_string s ns | (mk_string s p) := mk_string s (append_namespace p) | (mk_numeral n p) := mk_numeral n (append_namespace p) | anonymous := ns /-- Constructs a (non-simple) name from a string. Example: ``name.from_string "foo.bar" = `foo.bar`` -/ meta def from_string (s : string) : name := from_components $ s.split (= '.') /-- In surface Lean, we can write anonymous Π binders (i.e. binders where the argument is not named) using the function arrow notation: ```lean inductive test : Type | intro : unit → test ``` After elaboration, however, every binder must have a name, so Lean generates one. In the example, the binder in the type of `intro` is anonymous, so Lean gives it the name `ᾰ`: ```lean test.intro : ∀ (ᾰ : unit), test ``` When there are multiple anonymous binders, they are named `ᾰ_1`, `ᾰ_2` etc. Thus, when we want to know whether the user named a binder, we can check whether the name follows this scheme. Note, however, that this is not reliable. When the user writes (for whatever reason) ```lean inductive test : Type | intro : ∀ (ᾰ : unit), test ``` we cannot tell that the binder was, in fact, named. The function `name.is_likely_generated_binder_name` checks if a name is of the form `ᾰ`, `ᾰ_1`, etc. -/ library_note "likely generated binder names" /-- Check whether a simple name was likely generated by Lean to name an anonymous binder. Such names are either `ᾰ` or `ᾰ_n` for some natural `n`. See note [likely generated binder names]. -/ meta def is_likely_generated_binder_simple_name : string → bool | "ᾰ" := tt | n := match n.get_rest "ᾰ_" with | none := ff | some suffix := suffix.is_nat end /-- Check whether a name was likely generated by Lean to name an anonymous binder. Such names are either `ᾰ` or `ᾰ_n` for some natural `n`. See note [likely generated binder names]. -/ meta def is_likely_generated_binder_name (n : name) : bool := match n with | mk_string s anonymous := is_likely_generated_binder_simple_name s | _ := ff end end name namespace level /-! ### Declarations about `level` -/ /-- Tests whether a universe level is non-zero for all assignments of its variables -/ meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff /-- `l.fold_mvar f` folds a function `f : name → α → α` over each `n : name` appearing in a `level.mvar n` in `l`. -/ meta def fold_mvar {α} : level → (name → α → α) → α → α | zero f := id | (succ a) f := fold_mvar a f | (param a) f := id | (mvar a) f := f a | (max a b) f := fold_mvar a f ∘ fold_mvar b f | (imax a b) f := fold_mvar a f ∘ fold_mvar b f /-- `l.params` is the set of parameters occuring in `l`. For example if `l = max 1 (max (u+1) (max v w))` then `l.params = {u, v, w}`. -/ protected meta def params (u : level) : name_set := u.fold mk_name_set $ λ v l, match v with | (param nm) := l.insert nm | _ := l end end level /-! ### Declarations about `binder` -/ /-- The type of binders containing a name, the binding info and the binding type -/ @[derive decidable_eq, derive inhabited] meta structure binder := (name : name) (info : binder_info) (type : expr) namespace binder /-- Turn a binder into a string. Uses expr.to_string for the type. -/ protected meta def to_string (b : binder) : string := let (l, r) := b.info.brackets in l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r meta instance : has_to_string binder := ⟨ binder.to_string ⟩ meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩ meta instance : has_to_tactic_format binder := ⟨ λ b, let (l, r) := b.info.brackets in (λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩ end binder /-! ### Converting between expressions and numerals There are a number of ways to convert between expressions and numerals, depending on the input and output types and whether you want to infer the necessary type classes. See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`. -/ /-- `nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc. -/ meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr := let z : expr := `(@has_zero.zero.{0} %%type %%has_zero), o : expr := `(@has_one.one.{0} %%type %%has_one) in nat.binary_rec z (λ b n e, if n = 0 then o else if b then `(@bit1.{0} %%type %%has_one %%has_add %%e) else `(@bit0.{0} %%type %%has_add %%e)) /-- `int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc. -/ meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr | (int.of_nat n) := n.mk_numeral type has_zero has_one has_add | -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in `(@has_neg.neg.{0} %%type %%has_neg %%ne) /-- `nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`. The `pexpr` does not hold any typing information: `to_expr ``((%%(nat.to_pexpr 5) : ℤ))` will create a native integer numeral `(5 : ℤ)`. -/ meta def nat.to_pexpr : ℕ → pexpr | 0 := ``(0) | 1 := ``(1) | n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2))) /-- `int.to_pexpr n` creates a `pexpr` that will evaluate to `n`. The `pexpr` does not hold any typing information: `to_expr ``((%%(int.to_pexpr (-5)) : ℚ))` will create a native `ℚ` numeral `(-5 : ℚ)`. -/ meta def int.to_pexpr : ℤ → pexpr | (int.of_nat k) := k.to_pexpr | (int.neg_succ_of_nat k) := ``(-%%((k+1).to_pexpr)) namespace expr /-- Turns an expression into a natural number, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`. -/ protected meta def to_nat : expr → option ℕ | `(has_zero.zero) := some 0 | `(has_one.one) := some 1 | `(bit0 %%e) := bit0 <$> e.to_nat | `(bit1 %%e) := bit1 <$> e.to_nat | `(nat.succ %%e) := (+1) <$> e.to_nat | `(nat.zero) := some 0 | _ := none /-- Turns an expression into a integer, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head. -/ protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat /-- Turns an expression into a list, assuming it is only built up from `list.nil` and `list.cons`. -/ protected meta def to_list {α} (f : expr → option α) : expr → option (list α) | `(list.nil) := some [] | `(list.cons %%x %%l) := list.cons <$> f x <*> l.to_list | _ := none /-- `is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff end expr /-! ### Declarations about `pexpr` -/ namespace pexpr /-- If `e` is an annotation of `frozen_name` to `expr.const n`, `e.get_frozen_name` returns `n`. Otherwise, returns `name.anonymous`. -/ meta def get_frozen_name (e : pexpr) : name := match e.is_annotation with | some (`frozen_name, expr.const n _) := n | _ := name.anonymous end /-- If `e : pexpr` is a sequence of applications `f e₁ e₂ ... eₙ`, `e.get_app_fn_args` returns `(f, [e₁, ... eₙ])`. See also `expr.get_app_fn_args`. -/ meta def get_app_fn_args : pexpr → opt_param (list pexpr) [] → pexpr × list pexpr | (expr.app e1 e2) r := get_app_fn_args e1 (e2::r) | e1 r := (e1, r) /-- If `e : pexpr` is a sequence of applications `f e₁ e₂ ... eₙ`, `e.get_app_fn` returns `f`. See also `expr.get_app_fn`. -/ meta def get_app_fn : pexpr → list pexpr := prod.snd ∘ get_app_fn_args /-- If `e : pexpr` is a sequence of applications `f e₁ e₂ ... eₙ`, `e.get_app_args` returns `[e₁, ... eₙ]`. See also `expr.get_app_args`. -/ meta def get_app_args : pexpr → list pexpr := prod.snd ∘ get_app_fn_args end pexpr /-! ### Declarations about `expr` -/ namespace expr /-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/ meta def clean_ids : list name := [``id, ``id_rhs, ``id_delta, ``hidden] /-- Clean an expression by removing `id`s listed in `clean_ids`. -/ meta def clean (e : expr) : expr := e.replace (λ e n, match e with | (app (app (const n _) _) e') := if n ∈ clean_ids then some e' else none | (app (lam _ _ _ (var 0)) e') := some e' | _ := none end) /-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/ meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none /-- Implementation of `expr.mreplace`. -/ meta def mreplace_aux {m : Type* → Type*} [monad m] (R : expr → nat → m (option expr)) : expr → ℕ → m expr | (app f x) n := option.mget_or_else (R (app f x) n) (do Rf ← mreplace_aux f n, Rx ← mreplace_aux x n, return $ app Rf Rx) | (lam nm bi ty bd) n := option.mget_or_else (R (lam nm bi ty bd) n) (do Rty ← mreplace_aux ty n, Rbd ← mreplace_aux bd (n+1), return $ lam nm bi Rty Rbd) | (pi nm bi ty bd) n := option.mget_or_else (R (pi nm bi ty bd) n) (do Rty ← mreplace_aux ty n, Rbd ← mreplace_aux bd (n+1), return $ pi nm bi Rty Rbd) | (elet nm ty a b) n := option.mget_or_else (R (elet nm ty a b) n) (do Rty ← mreplace_aux ty n, Ra ← mreplace_aux a n, Rb ← mreplace_aux b n, return $ elet nm Rty Ra Rb) | (macro c es) n := option.mget_or_else (R (macro c es) n) $ macro c <$> es.mmap (λ e, mreplace_aux e n) | e n := option.mget_or_else (R e n) (return e) /-- Monadic analogue of `expr.replace`. The `mreplace R e` visits each subexpression `s` of `e`, and is called with `R s n`, where `n` is the number of binders above `e`. If `R s n` fails, the whole replacement fails. If `R s n` returns `some t`, `s` is replaced with `t` (and `mreplace` does not visit its subexpressions). If `R s n` return `none`, then `mreplace` continues visiting subexpressions of `s`. WARNING: This function performs exponentially worse on large terms than `expr.replace`, if a subexpression occurs more than once in an expression, `expr.replace` visits them only once, but this function will visit every occurence of it. Do not use this on large expressions. -/ meta def mreplace {m : Type* → Type*} [monad m] (R : expr → nat → m (option expr)) (e : expr) : m expr := mreplace_aux R e 0 /-- Match a variable. -/ meta def match_var {elab} : expr elab → option ℕ | (var n) := some n | _ := none /-- Match a sort. -/ meta def match_sort {elab} : expr elab → option level | (sort u) := some u | _ := none /-- Match a constant. -/ meta def match_const {elab} : expr elab → option (name × list level) | (const n lvls) := some (n, lvls) | _ := none /-- Match a metavariable. -/ meta def match_mvar {elab} : expr elab → option (name × name × expr elab) | (mvar unique pretty type) := some (unique, pretty, type) | _ := none /-- Match a local constant. -/ meta def match_local_const {elab} : expr elab → option (name × name × binder_info × expr elab) | (local_const unique pretty bi type) := some (unique, pretty, bi, type) | _ := none /-- Match an application. -/ meta def match_app {elab} : expr elab → option (expr elab × expr elab) | (app t u) := some (t, u) | _ := none /-- Match an application of `coe_fn`. -/ meta def match_app_coe_fn : expr → option (expr × expr × expr × expr × expr) | (app `(@coe_fn %%α %%β %%inst %%fexpr) x) := some (α, β, inst, fexpr, x) | _ := none /-- Match an abstraction. -/ meta def match_lam {elab} : expr elab → option (name × binder_info × expr elab × expr elab) | (lam var_name bi type body) := some (var_name, bi, type, body) | _ := none /-- Match a Π type. -/ meta def match_pi {elab} : expr elab → option (name × binder_info × expr elab × expr elab) | (pi var_name bi type body) := some (var_name, bi, type, body) | _ := none /-- Match a let. -/ meta def match_elet {elab} : expr elab → option (name × expr elab × expr elab × expr elab) | (elet var_name type assignment body) := some (var_name, type, assignment, body) | _ := none /-- Match a macro. -/ meta def match_macro {elab} : expr elab → option (macro_def × list (expr elab)) | (macro df args) := some (df, args) | _ := none /-- Tests whether an expression is a meta-variable. -/ meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- Tests whether an expression is a sort. -/ meta def is_sort : expr → bool | (sort _) := tt | e := ff /-- Get the universe levels of a `const` expression -/ meta def univ_levels : expr → list level | (const n ls) := ls | _ := [] /-- Replace any metavariables in the expression with underscores, in preparation for printing `refine ...` statements. -/ meta def replace_mvars (e : expr) : expr := e.replace (λ e' _, if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none) /-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/ meta def to_implicit_local_const : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e /-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/ meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e /-- Returns a list of all local constants in an expression (without duplicates). -/ meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) /-- Returns the set of all local constants in an expression. -/ meta def list_local_consts' (e : expr) : expr_set := e.fold mk_expr_set (λ e' _ es, if e'.is_local_constant then es.insert e' else es) /-- Returns the unique names of all local constants in an expression. -/ meta def list_local_const_unique_names (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_local_constant then es.insert e'.local_uniq_name else es) /-- Returns a `name_set` of all constants in an expression. -/ meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) /-- Returns a `list name` containing the constant names of an `expr` in the same order that `expr.fold` traverses it. -/ meta def list_constant' (e : expr) : list name := (e.fold [] (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es)).reverse /-- Returns a list of all meta-variables in an expression (without duplicates). -/ meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es) /-- Returns the set of all meta-variables in an expression. -/ meta def list_meta_vars' (e : expr) : expr_set := e.fold mk_expr_set (λ e' _ es, if e'.is_mvar then es.insert e' else es) /-- Returns a list of all universe meta-variables in an expression (without duplicates). -/ meta def list_univ_meta_vars (e : expr) : list name := native.rb_set.to_list $ e.fold native.mk_rb_set $ λ e' i s, match e' with | (sort u) := u.fold_mvar (flip native.rb_set.insert) s | (const _ ls) := ls.foldl (λ s' l, l.fold_mvar (flip native.rb_set.insert) s') s | _ := s end /-- Test `t` contains the specified subexpression `e`, or a metavariable. This represents the notion that `e` "may occur" in `t`, possibly after subsequent unification. -/ meta def contains_expr_or_mvar (t : expr) (e : expr) : bool := -- We can't use `t.has_meta_var` here, as that detects universe metavariables, too. ¬ t.list_meta_vars.empty ∨ e.occurs t /-- Returns a `name_set` of all constants in an expression starting with a certain prefix. -/ meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end /-- Returns true if `e` contains a name `n` where `p n` is true. Returns `true` if `p name.anonymous` is true. -/ meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool := e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b) /-- Returns true if `e` contains a `sorry`. See also `name.contains_sorry`. -/ meta def contains_sorry (e : expr) : bool := e.fold ff (λ e' _ b, if (is_sorry e').is_some then tt else b) /-- `app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`. -/ meta def app_symbol_in (e : expr) (l : list name) : bool := match e.get_app_fn with | (expr.const n _) := n ∈ l | _ := ff end /-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/ meta def get_simp_args (e : expr) : tactic (list expr) := -- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app if ¬ e.is_app then pure [] else do cgr ← mk_specialized_congr_lemma_simp e, pure $ do (arg_kind, arg) ← cgr.arg_kinds.zip e.get_app_args, guard $ arg_kind = congr_arg_kind.eq, pure arg /-- Simplifies the expression `t` with the specified options. The result is `(new_e, pr)` with the new expression `new_e` and a proof `pr : e = new_e`. -/ meta def simp (t : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic (expr × expr × name_set) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger /-- Definitionally simplifies the expression `t` with the specified options. The result is the simplified expression. -/ meta def dsimp (t : expr) (cfg : dsimp_config := {}) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg /-- Get the names of the bound variables by a sequence of pis or lambdas. -/ meta def binding_names : expr → list name | (pi n _ _ e) := n :: e.binding_names | (lam n _ _ e) := n :: e.binding_names | e := [] /-- head-reduce a single let expression -/ meta def reduce_let : expr → expr | (elet _ _ v b) := b.instantiate_var v | e := e /-- head-reduce all let expressions -/ meta def reduce_lets : expr → expr | (elet _ _ v b) := reduce_lets $ b.instantiate_var v | e := e /-- Instantiate lambdas in the second argument by expressions from the first. -/ meta def instantiate_lambdas : list expr → expr → expr | (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e') | _ e := e /-- Repeatedly apply `expr.subst`. -/ meta def substs : expr → list expr → expr | e es := es.foldl expr.subst e /-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`. If the length of `es` is larger than the number of lambdas in `e`, then the term is applied to the remaining terms. Also reduces head let-expressions in `e`, including those after instantiating all lambdas. This is very similar to `expr.substs`, but this also reduces head let-expressions. -/ meta def instantiate_lambdas_or_apps : list expr → expr → expr | (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es e := mk_app e es /-- Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ library_note "open expressions" /-- Get the codomain/target of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def pi_codomain : expr → expr | (pi n bi d b) := pi_codomain b | e := e /-- Get the body/value of a lambda-expression. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def lambda_body : expr → expr | (lam n bi d b) := lambda_body b | e := e /-- Auxiliary defintion for `pi_binders`. See note [open expressions]. -/ meta def pi_binders_aux : list binder → expr → list binder × expr | es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b | es e := (es, e) /-- Get the binders and codomain of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the free variables. See note [open expressions]. -/ meta def pi_binders (e : expr) : list binder × expr := let (es, e) := pi_binders_aux [] e in (es.reverse, e) /-- Auxiliary defintion for `get_app_fn_args`. -/ meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) /-- A combination of `get_app_fn` and `get_app_args`: lists both the function and its arguments of an application -/ meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] /-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/ meta def drop_pis : list expr → expr → tactic expr | (v :: vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed /-- `instantiate_pis es e` instantiates the pis in `e` with the expressions from `es`. Does not check whether the result remains type-correct. -/ meta def instantiate_pis : list expr → expr → expr | (v :: vs) (pi n bi d b) := instantiate_pis vs (b.instantiate_var v) | _ e := e /-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`. Returns `empty` if the list is empty. -/ meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es /-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/ meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) /-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/ meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) /-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant. Otherwise returns `binder_info.default`. -/ meta def local_binding_info : expr → binder_info | (expr.local_const _ _ bi _) := bi | _ := binder_info.default /-- `is_default_local e` tests whether `e` is a local constant with binder info `binder_info.default` -/ meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff /-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/ meta def has_local_constant (e l : expr) : bool := e.has_local_in $ mk_name_set.insert l.local_uniq_name /-- Turns a local constant into a binder -/ meta def to_binder : expr → binder | (local_const _ nm bi t) := ⟨nm, bi, t⟩ | _ := default /-- Strip-away the context-dependent unique id for the given local const and return: its friendly `name`, its `binder_info`, and its `type : expr`. -/ meta def get_local_const_kind : expr → name × binder_info × expr | (expr.local_const _ n bi e) := (n, bi, e) | _ := (name.anonymous, binder_info.default, expr.const name.anonymous []) /-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/ meta def local_const_set_type {elab : bool} : expr elab → expr elab → expr elab | (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t | e new_t := e /-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to access core `expr` manipulation functions for `pexpr`-based use, but which are restricted to `expr tt` at the site of definition unnecessarily. DANGER: Unless you know exactly what you are doing, this is probably not the function you are looking for. For `pexpr → expr` see `tactic.to_expr`. For `expr → pexpr` see `to_pexpr`. -/ meta def unsafe_cast {elab₁ elab₂ : bool} : expr elab₁ → expr elab₂ := unchecked_cast /-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr × expr)` as a collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says "whenever `f` is encountered in `e` verbatim, replace it with `t`". -/ meta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr × expr)) : expr elab := unsafe_cast $ e.unsafe_cast.replace $ λ e n, (mappings.filter $ λ ent : expr × expr, ent.1 = e).head'.map prod.snd /-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of other `expr.local_const`s. It determines whether `e` should be considered "available in context" as a variable by virtue of the fact that the variables `vs` have been deemed such. 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. DANGER: It is possible that for `f : expr` another `expr.local_const`, we have `is_implicitly_included_variable f vs = ff` but `is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to iteratively add a list of local constants (usually, the `variables` declared in the local scope) which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables were added in a particular iteration. The function `all_implicitly_included_variables` below implements this behaviour. Note that if `e ∈ vs` then `is_implicitly_included_variable e vs = tt`. -/ meta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool := if ¬(e.local_pp_name.to_string.starts_with "_") then e ∈ vs else e.local_type.fold tt $ λ se _ b, if ¬b then ff else if ¬se.is_local_constant then tt else se ∈ vs /-- Private work function for `all_implicitly_included_variables`, performing the actual series of iterations, tracking with a boolean whether any updates occured this iteration. -/ private meta def all_implicitly_included_variables_aux : list expr → list expr → list expr → bool → list expr | [] vs rs tt := all_implicitly_included_variables_aux rs vs [] ff | [] vs rs ff := vs | (e :: rest) vs rs b := let (vs, rs, b) := if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in all_implicitly_included_variables_aux rest vs rs b /-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`, another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion of the variables in `vs` into the local context implies that `e` should also be included. See `is_implicitly_included_variable e vs` for the details. In particular, those elements of `vs` are included automatically. -/ meta def all_implicitly_included_variables (es vs : list expr) : list expr := all_implicitly_included_variables_aux es vs [] ff /-- Get the list of explicit arguments of a function. -/ meta def list_explicit_args (f : expr) : tactic (list expr) := tactic.fold_explicit_args f [] (λ ll e, return $ ll ++ [e]) /-- `replace_explicit_args f parg` assumes that `f` is an expression corresponding to a function application. It replaces the explicit arguments of `f`, in succession, by the elements of `parg`. The implicit arguments of `f` remain unchanged. -/ meta def replace_explicit_args (f : expr) (parg : list expr) : tactic expr := do finf ← (get_fun_info f.get_app_fn), let is_ex_arg : list bool := finf.params.map (λ e, ¬ e.is_implicit ∧ ¬ e.is_inst_implicit), let nargs := list.replace_if f.get_app_args is_ex_arg parg, return $ expr.mk_app f.get_app_fn nargs /-- Infer the type of an application of the form `f x1 x2 ... xn`, where `f` is an identifier. This also works if `x1, ... xn` contain free variables. -/ protected meta def simple_infer_type (env : environment) (e : expr) : exceptional expr := do (@const tt n ls, es) ← return e.get_app_fn_args | exceptional.fail "expression is not a constant applied to arguments", d ← env.get n, return $ (d.type.instantiate_pis es).instantiate_univ_params $ d.univ_params.zip ls /-- Auxilliary function for `head_eta_expand`. -/ meta def head_eta_expand_aux : ℕ → expr → expr → expr | (n+1) e (pi x bi d b) := lam x bi d $ head_eta_expand_aux n e b | _ e _ := e /-- `head_eta_expand n e t` eta-expands `e` `n` times, with the binders info and domains obtained by its type `t`. -/ meta def head_eta_expand (n : ℕ) (e t : expr) : expr := ((e.lift_vars 0 n).mk_app $ (list.range n).reverse.map var).head_eta_expand_aux n t /-- `e.eta_expand env dict` eta-expands all expressions that have as head a constant `n` in `dict`. They are expanded until they are applied to one more argument than the maximum in `dict.find n`. -/ protected meta def eta_expand (env : environment) (dict : name_map $ list ℕ) : expr → expr | e := e.replace $ λ e _, do let (e0, es) := e.get_app_fn_args, let ns := (dict.find e0.const_name).iget, guard (bnot ns.empty), let e' := e0.mk_app $ es.map eta_expand, let needed_n := ns.foldr max 0 + 1, if needed_n ≤ es.length then some e' else do e'_type ← (e'.simple_infer_type env).to_option, some $ head_eta_expand (needed_n - es.length) e' e'_type /-- `e.apply_replacement_fun f test` applies `f` to each identifier (inductive type, defined function etc) in an expression, unless * The identifier occurs in an application with first argument `arg`; and * `test arg` is false. However, if `f` is in the dictionary `relevant`, then the argument `relevant.find f` is tested, instead of the first argument. Reorder contains the information about what arguments to reorder: e.g. `g x₁ x₂ x₃ ... xₙ` becomes `g x₂ x₁ x₃ ... xₙ` if `reorder.find g = some [1]`. We assume that all functions where we want to reorder arguments are fully applied. This can be done by applying `expr.eta_expand` first. -/ protected meta def apply_replacement_fun (f : name → name) (test : expr → bool) (relevant : name_map ℕ) (reorder : name_map $ list ℕ) : expr → expr | e := e.replace $ λ e _, match e with | const n ls := some $ const (f n) $ -- if the first two arguments are reordered, we also reorder the first two universe parameters if 1 ∈ (reorder.find n).iget then ls.inth 1::ls.head::ls.drop 2 else ls | app g x := let f := g.get_app_fn, nm := f.const_name, n_args := g.get_app_num_args in -- this might be inefficient if n_args ∈ (reorder.find nm).iget ∧ test g.get_app_args.head then -- interchange `x` and the last argument of `g` some $ apply_replacement_fun g.app_fn (apply_replacement_fun x) $ apply_replacement_fun g.app_arg else if n_args = (relevant.find nm).lhoare 0 ∧ f.is_constant ∧ ¬ test x then some $ (f.mk_app $ g.get_app_args.map apply_replacement_fun) (apply_replacement_fun x) else none | _ := none end end expr /-! ### Declarations about `environment` -/ namespace environment /-- Tests whether `n` is a structure. -/ meta def is_structure (env : environment) (n : name) : bool := (env.structure_fields n).is_some /-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a structure. -/ meta def structure_fields_full (env : environment) (n : name) : option (list name) := (env.structure_fields n).map (list.map $ λ n', n ++ n') /-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type. Note that `is_ginductive` returns `tt` even on regular inductive types. This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive type. -/ meta def is_ginductive' (e : environment) (nm : name) : bool := e.is_ginductive nm ∧ ¬ e.is_inductive nm /-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/ meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α := e.fold [] $ λ d l, match f d with | some r := r :: l | none := l end /-- Maps `f` to all declarations in the environment. -/ meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α := e.decl_filter_map $ λ d, some (f d) /-- Lists all declarations in the environment -/ meta def get_decls (e : environment) : list declaration := e.decl_map id /-- Lists all trusted (non-meta) declarations in the environment -/ meta def get_trusted_decls (e : environment) : list declaration := e.decl_filter_map (λ d, if d.is_trusted then some d else none) /-- Lists the name of all declarations in the environment -/ meta def get_decl_names (e : environment) : list name := e.decl_map declaration.to_name /-- Fold a monad over all declarations in the environment. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α) (fn : declaration → α → m α) : m α := e.fold (return x) (λ d t, t >>= fn d) /-- Filters all declarations in the environment. -/ meta def filter (e : environment) (test : declaration → bool) : list declaration := e.fold [] $ λ d ds, if test d then d::ds else ds /-- Filters all declarations in the environment. -/ meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) := e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds /-- Checks whether `s` is a prefix of the file where `n` is declared. This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/ meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool := s.is_prefix_of $ (e.decl_olean n).get_or_else "" end environment /-! ### `is_eta_expansion` In this section we define the tactic `is_eta_expansion` which checks whether an expression is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`). -/ namespace expr /-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have `pr = nm.{univs} args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) : bool := l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args /-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_test : list (name × expr) → option expr | [] := none | (⟨proj, val⟩::l) := match val.get_app_fn with | (const nm univs : expr) := if nm = proj then let args := val.get_app_args in let e := args.ilast in if is_eta_expansion_of args univs l then some e else none else none | _ := none end /-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`. Here `l` is intended to consists of the projections and the fields of `val`. This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and afterward checks whether the resulting expression `e` unifies with `val`. This last check is necessary, because `val` and `e` might have different types. -/ meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) := do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val), match is_eta_expansion_test l' with | some e := option.map (λ _, e) <$> try_core (unify e val) | none := return none end /-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the eta-expansion of `e`. With eta-expansion we here mean the eta-expansion of a structure, not of a function. For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`. This assumes that `val` is a fully-applied application of the constructor of a structure. This is useful to reduce expressions generated by the notation `{ field_1 := _, ..other_structure }` If `other_structure` is itself a field of the structure, then the elaborator will insert an eta-expanded version of `other_structure`. -/ meta def is_eta_expansion (val : expr) : tactic (option expr) := do e ← get_env, type ← infer_type val, projs ← e.structure_fields_full type.get_app_fn.const_name, let args := (val.get_app_args).drop type.get_app_args.length, is_eta_expansion_aux val (projs.zip args) end expr /-! ### Declarations about `declaration` -/ namespace declaration /-- `declaration.update_with_fun f test tgt decl` sets the name of the given `decl : declaration` to `tgt`, and applies both `expr.eta_expand` and `expr.apply_replacement_fun` to the value and type of `decl`. -/ protected meta def update_with_fun (env : environment) (f : name → name) (test : expr → bool) (relevant : name_map ℕ) (reorder : name_map $ list ℕ) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ (decl.type.eta_expand env reorder).apply_replacement_fun f test relevant reorder in decl.update_value $ (decl.value.eta_expand env reorder).apply_replacement_fun f test relevant reorder /-- Checks whether the declaration is declared in the current file. This is a simple wrapper around `environment.in_current_file` Use `environment.in_current_file` instead if performance matters. -/ meta def in_current_file (d : declaration) : tactic bool := do e ← get_env, return $ e.in_current_file d.to_name /-- Checks whether a declaration is a theorem -/ meta def is_theorem : declaration → bool | (thm _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a constant -/ meta def is_constant : declaration → bool | (cnst _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a axiom -/ meta def is_axiom : declaration → bool | (ax _ _ _) := tt | _ := ff /-- Checks whether a declaration is automatically generated in the environment. There is no cheap way to check whether a declaration in the namespace of a generalized inductive type is automatically generated, so for now we say that all of them are automatically generated. -/ meta def is_auto_generated (e : environment) (d : declaration) : bool := e.is_constructor d.to_name ∨ (e.is_projection d.to_name).is_some ∨ (e.is_constructor d.to_name.get_prefix ∧ d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨ (e.is_inductive d.to_name.get_prefix ∧ d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec", "rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨ d.to_name.has_prefix (λ nm, e.is_ginductive' nm) /-- Returns true iff `d` is an automatically-generated or internal declaration. -/ meta def is_auto_or_internal (env : environment) (d : declaration) : bool := d.to_name.is_internal || d.is_auto_generated env /-- Returns the list of universe levels of a declaration. -/ meta def univ_levels (d : declaration) : list level := d.univ_params.map level.param /-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/ protected meta def reducibility_hints : declaration → reducibility_hints | (declaration.defn _ _ _ _ red _) := red | _ := _root_.reducibility_hints.opaque /-- formats the arguments of a `declaration.thm` -/ private meta def print_thm (nm : name) (tp : expr) (body : task expr) : tactic format := do tp ← pp tp, body ← pp body.get, return $ "<theorem " ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">" /-- formats the arguments of a `declaration.defn` -/ private meta def print_defn (nm : name) (tp : expr) (body : expr) (is_trusted : bool) : tactic format := do tp ← pp tp, body ← pp body, return $ "<" ++ (if is_trusted then "def " else "meta def ") ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">" /-- formats the arguments of a `declaration.cnst` -/ private meta def print_cnst (nm : name) (tp : expr) (is_trusted : bool) : tactic format := do tp ← pp tp, return $ "<" ++ (if is_trusted then "constant " else "meta constant ") ++ to_fmt nm ++ " : " ++ tp ++ ">" /-- formats the arguments of a `declaration.ax` -/ private meta def print_ax (nm : name) (tp : expr) : tactic format := do tp ← pp tp, return $ "<axiom " ++ to_fmt nm ++ " : " ++ tp ++ ">" /-- pretty-prints a `declaration` object. -/ meta def to_tactic_format : declaration → tactic format | (declaration.thm nm _ tp bd) := print_thm nm tp bd | (declaration.defn nm _ tp bd _ is_trusted) := print_defn nm tp bd is_trusted | (declaration.cnst nm _ tp is_trusted) := print_cnst nm tp is_trusted | (declaration.ax nm _ tp) := print_ax nm tp meta instance : has_to_tactic_format declaration := ⟨to_tactic_format⟩ end declaration meta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) := unchecked_cast expr.has_decidable_eq section local attribute [semireducible] reflected meta instance {α} [has_reflect α] : has_reflect (thunk α) | a := expr.lam `x binder_info.default (reflect unit) (reflect $ a ()) end
01e7d4b86036b78f5a4e3a70491c2d803d3e8cf4
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch4/ex0412.lean
3e2a78ca539b1ac3f5d1f35d34ef913a8e69db2d
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
2,309
lean
open classical variables (α : Type) (p q : α → Prop) variable a : α variable r : Prop example : (∃ x : α, r) → r := λ ⟨w, hr⟩, hr example : r → (∃ x : α, r) := λ hr, ⟨a, hr⟩ example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r := ⟨λ ⟨w, hpw, hr⟩, ⟨⟨w, hpw⟩, hr⟩, λ ⟨⟨w, hpw⟩, hr⟩, ⟨w, hpw, hr⟩⟩ example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := ⟨λ ⟨w, hpqw⟩, hpqw.elim (λ hpw, or.inl ⟨w, hpw⟩) (λ hqw, or.inr ⟨w, hqw⟩), λ h, h.elim (λ ⟨w, hpw⟩, ⟨w, or.inl hpw⟩) (λ ⟨w, hqw⟩, ⟨w, or.inr hqw⟩)⟩ example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) := ⟨λ h ⟨w, hnpw⟩, hnpw (h w), λ hnen x, by_contradiction (λ hnpx, hnen ⟨x, hnpx⟩)⟩ example : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) := ⟨λ ⟨w, hpw⟩ h, absurd hpw (h w), λ hnun, by_contradiction (λ hne, hnun (λ x hpx, hne ⟨x, hpx⟩))⟩ example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := ⟨λ h x hpx, h ⟨x, hpx⟩, λ h ⟨w, hpw⟩, h w hpw⟩ example : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := ⟨λ hnu, by_contradiction (assume hnen : ¬ (∃ x, ¬ p x), suffices hu : ∀ x, p x, from hnu hu, assume x, by_contradiction (λ hnpx, hnen ⟨x, hnpx⟩)), λ ⟨w, hnpw⟩ hu, hnpw (hu w)⟩ example : (∀ x, p x → r) ↔ (∃ x, p x) → r := ⟨λ h ⟨w, hpw⟩, h w hpw, λ h x hpx, h ⟨x, hpx⟩⟩ example : (∃ x, p x → r) ↔ (∀ x, p x) → r := ⟨λ ⟨w, hpw2r⟩ h, hpw2r (h w), λ h, by_cases (assume hu : ∀ x, p x, ⟨a, λ hpa, h hu⟩) (assume hnu : ¬ ∀ x, p x, by_contradiction (assume hne : ¬ ∃ x, p x → r, have hu : ∀ x, p x, from assume x, by_contradiction (assume hnpx : ¬ p x, hne ⟨x, λ hpx, (hnpx hpx).elim⟩), hnu hu))⟩ example : (∃ x, r → p x) ↔ (r → ∃ x, p x) := ⟨λ ⟨w, hr2pw⟩ r, ⟨w, hr2pw r⟩, λ h, by_cases (assume hr : r, match h hr with ⟨w, hpw⟩ := ⟨w, λ hr, hpw⟩ end) (assume hnr : ¬r, ⟨a, λ hr, absurd hr hnr⟩)⟩
9be186fdee4d138b3861f61dcd12756848c31fc0
df561f413cfe0a88b1056655515399c546ff32a5
/3-function-world/l1.lean
6341f2c21b32cf662970052a7da74c172af198f8
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
71
lean
example (P Q : Type) (p : P) (h : P → Q) : Q := begin exact h(p), end
a31ddc07d47e873769bb054cad5c6fcbdd19478e
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/algebra/group_with_zero/basic.lean
912b745e40b69b499d84a41a87a4809c8d85c0cc
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
38,590
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import logic.nontrivial import algebra.group.units_hom import algebra.group.inj_surj import algebra.group_with_zero.defs /-! # Groups with an adjoined zero element This file describes structures that are not usually studied on their own right in mathematics, namely a special sort of monoid: apart from a distinguished “zero element” they form a group, or in other words, they are groups with an adjoined zero element. Examples are: * division rings; * the value monoid of a multiplicative valuation; * in particular, the non-negative real numbers. ## Main definitions Various lemmas about `group_with_zero` and `comm_group_with_zero`. To reduce import dependencies, the type-classes themselves are in `algebra.group_with_zero.defs`. ## Implementation details As is usual in mathlib, we extend the inverse function to the zero element, and require `0⁻¹ = 0`. -/ set_option old_structure_cmd true open_locale classical open function variables {M₀ G₀ M₀' G₀' : Type*} mk_simp_attribute field_simps "The simpset `field_simps` is used by the tactic `field_simp` to reduce an expression in a field to an expression of the form `n / d` where `n` and `d` are division-free." attribute [field_simps] mul_div_assoc' section section mul_zero_class variables [mul_zero_class M₀] {a b : M₀} /-- Pullback a `mul_zero_class` instance along an injective function. -/ protected def function.injective.mul_zero_class [has_mul M₀'] [has_zero M₀'] (f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (mul : ∀ a b, f (a * b) = f a * f b) : mul_zero_class M₀' := { mul := (*), zero := 0, zero_mul := λ a, hf $ by simp only [mul, zero, zero_mul], mul_zero := λ a, hf $ by simp only [mul, zero, mul_zero] } /-- Pushforward a `mul_zero_class` instance along an surjective function. -/ protected def function.surjective.mul_zero_class [has_mul M₀'] [has_zero M₀'] (f : M₀ → M₀') (hf : surjective f) (zero : f 0 = 0) (mul : ∀ a b, f (a * b) = f a * f b) : mul_zero_class M₀' := { mul := (*), zero := 0, mul_zero := hf.forall.2 $ λ x, by simp only [← zero, ← mul, mul_zero], zero_mul := hf.forall.2 $ λ x, by simp only [← zero, ← mul, zero_mul] } lemma mul_eq_zero_of_left (h : a = 0) (b : M₀) : a * b = 0 := h.symm ▸ zero_mul b lemma mul_eq_zero_of_right (a : M₀) (h : b = 0) : a * b = 0 := h.symm ▸ mul_zero a lemma left_ne_zero_of_mul : a * b ≠ 0 → a ≠ 0 := mt (λ h, mul_eq_zero_of_left h b) lemma right_ne_zero_of_mul : a * b ≠ 0 → b ≠ 0 := mt (mul_eq_zero_of_right a) lemma ne_zero_and_ne_zero_of_mul (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := ⟨left_ne_zero_of_mul h, right_ne_zero_of_mul h⟩ lemma mul_eq_zero_of_ne_zero_imp_eq_zero {a b : M₀} (h : a ≠ 0 → b = 0) : a * b = 0 := if ha : a = 0 then by rw [ha, zero_mul] else by rw [h ha, mul_zero] end mul_zero_class /-- Pushforward a `no_zero_divisors` instance along an injective function. -/ protected lemma function.injective.no_zero_divisors [has_mul M₀] [has_zero M₀] [has_mul M₀'] [has_zero M₀'] [no_zero_divisors M₀'] (f : M₀ → M₀') (hf : injective f) (zero : f 0 = 0) (mul : ∀ x y, f (x * y) = f x * f y) : no_zero_divisors M₀ := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y H, have f x * f y = 0, by rw [← mul, H, zero], (eq_zero_or_eq_zero_of_mul_eq_zero this).imp (λ H, hf $ by rwa zero) (λ H, hf $ by rwa zero) } lemma eq_zero_of_mul_self_eq_zero [has_mul M₀] [has_zero M₀] [no_zero_divisors M₀] {a : M₀} (h : a * a = 0) : a = 0 := (eq_zero_or_eq_zero_of_mul_eq_zero h).elim id id section variables [mul_zero_class M₀] [no_zero_divisors M₀] {a b : M₀} /-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them equals zero. -/ @[simp] theorem mul_eq_zero : a * b = 0 ↔ a = 0 ∨ b = 0 := ⟨eq_zero_or_eq_zero_of_mul_eq_zero, λo, o.elim (λ h, mul_eq_zero_of_left h b) (mul_eq_zero_of_right a)⟩ /-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them equals zero. -/ @[simp] theorem zero_eq_mul : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, mul_eq_zero] /-- If `α` has no zero divisors, then the product of two elements is nonzero iff both of them are nonzero. -/ theorem mul_ne_zero_iff : a * b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 := (not_congr mul_eq_zero).trans not_or_distrib @[field_simps] theorem mul_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 := mul_ne_zero_iff.2 ⟨ha, hb⟩ /-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` equals zero iff so is `b * a`. -/ theorem mul_eq_zero_comm : a * b = 0 ↔ b * a = 0 := mul_eq_zero.trans $ (or_comm _ _).trans mul_eq_zero.symm /-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` is nonzero iff so is `b * a`. -/ theorem mul_ne_zero_comm : a * b ≠ 0 ↔ b * a ≠ 0 := not_congr mul_eq_zero_comm lemma mul_self_eq_zero : a * a = 0 ↔ a = 0 := by simp lemma zero_eq_mul_self : 0 = a * a ↔ a = 0 := by simp end end section variables [monoid_with_zero M₀] [nontrivial M₀] {a b : M₀} /-- In a nontrivial monoid with zero, zero and one are different. -/ @[simp] lemma zero_ne_one : 0 ≠ (1:M₀) := begin assume h, rcases exists_pair_ne M₀ with ⟨x, y, hx⟩, apply hx, calc x = 1 * x : by rw [one_mul] ... = 0 : by rw [← h, zero_mul] ... = 1 * y : by rw [← h, zero_mul] ... = y : by rw [one_mul] end @[simp] lemma one_ne_zero : (1:M₀) ≠ 0 := zero_ne_one.symm lemma ne_zero_of_eq_one {a : M₀} (h : a = 1) : a ≠ 0 := calc a = 1 : h ... ≠ 0 : one_ne_zero lemma left_ne_zero_of_mul_eq_one (h : a * b = 1) : a ≠ 0 := left_ne_zero_of_mul $ ne_zero_of_eq_one h lemma right_ne_zero_of_mul_eq_one (h : a * b = 1) : b ≠ 0 := right_ne_zero_of_mul $ ne_zero_of_eq_one h /-- Pullback a `nontrivial` instance along a function sending `0` to `0` and `1` to `1`. -/ protected lemma pullback_nonzero [has_zero M₀'] [has_one M₀'] (f : M₀' → M₀) (zero : f 0 = 0) (one : f 1 = 1) : nontrivial M₀' := ⟨⟨0, 1, mt (congr_arg f) $ by { rw [zero, one], exact zero_ne_one }⟩⟩ end section monoid_with_zero /-- Pullback a `monoid_with_zero` class along an injective function. -/ protected def function.injective.monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀'] [monoid_with_zero M₀] (f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : monoid_with_zero M₀' := { .. hf.monoid f one mul, .. hf.mul_zero_class f zero mul } /-- Pushforward a `monoid_with_zero` class along a surjective function. -/ protected def function.surjective.monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀'] [monoid_with_zero M₀] (f : M₀ → M₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : monoid_with_zero M₀' := { .. hf.monoid f one mul, .. hf.mul_zero_class f zero mul } /-- Pullback a `monoid_with_zero` class along an injective function. -/ protected def function.injective.comm_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀'] [comm_monoid_with_zero M₀] (f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : comm_monoid_with_zero M₀' := { .. hf.comm_monoid f one mul, .. hf.mul_zero_class f zero mul } /-- Pushforward a `monoid_with_zero` class along a surjective function. -/ protected def function.surjective.comm_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀'] [comm_monoid_with_zero M₀] (f : M₀ → M₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : comm_monoid_with_zero M₀' := { .. hf.comm_monoid f one mul, .. hf.mul_zero_class f zero mul } variables [monoid_with_zero M₀] namespace units /-- An element of the unit group of a nonzero monoid with zero represented as an element of the monoid is nonzero. -/ @[simp] lemma ne_zero [nontrivial M₀] (u : units M₀) : (u : M₀) ≠ 0 := left_ne_zero_of_mul_eq_one u.mul_inv -- We can't use `mul_eq_zero` + `units.ne_zero` in the next two lemmas because we don't assume -- `nonzero M₀`. @[simp] lemma mul_left_eq_zero (u : units M₀) {a : M₀} : a * u = 0 ↔ a = 0 := ⟨λ h, by simpa using mul_eq_zero_of_left h ↑u⁻¹, λ h, mul_eq_zero_of_left h u⟩ @[simp] lemma mul_right_eq_zero (u : units M₀) {a : M₀} : ↑u * a = 0 ↔ a = 0 := ⟨λ h, by simpa using mul_eq_zero_of_right ↑u⁻¹ h, mul_eq_zero_of_right u⟩ end units namespace is_unit lemma ne_zero [nontrivial M₀] {a : M₀} (ha : is_unit a) : a ≠ 0 := let ⟨u, hu⟩ := ha in hu ▸ u.ne_zero lemma mul_right_eq_zero {a b : M₀} (ha : is_unit a) : a * b = 0 ↔ b = 0 := let ⟨u, hu⟩ := ha in hu ▸ u.mul_right_eq_zero lemma mul_left_eq_zero {a b : M₀} (hb : is_unit b) : a * b = 0 ↔ a = 0 := let ⟨u, hu⟩ := hb in hu ▸ u.mul_left_eq_zero end is_unit /-- In a monoid with zero, if zero equals one, then zero is the only element. -/ lemma eq_zero_of_zero_eq_one (h : (0 : M₀) = 1) (a : M₀) : a = 0 := by rw [← mul_one a, ← h, mul_zero] /-- In a monoid with zero, if zero equals one, then zero is the unique element. Somewhat arbitrarily, we define the default element to be `0`. All other elements will be provably equal to it, but not necessarily definitionally equal. -/ def unique_of_zero_eq_one (h : (0 : M₀) = 1) : unique M₀ := { default := 0, uniq := eq_zero_of_zero_eq_one h } /-- In a monoid with zero, zero equals one if and only if all elements of that semiring are equal. -/ theorem subsingleton_iff_zero_eq_one : (0 : M₀) = 1 ↔ subsingleton M₀ := ⟨λ h, @unique.subsingleton _ (unique_of_zero_eq_one h), λ h, @subsingleton.elim _ h _ _⟩ alias subsingleton_iff_zero_eq_one ↔ subsingleton_of_zero_eq_one _ lemma eq_of_zero_eq_one (h : (0 : M₀) = 1) (a b : M₀) : a = b := @subsingleton.elim _ (subsingleton_of_zero_eq_one h) a b @[simp] theorem is_unit_zero_iff : is_unit (0 : M₀) ↔ (0:M₀) = 1 := ⟨λ ⟨⟨_, a, (a0 : 0 * a = 1), _⟩, rfl⟩, by rwa zero_mul at a0, λ h, @is_unit_of_subsingleton _ _ (subsingleton_of_zero_eq_one h) 0⟩ @[simp] theorem not_is_unit_zero [nontrivial M₀] : ¬ is_unit (0 : M₀) := mt is_unit_zero_iff.1 zero_ne_one variable (M₀) /-- In a monoid with zero, either zero and one are nonequal, or zero is the only element. -/ lemma zero_ne_one_or_forall_eq_0 : (0 : M₀) ≠ 1 ∨ (∀a:M₀, a = 0) := not_or_of_imp eq_zero_of_zero_eq_one end monoid_with_zero section cancel_monoid_with_zero variables [cancel_monoid_with_zero M₀] {a b c : M₀} @[priority 10] -- see Note [lower instance priority] instance comm_cancel_monoid_with_zero.no_zero_divisors : no_zero_divisors M₀ := ⟨λ a b ab0, by { by_cases a = 0, { left, exact h }, right, apply cancel_monoid_with_zero.mul_left_cancel_of_ne_zero h, rw [ab0, mul_zero], }⟩ lemma mul_left_inj' (hc : c ≠ 0) : a * c = b * c ↔ a = b := ⟨mul_right_cancel' hc, λ h, h ▸ rfl⟩ lemma mul_right_inj' (ha : a ≠ 0) : a * b = a * c ↔ b = c := ⟨mul_left_cancel' ha, λ h, h ▸ rfl⟩ @[simp] lemma mul_eq_mul_right_iff : a * c = b * c ↔ a = b ∨ c = 0 := by by_cases hc : c = 0; [simp [hc], simp [mul_left_inj', hc]] @[simp] lemma mul_eq_mul_left_iff : a * b = a * c ↔ b = c ∨ a = 0 := by by_cases ha : a = 0; [simp [ha], simp [mul_right_inj', ha]] /-- Pullback a `monoid_with_zero` class along an injective function. -/ protected def function.injective.cancel_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀'] (f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : cancel_monoid_with_zero M₀' := { mul_left_cancel_of_ne_zero := λ x y z hx H, hf $ mul_left_cancel' ((hf.ne_iff' zero).2 hx) $ by erw [← mul, ← mul, H]; refl, mul_right_cancel_of_ne_zero := λ x y z hx H, hf $ mul_right_cancel' ((hf.ne_iff' zero).2 hx) $ by erw [← mul, ← mul, H]; refl, .. hf.monoid f one mul, .. hf.mul_zero_class f zero mul } /-- An element of a `cancel_monoid_with_zero` fixed by right multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_right (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := classical.by_contradiction $ λ ha, h₁ $ mul_left_cancel' ha $ h₂.symm ▸ (mul_one a).symm /-- An element of a `cancel_monoid_with_zero` fixed by left multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_left (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := classical.by_contradiction $ λ ha, h₁ $ mul_right_cancel' ha $ h₂.symm ▸ (one_mul a).symm end cancel_monoid_with_zero section group_with_zero variables [group_with_zero G₀] alias div_eq_mul_inv ← division_def /-- Pullback a `group_with_zero` class along an injective function. -/ protected def function.injective.group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀'] [has_inv G₀'] (f : G₀' → G₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) : group_with_zero G₀' := { inv := has_inv.inv, inv_zero := hf $ by erw [inv, zero, inv_zero], mul_inv_cancel := λ x hx, hf $ by erw [one, mul, inv, mul_inv_cancel ((hf.ne_iff' zero).2 hx)], .. hf.monoid_with_zero f zero one mul, .. pullback_nonzero f zero one } /-- Pullback a `group_with_zero` class along an injective function. This is a version of `function.injective.group_with_zero` that uses a specified `/` instead of the default `a / b = a * b⁻¹`. -/ protected def function.injective.group_with_zero_div [has_zero G₀'] [has_mul G₀'] [has_one G₀'] [has_inv G₀'] [has_div G₀'] (f : G₀' → G₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : group_with_zero G₀' := { .. hf.monoid_with_zero f zero one mul, .. hf.div_inv_monoid f one mul inv div, .. pullback_nonzero f zero one, .. hf.group_with_zero f zero one mul inv } /-- Pushforward a `group_with_zero` class along an surjective function. -/ protected def function.surjective.group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀'] [has_inv G₀'] (h01 : (0:G₀') ≠ 1) (f : G₀ → G₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) : group_with_zero G₀' := { inv := has_inv.inv, inv_zero := by erw [← zero, ← inv, inv_zero], mul_inv_cancel := hf.forall.2 $ λ x hx, by erw [← inv, ← mul, mul_inv_cancel (mt (congr_arg f) $ trans_rel_left ne hx zero.symm)]; exact one, exists_pair_ne := ⟨0, 1, h01⟩, .. hf.monoid_with_zero f zero one mul } /-- Pushforward a `group_with_zero` class along a surjective function. This is a version of `function.surjective.group_with_zero` that uses a specified `/` instead of the default `a / b = a * b⁻¹`. -/ protected def function.surjective.group_with_zero_div [has_zero G₀'] [has_mul G₀'] [has_one G₀'] [has_inv G₀'] [has_div G₀'] (h01 : (0:G₀') ≠ 1) (f : G₀ → G₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : group_with_zero G₀' := { .. hf.div_inv_monoid f one mul inv div, .. hf.group_with_zero h01 f zero one mul inv } @[simp] lemma mul_inv_cancel_right' {b : G₀} (h : b ≠ 0) (a : G₀) : (a * b) * b⁻¹ = a := calc (a * b) * b⁻¹ = a * (b * b⁻¹) : mul_assoc _ _ _ ... = a : by simp [h] @[simp] lemma mul_inv_cancel_left' {a : G₀} (h : a ≠ 0) (b : G₀) : a * (a⁻¹ * b) = b := calc a * (a⁻¹ * b) = (a * a⁻¹) * b : (mul_assoc _ _ _).symm ... = b : by simp [h] lemma inv_ne_zero {a : G₀} (h : a ≠ 0) : a⁻¹ ≠ 0 := assume a_eq_0, by simpa [a_eq_0] using mul_inv_cancel h @[simp] lemma inv_mul_cancel {a : G₀} (h : a ≠ 0) : a⁻¹ * a = 1 := calc a⁻¹ * a = (a⁻¹ * a) * a⁻¹ * a⁻¹⁻¹ : by simp [inv_ne_zero h] ... = a⁻¹ * a⁻¹⁻¹ : by simp [h] ... = 1 : by simp [inv_ne_zero h] @[simp] lemma inv_mul_cancel_right' {b : G₀} (h : b ≠ 0) (a : G₀) : (a * b⁻¹) * b = a := calc (a * b⁻¹) * b = a * (b⁻¹ * b) : mul_assoc _ _ _ ... = a : by simp [h] @[simp] lemma inv_mul_cancel_left' {a : G₀} (h : a ≠ 0) (b : G₀) : a⁻¹ * (a * b) = b := calc a⁻¹ * (a * b) = (a⁻¹ * a) * b : (mul_assoc _ _ _).symm ... = b : by simp [h] @[simp] lemma inv_one : 1⁻¹ = (1:G₀) := calc 1⁻¹ = 1 * 1⁻¹ : by rw [one_mul] ... = (1:G₀) : by simp @[simp] lemma inv_inv' (a : G₀) : a⁻¹⁻¹ = a := begin classical, by_cases h : a = 0, { simp [h] }, calc a⁻¹⁻¹ = a * (a⁻¹ * a⁻¹⁻¹) : by simp [h] ... = a : by simp [inv_ne_zero h] end /-- Multiplying `a` by itself and then by its inverse results in `a` (whether or not `a` is zero). -/ @[simp] lemma mul_self_mul_inv (a : G₀) : a * a * a⁻¹ = a := begin classical, by_cases h : a = 0, { rw [h, inv_zero, mul_zero] }, { rw [mul_assoc, mul_inv_cancel h, mul_one] } end /-- Multiplying `a` by its inverse and then by itself results in `a` (whether or not `a` is zero). -/ @[simp] lemma mul_inv_mul_self (a : G₀) : a * a⁻¹ * a = a := begin classical, by_cases h : a = 0, { rw [h, inv_zero, mul_zero] }, { rw [mul_inv_cancel h, one_mul] } end /-- Multiplying `a⁻¹` by `a` twice results in `a` (whether or not `a` is zero). -/ @[simp] lemma inv_mul_mul_self (a : G₀) : a⁻¹ * a * a = a := begin classical, by_cases h : a = 0, { rw [h, inv_zero, mul_zero] }, { rw [inv_mul_cancel h, one_mul] } end /-- Multiplying `a` by itself and then dividing by itself results in `a` (whether or not `a` is zero). -/ @[simp] lemma mul_self_div_self (a : G₀) : a * a / a = a := by rw [div_eq_mul_inv, mul_self_mul_inv a] /-- Dividing `a` by itself and then multiplying by itself results in `a` (whether or not `a` is zero). -/ @[simp] lemma div_self_mul_self (a : G₀) : a / a * a = a := by rw [div_eq_mul_inv, mul_inv_mul_self a] lemma inv_involutive' : function.involutive (has_inv.inv : G₀ → G₀) := inv_inv' lemma eq_inv_of_mul_right_eq_one {a b : G₀} (h : a * b = 1) : b = a⁻¹ := by rw [← inv_mul_cancel_left' (left_ne_zero_of_mul_eq_one h) b, h, mul_one] lemma eq_inv_of_mul_left_eq_one {a b : G₀} (h : a * b = 1) : a = b⁻¹ := by rw [← mul_inv_cancel_right' (right_ne_zero_of_mul_eq_one h) a, h, one_mul] lemma inv_injective' : function.injective (@has_inv.inv G₀ _) := inv_involutive'.injective @[simp] lemma inv_inj' {g h : G₀} : g⁻¹ = h⁻¹ ↔ g = h := inv_injective'.eq_iff lemma inv_eq_iff {g h : G₀} : g⁻¹ = h ↔ h⁻¹ = g := by rw [← inv_inj', eq_comm, inv_inv'] @[simp] lemma inv_eq_one' {g : G₀} : g⁻¹ = 1 ↔ g = 1 := by rw [inv_eq_iff, inv_one, eq_comm] end group_with_zero namespace units variables [group_with_zero G₀] variables {a b : G₀} /-- Embed a non-zero element of a `group_with_zero` into the unit group. By combining this function with the operations on units, or the `/ₚ` operation, it is possible to write a division as a partial function with three arguments. -/ def mk0 (a : G₀) (ha : a ≠ 0) : units G₀ := ⟨a, a⁻¹, mul_inv_cancel ha, inv_mul_cancel ha⟩ @[simp] lemma coe_mk0 {a : G₀} (h : a ≠ 0) : (mk0 a h : G₀) = a := rfl @[simp] lemma mk0_coe (u : units G₀) (h : (u : G₀) ≠ 0) : mk0 (u : G₀) h = u := units.ext rfl @[simp, norm_cast] lemma coe_inv' (u : units G₀) : ((u⁻¹ : units G₀) : G₀) = u⁻¹ := eq_inv_of_mul_left_eq_one u.inv_mul @[simp] lemma mul_inv' (u : units G₀) : (u : G₀) * u⁻¹ = 1 := mul_inv_cancel u.ne_zero @[simp] lemma inv_mul' (u : units G₀) : (u⁻¹ : G₀) * u = 1 := inv_mul_cancel u.ne_zero @[simp] lemma mk0_inj {a b : G₀} (ha : a ≠ 0) (hb : b ≠ 0) : units.mk0 a ha = units.mk0 b hb ↔ a = b := ⟨λ h, by injection h, λ h, units.ext h⟩ @[simp] lemma exists_iff_ne_zero {x : G₀} : (∃ u : units G₀, ↑u = x) ↔ x ≠ 0 := ⟨λ ⟨u, hu⟩, hu ▸ u.ne_zero, assume hx, ⟨mk0 x hx, rfl⟩⟩ end units section group_with_zero variables [group_with_zero G₀] lemma is_unit.mk0 (x : G₀) (hx : x ≠ 0) : is_unit x := is_unit_unit (units.mk0 x hx) lemma is_unit_iff_ne_zero {x : G₀} : is_unit x ↔ x ≠ 0 := units.exists_iff_ne_zero @[priority 10] -- see Note [lower instance priority] instance group_with_zero.no_zero_divisors : no_zero_divisors G₀ := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin classical, contrapose! h, exact ((units.mk0 a h.1) * (units.mk0 b h.2)).ne_zero end, .. (‹_› : group_with_zero G₀) } @[priority 10] -- see Note [lower instance priority] instance group_with_zero.cancel_monoid_with_zero : cancel_monoid_with_zero G₀ := { mul_left_cancel_of_ne_zero := λ x y z hx h, by rw [← inv_mul_cancel_left' hx y, h, inv_mul_cancel_left' hx z], mul_right_cancel_of_ne_zero := λ x y z hy h, by rw [← mul_inv_cancel_right' hy x, h, mul_inv_cancel_right' hy z], .. (‹_› : group_with_zero G₀) } lemma mul_inv_rev' (x y : G₀) : (x * y)⁻¹ = y⁻¹ * x⁻¹ := begin classical, by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, symmetry, apply eq_inv_of_mul_left_eq_one, simp [mul_assoc, hx, hy] end @[simp] lemma div_self {a : G₀} (h : a ≠ 0) : a / a = 1 := by rw [div_eq_mul_inv, mul_inv_cancel h] @[simp] lemma div_one (a : G₀) : a / 1 = a := by simp [div_eq_mul_inv a 1] @[simp] lemma zero_div (a : G₀) : 0 / a = 0 := by rw [div_eq_mul_inv, zero_mul] @[simp] lemma div_zero (a : G₀) : a / 0 = 0 := by rw [div_eq_mul_inv, inv_zero, mul_zero] @[simp] lemma div_mul_cancel (a : G₀) {b : G₀} (h : b ≠ 0) : a / b * b = a := by rw [div_eq_mul_inv, inv_mul_cancel_right' h a] lemma div_mul_cancel_of_imp {a b : G₀} (h : b = 0 → a = 0) : a / b * b = a := classical.by_cases (λ hb : b = 0, by simp [*]) (div_mul_cancel a) @[simp] lemma mul_div_cancel (a : G₀) {b : G₀} (h : b ≠ 0) : a * b / b = a := by rw [div_eq_mul_inv, mul_inv_cancel_right' h a] lemma mul_div_cancel_of_imp {a b : G₀} (h : b = 0 → a = 0) : a * b / b = a := classical.by_cases (λ hb : b = 0, by simp [*]) (mul_div_cancel a) local attribute [simp] div_eq_mul_inv mul_comm mul_assoc mul_left_comm lemma div_eq_mul_one_div (a b : G₀) : a / b = a * (1 / b) := by simp lemma mul_one_div_cancel {a : G₀} (h : a ≠ 0) : a * (1 / a) = 1 := by simp [h] lemma one_div_mul_cancel {a : G₀} (h : a ≠ 0) : (1 / a) * a = 1 := by simp [h] lemma one_div_one : 1 / 1 = (1:G₀) := div_self (ne.symm zero_ne_one) lemma one_div_ne_zero {a : G₀} (h : a ≠ 0) : 1 / a ≠ 0 := by simpa only [one_div] using inv_ne_zero h lemma eq_one_div_of_mul_eq_one {a b : G₀} (h : a * b = 1) : b = 1 / a := by simpa only [one_div] using eq_inv_of_mul_right_eq_one h lemma eq_one_div_of_mul_eq_one_left {a b : G₀} (h : b * a = 1) : b = 1 / a := by simpa only [one_div] using eq_inv_of_mul_left_eq_one h @[simp] lemma one_div_div (a b : G₀) : 1 / (a / b) = b / a := by rw [one_div, div_eq_mul_inv, mul_inv_rev', inv_inv', div_eq_mul_inv] lemma one_div_one_div (a : G₀) : 1 / (1 / a) = a := by simp lemma eq_of_one_div_eq_one_div {a b : G₀} (h : 1 / a = 1 / b) : a = b := by rw [← one_div_one_div a, h, one_div_one_div] variables {a b c : G₀} @[simp] lemma inv_eq_zero {a : G₀} : a⁻¹ = 0 ↔ a = 0 := by rw [inv_eq_iff, inv_zero, eq_comm] @[simp] lemma zero_eq_inv {a : G₀} : 0 = a⁻¹ ↔ 0 = a := eq_comm.trans $ inv_eq_zero.trans eq_comm lemma one_div_mul_one_div_rev (a b : G₀) : (1 / a) * (1 / b) = 1 / (b * a) := by simp only [div_eq_mul_inv, one_mul, mul_inv_rev'] theorem divp_eq_div (a : G₀) (u : units G₀) : a /ₚ u = a / u := by simpa only [div_eq_mul_inv] using congr_arg ((*) a) u.coe_inv' @[simp] theorem divp_mk0 (a : G₀) {b : G₀} (hb : b ≠ 0) : a /ₚ units.mk0 b hb = a / b := divp_eq_div _ _ lemma inv_div : (a / b)⁻¹ = b / a := by rw [div_eq_mul_inv, mul_inv_rev', div_eq_mul_inv, inv_inv'] lemma inv_div_left : a⁻¹ / b = (b * a)⁻¹ := by rw [mul_inv_rev', div_eq_mul_inv] lemma div_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 := by { rw div_eq_mul_inv, exact mul_ne_zero ha (inv_ne_zero hb) } @[simp] lemma div_eq_zero_iff : a / b = 0 ↔ a = 0 ∨ b = 0:= by simp [div_eq_mul_inv] lemma div_ne_zero_iff : a / b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 := (not_congr div_eq_zero_iff).trans not_or_distrib lemma div_left_inj' (hc : c ≠ 0) : a / c = b / c ↔ a = b := by rw [← divp_mk0 _ hc, ← divp_mk0 _ hc, divp_left_inj] lemma div_eq_iff_mul_eq (hb : b ≠ 0) : a / b = c ↔ c * b = a := ⟨λ h, by rw [← h, div_mul_cancel _ hb], λ h, by rw [← h, mul_div_cancel _ hb]⟩ lemma eq_div_iff_mul_eq (hc : c ≠ 0) : a = b / c ↔ a * c = b := by rw [eq_comm, div_eq_iff_mul_eq hc] lemma div_eq_of_eq_mul {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : y = z * x) : y / x = z := (div_eq_iff_mul_eq hx).2 h.symm lemma eq_div_of_mul_eq {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : z * x = y) : z = y / x := eq.symm $ div_eq_of_eq_mul hx h.symm lemma eq_of_div_eq_one (h : a / b = 1) : a = b := begin classical, by_cases hb : b = 0, { rw [hb, div_zero] at h, exact eq_of_zero_eq_one h a b }, { rwa [div_eq_iff_mul_eq hb, one_mul, eq_comm] at h } end lemma div_eq_one_iff_eq (hb : b ≠ 0) : a / b = 1 ↔ a = b := ⟨eq_of_div_eq_one, λ h, h.symm ▸ div_self hb⟩ lemma div_mul_left {a b : G₀} (hb : b ≠ 0) : b / (a * b) = 1 / a := by simp only [div_eq_mul_inv, mul_inv_rev', mul_inv_cancel_left' hb, one_mul] lemma mul_div_mul_right (a b : G₀) {c : G₀} (hc : c ≠ 0) : (a * c) / (b * c) = a / b := by simp only [div_eq_mul_inv, mul_inv_rev', mul_assoc, mul_inv_cancel_left' hc] lemma mul_mul_div (a : G₀) {b : G₀} (hb : b ≠ 0) : a = a * b * (1 / b) := by simp [hb] end group_with_zero section comm_group_with_zero -- comm variables [comm_group_with_zero G₀] {a b c : G₀} @[priority 10] -- see Note [lower instance priority] instance comm_group_with_zero.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero G₀ := { ..group_with_zero.cancel_monoid_with_zero, ..comm_group_with_zero.to_comm_monoid_with_zero G₀ } /-- Pullback a `comm_group_with_zero` class along an injective function. -/ protected def function.injective.comm_group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀'] [has_inv G₀'] (f : G₀' → G₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) : comm_group_with_zero G₀' := { .. hf.group_with_zero f zero one mul inv, .. hf.comm_semigroup f mul } /-- Pullback a `comm_group_with_zero` class along an injective function. -/ protected def function.injective.comm_group_with_zero_div [has_zero G₀'] [has_mul G₀'] [has_one G₀'] [has_inv G₀'] [has_div G₀'] (f : G₀' → G₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : comm_group_with_zero G₀' := { .. hf.group_with_zero_div f zero one mul inv div, .. hf.comm_semigroup f mul } /-- Pushforward a `comm_group_with_zero` class along an surjective function. -/ protected def function.surjective.comm_group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀'] [has_inv G₀'] (h01 : (0:G₀') ≠ 1) (f : G₀ → G₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) : comm_group_with_zero G₀' := { .. hf.group_with_zero h01 f zero one mul inv, .. hf.comm_semigroup f mul } /-- Pushforward a `comm_group_with_zero` class along a surjective function. -/ protected def function.surjective.comm_group_with_zero_div [has_zero G₀'] [has_mul G₀'] [has_one G₀'] [has_inv G₀'] [has_div G₀'] (h01 : (0:G₀') ≠ 1) (f : G₀ → G₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : comm_group_with_zero G₀' := { .. hf.group_with_zero_div h01 f zero one mul inv div, .. hf.comm_semigroup f mul } lemma mul_inv' : (a * b)⁻¹ = a⁻¹ * b⁻¹ := by rw [mul_inv_rev', mul_comm] lemma one_div_mul_one_div (a b : G₀) : (1 / a) * (1 / b) = 1 / (a * b) := by rw [one_div_mul_one_div_rev, mul_comm b] lemma div_mul_right {a : G₀} (b : G₀) (ha : a ≠ 0) : a / (a * b) = 1 / b := by rw [mul_comm, div_mul_left ha] lemma mul_div_cancel_left_of_imp {a b : G₀} (h : a = 0 → b = 0) : a * b / a = b := by rw [mul_comm, mul_div_cancel_of_imp h] lemma mul_div_cancel_left {a : G₀} (b : G₀) (ha : a ≠ 0) : a * b / a = b := mul_div_cancel_left_of_imp $ λ h, (ha h).elim lemma mul_div_cancel_of_imp' {a b : G₀} (h : b = 0 → a = 0) : b * (a / b) = a := by rw [mul_comm, div_mul_cancel_of_imp h] lemma mul_div_cancel' (a : G₀) {b : G₀} (hb : b ≠ 0) : b * (a / b) = a := by rw [mul_comm, (div_mul_cancel _ hb)] local attribute [simp] mul_assoc mul_comm mul_left_comm lemma div_mul_div (a b c d : G₀) : (a / b) * (c / d) = (a * c) / (b * d) := by simp [div_eq_mul_inv, mul_inv'] lemma mul_div_mul_left (a b : G₀) {c : G₀} (hc : c ≠ 0) : (c * a) / (c * b) = a / b := by rw [mul_comm c, mul_comm c, mul_div_mul_right _ _ hc] @[field_simps] lemma div_mul_eq_mul_div (a b c : G₀) : (b / c) * a = (b * a) / c := by simp [div_eq_mul_inv] lemma div_mul_eq_mul_div_comm (a b c : G₀) : (b / c) * a = b * (a / c) := by rw [div_mul_eq_mul_div, ← one_mul c, ← div_mul_div, div_one, one_mul] lemma mul_eq_mul_of_div_eq_div (a : G₀) {b : G₀} (c : G₀) {d : G₀} (hb : b ≠ 0) (hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b := by rw [← mul_one (a*d), mul_assoc, mul_comm d, ← mul_assoc, ← div_self hb, ← div_mul_eq_mul_div_comm, h, div_mul_eq_mul_div, div_mul_cancel _ hd] @[field_simps] lemma div_div_eq_mul_div (a b c : G₀) : a / (b / c) = (a * c) / b := by rw [div_eq_mul_one_div, one_div_div, ← mul_div_assoc] @[field_simps] lemma div_div_eq_div_mul (a b c : G₀) : (a / b) / c = a / (b * c) := by rw [div_eq_mul_one_div, div_mul_div, mul_one] lemma div_div_div_div_eq (a : G₀) {b c d : G₀} : (a / b) / (c / d) = (a * d) / (b * c) := by rw [div_div_eq_mul_div, div_mul_eq_mul_div, div_div_eq_div_mul] lemma div_mul_eq_div_mul_one_div (a b c : G₀) : a / (b * c) = (a / b) * (1 / c) := by rw [← div_div_eq_div_mul, ← div_eq_mul_one_div] /-- Dividing `a` by the result of dividing `a` by itself results in `a` (whether or not `a` is zero). -/ @[simp] lemma div_div_self (a : G₀) : a / (a / a) = a := begin rw div_div_eq_mul_div, exact mul_self_div_self a end lemma ne_zero_of_one_div_ne_zero {a : G₀} (h : 1 / a ≠ 0) : a ≠ 0 := assume ha : a = 0, begin rw [ha, div_zero] at h, contradiction end lemma eq_zero_of_one_div_eq_zero {a : G₀} (h : 1 / a = 0) : a = 0 := classical.by_cases (assume ha, ha) (assume ha, ((one_div_ne_zero ha) h).elim) lemma div_helper {a : G₀} (b : G₀) (h : a ≠ 0) : (1 / (a * b)) * a = 1 / b := by rw [div_mul_eq_mul_div, one_mul, div_mul_right _ h] end comm_group_with_zero section comm_group_with_zero variables [comm_group_with_zero G₀] {a b c d : G₀} lemma div_eq_inv_mul : a / b = b⁻¹ * a := by rw [div_eq_mul_inv, mul_comm] lemma mul_div_right_comm (a b c : G₀) : (a * b) / c = (a / c) * b := by rw [div_eq_mul_inv, mul_assoc, mul_comm b, ← mul_assoc, div_eq_mul_inv] lemma mul_comm_div' (a b c : G₀) : (a / b) * c = a * (c / b) := by rw [← mul_div_assoc, mul_div_right_comm] lemma div_mul_comm' (a b c : G₀) : (a / b) * c = (c / b) * a := by rw [div_mul_eq_mul_div, mul_comm, mul_div_right_comm] lemma mul_div_comm (a b c : G₀) : a * (b / c) = b * (a / c) := by rw [← mul_div_assoc, mul_comm, mul_div_assoc] lemma div_right_comm (a : G₀) : (a / b) / c = (a / c) / b := by rw [div_div_eq_div_mul, div_div_eq_div_mul, mul_comm] lemma div_div_div_cancel_right (a : G₀) (hc : c ≠ 0) : (a / c) / (b / c) = a / b := by rw [div_div_eq_mul_div, div_mul_cancel _ hc] lemma div_mul_div_cancel (a : G₀) (hc : c ≠ 0) : (a / c) * (c / b) = a / b := by rw [← mul_div_assoc, div_mul_cancel _ hc] @[field_simps] lemma div_eq_div_iff (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b := calc a / b = c / d ↔ a / b * (b * d) = c / d * (b * d) : by rw [mul_left_inj' (mul_ne_zero hb hd)] ... ↔ a * d = c * b : by rw [← mul_assoc, div_mul_cancel _ hb, ← mul_assoc, mul_right_comm, div_mul_cancel _ hd] @[field_simps] lemma div_eq_iff (hb : b ≠ 0) : a / b = c ↔ a = c * b := by simpa using @div_eq_div_iff _ _ a b c 1 hb one_ne_zero @[field_simps] lemma eq_div_iff (hb : b ≠ 0) : c = a / b ↔ c * b = a := by simpa using @div_eq_div_iff _ _ c 1 a b one_ne_zero hb lemma div_div_cancel' (ha : a ≠ 0) : a / (a / b) = b := by rw [div_eq_mul_inv, inv_div, mul_div_cancel' _ ha] end comm_group_with_zero namespace semiconj_by @[simp] lemma zero_right [mul_zero_class G₀] (a : G₀) : semiconj_by a 0 0 := by simp only [semiconj_by, mul_zero, zero_mul] @[simp] lemma zero_left [mul_zero_class G₀] (x y : G₀) : semiconj_by 0 x y := by simp only [semiconj_by, mul_zero, zero_mul] variables [group_with_zero G₀] {a x y x' y' : G₀} @[simp] lemma inv_symm_left_iff' : semiconj_by a⁻¹ x y ↔ semiconj_by a y x := classical.by_cases (λ ha : a = 0, by simp only [ha, inv_zero, semiconj_by.zero_left]) (λ ha, @units_inv_symm_left_iff _ _ (units.mk0 a ha) _ _) lemma inv_symm_left' (h : semiconj_by a x y) : semiconj_by a⁻¹ y x := semiconj_by.inv_symm_left_iff'.2 h lemma inv_right' (h : semiconj_by a x y) : semiconj_by a x⁻¹ y⁻¹ := begin classical, by_cases ha : a = 0, { simp only [ha, zero_left] }, by_cases hx : x = 0, { subst x, simp only [semiconj_by, mul_zero, @eq_comm _ _ (y * a), mul_eq_zero] at h, simp [h.resolve_right ha] }, { have := mul_ne_zero ha hx, rw [h.eq, mul_ne_zero_iff] at this, exact @units_inv_right _ _ _ (units.mk0 x hx) (units.mk0 y this.1) h }, end @[simp] lemma inv_right_iff' : semiconj_by a x⁻¹ y⁻¹ ↔ semiconj_by a x y := ⟨λ h, inv_inv' x ▸ inv_inv' y ▸ h.inv_right', inv_right'⟩ lemma div_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x / x') (y / y') := by { rw [div_eq_mul_inv, div_eq_mul_inv], exact h.mul_right h'.inv_right' } end semiconj_by namespace commute @[simp] theorem zero_right [mul_zero_class G₀] (a : G₀) :commute a 0 := semiconj_by.zero_right a @[simp] theorem zero_left [mul_zero_class G₀] (a : G₀) : commute 0 a := semiconj_by.zero_left a a variables [group_with_zero G₀] {a b c : G₀} @[simp] theorem inv_left_iff' : commute a⁻¹ b ↔ commute a b := semiconj_by.inv_symm_left_iff' theorem inv_left' (h : commute a b) : commute a⁻¹ b := inv_left_iff'.2 h @[simp] theorem inv_right_iff' : commute a b⁻¹ ↔ commute a b := semiconj_by.inv_right_iff' theorem inv_right' (h : commute a b) : commute a b⁻¹ := inv_right_iff'.2 h theorem inv_inv' (h : commute a b) : commute a⁻¹ b⁻¹ := h.inv_left'.inv_right' @[simp] theorem div_right (hab : commute a b) (hac : commute a c) : commute a (b / c) := hab.div_right hac @[simp] theorem div_left (hac : commute a c) (hbc : commute b c) : commute (a / b) c := by { rw div_eq_mul_inv, exact hac.mul_left hbc.inv_left' } end commute namespace monoid_with_zero_hom variables [group_with_zero G₀] [group_with_zero G₀'] [monoid_with_zero M₀] [nontrivial M₀] section monoid_with_zero variables (f : monoid_with_zero_hom G₀ M₀) {a : G₀} lemma map_ne_zero : f a ≠ 0 ↔ a ≠ 0 := ⟨λ hfa ha, hfa $ ha.symm ▸ f.map_zero, λ ha, ((is_unit.mk0 a ha).map f.to_monoid_hom).ne_zero⟩ @[simp] lemma map_eq_zero : f a = 0 ↔ a = 0 := by { classical, exact not_iff_not.1 f.map_ne_zero } end monoid_with_zero section group_with_zero variables (f : monoid_with_zero_hom G₀ G₀') (a b : G₀) /-- A monoid homomorphism between groups with zeros sending `0` to `0` sends `a⁻¹` to `(f a)⁻¹`. -/ @[simp] lemma map_inv' : f a⁻¹ = (f a)⁻¹ := begin classical, by_cases h : a = 0, by simp [h], apply eq_inv_of_mul_left_eq_one, rw [← f.map_mul, inv_mul_cancel h, f.map_one] end @[simp] lemma map_div : f (a / b) = f a / f b := by simpa only [div_eq_mul_inv] using ((f.map_mul _ _).trans $ _root_.congr_arg _ $ f.map_inv' b) end group_with_zero end monoid_with_zero_hom @[simp] lemma monoid_hom.map_units_inv {M G₀ : Type*} [monoid M] [group_with_zero G₀] (f : M →* G₀) (u : units M) : f ↑u⁻¹ = (f u)⁻¹ := by rw [← units.coe_map, ← units.coe_map, ← units.coe_inv', monoid_hom.map_inv] section noncomputable_defs variables {M : Type*} [nontrivial M] /-- Constructs a `group_with_zero` structure on a `monoid_with_zero` consisting only of units and 0. -/ noncomputable def group_with_zero_of_is_unit_or_eq_zero [hM : monoid_with_zero M] (h : ∀ (a : M), is_unit a ∨ a = 0) : group_with_zero M := { inv := λ a, if h0 : a = 0 then 0 else ↑((h a).resolve_right h0).unit⁻¹, inv_zero := dif_pos rfl, mul_inv_cancel := λ a h0, by { change a * (if h0 : a = 0 then 0 else ↑((h a).resolve_right h0).unit⁻¹) = 1, rw [dif_neg h0, units.mul_inv_eq_iff_eq_mul, one_mul, is_unit.unit_spec] }, exists_pair_ne := nontrivial.exists_pair_ne, .. hM } /-- Constructs a `comm_group_with_zero` structure on a `comm_monoid_with_zero` consisting only of units and 0. -/ noncomputable def comm_group_with_zero_of_is_unit_or_eq_zero [hM : comm_monoid_with_zero M] (h : ∀ (a : M), is_unit a ∨ a = 0) : comm_group_with_zero M := { .. (group_with_zero_of_is_unit_or_eq_zero h), .. hM } end noncomputable_defs
1c05f6ee98ce4785402dc5779f68e7a2eaebe765
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Elab/Print.lean
ebfff26fe3d34b3cafddbf98c5f206cd8e08159c
[ "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
5,467
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.FoldConsts import Lean.Elab.Command namespace Lean namespace Elab namespace Command private def throwUnknownId (id : Name) : CommandElabM Unit := throwError ("unknown identifier '" ++ toString id ++ "'") private def lparamsToMessageData (lparams : List Name) : MessageData := match lparams with | [] => "" | u::us => let m : MessageData := ".{" ++ u; let m := us.foldl (fun (s : MessageData) u => s ++ ", " ++ u) m; m ++ "}" private def mkHeader (kind : String) (id : Name) (lparams : List Name) (type : Expr) (isUnsafe : Bool) : CommandElabM MessageData := do let m : MessageData := if isUnsafe then "unsafe " else ""; env ← getEnv; let m := if isProtected env id then m ++ "protected " else m; let (m, id) := match privateToUserName? id : _ → MessageData × Name with | some id => (m ++ "private ", id) | none => (m, id); let m := m ++ kind ++ " " ++ id ++ lparamsToMessageData lparams ++ " : " ++ type; pure m private def printDefLike (kind : String) (id : Name) (lparams : List Name) (type : Expr) (value : Expr) (isUnsafe := false) : CommandElabM Unit := do m ← mkHeader kind id lparams type isUnsafe; let m := m ++ " :=" ++ Format.line ++ value; logInfo m private def printAxiomLike (kind : String) (id : Name) (lparams : List Name) (type : Expr) (isUnsafe := false) : CommandElabM Unit := do m ← mkHeader kind id lparams type isUnsafe; logInfo m private def printQuot (kind : QuotKind) (id : Name) (lparams : List Name) (type : Expr) : CommandElabM Unit := do printAxiomLike "Quotient primitive" id lparams type private def printInduct (id : Name) (lparams : List Name) (nparams : Nat) (nindices : Nat) (type : Expr) (ctors : List Name) (isUnsafe : Bool) : CommandElabM Unit := do env ← getEnv; m ← mkHeader "inductive" id lparams type isUnsafe; let m := m ++ Format.line ++ "constructors:"; m ← ctors.foldlM (fun (m : MessageData) ctor => do cinfo ← getConstInfo ctor; pure $ m ++ Format.line ++ ctor ++ " : " ++ cinfo.type) m; logInfo m private def printIdCore (id : Name) : CommandElabM Unit := do env ← getEnv; match env.find? id with | ConstantInfo.axiomInfo { lparams := us, type := t, isUnsafe := u, .. } => printAxiomLike "axiom" id us t u | ConstantInfo.defnInfo { lparams := us, type := t, value := v, isUnsafe := u, .. } => printDefLike "def" id us t v u | ConstantInfo.thmInfo { lparams := us, type := t, value := v, .. } => printDefLike "theorem" id us t v | ConstantInfo.opaqueInfo { lparams := us, type := t, isUnsafe := u, .. } => printAxiomLike "constant" id us t u | ConstantInfo.quotInfo { kind := kind, lparams := us, type := t, .. } => printQuot kind id us t | ConstantInfo.ctorInfo { lparams := us, type := t, isUnsafe := u, .. } => printAxiomLike "constructor" id us t u | ConstantInfo.recInfo { lparams := us, type := t, isUnsafe := u, .. } => printAxiomLike "recursor" id us t u | ConstantInfo.inductInfo { lparams := us, nparams := nparams, nindices := nindices, type := t, ctors := ctors, isUnsafe := u, .. } => printInduct id us nparams nindices t ctors u | none => throwUnknownId id def resolveId (id : Name) : CommandElabM (List Name) := do liftTermElabM none $ Term.resolveGlobalConst id private def printId (id : Name) : CommandElabM Unit := do cs ← resolveId id; cs.forM printIdCore @[builtinCommandElab «print»] def elabPrint : CommandElab := fun stx => let numArgs := stx.getNumArgs; if numArgs == 2 then let arg := stx.getArg 1; if arg.isIdent then printId arg.getId else match arg.isStrLit? with | some val => logInfo val | none => throwError "WIP" else throwError "invalid #print command" namespace CollectAxioms structure State := (visited : NameSet := {}) (axioms : Array Name := #[]) abbrev M := ReaderT Environment $ StateM State partial def collect : Name → M Unit | c => do let collectExpr (e : Expr) : M Unit := e.getUsedConstants.forM collect; s ← get; unless (s.visited.contains c) do modify fun s => { s with visited := s.visited.insert c }; env ← read; match env.find? c with | some (ConstantInfo.axiomInfo _) => modify fun s => { s with axioms := s.axioms.push c } | some (ConstantInfo.defnInfo v) => collectExpr v.type *> collectExpr v.value | some (ConstantInfo.thmInfo v) => collectExpr v.type *> collectExpr v.value | some (ConstantInfo.opaqueInfo v) => collectExpr v.type *> collectExpr v.value | some (ConstantInfo.quotInfo _) => pure () | some (ConstantInfo.ctorInfo v) => collectExpr v.type | some (ConstantInfo.recInfo v) => collectExpr v.type | some (ConstantInfo.inductInfo v) => collectExpr v.type *> v.ctors.forM collect | none => pure () end CollectAxioms private def printAxiomsOf (constName : Name) : CommandElabM Unit := do env ← getEnv; let (_, s) := ((CollectAxioms.collect constName).run env).run {}; if s.axioms.isEmpty then logInfo ("'" ++ constName ++ "' does not depend on any axioms") else logInfo ("'" ++ constName ++ "' depends on axioms: " ++ toString s.axioms.toList) @[builtinCommandElab «printAxioms»] def elabPrintAxioms : CommandElab := fun stx => do let id := (stx.getArg 2).getId; cs ← resolveId id; cs.forM printAxiomsOf end Command end Elab end Lean
a87222850b8bdf2b7311c166ec53163545731e30
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/group_theory/group_action/basic.lean
273cddea6076df010976e7585b92976966933b11
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,107
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.group_action.defs import group_theory.group_action.group import group_theory.coset /-! # Basic properties of group actions -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open_locale big_operators open function namespace mul_action variables (α) [monoid α] [mul_action α β] /-- The orbit of an element under an action. -/ def orbit (b : β) := set.range (λ x : α, x • b) variable {α} lemma mem_orbit_iff {b₁ b₂ : β} : b₂ ∈ orbit α b₁ ↔ ∃ x : α, x • b₁ = b₂ := iff.rfl @[simp] lemma mem_orbit (b : β) (x : α) : x • b ∈ orbit α b := ⟨x, rfl⟩ @[simp] lemma mem_orbit_self (b : β) : b ∈ orbit α b := ⟨1, by simp [mul_action.one_smul]⟩ variables (α) (β) /-- The set of elements fixed under the whole action. -/ def fixed_points : set β := {b : β | ∀ x : α, x • b = b} /-- `fixed_by g` is the subfield of elements fixed by `g`. -/ def fixed_by (g : α) : set β := { x | g • x = x } theorem fixed_eq_Inter_fixed_by : fixed_points α β = ⋂ g : α, fixed_by α β g := set.ext $ λ x, ⟨λ hx, set.mem_Inter.2 $ λ g, hx g, λ hx g, by exact (set.mem_Inter.1 hx g : _)⟩ variables {α} (β) @[simp] lemma mem_fixed_points {b : β} : b ∈ fixed_points α β ↔ ∀ x : α, x • b = b := iff.rfl @[simp] lemma mem_fixed_by {g : α} {b : β} : b ∈ fixed_by α β g ↔ g • b = b := iff.rfl lemma mem_fixed_points' {b : β} : b ∈ fixed_points α β ↔ (∀ b', b' ∈ orbit α b → b' = b) := ⟨λ h b h₁, let ⟨x, hx⟩ := mem_orbit_iff.1 h₁ in hx ▸ h x, λ h b, h _ (mem_orbit _ _)⟩ variables (α) {β} /-- The stabilizer of a point `b` as a submonoid of `α`. -/ def stabilizer.submonoid (b : β) : submonoid α := { carrier := { a | a • b = b }, one_mem' := one_smul _ b, mul_mem' := λ a a' (ha : a • b = b) (hb : a' • b = b), show (a * a') • b = b, by rw [←smul_smul, hb, ha] } @[simp] lemma mem_stabilizer_submonoid_iff {b : β} {a : α} : a ∈ stabilizer.submonoid α b ↔ a • b = b := iff.rfl end mul_action namespace mul_action variable (α) variables [group α] [mul_action α β] /-- The stabilizer of an element under an action, i.e. what sends the element to itself. A subgroup. -/ def stabilizer (b : β) : subgroup α := { inv_mem' := λ a (ha : a • b = b), show a⁻¹ • b = b, by rw [inv_smul_eq_iff, ha] ..stabilizer.submonoid α b } variables {α} {β} @[simp] lemma mem_stabilizer_iff {b : β} {a : α} : a ∈ stabilizer α b ↔ a • b = b := iff.rfl lemma orbit_eq_iff {a b : β} : orbit α a = orbit α b ↔ a ∈ orbit α b:= ⟨λ h, h ▸ mem_orbit_self _, λ ⟨x, (hx : x • b = a)⟩, set.ext (λ c, ⟨λ ⟨y, (hy : y • a = c)⟩, ⟨y * x, show (y * x) • b = c, by rwa [mul_action.mul_smul, hx]⟩, λ ⟨y, (hy : y • b = c)⟩, ⟨y * x⁻¹, show (y * x⁻¹) • a = c, by conv {to_rhs, rw [← hy, ← mul_one y, ← inv_mul_self x, ← mul_assoc, mul_action.mul_smul, hx]}⟩⟩)⟩ variables (α) {β} @[simp] lemma mem_orbit_smul (g : α) (a : β) : a ∈ orbit α (g • a) := ⟨g⁻¹, by simp⟩ @[simp] lemma smul_mem_orbit_smul (g h : α) (a : β) : g • a ∈ orbit α (h • a) := ⟨g * h⁻¹, by simp [mul_smul]⟩ variables (α) (β) /-- The relation "in the same orbit". -/ def orbit_rel : setoid β := { r := λ a b, a ∈ orbit α b, iseqv := ⟨mem_orbit_self, λ a b, by simp [orbit_eq_iff.symm, eq_comm], λ a b, by simp [orbit_eq_iff.symm, eq_comm] {contextual := tt}⟩ } variables {α β} open quotient_group /-- Action on left cosets. -/ def mul_left_cosets (H : subgroup α) (x : α) (y : quotient H) : quotient H := quotient.lift_on' y (λ y, quotient_group.mk ((x : α) * y)) (λ a b (hab : _ ∈ H), quotient_group.eq.2 (by rwa [mul_inv_rev, ← mul_assoc, mul_assoc (a⁻¹), inv_mul_self, mul_one])) instance quotient (H : subgroup α) : mul_action α (quotient H) := { smul := mul_left_cosets H, one_smul := λ a, quotient.induction_on' a (λ a, quotient_group.eq.2 (by simp [subgroup.one_mem])), mul_smul := λ x y a, quotient.induction_on' a (λ a, quotient_group.eq.2 (by simp [mul_inv_rev, subgroup.one_mem, mul_assoc])) } @[simp] lemma quotient.smul_mk (H : subgroup α) (a x : α) : (a • quotient_group.mk x : quotient_group.quotient H) = quotient_group.mk (a * x) := rfl @[simp] lemma quotient.smul_coe (H : subgroup α) (a x : α) : (a • x : quotient_group.quotient H) = ↑(a * x) := rfl instance mul_left_cosets_comp_subtype_val (H I : subgroup α) : mul_action I (quotient H) := mul_action.comp_hom (quotient H) (subgroup.subtype I) variables (α) {β} (x : β) /-- The canonical map from the quotient of the stabilizer to the set. -/ def of_quotient_stabilizer (g : quotient (mul_action.stabilizer α x)) : β := quotient.lift_on' g (•x) $ λ g1 g2 H, calc g1 • x = g1 • (g1⁻¹ * g2) • x : congr_arg _ H.symm ... = g2 • x : by rw [smul_smul, mul_inv_cancel_left] @[simp] theorem of_quotient_stabilizer_mk (g : α) : of_quotient_stabilizer α x (quotient_group.mk g) = g • x := rfl theorem of_quotient_stabilizer_mem_orbit (g) : of_quotient_stabilizer α x g ∈ orbit α x := quotient.induction_on' g $ λ g, ⟨g, rfl⟩ theorem of_quotient_stabilizer_smul (g : α) (g' : quotient (mul_action.stabilizer α x)) : of_quotient_stabilizer α x (g • g') = g • of_quotient_stabilizer α x g' := quotient.induction_on' g' $ λ _, mul_smul _ _ _ theorem injective_of_quotient_stabilizer : function.injective (of_quotient_stabilizer α x) := λ y₁ y₂, quotient.induction_on₂' y₁ y₂ $ λ g₁ g₂ (H : g₁ • x = g₂ • x), quotient.sound' $ show (g₁⁻¹ * g₂) • x = x, by rw [mul_smul, ← H, inv_smul_smul] /-- Orbit-stabilizer theorem. -/ noncomputable def orbit_equiv_quotient_stabilizer (b : β) : orbit α b ≃ quotient (stabilizer α b) := equiv.symm $ equiv.of_bijective (λ g, ⟨of_quotient_stabilizer α b g, of_quotient_stabilizer_mem_orbit α b g⟩) ⟨λ x y hxy, injective_of_quotient_stabilizer α b (by convert congr_arg subtype.val hxy), λ ⟨b, ⟨g, hgb⟩⟩, ⟨g, subtype.eq hgb⟩⟩ @[simp] theorem orbit_equiv_quotient_stabilizer_symm_apply (b : β) (a : α) : ((orbit_equiv_quotient_stabilizer α b).symm a : β) = a • b := rfl end mul_action section variables [monoid α] [add_monoid β] [distrib_mul_action α β] lemma list.smul_sum {r : α} {l : list β} : r • l.sum = (l.map ((•) r)).sum := (const_smul_hom β r).map_list_sum l end section variables [monoid α] [add_comm_monoid β] [distrib_mul_action α β] lemma multiset.smul_sum {r : α} {s : multiset β} : r • s.sum = (s.map ((•) r)).sum := (const_smul_hom β r).map_multiset_sum s lemma finset.smul_sum {r : α} {f : γ → β} {s : finset γ} : r • ∑ x in s, f x = ∑ x in s, r • f x := (const_smul_hom β r).map_sum f s end
c35847db749611a343bf4bde48e413fcfe589d1d
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/stage0/src/Std/Data/PersistentArray.lean
2d053df753fe8e6572cdbd4201d78632fe219b1a
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,333
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 -/ universes u v w namespace Std inductive PersistentArrayNode (α : Type u) | node (cs : Array PersistentArrayNode) : PersistentArrayNode | leaf (vs : Array α) : PersistentArrayNode namespace PersistentArrayNode instance {α : Type u} : Inhabited (PersistentArrayNode α) := ⟨leaf #[]⟩ def isNode {α} : PersistentArrayNode α → Bool | node _ => true | leaf _ => false end PersistentArrayNode abbrev PersistentArray.initShift : USize := 5 abbrev PersistentArray.branching : USize := USize.ofNat (2 ^ PersistentArray.initShift.toNat) structure PersistentArray (α : Type u) := /- Recall that we run out of memory if we have more than `usizeSz/8` elements. So, we can stop adding elements at `root` after `size > usizeSz`, and keep growing the `tail`. This modification allow us to use `USize` instead of `Nat` when traversing `root`. -/ (root : PersistentArrayNode α := PersistentArrayNode.node (Array.mkEmpty PersistentArray.branching.toNat)) (tail : Array α := Array.mkEmpty PersistentArray.branching.toNat) (size : Nat := 0) (shift : USize := PersistentArray.initShift) (tailOff : Nat := 0) abbrev PArray (α : Type u) := PersistentArray α namespace PersistentArray /- TODO: use proofs for showing that array accesses are not out of bounds. We can do it after we reimplement the tactic framework. -/ variables {α : Type u} open Std.PersistentArrayNode def empty : PersistentArray α := {} def isEmpty (a : PersistentArray α) : Bool := a.size == 0 instance : Inhabited (PersistentArray α) := ⟨{}⟩ def mkEmptyArray : Array α := Array.mkEmpty branching.toNat abbrev mul2Shift (i : USize) (shift : USize) : USize := i.shiftLeft shift abbrev div2Shift (i : USize) (shift : USize) : USize := i.shiftRight shift abbrev mod2Shift (i : USize) (shift : USize) : USize := USize.land i ((USize.shiftLeft 1 shift) - 1) partial def getAux [Inhabited α] : PersistentArrayNode α → USize → USize → α | node cs, i, shift => getAux (cs.get! (div2Shift i shift).toNat) (mod2Shift i shift) (shift - initShift) | leaf cs, i, _ => cs.get! i.toNat def get! [Inhabited α] (t : PersistentArray α) (i : Nat) : α := if i >= t.tailOff then t.tail.get! (i - t.tailOff) else getAux t.root (USize.ofNat i) t.shift def getOp [Inhabited α] (self : PersistentArray α) (idx : Nat) : α := self.get! idx partial def setAux : PersistentArrayNode α → USize → USize → α → PersistentArrayNode α | node cs, i, shift, a => let j := div2Shift i shift; let i := mod2Shift i shift; let shift := shift - initShift; node $ cs.modify j.toNat $ fun c => setAux c i shift a | leaf cs, i, _, a => leaf (cs.set! i.toNat a) def set (t : PersistentArray α) (i : Nat) (a : α) : PersistentArray α := if i >= t.tailOff then { t with tail := t.tail.set! (i - t.tailOff) a } else { t with root := setAux t.root (USize.ofNat i) t.shift a } @[specialize] partial def modifyAux [Inhabited α] (f : α → α) : PersistentArrayNode α → USize → USize → PersistentArrayNode α | node cs, i, shift => let j := div2Shift i shift; let i := mod2Shift i shift; let shift := shift - initShift; node $ cs.modify j.toNat $ fun c => modifyAux c i shift | leaf cs, i, _ => leaf (cs.modify i.toNat f) @[specialize] def modify [Inhabited α] (t : PersistentArray α) (i : Nat) (f : α → α) : PersistentArray α := if i >= t.tailOff then { t with tail := t.tail.modify (i - t.tailOff) f } else { t with root := modifyAux f t.root (USize.ofNat i) t.shift } partial def mkNewPath : USize → Array α → PersistentArrayNode α | shift, a => if shift == 0 then leaf a else node (mkEmptyArray.push (mkNewPath (shift - initShift) a)) partial def insertNewLeaf : PersistentArrayNode α → USize → USize → Array α → PersistentArrayNode α | node cs, i, shift, a => if i < branching then node (cs.push (leaf a)) else let j := div2Shift i shift; let i := mod2Shift i shift; let shift := shift - initShift; if j.toNat < cs.size then node $ cs.modify j.toNat $ fun c => insertNewLeaf c i shift a else node $ cs.push $ mkNewPath shift a | n, _, _, _ => n -- unreachable def mkNewTail (t : PersistentArray α) : PersistentArray α := if t.size <= (mul2Shift 1 (t.shift + initShift)).toNat then { t with tail := mkEmptyArray, root := insertNewLeaf t.root (USize.ofNat (t.size - 1)) t.shift t.tail, tailOff := t.size } else { t with tail := #[], root := let n := mkEmptyArray.push t.root; node (n.push (mkNewPath t.shift t.tail)), shift := t.shift + initShift, tailOff := t.size } def tooBig : Nat := usizeSz / 8 def push (t : PersistentArray α) (a : α) : PersistentArray α := let r := { t with tail := t.tail.push a, size := t.size + 1 }; if r.tail.size < branching.toNat || t.size >= tooBig then r else mkNewTail r private def emptyArray {α : Type u} : Array (PersistentArrayNode α) := Array.mkEmpty PersistentArray.branching.toNat partial def popLeaf : PersistentArrayNode α → Option (Array α) × Array (PersistentArrayNode α) | n@(node cs) => if h : cs.size ≠ 0 then let idx : Fin cs.size := ⟨cs.size - 1, Nat.predLt h⟩; let last := cs.get idx; let cs := cs.set idx (arbitrary _); match popLeaf last with | (none, _) => (none, emptyArray) | (some l, newLast) => if newLast.size == 0 then let cs := cs.pop; if cs.isEmpty then (some l, emptyArray) else (some l, cs) else (some l, cs.set idx (node newLast)) else (none, emptyArray) | leaf vs => (some vs, emptyArray) def pop (t : PersistentArray α) : PersistentArray α := if t.tail.size > 0 then { t with tail := t.tail.pop, size := t.size - 1 } else match popLeaf t.root with | (none, _) => t | (some last, newRoots) => let last := last.pop; let newSize := t.size - 1; let newTailOff := newSize - last.size; if newRoots.size == 1 && (newRoots.get! 0).isNode then { root := newRoots.get! 0, shift := t.shift - initShift, size := newSize, tail := last, tailOff := newTailOff } else { t with root := node newRoots, size := newSize, tail := last, tailOff := newTailOff } section variables {m : Type v → Type w} [Monad m] variable {β : Type v} @[specialize] partial def foldlMAux (f : β → α → m β) : PersistentArrayNode α → β → m β | node cs, b => cs.foldlM (fun b c => foldlMAux c b) b | leaf vs, b => vs.foldlM f b @[specialize] def foldlM (t : PersistentArray α) (f : β → α → m β) (b : β) : m β := do b ← foldlMAux f t.root b; t.tail.foldlM f b @[specialize] partial def findSomeMAux (f : α → m (Option β)) : PersistentArrayNode α → m (Option β) | node cs => cs.findSomeM? (fun c => findSomeMAux c) | leaf vs => vs.findSomeM? f @[specialize] def findSomeM? (t : PersistentArray α) (f : α → m (Option β)) : m (Option β) := do b ← findSomeMAux f t.root; match b with | none => t.tail.findSomeM? f | some b => pure (some b) @[specialize] partial def findSomeRevMAux (f : α → m (Option β)) : PersistentArrayNode α → m (Option β) | node cs => cs.findSomeRevM? (fun c => findSomeRevMAux c) | leaf vs => vs.findSomeRevM? f @[specialize] def findSomeRevM? (t : PersistentArray α) (f : α → m (Option β)) : m (Option β) := do b ← t.tail.findSomeRevM? f; match b with | none => findSomeRevMAux f t.root | some b => pure (some b) partial def foldlFromMAux (f : β → α → m β) : PersistentArrayNode α → USize → USize → β → m β | node cs, i, shift, b => do let j := (div2Shift i shift).toNat; b ← foldlFromMAux (cs.get! j) (mod2Shift i shift) (shift - initShift) b; cs.foldlFromM (fun b c => foldlMAux f c b) b (j+1) | leaf vs, i, _, b => vs.foldlFromM f b i.toNat def foldlFromM (t : PersistentArray α) (f : β → α → m β) (b : β) (ini : Nat) : m β := if ini >= t.tailOff then t.tail.foldlFromM f b (ini - t.tailOff) else do b ← foldlFromMAux f t.root (USize.ofNat ini) t.shift b; t.tail.foldlM f b @[specialize] partial def forMAux (f : α → m PUnit) : PersistentArrayNode α → m PUnit | node cs => cs.forM (fun c => forMAux c) | leaf vs => vs.forM f @[specialize] def forM (t : PersistentArray α) (f : α → m PUnit) : m PUnit := forMAux f t.root *> t.tail.forM f end @[inline] def foldl {β} (t : PersistentArray α) (f : β → α → β) (b : β) : β := Id.run (t.foldlM f b) def toArray (t : PersistentArray α) : Array α := t.foldl Array.push #[] def append (t₁ t₂ : PersistentArray α) : PersistentArray α := if t₁.isEmpty then t₂ else t₂.foldl PersistentArray.push t₁ instance : HasAppend (PersistentArray α) := ⟨append⟩ @[inline] def findSome? {β} (t : PersistentArray α) (f : α → (Option β)) : Option β := Id.run (t.findSomeM? f) @[inline] def findSomeRev? {β} (t : PersistentArray α) (f : α → (Option β)) : Option β := Id.run (t.findSomeRevM? f) @[inline] def foldlFrom {β} (t : PersistentArray α) (f : β → α → β) (b : β) (ini : Nat) : β := Id.run (t.foldlFromM f b ini) def toList (t : PersistentArray α) : List α := (t.foldl (fun xs x => x :: xs) []).reverse section variables {m : Type → Type w} [Monad m] @[specialize] partial def anyMAux (p : α → m Bool) : PersistentArrayNode α → m Bool | node cs => cs.anyM (fun c => anyMAux c) | leaf vs => vs.anyM p @[specialize] def anyM (t : PersistentArray α) (p : α → m Bool) : m Bool := anyMAux p t.root <||> t.tail.anyM p @[inline] def allM (a : PersistentArray α) (p : α → m Bool) : m Bool := do b ← anyM a (fun v => do b ← p v; pure (not b)); pure (not b) end @[inline] def any (a : PersistentArray α) (p : α → Bool) : Bool := Id.run $ anyM a p @[inline] def all (a : PersistentArray α) (p : α → Bool) : Bool := !any a (fun v => !p v) section variables {m : Type u → Type v} [Monad m] variable {β : Type u} @[specialize] partial def mapMAux (f : α → m β) : PersistentArrayNode α → m (PersistentArrayNode β) | node cs => node <$> cs.mapM (fun c => mapMAux c) | leaf vs => leaf <$> vs.mapM f @[specialize] def mapM (f : α → m β) (t : PersistentArray α) : m (PersistentArray β) := do root ← mapMAux f t.root; tail ← t.tail.mapM f; pure { t with tail := tail, root := root } end @[inline] def map {β} (f : α → β) (t : PersistentArray α) : PersistentArray β := Id.run (t.mapM f) structure Stats := (numNodes : Nat) (depth : Nat) (tailSize : Nat) partial def collectStats : PersistentArrayNode α → Stats → Nat → Stats | node cs, s, d => cs.foldl (fun s c => collectStats c s (d+1)) { s with numNodes := s.numNodes + 1, depth := Nat.max d s.depth } | leaf vs, s, d => { s with numNodes := s.numNodes + 1, depth := Nat.max d s.depth } def stats (r : PersistentArray α) : Stats := collectStats r.root { numNodes := 0, depth := 0, tailSize := r.tail.size } 0 def Stats.toString (s : Stats) : String := "{nodes := " ++ toString s.numNodes ++ ", depth := " ++ toString s.depth ++ ", tail size := " ++ toString s.tailSize ++ "}" instance : HasToString Stats := ⟨Stats.toString⟩ end PersistentArray def mkPersistentArray {α : Type u} (n : Nat) (v : α) : PArray α := n.fold (fun i p => p.push v) PersistentArray.empty @[inline] def mkPArray {α : Type u} (n : Nat) (v : α) : PArray α := mkPersistentArray n v end Std open Std (PersistentArray PersistentArray.empty) def List.toPersistentArrayAux {α : Type u} : List α → PersistentArray α → PersistentArray α | [], t => t | x::xs, t => List.toPersistentArrayAux xs (t.push x) def List.toPersistentArray {α : Type u} (xs : List α) : PersistentArray α := xs.toPersistentArrayAux {} def Array.toPersistentArray {α : Type u} (xs : Array α) : PersistentArray α := xs.foldl (fun p x => p.push x) PersistentArray.empty @[inline] def Array.toPArray {α : Type u} (xs : Array α) : PersistentArray α := xs.toPersistentArray
5062e47fdb19627f1b49126c71b0731be08a8cf0
5e0079f8e656a92238b64a952c7c0b202e6846ba
/src/export_json.lean
799ee28131380a6064e540944927cdacdee43110
[]
no_license
alexpeattie/doc-gen
e2083e13e92ecba0dc9d3aa703939de95f4fb999
742595863606f501dc93deddfa2b683902034720
refs/heads/master
1,671,958,354,503
1,598,970,982,000
1,598,970,982,000
295,526,651
0
0
null
1,600,114,057,000
1,600,114,056,000
null
UTF-8
Lean
false
false
16,206
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import tactic.core system.io data.string.defs tactic.interactive data.list.sort import all /-! Used to generate a json file for html docs. The json file is a list of maps, where each map has the structure ```typescript interface DeclInfo { name: string; args: efmt[]; type: efmt; doc_string: string; filename: string; line: int; attributes: string[]; equations: efmt[]; kind: string; structure_fields: [string, efmt][]; constructors: [string, efmt][]; } ``` Where efmt is defined as follows ('c' is a concatenation, 'n' is nesting): ```typescript type efmt = ['c', efmt, efmt] | ['n', efmt] | string; ``` Include this file somewhere in mathlib, e.g. in the `scripts` directory. Make sure mathlib is precompiled, with `all.lean` generated by `mk_all.sh`. Usage: `lean --run export_json.lean` creates `json_export.txt` in the current directory. -/ open tactic io io.fs native set_option pp.generalized_field_notation true meta def string.is_whitespace (s : string) : bool := s.fold tt (λ a b, a && b.is_whitespace) meta def string.has_whitespace (s : string) : bool := s.fold ff (λ a b, a || b.is_whitespace) meta inductive efmt | compose (a b : efmt) | of_string (s : string) | nest (f : efmt) namespace efmt meta instance : has_append efmt := ⟨compose⟩ meta instance : has_coe string efmt := ⟨of_string⟩ meta instance coe_format : has_coe format efmt := ⟨of_string ∘ format.to_string⟩ meta def to_json : efmt → format | (compose a b) := format!"[\"c\",{a.to_json},{b.to_json}]" | (of_string f) := repr f | (nest f) := format!"[\"n\",{f.to_json}]" meta def compose' : efmt → efmt → efmt | (of_string a) (of_string b) := of_string (a ++ b) | (of_string a) (compose (of_string b) c) := of_string (a ++ b) ++ c | (compose a (of_string b)) (of_string c) := a ++ of_string (b ++ c) | a b := compose a b meta def of_eformat : eformat → efmt | (tagged_format.group g) := of_eformat g | (tagged_format.nest i g) := of_eformat g | (tagged_format.tag _ g) := nest (of_eformat g) | (tagged_format.highlight _ g) := of_eformat g | (tagged_format.compose a b) := compose (of_eformat a) (of_eformat b) | (tagged_format.of_format f) := of_string f.to_string meta def sink_lparens_core : list string → efmt → efmt | ps (of_string a) := of_string $ string.join (a :: ps : list string).reverse | ps (compose (compose a b) c) := sink_lparens_core ps (compose a (compose b c)) | ps (compose (of_string "") a) := sink_lparens_core ps a | ps (compose (of_string a) b) := if a = "[" ∨ a = "(" ∨ a = "{" then sink_lparens_core (a :: ps) b else compose (sink_lparens_core ps (of_string a)) (sink_lparens_core [] b) | ps (compose a b) := compose (sink_lparens_core ps a) (sink_lparens_core [] b) | ps (nest a) := nest $ sink_lparens_core ps a meta def sink_rparens_core : efmt → list string → efmt | (of_string a) ps := of_string $ ps.foldl (++) a | (compose a (compose b c)) ps := sink_rparens_core (compose (compose a b) c) ps | (compose a (of_string "")) ps := sink_rparens_core a ps | (compose a (of_string b)) ps := if b = "]" ∨ b = ")" ∨ b = "}" then sink_rparens_core a (b :: ps) else compose (sink_rparens_core a []) (sink_rparens_core (of_string b) ps) | (compose a b) ps := compose (sink_rparens_core a []) (sink_rparens_core b ps) | (nest a) ps := nest $ sink_rparens_core a ps meta def sink_parens (e : efmt) : efmt := sink_lparens_core [] $ sink_rparens_core e [] meta def simplify : efmt → efmt | (compose a b) := compose' (simplify a) (simplify b) | (nest (nest a)) := simplify $ nest a | (nest a) := match simplify a with | of_string a := if a.has_whitespace then nest (of_string a) else of_string a | a := nest a end | (of_string a) := of_string a meta def pp (e : expr) : tactic efmt := (simplify ∘ sink_parens ∘ of_eformat) <$> pp_tagged e end efmt /-- The information collected from each declaration -/ meta structure decl_info := (name : name) (is_meta : bool) (args : list (bool × efmt)) -- tt means implicit (type : efmt) (doc_string : option string) (filename : string) (line : ℕ) (attributes : list string) -- not all attributes, we have a hardcoded list to check (equations : list efmt) (kind : string) -- def, thm, cnst, ax (structure_fields : list (string × efmt)) -- name and type of fields of a constructor (constructors : list (string × efmt)) -- name and type of constructors of an inductive type structure module_doc_info := (filename : string) (line : ℕ) (content : string) section set_option old_structure_cmd true structure ext_tactic_doc_entry extends tactic_doc_entry := (imported : string) meta def escape_name : name → string := repr ∘ to_string meta def ext_tactic_doc_entry.to_string : ext_tactic_doc_entry → string | ⟨name, category, decl_names, tags, description, _, imported⟩ := let decl_names := decl_names.map escape_name, tags := tags.map repr in "{" ++ to_string (format!"\"name\": {repr name}, \"category\": \"{category}\", \"decl_names\":{decl_names}, \"tags\": {tags}, \"description\": {repr description}, \"import\": {repr imported}") ++ "}" end meta def print_arg : bool × efmt → string | (b, s) := let bstr := if b then "true" else "false" in "{" ++ (to_string $ format!"\"arg\":{s.to_json}, \"implicit\":{bstr}") ++ "}" meta def decl_info.to_format : decl_info → format | ⟨name, is_meta, args, type, doc_string, filename, line, attributes, equations, kind, structure_fields, constructors⟩ := let doc_string := doc_string.get_or_else "", is_meta := if is_meta then "true" else "false", args := args.map print_arg, attributes := attributes.map repr, equations := equations.map efmt.to_json, structure_fields := structure_fields.map (λ ⟨n, t⟩, format!"[{escape_name n}, {t.to_json}]"), constructors := constructors.map (λ ⟨n, t⟩, format!"[{escape_name n}, {t.to_json}]") in "{" ++ format!"\"name\":{escape_name name}, \"is_meta\":{is_meta}, \"args\":{args}, \"type\":{type.to_json}, \"doc_string\":{repr doc_string}, " ++ format!"\"filename\":\"{filename}\",\"line\":{line}, \"attributes\":{attributes}, \"equations\":{equations}, " ++ format!" \"kind\":{repr kind}, \"structure_fields\":{structure_fields}, \"constructors\":{constructors}" ++ "}" section open tactic.interactive -- tt means implicit meta def format_binders (ns : list name) (bi : binder_info) (t : expr) : tactic (bool × efmt) := do t' ← efmt.pp t, let use_instance_style : bool := ns.length = 1 ∧ "_".is_prefix_of ns.head.to_string ∧ bi = binder_info.inst_implicit, let t' := if use_instance_style then t' else format_names ns ++ " : " ++ t', let brackets : string × string := match bi with | binder_info.default := ("(", ")") | binder_info.implicit := ("{", "}") | binder_info.strict_implicit := ("⦃", "⦄") | binder_info.inst_implicit := ("[", "]") | binder_info.aux_decl := ("(", ")") -- TODO: is this correct? end, pure $ prod.mk (bi ≠ binder_info.default : bool) $ (brackets.1 : efmt) ++ t' ++ brackets.2 meta def binder_info.is_inst_implicit : binder_info → bool | binder_info.inst_implicit := tt | _ := ff meta def count_named_intros : expr → tactic ℕ | e@(expr.pi _ bi _ _) := do ([_], b) ← open_n_pis e 1, v ← count_named_intros b, return $ if v = 0 ∧ e.is_arrow ∧ ¬ bi.is_inst_implicit then v else v + 1 | _ := return 0 /- meta def count_named_intros : expr → ℕ | e@(expr.pi _ _ _ b) := let v := count_named_intros b in if v = 0 ∧ e.is_arrow then v else v + 1 | _ := 0 -/ -- tt means implicit meta def get_args_and_type (e : expr) : tactic (list (bool × efmt) × efmt) := prod.fst <$> solve_aux e ( do count_named_intros e >>= intron, cxt ← local_context >>= tactic.interactive.compact_decl, cxt' ← cxt.mmap (λ t, do ft ← format_binders t.1 t.2.1 t.2.2, return (ft.1, ft.2)), tgt ← target >>= efmt.pp, return (cxt', tgt)) end /-- The attributes we check for -/ meta def attribute_list := [`simp, `squash_cast, `move_cast, `elim_cast, `nolint, `ext, `instance, `class] meta def attributes_of (n : name) : tactic (list string) := list.map to_string <$> attribute_list.mfilter (λ attr, succeeds $ has_attribute attr n) meta def declaration.kind : declaration → string | (declaration.defn a a_1 a_2 a_3 a_4 a_5) := "def" | (declaration.thm a a_1 a_2 a_3) := "thm" | (declaration.cnst a a_1 a_2 a_3) := "cnst" | (declaration.ax a a_1 a_2) := "ax" -- does this not exist already? I'm confused. meta def expr.instantiate_pis : list expr → expr → expr | (e'::es) (expr.pi n bi t e) := expr.instantiate_pis es (e.instantiate_var e') | _ e := e meta def enable_links : tactic unit := do o ← get_options, set_options $ o.set_bool `pp.links tt -- assumes proj_name exists meta def get_proj_type (struct_name proj_name : name) : tactic efmt := do (locs, _) ← mk_const struct_name >>= infer_type >>= mk_local_pis, proj_tp ← mk_const proj_name >>= infer_type, (_, t) ← open_n_pis (proj_tp.instantiate_pis locs) 1, efmt.pp t meta def mk_structure_fields (decl : name) (e : environment) : tactic (list (string × efmt)) := match e.is_structure decl, e.structure_fields_full decl with | tt, some proj_names := proj_names.mmap $ λ n, do tp ← get_proj_type decl n, return (to_string n, tp) | _, _ := return [] end -- this is used as a hack in get_constructor_type to avoid printing `Type ?`. meta def mk_const_with_params (d : declaration) : expr := let lvls := d.univ_params.map level.param in expr.const d.to_name lvls meta def get_constructor_type (type_name constructor_name : name) : tactic efmt := do d ← get_decl type_name, (locs, _) ← infer_type (mk_const_with_params d) >>= mk_local_pis, env ← get_env, let locs := locs.take (env.inductive_num_params type_name), proj_tp ← mk_const constructor_name >>= infer_type, do t ← pis locs (proj_tp.instantiate_pis locs), --.abstract_locals (locs.map expr.local_uniq_name), efmt.pp t meta def mk_constructors (decl : name) (e : environment): tactic (list (string × efmt)) := if (¬ e.is_inductive decl) ∨ (e.is_structure decl) then return [] else do d ← get_decl decl, ns ← get_constructors_for (mk_const_with_params d), ns.mmap $ λ n, do tp ← get_constructor_type decl n, return (to_string n, tp) meta def get_equations (decl : name) : tactic (list efmt) := do ns ← get_eqn_lemmas_for tt decl, ns.mmap $ λ n, do d ← get_decl n, (_, ty) ← mk_local_pis d.type, efmt.pp ty /-- extracts `decl_info` from `d`. Should return `none` instead of failing. -/ meta def process_decl (d : declaration) : tactic (option decl_info) := do ff ← d.in_current_file | return none, e ← get_env, let decl_name := d.to_name, if decl_name.is_internal ∨ d.is_auto_generated e then return none else do some filename ← return (e.decl_olean decl_name) | return none, some ⟨line, _⟩ ← return (e.decl_pos decl_name) | return none, doc_string ← (some <$> doc_string decl_name) <|> return none, (args, type) ← get_args_and_type d.type, attributes ← attributes_of decl_name, equations ← get_equations decl_name, structure_fields ← mk_structure_fields decl_name e, constructors ← mk_constructors decl_name e, return $ some ⟨decl_name, !d.is_trusted, args, type, doc_string, filename, line, attributes, equations, d.kind, structure_fields, constructors⟩ meta def run_on_dcl_list (e : environment) (ens : list name) (handle : handle) (is_first : bool) : io unit := ens.mfoldl (λ is_first d_name, do d ← run_tactic (e.get d_name), odi ← run_tactic (enable_links >> process_decl d), match odi with | some di := do when (bnot is_first) (put_str_ln handle ","), put_str_ln handle $ to_string di.to_format, return ff | none := return is_first end) is_first >> return () meta def itersplit {α} : list α → ℕ → list (list α) | l 0 := [l] | l 1 := let (l1, l2) := l.split in [l1, l2] | l (k+2) := let (l1, l2) := l.split in itersplit l1 (k+1) ++ itersplit l2 (k+1) meta def write_module_doc_pair : pos × string → string | (⟨line, _⟩, doc) := "{\"line\":" ++ to_string line ++ ", \"doc\" :" ++ repr doc ++ "}" meta def write_olean_docs : tactic (list string) := do docs ← olean_doc_strings, return (docs.foldl (λ rest p, match p with | (none, _) := rest | (_, []) := rest | (some filename, l) := let new := "\"" ++ filename ++ "\":" ++ to_string (l.map write_module_doc_pair) in new::rest end) []) meta def get_instances : tactic (rb_lmap string string) := attribute.get_instances `instance >>= list.mfoldl (λ map inst_nm, do (_, e) ← mk_const inst_nm >>= infer_type >>= mk_local_pis, (expr.const class_nm _) ← return e.get_app_fn, return $ map.insert class_nm.to_string inst_nm.to_string) mk_rb_map meta def format_instance_list : tactic string := do map ← get_instances, let lst := map.to_list.map (λ ⟨n, l⟩, to_string format!"\"{n}\" : {repr l}"), return $ "{" ++ (string.join (lst.intersperse ",")) ++ "}" meta def format_notes : tactic string := do l ← get_library_notes, let l := l.map $ λ ⟨l, r⟩, to_string $ format!"[{repr l}, {repr r}]", let l := string.join $ l.intersperse ", ", return $ to_string $ format!"[{l}]" meta def name.imported_by_tactic_basic (decl_name : name) : bool := let env := environment.from_imported_module_name `tactic.basic in env.contains decl_name meta def name.imported_by_tactic_default (decl_name : name) : bool := let env := environment.from_imported_module_name `tactic.default in env.contains decl_name meta def name.imported_always (decl_name : name) : bool := let env := environment.from_imported_module_name `system.random in env.contains decl_name meta def tactic_doc_entry.add_import : tactic_doc_entry → ext_tactic_doc_entry | ⟨name, category, [], tags, description, idf⟩ := ⟨name, category, [], tags, description, idf, ""⟩ | ⟨name, category, rel_decls@(decl_name::_), tags, description, idf⟩ := let imported := if decl_name.imported_always then "always imported" else if decl_name.imported_by_tactic_basic then "tactic.basic" else if decl_name.imported_by_tactic_default then "tactic" else "" in ⟨name, category, rel_decls, tags, description, idf, imported⟩ meta def format_tactic_docs : tactic string := do l ← list.map tactic_doc_entry.add_import <$> get_tactic_doc_entries, return $ to_string $ l.map ext_tactic_doc_entry.to_string /-- Using `environment.mfold` is much cleaner. Unfortunately this led to a segfault, I think because of a stack overflow. Converting the environment to a list of declarations and folding over that led to "deep recursion detected". Instead, we split that list into 8 smaller lists and process them one by one. More investigation is needed. -/ meta def export_json (filename : string) : io unit := do handle ← mk_file_handle filename mode.write, put_str_ln handle "{ \"decls\":[", e ← run_tactic get_env, let ens := environment.get_decl_names e, let enss := itersplit ens 4, enss.mfoldl (λ is_first l, do run_on_dcl_list e l handle is_first, return ff) tt, put_str_ln handle "],", ods ← run_tactic write_olean_docs, put_str_ln handle $ "\"mod_docs\": {" ++ string.join (ods.intersperse ",\n") ++ "},", notes ← run_tactic format_notes, put_str_ln handle $ "\"notes\": " ++ notes ++ ",", tactic_docs ← run_tactic format_tactic_docs, put_str_ln handle $ "\"tactic_docs\": " ++ tactic_docs ++ ",", instl ← run_tactic format_instance_list, put_str_ln handle $ "\"instances\": " ++ instl ++ "}", close handle meta def main : io unit := export_json "json_export.txt" -- HACK: print gadgets with less fluff notation x ` := `:10 y := opt_param x y -- HACKIER: print last component of name as string (because we can't do any better...) notation x ` . `:10 y := auto_param x (name.mk_string y _)
e01890a56822887d7f50a54962390e6e0a30acd9
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Lean/KeyedDeclsAttribute.lean
6b8921d02576b882a942fe8d4badb40d989c73c7
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
6,053
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.Attributes import Lean.Compiler.InitAttr import Lean.ToExpr import Lean.ScopedEnvExtension /-! A builder for attributes that are applied to declarations of a common type and group them by the given attribute argument (an arbitrary `Name`, currently). Also creates a second "builtin" attribute used for bootstrapping, which saves the applied declarations in an `IO.Ref` instead of an environment extension. Used to register elaborators, macros, tactics, and delaborators. -/ namespace Lean namespace KeyedDeclsAttribute -- could be a parameter as well, but right now it's all names abbrev Key := Name /-- `KeyedDeclsAttribute` definition. Important: `mkConst valueTypeName` and `γ` must be definitionally equal. -/ structure Def (γ : Type) where builtinName : Name := Name.anonymous -- Builtin attribute name, if any (e.g., `builtinTermElab) name : Name -- Attribute name (e.g., `termElab) descr : String -- Attribute description valueTypeName : Name -- Convert `Syntax` into a `Key`, the default implementation expects an identifier. evalKey : Bool → Syntax → AttrM Key := fun builtin stx => Attribute.Builtin.getId stx deriving Inhabited structure OLeanEntry where key : Key decl : Name -- Name of a declaration stored in the environment which has type `mkConst Def.valueTypeName`. deriving Inhabited structure AttributeEntry (γ : Type) extends OLeanEntry where /- Recall that we cannot store `γ` into .olean files because it is a closure. Given `OLeanEntry.decl`, we convert it into a `γ` by using the unsafe function `evalConstCheck`. -/ value : γ abbrev Table (γ : Type) := SMap Key (List γ) structure ExtensionState (γ : Type) where newEntries : List OLeanEntry := [] table : Table γ := {} deriving Inhabited abbrev Extension (γ : Type) := ScopedEnvExtension OLeanEntry (AttributeEntry γ) (ExtensionState γ) end KeyedDeclsAttribute structure KeyedDeclsAttribute (γ : Type) where defn : KeyedDeclsAttribute.Def γ -- imported/builtin instances tableRef : IO.Ref (KeyedDeclsAttribute.Table γ) -- instances from current module ext : KeyedDeclsAttribute.Extension γ deriving Inhabited namespace KeyedDeclsAttribute def Table.insert {γ : Type} (table : Table γ) (k : Key) (v : γ) : Table γ := match table.find? k with | some vs => SMap.insert table k (v::vs) | none => SMap.insert table k [v] def addBuiltin {γ} (attr : KeyedDeclsAttribute γ) (key : Key) (val : γ) : IO Unit := attr.tableRef.modify fun m => m.insert key val /-- def _regBuiltin$(declName) : IO Unit := @addBuiltin $(mkConst valueTypeName) $(mkConst attrDeclName) $(key) $(mkConst declName) -/ def declareBuiltin {γ} (df : Def γ) (attrDeclName : Name) (env : Environment) (key : Key) (declName : Name) : IO Environment := let name := `_regBuiltin ++ declName let type := mkApp (mkConst `IO) (mkConst `Unit) let val := mkAppN (mkConst `Lean.KeyedDeclsAttribute.addBuiltin) #[mkConst df.valueTypeName, mkConst attrDeclName, toExpr key, mkConst declName] let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := val, hints := ReducibilityHints.opaque, safety := DefinitionSafety.safe } match env.addAndCompile {} decl with -- TODO: pretty print error | Except.error e => do let msg ← (e.toMessageData {}).toString throw (IO.userError s!"failed to emit registration code for builtin '{declName}': {msg}") | Except.ok env => IO.ofExcept (setBuiltinInitAttr env name) protected unsafe def init {γ} (df : Def γ) (attrDeclName : Name) : IO (KeyedDeclsAttribute γ) := do let tableRef ← IO.mkRef ({} : Table γ) let ext : Extension γ ← registerScopedEnvExtension { name := df.name mkInitial := do return { table := (← tableRef.get) } ofOLeanEntry := fun s entry => do let ctx ← read match ctx.env.evalConstCheck γ ctx.opts df.valueTypeName entry.decl with | Except.ok f => return { toOLeanEntry := entry, value := f } | Except.error ex => throw (IO.userError ex) addEntry := fun s e => { table := s.table.insert e.key e.value, newEntries := e.toOLeanEntry :: s.newEntries } toOLeanEntry := (·.toOLeanEntry) } unless df.builtinName.isAnonymous do registerBuiltinAttribute { name := df.builtinName, descr := "(builtin) " ++ df.descr, add := fun declName stx kind => do unless kind == AttributeKind.global do throwError "invalid attribute '{df.builtinName}', must be global" let key ← df.evalKey true stx let decl ← getConstInfo declName match decl.type with | Expr.const c _ _ => if c != df.valueTypeName then throwError "unexpected type at '{declName}', '{df.valueTypeName}' expected" else let env ← getEnv let env ← declareBuiltin df attrDeclName env key declName setEnv env | _ => throwError "unexpected type at '{declName}', '{df.valueTypeName}' expected", applicationTime := AttributeApplicationTime.afterCompilation } registerBuiltinAttribute { name := df.name descr := df.descr add := fun constName stx attrKind => do let key ← df.evalKey false stx let val ← evalConstCheck γ df.valueTypeName constName ext.add { key := key, decl := constName, value := val } attrKind applicationTime := AttributeApplicationTime.afterCompilation } pure { defn := df, tableRef := tableRef, ext := ext } /-- Retrieve values tagged with `[attr key]` or `[builtinAttr key]`. -/ def getValues {γ} (attr : KeyedDeclsAttribute γ) (env : Environment) (key : Name) : List γ := (attr.ext.getState env).table.findD key [] end KeyedDeclsAttribute end Lean
6e5c568b55fbe0e324ee9493c47174713282893e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/std_basis.lean
56f2224deb91ed18f736bcdc57a86d806a5d7c4a
[ "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,989
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.matrix.basis import linear_algebra.basis import linear_algebra.pi /-! # The standard basis > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the standard basis `pi.basis (s : ∀ j, basis (ι j) R (M j))`, which is the `Σ j, ι j`-indexed basis of `Π j, M j`. The basis vectors are given by `pi.basis s ⟨j, i⟩ j' = linear_map.std_basis R M j' (s j) i = if j = j' then s i else 0`. The standard basis on `R^η`, i.e. `η → R` is called `pi.basis_fun`. To give a concrete example, `linear_map.std_basis R (λ (i : fin 3), R) i 1` gives the `i`th unit basis vector in `R³`, and `pi.basis_fun R (fin 3)` proves this is a basis over `fin 3 → R`. ## Main definitions - `linear_map.std_basis R M`: if `x` is a basis vector of `M i`, then `linear_map.std_basis R M i x` is the `i`th standard basis vector of `Π i, M i`. - `pi.basis s`: given a basis `s i` for each `M i`, the standard basis on `Π i, M i` - `pi.basis_fun R η`: the standard basis on `R^η`, i.e. `η → R`, given by `pi.basis_fun R η i j = if i = j then 1 else 0`. - `matrix.std_basis R n m`: the standard basis on `matrix n m R`, given by `matrix.std_basis R n m (i, j) i' j' = if (i, j) = (i', j') then 1 else 0`. -/ open function submodule open_locale big_operators namespace linear_map variables (R : Type*) {ι : Type*} [semiring R] (φ : ι → Type*) [Π i, add_comm_monoid (φ i)] [Π i, module R (φ i)] [decidable_eq ι] /-- The standard basis of the product of `φ`. -/ def std_basis : Π (i : ι), φ i →ₗ[R] (Πi, φ i) := single lemma std_basis_apply (i : ι) (b : φ i) : std_basis R φ i b = update 0 i b := rfl @[simp] lemma std_basis_apply' (i i' : ι) : (std_basis R (λ (_x : ι), R) i) 1 i' = ite (i = i') 1 0 := begin rw [linear_map.std_basis_apply, function.update_apply, pi.zero_apply], congr' 1, rw [eq_iff_iff, eq_comm], end lemma coe_std_basis (i : ι) : ⇑(std_basis R φ i) = pi.single i := rfl @[simp] lemma std_basis_same (i : ι) (b : φ i) : std_basis R φ i b i = b := pi.single_eq_same i b lemma std_basis_ne (i j : ι) (h : j ≠ i) (b : φ i) : std_basis R φ i b j = 0 := pi.single_eq_of_ne h b lemma std_basis_eq_pi_diag (i : ι) : std_basis R φ i = pi (diag i) := begin ext x j, convert (update_apply 0 x i j _).symm, refl, end lemma ker_std_basis (i : ι) : ker (std_basis R φ i) = ⊥ := ker_eq_bot_of_injective $ pi.single_injective _ _ lemma proj_comp_std_basis (i j : ι) : (proj i).comp (std_basis R φ j) = diag j i := by rw [std_basis_eq_pi_diag, proj_pi] lemma proj_std_basis_same (i : ι) : (proj i).comp (std_basis R φ i) = id := linear_map.ext $ std_basis_same R φ i lemma proj_std_basis_ne (i j : ι) (h : i ≠ j) : (proj i).comp (std_basis R φ j) = 0 := linear_map.ext $ std_basis_ne R φ _ _ h lemma supr_range_std_basis_le_infi_ker_proj (I J : set ι) (h : disjoint I J) : (⨆i∈I, range (std_basis R φ i)) ≤ (⨅i∈J, ker (proj i : (Πi, φ i) →ₗ[R] φ i)) := begin refine (supr_le $ λ i, supr_le $ λ hi, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, set_like.le_def, mem_ker, comap_infi, mem_infi], rintro b - j hj, rw [proj_std_basis_ne R φ j i, zero_apply], rintro rfl, exact h.le_bot ⟨hi, hj⟩ end lemma infi_ker_proj_le_supr_range_std_basis {I : finset ι} {J : set ι} (hu : set.univ ⊆ ↑I ∪ J) : (⨅ i∈J, ker (proj i : (Πi, φ i) →ₗ[R] φ i)) ≤ (⨆i∈I, range (std_basis R φ i)) := set_like.le_def.2 begin assume b hb, simp only [mem_infi, mem_ker, proj_apply] at hb, rw ← show ∑ i in I, std_basis R φ i (b i) = b, { ext i, rw [finset.sum_apply, ← std_basis_same R φ i (b i)], refine finset.sum_eq_single i (assume j hjI ne, std_basis_ne _ _ _ _ ne.symm _) _, assume hiI, rw [std_basis_same], exact hb _ ((hu trivial).resolve_left hiI) }, exact sum_mem_bsupr (λ i hi, mem_range_self (std_basis R φ i) (b i)) end lemma supr_range_std_basis_eq_infi_ker_proj {I J : set ι} (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) (hI : set.finite I) : (⨆i∈I, range (std_basis R φ i)) = (⨅i∈J, ker (proj i : (Πi, φ i) →ₗ[R] φ i)) := begin refine le_antisymm (supr_range_std_basis_le_infi_ker_proj _ _ _ _ hd) _, have : set.univ ⊆ ↑hI.to_finset ∪ J, { rwa [hI.coe_to_finset] }, refine le_trans (infi_ker_proj_le_supr_range_std_basis R φ this) (supr_mono $ assume i, _), rw [set.finite.mem_to_finset], exact le_rfl end lemma supr_range_std_basis [finite ι] : (⨆ i, range (std_basis R φ i)) = ⊤ := begin casesI nonempty_fintype ι, convert top_unique (infi_emptyset.ge.trans $ infi_ker_proj_le_supr_range_std_basis R φ _), { exact funext (λ i, (@supr_pos _ _ _ (λ h, range $ std_basis R φ i) $ finset.mem_univ i).symm) }, { rw [finset.coe_univ, set.union_empty] } end lemma disjoint_std_basis_std_basis (I J : set ι) (h : disjoint I J) : disjoint (⨆i∈I, range (std_basis R φ i)) (⨆i∈J, range (std_basis R φ i)) := begin refine disjoint.mono (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ disjoint_compl_right) (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ disjoint_compl_right) _, simp only [disjoint_iff_inf_le, set_like.le_def, mem_infi, mem_inf, mem_ker, mem_bot, proj_apply, funext_iff], rintros b ⟨hI, hJ⟩ i, classical, by_cases hiI : i ∈ I, { by_cases hiJ : i ∈ J, { exact (h.le_bot ⟨hiI, hiJ⟩).elim }, { exact hJ i hiJ } }, { exact hI i hiI } end lemma std_basis_eq_single {a : R} : (λ (i : ι), (std_basis R (λ _ : ι, R) i) a) = λ (i : ι), (finsupp.single i a) := funext $ λ i, (finsupp.single_eq_pi_single i a).symm end linear_map namespace pi open linear_map open set variables {R : Type*} section module variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*} lemma linear_independent_std_basis [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)] [decidable_eq η] (v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) : linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) := begin have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)), { intro j, exact (hs j).map' _ (ker_std_basis _ _ _) }, apply linear_independent_Union_finite hs', { assume j J _ hiJ, simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union], have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ range (std_basis R Ms j), { intro j, rw [span_le, linear_map.range_coe], apply range_comp_subset_range }, have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ ⨆ i ∈ {j}, range (std_basis R Ms i), { rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)), apply h₀ }, have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤ ⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) := supr₂_mono (λ i _, h₀ i), have h₃ : disjoint (λ (i : η), i ∈ {j}) J, { convert set.disjoint_singleton_left.2 hiJ using 0 }, exact (disjoint_std_basis_std_basis _ _ _ _ h₃).mono h₁ h₂ } end variables [semiring R] [∀i, add_comm_monoid (Ms i)] [∀i, module R (Ms i)] variable [fintype η] section open linear_equiv /-- `pi.basis (s : ∀ j, basis (ιs j) R (Ms j))` is the `Σ j, ιs j`-indexed basis on `Π j, Ms j` given by `s j` on each component. For the standard basis over `R` on the finite-dimensional space `η → R` see `pi.basis_fun`. -/ protected noncomputable def basis (s : ∀ j, basis (ιs j) R (Ms j)) : basis (Σ j, ιs j) R (Π j, Ms j) := -- The `add_comm_monoid (Π j, Ms j)` instance was hard to find. -- Defining this in tactic mode seems to shake up instance search enough that it works by itself. by { refine basis.of_repr (_ ≪≫ₗ (finsupp.sigma_finsupp_lequiv_pi_finsupp R).symm), exact linear_equiv.Pi_congr_right (λ j, (s j).repr) } @[simp] lemma basis_repr_std_basis [decidable_eq η] (s : ∀ j, basis (ιs j) R (Ms j)) (j i) : (pi.basis s).repr (std_basis R _ j (s j i)) = finsupp.single ⟨j, i⟩ 1 := begin ext ⟨j', i'⟩, by_cases hj : j = j', { subst hj, simp only [pi.basis, linear_equiv.trans_apply, basis.repr_self, std_basis_same, linear_equiv.Pi_congr_right_apply, finsupp.sigma_finsupp_lequiv_pi_finsupp_symm_apply], symmetry, exact finsupp.single_apply_left (λ i i' (h : (⟨j, i⟩ : Σ j, ιs j) = ⟨j, i'⟩), eq_of_heq (sigma.mk.inj h).2) _ _ _ }, simp only [pi.basis, linear_equiv.trans_apply, finsupp.sigma_finsupp_lequiv_pi_finsupp_symm_apply, linear_equiv.Pi_congr_right_apply], dsimp, rw [std_basis_ne _ _ _ _ (ne.symm hj), linear_equiv.map_zero, finsupp.zero_apply, finsupp.single_eq_of_ne], rintros ⟨⟩, contradiction end @[simp] lemma basis_apply [decidable_eq η] (s : ∀ j, basis (ιs j) R (Ms j)) (ji) : pi.basis s ji = std_basis R _ ji.1 (s ji.1 ji.2) := basis.apply_eq_iff.mpr (by simp) @[simp] lemma basis_repr (s : ∀ j, basis (ιs j) R (Ms j)) (x) (ji) : (pi.basis s).repr x ji = (s ji.1).repr (x ji.1) ji.2 := rfl end section variables (R η) /-- The basis on `η → R` where the `i`th basis vector is `function.update 0 i 1`. -/ noncomputable def basis_fun : basis η R (Π (j : η), R) := basis.of_equiv_fun (linear_equiv.refl _ _) @[simp] lemma basis_fun_apply [decidable_eq η] (i) : basis_fun R η i = std_basis R (λ (i : η), R) i 1 := by { simp only [basis_fun, basis.coe_of_equiv_fun, linear_equiv.refl_symm, linear_equiv.refl_apply, std_basis_apply] } @[simp] lemma basis_fun_repr (x : η → R) (i : η) : (pi.basis_fun R η).repr x i = x i := by simp [basis_fun] @[simp] lemma basis_fun_equiv_fun : (pi.basis_fun R η).equiv_fun = linear_equiv.refl _ _ := basis.equiv_fun_of_equiv_fun _ end end module end pi namespace matrix variables (R : Type*) (m n : Type*) [fintype m] [fintype n] [semiring R] /-- The standard basis of `matrix m n R`. -/ noncomputable def std_basis : basis (m × n) R (matrix m n R) := basis.reindex (pi.basis (λ (i : m), pi.basis_fun R n)) (equiv.sigma_equiv_prod _ _) variables {n m} lemma std_basis_eq_std_basis_matrix (i : n) (j : m) [decidable_eq n] [decidable_eq m] : std_basis R n m (i, j) = std_basis_matrix i j (1 : R) := begin ext a b, by_cases hi : i = a; by_cases hj : j = b, { simp [std_basis, hi, hj] }, { simp [std_basis, hi, hj, ne.symm hj, linear_map.std_basis_ne] }, { simp [std_basis, hi, hj, ne.symm hi, linear_map.std_basis_ne] }, { simp [std_basis, hi, hj, ne.symm hj, ne.symm hi, linear_map.std_basis_ne] } end end matrix
adaac8377378be99cea157b8737f622b6e4a94c7
82e44445c70db0f03e30d7be725775f122d72f3e
/src/ring_theory/jacobson.lean
7d89107f26f85e90b92004f41af270aa2efbc0f8
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
34,303
lean
/- Copyright (c) 2020 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Devon Tuma -/ import data.mv_polynomial import ring_theory.ideal.over import ring_theory.jacobson_ideal import ring_theory.localization /-! # Jacobson Rings The following conditions are equivalent for a ring `R`: 1. Every radical ideal `I` is equal to its Jacobson radical 2. Every radical ideal `I` can be written as an intersection of maximal ideals 3. Every prime ideal `I` is equal to its Jacobson radical Any ring satisfying any of these equivalent conditions is said to be Jacobson. Some particular examples of Jacobson rings are also proven. `is_jacobson_quotient` says that the quotient of a Jacobson ring is Jacobson. `is_jacobson_localization` says the localization of a Jacobson ring to a single element is Jacobson. `is_jacobson_polynomial_iff_is_jacobson` says polynomials over a Jacobson ring form a Jacobson ring. ## Main definitions Let `R` be a commutative ring. Jacobson Rings are defined using the first of the above conditions * `is_jacobson R` is the proposition that `R` is a Jacobson ring. It is a class, implemented as the predicate that for any ideal, `I.radical = I` implies `I.jacobson = I`. ## Main statements * `is_jacobson_iff_prime_eq` is the equivalence between conditions 1 and 3 above. * `is_jacobson_iff_Inf_maximal` is the equivalence between conditions 1 and 2 above. * `is_jacobson_of_surjective` says that if `R` is a Jacobson ring and `f : R →+* S` is surjective, then `S` is also a Jacobson ring * `is_jacobson_mv_polynomial` says that multi-variate polynomials over a Jacobson ring are Jacobson. ## Tags Jacobson, Jacobson Ring -/ namespace ideal open polynomial section is_jacobson variables {R S : Type*} [comm_ring R] [comm_ring S] {I : ideal R} /-- A ring is a Jacobson ring if for every radical ideal `I`, the Jacobson radical of `I` is equal to `I`. See `is_jacobson_iff_prime_eq` and `is_jacobson_iff_Inf_maximal` for equivalent definitions. -/ class is_jacobson (R : Type*) [comm_ring R] : Prop := (out' : ∀ (I : ideal R), I.radical = I → I.jacobson = I) theorem is_jacobson_iff {R} [comm_ring R] : is_jacobson R ↔ ∀ (I : ideal R), I.radical = I → I.jacobson = I := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem is_jacobson.out {R} [comm_ring R] : is_jacobson R → ∀ {I : ideal R}, I.radical = I → I.jacobson = I := is_jacobson_iff.1 /-- A ring is a Jacobson ring if and only if for all prime ideals `P`, the Jacobson radical of `P` is equal to `P`. -/ lemma is_jacobson_iff_prime_eq : is_jacobson R ↔ ∀ P : ideal R, is_prime P → P.jacobson = P := begin refine is_jacobson_iff.trans ⟨λ h I hI, h I (is_prime.radical hI), _⟩, refine λ h I hI, le_antisymm (λ x hx, _) (λ x hx, mem_Inf.mpr (λ _ hJ, hJ.left hx)), rw [← hI, radical_eq_Inf I, mem_Inf], intros P hP, rw set.mem_set_of_eq at hP, erw mem_Inf at hx, erw [← h P hP.right, mem_Inf], exact λ J hJ, hx ⟨le_trans hP.left hJ.left, hJ.right⟩ end /-- A ring `R` is Jacobson if and only if for every prime ideal `I`, `I` can be written as the infimum of some collection of maximal ideals. Allowing ⊤ in the set `M` of maximal ideals is equivalent, but makes some proofs cleaner. -/ lemma is_jacobson_iff_Inf_maximal : is_jacobson R ↔ ∀ {I : ideal R}, I.is_prime → ∃ M : set (ideal R), (∀ J ∈ M, is_maximal J ∨ J = ⊤) ∧ I = Inf M := ⟨λ H I h, eq_jacobson_iff_Inf_maximal.1 (H.out (is_prime.radical h)), λ H, is_jacobson_iff_prime_eq.2 (λ P hP, eq_jacobson_iff_Inf_maximal.2 (H hP))⟩ lemma is_jacobson_iff_Inf_maximal' : is_jacobson R ↔ ∀ {I : ideal R}, I.is_prime → ∃ M : set (ideal R), (∀ (J ∈ M) (K : ideal R), J < K → K = ⊤) ∧ I = Inf M := ⟨λ H I h, eq_jacobson_iff_Inf_maximal'.1 (H.out (is_prime.radical h)), λ H, is_jacobson_iff_prime_eq.2 (λ P hP, eq_jacobson_iff_Inf_maximal'.2 (H hP))⟩ lemma radical_eq_jacobson [H : is_jacobson R] (I : ideal R) : I.radical = I.jacobson := le_antisymm (le_Inf (λ J ⟨hJ, hJ_max⟩, (is_prime.radical_le_iff hJ_max.is_prime).mpr hJ)) ((H.out (radical_idem I)) ▸ (jacobson_mono le_radical)) /-- Fields have only two ideals, and the condition holds for both of them. -/ @[priority 100] instance is_jacobson_field {K : Type*} [field K] : is_jacobson K := ⟨λ I hI, or.rec_on (eq_bot_or_top I) (λ h, le_antisymm (Inf_le ⟨le_of_eq rfl, (eq.symm h) ▸ bot_is_maximal⟩) ((eq.symm h) ▸ bot_le)) (λ h, by rw [h, jacobson_eq_top_iff])⟩ theorem is_jacobson_of_surjective [H : is_jacobson R] : (∃ (f : R →+* S), function.surjective f) → is_jacobson S := begin rintros ⟨f, hf⟩, rw is_jacobson_iff_Inf_maximal, intros p hp, use map f '' {J : ideal R | comap f p ≤ J ∧ J.is_maximal }, use λ j ⟨J, hJ, hmap⟩, hmap ▸ or.symm (map_eq_top_or_is_maximal_of_surjective f hf hJ.right), have : p = map f ((comap f p).jacobson), from (is_jacobson.out' (comap f p) (by rw [← comap_radical, is_prime.radical hp])).symm ▸ (map_comap_of_surjective f hf p).symm, exact eq.trans this (map_Inf hf (λ J ⟨hJ, _⟩, le_trans (ideal.ker_le_comap f) hJ)), end @[priority 100] instance is_jacobson_quotient [is_jacobson R] : is_jacobson (quotient I) := is_jacobson_of_surjective ⟨quotient.mk I, (by rintro ⟨x⟩; use x; refl)⟩ lemma is_jacobson_iso (e : R ≃+* S) : is_jacobson R ↔ is_jacobson S := ⟨λ h, @is_jacobson_of_surjective _ _ _ _ h ⟨(e : R →+* S), e.surjective⟩, λ h, @is_jacobson_of_surjective _ _ _ _ h ⟨(e.symm : S →+* R), e.symm.surjective⟩⟩ lemma is_jacobson_of_is_integral [algebra R S] (hRS : algebra.is_integral R S) (hR : is_jacobson R) : is_jacobson S := begin rw is_jacobson_iff_prime_eq, introsI P hP, by_cases hP_top : comap (algebra_map R S) P = ⊤, { simp [comap_eq_top_iff.1 hP_top] }, { haveI : nontrivial (comap (algebra_map R S) P).quotient := quotient.nontrivial hP_top, rw jacobson_eq_iff_jacobson_quotient_eq_bot, refine eq_bot_of_comap_eq_bot (is_integral_quotient_of_is_integral hRS) _, rw [eq_bot_iff, ← jacobson_eq_iff_jacobson_quotient_eq_bot.1 ((is_jacobson_iff_prime_eq.1 hR) (comap (algebra_map R S) P) (comap_is_prime _ _)), comap_jacobson], refine Inf_le_Inf (λ J hJ, _), simp only [true_and, set.mem_image, bot_le, set.mem_set_of_eq], haveI : J.is_maximal := by simpa using hJ, exact exists_ideal_over_maximal_of_is_integral (is_integral_quotient_of_is_integral hRS) J (comap_bot_le_of_injective _ algebra_map_quotient_injective) } end lemma is_jacobson_of_is_integral' (f : R →+* S) (hf : f.is_integral) (hR : is_jacobson R) : is_jacobson S := @is_jacobson_of_is_integral _ _ _ _ f.to_algebra hf hR end is_jacobson section localization open is_localization submonoid variables {R S : Type*} [comm_ring R] [comm_ring S] {I : ideal R} variables (y : R) [algebra R S] [is_localization.away y S] lemma disjoint_powers_iff_not_mem (hI : I.radical = I) : disjoint ((submonoid.powers y) : set R) ↑I ↔ y ∉ I.1 := begin refine ⟨λ h, set.disjoint_left.1 h (mem_powers _), λ h, (disjoint_iff).mpr (eq_bot_iff.mpr _)⟩, rintros x ⟨⟨n, rfl⟩, hx'⟩, rw [← hI] at hx', exact absurd (hI ▸ mem_radical_of_pow_mem hx' : y ∈ I.carrier) h end variables (S) /-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y` correspond to maximal ideals in the original ring `R` that don't contain `y`. This lemma gives the correspondence in the particular case of an ideal and its comap. See `le_rel_iso_of_maximal` for the more general relation isomorphism -/ lemma is_maximal_iff_is_maximal_disjoint [H : is_jacobson R] (J : ideal S) : J.is_maximal ↔ (comap (algebra_map R S) J).is_maximal ∧ y ∉ ideal.comap (algebra_map R S) J := begin split, { refine λ h, ⟨_, λ hy, h.ne_top (ideal.eq_top_of_is_unit_mem _ hy (map_units _ ⟨y, submonoid.mem_powers _⟩))⟩, have hJ : J.is_prime := is_maximal.is_prime h, rw is_prime_iff_is_prime_disjoint (submonoid.powers y) at hJ, have : y ∉ (comap (algebra_map R S) J).1 := set.disjoint_left.1 hJ.right (submonoid.mem_powers _), erw [← H.out (is_prime.radical hJ.left), mem_Inf] at this, push_neg at this, rcases this with ⟨I, hI, hI'⟩, convert hI.right, by_cases hJ : J = map (algebra_map R S) I, { rw [hJ, comap_map_of_is_prime_disjoint (powers y) S I (is_maximal.is_prime hI.right)], rwa disjoint_powers_iff_not_mem y (is_maximal.is_prime hI.right).radical }, { have hI_p : (map (algebra_map R S) I).is_prime, { refine is_prime_of_is_prime_disjoint (powers y) _ I hI.right.is_prime _, rwa disjoint_powers_iff_not_mem y (is_maximal.is_prime hI.right).radical }, have : J ≤ map (algebra_map R S) I := (map_comap (submonoid.powers y) S J) ▸ (map_mono hI.left), exact absurd (h.1.2 _ (lt_of_le_of_ne this hJ)) hI_p.1 } }, { refine λ h, ⟨⟨λ hJ, h.1.ne_top (eq_top_iff.2 _), λ I hI, _⟩⟩, { rwa [eq_top_iff, ← (is_localization.order_embedding (powers y) S).le_iff_le] at hJ }, { have := congr_arg (map (algebra_map R S)) (h.1.1.2 _ ⟨comap_mono (le_of_lt hI), _⟩), rwa [map_comap (powers y) S I, map_top] at this, refine λ hI', hI.right _, rw [← map_comap (powers y) S I, ← map_comap (powers y) S J], exact map_mono hI' } } end variables {S} /-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y` correspond to maximal ideals in the original ring `R` that don't contain `y`. This lemma gives the correspondence in the particular case of an ideal and its map. See `le_rel_iso_of_maximal` for the more general statement, and the reverse of this implication -/ lemma is_maximal_of_is_maximal_disjoint [is_jacobson R] (I : ideal R) (hI : I.is_maximal) (hy : y ∉ I) : (map (algebra_map R S) I).is_maximal := begin rw [is_maximal_iff_is_maximal_disjoint S y, comap_map_of_is_prime_disjoint (powers y) S I (is_maximal.is_prime hI) ((disjoint_powers_iff_not_mem y (is_maximal.is_prime hI).radical).2 hy)], exact ⟨hI, hy⟩ end /-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y` correspond to maximal ideals in the original ring `R` that don't contain `y` -/ def order_iso_of_maximal [is_jacobson R] : {p : ideal S // p.is_maximal} ≃o {p : ideal R // p.is_maximal ∧ y ∉ p} := { to_fun := λ p, ⟨ideal.comap (algebra_map R S) p.1, (is_maximal_iff_is_maximal_disjoint S y p.1).1 p.2⟩, inv_fun := λ p, ⟨ideal.map (algebra_map R S) p.1, is_maximal_of_is_maximal_disjoint y p.1 p.2.1 p.2.2⟩, left_inv := λ J, subtype.eq (map_comap (powers y) S J), right_inv := λ I, subtype.eq (comap_map_of_is_prime_disjoint _ _ I.1 (is_maximal.is_prime I.2.1) ((disjoint_powers_iff_not_mem y I.2.1.is_prime.radical).2 I.2.2)), map_rel_iff' := λ I I', ⟨λ h, (show I.val ≤ I'.val, from (map_comap (powers y) S I.val) ▸ (map_comap (powers y) S I'.val) ▸ (ideal.map_mono h)), λ h x hx, h hx⟩ } include y /-- If `S` is the localization of the Jacobson ring `R` at the submonoid generated by `y : R`, then `S` is Jacobson. -/ lemma is_jacobson_localization [H : is_jacobson R] : is_jacobson S := begin rw is_jacobson_iff_prime_eq, refine λ P' hP', le_antisymm _ le_jacobson, obtain ⟨hP', hPM⟩ := (is_localization.is_prime_iff_is_prime_disjoint (powers y) S P').mp hP', have hP := H.out (is_prime.radical hP'), refine (le_of_eq (is_localization.map_comap (powers y) S P'.jacobson).symm).trans ((map_mono _).trans (le_of_eq (is_localization.map_comap (powers y) S P'))), have : Inf { I : ideal R | comap (algebra_map R S) P' ≤ I ∧ I.is_maximal ∧ y ∉ I } ≤ comap (algebra_map R S) P', { intros x hx, have hxy : x * y ∈ (comap (algebra_map R S) P').jacobson, { rw [ideal.jacobson, mem_Inf], intros J hJ, by_cases y ∈ J, { exact J.smul_mem x h }, { exact (mul_comm y x) ▸ J.smul_mem y ((mem_Inf.1 hx) ⟨hJ.left, ⟨hJ.right, h⟩⟩) } }, rw hP at hxy, cases hP'.mem_or_mem hxy with hxy hxy, { exact hxy }, { exact (hPM ⟨submonoid.mem_powers _, hxy⟩).elim } }, refine le_trans _ this, rw [ideal.jacobson, comap_Inf', Inf_eq_infi], refine infi_le_infi_of_subset (λ I hI, ⟨map (algebra_map R S) I, ⟨_, _⟩⟩), { exact ⟨le_trans (le_of_eq ((is_localization.map_comap (powers y) S P').symm)) (map_mono hI.1), is_maximal_of_is_maximal_disjoint y _ hI.2.1 hI.2.2⟩ }, { exact is_localization.comap_map_of_is_prime_disjoint _ S I (is_maximal.is_prime hI.2.1) ((disjoint_powers_iff_not_mem y hI.2.1.is_prime.radical).2 hI.2.2) } end end localization namespace polynomial open polynomial section comm_ring variables {R S : Type*} [comm_ring R] [integral_domain S] variables {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] /-- If `I` is a prime ideal of `polynomial R` and `pX ∈ I` is a non-constant polynomial, then the map `R →+* R[x]/I` descends to an integral map when localizing at `pX.leading_coeff`. In particular `X` is integral because it satisfies `pX`, and constants are trivially integral, so integrality of the entire extension follows by closure under addition and multiplication. -/ lemma is_integral_is_localization_polynomial_quotient (P : ideal (polynomial R)) [P.is_prime] (pX : polynomial R) (hpX : pX ∈ P) [algebra (P.comap (C : R →+* _)).quotient Rₘ] [is_localization.away (pX.map (quotient.mk (P.comap C))).leading_coeff Rₘ] [algebra P.quotient Sₘ] [is_localization ((submonoid.powers (pX.map (quotient.mk (P.comap C))).leading_coeff).map (quotient_map P C le_rfl) : submonoid P.quotient) Sₘ] : (is_localization.map Sₘ (quotient_map P C le_rfl) ((submonoid.powers (pX.map (quotient.mk (P.comap C))).leading_coeff).le_comap_map) : Rₘ →+* _) .is_integral := begin let P' : ideal R := P.comap C, let M : submonoid P'.quotient := submonoid.powers (pX.map (quotient.mk (P.comap C))).leading_coeff, let M' : submonoid P.quotient := (submonoid.powers (pX.map (quotient.mk (P.comap C))).leading_coeff).map (quotient_map P C le_rfl), let φ : P'.quotient →+* P.quotient := quotient_map P C le_rfl, let φ' := is_localization.map Sₘ φ M.le_comap_map, have hφ' : φ.comp (quotient.mk P') = (quotient.mk P).comp C := rfl, intro p, obtain ⟨⟨p', ⟨q, hq⟩⟩, hp⟩ := is_localization.surj M' p, suffices : φ'.is_integral_elem (algebra_map _ _ p'), { obtain ⟨q', hq', rfl⟩ := hq, obtain ⟨q'', hq''⟩ := is_unit_iff_exists_inv'.1 (is_localization.map_units Rₘ (⟨q', hq'⟩ : M)), refine φ'.is_integral_of_is_integral_mul_unit p (algebra_map _ _ (φ q')) q'' _ (hp.symm ▸ this), convert trans (trans (φ'.map_mul _ _).symm (congr_arg φ' hq'')) φ'.map_one using 2, rw [← φ'.comp_apply, is_localization.map_comp, ring_hom.comp_apply, subtype.coe_mk] }, refine is_integral_of_mem_closure'' (((algebra_map _ Sₘ).comp (quotient.mk P)) '' (insert X {p | p.degree ≤ 0})) _ _ _, { rintros x ⟨p, hp, rfl⟩, refine hp.rec_on (λ hy, _) (λ hy, _), { refine hy.symm ▸ (φ.is_integral_elem_localization_at_leading_coeff ((quotient.mk P) X) (pX.map (quotient.mk P')) _ M ⟨1, pow_one _⟩), rwa [eval₂_map, hφ', ← hom_eval₂, quotient.eq_zero_iff_mem, eval₂_C_X] }, { rw [set.mem_set_of_eq, degree_le_zero_iff] at hy, refine hy.symm ▸ ⟨X - C (algebra_map _ _ ((quotient.mk P') (p.coeff 0))), monic_X_sub_C _, _⟩, simp only [eval₂_sub, eval₂_C, eval₂_X], rw [sub_eq_zero, ← φ'.comp_apply, is_localization.map_comp], refl } }, { obtain ⟨p, rfl⟩ := quotient.mk_surjective p', refine polynomial.induction_on p (λ r, subring.subset_closure $ set.mem_image_of_mem _ (or.inr degree_C_le)) (λ _ _ h1 h2, _) (λ n _ hr, _), { convert subring.add_mem _ h1 h2, rw [ring_hom.map_add, ring_hom.map_add] }, { rw [pow_succ X n, mul_comm X, ← mul_assoc, ring_hom.map_mul, ring_hom.map_mul], exact subring.mul_mem _ hr (subring.subset_closure (set.mem_image_of_mem _ (or.inl rfl))) } }, end /-- If `f : R → S` descends to an integral map in the localization at `x`, and `R` is a Jacobson ring, then the intersection of all maximal ideals in `S` is trivial -/ lemma jacobson_bot_of_integral_localization {R : Type*} [integral_domain R] [is_jacobson R] (Rₘ Sₘ : Type*) [comm_ring Rₘ] [comm_ring Sₘ] (φ : R →+* S) (hφ : function.injective φ) (x : R) (hx : x ≠ 0) [algebra R Rₘ] [is_localization.away x Rₘ] [algebra S Sₘ] [is_localization ((submonoid.powers x).map φ : submonoid S) Sₘ] (hφ' : ring_hom.is_integral (is_localization.map Sₘ φ (submonoid.powers x).le_comap_map : Rₘ →+* Sₘ)) : (⊥ : ideal S).jacobson = (⊥ : ideal S) := begin have hM : ((submonoid.powers x).map φ : submonoid S) ≤ non_zero_divisors S := map_le_non_zero_divisors_of_injective hφ (powers_le_non_zero_divisors_of_domain hx), letI : integral_domain Sₘ := is_localization.integral_domain_of_le_non_zero_divisors _ hM, let φ' : Rₘ →+* Sₘ := is_localization.map _ φ (submonoid.powers x).le_comap_map, suffices : ∀ I : ideal Sₘ, I.is_maximal → (I.comap (algebra_map S Sₘ)).is_maximal, { have hϕ' : comap (algebra_map S Sₘ) (⊥ : ideal Sₘ) = (⊥ : ideal S), { rw [← ring_hom.ker_eq_comap_bot, ← ring_hom.injective_iff_ker_eq_bot], exact is_localization.injective Sₘ hM }, have hSₘ : is_jacobson Sₘ := is_jacobson_of_is_integral' φ' hφ' (is_jacobson_localization x), refine eq_bot_iff.mpr (le_trans _ (le_of_eq hϕ')), rw [← hSₘ.out radical_bot_of_integral_domain, comap_jacobson], exact Inf_le_Inf (λ j hj, ⟨bot_le, let ⟨J, hJ⟩ := hj in hJ.2 ▸ this J hJ.1.2⟩) }, introsI I hI, -- Remainder of the proof is pulling and pushing ideals around the square and the quotient square haveI : (I.comap (algebra_map S Sₘ)).is_prime := comap_is_prime _ I, haveI : (I.comap φ').is_prime := comap_is_prime φ' I, haveI : (⊥ : ideal (I.comap (algebra_map S Sₘ)).quotient).is_prime := bot_prime, have hcomm: φ'.comp (algebra_map R Rₘ) = (algebra_map S Sₘ).comp φ := is_localization.map_comp _, let f := quotient_map (I.comap (algebra_map S Sₘ)) φ le_rfl, let g := quotient_map I (algebra_map S Sₘ) le_rfl, have := is_maximal_comap_of_is_integral_of_is_maximal' φ' hφ' I (by convert hI; casesI _inst_4; refl), have := ((is_maximal_iff_is_maximal_disjoint Rₘ x _).1 this).left, have : ((I.comap (algebra_map S Sₘ)).comap φ).is_maximal, { rwa [comap_comap, hcomm, ← comap_comap] at this }, rw ← bot_quotient_is_maximal_iff at this ⊢, refine is_maximal_of_is_integral_of_is_maximal_comap' f _ ⊥ ((eq_bot_iff.2 (comap_bot_le_of_injective f quotient_map_injective)).symm ▸ this), exact f.is_integral_tower_bot_of_is_integral g quotient_map_injective ((comp_quotient_map_eq_of_comp_eq hcomm I).symm ▸ (ring_hom.is_integral_trans _ _ (ring_hom.is_integral_of_surjective _ (is_localization.surjective_quotient_map_of_maximal_of_localization (submonoid.powers x) Rₘ (by rwa [comap_comap, hcomm, ← bot_quotient_is_maximal_iff]))) (ring_hom.is_integral_quotient_of_is_integral _ hφ'))), end /-- Used to bootstrap the proof of `is_jacobson_polynomial_iff_is_jacobson`. That theorem is more general and should be used instead of this one. -/ private lemma is_jacobson_polynomial_of_domain (R : Type*) [integral_domain R] [hR : is_jacobson R] (P : ideal (polynomial R)) [is_prime P] (hP : ∀ (x : R), C x ∈ P → x = 0) : P.jacobson = P := begin by_cases Pb : P = ⊥, { exact Pb.symm ▸ jacobson_bot_polynomial_of_jacobson_bot (hR.out radical_bot_of_integral_domain) }, { rw jacobson_eq_iff_jacobson_quotient_eq_bot, haveI : (P.comap (C : R →+* polynomial R)).is_prime := comap_is_prime C P, obtain ⟨p, pP, p0⟩ := exists_nonzero_mem_of_ne_bot Pb hP, let x := (polynomial.map (quotient.mk (comap (C : R →+* _) P)) p).leading_coeff, have hx : x ≠ 0 := by rwa [ne.def, leading_coeff_eq_zero], refine jacobson_bot_of_integral_localization (localization.away x) (localization ((submonoid.powers x).map (P.quotient_map C le_rfl) : submonoid P.quotient)) (quotient_map P C le_rfl) quotient_map_injective x hx _, -- `convert` is noticeably faster than `exact` here: convert is_integral_is_localization_polynomial_quotient P p pP } end lemma is_jacobson_polynomial_of_is_jacobson (hR : is_jacobson R) : is_jacobson (polynomial R) := begin refine is_jacobson_iff_prime_eq.mpr (λ I, _), introI hI, let R' : subring I.quotient := ((quotient.mk I).comp C).range, let i : R →+* R' := ((quotient.mk I).comp C).range_restrict, have hi : function.surjective (i : R → R') := ((quotient.mk I).comp C).range_restrict_surjective, have hi' : (polynomial.map_ring_hom i : polynomial R →+* polynomial R').ker ≤ I, { refine λ f hf, polynomial_mem_ideal_of_coeff_mem_ideal I f (λ n, _), replace hf := congr_arg (λ (g : polynomial (((quotient.mk I).comp C).range)), g.coeff n) hf, change (polynomial.map ((quotient.mk I).comp C).range_restrict f).coeff n = 0 at hf, rw [coeff_map, subtype.ext_iff] at hf, rwa [mem_comap, ← quotient.eq_zero_iff_mem, ← ring_hom.comp_apply], }, haveI : (ideal.map (map_ring_hom i) I).is_prime := map_is_prime_of_surjective (map_surjective i hi) hi', suffices : (I.map (polynomial.map_ring_hom i)).jacobson = (I.map (polynomial.map_ring_hom i)), { replace this := congr_arg (comap (polynomial.map_ring_hom i)) this, rw [← map_jacobson_of_surjective _ hi', comap_map_of_surjective _ _, comap_map_of_surjective _ _] at this, refine le_antisymm (le_trans (le_sup_of_le_left le_rfl) (le_trans (le_of_eq this) (sup_le le_rfl hi'))) le_jacobson, all_goals {exact polynomial.map_surjective i hi} }, exact @is_jacobson_polynomial_of_domain R' _ (is_jacobson_of_surjective ⟨i, hi⟩) (map (map_ring_hom i) I) _ (eq_zero_of_polynomial_mem_map_range I), end theorem is_jacobson_polynomial_iff_is_jacobson : is_jacobson (polynomial R) ↔ is_jacobson R := begin refine ⟨_, is_jacobson_polynomial_of_is_jacobson⟩, introI H, exact is_jacobson_of_surjective ⟨eval₂_ring_hom (ring_hom.id _) 1, λ x, ⟨C x, by simp only [coe_eval₂_ring_hom, ring_hom.id_apply, eval₂_C]⟩⟩, end instance [is_jacobson R] : is_jacobson (polynomial R) := is_jacobson_polynomial_iff_is_jacobson.mpr ‹is_jacobson R› end comm_ring section integral_domain variables {R : Type*} [integral_domain R] [is_jacobson R] variables (P : ideal (polynomial R)) [hP : P.is_maximal] include P hP lemma is_maximal_comap_C_of_is_maximal (hP' : ∀ (x : R), C x ∈ P → x = 0) : is_maximal (comap C P : ideal R) := begin haveI hp'_prime : (P.comap C : ideal R).is_prime := comap_is_prime C P, obtain ⟨m, hm⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_of_maximal P polynomial_not_is_field), have : (m : polynomial R) ≠ 0, rwa [ne.def, submodule.coe_eq_zero], let φ : (P.comap C : ideal R).quotient →+* P.quotient := quotient_map P C le_rfl, let M : submonoid (P.comap C : ideal R).quotient := submonoid.powers ((m : polynomial R).map (quotient.mk (P.comap C : ideal R))).leading_coeff, rw ← bot_quotient_is_maximal_iff at hP ⊢, have hp0 : ((m : polynomial R).map (quotient.mk (P.comap C : ideal R))).leading_coeff ≠ 0 := λ hp0', this $ map_injective (quotient.mk (P.comap C : ideal R)) ((quotient.mk (P.comap C : ideal R)).injective_iff.2 (λ x hx, by rwa [quotient.eq_zero_iff_mem, (by rwa eq_bot_iff : (P.comap C : ideal R) = ⊥)] at hx)) (by simpa only [leading_coeff_eq_zero, map_zero] using hp0'), have hM : (0 : ((P.comap C : ideal R)).quotient) ∉ M := λ ⟨n, hn⟩, hp0 (pow_eq_zero hn), suffices : (⊥ : ideal (localization M)).is_maximal, { rw ← is_localization.comap_map_of_is_prime_disjoint M (localization M) ⊥ bot_prime (λ x hx, hM (hx.2 ▸ hx.1)), refine ((is_maximal_iff_is_maximal_disjoint (localization M) _ _).mp (by rwa map_bot)).1, swap, exact localization.is_localization }, let M' : submonoid P.quotient := M.map φ, have hM' : (0 : P.quotient) ∉ M' := λ ⟨z, hz⟩, hM (quotient_map_injective (trans hz.2 φ.map_zero.symm) ▸ hz.1), letI : integral_domain (localization M') := is_localization.integral_domain_localization (le_non_zero_divisors_of_domain hM'), suffices : (⊥ : ideal (localization M')).is_maximal, { rw le_antisymm bot_le (comap_bot_le_of_injective _ (is_localization.map_injective_of_injective M (localization M) (localization M') quotient_map_injective (le_non_zero_divisors_of_domain hM'))), refine is_maximal_comap_of_is_integral_of_is_maximal' _ _ ⊥ this, apply is_integral_is_localization_polynomial_quotient P _ (submodule.coe_mem m) }, rw (map_bot.symm : (⊥ : ideal (localization M')) = map (algebra_map P.quotient (localization M')) ⊥), refine map.is_maximal (algebra_map _ _) (localization_map_bijective_of_field hM' _) hP, rwa [← quotient.maximal_ideal_iff_is_field_quotient, ← bot_quotient_is_maximal_iff], end /-- Used to bootstrap the more general `quotient_mk_comp_C_is_integral_of_jacobson` -/ private lemma quotient_mk_comp_C_is_integral_of_jacobson' (hR : is_jacobson R) (hP' : ∀ (x : R), C x ∈ P → x = 0) : ((quotient.mk P).comp C : R →+* P.quotient).is_integral := begin refine (is_integral_quotient_map_iff _).mp _, let P' : ideal R := P.comap C, obtain ⟨pX, hpX, hp0⟩ := exists_nonzero_mem_of_ne_bot (ne_of_lt (bot_lt_of_maximal P polynomial_not_is_field)).symm hP', let M : submonoid P'.quotient := submonoid.powers (pX.map (quotient.mk P')).leading_coeff, let φ : P'.quotient →+* P.quotient := quotient_map P C le_rfl, haveI hp'_prime : P'.is_prime := comap_is_prime C P, have hM : (0 : P'.quotient) ∉ M := λ ⟨n, hn⟩, hp0 $ leading_coeff_eq_zero.mp (pow_eq_zero hn), let M' : submonoid P.quotient := M.map (quotient_map P C le_rfl), refine ((quotient_map P C le_rfl).is_integral_tower_bot_of_is_integral (algebra_map _ (localization M')) _ _), { refine is_localization.injective (localization M') (show M' ≤ _, from le_non_zero_divisors_of_domain (λ hM', hM _)), exact (let ⟨z, zM, z0⟩ := hM' in (quotient_map_injective (trans z0 φ.map_zero.symm)) ▸ zM) }, { rw ← is_localization.map_comp M.le_comap_map, refine ring_hom.is_integral_trans (algebra_map P'.quotient (localization M)) (is_localization.map _ _ M.le_comap_map) _ _, { exact (algebra_map P'.quotient (localization M)).is_integral_of_surjective (localization_map_bijective_of_field hM ((quotient.maximal_ideal_iff_is_field_quotient _).mp (is_maximal_comap_C_of_is_maximal P hP'))).2 }, { -- `convert` here is faster than `exact`, and this proof is near the time limit. convert is_integral_is_localization_polynomial_quotient P pX hpX } } end /-- If `R` is a Jacobson ring, and `P` is a maximal ideal of `polynomial R`, then `R → (polynomial R)/P` is an integral map. -/ lemma quotient_mk_comp_C_is_integral_of_jacobson : ((quotient.mk P).comp C : R →+* P.quotient).is_integral := begin let P' : ideal R := P.comap C, haveI : P'.is_prime := comap_is_prime C P, let f : polynomial R →+* polynomial P'.quotient := polynomial.map_ring_hom (quotient.mk P'), have hf : function.surjective f := map_surjective (quotient.mk P') quotient.mk_surjective, have hPJ : P = (P.map f).comap f, { rw comap_map_of_surjective _ hf, refine le_antisymm (le_sup_of_le_left le_rfl) (sup_le le_rfl _), refine λ p hp, polynomial_mem_ideal_of_coeff_mem_ideal P p (λ n, quotient.eq_zero_iff_mem.mp _), simpa only [coeff_map, coe_map_ring_hom] using (polynomial.ext_iff.mp hp) n }, refine ring_hom.is_integral_tower_bot_of_is_integral _ _ (injective_quotient_le_comap_map P) _, rw ← quotient_mk_maps_eq, refine ring_hom.is_integral_trans _ _ ((quotient.mk P').is_integral_of_surjective quotient.mk_surjective) _, apply quotient_mk_comp_C_is_integral_of_jacobson' _ _ (λ x hx, _), any_goals { exact ideal.is_jacobson_quotient }, { exact or.rec_on (map_eq_top_or_is_maximal_of_surjective f hf hP) (λ h, absurd (trans (h ▸ hPJ : P = comap f ⊤) comap_top : P = ⊤) hP.ne_top) id }, { obtain ⟨z, rfl⟩ := quotient.mk_surjective x, rwa [quotient.eq_zero_iff_mem, mem_comap, hPJ, mem_comap, coe_map_ring_hom, map_C] } end lemma is_maximal_comap_C_of_is_jacobson : (P.comap (C : R →+* polynomial R)).is_maximal := begin rw [← @mk_ker _ _ P, ring_hom.ker_eq_comap_bot, comap_comap], exact is_maximal_comap_of_is_integral_of_is_maximal' _ (quotient_mk_comp_C_is_integral_of_jacobson P) ⊥ ((bot_quotient_is_maximal_iff _).mpr hP), end omit P hP lemma comp_C_integral_of_surjective_of_jacobson {S : Type*} [field S] (f : (polynomial R) →+* S) (hf : function.surjective f) : (f.comp C).is_integral := begin haveI : (f.ker).is_maximal := @comap_is_maximal_of_surjective _ _ _ _ f ⊥ hf bot_is_maximal, let g : f.ker.quotient →+* S := ideal.quotient.lift f.ker f (λ _ h, h), have hfg : (g.comp (quotient.mk f.ker)) = f := ring_hom_ext' rfl rfl, rw [← hfg, ring_hom.comp_assoc], refine ring_hom.is_integral_trans _ g (quotient_mk_comp_C_is_integral_of_jacobson f.ker) (g.is_integral_of_surjective _), --(quotient.lift_surjective f.ker f _ hf)), rw [← hfg] at hf, exact function.surjective.of_comp hf, end end integral_domain end polynomial namespace mv_polynomial open mv_polynomial ring_hom lemma is_jacobson_mv_polynomial_fin {R : Type*} [comm_ring R] [H : is_jacobson R] : ∀ (n : ℕ), is_jacobson (mv_polynomial (fin n) R) | 0 := ((is_jacobson_iso ((rename_equiv R (equiv.equiv_pempty (fin 0))).to_ring_equiv.trans (pempty_ring_equiv R))).mpr H) | (n+1) := (is_jacobson_iso (fin_succ_equiv R n).to_ring_equiv).2 (polynomial.is_jacobson_polynomial_iff_is_jacobson.2 (is_jacobson_mv_polynomial_fin n)) /-- General form of the nullstellensatz for Jacobson rings, since in a Jacobson ring we have `Inf {P maximal | P ≥ I} = Inf {P prime | P ≥ I} = I.radical`. Fields are always Jacobson, and in that special case this is (most of) the classical Nullstellensatz, since `I(V(I))` is the intersection of maximal ideals containing `I`, which is then `I.radical` -/ instance {R : Type*} [comm_ring R] {ι : Type*} [fintype ι] [is_jacobson R] : is_jacobson (mv_polynomial ι R) := begin haveI := classical.dec_eq ι, let e := fintype.equiv_fin ι, rw is_jacobson_iso (rename_equiv R e).to_ring_equiv, exact is_jacobson_mv_polynomial_fin _ end variables {n : ℕ} lemma quotient_mk_comp_C_is_integral_of_jacobson {R : Type*} [integral_domain R] [is_jacobson R] (P : ideal (mv_polynomial (fin n) R)) [P.is_maximal] : ((quotient.mk P).comp mv_polynomial.C : R →+* P.quotient).is_integral := begin unfreezingI {induction n with n IH}, { refine ring_hom.is_integral_of_surjective _ (function.surjective.comp quotient.mk_surjective _), exact C_surjective (fin 0) }, { rw [← fin_succ_equiv_comp_C_eq_C, ← ring_hom.comp_assoc, ← ring_hom.comp_assoc, ← quotient_map_comp_mk le_rfl, ring_hom.comp_assoc (polynomial.C), ← quotient_map_comp_mk le_rfl, ring_hom.comp_assoc, ring_hom.comp_assoc, ← quotient_map_comp_mk le_rfl, ← ring_hom.comp_assoc (quotient.mk _)], refine ring_hom.is_integral_trans _ _ _ _, { refine ring_hom.is_integral_trans _ _ (is_integral_of_surjective _ quotient.mk_surjective) _, refine ring_hom.is_integral_trans _ _ _ _, { apply (is_integral_quotient_map_iff _).mpr (IH _), apply polynomial.is_maximal_comap_C_of_is_jacobson _, { exact mv_polynomial.is_jacobson_mv_polynomial_fin n }, { apply comap_is_maximal_of_surjective, exact (fin_succ_equiv R n).symm.surjective } }, { refine (is_integral_quotient_map_iff _).mpr _, rw ← quotient_map_comp_mk le_rfl, refine ring_hom.is_integral_trans _ _ _ ((is_integral_quotient_map_iff _).mpr _), { exact ring_hom.is_integral_of_surjective _ quotient.mk_surjective }, { apply polynomial.quotient_mk_comp_C_is_integral_of_jacobson _, { exact mv_polynomial.is_jacobson_mv_polynomial_fin n }, { exact comap_is_maximal_of_surjective _ (fin_succ_equiv R n).symm.surjective } } } }, { refine (is_integral_quotient_map_iff _).mpr _, refine ring_hom.is_integral_trans _ _ _ (is_integral_of_surjective _ quotient.mk_surjective), exact ring_hom.is_integral_of_surjective _ (fin_succ_equiv R n).symm.surjective } } end lemma comp_C_integral_of_surjective_of_jacobson {R : Type*} [integral_domain R] [is_jacobson R] {σ : Type*} [fintype σ] {S : Type*} [field S] (f : mv_polynomial σ R →+* S) (hf : function.surjective f) : (f.comp C).is_integral := begin haveI := classical.dec_eq σ, obtain ⟨e⟩ := fintype.trunc_equiv_fin σ, let f' : mv_polynomial (fin _) R →+* S := f.comp (rename_equiv R e.symm).to_ring_equiv.to_ring_hom, have hf' : function.surjective f' := ((function.surjective.comp hf (rename_equiv R e.symm).surjective)), have : (f'.comp C).is_integral, { haveI : (f'.ker).is_maximal := @comap_is_maximal_of_surjective _ _ _ _ f' ⊥ hf' bot_is_maximal, let g : f'.ker.quotient →+* S := ideal.quotient.lift f'.ker f' (λ _ h, h), have hfg : (g.comp (quotient.mk f'.ker)) = f' := ring_hom_ext (λ r, rfl) (λ i, rfl), rw [← hfg, ring_hom.comp_assoc], refine ring_hom.is_integral_trans _ g (quotient_mk_comp_C_is_integral_of_jacobson f'.ker) (g.is_integral_of_surjective _), rw ← hfg at hf', exact function.surjective.of_comp hf' }, rw ring_hom.comp_assoc at this, convert this, refine ring_hom.ext (λ x, _), exact ((rename_equiv R e.symm).commutes' x).symm, end end mv_polynomial end ideal
c65b96d668c3668726dba7026b3626518a3932ca
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/convex/strict.lean
f444b82976233d10810976191d91a4c7b3385357
[ "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
15,428
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import analysis.convex.basic import topology.order.basic /-! # Strictly convex sets This file defines strictly convex sets. A set is strictly convex if the open segment between any two distinct points lies in its interior. -/ open set open_locale convex pointwise variables {𝕜 𝕝 E F β : Type*} open function set open_locale convex section ordered_semiring variables [ordered_semiring 𝕜] [topological_space E] [topological_space F] section add_comm_monoid variables [add_comm_monoid E] [add_comm_monoid F] section has_smul variables (𝕜) [has_smul 𝕜 E] [has_smul 𝕜 F] (s : set E) /-- A set is strictly convex if the open segment between any two distinct points lies is in its interior. This basically means "convex and not flat on the boundary". -/ def strict_convex : Prop := s.pairwise $ λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ interior s variables {𝕜 s} {x y : E} {a b : 𝕜} lemma strict_convex_iff_open_segment_subset : strict_convex 𝕜 s ↔ s.pairwise (λ x y, open_segment 𝕜 x y ⊆ interior s) := forall₅_congr $ λ x hx y hy hxy, (open_segment_subset_iff 𝕜).symm lemma strict_convex.open_segment_subset (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (h : x ≠ y) : open_segment 𝕜 x y ⊆ interior s := strict_convex_iff_open_segment_subset.1 hs hx hy h lemma strict_convex_empty : strict_convex 𝕜 (∅ : set E) := pairwise_empty _ lemma strict_convex_univ : strict_convex 𝕜 (univ : set E) := begin intros x hx y hy hxy a b ha hb hab, rw interior_univ, exact mem_univ _, end protected lemma strict_convex.eq (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) (h : a • x + b • y ∉ interior s) : x = y := hs.eq hx hy $ λ H, h $ H ha hb hab protected lemma strict_convex.inter {t : set E} (hs : strict_convex 𝕜 s) (ht : strict_convex 𝕜 t) : strict_convex 𝕜 (s ∩ t) := begin intros x hx y hy hxy a b ha hb hab, rw interior_inter, exact ⟨hs hx.1 hy.1 hxy ha hb hab, ht hx.2 hy.2 hxy ha hb hab⟩, end lemma directed.strict_convex_Union {ι : Sort*} {s : ι → set E} (hdir : directed (⊆) s) (hs : ∀ ⦃i : ι⦄, strict_convex 𝕜 (s i)) : strict_convex 𝕜 (⋃ i, s i) := begin rintro x hx y hy hxy a b ha hb hab, rw mem_Union at hx hy, obtain ⟨i, hx⟩ := hx, obtain ⟨j, hy⟩ := hy, obtain ⟨k, hik, hjk⟩ := hdir i j, exact interior_mono (subset_Union s k) (hs (hik hx) (hjk hy) hxy ha hb hab), end lemma directed_on.strict_convex_sUnion {S : set (set E)} (hdir : directed_on (⊆) S) (hS : ∀ s ∈ S, strict_convex 𝕜 s) : strict_convex 𝕜 (⋃₀ S) := begin rw sUnion_eq_Union, exact (directed_on_iff_directed.1 hdir).strict_convex_Union (λ s, hS _ s.2), end end has_smul section module variables [module 𝕜 E] [module 𝕜 F] {s : set E} protected lemma strict_convex.convex (hs : strict_convex 𝕜 s) : convex 𝕜 s := convex_iff_pairwise_pos.2 $ λ x hx y hy hxy a b ha hb hab, interior_subset $ hs hx hy hxy ha hb hab /-- An open convex set is strictly convex. -/ protected lemma convex.strict_convex_of_open (h : is_open s) (hs : convex 𝕜 s) : strict_convex 𝕜 s := λ x hx y hy _ a b ha hb hab, h.interior_eq.symm ▸ hs hx hy ha.le hb.le hab lemma is_open.strict_convex_iff (h : is_open s) : strict_convex 𝕜 s ↔ convex 𝕜 s := ⟨strict_convex.convex, convex.strict_convex_of_open h⟩ lemma strict_convex_singleton (c : E) : strict_convex 𝕜 ({c} : set E) := pairwise_singleton _ _ lemma set.subsingleton.strict_convex (hs : s.subsingleton) : strict_convex 𝕜 s := hs.pairwise _ lemma strict_convex.linear_image [semiring 𝕝] [module 𝕝 E] [module 𝕝 F] [linear_map.compatible_smul E F 𝕜 𝕝] (hs : strict_convex 𝕜 s) (f : E →ₗ[𝕝] F) (hf : is_open_map f) : strict_convex 𝕜 (f '' s) := begin rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ hxy a b ha hb hab, refine hf.image_interior_subset _ ⟨a • x + b • y, hs hx hy (ne_of_apply_ne _ hxy) ha hb hab, _⟩, rw [map_add, f.map_smul_of_tower a, f.map_smul_of_tower b] end lemma strict_convex.is_linear_image (hs : strict_convex 𝕜 s) {f : E → F} (h : is_linear_map 𝕜 f) (hf : is_open_map f) : strict_convex 𝕜 (f '' s) := hs.linear_image (h.mk' f) hf lemma strict_convex.linear_preimage {s : set F} (hs : strict_convex 𝕜 s) (f : E →ₗ[𝕜] F) (hf : continuous f) (hfinj : injective f) : strict_convex 𝕜 (s.preimage f) := begin intros x hx y hy hxy a b ha hb hab, refine preimage_interior_subset_interior_preimage hf _, rw [mem_preimage, f.map_add, f.map_smul, f.map_smul], exact hs hx hy (hfinj.ne hxy) ha hb hab, end lemma strict_convex.is_linear_preimage {s : set F} (hs : strict_convex 𝕜 s) {f : E → F} (h : is_linear_map 𝕜 f) (hf : continuous f) (hfinj : injective f) : strict_convex 𝕜 (s.preimage f) := hs.linear_preimage (h.mk' f) hf hfinj section linear_ordered_cancel_add_comm_monoid variables [topological_space β] [linear_ordered_cancel_add_comm_monoid β] [order_topology β] [module 𝕜 β] [ordered_smul 𝕜 β] protected lemma set.ord_connected.strict_convex {s : set β} (hs : ord_connected s) : strict_convex 𝕜 s := begin refine strict_convex_iff_open_segment_subset.2 (λ x hx y hy hxy, _), cases hxy.lt_or_lt with hlt hlt; [skip, rw [open_segment_symm]]; exact (open_segment_subset_Ioo hlt).trans (is_open_Ioo.subset_interior_iff.2 $ Ioo_subset_Icc_self.trans $ hs.out ‹_› ‹_›) end lemma strict_convex_Iic (r : β) : strict_convex 𝕜 (Iic r) := ord_connected_Iic.strict_convex lemma strict_convex_Ici (r : β) : strict_convex 𝕜 (Ici r) := ord_connected_Ici.strict_convex lemma strict_convex_Iio (r : β) : strict_convex 𝕜 (Iio r) := ord_connected_Iio.strict_convex lemma strict_convex_Ioi (r : β) : strict_convex 𝕜 (Ioi r) := ord_connected_Ioi.strict_convex lemma strict_convex_Icc (r s : β) : strict_convex 𝕜 (Icc r s) := ord_connected_Icc.strict_convex lemma strict_convex_Ioo (r s : β) : strict_convex 𝕜 (Ioo r s) := ord_connected_Ioo.strict_convex lemma strict_convex_Ico (r s : β) : strict_convex 𝕜 (Ico r s) := ord_connected_Ico.strict_convex lemma strict_convex_Ioc (r s : β) : strict_convex 𝕜 (Ioc r s) := ord_connected_Ioc.strict_convex lemma strict_convex_uIcc (r s : β) : strict_convex 𝕜 (uIcc r s) := strict_convex_Icc _ _ lemma strict_convex_uIoc (r s : β) : strict_convex 𝕜 (uIoc r s) := strict_convex_Ioc _ _ end linear_ordered_cancel_add_comm_monoid end module end add_comm_monoid section add_cancel_comm_monoid variables [add_cancel_comm_monoid E] [has_continuous_add E] [module 𝕜 E] {s : set E} /-- The translation of a strictly convex set is also strictly convex. -/ lemma strict_convex.preimage_add_right (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, z + x) ⁻¹' s) := begin intros x hx y hy hxy a b ha hb hab, refine preimage_interior_subset_interior_preimage (continuous_add_left _) _, have h := hs hx hy ((add_right_injective _).ne hxy) ha hb hab, rwa [smul_add, smul_add, add_add_add_comm, ←add_smul, hab, one_smul] at h, end /-- The translation of a strictly convex set is also strictly convex. -/ lemma strict_convex.preimage_add_left (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, x + z) ⁻¹' s) := by simpa only [add_comm] using hs.preimage_add_right z end add_cancel_comm_monoid section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] section continuous_add variables [has_continuous_add E] {s t : set E} lemma strict_convex.add (hs : strict_convex 𝕜 s) (ht : strict_convex 𝕜 t) : strict_convex 𝕜 (s + t) := begin rintro _ ⟨v, w, hv, hw, rfl⟩ _ ⟨x, y, hx, hy, rfl⟩ h a b ha hb hab, rw [smul_add, smul_add, add_add_add_comm], obtain rfl | hvx := eq_or_ne v x, { refine interior_mono (add_subset_add (singleton_subset_iff.2 hv) subset.rfl) _, rw [convex.combo_self hab, singleton_add], exact (is_open_map_add_left _).image_interior_subset _ (mem_image_of_mem _ $ ht hw hy (ne_of_apply_ne _ h) ha hb hab) }, exact subset_interior_add_left (add_mem_add (hs hv hx hvx ha hb hab) $ ht.convex hw hy ha.le hb.le hab) end lemma strict_convex.add_left (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, z + x) '' s) := by simpa only [singleton_add] using (strict_convex_singleton z).add hs lemma strict_convex.add_right (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, x + z) '' s) := by simpa only [add_comm] using hs.add_left z /-- The translation of a strictly convex set is also strictly convex. -/ lemma strict_convex.vadd (hs : strict_convex 𝕜 s) (x : E) : strict_convex 𝕜 (x +ᵥ s) := hs.add_left x end continuous_add section continuous_smul variables [linear_ordered_field 𝕝] [module 𝕝 E] [has_continuous_const_smul 𝕝 E] [linear_map.compatible_smul E E 𝕜 𝕝] {s : set E} {x : E} lemma strict_convex.smul (hs : strict_convex 𝕜 s) (c : 𝕝) : strict_convex 𝕜 (c • s) := begin obtain rfl | hc := eq_or_ne c 0, { exact (subsingleton_zero_smul_set _).strict_convex }, { exact hs.linear_image (linear_map.lsmul _ _ c) (is_open_map_smul₀ hc) } end lemma strict_convex.affinity [has_continuous_add E] (hs : strict_convex 𝕜 s) (z : E) (c : 𝕝) : strict_convex 𝕜 (z +ᵥ c • s) := (hs.smul c).vadd z end continuous_smul end add_comm_group end ordered_semiring section ordered_comm_semiring variables [ordered_comm_semiring 𝕜] [topological_space E] section add_comm_group variables [add_comm_group E] [module 𝕜 E] [no_zero_smul_divisors 𝕜 E] [has_continuous_const_smul 𝕜 E] {s : set E} lemma strict_convex.preimage_smul (hs : strict_convex 𝕜 s) (c : 𝕜) : strict_convex 𝕜 ((λ z, c • z) ⁻¹' s) := begin classical, obtain rfl | hc := eq_or_ne c 0, { simp_rw [zero_smul, preimage_const], split_ifs, { exact strict_convex_univ }, { exact strict_convex_empty } }, refine hs.linear_preimage (linear_map.lsmul _ _ c) _ (smul_right_injective E hc), unfold linear_map.lsmul linear_map.mk₂ linear_map.mk₂' linear_map.mk₂'ₛₗ, exact continuous_const_smul _, end end add_comm_group end ordered_comm_semiring section ordered_ring variables [ordered_ring 𝕜] [topological_space E] [topological_space F] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s t : set E} {x y : E} lemma strict_convex.eq_of_open_segment_subset_frontier [nontrivial 𝕜] [densely_ordered 𝕜] (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (h : open_segment 𝕜 x y ⊆ frontier s) : x = y := begin obtain ⟨a, ha₀, ha₁⟩ := densely_ordered.dense (0 : 𝕜) 1 zero_lt_one, classical, by_contra hxy, exact (h ⟨a, 1 - a, ha₀, sub_pos_of_lt ha₁, add_sub_cancel'_right _ _, rfl⟩).2 (hs hx hy hxy ha₀ (sub_pos_of_lt ha₁) $ add_sub_cancel'_right _ _), end lemma strict_convex.add_smul_mem (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hxy : x + y ∈ s) (hy : y ≠ 0) {t : 𝕜} (ht₀ : 0 < t) (ht₁ : t < 1) : x + t • y ∈ interior s := begin have h : x + t • y = (1 - t) • x + t • (x + y), { rw [smul_add, ←add_assoc, ←add_smul, sub_add_cancel, one_smul] }, rw h, refine hs hx hxy (λ h, hy $ add_left_cancel _) (sub_pos_of_lt ht₁) ht₀ (sub_add_cancel _ _), exact x, rw [←h, add_zero], end lemma strict_convex.smul_mem_of_zero_mem (hs : strict_convex 𝕜 s) (zero_mem : (0 : E) ∈ s) (hx : x ∈ s) (hx₀ : x ≠ 0) {t : 𝕜} (ht₀ : 0 < t) (ht₁ : t < 1) : t • x ∈ interior s := by simpa using hs.add_smul_mem zero_mem (by simpa using hx) hx₀ ht₀ ht₁ lemma strict_convex.add_smul_sub_mem (h : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) {t : 𝕜} (ht₀ : 0 < t) (ht₁ : t < 1) : x + t • (y - x) ∈ interior s := begin apply h.open_segment_subset hx hy hxy, rw open_segment_eq_image', exact mem_image_of_mem _ ⟨ht₀, ht₁⟩, end /-- The preimage of a strictly convex set under an affine map is strictly convex. -/ lemma strict_convex.affine_preimage {s : set F} (hs : strict_convex 𝕜 s) {f : E →ᵃ[𝕜] F} (hf : continuous f) (hfinj : injective f) : strict_convex 𝕜 (f ⁻¹' s) := begin intros x hx y hy hxy a b ha hb hab, refine preimage_interior_subset_interior_preimage hf _, rw [mem_preimage, convex.combo_affine_apply hab], exact hs hx hy (hfinj.ne hxy) ha hb hab, end /-- The image of a strictly convex set under an affine map is strictly convex. -/ lemma strict_convex.affine_image (hs : strict_convex 𝕜 s) {f : E →ᵃ[𝕜] F} (hf : is_open_map f) : strict_convex 𝕜 (f '' s) := begin rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ hxy a b ha hb hab, exact hf.image_interior_subset _ ⟨a • x + b • y, ⟨hs hx hy (ne_of_apply_ne _ hxy) ha hb hab, convex.combo_affine_apply hab⟩⟩, end variables [topological_add_group E] lemma strict_convex.neg (hs : strict_convex 𝕜 s) : strict_convex 𝕜 (-s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg continuous_id.neg neg_injective lemma strict_convex.sub (hs : strict_convex 𝕜 s) (ht : strict_convex 𝕜 t) : strict_convex 𝕜 (s - t) := (sub_eq_add_neg s t).symm ▸ hs.add ht.neg end add_comm_group end ordered_ring section linear_ordered_field variables [linear_ordered_field 𝕜] [topological_space E] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s : set E} {x : E} /-- Alternative definition of set strict convexity, using division. -/ lemma strict_convex_iff_div : strict_convex 𝕜 s ↔ s.pairwise (λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → (a / (a + b)) • x + (b / (a + b)) • y ∈ interior s) := ⟨λ h x hx y hy hxy a b ha hb, begin apply h hx hy hxy (div_pos ha $ add_pos ha hb) (div_pos hb $ add_pos ha hb), rw ←add_div, exact div_self (add_pos ha hb).ne', end, λ h x hx y hy hxy a b ha hb hab, by convert h hx hy hxy ha hb; rw [hab, div_one] ⟩ lemma strict_convex.mem_smul_of_zero_mem (hs : strict_convex 𝕜 s) (zero_mem : (0 : E) ∈ s) (hx : x ∈ s) (hx₀ : x ≠ 0) {t : 𝕜} (ht : 1 < t) : x ∈ t • interior s := begin rw mem_smul_set_iff_inv_smul_mem₀ (zero_lt_one.trans ht).ne', exact hs.smul_mem_of_zero_mem zero_mem hx hx₀ (inv_pos.2 $ zero_lt_one.trans ht) (inv_lt_one ht), end end add_comm_group end linear_ordered_field /-! #### Convex sets in an ordered space Relates `convex` and `set.ord_connected`. -/ section variables [linear_ordered_field 𝕜] [topological_space 𝕜] [order_topology 𝕜] {s : set 𝕜} /-- A set in a linear ordered field is strictly convex if and only if it is convex. -/ @[simp] lemma strict_convex_iff_convex : strict_convex 𝕜 s ↔ convex 𝕜 s := ⟨strict_convex.convex, λ hs, hs.ord_connected.strict_convex⟩ lemma strict_convex_iff_ord_connected : strict_convex 𝕜 s ↔ s.ord_connected := strict_convex_iff_convex.trans convex_iff_ord_connected alias strict_convex_iff_ord_connected ↔ strict_convex.ord_connected _ end
cc00d41bf56dd9948588f93e24e614bba6140c24
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/group_theory/semidirect_product.lean
35cff2d99bf2624af939d9e54b0e682fdbb8ab42
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,068
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.equiv.mul_add_aut import logic.function.basic import group_theory.subgroup /-! # Semidirect product This file defines semidirect products of groups, and the canonical maps in and out of the semidirect product. The semidirect product of `N` and `G` given a hom `φ` from `φ` from `G` to the automorphism group of `N` is the product of sets with the group `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` ## Key definitions There are two homs into the semidirect product `inl : N →* N ⋊[φ] G` and `inr : G →* N ⋊[φ] G`, and `lift` can be used to define maps `N ⋊[φ] G →* H` out of the semidirect product given maps `f₁ : N →* H` and `f₂ : G →* H` that satisfy the condition `∀ n g, f₁ (φ g n) = f₂ g * f₁ n * f₂ g⁻¹` ## Notation This file introduces the global notation `N ⋊[φ] G` for `semidirect_product N G φ` ## Tags group, semidirect product -/ variables (N : Type*) (G : Type*) {H : Type*} [group N] [group G] [group H] /-- The semidirect product of groups `N` and `G`, given a map `φ` from `G` to the automorphism group of `N`. It the product of sets with the group operation `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` -/ @[ext, derive decidable_eq] structure semidirect_product (φ : G →* mul_aut N) := (left : N) (right : G) attribute [pp_using_anonymous_constructor] semidirect_product notation N` ⋊[`:35 φ:35`] `:0 G :35 := semidirect_product N G φ namespace semidirect_product variables {N G} {φ : G →* mul_aut N} private def one_aux : N ⋊[φ] G := ⟨1, 1⟩ private def mul_aux (a b : N ⋊[φ] G) : N ⋊[φ] G := ⟨a.1 * φ a.2 b.1, a.right * b.right⟩ private def inv_aux (a : N ⋊[φ] G) : N ⋊[φ] G := let i := a.2⁻¹ in ⟨φ i a.1⁻¹, i⟩ private lemma mul_assoc_aux (a b c : N ⋊[φ] G) : mul_aux (mul_aux a b) c = mul_aux a (mul_aux b c) := by simp [mul_aux, mul_assoc, mul_equiv.map_mul] private lemma mul_one_aux (a : N ⋊[φ] G) : mul_aux a one_aux = a := by cases a; simp [mul_aux, one_aux] private lemma one_mul_aux (a : N ⋊[φ] G) : mul_aux one_aux a = a := by cases a; simp [mul_aux, one_aux] private lemma mul_left_inv_aux (a : N ⋊[φ] G) : mul_aux (inv_aux a) a = one_aux := by simp only [mul_aux, inv_aux, one_aux, ← mul_equiv.map_mul, mul_left_inv]; simp instance : group (N ⋊[φ] G) := { one := one_aux, inv := inv_aux, mul := mul_aux, mul_assoc := mul_assoc_aux, one_mul := one_mul_aux, mul_one := mul_one_aux, mul_left_inv := mul_left_inv_aux } instance : inhabited (N ⋊[φ] G) := ⟨1⟩ @[simp] lemma one_left : (1 : N ⋊[φ] G).left = 1 := rfl @[simp] lemma one_right : (1 : N ⋊[φ] G).right = 1 := rfl @[simp] lemma inv_left (a : N ⋊[φ] G) : (a⁻¹).left = φ a.right⁻¹ a.left⁻¹ := rfl @[simp] lemma inv_right (a : N ⋊[φ] G) : (a⁻¹).right = a.right⁻¹ := rfl @[simp] lemma mul_left (a b : N ⋊[φ] G) : (a * b).left = a.left * φ a.right b.left := rfl @[simp] lemma mul_right (a b : N ⋊[φ] G) : (a * b).right = a.right * b.right := rfl /-- The canonical map `N →* N ⋊[φ] G` sending `n` to `⟨n, 1⟩` -/ def inl : N →* N ⋊[φ] G := { to_fun := λ n, ⟨n, 1⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inl (n : N) : (inl n : N ⋊[φ] G).left = n := rfl @[simp] lemma right_inl (n : N) : (inl n : N ⋊[φ] G).right = 1 := rfl lemma inl_injective : function.injective (inl : N → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨left, left_inl⟩ @[simp] lemma inl_inj {n₁ n₂ : N} : (inl n₁ : N ⋊[φ] G) = inl n₂ ↔ n₁ = n₂ := inl_injective.eq_iff /-- The canonical map `G →* N ⋊[φ] G` sending `g` to `⟨1, g⟩` -/ def inr : G →* N ⋊[φ] G := { to_fun := λ g, ⟨1, g⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inr (g : G) : (inr g : N ⋊[φ] G).left = 1 := rfl @[simp] lemma right_inr (g : G) : (inr g : N ⋊[φ] G).right = g := rfl lemma inr_injective : function.injective (inr : G → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨right, right_inr⟩ @[simp] lemma inr_inj {g₁ g₂ : G} : (inr g₁ : N ⋊[φ] G) = inr g₂ ↔ g₁ = g₂ := inr_injective.eq_iff lemma inl_aut (g : G) (n : N) : (inl (φ g n) : N ⋊[φ] G) = inr g * inl n * inr g⁻¹ := by ext; simp lemma inl_aut_inv (g : G) (n : N) : (inl ((φ g)⁻¹ n) : N ⋊[φ] G) = inr g⁻¹ * inl n * inr g := by rw [← monoid_hom.map_inv, inl_aut, inv_inv] @[simp] lemma mk_eq_inl_mul_inr (g : G) (n : N) : (⟨n, g⟩ : N ⋊[φ] G) = inl n * inr g := by ext; simp @[simp] lemma inl_left_mul_inr_right (x : N ⋊[φ] G) : inl x.left * inr x.right = x := by ext; simp /-- The canonical projection map `N ⋊[φ] G →* G`, as a group hom. -/ def right_hom : N ⋊[φ] G →* G := { to_fun := semidirect_product.right, map_one' := rfl, map_mul' := λ _ _, rfl } @[simp] lemma right_hom_eq_right : (right_hom : N ⋊[φ] G → G) = right := rfl @[simp] lemma right_hom_comp_inl : (right_hom : N ⋊[φ] G →* G).comp inl = 1 := by ext; simp [right_hom] @[simp] lemma right_hom_comp_inr : (right_hom : N ⋊[φ] G →* G).comp inr = monoid_hom.id _ := by ext; simp [right_hom] @[simp] lemma right_hom_inl (n : N) : right_hom (inl n : N ⋊[φ] G) = 1 := by simp [right_hom] @[simp] lemma right_hom_inr (g : G) : right_hom (inr g : N ⋊[φ] G) = g := by simp [right_hom] lemma right_hom_surjective : function.surjective (right_hom : N ⋊[φ] G → G) := function.surjective_iff_has_right_inverse.2 ⟨inr, right_hom_inr⟩ lemma range_inl_eq_ker_right_hom : (inl : N →* N ⋊[φ] G).range = right_hom.ker := le_antisymm (λ _, by simp [monoid_hom.mem_ker, eq_comm] {contextual := tt}) (λ x hx, ⟨x.left, by ext; simp [*, monoid_hom.mem_ker] at *⟩) section lift variables (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) /-- Define a group hom `N ⋊[φ] G →* H`, by defining maps `N →* H` and `G →* H` -/ def lift (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) : N ⋊[φ] G →* H := { to_fun := λ a, f₁ a.1 * f₂ a.2, map_one' := by simp, map_mul' := λ a b, begin have := λ n g, monoid_hom.ext_iff.1 (h n) g, simp only [mul_aut.conj_apply, monoid_hom.comp_apply, mul_equiv.coe_to_monoid_hom] at this, simp [this, mul_assoc] end } @[simp] lemma lift_inl (n : N) : lift f₁ f₂ h (inl n) = f₁ n := by simp [lift] @[simp] lemma lift_comp_inl : (lift f₁ f₂ h).comp inl = f₁ := by ext; simp @[simp] lemma lift_inr (g : G) : lift f₁ f₂ h (inr g) = f₂ g := by simp [lift] @[simp] lemma lift_comp_inr : (lift f₁ f₂ h).comp inr = f₂ := by ext; simp lemma lift_unique (F : N ⋊[φ] G →* H) : F = lift (F.comp inl) (F.comp inr) (λ _, by ext; simp [inl_aut]) := begin ext, simp only [lift, monoid_hom.comp_apply, monoid_hom.coe_mk], rw [← F.map_mul, inl_left_mul_inr_right], end /-- Two maps out of the semidirect product are equal if they're equal after composition with both `inl` and `inr` -/ lemma hom_ext {f g : (N ⋊[φ] G) →* H} (hl : f.comp inl = g.comp inl) (hr : f.comp inr = g.comp inr) : f = g := by { rw [lift_unique f, lift_unique g], simp only * } end lift section map variables {N₁ : Type*} {G₁ : Type*} [group N₁] [group G₁] {φ₁ : G₁ →* mul_aut N₁} /-- Define a map from `N ⋊[φ] G` to `N₁ ⋊[φ₁] G₁` given maps `N →* N₁` and `G →* G₁` that satisfy a commutativity condition `∀ n g, f₁ (φ g n) = φ₁ (f₂ g) (f₁ n)`. -/ def map (f₁ : N →* N₁) (f₂ : G →* G₁) (h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁) : N ⋊[φ] G →* N₁ ⋊[φ₁] G₁ := { to_fun := λ x, ⟨f₁ x.1, f₂ x.2⟩, map_one' := by simp, map_mul' := λ x y, begin replace h := monoid_hom.ext_iff.1 (h x.right) y.left, ext; simp * at *, end } variables (f₁ : N →* N₁) (f₂ : G →* G₁) (h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁) @[simp] lemma map_left (g : N ⋊[φ] G) : (map f₁ f₂ h g).left = f₁ g.left := rfl @[simp] lemma map_right (g : N ⋊[φ] G) : (map f₁ f₂ h g).right = f₂ g.right := rfl @[simp] lemma right_hom_comp_map : right_hom.comp (map f₁ f₂ h) = f₂.comp right_hom := rfl @[simp] lemma map_inl (n : N) : map f₁ f₂ h (inl n) = inl (f₁ n) := by simp [map] @[simp] lemma map_comp_inl : (map f₁ f₂ h).comp inl = inl.comp f₁ := by ext; simp @[simp] lemma map_inr (g : G) : map f₁ f₂ h (inr g) = inr (f₂ g) := by simp [map] @[simp] lemma map_comp_inr : (map f₁ f₂ h).comp inr = inr.comp f₂ := by ext; simp [map] end map end semidirect_product
cfa9c7c60ac32187fb1078232ef77d8d62f364c6
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/covering/liminf_limsup.lean
bd254f5dcaff9c4265310cbc2281d653497d373a
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
16,508
lean
/- Copyright (c) 2022 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import measure_theory.covering.density_theorem /-! # Liminf, limsup, and uniformly locally doubling measures. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file is a place to collect lemmas about liminf and limsup for subsets of a metric space carrying a uniformly locally doubling measure. ## Main results: * `blimsup_cthickening_mul_ae_eq`: the limsup of the closed thickening of a sequence of subsets of a metric space is unchanged almost everywhere for a uniformly locally doubling measure if the sequence of distances is multiplied by a positive scale factor. This is a generalisation of a result of Cassels, appearing as Lemma 9 on page 217 of [J.W.S. Cassels, *Some metrical theorems in Diophantine approximation. I*](cassels1950). * `blimsup_thickening_mul_ae_eq`: a variant of `blimsup_cthickening_mul_ae_eq` for thickenings rather than closed thickenings. -/ open set filter metric measure_theory topological_space open_locale nnreal ennreal topology variables {α : Type*} [metric_space α] [second_countable_topology α] [measurable_space α] [borel_space α] variables (μ : measure α) [is_locally_finite_measure μ] [is_unif_loc_doubling_measure μ] /-- This is really an auxiliary result en route to `blimsup_cthickening_ae_le_of_eventually_mul_le` (which is itself an auxiliary result en route to `blimsup_cthickening_mul_ae_eq`). NB: The `set : α` type ascription is present because of issue #16932 on GitHub. -/ lemma blimsup_cthickening_ae_le_of_eventually_mul_le_aux (p : ℕ → Prop) {s : ℕ → set α} (hs : ∀ i, is_closed (s i)) {r₁ r₂ : ℕ → ℝ} (hr : tendsto r₁ at_top (𝓝[>] 0)) (hrp : 0 ≤ r₁) {M : ℝ} (hM : 0 < M) (hM' : M < 1) (hMr : ∀ᶠ i in at_top, M * r₁ i ≤ r₂ i) : (blimsup (λ i, cthickening (r₁ i) (s i)) at_top p : set α) ≤ᵐ[μ] (blimsup (λ i, cthickening (r₂ i) (s i)) at_top p : set α) := begin /- Sketch of proof: Assume that `p` is identically true for simplicity. Let `Y₁ i = cthickening (r₁ i) (s i)`, define `Y₂` similarly except using `r₂`, and let `(Z i) = ⋃_{j ≥ i} (Y₂ j)`. Our goal is equivalent to showing that `μ ((limsup Y₁) \ (Z i)) = 0` for all `i`. Assume for contradiction that `μ ((limsup Y₁) \ (Z i)) ≠ 0` for some `i` and let `W = (limsup Y₁) \ (Z i)`. Apply Lebesgue's density theorem to obtain a point `d` in `W` of density `1`. Since `d ∈ limsup Y₁`, there is a subsequence of `j ↦ Y₁ j`, indexed by `f 0 < f 1 < ...`, such that `d ∈ Y₁ (f j)` for all `j`. For each `j`, we may thus choose `w j ∈ s (f j)` such that `d ∈ B j`, where `B j = closed_ball (w j) (r₁ (f j))`. Note that since `d` has density one, `μ (W ∩ (B j)) / μ (B j) → 1`. We obtain our contradiction by showing that there exists `η < 1` such that `μ (W ∩ (B j)) / μ (B j) ≤ η` for sufficiently large `j`. In fact we claim that `η = 1 - C⁻¹` is such a value where `C` is the scaling constant of `M⁻¹` for the uniformly locally doubling measure `μ`. To prove the claim, let `b j = closed_ball (w j) (M * r₁ (f j))` and for given `j` consider the sets `b j` and `W ∩ (B j)`. These are both subsets of `B j` and are disjoint for large enough `j` since `M * r₁ j ≤ r₂ j` and thus `b j ⊆ Z i ⊆ Wᶜ`. We thus have: `μ (b j) + μ (W ∩ (B j)) ≤ μ (B j)`. Combining this with `μ (B j) ≤ C * μ (b j)` we obtain the required inequality. -/ set Y₁ : ℕ → set α := λ i, cthickening (r₁ i) (s i), set Y₂ : ℕ → set α := λ i, cthickening (r₂ i) (s i), let Z : ℕ → set α := λ i, ⋃ j (h : p j ∧ i ≤ j), Y₂ j, suffices : ∀ i, μ (at_top.blimsup Y₁ p \ Z i) = 0, { rwa [ae_le_set, @blimsup_eq_infi_bsupr_of_nat _ _ _ Y₂, infi_eq_Inter, diff_Inter, measure_Union_null_iff], }, intros, set W := at_top.blimsup Y₁ p \ Z i, by_contra contra, obtain ⟨d, hd, hd'⟩ : ∃ d, d ∈ W ∧ ∀ {ι : Type*} {l : filter ι} (w : ι → α) (δ : ι → ℝ), tendsto δ l (𝓝[>] 0) → (∀ᶠ j in l, d ∈ closed_ball (w j) (2 * δ j)) → tendsto (λ j, μ (W ∩ closed_ball (w j) (δ j)) / μ (closed_ball (w j) (δ j))) l (𝓝 1) := measure.exists_mem_of_measure_ne_zero_of_ae contra (is_unif_loc_doubling_measure.ae_tendsto_measure_inter_div μ W 2), replace hd : d ∈ blimsup Y₁ at_top p := ((mem_diff _).mp hd).1, obtain ⟨f : ℕ → ℕ, hf⟩ := exists_forall_mem_of_has_basis_mem_blimsup' at_top_basis hd, simp only [forall_and_distrib] at hf, obtain ⟨hf₀ : ∀ j, d ∈ cthickening (r₁ (f j)) (s (f j)), hf₁, hf₂ : ∀ j, j ≤ f j⟩ := hf, have hf₃ : tendsto f at_top at_top := tendsto_at_top_at_top.mpr (λ j, ⟨f j, λ i hi, (hf₂ j).trans (hi.trans $ hf₂ i)⟩), replace hr : tendsto (r₁ ∘ f) at_top (𝓝[>] 0) := hr.comp hf₃, replace hMr : ∀ᶠ j in at_top, M * r₁ (f j) ≤ r₂ (f j) := hf₃.eventually hMr, replace hf₀ : ∀ j, ∃ (w ∈ s (f j)), d ∈ closed_ball w (2 * r₁ (f j)), { intros j, specialize hrp (f j), rw pi.zero_apply at hrp, rcases eq_or_lt_of_le hrp with hr0 | hrp', { specialize hf₀ j, rw [← hr0, cthickening_zero, (hs (f j)).closure_eq] at hf₀, exact ⟨d, hf₀, by simp [← hr0]⟩, }, { exact mem_Union₂.mp (cthickening_subset_Union_closed_ball_of_lt (s (f j)) (by positivity) (lt_two_mul_self hrp') (hf₀ j)), }, }, choose w hw hw' using hf₀, let C := is_unif_loc_doubling_measure.scaling_constant_of μ M⁻¹, have hC : 0 < C := lt_of_lt_of_le zero_lt_one (is_unif_loc_doubling_measure.one_le_scaling_constant_of μ M⁻¹), suffices : ∃ (η < (1 : ℝ≥0)), ∀ᶠ j in at_top, μ (W ∩ closed_ball (w j) (r₁ (f j))) / μ (closed_ball (w j) (r₁ (f j))) ≤ η, { obtain ⟨η, hη, hη'⟩ := this, replace hη' : 1 ≤ η := by simpa only [ennreal.one_le_coe_iff] using le_of_tendsto (hd' w (λ j, r₁ (f j)) hr $ eventually_of_forall hw') hη', exact (lt_self_iff_false _).mp (lt_of_lt_of_le hη hη'), }, refine ⟨1 - C⁻¹, tsub_lt_self zero_lt_one (inv_pos.mpr hC), _⟩, replace hC : C ≠ 0 := ne_of_gt hC, let b : ℕ → set α := λ j, closed_ball (w j) (M * r₁ (f j)), let B : ℕ → set α := λ j, closed_ball (w j) (r₁ (f j)), have h₁ : ∀ j, b j ⊆ B j := λ j, closed_ball_subset_closed_ball (mul_le_of_le_one_left (hrp (f j)) hM'.le), have h₂ : ∀ j, W ∩ B j ⊆ B j := λ j, inter_subset_right W (B j), have h₃ : ∀ᶠ j in at_top, disjoint (b j) (W ∩ B j), { apply hMr.mp, rw eventually_at_top, refine ⟨i, λ j hj hj', disjoint.inf_right (B j) $ disjoint.inf_right' (blimsup Y₁ at_top p) _⟩, change disjoint (b j) (Z i)ᶜ, rw disjoint_compl_right_iff_subset, refine (closed_ball_subset_cthickening (hw j) (M * r₁ (f j))).trans ((cthickening_mono hj' _).trans (λ a ha, _)), simp only [mem_Union, exists_prop], exact ⟨f j, ⟨hf₁ j, hj.le.trans (hf₂ j)⟩, ha⟩, }, have h₄ : ∀ᶠ j in at_top, μ (B j) ≤ C * μ (b j) := (hr.eventually (is_unif_loc_doubling_measure.eventually_measure_le_scaling_constant_mul' μ M hM)).mono (λ j hj, hj (w j)), refine (h₃.and h₄).mono (λ j hj₀, _), change μ (W ∩ B j) / μ (B j) ≤ ↑(1 - C⁻¹), rcases eq_or_ne (μ (B j)) ∞ with hB | hB, { simp [hB], }, apply ennreal.div_le_of_le_mul, rw [with_top.coe_sub, ennreal.coe_one, ennreal.sub_mul (λ _ _, hB), one_mul], replace hB : ↑C⁻¹ * μ (B j) ≠ ∞, { refine ennreal.mul_ne_top _ hB, rwa [ennreal.coe_inv hC, ne.def, ennreal.inv_eq_top, ennreal.coe_eq_zero], }, obtain ⟨hj₁ : disjoint (b j) (W ∩ B j), hj₂ : μ (B j) ≤ C * μ (b j)⟩ := hj₀, replace hj₂ : ↑C⁻¹ * μ (B j) ≤ μ (b j), { rw [ennreal.coe_inv hC, ← ennreal.div_eq_inv_mul], exact ennreal.div_le_of_le_mul' hj₂, }, have hj₃ : ↑C⁻¹ * μ (B j) + μ (W ∩ B j) ≤ μ (B j), { refine le_trans (add_le_add_right hj₂ _) _, rw ← measure_union' hj₁ measurable_set_closed_ball, exact measure_mono (union_subset (h₁ j) (h₂ j)), }, replace hj₃ := tsub_le_tsub_right hj₃ (↑C⁻¹ * μ (B j)), rwa ennreal.add_sub_cancel_left hB at hj₃, end /-- This is really an auxiliary result en route to `blimsup_cthickening_mul_ae_eq`. NB: The `set : α` type ascription is present because of issue #16932 on GitHub. -/ lemma blimsup_cthickening_ae_le_of_eventually_mul_le (p : ℕ → Prop) {s : ℕ → set α} {M : ℝ} (hM : 0 < M) {r₁ r₂ : ℕ → ℝ} (hr : tendsto r₁ at_top (𝓝[>] 0)) (hMr : ∀ᶠ i in at_top, M * r₁ i ≤ r₂ i) : (blimsup (λ i, cthickening (r₁ i) (s i)) at_top p : set α) ≤ᵐ[μ] (blimsup (λ i, cthickening (r₂ i) (s i)) at_top p : set α) := begin let R₁ := λ i, max 0 (r₁ i), let R₂ := λ i, max 0 (r₂ i), have hRp : 0 ≤ R₁ := λ i, le_max_left 0 (r₁ i), replace hMr : ∀ᶠ i in at_top, M * R₁ i ≤ R₂ i, { refine hMr.mono (λ i hi, _), rw [mul_max_of_nonneg _ _ hM.le, mul_zero], exact max_le_max (le_refl 0) hi, }, simp_rw [← cthickening_max_zero (r₁ _), ← cthickening_max_zero (r₂ _)], cases le_or_lt 1 M with hM' hM', { apply has_subset.subset.eventually_le, change _ ≤ _, refine mono_blimsup' (hMr.mono $ λ i hi hp, cthickening_mono _ (s i)), exact (le_mul_of_one_le_left (hRp i) hM').trans hi, }, { simp only [← @cthickening_closure _ _ _ (s _)], have hs : ∀ i, is_closed (closure (s i)) := λ i, is_closed_closure, exact blimsup_cthickening_ae_le_of_eventually_mul_le_aux μ p hs (tendsto_nhds_max_right hr) hRp hM hM' hMr, }, end /-- Given a sequence of subsets `sᵢ` of a metric space, together with a sequence of radii `rᵢ` such that `rᵢ → 0`, the set of points which belong to infinitely many of the closed `rᵢ`-thickenings of `sᵢ` is unchanged almost everywhere for a uniformly locally doubling measure if the `rᵢ` are all scaled by a positive constant. This lemma is a generalisation of Lemma 9 appearing on page 217 of [J.W.S. Cassels, *Some metrical theorems in Diophantine approximation. I*](cassels1950). See also `blimsup_thickening_mul_ae_eq`. NB: The `set : α` type ascription is present because of issue #16932 on GitHub. -/ theorem blimsup_cthickening_mul_ae_eq (p : ℕ → Prop) (s : ℕ → set α) {M : ℝ} (hM : 0 < M) (r : ℕ → ℝ) (hr : tendsto r at_top (𝓝 0)) : (blimsup (λ i, cthickening (M * r i) (s i)) at_top p : set α) =ᵐ[μ] (blimsup (λ i, cthickening (r i) (s i)) at_top p : set α) := begin have : ∀ (p : ℕ → Prop) {r : ℕ → ℝ} (hr : tendsto r at_top (𝓝[>] 0)), (blimsup (λ i, cthickening (M * r i) (s i)) at_top p : set α) =ᵐ[μ] (blimsup (λ i, cthickening (r i) (s i)) at_top p : set α), { clear p hr r, intros p r hr, have hr' : tendsto (λ i, M * r i) at_top (𝓝[>] 0), { convert tendsto_nhds_within_Ioi.const_mul hM hr; simp only [mul_zero], }, refine eventually_le_antisymm_iff.mpr ⟨_, _⟩, { exact blimsup_cthickening_ae_le_of_eventually_mul_le μ p (inv_pos.mpr hM) hr' (eventually_of_forall $ λ i, by rw inv_mul_cancel_left₀ hM.ne' (r i)), }, { exact blimsup_cthickening_ae_le_of_eventually_mul_le μ p hM hr (eventually_of_forall $ λ i, le_refl _), }, }, let r' : ℕ → ℝ := λ i, if 0 < r i then r i else 1/((i : ℝ) + 1), have hr' : tendsto r' at_top (𝓝[>] 0), { refine tendsto_nhds_within_iff.mpr ⟨tendsto.if' hr tendsto_one_div_add_at_top_nhds_0_nat, eventually_of_forall $ λ i, _⟩, by_cases hi : 0 < r i, { simp [hi, r'], }, { simp only [hi, r', one_div, mem_Ioi, if_false, inv_pos], positivity, }, }, have h₀ : ∀ i, (p i ∧ 0 < r i) → cthickening (r i) (s i) = cthickening (r' i) (s i), { rintros i ⟨-, hi⟩, congr, change r i = ite (0 < r i) (r i) _, simp [hi], }, have h₁ : ∀ i, (p i ∧ 0 < r i) → cthickening (M * r i) (s i) = cthickening (M * r' i) (s i), { rintros i ⟨-, hi⟩, simp only [hi, mul_ite, if_true], }, have h₂ : ∀ i, (p i ∧ r i ≤ 0) → cthickening (M * r i) (s i) = cthickening (r i) (s i), { rintros i ⟨-, hi⟩, have hi' : M * r i ≤ 0 := mul_nonpos_of_nonneg_of_nonpos hM.le hi, rw [cthickening_of_nonpos hi, cthickening_of_nonpos hi'], }, have hp : p = λ i, (p i ∧ 0 < r i) ∨ (p i ∧ r i ≤ 0), { ext i, simp [← and_or_distrib_left, lt_or_le 0 (r i)], }, rw [hp, blimsup_or_eq_sup, blimsup_or_eq_sup, sup_eq_union, blimsup_congr (eventually_of_forall h₀), blimsup_congr (eventually_of_forall h₁), blimsup_congr (eventually_of_forall h₂)], exact ae_eq_set_union (this (λ i, p i ∧ 0 < r i) hr') (ae_eq_refl _), end lemma blimsup_cthickening_ae_eq_blimsup_thickening {p : ℕ → Prop} {s : ℕ → set α} {r : ℕ → ℝ} (hr : tendsto r at_top (𝓝 0)) (hr' : ∀ᶠ i in at_top , p i → 0 < r i) : (blimsup (λ i, cthickening (r i) (s i)) at_top p : set α) =ᵐ[μ] (blimsup (λ i, thickening (r i) (s i)) at_top p : set α) := begin refine eventually_le_antisymm_iff.mpr ⟨_, has_subset.subset.eventually_le (_ : _ ≤ _)⟩, { rw eventually_le_congr (blimsup_cthickening_mul_ae_eq μ p s (@one_half_pos ℝ _) r hr).symm eventually_eq.rfl, apply has_subset.subset.eventually_le, change _ ≤ _, refine mono_blimsup' (hr'.mono $ λ i hi pi, cthickening_subset_thickening' (hi pi) _ (s i)), nlinarith [hi pi], }, { exact mono_blimsup (λ i pi, thickening_subset_cthickening _ _), }, end /-- An auxiliary result en route to `blimsup_thickening_mul_ae_eq`. -/ lemma blimsup_thickening_mul_ae_eq_aux (p : ℕ → Prop) (s : ℕ → set α) {M : ℝ} (hM : 0 < M) (r : ℕ → ℝ) (hr : tendsto r at_top (𝓝 0)) (hr' : ∀ᶠ i in at_top , p i → 0 < r i) : (blimsup (λ i, thickening (M * r i) (s i)) at_top p : set α) =ᵐ[μ] (blimsup (λ i, thickening (r i) (s i)) at_top p : set α) := begin have h₁ := blimsup_cthickening_ae_eq_blimsup_thickening μ hr hr', have h₂ := blimsup_cthickening_mul_ae_eq μ p s hM r hr, replace hr : tendsto (λ i, M * r i) at_top (𝓝 0), { convert hr.const_mul M, simp, }, replace hr' : ∀ᶠ i in at_top , p i → 0 < M * r i := hr'.mono (λ i hi hip, mul_pos hM (hi hip)), have h₃ := blimsup_cthickening_ae_eq_blimsup_thickening μ hr hr', exact h₃.symm.trans (h₂.trans h₁), end /-- Given a sequence of subsets `sᵢ` of a metric space, together with a sequence of radii `rᵢ` such that `rᵢ → 0`, the set of points which belong to infinitely many of the `rᵢ`-thickenings of `sᵢ` is unchanged almost everywhere for a uniformly locally doubling measure if the `rᵢ` are all scaled by a positive constant. This lemma is a generalisation of Lemma 9 appearing on page 217 of [J.W.S. Cassels, *Some metrical theorems in Diophantine approximation. I*](cassels1950). See also `blimsup_cthickening_mul_ae_eq`. NB: The `set : α` type ascription is present because of issue #16932 on GitHub. -/ theorem blimsup_thickening_mul_ae_eq (p : ℕ → Prop) (s : ℕ → set α) {M : ℝ} (hM : 0 < M) (r : ℕ → ℝ) (hr : tendsto r at_top (𝓝 0)) : (blimsup (λ i, thickening (M * r i) (s i)) at_top p : set α) =ᵐ[μ] (blimsup (λ i, thickening (r i) (s i)) at_top p : set α) := begin let q : ℕ → Prop := λ i, p i ∧ 0 < r i, have h₁ : blimsup (λ i, thickening (r i) (s i)) at_top p = blimsup (λ i, thickening (r i) (s i)) at_top q, { refine blimsup_congr' (eventually_of_forall $ λ i h, _), replace hi : 0 < r i, { contrapose! h, apply thickening_of_nonpos h, }, simp only [hi, iff_self_and, implies_true_iff], }, have h₂ : blimsup (λ i, thickening (M * r i) (s i)) at_top p = blimsup (λ i, thickening (M * r i) (s i)) at_top q, { refine blimsup_congr' (eventually_of_forall $ λ i h, _), replace h : 0 < r i, { rw ← zero_lt_mul_left hM, contrapose! h, apply thickening_of_nonpos h, }, simp only [h, iff_self_and, implies_true_iff], }, rw [h₁, h₂], exact blimsup_thickening_mul_ae_eq_aux μ q s hM r hr (eventually_of_forall (λ i hi, hi.2)), end
8d765ed2016e7743e41abb2ad9a4c1babf9f4a19
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/multiset/fold_auto.lean
a4d7f482eb3bd99b594cdc0dccc79a83034f31fc
[]
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,927
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.multiset.erase_dup import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # The fold operation for a commutative associative operation over a multiset. -/ namespace multiset /-! ### fold -/ /-- `fold op b s` folds a commutative associative operation `op` over the multiset `s`. -/ def fold {α : Type u_1} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] : α → multiset α → α := foldr op sorry theorem fold_eq_foldr {α : Type u_1} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] (b : α) (s : multiset α) : fold op b s = foldr op (left_comm op is_commutative.comm is_associative.assoc) b s := rfl @[simp] theorem coe_fold_r {α : Type u_1} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] (b : α) (l : List α) : fold op b ↑l = list.foldr op b l := rfl theorem coe_fold_l {α : Type u_1} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] (b : α) (l : List α) : fold op b ↑l = list.foldl op b l := sorry theorem fold_eq_foldl {α : Type u_1} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] (b : α) (s : multiset α) : fold op b s = foldl op (right_comm op is_commutative.comm is_associative.assoc) b s := quot.induction_on s fun (l : List α) => coe_fold_l op b l @[simp] theorem fold_zero {α : Type u_1} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] (b : α) : fold op b 0 = b := rfl @[simp] theorem fold_cons_left {α : Type u_1} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] (b : α) (a : α) (s : multiset α) : fold op b (a ::ₘ s) = op a (fold op b s) := foldr_cons op (fold._proof_1 op) theorem fold_cons_right {α : Type u_1} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] (b : α) (a : α) (s : multiset α) : fold op b (a ::ₘ s) = op (fold op b s) a := sorry theorem fold_cons'_right {α : Type u_1} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] (b : α) (a : α) (s : multiset α) : fold op b (a ::ₘ s) = fold op (op b a) s := sorry theorem fold_cons'_left {α : Type u_1} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] (b : α) (a : α) (s : multiset α) : fold op b (a ::ₘ s) = fold op (op a b) s := eq.mpr (id (Eq._oldrec (Eq.refl (fold op b (a ::ₘ s) = fold op (op a b) s)) (fold_cons'_right op b a s))) (eq.mpr (id (Eq._oldrec (Eq.refl (fold op (op b a) s = fold op (op a b) s)) (is_commutative.comm b a))) (Eq.refl (fold op (op a b) s))) theorem fold_add {α : Type u_1} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] (b₁ : α) (b₂ : α) (s₁ : multiset α) (s₂ : multiset α) : fold op (op b₁ b₂) (s₁ + s₂) = op (fold op b₁ s₁) (fold op b₂ s₂) := sorry theorem fold_singleton {α : Type u_1} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] (b : α) (a : α) : fold op b (a ::ₘ 0) = op a b := sorry theorem fold_distrib {α : Type u_1} {β : Type u_2} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] {f : β → α} {g : β → α} (u₁ : α) (u₂ : α) (s : multiset β) : fold op (op u₁ u₂) (map (fun (x : β) => op (f x) (g x)) s) = op (fold op u₁ (map f s)) (fold op u₂ (map g s)) := sorry theorem fold_hom {α : Type u_1} {β : Type u_2} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] {op' : β → β → β} [is_commutative β op'] [is_associative β op'] {m : α → β} (hm : ∀ (x y : α), m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) : fold op' (m b) (map m s) = m (fold op b s) := sorry theorem fold_union_inter {α : Type u_1} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] [DecidableEq α] (s₁ : multiset α) (s₂ : multiset α) (b₁ : α) (b₂ : α) : op (fold op b₁ (s₁ ∪ s₂)) (fold op b₂ (s₁ ∩ s₂)) = op (fold op b₁ s₁) (fold op b₂ s₂) := sorry @[simp] theorem fold_erase_dup_idem {α : Type u_1} (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] [DecidableEq α] [hi : is_idempotent α op] (s : multiset α) (b : α) : fold op b (erase_dup s) = fold op b s := sorry theorem le_smul_erase_dup {α : Type u_1} [DecidableEq α] (s : multiset α) : ∃ (n : ℕ), s ≤ n •ℕ erase_dup s := sorry end Mathlib
7176f8a30b5cce9e97acedfabfd44b0c0b654b45
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/algebra/category/constructions.lean
cdc51c09b6e04538a585788d620902caea74f77c
[ "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
16,701
lean
-- Copyright (c) 2014 Floris van Doorn. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Floris van Doorn -- This file contains basic constructions on categories, including common categories import .natural_transformation import data.unit data.sigma data.prod data.empty data.bool open eq eq.ops prod namespace category namespace opposite section definition opposite [reducible] {ob : Type} (C : category ob) : category ob := mk (λa b, hom b a) (λ a b c f g, g ∘ f) (λ a, id) (λ a b c d f g h, symm !assoc) (λ a b f, !id_right) (λ a b f, !id_left) definition Opposite [reducible] (C : Category) : Category := Mk (opposite C) --direct construction: -- MK C -- (λa b, hom b a) -- (λ a b c f g, g ∘ f) -- (λ a, id) -- (λ a b c d f g h, symm !assoc) -- (λ a b f, !id_right) -- (λ a b f, !id_left) infixr `∘op`:60 := @compose _ (opposite _) _ _ _ variables {C : Category} {a b c : C} theorem compose_op {f : hom a b} {g : hom b c} : f ∘op g = g ∘ f := rfl theorem op_op' {ob : Type} (C : category ob) : opposite (opposite C) = C := category.rec (λ hom comp id assoc idl idr, refl (mk _ _ _ _ _ _)) C definition op_op : Opposite (Opposite C) = C := (@congr_arg _ _ (@opposite C (@opposite C C)) _ (Category.mk C) (op_op' C)) ⬝ !Category.equal end end opposite definition type_category [reducible] : category Type := mk (λa b, a → b) (λ a b c, function.compose) (λ a, _root_.id) (λ a b c d h g f, symm (function.compose.assoc h g f)) (λ a b f, function.compose.left_id f) (λ a b f, function.compose.right_id f) definition Type_category [reducible] : Category := Mk type_category section open decidable unit empty variables {A : Type} [H : decidable_eq A] include H definition set_hom [reducible] (a b : A) := decidable.rec_on (H a b) (λh, unit) (λh, empty) theorem set_hom_subsingleton [instance] (a b : A) : subsingleton (set_hom a b) := rec_subsingleton definition set_compose [reducible] {a b c : A} (g : set_hom b c) (f : set_hom a b) : set_hom a c := decidable.rec_on (H b c) (λ Hbc g, decidable.rec_on (H a b) (λ Hab f, rec_on_true (trans Hab Hbc) ⋆) (λh f, empty.rec _ f) f) (λh (g : empty), empty.rec _ g) g omit H definition discrete_category (A : Type) [H : decidable_eq A] : category A := mk (λa b, set_hom a b) (λ a b c g f, set_compose g f) (λ a, decidable.rec_on_true rfl ⋆) (λ a b c d h g f, @subsingleton.elim (set_hom a d) _ _ _) (λ a b f, @subsingleton.elim (set_hom a b) _ _ _) (λ a b f, @subsingleton.elim (set_hom a b) _ _ _) local attribute discrete_category [reducible] definition Discrete_category (A : Type) [H : decidable_eq A] := Mk (discrete_category A) section local attribute discrete_category [instance] include H theorem discrete_category.endomorphism {a b : A} (f : a ⟶ b) : a = b := decidable.rec_on (H a b) (λh f, h) (λh f, empty.rec _ f) f theorem discrete_category.discrete {a b : A} (f : a ⟶ b) : eq.rec_on (discrete_category.endomorphism f) f = (ID b) := @subsingleton.elim _ !set_hom_subsingleton _ _ definition discrete_category.rec_on {P : Πa b, a ⟶ b → Type} {a b : A} (f : a ⟶ b) (H : ∀a, P a a id) : P a b f := cast (dcongr_arg3 P rfl (discrete_category.endomorphism f)⁻¹ (@subsingleton.elim _ !set_hom_subsingleton _ _))⁻¹ (H a) end end section open unit bool definition category_one := discrete_category unit definition Category_one := Mk category_one definition category_two := discrete_category bool definition Category_two := Mk category_two end namespace product section open prod definition prod_category [reducible] {obC obD : Type} (C : category obC) (D : category obD) : category (obC × obD) := mk (λa b, hom (pr1 a) (pr1 b) × hom (pr2 a) (pr2 b)) (λ a b c g f, (pr1 g ∘ pr1 f , pr2 g ∘ pr2 f) ) (λ a, (id,id)) (λ a b c d h g f, pair_eq !assoc !assoc ) (λ a b f, prod.eq !id_left !id_left ) (λ a b f, prod.eq !id_right !id_right) definition Prod_category [reducible] (C D : Category) : Category := Mk (prod_category C D) end end product namespace ops notation `type`:max := Type_category postfix `ᵒᵖ`:max := opposite.Opposite infixr `×c`:30 := product.Prod_category attribute type_category [instance] attribute category_one [instance] attribute category_two [instance] attribute product.prod_category [instance] end ops open ops namespace opposite section open functor definition opposite_functor [reducible] {C D : Category} (F : C ⇒ D) : Cᵒᵖ ⇒ Dᵒᵖ := @functor.mk (Cᵒᵖ) (Dᵒᵖ) (λ a, F a) (λ a b f, F f) (λ a, respect_id F a) (λ a b c g f, by apply @respect_comp C D) end end opposite namespace product section open ops functor definition prod_functor [reducible] {C C' D D' : Category} (F : C ⇒ D) (G : C' ⇒ D') : C ×c C' ⇒ D ×c D' := functor.mk (λ a, pair (F (pr1 a)) (G (pr2 a))) (λ a b f, pair (F (pr1 f)) (G (pr2 f))) (λ a, pair_eq !respect_id !respect_id) (λ a b c g f, pair_eq !respect_comp !respect_comp) end end product namespace ops infixr `×f`:30 := product.prod_functor infixr `ᵒᵖᶠ`:max := opposite.opposite_functor end ops section functor_category variables (C D : Category) definition functor_category : category (functor C D) := mk (λa b, natural_transformation a b) (λ a b c g f, natural_transformation.compose g f) (λ a, natural_transformation.id) (λ a b c d h g f, !natural_transformation.assoc) (λ a b f, !natural_transformation.id_left) (λ a b f, !natural_transformation.id_right) end functor_category namespace slice open sigma function variables {ob : Type} {C : category ob} {c : ob} protected definition slice_obs (C : category ob) (c : ob) := Σ(b : ob), hom b c variables {a b : slice.slice_obs C c} protected definition to_ob (a : slice.slice_obs C c) : ob := sigma.pr1 a protected definition to_ob_def (a : slice.slice_obs C c) : slice.to_ob a = sigma.pr1 a := rfl protected definition ob_hom (a : slice.slice_obs C c) : hom (slice.to_ob a) c := sigma.pr2 a -- protected theorem slice_obs_equal (H₁ : to_ob a = to_ob b) -- (H₂ : eq.drec_on H₁ (ob_hom a) = ob_hom b) : a = b := -- sigma.equal H₁ H₂ protected definition slice_hom (a b : slice.slice_obs C c) : Type := Σ(g : hom (slice.to_ob a) (slice.to_ob b)), slice.ob_hom b ∘ g = slice.ob_hom a protected definition hom_hom (f : slice.slice_hom a b) : hom (slice.to_ob a) (slice.to_ob b) := sigma.pr1 f protected definition commute (f : slice.slice_hom a b) : slice.ob_hom b ∘ (slice.hom_hom f) = slice.ob_hom a := sigma.pr2 f -- protected theorem slice_hom_equal (f g : slice_hom a b) (H : hom_hom f = hom_hom g) : f = g := -- sigma.equal H !proof_irrel definition slice_category (C : category ob) (c : ob) : category (slice.slice_obs C c) := mk (λa b, slice.slice_hom a b) (λ a b c g f, sigma.mk (slice.hom_hom g ∘ slice.hom_hom f) (show slice.ob_hom c ∘ (slice.hom_hom g ∘ slice.hom_hom f) = slice.ob_hom a, proof calc slice.ob_hom c ∘ (slice.hom_hom g ∘ slice.hom_hom f) = (slice.ob_hom c ∘ slice.hom_hom g) ∘ slice.hom_hom f : !assoc ... = slice.ob_hom b ∘ slice.hom_hom f : {slice.commute g} ... = slice.ob_hom a : {slice.commute f} qed)) (λ a, sigma.mk id !id_right) (λ a b c d h g f, dpair_eq !assoc !proof_irrel) (λ a b f, sigma.eq !id_left !proof_irrel) (λ a b f, sigma.eq !id_right !proof_irrel) -- We use !proof_irrel instead of rfl, to give the unifier an easier time -- definition slice_category {ob : Type} (C : category ob) (c : ob) : category (Σ(b : ob), hom b c) -- := -- mk (λa b, Σ(g : hom (dpr1 a) (dpr1 b)), dpr2 b ∘ g = dpr2 a) -- (λ a b c g f, dpair (dpr1 g ∘ dpr1 f) -- (show dpr2 c ∘ (dpr1 g ∘ dpr1 f) = dpr2 a, -- proof -- calc -- dpr2 c ∘ (dpr1 g ∘ dpr1 f) = (dpr2 c ∘ dpr1 g) ∘ dpr1 f : !assoc -- ... = dpr2 b ∘ dpr1 f : {dpr2 g} -- ... = dpr2 a : {dpr2 f} -- qed)) -- (λ a, dpair id !id_right) -- (λ a b c d h g f, dpair_eq !assoc !proof_irrel) -- (λ a b f, sigma.equal !id_left !proof_irrel) -- (λ a b f, sigma.equal !id_right !proof_irrel) -- We use !proof_irrel instead of rfl, to give the unifier an easier time definition Slice_category [reducible] (C : Category) (c : C) := Mk (slice_category C c) open category.ops attribute slice_category [instance] variables {D : Category} definition forgetful (x : D) : (Slice_category D x) ⇒ D := functor.mk (λ a, slice.to_ob a) (λ a b f, slice.hom_hom f) (λ a, rfl) (λ a b c g f, rfl) definition postcomposition_functor {x y : D} (h : x ⟶ y) : Slice_category D x ⇒ Slice_category D y := functor.mk (λ a, sigma.mk (slice.to_ob a) (h ∘ slice.ob_hom a)) (λ a b f, ⟨slice.hom_hom f, calc (h ∘ slice.ob_hom b) ∘ slice.hom_hom f = h ∘ (slice.ob_hom b ∘ slice.hom_hom f) : by rewrite assoc ... = h ∘ slice.ob_hom a : by rewrite slice.commute⟩) (λ a, rfl) (λ a b c g f, dpair_eq rfl !proof_irrel) -- -- in the following comment I tried to have (A = B) in the type of a == b, but that doesn't solve the problems -- definition heq2 {A B : Type} (H : A = B) (a : A) (b : B) := a == b -- definition heq2.intro {A B : Type} {a : A} {b : B} (H : a == b) : heq2 (heq.type_eq H) a b := H -- definition heq2.elim {A B : Type} {a : A} {b : B} (H : A = B) (H2 : heq2 H a b) : a == b := H2 -- definition heq2.proof_irrel {A B : Prop} (a : A) (b : B) (H : A = B) : heq2 H a b := -- hproof_irrel H a b -- theorem functor.mk_eq2 {C D : Category} {obF obG : C → D} {homF homG idF idG compF compG} -- (Hob : ∀x, obF x = obG x) -- (Hmor : ∀(a b : C) (f : a ⟶ b), heq2 (congr_arg (λ x, x a ⟶ x b) (funext Hob)) (homF a b f) (homG a b f)) -- : functor.mk obF homF idF compF = functor.mk obG homG idG compG := -- hddcongr_arg4 functor.mk -- (funext Hob) -- (hfunext (λ a, hfunext (λ b, hfunext (λ f, !Hmor)))) -- !proof_irrel -- !proof_irrel -- set_option pp.implicit true -- set_option pp.coercions true -- definition slice_functor : D ⇒ Category_of_categories := -- functor.mk (λ a, Category.mk (slice_obs D a) (slice_category D a)) -- (λ a b f, postcomposition_functor f) -- (λ a, functor.mk_heq -- (λx, sigma.equal rfl !id_left) -- (λb c f, sigma.hequal sorry !heq.refl (hproof_irrel sorry _ _))) -- (λ a b c g f, functor.mk_heq -- (λx, sigma.equal (sorry ⬝ refl (dpr1 x)) sorry) -- (λb c f, sorry)) --the error message generated here is really confusing: the type of the above refl should be -- "@dpr1 D (λ (a_1 : D), a_1 ⟶ a) x = @dpr1 D (λ (a_1 : D), a_1 ⟶ c) x", but the second dpr1 is not even well-typed end slice -- section coslice -- open sigma -- definition coslice {ob : Type} (C : category ob) (c : ob) : category (Σ(b : ob), hom c b) := -- mk (λa b, Σ(g : hom (dpr1 a) (dpr1 b)), g ∘ dpr2 a = dpr2 b) -- (λ a b c g f, dpair (dpr1 g ∘ dpr1 f) -- (show (dpr1 g ∘ dpr1 f) ∘ dpr2 a = dpr2 c, -- proof -- calc -- (dpr1 g ∘ dpr1 f) ∘ dpr2 a = dpr1 g ∘ (dpr1 f ∘ dpr2 a): symm !assoc -- ... = dpr1 g ∘ dpr2 b : {dpr2 f} -- ... = dpr2 c : {dpr2 g} -- qed)) -- (λ a, dpair id !id_left) -- (λ a b c d h g f, dpair_eq !assoc !proof_irrel) -- (λ a b f, sigma.equal !id_left !proof_irrel) -- (λ a b f, sigma.equal !id_right !proof_irrel) -- -- theorem slice_coslice_opp {ob : Type} (C : category ob) (c : ob) : -- -- coslice C c = opposite (slice (opposite C) c) := -- -- sorry -- end coslice section arrow open sigma eq.ops -- theorem concat_commutative_squares {ob : Type} {C : category ob} {a1 a2 a3 b1 b2 b3 : ob} -- {f1 : a1 => b1} {f2 : a2 => b2} {f3 : a3 => b3} {g2 : a2 => a3} {g1 : a1 => a2} -- {h2 : b2 => b3} {h1 : b1 => b2} (H1 : f2 ∘ g1 = h1 ∘ f1) (H2 : f3 ∘ g2 = h2 ∘ f2) -- : f3 ∘ (g2 ∘ g1) = (h2 ∘ h1) ∘ f1 := -- calc -- f3 ∘ (g2 ∘ g1) = (f3 ∘ g2) ∘ g1 : assoc -- ... = (h2 ∘ f2) ∘ g1 : {H2} -- ... = h2 ∘ (f2 ∘ g1) : symm assoc -- ... = h2 ∘ (h1 ∘ f1) : {H1} -- ... = (h2 ∘ h1) ∘ f1 : assoc -- definition arrow {ob : Type} (C : category ob) : category (Σ(a b : ob), hom a b) := -- mk (λa b, Σ(g : hom (dpr1 a) (dpr1 b)) (h : hom (dpr2' a) (dpr2' b)), -- dpr3 b ∘ g = h ∘ dpr3 a) -- (λ a b c g f, dpair (dpr1 g ∘ dpr1 f) (dpair (dpr2' g ∘ dpr2' f) (concat_commutative_squares (dpr3 f) (dpr3 g)))) -- (λ a, dpair id (dpair id (id_right ⬝ (symm id_left)))) -- (λ a b c d h g f, dtrip_eq2 assoc assoc !proof_irrel) -- (λ a b f, trip.equal2 id_left id_left !proof_irrel) -- (λ a b f, trip.equal2 id_right id_right !proof_irrel) -- make these definitions private? variables {ob : Type} {C : category ob} protected definition arrow_obs (ob : Type) (C : category ob) := Σ(a b : ob), hom a b variables {a b : category.arrow_obs ob C} protected definition src (a : category.arrow_obs ob C) : ob := sigma.pr1 a protected definition dst (a : category.arrow_obs ob C) : ob := sigma.pr2' a protected definition to_hom (a : category.arrow_obs ob C) : hom (category.src a) (category.dst a) := sigma.pr3 a protected definition arrow_hom (a b : category.arrow_obs ob C) : Type := Σ (g : hom (category.src a) (category.src b)) (h : hom (category.dst a) (category.dst b)), category.to_hom b ∘ g = h ∘ category.to_hom a protected definition hom_src (m : category.arrow_hom a b) : hom (category.src a) (category.src b) := sigma.pr1 m protected definition hom_dst (m : category.arrow_hom a b) : hom (category.dst a) (category.dst b) := sigma.pr2' m protected definition commute (m : category.arrow_hom a b) : category.to_hom b ∘ (category.hom_src m) = (category.hom_dst m) ∘ category.to_hom a := sigma.pr3 m definition arrow (ob : Type) (C : category ob) : category (category.arrow_obs ob C) := mk (λa b, category.arrow_hom a b) (λ a b c g f, sigma.mk (category.hom_src g ∘ category.hom_src f) (sigma.mk (category.hom_dst g ∘ category.hom_dst f) (show category.to_hom c ∘ (category.hom_src g ∘ category.hom_src f) = (category.hom_dst g ∘ category.hom_dst f) ∘ category.to_hom a, proof calc category.to_hom c ∘ (category.hom_src g ∘ category.hom_src f) = (category.to_hom c ∘ category.hom_src g) ∘ category.hom_src f : by rewrite assoc ... = (category.hom_dst g ∘ category.to_hom b) ∘ category.hom_src f : by rewrite category.commute ... = category.hom_dst g ∘ (category.to_hom b ∘ category.hom_src f) : by rewrite assoc ... = category.hom_dst g ∘ (category.hom_dst f ∘ category.to_hom a) : by rewrite category.commute ... = (category.hom_dst g ∘ category.hom_dst f) ∘ category.to_hom a : by rewrite assoc qed) )) (λ a, sigma.mk id (sigma.mk id (!id_right ⬝ (symm !id_left)))) (λ a b c d h g f, ndtrip_eq !assoc !assoc !proof_irrel) (λ a b f, ndtrip_equal !id_left !id_left !proof_irrel) (λ a b f, ndtrip_equal !id_right !id_right !proof_irrel) end arrow end category -- definition foo : category (sorry) := -- mk (λa b, sorry) -- (λ a b c g f, sorry) -- (λ a, sorry) -- (λ a b c d h g f, sorry) -- (λ a b f, sorry) -- (λ a b f, sorry)
1e6c65ae1c77c5c5fd91f550e8ef9e723e10018a
5c7fe6c4a9d4079b5457ffa5f061797d42a1cd65
/src/exercises/src_26_set_difference.lean
b19ecc5b8a2a656e037bad3125c9122c3e424931
[]
no_license
gihanmarasingha/mth1001_tutorial
8e0817feeb96e7c1bb3bac49b63e3c9a3a329061
bb277eebd5013766e1418365b91416b406275130
refs/heads/master
1,675,008,746,310
1,607,993,443,000
1,607,993,443,000
321,511,270
3
0
null
null
null
null
UTF-8
Lean
false
false
1,726
lean
import data.set import logic.basic open set namespace mth1001 section set_difference variable U : Type* -- We'll have sets on the type `U`. variables A B C : set U -- In addition to `mem_inter_iff` and `mem_union_eq` from the previous file, we'll -- now use `mem_diff` for the set difference example (x : U) : x ∈ A \ B ↔ x ∈ A ∧ x ∉ B := by rw mem_diff -- We need the follow two lines to admit classical reasoning. open classical local attribute [instance] prop_decidable -- In addition to the rules of propositional logic given in the previous file, we use -- De Morgan's laws, as follows. example (p q : Prop) : ¬(p ∧ q) ↔ ¬p ∨ ¬q := by rw not_and_distrib example (p q : Prop) : ¬(p ∨ q) ↔ ¬p ∧ ¬q := by rw not_or_distrib example : A \ (B ∩ C) = (A \ B) ∪ (A \ C) := begin ext, -- Assume `x : U`. It suffices to prove `x ∈ A \ (B ∩ C) ↔ x ∈ (A \ B) ∪ (A \ C)`. -- Rewrite using definitions of set difference, intersection, and union. rw [mem_diff, mem_union_eq, mem_inter_iff, mem_diff, mem_diff], rw not_and_distrib, -- De Morgan's law rw and_or_distrib_left, -- Distributivity of conjunction over disjunction end -- Exercise 138: -- In addition to De Morgan's law, the propositional logic aspect of the following problem requires -- several applications of the laws featured in the previous file. If you get irritated, the -- `tauto` tactic will close many goals in propositional logic. example : A \ (B ∪ C) = (A \ B) ∩ (A \ C) := begin ext, rw [mem_diff, mem_union_eq, mem_inter_iff, mem_diff, mem_diff], rw not_or_distrib, -- De Morgan's law rw and_comm (x ∈ A) (x ∉ B), sorry end end set_difference end mth1001
86c7d7bc5af52660f084861e93b5d4b958b86153
159fed64bfae88f3b6a6166836d6278f953bcbf9
/Structure/FunctorProperties.lean
be5929b35ca4c3ddb914d517446e1dfd28bf5990
[ "MIT" ]
permissive
SReichelt/lean4-experiments
3e56830c8b2fbe3814eda071c48e3c8810d254a8
ff55357a01a34a91bf670d712637480089085ee4
refs/heads/main
1,683,977,454,907
1,622,991,121,000
1,622,991,121,000
340,765,677
2
0
null
null
null
null
UTF-8
Lean
false
false
3,413
lean
-- An abstract formalization of "isomorphism is equality up to relabeling" -- ------------------------------------------------------------------------- -- -- See `README.md` for more info. -- -- Some special properties of structure functors. Currently not used in the rest of the formalization. import Structure.Basic open GeneralizedFunctor open StructureFunctor set_option autoBoundImplicitLocal false namespace FunctorProperties variable {S T : Structure} (F : StructureFunctor S T) -- If we interpret `≃` as equality, we can pretend that functors are just functions and define their -- properties accordingly. Again, note that these definitions contain data. -- However, for the definitions to be well-behaved, we need to add some functoriality conditions. def Injective := GeneralizedFunctor F.map id -- `∀ a b, F a ≃ F b → a ≃ b` plus functoriality def Surjective := Σ' h : (∀ b, Σ' a, IsType.type (F a ≃ b)), Σ' φ : Functor (λ b => (h b).fst), GeneralizedNaturalTransformation (comp.genFun' F.map F.functor φ) id.genFun def Bijective := PProd (Injective F) (Surjective F) -- We can even build an inverse (= adjoint) functor for any functor that is bijective according to this -- definition, even though we do not assume classical logic. This works because the equivalences in -- `Structure` can hold the data we are defining here. Note that if we were dealing with propositions and -- using `∃` instead of `Σ`, obtaining the inverse functor would require classical logic. -- -- (This is somewhat related to the fact that in HoTT, choice holds in universes above `Prop`.) -- -- The inverse functor is unique (modulo functor equivalence). section Inverse variable (h : Bijective F) def inverseElement (b : T) := (h.snd.fst b).fst namespace inverseElement def is_inverse (b : T) : F (inverseElement F h b) ≃ b := (h.snd.fst b).snd def is_inverse' (a : S) : inverseElement F h (F a) ≃ a := h.fst.mapEquiv (is_inverse F h (F a)) end inverseElement -- This is just a very terse way of writing the classical proof that the inverse element is unique. -- Writing it in this way has the advantage that `PiEquiv.transport` already contains the proof that the -- result is a functor. def uniqueValueFunctor := Pi.PiEquiv.transport.invFunctor (inverseElement.is_inverse F h) def inverseFunctor := comp.genFun' (inverseElement F h) (uniqueValueFunctor F h) h.fst def inverse : StructureFunctor T S := { map := inverseElement F h, functor := inverseFunctor F h } namespace inverse -- TODO: For the naturality condition, we should probably build some infrastructure around the interaction -- between `PiEquiv` and `GeneralizedNaturalTransformation`. -- We may also need to add some conditions to our definitions. def leftInv : inverse F h ⊙ F ≃ @idFun S := { ext := inverseElement.is_inverse' F h, nat := sorry } def rightInv : F ⊙ inverse F h ≃ @idFun T := { ext := inverseElement.is_inverse F h, nat := sorry } instance isInverse : IsInverse F (inverse F h) := { leftInv := leftInv F h, rightInv := rightInv F h, lrCompat := sorry, rlCompat := sorry } end inverse -- Now we can build a `StructureEquiv` from any bijective functor. def functorToEquiv : StructureEquiv S T := { toFun := F, invFun := inverse F h, isInv := inverse.isInverse F h } end Inverse end FunctorProperties
f861454cec27741a3d5119eb4aeacaadbfdff576
076f5040b63237c6dd928c6401329ed5adcb0e44
/assignments/hw7_bool_sat/bool_sat.lean
bb007c4f189d0098804deb937c08975987ae3259
[]
no_license
kevinsullivan/uva-cs-dm-f19
0f123689cf6cb078f263950b18382a7086bf30be
09a950752884bd7ade4be33e9e89a2c4b1927167
refs/heads/master
1,594,771,841,541
1,575,853,850,000
1,575,853,850,000
205,433,890
4
9
null
1,571,592,121,000
1,567,188,539,000
Lean
UTF-8
Lean
false
false
6,000
lean
import .prop_logic open prop_logic open prop_logic.var open prop_logic.unOp open prop_logic.binOp open prop_logic.pExp /- *** SATISFIABILITY solver *** This module implements a model finder and thus a satisfiability solver. A propositional logic model finder is a program that when given a propositional logic expression searches the possible interpretations for one or more under which the expression evaluates to true. Such an interpretation is called a model. Determining that there is at least one model is to show that the expression is satisfiable. If all interpretations make the expression true, it is valid. If no interpretations are models, it is said to be unsatisfiable. This presentation of our model finder is a capstone of the work we've done so far this semester. It works by generating the 2^n possible interpretations of a given propositional logic formula, where n is the number of distinct variables in the formula, and by evaluating the given formula under each of the interpretations to produce a list of Boolean truth values for that expression and each intepretations. True results correspond to models. The insights on which the design of our model finder is based are (1) that each row in a truth table in which values are given for variables represents an interpretation; and (2) in a truth table for an expression based on a set of n variables, with 2^n rows (interpretations), the truth table entry for the k'th variable in the m'th row is given by the k'th bit in the binary representation of the number, m. -/ /- We now define the function, mth_bit_from_right_in_n: ℕ → ℕ → ℕ Given (m n : nat), return m'th bit from the right in binary representation of n. Formerly called mrbn. However, the mrbn function returned a bool. This function just returns 0 or 1 of type nat. We then provide the following function to turn such a nat into a bool in the usual way, with 0 mapping to ff and 1 (or any other nat) mapping to tt. -/ def mth_bit_from_right_in_n: ℕ → ℕ → ℕ | 0 n := n % 2 | (nat.succ m') n := mth_bit_from_right_in_n m' (n/2) /- Convert bit value 0 or 1 (of type nat) to corresponding Boolean value. -/ def bit_to_bool : ℕ → bool | 0 := ff | _ := tt /- We now define the function, mth_interp_n_vars (m n: ℕ) : var → bool Given (m n : ℕ) return the m'th interpretation in an enumeration of the 2^n interpretations given n variables. Recall that in our formalization of the semantics of propositional logic, an interpretation is given as a function from var to bool, and there is an infinite number of values of type var. This function just assigns the "default" value ff to each variable of the form (mkVar k) where k >= n, and returns the "all false" intepretation function when m >= 2^n. Otherwise it returns an interpretation where the first n truth values are given by the n bits in the binary expansion of m. -/ def mth_interp_n_vars (m n: ℕ) : var → bool := if (m >= 2^n) then λ v, ff else λ (v : var), match v with | (mkVar i) := if i >= n then ff else bit_to_bool (mth_bit_from_right_in_n i m) end /- We now define interps_helper : nat → nat → list (var → bool) This is a helper function for the primary function that follows. The primary function, which is non-recursive and takes an argument, n, calls this recursive function with the values m=2^n and n to build a list of 2^n interpretations for n variables. Given arguments (m : nat), the number of interps to generate and (n : nat), the number of relevant variables defined to be the maximum index of any variable in the expression plus one, this function returns a list of m interpretations. In practice it is only called by the primary function, below, and is always called with m = 2^n and n. Using recursion it "loops" m=2^n times to build a list of the required 2^n interpretations, where each such interpretation gives a correct value to each relevant variable and default false values to variables with indices greater than or equal to the number of relevant variables (effectively filling each row with false values for the infinite number of variables beyond the last relevant one.) -/ def interps_helper : nat → nat → list (var → bool) | 0 n := list.cons (mth_interp_n_vars 0 n) list.nil | (nat.succ m') n := list.cons (mth_interp_n_vars (nat.succ m') n) (interps_helper m' n) /- Primary function: return list of all possible interpretations for n variables -/ def interps_for_n_vars : ℕ → list (var → bool) | nat.zero := [] | n := interps_helper (2^n-1) n /- We now define the main "model-identifying function" defined in this lean module: truth_table_results (e : pExp) (n : ℕ) : list bool It returns a list of the Boolean results of evaluating the given propositional logic expression, e, under each of its possible interpretations. It returns a list of the truth table "result" values for the given expression under each interpretation. The second argument, n, indicates the number of relevant variables in the expression, p, which is equal to one more than the highest index of and such variable. So, ... Precondition: if the variable expressions in e are (varExp (mkvar 0)), varExp (mkVar 1), and varExp (mkvar 3), for example, then the value of the second argument, n, should be set to 4. And the resulting truth table will contain 16 rows/interpretations, in which (mkvar 2) will also be given values. These values won't affect how p is evaluated, because that variable does not appear in p, but the variable nevertheless has to appear in the truth table for this code to work. A good practice is to give your var objects indices from 0 to n-1, using (mkVar 0), ..., (mkVar n-1), in order with no gaps and to use n as the value of the second argument. -/ def truth_table_results (p : pExp) (n : ℕ) : list bool := list.map (λ (i : var → bool), pEval p i) (interps_for_n_vars n)
f2a40dd04dd0dc9206c525d8ace5e72517e3b133
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/preadditive/opposite.lean
f846ccb1ba59d088919aff6d432573168bc0c228
[ "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,064
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Adam Topaz, Johan Commelin, Joël Riou -/ import category_theory.preadditive.additive_functor import logic.equiv.transfer_instance /-! # If `C` is preadditive, `Cᵒᵖ` has a natural preadditive structure. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ open opposite namespace category_theory variables (C : Type*) [category C] [preadditive C] instance : preadditive Cᵒᵖ := { hom_group := λ X Y, equiv.add_comm_group (op_equiv X Y), add_comp' := λ X Y Z f f' g, congr_arg quiver.hom.op (preadditive.comp_add _ _ _ g.unop f.unop f'.unop), comp_add' := λ X Y Z f g g', congr_arg quiver.hom.op (preadditive.add_comp _ _ _ g.unop g'.unop f.unop), } instance module_End_left {X : Cᵒᵖ} {Y : C} : module (End X) (unop X ⟶ Y) := { smul_add := λ r f g, preadditive.comp_add _ _ _ _ _ _, smul_zero := λ r, limits.comp_zero, add_smul := λ r s f, preadditive.add_comp _ _ _ _ _ _, zero_smul := λ f, limits.zero_comp } @[simp] lemma unop_zero (X Y : Cᵒᵖ) : (0 : X ⟶ Y).unop = 0 := rfl @[simp] lemma unop_add {X Y : Cᵒᵖ} (f g : X ⟶ Y) : (f + g).unop = f.unop + g.unop := rfl @[simp] lemma unop_zsmul {X Y : Cᵒᵖ} (k : ℤ) (f : X ⟶ Y) : (k • f).unop = k • f.unop := rfl @[simp] lemma unop_neg {X Y : Cᵒᵖ}(f : X ⟶ Y) : (-f).unop = -(f.unop) := rfl @[simp] lemma op_zero (X Y : C) : (0 : X ⟶ Y).op = 0 := rfl @[simp] lemma op_add {X Y : C} (f g : X ⟶ Y) : (f + g).op = f.op + g.op := rfl @[simp] lemma op_zsmul {X Y : C} (k : ℤ) (f : X ⟶ Y) : (k • f).op = k • f.op := rfl @[simp] lemma op_neg {X Y : C}(f : X ⟶ Y) : (-f).op = -(f.op) := rfl variable {C} /-- `unop` induces morphisms of monoids on hom groups of a preadditive category -/ @[simps] def unop_hom (X Y : Cᵒᵖ) : (X ⟶ Y) →+ (opposite.unop Y ⟶ opposite.unop X) := add_monoid_hom.mk' (λ f, f.unop) $ λ f g, unop_add _ f g @[simp] lemma unop_sum (X Y : Cᵒᵖ) {ι : Type*} (s : finset ι) (f : ι → (X ⟶ Y)) : (s.sum f).unop = s.sum (λ i, (f i).unop) := (unop_hom X Y).map_sum _ _ /-- `op` induces morphisms of monoids on hom groups of a preadditive category -/ @[simps] def op_hom (X Y : C) : (X ⟶ Y) →+ (opposite.op Y ⟶ opposite.op X) := add_monoid_hom.mk' (λ f, f.op) $ λ f g, op_add _ f g @[simp] lemma op_sum (X Y : C) {ι : Type*} (s : finset ι) (f : ι → (X ⟶ Y)) : (s.sum f).op = s.sum (λ i, (f i).op) := (op_hom X Y).map_sum _ _ variables {D : Type*} [category D] [preadditive D] instance functor.op_additive (F : C ⥤ D) [F.additive] : F.op.additive := {} instance functor.right_op_additive (F : Cᵒᵖ ⥤ D) [F.additive] : F.right_op.additive := {} instance functor.left_op_additive (F : C ⥤ Dᵒᵖ) [F.additive] : F.left_op.additive := {} instance functor.unop_additive (F : Cᵒᵖ ⥤ Dᵒᵖ) [F.additive] : F.unop.additive := {} end category_theory
73eb6a9ea036f6fdf7f90813157c106263bc18ec
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/unif_issue.lean
3f1ec2cee9d45d6cd8a0699f7a5e0d4db730b1a1
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,414
lean
import Lean open Lean #eval toString $ Unhygienic.run $ do a ← `(Nat.one); let rhs_0 : _ := fun (a : Lean.Syntax) (b : Lean.Syntax) => pure Syntax.missing; let rhs_1 : _ := fun (_a : _) => pure Lean.Syntax.missing; let discr_2 : _ := a; ite (Lean.Syntax.isOfKind discr_2 (Lean.mkNameStr (Lean.mkNameStr (Lean.mkNameStr (Lean.mkNameStr Lean.Name.anonymous "Lean") "Parser") "Term") "add")) (let discr_3 : _ := Lean.Syntax.getArg discr_2 0; let discr_4 : _ := Lean.Syntax.getArg discr_2 1; let discr_5 : _ := Lean.Syntax.getArg discr_2 2; rhs_0 discr_3 discr_5) (let discr_7 : _ := a; rhs_1 Unit.unit) #check (pure 0 : Id Nat) #check (let rhs := fun a => pure a; rhs 0 : Id Nat) new_frontend open Lean #check toString $ Unhygienic.run $ do a ← `(Nat.one); let rhs_0 : _ := fun (a : Lean.Syntax) (b : Lean.Syntax) => pure Syntax.missing; let rhs_1 : _ := fun (_a : _) => pure Lean.Syntax.missing; let discr_2 : _ := a; ite (Lean.Syntax.isOfKind discr_2 (Lean.mkNameStr (Lean.mkNameStr (Lean.mkNameStr (Lean.mkNameStr Lean.Name.anonymous "Lean") "Parser") "Term") "add")) (let discr_3 : _ := Lean.Syntax.getArg discr_2 0; let discr_4 : _ := Lean.Syntax.getArg discr_2 1; let discr_5 : _ := Lean.Syntax.getArg discr_2 2; rhs_0 discr_3 discr_5) (let discr_7 : _ := a; rhs_1 Unit.unit)
d998feeaa9459a0bcde7d76d459f56f9e077122f
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/topological_fiber_bundle.lean
2746dcfe22147e287e00b1406da1e5736516fcdd
[ "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
23,840
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.local_homeomorph /-! # Fiber bundles A topological fiber bundle with fiber F over a base B is a space projecting on B for which the fibers are all homeomorphic to F, such that the local situation around each point is a direct product. We define a predicate `is_topological_fiber_bundle F p` saying that `p : Z → B` is a topological fiber bundle with fiber `F`. It is in general nontrivial to construct a fiber bundle. A way is to start from the knowledge of how changes of local trivializations act on the fiber. From this, one can construct the total space of the bundle and its topology by a suitable gluing construction. The main content of this file is an implementation of this construction: starting from an object of type `topological_fiber_bundle_core` registering the trivialization changes, one gets the corresponding fiber bundle and projection. ## Main definitions `bundle_trivialization F p` : structure extending local homeomorphisms, defining a local trivialization of a topological space `Z` with projection `p` and fiber `F`. `is_topological_fiber_bundle F p` : Prop saying that the map `p` between topological spaces is a fiber bundle with fiber `F`. `topological_fiber_bundle_core ι B F` : structure registering how changes of coordinates act on the fiber `F` above open subsets of `B`, where local trivializations are indexed by ι. Let `Z : topological_fiber_bundle_core ι B F`. Then we define `Z.total_space` : the total space of `Z`, defined as a Type as `B × F`, but with a twisted topology coming from the fiber bundle structure `Z.proj` : projection from `Z.total_space` to `B`. It is continuous. `Z.fiber x` : the fiber above `x`, homeomorphic to `F` (and defeq to `F` as a type). `Z.local_triv i`: for `i : ι`, a local homeomorphism from `Z.total_space` to `B × F`, that realizes a trivialization above the set `Z.base_set i`, which is an open set in `B`. ## Implementation notes A topological fiber bundle with fiber F over a base B is a family of spaces isomorphic to F, indexed by B, which is locally trivial in the following sense: there is a covering of B by open sets such that, on each such open set `s`, the bundle is isomorphic to `s × F`. To construct a fiber bundle formally, the main data is what happens when one changes trivializations from `s × F` to `s' × F` on `s ∩ s'`: one should get a family of homeomorphisms of `F`, depending continuously on the base point, satisfying basic compatibility conditions (cocycle property). Useful classes of bundles can then be specified by requiring that these homeomorphisms of `F` belong to some subgroup, preserving some structure (the "structure group of the bundle"): then these structures are inherited by the fibers of the bundle. Given such trivialization change data (encoded below in a structure called `topological_fiber_bundle_core`), one can construct the fiber bundle. The intrinsic canonical mathematical construction is the following. The fiber above x is the disjoint union of F over all trivializations, modulo the gluing identifications: one gets a fiber which is isomorphic to F, but non-canonically (each choice of one of the trivializations around x gives such an isomorphism). Given a trivialization over a set `s`, one gets an isomorphism between `s × F` and `proj^{-1} s`, by using the identification corresponding to this trivialization. One chooses the topology on the bundle that makes all of these into homeomorphisms. For the practical implementation, it turns out to be more convenient to avoid completely the gluing and quotienting construction above, and to declare above each `x` that the fiber is `F`, but thinking that it corresponds to the `F` coming from the choice of one trivialization around `x`. This has several practical advantages: * without any work, one gets a topological space structure on the fiber. And if `F` has more structure it is inherited for free by the fiber. * In the trivial situation of the trivial bundle where there is only one chart and one trivialization, this construction gives the product space B × F with the product topology. In the case of the tangent bundle of manifolds, this also implies that on vector spaces the derivative and the manifold derivative are equal. A drawback is that some silly constructions will typecheck: in the case of the tangent bundle, one can add two vectors in different tangent spaces (as they both are elements of F from the point of view of Lean). To solve this, one could mark the tangent space as irreducible, but then one would lose the identification of the tangent space to F with F. There is however a big advantage of this situation: even if Lean can not check that two basepoints are defeq, it will accept the fact that the tangent spaces are the same. For instance, if two maps f and g are locally inverse to each other, one can express that the composition of their derivatives is the identity of `tangent_space I x`. One could fear issues as this composition goes from `tangent_space I x` to `tangent_space I (g (f x))` (which should be the same, but should not be obvious to Lean as it does not know that `g (f x) = x`). As these types are the same to Lean (equal to `F`), there are in fact no dependent type difficulties here! For this construction of a fiber bundle from a `topological_fiber_bundle_core`, we should thus choose for each `x` one specific trivialization around it. We include this choice in the definition of the `topological_fiber_bundle_core`, as it makes some constructions more functorial and it is a nice way to say that the trivializations cover the whole space B. With this definition, the type of the fiber bundle space constructed from the core data is just `B × F`, but the topology is not the product one. We also take the indexing type (indexing all the trivializations) as a parameter to the fiber bundle core: it could always be taken as a subtype of all the maps from open subsets of B to continuous maps of F, but in practice it will sometimes be something else. For instance, on a manifold, one will use the set of charts as a good parameterization for the trivializations of the tangent bundle. Or for the pullback of a `topological_fiber_bundle_core`, the indexing type will be the same as for the initial bundle. ## Tags Fiber bundle, topological bundle, vector bundle, local trivialization, structure group -/ variables {ι : Type*} {B : Type*} {F : Type*} open topological_space set open_locale topological_space section topological_fiber_bundle variables {Z : Type*} [topological_space B] [topological_space Z] [topological_space F] (proj : Z → B) variable (F) /-- A structure extending local homeomorphisms, defining a local trivialization of a projection `proj : Z → B` with fiber `F`, as a local homeomorphism between `Z` and `B × F` defined between two sets of the form `proj ⁻¹' base_set` and `base_set × F`, acting trivially on the first coordinate. -/ structure bundle_trivialization extends local_homeomorph Z (B × F) := (base_set : set B) (open_base_set : is_open base_set) (source_eq : source = proj ⁻¹' base_set) (target_eq : target = set.prod base_set univ) (proj_to_fun : ∀ p ∈ source, (to_fun p).1 = proj p) /-- A topological fiber bundle with fiber F over a base B is a space projecting on B for which the fibers are all homeomorphic to F, such that the local situation around each point is a direct product. -/ def is_topological_fiber_bundle : Prop := ∀ x : Z, ∃e : bundle_trivialization F proj, x ∈ e.source variables {F} {proj} /-- In the domain of a bundle trivialization, the projection is continuous-/ lemma bundle_trivialization.continuous_at_proj (e : bundle_trivialization F proj) {x : Z} (ex : x ∈ e.source) : continuous_at proj x := begin assume s hs, obtain ⟨t, st, t_open, xt⟩ : ∃ t ⊆ s, is_open t ∧ proj x ∈ t, from mem_nhds_sets_iff.1 hs, rw e.source_eq at ex, let u := e.base_set ∩ t, have u_open : is_open u := is_open_inter e.open_base_set t_open, have xu : proj x ∈ u := ⟨ex, xt⟩, /- Take a small enough open neighborhood u of `proj x`, contained in a trivialization domain o. One should show that its preimage is open. -/ suffices : is_open (proj ⁻¹' u), { have : proj ⁻¹' u ∈ 𝓝 x := mem_nhds_sets this xu, apply filter.mem_sets_of_superset this, exact preimage_mono (subset.trans (inter_subset_right _ _) st) }, -- to do this, rewrite `proj ⁻¹' u` in terms of the trivialization, and use its continuity. have : proj ⁻¹' u = e.to_fun ⁻¹' (set.prod u univ) ∩ e.source, { ext p, split, { assume h, have : p ∈ e.source, { rw e.source_eq, have : u ⊆ e.base_set := inter_subset_left _ _, exact preimage_mono this h }, simp [this, e.proj_to_fun, h.1, h.2] }, { rintros ⟨h, h_source⟩, simpa [e.proj_to_fun, h_source] using h } }, rw [this, inter_comm], exact continuous_on.preimage_open_of_open e.continuous_to_fun e.open_source (is_open_prod u_open is_open_univ) end /-- The projection from a topological fiber bundle to its base is continuous. -/ lemma is_topological_fiber_bundle.continuous_proj (h : is_topological_fiber_bundle F proj) : continuous proj := begin rw continuous_iff_continuous_at, assume x, rcases h x with ⟨e, ex⟩, exact e.continuous_at_proj ex end /-- The projection from a topological fiber bundle to its base is an open map. -/ lemma is_topological_fiber_bundle.is_open_map_proj (h : is_topological_fiber_bundle F proj) : is_open_map proj := begin assume s hs, rw is_open_iff_forall_mem_open, assume x xs, obtain ⟨y, ys, yx⟩ : ∃ y, y ∈ s ∧ proj y = x, from (mem_image _ _ _).1 xs, obtain ⟨e, he⟩ : ∃ (e : bundle_trivialization F proj), y ∈ e.source, from h y, refine ⟨proj '' (s ∩ e.source), image_subset _ (inter_subset_left _ _), _, ⟨y, ⟨ys, he⟩, yx⟩⟩, have : ∀z ∈ s ∩ e.source, prod.fst (e.to_fun z) = proj z := λz hz, e.proj_to_fun z hz.2, rw [← image_congr this, image_comp], have : is_open (e.to_fun '' (s ∩ e.source)) := e.to_local_homeomorph.image_open_of_open (is_open_inter hs e.to_local_homeomorph.open_source) (inter_subset_right _ _), exact is_open_map_fst _ this end /-- The first projection in a product is a topological fiber bundle. -/ lemma is_topological_fiber_bundle_fst : is_topological_fiber_bundle F (prod.fst : B × F → B) := begin let F : bundle_trivialization F (prod.fst : B × F → B) := { base_set := univ, open_base_set := is_open_univ, source_eq := rfl, target_eq := by simp, proj_to_fun := by simp, ..local_homeomorph.refl _ }, exact λx, ⟨F, by simp⟩ end /-- The second projection in a product is a topological fiber bundle. -/ lemma is_topological_fiber_bundle_snd : is_topological_fiber_bundle F (prod.snd : F × B → B) := begin let F : bundle_trivialization F (prod.snd : F × B → B) := { base_set := univ, open_base_set := is_open_univ, source_eq := rfl, target_eq := by simp, proj_to_fun := λp, by { simp, refl }, ..(homeomorph.prod_comm F B).to_local_homeomorph }, exact λx, ⟨F, by simp⟩ end end topological_fiber_bundle /-- Core data defining a locally trivial topological bundle with fiber `F` over a topological space `B`. Note that "bundle" is used in its mathematical sense. This is the (computer science) bundled version, i.e., all the relevant data is contained in the following structure. A family of local trivializations is indexed by a type ι, on open subsets `base_set i` for each `i : ι`. Trivialization changes from `i` to `j` are given by continuous maps `coord_change i j` from `base_set i ∩ base_set j` to the set of homeomorphisms of `F`, but we express them as maps `B → F → F` and require continuity on `(base_set i ∩ base_set j) × F` to avoid the topology on the space of continuous maps on `F`. -/ structure topological_fiber_bundle_core (ι : Type*) (B : Type*) [topological_space B] (F : Type*) [topological_space F] := (base_set : ι → set B) (is_open_base_set : ∀i, is_open (base_set i)) (index_at : B → ι) (mem_base_set_at : ∀x, x ∈ base_set (index_at x)) (coord_change : ι → ι → B → F → F) (coord_change_self : ∀i, ∀ x ∈ base_set i, ∀v, coord_change i i x v = v) (coord_change_continuous : ∀i j, continuous_on (λp : B × F, coord_change i j p.1 p.2) (set.prod ((base_set i) ∩ (base_set j)) univ)) (coord_change_comp : ∀i j k, ∀x ∈ (base_set i) ∩ (base_set j) ∩ (base_set k), ∀v, (coord_change j k x) (coord_change i j x v) = coord_change i k x v) attribute [simp] topological_fiber_bundle_core.mem_base_set_at namespace topological_fiber_bundle_core variables [topological_space B] [topological_space F] (Z : topological_fiber_bundle_core ι B F) include Z /-- The index set of a topological fiber bundle core, as a convenience function for dot notation -/ @[nolint unused_arguments] def index := ι /-- The base space of a topological fiber bundle core, as a convenience function for dot notation -/ @[nolint unused_arguments] def base := B /-- The fiber of a topological fiber bundle core, as a convenience function for dot notation and typeclass inference -/ @[nolint unused_arguments] def fiber (x : B) := F instance topological_space_fiber (x : B) : topological_space (Z.fiber x) := by { dsimp [fiber], apply_instance } /-- Total space of a topological bundle created from core. It is equal to `B × F`, but as it is not marked as reducible, typeclass inference will not infer the wrong topology, and will use the instance `topological_fiber_bundle_core.to_topological_space` with the right topology. -/ @[nolint unused_arguments] def total_space := B × F /-- The projection from the total space of a topological fiber bundle core, on its base. -/ @[simp] def proj : Z.total_space → B := λp, p.1 /-- Local homeomorphism version of the trivialization change. -/ def triv_change (i j : ι) : local_homeomorph (B × F) (B × F) := { source := set.prod (Z.base_set i ∩ Z.base_set j) univ, target := set.prod (Z.base_set i ∩ Z.base_set j) univ, to_fun := λp, ⟨p.1, Z.coord_change i j p.1 p.2⟩, inv_fun := λp, ⟨p.1, Z.coord_change j i p.1 p.2⟩, map_source := λp hp, by simpa using hp, map_target := λp hp, by simpa using hp, left_inv := begin rintros ⟨x, v⟩ hx, simp only [prod_mk_mem_set_prod_eq, mem_inter_eq, and_true, mem_univ] at hx, rw [Z.coord_change_comp, Z.coord_change_self], { exact hx.1 }, { simp [hx] } end, right_inv := begin rintros ⟨x, v⟩ hx, simp only [prod_mk_mem_set_prod_eq, mem_inter_eq, and_true, mem_univ] at hx, rw [Z.coord_change_comp, Z.coord_change_self], { exact hx.2 }, { simp [hx] }, end, open_source := is_open_prod (is_open_inter (Z.is_open_base_set i) (Z.is_open_base_set j)) is_open_univ, open_target := is_open_prod (is_open_inter (Z.is_open_base_set i) (Z.is_open_base_set j)) is_open_univ, continuous_to_fun := continuous_on.prod continuous_fst.continuous_on (Z.coord_change_continuous i j), continuous_inv_fun := by simpa [inter_comm] using continuous_on.prod continuous_fst.continuous_on (Z.coord_change_continuous j i) } @[simp] lemma mem_triv_change_source (i j : ι) (p : B × F) : p ∈ (Z.triv_change i j).source ↔ p.1 ∈ Z.base_set i ∩ Z.base_set j := by { erw [mem_prod], simp } /-- Associate to a trivialization index `i : ι` the corresponding trivialization, i.e., a bijection between `proj ⁻¹ (base_set i)` and `base_set i × F`. As the fiber above `x` is `F` but read in the chart with index `index_at x`, the trivialization in the fiber above x is by definition the coordinate change from i to `index_at x`, so it depends on `x`. The local trivialization will ultimately be a local homeomorphism. For now, we only introduce the local equiv version, denoted with a prime. In further developments, avoid this auxiliary version, and use Z.local_triv instead. -/ def local_triv' (i : ι) : local_equiv Z.total_space (B × F) := { source := Z.proj ⁻¹' (Z.base_set i), target := set.prod (Z.base_set i) univ, inv_fun := λp, ⟨p.1, Z.coord_change i (Z.index_at p.1) p.1 p.2⟩, to_fun := λp, ⟨p.1, Z.coord_change (Z.index_at p.1) i p.1 p.2⟩, map_source := λp hp, by simpa only [set.mem_preimage, and_true, set.mem_univ, set.prod_mk_mem_set_prod_eq] using hp, map_target := λp hp, by simpa only [set.mem_preimage, and_true, set.mem_univ, set.mem_prod] using hp, left_inv := begin rintros ⟨x, v⟩ hx, change x ∈ Z.base_set i at hx, dsimp, rw [Z.coord_change_comp, Z.coord_change_self], { exact Z.mem_base_set_at _ }, { simp [hx] } end, right_inv := begin rintros ⟨x, v⟩ hx, simp only [prod_mk_mem_set_prod_eq, and_true, mem_univ] at hx, rw [Z.coord_change_comp, Z.coord_change_self], { exact hx }, { simp [hx] } end } @[simp] lemma mem_local_triv'_source (i : ι) (p : Z.total_space) : p ∈ (Z.local_triv' i).source ↔ p.1 ∈ Z.base_set i := by refl @[simp] lemma mem_local_triv'_target (i : ι) (p : B × F) : p ∈ (Z.local_triv' i).target ↔ p.1 ∈ Z.base_set i := by { erw [mem_prod], simp } @[simp] lemma local_triv'_fst (i : ι) (p : Z.total_space) : ((Z.local_triv' i).to_fun p).1 = p.1 := rfl @[simp] lemma local_triv'_inv_fst (i : ι) (p : B × F) : ((Z.local_triv' i).inv_fun p).1 = p.1 := rfl /-- The composition of two local trivializations is the trivialization change Z.triv_change i j. -/ lemma local_triv'_trans (i j : ι) : (Z.local_triv' i).symm.trans (Z.local_triv' j) ≈ (Z.triv_change i j).to_local_equiv := begin split, { ext x, erw [mem_prod], simp [local_equiv.trans_source] }, { rintros ⟨x, v⟩ hx, simp only [triv_change, local_triv', local_equiv.symm, true_and, local_equiv.right_inv, prod_mk_mem_set_prod_eq, local_equiv.trans_source, mem_inter_eq, and_true, mem_univ, prod.mk.inj_iff, local_equiv.trans_apply, mem_preimage, proj, local_equiv.left_inv] at hx ⊢, simp [Z.coord_change_comp, hx] } end /-- Topological structure on the total space of a topological bundle created from core, designed so that all the local trivialization are continuous. -/ instance to_topological_space : topological_space Z.total_space := topological_space.generate_from $ ⋃ (i : ι) (s : set (B × F)) (s_open : is_open s), {(Z.local_triv' i).source ∩ (Z.local_triv' i).to_fun ⁻¹' s } lemma open_source' (i : ι) : is_open (Z.local_triv' i).source := begin apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], refine ⟨i, set.prod (Z.base_set i) univ, is_open_prod (Z.is_open_base_set i) (is_open_univ), _⟩, ext p, simp [topological_fiber_bundle_core.local_triv'_fst, topological_fiber_bundle_core.mem_local_triv'_source] end lemma open_target' (i : ι) : is_open (Z.local_triv' i).target := is_open_prod (Z.is_open_base_set i) (is_open_univ) /-- Local trivialization of a topological bundle created from core, as a local homeomorphism. -/ def local_triv (i : ι) : local_homeomorph Z.total_space (B × F) := { open_source := Z.open_source' i, open_target := Z.open_target' i, continuous_to_fun := begin rw continuous_on_open_iff (Z.open_source' i), assume s s_open, apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], exact ⟨i, s, s_open, rfl⟩ end, continuous_inv_fun := begin apply continuous_on_open_of_generate_from (Z.open_target' i), assume t ht, simp only [exists_prop, mem_Union, mem_singleton_iff] at ht, obtain ⟨j, s, s_open, ts⟩ : ∃ j s, is_open s ∧ t = (local_triv' Z j).source ∩ (local_triv' Z j).to_fun ⁻¹' s := ht, rw ts, simp only [local_equiv.right_inv, preimage_inter, local_equiv.left_inv], let e := Z.local_triv' i, let e' := Z.local_triv' j, let f := e.symm.trans e', have : is_open (f.source ∩ f.to_fun ⁻¹' s), { rw [local_equiv.eq_on_source_preimage (Z.local_triv'_trans i j)], exact (continuous_on_open_iff (Z.triv_change i j).open_source).1 ((Z.triv_change i j).continuous_to_fun) _ s_open }, convert this using 1, dsimp [local_equiv.trans_source], rw [← preimage_comp, inter_assoc] end, ..Z.local_triv' i } /- We will now state again the basic properties of the local trivializations, but without primes, i.e., for the local homeomorphism instead of the local equiv. -/ @[simp] lemma mem_local_triv_source (i : ι) (p : Z.total_space) : p ∈ (Z.local_triv i).source ↔ p.1 ∈ Z.base_set i := by refl @[simp] lemma mem_local_triv_target (i : ι) (p : B × F) : p ∈ (Z.local_triv i).target ↔ p.1 ∈ Z.base_set i := by { erw [mem_prod], simp } @[simp] lemma local_triv_fst (i : ι) (p : Z.total_space) : ((Z.local_triv i).to_fun p).1 = p.1 := rfl @[simp] lemma local_triv_symm_fst (i : ι) (p : B × F) : ((Z.local_triv i).inv_fun p).1 = p.1 := rfl /-- The composition of two local trivializations is the trivialization change Z.triv_change i j. -/ lemma local_triv_trans (i j : ι) : (Z.local_triv i).symm.trans (Z.local_triv j) ≈ Z.triv_change i j := Z.local_triv'_trans i j /-- Extended version of the local trivialization of a fiber bundle constructed from core, registering additionally in its type that it is a local bundle trivialization. -/ def local_triv_ext (i : ι) : bundle_trivialization F Z.proj := { base_set := Z.base_set i, open_base_set := Z.is_open_base_set i, source_eq := rfl, target_eq := rfl, proj_to_fun := λp hp, by simp, ..Z.local_triv i } /-- A topological fiber bundle constructed from core is indeed a topological fiber bundle. -/ theorem is_topological_fiber_bundle : is_topological_fiber_bundle F Z.proj := λx, ⟨Z.local_triv_ext (Z.index_at (Z.proj x)), by simp [local_triv_ext]⟩ /-- The projection on the base of a topological bundle created from core is continuous -/ lemma continuous_proj : continuous Z.proj := Z.is_topological_fiber_bundle.continuous_proj /-- The projection on the base of a topological bundle created from core is an open map -/ lemma is_open_map_proj : is_open_map Z.proj := Z.is_topological_fiber_bundle.is_open_map_proj /-- Preferred local trivialization of a fiber bundle constructed from core, at a given point, as a local homeomorphism -/ def local_triv_at (p : Z.total_space) : local_homeomorph Z.total_space (B × F) := Z.local_triv (Z.index_at (Z.proj p)) @[simp] lemma mem_local_triv_at_source (p : Z.total_space) : p ∈ (Z.local_triv_at p).source := by simp [local_triv_at] @[simp] lemma local_triv_at_fst (p q : Z.total_space) : ((Z.local_triv_at p).to_fun q).1 = q.1 := rfl @[simp] lemma local_triv_at_symm_fst (p : Z.total_space) (q : B × F) : ((Z.local_triv_at p).inv_fun q).1 = q.1 := rfl /-- Preferred local trivialization of a fiber bundle constructed from core, at a given point, as a bundle trivialization -/ def local_triv_at_ext (p : Z.total_space) : bundle_trivialization F Z.proj := Z.local_triv_ext (Z.index_at (Z.proj p)) @[simp] lemma local_triv_at_ext_to_local_homeomorph (p : Z.total_space) : (Z.local_triv_at_ext p).to_local_homeomorph = Z.local_triv_at p := rfl end topological_fiber_bundle_core
2a0b588bf9b92a42f9f7d638834606949b3f2298
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/nat/modeq.lean
989d94bc8274264c2fbf5f0dd144ba6146974af5
[ "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
14,222
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.int.gcd import tactic.abel import data.list.rotate /-! # Congruences modulo a natural number This file defines the equivalence relation `a ≡ b [MOD n]` on the natural numbers, and proves basic properties about it such as the Chinese Remainder Theorem `modeq_and_modeq_iff_modeq_mul`. ## Notations `a ≡ b [MOD n]` is notation for `modeq n a b`, which is defined to mean `a % n = b % n`. ## Tags modeq, congruence, mod, MOD, modulo -/ namespace nat /-- Modular equality. `modeq n a b`, or `a ≡ b [MOD n]`, means that `a - b` is a multiple of `n`. -/ @[derive decidable] def modeq (n a b : ℕ) := a % n = b % n notation a ` ≡ `:50 b ` [MOD `:50 n `]`:0 := modeq n a b namespace modeq variables {n m a b c d : ℕ} @[refl] protected theorem refl (a : ℕ) : a ≡ a [MOD n] := @rfl _ _ @[symm] protected theorem symm : a ≡ b [MOD n] → b ≡ a [MOD n] := eq.symm @[trans] protected theorem trans : a ≡ b [MOD n] → b ≡ c [MOD n] → a ≡ c [MOD n] := eq.trans protected theorem comm : a ≡ b [MOD n] ↔ b ≡ a [MOD n] := ⟨nat.modeq.symm, nat.modeq.symm⟩ theorem modeq_zero_iff : a ≡ 0 [MOD n] ↔ n ∣ a := by rw [modeq, zero_mod, dvd_iff_mod_eq_zero] theorem modeq_iff_dvd : a ≡ b [MOD n] ↔ (n:ℤ) ∣ b - a := by rw [modeq, eq_comm, ← int.coe_nat_inj', int.coe_nat_mod, int.coe_nat_mod, int.mod_eq_mod_iff_mod_sub_eq_zero, int.dvd_iff_mod_eq_zero] theorem modeq_of_dvd : (n:ℤ) ∣ b - a → a ≡ b [MOD n] := modeq_iff_dvd.2 theorem dvd_of_modeq : a ≡ b [MOD n] → (n:ℤ) ∣ b - a := modeq_iff_dvd.1 /-- A variant of `modeq_iff_dvd` with `nat` divisibility -/ theorem modeq_iff_dvd' (h : a ≤ b) : a ≡ b [MOD n] ↔ n ∣ b - a := by rw [modeq_iff_dvd, ←int.coe_nat_dvd, int.coe_nat_sub h] theorem mod_modeq (a n) : a % n ≡ a [MOD n] := nat.mod_mod _ _ theorem modeq_of_dvd_of_modeq (d : m ∣ n) (h : a ≡ b [MOD n]) : a ≡ b [MOD m] := modeq_of_dvd $ dvd_trans (int.coe_nat_dvd.2 d) (dvd_of_modeq h) theorem modeq_mul_left' (c : ℕ) (h : a ≡ b [MOD n]) : c * a ≡ c * b [MOD (c * n)] := by unfold modeq at *; rw [mul_mod_mul_left, mul_mod_mul_left, h] theorem modeq_mul_left (c : ℕ) (h : a ≡ b [MOD n]) : c * a ≡ c * b [MOD n] := modeq_of_dvd_of_modeq (dvd_mul_left _ _) $ modeq_mul_left' _ h theorem modeq_mul_right' (c : ℕ) (h : a ≡ b [MOD n]) : a * c ≡ b * c [MOD (n * c)] := by rw [mul_comm a, mul_comm b, mul_comm n]; exact modeq_mul_left' c h theorem modeq_mul_right (c : ℕ) (h : a ≡ b [MOD n]) : a * c ≡ b * c [MOD n] := by rw [mul_comm a, mul_comm b]; exact modeq_mul_left c h theorem modeq_mul (h₁ : a ≡ b [MOD n]) (h₂ : c ≡ d [MOD n]) : a * c ≡ b * d [MOD n] := (modeq_mul_left _ h₂).trans (modeq_mul_right _ h₁) theorem modeq_pow (m : ℕ) (h : a ≡ b [MOD n]) : a ^ m ≡ b ^ m [MOD n] := begin induction m with d hd, {refl}, rw [pow_succ, pow_succ], exact modeq_mul h hd, end theorem modeq_add (h₁ : a ≡ b [MOD n]) (h₂ : c ≡ d [MOD n]) : a + c ≡ b + d [MOD n] := modeq_of_dvd begin rw [int.coe_nat_add, int.coe_nat_add, add_sub_comm], exact dvd_add (dvd_of_modeq h₁) (dvd_of_modeq h₂), end theorem modeq_add_cancel_left (h₁ : a ≡ b [MOD n]) (h₂ : a + c ≡ b + d [MOD n]) : c ≡ d [MOD n] := begin simp only [modeq_iff_dvd, int.coe_nat_add] at *, rw add_sub_comm at h₂, convert _root_.dvd_sub h₂ h₁ using 1, rw add_sub_cancel', end theorem modeq_add_cancel_right (h₁ : c ≡ d [MOD n]) (h₂ : a + c ≡ b + d [MOD n]) : a ≡ b [MOD n] := by rw [add_comm a, add_comm b] at h₂; exact modeq_add_cancel_left h₁ h₂ theorem modeq_of_modeq_mul_left (m : ℕ) (h : a ≡ b [MOD m * n]) : a ≡ b [MOD n] := by rw [modeq_iff_dvd] at *; exact dvd.trans (dvd_mul_left (n : ℤ) (m : ℤ)) h theorem modeq_of_modeq_mul_right (m : ℕ) : a ≡ b [MOD n * m] → a ≡ b [MOD n] := mul_comm m n ▸ modeq_of_modeq_mul_left _ theorem modeq_one : a ≡ b [MOD 1] := modeq_of_dvd $ one_dvd _ local attribute [semireducible] int.nonneg /-- The natural number less than `lcm n m` congruent to `a` mod `n` and `b` mod `m` -/ def chinese_remainder' (h : a ≡ b [MOD gcd n m]) : {k // k ≡ a [MOD n] ∧ k ≡ b [MOD m]} := if hn : n = 0 then ⟨a, begin rw [hn, gcd_zero_left] at h, split, refl, exact h end⟩ else if hm : m = 0 then ⟨b, begin rw [hm, gcd_zero_right] at h, split, exact h.symm, refl end⟩ else ⟨let (c, d) := xgcd n m in int.to_nat (((n * c * b + m * d * a) / gcd n m) % lcm n m), begin rw xgcd_val, dsimp [chinese_remainder'._match_1], rw [modeq_iff_dvd, modeq_iff_dvd, int.to_nat_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero.2 (lcm_ne_zero hn hm)))], have hnonzero : (gcd n m : ℤ) ≠ 0 := begin norm_cast, rw [nat.gcd_eq_zero_iff, not_and], exact λ _, hm, end, have hcoedvd : ∀ t, (gcd n m : ℤ) ∣ t * (b - a) := λ t, dvd_mul_of_dvd_right h.dvd_of_modeq _, have := gcd_eq_gcd_ab n m, split; rw [int.mod_def, ← sub_add]; refine dvd_add _ (dvd_mul_of_dvd_left _ _); try {norm_cast}, { rw ← sub_eq_iff_eq_add' at this, rw [← this, sub_mul, ← add_sub_assoc, add_comm, add_sub_assoc, ← mul_sub, int.add_div_of_dvd_left, int.mul_div_cancel_left _ hnonzero, int.mul_div_assoc _ h.dvd_of_modeq, ← sub_sub, sub_self, zero_sub, dvd_neg, mul_assoc], exact dvd_mul_right _ _, norm_cast, exact dvd_mul_right _ _, }, { exact dvd_lcm_left n m, }, { rw ← sub_eq_iff_eq_add at this, rw [← this, sub_mul, sub_add, ← mul_sub, int.sub_div_of_dvd, int.mul_div_cancel_left _ hnonzero, int.mul_div_assoc _ h.dvd_of_modeq, ← sub_add, sub_self, zero_add, mul_assoc], exact dvd_mul_right _ _, exact hcoedvd _ }, { exact dvd_lcm_right n m, }, end⟩ /-- The natural number less than `n*m` congruent to `a` mod `n` and `b` mod `m` -/ def chinese_remainder (co : coprime n m) (a b : ℕ) : {k // k ≡ a [MOD n] ∧ k ≡ b [MOD m]} := chinese_remainder' (by convert modeq_one) lemma modeq_and_modeq_iff_modeq_mul {a b m n : ℕ} (hmn : coprime m n) : a ≡ b [MOD m] ∧ a ≡ b [MOD n] ↔ (a ≡ b [MOD m * n]) := ⟨λ h, begin rw [nat.modeq.modeq_iff_dvd, nat.modeq.modeq_iff_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd] at h, rw [nat.modeq.modeq_iff_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd], exact hmn.mul_dvd_of_dvd_of_dvd h.1 h.2 end, λ h, ⟨nat.modeq.modeq_of_modeq_mul_right _ h, nat.modeq.modeq_of_modeq_mul_left _ h⟩⟩ lemma coprime_of_mul_modeq_one (b : ℕ) {a n : ℕ} (h : a * b ≡ 1 [MOD n]) : coprime a n := nat.coprime_of_dvd' (λ k kp ⟨ka, hka⟩ ⟨kb, hkb⟩, int.coe_nat_dvd.1 begin rw [hka, hkb, modeq_iff_dvd] at h, cases h with z hz, rw [sub_eq_iff_eq_add] at hz, rw [hz, int.coe_nat_mul, mul_assoc, mul_assoc, int.coe_nat_mul, ← mul_add], exact dvd_mul_right _ _, end) end modeq @[simp] lemma mod_mul_right_mod (a b c : ℕ) : a % (b * c) % b = a % b := modeq.modeq_of_modeq_mul_right _ (modeq.mod_modeq _ _) @[simp] lemma mod_mul_left_mod (a b c : ℕ) : a % (b * c) % c = a % c := modeq.modeq_of_modeq_mul_left _ (modeq.mod_modeq _ _) lemma div_mod_eq_mod_mul_div (a b c : ℕ) : a / b % c = a % (b * c) / b := if hb0 : b = 0 then by simp [hb0] else by rw [← @add_right_cancel_iff _ _ (c * (a / b / c)), mod_add_div, nat.div_div_eq_div_mul, ← nat.mul_right_inj (nat.pos_of_ne_zero hb0),← @add_left_cancel_iff _ _ (a % b), mod_add_div, mul_add, ← @add_left_cancel_iff _ _ (a % (b * c) % b), add_left_comm, ← add_assoc (a % (b * c) % b), mod_add_div, ← mul_assoc, mod_add_div, mod_mul_right_mod] lemma add_mod_add_ite (a b c : ℕ) : (a + b) % c + (if c ≤ a % c + b % c then c else 0) = a % c + b % c := have (a + b) % c = (a % c + b % c) % c, from nat.modeq.modeq_add (nat.modeq.mod_modeq _ _).symm (nat.modeq.mod_modeq _ _).symm, if hc0 : c = 0 then by simp [hc0] else begin rw this, split_ifs, { have h2 : (a % c + b % c) / c < 2, from nat.div_lt_of_lt_mul (by rw mul_two; exact add_lt_add (nat.mod_lt _ (nat.pos_of_ne_zero hc0)) (nat.mod_lt _ (nat.pos_of_ne_zero hc0))), have h0 : 0 < (a % c + b % c) / c, from nat.div_pos h (nat.pos_of_ne_zero hc0), rw [← @add_right_cancel_iff _ _ (c * ((a % c + b % c) / c)), add_comm _ c, add_assoc, mod_add_div, le_antisymm (le_of_lt_succ h2) h0, mul_one, add_comm] }, { rw [nat.mod_eq_of_lt (lt_of_not_ge h), add_zero] } end lemma add_mod_of_add_mod_lt {a b c : ℕ} (hc : a % c + b % c < c) : (a + b) % c = a % c + b % c := by rw [← add_mod_add_ite, if_neg (not_le_of_lt hc), add_zero] lemma add_mod_add_of_le_add_mod {a b c : ℕ} (hc : c ≤ a % c + b % c) : (a + b) % c + c = a % c + b % c := by rw [← add_mod_add_ite, if_pos hc] lemma add_div {a b c : ℕ} (hc0 : 0 < c) : (a + b) / c = a / c + b / c + if c ≤ a % c + b % c then 1 else 0 := begin rw [← nat.mul_right_inj hc0, ← @add_left_cancel_iff _ _ ((a + b) % c + a % c + b % c)], suffices : (a + b) % c + c * ((a + b) / c) + a % c + b % c = a % c + c * (a / c) + (b % c + c * (b / c)) + c * (if c ≤ a % c + b % c then 1 else 0) + (a + b) % c, { simpa only [mul_add, add_comm, add_left_comm, add_assoc] }, rw [mod_add_div, mod_add_div, mod_add_div, mul_ite, add_assoc, add_assoc], conv_lhs { rw ← add_mod_add_ite }, simp, ac_refl end lemma add_div_eq_of_add_mod_lt {a b c : ℕ} (hc : a % c + b % c < c) : (a + b) / c = a / c + b / c := if hc0 : c = 0 then by simp [hc0] else by rw [add_div (nat.pos_of_ne_zero hc0), if_neg (not_le_of_lt hc), add_zero] protected lemma add_div_of_dvd_right {a b c : ℕ} (hca : c ∣ a) : (a + b) / c = a / c + b / c := if h : c = 0 then by simp [h] else add_div_eq_of_add_mod_lt begin rw [nat.mod_eq_zero_of_dvd hca, zero_add], exact nat.mod_lt _ (pos_iff_ne_zero.mpr h), end protected lemma add_div_of_dvd_left {a b c : ℕ} (hca : c ∣ b) : (a + b) / c = a / c + b / c := by rwa [add_comm, nat.add_div_of_dvd_right, add_comm] lemma add_div_eq_of_le_mod_add_mod {a b c : ℕ} (hc : c ≤ a % c + b % c) (hc0 : 0 < c) : (a + b) / c = a / c + b / c + 1 := by rw [add_div hc0, if_pos hc] lemma add_div_le_add_div (a b c : ℕ) : a / c + b / c ≤ (a + b) / c := if hc0 : c = 0 then by simp [hc0] else by rw [nat.add_div (nat.pos_of_ne_zero hc0)]; exact le_add_right _ _ lemma le_mod_add_mod_of_dvd_add_of_not_dvd {a b c : ℕ} (h : c ∣ a + b) (ha : ¬ c ∣ a) : c ≤ a % c + b % c := by_contradiction $ λ hc, have (a + b) % c = a % c + b % c, from add_mod_of_add_mod_lt (lt_of_not_ge hc), by simp [dvd_iff_mod_eq_zero, *] at * lemma odd_mul_odd {n m : ℕ} : n % 2 = 1 → m % 2 = 1 → (n * m) % 2 = 1 := by simpa [nat.modeq] using @nat.modeq.modeq_mul 2 n 1 m 1 lemma odd_mul_odd_div_two {m n : ℕ} (hm1 : m % 2 = 1) (hn1 : n % 2 = 1) : (m * n) / 2 = m * (n / 2) + m / 2 := have hm0 : 0 < m := nat.pos_of_ne_zero (λ h, by simp * at *), have hn0 : 0 < n := nat.pos_of_ne_zero (λ h, by simp * at *), (nat.mul_right_inj (show 0 < 2, from dec_trivial)).1 $ by rw [mul_add, two_mul_odd_div_two hm1, mul_left_comm, two_mul_odd_div_two hn1, two_mul_odd_div_two (nat.odd_mul_odd hm1 hn1), nat.mul_sub_left_distrib, mul_one, ← nat.add_sub_assoc hm0, nat.sub_add_cancel (le_mul_of_one_le_right (nat.zero_le _) hn0)] lemma odd_of_mod_four_eq_one {n : ℕ} : n % 4 = 1 → n % 2 = 1 := by simpa [modeq, show 2 * 2 = 4, by norm_num] using @modeq.modeq_of_modeq_mul_left 2 n 1 2 lemma odd_of_mod_four_eq_three {n : ℕ} : n % 4 = 3 → n % 2 = 1 := by simpa [modeq, show 2 * 2 = 4, by norm_num, show 3 % 4 = 3, by norm_num] using @modeq.modeq_of_modeq_mul_left 2 n 3 2 end nat namespace list variable {α : Type*} lemma nth_rotate : ∀ {l : list α} {n m : ℕ} (hml : m < l.length), (l.rotate n).nth m = l.nth ((m + n) % l.length) | [] n m hml := (nat.not_lt_zero _ hml).elim | l 0 m hml := by simp [nat.mod_eq_of_lt hml] | (a::l) (n+1) m hml := have h₃ : m < list.length (l ++ [a]), by simpa using hml, (lt_or_eq_of_le (nat.le_of_lt_succ $ nat.mod_lt (m + n) (lt_of_le_of_lt (nat.zero_le _) hml))).elim (λ hml', have h₁ : (m + (n + 1)) % ((a :: l : list α).length) = (m + n) % ((a :: l : list α).length) + 1, from calc (m + (n + 1)) % (l.length + 1) = ((m + n) % (l.length + 1) + 1) % (l.length + 1) : add_assoc m n 1 ▸ nat.modeq.modeq_add (nat.mod_mod _ _).symm rfl ... = (m + n) % (l.length + 1) + 1 : nat.mod_eq_of_lt (nat.succ_lt_succ hml'), have h₂ : (m + n) % (l ++ [a]).length < l.length, by simpa [nat.add_one] using hml', by rw [list.rotate_cons_succ, nth_rotate h₃, list.nth_append h₂, h₁, list.nth]; simp) (λ hml', have h₁ : (m + (n + 1)) % (l.length + 1) = 0, from calc (m + (n + 1)) % (l.length + 1) = (l.length + 1) % (l.length + 1) : add_assoc m n 1 ▸ nat.modeq.modeq_add (hml'.trans (nat.mod_eq_of_lt (nat.lt_succ_self _)).symm) rfl ... = 0 : by simp, by rw [list.length, list.rotate_cons_succ, nth_rotate h₃, list.length_append, list.length_cons, list.length, zero_add, hml', h₁, list.nth_concat_length]; refl) lemma rotate_eq_self_iff_eq_repeat [hα : nonempty α] : ∀ {l : list α}, (∀ n, l.rotate n = l) ↔ ∃ a, l = list.repeat a l.length | [] := ⟨λ h, nonempty.elim hα (λ a, ⟨a, by simp⟩), by simp⟩ | (a::l) := ⟨λ h, ⟨a, list.ext_le (by simp) $ λ n hn h₁, begin rw [← option.some_inj, ← list.nth_le_nth], conv {to_lhs, rw ← h ((list.length (a :: l)) - n)}, rw [nth_rotate hn, nat.add_sub_cancel' (le_of_lt hn), nat.mod_self, nth_le_repeat], refl end⟩, λ ⟨a, ha⟩ n, ha.symm ▸ list.ext_le (by simp) (λ m hm h, have hm' : (m + n) % (list.repeat a (list.length (a :: l))).length < list.length (a :: l), by rw list.length_repeat; exact nat.mod_lt _ (nat.succ_pos _), by rw [nth_le_repeat, ← option.some_inj, ← list.nth_le_nth, nth_rotate h, list.nth_le_nth, nth_le_repeat]; simp * at *)⟩ end list
afb1a3e1ff307bff267b8d79428ae76f7718763a
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/02_Dependent_Type_Theory.org.14.lean
651703a15ee336b91fa47840031dcaa298de43a9
[]
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
424
lean
/- page 18 -/ import standard import data.nat data.prod data.bool open nat prod bool constants m n : nat constant b : bool print "reducing pairs" eval pr1 (pair m n) -- m eval pr2 (pair m n) -- n print "reducing boolean expressions" eval tt && ff -- ff eval b && ff -- ff print "reducing arithmetic expressions" eval n + 0 -- n eval n + 2 -- succ (succ n) eval 2 + 3 -- 5
9f79e644ee1f72db3f7b2de70b3bc24b03d207c0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/compiler/StackOverflow.lean
9a0468e7cbfe7653da4261ca0cb9237131771b2a
[ "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
105
lean
partial def foo : Nat → Nat | n => foo n + 1 @[never_extract] def main : IO Unit := IO.println $ foo 0
90834812f3c668d8ac4d3aa3c3dd2f17af7d032b
690889011852559ee5ac4dfea77092de8c832e7e
/src/data/list/defs.lean
bdfa3df6443028106d9e05dbb6ca73d7d5691cb8
[ "Apache-2.0" ]
permissive
williamdemeo/mathlib
f6df180148f8acc91de9ba5e558976ab40a872c7
1fa03c29f9f273203bbffb79d10d31f696b3d317
refs/heads/master
1,584,785,260,929
1,572,195,914,000
1,572,195,913,000
138,435,193
0
0
Apache-2.0
1,529,789,739,000
1,529,789,739,000
null
UTF-8
Lean
false
false
19,773
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 Extra definitions on lists. -/ import data.option.defs logic.basic tactic.cache namespace list open function nat universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} 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) 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 @[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} /-- "inhabited" `nth` function: returns `default` instead of `none` in the case that the index is out of bounds. -/ @[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget /-- 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) def insert_nth (n : ℕ) (a : α) : list α → list α := modify_nth_tail (list.cons a) n section take' variable [inhabited α] 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 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 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 def find_indexes_aux (p : α → Prop) [decidable_pred p] : list α → nat → list nat | [] n := [] | (a::l) n := let t := find_indexes_aux l (succ n) in if p a then n :: t else t /-- `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 := find_indexes_aux p l 0 /-- `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 def map_with_index_core (f : ℕ → α → β) : ℕ → list α → list β | k [] := [] | k (a::as) := f k a::(map_with_index_core (k+1) as) def map_with_index (f : ℕ → α → β) (as : list α) : list β := map_with_index_core f 0 as /-- `indexes_of a l` is the list of all indexes of `a` in `l`. indexes_of a [a, b, a, a] = [0, 2, 3] -/ def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a) /-- `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} 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₂ 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 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 @[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 _ _ _ (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)⟩] } 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 [] end permutations def erasep (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then l else a :: erasep 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') 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 /-- `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 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) def of_fn {n} (f : fin n → α) : list α := of_fn_aux f n (le_refl _) [] def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α := if h : _ 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⟩ 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. `erase_dup`), 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 /-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence). Defined as `pw_filter (≠)`. erase_dup [1, 0, 2, 2, 1] = [0, 2, 1] -/ def erase_dup [decidable_eq α] : list α → list α := pw_filter (≠) /-- `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 def reduce_option {α} : list (option α) → list α := list.filter_map id def map_head {α} (f : α → α) : list α → list α | [] := [] | (x :: xs) := f x :: xs def map_last {α} (f : α → α) : list α → list α | [] := [] | [x] := [f x] | (x :: xs) := x :: map_last xs /-- `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 /- tfae: The Following (propositions) Are Equivalent -/ def tfae (l : list Prop) : Prop := ∀ x ∈ l, ∀ y ∈ l, x ↔ y /-- `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 α) 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⟩⟩ def choose (hp : ∃ a, a ∈ l ∧ p a) : α := choose_x p l hp end choose namespace func /- Definitions for using lists as finite representations of functions with domain ℕ. -/ def neg [has_neg α] (as : list α) := as.map (λ a, -a) variables [inhabited α] [inhabited β] @[simp] def set (a : α) : list α → ℕ → list α | (_::as) 0 := a::as | [] 0 := [a] | (h::as) (k+1) := h::(set as k) | [] (k+1) := (default α)::(set ([] : list α) k) @[simp] def get : ℕ → list α → α | _ [] := default α | 0 (a::as) := a | (n+1) (a::as) := get n as def equiv (as1 as2 : list α) : Prop := ∀ (m : nat), get m as1 = get m as2 @[simp] def pointwise (f : α → β → γ) : list α → list β → list γ | [] [] := [] | [] (b::bs) := map (f $ default α) (b::bs) | (a::as) [] := map (λ x, f x $ default β) (a::as) | (a::as) (b::bs) := (f a b)::(pointwise as bs) def add {α : Type u} [has_zero α] [has_add α] : list α → list α → list α := @pointwise α α α ⟨0⟩ ⟨0⟩ (+) def sub {α : Type u} [has_zero α] [has_sub α] : list α → list α → list α := @pointwise α α α ⟨0⟩ ⟨0⟩ (@has_sub.sub α _) end func /-- 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 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 end list
94eda6e1deb9347f30876b0b981768a99c2ba5d5
41ebf3cb010344adfa84907b3304db00e02db0a6
/uexp/src/uexp/rules/ExtractJoinFilterRule.lean
3cf317bddf4b6359c5afc5c69a01f152bac1f3c5
[ "BSD-2-Clause" ]
permissive
ReinierKoops/Cosette
e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb
eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29
refs/heads/master
1,686,483,953,198
1,624,293,498,000
1,624,293,498,000
378,997,885
0
0
BSD-2-Clause
1,624,293,485,000
1,624,293,484,000
null
UTF-8
Lean
false
false
1,885
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..meta.ucongr import ..meta.TDP import ..meta.cosette_tactics set_option profiler true open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int variable integer_1: const datatypes.int theorem rule: forall ( Γ scm_t scm_account scm_bonus scm_dept scm_emp: Schema) (rel_t: relation scm_t) (rel_account: relation scm_account) (rel_bonus: relation scm_bonus) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (t_k0 : Column int scm_t) (t_c1 : Column int scm_t) (t_f1_a0 : Column int scm_t) (t_f2_a0 : Column int scm_t) (t_f0_c0 : Column int scm_t) (t_f1_c0 : Column int scm_t) (t_f0_c1 : Column int scm_t) (t_f1_c2 : Column int scm_t) (t_f2_c3 : Column int scm_t) (account_acctno : Column int scm_account) (account_type : Column int scm_account) (account_balance : Column int scm_account) (bonus_ename : Column int scm_bonus) (bonus_job : Column int scm_bonus) (bonus_sal : Column int scm_bonus) (bonus_comm : Column int scm_bonus) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL ((SELECT1 (e2p (constantExpr integer_1)) FROM1 (product (table rel_emp) (table rel_dept)) WHERE (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅dept_deptno)))) :SQL Γ _) = denoteSQL ((SELECT1 (e2p (constantExpr integer_1)) FROM1 (product (table rel_emp) (table rel_dept)) WHERE (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅dept_deptno)))) :SQL Γ _) := begin intros, unfold_all_denotations, end
162856c996bd3b7070c06067d03e8f11590f4a10
bb31430994044506fa42fd667e2d556327e18dfe
/src/group_theory/coset.lean
48d24dd1d9afa80c590116608bad9effa8fa9967
[ "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
27,124
lean
/- Copyright (c) 2018 Mitchell Rowett. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mitchell Rowett, Scott Morrison -/ import algebra.quotient import group_theory.group_action.basic import tactic.group /-! # Cosets This file develops the basic theory of left and right cosets. ## Main definitions * `left_coset a s`: the left coset `a * s` for an element `a : α` and a subset `s ⊆ α`, for an `add_group` this is `left_add_coset a s`. * `right_coset s a`: the right coset `s * a` for an element `a : α` and a subset `s ⊆ α`, for an `add_group` this is `right_add_coset s a`. * `quotient_group.quotient s`: the quotient type representing the left cosets with respect to a subgroup `s`, for an `add_group` this is `quotient_add_group.quotient s`. * `quotient_group.mk`: the canonical map from `α` to `α/s` for a subgroup `s` of `α`, for an `add_group` this is `quotient_add_group.mk`. * `subgroup.left_coset_equiv_subgroup`: the natural bijection between a left coset and the subgroup, for an `add_group` this is `add_subgroup.left_coset_equiv_add_subgroup`. ## Notation * `a *l s`: for `left_coset a s`. * `a +l s`: for `left_add_coset a s`. * `s *r a`: for `right_coset s a`. * `s +r a`: for `right_add_coset s a`. * `G ⧸ H` is the quotient of the (additive) group `G` by the (additive) subgroup `H` -/ open set function variable {α : Type*} /-- The left coset `a * s` for an element `a : α` and a subset `s : set α` -/ @[to_additive left_add_coset "The left coset `a+s` for an element `a : α` and a subset `s : set α`"] def left_coset [has_mul α] (a : α) (s : set α) : set α := (λ x, a * x) '' s /-- The right coset `s * a` for an element `a : α` and a subset `s : set α` -/ @[to_additive right_add_coset "The right coset `s+a` for an element `a : α` and a subset `s : set α`"] def right_coset [has_mul α] (s : set α) (a : α) : set α := (λ x, x * a) '' s localized "infix (name := left_coset) ` *l `:70 := left_coset" in coset localized "infix (name := left_add_coset) ` +l `:70 := left_add_coset" in coset localized "infix (name := right_coset) ` *r `:70 := right_coset" in coset localized "infix (name := right_add_coset) ` +r `:70 := right_add_coset" in coset section coset_mul variable [has_mul α] @[to_additive mem_left_add_coset] lemma mem_left_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : a * x ∈ a *l s := mem_image_of_mem (λ b : α, a * b) hxS @[to_additive mem_right_add_coset] lemma mem_right_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : x * a ∈ s *r a := mem_image_of_mem (λ b : α, b * a) hxS /-- Equality of two left cosets `a * s` and `b * s`. -/ @[to_additive left_add_coset_equivalence "Equality of two left cosets `a + s` and `b + s`."] def left_coset_equivalence (s : set α) (a b : α) := a *l s = b *l s @[to_additive left_add_coset_equivalence_rel] lemma left_coset_equivalence_rel (s : set α) : equivalence (left_coset_equivalence s) := mk_equivalence (left_coset_equivalence s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) /-- Equality of two right cosets `s * a` and `s * b`. -/ @[to_additive right_add_coset_equivalence "Equality of two right cosets `s + a` and `s + b`."] def right_coset_equivalence (s : set α) (a b : α) := s *r a = s *r b @[to_additive right_add_coset_equivalence_rel] lemma right_coset_equivalence_rel (s : set α) : equivalence (right_coset_equivalence s) := mk_equivalence (right_coset_equivalence s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) end coset_mul section coset_semigroup variable [semigroup α] @[simp, to_additive left_add_coset_assoc] lemma left_coset_assoc (s : set α) (a b : α) : a *l (b *l s) = (a * b) *l s := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] @[simp, to_additive right_add_coset_assoc] lemma right_coset_assoc (s : set α) (a b : α) : s *r a *r b = s *r (a * b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] @[to_additive left_add_coset_right_add_coset] lemma left_coset_right_coset (s : set α) (a b : α) : a *l s *r b = a *l (s *r b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] end coset_semigroup section coset_monoid variables [monoid α] (s : set α) @[simp, to_additive zero_left_add_coset] lemma one_left_coset : 1 *l s = s := set.ext $ by simp [left_coset] @[simp, to_additive right_add_coset_zero] lemma right_coset_one : s *r 1 = s := set.ext $ by simp [right_coset] end coset_monoid section coset_submonoid open submonoid variables [monoid α] (s : submonoid α) @[to_additive mem_own_left_add_coset] lemma mem_own_left_coset (a : α) : a ∈ a *l s := suffices a * 1 ∈ a *l s, by simpa, mem_left_coset a (one_mem s : 1 ∈ s) @[to_additive mem_own_right_add_coset] lemma mem_own_right_coset (a : α) : a ∈ (s : set α) *r a := suffices 1 * a ∈ (s : set α) *r a, by simpa, mem_right_coset a (one_mem s : 1 ∈ s) @[to_additive mem_left_add_coset_left_add_coset] lemma mem_left_coset_left_coset {a : α} (ha : a *l s = s) : a ∈ s := by rw [←set_like.mem_coe, ←ha]; exact mem_own_left_coset s a @[to_additive mem_right_add_coset_right_add_coset] lemma mem_right_coset_right_coset {a : α} (ha : (s : set α) *r a = s) : a ∈ s := by rw [←set_like.mem_coe, ←ha]; exact mem_own_right_coset s a end coset_submonoid section coset_group variables [group α] {s : set α} {x : α} @[to_additive mem_left_add_coset_iff] lemma mem_left_coset_iff (a : α) : x ∈ a *l s ↔ a⁻¹ * x ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨a⁻¹ * x, h, by simp⟩) @[to_additive mem_right_add_coset_iff] lemma mem_right_coset_iff (a : α) : x ∈ s *r a ↔ x * a⁻¹ ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨x * a⁻¹, h, by simp⟩) end coset_group section coset_subgroup open subgroup variables [group α] (s : subgroup α) @[to_additive left_add_coset_mem_left_add_coset] lemma left_coset_mem_left_coset {a : α} (ha : a ∈ s) : a *l s = s := set.ext $ by simp [mem_left_coset_iff, mul_mem_cancel_left (s.inv_mem ha)] @[to_additive right_add_coset_mem_right_add_coset] lemma right_coset_mem_right_coset {a : α} (ha : a ∈ s) : (s : set α) *r a = s := set.ext $ assume b, by simp [mem_right_coset_iff, mul_mem_cancel_right (s.inv_mem ha)] @[to_additive] lemma orbit_subgroup_eq_right_coset (a : α) : mul_action.orbit s a = s *r a := set.ext (λ b, ⟨λ ⟨c, d⟩, ⟨c, c.2, d⟩, λ ⟨c, d, e⟩, ⟨⟨c, d⟩, e⟩⟩) @[to_additive] lemma orbit_subgroup_eq_self_of_mem {a : α} (ha : a ∈ s) : mul_action.orbit s a = s := (orbit_subgroup_eq_right_coset s a).trans (right_coset_mem_right_coset s ha) @[to_additive] lemma orbit_subgroup_one_eq_self : mul_action.orbit s (1 : α) = s := orbit_subgroup_eq_self_of_mem s s.one_mem @[to_additive eq_add_cosets_of_normal] theorem eq_cosets_of_normal (N : s.normal) (g : α) : g *l s = s *r g := set.ext $ assume a, by simp [mem_left_coset_iff, mem_right_coset_iff]; rw [N.mem_comm_iff] @[to_additive normal_of_eq_add_cosets] theorem normal_of_eq_cosets (h : ∀ g : α, g *l s = s *r g) : s.normal := ⟨assume a ha g, show g * a * g⁻¹ ∈ (s : set α), by rw [← mem_right_coset_iff, ← h]; exact mem_left_coset g ha⟩ @[to_additive normal_iff_eq_add_cosets] theorem normal_iff_eq_cosets : s.normal ↔ ∀ g : α, g *l s = s *r g := ⟨@eq_cosets_of_normal _ _ s, normal_of_eq_cosets s⟩ @[to_additive left_add_coset_eq_iff] lemma left_coset_eq_iff {x y : α} : left_coset x s = left_coset y s ↔ x⁻¹ * y ∈ s := begin rw set.ext_iff, simp_rw [mem_left_coset_iff, set_like.mem_coe], split, { intro h, apply (h y).mpr, rw mul_left_inv, exact s.one_mem }, { intros h z, rw ←mul_inv_cancel_right x⁻¹ y, rw mul_assoc, exact s.mul_mem_cancel_left h }, end @[to_additive right_add_coset_eq_iff] lemma right_coset_eq_iff {x y : α} : right_coset ↑s x = right_coset s y ↔ y * x⁻¹ ∈ s := begin rw set.ext_iff, simp_rw [mem_right_coset_iff, set_like.mem_coe], split, { intro h, apply (h y).mpr, rw mul_right_inv, exact s.one_mem }, { intros h z, rw ←inv_mul_cancel_left y x⁻¹, rw ←mul_assoc, exact s.mul_mem_cancel_right h }, end end coset_subgroup run_cmd to_additive.map_namespace `quotient_group `quotient_add_group namespace quotient_group variables [group α] (s : subgroup α) /-- The equivalence relation corresponding to the partition of a group by left cosets of a subgroup.-/ @[to_additive "The equivalence relation corresponding to the partition of a group by left cosets of a subgroup."] def left_rel : setoid α := mul_action.orbit_rel s.opposite α variables {s} @[to_additive] lemma left_rel_apply {x y : α} : @setoid.r _ (left_rel s) x y ↔ (x⁻¹ * y ∈ s) := calc (∃ a : s.opposite, y * mul_opposite.unop a = x) ↔ ∃ a : s, y * a = x : s.opposite_equiv.symm.exists_congr_left ... ↔ ∃ a : s, x⁻¹ * y = a⁻¹ : by simp only [inv_mul_eq_iff_eq_mul, eq_mul_inv_iff_mul_eq] ... ↔ x⁻¹ * y ∈ s : by simp [set_like.exists] variables (s) @[to_additive] lemma left_rel_eq : @setoid.r _ (left_rel s) = λ x y, x⁻¹ * y ∈ s := funext₂ $ by { simp only [eq_iff_iff], apply left_rel_apply } lemma left_rel_r_eq_left_coset_equivalence : @setoid.r _ (quotient_group.left_rel s) = left_coset_equivalence s := by { ext, rw left_rel_eq, exact (left_coset_eq_iff s).symm } @[to_additive] instance left_rel_decidable [decidable_pred (∈ s)] : decidable_rel (left_rel s).r := λ x y, by { rw left_rel_eq, exact ‹decidable_pred (∈ s)› _ } /-- `α ⧸ s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `α ⧸ s` is a group -/ @[to_additive "`α ⧸ s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `α ⧸ s` is a group"] instance : has_quotient α (subgroup α) := ⟨λ s, quotient (left_rel s)⟩ /-- The equivalence relation corresponding to the partition of a group by right cosets of a subgroup. -/ @[to_additive "The equivalence relation corresponding to the partition of a group by right cosets of a subgroup."] def right_rel : setoid α := mul_action.orbit_rel s α variables {s} @[to_additive] lemma right_rel_apply {x y : α} : @setoid.r _ (right_rel s) x y ↔ (y * x⁻¹ ∈ s) := calc (∃ a : s, (a:α) * y = x) ↔ ∃ a : s, y * x⁻¹ = a⁻¹ : by simp only [mul_inv_eq_iff_eq_mul, eq_inv_mul_iff_mul_eq] ... ↔ y * x⁻¹ ∈ s : by simp [set_like.exists] variables (s) @[to_additive] lemma right_rel_eq : @setoid.r _ (right_rel s) = λ x y, y * x⁻¹ ∈ s := funext₂ $ by { simp only [eq_iff_iff], apply right_rel_apply } lemma right_rel_r_eq_right_coset_equivalence : @setoid.r _ (quotient_group.right_rel s) = right_coset_equivalence s := by { ext, rw right_rel_eq, exact (right_coset_eq_iff s).symm } @[to_additive] instance right_rel_decidable [decidable_pred (∈ s)] : decidable_rel (right_rel s).r := λ x y, by { rw right_rel_eq, exact ‹decidable_pred (∈ s)› _ } /-- Right cosets are in bijection with left cosets. -/ @[to_additive "Right cosets are in bijection with left cosets."] def quotient_right_rel_equiv_quotient_left_rel : quotient (quotient_group.right_rel s) ≃ α ⧸ s := { to_fun := quotient.map' (λ g, g⁻¹) (λ a b, by { rw [left_rel_apply, right_rel_apply], exact λ h, (congr_arg (∈ s) (by group)).mp (s.inv_mem h) }), inv_fun := quotient.map' (λ g, g⁻¹) (λ a b, by { rw [left_rel_apply, right_rel_apply], exact λ h, (congr_arg (∈ s) (by group)).mp (s.inv_mem h) }), left_inv := λ g, quotient.induction_on' g (λ g, quotient.sound' (by { simp only [inv_inv], exact quotient.exact' rfl })), right_inv := λ g, quotient.induction_on' g (λ g, quotient.sound' (by { simp only [inv_inv], exact quotient.exact' rfl })) } @[to_additive] instance fintype_quotient_right_rel [fintype (α ⧸ s)] : fintype (quotient (quotient_group.right_rel s)) := fintype.of_equiv (α ⧸ s) (quotient_group.quotient_right_rel_equiv_quotient_left_rel s).symm @[to_additive] lemma card_quotient_right_rel [fintype (α ⧸ s)] : fintype.card (quotient (quotient_group.right_rel s)) = fintype.card (α ⧸ s) := fintype.of_equiv_card (quotient_group.quotient_right_rel_equiv_quotient_left_rel s).symm end quotient_group namespace quotient_group variables [group α] {s : subgroup α} @[to_additive] instance fintype [fintype α] (s : subgroup α) [decidable_rel (left_rel s).r] : fintype (α ⧸ s) := quotient.fintype (left_rel s) /-- The canonical map from a group `α` to the quotient `α ⧸ s`. -/ @[to_additive "The canonical map from an `add_group` `α` to the quotient `α ⧸ s`."] abbreviation mk (a : α) : α ⧸ s := quotient.mk' a @[to_additive] lemma mk_surjective : function.surjective $ @mk _ _ s := quotient.surjective_quotient_mk' @[elab_as_eliminator, to_additive] lemma induction_on {C : α ⧸ s → Prop} (x : α ⧸ s) (H : ∀ z, C (quotient_group.mk z)) : C x := quotient.induction_on' x H @[to_additive] instance : has_coe_t α (α ⧸ s) := ⟨mk⟩ -- note [use has_coe_t] @[elab_as_eliminator, to_additive] lemma induction_on' {C : α ⧸ s → Prop} (x : α ⧸ s) (H : ∀ z : α, C z) : C x := quotient.induction_on' x H @[simp, to_additive] lemma quotient_lift_on_coe {β} (f : α → β) (h) (x : α) : quotient.lift_on' (x : α ⧸ s) f h = f x := rfl @[to_additive] lemma forall_coe {C : α ⧸ s → Prop} : (∀ x : α ⧸ s, C x) ↔ ∀ x : α, C x := mk_surjective.forall @[to_additive] lemma exists_coe {C : α ⧸ s → Prop} : (∃ x : α ⧸ s, C x) ↔ ∃ x : α, C x := mk_surjective.exists @[to_additive] instance (s : subgroup α) : inhabited (α ⧸ s) := ⟨((1 : α) : α ⧸ s)⟩ @[to_additive quotient_add_group.eq] protected lemma eq {a b : α} : (a : α ⧸ s) = b ↔ a⁻¹ * b ∈ s := calc _ ↔ @setoid.r _ (left_rel s) a b : quotient.eq' ... ↔ _ : by rw left_rel_apply @[to_additive quotient_add_group.eq'] lemma eq' {a b : α} : (mk a : α ⧸ s) = mk b ↔ a⁻¹ * b ∈ s := quotient_group.eq @[simp, to_additive quotient_add_group.out_eq'] lemma out_eq' (a : α ⧸ s) : mk a.out' = a := quotient.out_eq' a variables (s) /- It can be useful to write `obtain ⟨h, H⟩ := mk_out'_eq_mul ...`, and then `rw [H]` or `simp_rw [H]` or `simp only [H]`. In order for `simp_rw` and `simp only` to work, this lemma is stated in terms of an arbitrary `h : s`, rathern that the specific `h = g⁻¹ * (mk g).out'`. -/ @[to_additive quotient_add_group.mk_out'_eq_mul] lemma mk_out'_eq_mul (g : α) : ∃ h : s, (mk g : α ⧸ s).out' = g * h := ⟨⟨g⁻¹ * (mk g).out', eq'.mp (mk g).out_eq'.symm⟩, by rw [set_like.coe_mk, mul_inv_cancel_left]⟩ variables {s} {a b : α} @[simp, to_additive quotient_add_group.mk_add_of_mem] lemma mk_mul_of_mem (a : α) (hb : b ∈ s) : (mk (a * b) : α ⧸ s) = mk a := by rwa [eq', mul_inv_rev, inv_mul_cancel_right, s.inv_mem_iff] @[to_additive] lemma eq_class_eq_left_coset (s : subgroup α) (g : α) : {x : α | (x : α ⧸ s) = g} = left_coset g s := set.ext $ λ z, by rw [mem_left_coset_iff, set.mem_set_of_eq, eq_comm, quotient_group.eq, set_like.mem_coe] @[to_additive] lemma preimage_image_coe (N : subgroup α) (s : set α) : coe ⁻¹' ((coe : α → α ⧸ N) '' s) = ⋃ x : N, (λ y : α, y * x) ⁻¹' s := begin ext x, simp only [quotient_group.eq, set_like.exists, exists_prop, set.mem_preimage, set.mem_Union, set.mem_image, set_like.coe_mk, ← eq_inv_mul_iff_mul_eq], exact ⟨λ ⟨y, hs, hN⟩, ⟨_, N.inv_mem hN, by simpa using hs⟩, λ ⟨z, hz, hxz⟩, ⟨x*z, hxz, by simpa using hz⟩⟩, end end quotient_group namespace subgroup open quotient_group variables [group α] {s : subgroup α} /-- The natural bijection between a left coset `g * s` and `s`. -/ @[to_additive "The natural bijection between the cosets `g + s` and `s`."] def left_coset_equiv_subgroup (g : α) : left_coset g s ≃ s := ⟨λ x, ⟨g⁻¹ * x.1, (mem_left_coset_iff _).1 x.2⟩, λ x, ⟨g * x.1, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ /-- The natural bijection between a right coset `s * g` and `s`. -/ @[to_additive "The natural bijection between the cosets `s + g` and `s`."] def right_coset_equiv_subgroup (g : α) : right_coset ↑s g ≃ s := ⟨λ x, ⟨x.1 * g⁻¹, (mem_right_coset_iff _).1 x.2⟩, λ x, ⟨x.1 * g, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ /-- A (non-canonical) bijection between a group `α` and the product `(α/s) × s` -/ @[to_additive "A (non-canonical) bijection between an add_group `α` and the product `(α/s) × s`"] noncomputable def group_equiv_quotient_times_subgroup : α ≃ (α ⧸ s) × s := calc α ≃ Σ L : α ⧸ s, {x : α // (x : α ⧸ s) = L} : (equiv.sigma_fiber_equiv quotient_group.mk).symm ... ≃ Σ L : α ⧸ s, left_coset (quotient.out' L) s : equiv.sigma_congr_right (λ L, begin rw ← eq_class_eq_left_coset, show _root_.subtype (λ x : α, quotient.mk' x = L) ≃ _root_.subtype (λ x : α, quotient.mk' x = quotient.mk' _), simp [-quotient.eq'], end) ... ≃ Σ L : α ⧸ s, s : equiv.sigma_congr_right (λ L, left_coset_equiv_subgroup _) ... ≃ (α ⧸ s) × s : equiv.sigma_equiv_prod _ _ variables {t : subgroup α} /-- If two subgroups `M` and `N` of `G` are equal, their quotients are in bijection. -/ @[to_additive "If two subgroups `M` and `N` of `G` are equal, their quotients are in bijection."] def quotient_equiv_of_eq (h : s = t) : α ⧸ s ≃ α ⧸ t := { to_fun := quotient.map' id (λ a b h', h ▸ h'), inv_fun := quotient.map' id (λ a b h', h.symm ▸ h'), left_inv := λ q, induction_on' q (λ g, rfl), right_inv := λ q, induction_on' q (λ g, rfl) } lemma quotient_equiv_of_eq_mk (h : s = t) (a : α) : quotient_equiv_of_eq h (quotient_group.mk a) = (quotient_group.mk a) := rfl /-- If `H ≤ K`, then `G/H ≃ G/K × K/H` constructively, using the provided right inverse of the quotient map `G → G/K`. The classical version is `quotient_equiv_prod_of_le`. -/ @[to_additive "If `H ≤ K`, then `G/H ≃ G/K × K/H` constructively, using the provided right inverse of the quotient map `G → G/K`. The classical version is `quotient_equiv_prod_of_le`.", simps] def quotient_equiv_prod_of_le' (h_le : s ≤ t) (f : α ⧸ t → α) (hf : function.right_inverse f quotient_group.mk) : α ⧸ s ≃ (α ⧸ t) × (t ⧸ s.subgroup_of t) := { to_fun := λ a, ⟨a.map' id (λ b c h, left_rel_apply.mpr (h_le (left_rel_apply.mp h))), a.map' (λ g : α, ⟨(f (quotient.mk' g))⁻¹ * g, left_rel_apply.mp (quotient.exact' (hf g))⟩) (λ b c h, by { rw left_rel_apply, change ((f b)⁻¹ * b)⁻¹ * ((f c)⁻¹ * c) ∈ s, have key : f b = f c := congr_arg f (quotient.sound' (left_rel_apply.mpr (h_le (left_rel_apply.mp h)))), rwa [key, mul_inv_rev, inv_inv, mul_assoc, mul_inv_cancel_left, ← left_rel_apply] })⟩, inv_fun := λ a, a.2.map' (λ b, f a.1 * b) (λ b c h, by { rw left_rel_apply at ⊢ h, change (f a.1 * b)⁻¹ * (f a.1 * c) ∈ s, rwa [mul_inv_rev, mul_assoc, inv_mul_cancel_left] }), left_inv := by { refine quotient.ind' (λ a, _), simp_rw [quotient.map'_mk', id.def, set_like.coe_mk, mul_inv_cancel_left] }, right_inv := by { refine prod.rec _, refine quotient.ind' (λ a, _), refine quotient.ind' (λ b, _), have key : quotient.mk' (f (quotient.mk' a) * b) = quotient.mk' a := (quotient_group.mk_mul_of_mem (f a) b.2).trans (hf a), simp_rw [quotient.map'_mk', id.def, key, inv_mul_cancel_left, subtype.coe_eta] } } /-- If `H ≤ K`, then `G/H ≃ G/K × K/H` nonconstructively. The constructive version is `quotient_equiv_prod_of_le'`. -/ @[to_additive "If `H ≤ K`, then `G/H ≃ G/K × K/H` nonconstructively. The constructive version is `quotient_equiv_prod_of_le'`.", simps] noncomputable def quotient_equiv_prod_of_le (h_le : s ≤ t) : α ⧸ s ≃ (α ⧸ t) × (t ⧸ s.subgroup_of t) := quotient_equiv_prod_of_le' h_le quotient.out' quotient.out_eq' /-- If `s ≤ t`, then there is an embedding `s ⧸ H.subgroup_of s ↪ t ⧸ H.subgroup_of t`. -/ @[to_additive "If `s ≤ t`, then there is an embedding `s ⧸ H.add_subgroup_of s ↪ t ⧸ H.add_subgroup_of t`."] def quotient_subgroup_of_embedding_of_le (H : subgroup α) (h : s ≤ t) : s ⧸ H.subgroup_of s ↪ t ⧸ H.subgroup_of t := { to_fun := quotient.map' (inclusion h) (λ a b, by { simp_rw left_rel_eq, exact id }), inj' := quotient.ind₂' $ by { intros a b h, simpa only [quotient.map'_mk', eq'] using h } } @[simp, to_additive] lemma quotient_subgroup_of_embedding_of_le_apply_mk (H : subgroup α) (h : s ≤ t) (g : s) : quotient_subgroup_of_embedding_of_le H h (quotient_group.mk g) = quotient_group.mk (inclusion h g) := rfl /-- If `s ≤ t`, then there is a map `H ⧸ s.subgroup_of H → H ⧸ t.subgroup_of H`. -/ @[to_additive "If `s ≤ t`, then there is an map `H ⧸ s.add_subgroup_of H → H ⧸ t.add_subgroup_of H`."] def quotient_subgroup_of_map_of_le (H : subgroup α) (h : s ≤ t) : H ⧸ s.subgroup_of H → H ⧸ t.subgroup_of H := quotient.map' id $ λ a b, by { simp_rw [left_rel_eq], apply h } @[simp, to_additive] lemma quotient_subgroup_of_map_of_le_apply_mk (H : subgroup α) (h : s ≤ t) (g : H) : quotient_subgroup_of_map_of_le H h (quotient_group.mk g) = quotient_group.mk g := rfl /-- If `s ≤ t`, then there is a map `α ⧸ s → α ⧸ t`. -/ @[to_additive "If `s ≤ t`, then there is an map `α ⧸ s → α ⧸ t`."] def quotient_map_of_le (h : s ≤ t) : α ⧸ s → α ⧸ t := quotient.map' id $ λ a b, by { simp_rw [left_rel_eq], apply h } @[simp, to_additive] lemma quotient_map_of_le_apply_mk (h : s ≤ t) (g : α) : quotient_map_of_le h (quotient_group.mk g) = quotient_group.mk g := rfl /-- The natural embedding `H ⧸ (⨅ i, f i).subgroup_of H ↪ Π i, H ⧸ (f i).subgroup_of H`. -/ @[to_additive "The natural embedding `H ⧸ (⨅ i, f i).add_subgroup_of H) ↪ Π i, H ⧸ (f i).add_subgroup_of H`.", simps] def quotient_infi_subgroup_of_embedding {ι : Type*} (f : ι → subgroup α) (H : subgroup α) : H ⧸ (⨅ i, f i).subgroup_of H ↪ Π i, H ⧸ (f i).subgroup_of H := { to_fun := λ q i, quotient_subgroup_of_map_of_le H (infi_le f i) q, inj' := quotient.ind₂' $ by simp_rw [funext_iff, quotient_subgroup_of_map_of_le_apply_mk, eq', mem_subgroup_of, mem_infi, imp_self, forall_const] } @[simp, to_additive] lemma quotient_infi_subgroup_of_embedding_apply_mk {ι : Type*} (f : ι → subgroup α) (H : subgroup α) (g : H) (i : ι) : quotient_infi_subgroup_of_embedding f H (quotient_group.mk g) i = quotient_group.mk g := rfl /-- The natural embedding `α ⧸ (⨅ i, f i) ↪ Π i, α ⧸ f i`. -/ @[to_additive "The natural embedding `α ⧸ (⨅ i, f i) ↪ Π i, α ⧸ f i`.", simps] def quotient_infi_embedding {ι : Type*} (f : ι → subgroup α) : α ⧸ (⨅ i, f i) ↪ Π i, α ⧸ f i := { to_fun := λ q i, quotient_map_of_le (infi_le f i) q, inj' := quotient.ind₂' $ by simp_rw [funext_iff, quotient_map_of_le_apply_mk, eq', mem_infi, imp_self, forall_const] } @[simp, to_additive] lemma quotient_infi_embedding_apply_mk {ι : Type*} (f : ι → subgroup α) (g : α) (i : ι) : quotient_infi_embedding f (quotient_group.mk g) i = quotient_group.mk g := rfl @[to_additive] lemma card_eq_card_quotient_mul_card_subgroup [fintype α] (s : subgroup α) [fintype s] [decidable_pred (λ a, a ∈ s)] : fintype.card α = fintype.card (α ⧸ s) * fintype.card s := by rw ← fintype.card_prod; exact fintype.card_congr (subgroup.group_equiv_quotient_times_subgroup) /-- **Lagrange's Theorem**: The order of a subgroup divides the order of its ambient group. -/ @[to_additive "**Lagrange's Theorem**: The order of an additive subgroup divides the order of its ambient group."] lemma card_subgroup_dvd_card [fintype α] (s : subgroup α) [fintype s] : fintype.card s ∣ fintype.card α := by classical; simp [card_eq_card_quotient_mul_card_subgroup s, @dvd_mul_left ℕ] @[to_additive] lemma card_quotient_dvd_card [fintype α] (s : subgroup α) [decidable_pred (∈ s)] : fintype.card (α ⧸ s) ∣ fintype.card α := by simp [card_eq_card_quotient_mul_card_subgroup s, @dvd_mul_right ℕ] open fintype variables {H : Type*} [group H] @[to_additive] lemma card_dvd_of_injective [fintype α] [fintype H] (f : α →* H) (hf : function.injective f) : card α ∣ card H := by classical; calc card α = card (f.range : subgroup H) : card_congr (equiv.of_injective f hf) ...∣ card H : card_subgroup_dvd_card _ @[to_additive] lemma card_dvd_of_le {H K : subgroup α} [fintype H] [fintype K] (hHK : H ≤ K) : card H ∣ card K := card_dvd_of_injective (inclusion hHK) (inclusion_injective hHK) @[to_additive] lemma card_comap_dvd_of_injective (K : subgroup H) [fintype K] (f : α →* H) [fintype (K.comap f)] (hf : function.injective f) : fintype.card (K.comap f) ∣ fintype.card K := by haveI : fintype ((K.comap f).map f) := fintype.of_equiv _ (equiv_map_of_injective _ _ hf).to_equiv; calc fintype.card (K.comap f) = fintype.card ((K.comap f).map f) : fintype.card_congr (equiv_map_of_injective _ _ hf).to_equiv ... ∣ fintype.card K : card_dvd_of_le (map_comap_le _ _) end subgroup namespace quotient_group variables [group α] /-- If `s` is a subgroup of the group `α`, and `t` is a subset of `α ⧸ s`, then there is a (typically non-canonical) bijection between the preimage of `t` in `α` and the product `s × t`. -/ @[to_additive "If `s` is a subgroup of the additive group `α`, and `t` is a subset of `α ⧸ s`, then there is a (typically non-canonical) bijection between the preimage of `t` in `α` and the product `s × t`."] noncomputable def preimage_mk_equiv_subgroup_times_set (s : subgroup α) (t : set (α ⧸ s)) : quotient_group.mk ⁻¹' t ≃ s × t := { to_fun := λ a, ⟨⟨(quotient.out' (quotient_group.mk a))⁻¹ * a, left_rel_apply.mp (@quotient.exact' _ (left_rel s) _ _ $ (quotient.out_eq' _))⟩, ⟨quotient_group.mk a, a.2⟩⟩, inv_fun := λ a, ⟨quotient.out' a.2.1 * a.1.1, show quotient_group.mk _ ∈ t, by { rw [mk_mul_of_mem _ a.1.2, out_eq'], exact a.2.2 }⟩, left_inv := λ ⟨a, ha⟩, subtype.eq $ show _ * _ = a, by simp, right_inv := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, by ext; simp [ha] } end quotient_group /-- We use the class `has_coe_t` instead of `has_coe` if the first argument is a variable, or if the second argument is a variable not occurring in the first. Using `has_coe` would cause looping of type-class inference. See <https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/remove.20all.20instances.20with.20variable.20domain> -/ library_note "use has_coe_t"
f1519bca90d6b1d3df23ca50542cb5f0fca252d9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/equiv/encodable/lattice.lean
b8d55e99620d4d7b9632675901a99c304a7ce9b6
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,841
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.equiv.encodable.basic import Mathlib.data.finset.basic import Mathlib.data.set.disjointed import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Lattice operations on encodable types Lemmas about lattice and set operations on encodable types ## Implementation Notes This is a separate file, to avoid unnecessary imports in basic files. Previously some of these results were in the `measure_theory` folder. -/ namespace encodable theorem supr_decode2 {α : Type u_1} {β : Type u_2} [encodable β] [complete_lattice α] (f : β → α) : (supr fun (i : ℕ) => supr fun (b : β) => supr fun (H : b ∈ decode2 β i) => f b) = supr fun (b : β) => f b := sorry theorem Union_decode2 {α : Type u_1} {β : Type u_2} [encodable β] (f : β → set α) : (set.Union fun (i : ℕ) => set.Union fun (b : β) => set.Union fun (H : b ∈ decode2 β i) => f b) = set.Union fun (b : β) => f b := supr_decode2 f theorem Union_decode2_cases {α : Type u_1} {β : Type u_2} [encodable β] {f : β → set α} {C : set α → Prop} (H0 : C ∅) (H1 : ∀ (b : β), C (f b)) {n : ℕ} : C (set.Union fun (b : β) => set.Union fun (H : b ∈ decode2 β n) => f b) := sorry theorem Union_decode2_disjoint_on {α : Type u_1} {β : Type u_2} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) : pairwise (disjoint on fun (i : ℕ) => set.Union fun (b : β) => set.Union fun (H : b ∈ decode2 β i) => f b) := sorry end encodable namespace finset theorem nonempty_encodable {α : Type u_1} (t : finset α) : Nonempty (encodable (Subtype fun (i : α) => i ∈ t)) := sorry
102890fd4f081d84daa18f1eb9c59fc1e0290889
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/cancel_denoms.lean
5b241ad0d12e4ee6b072073ea3e9d5a6a9b9b0ba
[ "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
9,206
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.rat.meta_defs import tactic.norm_num import data.tree import meta.expr /-! # A tactic for canceling numeric denominators This file defines tactics that cancel numeric denominators from field expressions. As an example, we want to transform a comparison `5*(a/3 + b/4) < c/3` into the equivalent `5*(4*a + 3*b) < 4*c`. ## Implementation notes The tooling here was originally written for `linarith`, not intended as an interactive tactic. The interactive version has been split off because it is sometimes convenient to use on its own. There are likely some rough edges to it. Improving this tactic would be a good project for someone interested in learning tactic programming. -/ namespace cancel_factors /-! ### Lemmas used in the procedure -/ lemma mul_subst {α} [comm_ring α] {n1 n2 k e1 e2 t1 t2 : α} (h1 : n1 * e1 = t1) (h2 : n2 * e2 = t2) (h3 : n1*n2 = k) : k * (e1 * e2) = t1 * t2 := by rw [←h3, mul_comm n1, mul_assoc n2, ←mul_assoc n1, h1, ←mul_assoc n2, mul_comm n2, mul_assoc, h2] lemma div_subst {α} [field α] {n1 n2 k e1 e2 t1 : α} (h1 : n1 * e1 = t1) (h2 : n2 / e2 = 1) (h3 : n1*n2 = k) : k * (e1 / e2) = t1 := by rw [←h3, mul_assoc, mul_div_left_comm, h2, ←mul_assoc, h1, mul_comm, one_mul] lemma cancel_factors_eq_div {α} [field α] {n e e' : α} (h : n*e = e') (h2 : n ≠ 0) : e = e' / n := eq_div_of_mul_eq h2 $ by rwa mul_comm at h lemma add_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 + e2) = t1 + t2 := by simp [left_distrib, *] lemma sub_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 - e2) = t1 - t2 := by simp [left_distrib, *, sub_eq_add_neg] lemma neg_subst {α} [ring α] {n e t : α} (h1 : n * e = t) : n * (-e) = -t := by simp * lemma cancel_factors_lt {α} [linear_ordered_field α] {a b ad bd a' b' gcd : α} (ha : ad*a = a') (hb : bd*b = b') (had : 0 < ad) (hbd : 0 < bd) (hgcd : 0 < gcd) : a < b = ((1/gcd)*(bd*a') < (1/gcd)*(ad*b')) := begin rw [mul_lt_mul_left, ←ha, ←hb, ←mul_assoc, ←mul_assoc, mul_comm bd, mul_lt_mul_left], exact mul_pos had hbd, exact one_div_pos.2 hgcd end lemma cancel_factors_le {α} [linear_ordered_field α] {a b ad bd a' b' gcd : α} (ha : ad*a = a') (hb : bd*b = b') (had : 0 < ad) (hbd : 0 < bd) (hgcd : 0 < gcd) : a ≤ b = ((1/gcd)*(bd*a') ≤ (1/gcd)*(ad*b')) := begin rw [mul_le_mul_left, ←ha, ←hb, ←mul_assoc, ←mul_assoc, mul_comm bd, mul_le_mul_left], exact mul_pos had hbd, exact one_div_pos.2 hgcd end lemma cancel_factors_eq {α} [linear_ordered_field α] {a b ad bd a' b' gcd : α} (ha : ad*a = a') (hb : bd*b = b') (had : 0 < ad) (hbd : 0 < bd) (hgcd : 0 < gcd) : a = b = ((1/gcd)*(bd*a') = (1/gcd)*(ad*b')) := begin rw [←ha, ←hb, ←mul_assoc bd, ←mul_assoc ad, mul_comm bd], ext, split, { rintro rfl, refl }, { intro h, simp only [←mul_assoc] at h, refine mul_left_cancel₀ (mul_ne_zero _ _) h, apply mul_ne_zero, apply div_ne_zero, all_goals {apply ne_of_gt; assumption <|> exact zero_lt_one}} end open tactic expr /-! ### Computing cancelation factors -/ open tree /-- `find_cancel_factor e` produces a natural number `n`, such that multiplying `e` by `n` will be able to cancel all the numeric denominators in `e`. The returned `tree` describes how to distribute the value `n` over products inside `e`. -/ meta def find_cancel_factor : expr → ℕ × tree ℕ | `(%%e1 + %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, node lcm t1 t2) | `(%%e1 - %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, node lcm t1 t2) | `(%%e1 * %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, pd := v1*v2 in (pd, node pd t1 t2) | `(%%e1 / %%e2) := match e2.to_nonneg_rat with | some q := let (v1, t1) := find_cancel_factor e1, n := v1.lcm q.num.nat_abs in (n, node n t1 (node q.num.nat_abs tree.nil tree.nil)) | none := (1, node 1 tree.nil tree.nil) end | `(-%%e) := find_cancel_factor e | _ := (1, node 1 tree.nil tree.nil) /-- `mk_prod_prf n tr e` produces a proof of `n*e = e'`, where numeric denominators have been canceled in `e'`, distributing `n` proportionally according to `tr`. -/ meta def mk_prod_prf : ℕ → tree ℕ → expr → tactic expr | v (node _ lhs rhs) `(%%e1 + %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``add_subst [v1, v2] | v (node _ lhs rhs) `(%%e1 - %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``sub_subst [v1, v2] | v (node n lhs@(node ln _ _) rhs) `(%%e1 * %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf ln lhs e1, v2 ← mk_prod_prf (v/ln) rhs e2, ln' ← tp.of_nat ln, vln' ← tp.of_nat (v/ln), v' ← tp.of_nat v, ntp ← to_expr ``(%%ln' * %%vln' = %%v'), (_, npf) ← solve_aux ntp `[norm_num, done], mk_app ``mul_subst [v1, v2, npf] | v (node n lhs rhs@(node rn _ _)) `(%%e1 / %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf (v/rn) lhs e1, rn' ← tp.of_nat rn, vrn' ← tp.of_nat (v/rn), n' ← tp.of_nat n, v' ← tp.of_nat v, ntp ← to_expr ``(%%rn' / %%e2 = 1), (_, npf) ← solve_aux ntp `[norm_num, done], ntp2 ← to_expr ``(%%vrn' * %%n' = %%v'), (_, npf2) ← solve_aux ntp2 `[norm_num, done], mk_app ``div_subst [v1, npf, npf2] | v t `(-%%e) := do v' ← mk_prod_prf v t e, mk_app ``neg_subst [v'] | v _ e := do tp ← infer_type e, v' ← tp.of_nat v, e' ← to_expr ``(%%v' * %%e), mk_app `eq.refl [e'] /-- Given `e`, a term with rational division, produces a natural number `n` and a proof of `n*e = e'`, where `e'` has no division. Assumes "well-behaved" division. -/ meta def derive (e : expr) : tactic (ℕ × expr) := let (n, t) := find_cancel_factor e in prod.mk n <$> mk_prod_prf n t e <|> fail!"cancel_factors.derive failed to normalize {e}. Are you sure this is well-behaved division?" /-- Given `e`, a term with rational divison, produces a natural number `n` and a proof of `e = e' / n`, where `e'` has no divison. Assumes "well-behaved" division. -/ meta def derive_div (e : expr) : tactic (ℕ × expr) := do (n, p) ← derive e, tp ← infer_type e, n' ← tp.of_nat n, tgt ← to_expr ``(%%n' ≠ 0), (_, pn) ← solve_aux tgt `[norm_num, done], prod.mk n <$> mk_mapp ``cancel_factors_eq_div [none, none, n', none, none, p, pn] /-- `find_comp_lemma e` arranges `e` in the form `lhs R rhs`, where `R ∈ {<, ≤, =}`, and returns `lhs`, `rhs`, and the `cancel_factors` lemma corresponding to `R`. -/ meta def find_comp_lemma : expr → option (expr × expr × name) | `(%%a < %%b) := (a, b, ``cancel_factors_lt) | `(%%a ≤ %%b) := (a, b, ``cancel_factors_le) | `(%%a = %%b) := (a, b, ``cancel_factors_eq) | `(%%a ≥ %%b) := (b, a, ``cancel_factors_le) | `(%%a > %%b) := (b, a, ``cancel_factors_lt) | _ := none /-- `cancel_denominators_in_type h` assumes that `h` is of the form `lhs R rhs`, where `R ∈ {<, ≤, =, ≥, >}`. It produces an expression `h'` of the form `lhs' R rhs'` and a proof that `h = h'`. Numeric denominators have been canceled in `lhs'` and `rhs'`. -/ meta def cancel_denominators_in_type (h : expr) : tactic (expr × expr) := do some (lhs, rhs, lem) ← return $ find_comp_lemma h | fail "cannot kill factors", (al, lhs_p) ← derive lhs, (ar, rhs_p) ← derive rhs, let gcd := al.gcd ar, tp ← infer_type lhs, al ← tp.of_nat al, ar ← tp.of_nat ar, gcd ← tp.of_nat gcd, al_pos ← to_expr ``(0 < %%al), ar_pos ← to_expr ``(0 < %%ar), gcd_pos ← to_expr ``(0 < %%gcd), (_, al_pos) ← solve_aux al_pos `[norm_num, done], (_, ar_pos) ← solve_aux ar_pos `[norm_num, done], (_, gcd_pos) ← solve_aux gcd_pos `[norm_num, done], pf ← mk_app lem [lhs_p, rhs_p, al_pos, ar_pos, gcd_pos], pf_tp ← infer_type pf, return ((find_comp_lemma pf_tp).elim default (prod.fst ∘ prod.snd), pf) end cancel_factors /-! ### Interactive version -/ setup_tactic_parser open tactic expr cancel_factors /-- `cancel_denoms` attempts to remove numerals from the denominators of fractions. It works on propositions that are field-valued inequalities. ```lean variables {α : Type} [linear_ordered_field α] (a b c : α) example (h : a / 5 + b / 4 < c) : 4*a + 5*b < 20*c := begin cancel_denoms at h, exact h end example (h : a > 0) : a / 5 > 0 := begin cancel_denoms, exact h end ``` -/ meta def tactic.interactive.cancel_denoms (l : parse location) : tactic unit := do locs ← l.get_locals, tactic.replace_at cancel_denominators_in_type locs l.include_goal >>= guardb <|> fail "failed to cancel any denominators", tactic.interactive.norm_num [simp_arg_type.symm_expr ``(mul_assoc)] l add_tactic_doc { name := "cancel_denoms", category := doc_category.tactic, decl_names := [`tactic.interactive.cancel_denoms], tags := ["simplification"] }
100216937bce456498e796895d74d0372c792c00
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/asymptotic_equivalent.lean
ff9bd01f360035010759e14a7d6b3e87e1ec6869
[]
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,627
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.asymptotics import Mathlib.analysis.normed_space.ordered import Mathlib.analysis.normed_space.bounded_linear_maps import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # Asymptotic equivalence In this file, we define the relation `is_equivalent u v l`, which means that `u-v` is little o of `v` along the filter `l`. Unlike `is_[oO]` relations, this one requires `u` and `v` to have the same codomaine `β`. While the definition only requires `β` to be a `normed_group`, most interesting properties require it to be a `normed_field`. ## Notations We introduce the notation `u ~[l] v := is_equivalent u v l`, which you can use by opening the `asymptotics` locale. ## Main results If `β` is a `normed_group` : - `_ ~[l] _` is an equivalence relation - Equivalent statements for `u ~[l] const _ c` : - If `c ≠ 0`, this is true iff `tendsto u l (𝓝 c)` (see `is_equivalent_const_iff_tendsto`) - For `c = 0`, this is true iff `u =ᶠ[l] 0` (see `is_equivalent_zero_iff_eventually_zero`) If `β` is a `normed_field` : - Alternative characterization of the relation (see `is_equivalent_iff_exists_eq_mul`) : `u ~[l] v ↔ ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v` - Provided some non-vanishing hypothesis, this can be seen as `u ~[l] v ↔ tendsto (u/v) l (𝓝 1)` (see `is_equivalent_iff_tendsto_one`) - For any constant `c`, `u ~[l] v` implies `tendsto u l (𝓝 c) ↔ tendsto v l (𝓝 c)` (see `is_equivalent.tendsto_nhds_iff`) - `*` and `/` are compatible with `_ ~[l] _` (see `is_equivalent.mul` and `is_equivalent.div`) If `β` is a `normed_linear_ordered_field` : - If `u ~[l] v`, we have `tendsto u l at_top ↔ tendsto v l at_top` (see `is_equivalent.tendsto_at_top_iff`) -/ namespace asymptotics /-- Two functions `u` and `v` are said to be asymptotically equivalent along a filter `l` when `u x - v x = o(v x)` as x converges along `l`. -/ def is_equivalent {α : Type u_1} {β : Type u_2} [normed_group β] (u : α → β) (v : α → β) (l : filter α) := is_o (u - v) v l theorem is_equivalent.is_o {α : Type u_1} {β : Type u_2} [normed_group β] {u : α → β} {v : α → β} {l : filter α} (h : is_equivalent u v l) : is_o (u - v) v l := h theorem is_equivalent.is_O {α : Type u_1} {β : Type u_2} [normed_group β] {u : α → β} {v : α → β} {l : filter α} (h : is_equivalent u v l) : is_O u v l := iff.mp (is_O.congr_of_sub (is_O.symm (is_o.is_O h))) (is_O_refl (fun (x : α) => v x) l) theorem is_equivalent.is_O_symm {α : Type u_1} {β : Type u_2} [normed_group β] {u : α → β} {v : α → β} {l : filter α} (h : is_equivalent u v l) : is_O v u l := sorry theorem is_equivalent.refl {α : Type u_1} {β : Type u_2} [normed_group β] {u : α → β} {l : filter α} : is_equivalent u u l := eq.mpr (id (Eq._oldrec (Eq.refl (is_equivalent u u l)) (is_equivalent.equations._eqn_1 u u l))) (eq.mpr (id (Eq._oldrec (Eq.refl (is_o (u - u) u l)) (sub_self u))) (is_o_zero u l)) theorem is_equivalent.symm {α : Type u_1} {β : Type u_2} [normed_group β] {u : α → β} {v : α → β} {l : filter α} (h : is_equivalent u v l) : is_equivalent v u l := is_o.symm (is_o.trans_is_O (is_equivalent.is_o h) (is_equivalent.is_O_symm h)) theorem is_equivalent.trans {α : Type u_1} {β : Type u_2} [normed_group β] {u : α → β} {v : α → β} {w : α → β} {l : filter α} (huv : is_equivalent u v l) (hvw : is_equivalent v w l) : is_equivalent u w l := is_o.triangle (is_o.trans_is_O (is_equivalent.is_o huv) (is_equivalent.is_O hvw)) (is_equivalent.is_o hvw) theorem is_equivalent_zero_iff_eventually_zero {α : Type u_1} {β : Type u_2} [normed_group β] {u : α → β} {l : filter α} : is_equivalent u 0 l ↔ filter.eventually_eq l u 0 := eq.mpr (id (Eq._oldrec (Eq.refl (is_equivalent u 0 l ↔ filter.eventually_eq l u 0)) (is_equivalent.equations._eqn_1 u 0 l))) (eq.mpr (id (Eq._oldrec (Eq.refl (is_o (u - 0) 0 l ↔ filter.eventually_eq l u 0)) (sub_zero u))) is_o_zero_right_iff) theorem is_equivalent_const_iff_tendsto {α : Type u_1} {β : Type u_2} [normed_group β] {u : α → β} {l : filter α} {c : β} (h : c ≠ 0) : is_equivalent u (function.const α c) l ↔ filter.tendsto u l (nhds c) := sorry theorem is_equivalent.tendsto_const {α : Type u_1} {β : Type u_2} [normed_group β] {u : α → β} {l : filter α} {c : β} (hu : is_equivalent u (function.const α c) l) : filter.tendsto u l (nhds c) := sorry theorem is_equivalent.tendsto_nhds {α : Type u_1} {β : Type u_2} [normed_group β] {u : α → β} {v : α → β} {l : filter α} {c : β} (huv : is_equivalent u v l) (hu : filter.tendsto u l (nhds c)) : filter.tendsto v l (nhds c) := sorry theorem is_equivalent.tendsto_nhds_iff {α : Type u_1} {β : Type u_2} [normed_group β] {u : α → β} {v : α → β} {l : filter α} {c : β} (huv : is_equivalent u v l) : filter.tendsto u l (nhds c) ↔ filter.tendsto v l (nhds c) := { mp := is_equivalent.tendsto_nhds huv, mpr := is_equivalent.tendsto_nhds (is_equivalent.symm huv) } theorem is_equivalent_iff_exists_eq_mul {α : Type u_1} {β : Type u_2} [normed_field β] {u : α → β} {v : α → β} {l : filter α} : is_equivalent u v l ↔ ∃ (φ : α → β), ∃ (hφ : filter.tendsto φ l (nhds 1)), filter.eventually_eq l u (φ * v) := sorry theorem is_equivalent.exists_eq_mul {α : Type u_1} {β : Type u_2} [normed_field β] {u : α → β} {v : α → β} {l : filter α} (huv : is_equivalent u v l) : ∃ (φ : α → β), ∃ (hφ : filter.tendsto φ l (nhds 1)), filter.eventually_eq l u (φ * v) := iff.mp is_equivalent_iff_exists_eq_mul huv theorem is_equivalent_of_tendsto_one {α : Type u_1} {β : Type u_2} [normed_field β] {u : α → β} {v : α → β} {l : filter α} (hz : filter.eventually (fun (x : α) => v x = 0 → u x = 0) l) (huv : filter.tendsto (u / v) l (nhds 1)) : is_equivalent u v l := sorry theorem is_equivalent_of_tendsto_one' {α : Type u_1} {β : Type u_2} [normed_field β] {u : α → β} {v : α → β} {l : filter α} (hz : ∀ (x : α), v x = 0 → u x = 0) (huv : filter.tendsto (u / v) l (nhds 1)) : is_equivalent u v l := is_equivalent_of_tendsto_one (filter.eventually_of_forall hz) huv theorem is_equivalent_iff_tendsto_one {α : Type u_1} {β : Type u_2} [normed_field β] {u : α → β} {v : α → β} {l : filter α} (hz : filter.eventually (fun (x : α) => v x ≠ 0) l) : is_equivalent u v l ↔ filter.tendsto (u / v) l (nhds 1) := sorry theorem is_equivalent.smul {α : Type u_1} {E : Type u_2} {𝕜 : Type u_3} [normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] {a : α → 𝕜} {b : α → 𝕜} {u : α → E} {v : α → E} {l : filter α} (hab : is_equivalent a b l) (huv : is_equivalent u v l) : is_equivalent (fun (x : α) => a x • u x) (fun (x : α) => b x • v x) l := sorry theorem is_equivalent.mul {α : Type u_1} {β : Type u_2} [normed_field β] {t : α → β} {u : α → β} {v : α → β} {w : α → β} {l : filter α} (htu : is_equivalent t u l) (hvw : is_equivalent v w l) : is_equivalent (t * v) (u * w) l := is_equivalent.smul htu hvw theorem is_equivalent.inv {α : Type u_1} {β : Type u_2} [normed_field β] {u : α → β} {v : α → β} {l : filter α} (huv : is_equivalent u v l) : is_equivalent (fun (x : α) => u x⁻¹) (fun (x : α) => v x⁻¹) l := sorry theorem is_equivalent.div {α : Type u_1} {β : Type u_2} [normed_field β] {t : α → β} {u : α → β} {v : α → β} {w : α → β} {l : filter α} (htu : is_equivalent t u l) (hvw : is_equivalent v w l) : is_equivalent (fun (x : α) => t x / v x) (fun (x : α) => u x / w x) l := is_equivalent.mul htu (is_equivalent.inv hvw) theorem is_equivalent.tendsto_at_top {α : Type u_1} {β : Type u_2} [normed_linear_ordered_field β] {u : α → β} {v : α → β} {l : filter α} [order_topology β] (huv : is_equivalent u v l) (hu : filter.tendsto u l filter.at_top) : filter.tendsto v l filter.at_top := sorry theorem is_equivalent.tendsto_at_top_iff {α : Type u_1} {β : Type u_2} [normed_linear_ordered_field β] {u : α → β} {v : α → β} {l : filter α} [order_topology β] (huv : is_equivalent u v l) : filter.tendsto u l filter.at_top ↔ filter.tendsto v l filter.at_top := { mp := is_equivalent.tendsto_at_top huv, mpr := is_equivalent.tendsto_at_top (is_equivalent.symm huv) }
ad13a17d64ab30bd35e913251e2db815f17a7403
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/types/trunc.hlean
2b4ce8b49b5665fb889469a5e7e94291c22502a0
[ "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
10,149
hlean
/- Copyright (c) 2015 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Properties of is_trunc and trunctype -/ -- NOTE: the fact that (is_trunc n A) is a mere proposition is proved in .hprop_trunc import types.pi types.eq types.equiv ..function open eq sigma sigma.ops pi function equiv is_trunc.trunctype is_equiv prod is_trunc.trunc_index pointed nat namespace is_trunc variables {A B : Type} {n : trunc_index} /- theorems about trunctype -/ protected definition trunctype.sigma_char.{l} (n : trunc_index) : (trunctype.{l} n) ≃ (Σ (A : Type.{l}), is_trunc n A) := begin fapply equiv.MK, { intro A, exact (⟨carrier A, struct A⟩)}, { intro S, exact (trunctype.mk S.1 S.2)}, { intro S, induction S with S1 S2, reflexivity}, { intro A, induction A with A1 A2, reflexivity}, end definition trunctype_eq_equiv (n : trunc_index) (A B : n-Type) : (A = B) ≃ (carrier A = carrier B) := calc (A = B) ≃ (to_fun (trunctype.sigma_char n) A = to_fun (trunctype.sigma_char n) B) : eq_equiv_fn_eq_of_equiv ... ≃ ((to_fun (trunctype.sigma_char n) A).1 = (to_fun (trunctype.sigma_char n) B).1) : equiv.symm (!equiv_subtype) ... ≃ (carrier A = carrier B) : equiv.refl theorem is_trunc_is_embedding_closed (f : A → B) [Hf : is_embedding f] [HB : is_trunc n B] (Hn : -1 ≤ n) : is_trunc n A := begin induction n with n, {exact !empty.elim Hn}, {apply is_trunc_succ_intro, intro a a', fapply @is_trunc_is_equiv_closed_rev _ _ n (ap f)} end theorem is_trunc_is_retraction_closed (f : A → B) [Hf : is_retraction f] (n : trunc_index) [HA : is_trunc n A] : is_trunc n B := begin revert A B f Hf HA, induction n with n IH, { intro A B f Hf HA, induction Hf with g ε, fapply is_contr.mk, { exact f (center A)}, { intro b, apply concat, { apply (ap f), exact (center_eq (g b))}, { apply ε}}}, { intro A B f Hf HA, induction Hf with g ε, apply is_trunc_succ_intro, intro b b', fapply (IH (g b = g b')), { intro q, exact ((ε b)⁻¹ ⬝ ap f q ⬝ ε b')}, { apply (is_retraction.mk (ap g)), { intro p, induction p, {rewrite [↑ap, con.left_inv]}}}, { apply is_trunc_eq}} end definition is_embedding_to_fun (A B : Type) : is_embedding (@to_fun A B) := λf f', !is_equiv_ap_to_fun theorem is_trunc_trunctype [instance] (n : trunc_index) : is_trunc n.+1 (n-Type) := begin apply is_trunc_succ_intro, intro X Y, fapply is_trunc_equiv_closed, {apply equiv.symm, apply trunctype_eq_equiv}, fapply is_trunc_equiv_closed, {apply equiv.symm, apply eq_equiv_equiv}, induction n, {apply @is_contr_of_inhabited_hprop, {apply is_trunc_is_embedding_closed, {apply is_embedding_to_fun} , {exact unit.star}}, {apply equiv_of_is_contr_of_is_contr}}, {apply is_trunc_is_embedding_closed, {apply is_embedding_to_fun}, {exact unit.star}} end /- theorems about decidable equality and axiom K -/ theorem is_hset_of_axiom_K {A : Type} (K : Π{a : A} (p : a = a), p = idp) : is_hset A := is_hset.mk _ (λa b p q, eq.rec_on q K p) theorem is_hset_of_relation.{u} {A : Type.{u}} (R : A → A → Type.{u}) (mere : Π(a b : A), is_hprop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) : is_hset A := is_hset_of_axiom_K (λa p, have H2 : transport (λx, R a x → a = x) p (@imp a a) = @imp a a, from !apd, have H3 : Π(r : R a a), transport (λx, a = x) p (imp r) = imp (transport (λx, R a x) p r), from to_fun (equiv.symm !heq_pi) H2, have H4 : imp (refl a) ⬝ p = imp (refl a), from calc imp (refl a) ⬝ p = transport (λx, a = x) p (imp (refl a)) : transport_eq_r ... = imp (transport (λx, R a x) p (refl a)) : H3 ... = imp (refl a) : is_hprop.elim, cancel_left H4) definition relation_equiv_eq {A : Type} (R : A → A → Type) (mere : Π(a b : A), is_hprop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) (a b : A) : R a b ≃ a = b := @equiv_of_is_hprop _ _ _ (@is_trunc_eq _ _ (is_hset_of_relation R mere refl @imp) a b) imp (λp, p ▸ refl a) local attribute not [reducible] theorem is_hset_of_double_neg_elim {A : Type} (H : Π(a b : A), ¬¬a = b → a = b) : is_hset A := is_hset_of_relation (λa b, ¬¬a = b) _ (λa n, n idp) H section open decidable --this is proven differently in init.hedberg theorem is_hset_of_decidable_eq (A : Type) [H : decidable_eq A] : is_hset A := is_hset_of_double_neg_elim (λa b, by_contradiction) end theorem is_trunc_of_axiom_K_of_leq {A : Type} (n : trunc_index) (H : -1 ≤ n) (K : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A := @is_trunc_succ_intro _ _ (λa b, is_trunc_of_imp_is_trunc_of_leq H (λp, eq.rec_on p !K)) theorem is_trunc_succ_of_is_trunc_loop (Hn : -1 ≤ n) (Hp : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A := begin apply is_trunc_succ_intro, intros a a', apply is_trunc_of_imp_is_trunc_of_leq Hn, intro p, induction p, apply Hp end theorem is_hprop_iff_is_contr {A : Type} (a : A) : is_hprop A ↔ is_contr A := iff.intro (λH, is_contr.mk a (is_hprop.elim a)) _ theorem is_trunc_succ_iff_is_trunc_loop (A : Type) (Hn : -1 ≤ n) : is_trunc (n.+1) A ↔ Π(a : A), is_trunc n (a = a) := iff.intro _ (is_trunc_succ_of_is_trunc_loop Hn) theorem is_trunc_iff_is_contr_loop_succ (n : ℕ) (A : Type) : is_trunc n A ↔ Π(a : A), is_contr (Ω[succ n](Pointed.mk a)) := begin revert A, induction n with n IH, { intro A, esimp [Iterated_loop_space], transitivity _, { apply is_trunc_succ_iff_is_trunc_loop, apply le.refl}, { apply pi_iff_pi, intro a, esimp, apply is_hprop_iff_is_contr, reflexivity}}, { intro A, esimp [Iterated_loop_space], transitivity _, apply @is_trunc_succ_iff_is_trunc_loop @n, esimp, constructor, apply pi_iff_pi, intro a, transitivity _, apply IH, transitivity _, apply pi_iff_pi, intro p, rewrite [iterated_loop_space_loop_irrel n p], apply iff.refl, esimp, apply imp_iff, reflexivity} end theorem is_trunc_iff_is_contr_loop (n : ℕ) (A : Type) : is_trunc (n.-2.+1) A ↔ (Π(a : A), is_contr (Ω[n](pointed.Mk a))) := begin induction n with n, { esimp [sub_two,Iterated_loop_space], apply iff.intro, intro H a, exact is_contr_of_inhabited_hprop a, intro H, apply is_hprop_of_imp_is_contr, exact H}, { apply is_trunc_iff_is_contr_loop_succ}, end theorem is_contr_loop_of_is_trunc (n : ℕ) (A : Type*) [H : is_trunc (n.-2.+1) A] : is_contr (Ω[n] A) := begin induction A, apply iff.mp !is_trunc_iff_is_contr_loop H end end is_trunc open is_trunc namespace trunc variable {A : Type} protected definition code (n : trunc_index) (aa aa' : trunc n.+1 A) : n-Type := trunc.rec_on aa (λa, trunc.rec_on aa' (λa', trunctype.mk' n (trunc n (a = a')))) protected definition encode (n : trunc_index) (aa aa' : trunc n.+1 A) : aa = aa' → trunc.code n aa aa' := begin intro p, induction p, induction aa with a, esimp [trunc.code,trunc.rec_on], exact (tr idp) end protected definition decode (n : trunc_index) (aa aa' : trunc n.+1 A) : trunc.code n aa aa' → aa = aa' := begin induction aa' with a', induction aa with a, esimp [trunc.code, trunc.rec_on], intro x, induction x with p, exact ap tr p, end definition trunc_eq_equiv [constructor] (n : trunc_index) (aa aa' : trunc n.+1 A) : aa = aa' ≃ trunc.code n aa aa' := begin fapply equiv.MK, { apply trunc.encode}, { apply trunc.decode}, { eapply (trunc.rec_on aa'), eapply (trunc.rec_on aa), intro a a' x, esimp [trunc.code, trunc.rec_on] at x, refine (@trunc.rec_on n _ _ x _ _), intro x, apply is_trunc_eq, intro p, induction p, reflexivity}, { intro p, induction p, apply (trunc.rec_on aa), intro a, exact idp}, end definition tr_eq_tr_equiv [constructor] (n : trunc_index) (a a' : A) : (tr a = tr a' :> trunc n.+1 A) ≃ trunc n (a = a') := !trunc_eq_equiv definition is_trunc_trunc_of_is_trunc [instance] [priority 500] (A : Type) (n m : trunc_index) [H : is_trunc n A] : is_trunc n (trunc m A) := begin revert A m H, eapply (trunc_index.rec_on n), { clear n, intro A m H, apply is_contr_equiv_closed, { apply equiv.symm, apply trunc_equiv, apply (@is_trunc_of_leq _ -2), exact unit.star} }, { clear n, intro n IH A m H, induction m with m, { apply (@is_trunc_of_leq _ -2), exact unit.star}, { apply is_trunc_succ_intro, intro aa aa', apply (@trunc.rec_on _ _ _ aa (λy, !is_trunc_succ_of_is_hprop)), eapply (@trunc.rec_on _ _ _ aa' (λy, !is_trunc_succ_of_is_hprop)), intro a a', apply (is_trunc_equiv_closed_rev), { apply tr_eq_tr_equiv}, { exact (IH _ _ _)}}} end open equiv.ops definition unique_choice {P : A → Type} [H : Πa, is_hprop (P a)] (f : Πa, ∥ P a ∥) (a : A) : P a := !trunc_equiv (f a) /- transport over a truncated family -/ definition trunc_transport {a a' : A} {P : A → Type} (p : a = a') (n : trunc_index) (x : P a) : transport (λa, trunc n (P a)) p (tr x) = tr (p ▸ x) := by induction p; reflexivity definition image {A B : Type} (f : A → B) (b : B) : hprop := ∃(a : A), f a = b end trunc open trunc namespace function variables {A B : Type} definition is_surjective_of_is_equiv [instance] (f : A → B) [H : is_equiv f] : is_surjective f := λb, !center definition is_equiv_equiv_is_embedding_times_is_surjective [constructor] (f : A → B) : is_equiv f ≃ (is_embedding f × is_surjective f) := equiv_of_is_hprop (λH, (_, _)) (λP, prod.rec_on P (λH₁ H₂, !is_equiv_of_is_surjective_of_is_embedding)) end function
901d510bec53501b174bed0d6e9cc518ce07af18
9dc8cecdf3c4634764a18254e94d43da07142918
/src/computability/primrec.lean
7529faa862a0ed27709aa405b56e21dbddcaf9a6
[ "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
52,144
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.join import logic.equiv.list import logic.function.iterate /-! # The primitive recursive functions The primitive recursive functions are the least collection of functions `nat → nat` which are closed under projections (using the mkpair pairing function), composition, zero, successor, and primitive recursion (i.e. nat.rec where the motive is C n := nat). We can extend this definition to a large class of basic types by using canonical encodings of types as natural numbers (Gödel numbering), which we implement through the type class `encodable`. (More precisely, we need that the composition of encode with decode yields a primitive recursive function, so we have the `primcodable` type class for this.) ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open denumerable encodable function namespace nat def elim {C : Sort*} : C → (ℕ → C → C) → ℕ → C := @nat.rec (λ _, C) @[simp] theorem elim_zero {C} (a f) : @nat.elim C a f 0 = a := rfl @[simp] theorem elim_succ {C} (a f n) : @nat.elim C a f (succ n) = f n (nat.elim a f n) := rfl def cases {C : Sort*} (a : C) (f : ℕ → C) : ℕ → C := nat.elim a (λ n _, f n) @[simp] theorem cases_zero {C} (a f) : @nat.cases C a f 0 = a := rfl @[simp] theorem cases_succ {C} (a f n) : @nat.cases C a f (succ n) = f n := rfl @[simp, reducible] def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α := f n.unpair.1 n.unpair.2 /-- The primitive recursive functions `ℕ → ℕ`. -/ inductive primrec : (ℕ → ℕ) → Prop | zero : primrec (λ n, 0) | succ : primrec succ | left : primrec (λ n, n.unpair.1) | right : primrec (λ n, n.unpair.2) | pair {f g} : primrec f → primrec g → primrec (λ n, mkpair (f n) (g n)) | comp {f g} : primrec f → primrec g → primrec (λ n, f (g n)) | prec {f g} : primrec f → primrec g → primrec (unpaired (λ z n, n.elim (f z) (λ y IH, g $ mkpair z $ mkpair y IH))) namespace primrec theorem of_eq {f g : ℕ → ℕ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const : ∀ (n : ℕ), primrec (λ _, n) | 0 := zero | (n+1) := succ.comp (const n) protected theorem id : primrec id := (left.pair right).of_eq $ λ n, by simp theorem prec1 {f} (m : ℕ) (hf : primrec f) : primrec (λ n, n.elim m (λ y IH, f $ mkpair y IH)) := ((prec (const m) (hf.comp right)).comp (zero.pair primrec.id)).of_eq $ λ n, by simp; dsimp; rw [unpair_mkpair] theorem cases1 {f} (m : ℕ) (hf : primrec f) : primrec (nat.cases m f) := (prec1 m (hf.comp left)).of_eq $ by simp [cases] theorem cases {f g} (hf : primrec f) (hg : primrec g) : primrec (unpaired (λ z n, n.cases (f z) (λ y, g $ mkpair z y))) := (prec hf (hg.comp (pair left (left.comp right)))).of_eq $ by simp [cases] protected theorem swap : primrec (unpaired (swap mkpair)) := (pair right left).of_eq $ λ n, by simp theorem swap' {f} (hf : primrec (unpaired f)) : primrec (unpaired (swap f)) := (hf.comp primrec.swap).of_eq $ λ n, by simp theorem pred : primrec pred := (cases1 0 primrec.id).of_eq $ λ n, by cases n; simp * theorem add : primrec (unpaired (+)) := (prec primrec.id ((succ.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, add_succ] theorem sub : primrec (unpaired has_sub.sub) := (prec primrec.id ((pred.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, sub_succ] theorem mul : primrec (unpaired (*)) := (prec zero (add.comp (pair left (right.comp right)))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, mul_succ, add_comm] theorem pow : primrec (unpaired (^)) := (prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, pow_succ'] end primrec end nat /-- A `primcodable` type is an `encodable` type for which the encode/decode functions are primitive recursive. -/ class primcodable (α : Type*) extends encodable α := (prim [] : nat.primrec (λ n, encodable.encode (decode n))) namespace primcodable open nat.primrec @[priority 10] instance of_denumerable (α) [denumerable α] : primcodable α := ⟨succ.of_eq $ by simp⟩ def of_equiv (α) {β} [primcodable α] (e : β ≃ α) : primcodable β := { prim := (primcodable.prim α).of_eq $ λ n, show encode (decode α n) = (option.cases_on (option.map e.symm (decode α n)) 0 (λ a, nat.succ (encode (e a))) : ℕ), by cases decode α n; dsimp; simp, ..encodable.of_equiv α e } instance empty : primcodable empty := ⟨zero⟩ instance unit : primcodable punit := ⟨(cases1 1 zero).of_eq $ λ n, by cases n; simp⟩ instance option {α : Type*} [h : primcodable α] : primcodable (option α) := ⟨(cases1 1 ((cases1 0 (succ.comp succ)).comp (primcodable.prim α))).of_eq $ λ n, by cases n; simp; cases decode α n; refl⟩ instance bool : primcodable bool := ⟨(cases1 1 (cases1 2 zero)).of_eq $ λ n, begin cases n, {refl}, cases n, {refl}, rw decode_ge_two, {refl}, exact dec_trivial end⟩ end primcodable /-- `primrec f` means `f` is primitive recursive (after encoding its input and output as natural numbers). -/ def primrec {α β} [primcodable α] [primcodable β] (f : α → β) : Prop := nat.primrec (λ n, encode ((decode α n).map f)) namespace primrec variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec protected theorem encode : primrec (@encode α _) := (primcodable.prim α).of_eq $ λ n, by cases decode α n; refl protected theorem decode : primrec (decode α) := succ.comp (primcodable.prim α) theorem dom_denumerable {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ nat.primrec (λ n, encode (f (of_nat α n))) := ⟨λ h, (pred.comp h).of_eq $ λ n, by simp; refl, λ h, (succ.comp h).of_eq $ λ n, by simp; refl⟩ theorem nat_iff {f : ℕ → ℕ} : primrec f ↔ nat.primrec f := dom_denumerable theorem encdec : primrec (λ n, encode (decode α n)) := nat_iff.2 (primcodable.prim α) theorem option_some : primrec (@some α) := ((cases1 0 (succ.comp succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp theorem of_eq {f g : α → σ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const (x : σ) : primrec (λ a : α, x) := ((cases1 0 (const (encode x).succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; refl protected theorem id : primrec (@id α) := (primcodable.prim α).of_eq $ by simp theorem comp {f : β → σ} {g : α → β} (hf : primrec f) (hg : primrec g) : primrec (λ a, f (g a)) := ((cases1 0 (hf.comp $ pred.comp hg)).comp (primcodable.prim α)).of_eq $ λ n, begin cases decode α n, {refl}, simp [encodek] end theorem succ : primrec nat.succ := nat_iff.2 nat.primrec.succ theorem pred : primrec nat.pred := nat_iff.2 nat.primrec.pred theorem encode_iff {f : α → σ} : primrec (λ a, encode (f a)) ↔ primrec f := ⟨λ h, nat.primrec.of_eq h $ λ n, by cases decode α n; refl, primrec.encode.comp⟩ theorem of_nat_iff {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ primrec (λ n, f (of_nat α n)) := dom_denumerable.trans $ nat_iff.symm.trans encode_iff protected theorem of_nat (α) [denumerable α] : primrec (of_nat α) := of_nat_iff.1 primrec.id theorem option_some_iff {f : α → σ} : primrec (λ a, some (f a)) ↔ primrec f := ⟨λ h, encode_iff.1 $ pred.comp $ encode_iff.2 h, option_some.comp⟩ theorem of_equiv {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e := by letI : primcodable β := primcodable.of_equiv α e; exact encode_iff.1 primrec.encode theorem of_equiv_symm {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e.symm := by letI := primcodable.of_equiv α e; exact encode_iff.1 (show primrec (λ a, encode (e (e.symm a))), by simp [primrec.encode]) theorem of_equiv_iff {β} (e : β ≃ α) {f : σ → β} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv_symm.comp h).of_eq (λ a, by simp), of_equiv.comp⟩ theorem of_equiv_symm_iff {β} (e : β ≃ α) {f : σ → α} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e.symm (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv.comp h).of_eq (λ a, by simp), of_equiv_symm.comp⟩ end primrec namespace primcodable open nat.primrec instance prod {α β} [primcodable α] [primcodable β] : primcodable (α × β) := ⟨((cases zero ((cases zero succ).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp [nat.unpaired], cases decode α n.unpair.1, { simp }, cases decode β n.unpair.2; simp end⟩ end primcodable namespace primrec variables {α : Type*} {σ : Type*} [primcodable α] [primcodable σ] open nat.primrec theorem fst {α β} [primcodable α] [primcodable β] : primrec (@prod.fst α β) := ((cases zero ((cases zero (nat.primrec.succ.comp left)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem snd {α β} [primcodable α] [primcodable β] : primrec (@prod.snd α β) := ((cases zero ((cases zero (nat.primrec.succ.comp right)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem pair {α β γ} [primcodable α] [primcodable β] [primcodable γ] {f : α → β} {g : α → γ} (hf : primrec f) (hg : primrec g) : primrec (λ a, (f a, g a)) := ((cases1 0 (nat.primrec.succ.comp $ pair (nat.primrec.pred.comp hf) (nat.primrec.pred.comp hg))).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp [encodek]; refl theorem unpair : primrec nat.unpair := (pair (nat_iff.2 nat.primrec.left) (nat_iff.2 nat.primrec.right)).of_eq $ λ n, by simp theorem list_nth₁ : ∀ (l : list α), primrec l.nth | [] := dom_denumerable.2 zero | (a::l) := dom_denumerable.2 $ (cases1 (encode a).succ $ dom_denumerable.1 $ list_nth₁ l).of_eq $ λ n, by cases n; simp end primrec /-- `primrec₂ f` means `f` is a binary primitive recursive function. This is technically unnecessary since we can always curry all the arguments together, but there are enough natural two-arg functions that it is convenient to express this directly. -/ def primrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := primrec (λ p : α × β, f p.1 p.2) /-- `primrec_pred p` means `p : α → Prop` is a (decidable) primitive recursive predicate, which is to say that `to_bool ∘ p : α → bool` is primitive recursive. -/ def primrec_pred {α} [primcodable α] (p : α → Prop) [decidable_pred p] := primrec (λ a, to_bool (p a)) /-- `primrec_rel p` means `p : α → β → Prop` is a (decidable) primitive recursive relation, which is to say that `to_bool ∘ p : α → β → bool` is primitive recursive. -/ def primrec_rel {α β} [primcodable α] [primcodable β] (s : α → β → Prop) [∀ a b, decidable (s a b)] := primrec₂ (λ a b, to_bool (s a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] theorem of_eq {f g : α → β → σ} (hg : primrec₂ f) (H : ∀ a b, f a b = g a b) : primrec₂ g := (by funext a b; apply H : f = g) ▸ hg theorem const (x : σ) : primrec₂ (λ (a : α) (b : β), x) := primrec.const _ protected theorem pair : primrec₂ (@prod.mk α β) := primrec.pair primrec.fst primrec.snd theorem left : primrec₂ (λ (a : α) (b : β), a) := primrec.fst theorem right : primrec₂ (λ (a : α) (b : β), b) := primrec.snd theorem mkpair : primrec₂ nat.mkpair := by simp [primrec₂, primrec]; constructor theorem unpaired {f : ℕ → ℕ → α} : primrec (nat.unpaired f) ↔ primrec₂ f := ⟨λ h, by simpa using h.comp mkpair, λ h, h.comp primrec.unpair⟩ theorem unpaired' {f : ℕ → ℕ → ℕ} : nat.primrec (nat.unpaired f) ↔ primrec₂ f := primrec.nat_iff.symm.trans unpaired theorem encode_iff {f : α → β → σ} : primrec₂ (λ a b, encode (f a b)) ↔ primrec₂ f := primrec.encode_iff theorem option_some_iff {f : α → β → σ} : primrec₂ (λ a b, some (f a b)) ↔ primrec₂ f := primrec.option_some_iff theorem of_nat_iff {α β σ} [denumerable α] [denumerable β] [primcodable σ] {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, f (of_nat α m) (of_nat β n)) := (primrec.of_nat_iff.trans $ by simp).trans unpaired theorem uncurry {f : α → β → σ} : primrec (function.uncurry f) ↔ primrec₂ f := by rw [show function.uncurry f = λ (p : α × β), f p.1 p.2, from funext $ λ ⟨a, b⟩, rfl]; refl theorem curry {f : α × β → σ} : primrec₂ (function.curry f) ↔ primrec f := by rw [← uncurry, function.uncurry_curry] end primrec₂ section comp variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem primrec.comp₂ {f : γ → σ} {g : α → β → γ} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a b, f (g a b)) := hf.comp hg theorem primrec₂.comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : primrec₂ f) (hg : primrec g) (hh : primrec h) : primrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem primrec₂.comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : primrec₂ f) (hg : primrec₂ g) (hh : primrec₂ h) : primrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh theorem primrec_pred.comp {p : β → Prop} [decidable_pred p] {f : α → β} : primrec_pred p → primrec f → primrec_pred (λ a, p (f a)) := primrec.comp theorem primrec_rel.comp {R : β → γ → Prop} [∀ a b, decidable (R a b)] {f : α → β} {g : α → γ} : primrec_rel R → primrec f → primrec g → primrec_pred (λ a, R (f a) (g a)) := primrec₂.comp theorem primrec_rel.comp₂ {R : γ → δ → Prop} [∀ a b, decidable (R a b)] {f : α → β → γ} {g : α → β → δ} : primrec_rel R → primrec₂ f → primrec₂ g → primrec_rel (λ a b, R (f a b) (g a b)) := primrec_rel.comp end comp theorem primrec_pred.of_eq {α} [primcodable α] {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (H : ∀ a, p a ↔ q a) : primrec_pred q := primrec.of_eq hp (λ a, to_bool_congr (H a)) theorem primrec_rel.of_eq {α β} [primcodable α] [primcodable β] {r s : α → β → Prop} [∀ a b, decidable (r a b)] [∀ a b, decidable (s a b)] (hr : primrec_rel r) (H : ∀ a b, r a b ↔ s a b) : primrec_rel s := primrec₂.of_eq hr (λ a b, to_bool_congr (H a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec theorem swap {f : α → β → σ} (h : primrec₂ f) : primrec₂ (swap f) := h.comp₂ primrec₂.right primrec₂.left theorem nat_iff {f : α → β → σ} : primrec₂ f ↔ nat.primrec (nat.unpaired $ λ m n : ℕ, encode $ (decode α m).bind $ λ a, (decode β n).map (f a)) := have ∀ (a : option α) (b : option β), option.map (λ (p : α × β), f p.1 p.2) (option.bind a (λ (a : α), option.map (prod.mk a) b)) = option.bind a (λ a, option.map (f a) b), by intros; cases a; [refl, {cases b; refl}], by simp [primrec₂, primrec, this] theorem nat_iff' {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, option.bind (decode α m) (λ a, option.map (f a) (decode β n))) := nat_iff.trans $ unpaired'.trans encode_iff end primrec₂ namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem to₂ {f : α × β → σ} (hf : primrec f) : primrec₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl theorem nat_elim {f : α → β} {g : α → ℕ × β → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a (n : ℕ), n.elim (f a) (λ n IH, g a (n, IH))) := primrec₂.nat_iff.2 $ ((nat.primrec.cases nat.primrec.zero $ (nat.primrec.prec hf $ nat.primrec.comp hg $ nat.primrec.left.pair $ (nat.primrec.left.comp nat.primrec.right).pair $ nat.primrec.pred.comp $ nat.primrec.right.comp nat.primrec.right).comp $ nat.primrec.right.pair $ nat.primrec.right.comp nat.primrec.left).comp $ nat.primrec.id.pair $ (primcodable.prim α).comp nat.primrec.left).of_eq $ λ n, begin simp, cases decode α n.unpair.1 with a, {refl}, simp [encodek], induction n.unpair.2 with m; simp [encodek], simp [ih, encodek] end theorem nat_elim' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).elim (g a) (λ n IH, h a (n, IH))) := (nat_elim hg hh).comp primrec.id hf theorem nat_elim₁ {f : ℕ → α → α} (a : α) (hf : primrec₂ f) : primrec (nat.elim a f) := nat_elim' primrec.id (const a) $ comp₂ hf primrec₂.right theorem nat_cases' {f : α → β} {g : α → ℕ → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a, nat.cases (f a) (g a)) := nat_elim hf $ hg.comp₂ primrec₂.left $ comp₂ fst primrec₂.right theorem nat_cases {f : α → ℕ} {g : α → β} {h : α → ℕ → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).cases (g a) (h a)) := (nat_cases' hg hh).comp primrec.id hf theorem nat_cases₁ {f : ℕ → α} (a : α) (hf : primrec f) : primrec (nat.cases a f) := nat_cases primrec.id (const a) (comp₂ hf primrec₂.right) theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (h a)^[f a] (g a)) := (nat_elim' hf hg (hh.comp₂ primrec₂.left $ snd.comp₂ primrec₂.right)).of_eq $ λ a, by induction f a; simp [*, function.iterate_succ'] theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ} (ho : primrec o) (hf : primrec f) (hg : primrec₂ g) : @primrec _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) := encode_iff.1 $ (nat_cases (encode_iff.2 ho) (encode_iff.2 hf) $ pred.comp₂ $ primrec₂.encode_iff.2 $ (primrec₂.nat_iff'.1 hg).comp₂ ((@primrec.encode α _).comp fst).to₂ primrec₂.right).of_eq $ λ a, by cases o a with b; simp [encodek]; refl theorem option_bind {f : α → option β} {g : α → β → option σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).bind (g a)) := (option_cases hf (const none) hg).of_eq $ λ a, by cases f a; refl theorem option_bind₁ {f : α → option σ} (hf : primrec f) : primrec (λ o, option.bind o f) := option_bind primrec.id (hf.comp snd).to₂ theorem option_map {f : α → option β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := option_bind hf (option_some.comp₂ hg) theorem option_map₁ {f : α → σ} (hf : primrec f) : primrec (option.map f) := option_map primrec.id (hf.comp snd).to₂ theorem option_iget [inhabited α] : primrec (@option.iget α _) := (option_cases primrec.id (const $ @default α _) primrec₂.right).of_eq $ λ o, by cases o; refl theorem option_is_some : primrec (@option.is_some α) := (option_cases primrec.id (const ff) (const tt).to₂).of_eq $ λ o, by cases o; refl theorem option_get_or_else : primrec₂ (@option.get_or_else α) := primrec.of_eq (option_cases primrec₂.left primrec₂.right primrec₂.right) $ λ ⟨o, a⟩, by cases o; refl theorem bind_decode_iff {f : α → β → option σ} : primrec₂ (λ a n, (decode β n).bind (f a)) ↔ primrec₂ f := ⟨λ h, by simpa [encodek] using h.comp fst ((@primrec.encode β _).comp snd), λ h, option_bind (primrec.decode.comp snd) $ h.comp (fst.comp fst) snd⟩ theorem map_decode_iff {f : α → β → σ} : primrec₂ (λ a n, (decode β n).map (f a)) ↔ primrec₂ f := bind_decode_iff.trans primrec₂.option_some_iff theorem nat_add : primrec₂ ((+) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.add theorem nat_sub : primrec₂ (has_sub.sub : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.sub theorem nat_mul : primrec₂ ((*) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.mul theorem cond {c : α → bool} {f : α → σ} {g : α → σ} (hc : primrec c) (hf : primrec f) (hg : primrec g) : primrec (λ a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $ λ a, by cases c a; refl theorem ite {c : α → Prop} [decidable_pred c] {f : α → σ} {g : α → σ} (hc : primrec_pred c) (hf : primrec f) (hg : primrec g) : primrec (λ a, if c a then f a else g a) := by simpa using cond hc hf hg theorem nat_le : primrec_rel ((≤) : ℕ → ℕ → Prop) := (nat_cases nat_sub (const tt) (const ff).to₂).of_eq $ λ p, begin dsimp [swap], cases e : p.1 - p.2 with n, { simp [tsub_eq_zero_iff_le.1 e] }, { simp [not_le.2 (nat.lt_of_sub_eq_succ e)] } end theorem nat_min : primrec₂ (@min ℕ _) := ite nat_le fst snd theorem nat_max : primrec₂ (@max ℕ _) := ite (nat_le.comp primrec.snd primrec.fst) fst snd theorem dom_bool (f : bool → α) : primrec f := (cond primrec.id (const (f tt)) (const (f ff))).of_eq $ λ b, by cases b; refl theorem dom_bool₂ (f : bool → bool → α) : primrec₂ f := (cond fst ((dom_bool (f tt)).comp snd) ((dom_bool (f ff)).comp snd)).of_eq $ λ ⟨a, b⟩, by cases a; refl protected theorem bnot : primrec bnot := dom_bool _ protected theorem band : primrec₂ band := dom_bool₂ _ protected theorem bor : primrec₂ bor := dom_bool₂ _ protected theorem not {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primrec_pred (λ a, ¬ p a) := (primrec.bnot.comp hp).of_eq $ λ n, by simp protected theorem and {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∧ q a) := (primrec.band.comp hp hq).of_eq $ λ n, by simp protected theorem or {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∨ q a) := (primrec.bor.comp hp hq).of_eq $ λ n, by simp protected theorem eq [decidable_eq α] : primrec_rel (@eq α) := have primrec_rel (λ a b : ℕ, a = b), from (primrec.and nat_le nat_le.swap).of_eq $ λ a, by simp [le_antisymm_iff], (this.comp₂ (primrec.encode.comp₂ primrec₂.left) (primrec.encode.comp₂ primrec₂.right)).of_eq $ λ a b, encode_injective.eq_iff theorem nat_lt : primrec_rel ((<) : ℕ → ℕ → Prop) := (nat_le.comp snd fst).not.of_eq $ λ p, by simp theorem option_guard {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) {f : α → β} (hf : primrec f) : primrec (λ a, option.guard (p a) (f a)) := ite (hp.comp primrec.id hf) (option_some_iff.2 hf) (const none) theorem option_orelse : primrec₂ ((<|>) : option α → option α → option α) := (option_cases fst snd (fst.comp fst).to₂).of_eq $ λ ⟨o₁, o₂⟩, by cases o₁; cases o₂; refl protected theorem decode₂ : primrec (decode₂ α) := option_bind primrec.decode $ option_guard ((@primrec.eq _ _ nat.decidable_eq).comp (encode_iff.2 snd) (fst.comp fst)) snd theorem list_find_index₁ {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) : ∀ (l : list β), primrec (λ a, l.find_index (p a)) | [] := const 0 | (a::l) := ite (hp.comp primrec.id (const a)) (const 0) (succ.comp (list_find_index₁ l)) theorem list_index_of₁ [decidable_eq α] (l : list α) : primrec (λ a, l.index_of a) := list_find_index₁ primrec.eq l theorem dom_fintype [fintype α] (f : α → σ) : primrec f := let ⟨l, nd, m⟩ := finite.exists_univ_list α in option_some_iff.1 $ begin haveI := decidable_eq_of_encodable α, refine ((list_nth₁ (l.map f)).comp (list_index_of₁ l)).of_eq (λ a, _), rw [list.nth_map, list.nth_le_nth (list.index_of_lt_length.2 (m _)), list.index_of_nth_le]; refl end theorem nat_bodd_div2 : primrec nat.bodd_div2 := (nat_elim' primrec.id (const (ff, 0)) (((cond fst (pair (const ff) (succ.comp snd)) (pair (const tt) snd)).comp snd).comp snd).to₂).of_eq $ λ n, begin simp [-nat.bodd_div2_eq], induction n with n IH, {refl}, simp [-nat.bodd_div2_eq, nat.bodd_div2, *], rcases nat.bodd_div2 n with ⟨_|_, m⟩; simp [nat.bodd_div2] end theorem nat_bodd : primrec nat.bodd := fst.comp nat_bodd_div2 theorem nat_div2 : primrec nat.div2 := snd.comp nat_bodd_div2 theorem nat_bit0 : primrec (@bit0 ℕ _) := nat_add.comp primrec.id primrec.id theorem nat_bit1 : primrec (@bit1 ℕ _ _) := nat_add.comp nat_bit0 (const 1) theorem nat_bit : primrec₂ nat.bit := (cond primrec.fst (nat_bit1.comp primrec.snd) (nat_bit0.comp primrec.snd)).of_eq $ λ n, by cases n.1; refl theorem nat_div_mod : primrec₂ (λ n k : ℕ, (n / k, n % k)) := let f (a : ℕ × ℕ) : ℕ × ℕ := a.1.elim (0, 0) (λ _ IH, if nat.succ IH.2 = a.2 then (nat.succ IH.1, 0) else (IH.1, nat.succ IH.2)) in have hf : primrec f, from nat_elim' fst (const (0, 0)) $ ((ite ((@primrec.eq ℕ _ _).comp (succ.comp $ snd.comp snd) fst) (pair (succ.comp $ fst.comp snd) (const 0)) (pair (fst.comp snd) (succ.comp $ snd.comp snd))) .comp (pair (snd.comp fst) (snd.comp snd))).to₂, suffices ∀ k n, (n / k, n % k) = f (n, k), from hf.of_eq $ λ ⟨m, n⟩, by simp [this], λ k n, begin have : (f (n, k)).2 + k * (f (n, k)).1 = n ∧ (0 < k → (f (n, k)).2 < k) ∧ (k = 0 → (f (n, k)).1 = 0), { induction n with n IH, {exact ⟨rfl, id, λ _, rfl⟩}, rw [λ n:ℕ, show f (n.succ, k) = _root_.ite ((f (n, k)).2.succ = k) (nat.succ (f (n, k)).1, 0) ((f (n, k)).1, (f (n, k)).2.succ), from rfl], by_cases h : (f (n, k)).2.succ = k; simp [h], { have := congr_arg nat.succ IH.1, refine ⟨_, λ k0, nat.no_confusion (h.trans k0)⟩, rwa [← nat.succ_add, h, add_comm, ← nat.mul_succ] at this }, { exact ⟨by rw [nat.succ_add, IH.1], λ k0, lt_of_le_of_ne (IH.2.1 k0) h, IH.2.2⟩ } }, revert this, cases f (n, k) with D M, simp, intros h₁ h₂ h₃, cases nat.eq_zero_or_pos k, { simp [h, h₃ h] at h₁ ⊢, simp [h₁] }, { exact (nat.div_mod_unique h).2 ⟨h₁, h₂ h⟩ } end theorem nat_div : primrec₂ ((/) : ℕ → ℕ → ℕ) := fst.comp₂ nat_div_mod theorem nat_mod : primrec₂ ((%) : ℕ → ℕ → ℕ) := snd.comp₂ nat_div_mod end primrec section variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] variable (H : nat.primrec (λ n, encodable.encode (decode (list β) n))) include H open primrec private def prim : primcodable (list β) := ⟨H⟩ private lemma list_cases' {f : α → list β} {g : α → σ} {h : α → β × list β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := by letI := prim H; exact have @primrec _ (option σ) _ _ (λ a, (decode (option (β × list β)) (encode (f a))).map (λ o, option.cases_on o (g a) (h a))), from ((@map_decode_iff _ (option (β × list β)) _ _ _ _ _).2 $ to₂ $ option_cases snd (hg.comp fst) (hh.comp₂ (fst.comp₂ primrec₂.left) primrec₂.right)) .comp primrec.id (encode_iff.2 hf), option_some_iff.1 $ this.of_eq $ λ a, by cases f a with b l; simp [encodek]; refl private lemma list_foldl' {f : α → list β} {g : α → σ} {h : α → σ × β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := by letI := prim H; exact let G (a : α) (IH : σ × list β) : σ × list β := list.cases_on IH.2 IH (λ b l, (h a (IH.1, b), l)) in let F (a : α) (n : ℕ) := (G a)^[n] (g a, f a) in have primrec (λ a, (F a (encode (f a))).1), from fst.comp $ nat_iterate (encode_iff.2 hf) (pair hg hf) $ list_cases' H (snd.comp snd) snd $ to₂ $ pair (hh.comp (fst.comp fst) $ pair ((fst.comp snd).comp fst) (fst.comp snd)) (snd.comp snd), this.of_eq $ λ a, begin have : ∀ n, F a n = ((list.take n (f a)).foldl (λ s b, h a (s, b)) (g a), list.drop n (f a)), { intro, simp [F], generalize : f a = l, generalize : g a = x, induction n with n IH generalizing l x, {refl}, simp, cases l with b l; simp [IH] }, rw [this, list.take_all_of_le (length_le_encode _)] end private lemma list_cons' : by haveI := prim H; exact primrec₂ (@list.cons β) := by letI := prim H; exact encode_iff.1 (succ.comp $ primrec₂.mkpair.comp (encode_iff.2 fst) (encode_iff.2 snd)) private lemma list_reverse' : by haveI := prim H; exact primrec (@list.reverse β) := by letI := prim H; exact (list_foldl' H primrec.id (const []) $ to₂ $ ((list_cons' H).comp snd fst).comp snd).of_eq (suffices ∀ l r, list.foldl (λ (s : list β) (b : β), b :: s) r l = list.reverse_core l r, from λ l, this l [], λ l, by induction l; simp [*, list.reverse_core]) end namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec instance sum : primcodable (α ⊕ β) := ⟨primrec.nat_iff.1 $ (encode_iff.2 (cond nat_bodd (((@primrec.decode β _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const tt) (primrec.encode.comp snd)) (((@primrec.decode α _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const ff) (primrec.encode.comp snd)))).of_eq $ λ n, show _ = encode (decode_sum n), begin simp [decode_sum], cases nat.bodd n; simp [decode_sum], { cases decode α n.div2; refl }, { cases decode β n.div2; refl } end⟩ instance list : primcodable (list α) := ⟨ by letI H := primcodable.prim (list ℕ); exact have primrec₂ (λ (a : α) (o : option (list ℕ)), o.map (list.cons (encode a))), from option_map snd $ (list_cons' H).comp ((@primrec.encode α _).comp (fst.comp fst)) snd, have primrec (λ n, (of_nat (list ℕ) n).reverse.foldl (λ o m, (decode α m).bind (λ a, o.map (list.cons (encode a)))) (some [])), from list_foldl' H ((list_reverse' H).comp (primrec.of_nat (list ℕ))) (const (some [])) (primrec.comp₂ (bind_decode_iff.2 $ primrec₂.swap this) primrec₂.right), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, begin rw list.foldl_reverse, apply nat.case_strong_induction_on n, { simp }, intros n IH, simp, cases decode α n.unpair.1 with a, {refl}, simp, suffices : ∀ (o : option (list ℕ)) p (_ : encode o = encode p), encode (option.map (list.cons (encode a)) o) = encode (option.map (list.cons a) p), from this _ _ (IH _ (nat.unpair_right_le n)), intros o p IH, cases o; cases p; injection IH with h, exact congr_arg (λ k, (nat.mkpair (encode a) k).succ.succ) h end⟩ end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem sum_inl : primrec (@sum.inl α β) := encode_iff.1 $ nat_bit0.comp primrec.encode theorem sum_inr : primrec (@sum.inr α β) := encode_iff.1 $ nat_bit1.comp primrec.encode theorem sum_cases {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : primrec f) (hg : primrec₂ g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ λ a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem list_cons : primrec₂ (@list.cons α) := list_cons' (primcodable.prim _) theorem list_cases {f : α → list β} {g : α → σ} {h : α → β × list β → σ} : primrec f → primrec g → primrec₂ h → @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := list_cases' (primcodable.prim _) theorem list_foldl {f : α → list β} {g : α → σ} {h : α → σ × β → σ} : primrec f → primrec g → primrec₂ h → primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := list_foldl' (primcodable.prim _) theorem list_reverse : primrec (@list.reverse α) := list_reverse' (primcodable.prim _) theorem list_foldr {f : α → list β} {g : α → σ} {h : α → β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).foldr (λ b s, h a (b, s)) (g a)) := (list_foldl (list_reverse.comp hf) hg $ to₂ $ hh.comp fst $ (pair snd fst).comp snd).of_eq $ λ a, by simp [list.foldl_reverse] theorem list_head' : primrec (@list.head' α) := (list_cases primrec.id (const none) (option_some_iff.2 $ (fst.comp snd)).to₂).of_eq $ λ l, by cases l; refl theorem list_head [inhabited α] : primrec (@list.head α _) := (option_iget.comp list_head').of_eq $ λ l, l.head_eq_head'.symm theorem list_tail : primrec (@list.tail α) := (list_cases primrec.id (const []) (snd.comp snd).to₂).of_eq $ λ l, by cases l; refl theorem list_rec {f : α → list β} {g : α → σ} {h : α → β × list β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))) := let F (a : α) := (f a).foldr (λ (b : β) (s : list β × σ), (b :: s.1, h a (b, s))) ([], g a) in have primrec F, from list_foldr hf (pair (const []) hg) $ to₂ $ pair ((list_cons.comp fst (fst.comp snd)).comp snd) hh, (snd.comp this).of_eq $ λ a, begin suffices : F a = (f a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))), {rw this}, simp [F], induction f a with b l IH; simp * end theorem list_nth : primrec₂ (@list.nth α) := let F (l : list α) (n : ℕ) := l.foldl (λ (s : ℕ ⊕ α) (a : α), sum.cases_on s (@nat.cases (ℕ ⊕ α) (sum.inr a) sum.inl) sum.inr) (sum.inl n) in have hF : primrec₂ F, from list_foldl fst (sum_inl.comp snd) ((sum_cases fst (nat_cases snd (sum_inr.comp $ snd.comp fst) (sum_inl.comp snd).to₂).to₂ (sum_inr.comp snd).to₂).comp snd).to₂, have @primrec _ (option α) _ _ (λ p : list α × ℕ, sum.cases_on (F p.1 p.2) (λ _, none) some), from sum_cases hF (const none).to₂ (option_some.comp snd).to₂, this.to₂.of_eq $ λ l n, begin dsimp, symmetry, induction l with a l IH generalizing n, {refl}, cases n with n, { rw [(_ : F (a :: l) 0 = sum.inr a)], {refl}, clear IH, dsimp [F], induction l with b l IH; simp * }, { apply IH } end theorem list_nthd (d : α) : primrec₂ (list.nthd d) := begin suffices : list.nthd d = λ l n, (list.nth l n).get_or_else d, { rw this, exact option_get_or_else.comp₂ list_nth (const _) }, funext, exact list.nthd_eq_get_or_else_nth _ _ _ end theorem list_inth [inhabited α] : primrec₂ (@list.inth α _) := list_nthd _ theorem list_append : primrec₂ ((++) : list α → list α → list α) := (list_foldr fst snd $ to₂ $ comp (@list_cons α _) snd).to₂.of_eq $ λ l₁ l₂, by induction l₁; simp * theorem list_concat : primrec₂ (λ l (a:α), l ++ [a]) := list_append.comp fst (list_cons.comp snd (const [])) theorem list_map {f : α → list β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := (list_foldr hf (const []) $ to₂ $ list_cons.comp (hg.comp fst (fst.comp snd)) (snd.comp snd)).of_eq $ λ a, by induction f a; simp * theorem list_range : primrec list.range := (nat_elim' primrec.id (const []) ((list_concat.comp snd fst).comp snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, list.range_succ]; refl theorem list_join : primrec (@list.join α) := (list_foldr primrec.id (const []) $ to₂ $ comp (@list_append α _) snd).of_eq $ λ l, by dsimp; induction l; simp * theorem list_length : primrec (@list.length α) := (list_foldr (@primrec.id (list α) _) (const 0) $ to₂ $ (succ.comp $ snd.comp snd).to₂).of_eq $ λ l, by dsimp; induction l; simp [*, -add_comm] theorem list_find_index {f : α → list β} {p : α → β → Prop} [∀ a b, decidable (p a b)] (hf : primrec f) (hp : primrec_rel p) : primrec (λ a, (f a).find_index (p a)) := (list_foldr hf (const 0) $ to₂ $ ite (hp.comp fst $ fst.comp snd) (const 0) (succ.comp $ snd.comp snd)).of_eq $ λ a, eq.symm $ by dsimp; induction f a with b l; [refl, simp [*, list.find_index]] theorem list_index_of [decidable_eq α] : primrec₂ (@list.index_of α _) := to₂ $ list_find_index snd $ primrec.eq.comp₂ (fst.comp fst).to₂ snd.to₂ theorem nat_strong_rec (f : α → ℕ → σ) {g : α → list σ → option σ} (hg : primrec₂ g) (H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : primrec₂ f := suffices primrec₂ (λ a n, (list.range n).map (f a)), from primrec₂.option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $ λ a n, by simp [list.nth_range (nat.lt_succ_self n)]; refl, primrec₂.option_some_iff.1 $ (nat_elim (const (some [])) (to₂ $ option_bind (snd.comp snd) $ to₂ $ option_map (hg.comp (fst.comp fst) snd) (to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $ λ a n, begin simp, induction n with n IH, {refl}, simp [IH, H, list.range_succ] end end primrec namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec def subtype {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primcodable (subtype p) := ⟨have primrec (λ n, (decode α n).bind (λ a, option.guard p a)), from option_bind primrec.decode (option_guard (hp.comp snd) snd), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, show _ = encode ((decode α n).bind (λ a, _)), begin cases decode α n with a, {refl}, dsimp [option.guard], by_cases h : p a; simp [h]; refl end⟩ instance fin {n} : primcodable (fin n) := @of_equiv _ _ (subtype $ nat_lt.comp primrec.id (const n)) fin.equiv_subtype instance vector {n} : primcodable (vector α n) := subtype ((@primrec.eq _ _ nat.decidable_eq).comp list_length (const _)) instance fin_arrow {n} : primcodable (fin n → α) := of_equiv _ (equiv.vector_equiv_fin _ _).symm instance array {n} : primcodable (array n α) := of_equiv _ (equiv.array_equiv_fin _ _) section ulower local attribute [instance, priority 100] encodable.decidable_range_encode encodable.decidable_eq_of_encodable instance ulower : primcodable (ulower α) := have primrec_pred (λ n, encodable.decode₂ α n ≠ none), from primrec.not (primrec.eq.comp (primrec.option_bind primrec.decode (primrec.ite (primrec.eq.comp (primrec.encode.comp primrec.snd) primrec.fst) (primrec.option_some.comp primrec.snd) (primrec.const _))) (primrec.const _)), primcodable.subtype $ primrec_pred.of_eq this (λ n, decode₂_ne_none_iff) end ulower end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem subtype_val {p : α → Prop} [decidable_pred p] {hp : primrec_pred p} : by haveI := primcodable.subtype hp; exact primrec (@subtype.val α p) := begin letI := primcodable.subtype hp, refine (primcodable.prim (subtype p)).of_eq (λ n, _), rcases decode (subtype p) n with _|⟨a,h⟩; refl end theorem subtype_val_iff {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → subtype p} : by haveI := primcodable.subtype hp; exact primrec (λ a, (f a).1) ↔ primrec f := begin letI := primcodable.subtype hp, refine ⟨λ h, _, λ hf, subtype_val.comp hf⟩, refine nat.primrec.of_eq h (λ n, _), cases decode α n with a, {refl}, simp, cases f a; refl end theorem subtype_mk {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → β} {h : ∀ a, p (f a)} (hf : primrec f) : by haveI := primcodable.subtype hp; exact primrec (λ a, @subtype.mk β p (f a) (h a)) := subtype_val_iff.1 hf theorem option_get {f : α → option β} {h : ∀ a, (f a).is_some} : primrec f → primrec (λ a, option.get (h a)) := begin intro hf, refine (nat.primrec.pred.comp hf).of_eq (λ n, _), generalize hx : decode α n = x, cases x; simp end theorem ulower_down : primrec (ulower.down : α → ulower α) := by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact subtype_mk primrec.encode theorem ulower_up : primrec (ulower.up : ulower α → α) := by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact option_get (primrec.decode₂.comp subtype_val) theorem fin_val_iff {n} {f : α → fin n} : primrec (λ a, (f a).1) ↔ primrec f := begin let : primcodable {a//id a<n}, swap, exactI (iff.trans (by refl) subtype_val_iff).trans (of_equiv_iff _) end theorem fin_val {n} : primrec (coe : fin n → ℕ) := fin_val_iff.2 primrec.id theorem fin_succ {n} : primrec (@fin.succ n) := fin_val_iff.1 $ by simp [succ.comp fin_val] theorem vector_to_list {n} : primrec (@vector.to_list α n) := subtype_val theorem vector_to_list_iff {n} {f : α → vector β n} : primrec (λ a, (f a).to_list) ↔ primrec f := subtype_val_iff theorem vector_cons {n} : primrec₂ (@vector.cons α n) := vector_to_list_iff.1 $ by simp; exact list_cons.comp fst (vector_to_list_iff.2 snd) theorem vector_length {n} : primrec (@vector.length α n) := const _ theorem vector_head {n} : primrec (@vector.head α n) := option_some_iff.1 $ (list_head'.comp vector_to_list).of_eq $ λ ⟨a::l, h⟩, rfl theorem vector_tail {n} : primrec (@vector.tail α n) := vector_to_list_iff.1 $ (list_tail.comp vector_to_list).of_eq $ λ ⟨l, h⟩, by cases l; refl theorem vector_nth {n} : primrec₂ (@vector.nth α n) := option_some_iff.1 $ (list_nth.comp (vector_to_list.comp fst) (fin_val.comp snd)).of_eq $ λ a, by simp [vector.nth_eq_nth_le]; rw [← list.nth_le_nth] theorem list_of_fn : ∀ {n} {f : fin n → α → σ}, (∀ i, primrec (f i)) → primrec (λ a, list.of_fn (λ i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ)) theorem vector_of_fn {n} {f : fin n → α → σ} (hf : ∀ i, primrec (f i)) : primrec (λ a, vector.of_fn (λ i, f i a)) := vector_to_list_iff.1 $ by simp [list_of_fn hf] theorem vector_nth' {n} : primrec (@vector.nth α n) := of_equiv_symm theorem vector_of_fn' {n} : primrec (@vector.of_fn α n) := of_equiv theorem fin_app {n} : primrec₂ (@id (fin n → σ)) := (vector_nth.comp (vector_of_fn'.comp fst) snd).of_eq $ λ ⟨v, i⟩, by simp theorem fin_curry₁ {n} {f : fin n → α → σ} : primrec₂ f ↔ ∀ i, primrec (f i) := ⟨λ h i, h.comp (const i) primrec.id, λ h, (vector_nth.comp ((vector_of_fn h).comp snd) fst).of_eq $ λ a, by simp⟩ theorem fin_curry {n} {f : α → fin n → σ} : primrec f ↔ primrec₂ f := ⟨λ h, fin_app.comp (h.comp fst) snd, λ h, (vector_nth'.comp (vector_of_fn (λ i, show primrec (λ a, f a i), from h.comp primrec.id (const i)))).of_eq $ λ a, by funext i; simp⟩ end primrec namespace nat open vector /-- An alternative inductive definition of `primrec` which does not use the pairing function on ℕ, and so has to work with n-ary functions on ℕ instead of unary functions. We prove that this is equivalent to the regular notion in `to_prim` and `of_prim`. -/ inductive primrec' : ∀ {n}, (vector ℕ n → ℕ) → Prop | zero : @primrec' 0 (λ _, 0) | succ : @primrec' 1 (λ v, succ v.head) | nth {n} (i : fin n) : primrec' (λ v, v.nth i) | comp {m n f} (g : fin n → vector ℕ m → ℕ) : primrec' f → (∀ i, primrec' (g i)) → primrec' (λ a, f (of_fn (λ i, g i a))) | prec {n f g} : @primrec' n f → @primrec' (n+2) g → primrec' (λ v : vector ℕ (n+1), v.head.elim (f v.tail) (λ y IH, g (y ::ᵥ IH ::ᵥ v.tail))) end nat namespace nat.primrec' open vector primrec nat (primrec') nat.primrec' hide ite theorem to_prim {n f} (pf : @primrec' n f) : primrec f := begin induction pf, case nat.primrec'.zero { exact const 0 }, case nat.primrec'.succ { exact primrec.succ.comp vector_head }, case nat.primrec'.nth : n i { exact vector_nth.comp primrec.id (const i) }, case nat.primrec'.comp : m n f g _ _ hf hg { exact hf.comp (vector_of_fn (λ i, hg i)) }, case nat.primrec'.prec : n f g _ _ hf hg { exact nat_elim' vector_head (hf.comp vector_tail) (hg.comp $ vector_cons.comp (fst.comp snd) $ vector_cons.comp (snd.comp snd) $ (@vector_tail _ _ (n+1)).comp fst).to₂ }, end theorem of_eq {n} {f g : vector ℕ n → ℕ} (hf : primrec' f) (H : ∀ i, f i = g i) : primrec' g := (funext H : f = g) ▸ hf theorem const {n} : ∀ m, @primrec' n (λ v, m) | 0 := zero.comp fin.elim0 (λ i, i.elim0) | (m+1) := succ.comp _ (λ i, const m) theorem head {n : ℕ} : @primrec' n.succ head := (nth 0).of_eq $ λ v, by simp [nth_zero] theorem tail {n f} (hf : @primrec' n f) : @primrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @nth _ i.succ)).of_eq $ λ v, by rw [← of_fn_nth v.tail]; congr; funext i; simp def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, primrec' (λ v, (f v).nth i) protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m f g} (hf : @primrec' n f) (hg : @vec n m g) : vec (λ v, (f v ::ᵥ g v)) := λ i, fin.cases (by simp *) (λ i, by simp [hg i]) i theorem idv {n} : @vec n n id := nth theorem comp' {n m f g} (hf : @primrec' m f) (hg : @vec n m g) : primrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ (f : ℕ → ℕ) (hf : @primrec' 1 (λ v, f v.head)) {n g} (hg : @primrec' n g) : primrec' (λ v, f (g v)) := hf.comp _ (λ i, hg) theorem comp₂ (f : ℕ → ℕ → ℕ) (hf : @primrec' 2 (λ v, f v.head v.tail.head)) {n g h} (hg : @primrec' n g) (hh : @primrec' n h) : primrec' (λ v, f (g v) (h v)) := by simpa using hf.comp' (hg.cons $ hh.cons primrec'.nil) theorem prec' {n f g h} (hf : @primrec' n f) (hg : @primrec' n g) (hh : @primrec' (n+2) h) : @primrec' n (λ v, (f v).elim (g v) (λ (y IH : ℕ), h (y ::ᵥ IH ::ᵥ v))) := by simpa using comp' (prec hg hh) (hf.cons idv) theorem pred : @primrec' 1 (λ v, v.head.pred) := (prec' head (const 0) head).of_eq $ λ v, by simp; cases v.head; refl theorem add : @primrec' 2 (λ v, v.head + v.tail.head) := (prec head (succ.comp₁ _ (tail head))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_add] theorem sub : @primrec' 2 (λ v, v.head - v.tail.head) := begin suffices, simpa using comp₂ (λ a b, b - a) this (tail head) head, refine (prec head (pred.comp₁ _ (tail head))).of_eq (λ v, _), simp, induction v.head; simp [*, nat.sub_succ] end theorem mul : @primrec' 2 (λ v, v.head * v.tail.head) := (prec (const 0) (tail (add.comp₂ _ (tail head) (head)))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_mul]; rw add_comm theorem if_lt {n a b f g} (ha : @primrec' n a) (hb : @primrec' n b) (hf : @primrec' n f) (hg : @primrec' n g) : @primrec' n (λ v, if a v < b v then f v else g v) := (prec' (sub.comp₂ _ hb ha) hg (tail $ tail hf)).of_eq $ λ v, begin cases e : b v - a v, { simp [not_lt.2 (tsub_eq_zero_iff_le.mp e)] }, { simp [nat.lt_of_sub_eq_succ e] } end theorem mkpair : @primrec' 2 (λ v, v.head.mkpair v.tail.head) := if_lt head (tail head) (add.comp₂ _ (tail $ mul.comp₂ _ head head) head) (add.comp₂ _ (add.comp₂ _ (mul.comp₂ _ head head) head) (tail head)) protected theorem encode : ∀ {n}, @primrec' n encode | 0 := (const 0).of_eq (λ v, by rw v.eq_nil; refl) | (n+1) := (succ.comp₁ _ (mkpair.comp₂ _ head (tail encode))) .of_eq $ λ ⟨a::l, e⟩, rfl theorem sqrt : @primrec' 1 (λ v, v.head.sqrt) := begin suffices H : ∀ n : ℕ, n.sqrt = n.elim 0 (λ x y, if x.succ < y.succ*y.succ then y else y.succ), { simp [H], have := @prec' 1 _ _ (λ v, by have x := v.head; have y := v.tail.head; from if x.succ < y.succ*y.succ then y else y.succ) head (const 0) _, { convert this, funext, congr, funext x y, congr; simp }, have x1 := succ.comp₁ _ head, have y1 := succ.comp₁ _ (tail head), exact if_lt x1 (mul.comp₂ _ y1 y1) (tail head) y1 }, intro, symmetry, induction n with n IH, {simp}, dsimp, rw IH, split_ifs, { exact le_antisymm (nat.sqrt_le_sqrt (nat.le_succ _)) (nat.lt_succ_iff.1 $ nat.sqrt_lt.2 h) }, { exact nat.eq_sqrt.2 ⟨not_lt.1 h, nat.sqrt_lt.1 $ nat.lt_succ_iff.2 $ nat.sqrt_succ_le_succ_sqrt _⟩ }, end theorem unpair₁ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.1) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s fss s).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem unpair₂ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.2) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s s (sub.comp₂ _ fss s)).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem of_prim : ∀ {n f}, primrec f → @primrec' n f := suffices ∀ f, nat.primrec f → @primrec' 1 (λ v, f v.head), from λ n f hf, (pred.comp₁ _ $ (this _ hf).comp₁ (λ m, encodable.encode $ (decode (vector ℕ n) m).map f) primrec'.encode).of_eq (λ i, by simp [encodek]), λ f hf, begin induction hf, case nat.primrec.zero { exact const 0 }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact unpair₁ head }, case nat.primrec.right { exact unpair₂ head }, case nat.primrec.pair : f g _ _ hf hg { exact mkpair.comp₂ _ hf hg }, case nat.primrec.comp : f g _ _ hf hg { exact hf.comp₁ _ hg }, case nat.primrec.prec : f g _ _ hf hg { simpa using prec' (unpair₂ head) (hf.comp₁ _ (unpair₁ head)) (hg.comp₁ _ $ mkpair.comp₂ _ (unpair₁ $ tail $ tail head) (mkpair.comp₂ _ head (tail head))) }, end theorem prim_iff {n f} : @primrec' n f ↔ primrec f := ⟨to_prim, of_prim⟩ theorem prim_iff₁ {f : ℕ → ℕ} : @primrec' 1 (λ v, f v.head) ↔ primrec f := prim_iff.trans ⟨ λ h, (h.comp $ vector_of_fn $ λ i, primrec.id).of_eq (λ v, by simp), λ h, h.comp vector_head⟩ theorem prim_iff₂ {f : ℕ → ℕ → ℕ} : @primrec' 2 (λ v, f v.head v.tail.head) ↔ primrec₂ f := prim_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (primrec.const nil)).of_eq (λ v, by simp), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ primrec f := ⟨λ h, by simpa using vector_of_fn (λ i, to_prim (h i)), λ h i, of_prim $ vector_nth.comp h (primrec.const i)⟩ end nat.primrec' theorem primrec.nat_sqrt : primrec nat.sqrt := nat.primrec'.prim_iff₁.1 nat.primrec'.sqrt
34406c093c49a03a06c418cf1034581e8e300c11
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/category_theory/over.lean
5056f625ea96f654c9259ee2643a4add4001ea32
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
9,755
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Bhavik Mehta -/ import category_theory.comma import category_theory.punit import category_theory.reflects_isomorphisms /-! # Over and under categories Over (and under) categories are special cases of comma categories. * If `L` is the identity functor and `R` is a constant functor, then `comma L R` is the "slice" or "over" category over the object `R` maps to. * Conversely, if `L` is a constant functor and `R` is the identity functor, then `comma L R` is the "coslice" or "under" category under the object `L` maps to. ## Tags comma, slice, coslice, over, under -/ namespace category_theory universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {T : Type u₁} [category.{v₁} T] /-- The over category has as objects arrows in `T` with codomain `X` and as morphisms commutative triangles. See https://stacks.math.columbia.edu/tag/001G. -/ @[derive category] def over (X : T) := comma.{v₁ v₁ v₁} (𝟭 T) (functor.from_punit X) -- Satisfying the inhabited linter instance over.inhabited [inhabited T] : inhabited (over (default T)) := { default := { left := default T, hom := 𝟙 _ } } namespace over variables {X : T} @[ext] lemma over_morphism.ext {X : T} {U V : over X} {f g : U ⟶ V} (h : f.left = g.left) : f = g := by tidy @[simp] lemma over_right (U : over X) : U.right = punit.star := by tidy @[simp] lemma id_left (U : over X) : comma_morphism.left (𝟙 U) = 𝟙 U.left := rfl @[simp] lemma comp_left (a b c : over X) (f : a ⟶ b) (g : b ⟶ c) : (f ≫ g).left = f.left ≫ g.left := rfl @[simp, reassoc] lemma w {A B : over X} (f : A ⟶ B) : f.left ≫ B.hom = A.hom := by have := f.w; tidy /-- To give an object in the over category, it suffices to give a morphism with codomain `X`. -/ @[simps] def mk {X Y : T} (f : Y ⟶ X) : over X := { left := Y, hom := f } /-- We can set up a coercion from arrows with codomain `X` to `over X`. This most likely should not be a global instance, but it is sometimes useful. -/ def coe_from_hom {X Y : T} : has_coe (Y ⟶ X) (over X) := { coe := mk } section local attribute [instance] coe_from_hom @[simp] lemma coe_hom {X Y : T} (f : Y ⟶ X) : (f : over X).hom = f := rfl end /-- To give a morphism in the over category, it suffices to give an arrow fitting in a commutative triangle. -/ @[simps] def hom_mk {U V : over X} (f : U.left ⟶ V.left) (w : f ≫ V.hom = U.hom . obviously) : U ⟶ V := { left := f } /-- Construct an isomorphism in the over category given isomorphisms of the objects whose forward direction gives a commutative triangle. -/ @[simps] def iso_mk {f g : over X} (hl : f.left ≅ g.left) (hw : hl.hom ≫ g.hom = f.hom . obviously) : f ≅ g := comma.iso_mk hl (eq_to_iso (subsingleton.elim _ _)) (by simp [hw]) section variable (X) /-- The forgetful functor mapping an arrow to its domain. See https://stacks.math.columbia.edu/tag/001G. -/ def forget : over X ⥤ T := comma.fst _ _ end @[simp] lemma forget_obj {U : over X} : (forget X).obj U = U.left := rfl @[simp] lemma forget_map {U V : over X} {f : U ⟶ V} : (forget X).map f = f.left := rfl /-- A morphism `f : X ⟶ Y` induces a functor `over X ⥤ over Y` in the obvious way. See https://stacks.math.columbia.edu/tag/001G. -/ def map {Y : T} (f : X ⟶ Y) : over X ⥤ over Y := comma.map_right _ $ discrete.nat_trans (λ _, f) section variables {Y : T} {f : X ⟶ Y} {U V : over X} {g : U ⟶ V} @[simp] lemma map_obj_left : ((map f).obj U).left = U.left := rfl @[simp] lemma map_obj_hom : ((map f).obj U).hom = U.hom ≫ f := rfl @[simp] lemma map_map_left : ((map f).map g).left = g.left := rfl /-- Mapping by the identity morphism is just the identity functor. -/ def map_id : map (𝟙 Y) ≅ 𝟭 _ := nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy) /-- Mapping by the composite morphism `f ≫ g` is the same as mapping by `f` then by `g`. -/ def map_comp {Y Z : T} (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map f ⋙ map g := nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy) end instance forget_reflects_iso : reflects_isomorphisms (forget X) := { reflects := λ Y Z f t, by exactI { inv := over.hom_mk t.inv ((as_iso ((forget X).map f)).inv_comp_eq.2 (over.w f).symm) } } section iterated_slice variables (f : over X) /-- Given f : Y ⟶ X, this is the obvious functor from (T/X)/f to T/Y -/ @[simps] def iterated_slice_forward : over f ⥤ over f.left := { obj := λ α, over.mk α.hom.left, map := λ α β κ, over.hom_mk κ.left.left (by { rw auto_param_eq, rw ← over.w κ, refl }) } /-- Given f : Y ⟶ X, this is the obvious functor from T/Y to (T/X)/f -/ @[simps] def iterated_slice_backward : over f.left ⥤ over f := { obj := λ g, mk (hom_mk g.hom : mk (g.hom ≫ f.hom) ⟶ f), map := λ g h α, hom_mk (hom_mk α.left (w_assoc α f.hom)) (over_morphism.ext (w α)) } /-- Given f : Y ⟶ X, we have an equivalence between (T/X)/f and T/Y -/ @[simps] def iterated_slice_equiv : over f ≌ over f.left := { functor := iterated_slice_forward f, inverse := iterated_slice_backward f, unit_iso := nat_iso.of_components (λ g, over.iso_mk (over.iso_mk (iso.refl _) (by tidy)) (by tidy)) (λ X Y g, by { ext, dsimp, simp }), counit_iso := nat_iso.of_components (λ g, over.iso_mk (iso.refl _) (by tidy)) (λ X Y g, by { ext, dsimp, simp }) } lemma iterated_slice_forward_forget : iterated_slice_forward f ⋙ forget f.left = forget f ⋙ forget X := rfl lemma iterated_slice_backward_forget_forget : iterated_slice_backward f ⋙ forget f ⋙ forget X = forget f.left := rfl end iterated_slice section variables {D : Type u₂} [category.{v₂} D] /-- A functor `F : T ⥤ D` induces a functor `over X ⥤ over (F.obj X)` in the obvious way. -/ @[simps] def post (F : T ⥤ D) : over X ⥤ over (F.obj X) := { obj := λ Y, mk $ F.map Y.hom, map := λ Y₁ Y₂ f, { left := F.map f.left, w' := by tidy; erw [← F.map_comp, w] } } end end over /-- The under category has as objects arrows with domain `X` and as morphisms commutative triangles. -/ @[derive category] def under (X : T) := comma.{v₁ v₁ v₁} (functor.from_punit X) (𝟭 T) -- Satisfying the inhabited linter instance under.inhabited [inhabited T] : inhabited (under (default T)) := { default := { right := default T, hom := 𝟙 _ } } namespace under variables {X : T} @[ext] lemma under_morphism.ext {X : T} {U V : under X} {f g : U ⟶ V} (h : f.right = g.right) : f = g := by tidy @[simp] lemma under_left (U : under X) : U.left = punit.star := by tidy @[simp] lemma id_right (U : under X) : comma_morphism.right (𝟙 U) = 𝟙 U.right := rfl @[simp] lemma comp_right (a b c : under X) (f : a ⟶ b) (g : b ⟶ c) : (f ≫ g).right = f.right ≫ g.right := rfl @[simp] lemma w {A B : under X} (f : A ⟶ B) : A.hom ≫ f.right = B.hom := by have := f.w; tidy /-- To give an object in the under category, it suffices to give an arrow with domain `X`. -/ @[simps] def mk {X Y : T} (f : X ⟶ Y) : under X := { right := Y, hom := f } /-- To give a morphism in the under category, it suffices to give a morphism fitting in a commutative triangle. -/ @[simps] def hom_mk {U V : under X} (f : U.right ⟶ V.right) (w : U.hom ≫ f = V.hom . obviously) : U ⟶ V := { right := f } /-- Construct an isomorphism in the over category given isomorphisms of the objects whose forward direction gives a commutative triangle. -/ def iso_mk {f g : under X} (hr : f.right ≅ g.right) (hw : f.hom ≫ hr.hom = g.hom) : f ≅ g := comma.iso_mk (eq_to_iso (subsingleton.elim _ _)) hr (by simp [hw]) @[simp] lemma iso_mk_hom_right {f g : under X} (hr : f.right ≅ g.right) (hw : f.hom ≫ hr.hom = g.hom) : (iso_mk hr hw).hom.right = hr.hom := rfl @[simp] lemma iso_mk_inv_right {f g : under X} (hr : f.right ≅ g.right) (hw : f.hom ≫ hr.hom = g.hom) : (iso_mk hr hw).inv.right = hr.inv := rfl section variables (X) /-- The forgetful functor mapping an arrow to its domain. -/ def forget : under X ⥤ T := comma.snd _ _ end @[simp] lemma forget_obj {U : under X} : (forget X).obj U = U.right := rfl @[simp] lemma forget_map {U V : under X} {f : U ⟶ V} : (forget X).map f = f.right := rfl /-- A morphism `X ⟶ Y` induces a functor `under Y ⥤ under X` in the obvious way. -/ def map {Y : T} (f : X ⟶ Y) : under Y ⥤ under X := comma.map_left _ $ discrete.nat_trans (λ _, f) section variables {Y : T} {f : X ⟶ Y} {U V : under Y} {g : U ⟶ V} @[simp] lemma map_obj_right : ((map f).obj U).right = U.right := rfl @[simp] lemma map_obj_hom : ((map f).obj U).hom = f ≫ U.hom := rfl @[simp] lemma map_map_right : ((map f).map g).right = g.right := rfl /-- Mapping by the identity morphism is just the identity functor. -/ def map_id : map (𝟙 Y) ≅ 𝟭 _ := nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy) /-- Mapping by the composite morphism `f ≫ g` is the same as mapping by `f` then by `g`. -/ def map_comp {Y Z : T} (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map g ⋙ map f := nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy) end section variables {D : Type u₂} [category.{v₂} D] /-- A functor `F : T ⥤ D` induces a functor `under X ⥤ under (F.obj X)` in the obvious way. -/ @[simps] def post {X : T} (F : T ⥤ D) : under X ⥤ under (F.obj X) := { obj := λ Y, mk $ F.map Y.hom, map := λ Y₁ Y₂ f, { right := F.map f.right, w' := by tidy; erw [← F.map_comp, w] } } end end under end category_theory
bc01188145a870cc2fc105f882ead93bd2ddf77b
e953c38599905267210b87fb5d82dcc3e52a4214
/hott/init/equiv.hlean
6d94fed01297697479ab50fb9eeeb001133362da
[ "Apache-2.0" ]
permissive
c-cube/lean
563c1020bff98441c4f8ba60111fef6f6b46e31b
0fb52a9a139f720be418dafac35104468e293b66
refs/heads/master
1,610,753,294,113
1,440,451,356,000
1,440,499,588,000
41,748,334
0
0
null
1,441,122,656,000
1,441,122,656,000
null
UTF-8
Lean
false
false
12,900
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Jakob von Raumer Ported from Coq HoTT -/ prelude import .path .function open eq function lift /- Equivalences -/ -- This is our definition of equivalence. In the HoTT-book it's called -- ihae (half-adjoint equivalence). structure is_equiv [class] {A B : Type} (f : A → B) := mk' :: (inv : B → A) (right_inv : Πb, f (inv b) = b) (left_inv : Πa, inv (f a) = a) (adj : Πx, right_inv (f x) = ap f (left_inv x)) attribute is_equiv.inv [quasireducible] -- A more bundled version of equivalence structure equiv (A B : Type) := (to_fun : A → B) (to_is_equiv : is_equiv to_fun) namespace is_equiv /- Some instances and closure properties of equivalences -/ postfix `⁻¹` := inv /- a second notation for the inverse, which is not overloaded -/ postfix [parsing-only] `⁻¹ᶠ`:std.prec.max_plus := inv section variables {A B C : Type} (f : A → B) (g : B → C) {f' : A → B} -- The variant of mk' where f is explicit. protected abbreviation mk [constructor] := @is_equiv.mk' A B f -- The identity function is an equivalence. definition is_equiv_id (A : Type) : (is_equiv (id : A → A)) := is_equiv.mk id id (λa, idp) (λa, idp) (λa, idp) -- The composition of two equivalences is, again, an equivalence. definition is_equiv_compose [Hf : is_equiv f] [Hg : is_equiv g] : is_equiv (g ∘ f) := is_equiv.mk (g ∘ f) (f⁻¹ ∘ g⁻¹) (λc, ap g (right_inv f (g⁻¹ c)) ⬝ right_inv g c) (λa, ap (inv f) (left_inv g (f a)) ⬝ left_inv f a) (λa, (whisker_left _ (adj g (f a))) ⬝ (ap_con g _ _)⁻¹ ⬝ ap02 g ((ap_con_eq_con (right_inv f) (left_inv g (f a)))⁻¹ ⬝ (ap_compose f (inv f) _ ◾ adj f a) ⬝ (ap_con f _ _)⁻¹ ) ⬝ (ap_compose g f _)⁻¹ ) -- Any function equal to an equivalence is an equivlance as well. variable {f} definition is_equiv_eq_closed [Hf : is_equiv f] (Heq : f = f') : is_equiv f' := eq.rec_on Heq Hf end section parameters {A B : Type} (f : A → B) (g : B → A) (ret : Πb, f (g b) = b) (sec : Πa, g (f a) = a) private definition adjointify_left_inv' (a : A) : g (f a) = a := ap g (ap f (inverse (sec a))) ⬝ ap g (ret (f a)) ⬝ sec a private definition adjointify_adj' (a : A) : ret (f a) = ap f (adjointify_left_inv' a) := let fgretrfa := ap f (ap g (ret (f a))) in let fgfinvsect := ap f (ap g (ap f (sec a)⁻¹)) in let fgfa := f (g (f a)) in let retrfa := ret (f a) in have eq1 : ap f (sec a) = _, from calc ap f (sec a) = idp ⬝ ap f (sec a) : by rewrite idp_con ... = (ret (f a) ⬝ (ret (f a))⁻¹) ⬝ ap f (sec a) : by rewrite con.right_inv ... = ((ret fgfa)⁻¹ ⬝ ap (f ∘ g) (ret (f a))) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((ret fgfa)⁻¹ ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc, have eq2 : ap f (sec a) ⬝ idp = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)), from !con_idp ⬝ eq1, have eq3 : idp = _, from calc idp = (ap f (sec a))⁻¹ ⬝ ((ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a))) : eq_inv_con_of_con_eq eq2 ... = ((ap f (sec a))⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc' ... = (ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite ap_inv ... = ((ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con.assoc' ... = ((retrfa⁻¹ ⬝ ap (f ∘ g) (ap f (sec a)⁻¹)) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((retrfa⁻¹ ⬝ fgfinvsect) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (retrfa⁻¹ ⬝ (fgfinvsect ⬝ fgretrfa)) ⬝ ap f (sec a) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a) : by rewrite ap_con ... = retrfa⁻¹ ⬝ (ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a)) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a) : by rewrite -ap_con, have eq4 : ret (f a) = ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a), from eq_of_idp_eq_inv_con eq3, eq4 definition adjointify [constructor] : is_equiv f := is_equiv.mk f g ret adjointify_left_inv' adjointify_adj' end -- Any function pointwise equal to an equivalence is an equivalence as well. definition homotopy_closed [constructor] {A B : Type} {f f' : A → B} [Hf : is_equiv f] (Hty : f ~ f') : is_equiv f' := adjointify f' (inv f) (λ b, (Hty (inv f b))⁻¹ ⬝ right_inv f b) (λ a, (ap (inv f) (Hty a))⁻¹ ⬝ left_inv f a) definition inv_homotopy_closed [constructor] {A B : Type} {f : A → B} {f' : B → A} [Hf : is_equiv f] (Hty : f⁻¹ ~ f') : is_equiv f := adjointify f f' (λ b, ap f !Hty⁻¹ ⬝ right_inv f b) (λ a, !Hty⁻¹ ⬝ left_inv f a) definition is_equiv_up [instance] (A : Type) : is_equiv (up : A → lift A) := adjointify up down (λa, by induction a;reflexivity) (λa, idp) section variables {A B C : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f] (g : B → C) include Hf --The inverse of an equivalence is, again, an equivalence. definition is_equiv_inv [instance] : is_equiv f⁻¹ := adjointify f⁻¹ f (left_inv f) (right_inv f) definition cancel_right (g : B → C) [Hgf : is_equiv (g ∘ f)] : (is_equiv g) := have Hfinv [visible] : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose f⁻¹ (g ∘ f)) (λb, ap g (@right_inv _ _ f _ b)) definition cancel_left (g : C → A) [Hgf : is_equiv (f ∘ g)] : (is_equiv g) := have Hfinv [visible] : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose (f ∘ g) f⁻¹) (λa, left_inv f (g a)) definition eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : x = y := (left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y definition is_equiv_ap [instance] (x y : A) : is_equiv (ap f : x = y → f x = f y) := adjointify (ap f) (eq_of_fn_eq_fn' f) (λq, !ap_con ⬝ whisker_right !ap_con _ ⬝ ((!ap_inv ⬝ inverse2 (adj f _)⁻¹) ◾ (inverse (ap_compose f f⁻¹ _)) ◾ (adj f _)⁻¹) ⬝ con_ap_con_eq_con_con (right_inv f) _ _ ⬝ whisker_right !con.left_inv _ ⬝ !idp_con) (λp, whisker_right (whisker_left _ (ap_compose f⁻¹ f _)⁻¹) _ ⬝ con_ap_con_eq_con_con (left_inv f) _ _ ⬝ whisker_right !con.left_inv _ ⬝ !idp_con) -- The function equiv_rect says that given an equivalence f : A → B, -- and a hypothesis from B, one may always assume that the hypothesis -- is in the image of e. -- In fibrational terms, if we have a fibration over B which has a section -- once pulled back along an equivalence f : A → B, then it has a section -- over all of B. definition is_equiv_rect (P : B → Type) : (Πx, P (f x)) → (Πy, P y) := (λg y, eq.transport _ (right_inv f y) (g (f⁻¹ y))) definition is_equiv_rect_comp (P : B → Type) (df : Π (x : A), P (f x)) (x : A) : is_equiv_rect f P df (f x) = df x := calc is_equiv_rect f P df (f x) = right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp ... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj ... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose ... = df x : by rewrite (apd df (left_inv f x)) end section variables {A B : Type} {f : A → B} [Hf : is_equiv f] {a : A} {b : B} include Hf --Rewrite rules definition eq_of_eq_inv (p : a = f⁻¹ b) : f a = b := ap f p ⬝ right_inv f b definition eq_of_inv_eq (p : f⁻¹ b = a) : b = f a := (eq_of_eq_inv p⁻¹)⁻¹ definition inv_eq_of_eq (p : b = f a) : f⁻¹ b = a := ap f⁻¹ p ⬝ left_inv f a definition eq_inv_of_eq (p : f a = b) : a = f⁻¹ b := (inv_eq_of_eq p⁻¹)⁻¹ end --Transporting is an equivalence definition is_equiv_tr [instance] {A : Type} (P : A → Type) {x y : A} (p : x = y) : (is_equiv (transport P p)) := is_equiv.mk _ (transport P p⁻¹) (tr_inv_tr p) (inv_tr_tr p) (tr_inv_tr_lemma p) end is_equiv open is_equiv namespace eq definition tr_inv_fn {A : Type} {B : A → Type} {a a' : A} (p : a = a') : transport B p⁻¹ = (transport B p)⁻¹ := idp definition tr_inv {A : Type} {B : A → Type} {a a' : A} (p : a = a') (b : B a') : p⁻¹ ▸ b = (transport B p)⁻¹ b := idp definition cast_inv_fn {A B : Type} (p : A = B) : cast p⁻¹ = (cast p)⁻¹ := idp definition cast_inv {A B : Type} (p : A = B) (b : B) : cast p⁻¹ b = (cast p)⁻¹ b := idp end eq namespace equiv namespace ops attribute to_fun [coercion] end ops open equiv.ops attribute to_is_equiv [instance] infix `≃`:25 := equiv variables {A B C : Type} protected definition MK [reducible] [constructor] (f : A → B) (g : B → A) (right_inv : Πb, f (g b) = b) (left_inv : Πa, g (f a) = a) : A ≃ B := equiv.mk f (adjointify f g right_inv left_inv) definition to_inv [reducible] [unfold 3] (f : A ≃ B) : B → A := f⁻¹ definition to_right_inv [reducible] [unfold 3] (f : A ≃ B) (b : B) : f (f⁻¹ b) = b := right_inv f b definition to_left_inv [reducible] [unfold 3] (f : A ≃ B) (a : A) : f⁻¹ (f a) = a := left_inv f a protected definition refl [refl] [constructor] : A ≃ A := equiv.mk id !is_equiv_id protected definition symm [symm] [unfold 3] (f : A ≃ B) : B ≃ A := equiv.mk f⁻¹ !is_equiv_inv protected definition trans [trans] (f : A ≃ B) (g: B ≃ C) : A ≃ C := equiv.mk (g ∘ f) !is_equiv_compose infixl `⬝e`:75 := equiv.trans postfix [parsing-only] `⁻¹ᵉ`:(max + 1) := equiv.symm -- notation for inverse which is not overloaded abbreviation erfl [constructor] := @equiv.refl definition equiv_change_fun [constructor] (f : A ≃ B) {f' : A → B} (Heq : f ~ f') : A ≃ B := equiv.mk f' (is_equiv.homotopy_closed Heq) definition equiv_change_inv [constructor] (f : A ≃ B) {f' : B → A} (Heq : f⁻¹ ~ f') : A ≃ B := equiv.mk f (inv_homotopy_closed Heq) --rename: eq_equiv_fn_eq_of_is_equiv definition eq_equiv_fn_eq [constructor] (f : A → B) [H : is_equiv f] (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap --rename: eq_equiv_fn_eq definition eq_equiv_fn_eq_of_equiv [constructor] (f : A ≃ B) (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap definition equiv_ap (P : A → Type) {a b : A} (p : a = b) : (P a) ≃ (P b) := equiv.mk (transport P p) !is_equiv_tr definition eq_of_fn_eq_fn (f : A ≃ B) {x y : A} (q : f x = f y) : x = y := (left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y definition eq_of_fn_eq_fn_inv (f : A ≃ B) {x y : B} (q : f⁻¹ x = f⁻¹ y) : x = y := (right_inv f x)⁻¹ ⬝ ap f q ⬝ right_inv f y --we need this theorem for the funext_of_ua proof theorem inv_eq {A B : Type} (eqf eqg : A ≃ B) (p : eqf = eqg) : (to_fun eqf)⁻¹ = (to_fun eqg)⁻¹ := eq.rec_on p idp definition equiv_of_equiv_of_eq [trans] {A B C : Type} (p : A = B) (q : B ≃ C) : A ≃ C := p⁻¹ ▸ q definition equiv_of_eq_of_equiv [trans] {A B C : Type} (p : A ≃ B) (q : B = C) : A ≃ C := q ▸ p definition equiv_lift (A : Type) : A ≃ lift A := equiv.mk up _ definition equiv_rect (f : A ≃ B) (P : B → Type) : (Πx, P (f x)) → (Πy, P y) := (λg y, eq.transport _ (right_inv f y) (g (f⁻¹ y))) definition equiv_rect_comp (f : A ≃ B) (P : B → Type) (df : Π (x : A), P (f x)) (x : A) : equiv_rect f P df (f x) = df x := calc equiv_rect f P df (f x) = right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp ... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj ... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose ... = df x : by rewrite (apd df (left_inv f x)) namespace ops postfix `⁻¹` := equiv.symm -- overloaded notation for inverse end ops end equiv export [unfold-hints] equiv [unfold-hints] is_equiv
44cbfc2ad40cffee1d194122a47f35d9f13088ac
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/ring_exp.lean
e2a9036b53ba7ecd39c024bda9f867f36a49271a
[ "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,377
lean
import tactic.ring_exp import tactic.zify import algebra.group_with_zero.power import algebra.ring.pi import tactic.field_simp universes u section addition /-! ### `addition` section Test associativity and commutativity of `(+)`. -/ example (a b : ℚ) : a = a := by ring_exp example (a b : ℚ) : a + b = a + b := by ring_exp example (a b : ℚ) : b + a = a + b := by ring_exp example (a b : ℤ) : a + b + b = b + (a + b) := by ring_exp example (a b c : ℕ) : a + b + b + (c + c) = c + (b + c) + (a + b) := by ring_exp end addition section numerals /-! ### `numerals` section Test that numerals behave like rational numbers. -/ example (a : ℕ) : a + 5 + 5 = 0 + a + 10 := by ring_exp example (a : ℤ) : a + 5 + 5 = 0 + a + 10 := by ring_exp example (a : ℚ) : (1/2) * a + (1/2) * a = a := by ring_exp end numerals section multiplication /-! ### `multiplication section` Test that multiplication is associative and commutative. Also test distributivity of `(+)` and `(*)`. -/ example (a : ℕ) : 0 = a * 0 := by ring_exp_eq example (a : ℕ) : a = a * 1 := by ring_exp example (a : ℕ) : a + a = a * 2 := by ring_exp example (a b : ℤ) : a * b = b * a := by ring_exp example (a b : ℕ) : a * 4 * b + a = a * (4 * b + 1) := by ring_exp end multiplication section exponentiation /-! ### `exponentiation` section Test that exponentiation has the correct distributivity properties. -/ example : 0 ^ 1 = 0 := by ring_exp example : 0 ^ 2 = 0 := by ring_exp example (a : ℕ) : a ^ 0 = 1 := by ring_exp example (a : ℕ) : a ^ 1 = a := by ring_exp example (a : ℕ) : a ^ 2 = a * a := by ring_exp example (a b : ℕ) : a ^ b = a ^ b := by ring_exp example (a b : ℕ) : a ^ (b + 1) = a * a ^ b := by ring_exp example (n : ℕ) (a m : ℕ) : a * a^n * m = a^(n+1) * m := by ring_exp example (n : ℕ) (a m : ℕ) : m * a^n * a = a^(n+1) * m := by ring_exp example (n : ℕ) (a m : ℤ) : a * a^n * m = a^(n+1) * m := by ring_exp example (n : ℕ) (m : ℤ) : 2 * 2^n * m = 2^(n+1) * m := by ring_exp example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring_exp example (n m : ℕ) (a : ℤ) : (a ^ n)^m = a^(n * m) := by ring_exp example (n m : ℕ) (a : ℤ) : a^(n^0) = a^1 := by ring_exp example (n : ℕ) : 0^(n + 1) = 0 := by ring_exp example {α} [comm_ring α] (x : α) (k : ℕ) : x ^ (k + 2) = x * x * x^k := by ring_exp example {α} [comm_ring α] (k : ℕ) (x y z : α) : x * (z * (x - y)) + (x * (y * y ^ k) - y * (y * y ^ k)) = (z * x + y * y ^ k) * (x - y) := by ring_exp -- We can represent a large exponent `n` more efficiently than just `n` multiplications: example (a b : ℚ) : (a * b) ^ 1000000 = (b * a) ^ 1000000 := by ring_exp example (n : ℕ) : 2 ^ (n + 1 + 1) = 2 * 2 ^ (n + 1) := by ring_exp_eq -- power does not have to be a syntactic match to `monoid.has_pow` example {α} [comm_ring α] (x : ℕ → α) : (x ^ 2 * x) = x ^ 3 := by ring_exp -- Powers in the exponent get evaluated correctly. example (X : ℤ) : (X^5 + 1) * (X^2^3 + X) = X^13 + X^8 + X^6 + X := by ring_exp end exponentiation section power_of_sum /-! ### `power_of_sum` section Test that raising a sum to a power behaves like repeated multiplication, if needed. -/ example (a b : ℤ) : (a + b)^2 = a^2 + b^2 + a * b + b * a := by ring_exp example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring_exp end power_of_sum section negation /-! ### `negation` section Test that negation and subtraction satisfy the expected properties, also in semirings such as `ℕ`. -/ example {α} [comm_ring α] (a : α) : a - a = 0 := by ring_exp_eq example (a : ℤ) : a - a = 0 := by ring_exp example (a : ℤ) : a + - a = 0 := by ring_exp example (a : ℤ) : - a = (-1) * a := by ring_exp -- Here, (a - b) is treated as an atom. example (a b : ℕ) : a - b + a + a = a - b + 2 * a := by ring_exp example (n : ℕ) : n + 1 - 1 = n := by ring_exp! -- But we can force a bit of evaluation anyway. end negation constant f {α} : α → α section complicated /-! ### `complicated` section Test that complicated, real-life expressions also get normalized. -/ example {α : Type} [linear_ordered_field α] (x : α) : 2 * x + 1 * 1 - (2 * f (x + 1 / 2) + 2 * 1) + (1 * 1 - (2 * x - 2 * f (x + 1 / 2))) = 0 := by ring_exp_eq example {α : Type u} [linear_ordered_field α] (x : α) : f (x + 1 / 2) ^ 1 * -2 + (f (x + 1 / 2) ^ 1 * 2 + 0) = 0 := by ring_exp_eq example (x y : ℕ) : x + id y = y + id x := by ring_exp! -- Here, we check that `n - s` is not treated as `n + additive_inverse s`, -- if `s` doesn't have an additive inverse. example (B s n : ℕ) : B * (f s * ((n - s) * f (n - s - 1))) = B * (n - s) * (f s * f (n - s - 1)) := by ring_exp -- This is a somewhat subtle case: `-c/b` is parsed as `(-c)/b`, -- so we can't simply treat both sides of the division as atoms. -- Instead, we follow the `ring` tactic in interpreting `-c / b` as `-c * b⁻¹`, -- with only `b⁻¹` an atom. example {α} [linear_ordered_field α] (a b c : α) : a*(-c/b)*(-c/b) = a*((c/b)*(c/b)) := by ring_exp -- test that `field_simp` works fine with powers and `ring_exp`. example (x y : ℚ) (n : ℕ) (hx : x ≠ 0) (hy : y ≠ 0) : 1/ (2/(x / y))^(2 * n) + y / y^(n+1) - (x/y)^n * (x/(2 * y))^n / 2 ^n = 1/y^n := begin field_simp, ring_exp end end complicated -- Test that `nat.succ d` gets handled as `d + 1`. example (d : ℕ) : 2 * (2 ^ d - 1) + 1 = 2 ^ d.succ - 1 := begin zify [nat.one_le_pow'], ring_exp, end -- Simplified instance of a bug reported by Patrick Massot: -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/ring_exp.20bug example (l : ℤ) : l - l = 0 := begin tactic.replace_at (tactic.ring_exp.normalize tactic.transparency.reducible) [] tt >> pure (), refl end -- Normalizing also works on more complicated expressions: example (a b : ℤ) : (a^2 - b - b) + (2 * id b - a^2) = 0 := begin tactic.replace_at (tactic.ring_exp.normalize tactic.transparency.semireducible) [] tt >> pure (), refl end section conv /-! ### `conv` section Test that `ring_exp` works inside of `conv`, both with and without `!`. -/ example (n : ℕ) : (2^n * 2 + 1)^10 = (2^(n+1) + 1)^10 := begin conv_rhs { congr, ring_exp, }, conv_lhs { congr, ring_exp, }, end example (x y : ℤ) : x + id y - y + id x = x * 2 := begin conv_lhs { ring_exp!, }, end end conv section benchmark /-! ### `benchmark` section The `ring_exp` tactic shouldn't be too slow. -/ -- This last example was copied from `data/polynomial.lean`, because it timed out. -- After some optimization, it doesn't. variables {α : Type} [comm_ring α] def pow_sub_pow_factor (x y : α) : Π {i : ℕ},{z // x^i - y^i = z*(x - y)} | 0 := ⟨0, by simp⟩ | 1 := ⟨1, by simp⟩ | (k+2) := begin cases @pow_sub_pow_factor (k+1) with z hz, existsi z*x + y^(k+1), rw [pow_succ x, pow_succ y, ←sub_add_sub_cancel (x*x^(k+1)) (x*y^(k+1)), ←mul_sub x, hz], ring_exp_eq end -- Another benchmark: bound the growth of the complexity somewhat. example {α} [comm_semiring α] (x : α) : (x + 1) ^ 4 = (1 + x) ^ 4 := by try_for 5000 {ring_exp} example {α} [comm_semiring α] (x : α) : (x + 1) ^ 6 = (1 + x) ^ 6 := by try_for 10000 {ring_exp} example {α} [comm_semiring α] (x : α) : (x + 1) ^ 8 = (1 + x) ^ 8 := by try_for 15000 {ring_exp} end benchmark
c73f437f79a0b234aae0cefcc7bcd1cfeb925c5c
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/category/Top/opens.lean
2e2bd928bf36b5744cb6da6531417d230793cf0a
[ "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
10,377
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.category.preorder import category_theory.eq_to_hom import topology.category.Top.epi_mono import topology.sets.opens /-! # The category of open sets in a topological space. We define `to_Top : opens X ⥤ Top` and `map (f : X ⟶ Y) : opens Y ⥤ opens X`, given by taking preimages of open sets. Unfortunately `opens` isn't (usefully) a functor `Top ⥤ Cat`. (One can in fact define such a functor, but using it results in unresolvable `eq.rec` terms in goals.) Really it's a 2-functor from (spaces, continuous functions, equalities) to (categories, functors, natural isomorphisms). We don't attempt to set up the full theory here, but do provide the natural isomorphisms `map_id : map (𝟙 X) ≅ 𝟭 (opens X)` and `map_comp : map (f ≫ g) ≅ map g ⋙ map f`. Beyond that, there's a collection of simp lemmas for working with these constructions. -/ open category_theory open topological_space open opposite universe u namespace topological_space.opens variables {X Y Z : Top.{u}} /-! Since `opens X` has a partial order, it automatically receives a `category` instance. Unfortunately, because we do not allow morphisms in `Prop`, the morphisms `U ⟶ V` are not just proofs `U ≤ V`, but rather `ulift (plift (U ≤ V))`. -/ instance opens_hom_has_coe_to_fun {U V : opens X} : has_coe_to_fun (U ⟶ V) (λ f, U → V) := ⟨λ f x, ⟨x, f.le x.2⟩⟩ /-! We now construct as morphisms various inclusions of open sets. -/ -- This is tedious, but necessary because we decided not to allow Prop as morphisms in a category... /-- The inclusion `U ⊓ V ⟶ U` as a morphism in the category of open sets. -/ def inf_le_left (U V : opens X) : U ⊓ V ⟶ U := inf_le_left.hom /-- The inclusion `U ⊓ V ⟶ V` as a morphism in the category of open sets. -/ def inf_le_right (U V : opens X) : U ⊓ V ⟶ V := inf_le_right.hom /-- The inclusion `U i ⟶ supr U` as a morphism in the category of open sets. -/ def le_supr {ι : Type*} (U : ι → opens X) (i : ι) : U i ⟶ supr U := (le_supr U i).hom /-- The inclusion `⊥ ⟶ U` as a morphism in the category of open sets. -/ def bot_le (U : opens X) : ⊥ ⟶ U := bot_le.hom /-- The inclusion `U ⟶ ⊤` as a morphism in the category of open sets. -/ def le_top (U : opens X) : U ⟶ ⊤ := le_top.hom -- We do not mark this as a simp lemma because it breaks open `x`. -- Nevertheless, it is useful in `sheaf_of_functions`. lemma inf_le_left_apply (U V : opens X) (x) : (inf_le_left U V) x = ⟨x.1, (@_root_.inf_le_left _ _ U V : _ ≤ _) x.2⟩ := rfl @[simp] lemma inf_le_left_apply_mk (U V : opens X) (x) (m) : (inf_le_left U V) ⟨x, m⟩ = ⟨x, (@_root_.inf_le_left _ _ U V : _ ≤ _) m⟩ := rfl @[simp] lemma le_supr_apply_mk {ι : Type*} (U : ι → opens X) (i : ι) (x) (m) : (le_supr U i) ⟨x, m⟩ = ⟨x, (_root_.le_supr U i : _) m⟩ := rfl /-- The functor from open sets in `X` to `Top`, realising each open set as a topological space itself. -/ def to_Top (X : Top.{u}) : opens X ⥤ Top := { obj := λ U, ⟨U.val, infer_instance⟩, map := λ U V i, ⟨λ x, ⟨x.1, i.le x.2⟩, (embedding.continuous_iff embedding_subtype_coe).2 continuous_induced_dom⟩ } @[simp] lemma to_Top_map (X : Top.{u}) {U V : opens X} {f : U ⟶ V} {x} {h} : ((to_Top X).map f) ⟨x, h⟩ = ⟨x, f.le h⟩ := rfl /-- The inclusion map from an open subset to the whole space, as a morphism in `Top`. -/ @[simps] def inclusion {X : Top.{u}} (U : opens X) : (to_Top X).obj U ⟶ X := { to_fun := _, continuous_to_fun := continuous_subtype_coe } lemma open_embedding {X : Top.{u}} (U : opens X) : open_embedding (inclusion U) := is_open.open_embedding_subtype_coe U.2 /-- The inclusion of the top open subset (i.e. the whole space) is an isomorphism. -/ def inclusion_top_iso (X : Top.{u}) : (to_Top X).obj ⊤ ≅ X := { hom := inclusion ⊤, inv := ⟨λ x, ⟨x, trivial⟩, continuous_def.2 $ λ U ⟨S, hS, hSU⟩, hSU ▸ hS⟩ } /-- `opens.map f` gives the functor from open sets in Y to open set in X, given by taking preimages under f. -/ def map (f : X ⟶ Y) : opens Y ⥤ opens X := { obj := λ U, ⟨ f ⁻¹' U.val, U.property.preimage f.continuous ⟩, map := λ U V i, ⟨ ⟨ λ x h, i.le h ⟩ ⟩ }. @[simp] lemma map_obj (f : X ⟶ Y) (U) (p) : (map f).obj ⟨U, p⟩ = ⟨f ⁻¹' U, p.preimage f.continuous⟩ := rfl @[simp] lemma map_id_obj (U : opens X) : (map (𝟙 X)).obj U = U := let ⟨_,_⟩ := U in rfl @[simp] lemma map_id_obj' (U) (p) : (map (𝟙 X)).obj ⟨U, p⟩ = ⟨U, p⟩ := rfl @[simp] lemma map_id_obj_unop (U : (opens X)ᵒᵖ) : (map (𝟙 X)).obj (unop U) = unop U := let ⟨_,_⟩ := U.unop in rfl @[simp] lemma op_map_id_obj (U : (opens X)ᵒᵖ) : (map (𝟙 X)).op.obj U = U := by simp /-- The inclusion `U ⟶ (map f).obj ⊤` as a morphism in the category of open sets. -/ def le_map_top (f : X ⟶ Y) (U : opens X) : U ⟶ (map f).obj ⊤ := le_top U @[simp] lemma map_comp_obj (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map (f ≫ g)).obj U = (map f).obj ((map g).obj U) := rfl @[simp] lemma map_comp_obj' (f : X ⟶ Y) (g : Y ⟶ Z) (U) (p) : (map (f ≫ g)).obj ⟨U, p⟩ = (map f).obj ((map g).obj ⟨U, p⟩) := rfl @[simp] lemma map_comp_map (f : X ⟶ Y) (g : Y ⟶ Z) {U V} (i : U ⟶ V) : (map (f ≫ g)).map i = (map f).map ((map g).map i) := rfl @[simp] lemma map_comp_obj_unop (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map (f ≫ g)).obj (unop U) = (map f).obj ((map g).obj (unop U)) := rfl @[simp] lemma op_map_comp_obj (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map (f ≫ g)).op.obj U = (map f).op.obj ((map g).op.obj U) := rfl lemma map_supr (f : X ⟶ Y) {ι : Type*} (U : ι → opens Y) : (map f).obj (supr U) = supr ((map f).obj ∘ U) := begin apply subtype.eq, rw [supr_def, supr_def, map_obj], dsimp, rw set.preimage_Union, refl, end section variable (X) /-- The functor `opens X ⥤ opens X` given by taking preimages under the identity function is naturally isomorphic to the identity functor. -/ @[simps] def map_id : map (𝟙 X) ≅ 𝟭 (opens X) := { hom := { app := λ U, eq_to_hom (map_id_obj U) }, inv := { app := λ U, eq_to_hom (map_id_obj U).symm } } lemma map_id_eq : map (𝟙 X) = 𝟭 (opens X) := by { unfold map, congr, ext, refl, ext } end /-- The natural isomorphism between taking preimages under `f ≫ g`, and the composite of taking preimages under `g`, then preimages under `f`. -/ @[simps] def map_comp (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map g ⋙ map f := { hom := { app := λ U, eq_to_hom (map_comp_obj f g U) }, inv := { app := λ U, eq_to_hom (map_comp_obj f g U).symm } } lemma map_comp_eq (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) = map g ⋙ map f := rfl /-- If two continuous maps `f g : X ⟶ Y` are equal, then the functors `opens Y ⥤ opens X` they induce are isomorphic. -/ -- We could make `f g` implicit here, but it's nice to be able to see when -- they are the identity (often!) def map_iso (f g : X ⟶ Y) (h : f = g) : map f ≅ map g := nat_iso.of_components (λ U, eq_to_iso (congr_fun (congr_arg functor.obj (congr_arg map h)) U) ) (by obviously) lemma map_eq (f g : X ⟶ Y) (h : f = g) : map f = map g := by { unfold map, congr, ext, rw h, rw h, assumption' } @[simp] lemma map_iso_refl (f : X ⟶ Y) (h) : map_iso f f h = iso.refl (map _) := rfl @[simp] lemma map_iso_hom_app (f g : X ⟶ Y) (h : f = g) (U : opens Y) : (map_iso f g h).hom.app U = eq_to_hom (congr_fun (congr_arg functor.obj (congr_arg map h)) U) := rfl @[simp] lemma map_iso_inv_app (f g : X ⟶ Y) (h : f = g) (U : opens Y) : (map_iso f g h).inv.app U = eq_to_hom (congr_fun (congr_arg functor.obj (congr_arg map h.symm)) U) := rfl /-- A homeomorphism of spaces gives an equivalence of categories of open sets. -/ @[simps] def map_map_iso {X Y : Top.{u}} (H : X ≅ Y) : opens Y ≌ opens X := { functor := map H.hom, inverse := map H.inv, unit_iso := nat_iso.of_components (λ U, eq_to_iso (by simp [map, set.preimage_preimage])) (by { intros _ _ _, simp }), counit_iso := nat_iso.of_components (λ U, eq_to_iso (by simp [map, set.preimage_preimage])) (by { intros _ _ _, simp }) } end topological_space.opens /-- An open map `f : X ⟶ Y` induces a functor `opens X ⥤ opens Y`. -/ @[simps] def is_open_map.functor {X Y : Top} {f : X ⟶ Y} (hf : is_open_map f) : opens X ⥤ opens Y := { obj := λ U, ⟨f '' U, hf U U.2⟩, map := λ U V h, ⟨⟨set.image_subset _ h.down.down⟩⟩ } /-- An open map `f : X ⟶ Y` induces an adjunction between `opens X` and `opens Y`. -/ def is_open_map.adjunction {X Y : Top} {f : X ⟶ Y} (hf : is_open_map f) : adjunction hf.functor (topological_space.opens.map f) := adjunction.mk_of_unit_counit { unit := { app := λ U, hom_of_le $ λ x hxU, ⟨x, hxU, rfl⟩ }, counit := { app := λ V, hom_of_le $ λ y ⟨x, hfxV, hxy⟩, hxy ▸ hfxV } } instance is_open_map.functor_full_of_mono {X Y : Top} {f : X ⟶ Y} (hf : is_open_map f) [H : mono f] : full hf.functor := { preimage := λ U V i, hom_of_le (λ x hx, by { obtain ⟨y, hy, eq⟩ := i.le ⟨x, hx, rfl⟩, exact (Top.mono_iff_injective f).mp H eq ▸ hy }) } instance is_open_map.functor_faithful {X Y : Top} {f : X ⟶ Y} (hf : is_open_map f) : faithful hf.functor := {} namespace topological_space.opens open topological_space @[simp] lemma open_embedding_obj_top {X : Top} (U : opens X) : U.open_embedding.is_open_map.functor.obj ⊤ = U := by { ext1, exact set.image_univ.trans subtype.range_coe } @[simp] lemma inclusion_map_eq_top {X : Top} (U : opens X) : (opens.map U.inclusion).obj U = ⊤ := by { ext1, exact subtype.coe_preimage_self _ } @[simp] lemma adjunction_counit_app_self {X : Top} (U : opens X) : U.open_embedding.is_open_map.adjunction.counit.app U = eq_to_hom (by simp) := by ext lemma inclusion_top_functor (X : Top) : (@opens.open_embedding X ⊤).is_open_map.functor = map (inclusion_top_iso X).inv := begin apply functor.hext, intro, abstract obj_eq { ext, exact ⟨ λ ⟨⟨_,_⟩,h,rfl⟩, h, λ h, ⟨⟨x,trivial⟩,h,rfl⟩ ⟩ }, intros, apply subsingleton.helim, congr' 1, iterate 2 {apply inclusion_top_functor.obj_eq}, end end topological_space.opens
7a23d2c8416e262eaddb5eee2401bace258bf506
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/calculus/darboux.lean
988217525e49eaa1380f01d83b6138b1edb2abe4
[ "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,372
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.local_extr /-! # Darboux's theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove that the derivative of a differentiable function on an interval takes all intermediate values. The proof is based on the [Wikipedia](https://en.wikipedia.org/wiki/Darboux%27s_theorem_(analysis)) page about this theorem. -/ open filter set open_locale topology classical variables {a b : ℝ} {f f' : ℝ → ℝ} /-- **Darboux's theorem**: if `a ≤ b` and `f' a < m < f' b`, then `f' c = m` for some `c ∈ (a, b)`. -/ theorem exists_has_deriv_within_at_eq_of_gt_of_lt (hab : a ≤ b) (hf : ∀ x ∈ (Icc a b), has_deriv_within_at f (f' x) (Icc a b) x) {m : ℝ} (hma : f' a < m) (hmb : m < f' b) : m ∈ f' '' Ioo a b := begin rcases hab.eq_or_lt with rfl | hab', { exact (lt_asymm hma hmb).elim }, set g : ℝ → ℝ := λ x, f x - m * x, have hg : ∀ x ∈ Icc a b, has_deriv_within_at g (f' x - m) (Icc a b) x, { intros x hx, simpa using (hf x hx).sub ((has_deriv_within_at_id x _).const_mul m) }, obtain ⟨c, cmem, hc⟩ : ∃ c ∈ Icc a b, is_min_on g (Icc a b) c, from is_compact_Icc.exists_forall_le (nonempty_Icc.2 $ hab) (λ x hx, (hg x hx).continuous_within_at), have cmem' : c ∈ Ioo a b, { rcases cmem.1.eq_or_lt with rfl | hac, -- Show that `c` can't be equal to `a` { refine absurd (sub_nonneg.1 $ nonneg_of_mul_nonneg_right _ (sub_pos.2 hab')) (not_le_of_lt hma), have : b - a ∈ pos_tangent_cone_at (Icc a b) a, from mem_pos_tangent_cone_at_of_segment_subset (segment_eq_Icc hab ▸ subset.refl _), simpa [-sub_nonneg, -continuous_linear_map.map_sub] using hc.localize.has_fderiv_within_at_nonneg (hg a (left_mem_Icc.2 hab)) this }, rcases cmem.2.eq_or_gt with rfl | hcb, -- Show that `c` can't be equal to `b` { refine absurd (sub_nonpos.1 $ nonpos_of_mul_nonneg_right _ (sub_lt_zero.2 hab')) (not_le_of_lt hmb), have : a - b ∈ pos_tangent_cone_at (Icc a b) b, from mem_pos_tangent_cone_at_of_segment_subset (by rw [segment_symm, segment_eq_Icc hab]), simpa [-sub_nonneg, -continuous_linear_map.map_sub] using hc.localize.has_fderiv_within_at_nonneg (hg b (right_mem_Icc.2 hab)) this }, exact ⟨hac, hcb⟩ }, use [c, cmem'], rw [← sub_eq_zero], have : Icc a b ∈ 𝓝 c, by rwa [← mem_interior_iff_mem_nhds, interior_Icc], exact (hc.is_local_min this).has_deriv_at_eq_zero ((hg c cmem).has_deriv_at this) end /-- **Darboux's theorem**: if `a ≤ b` and `f' b < m < f' a`, then `f' c = m` for some `c ∈ (a, b)`. -/ theorem exists_has_deriv_within_at_eq_of_lt_of_gt (hab : a ≤ b) (hf : ∀ x ∈ (Icc a b), has_deriv_within_at f (f' x) (Icc a b) x) {m : ℝ} (hma : m < f' a) (hmb : f' b < m) : m ∈ f' '' Ioo a b := let ⟨c, cmem, hc⟩ := exists_has_deriv_within_at_eq_of_gt_of_lt hab (λ x hx, (hf x hx).neg) (neg_lt_neg hma) (neg_lt_neg hmb) in ⟨c, cmem, neg_injective hc⟩ /-- **Darboux's theorem**: the image of an `ord_connected` set under `f'` is an `ord_connected` set, `has_deriv_within_at` version. -/ theorem set.ord_connected.image_has_deriv_within_at {s : set ℝ} (hs : ord_connected s) (hf : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) : ord_connected (f' '' s) := begin apply ord_connected_of_Ioo, rintros _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ - m ⟨hma, hmb⟩, cases le_total a b with hab hab, { have : Icc a b ⊆ s, from hs.out ha hb, rcases exists_has_deriv_within_at_eq_of_gt_of_lt hab (λ x hx, (hf x $ this hx).mono this) hma hmb with ⟨c, cmem, hc⟩, exact ⟨c, this $ Ioo_subset_Icc_self cmem, hc⟩ }, { have : Icc b a ⊆ s, from hs.out hb ha, rcases exists_has_deriv_within_at_eq_of_lt_of_gt hab (λ x hx, (hf x $ this hx).mono this) hmb hma with ⟨c, cmem, hc⟩, exact ⟨c, this $ Ioo_subset_Icc_self cmem, hc⟩ } end /-- **Darboux's theorem**: the image of an `ord_connected` set under `f'` is an `ord_connected` set, `deriv_within` version. -/ theorem set.ord_connected.image_deriv_within {s : set ℝ} (hs : ord_connected s) (hf : differentiable_on ℝ f s) : ord_connected (deriv_within f s '' s) := hs.image_has_deriv_within_at $ λ x hx, (hf x hx).has_deriv_within_at /-- **Darboux's theorem**: the image of an `ord_connected` set under `f'` is an `ord_connected` set, `deriv` version. -/ theorem set.ord_connected.image_deriv {s : set ℝ} (hs : ord_connected s) (hf : ∀ x ∈ s, differentiable_at ℝ f x) : ord_connected (deriv f '' s) := hs.image_has_deriv_within_at $ λ x hx, (hf x hx).has_deriv_at.has_deriv_within_at /-- **Darboux's theorem**: the image of a convex set under `f'` is a convex set, `has_deriv_within_at` version. -/ theorem convex.image_has_deriv_within_at {s : set ℝ} (hs : convex ℝ s) (hf : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) : convex ℝ (f' '' s) := (hs.ord_connected.image_has_deriv_within_at hf).convex /-- **Darboux's theorem**: the image of a convex set under `f'` is a convex set, `deriv_within` version. -/ theorem convex.image_deriv_within {s : set ℝ} (hs : convex ℝ s) (hf : differentiable_on ℝ f s) : convex ℝ (deriv_within f s '' s) := (hs.ord_connected.image_deriv_within hf).convex /-- **Darboux's theorem**: the image of a convex set under `f'` is a convex set, `deriv` version. -/ theorem convex.image_deriv {s : set ℝ} (hs : convex ℝ s) (hf : ∀ x ∈ s, differentiable_at ℝ f x) : convex ℝ (deriv f '' s) := (hs.ord_connected.image_deriv hf).convex /-- **Darboux's theorem**: if `a ≤ b` and `f' a ≤ m ≤ f' b`, then `f' c = m` for some `c ∈ [a, b]`. -/ theorem exists_has_deriv_within_at_eq_of_ge_of_le (hab : a ≤ b) (hf : ∀ x ∈ (Icc a b), has_deriv_within_at f (f' x) (Icc a b) x) {m : ℝ} (hma : f' a ≤ m) (hmb : m ≤ f' b) : m ∈ f' '' Icc a b := (ord_connected_Icc.image_has_deriv_within_at hf).out (mem_image_of_mem _ (left_mem_Icc.2 hab)) (mem_image_of_mem _ (right_mem_Icc.2 hab)) ⟨hma, hmb⟩ /-- **Darboux's theorem**: if `a ≤ b` and `f' b ≤ m ≤ f' a`, then `f' c = m` for some `c ∈ [a, b]`. -/ theorem exists_has_deriv_within_at_eq_of_le_of_ge (hab : a ≤ b) (hf : ∀ x ∈ (Icc a b), has_deriv_within_at f (f' x) (Icc a b) x) {m : ℝ} (hma : f' a ≤ m) (hmb : m ≤ f' b) : m ∈ f' '' Icc a b := (ord_connected_Icc.image_has_deriv_within_at hf).out (mem_image_of_mem _ (left_mem_Icc.2 hab)) (mem_image_of_mem _ (right_mem_Icc.2 hab)) ⟨hma, hmb⟩ /-- If the derivative of a function is never equal to `m`, then either it is always greater than `m`, or it is always less than `m`. -/ theorem has_deriv_within_at_forall_lt_or_forall_gt_of_forall_ne {s : set ℝ} (hs : convex ℝ s) (hf : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) {m : ℝ} (hf' : ∀ x ∈ s, f' x ≠ m) : (∀ x ∈ s, f' x < m) ∨ (∀ x ∈ s, m < f' x) := begin contrapose! hf', rcases hf' with ⟨⟨b, hb, hmb⟩, ⟨a, ha, hma⟩⟩, exact (hs.ord_connected.image_has_deriv_within_at hf).out (mem_image_of_mem f' ha) (mem_image_of_mem f' hb) ⟨hma, hmb⟩ end
0e6e8d9b1521ba19b04fe4809dbecfa83439e191
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/stage0/src/Init/Core.lean
41debea0e1c35d19d505553fb7e0900d7eaa22fd
[ "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
35,730
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 universe u v w def inline {α : Sort u} (a : α) : α := a @[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := fun b a => f a b /-- 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 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⟩ -- 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 () @[inline] protected def Thunk.map (f : α → β) (x : Thunk α) : Thunk β := ⟨fun _ => f x.get⟩ @[inline] protected def Thunk.bind (x : Thunk α) (f : α → Thunk β) : Thunk β := ⟨fun _ => (f x.get).get⟩ abbrev Eq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} {b : α} (h : a = b) (m : motive a) : motive b := Eq.ndrec m h structure Iff (a b : Prop) : Prop where intro :: (mp : a → b) (mpr : b → a) infix:20 " <-> " => Iff infix:20 " ↔ " => Iff inductive Sum (α : Type u) (β : Type v) where | inl (val : α) : Sum α β | inr (val : β) : Sum α β inductive PSum (α : Sort u) (β : Sort v) where | inl (val : α) : PSum α β | inr (val : β) : PSum α β structure Sigma {α : Type u} (β : α → Type v) where fst : α snd : β fst attribute [unbox] Sigma structure PSigma {α : Sort u} (β : α → Sort v) where fst : α snd : β fst inductive Exists {α : Sort u} (p : α → Prop) : Prop where | intro (w : α) (h : p w) : Exists p /- Auxiliary type used to compile `for x in xs` notation. -/ inductive ForInStep (α : Type u) where | done : α → ForInStep α | yield : α → ForInStep α class ForIn (m : Type u₁ → Type u₂) (ρ : Type u) (α : outParam (Type v)) where forIn {β} [Monad m] (x : ρ) (b : β) (f : α → β → m (ForInStep β)) : m β export ForIn (forIn) /- Auxiliary type used to compile `do` notation. -/ inductive DoResultPRBC (α β σ : Type u) where | «pure» : α → σ → DoResultPRBC α β σ | «return» : β → σ → DoResultPRBC α β σ | «break» : σ → DoResultPRBC α β σ | «continue» : σ → DoResultPRBC α β σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultPR (α β σ : Type u) where | «pure» : α → σ → DoResultPR α β σ | «return» : β → σ → DoResultPR α β σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultBC (σ : Type u) where | «break» : σ → DoResultBC σ | «continue» : σ → DoResultBC σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultSBC (α σ : Type u) where | «pureReturn» : α → σ → DoResultSBC α σ | «break» : σ → DoResultSBC α σ | «continue» : σ → DoResultSBC α σ class HasEquiv (α : Sort u) where Equiv : α → α → Sort v infix:50 " ≈ " => HasEquiv.Equiv class EmptyCollection (α : Type u) where emptyCollection : α notation "{" "}" => EmptyCollection.emptyCollection notation "∅" => EmptyCollection.emptyCollection /- Remark: tasks have an efficient implementation in the runtime. -/ structure Task (α : Type u) : Type u where pure :: (get : α) deriving Inhabited attribute [extern "lean_task_pure"] Task.pure attribute [extern "lean_task_get_own"] Task.get namespace Task /-- Task priority. Tasks with higher priority will always be scheduled before ones with lower priority. -/ abbrev Priority := Nat def Priority.default : Priority := 0 -- 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 @[noinline, extern "lean_task_spawn"] protected def spawn {α : Type u} (fn : Unit → α) (prio := Priority.default) : Task α := ⟨fn ()⟩ @[noinline, extern "lean_task_map"] protected def map {α : Type u} {β : Type v} (f : α → β) (x : Task α) (prio := Priority.default) : Task β := ⟨f x.get⟩ @[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 /- Some type that is not a scalar value in our runtime. -/ structure NonScalar where val : Nat /- Some type that is not a scalar value in our runtime and is universe polymorphic. -/ inductive PNonScalar : Type u where | 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 -/ @[extern c inline "#1 || #2"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂ @[extern c inline "#1 && #2"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂ @[inline] def bne {α : Type u} [BEq α] (a b : α) : Bool := !(a == b) infix:50 " != " => bne /- Logical connectives an equality -/ def implies (a b : Prop) := a → b theorem implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := fun hp => h₂ (h₁ hp) 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 @[macroInline] def Eq.mp {α β : Sort u} (h : α = β) (a : α) : β := h ▸ a @[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 @[reducible] def Ne {α : Sort u} (a b : α) := ¬(a = b) 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 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 := @HEq.rec α a (fun b _ => motive b) m β b h 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 := @HEq.rec α a (fun b _ => motive b) m β b h 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 := HEq.ndrecOn (motive := fun x => HEq x a) h (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₂ def type_eq_of_heq (h : HEq a b) : α = β := HEq.ndrecOn (motive := @fun (x : Sort u) _ => α = x) h (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 /- Exists -/ theorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : Exists (fun x => p x)) (h₂ : ∀ (a : α), p a → b) : b := h₂ h₁.1 h₁.2 /- Decidable -/ theorem decide_true_eq_true (h : Decidable True) : @decide True h = true := match h with | isTrue h => rfl | isFalse h => False.elim <| h ⟨⟩ theorem decide_false_eq_false (h : Decidable False) : @decide False h = false := match h with | isFalse h => 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 (s := d) h theorem ofBoolUsing_eq_true {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p := of_decide_eq_true (s := d) h theorem ofBoolUsing_eq_false {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : ¬ p := of_decide_eq_false (s := d) h instance : Decidable True := isTrue trivial instance : Decidable False := isFalse not_false namespace Decidable variable {p q : Prop} @[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 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} @[inline] def decidableOfDecidableOfIff (hp : 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 @[inline] def decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q := h ▸ hp end @[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (p → q) := if hp : p then if hq : q then isTrue (fun h => 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 hc => 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 hnc => 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 hc => 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 hnc => 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 h => t) (fun h => e) = ite c t e := match h with | isTrue hc => rfl | isFalse hnc => 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 hc => dT | isFalse hc => 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 definitions for generating compact `noConfusion` for enumeration types -/ abbrev noConfusionTypeEnum {α : Sort u} {β : Sort v} [DecidableEq β] (f : α → β) (P : Sort w) (x y : α) : Sort w := if f x = f y then P → P else P abbrev noConfusionEnum {α : Sort u} {β : Sort v} [DecidableEq β] (f : α → β) {P : Sort w} {x y : α} (h : x = y) : noConfusionTypeEnum f P x y := if h' : f x = f y then cast (@if_pos _ _ h' _ (P → P) (P)).symm (fun (h : P) => h) else False.elim (h' (congrArg f h)) /- Inhabited -/ instance : Inhabited Prop where default := True deriving instance Inhabited for NonScalar, PNonScalar, True, ForInStep class inductive Nonempty (α : Sort u) : Prop where | intro (val : α) : Nonempty α protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p := h₂ h₁.1 instance {α : Sort u} [Inhabited α] : Nonempty α := ⟨arbitrary⟩ theorem nonempty_of_exists {α : Sort u} {p : α → Prop} : Exists (fun x => p x) → Nonempty α | ⟨w, h⟩ => ⟨w⟩ /- Subsingleton -/ class Subsingleton (α : Sort u) : Prop where intro :: allEq : (a b : α) → a = b protected def Subsingleton.elim {α : Sort u} [h : Subsingleton α] : (a b : α) → a = b := h.allEq protected def 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 t₂ => rfl | isFalse f₂ => absurd t₁ f₂ | isFalse f₁ => fun | isTrue t₂ => absurd t₂ f₁ | isFalse f₂ => 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 (Decidable.casesOn (motive := fun _ => Sort u) h h₂ h₁) := match h with | isTrue h => h₃ h | isFalse h => h₄ h structure Equivalence {α : Sort u} (r : α → α → Prop) : Prop where refl : ∀ x, r x x symm : ∀ {x y}, r x y → r y x trans : ∀ {x y z}, r x y → r y z → r x z def emptyRelation {α : Sort u} (a₁ a₂ : α) : Prop := False def Subrelation {α : Sort u} (q r : α → α → Prop) := ∀ {x y}, q x y → r x y def InvImage {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) : α → α → Prop := fun a₁ a₂ => r (f a₁) (f a₂) inductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop where | base : ∀ a b, r a b → TC r a b | trans : ∀ a b c, TC r a b → TC r b c → TC r a c /- Subtype -/ namespace Subtype def 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 | ⟨x, h1⟩, ⟨_, _⟩, 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 [h : Inhabited α] : Inhabited (Sum α β) where default := Sum.inl arbitrary instance Sum.inhabitedRight [h : Inhabited β] : Inhabited (Sum α β) where default := Sum.inr arbitrary 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 a, Sum.inl b => isFalse fun h => Sum.noConfusion h | Sum.inl a, Sum.inr b => isFalse fun h => Sum.noConfusion h end /- Product -/ instance [Inhabited α] [Inhabited β] : Inhabited (α × β) where default := (arbitrary, arbitrary) 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₁' e₂' => absurd e₂' n₂ | isFalse n₁ => isFalse fun h => Prod.noConfusion h fun e₁' e₂' => absurd e₁' n₁ instance [BEq α] [BEq β] : BEq (α × β) where beq := fun (a₁, b₁) (a₂, b₂) => a₁ == a₂ && b₁ == b₂ instance [LT α] [LT β] : LT (α × β) where lt s t := s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2) instance prodHasDecidableLt [LT α] [LT β] [DecidableEq α] [DecidableEq β] [(a b : α) → Decidable (a < b)] [(a b : β) → Decidable (a < b)] : (s t : α × β) → Decidable (s < t) := fun t s => inferInstanceAs (Decidable (_ ∨ _)) theorem Prod.lt_def [LT α] [LT β] (s t : α × β) : (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 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 -/ class Setoid (α : Sort u) where r : α → α → Prop iseqv {} : Equivalence r instance {α : Sort u} [Setoid α] : HasEquiv α := ⟨Setoid.r⟩ namespace Setoid variable {α : Sort u} [Setoid α] theorem refl (a : α) : a ≈ a := (Setoid.iseqv α).refl a theorem symm {a b : α} (hab : a ≈ b) : b ≈ a := (Setoid.iseqv α).symm hab theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c := (Setoid.iseqv α).trans hab hbc end Setoid /- Propositional extensionality -/ 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₂ 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 /- 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 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 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 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) := Quot.inductionOn (motive := fun q => Exists (fun a => (Quot.mk r a) = q)) q (fun a => ⟨a, rfl⟩) section variable {α : Sort u} variable {r : α → α → Prop} variable {motive : Quot r → Sort v} @[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 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) 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 := Quot.rec f h q 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 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 def Quotient {α : Sort u} (s : Setoid α) := @Quot α Setoid.r namespace Quotient @[inline] protected def mk {α : Sort u} [s : Setoid α] (a : α) : Quotient s := Quot.mk Setoid.r a def sound {α : Sort u} [s : Setoid α] {a b : α} : a ≈ b → Quotient.mk a = Quotient.mk b := Quot.sound 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 a)) → (q : Quot Setoid.r) → motive q := Quot.ind 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 protected theorem inductionOn {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop} (q : Quotient s) (h : (a : α) → motive (Quotient.mk a)) : motive q := Quot.inductionOn q h theorem exists_rep {α : Sort u} [s : Setoid α] (q : Quotient s) : Exists (fun (a : α) => Quotient.mk a = q) := Quot.exists_rep q section variable {α : Sort u} variable [s : Setoid α] variable {motive : Quotient s → Sort v} @[inline] protected def rec (f : (a : α) → motive (Quotient.mk 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 protected abbrev recOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b) : motive q := Quot.recOn q f h protected abbrev recOnSubsingleton [h : (a : α) → Subsingleton (motive (Quotient.mk a))] (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) : motive q := Quot.recOnSubsingleton (h := h) q f protected abbrev hrecOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk 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 β] 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 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₂ protected theorem ind₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h protected theorem inductionOn₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h 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 a) (Quotient.mk b) (Quotient.mk 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₁ a₂ b₁ b₂ 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 := Quot.inductionOn (motive := fun q => rel q q) q (fun a => Setoid.refl a) 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 a = Quotient.mk 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 β] protected abbrev recOnSubsingleton₂ {motive : Quotient s₁ → Quotient s₂ → Sort uC} [s : (a : α) → (b : β) → Subsingleton (motive (Quotient.mk a) (Quotient.mk b))] (q₁ : Quotient s₁) (q₂ : Quotient s₂) (g : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk 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₂ (motive := fun a b => Decidable (a = b)) 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 -/ namespace Function variable {α : Sort u} {β : α → Sort v} protected def Equiv (f₁ f₂ : ∀ (x : α), β x) : Prop := ∀ x, f₁ x = f₂ x protected theorem Equiv.refl (f : ∀ (x : α), β x) : Function.Equiv f f := fun x => rfl protected theorem Equiv.symm {f₁ f₂ : ∀ (x : α), β x} : Function.Equiv f₁ f₂ → Function.Equiv f₂ f₁ := fun h x => Eq.symm (h x) protected theorem Equiv.trans {f₁ f₂ f₃ : ∀ (x : α), β x} : Function.Equiv f₁ f₂ → Function.Equiv f₂ f₃ → Function.Equiv f₁ f₃ := fun h₁ h₂ x => Eq.trans (h₁ x) (h₂ x) protected theorem Equiv.isEquivalence (α : Sort u) (β : α → Sort v) : Equivalence (@Function.Equiv α β) := { refl := Equiv.refl symm := Equiv.symm trans := Equiv.trans } end Function section open Quotient variable {α : Sort u} {β : α → Sort v} @[instance] private def funSetoid (α : Sort u) (β : α → Sort v) : Setoid (∀ (x : α), β x) := Setoid.mk (@Function.Equiv α β) (Function.Equiv.isEquivalence α β) private def extfunApp (f : Quotient <| funSetoid α β) (x : α) : β x := Quot.liftOn f (fun (f : ∀ (x : α), β x) => f x) (fun f₁ f₂ h => h x) theorem funext {f₁ f₂ : ∀ (x : α), β x} (h : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by show extfunApp (Quotient.mk f₁) = extfunApp (Quotient.mk f₂) apply congrArg apply Quotient.sound exact h end instance {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (∀ a, β a) where allEq f₁ f₂ := funext (fun a => Subsingleton.elim (f₁ a) (f₂ a)) /- Squash -/ def Squash (α : Type u) := Quot (fun (a b : α) => True) 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 @[inline] def Squash.lift {α β} [Subsingleton β] (s : Squash α) (f : α → β) : β := Quot.lift f (fun a b _ => 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 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 developement 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 developement 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. -/ constant 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). -/ constant reduceNat (n : Nat) : Nat := n axiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b axiom ofReduceNat (a b : Nat) (h : reduceNat a = b) : a = b end Lean
e3962b144cf5120d45604189de081579da5619c0
fca07070bb19b108b71d0e4b2036ba2c4813dc1e
/localdep/Local.lean
f4d991086aa364e3c02300513f252160c69df8d3
[]
no_license
rwbarton/lean4-test2
72259888aa87936c8458c3c416348a0d75b29e34
391d0c579ffca9b8f0ca23b099e3f4b5eee6ce15
refs/heads/master
1,677,432,125,878
1,612,365,361,000
1,612,365,361,000
335,665,877
1
0
null
null
null
null
UTF-8
Lean
false
false
51
lean
def twice (f : α → α) (x : α) : α := f (f x)
73b081cd5bb419e1549282653743f0faf83121eb
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/IR/Sorry.lean
8417dc145b2c31d066f8c0ce7e27ee0ea6dd2a8f
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,223
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.IR.CompilerM namespace Lean.IR namespace Sorry structure State where localSorryMap : NameMap Name := {} modified : Bool := false abbrev M := StateT State CompilerM def visitExpr : Expr → ExceptT Name M Unit | Expr.fap f _ => getSorryDepFor? f | Expr.pap f _ => getSorryDepFor? f | _ => return () where getSorryDepFor? (f : Name) : ExceptT Name M Unit := do let found (g : Name) := if g == ``sorryAx then throw f else throw g if f == ``sorryAx then throw f else if let some g := (← get).localSorryMap.find? f then found g else match (← findDecl f) with | some (.fdecl (info := { sorryDep? := some g, .. }) ..) => found g | _ => return () partial def visitFndBody (b : FnBody) : ExceptT Name M Unit := do match b with | .vdecl _ _ v b => visitExpr v; visitFndBody b | .jdecl _ _ v b => visitFndBody v; visitFndBody b | .case _ _ _ alts => alts.forM fun alt => visitFndBody alt.body | _ => unless b.isTerminal do let (_, b) := b.split visitFndBody b def visitDecl (d : Decl) : M Unit := do match d with | .fdecl (f := f) (body := b) .. => match (← get).localSorryMap.find? f with | some _ => return () | none => match (← visitFndBody b |>.run) with | .ok _ => return () | .error g => modify fun s => { localSorryMap := s.localSorryMap.insert f g modified := true } | _ => return () partial def collect (decls : Array Decl) : M Unit := do modify fun s => { s with modified := false } decls.forM visitDecl if (← get).modified then collect decls end Sorry def updateSorryDep (decls : Array Decl) : CompilerM (Array Decl) := do let (_, s) ← Sorry.collect decls |>.run {} return decls.map fun decl => match decl with | Decl.fdecl f xs t b _ => match s.localSorryMap.find? f with | some g => Decl.fdecl f xs t b { sorryDep? := some g } | _ => decl | _ => decl end Lean.IR
4a24c74a512d0c18342ae0fe8de95ce43128bfe8
7da5ceac20aaab989eeb795a4be9639982e7b35a
/src/category_theory/group_object.lean
3a5202d8ce93acf1bbe4bf6051a833ec67bf6e73
[ "MIT" ]
permissive
formalabstracts/formalabstracts
46c2f1b3a172e62ca6ffeb46fbbdf1705718af49
b0173da1af45421239d44492eeecd54bf65ee0f6
refs/heads/master
1,606,896,370,374
1,572,988,776,000
1,572,988,776,000
96,763,004
165
28
null
1,555,709,319,000
1,499,680,948,000
Lean
UTF-8
Lean
false
false
5,610
lean
-- Copyright (c) 2019 Jesse Han. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Jesse Han import .finite_limits open category_theory category_theory.limits category_theory.limits.binary_product category_theory.limits.finite_limits universes v u local infix ` × `:60 := binary_product local infix ` ×.map `:90 := binary_product.map local infix ` ×.iso `:90 := binary_product.iso /-- A group object in a category with finite products is an object `G` equipped with morphisms `μ : G × G ⟶ G`, `e : 1 ⟶ G` and `i : G ⟶ G` such that the axioms for a group hold (which is expressed in terms of commuting diagrams) -/ structure group_object (C : Type u) [𝓒 : category.{v+1} C] [H : has_binary_products.{v} C] [H' : has_terminal_object.{v} C] : Type (max u v) := (obj : C) (mul : obj × obj ⟶ obj) (mul_assoc : assoc_hom ≫ 𝟙 obj ×.map mul ≫ mul = mul ×.map 𝟙 obj ≫ mul) (one : term ⟶ obj) (one_mul : 𝟙 obj = one_mul_inv ≫ one ×.map 𝟙 obj ≫ mul) (mul_one : 𝟙 obj = mul_one_inv ≫ 𝟙 obj ×.map one ≫ mul) (inv : obj ⟶ obj) (mul_left_inv : terminal_map _ ≫ one = map_to_product.mk inv (𝟙 obj) ≫ mul) /-- A morphism between group objects is a morphism between the objects that commute with multiplication -/ structure group_hom {C : Type u} [category.{v+1} C] [has_binary_products C] [has_terminal_object C] (G G' : group_object C) : Type (max u v) := (map : G.obj ⟶ G'.obj) (map_mul : G.mul ≫ map = map ×.map map ≫ G'.mul) /- An action of a group object on any object in the category -/ structure group_action {C : Type u} [category.{v+1} C] [has_binary_products C] [has_terminal_object C] (G : group_object C) (X : C) : Type (max u v) := (map : G.obj × X ⟶ X) (map_one : map_to_product.mk (terminal_map X ≫ G.one) (𝟙 X) ≫ map = 𝟙 X) (map_mul : G.mul ×.map 𝟙 X ≫ map = assoc_hom ≫ 𝟙 G.obj ×.map map ≫ map) variables {C : Type u} [𝓒 : category.{v+1} C] [p𝓒 : has_binary_products.{v} C] [t𝓒 : has_terminal_object.{v} C] {X Y : C} {G G' G₁ G₂ G₃ H : group_object C} include 𝓒 p𝓒 t𝓒 namespace group_hom /-- The identity morphism between group objects -/ def id (G : group_object C) : group_hom G G := ⟨𝟙 G.obj, omitted⟩ /-- Composition of morphisms between group objects -/ def comp (f : group_hom G₁ G₂) (g : group_hom G₂ G₃) : group_hom G₁ G₃ := ⟨f.map ≫ g.map, omitted⟩ lemma map_one (f : group_hom G G') : G.one ≫ f.map = G'.one := omitted lemma map_inv (f : group_hom G G') : G.inv ≫ f.map = f.map ≫ G'.inv := omitted end group_hom namespace group_object /-- The category of group objects -/ instance category : category (group_object C) := { hom := group_hom, id := group_hom.id, comp := λ X Y Z, group_hom.comp } /-- The terminal group object -/ def terminal_group : group_object C := { obj := term, mul := terminal_map _, mul_assoc := terminal_map_eq _ _, one := terminal_map _, one_mul := terminal_map_eq _ _, mul_one := terminal_map_eq _ _, inv := terminal_map _, mul_left_inv := terminal_map_eq _ _ } /-- The morphism into the terminal group object -/ def hom_terminal_group (G : group_object C) : G ⟶ terminal_group := by exact ⟨terminal_map G.obj, omitted⟩ /-- The category of group objects has a terminal object -/ instance has_terminal_object : has_terminal_object (group_object C) := has_terminal_object.mk terminal_group hom_terminal_group omitted /-- The binary product of group objects -/ protected def prod (G G' : group_object C) : group_object C := { obj := G.obj × G'.obj, mul := product_assoc4.hom ≫ G.mul ×.map G'.mul, mul_assoc := omitted, one := map_to_product.mk G.one G'.one, one_mul := omitted, mul_one := omitted, inv := G.inv ×.map G'.inv, mul_left_inv := omitted } protected def pr1 : G.prod G' ⟶ G := by exact ⟨π₁, omitted⟩ protected def pr2 : G.prod G' ⟶ G' := by exact ⟨π₂, omitted⟩ protected def lift (f : H ⟶ G) (g : H ⟶ G') : H ⟶ G.prod G' := by exact ⟨map_to_product.mk f.map g.map, omitted⟩ /-- The category of group objects has binary products -/ instance has_binary_products : has_binary_products (group_object C) := begin apply has_binary_products.mk group_object.prod (λ G G', group_object.pr1) (λ G G', group_object.pr2) (λ G G' H, group_object.lift), omit_proofs end /-- Every group object has a point, i.e. a morphism from the terminal object -/ def one_hom (G : group_object C) : term ⟶ G := by exact ⟨G.one, omitted⟩ omit 𝓒 p𝓒 t𝓒 /-- A group object is abelian if multiplication is commutative -/ -- todo: maybe this should be a class class is_abelian {C : Type u} [𝓒 : category.{v+1} C] [H : has_binary_products.{v} C] [H' : has_terminal_object.{v} C] (G : group_object C) : Prop := (comm : product_comm.hom ≫ G.mul = G.mul) include 𝓒 p𝓒 t𝓒 /-- Multiplication is a group homomorphism if `G` is abelian -/ def mul_hom (G : group_object C) [G.is_abelian] : G × G ⟶ G := by exact ⟨G.mul, omitted⟩ /-- Inversion is a group homomorphism if `G` is abelian -/ def inv_hom (G : group_object C) [G.is_abelian] : G ⟶ G := by exact ⟨G.inv, omitted⟩ instance comm_group_hom (G G' : group_object C) [G'.is_abelian] : comm_group (G ⟶ G') := { mul := λ f g, map_to_product.mk f g ≫ G'.mul_hom, mul_assoc := omitted, one := terminal_map G ≫ one_hom G', one_mul := omitted, mul_one := omitted, inv := λ f, f ≫ inv_hom G', mul_left_inv := omitted, mul_comm := omitted } end group_object
92cf895f8d8064239d1e1ceef965702d04ee343e
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/limits/shapes/pullbacks.lean
07a1809e1fc44b57d180a30b1b6b666a63ace4a4
[ "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
22,833
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel, Bhavik Mehta -/ import category_theory.limits.shapes.finite_limits import category_theory.limits.shapes.wide_pullbacks import category_theory.limits.shapes.binary_products import category_theory.sparse /-! # Pullbacks We define a category `walking_cospan` (resp. `walking_span`), which is the index category for the given data for a pullback (resp. pushout) diagram. Convenience methods `cospan f g` and `span f g` construct functors from the walking (co)span, hitting the given morphisms. We define `pullback f g` and `pushout f g` as limits and colimits of such functors. Typeclasses `has_pullbacks` and `has_pushouts` assert the existence of (co)limits shaped as walking (co)spans. -/ open category_theory namespace category_theory.limits universes v u local attribute [tidy] tactic.case_bash /-- The type of objects for the diagram indexing a pullback, defined as a special case of `wide_pullback_shape`. -/ abbreviation walking_cospan : Type v := wide_pullback_shape walking_pair /-- The left point of the walking cospan. -/ abbreviation walking_cospan.left : walking_cospan := some walking_pair.left /-- The right point of the walking cospan. -/ abbreviation walking_cospan.right : walking_cospan := some walking_pair.right /-- The central point of the walking cospan. -/ abbreviation walking_cospan.one : walking_cospan := none /-- The type of objects for the diagram indexing a pushout, defined as a special case of `wide_pushout_shape`. -/ abbreviation walking_span : Type v := wide_pushout_shape walking_pair /-- The left point of the walking span. -/ abbreviation walking_span.left : walking_span := some walking_pair.left /-- The right point of the walking span. -/ abbreviation walking_span.right : walking_span := some walking_pair.right /-- The central point of the walking span. -/ abbreviation walking_span.zero : walking_span := none namespace walking_cospan /-- The type of arrows for the diagram indexing a pullback. -/ abbreviation hom : walking_cospan → walking_cospan → Type v := wide_pullback_shape.hom /-- The left arrow of the walking cospan. -/ abbreviation hom.inl : left ⟶ one := wide_pullback_shape.hom.term _ /-- The right arrow of the walking cospan. -/ abbreviation hom.inr : right ⟶ one := wide_pullback_shape.hom.term _ /-- The identity arrows of the walking cospan. -/ abbreviation hom.id (X : walking_cospan) : X ⟶ X := wide_pullback_shape.hom.id X instance (X Y : walking_cospan) : subsingleton (X ⟶ Y) := by tidy end walking_cospan namespace walking_span /-- The type of arrows for the diagram indexing a pushout. -/ abbreviation hom : walking_span → walking_span → Type v := wide_pushout_shape.hom /-- The left arrow of the walking span. -/ abbreviation hom.fst : zero ⟶ left := wide_pushout_shape.hom.init _ /-- The right arrow of the walking span. -/ abbreviation hom.snd : zero ⟶ right := wide_pushout_shape.hom.init _ /-- The identity arrows of the walking span. -/ abbreviation hom.id (X : walking_span) : X ⟶ X := wide_pushout_shape.hom.id X instance (X Y : walking_span) : subsingleton (X ⟶ Y) := by tidy end walking_span open walking_span.hom walking_cospan.hom wide_pullback_shape.hom wide_pushout_shape.hom variables {C : Type u} [category.{v} C] /-- `cospan f g` is the functor from the walking cospan hitting `f` and `g`. -/ def cospan {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : walking_cospan.{v} ⥤ C := wide_pullback_shape.wide_cospan Z (λ j, walking_pair.cases_on j X Y) (λ j, walking_pair.cases_on j f g) /-- `span f g` is the functor from the walking span hitting `f` and `g`. -/ def span {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : walking_span.{v} ⥤ C := wide_pushout_shape.wide_span X (λ j, walking_pair.cases_on j Y Z) (λ j, walking_pair.cases_on j f g) @[simp] lemma cospan_left {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.left = X := rfl @[simp] lemma span_left {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.left = Y := rfl @[simp] lemma cospan_right {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.right = Y := rfl @[simp] lemma span_right {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.right = Z := rfl @[simp] lemma cospan_one {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.one = Z := rfl @[simp] lemma span_zero {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.zero = X := rfl @[simp] lemma cospan_map_inl {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inl = f := rfl @[simp] lemma span_map_fst {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.fst = f := rfl @[simp] lemma cospan_map_inr {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inr = g := rfl @[simp] lemma span_map_snd {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.snd = g := rfl lemma cospan_map_id {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (w : walking_cospan) : (cospan f g).map (walking_cospan.hom.id w) = 𝟙 _ := rfl lemma span_map_id {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) (w : walking_span) : (span f g).map (walking_span.hom.id w) = 𝟙 _ := rfl /-- Every diagram indexing an pullback is naturally isomorphic (actually, equal) to a `cospan` -/ def diagram_iso_cospan (F : walking_cospan ⥤ C) : F ≅ cospan (F.map inl) (F.map inr) := nat_iso.of_components (λ j, eq_to_iso (by tidy)) (by tidy) /-- Every diagram indexing a pushout is naturally isomorphic (actually, equal) to a `span` -/ def diagram_iso_span (F : walking_span ⥤ C) : F ≅ span (F.map fst) (F.map snd) := nat_iso.of_components (λ j, eq_to_iso (by tidy)) (by tidy) variables {X Y Z : C} /-- A pullback cone is just a cone on the cospan formed by two morphisms `f : X ⟶ Z` and `g : Y ⟶ Z`.-/ abbreviation pullback_cone (f : X ⟶ Z) (g : Y ⟶ Z) := cone (cospan f g) namespace pullback_cone variables {f : X ⟶ Z} {g : Y ⟶ Z} /-- The first projection of a pullback cone. -/ abbreviation fst (t : pullback_cone f g) : t.X ⟶ X := t.π.app walking_cospan.left /-- The second projection of a pullback cone. -/ abbreviation snd (t : pullback_cone f g) : t.X ⟶ Y := t.π.app walking_cospan.right /-- A pullback cone on `f` and `g` is determined by morphisms `fst : W ⟶ X` and `snd : W ⟶ Y` such that `fst ≫ f = snd ≫ g`. -/ @[simps] def mk {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : pullback_cone f g := { X := W, π := { app := λ j, option.cases_on j (fst ≫ f) (λ j', walking_pair.cases_on j' fst snd) } } @[simp] lemma mk_π_app_left {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.left = fst := rfl @[simp] lemma mk_π_app_right {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.right = snd := rfl @[simp] lemma mk_π_app_one {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.one = fst ≫ f := rfl @[reassoc] lemma condition (t : pullback_cone f g) : fst t ≫ f = snd t ≫ g := (t.w inl).trans (t.w inr).symm /-- To check whether a morphism is equalized by the maps of a pullback cone, it suffices to check it for `fst t` and `snd t` -/ lemma equalizer_ext (t : pullback_cone f g) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : ∀ (j : walking_cospan), k ≫ t.π.app j = l ≫ t.π.app j | (some walking_pair.left) := h₀ | (some walking_pair.right) := h₁ | none := by rw [← t.w inl, reassoc_of h₀] lemma is_limit.hom_ext {t : pullback_cone f g} (ht : is_limit t) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : k = l := ht.hom_ext $ equalizer_ext _ h₀ h₁ /-- If `t` is a limit pullback cone over `f` and `g` and `h : W ⟶ X` and `k : W ⟶ Y` are such that `h ≫ f = k ≫ g`, then we have `l : W ⟶ t.X` satisfying `l ≫ fst t = h` and `l ≫ snd t = k`. -/ def is_limit.lift' {t : pullback_cone f g} (ht : is_limit t) {W : C} (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ t.X // l ≫ fst t = h ∧ l ≫ snd t = k} := ⟨ht.lift $ pullback_cone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a slightly more convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def is_limit.mk (t : pullback_cone f g) (lift : Π (s : cone (cospan f g)), s.X ⟶ t.X) (fac_left : ∀ (s : cone (cospan f g)), lift s ≫ t.π.app walking_cospan.left = s.π.app walking_cospan.left) (fac_right : ∀ (s : cone (cospan f g)), lift s ≫ t.π.app walking_cospan.right = s.π.app walking_cospan.right) (uniq : ∀ (s : cone (cospan f g)) (m : s.X ⟶ t.X) (w : ∀ j : walking_cospan, m ≫ t.π.app j = s.π.app j), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, option.cases_on j (by { simp [← s.w inl, ← t.w inl, ← fac_left s] } ) (λ j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } end pullback_cone /-- A pushout cocone is just a cocone on the span formed by two morphisms `f : X ⟶ Y` and `g : X ⟶ Z`.-/ abbreviation pushout_cocone (f : X ⟶ Y) (g : X ⟶ Z) := cocone (span f g) namespace pushout_cocone variables {f : X ⟶ Y} {g : X ⟶ Z} /-- The first inclusion of a pushout cocone. -/ abbreviation inl (t : pushout_cocone f g) : Y ⟶ t.X := t.ι.app walking_span.left /-- The second inclusion of a pushout cocone. -/ abbreviation inr (t : pushout_cocone f g) : Z ⟶ t.X := t.ι.app walking_span.right /-- A pushout cocone on `f` and `g` is determined by morphisms `inl : Y ⟶ W` and `inr : Z ⟶ W` such that `f ≫ inl = g ↠ inr`. -/ @[simps] def mk {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : pushout_cocone f g := { X := W, ι := { app := λ j, option.cases_on j (f ≫ inl) (λ j', walking_pair.cases_on j' inl inr) } } @[simp] lemma mk_ι_app_left {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.left = inl := rfl @[simp] lemma mk_ι_app_right {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.right = inr := rfl @[simp] lemma mk_ι_app_zero {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.zero = f ≫ inl := rfl @[reassoc] lemma condition (t : pushout_cocone f g) : f ≫ (inl t) = g ≫ (inr t) := (t.w fst).trans (t.w snd).symm /-- To check whether a morphism is coequalized by the maps of a pushout cocone, it suffices to check it for `inl t` and `inr t` -/ lemma coequalizer_ext (t : pushout_cocone f g) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : ∀ (j : walking_span), t.ι.app j ≫ k = t.ι.app j ≫ l | (some walking_pair.left) := h₀ | (some walking_pair.right) := h₁ | none := by rw [← t.w fst, category.assoc, category.assoc, h₀] lemma is_colimit.hom_ext {t : pushout_cocone f g} (ht : is_colimit t) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : k = l := ht.hom_ext $ coequalizer_ext _ h₀ h₁ /-- If `t` is a colimit pushout cocone over `f` and `g` and `h : Y ⟶ W` and `k : Z ⟶ W` are morphisms satisfying `f ≫ h = g ≫ k`, then we have a factorization `l : t.X ⟶ W` such that `inl t ≫ l = h` and `inr t ≫ l = k`. -/ def is_colimit.desc' {t : pushout_cocone f g} (ht : is_colimit t) {W : C} (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : t.X ⟶ W // inl t ≫ l = h ∧ inr t ≫ l = k } := ⟨ht.desc $ pushout_cocone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a slightly more convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def is_colimit.mk (t : pushout_cocone f g) (desc : Π (s : cocone (span f g)), t.X ⟶ s.X) (fac_left : ∀ (s : cocone (span f g)), t.ι.app walking_span.left ≫ desc s = s.ι.app walking_span.left) (fac_right : ∀ (s : cocone (span f g)), t.ι.app walking_span.right ≫ desc s = s.ι.app walking_span.right) (uniq : ∀ (s : cocone (span f g)) (m : t.X ⟶ s.X) (w : ∀ j : walking_span, t.ι.app j ≫ m = s.ι.app j), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, option.cases_on j (by { simp [← s.w fst, ← t.w fst, fac_left s] } ) (λ j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } end pushout_cocone /-- This is a helper construction that can be useful when verifying that a category has all pullbacks. Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a pullback cone on `F.map inl` and `F.map inr`, we get a cone on `F`. If you're thinking about using this, have a look at `has_pullbacks_of_has_limit_cospan`, which you may find to be an easier way of achieving your goal. -/ @[simps] def cone.of_pullback_cone {F : walking_cospan.{v} ⥤ C} (t : pullback_cone (F.map inl) (F.map inr)) : cone F := { X := t.X, π := t.π ≫ (diagram_iso_cospan F).inv } /-- This is a helper construction that can be useful when verifying that a category has all pushout. Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.mal snd)`, and a pushout cocone on `F.map fst` and `F.map snd`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_pushouts_of_has_colimit_span`, which you may find to be an easiery way of achieving your goal. -/ @[simps] def cocone.of_pushout_cocone {F : walking_span.{v} ⥤ C} (t : pushout_cocone (F.map fst) (F.map snd)) : cocone F := { X := t.X, ι := (diagram_iso_span F).hom ≫ t.ι } /-- Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a cone on `F`, we get a pullback cone on `F.map inl` and `F.map inr`. -/ @[simps] def pullback_cone.of_cone {F : walking_cospan.{v} ⥤ C} (t : cone F) : pullback_cone (F.map inl) (F.map inr) := { X := t.X, π := t.π ≫ (diagram_iso_cospan F).hom } /-- Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.map snd)`, and a cocone on `F`, we get a pushout cocone on `F.map fst` and `F.map snd`. -/ @[simps] def pushout_cocone.of_cocone {F : walking_span.{v} ⥤ C} (t : cocone F) : pushout_cocone (F.map fst) (F.map snd) := { X := t.X, ι := (diagram_iso_span F).inv ≫ t.ι } /-- `pullback f g` computes the pullback of a pair of morphisms with the same target. -/ abbreviation pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_limit (cospan f g)] := limit (cospan f g) /-- `pushout f g` computes the pushout of a pair of morphisms with the same source. -/ abbreviation pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_colimit (span f g)] := colimit (span f g) /-- The first projection of the pullback of `f` and `g`. -/ abbreviation pullback.fst {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : pullback f g ⟶ X := limit.π (cospan f g) walking_cospan.left /-- The second projection of the pullback of `f` and `g`. -/ abbreviation pullback.snd {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : pullback f g ⟶ Y := limit.π (cospan f g) walking_cospan.right /-- The first inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inl {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] : Y ⟶ pushout f g := colimit.ι (span f g) walking_span.left /-- The second inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inr {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] : Z ⟶ pushout f g := colimit.ι (span f g) walking_span.right /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `pullback.lift : W ⟶ pullback f g`. -/ abbreviation pullback.lift {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : W ⟶ pullback f g := limit.lift _ (pullback_cone.mk h k w) /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `pushout.desc : pushout f g ⟶ W`. -/ abbreviation pushout.desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout f g ⟶ W := colimit.desc _ (pushout_cocone.mk h k w) @[simp, reassoc] lemma pullback.lift_fst {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.fst = h := limit.lift_π _ _ @[simp, reassoc] lemma pullback.lift_snd {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.snd = k := limit.lift_π _ _ @[simp, reassoc] lemma pushout.inl_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inl ≫ pushout.desc h k w = h := colimit.ι_desc _ _ @[simp, reassoc] lemma pushout.inr_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inr ≫ pushout.desc h k w = k := colimit.ι_desc _ _ /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `l : W ⟶ pullback f g` such that `l ≫ pullback.fst = h` and `l ≫ pullback.snd = k`. -/ def pullback.lift' {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ pullback f g // l ≫ pullback.fst = h ∧ l ≫ pullback.snd = k} := ⟨pullback.lift h k w, pullback.lift_fst _ _ _, pullback.lift_snd _ _ _⟩ /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `l : pushout f g ⟶ W` such that `pushout.inl ≫ l = h` and `pushout.inr ≫ l = k`. -/ def pullback.desc' {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : pushout f g ⟶ W // pushout.inl ≫ l = h ∧ pushout.inr ≫ l = k} := ⟨pushout.desc h k w, pushout.inl_desc _ _ _, pushout.inr_desc _ _ _⟩ @[reassoc] lemma pullback.condition {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : (pullback.fst : pullback f g ⟶ X) ≫ f = pullback.snd ≫ g := pullback_cone.condition _ @[reassoc] lemma pushout.condition {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] : f ≫ (pushout.inl : Y ⟶ pushout f g) = g ≫ pushout.inr := pushout_cocone.condition _ /-- Two morphisms into a pullback are equal if their compositions with the pullback morphisms are equal -/ @[ext] lemma pullback.hom_ext {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] {W : C} {k l : W ⟶ pullback f g} (h₀ : k ≫ pullback.fst = l ≫ pullback.fst) (h₁ : k ≫ pullback.snd = l ≫ pullback.snd) : k = l := limit.hom_ext $ pullback_cone.equalizer_ext _ h₀ h₁ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.fst_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] [mono g] : mono (pullback.fst : pullback f g ⟶ X) := ⟨λ W u v h, pullback.hom_ext h $ (cancel_mono g).1 $ by simp [← pullback.condition, reassoc_of h]⟩ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.snd_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] [mono f] : mono (pullback.snd : pullback f g ⟶ Y) := ⟨λ W u v h, pullback.hom_ext ((cancel_mono f).1 $ by simp [pullback.condition, reassoc_of h]) h⟩ /-- Two morphisms out of a pushout are equal if their compositions with the pushout morphisms are equal -/ @[ext] lemma pushout.hom_ext {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] {W : C} {k l : pushout f g ⟶ W} (h₀ : pushout.inl ≫ k = pushout.inl ≫ l) (h₁ : pushout.inr ≫ k = pushout.inr ≫ l) : k = l := colimit.hom_ext $ pushout_cocone.coequalizer_ext _ h₀ h₁ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inl_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] [epi g] : epi (pushout.inl : Y ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext h $ (cancel_epi g).1 $ by simp [← pushout.condition_assoc, h] ⟩ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inr_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] [epi f] : epi (pushout.inr : Z ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext ((cancel_epi f).1 $ by simp [pushout.condition_assoc, h]) h⟩ variables (C) /-- `has_pullbacks` represents a choice of pullback for every pair of morphisms -/ class has_pullbacks := (has_limits_of_shape : has_limits_of_shape.{v} walking_cospan C) /-- `has_pushouts` represents a choice of pushout for every pair of morphisms -/ class has_pushouts := (has_colimits_of_shape : has_colimits_of_shape.{v} walking_span C) attribute [instance] has_pullbacks.has_limits_of_shape has_pushouts.has_colimits_of_shape /-- Pullbacks are finite limits, so if `C` has all finite limits, it also has all pullbacks -/ def has_pullbacks_of_has_finite_limits [has_finite_limits.{v} C] : has_pullbacks.{v} C := { has_limits_of_shape := infer_instance } /-- Pushouts are finite colimits, so if `C` has all finite colimits, it also has all pushouts -/ def has_pushouts_of_has_finite_colimits [has_finite_colimits.{v} C] : has_pushouts.{v} C := { has_colimits_of_shape := infer_instance } /-- If `C` has all limits of diagrams `cospan f g`, then it has all pullbacks -/ def has_pullbacks_of_has_limit_cospan [Π {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z}, has_limit (cospan f g)] : has_pullbacks.{v} C := { has_limits_of_shape := { has_limit := λ F, has_limit_of_iso (diagram_iso_cospan F).symm } } /-- If `C` has all colimits of diagrams `span f g`, then it has all pushouts -/ def has_pushouts_of_has_colimit_span [Π {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z}, has_colimit (span f g)] : has_pushouts.{v} C := { has_colimits_of_shape := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_span F) } } end category_theory.limits
7b935ff66327333ecc71d9f49f7057ba48e3eef6
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/linear_algebra/tensor_product.lean
d54f86021b5dd1688450f786a952f87453d85e41
[]
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
53,057
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.group_theory.congruence import Mathlib.linear_algebra.basic import Mathlib.PostPort universes u_1 u_4 u_3 u_2 u_5 l u_6 u_7 u_8 u_9 namespace Mathlib /-! # Tensor product of semimodules over commutative semirings. This file constructs the tensor product of semimodules over commutative semirings. Given a semiring `R` and semimodules over it `M` and `N`, the standard construction of the tensor product is `tensor_product R M N`. It is also a semimodule over `R`. It comes with a canonical bilinear map `M → N → tensor_product R M N`. Given any bilinear map `M → N → P`, there is a unique linear map `tensor_product R M N → P` whose composition with the canonical bilinear map `M → N → tensor_product R M N` is the given bilinear map `M → N → P`. We start by proving basic lemmas about bilinear maps. ## Notations This file uses the localized notation `M ⊗ N` and `M ⊗[R] N` for `tensor_product R M N`, as well as `m ⊗ₜ n` and `m ⊗ₜ[R] n` for `tensor_product.tmul R m n`. ## Tags bilinear, tensor, tensor product -/ namespace linear_map /-- Create a bilinear map from a function that is linear in each component. -/ def mk₂ (R : Type u_1) [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : M → N → P) (H1 : ∀ (m₁ m₂ : M) (n : N), f (m₁ + m₂) n = f m₁ n + f m₂ n) (H2 : ∀ (c : R) (m : M) (n : N), f (c • m) n = c • f m n) (H3 : ∀ (m : M) (n₁ n₂ : N), f m (n₁ + n₂) = f m n₁ + f m n₂) (H4 : ∀ (c : R) (m : M) (n : N), f m (c • n) = c • f m n) : linear_map R M (linear_map R N P) := mk (fun (m : M) => mk (f m) (H3 m) sorry) sorry sorry @[simp] theorem mk₂_apply {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : M → N → P) {H1 : ∀ (m₁ m₂ : M) (n : N), f (m₁ + m₂) n = f m₁ n + f m₂ n} {H2 : ∀ (c : R) (m : M) (n : N), f (c • m) n = c • f m n} {H3 : ∀ (m : M) (n₁ n₂ : N), f m (n₁ + n₂) = f m n₁ + f m n₂} {H4 : ∀ (c : R) (m : M) (n : N), f m (c • n) = c • f m n} (m : M) (n : N) : coe_fn (coe_fn (mk₂ R f H1 H2 H3 H4) m) n = f m n := rfl theorem ext₂ {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] {f : linear_map R M (linear_map R N P)} {g : linear_map R M (linear_map R N P)} (H : ∀ (m : M) (n : N), coe_fn (coe_fn f m) n = coe_fn (coe_fn g m) n) : f = g := ext fun (m : M) => ext fun (n : N) => H m n /-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map from `M × N` to `P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/ def flip {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R M (linear_map R N P)) : linear_map R N (linear_map R M P) := mk₂ R (fun (n : N) (m : M) => coe_fn (coe_fn f m) n) sorry sorry sorry sorry @[simp] theorem flip_apply {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R M (linear_map R N P)) (m : M) (n : N) : coe_fn (coe_fn (flip f) n) m = coe_fn (coe_fn f m) n := rfl theorem flip_inj {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] {f : linear_map R M (linear_map R N P)} {g : linear_map R M (linear_map R N P)} (H : flip f = flip g) : f = g := sorry /-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map `M → N → P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/ def lflip (R : Type u_1) [comm_semiring R] (M : Type u_2) (N : Type u_3) (P : Type u_4) [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] : linear_map R (linear_map R M (linear_map R N P)) (linear_map R N (linear_map R M P)) := mk flip sorry sorry @[simp] theorem lflip_apply {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R M (linear_map R N P)) (m : M) (n : N) : coe_fn (coe_fn (coe_fn (lflip R M N P) f) n) m = coe_fn (coe_fn f m) n := rfl theorem map_zero₂ {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R M (linear_map R N P)) (y : N) : coe_fn (coe_fn f 0) y = 0 := map_zero (coe_fn (flip f) y) theorem map_neg₂ {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_group M] [add_comm_monoid N] [add_comm_group P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R M (linear_map R N P)) (x : M) (y : N) : coe_fn (coe_fn f (-x)) y = -coe_fn (coe_fn f x) y := map_neg (coe_fn (flip f) y) x theorem map_sub₂ {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_group M] [add_comm_monoid N] [add_comm_group P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R M (linear_map R N P)) (x : M) (y : M) (z : N) : coe_fn (coe_fn f (x - y)) z = coe_fn (coe_fn f x) z - coe_fn (coe_fn f y) z := map_sub (coe_fn (flip f) z) x y theorem map_add₂ {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R M (linear_map R N P)) (x₁ : M) (x₂ : M) (y : N) : coe_fn (coe_fn f (x₁ + x₂)) y = coe_fn (coe_fn f x₁) y + coe_fn (coe_fn f x₂) y := map_add (coe_fn (flip f) y) x₁ x₂ theorem map_smul₂ {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R M (linear_map R N P)) (r : R) (x : M) (y : N) : coe_fn (coe_fn f (r • x)) y = r • coe_fn (coe_fn f x) y := map_smul (coe_fn (flip f) y) r x /-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/ def lcomp (R : Type u_1) [comm_semiring R] {M : Type u_2} {N : Type u_3} (P : Type u_4) [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R M N) : linear_map R (linear_map R N P) (linear_map R M P) := flip (comp (flip id) f) @[simp] theorem lcomp_apply {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R M N) (g : linear_map R N P) (x : M) : coe_fn (coe_fn (lcomp R P f) g) x = coe_fn g (coe_fn f x) := rfl /-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/ def llcomp (R : Type u_1) [comm_semiring R] (M : Type u_2) (N : Type u_3) (P : Type u_4) [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] : linear_map R (linear_map R N P) (linear_map R (linear_map R M N) (linear_map R M P)) := flip (mk (lcomp R P) sorry sorry) @[simp] theorem llcomp_apply {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R N P) (g : linear_map R M N) (x : M) : coe_fn (coe_fn (coe_fn (llcomp R M N P) f) g) x = coe_fn f (coe_fn g x) := rfl /-- Composing a linear map `Q → N` and a bilinear map `M → N → P` to form a bilinear map `M → Q → P`. -/ def compl₂ {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} {Q : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] (f : linear_map R M (linear_map R N P)) (g : linear_map R Q N) : linear_map R M (linear_map R Q P) := comp (lcomp R P g) f @[simp] theorem compl₂_apply {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} {Q : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] (f : linear_map R M (linear_map R N P)) (g : linear_map R Q N) (m : M) (q : Q) : coe_fn (coe_fn (compl₂ f g) m) q = coe_fn (coe_fn f m) (coe_fn g q) := rfl /-- Composing a linear map `P → Q` and a bilinear map `M × N → P` to form a bilinear map `M → N → Q`. -/ def compr₂ {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} {Q : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] (f : linear_map R M (linear_map R N P)) (g : linear_map R P Q) : linear_map R M (linear_map R N Q) := comp (coe_fn (llcomp R N P Q) g) f @[simp] theorem compr₂_apply {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} {Q : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] (f : linear_map R M (linear_map R N P)) (g : linear_map R P Q) (m : M) (n : N) : coe_fn (coe_fn (compr₂ f g) m) n = coe_fn g (coe_fn (coe_fn f m) n) := rfl /-- Scalar multiplication as a bilinear map `R → M → M`. -/ def lsmul (R : Type u_1) [comm_semiring R] (M : Type u_2) [add_comm_monoid M] [semimodule R M] : linear_map R R (linear_map R M M) := mk₂ R has_scalar.smul sorry sorry sorry sorry @[simp] theorem lsmul_apply {R : Type u_1} [comm_semiring R] {M : Type u_2} [add_comm_monoid M] [semimodule R M] (r : R) (m : M) : coe_fn (coe_fn (lsmul R M) r) m = r • m := rfl end linear_map namespace tensor_product -- open free_add_monoid /-- The relation on `free_add_monoid (M × N)` that generates a congruence whose quotient is the tensor product. -/ inductive eqv (R : Type u_1) [comm_semiring R] (M : Type u_3) (N : Type u_4) [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] : free_add_monoid (M × N) → free_add_monoid (M × N) → Prop where | of_zero_left : ∀ (n : N), eqv R M N (free_add_monoid.of (0, n)) 0 | of_zero_right : ∀ (m : M), eqv R M N (free_add_monoid.of (m, 0)) 0 | of_add_left : ∀ (m₁ m₂ : M) (n : N), eqv R M N (free_add_monoid.of (m₁, n) + free_add_monoid.of (m₂, n)) (free_add_monoid.of (m₁ + m₂, n)) | of_add_right : ∀ (m : M) (n₁ n₂ : N), eqv R M N (free_add_monoid.of (m, n₁) + free_add_monoid.of (m, n₂)) (free_add_monoid.of (m, n₁ + n₂)) | of_smul : ∀ (r : R) (m : M) (n : N), eqv R M N (free_add_monoid.of (r • m, n)) (free_add_monoid.of (m, r • n)) | add_comm : ∀ (x y : free_add_monoid (M × N)), eqv R M N (x + y) (y + x) end tensor_product /-- The tensor product of two semimodules `M` and `N` over the same commutative semiring `R`. The localized notations are `M ⊗ N` and `M ⊗[R] N`, accessed by `open_locale tensor_product`. -/ def tensor_product (R : Type u_1) [comm_semiring R] (M : Type u_3) (N : Type u_4) [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] := add_con.quotient (add_con_gen sorry) namespace tensor_product protected instance add_comm_monoid {R : Type u_1} [comm_semiring R] (M : Type u_3) (N : Type u_4) [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] : add_comm_monoid (tensor_product R M N) := add_comm_monoid.mk add_monoid.add sorry add_monoid.zero sorry sorry sorry protected instance inhabited {R : Type u_1} [comm_semiring R] (M : Type u_3) (N : Type u_4) [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] : Inhabited (tensor_product R M N) := { default := 0 } /-- The canonical function `M → N → M ⊗ N`. The localized notations are `m ⊗ₜ n` and `m ⊗ₜ[R] n`, accessed by `open_locale tensor_product`. -/ def tmul (R : Type u_1) [comm_semiring R] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] (m : M) (n : N) : tensor_product R M N := coe_fn (add_con.mk' (add_con_gen (eqv R M N))) (free_add_monoid.of (m, n)) protected theorem induction_on {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] {C : tensor_product R M N → Prop} (z : tensor_product R M N) (C0 : C 0) (C1 : ∀ {x : M} {y : N}, C (tmul R x y)) (Cp : ∀ {x y : tensor_product R M N}, C x → C y → C (x + y)) : C z := sorry @[simp] theorem zero_tmul {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] (n : N) : tmul R 0 n = 0 := quotient.sound' (add_con_gen.rel.of (free_add_monoid.of (0, n)) 0 (eqv.of_zero_left n)) theorem add_tmul {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] (m₁ : M) (m₂ : M) (n : N) : tmul R (m₁ + m₂) n = tmul R m₁ n + tmul R m₂ n := sorry @[simp] theorem tmul_zero {R : Type u_1} [comm_semiring R] {M : Type u_3} (N : Type u_4) [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] (m : M) : tmul R m 0 = 0 := quotient.sound' (add_con_gen.rel.of (free_add_monoid.of (m, 0)) 0 (eqv.of_zero_right m)) theorem tmul_add {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] (m : M) (n₁ : N) (n₂ : N) : tmul R m (n₁ + n₂) = tmul R m n₁ + tmul R m n₂ := sorry /-- A typeclass for `has_scalar` structures which can be moved across a tensor product. This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if `R` does not support negation. Note that `semimodule R' (M ⊗[R] N)` is available even without this typeclass on `R'`; it's only needed if `tensor_product.smul_tmul`, `tensor_product.smul_tmul'`, or `tensor_product.tmul_smul` is used. -/ class compatible_smul (R : Type u_1) [comm_semiring R] (R' : Type u_2) [comm_semiring R'] (M : Type u_3) (N : Type u_4) [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] [semimodule R' M] [semimodule R' N] where smul_tmul : ∀ (r : R') (m : M) (n : N), tmul R (r • m) n = tmul R m (r • n) /-- Note that this provides the default `compatible_smul R R M N` instance through `mul_action.is_scalar_tower.left`. -/ protected instance compatible_smul.is_scalar_tower {R : Type u_1} [comm_semiring R] {R' : Type u_2} [comm_semiring R'] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] [semimodule R' M] [semimodule R' N] [has_scalar R' R] [is_scalar_tower R' R M] [is_scalar_tower R' R N] : compatible_smul R R' M N := compatible_smul.mk sorry /-- `smul` can be moved from one side of the product to the other .-/ theorem smul_tmul {R : Type u_1} [comm_semiring R] {R' : Type u_2} [comm_semiring R'] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] [semimodule R' M] [semimodule R' N] [compatible_smul R R' M N] (r : R') (m : M) (n : N) : tmul R (r • m) n = tmul R m (r • n) := compatible_smul.smul_tmul r m n /-- Auxiliary function to defining scalar multiplication on tensor product. -/ def smul.aux {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] {R' : Type u_2} [has_scalar R' M] (r : R') : free_add_monoid (M × N) →+ tensor_product R M N := coe_fn free_add_monoid.lift fun (p : M × N) => tmul R (r • prod.fst p) (prod.snd p) theorem smul.aux_of {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] {R' : Type u_2} [has_scalar R' M] (r : R') (m : M) (n : N) : coe_fn (smul.aux r) (free_add_monoid.of (m, n)) = tmul R (r • m) n := rfl -- Most of the time we want the instance below this one, which is easier for typeclass resolution -- to find. The `unused_arguments` is from one of the two comm_classes - while we only make use -- of one, it makes sense to make the API symmetric. protected instance has_scalar' {R : Type u_1} [comm_semiring R] {R' : Type u_2} [comm_semiring R'] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] [semimodule R' M] [semimodule R' N] [smul_comm_class R R' M] [smul_comm_class R R' N] : has_scalar R' (tensor_product R M N) := has_scalar.mk fun (r : R') => ⇑(add_con.lift (add_con_gen (eqv R M N)) (smul.aux r) sorry) protected instance has_scalar {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] : has_scalar R (tensor_product R M N) := tensor_product.has_scalar' protected theorem smul_zero {R : Type u_1} [comm_semiring R] {R' : Type u_2} [comm_semiring R'] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] [semimodule R' M] [semimodule R' N] [smul_comm_class R R' M] [smul_comm_class R R' N] (r : R') : r • 0 = 0 := add_monoid_hom.map_zero (add_con.lift (add_con_gen (eqv R M N)) (smul.aux r) (has_scalar'._proof_1 r)) protected theorem smul_add {R : Type u_1} [comm_semiring R] {R' : Type u_2} [comm_semiring R'] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] [semimodule R' M] [semimodule R' N] [smul_comm_class R R' M] [smul_comm_class R R' N] (r : R') (x : tensor_product R M N) (y : tensor_product R M N) : r • (x + y) = r • x + r • y := add_monoid_hom.map_add (add_con.lift (add_con_gen (eqv R M N)) (smul.aux r) (has_scalar'._proof_1 r)) x y -- Most of the time we want the instance below this one, which is easier for typeclass resolution -- to find. protected instance semimodule' {R : Type u_1} [comm_semiring R] {R' : Type u_2} [comm_semiring R'] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] [semimodule R' M] [semimodule R' N] [smul_comm_class R R' M] [smul_comm_class R R' N] : semimodule R' (tensor_product R M N) := (fun (this : ∀ (r : R') (m : M) (n : N), r • tmul R m n = tmul R (r • m) n) => semimodule.mk sorry sorry) sorry protected instance semimodule {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] : semimodule R (tensor_product R M N) := tensor_product.semimodule' -- note that we don't actually need `compatible_smul` here, but we include it for symmetry -- with `tmul_smul` to avoid exposing our asymmetric definition. theorem smul_tmul' {R : Type u_1} [comm_semiring R] {R' : Type u_2} [comm_semiring R'] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] [semimodule R' M] [semimodule R' N] [smul_comm_class R R' M] [smul_comm_class R R' N] [compatible_smul R R' M N] (r : R') (m : M) (n : N) : r • tmul R m n = tmul R (r • m) n := rfl @[simp] theorem tmul_smul {R : Type u_1} [comm_semiring R] {R' : Type u_2} [comm_semiring R'] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] [semimodule R' M] [semimodule R' N] [smul_comm_class R R' M] [smul_comm_class R R' N] [compatible_smul R R' M N] (r : R') (x : M) (y : N) : tmul R x (r • y) = r • tmul R x y := Eq.symm (smul_tmul r x y) /-- The canonical bilinear map `M → N → M ⊗[R] N`. -/ def mk (R : Type u_1) [comm_semiring R] (M : Type u_3) (N : Type u_4) [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] : linear_map R M (linear_map R N (tensor_product R M N)) := linear_map.mk₂ R (fun (_x : M) (_y : N) => tmul R _x _y) add_tmul sorry tmul_add sorry @[simp] theorem mk_apply {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] (m : M) (n : N) : coe_fn (coe_fn (mk R M N) m) n = tmul R m n := rfl theorem ite_tmul {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] (x₁ : M) (x₂ : N) (P : Prop) [Decidable P] : tmul R (ite P x₁ 0) x₂ = ite P (tmul R x₁ x₂) 0 := sorry theorem tmul_ite {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] (x₁ : M) (x₂ : N) (P : Prop) [Decidable P] : tmul R x₁ (ite P x₂ 0) = ite P (tmul R x₁ x₂) 0 := sorry theorem sum_tmul {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] {α : Type u_2} (s : finset α) (m : α → M) (n : N) : tmul R (finset.sum s fun (a : α) => m a) n = finset.sum s fun (a : α) => tmul R (m a) n := sorry theorem tmul_sum {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] (m : M) {α : Type u_2} (s : finset α) (n : α → N) : tmul R m (finset.sum s fun (a : α) => n a) = finset.sum s fun (a : α) => tmul R m (n a) := sorry /-- Auxiliary function to constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift_aux {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R M (linear_map R N P)) : tensor_product R M N →+ P := add_con.lift (add_con_gen (eqv R M N)) (coe_fn free_add_monoid.lift fun (p : M × N) => coe_fn (coe_fn f (prod.fst p)) (prod.snd p)) sorry theorem lift_aux_tmul {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R M (linear_map R N P)) (m : M) (n : N) : coe_fn (lift_aux f) (tmul R m n) = coe_fn (coe_fn f m) n := zero_add ((fun (p : M × N) => coe_fn (coe_fn f (prod.fst p)) (prod.snd p)) (m, n)) @[simp] theorem lift_aux.smul {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] {f : linear_map R M (linear_map R N P)} (r : R) (x : tensor_product R M N) : coe_fn (lift_aux f) (r • x) = r • coe_fn (lift_aux f) x := sorry /-- Constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R M (linear_map R N P)) : linear_map R (tensor_product R M N) P := linear_map.mk (add_monoid_hom.to_fun (lift_aux f)) sorry lift_aux.smul @[simp] theorem lift.tmul {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] {f : linear_map R M (linear_map R N P)} (x : M) (y : N) : coe_fn (lift f) (tmul R x y) = coe_fn (coe_fn f x) y := zero_add ((fun (p : M × N) => coe_fn (coe_fn f (prod.fst p)) (prod.snd p)) (x, y)) @[simp] theorem lift.tmul' {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] {f : linear_map R M (linear_map R N P)} (x : M) (y : N) : linear_map.to_fun (lift f) (tmul R x y) = coe_fn (coe_fn f x) y := lift.tmul x y theorem ext {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] {g : linear_map R (tensor_product R M N) P} {h : linear_map R (tensor_product R M N) P} (H : ∀ (x : M) (y : N), coe_fn g (tmul R x y) = coe_fn h (tmul R x y)) : g = h := sorry theorem lift.unique {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] {f : linear_map R M (linear_map R N P)} {g : linear_map R (tensor_product R M N) P} (H : ∀ (x : M) (y : N), coe_fn g (tmul R x y) = coe_fn (coe_fn f x) y) : g = lift f := sorry theorem lift_mk {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] : lift (mk R M N) = linear_map.id := Eq.symm (lift.unique fun (x : M) (y : N) => rfl) theorem lift_compr₂ {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} {Q : Type u_6} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] {f : linear_map R M (linear_map R N P)} (g : linear_map R P Q) : lift (linear_map.compr₂ f g) = linear_map.comp g (lift f) := sorry theorem lift_mk_compr₂ {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R (tensor_product R M N) P) : lift (linear_map.compr₂ (mk R M N) f) = f := eq.mpr (id (Eq._oldrec (Eq.refl (lift (linear_map.compr₂ (mk R M N) f) = f)) (lift_compr₂ f))) (eq.mpr (id (Eq._oldrec (Eq.refl (linear_map.comp f (lift (mk R M N)) = f)) lift_mk)) (eq.mpr (id (Eq._oldrec (Eq.refl (linear_map.comp f linear_map.id = f)) (linear_map.comp_id f))) (Eq.refl f))) theorem mk_compr₂_inj {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] {g : linear_map R (tensor_product R M N) P} {h : linear_map R (tensor_product R M N) P} (H : linear_map.compr₂ (mk R M N) g = linear_map.compr₂ (mk R M N) h) : g = h := eq.mpr (id (Eq._oldrec (Eq.refl (g = h)) (Eq.symm (lift_mk_compr₂ g)))) (eq.mpr (id (Eq._oldrec (Eq.refl (lift (linear_map.compr₂ (mk R M N) g) = h)) H)) (eq.mpr (id (Eq._oldrec (Eq.refl (lift (linear_map.compr₂ (mk R M N) h) = h)) (lift_mk_compr₂ h))) (Eq.refl h))) /-- Linearly constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def uncurry (R : Type u_1) [comm_semiring R] (M : Type u_3) (N : Type u_4) (P : Type u_5) [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] : linear_map R (linear_map R M (linear_map R N P)) (linear_map R (tensor_product R M N) P) := linear_map.flip (lift (linear_map.comp (linear_map.lflip R (linear_map R M (linear_map R N P)) N P) (linear_map.flip linear_map.id))) @[simp] theorem uncurry_apply {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R M (linear_map R N P)) (m : M) (n : N) : coe_fn (coe_fn (uncurry R M N P) f) (tmul R m n) = coe_fn (coe_fn f m) n := sorry /-- A linear equivalence constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift.equiv (R : Type u_1) [comm_semiring R] (M : Type u_3) (N : Type u_4) (P : Type u_5) [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] : linear_equiv R (linear_map R M (linear_map R N P)) (linear_map R (tensor_product R M N) P) := linear_equiv.mk (linear_map.to_fun (uncurry R M N P)) sorry sorry (fun (f : linear_map R (tensor_product R M N) P) => linear_map.compr₂ (mk R M N) f) sorry sorry /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def lcurry (R : Type u_1) [comm_semiring R] (M : Type u_3) (N : Type u_4) (P : Type u_5) [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] : linear_map R (linear_map R (tensor_product R M N) P) (linear_map R M (linear_map R N P)) := ↑(linear_equiv.symm (lift.equiv R M N P)) @[simp] theorem lcurry_apply {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R (tensor_product R M N) P) (m : M) (n : N) : coe_fn (coe_fn (coe_fn (lcurry R M N P) f) m) n = coe_fn f (tmul R m n) := rfl /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def curry {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R (tensor_product R M N) P) : linear_map R M (linear_map R N P) := coe_fn (lcurry R M N P) f @[simp] theorem curry_apply {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R (tensor_product R M N) P) (m : M) (n : N) : coe_fn (coe_fn (curry f) m) n = coe_fn f (tmul R m n) := rfl theorem ext_threefold {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} {Q : Type u_6} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] {g : linear_map R (tensor_product R (tensor_product R M N) P) Q} {h : linear_map R (tensor_product R (tensor_product R M N) P) Q} (H : ∀ (x : M) (y : N) (z : P), coe_fn g (tmul R (tmul R x y) z) = coe_fn h (tmul R (tmul R x y) z)) : g = h := sorry -- We'll need this one for checking the pentagon identity! theorem ext_fourfold {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} {Q : Type u_6} {S : Type u_7} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [add_comm_monoid S] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] [semimodule R S] {g : linear_map R (tensor_product R (tensor_product R (tensor_product R M N) P) Q) S} {h : linear_map R (tensor_product R (tensor_product R (tensor_product R M N) P) Q) S} (H : ∀ (w : M) (x : N) (y : P) (z : Q), coe_fn g (tmul R (tmul R (tmul R w x) y) z) = coe_fn h (tmul R (tmul R (tmul R w x) y) z)) : g = h := sorry /-- The base ring is a left identity for the tensor product of modules, up to linear equivalence. -/ protected def lid (R : Type u_1) [comm_semiring R] (M : Type u_3) [add_comm_monoid M] [semimodule R M] : linear_equiv R (tensor_product R R M) M := linear_equiv.of_linear (lift (linear_map.lsmul R M)) (coe_fn (mk R R M) 1) sorry sorry @[simp] theorem lid_tmul {R : Type u_1} [comm_semiring R] {M : Type u_3} [add_comm_monoid M] [semimodule R M] (m : M) (r : R) : coe_fn (tensor_product.lid R M) (tmul R r m) = r • m := sorry @[simp] theorem lid_symm_apply {R : Type u_1} [comm_semiring R] {M : Type u_3} [add_comm_monoid M] [semimodule R M] (m : M) : coe_fn (linear_equiv.symm (tensor_product.lid R M)) m = tmul R 1 m := rfl /-- The tensor product of modules is commutative, up to linear equivalence. -/ protected def comm (R : Type u_1) [comm_semiring R] (M : Type u_3) (N : Type u_4) [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] : linear_equiv R (tensor_product R M N) (tensor_product R N M) := linear_equiv.of_linear (lift (linear_map.flip (mk R N M))) (lift (linear_map.flip (mk R M N))) sorry sorry @[simp] theorem comm_tmul (R : Type u_1) [comm_semiring R] (M : Type u_3) (N : Type u_4) [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] (m : M) (n : N) : coe_fn (tensor_product.comm R M N) (tmul R m n) = tmul R n m := rfl @[simp] theorem comm_symm_tmul (R : Type u_1) [comm_semiring R] (M : Type u_3) (N : Type u_4) [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] (m : M) (n : N) : coe_fn (linear_equiv.symm (tensor_product.comm R M N)) (tmul R n m) = tmul R m n := rfl /-- The base ring is a right identity for the tensor product of modules, up to linear equivalence. -/ protected def rid (R : Type u_1) [comm_semiring R] (M : Type u_3) [add_comm_monoid M] [semimodule R M] : linear_equiv R (tensor_product R M R) M := linear_equiv.trans (tensor_product.comm R M R) (tensor_product.lid R M) @[simp] theorem rid_tmul {R : Type u_1} [comm_semiring R] {M : Type u_3} [add_comm_monoid M] [semimodule R M] (m : M) (r : R) : coe_fn (tensor_product.rid R M) (tmul R m r) = r • m := sorry @[simp] theorem rid_symm_apply {R : Type u_1} [comm_semiring R] {M : Type u_3} [add_comm_monoid M] [semimodule R M] (m : M) : coe_fn (linear_equiv.symm (tensor_product.rid R M)) m = tmul R m 1 := rfl /-- The associator for tensor product of R-modules, as a linear equivalence. -/ protected def assoc (R : Type u_1) [comm_semiring R] (M : Type u_3) (N : Type u_4) (P : Type u_5) [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] : linear_equiv R (tensor_product R (tensor_product R M N) P) (tensor_product R M (tensor_product R N P)) := linear_equiv.of_linear (lift (lift (linear_map.comp (lcurry R N P (tensor_product R M (tensor_product R N P))) (mk R M (tensor_product R N P))))) (lift (linear_map.comp (uncurry R N P (tensor_product R (tensor_product R M N) P)) (curry (mk R (tensor_product R M N) P)))) sorry sorry @[simp] theorem assoc_tmul {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (m : M) (n : N) (p : P) : coe_fn (tensor_product.assoc R M N P) (tmul R (tmul R m n) p) = tmul R m (tmul R n p) := rfl @[simp] theorem assoc_symm_tmul {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (m : M) (n : N) (p : P) : coe_fn (linear_equiv.symm (tensor_product.assoc R M N P)) (tmul R m (tmul R n p)) = tmul R (tmul R m n) p := rfl /-- The tensor product of a pair of linear maps between modules. -/ def map {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} {Q : Type u_6} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] (f : linear_map R M P) (g : linear_map R N Q) : linear_map R (tensor_product R M N) (tensor_product R P Q) := lift (linear_map.comp (linear_map.compl₂ (mk R P Q) g) f) @[simp] theorem map_tmul {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} {Q : Type u_6} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] (f : linear_map R M P) (g : linear_map R N Q) (m : M) (n : N) : coe_fn (map f g) (tmul R m n) = tmul R (coe_fn f m) (coe_fn g n) := rfl theorem map_comp {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} {Q : Type u_6} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] {P' : Type u_8} {Q' : Type u_9} [add_comm_monoid P'] [semimodule R P'] [add_comm_monoid Q'] [semimodule R Q'] (f₂ : linear_map R P P') (f₁ : linear_map R M P) (g₂ : linear_map R Q Q') (g₁ : linear_map R N Q) : map (linear_map.comp f₂ f₁) (linear_map.comp g₂ g₁) = linear_map.comp (map f₂ g₂) (map f₁ g₁) := sorry theorem lift_comp_map {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} {Q : Type u_6} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] {Q' : Type u_9} [add_comm_monoid Q'] [semimodule R Q'] (i : linear_map R P (linear_map R Q Q')) (f : linear_map R M P) (g : linear_map R N Q) : linear_map.comp (lift i) (map f g) = lift (linear_map.compl₂ (linear_map.comp i f) g) := sorry /-- If `M` and `P` are linearly equivalent and `N` and `Q` are linearly equivalent then `M ⊗ N` and `P ⊗ Q` are linearly equivalent. -/ def congr {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} {Q : Type u_6} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] (f : linear_equiv R M P) (g : linear_equiv R N Q) : linear_equiv R (tensor_product R M N) (tensor_product R P Q) := linear_equiv.of_linear (map ↑f ↑g) (map ↑(linear_equiv.symm f) ↑(linear_equiv.symm g)) sorry sorry @[simp] theorem congr_tmul {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} {Q : Type u_6} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] (f : linear_equiv R M P) (g : linear_equiv R N Q) (m : M) (n : N) : coe_fn (congr f g) (tmul R m n) = tmul R (coe_fn f m) (coe_fn g n) := rfl @[simp] theorem congr_symm_tmul {R : Type u_1} [comm_semiring R] {M : Type u_3} {N : Type u_4} {P : Type u_5} {Q : Type u_6} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] (f : linear_equiv R M P) (g : linear_equiv R N Q) (p : P) (q : Q) : coe_fn (linear_equiv.symm (congr f g)) (tmul R p q) = tmul R (coe_fn (linear_equiv.symm f) p) (coe_fn (linear_equiv.symm g) q) := rfl end tensor_product namespace linear_map /-- `ltensor M f : M ⊗ N →ₗ M ⊗ P` is the natural linear map induced by `f : N →ₗ P`. -/ def ltensor {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R N P) : linear_map R (tensor_product R M N) (tensor_product R M P) := tensor_product.map id f /-- `rtensor f M : N₁ ⊗ M →ₗ N₂ ⊗ M` is the natural linear map induced by `f : N₁ →ₗ N₂`. -/ def rtensor {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R N P) : linear_map R (tensor_product R N M) (tensor_product R P M) := tensor_product.map f id @[simp] theorem ltensor_tmul {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R N P) (m : M) (n : N) : coe_fn (ltensor M f) (tensor_product.tmul R m n) = tensor_product.tmul R m (coe_fn f n) := rfl @[simp] theorem rtensor_tmul {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R N P) (m : M) (n : N) : coe_fn (rtensor M f) (tensor_product.tmul R n m) = tensor_product.tmul R (coe_fn f n) m := rfl /-- `ltensor_hom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. -/ def ltensor_hom {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] : linear_map R (linear_map R N P) (linear_map R (tensor_product R M N) (tensor_product R M P)) := mk (ltensor M) sorry sorry /-- `rtensor_hom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. -/ def rtensor_hom {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] : linear_map R (linear_map R N P) (linear_map R (tensor_product R N M) (tensor_product R P M)) := mk (fun (f : linear_map R N P) => rtensor M f) sorry sorry @[simp] theorem coe_ltensor_hom {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] : ⇑(ltensor_hom M) = ltensor M := rfl @[simp] theorem coe_rtensor_hom {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] : ⇑(rtensor_hom M) = rtensor M := rfl @[simp] theorem ltensor_add {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R N P) (g : linear_map R N P) : ltensor M (f + g) = ltensor M f + ltensor M g := map_add (ltensor_hom M) f g @[simp] theorem rtensor_add {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R N P) (g : linear_map R N P) : rtensor M (f + g) = rtensor M f + rtensor M g := map_add (rtensor_hom M) f g @[simp] theorem ltensor_zero {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] : ltensor M 0 = 0 := map_zero (ltensor_hom M) @[simp] theorem rtensor_zero {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] : rtensor M 0 = 0 := map_zero (rtensor_hom M) @[simp] theorem ltensor_smul {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (r : R) (f : linear_map R N P) : ltensor M (r • f) = r • ltensor M f := map_smul (ltensor_hom M) r f @[simp] theorem rtensor_smul {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [semimodule R M] [semimodule R N] [semimodule R P] (r : R) (f : linear_map R N P) : rtensor M (r • f) = r • rtensor M f := map_smul (rtensor_hom M) r f theorem ltensor_comp {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} {Q : Type u_6} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] (g : linear_map R P Q) (f : linear_map R N P) : ltensor M (comp g f) = comp (ltensor M g) (ltensor M f) := sorry theorem rtensor_comp {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} {Q : Type u_6} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] (g : linear_map R P Q) (f : linear_map R N P) : rtensor M (comp g f) = comp (rtensor M g) (rtensor M f) := sorry @[simp] theorem ltensor_id {R : Type u_1} [comm_semiring R] (M : Type u_3) (N : Type u_4) [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] : ltensor M id = id := sorry @[simp] theorem rtensor_id {R : Type u_1} [comm_semiring R] (M : Type u_3) (N : Type u_4) [add_comm_monoid M] [add_comm_monoid N] [semimodule R M] [semimodule R N] : rtensor M id = id := sorry @[simp] theorem ltensor_comp_rtensor {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} {Q : Type u_6} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] (f : linear_map R M P) (g : linear_map R N Q) : comp (ltensor P g) (rtensor N f) = tensor_product.map f g := sorry @[simp] theorem rtensor_comp_ltensor {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} {Q : Type u_6} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] (f : linear_map R M P) (g : linear_map R N Q) : comp (rtensor Q f) (ltensor M g) = tensor_product.map f g := sorry @[simp] theorem map_comp_rtensor {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} {Q : Type u_6} {S : Type u_7} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [add_comm_monoid S] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] [semimodule R S] (f : linear_map R M P) (g : linear_map R N Q) (f' : linear_map R S M) : comp (tensor_product.map f g) (rtensor N f') = tensor_product.map (comp f f') g := sorry @[simp] theorem map_comp_ltensor {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} {Q : Type u_6} {S : Type u_7} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [add_comm_monoid S] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] [semimodule R S] (f : linear_map R M P) (g : linear_map R N Q) (g' : linear_map R S N) : comp (tensor_product.map f g) (ltensor M g') = tensor_product.map f (comp g g') := sorry @[simp] theorem rtensor_comp_map {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} {Q : Type u_6} {S : Type u_7} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [add_comm_monoid S] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] [semimodule R S] (f' : linear_map R P S) (f : linear_map R M P) (g : linear_map R N Q) : comp (rtensor Q f') (tensor_product.map f g) = tensor_product.map (comp f' f) g := sorry @[simp] theorem ltensor_comp_map {R : Type u_1} [comm_semiring R] (M : Type u_3) {N : Type u_4} {P : Type u_5} {Q : Type u_6} {S : Type u_7} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [add_comm_monoid S] [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] [semimodule R S] (g' : linear_map R Q S) (f : linear_map R M P) (g : linear_map R N Q) : comp (ltensor P g') (tensor_product.map f g) = tensor_product.map f (comp g' g) := sorry end linear_map namespace tensor_product /-- Auxiliary function to defining negation multiplication on tensor product. -/ def neg.aux (R : Type u_1) [comm_semiring R] {M : Type u_2} {N : Type u_3} [add_comm_group M] [add_comm_group N] [semimodule R M] [semimodule R N] : free_add_monoid (M × N) →+ tensor_product R M N := coe_fn free_add_monoid.lift fun (p : M × N) => tmul R (-prod.fst p) (prod.snd p) theorem neg.aux_of {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} [add_comm_group M] [add_comm_group N] [semimodule R M] [semimodule R N] (m : M) (n : N) : coe_fn (neg.aux R) (free_add_monoid.of (m, n)) = tmul R (-m) n := rfl protected instance has_neg {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} [add_comm_group M] [add_comm_group N] [semimodule R M] [semimodule R N] : Neg (tensor_product R M N) := { neg := ⇑(add_con.lift (add_con_gen (eqv R M N)) (neg.aux R) sorry) } protected instance add_comm_group {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} [add_comm_group M] [add_comm_group N] [semimodule R M] [semimodule R N] : add_comm_group (tensor_product R M N) := add_comm_group.mk add_comm_monoid.add sorry add_comm_monoid.zero sorry sorry Neg.neg (fun (_x _x_1 : tensor_product R M N) => add_semigroup.add _x (-_x_1)) sorry sorry theorem neg_tmul {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} [add_comm_group M] [add_comm_group N] [semimodule R M] [semimodule R N] (m : M) (n : N) : tmul R (-m) n = -tmul R m n := rfl theorem tmul_neg {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} [add_comm_group M] [add_comm_group N] [semimodule R M] [semimodule R N] (m : M) (n : N) : tmul R m (-n) = -tmul R m n := linear_map.map_neg (coe_fn (mk R M N) m) n theorem tmul_sub {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} [add_comm_group M] [add_comm_group N] [semimodule R M] [semimodule R N] (m : M) (n₁ : N) (n₂ : N) : tmul R m (n₁ - n₂) = tmul R m n₁ - tmul R m n₂ := linear_map.map_sub (coe_fn (mk R M N) m) n₁ n₂ theorem sub_tmul {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} [add_comm_group M] [add_comm_group N] [semimodule R M] [semimodule R N] (m₁ : M) (m₂ : M) (n : N) : tmul R (m₁ - m₂) n = tmul R m₁ n - tmul R m₂ n := linear_map.map_sub₂ (mk R M N) m₁ m₂ n /-- While the tensor product will automatically inherit a ℤ-module structure from `add_comm_group.int_module`, that structure won't be compatible with lemmas like `tmul_smul` unless we use a `ℤ-module` instance provided by `tensor_product.semimodule'`. When `R` is a `ring` we get the required `tensor_product.compatible_smul` instance through `is_scalar_tower`, but when it is only a `semiring` we need to build it from scratch. The instance diamond in `compatible_smul` doesn't matter because it's in `Prop`. -/ protected instance compatible_smul.int {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} [add_comm_group M] [add_comm_group N] [semimodule R M] [semimodule R N] [semimodule ℤ M] [semimodule ℤ N] : compatible_smul R ℤ M N := compatible_smul.mk sorry end tensor_product namespace linear_map @[simp] theorem ltensor_sub {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_group M] [add_comm_group N] [add_comm_group P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R N P) (g : linear_map R N P) : ltensor M (f - g) = ltensor M f - ltensor M g := sorry @[simp] theorem rtensor_sub {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_group M] [add_comm_group N] [add_comm_group P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R N P) (g : linear_map R N P) : rtensor M (f - g) = rtensor M f - rtensor M g := sorry @[simp] theorem ltensor_neg {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_group M] [add_comm_group N] [add_comm_group P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R N P) : ltensor M (-f) = -ltensor M f := sorry @[simp] theorem rtensor_neg {R : Type u_1} [comm_semiring R] {M : Type u_2} {N : Type u_3} {P : Type u_4} [add_comm_group M] [add_comm_group N] [add_comm_group P] [semimodule R M] [semimodule R N] [semimodule R P] (f : linear_map R N P) : rtensor M (-f) = -rtensor M f := sorry
01839cf4feaf40773f6cde635b813cef918bd8a1
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/match_convoy3.lean
8d65aa7efc94510b70f0b887921f1dd02667b8fb
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
1,555
lean
constant bag_setoid : ∀ A, setoid (list A) attribute [instance] bag_setoid noncomputable definition bag (A : Type) : Type := quot (bag_setoid A) constant subcount : ∀ {A}, list A → list A → bool constant list.count : ∀ {A}, A → list A → nat constant all_of_subcount_eq_tt : ∀ {A} {l₁ l₂ : list A}, subcount l₁ l₂ = tt → ∀ a, list.count a l₁ ≤ list.count a l₂ constant ex_of_subcount_eq_ff : ∀ {A} {l₁ l₂ : list A}, subcount l₁ l₂ = ff → ∃ a, ¬ list.count a l₁ ≤ list.count a l₂ noncomputable definition count {A} (a : A) (b : bag A) : nat := quot.lift_on b (λ l, list.count a l) (λ l₁ l₂ h, sorry) noncomputable definition subbag {A} (b₁ b₂ : bag A) := ∀ a, count a b₁ ≤ count a b₂ infix ⊆ := subbag attribute [instance] noncomputable definition decidable_subbag {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quot.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂, rfl : ∀ (b : _), subcount l₁ l₂ = b → _ with | tt, H := is_true (all_of_subcount_eq_tt H) | ff, H := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) (λ w hw, hw (h w))) end) noncomputable definition decidable_subbag2 {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quot.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂, rfl : ∀ (b : _), subcount l₁ l₂ = b → _ with | tt, H := is_true (all_of_subcount_eq_tt H) | ff, H := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) (λ w hw, absurd (h w) hw)) end)
02c131f0660f9cbd934135d4e08315bed85697ae
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/ring_invo.lean
28fc739aec2878f89d66ac0f52bb24d120acbde3
[ "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,022
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow, Kenny Lau -/ import algebra.ring.equiv import algebra.ring.opposite /-! # Ring involutions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines a ring involution as a structure extending `R ≃+* Rᵐᵒᵖ`, with the additional fact `f.involution : (f (f x).unop).unop = x`. ## Notations We provide a coercion to a function `R → Rᵐᵒᵖ`. ## References * <https://en.wikipedia.org/wiki/Involution_(mathematics)#Ring_theory> ## Tags Ring involution -/ variables (R : Type*) set_option old_structure_cmd true /-- A ring involution -/ structure ring_invo [semiring R] extends R ≃+* Rᵐᵒᵖ := (involution' : ∀ x, (to_fun (to_fun x).unop).unop = x) /-- The equivalence of rings underlying a ring involution. -/ add_decl_doc ring_invo.to_ring_equiv /-- `ring_invo_class F R S` states that `F` is a type of ring involutions. You should extend this class when you extend `ring_invo`. -/ class ring_invo_class (F : Type*) (R : out_param Type*) [semiring R] extends ring_equiv_class F R Rᵐᵒᵖ := (involution : ∀ (f : F) (x), (f (f x).unop).unop = x) namespace ring_invo variables {R} [semiring R] instance (R : Type*) [semiring R] : ring_invo_class (ring_invo R) R := { coe := to_fun, inv := inv_fun, coe_injective' := λ e f h₁ h₂, by { cases e, cases f, congr' }, map_add := map_add', map_mul := map_mul', left_inv := left_inv, right_inv := right_inv, involution := involution' } /-- Construct a ring involution from a ring homomorphism. -/ def mk' (f : R →+* Rᵐᵒᵖ) (involution : ∀ r, (f (f r).unop).unop = r) : ring_invo R := { inv_fun := λ r, (f r.unop).unop, left_inv := λ r, involution r, right_inv := λ r, mul_opposite.unop_injective $ involution _, involution' := involution, .. f } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (ring_invo R) (λ _, R → Rᵐᵒᵖ) := ⟨λ f, f.to_ring_equiv.to_fun⟩ @[simp] lemma to_fun_eq_coe (f : ring_invo R) : f.to_fun = f := rfl @[simp] lemma involution (f : ring_invo R) (x : R) : (f (f x).unop).unop = x := f.involution' x instance has_coe_to_ring_equiv : has_coe (ring_invo R) (R ≃+* Rᵐᵒᵖ) := ⟨ring_invo.to_ring_equiv⟩ @[norm_cast] lemma coe_ring_equiv (f : ring_invo R) (a : R) : (f : R ≃+* Rᵐᵒᵖ) a = f a := rfl @[simp] lemma map_eq_zero_iff (f : ring_invo R) {x : R} : f x = 0 ↔ x = 0 := f.to_ring_equiv.map_eq_zero_iff end ring_invo open ring_invo section comm_ring variables [comm_ring R] /-- The identity function of a `comm_ring` is a ring involution. -/ protected def ring_invo.id : ring_invo R := { involution' := λ r, rfl, ..(ring_equiv.to_opposite R) } instance : inhabited (ring_invo R) := ⟨ring_invo.id _⟩ end comm_ring
17a18acdaaf7083e65500b07e7d47bc62d820d49
618003631150032a5676f229d13a079ac875ff77
/src/topology/metric_space/cau_seq_filter.lean
33f9e0e7ce515e7e6343c948458e3df7159dab7f
[ "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,753
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, Sébastien Gouëzel -/ import analysis.normed_space.basic /-! # Completeness in terms of `cauchy` filters vs `is_cau_seq` sequences In this file we apply `metric.complete_of_cauchy_seq_tendsto` to prove that a `normed_ring` is complete in terms of `cauchy` filter if and only if it is complete in terms of `cau_seq` Cauchy sequences. -/ universes u v open set filter open_locale topological_space classical variable {β : Type v} lemma cau_seq.tendsto_limit [normed_ring β] [hn : is_absolute_value (norm : β → ℝ)] (f : cau_seq β norm) [cau_seq.is_complete β norm] : tendsto f at_top (𝓝 f.lim) := _root_.tendsto_nhds.mpr begin intros s os lfs, suffices : ∃ (a : ℕ), ∀ (b : ℕ), b ≥ a → f b ∈ s, by simpa using this, rcases metric.is_open_iff.1 os _ lfs with ⟨ε, ⟨hε, hεs⟩⟩, cases setoid.symm (cau_seq.equiv_lim f) _ hε with N hN, existsi N, intros b hb, apply hεs, dsimp [metric.ball], rw [dist_comm, dist_eq_norm], solve_by_elim end variables [normed_field β] /- This section shows that if we have a uniform space generated by an absolute value, topological completeness and Cauchy sequence completeness coincide. The problem is that there isn't a good notion of "uniform space generated by an absolute value", so right now this is specific to norm. Furthermore, norm only instantiates is_absolute_value on normed_field. This needs to be fixed, since it prevents showing that ℤ_[hp] is complete -/ instance normed_field.is_absolute_value : is_absolute_value (norm : β → ℝ) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ _, norm_eq_zero, abv_add := norm_add_le, abv_mul := normed_field.norm_mul } open metric lemma cauchy_seq.is_cau_seq {f : ℕ → β} (hf : cauchy_seq f) : is_cau_seq norm f := begin cases cauchy_iff.1 hf with hf1 hf2, intros ε hε, rcases hf2 {x | dist x.1 x.2 < ε} (dist_mem_uniformity hε) with ⟨t, ⟨ht, htsub⟩⟩, simp at ht, cases ht with N hN, existsi N, intros j hj, rw ←dist_eq_norm, apply @htsub (f j, f N), apply set.mk_mem_prod; solve_by_elim [le_refl] end lemma cau_seq.cauchy_seq (f : cau_seq β norm) : cauchy_seq f := begin apply cauchy_iff.2, split, { exact map_ne_bot at_top_ne_bot }, { intros s hs, rcases mem_uniformity_dist.1 hs with ⟨ε, ⟨hε, hεs⟩⟩, cases cau_seq.cauchy₂ f hε with N hN, existsi {n | n ≥ N}.image f, simp, split, { existsi N, intros b hb, existsi b, simp [hb] }, { rintros ⟨a, b⟩ ⟨⟨a', ⟨ha'1, ha'2⟩⟩, ⟨b', ⟨hb'1, hb'2⟩⟩⟩, dsimp at ha'1 ha'2 hb'1 hb'2, rw [←ha'2, ←hb'2], apply hεs, rw dist_eq_norm, apply hN; assumption }}, end /-- In a normed field, `cau_seq` coincides with the usual notion of Cauchy sequences. -/ lemma cau_seq_iff_cauchy_seq {α : Type u} [normed_field α] {u : ℕ → α} : is_cau_seq norm u ↔ cauchy_seq u := ⟨λh, cau_seq.cauchy_seq ⟨u, h⟩, λh, h.is_cau_seq⟩ /-- A complete normed field is complete as a metric space, as Cauchy sequences converge by assumption and this suffices to characterize completeness. -/ @[priority 100] -- see Note [lower instance priority] instance complete_space_of_cau_seq_complete [cau_seq.is_complete β norm] : complete_space β := begin apply complete_of_cauchy_seq_tendsto, assume u hu, have C : is_cau_seq norm u := cau_seq_iff_cauchy_seq.2 hu, existsi cau_seq.lim ⟨u, C⟩, rw metric.tendsto_at_top, assume ε εpos, cases (cau_seq.equiv_lim ⟨u, C⟩) _ εpos with N hN, existsi N, simpa [dist_eq_norm] using hN end
46ff399e79c013bf59d3f4eda1d5ab3c1728752d
4326b832bc2eca87dc6275197fb22ce28be1cc82
/src/week04.lean
e2d602764abe9f27f8a0e743325f5304bdfe3e10
[]
no_license
UVM-M52/week04-hdthomas
600986aff5c5c5d7e29a1bf13e230920c973d8df
e1fcf2e2119650b899ddc7c10a3c564c517c1943
refs/heads/master
1,609,219,881,555
1,580,913,706,000
1,580,913,706,000
238,472,560
0
0
null
null
null
null
UTF-8
Lean
false
false
3,278
lean
-- Math 52: Week 4 import .utils.int_refl -- Lakins Definition 1.2.1: definition is_even (n : ℤ) := ∃ (k : ℤ), n = 2 * k definition is_odd (n : ℤ) := ∃ (k : ℤ), n = 2 * k + 1 -- Lakins Definition 2.1.1: Let a, b ∈ ℤ. -- a divides b if there exists n ∈ ℤ such that b = an. -- We write a ∣ b for "a divides b" and say that a is -- a divisor of b. definition divides (a b : ℤ) : Prop := ∃ (n : ℤ), a * n = b -- The notation `a ∣ b` can be used for `divides a b` local infix ∣ := divides -- Lakins Example 2.1.2: example : 3 ∣ 12 := begin unfold divides, existsi (4:ℤ), refl, end -- Theorem: For every integer a, a ∣ a. theorem divides_refl : ∀ (a : ℤ), a ∣ a := begin intro a, unfold divides, existsi (1:ℤ), calc a * 1 = a : by rw mul_one, end -- Proof: Let a ∈ ℤ be arbitrary. We must show that a ∣ a; -- i.e., we must find an integer k such that a = a * k. -- Since a = a * 1 and 1 is an integer, we see that -- a ∣ a is true. □ -- Lakins Proposition 2.1.3: For all integers a, b, c, -- if a ∣ b and b ∣ c, then a ∣ c. theorem divides_trans : ∀ (a b c : ℤ), a ∣ b ∧ b ∣ c → a ∣ c := begin sorry end -- Proof: Let a,b,c ∈ ℤ be arbitrary and assume that -- a ∣ b and b ∣ c. We must show that a ∣ c; i.e., we -- must find an integer k such that c = a * k. -- -- Since a ∣ b, by Definition 2.1.1 we may fix n ∈ ℤ -- such that b = a * n. Similarly, since b | c, we may -- fix m ∈ ℤ such that c = b * m, again by Definition -- 2.1.1. Then -- c = b * m = (a * n) * m = a * (n * m), -- since multiplication of integers is associative -- (Basic Properties of Integers 1.2.3). Since -- n * m ∈ ℤ, we have proved that a ∣ c, by -- Definition 2.1.1, as desired. 􏰟 -- Lakins Exercise 2.1.1: Let a,b, and c be integers. -- For all integers m and n, if a ∣ b and a ∣ c, then -- a ∣ (bm + cn). theorem L211 : ∀ (a b c m n : ℤ), a ∣ b ∧ a ∣ c → a ∣ (b * m + c * n) := begin sorry end -- Theorem: For every integer a, a is even if and only if 2 ∣ a. theorem is_even_iff_two_divides : ∀ (a : ℤ), is_even a ↔ 2 ∣ a := begin sorry end -- We will prove this fact later after we discuss induction. -- For now we take it as an axiom, i.e., as statement that we -- take as true without proof. axiom even_or_odd (a : ℤ) : is_even a ∨ is_odd a -- Lakins Theorem 2.1.9: For all integers a, a(a + 1) is even. theorem even_product : ∀ (a : ℤ), is_even (a * (a + 1)) := begin sorry end -- Proof: Let a ∈ ℤ. We show that a(a + 1) is even by -- considering two cases. -- -- Case I: a is even. -- Then 2 ∣ a, by Definition 1.2.1. Since a ∣ a(a + 1) -- by Definition 2.1.1, we have that 2 ∣ a(a + 1) since -- the divisibility relation is transitive (Proposition -- 2.1.3). Hence a(a + 1) is even. -- -- Case II: a is not even. -- Since a is not even, we know that a is odd. Then -- a+1 is even by Exercise 1.2.2b. Then, using an -- argument similar to that of Case I, we have that -- 2 ∣ (a+1) and (a+1) ∣ a(a+1), and hence 2 ∣ a(a+1) -- by Proposition 2.1.3. Thus a(a + 1) is even. -- -- Hence, since we have considered all possible cases -- for the integer a, we have proved that for all -- integers a, a(a + 1) is even. 􏰟
5f8b4588646caef16144923351c61985accafa8f
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/linear_algebra/basic.lean
42a22b9605fe07e28a7ae8b46c578a85b9cd74db
[ "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
116,456
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 algebra.big_operators.pi import algebra.module.prod import algebra.module.submodule_lattice import data.dfinsupp import data.finsupp.basic import order.compactly_generated import order.omega_complete_partial_order /-! # Linear algebra This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of modules over a ring, submodules, and linear maps. Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in `src/algebra/module`. ## Main definitions * Many constructors for linear maps * `submodule.span s` is defined to be the smallest submodule containing the set `s`. * If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`: that is, elements of `M` are identified if their difference is in `p`. This is itself a module. * The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain respectively. * The general linear group is defined to be the group of invertible linear maps from `M` to itself. ## Main statements * The first, second and third isomorphism laws for modules are proved as `linear_map.quot_ker_equiv_range`, `linear_map.quotient_inf_equiv_sup_quotient` and `submodule.quotient_quotient_equiv_quotient`. ## Notations * We continue to use the notation `M →ₗ[R] M₂` for the type of linear maps from `M` to `M₂` over the ring `R`. * We introduce the notations `M ≃ₗ M₂` and `M ≃ₗ[R] M₂` for `linear_equiv M M₂`. In the first, the ring `R` is implicit. * We introduce the notation `R ∙ v` for the span of a singleton, `submodule.span R {v}`. This is `\.`, not the same as the scalar multiplication `•`/`\bub`. ## Implementation notes We note that, when constructing linear maps, it is convenient to use operations defined on bundled maps (`linear_map.prod`, `linear_map.coprod`, arithmetic operations like `+`) instead of defining a function and proving it is linear. ## Tags linear algebra, vector space, module -/ open function open_locale big_operators pointwise universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} namespace finsupp lemma smul_sum {α : Type u} {β : Type v} {R : Type w} {M : Type y} [has_zero β] [monoid R] [add_comm_monoid M] [distrib_mul_action R M] {v : α →₀ β} {c : R} {h : α → β → M} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum @[simp] lemma sum_smul_index_linear_map' {α : Type u} {R : Type v} {M : Type w} {M₂ : Type x} [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] {v : α →₀ M} {c : R} {h : α → M →ₗ[R] M₂} : (c • v).sum (λ a, h a) = c • (v.sum (λ a, h a)) := begin rw [finsupp.sum_smul_index', finsupp.smul_sum], { simp only [linear_map.map_smul], }, { intro i, exact (h i).map_zero }, end variables (α : Type*) [fintype α] variables (R M) [add_comm_monoid M] [semiring R] [module R M] /-- Given `fintype α`, `linear_equiv_fun_on_fintype R` is the natural `R`-linear equivalence between `α →₀ β` and `α → β`. -/ @[simps apply] noncomputable def linear_equiv_fun_on_fintype : (α →₀ M) ≃ₗ[R] (α → M) := { to_fun := coe_fn, map_add' := λ f g, by { ext, refl }, map_smul' := λ c f, by { ext, refl }, .. equiv_fun_on_fintype } @[simp] lemma linear_equiv_fun_on_fintype_single [decidable_eq α] (x : α) (m : M) : (linear_equiv_fun_on_fintype R M α) (single x m) = pi.single x m := begin ext a, change (equiv_fun_on_fintype (single x m)) a = _, convert _root_.congr_fun (equiv_fun_on_fintype_single x m) a, end @[simp] lemma linear_equiv_fun_on_fintype_symm_single [decidable_eq α] (x : α) (m : M) : (linear_equiv_fun_on_fintype R M α).symm (pi.single x m) = single x m := begin ext a, change (equiv_fun_on_fintype.symm (pi.single x m)) a = _, convert congr_fun (equiv_fun_on_fintype_symm_single x m) a, end @[simp] lemma linear_equiv_fun_on_fintype_symm_coe (f : α →₀ M) : (linear_equiv_fun_on_fintype R M α).symm f = f := by { ext, simp [linear_equiv_fun_on_fintype], } end finsupp section open_locale classical /-- decomposing `x : ι → R` as a sum along the canonical basis -/ lemma pi_eq_sum_univ {ι : Type u} [fintype ι] {R : Type v} [semiring R] (x : ι → R) : x = ∑ i, x i • (λj, if i = j then 1 else 0) := by { ext, simp } end /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [module R M] [module R M₂] [module R M₃] [module R M₄] variables (f g : M →ₗ[R] M₂) include R theorem comp_assoc (g : M₂ →ₗ[R] M₃) (h : M₃ →ₗ[R] M₄) : (h.comp g).comp f = h.comp (g.comp f) := rfl /-- The restriction of a linear map `f : M → M₂` to a submodule `p ⊆ M` gives a linear map `p → M₂`. -/ def dom_restrict (f : M →ₗ[R] M₂) (p : submodule R M) : p →ₗ[R] M₂ := f.comp p.subtype @[simp] lemma dom_restrict_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) : f.dom_restrict p x = f x := rfl /-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a linear map M₂ → p. -/ def cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h : ∀c, f c ∈ p) : M₂ →ₗ[R] p := by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp @[simp] theorem cod_restrict_apply (p : submodule R M) (f : M₂ →ₗ[R] M) {h} (x : M₂) : (cod_restrict p f h x : M) = f x := rfl @[simp] lemma comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) (g : M₃ →ₗ[R] M) : (cod_restrict p f h).comp g = cod_restrict p (f.comp g) (assume b, h _) := ext $ assume b, rfl @[simp] lemma subtype_comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- Restrict domain and codomain of an endomorphism. -/ def restrict (f : M →ₗ[R] M) {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p →ₗ[R] p := (f.dom_restrict p).cod_restrict p $ set_like.forall.2 hf lemma restrict_apply {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) (x : p) : f.restrict hf x = ⟨f x, hf x.1 x.2⟩ := rfl lemma subtype_comp_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p.subtype.comp (f.restrict hf) = f.dom_restrict p := rfl lemma restrict_eq_cod_restrict_dom_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : f.restrict hf = (f.dom_restrict p).cod_restrict p (λ x, hf x.1 x.2) := rfl lemma restrict_eq_dom_restrict_cod_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x, f x ∈ p) : f.restrict (λ x _, hf x) = (f.cod_restrict p hf).dom_restrict p := rfl /-- The constant 0 map is linear. -/ instance : has_zero (M →ₗ[R] M₂) := ⟨{ to_fun := 0, map_add' := by simp, map_smul' := by simp }⟩ instance : inhabited (M →ₗ[R] M₂) := ⟨0⟩ @[simp] lemma zero_apply (x : M) : (0 : M →ₗ[R] M₂) x = 0 := rfl @[simp] lemma default_def : default (M →ₗ[R] M₂) = 0 := rfl instance unique_of_left [subsingleton M] : unique (M →ₗ[R] M₂) := { uniq := λ f, ext $ λ x, by rw [subsingleton.elim x 0, map_zero, map_zero], .. linear_map.inhabited } instance unique_of_right [subsingleton M₂] : unique (M →ₗ[R] M₂) := coe_injective.unique /-- The sum of two linear maps is linear. -/ instance : has_add (M →ₗ[R] M₂) := ⟨λ f g, { to_fun := f + g, map_add' := by simp [add_comm, add_left_comm], map_smul' := by simp [smul_add] }⟩ @[simp] lemma add_apply (x : M) : (f + g) x = f x + g x := rfl /-- The type of linear maps is an additive monoid. -/ instance : add_comm_monoid (M →ₗ[R] M₂) := { zero := 0, add := (+), add_assoc := by intros; ext; simp [add_comm, add_left_comm], zero_add := by intros; ext; simp [add_comm, add_left_comm], add_zero := by intros; ext; simp [add_comm, add_left_comm], add_comm := by intros; ext; simp [add_comm, add_left_comm], nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smul, smul_comm n c (f x)] }, nsmul_zero' := λ f, by { ext x, simp }, nsmul_succ' := λ n f, by { ext x, simp [nat.succ_eq_one_add, add_nsmul] } } /-- Evaluation of an `R`-linear map at a fixed `a`, as an `add_monoid_hom`. -/ def eval_add_monoid_hom (a : M) : (M →ₗ[R] M₂) →+ M₂ := { to_fun := λ f, f a, map_add' := λ f g, linear_map.add_apply f g a, map_zero' := rfl } lemma add_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) : (h + g).comp f = h.comp f + g.comp f := rfl lemma comp_add (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) : h.comp (f + g) = h.comp f + h.comp g := by { ext, simp } /-- `linear_map.to_add_monoid_hom` promoted to an `add_monoid_hom` -/ def to_add_monoid_hom' : (M →ₗ[R] M₂) →+ (M →+ M₂) := { to_fun := to_add_monoid_hom, map_zero' := by ext; refl, map_add' := by intros; ext; refl } lemma sum_apply (t : finset ι) (f : ι → M →ₗ[R] M₂) (b : M) : (∑ d in t, f d) b = ∑ d in t, f d b := add_monoid_hom.map_sum ((add_monoid_hom.eval b).comp to_add_monoid_hom') f _ section smul_right variables {S : Type*} [semiring S] [module R S] [module S M] [is_scalar_tower R S M] /-- When `f` is an `R`-linear map taking values in `S`, then `λb, f b • x` is an `R`-linear map. -/ def smul_right (f : M₂ →ₗ[R] S) (x : M) : M₂ →ₗ[R] M := { to_fun := λb, f b • x, map_add' := λ x y, by rw [f.map_add, add_smul], map_smul' := λ b y, by rw [f.map_smul, smul_assoc] } @[simp] theorem coe_smul_right (f : M₂ →ₗ[R] S) (x : M) : (smul_right f x : M₂ → M) = λ c, f c • x := rfl theorem smul_right_apply (f : M₂ →ₗ[R] S) (x : M) (c : M₂) : smul_right f x c = f c • x := rfl end smul_right instance : has_one (M →ₗ[R] M) := ⟨linear_map.id⟩ instance : has_mul (M →ₗ[R] M) := ⟨linear_map.comp⟩ lemma one_eq_id : (1 : M →ₗ[R] M) = id := rfl lemma mul_eq_comp (f g : M →ₗ[R] M) : f * g = f.comp g := rfl @[simp] lemma one_apply (x : M) : (1 : M →ₗ[R] M) x = x := rfl @[simp] lemma mul_apply (f g : M →ₗ[R] M) (x : M) : (f * g) x = f (g x) := rfl lemma coe_one : ⇑(1 : M →ₗ[R] M) = _root_.id := rfl lemma coe_mul (f g : M →ₗ[R] M) : ⇑(f * g) = f ∘ g := rfl instance [nontrivial M] : nontrivial (module.End R M) := begin obtain ⟨m, ne⟩ := (nontrivial_iff_exists_ne (0 : M)).mp infer_instance, exact nontrivial_of_ne 1 0 (λ p, ne (linear_map.congr_fun p m)), end @[simp] theorem comp_zero : f.comp (0 : M₃ →ₗ[R] M) = 0 := ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero] @[simp] theorem zero_comp : (0 : M₂ →ₗ[R] M₃).comp f = 0 := rfl @[simp, norm_cast] lemma coe_fn_sum {ι : Type*} (t : finset ι) (f : ι → M →ₗ[R] M₂) : ⇑(∑ i in t, f i) = ∑ i in t, (f i : M → M₂) := add_monoid_hom.map_sum ⟨@to_fun R M M₂ _ _ _ _ _, rfl, λ x y, rfl⟩ _ _ instance : monoid (M →ₗ[R] M) := by refine_struct { mul := (*), one := (1 : M →ₗ[R] M), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩ }; intros; try { refl }; apply linear_map.ext; simp {proj := ff} @[simp] lemma pow_apply (f : M →ₗ[R] M) (n : ℕ) (m : M) : (f^n) m = (f^[n] m) := begin induction n with n ih, { refl, }, { simp only [function.comp_app, function.iterate_succ, linear_map.mul_apply, pow_succ, ih], exact (function.commute.iterate_self _ _ m).symm, }, end lemma pow_map_zero_of_le {f : module.End R M} {m : M} {k l : ℕ} (hk : k ≤ l) (hm : (f^k) m = 0) : (f^l) m = 0 := by rw [← nat.sub_add_cancel hk, pow_add, mul_apply, hm, map_zero] lemma commute_pow_left_of_commute {f : M →ₗ[R] M₂} {g : module.End R M} {g₂ : module.End R M₂} (h : g₂.comp f = f.comp g) (k : ℕ) : (g₂^k).comp f = f.comp (g^k) := begin induction k with k ih, { simpa only [pow_zero], }, { rw [pow_succ, pow_succ, linear_map.mul_eq_comp, linear_map.comp_assoc, ih, ← linear_map.comp_assoc, h, linear_map.comp_assoc, linear_map.mul_eq_comp], }, end lemma submodule_pow_eq_zero_of_pow_eq_zero {N : submodule R M} {g : module.End R N} {G : module.End R M} (h : G.comp N.subtype = N.subtype.comp g) {k : ℕ} (hG : G^k = 0) : g^k = 0 := begin ext m, have hg : N.subtype.comp (g^k) m = 0, { rw [← commute_pow_left_of_commute h, hG, zero_comp, zero_apply], }, simp only [submodule.subtype_apply, comp_app, submodule.coe_eq_zero, coe_comp] at hg, rw [hg, linear_map.zero_apply], end lemma coe_pow (f : M →ₗ[R] M) (n : ℕ) : ⇑(f^n) = (f^[n]) := by { ext m, apply pow_apply, } @[simp] lemma id_pow (n : ℕ) : (id : M →ₗ[R] M)^n = id := one_pow n section variables {f' : M →ₗ[R] M} lemma iterate_succ (n : ℕ) : (f' ^ (n + 1)) = comp (f' ^ n) f' := by rw [pow_succ', mul_eq_comp] lemma iterate_surjective (h : surjective f') : ∀ n : ℕ, surjective ⇑(f' ^ n) | 0 := surjective_id | (n + 1) := by { rw [iterate_succ], exact surjective.comp (iterate_surjective n) h, } lemma iterate_injective (h : injective f') : ∀ n : ℕ, injective ⇑(f' ^ n) | 0 := injective_id | (n + 1) := by { rw [iterate_succ], exact injective.comp (iterate_injective n) h, } lemma iterate_bijective (h : bijective f') : ∀ n : ℕ, bijective ⇑(f' ^ n) | 0 := bijective_id | (n + 1) := by { rw [iterate_succ], exact bijective.comp (iterate_bijective n) h, } lemma injective_of_iterate_injective {n : ℕ} (hn : n ≠ 0) (h : injective ⇑(f' ^ n)) : injective f' := begin rw [← nat.succ_pred_eq_of_pos (pos_iff_ne_zero.mpr hn), iterate_succ, coe_comp] at h, exact injective.of_comp h, end end section open_locale classical /-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements of the canonical basis. -/ lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) : f x = ∑ i, x i • (f (λj, if i = j then 1 else 0)) := begin conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] }, apply finset.sum_congr rfl (λl hl, _), rw f.map_smul end end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_monoid M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] (f g : M →ₗ[R] M₂) /-- The negation of a linear map is linear. -/ instance : has_neg (M →ₗ[R] M₂) := ⟨λ f, { to_fun := -f, map_add' := by simp [add_comm], map_smul' := by simp }⟩ @[simp] lemma neg_apply (x : M) : (- f) x = - f x := rfl @[simp] lemma comp_neg (g : M₂ →ₗ[R] M₃) : g.comp (- f) = - g.comp f := by { ext, simp } /-- The negation of a linear map is linear. -/ instance : has_sub (M →ₗ[R] M₂) := ⟨λ f g, { to_fun := f - g, map_add' := λ x y, by simp only [pi.sub_apply, map_add, add_sub_comm], map_smul' := λ r x, by simp only [pi.sub_apply, map_smul, smul_sub] }⟩ @[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl lemma sub_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) : (g - h).comp f = g.comp f - h.comp f := rfl lemma comp_sub (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) : h.comp (g - f) = h.comp g - h.comp f := by { ext, simp } /-- The type of linear maps is an additive group. -/ instance : add_comm_group (M →ₗ[R] M₂) := by refine { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, add_left_neg := _, nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smul, smul_comm n c (f x)] }, gsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smul, smul_comm n c (f x)] }, gsmul_zero' := _, gsmul_succ' := _, gsmul_neg' := _, .. linear_map.add_comm_monoid }; intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg, add_smul, nat.succ_eq_add_one] end add_comm_group section has_scalar variables {S : Type*} [semiring R] [monoid S] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [module R M] [module R M₂] [module R M₃] [distrib_mul_action S M₂] [smul_comm_class R S M₂] (f : M →ₗ[R] M₂) instance : has_scalar S (M →ₗ[R] M₂) := ⟨λ a f, { to_fun := a • f, map_add' := λ x y, by simp only [pi.smul_apply, f.map_add, smul_add], map_smul' := λ c x, by simp only [pi.smul_apply, f.map_smul, smul_comm c] }⟩ @[simp] lemma smul_apply (a : S) (x : M) : (a • f) x = a • f x := rfl instance {T : Type*} [monoid T] [distrib_mul_action T M₂] [smul_comm_class R T M₂] [smul_comm_class S T M₂] : smul_comm_class S T (M →ₗ[R] M₂) := ⟨λ a b f, ext $ λ x, smul_comm _ _ _⟩ -- example application of this instance: if S -> T -> R are homomorphisms of commutative rings and -- M and M₂ are R-modules then the S-module and T-module structures on Hom_R(M,M₂) are compatible. instance {T : Type*} [monoid T] [has_scalar S T] [distrib_mul_action T M₂] [smul_comm_class R T M₂] [is_scalar_tower S T M₂] : is_scalar_tower S T (M →ₗ[R] M₂) := { smul_assoc := λ _ _ _, ext $ λ _, smul_assoc _ _ _ } instance : distrib_mul_action S (M →ₗ[R] M₂) := { one_smul := λ f, ext $ λ _, one_smul _ _, mul_smul := λ c c' f, ext $ λ _, mul_smul _ _ _, smul_add := λ c f g, ext $ λ x, smul_add _ _ _, smul_zero := λ c, ext $ λ x, smul_zero _ } theorem smul_comp (a : S) (g : M₃ →ₗ[R] M₂) (f : M →ₗ[R] M₃) : (a • g).comp f = a • (g.comp f) := rfl end has_scalar section module variables {S : Type*} [semiring R] [semiring S] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [module R M] [module R M₂] [module R M₃] [module S M₂] [module S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃] (f : M →ₗ[R] M₂) instance : module S (M →ₗ[R] M₂) := { add_smul := λ a b f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } variable (S) /-- Applying a linear map at `v : M`, seen as `S`-linear map from `M →ₗ[R] M₂` to `M₂`. See `linear_map.applyₗ` for a version where `S = R`. -/ @[simps] def applyₗ' : M →+ (M →ₗ[R] M₂) →ₗ[S] M₂ := { to_fun := λ v, { to_fun := λ f, f v, map_add' := λ f g, f.add_apply g v, map_smul' := λ x f, f.smul_apply x v }, map_zero' := linear_map.ext $ λ f, f.map_zero, map_add' := λ x y, linear_map.ext $ λ f, f.map_add _ _ } section variables (R M) /-- The equivalence between R-linear maps from `R` to `M`, and points of `M` itself. This says that the forgetful functor from `R`-modules to types is representable, by `R`. This as an `S`-linear equivalence, under the assumption that `S` acts on `M` commuting with `R`. When `R` is commutative, we can take this to be the usual action with `S = R`. Otherwise, `S = ℕ` shows that the equivalence is additive. See note [bundled maps over different rings]. -/ @[simps] def ring_lmap_equiv_self [module S M] [smul_comm_class R S M] : (R →ₗ[R] M) ≃ₗ[S] M := { to_fun := λ f, f 1, inv_fun := smul_right (1 : R →ₗ[R] R), left_inv := λ f, by { ext, simp }, right_inv := λ x, by simp, .. applyₗ' S (1 : R) } end end module section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] variables (f g : M →ₗ[R] M₂) include R theorem comp_smul (g : M₂ →ₗ[R] M₃) (a : R) : g.comp (a • f) = a • (g.comp f) := ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl /-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of linear maps `M₂ → M₃`. -/ def comp_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) := { to_fun := f.comp, map_add' := λ _ _, linear_map.ext $ λ _, f.map_add _ _, map_smul' := λ _ _, linear_map.ext $ λ _, f.map_smul _ _ } /-- Applying a linear map at `v : M`, seen as a linear map from `M →ₗ[R] M₂` to `M₂`. See also `linear_map.applyₗ'` for a version that works with two different semirings. This is the `linear_map` version of `add_monoid_hom.eval`. -/ @[simps] def applyₗ : M →ₗ[R] (M →ₗ[R] M₂) →ₗ[R] M₂ := { to_fun := λ v, { to_fun := λ f, f v, ..applyₗ' R v }, map_smul' := λ x y, linear_map.ext $ λ f, f.map_smul _ _, ..applyₗ' R } /-- Alternative version of `dom_restrict` as a linear map. -/ def dom_restrict' (p : submodule R M) : (M →ₗ[R] M₂) →ₗ[R] (p →ₗ[R] M₂) := { to_fun := λ φ, φ.dom_restrict p, map_add' := by simp [linear_map.ext_iff], map_smul' := by simp [linear_map.ext_iff] } @[simp] lemma dom_restrict'_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) : dom_restrict' p f x = f x := rfl end comm_semiring section semiring variables [semiring R] [add_comm_monoid M] [module R M] instance endomorphism_semiring : semiring (M →ₗ[R] M) := by refine_struct { mul := (*), one := (1 : M →ₗ[R] M), zero := 0, add := (+), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩, .. linear_map.add_comm_monoid, .. }; intros; try { refl }; apply linear_map.ext; simp {proj := ff} end semiring section ring variables [ring R] [add_comm_group M] [module R M] instance endomorphism_ring : ring (M →ₗ[R] M) := { ..linear_map.endomorphism_semiring, ..linear_map.add_comm_group } end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] /-- The family of linear maps `M₂ → M` parameterised by `f ∈ M₂ → R`, `x ∈ M`, is linear in `f`, `x`. -/ def smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M := { to_fun := λ f, { to_fun := linear_map.smul_right f, map_add' := λ m m', by { ext, apply smul_add, }, map_smul' := λ c m, by { ext, apply smul_comm, } }, map_add' := λ f f', by { ext, apply add_smul, }, map_smul' := λ c f, by { ext, apply mul_smul, } } @[simp] lemma smul_rightₗ_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_rightₗ : (M₂ →ₗ R) →ₗ M →ₗ M₂ →ₗ M) f x c = (f c) • x := rfl end comm_ring end linear_map /-- The `ℕ`-linear equivalence between additive morphisms `A →+ B` and `ℕ`-linear morphisms `A →ₗ[ℕ] B`. -/ @[simps] def add_monoid_hom_lequiv_nat {A B : Type*} [add_comm_monoid A] [add_comm_monoid B] : (A →+ B) ≃ₗ[ℕ] (A →ₗ[ℕ] B) := { to_fun := add_monoid_hom.to_nat_linear_map, inv_fun := linear_map.to_add_monoid_hom, map_add' := by { intros, ext, refl }, map_smul' := by { intros, ext, refl }, left_inv := by { intros f, ext, refl }, right_inv := by { intros f, ext, refl } } /-- The `ℤ`-linear equivalence between additive morphisms `A →+ B` and `ℤ`-linear morphisms `A →ₗ[ℤ] B`. -/ @[simps] def add_monoid_hom_lequiv_int {A B : Type*} [add_comm_group A] [add_comm_group B] : (A →+ B) ≃ₗ[ℤ] (A →ₗ[ℤ] B) := { to_fun := add_monoid_hom.to_int_linear_map, inv_fun := linear_map.to_add_monoid_hom, map_add' := by { intros, ext, refl }, map_smul' := by { intros, ext, refl }, left_inv := by { intros f, ext, refl }, right_inv := by { intros f, ext, refl } } /-! ### Properties of submodules -/ namespace submodule section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set variables {p p'} /-- If two submodules `p` and `p'` satisfy `p ⊆ p'`, then `of_le p p'` is the linear map version of this inclusion. -/ def of_le (h : p ≤ p') : p →ₗ[R] p' := p.subtype.cod_restrict p' $ λ ⟨x, hx⟩, h hx @[simp] theorem coe_of_le (h : p ≤ p') (x : p) : (of_le h x : M) = x := rfl theorem of_le_apply (h : p ≤ p') (x : p) : of_le h x = ⟨x, h x.2⟩ := rfl variables (p p') lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) : q.subtype.comp (of_le h) = p.subtype := by { ext ⟨b, hb⟩, refl } instance add_comm_monoid_submodule : add_comm_monoid (submodule R M) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm } @[simp] lemma add_eq_sup (p q : submodule R M) : p + q = p ⊔ q := rfl @[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl variables (R) @[simp] lemma subsingleton_iff : subsingleton (submodule R M) ↔ subsingleton M := have h : subsingleton (submodule R M) ↔ subsingleton (add_submonoid M), { rw [←subsingleton_iff_bot_eq_top, ←subsingleton_iff_bot_eq_top], convert to_add_submonoid_eq.symm; refl, }, h.trans add_submonoid.subsingleton_iff @[simp] lemma nontrivial_iff : nontrivial (submodule R M) ↔ nontrivial M := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans $ subsingleton_iff R).trans not_nontrivial_iff_subsingleton.symm) variables {R} instance [subsingleton M] : unique (submodule R M) := ⟨⟨⊥⟩, λ a, @subsingleton.elim _ ((subsingleton_iff R).mpr ‹_›) a _⟩ instance unique' [subsingleton R] : unique (submodule R M) := by haveI := module.subsingleton R M; apply_instance instance [nontrivial M] : nontrivial (submodule R M) := (nontrivial_iff R).mpr ‹_› theorem disjoint_def {p p' : submodule R M} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) := show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp theorem disjoint_def' {p p' : submodule R M} : disjoint p p' ↔ ∀ (x ∈ p) (y ∈ p'), x = y → x = (0:M) := disjoint_def.trans ⟨λ h x hx y hy hxy, h x hx $ hxy.symm ▸ hy, λ h x hx hx', h _ hx x hx' rfl⟩ theorem mem_right_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p} : (x:M) ∈ p' ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x x.2 hx, λ h, h.symm ▸ p'.zero_mem⟩ theorem mem_left_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p'} : (x:M) ∈ p ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x hx x.2, λ h, h.symm ▸ p.zero_mem⟩ /-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/ def map (f : M →ₗ[R] M₂) (p : submodule R M) : submodule R M₂ := { carrier := f '' p, smul_mem' := by rintro a _ ⟨b, hb, rfl⟩; exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩, .. p.to_add_submonoid.map f.to_add_monoid_hom } @[simp] lemma map_coe (f : M →ₗ[R] M₂) (p : submodule R M) : (map f p : set M₂) = f '' p := rfl @[simp] lemma mem_map {f : M →ₗ[R] M₂} {p : submodule R M} {x : M₂} : x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl theorem mem_map_of_mem {f : M →ₗ[R] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p := set.mem_image_of_mem _ h lemma apply_coe_mem_map (f : M →ₗ[R] M₂) {p : submodule R M} (r : p) : f r ∈ map f p := mem_map_of_mem r.prop @[simp] lemma map_id : map linear_map.id p = p := submodule.ext $ λ a, by simp lemma map_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M) : map (g.comp f) p = map g (map f p) := set_like.coe_injective $ by simp [map_coe]; rw ← image_comp lemma map_mono {f : M →ₗ[R] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' := image_subset _ @[simp] lemma map_zero : map (0 : M →ₗ[R] M₂) p = ⊥ := have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩, ext $ by simp [this, eq_comm] lemma range_map_nonempty (N : submodule R M) : (set.range (λ ϕ, submodule.map ϕ N : (M →ₗ[R] M₂) → submodule R M₂)).nonempty := ⟨_, set.mem_range.mpr ⟨0, rfl⟩⟩ /-- The pushforward of a submodule by an injective linear map is linearly equivalent to the original submodule. -/ noncomputable def equiv_map_of_injective (f : M →ₗ[R] M₂) (i : injective f) (p : submodule R M) : p ≃ₗ[R] p.map f := { map_add' := by { intros, simp, refl, }, map_smul' := by { intros, simp, refl, }, ..(equiv.set.image f p i) } @[simp] lemma coe_equiv_map_of_injective_apply (f : M →ₗ[R] M₂) (i : injective f) (p : submodule R M) (x : p) : (equiv_map_of_injective f i p x : M₂) = f x := rfl /-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/ def comap (f : M →ₗ[R] M₂) (p : submodule R M₂) : submodule R M := { carrier := f ⁻¹' p, smul_mem' := λ a x h, by simp [p.smul_mem _ h], .. p.to_add_submonoid.comap f.to_add_monoid_hom } @[simp] lemma comap_coe (f : M →ₗ[R] M₂) (p : submodule R M₂) : (comap f p : set M) = f ⁻¹' p := rfl @[simp] lemma mem_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : x ∈ comap f p ↔ f x ∈ p := iff.rfl lemma comap_id : comap linear_map.id p = p := set_like.coe_injective rfl lemma comap_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M₃) : comap (g.comp f) p = comap f (comap g p) := rfl lemma comap_mono {f : M →ₗ[R] M₂} {q q' : submodule R M₂} : q ≤ q' → comap f q ≤ comap f q' := preimage_mono lemma map_le_iff_le_comap {f : M →ₗ[R] M₂} {p : submodule R M} {q : submodule R M₂} : map f p ≤ q ↔ p ≤ comap f q := image_subset_iff lemma gc_map_comap (f : M →ₗ[R] M₂) : galois_connection (map f) (comap f) | p q := map_le_iff_le_comap @[simp] lemma map_bot (f : M →ₗ[R] M₂) : map f ⊥ = ⊥ := (gc_map_comap f).l_bot @[simp] lemma map_sup (f : M →ₗ[R] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' := (gc_map_comap f).l_sup @[simp] lemma map_supr {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M) : map f (⨆i, p i) = (⨆i, map f (p i)) := (gc_map_comap f).l_supr @[simp] lemma comap_top (f : M →ₗ[R] M₂) : comap f ⊤ = ⊤ := rfl @[simp] lemma comap_inf (f : M →ₗ[R] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl @[simp] lemma comap_infi {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M₂) : comap f (⨅i, p i) = (⨅i, comap f (p i)) := (gc_map_comap f).u_infi @[simp] lemma comap_zero : comap (0 : M →ₗ[R] M₂) q = ⊤ := ext $ by simp lemma map_comap_le (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) ≤ q := (gc_map_comap f).l_u_le _ lemma le_comap_map (f : M →ₗ[R] M₂) (p : submodule R M) : p ≤ comap f (map f p) := (gc_map_comap f).le_u_l _ section galois_coinsertion variables {f : M →ₗ[R] M₂} (hf : 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 (p : submodule R M) : (p.map f).comap f = p := (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 (p q : submodule R M) : (p.map f ⊓ q.map f).comap f = p ⊓ q := (gci_map_comap hf).u_inf_l _ _ lemma comap_infi_map_of_injective (S : ι → submodule R M) : (⨅ i, (S i).map f).comap f = infi S := (gci_map_comap hf).u_infi_l _ lemma comap_sup_map_of_injective (p q : submodule R M) : (p.map f ⊔ q.map f).comap f = p ⊔ q := (gci_map_comap hf).u_sup_l _ _ lemma comap_supr_map_of_injective (S : ι → submodule R M) : (⨆ i, (S i).map f).comap f = supr S := (gci_map_comap hf).u_supr_l _ lemma map_le_map_iff_of_injective (p q : submodule R M) : p.map f ≤ q.map f ↔ p ≤ q := (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 --TODO(Mario): is there a way to prove this from order properties? lemma map_inf_eq_map_inf_comap {f : M →ₗ[R] M₂} {p : submodule R M} {p' : submodule R M₂} : map f p ⊓ p' = map f (p ⊓ comap f p') := le_antisymm (by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩) (le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right)) lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' := ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩ lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0 | ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb section variables (R) /-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/ def span (s : set M) : submodule R M := Inf {p | s ⊆ p} end variables {s t : set M} lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_bInter_iff lemma subset_span : s ⊆ span R s := λ x h, mem_span.2 $ λ p hp, hp h lemma span_le {p} : span R s ≤ p ↔ s ⊆ p := ⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩ lemma span_mono (h : s ⊆ t) : span R s ≤ span R t := span_le.2 $ subset.trans h subset_span lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p := le_antisymm (span_le.2 h₁) h₂ @[simp] lemma span_eq : span R (p : set M) = p := span_eq_of_le _ (subset.refl _) subset_span lemma map_span (f : M →ₗ[R] M₂) (s : set M) : (span R s).map f = span R (f '' s) := eq.symm $ span_eq_of_le _ (set.image_subset f subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ λ x hx, subset_span ⟨x, hx, rfl⟩ alias submodule.map_span ← linear_map.map_span lemma map_span_le {R M M₂ : Type*} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M →ₗ[R] M₂) (s : set M) (N : submodule R M₂) : map f (span R s) ≤ N ↔ ∀ m ∈ s, f m ∈ N := begin rw [f.map_span, span_le, set.image_subset_iff], exact iff.rfl end alias submodule.map_span_le ← linear_map.map_span_le /- See also `span_preimage_eq` below. -/ lemma span_preimage_le (f : M →ₗ[R] M₂) (s : set M₂) : span R (f ⁻¹' s) ≤ (span R s).comap f := by { rw [span_le, comap_coe], exact preimage_mono (subset_span), } alias submodule.span_preimage_le ← linear_map.span_preimage_le /-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is preserved under addition and scalar multiplication, then `p` holds for all elements of the span of `s`. -/ @[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (a:R) x, p x → p (a • x)) : p x := (@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h lemma span_nat_eq_add_submonoid_closure (s : set M) : (span ℕ s).to_add_submonoid = add_submonoid.closure s := begin refine eq.symm (add_submonoid.closure_eq_of_le subset_span _), apply add_submonoid.to_nat_submodule.symm.to_galois_connection.l_le _, rw span_le, exact add_submonoid.subset_closure, end @[simp] lemma span_nat_eq (s : add_submonoid M) : (span ℕ (s : set M)).to_add_submonoid = s := by rw [span_nat_eq_add_submonoid_closure, s.closure_eq] lemma span_int_eq_add_subgroup_closure {M : Type*} [add_comm_group M] (s : set M) : (span ℤ s).to_add_subgroup = add_subgroup.closure s := eq.symm $ add_subgroup.closure_eq_of_le _ subset_span $ λ x hx, span_induction hx (λ x hx, add_subgroup.subset_closure hx) (add_subgroup.zero_mem _) (λ _ _, add_subgroup.add_mem _) (λ _ _ _, add_subgroup.gsmul_mem _ ‹_› _) @[simp] lemma span_int_eq {M : Type*} [add_comm_group M] (s : add_subgroup M) : (span ℤ (s : set M)).to_add_subgroup = s := by rw [span_int_eq_add_subgroup_closure, s.closure_eq] section variables (R M) /-- `span` forms a Galois insertion with the coercion from submodule to set. -/ protected def gi : galois_insertion (@span R M _ _ _) coe := { choice := λ s _, span R s, gc := λ s t, span_le, le_l_u := λ s, subset_span, choice_eq := λ s h, rfl } end @[simp] lemma span_empty : span R (∅ : set M) = ⊥ := (submodule.gi R M).gc.l_bot @[simp] lemma span_univ : span R (univ : set M) = ⊤ := eq_top_iff.2 $ set_like.le_def.2 $ subset_span lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t := (submodule.gi R M).gc.l_sup lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) := (submodule.gi R M).gc.l_supr lemma span_eq_supr_of_singleton_spans (s : set M) : span R s = ⨆ x ∈ s, span R {x} := by simp only [←span_Union, set.bUnion_of_singleton s] @[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) : ((supr S : submodule R M) : set M) = ⋃ i, S i := begin refine subset.antisymm _ (Union_subset $ le_supr S), suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i), by simpa only [span_Union, span_eq] using this, refine (λ x hx, span_induction hx (λ _, id) _ _ _); simp only [mem_Union, exists_imp_distrib], { exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) }, { intros x y i hi j hj, rcases H i j with ⟨k, ik, jk⟩, exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ }, { exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ }, end lemma sum_mem_bsupr {ι : Type*} {s : finset ι} {f : ι → M} {p : ι → submodule R M} (h : ∀ i ∈ s, f i ∈ p i) : ∑ i in s, f i ∈ ⨆ i ∈ s, p i := sum_mem _ $ λ i hi, mem_supr_of_mem i $ mem_supr_of_mem hi (h i hi) lemma sum_mem_supr {ι : Type*} [fintype ι] {f : ι → M} {p : ι → submodule R M} (h : ∀ i, f i ∈ p i) : ∑ i, f i ∈ ⨆ i, p i := sum_mem _ $ λ i hi, mem_supr_of_mem i (h i) @[simp] theorem mem_supr_of_directed {ι} [nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) {x} : x ∈ supr S ↔ ∃ i, x ∈ S i := by { rw [← set_like.mem_coe, coe_supr_of_directed S H, mem_Union], refl } theorem mem_Sup_of_directed {s : set (submodule R M)} {z} (hs : s.nonempty) (hdir : directed_on (≤) s) : z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y := begin haveI : nonempty s := hs.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed _ hdir.directed_coe, set_coe.exists, subtype.coe_mk] end @[norm_cast, simp] lemma coe_supr_of_chain (a : ℕ →ₘ submodule R M) : (↑(⨆ k, a k) : set M) = ⋃ k, (a k : set M) := coe_supr_of_directed a a.monotone.directed_le /-- We can regard `coe_supr_of_chain` as the statement that `coe : (submodule R M) → set M` is Scott continuous for the ω-complete partial order induced by the complete lattice structures. -/ lemma coe_scott_continuous : omega_complete_partial_order.continuous' (coe : submodule R M → set M) := ⟨set_like.coe_mono, coe_supr_of_chain⟩ @[simp] lemma mem_supr_of_chain (a : ℕ →ₘ submodule R M) (m : M) : m ∈ (⨆ k, a k) ↔ ∃ k, m ∈ a k := mem_supr_of_directed a a.monotone.directed_le section variables {p p'} lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x := ⟨λ h, begin rw [← span_eq p, ← span_eq p', ← span_union] at h, apply span_induction h, { rintro y (h | h), { exact ⟨y, h, 0, by simp, by simp⟩ }, { exact ⟨0, by simp, y, h, by simp⟩ } }, { exact ⟨0, by simp, 0, by simp⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp [add_assoc]; cc⟩ }, { rintro a _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _ ((le_sup_left : p ≤ p ⊔ p') hy) ((le_sup_right : p' ≤ p ⊔ p') hz)⟩ lemma mem_sup' : x ∈ p ⊔ p' ↔ ∃ (y : p) (z : p'), (y:M) + z = x := mem_sup.trans $ by simp only [set_like.exists, coe_mk] lemma coe_sup : ↑(p ⊔ p') = (p + p' : set M) := by { ext, rw [set_like.mem_coe, mem_sup, set.mem_add], simp, } end /- This is the character `∙`, with escape sequence `\.`, and is thus different from the scalar multiplication character `•`, with escape sequence `\bub`. -/ notation R`∙`:1000 x := span R (@singleton _ _ set.has_singleton x) lemma mem_span_singleton_self (x : M) : x ∈ R ∙ x := subset_span rfl lemma nontrivial_span_singleton {x : M} (h : x ≠ 0) : nontrivial (R ∙ x) := ⟨begin use [0, x, submodule.mem_span_singleton_self x], intros H, rw [eq_comm, submodule.mk_eq_zero] at H, exact h H end⟩ lemma mem_span_singleton {y : M} : x ∈ (R ∙ y) ↔ ∃ a:R, a • y = x := ⟨λ h, begin apply span_induction h, { rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ }, { exact ⟨0, by simp⟩ }, { rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩, exact ⟨a + b, by simp [add_smul]⟩ }, { rintro a _ ⟨b, rfl⟩, exact ⟨a * b, by simp [smul_smul]⟩ } end, by rintro ⟨a, y, rfl⟩; exact smul_mem _ _ (subset_span $ by simp)⟩ lemma le_span_singleton_iff {s : submodule R M} {v₀ : M} : s ≤ (R ∙ v₀) ↔ ∀ v ∈ s, ∃ r : R, r • v₀ = v := by simp_rw [set_like.le_def, mem_span_singleton] lemma span_singleton_eq_top_iff (x : M) : (R ∙ x) = ⊤ ↔ ∀ v, ∃ r : R, r • x = v := begin rw [eq_top_iff, le_span_singleton_iff], finish, end @[simp] lemma span_zero_singleton : (R ∙ (0:M)) = ⊥ := by { ext, simp [mem_span_singleton, eq_comm] } lemma span_singleton_eq_range (y : M) : ↑(R ∙ y) = range ((• y) : R → M) := set.ext $ λ x, mem_span_singleton lemma span_singleton_smul_le (r : R) (x : M) : (R ∙ (r • x)) ≤ R ∙ x := begin rw [span_le, set.singleton_subset_iff, set_like.mem_coe], exact smul_mem _ _ (mem_span_singleton_self _) end lemma span_singleton_smul_eq {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {r : K} (x : E) (hr : r ≠ 0) : (K ∙ (r • x)) = K ∙ x := begin refine le_antisymm (span_singleton_smul_le r x) _, convert span_singleton_smul_le r⁻¹ (r • x), exact (inv_smul_smul' hr _).symm end lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {s : submodule K E} {x : E} : disjoint s (K ∙ x) ↔ (x ∈ s → x = 0) := begin refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩, assume H y hy hyx, obtain ⟨c, hc⟩ := mem_span_singleton.1 hyx, subst y, classical, by_cases hc : c = 0, by simp only [hc, zero_smul], rw [s.smul_mem_iff hc] at hy, rw [H hy, smul_zero] end lemma disjoint_span_singleton' {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {p : submodule K E} {x : E} (x0 : x ≠ 0) : disjoint p (K ∙ x) ↔ x ∉ p := disjoint_span_singleton.trans ⟨λ h₁ h₂, x0 (h₁ h₂), λ h₁ h₂, (h₁ h₂).elim⟩ lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z := begin simp only [← union_singleton, span_union, mem_sup, mem_span_singleton, exists_prop, exists_exists_eq_and], rw [exists_comm], simp only [eq_comm, add_comm, exists_and_distrib_left] end lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s := span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_span : span R (span R s : set M) = span R s := span_eq _ lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 := eq_bot_iff.trans ⟨ λ H x h, (mem_bot R).1 $ H $ subset_span h, λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩ @[simp] lemma span_singleton_eq_bot : (R ∙ x) = ⊥ ↔ x = 0 := span_eq_bot.trans $ by simp @[simp] lemma span_zero : span R (0 : set M) = ⊥ := by rw [←singleton_zero, span_singleton_eq_bot] @[simp] lemma span_image (f : M →ₗ[R] M₂) : span R (f '' s) = map f (span R s) := span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ image_subset_iff.1 subset_span lemma apply_mem_span_image_of_mem_span (f : M →ₗ[R] M₂) {x : M} {s : set M} (h : x ∈ submodule.span R s) : f x ∈ submodule.span R (f '' s) := begin rw submodule.span_image, exact submodule.mem_map_of_mem h end /-- `f` is an explicit argument so we can `apply` this theorem and obtain `h` as a new goal. -/ lemma not_mem_span_of_apply_not_mem_span_image (f : M →ₗ[R] M₂) {x : M} {s : set M} (h : f x ∉ submodule.span R (f '' s)) : x ∉ submodule.span R s := not.imp h (apply_mem_span_image_of_mem_span f) lemma supr_eq_span {ι : Sort w} (p : ι → submodule R M) : (⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) := le_antisymm (supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span) (span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem i hm) lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : (R ∙ m) ≤ p ↔ m ∈ p := by rw [span_le, singleton_subset_iff, set_like.mem_coe] lemma singleton_span_is_compact_element (x : M) : complete_lattice.is_compact_element (span R {x} : submodule R M) := begin rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le, intros d hemp hdir hsup, have : x ∈ Sup d, from (set_like.le_def.mp hsup) (mem_span_singleton_self x), obtain ⟨y, ⟨hyd, hxy⟩⟩ := (mem_Sup_of_directed hemp hdir).mp this, exact ⟨y, ⟨hyd, by simpa only [span_le, singleton_subset_iff]⟩⟩, end instance : is_compactly_generated (submodule R M) := ⟨λ s, ⟨(λ x, span R {x}) '' s, ⟨λ t ht, begin rcases (set.mem_image _ _ _).1 ht with ⟨x, hx, rfl⟩, apply singleton_span_is_compact_element, end, by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, span_eq]⟩⟩⟩ lemma lt_add_iff_not_mem {I : submodule R M} {a : M} : I < I + (R ∙ a) ↔ a ∉ I := begin split, { intro h, by_contra akey, have h1 : I + (R ∙ a) ≤ I, { simp only [add_eq_sup, sup_le_iff], split, { exact le_refl I, }, { exact (span_singleton_le_iff_mem a I).mpr akey, } }, have h2 := gt_of_ge_of_gt h1 h, exact lt_irrefl I h2, }, { intro h, apply set_like.lt_iff_le_and_exists.mpr, split, simp only [add_eq_sup, le_sup_left], use a, split, swap, { assumption, }, { have : (R ∙ a) ≤ I + (R ∙ a) := le_sup_right, exact this (mem_span_singleton_self a), } }, end lemma mem_supr {ι : Sort w} (p : ι → submodule R M) {m : M} : (m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) := begin rw [← span_singleton_le_iff_mem, le_supr_iff], simp only [span_singleton_le_iff_mem], end section open_locale classical /-- For every element in the span of a set, there exists a finite subset of the set such that the element is contained in the span of the subset. -/ lemma mem_span_finite_of_mem_span {S : set M} {x : M} (hx : x ∈ span R S) : ∃ T : finset M, ↑T ⊆ S ∧ x ∈ span R (T : set M) := begin refine span_induction hx (λ x hx, _) _ _ _, { refine ⟨{x}, _, _⟩, { rwa [finset.coe_singleton, set.singleton_subset_iff] }, { rw finset.coe_singleton, exact submodule.mem_span_singleton_self x } }, { use ∅, simp }, { rintros x y ⟨X, hX, hxX⟩ ⟨Y, hY, hyY⟩, refine ⟨X ∪ Y, _, _⟩, { rw finset.coe_union, exact set.union_subset hX hY }, rw [finset.coe_union, span_union, mem_sup], exact ⟨x, hxX, y, hyY, rfl⟩, }, { rintros a x ⟨T, hT, h2⟩, exact ⟨T, hT, smul_mem _ _ h2⟩ } end end /-- The product of two submodules is a submodule. -/ def prod : submodule R (M × M₂) := { carrier := set.prod p q, smul_mem' := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩, .. p.to_add_submonoid.prod q.to_add_submonoid } @[simp] lemma prod_coe : (prod p q : set (M × M₂)) = set.prod p q := rfl @[simp] lemma mem_prod {p : submodule R M} {q : submodule R M₂} {x : M × M₂} : x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod lemma span_prod_le (s : set M) (t : set M₂) : span R (set.prod s t) ≤ prod (span R s) (span R t) := span_le.2 $ set.prod_mono subset_span subset_span @[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M₂)) = ⊤ := by ext; simp @[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M₂)) = ⊥ := by ext ⟨x, y⟩; simp [prod.zero_eq_mk] lemma prod_mono {p p' : submodule R M} {q q' : submodule R M₂} : p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono @[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') := set_like.coe_injective set.prod_inter_prod @[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') := begin refine le_antisymm (sup_le (prod_mono le_sup_left le_sup_left) (prod_mono le_sup_right le_sup_right)) _, simp [set_like.le_def], intros xx yy hxx hyy, rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩, rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩, refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩ end end add_comm_monoid 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 (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set @[simp] lemma neg_coe : -(p : set M) = p := set.ext $ λ x, p.neg_mem_iff @[simp] protected lemma map_neg (f : M →ₗ[R] M₂) : map (-f) p = map f p := ext $ λ y, ⟨λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, f.map_neg x⟩, λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, ((-f).map_neg _).trans (neg_neg (f x))⟩⟩ @[simp] lemma span_neg (s : set M) : span R (-s) = span R s := calc span R (-s) = span R ((-linear_map.id : M →ₗ[R] M) '' s) : by simp ... = map (-linear_map.id) (span R s) : ((-linear_map.id).map_span _).symm ... = span R s : by simp lemma mem_span_insert' {y} {s : set M} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s := begin rw mem_span_insert, split, { rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz, add_assoc]⟩ }, { rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ } end -- TODO(Mario): Factor through add_subgroup /-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/ def quotient_rel : setoid M := ⟨λ x y, x - y ∈ p, λ x, by simp, λ x y h, by simpa using neg_mem _ h, λ x y z h₁ h₂, by simpa [sub_eq_add_neg, add_left_comm, add_assoc] using add_mem _ h₁ h₂⟩ /-- The quotient of a module `M` by a submodule `p ⊆ M`. -/ def quotient : Type* := quotient (quotient_rel p) namespace quotient /-- Map associating to an element of `M` the corresponding element of `M/p`, when `p` is a submodule of `M`. -/ def mk {p : submodule R M} : M → quotient p := quotient.mk' @[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (quotient.mk x : quotient p) = mk x := rfl @[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl @[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq' instance : has_zero (quotient p) := ⟨mk 0⟩ instance : inhabited (quotient p) := ⟨0⟩ @[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl @[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p := by simpa using (quotient.eq p : mk x = 0 ↔ _) instance : has_add (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ h₂⟩ @[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl instance : has_neg (quotient p) := ⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $ λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩ @[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl instance : has_sub (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a - b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ (neg_mem p h₂)⟩ @[simp] theorem mk_sub : (mk (x - y) : quotient p) = mk x - mk y := rfl instance : add_comm_group (quotient p) := { zero := (0 : quotient p), add := (+), neg := has_neg.neg, sub := has_sub.sub, add_assoc := by { rintros ⟨x⟩ ⟨y⟩ ⟨z⟩, simp only [←mk_add p, quot_mk_eq_mk, add_assoc] }, zero_add := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, quot_mk_eq_mk, zero_add] }, add_zero := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, add_zero, quot_mk_eq_mk] }, add_comm := by { rintros ⟨x⟩ ⟨y⟩, simp only [←mk_add p, quot_mk_eq_mk, add_comm] }, add_left_neg := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, ←mk_neg p, quot_mk_eq_mk, add_left_neg] }, sub_eq_add_neg := by { rintros ⟨x⟩ ⟨y⟩, simp only [←mk_add p, ←mk_neg p, ←mk_sub p, sub_eq_add_neg, quot_mk_eq_mk] }, nsmul := λ n x, quotient.lift_on' x (λ x, mk (n • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_of_tower_mem p n h, nsmul_zero' := by { rintros ⟨⟩, simp only [mk_zero, quot_mk_eq_mk, zero_smul], refl }, nsmul_succ' := by { rintros n ⟨⟩, simp only [nat.succ_eq_one_add, add_nsmul, mk_add, quot_mk_eq_mk, one_nsmul], refl }, gsmul := λ n x, quotient.lift_on' x (λ x, mk (n • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_of_tower_mem p n h, gsmul_zero' := by { rintros ⟨⟩, simp only [mk_zero, quot_mk_eq_mk, zero_smul], refl }, gsmul_succ' := by { rintros n ⟨⟩, simp [nat.succ_eq_add_one, add_nsmul, mk_add, quot_mk_eq_mk, one_nsmul, add_smul, add_comm], refl }, gsmul_neg' := by { rintros n ⟨x⟩, simp_rw [gsmul_neg_succ_of_nat, gsmul_coe_nat], refl }, } instance : has_scalar R (quotient p) := ⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_mem p a h⟩ @[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl @[simp] theorem mk_nsmul (n : ℕ) : (mk (n • x) : quotient p) = n • mk x := rfl instance : module R (quotient p) := module.of_core $ by refine {smul := (•), ..}; repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul, -mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm] lemma mk_surjective : function.surjective (@mk _ _ _ _ _ p) := by { rintros ⟨x⟩, exact ⟨x, rfl⟩ } lemma nontrivial_of_lt_top (h : p < ⊤) : nontrivial (p.quotient) := begin obtain ⟨x, _, not_mem_s⟩ := set_like.exists_of_lt h, refine ⟨⟨mk x, 0, _⟩⟩, simpa using not_mem_s end end quotient lemma quot_hom_ext ⦃f g : quotient p →ₗ[R] M₂⦄ (h : ∀ x, f (quotient.mk x) = g (quotient.mk x)) : f = g := linear_map.ext $ λ x, quotient.induction_on' x h end submodule namespace submodule variables [field K] variables [add_comm_group V] [module K V] variables [add_comm_group V₂] [module K V₂] lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) : p.comap (a • f) = p.comap f := by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply] lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) : p.map (a • f) = p.map f := le_antisymm begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) : p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) := by classical; by_cases a = 0; simp [h, comap_smul] lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) : p.map (a • f) = (⨆ h : a ≠ 0, p.map f) := by classical; by_cases a = 0; simp [h, map_smul] end submodule /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] include R open submodule /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. See also `linear_map.eq_on_span'` for a version using `set.eq_on`. -/ lemma eq_on_span {s : set M} {f g : M →ₗ[R] M₂} (H : set.eq_on f g s) ⦃x⦄ (h : x ∈ span R s) : f x = g x := by apply span_induction h H; simp {contextual := tt} /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. This version uses `set.eq_on`, and the hidden argument will expand to `h : x ∈ (span R s : set M)`. See `linear_map.eq_on_span` for a version that takes `h : x ∈ span R s` as an argument. -/ lemma eq_on_span' {s : set M} {f g : M →ₗ[R] M₂} (H : set.eq_on f g s) : set.eq_on f g (span R s : set M) := eq_on_span H /-- If `s` generates the whole module and linear maps `f`, `g` are equal on `s`, then they are equal. -/ lemma ext_on {s : set M} {f g : M →ₗ[R] M₂} (hv : span R s = ⊤) (h : set.eq_on f g s) : f = g := linear_map.ext (λ x, eq_on_span h (eq_top_iff'.1 hv _)) /-- If the range of `v : ι → M` generates the whole module and linear maps `f`, `g` are equal at each `v i`, then they are equal. -/ lemma ext_on_range {v : ι → M} {f g : M →ₗ[R] M₂} (hv : span R (set.range v) = ⊤) (h : ∀i, f (v i) = g (v i)) : f = g := ext_on hv (set.forall_range_iff.2 h) section finsupp variables {γ : Type*} [has_zero γ] @[simp] lemma map_finsupp_sum (f : M →ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum lemma coe_finsupp_sum (t : ι →₀ γ) (g : ι → γ → M →ₗ[R] M₂) : ⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _ @[simp] lemma finsupp_sum_apply (t : ι →₀ γ) (g : ι → γ → M →ₗ[R] M₂) (b : M) : (t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _ end finsupp section dfinsupp open dfinsupp variables {γ : ι → Type*} [decidable_eq ι] section sum variables [Π i, has_zero (γ i)] [Π i (x : γ i), decidable (x ≠ 0)] @[simp] lemma map_dfinsupp_sum (f : M →ₗ[R] M₂) {t : Π₀ i, γ i} {g : Π i, γ i → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum lemma coe_dfinsupp_sum (t : Π₀ i, γ i) (g : Π i, γ i → M →ₗ[R] M₂) : ⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _ @[simp] lemma dfinsupp_sum_apply (t : Π₀ i, γ i) (g : Π i, γ i → M →ₗ[R] M₂) (b : M) : (t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _ end sum section sum_add_hom variables [Π i, add_zero_class (γ i)] @[simp] lemma map_dfinsupp_sum_add_hom (f : M →ₗ[R] M₂) {t : Π₀ i, γ i} {g : Π i, γ i →+ M} : f (sum_add_hom g t) = sum_add_hom (λ i, f.to_add_monoid_hom.comp (g i)) t := f.to_add_monoid_hom.map_dfinsupp_sum_add_hom _ _ end sum_add_hom end dfinsupp theorem map_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h p') : submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) := submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.ext_iff_val] theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf p') : submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') := submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩ /-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. See Note [range copy pattern]. -/ def range (f : M →ₗ[R] M₂) : submodule R M₂ := (map f ⊤).copy (set.range f) set.image_univ.symm theorem range_coe (f : M →ₗ[R] M₂) : (range f : set M₂) = set.range f := rfl @[simp] theorem mem_range {f : M →ₗ[R] M₂} {x} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl lemma range_eq_map (f : M →ₗ[R] M₂) : f.range = map f ⊤ := by { ext, simp } theorem mem_range_self (f : M →ₗ[R] M₂) (x : M) : f x ∈ f.range := ⟨x, rfl⟩ @[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := set_like.coe_injective set.range_id theorem range_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) = map g (range f) := set_like.coe_injective (set.range_comp g f) theorem range_comp_le_range (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) ≤ range g := set_like.coe_mono (set.range_comp_subset_range f g) theorem range_eq_top {f : M →ₗ[R] M₂} : range f = ⊤ ↔ surjective f := by rw [set_like.ext'_iff, range_coe, top_coe, set.range_iff_surjective] lemma range_le_iff_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : range f ≤ p ↔ comap f p = ⊤ := by rw [range_eq_map, map_le_iff_le_comap, eq_top_iff] lemma map_le_range {f : M →ₗ[R] M₂} {p : submodule R M} : map f p ≤ range f := set_like.coe_mono (set.image_subset_range f p) /-- The decreasing sequence of submodules consisting of the ranges of the iterates of a linear map. -/ @[simps] def iterate_range {R M} [ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M) : ℕ →ₘ order_dual (submodule R M) := ⟨λ n, (f ^ n).range, λ n m w x h, begin obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w, rw linear_map.mem_range at h, obtain ⟨m, rfl⟩ := h, rw linear_map.mem_range, use (f ^ c) m, rw [pow_add, linear_map.mul_apply], end⟩ /-- Restrict the codomain of a linear map `f` to `f.range`. This is the bundled version of `set.range_factorization`. -/ @[reducible] def range_restrict (f : M →ₗ[R] M₂) : M →ₗ[R] f.range := f.cod_restrict f.range f.mem_range_self /-- The range of a linear map is finite if the domain is finite. Note: this instance can form a diamond with `subtype.fintype` in the presence of `fintype M₂`. -/ instance fintype_range [fintype M] [decidable_eq M₂] (f : M →ₗ[R] M₂) : fintype (range f) := set.fintype_range f section variables (R) (M) /-- Given an element `x` of a module `M` over `R`, the natural map from `R` to scalar multiples of `x`.-/ def to_span_singleton (x : M) : R →ₗ[R] M := linear_map.id.smul_right x /-- The range of `to_span_singleton x` is the span of `x`.-/ lemma span_singleton_eq_range (x : M) : (R ∙ x) = (to_span_singleton R M x).range := submodule.ext $ λ y, by {refine iff.trans _ mem_range.symm, exact mem_span_singleton } lemma to_span_singleton_one (x : M) : to_span_singleton R M x 1 = x := one_smul _ _ end /-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/ def ker (f : M →ₗ[R] M₂) : submodule R M := comap f ⊥ @[simp] theorem mem_ker {f : M →ₗ[R] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R @[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl @[simp] theorem map_coe_ker (f : M →ₗ[R] M₂) (x : ker f) : f x = 0 := mem_ker.1 x.2 lemma comp_ker_subtype (f : M →ₗ[R] M₂) : f.comp f.ker.subtype = 0 := linear_map.ext $ λ x, suffices f x = 0, by simp [this], mem_ker.1 x.2 theorem ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker (g.comp f) = comap f (ker g) := rfl theorem ker_le_ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker f ≤ ker (g.comp f) := by rw ker_comp; exact comap_mono bot_le theorem disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 := by simp [disjoint_def] theorem ker_eq_bot' {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) := by simpa [disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤ theorem ker_eq_bot_of_inverse {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M} (h : g.comp f = id) : ker f = ⊥ := ker_eq_bot'.2 $ λ m hm, by rw [← id_apply m, ← h, comp_apply, hm, g.map_zero] lemma le_ker_iff_map {f : M →ₗ[R] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ := by rw [ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : ker (cod_restrict p f hf) = ker f := by rw [ker, comap_cod_restrict, map_bot]; refl lemma range_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : range (cod_restrict p f hf) = comap p.subtype f.range := by simpa only [range_eq_map] using map_cod_restrict _ _ _ _ lemma ker_restrict {p : submodule R M} {f : M →ₗ[R] M} (hf : ∀ x : M, x ∈ p → f x ∈ p) : ker (f.restrict hf) = (f.dom_restrict p).ker := by rw [restrict_eq_cod_restrict_dom_restrict, ker_cod_restrict] lemma map_comap_eq (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) = range f ⊓ q := le_antisymm (le_inf map_le_range (map_comap_le _ _)) $ by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩ lemma map_comap_eq_self {f : M →ₗ[R] M₂} {q : submodule R M₂} (h : q ≤ range f) : map f (comap f q) = q := by rwa [map_comap_eq, inf_eq_right] @[simp] theorem ker_zero : ker (0 : M →ₗ[R] M₂) = ⊤ := eq_top_iff'.2 $ λ x, by simp @[simp] theorem range_zero : range (0 : M →ₗ[R] M₂) = ⊥ := by simpa only [range_eq_map] using submodule.map_zero _ theorem ker_eq_top {f : M →ₗ[R] M₂} : ker f = ⊤ ↔ f = 0 := ⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩ lemma range_le_bot_iff (f : M →ₗ[R] M₂) : range f ≤ ⊥ ↔ f = 0 := by rw [range_le_iff_comap]; exact ker_eq_top theorem range_eq_bot {f : M →ₗ[R] M₂} : range f = ⊥ ↔ f = 0 := by rw [← range_le_bot_iff, le_bot_iff] lemma range_le_ker_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : range f ≤ ker g ↔ g.comp f = 0 := ⟨λ h, ker_eq_top.1 $ eq_top_iff'.2 $ λ x, h $ ⟨_, rfl⟩, λ h x hx, mem_ker.2 $ exists.elim hx $ λ y hy, by rw [←hy, ←comp_apply, h, zero_apply]⟩ theorem comap_le_comap_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' := ⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩ theorem comap_injective {f : M →ₗ[R] M₂} (hf : range f = ⊤) : injective (comap f) := λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h)) theorem ker_eq_bot_of_injective {f : M →ₗ[R] M₂} (hf : injective f) : ker f = ⊥ := begin have : disjoint ⊤ f.ker, by { rw [disjoint_ker, ← map_zero f], exact λ x hx H, hf H }, simpa [disjoint] end /-- The increasing sequence of submodules consisting of the kernels of the iterates of a linear map. -/ @[simps] def iterate_ker {R M} [ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M) : ℕ →ₘ submodule R M := ⟨λ n, (f ^ n).ker, λ n m w x h, begin obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w, rw linear_map.mem_ker at h, rw [linear_map.mem_ker, add_comm, pow_add, linear_map.mul_apply, h, linear_map.map_zero], end⟩ end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] include R open submodule lemma comap_map_eq (f : M →ₗ[R] M₂) (p : submodule R M) : comap f (map f p) = p ⊔ ker f := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)), rintro x ⟨y, hy, e⟩, exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩ end lemma comap_map_eq_self {f : M →ₗ[R] M₂} {p : submodule R M} (h : ker f ≤ p) : comap f (map f p) = p := by rw [comap_map_eq, sup_of_le_left h] theorem map_le_map_iff (f : M →ₗ[R] M₂) {p p'} : map f p ≤ map f p' ↔ p ≤ p' ⊔ ker f := by rw [map_le_iff_le_comap, comap_map_eq] theorem map_le_map_iff' {f : M →ₗ[R] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' := by rw [map_le_map_iff, hf, sup_bot_eq] theorem map_injective {f : M →ₗ[R] M₂} (hf : ker f = ⊥) : injective (map f) := λ p p' h, le_antisymm ((map_le_map_iff' hf).1 (le_of_eq h)) ((map_le_map_iff' hf).1 (ge_of_eq h)) theorem map_eq_top_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p : submodule R M} : p.map f = ⊤ ↔ p ⊔ f.ker = ⊤ := by simp_rw [← top_le_iff, ← hf, range_eq_map, map_le_map_iff] end add_comm_group section ring 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₂} include R open submodule theorem sub_mem_ker_iff {x y} : x - y ∈ f.ker ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] theorem disjoint_ker' {p : submodule R M} : disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y := disjoint_ker.trans ⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]), λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩ theorem inj_of_disjoint_ker {p : submodule R M} {s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) : ∀ x y ∈ s, f x = f y → x = y := λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy) theorem ker_eq_bot : ker f = ⊥ ↔ injective f := by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤ lemma ker_le_iff {p : submodule R M} : ker f ≤ p ↔ ∃ (y ∈ range f), f ⁻¹' {y} ⊆ p := begin split, { intros h, use 0, rw [← set_like.mem_coe, f.range_coe], exact ⟨⟨0, map_zero f⟩, h⟩, }, { rintros ⟨y, h₁, h₂⟩, rw set_like.le_def, intros z hz, simp only [mem_ker, set_like.mem_coe] at hz, rw [← set_like.mem_coe, f.range_coe, set.mem_range] at h₁, obtain ⟨x, hx⟩ := h₁, have hx' : x ∈ p, { exact h₂ hx, }, have hxz : z + x ∈ p, { apply h₂, simp [hx, hz], }, suffices : z + x - x ∈ p, { simpa only [this, add_sub_cancel], }, exact p.sub_mem hxz hx', }, end end ring section field variables [field K] variables [add_comm_group V] [module K V] variables [add_comm_group V₂] [module K V₂] lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f := submodule.comap_smul f _ a h lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f := submodule.comap_smul' f _ a lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f := by simpa only [range_eq_map] using submodule.map_smul f _ a h lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f := by simpa only [range_eq_map] using submodule.map_smul' f _ a lemma span_singleton_sup_ker_eq_top (f : V →ₗ[K] K) {x : V} (hx : f x ≠ 0) : (K ∙ x) ⊔ f.ker = ⊤ := eq_top_iff.2 (λ y hy, submodule.mem_sup.2 ⟨(f y * (f x)⁻¹) • x, submodule.mem_span_singleton.2 ⟨f y * (f x)⁻¹, rfl⟩, ⟨y - (f y * (f x)⁻¹) • x, by rw [linear_map.mem_ker, f.map_sub, f.map_smul, smul_eq_mul, mul_assoc, inv_mul_cancel hx, mul_one, sub_self], by simp only [add_sub_cancel'_right]⟩⟩) end field end linear_map namespace is_linear_map lemma is_linear_map_add [semiring R] [add_comm_monoid M] [module R M] : is_linear_map R (λ (x : M × M), x.1 + x.2) := begin apply is_linear_map.mk, { intros x y, simp, cc }, { intros x y, simp [smul_add] } end lemma is_linear_map_sub {R M : Type*} [semiring R] [add_comm_group M] [module R M]: is_linear_map R (λ (x : M × M), x.1 - x.2) := begin apply is_linear_map.mk, { intros x y, simp [add_comm, add_left_comm, sub_eq_add_neg] }, { intros x y, simp [smul_sub] } end end is_linear_map namespace submodule section add_comm_monoid variables {T : semiring R} [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map @[simp] theorem map_top (f : M →ₗ[R] M₂) : map f ⊤ = range f := f.range_eq_map.symm @[simp] theorem comap_bot (f : M →ₗ[R] M₂) : comap f ⊥ = ker f := rfl @[simp] theorem ker_subtype : p.subtype.ker = ⊥ := ker_eq_bot_of_injective $ λ x y, subtype.ext_val @[simp] theorem range_subtype : p.subtype.range = p := by simpa using map_comap_subtype p ⊤ lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p := by simpa using (map_le_range : map p.subtype p' ≤ p.subtype.range) /-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the maximal submodule of `p` is just `p `. -/ @[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p := by simp @[simp] lemma comap_subtype_eq_top {p p' : submodule R M} : comap p.subtype p' = ⊤ ↔ p ≤ p' := eq_top_iff.trans $ map_le_iff_le_comap.symm.trans $ by rw [map_subtype_top] @[simp] lemma comap_subtype_self : comap p.subtype p = ⊤ := comap_subtype_eq_top.2 (le_refl _) @[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ := by rw [of_le, ker_cod_restrict, ker_subtype] lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p := by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype] end add_comm_monoid section ring variables {T : ring R} [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map lemma disjoint_iff_comap_eq_bot {p q : submodule R M} : disjoint p q ↔ comap p.subtype q = ⊥ := by rw [eq_bot_iff, ← map_le_map_iff' p.ker_subtype, map_bot, map_comap_subtype, disjoint] /-- If `N ⊆ M` then submodules of `N` are the same as submodules of `M` contained in `N` -/ def map_subtype.rel_iso : submodule R p ≃o {p' : submodule R M // p' ≤ p} := { to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩, inv_fun := λ q, comap p.subtype q, left_inv := λ p', comap_map_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simp [map_comap_subtype p, inf_of_le_right hq], map_rel_iff' := λ p₁ p₂, map_le_map_iff' (ker_subtype p) } /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of `M`. -/ def map_subtype.order_embedding : submodule R p ↪o submodule R M := (rel_iso.to_rel_embedding $ map_subtype.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma map_subtype_embedding_eq (p' : submodule R p) : map_subtype.order_embedding p p' = map p.subtype p' := rfl /-- The map from a module `M` to the quotient of `M` by a submodule `p` as a linear map. -/ def mkq : M →ₗ[R] p.quotient := { to_fun := quotient.mk, map_add' := by simp, map_smul' := by simp } @[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl /-- Two `linear_map`s from a quotient module are equal if their compositions with `submodule.mkq` are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma linear_map_qext ⦃f g : p.quotient →ₗ[R] M₂⦄ (h : f.comp p.mkq = g.comp p.mkq) : f = g := linear_map.ext $ λ x, quotient.induction_on' x $ (linear_map.congr_fun h : _) /-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂` vanishing on `p`, as a linear map. -/ def liftq (f : M →ₗ[R] M₂) (h : p ≤ f.ker) : p.quotient →ₗ[R] M₂ := { to_fun := λ x, _root_.quotient.lift_on' x f $ λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab, map_add' := by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y, map_smul' := by rintro a ⟨x⟩; exact f.map_smul a x } @[simp] theorem liftq_apply (f : M →ₗ[R] M₂) {h} (x : M) : p.liftq f h (quotient.mk x) = f x := rfl @[simp] theorem liftq_mkq (f : M →ₗ[R] M₂) (h) : (p.liftq f h).comp p.mkq = f := by ext; refl @[simp] theorem range_mkq : p.mkq.range = ⊤ := eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, rfl⟩ @[simp] theorem ker_mkq : p.mkq.ker = p := by ext; simp lemma le_comap_mkq (p' : submodule R p.quotient) : p ≤ comap p.mkq p' := by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p') @[simp] theorem mkq_map_self : map p.mkq p = ⊥ := by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _ @[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' := by simp [comap_map_eq, sup_comm] @[simp] theorem map_mkq_eq_top : map p.mkq p' = ⊤ ↔ p ⊔ p' = ⊤ := by simp only [map_eq_top_iff p.range_mkq, sup_comm, ker_mkq] /-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along `f : M → M₂` is linear. -/ def mapq (f : M →ₗ[R] M₂) (h : p ≤ comap f q) : p.quotient →ₗ[R] q.quotient := p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h @[simp] theorem mapq_apply (f : M →ₗ[R] M₂) {h} (x : M) : mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl theorem mapq_mkq (f : M →ₗ[R] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f := by ext x; refl theorem comap_liftq (f : M →ₗ[R] M₂) (h) : q.comap (p.liftq f h) = (q.comap f).map (mkq p) := le_antisymm (by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩) (by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _) theorem map_liftq (f : M →ₗ[R] M₂) (h) (q : submodule R (quotient p)) : q.map (p.liftq f h) = (q.comap p.mkq).map f := le_antisymm (by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩) (by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩) theorem ker_liftq (f : M →ₗ[R] M₂) (h) : ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _ theorem range_liftq (f : M →ₗ[R] M₂) (h) : range (p.liftq f h) = range f := by simpa only [range_eq_map] using map_liftq _ _ _ _ theorem ker_liftq_eq_bot (f : M →ₗ[R] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ := by rw [ker_liftq, le_antisymm h h', mkq_map_self] /-- The correspondence theorem for modules: there is an order isomorphism between submodules of the quotient of `M` by `p`, and submodules of `M` larger than `p`. -/ def comap_mkq.rel_iso : submodule R p.quotient ≃o {p' : submodule R M // p ≤ p'} := { to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩, inv_fun := λ q, map p.mkq q, left_inv := λ p', map_comap_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simpa [comap_map_mkq p], map_rel_iff' := λ p₁ p₂, comap_le_comap_iff $ range_mkq _ } /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.order_embedding : submodule R p.quotient ↪o submodule R M := (rel_iso.to_rel_embedding $ comap_mkq.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) : comap_mkq.order_embedding p p' = comap p.mkq p' := rfl lemma span_preimage_eq {f : M →ₗ[R] M₂} {s : set M₂} (h₀ : s.nonempty) (h₁ : s ⊆ range f) : span R (f ⁻¹' s) = (span R s).comap f := begin suffices : (span R s).comap f ≤ span R (f ⁻¹' s), { exact le_antisymm (span_preimage_le f s) this, }, have hk : ker f ≤ span R (f ⁻¹' s), { let y := classical.some h₀, have hy : y ∈ s, { exact classical.some_spec h₀, }, rw ker_le_iff, use [y, h₁ hy], rw ← set.singleton_subset_iff at hy, exact set.subset.trans subset_span (span_mono (set.preimage_mono hy)), }, rw ← left_eq_sup at hk, rw f.range_coe at h₁, rw [hk, ← map_le_map_iff, map_span, map_comap_eq, set.image_preimage_eq_of_subset h₁], exact inf_le_right, end end ring end submodule namespace linear_map section semiring variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] /-- A monomorphism is injective. -/ lemma ker_eq_bot_of_cancel {f : M →ₗ[R] M₂} (h : ∀ (u v : f.ker →ₗ[R] M), f.comp u = f.comp v → u = v) : f.ker = ⊥ := begin have h₁ : f.comp (0 : f.ker →ₗ[R] M) = 0 := comp_zero _, rw [←submodule.range_subtype f.ker, ←h 0 f.ker.subtype (eq.trans h₁ (comp_ker_subtype f).symm)], exact range_zero end lemma range_comp_of_range_eq_top {f : M →ₗ[R] M₂} (g : M₂ →ₗ[R] M₃) (hf : range f = ⊤) : range (g.comp f) = range g := by rw [range_comp, hf, submodule.map_top] lemma ker_comp_of_ker_eq_bot (f : M →ₗ[R] M₂) {g : M₂ →ₗ[R] M₃} (hg : ker g = ⊥) : ker (g.comp f) = ker f := by rw [ker_comp, hg, submodule.comap_bot] end semiring section ring variables [ring R] [add_comm_monoid M] [add_comm_group M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] lemma range_mkq_comp (f : M →ₗ[R] M₂) : f.range.mkq.comp f = 0 := linear_map.ext $ λ x, by simp lemma ker_le_range_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : g.ker ≤ f.range ↔ f.range.mkq.comp g.ker.subtype = 0 := by rw [←range_le_ker_iff, submodule.ker_mkq, submodule.range_subtype] /-- An epimorphism is surjective. -/ lemma range_eq_top_of_cancel {f : M →ₗ[R] M₂} (h : ∀ (u v : M₂ →ₗ[R] f.range.quotient), u.comp f = v.comp f → u = v) : f.range = ⊤ := begin have h₁ : (0 : M₂ →ₗ[R] f.range.quotient).comp f = 0 := zero_comp _, rw [←submodule.ker_mkq f.range, ←h 0 f.range.mkq (eq.trans h₁ (range_mkq_comp _).symm)], exact ker_zero end end ring end linear_map @[simp] lemma linear_map.range_range_restrict [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M →ₗ[R] M₂) : f.range_restrict.range = ⊤ := by simp [f.range_cod_restrict _] /-! ### Linear equivalences -/ namespace linear_equiv section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section subsingleton variables [module R M] [module R M₂] [subsingleton M] [subsingleton M₂] /-- Between two zero modules, the zero map is an equivalence. -/ instance : has_zero (M ≃ₗ[R] M₂) := ⟨{ to_fun := 0, inv_fun := 0, right_inv := λ x, subsingleton.elim _ _, left_inv := λ x, subsingleton.elim _ _, ..(0 : M →ₗ[R] M₂)}⟩ -- Even though these are implied by `subsingleton.elim` via the `unique` instance below, they're -- nice to have as `rfl`-lemmas for `dsimp`. @[simp] lemma zero_symm : (0 : M ≃ₗ[R] M₂).symm = 0 := rfl @[simp] lemma coe_zero : ⇑(0 : M ≃ₗ[R] M₂) = 0 := rfl lemma zero_apply (x : M) : (0 : M ≃ₗ[R] M₂) x = 0 := rfl /-- Between two zero modules, the zero map is the only equivalence. -/ instance : unique (M ≃ₗ[R] M₂) := { uniq := λ f, to_linear_map_injective (subsingleton.elim _ _), default := 0 } end subsingleton section variables {module_M : module R M} {module_M₂ : module R M₂} variables (e e' : M ≃ₗ[R] M₂) lemma map_eq_comap {p : submodule R M} : (p.map e : submodule R M₂) = p.comap e.symm := set_like.coe_injective $ by simp [e.image_eq_preimage] /-- A linear equivalence of two modules restricts to a linear equivalence from any submodule `p` of the domain onto the image of that submodule. This is `linear_equiv.of_submodule'` but with `map` on the right instead of `comap` on the left. -/ def of_submodule (p : submodule R M) : p ≃ₗ[R] ↥(p.map ↑e : submodule R M₂) := { inv_fun := λ y, ⟨e.symm y, by { rcases y with ⟨y', hy⟩, rw submodule.mem_map at hy, rcases hy with ⟨x, hx, hxy⟩, subst hxy, simp only [symm_apply_apply, submodule.coe_mk, coe_coe, hx], }⟩, left_inv := λ x, by simp, right_inv := λ y, by { apply set_coe.ext, simp, }, ..((e : M →ₗ[R] M₂).dom_restrict p).cod_restrict (p.map ↑e) (λ x, ⟨x, by simp⟩) } @[simp] lemma of_submodule_apply (p : submodule R M) (x : p) : ↑(e.of_submodule p x) = e x := rfl @[simp] lemma of_submodule_symm_apply (p : submodule R M) (x : (p.map ↑e : submodule R M₂)) : ↑((e.of_submodule p).symm x) = e.symm x := rfl end section finsupp variables {γ : Type*} [module R M] [module R M₂] [has_zero γ] @[simp] lemma map_finsupp_sum (f : M ≃ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum _ end finsupp section dfinsupp open dfinsupp variables {γ : ι → Type*} [decidable_eq ι] [module R M] [module R M₂] @[simp] lemma map_dfinsupp_sum [Π i, has_zero (γ i)] [Π i (x : γ i), decidable (x ≠ 0)] (f : M ≃ₗ[R] M₂) (t : Π₀ i, γ i) (g : Π i, γ i → M) : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum _ @[simp] lemma map_dfinsupp_sum_add_hom [Π i, add_zero_class (γ i)] (f : M ≃ₗ[R] M₂) (t : Π₀ i, γ i) (g : Π i, γ i →+ M) : f (sum_add_hom g t) = sum_add_hom (λ i, f.to_add_equiv.to_add_monoid_hom.comp (g i)) t := f.to_add_equiv.map_dfinsupp_sum_add_hom _ _ end dfinsupp section uncurry variables (V V₂ R) /-- Linear equivalence between a curried and uncurried function. Differs from `tensor_product.curry`. -/ protected def curry : (V × V₂ → R) ≃ₗ[R] (V → V₂ → R) := { map_add' := λ _ _, by { ext, refl }, map_smul' := λ _ _, by { ext, refl }, .. equiv.curry _ _ _ } @[simp] lemma coe_curry : ⇑(linear_equiv.curry R V V₂) = curry := rfl @[simp] lemma coe_curry_symm : ⇑(linear_equiv.curry R V V₂).symm = uncurry := rfl end uncurry section variables {module_M : module R M} {module_M₂ : module R M₂} {module_M₃ : module R M₃} variables (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) (e : M ≃ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) (l : M₃ →ₗ[R] M) variables (p q : submodule R M) /-- Linear equivalence between two equal submodules. -/ def of_eq (h : p = q) : p ≃ₗ[R] q := { map_smul' := λ _ _, rfl, map_add' := λ _ _, rfl, .. equiv.set.of_eq (congr_arg _ h) } variables {p q} @[simp] lemma coe_of_eq_apply (h : p = q) (x : p) : (of_eq p q h x : M) = x := rfl @[simp] lemma of_eq_symm (h : p = q) : (of_eq p q h).symm = of_eq q p h.symm := rfl /-- A linear equivalence which maps a submodule of one module onto another, restricts to a linear equivalence of the two submodules. -/ def of_submodules (p : submodule R M) (q : submodule R M₂) (h : p.map ↑e = q) : p ≃ₗ[R] q := (e.of_submodule p).trans (linear_equiv.of_eq _ _ h) @[simp] lemma of_submodules_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : p) : ↑(e.of_submodules p q h x) = e x := rfl @[simp] lemma of_submodules_symm_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : q) : ↑((e.of_submodules p q h).symm x) = e.symm x := rfl /-- A linear equivalence of two modules restricts to a linear equivalence from the preimage of any submodule to that submodule. This is `linear_equiv.of_submodule` but with `comap` on the left instead of `map` on the right. -/ def of_submodule' [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) : U.comap (f : M →ₗ[R] M₂) ≃ₗ[R] U := (f.symm.of_submodules _ _ f.symm.map_eq_comap).symm lemma of_submodule'_to_linear_map [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) : (f.of_submodule' U).to_linear_map = (f.to_linear_map.dom_restrict _).cod_restrict _ subtype.prop := by { ext, refl } @[simp] lemma of_submodule'_apply [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) (x : U.comap (f : M →ₗ[R] M₂)) : (f.of_submodule' U x : M₂) = f (x : M) := rfl @[simp] lemma of_submodule'_symm_apply [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) (x : U) : ((f.of_submodule' U).symm x : M) = f.symm (x : M₂) := rfl variable (p) /-- The top submodule of `M` is linearly equivalent to `M`. -/ def of_top (h : p = ⊤) : p ≃ₗ[R] M := { inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩, left_inv := λ ⟨x, h⟩, rfl, right_inv := λ x, rfl, .. p.subtype } @[simp] theorem of_top_apply {h} (x : p) : of_top p h x = x := rfl @[simp] theorem coe_of_top_symm_apply {h} (x : M) : ((of_top p h).symm x : M) = x := rfl theorem of_top_symm_apply {h} (x : M) : (of_top p h).symm x = ⟨x, h.symm ▸ trivial⟩ := rfl /-- If a linear map has an inverse, it is a linear equivalence. -/ def of_linear (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₗ[R] M₂ := { inv_fun := g, left_inv := linear_map.ext_iff.1 h₂, right_inv := linear_map.ext_iff.1 h₁, ..f } @[simp] theorem of_linear_apply {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl @[simp] theorem of_linear_symm_apply {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl @[simp] protected theorem range : (e : M →ₗ[R] M₂).range = ⊤ := linear_map.range_eq_top.2 e.to_equiv.surjective lemma eq_bot_of_equiv [module R M₂] (e : p ≃ₗ[R] (⊥ : submodule R M₂)) : p = ⊥ := begin refine bot_unique (set_like.le_def.2 $ assume b hb, (submodule.mem_bot R).2 _), rw [← p.mk_eq_zero hb, ← e.map_eq_zero_iff], apply submodule.eq_zero_of_bot_submodule end @[simp] protected theorem ker : (e : M →ₗ[R] M₂).ker = ⊥ := linear_map.ker_eq_bot_of_injective e.to_equiv.injective @[simp] theorem range_comp : (h.comp (e : M →ₗ[R] M₂)).range = h.range := linear_map.range_comp_of_range_eq_top _ e.range @[simp] theorem ker_comp : ((e : M →ₗ[R] M₂).comp l).ker = l.ker := linear_map.ker_comp_of_ker_eq_bot _ e.ker variables {f g} /-- An linear map `f : M →ₗ[R] M₂` with a left-inverse `g : M₂ →ₗ[R] M` defines a linear equivalence between `M` and `f.range`. This is a computable alternative to `linear_equiv.of_injective`, and a bidirectional version of `linear_map.range_restrict`. -/ def of_left_inverse {g : M₂ → M} (h : function.left_inverse g f) : M ≃ₗ[R] f.range := { to_fun := f.range_restrict, inv_fun := g ∘ f.range.subtype, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := linear_map.mem_range.mp x.prop in show f (g x) = x, by rw [←hx', h x'], .. f.range_restrict } @[simp] lemma of_left_inverse_apply (h : function.left_inverse g f) (x : M) : ↑(of_left_inverse h x) = f x := rfl @[simp] lemma of_left_inverse_symm_apply (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl end end add_comm_monoid section add_comm_group variables [semiring R] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) @[simp] theorem map_neg (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a @[simp] theorem map_sub (a b : M) : e (a - b) = e a - e b := e.to_linear_map.map_sub a b end add_comm_group section neg variables (R) [semiring R] [add_comm_group M] [module R M] /-- `x ↦ -x` as a `linear_equiv` -/ def neg : M ≃ₗ[R] M := { .. equiv.neg M, .. (-linear_map.id : M →ₗ[R] M) } variable {R} @[simp] lemma coe_neg : ⇑(neg R : M ≃ₗ[R] M) = -id := rfl lemma neg_apply (x : M) : neg R x = -x := by simp @[simp] lemma symm_neg : (neg R : M ≃ₗ[R] M).symm = neg R := rfl end neg section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] variables {module_M : module R M} {module_M₂ : module R M₂} variables (f : M →ₗ[R] M₂) (e : M ≃ₗ[R] M₂) /-- An `injective` linear map `f : M →ₗ[R] M₂` defines a linear equivalence between `M` and `f.range`. See also `linear_map.of_left_inverse`. -/ noncomputable def of_injective (h : f.ker = ⊥) : M ≃ₗ[R] f.range := of_left_inverse $ classical.some_spec (linear_map.ker_eq_bot.1 h).has_left_inverse @[simp] theorem of_injective_apply {h : f.ker = ⊥} (x : M) : ↑(of_injective f h x) = f x := rfl /-- A bijective linear map is a linear equivalence. Here, bijectivity is described by saying that the kernel of `f` is `{0}` and the range is the universal set. -/ noncomputable def of_bijective (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : M ≃ₗ[R] M₂ := (of_injective f hf₁).trans (of_top _ hf₂) @[simp] theorem of_bijective_apply {hf₁ hf₂} (x : M) : of_bijective f hf₁ hf₂ x = f x := rfl end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] open linear_map /-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/ def smul_of_unit (a : units R) : M ≃ₗ[R] M := of_linear ((a:R) • 1 : M →ₗ M) (((a⁻¹ : units R) : R) • 1 : M →ₗ M) (by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl) (by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl) /-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a linear isomorphism between the two function spaces. -/ def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) : (M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) := { to_fun := λ f, (e₂ : M₂₁ →ₗ[R] M₂₂).comp $ f.comp e₁.symm, inv_fun := λ f, (e₂.symm : M₂₂ →ₗ[R] M₂₁).comp $ f.comp e₁, left_inv := λ f, by { ext x, simp }, right_inv := λ f, by { ext x, simp }, map_add' := λ f g, by { ext x, simp }, map_smul' := λ c f, by { ext x, simp } } @[simp] lemma arrow_congr_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₁ →ₗ[R] M₂₁) (x : M₂) : arrow_congr e₁ e₂ f x = e₂ (f (e₁.symm x)) := rfl @[simp] lemma arrow_congr_symm_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₂ →ₗ[R] M₂₂) (x : M₁) : (arrow_congr e₁ e₂).symm f x = e₂.symm (f (e₁ x)) := rfl lemma arrow_congr_comp {N N₂ N₃ : Sort*} [add_comm_group N] [add_comm_group N₂] [add_comm_group N₃] [module R N] [module R N₂] [module R N₃] (e₁ : M ≃ₗ[R] N) (e₂ : M₂ ≃ₗ[R] N₂) (e₃ : M₃ ≃ₗ[R] N₃) (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) := by { ext, simp only [symm_apply_apply, arrow_congr_apply, linear_map.comp_apply], } lemma arrow_congr_trans {M₁ M₂ M₃ N₁ N₂ N₃ : Sort*} [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] [add_comm_group M₃] [module R M₃] [add_comm_group N₁] [module R N₁] [add_comm_group N₂] [module R N₂] [add_comm_group N₃] [module R N₃] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : N₁ ≃ₗ[R] N₂) (e₃ : M₂ ≃ₗ[R] M₃) (e₄ : N₂ ≃ₗ[R] N₃) : (arrow_congr e₁ e₂).trans (arrow_congr e₃ e₄) = arrow_congr (e₁.trans e₃) (e₂.trans e₄) := rfl /-- If `M₂` and `M₃` are linearly isomorphic then the two spaces of linear maps from `M` into `M₂` and `M` into `M₃` are linearly isomorphic. -/ def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ (M →ₗ M₃) := arrow_congr (linear_equiv.refl R M) f /-- If `M` and `M₂` are linearly isomorphic then the two spaces of linear maps from `M` and `M₂` to themselves are linearly isomorphic. -/ def conj (e : M ≃ₗ[R] M₂) : (module.End R M) ≃ₗ[R] (module.End R M₂) := arrow_congr e e lemma conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M) : e.conj f = ((↑e : M →ₗ[R] M₂).comp f).comp e.symm := rfl lemma symm_conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M₂) : e.symm.conj f = ((↑e.symm : M₂ →ₗ[R] M).comp f).comp e := rfl lemma conj_comp (e : M ≃ₗ[R] M₂) (f g : module.End R M) : e.conj (g.comp f) = (e.conj g).comp (e.conj f) := arrow_congr_comp e e e f g lemma conj_trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) : e₁.conj.trans e₂.conj = (e₁.trans e₂).conj := by { ext f x, refl, } @[simp] lemma conj_id (e : M ≃ₗ[R] M₂) : e.conj linear_map.id = linear_map.id := by { ext, simp [conj_apply], } end comm_ring section field variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module K M] [module K M₂] [module K M₃] variables (K) (M) open linear_map /-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/ def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M := smul_of_unit $ units.mk0 a ha section noncomputable theory open_locale classical lemma ker_to_span_singleton {x : M} (h : x ≠ 0) : (to_span_singleton K M x).ker = ⊥ := begin ext c, split, { intros hc, rw submodule.mem_bot, rw mem_ker at hc, by_contra hc', have : x = 0, calc x = c⁻¹ • (c • x) : by rw [← mul_smul, inv_mul_cancel hc', one_smul] ... = c⁻¹ • ((to_span_singleton K M x) c) : rfl ... = 0 : by rw [hc, smul_zero], tauto }, { rw [mem_ker, submodule.mem_bot], intros h, rw h, simp } end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from `K` to the span of `x`, with invertibility check to consider it as an isomorphism.-/ def to_span_nonzero_singleton (x : M) (h : x ≠ 0) : K ≃ₗ[K] (K ∙ x) := linear_equiv.trans (linear_equiv.of_injective (to_span_singleton K M x) (ker_to_span_singleton K M h)) (of_eq (to_span_singleton K M x).range (K ∙ x) (span_singleton_eq_range K M x).symm) lemma to_span_nonzero_singleton_one (x : M) (h : x ≠ 0) : to_span_nonzero_singleton K M x h 1 = (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) := begin apply set_like.coe_eq_coe.mp, have : ↑(to_span_nonzero_singleton K M x h 1) = to_span_singleton K M x 1 := rfl, rw [this, to_span_singleton_one, submodule.coe_mk], end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from the span of `x` to `K`.-/ abbreviation coord (x : M) (h : x ≠ 0) : (K ∙ x) ≃ₗ[K] K := (to_span_nonzero_singleton K M x h).symm lemma coord_self (x : M) (h : x ≠ 0) : (coord K M x h) (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) = 1 := by rw [← to_span_nonzero_singleton_one K M x h, symm_apply_apply] end end field end linear_equiv namespace submodule section module variables [semiring R] [add_comm_monoid M] [module R M] /-- Given `p` a submodule of the module `M` and `q` a submodule of `p`, `p.equiv_subtype_map q` is the natural `linear_equiv` between `q` and `q.map p.subtype`. -/ def equiv_subtype_map (p : submodule R M) (q : submodule R p) : q ≃ₗ[R] q.map p.subtype := { inv_fun := begin rintro ⟨x, hx⟩, refine ⟨⟨x, _⟩, _⟩; rcases hx with ⟨⟨_, h⟩, _, rfl⟩; assumption end, left_inv := λ ⟨⟨_, _⟩, _⟩, rfl, right_inv := λ ⟨x, ⟨_, h⟩, _, rfl⟩, rfl, .. (p.subtype.dom_restrict q).cod_restrict _ begin rintro ⟨x, hx⟩, refine ⟨x, hx, rfl⟩, end } @[simp] lemma equiv_subtype_map_apply {p : submodule R M} {q : submodule R p} (x : q) : (p.equiv_subtype_map q x : M) = p.subtype.dom_restrict q x := rfl @[simp] lemma equiv_subtype_map_symm_apply {p : submodule R M} {q : submodule R p} (x : q.map p.subtype) : ((p.equiv_subtype_map q).symm x : M) = x := by { cases x, refl } /-- If `s ≤ t`, then we can view `s` as a submodule of `t` by taking the comap of `t.subtype`. -/ @[simps] def comap_subtype_equiv_of_le {p q : submodule R M} (hpq : p ≤ q) : comap q.subtype p ≃ₗ[R] p := { to_fun := λ x, ⟨x, x.2⟩, inv_fun := λ x, ⟨⟨x, hpq x.2⟩, x.2⟩, left_inv := λ x, by simp only [coe_mk, set_like.eta, coe_coe], right_inv := λ x, by simp only [subtype.coe_mk, set_like.eta, coe_coe], map_add' := λ x y, rfl, map_smul' := λ c x, rfl } end module variables [ring R] [add_comm_group M] [module R M] variables (p : submodule R M) open linear_map /-- If `p = ⊥`, then `M / p ≃ₗ[R] M`. -/ def quot_equiv_of_eq_bot (hp : p = ⊥) : p.quotient ≃ₗ[R] M := linear_equiv.of_linear (p.liftq id $ hp.symm ▸ bot_le) p.mkq (liftq_mkq _ _ _) $ p.quot_hom_ext $ λ x, rfl @[simp] lemma quot_equiv_of_eq_bot_apply_mk (hp : p = ⊥) (x : M) : p.quot_equiv_of_eq_bot hp (quotient.mk x) = x := rfl @[simp] lemma quot_equiv_of_eq_bot_symm_apply (hp : p = ⊥) (x : M) : (p.quot_equiv_of_eq_bot hp).symm x = quotient.mk x := rfl @[simp] lemma coe_quot_equiv_of_eq_bot_symm (hp : p = ⊥) : ((p.quot_equiv_of_eq_bot hp).symm : M →ₗ[R] p.quotient) = p.mkq := rfl variables (q : submodule R M) /-- Quotienting by equal submodules gives linearly equivalent quotients. -/ def quot_equiv_of_eq (h : p = q) : p.quotient ≃ₗ[R] q.quotient := { map_add' := by { rintros ⟨x⟩ ⟨y⟩, refl }, map_smul' := by { rintros x ⟨y⟩, refl }, ..@quotient.congr _ _ (quotient_rel p) (quotient_rel q) (equiv.refl _) $ λ a b, by { subst h, refl } } @[simp] lemma quot_equiv_of_eq_mk (h : p = q) (x : M) : submodule.quot_equiv_of_eq p q h (submodule.quotient.mk x) = submodule.quotient.mk x := rfl end submodule namespace submodule variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p : submodule R M) (q : submodule R M₂) @[simp] lemma mem_map_equiv {e : M ≃ₗ[R] M₂} {x : M₂} : x ∈ p.map (e : M →ₗ[R] M₂) ↔ e.symm x ∈ p := begin rw submodule.mem_map, split, { rintros ⟨y, hy, hx⟩, simp [←hx, hy], }, { intros hx, refine ⟨e.symm x, hx, by simp⟩, }, end lemma map_equiv_eq_comap_symm (e : M ≃ₗ[R] M₂) (K : submodule R M) : K.map (e : M →ₗ[R] M₂) = K.comap e.symm := submodule.ext (λ _, by rw [mem_map_equiv, mem_comap, linear_equiv.coe_coe]) lemma comap_equiv_eq_map_symm (e : M ≃ₗ[R] M₂) (K : submodule R M₂) : K.comap (e : M →ₗ[R] M₂) = K.map e.symm := (map_equiv_eq_comap_symm e.symm K).symm lemma comap_le_comap_smul (f : M →ₗ[R] M₂) (c : R) : comap f q ≤ comap (c • f) q := begin rw set_like.le_def, intros m h, change c • (f m) ∈ q, change f m ∈ q at h, apply q.smul_mem _ h, end lemma inf_comap_le_comap_add (f₁ f₂ : M →ₗ[R] M₂) : comap f₁ q ⊓ comap f₂ q ≤ comap (f₁ + f₂) q := begin rw set_like.le_def, intros m h, change f₁ m + f₂ m ∈ q, change f₁ m ∈ q ∧ f₂ m ∈ q at h, apply q.add_mem h.1 h.2, end /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the set of maps $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \}$ is a submodule of `Hom(M, M₂)`. -/ def compatible_maps : submodule R (M →ₗ[R] M₂) := { carrier := {f | p ≤ comap f q}, zero_mem' := by { change p ≤ comap 0 q, rw comap_zero, refine le_top, }, add_mem' := λ f₁ f₂ h₁ h₂, by { apply le_trans _ (inf_comap_le_comap_add q f₁ f₂), rw le_inf_iff, exact ⟨h₁, h₂⟩, }, smul_mem' := λ c f h, le_trans h (comap_le_comap_smul q f c), } /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the natural map $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \} \to Hom(M/p, M₂/q)$ is linear. -/ def mapq_linear : compatible_maps p q →ₗ[R] p.quotient →ₗ[R] q.quotient := { to_fun := λ f, mapq _ _ f.val f.property, map_add' := λ x y, by { ext, refl, }, map_smul' := λ c f, by { ext, refl, } } end submodule namespace equiv variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] /-- An equivalence whose underlying function is linear is a linear equivalence. -/ def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ := { .. e, .. h.mk' e} end equiv namespace add_equiv variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] /-- An additive equivalence whose underlying function preserves `smul` is a linear equivalence. -/ def to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : M ≃ₗ[R] M₂ := { map_smul' := h, .. e, } @[simp] lemma coe_to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h) = e := rfl @[simp] lemma coe_to_linear_equiv_symm (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h).symm = e.symm := rfl end add_equiv namespace linear_map open submodule section isomorphism_laws 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 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 : f.ker.quotient ≃ₗ[R] f.range := (linear_equiv.of_injective (f.ker.liftq f $ le_refl _) $ 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) : f.ker.quotient ≃ₗ[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) : (comap p.subtype (p ⊓ p')).quotient →ₗ[R] (comap (p ⊔ p').subtype p').quotient := (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) : (comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient := linear_equiv.of_bijective (quotient_inf_to_sup_quotient p p') begin rw [quotient_inf_to_sup_quotient, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], exact λ ⟨x, hx1⟩ hx2, ⟨hx1, hx2⟩ end begin rw [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 section fun_left variables (R M) [semiring R] [add_comm_monoid M] [module R M] variables {m n p : Type*} namespace linear_map /-- Given an `R`-module `M` and a function `m → n` between arbitrary types, construct a linear map `(n → M) →ₗ[R] (m → M)` -/ def fun_left (f : m → n) : (n → M) →ₗ[R] (m → M) := { to_fun := (∘ f), map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl } @[simp] theorem fun_left_apply (f : m → n) (g : n → M) (i : m) : fun_left R M f g i = g (f i) := rfl @[simp] theorem fun_left_id (g : n → M) : fun_left R M _root_.id g = g := rfl theorem fun_left_comp (f₁ : n → p) (f₂ : m → n) : fun_left R M (f₁ ∘ f₂) = (fun_left R M f₂).comp (fun_left R M f₁) := rfl theorem fun_left_surjective_of_injective (f : m → n) (hf : injective f) : surjective (fun_left R M f) := begin classical, intro g, refine ⟨λ x, if h : ∃ y, f y = x then g h.some else 0, _⟩, { ext, dsimp only [fun_left_apply], split_ifs with w, { congr, exact hf w.some_spec, }, { simpa only [not_true, exists_apply_eq_apply] using w } }, end theorem fun_left_injective_of_surjective (f : m → n) (hf : surjective f) : injective (fun_left R M f) := begin obtain ⟨g, hg⟩ := hf.has_right_inverse, suffices : left_inverse (fun_left R M g) (fun_left R M f), { exact this.injective }, intro x, simp only [← linear_map.comp_apply, ← fun_left_comp, hg.id, fun_left_id] end end linear_map namespace linear_equiv open linear_map /-- Given an `R`-module `M` and an equivalence `m ≃ n` between arbitrary types, construct a linear equivalence `(n → M) ≃ₗ[R] (m → M)` -/ def fun_congr_left (e : m ≃ n) : (n → M) ≃ₗ[R] (m → M) := linear_equiv.of_linear (fun_left R M e) (fun_left R M e.symm) (linear_map.ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.symm_comp_self, fun_left_id]) (linear_map.ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.self_comp_symm, fun_left_id]) @[simp] theorem fun_congr_left_apply (e : m ≃ n) (x : n → M) : fun_congr_left R M e x = fun_left R M e x := rfl @[simp] theorem fun_congr_left_id : fun_congr_left R M (equiv.refl n) = linear_equiv.refl R (n → M) := rfl @[simp] theorem fun_congr_left_comp (e₁ : m ≃ n) (e₂ : n ≃ p) : fun_congr_left R M (equiv.trans e₁ e₂) = linear_equiv.trans (fun_congr_left R M e₂) (fun_congr_left R M e₁) := rfl @[simp] lemma fun_congr_left_symm (e : m ≃ n) : (fun_congr_left R M e).symm = fun_congr_left R M e.symm := rfl end linear_equiv end fun_left namespace linear_equiv variables [semiring R] [add_comm_monoid M] [module R M] variables (R M) instance automorphism_group : group (M ≃ₗ[R] M) := { mul := λ f g, g.trans f, one := linear_equiv.refl R M, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } /-- Restriction from `R`-linear automorphisms of `M` to `R`-linear endomorphisms of `M`, promoted to a monoid hom. -/ def automorphism_group.to_linear_map_monoid_hom : (M ≃ₗ[R] M) →* (M →ₗ[R] M) := { to_fun := coe, map_one' := rfl, map_mul' := λ _ _, rfl } end linear_equiv namespace linear_map variables [semiring R] [add_comm_monoid M] [module R M] variables (R M) /-- The group of invertible linear maps from `M` to itself -/ @[reducible] def general_linear_group := units (M →ₗ[R] M) namespace general_linear_group variables {R M} instance : has_coe_to_fun (general_linear_group R M) := by apply_instance /-- An invertible linear map `f` determines an equivalence from `M` to itself. -/ def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) := { inv_fun := f.inv.to_fun, left_inv := λ m, show (f.inv * f.val) m = m, by erw f.inv_val; simp, right_inv := λ m, show (f.val * f.inv) m = m, by erw f.val_inv; simp, ..f.val } /-- An equivalence from `M` to itself determines an invertible linear map. -/ def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M := { val := f, inv := f.symm, val_inv := linear_map.ext $ λ _, f.apply_symm_apply _, inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ } variables (R M) /-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear equivalences between `M` and itself. -/ def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) := { to_fun := to_linear_equiv, inv_fun := of_linear_equiv, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl }, map_mul' := λ x y, by {ext, refl} } @[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) : (general_linear_equiv R M f : M →ₗ[R] M) = f := by {ext, refl} end general_linear_group end linear_map namespace submodule variables [ring R] [add_comm_group M] [module R M] instance : is_modular_lattice (submodule R M) := ⟨λ x y z xz a ha, begin rw [mem_inf, mem_sup] at ha, rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩, rw mem_sup, refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩, rw [← add_sub_cancel c b, add_comm], apply z.sub_mem haz (xz hb), end⟩ section third_iso_thm 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 : quotient (T.map S.mkq) →ₗ[R] quotient T := 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 : S.quotient) : 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 : quotient (T.map S.mkq) ≃ₗ[R] quotient 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 } end third_iso_thm end submodule
8779d96386672f93bb1bea8f96b09c727d5e95fe
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/examples/targets/src/Bar.lean
55f962e1ea90449c5018ab74ad1b3a7483caf400
[ "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
17
lean
def bar := "bar"
b92326adf78e6076d213feea1c36388e10d89f51
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/category/Module/projective.lean
6fa327c3db2be95343b257997dedbb0c71c422ad
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,273
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison -/ import algebra.category.Module.epi_mono import algebra.module.projective import category_theory.preadditive.projective import linear_algebra.finsupp_vector_space /-! # The category of `R`-modules has enough projectives. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ universes v u open category_theory open category_theory.limits open linear_map open_locale Module /-- The categorical notion of projective object agrees with the explicit module-theoretic notion. -/ theorem is_projective.iff_projective {R : Type u} [ring R] {P : Type (max u v)} [add_comm_group P] [module R P] : module.projective R P ↔ projective (Module.of R P) := begin refine ⟨λ h, _, λ h, _⟩, { letI : module.projective R ↥(Module.of R P) := h, exact ⟨λ E X f e epi, module.projective_lifting_property _ _ ((Module.epi_iff_surjective _).mp epi)⟩ }, { refine module.projective_of_lifting_property _, introsI E X mE mX sE sX f g s, haveI : epi ↟f := (Module.epi_iff_surjective ↟f).mpr s, letI : projective (Module.of R P) := h, exact ⟨projective.factor_thru ↟g ↟f, projective.factor_thru_comp ↟g ↟f⟩ } end namespace Module variables {R : Type u} [ring R] {M : Module.{max u v} R} /-- Modules that have a basis are projective. -/ -- We transport the corresponding result from `module.projective`. lemma projective_of_free {ι : Type*} (b : basis ι R M) : projective M := projective.of_iso (Module.of_self_iso _) ((is_projective.iff_projective).mp (module.projective_of_basis b)) /-- The category of modules has enough projectives, since every module is a quotient of a free module. -/ instance Module_enough_projectives : enough_projectives (Module.{max u v} R) := { presentation := λ M, ⟨{ P := Module.of R (M →₀ R), projective := projective_of_free finsupp.basis_single_one, f := finsupp.basis_single_one.constr ℕ id, epi := (epi_iff_range_eq_top _).mpr (range_eq_top.2 (λ m, ⟨finsupp.single m (1 : R), by simp [basis.constr]⟩)) }⟩, } end Module
6d52f86d2eb9043b02899c13deba7af237d171ef
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/group/with_one.lean
2608b1588fe671a76bb0f08b59254d68c3d4c2e5
[ "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
8,754
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johan Commelin -/ import algebra.ring.basic import data.equiv.basic /-! # Adjoining a zero/one to semigroups and related algebraic structures This file contains different results about adjoining an element to an algebraic structure which then behaves like a zero or a one. An example is adjoining a one to a semigroup to obtain a monoid. That this provides an example of an adjunction is proved in `algebra.category.Mon.adjunctions`. Another result says that adjoining to a group an element `zero` gives a `group_with_zero`. For more information about these structures (which are not that standard in informal mathematics, see `algebra.group_with_zero.basic`) -/ universes u v w variable {α : Type u} /-- Add an extra element `1` to a type -/ @[to_additive "Add an extra element `0` to a type"] def with_one (α) := option α namespace with_one @[to_additive] instance : monad with_one := option.monad @[to_additive] instance : has_one (with_one α) := ⟨none⟩ @[to_additive] instance : inhabited (with_one α) := ⟨1⟩ @[to_additive] instance [nonempty α] : nontrivial (with_one α) := option.nontrivial @[to_additive] instance : has_coe_t α (with_one α) := ⟨some⟩ @[to_additive] lemma some_eq_coe {a : α} : (some a : with_one α) = ↑a := rfl @[simp, to_additive] lemma coe_ne_one {a : α} : (a : with_one α) ≠ (1 : with_one α) := option.some_ne_none a @[simp, to_additive] lemma one_ne_coe {a : α} : (1 : with_one α) ≠ a := coe_ne_one.symm @[to_additive] lemma ne_one_iff_exists {x : with_one α} : x ≠ 1 ↔ ∃ (a : α), ↑a = x := option.ne_none_iff_exists -- `to_additive` fails to generate some meta info around eqn lemmas, so `lift` doesn't work -- unless we explicitly define this instance instance : can_lift (with_one α) α := { coe := coe, cond := λ a, a ≠ 1, prf := λ a, ne_one_iff_exists.1 } @[simp, to_additive] lemma coe_inj {a b : α} : (a : with_one α) = b ↔ a = b := option.some_inj attribute [norm_cast] coe_inj with_zero.coe_inj @[elab_as_eliminator, to_additive] protected lemma cases_on {P : with_one α → Prop} : ∀ (x : with_one α), P 1 → (∀ a : α, P a) → P x := option.cases_on @[to_additive] instance [has_mul α] : mul_one_class (with_one α) := { mul := option.lift_or_get (*), one := (1), one_mul := (option.lift_or_get_is_left_id _).1, mul_one := (option.lift_or_get_is_right_id _).1 } @[to_additive] instance [semigroup α] : monoid (with_one α) := { mul_assoc := (option.lift_or_get_assoc _).1, ..with_one.mul_one_class } @[to_additive] instance [comm_semigroup α] : comm_monoid (with_one α) := { mul_comm := (option.lift_or_get_comm _).1, ..with_one.monoid } /-- `coe` as a bundled morphism -/ @[to_additive "`coe` as a bundled morphism", simps apply] def coe_mul_hom [has_mul α] : mul_hom α (with_one α) := { to_fun := coe, map_mul' := λ x y, rfl } section lift variables [has_mul α] {β : Type v} [mul_one_class β] /-- Lift a semigroup homomorphism `f` to a bundled monoid homorphism. -/ @[to_additive "Lift an add_semigroup homomorphism `f` to a bundled add_monoid homorphism."] def lift : mul_hom α β ≃ (with_one α →* β) := { to_fun := λ f, { to_fun := λ x, option.cases_on x 1 f, map_one' := rfl, map_mul' := λ x y, with_one.cases_on x (by { rw one_mul, exact (one_mul _).symm }) $ λ x, with_one.cases_on y (by { rw mul_one, exact (mul_one _).symm }) $ λ y, f.map_mul x y }, inv_fun := λ F, F.to_mul_hom.comp coe_mul_hom, left_inv := λ f, mul_hom.ext $ λ x, rfl, right_inv := λ F, monoid_hom.ext $ λ x, with_one.cases_on x F.map_one.symm $ λ x, rfl } variables (f : mul_hom α β) @[simp, to_additive] lemma lift_coe (x : α) : lift f x = f x := rfl @[simp, to_additive] lemma lift_one : lift f 1 = 1 := rfl @[to_additive] theorem lift_unique (f : with_one α →* β) : f = lift (f.to_mul_hom.comp coe_mul_hom) := (lift.apply_symm_apply f).symm end lift section map variables {β : Type v} [has_mul α] [has_mul β] /-- Given a multiplicative map from `α → β` returns a monoid homomorphism from `with_one α` to `with_one β` -/ @[to_additive "Given an additive map from `α → β` returns an add_monoid homomorphism from `with_zero α` to `with_zero β`"] def map (f : mul_hom α β) : with_one α →* with_one β := lift (coe_mul_hom.comp f) @[simp, to_additive] lemma map_id : map (mul_hom.id α) = monoid_hom.id (with_one α) := by { ext, cases x; refl } @[simp, to_additive] lemma map_comp {γ : Type w} [has_mul γ] (f : mul_hom α β) (g : mul_hom β γ) : map (g.comp f) = (map g).comp (map f) := by { ext, cases x; refl } end map attribute [irreducible] with_one @[simp, norm_cast, to_additive] lemma coe_mul [has_mul α] (a b : α) : ((a * b : α) : with_one α) = a * b := rfl end with_one namespace with_zero -- `to_additive` fails to generate some meta info around eqn lemmas, so `lift` doesn't work -- unless we explicitly define this instance instance : can_lift (with_zero α) α := { coe := coe, cond := λ a, a ≠ 0, prf := λ a, ne_zero_iff_exists.1 } attribute [to_additive] with_one.can_lift instance [one : has_one α] : has_one (with_zero α) := { ..one } @[simp, norm_cast] lemma coe_one [has_one α] : ((1 : α) : with_zero α) = 1 := rfl instance [has_mul α] : mul_zero_class (with_zero α) := { mul := λ o₁ o₂, o₁.bind (λ a, option.map (λ b, a * b) o₂), zero_mul := λ a, rfl, mul_zero := λ a, by cases a; refl, ..with_zero.has_zero } @[simp, norm_cast] lemma coe_mul {α : Type u} [has_mul α] {a b : α} : ((a * b : α) : with_zero α) = a * b := rfl @[simp] lemma zero_mul {α : Type u} [has_mul α] (a : with_zero α) : 0 * a = 0 := rfl @[simp] lemma mul_zero {α : Type u} [has_mul α] (a : with_zero α) : a * 0 = 0 := by cases a; refl instance [semigroup α] : semigroup (with_zero α) := { mul_assoc := λ a b c, match a, b, c with | none, _, _ := rfl | some a, none, _ := rfl | some a, some b, none := rfl | some a, some b, some c := congr_arg some (mul_assoc _ _ _) end, ..with_zero.mul_zero_class } instance [comm_semigroup α] : comm_semigroup (with_zero α) := { mul_comm := λ a b, match a, b with | none, _ := (mul_zero _).symm | some a, none := rfl | some a, some b := congr_arg some (mul_comm _ _) end, ..with_zero.semigroup } instance [monoid α] : monoid_with_zero (with_zero α) := { one_mul := λ a, match a with | none := rfl | some a := congr_arg some $ one_mul _ end, mul_one := λ a, match a with | none := rfl | some a := congr_arg some $ mul_one _ end, ..with_zero.mul_zero_class, ..with_zero.has_one, ..with_zero.semigroup } instance [comm_monoid α] : comm_monoid_with_zero (with_zero α) := { ..with_zero.monoid_with_zero, ..with_zero.comm_semigroup } /-- Given an inverse operation on `α` there is an inverse operation on `with_zero α` sending `0` to `0`-/ definition inv [has_inv α] (x : with_zero α) : with_zero α := do a ← x, return a⁻¹ instance [has_inv α] : has_inv (with_zero α) := ⟨with_zero.inv⟩ @[simp, norm_cast] lemma coe_inv [has_inv α] (a : α) : ((a⁻¹ : α) : with_zero α) = a⁻¹ := rfl @[simp] lemma inv_zero [has_inv α] : (0 : with_zero α)⁻¹ = 0 := rfl section group variables [group α] @[simp] lemma inv_one : (1 : with_zero α)⁻¹ = 1 := show ((1⁻¹ : α) : with_zero α) = 1, by simp /-- if `G` is a group then `with_zero G` is a group with zero. -/ instance : group_with_zero (with_zero α) := { inv_zero := inv_zero, mul_inv_cancel := by { intros a ha, lift a to α using ha, norm_cast, apply mul_right_inv }, .. with_zero.monoid_with_zero, .. with_zero.has_inv, .. with_zero.nontrivial } @[norm_cast] lemma div_coe (a b : α) : (a : with_zero α) / b = (a * b⁻¹ : α) := rfl end group instance [comm_group α] : comm_group_with_zero (with_zero α) := { .. with_zero.group_with_zero, .. with_zero.comm_monoid_with_zero } instance [semiring α] : semiring (with_zero α) := { left_distrib := λ a b c, begin cases a with a, {refl}, cases b with b; cases c with c; try {refl}, exact congr_arg some (left_distrib _ _ _) end, right_distrib := λ a b c, begin cases c with c, { change (a + b) * 0 = a * 0 + b * 0, simp }, cases a with a; cases b with b; try {refl}, exact congr_arg some (right_distrib _ _ _) end, ..with_zero.add_comm_monoid, ..with_zero.mul_zero_class, ..with_zero.monoid_with_zero } attribute [irreducible] with_zero end with_zero
703daec831ad11607c5be435d56d67fc3e75063b
78630e908e9624a892e24ebdd21260720d29cf55
/src/logic_first_order/fol_11.lean
ccbb1004dd8327ad2c8f77d33957e0cb1ef60830
[ "CC0-1.0" ]
permissive
tomasz-lisowski/lean-logic-examples
84e612466776be0a16c23a0439ff8ef6114ddbe1
2b2ccd467b49c3989bf6c92ec0358a8d6ee68c5d
refs/heads/master
1,683,334,199,431
1,621,938,305,000
1,621,938,305,000
365,041,573
1
0
null
null
null
null
UTF-8
Lean
false
false
772
lean
namespace fol_11 open classical axiom not_iff_not_self (P : Prop) : ¬ (P ↔ ¬ P) -- Example of using the axiom: example (Q : Prop) : ¬ (Q ↔ ¬ Q) := not_iff_not_self Q section variable Person : Type variable shaves : Person → Person → Prop variable barber : Person variable h : ∀ x, shaves barber x ↔ ¬ shaves x x include h theorem fol_11 : false := have h1: shaves barber barber ↔ ¬ shaves barber barber, from h barber, have h2: shaves barber barber → ¬ shaves barber barber, from h1.mp, have h3: shaves barber barber, from iff.elim_right h1 (assume h4: shaves barber barber, have h5: ¬ shaves barber barber, from h2 h4, h5 h4), have h6: ¬ shaves barber barber, from h2 h3, h6 h3 end #check fol_11 end fol_11
99772ba9d3b8ee687c702b111d6a4cd99cde4f52
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/run/eq2.lean
6ebf0d1cde46fd31e7e21e67a275aa02f0ed096e
[ "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
172
lean
definition symm {A : Type} : Π {a b : A}, a = b → b = a | a a rfl := rfl definition trans {A : Type} : Π {a b c : A}, a = b → b = c → a = c | a a a rfl rfl := rfl
a1f23c62db1c5be0ba4e088967f9cc00c290f819
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/slack_eqn_issue.lean
6e06f9a6e09ee99614f572e9f5b38d7d10db54e6
[ "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
487
lean
lemma test1 {p : ℕ → Prop} {a : ℕ} (h : p a) : ∀b, b = a → p b | ._ rfl := h lemma test2 {p : ℕ → Prop} {a : ℕ} (h : p a) : ∀b, b = a → p a | ._ rfl := h lemma test3 {p : ℕ → Prop} {a : ℕ} (h : p a) : ∀b, a = b → p b | ._ rfl := h lemma test4 {p : ℕ → Prop} {a : ℕ} {f : ℕ → ℕ} (h : p (f a)) : ∀b, b = f a → p b | ._ rfl := h lemma test5 {p : ℕ → Prop} {a : ℕ} {f : ℕ → ℕ} (h : p (f a)) : ∀b, f a = b → p b | ._ rfl := h
0a4d3e6eaf694b11d60b4ba22fe35a73d9842a75
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Server/GoTo.lean
313d0db91862b6e390ecbef0359100adc254a550
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,686
lean
/- Copyright (c) 2022 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Lars König, Wojciech Nawrocki -/ import Lean.Data.Json.FromToJson import Lean.Util.Path import Lean.Server.Utils namespace Lean.Server open Lsp inductive GoToKind | declaration | definition | type deriving BEq, ToJson, FromJson def documentUriFromModule (srcSearchPath : SearchPath) (modName : Name) : IO (Option DocumentUri) := do let some modFname ← srcSearchPath.findModuleWithExt "lean" modName | pure none -- resolve symlinks (such as `src` in the build dir) so that files are opened -- in the right folder let modFname ← IO.FS.realPath modFname return some <| System.Uri.pathToUri modFname open Elab in def locationLinksFromDecl (srcSearchPath : SearchPath) (uri : DocumentUri) (n : Name) (originRange? : Option Range) : MetaM (Array LocationLink) := do let mod? ← findModuleOf? n let modUri? ← match mod? with | some modName => documentUriFromModule srcSearchPath modName | none => pure <| some uri let ranges? ← findDeclarationRanges? n if let (some ranges, some modUri) := (ranges?, modUri?) then let declRangeToLspRange (r : DeclarationRange) : Lsp.Range := { start := ⟨r.pos.line - 1, r.charUtf16⟩ «end» := ⟨r.endPos.line - 1, r.endCharUtf16⟩ } let ll : LocationLink := { originSelectionRange? := originRange? targetUri := modUri targetRange := declRangeToLspRange ranges.range targetSelectionRange := declRangeToLspRange ranges.selectionRange } return #[ll] return #[] end Lean.Server
ab603a2993ff1f13ea93d90cbd032a299150ed6f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/GeneralizeVars.lean
127903bd0f98862dc464c825326a97896f68ffa4
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,825
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Basic import Lean.Util.CollectFVars namespace Lean.Meta /-- Add to `forbidden` all a set of `FVarId`s containing `targets` and all variables they depend on. -/ partial def mkGeneralizationForbiddenSet (targets : Array Expr) (forbidden : FVarIdSet := {}) : MetaM FVarIdSet := do let mut s := { fvarSet := forbidden } let mut todo := #[] for target in targets do if target.isFVar then todo := todo.push target.fvarId! else s := collectFVars s (← instantiateMVars (← inferType target)) loop todo.toList s.fvarSet where visit (fvarId : FVarId) (todo : List FVarId) (s : FVarIdSet) : MetaM (List FVarId × FVarIdSet) := do let localDecl ← fvarId.getDecl let mut s' := collectFVars {} (← instantiateMVars localDecl.type) if let some val := localDecl.value? then s' := collectFVars s' (← instantiateMVars val) let mut todo := todo let mut s := s for fvarId in s'.fvarSet do unless s.contains fvarId do todo := fvarId :: todo s := s.insert fvarId return (todo, s) loop (todo : List FVarId) (s : FVarIdSet) : MetaM FVarIdSet := do match todo with | [] => return s | fvarId::todo => if s.contains fvarId then loop todo s else let (todo, s) ← visit fvarId todo <| s.insert fvarId loop todo s /-- Collect variables to be generalized. It uses the following heuristic - Collect forward dependencies that are not in the forbidden set, and depend on some variable in `targets`. - We use `mkForbiddenSet` to compute `forbidden`. Remark: we *not* collect instance implicit arguments nor auxiliary declarations for compiling recursive declarations. -/ def getFVarSetToGeneralize (targets : Array Expr) (forbidden : FVarIdSet) (ignoreLetDecls := false) : MetaM FVarIdSet := do let mut s : FVarIdSet := targets.foldl (init := {}) fun s target => if target.isFVar then s.insert target.fvarId! else s let mut r : FVarIdSet := {} for localDecl in (← getLCtx) do unless forbidden.contains localDecl.fvarId do unless localDecl.isAuxDecl || localDecl.binderInfo.isInstImplicit || (ignoreLetDecls && localDecl.isLet) do if (← findLocalDeclDependsOn localDecl (s.contains ·)) then r := r.insert localDecl.fvarId s := s.insert localDecl.fvarId return r def getFVarsToGeneralize (targets : Array Expr) (forbidden : FVarIdSet := {}) (ignoreLetDecls := false) : MetaM (Array FVarId) := do let forbidden ← mkGeneralizationForbiddenSet targets forbidden let s ← getFVarSetToGeneralize targets forbidden ignoreLetDecls sortFVarIds s.toArray end Lean.Meta
51e6c296c05e4d12dc14107f1d4eb2f5354a7149
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/qpf/multivariate/constructions/cofix.lean
bd2d37c73de4e0a7c99bd8fa1fdc668d26360d79
[ "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
19,007
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Simon Hudon -/ import control.functor.multivariate import data.pfunctor.multivariate.basic import data.pfunctor.multivariate.M import data.qpf.multivariate.basic /-! # The final co-algebra of a multivariate qpf is again a qpf. For a `(n+1)`-ary QPF `F (α₀,..,αₙ)`, we take the least fixed point of `F` with regards to its last argument `αₙ`. The result is a `n`-ary functor: `fix F (α₀,..,αₙ₋₁)`. Making `fix F` into a functor allows us to take the fixed point, compose with other functors and take a fixed point again. ## Main definitions * `cofix.mk` - constructor * `cofix.dest - destructor * `cofix.corec` - corecursor: useful for formulating infinite, productive computations * `cofix.bisim` - bisimulation: proof technique to show the equality of possibly infinite values of `cofix F α` ## Implementation notes For `F` a QPF`, we define `cofix F α` in terms of the M-type of the polynomial functor `P` of `F`. We define the relation `Mcongr` and take its quotient as the definition of `cofix F α`. `Mcongr` is taken as the weakest bisimulation on M-type. See [avigad-carneiro-hudon2019] for more details. ## Reference * [Jeremy Avigad, Mario M. Carneiro and Simon Hudon, *Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ universe u open_locale mvfunctor namespace mvqpf open typevec mvpfunctor open mvfunctor (liftp liftr) variables {n : ℕ} {F : typevec.{u} (n+1) → Type u} [mvfunctor F] [q : mvqpf F] include q /-- `corecF` is used as a basis for defining the corecursor of `cofix F α`. `corecF` uses corecursion to construct the M-type generated by `q.P` and uses function on `F` as a corecursive step -/ def corecF {α : typevec n} {β : Type*} (g : β → F (α.append1 β)) : β → q.P.M α := M.corec _ (λ x, repr (g x)) theorem corecF_eq {α : typevec n} {β : Type*} (g : β → F (α.append1 β)) (x : β) : M.dest q.P (corecF g x) = append_fun id (corecF g) <$$> repr (g x) := by rw [corecF, M.dest_corec] /-- Characterization of desirable equivalence relations on M-types -/ def is_precongr {α : typevec n} (r : q.P.M α → q.P.M α → Prop) : Prop := ∀ ⦃x y⦄, r x y → abs (append_fun id (quot.mk r) <$$> M.dest q.P x) = abs (append_fun id (quot.mk r) <$$> M.dest q.P y) /-- Equivalence relation on M-types representing a value of type `cofix F` -/ def Mcongr {α : typevec n} (x y : q.P.M α) : Prop := ∃ r, is_precongr r ∧ r x y /-- Greatest fixed point of functor F. The result is a functor with one fewer parameters than the input. For `F a b c` a ternary functor, fix F is a binary functor such that ```lean cofix F a b = F a b (cofix F a b) ``` -/ def cofix (F : typevec (n + 1) → Type u) [mvfunctor F] [q : mvqpf F] (α : typevec n) := quot (@Mcongr _ F _ q α) instance {α : typevec n} [inhabited q.P.A] [Π (i : fin2 n), inhabited (α i)] : inhabited (cofix F α) := ⟨ quot.mk _ (default _) ⟩ /-- maps every element of the W type to a canonical representative -/ def Mrepr {α : typevec n} : q.P.M α → q.P.M α := corecF (abs ∘ M.dest q.P) /-- the map function for the functor `cofix F` -/ def cofix.map {α β : typevec n} (g : α ⟹ β) : cofix F α → cofix F β := quot.lift (λ x : q.P.M α, quot.mk Mcongr (g <$$> x)) begin rintros aa₁ aa₂ ⟨r, pr, ra₁a₂⟩, apply quot.sound, let r' := λ b₁ b₂, ∃ a₁ a₂ : q.P.M α, r a₁ a₂ ∧ b₁ = g <$$> a₁ ∧ b₂ = g <$$> a₂, use r', split, { show is_precongr r', rintros b₁ b₂ ⟨a₁, a₂, ra₁a₂, b₁eq, b₂eq⟩, let u : quot r → quot r' := quot.lift (λ x : q.P.M α, quot.mk r' (g <$$> x)) (by { intros a₁ a₂ ra₁a₂, apply quot.sound, exact ⟨a₁, a₂, ra₁a₂, rfl, rfl⟩ }), have hu : (quot.mk r' ∘ λ x : q.P.M α, g <$$> x) = u ∘ quot.mk r, { ext x, refl }, rw [b₁eq, b₂eq, M.dest_map, M.dest_map, ←q.P.comp_map, ←q.P.comp_map], rw [←append_fun_comp, id_comp, hu, hu, ←comp_id g, append_fun_comp], rw [q.P.comp_map, q.P.comp_map, abs_map, pr ra₁a₂, ←abs_map] }, show r' (g <$$> aa₁) (g <$$> aa₂), from ⟨aa₁, aa₂, ra₁a₂, rfl, rfl⟩ end instance cofix.mvfunctor : mvfunctor (cofix F) := { map := @cofix.map _ _ _ _} /-- Corecursor for `cofix F` -/ def cofix.corec {α : typevec n} {β : Type u} (g : β → F (α.append1 β)) : β → cofix F α := λ x, quot.mk _ (corecF g x) /-- Destructor for `cofix F` -/ def cofix.dest {α : typevec n} : cofix F α → F (α.append1 (cofix F α)) := quot.lift (λ x, append_fun id (quot.mk Mcongr) <$$> (abs (M.dest q.P x))) begin rintros x y ⟨r, pr, rxy⟩, dsimp, have : ∀ x y, r x y → Mcongr x y, { intros x y h, exact ⟨r, pr, h⟩ }, rw [←quot.factor_mk_eq _ _ this], dsimp, conv { to_lhs, rw [append_fun_comp_id, comp_map, ←abs_map, pr rxy, abs_map, ←comp_map, ←append_fun_comp_id] } end /-- Abstraction function for `cofix F α` -/ def cofix.abs {α} : q.P.M α → cofix F α := quot.mk _ /-- Representation function for `cofix F α` -/ def cofix.repr {α} : cofix F α → q.P.M α := M.corec _ $ repr ∘ cofix.dest /-- Corecursor for `cofix F` -/ def cofix.corec'₁ {α : typevec n} {β : Type u} (g : Π {X}, (β → X) → F (α.append1 X)) (x : β) : cofix F α := cofix.corec (λ x, g id) x /-- More flexible corecursor for `cofix F`. Allows the return of a fully formed value instead of making a recursive call -/ def cofix.corec' {α : typevec n} {β : Type u} (g : β → F (α.append1 (cofix F α ⊕ β))) (x : β) : cofix F α := let f : α ::: cofix F α ⟹ α ::: (cofix F α ⊕ β) := id ::: sum.inl in cofix.corec (sum.elim (mvfunctor.map f ∘ cofix.dest) g) (sum.inr x : cofix F α ⊕ β) /-- Corecursor for `cofix F`. The shape allows recursive calls to look like recursive calls. -/ def cofix.corec₁ {α : typevec n} {β : Type u} (g : Π {X}, (cofix F α → X) → (β → X) → β → F (α ::: X)) (x : β) : cofix F α := cofix.corec' (λ x, g sum.inl sum.inr x) x theorem cofix.dest_corec {α : typevec n} {β : Type u} (g : β → F (α.append1 β)) (x : β) : cofix.dest (cofix.corec g x) = append_fun id (cofix.corec g) <$$> g x := begin conv { to_lhs, rw [cofix.dest, cofix.corec] }, dsimp, rw [corecF_eq, abs_map, abs_repr, ←comp_map, ←append_fun_comp], reflexivity end /-- constructor for `cofix F` -/ def cofix.mk {α : typevec n} : F (α.append1 $ cofix F α) → cofix F α := cofix.corec (λ x, append_fun id (λ i : cofix F α, cofix.dest.{u} i) <$$> x) /-! ## Bisimulation principles for `cofix F` The following theorems are bisimulation principles. The general idea is to use a bisimulation relation to prove the equality between specific values of type `cofix F α`. A bisimulation relation `R` for values `x y : cofix F α`: * holds for `x y`: `R x y` * for any values `x y` that satisfy `R`, their root has the same shape and their children can be paired in such a way that they satisfy `R`. -/ private theorem cofix.bisim_aux {α : typevec n} (r : cofix F α → cofix F α → Prop) (h' : ∀ x, r x x) (h : ∀ x y, r x y → append_fun id (quot.mk r) <$$> cofix.dest x = append_fun id (quot.mk r) <$$> cofix.dest y) : ∀ x y, r x y → x = y := begin intro x, apply quot.induction_on x, clear x, intros x y, apply quot.induction_on y, clear y, intros y rxy, apply quot.sound, let r' := λ x y, r (quot.mk _ x) (quot.mk _ y), have : is_precongr r', { intros a b r'ab, have h₀ : append_fun id (quot.mk r ∘ quot.mk Mcongr) <$$> abs (M.dest q.P a) = append_fun id (quot.mk r ∘ quot.mk Mcongr) <$$> abs (M.dest q.P b) := by rw [append_fun_comp_id, comp_map, comp_map]; exact h _ _ r'ab, have h₁ : ∀ u v : q.P.M α, Mcongr u v → quot.mk r' u = quot.mk r' v, { intros u v cuv, apply quot.sound, dsimp [r'], rw quot.sound cuv, apply h' }, let f : quot r → quot r' := quot.lift (quot.lift (quot.mk r') h₁) begin intro c, apply quot.induction_on c, clear c, intros c d, apply quot.induction_on d, clear d, intros d rcd, apply quot.sound, apply rcd end, have : f ∘ quot.mk r ∘ quot.mk Mcongr = quot.mk r' := rfl, rw [←this, append_fun_comp_id, q.P.comp_map, q.P.comp_map, abs_map, abs_map, abs_map, abs_map, h₀] }, refine ⟨r', this, rxy⟩ end /-- Bisimulation principle using `map` and `quot.mk` to match and relate children of two trees. -/ theorem cofix.bisim_rel {α : typevec n} (r : cofix F α → cofix F α → Prop) (h : ∀ x y, r x y → append_fun id (quot.mk r) <$$> cofix.dest x = append_fun id (quot.mk r) <$$> cofix.dest y) : ∀ x y, r x y → x = y := let r' x y := x = y ∨ r x y in begin intros x y rxy, apply cofix.bisim_aux r', { intro x, left, reflexivity }, { intros x y r'xy, cases r'xy, { rw r'xy }, have : ∀ x y, r x y → r' x y := λ x y h, or.inr h, rw ←quot.factor_mk_eq _ _ this, dsimp, rw [append_fun_comp_id, append_fun_comp_id], rw [@comp_map _ _ _ q _ _ _ (append_fun id (quot.mk r)), @comp_map _ _ _ q _ _ _ (append_fun id (quot.mk r))], rw h _ _ r'xy }, right, exact rxy end /-- Bisimulation principle using `liftr` to match and relate children of two trees. -/ theorem cofix.bisim {α : typevec n} (r : cofix F α → cofix F α → Prop) (h : ∀ x y, r x y → liftr (rel_last α r) (cofix.dest x) (cofix.dest y)) : ∀ x y, r x y → x = y := begin apply cofix.bisim_rel, intros x y rxy, rcases (liftr_iff (rel_last α r) _ _).mp (h x y rxy) with ⟨a, f₀, f₁, dxeq, dyeq, h'⟩, rw [dxeq, dyeq, ←abs_map, ←abs_map, mvpfunctor.map_eq, mvpfunctor.map_eq], rw [←split_drop_fun_last_fun f₀, ←split_drop_fun_last_fun f₁], rw [append_fun_comp_split_fun, append_fun_comp_split_fun], rw [id_comp, id_comp], congr' 2 with i j, cases i with _ i; dsimp, { apply quot.sound, apply h' _ j }, { change f₀ _ j = f₁ _ j, apply h' _ j }, end open mvfunctor /-- Bisimulation principle using `liftr'` to match and relate children of two trees. -/ theorem cofix.bisim₂ {α : typevec n} (r : cofix F α → cofix F α → Prop) (h : ∀ x y, r x y → liftr' (rel_last' α r) (cofix.dest x) (cofix.dest y)) : ∀ x y, r x y → x = y := cofix.bisim _ $ by intros; rw ← liftr_last_rel_iff; apply h; assumption /-- Bisimulation principle the values `⟨a,f⟩` of the polynomial functor representing `cofix F α` as well as an invariant `Q : β → Prop` and a state `β` generating the left-hand side and right-hand side of the equality through functions `u v : β → cofix F α` -/ theorem cofix.bisim' {α : typevec n} {β : Type*} (Q : β → Prop) (u v : β → cofix F α) (h : ∀ x, Q x → ∃ a f' f₀ f₁, cofix.dest (u x) = abs ⟨a, q.P.append_contents f' f₀⟩ ∧ cofix.dest (v x) = abs ⟨a, q.P.append_contents f' f₁⟩ ∧ ∀ i, ∃ x', Q x' ∧ f₀ i = u x' ∧ f₁ i = v x') : ∀ x, Q x → u x = v x := λ x Qx, let R := λ w z : cofix F α, ∃ x', Q x' ∧ w = u x' ∧ z = v x' in cofix.bisim R (λ x y ⟨x', Qx', xeq, yeq⟩, begin rcases h x' Qx' with ⟨a, f', f₀, f₁, ux'eq, vx'eq, h'⟩, rw liftr_iff, refine ⟨a, q.P.append_contents f' f₀, q.P.append_contents f' f₁, xeq.symm ▸ ux'eq, yeq.symm ▸ vx'eq, _⟩, intro i, cases i, { apply h' }, { intro j, apply eq.refl }, end) _ _ ⟨x, Qx, rfl, rfl⟩ lemma cofix.mk_dest {α : typevec n} (x : cofix F α) : cofix.mk (cofix.dest x) = x := begin apply cofix.bisim_rel (λ x y : cofix F α, x = cofix.mk (cofix.dest y)) _ _ _ rfl, dsimp, intros x y h, rw h, conv { to_lhs, congr, skip, rw [cofix.mk], rw cofix.dest_corec}, rw [←comp_map, ←append_fun_comp, id_comp], rw [←comp_map, ←append_fun_comp, id_comp, ←cofix.mk], congr' 2 with u, apply quot.sound, refl end lemma cofix.dest_mk {α : typevec n} (x : F (α.append1 $ cofix F α)) : cofix.dest (cofix.mk x) = x := begin have : cofix.mk ∘ cofix.dest = @_root_.id (cofix F α) := funext cofix.mk_dest, rw [cofix.mk, cofix.dest_corec, ←comp_map, ←cofix.mk, ← append_fun_comp, this, id_comp, append_fun_id_id, mvfunctor.id_map] end lemma cofix.ext {α : typevec n} (x y : cofix F α) (h : x.dest = y.dest) : x = y := by rw [← cofix.mk_dest x,h,cofix.mk_dest] lemma cofix.ext_mk {α : typevec n} (x y : F (α ::: cofix F α)) (h : cofix.mk x = cofix.mk y) : x = y := by rw [← cofix.dest_mk x,h,cofix.dest_mk] /-! `liftr_map`, `liftr_map_last` and `liftr_map_last'` are useful for reasoning about the induction step in bisimulation proofs. -/ section liftr_map omit q theorem liftr_map {α β : typevec n} {F' : typevec n → Type u} [mvfunctor F'] [is_lawful_mvfunctor F'] (R : β ⊗ β ⟹ repeat n Prop) (x : F' α) (f g : α ⟹ β) (h : α ⟹ subtype_ R) (hh : subtype_val _ ⊚ h = (f ⊗' g) ⊚ prod.diag) : liftr' R (f <$$> x) (g <$$> x) := begin rw liftr_def, existsi h <$$> x, rw [mvfunctor.map_map,comp_assoc,hh,← comp_assoc,fst_prod_mk,comp_assoc,fst_diag], rw [mvfunctor.map_map,comp_assoc,hh,← comp_assoc,snd_prod_mk,comp_assoc,snd_diag], dsimp [liftr'], split; refl, end open function theorem liftr_map_last [is_lawful_mvfunctor F] {α : typevec n} {ι ι'} (R : ι' → ι' → Prop) (x : F (α ::: ι)) (f g : ι → ι') (hh : ∀ x : ι, R (f x) (g x)) : liftr' (rel_last' _ R) ((id ::: f) <$$> x) ((id ::: g) <$$> x) := let h : ι → { x : ι' × ι' // uncurry R x } := λ x, ⟨ (f x,g x), hh x ⟩ in let b : α ::: ι ⟹ _ := @diag_sub n α ::: h, c : subtype_ α.repeat_eq ::: {x // uncurry R x} ⟹ (λ (i : fin2 (n)), {x // of_repeat (α.rel_last' R i.fs x)}) ::: subtype (uncurry R) := of_subtype _ ::: id in have hh : subtype_val _ ⊚ to_subtype _ ⊚ from_append1_drop_last ⊚ c ⊚ b = (id ::: f ⊗' id ::: g) ⊚ prod.diag, by { dsimp [c,b], apply eq_of_drop_last_eq, { dsimp, simp only [prod_map_id, drop_fun_prod, drop_fun_append_fun, drop_fun_diag, id_comp, drop_fun_to_subtype], erw [to_subtype_of_subtype_assoc,id_comp], clear_except, ext i x : 2, induction i, refl, apply i_ih, }, simp only [h, last_fun_from_append1_drop_last, last_fun_to_subtype, last_fun_append_fun, last_fun_subtype_val, comp.left_id, last_fun_comp, last_fun_prod], dsimp, ext1, refl }, liftr_map _ _ _ _ (to_subtype _ ⊚ from_append1_drop_last ⊚ c ⊚ b) hh theorem liftr_map_last' [is_lawful_mvfunctor F] {α : typevec n} {ι} (R : ι → ι → Prop) (x : F (α ::: ι)) (f : ι → ι) (hh : ∀ x : ι, R (f x) x) : liftr' (rel_last' _ R) ((id ::: f) <$$> x) x := begin have := liftr_map_last R x f id hh, rwa [append_fun_id_id,mvfunctor.id_map] at this, end end liftr_map lemma cofix.abs_repr {α} (x : cofix F α) : quot.mk _ (cofix.repr x) = x := begin let R := λ x y : cofix F α, cofix.abs (cofix.repr y) = x, refine cofix.bisim₂ R _ _ _ rfl, clear x, rintros x y h, dsimp [R] at h, subst h, dsimp [cofix.dest,cofix.abs], induction y using quot.ind, simp only [cofix.repr, M.dest_corec, abs_map, abs_repr], conv { congr, skip, rw cofix.dest }, dsimp, rw [mvfunctor.map_map,mvfunctor.map_map,← append_fun_comp_id,← append_fun_comp_id], let f : α ::: (P F).M α ⟹ subtype_ (α.rel_last' R) := split_fun diag_sub (λ x, ⟨(cofix.abs (cofix.abs x).repr, cofix.abs x),_⟩), refine liftr_map _ _ _ _ f _, { simp only [←append_prod_append_fun, prod_map_id], apply eq_of_drop_last_eq, { dsimp, simp only [drop_fun_diag], erw subtype_val_diag_sub }, ext1, simp only [cofix.abs, prod.mk.inj_iff, prod_map, function.comp_app, last_fun_append_fun, last_fun_subtype_val, last_fun_comp, last_fun_split_fun], dsimp [drop_fun_rel_last,last_fun,prod.diag], split; refl, }, dsimp [rel_last',split_fun,function.uncurry,R], refl, end section tactic setup_tactic_parser open tactic omit q /-- tactic for proof by bisimulation -/ meta def mv_bisim (e : parse texpr) (ids : parse with_ident_list) : tactic unit := do e ← to_expr e, (expr.pi n bi d b) ← retrieve $ do { generalize e, target }, `(@eq %%t %%l %%r) ← pure b, x ← mk_local_def `n d, v₀ ← mk_local_def `a t, v₁ ← mk_local_def `b t, x₀ ← mk_app ``eq [v₀,l.instantiate_var x], x₁ ← mk_app ``eq [v₁,r.instantiate_var x], xx ← mk_app ``and [x₀,x₁], ex ← lambdas [x] xx, ex ← mk_app ``Exists [ex] >>= lambdas [v₀,v₁], R ← pose `R none ex, refine ``(cofix.bisim₂ %%R _ _ _ ⟨_,rfl,rfl⟩), let f (a b : name) : name := if a = `_ then b else a, let ids := (ids ++ list.repeat `_ 5).zip_with f [`a,`b,`x,`Ha,`Hb], (ids₀,w::ids₁) ← pure $ list.split_at 2 ids, intro_lst ids₀, h ← intro1, [(_,[w,h],_)] ← cases_core h [w], cases h ids₁, pure () run_cmd add_interactive [``mv_bisim] end tactic theorem corec_roll {α : typevec n} {X Y} {x₀ : X} (f : X → Y) (g : Y → F (α ::: X)) : cofix.corec (g ∘ f) x₀ = cofix.corec (mvfunctor.map (id ::: f) ∘ g) (f x₀) := begin mv_bisim x₀, rw [Ha,Hb,cofix.dest_corec,cofix.dest_corec], rw [mvfunctor.map_map,← append_fun_comp_id], refine liftr_map_last _ _ _ _ _, intros a, refine ⟨a,rfl,rfl⟩ end theorem cofix.dest_corec' {α : typevec n} {β : Type u} (g : β → F (α.append1 (cofix F α ⊕ β))) (x : β) : cofix.dest (cofix.corec' g x) = append_fun id (sum.elim id (cofix.corec' g)) <$$> g x := begin rw [cofix.corec',cofix.dest_corec], dsimp, congr' with (i|i); rw corec_roll; dsimp [cofix.corec'], { mv_bisim i, rw [Ha,Hb,cofix.dest_corec], dsimp [(∘)], repeat { rw [mvfunctor.map_map,← append_fun_comp_id] }, apply liftr_map_last', dsimp [(∘),R], intros, exact ⟨_,rfl,rfl⟩ }, { congr' with y, erw [append_fun_id_id], simp [mvfunctor.id_map] }, end theorem cofix.dest_corec₁ {α : typevec n} {β : Type u} (g : Π {X}, (cofix F α → X) → (β → X) → β → F (α.append1 X)) (x : β) (h : ∀ X Y (f : cofix F α → X) (f' : β → X) (k : X → Y), g (k ∘ f) (k ∘ f') x = (id ::: k) <$$> g f f' x) : cofix.dest (cofix.corec₁ @g x) = g id (cofix.corec₁ @g) x := by rw [cofix.corec₁,cofix.dest_corec',← h]; refl instance mvqpf_cofix : mvqpf (cofix F) := { P := q.P.Mp, abs := λ α, quot.mk Mcongr, repr := λ α, cofix.repr, abs_repr := λ α, cofix.abs_repr, abs_map := λ α β g x, rfl } end mvqpf
37071d69d10c9040493c420acdadaa3bb3a5a31b
bae21755a4a03bbe0a5c22e258db8633407711ad
/library/init/category/monad_fail.lean
9c1475bb60d4a0579ea8bebd52e9530f06816653
[ "Apache-2.0" ]
permissive
nor-code/lean
f437357a8f85db0f06f186fa50fcb1bc75f6b122
aa306af3d7c47de3c7937c98d3aa919eb8da6f34
refs/heads/master
1,662,613,329,886
1,586,696,014,000
1,586,696,014,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
600
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.category.lift init.data.string.basic universes u v class monad_fail (m : Type u → Type v) := (fail : Π {a}, string → m a) def match_failed {α : Type u} {m : Type u → Type v} [monad_fail m] : m α := monad_fail.fail "match failed" instance monad_fail_lift (m n : Type u → Type v) [monad n] [monad_fail m] [has_monad_lift m n] : monad_fail n := { fail := λ α s, monad_lift (monad_fail.fail s : m α) }
44f90ee5776d172015082d7229f24c6179a83c8e
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/category/CompHaus.lean
990f1c3ac687d02e4234f940ed0ed469613075c2
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
1,820
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import topology.category.Top /-! # The category of Compact Hausdorff Spaces We construct the category of compact Hausdorff spaces. The type of compact Hausdorff spaces is denoted `CompHaus`, and it is endowed with a category instance making it a full subcategory of `Top`. The fully faithful functor `CompHaus ⥤ Top` is denoted `CompHaus_to_Top`. **Note:** The file `topology/category/Compactum.lean` provides the equivalence between `Compactum`, which is defined as the category of algebras for the ultrafilter monad, and `CompHaus`. `Compactum_to_CompHaus` is the functor from `Compactum` to `CompHaus` which is proven to be an equivalence of categories in `Compactum_to_CompHaus.is_equivalence`. See `topology/category/Compactum.lean` for a more detailed discussion where these definitions are introduced. -/ open category_theory /-- The type of Compact Hausdorff topological spaces. -/ structure CompHaus := (to_Top : Top) [is_compact : compact_space to_Top] [is_hausdorff : t2_space to_Top] namespace CompHaus instance : inhabited CompHaus := ⟨{to_Top := { α := pempty }}⟩ instance : has_coe_to_sort CompHaus := ⟨Type*, λ X, X.to_Top⟩ instance {X : CompHaus} : compact_space X := X.is_compact instance {X : CompHaus} : t2_space X := X.is_hausdorff instance category : category CompHaus := induced_category.category to_Top end CompHaus /-- The fully faithful embedding of `CompHaus` in `Top`. -/ def CompHaus_to_Top : CompHaus ⥤ Top := { obj := λ X, { α := X }, map := λ _ _ f, f } namespace CompHaus_to_Top instance : full CompHaus_to_Top := { preimage := λ _ _ f, f } instance : faithful CompHaus_to_Top := {} end CompHaus_to_Top
41dde3aca858a29dab6209cbb3692e2d88ac41c2
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/algebra.lean
e240d5ae977128e3162cdc5cf257073d8a0dea10
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,505
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 algebra.algebra.basic import algebra.order.smul /-! # Ordered algebras > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. An ordered algebra is an ordered semiring, which is an algebra over an ordered commutative semiring, for which scalar multiplication is "compatible" with the two orders. The prototypical example is 2x2 matrices over the reals or complexes (or indeed any C^* algebra) where the ordering the one determined by the positive cone of positive operators, i.e. `A ≤ B` iff `B - A = star R * R` for some `R`. (We don't yet have this example in mathlib.) ## Implementation Because the axioms for an ordered algebra are exactly the same as those for the underlying module being ordered, we don't actually introduce a new class, but just use the `ordered_smul` mixin. ## Tags ordered algebra -/ section ordered_algebra variables {R A : Type*} {a b : A} {r : R} variables [ordered_comm_ring R] [ordered_ring A] [algebra R A] [ordered_smul R A] lemma algebra_map_monotone : monotone (algebra_map R A) := λ a b h, begin rw [algebra.algebra_map_eq_smul_one, algebra.algebra_map_eq_smul_one, ←sub_nonneg, ←sub_smul], transitivity (b - a) • (0 : A), { simp, }, { exact smul_le_smul_of_nonneg zero_le_one (sub_nonneg.mpr h) } end end ordered_algebra
43398991037f357d84ea6f976e59d2e4729e9727
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/big_operators/multiset/basic.lean
6ca614001b23d022aa1b97831f38138f979a3059
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
16,803
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.big_operators.basic import data.multiset.basic /-! # Sums and products over multisets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define products and sums indexed by multisets. This is later used to define products and sums indexed by finite sets. ## Main declarations * `multiset.prod`: `s.prod f` is the product of `f i` over all `i ∈ s`. Not to be mistaken with the cartesian product `multiset.product`. * `multiset.sum`: `s.sum f` is the sum of `f i` over all `i ∈ s`. ## Implementation notes Nov 2022: To speed the Lean 4 port, lemmas requiring extra algebra imports (`data.list.big_operators.lemmas` rather than `.basic`) have been moved to a separate file, `algebra.big_operators.multiset.lemmas`. This split does not need to be permanent. -/ variables {ι α β γ : Type*} namespace multiset section comm_monoid variables [comm_monoid α] {s t : multiset α} {a : α} {m : multiset ι} {f g : ι → α} /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ @[to_additive "Sum of a multiset given a commutative additive monoid structure on `α`. `sum {a, b, c} = a + b + c`"] def prod : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 @[to_additive] lemma prod_eq_foldr (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive] lemma prod_eq_foldl (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, norm_cast, to_additive] lemma coe_prod (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ @[simp, to_additive] lemma prod_to_list (s : multiset α) : s.to_list.prod = s.prod := begin conv_rhs { rw ←coe_to_list s }, rw coe_prod, end @[simp, to_additive] lemma prod_zero : @prod α _ 0 = 1 := rfl @[simp, to_additive] lemma prod_cons (a : α) (s) : prod (a ::ₘ s) = a * prod s := foldr_cons _ _ _ _ _ @[simp, to_additive] lemma prod_erase [decidable_eq α] (h : a ∈ s) : a * (s.erase a).prod = s.prod := by rw [← s.coe_to_list, coe_erase, coe_prod, coe_prod, list.prod_erase (mem_to_list.2 h)] @[simp, to_additive] lemma prod_map_erase [decidable_eq ι] {a : ι} (h : a ∈ m) : f a * ((m.erase a).map f).prod = (m.map f).prod := by rw [← m.coe_to_list, coe_erase, coe_map, coe_map, coe_prod, coe_prod, list.prod_map_erase f (mem_to_list.2 h)] @[simp, to_additive] lemma prod_singleton (a : α) : prod {a} = a := by simp only [mul_one, prod_cons, ←cons_zero, eq_self_iff_true, prod_zero] @[to_additive] lemma prod_pair (a b : α) : ({a, b} : multiset α).prod = a * b := by rw [insert_eq_cons, prod_cons, prod_singleton] @[simp, to_additive] lemma prod_add (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp lemma prod_nsmul (m : multiset α) : ∀ (n : ℕ), (n • m).prod = m.prod ^ n | 0 := by { rw [zero_nsmul, pow_zero], refl } | (n + 1) := by rw [add_nsmul, one_nsmul, pow_add, pow_one, prod_add, prod_nsmul n] @[simp, to_additive] lemma prod_replicate (n : ℕ) (a : α) : (replicate n a).prod = a ^ n := by simp [replicate, list.prod_replicate] @[to_additive] lemma prod_map_eq_pow_single [decidable_eq ι] (i : ι) (hf : ∀ i' ≠ i, i' ∈ m → f i' = 1) : (m.map f).prod = f i ^ m.count i := begin induction m using quotient.induction_on with l, simp [list.prod_map_eq_pow_single i f hf], end @[to_additive] lemma prod_eq_pow_single [decidable_eq α] (a : α) (h : ∀ a' ≠ a, a' ∈ s → a' = 1) : s.prod = a ^ (s.count a) := begin induction s using quotient.induction_on with l, simp [list.prod_eq_pow_single a h], end @[to_additive] lemma pow_count [decidable_eq α] (a : α) : a ^ s.count a = (s.filter (eq a)).prod := by rw [filter_eq, prod_replicate] @[to_additive] lemma prod_hom [comm_monoid β] (s : multiset α) {F : Type*} [monoid_hom_class F α β] (f : F) : (s.map f).prod = f s.prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom f, quot_mk_to_coe, coe_map, coe_prod] @[to_additive] lemma prod_hom' [comm_monoid β] (s : multiset ι) {F : Type*} [monoid_hom_class F α β] (f : F) (g : ι → α) : (s.map $ λ i, f $ g i).prod = f (s.map g).prod := by { convert (s.map g).prod_hom f, exact (map_map _ _ _).symm } @[to_additive] lemma prod_hom₂ [comm_monoid β] [comm_monoid γ] (s : multiset ι) (f : α → β → γ) (hf : ∀ a b c d, f (a * b) (c * d) = f a c * f b d) (hf' : f 1 1 = 1) (f₁ : ι → α) (f₂ : ι → β) : (s.map $ λ i, f (f₁ i) (f₂ i)).prod = f (s.map f₁).prod (s.map f₂).prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom₂ f hf hf', quot_mk_to_coe, coe_map, coe_prod] @[to_additive] lemma prod_hom_rel [comm_monoid β] (s : multiset ι) {r : α → β → Prop} {f : ι → α} {g : ι → β} (h₁ : r 1 1) (h₂ : ∀ ⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (s.map f).prod (s.map g).prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom_rel h₁ h₂, quot_mk_to_coe, coe_map, coe_prod] @[to_additive] lemma prod_map_one : prod (m.map (λ i, (1 : α))) = 1 := by rw [map_const, prod_replicate, one_pow] @[simp, to_additive] lemma prod_map_mul : (m.map $ λ i, f i * g i).prod = (m.map f).prod * (m.map g).prod := m.prod_hom₂ (*) mul_mul_mul_comm (mul_one _) _ _ @[simp] lemma prod_map_neg [has_distrib_neg α] (s : multiset α) : (s.map has_neg.neg).prod = (-1) ^ s.card * s.prod := by { refine quotient.ind _ s, simp } @[to_additive] lemma prod_map_pow {n : ℕ} : (m.map $ λ i, f i ^ n).prod = (m.map f).prod ^ n := m.prod_hom' (pow_monoid_hom n : α →* α) f @[to_additive] lemma prod_map_prod_map (m : multiset β) (n : multiset γ) {f : β → γ → α} : prod (m.map $ λ a, prod $ n.map $ λ b, f a b) = prod (n.map $ λ b, prod $ m.map $ λ a, f a b) := multiset.induction_on m (by simp) (λ a m ih, by simp [ih]) @[to_additive] lemma prod_induction (p : α → Prop) (s : multiset α) (p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ a ∈ s, p a) : p s.prod := begin rw prod_eq_foldr, exact foldr_induction (*) (λ x y z, by simp [mul_left_comm]) 1 p s p_mul p_one p_s, end @[to_additive] lemma prod_induction_nonempty (p : α → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (hs : s ≠ ∅) (p_s : ∀ a ∈ s, p a) : p s.prod := begin revert s, refine multiset.induction _ _, { intro h, exfalso, simpa using h }, intros a s hs hsa hpsa, rw prod_cons, by_cases hs_empty : s = ∅, { simp [hs_empty, hpsa a] }, have hps : ∀ x, x ∈ s → p x, from λ x hxs, hpsa x (mem_cons_of_mem hxs), exact p_mul a s.prod (hpsa a (mem_cons_self a s)) (hs hs_empty hps), end lemma prod_dvd_prod_of_le (h : s ≤ t) : s.prod ∣ t.prod := by { obtain ⟨z, rfl⟩ := exists_add_of_le h, simp only [prod_add, dvd_mul_right] } end comm_monoid lemma prod_dvd_prod_of_dvd [comm_monoid β] {S : multiset α} (g1 g2 : α → β) (h : ∀ a ∈ S, g1 a ∣ g2 a) : (multiset.map g1 S).prod ∣ (multiset.map g2 S).prod := begin apply multiset.induction_on' S, { simp }, intros a T haS _ IH, simp [mul_dvd_mul (h a haS) IH] end section add_comm_monoid variables [add_comm_monoid α] /-- `multiset.sum`, the sum of the elements of a multiset, promoted to a morphism of `add_comm_monoid`s. -/ def sum_add_monoid_hom : multiset α →+ α := { to_fun := sum, map_zero' := sum_zero, map_add' := sum_add } @[simp] lemma coe_sum_add_monoid_hom : (sum_add_monoid_hom : multiset α → α) = sum := rfl end add_comm_monoid section comm_monoid_with_zero variables [comm_monoid_with_zero α] lemma prod_eq_zero {s : multiset α} (h : (0 : α) ∈ s) : s.prod = 0 := begin rcases multiset.exists_cons_of_mem h with ⟨s', hs'⟩, simp [hs', multiset.prod_cons] end variables [no_zero_divisors α] [nontrivial α] {s : multiset α} lemma prod_eq_zero_iff : s.prod = 0 ↔ (0 : α) ∈ s := quotient.induction_on s $ λ l, by { rw [quot_mk_to_coe, coe_prod], exact list.prod_eq_zero_iff } lemma prod_ne_zero (h : (0 : α) ∉ s) : s.prod ≠ 0 := mt prod_eq_zero_iff.1 h end comm_monoid_with_zero section division_comm_monoid variables [division_comm_monoid α] {m : multiset ι} {f g : ι → α} @[to_additive] lemma prod_map_inv' (m : multiset α) : (m.map has_inv.inv).prod = m.prod⁻¹ := m.prod_hom (inv_monoid_hom : α →* α) @[simp, to_additive] lemma prod_map_inv : (m.map $ λ i, (f i)⁻¹).prod = (m.map f).prod ⁻¹ := by { convert (m.map f).prod_map_inv', rw map_map } @[simp, to_additive] lemma prod_map_div : (m.map $ λ i, f i / g i).prod = (m.map f).prod / (m.map g).prod := m.prod_hom₂ (/) mul_div_mul_comm (div_one _) _ _ @[to_additive] lemma prod_map_zpow {n : ℤ} : (m.map $ λ i, f i ^ n).prod = (m.map f).prod ^ n := by { convert (m.map f).prod_hom (zpow_group_hom _ : α →* α), rw map_map, refl } end division_comm_monoid section non_unital_non_assoc_semiring variables [non_unital_non_assoc_semiring α] {a : α} {s : multiset ι} {f : ι → α} lemma sum_map_mul_left : sum (s.map (λ i, a * f i)) = a * sum (s.map f) := multiset.induction_on s (by simp) (λ i s ih, by simp [ih, mul_add]) lemma sum_map_mul_right : sum (s.map (λ i, f i * a)) = sum (s.map f) * a := multiset.induction_on s (by simp) (λ a s ih, by simp [ih, add_mul]) end non_unital_non_assoc_semiring section semiring variables [semiring α] lemma dvd_sum {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum := multiset.induction_on s (λ _, dvd_zero _) (λ x s ih h, by { rw sum_cons, exact dvd_add (h _ (mem_cons_self _ _)) (ih $ λ y hy, h _ $ mem_cons.2 $ or.inr hy) }) end semiring /-! ### Order -/ section ordered_comm_monoid variables [ordered_comm_monoid α] {s t : multiset α} {a : α} @[to_additive sum_nonneg] lemma one_le_prod_of_one_le : (∀ x ∈ s, (1 : α) ≤ x) → 1 ≤ s.prod := quotient.induction_on s $ λ l hl, by simpa using list.one_le_prod_of_one_le hl @[to_additive] lemma single_le_prod : (∀ x ∈ s, (1 : α) ≤ x) → ∀ x ∈ s, x ≤ s.prod := quotient.induction_on s $ λ l hl x hx, by simpa using list.single_le_prod hl x hx @[to_additive sum_le_card_nsmul] lemma prod_le_pow_card (s : multiset α) (n : α) (h : ∀ x ∈ s, x ≤ n) : s.prod ≤ n ^ s.card := begin induction s using quotient.induction_on, simpa using list.prod_le_pow_card _ _ h, end @[to_additive all_zero_of_le_zero_le_of_sum_eq_zero] lemma all_one_of_le_one_le_of_prod_eq_one : (∀ x ∈ s, (1 : α) ≤ x) → s.prod = 1 → ∀ x ∈ s, x = (1 : α) := begin apply quotient.induction_on s, simp only [quot_mk_to_coe, coe_prod, mem_coe], exact λ l, list.all_one_of_le_one_le_of_prod_eq_one, end @[to_additive] lemma prod_le_prod_of_rel_le (h : s.rel (≤) t) : s.prod ≤ t.prod := begin induction h with _ _ _ _ rh _ rt, { refl }, { rw [prod_cons, prod_cons], exact mul_le_mul' rh rt } end @[to_additive] lemma prod_map_le_prod_map {s : multiset ι} (f : ι → α) (g : ι → α) (h : ∀ i, i ∈ s → f i ≤ g i) : (s.map f).prod ≤ (s.map g).prod := prod_le_prod_of_rel_le $ rel_map.2 $ rel_refl_of_refl_on h @[to_additive] lemma prod_map_le_prod (f : α → α) (h : ∀ x, x ∈ s → f x ≤ x) : (s.map f).prod ≤ s.prod := prod_le_prod_of_rel_le $ rel_map_left.2 $ rel_refl_of_refl_on h @[to_additive] lemma prod_le_prod_map (f : α → α) (h : ∀ x, x ∈ s → x ≤ f x) : s.prod ≤ (s.map f).prod := @prod_map_le_prod αᵒᵈ _ _ f h @[to_additive card_nsmul_le_sum] lemma pow_card_le_prod (h : ∀ x ∈ s, a ≤ x) : a ^ s.card ≤ s.prod := by { rw [←multiset.prod_replicate, ←multiset.map_const], exact prod_map_le_prod _ h } end ordered_comm_monoid lemma prod_nonneg [ordered_comm_semiring α] {m : multiset α} (h : ∀ a ∈ m, (0 : α) ≤ a) : 0 ≤ m.prod := begin revert h, refine m.induction_on _ _, { rintro -, rw prod_zero, exact zero_le_one }, intros a s hs ih, rw prod_cons, exact mul_nonneg (ih _ $ mem_cons_self _ _) (hs $ λ a ha, ih _ $ mem_cons_of_mem ha), end /-- Slightly more general version of `multiset.prod_eq_one_iff` for a non-ordered `monoid` -/ @[to_additive "Slightly more general version of `multiset.sum_eq_zero_iff` for a non-ordered `add_monoid`"] lemma prod_eq_one [comm_monoid α] {m : multiset α} (h : ∀ x ∈ m, x = (1 : α)) : m.prod = 1 := begin induction m using quotient.induction_on with l, simp [list.prod_eq_one h], end @[to_additive] lemma le_prod_of_mem [canonically_ordered_monoid α] {m : multiset α} {a : α} (h : a ∈ m) : a ≤ m.prod := begin obtain ⟨m', rfl⟩ := exists_cons_of_mem h, rw [prod_cons], exact _root_.le_mul_right (le_refl a), end @[to_additive le_sum_of_subadditive_on_pred] lemma le_prod_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (p : α → Prop) (h_one : f 1 = 1) (hp_one : p 1) (h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b) (hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hps : ∀ a, a ∈ s → p a) : f s.prod ≤ (s.map f).prod := begin revert s, refine multiset.induction _ _, { simp [le_of_eq h_one] }, intros a s hs hpsa, have hps : ∀ x, x ∈ s → p x, from λ x hx, hpsa x (mem_cons_of_mem hx), have hp_prod : p s.prod, from prod_induction p s hp_mul hp_one hps, rw [prod_cons, map_cons, prod_cons], exact (h_mul a s.prod (hpsa a (mem_cons_self a s)) hp_prod).trans (mul_le_mul_left' (hs hps) _), end @[to_additive le_sum_of_subadditive] lemma le_prod_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_one : f 1 = 1) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) : f s.prod ≤ (s.map f).prod := le_prod_of_submultiplicative_on_pred f (λ i, true) h_one trivial (λ x y _ _ , h_mul x y) (by simp) s (by simp) @[to_additive le_sum_nonempty_of_subadditive_on_pred] lemma le_prod_nonempty_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (p : α → Prop) (h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b) (hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hs_nonempty : s ≠ ∅) (hs : ∀ a, a ∈ s → p a) : f s.prod ≤ (s.map f).prod := begin revert s, refine multiset.induction _ _, { intro h, exfalso, exact h rfl }, rintros a s hs hsa_nonempty hsa_prop, rw [prod_cons, map_cons, prod_cons], by_cases hs_empty : s = ∅, { simp [hs_empty] }, have hsa_restrict : (∀ x, x ∈ s → p x), from λ x hx, hsa_prop x (mem_cons_of_mem hx), have hp_sup : p s.prod, from prod_induction_nonempty p hp_mul hs_empty hsa_restrict, have hp_a : p a, from hsa_prop a (mem_cons_self a s), exact (h_mul a _ hp_a hp_sup).trans (mul_le_mul_left' (hs hs_empty hsa_restrict) _), end @[to_additive le_sum_nonempty_of_subadditive] lemma le_prod_nonempty_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) (hs_nonempty : s ≠ ∅) : f s.prod ≤ (s.map f).prod := le_prod_nonempty_of_submultiplicative_on_pred f (λ i, true) (by simp [h_mul]) (by simp) s hs_nonempty (by simp) @[simp] lemma sum_map_singleton (s : multiset α) : (s.map (λ a, ({a} : multiset α))).sum = s := multiset.induction_on s (by simp) (by simp) lemma abs_sum_le_sum_abs [linear_ordered_add_comm_group α] {s : multiset α} : abs s.sum ≤ (s.map abs).sum := le_sum_of_subadditive _ abs_zero abs_add s lemma sum_nat_mod (s : multiset ℕ) (n : ℕ) : s.sum % n = (s.map (% n)).sum % n := by induction s using multiset.induction; simp [nat.add_mod, *] lemma prod_nat_mod (s : multiset ℕ) (n : ℕ) : s.prod % n = (s.map (% n)).prod % n := by induction s using multiset.induction; simp [nat.mul_mod, *] lemma sum_int_mod (s : multiset ℤ) (n : ℤ) : s.sum % n = (s.map (% n)).sum % n := by induction s using multiset.induction; simp [int.add_mod, *] lemma prod_int_mod (s : multiset ℤ) (n : ℤ) : s.prod % n = (s.map (% n)).prod % n := by induction s using multiset.induction; simp [int.mul_mod, *] end multiset @[to_additive] lemma map_multiset_prod [comm_monoid α] [comm_monoid β] {F : Type*} [monoid_hom_class F α β] (f : F) (s : multiset α) : f s.prod = (s.map f).prod := (s.prod_hom f).symm @[to_additive] protected lemma monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β) (s : multiset α) : f s.prod = (s.map f).prod := (s.prod_hom f).symm
4ef0d7345f359e0d0ef9a1036552faca84edf65b
51241b440c9d9e72556bd50c272c2654f722af28
/20170116_POPL/backchain/back.lean
e86ffc7c8b29b8bd97816b5e00f38ae5e61749bd
[ "Apache-2.0" ]
permissive
jroesch/presentations
deb419a483a788fa6bf3c5b4949e151186e9ea6d
b64fd2bf65a64faf16c52729cde0436f0d2f2cca
refs/heads/master
1,610,543,247,969
1,484,284,236,000
1,484,284,236,000
78,833,725
0
0
null
1,484,298,759,000
1,484,298,759,000
null
UTF-8
Lean
false
false
4,725
lean
/- In this example, we show how to write a simple tactic for performing backward chaining. The tactic builds list membership proofs for goals such as a ∈ [b, c] ++ [b, a, b] -/ open list expr tactic universe variable u /- The tactic uses the following 4 theorems from the standard library. Here, we just give them shorter names, and state their types. -/ lemma in_tail {α : Type u} {a b : α} {l : list α} : a ∈ l → a ∈ b::l := mem_cons_of_mem _ lemma in_head {α : Type u} {a : α} {l : list α} : a ∈ a::l := mem_cons_self _ _ lemma in_left {α : Type u} {a : α} {l : list α} (r : list α) : a ∈ l → a ∈ l ++ r := mem_append_left _ lemma in_right {α : Type u} {a : α} (l : list α) {r : list α} : a ∈ r → a ∈ l ++ r := mem_append_right _ /- Now, we define two helper tactics for matching cons/append-applications. For example, (match_cons e) succeeds and return a pair (h, t) iff it is of the form (h::t). -/ meta def match_cons (e : expr) : tactic (expr × expr) := /- The tactic (match_app_of e `list.cons) succeeds if e is a list-cons application, and returns a list of arguments. The notationm `list.cons is a "name quotation". It is a shorthand for (name.mk_string "cons" (name.mk_string "list" name.anonymous)) We can pattern match in the do-notation. This definition is equivalent to do args ← match_app_of e `list.cons, match args with | [_, h, t] := return (h, t) | _ := failed end It is quite convenient when we have many nested patterns. -/ do [_, h, t] ← match_app_of e `list.cons | failed, return (h, t) meta def match_append (e : expr) : tactic (expr × expr) := do [_, _, l, r] ← match_app_of e `append | failed, return (l, r) /- The tactic (search_mem_list a e) tries to build a proof-term for (a ∈ e). -/ meta def search_mem_list : expr → expr → tactic expr | a e := /- First, we check if there is an assumption with type (a ∈ e). We use the helper tactic mk_app. It infers implicit arguments using type inference and type class resolution. Note that the type of mem is: Π {α : Type u₁} {γ : Type u₁ → Type u₂} [s : has_mem α γ], α → γ α → Prop It has 2 universe variables and 3 implicit arguments, where one of them is a type class instance. So, it is quite inconvenient to create mem-applications by hand. The tactic mk_app hides this complexity. The tactic (find_assumption m) succeeds if there is a hypothesis (h : m) in the local context of the main goal. It is implemented in Lean, and we can jump to its definition by using `M-.` (on Emacs) and `F12` (on VS Code). On VS Code, we can also "peek" on its definition by typing (Alt-F12). -/ (do m ← mk_app `mem [a, e], find_assumption m) <|> /- If e is of the form l++r, then we try to build a proof for (a ∈ l), if we succeed, we built a proof for (a ∈ l++r) using the lemma in_left. -/ (do (l, r) ← match_append e, h ← search_mem_list a l, mk_app `in_left [l, r, h]) <|> (do (l, r) ← match_append e, h ← search_mem_list a r, mk_app `in_right [l, r, h]) <|> (do (b, t) ← match_cons e, is_def_eq a b, mk_app `in_head [b, t]) <|> (do (b, t) ← match_cons e, h ← search_mem_list a t, mk_app `in_tail [a, b, t, h]) /- The tactic mk_mem_list tries to close the current goal using search_mem_list if it is of the form (a ∈ e). We can view mk_mem_list as an "overloaded lemma" as described by Gonthier et al. in the paper "How to make ad hoc proof automation less ad hoc" -/ meta def mk_mem_list : tactic unit := do t ← target, [_, _, _, a, e] ← match_app_of t `mem | failed, search_mem_list a e >>= exact example (a b c : nat) : a ∈ [b, c] ++ [b, a, b] := by mk_mem_list example (a b c : nat) : a ∈ [b, c] ++ [b, a+0, b] := by mk_mem_list example (a b c : nat) : a ∈ [b, c] ++ [b, c, c] ++ [b, a+0, b] := by mk_mem_list example (a b c : nat) (l : list nat) : a ∈ l → a ∈ [b, c] ++ b::l := by tactic.intros >> mk_mem_list example (a b c : nat) (l : list nat) : a ∈ l → a ∈ b::b::c::l ++ [c, c, b] := by tactic.intros >> mk_mem_list /- We can use mk_mem_list nested in our proofs -/ example (a b c : nat) (l₁ l₂ : list nat) : (a ∈ l₁ ∨ a ∈ l₂) → a ∈ b::l₂ ∨ a ∈ b::c::l₁ ++ [b, c] | (or.inl h) := or.inr (by mk_mem_list) | (or.inr r) := or.inl (by mk_mem_list) /- We can prove the same theorem using just tactics. -/ example (a b c : nat) (l₁ l₂ : list nat) : (a ∈ l₁ ∨ a ∈ l₂) → a ∈ b::l₂ ∨ a ∈ b::c::l₁ ++ [b, c] := begin intro h, cases h, {apply or.inr, mk_mem_list}, {apply or.inl, mk_mem_list} end
95c3527da5feeb3f2a2c1e9921cc0d47282b5357
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/stage0/src/Lean/Meta/AbstractNestedProofs.lean
de623639affadc86358c3db2ea5e4d356c0dc095
[ "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
2,974
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.Closure namespace Lean.Meta namespace AbstractNestedProofs def isNonTrivialProof (e : Expr) : MetaM Bool := do if !(← isProof e) then pure false else e.withApp fun f args => pure $ !f.isAtomic || args.any fun arg => !arg.isAtomic structure Context where baseName : Name structure State where nextIdx : Nat := 1 abbrev M := ReaderT Context $ MonadCacheT ExprStructEq Expr $ StateRefT State MetaM private def mkAuxLemma (e : Expr) : M Expr := do let ctx ← read let s ← get let lemmaName ← mkAuxName (ctx.baseName ++ `proof) s.nextIdx modify fun s => { s with nextIdx := s.nextIdx + 1 } /- We turn on zeta-expansion to make sure we don't need to perform an expensive `check` step to identify which let-decls can be abstracted. If we design a more efficient test, we can avoid the eager zeta expasion step. It a benchmark created by @selsam, The extra `check` step was a bottleneck. -/ mkAuxDefinitionFor lemmaName e (zeta := true) partial def visit (e : Expr) : M Expr := do if e.isAtomic then pure e else let visitBinders (xs : Array Expr) (k : M Expr) : M Expr := do let localInstances ← getLocalInstances let mut lctx ← getLCtx for x in xs do let xFVarId := x.fvarId! let localDecl ← getLocalDecl xFVarId let type ← visit localDecl.type let localDecl := localDecl.setType type let localDecl ← match localDecl.value? with | some value => do let value ← visit value; pure $ localDecl.setValue value | none => pure localDecl lctx :=lctx.modifyLocalDecl xFVarId fun _ => localDecl withLCtx lctx localInstances k checkCache { val := e : ExprStructEq } fun _ => do if (← isNonTrivialProof e) then mkAuxLemma e else match e with | Expr.lam _ _ _ _ => lambdaLetTelescope e fun xs b => visitBinders xs do mkLambdaFVars xs (← visit b) | Expr.letE _ _ _ _ _ => lambdaLetTelescope e fun xs b => visitBinders xs do mkLambdaFVars xs (← visit b) | Expr.forallE _ _ _ _ => forallTelescope e fun xs b => visitBinders xs do mkForallFVars xs (← visit b) | Expr.mdata _ b _ => return e.updateMData! (← visit b) | Expr.proj _ _ b _ => return e.updateProj! (← visit b) | Expr.app _ _ _ => e.withApp fun f args => return mkAppN f (← args.mapM visit) | _ => pure e end AbstractNestedProofs /-- Replace proofs nested in `e` with new lemmas. The new lemmas have names of the form `mainDeclName.proof_<idx>` -/ def abstractNestedProofs (mainDeclName : Name) (e : Expr) : MetaM Expr := AbstractNestedProofs.visit e |>.run { baseName := mainDeclName } |>.run |>.run' { nextIdx := 1 } end Lean.Meta
3e23d3fed4fcb7fd5af5313c9d3598bab5bcf3ae
f4bff2062c030df03d65e8b69c88f79b63a359d8
/src/game/sets/L01defs.lean
f1dc2fa57cc61a08c88938b4b2c455740514c868
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,956
lean
import data.set.basic import kb_defs namespace xena -- hide variable X : Type -- we will think of X as a set here -- begin hide /- The first level, originally written by KMB. -/ -- end hide /- # Chapter 1 : Sets ## Level 1 : Introduction to sets. This chapter assumes you are familiar with the following tactics: `rw`, `intro`, `apply`, `exact`, `cases`, `split`, `left`, `right` and `exfalso`.<br> (TODO (kmb) : check this list is exhaustive) If you are not, try playing Function World and Proposition World of the Natural Number Game. ## Sets in Lean In this world, there will be an ambient "big" set `X` (actually `X` will be a type), and we will consider subsets of `X`. The type of subsets of `X` is called `set X`. So if you see `A : set X` it means that `A` is a subset of `X`. ## subsets (⊆) and `subset_iff` If `A B : set X` (i.e. `A` and `B` are subsets of `X`), then `A ⊆ B` is a Proposition, i.e. a true/false statement. Lean knows the following fact: ``` subset_iff : A ⊆ B ↔ ∀ x : X, x ∈ A → x ∈ B ``` Let's see if you can prove `A ⊆ A` by rewriting `subset_iff`. -/ /- Axiom : subset_iff A ⊆ B ↔ ∀ x : X, x ∈ A → x ∈ B -/ /- Hint : Hint To make progress with a goal of form `∀ a : X, ...`, introduce a term of type `X` by using a familiar tactic. In this example, using `intro a,` will introduce an arbitrary term of type X. Note that this is the tactic we use to assume a hypothesis (when proving an implication), or to choose an arbitrary element of some domain (when defining a function). Use the same tactic to introduce an appropriately named hypothesis for an implication, and close the goal with the `exact` tactic. -/ /- If you get stuck, you can click on the hints for more details! -/ /- Lemma If $A$ is a set of elements of type X, then $A \subseteq A$. -/ lemma subset.refl (A : set X) : A ⊆ A := begin rw subset_iff, intros x h, exact h end end xena --hide
f5c0e86de7c9c9dcfc316f12a5e677ebcbf6fe72
618003631150032a5676f229d13a079ac875ff77
/archive/100-theorems-list/42_inverse_triangle_sum.lean
6e0f3fc22dec823cbafa34694bc63fc9edbdac32
[ "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
1,044
lean
/- Copyright (c) 2020. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jalex Stark, Yury Kudryashov -/ import tactic import algebra.big_operators import data.real.basic /-! # Sum of the Reciprocals of the Triangular Numbers This file proves Theorem 42 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/). We interpret “triangular numbers” as naturals of the form $\frac{k(k+1)}{2}$ for natural `k`. We prove that the sum of the first `n` triangular numbers is equal to $2 - \frac2n$. ## Tags discrete_sum -/ open_locale big_operators open finset lemma inverse_triangle_sum : ∀ n, ∑ k in range n, (2 : ℚ) / (k * (k + 1)) = if n = 0 then 0 else 2 - (2 : ℚ) / n := begin refine sum_range_induction _ _ (if_pos rfl) _, rintro (_|n), { rw [if_neg, if_pos]; norm_num }, simp_rw [if_neg (nat.succ_ne_zero _), nat.succ_eq_add_one], have A : (n + 1 + 1 : ℚ) ≠ 0, by { norm_cast, norm_num }, push_cast, field_simp [nat.cast_add_one_ne_zero, A], ring end
a3b2021f390275a2b8837bd4c1e663fbeb4f6277
246309748072bf9f8da313401699689ebbecd94d
/src/linear_algebra/affine_space/combination.lean
658a34f0a33180ae3fae33f0ffb5c2a51a159114
[ "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
24,962
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import data.indicator_function import linear_algebra.affine_space.basic import linear_algebra.finsupp noncomputable theory open_locale big_operators open_locale classical /-! # Affine combinations of points 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 -/ namespace finset 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 ι) /-- 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 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 (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 (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 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 `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] /-- 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 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) : affine_map 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_assoc, 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 p : affine_map k (ι → k) P).linear = s.weighted_vsub p := rfl /-- 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 p w = s.weighted_vsub_of_point p (classical.choice S.nonempty) w +ᵥ (classical.choice S.nonempty) := rfl /-- `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 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 p w₂ = s.affine_combination 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 p w₁ -ᵥ s.affine_combination p w₂ = s.weighted_vsub p (w₁ - w₂) := by rw [←affine_map.linear_map_vsub, affine_combination_linear, vsub_eq_sub] /-- 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 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 p w = s₂.affine_combination p (set.indicator ↑s₁ w) := by rw [affine_combination_apply, affine_combination_apply, weighted_vsub_of_point_indicator_subset _ _ _ 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 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 p w) ↔ ∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = 1), p0 = fs.affine_combination (λ (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 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 ι) /-- 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 p (s.centroid_weights k) /-- The definition of the centroid. -/ lemma centroid_def (p : ι → P) : s.centroid k p = s.affine_combination p (s.centroid_weights k) := rfl /-- 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] 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 by_cases hn : nonempty ι, { cases hn with i0, rw [vector_span_range_eq_span_range_vsub_right k p i0, ←set.image_univ, finsupp.mem_span_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 _ } }, { simp [finset.eq_empty_of_not_nonempty hn s] } 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 p w ∈ affine_span k (set.range p) := begin 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 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 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 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 split, { by_cases hn : nonempty ι, { cases hn with i0, rw [vector_span_range_eq_span_range_vsub_right k p i0, ←set.image_univ, finsupp.mem_span_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] } }, { rw [set.range_eq_empty.2 hn, vector_span_empty, submodule.mem_bot], intro hv, use [∅], simp [hv] } }, { 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. -/ 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 p w := begin 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 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 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 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 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) : affine_map k ((ι → P) × P) 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
eb88d6b718870a7f50bb88c0de47eb0766338256
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/natural_transformation.lean
5b6b0875a75db469473a2a48237d17a0b1fa1e9d
[]
no_license
PatrickMassot/lean-category-theory
0f56a83464396a253c28a42dece16c93baf8ad74
ef239978e91f2e1c3b8e88b6e9c64c155dc56c99
refs/heads/master
1,629,739,187,316
1,512,422,659,000
1,512,422,659,000
113,098,786
0
0
null
1,512,424,022,000
1,512,424,022,000
null
UTF-8
Lean
false
false
3,849
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Tim Baumann, Stephen Morgan, Scott Morrison import .isomorphism import .functor open categories open categories.isomorphism open categories.functor namespace categories.natural_transformation structure {u1 v1 u2 v2} NaturalTransformation { C : Category.{u1 v1} } { D : Category.{u2 v2} } ( F G : Functor C D ) := (components: Π X : C.Obj, D.Hom (F.onObjects X) (G.onObjects X)) (naturality: ∀ { X Y : C.Obj } (f : C.Hom X Y), D.compose (F.onMorphisms f) (components Y) = D.compose (components X) (G.onMorphisms f)) attribute [ematch] NaturalTransformation.naturality -- This defines a coercion so we can write `α X` for `components α X`. instance NaturalTransformation_to_components { C D : Category } { F G : Functor C D } : has_coe_to_fun (NaturalTransformation F G) := { F := λ f, Π X : C.Obj, D.Hom (F X) (G X), coe := NaturalTransformation.components } -- We'll want to be able to prove that two natural transformations are equal if they are componentwise equal. @[applicable] lemma {u1 v1 u2 v2} NaturalTransformations_componentwise_equal { C : Category.{u1 v1} } { D : Category.{u2 v2} } { F G : Functor C D } ( α β : NaturalTransformation F G ) ( w : ∀ X : C.Obj, α.components X = β.components X ) : α = β := begin induction α with α_components α_naturality, induction β with β_components β_naturality, have hc : α_components = β_components := funext w, subst hc end definition {u1 v1 u2 v2} IdentityNaturalTransformation { C : Category.{u1 v1} } { D : Category.{u2 v2} } (F : Functor C D) : NaturalTransformation F F := { components := λ X, D.identity (F.onObjects X), naturality := ♮ } definition {u1 v1 u2 v2} vertical_composition_of_NaturalTransformations { C : Category.{u1 v1} } { D : Category.{u2 v2} } { F G H : Functor C D } ( α : NaturalTransformation F G ) ( β : NaturalTransformation G H ) : NaturalTransformation F H := { components := λ X, D.compose (α.components X) (β.components X), naturality := ♮ } notation α `∘̬` β := vertical_composition_of_NaturalTransformations α β open categories.functor @[simp] lemma {u1 v1 u2 v2 u3 v3} FunctorComposition.onObjects { C : Category.{u1 v1} } { D : Category.{u2 v2} } { E : Category.{u3 v3} } { F : Functor C D } { G : Functor D E } ( X : C.Obj ) : (FunctorComposition F G).onObjects X = G.onObjects (F.onObjects X) := ♯ definition {u1 v1 u2 v2 u3 v3} horizontal_composition_of_NaturalTransformations { C : Category.{u1 v1} } { D : Category.{u2 v2} } { E : Category.{u3 v3} } { F G : Functor C D } { H I : Functor D E } ( α : NaturalTransformation F G ) ( β : NaturalTransformation H I ) : NaturalTransformation (FunctorComposition F H) (FunctorComposition G I) := { components := λ X : C.Obj, E.compose (β.components (F.onObjects X)) (I.onMorphisms (α.components X)), naturality := ♯ } notation α `∘ₕ` β := horizontal_composition_of_NaturalTransformations α β definition {u1 v1 u2 v2 u3 v3} whisker_on_left { C : Category.{u1 v1} } { D : Category.{u2 v2} } { E : Category.{u3 v3} } ( F : Functor C D ) { G H : Functor D E } ( α : NaturalTransformation G H ) : NaturalTransformation (FunctorComposition F G) (FunctorComposition F H) := (IdentityNaturalTransformation F) ∘ₕ α definition {u1 v1 u2 v2 u3 v3} whisker_on_right { C : Category.{u1 v1} } { D : Category.{u2 v2} } { E : Category.{u3 v3} } { F G : Functor C D } ( α : NaturalTransformation F G ) ( H : Functor D E ) : NaturalTransformation (FunctorComposition F H) (FunctorComposition G H) := α ∘ₕ (IdentityNaturalTransformation H) end categories.natural_transformation
adfe82c9228103440e826629174dc8823005682a
4da0c8e61fcd6ec3f3be47ee14a038850c03d0c3
/src/s5/syntax/basic.lean
f589a22e757890f302eabfb853568998f44fe817
[ "Apache-2.0" ]
permissive
bbentzen/mpl
fcbea60204bc8fd64667e0f76a5cebf4b67fb6ca
bb5066ec51fa11a4b66f440c4f6c9a3d8fb2e0de
refs/heads/master
1,625,175,849,308
1,624,207,634,000
1,624,207,634,000
142,774,375
9
0
null
null
null
null
UTF-8
Lean
false
false
887
lean
/- Copyright (c) 2018 Bruno Bentzen. All rights reserved. Released under the Apache License 2.0 (see "License"); Author: Bruno Bentzen -/ import ..default variable {σ : nat} /- a general modal system -/ inductive prf : ctx σ → form σ → Prop | ax {Γ} {p} (h : p ∈ Γ) : prf Γ p | pl1 {Γ} {p q} : prf Γ (p ⊃ (q ⊃ p)) | pl2 {Γ} {p q r} : prf Γ ((p ⊃ (q ⊃ r)) ⊃ ((p ⊃ q) ⊃ (p ⊃ r))) | pl3 {Γ} {p q} : prf Γ (((~p) ⊃ ~q) ⊃ (((~p) ⊃ q) ⊃ p)) | mp {Γ} {p q} (hpq: prf Γ (p ⊃ q)) (hp : prf Γ p) : prf Γ q | k {Γ} {p q} : prf Γ (◻(p ⊃ q) ⊃ (◻p ⊃ ◻q)) | t {Γ} {p} : prf Γ (◻p ⊃ p) | s4 {Γ} {p} : prf Γ (◻p ⊃ ◻◻p) | b {Γ} {p} : prf Γ (p ⊃ ◻◇p) | nec {Γ} {p} (h : prf · p) : prf Γ (◻p) notation Γ ` ⊢ₛ₅ ` p := prf Γ p notation Γ ` ⊬ₛ₅ ` p := prf Γ p → false
de0ad46edf59b59a29dad1b4ccbee2c41bd4f00c
750acab0c635b67751bcfec43c5411aa3941c441
/bootcamp.lean
4acd6319e1a98379dd162fe164adbd45111f6b38
[]
no_license
nthomas103/lean_work
912f8e662cdd73ba97f5d3655ddb8a5d2cd204c9
7e9785cae2b60a77b41922fd5d5b159a1fae415c
refs/heads/master
1,586,739,169,355
1,455,759,226,000
1,455,759,226,000
50,978,095
0
0
null
null
null
null
UTF-8
Lean
false
false
5,545
lean
import standard open prod prod.ops subtype real nat fin algebra --types check (λ n : ℕ, n) check (λ a b : ℕ, a + b) check ℕ check (λ a b : ℕ, a = b + 1) check true check λ n : ℕ, n ≥ 1 check λ (x : ℝ) (H : x ≠ 3), 1 / (x - 3) check @nat.induction_on check Type check Prop check Type₁ check Type₂ --defining functions definition add_one : ℕ → ℕ := λ n : ℕ, n + 1 eval add_one 5 --higher-order functions constant exp : ℝ → ℝ constant gcd : ℕ → ℕ → ℕ constant derivative : (ℝ → ℝ) → (ℝ → ℝ) constant integral : (ℝ → ℝ) → ℝ → ℝ → ℝ constant path_integral : ((ℝ → ℝ) → ℝ) → ℝ → ℝ → ℝ definition do_twice : (ℕ → ℕ) → (ℕ → ℕ) := λ (f : ℕ → ℕ) (x : ℕ), f (f x) eval do_twice add_one 4 --recursion definition fib : ℕ → ℕ | fib 0 := 1 | fib 1 := 1 | fib (a+2) := fib (a+1) + fib a eval fib 0 eval fib 1 eval fib 2 eval fib 3 eval fib 4 eval fib 5 eval fib 6 eval fib 7 theorem fib_pos : ∀ n, 0 < fib n | fib_pos 0 := sorry | fib_pos 1 := sorry | fib_pos (a+2) := sorry /-calc 0 = 0 + 0 : rfl ... < fib (a+1) + 0 : !add_lt_add_right !fib_pos ... < fib (a+1) + fib a : !add_lt_add_left !fib_pos ... = fib (a+2) : rfl-/ theorem nat_induct (P : ℕ → Prop) : ∀ n, P 0 → (∀ n, P n → P (n+1)) → P n | 0 p₀ _ := p₀ | (n+1) p₀ pind := pind n (nat_induct n p₀ pind) --polymorphism definition id_fun : Π (T : Type), T → T := λ (T : Type) (x : T), x definition do_thrice : Π (T : Type), (T → T) → (T → T) := λ (T : Type) (f : T → T) (x : T), f (f (f x)) definition composition : Π (A B C : Type), (A → B) → (B → C) → (A → C) := λ (A B C : Type) (f : A → B) (g : B → C) (a : A), g (f a) definition swap' : Π A B C, (A → B → C) → (B → A → C) := λ A B C f b a, f a b definition swap {A B C} (f : A → B → C) (b : B) (a : A) : C := f a b definition curry [reducible] {A B C} (f : A × B → C) : A → B → C := λ a b, f (a,b) definition uncurry [reducible] {A B C} (f : A → B → C) : A × B → C := λ ab, f ab.1 ab.2 theorem uncurry_curry {A B C} (f : A → B → C) : curry (uncurry f) = f := !eq.refl reveal uncurry_curry print uncurry_curry theorem curry_uncurry {A B C} (f : A × B → C) : uncurry (curry f) = f := funext (by blast) /-funext (λ ab, calc uncurry (curry f) ab = (curry f) ab.1 ab.2 : rfl ... = f (ab.1,ab.2) : rfl ... = f ab : eta)-/ print funext reveal curry_uncurry print curry_uncurry --dependent types constant safe_log : Π (x : ℝ), x > 0 → ℝ constant safe_inv : Π (x : ℝ), x ≠ 0 → ℝ constant differentiable : (ℝ → ℝ) → Prop constant safe_deriv : Π (f : ℝ → ℝ), differentiable f → (ℝ → ℝ) constant vector : Π (T : Type) (n : ℕ), fin n → T constant matrix : Π (T : Type) (m n : ℕ), fin m → fin n → T example : Π (a b : ℕ), a < b → a + a < b + b := sorry definition prime (p : nat) := p ≥ 2 ∧ ∀ m, m ∣ p → m = 1 ∨ m = p print prime --inductive types namespace hide inductive bool : Type := | tru : bool | fal : bool print bool.rec inductive nat : Type := | o : nat | s : nat → nat print nat.rec inductive list' : Type := | nil : list' | cons : nat → list' → list' inductive list (T : Type) : Type := | nil {} : list T | cons : T → list T → list T namespace list notation h :: t := cons h t notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l variable {T : Type} definition length : list T → ℕ | [] := 0 | (a :: l) := length l + 1 definition append : list T → list T → list T | [] l₂ := l₂ | (h :: l₁) l₂ := h :: (append l₁ l₂) notation l₁ ++ l₂ := append l₁ l₂ eval [1,2,3] ++ [3,2,(1:ℕ)] definition mem : T → list T → Prop | a [] := false | a (b :: l) := a = b ∨ mem a l variables {A B : Type} definition map (f : A → B) : list A → list B | [] := [] | (a :: l) := f a :: map l end list inductive btree : Type := sorry print btree.rec inductive eq (A : Type) : Type := | refl : ∀ a : A, a = a → eq A print eq.rec -- Curry-Howard correspondence inductive and (A B : Prop) := sorry inductive or (A B : Prop) := sorry inductive false : Prop print false definition not (A : Prop) : Prop := A → false print not end hide --structures: monoids, semigroups, groups, etc etc namespace hide structure has_mul (A : Type) := (mul : A → A → A) print has_mul inductive has_mul' (A : Type) := | mk : (A → A → A) → has_mul' A structure semigroup (A : Type) extends has_mul A := (assoc : ∀ a b c, mul (mul a b) c = mul a (mul b c)) inductive semigroup' (A : Type) := | mk : ∀ (mul : A → A → A), (∀ a b c, mul (mul a b) c = mul a (mul b c)) → semigroup' A structure has_one (A : Type) := (one : A) print has_one structure has_inv (A : Type) := (inv : A → A) structure monoid (A : Type) extends has_mul A, has_one A := sorry structure comm_semigroup (A : Type) extends semigroup A := sorry structure comm_monoid (A : Type) extends comm_semigroup A, monoid A print hide.comm_monoid --structure group (A : Type) end hide section group_proofs variables {G : Type} [group G] example (a : G) (h₁ : a = a⁻¹) : a * a = 1 := sorry example (a : G) (h₁ : a = a⁻¹) : a * a = 1 := sorry end group_proofs
88954ef158b6c5d1d700ed2ea99702037fc5ac47
7cef822f3b952965621309e88eadf618da0c8ae9
/src/tactic/cache.lean
688989596281cb4eb1b5690dfde71298cfc1d6da
[ "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
2,372
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic /-- Reset the instance cache for the main goal. -/ meta def reset_instance_cache : tactic unit := unfreeze_local_instances namespace interactive open interactive interactive.types /-- Unfreeze local instances, which allows us to revert instances in the context. -/ meta def unfreezeI := tactic.unfreeze_local_instances /-- Reset the instance cache. This allows any new instances added to the context to be used in typeclass inference. -/ meta def resetI := reset_instance_cache /-- Like `intro`, but uses the introduced variable in typeclass inference. -/ meta def introI (p : parse ident_?) : tactic unit := intro p >> reset_instance_cache /-- Like `intros`, but uses the introduced variable(s) in typeclass inference. -/ meta def introsI (p : parse ident_*) : tactic unit := intros p >> reset_instance_cache /-- Used to add typeclasses to the context so that they can be used in typeclass inference. The syntax is the same as `have`, but the proof-omitted version is not supported. For this one must write `have : t, { <proof> }, resetI, <proof>`. -/ meta def haveI (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse (tk ":=" *> texpr)) : tactic unit := do h ← match h with | none := get_unused_name "_inst" | some a := return a end, «have» (some h) q₁ (some q₂), match q₁ with | none := swap >> reset_instance_cache >> swap | some p₂ := reset_instance_cache end /-- Used to add typeclasses to the context so that they can be used in typeclass inference. The syntax is the same as `let`. -/ meta def letI (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := do h ← match h with | none := get_unused_name "_inst" | some a := return a end, «let» (some h) q₁ q₂, match q₁ with | none := swap >> reset_instance_cache >> swap | some p₂ := reset_instance_cache end /-- Like `exact`, but uses all variables in the context for typeclass inference. -/ meta def exactI (q : parse texpr) : tactic unit := reset_instance_cache >> exact q end interactive end tactic
3822c5acb83b58b0f712de7c50f01ae300df1261
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/real/nnreal.lean
3796090a1debf0811036494c5de575a3e6aee906
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
31,856
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.linear_ordered_comm_group_with_zero import algebra.big_operators.ring import data.real.basic import algebra.indicator_function import algebra.algebra.basic /-! # Nonnegative real numbers In this file we define `nnreal` (notation: `ℝ≥0`) to be the type of non-negative real numbers, a.k.a. the interval `[0, ∞)`. We also define the following operations and structures on `ℝ≥0`: * the order on `ℝ≥0` is the restriction of the order on `ℝ`; these relations define a conditionally complete linear order with a bottom element, `conditionally_complete_linear_order_bot`; * `a + b` and `a * b` are the restrictions of addition and multiplication of real numbers to `ℝ≥0`; these operations together with `0 = ⟨0, _⟩` and `1 = ⟨1, _⟩` turn `ℝ≥0` into a linear ordered archimedean commutative semifield; we have no typeclass for this in `mathlib` yet, so we define the following instances instead: - `linear_ordered_semiring ℝ≥0`; - `comm_semiring ℝ≥0`; - `canonically_ordered_comm_semiring ℝ≥0`; - `linear_ordered_comm_group_with_zero ℝ≥0`; - `archimedean ℝ≥0`. * `real.to_nnreal x` is defined as `⟨max x 0, _⟩`, i.e. `↑(real.to_nnreal x) = x` when `0 ≤ x` and `↑(real.to_nnreal x) = 0` otherwise. We also define an instance `can_lift ℝ ℝ≥0`. This instance can be used by the `lift` tactic to replace `x : ℝ` and `hx : 0 ≤ x` in the proof context with `x : ℝ≥0` while replacing all occurences of `x` with `↑x`. This tactic also works for a function `f : α → ℝ` with a hypothesis `hf : ∀ x, 0 ≤ f x`. ## Notations This file defines `ℝ≥0` as a localized notation for `nnreal`. -/ noncomputable theory open_locale classical big_operators /-- Nonnegative real numbers. -/ def nnreal := {r : ℝ // 0 ≤ r} localized "notation ` ℝ≥0 ` := nnreal" in nnreal namespace nnreal instance : has_coe ℝ≥0 ℝ := ⟨subtype.val⟩ /- Simp lemma to put back `n.val` into the normal form given by the coercion. -/ @[simp] lemma val_eq_coe (n : ℝ≥0) : n.val = n := rfl instance : can_lift ℝ ℝ≥0 := { coe := coe, cond := λ r, 0 ≤ r, prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ } protected lemma eq {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) → n = m := subtype.eq protected lemma eq_iff {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) ↔ n = m := iff.intro nnreal.eq (congr_arg coe) lemma ne_iff {x y : ℝ≥0} : (x : ℝ) ≠ (y : ℝ) ↔ x ≠ y := not_iff_not_of_iff $ nnreal.eq_iff /-- Reinterpret a real number `r` as a non-negative real number. Returns `0` if `r < 0`. -/ def _root_.real.to_nnreal (r : ℝ) : ℝ≥0 := ⟨max r 0, le_max_right _ _⟩ lemma _root_.real.coe_to_nnreal (r : ℝ) (hr : 0 ≤ r) : (real.to_nnreal r : ℝ) = r := max_eq_left hr lemma _root_.real.le_coe_to_nnreal (r : ℝ) : r ≤ real.to_nnreal r := le_max_left r 0 lemma coe_nonneg (r : ℝ≥0) : (0 : ℝ) ≤ r := r.2 @[norm_cast] theorem coe_mk (a : ℝ) (ha) : ((⟨a, ha⟩ : ℝ≥0) : ℝ) = a := rfl instance : has_zero ℝ≥0 := ⟨⟨0, le_refl 0⟩⟩ instance : has_one ℝ≥0 := ⟨⟨1, zero_le_one⟩⟩ instance : has_add ℝ≥0 := ⟨λa b, ⟨a + b, add_nonneg a.2 b.2⟩⟩ instance : has_sub ℝ≥0 := ⟨λa b, real.to_nnreal (a - b)⟩ instance : has_mul ℝ≥0 := ⟨λa b, ⟨a * b, mul_nonneg a.2 b.2⟩⟩ instance : has_inv ℝ≥0 := ⟨λa, ⟨(a.1)⁻¹, inv_nonneg.2 a.2⟩⟩ instance : has_div ℝ≥0 := ⟨λa b, ⟨a / b, div_nonneg a.2 b.2⟩⟩ instance : has_le ℝ≥0 := ⟨λ r s, (r:ℝ) ≤ s⟩ instance : has_bot ℝ≥0 := ⟨0⟩ instance : inhabited ℝ≥0 := ⟨0⟩ protected lemma coe_injective : function.injective (coe : ℝ≥0 → ℝ) := subtype.coe_injective @[simp, norm_cast] protected lemma coe_eq {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) = r₂ ↔ r₁ = r₂ := nnreal.coe_injective.eq_iff @[simp, norm_cast] protected lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl @[simp, norm_cast] protected lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl @[simp, norm_cast] protected lemma coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ := rfl @[simp, norm_cast] protected lemma coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ := rfl @[simp, norm_cast] protected lemma coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = r⁻¹ := rfl @[simp, norm_cast] protected lemma coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = r₁ / r₂ := rfl @[simp, norm_cast] protected lemma coe_bit0 (r : ℝ≥0) : ((bit0 r : ℝ≥0) : ℝ) = bit0 r := rfl @[simp, norm_cast] protected lemma coe_bit1 (r : ℝ≥0) : ((bit1 r : ℝ≥0) : ℝ) = bit1 r := rfl @[simp, norm_cast] protected lemma coe_sub {r₁ r₂ : ℝ≥0} (h : r₂ ≤ r₁) : ((r₁ - r₂ : ℝ≥0) : ℝ) = r₁ - r₂ := max_eq_left $ le_sub.2 $ by simp [show (r₂ : ℝ) ≤ r₁, from h] -- TODO: setup semifield! @[simp] protected lemma coe_eq_zero (r : ℝ≥0) : ↑r = (0 : ℝ) ↔ r = 0 := by norm_cast lemma coe_ne_zero {r : ℝ≥0} : (r : ℝ) ≠ 0 ↔ r ≠ 0 := by norm_cast instance : comm_semiring ℝ≥0 := { zero := 0, add := (+), one := 1, mul := (*), .. nnreal.coe_injective.comm_semiring _ rfl rfl (λ _ _, rfl) (λ _ _, rfl) } /-- Coercion `ℝ≥0 → ℝ` as a `ring_hom`. -/ def to_real_hom : ℝ≥0 →+* ℝ := ⟨coe, nnreal.coe_one, nnreal.coe_mul, nnreal.coe_zero, nnreal.coe_add⟩ @[simp] lemma coe_to_real_hom : ⇑to_real_hom = coe := rfl section actions /-- A `mul_action` over `ℝ` restricts to a `mul_action` over `ℝ≥0`. -/ instance {M : Type*} [mul_action ℝ M] : mul_action ℝ≥0 M := mul_action.comp_hom M to_real_hom.to_monoid_hom lemma smul_def {M : Type*} [mul_action ℝ M] (c : ℝ≥0) (x : M) : c • x = (c : ℝ) • x := rfl instance {M N : Type*} [mul_action ℝ M] [mul_action ℝ N] [has_scalar M N] [is_scalar_tower ℝ M N] : is_scalar_tower ℝ≥0 M N := { smul_assoc := λ r, (smul_assoc (r : ℝ) : _)} instance smul_comm_class_left {M N : Type*} [mul_action ℝ N] [has_scalar M N] [smul_comm_class ℝ M N] : smul_comm_class ℝ≥0 M N := { smul_comm := λ r, (smul_comm (r : ℝ) : _)} instance smul_comm_class_right {M N : Type*} [mul_action ℝ N] [has_scalar M N] [smul_comm_class M ℝ N] : smul_comm_class M ℝ≥0 N := { smul_comm := λ m r, (smul_comm m (r : ℝ) : _)} /-- A `distrib_mul_action` over `ℝ` restricts to a `distrib_mul_action` over `ℝ≥0`. -/ instance {M : Type*} [add_monoid M] [distrib_mul_action ℝ M] : distrib_mul_action ℝ≥0 M := distrib_mul_action.comp_hom M to_real_hom.to_monoid_hom /-- A `module` over `ℝ` restricts to a `module` over `ℝ≥0`. -/ instance {M : Type*} [add_comm_monoid M] [module ℝ M] : module ℝ≥0 M := module.comp_hom M to_real_hom /-- An `algebra` over `ℝ` restricts to an `algebra` over `ℝ≥0`. -/ instance {A : Type*} [semiring A] [algebra ℝ A] : algebra ℝ≥0 A := { smul := (•), commutes' := λ r x, by simp [algebra.commutes], smul_def' := λ r x, by simp [←algebra.smul_def (r : ℝ) x, smul_def], to_ring_hom := ((algebra_map ℝ A).comp (to_real_hom : ℝ≥0 →+* ℝ)) } -- verify that the above produces instances we might care about example : algebra ℝ≥0 ℝ := by apply_instance example : distrib_mul_action (units ℝ≥0) ℝ := by apply_instance end actions instance : comm_group_with_zero ℝ≥0 := { zero := 0, mul := (*), one := 1, inv := has_inv.inv, div := (/), .. nnreal.coe_injective.comm_group_with_zero _ rfl rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) } @[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) : ((s.indicator f a : ℝ≥0) : ℝ) = s.indicator (λ x, f x) a := (to_real_hom : ℝ≥0 →+ ℝ).map_indicator _ _ _ @[simp, norm_cast] lemma coe_pow (r : ℝ≥0) (n : ℕ) : ((r^n : ℝ≥0) : ℝ) = r^n := to_real_hom.map_pow r n @[norm_cast] lemma coe_list_sum (l : list ℝ≥0) : ((l.sum : ℝ≥0) : ℝ) = (l.map coe).sum := to_real_hom.map_list_sum l @[norm_cast] lemma coe_list_prod (l : list ℝ≥0) : ((l.prod : ℝ≥0) : ℝ) = (l.map coe).prod := to_real_hom.map_list_prod l @[norm_cast] lemma coe_multiset_sum (s : multiset ℝ≥0) : ((s.sum : ℝ≥0) : ℝ) = (s.map coe).sum := to_real_hom.map_multiset_sum s @[norm_cast] lemma coe_multiset_prod (s : multiset ℝ≥0) : ((s.prod : ℝ≥0) : ℝ) = (s.map coe).prod := to_real_hom.map_multiset_prod s @[norm_cast] lemma coe_sum {α} {s : finset α} {f : α → ℝ≥0} : ↑(∑ a in s, f a) = ∑ a in s, (f a : ℝ) := to_real_hom.map_sum _ _ lemma _root_.real.to_nnreal_sum_of_nonneg {α} {s : finset α} {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : real.to_nnreal (∑ a in s, f a) = ∑ a in s, real.to_nnreal (f a) := begin rw [←nnreal.coe_eq, nnreal.coe_sum, real.coe_to_nnreal _ (finset.sum_nonneg hf)], exact finset.sum_congr rfl (λ x hxs, by rw real.coe_to_nnreal _ (hf x hxs)), end @[norm_cast] lemma coe_prod {α} {s : finset α} {f : α → ℝ≥0} : ↑(∏ a in s, f a) = ∏ a in s, (f a : ℝ) := to_real_hom.map_prod _ _ lemma _root_.real.to_nnreal_prod_of_nonneg {α} {s : finset α} {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : real.to_nnreal (∏ a in s, f a) = ∏ a in s, real.to_nnreal (f a) := begin rw [←nnreal.coe_eq, nnreal.coe_prod, real.coe_to_nnreal _ (finset.prod_nonneg hf)], exact finset.prod_congr rfl (λ x hxs, by rw real.coe_to_nnreal _ (hf x hxs)), end @[norm_cast] lemma nsmul_coe (r : ℝ≥0) (n : ℕ) : ↑(n • r) = n • (r:ℝ) := to_real_hom.to_add_monoid_hom.map_nsmul _ _ @[simp, norm_cast] protected lemma coe_nat_cast (n : ℕ) : (↑(↑n : ℝ≥0) : ℝ) = n := to_real_hom.map_nat_cast n instance : linear_order ℝ≥0 := linear_order.lift (coe : ℝ≥0 → ℝ) nnreal.coe_injective @[simp, norm_cast] protected lemma coe_le_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) ≤ r₂ ↔ r₁ ≤ r₂ := iff.rfl @[simp, norm_cast] protected lemma coe_lt_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) < r₂ ↔ r₁ < r₂ := iff.rfl @[simp, norm_cast] protected lemma coe_pos {r : ℝ≥0} : (0 : ℝ) < r ↔ 0 < r := iff.rfl protected lemma coe_mono : monotone (coe : ℝ≥0 → ℝ) := λ _ _, nnreal.coe_le_coe.2 protected lemma _root_.real.to_nnreal_mono : monotone real.to_nnreal := λ x y h, max_le_max h (le_refl 0) @[simp] lemma _root_.real.to_nnreal_coe {r : ℝ≥0} : real.to_nnreal r = r := nnreal.eq $ max_eq_left r.2 @[simp] lemma mk_coe_nat (n : ℕ) : @eq ℝ≥0 (⟨(n : ℝ), n.cast_nonneg⟩ : ℝ≥0) n := nnreal.eq (nnreal.coe_nat_cast n).symm @[simp] lemma to_nnreal_coe_nat (n : ℕ) : real.to_nnreal n = n := nnreal.eq $ by simp [real.coe_to_nnreal] /-- `real.to_nnreal` and `coe : ℝ≥0 → ℝ` form a Galois insertion. -/ protected def gi : galois_insertion real.to_nnreal coe := galois_insertion.monotone_intro nnreal.coe_mono real.to_nnreal_mono real.le_coe_to_nnreal (λ _, real.to_nnreal_coe) instance : order_bot ℝ≥0 := { bot := ⊥, bot_le := assume ⟨a, h⟩, h, .. nnreal.linear_order } instance : canonically_linear_ordered_add_monoid ℝ≥0 := { add_le_add_left := assume a b h c, nnreal.coe_le_coe.mp $ (add_le_add_left (nnreal.coe_le_coe.mpr h) c), lt_of_add_lt_add_left := assume a b c bc, nnreal.coe_lt_coe.mp $ lt_of_add_lt_add_left (nnreal.coe_lt_coe.mpr bc), le_iff_exists_add := assume ⟨a, ha⟩ ⟨b, hb⟩, iff.intro (assume h : a ≤ b, ⟨⟨b - a, le_sub_iff_add_le.2 $ (zero_add _).le.trans h⟩, nnreal.eq $ show b = a + (b - a), from (add_sub_cancel'_right _ _).symm⟩) (assume ⟨⟨c, hc⟩, eq⟩, eq.symm ▸ show a ≤ a + c, from (le_add_iff_nonneg_right a).2 hc), ..nnreal.comm_semiring, ..nnreal.order_bot, ..nnreal.linear_order } instance : linear_ordered_add_comm_monoid ℝ≥0 := { .. nnreal.comm_semiring, .. nnreal.canonically_linear_ordered_add_monoid } instance : distrib_lattice ℝ≥0 := by apply_instance instance : semilattice_inf_bot ℝ≥0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : semilattice_sup_bot ℝ≥0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : linear_ordered_semiring ℝ≥0 := { add_left_cancel := assume a b c h, nnreal.eq $ @add_left_cancel ℝ _ a b c (nnreal.eq_iff.2 h), le_of_add_le_add_left := assume a b c, @le_of_add_le_add_left ℝ _ _ _ a b c, mul_lt_mul_of_pos_left := assume a b c, @mul_lt_mul_of_pos_left ℝ _ a b c, mul_lt_mul_of_pos_right := assume a b c, @mul_lt_mul_of_pos_right ℝ _ a b c, zero_le_one := @zero_le_one ℝ _, exists_pair_ne := ⟨0, 1, ne_of_lt (@zero_lt_one ℝ _ _)⟩, .. nnreal.canonically_linear_ordered_add_monoid, .. nnreal.comm_semiring } instance : ordered_comm_semiring ℝ≥0 := { .. nnreal.linear_ordered_semiring, .. nnreal.comm_semiring } instance : linear_ordered_comm_group_with_zero ℝ≥0 := { mul_le_mul_left := assume a b h c, mul_le_mul (le_refl c) h (zero_le a) (zero_le c), zero_le_one := zero_le 1, .. nnreal.linear_ordered_semiring, .. nnreal.comm_group_with_zero } instance : canonically_ordered_comm_semiring ℝ≥0 := { .. nnreal.canonically_linear_ordered_add_monoid, .. nnreal.comm_semiring, .. (show no_zero_divisors ℝ≥0, by apply_instance), .. nnreal.comm_group_with_zero } instance : densely_ordered ℝ≥0 := ⟨assume a b (h : (a : ℝ) < b), let ⟨c, hac, hcb⟩ := exists_between h in ⟨⟨c, le_trans a.property $ le_of_lt $ hac⟩, hac, hcb⟩⟩ instance : no_top_order ℝ≥0 := ⟨assume a, let ⟨b, hb⟩ := no_top (a:ℝ) in ⟨⟨b, le_trans a.property $ le_of_lt $ hb⟩, hb⟩⟩ lemma bdd_above_coe {s : set ℝ≥0} : bdd_above ((coe : ℝ≥0 → ℝ) '' s) ↔ bdd_above s := iff.intro (assume ⟨b, hb⟩, ⟨real.to_nnreal b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from le_max_of_le_left $ hb $ set.mem_image_of_mem _ hys⟩) (assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq ▸ hb hx⟩) lemma bdd_below_coe (s : set ℝ≥0) : bdd_below ((coe : ℝ≥0 → ℝ) '' s) := ⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩ instance : conditionally_complete_linear_order_bot ℝ≥0 := { cSup_empty := (function.funext_iff.1 (@subset_Sup_def ℝ (set.Ici (0 : ℝ)) _ ⟨(0 : ℝ≥0)⟩) ∅).trans $ nnreal.eq $ by simp, .. nnreal.order_bot, .. @ord_connected_subset_conditionally_complete_linear_order ℝ (set.Ici (0 : ℝ)) _ ⟨(0 : ℝ≥0)⟩ _ } lemma coe_Sup (s : set ℝ≥0) : (↑(Sup s) : ℝ) = Sup ((coe : ℝ≥0 → ℝ) '' s) := eq.symm $ @subset_Sup_of_within ℝ (set.Ici 0) _ ⟨(0 : ℝ≥0)⟩ s $ real.Sup_nonneg _ $ λ y ⟨x, _, hy⟩, hy ▸ x.2 lemma coe_Inf (s : set ℝ≥0) : (↑(Inf s) : ℝ) = Inf ((coe : ℝ≥0 → ℝ) '' s) := eq.symm $ @subset_Inf_of_within ℝ (set.Ici 0) _ ⟨(0 : ℝ≥0)⟩ s $ real.Inf_nonneg _ $ λ y ⟨x, _, hy⟩, hy ▸ x.2 instance : archimedean ℝ≥0 := ⟨ assume x y pos_y, let ⟨n, hr⟩ := archimedean.arch (x:ℝ) (pos_y : (0 : ℝ) < y) in ⟨n, show (x:ℝ) ≤ (n • y : ℝ≥0), by simp [*, -nsmul_eq_mul, nsmul_coe]⟩ ⟩ lemma le_of_forall_pos_le_add {a b : ℝ≥0} (h : ∀ε, 0 < ε → a ≤ b + ε) : a ≤ b := le_of_forall_le_of_dense $ assume x hxb, begin rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨ε, rfl⟩, exact h _ ((lt_add_iff_pos_right b).1 hxb) end -- TODO: generalize to some ordered add_monoids, based on #6145 lemma le_of_add_le_left {a b c : ℝ≥0} (h : a + b ≤ c) : a ≤ c := by { refine le_trans _ h, simp } lemma le_of_add_le_right {a b c : ℝ≥0} (h : a + b ≤ c) : b ≤ c := by { refine le_trans _ h, simp } lemma lt_iff_exists_rat_btwn (a b : ℝ≥0) : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < real.to_nnreal q ∧ real.to_nnreal q < b) := iff.intro (assume (h : (↑a:ℝ) < (↑b:ℝ)), let ⟨q, haq, hqb⟩ := exists_rat_btwn h in have 0 ≤ (q : ℝ), from le_trans a.2 $ le_of_lt haq, ⟨q, rat.cast_nonneg.1 this, by simp [real.coe_to_nnreal _ this, nnreal.coe_lt_coe.symm, haq, hqb]⟩) (assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb) lemma bot_eq_zero : (⊥ : ℝ≥0) = 0 := rfl lemma mul_sup (a b c : ℝ≥0) : a * (b ⊔ c) = (a * b) ⊔ (a * c) := begin cases le_total b c with h h, { simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] }, { simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] }, end lemma mul_finset_sup {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) : r * s.sup f = s.sup (λa, r * f a) := begin refine s.induction_on _ _, { simp [bot_eq_zero] }, { assume a s has ih, simp [has, ih, mul_sup], } end @[simp, norm_cast] lemma coe_max (x y : ℝ≥0) : ((max x y : ℝ≥0) : ℝ) = max (x : ℝ) (y : ℝ) := by { delta max, split_ifs; refl } @[simp, norm_cast] lemma coe_min (x y : ℝ≥0) : ((min x y : ℝ≥0) : ℝ) = min (x : ℝ) (y : ℝ) := by { delta min, split_ifs; refl } @[simp] lemma zero_le_coe {q : ℝ≥0} : 0 ≤ (q : ℝ) := q.2 end nnreal namespace real section to_nnreal @[simp] lemma to_nnreal_zero : real.to_nnreal 0 = 0 := by simp [real.to_nnreal]; refl @[simp] lemma to_nnreal_one : real.to_nnreal 1 = 1 := by simp [real.to_nnreal, max_eq_left (zero_le_one : (0 :ℝ) ≤ 1)]; refl @[simp] lemma to_nnreal_pos {r : ℝ} : 0 < real.to_nnreal r ↔ 0 < r := by simp [real.to_nnreal, nnreal.coe_lt_coe.symm, lt_irrefl] @[simp] lemma to_nnreal_eq_zero {r : ℝ} : real.to_nnreal r = 0 ↔ r ≤ 0 := by simpa [-to_nnreal_pos] using (not_iff_not.2 (@to_nnreal_pos r)) lemma to_nnreal_of_nonpos {r : ℝ} : r ≤ 0 → real.to_nnreal r = 0 := to_nnreal_eq_zero.2 @[simp] lemma coe_to_nnreal' (r : ℝ) : (real.to_nnreal r : ℝ) = max r 0 := rfl @[simp] lemma to_nnreal_le_to_nnreal_iff {r p : ℝ} (hp : 0 ≤ p) : real.to_nnreal r ≤ real.to_nnreal p ↔ r ≤ p := by simp [nnreal.coe_le_coe.symm, real.to_nnreal, hp] @[simp] lemma to_nnreal_lt_to_nnreal_iff' {r p : ℝ} : real.to_nnreal r < real.to_nnreal p ↔ r < p ∧ 0 < p := by simp [nnreal.coe_lt_coe.symm, real.to_nnreal, lt_irrefl] lemma to_nnreal_lt_to_nnreal_iff {r p : ℝ} (h : 0 < p) : real.to_nnreal r < real.to_nnreal p ↔ r < p := to_nnreal_lt_to_nnreal_iff'.trans (and_iff_left h) lemma to_nnreal_lt_to_nnreal_iff_of_nonneg {r p : ℝ} (hr : 0 ≤ r) : real.to_nnreal r < real.to_nnreal p ↔ r < p := to_nnreal_lt_to_nnreal_iff'.trans ⟨and.left, λ h, ⟨h, lt_of_le_of_lt hr h⟩⟩ @[simp] lemma to_nnreal_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : real.to_nnreal (r + p) = real.to_nnreal r + real.to_nnreal p := nnreal.eq $ by simp [real.to_nnreal, hr, hp, add_nonneg] lemma to_nnreal_add_to_nnreal {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : real.to_nnreal r + real.to_nnreal p = real.to_nnreal (r + p) := (real.to_nnreal_add hr hp).symm lemma to_nnreal_le_to_nnreal {r p : ℝ} (h : r ≤ p) : real.to_nnreal r ≤ real.to_nnreal p := real.to_nnreal_mono h lemma to_nnreal_add_le {r p : ℝ} : real.to_nnreal (r + p) ≤ real.to_nnreal r + real.to_nnreal p := nnreal.coe_le_coe.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe lemma to_nnreal_le_iff_le_coe {r : ℝ} {p : ℝ≥0} : real.to_nnreal r ≤ p ↔ r ≤ ↑p := nnreal.gi.gc r p lemma le_to_nnreal_iff_coe_le {r : ℝ≥0} {p : ℝ} (hp : 0 ≤ p) : r ≤ real.to_nnreal p ↔ ↑r ≤ p := by rw [← nnreal.coe_le_coe, real.coe_to_nnreal p hp] lemma le_to_nnreal_iff_coe_le' {r : ℝ≥0} {p : ℝ} (hr : 0 < r) : r ≤ real.to_nnreal p ↔ ↑r ≤ p := (le_or_lt 0 p).elim le_to_nnreal_iff_coe_le $ λ hp, by simp only [(hp.trans_le r.coe_nonneg).not_le, to_nnreal_eq_zero.2 hp.le, hr.not_le] lemma to_nnreal_lt_iff_lt_coe {r : ℝ} {p : ℝ≥0} (ha : 0 ≤ r) : real.to_nnreal r < p ↔ r < ↑p := by rw [← nnreal.coe_lt_coe, real.coe_to_nnreal r ha] lemma lt_to_nnreal_iff_coe_lt {r : ℝ≥0} {p : ℝ} : r < real.to_nnreal p ↔ ↑r < p := begin cases le_total 0 p, { rw [← nnreal.coe_lt_coe, real.coe_to_nnreal p h] }, { rw [to_nnreal_eq_zero.2 h], split, { intro, have := not_lt_of_le (zero_le r), contradiction }, { intro rp, have : ¬(p ≤ 0) := not_le_of_lt (lt_of_le_of_lt (nnreal.coe_nonneg _) rp), contradiction } } end @[simp] lemma to_nnreal_bit0 {r : ℝ} (hr : 0 ≤ r) : real.to_nnreal (bit0 r) = bit0 (real.to_nnreal r) := real.to_nnreal_add hr hr @[simp] lemma to_nnreal_bit1 {r : ℝ} (hr : 0 ≤ r) : real.to_nnreal (bit1 r) = bit1 (real.to_nnreal r) := (real.to_nnreal_add (by simp [hr]) zero_le_one).trans (by simp [to_nnreal_one, bit1, hr]) end to_nnreal end real open real namespace nnreal section mul lemma mul_eq_mul_left {a b c : ℝ≥0} (h : a ≠ 0) : (a * b = a * c ↔ b = c) := begin rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split, { exact mul_left_cancel' (mt (@nnreal.eq_iff a 0).1 h) }, { assume h, rw [h] } end lemma _root_.real.to_nnreal_mul {p q : ℝ} (hp : 0 ≤ p) : real.to_nnreal (p * q) = real.to_nnreal p * real.to_nnreal q := begin cases le_total 0 q with hq hq, { apply nnreal.eq, simp [real.to_nnreal, hp, hq, max_eq_left, mul_nonneg] }, { have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq, rw [to_nnreal_eq_zero.2 hq, to_nnreal_eq_zero.2 hpq, mul_zero] } end end mul section pow lemma pow_mono_decr_exp {a : ℝ≥0} (m n : ℕ) (mn : m ≤ n) (a1 : a ≤ 1) : a ^ n ≤ a ^ m := begin rcases le_iff_exists_add.mp mn with ⟨k, rfl⟩, rw [← mul_one (a ^ m), pow_add], refine mul_le_mul rfl.le (pow_le_one _ (zero_le a) a1) _ _; exact pow_nonneg (zero_le _) _, end end pow section sub lemma sub_def {r p : ℝ≥0} : r - p = real.to_nnreal (r - p) := rfl lemma sub_eq_zero {r p : ℝ≥0} (h : r ≤ p) : r - p = 0 := nnreal.eq $ max_eq_right $ sub_le_iff_le_add.2 $ by simpa [nnreal.coe_le_coe] using h @[simp] lemma sub_self {r : ℝ≥0} : r - r = 0 := sub_eq_zero $ le_refl r @[simp] lemma sub_zero {r : ℝ≥0} : r - 0 = r := by rw [sub_def, nnreal.coe_zero, sub_zero, real.to_nnreal_coe] lemma sub_pos {r p : ℝ≥0} : 0 < r - p ↔ p < r := to_nnreal_pos.trans $ sub_pos.trans $ nnreal.coe_lt_coe protected lemma sub_lt_self {r p : ℝ≥0} : 0 < r → 0 < p → r - p < r := assume hr hp, begin cases le_total r p, { rwa [sub_eq_zero h] }, { rw [← nnreal.coe_lt_coe, nnreal.coe_sub h], exact sub_lt_self _ hp } end @[simp] lemma sub_le_iff_le_add {r p q : ℝ≥0} : r - p ≤ q ↔ r ≤ q + p := match le_total p r with | or.inl h := by rw [← nnreal.coe_le_coe, ← nnreal.coe_le_coe, nnreal.coe_sub h, nnreal.coe_add, sub_le_iff_le_add] | or.inr h := have r ≤ p + q, from le_add_right h, by simpa [nnreal.coe_le_coe, nnreal.coe_le_coe, sub_eq_zero h, add_comm] end @[simp] lemma sub_le_self {r p : ℝ≥0} : r - p ≤ r := sub_le_iff_le_add.2 $ le_add_right $ le_refl r lemma add_sub_cancel {r p : ℝ≥0} : (p + r) - r = p := nnreal.eq $ by rw [nnreal.coe_sub, nnreal.coe_add, add_sub_cancel]; exact le_add_self lemma add_sub_cancel' {r p : ℝ≥0} : (r + p) - r = p := by rw [add_comm, add_sub_cancel] lemma sub_add_eq_max {r p : ℝ≥0} : (r - p) + p = max r p := nnreal.eq $ by rw [sub_def, nnreal.coe_add, coe_max, real.to_nnreal, coe_mk, ← max_add_add_right, zero_add, sub_add_cancel] lemma add_sub_eq_max {r p : ℝ≥0} : p + (r - p) = max p r := by rw [add_comm, sub_add_eq_max, max_comm] @[simp] lemma sub_add_cancel_of_le {a b : ℝ≥0} (h : b ≤ a) : (a - b) + b = a := by rw [sub_add_eq_max, max_eq_left h] lemma sub_sub_cancel_of_le {r p : ℝ≥0} (h : r ≤ p) : p - (p - r) = r := by rw [nnreal.sub_def, nnreal.sub_def, real.coe_to_nnreal _ $ sub_nonneg.2 h, sub_sub_cancel, real.to_nnreal_coe] lemma lt_sub_iff_add_lt {p q r : ℝ≥0} : p < q - r ↔ p + r < q := begin split, { assume H, have : (((q - r) : ℝ≥0) : ℝ) = (q : ℝ) - (r : ℝ) := nnreal.coe_sub (le_of_lt (sub_pos.1 (lt_of_le_of_lt (zero_le _) H))), rwa [← nnreal.coe_lt_coe, this, lt_sub_iff_add_lt, ← nnreal.coe_add] at H }, { assume H, have : r ≤ q := le_trans (le_add_self) (le_of_lt H), rwa [← nnreal.coe_lt_coe, nnreal.coe_sub this, lt_sub_iff_add_lt, ← nnreal.coe_add] } end lemma sub_lt_iff_lt_add {a b c : ℝ≥0} (h : b ≤ a) : a - b < c ↔ a < b + c := by simp only [←nnreal.coe_lt_coe, nnreal.coe_sub h, nnreal.coe_add, sub_lt_iff_lt_add'] lemma sub_eq_iff_eq_add {a b c : ℝ≥0} (h : b ≤ a) : a - b = c ↔ a = c + b := by rw [←nnreal.eq_iff, nnreal.coe_sub h, ←nnreal.eq_iff, nnreal.coe_add, sub_eq_iff_eq_add] end sub section inv lemma sum_div {ι} (s : finset ι) (f : ι → ℝ≥0) (b : ℝ≥0) : (∑ i in s, f i) / b = ∑ i in s, (f i / b) := by simp only [div_eq_mul_inv, finset.sum_mul] @[simp] lemma inv_pos {r : ℝ≥0} : 0 < r⁻¹ ↔ 0 < r := by simp [pos_iff_ne_zero] lemma div_pos {r p : ℝ≥0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p := by simpa only [div_eq_mul_inv] using mul_pos hr (inv_pos.2 hp) protected lemma mul_inv {r p : ℝ≥0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnreal.eq $ mul_inv_rev' _ _ lemma div_self_le (r : ℝ≥0) : r / r ≤ 1 := if h : r = 0 then by simp [h] else by rw [div_self h] @[simp] lemma inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p := by rw [← mul_le_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h] lemma inv_le_of_le_mul {r p : ℝ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p := by by_cases r = 0; simp [*, inv_le] @[simp] lemma le_inv_iff_mul_le {r p : ℝ≥0} (h : p ≠ 0) : (r ≤ p⁻¹ ↔ r * p ≤ 1) := by rw [← mul_le_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] @[simp] lemma lt_inv_iff_mul_lt {r p : ℝ≥0} (h : p ≠ 0) : (r < p⁻¹ ↔ r * p < 1) := by rw [← mul_lt_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] lemma mul_le_iff_le_inv {a b r : ℝ≥0} (hr : r ≠ 0) : r * a ≤ b ↔ a ≤ r⁻¹ * b := have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm, by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul] lemma le_div_iff_mul_le {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b := by rw [div_eq_inv_mul, ← mul_le_iff_le_inv hr, mul_comm] lemma div_le_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a / r ≤ b ↔ a ≤ b * r := @div_le_iff ℝ _ a r b $ pos_iff_ne_zero.2 hr lemma div_le_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a / r ≤ b ↔ a ≤ r * b := @div_le_iff' ℝ _ a r b $ pos_iff_ne_zero.2 hr lemma div_le_of_le_mul {a b c : ℝ≥0} (h : a ≤ b * c) : a / c ≤ b := if h0 : c = 0 then by simp [h0] else (div_le_iff h0).2 h lemma div_le_of_le_mul' {a b c : ℝ≥0} (h : a ≤ b * c) : a / b ≤ c := div_le_of_le_mul $ mul_comm b c ▸ h lemma le_div_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b := @le_div_iff ℝ _ a b r $ pos_iff_ne_zero.2 hr lemma le_div_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ r * a ≤ b := @le_div_iff' ℝ _ a b r $ pos_iff_ne_zero.2 hr lemma div_lt_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a / r < b ↔ a < b * r := lt_iff_lt_of_le_iff_le (le_div_iff hr) lemma div_lt_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a / r < b ↔ a < r * b := lt_iff_lt_of_le_iff_le (le_div_iff' hr) lemma lt_div_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a < b / r ↔ a * r < b := lt_iff_lt_of_le_iff_le (div_le_iff hr) lemma lt_div_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a < b / r ↔ r * a < b := lt_iff_lt_of_le_iff_le (div_le_iff' hr) lemma mul_lt_of_lt_div {a b r : ℝ≥0} (h : a < b / r) : a * r < b := begin refine (lt_div_iff $ λ hr, false.elim _).1 h, subst r, simpa using h end lemma div_le_div_left_of_le {a b c : ℝ≥0} (b0 : 0 < b) (c0 : 0 < c) (cb : c ≤ b) : a / b ≤ a / c := begin by_cases a0 : a = 0, { rw [a0, zero_div, zero_div] }, { cases a with a ha, replace a0 : 0 < a := lt_of_le_of_ne ha (ne_of_lt (zero_lt_iff.mpr a0)), exact (div_le_div_left a0 b0 c0).mpr cb } end lemma div_le_div_left {a b c : ℝ≥0} (a0 : 0 < a) (b0 : 0 < b) (c0 : 0 < c) : a / b ≤ a / c ↔ c ≤ b := by rw [nnreal.div_le_iff b0.ne.symm, div_mul_eq_mul_div, nnreal.le_div_iff_mul_le c0.ne.symm, mul_le_mul_left a0] lemma le_of_forall_lt_one_mul_le {x y : ℝ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y := le_of_forall_ge_of_dense $ assume a ha, have hx : x ≠ 0 := pos_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha), have hx' : x⁻¹ ≠ 0, by rwa [(≠), inv_eq_zero], have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv'], have (a * x⁻¹) * x ≤ y, from h _ this, by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this lemma div_add_div_same (a b c : ℝ≥0) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma half_pos {a : ℝ≥0} (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma add_halves (a : ℝ≥0) : a / 2 + a / 2 = a := nnreal.eq (add_halves a) lemma half_lt_self {a : ℝ≥0} (h : a ≠ 0) : a / 2 < a := by rw [← nnreal.coe_lt_coe, nnreal.coe_div]; exact half_lt_self (bot_lt_iff_ne_bot.2 h) lemma two_inv_lt_one : (2⁻¹:ℝ≥0) < 1 := by simpa using half_lt_self zero_ne_one.symm lemma div_lt_one_of_lt {a b : ℝ≥0} (h : a < b) : a / b < 1 := begin rwa [div_lt_iff, one_mul], exact ne_of_gt (lt_of_le_of_lt (zero_le _) h) end @[field_simps] lemma div_add_div (a : ℝ≥0) {b : ℝ≥0} (c : ℝ≥0) {d : ℝ≥0} (hb : b ≠ 0) (hd : d ≠ 0) : a / b + c / d = (a * d + b * c) / (b * d) := begin rw ← nnreal.eq_iff, simp only [nnreal.coe_add, nnreal.coe_div, nnreal.coe_mul], exact div_add_div _ _ (coe_ne_zero.2 hb) (coe_ne_zero.2 hd) end @[field_simps] lemma add_div' (a b c : ℝ≥0) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : ℝ≥0) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] lemma _root_.real.to_nnreal_inv {x : ℝ} : real.to_nnreal x⁻¹ = (real.to_nnreal x)⁻¹ := begin by_cases hx : 0 ≤ x, { nth_rewrite 0 ← real.coe_to_nnreal x hx, rw [←nnreal.coe_inv, real.to_nnreal_coe], }, { have hx' := le_of_not_ge hx, rw [to_nnreal_eq_zero.mpr hx', inv_zero, to_nnreal_eq_zero.mpr (inv_nonpos.mpr hx')], }, end lemma _root_.real.to_nnreal_div {x y : ℝ} (hx : 0 ≤ x) : real.to_nnreal (x / y) = real.to_nnreal x / real.to_nnreal y := by rw [div_eq_mul_inv, div_eq_mul_inv, ← real.to_nnreal_inv, ← real.to_nnreal_mul hx] lemma _root_.real.to_nnreal_div' {x y : ℝ} (hy : 0 ≤ y) : real.to_nnreal (x / y) = real.to_nnreal x / real.to_nnreal y := by rw [div_eq_inv_mul, div_eq_inv_mul, real.to_nnreal_mul (inv_nonneg.2 hy), real.to_nnreal_inv] end inv @[simp] lemma abs_eq (x : ℝ≥0) : abs (x : ℝ) = x := abs_of_nonneg x.property end nnreal /-- The absolute value on `ℝ` as a map to `ℝ≥0`. -/ @[pp_nodot] def real.nnabs (x : ℝ) : ℝ≥0 := ⟨abs x, abs_nonneg x⟩ @[norm_cast, simp] lemma nnreal.coe_nnabs (x : ℝ) : (real.nnabs x : ℝ) = abs x := by simp [real.nnabs] @[simp] lemma real.nnabs_of_nonneg {x : ℝ} (h : 0 ≤ x) : real.nnabs x = real.to_nnreal x := by { ext, simp [real.coe_to_nnreal x h, abs_of_nonneg h] } lemma real.coe_to_nnreal_le (x : ℝ) : (real.to_nnreal x : ℝ) ≤ abs x := max_le (le_abs_self _) (abs_nonneg _) lemma cast_nat_abs_eq_nnabs_cast (n : ℤ) : (n.nat_abs : ℝ≥0) = real.nnabs n := by { ext, rw [nnreal.coe_nat_cast, int.cast_nat_abs, nnreal.coe_nnabs] }
3cbd9146e882b5dabc2ca9fd6460130d5708970f
4727251e0cd73359b15b664c3170e5d754078599
/src/combinatorics/set_family/shadow.lean
d08ac501c6671dac1fe3c68e8522d5ccdbc7925b
[ "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
10,988
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Alena Gusakov, Yaël Dillies -/ import data.finset.slice import logic.function.iterate /-! # Shadows This file defines shadows of a set family. The shadow of a set family is the set family of sets we get by removing any element from any set of the original family. If one pictures `finset α` as a big hypercube (each dimension being membership of a given element), then taking the shadow corresponds to projecting each finset down once in all available directions. ## Main definitions * `finset.shadow`: The shadow of a set family. Everything we can get by removing a new element from some set. * `finset.up_shadow`: The upper shadow of a set family. Everything we can get by adding an element to some set. ## Notation We define notation in locale `finset_family`: * `∂ 𝒜`: Shadow of `𝒜`. * `∂⁺ 𝒜`: Upper shadow of `𝒜`. We also maintain the convention that `a, b : α` are elements of the ground type, `s, t : finset α` are finsets, and `𝒜, ℬ : finset (finset α)` are finset families. ## References * https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf * http://discretemath.imp.fu-berlin.de/DMII-2015-16/kruskal.pdf ## Tags shadow, set family -/ open finset nat variables {α : Type*} namespace finset section shadow variables [decidable_eq α] {𝒜 : finset (finset α)} {s t : finset α} {a : α} {k r : ℕ} /-- The shadow of a set family `𝒜` is all sets we can get by removing one element from any set in `𝒜`, and the (`k` times) iterated shadow (`shadow^[k]`) is all sets we can get by removing `k` elements from any set in `𝒜`. -/ def shadow (𝒜 : finset (finset α)) : finset (finset α) := 𝒜.sup (λ s, s.image (erase s)) localized "notation `∂ `:90 := finset.shadow" in finset_family /-- The shadow of the empty set is empty. -/ @[simp] lemma shadow_empty : ∂ (∅ : finset (finset α)) = ∅ := rfl @[simp] lemma shadow_singleton_empty : ∂ ({∅} : finset (finset α)) = ∅ := rfl --TODO: Prove `∂ {{a}} = {∅}` quickly using `covers` and `grade_order` /-- The shadow is monotone. -/ @[mono] lemma shadow_monotone : monotone (shadow : finset (finset α) → finset (finset α)) := λ 𝒜 ℬ, sup_mono /-- `s` is in the shadow of `𝒜` iff there is an `t ∈ 𝒜` from which we can remove one element to get `s`. -/ lemma mem_shadow_iff : s ∈ ∂ 𝒜 ↔ ∃ t ∈ 𝒜, ∃ a ∈ t, erase t a = s := by simp only [shadow, mem_sup, mem_image] lemma erase_mem_shadow (hs : s ∈ 𝒜) (ha : a ∈ s) : erase s a ∈ ∂ 𝒜 := mem_shadow_iff.2 ⟨s, hs, a, ha, rfl⟩ /-- `t` is in the shadow of `𝒜` iff we can add an element to it so that the resulting finset is in `𝒜`. -/ lemma mem_shadow_iff_insert_mem : s ∈ ∂ 𝒜 ↔ ∃ a ∉ s, insert a s ∈ 𝒜 := begin refine mem_shadow_iff.trans ⟨_, _⟩, { rintro ⟨s, hs, a, ha, rfl⟩, refine ⟨a, not_mem_erase a s, _⟩, rwa insert_erase ha }, { rintro ⟨a, ha, hs⟩, exact ⟨insert a s, hs, a, mem_insert_self _ _, erase_insert ha⟩ } end /-- The shadow of a family of `r`-sets is a family of `r - 1`-sets. -/ protected lemma _root_.set.sized.shadow (h𝒜 : (𝒜 : set (finset α)).sized r) : (∂ 𝒜 : set (finset α)).sized (r - 1) := begin intros A h, obtain ⟨A, hA, i, hi, rfl⟩ := mem_shadow_iff.1 h, rw [card_erase_of_mem hi, h𝒜 hA], end lemma sized_shadow_iff (h : ∅ ∉ 𝒜) : (∂ 𝒜 : set (finset α)).sized r ↔ (𝒜 : set (finset α)).sized (r + 1) := begin refine ⟨λ h𝒜 s hs, _, set.sized.shadow⟩, obtain ⟨a, ha⟩ := nonempty_iff_ne_empty.2 (ne_of_mem_of_not_mem hs h), rw [←h𝒜 (erase_mem_shadow hs ha), card_erase_add_one ha], end /-- `s ∈ ∂ 𝒜` iff `s` is exactly one element less than something from `𝒜` -/ lemma mem_shadow_iff_exists_mem_card_add_one : s ∈ ∂ 𝒜 ↔ ∃ t ∈ 𝒜, s ⊆ t ∧ t.card = s.card + 1 := begin refine mem_shadow_iff_insert_mem.trans ⟨_, _⟩, { rintro ⟨a, ha, hs⟩, exact ⟨insert a s, hs, subset_insert _ _, card_insert_of_not_mem ha⟩ }, { rintro ⟨t, ht, hst, h⟩, obtain ⟨a, ha⟩ : ∃ a, t \ s = {a} := card_eq_one.1 (by rw [card_sdiff hst, h, add_tsub_cancel_left]), exact ⟨a, λ hat, not_mem_sdiff_of_mem_right hat ((ha.ge : _ ⊆ _) $ mem_singleton_self a), by rwa [insert_eq a s, ←ha, sdiff_union_of_subset hst]⟩ } end /-- Being in the shadow of `𝒜` means we have a superset in `𝒜`. -/ lemma exists_subset_of_mem_shadow (hs : s ∈ ∂ 𝒜) : ∃ t ∈ 𝒜, s ⊆ t := let ⟨t, ht, hst⟩ := mem_shadow_iff_exists_mem_card_add_one.1 hs in ⟨t, ht, hst.1⟩ /-- `t ∈ ∂^k 𝒜` iff `t` is exactly `k` elements less than something in `𝒜`. -/ lemma mem_shadow_iff_exists_mem_card_add : s ∈ (∂^[k]) 𝒜 ↔ ∃ t ∈ 𝒜, s ⊆ t ∧ t.card = s.card + k := begin induction k with k ih generalizing 𝒜 s, { refine ⟨λ hs, ⟨s, hs, subset.refl _, rfl⟩, _⟩, rintro ⟨t, ht, hst, hcard⟩, rwa eq_of_subset_of_card_le hst hcard.le }, simp only [exists_prop, function.comp_app, function.iterate_succ], refine ih.trans _, clear ih, split, { rintro ⟨t, ht, hst, hcardst⟩, obtain ⟨u, hu, htu, hcardtu⟩ := mem_shadow_iff_exists_mem_card_add_one.1 ht, refine ⟨u, hu, hst.trans htu, _⟩, rw [hcardtu, hcardst], refl }, { rintro ⟨t, ht, hst, hcard⟩, obtain ⟨u, hsu, hut, hu⟩ := finset.exists_intermediate_set k (by { rw [add_comm, hcard], exact le_succ _ }) hst, rw add_comm at hu, refine ⟨u, mem_shadow_iff_exists_mem_card_add_one.2 ⟨t, ht, hut, _⟩, hsu, hu⟩, rw [hcard, hu], refl } end end shadow open_locale finset_family section up_shadow variables [decidable_eq α] [fintype α] {𝒜 : finset (finset α)} {s t : finset α} {a : α} {k r : ℕ} /-- The upper shadow of a set family `𝒜` is all sets we can get by adding one element to any set in `𝒜`, and the (`k` times) iterated upper shadow (`up_shadow^[k]`) is all sets we can get by adding `k` elements from any set in `𝒜`. -/ def up_shadow (𝒜 : finset (finset α)) : finset (finset α) := 𝒜.sup $ λ s, sᶜ.image $ λ a, insert a s localized "notation `∂⁺ `:90 := finset.up_shadow" in finset_family /-- The upper shadow of the empty set is empty. -/ @[simp] lemma up_shadow_empty : ∂⁺ (∅ : finset (finset α)) = ∅ := rfl /-- The upper shadow is monotone. -/ @[mono] lemma up_shadow_monotone : monotone (up_shadow : finset (finset α) → finset (finset α)) := λ 𝒜 ℬ, sup_mono /-- `s` is in the upper shadow of `𝒜` iff there is an `t ∈ 𝒜` from which we can remove one element to get `s`. -/ lemma mem_up_shadow_iff : s ∈ ∂⁺ 𝒜 ↔ ∃ t ∈ 𝒜, ∃ a ∉ t, insert a t = s := by simp_rw [up_shadow, mem_sup, mem_image, exists_prop, mem_compl] lemma insert_mem_up_shadow (hs : s ∈ 𝒜) (ha : a ∉ s) : insert a s ∈ ∂⁺ 𝒜 := mem_up_shadow_iff.2 ⟨s, hs, a, ha, rfl⟩ /-- The upper shadow of a family of `r`-sets is a family of `r + 1`-sets. -/ protected lemma _root_.set.sized.up_shadow (h𝒜 : (𝒜 : set (finset α)).sized r) : (∂⁺ 𝒜 : set (finset α)).sized (r + 1) := begin intros A h, obtain ⟨A, hA, i, hi, rfl⟩ := mem_up_shadow_iff.1 h, rw [card_insert_of_not_mem hi, h𝒜 hA], end /-- `t` is in the upper shadow of `𝒜` iff we can remove an element from it so that the resulting finset is in `𝒜`. -/ lemma mem_up_shadow_iff_erase_mem : s ∈ ∂⁺ 𝒜 ↔ ∃ a ∈ s, s.erase a ∈ 𝒜 := begin refine mem_up_shadow_iff.trans ⟨_, _⟩, { rintro ⟨s, hs, a, ha, rfl⟩, refine ⟨a, mem_insert_self a s, _⟩, rwa erase_insert ha }, { rintro ⟨a, ha, hs⟩, exact ⟨s.erase a, hs, a, not_mem_erase _ _, insert_erase ha⟩ } end /-- `s ∈ ∂⁺ 𝒜` iff `s` is exactly one element less than something from `𝒜`. -/ lemma mem_up_shadow_iff_exists_mem_card_add_one : s ∈ ∂⁺ 𝒜 ↔ ∃ t ∈ 𝒜, t ⊆ s ∧ t.card + 1 = s.card := begin refine mem_up_shadow_iff_erase_mem.trans ⟨_, _⟩, { rintro ⟨a, ha, hs⟩, exact ⟨s.erase a, hs, erase_subset _ _, card_erase_add_one ha⟩ }, { rintro ⟨t, ht, hts, h⟩, obtain ⟨a, ha⟩ : ∃ a, s \ t = {a} := card_eq_one.1 (by rw [card_sdiff hts, ←h, add_tsub_cancel_left]), refine ⟨a, sdiff_subset _ _ ((ha.ge : _ ⊆ _) $ mem_singleton_self a), _⟩, rwa [←sdiff_singleton_eq_erase, ←ha, sdiff_sdiff_eq_self hts] } end /-- Being in the upper shadow of `𝒜` means we have a superset in `𝒜`. -/ lemma exists_subset_of_mem_up_shadow (hs : s ∈ ∂⁺ 𝒜) : ∃ t ∈ 𝒜, t ⊆ s := let ⟨t, ht, hts, _⟩ := mem_up_shadow_iff_exists_mem_card_add_one.1 hs in ⟨t, ht, hts⟩ /-- `t ∈ ∂^k 𝒜` iff `t` is exactly `k` elements more than something in `𝒜`. -/ lemma mem_up_shadow_iff_exists_mem_card_add : s ∈ (∂⁺^[k]) 𝒜 ↔ ∃ t ∈ 𝒜, t ⊆ s ∧ t.card + k = s.card := begin induction k with k ih generalizing 𝒜 s, { refine ⟨λ hs, ⟨s, hs, subset.refl _, rfl⟩, _⟩, rintro ⟨t, ht, hst, hcard⟩, rwa ←eq_of_subset_of_card_le hst hcard.ge }, simp only [exists_prop, function.comp_app, function.iterate_succ], refine ih.trans _, clear ih, split, { rintro ⟨t, ht, hts, hcardst⟩, obtain ⟨u, hu, hut, hcardtu⟩ := mem_up_shadow_iff_exists_mem_card_add_one.1 ht, refine ⟨u, hu, hut.trans hts, _⟩, rw [←hcardst, ←hcardtu, add_right_comm], refl }, { rintro ⟨t, ht, hts, hcard⟩, obtain ⟨u, htu, hus, hu⟩ := finset.exists_intermediate_set 1 (by { rw [add_comm, ←hcard], exact add_le_add_left (zero_lt_succ _) _ }) hts, rw add_comm at hu, refine ⟨u, mem_up_shadow_iff_exists_mem_card_add_one.2 ⟨t, ht, htu, hu.symm⟩, hus, _⟩, rw [hu, ←hcard, add_right_comm], refl } end @[simp] lemma shadow_image_compl : (∂ 𝒜).image compl = ∂⁺ (𝒜.image compl) := begin ext s, simp only [mem_image, exists_prop, mem_shadow_iff, mem_up_shadow_iff], split, { rintro ⟨_, ⟨s, hs, a, ha, rfl⟩, rfl⟩, exact ⟨sᶜ, ⟨s, hs, rfl⟩, a, not_mem_compl.2 ha, compl_erase.symm⟩ }, { rintro ⟨_, ⟨s, hs, rfl⟩, a, ha, rfl⟩, exact ⟨s.erase a, ⟨s, hs, a, not_mem_compl.1 ha, rfl⟩, compl_erase⟩ } end @[simp] lemma up_shadow_image_compl : (∂⁺ 𝒜).image compl = ∂ (𝒜.image compl) := begin ext s, simp only [mem_image, exists_prop, mem_shadow_iff, mem_up_shadow_iff], split, { rintro ⟨_, ⟨s, hs, a, ha, rfl⟩, rfl⟩, exact ⟨sᶜ, ⟨s, hs, rfl⟩, a, mem_compl.2 ha, compl_insert.symm⟩ }, { rintro ⟨_, ⟨s, hs, rfl⟩, a, ha, rfl⟩, exact ⟨insert a s, ⟨s, hs, a, mem_compl.1 ha, rfl⟩, compl_insert⟩ } end end up_shadow end finset
055d79096edb3cee7b7fdf8b32d92293555a2732
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/tests/lean/run/assert_tac2.lean
f643eadc91869221f0902a3d3e88641c4133c0a8
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,295
lean
import data.nat open nat eq.ops theorem lcm_dvd {m n k : nat} (H1 : (m | k)) (H2 : (n | k)) : (lcm m n | k) := match eq_zero_or_pos k with | @or.inl _ _ kzero := begin rewrite kzero, apply dvd_zero end | @or.inr _ _ kpos := obtain (p : nat) (km : k = m * p), from exists_eq_mul_right_of_dvd H1, obtain (q : nat) (kn : k = n * q), from exists_eq_mul_right_of_dvd H2, begin have mpos : m > 0, from pos_of_dvd_of_pos H1 kpos, have npos : n > 0, from pos_of_dvd_of_pos H2 kpos, have gcd_pos : gcd m n > 0, from gcd_pos_of_pos_left n mpos, have ppos : p > 0, begin apply pos_of_mul_pos_left, apply (eq.rec_on km), exact kpos end, have qpos : q > 0, from pos_of_mul_pos_left (kn ▸ kpos), have H3 : p * q * (m * n * gcd p q) = p * q * (gcd m n * k), begin apply sorry end, have H4 : m * n * gcd p q = gcd m n * k, from !eq_of_mul_eq_mul_left (mul_pos ppos qpos) H3, have H5 : gcd m n * (lcm m n * gcd p q) = gcd m n * k, begin rewrite [-mul.assoc, gcd_mul_lcm], exact H4 end, have H6 : lcm m n * gcd p q = k, from !eq_of_mul_eq_mul_left gcd_pos H5, exact (dvd.intro H6) end end
869dc5a899c2cab82b9d2041cfe56a31443426c4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/big_operators/enat.lean
2e91d5558e9188f0fa3c8511612651e044334395
[]
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
673
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.big_operators.basic import Mathlib.data.nat.enat import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Big operators in `enat` A simple lemma about sums in `enat`. -/ namespace finset theorem sum_nat_coe_enat {α : Type u_1} (s : finset α) (f : α → ℕ) : (finset.sum s fun (x : α) => ↑(f x)) = ↑(finset.sum s fun (x : α) => f x) := Eq.symm (add_monoid_hom.map_sum enat.coe_hom (fun (x : α) => f x) s)
76f90a6168c6d9be0a8db33d1dc597e226fda110
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/algebra/big_operators.lean
9ccc766380136f084d09e549e138de7151cb34b9
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
37,469
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 Some big operators for lists and finite sets. -/ import tactic.tauto data.list.basic data.finset data.nat.enat import algebra.group algebra.ordered_group algebra.group_power universes u v w variables {α : Type u} {β : Type v} {γ : Type w} theorem directed.finset_le {r : α → α → Prop} [is_trans α r] {ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) := show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $ λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in ⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h) (λ h, h.symm ▸ h₁) (λ h, trans (H _ h) h₂)⟩ theorem finset.exists_le {α : Type u} [nonempty α] [directed_order α] (s : finset α) : ∃ M, ∀ i ∈ s, i ≤ M := directed.finset_le (by apply_instance) directed_order.directed s namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} /-- `prod s f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = (s.1.map f).prod := rfl @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = s.fold (*) 1 f := rfl section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {α : Type u} {f : α → β} : (∅:finset α).prod f = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (insert a s).prod f = f a * s.prod f := fold_insert @[simp, to_additive] lemma prod_singleton : (singleton a).prod f = f a := eq.trans fold_singleton $ mul_one _ @[to_additive] lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) : ({a, b} : finset α).prod f = f a * f b := by simp [prod_insert (not_mem_singleton.2 h.symm), mul_comm] @[simp] lemma prod_const_one : s.prod (λx, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : s.sum (λx, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive] prod_const_one @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (s.image g).prod f = s.prod (λx, f (g x)) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (s.map e).prod f = s.prod (λa, f (e a)) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (s₁ ∪ s₂).prod f * (s₁ ∩ s₂).prod f = s₁.prod f * s₂.prod f := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (s₁ ∪ s₂).prod f = s₁.prod f * s₂.prod f := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (s₂ \ s₁).prod f * s₁.prod f = s₂.prod f := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[to_additive] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y)) → (s.bind t).prod f = s.prod (λx, (t x).prod f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y), from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have ∀y∈s, x ≠ y, from assume _ hy h, by rw [←h] at hy; contradiction, have ∀y∈s, disjoint (t x) (t y), from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy), have disjoint (t x) (finset.bind s t), from (disjoint_bind_right _ _ _).mpr this, by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (s.product t).prod f = s.prod (λx, t.prod $ λy, f (x, y)) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _, apply h, cc end @[to_additive] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (s.sigma t).prod f = s.prod (λa, (t a).prod $ λs, f ⟨a, s⟩) := by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact calc (s.sigma t).prod f = (s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind ... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) : prod_bind $ assume a₁ ha a₂ ha₂ h, by simp only [disjoint_iff_ne, mem_image]; rintro ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩; apply h; cc ... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) : prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = (s.filter (λc', g c' = g c)).prod h) : (s.image g).prod f = s.prod h := begin letI := classical.dec_eq γ, rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]}, rw [finset.prod_bind], { refine finset.prod_congr rfl (assume a ha, _), rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩, exact eq b hb }, assume a₀ _ a₁ _ ne, refine (disjoint_iff_ne.2 _), assume c₀ h₀ c₁ h₁, rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩, rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩, exact mt (congr_arg g) ne end @[to_additive] lemma prod_mul_distrib : s.prod (λx, f x * g x) = s.prod f * s.prod g := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm [decidable_eq γ] {s : finset γ} {t : finset α} {f : γ → α → β} : s.prod (λx, t.prod $ f x) = t.prod (λy, s.prod $ λx, f x y) := finset.induction_on s (by simp only [prod_empty, prod_const_one]) $ λ _ _ H ih, by simp only [prod_insert H, prod_mul_distrib, ih] @[to_additive] lemma prod_hom [comm_monoid γ] (s : finset α) {f : α → β} (g : β → γ) [is_monoid_hom g] : s.prod (λx, g (f x)) = g (s.prod f) := by { delta finset.prod, rw [← multiset.map_map, multiset.prod_hom _ g] } @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (s.prod f) (s.prod g) := by { delta finset.prod, apply multiset.prod_hom_rel; assumption } @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : s₁.prod f = s₂.prod f := by haveI := classical.dec_eq α; exact have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 1), from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] -- If we use `[decidable_eq β]` here, some rewrites fail because they find a wrong `decidable` -- instance first; `{∀x, decidable (f x ≠ 1)}` doesn't work with `rw ← prod_filter_ne_one` @[to_additive] lemma prod_filter_ne_one [∀ x, decidable (f x ≠ 1)] : (s.filter $ λx, f x ≠ 1).prod f = s.prod f := prod_subset (filter_subset _) $ λ x, by { classical, rw [not_imp_comm, mem_filter], exact and.intro } @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (s.filter p).prod f = s.prod (λa, if p a then f a else 1) := calc (s.filter p).prod f = (s.filter p).prod (λa, if p a then f a else 1) : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = s.prod (λa, if p a then f a else 1) : begin refine prod_subset (filter_subset s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : s.prod f = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc s.prod f = ({a} : finset α).prod f : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_ite [comm_monoid γ] {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : s.prod (λ x, h (if p x then f x else g x)) = (s.filter p).prod (λ x, h (f x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (g x)) := by letI := classical.dec_eq α; exact calc s.prod (λ x, h (if p x then f x else g x)) = (s.filter p ∪ s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) : by rw [filter_union_filter_neg_eq] ... = (s.filter p).prod (λ x, h (if p x then f x else g x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) : prod_union (by simp [disjoint_right] {contextual := tt}) ... = (s.filter p).prod (λ x, h (f x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (g x)) : congr_arg2 _ (prod_congr rfl (by simp {contextual := tt})) (prod_congr rfl (by simp {contextual := tt})) @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : β) : s.prod (λ x, (ite (a = x) b 1)) = ite (a ∈ s) b 1 := begin rw ←finset.prod_filter, split_ifs; simp only [filter_eq, if_true, if_false, h, prod_empty, prod_singleton, insert_empty_eq_singleton], end @[to_additive] lemma prod_attach {f : α → β} : s.attach.prod (λx, f x.val) = s.prod f := by haveI := classical.dec_eq α; exact calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] @[to_additive] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.prod f = t.prod g := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : s.prod f = t.prod g := by classical; exact calc s.prod f = (s.filter $ λx, f x ≠ 1).prod f : prod_filter_ne_one.symm ... = (t.filter $ λx, g x ≠ 1).prod g : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = t.prod g : prod_filter_ne_one @[to_additive] lemma nonempty_of_prod_ne_one (h : s.prod f ≠ 1) : s.nonempty := s.eq_empty_or_nonempty.elim (λ H, false.elim $ h $ H.symm ▸ prod_empty) id @[to_additive] lemma exists_ne_one_of_prod_ne_one (h : s.prod f ≠ 1) : ∃a∈s, f a ≠ 1 := begin classical, rw ← prod_filter_ne_one at h, rcases nonempty_of_prod_ne_one h with ⟨x, hx⟩, exact ⟨x, (mem_filter.1 hx).1, (mem_filter.1 hx).2⟩ end @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (range (nat.succ n)).prod f = f n * (range n).prod f := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).prod f = (range n).prod (f ∘ nat.succ) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ lemma sum_Ico_add {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) (m n k : ℕ) : (Ico m n).sum (λ l, f (k + l)) = (Ico (m + k) (n + k)).sum f := Ico.image_add m n k ▸ eq.symm $ sum_image $ λ x hx y hy h, nat.add_left_cancel h @[to_additive] lemma prod_Ico_add (f : ℕ → β) (m n k : ℕ) : (Ico m n).prod (λ l, f (k + l)) = (Ico (m + k) (n + k)).prod f := Ico.image_add m n k ▸ eq.symm $ prod_image $ λ x hx y hy h, nat.add_left_cancel h lemma sum_Ico_succ_top {δ : Type*} [add_comm_monoid δ] {a b : ℕ} (hab : a ≤ b) (f : ℕ → δ) : (Ico a (b + 1)).sum f = (Ico a b).sum f + f b := by rw [Ico.succ_top hab, sum_insert Ico.not_mem_top, add_comm] @[to_additive] lemma prod_Ico_succ_top {a b : ℕ} (hab : a ≤ b) (f : ℕ → β) : (Ico a b.succ).prod f = (Ico a b).prod f * f b := @sum_Ico_succ_top (additive β) _ _ _ hab _ lemma sum_eq_sum_Ico_succ_bot {δ : Type*} [add_comm_monoid δ] {a b : ℕ} (hab : a < b) (f : ℕ → δ) : (Ico a b).sum f = f a + (Ico (a + 1) b).sum f := have ha : a ∉ Ico (a + 1) b, by simp, by rw [← sum_insert ha, Ico.insert_succ_bot hab] @[to_additive] lemma prod_eq_prod_Ico_succ_bot {a b : ℕ} (hab : a < b) (f : ℕ → β) : (Ico a b).prod f = f a * (Ico (a + 1) b).prod f := @sum_eq_sum_Ico_succ_bot (additive β) _ _ _ hab _ @[to_additive] lemma prod_Ico_consecutive (f : ℕ → β) {m n k : ℕ} (hmn : m ≤ n) (hnk : n ≤ k) : (Ico m n).prod f * (Ico n k).prod f = (Ico m k).prod f := Ico.union_consecutive hmn hnk ▸ eq.symm $ prod_union $ Ico.disjoint_consecutive m n k @[to_additive] lemma prod_range_mul_prod_Ico (f : ℕ → β) {m n : ℕ} (h : m ≤ n) : (range m).prod f * (Ico m n).prod f = (range n).prod f := Ico.zero_bot m ▸ Ico.zero_bot n ▸ prod_Ico_consecutive f (nat.zero_le m) h @[to_additive sum_Ico_eq_add_neg] lemma prod_Ico_eq_div {δ : Type*} [comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).prod f = (range n).prod f * ((range m).prod f)⁻¹ := eq_mul_inv_iff_mul_eq.2 $ by rw [mul_comm]; exact prod_range_mul_prod_Ico f h lemma sum_Ico_eq_sub {δ : Type*} [add_comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).sum f = (range n).sum f - (range m).sum f := sum_Ico_eq_add_neg f h @[to_additive] lemma prod_Ico_eq_prod_range (f : ℕ → β) (m n : ℕ) : (Ico m n).prod f = (range (n - m)).prod (λ l, f (m + l)) := begin by_cases h : m ≤ n, { rw [← Ico.zero_bot, prod_Ico_add, zero_add, nat.sub_add_cancel h] }, { replace h : n ≤ m := le_of_not_ge h, rw [Ico.eq_empty_of_le h, nat.sub_eq_zero_of_le h, range_zero, prod_empty, prod_empty] } end @[to_additive] lemma prod_range_zero (f : ℕ → β) : (range 0).prod f = 1 := by rw [range_zero, prod_empty] lemma prod_range_one (f : ℕ → β) : (range 1).prod f = f 0 := by { rw [range_one], apply @prod_singleton ℕ β 0 f } lemma sum_range_one {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) : (range 1).sum f = f 0 := by { rw [range_one], apply @sum_singleton ℕ δ 0 f } attribute [to_additive finset.sum_range_one] prod_range_one @[simp] lemma prod_const (b : β) : s.prod (λ a, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt}) lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt}) @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), s.prod f = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ rfl) (λ ⟨x, hx⟩, have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': (erase (erase s x) (g x hx)).prod f = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx])) @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : s.prod f = 1 := calc s.prod f = s.prod (λx, 1) : finset.prod_congr rfl h ... = 1 : finset.prod_const_one /-- A product over all subsets of `s ∪ {x}` is obtained by multiplying the product over all subsets of `s`, and over all subsets of `s` to which one adds `x`. -/ @[to_additive] lemma prod_powerset_insert [decidable_eq α] {s : finset α} {x : α} (h : x ∉ s) (f : finset α → β) : (insert x s).powerset.prod f = s.powerset.prod f * s.powerset.prod (λt, f (insert x t)) := begin rw [powerset_insert, finset.prod_union, finset.prod_image], { assume t₁ h₁ t₂ h₂ heq, rw [← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₁ h), ← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₂ h), heq] }, { rw finset.disjoint_iff_ne, assume t₁ h₁ t₂ h₂, rcases finset.mem_image.1 h₂ with ⟨t₃, h₃, H₃₂⟩, rw ← H₃₂, exact ne_insert_of_not_mem _ _ (not_mem_of_mem_powerset_of_not_mem h₁ h) } end @[to_additive] lemma prod_piecewise [decidable_eq α] (s t : finset α) (f g : α → β) : s.prod (t.piecewise f g) = (s ∩ t).prod f * (s \ t).prod g := begin refine s.induction_on (by simp) _, assume x s hxs Hrec, by_cases h : x ∈ t, { simp [hxs, h, Hrec, insert_sdiff_of_mem s h, mul_assoc] }, { simp [hxs, h, Hrec, insert_sdiff_of_not_mem s h], rw [mul_comm, mul_assoc], congr' 1, rw mul_comm } end end comm_monoid lemma sum_smul' [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : s.sum (λ x, add_monoid.smul n (f x)) = add_monoid.smul n (s.sum f) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive sum_smul'] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : s.sum (λ a, b) = add_monoid.smul s.card b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive] prod_const lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive] prod_range_succ' lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(s.sum f) = s.sum (λa, f a : α → β) := (s.sum_hom _).symm lemma prod_nat_cast [comm_semiring β] (s : finset α) (f : α → ℕ) : ↑(s.prod f) = s.prod (λa, f a : α → β) := (s.prod_hom _).symm protected lemma sum_nat_coe_enat [decidable_eq α] (s : finset α) (f : α → ℕ) : s.sum (λ x, (f x : enat)) = (s.sum f : ℕ) := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has, ih] } end theorem dvd_sum [comm_semiring α] {a : α} {s : finset β} {f : β → α} (h : ∀ x ∈ s, a ∣ f x) : a ∣ s.sum f := multiset.dvd_sum (λ y hy, by rcases multiset.mem_map.1 hy with ⟨x, hx, rfl⟩; exact h x hx) lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) : f (s.sum g) ≤ s.sum (λc, f (g c)) := begin refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _, rw [multiset.map_map], refl end lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {f : β → α} {s : finset β} : abs (s.sum f) ≤ s.sum (λa, abs (f a)) := le_sum_of_subadditive _ abs_zero abs_add s f section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : s.prod (λx, (f x)⁻¹) = (s.prod f)⁻¹ := s.prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = s.sum (λ a, card (t a)) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bind t).card = s.sum (λ u, card (t u)) := calc (s.bind t).card = (s.bind t).sum (λ _, 1) : by simp ... = s.sum (λ a, (t a).sum (λ _, 1)) : finset.sum_bind h ... = s.sum (λ u, card (t u)) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ s.sum (λ a, (t a).card) := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ (insert a s).sum (λ a, card (t a)) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) := by letI := classical.dec_eq α; exact calc s.card = ((s.image f).bind (λ a, s.filter (λ x, f x = a))).card : congr_arg _ (finset.ext.2 $ λ x, ⟨λ hs, mem_bind.2 ⟨f x, mem_image_of_mem _ hs, mem_filter.2 ⟨hs, rfl⟩⟩, λ h, let ⟨a, ha₁, ha₂⟩ := mem_bind.1 h in by convert filter_subset s ha₂⟩) ... = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_bind (by simp [disjoint_left, finset.ext] {contextual := tt}) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (s.sum f) = s.sum (λa, gsmul z (f a)) := (s.sum_hom (gsmul z)).symm end finset namespace finset variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α} @[simp] lemma sum_sub_distrib [add_comm_group β] : s.sum (λx, f x - g x) = s.sum f - s.sum g := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section semiring variables [semiring β] lemma sum_mul : s.sum f * b = s.sum (λx, f x * b) := (s.sum_hom (λ x, x * b)).symm lemma mul_sum : b * s.sum f = s.sum (λx, b * f x) := (s.sum_hom _).symm @[simp] lemma sum_mul_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (f x * ite (a = x) 1 0)) = ite (a ∈ s) (f a) 0 := begin convert sum_ite_eq s a (f a), funext, split_ifs with h; simp [h], end @[simp] lemma sum_boole_mul [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (ite (a = x) 1 0) * f x) = ite (a ∈ s) (f a) 0 := begin convert sum_ite_eq s a (f a), funext, split_ifs with h; simp [h], end end semiring section comm_semiring variables [decidable_eq α] [comm_semiring β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : s.prod f = 0 := calc s.prod f = (insert a (erase s a)).prod f : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_sum {δ : α → Type*} [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : s.prod (λa, (t a).sum (λb, f a b)) = (s.pi t).sum (λp, s.attach.prod (λx, f x.1 (p x.1 x.2))) := begin induction s using finset.induction with a s ha ih, { rw [pi_empty, sum_singleton], refl }, { have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y, disjoint (image (pi.cons s a x) (pi s t)) (image (pi.cons s a y) (pi s t)), { assume x hx y hy h, simp only [disjoint_iff_ne, mem_image], rintros _ ⟨p₂, hp, eq₂⟩ _ ⟨p₃, hp₃, eq₃⟩ eq, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq₂, eq₃, eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind h₁], refine sum_congr rfl (λ b _, _), have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from assume p₁ h₁ p₂ h₂ eq, injective_pi_cons ha eq, rw [sum_image h₂, mul_sum], refine sum_congr rfl (λ g _, _), rw [attach_insert, prod_insert, prod_image], { simp only [pi.cons_same], congr', ext ⟨v, hv⟩, congr', exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm }, { exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj }, { simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } } end end comm_semiring section integral_domain /- add integral_semi_domain to support nat and ennreal -/ variables [decidable_eq α] [integral_domain β] lemma prod_eq_zero_iff : s.prod f = 0 ↔ (∃a∈s, f a = 0) := finset.induction_on s ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩ $ λ a s ha ih, by rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end integral_domain section ordered_comm_monoid variables [decidable_eq α] [ordered_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f ≤ (s₂ \ s₁).sum f + s₁.sum f : le_add_of_nonneg_left' $ sum_nonneg $ by simpa only [mem_sdiff, and_imp] ... = (s₂ \ s₁ ∪ s₁).sum f : (sum_union sdiff_disjoint).symm ... = s₂.sum f : by rw [sdiff_union_of_subset h] lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := finset.induction_on s (λ _, ⟨λ _ _, false.elim, λ _, rfl⟩) $ λ a s ha ih H, have ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, by rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this), forall_mem_insert, ih this] lemma sum_eq_zero_iff_of_nonpos : (∀x∈s, f x ≤ 0) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := @sum_eq_zero_iff_of_nonneg _ (order_dual β) _ _ _ _ lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ s.sum f := have (singleton a).sum f ≤ s.sum f, from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_comm_monoid section canonically_ordered_monoid variables [decidable_eq α] [canonically_ordered_monoid β] lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : s₁.sum f ≤ s₂.sum f := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_le_sum_of_ne_zero [@decidable_rel β (≤)] (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f : by rw [←sum_union, filter_union_filter_neg_eq]; exact disjoint_filter.2 (assume _ _ h n_h, n_h h) ... ≤ s₂.sum f : add_le_of_nonpos_of_le' (sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid β] theorem sum_lt_sum (Hle : ∀ i ∈ s, f i ≤ g i) (Hlt : ∃ i ∈ s, f i < g i) : s.sum f < s.sum g := begin classical, rcases Hlt with ⟨i, hi, hlt⟩, rw [← insert_erase hi, sum_insert (not_mem_erase _ _), sum_insert (not_mem_erase _ _)], exact add_lt_add_of_lt_of_le hlt (sum_le_sum $ λ j hj, Hle j $ mem_of_mem_erase hj) end end ordered_cancel_comm_monoid section decidable_linear_ordered_cancel_comm_monoid variables [decidable_linear_ordered_cancel_comm_monoid β] theorem exists_le_of_sum_le (hs : s.nonempty) (Hle : s.sum f ≤ s.sum g) : ∃ i ∈ s, f i ≤ g i := begin classical, contrapose! Hle with Hlt, rcases hs with ⟨i, hi⟩, exact sum_lt_sum (λ i hi, le_of_lt (Hlt i hi)) ⟨i, hi, Hlt i hi⟩ end end decidable_linear_ordered_cancel_comm_monoid section linear_ordered_comm_ring variables [decidable_eq α] [linear_ordered_comm_ring β] /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_nonneg {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_le_one] }, { simp [has], apply mul_nonneg, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_pos {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_lt_one] }, { simp [has], apply mul_pos, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_le_prod {s : finset α} {f g : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ g x) : s.prod f ≤ s.prod g := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has], apply mul_le_mul, exact h1 a (mem_insert_self a s), apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H), apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)), apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) } end end linear_ordered_comm_ring @[simp] lemma card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ theorem card_le_mul_card_image [decidable_eq β] {f : α → β} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * (s.image f).card := calc s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_image _ _ ... ≤ (s.image f).sum (λ _, n) : sum_le_sum hn ... = _ : by simp [mul_comm] @[simp] lemma prod_Ico_id_eq_fact : ∀ n : ℕ, (Ico 1 n.succ).prod (λ x, x) = nat.fact n | 0 := rfl | (n+1) := by rw [prod_Ico_succ_top $ nat.succ_le_succ $ zero_le n, nat.fact_succ, prod_Ico_id_eq_fact n, nat.succ_eq_add_one, mul_comm] end finset namespace finset section gauss_sum /-- Gauss' summation formula -/ lemma sum_range_id_mul_two : ∀(n : ℕ), (finset.range n).sum (λi, i) * 2 = n * (n - 1) | 0 := rfl | 1 := rfl | ((n + 1) + 1) := begin rw [sum_range_succ, add_mul, sum_range_id_mul_two (n + 1), mul_comm, two_mul, nat.add_sub_cancel, nat.add_sub_cancel, mul_comm _ n], simp only [add_mul, one_mul, add_comm, add_assoc, add_left_comm] end /-- Gauss' summation formula -/ lemma sum_range_id (n : ℕ) : (finset.range n).sum (λi, i) = (n * (n - 1)) / 2 := by rw [← sum_range_id_mul_two n, nat.mul_div_cancel]; exact dec_trivial end gauss_sum lemma card_eq_sum_ones (s : finset α) : s.card = s.sum (λ _, 1) := by simp end finset section group open list variables [group α] [group β] theorem is_group_anti_hom.map_prod (f : α → β) [is_group_anti_hom f] (l : list α) : f (prod l) = prod (map f (reverse l)) := by induction l with hd tl ih; [exact is_group_anti_hom.map_one f, simp only [prod_cons, is_group_anti_hom.map_mul f, ih, reverse_cons, map_append, prod_append, map_singleton, prod_cons, prod_nil, mul_one]] theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) := λ l, @is_group_anti_hom.map_prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this end group @[to_additive] lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β) (s : finset α) : g (s.prod f) = s.prod (λx, g (f x)) := (s.prod_hom g).symm @[to_additive is_add_group_hom_finset_sum] lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ) (f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, s.prod (λc, f c a)) := { map_mul := assume a b, by simp only [λc, is_mul_hom.map_mul (f c), finset.prod_mul_distrib] } attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : s.to_finset.sum (λa, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (to_finset (a :: s)).sum (λx, count x (a :: s)) = (to_finset (a :: s)).sum (λx, (if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a :: s) : begin by_cases a ∈ s.to_finset, { have : (to_finset s).sum (λx, ite (x = a) 1 0) = (finset.singleton a).sum (λx, ite (x = a) 1 0), { apply (finset.sum_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { exact λ _ _ H, if_neg (mt finset.mem_singleton.2 H) } }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : (to_finset s).sum (λx, ite (x = a) 1 0) = (to_finset s).sum (λx, 0), from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) end multiset namespace with_top open finset variables [decidable_eq α] /-- sum of finte numbers is still finite -/ lemma sum_lt_top [ordered_comm_monoid β] {s : finset α} {f : α → with_top β} : (∀a∈s, f a < ⊤) → s.sum f < ⊤ := finset.induction_on s (by { intro h, rw sum_empty, exact coe_lt_top _ }) (λa s ha ih h, begin rw [sum_insert ha, add_lt_top], split, { apply h, apply mem_insert_self }, { apply ih, intros a ha, apply h, apply mem_insert_of_mem ha } end) /-- sum of finte numbers is still finite -/ lemma sum_lt_top_iff [canonically_ordered_monoid β] {s : finset α} {f : α → with_top β} : s.sum f < ⊤ ↔ (∀a∈s, f a < ⊤) := iff.intro (λh a ha, lt_of_le_of_lt (single_le_sum (λa ha, zero_le _) ha) h) sum_lt_top end with_top
5dbbed5fb6661bd7633b6978eb8490d9a3e94374
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/map.lean
72c1715f45013763da79ec1e71d62657f3257874
[ "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
2,092
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ definition map (A B : Type) := A → option B namespace map variables {A B : Type} open tactic definition empty : map A B := λ a, none definition lookup (k : A) (m : map A B) : option B := m k theorem ext (m₁ m₂ : map A B) : (∀ a, lookup a m₁ = lookup a m₂) → m₁ = m₂ := funext theorem lookup_empty (k : A) : lookup k (empty : map A B) = none := rfl variable [decidable_eq A] definition insert (k : A) (v : B) (m : map A B) : map A B := λ a, if a = k then some v else m a theorem lookup_insert (k : A) (v : B) (m : map A B) : lookup k (insert k v m) = some v := by unfold [`map.insert, `map.lookup] >> dsimp >> rewrite `if_pos >> reflexivity theorem lookup_insert_of_ne {k₁ k₂ : A} (v : B) (m : map A B) : k₁ ≠ k₂ → lookup k₁ (insert k₂ v m) = lookup k₁ m := by intros >> unfold [`map.insert, `map.lookup] >> dsimp >> rewrite `if_neg >> assumption definition erase (k : A) (m : map A B) : map A B := λ a, if a = k then none else m a theorem lookup_erase (k : A) (v : B) (m : map A B) : lookup k (erase k m) = none := by unfold [`map.erase, `map.lookup] >> dsimp >> rewrite `if_pos >> reflexivity theorem lookup_erase_of_ne {k₁ k₂ : A} (v : B) (m : map A B) : k₁ ≠ k₂ → lookup k₁ (erase k₂ m) = lookup k₁ m := by intros >> unfold [`map.erase, `map.lookup] >> dsimp >> rewrite `if_neg >> assumption theorem erase_empty (k : A) : erase k empty = (empty : map A B) := funext (λ a, by unfold [`map.erase, `map.empty] >> rewrite `if_t_t) theorem erase_insert {k : A} {m : map A B} (v : B) : lookup k m = none → erase k (insert k v m) = m := assume h, funext (λ a, decidable.by_cases (suppose a = k, by get_local `this >>= subst >> unfold [`map.erase, `map.insert] >> rewrite `if_pos >> symmetry >> assumption >> reflexivity) (suppose a ≠ k, by unfold [`map.erase, `map.insert] >> rewrite `if_neg >> dsimp >> rewrite `if_neg >> repeat assumption)) end map
5ba7549f62471c2ae902e5e889a9d147572d1dbb
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/qpf/multivariate/constructions/sigma.lean
7a4e966b84a331e88ecb4c0d1fce08c127f18021
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,046
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.pfunctor.multivariate.basic import data.qpf.multivariate.basic /-! # Dependent product and sum of QPFs are QPFs -/ universes u namespace mvqpf open_locale mvfunctor variables {n : ℕ} {A : Type u} variables (F : A → typevec.{u} n → Type u) /-- Dependent sum of of an `n`-ary functor. The sum can range over data types like `ℕ` or over `Type.{u-1}` -/ def sigma (v : typevec.{u} n) : Type.{u} := Σ α : A, F α v /-- Dependent product of of an `n`-ary functor. The sum can range over data types like `ℕ` or over `Type.{u-1}` -/ def pi (v : typevec.{u} n) : Type.{u} := Π α : A, F α v instance sigma.inhabited {α} [inhabited A] [inhabited (F (default A) α)] : inhabited (sigma F α) := ⟨ ⟨default A, default _⟩ ⟩ instance pi.inhabited {α} [Π a, inhabited (F a α)] : inhabited (pi F α) := ⟨ λ a, default _ ⟩ variables [Π α, mvfunctor $ F α] namespace sigma instance : mvfunctor (sigma F) := { map := λ α β f ⟨a,x⟩, ⟨a,f <$$> x⟩ } variables [Π α, mvqpf $ F α] /-- polynomial functor representation of a dependent sum -/ protected def P : mvpfunctor n := ⟨ Σ a, (P (F a)).A, λ x, (P (F x.1)).B x.2 ⟩ /-- abstraction function for dependent sums -/ protected def abs ⦃α⦄ : (sigma.P F).obj α → sigma F α | ⟨a,f⟩ := ⟨ a.1, mvqpf.abs ⟨a.2, f⟩ ⟩ /-- representation function for dependent sums -/ protected def repr ⦃α⦄ : sigma F α → (sigma.P F).obj α | ⟨a,f⟩ := let x := mvqpf.repr f in ⟨ ⟨a,x.1⟩, x.2 ⟩ instance : mvqpf (sigma F) := { P := sigma.P F, abs := sigma.abs F, repr := sigma.repr F, abs_repr := by rintros α ⟨x,f⟩; simp [sigma.repr,sigma.abs,abs_repr], abs_map := by rintros α β f ⟨x,g⟩; simp [sigma.abs,mvpfunctor.map_eq]; simp [(<$$>),mvfunctor._match_1,← abs_map,← mvpfunctor.map_eq] } end sigma namespace pi instance : mvfunctor (pi F) := { map := λ α β f x a, f <$$> x a } variables [Π α, mvqpf $ F α] /-- polynomial functor representation of a dependent product -/ protected def P : mvpfunctor n := ⟨ Π a, (P (F a)).A, λ x i, Σ a : A, (P (F a)).B (x a) i ⟩ /-- abstraction function for dependent products -/ protected def abs ⦃α⦄ : (pi.P F).obj α → pi F α | ⟨a,f⟩ := λ x, mvqpf.abs ⟨a x, λ i y, f i ⟨_,y⟩⟩ /-- representation function for dependent products -/ protected def repr ⦃α⦄ : pi F α → (pi.P F).obj α | f := ⟨ λ a, (mvqpf.repr (f a)).1, λ i a, (@mvqpf.repr _ _ _ (_inst_2 _) _ (f _)).2 _ a.2 ⟩ instance : mvqpf (pi F) := { P := pi.P F, abs := pi.abs F, repr := pi.repr F, abs_repr := by rintros α f; ext; simp [pi.repr,pi.abs,abs_repr], abs_map := by rintros α β f ⟨x,g⟩; simp only [pi.abs, mvpfunctor.map_eq]; ext; simp only [(<$$>)]; simp only [←abs_map, mvpfunctor.map_eq]; refl } end pi end mvqpf
b8f4eb215295fa9ae1220e8b2cb01e5307685d2c
7cdf3413c097e5d36492d12cdd07030eb991d394
/world_experiments/world8/level9andahalf.lean
019e97006cd8bf6ac3f60dde384d57756c8ad50f
[]
no_license
alreadydone/natural_number_game
3135b9385a9f43e74cfbf79513fc37e69b99e0b3
1a39e693df4f4e871eb449890d3c7715a25c2ec9
refs/heads/master
1,599,387,390,105
1,573,200,587,000
1,573,200,691,000
220,397,084
0
0
null
1,573,192,734,000
1,573,192,733,000
null
UTF-8
Lean
false
false
879
lean
import game.world3.level8 -- hide import game.world2.level11 -- succ ne zero -- hide import game.world2.level13 -- add_left_eq_zero -- hide namespace mynat -- hide /- # Multiplication World ## Level 9: `mul_pos` If you do `cases b with n` when `b` is a natural number, it will split into the two possibilites, namely `b = 0` and `b = succ(n)`. So `cases` here is like a weaker version of induction (you don't get the inductive hypothesis). Understanding `intro` and `apply` will be useful here. -/ /- Theorem The product of two non-zero natural numbers is non-zero. -/ theorem mul_pos (a b : mynat) : a ≠ 0 → b ≠ 0 → a * b ≠ 0 := begin [less_leaky] intros ha hb, intro hab, cases b with b, apply hb, refl, rw mul_succ at hab, apply ha, cases a with a, refl, rw add_succ at hab, exfalso, apply succ_ne_zero hab end end mynat -- hide
252cb80032644b669ac189c5a7bb6b2236a8a67c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/equiv/ring_aut_auto.lean
18cc962beb1c0670f19ca7312a373e525f60eb69
[]
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
2,208
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.equiv.ring import Mathlib.data.equiv.mul_add_aut import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Ring automorphisms This file defines the automorphism group structure on `ring_aut R := ring_equiv R R`. ## Implementation notes The definition of multiplication in the automorphism group agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, but not with `category_theory.comp`. This file is kept separate from `data/equiv/ring` so that `group_theory.perm` is free to use equivalences (and other files that use them) before the group structure is defined. ## Tags ring_aut -/ /-- The group of ring automorphisms. -/ def ring_aut (R : Type u_1) [Mul R] [Add R] := R ≃+* R namespace ring_aut /-- The group operation on automorphisms of a ring is defined by `λ g h, ring_equiv.trans h g`. This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`. -/ protected instance group (R : Type u_1) [Mul R] [Add R] : group (ring_aut R) := group.mk (fun (g h : R ≃+* R) => ring_equiv.trans h g) sorry (ring_equiv.refl R) sorry sorry ring_equiv.symm (fun (a b : R ≃+* R) => a * ring_equiv.symm b) sorry protected instance inhabited (R : Type u_1) [Mul R] [Add R] : Inhabited (ring_aut R) := { default := 1 } /-- Monoid homomorphism from ring automorphisms to additive automorphisms. -/ def to_add_aut (R : Type u_1) [Mul R] [Add R] : ring_aut R →* add_aut R := monoid_hom.mk ring_equiv.to_add_equiv sorry sorry /-- Monoid homomorphism from ring automorphisms to multiplicative automorphisms. -/ def to_mul_aut (R : Type u_1) [Mul R] [Add R] : ring_aut R →* mul_aut R := monoid_hom.mk ring_equiv.to_mul_equiv sorry sorry /-- Monoid homomorphism from ring automorphisms to permutations. -/ def to_perm (R : Type u_1) [Mul R] [Add R] : ring_aut R →* equiv.perm R := monoid_hom.mk ring_equiv.to_equiv sorry sorry end Mathlib
5114f177eeb46f241799097070f9b2305eb9626f
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/consumePPHint.lean
4a3b50ae70d9b50adfd713274373efbc32cf5dc7
[ "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
256
lean
constant p : Nat → Prop constant q : Nat → Prop theorem p_of_q : q x → p x := sorry theorem pletfun : p (let_fun x := 0; x + 1) := by -- ⊢ p (let_fun x := 0; x + 1) apply p_of_q trace_state -- `let_fun` hint should not be consumed. sorry
d4971cd6fdbf6ef010dd232283b10538d07e879a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/hom/equiv/units/group_with_zero.lean
a8325367140ac79f42c4c757b05ab45de460f58b
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,225
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov -/ import algebra.hom.equiv.units.basic import algebra.group_with_zero.units.basic /-! # Multiplication by a nonzero element in a `group_with_zero` is a permutation. -/ variables {G : Type*} namespace equiv section group_with_zero variables [group_with_zero G] /-- Left multiplication by a nonzero element in a `group_with_zero` is a permutation of the underlying type. -/ @[simps {fully_applied := ff}] protected def mul_left₀ (a : G) (ha : a ≠ 0) : perm G := (units.mk0 a ha).mul_left lemma _root_.mul_left_bijective₀ (a : G) (ha : a ≠ 0) : function.bijective ((*) a : G → G) := (equiv.mul_left₀ a ha).bijective /-- Right multiplication by a nonzero element in a `group_with_zero` is a permutation of the underlying type. -/ @[simps {fully_applied := ff}] protected def mul_right₀ (a : G) (ha : a ≠ 0) : perm G := (units.mk0 a ha).mul_right lemma _root_.mul_right_bijective₀ (a : G) (ha : a ≠ 0) : function.bijective ((* a) : G → G) := (equiv.mul_right₀ a ha).bijective end group_with_zero end equiv
130a01bc32ad992b98600c3975726e2c585b2997
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/nat/prime.lean
ddc4f54399a50974c6cd3dddefc6c57cb6f43846
[ "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
17,904
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro Prime numbers. -/ import data.nat.sqrt data.nat.gcd data.list.basic data.list.perm tactic.wlog open bool subtype namespace nat open decidable /-- `prime p` means that `p` is a prime number, that is, a natural number at least 2 whose only divisors are `p` and `1`. -/ def prime (p : ℕ) := p ≥ 2 ∧ ∀ m ∣ p, m = 1 ∨ m = p theorem prime.ge_two {p : ℕ} : prime p → p ≥ 2 := and.left theorem prime.gt_one {p : ℕ} : prime p → p > 1 := prime.ge_two lemma prime.ne_one {p : ℕ} (hp : p.prime) : p ≠ 1 := ne.symm $ (ne_of_lt hp.gt_one) theorem prime_def_lt {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m < p, m ∣ p → m = 1 := and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h l d, (h d).resolve_right (ne_of_lt l), λ h d, (decidable.lt_or_eq_of_le $ le_of_dvd (le_of_succ_le p2) d).imp_left (λ l, h l d)⟩ theorem prime_def_lt' {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m, 2 ≤ m → m < p → ¬ m ∣ p := prime_def_lt.trans $ and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h m2 l d, not_lt_of_ge m2 ((h l d).symm ▸ dec_trivial), λ h l d, begin rcases m with _|_|m, { rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial }, { refl }, { exact (h dec_trivial l).elim d } end⟩ theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m, 2 ≤ m → m ≤ sqrt p → ¬ m ∣ p := prime_def_lt'.trans $ and_congr_right $ λ p2, ⟨λ a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2, λ a, have ∀ {m k}, m ≤ k → 1 < m → p ≠ m * k, from λ m k mk m1 e, a m m1 (le_sqrt.2 (e.symm ▸ mul_le_mul_left m mk)) ⟨k, e⟩, λ m m2 l ⟨k, e⟩, begin cases (le_total m k) with mk km, { exact this mk m2 e }, { rw [mul_comm] at e, refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e, rwa [one_mul, ← e] } end⟩ /-- This instance is slower than the instance `decidable_prime` defined below, but has the advantage that it works in the kernel. If you need to prove that a particular number is prime, in any case you should not use `dec_trivial`, but rather `by norm_num`, which is much faster. -/ def decidable_prime_1 (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_lt' local attribute [instance] decidable_prime_1 lemma prime.ne_zero {n : ℕ} (h : prime n) : n ≠ 0 := assume hn : n = 0, have h2 : ¬ prime 0, from dec_trivial, h2 (hn ▸ h) theorem prime.pos {p : ℕ} (pp : prime p) : p > 0 := lt_of_succ_lt pp.gt_one theorem not_prime_zero : ¬ prime 0 := dec_trivial theorem not_prime_one : ¬ prime 1 := dec_trivial theorem prime_two : prime 2 := dec_trivial theorem prime_three : prime 3 := dec_trivial theorem prime.pred_pos {p : ℕ} (pp : prime p) : pred p > 0 := lt_pred_iff.2 pp.gt_one theorem succ_pred_prime {p : ℕ} (pp : prime p) : succ (pred p) = p := succ_pred_eq_of_pos pp.pos theorem dvd_prime {p m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p := ⟨λ d, pp.2 m d, λ h, h.elim (λ e, e.symm ▸ one_dvd _) (λ e, e.symm ▸ dvd_refl _)⟩ theorem dvd_prime_ge_two {p m : ℕ} (pp : prime p) (H : m ≥ 2) : m ∣ p ↔ m = p := (dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬ p ∣ 1 | d := (not_le_of_gt pp.gt_one) $ le_of_dvd dec_trivial d theorem not_prime_mul {a b : ℕ} (a1 : 1 < a) (b1 : 1 < b) : ¬ prime (a * b) := λ h, ne_of_lt (nat.mul_lt_mul_of_pos_left b1 (lt_of_succ_lt a1)) $ by simpa using (dvd_prime_ge_two h a1).1 (dvd_mul_right _ _) section min_fac private lemma min_fac_lemma (n k : ℕ) (h : ¬ k * k > n) : sqrt n - k < sqrt n + 2 - k := (nat.sub_lt_sub_right_iff $ le_sqrt.2 $ le_of_not_gt h).2 $ nat.lt_add_of_pos_right dec_trivial def min_fac_aux (n : ℕ) : ℕ → ℕ | k := if h : n < k * k then n else if k ∣ n then k else have _, from min_fac_lemma n k h, min_fac_aux (k + 2) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} /-- Returns the smallest prime factor of `n ≠ 1`. -/ def min_fac : ℕ → ℕ | 0 := 2 | 1 := 1 | (n+2) := if 2 ∣ n then 2 else min_fac_aux (n + 2) 3 @[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl @[simp] theorem min_fac_one : min_fac 1 = 1 := rfl theorem min_fac_eq : ∀ n, min_fac n = if 2 ∣ n then 2 else min_fac_aux n 3 | 0 := rfl | 1 := by simp [show 2≠1, from dec_trivial]; rw min_fac_aux; refl | (n+2) := have 2 ∣ n + 2 ↔ 2 ∣ n, from (nat.dvd_add_iff_left (by refl)).symm, by simp [min_fac, this]; congr private def min_fac_prop (n k : ℕ) := k ≥ 2 ∧ k ∣ n ∧ ∀ m ≥ 2, m ∣ n → k ≤ m theorem min_fac_aux_has_prop {n : ℕ} (n2 : n ≥ 2) (nd2 : ¬ 2 ∣ n) : ∀ k i, k = 2*i+3 → (∀ m ≥ 2, m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k) | k := λ i e a, begin rw min_fac_aux, by_cases h : n < k*k; simp [h], { have pp : prime n := prime_def_le_sqrt.2 ⟨n2, λ m m2 l d, not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩, from ⟨n2, dvd_refl _, λ m m2 d, le_of_eq ((dvd_prime_ge_two pp m2).1 d).symm⟩ }, have k2 : 2 ≤ k, { subst e, exact dec_trivial }, by_cases dk : k ∣ n; simp [dk], { exact ⟨k2, dk, a⟩ }, { refine have _, from min_fac_lemma n k h, min_fac_aux_has_prop (k+2) (i+1) (by simp [e, left_distrib]) (λ m m2 d, _), cases nat.eq_or_lt_of_le (a m m2 d) with me ml, { subst me, contradiction }, apply (nat.eq_or_lt_of_le ml).resolve_left, intro me, rw [← me, e] at d, change 2 * (i + 2) ∣ n at d, have := dvd_of_mul_right_dvd d, contradiction } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) : min_fac_prop n (min_fac n) := begin by_cases n0 : n = 0, {simp [n0, min_fac_prop, ge]}, have n2 : 2 ≤ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial }, simp [min_fac_eq], by_cases d2 : 2 ∣ n; simp [d2], { exact ⟨le_refl _, d2, λ k k2 d, k2⟩ }, { refine min_fac_aux_has_prop n2 d2 3 0 rfl (λ m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)), exact λ e, e.symm ▸ d } end theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_has_prop n1).2.1] theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) := let ⟨f2, fd, a⟩ := min_fac_has_prop n1 in prime_def_lt'.2 ⟨f2, λ m m2 l d, not_le_of_gt l (a m m2 (dvd_trans d fd))⟩ theorem min_fac_le_of_dvd {n : ℕ} : ∀ {m : ℕ}, m ≥ 2 → m ∣ n → min_fac n ≤ m := by by_cases n1 : n = 1; [exact λ m m2 d, n1.symm ▸ le_trans dec_trivial m2, exact (min_fac_has_prop n1).2.2] theorem min_fac_pos (n : ℕ) : min_fac n > 0 := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_prime n1).pos] theorem min_fac_le {n : ℕ} (H : n > 0) : min_fac n ≤ n := le_of_dvd H (min_fac_dvd n) theorem prime_def_min_fac {p : ℕ} : prime p ↔ p ≥ 2 ∧ min_fac p = p := ⟨λ pp, ⟨pp.ge_two, let ⟨f2, fd, a⟩ := min_fac_has_prop $ ne_of_gt pp.gt_one in ((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩, λ ⟨p2, e⟩, e ▸ min_fac_prime (ne_of_gt p2)⟩ /-- This instance is faster in the virtual machine than `decidable_prime_1`, but slower in the kernel. If you need to prove that a particular number is prime, in any case you should not use `dec_trivial`, but rather `by norm_num`, which is much faster. -/ instance decidable_prime (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_min_fac theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : n ≥ 2) : ¬ prime n ↔ min_fac n < n := (not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $ (lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm end min_fac theorem exists_dvd_of_not_prime {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n := ⟨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).gt_one, ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≥ 2 ∧ m < n := ⟨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).ge_two, (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_prime_and_dvd {n : ℕ} (n2 : n ≥ 2) : ∃ p, prime p ∧ p ∣ n := ⟨min_fac n, min_fac_prime (ne_of_gt n2), min_fac_dvd _⟩ theorem exists_infinite_primes (n : ℕ) : ∃ p, p ≥ n ∧ prime p := let p := min_fac (fact n + 1) in have f1 : fact n + 1 ≠ 1, from ne_of_gt $ succ_lt_succ $ fact_pos _, have pp : prime p, from min_fac_prime f1, have np : n ≤ p, from le_of_not_ge $ λ h, have h₁ : p ∣ fact n, from dvd_fact (min_fac_pos _) h, have h₂ : p ∣ 1, from (nat.dvd_add_iff_right h₁).2 (min_fac_dvd _), pp.not_dvd_one h₂, ⟨p, np, pp⟩ lemma prime.eq_two_or_odd {p : ℕ} (hp : prime p) : p = 2 ∨ p % 2 = 1 := (nat.mod_two_eq_zero_or_one p).elim (λ h, or.inl ((hp.2 2 (dvd_of_mod_eq_zero h)).resolve_left dec_trivial).symm) or.inr theorem factors_lemma {k} : (k+2) / min_fac (k+2) < k+2 := div_lt_self dec_trivial (min_fac_prime dec_trivial).gt_one /-- `factors n` is the prime factorization of `n`, listed in increasing order. -/ def factors : ℕ → list ℕ | 0 := [] | 1 := [] | n@(k+2) := let m := min_fac n in have n / m < n := factors_lemma, m :: factors (n / m) lemma mem_factors : ∀ {n p}, p ∈ factors n → prime p | 0 := λ p, false.elim | 1 := λ p, false.elim | n@(k+2) := λ p h, let m := min_fac n in have n / m < n := factors_lemma, have h₁ : p = m ∨ p ∈ (factors (n / m)) := (list.mem_cons_iff _ _ _).1 h, or.cases_on h₁ (λ h₂, h₂.symm ▸ min_fac_prime dec_trivial) mem_factors lemma prod_factors : ∀ {n}, 0 < n → list.prod (factors n) = n | 0 := (lt_irrefl _).elim | 1 := λ h, rfl | n@(k+2) := λ h, let m := min_fac n in have n / m < n := factors_lemma, show list.prod (m :: factors (n / m)) = n, from have h₁ : 0 < n / m := nat.pos_of_ne_zero $ λ h, have n = 0 * m := (nat.div_eq_iff_eq_mul_left (min_fac_pos _) (min_fac_dvd _)).1 h, by rw zero_mul at this; exact (show k + 2 ≠ 0, from dec_trivial) this, by rw [list.prod_cons, prod_factors h₁, nat.mul_div_cancel' (min_fac_dvd _)] theorem prime.coprime_iff_not_dvd {p n : ℕ} (pp : prime p) : coprime p n ↔ ¬ p ∣ n := ⟨λ co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]), λ nd, coprime_of_dvd $ λ m m2 mp, ((dvd_prime_ge_two pp m2).1 mp).symm ▸ nd⟩ theorem prime.dvd_iff_not_coprime {p n : ℕ} (pp : prime p) : p ∣ n ↔ ¬ coprime p n := iff_not_comm.2 pp.coprime_iff_not_dvd theorem prime.dvd_mul {p m n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n := ⟨λ H, or_iff_not_imp_left.2 $ λ h, (pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H, or.rec (λ h, dvd_mul_of_dvd_left h _) (λ h, dvd_mul_of_dvd_right h _)⟩ theorem prime.not_dvd_mul {p m n : ℕ} (pp : prime p) (Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) : ¬ p ∣ m * n := mt pp.dvd_mul.1 $ by simp [Hm, Hn] theorem prime.dvd_of_dvd_pow {p m n : ℕ} (pp : prime p) (h : p ∣ m^n) : p ∣ m := by induction n with n IH; [exact pp.not_dvd_one.elim h, exact (pp.dvd_mul.1 h).elim IH id] lemma prime.mul_eq_prime_pow_two_iff {x y p : ℕ} (hp : p.prime) (hx : x ≠ 1) (hy : y ≠ 1) : x * y = p ^ 2 ↔ x = p ∧ y = p := ⟨λ h, have pdvdxy : p ∣ x * y, by rw h; simp [nat.pow_two], begin wlog := hp.dvd_mul.1 pdvdxy using x y, cases case with a ha, have hap : a ∣ p, from ⟨y, by rwa [ha, nat.pow_two, mul_assoc, nat.mul_left_inj hp.pos, eq_comm] at h⟩, exact ((nat.dvd_prime hp).1 hap).elim (λ _, by clear_aux_decl; simp [*, nat.pow_two, nat.mul_left_inj hp.pos] at * {contextual := tt}) (λ _, by clear_aux_decl; simp [*, nat.pow_two, mul_comm, mul_assoc, nat.mul_left_inj hp.pos, nat.mul_right_eq_self_iff hp.pos] at * {contextual := tt}) end, λ ⟨h₁, h₂⟩, h₁.symm ▸ h₂.symm ▸ (nat.pow_two _).symm⟩ lemma prime.dvd_fact : ∀ {n p : ℕ} (hp : prime p), p ∣ n.fact ↔ p ≤ n | 0 p hp := iff_of_false hp.not_dvd_one (not_le_of_lt hp.pos) | (n+1) p hp := begin rw [fact_succ, hp.dvd_mul, prime.dvd_fact hp], exact ⟨λ h, h.elim (le_of_dvd (succ_pos _)) le_succ_of_le, λ h, (_root_.lt_or_eq_of_le h).elim (or.inr ∘ le_of_lt_succ) (λ h, or.inl $ by rw h)⟩ end theorem prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : prime p) (h : ¬ p ∣ a) : coprime a (p^m) := (pp.coprime_iff_not_dvd.2 h).symm.pow_right _ theorem coprime_primes {p q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q := pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_ge_two pq pp.ge_two theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) : coprime (p^n) (q^m) := ((coprime_primes pp pq).2 h).pow _ _ theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i := by rw [pp.dvd_iff_not_coprime]; apply em theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m i : ℕ} : i ∣ (p^m) ↔ ∃ k ≤ m, i = p^k := begin induction m with m IH generalizing i, {simp [pow_succ, le_zero_iff] at *}, by_cases p ∣ i, { cases h with a e, subst e, rw [pow_succ, mul_comm (p^m) p, nat.mul_dvd_mul_iff_left pp.pos, IH], split; intro h; rcases h with ⟨k, h, e⟩, { exact ⟨succ k, succ_le_succ h, by rw [mul_comm, e]; refl⟩ }, cases k with k, { apply pp.not_dvd_one.elim, simp at e, rw ← e, apply dvd_mul_right }, { refine ⟨k, le_of_succ_le_succ h, _⟩, rwa [mul_comm, pow_succ, nat.mul_right_inj pp.pos] at e } }, { split; intro d, { rw (pp.coprime_pow_of_not_dvd h).eq_one_of_dvd d, exact ⟨0, zero_le _, rfl⟩ }, { rcases d with ⟨k, l, e⟩, rw e, exact pow_dvd_pow _ l } } end section open list lemma mem_list_primes_of_dvd_prod {p : ℕ} (hp : prime p) : ∀ {l : list ℕ}, (∀ p ∈ l, prime p) → p ∣ prod l → p ∈ l | [] := λ h₁ h₂, absurd h₂ (prime.not_dvd_one hp) | (q :: l) := λ h₁ h₂, have h₃ : p ∣ q * prod l := @prod_cons _ _ l q ▸ h₂, have hq : prime q := h₁ q (mem_cons_self _ _), or.cases_on ((prime.dvd_mul hp).1 h₃) (λ h, by rw [prime.dvd_iff_not_coprime hp, coprime_primes hp hq, ne.def, not_not] at h; exact h ▸ mem_cons_self _ _) (λ h, have hl : ∀ p ∈ l, prime p := λ p hlp, h₁ p ((mem_cons_iff _ _ _).2 (or.inr hlp)), (mem_cons_iff _ _ _).2 (or.inr (mem_list_primes_of_dvd_prod hl h))) lemma mem_factors_iff_dvd {n p : ℕ} (hn : 0 < n) (hp : prime p) : p ∈ factors n ↔ p ∣ n := ⟨λ h, prod_factors hn ▸ list.dvd_prod h, λ h, mem_list_primes_of_dvd_prod hp (@mem_factors n) ((prod_factors hn).symm ▸ h)⟩ lemma perm_of_prod_eq_prod : ∀ {l₁ l₂ : list ℕ}, prod l₁ = prod l₂ → (∀ p ∈ l₁, prime p) → (∀ p ∈ l₂, prime p) → l₁ ~ l₂ | [] [] _ _ _ := perm.nil | [] (a :: l) h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁.symm ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₃ a (mem_cons_self _ _))) | (a :: l) [] h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁ ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₂ a (mem_cons_self _ _))) | (a :: l₁) (b :: l₂) h hl₁ hl₂ := have hl₁' : ∀ p ∈ l₁, prime p := λ p hp, hl₁ p (mem_cons_of_mem _ hp), have hl₂' : ∀ p ∈ (b :: l₂).erase a, prime p := λ p hp, hl₂ p (mem_of_mem_erase hp), have ha : a ∈ (b :: l₂) := mem_list_primes_of_dvd_prod (hl₁ a (mem_cons_self _ _)) hl₂ (h ▸ by rw prod_cons; exact dvd_mul_right _ _), have hb : b :: l₂ ~ a :: (b :: l₂).erase a := perm_erase ha, have hl : prod l₁ = prod ((b :: l₂).erase a) := (nat.mul_left_inj (prime.pos (hl₁ a (mem_cons_self _ _)))).1 $ by rwa [← prod_cons, ← prod_cons, ← prod_eq_of_perm hb], perm.trans (perm.skip _ (perm_of_prod_eq_prod hl hl₁' hl₂')) hb.symm lemma factors_unique {n : ℕ} {l : list ℕ} (h₁ : prod l = n) (h₂ : ∀ p ∈ l, prime p) : l ~ factors n := have hn : 0 < n := nat.pos_of_ne_zero $ λ h, begin rw h at *, clear h, induction l with a l hi, { exact absurd h₁ dec_trivial }, { rw prod_cons at h₁, exact nat.mul_ne_zero (ne_of_lt (prime.pos (h₂ a (mem_cons_self _ _)))).symm (hi (λ p hp, h₂ p (mem_cons_of_mem _ hp))) h₁ } end, perm_of_prod_eq_prod (by rwa prod_factors hn) h₂ (@mem_factors _) end lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : prime p) {m n k l : ℕ} (hpm : p ^ k ∣ m) (hpn : p ^ l ∣ n) (hpmn : p ^ (k+l+1) ∣ m*n) : p ^ (k+1) ∣ m ∨ p ^ (l+1) ∣ n := have hpd : p^(k+l) * p ∣ m*n, from hpmn, have hpd2 : p ∣ (m*n) / p ^ (k+l), from dvd_div_of_mul_dvd hpd, have hpd3 : p ∣ (m*n) / (p^k * p^l), by simpa [nat.pow_add] using hpd2, have hpd4 : p ∣ (m / p^k) * (n / p^l), by simpa [nat.div_mul_div hpm hpn] using hpd3, have hpd5 : p ∣ (m / p^k) ∨ p ∣ (n / p^l), from (prime.dvd_mul p_prime).1 hpd4, show p^k*p ∣ m ∨ p^l*p ∣ n, from hpd5.elim (assume : p ∣ m / p ^ k, or.inl $ mul_dvd_of_dvd_div hpm this) (assume : p ∣ n / p ^ l, or.inr $ mul_dvd_of_dvd_div hpn this) end nat
0a3c2622c0ba1f029f0ba5d192995f180c1267be
cf39355caa609c0f33405126beee2739aa3cb77e
/library/data/dlist.lean
e554844c254f6b221296b51e9445191c37168e7f
[ "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
2,838
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ universes u /-- A difference list is a function that, given a list, returns the original contents of the difference list prepended to the given list. This structure supports `O(1)` `append` and `concat` operations on lists, making it useful for append-heavy uses such as logging and pretty printing. -/ structure dlist (α : Type u) := (apply : list α → list α) (invariant : ∀ l, apply l = apply [] ++ l) namespace dlist open function variables {α : Type u} local notation `♯`:max := by abstract { intros, simp } /-- Convert a list to a dlist -/ def of_list (l : list α) : dlist α := ⟨append l, ♯⟩ /-- Convert a lazily-evaluated list to a dlist -/ def lazy_of_list (l : thunk (list α)) : dlist α := ⟨λ xs, l () ++ xs, ♯⟩ /-- Convert a dlist to a list -/ def to_list : dlist α → list α | ⟨xs, _⟩ := xs [] /-- Create a dlist containing no elements -/ def empty : dlist α := ⟨id, ♯⟩ local notation a `::_`:max := list.cons a /-- Create dlist with a single element -/ def singleton (x : α) : dlist α := ⟨x::_, ♯⟩ local attribute [simp] function.comp /-- `O(1)` Prepend a single element to a dlist -/ def cons (x : α) : dlist α → dlist α | ⟨xs, h⟩ := ⟨x::_ ∘ xs, by abstract { intros, simp, rw [←h] }⟩ /-- `O(1)` Append a single element to a dlist -/ def concat (x : α) : dlist α → dlist α | ⟨xs, h⟩ := ⟨xs ∘ x::_, by abstract { intros, simp, rw [h, h [x]], simp }⟩ /-- `O(1)` Append dlists -/ protected def append : dlist α → dlist α → dlist α | ⟨xs, h₁⟩ ⟨ys, h₂⟩ := ⟨xs ∘ ys, by { intros, simp, rw [h₂, h₁, h₁ (ys list.nil)], simp } ⟩ instance : has_append (dlist α) := ⟨dlist.append⟩ local attribute [simp] of_list to_list empty singleton cons concat dlist.append lemma to_list_of_list (l : list α) : to_list (of_list l) = l := by cases l; simp lemma of_list_to_list (l : dlist α) : of_list (to_list l) = l := begin cases l with xs, have h : append (xs []) = xs, { intros, funext x, simp [l_invariant x] }, simp [h] end lemma to_list_empty : to_list (@empty α) = [] := by simp lemma to_list_singleton (x : α) : to_list (singleton x) = [x] := by simp lemma to_list_append (l₁ l₂ : dlist α) : to_list (l₁ ++ l₂) = to_list l₁ ++ to_list l₂ := show to_list (dlist.append l₁ l₂) = to_list l₁ ++ to_list l₂, from by cases l₁; cases l₂; simp; rw l₁_invariant lemma to_list_cons (x : α) (l : dlist α) : to_list (cons x l) = x :: to_list l := by cases l; simp lemma to_list_concat (x : α) (l : dlist α) : to_list (concat x l) = to_list l ++ [x] := by cases l; simp; rw [l_invariant] end dlist
57929056546a12a3672bbc38646ce19e3fa579de
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/limits/shapes/images.lean
1457e0257f1e31eba8dce8f18e0c52601579d64b
[ "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
30,488
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.pullbacks import category_theory.limits.shapes.strong_epi /-! # Categorical images We define the categorical image of `f` as a factorisation `f = e ≫ m` through a monomorphism `m`, so that `m` factors through the `m'` in any other such factorisation. ## Main definitions * A `mono_factorisation` is a factorisation `f = e ≫ m`, where `m` is a monomorphism * `is_image F` means that a given mono factorisation `F` has the universal property of the image. * `has_image f` means that there is some image factorization for the morphism `f : X ⟶ Y`. * In this case, `image f` is some image object (selected with choice), `image.ι f : image f ⟶ Y` is the monomorphism `m` of the factorisation and `factor_thru_image f : X ⟶ image f` is the morphism `e`. * `has_images C` means that every morphism in `C` has an image. * Let `f : X ⟶ Y` and `g : P ⟶ Q` be morphisms in `C`, which we will represent as objects of the arrow category `arrow C`. Then `sq : f ⟶ g` is a commutative square in `C`. If `f` and `g` have images, then `has_image_map sq` represents the fact that there is a morphism `i : image f ⟶ image g` making the diagram X ----→ image f ----→ Y | | | | | | ↓ ↓ ↓ P ----→ image g ----→ Q commute, where the top row is the image factorisation of `f`, the bottom row is the image factorisation of `g`, and the outer rectangle is the commutative square `sq`. * If a category `has_images`, then `has_image_maps` means that every commutative square admits an image map. * If a category `has_images`, then `has_strong_epi_images` means that the morphism to the image is always a strong epimorphism. ## Main statements * When `C` has equalizers, the morphism `e` appearing in an image factorisation is an epimorphism. * When `C` has strong epi images, then these images admit image maps. ## Future work * TODO: coimages, and abelian categories. * TODO: connect this with existing working in the group theory and ring theory libraries. -/ noncomputable theory universes v u open category_theory open category_theory.limits.walking_parallel_pair namespace category_theory.limits variables {C : Type u} [category.{v} C] variables {X Y : C} (f : X ⟶ Y) /-- A factorisation of a morphism `f = e ≫ m`, with `m` monic. -/ structure mono_factorisation (f : X ⟶ Y) := (I : C) (m : I ⟶ Y) [m_mono : mono m] (e : X ⟶ I) (fac' : e ≫ m = f . obviously) restate_axiom mono_factorisation.fac' attribute [simp, reassoc] mono_factorisation.fac attribute [instance] mono_factorisation.m_mono attribute [instance] mono_factorisation.m_mono namespace mono_factorisation /-- The obvious factorisation of a monomorphism through itself. -/ def self [mono f] : mono_factorisation f := { I := X, m := f, e := 𝟙 X } -- I'm not sure we really need this, but the linter says that an inhabited instance -- ought to exist... instance [mono f] : inhabited (mono_factorisation f) := ⟨self f⟩ variables {f} /-- The morphism `m` in a factorisation `f = e ≫ m` through a monomorphism is uniquely determined. -/ @[ext] lemma ext {F F' : mono_factorisation f} (hI : F.I = F'.I) (hm : F.m = (eq_to_hom hI) ≫ F'.m) : F = F' := begin cases F, cases F', cases hI, simp at hm, dsimp at F_fac' F'_fac', congr, { assumption }, { resetI, apply (cancel_mono F_m).1, rw [F_fac', hm, F'_fac'], } end /-- Any mono factorisation of `f` gives a mono factorisation of `f ≫ g` when `g` is a mono. -/ @[simps] def comp_mono (F : mono_factorisation f) {Y' : C} (g : Y ⟶ Y') [mono g] : mono_factorisation (f ≫ g) := { I := F.I, m := F.m ≫ g, m_mono := mono_comp _ _, e := F.e, } /-- A mono factorisation of `f ≫ g`, where `g` is an isomorphism, gives a mono factorisation of `f`. -/ @[simps] def of_comp_iso {Y' : C} {g : Y ⟶ Y'} [is_iso g] (F : mono_factorisation (f ≫ g)) : mono_factorisation f := { I := F.I, m := F.m ≫ (inv g), m_mono := mono_comp _ _, e := F.e, } /-- Any mono factorisation of `f` gives a mono factorisation of `g ≫ f`. -/ @[simps] def iso_comp (F : mono_factorisation f) {X' : C} (g : X' ⟶ X) : mono_factorisation (g ≫ f) := { I := F.I, m := F.m, e := g ≫ F.e, } /-- A mono factorisation of `g ≫ f`, where `g` is an isomorphism, gives a mono factorisation of `f`. -/ @[simps] def of_iso_comp {X' : C} (g : X' ⟶ X) [is_iso g] (F : mono_factorisation (g ≫ f)) : mono_factorisation f := { I := F.I, m := F.m, e := inv g ≫ F.e, } /-- If `f` and `g` are isomorphic arrows, then a mono factorisation of `f` gives a mono factorisation of `g` -/ @[simps] def of_arrow_iso {f g : arrow C} (F : mono_factorisation f.hom) (sq : f ⟶ g) [is_iso sq] : mono_factorisation g.hom := { I := F.I, m := F.m ≫ sq.right, e := inv sq.left ≫ F.e, m_mono := mono_comp _ _, fac' := by simp only [fac_assoc, arrow.w, is_iso.inv_comp_eq, category.assoc] } end mono_factorisation variable {f} /-- Data exhibiting that a given factorisation through a mono is initial. -/ structure is_image (F : mono_factorisation f) := (lift : Π (F' : mono_factorisation f), F.I ⟶ F'.I) (lift_fac' : Π (F' : mono_factorisation f), lift F' ≫ F'.m = F.m . obviously) restate_axiom is_image.lift_fac' attribute [simp, reassoc] is_image.lift_fac namespace is_image @[simp, reassoc] lemma fac_lift {F : mono_factorisation f} (hF : is_image F) (F' : mono_factorisation f) : F.e ≫ hF.lift F' = F'.e := (cancel_mono F'.m).1 $ by simp variable (f) /-- The trivial factorisation of a monomorphism satisfies the universal property. -/ @[simps] def self [mono f] : is_image (mono_factorisation.self f) := { lift := λ F', F'.e } instance [mono f] : inhabited (is_image (mono_factorisation.self f)) := ⟨self f⟩ variable {f} /-- Two factorisations through monomorphisms satisfying the universal property must factor through isomorphic objects. -/ -- TODO this is another good candidate for a future `unique_up_to_canonical_iso`. @[simps] def iso_ext {F F' : mono_factorisation f} (hF : is_image F) (hF' : is_image F') : F.I ≅ F'.I := { hom := hF.lift F', inv := hF'.lift F, hom_inv_id' := (cancel_mono F.m).1 (by simp), inv_hom_id' := (cancel_mono F'.m).1 (by simp) } variables {F F' : mono_factorisation f} (hF : is_image F) (hF' : is_image F') lemma iso_ext_hom_m : (iso_ext hF hF').hom ≫ F'.m = F.m := by simp lemma iso_ext_inv_m : (iso_ext hF hF').inv ≫ F.m = F'.m := by simp lemma e_iso_ext_hom : F.e ≫ (iso_ext hF hF').hom = F'.e := by simp lemma e_iso_ext_inv : F'.e ≫ (iso_ext hF hF').inv = F.e := by simp /-- If `f` and `g` are isomorphic arrows, then a mono factorisation of `f` that is an image gives a mono factorisation of `g` that is an image -/ @[simps] def of_arrow_iso {f g : arrow C} {F : mono_factorisation f.hom} (hF : is_image F) (sq : f ⟶ g) [is_iso sq] : is_image (F.of_arrow_iso sq) := { lift := λ F', hF.lift (F'.of_arrow_iso (inv sq)), lift_fac' := λ F', by simpa only [mono_factorisation.of_arrow_iso_m, arrow.inv_right, ← category.assoc, is_iso.comp_inv_eq] using hF.lift_fac (F'.of_arrow_iso (inv sq)) } end is_image variable (f) /-- Data exhibiting that a morphism `f` has an image. -/ structure image_factorisation (f : X ⟶ Y) := (F : mono_factorisation f) (is_image : is_image F) namespace image_factorisation instance [mono f] : inhabited (image_factorisation f) := ⟨⟨_, is_image.self f⟩⟩ /-- If `f` and `g` are isomorphic arrows, then an image factorisation of `f` gives an image factorisation of `g` -/ @[simps] def of_arrow_iso {f g : arrow C} (F : image_factorisation f.hom) (sq : f ⟶ g) [is_iso sq] : image_factorisation g.hom := { F := F.F.of_arrow_iso sq, is_image := F.is_image.of_arrow_iso sq } end image_factorisation /-- `has_image f` means that there exists an image factorisation of `f`. -/ class has_image (f : X ⟶ Y) : Prop := mk' :: (exists_image : nonempty (image_factorisation f)) lemma has_image.mk {f : X ⟶ Y} (F : image_factorisation f) : has_image f := ⟨nonempty.intro F⟩ lemma has_image.of_arrow_iso {f g : arrow C} [h : has_image f.hom] (sq : f ⟶ g) [is_iso sq] : has_image g.hom := ⟨⟨h.exists_image.some.of_arrow_iso sq⟩⟩ @[priority 100] instance mono_has_image (f : X ⟶ Y) [mono f] : has_image f := has_image.mk ⟨_, is_image.self f⟩ section variable [has_image f] /-- Some factorisation of `f` through a monomorphism (selected with choice). -/ def image.mono_factorisation : mono_factorisation f := (classical.choice (has_image.exists_image)).F /-- The witness of the universal property for the chosen factorisation of `f` through a monomorphism. -/ def image.is_image : is_image (image.mono_factorisation f) := (classical.choice (has_image.exists_image)).is_image /-- The categorical image of a morphism. -/ def image : C := (image.mono_factorisation f).I /-- The inclusion of the image of a morphism into the target. -/ def image.ι : image f ⟶ Y := (image.mono_factorisation f).m @[simp] lemma image.as_ι : (image.mono_factorisation f).m = image.ι f := rfl instance : mono (image.ι f) := (image.mono_factorisation f).m_mono /-- The map from the source to the image of a morphism. -/ def factor_thru_image : X ⟶ image f := (image.mono_factorisation f).e /-- Rewrite in terms of the `factor_thru_image` interface. -/ @[simp] lemma as_factor_thru_image : (image.mono_factorisation f).e = factor_thru_image f := rfl @[simp, reassoc] lemma image.fac : factor_thru_image f ≫ image.ι f = f := (image.mono_factorisation f).fac' variable {f} /-- Any other factorisation of the morphism `f` through a monomorphism receives a map from the image. -/ def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I := (image.is_image f).lift F' @[simp, reassoc] lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f := (image.is_image f).lift_fac' F' @[simp, reassoc] lemma image.fac_lift (F' : mono_factorisation f) : factor_thru_image f ≫ image.lift F' = F'.e := (image.is_image f).fac_lift F' @[simp] lemma image.is_image_lift (F : mono_factorisation f) : (image.is_image f).lift F = image.lift F := rfl @[simp, reassoc] lemma is_image.lift_ι {F : mono_factorisation f} (hF : is_image F) : hF.lift (image.mono_factorisation f) ≫ image.ι f = F.m := hF.lift_fac _ -- TODO we could put a category structure on `mono_factorisation f`, -- with the morphisms being `g : I ⟶ I'` commuting with the `m`s -- (they then automatically commute with the `e`s) -- and show that an `image_of f` gives an initial object there -- (uniqueness of the lift comes for free). instance image.lift_mono (F' : mono_factorisation f) : mono (image.lift F') := by { apply mono_of_mono _ F'.m, simpa using mono_factorisation.m_mono _ } lemma has_image.uniq (F' : mono_factorisation f) (l : image f ⟶ F'.I) (w : l ≫ F'.m = image.ι f) : l = image.lift F' := (cancel_mono F'.m).1 (by simp [w]) /-- If `has_image g`, then `has_image (f ≫ g)` when `f` is an isomorphism. -/ instance {X Y Z : C} (f : X ⟶ Y) [is_iso f] (g : Y ⟶ Z) [has_image g] : has_image (f ≫ g) := { exists_image := ⟨ { F := { I := image g, m := image.ι g, e := f ≫ factor_thru_image g, }, is_image := { lift := λ F', image.lift { I := F'.I, m := F'.m, e := inv f ≫ F'.e, }, }, }⟩ } end section variables (C) /-- `has_images` asserts that every morphism has an image. -/ class has_images : Prop := (has_image : Π {X Y : C} (f : X ⟶ Y), has_image f) attribute [instance, priority 100] has_images.has_image end section variables (f) /-- The image of a monomorphism is isomorphic to the source. -/ def image_mono_iso_source [mono f] : image f ≅ X := is_image.iso_ext (image.is_image f) (is_image.self f) @[simp, reassoc] lemma image_mono_iso_source_inv_ι [mono f] : (image_mono_iso_source f).inv ≫ image.ι f = f := by simp [image_mono_iso_source] @[simp, reassoc] lemma image_mono_iso_source_hom_self [mono f] : (image_mono_iso_source f).hom ≫ f = image.ι f := begin conv { to_lhs, congr, skip, rw ←image_mono_iso_source_inv_ι f, }, rw [←category.assoc, iso.hom_inv_id, category.id_comp], end -- This is the proof that `factor_thru_image f` is an epimorphism -- from https://en.wikipedia.org/wiki/Image_%28category_theory%29, which is in turn taken from: -- Mitchell, Barry (1965), Theory of categories, MR 0202787, p.12, Proposition 10.1 @[ext] lemma image.ext [has_image f] {W : C} {g h : image f ⟶ W} [has_limit (parallel_pair g h)] (w : factor_thru_image f ≫ g = factor_thru_image f ≫ h) : g = h := begin let q := equalizer.ι g h, let e' := equalizer.lift _ w, let F' : mono_factorisation f := { I := equalizer g h, m := q ≫ image.ι f, m_mono := by apply mono_comp, e := e' }, let v := image.lift F', have t₀ : v ≫ q ≫ image.ι f = image.ι f := image.lift_fac F', have t : v ≫ q = 𝟙 (image f) := (cancel_mono_id (image.ι f)).1 (by { convert t₀ using 1, rw category.assoc }), -- The proof from wikipedia next proves `q ≫ v = 𝟙 _`, -- and concludes that `equalizer g h ≅ image f`, -- but this isn't necessary. calc g = 𝟙 (image f) ≫ g : by rw [category.id_comp] ... = v ≫ q ≫ g : by rw [←t, category.assoc] ... = v ≫ q ≫ h : by rw [equalizer.condition g h] ... = 𝟙 (image f) ≫ h : by rw [←category.assoc, t] ... = h : by rw [category.id_comp] end instance [has_image f] [Π {Z : C} (g h : image f ⟶ Z), has_limit (parallel_pair g h)] : epi (factor_thru_image f) := ⟨λ Z g h w, image.ext f w⟩ lemma epi_image_of_epi {X Y : C} (f : X ⟶ Y) [has_image f] [E : epi f] : epi (image.ι f) := begin rw ←image.fac f at E, resetI, exact epi_of_epi (factor_thru_image f) (image.ι f), end lemma epi_of_epi_image {X Y : C} (f : X ⟶ Y) [has_image f] [epi (image.ι f)] [epi (factor_thru_image f)] : epi f := by { rw [←image.fac f], apply epi_comp, } end section variables {f} {f' : X ⟶ Y} [has_image f] [has_image f'] /-- An equation between morphisms gives a comparison map between the images (which momentarily we prove is an iso). -/ def image.eq_to_hom (h : f = f') : image f ⟶ image f' := image.lift { I := image f', m := image.ι f', e := factor_thru_image f', }. instance (h : f = f') : is_iso (image.eq_to_hom h) := ⟨⟨image.eq_to_hom h.symm, ⟨(cancel_mono (image.ι f)).1 (by simp [image.eq_to_hom]), (cancel_mono (image.ι f')).1 (by simp [image.eq_to_hom])⟩⟩⟩ /-- An equation between morphisms gives an isomorphism between the images. -/ def image.eq_to_iso (h : f = f') : image f ≅ image f' := as_iso (image.eq_to_hom h) /-- As long as the category has equalizers, the image inclusion maps commute with `image.eq_to_iso`. -/ lemma image.eq_fac [has_equalizers C] (h : f = f') : image.ι f = (image.eq_to_iso h).hom ≫ image.ι f' := by { ext, simp [image.eq_to_iso, image.eq_to_hom], } end section variables {Z : C} (g : Y ⟶ Z) /-- The comparison map `image (f ≫ g) ⟶ image g`. -/ def image.pre_comp [has_image g] [has_image (f ≫ g)] : image (f ≫ g) ⟶ image g := image.lift { I := image g, m := image.ι g, e := f ≫ factor_thru_image g } @[simp, reassoc] lemma image.pre_comp_ι [has_image g] [has_image (f ≫ g)] : image.pre_comp f g ≫ image.ι g = image.ι (f ≫ g) := by simp [image.pre_comp] @[simp, reassoc] lemma image.factor_thru_image_pre_comp [has_image g] [has_image (f ≫ g)] : factor_thru_image (f ≫ g) ≫ image.pre_comp f g = f ≫ factor_thru_image g := by simp [image.pre_comp] /-- `image.pre_comp f g` is a monomorphism. -/ instance image.pre_comp_mono [has_image g] [has_image (f ≫ g)] : mono (image.pre_comp f g) := begin apply mono_of_mono _ (image.ι g), simp only [image.pre_comp_ι], apply_instance, end /-- The two step comparison map `image (f ≫ (g ≫ h)) ⟶ image (g ≫ h) ⟶ image h` agrees with the one step comparison map `image (f ≫ (g ≫ h)) ≅ image ((f ≫ g) ≫ h) ⟶ image h`. -/ lemma image.pre_comp_comp {W : C} (h : Z ⟶ W) [has_image (g ≫ h)] [has_image (f ≫ g ≫ h)] [has_image h] [has_image ((f ≫ g) ≫ h)] : image.pre_comp f (g ≫ h) ≫ image.pre_comp g h = image.eq_to_hom (category.assoc f g h).symm ≫ (image.pre_comp (f ≫ g) h) := begin apply (cancel_mono (image.ι h)).1, simp [image.pre_comp, image.eq_to_hom], end variables [has_equalizers C] /-- `image.pre_comp f g` is an epimorphism when `f` is an epimorphism (we need `C` to have equalizers to prove this). -/ instance image.pre_comp_epi_of_epi [has_image g] [has_image (f ≫ g)] [epi f] : epi (image.pre_comp f g) := begin apply epi_of_epi_fac (image.factor_thru_image_pre_comp _ _), exact epi_comp _ _ end instance has_image_iso_comp [is_iso f] [has_image g] : has_image (f ≫ g) := has_image.mk { F := (image.mono_factorisation g).iso_comp f, is_image := { lift := λ F', image.lift (F'.of_iso_comp f) }, } /-- `image.pre_comp f g` is an isomorphism when `f` is an isomorphism (we need `C` to have equalizers to prove this). -/ instance image.is_iso_precomp_iso (f : X ⟶ Y) [is_iso f] [has_image g] : is_iso (image.pre_comp f g) := ⟨⟨image.lift { I := image (f ≫ g), m := image.ι (f ≫ g), e := inv f ≫ factor_thru_image (f ≫ g) }, ⟨by { ext, simp [image.pre_comp], }, by { ext, simp [image.pre_comp], }⟩⟩⟩ -- Note that in general we don't have the other comparison map you might expect -- `image f ⟶ image (f ≫ g)`. instance has_image_comp_iso [has_image f] [is_iso g] : has_image (f ≫ g) := has_image.mk { F := (image.mono_factorisation f).comp_mono g, is_image := { lift := λ F', image.lift F'.of_comp_iso }, } /-- Postcomposing by an isomorphism induces an isomorphism on the image. -/ def image.comp_iso [has_image f] [is_iso g] : image f ≅ image (f ≫ g) := { hom := image.lift (image.mono_factorisation (f ≫ g)).of_comp_iso, inv := image.lift ((image.mono_factorisation f).comp_mono g) } @[simp, reassoc] lemma image.comp_iso_hom_comp_image_ι [has_image f] [is_iso g] : (image.comp_iso f g).hom ≫ image.ι (f ≫ g) = image.ι f ≫ g := by { ext, simp [image.comp_iso] } @[simp, reassoc] lemma image.comp_iso_inv_comp_image_ι [has_image f] [is_iso g] : (image.comp_iso f g).inv ≫ image.ι f = image.ι (f ≫ g) ≫ inv g := by { ext, simp [image.comp_iso] } end end category_theory.limits namespace category_theory.limits variables {C : Type u} [category.{v} C] section instance {X Y : C} (f : X ⟶ Y) [has_image f] : has_image (arrow.mk f).hom := show has_image f, by apply_instance end section has_image_map /-- An image map is a morphism `image f → image g` fitting into a commutative square and satisfying the obvious commutativity conditions. -/ structure image_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) := (map : image f.hom ⟶ image g.hom) (map_ι' : map ≫ image.ι g.hom = image.ι f.hom ≫ sq.right . obviously) instance inhabited_image_map {f : arrow C} [has_image f.hom] : inhabited (image_map (𝟙 f)) := ⟨⟨𝟙 _, by tidy⟩⟩ restate_axiom image_map.map_ι' attribute [simp, reassoc] image_map.map_ι @[simp, reassoc] lemma image_map.factor_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) (m : image_map sq) : factor_thru_image f.hom ≫ m.map = sq.left ≫ factor_thru_image g.hom := (cancel_mono (image.ι g.hom)).1 $ by simp /-- To give an image map for a commutative square with `f` at the top and `g` at the bottom, it suffices to give a map between any mono factorisation of `f` and any image factorisation of `g`. -/ def image_map.transport {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) (F : mono_factorisation f.hom) {F' : mono_factorisation g.hom} (hF' : is_image F') {map : F.I ⟶ F'.I} (map_ι : map ≫ F'.m = F.m ≫ sq.right) : image_map sq := { map := image.lift F ≫ map ≫ hF'.lift (image.mono_factorisation g.hom), map_ι' := by simp [map_ι] } /-- `has_image_map sq` means that there is an `image_map` for the square `sq`. -/ class has_image_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) : Prop := mk' :: (has_image_map : nonempty (image_map sq)) lemma has_image_map.mk {f g : arrow C} [has_image f.hom] [has_image g.hom] {sq : f ⟶ g} (m : image_map sq) : has_image_map sq := ⟨nonempty.intro m⟩ lemma has_image_map.transport {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) (F : mono_factorisation f.hom) {F' : mono_factorisation g.hom} (hF' : is_image F') (map : F.I ⟶ F'.I) (map_ι : map ≫ F'.m = F.m ≫ sq.right) : has_image_map sq := has_image_map.mk $ image_map.transport sq F hF' map_ι /-- Obtain an `image_map` from a `has_image_map` instance. -/ def has_image_map.image_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) [has_image_map sq] : image_map sq := classical.choice $ @has_image_map.has_image_map _ _ _ _ _ _ sq _ @[priority 100] -- see Note [lower instance priority] instance has_image_map_of_is_iso {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) [is_iso sq] : has_image_map sq := has_image_map.mk { map := image.lift ((image.mono_factorisation g.hom).of_arrow_iso (inv sq)), map_ι' := begin erw [← cancel_mono (inv sq).right, category.assoc, ← mono_factorisation.of_arrow_iso_m, image.lift_fac, category.assoc, ← comma.comp_right, is_iso.hom_inv_id, comma.id_right, category.comp_id], end } instance has_image_map.comp {f g h : arrow C} [has_image f.hom] [has_image g.hom] [has_image h.hom] (sq1 : f ⟶ g) (sq2 : g ⟶ h) [has_image_map sq1] [has_image_map sq2] : has_image_map (sq1 ≫ sq2) := has_image_map.mk { map := (has_image_map.image_map sq1).map ≫ (has_image_map.image_map sq2).map, map_ι' := by simp only [image_map.map_ι, image_map.map_ι_assoc, comma.comp_right, category.assoc] } variables {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) section local attribute [ext] image_map instance : subsingleton (image_map sq) := subsingleton.intro $ λ a b, image_map.ext a b $ (cancel_mono (image.ι g.hom)).1 $ by simp only [image_map.map_ι] end variable [has_image_map sq] /-- The map on images induced by a commutative square. -/ abbreviation image.map : image f.hom ⟶ image g.hom := (has_image_map.image_map sq).map lemma image.factor_map : factor_thru_image f.hom ≫ image.map sq = sq.left ≫ factor_thru_image g.hom := by simp lemma image.map_ι : image.map sq ≫ image.ι g.hom = image.ι f.hom ≫ sq.right := by simp lemma image.map_hom_mk'_ι {X Y P Q : C} {k : X ⟶ Y} [has_image k] {l : P ⟶ Q} [has_image l] {m : X ⟶ P} {n : Y ⟶ Q} (w : m ≫ l = k ≫ n) [has_image_map (arrow.hom_mk' w)] : image.map (arrow.hom_mk' w) ≫ image.ι l = image.ι k ≫ n := image.map_ι _ section variables {h : arrow C} [has_image h.hom] (sq' : g ⟶ h) variables [has_image_map sq'] /-- Image maps for composable commutative squares induce an image map in the composite square. -/ def image_map_comp : image_map (sq ≫ sq') := { map := image.map sq ≫ image.map sq' } @[simp] lemma image.map_comp [has_image_map (sq ≫ sq')] : image.map (sq ≫ sq') = image.map sq ≫ image.map sq' := show (has_image_map.image_map (sq ≫ sq')).map = (image_map_comp sq sq').map, by congr end section variables (f) /-- The identity `image f ⟶ image f` fits into the commutative square represented by the identity morphism `𝟙 f` in the arrow category. -/ def image_map_id : image_map (𝟙 f) := { map := 𝟙 (image f.hom) } @[simp] lemma image.map_id [has_image_map (𝟙 f)] : image.map (𝟙 f) = 𝟙 (image f.hom) := show (has_image_map.image_map (𝟙 f)).map = (image_map_id f).map, by congr end end has_image_map section variables (C) [has_images C] /-- If a category `has_image_maps`, then all commutative squares induce morphisms on images. -/ class has_image_maps := (has_image_map : Π {f g : arrow C} (st : f ⟶ g), has_image_map st) attribute [instance, priority 100] has_image_maps.has_image_map end section has_image_maps variables [has_images C] [has_image_maps C] /-- The functor from the arrow category of `C` to `C` itself that maps a morphism to its image and a commutative square to the induced morphism on images. -/ @[simps] def im : arrow C ⥤ C := { obj := λ f, image f.hom, map := λ _ _ st, image.map st } end has_image_maps section strong_epi_mono_factorisation /-- A strong epi-mono factorisation is a decomposition `f = e ≫ m` with `e` a strong epimorphism and `m` a monomorphism. -/ structure strong_epi_mono_factorisation {X Y : C} (f : X ⟶ Y) extends mono_factorisation f := [e_strong_epi : strong_epi e] attribute [instance] strong_epi_mono_factorisation.e_strong_epi /-- Satisfying the inhabited linter -/ instance strong_epi_mono_factorisation_inhabited {X Y : C} (f : X ⟶ Y) [strong_epi f] : inhabited (strong_epi_mono_factorisation f) := ⟨⟨⟨Y, 𝟙 Y, f, by simp⟩⟩⟩ /-- A mono factorisation coming from a strong epi-mono factorisation always has the universal property of the image. -/ def strong_epi_mono_factorisation.to_mono_is_image {X Y : C} {f : X ⟶ Y} (F : strong_epi_mono_factorisation f) : is_image F.to_mono_factorisation := { lift := λ G, (comm_sq.mk (show G.e ≫ G.m = F.e ≫ F.m, by rw [F.to_mono_factorisation.fac, G.fac])).lift, } variable (C) /-- A category has strong epi-mono factorisations if every morphism admits a strong epi-mono factorisation. -/ class has_strong_epi_mono_factorisations : Prop := mk' :: (has_fac : Π {X Y : C} (f : X ⟶ Y), nonempty (strong_epi_mono_factorisation f)) variable {C} lemma has_strong_epi_mono_factorisations.mk (d : Π {X Y : C} (f : X ⟶ Y), strong_epi_mono_factorisation f) : has_strong_epi_mono_factorisations C := ⟨λ X Y f, nonempty.intro $ d f⟩ @[priority 100] instance has_images_of_has_strong_epi_mono_factorisations [has_strong_epi_mono_factorisations C] : has_images C := { has_image := λ X Y f, let F' := classical.choice (has_strong_epi_mono_factorisations.has_fac f) in has_image.mk { F := F'.to_mono_factorisation, is_image := F'.to_mono_is_image } } end strong_epi_mono_factorisation section has_strong_epi_images variables (C) [has_images C] /-- A category has strong epi images if it has all images and `factor_thru_image f` is a strong epimorphism for all `f`. -/ class has_strong_epi_images : Prop := (strong_factor_thru_image : Π {X Y : C} (f : X ⟶ Y), strong_epi (factor_thru_image f)) attribute [instance] has_strong_epi_images.strong_factor_thru_image end has_strong_epi_images section has_strong_epi_images /-- If there is a single strong epi-mono factorisation of `f`, then every image factorisation is a strong epi-mono factorisation. -/ lemma strong_epi_of_strong_epi_mono_factorisation {X Y : C} {f : X ⟶ Y} (F : strong_epi_mono_factorisation f) {F' : mono_factorisation f} (hF' : is_image F') : strong_epi F'.e := by { rw ←is_image.e_iso_ext_hom F.to_mono_is_image hF', apply strong_epi_comp } lemma strong_epi_factor_thru_image_of_strong_epi_mono_factorisation {X Y : C} {f : X ⟶ Y} [has_image f] (F : strong_epi_mono_factorisation f) : strong_epi (factor_thru_image f) := strong_epi_of_strong_epi_mono_factorisation F $ image.is_image f /-- If we constructed our images from strong epi-mono factorisations, then these images are strong epi images. -/ @[priority 100] instance has_strong_epi_images_of_has_strong_epi_mono_factorisations [has_strong_epi_mono_factorisations C] : has_strong_epi_images C := { strong_factor_thru_image := λ X Y f, strong_epi_factor_thru_image_of_strong_epi_mono_factorisation $ classical.choice $ has_strong_epi_mono_factorisations.has_fac f } end has_strong_epi_images section has_strong_epi_images variables [has_images C] /-- A category with strong epi images has image maps. -/ @[priority 100] instance has_image_maps_of_has_strong_epi_images [has_strong_epi_images C] : has_image_maps C := { has_image_map := λ f g st, has_image_map.mk { map := (comm_sq.mk (show (st.left ≫ factor_thru_image g.hom) ≫ image.ι g.hom = factor_thru_image f.hom ≫ (image.ι f.hom ≫ st.right), by simp)).lift, }, } /-- If a category has images, equalizers and pullbacks, then images are automatically strong epi images. -/ @[priority 100] instance has_strong_epi_images_of_has_pullbacks_of_has_equalizers [has_pullbacks C] [has_equalizers C] : has_strong_epi_images C := { strong_factor_thru_image := λ X Y f, strong_epi.mk' (λ A B h h_mono x y sq, comm_sq.has_lift.mk' { l := image.lift { I := pullback h y, m := pullback.snd ≫ image.ι f, m_mono := by exactI mono_comp _ _, e := pullback.lift _ _ sq.w } ≫ pullback.fst, fac_left' := by simp only [image.fac_lift_assoc, pullback.lift_fst], fac_right' := by { ext, simp only [sq.w, category.assoc, image.fac_lift_assoc, pullback.lift_fst_assoc], }, }) } end has_strong_epi_images variables [has_strong_epi_mono_factorisations C] variables {X Y : C} {f : X ⟶ Y} /-- If `C` has strong epi mono factorisations, then the image is unique up to isomorphism, in that if `f` factors as a strong epi followed by a mono, this factorisation is essentially the image factorisation. -/ def image.iso_strong_epi_mono {I' : C} (e : X ⟶ I') (m : I' ⟶ Y) (comm : e ≫ m = f) [strong_epi e] [mono m] : I' ≅ image f := is_image.iso_ext {strong_epi_mono_factorisation . I := I', m := m, e := e}.to_mono_is_image $ image.is_image f @[simp] lemma image.iso_strong_epi_mono_hom_comp_ι {I' : C} (e : X ⟶ I') (m : I' ⟶ Y) (comm : e ≫ m = f) [strong_epi e] [mono m] : (image.iso_strong_epi_mono e m comm).hom ≫ image.ι f = m := is_image.lift_fac _ _ @[simp] lemma image.iso_strong_epi_mono_inv_comp_mono {I' : C} (e : X ⟶ I') (m : I' ⟶ Y) (comm : e ≫ m = f) [strong_epi e] [mono m] : (image.iso_strong_epi_mono e m comm).inv ≫ m = image.ι f := image.lift_fac _ end category_theory.limits
d8f8776935aa48a6f39f4f2368ae4c818ce50e4b
367134ba5a65885e863bdc4507601606690974c1
/src/system/random/basic.lean
7449015580ed9699abb061aca9976b6aedb96a79
[ "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
9,932
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import algebra.group_power import control.uliftable import control.monad.basic import data.bitvec.basic import data.list.basic import data.set.intervals.basic import data.stream.basic import data.fin import tactic.cache import tactic.interactive import tactic.norm_num import system.io import system.random /-! # Rand Monad and Random Class This module provides tools for formulating computations guided by randomness and for defining objects that can be created randomly. ## Main definitions * `rand` monad for computations guided by randomness; * `random` class for objects that can be generated randomly; * `random` to generate one object; * `random_r` to generate one object inside a range; * `random_series` to generate an infinite series of objects; * `random_series_r` to generate an infinite series of objects inside a range; * `io.mk_generator` to create a new random number generator; * `io.run_rand` to run a randomized computation inside the `io` monad; * `tactic.run_rand` to run a randomized computation inside the `tactic` monad ## Local notation * `i .. j` : `Icc i j`, the set of values between `i` and `j` inclusively; ## Tags random monad io ## References * Similar library in Haskell: https://hackage.haskell.org/package/MonadRandom -/ open list io applicative universes u v w /-- A monad to generate random objects using the generator type `g` -/ @[reducible] def rand_g (g : Type) (α : Type u) : Type u := state (ulift.{u} g) α /-- A monad to generate random objects using the generator type `std_gen` -/ @[reducible] def rand := rand_g std_gen instance (g : Type) : uliftable (rand_g.{u} g) (rand_g.{v} g) := @state_t.uliftable' _ _ _ _ _ (equiv.ulift.trans.{u u u u u} equiv.ulift.symm) open ulift (hiding inhabited) /-- Generate one more `ℕ` -/ def rand_g.next {g : Type} [random_gen g] : rand_g g ℕ := ⟨ prod.map id up ∘ random_gen.next ∘ down ⟩ local infix ` .. `:41 := set.Icc open stream /-- `bounded_random α` gives us machinery to generate values of type `α` between certain bounds -/ class bounded_random (α : Type u) [preorder α] := (random_r : Π g [random_gen g] (x y : α), (x ≤ y) → rand_g g (x .. y)) /-- `random α` gives us machinery to generate values of type `α` -/ class random (α : Type u) := (random [] : Π (g : Type) [random_gen g], rand_g g α) /-- shift_31_left = 2^31; multiplying by it shifts the binary representation of a number left by 31 bits, dividing by it shifts it right by 31 bits -/ def shift_31_left : ℕ := by apply_normed 2^31 namespace rand open stream variables (α : Type u) variables (g : Type) [random_gen g] /-- create a new random number generator distinct from the one stored in the state -/ def split : rand_g g g := ⟨ prod.map id up ∘ random_gen.split ∘ down ⟩ variables {g} section random variables [random α] export random (random) /-- Generate a random value of type `α`. -/ def random : rand_g g α := random.random α g /-- generate an infinite series of random values of type `α` -/ def random_series : rand_g g (stream α) := do gen ← uliftable.up (split g), pure $ stream.corec_state (random.random α g) gen end random variables {α} /-- Generate a random value between `x` and `y` inclusive. -/ def random_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) : rand_g g (x .. y) := bounded_random.random_r g x y h /-- generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ def random_series_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) : rand_g g (stream (x .. y)) := do gen ← uliftable.up (split g), pure $ corec_state (bounded_random.random_r g x y h) gen end rand namespace io private def accum_char (w : ℕ) (c : char) : ℕ := c.to_nat + 256 * w /-- create and a seed a random number generator -/ def mk_generator : io std_gen := do seed ← io.rand 0 shift_31_left, return $ mk_std_gen seed variables {α : Type} /-- Run `cmd` using a randomly seeded random number generator -/ def run_rand (cmd : _root_.rand α) : io α := do g ← io.mk_generator, return $ (cmd.run ⟨g⟩).1 /-- Run `cmd` using the provided seed. -/ def run_rand_with (seed : ℕ) (cmd : _root_.rand α) : io α := return $ (cmd.run ⟨mk_std_gen seed⟩).1 section random variables [random α] /-- randomly generate a value of type α -/ def random : io α := io.run_rand (rand.random α) /-- randomly generate an infinite series of value of type α -/ def random_series : io (stream α) := io.run_rand (rand.random_series α) end random section bounded_random variables [preorder α] [bounded_random α] /-- randomly generate a value of type α between `x` and `y` -/ def random_r (x y : α) (p : x ≤ y) : io (x .. y) := io.run_rand (bounded_random.random_r _ x y p) /-- randomly generate an infinite series of value of type α between `x` and `y` -/ def random_series_r (x y : α) (h : x ≤ y) : io (stream $ x .. y) := io.run_rand (rand.random_series_r x y h) end bounded_random end io namespace tactic /-- create a seeded random number generator in the `tactic` monad -/ meta def mk_generator : tactic std_gen := do tactic.unsafe_run_io @io.mk_generator /-- run `cmd` using the a randomly seeded random number generator in the tactic monad -/ meta def run_rand {α : Type u} (cmd : rand α) : tactic α := do ⟨g⟩ ← tactic.up mk_generator, return (cmd.run ⟨g⟩).1 variables {α : Type u} section bounded_random variables [preorder α] [bounded_random α] /-- Generate a random value between `x` and `y` inclusive. -/ meta def random_r (x y : α) (h : x ≤ y) : tactic (x .. y) := run_rand (rand.random_r x y h) /-- Generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ meta def random_series_r (x y : α) (h : x ≤ y) : tactic (stream $ x .. y) := run_rand (rand.random_series_r x y h) end bounded_random section random variables [random α] /-- randomly generate a value of type α -/ meta def random : tactic α := run_rand (rand.random α) /-- randomly generate an infinite series of value of type α -/ meta def random_series : tactic (stream α) := run_rand (rand.random_series α) end random end tactic open nat (succ one_add mod_eq_of_lt zero_lt_succ add_one succ_le_succ) variables {g : Type} [random_gen g] open nat namespace fin variables {n : ℕ} [fact (0 < n)] /-- generate a `fin` randomly -/ protected def random : rand_g g (fin n) := ⟨ λ ⟨g⟩, prod.map of_nat' up $ rand_nat g 0 n ⟩ end fin open nat instance nat_bounded_random : bounded_random ℕ := { random_r := λ g inst x y hxy, do z ← @fin.random g inst (succ $ y - x) _, pure ⟨z.val + x, nat.le_add_left _ _, by rw ← nat.le_sub_right_iff_add_le hxy; apply le_of_succ_le_succ z.is_lt⟩ } /-- This `bounded_random` interval generates integers between `x` and `y` by first generating a natural number between `0` and `y - x` and shifting the result appropriately. -/ instance int_bounded_random : bounded_random ℤ := { random_r := λ g inst x y hxy, do ⟨z,h₀,h₁⟩ ← @bounded_random.random_r ℕ _ _ g inst 0 (int.nat_abs $ y - x) dec_trivial, pure ⟨z + x, int.le_add_of_nonneg_left (int.coe_nat_nonneg _), int.add_le_of_le_sub_right $ le_trans (int.coe_nat_le_coe_nat_of_le h₁) (le_of_eq $ int.of_nat_nat_abs_eq_of_nonneg (int.sub_nonneg_of_le hxy)) ⟩ } instance fin_random (n : ℕ) [fact (0 < n)] : random (fin n) := { random := λ g inst, @fin.random g inst _ _ } instance fin_bounded_random (n : ℕ) : bounded_random (fin n) := { random_r := λ g inst (x y : fin n) p, do ⟨r, h, h'⟩ ← @rand.random_r ℕ g inst _ _ x.val y.val p, pure ⟨⟨r,lt_of_le_of_lt h' y.is_lt⟩, h, h'⟩ } /-- A shortcut for creating a `random (fin n)` instance from a proof that `0 < n` rather than on matching on `fin (succ n)` -/ def random_fin_of_pos : ∀ {n : ℕ} (h : 0 < n), random (fin n) | (succ n) _ := fin_random _ | 0 h := false.elim (not_lt_zero _ h) lemma bool_of_nat_mem_Icc_of_mem_Icc_to_nat (x y : bool) (n : ℕ) : n ∈ (x.to_nat .. y.to_nat) → bool.of_nat n ∈ (x .. y) := begin simp only [and_imp, set.mem_Icc], intros h₀ h₁, split; [ have h₂ := bool.of_nat_le_of_nat h₀, have h₂ := bool.of_nat_le_of_nat h₁ ]; rw bool.of_nat_to_nat at h₂; exact h₂, end instance : random bool := { random := λ g inst, (bool.of_nat ∘ subtype.val) <$> @bounded_random.random_r ℕ _ _ g inst 0 1 (nat.zero_le _) } instance : bounded_random bool := { random_r := λ g _inst x y p, subtype.map bool.of_nat (bool_of_nat_mem_Icc_of_mem_Icc_to_nat x y) <$> @bounded_random.random_r ℕ _ _ g _inst x.to_nat y.to_nat (bool.to_nat_le_to_nat p) } open_locale fin_fact /-- generate a random bit vector of length `n` -/ def bitvec.random (n : ℕ) : rand_g g (bitvec n) := bitvec.of_fin <$> rand.random (fin $ 2^n) /-- generate a random bit vector of length `n` -/ def bitvec.random_r {n : ℕ} (x y : bitvec n) (h : x ≤ y) : rand_g g (x .. y) := have h' : ∀ (a : fin (2 ^ n)), a ∈ (x.to_fin .. y.to_fin) → bitvec.of_fin a ∈ (x .. y), begin simp only [and_imp, set.mem_Icc], intros z h₀ h₁, replace h₀ := bitvec.of_fin_le_of_fin_of_le h₀, replace h₁ := bitvec.of_fin_le_of_fin_of_le h₁, rw bitvec.of_fin_to_fin at h₀ h₁, split; assumption, end, subtype.map bitvec.of_fin h' <$> rand.random_r x.to_fin y.to_fin (bitvec.to_fin_le_to_fin_of_le h) open nat instance random_bitvec (n : ℕ) : random (bitvec n) := { random := λ _ inst, @bitvec.random _ inst n } instance bounded_random_bitvec (n : ℕ) : bounded_random (bitvec n) := { random_r := λ _ inst x y p, @bitvec.random_r _ inst _ _ _ p }
7b65dbcd35054a99fc6eed4616f0318e29f85b10
bc0ebfde190bc1da50a425e63b8f44a50746ca42
/src/basic.lean
da6a867ec3a509739cb73834071c64a45c6a26aa
[ "Apache-2.0" ]
permissive
Pazzaz/erdos-szekeres
d93996420d10aaa8c603379abdea3391295e8be2
b6e53035340946602b9e4cc346314e541a5f3774
refs/heads/master
1,680,656,743,365
1,618,681,128,000
1,618,681,128,000
358,942,643
0
0
null
null
null
null
UTF-8
Lean
false
false
13,209
lean
import data.list import tactic import data.finset import misc_mathlib /-- Define all subsequences that (1) ends at an index and (2) are pairwise following a relation (This will in our case be `≤` and `≥`). -/ def subsequences_ending {X : Type*} [decidable_eq X] {A : list X} {n : ℕ} (h : n < A.length) (r : X → X → Prop) [decidable_rel r] : list (list X) := (A.take n.succ).sublists.filter (λ l, A.nth_le n h ∈ l.last' ∧ l.pairwise r) /- Our definition of `subsequences_ending` has the properties we want -/ theorem is_sublist {X : Type*} [decidable_eq X] {A l : list X} {n : ℕ} (h : n < A.length) (R : X → X → Prop) [decidable_rel R] (l_in : l ∈ subsequences_ending h R) : l <+ A ∧ l.pairwise R := begin obtain ⟨rest, ⟨_, pairw⟩⟩ := list.mem_filter.mp l_in, rw list.mem_sublists at rest, exact ⟨sublist_take_mp_sublist A l n.succ rest, pairw⟩, end theorem index_singleton_mem_finset {X : Type*} [decidable_eq X] {A : list X} {n1 : ℕ} (h1 : n1 < A.length) (r : X → X → Prop) [decidable_rel r] : [A.nth_le n1 h1] ∈ (subsequences_ending h1 r).to_finset := begin refine list.mem_to_finset.mpr _, dsimp [subsequences_ending], rw list.mem_filter, split, { refine list.mem_sublists.mpr (list.singleton_sublist.mpr _), rw (list.nth_le_take A h1 (lt_add_one n1)), exact list.nth_le_mem (list.take (n1.succ) A) n1 _, }, { exact ⟨rfl, list.pairwise_singleton r (list.nth_le A n1 h1)⟩, }, end theorem largest_subsequence_ending_ne_zero {X : Type*} [decidable_eq X] {A : list X} {n : ℕ} (h1 : n < A.length) (r : X → X → Prop) [decidable_rel r] : ((subsequences_ending h1 r).to_finset).sup list.length ≠ 0 := begin rw [(finset.insert_eq_of_mem (index_singleton_mem_finset h1 r)).symm, finset.sup_insert], exact ne_of_gt (le_max_left 1 (finset.sup _ list.length)), end theorem subsequences_ending_increasing {X : Type*} [decidable_eq X] {A : list X} {n1 n2 : ℕ} (h1 : n1 < A.length) (h2 : n2 < A.length) (h3 : n1 < n2) (r : X → X → Prop) [decidable_rel r] (r_trans : transitive r) (h4 : r (A.nth_le n1 h1) (A.nth_le n2 h2)) : ((subsequences_ending h1 r).to_finset).sup list.length < ((subsequences_ending h2 r).to_finset).sup list.length := begin obtain ⟨a, b, c⟩ := finset.exists_mem_eq_sup ((subsequences_ending h1 r).to_finset) _ list.length, { let newer := a.concat (A.nth_le n2 h2), have newer_in : newer ∈ (subsequences_ending h2 r).to_finset, { have kkk := list.mem_to_finset.mp b, dsimp [subsequences_ending] at kkk, rw list.mem_filter at kkk, apply list.mem_to_finset.mpr, dsimp [subsequences_ending], rw list.mem_filter, have thiny : newer = a ++ [A.nth_le n2 h2] := list.concat_eq_append (list.nth_le A n2 h2) a, split, { have newer_sub: newer <+ list.take n2.succ A := sublist_of_take_concat_sublist_of_take h2 h3 (list.mem_sublists.mp kkk.1), exact list.mem_sublists.mpr newer_sub, }, { split, { dsimp [newer], rw list.concat_eq_append (list.nth_le A n2 h2) a, rw list.last'_append_of_ne_nil _ (list.cons_ne_nil (list.nth_le A n2 h2) list.nil), exact rfl, }, { apply (list.chain'_iff_pairwise r_trans).mp _, apply list_chain_concat, { exact (list.chain'_iff_pairwise r_trans).mpr kkk.2.2, }, { intros _ ku_in, rw option.mem_unique ku_in kkk.2.1, exact h4, } } } }, rw c, have gflggl : a.length < newer.length := by { rw list.length_concat _ _, exact lt_add_one (list.length a),}, exact gt_of_ge_of_gt (finset.le_sup newer_in) gflggl, }, exact ⟨[A.nth_le n1 h1], index_singleton_mem_finset h1 r⟩, end theorem subsequence_sup_short_exist {X : Type*} [decidable_eq X] {A : list X} {n : ℕ} (h : n < A.length) (r : ℕ) (R : X → X → Prop) [decidable_rel R] (kk : (subsequences_ending h R).to_finset.sup list.length = r) {nnn : ℕ} (nle : nnn ≤ r) : ∃ l, l <+ A ∧ l.length = nnn ∧ l.pairwise R := begin obtain ⟨aaa, memming, lenning⟩ := finset.exists_mem_eq_sup ((subsequences_ending h R).to_finset) _ list.length, { obtain ⟨aaa_pre, aaa_pairwise⟩ := is_sublist h R (list.mem_to_finset.mp memming), refine ⟨aaa.take nnn, _, _, _⟩, { exact list.sublist.trans (list.sublist_of_prefix (list.take_prefix nnn aaa)) aaa_pre, }, { rw [list.length_take, lenning.symm, kk, min_eq_left_iff], exact nle, }, { have take_sublist := list.sublist_of_prefix (list.take_prefix nnn aaa), exact list.pairwise_of_sublist take_sublist aaa_pairwise, } }, exact ⟨[A.nth_le n h], index_singleton_mem_finset h R⟩, end theorem subsequences_ending_image {X : Type*} [decidable_eq X] {A : list X} {x : ℕ} (x_le : x < A.length) (k : ℕ) (R : X → X → Prop) [decidable_rel R] (h : transitive R) (h1: ∀ (x : list X), ¬(x <+ A ∧ x.length = k ∧ list.pairwise R x)) : (subsequences_ending x_le R).to_finset.sup list.length ∈ finset.range k \ {0} := begin apply finset.mem_sdiff.mpr, split, { rw finset.mem_range, by_contradiction, simp only [fin.val_eq_coe, not_lt] at h, let lenner := (subsequences_ending x_le R).to_finset.sup list.length, obtain ⟨ll, h_ll⟩ := subsequence_sup_short_exist x_le lenner R rfl h, exact (h1 ll) h_ll, }, { apply finset.not_mem_singleton.mpr, exact largest_subsequence_ending_ne_zero x_le R, } end /- **Erdős–Szekeres theorem** -/ theorem erdos_szekeres {X : Type*} [linear_order X] (A : list X) (r s : ℕ) (h : (r-1)*(s-1) < A.length) : (∃ (R : list X), R <+ A ∧ R.length = r ∧ R.pairwise (≤)) ∨ (∃ (S : list X), S <+ A ∧ S.length = s ∧ S.pairwise (≥)) := begin by_cases hr : (1 ≤ r), by_cases hs : (1 ≤ s), -- We assume the sequences don't exist. { by_contradiction, simp only [not_or_distrib, not_exists] at h, cases h, -- Label each number nᵢ in the sequence with the pair (aᵢ, bᵢ), where aᵢ is -- the length of the longest monotonically increasing subsequence ending with -- nᵢ and bᵢ is the length of the longest monotonically decreasing subsequence -- ending with nᵢ let f := (λ (i : (fin (A.length))), ((subsequences_ending i.2 (≤)).to_finset.sup list.length, (subsequences_ending i.2 (≥)).to_finset.sup list.length) ), let B := (list.fin_range A.length).map f, have aaaa: B.length = (list.fin_range A.length).length := by {dsimp [B], exact list.length_map f (list.fin_range (A.length)), }, have se: A.length = B.length := (finset.card_fin A.length).symm.trans aaaa.symm, -- Each two numbers in the sequence are labeled with a different pair have B_nodup : B.nodup, { unfold list.nodup, apply list.pairwise_iff_nth_le.mpr, intros ii jj hhj hh2, let bi := B.nth_le ii (lt_trans hh2 hhj), let bj := B.nth_le jj hhj, have hhi : ii < B.length := lt_trans hh2 hhj, have hhia : ii < A.length := by {rw se, exact hhi}, have hhja : jj < A.length := by {rw se, exact hhj}, have hhfi : ii < (list.fin_range A.length).length := by {rw [ list.length_fin_range, se ], exact hhi,}, have hhfj : jj < (list.fin_range A.length).length := by {rw [ list.length_fin_range, se ], exact hhj,}, apply (prod_ne_iff_right_or_left_ne bi bj).mp, dsimp [bj, bi], by_cases lt_ind : (A.nth_le ii hhia ≤ A.nth_le jj hhja), refine or.inl _, rotate, refine or.inr _, all_goals { refine ne_of_lt _, rw [list.nth_le_map _ hhj hhfj, list.nth_le_map _ hhi hhfi], simp only [list.nth_le_fin_range], }, exact subsequences_ending_increasing hhia hhja hh2 (≥) (@ge_trans X _) (le_of_not_ge lt_ind), exact subsequences_ending_increasing hhia hhja hh2 (≤) preorder.le_trans lt_ind, }, let values : finset (ℕ × ℕ) := ⟨↑B, B_nodup⟩, have v_card : values.card = A.length := eq.symm se, let poss_values : finset (ℕ × ℕ) := finset.product ((finset.range r) \ {0}) ((finset.range s) \ {0}), have pv_card: poss_values.card = (r-1)*(s-1), { rw [finset.card_product, ←finset.range_one, finset.card_sdiff (finset.range_subset.mpr hr), finset.card_sdiff (finset.range_subset.mpr hs)], repeat { rw finset.card_range, }, }, have hc : poss_values.card < values.card := by {rw [v_card, pv_card], exact h, }, -- But there are only (r − 1)(s − 1) possible labels if aᵢ is at most r − 1 and bᵢ is at most s − 1 have incl : ∀ x ∈ values, x ∈ poss_values, { intros xx xx_in_ttt, apply finset.mem_product.mpr, obtain ⟨xx_ind, _, uuuu⟩ := list.mem_map.mp (finset.mem_def.mp xx_in_ttt), rw ←uuuu, split, { exact subsequences_ending_image xx_ind.2 r (≤) preorder.le_trans h_left }, { exact subsequences_ending_image xx_ind.2 s (≥) (@ge_trans X _) h_right }, }, -- By the pigeonhole principle, two pairs must have the same value to fit in the range. obtain ⟨x, _, y, _, h⟩ := @finset.exists_ne_map_eq_of_card_lt_of_maps_to _ _ _ _ hc id incl, -- Contradiction exact (not_and_self (x = y)).mp h, }, -- Special cases when s=0 ... { have s_eq_zero : s = 0, { linarith }, refine or.inr (exists.intro list.nil _), rw s_eq_zero, exact ⟨list.nil_sublist A, rfl, list.pairwise.nil⟩, }, -- ... or r=0 { have r_eq_zero : r = 0, { linarith }, refine or.inl (exists.intro list.nil _), rw r_eq_zero, exact ⟨list.nil_sublist A, rfl, list.pairwise.nil⟩, } end theorem erdos_szekeres' {X : Type*} [linear_order X] (A : list X) : ∃ (R : list X), R <+ A ∧ R.length = A.length.sqrt ∧ (R.pairwise (≤) ∨ R.pairwise (≥)) := begin let l := A.length.sqrt, by_cases h : 1 ≤ A.length, { have one_le2 : A.length.sqrt ≠ 0 := mt (nat.sqrt_eq_zero).mp (ne_of_gt h), have leee := calc (A.length.sqrt - 1) * (A.length.sqrt - 1) ≤ A.length.sqrt * (A.length.sqrt - 1) : nat_mul_sub_left_le A.length.sqrt (A.length.sqrt - 1) ... < A.length.sqrt * A.length.sqrt : nat_mul_sub_right_lt one_le2 one_le2 ... ≤ A.length : (list.length A).sqrt_le, have list_erdos := erdos_szekeres A (A.length.sqrt) (A.length.sqrt) leee, cases list_erdos, { obtain ⟨R, rl, rp, pw⟩ := list_erdos, exact ⟨R, rl, rp, (or.inl pw)⟩, }, { obtain ⟨R, rl, rp, pw⟩ := list_erdos, exact ⟨R, rl, rp, (or.inr pw)⟩, }, }, { have len_eq_zero : A.length = 0 := by omega, rw (nat.sqrt_eq_zero.mpr len_eq_zero), exact ⟨list.nil, (list.nil_sublist A), (list.length_eq_zero.mpr rfl), (or.inl list.pairwise.nil)⟩, } end theorem finset_from_list_properties {X Y: Type*} [linear_order X] (A : finset X) (r : ℕ) (r1 : Y → Y → Prop) (r1_refl : reflexive r1) (f : X → Y) (cses : ∃ (Rl : list Y), Rl <+ (A.sort (≤)).map f ∧ Rl.length = r ∧ list.pairwise r1 Rl) : ∃ R ⊆ A, R.card = r ∧ ∀ (x ∈ R) (y ∈ R), x ≤ y → r1 (f x) (f y) := begin let li := (A.sort (≤)).map f, have bef_sorted := finset.sort_sorted (≤) A, have bef_nodup := finset.sort_nodup (≤) A, obtain ⟨r_list, r_list_sub, r_list_len, r_list_pairwise⟩ := cses, obtain ⟨bef_sub, bef_sub_sub, bef_sub_map_eq_r_list⟩ := sublist_map_exists r_list_sub, have bef_sub_sorted := list.pairwise_of_sublist bef_sub_sub bef_sorted, have bef_sub_nodup := list.nodup_of_sublist bef_sub_sub bef_nodup, have yeppers := finset_sort_idempotent bef_sub_sorted bef_sub_nodup, let bef_sub_set := bef_sub.to_finset, have bef_sub_set_sub : bef_sub_set ⊆ A, { intros _ xx_in, refine (finset.mem_sort (≤)).mp _, refine list.subset_def.mp (list.sublist.subset bef_sub_sub) _, exact list.mem_to_finset.mp xx_in, }, have len : bef_sub_set.card = r, { rw [←r_list_len, ←bef_sub_map_eq_r_list, bef_sub.length_map f, ←yeppers], exact (finset.length_sort (≤)).symm, }, refine ⟨bef_sub_set, bef_sub_set_sub, len, _⟩, { intros xx xx_in yy yy_in xx_le_yy, have xx_in' : xx ∈ bef_sub := list.mem_to_finset.mp xx_in, have yy_in' : yy ∈ bef_sub := list.mem_to_finset.mp yy_in, rw ←bef_sub_map_eq_r_list at r_list_pairwise, exact @pair_from_pairwise_to_pair_from_map X Y bef_sub f (≤) (@le_antisymm X _) r1 r1_refl bef_sub_sorted r_list_pairwise _ _ xx_in' yy_in' xx_le_yy, }, end /- An indexed version of Erdős–Szekeres theorem -/ theorem erdos_szekeres'' {X Y: Type*} [linear_order X] [linear_order Y] (r s : ℕ) (A : finset X) (h : (r-1)*(s-1) < A.card) (f : X → Y) : (∃ R ⊆ A, R.card = r ∧ ∀ (x ∈ R) (y ∈ R), x ≤ y → f x ≤ f y) ∨ (∃ S ⊆ A, S.card = s ∧ ∀ (x ∈ S) (y ∈ S), x ≤ y → f y ≤ f x) := begin let li := (A.sort (≤)).map f, have ye : (r - 1) * (s - 1) < li.length := by { rw [list.length_map, finset.length_sort], exact h, }, have cses := erdos_szekeres li r s ye, cases cses, { exact or.inl (finset_from_list_properties A r (≤) (@le_rfl Y _) f cses), }, { exact or.inr (finset_from_list_properties A s (≥) (@le_rfl Y _) f cses), }, end
0a298fc939d4e17ac5ebe3bf281f3cfb08192e5f
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/analysis/normed_space/euclidean_dist.lean
639ccda548cd942b8c7e088bcb0c868cf4683852
[ "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
4,627
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.normed_space.inner_product /-! # Euclidean distance on a finite dimensional space When we define a smooth bump function on a normed space, it is useful to have a smooth distance on the space. Since the default distance is not guaranteed to be smooth, we define `to_euclidean` to be an equivalence between a finite dimensional normed space and the standard Euclidean space of the same dimension. Then we define `euclidean.dist x y = dist (to_euclidean x) (to_euclidean y)` and provide some definitions (`euclidean.ball`, `euclidean.closed_ball`) and simple lemmas about this distance. This way we hide the usage of `to_euclidean` behind an API. -/ open_locale topological_space open set variables {E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] noncomputable theory /-- If `E` is a finite dimensional space over `ℝ`, then `to_euclidean` is a continuous `ℝ`-linear equivalence between `E` and the Euclidean space of the same dimension. -/ def to_euclidean : E ≃L[ℝ] euclidean_space ℝ (fin $ finite_dimensional.findim ℝ E) := continuous_linear_equiv.of_findim_eq findim_euclidean_space_fin.symm namespace euclidean /-- If `x` and `y` are two points in a finite dimensional space over `ℝ`, then `euclidean.dist x y` is the distance between these points in the metric defined by some inner product space structure on `E`. -/ def dist (x y : E) : ℝ := dist (to_euclidean x) (to_euclidean y) /-- Closed ball w.r.t. the euclidean distance. -/ def closed_ball (x : E) (r : ℝ) : set E := {y | dist y x ≤ r} /-- Open ball w.r.t. the euclidean distance. -/ def ball (x : E) (r : ℝ) : set E := {y | dist y x < r} lemma ball_eq_preimage (x : E) (r : ℝ) : ball x r = to_euclidean ⁻¹' (metric.ball (to_euclidean x) r) := rfl lemma closed_ball_eq_preimage (x : E) (r : ℝ) : closed_ball x r = to_euclidean ⁻¹' (metric.closed_ball (to_euclidean x) r) := rfl lemma ball_subset_closed_ball {x : E} {r : ℝ} : ball x r ⊆ closed_ball x r := λ y (hy : _ < _), le_of_lt hy lemma is_open_ball {x : E} {r : ℝ} : is_open (ball x r) := metric.is_open_ball.preimage to_euclidean.continuous lemma mem_ball_self {x : E} {r : ℝ} (hr : 0 < r) : x ∈ ball x r := metric.mem_ball_self hr lemma closed_ball_eq_image (x : E) (r : ℝ) : closed_ball x r = to_euclidean.symm '' metric.closed_ball (to_euclidean x) r := by rw [to_euclidean.image_symm_eq_preimage, closed_ball_eq_preimage] lemma compact_ball {x : E} {r : ℝ} : is_compact (closed_ball x r) := begin rw closed_ball_eq_image, exact (proper_space.compact_ball _ _).image to_euclidean.symm.continuous end lemma is_closed_closed_ball {x : E} {r : ℝ} : is_closed (closed_ball x r) := compact_ball.is_closed lemma closure_ball (x : E) {r : ℝ} (h : 0 < r) : closure (ball x r) = closed_ball x r := by rw [ball_eq_preimage, ← to_euclidean.preimage_closure, closure_ball (to_euclidean x) h, closed_ball_eq_preimage] lemma exists_pos_lt_subset_ball {R : ℝ} {s : set E} {x : E} (hR : 0 < R) (hs : is_closed s) (h : s ⊆ ball x R) : ∃ r ∈ Ioo 0 R, s ⊆ ball x r := begin rw [ball_eq_preimage, ← image_subset_iff] at h, rcases exists_pos_lt_subset_ball hR (to_euclidean.is_closed_image.2 hs) h with ⟨r, hr, hsr⟩, exact ⟨r, hr, image_subset_iff.1 hsr⟩ end lemma nhds_basis_closed_ball {x : E} : (𝓝 x).has_basis (λ r : ℝ, 0 < r) (closed_ball x) := begin rw [to_euclidean.to_homeomorph.nhds_eq_comap], exact metric.nhds_basis_closed_ball.comap _ end lemma closed_ball_mem_nhds {x : E} {r : ℝ} (hr : 0 < r) : closed_ball x r ∈ 𝓝 x := nhds_basis_closed_ball.mem_of_mem hr lemma nhds_basis_ball {x : E} : (𝓝 x).has_basis (λ r : ℝ, 0 < r) (ball x) := begin rw [to_euclidean.to_homeomorph.nhds_eq_comap], exact metric.nhds_basis_ball.comap _ end lemma ball_mem_nhds {x : E} {r : ℝ} (hr : 0 < r) : ball x r ∈ 𝓝 x := nhds_basis_ball.mem_of_mem hr end euclidean variables {F : Type*} [normed_group F] [normed_space ℝ F] {f g : F → E} {n : with_top ℕ} lemma times_cont_diff.euclidean_dist (hf : times_cont_diff ℝ n f) (hg : times_cont_diff ℝ n g) (h : ∀ x, f x ≠ g x) : times_cont_diff ℝ n (λ x, euclidean.dist (f x) (g x)) := begin simp only [euclidean.dist], apply @times_cont_diff.dist ℝ, exacts [(@to_euclidean E _ _ _).times_cont_diff.comp hf, (@to_euclidean E _ _ _).times_cont_diff.comp hg, λ x, to_euclidean.injective.ne (h x)] end
e4dd6fa758a1e26c2b6497bf30ab5d04bab8847d
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/measure_theory/probability_mass_function.lean
21cdbcdb0b77b0b238e315055b48dcaac05ce218
[ "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
21,028
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import topology.instances.ennreal import measure_theory.measure.measure_space /-! # Probability mass functions This file is about probability mass functions or discrete probability measures: a function `α → ℝ≥0` such that the values have (infinite) sum `1`. This file features the monadic structure of `pmf` and the Bernoulli distribution Given `p : pmf α`, `pmf.to_outer_measure` constructs an `outer_measure` on `α`, by assigning each set the sum of the probabilities of each of its elements. Under this outer measure, every set is Carathéodory-measurable, so we can further extend this to a `measure` on `α`, see `pmf.to_measure`. `pmf.to_measure.is_probability_measure` shows this associated measure is a probability measure. ## Tags probability mass function, discrete probability measure, bernoulli distribution -/ noncomputable theory variables {α : Type*} {β : Type*} {γ : Type*} open_locale classical big_operators nnreal ennreal /-- A probability mass function, or discrete probability measures is a function `α → ℝ≥0` such that the values have (infinite) sum `1`. -/ def {u} pmf (α : Type u) : Type u := { f : α → ℝ≥0 // has_sum f 1 } namespace pmf instance : has_coe_to_fun (pmf α) (λ p, α → ℝ≥0) := ⟨λ p a, p.1 a⟩ @[ext] protected lemma ext : ∀ {p q : pmf α}, (∀ a, p a = q a) → p = q | ⟨f, hf⟩ ⟨g, hg⟩ eq := subtype.eq $ funext eq lemma has_sum_coe_one (p : pmf α) : has_sum p 1 := p.2 lemma summable_coe (p : pmf α) : summable p := (p.has_sum_coe_one).summable @[simp] lemma tsum_coe (p : pmf α) : ∑' a, p a = 1 := p.has_sum_coe_one.tsum_eq /-- The support of a `pmf` is the set where it is nonzero. -/ def support (p : pmf α) : set α := function.support p @[simp] lemma mem_support_iff (p : pmf α) (a : α) : a ∈ p.support ↔ p a ≠ 0 := iff.rfl lemma coe_le_one (p : pmf α) (a : α) : p a ≤ 1 := has_sum_le (by { intro b, split_ifs; simp only [h, zero_le'] }) (has_sum_ite_eq a (p a)) (has_sum_coe_one p) section pure /-- The pure `pmf` is the `pmf` where all the mass lies in one point. The value of `pure a` is `1` at `a` and `0` elsewhere. -/ def pure (a : α) : pmf α := ⟨λ a', if a' = a then 1 else 0, has_sum_ite_eq _ _⟩ @[simp] lemma pure_apply (a a' : α) : pure a a' = (if a' = a then 1 else 0) := rfl lemma mem_support_pure_iff (a a' : α) : a' ∈ (pure a).support ↔ a' = a := by simp instance [inhabited α] : inhabited (pmf α) := ⟨pure (default α)⟩ end pure section bind protected lemma bind.summable (p : pmf α) (f : α → pmf β) (b : β) : summable (λ a : α, p a * f a b) := begin refine nnreal.summable_of_le (assume a, _) p.summable_coe, suffices : p a * f a b ≤ p a * 1, { simpa }, exact mul_le_mul_of_nonneg_left ((f a).coe_le_one _) (p a).2 end /-- The monadic bind operation for `pmf`. -/ def bind (p : pmf α) (f : α → pmf β) : pmf β := ⟨λ b, ∑'a, p a * f a b, begin apply ennreal.has_sum_coe.1, simp only [ennreal.coe_tsum (bind.summable p f _)], rw [ennreal.summable.has_sum_iff, ennreal.tsum_comm], simp [ennreal.tsum_mul_left, (ennreal.coe_tsum (f _).summable_coe).symm, (ennreal.coe_tsum p.summable_coe).symm] end⟩ @[simp] lemma bind_apply (p : pmf α) (f : α → pmf β) (b : β) : p.bind f b = ∑'a, p a * f a b := rfl lemma coe_bind_apply (p : pmf α) (f : α → pmf β) (b : β) : (p.bind f b : ℝ≥0∞) = ∑'a, p a * f a b := eq.trans (ennreal.coe_tsum $ bind.summable p f b) $ by simp @[simp] lemma pure_bind (a : α) (f : α → pmf β) : (pure a).bind f = f a := have ∀ b a', ite (a' = a) 1 0 * f a' b = ite (a' = a) (f a b) 0, from assume b a', by split_ifs; simp; subst h; simp, by ext b; simp [this] @[simp] lemma bind_pure (p : pmf α) : p.bind pure = p := have ∀ a a', (p a * ite (a' = a) 1 0) = ite (a = a') (p a') 0, from assume a a', begin split_ifs; try { subst a }; try { subst a' }; simp * at * end, by ext b; simp [this] @[simp] lemma bind_bind (p : pmf α) (f : α → pmf β) (g : β → pmf γ) : (p.bind f).bind g = p.bind (λ a, (f a).bind g) := begin ext1 b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end lemma bind_comm (p : pmf α) (q : pmf β) (f : α → β → pmf γ) : p.bind (λ a, q.bind (f a)) = q.bind (λ b, p.bind (λ a, f a b)) := begin ext1 b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end end bind section bind_on_support protected lemma bind_on_support.summable (p : pmf α) (f : ∀ a ∈ p.support, pmf β) (b : β) : summable (λ a : α, p a * if h : p a = 0 then 0 else f a h b) := begin refine nnreal.summable_of_le (assume a, _) p.summable_coe, split_ifs, { refine (mul_zero (p a)).symm ▸ le_of_eq h.symm }, { suffices : p a * f a h b ≤ p a * 1, { simpa }, exact mul_le_mul_of_nonneg_left ((f a h).coe_le_one _) (p a).2 } end /-- Generalized version of `bind` allowing `f` to only be defined on the support of `p`. `p.bind f` is equivalent to `p.bind_on_support (λ a _, f a)`, see `bind_on_support_eq_bind` -/ def bind_on_support (p : pmf α) (f : ∀ a ∈ p.support, pmf β) : pmf β := ⟨λ b, ∑' a, p a * if h : p a = 0 then 0 else f a h b, ennreal.has_sum_coe.1 begin simp only [ennreal.coe_tsum (bind_on_support.summable p f _)], rw [ennreal.summable.has_sum_iff, ennreal.tsum_comm], simp only [ennreal.coe_mul, ennreal.coe_one, ennreal.tsum_mul_left], have : ∑' (a : α), (p a : ennreal) = 1 := by simp only [←ennreal.coe_tsum p.summable_coe, ennreal.coe_one, tsum_coe], refine trans (tsum_congr (λ a, _)) this, split_ifs with h, { simp [h] }, { simp [← ennreal.coe_tsum (f a h).summable_coe, (f a h).tsum_coe] } end⟩ @[simp] lemma bind_on_support_apply (p : pmf α) (f : ∀ a ∈ p.support, pmf β) (b : β) : p.bind_on_support f b = ∑' a, p a * if h : p a = 0 then 0 else f a h b := rfl /-- `bind_on_support` reduces to `bind` if `f` doesn't depend on the additional hypothesis -/ @[simp] lemma bind_on_support_eq_bind (p : pmf α) (f : α → pmf β) : p.bind_on_support (λ a _, f a) = p.bind f := begin ext b, simp only [p.bind_on_support_apply (λ a _, f a), p.bind_apply f, dite_eq_ite, nnreal.coe_eq, mul_ite, mul_zero], refine congr_arg _ (funext (λ a, _)), split_ifs with h; simp [h], end lemma coe_bind_on_support_apply (p : pmf α) (f : ∀ a ∈ p.support, pmf β) (b : β) : (p.bind_on_support f b : ℝ≥0∞) = ∑' a, p a * if h : p a = 0 then 0 else f a h b := by simp only [bind_on_support_apply, ennreal.coe_tsum (bind_on_support.summable p f b), dite_cast, ennreal.coe_mul, ennreal.coe_zero] @[simp] lemma mem_support_bind_on_support_iff (p : pmf α) (f : ∀ a ∈ p.support, pmf β) (b : β) : b ∈ (p.bind_on_support f).support ↔ ∃ a (ha : p a ≠ 0), b ∈ (f a ha).support := begin simp only [mem_support_iff, bind_on_support_apply, tsum_ne_zero_iff (bind_on_support.summable p f b), mul_ne_zero_iff], split; { rintro ⟨a, ha, haf⟩, refine ⟨a, ha, ne_of_eq_of_ne _ haf⟩, simp [ha], }, end lemma bind_on_support_eq_zero_iff (p : pmf α) (f : ∀ a ∈ p.support, pmf β) (b : β) : p.bind_on_support f b = 0 ↔ ∀ a (ha : p a ≠ 0), f a ha b = 0 := begin simp only [bind_on_support_apply, tsum_eq_zero_iff (bind_on_support.summable p f b), mul_eq_zero, or_iff_not_imp_left], exact ⟨λ h a ha, trans (dif_neg ha).symm (h a ha), λ h a ha, trans (dif_neg ha) (h a ha)⟩, end @[simp] lemma pure_bind_on_support (a : α) (f : ∀ (a' : α) (ha : a' ∈ (pure a).support), pmf β) : (pure a).bind_on_support f = f a ((mem_support_pure_iff a a).mpr rfl) := begin refine pmf.ext (λ b, _), simp only [nnreal.coe_eq, bind_on_support_apply, pure_apply], refine trans (tsum_congr (λ a', _)) (tsum_ite_eq a _), by_cases h : (a' = a); simp [h], end lemma bind_on_support_pure (p : pmf α) : p.bind_on_support (λ a _, pure a) = p := by simp only [pmf.bind_pure, pmf.bind_on_support_eq_bind] @[simp] lemma bind_on_support_bind_on_support (p : pmf α) (f : ∀ a ∈ p.support, pmf β) (g : ∀ (b ∈ (p.bind_on_support f).support), pmf γ) : (p.bind_on_support f).bind_on_support g = p.bind_on_support (λ a ha, (f a ha).bind_on_support (λ b hb, g b ((p.mem_support_bind_on_support_iff f b).mpr ⟨a, ha, hb⟩))) := begin refine pmf.ext (λ a, _), simp only [ennreal.coe_eq_coe.symm, coe_bind_on_support_apply, ← tsum_dite_right, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], refine trans (ennreal.tsum_comm) (tsum_congr (λ a', _)), split_ifs with h, { simp only [h, ennreal.coe_zero, zero_mul, tsum_zero] }, { simp only [← ennreal.tsum_mul_left, ← mul_assoc], refine tsum_congr (λ b, _), split_ifs with h1 h2 h2, any_goals { ring1 }, { rw bind_on_support_eq_zero_iff at h1, simp only [h1 a' h, ennreal.coe_zero, zero_mul, mul_zero] }, { simp only [h2, ennreal.coe_zero, mul_zero, zero_mul] } } end lemma bind_on_support_comm (p : pmf α) (q : pmf β) (f : ∀ (a ∈ p.support) (b ∈ q.support), pmf γ) : p.bind_on_support (λ a ha, q.bind_on_support (f a ha)) = q.bind_on_support (λ b hb, p.bind_on_support (λ a ha, f a ha b hb)) := begin apply pmf.ext, rintro c, simp only [ennreal.coe_eq_coe.symm, coe_bind_on_support_apply, ← tsum_dite_right, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], refine trans (ennreal.tsum_comm) (tsum_congr (λ b, tsum_congr (λ a, _))), split_ifs with h1 h2 h2; ring, end end bind_on_support section map /-- The functorial action of a function on a `pmf`. -/ def map (f : α → β) (p : pmf α) : pmf β := bind p (pure ∘ f) lemma bind_pure_comp (f : α → β) (p : pmf α) : bind p (pure ∘ f) = map f p := rfl lemma map_id (p : pmf α) : map id p = p := by simp [map] lemma map_comp (p : pmf α) (f : α → β) (g : β → γ) : (p.map f).map g = p.map (g ∘ f) := by simp [map] lemma pure_map (a : α) (f : α → β) : (pure a).map f = pure (f a) := by simp [map] end map /-- The monadic sequencing operation for `pmf`. -/ def seq (f : pmf (α → β)) (p : pmf α) : pmf β := f.bind (λ m, p.bind $ λ a, pure (m a)) section of_finite /-- Given a finset `s` and a function `f : α → ℝ≥0` with sum `1` on `s`, such that `f x = 0` for `x ∉ s`, we get a `pmf` -/ def of_finset (f : α → ℝ≥0) (s : finset α) (h : ∑ x in s, f x = 1) (h' : ∀ x ∉ s, f x = 0) : pmf α := ⟨f, h ▸ has_sum_sum_of_ne_finset_zero h'⟩ @[simp] lemma of_finset_apply {f : α → ℝ≥0} {s : finset α} (h : ∑ x in s, f x = 1) (h' : ∀ x ∉ s, f x = 0) (a : α) : of_finset f s h h' a = f a := rfl lemma of_finset_apply_of_not_mem {f : α → ℝ≥0} {s : finset α} (h : ∑ x in s, f x = 1) (h' : ∀ x ∉ s, f x = 0) {a : α} (ha : a ∉ s) : of_finset f s h h' a = 0 := h' a ha /-- Given a finite type `α` and a function `f : α → ℝ≥0` with sum 1, we get a `pmf`. -/ def of_fintype [fintype α] (f : α → ℝ≥0) (h : ∑ x, f x = 1) : pmf α := of_finset f finset.univ h (λ x hx, absurd (finset.mem_univ x) hx) @[simp] lemma of_fintype_apply [fintype α] {f : α → ℝ≥0} (h : ∑ x, f x = 1) (a : α) : of_fintype f h a = f a := rfl /-- Given a non-empty multiset `s` we construct the `pmf` which sends `a` to the fraction of elements in `s` that are `a`. -/ def of_multiset (s : multiset α) (hs : s ≠ 0) : pmf α := ⟨λ a, s.count a / s.card, have ∑ a in s.to_finset, (s.count a : ℝ) / s.card = 1, by simp [div_eq_inv_mul, finset.mul_sum.symm, (nat.cast_sum _ _).symm, hs], have ∑ a in s.to_finset, (s.count a : ℝ≥0) / s.card = 1, by rw [← nnreal.eq_iff, nnreal.coe_one, ← this, nnreal.coe_sum]; simp, begin rw ← this, apply has_sum_sum_of_ne_finset_zero, simp {contextual := tt}, end⟩ @[simp] lemma of_multiset_apply {s : multiset α} (hs : s ≠ 0) (a : α) : of_multiset s hs a = s.count a / s.card := rfl lemma of_multiset_apply_of_not_mem {s : multiset α} (hs : s ≠ 0) {a : α} (ha : a ∉ s) : of_multiset s hs a = 0 := div_eq_zero_iff.2 (or.inl $ nat.cast_eq_zero.2 $ multiset.count_eq_zero_of_not_mem ha) end of_finite section uniform /-- Uniform distribution taking the same non-zero probability on the nonempty finset `s` -/ def uniform_of_finset (s : finset α) (hs : s.nonempty) : pmf α := of_finset (λ a, if a ∈ s then (s.card : ℝ≥0)⁻¹ else 0) s (Exists.rec_on hs (λ x hx, calc ∑ (a : α) in s, ite (a ∈ s) (s.card : ℝ≥0)⁻¹ 0 = ∑ (a : α) in s, (s.card : ℝ≥0)⁻¹ : finset.sum_congr rfl (λ x hx, by simp [hx]) ... = s.card • (s.card : ℝ≥0)⁻¹ : finset.sum_const _ ... = (s.card : ℝ≥0) * (s.card : ℝ≥0)⁻¹ : by rw nsmul_eq_mul ... = 1 : div_self (nat.cast_ne_zero.2 $ finset.card_ne_zero_of_mem hx) )) (λ x hx, by simp only [hx, if_false]) @[simp] lemma uniform_of_finset_apply {s : finset α} (hs : s.nonempty) (a : α) : uniform_of_finset s hs a = if a ∈ s then (s.card : ℝ≥0)⁻¹ else 0 := rfl lemma uniform_of_finset_apply_of_mem {s : finset α} (hs : s.nonempty) {a : α} (ha : a ∈ s) : uniform_of_finset s hs a = (s.card)⁻¹ := by simp [ha] lemma uniform_of_finset_apply_of_not_mem {s : finset α} (hs : s.nonempty) {a : α} (ha : a ∉ s) : uniform_of_finset s hs a = 0 := by simp [ha] /-- The uniform pmf taking the same uniform value on all of the fintype `α` -/ def uniform_of_fintype (α : Type*) [fintype α] [nonempty α] : pmf α := uniform_of_finset (finset.univ) (finset.univ_nonempty) @[simp] lemma uniform_of_fintype_apply [fintype α] [nonempty α] (a : α) : uniform_of_fintype α a = (fintype.card α)⁻¹ := by simpa only [uniform_of_fintype, finset.mem_univ, if_true, uniform_of_finset_apply] end uniform /-- Given a `f` with non-zero sum, we get a `pmf` by normalizing `f` by it's `tsum` -/ def normalize (f : α → ℝ≥0) (hf0 : tsum f ≠ 0) : pmf α := ⟨λ a, f a * (∑' x, f x)⁻¹, (mul_inv_cancel hf0) ▸ has_sum.mul_right (∑' x, f x)⁻¹ (not_not.mp (mt tsum_eq_zero_of_not_summable hf0 : ¬¬summable f)).has_sum⟩ lemma normalize_apply {f : α → ℝ≥0} (hf0 : tsum f ≠ 0) (a : α) : (normalize f hf0) a = f a * (∑' x, f x)⁻¹ := rfl section filter /-- Create new `pmf` by filtering on a set with non-zero measure and normalizing -/ def filter (p : pmf α) (s : set α) (h : ∃ a ∈ s, p a ≠ 0) : pmf α := pmf.normalize (s.indicator p) $ nnreal.tsum_indicator_ne_zero p.2.summable h lemma filter_apply (p : pmf α) {s : set α} (h : ∃ a ∈ s, p a ≠ 0) {a : α} : (p.filter s h) a = (s.indicator p a) * (∑' x, (s.indicator p) x)⁻¹ := by rw [filter, normalize_apply] lemma filter_apply_eq_zero_of_not_mem (p : pmf α) {s : set α} (h : ∃ a ∈ s, p a ≠ 0) {a : α} (ha : a ∉ s) : (p.filter s h) a = 0 := by rw [filter_apply, set.indicator_apply_eq_zero.mpr (λ ha', absurd ha' ha), zero_mul] lemma filter_apply_eq_zero_iff (p : pmf α) {s : set α} (h : ∃ a ∈ s, p a ≠ 0) (a : α) : (p.filter s h) a = 0 ↔ a ∉ (p.support ∩ s) := begin rw [set.mem_inter_iff, p.mem_support_iff, not_and_distrib, not_not], split; intro ha, { rw [filter_apply, mul_eq_zero] at ha, refine ha.by_cases (λ ha, (em (a ∈ s)).by_cases (λ h, or.inl ((set.indicator_apply_eq_zero.mp ha) h)) or.inr) (λ ha, absurd (inv_eq_zero.1 ha) (nnreal.tsum_indicator_ne_zero p.2.summable h)) }, { rw [filter_apply, set.indicator_apply_eq_zero.2 (λ h, ha.by_cases id (absurd h)), zero_mul] } end lemma filter_apply_ne_zero_iff (p : pmf α) {s : set α} (h : ∃ a ∈ s, p a ≠ 0) (a : α) : (p.filter s h) a ≠ 0 ↔ a ∈ (p.support ∩ s) := by rw [← not_iff, filter_apply_eq_zero_iff, not_iff, not_not] end filter section bernoulli /-- A `pmf` which assigns probability `p` to `tt` and `1 - p` to `ff`. -/ def bernoulli (p : ℝ≥0) (h : p ≤ 1) : pmf bool := of_fintype (λ b, cond b p (1 - p)) (nnreal.eq $ by simp [h]) @[simp] lemma bernuolli_apply {p : ℝ≥0} (h : p ≤ 1) (b : bool) : bernoulli p h b = cond b p (1 - p) := rfl end bernoulli section outer_measure open measure_theory measure_theory.outer_measure /-- Construct an `outer_measure` from a `pmf`, by assigning measure to each set `s : set α` equal to the sum of `p x` for for each `x ∈ α` -/ def to_outer_measure (p : pmf α) : outer_measure α := outer_measure.sum (λ (x : α), p x • dirac x) lemma to_outer_measure_apply (p : pmf α) (s : set α) : p.to_outer_measure s = ∑' x, s.indicator (λ x, (p x : ℝ≥0∞)) x := tsum_congr (λ x, smul_dirac_apply (p x) x s) lemma to_outer_measure_apply' (p : pmf α) (s : set α) : p.to_outer_measure s = ↑(∑' (x : α), s.indicator p x) := by simp only [ennreal.coe_tsum (nnreal.indicator_summable (summable_coe p) s), ennreal.coe_indicator, to_outer_measure_apply] @[simp] lemma to_outer_measure_apply_finset (p : pmf α) (s : finset α) : p.to_outer_measure s = ∑ x in s, (p x : ℝ≥0∞) := begin refine (to_outer_measure_apply p s).trans ((@tsum_eq_sum _ _ _ _ _ _ s _).trans _), { exact λ x hx, set.indicator_of_not_mem hx _ }, { exact finset.sum_congr rfl (λ x hx, set.indicator_of_mem hx _) } end @[simp] lemma to_outer_measure_apply_fintype [fintype α] (p : pmf α) (s : set α) : p.to_outer_measure s = ∑ x, (s.indicator (λ x, (p x : ℝ≥0∞)) x) := (p.to_outer_measure_apply s).trans (tsum_eq_sum (λ x h, absurd (finset.mem_univ x) h)) lemma to_outer_measure_apply_eq_zero_iff (p : pmf α) (s : set α) : p.to_outer_measure s = 0 ↔ disjoint p.support s := begin rw [to_outer_measure_apply', ennreal.coe_eq_zero, tsum_eq_zero_iff (nnreal.indicator_summable (summable_coe p) s)], exact function.funext_iff.symm.trans set.indicator_eq_zero', end @[simp] lemma to_outer_measure_caratheodory (p : pmf α) : (to_outer_measure p).caratheodory = ⊤ := begin refine (eq_top_iff.2 $ le_trans (le_Inf $ λ x hx, _) (le_sum_caratheodory _)), obtain ⟨y, hy⟩ := hx, exact ((le_of_eq (dirac_caratheodory _).symm).trans (le_smul_caratheodory _ _)).trans (le_of_eq hy), end end outer_measure section measure open measure_theory /-- Since every set is Carathéodory-measurable under `pmf.to_outer_measure`, we can further extend this `outer_measure` to a `measure` on `α` -/ def to_measure [measurable_space α] (p : pmf α) : measure α := p.to_outer_measure.to_measure ((to_outer_measure_caratheodory p).symm ▸ le_top) variables [measurable_space α] lemma to_measure_apply_eq_to_outer_measure_apply (p : pmf α) (s : set α) (hs : measurable_set s) : p.to_measure s = p.to_outer_measure s := to_measure_apply p.to_outer_measure _ hs lemma to_outer_measure_apply_le_to_measure_apply (p : pmf α) (s : set α) : p.to_outer_measure s ≤ p.to_measure s := le_to_measure_apply p.to_outer_measure _ s lemma to_measure_apply (p : pmf α) (s : set α) (hs : measurable_set s) : p.to_measure s = ∑' x, s.indicator (λ x, (p x : ℝ≥0∞)) x := (p.to_measure_apply_eq_to_outer_measure_apply s hs).trans (p.to_outer_measure_apply s) lemma to_measure_apply' (p : pmf α) (s : set α) (hs : measurable_set s) : p.to_measure s = ↑(∑' x, s.indicator p x) := (p.to_measure_apply_eq_to_outer_measure_apply s hs).trans (p.to_outer_measure_apply' s) @[simp] lemma to_measure_apply_finset [measurable_singleton_class α] (p : pmf α) (s : finset α) : p.to_measure s = ∑ x in s, (p x : ℝ≥0∞) := (p.to_measure_apply_eq_to_outer_measure_apply s s.measurable_set).trans (p.to_outer_measure_apply_finset s) lemma to_measure_apply_of_finite [measurable_singleton_class α] (p : pmf α) (s : set α) (hs : s.finite) : p.to_measure s = ∑' x, s.indicator (λ x, (p x : ℝ≥0∞)) x := (p.to_measure_apply_eq_to_outer_measure_apply s hs.measurable_set).trans (p.to_outer_measure_apply s) @[simp] lemma to_measure_apply_fintype [measurable_singleton_class α] [fintype α] (p : pmf α) (s : set α) : p.to_measure s = ∑ x, s.indicator (λ x, (p x : ℝ≥0∞)) x := (p.to_measure_apply_eq_to_outer_measure_apply s (set.finite.of_fintype s).measurable_set).trans (p.to_outer_measure_apply_fintype s) /-- The measure associated to a `pmf` by `to_measure` is a probability measure -/ instance to_measure.is_probability_measure (p : pmf α) : is_probability_measure (p.to_measure) := ⟨by simpa only [measurable_set.univ, to_measure_apply_eq_to_outer_measure_apply, set.indicator_univ, to_outer_measure_apply', ennreal.coe_eq_one] using tsum_coe p⟩ end measure end pmf
29e04f437dd7e87af92807b69a08573bd88df7da
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/polynomial/field_division.lean
0ccf6d01b6bd0cbe7be5075a477ff301e1ff6fa8
[ "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
19,578
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.derivative import data.polynomial.ring_division import ring_theory.euclidean_domain /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory open_locale classical big_operators polynomial namespace polynomial universes u v w y z variables {R : Type u} {S : Type v} {k : Type y} {A : Type z} {a b : R} {n : ℕ} section is_domain variables [comm_ring R] [is_domain R] lemma derivative_root_multiplicity_of_root [char_zero R] {p : R[X]} {t : R} (hpt : p.is_root t) : p.derivative.root_multiplicity t = p.root_multiplicity t - 1 := begin rcases eq_or_ne p 0 with rfl | hp, { simp }, nth_rewrite 0 [←p.div_by_monic_mul_pow_root_multiplicity_eq t], simp only [derivative_pow, derivative_mul, derivative_sub, derivative_X, derivative_C, sub_zero, mul_one], set n := p.root_multiplicity t - 1, have hn : n + 1 = _ := tsub_add_cancel_of_le ((root_multiplicity_pos hp).mpr hpt), rw ←hn, set q := p /ₘ (X - C t) ^ (n + 1) with hq, convert_to root_multiplicity t ((X - C t) ^ n * (derivative q * (X - C t) + q * ↑(n + 1))) = n, { congr, rw [mul_add, mul_left_comm $ (X - C t) ^ n, ←pow_succ'], congr' 1, rw [mul_left_comm $ (X - C t) ^ n, mul_comm $ (X - C t) ^ n] }, have h : (derivative q * (X - C t) + q * ↑(n + 1)).eval t ≠ 0, { suffices : eval t q * ↑(n + 1) ≠ 0, { simpa }, refine mul_ne_zero _ (nat.cast_ne_zero.mpr n.succ_ne_zero), convert eval_div_by_monic_pow_root_multiplicity_ne_zero t hp, exact hn ▸ hq }, rw [root_multiplicity_mul, root_multiplicity_X_sub_C_pow, root_multiplicity_eq_zero h, add_zero], refine mul_ne_zero (pow_ne_zero n $ X_sub_C_ne_zero t) _, contrapose! h, rw [h, eval_zero] end lemma root_multiplicity_sub_one_le_derivative_root_multiplicity [char_zero R] (p : R[X]) (t : R) : p.root_multiplicity t - 1 ≤ p.derivative.root_multiplicity t := begin by_cases p.is_root t, { exact (derivative_root_multiplicity_of_root h).symm.le }, { rw [root_multiplicity_eq_zero h, zero_tsub], exact zero_le _ } end section normalization_monoid variables [normalization_monoid R] instance : normalization_monoid R[X] := { norm_unit := λ p, ⟨C ↑(norm_unit (p.leading_coeff)), C ↑(norm_unit (p.leading_coeff))⁻¹, by rw [← ring_hom.map_mul, units.mul_inv, C_1], by rw [← ring_hom.map_mul, units.inv_mul, C_1]⟩, norm_unit_zero := units.ext (by simp), norm_unit_mul := λ p q hp0 hq0, units.ext (begin dsimp, rw [ne.def, ← leading_coeff_eq_zero] at *, rw [leading_coeff_mul, norm_unit_mul hp0 hq0, units.coe_mul, C_mul], end), norm_unit_coe_units := λ u, units.ext begin rw [← mul_one u⁻¹, units.coe_mul, units.eq_inv_mul_iff_mul_eq], dsimp, rcases polynomial.is_unit_iff.1 ⟨u, rfl⟩ with ⟨_, ⟨w, rfl⟩, h2⟩, rw [← h2, leading_coeff_C, norm_unit_coe_units, ← C_mul, units.mul_inv, C_1], end } @[simp] lemma coe_norm_unit {p : R[X]} : (norm_unit p : R[X]) = C ↑(norm_unit p.leading_coeff) := by simp [norm_unit] lemma leading_coeff_normalize (p : R[X]) : leading_coeff (normalize p) = normalize (leading_coeff p) := by simp lemma monic.normalize_eq_self {p : R[X]} (hp : p.monic) : normalize p = p := by simp only [polynomial.coe_norm_unit, normalize_apply, hp.leading_coeff, norm_unit_one, units.coe_one, polynomial.C.map_one, mul_one] lemma roots_normalize {p : R[X]} : (normalize p).roots = p.roots := by rw [normalize_apply, mul_comm, coe_norm_unit, roots_C_mul _ (norm_unit (leading_coeff p)).ne_zero] end normalization_monoid end is_domain section division_ring variables [division_ring R] {p q : R[X]} lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := lt_of_not_ge (λ h, begin rw [eq_C_of_degree_le_zero h] at hp0 hp, exact hp (is_unit.map C (is_unit.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0)))), end) lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (p : R[X]) (h : q ≠ 0) : degree (p * C (leading_coeff q)⁻¹) = degree p := have h₁ : (leading_coeff q)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul, degree_C h₁, add_zero] @[simp] lemma map_eq_zero [semiring S] [nontrivial S] (f : R →+* S) : p.map f = 0 ↔ p = 0 := by simp only [polynomial.ext_iff, map_eq_zero, coeff_map, coeff_zero] lemma map_ne_zero [semiring S] [nontrivial S] {f : R →+* S} (hp : p ≠ 0) : p.map f ≠ 0 := mt (map_eq_zero f).1 hp end division_ring section field variables [field R] {p q : R[X]} lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 := ⟨degree_eq_zero_of_is_unit, λ h, have degree p ≤ 0, by simp [*, le_refl], have hc : coeff p 0 ≠ 0, from λ hc, by rw [eq_C_of_degree_le_zero this, hc] at h; simpa using h, is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin conv in p { rw eq_C_of_degree_le_zero this }, rw [← C_mul, _root_.mul_inv_cancel hc, C_1] end⟩⟩ /-- Division of polynomials. See `polynomial.div_by_monic` for more details.-/ def div (p q : R[X]) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) /-- Remainder of polynomial division. See `polynomial.mod_by_monic` for more details. -/ def mod (p q : R[X]) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : R[X]) : q * div p q + mod p q = p := if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : R[X]) (hq : q ≠ 0) : degree (mod p q) < degree q := by rw ← degree_mul_leading_coeff_inv q hq; exact degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) instance : has_div R[X] := ⟨div⟩ instance : has_mod R[X] := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : R[X]) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1] lemma div_by_monic_eq_div (p : R[X]) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one] lemma mod_X_sub_C_eq_C_eval (p : R[X]) (a : R) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain R[X] := { quotient := (/), quotient_zero := by simp [div_def], remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq), .. polynomial.comm_ring, .. polynomial.nontrivial } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp only [this, false_and, if_false] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv q hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv_rhs { rw [← euclidean_domain.div_add_mod p q, degree_add_eq_left_of_degree_lt this, degree_mul] } lemma degree_div_le (p q : R[X]) : degree (p / q) ≤ degree p := if hq : q = 0 then by simp [hq] else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq]; exact degree_div_by_monic_le _ _ lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq, by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0]; exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp (by rw degree_mul_leading_coeff_inv _ hq0; exact hq) @[simp] lemma degree_map [division_ring k] (p : R[X]) (f : R →+* k) : degree (p.map f) = degree p := p.degree_map_eq_of_injective f.injective @[simp] lemma nat_degree_map [division_ring k] (f : R →+* k) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map _ f) @[simp] lemma leading_coeff_map [division_ring k] (f : R →+* k) : leading_coeff (p.map f) = f (leading_coeff p) := by simp only [← coeff_nat_degree, coeff_map f, nat_degree_map] theorem monic_map_iff [division_ring k] {f : R →+* k} {p : R[X]} : (p.map f).monic ↔ p.monic := by rw [monic, leading_coeff_map, ← f.map_one, function.injective.eq_iff f.injective, monic] theorem is_unit_map [field k] (f : R →+* k) : is_unit (p.map f) ↔ is_unit p := by simp_rw [is_unit_iff_degree_eq_zero, degree_map] lemma map_div [field k] (f : R →+* k) : (p / q).map f = p.map f / q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [div_def, div_def, polynomial.map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)]; simp [coeff_map f] lemma map_mod [field k] (f : R →+* k) : (p % q).map f = p.map f % q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [mod_def, mod_def, leading_coeff_map f, ← map_inv₀ f, ← map_C f, ← polynomial.map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)] section open euclidean_domain theorem gcd_map [field k] (f : R →+* k) : gcd (p.map f) (q.map f) = (gcd p q).map f := gcd.induction p q (λ x, by simp_rw [polynomial.map_zero, euclidean_domain.gcd_zero_left]) $ λ x y hx ih, by rw [gcd_val, ← map_mod, ih, ← gcd_val] end lemma eval₂_gcd_eq_zero [comm_semiring k] {ϕ : R →+* k} {f g : R[X]} {α : k} (hf : f.eval₂ ϕ α = 0) (hg : g.eval₂ ϕ α = 0) : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 := by rw [euclidean_domain.gcd_eq_gcd_ab f g, polynomial.eval₂_add, polynomial.eval₂_mul, polynomial.eval₂_mul, hf, hg, zero_mul, zero_mul, zero_add] lemma eval_gcd_eq_zero {f g : R[X]} {α : R} (hf : f.eval α = 0) (hg : g.eval α = 0) : (euclidean_domain.gcd f g).eval α = 0 := eval₂_gcd_eq_zero hf hg lemma root_left_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : R[X]} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : f.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_left f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_right_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : R[X]} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : g.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_right f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_gcd_iff_root_left_right [comm_semiring k] {ϕ : R →+* k} {f g : R[X]} {α : k} : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 ↔ (f.eval₂ ϕ α = 0) ∧ (g.eval₂ ϕ α = 0) := ⟨λ h, ⟨root_left_of_root_gcd h, root_right_of_root_gcd h⟩, λ h, eval₂_gcd_eq_zero h.1 h.2⟩ lemma is_root_gcd_iff_is_root_left_right {f g : R[X]} {α : R} : (euclidean_domain.gcd f g).is_root α ↔ f.is_root α ∧ g.is_root α := root_gcd_iff_root_left_right theorem is_coprime_map [field k] (f : R →+* k) : is_coprime (p.map f) (q.map f) ↔ is_coprime p q := by rw [← euclidean_domain.gcd_is_unit_iff, ← euclidean_domain.gcd_is_unit_iff, gcd_map, is_unit_map] lemma mem_roots_map [comm_ring k] [is_domain k] {f : R →+* k} {x : k} (hp : p ≠ 0) : x ∈ (p.map f).roots ↔ p.eval₂ f x = 0 := by rw [mem_roots (map_ne_zero hp), is_root, polynomial.eval_map]; apply_instance lemma mem_root_set [comm_ring k] [is_domain k] [algebra R k] {x : k} (hp : p ≠ 0) : x ∈ p.root_set k ↔ aeval x p = 0 := iff.trans multiset.mem_to_finset (mem_roots_map hp) lemma root_set_monomial [comm_ring S] [is_domain S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (monomial n a).root_set S = {0} := by rw [root_set, map_monomial, roots_monomial ((_root_.map_ne_zero (algebra_map R S)).2 ha), multiset.to_finset_nsmul _ _ hn, multiset.to_finset_singleton, finset.coe_singleton] lemma root_set_C_mul_X_pow [comm_ring S] [is_domain S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (C a * X ^ n).root_set S = {0} := by rw [C_mul_X_pow_eq_monomial, root_set_monomial hn ha] lemma root_set_X_pow [comm_ring S] [is_domain S] [algebra R S] {n : ℕ} (hn : n ≠ 0) : (X ^ n : R[X]).root_set S = {0} := by { rw [←one_mul (X ^ n : R[X]), ←C_1, root_set_C_mul_X_pow hn], exact one_ne_zero } lemma root_set_prod [comm_ring S] [is_domain S] [algebra R S] {ι : Type*} (f : ι → R[X]) (s : finset ι) (h : s.prod f ≠ 0) : (s.prod f).root_set S = ⋃ (i ∈ s), (f i).root_set S := begin simp only [root_set, ←finset.mem_coe], rw [polynomial.map_prod, roots_prod, finset.bind_to_finset, s.val_to_finset, finset.coe_bUnion], rwa [←polynomial.map_prod, ne, map_eq_zero], end lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x := ⟨-(p.coeff 0 / p.coeff 1), have p.coeff 1 ≠ 0, by rw ← nat_degree_eq_of_degree_eq_some h; exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h), by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_rfl)] }; simp [is_root, mul_div_cancel' _ this]⟩ lemma coeff_inv_units (u : R[X]ˣ) (n : ℕ) : ((↑u : R[X]).coeff n)⁻¹ = ((↑u⁻¹ : R[X]).coeff n) := begin rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹), coeff_C, coeff_C, inv_eq_one_div], split_ifs, { rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero, coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self]; simp }, { simp } end lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) := begin rw [ne.def, ← leading_coeff_eq_zero, ← ne.def, ← is_unit_iff_ne_zero] at hp0, rw [monic, leading_coeff_normalize, normalize_eq_one], apply hp0, end lemma leading_coeff_div (hpq : q.degree ≤ p.degree) : (p / q).leading_coeff = p.leading_coeff / q.leading_coeff := begin by_cases hq : q = 0, { simp [hq] }, rw [div_def, leading_coeff_mul, leading_coeff_C, leading_coeff_div_by_monic_of_monic (monic_mul_leading_coeff_inv hq) _, mul_comm, div_eq_mul_inv], rwa [degree_mul_leading_coeff_inv q hq] end lemma div_C_mul : p / (C a * q) = C a⁻¹ * (p / q) := begin by_cases ha : a = 0, { simp [ha] }, simp only [div_def, leading_coeff_mul, mul_inv, leading_coeff_C, C.map_mul, mul_assoc], congr' 3, rw [mul_left_comm q, ← mul_assoc, ← C.map_mul, mul_inv_cancel ha, C.map_one, one_mul] end lemma C_mul_dvd (ha : a ≠ 0) : C a * p ∣ q ↔ p ∣ q := ⟨λ h, dvd_trans (dvd_mul_left _ _) h, λ ⟨r, hr⟩, ⟨C a⁻¹ * r, by rw [mul_assoc, mul_left_comm p, ← mul_assoc, ← C.map_mul, _root_.mul_inv_cancel ha, C.map_one, one_mul, hr]⟩⟩ lemma dvd_C_mul (ha : a ≠ 0) : p ∣ polynomial.C a * q ↔ p ∣ q := ⟨λ ⟨r, hr⟩, ⟨C a⁻¹ * r, by rw [mul_left_comm p, ← hr, ← mul_assoc, ← C.map_mul, _root_.inv_mul_cancel ha, C.map_one, one_mul]⟩, λ h, dvd_trans h (dvd_mul_left _ _)⟩ lemma coe_norm_unit_of_ne_zero (hp : p ≠ 0) : (norm_unit p : R[X]) = C p.leading_coeff⁻¹ := have p.leading_coeff ≠ 0 := mt leading_coeff_eq_zero.mp hp, by simp [comm_group_with_zero.coe_norm_unit _ this] lemma normalize_monic (h : monic p) : normalize p = p := by simp [h] theorem map_dvd_map' [field k] (f : R →+* k) {x y : R[X]} : x.map f ∣ y.map f ↔ x ∣ y := if H : x = 0 then by rw [H, polynomial.map_zero, zero_dvd_iff, zero_dvd_iff, map_eq_zero] else by rw [← normalize_dvd_iff, ← @normalize_dvd_iff R[X], normalize_apply, normalize_apply, coe_norm_unit_of_ne_zero H, coe_norm_unit_of_ne_zero (mt (map_eq_zero f).1 H), leading_coeff_map, ← map_inv₀ f, ← map_C, ← polynomial.map_mul, map_dvd_map _ f.injective (monic_mul_leading_coeff_inv H)] lemma degree_normalize : degree (normalize p) = degree p := by simp lemma prime_of_degree_eq_one (hp1 : degree p = 1) : prime p := have prime (normalize p), from monic.prime_of_degree_eq_one (hp1 ▸ degree_normalize) (monic_normalize (λ hp0, absurd hp1 (hp0.symm ▸ by simp; exact dec_trivial))), (normalize_associated _).prime this lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p := (prime_of_degree_eq_one hp1).irreducible theorem not_irreducible_C (x : R) : ¬irreducible (C x) := if H : x = 0 then by { rw [H, C_0], exact not_irreducible_zero } else λ hx, irreducible.not_unit hx $ is_unit_C.2 $ is_unit_iff_ne_zero.2 H theorem degree_pos_of_irreducible (hp : irreducible p) : 0 < p.degree := lt_of_not_ge $ λ hp0, have _ := eq_C_of_degree_le_zero hp0, not_irreducible_C (p.coeff 0) $ this ▸ hp /-- If `f` is a polynomial over a field, and `a : K` satisfies `f' a ≠ 0`, then `f / (X - a)` is coprime with `X - a`. Note that we do not assume `f a = 0`, because `f / (X - a) = (f - f a) / (X - a)`. -/ lemma is_coprime_of_is_root_of_eval_derivative_ne_zero {K : Type*} [field K] (f : K[X]) (a : K) (hf' : f.derivative.eval a ≠ 0) : is_coprime (X - C a : K[X]) (f /ₘ (X - C a)) := begin refine or.resolve_left (euclidean_domain.dvd_or_coprime (X - C a) (f /ₘ (X - C a)) (irreducible_of_degree_eq_one (polynomial.degree_X_sub_C a))) _, contrapose! hf' with h, have key : (X - C a) * (f /ₘ (X - C a)) = f - (f %ₘ (X - C a)), { rw [eq_sub_iff_add_eq, ← eq_sub_iff_add_eq', mod_by_monic_eq_sub_mul_div], exact monic_X_sub_C a }, replace key := congr_arg derivative key, simp only [derivative_X, derivative_mul, one_mul, sub_zero, derivative_sub, mod_by_monic_X_sub_C_eq_C_eval, derivative_C] at key, have : (X - C a) ∣ derivative f := key ▸ (dvd_add h (dvd_mul_right _ _)), rw [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval] at this, rw [← C_inj, this, C_0], end end field end polynomial
a30d782f63f7fb5008e611fa993b7974674bcab9
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/group_with_zero/power.lean
ace02e08ff1c5f6b44e43e29c7438ff2a195f838
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
6,341
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.group_power.lemmas /-! # Powers of elements of groups with an adjoined zero element In this file we define integer power functions for groups with an adjoined zero element. This generalises the integer power function on a division ring. -/ section group_with_zero variables {G₀ : Type*} [group_with_zero G₀] {a : G₀} {m n : ℕ} section nat_pow theorem pow_sub₀ (a : G₀) {m n : ℕ} (ha : a ≠ 0) (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], by simpa only [div_eq_mul_inv] using eq_div_of_mul_eq (pow_ne_zero _ ha) h2 lemma pow_sub_of_lt (a : G₀) {m n : ℕ} (h : n < m) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ := begin obtain rfl | ha := eq_or_ne a 0, { rw [zero_pow (tsub_pos_of_lt h), zero_pow (n.zero_le.trans_lt h), zero_mul] }, { exact pow_sub₀ _ ha h.le } end 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 lemma inv_pow_sub₀ (ha : a ≠ 0) (h : n ≤ m) : a⁻¹ ^ (m - n) = (a ^ m)⁻¹ * a ^ n := by rw [pow_sub₀ _ (inv_ne_zero ha) h, inv_pow, inv_pow, inv_inv] lemma inv_pow_sub_of_lt (a : G₀) (h : n < m) : a⁻¹ ^ (m - n) = (a ^ m)⁻¹ * a ^ n := by rw [pow_sub_of_lt a⁻¹ h, inv_pow, inv_pow, inv_inv] end nat_pow end group_with_zero section zpow open int variables {G₀ : Type*} [group_with_zero G₀] local attribute [ematch] le_of_lt lemma zero_zpow : ∀ z : ℤ, z ≠ 0 → (0 : G₀) ^ z = 0 | (n : ℕ) h := by { rw [zpow_coe_nat, zero_pow'], simpa using h } | -[1+n] h := by simp lemma zero_zpow_eq (n : ℤ) : (0 : G₀) ^ n = if n = 0 then 1 else 0 := begin split_ifs with h, { rw [h, zpow_zero] }, { rw [zero_zpow _ h] } end lemma zpow_add_one₀ {a : G₀} (ha : a ≠ 0) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a | (n : ℕ) := by simp only [← int.coe_nat_succ, zpow_coe_nat, pow_succ'] | -[1+0] := by erw [zpow_zero, zpow_neg_succ_of_nat, pow_one, inv_mul_cancel ha] | -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, zpow_neg, neg_add, neg_add_cancel_right, zpow_neg, ← int.coe_nat_succ, zpow_coe_nat, zpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev, mul_assoc, inv_mul_cancel ha, mul_one] lemma zpow_sub_one₀ {a : G₀} (ha : a ≠ 0) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ := calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : by rw [mul_assoc, mul_inv_cancel ha, mul_one] ... = a^n * a⁻¹ : by rw [← zpow_add_one₀ ha, sub_add_cancel] lemma zpow_add₀ {a : G₀} (ha : a ≠ 0) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n := begin induction n using int.induction_on with n ihn n ihn, case hz : { simp }, { simp only [← add_assoc, zpow_add_one₀ ha, ihn, mul_assoc] }, { rw [zpow_sub_one₀ ha, ← mul_assoc, ← ihn, ← zpow_sub_one₀ ha, add_sub_assoc] } end lemma zpow_add' {a : G₀} {m n : ℤ} (h : a ≠ 0 ∨ m + n ≠ 0 ∨ m = 0 ∧ n = 0) : a ^ (m + n) = a ^ m * a ^ n := begin by_cases hm : m = 0, { simp [hm] }, by_cases hn : n = 0, { simp [hn] }, by_cases ha : a = 0, { subst a, simp only [false_or, eq_self_iff_true, not_true, ne.def, hm, hn, false_and, or_false] at h, rw [zero_zpow _ h, zero_zpow _ hm, zero_mul] }, { exact zpow_add₀ ha m n } end theorem zpow_one_add₀ {a : G₀} (h : a ≠ 0) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [zpow_add₀ h, zpow_one] theorem semiconj_by.zpow_right₀ {a x y : G₀} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (x^m) (y^m) | (n : ℕ) := by simp [h.pow_right n] | -[1+n] := by simp [(h.pow_right (n + 1)).inv_right₀] theorem commute.zpow_right₀ {a b : G₀} (h : commute a b) : ∀ m : ℤ, commute a (b^m) := h.zpow_right₀ theorem commute.zpow_left₀ {a b : G₀} (h : commute a b) (m : ℤ) : commute (a^m) b := (h.symm.zpow_right₀ m).symm theorem commute.zpow_zpow₀ {a b : G₀} (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) := (h.zpow_left₀ m).zpow_right₀ n theorem commute.zpow_self₀ (a : G₀) (n : ℤ) : commute (a^n) a := (commute.refl a).zpow_left₀ n theorem commute.self_zpow₀ (a : G₀) (n : ℤ) : commute a (a^n) := (commute.refl a).zpow_right₀ n theorem commute.zpow_zpow_self₀ (a : G₀) (m n : ℤ) : commute (a^m) (a^n) := (commute.refl a).zpow_zpow₀ m n theorem zpow_bit1₀ (a : G₀) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := begin rw [← zpow_bit0, bit1, zpow_add', zpow_one], right, left, apply bit1_ne_zero end lemma zpow_ne_zero_of_ne_zero {a : G₀} (ha : a ≠ 0) : ∀ (z : ℤ), a ^ z ≠ 0 | (n : ℕ) := by { rw zpow_coe_nat, exact pow_ne_zero _ ha } | -[1+n] := by { rw zpow_neg_succ_of_nat, exact inv_ne_zero (pow_ne_zero _ ha) } lemma zpow_sub₀ {a : G₀} (ha : a ≠ 0) (z1 z2 : ℤ) : a ^ (z1 - z2) = a ^ z1 / a ^ z2 := by rw [sub_eq_add_neg, zpow_add₀ ha, zpow_neg, div_eq_mul_inv] theorem zpow_bit1' (a : G₀) (n : ℤ) : a ^ bit1 n = (a * a) ^ n * a := by rw [zpow_bit1₀, (commute.refl a).mul_zpow] lemma zpow_eq_zero {x : G₀} {n : ℤ} (h : x ^ n = 0) : x = 0 := classical.by_contradiction $ λ hx, zpow_ne_zero_of_ne_zero hx n h lemma zpow_eq_zero_iff {a : G₀} {n : ℤ} (hn : n ≠ 0) : a ^ n = 0 ↔ a = 0 := ⟨zpow_eq_zero, λ ha, ha.symm ▸ zero_zpow _ hn⟩ lemma zpow_ne_zero {x : G₀} (n : ℤ) : x ≠ 0 → x ^ n ≠ 0 := mt zpow_eq_zero theorem zpow_neg_mul_zpow_self (n : ℤ) {x : G₀} (h : x ≠ 0) : x ^ (-n) * x ^ n = 1 := begin rw [zpow_neg], exact inv_mul_cancel (zpow_ne_zero n h) end end zpow section variables {G₀ : Type*} [comm_group_with_zero G₀] lemma div_sq_cancel (a b : G₀) : a ^ 2 * b / a = a * b := begin by_cases ha : a = 0, { simp [ha] }, rw [sq, mul_assoc, mul_div_cancel_left _ ha] end end /-- If a monoid homomorphism `f` between two `group_with_zero`s maps `0` to `0`, then it maps `x^n`, `n : ℤ`, to `(f x)^n`. -/ @[simp] lemma map_zpow₀ {F G₀ G₀' : Type*} [group_with_zero G₀] [group_with_zero G₀'] [monoid_with_zero_hom_class F G₀ G₀'] (f : F) (x : G₀) (n : ℤ) : f (x ^ n) = f x ^ n := map_zpow' f (map_inv₀ f) x n
7545eb1aae0828b9ef76f47d22c8bfbfce090fce
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/tactic.lean
9339cd4426749d145e1ea21fc7d33fb4a1fbaa1a
[ "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
4,074
lean
/- Copyright (c) 2020 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import tactic.auto_cases import tactic.tidy import tactic.with_local_reducibility import tactic.show_term import topology.basic /-! # Tactics for topology Currently we have one domain-specific tactic for topology: `continuity`. -/ /-! ### `continuity` tactic Automatically solve goals of the form `continuous f`. Mark lemmas with `@[continuity]` to add them to the set of lemmas used by `continuity`. -/ /-- User attribute used to mark tactics used by `continuity`. -/ @[user_attribute] meta def continuity : user_attribute := { name := `continuity, descr := "lemmas usable to prove continuity" } -- Mark some continuity lemmas already defined in `topology.basic` attribute [continuity] continuous_id continuous_const -- As we will be using `apply_rules` with `md := semireducible`, -- we need another version of `continuous_id`. @[continuity] lemma continuous_id' {α : Type*} [topological_space α] : continuous (λ a : α, a) := continuous_id namespace tactic /-- Tactic to apply `continuous.comp` when appropriate. Applying `continuous.comp` is not always a good idea, so we have some extra logic here to try to avoid bad cases. * If the function we're trying to prove continuous is actually constant, and that constant is a function application `f z`, then continuous.comp would produce new goals `continuous f`, `continuous (λ _, z)`, which is silly. We avoid this by failing if we could apply continuous_const. * continuous.comp will always succeed on `continuous (λ x, f x)` and produce new goals `continuous (λ x, x)`, `continuous f`. We detect this by failing if a new goal can be closed by applying continuous_id. -/ meta def apply_continuous.comp : tactic unit := `[fail_if_success { exact continuous_const }; refine continuous.comp _ _; fail_if_success { exact continuous_id }] /-- List of tactics used by `continuity` internally. -/ meta def continuity_tactics (md : transparency := reducible) : list (tactic string) := [ intros1 >>= λ ns, pure ("intros " ++ (" ".intercalate (ns.map (λ e, e.to_string)))), apply_rules [] [``continuity] 50 { md := md } >> pure "apply_rules with continuity", apply_continuous.comp >> pure "refine continuous.comp _ _" ] namespace interactive setup_tactic_parser /-- Solve goals of the form `continuous f`. `continuity?` reports back the proof term it found. -/ meta def continuity (bang : parse $ optional (tk "!")) (trace : parse $ optional (tk "?")) (cfg : tidy.cfg := {}) : tactic unit := let md := if bang.is_some then semireducible else reducible, continuity_core := tactic.tidy { tactics := continuity_tactics md, ..cfg }, trace_fn := if trace.is_some then show_term else id in trace_fn continuity_core /-- Version of `continuity` for use with auto_param. -/ meta def continuity' : tactic unit := continuity none none {} /-- `continuity` solves goals of the form `continuous f` by applying lemmas tagged with the `continuity` user attribute. ``` example {X Y : Type*} [topological_space X] [topological_space Y] (f₁ f₂ : X → Y) (hf₁ : continuous f₁) (hf₂ : continuous f₂) (g : Y → ℝ) (hg : continuous g) : continuous (λ x, (max (g (f₁ x)) (g (f₂ x))) + 1) := by continuity ``` will discharge the goal, generating a proof term like `((continuous.comp hg hf₁).max (continuous.comp hg hf₂)).add continuous_const` You can also use `continuity!`, which applies lemmas with `{ md := semireducible }`. The default behaviour is more conservative, and only unfolds `reducible` definitions when attempting to match lemmas with the goal. `continuity?` reports back the proof term it found. -/ add_tactic_doc { name := "continuity / continuity'", category := doc_category.tactic, decl_names := [`tactic.interactive.continuity, `tactic.interactive.continuity'], tags := ["lemma application"] } end interactive end tactic
72da128d22056901b166e8deabb8571a2056b9a4
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/linear/linear_functor.lean
d532a7e4136efa2ba7d1681a78f7aca05a3adf2f
[ "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
3,083
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.preadditive.additive_functor import category_theory.linear /-! # Linear Functors An additive functor between two `R`-linear categories is called *linear* if the induced map on hom types is a morphism of `R`-modules. # Implementation details `functor.linear` is a `Prop`-valued class, defined by saying that for every two objects `X` and `Y`, the map `F.map : (X ⟶ Y) → (F.obj X ⟶ F.obj Y)` is a morphism of `R`-modules. -/ namespace category_theory variables (R : Type*) [semiring R] /-- An additive functor `F` is `R`-linear provided `F.map` is an `R`-module morphism. -/ class functor.linear {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] [linear R C] [linear R D] (F : C ⥤ D) [F.additive] : Prop := (map_smul' : Π {X Y : C} {f : X ⟶ Y} {r : R}, F.map (r • f) = r • F.map f . obviously) section linear namespace functor section variables {R} {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] [category_theory.linear R C] [category_theory.linear R D] (F : C ⥤ D) [additive F] [linear R F] @[simp] lemma map_smul {X Y : C} (r : R) (f : X ⟶ Y) : F.map (r • f) = r • F.map f := functor.linear.map_smul' instance : linear R (𝟭 C) := {} instance {E : Type*} [category E] [preadditive E] [category_theory.linear R E] (G : D ⥤ E) [additive G] [linear R G]: linear R (F ⋙ G) := {} variables (R) /-- `F.map_linear_map` is an `R`-linear map whose underlying function is `F.map`. -/ @[simps] def map_linear_map {X Y : C} : (X ⟶ Y) →ₗ[R] (F.obj X ⟶ F.obj Y) := { map_smul' := λ r f, F.map_smul r f, ..F.map_add_hom } lemma coe_map_linear_map {X Y : C} : ⇑(F.map_linear_map R : (X ⟶ Y) →ₗ[R] _) = @map C _ D _ F X Y := rfl end section induced_category variables {C : Type*} {D : Type*} [category D] [preadditive D] [category_theory.linear R D] (F : C → D) instance induced_functor_linear : functor.linear R (induced_functor F) := {} end induced_category section variables {R} {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] (F : C ⥤ D) [additive F] instance nat_linear : F.linear ℕ := { map_smul' := λ X Y f r, F.map_add_hom.map_nsmul f r, } instance int_linear : F.linear ℤ := { map_smul' := λ X Y f r, (F.map_add_hom : (X ⟶ Y) →+ (F.obj X ⟶ F.obj Y)).map_zsmul f r, } variables [category_theory.linear ℚ C] [category_theory.linear ℚ D] instance rat_linear : F.linear ℚ := { map_smul' := λ X Y f r, F.map_add_hom.to_rat_linear_map.map_smul r f, } end end functor namespace equivalence variables {C D : Type*} [category C] [category D] [preadditive C] [linear R C] [preadditive D] [linear R D] instance inverse_linear (e : C ≌ D) [e.functor.additive] [e.functor.linear R] : e.inverse.linear R := { map_smul' := λ X Y r f, by { apply e.functor.map_injective, simp, }, } end equivalence end linear end category_theory
30b3d62ebabad28ed315f0943a87cdd3b1724ea9
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/basics/unnamed_1915.lean
9374761e77663409b35abedad5a1df2fd15e9374
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
173
lean
import order.lattice variables {α : Type*} [lattice α] variables x y z : α -- BEGIN example : x ⊓ (x ⊔ y) = x := sorry example : x ⊔ (x ⊓ y) = x := sorry -- END
071d410b56febd7ae8e7646db4bd642efe85aa0a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/equiv/functor_auto.lean
071da2e438095b509f9105899a33ab0e1981258b
[]
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
2,852
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Simon Hudon, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.equiv.basic import Mathlib.control.bifunctor import Mathlib.PostPort universes u v w namespace Mathlib /-! # Functor and bifunctors can be applied to `equiv`s. We define ```lean def functor.map_equiv (f : Type u → Type v) [functor f] [is_lawful_functor f] : α ≃ β → f α ≃ f β ``` and ```lean def bifunctor.map_equiv (F : Type u → Type v → Type w) [bifunctor F] [is_lawful_bifunctor F] : α ≃ β → α' ≃ β' → F α α' ≃ F β β' ``` -/ namespace functor /-- Apply a functor to an `equiv`. -/ def map_equiv {α : Type u} {β : Type u} (f : Type u → Type v) [Functor f] [is_lawful_functor f] (h : α ≃ β) : f α ≃ f β := equiv.mk (Functor.map ⇑h) (Functor.map ⇑(equiv.symm h)) sorry sorry @[simp] theorem map_equiv_apply {α : Type u} {β : Type u} (f : Type u → Type v) [Functor f] [is_lawful_functor f] (h : α ≃ β) (x : f α) : coe_fn (map_equiv f h) x = ⇑h <$> x := rfl @[simp] theorem map_equiv_symm_apply {α : Type u} {β : Type u} (f : Type u → Type v) [Functor f] [is_lawful_functor f] (h : α ≃ β) (y : f β) : coe_fn (equiv.symm (map_equiv f h)) y = ⇑(equiv.symm h) <$> y := rfl @[simp] theorem map_equiv_refl {α : Type u} (f : Type u → Type v) [Functor f] [is_lawful_functor f] : map_equiv f (equiv.refl α) = equiv.refl (f α) := sorry end functor namespace bifunctor /-- Apply a bifunctor to a pair of `equiv`s. -/ def map_equiv {α : Type u} {β : Type u} {α' : Type v} {β' : Type v} (F : Type u → Type v → Type w) [bifunctor F] [is_lawful_bifunctor F] (h : α ≃ β) (h' : α' ≃ β') : F α α' ≃ F β β' := equiv.mk (bimap ⇑h ⇑h') (bimap ⇑(equiv.symm h) ⇑(equiv.symm h')) sorry sorry @[simp] theorem map_equiv_apply {α : Type u} {β : Type u} {α' : Type v} {β' : Type v} (F : Type u → Type v → Type w) [bifunctor F] [is_lawful_bifunctor F] (h : α ≃ β) (h' : α' ≃ β') (x : F α α') : coe_fn (map_equiv F h h') x = bimap (⇑h) (⇑h') x := rfl @[simp] theorem map_equiv_symm_apply {α : Type u} {β : Type u} {α' : Type v} {β' : Type v} (F : Type u → Type v → Type w) [bifunctor F] [is_lawful_bifunctor F] (h : α ≃ β) (h' : α' ≃ β') (y : F β β') : coe_fn (equiv.symm (map_equiv F h h')) y = bimap (⇑(equiv.symm h)) (⇑(equiv.symm h')) y := rfl @[simp] theorem map_equiv_refl_refl {α : Type u} {α' : Type v} (F : Type u → Type v → Type w) [bifunctor F] [is_lawful_bifunctor F] : map_equiv F (equiv.refl α) (equiv.refl α') = equiv.refl (F α α') := sorry end Mathlib