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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4d4f5cf293ef74581bd25c5450baf734b98d240f
|
367134ba5a65885e863bdc4507601606690974c1
|
/src/data/nat/totient.lean
|
39aa4c8bf7f9b729d251c1db610a3405e9f4f5b8
|
[
"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
| 3,699
|
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 algebra.big_operators.basic
open finset
open_locale big_operators
namespace nat
/-- Euler's totient function. This counts the number of positive integers less than `n` which are
coprime with `n`. -/
def totient (n : ℕ) : ℕ := ((range n).filter (nat.coprime n)).card
localized "notation `φ` := nat.totient" in nat
@[simp] theorem totient_zero : φ 0 = 0 := rfl
lemma totient_le (n : ℕ) : φ n ≤ n :=
calc totient n ≤ (range n).card : card_filter_le _ _
... = n : card_range _
lemma totient_pos : ∀ {n : ℕ}, 0 < n → 0 < φ n
| 0 := dec_trivial
| 1 := dec_trivial
| (n+2) := λ h, card_pos.2 ⟨1, mem_filter.2 ⟨mem_range.2 dec_trivial, coprime_one_right _⟩⟩
lemma sum_totient (n : ℕ) : ∑ m in (range n.succ).filter (∣ n), φ m = n :=
if hn0 : n = 0 then by rw hn0; refl
else
calc ∑ m in (range n.succ).filter (∣ n), φ m
= ∑ d in (range n.succ).filter (∣ n), ((range (n / d)).filter (λ m, gcd (n / d) m = 1)).card :
eq.symm $ sum_bij (λ d _, n / d)
(λ d hd, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _,
by conv {to_rhs, rw ← nat.mul_div_cancel' (mem_filter.1 hd).2}; simp⟩)
(λ _ _, rfl)
(λ a b ha hb h,
have ha : a * (n / a) = n, from nat.mul_div_cancel' (mem_filter.1 ha).2,
have 0 < (n / a), from nat.pos_of_ne_zero (λ h, by simp [*, lt_irrefl] at *),
by rw [← nat.mul_left_inj this, ha, h, nat.mul_div_cancel' (mem_filter.1 hb).2])
(λ b hb,
have hb : b < n.succ ∧ b ∣ n, by simpa [-range_succ] using hb,
have hbn : (n / b) ∣ n, from ⟨b, by rw nat.div_mul_cancel hb.2⟩,
have hnb0 : (n / b) ≠ 0, from λ h, by simpa [h, ne.symm hn0] using nat.div_mul_cancel hbn,
⟨n / b, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, hbn⟩,
by rw [← nat.mul_left_inj (nat.pos_of_ne_zero hnb0),
nat.mul_div_cancel' hb.2, nat.div_mul_cancel hbn]⟩)
... = ∑ d in (range n.succ).filter (∣ n), ((range n).filter (λ m, gcd n m = d)).card :
sum_congr rfl (λ d hd,
have hd : d ∣ n, from (mem_filter.1 hd).2,
have hd0 : 0 < d, from nat.pos_of_ne_zero (λ h, hn0 (eq_zero_of_zero_dvd $ h ▸ hd)),
card_congr (λ m hm, d * m)
(λ m hm, have hm : m < n / d ∧ gcd (n / d) m = 1, by simpa using hm,
mem_filter.2 ⟨mem_range.2 $ nat.mul_div_cancel' hd ▸
(mul_lt_mul_left hd0).2 hm.1,
by rw [← nat.mul_div_cancel' hd, gcd_mul_left, hm.2, mul_one]⟩)
(λ a b ha hb h, (nat.mul_right_inj hd0).1 h)
(λ b hb, have hb : b < n ∧ gcd n b = d, by simpa using hb,
⟨b / d, mem_filter.2 ⟨mem_range.2 ((mul_lt_mul_left (show 0 < d, from hb.2 ▸ hb.2.symm ▸ hd0)).1
(by rw [← hb.2, nat.mul_div_cancel' (gcd_dvd_left _ _),
nat.mul_div_cancel' (gcd_dvd_right _ _)]; exact hb.1)),
hb.2 ▸ coprime_div_gcd_div_gcd (hb.2.symm ▸ hd0)⟩,
hb.2 ▸ nat.mul_div_cancel' (gcd_dvd_right _ _)⟩))
... = ((filter (∣ n) (range n.succ)).bUnion (λ d, (range n).filter (λ m, gcd n m = d))).card :
(card_bUnion (by intros; apply disjoint_filter.2; cc)).symm
... = (range n).card :
congr_arg card (finset.ext (λ m, ⟨by finish,
λ hm, have h : m < n, from mem_range.1 hm,
mem_bUnion.2 ⟨gcd n m, mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd (lt_of_le_of_lt (nat.zero_le _) h)
(gcd_dvd_left _ _))), gcd_dvd_left _ _⟩, mem_filter.2 ⟨hm, rfl⟩⟩⟩))
... = n : card_range _
end nat
|
9f150b87366c8dcbaa0dc44011525b8d609ae7d8
|
d1a52c3f208fa42c41df8278c3d280f075eb020c
|
/src/Lean/Meta/GeneralizeTelescope.lean
|
a023ebefc852120f48c0813f8a6097ee7ffe306e
|
[
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"
] |
permissive
|
cipher1024/lean4
|
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
|
69114d3b50806264ef35b57394391c3e738a9822
|
refs/heads/master
| 1,642,227,983,603
| 1,642,011,696,000
| 1,642,011,696,000
| 228,607,691
| 0
| 0
|
Apache-2.0
| 1,576,584,269,000
| 1,576,584,268,000
| null |
UTF-8
|
Lean
| false
| false
| 3,886
|
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.KAbstract
import Lean.Meta.Check
namespace Lean.Meta
namespace GeneralizeTelescope
structure Entry where
expr : Expr
type : Expr
modified : Bool
partial def updateTypes (e eNew : Expr) (entries : Array Entry) (i : Nat) : MetaM (Array Entry) :=
if h : i < entries.size then
let entry := entries.get ⟨i, h⟩
match entry with
| ⟨_, type, _⟩ => do
let typeAbst ← kabstract type e
if typeAbst.hasLooseBVars then do
let typeNew := typeAbst.instantiate1 eNew
let entries := entries.set ⟨i, h⟩ { entry with type := typeNew, modified := true }
updateTypes e eNew entries (i+1)
else
updateTypes e eNew entries (i+1)
else
pure entries
partial def generalizeTelescopeAux {α} (k : Array Expr → MetaM α)
(entries : Array Entry) (i : Nat) (fvars : Array Expr) : MetaM α := do
if h : i < entries.size then
let replace (baseUserName : Name) (e : Expr) (type : Expr) : MetaM α := do
let userName ← mkFreshUserName baseUserName
withLocalDeclD userName type fun x => do
let entries ← updateTypes e x entries (i+1)
generalizeTelescopeAux k entries (i+1) (fvars.push x)
match entries.get ⟨i, h⟩ with
| ⟨e@(Expr.fvar fvarId _), type, false⟩ =>
let localDecl ← getLocalDecl fvarId
match localDecl with
| LocalDecl.cdecl .. => generalizeTelescopeAux k entries (i+1) (fvars.push e)
| LocalDecl.ldecl .. => replace localDecl.userName e type
| ⟨e, type, modified⟩ =>
if modified then
unless (← isTypeCorrect type) do
throwError "failed to create telescope generalizing {entries.map Entry.expr}"
replace `x e type
else
k fvars
end GeneralizeTelescope
open GeneralizeTelescope
/--
Given expressions `es := #[e_1, e_2, ..., e_n]`, execute `k` with the
free variables `(x_1 : A_1) (x_2 : A_2 [x_1]) ... (x_n : A_n [x_1, ... x_{n-1}])`.
Moreover,
- type of `e_1` is definitionally equal to `A_1`,
- type of `e_2` is definitionally equal to `A_2[e_1]`.
- ...
- type of `e_n` is definitionally equal to `A_n[e_1, ..., e_{n-1}]`.
This method tries to avoid the creation of new free variables. For example, if `e_i` is a
free variable `x_i` and it is not a let-declaration variable, and its type does not depend on
previous `e_j`s, the method will just use `x_i`.
The telescope `x_1 ... x_n` can be used to create lambda and forall abstractions.
Moreover, for any type correct lambda abstraction `f` constructed using `mkForall #[x_1, ..., x_n] ...`,
The application `f e_1 ... e_n` is also type correct.
The `kabstract` method is used to "locate" and abstract forward dependencies.
That is, an occurrence of `e_i` in the of `e_j` for `j > i`.
The method checks whether the abstract types `A_i` are type correct. Here is an example
where `generalizeTelescope` fails to create the telescope `x_1 ... x_n`.
Assume the local context contains `(n : Nat := 10) (xs : Vec Nat n) (ys : Vec Nat 10) (h : xs = ys)`.
Then, assume we invoke `generalizeTelescope` with `es := #[10, xs, ys, h]`
A type error is detected when processing `h`'s type. At this point, the method had successfully produced
```
(x_1 : Nat) (xs : Vec Nat n) (x_2 : Vec Nat x_1)
```
and the type for the new variable abstracting `h` is `xs = x_2` which is not type correct. -/
def generalizeTelescope {α} (es : Array Expr) (k : Array Expr → MetaM α) : MetaM α := do
let es ← es.mapM fun e => do
let type ← inferType e
let type ← instantiateMVars type
pure { expr := e, type := type, modified := false : Entry }
generalizeTelescopeAux k es 0 #[]
end Lean.Meta
|
e2b483cb84f23b11d5dee6bdb746d22c362e0553
|
4727251e0cd73359b15b664c3170e5d754078599
|
/src/tactic/norm_num.lean
|
66472527140b0310a8cf496e98dd5894c7c5e51c
|
[
"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
| 69,135
|
lean
|
/-
Copyright (c) 2017 Simon Hudon All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Mario Carneiro
-/
import data.rat.cast
import data.rat.meta_defs
/-!
# `norm_num`
Evaluating arithmetic expressions including `*`, `+`, `-`, `^`, `≤`.
-/
universes u v w
namespace tactic
namespace instance_cache
/-- Faster version of `mk_app ``bit0 [e]`. -/
meta def mk_bit0 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) :=
do (c, ai) ← c.get ``has_add,
return (c, (expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e])
/-- Faster version of `mk_app ``bit1 [e]`. -/
meta def mk_bit1 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) :=
do (c, ai) ← c.get ``has_add,
(c, oi) ← c.get ``has_one,
return (c, (expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e])
end instance_cache
end tactic
open tactic
/-!
Each lemma in this file is written the way it is to exactly match (with no defeq reduction allowed)
the conclusion of some lemma generated by the proof procedure that uses it. That proof procedure
should describe the shape of the generated lemma in its docstring.
-/
namespace norm_num
variable {α : Type u}
lemma subst_into_add {α} [has_add α] (l r tl tr t)
(prl : (l : α) = tl) (prr : r = tr) (prt : tl + tr = t) : l + r = t :=
by rw [prl, prr, prt]
lemma subst_into_mul {α} [has_mul α] (l r tl tr t)
(prl : (l : α) = tl) (prr : r = tr) (prt : tl * tr = t) : l * r = t :=
by rw [prl, prr, prt]
lemma subst_into_neg {α} [has_neg α] (a ta t : α) (pra : a = ta) (prt : -ta = t) : -a = t :=
by simp [pra, prt]
/-- The result type of `match_numeral`, either `0`, `1`, or a top level
decomposition of `bit0 e` or `bit1 e`. The `other` case means it is not a numeral. -/
meta inductive match_numeral_result
| zero | one | bit0 (e : expr) | bit1 (e : expr) | other
/-- Unfold the top level constructor of the numeral expression. -/
meta def match_numeral : expr → match_numeral_result
| `(bit0 %%e) := match_numeral_result.bit0 e
| `(bit1 %%e) := match_numeral_result.bit1 e
| `(@has_zero.zero _ _) := match_numeral_result.zero
| `(@has_one.one _ _) := match_numeral_result.one
| _ := match_numeral_result.other
theorem zero_succ {α} [semiring α] : (0 + 1 : α) = 1 := zero_add _
theorem one_succ {α} [semiring α] : (1 + 1 : α) = 2 := rfl
theorem bit0_succ {α} [semiring α] (a : α) : bit0 a + 1 = bit1 a := rfl
theorem bit1_succ {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 = bit0 b :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
section
open match_numeral_result
/-- Given `a`, `b` natural numerals, proves `⊢ a + 1 = b`, assuming that this is provable.
(It may prove garbage instead of failing if `a + 1 = b` is false.) -/
meta def prove_succ : instance_cache → expr → expr → tactic (instance_cache × expr)
| c e r := match match_numeral e with
| zero := c.mk_app ``zero_succ []
| one := c.mk_app ``one_succ []
| bit0 e := c.mk_app ``bit0_succ [e]
| bit1 e := do
let r := r.app_arg,
(c, p) ← prove_succ c e r,
c.mk_app ``bit1_succ [e, r, p]
| _ := failed
end
end
/-- Given `a` natural numeral, returns `(b, ⊢ a + 1 = b)`. -/
meta def prove_succ' (c : instance_cache) (a : expr) : tactic (instance_cache × expr × expr) :=
do na ← a.to_nat,
(c, b) ← c.of_nat (na + 1),
(c, p) ← prove_succ c a b,
return (c, b, p)
theorem zero_adc {α} [semiring α] (a b : α) (h : a + 1 = b) : 0 + a + 1 = b := by rwa zero_add
theorem adc_zero {α} [semiring α] (a b : α) (h : a + 1 = b) : a + 0 + 1 = b := by rwa add_zero
theorem one_add {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + a = b := by rwa add_comm
theorem add_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b = bit0 c :=
h ▸ by simp [bit0, add_left_comm, add_assoc]
theorem add_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit1 b = bit1 c :=
h ▸ by simp [bit0, bit1, add_left_comm, add_assoc]
theorem add_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit1 a + bit0 b = bit1 c :=
h ▸ by simp [bit0, bit1, add_left_comm, add_comm, add_assoc]
theorem add_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b = bit0 c :=
h ▸ by simp [bit0, bit1, add_left_comm, add_comm, add_assoc]
theorem adc_one_one {α} [semiring α] : (1 + 1 + 1 : α) = 3 := rfl
theorem adc_bit0_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit0 a + 1 + 1 = bit0 b :=
h ▸ by simp [bit0, add_left_comm, add_assoc]
theorem adc_one_bit0 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit0 a + 1 = bit0 b :=
h ▸ by simp [bit0, add_left_comm, add_assoc]
theorem adc_bit1_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 + 1 = bit1 b :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_one_bit1 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit1 a + 1 = bit1 b :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b + 1 = bit1 c :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) :
bit1 a + bit0 b + 1 = bit0 c :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) :
bit0 a + bit1 b + 1 = bit0 c :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) :
bit1 a + bit1 b + 1 = bit1 c :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
section
open match_numeral_result
meta mutual def prove_add_nat, prove_adc_nat
with prove_add_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr)
| c a b r := do
match match_numeral a, match_numeral b with
| zero, _ := c.mk_app ``zero_add [b]
| _, zero := c.mk_app ``add_zero [a]
| _, one := prove_succ c a r
| one, _ := do (c, p) ← prove_succ c b r, c.mk_app ``one_add [b, r, p]
| bit0 a, bit0 b :=
do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit0 [a, b, r, p]
| bit0 a, bit1 b :=
do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit1 [a, b, r, p]
| bit1 a, bit0 b :=
do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit1_bit0 [a, b, r, p]
| bit1 a, bit1 b :=
do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``add_bit1_bit1 [a, b, r, p]
| _, _ := failed
end
with prove_adc_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr)
| c a b r := do
match match_numeral a, match_numeral b with
| zero, _ := do (c, p) ← prove_succ c b r, c.mk_app ``zero_adc [b, r, p]
| _, zero := do (c, p) ← prove_succ c b r, c.mk_app ``adc_zero [b, r, p]
| one, one := c.mk_app ``adc_one_one []
| bit0 a, one :=
do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit0_one [a, r, p]
| one, bit0 b :=
do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit0 [b, r, p]
| bit1 a, one :=
do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit1_one [a, r, p]
| one, bit1 b :=
do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit1 [b, r, p]
| bit0 a, bit0 b :=
do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``adc_bit0_bit0 [a, b, r, p]
| bit0 a, bit1 b :=
do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit0_bit1 [a, b, r, p]
| bit1 a, bit0 b :=
do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit0 [a, b, r, p]
| bit1 a, bit1 b :=
do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit1 [a, b, r, p]
| _, _ := failed
end
/-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b = r`. -/
add_decl_doc prove_add_nat
/-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b + 1 = r`. -/
add_decl_doc prove_adc_nat
/-- Given `a`,`b` natural numerals, returns `(r, ⊢ a + b = r)`. -/
meta def prove_add_nat' (c : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) :=
do na ← a.to_nat,
nb ← b.to_nat,
(c, r) ← c.of_nat (na + nb),
(c, p) ← prove_add_nat c a b r,
return (c, r, p)
end
theorem bit0_mul {α} [semiring α] (a b c : α) (h : a * b = c) :
bit0 a * b = bit0 c := h ▸ by simp [bit0, add_mul]
theorem mul_bit0' {α} [semiring α] (a b c : α) (h : a * b = c) :
a * bit0 b = bit0 c := h ▸ by simp [bit0, mul_add]
theorem mul_bit0_bit0 {α} [semiring α] (a b c : α) (h : a * b = c) :
bit0 a * bit0 b = bit0 (bit0 c) := bit0_mul _ _ _ (mul_bit0' _ _ _ h)
theorem mul_bit1_bit1 {α} [semiring α] (a b c d e : α)
(hc : a * b = c) (hd : a + b = d) (he : bit0 c + d = e) :
bit1 a * bit1 b = bit1 e :=
by rw [← he, ← hd, ← hc]; simp [bit1, bit0, mul_add, add_mul, add_left_comm, add_assoc]
section
open match_numeral_result
/-- Given `a`,`b` natural numerals, returns `(r, ⊢ a * b = r)`. -/
meta def prove_mul_nat : instance_cache → expr → expr → tactic (instance_cache × expr × expr)
| ic a b :=
match match_numeral a, match_numeral b with
| zero, _ := do
(ic, z) ← ic.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``zero_mul [b],
return (ic, z, p)
| _, zero := do
(ic, z) ← ic.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``mul_zero [a],
return (ic, z, p)
| one, _ := do (ic, p) ← ic.mk_app ``one_mul [b], return (ic, b, p)
| _, one := do (ic, p) ← ic.mk_app ``mul_one [a], return (ic, a, p)
| bit0 a, bit0 b := do
(ic, c, p) ← prove_mul_nat ic a b,
(ic, p) ← ic.mk_app ``mul_bit0_bit0 [a, b, c, p],
(ic, c') ← ic.mk_bit0 c,
(ic, c') ← ic.mk_bit0 c',
return (ic, c', p)
| bit0 a, _ := do
(ic, c, p) ← prove_mul_nat ic a b,
(ic, p) ← ic.mk_app ``bit0_mul [a, b, c, p],
(ic, c') ← ic.mk_bit0 c,
return (ic, c', p)
| _, bit0 b := do
(ic, c, p) ← prove_mul_nat ic a b,
(ic, p) ← ic.mk_app ``mul_bit0' [a, b, c, p],
(ic, c') ← ic.mk_bit0 c,
return (ic, c', p)
| bit1 a, bit1 b := do
(ic, c, pc) ← prove_mul_nat ic a b,
(ic, d, pd) ← prove_add_nat' ic a b,
(ic, c') ← ic.mk_bit0 c,
(ic, e, pe) ← prove_add_nat' ic c' d,
(ic, p) ← ic.mk_app ``mul_bit1_bit1 [a, b, c, d, e, pc, pd, pe],
(ic, e') ← ic.mk_bit1 e,
return (ic, e', p)
| _, _ := failed
end
end
section
open match_numeral_result
/-- Given `a` a positive natural numeral, returns `⊢ 0 < a`. -/
meta def prove_pos_nat (c : instance_cache) : expr → tactic (instance_cache × expr)
| e :=
match match_numeral e with
| one := c.mk_app ``zero_lt_one' []
| bit0 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit0_pos [e, p]
| bit1 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit1_pos' [e, p]
| _ := failed
end
end
/-- Given `a` a rational numeral, returns `⊢ 0 < a`. -/
meta def prove_pos (c : instance_cache) : expr → tactic (instance_cache × expr)
| `(%%e₁ / %%e₂) := do
(c, p₁) ← prove_pos_nat c e₁, (c, p₂) ← prove_pos_nat c e₂,
c.mk_app ``div_pos [e₁, e₂, p₁, p₂]
| e := prove_pos_nat c e
/-- `match_neg (- e) = some e`, otherwise `none` -/
meta def match_neg : expr → option expr
| `(- %%e) := some e
| _ := none
/-- `match_sign (- e) = inl e`, `match_sign 0 = inr ff`, otherwise `inr tt` -/
meta def match_sign : expr → expr ⊕ bool
| `(- %%e) := sum.inl e
| `(has_zero.zero) := sum.inr ff
| _ := sum.inr tt
theorem ne_zero_of_pos {α} [ordered_add_comm_group α] (a : α) : 0 < a → a ≠ 0 := ne_of_gt
theorem ne_zero_neg {α} [add_group α] (a : α) : a ≠ 0 → -a ≠ 0 := mt neg_eq_zero.1
/-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/
meta def prove_ne_zero' (c : instance_cache) : expr → tactic (instance_cache × expr)
| a :=
match match_neg a with
| some a := do (c, p) ← prove_ne_zero' a, c.mk_app ``ne_zero_neg [a, p]
| none := do (c, p) ← prove_pos c a, c.mk_app ``ne_zero_of_pos [a, p]
end
theorem clear_denom_div {α} [division_ring α] (a b b' c d : α)
(h₀ : b ≠ 0) (h₁ : b * b' = d) (h₂ : a * b' = c) : (a / b) * d = c :=
by rwa [← h₁, ← mul_assoc, div_mul_cancel _ h₀]
/-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`.
(`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/
meta def prove_clear_denom'
(prove_ne_zero : instance_cache → expr → ℚ → tactic (instance_cache × expr))
(c : instance_cache) (a d : expr) (na : ℚ) (nd : ℕ) :
tactic (instance_cache × expr × expr) :=
if na.denom = 1 then
prove_mul_nat c a d
else do
[_, _, a, b] ← return a.get_app_args,
(c, b') ← c.of_nat (nd / na.denom),
(c, p₀) ← prove_ne_zero c b (rat.of_int na.denom),
(c, _, p₁) ← prove_mul_nat c b b',
(c, r, p₂) ← prove_mul_nat c a b',
(c, p) ← c.mk_app ``clear_denom_div [a, b, b', r, d, p₀, p₁, p₂],
return (c, r, p)
theorem nonneg_pos {α} [ordered_cancel_add_comm_monoid α] (a : α) : 0 < a → 0 ≤ a := le_of_lt
theorem lt_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 < bit0 a :=
lt_of_lt_of_le one_lt_two (bit0_le_bit0.2 h)
theorem lt_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 < bit1 a :=
one_lt_bit1.2 h
theorem lt_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit0 a < bit0 b :=
bit0_lt_bit0.2
theorem lt_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a < bit1 b :=
lt_of_le_of_lt (bit0_le_bit0.2 h) (lt_add_one _)
theorem lt_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a < bit0 b :=
lt_of_lt_of_le (by simp [bit0, bit1, zero_lt_one, add_assoc]) (bit0_le_bit0.2 h)
theorem lt_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit1 a < bit1 b :=
bit1_lt_bit1.2
theorem le_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 ≤ bit0 a :=
le_of_lt (lt_one_bit0 _ h)
-- deliberately strong hypothesis because bit1 0 is not a numeral
theorem le_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 ≤ bit1 a :=
le_of_lt (lt_one_bit1 _ h)
theorem le_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit0 a ≤ bit0 b :=
bit0_le_bit0.2
theorem le_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a ≤ bit1 b :=
le_of_lt (lt_bit0_bit1 _ _ h)
theorem le_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a ≤ bit0 b :=
le_of_lt (lt_bit1_bit0 _ _ h)
theorem le_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit1 a ≤ bit1 b :=
bit1_le_bit1.2
theorem sle_one_bit0 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit0 a :=
bit0_le_bit0.2
theorem sle_one_bit1 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit1 a :=
le_bit0_bit1 _ _
theorem sle_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a + 1 ≤ b → bit0 a + 1 ≤ bit0 b :=
le_bit1_bit0 _ _
theorem sle_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a + 1 ≤ bit1 b :=
bit1_le_bit1.2 h
theorem sle_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) :
bit1 a + 1 ≤ bit0 b :=
(bit1_succ a _ rfl).symm ▸ bit0_le_bit0.2 h
theorem sle_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) :
bit1 a + 1 ≤ bit1 b :=
(bit1_succ a _ rfl).symm ▸ le_bit0_bit1 _ _ h
/-- Given `a` a rational numeral, returns `⊢ 0 ≤ a`. -/
meta def prove_nonneg (ic : instance_cache) : expr → tactic (instance_cache × expr)
| e@`(has_zero.zero) := ic.mk_app ``le_refl [e]
| e :=
if ic.α = `(ℕ) then
return (ic, `(nat.zero_le).mk_app [e])
else do
(ic, p) ← prove_pos ic e,
ic.mk_app ``nonneg_pos [e, p]
section
open match_numeral_result
/-- Given `a` a rational numeral, returns `⊢ 1 ≤ a`. -/
meta def prove_one_le_nat (ic : instance_cache) : expr → tactic (instance_cache × expr)
| a :=
match match_numeral a with
| one := ic.mk_app ``le_refl [a]
| bit0 a := do (ic, p) ← prove_one_le_nat a, ic.mk_app ``le_one_bit0 [a, p]
| bit1 a := do (ic, p) ← prove_pos_nat ic a, ic.mk_app ``le_one_bit1 [a, p]
| _ := failed
end
meta mutual def prove_le_nat, prove_sle_nat (ic : instance_cache)
with prove_le_nat : expr → expr → tactic (instance_cache × expr)
| a b :=
if a = b then ic.mk_app ``le_refl [a] else
match match_numeral a, match_numeral b with
| zero, _ := prove_nonneg ic b
| one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``le_one_bit0 [b, p]
| one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``le_one_bit1 [b, p]
| bit0 a, bit0 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit0 [a, b, p]
| bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit1 [a, b, p]
| bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``le_bit1_bit0 [a, b, p]
| bit1 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit1_bit1 [a, b, p]
| _, _ := failed
end
with prove_sle_nat : expr → expr → tactic (instance_cache × expr)
| a b :=
match match_numeral a, match_numeral b with
| zero, _ := prove_nonneg ic b
| one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit0 [b, p]
| one, bit1 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit1 [b, p]
| bit0 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit0_bit0 [a, b, p]
| bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``sle_bit0_bit1 [a, b, p]
| bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit0 [a, b, p]
| bit1 a, bit1 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit1 [a, b, p]
| _, _ := failed
end
/-- Given `a`,`b` natural numerals, proves `⊢ a ≤ b`. -/
add_decl_doc prove_le_nat
/-- Given `a`,`b` natural numerals, proves `⊢ a + 1 ≤ b`. -/
add_decl_doc prove_sle_nat
/-- Given `a`,`b` natural numerals, proves `⊢ a < b`. -/
meta def prove_lt_nat (ic : instance_cache) : expr → expr → tactic (instance_cache × expr)
| a b :=
match match_numeral a, match_numeral b with
| zero, _ := prove_pos ic b
| one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``lt_one_bit0 [b, p]
| one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``lt_one_bit1 [b, p]
| bit0 a, bit0 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit0_bit0 [a, b, p]
| bit0 a, bit1 b := do (ic, p) ← prove_le_nat ic a b, ic.mk_app ``lt_bit0_bit1 [a, b, p]
| bit1 a, bit0 b := do (ic, p) ← prove_sle_nat ic a b, ic.mk_app ``lt_bit1_bit0 [a, b, p]
| bit1 a, bit1 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit1_bit1 [a, b, p]
| _, _ := failed
end
end
theorem clear_denom_lt {α} [linear_ordered_semiring α] (a a' b b' d : α)
(h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' < b') : a < b :=
lt_of_mul_lt_mul_right (by rwa [ha, hb]) (le_of_lt h₀)
/-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a < b`. -/
meta def prove_lt_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr) :=
if na.denom = 1 ∧ nb.denom = 1 then
prove_lt_nat ic a b
else do
let nd := na.denom.lcm nb.denom,
(ic, d) ← ic.of_nat nd,
(ic, p₀) ← prove_pos ic d,
(ic, a', pa) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic a d na nd,
(ic, b', pb) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic b d nb nd,
(ic, p) ← prove_lt_nat ic a' b',
ic.mk_app ``clear_denom_lt [a, a', b, b', d, p₀, pa, pb, p]
lemma lt_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 < a) (hb : 0 < b) : -a < b :=
lt_trans (neg_neg_of_pos ha) hb
/-- Given `a`,`b` rational numerals, proves `⊢ a < b`. -/
meta def prove_lt_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr) :=
match match_sign a, match_sign b with
| sum.inl a, sum.inl b := do
-- we have to switch the order of `a` and `b` because `a < b ↔ -b < -a`
(ic, p) ← prove_lt_nonneg_rat ic b a (-nb) (-na),
ic.mk_app ``neg_lt_neg [b, a, p]
| sum.inl a, sum.inr ff := do
(ic, p) ← prove_pos ic a,
ic.mk_app ``neg_neg_of_pos [a, p]
| sum.inl a, sum.inr tt := do
(ic, pa) ← prove_pos ic a,
(ic, pb) ← prove_pos ic b,
ic.mk_app ``lt_neg_pos [a, b, pa, pb]
| sum.inr ff, _ := prove_pos ic b
| sum.inr tt, _ := prove_lt_nonneg_rat ic a b na nb
end
theorem clear_denom_le {α} [linear_ordered_semiring α] (a a' b b' d : α)
(h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' ≤ b') : a ≤ b :=
le_of_mul_le_mul_right (by rwa [ha, hb]) h₀
/-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a ≤ b`. -/
meta def prove_le_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr) :=
if na.denom = 1 ∧ nb.denom = 1 then
prove_le_nat ic a b
else do
let nd := na.denom.lcm nb.denom,
(ic, d) ← ic.of_nat nd,
(ic, p₀) ← prove_pos ic d,
(ic, a', pa) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic a d na nd,
(ic, b', pb) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic b d nb nd,
(ic, p) ← prove_le_nat ic a' b',
ic.mk_app ``clear_denom_le [a, a', b, b', d, p₀, pa, pb, p]
lemma le_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 ≤ a) (hb : 0 ≤ b) : -a ≤ b :=
le_trans (neg_nonpos_of_nonneg ha) hb
/-- Given `a`,`b` rational numerals, proves `⊢ a ≤ b`. -/
meta def prove_le_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr) :=
match match_sign a, match_sign b with
| sum.inl a, sum.inl b := do
(ic, p) ← prove_le_nonneg_rat ic a b (-na) (-nb),
ic.mk_app ``neg_le_neg [a, b, p]
| sum.inl a, sum.inr ff := do
(ic, p) ← prove_nonneg ic a,
ic.mk_app ``neg_nonpos_of_nonneg [a, p]
| sum.inl a, sum.inr tt := do
(ic, pa) ← prove_nonneg ic a,
(ic, pb) ← prove_nonneg ic b,
ic.mk_app ``le_neg_pos [a, b, pa, pb]
| sum.inr ff, _ := prove_nonneg ic b
| sum.inr tt, _ := prove_le_nonneg_rat ic a b na nb
end
/-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. This version tries to prove
`⊢ a < b` or `⊢ b < a`, and so is not appropriate for types without an order relation. -/
meta def prove_ne_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr) :=
if na < nb then do
(ic, p) ← prove_lt_rat ic a b na nb,
ic.mk_app ``ne_of_lt [a, b, p]
else do
(ic, p) ← prove_lt_rat ic b a nb na,
ic.mk_app ``ne_of_gt [a, b, p]
theorem nat_cast_zero {α} [semiring α] : ↑(0 : ℕ) = (0 : α) := nat.cast_zero
theorem nat_cast_one {α} [semiring α] : ↑(1 : ℕ) = (1 : α) := nat.cast_one
theorem nat_cast_bit0 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' :=
h ▸ nat.cast_bit0 _
theorem nat_cast_bit1 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' :=
h ▸ nat.cast_bit1 _
theorem int_cast_zero {α} [ring α] : ↑(0 : ℤ) = (0 : α) := int.cast_zero
theorem int_cast_one {α} [ring α] : ↑(1 : ℤ) = (1 : α) := int.cast_one
theorem int_cast_bit0 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' :=
h ▸ int.cast_bit0 _
theorem int_cast_bit1 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' :=
h ▸ int.cast_bit1 _
theorem rat_cast_bit0 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') :
↑(bit0 a) = bit0 a' :=
h ▸ rat.cast_bit0 _
theorem rat_cast_bit1 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') :
↑(bit1 a) = bit1 a' :=
h ▸ rat.cast_bit1 _
/-- Given `a' : α` a natural numeral, returns `(a : ℕ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_nat_uncast (ic nc : instance_cache) : ∀ (a' : expr),
tactic (instance_cache × instance_cache × expr × expr)
| a' :=
match match_numeral a' with
| match_numeral_result.zero := do
(nc, e) ← nc.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``nat_cast_zero [],
return (ic, nc, e, p)
| match_numeral_result.one := do
(nc, e) ← nc.mk_app ``has_one.one [],
(ic, p) ← ic.mk_app ``nat_cast_one [],
return (ic, nc, e, p)
| match_numeral_result.bit0 a' := do
(ic, nc, a, p) ← prove_nat_uncast a',
(nc, a0) ← nc.mk_bit0 a,
(ic, p) ← ic.mk_app ``nat_cast_bit0 [a, a', p],
return (ic, nc, a0, p)
| match_numeral_result.bit1 a' := do
(ic, nc, a, p) ← prove_nat_uncast a',
(nc, a1) ← nc.mk_bit1 a,
(ic, p) ← ic.mk_app ``nat_cast_bit1 [a, a', p],
return (ic, nc, a1, p)
| _ := failed
end
/-- Given `a' : α` a natural numeral, returns `(a : ℤ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_int_uncast_nat (ic zc : instance_cache) : ∀ (a' : expr),
tactic (instance_cache × instance_cache × expr × expr)
| a' :=
match match_numeral a' with
| match_numeral_result.zero := do
(zc, e) ← zc.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``int_cast_zero [],
return (ic, zc, e, p)
| match_numeral_result.one := do
(zc, e) ← zc.mk_app ``has_one.one [],
(ic, p) ← ic.mk_app ``int_cast_one [],
return (ic, zc, e, p)
| match_numeral_result.bit0 a' := do
(ic, zc, a, p) ← prove_int_uncast_nat a',
(zc, a0) ← zc.mk_bit0 a,
(ic, p) ← ic.mk_app ``int_cast_bit0 [a, a', p],
return (ic, zc, a0, p)
| match_numeral_result.bit1 a' := do
(ic, zc, a, p) ← prove_int_uncast_nat a',
(zc, a1) ← zc.mk_bit1 a,
(ic, p) ← ic.mk_app ``int_cast_bit1 [a, a', p],
return (ic, zc, a1, p)
| _ := failed
end
/-- Given `a' : α` a natural numeral, returns `(a : ℚ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_rat_uncast_nat (ic qc : instance_cache) (cz_inst : expr) : ∀ (a' : expr),
tactic (instance_cache × instance_cache × expr × expr)
| a' :=
match match_numeral a' with
| match_numeral_result.zero := do
(qc, e) ← qc.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``rat.cast_zero [],
return (ic, qc, e, p)
| match_numeral_result.one := do
(qc, e) ← qc.mk_app ``has_one.one [],
(ic, p) ← ic.mk_app ``rat.cast_one [],
return (ic, qc, e, p)
| match_numeral_result.bit0 a' := do
(ic, qc, a, p) ← prove_rat_uncast_nat a',
(qc, a0) ← qc.mk_bit0 a,
(ic, p) ← ic.mk_app ``rat_cast_bit0 [cz_inst, a, a', p],
return (ic, qc, a0, p)
| match_numeral_result.bit1 a' := do
(ic, qc, a, p) ← prove_rat_uncast_nat a',
(qc, a1) ← qc.mk_bit1 a,
(ic, p) ← ic.mk_app ``rat_cast_bit1 [cz_inst, a, a', p],
return (ic, qc, a1, p)
| _ := failed
end
theorem rat_cast_div {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α)
(ha : ↑a = a') (hb : ↑b = b') : ↑(a / b) = a' / b' :=
ha ▸ hb ▸ rat.cast_div _ _
/-- Given `a' : α` a nonnegative rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_rat_uncast_nonneg (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) :
tactic (instance_cache × instance_cache × expr × expr) :=
if na'.denom = 1 then
prove_rat_uncast_nat ic qc cz_inst a'
else do
[_, _, a', b'] ← return a'.get_app_args,
(ic, qc, a, pa) ← prove_rat_uncast_nat ic qc cz_inst a',
(ic, qc, b, pb) ← prove_rat_uncast_nat ic qc cz_inst b',
(qc, e) ← qc.mk_app ``has_div.div [a, b],
(ic, p) ← ic.mk_app ``rat_cast_div [cz_inst, a, b, a', b', pa, pb],
return (ic, qc, e, p)
theorem int_cast_neg {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑-a = -a' :=
h ▸ int.cast_neg _
theorem rat_cast_neg {α} [division_ring α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑-a = -a' :=
h ▸ rat.cast_neg _
/-- Given `a' : α` an integer numeral, returns `(a : ℤ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_int_uncast (ic zc : instance_cache) (a' : expr) :
tactic (instance_cache × instance_cache × expr × expr) :=
match match_neg a' with
| some a' := do
(ic, zc, a, p) ← prove_int_uncast_nat ic zc a',
(zc, e) ← zc.mk_app ``has_neg.neg [a],
(ic, p) ← ic.mk_app ``int_cast_neg [a, a', p],
return (ic, zc, e, p)
| none := prove_int_uncast_nat ic zc a'
end
/-- Given `a' : α` a rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_rat_uncast (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) :
tactic (instance_cache × instance_cache × expr × expr) :=
match match_neg a' with
| some a' := do
(ic, qc, a, p) ← prove_rat_uncast_nonneg ic qc cz_inst a' (-na'),
(qc, e) ← qc.mk_app ``has_neg.neg [a],
(ic, p) ← ic.mk_app ``rat_cast_neg [a, a', p],
return (ic, qc, e, p)
| none := prove_rat_uncast_nonneg ic qc cz_inst a' na'
end
theorem nat_cast_ne {α} [semiring α] [char_zero α] (a b : ℕ) (a' b' : α)
(ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' :=
ha ▸ hb ▸ mt nat.cast_inj.1 h
theorem int_cast_ne {α} [ring α] [char_zero α] (a b : ℤ) (a' b' : α)
(ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' :=
ha ▸ hb ▸ mt int.cast_inj.1 h
theorem rat_cast_ne {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α)
(ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' :=
ha ▸ hb ▸ mt rat.cast_inj.1 h
/-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. Currently it tries two methods:
* Prove `⊢ a < b` or `⊢ b < a`, if the base type has an order
* Embed `↑(a':ℚ) = a` and `↑(b':ℚ) = b`, and then prove `a' ≠ b'`.
This requires that the base type be `char_zero`, and also that it be a `division_ring`
so that the coercion from `ℚ` is well defined.
We may also add coercions to `ℤ` and `ℕ` as well in order to support `char_zero`
rings and semirings. -/
meta def prove_ne : instance_cache → expr → expr → ℚ → ℚ → tactic (instance_cache × expr)
| ic a b na nb := prove_ne_rat ic a b na nb <|> do
cz_inst ← mk_mapp ``char_zero [ic.α, none, none] >>= mk_instance,
if na.denom = 1 ∧ nb.denom = 1 then
if na ≥ 0 ∧ nb ≥ 0 then do
guard (ic.α ≠ `(ℕ)),
nc ← mk_instance_cache `(ℕ),
(ic, nc, a', pa) ← prove_nat_uncast ic nc a,
(ic, nc, b', pb) ← prove_nat_uncast ic nc b,
(nc, p) ← prove_ne_rat nc a' b' na nb,
ic.mk_app ``nat_cast_ne [cz_inst, a', b', a, b, pa, pb, p]
else do
guard (ic.α ≠ `(ℤ)),
zc ← mk_instance_cache `(ℤ),
(ic, zc, a', pa) ← prove_int_uncast ic zc a,
(ic, zc, b', pb) ← prove_int_uncast ic zc b,
(zc, p) ← prove_ne_rat zc a' b' na nb,
ic.mk_app ``int_cast_ne [cz_inst, a', b', a, b, pa, pb, p]
else do
guard (ic.α ≠ `(ℚ)),
qc ← mk_instance_cache `(ℚ),
(ic, qc, a', pa) ← prove_rat_uncast ic qc cz_inst a na,
(ic, qc, b', pb) ← prove_rat_uncast ic qc cz_inst b nb,
(qc, p) ← prove_ne_rat qc a' b' na nb,
ic.mk_app ``rat_cast_ne [cz_inst, a', b', a, b, pa, pb, p]
/-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/
meta def prove_ne_zero (ic : instance_cache) : expr → ℚ → tactic (instance_cache × expr)
| a na := do
(ic, z) ← ic.mk_app ``has_zero.zero [],
prove_ne ic a z na 0
/-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`.
(`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/
meta def prove_clear_denom : instance_cache → expr → expr → ℚ → ℕ →
tactic (instance_cache × expr × expr) := prove_clear_denom' prove_ne_zero
theorem clear_denom_add {α} [division_ring α] (a a' b b' c c' d : α)
(h₀ : d ≠ 0) (ha : a * d = a') (hb : b * d = b') (hc : c * d = c')
(h : a' + b' = c') : a + b = c :=
mul_right_cancel₀ h₀ $ by rwa [add_mul, ha, hb, hc]
/-- Given `a`,`b`,`c` nonnegative rational numerals, returns `⊢ a + b = c`. -/
meta def prove_add_nonneg_rat (ic : instance_cache) (a b c : expr) (na nb nc : ℚ) :
tactic (instance_cache × expr) :=
if na.denom = 1 ∧ nb.denom = 1 then
prove_add_nat ic a b c
else do
let nd := na.denom.lcm nb.denom,
(ic, d) ← ic.of_nat nd,
(ic, p₀) ← prove_ne_zero ic d (rat.of_int nd),
(ic, a', pa) ← prove_clear_denom ic a d na nd,
(ic, b', pb) ← prove_clear_denom ic b d nb nd,
(ic, c', pc) ← prove_clear_denom ic c d nc nd,
(ic, p) ← prove_add_nat ic a' b' c',
ic.mk_app ``clear_denom_add [a, a', b, b', c, c', d, p₀, pa, pb, pc, p]
theorem add_pos_neg_pos {α} [add_group α] (a b c : α) (h : c + b = a) : a + -b = c :=
h ▸ by simp
theorem add_pos_neg_neg {α} [add_group α] (a b c : α) (h : c + a = b) : a + -b = -c :=
h ▸ by simp
theorem add_neg_pos_pos {α} [add_group α] (a b c : α) (h : a + c = b) : -a + b = c :=
h ▸ by simp
theorem add_neg_pos_neg {α} [add_group α] (a b c : α) (h : b + c = a) : -a + b = -c :=
h ▸ by simp
theorem add_neg_neg {α} [add_group α] (a b c : α) (h : b + a = c) : -a + -b = -c :=
h ▸ by simp
/-- Given `a`,`b`,`c` rational numerals, returns `⊢ a + b = c`. -/
meta def prove_add_rat (ic : instance_cache) (ea eb ec : expr) (a b c : ℚ) :
tactic (instance_cache × expr) :=
match match_neg ea, match_neg eb, match_neg ec with
| some ea, some eb, some ec := do
(ic, p) ← prove_add_nonneg_rat ic eb ea ec (-b) (-a) (-c),
ic.mk_app ``add_neg_neg [ea, eb, ec, p]
| some ea, none, some ec := do
(ic, p) ← prove_add_nonneg_rat ic eb ec ea b (-c) (-a),
ic.mk_app ``add_neg_pos_neg [ea, eb, ec, p]
| some ea, none, none := do
(ic, p) ← prove_add_nonneg_rat ic ea ec eb (-a) c b,
ic.mk_app ``add_neg_pos_pos [ea, eb, ec, p]
| none, some eb, some ec := do
(ic, p) ← prove_add_nonneg_rat ic ec ea eb (-c) a (-b),
ic.mk_app ``add_pos_neg_neg [ea, eb, ec, p]
| none, some eb, none := do
(ic, p) ← prove_add_nonneg_rat ic ec eb ea c (-b) a,
ic.mk_app ``add_pos_neg_pos [ea, eb, ec, p]
| _, _, _ := prove_add_nonneg_rat ic ea eb ec a b c
end
/-- Given `a`,`b` rational numerals, returns `(c, ⊢ a + b = c)`. -/
meta def prove_add_rat' (ic : instance_cache) (a b : expr) :
tactic (instance_cache × expr × expr) :=
do na ← a.to_rat,
nb ← b.to_rat,
let nc := na + nb,
(ic, c) ← ic.of_rat nc,
(ic, p) ← prove_add_rat ic a b c na nb nc,
return (ic, c, p)
theorem clear_denom_simple_nat {α} [division_ring α] (a : α) :
(1:α) ≠ 0 ∧ a * 1 = a := ⟨one_ne_zero, mul_one _⟩
theorem clear_denom_simple_div {α} [division_ring α] (a b : α) (h : b ≠ 0) :
b ≠ 0 ∧ a / b * b = a := ⟨h, div_mul_cancel _ h⟩
/-- Given `a` a nonnegative rational numeral, returns `(b, c, ⊢ a * b = c)`
where `b` and `c` are natural numerals. (`b` will be the denominator of `a`.) -/
meta def prove_clear_denom_simple (c : instance_cache) (a : expr) (na : ℚ) :
tactic (instance_cache × expr × expr × expr) :=
if na.denom = 1 then do
(c, d) ← c.mk_app ``has_one.one [],
(c, p) ← c.mk_app ``clear_denom_simple_nat [a],
return (c, d, a, p)
else do
[α, _, a, b] ← return a.get_app_args,
(c, p₀) ← prove_ne_zero c b (rat.of_int na.denom),
(c, p) ← c.mk_app ``clear_denom_simple_div [a, b, p₀],
return (c, b, a, p)
theorem clear_denom_mul {α} [field α] (a a' b b' c c' d₁ d₂ d : α)
(ha : d₁ ≠ 0 ∧ a * d₁ = a') (hb : d₂ ≠ 0 ∧ b * d₂ = b')
(hc : c * d = c') (hd : d₁ * d₂ = d)
(h : a' * b' = c') : a * b = c :=
mul_right_cancel₀ ha.1 $ mul_right_cancel₀ hb.1 $
by rw [mul_assoc c, hd, hc, ← h, ← ha.2, ← hb.2, ← mul_assoc, mul_right_comm a]
/-- Given `a`,`b` nonnegative rational numerals, returns `(c, ⊢ a * b = c)`. -/
meta def prove_mul_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr × expr) :=
if na.denom = 1 ∧ nb.denom = 1 then
prove_mul_nat ic a b
else do
let nc := na * nb, (ic, c) ← ic.of_rat nc,
(ic, d₁, a', pa) ← prove_clear_denom_simple ic a na,
(ic, d₂, b', pb) ← prove_clear_denom_simple ic b nb,
(ic, d, pd) ← prove_mul_nat ic d₁ d₂, nd ← d.to_nat,
(ic, c', pc) ← prove_clear_denom ic c d nc nd,
(ic, _, p) ← prove_mul_nat ic a' b',
(ic, p) ← ic.mk_app ``clear_denom_mul [a, a', b, b', c, c', d₁, d₂, d, pa, pb, pc, pd, p],
return (ic, c, p)
theorem mul_neg_pos {α} [ring α] (a b c : α) (h : a * b = c) : -a * b = -c := h ▸ by simp
theorem mul_pos_neg {α} [ring α] (a b c : α) (h : a * b = c) : a * -b = -c := h ▸ by simp
theorem mul_neg_neg {α} [ring α] (a b c : α) (h : a * b = c) : -a * -b = c := h ▸ by simp
/-- Given `a`,`b` rational numerals, returns `(c, ⊢ a * b = c)`. -/
meta def prove_mul_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr × expr) :=
match match_sign a, match_sign b with
| sum.inl a, sum.inl b := do
(ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) (-nb),
(ic, p) ← ic.mk_app ``mul_neg_neg [a, b, c, p],
return (ic, c, p)
| sum.inr ff, _ := do
(ic, z) ← ic.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``zero_mul [b],
return (ic, z, p)
| _, sum.inr ff := do
(ic, z) ← ic.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``mul_zero [a],
return (ic, z, p)
| sum.inl a, sum.inr tt := do
(ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) nb,
(ic, p) ← ic.mk_app ``mul_neg_pos [a, b, c, p],
(ic, c') ← ic.mk_app ``has_neg.neg [c],
return (ic, c', p)
| sum.inr tt, sum.inl b := do
(ic, c, p) ← prove_mul_nonneg_rat ic a b na (-nb),
(ic, p) ← ic.mk_app ``mul_pos_neg [a, b, c, p],
(ic, c') ← ic.mk_app ``has_neg.neg [c],
return (ic, c', p)
| sum.inr tt, sum.inr tt := prove_mul_nonneg_rat ic a b na nb
end
theorem inv_neg {α} [division_ring α] (a b : α) (h : a⁻¹ = b) : (-a)⁻¹ = -b :=
h ▸ by simp only [inv_eq_one_div, one_div_neg_eq_neg_one_div]
theorem inv_one {α} [division_ring α] : (1 : α)⁻¹ = 1 := inv_one
theorem inv_one_div {α} [division_ring α] (a : α) : (1 / a)⁻¹ = a :=
by rw [one_div, inv_inv]
theorem inv_div_one {α} [division_ring α] (a : α) : a⁻¹ = 1 / a :=
inv_eq_one_div _
theorem inv_div {α} [division_ring α] (a b : α) : (a / b)⁻¹ = b / a :=
by simp only [inv_eq_one_div, one_div_div]
/-- Given `a` a rational numeral, returns `(b, ⊢ a⁻¹ = b)`. -/
meta def prove_inv : instance_cache → expr → ℚ → tactic (instance_cache × expr × expr)
| ic e n :=
match match_sign e with
| sum.inl e := do
(ic, e', p) ← prove_inv ic e (-n),
(ic, r) ← ic.mk_app ``has_neg.neg [e'],
(ic, p) ← ic.mk_app ``inv_neg [e, e', p],
return (ic, r, p)
| sum.inr ff := do
(ic, p) ← ic.mk_app ``inv_zero [],
return (ic, e, p)
| sum.inr tt :=
if n.num = 1 then
if n.denom = 1 then do
(ic, p) ← ic.mk_app ``inv_one [],
return (ic, e, p)
else do
let e := e.app_arg,
(ic, p) ← ic.mk_app ``inv_one_div [e],
return (ic, e, p)
else if n.denom = 1 then do
(ic, p) ← ic.mk_app ``inv_div_one [e],
e ← infer_type p,
return (ic, e.app_arg, p)
else do
[_, _, a, b] ← return e.get_app_args,
(ic, e') ← ic.mk_app ``has_div.div [b, a],
(ic, p) ← ic.mk_app ``inv_div [a, b],
return (ic, e', p)
end
theorem div_eq {α} [division_ring α] (a b b' c : α)
(hb : b⁻¹ = b') (h : a * b' = c) : a / b = c :=
by rwa [ ← hb, ← div_eq_mul_inv] at h
/-- Given `a`,`b` rational numerals, returns `(c, ⊢ a / b = c)`. -/
meta def prove_div (ic : instance_cache) (a b : expr) (na nb : ℚ) :
tactic (instance_cache × expr × expr) :=
do (ic, b', pb) ← prove_inv ic b nb,
(ic, c, p) ← prove_mul_rat ic a b' na nb⁻¹,
(ic, p) ← ic.mk_app ``div_eq [a, b, b', c, pb, p],
return (ic, c, p)
/-- Given `a` a rational numeral, returns `(b, ⊢ -a = b)`. -/
meta def prove_neg (ic : instance_cache) (a : expr) : tactic (instance_cache × expr × expr) :=
match match_sign a with
| sum.inl a := do
(ic, p) ← ic.mk_app ``neg_neg [a],
return (ic, a, p)
| sum.inr ff := do
(ic, p) ← ic.mk_app ``neg_zero [],
return (ic, a, p)
| sum.inr tt := do
(ic, a') ← ic.mk_app ``has_neg.neg [a],
p ← mk_eq_refl a',
return (ic, a', p)
end
theorem sub_pos {α} [add_group α] (a b b' c : α) (hb : -b = b') (h : a + b' = c) : a - b = c :=
by rwa [← hb, ← sub_eq_add_neg] at h
theorem sub_neg {α} [add_group α] (a b c : α) (h : a + b = c) : a - -b = c :=
by rwa sub_neg_eq_add
/-- Given `a`,`b` rational numerals, returns `(c, ⊢ a - b = c)`. -/
meta def prove_sub (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) :=
match match_sign b with
| sum.inl b := do
(ic, c, p) ← prove_add_rat' ic a b,
(ic, p) ← ic.mk_app ``sub_neg [a, b, c, p],
return (ic, c, p)
| sum.inr ff := do
(ic, p) ← ic.mk_app ``sub_zero [a],
return (ic, a, p)
| sum.inr tt := do
(ic, b', pb) ← prove_neg ic b,
(ic, c, p) ← prove_add_rat' ic a b',
(ic, p) ← ic.mk_app ``sub_pos [a, b, b', c, pb, p],
return (ic, c, p)
end
theorem sub_nat_pos (a b c : ℕ) (h : b + c = a) : a - b = c :=
h ▸ add_tsub_cancel_left _ _
theorem sub_nat_neg (a b c : ℕ) (h : a + c = b) : a - b = 0 :=
tsub_eq_zero_iff_le.mpr $ h ▸ nat.le_add_right _ _
/-- Given `a : nat`,`b : nat` natural numerals, returns `(c, ⊢ a - b = c)`. -/
meta def prove_sub_nat (ic : instance_cache) (a b : expr) : tactic (expr × expr) :=
do na ← a.to_nat, nb ← b.to_nat,
if nb ≤ na then do
(ic, c) ← ic.of_nat (na - nb),
(ic, p) ← prove_add_nat ic b c a,
return (c, `(sub_nat_pos).mk_app [a, b, c, p])
else do
(ic, c) ← ic.of_nat (nb - na),
(ic, p) ← prove_add_nat ic a c b,
return (`(0 : ℕ), `(sub_nat_neg).mk_app [a, b, c, p])
/-- Evaluates the basic field operations `+`,`neg`,`-`,`*`,`inv`,`/` on numerals.
Also handles nat subtraction. Does not do recursive simplification; that is,
`1 + 1 + 1` will not simplify but `2 + 1` will. This is handled by the top level
`simp` call in `norm_num.derive`. -/
meta def eval_field : expr → tactic (expr × expr)
| `(%%e₁ + %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
let n₃ := n₁ + n₂,
(c, e₃) ← c.of_rat n₃,
(_, p) ← prove_add_rat c e₁ e₂ e₃ n₁ n₂ n₃,
return (e₃, p)
| `(%%e₁ * %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
prod.snd <$> prove_mul_rat c e₁ e₂ n₁ n₂
| `(- %%e) := do
c ← infer_type e >>= mk_instance_cache,
prod.snd <$> prove_neg c e
| `(@has_sub.sub %%α %%inst %%a %%b) := do
c ← mk_instance_cache α,
if α = `(nat) then prove_sub_nat c a b
else prod.snd <$> prove_sub c a b
| `(has_inv.inv %%e) := do
n ← e.to_rat,
c ← infer_type e >>= mk_instance_cache,
prod.snd <$> prove_inv c e n
| `(%%e₁ / %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
prod.snd <$> prove_div c e₁ e₂ n₁ n₂
| _ := failed
lemma pow_bit0 [monoid α] (a c' c : α) (b : ℕ)
(h : a ^ b = c') (h₂ : c' * c' = c) : a ^ bit0 b = c :=
h₂ ▸ by simp [pow_bit0, h]
lemma pow_bit1 [monoid α] (a c₁ c₂ c : α) (b : ℕ)
(h : a ^ b = c₁) (h₂ : c₁ * c₁ = c₂) (h₃ : c₂ * a = c) : a ^ bit1 b = c :=
by rw [← h₃, ← h₂]; simp [pow_bit1, h]
section
open match_numeral_result
/-- Given `a` a rational numeral and `b : nat`, returns `(c, ⊢ a ^ b = c)`. -/
meta def prove_pow (a : expr) (na : ℚ) :
instance_cache → expr → tactic (instance_cache × expr × expr)
| ic b :=
match match_numeral b with
| zero := do
(ic, p) ← ic.mk_app ``pow_zero [a],
(ic, o) ← ic.mk_app ``has_one.one [],
return (ic, o, p)
| one := do
(ic, p) ← ic.mk_app ``pow_one [a],
return (ic, a, p)
| bit0 b := do
(ic, c', p) ← prove_pow ic b,
nc' ← expr.to_rat c',
(ic, c, p₂) ← prove_mul_rat ic c' c' nc' nc',
(ic, p) ← ic.mk_app ``pow_bit0 [a, c', c, b, p, p₂],
return (ic, c, p)
| bit1 b := do
(ic, c₁, p) ← prove_pow ic b,
nc₁ ← expr.to_rat c₁,
(ic, c₂, p₂) ← prove_mul_rat ic c₁ c₁ nc₁ nc₁,
(ic, c, p₃) ← prove_mul_rat ic c₂ a (nc₁ * nc₁) na,
(ic, p) ← ic.mk_app ``pow_bit1 [a, c₁, c₂, c, b, p, p₂, p₃],
return (ic, c, p)
| _ := failed
end
end
lemma zpow_pos {α} [div_inv_monoid α] (a : α) (b : ℤ) (b' : ℕ) (c : α)
(hb : b = b') (h : a ^ b' = c) : a ^ b = c := by rw [← h, hb, zpow_coe_nat]
lemma zpow_neg {α} [div_inv_monoid α] (a : α) (b : ℤ) (b' : ℕ) (c c' : α)
(b0 : 0 < b') (hb : b = b') (h : a ^ b' = c) (hc : c⁻¹ = c') : a ^ -b = c' :=
by rw [← hc, ← h, hb, zpow_neg_coe_of_pos _ b0]
/-- Given `a` a rational numeral and `b : ℤ`, returns `(c, ⊢ a ^ b = c)`. -/
meta def prove_zpow (ic zc nc : instance_cache) (a : expr) (na : ℚ) (b : expr) :
tactic (instance_cache × instance_cache × instance_cache × expr × expr) :=
match match_sign b with
| sum.inl b := do
(zc, nc, b', hb) ← prove_nat_uncast zc nc b,
(ic, c, h) ← prove_pow a na ic b',
(ic, c', hc) ← c.to_rat >>= prove_inv ic c,
(ic, p) ← ic.mk_app ``zpow_neg [a, b, b', c, c', hb, h, hc],
pure (ic, zc, nc, c', p)
| sum.inr ff := do
(ic, o) ← ic.mk_app ``has_one.one [],
(ic, p) ← ic.mk_app ``zpow_zero [a],
pure (ic, zc, nc, o, p)
| sum.inr tt := do
(zc, nc, b', hb) ← prove_nat_uncast zc nc b,
(ic, c, h) ← prove_pow a na ic b',
(ic, p) ← ic.mk_app ``zpow_pos [a, b, b', c, hb, h],
pure (ic, zc, nc, c, p)
end
/-- Evaluates expressions of the form `a ^ b`, `monoid.npow a b` or `nat.pow a b`. -/
meta def eval_pow : expr → tactic (expr × expr)
| `(@has_pow.pow %%α _ %%m %%e₁ %%e₂) := do
n₁ ← e₁.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
match m with
| `(@monoid.has_pow %%_ %%_) := prod.snd <$> prove_pow e₁ n₁ c e₂
| `(@div_inv_monoid.has_pow %%_ %%_) := do
zc ← mk_instance_cache `(ℤ),
nc ← mk_instance_cache `(ℕ),
(prod.snd ∘ prod.snd ∘ prod.snd) <$> prove_zpow c zc nc e₁ n₁ e₂
| _ := failed
end
| `(monoid.npow %%e₁ %%e₂) := do
n₁ ← e₁.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
prod.snd <$> prove_pow e₁ n₁ c e₂
| `(div_inv_monoid.zpow %%e₁ %%e₂) := do
n₁ ← e₁.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
zc ← mk_instance_cache `(ℤ),
nc ← mk_instance_cache `(ℕ),
(prod.snd ∘ prod.snd ∘ prod.snd) <$> prove_zpow c zc nc e₁ n₁ e₂
| _ := failed
/-- Given `⊢ p`, returns `(true, ⊢ p = true)`. -/
meta def true_intro (p : expr) : tactic (expr × expr) :=
prod.mk `(true) <$> mk_app ``eq_true_intro [p]
/-- Given `⊢ ¬ p`, returns `(false, ⊢ p = false)`. -/
meta def false_intro (p : expr) : tactic (expr × expr) :=
prod.mk `(false) <$> mk_app ``eq_false_intro [p]
theorem not_refl_false_intro {α} (a : α) : (a ≠ a) = false :=
eq_false_intro $ not_not_intro rfl
/-- Evaluates the inequality operations `=`,`<`,`>`,`≤`,`≥`,`≠` on numerals. -/
meta def eval_ineq : expr → tactic (expr × expr)
| `(%%e₁ < %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ < n₂ then
do (_, p) ← prove_lt_rat c e₁ e₂ n₁ n₂, true_intro p
else if n₁ = n₂ then do
(_, p) ← c.mk_app ``lt_irrefl [e₁],
false_intro p
else do
(c, p') ← prove_lt_rat c e₂ e₁ n₂ n₁,
(_, p) ← c.mk_app ``not_lt_of_gt [e₁, e₂, p'],
false_intro p
| `(%%e₁ ≤ %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ ≤ n₂ then do
(_, p) ←
if n₁ = n₂ then c.mk_app ``le_refl [e₁]
else prove_le_rat c e₁ e₂ n₁ n₂,
true_intro p
else do
(c, p) ← prove_lt_rat c e₂ e₁ n₂ n₁,
(_, p) ← c.mk_app ``not_le_of_gt [e₁, e₂, p],
false_intro p
| `(%%e₁ = %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ = n₂ then mk_eq_refl e₁ >>= true_intro
else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, false_intro p
| `(%%e₁ > %%e₂) := mk_app ``has_lt.lt [e₂, e₁] >>= eval_ineq
| `(%%e₁ ≥ %%e₂) := mk_app ``has_le.le [e₂, e₁] >>= eval_ineq
| `(%%e₁ ≠ %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ = n₂ then
prod.mk `(false) <$> mk_app ``not_refl_false_intro [e₁]
else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, true_intro p
| _ := failed
theorem nat_succ_eq (a b c : ℕ) (h₁ : a = b) (h₂ : b + 1 = c) : nat.succ a = c := by rwa h₁
/-- Evaluates the expression `nat.succ ... (nat.succ n)` where `n` is a natural numeral.
(We could also just handle `nat.succ n` here and rely on `simp` to work bottom up, but we figure
that towers of successors coming from e.g. `induction` are a common case.) -/
meta def prove_nat_succ (ic : instance_cache) : expr → tactic (instance_cache × ℕ × expr × expr)
| `(nat.succ %%a) := do
(ic, n, b, p₁) ← prove_nat_succ a,
let n' := n + 1,
(ic, c) ← ic.of_nat n',
(ic, p₂) ← prove_add_nat ic b `(1) c,
return (ic, n', c, `(nat_succ_eq).mk_app [a, b, c, p₁, p₂])
| e := do
n ← e.to_nat,
p ← mk_eq_refl e,
return (ic, n, e, p)
lemma nat_div (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a / b = q :=
by rw [← h, ← hm, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) h₂),
nat.div_eq_of_lt h₂, zero_add]
lemma int_div (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) :
a / b = q :=
by rw [← h, ← hm, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt h₁ h₂)),
int.div_eq_zero_of_lt h₁ h₂, zero_add]
lemma nat_mod (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a % b = r :=
by rw [← h, ← hm, nat.add_mul_mod_self_right, nat.mod_eq_of_lt h₂]
lemma int_mod (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) :
a % b = r :=
by rw [← h, ← hm, int.add_mul_mod_self, int.mod_eq_of_lt h₁ h₂]
lemma int_div_neg (a b c' c : ℤ) (h : a / b = c') (h₂ : -c' = c) : a / -b = c :=
h₂ ▸ h ▸ int.div_neg _ _
lemma int_mod_neg (a b c : ℤ) (h : a % b = c) : a % -b = c :=
(int.mod_neg _ _).trans h
/-- Given `a`,`b` numerals in `nat` or `int`,
* `prove_div_mod ic a b ff` returns `(c, ⊢ a / b = c)`
* `prove_div_mod ic a b tt` returns `(c, ⊢ a % b = c)`
-/
meta def prove_div_mod (ic : instance_cache) :
expr → expr → bool → tactic (instance_cache × expr × expr)
| a b mod :=
match match_neg b with
| some b := do
(ic, c', p) ← prove_div_mod a b mod,
if mod then
return (ic, c', `(int_mod_neg).mk_app [a, b, c', p])
else do
(ic, c, p₂) ← prove_neg ic c',
return (ic, c, `(int_div_neg).mk_app [a, b, c', c, p, p₂])
| none := do
nb ← b.to_nat,
na ← a.to_int,
let nq := na / nb,
let nr := na % nb,
let nm := nq * nr,
(ic, q) ← ic.of_int nq,
(ic, r) ← ic.of_int nr,
(ic, m, pm) ← prove_mul_rat ic q b (rat.of_int nq) (rat.of_int nb),
(ic, p) ← prove_add_rat ic r m a (rat.of_int nr) (rat.of_int nm) (rat.of_int na),
(ic, p') ← prove_lt_nat ic r b,
if ic.α = `(nat) then
if mod then return (ic, r, `(nat_mod).mk_app [a, b, q, r, m, pm, p, p'])
else return (ic, q, `(nat_div).mk_app [a, b, q, r, m, pm, p, p'])
else if ic.α = `(int) then do
(ic, p₀) ← prove_nonneg ic r,
if mod then return (ic, r, `(int_mod).mk_app [a, b, q, r, m, pm, p, p₀, p'])
else return (ic, q, `(int_div).mk_app [a, b, q, r, m, pm, p, p₀, p'])
else failed
end
theorem dvd_eq_nat (a b c : ℕ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p :=
(propext $ by rw [← h₁, nat.dvd_iff_mod_eq_zero]).trans h₂
theorem dvd_eq_int (a b c : ℤ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p :=
(propext $ by rw [← h₁, int.dvd_iff_mod_eq_zero]).trans h₂
theorem int_to_nat_pos (a : ℤ) (b : ℕ) (h : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = a) :
a.to_nat = b := by rw ← h; simp
theorem int_to_nat_neg (a : ℤ) (h : 0 < a) : (-a).to_nat = 0 :=
by simp only [int.to_nat_of_nonpos, h.le, neg_nonpos]
theorem nat_abs_pos (a : ℤ) (b : ℕ) (h : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = a) :
a.nat_abs = b := by rw ← h; simp
theorem nat_abs_neg (a : ℤ) (b : ℕ) (h : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = a) :
(-a).nat_abs = b := by rw ← h; simp
theorem neg_succ_of_nat (a b : ℕ) (c : ℤ) (h₁ : a + 1 = b)
(h₂ : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = c) :
-[1+ a] = -c := by rw [← h₂, ← h₁, int.nat_cast_eq_coe_nat]; refl
/-- Evaluates some extra numeric operations on `nat` and `int`, specifically
`nat.succ`, `/` and `%`, and `∣` (divisibility). -/
meta def eval_nat_int_ext : expr → tactic (expr × expr)
| e@`(nat.succ _) := do
ic ← mk_instance_cache `(ℕ),
(_, _, ep) ← prove_nat_succ ic e,
return ep
| `(%%a / %%b) := do
c ← infer_type a >>= mk_instance_cache,
prod.snd <$> prove_div_mod c a b ff
| `(%%a % %%b) := do
c ← infer_type a >>= mk_instance_cache,
prod.snd <$> prove_div_mod c a b tt
| `(%%a ∣ %%b) := do
α ← infer_type a,
ic ← mk_instance_cache α,
th ← if α = `(nat) then return (`(dvd_eq_nat):expr) else
if α = `(int) then return `(dvd_eq_int) else failed,
(ic, c, p₁) ← prove_div_mod ic b a tt,
(ic, z) ← ic.mk_app ``has_zero.zero [],
(e', p₂) ← mk_app ``eq [c, z] >>= eval_ineq,
return (e', th.mk_app [a, b, c, e', p₁, p₂])
| `(int.to_nat %%a) := do
n ← a.to_int,
ic ← mk_instance_cache `(ℤ),
if n ≥ 0 then do
nc ← mk_instance_cache `(ℕ),
(_, _, b, p) ← prove_nat_uncast ic nc a,
pure (b, `(int_to_nat_pos).mk_app [a, b, p])
else do
a ← match_neg a,
(_, p) ← prove_pos ic a,
pure (`(0), `(int_to_nat_neg).mk_app [a, p])
| `(int.nat_abs %%a) := do
n ← a.to_int,
ic ← mk_instance_cache `(ℤ),
nc ← mk_instance_cache `(ℕ),
if n ≥ 0 then do
(_, _, b, p) ← prove_nat_uncast ic nc a,
pure (b, `(nat_abs_pos).mk_app [a, b, p])
else do
a ← match_neg a,
(_, _, b, p) ← prove_nat_uncast ic nc a,
pure (b, `(nat_abs_neg).mk_app [a, b, p])
| `(int.neg_succ_of_nat %%a) := do
na ← a.to_nat,
ic ← mk_instance_cache `(ℤ),
nc ← mk_instance_cache `(ℕ),
let nb := na + 1,
(nc, b) ← nc.of_nat nb,
(nc, p₁) ← prove_add_nat nc a `(1) b,
(ic, c) ← ic.of_nat nb,
(_, _, _, p₂) ← prove_nat_uncast ic nc c,
pure (`(-%%c : ℤ), `(neg_succ_of_nat).mk_app [a, b, c, p₁, p₂])
| _ := failed
theorem int_to_nat_cast (a : ℕ) (b : ℤ)
(h : (by haveI := @nat.cast_coe ℤ; exact a : ℤ) = b) :
↑a = b := eq.trans (by simp) h
/-- Evaluates the `↑n` cast operation from `ℕ`, `ℤ`, `ℚ` to an arbitrary type `α`. -/
meta def eval_cast : expr → tactic (expr × expr)
| `(@coe ℕ %%α %%inst %%a) := do
if inst.is_app_of ``coe_to_lift then
if inst.app_arg.is_app_of ``nat.cast_coe then do
n ← a.to_nat,
ic ← mk_instance_cache α,
nc ← mk_instance_cache `(ℕ),
(ic, b) ← ic.of_nat n,
(_, _, _, p) ← prove_nat_uncast ic nc b,
pure (b, p)
else if inst.app_arg.is_app_of ``int.cast_coe then do
n ← a.to_int,
ic ← mk_instance_cache α,
zc ← mk_instance_cache `(ℤ),
(ic, b) ← ic.of_int n,
(_, _, _, p) ← prove_int_uncast ic zc b,
pure (b, p)
else if inst.app_arg.is_app_of ``int.cast_coe then do
n ← a.to_rat,
cz_inst ← mk_mapp ``char_zero [α, none, none] >>= mk_instance,
ic ← mk_instance_cache α,
qc ← mk_instance_cache `(ℚ),
(ic, b) ← ic.of_rat n,
(_, _, _, p) ← prove_rat_uncast ic qc cz_inst b n,
pure (b, p)
else failed
else if inst = `(@coe_base nat int int.has_coe) then do
n ← a.to_nat,
ic ← mk_instance_cache `(ℤ),
nc ← mk_instance_cache `(ℕ),
(ic, b) ← ic.of_nat n,
(_, _, _, p) ← prove_nat_uncast ic nc b,
pure (b, `(int_to_nat_cast).mk_app [a, b, p])
else failed
| _ := failed
/-- This version of `derive` does not fail when the input is already a numeral -/
meta def derive.step (e : expr) : tactic (expr × expr) :=
eval_field e <|> eval_pow e <|> eval_ineq e <|> eval_cast e <|> eval_nat_int_ext e
/-- An attribute for adding additional extensions to `norm_num`. To use this attribute, put
`@[norm_num]` on a tactic of type `expr → tactic (expr × expr)`; the tactic will be called on
subterms by `norm_num`, and it is responsible for identifying that the expression is a numerical
function applied to numerals, for example `nat.fib 17`, and should return the reduced numerical
expression (which must be in `norm_num`-normal form: a natural or rational numeral, i.e. `37`,
`12 / 7` or `-(2 / 3)`, although this can be an expression in any type), and the proof that the
original expression is equal to the rewritten expression.
Failure is used to indicate that this tactic does not apply to the term. For performance reasons,
it is best to detect non-applicability as soon as possible so that the next tactic can have a go,
so generally it will start with a pattern match and then checking that the arguments to the term
are numerals or of the appropriate form, followed by proof construction, which should not fail.
Propositions are treated like any other term. The normal form for propositions is `true` or
`false`, so it should produce a proof of the form `p = true` or `p = false`. `eq_true_intro` can be
used to help here.
-/
@[user_attribute]
protected meta def attr : user_attribute (expr → tactic (expr × expr)) unit :=
{ name := `norm_num,
descr := "Add norm_num derivers",
cache_cfg :=
{ mk_cache := λ ns, do
{ t ← ns.mfoldl
(λ (t : expr → tactic (expr × expr)) n, do
t' ← eval_expr (expr → tactic (expr × expr)) (expr.const n []),
pure (λ e, t' e <|> t e))
(λ _, failed),
pure (λ e, derive.step e <|> t e) },
dependencies := [] } }
add_tactic_doc
{ name := "norm_num",
category := doc_category.attr,
decl_names := [`norm_num.attr],
tags := ["arithmetic", "decision_procedure"] }
/-- Look up the `norm_num` extensions in the cache and return a tactic extending `derive.step` with
additional reduction procedures. -/
meta def get_step : tactic (expr → tactic (expr × expr)) := norm_num.attr.get_cache
/-- Simplify an expression bottom-up using `step` to simplify the subexpressions. -/
meta def derive' (step : expr → tactic (expr × expr))
: expr → tactic (expr × expr) | e :=
do e ← instantiate_mvars e,
(_, e', pr) ←
ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed)
(λ _ _ _ _ e,
do (new_e, pr) ← step e,
guard (¬ new_e =ₐ e),
return ((), new_e, some pr, tt))
`eq e,
return (e', pr)
/-- Simplify an expression bottom-up using the default `norm_num` set to simplify the
subexpressions. -/
meta def derive (e : expr) : tactic (expr × expr) := do f ← get_step, derive' f e
end norm_num
/-- Basic version of `norm_num` that does not call `simp`. It uses the provided `step` tactic
to simplify the expression; use `get_step` to get the default `norm_num` set and `derive.step` for
the basic builtin set of simplifications. -/
meta def tactic.norm_num1 (step : expr → tactic (expr × expr))
(loc : interactive.loc) : tactic unit :=
do ns ← loc.get_locals,
success ← tactic.replace_at (norm_num.derive' step) ns loc.include_goal,
when loc.include_goal $ try tactic.triv,
when (¬ ns.empty) $ try tactic.contradiction,
monad.unlessb success $ done <|> fail "norm_num failed to simplify"
/-- Normalize numerical expressions. It uses the provided `step` tactic to simplify the expression;
use `get_step` to get the default `norm_num` set and `derive.step` for the basic builtin set of
simplifications. -/
meta def tactic.norm_num (step : expr → tactic (expr × expr))
(hs : list simp_arg_type) (l : interactive.loc) : tactic unit :=
repeat1 $ orelse' (tactic.norm_num1 step l) $
interactive.simp_core {} (tactic.norm_num1 step (interactive.loc.ns [none]))
ff (simp_arg_type.except ``one_div :: hs) [] l >> skip
/-- Carry out similar operations as `tactic.norm_num` but on an `expr` rather than a location.
Given an expression `e`, returns `(e', ⊢ e = e')`.
The `no_dflt`, `hs`, and `attr_names` are passed on to `simp`.
Unlike `norm_num`, this tactic does not fail. -/
meta def _root_.expr.norm_num (step : expr → tactic (expr × expr))
(no_dflt : bool := ff) (hs : list simp_arg_type := []) (attr_names : list name := []) :
expr → tactic (expr × expr) :=
let simp_step (e : expr) := do
(e', p, _) ← e.simp {} (tactic.norm_num1 step (interactive.loc.ns [none]))
no_dflt attr_names (simp_arg_type.except ``one_div :: hs),
return (e', p)
in or_refl_conv $ λ e, do
(e', p') ← norm_num.derive' step e <|> simp_step e,
(e'', p'') ← _root_.expr.norm_num e',
p ← mk_eq_trans p' p'',
return (e'', p)
namespace tactic.interactive
open norm_num interactive interactive.types
/-- Basic version of `norm_num` that does not call `simp`. -/
meta def norm_num1 (loc : parse location) : tactic unit :=
do f ← get_step, tactic.norm_num1 f loc
/-- Normalize numerical expressions. Supports the operations
`+` `-` `*` `/` `^` and `%` over numerical types such as
`ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types,
and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`,
where `A` and `B` are numerical expressions.
It also has a relatively simple primality prover. -/
meta def norm_num (hs : parse simp_arg_list) (l : parse location) : tactic unit :=
do f ← get_step, tactic.norm_num f hs l
add_hint_tactic "norm_num"
/-- Normalizes a numerical expression and tries to close the goal with the result. -/
meta def apply_normed (x : parse texpr) : tactic unit :=
do x₁ ← to_expr x,
(x₂,_) ← derive x₁,
tactic.exact x₂
/--
Normalises numerical expressions. It supports the operations `+` `-` `*` `/` `^` and `%` over
numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ`, and can prove goals of the form `A = B`, `A ≠ B`,
`A < B` and `A ≤ B`, where `A` and `B` are numerical expressions.
Add-on tactics marked as `@[norm_num]` can extend the behavior of `norm_num` to include other
functions. This is used to support several other functions on `nat` like `prime`, `min_fac` and
`factors`.
```lean
import data.real.basic
example : (2 : ℝ) + 2 = 4 := by norm_num
example : (12345.2 : ℝ) ≠ 12345.3 := by norm_num
example : (73 : ℝ) < 789/2 := by norm_num
example : 123456789 + 987654321 = 1111111110 := by norm_num
example (R : Type*) [ring R] : (2 : R) + 2 = 4 := by norm_num
example (F : Type*) [linear_ordered_field F] : (2 : F) + 2 < 5 := by norm_num
example : nat.prime (2^13 - 1) := by norm_num
example : ¬ nat.prime (2^11 - 1) := by norm_num
example (x : ℝ) (h : x = 123 + 456) : x = 579 := by norm_num at h; assumption
```
The variant `norm_num1` does not call `simp`.
Both `norm_num` and `norm_num1` can be called inside the `conv` tactic.
The tactic `apply_normed` normalises a numerical expression and tries to close the goal with
the result. Compare:
```lean
def a : ℕ := 2^100
#print a -- 2 ^ 100
def normed_a : ℕ := by apply_normed 2^100
#print normed_a -- 1267650600228229401496703205376
```
-/
add_tactic_doc
{ name := "norm_num",
category := doc_category.tactic,
decl_names := [`tactic.interactive.norm_num1, `tactic.interactive.norm_num,
`tactic.interactive.apply_normed],
tags := ["arithmetic", "decision procedure"] }
end tactic.interactive
/-! ## `conv` tactic -/
namespace conv.interactive
open conv interactive tactic.interactive
open norm_num (derive)
/-- Basic version of `norm_num` that does not call `simp`. -/
meta def norm_num1 : conv unit := replace_lhs derive
/-- Normalize numerical expressions. Supports the operations
`+` `-` `*` `/` `^` and `%` over numerical types such as
`ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types,
and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`,
where `A` and `B` are numerical expressions.
It also has a relatively simple primality prover. -/
meta def norm_num (hs : parse simp_arg_list) : conv unit :=
repeat1 $ orelse' norm_num1 $
conv.interactive.simp ff (simp_arg_type.except ``one_div :: hs) []
{ discharger := tactic.interactive.norm_num1 (loc.ns [none]) }
end conv.interactive
/-!
## `#norm_num` command
A user command to run `norm_num`. Mostly copied from the `#simp` command.
-/
namespace tactic
setup_tactic_parser
/- With this option, turn off the messages if the result is exactly `true` -/
declare_trace silence_norm_num_if_true
/--
The basic usage is `#norm_num e`, where `e` is an expression,
which will print the `norm_num` form of `e`.
Syntax: `#norm_num` (`only`)? (`[` simp lemma list `]`)? (`with` simp sets)? `:`? expression
This accepts the same options as the `#simp` command.
You can specify additional simp lemmas as usual, for example using
`#norm_num [f, g] : e`, or `#norm_num with attr : e`.
(The colon is optional but helpful for the parser.)
The `only` restricts `norm_num` to using only the provided lemmas, and so
`#norm_num only : e` behaves similarly to `norm_num1`.
Unlike `norm_num`, this command does not fail when no simplifications are made.
`#norm_num` understands local variables, so you can use them to
introduce parameters.
-/
@[user_command] meta def norm_num_cmd (_ : parse $ tk "#norm_num") : lean.parser unit :=
do
no_dflt ← only_flag,
hs ← simp_arg_list,
attr_names ← with_ident_list,
o ← optional (tk ":"),
e ← texpr,
/- Retrieve the `pexpr`s parsed as part of the simp args, and collate them into a big list. -/
let hs_es := list.join $ hs.map $ option.to_list ∘ simp_arg_type.to_pexpr,
/- Synthesize a `tactic_state` including local variables as hypotheses under which `expr.simp`
may be safely called with expected behaviour given the `variables` in the environment. -/
(ts, mappings) ← synthesize_tactic_state_with_variables_as_hyps (e :: hs_es),
/- Enter the `tactic` monad, *critically* using the synthesized tactic state `ts`. -/
result ← lean.parser.of_tactic $ λ _, do
{ /- Resolve the local variables added by the parser to `e` (when it was parsed) against the local
hypotheses added to the `ts : tactic_state` which we are using. -/
e ← to_expr e,
/- Replace the variables referenced in the passed `simp_arg_list` with the `expr`s corresponding
to the local hypotheses we created.
We would prefer to just elaborate the `pexpr`s encoded in the `simp_arg_list` against the
tactic state we have created (as we could with `e` above), but the simplifier expects
`pexpr`s and not `expr`s. Thus, we just modify the `pexpr`s now and let `simp` do the
elaboration when the time comes.
You might think that we could just examine each of these `pexpr`s, call `to_expr` on them,
and then call `to_pexpr` afterward and save the results over the original `pexprs`. Due to
how functions like `simp_lemmas.add_pexpr` are implemented in the core library, the `simp`
framework is not robust enough to handle this method. When pieces of expressions like
annotation macros are injected, the direct patten matches in the `simp_lemmas.*` codebase
fail, and the lemmas we want don't get added.
-/
let hs := hs.map $ λ sat, sat.replace_subexprs mappings,
/- Try simplifying the expression. -/
step ← norm_num.get_step,
prod.fst <$> e.norm_num step no_dflt hs attr_names } ts,
/- Trace the result. -/
when (¬ is_trace_enabled_for `silence_norm_num_if_true ∨ result ≠ expr.const `true [])
(trace result)
add_tactic_doc
{ name := "#norm_num",
category := doc_category.cmd,
decl_names := [`tactic.norm_num_cmd],
tags := ["simplification", "arithmetic", "decision procedure"] }
end tactic
|
b9ce54182fc0b5c749d86161c889d90ee364e83f
|
4767244035cdd124e1ce3d0c81128f8929df6163
|
/group_theory/subgroup.lean
|
ec5caa0969b5def003530fd5a6c46a10117836ea
|
[
"Apache-2.0"
] |
permissive
|
5HT/mathlib
|
b941fecacd31a9c5dd0abad58770084b8a1e56b1
|
40fa9ade2f5649569639608db5e621e5fad0cc02
|
refs/heads/master
| 1,586,978,681,358
| 1,546,681,764,000
| 1,546,681,764,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 19,708
|
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, Mitchell Rowett, Scott Morrison, Johan Commelin, Mario Carneiro
-/
import group_theory.submonoid
open set function
variables {α : Type*} {β : Type*} {a a₁ a₂ b c: α}
section group
variables [group α] [add_group β]
@[to_additive injective_add]
lemma injective_mul {a : α} : injective ((*) a) :=
assume a₁ a₂ h,
have a⁻¹ * a * a₁ = a⁻¹ * a * a₂, by rw [mul_assoc, mul_assoc, h],
by rwa [inv_mul_self, one_mul, one_mul] at this
/-- `s` is a subgroup: a set containing 1 and closed under multiplication and inverse. -/
class is_subgroup (s : set α) extends is_submonoid s : Prop :=
(inv_mem {a} : a ∈ s → a⁻¹ ∈ s)
/-- `s` is an additive subgroup: a set containing 0 and closed under addition and negation. -/
class is_add_subgroup (s : set β) extends is_add_submonoid s : Prop :=
(neg_mem {a} : a ∈ s → -a ∈ s)
attribute [to_additive is_add_subgroup] is_subgroup
attribute [to_additive is_add_subgroup.to_is_add_submonoid] is_subgroup.to_is_submonoid
attribute [to_additive is_add_subgroup.neg_mem] is_subgroup.inv_mem
attribute [to_additive is_add_subgroup.mk] is_subgroup.mk
instance additive.is_add_subgroup
(s : set α) [is_subgroup s] : @is_add_subgroup (additive α) _ s :=
⟨@is_subgroup.inv_mem _ _ _ _⟩
theorem additive.is_add_subgroup_iff
{s : set α} : @is_add_subgroup (additive α) _ s ↔ is_subgroup s :=
⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_subgroup.mk α _ _ ⟨h₁, @h₂⟩ @h₃,
λ h, by resetI; apply_instance⟩
instance multiplicative.is_subgroup
(s : set β) [is_add_subgroup s] : @is_subgroup (multiplicative β) _ s :=
⟨@is_add_subgroup.neg_mem _ _ _ _⟩
theorem multiplicative.is_subgroup_iff
{s : set β} : @is_subgroup (multiplicative β) _ s ↔ is_add_subgroup s :=
⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_add_subgroup.mk β _ _ ⟨h₁, @h₂⟩ @h₃,
λ h, by resetI; apply_instance⟩
instance subtype.group {s : set α} [is_subgroup s] : group s :=
by subtype_instance
instance subtype.add_group {s : set β} [is_add_subgroup s] : add_group s :=
by subtype_instance
attribute [to_additive subtype.add_group] subtype.group
@[simp, to_additive is_add_subgroup.coe_neg]
lemma is_subgroup.coe_inv {s : set α} [is_subgroup s] (a : s) : ((a⁻¹ : s) : α) = a⁻¹ := rfl
@[simp] lemma is_subgroup.coe_gpow {s : set α} [is_subgroup s] (a : s) (n : ℤ) : ((a ^ n : s) : α) = a ^ n :=
by induction n; simp [is_submonoid.coe_pow a]
@[simp] lemma is_add_subgroup.gsmul_coe {β : Type*} [add_group β] {s : set β} [is_add_subgroup s] (a : s) (n : ℤ) :
((gsmul n a : s) : β) = gsmul n a :=
by induction n; simp [is_add_submonoid.smul_coe a]
attribute [to_additive is_add_subgroup.gsmul_coe] is_subgroup.coe_gpow
theorem is_subgroup.of_div (s : set α)
(one_mem : (1:α) ∈ s) (div_mem : ∀{a b:α}, a ∈ s → b ∈ s → a * b⁻¹ ∈ s):
is_subgroup s :=
have inv_mem : ∀a, a ∈ s → a⁻¹ ∈ s, from
assume a ha,
have 1 * a⁻¹ ∈ s, from div_mem one_mem ha,
by simpa,
{ inv_mem := inv_mem,
mul_mem := assume a b ha hb,
have a * b⁻¹⁻¹ ∈ s, from div_mem ha (inv_mem b hb),
by simpa,
one_mem := one_mem }
theorem is_add_subgroup.of_sub (s : set β)
(zero_mem : (0:β) ∈ s) (sub_mem : ∀{a b:β}, a ∈ s → b ∈ s → a - b ∈ s):
is_add_subgroup s :=
multiplicative.is_subgroup_iff.1 $
@is_subgroup.of_div (multiplicative β) _ _ zero_mem @sub_mem
def gpowers (x : α) : set α := set.range ((^) x : ℤ → α)
def gmultiples (x : β) : set β := set.range (λ i, gsmul i x)
attribute [to_additive gmultiples] gpowers
instance gpowers.is_subgroup (x : α) : is_subgroup (gpowers x) :=
{ one_mem := ⟨(0:ℤ), by simp⟩,
mul_mem := assume x₁ x₂ ⟨i₁, h₁⟩ ⟨i₂, h₂⟩, ⟨i₁ + i₂, by simp [gpow_add, *]⟩,
inv_mem := assume x₀ ⟨i, h⟩, ⟨-i, by simp [h.symm]⟩ }
instance gmultiples.is_add_subgroup (x : β) : is_add_subgroup (gmultiples x) :=
multiplicative.is_subgroup_iff.1 $ gpowers.is_subgroup _
attribute [to_additive gmultiples.is_add_subgroup] gpowers.is_subgroup
lemma is_subgroup.gpow_mem {a : α} {s : set α} [is_subgroup s] (h : a ∈ s) : ∀{i:ℤ}, a ^ i ∈ s
| (n : ℕ) := is_submonoid.pow_mem h
| -[1+ n] := is_subgroup.inv_mem (is_submonoid.pow_mem h)
lemma is_add_subgroup.gsmul_mem {a : β} {s : set β} [is_add_subgroup s] : a ∈ s → ∀{i:ℤ}, gsmul i a ∈ s :=
@is_subgroup.gpow_mem (multiplicative β) _ _ _ _
lemma mem_gpowers {a : α} : a ∈ gpowers a := ⟨1, by simp⟩
lemma mem_gmultiples {a : β} : a ∈ gmultiples a := ⟨1, by simp⟩
attribute [to_additive mem_gmultiples] mem_gpowers
end group
namespace is_subgroup
open is_submonoid
variables [group α] (s : set α) [is_subgroup s]
@[to_additive is_add_subgroup.neg_mem_iff]
lemma inv_mem_iff : a⁻¹ ∈ s ↔ a ∈ s :=
⟨λ h, by simpa using inv_mem h, inv_mem⟩
@[to_additive is_add_subgroup.add_mem_cancel_left]
lemma mul_mem_cancel_left (h : a ∈ s) : b * a ∈ s ↔ b ∈ s :=
⟨λ hba, by simpa using mul_mem hba (inv_mem h), λ hb, mul_mem hb h⟩
@[to_additive is_add_subgroup.add_mem_cancel_right]
lemma mul_mem_cancel_right (h : a ∈ s) : a * b ∈ s ↔ b ∈ s :=
⟨λ hab, by simpa using mul_mem (inv_mem h) hab, mul_mem h⟩
end is_subgroup
theorem is_add_subgroup.sub_mem {α} [add_group α] (s : set α) [is_add_subgroup s] (a b : α)
(ha : a ∈ s) (hb : b ∈ s) : a - b ∈ s :=
is_add_submonoid.add_mem ha (is_add_subgroup.neg_mem hb)
namespace group
open is_submonoid is_subgroup
variables [group α] {s : set α}
inductive in_closure (s : set α) : α → Prop
| basic {a : α} : a ∈ s → in_closure a
| one : in_closure 1
| inv {a : α} : in_closure a → in_closure a⁻¹
| mul {a b : α} : in_closure a → in_closure b → in_closure (a * b)
/-- `group.closure s` is the subgroup closed over `s`, i.e. the smallest subgroup containg s. -/
def closure (s : set α) : set α := {a | in_closure s a }
lemma mem_closure {a : α} : a ∈ s → a ∈ closure s := in_closure.basic
instance closure.is_subgroup (s : set α) : is_subgroup (closure s) :=
{ one_mem := in_closure.one s, mul_mem := assume a b, in_closure.mul, inv_mem := assume a, in_closure.inv }
theorem subset_closure {s : set α} : s ⊆ closure s := λ a, mem_closure
theorem closure_subset {s t : set α} [is_subgroup t] (h : s ⊆ t) : closure s ⊆ t :=
assume a ha, by induction ha; simp [h _, *, one_mem, mul_mem, inv_mem_iff]
lemma closure_subset_iff (s t : set α) [is_subgroup t] : closure s ⊆ t ↔ s ⊆ t :=
⟨assume h b ha, h (mem_closure ha), assume h b ha, closure_subset h ha⟩
theorem gpowers_eq_closure {a : α} : gpowers a = closure {a} :=
subset.antisymm
(assume x h, match x, h with _, ⟨i, rfl⟩ := gpow_mem (mem_closure $ by simp) end)
(closure_subset $ by simp [mem_gpowers])
end group
namespace add_group
open is_add_submonoid is_add_subgroup
variables [add_group α] {s : set α}
/-- `add_group.closure s` is the additive subgroup closed over `s`, i.e. the smallest subgroup containg s. -/
def closure (s : set α) : set α := @group.closure (multiplicative α) _ s
attribute [to_additive add_group.closure] group.closure
lemma mem_closure {a : α} : a ∈ s → a ∈ closure s := group.mem_closure
attribute [to_additive add_group.mem_closure] group.mem_closure
instance closure.is_add_subgroup (s : set α) : is_add_subgroup (closure s) :=
multiplicative.is_subgroup_iff.1 $ group.closure.is_subgroup _
attribute [to_additive add_group.closure.is_add_subgroup] group.closure.is_subgroup
attribute [to_additive add_group.subset_closure] group.subset_closure
theorem closure_subset {s t : set α} [is_add_subgroup t] : s ⊆ t → closure s ⊆ t :=
group.closure_subset
attribute [to_additive add_group.closure_subset] group.closure_subset
attribute [to_additive add_group.closure_subset_iff] group.closure_subset_iff
theorem gmultiples_eq_closure {a : α} : gmultiples a = closure {a} :=
group.gpowers_eq_closure
attribute [to_additive add_group.gmultiples_eq_closure] group.gpowers_eq_closure
@[elab_as_eliminator]
theorem in_closure.rec_on {C : α → Prop}
{a : α} (H : a ∈ closure s)
(H1 : ∀ {a : α}, a ∈ s → C a) (H2 : C 0) (H3 : ∀ {a : α}, a ∈ closure s → C a → C (-a))
(H4 : ∀ {a b : α}, a ∈ closure s → b ∈ closure s → C a → C b → C (a + b)) :
C a :=
group.in_closure.rec_on H (λ _, H1) H2 (λ _, H3) (λ _ _, H4)
end add_group
class normal_subgroup [group α] (s : set α) extends is_subgroup s : Prop :=
(normal : ∀ n ∈ s, ∀ g : α, g * n * g⁻¹ ∈ s)
class normal_add_subgroup [add_group α] (s : set α) extends is_add_subgroup s : Prop :=
(normal : ∀ n ∈ s, ∀ g : α, g + n - g ∈ s)
attribute [to_additive normal_add_subgroup] normal_subgroup
attribute [to_additive normal_add_subgroup.to_is_add_subgroup] normal_subgroup.to_is_subgroup
attribute [to_additive normal_add_subgroup.normal] normal_subgroup.normal
attribute [to_additive normal_add_subgroup.mk] normal_subgroup.mk
@[to_additive normal_add_subgroup_of_add_comm_group]
lemma normal_subgroup_of_comm_group [comm_group α] (s : set α) [hs : is_subgroup s] :
normal_subgroup s :=
{ normal := λ n hn g, by rwa [mul_right_comm, mul_right_inv, one_mul],
..hs }
instance additive.normal_add_subgroup [group α]
(s : set α) [normal_subgroup s] : @normal_add_subgroup (additive α) _ s :=
⟨@normal_subgroup.normal _ _ _ _⟩
theorem additive.normal_add_subgroup_iff [group α]
{s : set α} : @normal_add_subgroup (additive α) _ s ↔ normal_subgroup s :=
⟨by rintro ⟨h₁, h₂⟩; exact
@normal_subgroup.mk α _ _ (additive.is_add_subgroup_iff.1 h₁) @h₂,
λ h, by resetI; apply_instance⟩
instance multiplicative.normal_subgroup [add_group α]
(s : set α) [normal_add_subgroup s] : @normal_subgroup (multiplicative α) _ s :=
⟨@normal_add_subgroup.normal _ _ _ _⟩
theorem multiplicative.normal_subgroup_iff [add_group α]
{s : set α} : @normal_subgroup (multiplicative α) _ s ↔ normal_add_subgroup s :=
⟨by rintro ⟨h₁, h₂⟩; exact
@normal_add_subgroup.mk α _ _ (multiplicative.is_subgroup_iff.1 h₁) @h₂,
λ h, by resetI; apply_instance⟩
namespace is_subgroup
variable [group α]
-- Normal subgroup properties
lemma mem_norm_comm {s : set α} [normal_subgroup s] {a b : α} (hab : a * b ∈ s) : b * a ∈ s :=
have h : a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ s, from normal_subgroup.normal (a * b) hab a⁻¹,
by simp at h; exact h
lemma mem_norm_comm_iff {s : set α} [normal_subgroup s] {a b : α} : a * b ∈ s ↔ b * a ∈ s :=
⟨mem_norm_comm, mem_norm_comm⟩
/-- The trivial subgroup -/
def trivial (α : Type*) [group α] : set α := {1}
@[simp] lemma mem_trivial [group α] {g : α} : g ∈ trivial α ↔ g = 1 :=
mem_singleton_iff
instance trivial_normal : normal_subgroup (trivial α) :=
by refine {..}; simp [trivial] {contextual := tt}
lemma trivial_eq_closure : trivial α = group.closure ∅ :=
subset.antisymm
(by simp [set.subset_def, is_submonoid.one_mem])
(group.closure_subset $ by simp)
instance univ_subgroup : normal_subgroup (@univ α) :=
by refine {..}; simp
def center (α : Type*) [group α] : set α := {z | ∀ g, g * z = z * g}
lemma mem_center {a : α} : a ∈ center α ↔ ∀g, g * a = a * g := iff.rfl
instance center_normal : normal_subgroup (center α) :=
{ one_mem := by simp [center],
mul_mem := assume a b ha hb g,
by rw [←mul_assoc, mem_center.2 ha g, mul_assoc, mem_center.2 hb g, ←mul_assoc],
inv_mem := assume a ha g,
calc
g * a⁻¹ = a⁻¹ * (g * a) * a⁻¹ : by simp [ha g]
... = a⁻¹ * g : by rw [←mul_assoc, mul_assoc]; simp,
normal := assume n ha g h,
calc
h * (g * n * g⁻¹) = h * n : by simp [ha g, mul_assoc]
... = g * g⁻¹ * n * h : by rw ha h; simp
... = g * n * g⁻¹ * h : by rw [mul_assoc g, ha g⁻¹, ←mul_assoc] }
def normalizer (s : set α) : set α :=
{g : α | ∀ n, n ∈ s ↔ g * n * g⁻¹ ∈ s}
instance (s : set α) [is_subgroup s] : is_subgroup (normalizer s) :=
{ one_mem := by simp [normalizer],
mul_mem := λ a b (ha : ∀ n, n ∈ s ↔ a * n * a⁻¹ ∈ s)
(hb : ∀ n, n ∈ s ↔ b * n * b⁻¹ ∈ s) n,
by rw [mul_inv_rev, ← mul_assoc, mul_assoc a, mul_assoc a, ← ha, ← hb],
inv_mem := λ a (ha : ∀ n, n ∈ s ↔ a * n * a⁻¹ ∈ s) n,
by rw [ha (a⁻¹ * n * a⁻¹⁻¹)];
simp [mul_assoc] }
lemma subset_normalizer (s : set α) [is_subgroup s] : s ⊆ normalizer s :=
λ g hg n, by rw [is_subgroup.mul_mem_cancel_left _ ((is_subgroup.inv_mem_iff _).2 hg),
is_subgroup.mul_mem_cancel_right _ hg]
instance (s : set α) [is_subgroup s] : normal_subgroup (subtype.val ⁻¹' s : set (normalizer s)) :=
{ one_mem := show (1 : α) ∈ s, from is_submonoid.one_mem _,
mul_mem := λ a b ha hb, show (a * b : α) ∈ s, from is_submonoid.mul_mem ha hb,
inv_mem := λ a ha, show (a⁻¹ : α) ∈ s, from is_subgroup.inv_mem ha,
normal := λ a ha ⟨m, hm⟩, (hm a).1 ha }
end is_subgroup
namespace is_add_subgroup
variable [add_group α]
attribute [to_additive is_add_subgroup.mem_norm_comm] is_subgroup.mem_norm_comm
attribute [to_additive is_add_subgroup.mem_norm_comm_iff] is_subgroup.mem_norm_comm_iff
/-- The trivial subgroup -/
def trivial (α : Type*) [add_group α] : set α := {0}
attribute [to_additive is_add_subgroup.trivial] is_subgroup.trivial
attribute [to_additive is_add_subgroup.mem_trivial] is_subgroup.mem_trivial
instance trivial_normal : normal_add_subgroup (trivial α) :=
multiplicative.normal_subgroup_iff.1 is_subgroup.trivial_normal
attribute [to_additive is_add_subgroup.trivial_normal] is_subgroup.trivial_normal
attribute [to_additive is_add_subgroup.trivial_eq_closure] is_subgroup.trivial_eq_closure
instance univ_add_subgroup : normal_add_subgroup (@univ α) :=
multiplicative.normal_subgroup_iff.1 is_subgroup.univ_subgroup
attribute [to_additive is_add_subgroup.univ_add_subgroup] is_subgroup.univ_subgroup
def center (α : Type*) [add_group α] : set α := {z | ∀ g, g + z = z + g}
attribute [to_additive is_add_subgroup.center] is_subgroup.center
attribute [to_additive is_add_subgroup.mem_center] is_subgroup.mem_center
instance center_normal : normal_add_subgroup (center α) :=
multiplicative.normal_subgroup_iff.1 is_subgroup.center_normal
end is_add_subgroup
-- Homomorphism subgroups
namespace is_group_hom
open is_submonoid is_subgroup
variables [group α] [group β]
@[to_additive is_add_group_hom.ker]
def ker (f : α → β) [is_group_hom f] : set α := preimage f (trivial β)
attribute [to_additive is_add_group_hom.ker.equations._eqn_1] ker.equations._eqn_1
@[to_additive is_add_group_hom.mem_ker]
lemma mem_ker (f : α → β) [is_group_hom f] {x : α} : x ∈ ker f ↔ f x = 1 :=
mem_trivial
@[to_additive is_add_group_hom.zero_ker_neg]
lemma one_ker_inv (f : α → β) [is_group_hom f] {a b : α} (h : f (a * b⁻¹) = 1) : f a = f b :=
begin
rw [mul f, inv f] at h,
rw [←inv_inv (f b), eq_inv_of_mul_eq_one h]
end
@[to_additive is_add_group_hom.neg_ker_zero]
lemma inv_ker_one (f : α → β) [is_group_hom f] {a b : α} (h : f a = f b) : f (a * b⁻¹) = 1 :=
have f a * (f b)⁻¹ = 1, by rw [h, mul_right_inv],
by rwa [←inv f, ←mul f] at this
@[to_additive is_add_group_hom.zero_iff_ker_neg]
lemma one_iff_ker_inv (f : α → β) [is_group_hom f] (a b : α) : f a = f b ↔ f (a * b⁻¹) = 1 :=
⟨inv_ker_one f, one_ker_inv f⟩
@[to_additive is_add_group_hom.neg_iff_ker]
lemma inv_iff_ker (f : α → β) [w : is_group_hom f] (a b : α) : f a = f b ↔ a * b⁻¹ ∈ ker f :=
by rw [mem_ker]; exact one_iff_ker_inv _ _ _
instance image_subgroup (f : α → β) [is_group_hom f] (s : set α) [is_subgroup s] :
is_subgroup (f '' s) :=
{ mul_mem := assume a₁ a₂ ⟨b₁, hb₁, eq₁⟩ ⟨b₂, hb₂, eq₂⟩,
⟨b₁ * b₂, mul_mem hb₁ hb₂, by simp [eq₁, eq₂, mul f]⟩,
one_mem := ⟨1, one_mem s, one f⟩,
inv_mem := assume a ⟨b, hb, eq⟩, ⟨b⁻¹, inv_mem hb, by rw inv f; simp *⟩ }
attribute [to_additive is_add_group_hom.image_add_subgroup._match_1] is_group_hom.image_subgroup._match_1
attribute [to_additive is_add_group_hom.image_add_subgroup._match_2] is_group_hom.image_subgroup._match_2
attribute [to_additive is_add_group_hom.image_add_subgroup._match_3] is_group_hom.image_subgroup._match_3
attribute [to_additive is_add_group_hom.image_add_subgroup] is_group_hom.image_subgroup
attribute [to_additive is_add_group_hom.image_add_subgroup._match_1.equations._eqn_1] is_group_hom.image_subgroup._match_1.equations._eqn_1
attribute [to_additive is_add_group_hom.image_add_subgroup._match_2.equations._eqn_1] is_group_hom.image_subgroup._match_2.equations._eqn_1
attribute [to_additive is_add_group_hom.image_add_subgroup._match_3.equations._eqn_1] is_group_hom.image_subgroup._match_3.equations._eqn_1
attribute [to_additive is_add_group_hom.image_add_subgroup.equations._eqn_1] is_group_hom.image_subgroup.equations._eqn_1
instance range_subgroup (f : α → β) [is_group_hom f] : is_subgroup (set.range f) :=
@set.image_univ _ _ f ▸ is_group_hom.image_subgroup f set.univ
attribute [to_additive is_add_group_hom.range_add_subgroup] is_group_hom.range_subgroup
attribute [to_additive is_add_group_hom.range_add_subgroup.equations._eqn_1] is_group_hom.range_subgroup.equations._eqn_1
local attribute [simp] one_mem inv_mem mul_mem normal_subgroup.normal
instance preimage (f : α → β) [is_group_hom f] (s : set β) [is_subgroup s] :
is_subgroup (f ⁻¹' s) :=
by refine {..}; simp [mul f, one f, inv f, @inv_mem β _ s] {contextual:=tt}
attribute [to_additive is_add_group_hom.preimage] is_group_hom.preimage
attribute [to_additive is_add_group_hom.preimage.equations._eqn_1] is_group_hom.preimage.equations._eqn_1
instance preimage_normal (f : α → β) [is_group_hom f] (s : set β) [normal_subgroup s] :
normal_subgroup (f ⁻¹' s) :=
⟨by simp [mul f, inv f] {contextual:=tt}⟩
attribute [to_additive is_add_group_hom.preimage_normal] is_group_hom.preimage_normal
attribute [to_additive is_add_group_hom.preimage_normal.equations._eqn_1] is_group_hom.preimage_normal.equations._eqn_1
instance normal_subgroup_ker (f : α → β) [is_group_hom f] : normal_subgroup (ker f) :=
is_group_hom.preimage_normal f (trivial β)
attribute [to_additive is_add_group_hom.normal_subgroup_ker] is_group_hom.normal_subgroup_ker
attribute [to_additive is_add_group_hom.normal_subgroup_ker.equations._eqn_1] is_group_hom.normal_subgroup_ker.equations._eqn_1
lemma inj_of_trivial_ker (f : α → β) [is_group_hom f] (h : ker f = trivial α) :
function.injective f :=
begin
intros a₁ a₂ hfa,
simp [ext_iff, ker, is_subgroup.trivial] at h,
have ha : a₁ * a₂⁻¹ = 1, by rw ←h; exact inv_ker_one f hfa,
rw [eq_inv_of_mul_eq_one ha, inv_inv a₂]
end
lemma trivial_ker_of_inj (f : α → β) [is_group_hom f] (h : function.injective f) :
ker f = trivial α :=
set.ext $ assume x, iff.intro
(assume hx,
suffices f x = f 1, by simpa using h this,
by simp [one f]; rwa [mem_ker] at hx)
(by simp [mem_ker, is_group_hom.one f] {contextual := tt})
lemma inj_iff_trivial_ker (f : α → β) [is_group_hom f] :
function.injective f ↔ ker f = trivial α :=
⟨trivial_ker_of_inj f, inj_of_trivial_ker f⟩
instance (s : set α) [is_subgroup s] : is_group_hom (subtype.val : s → α) :=
⟨λ _ _, rfl⟩
end is_group_hom
|
3ead8c737caa30be6b4bb1d45e072f090b18ea08
|
74addaa0e41490cbaf2abd313a764c96df57b05d
|
/Mathlib/tactic/slim_check_auto.lean
|
b9760bc4dbaf230d3e996a56d2f4fa2dbb9c05ca
|
[] |
no_license
|
AurelienSaue/Mathlib4_auto
|
f538cfd0980f65a6361eadea39e6fc639e9dae14
|
590df64109b08190abe22358fabc3eae000943f2
|
refs/heads/master
| 1,683,906,849,776
| 1,622,564,669,000
| 1,622,564,669,000
| 371,723,747
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 3,764
|
lean
|
/-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Simon Hudon
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.testing.slim_check.testable
import Mathlib.testing.slim_check.functions
import Mathlib.data.list.sort
import Mathlib.PostPort
namespace Mathlib
/-!
## Finding counterexamples automatically using `slim_check`
A proposition can be tested by writing it out as:
```lean
example (xs : list ℕ) (w : ∃ x ∈ xs, x < 3) : ∀ y ∈ xs, y < 5 := by slim_check
-- ===================
-- ===================
-- Found problems!
-- Found problems!
-- xs := [0, 5]
-- xs := [0, 5]
-- x := 0
-- x := 0
-- y := 5
-- y := 5
-- -------------------
-- -------------------
example (x : ℕ) (h : 2 ∣ x) : x < 100 := by slim_check
-- ===================
-- ===================
-- Found problems!
-- Found problems!
-- x := 258
-- x := 258
-- -------------------
-- -------------------
example (α : Type) (xs ys : list α) : xs ++ ys = ys ++ xs := by slim_check
-- ===================
-- ===================
-- Found problems!
-- Found problems!
-- α := ℤ
-- α := ℤ
-- xs := [-4]
-- xs := [-4]
-- ys := [1]
-- ys := [1]
-- -------------------
-- -------------------
example : ∀ x ∈ [1,2,3], x < 4 := by slim_check
-- Success
-- Success
```
In the first example, `slim_check` is called on the following goal:
```lean
xs : list ℕ,
h : ∃ (x : ℕ) (H : x ∈ xs), x < 3
⊢ ∀ (y : ℕ), y ∈ xs → y < 5
```
The local constants are reverted and an instance is found for
`testable (∀ (xs : list ℕ), (∃ x ∈ xs, x < 3) → (∀ y ∈ xs, y < 5))`.
The `testable` instance is supported by instances of `sampleable (list ℕ)`,
`decidable (x < 3)` and `decidable (y < 5)`. `slim_check` builds a
`testable` instance step by step with:
```
- testable (∀ (xs : list ℕ), (∃ x ∈ xs, x < 3) → (∀ y ∈ xs, y < 5))
-: sampleable (list xs)
- testable ((∃ x ∈ xs, x < 3) → (∀ y ∈ xs, y < 5))
- testable (∀ x ∈ xs, x < 3 → (∀ y ∈ xs, y < 5))
- testable (x < 3 → (∀ y ∈ xs, y < 5))
-: decidable (x < 3)
- testable (∀ y ∈ xs, y < 5)
-: decidable (y < 5)
```
`sampleable (list ℕ)` lets us create random data of type `list ℕ` in a way that
helps find small counter-examples. Next, the test of the proposition
hinges on `x < 3` and `y < 5` to both be decidable. The
implication between the two could be tested as a whole but it would be
less informative. Indeed, if we generate lists that only contain numbers
greater than `3`, the implication will always trivially hold but we should
conclude that we haven't found meaningful examples. Instead, when `x < 3`
does not hold, we reject the example (i.e. we do not count it toward
the 100 required positive examples) and we start over. Therefore, when
`slim_check` prints `Success`, it means that a hundred suitable lists
were found and successfully tested.
If no counter-examples are found, `slim_check` behaves like `admit`.
`slim_check` can also be invoked using `#eval`:
```lean
#eval slim_check.testable.check (∀ (α : Type) (xs ys : list α), xs ++ ys = ys ++ xs)
-- ===================
-- ===================
-- Found problems!
-- Found problems!
-- α := ℤ
-- α := ℤ
-- xs := [-4]
-- xs := [-4]
-- ys := [1]
-- ys := [1]
-- -------------------
-- -------------------
```
For more information on writing your own `sampleable` and `testable`
instances, see `testing.slim_check.testable`.
-/
namespace tactic.interactive
/-- Tree structure representing a `testable` instance. -/
end Mathlib
|
fa0e044acdec20df9c3c11e763d2e25e675610a5
|
36c7a18fd72e5b57229bd8ba36493daf536a19ce
|
/hott/types/int/hott.hlean
|
c79d5fa96128ed6c57deab98d4b7eef8e79a83bc
|
[
"Apache-2.0"
] |
permissive
|
YHVHvx/lean
|
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
|
038369533e0136dd395dc252084d3c1853accbf2
|
refs/heads/master
| 1,610,701,080,210
| 1,449,128,595,000
| 1,449,128,595,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 5,537
|
hlean
|
/-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Theorems about the integers specific to HoTT
-/
import .basic types.eq arity
open core eq is_equiv equiv equiv.ops
open nat (hiding pred)
namespace int
section
open algebra
definition group_integers : Group :=
Group.mk ℤ (group_of_add_group _)
end
definition is_equiv_succ [instance] : is_equiv succ :=
adjointify succ pred (λa, !add_sub_cancel) (λa, !sub_add_cancel)
definition equiv_succ : ℤ ≃ ℤ := equiv.mk succ _
definition is_equiv_neg [instance] : is_equiv neg :=
adjointify neg neg (λx, !neg_neg) (λa, !neg_neg)
definition equiv_neg : ℤ ≃ ℤ := equiv.mk neg _
definition iterate {A : Type} (f : A ≃ A) (a : ℤ) : A ≃ A :=
rec_nat_on a erfl
(λb g, f ⬝e g)
(λb g, g ⬝e f⁻¹ᵉ)
-- definition iterate_trans {A : Type} (f : A ≃ A) (a : ℤ)
-- : iterate f a ⬝e f = iterate f (a + 1) :=
-- sorry
-- definition trans_iterate {A : Type} (f : A ≃ A) (a : ℤ)
-- : f ⬝e iterate f a = iterate f (a + 1) :=
-- sorry
-- definition iterate_trans_symm {A : Type} (f : A ≃ A) (a : ℤ)
-- : iterate f a ⬝e f⁻¹e = iterate f (a - 1) :=
-- sorry
-- definition symm_trans_iterate {A : Type} (f : A ≃ A) (a : ℤ)
-- : f⁻¹e ⬝e iterate f a = iterate f (a - 1) :=
-- sorry
-- definition iterate_neg {A : Type} (f : A ≃ A) (a : ℤ)
-- : iterate f (-a) = (iterate f a)⁻¹e :=
-- rec_nat_on a idp
-- (λn p, calc
-- iterate f (-succ n) = iterate f (-n) ⬝e f⁻¹e : rec_nat_on_neg
-- ... = (iterate f n)⁻¹e ⬝e f⁻¹e : by rewrite p
-- ... = (f ⬝e iterate f n)⁻¹e : sorry
-- ... = (iterate f (succ n))⁻¹e : idp)
-- sorry
-- definition iterate_add {A : Type} (f : A ≃ A) (a b : ℤ)
-- : iterate f (a + b) = equiv.trans (iterate f a) (iterate f b) :=
-- sorry
-- definition iterate_sub {A : Type} (f : A ≃ A) (a b : ℤ)
-- : iterate f (a - b) = equiv.trans (iterate f a) (equiv.symm (iterate f b)) :=
-- sorry
-- definition iterate_mul {A : Type} (f : A ≃ A) (a b : ℤ)
-- : iterate f (a * b) = iterate (iterate f a) b :=
-- sorry
end int open int
namespace eq
variables {A : Type} {a : A} (p : a = a) (b c : ℤ) (n : ℕ)
definition power : a = a :=
rec_nat_on b idp
(λc q, q ⬝ p)
(λc q, q ⬝ p⁻¹)
--iterate (equiv_eq_closed_right p a) b idp
-- definition power_neg_succ (n : ℕ) : power p (-succ n) = power p (-n) ⬝ p⁻¹ :=
-- !rec_nat_on_neg
-- local attribute nat.add int.add int.of_num nat.of_num int.succ [constructor]
definition power_con : power p b ⬝ p = power p (succ b) :=
rec_nat_on b
idp
(λn IH, idp)
(λn IH, calc
power p (-succ n) ⬝ p = (power p (-n) ⬝ p⁻¹) ⬝ p : by rewrite [↑power,-rec_nat_on_neg]
... = power p (-n) : inv_con_cancel_right
... = power p (succ (-succ n)) : by rewrite -succ_neg_succ)
definition power_con_inv : power p b ⬝ p⁻¹ = power p (pred b) :=
rec_nat_on b
idp
(λn IH, calc
power p (succ n) ⬝ p⁻¹ = power p n : by apply con_inv_cancel_right
... = power p (pred (succ n)) : by rewrite pred_nat_succ)
(λn IH, calc
power p (-succ n) ⬝ p⁻¹ = power p (-succ (succ n)) : by rewrite [↑power,-rec_nat_on_neg]
... = power p (pred (-succ n)) : by rewrite -neg_succ)
definition con_power : p ⬝ power p b = power p (succ b) :=
rec_nat_on b
( by rewrite ↑[power];exact !idp_con⁻¹)
( λn IH, proof calc
p ⬝ power p (succ n) = (p ⬝ power p n) ⬝ p : con.assoc p _ p
... = power p (succ (succ n)) : by rewrite IH qed)
( λn IH, calc
p ⬝ power p (-succ n)
= p ⬝ (power p (-n) ⬝ p⁻¹) : by rewrite [↑power,rec_nat_on_neg]
... = (p ⬝ power p (-n)) ⬝ p⁻¹ : con.assoc
... = power p (succ (-n)) ⬝ p⁻¹ : by rewrite IH
... = power p (pred (succ (-n))) : power_con_inv
... = power p (succ (-succ n)) : by rewrite [succ_neg_nat_succ,int.pred_succ])
definition inv_con_power : p⁻¹ ⬝ power p b = power p (pred b) :=
rec_nat_on b
( by rewrite ↑[power];exact !idp_con⁻¹)
(λn IH, calc
p⁻¹ ⬝ power p (succ n) = p⁻¹ ⬝ power p n ⬝ p : con.assoc
... = power p (pred n) ⬝ p : by rewrite IH
... = power p (succ (pred n)) : power_con
... = power p (pred (succ n)) : by rewrite [succ_pred,-int.pred_succ n])
( λn IH, calc
p⁻¹ ⬝ power p (-succ n) = p⁻¹ ⬝ (power p (-n) ⬝ p⁻¹) : by rewrite [↑power,rec_nat_on_neg]
... = (p⁻¹ ⬝ power p (-n)) ⬝ p⁻¹ : con.assoc
... = power p (pred (-n)) ⬝ p⁻¹ : by rewrite IH
... = power p (-succ n) ⬝ p⁻¹ : by rewrite -neg_succ
... = power p (-succ (succ n)) : by rewrite [↑power,-rec_nat_on_neg]
... = power p (pred (-succ n)) : by rewrite -neg_succ)
definition power_con_power : Π(b : ℤ), power p b ⬝ power p c = power p (b + c) :=
rec_nat_on c
(λb, by rewrite int.add_zero)
(λn IH b, by rewrite [-con_power,-con.assoc,power_con,IH,↑succ,int.add.assoc,int.add.comm 1 n])
(λn IH b, by rewrite [neg_nat_succ,-inv_con_power,-con.assoc,power_con_inv,IH,↑pred,
+sub_eq_add_neg,int.add.assoc,int.add.comm (-1) (-n)])
end eq
|
f934c24b2ad34af5a3b5271ab3dbeddc23d20b01
|
3b15c7b0b62d8ada1399c112ad88a529e6bfa115
|
/stage0/src/Init/NotationExtra.lean
|
dbf41b35a19fa73ab000e12860b1dd97bf578a43
|
[
"Apache-2.0"
] |
permissive
|
stephenbrady/lean4
|
74bf5cae8a433e9c815708ce96c9e54a5caf2115
|
b1bd3fc304d0f7bc6810ec78bfa4c51476d263f9
|
refs/heads/master
| 1,692,621,473,161
| 1,634,308,743,000
| 1,634,310,749,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 8,338
|
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
Extra notation that depends on Init/Meta
-/
prelude
import Init.Meta
import Init.Data.Array.Subarray
import Init.Data.ToString
namespace Lean
syntax "Macro.trace[" ident "]" interpolatedStr(term) : term
macro_rules
| `(Macro.trace[$id] $s) => `(Macro.trace $(quote id.getId) (s! $s))
-- Auxiliary parsers and functions for declaring notation with binders
syntax binderIdent := ident <|> "_"
syntax unbracketedExplicitBinders := binderIdent+ (" : " term)?
syntax bracketedExplicitBinders := "(" binderIdent+ " : " term ")"
syntax explicitBinders := bracketedExplicitBinders+ <|> unbracketedExplicitBinders
def expandExplicitBindersAux (combinator : Syntax) (idents : Array Syntax) (type? : Option Syntax) (body : Syntax) : MacroM Syntax :=
let rec loop (i : Nat) (acc : Syntax) := do
match i with
| 0 => pure acc
| i+1 =>
let ident := idents[i][0]
let acc ← match ident.isIdent, type? with
| true, none => `($combinator fun $ident => $acc)
| true, some type => `($combinator fun $ident:ident : $type => $acc)
| false, none => `($combinator fun _ => $acc)
| false, some type => `($combinator fun _ : $type => $acc)
loop i acc
loop idents.size body
def expandBrackedBindersAux (combinator : Syntax) (binders : Array Syntax) (body : Syntax) : MacroM Syntax :=
let rec loop (i : Nat) (acc : Syntax) := do
match i with
| 0 => pure acc
| i+1 =>
let idents := binders[i][1].getArgs
let type := binders[i][3]
loop i (← expandExplicitBindersAux combinator idents (some type) acc)
loop binders.size body
def expandExplicitBinders (combinatorDeclName : Name) (explicitBinders : Syntax) (body : Syntax) : MacroM Syntax := do
let combinator := mkIdentFrom (← getRef) combinatorDeclName
let explicitBinders := explicitBinders[0]
if explicitBinders.getKind == ``Lean.unbracketedExplicitBinders then
let idents := explicitBinders[0].getArgs
let type? := if explicitBinders[1].isNone then none else some explicitBinders[1][1]
expandExplicitBindersAux combinator idents type? body
else if explicitBinders.getArgs.all (·.getKind == ``Lean.bracketedExplicitBinders) then
expandBrackedBindersAux combinator explicitBinders.getArgs body
else
Macro.throwError "unexpected explicit binder"
def expandBrackedBinders (combinatorDeclName : Name) (bracketedExplicitBinders : Syntax) (body : Syntax) : MacroM Syntax := do
let combinator := mkIdentFrom (← getRef) combinatorDeclName
expandBrackedBindersAux combinator #[bracketedExplicitBinders] body
syntax unifConstraint := term (" =?= " <|> " ≟ ") term
syntax unifConstraintElem := colGe unifConstraint ", "?
syntax attrKind "unif_hint " (ident)? bracketedBinder* " where " withPosition(unifConstraintElem*) ("|-" <|> "⊢ ") unifConstraint : command
private def mkHintBody (cs : Array Syntax) (p : Syntax) : MacroM Syntax := do
let mut body ← `($(p[0]) = $(p[2]))
for c in cs.reverse do
body ← `($(c[0][0]) = $(c[0][2]) → $body)
return body
macro_rules
| `($kind:attrKind unif_hint $bs:explicitBinder* where $cs* |- $p) => do
let body ← mkHintBody cs p
`(@[$kind:attrKind unificationHint] def hint $bs:explicitBinder* : Sort _ := $body)
| `($kind:attrKind unif_hint $n:ident $bs* where $cs* |- $p) => do
let body ← mkHintBody cs p
`(@[$kind:attrKind unificationHint] def $n:ident $bs:explicitBinder* : Sort _ := $body)
end Lean
open Lean
macro "∃ " xs:explicitBinders ", " b:term : term => expandExplicitBinders ``Exists xs b
macro "exists" xs:explicitBinders ", " b:term : term => expandExplicitBinders ``Exists xs b
macro "Σ" xs:explicitBinders ", " b:term : term => expandExplicitBinders ``Sigma xs b
macro "Σ'" xs:explicitBinders ", " b:term : term => expandExplicitBinders ``PSigma xs b
macro:35 xs:bracketedExplicitBinders " × " b:term:35 : term => expandBrackedBinders ``Sigma xs b
macro:35 xs:bracketedExplicitBinders " ×' " b:term:35 : term => expandBrackedBinders ``PSigma xs b
-- enforce indentation of calc steps so we know when to stop parsing them
syntax calcStep := colGe term " := " withPosition(term)
syntax (name := calc) "calc " withPosition((calcStep ppLine)+) : term
macro "calc " steps:withPosition(calcStep+) : tactic => `(exact calc $(steps.getArgs)*)
@[appUnexpander Unit.unit] def unexpandUnit : Lean.PrettyPrinter.Unexpander
| `($(_)) => `(())
| _ => throw ()
@[appUnexpander List.nil] def unexpandListNil : Lean.PrettyPrinter.Unexpander
| `($(_)) => `([])
| _ => throw ()
@[appUnexpander List.cons] def unexpandListCons : Lean.PrettyPrinter.Unexpander
| `($(_) $x []) => `([$x])
| `($(_) $x [$xs,*]) => `([$x, $xs,*])
| _ => throw ()
@[appUnexpander List.toArray] def unexpandListToArray : Lean.PrettyPrinter.Unexpander
| `($(_) [$xs,*]) => `(#[$xs,*])
| _ => throw ()
@[appUnexpander Prod.mk] def unexpandProdMk : Lean.PrettyPrinter.Unexpander
| `($(_) $x ($y, $ys,*)) => `(($x, $y, $ys,*))
| `($(_) $x $y) => `(($x, $y))
| _ => throw ()
@[appUnexpander ite] def unexpandIte : Lean.PrettyPrinter.Unexpander
| `($(_) $c $t $e) => `(if $c then $t else $e)
| _ => throw ()
@[appUnexpander sorryAx] def unexpandSorryAx : Lean.PrettyPrinter.Unexpander
| `($(_) _) => `(sorry)
| `($(_) _ _) => `(sorry)
| _ => throw ()
@[appUnexpander Eq.ndrec] def unexpandEqNDRec : Lean.PrettyPrinter.Unexpander
| `($(_) $m $h) => `($h ▸ $m)
| _ => throw ()
@[appUnexpander Eq.rec] def unexpandEqRec : Lean.PrettyPrinter.Unexpander
| `($(_) $m $h) => `($h ▸ $m)
| _ => throw ()
@[appUnexpander Exists] def unexpandExists : Lean.PrettyPrinter.Unexpander
| `($(_) fun $x:ident => ∃ $xs:binderIdent*, $b) => `(∃ $x:ident $xs:binderIdent*, $b)
| `($(_) fun $x:ident => $b) => `(∃ $x:ident, $b)
| `($(_) fun ($x:ident : $t) => $b) => `(∃ ($x:ident : $t), $b)
| _ => throw ()
@[appUnexpander Sigma] def unexpandSigma : Lean.PrettyPrinter.Unexpander
| `($(_) fun ($x:ident : $t) => $b) => `(($x:ident : $t) × $b)
| _ => throw ()
@[appUnexpander PSigma] def unexpandPSigma : Lean.PrettyPrinter.Unexpander
| `($(_) fun ($x:ident : $t) => $b) => `(($x:ident : $t) ×' $b)
| _ => throw ()
@[appUnexpander Subtype] def unexpandSubtype : Lean.PrettyPrinter.Unexpander
| `($(_) fun ($x:ident : $type) => $p) => `({ $x : $type // $p })
| `($(_) fun $x:ident => $p) => `({ $x // $p })
| _ => throw ()
syntax "funext " (colGt term:max)+ : tactic
macro_rules
| `(tactic|funext $xs*) =>
if xs.size == 1 then
`(tactic| apply funext; intro $(xs[0]):term)
else
`(tactic| apply funext; intro $(xs[0]):term; funext $(xs[1:])*)
macro_rules
| `(%[ $[$x],* | $k ]) =>
if x.size < 8 then
x.foldrM (init := k) fun x k =>
`(List.cons $x $k)
else
let m := x.size / 2
let y := x[m:]
let z := x[:m]
`(let y := %[ $[$y],* | $k ]
%[ $[$z],* | y ])
/-
Expands
```
class abbrev C <params> := D_1, ..., D_n
```
into
```
class C <params> extends D_1, ..., D_n
attribute [instance] C.mk
```
-/
syntax declModifiers "class " "abbrev " declId bracketedBinder* (":" term)?
":=" withPosition(group(colGe term ","?)*) : command
macro_rules
| `($mods:declModifiers class abbrev $id $params* $[: $ty:term]? := $[ $parents:term $[,]? ]*) =>
let name := id[0]
let ctor := mkIdentFrom name <| name.getId.modifyBase (. ++ `mk)
`($mods:declModifiers class $id $params* extends $[$parents:term],* $[: $ty]?
attribute [instance] $ctor)
/-
Similar to `first`, but succeeds only if one the given tactics solves the current goal.
-/
syntax (name := solve) "solve " withPosition((group(colGe "|" tacticSeq))+) : tactic
macro_rules
| `(tactic| solve $[| $ts]* ) => `(tactic| focus first $[| ($ts); done]*)
|
3d617f7f05f34034d1ee97116f38c9cc03ffe85a
|
5d166a16ae129621cb54ca9dde86c275d7d2b483
|
/library/data/hash_map.lean
|
c6fa5bdfb5ccc3126d02a6c18291aeb22827e4d1
|
[
"Apache-2.0"
] |
permissive
|
jcarlson23/lean
|
b00098763291397e0ac76b37a2dd96bc013bd247
|
8de88701247f54d325edd46c0eed57aeacb64baf
|
refs/heads/master
| 1,611,571,813,719
| 1,497,020,963,000
| 1,497,021,515,000
| 93,882,536
| 1
| 0
| null | 1,497,029,896,000
| 1,497,029,896,000
| null |
UTF-8
|
Lean
| false
| false
| 35,270
|
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, Mario Carneiro
-/
import data.list.set data.list.comb init.data.array data.pnat
universes u v w
def bucket_array (α : Type u) (β : α → Type v) (n : ℕ+) :=
array (list Σ a, β a) n.1
def hash_map.mk_idx (n : ℕ+) (i : nat) : fin n.1 :=
⟨i % n.1, nat.mod_lt _ n.2⟩
namespace bucket_array
section
parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat)
variables {n : ℕ+} (data : bucket_array α β n)
def read (a : α) : list Σ a, β a :=
let bidx := hash_map.mk_idx n (hash_fn a) in
data.read bidx
def write (hash_fn : α → nat) (a : α) (l : list Σ a, β a) : bucket_array α β n :=
let bidx := hash_map.mk_idx n (hash_fn a) in
data.write bidx l
def modify (hash_fn : α → nat) (a : α) (f : list (Σ a, β a) → list (Σ a, β a)) : bucket_array α β n :=
let bidx := hash_map.mk_idx n (hash_fn a) in
array.write data bidx (f (array.read data bidx))
def as_list : list Σ a, β a :=
data.foldl [] (λbkt r, r ++ bkt)
theorem mem_as_list (a : Σ a, β a) : a ∈ data.as_list ↔ ∃i, a ∈ array.read data i :=
suffices ∀j h, a ∈ array.iterate_aux data (λ_ bkt r, r ++ bkt) j h [] ↔
∃ (i : fin n.1), i.1 < j ∧ a ∈ array.read data i, from
iff.trans (this _ _) (exists_congr $ λi, and_iff_right i.2),
begin
intros,
induction j with j IH,
exact ⟨false.elim, λ⟨i, h, _⟩, absurd h (nat.not_lt_zero _)⟩,
note IH := IH (le_of_lt h),
simp[array.iterate_aux],
exact ⟨λo, or.elim o
(λm, ⟨⟨j, h⟩, nat.le_refl _, m⟩)
(λm, let ⟨i, il, im⟩ := IH.1 m in ⟨i, nat.le_succ_of_le il, im⟩),
λ⟨i, le, m⟩, or.elim (lt_or_eq_of_le (nat.le_of_succ_le_succ le))
(λl, or.inr (IH.2 ⟨i, l, m⟩))
(λe, or.inl $ by rwa -(show i = ⟨j, h⟩, from fin.eq_of_veq e))⟩
end
def foldl {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) : δ :=
data.foldl d (λ b d, b.foldl (λ r a, f r a.1 a.2) d)
lemma foldl_eq_lem {γ : Type u} {δ : Type w} (d : δ) (f : δ → γ → δ) : Π l : list (list γ),
l.foldr (λ (b:list γ) d, b.foldl f d) d = (l.foldr (λ(bkt r : list γ), r ++ bkt) []).foldl f d
| [] := rfl
| (l::ls) := show l.foldl f (ls.foldr (λ (b:list γ) d, b.foldl f d) d) =
(ls.foldr (λ (bkt r : list γ), r ++ bkt) [] ++ l).foldl f d, by rw [list.append_foldl, foldl_eq_lem ls]
theorem foldl_eq {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) :
data.foldl d f = data.as_list.foldl (λ r a, f r a.1 a.2) d :=
let f' : δ → (Σ a, β a) → δ := λ r a, f r a.1 a.2 in
let g : list (Σ a, β a) → δ → δ := λ b d, b.foldl f' d in
calc array.foldl data d g = data.rev_list.foldr g d : data.foldl_eq d g
... = (data.rev_list.foldr (λ(bkt r : list (Σa, β a)), r ++ bkt) []).foldl f' d : foldl_eq_lem _ _ _
... = (array.foldl data [] (λbkt r, r ++ bkt)).foldl f' d : by rw array.foldl_eq data [] (λbkt r, r ++ bkt)
end
end bucket_array
namespace hash_map
section
parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat)
def reinsert_aux {n} (data : bucket_array α β n) (a : α) (b : β a) : bucket_array α β n :=
data.modify hash_fn a (λl, ⟨a, b⟩ :: l)
parameter [decidable_eq α]
def find_aux (a : α) : list (Σ a, β a) → option (β a)
| [] := none
| (⟨a',b⟩::t) := if h : a' = a then some (eq.rec_on h b) else find_aux t
theorem find_aux_iff (a : α) (b : β a) : Π (l : list Σ a, β a), (l.map sigma.fst).nodup → (find_aux a l = some b ↔ sigma.mk a b ∈ l)
| [] nd := ⟨λn, by contradiction, false.elim⟩
| (⟨a',b'⟩::t) nd := by simp[find_aux]; exact
if h : a' = a then by rw dif_pos h; exact
match a', b', h with ._, b', rfl :=
⟨λe, by injection e with e; rw -e; exact or.inl rfl,
λo, or.elim o
(λe, by injection e with _ e; rw eq_of_heq e)
(λm, have a' ∉ t.map sigma.fst, from list.not_mem_of_nodup_cons nd,
by rw h at this; exact absurd (list.mem_map sigma.fst m) this)⟩
end
else by rw dif_neg h; exact iff.trans (find_aux_iff t $ list.nodup_of_nodup_cons nd)
(iff.symm $ or_iff_right_of_imp (λn, by injection n with aa _; rw aa at h; contradiction))
def contains_aux (a : α) (l : list Σ a, β a) : bool :=
(find_aux a l).is_some
theorem contains_aux_iff (a : α) (l : list Σ a, β a) (nd : (l.map sigma.fst).nodup) : (contains_aux a l ↔ a ∈ l.map sigma.fst) :=
begin
delta contains_aux,
ginduction find_aux a l with h b,
all_goals {rw h},
refine ⟨λn, by contradiction, λm, _⟩,
exact
let ⟨⟨a', b⟩, m, e⟩ := list.exists_of_mem_map m in
match a', b, m, e with ._, b, m, rfl :=
by rw ((find_aux_iff a b l nd).2 m) at h; contradiction end,
exact ⟨λ_, list.mem_map _ ((find_aux_iff a b l nd).1 h), λ_, dec_trivial⟩,
end
def replace_aux (a : α) (b : β a) : list (Σ a, β a) → list (Σ a, β a)
| [] := []
| (⟨a', b'⟩::t) := if a' = a then ⟨a, b⟩::t else ⟨a', b'⟩ :: replace_aux t
def erase_aux (a : α) : list (Σ a, β a) → list (Σ a, β a)
| [] := []
| (⟨a', b'⟩::t) := if a' = a then t else ⟨a', b'⟩ :: erase_aux t
inductive valid_aux {α : Type u} {β : α → Type v} (idx : α → nat) : Π (l : list (list Σ a, β a)) (sz : nat), Prop
| nil {} : valid_aux [] 0
| cons : Π (c : list Σ a, β a) {l sz}, valid_aux l sz → (c.map sigma.fst).nodup →
(∀ a ∈ c, idx (sigma.fst a) = l.length) → valid_aux (c::l) (sz + c.length)
theorem valid_aux.unfold_cons {idx : α → nat} : Π {c l sz}, valid_aux idx (c::l) sz →
∃ sz', valid_aux idx l sz' ∧ (c.map sigma.fst).nodup ∧ (∀ a ∈ c, idx (sigma.fst a) = l.length) ∧ sz = sz' + c.length
| ._ ._ ._ (@valid_aux.cons ._ ._ ._ c l sz' v nd e) := ⟨sz', v, nd, e, rfl⟩
theorem valid_aux.nodup {idx : α → nat} : Π {l : list (list Σ a, β a)} {sz : nat}, valid_aux idx l sz →
∀ ⦃c : list Σ a, β a⦄, c ∈ l → (c.map sigma.fst).nodup
| ._ ._ valid_aux.nil c' cl := false.elim cl
| ._ ._ (@valid_aux.cons ._ ._ ._ c l sz v nd e) c' cl := or.elim cl (λe, by rwa e) (λm : c' ∈ l, valid_aux.nodup v m)
theorem valid_aux.eq {idx : α → nat} : Π {l : list (list Σ a, β a)} {sz : nat}, valid_aux idx l sz →
∀ {i h a b}, sigma.mk a b ∈ l.nth_le i h → idx a = l.length - 1 - i
| ._ ._ valid_aux.nil i h _ _ _ := absurd h (nat.not_lt_zero _)
| ._ ._ (@valid_aux.cons ._ ._ ._ c l sz v nd e) 0 h a b el := e ⟨a, b⟩ el
| ._ ._ (@valid_aux.cons ._ ._ ._ c l sz v nd e) (i+1) h a b el :=
have idx a = list.length l - 1 - i, from valid_aux.eq v el,
by rwa [nat.sub_sub, nat.add_comm] at this
theorem valid_aux.insert_lemma1 {idx : α → nat} : Π {l : list (list Σ a, β a)} {sz : nat}, valid_aux idx l sz →
∀ {i h a b}, sigma.mk a b ∈ l.nth_le i h → idx a = l.length - 1 - i
| ._ ._ valid_aux.nil i h _ _ _ := absurd h (nat.not_lt_zero _)
| ._ ._ (@valid_aux.cons ._ ._ ._ c l sz v nd e) 0 h a b el := e ⟨a, b⟩ el
| ._ ._ (@valid_aux.cons ._ ._ ._ c l sz v nd e) (i+1) h a b el :=
have idx a = list.length l - 1 - i, from valid_aux.eq v el,
by rwa [nat.sub_sub, nat.add_comm] at this
def valid {n} (bkts : bucket_array α β n) (sz : nat) : Prop :=
valid_aux (λa, (mk_idx n (hash_fn a)).1) bkts.rev_list sz
theorem valid.nodup {n} {bkts : bucket_array α β n} {sz : nat} : valid bkts sz → ∀i, ((array.read bkts i).map sigma.fst).nodup :=
λv i, valid_aux.nodup v ((bkts.mem_iff_rev_list_mem _).1 (bkts.read_mem i))
theorem valid.eq {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz)
{i h a b} (el : sigma.mk a b ∈ array.read bkts ⟨i, h⟩) : (mk_idx n (hash_fn a)).1 = i :=
have h1 : list.length (array.to_list bkts) - 1 - i < list.length (list.reverse (array.to_list bkts)),
by simph[array.to_list_length, nat.sub_one_sub_lt],
have _, from nat.sub_eq_sub_min,
have sigma.mk a b ∈ list.nth_le (array.to_list bkts) i (by simph[array.to_list_length]), by {rw array.to_list_nth, exact el},
begin
rw -list.nth_le_reverse at this,
assert v : valid_aux (λa, (mk_idx n (hash_fn a)).1) (array.to_list bkts).reverse sz,
rw array.to_list_reverse,
exact v,
note mm := @_root_.hash_map.valid_aux.eq _ _ _ _ _ _ v -- TODO (Mario): Why is explicit namespacing needed here?
(list.length (array.to_list bkts) - 1 - i) h1 a b this,
rwa [list.length_reverse, array.to_list_length, nat.sub_sub_self (show i ≤ n.1 - 1, from nat.pred_le_pred h)] at mm
end
theorem valid.eq' {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz)
{i a b} (el : sigma.mk a b ∈ array.read bkts i) : mk_idx n (hash_fn a) = i :=
fin.eq_of_veq (match i, el with ⟨j, h⟩, el := v.eq _ el end)
theorem valid.as_list_nodup {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) : (bkts.as_list.map sigma.fst).nodup :=
suffices ∀i h, ((bkts.iterate_aux (λ _ bkt r, r ++ bkt) i h []).map sigma.fst).nodup ∧
∀a, a ∈ bkts.iterate_aux (λ _ bkt r, r ++ bkt) i h [] → (mk_idx n (hash_fn a.1)).1 < i, from (this n.1 (le_refl _)).left,
begin
intros,
induction i with i IH,
exact ⟨list.nodup.ndnil, λ_, false.elim⟩,
simp[array.iterate_aux, list.map_append], exact
let ⟨nd, al⟩ := IH (le_of_lt h) in
⟨ list.nodup_append_of_nodup_of_nodup_of_disjoint nd (v.nodup _ _) $ λa m1 m2,
let ⟨⟨a', b⟩, m1, e1⟩ := list.exists_of_mem_map m1 in
let ⟨⟨a'', b'⟩, m2, e2⟩ := list.exists_of_mem_map m2 in
match a', a'', b, b', m1, m2, e1, e2 with ._, ._, b, b', m1, m2, rfl, rfl :=
by {note hlt := al _ m1, rw v.eq _ m2 at hlt, exact lt_irrefl _ hlt}
end,
λ⟨a, b⟩ m, or.elim m
(λm2, by rw v.eq _ m2; exact nat.le_refl _)
(λm1, nat.le_succ_of_le (al _ m1))⟩
end
theorem valid.as_list_length {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) : bkts.as_list.length = sz :=
have ∀l sz, valid_aux (λ (a : α), (mk_idx n (hash_fn a)).val) l sz → ∀t, (l.foldr (λbkt r, r ++ bkt) t).length = sz + t.length,
by {intros, induction a, simp[list.foldr], simp[list.foldr, ih_1]},
by note h := this _ _ v []; rwa -array.foldl_eq at h
theorem valid.mk (n : ℕ+) : @valid n (mk_array n.1 []) 0 :=
let bkts : bucket_array α β n := mk_array n.1 [] in
show valid_aux (λa, (mk_idx n (hash_fn a)).1) (array.iterate_aux bkts (λ_ v l, v :: l) n.1 (le_refl n.1) []) 0, from
@nat.rec_on (λi, Πh:i≤n.1, valid_aux (λa, (mk_idx n (hash_fn a)).1)
(array.iterate_aux bkts (λ_ v l, v :: l) i h []) 0) n.1 (λ_, valid_aux.nil)
(λi IH h, valid_aux.cons _ (IH (le_of_lt h)) list.nodup.ndnil (λ_, false.elim)) (le_refl _)
theorem valid.find_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) (a : α) (b : β a) :
find_aux a (bkts.read hash_fn a) = some b ↔ sigma.mk a b ∈ bkts.as_list :=
iff.trans (find_aux_iff _ _ _ (v.nodup _ _))
$ iff.trans (by exact ⟨λm, ⟨_, m⟩, λ⟨⟨i, h⟩, m⟩, by rwa -(v.eq' _ m) at m⟩)
(iff.symm (bkts.mem_as_list _))
theorem valid.contains_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) (a : α) :
contains_aux a (bkts.read hash_fn a) ↔ a ∈ bkts.as_list.map sigma.fst :=
begin
delta contains_aux,
ginduction find_aux a (bkts.read hash_fn a) with h b,
all_goals {rw h},
refine ⟨λn, by contradiction, λm, _⟩,
exact
let ⟨⟨a', b⟩, m, e⟩ := list.exists_of_mem_map m in
match a', b, m, e with ._, b, m, rfl :=
by rw ((v.find_aux_iff _ a b).2 m) at h; contradiction end,
exact ⟨λ_, list.mem_map _ ((v.find_aux_iff _ a b).1 h), λ_, dec_trivial⟩,
end
theorem mk_as_list (n : ℕ+) : bucket_array.as_list (mk_array n.1 [] : bucket_array α β n) = [] :=
list.eq_nil_of_length_eq_zero ((valid.mk n).as_list_length _)
section
parameters {n : ℕ+} {bkts : bucket_array α β n}
{bidx : fin n.1} {f : list (Σ a, β a) → list (Σ a, β a)}
(u v1 v2 w : list Σ a, β a)
local notation `L` := array.read bkts bidx
private def bkts' : bucket_array α β n := array.write bkts bidx (f L)
theorem valid.modify_aux1 {δ fn} {b : δ} : Π (i) (h : i ≤ n.1) (hb : i ≤ bidx.1),
array.iterate_aux bkts fn i h b = array.iterate_aux bkts' fn i h b
| 0 h hb := by simp[array.iterate_aux]
| (i+1) h (hb : i < bidx.1) := by simp[array.iterate_aux]; exact
have bn : bidx ≠ ⟨i, h⟩, from λhh, ne_of_lt hb $ fin.veq_of_eq $ eq.symm hh,
congr (congr_arg (fn _) (show _ = ite (bidx = ⟨i, h⟩) (f _) _, by rw if_neg bn))
(valid.modify_aux1 i (le_of_lt h) (le_of_lt hb))
variables (hl : L = u ++ v1 ++ w)
(hfl : f L = u ++ v2 ++ w)
include hl hfl
theorem append_of_modify_aux : Π (i) (h : i ≤ n.1) (hb : i > bidx.1),
∃ u' w', array.iterate_aux bkts (λ_ bkt r, r ++ bkt) i h [] = u' ++ v1 ++ w' ∧
array.iterate_aux bkts' (λ_ bkt r, r ++ bkt) i h [] = u' ++ v2 ++ w'
| 0 _ hb := absurd hb (nat.not_lt_zero _)
| (i+1) h hb :=
match nat.lt_or_eq_of_le $ nat.le_of_succ_le_succ hb with
| or.inl hl :=
have bn : bidx ≠ ⟨i, h⟩, from λhh, ne_of_gt hl $ fin.veq_of_eq $ eq.symm hh,
have he : array.read bkts ⟨i, h⟩ = array.read bkts' ⟨i, h⟩, from
(show _ = ite (bidx = ⟨i, h⟩) (f _) _, by rw if_neg bn),
by simp[array.iterate_aux]; rw -he; exact
let ⟨u', w', hb, hb'⟩ := append_of_modify_aux i (le_of_lt h) hl in
⟨u', w' ++ array.read bkts ⟨i, h⟩, by simp[hb], by simp[hb']⟩
| or.inr e :=
match i, e, h with ._, rfl, h :=
have array.read bkts' bidx = f L, from
show ite (bidx = bidx) _ _ = _, by rw if_pos rfl,
begin
simp[array.iterate_aux] without add_comm,
rw -(show bidx = ⟨bidx.1, h⟩, from fin.eq_of_veq rfl),
refine ⟨array.iterate_aux bkts (λ_ bkt r, r ++ bkt) bidx.1 (le_of_lt h) [] ++ u, w, _⟩,
rw -valid.modify_aux1 _ _ (le_refl _),
rw [this, hfl, hl],
simp
end
end
end
theorem append_of_modify : ∃ u' w', bkts.as_list = u' ++ v1 ++ w' ∧ bkts'.as_list = u' ++ v2 ++ w' :=
append_of_modify_aux hl hfl _ _ bidx.2
variables (hvnd : (v2.map sigma.fst).nodup)
(hal : ∀ (a : Σ a, β a), a ∈ v2 → mk_idx n (hash_fn a.1) = bidx)
(djuv : (u.map sigma.fst).disjoint (v2.map sigma.fst))
(djwv : (w.map sigma.fst).disjoint (v2.map sigma.fst))
include hvnd hal djuv djwv
theorem valid.modify_aux2 : Π (i) (h : i ≤ n.1) (hb : i > bidx.1) {sz : ℕ},
valid_aux (λa, (mk_idx n (hash_fn a)).1) (array.iterate_aux bkts (λ_ v l, v :: l) i h []) sz → sz + v2.length ≥ v1.length ∧
valid_aux (λa, (mk_idx n (hash_fn a)).1) (array.iterate_aux bkts' (λ_ v l, v :: l) i h []) (sz + v2.length - v1.length)
| 0 _ hb sz := absurd hb (nat.not_lt_zero _)
| (i+1) h hb sz :=
match nat.lt_or_eq_of_le $ nat.le_of_succ_le_succ hb with
| or.inl hl :=
have bn : bidx ≠ ⟨i, h⟩, from λhh, ne_of_gt hl $ fin.veq_of_eq $ eq.symm hh,
have he : array.read bkts ⟨i, h⟩ = array.read bkts' ⟨i, h⟩, from
(show _ = ite (bidx = ⟨i, h⟩) (f _) _, by rw if_neg bn),
by simp[array.iterate_aux]; rw -he; exact λvv,
let ⟨s, v, nd, al, e⟩ := _root_.hash_map.valid_aux.unfold_cons vv in
let ⟨hsz, v'⟩ := valid.modify_aux2 i (le_of_lt h) hl v in
by rw [e, calc (s + (array.read bkts ⟨i, h⟩).length) + v2.length - v1.length
= s + v2.length + (array.read bkts ⟨i, h⟩).length - v1.length : by simp
... = s + v2.length - v1.length + (array.read bkts ⟨i, h⟩).length : nat.sub_add_comm hsz]; exact
⟨nat.le_trans hsz $ nat.add_le_add_right (nat.le_add_right _ _) _,
valid_aux.cons _ v' nd (by rw bkts'.rev_list_length_aux; rwa bkts.rev_list_length_aux at al)⟩
| or.inr e :=
match i, e, h with ._, rfl, h :=
have array.read bkts' bidx = f L, from
show ite (bidx = bidx) _ _ = _, by rw if_pos rfl,
begin
simp[array.iterate_aux] without add_comm,
rw [-(show bidx = ⟨bidx.1, h⟩, from fin.eq_of_veq rfl),
-valid.modify_aux1 _ _ (le_refl _),
this, hfl, hl],
exact λvv,
let ⟨s, v, nd, al, e⟩ := _root_.hash_map.valid_aux.unfold_cons vv in
have nd' : ((u ++ v2 ++ w).map sigma.fst).nodup, begin
rw [list.map_append, list.map_append] at nd,
rw [list.map_append, list.map_append],
note ndu : (u.map sigma.fst).nodup := list.nodup_of_nodup_append_left (list.nodup_of_nodup_append_left nd),
note ndv1 : (v1.map sigma.fst).nodup := list.nodup_of_nodup_append_right (list.nodup_of_nodup_append_left nd),
note ndw : (w.map sigma.fst).nodup := list.nodup_of_nodup_append_right nd,
note djuw : (u.map sigma.fst).disjoint (w.map sigma.fst) :=
list.disjoint_of_disjoint_append_left_left (list.disjoint_of_nodup_append nd),
exact list.nodup_append_of_nodup_of_nodup_of_disjoint
(list.nodup_append_of_nodup_of_nodup_of_disjoint ndu hvnd djuv)
ndw (list.disjoint_append_of_disjoint_left djuw djwv.comm)
end,
begin
rw [e, calc s + (u ++ v1 ++ w).length + v2.length - v1.length
= s + u.length + v1.length + w.length + v2.length - v1.length : by simp[list.length_append]
... = s + u.length + v2.length + w.length + v1.length - v1.length : by simp
... = s + u.length + v2.length + w.length : by rw[nat.add_sub_cancel]
... = s + (u ++ v2 ++ w).length : by simp[list.length_append, list.length_append]],
constructor,
exact calc v1.length
≤ v1.length + (s + u.length + w.length + v2.length) : nat.le_add_right _ _
... = s + (u.length + v1.length + w.length) + v2.length : by simp
... = s + (u ++ v1 ++ w).length + v2.length : by rw[list.length_append, list.length_append],
apply valid_aux.cons _ v nd',
intros a muvw,
simp at al,
simp at muvw,
cases muvw with mu mvw,
exact al a (or.inl mu),
cases mvw with mv mw,
rw bkts.rev_list_length_aux,
exact congr_arg fin.val (hal a mv),
exact al a (or.inr (or.inr mw)),
end
end
end
end
theorem valid.modify {sz : ℕ} : valid bkts sz → sz + v2.length ≥ v1.length ∧ valid bkts' (sz + v2.length - v1.length) :=
valid.modify_aux2 hl hfl hvnd hal djuv djwv _ _ bidx.2
end
theorem valid.replace_aux (a : α) (b : β a) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst →
∃ (u w : list Σ a, β a) b', l = u ++ [⟨a, b'⟩] ++ w ∧ replace_aux a b l = u ++ [⟨a, b⟩] ++ w ∧ a ∉ u.map sigma.fst
| [] Hc := false.elim Hc
| (⟨a', b'⟩::t) Hc := begin
simp at Hc,
simp [replace_aux] without and.comm,
exact match (by apply_instance : decidable (a' = a)) with
| is_true e := match a', b', e with ._, b', rfl := ⟨[], t, b', rfl, rfl, by simp⟩ end
| is_false ne :=
let ⟨u, w, b'', hl, hfl, nin⟩ := valid.replace_aux t (or.resolve_left Hc (λe, ne (eq.symm e))) in
show ∃ (u w : list (Σ (a : α), β a)) (b'_1 : β a), sigma.mk a' b' :: t = u ++ ⟨a, b'_1⟩ :: w ∧
(sigma.mk a' b' :: hash_map.replace_aux a b t) = u ++ ⟨a, b⟩ :: w ∧ a ∉ list.map sigma.fst u, from
⟨⟨a', b'⟩ :: u, w, b'', by simp[hl], by simp[hfl], λm, by {simp at m, cases m with e m, exact ne (eq.symm e), exact nin m}⟩
end
end
theorem valid.replace {n : ℕ+}
{bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a)
(Hc : contains_aux a (bkts.read hash_fn a))
(v : valid bkts sz) : valid (bkts.modify hash_fn a (replace_aux a b)) sz :=
let nd := v.nodup hash_fn (mk_idx n (hash_fn a)) in
let ⟨u, w, b', hl, hfl, nin⟩ := valid.replace_aux a b
(array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff _ _ nd).1 Hc) in
and.right $ valid.modify
u [⟨a, b'⟩] [⟨a, b⟩] w hl hfl (list.nodup_singleton _)
(λa' e, by simp at e; rw e)
(λa' e1 e2, by simp at e2; rw e2 at e1; exact nin e1)
(λa' e1 e2, begin
simp at e2,
rw e2 at e1,
rw [hl, list.map_append, list.map_append] at nd,
apply list.disjoint_of_nodup_append nd _ e1,
simp
end) v
theorem valid.insert {n : ℕ+}
{bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a)
(Hnc : ¬ contains_aux a (bkts.read hash_fn a))
(v : valid bkts sz) : valid (reinsert_aux bkts a b) (sz+1) :=
let nd := v.nodup hash_fn (mk_idx n (hash_fn a)) in
and.right $ valid.modify
[] [] [⟨a, b⟩] (bkts.read hash_fn a) rfl rfl (list.nodup_singleton _)
(λa' e, by simp at e; rw e)
(λa', false.elim)
(λa' e1 e2, begin
simp at e2,
rw e2 at e1,
exact Hnc ((contains_aux_iff _ _ nd).2 e1)
end) v
theorem valid.erase_aux (a : α) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst →
∃ (u w : list Σ a, β a) b, l = u ++ [⟨a, b⟩] ++ w ∧ erase_aux a l = u ++ [] ++ w
| [] Hc := false.elim Hc
| (⟨a', b'⟩::t) Hc := begin
simp at Hc,
simp [erase_aux],
exact match (by apply_instance : decidable (a' = a)) with
| is_true e := match a', b', e with ._, b', rfl := ⟨[], t, b', rfl, rfl⟩ end
| is_false ne :=
let ⟨u, w, b'', hl, hfl⟩ := valid.erase_aux t (or.resolve_left Hc (λe, ne (eq.symm e))) in
⟨⟨a', b'⟩::u, w, b'', by simp[hl], by simp[ne, hfl]⟩
end
end
theorem valid.erase {n} {bkts : bucket_array α β n} {sz}
(a : α) (Hc : contains_aux a (bkts.read hash_fn a))
(v : valid bkts sz) : valid (bkts.modify hash_fn a (erase_aux a)) (sz-1) :=
let nd := v.nodup _ (mk_idx n (hash_fn a)) in
let ⟨u, w, b, hl, hfl⟩ := valid.erase_aux a (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff _ _ nd).1 Hc) in
and.right $ valid.modify
u [⟨a, b⟩] [] w hl hfl list.nodup.ndnil
(λa', false.elim) (λa' e1, false.elim) (λa' e1, false.elim) v
end
end hash_map
structure hash_map (α : Type u) [decidable_eq α] (β : α → Type v) :=
(hash_fn : α → nat)
(size : ℕ)
(nbuckets : ℕ+)
(buckets : bucket_array α β nbuckets)
(is_valid : hash_map.valid hash_fn buckets size)
def mk_hash_map {α : Type u} [decidable_eq α] {β : α → Type v} (hash_fn : α → nat) (nbuckets := 8) : hash_map α β :=
let n := if nbuckets = 0 then 8 else nbuckets in
let nz : n > 0 := by abstract {dsimp, cases nbuckets, {simp, tactic.comp_val}, simp [if_pos, nat.succ_ne_zero], apply nat.zero_lt_succ} in
{ hash_fn := hash_fn,
size := 0,
nbuckets := ⟨n, nz⟩,
buckets := mk_array n [],
is_valid := hash_map.valid.mk _ _ }
namespace hash_map
variables {α : Type u} {β : α → Type v} [decidable_eq α]
def find (m : hash_map α β) (a : α) : option (β a) :=
find_aux a (m.buckets.read m.hash_fn a)
def contains (m : hash_map α β) (a : α) : bool :=
(m.find a).is_some
instance : has_mem α (hash_map α β) := ⟨λa m, m.contains a⟩
def fold {δ : Type w} (m : hash_map α β) (d : δ) (f : δ → Π a, β a → δ) : δ :=
m.buckets.foldl d f
def entries (m : hash_map α β) : list Σ a, β a :=
m.buckets.as_list
def keys (m : hash_map α β) : list α :=
m.entries.map sigma.fst
theorem find_iff (m : hash_map α β) (a : α) (b : β a) :
m.find a = some b ↔ sigma.mk a b ∈ m.entries :=
m.is_valid.find_aux_iff _ _ _
theorem contains_iff (m : hash_map α β) (a : α) (b : β a) :
m.contains a ↔ a ∈ m.keys :=
m.is_valid.contains_aux_iff _ _
lemma insert_lemma (hash_fn : α → nat) {n n'}
{bkts : bucket_array α β n} {sz} (v : valid hash_fn bkts sz) :
valid hash_fn (bkts.foldl (mk_array _ [] : bucket_array α β n') (reinsert_aux hash_fn)) sz :=
suffices ∀ (l : list Σ a, β a),
∀ (t : bucket_array α β n') sz, valid hash_fn t sz → ((l ++ t.as_list).map sigma.fst).nodup →
valid hash_fn (l.foldl (λr (a : Σ a, β a), reinsert_aux hash_fn r a.1 a.2) t) (sz + l.length),
begin
note p := this bkts.as_list _ _ (valid.mk _ _),
rw [mk_as_list hash_fn, list.append_nil, zero_add, v.as_list_length _] at p,
rw bucket_array.foldl_eq,
exact p (v.as_list_nodup _),
end,
λl, begin
induction l with c l IH,
exact λ t sz v nd, v,
intros t sz v nd,
rw (show sz + (c :: l).length = sz + 1 + l.length, by simp),
simp at nd,
note nc := list.not_mem_of_nodup_cons nd,
note v' := v.insert _ _ c.2
(λHc, nc $ list.mem_append_right _ $
(v.contains_aux_iff _ c.1).1 Hc),
apply IH _ _ v',
simp,
note nd' := list.nodup_of_nodup_cons nd,
apply list.nodup_append_of_nodup_of_nodup_of_disjoint
(list.nodup_of_nodup_append_left nd')
(v'.as_list_nodup _),
exact λa m1 m2,
let ⟨⟨a', b⟩, m1, e1⟩ := list.exists_of_mem_map m1 in
let ⟨⟨a'', b'⟩, m2, e2⟩ := list.exists_of_mem_map m2 in
match a', a'', b, b', m1, m2, e1, e2 with ._, ._, b, b', m1, m2, rfl, rfl :=
let ⟨i, im⟩ := ((reinsert_aux hash_fn t c.1 c.2).mem_as_list _).1 m2 in
have im : sigma.mk a b' ∈ ite _ _ _, from im,
have sigma.mk a b' ∉ array.read t i, from λm3,
have a ∈ list.map sigma.fst (bucket_array.as_list t), from
list.mem_map sigma.fst ((t.mem_as_list _).2 ⟨_, m3⟩),
list.disjoint_of_nodup_append nd' (list.mem_map sigma.fst m1) this,
if h : mk_idx n' (hash_fn c.1) = i
then by simp[h] at im; exact or.elim im
(λe, nc $ list.mem_append_left _ (by rwa -(show a = c.fst, from congr_arg sigma.fst e)))
this
else by simp[h] at im; exact this im
end
end
def insert : Π (m : hash_map α β) (a : α) (b : β a), hash_map α β
| ⟨hash_fn, size, n, buckets, v⟩ a b :=
let bkt := buckets.read hash_fn a in
if hc : contains_aux a bkt then
{ hash_fn := hash_fn,
size := size,
nbuckets := n,
buckets := buckets.modify hash_fn a (replace_aux a b),
is_valid := v.replace _ a b hc }
else
let size' := size + 1,
buckets' := buckets.modify hash_fn a (λl, ⟨a, b⟩::l),
valid' := v.insert _ a b hc in
if size' ≤ n.1 then
{ hash_fn := hash_fn,
size := size',
nbuckets := n,
buckets := buckets',
is_valid := valid' }
else
let n' : ℕ+ := ⟨n.1 * 2, mul_pos n.2 dec_trivial⟩,
buckets'' : bucket_array α β n' :=
buckets'.foldl (mk_array _ []) (reinsert_aux hash_fn) in
{ hash_fn := hash_fn,
size := size',
nbuckets := n',
buckets := buckets'',
is_valid := insert_lemma _ valid' }
theorem mem_insert : Π (m : hash_map α β) (a b a' b'),
sigma.mk a' b' ∈ (m.insert a b).entries ↔
if a = a' then b == b' else sigma.mk a' b' ∈ m.entries
| ⟨hash_fn, size, n, bkts, v⟩ a b a' b' :=
let bkt := bkts.read hash_fn a,
nd : (bkt.map sigma.fst).nodup := v.nodup hash_fn (mk_idx n (hash_fn a)) in
have lem : Π (bkts' : bucket_array α β n) (v1 u w)
(hl : bucket_array.as_list bkts = u ++ v1 ++ w)
(hfl : bucket_array.as_list bkts' = u ++ [⟨a, b⟩] ++ w)
(veq : (v1 = [] ∧ ¬ contains_aux a bkt) ∨ ∃b'', v1 = [⟨a, b''⟩]),
sigma.mk a' b' ∈ bkts'.as_list ↔
if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list, from
λbkts' v1 u w hl hfl veq, by rw [hl, hfl]; exact
if h : a = a' then by simp[h]; exact
match a', b', h with ._, b', rfl :=
have nd' : _, from v.as_list_nodup _,
have a ∉ u.map sigma.fst ++ w.map sigma.fst, from match v1, veq, hl with
| ._, or.inl ⟨rfl, Hnc⟩, hl := let na := (not_iff_not_of_iff $ v.contains_aux_iff _ _).1 Hnc in
have bkts.as_list.map sigma.fst = u.map sigma.fst ++ w.map sigma.fst, by simp [hl],
by rw this at na; exact na
| ._, or.inr ⟨b'', rfl⟩, hl := by {
note nd' := v.as_list_nodup _,
rw hl at nd', simp at nd',
exact list.not_mem_of_nodup_cons (list.nodup_head nd') }
end,
show sigma.mk a b' = ⟨a, b⟩ ∨ sigma.mk a b' ∈ u ∨ sigma.mk a b' ∈ w ↔ b == b', from
⟨λo, match o with
| or.inl e := by injection e with _ e; exact heq.symm e
| or.inr (or.inl mu) := absurd (list.mem_append_left _ (list.mem_map sigma.fst mu)) this
| or.inr (or.inr mw) := absurd (list.mem_append_right _ (list.mem_map sigma.fst mw)) this
end,
λe, or.inl $ congr_arg (sigma.mk a) $ eq.symm $ eq_of_heq e⟩
end
else match v1, veq, hl with
| ._, or.inl ⟨rfl, Hnc⟩, hl := by {
simp[h],
refine ⟨λo, or.elim o (λ(hn : sigma.mk a' b' = ⟨a, b⟩), _) id, or.inr⟩,
{ injection hn with hn _, exact absurd hn.symm h } }
| ._, or.inr ⟨b'', rfl⟩, hl := by {
simp[h],
refine or_congr ⟨λ(hn : sigma.mk a' b' = ⟨a, b⟩), _,
λ(hn : sigma.mk a' b' = ⟨a, b''⟩), _⟩ (iff.refl _);
{ injection hn with hn _, exact absurd hn.symm h } }
end,
by simp[insert]; exact
match (by apply_instance : decidable (contains_aux a bkt)) with
| is_true Hc :=
let bkts' := bkts.modify hash_fn a (replace_aux a b),
⟨u', w', b'', hl', hfl', _⟩ := valid.replace_aux a b
(array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff _ _ nd).1 Hc),
⟨u, w, hl, hfl⟩ := show ∃ u' w', _ ∧ bkts'.as_list = _, from
append_of_modify u' [⟨a, b''⟩] [⟨a, b⟩] w' hl' hfl' in
lem bkts' _ u w hl hfl $ or.inr ⟨b'', rfl⟩
| is_false Hnc :=
let size' := size + 1,
bkts' := bkts.modify hash_fn a (λl, ⟨a, b⟩::l) in
have sigma.mk a' b' ∈ bkts'.as_list ↔ if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list, from
let ⟨u, w, hl, hfl⟩ := show ∃ u' w', _ ∧ bkts'.as_list = _, from
append_of_modify [] [] [⟨a, b⟩] _ rfl rfl in
lem bkts' _ u w hl hfl $ or.inl ⟨rfl, Hnc⟩,
match (by apply_instance : decidable (size' ≤ n.1)) with
| is_true _ := this
| is_false _ :=
let n' : ℕ+ := ⟨n.1 * 2, mul_pos n.2 dec_trivial⟩,
bkts'' : bucket_array α β n' := bkts'.foldl (mk_array _ []) (reinsert_aux hash_fn) in
suffices h : sigma.mk a' b' ∈ bkts''.as_list ↔ sigma.mk a' b' ∈ bkts'.as_list.reverse,
from h.trans $ (list.mem_reverse _ _).trans this,
have h : bkts'' = bkts'.as_list.foldl _ _, from bkts'.foldl_eq _ _,
begin
rw -list.foldr_reverse at h, rw h,
generalize bkts'.as_list.reverse l, intro l, induction l with a l IH,
{ simp, rw[mk_as_list hash_fn n'], simp },
{ cases a with a'' b'', simp, rw -IH, exact
let B := l.foldr (λ y (x : bucket_array α β n'),
reinsert_aux hash_fn x y.1 y.2) (mk_array n'.1 []),
⟨u, w, hl, hfl⟩ := show ∃ u' w', B.as_list = _ ∧
(reinsert_aux hash_fn B a'' b'').as_list = _, from
append_of_modify [] [] [⟨a'', b''⟩] _ rfl rfl in
by simp [hl, hfl] }
end
end
end
theorem find_insert_eq (m : hash_map α β) (a : α) (b : β a) : (m.insert a b).find a = some b :=
(find_iff (m.insert a b) a b).2 $ (mem_insert m a b a b).2 $ by rw if_pos rfl
theorem find_insert_ne (m : hash_map α β) (a a' : α) (b : β a) (h : a ≠ a') :
(m.insert a b).find a' = m.find a' :=
option.eq_of_eq_some $ λb',
let t := mem_insert m a b a' b' in
(find_iff _ _ _).trans $ iff.trans (by rwa if_neg h at t) (find_iff _ _ _).symm
theorem find_insert (m : hash_map α β) (a' a : α) (b : β a) :
(m.insert a b).find a' = if h : a = a' then some (eq.rec_on h b) else m.find a' :=
if h : a = a' then by rw dif_pos h; exact
match a', h with ._, rfl := find_insert_eq m a b end
else by rw dif_neg h; exact find_insert_ne m a a' b h
def erase (m : hash_map α β) (a : α) : hash_map α β :=
match m with ⟨hash_fn, size, n, buckets, v⟩ :=
if hc : contains_aux a (buckets.read hash_fn a) then
{ hash_fn := hash_fn,
size := size - 1,
nbuckets := n,
buckets := buckets.modify hash_fn a (erase_aux a),
is_valid := v.erase _ a hc }
else m
end
theorem mem_erase : Π (m : hash_map α β) (a a' b'),
sigma.mk a' b' ∈ (m.erase a).entries ↔
a ≠ a' ∧ sigma.mk a' b' ∈ m.entries
| ⟨hash_fn, size, n, bkts, v⟩ a a' b' :=
let bkt := bkts.read hash_fn a in
by simp[erase]; exact
match (by apply_instance : decidable (contains_aux a bkt)) with
| is_true Hc :=
let bkts' := bkts.modify hash_fn a (erase_aux a) in
show sigma.mk a' b' ∈ bkts'.as_list ↔ a ≠ a' ∧ sigma.mk a' b' ∈ bkts.as_list, from
let nd := v.nodup _ (mk_idx n (hash_fn a)) in
let ⟨u', w', b, hl', hfl'⟩ := valid.erase_aux a bkt ((contains_aux_iff _ _ nd).1 Hc) in
match bkts.as_list, bkts'.as_list,
append_of_modify u' [⟨a, b⟩] [] _ hl' hfl', v.as_list_nodup _ with
| ._, ._, ⟨u, w, rfl, rfl⟩, nd' := by simp; simp at nd'; exact
⟨λhm, ⟨λe, match a', e, b', hm with ._, rfl, b', hm := by {
rw -list.mem_append_iff at hm;
note hm := list.mem_map sigma.fst hm;
rw list.map_append at hm;
exact list.not_mem_of_nodup_cons (list.nodup_head nd') hm }
end, or.inr hm⟩,
λ⟨hn, o⟩, or.elim o (λhm, by injection hm with hm; exact absurd hm.symm hn) id⟩
end
| is_false Hnc :=
by refine ⟨λ(h : sigma.mk a' b' ∈ bkts.as_list), ⟨_, h⟩, and.right⟩;
exact λe, match a', e, b', h with ._, rfl, b, h :=
Hnc $ (v.contains_aux_iff _ _).2 (list.mem_map sigma.fst h)
end
end
theorem find_erase_eq (m : hash_map α β) (a : α) : (m.erase a).find a = none :=
begin
ginduction (m.erase a).find a with h b, refl,
exact absurd rfl ((mem_erase m a a b).1 ((find_iff (m.erase a) a b).1 h)).left
end
theorem find_erase_ne (m : hash_map α β) (a a' : α) (h : a ≠ a') :
(m.erase a).find a' = m.find a' :=
option.eq_of_eq_some $ λb',
(find_iff _ _ _).trans $ (mem_erase m a a' b').trans $
(and_iff_right h).trans (find_iff _ _ _).symm
theorem find_erase (m : hash_map α β) (a' a : α) :
(m.erase a).find a' = if a = a' then none else m.find a' :=
if h : a = a' then by rw if_pos h; exact
match a', h with ._, rfl := find_erase_eq m a end
else by rw if_neg h; exact find_erase_ne m a a' h
section string
variables [has_to_string α] [∀ a, has_to_string (β a)]
open prod
private def key_data_to_string (a : α) (b : β a) (first : bool) : string :=
(if first then "" else ", ") ++ sformat!"{a} ← {b}"
private def to_string (m : hash_map α β) : string :=
"⟨" ++ (fst (fold m ("", tt) (λ p a b, (fst p ++ key_data_to_string a b (snd p), ff)))) ++ "⟩"
instance : has_to_string (hash_map α β) :=
⟨to_string⟩
end string
section format
open format prod
variables [has_to_format α] [∀ a, has_to_format (β a)]
private meta def format_key_data (a : α) (b : β a) (first : bool) : format :=
(if first then to_fmt "" else to_fmt "," ++ line) ++ to_fmt a ++ space ++ to_fmt "←" ++ space ++ to_fmt b
private meta def to_format (m : hash_map α β) : format :=
group $ to_fmt "⟨" ++ nest 1 (fst (fold m (to_fmt "", tt) (λ p a b, (fst p ++ format_key_data a b (snd p), ff)))) ++
to_fmt "⟩"
meta instance : has_to_format (hash_map α β) :=
⟨to_format⟩
end format
end hash_map
|
1a0b87be9d18aef17d2ee5697d67589120187313
|
fa02ed5a3c9c0adee3c26887a16855e7841c668b
|
/test/zify.lean
|
e3d80696f2c1001a6258efe0b367dc84bc82b5b2
|
[
"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
| 752
|
lean
|
import tactic.zify
example (a b c x y z : ℕ) (h : ¬ x*y*z < 0) (h2 : (c : ℤ) < a + 3 * b) : a + 3*b > c :=
begin
zify at h ⊢,
guard_hyp h : ¬↑x * ↑y * ↑z < (0 : ℤ),
guard_target ↑c < (↑a : ℤ) + 3 * ↑b,
exact h2
end
example (a b : ℕ) (h : (a : ℤ) ≤ b) : a ≤ b :=
begin
zify,
guard_target (a : ℤ) ≤ b,
exact h
end
example (a b : ℕ) (h : a = b ∧ b < a) : false :=
begin
zify at h,
cases h with ha hb,
apply ne_of_lt hb,
rw ha
end
example (a b c : ℕ) (h : a - b < c) (hab : b ≤ a) : true :=
begin
zify [hab] at h,
guard_hyp h : (a : ℤ) - b < c,
trivial
end
example (a b c : ℕ) (h : a + b ≠ c) : true :=
begin
zify at h,
guard_hyp h : (a : ℤ) + b ≠ c,
trivial
end
|
d820d3b11236f5d6ee7850b560ca323b5668e052
|
9028d228ac200bbefe3a711342514dd4e4458bff
|
/src/ring_theory/polynomial/rational_root.lean
|
348be044c69fc3423e465fbaa38a7c8a14aba1b4
|
[
"Apache-2.0"
] |
permissive
|
mcncm/mathlib
|
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
|
fde3d78cadeec5ef827b16ae55664ef115e66f57
|
refs/heads/master
| 1,672,743,316,277
| 1,602,618,514,000
| 1,602,618,514,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 4,998
|
lean
|
/-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import ring_theory.polynomial.scale_roots
import ring_theory.localization
/-!
# Rational root theorem and integral root theorem
This file contains the rational root theorem and integral root theorem.
The rational root theorem for a unique factorization domain `A`
with localization `S`, states that the roots of `p : polynomial A` in `A`'s
field of fractions are of the form `x / y` with `x y : A`, `x ∣ p.coeff 0` and
`y ∣ p.leading_coeff`.
The corollary is the integral root theorem `is_integer_of_is_root_of_monic`:
if `p` is monic, its roots must be integers.
Finally, we use this to show unique factorization domains are integrally closed.
## References
* https://en.wikipedia.org/wiki/Rational_root_theorem
-/
section scale_roots
variables {A K R S : Type*} [integral_domain A] [field K] [comm_ring R] [comm_ring S]
variables {M : submonoid A} {f : localization_map M S} {g : fraction_map A K}
open finsupp polynomial
lemma scale_roots_aeval_eq_zero_of_aeval_mk'_eq_zero {p : polynomial A} {r : A} {s : M}
(hr : @aeval A f.codomain _ _ _ (f.mk' r s) p = 0) :
@aeval A f.codomain _ _ _ (f.to_map r) (scale_roots p s) = 0 :=
begin
convert scale_roots_eval₂_eq_zero f.to_map hr,
rw aeval_def,
congr,
apply (f.mk'_spec' r s).symm
end
lemma num_is_root_scale_roots_of_aeval_eq_zero
[unique_factorization_monoid A] (g : fraction_map A K)
{p : polynomial A} {x : g.codomain} (hr : aeval x p = 0) :
is_root (scale_roots p (g.denom x)) (g.num x) :=
begin
apply is_root_of_eval₂_map_eq_zero g.injective,
refine scale_roots_aeval_eq_zero_of_aeval_mk'_eq_zero _,
rw g.mk'_num_denom,
exact hr
end
end scale_roots
section rational_root_theorem
variables {A K : Type*} [integral_domain A] [unique_factorization_monoid A] [field K]
variables {f : fraction_map A K}
open polynomial unique_factorization_monoid
/-- Rational root theorem part 1:
if `r : f.codomain` is a root of a polynomial over the ufd `A`,
then the numerator of `r` divides the constant coefficient -/
theorem num_dvd_of_is_root {p : polynomial A} {r : f.codomain} (hr : aeval r p = 0) :
f.num r ∣ p.coeff 0 :=
begin
suffices : f.num r ∣ (scale_roots p (f.denom r)).coeff 0,
{ simp only [coeff_scale_roots, nat.sub_zero] at this,
haveI := classical.prop_decidable,
by_cases hr : f.num r = 0,
{ obtain ⟨u, hu⟩ := (f.is_unit_denom_of_num_eq_zero hr).pow p.nat_degree,
rw ←hu at this,
exact units.dvd_mul_right.mp this },
{ refine dvd_of_dvd_mul_left_of_no_prime_of_factor hr _ this,
intros q dvd_num dvd_denom_pow hq,
apply hq.not_unit,
exact f.num_denom_reduced r dvd_num (hq.dvd_of_dvd_pow dvd_denom_pow) } },
convert dvd_term_of_is_root_of_dvd_terms 0 (num_is_root_scale_roots_of_aeval_eq_zero f hr) _,
{ rw [pow_zero, mul_one] },
intros j hj,
apply dvd_mul_of_dvd_right,
convert pow_dvd_pow (f.num r) (nat.succ_le_of_lt (bot_lt_iff_ne_bot.mpr hj)),
exact (pow_one _).symm
end
/-- Rational root theorem part 2:
if `r : f.codomain` is a root of a polynomial over the ufd `A`,
then the denominator of `r` divides the leading coefficient -/
theorem denom_dvd_of_is_root {p : polynomial A} {r : f.codomain} (hr : aeval r p = 0) :
(f.denom r : A) ∣ p.leading_coeff :=
begin
suffices : (f.denom r : A) ∣ p.leading_coeff * f.num r ^ p.nat_degree,
{ refine dvd_of_dvd_mul_left_of_no_prime_of_factor
(mem_non_zero_divisors_iff_ne_zero.mp (f.denom r).2) _ this,
intros q dvd_denom dvd_num_pow hq,
apply hq.not_unit,
exact f.num_denom_reduced r (hq.dvd_of_dvd_pow dvd_num_pow) dvd_denom },
rw ←coeff_scale_roots_nat_degree,
apply dvd_term_of_is_root_of_dvd_terms _ (num_is_root_scale_roots_of_aeval_eq_zero f hr),
intros j hj,
by_cases h : j < p.nat_degree,
{ refine dvd_mul_of_dvd_left (dvd_mul_of_dvd_right _ _) _,
convert pow_dvd_pow _ (nat.succ_le_iff.mpr (nat.lt_sub_left_of_add_lt _)),
{ exact (pow_one _).symm },
simpa using h },
rw [←nat_degree_scale_roots p (f.denom r)] at *,
rw [coeff_eq_zero_of_nat_degree_lt (lt_of_le_of_ne (le_of_not_gt h) hj.symm), zero_mul],
exact dvd_zero _
end
/-- Integral root theorem:
if `r : f.codomain` is a root of a monic polynomial over the ufd `A`,
then `r` is an integer -/
theorem is_integer_of_is_root_of_monic {p : polynomial A} (hp : monic p) {r : f.codomain}
(hr : aeval r p = 0) : f.is_integer r :=
f.is_integer_of_is_unit_denom (is_unit_of_dvd_one _ (hp ▸ denom_dvd_of_is_root hr))
namespace unique_factorization_monoid
lemma integer_of_integral {x : f.codomain} :
is_integral A x → f.is_integer x :=
λ ⟨p, hp, hx⟩, is_integer_of_is_root_of_monic hp hx
lemma integrally_closed : integral_closure A f.codomain = ⊥ :=
eq_bot_iff.mpr (λ x hx, algebra.mem_bot.mpr (integer_of_integral hx))
end unique_factorization_monoid
end rational_root_theorem
|
0ebcc573bcd502d248956e8e6d86e68208e69e16
|
2a70b774d16dbdf5a533432ee0ebab6838df0948
|
/_target/deps/mathlib/src/data/polynomial/erase_lead.lean
|
680b5464fba032728eaffa02e8252a05c5961e7e
|
[
"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
| 5,589
|
lean
|
/-
Copyright (c) 2020 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import data.polynomial.degree
import data.polynomial.degree.trailing_degree
/-!
# Erase the leading term of a univariate polynomial
## Definition
* `erase_lead f`: the polynomial `f - leading term of f`
`erase_lead` serves as reduction step in an induction, shaving off one monomial from a polynomial.
The definition is set up so that it does not mention subtraction in the definition,
and thus works for polynomials over semirings as well as rings.
-/
noncomputable theory
open_locale classical
open polynomial finsupp finset
namespace polynomial
variables {R : Type*} [semiring R] {f : polynomial R}
/-- `erase_lead f` for a polynomial `f` is the polynomial obtained by
subtracting from `f` the leading term of `f`. -/
def erase_lead (f : polynomial R) : polynomial R :=
finsupp.erase f.nat_degree f
section erase_lead
lemma erase_lead_support (f : polynomial R) :
f.erase_lead.support = f.support.erase f.nat_degree :=
-- `rfl` fails because LHS uses `nat.decidable_eq` but RHS is classical.
by convert rfl
lemma erase_lead_coeff (i : ℕ) :
f.erase_lead.coeff i = if i = f.nat_degree then 0 else f.coeff i :=
-- `rfl` fails because LHS uses `nat.decidable_eq` but RHS is classical.
by convert rfl
@[simp] lemma erase_lead_coeff_nat_degree : f.erase_lead.coeff f.nat_degree = 0 :=
finsupp.erase_same
lemma erase_lead_coeff_of_ne (i : ℕ) (hi : i ≠ f.nat_degree) :
f.erase_lead.coeff i = f.coeff i :=
finsupp.erase_ne hi
@[simp] lemma erase_lead_zero : erase_lead (0 : polynomial R) = 0 :=
finsupp.erase_zero _
@[simp] lemma erase_lead_add_monomial_nat_degree_leading_coeff (f : polynomial R) :
f.erase_lead + monomial f.nat_degree f.leading_coeff = f :=
begin
ext i,
simp only [erase_lead_coeff, coeff_monomial, coeff_add, @eq_comm _ _ i],
split_ifs with h,
{ subst i, simp only [leading_coeff, zero_add] },
{ exact add_zero _ }
end
@[simp] lemma erase_lead_add_C_mul_X_pow (f : polynomial R) :
f.erase_lead + (C f.leading_coeff) * X ^ f.nat_degree = f :=
by rw [C_mul_X_pow_eq_monomial, erase_lead_add_monomial_nat_degree_leading_coeff]
@[simp] lemma self_sub_monomial_nat_degree_leading_coeff {R : Type*} [ring R] (f : polynomial R) :
f - monomial f.nat_degree f.leading_coeff = f.erase_lead :=
(eq_sub_iff_add_eq.mpr (erase_lead_add_monomial_nat_degree_leading_coeff f)).symm
@[simp] lemma self_sub_C_mul_X_pow {R : Type*} [ring R] (f : polynomial R) :
f - (C f.leading_coeff) * X ^ f.nat_degree = f.erase_lead :=
by rw [C_mul_X_pow_eq_monomial, self_sub_monomial_nat_degree_leading_coeff]
lemma erase_lead_ne_zero (f0 : 2 ≤ f.support.card) : erase_lead f ≠ 0 :=
begin
rw [ne.def, ← finsupp.card_support_eq_zero, erase_lead_support],
exact (zero_lt_one.trans_le $ (nat.sub_le_sub_right f0 1).trans
finset.pred_card_le_card_erase).ne.symm
end
@[simp] lemma nat_degree_not_mem_erase_lead_support : f.nat_degree ∉ (erase_lead f).support :=
by convert not_mem_erase _ _
lemma ne_nat_degree_of_mem_erase_lead_support {a : ℕ} (h : a ∈ (erase_lead f).support) :
a ≠ f.nat_degree :=
by { rintro rfl, exact nat_degree_not_mem_erase_lead_support h }
lemma erase_lead_support_card_lt (h : f ≠ 0) : (erase_lead f).support.card < f.support.card :=
begin
rw erase_lead_support,
exact card_lt_card (erase_ssubset $ nat_degree_mem_support_of_nonzero h)
end
lemma erase_lead_card_support {c : ℕ} (fc : f.support.card = c) :
f.erase_lead.support.card = c - 1 :=
begin
by_cases f0 : f = 0,
{ rw [← fc, f0, erase_lead_zero, support_zero, card_empty] },
{ rw [erase_lead_support, card_erase_of_mem (nat_degree_mem_support_of_nonzero f0), fc],
exact c.pred_eq_sub_one },
end
lemma erase_lead_card_support' {c : ℕ} (fc : f.support.card = c + 1) :
f.erase_lead.support.card = c :=
erase_lead_card_support fc
@[simp] lemma erase_lead_monomial (i : ℕ) (r : R) :
erase_lead (monomial i r) = 0 :=
begin
by_cases hr : r = 0,
{ subst r, simp only [monomial_zero_right, erase_lead_zero] },
{ rw [erase_lead, nat_degree_monomial _ _ hr], exact erase_single }
end
@[simp] lemma erase_lead_C (r : R) : erase_lead (C r) = 0 :=
erase_lead_monomial _ _
@[simp] lemma erase_lead_X : erase_lead (X : polynomial R) = 0 :=
erase_lead_monomial _ _
@[simp] lemma erase_lead_X_pow (n : ℕ) : erase_lead (X ^ n : polynomial R) = 0 :=
by rw [X_pow_eq_monomial, erase_lead_monomial]
@[simp] lemma erase_lead_C_mul_X_pow (r : R) (n : ℕ) : erase_lead (C r * X ^ n) = 0 :=
by rw [C_mul_X_pow_eq_monomial, erase_lead_monomial]
lemma erase_lead_degree_le : (erase_lead f).degree ≤ f.degree :=
begin
rw degree_le_iff_coeff_zero,
intros i hi,
rw erase_lead_coeff,
split_ifs with h, { refl },
apply coeff_eq_zero_of_degree_lt hi
end
lemma erase_lead_nat_degree_le : (erase_lead f).nat_degree ≤ f.nat_degree :=
nat_degree_le_nat_degree erase_lead_degree_le
lemma erase_lead_nat_degree_lt (f0 : 2 ≤ f.support.card) :
(erase_lead f).nat_degree < f.nat_degree :=
lt_of_le_of_ne erase_lead_nat_degree_le $ ne_nat_degree_of_mem_erase_lead_support $
nat_degree_mem_support_of_nonzero $ erase_lead_ne_zero f0
lemma erase_lead_nat_degree_lt_or_erase_lead_eq_zero (f : polynomial R) :
(erase_lead f).nat_degree < f.nat_degree ∨ f.erase_lead = 0 :=
begin
by_cases h : f.support.card ≤ 1,
{ right,
rw ← C_mul_X_pow_eq_self h,
simp },
{ left,
apply erase_lead_nat_degree_lt (lt_of_not_ge h) }
end
end erase_lead
end polynomial
|
4bce4fff82239c77e8595fac7722c02f304ddd21
|
7cef822f3b952965621309e88eadf618da0c8ae9
|
/src/data/padics/padic_integers.lean
|
dc49403852efda1f28cefbaf167ecef668bcd0c5
|
[
"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
| 10,683
|
lean
|
/-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis, Mario Carneiro
-/
import data.int.modeq data.padics.padic_numbers ring_theory.ideals ring_theory.algebra
/-!
# p-adic integers
This file defines the p-adic integers ℤ_p as the subtype of ℚ_p with norm ≤ 1. We show that ℤ_p is a
complete nonarchimedean normed local ring.
## Important definitions
* `padic_int` : the type of p-adic numbers
## Notation
We introduce the notation ℤ_[p] for the p-adic integers.
## Implementation notes
Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically
by taking (prime p) as a type class argument.
Coercions into ℤ_p are set up to work with the `norm_cast` tactic.
## References
* [F. Q. Gouêva, *p-adic numbers*][gouvea1997]
* [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]
* <https://en.wikipedia.org/wiki/P-adic_number>
## Tags
p-adic, p adic, padic, p-adic integer
-/
open nat padic metric
noncomputable theory
open_locale classical
/-- The p-adic integers ℤ_p are the p-adic numbers with norm ≤ 1. -/
def padic_int (p : ℕ) [p.prime] := {x : ℚ_[p] // ∥x∥ ≤ 1}
notation `ℤ_[`p`]` := padic_int p
namespace padic_int
variables {p : ℕ} [nat.prime p]
/-- Addition on ℤ_p is inherited from ℚ_p. -/
def add : ℤ_[p] → ℤ_[p] → ℤ_[p]
| ⟨x, hx⟩ ⟨y, hy⟩ := ⟨x+y,
le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx,hy⟩)⟩
/-- Multiplication on ℤ_p is inherited from ℚ_p. -/
def mul : ℤ_[p] → ℤ_[p] → ℤ_[p]
| ⟨x, hx⟩ ⟨y, hy⟩ := ⟨x*y,
begin rw padic_norm_e.mul, apply mul_le_one; {assumption <|> apply norm_nonneg} end⟩
/-- Negation on ℤ_p is inherited from ℚ_p. -/
def neg : ℤ_[p] → ℤ_[p]
| ⟨x, hx⟩ := ⟨-x, by simpa⟩
instance : ring ℤ_[p] :=
begin
refine { add := add,
mul := mul,
neg := neg,
zero := ⟨0, by simp [zero_le_one]⟩,
one := ⟨1, by simp⟩,
.. };
{repeat {rintro ⟨_, _⟩}, simp [mul_assoc, left_distrib, right_distrib, add, mul, neg]}
end
lemma zero_def : ∀ x : ℤ_[p], x = 0 ↔ x.val = 0
| ⟨x, _⟩ := ⟨subtype.mk.inj, λ h, by simp at h; simp only [h]; refl⟩
@[simp] lemma add_def : ∀ (x y : ℤ_[p]), (x+y).val = x.val + y.val
| ⟨x, hx⟩ ⟨y, hy⟩ := rfl
@[simp] lemma mul_def : ∀ (x y : ℤ_[p]), (x*y).val = x.val * y.val
| ⟨x, hx⟩ ⟨y, hy⟩ := rfl
@[simp] lemma mk_zero {h} : (⟨0, h⟩ : ℤ_[p]) = (0 : ℤ_[p]) := rfl
instance : has_coe ℤ_[p] ℚ_[p] := ⟨subtype.val⟩
@[simp] lemma val_eq_coe (z : ℤ_[p]) : z.val = ↑z := rfl
@[simp, move_cast] lemma coe_add : ∀ (z1 z2 : ℤ_[p]), (↑(z1 + z2) : ℚ_[p]) = ↑z1 + ↑z2
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp, move_cast] lemma coe_mul : ∀ (z1 z2 : ℤ_[p]), (↑(z1 * z2) : ℚ_[p]) = ↑z1 * ↑z2
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp, move_cast] lemma coe_neg : ∀ (z1 : ℤ_[p]), (↑(-z1) : ℚ_[p]) = -↑z1
| ⟨_, _⟩ := rfl
@[simp, move_cast] lemma coe_sub : ∀ (z1 z2 : ℤ_[p]), (↑(z1 - z2) : ℚ_[p]) = ↑z1 - ↑z2
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp, squash_cast] lemma coe_one : (↑(1 : ℤ_[p]) : ℚ_[p]) = 1 := rfl
@[simp, squash_cast] lemma coe_coe : ∀ n : ℕ, (↑(↑n : ℤ_[p]) : ℚ_[p]) = (↑n : ℚ_[p])
| 0 := rfl
| (k+1) := by simp [coe_coe]
@[simp, squash_cast] lemma coe_zero : (↑(0 : ℤ_[p]) : ℚ_[p]) = 0 := rfl
@[simp, move_cast] lemma cast_pow (x : ℤ_[p]) : ∀ (n : ℕ), (↑(x^n) : ℚ_[p]) = (↑x : ℚ_[p])^n
| 0 := by simp
| (k+1) := by simp [monoid.pow, pow]; congr; apply cast_pow
lemma mk_coe : ∀ (k : ℤ_[p]), (⟨↑k, k.2⟩ : ℤ_[p]) = k
| ⟨_, _⟩ := rfl
/-- The inverse of a p-adic integer with norm equal to 1 is also a p-adic integer. Otherwise, the
inverse is defined to be 0. -/
def inv : ℤ_[p] → ℤ_[p]
| ⟨k, _⟩ := if h : ∥k∥ = 1 then ⟨1/k, by simp [h]⟩ else 0
end padic_int
section instances
variables {p : ℕ} [nat.prime p]
@[reducible] def padic_norm_z (z : ℤ_[p]) : ℝ := ∥z.val∥
instance : metric_space ℤ_[p] := subtype.metric_space
instance : has_norm ℤ_[p] := ⟨padic_norm_z⟩
instance : normed_ring ℤ_[p] :=
{ dist_eq := λ ⟨_, _⟩ ⟨_, _⟩, rfl,
norm_mul := λ ⟨_, _⟩ ⟨_, _⟩, norm_mul_le _ _ }
instance padic_norm_z.is_absolute_value : is_absolute_value (λ z : ℤ_[p], ∥z∥) :=
{ abv_nonneg := norm_nonneg,
abv_eq_zero := λ ⟨_, _⟩, by simp [norm_eq_zero, padic_int.zero_def],
abv_add := λ ⟨_,_⟩ ⟨_, _⟩, norm_add_le _ _,
abv_mul := λ _ _, by unfold norm; simp [padic_norm_z] }
protected lemma padic_int.pmul_comm : ∀ z1 z2 : ℤ_[p], z1*z2 = z2*z1
| ⟨q1, h1⟩ ⟨q2, h2⟩ := show (⟨q1*q2, _⟩ : ℤ_[p]) = ⟨q2*q1, _⟩, by simp [mul_comm]
instance : comm_ring ℤ_[p] :=
{ mul_comm := padic_int.pmul_comm,
..padic_int.ring }
protected lemma padic_int.zero_ne_one : (0 : ℤ_[p]) ≠ 1 :=
show (⟨(0 : ℚ_[p]), _⟩ : ℤ_[p]) ≠ ⟨(1 : ℚ_[p]), _⟩, from mt subtype.ext.1 zero_ne_one
protected lemma padic_int.eq_zero_or_eq_zero_of_mul_eq_zero :
∀ (a b : ℤ_[p]), a * b = 0 → a = 0 ∨ b = 0
| ⟨a, ha⟩ ⟨b, hb⟩ := λ h : (⟨a * b, _⟩ : ℤ_[p]) = ⟨0, _⟩,
have a * b = 0, from subtype.ext.1 h,
(mul_eq_zero_iff_eq_zero_or_eq_zero.1 this).elim
(λ h1, or.inl (by simp [h1]; refl))
(λ h2, or.inr (by simp [h2]; refl))
instance : integral_domain ℤ_[p] :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := padic_int.eq_zero_or_eq_zero_of_mul_eq_zero,
zero_ne_one := padic_int.zero_ne_one,
..padic_int.comm_ring }
end instances
namespace padic_norm_z
variables {p : ℕ} [nat.prime p]
lemma le_one : ∀ z : ℤ_[p], ∥z∥ ≤ 1
| ⟨_, h⟩ := h
@[simp] lemma one : ∥(1 : ℤ_[p])∥ = 1 := by simp [norm, padic_norm_z]
@[simp] lemma mul (z1 z2 : ℤ_[p]) : ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ :=
by unfold norm; simp [padic_norm_z]
@[simp] lemma pow (z : ℤ_[p]) : ∀ n : ℕ, ∥z^n∥ = ∥z∥^n
| 0 := by simp
| (k+1) := show ∥z*z^k∥ = ∥z∥*∥z∥^k, by {rw mul, congr, apply pow}
theorem nonarchimedean : ∀ (q r : ℤ_[p]), ∥q + r∥ ≤ max (∥q∥) (∥r∥)
| ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.nonarchimedean _ _
theorem add_eq_max_of_ne : ∀ {q r : ℤ_[p]}, ∥q∥ ≠ ∥r∥ → ∥q+r∥ = max (∥q∥) (∥r∥)
| ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.add_eq_max_of_ne
@[simp] lemma norm_one : ∥(1 : ℤ_[p])∥ = 1 := normed_field.norm_one
lemma eq_of_norm_add_lt_right {z1 z2 : ℤ_[p]}
(h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ :=
by_contradiction $ λ hne,
not_lt_of_ge (by rw padic_norm_z.add_eq_max_of_ne hne; apply le_max_right) h
lemma eq_of_norm_add_lt_left {z1 z2 : ℤ_[p]}
(h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ :=
by_contradiction $ λ hne,
not_lt_of_ge (by rw padic_norm_z.add_eq_max_of_ne hne; apply le_max_left) h
@[simp] lemma padic_norm_e_of_padic_int (z : ℤ_[p]) : ∥(↑z : ℚ_[p])∥ = ∥z∥ :=
by simp [norm, padic_norm_z]
@[simp] lemma padic_norm_z_eq_padic_norm_e {q : ℚ_[p]} (hq : ∥q∥ ≤ 1) :
@norm ℤ_[p] _ ⟨q, hq⟩ = ∥q∥ := rfl
end padic_norm_z
private lemma mul_lt_one {α} [decidable_linear_ordered_comm_ring α] {a b : α} (hbz : 0 < b)
(ha : a < 1) (hb : b < 1) : a * b < 1 :=
suffices a*b < 1*1, by simpa,
mul_lt_mul ha (le_of_lt hb) hbz zero_le_one
private lemma mul_lt_one_of_le_of_lt {α} [decidable_linear_ordered_comm_ring α] {a b : α} (ha : a ≤ 1)
(hbz : 0 ≤ b) (hb : b < 1) : a * b < 1 :=
if hb' : b = 0 then by simpa [hb'] using zero_lt_one
else if ha' : a = 1 then by simpa [ha']
else mul_lt_one (lt_of_le_of_ne hbz (ne.symm hb')) (lt_of_le_of_ne ha ha') hb
namespace padic_int
variables {p : ℕ} [nat.prime p]
local attribute [reducible] padic_int
lemma mul_inv : ∀ {z : ℤ_[p]}, ∥z∥ = 1 → z * z.inv = 1
| ⟨k, _⟩ h :=
begin
have hk : k ≠ 0, from λ h', @zero_ne_one ℚ_[p] _ (by simpa [h'] using h),
unfold padic_int.inv, split_ifs,
{ change (⟨k * (1/k), _⟩ : ℤ_[p]) = 1,
simp [hk], refl },
{ apply subtype.ext.2, simp [mul_inv_cancel hk] }
end
lemma inv_mul {z : ℤ_[p]} (hz : ∥z∥ = 1) : z.inv * z = 1 :=
by rw [mul_comm, mul_inv hz]
lemma is_unit_iff {z : ℤ_[p]} : is_unit z ↔ ∥z∥ = 1 :=
⟨λ h, begin
rcases is_unit_iff_dvd_one.1 h with ⟨w, eq⟩,
refine le_antisymm (padic_norm_z.le_one _) _,
have := mul_le_mul_of_nonneg_left (padic_norm_z.le_one w) (norm_nonneg z),
rwa [mul_one, ← padic_norm_z.mul, ← eq, padic_norm_z.one] at this
end, λ h, ⟨⟨z, z.inv, mul_inv h, inv_mul h⟩, rfl⟩⟩
lemma norm_lt_one_add {z1 z2 : ℤ_[p]} (hz1 : ∥z1∥ < 1) (hz2 : ∥z2∥ < 1) : ∥z1 + z2∥ < 1 :=
lt_of_le_of_lt (padic_norm_z.nonarchimedean _ _) (max_lt hz1 hz2)
lemma norm_lt_one_mul {z1 z2 : ℤ_[p]} (hz2 : ∥z2∥ < 1) : ∥z1 * z2∥ < 1 :=
calc ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ : by simp
... < 1 : mul_lt_one_of_le_of_lt (padic_norm_z.le_one _) (norm_nonneg _) hz2
@[simp] lemma mem_nonunits {z : ℤ_[p]} : z ∈ nonunits ℤ_[p] ↔ ∥z∥ < 1 :=
by rw lt_iff_le_and_ne; simp [padic_norm_z.le_one z, nonunits, is_unit_iff]
instance : local_ring ℤ_[p] :=
local_of_nonunits_ideal zero_ne_one $ λ x y, by simp; exact norm_lt_one_add
private def cau_seq_to_rat_cau_seq (f : cau_seq ℤ_[p] norm) :
cau_seq ℚ_[p] (λ a, ∥a∥) :=
⟨ λ n, f n,
λ _ hε, by simpa [norm, padic_norm_z] using f.cauchy hε ⟩
instance complete : cau_seq.is_complete ℤ_[p] norm :=
⟨ λ f,
have hqn : ∥cau_seq.lim (cau_seq_to_rat_cau_seq f)∥ ≤ 1,
from padic_norm_e_lim_le zero_lt_one (λ _, padic_norm_z.le_one _),
⟨ ⟨_, hqn⟩,
λ ε, by simpa [norm, padic_norm_z] using cau_seq.equiv_lim (cau_seq_to_rat_cau_seq f) ε⟩⟩
instance is_ring_hom_coe : is_ring_hom (coe : ℤ_[p] → ℚ_[p]) :=
{ map_one := rfl,
map_mul := coe_mul,
map_add := coe_add }
instance : algebra ℤ_[p] ℚ_[p] :=
@algebra.of_ring_hom ℤ_[p] _ _ _ (coe) padic_int.is_ring_hom_coe
end padic_int
namespace padic_norm_z
variables {p : ℕ} [nat.prime p]
lemma padic_val_of_cong_pow_p {z1 z2 : ℤ} {n : ℕ} (hz : z1 ≡ z2 [ZMOD ↑(p^n)]) :
∥(z1 - z2 : ℚ_[p])∥ ≤ ↑(↑p ^ (-n : ℤ) : ℚ) :=
have hdvd : ↑(p^n) ∣ z2 - z1, from int.modeq.modeq_iff_dvd.1 hz,
have (z2 - z1 : ℚ_[p]) = ↑(↑(z2 - z1) : ℚ), by norm_cast,
begin
rw [norm_sub_rev, this, padic_norm_e.eq_padic_norm],
exact_mod_cast padic_norm.le_of_dvd p hdvd
end
end padic_norm_z
|
3adc2cd0ff4e6c16aa321604d3bfcccb9e37c5a3
|
56e5b79a7ab4f2c52e6eb94f76d8100a25273cf3
|
/src/tactic_state.lean
|
5944f89f209e6e8fa43dbb9dceb71b7eb71be886
|
[
"Apache-2.0"
] |
permissive
|
DyeKuu/lean-tpe-public
|
3a9968f286ca182723ef7e7d97e155d8cb6b1e70
|
750ade767ab28037e80b7a80360d213a875038f8
|
refs/heads/master
| 1,682,842,633,115
| 1,621,330,793,000
| 1,621,330,793,000
| 368,475,816
| 0
| 0
|
Apache-2.0
| 1,621,330,745,000
| 1,621,330,744,000
| null |
UTF-8
|
Lean
| false
| false
| 25,683
|
lean
|
import system.io
import utils
open tactic.unsafe
universes u v w
-- tools and help functions
-- def option.mmap {m : Type u → Type v} [monad m] {α : Type w} {β : Type u} (f : α → m β) : option α → m (option β)
-- | none := return none
-- | (some x) := do x' ← f x, return (some x')
def list.last_option {α : Type u}: list α → option α
| [] := none
| [a] := some a
| (a::b::l) := list.last_option (b::l)
meta def expr.local_uniq_name_option : expr → option name
| (expr.local_const n m bi t) := some n
| e := none
meta def expr.mvar_uniq_name_option : expr → option name
| (expr.mvar n ppn t) := some n
| e := none
-- set the tactic state
meta def set_state (new_state: tactic_state): tactic unit :=
-- this is in mathlib but easier to recreate
λ _, interaction_monad.result.success () new_state
-- types for encoding tactic state information
meta structure mvar_decl :=
(unique_name : name)
(pp_name : name)
(expr_type : expr)
(local_cxt : list expr)
(type : option expr)
(assignment : option expr)
/- There already is a local_decl type, but
this is some more informtion for understanding
the type better.-/
meta structure local_decl2 :=
(unique_name : name)
(pp_name : name)
(expr_type : expr)
(bi : binder_info)
(type : option expr)
(prev : option name)
(frozen : bool)
(ld : option local_decl)
meta structure univ_mvar_decl :=
(unique_name : name)
(assignment : option level)
meta inductive context.decl
| mvar_decl (mv : mvar_decl) : context.decl
| univ_mvar_decl (mv : univ_mvar_decl) : context.decl
| local_decl (loc : local_decl2) : context.decl
meta structure context :=
-- in order of dependecies
(decls : list context.decl)
(names : name_set)
meta structure tactic_state_data :=
(decls : list context.decl)
(goals : list (name × tactic.tag))
-- meta instance : has_to_format tactic.tag := sorry
-- meta instance : has_to_format context.decl := sorry
-- -- meta instance : has_to_tactic_format context.decl := sorry
-- meta instance foo' : has_to_format $ list (name × tactic.tag) := by apply_instance
-- meta instance foo : has_to_format (list decl) := by apply_instance
-- meta instance : has_to_tactic_format tactic_state_data :=
-- ⟨λ ⟨decls, goals⟩, pure $ format!"tactic_state_data.mk \n\t decls := {decls} \n\t goals := {goals}"⟩
attribute [derive [has_to_format]] mvar_decl univ_mvar_decl binder_info
attribute [derive [has_to_format]] local_decl
attribute [derive [has_to_format]] local_decl2
attribute [derive [has_to_format]] context.decl
meta instance : has_to_format tactic.tag := (by apply_instance : has_to_format (list name))
attribute [derive [has_to_format]] tactic_state_data
section instances
attribute [derive [has_to_tactic_json]] mvar_decl
attribute [derive [has_to_tactic_json]] univ_mvar_decl
attribute [derive [has_to_tactic_json]] local_decl
attribute [derive [has_to_tactic_json]] local_decl
attribute [derive [has_to_tactic_json]] local_decl2
attribute [derive has_to_tactic_json] context.decl
meta instance : has_to_tactic_json tactic.tag :=
⟨by mk_to_tactic_json name.anonymous⟩
meta instance : has_from_json tactic.tag :=
has_from_json_list
attribute [derive has_to_tactic_json] tactic_state_data
meta instance : has_from_json mvar_decl :=
⟨λ msg, match msg with
| (json.array $ [c, json.array [un, pp, ety, cxt, ty, assn]]) := do
(c_nm : name) ← has_from_json_name_aux c,
if c_nm = `mvar_decl.mk then do
mvar_decl.mk <$> (has_from_json.from_json un) <*> (has_from_json.from_json pp)
<*> has_from_json.from_json ety <*> has_from_json.from_json cxt
<*> has_from_json.from_json ty <*> has_from_json.from_json assn
else
tactic.fail format!"[has_from_json_mvar_decl] unexpected: {msg}"
| exc := tactic.fail format!"[has_from_json_mvar_decl] unexpected: {exc}"
end
⟩
meta instance : has_from_json univ_mvar_decl :=
⟨λ msg, match msg with
| (json.array $ [c, json.array [un, pp]]) := do
(c_nm : name) ← has_from_json_name_aux c,
if c_nm = `univ_mvar_decl.mk then do
univ_mvar_decl.mk <$> (has_from_json.from_json un) <*> (has_from_json.from_json pp)
else
tactic.fail format!"[has_from_json_univ_mvar_decl] unexpected: {msg}"
| exc := tactic.fail format!"[has_from_json_univ_mvar_decl] unexpected: {exc}"
end
⟩
-- meta instance : has_from_json univ_mvar_decl := sorry
-- attribute [derive [has_to_tactic_json]] bool
run_cmd (has_to_tactic_json.to_tactic_json tt >>= (has_from_json.from_json : json → tactic bool))
meta instance : has_from_json local_decl :=
⟨λ msg, match msg with
| (json.array $ [c, json.array [un, pp, ty, val, bi, idx]]) := do
(c_nm : name) ← has_from_json_name_aux c,
if c_nm = `local_decl.mk then do
local_decl.mk <$>
(has_from_json.from_json un) <*>
(has_from_json.from_json pp) <*>
has_from_json.from_json ty <*>
has_from_json.from_json val <*>
has_from_json.from_json bi <*>
has_from_json.from_json idx
else
tactic.fail format!"[has_from_json_local_decl] unexpected: {msg}"
| exc := tactic.fail format!"[has_from_json_local_decl] unexpected: {exc}"
end
⟩
meta instance : has_from_json local_decl2 :=
⟨λ msg, match msg with
| (json.array $ [c, json.array [un, pp, ety, bi, ty, prev, frozen, ld]]) := do
(c_nm : name) ← has_from_json_name_aux c,
if c_nm = `local_decl2.mk then do
local_decl2.mk <$>
(has_from_json.from_json un) <*>
(has_from_json.from_json pp) <*>
has_from_json.from_json ety <*>
has_from_json.from_json bi <*>
has_from_json.from_json ty <*>
has_from_json.from_json prev <*>
has_from_json.from_json frozen <*>
has_from_json.from_json ld
else
tactic.fail format!"[has_from_json_local_decl2] unexpected: {msg}"
| exc := tactic.fail format!"[has_from_json_local_decl2] unexpected: {exc}"
end
⟩
meta instance : has_from_json context.decl :=
let ⟨fn₁⟩ := (by apply_instance : has_from_json mvar_decl) in
let ⟨fn₂⟩ := (by apply_instance : has_from_json univ_mvar_decl) in
let ⟨fn₃⟩ := (by apply_instance : has_from_json local_decl2) in
⟨λ msg, match msg with
| (json.array $ [c, json.array args]) := do
(c_nm : name) ← has_from_json_name_aux c,
tactic.trace format!"[has_from_json_context.decl] c_nm: {c_nm}",
if c_nm = `context.decl.mvar_decl then context.decl.mvar_decl <$> fn₁ args.head else
if c_nm = `context.decl.univ_mvar_decl then context.decl.univ_mvar_decl <$> fn₂ args.head else
if c_nm = `context.decl.local_decl then context.decl.local_decl <$> fn₃ args.head else
tactic.fail format!"[has_from_json_context.decl] unexpected: {msg}"
| exc := tactic.fail format!"[has_from_json_context.decl] unexpected: {exc}"
end
⟩
meta instance : has_from_json (list context.decl) := has_from_json_list
meta instance has_from_json_list_name_tactic_tag : has_from_json (list (name × tactic.tag)) := has_from_json_list
meta instance : has_from_json tactic_state_data :=
let ⟨fn₁⟩ := (by apply_instance : has_from_json (list context.decl)) in
let ⟨fn₂⟩ := (by apply_instance : has_from_json (list (name × tactic.tag))) in
⟨λ msg, match msg with
| (json.array $ [c, json.array [decls_msg, goals_msg]]) := do
(c_nm : name) ← has_from_json_name_aux c,
tactic.trace format!"[has_from_json_tactic_state_data] c_nm: {c_nm}",
if c_nm = `tactic_state_data.mk then tactic_state_data.mk <$> fn₁ decls_msg <*> fn₂ goals_msg else
tactic.fail format!"[has_from_json_tactic_state_data] unexpected: {msg}"
| exc := tactic.fail format!"[has_from_json_tactic_state_data] unexpected: {exc}"
end
⟩
end instances
-- convience functions and instances
meta instance mvar_decl_has_to_string : has_to_format mvar_decl :=
⟨ λ d, format! "{{mvar_decl .\nunique_name := {d.unique_name},\npp_name := {d.pp_name},\nexpr_type := {d.expr_type},\nlocal_cxt := {d.local_cxt},\ntype := {d.type},\nassignment := {d.assignment},\n}" ⟩
meta instance univ_mvar_decl_has_to_string : has_to_format univ_mvar_decl :=
⟨ λ d, format! "{{univ_mvar_decl .\nunique_name := {d.unique_name},\nassignment := {d.assignment},\n}" ⟩
meta instance local_decl_has_to_string : has_to_format local_decl :=
⟨ λ d, format! "{{local_decl .\nunique_name := {d.unique_name},\npp_name := {d.pp_name},\ntype := {d.type},\nvalue := {d.value},\nbi := {repr d.bi},\nidx := {d.idx},\n}" ⟩
meta instance local_decl2_has_to_string : has_to_format local_decl2 :=
⟨ λ d, format! "{{local_decl2 .\nunique_name := {d.unique_name},\npp_name := {d.pp_name},\nexpr_type := {d.expr_type},\nbi := {repr d.bi},\ntype := {d.type},\nprev := {d.prev}\n},\nfrozen := {d.frozen},\nld := {d.ld}" ⟩
meta def context.decl.unique_name : context.decl -> name
| (context.decl.mvar_decl d) := d.unique_name
| (context.decl.univ_mvar_decl d) := d.unique_name
| (context.decl.local_decl d) := d.unique_name
meta instance context_decl_has_to_string : has_to_format context.decl :=
⟨ λ d, match d with
| context.decl.mvar_decl d := format! "{d}"
| context.decl.univ_mvar_decl d := format! "{d}"
| context.decl.local_decl d := format! "{d}"
end ⟩
meta instance context_has_to_string : has_to_format context :=
⟨ λ cxt, format! "{cxt.decls}" ⟩
-- constructors
meta def context.empty : context :=
{ decls := [], names := mk_name_set }
meta def context.mk1 (d : context.decl) : context :=
{ decls := [d], names := name_set.of_list [d.unique_name]}
meta def context.append (cxt1 : context) (cxt2 : context) : context :=
{ decls := cxt1.decls ++ (cxt2.decls.filter (λ d, ¬ (cxt1.names.contains d.unique_name))),
names := cxt1.names.fold cxt2.names $ λ n ns, ns.insert n
}
meta instance context.has_append : has_append context := ⟨ context.append ⟩
/- Get univ metavariables level expression tree.-/
meta def context.process_level : level -> tactic context
| level.zero := return context.empty
| (level.succ lvl) := context.process_level lvl
| (level.max lvl1 lvl2) := do
cxt1 <- context.process_level lvl1,
cxt2 <- context.process_level lvl2,
return (cxt1 ++ cxt2)
| (level.imax lvl1 lvl2) := do
cxt1 <- context.process_level lvl1,
cxt2 <- context.process_level lvl2,
return (cxt1 ++ cxt2)
| (level.param _) := return context.empty
| lvl@(level.mvar nm) := do
ass <- optional (tactic.get_univ_assignment lvl),
let univ_decl := context.decl.univ_mvar_decl {
unique_name := nm,
assignment := ass
},
return (context.mk1 univ_decl)
def find_prev {α : Type} [decidable_eq α] (a : α) : list α -> option α
| [] := none
| [b] := none
| (b :: c :: ls) := if c = a then some b else find_prev (c :: ls)
/- Get metavariables and local constants inside an expression tree, follow recursively. -/
meta def context.process_expr : expr -> local_context -> tactic context
| (expr.var _) _ := return context.empty
| (expr.sort lvl) _ := context.process_level lvl
| (expr.const _ lvls) _ := do
cxts <- lvls.mmap context.process_level,
let cxt := cxts.foldl context.append context.empty,
return cxt
| mv@(expr.mvar unique_nm pp_nm tp) _ := do
lcxt <- type_context.run $ type_context.get_context mv,
let local_cxt := lcxt.to_list,
cxts <- local_cxt.mmap (λ e, e.unfold_macros >>= flip context.process_expr lcxt),
let cxt := cxts.foldl context.append context.empty,
tp_cxt <- tp.unfold_macros >>= flip context.process_expr lcxt,
mv_type <- optional (tactic.infer_type mv),
tp_cxt2 <- match mv_type with
| (some e) := e.unfold_macros >>= flip context.process_expr lcxt
| none := return context.empty
end,
assignment <- optional (tactic.get_assignment mv),
ass_cxt <- match assignment with
| (some e) := e.unfold_macros >>= flip context.process_expr lcxt
| none := return context.empty
end,
let mv_dec := context.decl.mvar_decl {
unique_name := unique_nm,
pp_name := pp_nm,
expr_type := tp,
local_cxt := local_cxt,
type := mv_type,
assignment := assignment
},
return $ cxt ++ tp_cxt ++ tp_cxt2 ++ ass_cxt ++ (context.mk1 mv_dec)
| lconst@(expr.local_const unique_nm pp_nm bi tp) lcxt := do
tp_cxt <- tp.unfold_macros >>= flip context.process_expr lcxt,
loc_type <- optional (tactic.infer_type lconst),
tp_cxt2 <- match loc_type with
| (some e) := e.unfold_macros >>= flip context.process_expr lcxt
| none := return context.empty
end,
let ld := lcxt.get_local_decl unique_nm,
tp_cxt3 <- match ld with
| (some ld) := ld.type.unfold_macros >>= flip context.process_expr lcxt
| none := return context.empty
end,
value_cxt <- match ld with
| (some ld) := match ld.value with
| (some e) := e.unfold_macros >>= flip context.process_expr lcxt
| none := return context.empty
end
| none := return context.empty
end,
let (prev : option expr) := find_prev lconst lcxt.to_list,
let prev_id := match prev with
| some (expr.local_const id _ _ _) := some id
| _ := none
end,
frozen_instances_opt <- tactic.frozen_local_instances,
let frozen := match frozen_instances_opt with
| none := ff
| some frozen_instances := frozen_instances.any (λ e, e.local_uniq_name_option = some unique_nm)
end,
let loc_dec := context.decl.local_decl {
unique_name := unique_nm,
pp_name := pp_nm,
expr_type := tp,
bi := bi,
type := loc_type,
prev := prev_id,
frozen := frozen,
ld := lcxt.get_local_decl unique_nm,
},
return $ tp_cxt ++ tp_cxt2 ++ tp_cxt3 ++ value_cxt ++ (context.mk1 loc_dec)
| (expr.app expr1 expr2) lcxt := do
cxt1 <- expr1.unfold_macros >>= flip context.process_expr lcxt,
cxt2 <- expr2.unfold_macros >>= flip context.process_expr lcxt,
return (cxt1 ++ cxt2)
| (expr.lam _ _ expr1 expr2) lcxt := do
cxt1 <- expr1.unfold_macros >>= flip context.process_expr lcxt,
cxt2 <- expr2.unfold_macros >>= flip context.process_expr lcxt,
return (cxt1 ++ cxt2)
| (expr.pi _ _ expr1 expr2) lcxt := do
cxt1 <- expr1.unfold_macros >>= flip context.process_expr lcxt,
cxt2 <- expr2.unfold_macros >>= flip context.process_expr lcxt,
return (cxt1 ++ cxt2)
| (expr.elet _ expr1 expr2 expr3) lcxt := do
cxt1 <- expr1.unfold_macros >>= flip context.process_expr lcxt,
cxt2 <- expr2.unfold_macros >>= flip context.process_expr lcxt,
cxt3 <- expr3.unfold_macros >>= flip context.process_expr lcxt,
return (cxt1 ++ cxt2 ++ cxt3)
| (expr.macro md deps) _ := tactic.fail format!"[process_expr] can't handle macro {expr.macro_def_name md}"
meta def context.get : tactic context := do
lcxt <- type_context.run $ type_context.get_local_context,
mvs <- tactic.get_goals,
cxts <- mvs.mmap (λ e, e.unfold_macros >>= flip context.process_expr lcxt),
let cxt := cxts.foldl context.append context.empty,
return cxt
meta def tactic_state_data.get : tactic tactic_state_data := do
cxt <- context.get,
gs <- tactic.get_goals,
goals <- gs.mmap $ λ g, do {
nm <- g.mvar_uniq_name_option,
tag <- tactic.get_tag g,
return (nm, tag)
},
return {
decls := cxt.decls,
goals := goals
}
-- tracing code for debugging
meta def trace_context : tactic unit := do
-- cxt <- context.get,
cxt ← tactic_state_data.get,
has_to_tactic_json.to_tactic_json cxt >>= tactic.trace
-- rebuilding the context
meta def swap_univ_mvs (nm_map : name_map context.decl) : level → tactic level
| (level.mvar nm) := do {
d <- nm_map.find nm,
nm' <- match d with
| (context.decl.univ_mvar_decl dd) := return dd.unique_name
| _ := tactic.failed
end,
return $ level.mvar nm'
}
| (level.max lvl1 lvl2) := do {
lvl1' <- swap_univ_mvs lvl1,
lvl2' <- swap_univ_mvs lvl2,
return $ level.max lvl1' lvl2'
}
| (level.imax lvl1 lvl2) := do {
lvl1' <- swap_univ_mvs lvl1,
lvl2' <- swap_univ_mvs lvl2,
return $ level.imax lvl1' lvl2'
}
| (level.succ lvl) := do {
lvl' <- swap_univ_mvs lvl,
return $ level.succ lvl'
}
| lvl := return lvl --level.zero and level.param
meta def swap_mvs (nm_map : name_map context.decl) : expr -> tactic expr
| (expr.mvar unique_nm pp_nm tp) := do {
d <- nm_map.find unique_nm,
(unique_nm', tp') <- match d with
| (context.decl.mvar_decl dd) := return (dd.unique_name, dd.expr_type)
| _ := tactic.failed
end,
return $ expr.mvar unique_nm pp_nm tp'
}
| (expr.local_const unique_nm pp_nm bi tp) := do {
d <- nm_map.find unique_nm,
(unique_nm', tp') <- match d with
| (context.decl.local_decl dd) := return (dd.unique_name, dd.expr_type)
| _ := tactic.failed
end,
return $ expr.local_const unique_nm' pp_nm bi tp'
}
| e@(expr.var _) := return e
| (expr.sort lvl) := do {
lvl' <- swap_univ_mvs nm_map lvl,
return $ expr.sort lvl'
}
| (expr.const nm lvls) := do {
lvls' <- lvls.mmap (swap_univ_mvs nm_map),
return $ expr.const nm lvls'
}
| (expr.app expr1 expr2) := do {
expr1' <- swap_mvs expr1.unfold_string_macros.erase_annotations,
expr2' <- swap_mvs expr2.unfold_string_macros.erase_annotations,
return $ expr.app expr1' expr2'
}
| (expr.lam nm bi expr1 expr2) := do {
expr1' <- swap_mvs expr1.unfold_string_macros.erase_annotations,
expr2' <- swap_mvs expr2.unfold_string_macros.erase_annotations,
return $ expr.lam nm bi expr1' expr2'
}
| (expr.pi nm bi expr1 expr2) := do {
expr1' <- swap_mvs expr1.unfold_string_macros.erase_annotations,
expr2' <- swap_mvs expr2.unfold_string_macros.erase_annotations,
return $ expr.pi nm bi expr1' expr2'
}
| (expr.elet nm expr1 expr2 expr3) := do {
expr1' <- swap_mvs expr1.unfold_string_macros.erase_annotations,
expr2' <- swap_mvs expr2.unfold_string_macros.erase_annotations,
expr3' <- swap_mvs expr3.unfold_string_macros.erase_annotations,
return $ expr.elet nm expr1' expr2' expr3'
}
| (expr.macro _ _) := tactic.fail "[swap_mvs] can't handle macros yet"
/- A better constructor for locals which covers
frozen status and assignments. -/
meta def local_context.mk_local2 (pretty_name : name) (type : expr) (bi : binder_info) (frozen : bool) (assignment : option expr) (lcxt : local_context) : tactic (expr × local_context) := do
-- capture state
s <- tactic.read,
-- there are a few ways to add to local context,
-- the most direct being local_context.mk_local
-- however that doesn't handle assignments or frozen locals,
-- so we are setting the local context as the context of a goal
-- and using intro to push a new hypothesis onto the stack
target <- match (assignment, bi) with
| (none, bi) :=
pure $ expr.pi pretty_name bi type `(true)
| (some ass, binder_info.default) :=
pure $ expr.elet pretty_name type ass `(true)
| _ := tactic.fail "Unreachable state reached"
end,
goal_mv <- type_context.run $ type_context.mk_mvar "tmp_goal" target lcxt,
tactic.set_goals [goal_mv],
new_local <- tactic.intro_core pretty_name,
if frozen then
tactic.freeze_local_instances
else
pure (),
new_lcxt <- type_context.run $ type_context.get_local_context,
-- reset the state back to the beginning
_root_.set_state s,
return (new_local, new_lcxt)
meta def build_context_aux (nm_map : name_map context.decl) (loc_map : name_map local_context): context.decl -> tactic ((name_map context.decl) × (name_map local_context) × context.decl)
| (context.decl.univ_mvar_decl d) := do
-- update dependencies
new_assignment <- d.assignment.mmap (swap_univ_mvs nm_map),
-- create mvar
new_univ_mvar <- tactic.mk_meta_univ,
new_uid <- match new_univ_mvar with
| level.mvar nm := return nm
| _ := tactic.failed
end,
-- assign mvar
match new_assignment with
| some lvl := type_context.run $ type_context.level.assign new_univ_mvar lvl
| none := return ()
end,
-- return new decl
let new_decl := context.decl.univ_mvar_decl {
unique_name := new_uid,
assignment := new_assignment
},
let new_nmap := nm_map.insert d.unique_name new_decl,
return (new_nmap, loc_map, new_decl)
| (context.decl.local_decl d) := do
-- update dependencies
let pp_name := d.pp_name,
new_type <- swap_mvs nm_map (d.type.get_or_else d.expr_type).unfold_string_macros.erase_annotations,
let (new_lcxt_option : option local_context) := do {
unique_name <- d.prev,
loc_map.find unique_name
},
let new_lcxt := new_lcxt_option.get_or_else local_context.empty,
ld <- d.ld,
new_assignment <- ld.value.mmap ((swap_mvs nm_map) ∘ expr.unfold_string_macros ∘ expr.erase_annotations),
-- create local
(new_loc, new_lcxt) <- new_lcxt.mk_local2 pp_name new_type d.bi d.frozen new_assignment,
(new_uid, new_tp) <- match new_loc with
| expr.local_const nm _ bi tp := return (nm, tp)
| _ := tactic.failed
end,
let (new_prev : option expr) := new_lcxt.fold (λ prev e, if e = new_loc then prev else some e) none,
let new_prev_id := match new_prev with
| some (expr.local_const id _ _ _) := some id
| _ := none
end,
let new_decl := context.decl.local_decl {
unique_name := new_uid,
pp_name := pp_name,
expr_type := new_tp,
bi := d.bi,
prev := new_prev_id,
type := new_type,
frozen := d.frozen,
ld := new_lcxt.get_local_decl new_uid
},
let new_nmap := nm_map.insert d.unique_name new_decl,
let new_loc_map := loc_map.insert d.unique_name new_lcxt,
return (new_nmap, new_loc_map, new_decl)
| (context.decl.mvar_decl d) := do
-- update dependencies
let pp_name := d.pp_name,
new_type <- swap_mvs nm_map (d.type.get_or_else d.expr_type).unfold_string_macros.erase_annotations,
let (new_lcxt_option : option local_context) := do {
last <- d.local_cxt.last_option,
unique_name <- last.local_uniq_name_option,
loc_map.find unique_name
},
let new_lcxt := new_lcxt_option.get_or_else local_context.empty,
new_assignment <- d.assignment.mmap ((swap_mvs nm_map) ∘ expr.unfold_string_macros ∘ expr.erase_annotations),
-- create mvar
new_mvar <- type_context.run $ type_context.mk_mvar pp_name new_type new_lcxt,
(new_uid, new_tp) <- match new_mvar with
| expr.mvar nm _ tp := return (nm, tp)
| _ := tactic.failed
end,
-- assign mvar
match new_assignment with
| some e := type_context.run $ type_context.assign new_mvar e
| none := return ()
end,
let new_decl := context.decl.mvar_decl {
unique_name := new_uid,
pp_name := pp_name,
expr_type := new_tp,
local_cxt := new_lcxt.to_list,
type := new_type,
assignment := new_assignment
},
let new_nmap := nm_map.insert d.unique_name new_decl,
return (new_nmap, loc_map, new_decl)
meta def rebuild_context : (list context.decl) -> tactic ((name_map context.decl) × (name_map local_context))
| [] := return (mk_name_map, mk_name_map)
| (d :: ds) := do
(nm_map, loc_map) <- rebuild_context ds,
(nm_map, loc_map, _) <- build_context_aux nm_map loc_map d,
return (nm_map, loc_map)
meta def mvar_id : expr -> tactic name
| (expr.mvar uid _ _) := return uid
| _ := tactic.fail "Expecting mvar"
meta def rebuild_tactic_state (ts : tactic_state_data) : tactic unit := do
(nm_map, _) <- rebuild_context ts.decls.reverse,
goals_and_tags <- ts.goals.mmap $ λ ⟨nm, tag⟩, do {
d <- nm_map.find nm,
nm' <- match d with
| context.decl.mvar_decl dd := return dd.unique_name
| _ := tactic.fail "Expecting mvar_decl"
end,
mvars <- type_context.run type_context.list_mvars,
mv <- mvars.mfirst $ λ e, do {
nm2 <- mvar_id e,
if nm' = nm2 then return e else failure
},
return (mv, tag)
},
let goals := goals_and_tags.map prod.fst,
tactic.set_goals goals,
goals_and_tags.mmap $ λ ⟨g, tag⟩, do {
tactic.enable_tags tt,
tactic.set_tag g tag,
tactic.enable_tags ff -- seems to be off by default
},
return ()
-- for testing
meta def refresh_context : tactic unit := do
cxt <- context.get,
(nm_map, _) <- rebuild_context cxt.decls.reverse,
gs <- tactic.get_goals,
new_goals <- gs.mmap $ λ g, do {
nm <- mvar_id g,
d <- nm_map.find nm,
tactic.trace (nm, d),
nm' <- match d with
| context.decl.mvar_decl dd := return dd.unique_name
| _ := tactic.fail "Expecting mvar_decl"
end,
mvars <- type_context.run type_context.list_mvars,
mv <- mvars.mfirst $ λ e, do {
nm2 <- mvar_id e,
if nm' = nm2 then return e else failure
},
return mv
},
tactic.set_goals new_goals
meta def refresh_tactic_state : tactic unit := do
ts_data <- tactic_state_data.get,
-- go into a clean tactic environment and build the tactic state
ts <- tactic.unsafe_run_io $ io.run_tactic' $ do {
rebuild_tactic_state ts_data,
tactic.read -- return tactic state
},
-- set tactic state to new one
_root_.set_state ts
-- examples
section examples
-- example (α : Type) (a : nat): a=a := begin
-- trace_context,
-- refresh_tactic_state,
-- trace_context,
-- induction a,
-- trace_context,
-- refresh_tactic_state, -- check that tags are still there
-- trace_context,
-- refl,
-- refl,
-- done,
-- trace_context,
-- end
-- -- Debug
-- example {α β γ : Type} --(f : α → β) (g : β → γ)
-- : α :=
-- begin
-- trace_context,
-- refresh_tactic_state,
-- trace_context,
-- end
-- -- Frozen local instances
-- def fish {α β γ} {m : Type → Type} [monad m] (f : m α → m β) (g : m β → m γ)
-- : m α → m γ :=
-- begin
-- trace_context,
-- refresh_tactic_state,
-- trace_context,
-- revert m, -- fails, `monad m` is a frozen instance
-- revert f, -- succeeds
-- revert α -- succeeds
-- end
-- example : let x := 0 in x=0 := begin
-- intro,
-- trace_context,
-- refresh_tactic_state,
-- trace_context,
-- simp,
-- done,
-- end
end examples
|
a2472ab1839051cb6bd6c11f3033e9274e53bfd9
|
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
|
/tests/lean/run/lcnfCheckIssue.lean
|
d963d7096ecbee716866471f1b8f87a9762078f5
|
[
"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
| 364
|
lean
|
import Lean
abbrev Sequence (α : Type) := List α
def bigop (init : β) (seq : Sequence α) (op : β → β → β) (f : α → Bool × β) : β := Id.run do
let mut result := init
for a in seq do
let (ok, b) := f a
if ok then
result := op result b
return result
set_option trace.Compiler.result true
#eval Lean.Compiler.compile #[``bigop]
|
337c9803add54c354b539b3ed0eea0b5b3ab2c23
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/src/group_theory/commutator.lean
|
5c21d23e5f311a3a421452a623825c0d623af94f
|
[
"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,766
|
lean
|
/-
Copyright (c) 2021 Jordan Brown, Thomas Browning, Patrick Lutz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jordan Brown, Thomas Browning, Patrick Lutz
-/
import data.bracket
import group_theory.subgroup.finite
import tactic.group
/-!
# Commutators of Subgroups
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
If `G` is a group and `H₁ H₂ : subgroup G` then the commutator `⁅H₁, H₂⁆ : subgroup G`
is the subgroup of `G` generated by the commutators `h₁ * h₂ * h₁⁻¹ * h₂⁻¹`.
## Main definitions
* `⁅g₁, g₂⁆` : the commutator of the elements `g₁` and `g₂`
(defined by `commutator_element` elsewhere).
* `⁅H₁, H₂⁆` : the commutator of the subgroups `H₁` and `H₂`.
-/
variables {G G' F : Type*} [group G] [group G'] [monoid_hom_class F G G'] (f : F) {g₁ g₂ g₃ g : G}
lemma commutator_element_eq_one_iff_mul_comm : ⁅g₁, g₂⁆ = 1 ↔ g₁ * g₂ = g₂ * g₁ :=
by rw [commutator_element_def, mul_inv_eq_one, mul_inv_eq_iff_eq_mul]
lemma commutator_element_eq_one_iff_commute : ⁅g₁, g₂⁆ = 1 ↔ commute g₁ g₂ :=
commutator_element_eq_one_iff_mul_comm
lemma commute.commutator_eq (h : commute g₁ g₂) : ⁅g₁, g₂⁆ = 1 :=
commutator_element_eq_one_iff_commute.mpr h
variables (g₁ g₂ g₃ g)
@[simp] lemma commutator_element_one_right : ⁅g, (1 : G)⁆ = 1 :=
(commute.one_right g).commutator_eq
@[simp] lemma commutator_element_one_left : ⁅(1 : G), g⁆ = 1 :=
(commute.one_left g).commutator_eq
@[simp] lemma commutator_element_self : ⁅g, g⁆ = 1 :=
(commute.refl g).commutator_eq
@[simp] lemma commutator_element_inv : ⁅g₁, g₂⁆⁻¹ = ⁅g₂, g₁⁆ :=
by simp_rw [commutator_element_def, mul_inv_rev, inv_inv, mul_assoc]
lemma map_commutator_element : (f ⁅g₁, g₂⁆ : G') = ⁅f g₁, f g₂⁆ :=
by simp_rw [commutator_element_def, map_mul f, map_inv f]
lemma conjugate_commutator_element : g₃ * ⁅g₁, g₂⁆ * g₃⁻¹ = ⁅g₃ * g₁ * g₃⁻¹, g₃ * g₂ * g₃⁻¹⁆ :=
map_commutator_element (mul_aut.conj g₃).to_monoid_hom g₁ g₂
namespace subgroup
/-- The commutator of two subgroups `H₁` and `H₂`. -/
instance commutator : has_bracket (subgroup G) (subgroup G) :=
⟨λ H₁ H₂, closure {g | ∃ (g₁ ∈ H₁) (g₂ ∈ H₂), ⁅g₁, g₂⁆ = g}⟩
lemma commutator_def (H₁ H₂ : subgroup G) :
⁅H₁, H₂⁆ = closure {g | ∃ (g₁ ∈ H₁) (g₂ ∈ H₂), ⁅g₁, g₂⁆ = g} := rfl
variables {g₁ g₂ g₃} {H₁ H₂ H₃ K₁ K₂ : subgroup G}
lemma commutator_mem_commutator (h₁ : g₁ ∈ H₁) (h₂ : g₂ ∈ H₂) : ⁅g₁, g₂⁆ ∈ ⁅H₁, H₂⁆ :=
subset_closure ⟨g₁, h₁, g₂, h₂, rfl⟩
lemma commutator_le : ⁅H₁, H₂⁆ ≤ H₃ ↔ ∀ (g₁ ∈ H₁) (g₂ ∈ H₂), ⁅g₁, g₂⁆ ∈ H₃ :=
H₃.closure_le.trans ⟨λ h a b c d, h ⟨a, b, c, d, rfl⟩, λ h g ⟨a, b, c, d, h_eq⟩, h_eq ▸ h a b c d⟩
lemma commutator_mono (h₁ : H₁ ≤ K₁) (h₂ : H₂ ≤ K₂) : ⁅H₁, H₂⁆ ≤ ⁅K₁, K₂⁆ :=
commutator_le.mpr (λ g₁ hg₁ g₂ hg₂, commutator_mem_commutator (h₁ hg₁) (h₂ hg₂))
lemma commutator_eq_bot_iff_le_centralizer : ⁅H₁, H₂⁆ = ⊥ ↔ H₁ ≤ centralizer H₂ :=
begin
rw [eq_bot_iff, commutator_le],
refine forall_congr (λ p, forall_congr (λ hp, forall_congr (λ q, forall_congr (λ hq, _)))),
rw [mem_bot, commutator_element_eq_one_iff_mul_comm, eq_comm],
end
/-- **The Three Subgroups Lemma** (via the Hall-Witt identity) -/
lemma commutator_commutator_eq_bot_of_rotate
(h1 : ⁅⁅H₂, H₃⁆, H₁⁆ = ⊥) (h2 : ⁅⁅H₃, H₁⁆, H₂⁆ = ⊥) : ⁅⁅H₁, H₂⁆, H₃⁆ = ⊥ :=
begin
simp_rw [commutator_eq_bot_iff_le_centralizer, commutator_le,
mem_centralizer_iff_commutator_eq_one, ←commutator_element_def] at h1 h2 ⊢,
intros x hx y hy z hz,
transitivity x * z * ⁅y, ⁅z⁻¹, x⁻¹⁆⁆⁻¹ * z⁻¹ * y * ⁅x⁻¹, ⁅y⁻¹, z⁆⁆⁻¹ * y⁻¹ * x⁻¹,
{ group },
{ rw [h1 _ (H₂.inv_mem hy) _ hz _ (H₁.inv_mem hx), h2 _ (H₃.inv_mem hz) _ (H₁.inv_mem hx) _ hy],
group },
end
variables (H₁ H₂)
lemma commutator_comm_le : ⁅H₁, H₂⁆ ≤ ⁅H₂, H₁⁆ :=
commutator_le.mpr (λ g₁ h₁ g₂ h₂,
commutator_element_inv g₂ g₁ ▸ ⁅H₂, H₁⁆.inv_mem_iff.mpr (commutator_mem_commutator h₂ h₁))
lemma commutator_comm : ⁅H₁, H₂⁆ = ⁅H₂, H₁⁆ :=
le_antisymm (commutator_comm_le H₁ H₂) (commutator_comm_le H₂ H₁)
section normal
instance commutator_normal [h₁ : H₁.normal] [h₂ : H₂.normal] : normal ⁅H₁, H₂⁆ :=
begin
let base : set G := {x | ∃ (g₁ ∈ H₁) (g₂ ∈ H₂), ⁅g₁, g₂⁆ = x},
change (closure base).normal,
suffices h_base : base = group.conjugates_of_set base,
{ rw h_base,
exact subgroup.normal_closure_normal },
refine set.subset.antisymm group.subset_conjugates_of_set (λ a h, _),
simp_rw [group.mem_conjugates_of_set_iff, is_conj_iff] at h,
rcases h with ⟨b, ⟨c, hc, e, he, rfl⟩, d, rfl⟩,
exact ⟨_, h₁.conj_mem c hc d, _, h₂.conj_mem e he d, (conjugate_commutator_element c e d).symm⟩,
end
lemma commutator_def' [H₁.normal] [H₂.normal] :
⁅H₁, H₂⁆ = normal_closure {g | ∃ (g₁ ∈ H₁) (g₂ ∈ H₂), ⁅g₁, g₂⁆ = g} :=
le_antisymm closure_le_normal_closure (normal_closure_le_normal subset_closure)
lemma commutator_le_right [h : H₂.normal] : ⁅H₁, H₂⁆ ≤ H₂ :=
commutator_le.mpr (λ g₁ h₁ g₂ h₂, H₂.mul_mem (h.conj_mem g₂ h₂ g₁) (H₂.inv_mem h₂))
lemma commutator_le_left [H₁.normal] : ⁅H₁, H₂⁆ ≤ H₁ :=
commutator_comm H₂ H₁ ▸ commutator_le_right H₂ H₁
@[simp] lemma commutator_bot_left : ⁅(⊥ : subgroup G), H₁⁆ = ⊥ :=
le_bot_iff.mp (commutator_le_left ⊥ H₁)
@[simp] lemma commutator_bot_right : ⁅H₁, ⊥⁆ = (⊥ : subgroup G) :=
le_bot_iff.mp (commutator_le_right H₁ ⊥)
lemma commutator_le_inf [normal H₁] [normal H₂] : ⁅H₁, H₂⁆ ≤ H₁ ⊓ H₂ :=
le_inf (commutator_le_left H₁ H₂) (commutator_le_right H₁ H₂)
end normal
lemma map_commutator (f : G →* G') : map f ⁅H₁, H₂⁆ = ⁅map f H₁, map f H₂⁆ :=
begin
simp_rw [le_antisymm_iff, map_le_iff_le_comap, commutator_le, mem_comap, map_commutator_element],
split,
{ intros p hp q hq,
exact commutator_mem_commutator (mem_map_of_mem _ hp) (mem_map_of_mem _ hq), },
{ rintros _ ⟨p, hp, rfl⟩ _ ⟨q, hq, rfl⟩,
rw ← map_commutator_element,
exact mem_map_of_mem _ (commutator_mem_commutator hp hq) }
end
variables {H₁ H₂}
lemma commutator_le_map_commutator {f : G →* G'} {K₁ K₂ : subgroup G'}
(h₁ : K₁ ≤ H₁.map f) (h₂ : K₂ ≤ H₂.map f) : ⁅K₁, K₂⁆ ≤ ⁅H₁, H₂⁆.map f :=
(commutator_mono h₁ h₂).trans (ge_of_eq (map_commutator H₁ H₂ f))
variables (H₁ H₂)
instance commutator_characteristic [h₁ : characteristic H₁] [h₂ : characteristic H₂] :
characteristic ⁅H₁, H₂⁆ :=
characteristic_iff_le_map.mpr (λ ϕ, commutator_le_map_commutator
(characteristic_iff_le_map.mp h₁ ϕ) (characteristic_iff_le_map.mp h₂ ϕ))
lemma commutator_prod_prod (K₁ K₂ : subgroup G') :
⁅H₁.prod K₁, H₂.prod K₂⁆ = ⁅H₁, H₂⁆.prod ⁅K₁, K₂⁆ :=
begin
apply le_antisymm,
{ rw commutator_le,
rintros ⟨p₁, p₂⟩ ⟨hp₁, hp₂⟩ ⟨q₁, q₂⟩ ⟨hq₁, hq₂⟩,
exact ⟨commutator_mem_commutator hp₁ hq₁, commutator_mem_commutator hp₂ hq₂⟩ },
{ rw prod_le_iff, split;
{ rw map_commutator,
apply commutator_mono;
simp [le_prod_iff, map_map, monoid_hom.fst_comp_inl, monoid_hom.snd_comp_inl,
monoid_hom.fst_comp_inr, monoid_hom.snd_comp_inr ], }, }
end
/-- The commutator of direct product is contained in the direct product of the commutators.
See `commutator_pi_pi_of_finite` for equality given `fintype η`.
-/
lemma commutator_pi_pi_le {η : Type*} {Gs : η → Type*} [∀ i, group (Gs i)]
(H K : Π i, subgroup (Gs i)) :
⁅subgroup.pi set.univ H, subgroup.pi set.univ K⁆ ≤ subgroup.pi set.univ (λ i, ⁅H i, K i⁆) :=
commutator_le.mpr $ λ p hp q hq i hi, commutator_mem_commutator (hp i hi) (hq i hi)
/-- The commutator of a finite direct product is contained in the direct product of the commutators.
-/
lemma commutator_pi_pi_of_finite {η : Type*} [finite η] {Gs : η → Type*}
[∀ i, group (Gs i)] (H K : Π i, subgroup (Gs i)) :
⁅subgroup.pi set.univ H, subgroup.pi set.univ K⁆ = subgroup.pi set.univ (λ i, ⁅H i, K i⁆) :=
begin
classical,
apply le_antisymm (commutator_pi_pi_le H K),
{ rw pi_le_iff, intros i hi,
rw map_commutator,
apply commutator_mono;
{ rw le_pi_iff,
intros j hj,
rintros _ ⟨_, ⟨x, hx, rfl⟩, rfl⟩,
by_cases h : j = i,
{ subst h, simpa using hx, },
{ simp [h, one_mem] }, }, },
end
end subgroup
variables (G)
/-- The set of commutator elements `⁅g₁, g₂⁆` in `G`. -/
def commutator_set : set G :=
{g | ∃ g₁ g₂ : G, ⁅g₁, g₂⁆ = g}
lemma commutator_set_def : commutator_set G = {g | ∃ g₁ g₂ : G, ⁅g₁, g₂⁆ = g} := rfl
lemma one_mem_commutator_set : (1 : G) ∈ commutator_set G :=
⟨1, 1, commutator_element_self 1⟩
instance : nonempty (commutator_set G) :=
⟨⟨1, one_mem_commutator_set G⟩⟩
variables {G g}
lemma mem_commutator_set_iff : g ∈ commutator_set G ↔ ∃ g₁ g₂ : G, ⁅g₁, g₂⁆ = g :=
iff.rfl
lemma commutator_mem_commutator_set : ⁅g₁, g₂⁆ ∈ commutator_set G :=
⟨g₁, g₂, rfl⟩
|
933e886d1a7e056abf6a90c38848f170fad4558a
|
acc85b4be2c618b11fc7cb3005521ae6858a8d07
|
/order/filter.lean
|
00bfeade8d2e738e09933fbed1919aa263df0a9a
|
[
"Apache-2.0"
] |
permissive
|
linpingchuan/mathlib
|
d49990b236574df2a45d9919ba43c923f693d341
|
5ad8020f67eb13896a41cc7691d072c9331b1f76
|
refs/heads/master
| 1,626,019,377,808
| 1,508,048,784,000
| 1,508,048,784,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 68,464
|
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
Theory of filters on sets.
-/
import order.complete_lattice order.galois_connection data.set data.finset order.zorn
open lattice set
universes u v w x y
open set classical
local attribute [instance] decidable_inhabited prop_decidable
-- should be handled by implies_true_iff
namespace lattice
variables {α : Type u} {ι : Sort v} [complete_lattice α]
lemma Inf_eq_finite_sets {s : set α} :
Inf s = (⨅ t ∈ { t | finite t ∧ t ⊆ s}, Inf t) :=
le_antisymm
(le_infi $ assume t, le_infi $ assume ⟨_, h⟩, Inf_le_Inf h)
(le_Inf $ assume b h, infi_le_of_le {b} $ infi_le_of_le (by simp [h]) $ Inf_le $ by simp)
end lattice
namespace set
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort y}
theorem monotone_inter [preorder β] {f g : β → set α}
(hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ∩ (g x)) :=
assume a b h x ⟨h₁, h₂⟩, ⟨hf h h₁, hg h h₂⟩
theorem monotone_set_of [preorder α] {p : α → β → Prop}
(hp : ∀b, monotone (λa, p a b)) : monotone (λa, {b | p a b}) :=
assume a a' h b, hp b h
end set
section order
variables {α : Type u} (r : α → α → Prop)
local infix `≼` : 50 := r
def directed {ι : Sort v} (f : ι → α) := ∀x, ∀y, ∃z, f z ≼ f x ∧ f z ≼ f y
def directed_on (s : set α) := ∀x ∈ s, ∀y ∈ s, ∃z ∈ s, z ≼ x ∧ z ≼ y
lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊇) f)
(h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) :=
by simp [directed_on]; exact
assume a₁ b₁ fb₁ a₂ b₂ fb₂,
let
⟨z, zb₁, zb₂⟩ := hd b₁ b₂,
⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂)
in
⟨x, xa₁, xa₂, z, xf⟩
def upwards (s : set α) := ∀{x y}, x ∈ s → x ≼ y → y ∈ s
end order
theorem directed_of_chain {α : Type u} {β : Type v} [preorder β] {f : α → β} {c : set α}
(h : @zorn.chain α (λa b, f b ≤ f a) c) :
directed (≤) (λx:{a:α // a ∈ c}, f (x.val)) :=
assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases
(assume : a = b, by simp [this]; exact ⟨b, hb, le_refl _⟩)
(assume : a ≠ b,
have f b ≤ f a ∨ f a ≤ f b, from h a ha b hb this,
or.elim this
(assume : f b ≤ f a, ⟨⟨b, hb⟩, this, le_refl _⟩)
(assume : f a ≤ f b, ⟨⟨a, ha⟩, le_refl _, this⟩))
structure filter (α : Type u) :=
(sets : set (set α))
(exists_mem_sets : ∃x, x ∈ sets)
(upwards_sets : upwards (⊆) sets)
(directed_sets : directed_on (⊆) sets)
namespace filter
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
lemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g
| ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl
lemma univ_mem_sets' {f : filter α} {s : set α} (h : ∀ a, a ∈ s): s ∈ f.sets :=
let ⟨x, x_in_s⟩ := f.exists_mem_sets in
f.upwards_sets x_in_s (assume x _, h x)
lemma univ_mem_sets {f : filter α} : univ ∈ f.sets :=
univ_mem_sets' mem_univ
lemma inter_mem_sets {f : filter α} {x y : set α} (hx : x ∈ f.sets) (hy : y ∈ f.sets) :
x ∩ y ∈ f.sets :=
let ⟨z, ⟨z_in_s, z_le_x, z_le_y⟩⟩ := f.directed_sets _ hx _ hy in
f.upwards_sets z_in_s (subset_inter z_le_x z_le_y)
lemma Inter_mem_sets {f : filter α} {s : β → set α}
{is : set β} (hf : finite is) (hs : ∀i∈is, s i ∈ f.sets) : (⋂i∈is, s i) ∈ f.sets :=
begin /- equation compiler complains that this requires well-founded recursion -/
induction hf with i is _ hf hi,
{ simp [univ_mem_sets] },
begin
simp,
apply inter_mem_sets,
apply hs i,
simp,
exact (hi $ assume a ha, hs _ $ by simp [ha])
end
end
lemma exists_sets_subset_iff {f : filter α} {x : set α} :
(∃y∈f.sets, y ⊆ x) ↔ x ∈ f.sets :=
⟨assume ⟨y, hy, yx⟩, f.upwards_sets hy yx,
assume hx, ⟨x, hx, subset.refl _⟩⟩
lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f.sets) :=
assume s t hst h, f.upwards_sets h hst
def principal (s : set α) : filter α :=
{ filter .
sets := {t | s ⊆ t},
exists_mem_sets := ⟨s, subset.refl _⟩,
upwards_sets := assume x y hx hy, subset.trans hx hy,
directed_sets := assume x hx y hy, ⟨s, subset.refl _, hx, hy⟩ }
def join (f : filter (filter α)) : filter α :=
{ filter .
sets := {s | {t : filter α | s ∈ t.sets} ∈ f.sets},
exists_mem_sets := ⟨univ, by simp [univ_mem_sets]; exact univ_mem_sets⟩,
upwards_sets := assume x y hx xy, f.upwards_sets hx $ assume a h, a.upwards_sets h xy,
directed_sets := assume x hx y hy, ⟨x ∩ y,
f.upwards_sets (inter_mem_sets hx hy) $ assume z ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂,
inter_subset_left _ _, inter_subset_right _ _⟩ }
def map (m : α → β) (f : filter α) : filter β :=
{ filter .
sets := preimage (preimage m) f.sets,
exists_mem_sets := ⟨univ, univ_mem_sets⟩,
upwards_sets := assume s t hs st, f.upwards_sets hs (assume x h, st h),
directed_sets := assume s hs t ht, ⟨s ∩ t, inter_mem_sets hs ht,
inter_subset_left _ _, inter_subset_right _ _⟩ }
def vmap (m : α → β) (f : filter β) : filter α :=
{ filter .
sets := { s | ∃t∈f.sets, preimage m t ⊆ s },
exists_mem_sets := ⟨univ, univ, univ_mem_sets, by simp⟩,
upwards_sets := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩,
directed_sets := assume a ⟨a', ha₁, ha₂⟩ b ⟨b', hb₁, hb₂⟩,
⟨preimage m (a' ∩ b'),
⟨a' ∩ b', inter_mem_sets ha₁ hb₁, subset.refl _⟩,
subset.trans (preimage_mono $ inter_subset_left _ _) ha₂,
subset.trans (preimage_mono $ inter_subset_right _ _) hb₂⟩ }
protected def sup (f g : filter α) : filter α :=
{ filter .
sets := f.sets ∩ g.sets,
exists_mem_sets := ⟨univ, by simp [univ_mem_sets]; exact univ_mem_sets⟩,
upwards_sets := assume x y hx xy,
and.imp (assume h, f.upwards_sets h xy) (assume h, g.upwards_sets h xy) hx,
directed_sets := assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∩ y,
⟨inter_mem_sets hx₁ hy₁, inter_mem_sets hx₂ hy₂⟩,
inter_subset_left _ _, inter_subset_right _ _⟩ }
protected def inf (f g : filter α) :=
{ filter .
sets := {s | ∃ a ∈ f.sets, ∃ b ∈ g.sets, a ∩ b ⊆ s },
exists_mem_sets := ⟨univ, univ, univ_mem_sets, univ, univ_mem_sets, subset_univ _⟩,
upwards_sets := assume x y ⟨a, ha, b, hb, h⟩ xy,
⟨a, ha, b, hb, subset.trans h xy⟩,
directed_sets := assume x ⟨a₁, ha₁, b₁, hb₁, h₁⟩ y ⟨a₂, ha₂, b₂, hb₂, h₂⟩,
⟨x ∩ y,
⟨_, inter_mem_sets ha₁ ha₂, _, inter_mem_sets hb₁ hb₂,
calc (a₁ ⊓ a₂) ⊓ (b₁ ⊓ b₂) = (a₁ ⊓ b₁) ⊓ (a₂ ⊓ b₂) : by ac_refl
... ≤ x ∩ y : inf_le_inf h₁ h₂ ⟩,
inter_subset_left _ _, inter_subset_right _ _⟩ }
def cofinite : filter α :=
{ filter .
sets := {s | finite (- s)},
exists_mem_sets := ⟨univ, by simp⟩,
upwards_sets := assume s t, assume hs : finite (-s), assume st: s ⊆ t,
finite_subset hs $ @lattice.neg_le_neg (set α) _ _ _ st,
directed_sets := assume s, assume hs : finite (-s), assume t, assume ht : finite (-t),
⟨s ∩ t, by simp [compl_inter, finite_union, ht, hs],
inter_subset_left _ _, inter_subset_right _ _⟩ }
instance partial_order_filter : partial_order (filter α) :=
{ partial_order .
le := λf g, g.sets ⊆ f.sets,
le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁,
le_refl := assume a, subset.refl _,
le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ }
instance : has_Sup (filter α) := ⟨join ∘ principal⟩
instance : inhabited (filter α) :=
⟨principal ∅⟩
protected lemma le_Sup {s : set (filter α)} {f : filter α} : f ∈ s → f ≤ Sup s :=
assume f_in_s t' h, h f_in_s
protected lemma Sup_le {s : set (filter α)} {f : filter α} : (∀g∈s, g ≤ f) → Sup s ≤ f :=
assume h a ha g hg, h g hg ha
@[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} :
s ∈ (join f).sets = ({t | s ∈ filter.sets t} ∈ f.sets) := rfl
@[simp] lemma mem_principal_sets {s t : set α} : s ∈ (principal t).sets = (t ⊆ s) := rfl
@[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ principal s ↔ s ∈ f.sets :=
show (∀{t}, s ⊆ t → t ∈ f.sets) ↔ s ∈ f.sets,
from ⟨assume h, h (subset.refl s), assume hs t ht, f.upwards_sets hs ht⟩
lemma principal_mono {s t : set α} : principal s ≤ principal t ↔ s ⊆ t :=
by simp
lemma monotone_principal : monotone (principal : set α → filter α) :=
by simp [monotone, principal_mono]; exact assume a b h, h
@[simp] lemma principal_eq_iff_eq {s t : set α} : principal s = principal t ↔ s = t :=
by simp [eq_iff_le_and_le]; refl
instance complete_lattice_filter : complete_lattice (filter α) :=
{ filter.partial_order_filter with
sup := filter.sup,
le_sup_left := assume a b, inter_subset_left _ _,
le_sup_right := assume a b, inter_subset_right _ _,
sup_le := assume a b c h₁ h₂, subset_inter h₁ h₂,
inf := filter.inf,
le_inf := assume f g h fg fh s ⟨a, ha, b, hb, h⟩,
f.upwards_sets (inter_mem_sets (fg ha) (fh hb)) h,
inf_le_left := assume f g s h, ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩,
inf_le_right := assume f g s h, ⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩,
top := principal univ,
le_top := assume a, show a ≤ principal univ, by simp [univ_mem_sets],
bot := principal ∅,
bot_le := assume a, show a.sets ⊆ {x | ∅ ⊆ x}, by simp; apply subset_univ,
Sup := Sup,
le_Sup := assume s f, filter.le_Sup,
Sup_le := assume s f, filter.Sup_le,
Inf := λs, Sup {x | ∀y∈s, x ≤ y},
le_Inf := assume s a h, filter.le_Sup h,
Inf_le := assume s a ha, filter.Sup_le $ assume b h, h _ ha }
@[simp] lemma map_principal {s : set α} {f : α → β} :
map f (principal s) = principal (set.image f s) :=
filter_eq $ set.ext $ assume a, image_subset_iff.symm
@[simp] lemma mem_top_sets_iff {s : set α} : s ∈ (⊤ : filter α).sets ↔ s = univ :=
⟨assume h, top_unique $ h, assume h, h.symm ▸ univ_mem_sets⟩
@[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (principal s) = Sup s := rfl
instance monad_filter : monad filter :=
{ monad .
bind := λ(α β : Type u) f m, join (map m f),
pure := λ(α : Type u) x, principal {x},
map := λ(α β : Type u), filter.map,
id_map := assume α f, filter_eq $ rfl,
pure_bind := assume α β a f, by simp [Sup_image],
bind_assoc := assume α β γ f m₁ m₂, filter_eq $ rfl,
bind_pure_comp_eq_map := assume α β f x, filter_eq $ by simp [join, map, preimage, principal] }
@[simp] lemma pure_def (x : α) : pure x = principal {x} := rfl
@[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = join (map m f) := rfl
instance : alternative filter :=
{ filter.monad_filter with
failure := λα, ⊥,
orelse := λα x y, x ⊔ y }
/- lattice equations -/
lemma mem_inf_sets_of_left {f g : filter α} {s : set α} :
s ∈ f.sets → s ∈ (f ⊓ g).sets :=
have f ⊓ g ≤ f, from inf_le_left,
assume hs, this hs
lemma mem_inf_sets_of_right {f g : filter α} {s : set α} :
s ∈ g.sets → s ∈ (f ⊓ g).sets :=
have f ⊓ g ≤ g, from inf_le_right,
assume hs, this hs
@[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α).sets :=
assume x, false.elim
lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f.sets ↔ f = ⊥ :=
⟨assume h, bot_unique $ assume s _, f.upwards_sets h (empty_subset s),
assume : f = ⊥, this.symm ▸ mem_bot_sets⟩
lemma inhabited_of_mem_sets {f : filter α} {s : set α} (hf : f ≠ ⊥) (hs : s ∈ f.sets) :
∃x, x ∈ s :=
have ∅ ∉ f.sets, from assume h, hf $ empty_in_sets_eq_bot.mp h,
have s ≠ ∅, from assume h, this (h ▸ hs),
exists_mem_of_ne_empty this
lemma filter_eq_bot_of_not_nonempty {f : filter α} (ne : ¬ nonempty α) : f = ⊥ :=
empty_in_sets_eq_bot.mp $ f.upwards_sets univ_mem_sets $
assume x, false.elim (ne ⟨x⟩)
lemma forall_sets_neq_empty_iff_neq_bot {f : filter α} :
(∀ (s : set α), s ∈ f.sets → s ≠ ∅) ↔ f ≠ ⊥ :=
by
simp [(@empty_in_sets_eq_bot α f).symm];
exact ⟨assume h hs, h _ hs rfl, assume h s hs eq, h $ eq ▸ hs⟩
lemma mem_sets_of_neq_bot {f : filter α} {s : set α} (h : f ⊓ principal (-s) = ⊥) : s ∈ f.sets :=
have ∅ ∈ (f ⊓ principal (- s)).sets, from h.symm ▸ mem_bot_sets,
let ⟨s₁, hs₁, s₂, (hs₂ : -s ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in
have s₁ ⊆ s, from assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩,
f.upwards_sets hs₁ this
@[simp] lemma mem_sup_sets {f g : filter α} {s : set α} :
s ∈ (f ⊔ g).sets = (s ∈ f.sets ∧ s ∈ g.sets) := rfl
@[simp] lemma mem_inf_sets {f g : filter α} {s : set α} :
s ∈ (f ⊓ g).sets = (∃t₁∈f.sets, ∃t₂∈g.sets, t₁ ∩ t₂ ⊆ s) :=
by refl
lemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α}
(hs : s ∈ f.sets) (ht : t ∈ g.sets) : s ∩ t ∈ (f ⊓ g).sets :=
inter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht)
lemma infi_sets_eq {f : ι → filter α} (h : directed (≤) f) (ne : nonempty ι) :
(infi f).sets = (⋃ i, (f i).sets) :=
let
⟨i⟩ := ne,
u := { filter .
sets := (⋃ i, (f i).sets),
exists_mem_sets := ⟨univ, begin simp, exact ⟨i, univ_mem_sets⟩ end⟩,
directed_sets := directed_on_Union (show directed (≤) f, from h) (assume i, (f i).directed_sets),
upwards_sets := by simp [upwards]; exact assume x y j xf xy, ⟨j, (f j).upwards_sets xf xy⟩ }
in
subset.antisymm
(show u ≤ infi f, from le_infi $ assume i, le_supr (λi, (f i).sets) i)
(Union_subset $ assume i, infi_le f i)
lemma infi_sets_eq' {f : β → filter α} {s : set β} (h : directed_on (λx y, f x ≤ f y) s) (ne : ∃i, i ∈ s) :
(⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) :=
let ⟨i, hi⟩ := ne in
calc (⨅ i ∈ s, f i).sets = (⨅ t : {t // t ∈ s}, (f t.val)).sets : by simp [infi_subtype]; refl
... = (⨆ t : {t // t ∈ s}, (f t.val).sets) : infi_sets_eq
(assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end)
⟨⟨i, hi⟩⟩
... = (⨆ t ∈ {t | t ∈ s}, (f t).sets) : by simp [supr_subtype]; refl
lemma Inf_sets_eq_finite {s : set (filter α)} :
(complete_lattice.Inf s).sets = (⋃ t ∈ {t | finite t ∧ t ⊆ s}, (Inf t).sets) :=
calc (Inf s).sets = (⨅ t ∈ { t | finite t ∧ t ⊆ s}, Inf t).sets : by rw [lattice.Inf_eq_finite_sets]
... = (⨆ t ∈ {t | finite t ∧ t ⊆ s}, (Inf t).sets) : infi_sets_eq'
(assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∪ y, ⟨finite_union hx₁ hy₁, union_subset hx₂ hy₂⟩,
Inf_le_Inf $ subset_union_left _ _, Inf_le_Inf $ subset_union_right _ _⟩)
⟨∅, by simp⟩
lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) :=
set.ext $ assume s,
show s ∈ (join (principal {a : filter α | ∃i : ι, a = f i})).sets ↔ s ∈ (⋂i, (f i).sets),
begin
rw [mem_join_sets],
simp, rw [forall_swap],
exact forall_congr (λ i, by simp)
end
@[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) :=
filter_eq $ set.ext $ assume x, by simp [supr_sets_eq, join]
@[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) :=
filter_eq $ set.ext $ assume x, by simp [supr_sets_eq, join]
instance : bounded_distrib_lattice (filter α) :=
{ filter.complete_lattice_filter with
le_sup_inf := assume x y z s h,
begin
cases h with h₁ h₂, revert h₂,
simp,
exact assume t₁ ht₁ t₂ ht₂ hs, ⟨s ∪ t₁,
x.upwards_sets h₁ $ subset_union_left _ _,
y.upwards_sets ht₁ $ subset_union_right _ _,
s ∪ t₂,
x.upwards_sets h₁ $ subset_union_left _ _,
z.upwards_sets ht₂ $ subset_union_right _ _,
subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hs)⟩
end }
private lemma infi_finite_distrib {s : set (filter α)} {f : filter α} (h : finite s) :
(⨅ a ∈ s, f ⊔ a) = f ⊔ (Inf s) :=
begin
induction h with a s hn hs hi,
{ simp },
{ rw [infi_insert], simp [hi, infi_or, sup_inf_left] }
end
/- the complementary version with ⨆ g∈s, f ⊓ g does not hold! -/
lemma binfi_sup_eq { f : filter α } {s : set (filter α)} :
(⨅ g∈s, f ⊔ g) = f ⊔ complete_lattice.Inf s :=
le_antisymm
begin
intros t h,
cases h with h₁ h₂,
rw [Inf_sets_eq_finite] at h₂,
simp at h₂,
cases h₂ with s' hs', cases hs' with hs' hs'', cases hs'' with hs's ht',
have ht : t ∈ (⨅ a ∈ s', f ⊔ a).sets,
{ rw [infi_finite_distrib], exact ⟨h₁, ht'⟩, exact hs' },
clear h₁ ht',
revert ht t,
change (⨅ a ∈ s, f ⊔ a) ≤ (⨅ a ∈ s', f ⊔ a),
apply infi_le_infi2 _,
exact assume i, ⟨i, infi_le_infi2 $ assume h, ⟨hs's h, le_refl _⟩⟩
end
(le_infi $ assume g, le_infi $ assume h, sup_le_sup (le_refl f) $ Inf_le h)
lemma infi_sup_eq { f : filter α } {g : ι → filter α} :
(⨅ x, f ⊔ g x) = f ⊔ infi g :=
calc (⨅ x, f ⊔ g x) = (⨅ x (h : ∃i, g i = x), f ⊔ x) : by simp; rw [infi_comm]; simp
... = f ⊔ Inf {x | ∃i, g i = x} : binfi_sup_eq
... = f ⊔ infi g : by rw [Inf_eq_infi]; dsimp; simp; rw [infi_comm]; simp
lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} :
∀t, t ∈ (⨅a∈s, f a).sets ↔ (∃p:α → set β, (∀a∈s, p a ∈ (f a).sets) ∧ (⋂a∈s, p a) ⊆ t) :=
show ∀t, t ∈ (⨅a∈s, f a).sets ↔ (∃p:α → set β, (∀a∈s, p a ∈ (f a).sets) ∧ (⨅a∈s, p a) ≤ t),
from s.induction_on (by simp; exact assume t, iff.refl _) $
by simp [infi_or, mem_inf_sets, infi_inf_eq] {contextual := tt};
from assume a s has ih t, iff.intro
(assume ⟨t₁, ht₁, t₂, ht, p, hp, ht₂⟩,
⟨λa', if a' = a then t₁ else p a',
assume a' ha', by by_cases a' = a; simp * at *,
have ∀a', (⨅ (h : a' ∈ s), ite (a' = a) t₁ (p a')) ≤ ⨅ (H : a' ∈ s), p a',
from assume a', infi_le_infi $ assume has',
have a' ≠ a, from assume h, has $ h ▸ has',
le_of_eq $ by simp [this],
le_trans (inf_le_inf (by simp; exact le_refl t₁) (le_trans (infi_le_infi this) ht₂)) ht⟩)
(assume ⟨p, hp, ht⟩, ⟨p a, hp _ (by simp), ⨅ (x : α) (h : x ∈ s), p x, ht, p,
assume a ha, hp _ (or.inr ha), le_refl _⟩)
/- principal equations -/
@[simp] lemma inf_principal {s t : set α} : principal s ⊓ principal t = principal (s ∩ t) :=
le_antisymm
(by simp; exact ⟨s, subset.refl s, t, subset.refl t, subset.refl _⟩)
(by simp [le_inf_iff, inter_subset_left, inter_subset_right])
@[simp] lemma sup_principal {s t : set α} : principal s ⊔ principal t = principal (s ∪ t) :=
filter_eq $ set.ext $ by simp [union_subset_iff]
@[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, principal (s x)) = principal (⋃i, s i) :=
filter_eq $ set.ext $ assume x, by simp [supr_sets_eq]; exact (@supr_le_iff (set α) _ _ _ _).symm
lemma principal_univ : principal (univ : set α) = ⊤ := rfl
lemma principal_empty : principal (∅ : set α) = ⊥ := rfl
@[simp] lemma principal_eq_bot_iff {s : set α} : principal s = ⊥ ↔ s = ∅ :=
⟨assume h, principal_eq_iff_eq.mp $ by simp [principal_empty, h], assume h, by simp [*, principal_empty]⟩
lemma inf_principal_eq_bot {f : filter α} {s : set α} (hs : -s ∈ f.sets) : f ⊓ principal s = ⊥ :=
empty_in_sets_eq_bot.mp $ (f ⊓ principal s).upwards_sets
(inter_mem_inf_sets hs (mem_principal_sets.mpr $ set.subset.refl s))
(assume x ⟨h₁, h₂⟩, h₁ h₂)
@[simp] lemma mem_pure {a : α} {s : set α} : a ∈ s → s ∈ (pure a : filter α).sets :=
by simp; exact id
/- map and vmap equations -/
section map
variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β}
@[simp] lemma mem_map : (t ∈ (map m f).sets) = ({x | m x ∈ t} ∈ f.sets) := rfl
lemma image_mem_map (hs : s ∈ f.sets) : m '' s ∈ (map m f).sets :=
f.upwards_sets hs $ assume x hx, ⟨x, hx, rfl⟩
@[simp] lemma map_id : filter.map id f = f :=
filter_eq $ rfl
@[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) :=
funext $ assume _, filter_eq $ rfl
@[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f :=
congr_fun (@@filter.map_compose m m') f
theorem mem_vmap : s ∈ (vmap m g).sets = (∃t∈g.sets, m ⁻¹' t ⊆ s) := rfl
theorem preimage_mem_vmap (ht : t ∈ g.sets) : m ⁻¹' t ∈ (vmap m g).sets :=
⟨t, ht, subset.refl _⟩
lemma vmap_id : vmap id f = f :=
le_antisymm (assume s, preimage_mem_vmap) (assume s ⟨t, ht, hst⟩, f.upwards_sets ht hst)
lemma vmap_vmap_comp {m : γ → β} {n : β → α} : vmap m (vmap n f) = vmap (n ∘ m) f :=
le_antisymm
(assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_vmap hb, h⟩)
(assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩,
⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩)
@[simp] theorem vmap_principal {t : set β} : vmap m (principal t) = principal (m ⁻¹' t) :=
filter_eq $ set.ext $ assume s,
⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b,
assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩
lemma map_le_iff_vmap_le : map m f ≤ g ↔ f ≤ vmap m g :=
⟨assume h s ⟨t, ht, hts⟩, f.upwards_sets (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩
lemma gc_map_vmap (m : α → β) : galois_connection (map m) (vmap m) :=
assume f g, map_le_iff_vmap_le
lemma map_mono (h : f₁ ≤ f₂) : map m f₁ ≤ map m f₂ := (gc_map_vmap m).monotone_l h
lemma monotone_map : monotone (map m) := assume a b h, map_mono h
lemma vmap_mono (h : g₁ ≤ g₂) : vmap m g₁ ≤ vmap m g₂ := (gc_map_vmap m).monotone_u h
lemma monotone_vmap : monotone (vmap m) := assume a b h, vmap_mono h
@[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_vmap m).l_bot
@[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_vmap m).l_sup
@[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) :=
(gc_map_vmap m).l_supr
@[simp] lemma vmap_top : vmap m ⊤ = ⊤ := (gc_map_vmap m).u_top
@[simp] lemma vmap_inf : vmap m (g₁ ⊓ g₂) = vmap m g₁ ⊓ vmap m g₂ := (gc_map_vmap m).u_inf
@[simp] lemma vmap_infi {f : ι → filter β} : vmap m (⨅i, f i) = (⨅i, vmap m (f i)) :=
(gc_map_vmap m).u_infi
lemma map_vmap_le : map m (vmap m g) ≤ g := (gc_map_vmap m).decreasing_l_u _
lemma le_vmap_map : f ≤ vmap m (map m f) := (gc_map_vmap m).increasing_u_l _
@[simp] lemma vmap_bot : vmap m ⊥ = ⊥ :=
bot_unique $ assume s _, ⟨∅, by simp, by simp⟩
lemma vmap_sup : vmap m (g₁ ⊔ g₂) = vmap m g₁ ⊔ vmap m g₂ :=
le_antisymm
(assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩,
⟨t₁ ∪ t₂,
⟨g₁.upwards_sets ht₁ (subset_union_left _ _), g₂.upwards_sets ht₂ (subset_union_right _ _)⟩,
union_subset hs₁ hs₂⟩)
(sup_le (vmap_mono le_sup_left) (vmap_mono le_sup_right))
lemma le_map_vmap' {f : filter β} {m : α → β} {s : set β}
(hs : s ∈ f.sets) (hm : ∀b∈s, ∃a, m a = b) : f ≤ map m (vmap m f) :=
assume t' ⟨t, ht, (sub : m ⁻¹' t ⊆ m ⁻¹' t')⟩,
f.upwards_sets (inter_mem_sets ht hs) $
assume x ⟨hxt, hxs⟩,
let ⟨y, (hy : m y = x)⟩ := hm x hxs in
hy ▸ sub (show m y ∈ t, from hy.symm ▸ hxt)
lemma le_map_vmap {f : filter β} {m : α → β} (hm : ∀x, ∃y, m y = x) : f ≤ map m (vmap m f) :=
le_map_vmap' univ_mem_sets (assume b _, hm b)
lemma vmap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) :
vmap m (map m f) = f :=
have ∀s, preimage m (image m s) = s,
from assume s, preimage_image_eq h,
le_antisymm
(assume s hs, ⟨
image m s,
f.upwards_sets hs $ by simp [this, subset.refl],
by simp [this, subset.refl]⟩)
(assume s ⟨t, (h₁ : preimage m t ∈ f.sets), (h₂ : preimage m t ⊆ s)⟩,
f.upwards_sets h₁ h₂)
lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α}
(hsf : s ∈ f.sets) (hsg : s ∈ g.sets) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y)
(h : map m f ≤ map m g) : f ≤ g :=
assume t ht,
have m ⁻¹' (m '' (s ∩ t)) ∈ f.sets, from h $ image_mem_map (inter_mem_sets hsg ht),
f.upwards_sets (inter_mem_sets hsf this) $
assume a ⟨has, b, ⟨hbs, hb⟩, h⟩,
have b = a, from hm _ hbs _ has h,
this ▸ hb
lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α}
(hsf : s ∈ f.sets) (hsg : s ∈ g.sets) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y)
(h : map m f = map m g) : f = g :=
le_antisymm
(le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h)
(le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm)
lemma map_inj {f g : filter α} {m : α → β} (hm : ∀ x y, m x = m y → x = y) (h : map m f = map m g) :
f = g :=
have vmap m (map m f) = vmap m (map m g), by rw h,
by rwa [vmap_map hm, vmap_map hm] at this
lemma vmap_neq_bot {f : filter β} {m : α → β}
(hm : ∀t∈f.sets, ∃a, m a ∈ t) : vmap m f ≠ ⊥ :=
forall_sets_neq_empty_iff_neq_bot.mp $ assume s ⟨t, ht, t_s⟩,
let ⟨a, (ha : a ∈ preimage m t)⟩ := hm t ht in
neq_bot_of_le_neq_bot (ne_empty_of_mem ha) t_s
lemma vmap_neq_bot_of_surj {f : filter β} {m : α → β}
(hf : f ≠ ⊥) (hm : ∀b, ∃a, m a = b) : vmap m f ≠ ⊥ :=
vmap_neq_bot $ assume t ht,
let
⟨b, (hx : b ∈ t)⟩ := inhabited_of_mem_sets hf ht,
⟨a, (ha : m a = b)⟩ := hm b
in ⟨a, ha.symm ▸ hx⟩
lemma le_vmap_iff_map_le {f : filter α} {g : filter β} {m : α → β} :
f ≤ vmap m g ↔ map m f ≤ g :=
⟨assume h, le_trans (map_mono h) map_vmap_le,
assume h, le_trans le_vmap_map (vmap_mono h)⟩
@[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ :=
⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id,
assume h, by simp [*]⟩
lemma map_ne_bot (hf : f ≠ ⊥) : map m f ≠ ⊥ :=
assume h, hf $ by rwa [map_eq_bot_iff] at h
end map
lemma map_cong {m₁ m₂ : α → β} {f : filter α} (h : {x | m₁ x = m₂ x} ∈ f.sets) :
map m₁ f = map m₂ f :=
have ∀(m₁ m₂ : α → β) (h : {x | m₁ x = m₂ x} ∈ f.sets), map m₁ f ≤ map m₂ f,
from assume m₁ m₂ h s (hs : {x | m₂ x ∈ s} ∈ f.sets),
show {x | m₁ x ∈ s} ∈ f.sets,
from f.upwards_sets (inter_mem_sets hs h) $
assume x ⟨(h₁ : m₂ x ∈ s), (h₂ : m₁ x = m₂ x)⟩, show m₁ x ∈ s, from h₂.symm ▸ h₁,
le_antisymm (this m₁ m₂ h) (this m₂ m₁ $ f.upwards_sets h $ assume x, eq.symm)
-- this is a generic rule for monotone functions:
lemma map_infi_le {f : ι → filter α} {m : α → β} :
map m (infi f) ≤ (⨅ i, map m (f i)) :=
le_infi $ assume i, map_mono $ infi_le _ _
lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≤) f) (hι : nonempty ι) :
map m (infi f) = (⨅ i, map m (f i)) :=
le_antisymm
map_infi_le
(assume s (hs : preimage m s ∈ (infi f).sets),
have ∃i, preimage m s ∈ (f i).sets,
by simp [infi_sets_eq hf hι] at hs; assumption,
let ⟨i, hi⟩ := this in
have (⨅ i, map m (f i)) ≤ principal s,
from infi_le_of_le i $ by simp; assumption,
by simp at this; assumption)
lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop}
(h : directed_on (λx y, f x ≤ f y) {x | p x}) (ne : ∃i, p i) :
map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) :=
let ⟨i, hi⟩ := ne in
calc map m (⨅i (h : p i), f i) = map m (⨅i:subtype p, f i.val) : by simp [infi_subtype]
... = (⨅i:subtype p, map m (f i.val)) : map_infi_eq
(assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end)
⟨⟨i, hi⟩⟩
... = (⨅i (h : p i), map m (f i)) : by simp [infi_subtype]
lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f.sets) (htg : t ∈ g.sets)
(h : ∀x∈t, ∀y∈t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g :=
le_antisymm
(le_inf (map_mono inf_le_left) (map_mono inf_le_right))
(assume s hs,
begin
simp [map, mem_inf_sets] at hs,
simp [map, mem_inf_sets],
exact (let ⟨t₁, h₁, t₂, h₂, hs⟩ := hs in
have m '' (t₁ ∩ t) ∩ m '' (t₂ ∩ t) ⊆ s,
begin
rw [image_inter_on],
apply image_subset_iff.mpr _,
exact assume x ⟨⟨h₁, _⟩, h₂, _⟩, hs ⟨h₁, h₂⟩,
exact assume x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy
end,
⟨m '' (t₁ ∩ t),
f.upwards_sets (inter_mem_sets h₁ htf) $ image_subset_iff.mp $ subset.refl _,
m '' (t₂ ∩ t),
this,
g.upwards_sets (inter_mem_sets h₂ htg) $ image_subset_iff.mp $ subset.refl _⟩)
end)
lemma map_inf {f g : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) :
map m (f ⊓ g) = map m f ⊓ map m g :=
map_inf' univ_mem_sets univ_mem_sets (assume x _ y _, h x y)
/- bind equations -/
lemma mem_bind_sets {β : Type u} {s : set β} {f : filter α} {m : α → filter β} :
s ∈ (f >>= m).sets ↔ (∃t ∈ f.sets, ∀x ∈ t, s ∈ (m x).sets) :=
calc s ∈ (f >>= m).sets ↔ {a | s ∈ (m a).sets} ∈ f.sets : by simp
... ↔ (∃t ∈ f.sets, t ⊆ {a | s ∈ (m a).sets}) : exists_sets_subset_iff.symm
... ↔ (∃t ∈ f.sets, ∀x ∈ t, s ∈ (m x).sets) : iff.refl _
lemma bind_mono {β : Type u} {f : filter α} {g h : α → filter β} (h₁ : {a | g a ≤ h a} ∈ f.sets) :
f >>= g ≤ f >>= h :=
assume x h₂, f.upwards_sets (inter_mem_sets h₁ h₂) $ assume s ⟨gh', h'⟩, gh' h'
lemma bind_sup {β : Type u} {f g : filter α} {h : α → filter β} :
(f ⊔ g) >>= h = (f >>= h) ⊔ (g >>= h) :=
by simp
lemma bind_mono2 {β : Type u} {f g : filter α} {h : α → filter β} (h₁ : f ≤ g) :
f >>= h ≤ g >>= h :=
assume s h', h₁ h'
lemma principal_bind {β : Type u} {s : set α} {f : α → filter β} :
(principal s >>= f) = (⨆x ∈ s, f x) :=
show join (map f (principal s)) = (⨆x ∈ s, f x),
by simp [Sup_image]
lemma seq_mono {β : Type u} {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α}
(hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ <*> g₁ ≤ f₂ <*> g₂ :=
le_trans (bind_mono2 hf) (bind_mono $ univ_mem_sets' $ assume f, map_mono hg)
@[simp] lemma fmap_principal {β : Type u} {s : set α} {f : α → β} :
f <$> principal s = principal (set.image f s) :=
filter_eq $ set.ext $ assume a, image_subset_iff.symm
lemma mem_return_sets {a : α} {s : set α} : s ∈ (return a : filter α).sets ↔ a ∈ s :=
show s ∈ (principal {a}).sets ↔ a ∈ s,
by simp
lemma infi_neq_bot_of_directed {f : ι → filter α}
(hn : nonempty α) (hd : directed (≤) f) (hb : ∀i, f i ≠ ⊥): (infi f) ≠ ⊥ :=
let ⟨x⟩ := hn in
assume h, have he: ∅ ∈ (infi f).sets, from h.symm ▸ mem_bot_sets,
classical.by_cases
(assume : nonempty ι,
have ∃i, ∅ ∈ (f i).sets,
by rw [infi_sets_eq hd this] at he; simp at he; assumption,
let ⟨i, hi⟩ := this in
hb i $ bot_unique $
assume s _, (f i).upwards_sets hi $ empty_subset _)
(assume : ¬ nonempty ι,
have univ ⊆ (∅ : set α),
begin
rw [←principal_mono, principal_univ, principal_empty, ←h],
exact (le_infi $ assume i, false.elim $ this ⟨i⟩)
end,
this $ mem_univ x)
lemma infi_neq_bot_iff_of_directed {f : ι → filter α}
(hn : nonempty α) (hd : directed (≤) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) :=
⟨assume neq_bot i eq_bot, neq_bot $ bot_unique $ infi_le_of_le i $ eq_bot ▸ le_refl _,
infi_neq_bot_of_directed hn hd⟩
@[simp] lemma return_neq_bot {α : Type u} {a : α} : return a ≠ (⊥ : filter α) :=
by simp [return]
/- tendsto -/
def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := filter.map f l₁ ≤ l₂
lemma tendsto_cong {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β}
(h : tendsto f₁ l₁ l₂) (hl : {x | f₁ x = f₂ x} ∈ l₁.sets) : tendsto f₂ l₁ l₂ :=
by rwa [tendsto, ←map_cong hl]
lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y :=
by simp [tendsto] { contextual := tt }
lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x
lemma tendsto_compose {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ}
(hf : tendsto f x y) (hg : tendsto g y z) : tendsto (g ∘ f) x z :=
calc map (g ∘ f) x = map g (map f x) : by rw [map_map]
... ≤ map g y : map_mono hf
... ≤ z : hg
lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x)
lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ}
(h : tendsto (f ∘ g) x y) : tendsto f (map g x) y :=
by rwa [tendsto, map_map]
lemma tendsto_vmap {f : α → β} {x : filter β} : tendsto f (vmap f x) x :=
map_vmap_le
lemma tendsto_vmap' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ}
(h : tendsto (f ∘ g) x y) : tendsto g x (vmap f y) :=
le_vmap_iff_map_le.mpr $ by rwa [map_map]
lemma tendsto_vmap'' {m : α → β} {f : filter α} {g : filter β} (s : set α)
{i : γ → α} (hs : s ∈ f.sets) (hi : ∀a∈s, ∃c, i c = a)
(h : tendsto (m ∘ i) (vmap i f) g) : tendsto m f g :=
have tendsto m (map i $ vmap i $ f) g,
by rwa [tendsto, ←map_compose] at h,
le_trans (map_mono $ le_map_vmap' hs hi) this
lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β}
(h₁ : tendsto f x y₁) (h₂ : tendsto f x y₂) : tendsto f x (y₁ ⊓ y₂) :=
le_inf h₁ h₂
lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β}
(h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y :=
le_trans (map_mono inf_le_left) h
lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β}
(h : ∀i, tendsto f x (y i)) : tendsto f x (⨅i, y i) :=
le_infi h
lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι)
(h : tendsto f (x i) y) : tendsto f (⨅i, x i) y :=
le_trans (map_mono $ infi_le _ _) h
lemma tendsto_principal {f : α → β} {a : filter α} {s : set β}
(h : {a | f a ∈ s} ∈ a.sets) : tendsto f a (principal s) :=
by simp [tendsto]; exact h
lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β}
(h : ∀a∈s, f a ∈ t) : tendsto f (principal s) (principal t) :=
by simp [tendsto, image_subset_iff]; exact h
section lift
protected def lift (f : filter α) (g : set α → filter β) :=
(⨅s ∈ f.sets, g s)
section
variables {f f₁ f₂ : filter α} {g g₁ g₂ : set α → filter β}
lemma lift_sets_eq (hg : monotone g) : (f.lift g).sets = (⋃t∈f.sets, (g t).sets) :=
infi_sets_eq'
(assume s hs t ht, ⟨s ∩ t, inter_mem_sets hs ht,
hg $ inter_subset_left s t, hg $ inter_subset_right s t⟩)
⟨univ, univ_mem_sets⟩
lemma mem_lift {s : set β} {t : set α} (ht : t ∈ f.sets) (hs : s ∈ (g t).sets) :
s ∈ (f.lift g).sets :=
le_principal_iff.mp $ show f.lift g ≤ principal s,
from infi_le_of_le t $ infi_le_of_le ht $ le_principal_iff.mpr hs
lemma mem_lift_iff (hg : monotone g) {s : set β} :
s ∈ (f.lift g).sets ↔ (∃t∈f.sets, s ∈ (g t).sets) :=
by rw [lift_sets_eq hg]; simp
lemma lift_le {f : filter α} {g : set α → filter β} {h : filter β} {s : set α}
(hs : s ∈ f.sets) (hg : g s ≤ h) : f.lift g ≤ h :=
infi_le_of_le s $ infi_le_of_le hs $ hg
lemma lift_mono (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.lift g₁ ≤ f₂.lift g₂ :=
infi_le_infi $ assume s, infi_le_infi2 $ assume hs, ⟨hf hs, hg s⟩
lemma lift_mono' (hg : ∀s∈f.sets, g₁ s ≤ g₂ s) : f.lift g₁ ≤ f.lift g₂ :=
infi_le_infi $ assume s, infi_le_infi $ assume hs, hg s hs
lemma map_lift_eq {m : β → γ} (hg : monotone g) :
map m (f.lift g) = f.lift (map m ∘ g) :=
have monotone (map m ∘ g),
from monotone_comp hg monotone_map,
filter_eq $ set.ext $
by simp [mem_lift_iff, hg, @mem_lift_iff _ _ f _ this]
lemma vmap_lift_eq {m : γ → β} (hg : monotone g) :
vmap m (f.lift g) = f.lift (vmap m ∘ g) :=
have monotone (vmap m ∘ g),
from monotone_comp hg monotone_vmap,
filter_eq $ set.ext $
begin
simp [vmap, mem_lift_iff, hg, @mem_lift_iff _ _ f _ this],
simp [vmap, function.comp],
exact assume s, ⟨assume ⟨t₁, hs, t₂, ht, ht₁⟩, ⟨t₂, ht, t₁, hs, ht₁⟩,
assume ⟨t₂, ht, t₁, hs, ht₁⟩, ⟨t₁, hs, t₂, ht, ht₁⟩⟩
end
theorem vmap_lift_eq2 {m : β → α} {g : set β → filter γ} (hg : monotone g) :
(vmap m f).lift g = f.lift (g ∘ preimage m) :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs,
infi_le_of_le (preimage m s) $ infi_le _ ⟨s, hs, subset.refl _⟩)
(le_infi $ assume s, le_infi $ assume ⟨s', hs', (h_sub : preimage m s' ⊆ s)⟩,
infi_le_of_le s' $ infi_le_of_le hs' $ hg h_sub)
lemma map_lift_eq2 {g : set β → filter γ} {m : α → β} (hg : monotone g) :
(map m f).lift g = f.lift (g ∘ image m) :=
le_antisymm
(infi_le_infi2 $ assume s, ⟨image m s,
infi_le_infi2 $ assume hs, ⟨
f.upwards_sets hs $ assume a h, mem_image_of_mem _ h,
le_refl _⟩⟩)
(infi_le_infi2 $ assume t, ⟨preimage m t,
infi_le_infi2 $ assume ht, ⟨ht,
hg $ assume x, assume h : x ∈ m '' preimage m t,
let ⟨y, hy, h_eq⟩ := h in
show x ∈ t, from h_eq ▸ hy⟩⟩)
lemma lift_comm {g : filter β} {h : set α → set β → filter γ} :
f.lift (λs, g.lift (h s)) = g.lift (λt, f.lift (λs, h s t)) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj,
infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi)
(le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj,
infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi)
lemma lift_assoc {h : set β → filter γ} (hg : monotone g) :
(f.lift g).lift h = f.lift (λs, (g s).lift h) :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht,
infi_le_of_le t $ infi_le _ $ (mem_lift_iff hg).mpr ⟨_, hs, ht⟩)
(le_infi $ assume t, le_infi $ assume ht,
let ⟨s, hs, h'⟩ := (mem_lift_iff hg).mp ht in
infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ h')
lemma lift_lift_same_le_lift {g : set α → set α → filter β} :
f.lift (λs, f.lift (g s)) ≤ f.lift (λs, g s s) :=
le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le _ hs
lemma lift_lift_same_eq_lift {g : set α → set α → filter β}
(hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)):
f.lift (λs, f.lift (g s)) = f.lift (λs, g s s) :=
le_antisymm
lift_lift_same_le_lift
(le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht,
infi_le_of_le (s ∩ t) $
infi_le_of_le (inter_mem_sets hs ht) $
calc g (s ∩ t) (s ∩ t) ≤ g s (s ∩ t) : hg₂ (s ∩ t) (inter_subset_left _ _)
... ≤ g s t : hg₁ s (inter_subset_right _ _))
lemma lift_principal {s : set α} (hg : monotone g) :
(principal s).lift g = g s :=
le_antisymm
(infi_le_of_le s $ infi_le _ $ subset.refl _)
(le_infi $ assume t, le_infi $ assume hi, hg hi)
theorem monotone_lift [preorder γ] {f : γ → filter α} {g : γ → set α → filter β}
(hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift (g c)) :=
assume a b h, lift_mono (hf h) (hg h)
lemma lift_neq_bot_iff (hm : monotone g) : (f.lift g ≠ ⊥) ↔ (∀s∈f.sets, g s ≠ ⊥) :=
classical.by_cases
(assume hn : nonempty β,
calc f.lift g ≠ ⊥ ↔ (⨅s : { s // s ∈ f.sets}, g s.val) ≠ ⊥ : by simp [filter.lift, infi_subtype]
... ↔ (∀s:{ s // s ∈ f.sets}, g s.val ≠ ⊥) :
infi_neq_bot_iff_of_directed hn
(assume ⟨a, ha⟩ ⟨b, hb⟩, ⟨⟨a ∩ b, inter_mem_sets ha hb⟩,
hm $ inter_subset_left _ _, hm $ inter_subset_right _ _⟩)
... ↔ (∀s∈f.sets, g s ≠ ⊥) : ⟨assume h s hs, h ⟨s, hs⟩, assume h ⟨s, hs⟩, h s hs⟩)
(assume hn : ¬ nonempty β,
have h₁ : f.lift g = ⊥, from filter_eq_bot_of_not_nonempty hn,
have h₂ : ∀s, g s = ⊥, from assume s, filter_eq_bot_of_not_nonempty hn,
calc (f.lift g ≠ ⊥) ↔ false : by simp [h₁]
... ↔ (∀s∈f.sets, false) : ⟨false.elim, assume h, h univ univ_mem_sets⟩
... ↔ (∀s∈f.sets, g s ≠ ⊥) : by simp [h₂])
end
section
protected def lift' (f : filter α) (h : set α → set β) :=
f.lift (principal ∘ h)
variables {f f₁ f₂ : filter α} {h h₁ h₂ : set α → set β}
lemma mem_lift' {t : set α} (ht : t ∈ f.sets) : h t ∈ (f.lift' h).sets :=
le_principal_iff.mp $ show f.lift' h ≤ principal (h t),
from infi_le_of_le t $ infi_le_of_le ht $ le_refl _
lemma mem_lift'_iff (hh : monotone h) {s : set β} : s ∈ (f.lift' h).sets ↔ (∃t∈f.sets, h t ⊆ s) :=
have monotone (principal ∘ h),
from assume a b h, principal_mono.mpr $ hh h,
by simp [filter.lift', @mem_lift_iff α β f _ this]
lemma lift'_le {f : filter α} {g : set α → set β} {h : filter β} {s : set α}
(hs : s ∈ f.sets) (hg : principal (g s) ≤ h) : f.lift' g ≤ h :=
lift_le hs hg
lemma lift'_mono (hf : f₁ ≤ f₂) (hh : h₁ ≤ h₂) : f₁.lift' h₁ ≤ f₂.lift' h₂ :=
lift_mono hf $ assume s, principal_mono.mpr $ hh s
lemma lift'_mono' (hh : ∀s∈f.sets, h₁ s ⊆ h₂ s) : f.lift' h₁ ≤ f.lift' h₂ :=
infi_le_infi $ assume s, infi_le_infi $ assume hs, principal_mono.mpr $ hh s hs
lemma lift'_cong (hh : ∀s∈f.sets, h₁ s = h₂ s) : f.lift' h₁ = f.lift' h₂ :=
le_antisymm (lift'_mono' $ assume s hs, le_of_eq $ hh s hs) (lift'_mono' $ assume s hs, le_of_eq $ (hh s hs).symm)
lemma map_lift'_eq {m : β → γ} (hh : monotone h) : map m (f.lift' h) = f.lift' (image m ∘ h) :=
calc map m (f.lift' h) = f.lift (map m ∘ principal ∘ h) :
map_lift_eq $ monotone_comp hh monotone_principal
... = f.lift' (image m ∘ h) : by simp [function.comp, filter.lift']
lemma map_lift'_eq2 {g : set β → set γ} {m : α → β} (hg : monotone g) :
(map m f).lift' g = f.lift' (g ∘ image m) :=
map_lift_eq2 $ monotone_comp hg monotone_principal
theorem vmap_lift'_eq {m : γ → β} (hh : monotone h) :
vmap m (f.lift' h) = f.lift' (preimage m ∘ h) :=
calc vmap m (f.lift' h) = f.lift (vmap m ∘ principal ∘ h) :
vmap_lift_eq $ monotone_comp hh monotone_principal
... = f.lift' (preimage m ∘ h) : by simp [function.comp, filter.lift']
theorem vmap_lift'_eq2 {m : β → α} {g : set β → set γ} (hg : monotone g) :
(vmap m f).lift' g = f.lift' (g ∘ preimage m) :=
vmap_lift_eq2 $ monotone_comp hg monotone_principal
lemma lift'_principal {s : set α} (hh : monotone h) :
(principal s).lift' h = principal (h s) :=
lift_principal $ monotone_comp hh monotone_principal
lemma principal_le_lift' {t : set β} (hh : ∀s∈f.sets, t ⊆ h s) :
principal t ≤ f.lift' h :=
le_infi $ assume s, le_infi $ assume hs, principal_mono.mpr (hh s hs)
theorem monotone_lift' [preorder γ] {f : γ → filter α} {g : γ → set α → set β}
(hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift' (g c)) :=
assume a b h, lift'_mono (hf h) (hg h)
lemma lift_lift'_assoc {g : set α → set β} {h : set β → filter γ}
(hg : monotone g) (hh : monotone h) :
(f.lift' g).lift h = f.lift (λs, h (g s)) :=
calc (f.lift' g).lift h = f.lift (λs, (principal (g s)).lift h) :
lift_assoc (monotone_comp hg monotone_principal)
... = f.lift (λs, h (g s)) : by simp [lift_principal, hh]
lemma lift'_lift'_assoc {g : set α → set β} {h : set β → set γ}
(hg : monotone g) (hh : monotone h) :
(f.lift' g).lift' h = f.lift' (λs, h (g s)) :=
lift_lift'_assoc hg (monotone_comp hh monotone_principal)
lemma lift'_lift_assoc {g : set α → filter β} {h : set β → set γ}
(hg : monotone g) : (f.lift g).lift' h = f.lift (λs, (g s).lift' h) :=
lift_assoc hg
lemma lift_lift'_same_le_lift' {g : set α → set α → set β} :
f.lift (λs, f.lift' (g s)) ≤ f.lift' (λs, g s s) :=
lift_lift_same_le_lift
lemma lift_lift'_same_eq_lift' {g : set α → set α → set β}
(hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)):
f.lift (λs, f.lift' (g s)) = f.lift' (λs, g s s) :=
lift_lift_same_eq_lift
(assume s, monotone_comp monotone_id $ monotone_comp (hg₁ s) monotone_principal)
(assume t, monotone_comp (hg₂ t) monotone_principal)
lemma lift'_inf_principal_eq {h : set α → set β} {s : set β} :
f.lift' h ⊓ principal s = f.lift' (λt, h t ∩ s) :=
le_antisymm
(le_infi $ assume t, le_infi $ assume ht,
calc filter.lift' f h ⊓ principal s ≤ principal (h t) ⊓ principal s :
inf_le_inf (infi_le_of_le t $ infi_le _ ht) (le_refl _)
... = _ : by simp)
(le_inf
(le_infi $ assume t, le_infi $ assume ht,
infi_le_of_le t $ infi_le_of_le ht $ by simp; exact inter_subset_right _ _)
(infi_le_of_le univ $ infi_le_of_le univ_mem_sets $ by simp; exact inter_subset_left _ _))
lemma lift'_neq_bot_iff (hh : monotone h) : (f.lift' h ≠ ⊥) ↔ (∀s∈f.sets, h s ≠ ∅) :=
calc (f.lift' h ≠ ⊥) ↔ (∀s∈f.sets, principal (h s) ≠ ⊥) :
lift_neq_bot_iff (monotone_comp hh monotone_principal)
... ↔ (∀s∈f.sets, h s ≠ ∅) : by simp [principal_eq_bot_iff]
@[simp] lemma lift'_id {f : filter α} : f.lift' id = f :=
le_antisymm
(assume s hs, mem_lift' hs)
(le_infi $ assume s, le_infi $ assume hs, by simp [hs])
lemma le_lift' {f : filter α} {h : set α → set β} {g : filter β}
(h_le : ∀s∈f.sets, h s ∈ g.sets) : g ≤ f.lift' h :=
le_infi $ assume s, le_infi $ assume hs, by simp [h_le]; exact h_le s hs
end
end lift
theorem vmap_eq_lift' {f : filter β} {m : α → β} :
vmap m f = f.lift' (preimage m) :=
filter_eq $ set.ext $ by simp [mem_lift'_iff, monotone_preimage, vmap]
/- product filter -/
/- The product filter cannot be defined using the monad structure on filters. For example:
F := do {x <- seq, y <- top, return (x, y)}
hence:
s ∈ F <-> ∃n, [n..∞] × univ ⊆ s
G := do {y <- top, x <- seq, return (x, y)}
hence:
s ∈ G <-> ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s
Now ⋃i, [i..∞] × {i} is in G but not in F.
As product filter we want to have F as result.
-/
/- Alternative definition of the product:
protected def prod (f : filter α) (g : filter β) : filter (α × β) :=
f.vmap prod.fst ⊓ g.vmap prod.snd
lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β}
(hs : s ∈ f.sets) (ht : t ∈ g.sets) : set.prod s t ∈ (filter.prod f g).sets :=
inter_mem_inf_sets (preimage_mem_vmap hs) (preimage_mem_vmap ht)
lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} :
s ∈ (filter.prod f g).sets ↔ (∃t₁∈f.sets, ∃t₂∈g.sets, set.prod t₁ t₂ ⊆ s) :=
by simp [filter.prod, mem_inf_sets, mem_vmap];
exact ⟨assume ⟨t₁', ⟨t₁, ht₁, h₁⟩, t₂', hst, ⟨t₂, ht₂, h₂⟩⟩,
⟨t₁, ht₁, t₂, ht₂, subset.trans (inter_subset_inter h₁ h₂) hst⟩,
assume ⟨t₁, ht₁, t₂, ht₂, h⟩,
⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, h, t₂, ht₂, subset.refl _⟩⟩
#exit
-/
section prod
variables {s : set α} {t : set β} {f : filter α} {g : filter β}
protected def prod (f : filter α) (g : filter β) : filter (α × β) :=
f.lift $ λs, g.lift' $ λt, set.prod s t
lemma prod_mem_prod (hs : s ∈ f.sets) (ht : t ∈ g.sets) : set.prod s t ∈ (filter.prod f g).sets :=
le_principal_iff.mp $ show filter.prod f g ≤ principal (set.prod s t),
from infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ ht
lemma prod_same_eq : filter.prod f f = f.lift' (λt, set.prod t t) :=
lift_lift'_same_eq_lift'
(assume s, set.monotone_prod monotone_const monotone_id)
(assume t, set.monotone_prod monotone_id monotone_const)
lemma mem_prod_iff {s : set (α×β)} :
s ∈ (filter.prod f g).sets ↔ (∃t₁∈f.sets, ∃t₂∈g.sets, set.prod t₁ t₂ ⊆ s) :=
begin
delta filter.prod,
rw [mem_lift_iff],
apply exists_congr, intro t₁,
apply exists_congr, intro ht₁,
rw [mem_lift'_iff],
exact set.monotone_prod monotone_const monotone_id,
exact (monotone_lift' monotone_const $ monotone_lam $ assume b, set.monotone_prod monotone_id monotone_const)
end
lemma prod_def : filter.prod f g = f.vmap prod.fst ⊓ g.vmap prod.snd :=
filter_eq $ set.ext $ assume s,
begin
simp [mem_prod_iff, mem_inf_sets],
exact ⟨assume ⟨t₁, ht₁, t₂, ht₂, h⟩,
⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, h, ⟨t₂, ht₂, subset.refl _⟩⟩,
assume ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, h, ⟨s₂, hs₂, hts₂⟩⟩,
⟨s₁, hs₁, s₂, hs₂, subset.trans (inter_subset_inter hts₁ hts₂) h⟩⟩
end
lemma prod_infi_left {f : ι → filter α} {g : filter β} (i : ι) :
filter.prod (⨅i, f i) g = (⨅i, filter.prod (f i) g) :=
by rw [prod_def, vmap_infi, infi_inf i]; simp [prod_def]
lemma prod_infi_right {f : filter α} {g : ι → filter β} (i : ι) :
filter.prod f (⨅i, g i) = (⨅i, filter.prod f (g i)) :=
by rw [prod_def, vmap_infi, inf_infi i]; simp [prod_def]
lemma mem_prod_same_iff {s : set (α×α)} :
s ∈ (filter.prod f f).sets ↔ (∃t∈f.sets, set.prod t t ⊆ s) :=
by rw [prod_same_eq, mem_lift'_iff]; exact set.monotone_prod monotone_id monotone_id
lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) :
filter.prod f₁ g₁ ≤ filter.prod f₂ g₂ :=
lift_mono hf $ assume s, lift'_mono hg $ le_refl _
lemma prod_comm : filter.prod f g = map (λp:β×α, (p.2, p.1)) (filter.prod g f) :=
eq.symm $ calc map (λp:β×α, (p.2, p.1)) (filter.prod g f) =
(g.lift $ λt, map (λp:β×α, (p.2, p.1)) (f.lift' $ λs, set.prod t s)) :
map_lift_eq $ assume a b h, lift'_mono (le_refl f) (assume t, set.prod_mono h (subset.refl t))
... = (g.lift $ λt, f.lift' $ λs, image (λp:β×α, (p.2, p.1)) (set.prod t s)) :
congr_arg (filter.lift g) $ funext $ assume s, map_lift'_eq $ assume a b h, set.prod_mono (subset.refl s) h
... = (g.lift $ λt, f.lift' $ λs, set.prod s t) : by simp [set.image_swap_prod]
... = filter.prod f g : lift_comm
lemma prod_lift_lift {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → filter β₁} {g₂ : set α₂ → filter β₂}
(hg₁ : monotone g₁) (hg₂ : monotone g₂) :
filter.prod (f₁.lift g₁) (f₂.lift g₂) = f₁.lift (λs, f₂.lift (λt, filter.prod (g₁ s) (g₂ t))) :=
begin
delta filter.prod,
rw [lift_assoc],
apply congr_arg, apply funext, intro x,
rw [lift_comm],
apply congr_arg, apply funext, intro y,
rw [lift'_lift_assoc],
exact hg₂,
exact hg₁
end
lemma prod_lift'_lift' {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → set β₁} {g₂ : set α₂ → set β₂}
(hg₁ : monotone g₁) (hg₂ : monotone g₂) :
filter.prod (f₁.lift' g₁) (f₂.lift' g₂) = f₁.lift (λs, f₂.lift' (λt, set.prod (g₁ s) (g₂ t))) :=
begin
delta filter.prod,
rw [lift_lift'_assoc],
apply congr_arg, apply funext, intro x,
rw [lift'_lift'_assoc],
exact hg₂,
exact set.monotone_prod monotone_const monotone_id,
exact hg₁,
exact (monotone_lift' monotone_const $ monotone_lam $
assume x, set.monotone_prod monotone_id monotone_const)
end
lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (filter.prod f g) f :=
assume s hs, (filter.prod f g).upwards_sets (prod_mem_prod hs univ_mem_sets) $
show set.prod s univ ⊆ preimage prod.fst s, by simp [set.prod, preimage] {contextual := tt}
lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (filter.prod f g) g :=
assume s hs, (filter.prod f g).upwards_sets (prod_mem_prod univ_mem_sets hs) $
show set.prod univ s ⊆ preimage prod.snd s, by simp [set.prod, preimage] {contextual := tt}
lemma tendsto_prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ}
(h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (filter.prod g h) :=
assume s hs,
let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in
f.upwards_sets (inter_mem_sets (h₁ hs₁) (h₂ hs₂)) $
calc preimage m₁ s₁ ∩ preimage m₂ s₂ ⊆ preimage (λx, (m₁ x, m₂ x)) (set.prod s₁ s₂) : λx ⟨h₁, h₂⟩, ⟨h₁, h₂⟩
... ⊆ preimage (λx, (m₁ x, m₂ x)) s : preimage_mono h
lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} :
filter.prod (map m₁ f₁) (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) :=
le_antisymm
(assume s hs,
let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in
filter.upwards_sets _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $
calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ :
set.prod_image_image_eq
... ⊆ _ : by rwa [image_subset_iff])
(tendsto_prod_mk (tendsto_compose tendsto_fst (le_refl _)) (tendsto_compose tendsto_snd (le_refl _)))
lemma prod_vmap_vmap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} :
filter.prod (vmap m₁ f₁) (vmap m₂ f₂) = vmap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) :=
have ∀s t, set.prod (preimage m₁ s) (preimage m₂ t) = preimage (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (set.prod s t),
from assume s t, rfl,
begin
rw [vmap_eq_lift', vmap_eq_lift', prod_lift'_lift'],
simp [this, filter.prod],
rw [vmap_lift_eq], tactic.swap, exact (monotone_lift' monotone_const $
monotone_lam $ assume t, set.monotone_prod monotone_id monotone_const),
apply congr_arg, apply funext, intro t',
dsimp [function.comp],
rw [vmap_lift'_eq],
exact set.monotone_prod monotone_const monotone_id,
exact monotone_preimage,
exact monotone_preimage
end
lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} :
filter.prod f₁ g₁ ⊓ filter.prod f₂ g₂ = filter.prod (f₁ ⊓ f₂) (g₁ ⊓ g₂) :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht,
begin
revert s hs t ht,
simp,
exact assume s s₁ hs₁ s₂ hs₂ hs t t₁ ht₁ t₂ ht₂ ht,
⟨set.prod s₁ t₁, prod_mem_prod hs₁ ht₁, set.prod s₂ t₂, prod_mem_prod hs₂ ht₂,
by rw [set.prod_inter_prod]; exact set.prod_mono hs ht⟩
end)
(le_inf (prod_mono inf_le_left inf_le_left) (prod_mono inf_le_right inf_le_right))
lemma prod_neq_bot {f : filter α} {g : filter β} :
filter.prod f g ≠ ⊥ ↔ (f ≠ ⊥ ∧ g ≠ ⊥) :=
calc filter.prod f g ≠ ⊥ ↔ (∀s∈f.sets, g.lift' (set.prod s) ≠ ⊥) :
begin
delta filter.prod,
rw [lift_neq_bot_iff],
exact (monotone_lift' monotone_const $ monotone_lam $ assume s, set.monotone_prod monotone_id monotone_const)
end
... ↔ (∀s∈f.sets, ∀t∈g.sets, s ≠ ∅ ∧ t ≠ ∅) :
begin
apply forall_congr, intro s,
apply forall_congr, intro hs,
rw [lift'_neq_bot_iff],
apply forall_congr, intro t,
apply forall_congr, intro ht,
rw [set.prod_neq_empty_iff],
exact set.monotone_prod monotone_const monotone_id
end
... ↔ (∀s∈f.sets, s ≠ ∅) ∧ (∀t∈g.sets, t ≠ ∅) :
⟨assume h, ⟨assume s hs, (h s hs univ univ_mem_sets).left,
assume t ht, (h univ univ_mem_sets t ht).right⟩,
assume ⟨h₁, h₂⟩ s hs t ht, ⟨h₁ s hs, h₂ t ht⟩⟩
... ↔ _ : by simp [forall_sets_neq_empty_iff_neq_bot]
lemma prod_principal_principal {s : set α} {t : set β} :
filter.prod (principal s) (principal t) = principal (set.prod s t) :=
begin
delta filter.prod,
rw [lift_principal, lift'_principal],
exact set.monotone_prod monotone_const monotone_id,
exact (monotone_lift' monotone_const $ monotone_lam $
assume s, set.monotone_prod monotone_id monotone_const)
end
end prod
lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ (f i).sets → s ∈ (⨅i, f i).sets :=
show (⨅i, f i) ≤ f i, from infi_le _ _
@[elab_as_eliminator]
lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ (infi f).sets) {p : set α → Prop}
(uni : p univ)
(ins : ∀{i s₁ s₂}, s₁ ∈ (f i).sets → p s₂ → p (s₁ ∩ s₂))
(upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s :=
begin
have hs' : s ∈ (complete_lattice.Inf {a : filter α | ∃ (i : ι), a = f i}).sets := hs,
rw [Inf_sets_eq_finite] at hs',
simp at hs',
cases hs' with is hs, cases hs with fin_is hs, cases hs with hs his,
induction fin_is generalizing s,
case finite.empty hs' s hs' hs {
simp at hs, subst hs, assumption },
case finite.insert fi is fi_ne_is fin_is ih fi_sub s hs' hs {
simp at hs,
cases hs with s₁ hs, cases hs with hs₁ hs, cases hs with s₂ hs, cases hs with hs hs₂,
have hi : ∃i, fi = f i := fi_sub (mem_insert _ _),
cases hi with i hi,
exact have hs₁ : s₁ ∈ (f i).sets, from hi ▸ hs₁,
have hs₂ : p s₂, from
have his : is ⊆ {x | ∃i, x = f i}, from assume i hi, fi_sub $ mem_insert_of_mem _ hi,
have infi f ≤ Inf is, from Inf_le_Inf his,
ih his (this hs₂) hs₂,
show p s, from upw hs $ ins hs₁ hs₂ }
end
lemma lift_infi {f : ι → filter α} {g : set α → filter β}
(hι : nonempty ι) (hg : ∀{s t}, g s ⊓ g t = g (s ∩ t)) : (infi f).lift g = (⨅i, (f i).lift g) :=
le_antisymm
(le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _))
(assume s,
have g_mono : monotone g,
from assume s t h, le_of_inf_eq $ eq.trans hg $ congr_arg g $ inter_eq_self_of_subset_left h,
have ∀t∈(infi f).sets, (⨅ (i : ι), filter.lift (f i) g) ≤ g t,
from assume t ht, infi_sets_induct ht
(let ⟨i⟩ := hι in infi_le_of_le i $ infi_le_of_le univ $ infi_le _ univ_mem_sets)
(assume i s₁ s₂ hs₁ hs₂,
@hg s₁ s₂ ▸ le_inf (infi_le_of_le i $ infi_le_of_le s₁ $ infi_le _ hs₁) hs₂)
(assume s₁ s₂ hs₁ hs₂, le_trans hs₂ $ g_mono hs₁),
by rw [lift_sets_eq g_mono]; simp; exact assume t hs ht, this t ht hs)
lemma lift_infi' {f : ι → filter α} {g : set α → filter β}
(hι : nonempty ι) (hf : directed (≤) f) (hg : monotone g) : (infi f).lift g = (⨅i, (f i).lift g) :=
le_antisymm
(le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _))
(assume s,
begin
rw [lift_sets_eq hg],
simp [infi_sets_eq hf hι],
exact assume t hs i ht, mem_infi_sets i $ mem_lift ht hs
end)
lemma lift'_infi {f : ι → filter α} {g : set α → set β}
(hι : nonempty ι) (hg : ∀{s t}, g s ∩ g t = g (s ∩ t)) : (infi f).lift' g = (⨅i, (f i).lift' g) :=
lift_infi hι $ by simp; apply assume s t, hg
lemma map_eq_vmap_of_inverse {f : filter α} {m : α → β} {n : β → α}
(h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = vmap n f :=
le_antisymm
(assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.upwards_sets ha $
calc a = preimage (n ∘ m) a : by simp [h₂, preimage_id]
... ⊆ preimage m b : preimage_mono h)
(assume b (hb : preimage m b ∈ f.sets),
⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp [h₁]; apply subset.refl⟩)
lemma map_swap_vmap_swap_eq {f : filter (α × β)} : prod.swap <$> f = vmap prod.swap f :=
map_eq_vmap_of_inverse prod.swap_swap_eq prod.swap_swap_eq
/- at_top and at_bot -/
def at_top [preorder α] : filter α := ⨅ a, principal {b | a ≤ b}
def at_bot [preorder α] : filter α := ⨅ a, principal {b | b ≤ a}
lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ (@at_top α _).sets :=
mem_infi_sets a $ subset.refl _
@[simp] lemma at_top_ne_bot [inhabited α] [semilattice_sup α] : (at_top : filter α) ≠ ⊥ :=
infi_neq_bot_of_directed (by apply_instance)
(assume a b, ⟨a ⊔ b, by simp {contextual := tt}⟩)
(assume a, by simp [principal_eq_bot_iff]; exact ne_empty_of_mem (le_refl a))
lemma mem_at_top_iff [inhabited α] [semilattice_sup α] {s : set α} :
s ∈ (at_top : filter α).sets ↔ (∃a:α, ∀b≥a, b ∈ s) :=
iff.intro
(assume h, infi_sets_induct h ⟨default α, by simp⟩
(assume a s₁ s₂ ha ⟨b, hb⟩, ⟨a ⊔ b,
assume c hc, ⟨ha $ le_trans le_sup_left hc, hb _ $ le_trans le_sup_right hc⟩⟩)
(assume s₁ s₂ h ⟨a, ha⟩, ⟨a, assume b hb, h $ ha _ hb⟩))
(assume ⟨a, h⟩, mem_infi_sets a $ assume x, h x)
lemma map_at_top_eq [inhabited α] [semilattice_sup α] {f : α → β} :
at_top.map f = (⨅a, principal $ f '' {a' | a ≤ a'}) :=
calc map f (⨅a, principal {a' | a ≤ a'}) = (⨅a, map f $ principal {a' | a ≤ a'}) :
map_infi_eq (assume a b, ⟨a ⊔ b, by simp {contextual := tt}⟩) ⟨default α⟩
... = (⨅a, principal $ f '' {a' | a ≤ a'}) : by simp
lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : ∀x, j (i x) = x) :
tendsto (λs:finset γ, s.image j) at_top at_top :=
tendsto_infi $ assume s, tendsto_infi' (s.image i) $ tendsto_principal_principal $
assume t (ht : s.image i ⊆ t),
calc s = (s.image i).image j :
by simp [finset.image_image, (∘), h]; exact finset.image_id.symm
... ⊆ t.image j : finset.image_subset_image ht
/- ultrafilter -/
section ultrafilter
open classical zorn
local attribute [instance] prop_decidable
variables {f g : filter α}
def ultrafilter (f : filter α) := f ≠ ⊥ ∧ ∀g, g ≠ ⊥ → g ≤ f → f ≤ g
lemma ultrafilter_pure {a : α} : ultrafilter (pure a) :=
⟨return_neq_bot,
assume g hg ha,
have {a} ∈ g.sets, by simp at ha; assumption,
show ∀s∈g.sets, {a} ⊆ s, from classical.by_contradiction $
begin
simp [classical.not_forall, not_imp],
exact assume s hna hs,
have {a} ∩ s ∈ g.sets, from inter_mem_sets ‹{a} ∈ g.sets› hs,
have ∅ ∈ g.sets, from g.upwards_sets this $
assume x ⟨hxa, hxs⟩, begin simp at hxa; simp [hxa] at hxs, exact hna hxs end,
have g = ⊥, from empty_in_sets_eq_bot.mp this,
hg this
end⟩
lemma ultrafilter_unique (hg : ultrafilter g) (hf : f ≠ ⊥) (h : f ≤ g) : f = g :=
le_antisymm h (hg.right _ hf h)
lemma exists_ultrafilter (h : f ≠ ⊥) : ∃u, u ≤ f ∧ ultrafilter u :=
let
τ := {f' // f' ≠ ⊥ ∧ f' ≤ f},
r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val,
⟨a, ha⟩ := inhabited_of_mem_sets h univ_mem_sets,
top : τ := ⟨f, h, le_refl f⟩,
sup : Π(c:set τ), chain c → τ :=
λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.val.val,
infi_neq_bot_of_directed ⟨a⟩
(directed_of_chain $ chain_insert hc $ assume ⟨b, _, hb⟩ _ _, or.inl hb)
(assume ⟨⟨a, ha, _⟩, _⟩, ha),
infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩
in
have ∀c (hc: chain c) a (ha : a ∈ c), r a (sup c hc),
from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _),
have (∃ (u : τ), ∀ (a : τ), r u a → r a u),
from zorn (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁),
let ⟨uτ, hmin⟩ := this in
⟨uτ.val, uτ.property.right, uτ.property.left, assume g hg₁ hg₂,
hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩
lemma le_of_ultrafilter {g : filter α} (hf : ultrafilter f) (h : f ⊓ g ≠ ⊥) :
f ≤ g :=
le_of_inf_eq $ ultrafilter_unique hf h inf_le_left
lemma mem_or_compl_mem_of_ultrafilter (hf : ultrafilter f) (s : set α) :
s ∈ f.sets ∨ - s ∈ f.sets :=
or_iff_not_imp_right.2 $ assume : - s ∉ f.sets,
have f ≤ principal s,
from le_of_ultrafilter hf $ assume h, this $ mem_sets_of_neq_bot $ by simp [*],
by simp at this; assumption
lemma mem_or_mem_of_ultrafilter {s t : set α} (hf : ultrafilter f) (h : s ∪ t ∈ f.sets) :
s ∈ f.sets ∨ t ∈ f.sets :=
(mem_or_compl_mem_of_ultrafilter hf s).imp_right
(assume : -s ∈ f.sets, f.upwards_sets (inter_mem_sets this h) $
assume x ⟨hnx, hx⟩, hx.resolve_left hnx)
lemma mem_of_finite_sUnion_ultrafilter {s : set (set α)} (hf : ultrafilter f) (hs : finite s)
: ⋃₀ s ∈ f.sets → ∃t∈s, t ∈ f.sets :=
begin
induction hs,
case finite.empty { simp [empty_in_sets_eq_bot, hf.left] },
case finite.insert t s' ht' hs' ih {
simp,
exact assume h, (mem_or_mem_of_ultrafilter hf h).elim
(assume : t ∈ f.sets, ⟨t, this, or.inl rfl⟩)
(assume h, let ⟨t, hts', ht⟩ := ih h in ⟨t, ht, or.inr hts'⟩) }
end
lemma mem_of_finite_Union_ultrafilter {is : set β} {s : β → set α}
(hf : ultrafilter f) (his : finite is) (h : (⋃i∈is, s i) ∈ f.sets) : ∃i∈is, s i ∈ f.sets :=
have his : finite (image s is), from finite_image his,
have h : (⋃₀ image s is) ∈ f.sets, from by simp [sUnion_image]; assumption,
let ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f.sets)⟩ := mem_of_finite_sUnion_ultrafilter hf his h in
⟨i, hi, h_eq.symm ▸ ht⟩
lemma ultrafilter_of_split {f : filter α} (hf : f ≠ ⊥) (h : ∀s, s ∈ f.sets ∨ - s ∈ f.sets) :
ultrafilter f :=
⟨hf, assume g hg g_le s hs, (h s).elim id $
assume : - s ∈ f.sets,
have s ∩ -s ∈ g.sets, from inter_mem_sets hs (g_le this),
by simp [empty_in_sets_eq_bot, hg] at this; contradiction⟩
lemma ultrafilter_map {f : filter α} {m : α → β} (h : ultrafilter f) : ultrafilter (map m f) :=
ultrafilter_of_split (by simp [map_eq_bot_iff, h.left]) $
assume s, show preimage m s ∈ f.sets ∨ - preimage m s ∈ f.sets,
from mem_or_compl_mem_of_ultrafilter h (preimage m s)
noncomputable def ultrafilter_of (f : filter α) : filter α :=
if h : f = ⊥ then ⊥ else epsilon (λu, u ≤ f ∧ ultrafilter u)
lemma ultrafilter_of_spec (h : f ≠ ⊥) : ultrafilter_of f ≤ f ∧ ultrafilter (ultrafilter_of f) :=
begin
have h' := epsilon_spec (exists_ultrafilter h),
simp [ultrafilter_of, dif_neg, h],
simp at h',
assumption
end
lemma ultrafilter_of_le : ultrafilter_of f ≤ f :=
if h : f = ⊥ then by simp [ultrafilter_of, dif_pos, h]; exact le_refl _
else (ultrafilter_of_spec h).left
lemma ultrafilter_ultrafilter_of (h : f ≠ ⊥) : ultrafilter (ultrafilter_of f) :=
(ultrafilter_of_spec h).right
lemma ultrafilter_of_ultrafilter (h : ultrafilter f) : ultrafilter_of f = f :=
ultrafilter_unique h (ultrafilter_ultrafilter_of h.left).left ultrafilter_of_le
end ultrafilter
end filter
|
00d242a31722df920c372b9fd08655d34c4b82f7
|
57c233acf9386e610d99ed20ef139c5f97504ba3
|
/src/topology/order.lean
|
bd6fc6d82cdd79960281d7e5edbec4eb9885560f
|
[
"Apache-2.0"
] |
permissive
|
robertylewis/mathlib
|
3d16e3e6daf5ddde182473e03a1b601d2810952c
|
1d13f5b932f5e40a8308e3840f96fc882fae01f0
|
refs/heads/master
| 1,651,379,945,369
| 1,644,276,960,000
| 1,644,276,960,000
| 98,875,504
| 0
| 0
|
Apache-2.0
| 1,644,253,514,000
| 1,501,495,700,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 36,838
|
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
-/
import topology.tactic
/-!
# Ordering on topologies and (co)induced topologies
Topologies on a fixed type `α` are ordered, by reverse inclusion.
That is, for topologies `t₁` and `t₂` on `α`, we write `t₁ ≤ t₂`
if every set open in `t₂` is also open in `t₁`.
(One also calls `t₁` finer than `t₂`, and `t₂` coarser than `t₁`.)
Any function `f : α → β` induces
`induced f : topological_space β → topological_space α`
and `coinduced f : topological_space α → topological_space β`.
Continuity, the ordering on topologies and (co)induced topologies are
related as follows:
* The identity map (α, t₁) → (α, t₂) is continuous iff t₁ ≤ t₂.
* A map f : (α, t) → (β, u) is continuous
iff t ≤ induced f u (`continuous_iff_le_induced`)
iff coinduced f t ≤ u (`continuous_iff_coinduced_le`).
Topologies on α form a complete lattice, with ⊥ the discrete topology
and ⊤ the indiscrete topology.
For a function f : α → β, (coinduced f, induced f) is a Galois connection
between topologies on α and topologies on β.
## Implementation notes
There is a Galois insertion between topologies on α (with the inclusion ordering)
and all collections of sets in α. The complete lattice structure on topologies
on α is defined as the reverse of the one obtained via this Galois insertion.
## Tags
finer, coarser, induced topology, coinduced topology
-/
open set filter classical
open_locale classical topological_space filter
universes u v w
namespace topological_space
variables {α : Type u}
/-- The open sets of the least topology containing a collection of basic sets. -/
inductive generate_open (g : set (set α)) : set α → Prop
| basic : ∀s∈g, generate_open s
| univ : generate_open univ
| inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t)
| sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k)
/-- The smallest topological space containing the collection `g` of basic sets -/
def generate_from (g : set (set α)) : topological_space α :=
{ is_open := generate_open g,
is_open_univ := generate_open.univ,
is_open_inter := generate_open.inter,
is_open_sUnion := generate_open.sUnion }
lemma nhds_generate_from {g : set (set α)} {a : α} :
@nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, 𝓟 s) :=
by rw nhds_def; exact le_antisymm
(infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩)
(le_infi $ assume s, le_infi $ assume ⟨as, hs⟩,
begin
revert as, clear_, induction hs,
case generate_open.basic : s hs
{ exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ },
case generate_open.univ
{ rw [principal_univ],
exact assume _, le_top },
case generate_open.inter : s t hs' ht' hs ht
{ exact assume ⟨has, hat⟩, calc _ ≤ 𝓟 s ⊓ 𝓟 t : le_inf (hs has) (ht hat)
... = _ : inf_principal },
case generate_open.sUnion : k hk' hk
{ exact λ ⟨t, htk, hat⟩, calc _ ≤ 𝓟 t : hk t htk hat
... ≤ _ : le_principal_iff.2 $ subset_sUnion_of_mem htk }
end)
lemma tendsto_nhds_generate_from {β : Type*} {m : α → β} {f : filter α} {g : set (set β)} {b : β}
(h : ∀s∈g, b ∈ s → m ⁻¹' s ∈ f) : tendsto m f (@nhds β (generate_from g) b) :=
by rw [nhds_generate_from]; exact
(tendsto_infi.2 $ assume s, tendsto_infi.2 $ assume ⟨hbs, hsg⟩, tendsto_principal.2 $ h s hsg hbs)
/-- Construct a topology on α given the filter of neighborhoods of each point of α. -/
protected def mk_of_nhds (n : α → filter α) : topological_space α :=
{ is_open := λs, ∀a∈s, s ∈ n a,
is_open_univ := assume x h, univ_mem,
is_open_inter := assume s t hs ht x ⟨hxs, hxt⟩, inter_mem (hs x hxs) (ht x hxt),
is_open_sUnion := assume s hs a ⟨x, hx, hxa⟩,
mem_of_superset (hs x hx _ hxa) (set.subset_sUnion_of_mem hx) }
lemma nhds_mk_of_nhds (n : α → filter α) (a : α)
(h₀ : pure ≤ n) (h₁ : ∀{a s}, s ∈ n a → ∃ t ∈ n a, t ⊆ s ∧ ∀a' ∈ t, s ∈ n a') :
@nhds α (topological_space.mk_of_nhds n) a = n a :=
begin
letI := topological_space.mk_of_nhds n,
refine le_antisymm (assume s hs, _) (assume s hs, _),
{ have h₀ : {b | s ∈ n b} ⊆ s := assume b hb, mem_pure.1 $ h₀ b hb,
have h₁ : {b | s ∈ n b} ∈ 𝓝 a,
{ refine is_open.mem_nhds (assume b (hb : s ∈ n b), _) hs,
rcases h₁ hb with ⟨t, ht, hts, h⟩,
exact mem_of_superset ht h },
exact mem_of_superset h₁ h₀ },
{ rcases (@mem_nhds_iff α (topological_space.mk_of_nhds n) _ _).1 hs with ⟨t, hts, ht, hat⟩,
exact (n a).sets_of_superset (ht _ hat) hts },
end
lemma nhds_mk_of_nhds_filter_basis (B : α → filter_basis α) (a : α) (h₀ : ∀ x (n ∈ B x), x ∈ n)
(h₁ : ∀ x (n ∈ B x), ∃ n₁ ∈ B x, n₁ ⊆ n ∧ ∀ x' ∈ n₁, ∃ n₂ ∈ B x', n₂ ⊆ n) :
@nhds α (topological_space.mk_of_nhds (λ x, (B x).filter)) a = (B a).filter :=
begin
rw topological_space.nhds_mk_of_nhds;
intros x n hn;
obtain ⟨m, hm₁, hm₂⟩ := (B x).mem_filter_iff.mp hn,
{ exact hm₂ (h₀ _ _ hm₁), },
{ obtain ⟨n₁, hn₁, hn₂, hn₃⟩ := h₁ x m hm₁,
refine ⟨n₁, (B x).mem_filter_of_mem hn₁, hn₂.trans hm₂, λ x' hx', (B x').mem_filter_iff.mp _⟩,
obtain ⟨n₂, hn₄, hn₅⟩ := hn₃ x' hx',
exact ⟨n₂, hn₄, hn₅.trans hm₂⟩, },
end
end topological_space
section lattice
variables {α : Type u} {β : Type v}
/-- The inclusion ordering on topologies on α. We use it to get a complete
lattice instance via the Galois insertion method, but the partial order
that we will eventually impose on `topological_space α` is the reverse one. -/
def tmp_order : partial_order (topological_space α) :=
{ le := λt s, t.is_open ≤ s.is_open,
le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂,
le_refl := assume t, le_refl t.is_open,
le_trans := assume a b c h₁ h₂, @le_trans _ _ a.is_open b.is_open c.is_open h₁ h₂ }
local attribute [instance] tmp_order
/- We'll later restate this lemma in terms of the correct order on `topological_space α`. -/
private lemma generate_from_le_iff_subset_is_open {g : set (set α)} {t : topological_space α} :
topological_space.generate_from g ≤ t ↔ g ⊆ {s | t.is_open s} :=
iff.intro
(assume ht s hs, ht _ $ topological_space.generate_open.basic s hs)
(assume hg s hs, hs.rec_on (assume v hv, hg hv)
t.is_open_univ (assume u v _ _, t.is_open_inter u v) (assume k _, t.is_open_sUnion k))
/-- If `s` equals the collection of open sets in the topology it generates,
then `s` defines a topology. -/
protected def mk_of_closure (s : set (set α))
(hs : {u | (topological_space.generate_from s).is_open u} = s) : topological_space α :=
{ is_open := λu, u ∈ s,
is_open_univ := hs ▸ topological_space.generate_open.univ,
is_open_inter := hs ▸ topological_space.generate_open.inter,
is_open_sUnion := hs ▸ topological_space.generate_open.sUnion }
lemma mk_of_closure_sets {s : set (set α)}
{hs : {u | (topological_space.generate_from s).is_open u} = s} :
mk_of_closure s hs = topological_space.generate_from s :=
topological_space_eq hs.symm
/-- The Galois insertion between `set (set α)` and `topological_space α` whose lower part
sends a collection of subsets of α to the topology they generate, and whose upper part
sends a topology to its collection of open subsets. -/
def gi_generate_from (α : Type*) :
galois_insertion topological_space.generate_from (λt:topological_space α, {s | t.is_open s}) :=
{ gc := assume g t, generate_from_le_iff_subset_is_open,
le_l_u := assume ts s hs, topological_space.generate_open.basic s hs,
choice := λg hg, mk_of_closure g
(subset.antisymm hg $ generate_from_le_iff_subset_is_open.1 $ le_rfl),
choice_eq := assume s hs, mk_of_closure_sets }
lemma generate_from_mono {α} {g₁ g₂ : set (set α)} (h : g₁ ⊆ g₂) :
topological_space.generate_from g₁ ≤ topological_space.generate_from g₂ :=
(gi_generate_from _).gc.monotone_l h
lemma generate_from_set_of_is_open (t : topological_space α) :
topological_space.generate_from {s | t.is_open s} = t :=
(gi_generate_from α).l_u_eq t
lemma left_inverse_generate_from :
function.left_inverse topological_space.generate_from
(λ t : topological_space α, {s | t.is_open s}) :=
(gi_generate_from α).left_inverse_l_u
lemma generate_from_surjective :
function.surjective (topological_space.generate_from : set (set α) → topological_space α) :=
(gi_generate_from α).l_surjective
lemma set_of_is_open_injective :
function.injective (λ t : topological_space α, {s | t.is_open s}) :=
(gi_generate_from α).u_injective
/-- The "temporary" order `tmp_order` on `topological_space α`, i.e. the inclusion order, is a
complete lattice. (Note that later `topological_space α` will equipped with the dual order to
`tmp_order`). -/
def tmp_complete_lattice {α : Type u} : complete_lattice (topological_space α) :=
(gi_generate_from α).lift_complete_lattice
instance : has_le (topological_space α) :=
{ le := λ t s, s.is_open ≤ t.is_open }
protected lemma topological_space.le_def {α} {t s : topological_space α} :
t ≤ s ↔ s.is_open ≤ t.is_open := iff.rfl
/-- The ordering on topologies on the type `α`.
`t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/
instance : partial_order (topological_space α) :=
{ le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₂ h₁,
le_refl := assume t, le_refl t.is_open,
le_trans := assume a b c h₁ h₂, topological_space.le_def.mpr (le_trans h₂ h₁),
..topological_space.has_le }
lemma le_generate_from_iff_subset_is_open {g : set (set α)} {t : topological_space α} :
t ≤ topological_space.generate_from g ↔ g ⊆ {s | t.is_open s} :=
generate_from_le_iff_subset_is_open
/-- Topologies on `α` form a complete lattice, with `⊥` the discrete topology
and `⊤` the indiscrete topology. The infimum of a collection of topologies
is the topology generated by all their open sets, while the supremum is the
topology whose open sets are those sets open in every member of the collection. -/
instance : complete_lattice (topological_space α) :=
@order_dual.complete_lattice _ tmp_complete_lattice
lemma is_open_implies_is_open_iff {a b : topological_space α} :
(∀ s, a.is_open s → b.is_open s) ↔ b ≤ a :=
@galois_insertion.u_le_u_iff _ (order_dual (topological_space α)) _ _ _ _ (gi_generate_from α) a b
/-- A topological space is discrete if every set is open, that is,
its topology equals the discrete topology `⊥`. -/
class discrete_topology (α : Type*) [t : topological_space α] : Prop :=
(eq_bot [] : t = ⊥)
@[priority 100]
instance discrete_topology_bot (α : Type*) : @discrete_topology α ⊥ :=
{ eq_bot := rfl }
@[simp] lemma is_open_discrete [topological_space α] [discrete_topology α] (s : set α) :
is_open s :=
(discrete_topology.eq_bot α).symm ▸ trivial
@[simp] lemma is_closed_discrete [topological_space α] [discrete_topology α] (s : set α) :
is_closed s :=
is_open_compl_iff.1 $ (discrete_topology.eq_bot α).symm ▸ trivial
@[nontriviality]
lemma continuous_of_discrete_topology [topological_space α] [discrete_topology α]
[topological_space β] {f : α → β} : continuous f :=
continuous_def.2 $ λs hs, is_open_discrete _
lemma nhds_bot (α : Type*) : (@nhds α ⊥) = pure :=
begin
refine le_antisymm _ (@pure_le_nhds α ⊥),
assume a s hs,
exact @is_open.mem_nhds α ⊥ a s trivial hs
end
lemma nhds_discrete (α : Type*) [topological_space α] [discrete_topology α] : (@nhds α _) = pure :=
(discrete_topology.eq_bot α).symm ▸ nhds_bot α
lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x ≤ @nhds α t₂ x) :
t₁ ≤ t₂ :=
assume s, show @is_open α t₂ s → @is_open α t₁ s,
by { simp only [is_open_iff_nhds, le_principal_iff], exact assume hs a ha, h _ $ hs _ ha }
lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x = @nhds α t₂ x) :
t₁ = t₂ :=
le_antisymm
(le_of_nhds_le_nhds $ assume x, le_of_eq $ h x)
(le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm)
lemma eq_bot_of_singletons_open {t : topological_space α} (h : ∀ x, t.is_open {x}) : t = ⊥ :=
bot_unique $ λ s hs, bUnion_of_singleton s ▸ is_open_bUnion (λ x _, h x)
lemma forall_open_iff_discrete {X : Type*} [topological_space X] :
(∀ s : set X, is_open s) ↔ discrete_topology X :=
⟨λ h, ⟨by { ext U , show is_open U ↔ true, simp [h U] }⟩, λ a, @is_open_discrete _ _ a⟩
lemma singletons_open_iff_discrete {X : Type*} [topological_space X] :
(∀ a : X, is_open ({a} : set X)) ↔ discrete_topology X :=
⟨λ h, ⟨eq_bot_of_singletons_open h⟩, λ a _, @is_open_discrete _ _ a _⟩
end lattice
section galois_connection
variables {α : Type*} {β : Type*} {γ : Type*}
/-- Given `f : α → β` and a topology on `β`, the induced topology on `α` is the collection of
sets that are preimages of some open set in `β`. This is the coarsest topology that
makes `f` continuous. -/
def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) :
topological_space α :=
{ is_open := λs, ∃s', t.is_open s' ∧ f ⁻¹' s' = s,
is_open_univ := ⟨univ, t.is_open_univ, preimage_univ⟩,
is_open_inter := by rintro s₁ s₂ ⟨s'₁, hs₁, rfl⟩ ⟨s'₂, hs₂, rfl⟩;
exact ⟨s'₁ ∩ s'₂, t.is_open_inter _ _ hs₁ hs₂, preimage_inter⟩,
is_open_sUnion := assume s h,
begin
simp only [classical.skolem] at h,
cases h with f hf,
apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h),
simp only [sUnion_eq_bUnion, preimage_Union, (λx h, (hf x h).right)], refine ⟨_, rfl⟩,
exact (@is_open_Union β _ t _ $ assume i,
show is_open (⋃h, f i h), from @is_open_Union β _ t _ $ assume h, (hf i h).left)
end }
lemma is_open_induced_iff [t : topological_space β] {s : set α} {f : α → β} :
@is_open α (t.induced f) s ↔ (∃t, is_open t ∧ f ⁻¹' t = s) :=
iff.rfl
lemma is_open_induced_iff' [t : topological_space β] {s : set α} {f : α → β} :
(t.induced f).is_open s ↔ (∃t, is_open t ∧ f ⁻¹' t = s) :=
iff.rfl
lemma is_closed_induced_iff [t : topological_space β] {s : set α} {f : α → β} :
@is_closed α (t.induced f) s ↔ (∃t, is_closed t ∧ f ⁻¹' t = s) :=
begin
simp only [← is_open_compl_iff, is_open_induced_iff],
exact ⟨λ ⟨t, ht, heq⟩, ⟨tᶜ, by rwa compl_compl, by simp [preimage_compl, heq, compl_compl]⟩,
λ ⟨t, ht, heq⟩, ⟨tᶜ, ht, by simp only [preimage_compl, heq.symm]⟩⟩
end
/-- Given `f : α → β` and a topology on `α`, the coinduced topology on `β` is defined
such that `s:set β` is open if the preimage of `s` is open. This is the finest topology that
makes `f` continuous. -/
def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) :
topological_space β :=
{ is_open := λs, t.is_open (f ⁻¹' s),
is_open_univ := by rw preimage_univ; exact t.is_open_univ,
is_open_inter := assume s₁ s₂ h₁ h₂, by rw preimage_inter; exact t.is_open_inter _ _ h₁ h₂,
is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i,
show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from
@is_open_Union _ _ t _ $ assume hi, h i hi) }
lemma is_open_coinduced {t : topological_space α} {s : set β} {f : α → β} :
@is_open β (topological_space.coinduced f t) s ↔ is_open (f ⁻¹' s) :=
iff.rfl
lemma preimage_nhds_coinduced [topological_space α] {π : α → β} {s : set β}
{a : α} (hs : s ∈ @nhds β (topological_space.coinduced π ‹_›) (π a)) : π ⁻¹' s ∈ 𝓝 a :=
begin
letI := topological_space.coinduced π ‹_›,
rcases mem_nhds_iff.mp hs with ⟨V, hVs, V_op, mem_V⟩,
exact mem_nhds_iff.mpr ⟨π ⁻¹' V, set.preimage_mono hVs, V_op, mem_V⟩
end
variables {t t₁ t₂ : topological_space α} {t' : topological_space β} {f : α → β} {g : β → α}
lemma continuous.coinduced_le (h : @continuous α β t t' f) :
t.coinduced f ≤ t' :=
λ s hs, (continuous_def.1 h s hs : _)
lemma coinduced_le_iff_le_induced {f : α → β} {tα : topological_space α}
{tβ : topological_space β} :
tα.coinduced f ≤ tβ ↔ tα ≤ tβ.induced f :=
iff.intro
(assume h s ⟨t, ht, hst⟩, hst ▸ h _ ht)
(assume h s hs, show tα.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩)
lemma continuous.le_induced (h : @continuous α β t t' f) :
t ≤ t'.induced f :=
coinduced_le_iff_le_induced.1 h.coinduced_le
lemma gc_coinduced_induced (f : α → β) :
galois_connection (topological_space.coinduced f) (topological_space.induced f) :=
assume f g, coinduced_le_iff_le_induced
lemma induced_mono (h : t₁ ≤ t₂) : t₁.induced g ≤ t₂.induced g :=
(gc_coinduced_induced g).monotone_u h
lemma coinduced_mono (h : t₁ ≤ t₂) : t₁.coinduced f ≤ t₂.coinduced f :=
(gc_coinduced_induced f).monotone_l h
@[simp] lemma induced_top : (⊤ : topological_space α).induced g = ⊤ :=
(gc_coinduced_induced g).u_top
@[simp] lemma induced_inf : (t₁ ⊓ t₂).induced g = t₁.induced g ⊓ t₂.induced g :=
(gc_coinduced_induced g).u_inf
@[simp] lemma induced_infi {ι : Sort w} {t : ι → topological_space α} :
(⨅i, t i).induced g = (⨅i, (t i).induced g) :=
(gc_coinduced_induced g).u_infi
@[simp] lemma coinduced_bot : (⊥ : topological_space α).coinduced f = ⊥ :=
(gc_coinduced_induced f).l_bot
@[simp] lemma coinduced_sup : (t₁ ⊔ t₂).coinduced f = t₁.coinduced f ⊔ t₂.coinduced f :=
(gc_coinduced_induced f).l_sup
@[simp] lemma coinduced_supr {ι : Sort w} {t : ι → topological_space α} :
(⨆i, t i).coinduced f = (⨆i, (t i).coinduced f) :=
(gc_coinduced_induced f).l_supr
lemma induced_id [t : topological_space α] : t.induced id = t :=
topological_space_eq $ funext $ assume s, propext $
⟨assume ⟨s', hs, h⟩, h ▸ hs, assume hs, ⟨s, hs, rfl⟩⟩
lemma induced_compose [tγ : topological_space γ]
{f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) :=
topological_space_eq $ funext $ assume s, propext $
⟨assume ⟨s', ⟨s, hs, h₂⟩, h₁⟩, h₁ ▸ h₂ ▸ ⟨s, hs, rfl⟩,
assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩
lemma induced_const [t : topological_space α] {x : α} :
t.induced (λ y : β, x) = ⊤ :=
le_antisymm le_top (@continuous_const β α ⊤ t x).le_induced
lemma coinduced_id [t : topological_space α] : t.coinduced id = t :=
topological_space_eq rfl
lemma coinduced_compose [tα : topological_space α]
{f : α → β} {g : β → γ} : (tα.coinduced f).coinduced g = tα.coinduced (g ∘ f) :=
topological_space_eq rfl
end galois_connection
/- constructions using the complete lattice structure -/
section constructions
open topological_space
variables {α : Type u} {β : Type v}
instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) :=
⟨⊤⟩
@[priority 100]
instance subsingleton.unique_topological_space [subsingleton α] :
unique (topological_space α) :=
{ default := ⊥,
uniq := λ t, eq_bot_of_singletons_open $ λ x, subsingleton.set_cases
(@is_open_empty _ t) (@is_open_univ _ t) ({x} : set α) }
@[priority 100]
instance subsingleton.discrete_topology [t : topological_space α] [subsingleton α] :
discrete_topology α :=
⟨unique.eq_default t⟩
instance : topological_space empty := ⊥
instance : discrete_topology empty := ⟨rfl⟩
instance : topological_space pempty := ⊥
instance : discrete_topology pempty := ⟨rfl⟩
instance : topological_space punit := ⊥
instance : discrete_topology punit := ⟨rfl⟩
instance : topological_space bool := ⊥
instance : discrete_topology bool := ⟨rfl⟩
instance : topological_space ℕ := ⊥
instance : discrete_topology ℕ := ⟨rfl⟩
instance : topological_space ℤ := ⊥
instance : discrete_topology ℤ := ⟨rfl⟩
instance sierpinski_space : topological_space Prop :=
generate_from {{true}}
lemma le_generate_from {t : topological_space α} { g : set (set α) } (h : ∀s∈g, is_open s) :
t ≤ generate_from g :=
le_generate_from_iff_subset_is_open.2 h
lemma induced_generate_from_eq {α β} {b : set (set β)} {f : α → β} :
(generate_from b).induced f = topological_space.generate_from (preimage f '' b) :=
le_antisymm
(le_generate_from $ ball_image_iff.2 $ assume s hs, ⟨s, generate_open.basic _ hs, rfl⟩)
(coinduced_le_iff_le_induced.1 $ le_generate_from $ assume s hs,
generate_open.basic _ $ mem_image_of_mem _ hs)
lemma le_induced_generate_from {α β} [t : topological_space α] {b : set (set β)}
{f : α → β} (h : ∀ (a : set β), a ∈ b → is_open (f ⁻¹' a)) : t ≤ induced f (generate_from b) :=
begin
rw induced_generate_from_eq,
apply le_generate_from,
simp only [mem_image, and_imp, forall_apply_eq_imp_iff₂, exists_imp_distrib],
exact h,
end
/-- This construction is left adjoint to the operation sending a topology on `α`
to its neighborhood filter at a fixed point `a : α`. -/
def nhds_adjoint (a : α) (f : filter α) : topological_space α :=
{ is_open := λs, a ∈ s → s ∈ f,
is_open_univ := assume s, univ_mem,
is_open_inter := assume s t hs ht ⟨has, hat⟩, inter_mem (hs has) (ht hat),
is_open_sUnion := assume k hk ⟨u, hu, hau⟩, mem_of_superset (hk u hu hau)
(subset_sUnion_of_mem hu) }
lemma gc_nhds (a : α) :
galois_connection (nhds_adjoint a) (λt, @nhds α t a) :=
assume f t, by { rw le_nhds_iff, exact ⟨λ H s hs has, H _ has hs, λ H s has hs, H _ hs has⟩ }
lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) :
@nhds α t₁ a ≤ @nhds α t₂ a := (gc_nhds a).monotone_u h
lemma le_iff_nhds {α : Type*} (t t' : topological_space α) :
t ≤ t' ↔ ∀ x, @nhds α t x ≤ @nhds α t' x :=
⟨λ h x, nhds_mono h, le_of_nhds_le_nhds⟩
lemma nhds_adjoint_nhds {α : Type*} (a : α) (f : filter α) :
@nhds α (nhds_adjoint a f) a = pure a ⊔ f :=
begin
ext U,
rw mem_nhds_iff,
split,
{ rintros ⟨t, htU, ht, hat⟩,
exact ⟨htU hat, mem_of_superset (ht hat) htU⟩},
{ rintros ⟨haU, hU⟩,
exact ⟨U, subset.rfl, λ h, hU, haU⟩ }
end
lemma nhds_adjoint_nhds_of_ne {α : Type*} (a : α) (f : filter α) {b : α} (h : b ≠ a) :
@nhds α (nhds_adjoint a f) b = pure b :=
begin
apply le_antisymm,
{ intros U hU,
rw mem_nhds_iff,
use {b},
simp only [and_true, singleton_subset_iff, mem_singleton],
refine ⟨hU, λ ha, (h.symm ha).elim⟩ },
{ exact @pure_le_nhds α (nhds_adjoint a f) b },
end
lemma is_open_singleton_nhds_adjoint {α : Type*} {a b : α} (f : filter α) (hb : b ≠ a) :
@is_open α (nhds_adjoint a f) {b} :=
begin
rw is_open_singleton_iff_nhds_eq_pure,
exact nhds_adjoint_nhds_of_ne a f hb
end
lemma le_nhds_adjoint_iff' {α : Type*} (a : α) (f : filter α) (t : topological_space α) :
t ≤ nhds_adjoint a f ↔ @nhds α t a ≤ pure a ⊔ f ∧ ∀ b ≠ a, @nhds α t b = pure b :=
begin
rw le_iff_nhds,
split,
{ intros h,
split,
{ specialize h a,
rwa nhds_adjoint_nhds at h },
{ intros b hb,
apply le_antisymm _ (pure_le_nhds b),
specialize h b,
rwa nhds_adjoint_nhds_of_ne a f hb at h } },
{ rintros ⟨h, h'⟩ b,
by_cases hb : b = a,
{ rwa [hb, nhds_adjoint_nhds] },
{ simp [nhds_adjoint_nhds_of_ne a f hb, h' b hb] } }
end
lemma le_nhds_adjoint_iff {α : Type*} (a : α) (f : filter α) (t : topological_space α) :
t ≤ nhds_adjoint a f ↔ (@nhds α t a ≤ pure a ⊔ f ∧ ∀ b, b ≠ a → t.is_open {b}) :=
begin
change _ ↔ _ ∧ ∀ (b : α), b ≠ a → is_open {b},
rw [le_nhds_adjoint_iff', and.congr_right_iff],
apply λ h, forall_congr (λ b, _),
rw @is_open_singleton_iff_nhds_eq_pure α t b
end
lemma nhds_infi {ι : Sort*} {t : ι → topological_space α} {a : α} :
@nhds α (infi t) a = (⨅i, @nhds α (t i) a) := (gc_nhds a).u_infi
lemma nhds_Inf {s : set (topological_space α)} {a : α} :
@nhds α (Inf s) a = (⨅t∈s, @nhds α t a) := (gc_nhds a).u_Inf
lemma nhds_inf {t₁ t₂ : topological_space α} {a : α} :
@nhds α (t₁ ⊓ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := (gc_nhds a).u_inf
lemma nhds_top {a : α} : @nhds α ⊤ a = ⊤ := (gc_nhds a).u_top
local notation `cont` := @continuous _ _
local notation `tspace` := topological_space
open topological_space
variables {γ : Type*} {f : α → β} {ι : Sort*}
lemma continuous_iff_coinduced_le {t₁ : tspace α} {t₂ : tspace β} :
cont t₁ t₂ f ↔ coinduced f t₁ ≤ t₂ :=
continuous_def.trans iff.rfl
lemma continuous_iff_le_induced {t₁ : tspace α} {t₂ : tspace β} :
cont t₁ t₂ f ↔ t₁ ≤ induced f t₂ :=
iff.trans continuous_iff_coinduced_le (gc_coinduced_induced f _ _)
theorem continuous_generated_from {t : tspace α} {b : set (set β)}
(h : ∀s∈b, is_open (f ⁻¹' s)) : cont t (generate_from b) f :=
continuous_iff_coinduced_le.2 $ le_generate_from h
@[continuity]
lemma continuous_induced_dom {t : tspace β} : cont (induced f t) t f :=
by { rw continuous_def, assume s h, exact ⟨_, h, rfl⟩ }
lemma continuous_induced_rng {g : γ → α} {t₂ : tspace β} {t₁ : tspace γ}
(h : cont t₁ t₂ (f ∘ g)) : cont t₁ (induced f t₂) g :=
begin
rw continuous_def,
rintros s ⟨t, ht, s_eq⟩,
simpa [← s_eq] using continuous_def.1 h t ht,
end
lemma continuous_induced_rng' [topological_space α] [topological_space β] [topological_space γ]
{g : γ → α} (f : α → β) (H : ‹topological_space α› = ‹topological_space β›.induced f)
(h : continuous (f ∘ g)) : continuous g :=
H.symm ▸ continuous_induced_rng h
lemma continuous_coinduced_rng {t : tspace α} : cont t (coinduced f t) f :=
by { rw continuous_def, assume s h, exact h }
lemma continuous_coinduced_dom {g : β → γ} {t₁ : tspace α} {t₂ : tspace γ}
(h : cont t₁ t₂ (g ∘ f)) : cont (coinduced f t₁) t₂ g :=
begin
rw continuous_def at h ⊢,
assume s hs,
exact h _ hs
end
lemma continuous_le_dom {t₁ t₂ : tspace α} {t₃ : tspace β}
(h₁ : t₂ ≤ t₁) (h₂ : cont t₁ t₃ f) : cont t₂ t₃ f :=
begin
rw continuous_def at h₂ ⊢,
assume s h,
exact h₁ _ (h₂ s h)
end
lemma continuous_le_rng {t₁ : tspace α} {t₂ t₃ : tspace β}
(h₁ : t₂ ≤ t₃) (h₂ : cont t₁ t₂ f) : cont t₁ t₃ f :=
begin
rw continuous_def at h₂ ⊢,
assume s h,
exact h₂ s (h₁ s h)
end
lemma continuous_sup_dom {t₁ t₂ : tspace α} {t₃ : tspace β}
(h₁ : cont t₁ t₃ f) (h₂ : cont t₂ t₃ f) : cont (t₁ ⊔ t₂) t₃ f :=
begin
rw continuous_def at h₁ h₂ ⊢,
assume s h,
exact ⟨h₁ s h, h₂ s h⟩
end
lemma continuous_sup_rng_left {t₁ : tspace α} {t₃ t₂ : tspace β} :
cont t₁ t₂ f → cont t₁ (t₂ ⊔ t₃) f :=
continuous_le_rng le_sup_left
lemma continuous_sup_rng_right {t₁ : tspace α} {t₃ t₂ : tspace β} :
cont t₁ t₃ f → cont t₁ (t₂ ⊔ t₃) f :=
continuous_le_rng le_sup_right
lemma continuous_Sup_dom {t₁ : set (tspace α)} {t₂ : tspace β}
(h : ∀t∈t₁, cont t t₂ f) : cont (Sup t₁) t₂ f :=
continuous_iff_le_induced.2 $ Sup_le $ assume t ht, continuous_iff_le_induced.1 $ h t ht
lemma continuous_Sup_rng {t₁ : tspace α} {t₂ : set (tspace β)} {t : tspace β}
(h₁ : t ∈ t₂) (hf : cont t₁ t f) : cont t₁ (Sup t₂) f :=
continuous_iff_coinduced_le.2 $ le_Sup_of_le h₁ $ continuous_iff_coinduced_le.1 hf
lemma continuous_supr_dom {t₁ : ι → tspace α} {t₂ : tspace β}
(h : ∀i, cont (t₁ i) t₂ f) : cont (supr t₁) t₂ f :=
continuous_Sup_dom $ assume t ⟨i, (t_eq : t₁ i = t)⟩, t_eq ▸ h i
lemma continuous_supr_rng {t₁ : tspace α} {t₂ : ι → tspace β} {i : ι}
(h : cont t₁ (t₂ i) f) : cont t₁ (supr t₂) f :=
continuous_Sup_rng ⟨i, rfl⟩ h
lemma continuous_inf_rng {t₁ : tspace α} {t₂ t₃ : tspace β}
(h₁ : cont t₁ t₂ f) (h₂ : cont t₁ t₃ f) : cont t₁ (t₂ ⊓ t₃) f :=
continuous_iff_coinduced_le.2 $ le_inf
(continuous_iff_coinduced_le.1 h₁)
(continuous_iff_coinduced_le.1 h₂)
lemma continuous_inf_dom_left {t₁ t₂ : tspace α} {t₃ : tspace β} :
cont t₁ t₃ f → cont (t₁ ⊓ t₂) t₃ f :=
continuous_le_dom inf_le_left
lemma continuous_inf_dom_right {t₁ t₂ : tspace α} {t₃ : tspace β} :
cont t₂ t₃ f → cont (t₁ ⊓ t₂) t₃ f :=
continuous_le_dom inf_le_right
lemma continuous_Inf_dom {t₁ : set (tspace α)} {t₂ : tspace β} {t : tspace α} (h₁ : t ∈ t₁) :
cont t t₂ f → cont (Inf t₁) t₂ f :=
continuous_le_dom $ Inf_le h₁
lemma continuous_Inf_rng {t₁ : tspace α} {t₂ : set (tspace β)}
(h : ∀t∈t₂, cont t₁ t f) : cont t₁ (Inf t₂) f :=
continuous_iff_coinduced_le.2 $ le_Inf $ assume b hb, continuous_iff_coinduced_le.1 $ h b hb
lemma continuous_infi_dom {t₁ : ι → tspace α} {t₂ : tspace β} {i : ι} :
cont (t₁ i) t₂ f → cont (infi t₁) t₂ f :=
continuous_le_dom $ infi_le _ _
lemma continuous_infi_rng {t₁ : tspace α} {t₂ : ι → tspace β}
(h : ∀i, cont t₁ (t₂ i) f) : cont t₁ (infi t₂) f :=
continuous_iff_coinduced_le.2 $ le_infi $ assume i, continuous_iff_coinduced_le.1 $ h i
@[continuity] lemma continuous_bot {t : tspace β} : cont ⊥ t f :=
continuous_iff_le_induced.2 $ bot_le
@[continuity] lemma continuous_top {t : tspace α} : cont t ⊤ f :=
continuous_iff_coinduced_le.2 $ le_top
/- 𝓝 in the induced topology -/
theorem mem_nhds_induced [T : topological_space α] (f : β → α) (a : β) (s : set β) :
s ∈ @nhds β (topological_space.induced f T) a ↔ ∃ u ∈ 𝓝 (f a), f ⁻¹' u ⊆ s :=
begin
simp only [mem_nhds_iff, is_open_induced_iff, exists_prop, set.mem_set_of_eq],
split,
{ rintros ⟨u, usub, ⟨v, openv, ueq⟩, au⟩,
exact ⟨v, ⟨v, set.subset.refl v, openv, by rwa ←ueq at au⟩, by rw ueq; exact usub⟩ },
rintros ⟨u, ⟨v, vsubu, openv, amem⟩, finvsub⟩,
exact ⟨f ⁻¹' v, set.subset.trans (set.preimage_mono vsubu) finvsub, ⟨⟨v, openv, rfl⟩, amem⟩⟩
end
theorem nhds_induced [T : topological_space α] (f : β → α) (a : β) :
@nhds β (topological_space.induced f T) a = comap f (𝓝 (f a)) :=
by { ext s, rw [mem_nhds_induced, mem_comap] }
lemma induced_iff_nhds_eq [tα : topological_space α] [tβ : topological_space β] (f : β → α) :
tβ = tα.induced f ↔ ∀ b, 𝓝 b = comap f (𝓝 $ f b) :=
⟨λ h a, h.symm ▸ nhds_induced f a, λ h, eq_of_nhds_eq_nhds $ λ x, by rw [h, nhds_induced]⟩
theorem map_nhds_induced_of_surjective [T : topological_space α]
{f : β → α} (hf : function.surjective f) (a : β) :
map f (@nhds β (topological_space.induced f T) a) = 𝓝 (f a) :=
by rw [nhds_induced, map_comap_of_surjective hf]
end constructions
section induced
open topological_space
variables {α : Type*} {β : Type*}
variables [t : topological_space β] {f : α → β}
theorem is_open_induced_eq {s : set α} :
@is_open _ (induced f t) s ↔ s ∈ preimage f '' {s | is_open s} :=
iff.rfl
theorem is_open_induced {s : set β} (h : is_open s) : (induced f t).is_open (f ⁻¹' s) :=
⟨s, h, rfl⟩
lemma map_nhds_induced_eq (a : α) : map f (@nhds α (induced f t) a) = 𝓝[range f] (f a) :=
by rw [nhds_induced, filter.map_comap, nhds_within]
lemma map_nhds_induced_of_mem {a : α} (h : range f ∈ 𝓝 (f a)) :
map f (@nhds α (induced f t) a) = 𝓝 (f a) :=
by rw [nhds_induced, filter.map_comap_of_mem h]
lemma closure_induced [t : topological_space β] {f : α → β} {a : α} {s : set α} :
a ∈ @closure α (topological_space.induced f t) s ↔ f a ∈ closure (f '' s) :=
by simp only [mem_closure_iff_frequently, nhds_induced, frequently_comap, mem_image, and_comm]
end induced
section sierpinski
variables {α : Type*} [topological_space α]
@[simp] lemma is_open_singleton_true : is_open ({true} : set Prop) :=
topological_space.generate_open.basic _ (by simp)
lemma continuous_Prop {p : α → Prop} : continuous p ↔ is_open {x | p x} :=
⟨assume h : continuous p,
have is_open (p ⁻¹' {true}),
from is_open_singleton_true.preimage h,
by simp [preimage, eq_true] at this; assumption,
assume h : is_open {x | p x},
continuous_generated_from $ assume s (hs : s ∈ {{true}}),
by simp at hs; simp [hs, preimage, eq_true, h]⟩
lemma is_open_iff_continuous_mem {s : set α} : is_open s ↔ continuous (λ x, x ∈ s) :=
continuous_Prop.symm
end sierpinski
section infi
variables {α : Type u} {ι : Sort v}
lemma generate_from_union (a₁ a₂ : set (set α)) :
topological_space.generate_from (a₁ ∪ a₂) =
topological_space.generate_from a₁ ⊓ topological_space.generate_from a₂ :=
@galois_connection.l_sup _ (order_dual (topological_space α)) a₁ a₂ _ _ _ _
(λ g t, generate_from_le_iff_subset_is_open)
lemma set_of_is_open_sup (t₁ t₂ : topological_space α) :
{s | (t₁ ⊔ t₂).is_open s} = {s | t₁.is_open s} ∩ {s | t₂.is_open s} :=
@galois_connection.u_inf _ (order_dual (topological_space α)) t₁ t₂ _ _ _ _
(λ g t, generate_from_le_iff_subset_is_open)
lemma generate_from_Union {f : ι → set (set α)} :
topological_space.generate_from (⋃ i, f i) = (⨅ i, topological_space.generate_from (f i)) :=
@galois_connection.l_supr _ (order_dual (topological_space α)) _ _ _ _ _
(λ g t, generate_from_le_iff_subset_is_open) f
lemma set_of_is_open_supr {t : ι → topological_space α} :
{s | (⨆ i, t i).is_open s} = ⋂ i, {s | (t i).is_open s} :=
@galois_connection.u_infi _ (order_dual (topological_space α)) _ _ _ _ _
(λ g t, generate_from_le_iff_subset_is_open) t
lemma generate_from_sUnion {S : set (set (set α))} :
topological_space.generate_from (⋃₀ S) = (⨅ s ∈ S, topological_space.generate_from s) :=
@galois_connection.l_Sup _ (order_dual (topological_space α)) _ _ _ _
(λ g t, generate_from_le_iff_subset_is_open) S
lemma set_of_is_open_Sup {T : set (topological_space α)} :
{s | (Sup T).is_open s} = ⋂ t ∈ T, {s | (t : topological_space α).is_open s} :=
@galois_connection.u_Inf _ (order_dual (topological_space α)) _ _ _ _
(λ g t, generate_from_le_iff_subset_is_open) T
lemma generate_from_union_is_open (a b : topological_space α) :
topological_space.generate_from ({s | a.is_open s} ∪ {s | b.is_open s}) = a ⊓ b :=
@galois_insertion.l_sup_u _ (order_dual (topological_space α)) _ _ _ _ (gi_generate_from α) a b
lemma generate_from_Union_is_open (f : ι → topological_space α) :
topological_space.generate_from (⋃ i, {s | (f i).is_open s}) = ⨅ i, (f i) :=
@galois_insertion.l_supr_u _ (order_dual (topological_space α)) _ _ _ _ (gi_generate_from α) _ f
lemma generate_from_inter (a b : topological_space α) :
topological_space.generate_from ({s | a.is_open s} ∩ {s | b.is_open s}) = a ⊔ b :=
@galois_insertion.l_inf_u _ (order_dual (topological_space α)) _ _ _ _
(gi_generate_from α) a b
lemma generate_from_Inter (f : ι → topological_space α) :
topological_space.generate_from (⋂ i, {s | (f i).is_open s}) = ⨆ i, (f i) :=
@galois_insertion.l_infi_u _ (order_dual (topological_space α)) _ _ _ _ (gi_generate_from α) _ f
lemma generate_from_Inter_of_generate_from_eq_self (f : ι → set (set α))
(hf : ∀ i, {s | (topological_space.generate_from (f i)).is_open s} = f i) :
topological_space.generate_from (⋂ i, (f i)) = ⨆ i, topological_space.generate_from (f i) :=
@galois_insertion.l_infi_of_ul_eq_self _ (order_dual (topological_space α)) _ _ _ _
(gi_generate_from α) _ f hf
variables {t : ι → topological_space α}
lemma is_open_supr_iff {s : set α} : @is_open _ (⨆ i, t i) s ↔ ∀ i, @is_open _ (t i) s :=
show s ∈ set_of (supr t).is_open ↔ s ∈ {x : set α | ∀ (i : ι), (t i).is_open x},
by simp [set_of_is_open_supr]
lemma is_closed_infi_iff {s : set α} : @is_closed _ (⨆ i, t i) s ↔ ∀ i, @is_closed _ (t i) s :=
by simp [← is_open_compl_iff, is_open_supr_iff]
end infi
|
6cc1e2ea02b5af0e43d3a1b8e8876bdf0996deab
|
57c233acf9386e610d99ed20ef139c5f97504ba3
|
/src/probability_theory/independence.lean
|
751db8ca4bff293a5ee43beeb5401f5c98503cb6
|
[
"Apache-2.0"
] |
permissive
|
robertylewis/mathlib
|
3d16e3e6daf5ddde182473e03a1b601d2810952c
|
1d13f5b932f5e40a8308e3840f96fc882fae01f0
|
refs/heads/master
| 1,651,379,945,369
| 1,644,276,960,000
| 1,644,276,960,000
| 98,875,504
| 0
| 0
|
Apache-2.0
| 1,644,253,514,000
| 1,501,495,700,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 17,224
|
lean
|
/-
Copyright (c) 2021 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne
-/
import algebra.big_operators.intervals
import measure_theory.measure.measure_space
import measure_theory.pi_system
/-!
# Independence of sets of sets and measure spaces (σ-algebras)
* A family of sets of sets `π : ι → set (set α)` is independent with respect to a measure `μ` if for
any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`,
`μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. It will be used for families of π-systems.
* A family of measurable space structures (i.e. of σ-algebras) is independent with respect to a
measure `μ` (typically defined on a finer σ-algebra) if the family of sets of measurable sets they
define is independent. I.e., `m : ι → measurable_space α` is independent with respect to a
measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets
`f i_1 ∈ m i_1, ..., f i_n ∈ m i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i)`.
* Independence of sets (or events in probabilistic parlance) is defined as independence of the
measurable space structures they generate: a set `s` generates the measurable space structure with
measurable sets `∅, s, sᶜ, univ`.
* Independence of functions (or random variables) is also defined as independence of the measurable
space structures they generate: a function `f` for which we have a measurable space `m` on the
codomain generates `measurable_space.comap f m`.
## Main statements
* TODO: `Indep_of_Indep_sets`: if π-systems are independent as sets of sets, then the
measurable space structures they generate are independent.
* `indep_of_indep_sets`: variant with two π-systems.
## Implementation notes
We provide one main definition of independence:
* `Indep_sets`: independence of a family of sets of sets `pi : ι → set (set α)`.
Three other independence notions are defined using `Indep_sets`:
* `Indep`: independence of a family of measurable space structures `m : ι → measurable_space α`,
* `Indep_set`: independence of a family of sets `s : ι → set α`,
* `Indep_fun`: independence of a family of functions. For measurable spaces
`m : Π (i : ι), measurable_space (β i)`, we consider functions `f : Π (i : ι), α → β i`.
Additionally, we provide four corresponding statements for two measurable space structures (resp.
sets of sets, sets, functions) instead of a family. These properties are denoted by the same names
as for a family, but without a capital letter, for example `indep_fun` is the version of `Indep_fun`
for two functions.
The definition of independence for `Indep_sets` uses finite sets (`finset`). An alternative and
equivalent way of defining independence would have been to use countable sets.
TODO: prove that equivalence.
Most of the definitions and lemma in this file list all variables instead of using the `variables`
keyword at the beginning of a section, for example
`lemma indep.symm {α} {m₁ m₂ : measurable_space α} [measurable_space α] {μ : measure α} ...` .
This is intentional, to be able to control the order of the `measurable_space` variables. Indeed
when defining `μ` in the example above, the measurable space used is the last one defined, here
`[measurable_space α]`, and not `m₁` or `m₂`.
## References
* Williams, David. Probability with martingales. Cambridge university press, 1991.
Part A, Chapter 4.
-/
open measure_theory measurable_space
open_locale big_operators classical
namespace probability_theory
section definitions
/-- A family of sets of sets `π : ι → set (set α)` is independent with respect to a measure `μ` if
for any finite set of indices `s = {i_1, ..., i_n}`, for any sets
`f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `.
It will be used for families of pi_systems. -/
def Indep_sets {α ι} [measurable_space α] (π : ι → set (set α)) (μ : measure α . volume_tac) :
Prop :=
∀ (s : finset ι) {f : ι → set α} (H : ∀ i, i ∈ s → f i ∈ π i), μ (⋂ i ∈ s, f i) = ∏ i in s, μ (f i)
/-- Two sets of sets `s₁, s₂` are independent with respect to a measure `μ` if for any sets
`t₁ ∈ p₁, t₂ ∈ s₂`, then `μ (t₁ ∩ t₂) = μ (t₁) * μ (t₂)` -/
def indep_sets {α} [measurable_space α] (s1 s2 : set (set α)) (μ : measure α . volume_tac) : Prop :=
∀ t1 t2 : set α, t1 ∈ s1 → t2 ∈ s2 → μ (t1 ∩ t2) = μ t1 * μ t2
/-- A family of measurable space structures (i.e. of σ-algebras) is independent with respect to a
measure `μ` (typically defined on a finer σ-algebra) if the family of sets of measurable sets they
define is independent. `m : ι → measurable_space α` is independent with respect to measure `μ` if
for any finite set of indices `s = {i_1, ..., i_n}`, for any sets
`f i_1 ∈ m i_1, ..., f i_n ∈ m i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. -/
def Indep {α ι} (m : ι → measurable_space α) [measurable_space α] (μ : measure α . volume_tac) :
Prop :=
Indep_sets (λ x, (m x).measurable_set') μ
/-- Two measurable space structures (or σ-algebras) `m₁, m₂` are independent with respect to a
measure `μ` (defined on a third σ-algebra) if for any sets `t₁ ∈ m₁, t₂ ∈ m₂`,
`μ (t₁ ∩ t₂) = μ (t₁) * μ (t₂)` -/
def indep {α} (m₁ m₂ : measurable_space α) [measurable_space α] (μ : measure α . volume_tac) :
Prop :=
indep_sets (m₁.measurable_set') (m₂.measurable_set') μ
/-- A family of sets is independent if the family of measurable space structures they generate is
independent. For a set `s`, the generated measurable space has measurable sets `∅, s, sᶜ, univ`. -/
def Indep_set {α ι} [measurable_space α] (s : ι → set α) (μ : measure α . volume_tac) : Prop :=
Indep (λ i, generate_from {s i}) μ
/-- Two sets are independent if the two measurable space structures they generate are independent.
For a set `s`, the generated measurable space structure has measurable sets `∅, s, sᶜ, univ`. -/
def indep_set {α} [measurable_space α] (s t : set α) (μ : measure α . volume_tac) : Prop :=
indep (generate_from {s}) (generate_from {t}) μ
/-- A family of functions defined on the same space `α` and taking values in possibly different
spaces, each with a measurable space structure, is independent if the family of measurable space
structures they generate on `α` is independent. For a function `g` with codomain having measurable
space structure `m`, the generated measurable space structure is `measurable_space.comap g m`. -/
def Indep_fun {α ι} [measurable_space α] {β : ι → Type*} (m : Π (x : ι), measurable_space (β x))
(f : Π (x : ι), α → β x) (μ : measure α . volume_tac) : Prop :=
Indep (λ x, measurable_space.comap (f x) (m x)) μ
/-- Two functions are independent if the two measurable space structures they generate are
independent. For a function `f` with codomain having measurable space structure `m`, the generated
measurable space structure is `measurable_space.comap f m`. -/
def indep_fun {α β γ} [measurable_space α] [mβ : measurable_space β] [mγ : measurable_space γ]
(f : α → β) (g : α → γ) (μ : measure α . volume_tac) : Prop :=
indep (measurable_space.comap f mβ) (measurable_space.comap g mγ) μ
end definitions
section indep
lemma indep_sets.symm {α} {s₁ s₂ : set (set α)} [measurable_space α] {μ : measure α}
(h : indep_sets s₁ s₂ μ) :
indep_sets s₂ s₁ μ :=
by { intros t1 t2 ht1 ht2, rw [set.inter_comm, mul_comm], exact h t2 t1 ht2 ht1, }
lemma indep.symm {α} {m₁ m₂ : measurable_space α} [measurable_space α] {μ : measure α}
(h : indep m₁ m₂ μ) :
indep m₂ m₁ μ :=
indep_sets.symm h
lemma indep_sets_of_indep_sets_of_le_left {α} {s₁ s₂ s₃: set (set α)} [measurable_space α]
{μ : measure α} (h_indep : indep_sets s₁ s₂ μ) (h31 : s₃ ⊆ s₁) :
indep_sets s₃ s₂ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 (set.mem_of_subset_of_mem h31 ht1) ht2
lemma indep_sets_of_indep_sets_of_le_right {α} {s₁ s₂ s₃: set (set α)} [measurable_space α]
{μ : measure α} (h_indep : indep_sets s₁ s₂ μ) (h32 : s₃ ⊆ s₂) :
indep_sets s₁ s₃ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 ht1 (set.mem_of_subset_of_mem h32 ht2)
lemma indep_of_indep_of_le_left {α} {m₁ m₂ m₃: measurable_space α} [measurable_space α]
{μ : measure α} (h_indep : indep m₁ m₂ μ) (h31 : m₃ ≤ m₁) :
indep m₃ m₂ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 (h31 _ ht1) ht2
lemma indep_of_indep_of_le_right {α} {m₁ m₂ m₃: measurable_space α} [measurable_space α]
{μ : measure α} (h_indep : indep m₁ m₂ μ) (h32 : m₃ ≤ m₂) :
indep m₁ m₃ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 ht1 (h32 _ ht2)
lemma indep_sets.union {α} [measurable_space α] {s₁ s₂ s' : set (set α)} {μ : measure α}
(h₁ : indep_sets s₁ s' μ) (h₂ : indep_sets s₂ s' μ) :
indep_sets (s₁ ∪ s₂) s' μ :=
begin
intros t1 t2 ht1 ht2,
cases (set.mem_union _ _ _).mp ht1 with ht1₁ ht1₂,
{ exact h₁ t1 t2 ht1₁ ht2, },
{ exact h₂ t1 t2 ht1₂ ht2, },
end
@[simp] lemma indep_sets.union_iff {α} [measurable_space α] {s₁ s₂ s' : set (set α)}
{μ : measure α} :
indep_sets (s₁ ∪ s₂) s' μ ↔ indep_sets s₁ s' μ ∧ indep_sets s₂ s' μ :=
⟨λ h, ⟨indep_sets_of_indep_sets_of_le_left h (set.subset_union_left s₁ s₂),
indep_sets_of_indep_sets_of_le_left h (set.subset_union_right s₁ s₂)⟩,
λ h, indep_sets.union h.left h.right⟩
lemma indep_sets.Union {α ι} [measurable_space α] {s : ι → set (set α)} {s' : set (set α)}
{μ : measure α} (hyp : ∀ n, indep_sets (s n) s' μ) :
indep_sets (⋃ n, s n) s' μ :=
begin
intros t1 t2 ht1 ht2,
rw set.mem_Union at ht1,
cases ht1 with n ht1,
exact hyp n t1 t2 ht1 ht2,
end
lemma indep_sets.inter {α} [measurable_space α] {s₁ s' : set (set α)} (s₂ : set (set α))
{μ : measure α} (h₁ : indep_sets s₁ s' μ) :
indep_sets (s₁ ∩ s₂) s' μ :=
λ t1 t2 ht1 ht2, h₁ t1 t2 ((set.mem_inter_iff _ _ _).mp ht1).left ht2
lemma indep_sets.Inter {α ι} [measurable_space α] {s : ι → set (set α)} {s' : set (set α)}
{μ : measure α} (h : ∃ n, indep_sets (s n) s' μ) :
indep_sets (⋂ n, s n) s' μ :=
by {intros t1 t2 ht1 ht2, cases h with n h, exact h t1 t2 (set.mem_Inter.mp ht1 n) ht2 }
lemma indep_sets_singleton_iff {α} [measurable_space α] {s t : set α} {μ : measure α} :
indep_sets {s} {t} μ ↔ μ (s ∩ t) = μ s * μ t :=
⟨λ h, h s t rfl rfl,
λ h s1 t1 hs1 ht1, by rwa [set.mem_singleton_iff.mp hs1, set.mem_singleton_iff.mp ht1]⟩
end indep
/-! ### Deducing `indep` from `Indep` -/
section from_Indep_to_indep
lemma Indep_sets.indep_sets {α ι} {s : ι → set (set α)} [measurable_space α] {μ : measure α}
(h_indep : Indep_sets s μ) {i j : ι} (hij : i ≠ j) :
indep_sets (s i) (s j) μ :=
begin
intros t₁ t₂ ht₁ ht₂,
have hf_m : ∀ (x : ι), x ∈ {i, j} → (ite (x=i) t₁ t₂) ∈ s x,
{ intros x hx,
cases finset.mem_insert.mp hx with hx hx,
{ simp [hx, ht₁], },
{ simp [finset.mem_singleton.mp hx, hij.symm, ht₂], }, },
have h1 : t₁ = ite (i = i) t₁ t₂, by simp only [if_true, eq_self_iff_true],
have h2 : t₂ = ite (j = i) t₁ t₂, by simp only [hij.symm, if_false],
have h_inter : (⋂ (t : ι) (H : t ∈ ({i, j} : finset ι)), ite (t = i) t₁ t₂)
= (ite (i = i) t₁ t₂) ∩ (ite (j = i) t₁ t₂),
by simp only [finset.set_bInter_singleton, finset.set_bInter_insert],
have h_prod : (∏ (t : ι) in ({i, j} : finset ι), μ (ite (t = i) t₁ t₂))
= μ (ite (i = i) t₁ t₂) * μ (ite (j = i) t₁ t₂),
by simp only [hij, finset.prod_singleton, finset.prod_insert, not_false_iff,
finset.mem_singleton],
rw h1,
nth_rewrite 1 h2,
nth_rewrite 3 h2,
rw [←h_inter, ←h_prod, h_indep {i, j} hf_m],
end
lemma Indep.indep {α ι} {m : ι → measurable_space α} [measurable_space α] {μ : measure α}
(h_indep : Indep m μ) {i j : ι} (hij : i ≠ j) :
indep (m i) (m j) μ :=
begin
change indep_sets ((λ x, (m x).measurable_set') i) ((λ x, (m x).measurable_set') j) μ,
exact Indep_sets.indep_sets h_indep hij,
end
end from_Indep_to_indep
/-!
## π-system lemma
Independence of measurable spaces is equivalent to independence of generating π-systems.
-/
section from_measurable_spaces_to_sets_of_sets
/-! ### Independence of measurable space structures implies independence of generating π-systems -/
lemma Indep.Indep_sets {α ι} [measurable_space α] {μ : measure α} {m : ι → measurable_space α}
{s : ι → set (set α)} (hms : ∀ n, m n = measurable_space.generate_from (s n))
(h_indep : Indep m μ) :
Indep_sets s μ :=
begin
refine (λ S f hfs, h_indep S (λ x hxS, _)),
simp_rw hms x,
exact measurable_set_generate_from (hfs x hxS),
end
lemma indep.indep_sets {α} [measurable_space α] {μ : measure α} {s1 s2 : set (set α)}
(h_indep : indep (generate_from s1) (generate_from s2) μ) :
indep_sets s1 s2 μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 (measurable_set_generate_from ht1) (measurable_set_generate_from ht2)
end from_measurable_spaces_to_sets_of_sets
section from_pi_systems_to_measurable_spaces
/-! ### Independence of generating π-systems implies independence of measurable space structures -/
private lemma indep_sets.indep_aux {α} {m2 : measurable_space α}
{m : measurable_space α} {μ : measure α} [is_probability_measure μ] {p1 p2 : set (set α)}
(h2 : m2 ≤ m) (hp2 : is_pi_system p2) (hpm2 : m2 = generate_from p2)
(hyp : indep_sets p1 p2 μ) {t1 t2 : set α} (ht1 : t1 ∈ p1) (ht2m : m2.measurable_set' t2) :
μ (t1 ∩ t2) = μ t1 * μ t2 :=
begin
let μ_inter := μ.restrict t1,
let ν := (μ t1) • μ,
have h_univ : μ_inter set.univ = ν set.univ,
by rw [measure.restrict_apply_univ, measure.smul_apply, measure_univ, mul_one],
haveI : is_finite_measure μ_inter := @restrict.is_finite_measure α _ t1 μ ⟨measure_lt_top μ t1⟩,
rw [set.inter_comm, ←@measure.restrict_apply α _ μ t1 t2 (h2 t2 ht2m)],
refine ext_on_measurable_space_of_generate_finite m p2 (λ t ht, _) h2 hpm2 hp2 h_univ ht2m,
have ht2 : m.measurable_set' t,
{ refine h2 _ _,
rw hpm2,
exact measurable_set_generate_from ht, },
rw [measure.restrict_apply ht2, measure.smul_apply, set.inter_comm],
exact hyp t1 t ht1 ht,
end
lemma indep_sets.indep {α} {m1 m2 : measurable_space α} {m : measurable_space α}
{μ : measure α} [is_probability_measure μ] {p1 p2 : set (set α)} (h1 : m1 ≤ m) (h2 : m2 ≤ m)
(hp1 : is_pi_system p1) (hp2 : is_pi_system p2) (hpm1 : m1 = generate_from p1)
(hpm2 : m2 = generate_from p2) (hyp : indep_sets p1 p2 μ) :
indep m1 m2 μ :=
begin
intros t1 t2 ht1 ht2,
let μ_inter := μ.restrict t2,
let ν := (μ t2) • μ,
have h_univ : μ_inter set.univ = ν set.univ,
by rw [measure.restrict_apply_univ, measure.smul_apply, measure_univ, mul_one],
haveI : is_finite_measure μ_inter := @restrict.is_finite_measure α _ t2 μ ⟨measure_lt_top μ t2⟩,
rw [mul_comm, ←@measure.restrict_apply α _ μ t2 t1 (h1 t1 ht1)],
refine ext_on_measurable_space_of_generate_finite m p1 (λ t ht, _) h1 hpm1 hp1 h_univ ht1,
have ht1 : m.measurable_set' t,
{ refine h1 _ _,
rw hpm1,
exact measurable_set_generate_from ht, },
rw [measure.restrict_apply ht1, measure.smul_apply, mul_comm],
exact indep_sets.indep_aux h2 hp2 hpm2 hyp ht ht2,
end
end from_pi_systems_to_measurable_spaces
section indep_set
/-! ### Independence of measurable sets
We prove the following equivalences on `indep_set`, for measurable sets `s, t`.
* `indep_set s t μ ↔ μ (s ∩ t) = μ s * μ t`,
* `indep_set s t μ ↔ indep_sets {s} {t} μ`.
-/
variables {α : Type*} [measurable_space α] {s t : set α} (S T : set (set α))
lemma indep_set_iff_indep_sets_singleton (hs_meas : measurable_set s) (ht_meas : measurable_set t)
(μ : measure α . volume_tac) [is_probability_measure μ] :
indep_set s t μ ↔ indep_sets {s} {t} μ :=
⟨indep.indep_sets, λ h, indep_sets.indep
(generate_from_le (λ u hu, by rwa set.mem_singleton_iff.mp hu))
(generate_from_le (λ u hu, by rwa set.mem_singleton_iff.mp hu)) (is_pi_system.singleton s)
(is_pi_system.singleton t) rfl rfl h⟩
lemma indep_set_iff_measure_inter_eq_mul (hs_meas : measurable_set s) (ht_meas : measurable_set t)
(μ : measure α . volume_tac) [is_probability_measure μ] :
indep_set s t μ ↔ μ (s ∩ t) = μ s * μ t :=
(indep_set_iff_indep_sets_singleton hs_meas ht_meas μ).trans indep_sets_singleton_iff
lemma indep_sets.indep_set_of_mem (hs : s ∈ S) (ht : t ∈ T) (hs_meas : measurable_set s)
(ht_meas : measurable_set t) (μ : measure α . volume_tac) [is_probability_measure μ]
(h_indep : indep_sets S T μ) :
indep_set s t μ :=
(indep_set_iff_measure_inter_eq_mul hs_meas ht_meas μ).mpr (h_indep s t hs ht)
end indep_set
end probability_theory
|
bc4f5a8c1994a4193588a096a59fab96f738915b
|
26ac254ecb57ffcb886ff709cf018390161a9225
|
/src/ring_theory/algebra_tower.lean
|
cc4c756c17eaf588b96faf90be518a9ddbc9fe9c
|
[
"Apache-2.0"
] |
permissive
|
eric-wieser/mathlib
|
42842584f584359bbe1fc8b88b3ff937c8acd72d
|
d0df6b81cd0920ad569158c06a3fd5abb9e63301
|
refs/heads/master
| 1,669,546,404,255
| 1,595,254,668,000
| 1,595,254,668,000
| 281,173,504
| 0
| 0
|
Apache-2.0
| 1,595,263,582,000
| 1,595,263,581,000
| null |
UTF-8
|
Lean
| false
| false
| 12,186
|
lean
|
/-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import ring_theory.adjoin
/-!
# Towers of algebras
We set up the basic theory of algebra towers.
The typeclass `is_algebra_tower R S A` expresses that `A` is an `S`-algebra,
and both `S` and `A` are `R`-algebras, with the compatibility condition
`(r • s) • a = r • (s • a)`.
In `field_theory/tower.lean` we use this to prove the tower law for finite extensions,
that if `R` and `S` are both fields, then `[A:R] = [A:S] [S:A]`.
In this file we prepare the main lemma:
if `{bi | i ∈ I}` is an `R`-basis of `S` and `{cj | j ∈ J}` is a `S`-basis
of `A`, then `{bi cj | i ∈ I, j ∈ J}` is an `R`-basis of `A`. This statement does not require the
base rings to be a field, so we also generalize the lemma to rings in this file.
-/
universes u v w u₁
variables (R : Type u) (S : Type v) (A : Type w) (B : Type u₁)
/-- Typeclass for a tower of three algebras. -/
class is_algebra_tower [comm_semiring R] [comm_semiring S] [semiring A]
[algebra R S] [algebra S A] [algebra R A] : Prop :=
(smul_assoc : ∀ (x : R) (y : S) (z : A), (x • y) • z = x • (y • z))
namespace is_algebra_tower
section semiring
variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B]
variables [algebra R S] [algebra S A] [algebra R A] [algebra S B] [algebra R B]
variables {R S A}
theorem of_algebra_map_eq (h : ∀ x, algebra_map R A x = algebra_map S A (algebra_map R S x)) :
is_algebra_tower R S A :=
⟨λ x y z, by simp_rw [algebra.smul_def, ring_hom.map_mul, mul_assoc, h]⟩
variables [is_algebra_tower R S A] [is_algebra_tower R S B]
variables (R S A)
theorem algebra_map_eq :
algebra_map R A = (algebra_map S A).comp (algebra_map R S) :=
ring_hom.ext $ λ x, by simp_rw [ring_hom.comp_apply, algebra.algebra_map_eq_smul_one,
smul_assoc, one_smul]
theorem algebra_map_apply (x : R) : algebra_map R A x = algebra_map S A (algebra_map R S x) :=
by rw [algebra_map_eq R S A, ring_hom.comp_apply]
variables {R} (S) {A}
theorem algebra_map_smul (r : R) (x : A) : algebra_map R S r • x = r • x :=
by rw [algebra.algebra_map_eq_smul_one, smul_assoc, one_smul]
variables {R S A}
theorem smul_left_comm (r : R) (s : S) (x : A) : r • s • x = s • r • x :=
by simp_rw [algebra.smul_def, ← mul_assoc, algebra_map_apply R S A,
← (algebra_map S A).map_mul, mul_comm s]
@[ext] lemma algebra.ext {S : Type u} {A : Type v} [comm_semiring S] [semiring A]
(h1 h2 : algebra S A) (h : ∀ {r : S} {x : A}, (by clear h2; exact r • x) = r • x) : h1 = h2 :=
begin
unfreezingI { cases h1 with f1 g1 h11 h12, cases h2 with f2 g2 h21 h22,
cases f1, cases f2, congr', { ext r x, exact h },
ext r, erw [← mul_one (g1 r), ← h12, ← mul_one (g2 r), ← h22, h], refl }
end
variables (R S A)
theorem comap_eq : algebra.comap.algebra R S A = ‹_› :=
algebra.ext _ _ $ λ x (z : A),
calc algebra_map R S x • z
= (x • 1 : S) • z : by rw algebra.algebra_map_eq_smul_one
... = x • (1 : S) • z : by rw smul_assoc
... = (by exact x • z : A) : by rw one_smul
/-- In a tower, the canonical map from the middle element to the top element is an
algebra homomorphism over the bottom element. -/
def to_alg_hom : S →ₐ[R] A :=
{ commutes' := λ _, (algebra_map_apply _ _ _ _).symm,
.. algebra_map S A }
@[simp] lemma to_alg_hom_apply (y : S) : to_alg_hom R S A y = algebra_map S A y := rfl
variables (R) {S A B}
/-- R ⟶ S induces S-Alg ⥤ R-Alg -/
def restrict_base (f : A →ₐ[S] B) : A →ₐ[R] B :=
{ commutes' := λ r, by { rw [algebra_map_apply R S A, algebra_map_apply R S B],
exact f.commutes (algebra_map R S r) },
.. (f : A →+* B) }
@[simp] lemma restrict_base_apply (f : A →ₐ[S] B) (x : A) : restrict_base R f x = f x := rfl
instance left : is_algebra_tower S S A :=
of_algebra_map_eq $ λ x, rfl
instance right : is_algebra_tower R S S :=
of_algebra_map_eq $ λ x, rfl
instance nat : is_algebra_tower ℕ S A :=
of_algebra_map_eq $ λ x, ((algebra_map S A).map_nat_cast x).symm
instance comap {R S A : Type*} [comm_semiring R] [comm_semiring S] [semiring A]
[algebra R S] [algebra S A] : is_algebra_tower R S (algebra.comap R S A) :=
of_algebra_map_eq $ λ x, rfl
instance subsemiring (U : subsemiring S) : is_algebra_tower U S A :=
of_algebra_map_eq $ λ x, rfl
instance subring {S A : Type*} [comm_ring S] [ring A] [algebra S A]
(U : set S) [is_subring U] : is_algebra_tower U S A :=
of_algebra_map_eq $ λ x, rfl
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A] [algebra R A]
variables [comm_semiring B] [algebra A B] [algebra R B] [is_algebra_tower R A B]
instance subalgebra (S : subalgebra R A) : is_algebra_tower R S A :=
of_algebra_map_eq $ λ x, rfl
instance polynomial : is_algebra_tower R A (polynomial B) :=
of_algebra_map_eq $ λ x, congr_arg polynomial.C $ algebra_map_apply R A B x
theorem aeval_apply (x : B) (p) : polynomial.aeval R B x p =
polynomial.aeval A B x (polynomial.map (algebra_map R A) p) :=
by rw [polynomial.aeval_def, polynomial.aeval_def, polynomial.eval₂_map, algebra_map_eq R A B]
end comm_semiring
section ring
variables [comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A] [algebra R A]
variables [is_algebra_tower R S A]
/-- If A/S/R is a tower of algebras then any S-subalgebra of A gives an R-subalgebra of A. -/
def subalgebra_comap (U : subalgebra S A) : subalgebra R A :=
{ carrier := U,
algebra_map_mem' := λ x, by { rw algebra_map_apply R S A, exact U.algebra_map_mem _ } }
theorem subalgebra_comap_top : subalgebra_comap R S A ⊤ = ⊤ :=
algebra.eq_top_iff.2 $ λ _, show _ ∈ (⊤ : subalgebra S A), from algebra.mem_top
end ring
section comm_ring
variables [comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] [algebra R A]
variables [is_algebra_tower R S A]
theorem range_under_adjoin (t : set A) :
(to_alg_hom R S A).range.under (algebra.adjoin _ t) =
subalgebra_comap R S A (algebra.adjoin S t) :=
subalgebra.ext $ λ z,
show z ∈ subsemiring.closure (set.range (algebra_map (to_alg_hom R S A).range A) ∪ t : set A) ↔
z ∈ subsemiring.closure (set.range (algebra_map S A) ∪ t : set A),
from suffices set.range (algebra_map (to_alg_hom R S A).range A) = set.range (algebra_map S A),
by rw this,
by { ext z, exact ⟨λ ⟨⟨x, y, h1⟩, h2⟩, ⟨y, h2 ▸ h1⟩, λ ⟨y, hy⟩, ⟨⟨z, y, hy⟩, rfl⟩⟩ }
instance int : is_algebra_tower ℤ S A :=
of_algebra_map_eq $ λ x, ((algebra_map S A).map_int_cast x).symm
end comm_ring
section division_ring
variables [field R] [division_ring S] [algebra R S] [char_zero R] [char_zero S]
instance rat : is_algebra_tower ℚ R S :=
of_algebra_map_eq $ λ x, ((algebra_map R S).map_rat_cast x).symm
end division_ring
end is_algebra_tower
namespace algebra
theorem adjoin_algebra_map' {R : Type u} {S : Type v} {A : Type w}
[comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] (s : set S) :
adjoin R (algebra_map S (comap R S A) '' s) = subalgebra.map (adjoin R s) (to_comap R S A) :=
le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩)
(subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩)
theorem adjoin_algebra_map (R : Type u) (S : Type v) (A : Type w)
[comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] [algebra R A]
[is_algebra_tower R S A] (s : set S) :
adjoin R (algebra_map S A '' s) = subalgebra.map (adjoin R s) (is_algebra_tower.to_alg_hom R S A) :=
le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩)
(subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩)
end algebra
namespace submodule
open is_algebra_tower
variables [comm_semiring R] [comm_semiring S] [semiring A]
variables [algebra R S] [algebra S A] [algebra R A] [is_algebra_tower R S A]
variables (R) {S A}
/-- Restricting the scalars of submodules in an algebra tower. -/
def restrict_scalars' (U : submodule S A) : submodule R A :=
{ smul_mem' := λ r x hx, algebra_map_smul S r x ▸ U.smul_mem _ hx, .. U }
variables (R S A)
theorem restrict_scalars'_top : restrict_scalars' R (⊤ : submodule S A) = ⊤ := rfl
variables {R S A}
theorem restrict_scalars'_injective (U₁ U₂ : submodule S A)
(h : restrict_scalars' R U₁ = restrict_scalars' R U₂) : U₁ = U₂ :=
ext $ by convert set.ext_iff.1 (ext'_iff.1 h); refl
theorem restrict_scalars'_inj {U₁ U₂ : submodule S A} :
restrict_scalars' R U₁ = restrict_scalars' R U₂ ↔ U₁ = U₂ :=
⟨restrict_scalars'_injective U₁ U₂, congr_arg _⟩
end submodule
section semiring
variables {R S A}
variables [comm_semiring R] [comm_semiring S] [semiring A]
variables [algebra R S] [algebra S A] [algebra R A] [is_algebra_tower R S A]
namespace submodule
open is_algebra_tower
theorem smul_mem_span_smul_of_mem {s : set S} {t : set A} {k : S} (hks : k ∈ span R s)
{x : A} (hx : x ∈ t) : k • x ∈ span R (s • t) :=
span_induction hks (λ c hc, subset_span $ set.mem_smul.2 ⟨c, x, hc, hx, rfl⟩)
(by { rw zero_smul, exact zero_mem _ })
(λ c₁ c₂ ih₁ ih₂, by { rw add_smul, exact add_mem _ ih₁ ih₂ })
(λ b c hc, by { rw is_algebra_tower.smul_assoc, exact smul_mem _ _ hc })
theorem smul_mem_span_smul {s : set S} (hs : span R s = ⊤) {t : set A} {k : S}
{x : A} (hx : x ∈ span R t) :
k • x ∈ span R (s • t) :=
span_induction hx (λ x hx, smul_mem_span_smul_of_mem (hs.symm ▸ mem_top) hx)
(by { rw smul_zero, exact zero_mem _ })
(λ x y ihx ihy, by { rw smul_add, exact add_mem _ ihx ihy })
(λ c x hx, smul_left_comm c k x ▸ smul_mem _ _ hx)
theorem smul_mem_span_smul' {s : set S} (hs : span R s = ⊤) {t : set A} {k : S}
{x : A} (hx : x ∈ span R (s • t)) :
k • x ∈ span R (s • t) :=
span_induction hx (λ x hx, let ⟨p, q, hp, hq, hpq⟩ := set.mem_smul.1 hx in
by { rw [← hpq, smul_smul], exact smul_mem_span_smul_of_mem (hs.symm ▸ mem_top) hq })
(by { rw smul_zero, exact zero_mem _ })
(λ x y ihx ihy, by { rw smul_add, exact add_mem _ ihx ihy })
(λ c x hx, smul_left_comm c k x ▸ smul_mem _ _ hx)
theorem span_smul {s : set S} (hs : span R s = ⊤) (t : set A) :
span R (s • t) = (span S t).restrict_scalars' R :=
le_antisymm (span_le.2 $ λ x hx, let ⟨p, q, hps, hqt, hpqx⟩ := set.mem_smul.1 hx in
hpqx ▸ (span S t).smul_mem p (subset_span hqt)) $
λ p hp, span_induction hp (λ x hx, one_smul S x ▸ smul_mem_span_smul hs (subset_span hx))
(zero_mem _)
(λ _ _, add_mem _)
(λ k x hx, smul_mem_span_smul' hs hx)
end submodule
end semiring
section ring
open_locale big_operators classical
universes v₁ w₁
variables {R S A}
variables [comm_ring R] [comm_ring S] [ring A]
variables [algebra R S] [algebra S A] [algebra R A] [is_algebra_tower R S A]
theorem linear_independent_smul {ι : Type v₁} {b : ι → S} {κ : Type w₁} {c : κ → A}
(hb : linear_independent R b) (hc : linear_independent S c) :
linear_independent R (λ p : ι × κ, b p.1 • c p.2) :=
begin
rw linear_independent_iff' at hb hc, rw linear_independent_iff'', rintros s g hg hsg ⟨i, k⟩,
by_cases hik : (i, k) ∈ s,
{ have h1 : ∑ i in (s.image prod.fst).product (s.image prod.snd), g i • b i.1 • c i.2 = 0,
{ rw ← hsg, exact (finset.sum_subset finset.subset_product $ λ p _ hp,
show g p • b p.1 • c p.2 = 0, by rw [hg p hp, zero_smul]).symm },
rw [finset.sum_product, finset.sum_comm] at h1,
simp_rw [← is_algebra_tower.smul_assoc, ← finset.sum_smul] at h1,
exact hb _ _ (hc _ _ h1 k (finset.mem_image_of_mem _ hik)) i (finset.mem_image_of_mem _ hik) },
exact hg _ hik
end
theorem is_basis.smul {ι : Type v₁} {b : ι → S} {κ : Type w₁} {c : κ → A}
(hb : is_basis R b) (hc : is_basis S c) : is_basis R (λ p : ι × κ, b p.1 • c p.2) :=
⟨linear_independent_smul hb.1 hc.1,
by rw [← set.range_smul_range, submodule.span_smul hb.2, ← submodule.restrict_scalars'_top R S A,
submodule.restrict_scalars'_inj, hc.2]⟩
end ring
|
bb29cd58a8a5459cd96331a44b066059fc13edc8
|
3b15c7b0b62d8ada1399c112ad88a529e6bfa115
|
/src/Lean/Widget/InteractiveCode.lean
|
d5d31cd2c822d83eac8a33c1520505e3bcfc3881
|
[
"Apache-2.0"
] |
permissive
|
stephenbrady/lean4
|
74bf5cae8a433e9c815708ce96c9e54a5caf2115
|
b1bd3fc304d0f7bc6810ec78bfa4c51476d263f9
|
refs/heads/master
| 1,692,621,473,161
| 1,634,308,743,000
| 1,634,310,749,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 4,872
|
lean
|
/-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Wojciech Nawrocki
-/
import Lean.PrettyPrinter
import Lean.Server.Rpc.Basic
import Lean.Widget.TaggedText
/-! RPC infrastructure for storing and formatting code fragments, in particular `Expr`s,
with environment and subexpression information. -/
namespace Lean.Widget
open Server
-- TODO: Some of the `WithBlah` types exist mostly because we cannot derive multi-argument RPC wrappers.
-- They will be gone eventually.
structure InfoWithCtx where
ctx : Elab.ContextInfo
info : Elab.Info
deriving Inhabited, RpcEncoding with { withRef := true }
structure CodeToken where
info : WithRpcRef InfoWithCtx
-- TODO(WN): add fields for semantic highlighting
-- kind : Lsp.SymbolKind
deriving Inhabited, RpcEncoding
/-- Pretty-printed syntax (usually but not necessarily an `Expr`) with embedded `Info`s. -/
abbrev CodeWithInfos := TaggedText CodeToken
def CodeWithInfos.pretty (tt : CodeWithInfos) :=
tt.stripTags
open Expr in
/-- Find a subexpression of `e` using the pretty-printer address scheme. -/
-- NOTE(WN): not currently in use
partial def traverse (e : Expr) (addr : Nat) : MetaM (LocalContext × Expr):= do
let e ← Meta.instantiateMVars e
go (tritsLE [] addr |>.drop 1) (← getLCtx) e
where
tritsLE (acc : List Nat) (n : Nat) : List Nat :=
if n == 0 then acc
else tritsLE (n % 3 :: acc) (n / 3)
go (addr : List Nat) (lctx : LocalContext) (e : Expr) : MetaM (LocalContext × Expr) := do
match addr with
| [] => (lctx, e)
| a::as => do
let go' (e' : Expr) := do
go as (← getLCtx) e'
let eExpr ← match a, e with
| 0, app e₁ e₂ _ => go' e₁
| 1, app e₁ e₂ _ => go' e₂
| 0, lam _ e₁ e₂ _ => go' e₁
| 1, lam n e₁ e₂ data =>
Meta.withLocalDecl n data.binderInfo e₁ fun fvar =>
go' (e₂.instantiate1 fvar)
| 0, forallE _ e₁ e₂ _ => go' e₁
| 1, forallE n e₁ e₂ data =>
Meta.withLocalDecl n data.binderInfo e₁ fun fvar =>
go' (e₂.instantiate1 fvar)
| 0, letE _ e₁ e₂ e₃ _ => go' e₁
| 1, letE _ e₁ e₂ e₃ _ => go' e₂
| 2, letE n e₁ e₂ e₃ _ =>
Meta.withLetDecl n e₁ e₂ fun fvar => do
go' (e₃.instantiate1 fvar)
| 0, mdata _ e₁ _ => go' e₁
| 0, proj _ _ e₁ _ => go' e₁
| _, _ => (lctx, e) -- panic! s!"cannot descend {a} into {e.expr}"
-- TODO(WN): should the two fns below go in `Lean.PrettyPrinter` ?
open PrettyPrinter in
private def formatWithOpts (e : Expr) (optsPerPos : Delaborator.OptionsPerPos)
: MetaM (Format × Std.RBMap Nat Elab.Info compare) := do
let currNamespace ← getCurrNamespace
let openDecls ← getOpenDecls
let opts ← getOptions
let (stx, infos) ← PrettyPrinter.delabCore currNamespace openDecls e optsPerPos
let stx := sanitizeSyntax stx |>.run' { options := opts }
let stx ← PrettyPrinter.parenthesizeTerm stx
let fmt ← PrettyPrinter.formatTerm stx
return (fmt, infos)
/-- Pretty-print the expression and its subexpression information. -/
def formatInfos (e : Expr) : MetaM (Format × Std.RBMap Nat Elab.Info compare) :=
formatWithOpts e {}
/-- Like `formatInfos` but with `pp.all` set at the top-level expression. -/
def formatExplicitInfos (e : Expr) : MetaM (Format × Std.RBMap Nat Elab.Info compare) :=
let optsPerPos := Std.RBMap.ofList [(1, KVMap.empty.setBool `pp.all true)]
formatWithOpts e optsPerPos
/-- Tags a pretty-printed `Expr` with infos from the delaborator. -/
partial def tagExprInfos (ctx : Elab.ContextInfo) (infos : Std.RBMap Nat Elab.Info compare) (tt : TaggedText (Nat × Nat))
: CodeWithInfos :=
go tt
where
go (tt : TaggedText (Nat × Nat)) :=
tt.rewrite fun (n, _) subTt =>
match infos.find? n with
| none => go subTt
| some i => TaggedText.tag ⟨WithRpcRef.mk { ctx, info := i }⟩ (go subTt)
def exprToInteractive (e : Expr) : MetaM CodeWithInfos := do
let (fmt, infos) ← formatInfos e
let tt := TaggedText.prettyTagged fmt
let ctx := {
env := ← getEnv
mctx := ← getMCtx
options := ← getOptions
currNamespace := ← getCurrNamespace
openDecls := ← getOpenDecls
fileMap := arbitrary
}
tagExprInfos ctx infos tt
def exprToInteractiveExplicit (e : Expr) : MetaM CodeWithInfos := do
let (fmt, infos) ← formatExplicitInfos e
let tt := TaggedText.prettyTagged fmt
let ctx := {
env := ← getEnv
mctx := ← getMCtx
options := ← getOptions
currNamespace := ← getCurrNamespace
openDecls := ← getOpenDecls
fileMap := arbitrary
}
tagExprInfos ctx infos tt
end Lean.Widget
|
4e35df690fa5236d7480dc8f113c99a1398e371f
|
ac076ebc286fa9b7a67171f6cd11eb98b263d6ef
|
/src/induction.lean
|
d98c5afa039a06106aec5957056db620683a0d93
|
[] |
no_license
|
Shamrock-Frost/jordan-holder
|
e891e489d00f8ff9e29c47b3083f22cac7804efb
|
bab3daccd70a4f3c5b25731b899a2cd72d7b8376
|
refs/heads/master
| 1,594,962,465,041
| 1,576,197,432,000
| 1,576,197,432,000
| 205,951,913
| 1
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 5,475
|
lean
|
import group_theory.subgroup
import group_theory.quotient_group
import group_theory.category
open category_theory
local attribute [instance] classical.prop_decidable
lemma fintype.card_of_removed {α} [fintype α] (a : α)
: fintype.card { x : α // x ≠ a } = nat.pred (fintype.card α) :=
begin
transitivity finset.card (finset.erase finset.univ a),
apply fintype.card_of_subtype, intros,
rw [finset.mem_erase, eq_true_intro (finset.mem_univ x), and_true],
apply finset.card_erase_of_mem, apply finset.mem_univ
end
noncomputable
def quotient.out_avoid {α} (s : setoid α) (a b : α)
(hdist : a ≠ b) : quotient s → { x : α // x ≠ b } :=
λ x, if h : quotient.out x = b
then ⟨a, hdist⟩
else ⟨quotient.out x, h⟩
lemma quotient.out_avoid_inj {α : Type*} (s : setoid α) (a b : α)
(hdist : a ≠ b) (hrel : setoid.r a b)
: function.injective (quotient.out_avoid s a b hdist) :=
λ x y hxy,
if hx : quotient.out x = b
then if hy : quotient.out y = b
then calc x = quotient.mk b : by { rw ← hx, rw quotient.out_eq }
... = y : by { symmetry, rw ← hy, rw quotient.out_eq }
else by { simp [quotient.out_avoid] at hxy,
rw [dif_pos hx, dif_neg hy] at hxy,
transitivity quotient.mk b,
rw ← hx, rw quotient.out_eq,
transitivity quotient.mk a,
exact quot.eqv_gen_sound (eqv_gen.symm _ _ (eqv_gen.rel _ _ hrel)),
rw subtype.ext at hxy, simp at hxy,
rw hxy, rw quotient.out_eq }
else if hy : quotient.out y = b
then by { simp [quotient.out_avoid] at hxy,
rw [dif_neg hx, dif_pos hy] at hxy,
transitivity quotient.mk a,
rw subtype.ext at hxy, simp at hxy,
rw ← hxy, rw quotient.out_eq,
transitivity quotient.mk b,
exact quot.eqv_gen_sound (eqv_gen.rel _ _ hrel),
rw ← hy, rw quotient.out_eq }
else by { simp [quotient.out_avoid] at hxy,
rw [dif_neg hx, dif_neg hy] at hxy,
rw subtype.ext at hxy, simp at hxy,
rw [← quotient.out_eq x, ← quotient.out_eq y, hxy] }
lemma quotient.card_lt {α : Type*} [fintype α] (s : setoid α)
(a b : α) (hdist : a ≠ b) (hrel : setoid.r a b)
: fintype.card (quotient s) < fintype.card α :=
by { apply @nat.lt_of_le_of_lt _ (fintype.card { x : α // x ≠ b }) _,
apply fintype.card_le_of_injective (quotient.out_avoid s a b hdist),
apply quotient.out_avoid_inj, assumption,
rw fintype.card_of_removed, apply nat.pred_lt,
intro h, rw fintype.card_eq_zero_iff at h, exact h a }
lemma finite_group.induction_ord (P : Π (G : Group), fintype G → Sort _)
: (∀ (G : Group) (h : fintype G),
(∀ (H : Group) (h' : fintype H),
@fintype.card H h' < @fintype.card G h → P H h')
→ P G h)
→ ∀ (G : Group) (h : fintype G), P G h :=
begin
intro inductive_step,
suffices : ∀ n (G : Group) (h : fintype G), @fintype.card G h = n → P G h,
{ intros, apply this (@fintype.card G h), refl },
intro n, apply @nat.strong_rec_on (λ n, ∀ (G : Group) (h : fintype G), @fintype.card G h = n → P G h) n,
clear n, intros n ih G h card_eq,
apply inductive_step,
intros H h' hlt,
apply ih (@fintype.card H h') (card_eq ▸ hlt),
refl
end
noncomputable
lemma finite_group.induction_subquot (P : Π (G : Group), fintype G → Sort _)
: (∀ (G : Group) (h : fintype G),
(∀ (H : set G) [inst : is_subgroup H], H ≠ set.univ →
P (@Group.of H (@subtype.group _ _ _ inst))
(@subtype.fintype _ h _ _))
→ (∀ (N : set G) [inst : normal_subgroup N], N ≠ is_subgroup.trivial G →
P (@Group.of (@quotient_group.quotient _ _ N inst.to_is_subgroup)
(@quotient_group.group _ _ N inst))
(@quotient.fintype _ h _ _))
→ P G h)
→ ∀ (G : Group) (h : fintype G), P G h :=
begin
intro inductive_step,
apply finite_group.induction_ord,
intros G h ih,
apply inductive_step,
{ intros H inst h', apply ih,
apply @nat.lt_of_le_of_lt _ (@fintype.card (subtype H) (@subtype.fintype _ h _ _)),
refl,
rw fintype.card_of_subtype (@set.to_finset _ H (@subtype.fintype _ h _ _)),
dsimp [fintype.card], apply finset.card_lt_card,
refine (_ : @set.to_finset _ H (@subtype.fintype _ h _ _) < @finset.univ _ h),
apply lt_of_le_of_ne,
apply finset.subset_univ,
intro h'', apply h', ext,
transitivity true, rw iff_true,
have : x ∈ @set.to_finset _ H (@subtype.fintype _ h _ _), rw h'', apply finset.mem_univ,
rw set.mem_to_finset at this, assumption,
rw true_iff, apply set.mem_univ,
intro, rw set.mem_to_finset, refl },
{ intros N inst hproper,
apply ih,
apply @nat.lt_of_le_of_lt _ (@fintype.card (@quotient_group.quotient _ _ N inst.to_is_subgroup) (@quotient.fintype _ h _ _)),
refl, dsimp [quotient_group.quotient],
have : ∃ x : G, x ∈ N ∧ x ≠ 1,
{ by_contra h, apply hproper,
rw @is_subgroup.eq_trivial_iff _ _ _ inst.to_is_subgroup,
intros, by_contra, apply h,
existsi x, constructor; assumption },
cases this with x hx, cases hx with hN hdist,
apply quotient.card_lt _, exact hdist.symm,
refine (_ : 1⁻¹ * x ∈ N),
rw [one_inv, one_mul], assumption }
end
|
f7b309a856a8ace66a8fed357e8800d9cc258d13
|
12dabd587ce2621d9a4eff9f16e354d02e206c8e
|
/world01/level03.lean
|
d859e5c4c257242cd818692356865d014f62f981
|
[] |
no_license
|
abdelq/natural-number-game
|
a1b5b8f1d52625a7addcefc97c966d3f06a48263
|
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
|
refs/heads/master
| 1,668,606,478,691
| 1,594,175,058,000
| 1,594,175,058,000
| 278,673,209
| 0
| 1
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 126
|
lean
|
import mynat.definition
lemma example3 (a b : mynat) (h : succ a = b) : succ(succ(a)) = succ(b) :=
begin
rw ← h,
refl,
end
|
a6eda5dbb6829cfa8e5296f7e7a40e49064e3d6a
|
d406927ab5617694ec9ea7001f101b7c9e3d9702
|
/src/algebra/graded_monoid.lean
|
9aae3d0e47614cb009e7c560a015eddf4c658b13
|
[
"Apache-2.0"
] |
permissive
|
alreadydone/mathlib
|
dc0be621c6c8208c581f5170a8216c5ba6721927
|
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
|
refs/heads/master
| 1,685,523,275,196
| 1,670,184,141,000
| 1,670,184,141,000
| 287,574,545
| 0
| 0
|
Apache-2.0
| 1,670,290,714,000
| 1,597,421,623,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 21,998
|
lean
|
/-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import algebra.group.inj_surj
import data.list.big_operators.basic
import data.list.range
import group_theory.group_action.defs
import group_theory.submonoid.basic
import data.set_like.basic
import data.sigma.basic
/-!
# Additively-graded multiplicative structures
This module provides a set of heterogeneous typeclasses for defining a multiplicative structure
over the sigma type `graded_monoid A` such that `(*) : A i → A j → A (i + j)`; that is to say, `A`
forms an additively-graded monoid. The typeclasses are:
* `graded_monoid.ghas_one A`
* `graded_monoid.ghas_mul A`
* `graded_monoid.gmonoid A`
* `graded_monoid.gcomm_monoid A`
With the `sigma_graded` locale open, these respectively imbue:
* `has_one (graded_monoid A)`
* `has_mul (graded_monoid A)`
* `monoid (graded_monoid A)`
* `comm_monoid (graded_monoid A)`
the base type `A 0` with:
* `graded_monoid.grade_zero.has_one`
* `graded_monoid.grade_zero.has_mul`
* `graded_monoid.grade_zero.monoid`
* `graded_monoid.grade_zero.comm_monoid`
and the `i`th grade `A i` with `A 0`-actions (`•`) defined as left-multiplication:
* (nothing)
* `graded_monoid.grade_zero.has_smul (A 0)`
* `graded_monoid.grade_zero.mul_action (A 0)`
* (nothing)
For now, these typeclasses are primarily used in the construction of `direct_sum.ring` and the rest
of that file.
## Dependent graded products
This also introduces `list.dprod`, which takes the (possibly non-commutative) product of a list
of graded elements of type `A i`. This definition primarily exist to allow `graded_monoid.mk`
and `direct_sum.of` to be pulled outside a product, such as in `graded_monoid.mk_list_dprod` and
`direct_sum.of_list_dprod`.
## Internally graded monoids
In addition to the above typeclasses, in the most frequent case when `A` is an indexed collection of
`set_like` subobjects (such as `add_submonoid`s, `add_subgroup`s, or `submodule`s), this file
provides the `Prop` typeclasses:
* `set_like.has_graded_one A` (which provides the obvious `graded_monoid.ghas_one A` instance)
* `set_like.has_graded_mul A` (which provides the obvious `graded_monoid.ghas_mul A` instance)
* `set_like.graded_monoid A` (which provides the obvious `graded_monoid.gmonoid A` and
`graded_monoid.gcomm_monoid A` instances)
which respectively provide the API lemmas
* `set_like.one_mem_graded`
* `set_like.mul_mem_graded`
* `set_like.pow_mem_graded`, `set_like.list_prod_map_mem_graded`
Strictly this last class is unecessary as it has no fields not present in its parents, but it is
included for convenience. Note that there is no need for `set_like.graded_ring` or similar, as all
the information it would contain is already supplied by `graded_monoid` when `A` is a collection
of objects satisfying `add_submonoid_class` such as `submodule`s. These constructions are explored
in `algebra.direct_sum.internal`.
This file also defines:
* `set_like.is_homogeneous A` (which says that `a` is homogeneous iff `a ∈ A i` for some `i : ι`)
* `set_like.homogeneous_submonoid A`, which is, as the name suggests, the submonoid consisting of
all the homogeneous elements.
## tags
graded monoid
-/
set_option old_structure_cmd true
variables {ι : Type*}
/-- A type alias of sigma types for graded monoids. -/
def graded_monoid (A : ι → Type*) := sigma A
namespace graded_monoid
instance {A : ι → Type*} [inhabited ι] [inhabited (A default)]: inhabited (graded_monoid A) :=
sigma.inhabited
/-- Construct an element of a graded monoid. -/
def mk {A : ι → Type*} : Π i, A i → graded_monoid A := sigma.mk
/-! ### Typeclasses -/
section defs
variables (A : ι → Type*)
/-- A graded version of `has_one`, which must be of grade 0. -/
class ghas_one [has_zero ι] :=
(one : A 0)
/-- `ghas_one` implies `has_one (graded_monoid A)` -/
instance ghas_one.to_has_one [has_zero ι] [ghas_one A] : has_one (graded_monoid A) :=
⟨⟨_, ghas_one.one⟩⟩
/-- A graded version of `has_mul`. Multiplication combines grades additively, like
`add_monoid_algebra`. -/
class ghas_mul [has_add ι] :=
(mul {i j} : A i → A j → A (i + j))
/-- `ghas_mul` implies `has_mul (graded_monoid A)`. -/
instance ghas_mul.to_has_mul [has_add ι] [ghas_mul A] :
has_mul (graded_monoid A) :=
⟨λ (x y : graded_monoid A), ⟨_, ghas_mul.mul x.snd y.snd⟩⟩
lemma mk_mul_mk [has_add ι] [ghas_mul A] {i j} (a : A i) (b : A j) :
mk i a * mk j b = mk (i + j) (ghas_mul.mul a b) :=
rfl
namespace gmonoid
variables {A} [add_monoid ι] [ghas_mul A] [ghas_one A]
/-- A default implementation of power on a graded monoid, like `npow_rec`.
`gmonoid.gnpow` should be used instead. -/
def gnpow_rec : Π (n : ℕ) {i}, A i → A (n • i)
| 0 i a := cast (congr_arg A (zero_nsmul i).symm) ghas_one.one
| (n + 1) i a := cast (congr_arg A (succ_nsmul i n).symm) (ghas_mul.mul a $ gnpow_rec _ a)
@[simp] lemma gnpow_rec_zero (a : graded_monoid A) : graded_monoid.mk _ (gnpow_rec 0 a.snd) = 1 :=
sigma.ext (zero_nsmul _) (heq_of_cast_eq _ rfl).symm
/-- Tactic used to autofill `graded_monoid.gmonoid.gnpow_zero'` when the default
`graded_monoid.gmonoid.gnpow_rec` is used. -/
meta def apply_gnpow_rec_zero_tac : tactic unit := `[apply graded_monoid.gmonoid.gnpow_rec_zero]
@[simp] lemma gnpow_rec_succ (n : ℕ) (a : graded_monoid A) :
(graded_monoid.mk _ $ gnpow_rec n.succ a.snd) = a * ⟨_, gnpow_rec n a.snd⟩ :=
sigma.ext (succ_nsmul _ _) (heq_of_cast_eq _ rfl).symm
/-- Tactic used to autofill `graded_monoid.gmonoid.gnpow_succ'` when the default
`graded_monoid.gmonoid.gnpow_rec` is used. -/
meta def apply_gnpow_rec_succ_tac : tactic unit := `[apply graded_monoid.gmonoid.gnpow_rec_succ]
end gmonoid
/-- A graded version of `monoid`.
Like `monoid.npow`, this has an optional `gmonoid.gnpow` field to allow definitional control of
natural powers of a graded monoid. -/
class gmonoid [add_monoid ι] extends ghas_mul A, ghas_one A :=
(one_mul (a : graded_monoid A) : 1 * a = a)
(mul_one (a : graded_monoid A) : a * 1 = a)
(mul_assoc (a b c : graded_monoid A) : a * b * c = a * (b * c))
(gnpow : Π (n : ℕ) {i}, A i → A (n • i) := gmonoid.gnpow_rec)
(gnpow_zero' : Π (a : graded_monoid A), graded_monoid.mk _ (gnpow 0 a.snd) = 1
. gmonoid.apply_gnpow_rec_zero_tac)
(gnpow_succ' : Π (n : ℕ) (a : graded_monoid A),
(graded_monoid.mk _ $ gnpow n.succ a.snd) = a * ⟨_, gnpow n a.snd⟩
. gmonoid.apply_gnpow_rec_succ_tac)
/-- `gmonoid` implies a `monoid (graded_monoid A)`. -/
instance gmonoid.to_monoid [add_monoid ι] [gmonoid A] :
monoid (graded_monoid A) :=
{ one := (1), mul := (*),
npow := λ n a, graded_monoid.mk _ (gmonoid.gnpow n a.snd),
npow_zero' := λ a, gmonoid.gnpow_zero' a,
npow_succ' := λ n a, gmonoid.gnpow_succ' n a,
one_mul := gmonoid.one_mul, mul_one := gmonoid.mul_one, mul_assoc := gmonoid.mul_assoc }
lemma mk_pow [add_monoid ι] [gmonoid A] {i} (a : A i) (n : ℕ) :
mk i a ^ n = mk (n • i) (gmonoid.gnpow _ a) :=
begin
induction n with n,
{ rw [pow_zero],
exact (gmonoid.gnpow_zero' ⟨_, a⟩).symm, },
{ rw [pow_succ, n_ih, mk_mul_mk],
exact (gmonoid.gnpow_succ' n ⟨_, a⟩).symm, },
end
/-- A graded version of `comm_monoid`. -/
class gcomm_monoid [add_comm_monoid ι] extends gmonoid A :=
(mul_comm (a : graded_monoid A) (b : graded_monoid A) : a * b = b * a)
/-- `gcomm_monoid` implies a `comm_monoid (graded_monoid A)`, although this is only used as an
instance locally to define notation in `gmonoid` and similar typeclasses. -/
instance gcomm_monoid.to_comm_monoid [add_comm_monoid ι] [gcomm_monoid A] :
comm_monoid (graded_monoid A) :=
{ mul_comm := gcomm_monoid.mul_comm, ..gmonoid.to_monoid A }
end defs
/-! ### Instances for `A 0`
The various `g*` instances are enough to promote the `add_comm_monoid (A 0)` structure to various
types of multiplicative structure.
-/
section grade_zero
variables (A : ι → Type*)
section one
variables [has_zero ι] [ghas_one A]
/-- `1 : A 0` is the value provided in `ghas_one.one`. -/
@[nolint unused_arguments]
instance grade_zero.has_one : has_one (A 0) :=
⟨ghas_one.one⟩
end one
section mul
variables [add_zero_class ι] [ghas_mul A]
/-- `(•) : A 0 → A i → A i` is the value provided in `graded_monoid.ghas_mul.mul`, composed with
an `eq.rec` to turn `A (0 + i)` into `A i`.
-/
instance grade_zero.has_smul (i : ι) : has_smul (A 0) (A i) :=
{ smul := λ x y, (zero_add i).rec (ghas_mul.mul x y) }
/-- `(*) : A 0 → A 0 → A 0` is the value provided in `graded_monoid.ghas_mul.mul`, composed with
an `eq.rec` to turn `A (0 + 0)` into `A 0`.
-/
instance grade_zero.has_mul : has_mul (A 0) :=
{ mul := (•) }
variables {A}
@[simp] lemma mk_zero_smul {i} (a : A 0) (b : A i) : mk _ (a • b) = mk _ a * mk _ b :=
sigma.ext (zero_add _).symm $ eq_rec_heq _ _
@[simp] lemma grade_zero.smul_eq_mul (a b : A 0) : a • b = a * b := rfl
end mul
section monoid
variables [add_monoid ι] [gmonoid A]
instance : has_pow (A 0) ℕ :=
{ pow := λ x n, (nsmul_zero n).rec (gmonoid.gnpow n x : A (n • 0)) }
variables {A}
@[simp] lemma mk_zero_pow (a : A 0) (n : ℕ) : mk _ (a ^ n) = mk _ a ^ n :=
sigma.ext (nsmul_zero n).symm $ eq_rec_heq _ _
variables (A)
/-- The `monoid` structure derived from `gmonoid A`. -/
instance grade_zero.monoid : monoid (A 0) :=
function.injective.monoid (mk 0) sigma_mk_injective rfl mk_zero_smul mk_zero_pow
end monoid
section monoid
variables [add_comm_monoid ι] [gcomm_monoid A]
/-- The `comm_monoid` structure derived from `gcomm_monoid A`. -/
instance grade_zero.comm_monoid : comm_monoid (A 0) :=
function.injective.comm_monoid (mk 0) sigma_mk_injective rfl mk_zero_smul mk_zero_pow
end monoid
section mul_action
variables [add_monoid ι] [gmonoid A]
/-- `graded_monoid.mk 0` is a `monoid_hom`, using the `graded_monoid.grade_zero.monoid` structure.
-/
def mk_zero_monoid_hom : A 0 →* (graded_monoid A) :=
{ to_fun := mk 0, map_one' := rfl, map_mul' := mk_zero_smul }
/-- Each grade `A i` derives a `A 0`-action structure from `gmonoid A`. -/
instance grade_zero.mul_action {i} : mul_action (A 0) (A i) :=
begin
letI := mul_action.comp_hom (graded_monoid A) (mk_zero_monoid_hom A),
exact function.injective.mul_action (mk i) sigma_mk_injective mk_zero_smul,
end
end mul_action
end grade_zero
end graded_monoid
/-! ### Dependent products of graded elements -/
section dprod
variables {α : Type*} {A : ι → Type*} [add_monoid ι] [graded_monoid.gmonoid A]
/-- The index used by `list.dprod`. Propositionally this is equal to `(l.map fι).sum`, but
definitionally it needs to have a different form to avoid introducing `eq.rec`s in `list.dprod`. -/
def list.dprod_index (l : list α) (fι : α → ι) : ι :=
l.foldr (λ i b, fι i + b) 0
@[simp] lemma list.dprod_index_nil (fι : α → ι) : ([] : list α).dprod_index fι = 0 := rfl
@[simp] lemma list.dprod_index_cons (a : α) (l : list α) (fι : α → ι) :
(a :: l).dprod_index fι = fι a + l.dprod_index fι := rfl
lemma list.dprod_index_eq_map_sum (l : list α) (fι : α → ι) :
l.dprod_index fι = (l.map fι).sum :=
begin
dunfold list.dprod_index,
induction l,
{ simp, },
{ simp [l_ih], },
end
/-- A dependent product for graded monoids represented by the indexed family of types `A i`.
This is a dependent version of `(l.map fA).prod`.
For a list `l : list α`, this computes the product of `fA a` over `a`, where each `fA` is of type
`A (fι a)`. -/
def list.dprod (l : list α) (fι : α → ι) (fA : Π a, A (fι a)) :
A (l.dprod_index fι) :=
l.foldr_rec_on _ _ graded_monoid.ghas_one.one (λ i x a ha, graded_monoid.ghas_mul.mul (fA a) x)
@[simp] lemma list.dprod_nil (fι : α → ι) (fA : Π a, A (fι a)) :
(list.nil : list α).dprod fι fA = graded_monoid.ghas_one.one := rfl
-- the `( : _)` in this lemma statement results in the type on the RHS not being unfolded, which
-- is nicer in the goal view.
@[simp] lemma list.dprod_cons (fι : α → ι) (fA : Π a, A (fι a)) (a : α) (l : list α) :
(a :: l).dprod fι fA = (graded_monoid.ghas_mul.mul (fA a) (l.dprod fι fA) : _) := rfl
lemma graded_monoid.mk_list_dprod (l : list α) (fι : α → ι) (fA : Π a, A (fι a)) :
graded_monoid.mk _ (l.dprod fι fA) = (l.map (λ a, graded_monoid.mk (fι a) (fA a))).prod :=
begin
induction l,
{ simp, refl },
{ simp [←l_ih, graded_monoid.mk_mul_mk, list.prod_cons],
refl, },
end
/-- A variant of `graded_monoid.mk_list_dprod` for rewriting in the other direction. -/
lemma graded_monoid.list_prod_map_eq_dprod (l : list α) (f : α → graded_monoid A) :
(l.map f).prod = graded_monoid.mk _ (l.dprod (λ i, (f i).1) (λ i, (f i).2)) :=
begin
rw [graded_monoid.mk_list_dprod, graded_monoid.mk],
simp_rw sigma.eta,
end
lemma graded_monoid.list_prod_of_fn_eq_dprod {n : ℕ} (f : fin n → graded_monoid A) :
(list.of_fn f).prod =
graded_monoid.mk _ ((list.fin_range n).dprod (λ i, (f i).1) (λ i, (f i).2)) :=
by rw [list.of_fn_eq_map, graded_monoid.list_prod_map_eq_dprod]
end dprod
/-! ### Concrete instances -/
section
variables (ι) {R : Type*}
@[simps one]
instance has_one.ghas_one [has_zero ι] [has_one R] : graded_monoid.ghas_one (λ i : ι, R) :=
{ one := 1 }
@[simps mul]
instance has_mul.ghas_mul [has_add ι] [has_mul R] : graded_monoid.ghas_mul (λ i : ι, R) :=
{ mul := λ i j, (*) }
/-- If all grades are the same type and themselves form a monoid, then there is a trivial grading
structure. -/
@[simps gnpow]
instance monoid.gmonoid [add_monoid ι] [monoid R] : graded_monoid.gmonoid (λ i : ι, R) :=
{ one_mul := λ a, sigma.ext (zero_add _) (heq_of_eq (one_mul _)),
mul_one := λ a, sigma.ext (add_zero _) (heq_of_eq (mul_one _)),
mul_assoc := λ a b c, sigma.ext (add_assoc _ _ _) (heq_of_eq (mul_assoc _ _ _)),
gnpow := λ n i a, a ^ n,
gnpow_zero' := λ a, sigma.ext (zero_nsmul _) (heq_of_eq (monoid.npow_zero' _)),
gnpow_succ' := λ n ⟨i, a⟩, sigma.ext (succ_nsmul _ _) (heq_of_eq (monoid.npow_succ' _ _)),
..has_one.ghas_one ι,
..has_mul.ghas_mul ι }
/-- If all grades are the same type and themselves form a commutative monoid, then there is a
trivial grading structure. -/
instance comm_monoid.gcomm_monoid [add_comm_monoid ι] [comm_monoid R] :
graded_monoid.gcomm_monoid (λ i : ι, R) :=
{ mul_comm := λ a b, sigma.ext (add_comm _ _) (heq_of_eq (mul_comm _ _)),
..monoid.gmonoid ι }
/-- When all the indexed types are the same, the dependent product is just the regular product. -/
@[simp] lemma list.dprod_monoid {α} [add_monoid ι] [monoid R] (l : list α) (fι : α → ι)
(fA : α → R) :
(l.dprod fι fA : (λ i : ι, R) _) = ((l.map fA).prod : _) :=
begin
induction l,
{ rw [list.dprod_nil, list.map_nil, list.prod_nil], refl },
{ rw [list.dprod_cons, list.map_cons, list.prod_cons, l_ih], refl },
end
end
/-! ### Shorthands for creating instance of the above typeclasses for collections of subobjects -/
section subobjects
variables {R : Type*}
/-- A version of `graded_monoid.ghas_one` for internally graded objects. -/
class set_like.has_graded_one {S : Type*} [set_like S R] [has_one R] [has_zero ι]
(A : ι → S) : Prop :=
(one_mem : (1 : R) ∈ A 0)
lemma set_like.one_mem_graded {S : Type*} [set_like S R] [has_one R] [has_zero ι] (A : ι → S)
[set_like.has_graded_one A] : (1 : R) ∈ A 0 := set_like.has_graded_one.one_mem
instance set_like.ghas_one {S : Type*} [set_like S R] [has_one R] [has_zero ι] (A : ι → S)
[set_like.has_graded_one A] : graded_monoid.ghas_one (λ i, A i) :=
{ one := ⟨1, set_like.one_mem_graded _⟩ }
@[simp] lemma set_like.coe_ghas_one {S : Type*} [set_like S R] [has_one R] [has_zero ι] (A : ι → S)
[set_like.has_graded_one A] : ↑(@graded_monoid.ghas_one.one _ (λ i, A i) _ _) = (1 : R) := rfl
/-- A version of `graded_monoid.ghas_one` for internally graded objects. -/
class set_like.has_graded_mul {S : Type*} [set_like S R] [has_mul R] [has_add ι]
(A : ι → S) : Prop :=
(mul_mem : ∀ ⦃i j⦄ {gi gj}, gi ∈ A i → gj ∈ A j → gi * gj ∈ A (i + j))
lemma set_like.mul_mem_graded {S : Type*} [set_like S R] [has_mul R] [has_add ι] {A : ι → S}
[set_like.has_graded_mul A] ⦃i j⦄ {gi gj} (hi : gi ∈ A i) (hj : gj ∈ A j) :
gi * gj ∈ A (i + j) :=
set_like.has_graded_mul.mul_mem hi hj
instance set_like.ghas_mul {S : Type*} [set_like S R] [has_mul R] [has_add ι] (A : ι → S)
[set_like.has_graded_mul A] :
graded_monoid.ghas_mul (λ i, A i) :=
{ mul := λ i j a b, ⟨(a * b : R), set_like.mul_mem_graded a.prop b.prop⟩ }
@[simp] lemma set_like.coe_ghas_mul {S : Type*} [set_like S R] [has_mul R] [has_add ι] (A : ι → S)
[set_like.has_graded_mul A] {i j : ι} (x : A i) (y : A j) :
↑(@graded_monoid.ghas_mul.mul _ (λ i, A i) _ _ _ _ x y) = (x * y : R) := rfl
/-- A version of `graded_monoid.gmonoid` for internally graded objects. -/
class set_like.graded_monoid {S : Type*} [set_like S R] [monoid R] [add_monoid ι]
(A : ι → S) extends set_like.has_graded_one A, set_like.has_graded_mul A : Prop
namespace set_like
variables {S : Type*} [set_like S R] [monoid R] [add_monoid ι]
variables {A : ι → S} [set_like.graded_monoid A]
lemma pow_mem_graded (n : ℕ) {r : R} {i : ι} (h : r ∈ A i) : r ^ n ∈ A (n • i) :=
begin
induction n,
{ rw [pow_zero, zero_nsmul], exact one_mem_graded _ },
{ rw [pow_succ', succ_nsmul'], exact mul_mem_graded n_ih h },
end
lemma list_prod_map_mem_graded {ι'} (l : list ι') (i : ι' → ι) (r : ι' → R)
(h : ∀ j ∈ l, r j ∈ A (i j)) :
(l.map r).prod ∈ A (l.map i).sum :=
begin
induction l,
{ rw [list.map_nil, list.map_nil, list.prod_nil, list.sum_nil],
exact one_mem_graded _ },
{ rw [list.map_cons, list.map_cons, list.prod_cons, list.sum_cons],
exact mul_mem_graded
(h _ $ list.mem_cons_self _ _) (l_ih $ λ j hj, h _ $ list.mem_cons_of_mem _ hj) },
end
lemma list_prod_of_fn_mem_graded {n} (i : fin n → ι) (r : fin n → R) (h : ∀ j, r j ∈ A (i j)) :
(list.of_fn r).prod ∈ A (list.of_fn i).sum :=
begin
rw [list.of_fn_eq_map, list.of_fn_eq_map],
exact list_prod_map_mem_graded _ _ _ (λ _ _, h _),
end
end set_like
/-- Build a `gmonoid` instance for a collection of subobjects. -/
instance set_like.gmonoid {S : Type*} [set_like S R] [monoid R] [add_monoid ι] (A : ι → S)
[set_like.graded_monoid A] :
graded_monoid.gmonoid (λ i, A i) :=
{ one_mul := λ ⟨i, a, h⟩, sigma.subtype_ext (zero_add _) (one_mul _),
mul_one := λ ⟨i, a, h⟩, sigma.subtype_ext (add_zero _) (mul_one _),
mul_assoc := λ ⟨i, a, ha⟩ ⟨j, b, hb⟩ ⟨k, c, hc⟩,
sigma.subtype_ext (add_assoc _ _ _) (mul_assoc _ _ _),
gnpow := λ n i a, ⟨a ^ n, set_like.pow_mem_graded n a.prop⟩,
gnpow_zero' := λ n, sigma.subtype_ext (zero_nsmul _) (pow_zero _),
gnpow_succ' := λ n a, sigma.subtype_ext (succ_nsmul _ _) (pow_succ _ _),
..set_like.ghas_one A,
..set_like.ghas_mul A }
@[simp] lemma set_like.coe_gnpow {S : Type*} [set_like S R] [monoid R] [add_monoid ι] (A : ι → S)
[set_like.graded_monoid A] {i : ι} (x : A i) (n : ℕ) :
↑(@graded_monoid.gmonoid.gnpow _ (λ i, A i) _ _ n _ x) = (x ^ n : R) := rfl
/-- Build a `gcomm_monoid` instance for a collection of subobjects. -/
instance set_like.gcomm_monoid {S : Type*} [set_like S R] [comm_monoid R] [add_comm_monoid ι]
(A : ι → S) [set_like.graded_monoid A] :
graded_monoid.gcomm_monoid (λ i, A i) :=
{ mul_comm := λ ⟨i, a, ha⟩ ⟨j, b, hb⟩, sigma.subtype_ext (add_comm _ _) (mul_comm _ _),
..set_like.gmonoid A}
section dprod
open set_like set_like.graded_monoid
variables {α S : Type*} [set_like S R] [monoid R] [add_monoid ι]
/-- Coercing a dependent product of subtypes is the same as taking the regular product of the
coercions. -/
@[simp] lemma set_like.coe_list_dprod (A : ι → S) [set_like.graded_monoid A]
(fι : α → ι) (fA : Π a, A (fι a)) (l : list α) :
↑(l.dprod fι fA : (λ i, ↥(A i)) _) = (list.prod (l.map (λ a, fA a)) : R) :=
begin
induction l,
{ rw [list.dprod_nil, coe_ghas_one, list.map_nil, list.prod_nil] },
{ rw [list.dprod_cons, coe_ghas_mul, list.map_cons, list.prod_cons, l_ih], },
end
include R
/-- A version of `list.coe_dprod_set_like` with `subtype.mk`. -/
lemma set_like.list_dprod_eq (A : ι → S) [set_like.graded_monoid A]
(fι : α → ι) (fA : Π a, A (fι a)) (l : list α) :
(l.dprod fι fA : (λ i, ↥(A i)) _) =
⟨list.prod (l.map (λ a, fA a)), (l.dprod_index_eq_map_sum fι).symm ▸
list_prod_map_mem_graded l _ _ (λ i hi, (fA i).prop)⟩ :=
subtype.ext $ set_like.coe_list_dprod _ _ _ _
end dprod
end subobjects
section homogeneous_elements
variables {R S : Type*} [set_like S R]
/-- An element `a : R` is said to be homogeneous if there is some `i : ι` such that `a ∈ A i`. -/
def set_like.is_homogeneous (A : ι → S) (a : R) : Prop := ∃ i, a ∈ A i
@[simp] lemma set_like.is_homogeneous_coe {A : ι → S} {i} (x : A i) :
set_like.is_homogeneous A (x : R) :=
⟨i, x.prop⟩
lemma set_like.is_homogeneous_one [has_zero ι] [has_one R]
(A : ι → S) [set_like.has_graded_one A] : set_like.is_homogeneous A (1 : R) :=
⟨0, set_like.one_mem_graded _⟩
lemma set_like.is_homogeneous.mul [has_add ι] [has_mul R] {A : ι → S}
[set_like.has_graded_mul A] {a b : R} :
set_like.is_homogeneous A a → set_like.is_homogeneous A b → set_like.is_homogeneous A (a * b)
| ⟨i, hi⟩ ⟨j, hj⟩ := ⟨i + j, set_like.mul_mem_graded hi hj⟩
/-- When `A` is a `set_like.graded_monoid A`, then the homogeneous elements forms a submonoid. -/
def set_like.homogeneous_submonoid [add_monoid ι] [monoid R]
(A : ι → S) [set_like.graded_monoid A] : submonoid R :=
{ carrier := { a | set_like.is_homogeneous A a },
one_mem' := set_like.is_homogeneous_one A,
mul_mem' := λ a b, set_like.is_homogeneous.mul }
end homogeneous_elements
|
64901a486f265831bbf76250c29616450a94fcaf
|
856e2e1615a12f95b551ed48fa5b03b245abba44
|
/src/algebra/pi_instances.lean
|
21b71230521b045c5459d612a2f795808ae24803
|
[
"Apache-2.0"
] |
permissive
|
pimsp/mathlib
|
8b77e1ccfab21703ba8fbe65988c7de7765aa0e5
|
913318ca9d6979686996e8d9b5ebf7e74aae1c63
|
refs/heads/master
| 1,669,812,465,182
| 1,597,133,610,000
| 1,597,133,610,000
| 281,890,685
| 1
| 0
| null | 1,595,491,577,000
| 1,595,491,576,000
| null |
UTF-8
|
Lean
| false
| false
| 19,257
|
lean
|
/-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot
-/
import algebra.module
import ring_theory.subring
import ring_theory.prod
import data.fintype.basic
open_locale big_operators
/-!
# Pi instances for algebraic structures
## Implementation notes
We don't use `by pi_instance` directly because currently instances generated by this tactic have
slightly wrong definitions (extra `id`s and `group.mul` instead of `has_mul.mul`). These little
bugs prevent Lean from applying a `simp` lemma about `pi.has_one` to `1` coming from `pi.group`.
## TODO
Properly fix `tactic.pi_instance`.
-/
namespace pi
universes u v w
variable {I : Type u} -- The indexing type
variable {f : I → Type v} -- The family of types already equipped with instances
variables (x y : Π i, f i) (i : I)
@[to_additive] instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ _, 1⟩
@[simp, to_additive] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl
@[to_additive]
instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ f g i, f i * g i⟩
@[simp, to_additive] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl
@[to_additive] instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ f i, (f i)⁻¹⟩
@[simp, to_additive] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl
instance has_scalar {α : Type*} [Π i, has_scalar α $ f i] :
has_scalar α (Π i : I, f i) :=
⟨λ s x, λ i, s • (x i)⟩
@[simp] lemma smul_apply {α : Type*} [Π i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl
instance has_scalar' {g : I → Type*} [Π i, has_scalar (f i) (g i)] :
has_scalar (Π i, f i) (Π i : I, g i) :=
⟨λ s x, λ i, (s i) • (x i)⟩
@[simp]
lemma smul_apply' {g : I → Type*} [∀ i, has_scalar (f i) (g i)] (s : Π i, f i) (x : Π i, g i) :
(s • x) i = s i • x i :=
rfl
@[to_additive add_semigroup]
instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) :=
by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field
@[to_additive add_comm_semigroup]
instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) :=
by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field
@[to_additive add_monoid]
instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field
@[to_additive add_comm_monoid]
instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field
@[to_additive add_group]
instance group [∀ i, group $ f i] : group (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, .. };
tactic.pi_instance_derive_field
@[to_additive add_comm_group]
instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) :=
by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, .. };
tactic.pi_instance_derive_field
instance mul_zero_class [Π i, mul_zero_class $ f i] : mul_zero_class (Π i : I, f i) :=
by refine_struct { zero := (0 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field
instance distrib [Π i, distrib $ f i] : distrib (Π i : I, f i) :=
by refine_struct { add := (+), mul := (*), .. }; tactic.pi_instance_derive_field
instance semiring [∀ i, semiring $ f i] : semiring (Π i : I, f i) :=
by refine_struct { zero := (0 : Π i, f i), one := 1, add := (+), mul := (*), .. };
tactic.pi_instance_derive_field
instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) :=
by refine_struct { zero := (0 : Π i, f i), one := 1, add := (+), mul := (*),
neg := has_neg.neg, .. }; tactic.pi_instance_derive_field
instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) :=
by refine_struct { zero := (0 : Π i, f i), one := 1, add := (+), mul := (*),
neg := has_neg.neg, .. }; tactic.pi_instance_derive_field
instance mul_action (α) {m : monoid α} [Π i, mul_action α $ f i] :
@mul_action α (Π i : I, f i) m :=
{ smul := (•),
mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _,
one_smul := λ f, funext $ λ i, one_smul α _ }
instance mul_action' {g : I → Type*} {m : Π i, monoid (f i)} [Π i, mul_action (f i) (g i)] :
@mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) :=
{ smul := (•),
mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _,
one_smul := λ f, funext $ λ i, one_smul _ _ }
instance distrib_mul_action (α) {m : monoid α} {n : ∀ i, add_monoid $ f i} [∀ i, distrib_mul_action α $ f i] :
@distrib_mul_action α (Π i : I, f i) m (@pi.add_monoid I f n) :=
{ smul_zero := λ c, funext $ λ i, smul_zero _,
smul_add := λ c f g, funext $ λ i, smul_add _ _ _,
..pi.mul_action _ }
instance distrib_mul_action' {g : I → Type*} {m : Π i, monoid (f i)} {n : Π i, add_monoid $ g i}
[Π i, distrib_mul_action (f i) (g i)] :
@distrib_mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) (@pi.add_monoid I g n) :=
{ smul_add := by { intros, ext x, apply smul_add },
smul_zero := by { intros, ext x, apply smul_zero } }
variables (I f)
instance semimodule (α) {r : semiring α} {m : ∀ i, add_comm_monoid $ f i} [∀ i, semimodule α $ f i] :
@semimodule α (Π i : I, f i) r (@pi.add_comm_monoid I f m) :=
{ add_smul := λ c f g, funext $ λ i, add_smul _ _ _,
zero_smul := λ f, funext $ λ i, zero_smul α _,
..pi.distrib_mul_action _ }
variables {I f}
instance semimodule' {g : I → Type*} {r : Π i, semiring (f i)} {m : Π i, add_comm_monoid (g i)}
[Π i, semimodule (f i) (g i)] :
semimodule (Π i, f i) (Π i, g i) :=
{ add_smul := by { intros, ext1, apply add_smul },
zero_smul := by { intros, ext1, apply zero_smul } }
@[to_additive add_left_cancel_semigroup]
instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] :
left_cancel_semigroup (Π i : I, f i) :=
by refine_struct { mul := (*) }; tactic.pi_instance_derive_field
@[to_additive add_right_cancel_semigroup]
instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] :
right_cancel_semigroup (Π i : I, f i) :=
by refine_struct { mul := (*) }; tactic.pi_instance_derive_field
@[to_additive ordered_cancel_add_comm_monoid]
instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] :
ordered_cancel_comm_monoid (Π i : I, f i) :=
by refine_struct { mul := (*), one := (1 : Π i, f i), le := (≤), lt := (<), .. pi.partial_order };
tactic.pi_instance_derive_field
@[to_additive ordered_add_comm_group]
instance ordered_comm_group [∀ i, ordered_comm_group $ f i] :
ordered_comm_group (Π i : I, f i) :=
{ mul_le_mul_left := λ x y hxy c i, mul_le_mul_left' (hxy i) _,
..pi.comm_group,
..pi.partial_order }
@[simp] lemma sub_apply [∀ i, add_group $ f i] : (x - y) i = x i - y i := rfl
@[to_additive]
lemma list_prod_apply {α : Type*} {β : α → Type*} [∀a, monoid (β a)] (a : α) :
∀ (l : list (Πa, β a)), l.prod a = (l.map (λf:Πa, β a, f a)).prod
| [] := rfl
| (f :: l) := by simp [mul_apply f l.prod a, list_prod_apply l]
@[to_additive]
lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α)
(s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod :=
quotient.induction_on s $ assume l, begin simp [list_prod_apply a l] end
@[to_additive]
lemma finset_prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α)
(s : finset γ) (g : γ → Πa, β a) : (∏ c in s, g c) a = ∏ c in s, g c a :=
show (s.val.map g).prod a = (s.val.map (λc, g c a)).prod,
by rw [multiset_prod_apply, multiset.map_map]
/-- A family of ring homomorphisms `f a : γ →+* β a` defines a ring homomorphism
`pi.ring_hom f : γ →+* Π a, β a` given by `pi.ring_hom f x b = f b x`. -/
protected def ring_hom
{α : Type u} {β : α → Type v} [R : Π a : α, semiring (β a)]
{γ : Type w} [semiring γ] (f : Π a : α, γ →+* β a) :
γ →+* Π a, β a :=
{ to_fun := λ x b, f b x,
map_add' := λ x y, funext $ λ z, (f z).map_add x y,
map_mul' := λ x y, funext $ λ z, (f z).map_mul x y,
map_one' := funext $ λ z, (f z).map_one,
map_zero' := funext $ λ z, (f z).map_zero }
instance is_ring_hom_pi
{α : Type u} {β : α → Type v} [R : Π a : α, ring (β a)]
{γ : Type w} [ring γ]
(f : Π a : α, γ → β a) [Rh : Π a : α, is_ring_hom (f a)] :
is_ring_hom (λ x b, f b x) :=
(show γ →+* Π a, β a, from pi.ring_hom (λ a, ring_hom.of (f a))).is_ring_hom
-- Note that we only define `single` here for dependent functions with additive fibres.
section
variables [decidable_eq I]
variables [Π i, has_zero (f i)]
/-- The function supported at `i`, with value `x` there. -/
def single (i : I) (x : f i) : Π i, f i :=
λ i', if h : i' = i then (by { subst h, exact x }) else 0
@[simp]
lemma single_eq_same (i : I) (x : f i) : single i x i = x :=
begin
dsimp [single],
split_ifs,
{ refl, },
{ exfalso, exact h rfl, }
end
@[simp]
lemma single_eq_of_ne {i i' : I} (h : i' ≠ i) (x : f i) : single i x i' = 0 :=
begin
dsimp [single],
split_ifs with h',
{ exfalso, exact h h', },
{ refl, }
end
end
end pi
section
universes u v
variable {I : Type u} -- The indexing type
variable (f : I → Type v) -- The family of types already equipped with instances
variables [Π i, monoid (f i)]
/-- Evaluation of functions into an indexed collection of monoids at a point is a monoid
homomorphism. -/
@[to_additive "Evaluation of functions into an indexed collection of additive monoids at a point
is an additive monoid homomorphism."]
def monoid_hom.apply (i : I) : (Π i, f i) →* f i :=
{ to_fun := λ g, g i,
map_one' := rfl,
map_mul' := λ x y, rfl, }
@[simp, to_additive]
lemma monoid_hom.apply_apply (i : I) (g : Π i, f i) : (monoid_hom.apply f i) g = g i := rfl
end
section
universes u v
variable {I : Type u} -- The indexing type
variable (f : I → Type v) -- The family of types already equipped with instances
variables [Π i, semiring (f i)]
/-- Evaluation of functions into an indexed collection of monoids at a point is a monoid homomorphism. -/
def ring_hom.apply (i : I) : (Π i, f i) →+* f i :=
{ ..(monoid_hom.apply f i),
..(add_monoid_hom.apply f i) }
@[simp]
lemma ring_hom.apply_apply (i : I) (g : Π i, f i) : (ring_hom.apply f i) g = g i := rfl
end
section
variables {I : Type*} (Z : I → Type*)
variables [Π i, comm_monoid (Z i)]
@[simp, to_additive]
lemma finset.prod_apply {γ : Type*} {s : finset γ} (h : γ → (Π i, Z i)) (i : I) :
(∏ g in s, h g) i = ∏ g in s, h g i :=
begin
classical,
induction s using finset.induction_on with b s nmem ih,
{ simp only [finset.prod_empty], refl },
{ simp only [nmem, finset.prod_insert, not_false_iff],
rw pi.mul_apply (h b) _ i,
rw ih, }
end
end
section
-- As we only defined `single` into `add_monoid`, we only prove the `finset.sum` version here.
variables {I : Type*} [decidable_eq I] {Z : I → Type*}
variables [Π i, add_comm_monoid (Z i)]
lemma finset.univ_sum_single [fintype I] (f : Π i, Z i) :
∑ i, pi.single i (f i) = f :=
begin
ext a,
rw [finset.sum_apply, finset.sum_eq_single a],
{ simp, },
{ intros b _ h, simp [h.symm], },
{ intro h, exfalso, simpa using h, },
end
end
section
open pi
variables {I : Type*} [decidable_eq I]
variable (f : I → Type*)
section
variables [Π i, add_monoid (f i)]
/-- The additive monoid homomorphism including a single additive monoid
into a dependent family of additive monoids, as functions supported at a point. -/
def add_monoid_hom.single (i : I) : f i →+ Π i, f i :=
{ to_fun := λ x, single i x,
map_zero' :=
begin
ext i', by_cases h : i' = i,
{ subst h, simp only [single_eq_same], refl, },
{ simp only [h, single_eq_of_ne, ne.def, not_false_iff], refl, },
end,
map_add' := λ x y,
begin
ext i', by_cases h : i' = i,
-- FIXME in the next two `simp only`s,
-- it would be really nice to not have to provide the arguments to `add_apply`.
{ subst h, simp only [single_eq_same, add_apply (single i' x) (single i' y) i'], },
{ simp only [h, add_zero, single_eq_of_ne, add_apply (single i x) (single i y) i', ne.def, not_false_iff], },
end, }
@[simp]
lemma add_monoid_hom.single_apply {i : I} (x : f i) : (add_monoid_hom.single f i) x = single i x := rfl
end
section
variables {f}
variables [Π i, add_comm_monoid (f i)]
@[ext]
lemma add_monoid_hom.functions_ext [fintype I] (G : Type*) [add_comm_monoid G] (g h : (Π i, f i) →+ G)
(w : ∀ (i : I) (x : f i), g (single i x) = h (single i x)) : g = h :=
begin
ext k,
rw [←finset.univ_sum_single k, add_monoid_hom.map_sum, add_monoid_hom.map_sum],
apply finset.sum_congr rfl,
intros,
apply w,
end
end
section
variables {f}
variables [Π i, semiring (f i)]
-- we need `apply`+`convert` because Lean fails to unify different `add_monoid` instances
-- on `Π i, f i`
@[ext]
lemma ring_hom.functions_ext [fintype I] (G : Type*) [semiring G] (g h : (Π i, f i) →+* G)
(w : ∀ (i : I) (x : f i), g (single i x) = h (single i x)) : g = h :=
begin
apply ring_hom.coe_add_monoid_hom_injective,
convert add_monoid_hom.functions_ext _ _ _ _; assumption
end
end
end
namespace prod
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {p q : α × β}
@[to_additive is_add_monoid_hom]
lemma fst.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.fst : α × β → α) :=
{ map_mul := λ _ _, rfl, map_one := rfl }
@[to_additive is_add_monoid_hom]
lemma snd.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.snd : α × β → β) :=
{ map_mul := λ _ _, rfl, map_one := rfl }
@[to_additive is_add_group_hom]
lemma fst.is_group_hom [group α] [group β] : is_group_hom (prod.fst : α × β → α) :=
{ map_mul := λ _ _, rfl }
@[to_additive is_add_group_hom]
lemma snd.is_group_hom [group α] [group β] : is_group_hom (prod.snd : α × β → β) :=
{ map_mul := λ _ _, rfl }
attribute [instance] fst.is_monoid_hom fst.is_add_monoid_hom snd.is_monoid_hom snd.is_add_monoid_hom
fst.is_group_hom fst.is_add_group_hom snd.is_group_hom snd.is_add_group_hom
@[to_additive]
lemma fst_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} :
(∏ c in t, f c).1 = ∏ c in t, (f c).1 :=
(monoid_hom.fst α β).map_prod f t
@[to_additive]
lemma snd_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} :
(∏ c in t, f c).2 = ∏ c in t, (f c).2 :=
(monoid_hom.snd α β).map_prod f t
instance fst.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.fst : α × β → α) :=
(ring_hom.fst α β).is_semiring_hom
instance snd.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.snd : α × β → β) :=
(ring_hom.snd α β).is_semiring_hom
instance fst.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.fst : α × β → α) :=
(ring_hom.fst α β).is_ring_hom
instance snd.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.snd : α × β → β) :=
(ring_hom.snd α β).is_ring_hom
/-- Left injection function for the inner product
From a vector space (and also group and module) perspective the product is the same as the sum of
two vector spaces. `inl` and `inr` provide the corresponding injection functions.
-/
def inl [has_zero β] (a : α) : α × β := (a, 0)
/-- Right injection function for the inner product -/
def inr [has_zero α] (b : β) : α × β := (0, b)
lemma inl_injective [has_zero β] : function.injective (inl : α → α × β) :=
assume x y h, (prod.mk.inj_iff.mp h).1
lemma inr_injective [has_zero α] : function.injective (inr : β → α × β) :=
assume x y h, (prod.mk.inj_iff.mp h).2
@[simp] lemma inl_eq_inl [has_zero β] {a₁ a₂ : α} : (inl a₁ : α × β) = inl a₂ ↔ a₁ = a₂ :=
iff.intro (assume h, inl_injective h) (assume h, h ▸ rfl)
@[simp] lemma inr_eq_inr [has_zero α] {b₁ b₂ : β} : (inr b₁ : α × β) = inr b₂ ↔ b₁ = b₂ :=
iff.intro (assume h, inr_injective h) (assume h, h ▸ rfl)
@[simp] lemma inl_eq_inr [has_zero α] [has_zero β] {a : α} {b : β} :
inl a = inr b ↔ a = 0 ∧ b = 0 :=
by constructor; simp [inl, inr] {contextual := tt}
@[simp] lemma inr_eq_inl [has_zero α] [has_zero β] {a : α} {b : β} :
inr b = inl a ↔ a = 0 ∧ b = 0 :=
by constructor; simp [inl, inr] {contextual := tt}
@[simp] lemma fst_inl [has_zero β] (a : α) : (inl a : α × β).1 = a := rfl
@[simp] lemma snd_inl [has_zero β] (a : α) : (inl a : α × β).2 = 0 := rfl
@[simp] lemma fst_inr [has_zero α] (b : β) : (inr b : α × β).1 = 0 := rfl
@[simp] lemma snd_inr [has_zero α] (b : β) : (inr b : α × β).2 = b := rfl
instance [has_scalar α β] [has_scalar α γ] : has_scalar α (β × γ) := ⟨λa p, (a • p.1, a • p.2)⟩
@[simp] theorem smul_fst [has_scalar α β] [has_scalar α γ]
(a : α) (x : β × γ) : (a • x).1 = a • x.1 := rfl
@[simp] theorem smul_snd [has_scalar α β] [has_scalar α γ]
(a : α) (x : β × γ) : (a • x).2 = a • x.2 := rfl
@[simp] theorem smul_mk [has_scalar α β] [has_scalar α γ]
(a : α) (b : β) (c : γ) : a • (b, c) = (a • b, a • c) := rfl
instance {r : semiring α} [add_comm_monoid β] [add_comm_monoid γ]
[semimodule α β] [semimodule α γ] : semimodule α (β × γ) :=
{ smul_add := assume a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩,
add_smul := assume a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩,
mul_smul := assume a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩,
one_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩,
zero_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩,
smul_zero := assume a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩,
.. prod.has_scalar }
section substructures
variables (s : set α) (t : set β)
@[to_additive is_add_submonoid]
instance [monoid α] [monoid β] [is_submonoid s] [is_submonoid t] :
is_submonoid (s.prod t) :=
{ one_mem := by rw set.mem_prod; split; apply is_submonoid.one_mem,
mul_mem := by intros; rw set.mem_prod at *; split; apply is_submonoid.mul_mem; tauto }
@[to_additive prod.is_add_subgroup.prod]
instance is_subgroup.prod [group α] [group β] [is_subgroup s] [is_subgroup t] :
is_subgroup (s.prod t) :=
{ inv_mem := by intros; rw set.mem_prod at *; split; apply is_subgroup.inv_mem; tauto,
.. prod.is_submonoid s t }
instance is_subring.prod [ring α] [ring β] [is_subring s] [is_subring t] :
is_subring (s.prod t) :=
{ .. prod.is_submonoid s t, .. prod.is_add_subgroup.prod s t }
end substructures
end prod
namespace finset
@[to_additive prod_mk_sum]
lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ)
(f : γ → α) (g : γ → β) : (∏ x in s, f x, ∏ x in s, g x) = ∏ x in s, (f x, g x) :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt})
end finset
|
dbf632634672411e4a2bcd801780db1f33dd0047
|
4727251e0cd73359b15b664c3170e5d754078599
|
/src/category_theory/sites/cover_lifting.lean
|
6e3eb8f8408672d1f5a6febfb75f426f8b066922
|
[
"Apache-2.0"
] |
permissive
|
Vierkantor/mathlib
|
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
|
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
|
refs/heads/master
| 1,658,323,012,449
| 1,652,256,003,000
| 1,652,256,003,000
| 209,296,341
| 0
| 1
|
Apache-2.0
| 1,568,807,655,000
| 1,568,807,655,000
| null |
UTF-8
|
Lean
| false
| false
| 13,246
|
lean
|
/-
Copyright (c) 2021 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import category_theory.sites.sheaf
import category_theory.limits.kan_extension
import category_theory.sites.cover_preserving
/-!
# Cover-lifting functors between sites.
We define cover-lifting functors between sites as functors that pull covering sieves back to
covering sieves. This concept is also known as *cocontinuous functors* or
*cover-reflecting functors*, but we have chosen this name following [MM92] in order to avoid
potential naming collision or confusion with the general definition of cocontinuous functors
between categories as functors preserving small colimits.
The definition given here seems stronger than the definition found elsewhere,
but they are actually equivalent via `category_theory.grothendieck_topology.superset_covering`.
(The precise statement is not formalized, but follows from it quite trivially).
## Main definitions
* `category_theory.sites.cover_lifting`: a functor between sites is cover-lifting if it
pulls back covering sieves to covering sieves
* `category_theory.sites.copullback`: A cover-lifting functor `G : (C, J) ⥤ (D, K)` induces a
morphism of sites in the same direction as the functor.
## Main results
* `category_theory.sites.Ran_is_sheaf_of_cover_lifting`: If `G : C ⥤ D` is cover_lifting, then
`Ran G.op` (`ₚu`) as a functor `(Cᵒᵖ ⥤ A) ⥤ (Dᵒᵖ ⥤ A)` of presheaves maps sheaves to sheaves.
* `category_theory.pullback_copullback_adjunction`: If `G : (C, J) ⥤ (D, K)` is cover-lifting,
cover-preserving, and compatible-preserving, then `pullback G` and `copullback G` are adjoint.
## References
* [Elephant]: *Sketches of an Elephant*, P. T. Johnstone: C2.3.
* [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92]
* https://stacks.math.columbia.edu/tag/00XI
-/
universes w v v₁ v₂ v₃ u u₁ u₂ u₃
noncomputable theory
open category_theory
open opposite
open category_theory.presieve.family_of_elements
open category_theory.presieve
open category_theory.limits
namespace category_theory
section cover_lifting
variables {C : Type*} [category C] {D : Type*} [category D] {E : Type*} [category E]
variables (J : grothendieck_topology C) (K : grothendieck_topology D)
variables {L : grothendieck_topology E}
/--
A functor `G : (C, J) ⥤ (D, K)` between sites is called to have the cover-lifting property
if for all covering sieves `R` in `D`, `R.pullback G` is a covering sieve in `C`.
-/
@[nolint has_inhabited_instance]
structure cover_lifting (G : C ⥤ D) : Prop :=
(cover_lift : ∀ {U : C} {S : sieve (G.obj U)} (hS : S ∈ K (G.obj U)), S.functor_pullback G ∈ J U)
/-- The identity functor on a site is cover-lifting. -/
lemma id_cover_lifting : cover_lifting J J (𝟭 _) := ⟨λ _ _ h, by simpa using h⟩
variables {J K}
/-- The composition of two cover-lifting functors are cover-lifting -/
lemma comp_cover_lifting {F : C ⥤ D} (hu : cover_lifting J K F) {G : D ⥤ E}
(hv : cover_lifting K L G) : cover_lifting J L (F ⋙ G) :=
⟨λ _ S h, hu.cover_lift (hv.cover_lift h)⟩
end cover_lifting
/-!
We will now prove that `Ran G.op` (`ₚu`) maps sheaves to sheaves if `G` is cover-lifting. This can
be found in <https://stacks.math.columbia.edu/tag/00XK>. However, the proof given here uses the
amalgamation definition of sheaves, and thus does not require that `C` or `D` has categorical
pullbacks.
For the following proof sketch, `⊆` denotes the homs on `C` and `D` as in the topological analogy.
By definition, the presheaf `𝒢 : Dᵒᵖ ⥤ A` is a sheaf if for every sieve `S` of `U : D`, and every
compatible family of morphisms `X ⟶ 𝒢(V)` for each `V ⊆ U : S` with a fixed source `X`,
we can glue them into a morphism `X ⟶ 𝒢(U)`.
Since the presheaf `𝒢 := (Ran G.op).obj ℱ.val` is defined via `𝒢(U) = lim_{G(V) ⊆ U} ℱ(V)`, for
gluing the family `x` into a `X ⟶ 𝒢(U)`, it suffices to provide a `X ⟶ ℱ(Y)` for each
`G(Y) ⊆ U`. This can be done since `{ Y' ⊆ Y : G(Y') ⊆ U ∈ S}` is a covering sieve for `Y` on
`C` (by the cover-lifting property of `G`). Thus the morphisms `X ⟶ 𝒢(G(Y')) ⟶ ℱ(Y')` can be
glued into a morphism `X ⟶ ℱ(Y)`. This is done in `get_sections`.
In `glued_limit_cone`, we verify these obtained sections are indeed compatible, and thus we obtain
A `X ⟶ 𝒢(U)`. The remaining work is to verify that this is indeed the amalgamation and is unique.
-/
variables {C D : Type u} [category.{v} C] [category.{v} D]
variables {A : Type w} [category.{max u v} A] [has_limits A]
variables {J : grothendieck_topology C} {K : grothendieck_topology D}
namespace Ran_is_sheaf_of_cover_lifting
variables {G : C ⥤ D} (hu : cover_lifting J K G) (ℱ : Sheaf J A)
variables {X : A} {U : D} (S : sieve U) (hS : S ∈ K U)
instance (X : Dᵒᵖ) : has_limits_of_shape (structured_arrow X G.op) A :=
begin
haveI := limits.has_limits_of_size_shrink.{v (max u v) (max u v) (max u v)} A,
exact has_limits_of_size.has_limits_of_shape _
end
variables (x : S.arrows.family_of_elements ((Ran G.op).obj ℱ.val ⋙ coyoneda.obj (op X)))
variables (hx : x.compatible)
/-- The family of morphisms `X ⟶ 𝒢(G(Y')) ⟶ ℱ(Y')` defined on `{ Y' ⊆ Y : G(Y') ⊆ U ∈ S}`. -/
def pulledback_family (Y : structured_arrow (op U) G.op) :=
(((x.pullback Y.hom.unop).functor_pullback G).comp_presheaf_map
(show _ ⟶ _, from whisker_right ((Ran.adjunction A G.op).counit.app ℱ.val)
(coyoneda.obj (op X))))
@[simp] lemma pulledback_family_apply (Y : structured_arrow (op U) G.op) {W} {f : W ⟶ _} (Hf) :
pulledback_family ℱ S x Y f Hf =
x (G.map f ≫ Y.hom.unop) Hf ≫ ((Ran.adjunction A G.op).counit.app ℱ.val).app (op W) := rfl
variables {x} {S}
include hu hS hx
/-- Given a `G(Y) ⊆ U`, we can find a unique section `X ⟶ ℱ(Y)` that agrees with `x`. -/
def get_section (Y : structured_arrow (op U) G.op) : X ⟶ ℱ.val.obj Y.right :=
begin
let hom_sh := whisker_right ((Ran.adjunction A G.op).counit.app ℱ.val) (coyoneda.obj (op X)),
have S' := (K.pullback_stable Y.hom.unop hS),
have hs' := ((hx.pullback Y.3.unop).functor_pullback G).comp_presheaf_map hom_sh,
exact (ℱ.2 X _ (hu.cover_lift S')).amalgamate _ hs'
end
lemma get_section_is_amalgamation (Y : structured_arrow (op U) G.op) :
(pulledback_family ℱ S x Y).is_amalgamation (get_section hu ℱ hS hx Y) :=
is_sheaf_for.is_amalgamation _ _
lemma get_section_is_unique (Y : structured_arrow (op U) G.op)
{y} (H : (pulledback_family ℱ S x Y).is_amalgamation y) : y = get_section hu ℱ hS hx Y :=
begin
apply is_sheaf_for.is_separated_for _ (pulledback_family ℱ S x Y),
{ exact H },
{ apply get_section_is_amalgamation },
{ exact ℱ.2 X _ (hu.cover_lift (K.pullback_stable Y.hom.unop hS)) }
end
@[simp] lemma get_section_commute {Y Z : structured_arrow (op U) G.op} (f : Y ⟶ Z) :
get_section hu ℱ hS hx Y ≫ ℱ.val.map f.right = get_section hu ℱ hS hx Z :=
begin
apply get_section_is_unique,
intros V' fV' hV',
have eq : Z.hom = Y.hom ≫ (G.map f.right.unop).op,
{ convert f.w, erw category.id_comp },
rw eq at hV',
convert get_section_is_amalgamation hu ℱ hS hx Y (fV' ≫ f.right.unop) _ using 1,
{ tidy },
{ simp only [eq, quiver.hom.unop_op, pulledback_family_apply,
functor.map_comp, unop_comp, category.assoc] },
{ change S (G.map _ ≫ Y.hom.unop),
simpa only [functor.map_comp, category.assoc] using hV' }
end
/-- The limit cone in order to glue the sections obtained via `get_section`. -/
def glued_limit_cone : limits.cone (Ran.diagram G.op ℱ.val (op U)) :=
{ X := X, π := { app := λ Y, get_section hu ℱ hS hx Y, naturality' := λ Y Z f, by tidy } }
@[simp] lemma glued_limit_cone_π_app (W) : (glued_limit_cone hu ℱ hS hx).π.app W =
get_section hu ℱ hS hx W := rfl
/-- The section obtained by passing `glued_limit_cone` into `category_theory.limits.limit.lift`. -/
def glued_section : X ⟶ ((Ran G.op).obj ℱ.val).obj (op U) :=
limit.lift _ (glued_limit_cone hu ℱ hS hx)
/--
A helper lemma for the following two lemmas. Basically stating that if the section `y : X ⟶ 𝒢(V)`
coincides with `x` on `G(V')` for all `G(V') ⊆ V ∈ S`, then `X ⟶ 𝒢(V) ⟶ ℱ(W)` is indeed the
section obtained in `get_sections`. That said, this is littered with some more categorical jargon
in order to be applied in the following lemmas easier.
-/
lemma helper {V} (f : V ⟶ U) (y : X ⟶ ((Ran G.op).obj ℱ.val).obj (op V)) (W)
(H : ∀ {V'} {fV : G.obj V' ⟶ V} (hV), y ≫ ((Ran G.op).obj ℱ.val).map fV.op = x (fV ≫ f) hV) :
y ≫ limit.π (Ran.diagram G.op ℱ.val (op V)) W =
(glued_limit_cone hu ℱ hS hx).π.app ((structured_arrow.map f.op).obj W) :=
begin
dsimp only [glued_limit_cone_π_app],
apply get_section_is_unique hu ℱ hS hx ((structured_arrow.map f.op).obj W),
intros V' fV' hV',
dsimp only [Ran.adjunction, Ran.equiv, pulledback_family_apply],
erw [adjunction.adjunction_of_equiv_right_counit_app],
have : y ≫ ((Ran G.op).obj ℱ.val).map (G.map fV' ≫ W.hom.unop).op =
x (G.map fV' ≫ W.hom.unop ≫ f) (by simpa only using hV'),
{ convert H (show S ((G.map fV' ≫ W.hom.unop) ≫ f),
by simpa only [category.assoc] using hV') using 2,
simp only [category.assoc] },
simp only [quiver.hom.unop_op, equiv.symm_symm, structured_arrow.map_obj_hom, unop_comp,
equiv.coe_fn_mk, functor.comp_map, coyoneda_obj_map, category.assoc, ← this, op_comp,
Ran_obj_map, nat_trans.id_app],
erw [category.id_comp, limit.pre_π],
congr,
convert limit.w (Ran.diagram G.op ℱ.val (op V)) (structured_arrow.hom_mk' W fV'.op),
rw structured_arrow.map_mk,
erw category.comp_id,
simp only [quiver.hom.unop_op, functor.op_map, quiver.hom.op_unop]
end
/-- Verify that the `glued_section` is an amalgamation of `x`. -/
lemma glued_section_is_amalgamation : x.is_amalgamation (glued_section hu ℱ hS hx) :=
begin
intros V fV hV,
ext W,
simp only [functor.comp_map, limit.lift_pre, coyoneda_obj_map, Ran_obj_map, glued_section],
erw limit.lift_π,
symmetry,
convert helper hu ℱ hS hx _ (x fV hV) _ _ using 1,
intros V' fV' hV',
convert hx (fV') (𝟙 _) hV hV' (by rw category.id_comp),
simp only [op_id, functor_to_types.map_id_apply]
end
/-- Verify that the amalgamation is indeed unique. -/
lemma glued_section_is_unique (y) (hy: x.is_amalgamation y) : y = glued_section hu ℱ hS hx :=
begin
unfold glued_section limit.lift,
ext W,
erw limit.lift_π,
convert helper hu ℱ hS hx (𝟙 _) y W _,
{ simp only [op_id, structured_arrow.map_id] },
{ intros V' fV' hV',
convert hy fV' (by simpa only [category.comp_id] using hV'),
erw category.comp_id }
end
end Ran_is_sheaf_of_cover_lifting
/--
If `G` is cover_lifting, then `Ran G.op` pushes sheaves to sheaves.
This result is basically https://stacks.math.columbia.edu/tag/00XK,
but without the condition that `C` or `D` has pullbacks.
-/
theorem Ran_is_sheaf_of_cover_lifting {G : C ⥤ D} (hG : cover_lifting J K G) (ℱ : Sheaf J A) :
presheaf.is_sheaf K ((Ran G.op).obj ℱ.val) :=
begin
intros X U S hS x hx,
split, swap,
{ apply Ran_is_sheaf_of_cover_lifting.glued_section hG ℱ hS hx },
split,
{ apply Ran_is_sheaf_of_cover_lifting.glued_section_is_amalgamation },
{ apply Ran_is_sheaf_of_cover_lifting.glued_section_is_unique }
end
variable (A)
/-- A cover-lifting functor induces a morphism of sites in the same direction as the functor. -/
def sites.copullback {G : C ⥤ D} (hG : cover_lifting J K G) :
Sheaf J A ⥤ Sheaf K A :=
{ obj := λ ℱ, ⟨(Ran G.op).obj ℱ.val, Ran_is_sheaf_of_cover_lifting hG ℱ⟩,
map := λ _ _ f, ⟨(Ran G.op).map f.val⟩,
map_id' := λ ℱ, Sheaf.hom.ext _ _ $ (Ran G.op).map_id ℱ.val,
map_comp' := λ _ _ _ f g, Sheaf.hom.ext _ _ $ (Ran G.op).map_comp f.val g.val }
/--
Given a functor between sites that is cover-preserving, cover-lifting, and compatible-preserving,
the pullback and copullback along `G` are adjoint to each other
-/
@[simps unit_app_val counit_app_val] noncomputable
def sites.pullback_copullback_adjunction {G : C ⥤ D} (Hp : cover_preserving J K G)
(Hl : cover_lifting J K G) (Hc : compatible_preserving K G) :
sites.pullback A Hc Hp ⊣ sites.copullback A Hl :=
{ hom_equiv := λ X Y,
{ to_fun := λ f, ⟨(Ran.adjunction A G.op).hom_equiv X.val Y.val f.val⟩,
inv_fun := λ f, ⟨((Ran.adjunction A G.op).hom_equiv X.val Y.val).symm f.val⟩,
left_inv := λ f, by { ext1, dsimp, rw [equiv.symm_apply_apply] },
right_inv := λ f, by { ext1, dsimp, rw [equiv.apply_symm_apply] } },
unit := { app := λ X, ⟨(Ran.adjunction A G.op).unit.app X.val⟩,
naturality' := λ _ _ f, Sheaf.hom.ext _ _ $ (Ran.adjunction A G.op).unit.naturality f.val },
counit := { app := λ X, ⟨(Ran.adjunction A G.op).counit.app X.val⟩,
naturality' := λ _ _ f, Sheaf.hom.ext _ _ $ (Ran.adjunction A G.op).counit.naturality f.val },
hom_equiv_unit' := λ X Y f, by { ext1, apply (Ran.adjunction A G.op).hom_equiv_unit },
hom_equiv_counit' := λ X Y f, by { ext1, apply (Ran.adjunction A G.op).hom_equiv_counit } }
end category_theory
|
aff9fcbee2eea8fd7a36071add05d37242051238
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/src/ring_theory/finite_type.lean
|
b0c17406ed9b7feac63cfd5c1e0cb5beacc54125
|
[
"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
| 23,915
|
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 group_theory.finiteness
import ring_theory.adjoin.tower
import ring_theory.finiteness
import ring_theory.noetherian
/-!
# Finiteness conditions in commutative algebra
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define a notion of finiteness that is common in commutative algebra.
## Main declarations
- `algebra.finite_type`, `ring_hom.finite_type`, `alg_hom.finite_type`
all of these express that some object is finitely generated *as algebra* over some base ring.
-/
open function (surjective)
open_locale big_operators polynomial
section module_and_algebra
variables (R A B M N : Type*)
/-- An algebra over a commutative semiring is of `finite_type` if it is finitely generated
over the base ring as algebra. -/
class algebra.finite_type [comm_semiring R] [semiring A] [algebra R A] : Prop :=
(out : (⊤ : subalgebra R A).fg)
namespace module
variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N]
namespace finite
open _root_.submodule set
variables {R M N}
section algebra
@[priority 100] -- see Note [lower instance priority]
instance finite_type {R : Type*} (A : Type*) [comm_semiring R] [semiring A]
[algebra R A] [hRA : finite R A] : algebra.finite_type R A :=
⟨subalgebra.fg_of_submodule_fg hRA.1⟩
end algebra
end finite
end module
namespace algebra
variables [comm_ring R] [comm_ring A] [algebra R A] [comm_ring B] [algebra R B]
variables [add_comm_group M] [module R M]
variables [add_comm_group N] [module R N]
namespace finite_type
lemma self : finite_type R R := ⟨⟨{1}, subsingleton.elim _ _⟩⟩
protected lemma polynomial : finite_type R R[X] :=
⟨⟨{polynomial.X}, by { rw finset.coe_singleton, exact polynomial.adjoin_X }⟩⟩
open_locale classical
protected lemma mv_polynomial (ι : Type*) [finite ι] : finite_type R (mv_polynomial ι R) :=
by casesI nonempty_fintype ι; exact ⟨⟨finset.univ.image mv_polynomial.X,
by {rw [finset.coe_image, finset.coe_univ, set.image_univ], exact mv_polynomial.adjoin_range_X}⟩⟩
lemma of_restrict_scalars_finite_type [algebra A B] [is_scalar_tower R A B] [hB : finite_type R B] :
finite_type A B :=
begin
obtain ⟨S, hS⟩ := hB.out,
refine ⟨⟨S, eq_top_iff.2 (λ b, _)⟩⟩,
have le : adjoin R (S : set B) ≤ subalgebra.restrict_scalars R (adjoin A S),
{ apply (algebra.adjoin_le _ : _ ≤ (subalgebra.restrict_scalars R (adjoin A ↑S))),
simp only [subalgebra.coe_restrict_scalars],
exact algebra.subset_adjoin, },
exact le (eq_top_iff.1 hS b),
end
variables {R A B}
lemma of_surjective (hRA : finite_type R A) (f : A →ₐ[R] B) (hf : surjective f) :
finite_type R B :=
⟨begin
convert hRA.1.map f,
simpa only [map_top f, @eq_comm _ ⊤, eq_top_iff, alg_hom.mem_range] using hf
end⟩
lemma equiv (hRA : finite_type R A) (e : A ≃ₐ[R] B) : finite_type R B :=
hRA.of_surjective e e.surjective
lemma trans [algebra A B] [is_scalar_tower R A B] (hRA : finite_type R A) (hAB : finite_type A B) :
finite_type R B :=
⟨fg_trans' hRA.1 hAB.1⟩
/-- An algebra is finitely generated if and only if it is a quotient
of a polynomial ring whose variables are indexed by a finset. -/
lemma iff_quotient_mv_polynomial : (finite_type R A) ↔ ∃ (s : finset A)
(f : (mv_polynomial {x // x ∈ s} R) →ₐ[R] A), (surjective f) :=
begin
split,
{ rintro ⟨s, hs⟩,
use [s, mv_polynomial.aeval coe],
intro x,
have hrw : (↑s : set A) = (λ (x : A), x ∈ s.val) := rfl,
rw [← set.mem_range, ← alg_hom.coe_range, ← adjoin_eq_range, ← hrw, hs],
exact set.mem_univ x },
{ rintro ⟨s, ⟨f, hsur⟩⟩,
exact finite_type.of_surjective (finite_type.mv_polynomial R {x // x ∈ s}) f hsur }
end
/-- An algebra is finitely generated if and only if it is a quotient
of a polynomial ring whose variables are indexed by a fintype. -/
lemma iff_quotient_mv_polynomial' : (finite_type R A) ↔ ∃ (ι : Type u_2) (_ : fintype ι)
(f : (mv_polynomial ι R) →ₐ[R] A), (surjective f) :=
begin
split,
{ rw iff_quotient_mv_polynomial,
rintro ⟨s, ⟨f, hsur⟩⟩,
use [{x // x ∈ s}, by apply_instance, f, hsur] },
{ rintro ⟨ι, ⟨hfintype, ⟨f, hsur⟩⟩⟩,
letI : fintype ι := hfintype,
exact finite_type.of_surjective (finite_type.mv_polynomial R ι) f hsur }
end
/-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring in `n`
variables. -/
lemma iff_quotient_mv_polynomial'' : (finite_type R A) ↔ ∃ (n : ℕ)
(f : (mv_polynomial (fin n) R) →ₐ[R] A), (surjective f) :=
begin
split,
{ rw iff_quotient_mv_polynomial',
rintro ⟨ι, hfintype, ⟨f, hsur⟩⟩,
resetI,
have equiv := mv_polynomial.rename_equiv R (fintype.equiv_fin ι),
exact ⟨fintype.card ι, alg_hom.comp f equiv.symm, function.surjective.comp hsur
(alg_equiv.symm equiv).surjective⟩ },
{ rintro ⟨n, ⟨f, hsur⟩⟩,
exact finite_type.of_surjective (finite_type.mv_polynomial R (fin n)) f hsur }
end
instance prod [hA : finite_type R A] [hB : finite_type R B] : finite_type R (A × B) :=
⟨begin
rw ← subalgebra.prod_top,
exact hA.1.prod hB.1
end⟩
lemma is_noetherian_ring (R S : Type*) [comm_ring R] [comm_ring S] [algebra R S]
[h : algebra.finite_type R S] [is_noetherian_ring R] : is_noetherian_ring S :=
begin
obtain ⟨s, hs⟩ := h.1,
apply is_noetherian_ring_of_surjective
(mv_polynomial s R) S (mv_polynomial.aeval coe : mv_polynomial s R →ₐ[R] S),
rw [← set.range_iff_surjective, alg_hom.coe_to_ring_hom, ← alg_hom.coe_range,
← algebra.adjoin_range_eq_range_aeval, subtype.range_coe_subtype, finset.set_of_mem, hs],
refl
end
lemma _root_.subalgebra.fg_iff_finite_type {R A : Type*} [comm_semiring R] [semiring A]
[algebra R A] (S : subalgebra R A) : S.fg ↔ algebra.finite_type R S :=
S.fg_top.symm.trans ⟨λ h, ⟨h⟩, λ h, h.out⟩
end finite_type
end algebra
end module_and_algebra
namespace ring_hom
variables {A B C : Type*} [comm_ring A] [comm_ring B] [comm_ring C]
/-- A ring morphism `A →+* B` is of `finite_type` if `B` is finitely generated as `A`-algebra. -/
def finite_type (f : A →+* B) : Prop := @algebra.finite_type A B _ _ f.to_algebra
namespace finite
variables {A}
lemma finite_type {f : A →+* B} (hf : f.finite) : finite_type f :=
@module.finite.finite_type _ _ _ _ f.to_algebra hf
end finite
namespace finite_type
variables (A)
lemma id : finite_type (ring_hom.id A) := algebra.finite_type.self A
variables {A}
lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_type) (hg : surjective g) :
(g.comp f).finite_type :=
@algebra.finite_type.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra hf
{ to_fun := g, commutes' := λ a, rfl, .. g } hg
lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite_type :=
by { rw ← f.comp_id, exact (id A).comp_surjective hf }
lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_type) (hf : f.finite_type) :
(g.comp f).finite_type :=
@algebra.finite_type.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra
begin
fconstructor,
intros a b c,
simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc],
refl
end
hf hg
lemma of_finite {f : A →+* B} (hf : f.finite) : f.finite_type :=
@module.finite.finite_type _ _ _ _ f.to_algebra hf
alias of_finite ← _root_.ring_hom.finite.to_finite_type
lemma of_comp_finite_type {f : A →+* B} {g : B →+* C} (h : (g.comp f).finite_type) :
g.finite_type :=
begin
letI := f.to_algebra,
letI := g.to_algebra,
letI := (g.comp f).to_algebra,
letI : is_scalar_tower A B C := restrict_scalars.is_scalar_tower A B C,
letI : algebra.finite_type A C := h,
exact algebra.finite_type.of_restrict_scalars_finite_type A B C
end
end finite_type
end ring_hom
namespace alg_hom
variables {R A B C : Type*} [comm_ring R]
variables [comm_ring A] [comm_ring B] [comm_ring C]
variables [algebra R A] [algebra R B] [algebra R C]
/-- An algebra morphism `A →ₐ[R] B` is of `finite_type` if it is of finite type as ring morphism.
In other words, if `B` is finitely generated as `A`-algebra. -/
def finite_type (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_type
namespace finite
variables {R A}
lemma finite_type {f : A →ₐ[R] B} (hf : f.finite) : finite_type f :=
ring_hom.finite.finite_type hf
end finite
namespace finite_type
variables (R A)
lemma id : finite_type (alg_hom.id R A) := ring_hom.finite_type.id A
variables {R A}
lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_type) (hf : f.finite_type) :
(g.comp f).finite_type :=
ring_hom.finite_type.comp hg hf
lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_type) (hg : surjective g) :
(g.comp f).finite_type :=
ring_hom.finite_type.comp_surjective hf hg
lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite_type :=
ring_hom.finite_type.of_surjective f hf
lemma of_comp_finite_type {f : A →ₐ[R] B} {g : B →ₐ[R] C} (h : (g.comp f).finite_type) :
g.finite_type :=
ring_hom.finite_type.of_comp_finite_type h
end finite_type
end alg_hom
section monoid_algebra
variables {R : Type*} {M : Type*}
namespace add_monoid_algebra
open algebra add_submonoid submodule
section span
section semiring
variables [comm_semiring R] [add_monoid M]
/-- An element of `add_monoid_algebra R M` is in the subalgebra generated by its support. -/
lemma mem_adjoin_support (f : add_monoid_algebra R M) : f ∈ adjoin R (of' R M '' f.support) :=
begin
suffices : span R (of' R M '' f.support) ≤ (adjoin R (of' R M '' f.support)).to_submodule,
{ exact this (mem_span_support f) },
rw submodule.span_le,
exact subset_adjoin
end
/-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the set of supports of
elements of `S` generates `add_monoid_algebra R M`. -/
lemma support_gen_of_gen {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (⋃ f ∈ S, (of' R M '' (f.support : set M))) = ⊤ :=
begin
refine le_antisymm le_top _,
rw [← hS, adjoin_le_iff],
intros f hf,
have hincl : of' R M '' f.support ⊆
⋃ (g : add_monoid_algebra R M) (H : g ∈ S), of' R M '' g.support,
{ intros s hs,
exact set.mem_Union₂.2 ⟨f, ⟨hf, hs⟩⟩ },
exact adjoin_mono hincl (mem_adjoin_support f)
end
/-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the image of the union of
the supports of elements of `S` generates `add_monoid_algebra R M`. -/
lemma support_gen_of_gen' {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (of' R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ :=
begin
suffices : of' R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of' R M '' (f.support : set M)),
{ rw this,
exact support_gen_of_gen hS },
simp only [set.image_Union]
end
end semiring
section ring
variables [comm_ring R] [add_comm_monoid M]
/-- If `add_monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its
image generates, as algera, `add_monoid_algebra R M`. -/
lemma exists_finset_adjoin_eq_top [h : finite_type R (add_monoid_algebra R M)] :
∃ G : finset M, algebra.adjoin R (of' R M '' G) = ⊤ :=
begin
unfreezingI { obtain ⟨S, hS⟩ := h },
letI : decidable_eq M := classical.dec_eq M,
use finset.bUnion S (λ f, f.support),
have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M),
{ simp only [finset.set_bUnion_coe, finset.coe_bUnion] },
rw [this],
exact support_gen_of_gen' hS
end
/-- The image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by
`S : set M` if and only if `m ∈ S`. -/
lemma of'_mem_span [nontrivial R] {m : M} {S : set M} :
of' R M m ∈ span R (of' R M '' S) ↔ m ∈ S :=
begin
refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩,
rw [of', ← finsupp.supported_eq_span_single, finsupp.mem_supported,
finsupp.support_single_ne_zero _ (one_ne_zero' R)] at h,
simpa using h
end
/--If the image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by
the closure of some `S : set M` then `m ∈ closure S`. -/
lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M}
(h : of' R M m ∈ span R (submonoid.closure (of' R M '' S) : set (add_monoid_algebra R M))) :
m ∈ closure S :=
begin
suffices : multiplicative.of_add m ∈ submonoid.closure (multiplicative.to_add ⁻¹' S),
{ simpa [← to_submonoid_closure] },
let S' := @submonoid.closure M multiplicative.mul_one_class S,
have h' : submonoid.map (of R M) S' = submonoid.closure ((λ (x : M), (of R M) x) '' S) :=
monoid_hom.map_mclosure _ _,
rw [set.image_congr' (show ∀ x, of' R M x = of R M x, from λ x, of'_eq_of x), ← h'] at h,
simpa using of'_mem_span.1 h
end
end ring
end span
variables [add_comm_monoid M]
/-- If a set `S` generates an additive monoid `M`, then the image of `M` generates, as algebra,
`add_monoid_algebra R M`. -/
lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M}
(hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval
(λ (s : S), of' R M ↑s) : mv_polynomial S R → add_monoid_algebra R M) :=
begin
refine λ f, induction_on f (λ m, _) _ _,
{ have : m ∈ closure S := hS.symm ▸ mem_top _,
refine closure_induction this (λ m hm, _) _ _,
{ exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ },
{ exact ⟨1, alg_hom.map_one _⟩ },
{ rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩,
exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply,
single_mul_single, one_mul]; refl⟩ } },
{ rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩,
exact ⟨P + Q, alg_hom.map_add _ _ _⟩ },
{ rintro r f ⟨P, rfl⟩,
exact ⟨r • P, alg_hom.map_smul _ _ _⟩ }
end
variables (R M)
/-- If an additive monoid `M` is finitely generated then `add_monoid_algebra R M` is of finite
type. -/
instance finite_type_of_fg [comm_ring R] [h : add_monoid.fg M] :
finite_type R (add_monoid_algebra R M) :=
begin
obtain ⟨S, hS⟩ := h.out,
exact (finite_type.mv_polynomial R (S : set M)).of_surjective (mv_polynomial.aeval
(λ (s : (S : set M)), of' R M ↑s)) (mv_polynomial_aeval_of_surjective_of_closure hS)
end
variables {R M}
/-- An additive monoid `M` is finitely generated if and only if `add_monoid_algebra R M` is of
finite type. -/
lemma finite_type_iff_fg [comm_ring R] [nontrivial R] :
finite_type R (add_monoid_algebra R M) ↔ add_monoid.fg M :=
begin
refine ⟨λ h, _, λ h, @add_monoid_algebra.finite_type_of_fg _ _ _ _ h⟩,
obtain ⟨S, hS⟩ := @exists_finset_adjoin_eq_top R M _ _ h,
refine add_monoid.fg_def.2 ⟨S, (eq_top_iff' _).2 (λ m, _)⟩,
have hm : of' R M m ∈ (adjoin R (of' R M '' ↑S)).to_submodule,
{ simp only [hS, top_to_submodule, submodule.mem_top], },
rw [adjoin_eq_span] at hm,
exact mem_closure_of_mem_span_closure hm
end
/-- If `add_monoid_algebra R M` is of finite type then `M` is finitely generated. -/
lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (add_monoid_algebra R M)] :
add_monoid.fg M :=
finite_type_iff_fg.1 h
/-- An additive group `G` is finitely generated if and only if `add_monoid_algebra R G` is of
finite type. -/
lemma finite_type_iff_group_fg {G : Type*} [add_comm_group G] [comm_ring R] [nontrivial R] :
finite_type R (add_monoid_algebra R G) ↔ add_group.fg G :=
by simpa [add_group.fg_iff_add_monoid.fg] using finite_type_iff_fg
end add_monoid_algebra
namespace monoid_algebra
open algebra submonoid submodule
section span
section semiring
variables [comm_semiring R] [monoid M]
/-- An element of `monoid_algebra R M` is in the subalgebra generated by its support. -/
lemma mem_adjoin_support (f : monoid_algebra R M) : f ∈ adjoin R (of R M '' f.support) :=
begin
suffices : span R (of R M '' f.support) ≤ (adjoin R (of R M '' f.support)).to_submodule,
{ exact this (mem_span_support f) },
rw submodule.span_le,
exact subset_adjoin
end
/-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the set of supports of elements
of `S` generates `monoid_algebra R M`. -/
lemma support_gen_of_gen {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (⋃ f ∈ S, (of R M '' (f.support : set M))) = ⊤ :=
begin
refine le_antisymm le_top _,
rw [← hS, adjoin_le_iff],
intros f hf,
have hincl : (of R M) '' f.support ⊆
⋃ (g : monoid_algebra R M) (H : g ∈ S), of R M '' g.support,
{ intros s hs,
exact set.mem_Union₂.2 ⟨f, ⟨hf, hs⟩⟩ },
exact adjoin_mono hincl (mem_adjoin_support f)
end
/-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the image of the union of the
supports of elements of `S` generates `monoid_algebra R M`. -/
lemma support_gen_of_gen' {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (of R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ :=
begin
suffices : of R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of R M '' (f.support : set M)),
{ rw this,
exact support_gen_of_gen hS },
simp only [set.image_Union]
end
end semiring
section ring
variables [comm_ring R] [comm_monoid M]
/-- If `monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its image
generates, as algera, `monoid_algebra R M`. -/
lemma exists_finset_adjoin_eq_top [h :finite_type R (monoid_algebra R M)] :
∃ G : finset M, algebra.adjoin R (of R M '' G) = ⊤ :=
begin
unfreezingI { obtain ⟨S, hS⟩ := h },
letI : decidable_eq M := classical.dec_eq M,
use finset.bUnion S (λ f, f.support),
have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M),
{ simp only [finset.set_bUnion_coe, finset.coe_bUnion] },
rw [this],
exact support_gen_of_gen' hS
end
/-- The image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by
`S : set M` if and only if `m ∈ S`. -/
lemma of_mem_span_of_iff [nontrivial R] {m : M} {S : set M} :
of R M m ∈ span R (of R M '' S) ↔ m ∈ S :=
begin
refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩,
rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported,
finsupp.support_single_ne_zero _ (one_ne_zero' R)] at h,
simpa using h
end
/--If the image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by the
closure of some `S : set M` then `m ∈ closure S`. -/
lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M}
(h : of R M m ∈ span R (submonoid.closure (of R M '' S) : set (monoid_algebra R M))) :
m ∈ closure S :=
begin
rw ← monoid_hom.map_mclosure at h,
simpa using of_mem_span_of_iff.1 h
end
end ring
end span
variables [comm_monoid M]
/-- If a set `S` generates a monoid `M`, then the image of `M` generates, as algebra,
`monoid_algebra R M`. -/
lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M}
(hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval
(λ (s : S), of R M ↑s) : mv_polynomial S R → monoid_algebra R M) :=
begin
refine λ f, induction_on f (λ m, _) _ _,
{ have : m ∈ closure S := hS.symm ▸ mem_top _,
refine closure_induction this (λ m hm, _) _ _,
{ exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ },
{ exact ⟨1, alg_hom.map_one _⟩ },
{ rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩,
exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply,
single_mul_single, one_mul]⟩ } },
{ rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩,
exact ⟨P + Q, alg_hom.map_add _ _ _⟩ },
{ rintro r f ⟨P, rfl⟩,
exact ⟨r • P, alg_hom.map_smul _ _ _⟩ }
end
/-- If a monoid `M` is finitely generated then `monoid_algebra R M` is of finite type. -/
instance finite_type_of_fg [comm_ring R] [monoid.fg M] : finite_type R (monoid_algebra R M) :=
(add_monoid_algebra.finite_type_of_fg R (additive M)).equiv (to_additive_alg_equiv R M).symm
/-- A monoid `M` is finitely generated if and only if `monoid_algebra R M` is of finite type. -/
lemma finite_type_iff_fg [comm_ring R] [nontrivial R] :
finite_type R (monoid_algebra R M) ↔ monoid.fg M :=
⟨λ h, monoid.fg_iff_add_fg.2 $ add_monoid_algebra.finite_type_iff_fg.1 $ h.equiv $
to_additive_alg_equiv R M, λ h, @monoid_algebra.finite_type_of_fg _ _ _ _ h⟩
/-- If `monoid_algebra R M` is of finite type then `M` is finitely generated. -/
lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (monoid_algebra R M)] :
monoid.fg M :=
finite_type_iff_fg.1 h
/-- A group `G` is finitely generated if and only if `add_monoid_algebra R G` is of finite type. -/
lemma finite_type_iff_group_fg {G : Type*} [comm_group G] [comm_ring R] [nontrivial R] :
finite_type R (monoid_algebra R G) ↔ group.fg G :=
by simpa [group.fg_iff_monoid.fg] using finite_type_iff_fg
end monoid_algebra
end monoid_algebra
section vasconcelos
variables {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (f : M →ₗ[R] M)
noncomputable theory
/-- The structure of a module `M` over a ring `R` as a module over `R[X]` when given a
choice of how `X` acts by choosing a linear map `f : M →ₗ[R] M` -/
def module_polynomial_of_endo : module R[X] M :=
module.comp_hom M (polynomial.aeval f).to_ring_hom
lemma module_polynomial_of_endo_smul_def (n : R[X]) (a : M) :
@@has_smul.smul (module_polynomial_of_endo f).to_has_smul n a = polynomial.aeval f n a := rfl
local attribute [simp] module_polynomial_of_endo_smul_def
include f
lemma module_polynomial_of_endo.is_scalar_tower : @is_scalar_tower R R[X] M _
(by { letI := module_polynomial_of_endo f, apply_instance }) _ :=
begin
letI := module_polynomial_of_endo f,
constructor,
intros x y z,
simp,
end
open polynomial module
/-- A theorem/proof by Vasconcelos, given a finite module `M` over a commutative ring, any
surjective endomorphism of `M` is also injective. Based on,
https://math.stackexchange.com/a/239419/31917,
https://www.ams.org/journals/tran/1969-138-00/S0002-9947-1969-0238839-5/.
This is similar to `is_noetherian.injective_of_surjective_endomorphism` but only applies in the
commutative case, but does not use a Noetherian hypothesis. -/
theorem module.finite.injective_of_surjective_endomorphism [hfg : finite R M]
(f_surj : function.surjective f) : function.injective f :=
begin
letI := module_polynomial_of_endo f,
haveI : is_scalar_tower R R[X] M := module_polynomial_of_endo.is_scalar_tower f,
have hfgpoly : finite R[X] M, from finite.of_restrict_scalars_finite R _ _,
have X_mul : ∀ o, (X : R[X]) • o = f o,
{ intro,
simp, },
have : (⊤ : submodule R[X] M) ≤ ideal.span {X} • ⊤,
{ intros a ha,
obtain ⟨y, rfl⟩ := f_surj a,
rw [← X_mul y],
exact submodule.smul_mem_smul (ideal.mem_span_singleton.mpr (dvd_refl _)) trivial, },
obtain ⟨F, hFa, hFb⟩ := submodule.exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul _
(⊤ : submodule R[X] M) (finite_def.mp hfgpoly) this,
rw [← linear_map.ker_eq_bot, linear_map.ker_eq_bot'],
intros m hm,
rw ideal.mem_span_singleton' at hFa,
obtain ⟨G, hG⟩ := hFa,
suffices : (F - 1) • m = 0,
{ have Fmzero := hFb m (by simp),
rwa [← sub_add_cancel F 1, add_smul, one_smul, this, zero_add] at Fmzero, },
rw [← hG, mul_smul, X_mul m, hm, smul_zero],
end
end vasconcelos
|
ef8ccf06e2d87e79bda8a5534821e1a37a853515
|
9028d228ac200bbefe3a711342514dd4e4458bff
|
/src/data/int/gcd.lean
|
aeefef899096aaeb70246162e3d8d2caece3071e
|
[
"Apache-2.0"
] |
permissive
|
mcncm/mathlib
|
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
|
fde3d78cadeec5ef827b16ae55664ef115e66f57
|
refs/heads/master
| 1,672,743,316,277
| 1,602,618,514,000
| 1,602,618,514,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 5,846
|
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 ⟨_, mul_left_cancel' 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
lemma prime.dvd_nat_abs_of_coe_dvd_pow_two {p : ℕ} (hp : p.prime) (k : ℤ) (h : ↑p ∣ k ^ 2) :
p ∣ k.nat_abs :=
begin
apply @nat.prime.dvd_of_dvd_pow _ _ 2 hp,
rwa [pow_two, ← nat_abs_mul, ← coe_nat_dvd_left, ← pow_two]
end
end int
lemma pow_gcd_eq_one {M : Type*} [monoid M] (x : M) {m n : ℕ} (hm : x ^ m = 1) (hn : x ^ n = 1) :
x ^ m.gcd n = 1 :=
begin
cases m, { simp only [hn, nat.gcd_zero_left] },
obtain ⟨x, rfl⟩ : is_unit x,
{ apply is_unit_of_pow_eq_one _ _ hm m.succ_pos },
simp only [← units.coe_pow] at *,
rw [← units.coe_one, ← gpow_coe_nat, ← units.ext_iff] at *,
simp only [nat.gcd_eq_gcd_ab, gpow_add, gpow_mul, hm, hn, one_gpow, one_mul]
end
|
68c7b9c7ced555da04238e6b0f40bb1bd10812c3
|
63abd62053d479eae5abf4951554e1064a4c45b4
|
/src/representation_theory/maschke.lean
|
40119877a15446b9953d1c407a2d453103de731a
|
[
"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
| 5,901
|
lean
|
/-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Scott Morrison
-/
import algebra.monoid_algebra
import algebra.invertible
import algebra.char_p
import linear_algebra.basis
/-!
# Maschke's theorem
We prove Maschke's theorem for finite groups,
in the formulation that every submodule of a `k[G]` module has a complement,
when `k` is a field with `¬(ring_char k ∣ fintype.card G)`.
We do the core computation in greater generality.
For any `[comm_ring k]` in which `[invertible (fintype.card G : k)]`,
and a `k[G]`-linear map `i : V → W` which admits a `k`-linear retraction `π`,
we produce a `k[G]`-linear retraction by
taking the average over `G` of the conjugates of `π`.
## Future work
It's not so far to give the usual statement, that every finite dimensional representation
of a finite group is semisimple (i.e. a direct sum of irreducibles).
-/
universes u
noncomputable theory
open semimodule
open monoid_algebra
open_locale big_operators
section
-- At first we work with any `[comm_ring k]`, and add the assumption that
-- `[invertible (fintype.card G : k)]` when it is required.
variables {k : Type u} [comm_ring k] {G : Type u} [group G]
variables {V : Type u} [add_comm_group V] [module k V] [module (monoid_algebra k G) V]
variables [is_scalar_tower k (monoid_algebra k G) V]
variables {W : Type u} [add_comm_group W] [module k W] [module (monoid_algebra k G) W]
variables [is_scalar_tower k (monoid_algebra k G) W]
/-!
We now do the key calculation in Maschke's theorem.
Given `V → W`, an inclusion of `k[G]` modules,,
assume we have some retraction `π` (i.e. `∀ v, π (i v) = v`),
just as a `k`-linear map.
(When `k` is a field, this will be available cheaply, by choosing a basis.)
We now construct a retraction of the inclusion as a `k[G]`-linear map,
by the formula
$$ \frac{1}{|G|} \sum_{g \in G} g⁻¹ • π(g • -). $$
-/
namespace linear_map
variables (π : W →ₗ[k] V)
include π
/--
We define the conjugate of `π` by `g`, as a `k`-linear map.
-/
def conjugate (g : G) : W →ₗ[k] V :=
((group_smul.linear_map k V g⁻¹).comp π).comp (group_smul.linear_map k W g)
variables (i : V →ₗ[monoid_algebra k G] W) (h : ∀ v : V, π (i v) = v)
section
include h
lemma conjugate_i (g : G) (v : V) : (conjugate π g) (i v) = v :=
begin
dsimp [conjugate],
simp only [←i.map_smul, h, ←mul_smul, single_mul_single, mul_one, mul_left_inv],
change (1 : monoid_algebra k G) • v = v,
simp,
end
end
variables (G) [fintype G]
/--
The sum of the conjugates of `π` by each element `g : G`, as a `k`-linear map.
(We postpone dividing by the size of the group as long as possible.)
-/
def sum_of_conjugates : W →ₗ[k] V :=
∑ g : G, π.conjugate g
/--
In fact, the sum over `g : G` of the conjugate of `π` by `g` is a `k[G]`-linear map.
-/
def sum_of_conjugates_equivariant : W →ₗ[monoid_algebra k G] V :=
monoid_algebra.equivariant_of_linear_of_comm (π.sum_of_conjugates G) (λ g v,
begin
dsimp [sum_of_conjugates],
simp only [linear_map.sum_apply, finset.smul_sum],
dsimp [conjugate],
conv_lhs {
rw [←finset.univ_map_embedding (mul_right_embedding g⁻¹)],
simp only [mul_right_embedding],
},
simp only [←mul_smul, single_mul_single, mul_inv_rev, mul_one, function.embedding.coe_fn_mk,
finset.sum_map, inv_inv, inv_mul_cancel_right],
recover,
end)
section
variables [inv : invertible (fintype.card G : k)]
include inv
/--
We construct our `k[G]`-linear retraction of `i` as
$$ \frac{1}{|G|} \sum_{g \in G} g⁻¹ • π(g • -). $$
-/
def equivariant_projection : W →ₗ[monoid_algebra k G] V :=
⅟(fintype.card G : k) • (π.sum_of_conjugates_equivariant G)
include h
lemma equivariant_projection_condition (v : V) : (π.equivariant_projection G) (i v) = v :=
begin
rw [equivariant_projection, linear_map.algebra_module.smul_apply, sum_of_conjugates_equivariant,
equivariant_of_linear_of_comm_apply, sum_of_conjugates],
rw [linear_map.sum_apply],
simp only [conjugate_i π i h],
rw [finset.sum_const, finset.card_univ,
@semimodule.nsmul_eq_smul k _
V _ _ (fintype.card G) v,
←mul_smul, invertible.inv_of_mul_self, one_smul],
end
end
end linear_map
end
-- Now we work over a `[field k]`, and replace the assumption `[invertible (fintype.card G : k)]`
-- with `¬(ring_char k ∣ fintype.card G)`.
variables {k : Type u} [field k] {G : Type u} [fintype G] [group G]
variables {V : Type u} [add_comm_group V] [module k V] [module (monoid_algebra k G) V]
variables [is_scalar_tower k (monoid_algebra k G) V]
variables {W : Type u} [add_comm_group W] [module k W] [module (monoid_algebra k G) W]
variables [is_scalar_tower k (monoid_algebra k G) W]
lemma monoid_algebra.exists_left_inverse_of_injective
(not_dvd : ¬(ring_char k ∣ fintype.card G)) (f : V →ₗ[monoid_algebra k G] W) (hf : f.ker = ⊥) :
∃ (g : W →ₗ[monoid_algebra k G] V), g.comp f = linear_map.id :=
begin
haveI : invertible (fintype.card G : k) :=
invertible_of_ring_char_not_dvd not_dvd,
obtain ⟨φ, hφ⟩ := (f.restrict_scalars k).exists_left_inverse_of_injective
(by simp only [hf, submodule.restrict_scalars_bot, linear_map.ker_restrict_scalars]),
refine ⟨φ.equivariant_projection G, _⟩,
ext v,
simp only [linear_map.id_coe, id.def, linear_map.comp_apply],
apply linear_map.equivariant_projection_condition,
intro v,
have := congr_arg linear_map.to_fun hφ,
exact congr_fun this v
end
lemma monoid_algebra.submodule.exists_is_compl
(not_dvd : ¬(ring_char k ∣ fintype.card G)) (p : submodule (monoid_algebra k G) V) :
∃ q : submodule (monoid_algebra k G) V, is_compl p q :=
let ⟨f, hf⟩ := monoid_algebra.exists_left_inverse_of_injective not_dvd p.subtype p.ker_subtype in
⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩
|
0f7d9caf69a133f1c25a3768cad25009675dcf36
|
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
|
/src/data/qpf/univariate/basic.lean
|
fcce2259c843fe503caa453c46d192e345c72e92
|
[
"Apache-2.0"
] |
permissive
|
DanielFabian/mathlib
|
efc3a50b5dde303c59eeb6353ef4c35a345d7112
|
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
|
refs/heads/master
| 1,668,739,922,971
| 1,595,201,756,000
| 1,595,201,756,000
| 279,469,476
| 0
| 0
| null | 1,594,696,604,000
| 1,594,696,604,000
| null |
UTF-8
|
Lean
| false
| false
| 20,555
|
lean
|
/-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
-/
import data.pfunctor.univariate
/-!
# Quotients of Polynomial Functors
We assume the following:
`P` : a polynomial functor
`W` : its W-type
`M` : its M-type
`F` : a functor
We define:
`q` : `qpf` data, representing `F` as a quotient of `P`
The main goal is to construct:
`fix` : the initial algebra with structure map `F fix → fix`.
`cofix` : the final coalgebra with structure map `cofix → F cofix`
We also show that the composition of qpfs is a qpf, and that the quotient of a qpf
is a qpf.
The present theory focuses on the univariate case for qpfs
## References
* [Jeremy Avigad, Mario M. Carneiro and Simon Hudon, *Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019]
-/
universe u
/--
Quotients of polynomial functors.
Roughly speaking, saying that `F` is a quotient of a polynomial functor means that for each `α`,
elements of `F α` are represented by pairs `⟨a, f⟩`, where `a` is the shape of the object and
`f` indexes the relevant elements of `α`, in a suitably natural manner.
-/
class qpf (F : Type u → Type u) [functor F] :=
(P : pfunctor.{u})
(abs : Π {α}, P.obj α → F α)
(repr : Π {α}, F α → P.obj α)
(abs_repr : ∀ {α} (x : F α), abs (repr x) = x)
(abs_map : ∀ {α β} (f : α → β) (p : P.obj α), abs (f <$> p) = f <$> abs p)
namespace qpf
variables {F : Type u → Type u} [functor F] [q : qpf F]
include q
open functor (liftp liftr)
/-
Show that every qpf is a lawful functor.
Note: every functor has a field, `map_const`, and is_lawful_functor has the defining
characterization. We can only propagate the assumption.
-/
theorem id_map {α : Type*} (x : F α) : id <$> x = x :=
by { rw ←abs_repr x, cases repr x with a f, rw [←abs_map], reflexivity }
theorem comp_map {α β γ : Type*} (f : α → β) (g : β → γ) (x : F α) :
(g ∘ f) <$> x = g <$> f <$> x :=
by { rw ←abs_repr x, cases repr x with a f, rw [←abs_map, ←abs_map, ←abs_map], reflexivity }
theorem is_lawful_functor
(h : ∀ α β : Type u, @functor.map_const F _ α _ = functor.map ∘ function.const β) :
is_lawful_functor F :=
{ map_const_eq := h,
id_map := @id_map F _ _,
comp_map := @comp_map F _ _ }
/-
Lifting predicates and relations
-/
section
open functor
theorem liftp_iff {α : Type u} (p : α → Prop) (x : F α) :
liftp p x ↔ ∃ a f, x = abs ⟨a, f⟩ ∧ ∀ i, p (f i) :=
begin
split,
{ rintros ⟨y, hy⟩, cases h : repr y with a f,
use [a, λ i, (f i).val], split,
{ rw [←hy, ←abs_repr y, h, ←abs_map], reflexivity },
intro i, apply (f i).property },
rintros ⟨a, f, h₀, h₁⟩, dsimp at *,
use abs (⟨a, λ i, ⟨f i, h₁ i⟩⟩),
rw [←abs_map, h₀], reflexivity
end
theorem liftp_iff' {α : Type u} (p : α → Prop) (x : F α) :
liftp p x ↔ ∃ u : q.P.obj α, abs u = x ∧ ∀ i, p (u.snd i) :=
begin
split,
{ rintros ⟨y, hy⟩, cases h : repr y with a f,
use ⟨a, λ i, (f i).val⟩, dsimp, split,
{ rw [←hy, ←abs_repr y, h, ←abs_map], reflexivity },
intro i, apply (f i).property },
rintros ⟨⟨a, f⟩, h₀, h₁⟩, dsimp at *,
use abs (⟨a, λ i, ⟨f i, h₁ i⟩⟩),
rw [←abs_map, ←h₀], reflexivity
end
theorem liftr_iff {α : Type u} (r : α → α → Prop) (x y : F α) :
liftr r x y ↔ ∃ a f₀ f₁, x = abs ⟨a, f₀⟩ ∧ y = abs ⟨a, f₁⟩ ∧ ∀ i, r (f₀ i) (f₁ i) :=
begin
split,
{ rintros ⟨u, xeq, yeq⟩, cases h : repr u with a f,
use [a, λ i, (f i).val.fst, λ i, (f i).val.snd],
split, { rw [←xeq, ←abs_repr u, h, ←abs_map], refl },
split, { rw [←yeq, ←abs_repr u, h, ←abs_map], refl },
intro i, exact (f i).property },
rintros ⟨a, f₀, f₁, xeq, yeq, h⟩,
use abs ⟨a, λ i, ⟨(f₀ i, f₁ i), h i⟩⟩,
dsimp, split,
{ rw [xeq, ←abs_map], refl },
rw [yeq, ←abs_map], refl
end
end
/-
Think of trees in the `W` type corresponding to `P` as representatives of elements of the
least fixed point of `F`, and assign a canonical representative to each equivalence class
of trees.
-/
/-- does recursion on `q.P.W` using `g : F α → α` rather than `g : P α → α` -/
def recF {α : Type*} (g : F α → α) : q.P.W → α
| ⟨a, f⟩ := g (abs ⟨a, λ x, recF (f x)⟩)
theorem recF_eq {α : Type*} (g : F α → α) (x : q.P.W) :
recF g x = g (abs (recF g <$> x.dest)) :=
by cases x; reflexivity
theorem recF_eq' {α : Type*} (g : F α → α) (a : q.P.A) (f : q.P.B a → q.P.W) :
recF g ⟨a, f⟩ = g (abs (recF g <$> ⟨a, f⟩)) :=
rfl
/-- two trees are equivalent if their F-abstractions are -/
inductive Wequiv : q.P.W → q.P.W → Prop
| ind (a : q.P.A) (f f' : q.P.B a → q.P.W) :
(∀ x, Wequiv (f x) (f' x)) → Wequiv ⟨a, f⟩ ⟨a, f'⟩
| abs (a : q.P.A) (f : q.P.B a → q.P.W) (a' : q.P.A) (f' : q.P.B a' → q.P.W) :
abs ⟨a, f⟩ = abs ⟨a', f'⟩ → Wequiv ⟨a, f⟩ ⟨a', f'⟩
| trans (u v w : q.P.W) : Wequiv u v → Wequiv v w → Wequiv u w
/-- recF is insensitive to the representation -/
theorem recF_eq_of_Wequiv {α : Type u} (u : F α → α) (x y : q.P.W) :
Wequiv x y → recF u x = recF u y :=
begin
cases x with a f, cases y with b g,
intro h, induction h,
case qpf.Wequiv.ind : a f f' h ih
{ simp only [recF_eq', pfunctor.map_eq, function.comp, ih] },
case qpf.Wequiv.abs : a f a' f' h
{ simp only [recF_eq', abs_map, h] },
case qpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂
{ exact eq.trans ih₁ ih₂ }
end
theorem Wequiv.abs' (x y : q.P.W) (h : abs x.dest = abs y.dest) :
Wequiv x y :=
by { cases x, cases y, apply Wequiv.abs, apply h }
theorem Wequiv.refl (x : q.P.W) : Wequiv x x :=
by cases x with a f; exact Wequiv.abs a f a f rfl
theorem Wequiv.symm (x y : q.P.W) : Wequiv x y → Wequiv y x :=
begin
cases x with a f, cases y with b g,
intro h, induction h,
case qpf.Wequiv.ind : a f f' h ih
{ exact Wequiv.ind _ _ _ ih },
case qpf.Wequiv.abs : a f a' f' h
{ exact Wequiv.abs _ _ _ _ h.symm },
case qpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂
{ exact qpf.Wequiv.trans _ _ _ ih₂ ih₁}
end
/-- maps every element of the W type to a canonical representative -/
def Wrepr : q.P.W → q.P.W := recF (pfunctor.W.mk ∘ repr)
theorem Wrepr_equiv (x : q.P.W) : Wequiv (Wrepr x) x :=
begin
induction x with a f ih,
apply Wequiv.trans,
{ change Wequiv (Wrepr ⟨a, f⟩) (pfunctor.W.mk (Wrepr <$> ⟨a, f⟩)),
apply Wequiv.abs',
have : Wrepr ⟨a, f⟩ = pfunctor.W.mk (repr (abs (Wrepr <$> ⟨a, f⟩))) := rfl,
rw [this, pfunctor.W.dest_mk, abs_repr],
reflexivity },
apply Wequiv.ind, exact ih
end
/--
Define the fixed point as the quotient of trees under the equivalence relation `Wequiv`.
-/
def W_setoid : setoid q.P.W :=
⟨Wequiv, @Wequiv.refl _ _ _, @Wequiv.symm _ _ _, @Wequiv.trans _ _ _⟩
local attribute [instance] W_setoid
/-- inductive type defined as initial algebra of a Quotient of Polynomial Functor -/
@[nolint has_inhabited_instance]
def fix (F : Type u → Type u) [functor F] [q : qpf F] := quotient (W_setoid : setoid q.P.W)
/-- recursor of a type defined by a qpf -/
def fix.rec {α : Type*} (g : F α → α) : fix F → α :=
quot.lift (recF g) (recF_eq_of_Wequiv g)
/-- access the underlying W-type of a fixpoint data type -/
def fix_to_W : fix F → q.P.W :=
quotient.lift Wrepr (recF_eq_of_Wequiv (λ x, @pfunctor.W.mk q.P (repr x)))
/-- constructor of a type defined by a qpf -/
def fix.mk (x : F (fix F)) : fix F := quot.mk _ (pfunctor.W.mk (fix_to_W <$> repr x))
/-- destructor of a type defined by a qpf -/
def fix.dest : fix F → F (fix F) := fix.rec (functor.map fix.mk)
theorem fix.rec_eq {α : Type*} (g : F α → α) (x : F (fix F)) :
fix.rec g (fix.mk x) = g (fix.rec g <$> x) :=
have recF g ∘ fix_to_W = fix.rec g,
by { apply funext, apply quotient.ind, intro x, apply recF_eq_of_Wequiv,
rw fix_to_W, apply Wrepr_equiv },
begin
conv { to_lhs, rw [fix.rec, fix.mk], dsimp },
cases h : repr x with a f,
rw [pfunctor.map_eq, recF_eq, ←pfunctor.map_eq, pfunctor.W.dest_mk, ←pfunctor.comp_map,
abs_map, ←h, abs_repr, this]
end
theorem fix.ind_aux (a : q.P.A) (f : q.P.B a → q.P.W) :
fix.mk (abs ⟨a, λ x, ⟦f x⟧⟩) = ⟦⟨a, f⟩⟧ :=
have fix.mk (abs ⟨a, λ x, ⟦f x⟧⟩) = ⟦Wrepr ⟨a, f⟩⟧,
begin
apply quot.sound, apply Wequiv.abs',
rw [pfunctor.W.dest_mk, abs_map, abs_repr, ←abs_map, pfunctor.map_eq],
conv { to_rhs, simp only [Wrepr, recF_eq, pfunctor.W.dest_mk, abs_repr] },
reflexivity
end,
by { rw this, apply quot.sound, apply Wrepr_equiv }
theorem fix.ind_rec {α : Type u} (g₁ g₂ : fix F → α)
(h : ∀ x : F (fix F), g₁ <$> x = g₂ <$> x → g₁ (fix.mk x) = g₂ (fix.mk x)) :
∀ x, g₁ x = g₂ x :=
begin
apply quot.ind,
intro x,
induction x with a f ih,
change g₁ ⟦⟨a, f⟩⟧ = g₂ ⟦⟨a, f⟩⟧,
rw [←fix.ind_aux a f], apply h,
rw [←abs_map, ←abs_map, pfunctor.map_eq, pfunctor.map_eq],
dsimp [function.comp],
congr, ext x, apply ih
end
theorem fix.rec_unique {α : Type u} (g : F α → α) (h : fix F → α)
(hyp : ∀ x, h (fix.mk x) = g (h <$> x)) :
fix.rec g = h :=
begin
ext x,
apply fix.ind_rec,
intros x hyp',
rw [hyp, ←hyp', fix.rec_eq]
end
theorem fix.mk_dest (x : fix F) : fix.mk (fix.dest x) = x :=
begin
change (fix.mk ∘ fix.dest) x = id x,
apply fix.ind_rec,
intro x, dsimp,
rw [fix.dest, fix.rec_eq, id_map, comp_map],
intro h, rw h
end
theorem fix.dest_mk (x : F (fix F)) : fix.dest (fix.mk x) = x :=
begin
unfold fix.dest, rw [fix.rec_eq, ←fix.dest, ←comp_map],
conv { to_rhs, rw ←(id_map x) },
congr, ext x, apply fix.mk_dest
end
theorem fix.ind (p : fix F → Prop)
(h : ∀ x : F (fix F), liftp p x → p (fix.mk x)) :
∀ x, p x :=
begin
apply quot.ind,
intro x,
induction x with a f ih,
change p ⟦⟨a, f⟩⟧,
rw [←fix.ind_aux a f],
apply h,
rw liftp_iff,
refine ⟨_, _, rfl, _⟩,
apply ih
end
end qpf
/-
Construct the final coalgebra to a qpf.
-/
namespace qpf
variables {F : Type u → Type u} [functor F] [q : qpf F]
include q
open functor (liftp liftr)
/-- does recursion on `q.P.M` using `g : α → F α` rather than `g : α → P α` -/
def corecF {α : Type*} (g : α → F α) : α → q.P.M :=
pfunctor.M.corec (λ x, repr (g x))
theorem corecF_eq {α : Type*} (g : α → F α) (x : α) :
pfunctor.M.dest (corecF g x) = corecF g <$> repr (g x) :=
by rw [corecF, pfunctor.M.dest_corec]
/- Equivalence -/
/-- A pre-congruence on q.P.M *viewed as an F-coalgebra*. Not necessarily symmetric. -/
def is_precongr (r : q.P.M → q.P.M → Prop) : Prop :=
∀ ⦃x y⦄, r x y →
abs (quot.mk r <$> pfunctor.M.dest x) = abs (quot.mk r <$> pfunctor.M.dest y)
/-- The maximal congruence on q.P.M -/
def Mcongr : q.P.M → q.P.M → Prop :=
λ x y, ∃ r, is_precongr r ∧ r x y
/-- coinductive type defined as the final coalgebra of a qpf -/
def cofix (F : Type u → Type u) [functor F] [q : qpf F]:= quot (@Mcongr F _ q)
instance [inhabited q.P.A] : inhabited (cofix F) := ⟨ quot.mk _ (default _) ⟩
/-- corecursor for type defined by `cofix` -/
def cofix.corec {α : Type*} (g : α → F α) (x : α) : cofix F :=
quot.mk _ (corecF g x)
/-- destructor for type defined by `cofix` -/
def cofix.dest : cofix F → F (cofix F) :=
quot.lift
(λ x, quot.mk Mcongr <$> (abs (pfunctor.M.dest 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 [comp_map, ←abs_map, pr rxy, abs_map, ←comp_map] }
end
theorem cofix.dest_corec {α : Type u} (g : α → F α) (x : α) :
cofix.dest (cofix.corec g x) = cofix.corec g <$> g x :=
begin
conv { to_lhs, rw [cofix.dest, cofix.corec] }, dsimp,
rw [corecF_eq, abs_map, abs_repr, ←comp_map], reflexivity
end
private theorem cofix.bisim_aux
(r : cofix F → cofix F → Prop)
(h' : ∀ x, r x x)
(h : ∀ x y, r x y → quot.mk r <$> cofix.dest x = 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₀: quot.mk r <$> quot.mk Mcongr <$> abs (pfunctor.M.dest a) =
quot.mk r <$> quot.mk Mcongr <$> abs (pfunctor.M.dest b) := 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, pfunctor.comp_map _ _ f, pfunctor.comp_map _ _ (quot.mk r),
abs_map, abs_map, abs_map, h₀],
rw [pfunctor.comp_map _ _ f, pfunctor.comp_map _ _ (quot.mk r),
abs_map, abs_map, abs_map] },
refine ⟨r', this, rxy⟩
end
theorem cofix.bisim_rel
(r : cofix F → cofix F → Prop)
(h : ∀ x y, r x y → quot.mk r <$> cofix.dest x = 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 [@comp_map _ _ q _ _ _ (quot.mk r), @comp_map _ _ q _ _ _ (quot.mk r)],
rw h _ _ r'xy },
right, exact rxy
end
theorem cofix.bisim
(r : cofix F → cofix F → Prop)
(h : ∀ x y, r x y → liftr 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 r _ _).mp (h x y rxy) with ⟨a, f₀, f₁, dxeq, dyeq, h'⟩,
rw [dxeq, dyeq, ←abs_map, ←abs_map, pfunctor.map_eq, pfunctor.map_eq],
congr' 2, ext i,
apply quot.sound,
apply h'
end
theorem cofix.bisim' {α : Type*} (Q : α → Prop) (u v : α → cofix F)
(h : ∀ x, Q x → ∃ a f f',
cofix.dest (u x) = abs ⟨a, f⟩ ∧
cofix.dest (v x) = abs ⟨a, 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', ux'eq, vx'eq, h'⟩,
rw liftr_iff,
refine ⟨a, f, f', xeq.symm ▸ ux'eq, yeq.symm ▸ vx'eq, h'⟩,
end)
_ _ ⟨x, Qx, rfl, rfl⟩
end qpf
/-
Composition of qpfs.
-/
namespace qpf
variables {F₂ : Type u → Type u} [functor F₂] [q₂ : qpf F₂]
variables {F₁ : Type u → Type u} [functor F₁] [q₁ : qpf F₁]
include q₂ q₁
/-- composition of qpfs gives another qpf -/
def comp : qpf (functor.comp F₂ F₁) :=
{ P := pfunctor.comp (q₂.P) (q₁.P),
abs := λ α,
begin
dsimp [functor.comp],
intro p,
exact abs ⟨p.1.1, λ x, abs ⟨p.1.2 x, λ y, p.2 ⟨x, y⟩⟩⟩
end,
repr := λ α,
begin
dsimp [functor.comp],
intro y,
refine ⟨⟨(repr y).1, λ u, (repr ((repr y).2 u)).1⟩, _⟩,
dsimp [pfunctor.comp],
intro x,
exact (repr ((repr y).2 x.1)).snd x.2
end,
abs_repr := λ α,
begin
abstract {
dsimp [functor.comp],
intro x,
conv { to_rhs, rw ←abs_repr x},
cases h : repr x with a f,
dsimp,
congr,
ext x,
cases h' : repr (f x) with b g,
dsimp, rw [←h', abs_repr] }
end,
abs_map := λ α β f,
begin
abstract {
dsimp [functor.comp, pfunctor.comp],
intro p,
cases p with a g, dsimp,
cases a with b h, dsimp,
symmetry,
transitivity,
symmetry,
apply abs_map,
congr,
rw pfunctor.map_eq,
dsimp [function.comp],
simp [abs_map],
split,
reflexivity,
ext x,
rw ←abs_map,
reflexivity }
end
}
end qpf
/-
Quotients.
We show that if `F` is a qpf and `G` is a suitable quotient of `F`, then `G` is a qpf.
-/
namespace qpf
variables {F : Type u → Type u} [functor F] [q : qpf F]
variables {G : Type u → Type u} [functor G]
variable {FG_abs : Π {α}, F α → G α}
variable {FG_repr : Π {α}, G α → F α}
/-- Given a qpf `F` and a well-behaved surjection `FG_abs` from F α to
functor G α, `G` is a qpf. We can consider `G` a quotient on `F` where
elements `x y : F α` are in the same equivalence class if
`FG_abs x = FG_abs y` -/
def quotient_qpf
(FG_abs_repr : Π {α} (x : G α), FG_abs (FG_repr x) = x)
(FG_abs_map : ∀ {α β} (f : α → β) (x : F α), FG_abs (f <$> x) = f <$> FG_abs x) :
qpf G :=
{ P := q.P,
abs := λ {α} p, FG_abs (abs p),
repr := λ {α} x, repr (FG_repr x),
abs_repr := λ {α} x, by rw [abs_repr, FG_abs_repr],
abs_map := λ {α β} f x, by { rw [abs_map, FG_abs_map] } }
end qpf
/-
Support.
-/
namespace qpf
variables {F : Type u → Type u} [functor F] [q : qpf F]
include q
open functor (liftp liftr supp)
open set
theorem mem_supp {α : Type u} (x : F α) (u : α) :
u ∈ supp x ↔ ∀ a f, abs ⟨a, f⟩ = x → u ∈ f '' univ :=
begin
rw [supp], dsimp, split,
{ intros h a f haf,
have : liftp (λ u, u ∈ f '' univ) x,
{ rw liftp_iff, refine ⟨a, f, haf.symm, λ i, mem_image_of_mem _ (mem_univ _)⟩ },
exact h this },
intros h p, rw liftp_iff,
rintros ⟨a, f, xeq, h'⟩,
rcases h a f xeq.symm with ⟨i, _, hi⟩,
rw ←hi, apply h'
end
theorem supp_eq {α : Type u} (x : F α) : supp x = { u | ∀ a f, abs ⟨a, f⟩ = x → u ∈ f '' univ } :=
by ext; apply mem_supp
theorem has_good_supp_iff {α : Type u} (x : F α) :
(∀ p, liftp p x ↔ ∀ u ∈ supp x, p u) ↔
∃ a f, abs ⟨a, f⟩ = x ∧ ∀ a' f', abs ⟨a', f'⟩ = x → f '' univ ⊆ f' '' univ :=
begin
split,
{ intro h,
have : liftp (supp x) x, by rw h; intro u; exact id,
rw liftp_iff at this, rcases this with ⟨a, f, xeq, h'⟩,
refine ⟨a, f, xeq.symm, _⟩,
intros a' f' h'',
rintros u ⟨i, _, hfi⟩,
have : u ∈ supp x, by rw ←hfi; apply h',
exact (mem_supp x u).mp this _ _ h'' },
rintros ⟨a, f, xeq, h⟩ p, rw liftp_iff, split,
{ rintros ⟨a', f', xeq', h'⟩ u usuppx,
rcases (mem_supp x u).mp usuppx a' f' xeq'.symm with ⟨i, _, f'ieq⟩,
rw ←f'ieq, apply h' },
intro h',
refine ⟨a, f, xeq.symm, _⟩, intro i,
apply h', rw mem_supp,
intros a' f' xeq',
apply h a' f' xeq',
apply mem_image_of_mem _ (mem_univ _)
end
variable (q)
/-- A qpf is said to be uniform if every polynomial functor
representing a single value all have the same range. -/
def is_uniform : Prop := ∀ ⦃α : Type u⦄ (a a' : q.P.A)
(f : q.P.B a → α) (f' : q.P.B a' → α),
abs ⟨a, f⟩ = abs ⟨a', f'⟩ → f '' univ = f' '' univ
variable [q]
theorem supp_eq_of_is_uniform (h : q.is_uniform) {α : Type u} (a : q.P.A) (f : q.P.B a → α) :
supp (abs ⟨a, f⟩) = f '' univ :=
begin
ext u, rw [mem_supp], split,
{ intro h', apply h' _ _ rfl },
intros h' a' f' e,
rw [←h _ _ _ _ e.symm], apply h'
end
theorem liftp_iff_of_is_uniform (h : q.is_uniform) {α : Type u} (x : F α) (p : α → Prop) :
liftp p x ↔ ∀ u ∈ supp x, p u :=
begin
rw [liftp_iff, ←abs_repr x],
cases repr x with a f, split,
{ rintros ⟨a', f', abseq, hf⟩ u,
rw [supp_eq_of_is_uniform h, h _ _ _ _ abseq],
rintros ⟨i, _, hi⟩, rw ←hi, apply hf },
intro h',
refine ⟨a, f, rfl, λ i, h' _ _⟩,
rw supp_eq_of_is_uniform h,
exact ⟨i, mem_univ i, rfl⟩
end
theorem supp_map (h : q.is_uniform) {α β : Type u} (g : α → β) (x : F α) :
supp (g <$> x) = g '' supp x :=
begin
rw ←abs_repr x, cases repr x with a f, rw [←abs_map, pfunctor.map_eq],
rw [supp_eq_of_is_uniform h, supp_eq_of_is_uniform h, image_comp]
end
end qpf
|
8e37396b1d368df3f3deda986ff1164c732e70ff
|
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
|
/order/complete_lattice.lean
|
ae38ecbfc8824aab5a395757ca91a71236acd2b4
|
[
"Apache-2.0"
] |
permissive
|
kckennylau/mathlib
|
21fb810b701b10d6606d9002a4004f7672262e83
|
47b3477e20ffb5a06588dd3abb01fe0fe3205646
|
refs/heads/master
| 1,634,976,409,281
| 1,542,042,832,000
| 1,542,319,733,000
| 109,560,458
| 0
| 0
|
Apache-2.0
| 1,542,369,208,000
| 1,509,867,494,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 30,750
|
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
Theory of complete lattices.
-/
import order.bounded_lattice data.set.basic tactic.pi_instances
set_option old_structure_cmd true
open set
namespace lattice
universes u v w w₂
variables {α : Type u} {β : Type v} {ι : Sort w} {ι₂ : Sort w₂}
/-- class for the `Sup` operator -/
class has_Sup (α : Type u) := (Sup : set α → α)
/-- class for the `Inf` operator -/
class has_Inf (α : Type u) := (Inf : set α → α)
/-- Supremum of a set -/
def Sup [has_Sup α] : set α → α := has_Sup.Sup
/-- Infimum of a set -/
def Inf [has_Inf α] : set α → α := has_Inf.Inf
/-- Indexed supremum -/
def supr [has_Sup α] (s : ι → α) : α := Sup (range s)
/-- Indexed infimum -/
def infi [has_Inf α] (s : ι → α) : α := Inf (range s)
notation `⨆` binders `, ` r:(scoped f, supr f) := r
notation `⨅` binders `, ` r:(scoped f, infi f) := r
/-- A complete lattice is a bounded lattice which
has suprema and infima for every subset. -/
class complete_lattice (α : Type u) extends bounded_lattice α, has_Sup α, has_Inf α :=
(le_Sup : ∀s, ∀a∈s, a ≤ Sup s)
(Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a)
(Inf_le : ∀s, ∀a∈s, Inf s ≤ a)
(le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s)
/-- A complete linear order is a linear order whose lattice structure is complete. -/
class complete_linear_order (α : Type u) extends complete_lattice α, linear_order α
section
variables [complete_lattice α] {s t : set α} {a b : α}
@[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_lattice.le_Sup s a
theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_lattice.Sup_le s a
@[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_lattice.Inf_le s a
theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_lattice.le_Inf s a
theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s :=
le_trans h (le_Sup hb)
theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a :=
le_trans (Inf_le hb) h
theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t :=
Sup_le (assume a, assume ha : a ∈ s, le_Sup $ h ha)
theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s :=
le_Inf (assume a, assume ha : a ∈ s, Inf_le $ h ha)
@[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) :=
⟨assume : Sup s ≤ a, assume b, assume : b ∈ s,
le_trans (le_Sup ‹b ∈ s›) ‹Sup s ≤ a›,
Sup_le⟩
@[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) :=
⟨assume : a ≤ Inf s, assume b, assume : b ∈ s,
le_trans ‹a ≤ Inf s› (Inf_le ‹b ∈ s›),
le_Inf⟩
-- how to state this? instead a parameter `a`, use `∃a, a ∈ s` or `s ≠ ∅`?
theorem Inf_le_Sup (h : a ∈ s) : Inf s ≤ Sup s :=
by have := le_Sup h; finish
--Inf_le_of_le h (le_Sup h)
-- TODO: it is weird that we have to add union_def
theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t :=
le_antisymm
(by finish)
(sup_le (Sup_le_Sup $ subset_union_left _ _) (Sup_le_Sup $ subset_union_right _ _))
/- old proof:
le_antisymm
(Sup_le $ assume a h, or.rec_on h (le_sup_left_of_le ∘ le_Sup) (le_sup_right_of_le ∘ le_Sup))
(sup_le (Sup_le_Sup $ subset_union_left _ _) (Sup_le_Sup $ subset_union_right _ _))
-/
theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t :=
by finish
/-
Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t))
-/
theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t :=
le_antisymm
(le_inf (Inf_le_Inf $ subset_union_left _ _) (Inf_le_Inf $ subset_union_right _ _))
(by finish)
/- old proof:
le_antisymm
(le_inf (Inf_le_Inf $ subset_union_left _ _) (Inf_le_Inf $ subset_union_right _ _))
(le_Inf $ assume a h, or.rec_on h (inf_le_left_of_le ∘ Inf_le) (inf_le_right_of_le ∘ Inf_le))
-/
theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) :=
by finish
/-
le_Inf (assume a ⟨a_s, a_t⟩, sup_le (Inf_le a_s) (Inf_le a_t))
-/
@[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) :=
le_antisymm (by finish) (by finish)
-- le_antisymm (Sup_le (assume _, false.elim)) bot_le
@[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) :=
le_antisymm (by finish) (by finish)
--le_antisymm le_top (le_Inf (assume _, false.elim))
@[simp] theorem Sup_univ : Sup univ = (⊤ : α) :=
le_antisymm (by finish) (le_Sup ⟨⟩) -- finish fails because ⊤ ≤ a simplifies to a = ⊤
--le_antisymm le_top (le_Sup ⟨⟩)
@[simp] theorem Inf_univ : Inf univ = (⊥ : α) :=
le_antisymm (Inf_le ⟨⟩) bot_le
-- TODO(Jeremy): get this automatically
@[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s :=
have Sup {b | b = a} = a,
from le_antisymm (Sup_le $ assume b b_eq, b_eq ▸ le_refl _) (le_Sup rfl),
calc Sup (insert a s) = Sup {b | b = a} ⊔ Sup s : Sup_union
... = a ⊔ Sup s : by rw [this]
@[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s :=
have Inf {b | b = a} = a,
from le_antisymm (Inf_le rfl) (le_Inf $ assume b b_eq, b_eq ▸ le_refl _),
calc Inf (insert a s) = Inf {b | b = a} ⊓ Inf s : Inf_union
... = a ⊓ Inf s : by rw [this]
@[simp] theorem Sup_singleton {a : α} : Sup {a} = a :=
by finish [singleton_def]
--eq.trans Sup_insert $ by simp
@[simp] theorem Inf_singleton {a : α} : Inf {a} = a :=
by finish [singleton_def]
--eq.trans Inf_insert $ by simp
@[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) :=
iff.intro
(assume h a ha, top_unique $ h ▸ Inf_le ha)
(assume h, top_unique $ le_Inf $ assume a ha, top_le_iff.2 $ h a ha)
@[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) :=
iff.intro
(assume h a ha, bot_unique $ h ▸ le_Sup ha)
(assume h, bot_unique $ Sup_le $ assume a ha, le_bot_iff.2 $ h a ha)
end
section complete_linear_order
variables [complete_linear_order α] {s t : set α} {a b : α}
lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) :=
iff.intro
(assume : Inf s < b, classical.by_contradiction $ assume : ¬ (∃a∈s, a < b),
have b ≤ Inf s,
from le_Inf $ assume a ha, le_of_not_gt $ assume h, this ⟨a, ha, h⟩,
lt_irrefl b (lt_of_le_of_lt ‹b ≤ Inf s› ‹Inf s < b›))
(assume ⟨a, ha, h⟩, lt_of_le_of_lt (Inf_le ha) h)
lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) :=
iff.intro
(assume : b < Sup s, classical.by_contradiction $ assume : ¬ (∃a∈s, b < a),
have Sup s ≤ b,
from Sup_le $ assume a ha, le_of_not_gt $ assume h, this ⟨a, ha, h⟩,
lt_irrefl b (lt_of_lt_of_le ‹b < Sup s› ‹Sup s ≤ b›))
(assume ⟨a, ha, h⟩, lt_of_lt_of_le h $ le_Sup ha)
lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) :=
iff.intro
(assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb)
(assume h, top_unique $ le_of_not_gt $ assume h',
let ⟨a, ha, h⟩ := h _ h' in
lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h)
lemma Inf_eq_bot : Inf s = ⊥ ↔ (∀b>⊥, ∃a∈s, a < b) :=
iff.intro
(assume (h : Inf s = ⊥) b (hb : ⊥ < b), by rwa [←h, Inf_lt_iff] at hb)
(assume h, bot_unique $ le_of_not_gt $ assume h',
let ⟨a, ha, h⟩ := h _ h' in
lt_irrefl a $ lt_of_lt_of_le h (Inf_le ha))
lemma lt_supr_iff {ι : Sort*} {f : ι → α} : a < supr f ↔ (∃i, a < f i) :=
iff.trans lt_Sup_iff $ iff.intro
(assume ⟨a', ⟨i, rfl⟩, ha⟩, ⟨i, ha⟩)
(assume ⟨i, hi⟩, ⟨f i, ⟨i, rfl⟩, hi⟩)
lemma infi_lt_iff {ι : Sort*} {f : ι → α} : infi f < a ↔ (∃i, f i < a) :=
iff.trans Inf_lt_iff $ iff.intro
(assume ⟨a', ⟨i, rfl⟩, ha⟩, ⟨i, ha⟩)
(assume ⟨i, hi⟩, ⟨f i, ⟨i, rfl⟩, hi⟩)
end complete_linear_order
/- supr & infi -/
section
variables [complete_lattice α] {s t : ι → α} {a b : α}
-- TODO: this declaration gives error when starting smt state
--@[ematch]
theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s :=
le_Sup ⟨i, rfl⟩
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) :=
le_Sup ⟨i, rfl⟩
/- TODO: this version would be more powerful, but, alas, the pattern matcher
doesn't accept it.
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) :=
le_Sup ⟨i, rfl⟩
-/
theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s :=
le_trans h (le_supr _ i)
theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a :=
Sup_le $ assume b ⟨i, eq⟩, eq ▸ h i
theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t :=
supr_le $ assume i, le_supr_of_le i (h i)
theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t :=
supr_le $ assume j, exists.elim (h j) le_supr_of_le
theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) :=
supr_le $ le_supr _ ∘ h
@[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) :=
⟨assume : supr s ≤ a, assume i, le_trans (le_supr _ _) this, supr_le⟩
-- TODO: finish doesn't do well here.
@[congr] theorem supr_congr_Prop {α : Type u} [has_Sup α] {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ :=
begin
unfold supr,
apply congr_arg,
ext,
simp,
split,
exact λ⟨h, W⟩, ⟨pq.1 h, eq.trans (f (pq.1 h)).symm W⟩,
exact λ⟨h, W⟩, ⟨pq.2 h, eq.trans (f h) W⟩
end
theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i :=
Inf_le ⟨i, rfl⟩
@[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) :=
Inf_le ⟨i, rfl⟩
/- I wanted to see if this would help for infi_comm; it doesn't.
@[ematch] theorem infi_le₂' (s : ι → ι₂ → α) (i : ι) (j : ι₂): (: ⨅ i j, s i j :) ≤ (: s i j :) :=
begin
transitivity,
apply (infi_le (λ i, ⨅ j, s i j) i),
apply infi_le
end
-/
theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a :=
le_trans (infi_le _ i) h
theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s :=
le_Inf $ assume b ⟨i, eq⟩, eq ▸ h i
theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t :=
le_infi $ assume i, infi_le_of_le i (h i)
theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t :=
le_infi $ assume j, exists.elim (h j) infi_le_of_le
theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) :=
le_infi $ infi_le _ ∘ h
@[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) :=
⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩
@[congr] theorem infi_congr_Prop {α : Type u} [has_Inf α] {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ :=
begin
unfold infi,
apply congr_arg,
ext,
simp,
split,
exact λ⟨h, W⟩, ⟨pq.1 h, eq.trans (f (pq.1 h)).symm W⟩,
exact λ⟨h, W⟩, ⟨pq.2 h, eq.trans (f h) W⟩
end
@[simp] theorem infi_const {a : α} : ∀[nonempty ι], (⨅ b:ι, a) = a
| ⟨i⟩ := le_antisymm (Inf_le ⟨i, rfl⟩) (by finish)
@[simp] theorem supr_const {a : α} : ∀[nonempty ι], (⨆ b:ι, a) = a
| ⟨i⟩ := le_antisymm (by finish) (le_Sup ⟨i, rfl⟩)
@[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ :=
top_unique $ le_infi $ assume i, le_refl _
@[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ :=
bot_unique $ supr_le $ assume i, le_refl _
@[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) :=
iff.intro
(assume eq i, top_unique $ eq ▸ infi_le _ _)
(assume h, top_unique $ le_infi $ assume i, top_le_iff.2 $ h i)
@[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) :=
iff.intro
(assume eq i, bot_unique $ eq ▸ le_supr _ _)
(assume h, bot_unique $ supr_le $ assume i, le_bot_iff.2 $ h i)
@[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp :=
le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _)
@[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ :=
le_antisymm le_top $ le_infi $ assume h, (hp h).elim
@[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp :=
le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _)
@[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ :=
le_antisymm (supr_le $ assume h, (hp h).elim) bot_le
-- TODO: should this be @[simp]?
theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i)
(le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j)
/- TODO: this is strange. In the proof below, we get exactly the desired
among the equalities, but close does not get it.
begin
apply @le_antisymm,
simp, intros,
begin [smt]
ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i),
trace_state, close
end
end
-/
-- TODO: should this be @[simp]?
theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) :=
le_antisymm
(supr_le $ assume i, supr_le $ assume j, le_supr_of_le j $ le_supr _ i)
(supr_le $ assume j, supr_le $ assume i, le_supr_of_le i $ le_supr _ j)
@[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl :=
le_antisymm
(supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end)
(le_supr_of_le b $ le_supr _ rfl)
@[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl :=
le_antisymm
(supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end)
(le_supr_of_le b $ le_supr _ rfl)
attribute [ematch] le_refl
theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) :=
le_antisymm
(le_inf
(le_infi $ assume i, infi_le_of_le i inf_le_left)
(le_infi $ assume i, infi_le_of_le i inf_le_right))
(le_infi $ assume i, le_inf
(inf_le_left_of_le $ infi_le _ _)
(inf_le_right_of_le $ infi_le _ _))
/- TODO: here is another example where more flexible pattern matching
might help.
begin
apply @le_antisymm,
safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end
end
-/
lemma infi_inf {f : ι → α} {a : α} (i : ι) : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) :=
le_antisymm
(le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) inf_le_right)
(le_inf (infi_le_infi $ assume i, inf_le_left) (infi_le_of_le i inf_le_right))
lemma inf_infi {f : ι → α} {a : α} (i : ι) : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) :=
by rw [inf_comm, infi_inf i]; simp [inf_comm]
lemma binfi_inf {ι : Sort*} {p : ι → Prop}
{f : Πi, p i → α} {a : α} {i : ι} (hi : p i) :
(⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume hi,
le_inf (inf_le_left_of_le $ infi_le_of_le i $ infi_le _ _) inf_le_right)
(le_inf (infi_le_infi $ assume i, infi_le_infi $ assume hi, inf_le_left)
(infi_le_of_le i $ infi_le_of_le hi $ inf_le_right))
theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) :=
le_antisymm
(supr_le $ assume i, sup_le
(le_sup_left_of_le $ le_supr _ _)
(le_sup_right_of_le $ le_supr _ _))
(sup_le
(supr_le $ assume i, le_supr_of_le i le_sup_left)
(supr_le $ assume i, le_supr_of_le i le_sup_right))
/- supr and infi under Prop -/
@[simp] theorem infi_false {s : false → α} : infi s = ⊤ :=
le_antisymm le_top (le_infi $ assume i, false.elim i)
@[simp] theorem supr_false {s : false → α} : supr s = ⊥ :=
le_antisymm (supr_le $ assume i, false.elim i) bot_le
@[simp] theorem infi_true {s : true → α} : infi s = s trivial :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_true {s : true → α} : supr s = s trivial :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
@[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
@[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, s ⟨i, j⟩) _)
(supr_le $ assume i, supr_le $ assume j, le_supr _ _)
theorem infi_or {p q : Prop} {s : p ∨ q → α} :
infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume i, match i with
| or.inl i := inf_le_left_of_le $ infi_le _ _
| or.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_or {p q : Prop} {s : p ∨ q → α} :
(⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) :=
le_antisymm
(supr_le $ assume s, match s with
| or.inl i := le_sup_left_of_le $ le_supr _ i
| or.inr j := le_sup_right_of_le $ le_supr _ j
end)
(sup_le
(supr_le_supr2 $ assume i, ⟨or.inl i, le_refl _⟩)
(supr_le_supr2 $ assume j, ⟨or.inr j, le_refl _⟩))
theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) :=
le_antisymm
(le_infi $ assume b, le_infi $ assume h, Inf_le h)
(le_Inf $ assume b h, infi_le_of_le b $ infi_le _ h)
theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) :=
le_antisymm
(Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h)
(supr_le $ assume b, supr_le $ assume h, le_Sup h)
lemma Sup_range {α : Type u} [has_Sup α] {f : ι → α} : Sup (range f) = supr f := rfl
lemma Inf_range {α : Type u} [has_Inf α] {f : ι → α} : Inf (range f) = infi f := rfl
lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) :=
le_antisymm
(supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i)
(supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) (mem_range_self _))
lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) :=
le_antisymm
(le_infi $ assume i, infi_le_of_le (f i) $ infi_le (λp, g (f i)) (mem_range_self _))
(le_infi $ assume b, le_infi $ assume ⟨i, (h : f i = b)⟩, h ▸ infi_le _ i)
theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) :=
calc Inf (set.image f s) = (⨅a, ⨅h : ∃b, b ∈ s ∧ f b = a, a) : Inf_eq_infi
... = (⨅a, ⨅b, ⨅h : f b = a ∧ b ∈ s, a) : by simp [and_comm]
... = (⨅a, ⨅b, ⨅h : a = f b, ⨅h : b ∈ s, a) : by simp [infi_and, eq_comm]
... = (⨅b, ⨅a, ⨅h : a = f b, ⨅h : b ∈ s, a) : by rw [infi_comm]
... = (⨅a∈s, f a) : congr_arg infi $ by funext x; rw [infi_infi_eq_left]
theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) :=
calc Sup (set.image f s) = (⨆a, ⨆h : ∃b, b ∈ s ∧ f b = a, a) : Sup_eq_supr
... = (⨆a, ⨆b, ⨆h : f b = a ∧ b ∈ s, a) : by simp [and_comm]
... = (⨆a, ⨆b, ⨆h : a = f b, ⨆h : b ∈ s, a) : by simp [supr_and, eq_comm]
... = (⨆b, ⨆a, ⨆h : a = f b, ⨆h : b ∈ s, a) : by rw [supr_comm]
... = (⨆a∈s, f a) : congr_arg supr $ by funext x; rw [supr_supr_eq_left]
/- supr and infi under set constructions -/
/- should work using the simplifier! -/
@[simp] theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ :=
le_antisymm le_top (le_infi $ assume x, le_infi false.elim)
@[simp] theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ :=
le_antisymm (supr_le $ assume x, supr_le false.elim) bot_le
@[simp] theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) :=
show (⨅ (x : β) (H : true), f x) = ⨅ (x : β), f x,
from congr_arg infi $ funext $ assume x, infi_const
@[simp] theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) :=
show (⨆ (x : β) (H : true), f x) = ⨆ (x : β), f x,
from congr_arg supr $ funext $ assume x, supr_const
@[simp] theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) :=
calc (⨅ x ∈ s ∪ t, f x) = (⨅ x, (⨅h : x∈s, f x) ⊓ (⨅h : x∈t, f x)) : congr_arg infi $ funext $ assume x, infi_or
... = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) : infi_inf_eq
@[simp] theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) :=
calc (⨆ x ∈ s ∪ t, f x) = (⨆ x, (⨆h : x∈s, f x) ⊔ (⨆h : x∈t, f x)) : congr_arg supr $ funext $ assume x, supr_or
... = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) : supr_sup_eq
@[simp] theorem insert_of_has_insert (x : α) (a : set α) : has_insert.insert x a = insert x a := rfl
@[simp] theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) :=
eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left
@[simp] theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) :=
eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left
@[simp] theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b :=
show (⨅ x ∈ insert b (∅ : set β), f x) = f b,
by simp
@[simp] theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b :=
show (⨆ x ∈ insert b (∅ : set β), f x) = f b,
by simp
/- supr and infi under Type -/
@[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ :=
le_antisymm le_top (le_infi $ assume i, empty.rec_on _ i)
@[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ :=
le_antisymm (supr_le $ assume i, empty.rec_on _ i) bot_le
@[simp] theorem infi_unit {f : unit → α} : (⨅ x, f x) = f () :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_unit {f : unit → α} : (⨆ x, f x) = f () :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff :=
le_antisymm
(supr_le $ assume b, match b with tt := le_sup_left | ff := le_sup_right end)
(sup_le (le_supr _ _) (le_supr _ _))
lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff :=
le_antisymm
(le_inf (infi_le _ _) (infi_le _ _))
(le_infi $ assume b, match b with tt := inf_le_left | ff := inf_le_right end)
theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_sigma {p : β → Type w} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_sigma {p : β → Type w} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_prod {γ : Type w} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_prod {γ : Type w} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, f ⟨i, j⟩) _)
(supr_le $ assume i, supr_le $ assume j, le_supr _ _)
theorem infi_sum {γ : Type w} {f : β ⊕ γ → α} :
(⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume i, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume s, match s with
| sum.inl i := inf_le_left_of_le $ infi_le _ _
| sum.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_sum {γ : Type w} {f : β ⊕ γ → α} :
(⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) :=
le_antisymm
(supr_le $ assume s, match s with
| sum.inl i := le_sup_left_of_le $ le_supr _ i
| sum.inr j := le_sup_right_of_le $ le_supr _ j
end)
(sup_le
(supr_le_supr2 $ assume i, ⟨sum.inl i, le_refl _⟩)
(supr_le_supr2 $ assume j, ⟨sum.inr j, le_refl _⟩))
end
section complete_linear_order
variables [complete_linear_order α]
lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) :=
by rw [← Sup_range, Sup_eq_top];
from forall_congr (assume b, forall_congr (assume hb, set.exists_range_iff))
lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, b > f i) :=
by rw [← Inf_range, Inf_eq_bot];
from forall_congr (assume b, forall_congr (assume hb, set.exists_range_iff))
end complete_linear_order
/- Instances -/
instance complete_lattice_Prop : complete_lattice Prop :=
{ Sup := λs, ∃a∈s, a,
le_Sup := assume s a h p, ⟨a, h, p⟩,
Sup_le := assume s a h ⟨b, h', p⟩, h b h' p,
Inf := λs, ∀a:Prop, a∈s → a,
Inf_le := assume s a h p, p a h,
le_Inf := assume s a h p b hb, h b hb p,
..lattice.bounded_lattice_Prop }
lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl
lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl
lemma infi_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨅i, p i) = (∀i, p i) :=
le_antisymm (assume h i, h _ ⟨i, rfl⟩ ) (assume h p ⟨i, eq⟩, eq ▸ h i)
lemma supr_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨆i, p i) = (∃i, p i) :=
le_antisymm (assume ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (assume ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩)
instance pi.complete_lattice {α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] :
complete_lattice (Π i, β i) :=
by { pi_instance;
{ intros, intro,
apply_field, intros,
simp at H, rcases H with ⟨ x, H₀, H₁ ⟩,
subst b, apply a_1 _ H₀ i, } }
lemma Inf_apply
{α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] {s : set (Πa, β a)} {a : α} :
(Inf s) a = (⨅f∈s, (f : Πa, β a) a) :=
by rw [← Inf_image]; refl
lemma infi_apply {α : Type u} {β : α → Type v} {ι : Sort*} [∀ i, complete_lattice (β i)]
{f : ι → Πa, β a} {a : α} : (⨅i, f i) a = (⨅i, f i a) :=
by erw [← Inf_range, Inf_apply, infi_range]
lemma Sup_apply
{α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] {s : set (Πa, β a)} {a : α} :
(Sup s) a = (⨆f∈s, (f : Πa, β a) a) :=
by rw [← Sup_image]; refl
lemma supr_apply {α : Type u} {β : α → Type v} {ι : Sort*} [∀ i, complete_lattice (β i)]
{f : ι → Πa, β a} {a : α} : (⨆i, f i) a = (⨆i, f i a) :=
by erw [← Sup_range, Sup_apply, supr_range]
section complete_lattice
variables [preorder α] [complete_lattice β]
theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) :=
assume x y h, Sup_le $ assume x' ⟨f, f_in, fx_eq⟩, le_Sup_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h
theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) :=
assume x y h, le_Inf $ assume x' ⟨f, f_in, fx_eq⟩, Inf_le_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h
end complete_lattice
section ord_continuous
open lattice
variables [complete_lattice α] [complete_lattice β]
/-- A function `f` between complete lattices is order-continuous
if it preserves all suprema. -/
def ord_continuous (f : α → β) := ∀s : set α, f (Sup s) = (⨆i∈s, f i)
lemma ord_continuous_sup {f : α → β} {a₁ a₂ : α} (hf : ord_continuous f) : f (a₁ ⊔ a₂) = f a₁ ⊔ f a₂ :=
have h : f (Sup {a₁, a₂}) = (⨆i∈({a₁, a₂} : set α), f i), from hf _,
have h₁ : {a₁, a₂} = (insert a₂ {a₁} : set α), from rfl,
begin
rw [h₁, Sup_insert, Sup_singleton, sup_comm] at h,
rw [h, supr_insert, supr_singleton, sup_comm]
end
lemma ord_continuous_mono {f : α → β} (hf : ord_continuous f) : monotone f :=
assume a₁ a₂ h,
calc f a₁ ≤ f a₁ ⊔ f a₂ : le_sup_left
... = f (a₁ ⊔ a₂) : (ord_continuous_sup hf).symm
... = _ : by rw [sup_of_le_right h]
end ord_continuous
end lattice
namespace order_dual
open lattice
variable (α : Type*)
instance [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩
instance [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩
instance [complete_lattice α] : complete_lattice (order_dual α) :=
{ le_Sup := @complete_lattice.Inf_le α _,
Sup_le := @complete_lattice.le_Inf α _,
Inf_le := @complete_lattice.le_Sup α _,
le_Inf := @complete_lattice.Sup_le α _,
.. order_dual.lattice.bounded_lattice α, ..order_dual.lattice.has_Sup α, ..order_dual.lattice.has_Inf α }
end order_dual
|
55f850ab7f15a1ac96386411d7f5f610ee56032a
|
2a70b774d16dbdf5a533432ee0ebab6838df0948
|
/_target/deps/mathlib/src/topology/category/CompHaus.lean
|
64347d5560ed7bdd525ff0c8e75d66b800e02581
|
[
"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
| 1,740
|
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
@[simp]
lemma coe_to_Top {X : CompHaus} : (X.to_Top : Type*) = X :=
rfl
end CompHaus
/-- The fully faithful embedding of `CompHaus` in `Top`. -/
@[simps, derive [full, faithful]]
def CompHaus_to_Top : CompHaus ⥤ Top := induced_functor _
|
4ba7466e062a6c4800d16188df883bb25ffb9bb0
|
947b78d97130d56365ae2ec264df196ce769371a
|
/tests/lean/run/patbug.lean
|
d5e07c85dc6fb5b50b364b0f9441604695860165
|
[
"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
| 213
|
lean
|
new_frontend
open Lean
def f : Name → Name
| n@(`foo.bla) => n
| _ => Name.anonymous
def tst : IO Unit := do
when (hash `foo.bla != hash (f `foo.bla)) $
throw $ IO.userError "bug"
IO.println "ok"
#eval tst
|
f503618e6dd6334f405127f5bdb3330060a65dba
|
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
|
/tests/lean/run/Reid1.lean
|
4d71c55276818db458933177eeb09e9e03b68340
|
[
"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
| 689
|
lean
|
structure ConstantFunction (α β : Type) :=
(f : α → β)
(h : ∀ a₁ a₂, f a₁ = f a₂)
instance constFunCoe {α β : Type} : CoeFun (ConstantFunction α β) (fun _ => α → β) :=
{ coe := fun c => c.f }
def myFun {α : Type} : ConstantFunction α (Option α) :=
{ f := fun a => none,
h := fun a₁ a₂ => rfl }
def myFun' (α : Type) : ConstantFunction α (Option α) :=
{ f := fun a => none,
h := fun a₁ a₂ => rfl }
set_option pp.all true
#check myFun 3 -- works
#check @myFun Nat 3 -- works
#check myFun' _ 3 -- works
#check myFun' Nat 3 -- works
variable (c : ConstantFunction Nat Nat)
#check c 3 -- works
#check (fun c => c 3) myFun -- works
|
c27300ec044c22b094f9cee9574c237c8cd60322
|
037dba89703a79cd4a4aec5e959818147f97635d
|
/src/2020/sets/canonical.lean
|
ff79002f36e916aed997925ef0ffd66000daee75
|
[] |
no_license
|
ImperialCollegeLondon/M40001_lean
|
3a6a09298da395ab51bc220a535035d45bbe919b
|
62a76fa92654c855af2b2fc2bef8e60acd16ccec
|
refs/heads/master
| 1,666,750,403,259
| 1,665,771,117,000
| 1,665,771,117,000
| 209,141,835
| 115
| 12
| null | 1,640,270,596,000
| 1,568,749,174,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 850
|
lean
|
import tactic
/- Let α be a fixed ground set, which is a type.
There is a bijection between
(a) the type `α → Prop` whose terms
are functions from `α` to `Prop`, and
(b) the type `set α`, whose terms
are subsets of α.
-/
def canonical (α : Type) : (α → Prop) ≃ (set α) :=
{ to_fun :=
-- construction A
-- let P be a function from α to Prop
λ P,
-- Then return the subset {x | P x} of α
{x : α | P x},
inv_fun :=
-- construction B
-- let X be a subset of α,
λ X,
-- and let's define a function from α to Prop.
-- So say x is in α,
λ a,
-- and we're supposed to be returning a Prop,
-- so let's return `a ∈ X`
a ∈ X,
left_inv := begin
intro P,
ext a,
dsimp,
refl,
end
,
right_inv := begin
intro X,
refl,
end }
|
9275fb58978aafe541b94948597cb69e766e17df
|
4efff1f47634ff19e2f786deadd394270a59ecd2
|
/src/category_theory/abelian/basic.lean
|
4c8c3c155fa864dc12a9579480a3814d53b33c73
|
[
"Apache-2.0"
] |
permissive
|
agjftucker/mathlib
|
d634cd0d5256b6325e3c55bb7fb2403548371707
|
87fe50de17b00af533f72a102d0adefe4a2285e8
|
refs/heads/master
| 1,625,378,131,941
| 1,599,166,526,000
| 1,599,166,526,000
| 160,748,509
| 0
| 0
|
Apache-2.0
| 1,544,141,789,000
| 1,544,141,789,000
| null |
UTF-8
|
Lean
| false
| false
| 22,103
|
lean
|
/-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import category_theory.limits.shapes.constructions.pullbacks
import category_theory.limits.shapes.regular_mono
import category_theory.limits.shapes.biproducts
import category_theory.limits.shapes.images
import category_theory.abelian.non_preadditive
/-!
# Abelian categories
This file contains the definition and basic properties of abelian categories.
There are many definitions of abelian category. Our definition is as follows:
A category is called abelian if it is preadditive,
has a finite products, kernels and cokernels,
and if every monomorphism and epimorphism is normal.
It should be noted that if we also assume coproducts, then preadditivity is
actually a consequence of the other properties, as we show in
`non_preadditive_abelian.lean`. However, this fact is of little practical
relevance, since essentially all interesting abelian categories come with a
preadditive structure. In this way, by requiring preadditivity, we allow the
user to pass in the preadditive structure the specific category they are
working with has natively.
## Main definitions
* `abelian` is the type class indicating that a category is abelian. It extends `preadditive`.
* `abelian.image f` is `kernel (cokernel.π f)`, and
* `abelian.coimage f` is `cokernel (kernel.ι f)`.
## Main results
* In an abelian category, mono + epi = iso.
* If `f : X ⟶ Y`, then the map `factor_thru_image f : X ⟶ image f` is an epimorphism, and the map
`factor_thru_coimage f : coimage f ⟶ Y` is a monomorphism.
* Factoring through the image and coimage is a strong epi-mono factorisation. This means that
* every abelian category has images. We instantiated this in such a way that `abelian.image f` is
definitionally equal to `limits.image f`, and
* there is a canonical isomorphism `coimage_iso_image : coimage f ≅ image f` such that
`coimage.π f ≫ (coimage_iso_image f).hom ≫ image.ι f = f`. The lemma stating this is called
`full_image_factorisation`.
* Every epimorphism is a cokernel of its kernel. Every monomorphism is a kernel of its cokernel.
* The pullback of an epimorphism is an epimorphism. The pushout of a monomorphism is a monomorphism.
(This is not to be confused with the fact that the pullback of a monomorphism is a monomorphism,
which is true in any category).
## Implementation notes
The typeclass `abelian` does not extend `non_preadditive_abelian`,
to avoid having to deal with comparing the two `has_zero_morphisms` instances
(one from `preadditive` in `abelian`, and the other a field of `non_preadditive_abelian`).
As a consequence, at the beginning of this file we trivially build
a `non_preadditive_abelian` instance from an `abelian` instance,
and use this to restate a number of theorems,
in each case just reusing the proof from `non_preadditive_abelian.lean`.
We don't show this yet, but abelian categories are finitely complete and finitely cocomplete.
However, the limits we can construct at this level of generality will most likely be less nice than
the ones that can be created in specific applications. For this reason, we adopt the following
convention:
* If the statement of a theorem involves limits, the existence of these limits should be made an
explicit typeclass parameter.
* If a limit only appears in a proof, but not in the statement of a theorem, the limit should not
be a typeclass parameter, but instead be created using `abelian.has_pullbacks` or a similar
definition.
## References
* [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2]
* [P. Aluffi, *Algebra: Chaper 0*][aluffi2016]
-/
open category_theory
open category_theory.preadditive
open category_theory.limits
universes v u
namespace category_theory
variables {C : Type u} [category.{v} C]
variables (C)
section prio
set_option default_priority 100
/--
A (preadditive) category `C` is called abelian if it has all finite products,
all kernels and cokernels, and if every monomorphism is the kernel of some morphism
and every epimorphism is the cokernel of some morphism.
(This definition implies the existence of zero objects:
finite products give a terminal object, and in a preadditive category
any terminal object is a zero object.)
-/
class abelian extends preadditive C :=
[has_finite_products : has_finite_products C]
[has_kernels : has_kernels C]
[has_cokernels : has_cokernels C]
(normal_mono : Π {X Y : C} (f : X ⟶ Y) [mono f], normal_mono f)
(normal_epi : Π {X Y : C} (f : X ⟶ Y) [epi f], normal_epi f)
attribute [instance] abelian.has_finite_products
attribute [instance] abelian.has_kernels abelian.has_cokernels
end prio
end category_theory
open category_theory
namespace category_theory.abelian
variables {C : Type u} [category.{v} C] [abelian C]
/-- An abelian category has finite biproducts. -/
def has_finite_biproducts : has_finite_biproducts C :=
limits.has_finite_biproducts.of_has_finite_products
section to_non_preadditive_abelian
local attribute [instance] has_finite_biproducts
/-- Every abelian category is, in particular, `non_preadditive_abelian`. -/
def non_preadditive_abelian : non_preadditive_abelian C := { ..‹abelian C› }
end to_non_preadditive_abelian
section strong
local attribute [instance] abelian.normal_epi
/-- In an abelian category, every epimorphism is strong. -/
def strong_epi_of_epi {P Q : C} (f : P ⟶ Q) [epi f] : strong_epi f := by apply_instance
end strong
section mono_epi_iso
variables {X Y : C} (f : X ⟶ Y)
local attribute [instance] strong_epi_of_epi
/-- In an abelian category, a monomorphism which is also an epimorphism is an isomorphism. -/
def is_iso_of_mono_of_epi [mono f] [epi f] : is_iso f :=
is_iso_of_mono_of_strong_epi _
end mono_epi_iso
section factor
local attribute [instance] non_preadditive_abelian
variables {P Q : C} (f : P ⟶ Q)
namespace images
/-- The kernel of the cokernel of `f` is called the image of `f`. -/
protected abbreviation image : C := kernel (cokernel.π f)
/-- The inclusion of the image into the codomain. -/
protected abbreviation image.ι : images.image f ⟶ Q :=
kernel.ι (cokernel.π f)
/-- There is a canonical epimorphism `p : P ⟶ image f` for every `f`. -/
protected abbreviation factor_thru_image : P ⟶ images.image f :=
kernel.lift (cokernel.π f) f $ cokernel.condition f
/-- `f` factors through its image via the canonical morphism `p`. -/
@[simp, reassoc] protected lemma image.fac :
images.factor_thru_image f ≫ image.ι f = f :=
kernel.lift_ι _ _ _
/-- The map `p : P ⟶ image f` is an epimorphism -/
instance : epi (images.factor_thru_image f) :=
show epi (non_preadditive_abelian.factor_thru_image f), by apply_instance
instance mono_factor_thru_image [mono f] : mono (images.factor_thru_image f) :=
mono_of_mono_fac $ image.fac f
instance is_iso_factor_thru_image [mono f] : is_iso (images.factor_thru_image f) :=
is_iso_of_mono_of_epi _
/-- Factoring through the image is a strong epi-mono factorisation. -/
@[simps] def image_strong_epi_mono_factorisation : strong_epi_mono_factorisation f :=
{ I := images.image f,
m := image.ι f,
m_mono := by apply_instance,
e := images.factor_thru_image f,
e_strong_epi := strong_epi_of_epi _ }
end images
namespace coimages
/-- The cokernel of the kernel of `f` is called the coimage of `f`. -/
protected abbreviation coimage : C := cokernel (kernel.ι f)
/-- The projection onto the coimage. -/
protected abbreviation coimage.π : P ⟶ coimages.coimage f :=
cokernel.π (kernel.ι f)
/-- There is a canonical monomorphism `i : coimage f ⟶ Q`. -/
protected abbreviation factor_thru_coimage : coimages.coimage f ⟶ Q :=
cokernel.desc (kernel.ι f) f $ kernel.condition f
/-- `f` factors through its coimage via the canonical morphism `p`. -/
protected lemma coimage.fac : coimage.π f ≫ coimages.factor_thru_coimage f = f :=
cokernel.π_desc _ _ _
/-- The canonical morphism `i : coimage f ⟶ Q` is a monomorphism -/
instance : mono (coimages.factor_thru_coimage f) :=
show mono (non_preadditive_abelian.factor_thru_coimage f), by apply_instance
instance epi_factor_thru_coimage [epi f] : epi (coimages.factor_thru_coimage f) :=
epi_of_epi_fac $ coimage.fac f
instance is_iso_factor_thru_coimage [epi f] : is_iso (coimages.factor_thru_coimage f) :=
is_iso_of_mono_of_epi _
/-- Factoring through the coimage is a strong epi-mono factorisation. -/
@[simps] def coimage_strong_epi_mono_factorisation : strong_epi_mono_factorisation f :=
{ I := coimages.coimage f,
m := coimages.factor_thru_coimage f,
m_mono := by apply_instance,
e := coimage.π f,
e_strong_epi := strong_epi_of_epi _ }
end coimages
end factor
section has_strong_epi_mono_factorisations
/-- An abelian category has strong epi-mono factorisations. -/
@[priority 100] instance : has_strong_epi_mono_factorisations C :=
⟨λ X Y f, images.image_strong_epi_mono_factorisation f⟩
/- In particular, this means that it has well-behaved images. -/
example : has_images C := by apply_instance
example : has_image_maps C := by apply_instance
end has_strong_epi_mono_factorisations
section images
variables {X Y : C} (f : X ⟶ Y)
lemma image_eq_image : limits.image f = images.image f := rfl
lemma image_ι_eq_image_ι : limits.image.ι f = images.image.ι f := rfl
lemma kernel_cokernel_eq_image_ι : kernel.ι (cokernel.π f) = images.image.ι f := rfl
/-- There is a canonical isomorphism between the coimage and the image of a morphism. -/
abbreviation coimage_iso_image : coimages.coimage f ≅ images.image f :=
is_image.iso_ext (coimages.coimage_strong_epi_mono_factorisation f).to_mono_is_image
(images.image_strong_epi_mono_factorisation f).to_mono_is_image
lemma full_image_factorisation : coimages.coimage.π f ≫ (coimage_iso_image f).hom ≫
images.image.ι f = f :=
by rw [limits.is_image.iso_ext_hom,
←images.image_strong_epi_mono_factorisation_to_mono_factorisation_m, is_image.lift_fac,
coimages.coimage_strong_epi_mono_factorisation_to_mono_factorisation_m, coimages.coimage.fac]
end images
section cokernel_of_kernel
variables {X Y : C} {f : X ⟶ Y}
local attribute [instance] non_preadditive_abelian
/-- In an abelian category, an epi is the cokernel of its kernel. More precisely:
If `f` is an epimorphism and `s` is some limit kernel cone on `f`, then `f` is a cokernel
of `fork.ι s`. -/
def epi_is_cokernel_of_kernel [epi f] (s : fork f 0) (h : is_limit s) :
is_colimit (cokernel_cofork.of_π f (kernel_fork.condition s)) :=
non_preadditive_abelian.epi_is_cokernel_of_kernel s h
/-- In an abelian category, a mono is the kernel of its cokernel. More precisely:
If `f` is a monomorphism and `s` is some colimit cokernel cocone on `f`, then `f` is a kernel
of `cofork.π s`. -/
def mono_is_kernel_of_cokernel [mono f] (s : cofork f 0) (h : is_colimit s) :
is_limit (kernel_fork.of_ι f (cokernel_cofork.condition s)) :=
non_preadditive_abelian.mono_is_kernel_of_cokernel s h
end cokernel_of_kernel
section
local attribute [instance] preadditive.has_equalizers_of_has_kernels
/-- Any abelian category has pullbacks -/
def has_pullbacks : has_pullbacks C :=
has_pullbacks_of_has_binary_products_of_has_equalizers C
end
section
local attribute [instance] preadditive.has_coequalizers_of_has_cokernels
local attribute [instance] has_binary_biproducts.of_has_binary_products
/-- Any abelian category has pushouts -/
def has_pushouts : has_pushouts C :=
has_pushouts_of_has_binary_coproducts_of_has_coequalizers C
end
namespace pullback_to_biproduct_is_kernel
variables [limits.has_pullbacks C] {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z)
local attribute [instance] has_binary_biproducts.of_has_binary_products
/-! This section contains a slightly technical result about pullbacks and biproducts.
We will need it in the proof that the pullback of an epimorphism is an epimorpism. -/
/-- The canonical map `pullback f g ⟶ X ⊞ Y` -/
abbreviation pullback_to_biproduct : pullback f g ⟶ X ⊞ Y :=
biprod.lift pullback.fst pullback.snd
/-- The canonical map `pullback f g ⟶ X ⊞ Y` induces a kernel cone on the map
`biproduct X Y ⟶ Z` induced by `f` and `g`. A slightly more intuitive way to think of
this may be that it induces an equalizer fork on the maps induced by `(f, 0)` and
`(0, g)`. -/
abbreviation pullback_to_biproduct_fork : kernel_fork (biprod.desc f (-g)) :=
kernel_fork.of_ι (pullback_to_biproduct f g) $
by rw [biprod.lift_desc, comp_neg, pullback.condition, add_right_neg]
local attribute [irreducible] has_limit_cospan_of_has_limit_pair_of_has_limit_parallel_pair
/-- The canonical map `pullback f g ⟶ X ⊞ Y` is a kernel of the map induced by
`(f, -g)`. -/
def is_limit_pullback_to_biproduct : is_limit (pullback_to_biproduct_fork f g) :=
fork.is_limit.mk _
(λ s, pullback.lift (fork.ι s ≫ biprod.fst) (fork.ι s ≫ biprod.snd) $
sub_eq_zero.1 $ by rw [category.assoc, category.assoc, ←comp_sub, sub_eq_add_neg, ←comp_neg,
←biprod.desc_eq, kernel_fork.condition s])
(λ s,
begin
ext; rw [fork.ι_of_ι, category.assoc],
{ rw [prod.lift_fst, pullback.lift_fst] },
{ rw [prod.lift_snd, pullback.lift_snd] }
end)
(λ s m h, by ext; simp [fork.ι_eq_app_zero, ←h walking_parallel_pair.zero])
end pullback_to_biproduct_is_kernel
namespace biproduct_to_pushout_is_cokernel
variables [limits.has_pushouts C] {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z)
local attribute [instance] has_binary_biproducts.of_has_binary_products
/-- The canonical map `Y ⊞ Z ⟶ pushout f g` -/
abbreviation biproduct_to_pushout : Y ⊞ Z ⟶ pushout f g :=
biprod.desc pushout.inl pushout.inr
/-- The canonical map `Y ⊞ Z ⟶ pushout f g` induces a cokernel cofork on the map
`X ⟶ Y ⊞ Z` induced by `f` and `-g`. -/
abbreviation biproduct_to_pushout_cofork : cokernel_cofork (biprod.lift f (-g)) :=
cokernel_cofork.of_π (biproduct_to_pushout f g) $
by rw [biprod.lift_desc, neg_comp, pushout.condition, add_right_neg]
/-- The cofork induced by the canonical map `Y ⊞ Z ⟶ pushout f g` is in fact a colimit cokernel
cofork. -/
def is_colimit_biproduct_to_pushout : is_colimit (biproduct_to_pushout_cofork f g) :=
cofork.is_colimit.mk _
(λ s, pushout.desc (biprod.inl ≫ cofork.π s) (biprod.inr ≫ cofork.π s) $
sub_eq_zero.1 $ by rw [←category.assoc, ←category.assoc, ←sub_comp, sub_eq_add_neg, ←neg_comp,
←biprod.lift_eq, cofork.condition s, has_zero_morphisms.zero_comp])
(λ s, by ext; simp)
(λ s m h, by ext; simp [cofork.π_eq_app_one, ←h walking_parallel_pair.one] )
end biproduct_to_pushout_is_cokernel
section epi_pullback
variables [limits.has_pullbacks C] {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z)
local attribute [instance] has_binary_biproducts.of_has_binary_products
/-- In an abelian category, the pullback of an epimorphism is an epimorphism.
Proof from [aluffi2016, IX.2.3], cf. [borceux-vol2, 1.7.6] -/
instance epi_pullback_of_epi_f [epi f] : epi (pullback.snd : pullback f g ⟶ Y) :=
-- It will suffice to consider some morphism e : Y ⟶ R such that
-- pullback.snd ≫ e = 0 and show that e = 0.
epi_of_cancel_zero _ $ λ R e h,
begin
-- Consider the morphism u := (0, e) : X ⊞ Y⟶ R.
let u := biprod.desc (0 : X ⟶ R) e,
-- The composite pullback f g ⟶ X ⊞ Y ⟶ R is zero by assumption.
have hu : pullback_to_biproduct_is_kernel.pullback_to_biproduct f g ≫ u = 0 := by simpa,
-- pullback_to_biproduct f g is a kernel of (f, -g), so (f, -g) is a
-- cokernel of pullback_to_biproduct f g
have := epi_is_cokernel_of_kernel _
(pullback_to_biproduct_is_kernel.is_limit_pullback_to_biproduct f g),
-- We use this fact to obtain a factorization of u through (f, -g) via some d : Z ⟶ R.
obtain ⟨d, hd⟩ := cokernel_cofork.is_colimit.desc' this u hu,
change Z ⟶ R at d,
change biprod.desc f (-g) ≫ d = u at hd,
-- But then f ≫ d = 0:
have : f ≫ d = 0, calc
f ≫ d = (biprod.inl ≫ biprod.desc f (-g)) ≫ d : by rw coprod.inl_desc
... = biprod.inl ≫ u : by rw [category.assoc, hd]
... = 0 : coprod.inl_desc _ _,
-- But f is an epimorphism, so d = 0...
have : d = 0 := (cancel_epi f).1 (by simpa),
-- ...or, in other words, e = 0.
calc
e = biprod.inr ≫ u : by rw coprod.inr_desc
... = biprod.inr ≫ biprod.desc f (-g) ≫ d : by rw ←hd
... = biprod.inr ≫ biprod.desc f (-g) ≫ 0 : by rw this
... = (biprod.inr ≫ biprod.desc f (-g)) ≫ 0 : by rw ←category.assoc
... = 0 : has_zero_morphisms.comp_zero _ _
end
/-- In an abelian category, the pullback of an epimorphism is an epimorphism. -/
instance epi_pullback_of_epi_g [epi g] : epi (pullback.fst : pullback f g ⟶ X) :=
-- It will suffice to consider some morphism e : X ⟶ R such that
-- pullback.fst ≫ e = 0 and show that e = 0.
epi_of_cancel_zero _ $ λ R e h,
begin
-- Consider the morphism u := (e, 0) : X ⊞ Y ⟶ R.
let u := biprod.desc e (0 : Y ⟶ R),
-- The composite pullback f g ⟶ X ⊞ Y ⟶ R is zero by assumption.
have hu : pullback_to_biproduct_is_kernel.pullback_to_biproduct f g ≫ u = 0 := by simpa,
-- pullback_to_biproduct f g is a kernel of (f, -g), so (f, -g) is a
-- cokernel of pullback_to_biproduct f g
have := epi_is_cokernel_of_kernel _
(pullback_to_biproduct_is_kernel.is_limit_pullback_to_biproduct f g),
-- We use this fact to obtain a factorization of u through (f, -g) via some d : Z ⟶ R.
obtain ⟨d, hd⟩ := cokernel_cofork.is_colimit.desc' this u hu,
change Z ⟶ R at d,
change biprod.desc f (-g) ≫ d = u at hd,
-- But then (-g) ≫ d = 0:
have : (-g) ≫ d = 0, calc
(-g) ≫ d = (biprod.inr ≫ biprod.desc f (-g)) ≫ d : by rw coprod.inr_desc
... = biprod.inr ≫ u : by rw [category.assoc, hd]
... = 0 : coprod.inr_desc _ _,
-- But g is an epimorphism, thus so is -g, so d = 0...
have : d = 0 := (cancel_epi (-g)).1 (by simpa),
-- ...or, in other words, e = 0.
calc
e = biprod.inl ≫ u : by rw coprod.inl_desc
... = biprod.inl ≫ biprod.desc f (-g) ≫ d : by rw ←hd
... = biprod.inl ≫ biprod.desc f (-g) ≫ 0 : by rw this
... = (biprod.inl ≫ biprod.desc f (-g)) ≫ 0 : by rw ←category.assoc
... = 0 : has_zero_morphisms.comp_zero _ _
end
end epi_pullback
section mono_pushout
variables [limits.has_pushouts C] {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z)
local attribute [instance] has_binary_biproducts.of_has_binary_products
instance mono_pushout_of_mono_f [mono f] : mono (pushout.inr : Z ⟶ pushout f g) :=
mono_of_cancel_zero _ $ λ R e h,
begin
let u := biprod.lift (0 : R ⟶ Y) e,
have hu : u ≫ biproduct_to_pushout_is_cokernel.biproduct_to_pushout f g = 0 := by simpa,
have := mono_is_kernel_of_cokernel _
(biproduct_to_pushout_is_cokernel.is_colimit_biproduct_to_pushout f g),
obtain ⟨d, hd⟩ := kernel_fork.is_limit.lift' this u hu,
change R ⟶ X at d,
change d ≫ biprod.lift f (-g) = u at hd,
have : d ≫ f = 0, calc
d ≫ f = d ≫ biprod.lift f (-g) ≫ biprod.fst : by rw prod.lift_fst
... = u ≫ biprod.fst : by rw [←category.assoc, hd]
... = 0 : prod.lift_fst _ _,
have : d = 0 := (cancel_mono f).1 (by simpa),
calc
e = u ≫ biprod.snd : by rw prod.lift_snd
... = (d ≫ biprod.lift f (-g)) ≫ biprod.snd : by rw ←hd
... = (0 ≫ biprod.lift f (-g)) ≫ biprod.snd : by rw this
... = 0 ≫ biprod.lift f (-g) ≫ biprod.snd : by rw category.assoc
... = 0 : has_zero_morphisms.zero_comp _ _
end
instance mono_pushout_of_mono_g [mono g] : mono (pushout.inl : Y ⟶ pushout f g) :=
mono_of_cancel_zero _ $ λ R e h,
begin
let u := biprod.lift e (0 : R ⟶ Z),
have hu : u ≫ biproduct_to_pushout_is_cokernel.biproduct_to_pushout f g = 0 := by simpa,
have := mono_is_kernel_of_cokernel _
(biproduct_to_pushout_is_cokernel.is_colimit_biproduct_to_pushout f g),
obtain ⟨d, hd⟩ := kernel_fork.is_limit.lift' this u hu,
change R ⟶ X at d,
change d ≫ biprod.lift f (-g) = u at hd,
have : d ≫ (-g) = 0, calc
d ≫ (-g) = d ≫ biprod.lift f (-g) ≫ biprod.snd : by rw prod.lift_snd
... = u ≫ biprod.snd : by rw [←category.assoc, hd]
... = 0 : prod.lift_snd _ _,
have : d = 0 := (cancel_mono (-g)).1 (by simpa),
calc
e = u ≫ biprod.fst : by rw prod.lift_fst
... = (d ≫ biprod.lift f (-g)) ≫ biprod.fst : by rw ←hd
... = (0 ≫ biprod.lift f (-g)) ≫ biprod.fst : by rw this
... = 0 ≫ biprod.lift f (-g) ≫ biprod.fst : by rw category.assoc
... = 0 : has_zero_morphisms.zero_comp _ _
end
end mono_pushout
end category_theory.abelian
namespace category_theory.non_preadditive_abelian
variables (C : Type u) [category.{v} C] [non_preadditive_abelian C]
/-- Every non_preadditive_abelian category can be promoted to an abelian category. -/
def abelian : abelian C :=
{ has_finite_products := infer_instance,
/- We need the `convert`s here because the instances we have are slightly different from the
instances we need: `has_kernels` depends on an instance of `has_zero_morphisms`. In the
case of `non_preadditive_abelian`, this instance is an explicit argument. However, in the case
of `abelian`, the `has_zero_morphisms` instance is derived from `preadditive`. So we need to
transform an instance of "has kernels with non_preadditive_abelian.has_zero_morphisms" to an
instance of "has kernels with non_preadditive_abelian.preadditive.has_zero_morphisms". Luckily,
we have a `subsingleton` instance for `has_zero_morphisms`, so `convert` can immediately close
the goal it creates for the two instances of `has_zero_morphisms`, and the proof is complete. -/
has_kernels := by convert (infer_instance : limits.has_kernels C),
has_cokernels := by convert (infer_instance : limits.has_cokernels C),
normal_mono := by { introsI, convert normal_mono f },
normal_epi := by { introsI, convert normal_epi f },
..non_preadditive_abelian.preadditive }
end category_theory.non_preadditive_abelian
|
acab900a68e7c876669702d79954c0c3f72dc83d
|
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
|
/tests/lean/well_founded_tactics.lean
|
576d65eaca4e8f62b686f55ddf3e26af3a95f9da
|
[
"Apache-2.0"
] |
permissive
|
kbuzzard/lean
|
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
|
ed1788fd674bb8991acffc8fca585ec746711928
|
refs/heads/master
| 1,620,983,366,617
| 1,618,937,600,000
| 1,618,937,600,000
| 359,886,396
| 1
| 0
|
Apache-2.0
| 1,618,936,987,000
| 1,618,936,987,000
| null |
UTF-8
|
Lean
| false
| false
| 255
|
lean
|
variables {α : Type} {lt : α → α → Prop} [decidable_rel lt]
def merge : list α → list α → list α
| [] l' := l'
| l [] := l
| (a :: l) (b :: l') := if lt a b then a :: merge l (b :: l') else b :: merge (a :: l) l'
|
ccd59376780dc4069152290d4dfa1ff91db91a39
|
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
|
/src/algebra/regular/basic.lean
|
f0b5e342e48cd80ab56ad1855b8de216141135ae
|
[
"Apache-2.0"
] |
permissive
|
AntoineChambert-Loir/mathlib
|
64aabb896129885f12296a799818061bc90da1ff
|
07be904260ab6e36a5769680b6012f03a4727134
|
refs/heads/master
| 1,693,187,631,771
| 1,636,719,886,000
| 1,636,719,886,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 11,590
|
lean
|
/-
Copyright (c) 2021 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import algebra.order.monoid_lemmas
import algebra.group_with_zero.basic
import logic.embedding
/-!
# Regular elements
We introduce left-regular, right-regular and regular elements.
By definition, a regular element in a commutative ring is a non-zero divisor.
Lemma `is_regular_of_ne_zero` implies that every non-zero element of an integral domain is regular.
Since it assumes that the ring is a `cancel_monoid_with_zero` it applies also, for instance, to `ℕ`.
The lemmas in Section `mul_zero_class` show that the `0` element is (left/right-)regular if and
only if the `mul_zero_class` is trivial. This is useful when figuring out stopping conditions for
regular sequences: if `0` is ever an element of a regular sequence, then we can extend the sequence
by adding one further `0`.
The final goal is to develop part of the API to prove, eventually, results about non-zero-divisors.
-/
variables {R : Type*} {a b : R}
section has_mul
variable [has_mul R]
/-- A left-regular element is an element `c` such that multiplication on the left by `c`
is injective on the left. -/
def is_left_regular (c : R) := function.injective ((*) c)
/-- A right-regular element is an element `c` such that multiplication on the right by `c`
is injective on the right. -/
def is_right_regular (c : R) := function.injective (* c)
/-- A regular element is an element `c` such that multiplication by `c` both on the left and
on the right is injective. -/
structure is_regular (c : R) : Prop :=
(left : is_left_regular c)
(right : is_right_regular c)
protected lemma mul_le_cancellable.is_left_regular [partial_order R] {a : R}
(ha : mul_le_cancellable a) : is_left_regular a :=
ha.injective
end has_mul
section semigroup
variable [semigroup R]
/-- In a semigroup, the product of left-regular elements is left-regular. -/
lemma is_left_regular.mul (lra : is_left_regular a) (lrb : is_left_regular b) :
is_left_regular (a * b) :=
show function.injective ((*) (a * b)), from (comp_mul_left a b) ▸ lra.comp lrb
/-- In a semigroup, the product of right-regular elements is right-regular. -/
lemma is_right_regular.mul (rra : is_right_regular a) (rrb : is_right_regular b) :
is_right_regular (a * b) :=
show function.injective (* (a * b)), from (comp_mul_right b a) ▸ rrb.comp rra
/-- If an element `b` becomes left-regular after multiplying it on the left by a left-regular
element, then `b` is left-regular. -/
lemma is_left_regular.of_mul (ab : is_left_regular (a * b)) :
is_left_regular b :=
function.injective.of_comp (by rwa comp_mul_left a b)
/-- An element is left-regular if and only if multiplying it on the left by a left-regular element
is left-regular. -/
@[simp] lemma mul_is_left_regular_iff (b : R) (ha : is_left_regular a) :
is_left_regular (a * b) ↔ is_left_regular b :=
⟨λ ab, is_left_regular.of_mul ab, λ ab, is_left_regular.mul ha ab⟩
/-- If an element `b` becomes right-regular after multiplying it on the right by a right-regular
element, then `b` is right-regular. -/
lemma is_right_regular.of_mul (ab : is_right_regular (b * a)) :
is_right_regular b :=
begin
refine λ x y xy, ab (_ : x * (b * a) = y * (b * a)),
rw [← mul_assoc, ← mul_assoc],
exact congr_fun (congr_arg has_mul.mul xy) a,
end
/-- An element is right-regular if and only if multiplying it on the right with a right-regular
element is right-regular. -/
@[simp] lemma mul_is_right_regular_iff (b : R) (ha : is_right_regular a) :
is_right_regular (b * a) ↔ is_right_regular b :=
⟨λ ab, is_right_regular.of_mul ab, λ ab, is_right_regular.mul ab ha⟩
/-- Two elements `a` and `b` are regular if and only if both products `a * b` and `b * a`
are regular. -/
lemma is_regular_mul_and_mul_iff :
is_regular (a * b) ∧ is_regular (b * a) ↔ is_regular a ∧ is_regular b :=
begin
refine ⟨_, _⟩,
{ rintros ⟨ab, ba⟩,
exact ⟨⟨is_left_regular.of_mul ba.left, is_right_regular.of_mul ab.right⟩,
⟨is_left_regular.of_mul ab.left, is_right_regular.of_mul ba.right⟩⟩ },
{ rintros ⟨ha, hb⟩,
exact ⟨⟨(mul_is_left_regular_iff _ ha.left).mpr hb.left,
(mul_is_right_regular_iff _ hb.right).mpr ha.right⟩,
⟨(mul_is_left_regular_iff _ hb.left).mpr ha.left,
(mul_is_right_regular_iff _ ha.right).mpr hb.right⟩⟩ }
end
/-- The "most used" implication of `mul_and_mul_iff`, with split hypotheses, instead of `∧`. -/
lemma is_regular.and_of_mul_of_mul (ab : is_regular (a * b)) (ba : is_regular (b * a)) :
is_regular a ∧ is_regular b :=
is_regular_mul_and_mul_iff.mp ⟨ab, ba⟩
end semigroup
section mul_zero_class
variables [mul_zero_class R]
/-- The element `0` is left-regular if and only if `R` is trivial. -/
lemma is_left_regular.subsingleton (h : is_left_regular (0 : R)) : subsingleton R :=
⟨λ a b, h $ eq.trans (zero_mul a) (zero_mul b).symm⟩
/-- The element `0` is right-regular if and only if `R` is trivial. -/
lemma is_right_regular.subsingleton (h : is_right_regular (0 : R)) : subsingleton R :=
⟨λ a b, h $ eq.trans (mul_zero a) (mul_zero b).symm⟩
/-- The element `0` is regular if and only if `R` is trivial. -/
lemma is_regular.subsingleton (h : is_regular (0 : R)) : subsingleton R :=
h.left.subsingleton
/-- The element `0` is left-regular if and only if `R` is trivial. -/
lemma is_left_regular_zero_iff_subsingleton : is_left_regular (0 : R) ↔ subsingleton R :=
begin
refine ⟨λ h, h.subsingleton, _⟩,
intros H a b h,
exact @subsingleton.elim _ H a b
end
/-- In a non-trivial `mul_zero_class`, the `0` element is not left-regular. -/
lemma not_is_left_regular_zero_iff : ¬ is_left_regular (0 : R) ↔ nontrivial R :=
begin
rw [nontrivial_iff, not_iff_comm, is_left_regular_zero_iff_subsingleton, subsingleton_iff],
push_neg,
exact iff.rfl
end
/-- The element `0` is right-regular if and only if `R` is trivial. -/
lemma is_right_regular_zero_iff_subsingleton : is_right_regular (0 : R) ↔ subsingleton R :=
begin
refine ⟨λ h, h.subsingleton, _⟩,
intros H a b h,
exact @subsingleton.elim _ H a b
end
/-- In a non-trivial `mul_zero_class`, the `0` element is not right-regular. -/
lemma not_is_right_regular_zero_iff : ¬ is_right_regular (0 : R) ↔ nontrivial R :=
begin
rw [nontrivial_iff, not_iff_comm, is_right_regular_zero_iff_subsingleton, subsingleton_iff],
push_neg,
exact iff.rfl
end
/-- The element `0` is regular if and only if `R` is trivial. -/
lemma is_regular_iff_subsingleton : is_regular (0 : R) ↔ subsingleton R :=
⟨λ h, h.left.subsingleton,
λ h, ⟨is_left_regular_zero_iff_subsingleton.mpr h, is_right_regular_zero_iff_subsingleton.mpr h⟩⟩
/-- A left-regular element of a `nontrivial` `mul_zero_class` is non-zero. -/
lemma is_left_regular.ne_zero [nontrivial R] (la : is_left_regular a) : a ≠ 0 :=
begin
rintro rfl,
rcases exists_pair_ne R with ⟨x, y, xy⟩,
refine xy (la _),
rw [zero_mul, zero_mul]
end
/-- A right-regular element of a `nontrivial` `mul_zero_class` is non-zero. -/
lemma is_right_regular.ne_zero [nontrivial R] (ra : is_right_regular a) : a ≠ 0 :=
begin
rintro rfl,
rcases exists_pair_ne R with ⟨x, y, xy⟩,
refine xy (ra (_ : x * 0 = y * 0)),
rw [mul_zero, mul_zero]
end
/-- A regular element of a `nontrivial` `mul_zero_class` is non-zero. -/
lemma is_regular.ne_zero [nontrivial R] (la : is_regular a) : a ≠ 0 :=
la.left.ne_zero
/-- In a non-trivial ring, the element `0` is not left-regular -- with typeclasses. -/
lemma not_is_left_regular_zero [nR : nontrivial R] : ¬ is_left_regular (0 : R) :=
not_is_left_regular_zero_iff.mpr nR
/-- In a non-trivial ring, the element `0` is not right-regular -- with typeclasses. -/
lemma not_is_right_regular_zero [nR : nontrivial R] : ¬ is_right_regular (0 : R) :=
not_is_right_regular_zero_iff.mpr nR
/-- In a non-trivial ring, the element `0` is not regular -- with typeclasses. -/
lemma not_is_regular_zero [nontrivial R] : ¬ is_regular (0 : R) :=
λ h, is_regular.ne_zero h rfl
end mul_zero_class
section comm_semigroup
variable [comm_semigroup R]
/-- A product is regular if and only if the factors are. -/
lemma is_regular_mul_iff : is_regular (a * b) ↔ is_regular a ∧ is_regular b :=
begin
refine iff.trans _ is_regular_mul_and_mul_iff,
refine ⟨λ ab, ⟨ab, by rwa mul_comm⟩, λ rab, rab.1⟩
end
end comm_semigroup
section monoid
variables [monoid R]
/-- In a monoid, `1` is regular. -/
lemma is_regular_one : is_regular (1 : R) :=
⟨λ a b ab, (one_mul a).symm.trans (eq.trans ab (one_mul b)),
λ a b ab, (mul_one a).symm.trans (eq.trans ab (mul_one b))⟩
/-- An element admitting a left inverse is left-regular. -/
lemma is_left_regular_of_mul_eq_one (h : b * a = 1) : is_left_regular a :=
@is_left_regular.of_mul R _ a _ (by { rw h, exact is_regular_one.left })
/-- An element admitting a right inverse is right-regular. -/
lemma is_right_regular_of_mul_eq_one (h : a * b = 1) : is_right_regular a :=
@is_right_regular.of_mul R _ a _ (by { rw h, exact is_regular_one.right })
/-- If `R` is a monoid, an element in `units R` is regular. -/
lemma units.is_regular (a : units R) : is_regular (a : R) :=
⟨is_left_regular_of_mul_eq_one a.inv_mul, is_right_regular_of_mul_eq_one a.mul_inv⟩
/-- A unit in a monoid is regular. -/
lemma is_unit.is_regular (ua : is_unit a) : is_regular a :=
begin
rcases ua with ⟨a, rfl⟩,
exact units.is_regular a,
end
end monoid
section left_or_right_cancel_semigroup
/--
The embedding of a left cancellative semigroup into itself
by left multiplication by a fixed element.
-/
@[to_additive
"The embedding of a left cancellative additive semigroup into itself
by left translation by a fixed element.", simps]
def mul_left_embedding {G : Type*} [left_cancel_semigroup G] (g : G) : G ↪ G :=
{ to_fun := λ h, g * h, inj' := mul_right_injective g }
/--
The embedding of a right cancellative semigroup into itself
by right multiplication by a fixed element.
-/
@[to_additive
"The embedding of a right cancellative additive semigroup into itself
by right translation by a fixed element.", simps]
def mul_right_embedding {G : Type*} [right_cancel_semigroup G] (g : G) : G ↪ G :=
{ to_fun := λ h, h * g, inj' := mul_left_injective g }
/-- Elements of a left cancel semigroup are left regular. -/
lemma is_left_regular_of_left_cancel_semigroup [left_cancel_semigroup R] (g : R) :
is_left_regular g :=
mul_right_injective g
/-- Elements of a right cancel semigroup are right regular. -/
lemma is_right_regular_of_right_cancel_semigroup [right_cancel_semigroup R] (g : R) :
is_right_regular g :=
mul_left_injective g
end left_or_right_cancel_semigroup
section cancel_monoid
variables [cancel_monoid R]
/-- Elements of a cancel monoid are regular. Cancel semigroups do not appear to exist. -/
lemma is_regular_of_cancel_monoid (g : R) : is_regular g :=
⟨mul_right_injective g, mul_left_injective g⟩
end cancel_monoid
section cancel_monoid_with_zero
variables [cancel_monoid_with_zero R]
/-- Non-zero elements of an integral domain are regular. -/
lemma is_regular_of_ne_zero (a0 : a ≠ 0) : is_regular a :=
⟨λ b c, (mul_right_inj' a0).mp, λ b c, (mul_left_inj' a0).mp⟩
/-- In a non-trivial integral domain, an element is regular iff it is non-zero. -/
lemma is_regular_iff_ne_zero [nontrivial R] : is_regular a ↔ a ≠ 0 :=
⟨is_regular.ne_zero, is_regular_of_ne_zero⟩
end cancel_monoid_with_zero
|
851dae6884a45d2614f9b2a6f66e616e4a19cfc6
|
cf39355caa609c0f33405126beee2739aa3cb77e
|
/tests/lean/run/have4.lean
|
8b1fc7cee09210323aa9d49bf03241b78929d62a
|
[
"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
| 217
|
lean
|
prelude
definition Prop : Type.{1} := Type.{0}
constants a b c : Prop
axiom Ha : a
axiom Hb : b
axiom Hc : c
#check
have H1 : a, from Ha,
have H2 : a, from H1,
have H3 : a, from H2,
have H4 : a, from H3,
H4
|
4d3d5fd155430ad5b51b2943cfac7b2a912c81c3
|
37da0369b6c03e380e057bf680d81e6c9fdf9219
|
/hott/homotopy/interval.hlean
|
d8df97ae0be12dd11865bf99f321914f821c9639
|
[
"Apache-2.0"
] |
permissive
|
kodyvajjha/lean2
|
72b120d95c3a1d77f54433fa90c9810e14a931a4
|
227fcad22ab2bc27bb7471be7911075d101ba3f9
|
refs/heads/master
| 1,627,157,512,295
| 1,501,855,676,000
| 1,504,809,427,000
| 109,317,326
| 0
| 0
| null | 1,509,839,253,000
| 1,509,655,713,000
|
C++
|
UTF-8
|
Lean
| false
| false
| 3,471
|
hlean
|
/-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
Declaration of the interval
-/
import .susp types.eq types.prod cubical.square
open eq susp unit equiv is_trunc nat prod pointed
definition interval : Type₀ := susp unit
namespace interval
definition zero : interval := north
definition one : interval := south
definition seg : zero = one := merid star
protected definition rec {P : interval → Type} (P0 : P zero) (P1 : P one)
(Ps : P0 =[seg] P1) (x : interval) : P x :=
begin
fapply susp.rec_on x,
{ exact P0},
{ exact P1},
{ intro x, cases x, exact Ps}
end
protected definition rec_on [reducible] {P : interval → Type} (x : interval)
(P0 : P zero) (P1 : P one) (Ps : P0 =[seg] P1) : P x :=
interval.rec P0 P1 Ps x
theorem rec_seg {P : interval → Type} (P0 : P zero) (P1 : P one) (Ps : P0 =[seg] P1)
: apd (interval.rec P0 P1 Ps) seg = Ps :=
!rec_merid
protected definition elim {P : Type} (P0 P1 : P) (Ps : P0 = P1) (x : interval) : P :=
interval.rec P0 P1 (pathover_of_eq _ Ps) x
protected definition elim_on [reducible] {P : Type} (x : interval) (P0 P1 : P)
(Ps : P0 = P1) : P :=
interval.elim P0 P1 Ps x
theorem elim_seg {P : Type} (P0 P1 : P) (Ps : P0 = P1)
: ap (interval.elim P0 P1 Ps) seg = Ps :=
begin
apply eq_of_fn_eq_fn_inv !(pathover_constant seg),
rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑interval.elim,rec_seg],
end
protected definition elim_type (P0 P1 : Type) (Ps : P0 ≃ P1) (x : interval) : Type :=
interval.elim P0 P1 (ua Ps) x
protected definition elim_type_on [reducible] (x : interval) (P0 P1 : Type) (Ps : P0 ≃ P1)
: Type :=
interval.elim_type P0 P1 Ps x
theorem elim_type_seg (P0 P1 : Type) (Ps : P0 ≃ P1)
: transport (interval.elim_type P0 P1 Ps) seg = Ps :=
by rewrite [tr_eq_cast_ap_fn,↑interval.elim_type,elim_seg];apply cast_ua_fn
definition is_contr_interval [instance] [priority 900] : is_contr interval :=
is_contr.mk zero (λx, interval.rec_on x idp seg !eq_pathover_r_idp)
definition naive_funext_of_interval : naive_funext :=
λA P f g p, ap (λ(i : interval) (x : A), interval.elim_on i (f x) (g x) (p x)) seg
definition funext_of_interval : funext :=
funext_from_naive_funext naive_funext_of_interval
end interval open interval
definition cube : ℕ → Type₀
| cube 0 := unit
| cube (succ n) := cube n × interval
abbreviation square := cube (succ (succ nat.zero))
definition cube_one_equiv_interval : cube 1 ≃ interval :=
!prod_comm_equiv ⬝e !prod_unit_equiv
definition prod_square {A B : Type} {a a' : A} {b b' : B} (p : a = a') (q : b = b')
: square (pair_eq p idp) (pair_eq p idp) (pair_eq idp q) (pair_eq idp q) :=
by cases p; cases q; exact ids
namespace square
definition tl : square := (star, zero, zero)
definition tr : square := (star, one, zero)
definition bl : square := (star, zero, one )
definition br : square := (star, one, one )
-- s stands for "square" in the following definitions
definition st : tl = tr := pair_eq (pair_eq idp seg) idp
definition sb : bl = br := pair_eq (pair_eq idp seg) idp
definition sl : tl = bl := pair_eq idp seg
definition sr : tr = br := pair_eq idp seg
definition sfill : square st sb sl sr := !prod_square
definition fill : st ⬝ sr = sl ⬝ sb := !square_equiv_eq sfill
end square
|
787e298eb9524b224e2f5437d0fb12962265ca3b
|
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
|
/tests/lean/run/calc.lean
|
c4fa26cedac8e1808e8e569b0eddabe984df9341
|
[
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"
] |
permissive
|
EdAyers/lean4
|
57ac632d6b0789cb91fab2170e8c9e40441221bd
|
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
|
refs/heads/master
| 1,676,463,245,298
| 1,660,619,433,000
| 1,660,619,433,000
| 183,433,437
| 1
| 0
|
Apache-2.0
| 1,657,612,672,000
| 1,556,196,574,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 496
|
lean
|
variable (t1 t2 t3 t4 : Nat)
variable (pf12 : t1 = t2) (pf23 : t2 = t3) (pf34 : t3 = t4)
theorem foo : t1 = t4 :=
calc
t1 = t2 := pf12
_ = t3 := pf23
_ = t4 := pf34
variable (t5 : Nat)
variable (pf23' : t2 < t3) (pf45' : t4 < t5)
instance [LT α] : Trans (α := α) (· < ·) (· < ·) (· < ·) where
trans := sorry
theorem foo' : t1 < t5 :=
let p := calc
t1 = t2 := pf12
_ < t3 := pf23'
_ = t4 := pf34
_ < t5 := pf45'
-- dedent terminates the block
p
|
a9b2eb90d4b093268a48e50a1028241cc4eda861
|
94e33a31faa76775069b071adea97e86e218a8ee
|
/src/algebra/gcd_monoid/basic.lean
|
28ce75282b94fea927c2705b8bcf2a96f564c5fd
|
[
"Apache-2.0"
] |
permissive
|
urkud/mathlib
|
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
|
6379d39e6b5b279df9715f8011369a301b634e41
|
refs/heads/master
| 1,658,425,342,662
| 1,658,078,703,000
| 1,658,078,703,000
| 186,910,338
| 0
| 0
|
Apache-2.0
| 1,568,512,083,000
| 1,557,958,709,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 48,956
|
lean
|
/-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jens Wagemaker
-/
import algebra.associated
import algebra.group_power.lemmas
/-!
# Monoids with normalization functions, `gcd`, and `lcm`
This file defines extra structures on `cancel_comm_monoid_with_zero`s, including `is_domain`s.
## Main Definitions
* `normalization_monoid`
* `gcd_monoid`
* `normalized_gcd_monoid`
* `gcd_monoid_of_gcd`, `gcd_monoid_of_exists_gcd`, `normalized_gcd_monoid_of_gcd`,
`normalized_gcd_monoid_of_exists_gcd`
* `gcd_monoid_of_lcm`, `gcd_monoid_of_exists_lcm`, `normalized_gcd_monoid_of_lcm`,
`normalized_gcd_monoid_of_exists_lcm`
For the `normalized_gcd_monoid` instances on `ℕ` and `ℤ`, see `ring_theory.int.basic`.
## Implementation Notes
* `normalization_monoid` is defined by assigning to each element a `norm_unit` such that multiplying
by that unit normalizes the monoid, and `normalize` is an idempotent monoid homomorphism. This
definition as currently implemented does casework on `0`.
* `gcd_monoid` contains the definitions of `gcd` and `lcm` with the usual properties. They are
both determined up to a unit.
* `normalized_gcd_monoid` extends `normalization_monoid`, so the `gcd` and `lcm` are always
normalized. This makes `gcd`s of polynomials easier to work with, but excludes Euclidean domains,
and monoids without zero.
* `gcd_monoid_of_gcd` and `normalized_gcd_monoid_of_gcd` noncomputably construct a `gcd_monoid`
(resp. `normalized_gcd_monoid`) structure just from the `gcd` and its properties.
* `gcd_monoid_of_exists_gcd` and `normalized_gcd_monoid_of_exists_gcd` noncomputably construct a
`gcd_monoid` (resp. `normalized_gcd_monoid`) structure just from a proof that any two elements
have a (not necessarily normalized) `gcd`.
* `gcd_monoid_of_lcm` and `normalized_gcd_monoid_of_lcm` noncomputably construct a `gcd_monoid`
(resp. `normalized_gcd_monoid`) structure just from the `lcm` and its properties.
* `gcd_monoid_of_exists_lcm` and `normalized_gcd_monoid_of_exists_lcm` noncomputably construct a
`gcd_monoid` (resp. `normalized_gcd_monoid`) structure just from a proof that any two elements
have a (not necessarily normalized) `lcm`.
## TODO
* Port GCD facts about nats, definition of coprime
* Generalize normalization monoids to commutative (cancellative) monoids with or without zero
## Tags
divisibility, gcd, lcm, normalize
-/
variables {α : Type*}
/-- Normalization monoid: multiplying with `norm_unit` gives a normal form for associated
elements. -/
@[protect_proj] class normalization_monoid (α : Type*)
[cancel_comm_monoid_with_zero α] :=
(norm_unit : α → αˣ)
(norm_unit_zero : norm_unit 0 = 1)
(norm_unit_mul : ∀{a b}, a ≠ 0 → b ≠ 0 → norm_unit (a * b) = norm_unit a * norm_unit b)
(norm_unit_coe_units : ∀(u : αˣ), norm_unit u = u⁻¹)
export normalization_monoid (norm_unit norm_unit_zero norm_unit_mul norm_unit_coe_units)
attribute [simp] norm_unit_coe_units norm_unit_zero norm_unit_mul
section normalization_monoid
variables [cancel_comm_monoid_with_zero α] [normalization_monoid α]
@[simp] theorem norm_unit_one : norm_unit (1:α) = 1 :=
norm_unit_coe_units 1
/-- Chooses an element of each associate class, by multiplying by `norm_unit` -/
def normalize : α →*₀ α :=
{ to_fun := λ x, x * norm_unit x,
map_zero' := by simp,
map_one' := by rw [norm_unit_one, units.coe_one, mul_one],
map_mul' := λ x y,
classical.by_cases (λ hx : x = 0, by rw [hx, zero_mul, zero_mul, zero_mul]) $ λ hx,
classical.by_cases (λ hy : y = 0, by rw [hy, mul_zero, zero_mul, mul_zero]) $ λ hy,
by simp only [norm_unit_mul hx hy, units.coe_mul]; simp only [mul_assoc, mul_left_comm y], }
theorem associated_normalize (x : α) : associated x (normalize x) :=
⟨_, rfl⟩
theorem normalize_associated (x : α) : associated (normalize x) x :=
(associated_normalize _).symm
lemma associates.mk_normalize (x : α) : associates.mk (normalize x) = associates.mk x :=
associates.mk_eq_mk_iff_associated.2 (normalize_associated _)
@[simp] lemma normalize_apply (x : α) : normalize x = x * norm_unit x := rfl
@[simp] lemma normalize_zero : normalize (0 : α) = 0 := normalize.map_zero
@[simp] lemma normalize_one : normalize (1 : α) = 1 := normalize.map_one
lemma normalize_coe_units (u : αˣ) : normalize (u : α) = 1 := by simp
lemma normalize_eq_zero {x : α} : normalize x = 0 ↔ x = 0 :=
⟨λ hx, (associated_zero_iff_eq_zero x).1 $ hx ▸ associated_normalize _,
by rintro rfl; exact normalize_zero⟩
lemma normalize_eq_one {x : α} : normalize x = 1 ↔ is_unit x :=
⟨λ hx, is_unit_iff_exists_inv.2 ⟨_, hx⟩, λ ⟨u, hu⟩, hu ▸ normalize_coe_units u⟩
@[simp] theorem norm_unit_mul_norm_unit (a : α) : norm_unit (a * norm_unit a) = 1 :=
begin
nontriviality α using [subsingleton.elim a 0],
obtain rfl|h := eq_or_ne a 0,
{ rw [norm_unit_zero, zero_mul, norm_unit_zero] },
{ rw [norm_unit_mul h (units.ne_zero _), norm_unit_coe_units, mul_inv_eq_one] }
end
theorem normalize_idem (x : α) : normalize (normalize x) = normalize x := by simp
theorem normalize_eq_normalize {a b : α}
(hab : a ∣ b) (hba : b ∣ a) : normalize a = normalize b :=
begin
nontriviality α,
rcases associated_of_dvd_dvd hab hba with ⟨u, rfl⟩,
refine classical.by_cases (by rintro rfl; simp only [zero_mul]) (assume ha : a ≠ 0, _),
suffices : a * ↑(norm_unit a) = a * ↑u * ↑(norm_unit a) * ↑u⁻¹,
by simpa only [normalize_apply, mul_assoc, norm_unit_mul ha u.ne_zero, norm_unit_coe_units],
calc a * ↑(norm_unit a) = a * ↑(norm_unit a) * ↑u * ↑u⁻¹:
(units.mul_inv_cancel_right _ _).symm
... = a * ↑u * ↑(norm_unit a) * ↑u⁻¹ : by rw mul_right_comm a
end
lemma normalize_eq_normalize_iff {x y : α} : normalize x = normalize y ↔ x ∣ y ∧ y ∣ x :=
⟨λ h, ⟨units.dvd_mul_right.1 ⟨_, h.symm⟩, units.dvd_mul_right.1 ⟨_, h⟩⟩,
λ ⟨hxy, hyx⟩, normalize_eq_normalize hxy hyx⟩
theorem dvd_antisymm_of_normalize_eq {a b : α}
(ha : normalize a = a) (hb : normalize b = b) (hab : a ∣ b) (hba : b ∣ a) :
a = b :=
ha ▸ hb ▸ normalize_eq_normalize hab hba
--can be proven by simp
lemma dvd_normalize_iff {a b : α} : a ∣ normalize b ↔ a ∣ b :=
units.dvd_mul_right
--can be proven by simp
lemma normalize_dvd_iff {a b : α} : normalize a ∣ b ↔ a ∣ b :=
units.mul_right_dvd
end normalization_monoid
namespace associates
variables [cancel_comm_monoid_with_zero α] [normalization_monoid α]
local attribute [instance] associated.setoid
/-- Maps an element of `associates` back to the normalized element of its associate class -/
protected def out : associates α → α :=
quotient.lift (normalize : α → α) $ λ a b ⟨u, hu⟩, hu ▸
normalize_eq_normalize ⟨_, rfl⟩ (units.mul_right_dvd.2 $ dvd_refl a)
@[simp] lemma out_mk (a : α) : (associates.mk a).out = normalize a := rfl
@[simp] lemma out_one : (1 : associates α).out = 1 :=
normalize_one
lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out :=
quotient.induction_on₂ a b $ assume a b,
by simp only [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk, normalize.map_mul]
lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b :=
quotient.induction_on b $
by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff]
lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a :=
quotient.induction_on b $
by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff]
@[simp] lemma out_top : (⊤ : associates α).out = 0 :=
normalize_zero
@[simp] lemma normalize_out (a : associates α) : normalize a.out = a.out :=
quotient.induction_on a normalize_idem
@[simp] lemma mk_out (a : associates α) : associates.mk (a.out) = a :=
quotient.induction_on a mk_normalize
lemma out_injective : function.injective (associates.out : _ → α) :=
function.left_inverse.injective mk_out
end associates
/-- GCD monoid: a `cancel_comm_monoid_with_zero` with `gcd` (greatest common divisor) and
`lcm` (least common multiple) operations, determined up to a unit. The type class focuses on `gcd`
and we derive the corresponding `lcm` facts from `gcd`.
-/
@[protect_proj] class gcd_monoid (α : Type*) [cancel_comm_monoid_with_zero α] :=
(gcd : α → α → α)
(lcm : α → α → α)
(gcd_dvd_left : ∀a b, gcd a b ∣ a)
(gcd_dvd_right : ∀a b, gcd a b ∣ b)
(dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b)
(gcd_mul_lcm : ∀a b, associated (gcd a b * lcm a b) (a * b))
(lcm_zero_left : ∀a, lcm 0 a = 0)
(lcm_zero_right : ∀a, lcm a 0 = 0)
/-- Normalized GCD monoid: a `cancel_comm_monoid_with_zero` with normalization and `gcd`
(greatest common divisor) and `lcm` (least common multiple) operations. In this setting `gcd` and
`lcm` form a bounded lattice on the associated elements where `gcd` is the infimum, `lcm` is the
supremum, `1` is bottom, and `0` is top. The type class focuses on `gcd` and we derive the
corresponding `lcm` facts from `gcd`.
-/
class normalized_gcd_monoid (α : Type*) [cancel_comm_monoid_with_zero α]
extends normalization_monoid α, gcd_monoid α :=
(normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b)
(normalize_lcm : ∀a b, normalize (lcm a b) = lcm a b)
export gcd_monoid (gcd lcm gcd_dvd_left gcd_dvd_right dvd_gcd lcm_zero_left lcm_zero_right)
attribute [simp] lcm_zero_left lcm_zero_right
section gcd_monoid
variables [cancel_comm_monoid_with_zero α]
@[simp] theorem normalize_gcd [normalized_gcd_monoid α] : ∀a b:α, normalize (gcd a b) = gcd a b :=
normalized_gcd_monoid.normalize_gcd
theorem gcd_mul_lcm [gcd_monoid α] : ∀a b:α, associated (gcd a b * lcm a b) (a * b) :=
gcd_monoid.gcd_mul_lcm
section gcd
theorem dvd_gcd_iff [gcd_monoid α] (a b c : α) : a ∣ gcd b c ↔ (a ∣ b ∧ a ∣ c) :=
iff.intro
(assume h, ⟨h.trans (gcd_dvd_left _ _), h.trans (gcd_dvd_right _ _)⟩)
(assume ⟨hab, hac⟩, dvd_gcd hab hac)
theorem gcd_comm [normalized_gcd_monoid α] (a b : α) : gcd a b = gcd b a :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _)
(dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _))
(dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _))
theorem gcd_comm' [gcd_monoid α] (a b : α) : associated (gcd a b) (gcd b a) :=
associated_of_dvd_dvd
(dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _))
(dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _))
theorem gcd_assoc [normalized_gcd_monoid α] (m n k : α) : gcd (gcd m n) k = gcd m (gcd n k) :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _)
(dvd_gcd
((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_left m n))
(dvd_gcd ((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_right m n))
(gcd_dvd_right (gcd m n) k)))
(dvd_gcd
(dvd_gcd (gcd_dvd_left m (gcd n k)) ((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_left n k)))
((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_right n k)))
theorem gcd_assoc' [gcd_monoid α] (m n k : α) : associated (gcd (gcd m n) k) (gcd m (gcd n k)) :=
associated_of_dvd_dvd
(dvd_gcd
((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_left m n))
(dvd_gcd ((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_right m n))
(gcd_dvd_right (gcd m n) k)))
(dvd_gcd
(dvd_gcd (gcd_dvd_left m (gcd n k)) ((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_left n k)))
((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_right n k)))
instance [normalized_gcd_monoid α] : is_commutative α gcd := ⟨gcd_comm⟩
instance [normalized_gcd_monoid α] : is_associative α gcd := ⟨gcd_assoc⟩
theorem gcd_eq_normalize [normalized_gcd_monoid α] {a b c : α}
(habc : gcd a b ∣ c) (hcab : c ∣ gcd a b) :
gcd a b = normalize c :=
normalize_gcd a b ▸ normalize_eq_normalize habc hcab
@[simp] theorem gcd_zero_left [normalized_gcd_monoid α] (a : α) : gcd 0 a = normalize a :=
gcd_eq_normalize (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a))
theorem gcd_zero_left' [gcd_monoid α] (a : α) : associated (gcd 0 a) a :=
associated_of_dvd_dvd (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a))
@[simp] theorem gcd_zero_right [normalized_gcd_monoid α] (a : α) : gcd a 0 = normalize a :=
gcd_eq_normalize (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero _))
theorem gcd_zero_right' [gcd_monoid α] (a : α) : associated (gcd a 0) a :=
associated_of_dvd_dvd (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero _))
@[simp] theorem gcd_eq_zero_iff [gcd_monoid α] (a b : α) : gcd a b = 0 ↔ a = 0 ∧ b = 0 :=
iff.intro
(assume h, let ⟨ca, ha⟩ := gcd_dvd_left a b, ⟨cb, hb⟩ := gcd_dvd_right a b in
by rw [h, zero_mul] at ha hb; exact ⟨ha, hb⟩)
(assume ⟨ha, hb⟩, by
{ rw [ha, hb, ←zero_dvd_iff],
apply dvd_gcd; refl })
@[simp] theorem gcd_one_left [normalized_gcd_monoid α] (a : α) : gcd 1 a = 1 :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_left _ _) (one_dvd _)
@[simp] theorem gcd_one_left' [gcd_monoid α] (a : α) : associated (gcd 1 a) 1 :=
associated_of_dvd_dvd (gcd_dvd_left _ _) (one_dvd _)
@[simp] theorem gcd_one_right [normalized_gcd_monoid α] (a : α) : gcd a 1 = 1 :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_right _ _) (one_dvd _)
@[simp] theorem gcd_one_right' [gcd_monoid α] (a : α) : associated (gcd a 1) 1 :=
associated_of_dvd_dvd (gcd_dvd_right _ _) (one_dvd _)
theorem gcd_dvd_gcd [gcd_monoid α] {a b c d: α} (hab : a ∣ b) (hcd : c ∣ d) : gcd a c ∣ gcd b d :=
dvd_gcd ((gcd_dvd_left _ _).trans hab) ((gcd_dvd_right _ _).trans hcd)
@[simp] theorem gcd_same [normalized_gcd_monoid α] (a : α) : gcd a a = normalize a :=
gcd_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_refl a))
@[simp] theorem gcd_mul_left [normalized_gcd_monoid α] (a b c : α) :
gcd (a * b) (a * c) = normalize a * gcd b c :=
classical.by_cases (by rintro rfl; simp only [zero_mul, gcd_zero_left, normalize_zero]) $
assume ha : a ≠ 0,
suffices gcd (a * b) (a * c) = normalize (a * gcd b c),
by simpa only [normalize.map_mul, normalize_gcd],
let ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c) in
gcd_eq_normalize
(eq.symm ▸ mul_dvd_mul_left a $ show d ∣ gcd b c, from
dvd_gcd
((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_left _ _)
((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_right _ _))
(dvd_gcd
(mul_dvd_mul_left a $ gcd_dvd_left _ _)
(mul_dvd_mul_left a $ gcd_dvd_right _ _))
theorem gcd_mul_left' [gcd_monoid α] (a b c : α) : associated (gcd (a * b) (a * c)) (a * gcd b c) :=
begin
obtain rfl|ha := eq_or_ne a 0,
{ simp only [zero_mul, gcd_zero_left'] },
obtain ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c),
apply associated_of_dvd_dvd,
{ rw eq,
apply mul_dvd_mul_left,
exact dvd_gcd
((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_left _ _)
((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_right _ _) },
{ exact (dvd_gcd
(mul_dvd_mul_left a $ gcd_dvd_left _ _)
(mul_dvd_mul_left a $ gcd_dvd_right _ _)) },
end
@[simp] theorem gcd_mul_right [normalized_gcd_monoid α] (a b c : α) :
gcd (b * a) (c * a) = gcd b c * normalize a :=
by simp only [mul_comm, gcd_mul_left]
@[simp] theorem gcd_mul_right' [gcd_monoid α] (a b c : α) :
associated (gcd (b * a) (c * a)) (gcd b c * a) :=
by simp only [mul_comm, gcd_mul_left']
theorem gcd_eq_left_iff [normalized_gcd_monoid α] (a b : α) (h : normalize a = a) :
gcd a b = a ↔ a ∣ b :=
iff.intro (assume eq, eq ▸ gcd_dvd_right _ _) $
assume hab, dvd_antisymm_of_normalize_eq (normalize_gcd _ _) h (gcd_dvd_left _ _)
(dvd_gcd (dvd_refl a) hab)
theorem gcd_eq_right_iff [normalized_gcd_monoid α] (a b : α) (h : normalize b = b) :
gcd a b = b ↔ b ∣ a :=
by simpa only [gcd_comm a b] using gcd_eq_left_iff b a h
theorem gcd_dvd_gcd_mul_left [gcd_monoid α] (m n k : α) : gcd m n ∣ gcd (k * m) n :=
gcd_dvd_gcd (dvd_mul_left _ _) dvd_rfl
theorem gcd_dvd_gcd_mul_right [gcd_monoid α] (m n k : α) : gcd m n ∣ gcd (m * k) n :=
gcd_dvd_gcd (dvd_mul_right _ _) dvd_rfl
theorem gcd_dvd_gcd_mul_left_right [gcd_monoid α] (m n k : α) : gcd m n ∣ gcd m (k * n) :=
gcd_dvd_gcd dvd_rfl (dvd_mul_left _ _)
theorem gcd_dvd_gcd_mul_right_right [gcd_monoid α] (m n k : α) : gcd m n ∣ gcd m (n * k) :=
gcd_dvd_gcd dvd_rfl (dvd_mul_right _ _)
theorem associated.gcd_eq_left [normalized_gcd_monoid α] {m n : α} (h : associated m n) (k : α) :
gcd m k = gcd n k :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _)
(gcd_dvd_gcd h.dvd dvd_rfl)
(gcd_dvd_gcd h.symm.dvd dvd_rfl)
theorem associated.gcd_eq_right [normalized_gcd_monoid α] {m n : α} (h : associated m n) (k : α) :
gcd k m = gcd k n :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _)
(gcd_dvd_gcd dvd_rfl h.dvd)
(gcd_dvd_gcd dvd_rfl h.symm.dvd)
lemma dvd_gcd_mul_of_dvd_mul [gcd_monoid α] {m n k : α} (H : k ∣ m * n) : k ∣ (gcd k m) * n :=
(dvd_gcd (dvd_mul_right _ n) H).trans (gcd_mul_right' n k m).dvd
lemma dvd_mul_gcd_of_dvd_mul [gcd_monoid α] {m n k : α} (H : k ∣ m * n) : k ∣ m * gcd k n :=
by { rw mul_comm at H ⊢, exact dvd_gcd_mul_of_dvd_mul H }
/-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`.
Note: In general, this representation is highly non-unique. -/
lemma exists_dvd_and_dvd_of_dvd_mul [gcd_monoid α] {m n k : α} (H : k ∣ m * n) :
∃ d₁ (hd₁ : d₁ ∣ m) d₂ (hd₂ : d₂ ∣ n), k = d₁ * d₂ :=
begin
by_cases h0 : gcd k m = 0,
{ rw gcd_eq_zero_iff at h0,
rcases h0 with ⟨rfl, rfl⟩,
refine ⟨0, dvd_refl 0, n, dvd_refl n, _⟩,
simp },
{ obtain ⟨a, ha⟩ := gcd_dvd_left k m,
refine ⟨gcd k m, gcd_dvd_right _ _, a, _, ha⟩,
suffices h : gcd k m * a ∣ gcd k m * n,
{ cases h with b hb,
use b,
rw mul_assoc at hb,
apply mul_left_cancel₀ h0 hb },
rw ← ha,
exact dvd_gcd_mul_of_dvd_mul H }
end
theorem gcd_mul_dvd_mul_gcd [gcd_monoid α] (k m n : α) : gcd k (m * n) ∣ gcd k m * gcd k n :=
begin
obtain ⟨m', hm', n', hn', h⟩ := (exists_dvd_and_dvd_of_dvd_mul $ gcd_dvd_right k (m * n)),
replace h : gcd k (m * n) = m' * n' := h,
rw h,
have hm'n' : m' * n' ∣ k := h ▸ gcd_dvd_left _ _,
apply mul_dvd_mul,
{ have hm'k : m' ∣ k := (dvd_mul_right m' n').trans hm'n',
exact dvd_gcd hm'k hm' },
{ have hn'k : n' ∣ k := (dvd_mul_left n' m').trans hm'n',
exact dvd_gcd hn'k hn' }
end
theorem gcd_pow_right_dvd_pow_gcd [gcd_monoid α] {a b : α} {k : ℕ} :
gcd a (b ^ k) ∣ (gcd a b) ^ k :=
begin
by_cases hg : gcd a b = 0,
{ rw gcd_eq_zero_iff at hg,
rcases hg with ⟨rfl, rfl⟩,
exact (gcd_zero_left' (0 ^ k : α)).dvd.trans
(pow_dvd_pow_of_dvd (gcd_zero_left' (0 : α)).symm.dvd _) },
{ induction k with k hk,
{ simp only [pow_zero],
exact (gcd_one_right' a).dvd, },
rw [pow_succ, pow_succ],
transitivity gcd a b * gcd a (b ^ k),
apply gcd_mul_dvd_mul_gcd a b (b ^ k),
exact (mul_dvd_mul_iff_left hg).mpr hk }
end
theorem gcd_pow_left_dvd_pow_gcd [gcd_monoid α] {a b : α} {k : ℕ} :
gcd (a ^ k) b ∣ (gcd a b) ^ k :=
calc gcd (a ^ k) b
∣ gcd b (a ^ k) : (gcd_comm' _ _).dvd
... ∣ (gcd b a) ^ k : gcd_pow_right_dvd_pow_gcd
... ∣ (gcd a b) ^ k : pow_dvd_pow_of_dvd (gcd_comm' _ _).dvd _
theorem pow_dvd_of_mul_eq_pow [gcd_monoid α] {a b c d₁ d₂ : α} (ha : a ≠ 0)
(hab : is_unit (gcd a b)) {k : ℕ} (h : a * b = c ^ k) (hc : c = d₁ * d₂)
(hd₁ : d₁ ∣ a) : d₁ ^ k ≠ 0 ∧ d₁ ^ k ∣ a :=
begin
have h1 : is_unit (gcd (d₁ ^ k) b),
{ apply is_unit_of_dvd_one,
transitivity (gcd d₁ b) ^ k,
{ exact gcd_pow_left_dvd_pow_gcd },
{ apply is_unit.dvd, apply is_unit.pow, apply is_unit_of_dvd_one,
apply dvd_trans _ hab.dvd,
apply gcd_dvd_gcd hd₁ (dvd_refl b) } },
have h2 : d₁ ^ k ∣ a * b, { use d₂ ^ k, rw [h, hc], exact mul_pow d₁ d₂ k },
rw mul_comm at h2,
have h3 : d₁ ^ k ∣ a,
{ apply (dvd_gcd_mul_of_dvd_mul h2).trans,
rw is_unit.mul_left_dvd _ _ _ h1 },
have h4 : d₁ ^ k ≠ 0,
{ intro hdk, rw hdk at h3, apply absurd (zero_dvd_iff.mp h3) ha },
exact ⟨h4, h3⟩,
end
theorem exists_associated_pow_of_mul_eq_pow [gcd_monoid α] {a b c : α}
(hab : is_unit (gcd a b)) {k : ℕ}
(h : a * b = c ^ k) : ∃ (d : α), associated (d ^ k) a :=
begin
casesI subsingleton_or_nontrivial α,
{ use 0, rw [subsingleton.elim a (0 ^ k)] },
by_cases ha : a = 0,
{ use 0, rw ha,
obtain (rfl | hk) := k.eq_zero_or_pos,
{ exfalso, revert h, rw [ha, zero_mul, pow_zero], apply zero_ne_one },
{ rw zero_pow hk } },
by_cases hb : b = 0,
{ use 1, rw [one_pow],
apply (associated_one_iff_is_unit.mpr hab).symm.trans,
rw hb,
exact gcd_zero_right' a },
obtain (rfl | hk) := k.eq_zero_or_pos,
{ use 1, rw pow_zero at h ⊢, use units.mk_of_mul_eq_one _ _ h,
rw [units.coe_mk_of_mul_eq_one, one_mul] },
have hc : c ∣ a * b, { rw h, exact dvd_pow_self _ hk.ne' },
obtain ⟨d₁, hd₁, d₂, hd₂, hc⟩ := exists_dvd_and_dvd_of_dvd_mul hc,
use d₁,
obtain ⟨h0₁, ⟨a', ha'⟩⟩ := pow_dvd_of_mul_eq_pow ha hab h hc hd₁,
rw [mul_comm] at h hc,
rw (gcd_comm' a b).is_unit_iff at hab,
obtain ⟨h0₂, ⟨b', hb'⟩⟩ := pow_dvd_of_mul_eq_pow hb hab h hc hd₂,
rw [ha', hb', hc, mul_pow] at h,
have h' : a' * b' = 1,
{ apply (mul_right_inj' h0₁).mp, rw mul_one,
apply (mul_right_inj' h0₂).mp, rw ← h,
rw [mul_assoc, mul_comm a', ← mul_assoc _ b', ← mul_assoc b', mul_comm b'] },
use units.mk_of_mul_eq_one _ _ h',
rw [units.coe_mk_of_mul_eq_one, ha']
end
theorem exists_eq_pow_of_mul_eq_pow [gcd_monoid α] [unique αˣ] {a b c : α}
(hab : is_unit (gcd a b)) {k : ℕ}
(h : a * b = c ^ k) : ∃ (d : α), a = d ^ k :=
let ⟨d, hd⟩ := exists_associated_pow_of_mul_eq_pow hab h in ⟨d, (associated_iff_eq.mp hd).symm⟩
lemma gcd_greatest {α : Type*} [cancel_comm_monoid_with_zero α] [normalized_gcd_monoid α]
{a b d : α} (hda : d ∣ a) (hdb : d ∣ b)
(hd : ∀ e : α, e ∣ a → e ∣ b → e ∣ d) : gcd_monoid.gcd a b = normalize d :=
begin
have h := hd _ (gcd_monoid.gcd_dvd_left a b) (gcd_monoid.gcd_dvd_right a b),
exact gcd_eq_normalize h (gcd_monoid.dvd_gcd hda hdb),
end
lemma gcd_greatest_associated {α : Type*} [cancel_comm_monoid_with_zero α] [gcd_monoid α]
{a b d : α} (hda : d ∣ a) (hdb : d ∣ b)
(hd : ∀ e : α, e ∣ a → e ∣ b → e ∣ d) : associated d (gcd_monoid.gcd a b) :=
begin
have h := hd _ (gcd_monoid.gcd_dvd_left a b) (gcd_monoid.gcd_dvd_right a b),
exact associated_of_dvd_dvd (gcd_monoid.dvd_gcd hda hdb) h,
end
lemma is_unit_gcd_of_eq_mul_gcd {α : Type*} [cancel_comm_monoid_with_zero α] [gcd_monoid α]
{x y x' y' : α} (ex : x = gcd x y * x') (ey : y = gcd x y * y') (h : gcd x y ≠ 0) :
is_unit (gcd x' y') :=
begin
rw ← associated_one_iff_is_unit,
refine associated.of_mul_left _ (associated.refl $ gcd x y) h,
convert (gcd_mul_left' _ _ _).symm using 1,
rw [← ex, ← ey, mul_one],
end
lemma extract_gcd {α : Type*} [cancel_comm_monoid_with_zero α] [gcd_monoid α] (x y : α) :
∃ x' y' d : α, x = d * x' ∧ y = d * y' ∧ is_unit (gcd x' y') :=
begin
cases eq_or_ne (gcd x y) 0 with h h,
{ obtain ⟨rfl, rfl⟩ := (gcd_eq_zero_iff x y).1 h,
simp_rw ← associated_one_iff_is_unit,
exact ⟨1, 1, 0, (zero_mul 1).symm, (zero_mul 1).symm, gcd_one_left' 1⟩ },
obtain ⟨x', ex⟩ := gcd_dvd_left x y,
obtain ⟨y', ey⟩ := gcd_dvd_right x y,
exact ⟨x', y', gcd x y, ex, ey, is_unit_gcd_of_eq_mul_gcd ex ey h⟩,
end
end gcd
section lcm
lemma lcm_dvd_iff [gcd_monoid α] {a b c : α} : lcm a b ∣ c ↔ a ∣ c ∧ b ∣ c :=
begin
by_cases this : a = 0 ∨ b = 0,
{ rcases this with rfl | rfl;
simp only [iff_def, lcm_zero_left, lcm_zero_right, zero_dvd_iff, dvd_zero,
eq_self_iff_true, and_true, imp_true_iff] {contextual:=tt} },
{ obtain ⟨h1, h2⟩ := not_or_distrib.1 this,
have h : gcd a b ≠ 0, from λ H, h1 ((gcd_eq_zero_iff _ _).1 H).1,
rw [← mul_dvd_mul_iff_left h, (gcd_mul_lcm a b).dvd_iff_dvd_left,
←(gcd_mul_right' c a b).dvd_iff_dvd_right, dvd_gcd_iff, mul_comm b c,
mul_dvd_mul_iff_left h1, mul_dvd_mul_iff_right h2, and_comm] }
end
lemma dvd_lcm_left [gcd_monoid α] (a b : α) : a ∣ lcm a b :=
(lcm_dvd_iff.1 (dvd_refl (lcm a b))).1
lemma dvd_lcm_right [gcd_monoid α] (a b : α) : b ∣ lcm a b :=
(lcm_dvd_iff.1 (dvd_refl (lcm a b))).2
lemma lcm_dvd [gcd_monoid α] {a b c : α} (hab : a ∣ b) (hcb : c ∣ b) : lcm a c ∣ b :=
lcm_dvd_iff.2 ⟨hab, hcb⟩
@[simp] theorem lcm_eq_zero_iff [gcd_monoid α] (a b : α) : lcm a b = 0 ↔ a = 0 ∨ b = 0 :=
iff.intro
(assume h : lcm a b = 0,
have associated (a * b) 0 := (gcd_mul_lcm a b).symm.trans $
by rw [h, mul_zero],
by simpa only [associated_zero_iff_eq_zero, mul_eq_zero])
(by rintro (rfl | rfl); [apply lcm_zero_left, apply lcm_zero_right])
@[simp] lemma normalize_lcm [normalized_gcd_monoid α] (a b : α) : normalize (lcm a b) = lcm a b :=
normalized_gcd_monoid.normalize_lcm a b
theorem lcm_comm [normalized_gcd_monoid α] (a b : α) : lcm a b = lcm b a :=
dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _)
(lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _))
(lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _))
theorem lcm_comm' [gcd_monoid α] (a b : α) : associated (lcm a b) (lcm b a) :=
associated_of_dvd_dvd
(lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _))
(lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _))
theorem lcm_assoc [normalized_gcd_monoid α] (m n k : α) : lcm (lcm m n) k = lcm m (lcm n k) :=
dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _)
(lcm_dvd
(lcm_dvd (dvd_lcm_left _ _) ((dvd_lcm_left _ _).trans (dvd_lcm_right _ _)))
((dvd_lcm_right _ _).trans (dvd_lcm_right _ _)))
(lcm_dvd
((dvd_lcm_left _ _).trans (dvd_lcm_left _ _))
(lcm_dvd ((dvd_lcm_right _ _).trans (dvd_lcm_left _ _)) (dvd_lcm_right _ _)))
theorem lcm_assoc' [gcd_monoid α] (m n k : α) : associated (lcm (lcm m n) k) (lcm m (lcm n k)) :=
associated_of_dvd_dvd
(lcm_dvd
(lcm_dvd (dvd_lcm_left _ _) ((dvd_lcm_left _ _).trans (dvd_lcm_right _ _)))
((dvd_lcm_right _ _).trans (dvd_lcm_right _ _)))
(lcm_dvd
((dvd_lcm_left _ _).trans (dvd_lcm_left _ _))
(lcm_dvd ((dvd_lcm_right _ _).trans (dvd_lcm_left _ _)) (dvd_lcm_right _ _)))
instance [normalized_gcd_monoid α] : is_commutative α lcm := ⟨lcm_comm⟩
instance [normalized_gcd_monoid α] : is_associative α lcm := ⟨lcm_assoc⟩
lemma lcm_eq_normalize [normalized_gcd_monoid α] {a b c : α}
(habc : lcm a b ∣ c) (hcab : c ∣ lcm a b) :
lcm a b = normalize c :=
normalize_lcm a b ▸ normalize_eq_normalize habc hcab
theorem lcm_dvd_lcm [gcd_monoid α] {a b c d : α} (hab : a ∣ b) (hcd : c ∣ d) :
lcm a c ∣ lcm b d :=
lcm_dvd (hab.trans (dvd_lcm_left _ _)) (hcd.trans (dvd_lcm_right _ _))
@[simp] theorem lcm_units_coe_left [normalized_gcd_monoid α] (u : αˣ) (a : α) :
lcm ↑u a = normalize a :=
lcm_eq_normalize (lcm_dvd units.coe_dvd dvd_rfl) (dvd_lcm_right _ _)
@[simp] theorem lcm_units_coe_right [normalized_gcd_monoid α] (a : α) (u : αˣ) :
lcm a ↑u = normalize a :=
(lcm_comm a u).trans $ lcm_units_coe_left _ _
@[simp] theorem lcm_one_left [normalized_gcd_monoid α] (a : α) : lcm 1 a = normalize a :=
lcm_units_coe_left 1 a
@[simp] theorem lcm_one_right [normalized_gcd_monoid α] (a : α) : lcm a 1 = normalize a :=
lcm_units_coe_right a 1
@[simp] theorem lcm_same [normalized_gcd_monoid α] (a : α) : lcm a a = normalize a :=
lcm_eq_normalize (lcm_dvd dvd_rfl dvd_rfl) (dvd_lcm_left _ _)
@[simp] theorem lcm_eq_one_iff [normalized_gcd_monoid α] (a b : α) : lcm a b = 1 ↔ a ∣ 1 ∧ b ∣ 1 :=
iff.intro
(assume eq, eq ▸ ⟨dvd_lcm_left _ _, dvd_lcm_right _ _⟩)
(assume ⟨⟨c, hc⟩, ⟨d, hd⟩⟩,
show lcm (units.mk_of_mul_eq_one a c hc.symm : α) (units.mk_of_mul_eq_one b d hd.symm) = 1,
by rw [lcm_units_coe_left, normalize_coe_units])
@[simp] theorem lcm_mul_left [normalized_gcd_monoid α] (a b c : α) :
lcm (a * b) (a * c) = normalize a * lcm b c :=
classical.by_cases (by rintro rfl; simp only [zero_mul, lcm_zero_left, normalize_zero]) $
assume ha : a ≠ 0,
suffices lcm (a * b) (a * c) = normalize (a * lcm b c),
by simpa only [normalize.map_mul, normalize_lcm],
have a ∣ lcm (a * b) (a * c), from (dvd_mul_right _ _).trans (dvd_lcm_left _ _),
let ⟨d, eq⟩ := this in
lcm_eq_normalize
(lcm_dvd (mul_dvd_mul_left a (dvd_lcm_left _ _)) (mul_dvd_mul_left a (dvd_lcm_right _ _)))
(eq.symm ▸ (mul_dvd_mul_left a $ lcm_dvd
((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_left _ _)
((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_right _ _)))
@[simp] theorem lcm_mul_right [normalized_gcd_monoid α] (a b c : α) :
lcm (b * a) (c * a) = lcm b c * normalize a :=
by simp only [mul_comm, lcm_mul_left]
theorem lcm_eq_left_iff [normalized_gcd_monoid α] (a b : α) (h : normalize a = a) :
lcm a b = a ↔ b ∣ a :=
iff.intro (assume eq, eq ▸ dvd_lcm_right _ _) $
assume hab, dvd_antisymm_of_normalize_eq (normalize_lcm _ _) h (lcm_dvd (dvd_refl a) hab)
(dvd_lcm_left _ _)
theorem lcm_eq_right_iff [normalized_gcd_monoid α] (a b : α) (h : normalize b = b) :
lcm a b = b ↔ a ∣ b :=
by simpa only [lcm_comm b a] using lcm_eq_left_iff b a h
theorem lcm_dvd_lcm_mul_left [gcd_monoid α] (m n k : α) : lcm m n ∣ lcm (k * m) n :=
lcm_dvd_lcm (dvd_mul_left _ _) dvd_rfl
theorem lcm_dvd_lcm_mul_right [gcd_monoid α] (m n k : α) : lcm m n ∣ lcm (m * k) n :=
lcm_dvd_lcm (dvd_mul_right _ _) dvd_rfl
theorem lcm_dvd_lcm_mul_left_right [gcd_monoid α] (m n k : α) : lcm m n ∣ lcm m (k * n) :=
lcm_dvd_lcm dvd_rfl (dvd_mul_left _ _)
theorem lcm_dvd_lcm_mul_right_right [gcd_monoid α] (m n k : α) : lcm m n ∣ lcm m (n * k) :=
lcm_dvd_lcm dvd_rfl (dvd_mul_right _ _)
theorem lcm_eq_of_associated_left [normalized_gcd_monoid α] {m n : α}
(h : associated m n) (k : α) : lcm m k = lcm n k :=
dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _)
(lcm_dvd_lcm h.dvd dvd_rfl)
(lcm_dvd_lcm h.symm.dvd dvd_rfl)
theorem lcm_eq_of_associated_right [normalized_gcd_monoid α] {m n : α}
(h : associated m n) (k : α) : lcm k m = lcm k n :=
dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _)
(lcm_dvd_lcm dvd_rfl h.dvd)
(lcm_dvd_lcm dvd_rfl h.symm.dvd)
end lcm
namespace gcd_monoid
theorem prime_of_irreducible [gcd_monoid α] {x : α} (hi: irreducible x) : prime x :=
⟨hi.ne_zero, ⟨hi.1, λ a b h,
begin
cases gcd_dvd_left x a with y hy,
cases hi.is_unit_or_is_unit hy with hu hu,
{ right, transitivity (gcd (x * b) (a * b)), apply dvd_gcd (dvd_mul_right x b) h,
rw (gcd_mul_right' b x a).dvd_iff_dvd_left,
exact (associated_unit_mul_left _ _ hu).dvd },
{ left,
rw hy,
exact dvd_trans (associated_mul_unit_left _ _ hu).dvd (gcd_dvd_right x a) }
end ⟩⟩
theorem irreducible_iff_prime [gcd_monoid α] {p : α} : irreducible p ↔ prime p :=
⟨prime_of_irreducible, prime.irreducible⟩
end gcd_monoid
end gcd_monoid
section unique_unit
variables [cancel_comm_monoid_with_zero α] [unique αˣ]
@[priority 100] -- see Note [lower instance priority]
instance normalization_monoid_of_unique_units : normalization_monoid α :=
{ norm_unit := λ x, 1,
norm_unit_zero := rfl,
norm_unit_mul := λ x y hx hy, (mul_one 1).symm,
norm_unit_coe_units := λ u, subsingleton.elim _ _ }
@[simp] lemma norm_unit_eq_one (x : α) : norm_unit x = 1 := rfl
@[simp] lemma normalize_eq (x : α) : normalize x = x := mul_one x
/-- If a monoid's only unit is `1`, then it is isomorphic to its associates. -/
@[simps]
def associates_equiv_of_unique_units : associates α ≃* α :=
{ to_fun := associates.out,
inv_fun := associates.mk,
left_inv := associates.mk_out,
right_inv := λ t, (associates.out_mk _).trans $ normalize_eq _,
map_mul' := associates.out_mul }
end unique_unit
section is_domain
variables [comm_ring α] [is_domain α] [normalized_gcd_monoid α]
lemma gcd_eq_of_dvd_sub_right {a b c : α} (h : a ∣ b - c) : gcd a b = gcd a c :=
begin
apply dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _);
rw dvd_gcd_iff; refine ⟨gcd_dvd_left _ _, _⟩,
{ rcases h with ⟨d, hd⟩,
rcases gcd_dvd_right a b with ⟨e, he⟩,
rcases gcd_dvd_left a b with ⟨f, hf⟩,
use e - f * d,
rw [mul_sub, ← he, ← mul_assoc, ← hf, ← hd, sub_sub_cancel] },
{ rcases h with ⟨d, hd⟩,
rcases gcd_dvd_right a c with ⟨e, he⟩,
rcases gcd_dvd_left a c with ⟨f, hf⟩,
use e + f * d,
rw [mul_add, ← he, ← mul_assoc, ← hf, ← hd, ← add_sub_assoc, add_comm c b, add_sub_cancel] }
end
lemma gcd_eq_of_dvd_sub_left {a b c : α} (h : a ∣ b - c) : gcd b a = gcd c a :=
by rw [gcd_comm _ a, gcd_comm _ a, gcd_eq_of_dvd_sub_right h]
end is_domain
section constructors
noncomputable theory
open associates
variables [cancel_comm_monoid_with_zero α]
private lemma map_mk_unit_aux [decidable_eq α] {f : associates α →* α}
(hinv : function.right_inverse f associates.mk) (a : α) :
a * ↑(classical.some (associated_map_mk hinv a)) = f (associates.mk a) :=
classical.some_spec (associated_map_mk hinv a)
/-- Define `normalization_monoid` on a structure from a `monoid_hom` inverse to `associates.mk`. -/
def normalization_monoid_of_monoid_hom_right_inverse [decidable_eq α] (f : associates α →* α)
(hinv : function.right_inverse f associates.mk) :
normalization_monoid α :=
{ norm_unit := λ a, if a = 0 then 1 else
classical.some (associates.mk_eq_mk_iff_associated.1 (hinv (associates.mk a)).symm),
norm_unit_zero := if_pos rfl,
norm_unit_mul := λ a b ha hb, by
{ rw [if_neg (mul_ne_zero ha hb), if_neg ha, if_neg hb, units.ext_iff, units.coe_mul],
suffices : (a * b) * ↑(classical.some (associated_map_mk hinv (a * b))) =
(a * ↑(classical.some (associated_map_mk hinv a))) *
(b * ↑(classical.some (associated_map_mk hinv b))),
{ apply mul_left_cancel₀ (mul_ne_zero ha hb) _,
simpa only [mul_assoc, mul_comm, mul_left_comm] using this },
rw [map_mk_unit_aux hinv a, map_mk_unit_aux hinv (a * b), map_mk_unit_aux hinv b,
← monoid_hom.map_mul, associates.mk_mul_mk] },
norm_unit_coe_units := λ u, by
{ nontriviality α,
rw [if_neg (units.ne_zero u), units.ext_iff],
apply mul_left_cancel₀ (units.ne_zero u),
rw [units.mul_inv, map_mk_unit_aux hinv u,
associates.mk_eq_mk_iff_associated.2 (associated_one_iff_is_unit.2 ⟨u, rfl⟩),
associates.mk_one, monoid_hom.map_one] } }
/-- Define `gcd_monoid` on a structure just from the `gcd` and its properties. -/
noncomputable def gcd_monoid_of_gcd [decidable_eq α] (gcd : α → α → α)
(gcd_dvd_left : ∀a b, gcd a b ∣ a)
(gcd_dvd_right : ∀a b, gcd a b ∣ b)
(dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b) :
gcd_monoid α :=
{ gcd := gcd,
gcd_dvd_left := gcd_dvd_left,
gcd_dvd_right := gcd_dvd_right,
dvd_gcd := λ a b c, dvd_gcd,
lcm := λ a b, if a = 0 then 0 else classical.some ((gcd_dvd_left a b).trans (dvd.intro b rfl)),
gcd_mul_lcm := λ a b, by
{ split_ifs with a0,
{ rw [mul_zero, a0, zero_mul] },
{ rw ←classical.some_spec ((gcd_dvd_left a b).trans (dvd.intro b rfl)) } },
lcm_zero_left := λ a, if_pos rfl,
lcm_zero_right := λ a, by
{ split_ifs with a0, { refl },
have h := (classical.some_spec ((gcd_dvd_left a 0).trans (dvd.intro 0 rfl))).symm,
have a0' : gcd a 0 ≠ 0,
{ contrapose! a0,
rw [←associated_zero_iff_eq_zero, ←a0],
exact associated_of_dvd_dvd (dvd_gcd (dvd_refl a) (dvd_zero a)) (gcd_dvd_left _ _) },
apply or.resolve_left (mul_eq_zero.1 _) a0',
rw [h, mul_zero] } }
/-- Define `normalized_gcd_monoid` on a structure just from the `gcd` and its properties. -/
noncomputable def normalized_gcd_monoid_of_gcd [normalization_monoid α] [decidable_eq α]
(gcd : α → α → α)
(gcd_dvd_left : ∀a b, gcd a b ∣ a)
(gcd_dvd_right : ∀a b, gcd a b ∣ b)
(dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b)
(normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b) :
normalized_gcd_monoid α :=
{ gcd := gcd,
gcd_dvd_left := gcd_dvd_left,
gcd_dvd_right := gcd_dvd_right,
dvd_gcd := λ a b c, dvd_gcd,
normalize_gcd := normalize_gcd,
lcm := λ a b, if a = 0 then 0 else classical.some (dvd_normalize_iff.2
((gcd_dvd_left a b).trans (dvd.intro b rfl))),
normalize_lcm := λ a b, by
{ dsimp [normalize],
split_ifs with a0,
{ exact @normalize_zero α _ _ },
{ have := (classical.some_spec (dvd_normalize_iff.2
((gcd_dvd_left a b).trans (dvd.intro b rfl)))).symm,
set l := classical.some (dvd_normalize_iff.2
((gcd_dvd_left a b).trans (dvd.intro b rfl))),
obtain rfl|hb := eq_or_ne b 0,
{ simp only [normalize_zero, mul_zero, mul_eq_zero] at this,
obtain ha|hl := this,
{ apply (a0 _).elim,
rw [←zero_dvd_iff, ←ha],
exact gcd_dvd_left _ _ },
{ convert @normalize_zero α _ _ } },
have h1 : gcd a b ≠ 0,
{ have hab : a * b ≠ 0 := mul_ne_zero a0 hb,
contrapose! hab,
rw [←normalize_eq_zero, ←this, hab, zero_mul] },
have h2 : normalize (gcd a b * l) = gcd a b * l,
{ rw [this, normalize_idem] },
rw ←normalize_gcd at this,
rwa [normalize.map_mul, normalize_gcd, mul_right_inj' h1] at h2 } },
gcd_mul_lcm := λ a b, by
{ split_ifs with a0,
{ rw [mul_zero, a0, zero_mul] },
{ rw ←classical.some_spec (dvd_normalize_iff.2 ((gcd_dvd_left a b).trans (dvd.intro b rfl))),
exact normalize_associated (a * b) } },
lcm_zero_left := λ a, if_pos rfl,
lcm_zero_right := λ a, by
{ split_ifs with a0, { refl },
rw ← normalize_eq_zero at a0,
have h := (classical.some_spec (dvd_normalize_iff.2
((gcd_dvd_left a 0).trans (dvd.intro 0 rfl)))).symm,
have gcd0 : gcd a 0 = normalize a,
{ rw ← normalize_gcd,
exact normalize_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_zero a)) },
rw ← gcd0 at a0,
apply or.resolve_left (mul_eq_zero.1 _) a0,
rw [h, mul_zero, normalize_zero] },
.. (infer_instance : normalization_monoid α) }
/-- Define `gcd_monoid` on a structure just from the `lcm` and its properties. -/
noncomputable def gcd_monoid_of_lcm [decidable_eq α] (lcm : α → α → α)
(dvd_lcm_left : ∀a b, a ∣ lcm a b)
(dvd_lcm_right : ∀a b, b ∣ lcm a b)
(lcm_dvd : ∀{a b c}, c ∣ a → b ∣ a → lcm c b ∣ a):
gcd_monoid α :=
let exists_gcd := λ a b, lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl) in
{ lcm := lcm,
gcd := λ a b, if a = 0 then b else (if b = 0 then a else
classical.some (exists_gcd a b)),
gcd_mul_lcm := λ a b, by
{ split_ifs,
{ rw [h, eq_zero_of_zero_dvd (dvd_lcm_left _ _), mul_zero, zero_mul] },
{ rw [h_1, eq_zero_of_zero_dvd (dvd_lcm_right _ _), mul_zero] },
rw [mul_comm, ←classical.some_spec (exists_gcd a b)] },
lcm_zero_left := λ a, eq_zero_of_zero_dvd (dvd_lcm_left _ _),
lcm_zero_right := λ a, eq_zero_of_zero_dvd (dvd_lcm_right _ _),
gcd_dvd_left := λ a b, by
{ split_ifs with h h_1,
{ rw h, apply dvd_zero },
{ exact dvd_rfl },
have h0 : lcm a b ≠ 0,
{ intro con,
have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl),
rw [con, zero_dvd_iff, mul_eq_zero] at h,
cases h; tauto },
rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b),
mul_comm, mul_dvd_mul_iff_right h],
apply dvd_lcm_right },
gcd_dvd_right := λ a b, by
{ split_ifs with h h_1,
{ exact dvd_rfl },
{ rw h_1, apply dvd_zero },
have h0 : lcm a b ≠ 0,
{ intro con,
have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl),
rw [con, zero_dvd_iff, mul_eq_zero] at h,
cases h; tauto },
rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b),
mul_dvd_mul_iff_right h_1],
apply dvd_lcm_left },
dvd_gcd := λ a b c ac ab, by
{ split_ifs,
{ exact ab },
{ exact ac },
have h0 : lcm c b ≠ 0,
{ intro con,
have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left c rfl),
rw [con, zero_dvd_iff, mul_eq_zero] at h,
cases h; tauto },
rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd c b)],
rcases ab with ⟨d, rfl⟩,
rw mul_eq_zero at h_1,
push_neg at h_1,
rw [mul_comm a, ← mul_assoc, mul_dvd_mul_iff_right h_1.1],
apply lcm_dvd (dvd.intro d rfl),
rw [mul_comm, mul_dvd_mul_iff_right h_1.2],
apply ac } }
/-- Define `normalized_gcd_monoid` on a structure just from the `lcm` and its properties. -/
noncomputable def normalized_gcd_monoid_of_lcm [normalization_monoid α] [decidable_eq α]
(lcm : α → α → α)
(dvd_lcm_left : ∀a b, a ∣ lcm a b)
(dvd_lcm_right : ∀a b, b ∣ lcm a b)
(lcm_dvd : ∀{a b c}, c ∣ a → b ∣ a → lcm c b ∣ a)
(normalize_lcm : ∀a b, normalize (lcm a b) = lcm a b) :
normalized_gcd_monoid α :=
let exists_gcd := λ a b, dvd_normalize_iff.2 (lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl)) in
{ lcm := lcm,
gcd := λ a b, if a = 0 then normalize b else (if b = 0 then normalize a else
classical.some (exists_gcd a b)),
gcd_mul_lcm := λ a b, by
{ split_ifs with h h_1,
{ rw [h, eq_zero_of_zero_dvd (dvd_lcm_left _ _), mul_zero, zero_mul] },
{ rw [h_1, eq_zero_of_zero_dvd (dvd_lcm_right _ _), mul_zero, mul_zero] },
rw [mul_comm, ←classical.some_spec (exists_gcd a b)],
exact normalize_associated (a * b) },
normalize_lcm := normalize_lcm,
normalize_gcd := λ a b, by
{ dsimp [normalize],
split_ifs with h h_1,
{ apply normalize_idem },
{ apply normalize_idem },
have h0 : lcm a b ≠ 0,
{ intro con,
have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl),
rw [con, zero_dvd_iff, mul_eq_zero] at h,
cases h; tauto },
apply mul_left_cancel₀ h0,
refine trans _ (classical.some_spec (exists_gcd a b)),
conv_lhs { congr, rw [← normalize_lcm a b] },
erw [← normalize.map_mul, ← classical.some_spec (exists_gcd a b), normalize_idem] },
lcm_zero_left := λ a, eq_zero_of_zero_dvd (dvd_lcm_left _ _),
lcm_zero_right := λ a, eq_zero_of_zero_dvd (dvd_lcm_right _ _),
gcd_dvd_left := λ a b, by
{ split_ifs,
{ rw h, apply dvd_zero },
{ exact (normalize_associated _).dvd },
have h0 : lcm a b ≠ 0,
{ intro con,
have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl),
rw [con, zero_dvd_iff, mul_eq_zero] at h,
cases h; tauto },
rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b),
normalize_dvd_iff, mul_comm, mul_dvd_mul_iff_right h],
apply dvd_lcm_right },
gcd_dvd_right := λ a b, by
{ split_ifs,
{ exact (normalize_associated _).dvd },
{ rw h_1, apply dvd_zero },
have h0 : lcm a b ≠ 0,
{ intro con,
have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl),
rw [con, zero_dvd_iff, mul_eq_zero] at h,
cases h; tauto },
rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b),
normalize_dvd_iff, mul_dvd_mul_iff_right h_1],
apply dvd_lcm_left },
dvd_gcd := λ a b c ac ab, by
{ split_ifs,
{ apply dvd_normalize_iff.2 ab },
{ apply dvd_normalize_iff.2 ac },
have h0 : lcm c b ≠ 0,
{ intro con,
have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left c rfl),
rw [con, zero_dvd_iff, mul_eq_zero] at h,
cases h; tauto },
rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (dvd_normalize_iff.2
(lcm_dvd (dvd.intro b rfl) (dvd.intro_left c rfl))), dvd_normalize_iff],
rcases ab with ⟨d, rfl⟩,
rw mul_eq_zero at h_1,
push_neg at h_1,
rw [mul_comm a, ← mul_assoc, mul_dvd_mul_iff_right h_1.1],
apply lcm_dvd (dvd.intro d rfl),
rw [mul_comm, mul_dvd_mul_iff_right h_1.2],
apply ac },
.. (infer_instance : normalization_monoid α) }
/-- Define a `gcd_monoid` structure on a monoid just from the existence of a `gcd`. -/
noncomputable def gcd_monoid_of_exists_gcd [decidable_eq α]
(h : ∀ a b : α, ∃ c : α, ∀ d : α, d ∣ a ∧ d ∣ b ↔ d ∣ c) :
gcd_monoid α :=
gcd_monoid_of_gcd
(λ a b, (classical.some (h a b)))
(λ a b,
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).1)
(λ a b,
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).2)
(λ a b c ac ab, ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩))
/-- Define a `normalized_gcd_monoid` structure on a monoid just from the existence of a `gcd`. -/
noncomputable def normalized_gcd_monoid_of_exists_gcd [normalization_monoid α] [decidable_eq α]
(h : ∀ a b : α, ∃ c : α, ∀ d : α, d ∣ a ∧ d ∣ b ↔ d ∣ c) :
normalized_gcd_monoid α :=
normalized_gcd_monoid_of_gcd
(λ a b, normalize (classical.some (h a b)))
(λ a b, normalize_dvd_iff.2
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).1)
(λ a b, normalize_dvd_iff.2
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).2)
(λ a b c ac ab, dvd_normalize_iff.2 ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩))
(λ a b, normalize_idem _)
/-- Define a `gcd_monoid` structure on a monoid just from the existence of an `lcm`. -/
noncomputable def gcd_monoid_of_exists_lcm [decidable_eq α]
(h : ∀ a b : α, ∃ c : α, ∀ d : α, a ∣ d ∧ b ∣ d ↔ c ∣ d) :
gcd_monoid α :=
gcd_monoid_of_lcm
(λ a b, (classical.some (h a b)))
(λ a b,
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).1)
(λ a b,
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).2)
(λ a b c ac ab, ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩))
/-- Define a `normalized_gcd_monoid` structure on a monoid just from the existence of an `lcm`. -/
noncomputable def normalized_gcd_monoid_of_exists_lcm [normalization_monoid α] [decidable_eq α]
(h : ∀ a b : α, ∃ c : α, ∀ d : α, a ∣ d ∧ b ∣ d ↔ c ∣ d) :
normalized_gcd_monoid α :=
normalized_gcd_monoid_of_lcm
(λ a b, normalize (classical.some (h a b)))
(λ a b, dvd_normalize_iff.2
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).1)
(λ a b, dvd_normalize_iff.2
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).2)
(λ a b c ac ab, normalize_dvd_iff.2 ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩))
(λ a b, normalize_idem _)
end constructors
namespace comm_group_with_zero
variables (G₀ : Type*) [comm_group_with_zero G₀] [decidable_eq G₀]
@[priority 100] -- see Note [lower instance priority]
instance : normalized_gcd_monoid G₀ :=
{ norm_unit := λ x, if h : x = 0 then 1 else (units.mk0 x h)⁻¹,
norm_unit_zero := dif_pos rfl,
norm_unit_mul := λ x y x0 y0, units.eq_iff.1 (by simp [x0, y0, mul_comm]),
norm_unit_coe_units := λ u, by { rw [dif_neg (units.ne_zero _), units.mk0_coe], apply_instance },
gcd := λ a b, if a = 0 ∧ b = 0 then 0 else 1,
lcm := λ a b, if a = 0 ∨ b = 0 then 0 else 1,
gcd_dvd_left := λ a b, by { split_ifs with h, { rw h.1 }, { exact one_dvd _ } },
gcd_dvd_right := λ a b, by { split_ifs with h, { rw h.2 }, { exact one_dvd _ } },
dvd_gcd := λ a b c hac hab, begin
split_ifs with h, { apply dvd_zero },
cases not_and_distrib.mp h with h h;
refine is_unit_iff_dvd_one.mp (is_unit_of_dvd_unit _ (is_unit.mk0 _ h));
assumption
end,
gcd_mul_lcm := λ a b, begin
by_cases ha : a = 0, { simp [ha] },
by_cases hb : b = 0, { simp [hb] },
rw [if_neg (not_and_of_not_left _ ha), one_mul, if_neg (not_or ha hb)],
exact (associated_one_iff_is_unit.mpr ((is_unit.mk0 _ ha).mul (is_unit.mk0 _ hb))).symm
end,
lcm_zero_left := λ b, if_pos (or.inl rfl),
lcm_zero_right := λ a, if_pos (or.inr rfl),
-- `split_ifs` wants to split `normalize`, so handle the cases manually
normalize_gcd := λ a b, if h : a = 0 ∧ b = 0 then by simp [if_pos h] else by simp [if_neg h],
normalize_lcm := λ a b, if h : a = 0 ∨ b = 0 then by simp [if_pos h] else by simp [if_neg h] }
@[simp]
lemma coe_norm_unit {a : G₀} (h0 : a ≠ 0) : (↑(norm_unit a) : G₀) = a⁻¹ :=
by simp [norm_unit, h0]
lemma normalize_eq_one {a : G₀} (h0 : a ≠ 0) : normalize a = 1 :=
by simp [normalize_apply, h0]
end comm_group_with_zero
|
0985122535fc1008144f303d8b959f08b480e3e3
|
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
|
/tests/lean/run/meta2.lean
|
7c2c6933a59f4ffe247dc8fe7456ad667b432730
|
[
"Apache-2.0"
] |
permissive
|
dupuisf/lean4
|
d082d13b01243e1de29ae680eefb476961221eef
|
6a39c65bd28eb0e28c3870188f348c8914502718
|
refs/heads/master
| 1,676,948,755,391
| 1,610,665,114,000
| 1,610,665,114,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 19,079
|
lean
|
#lang lean4
import Lean.Meta
open Lean
open Lean.Meta
-- set_option trace.Meta true
--set_option trace.Meta.isDefEq.step false
-- set_option trace.Meta.isDefEq.delta false
set_option trace.Meta.debug true
def print (msg : MessageData) : MetaM Unit :=
trace! `Meta.debug msg
def checkM (x : MetaM Bool) : MetaM Unit :=
unless (← x) do throwError "check failed"
def getAssignment (m : Expr) : MetaM Expr :=
do let v? ← getExprMVarAssignment? m.mvarId!;
(match v? with
| some v => pure v
| none => throwError "metavariable is not assigned")
def nat := mkConst `Nat
def boolE := mkConst `Bool
def succ := mkConst `Nat.succ
def zero := mkConst `Nat.zero
def add := mkConst `Nat.add
def io := mkConst `IO
def type := mkSort levelOne
def boolFalse := mkConst `Bool.false
def boolTrue := mkConst `Bool.true
def tst1 : MetaM Unit :=
do print "----- tst1 -----";
let mvar <- mkFreshExprMVar nat;
checkM $ isExprDefEq mvar (mkNatLit 10);
checkM $ isExprDefEq mvar (mkNatLit 10);
pure ()
#eval tst1
def tst2 : MetaM Unit :=
do print "----- tst2 -----";
let mvar <- mkFreshExprMVar nat;
checkM $ isExprDefEq (mkApp succ mvar) (mkApp succ (mkNatLit 10));
checkM $ isExprDefEq mvar (mkNatLit 10);
pure ()
#eval tst2
def tst3 : MetaM Unit :=
do print "----- tst3 -----";
let t := mkLambda `x BinderInfo.default nat $ mkBVar 0;
let mvar ← mkFreshExprMVar (mkForall `x BinderInfo.default nat nat);
lambdaTelescope t fun xs _ => do
let x := xs[0];
checkM $ isExprDefEq (mkApp mvar x) (mkAppN add #[x, mkAppN add #[mkNatLit 10, x]]);
pure ();
let v ← getAssignment mvar;
print v;
pure ()
#eval tst3
def tst4 : MetaM Unit :=
do print "----- tst4 -----";
let t := mkLambda `x BinderInfo.default nat $ mkBVar 0;
lambdaTelescope t fun xs _ => do
let x := xs[0];
let mvar ← mkFreshExprMVar (mkForall `x BinderInfo.default nat nat);
-- the following `isExprDefEq` fails because `x` is also in the context of `mvar`
checkM $ not <$> isExprDefEq (mkApp mvar x) (mkAppN add #[x, mkAppN add #[mkNatLit 10, x]]);
checkM $ approxDefEq $ isExprDefEq (mkApp mvar x) (mkAppN add #[x, mkAppN add #[mkNatLit 10, x]]);
let v ← getAssignment mvar;
print v;
pure ();
pure ()
#eval tst4
def mkAppC (c : Name) (xs : Array Expr) : MetaM Expr :=
do let r ← mkAppM c xs;
check r;
pure r
def mkProd (a b : Expr) : MetaM Expr := mkAppC `Prod #[a, b]
def mkPair (a b : Expr) : MetaM Expr := mkAppC `Prod.mk #[a, b]
def mkFst (s : Expr) : MetaM Expr := mkAppC `Prod.fst #[s]
def mkSnd (s : Expr) : MetaM Expr := mkAppC `Prod.snd #[s]
def tst5 : MetaM Unit :=
do print "----- tst5 -----";
let p₁ ← mkPair (mkNatLit 1) (mkNatLit 2);
let x ← mkFst p₁;
print x;
let v ← whnf x;
print v;
let v ← withTransparency TransparencyMode.reducible $ whnf x;
print v;
let x ← mkId x;
print x;
let prod ← mkProd nat nat;
let m ← mkFreshExprMVar prod;
let y ← mkFst m;
checkM $ isExprDefEq y x;
print y;
let x ← mkProjection p₁ `fst;
print x;
let y ← mkProjection p₁ `snd;
print y
#eval tst5
def tst6 : MetaM Unit :=
do print "----- tst6 -----";
withLocalDeclD `x nat $ fun x => do
let m ← mkFreshExprMVar nat;
let t := mkAppN add #[m, mkNatLit 4];
let s := mkAppN add #[x, mkNatLit 3];
checkM $ not <$> isExprDefEq t s;
let s := mkAppN add #[x, mkNatLit 6];
checkM $ isExprDefEq t s;
let v ← getAssignment m;
checkM $ pure $ v == mkAppN add #[x, mkNatLit 2];
print v;
let m ← mkFreshExprMVar nat;
let t := mkAppN add #[m, mkNatLit 4];
let s := mkNatLit 3;
checkM $ not <$> isExprDefEq t s;
let s := mkNatLit 10;
checkM $ isExprDefEq t s;
let v ← getAssignment m;
checkM $ pure $ v == mkNatLit 6;
print v;
pure ()
#eval tst6
def tst7 : MetaM Unit :=
do print "----- tst7 -----";
withLocalDeclD `x type $ fun x => do
let m1 ← mkFreshExprMVar (← mkArrow type type);
let m2 ← mkFreshExprMVar type;
let t := mkApp io x;
-- we need to use foApprox to solve `?m1 ?m2 =?= IO x`
checkM $ not <$> isDefEq (mkApp m1 m2) t;
checkM $ approxDefEq $ isDefEq (mkApp m1 m2) t;
let v ← getAssignment m1;
checkM $ pure $ v == io;
let v ← getAssignment m2;
checkM $ pure $ v == x;
pure ()
#eval tst7
def tst9 : MetaM Unit :=
do print "----- tst9 -----";
let env ← getEnv;
print (toString (← isReducible `Prod.fst))
print (toString (← isReducible `Add.add))
pure ()
#eval tst9
def tst10 : MetaM Unit :=
do print "----- tst10 -----";
let t ← withLocalDeclD `x nat $ fun x => do {
let b := mkAppN add #[x, mkAppN add #[mkNatLit 2, mkNatLit 3]];
mkLambdaFVars #[x] b
};
print t;
let t ← reduce t;
print t;
pure ()
#eval tst10
def tst11 : MetaM Unit :=
do print "----- tst11 -----";
checkM $ isType nat;
checkM $ isType (← mkArrow nat nat);
checkM $ not <$> isType add;
checkM $ not <$> isType (mkNatLit 1);
withLocalDeclD `x nat fun x => do
checkM $ not <$> isType x;
checkM $ not <$> (mkLambdaFVars #[x] x >>= isType);
checkM $ not <$> (mkLambdaFVars #[x] nat >>= isType);
let t ← mkEq x (mkNatLit 0);
let (t, _) ← mkForallUsedOnly #[x] t;
print t;
checkM $ isType t;
pure ();
pure ()
#eval tst11
def tst12 : MetaM Unit :=
do print "----- tst12 -----";
withLocalDeclD `x nat $ fun x => do
let t ← mkEqRefl x >>= mkLambdaFVars #[x];
print t;
let type ← inferType t;
print type;
isProofQuick t >>= fun b => print (toString b);
isProofQuick nat >>= fun b => print (toString b);
isProofQuick type >>= fun b => print (toString b);
pure ();
pure ()
#eval tst12
def tst13 : MetaM Unit :=
do print "----- tst13 -----";
let m₁ ← mkFreshExprMVar (← mkArrow type type);
let m₂ ← mkFreshExprMVar (mkApp m₁ nat);
let t ← mkId m₂;
print t;
let r ← abstractMVars t;
print r.expr;
let (_, _, e) ← openAbstractMVarsResult r;
print e;
pure ()
def mkDecEq (type : Expr) : MetaM Expr := mkAppC `DecidableEq #[type]
def mkStateM (σ : Expr) : MetaM Expr := mkAppC `StateM #[σ]
def mkMonad (m : Expr) : MetaM Expr := mkAppC `Monad #[m]
def mkMonadState (σ m : Expr) : MetaM Expr := mkAppC `MonadState #[σ, m]
def mkAdd (a : Expr) : MetaM Expr := mkAppC `Add #[a]
def mkToString (a : Expr) : MetaM Expr := mkAppC `ToString #[a]
def tst14 : MetaM Unit :=
do print "----- tst14 -----";
let stateM ← mkStateM nat;
print stateM;
let monad ← mkMonad stateM;
let globalInsts ← getGlobalInstancesIndex;
let insts ← globalInsts.getUnify monad;
print (insts.map (·.val));
pure ()
#eval tst14
def tst15 : MetaM Unit :=
do print "----- tst15 -----";
let inst ← mkAdd nat;
let r ← synthInstance inst;
print r;
pure ()
#eval tst15
def tst16 : MetaM Unit :=
do print "----- tst16 -----";
let prod ← mkProd nat nat;
let inst ← mkToString prod;
print inst;
let r ← synthInstance inst;
print r;
pure ()
#eval tst16
def tst17 : MetaM Unit :=
do print "----- tst17 -----";
let prod ← mkProd nat nat;
let prod ← mkProd boolE prod;
let inst ← mkToString prod;
print inst;
let r ← synthInstance inst;
print r;
pure ()
#eval tst17
def tst18 : MetaM Unit :=
do print "----- tst18 -----";
let decEqNat ← mkDecEq nat;
let r ← synthInstance decEqNat;
print r;
pure ()
#eval tst18
def tst19 : MetaM Unit :=
do print "----- tst19 -----";
let stateM ← mkStateM nat;
print stateM;
let monad ← mkMonad stateM;
print monad;
let r ← synthInstance monad;
print r;
pure ()
#eval tst19
def tst20 : MetaM Unit :=
do print "----- tst20 -----";
let stateM ← mkStateM nat;
print stateM;
let monadState ← mkMonadState nat stateM;
print monadState;
let r ← synthInstance monadState;
print r;
pure ()
#eval tst20
def tst21 : MetaM Unit :=
do print "----- tst21 -----";
withLocalDeclD `x nat $ fun x => do
withLocalDeclD `y nat $ fun y => do
withLocalDeclD `z nat $ fun z => do
let eq₁ ← mkEq x y;
let eq₂ ← mkEq y z;
withLocalDeclD `h₁ eq₁ $ fun h₁ => do
withLocalDeclD `h₂ eq₂ $ fun h₂ => do
let h ← mkEqTrans h₁ h₂;
let h ← mkEqSymm h;
let h ← mkCongrArg succ h;
let h₂ ← mkEqRefl succ;
let h ← mkCongr h₂ h;
let t ← inferType h;
check h;
print h;
print t;
let h ← mkCongrFun h₂ x;
let t ← inferType h;
check h;
print t;
pure ()
#eval tst21
def tst22 : MetaM Unit :=
do print "----- tst22 -----";
withLocalDeclD `x nat $ fun x => do
withLocalDeclD `y nat $ fun y => do
let t ← mkAppC `Add.add #[x, y];
print t;
let t ← mkAppC `Add.add #[y, x];
print t;
let t ← mkAppC `ToString.toString #[x];
print t;
pure ()
#eval tst22
def test1 : Nat := (fun x y => x + y) 0 1
def tst23 : MetaM Unit :=
do print "----- tst23 -----";
let cinfo ← getConstInfo `test1;
let v := cinfo.value?.get!;
print v;
print v.headBeta
#eval tst23
def tst25 : MetaM Unit :=
do print "----- tst25 -----";
withLocalDeclD `α type $ fun α =>
withLocalDeclD `β type $ fun β =>
withLocalDeclD `σ type $ fun σ => do {
let (t1, n) ← mkForallUsedOnly #[α, β, σ] $ ← mkArrow α β;
print t1;
checkM $ pure $ n == 2;
let (t2, n) ← mkForallUsedOnly #[α, β, σ] $ ← mkArrow α (← mkArrow β σ);
checkM $ pure $ n == 3;
print t2;
let (t3, n) ← mkForallUsedOnly #[α, β, σ] $ α;
checkM $ pure $ n == 1;
print t3;
let (t4, n) ← mkForallUsedOnly #[α, β, σ] $ σ;
checkM $ pure $ n == 1;
print t4;
let (t5, n) ← mkForallUsedOnly #[α, β, σ] $ nat;
checkM $ pure $ n == 0;
print t5;
pure ()
};
pure ()
#eval tst25
def tst26 : MetaM Unit := do
print "----- tst26 -----";
let m1 ← mkFreshExprMVar (← mkArrow nat nat);
let m2 ← mkFreshExprMVar nat;
let m3 ← mkFreshExprMVar nat;
checkM $ approxDefEq $ isDefEq (mkApp m1 m2) m3;
checkM $ do { let b ← isExprMVarAssigned $ m1.mvarId!; pure (!b) };
checkM $ isExprMVarAssigned $ m3.mvarId!;
pure ()
#eval tst26
section
set_option trace.Meta.isDefEq.step true
set_option trace.Meta.isDefEq.delta true
set_option trace.Meta.isDefEq.assign true
def tst27 : MetaM Unit := do
print "----- tst27 -----";
let m ← mkFreshExprMVar nat;
checkM $ isDefEq (mkNatLit 1) (mkApp (mkConst `Nat.succ) m);
pure ()
#eval tst27
end
def tst28 : MetaM Unit := do
print "----- tst28 -----";
withLocalDeclD `x nat $ fun x =>
withLocalDeclD `y nat $ fun y =>
withLocalDeclD `z nat $ fun z => do
let t1 ← mkAppM `Add.add #[x, y];
let t1 ← mkAppM `Add.add #[x, t1];
let t1 ← mkAppM `Add.add #[t1, t1];
let t2 ← mkAppM `Add.add #[z, y];
let t3 ← mkAppM `Eq #[t2, t1];
let t3 ← mkForallFVars #[z] t3;
let m ← mkFreshExprMVar nat;
let p ← mkAppM `Add.add #[x, m];
print t3;
let r ← kabstract t3 p;
print r;
let p ← mkAppM `Add.add #[x, y];
let r ← kabstract t3 p;
print r;
pure ()
#eval tst28
def norm : Level → Level := @Lean.Level.normalize
def tst29 : MetaM Unit := do
print "----- tst29 -----";
let u := mkLevelParam `u;
let v := mkLevelParam `v;
let u1 := mkLevelSucc u;
let m := mkLevelMax levelOne u1;
print (norm m);
checkM $ pure $ norm m == u1;
let m := mkLevelMax u1 levelOne;
print (norm m);
checkM $ pure $ norm m == u1;
let m := mkLevelMax (mkLevelMax levelOne (mkLevelSucc u1)) (mkLevelSucc levelOne);
checkM $ pure $ norm m == mkLevelSucc u1;
print m;
print (norm m);
let m := mkLevelMax (mkLevelMax (mkLevelSucc (mkLevelSucc u1)) (mkLevelSucc u1)) (mkLevelSucc levelOne);
print m;
print (norm m);
checkM $ pure $ norm m == mkLevelSucc (mkLevelSucc u1);
let m := mkLevelMax (mkLevelMax (mkLevelSucc v) (mkLevelSucc u1)) (mkLevelSucc levelOne);
print m;
print (norm m);
pure ()
#eval tst29
def tst30 : MetaM Unit := do
print "----- tst30 -----";
let m1 ← mkFreshExprMVar nat;
let m2 ← mkFreshExprMVar (← mkArrow nat nat);
withLocalDeclD `x nat $ fun x => do
let t := mkApp succ $ mkApp m2 x;
print t;
checkM $ approxDefEq $ isDefEq m1 t;
let r ← instantiateMVars m1;
print r;
let r ← instantiateMVars m2;
print r;
pure ()
#eval tst30
def tst31 : MetaM Unit := do
print "----- tst31 -----";
let m ← mkFreshExprMVar nat;
let t := mkLet `x nat zero m;
print t;
checkM $ isDefEq t m;
pure ()
def tst32 : MetaM Unit := do
print "----- tst32 -----";
withLocalDeclD `a nat $ fun a => do
withLocalDeclD `b nat $ fun b => do
let aeqb ← mkEq a b;
withLocalDeclD `h2 aeqb $ fun h2 => do
let t ← mkEq (mkApp2 add a a) a;
print t;
let motive := mkLambda `x BinderInfo.default nat (mkApp3 (mkConst `Eq [levelOne]) nat (mkApp2 add a (mkBVar 0)) a);
withLocalDeclD `h1 t $ fun h1 => do
let r ← mkEqNDRec motive h1 h2;
print r;
let rType ← inferType r >>= whnf;
print rType;
check r;
pure ()
#eval tst32
def tst33 : MetaM Unit := do
print "----- tst33 -----";
withLocalDeclD `a nat $ fun a => do
withLocalDeclD `b nat $ fun b => do
let aeqb ← mkEq a b;
withLocalDeclD `h2 aeqb $ fun h2 => do
let t ← mkEq (mkApp2 add a a) a;
let motive :=
mkLambda `x BinderInfo.default nat $
mkLambda `h BinderInfo.default (mkApp3 (mkConst `Eq [levelOne]) nat a (mkBVar 0)) $
(mkApp3 (mkConst `Eq [levelOne]) nat (mkApp2 add a (mkBVar 1)) a);
withLocalDeclD `h1 t $ fun h1 => do
let r ← mkEqRec motive h1 h2;
print r;
let rType ← inferType r >>= whnf;
print rType;
check r;
pure ()
#eval tst33
def tst34 : MetaM Unit := do
print "----- tst34 -----";
let type := mkSort levelOne;
withLocalDeclD `α type $ fun α => do
let m ← mkFreshExprMVar type;
let t ← mkLambdaFVars #[α] (← mkArrow m m);
print t;
pure ()
set_option pp.purify_metavars false
#eval tst34
def tst35 : MetaM Unit := do
print "----- tst35 -----";
let type := mkSort levelOne;
withLocalDeclD `α type $ fun α => do
let m1 ← mkFreshExprMVar type;
let m2 ← mkFreshExprMVar (← mkArrow nat type);
let v := mkLambda `x BinderInfo.default nat m1;
assignExprMVar m2.mvarId! v;
let w := mkApp m2 zero;
let t1 ← mkLambdaFVars #[α] (← mkArrow w w);
print t1;
let m3 ← mkFreshExprMVar type;
let t2 ← mkLambdaFVars #[α] (← mkArrow (mkBVar 0) (mkBVar 1));
print t2;
checkM $ isDefEq t1 t2;
pure ()
#eval tst35
#check @Id
def tst36 : MetaM Unit := do
print "----- tst36 -----";
let type := mkSort levelOne;
let m1 ← mkFreshExprMVar (← mkArrow type type);
withLocalDeclD `α type $ fun α => do
let m2 ← mkFreshExprMVar type;
let t ← mkAppM `Id #[m2];
checkM $ approxDefEq $ isDefEq (mkApp m1 α) t;
checkM $ approxDefEq $ isDefEq m1 (mkConst `Id [levelZero]);
pure ()
#eval tst36
def tst37 : MetaM Unit := do
print "----- tst37 -----";
let m1 ← mkFreshExprMVar (←mkArrow nat (←mkArrow type type));
let m2 ← mkFreshExprMVar (←mkArrow nat type);
withLocalDeclD `v nat $ fun v => do
let lhs := mkApp2 m1 v (mkApp m2 v);
let rhs ← mkAppM `StateM #[nat, nat];
print lhs;
print rhs;
checkM $ approxDefEq $ isDefEq lhs rhs;
pure ()
#eval tst37
def tst38 : MetaM Unit := do
print "----- tst38 -----";
let m1 ← mkFreshExprMVar nat;
withLocalDeclD `x nat $ fun x => do
let m2 ← mkFreshExprMVar type;
withLocalDeclD `y m2 $ fun y => do
let m3 ← mkFreshExprMVar (←mkArrow m2 nat);
let rhs := mkApp m3 y;
checkM $ approxDefEq $ isDefEq m2 nat;
print m2;
checkM $ getAssignment m2 >>= fun v => pure $ v == nat;
checkM $ approxDefEq $ isDefEq m1 rhs;
print m2;
checkM $ getAssignment m2 >>= fun v => pure $ v == nat;
pure ()
set_option pp.all true
set_option trace.Meta.isDefEq.step true
set_option trace.Meta.isDefEq.delta true
set_option trace.Meta.isDefEq.assign true
#eval tst38
def tst39 : MetaM Unit := do
print "----- tst39 -----";
withLocalDeclD `α type $ fun α =>
withLocalDeclD `β type $ fun β => do
let p ← mkProd α β;
let t ← mkForallFVars #[α, β] p;
print t;
let e ← instantiateForall t #[nat, boolE];
print e;
pure ()
#eval tst39
def tst40 : MetaM Unit := do
print "----- tst40 -----";
withLocalDeclD `α type $ fun α =>
withLocalDeclD `β type $ fun β =>
withLocalDeclD `a α $ fun a =>
withLocalDeclD `b β $ fun b =>
do
let p ← mkProd α β;
let t1 ← mkForallFVars #[α, β] p;
let t2 ← mkForallFVars #[α, β, a, b] p;
print t1;
print $ toString $ t1.bindingBody!.hasLooseBVarInExplicitDomain 0 false;
print $ toString $ t1.bindingBody!.hasLooseBVarInExplicitDomain 0 true;
print $ toString $ t2.bindingBody!.hasLooseBVarInExplicitDomain 0 false;
print $ t1.inferImplicit 2 false;
checkM $ pure $ ((t1.inferImplicit 2 false).bindingInfo! == BinderInfo.default);
checkM $ pure $ ((t1.inferImplicit 2 false).bindingBody!.bindingInfo! == BinderInfo.default);
print $ t1.inferImplicit 2 true;
checkM $ pure $ ((t1.inferImplicit 2 true).bindingInfo! == BinderInfo.implicit);
checkM $ pure $ ((t1.inferImplicit 2 true).bindingBody!.bindingInfo! == BinderInfo.implicit);
print t2;
print $ t2.inferImplicit 2 false;
checkM $ pure $ ((t2.inferImplicit 2 false).bindingInfo! == BinderInfo.implicit);
checkM $ pure $ ((t2.inferImplicit 2 false).bindingBody!.bindingInfo! == BinderInfo.implicit);
print $ t2.inferImplicit 1 false;
checkM $ pure $ ((t2.inferImplicit 1 false).bindingInfo! == BinderInfo.implicit);
checkM $ pure $ ((t2.inferImplicit 1 false).bindingBody!.bindingInfo! == BinderInfo.default);
pure ()
#eval tst40
universes u
structure A (α : Type u) :=
(x y : α)
structure B (α : Type u) :=
(z : α)
structure C (α : Type u) extends A α, B α :=
(w : Bool)
def mkA (x y : Expr) : MetaM Expr := mkAppC `A.mk #[x, y]
def mkB (z : Expr) : MetaM Expr := mkAppC `B.mk #[z]
def mkC (x y z w : Expr) : MetaM Expr := do
let a ← mkA x y;
let b ← mkB z;
mkAppC `C.mk #[a, b, w]
def tst41 : MetaM Unit := do
print "----- tst41 -----";
let c ← mkC (mkNatLit 1) (mkNatLit 2) (mkNatLit 3) boolTrue;
print c;
let x ← mkProjection c `x;
check x;
print x;
let y ← mkProjection c `y;
check y;
print y;
let z ← mkProjection c `z;
check z;
print z;
let w ← mkProjection c `w;
check w;
print w;
pure ()
set_option trace.Meta.isDefEq.step false
set_option trace.Meta.isDefEq.delta false
set_option trace.Meta.isDefEq.assign false
#eval tst41
set_option pp.all false
def tst42 : MetaM Unit := do
print "----- tst42 -----";
let t ← mkListLit nat [mkNatLit 1, mkNatLit 2];
print t;
check t;
let t ← mkArrayLit nat [mkNatLit 1, mkNatLit 2];
print t;
check t;
(match t.arrayLit? with
| some (_, xs) => do
checkM $ pure $ xs.length == 2;
(match (xs.get! 0).natLit?, (xs.get! 1).natLit? with
| some 1, some 2 => pure ()
| _, _ => throwError "nat lits expected")
| none => throwError "array lit expected")
#eval tst42
|
81b4d490de8cea404677b9055f0033a21f497c0e
|
302c785c90d40ad3d6be43d33bc6a558354cc2cf
|
/src/category_theory/limits/cofinal.lean
|
b3f4ceade9f2a02728795fc59690a6e8eee1a3b3
|
[
"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
| 16,433
|
lean
|
/-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.punit
import category_theory.structured_arrow
import category_theory.is_connected
import category_theory.limits.yoneda
import category_theory.limits.types
/-!
# Cofinal functors
A functor `F : C ⥤ D` is cofinal if for every `d : D`,
the comma category of morphisms `d ⟶ F.obj c` is connected.
We prove the following three statements are equivalent:
1. `F : C ⥤ D` is cofinal.
2. Every functor `G : D ⥤ E` has a colimit if and only if `F ⋙ G` does,
and these colimits are isomorphic via `colimit.pre G F`.
3. `colimit (F ⋙ coyoneda.obj (op d)) ≅ punit`.
Starting at 1. we show (in `cocones_equiv`) that
the categories of cocones over `G : D ⥤ E` and over `F ⋙ G` are equivalent.
(In fact, via an equivalence which does not change the cocone point.)
This readily implies 2., as `comp_has_colimit`, `has_colimit_of_comp`, and `colimit_iso`.
From 2. we can specialize to `G = coyoneda.obj (op d)` to obtain 3., as `colimit_comp_coyoneda_iso`.
From 3., we prove 1. directly in `cofinal_of_colimit_comp_coyoneda_iso_punit`.
We also show these conditions imply:
4. Every functor `H : Dᵒᵖ ⥤ E` has a limit if and only if `F.op ⋙ H` does,
and these limits are isomorphic via `limit.pre H F.op`.
## Naming
There is some discrepancy in the literature about naming; some say 'final' instead of 'cofinal'.
The explanation for this is that the 'co' prefix here is *not* the usual category-theoretic one
indicating duality, but rather indicating the sense of "along with".
While the trend seems to be towards using 'final', for now we go with the bulk of the literature
and use 'cofinal'.
## References
* https://stacks.math.columbia.edu/tag/09WN
* https://ncatlab.org/nlab/show/final+functor
* Borceux, Handbook of Categorical Algebra I, Section 2.11.
(Note he reverses the roles of definition and main result relative to here!)
-/
noncomputable theory
universes v u
namespace category_theory
open opposite
open category_theory.limits
variables {C : Type v} [small_category C]
variables {D : Type v} [small_category D]
/--
A functor `F : C ⥤ D` is cofinal if for every `d : D`, the comma category of morphisms `d ⟶ F.obj c`
is connected.
See https://stacks.math.columbia.edu/tag/04E6
-/
class cofinal (F : C ⥤ D) : Prop :=
(out (d : D) : is_connected (structured_arrow d F))
attribute [instance] cofinal.out
namespace cofinal
variables (F : C ⥤ D) [cofinal F]
instance (d : D) : nonempty (structured_arrow d F) := is_connected.is_nonempty
variables {E : Type u} [category.{v} E] (G : D ⥤ E)
/--
When `F : C ⥤ D` is cofinal, we denote by `lift F d` an arbitrary choice of object in `C` such that
there exists a morphism `d ⟶ F.obj (lift F d)`.
-/
def lift (d : D) : C :=
(classical.arbitrary (structured_arrow d F)).right
/--
When `F : C ⥤ D` is cofinal, we denote by `hom_to_lift` an arbitrary choice of morphism
`d ⟶ F.obj (lift F d)`.
-/
def hom_to_lift (d : D) : d ⟶ F.obj (lift F d) :=
(classical.arbitrary (structured_arrow d F)).hom
/--
We provide an induction principle for reasoning about `lift` and `hom_to_lift`.
We want to perform some construction (usually just a proof) about
the particular choices `lift F d` and `hom_to_lift F d`,
it suffices to perform that construction for some other pair of choices
(denoted `X₀ : C` and `k₀ : d ⟶ F.obj X₀` below),
and to show that how to transport such a construction
*both* directions along a morphism between such choices.
-/
lemma induction {d : D} (Z : Π (X : C) (k : d ⟶ F.obj X), Prop)
(h₁ : Π X₁ X₂ (k₁ : d ⟶ F.obj X₁) (k₂ : d ⟶ F.obj X₂) (f : X₁ ⟶ X₂),
(k₁ ≫ F.map f = k₂) → Z X₁ k₁ → Z X₂ k₂)
(h₂ : Π X₁ X₂ (k₁ : d ⟶ F.obj X₁) (k₂ : d ⟶ F.obj X₂) (f : X₁ ⟶ X₂),
(k₁ ≫ F.map f = k₂) → Z X₂ k₂ → Z X₁ k₁)
{X₀ : C} {k₀ : d ⟶ F.obj X₀} (z : Z X₀ k₀) : Z (lift F d) (hom_to_lift F d) :=
begin
apply nonempty.some,
apply @is_preconnected_induction _ _ _
(λ (Y : structured_arrow d F), Z Y.right Y.hom) _ _ { right := X₀, hom := k₀, } z,
{ intros j₁ j₂ f a, fapply h₁ _ _ _ _ f.right _ a, convert f.w.symm, dsimp, simp, },
{ intros j₁ j₂ f a, fapply h₂ _ _ _ _ f.right _ a, convert f.w.symm, dsimp, simp, },
end
variables {F G}
/--
Given a cocone over `F ⋙ G`, we can construct a `cocone G` with the same cocone point.
-/
@[simps]
def extend_cocone : cocone (F ⋙ G) ⥤ cocone G :=
{ obj := λ c,
{ X := c.X,
ι :=
{ app := λ X, G.map (hom_to_lift F X) ≫ c.ι.app (lift F X),
naturality' := λ X Y f,
begin
dsimp, simp,
-- This would be true if we'd chosen `lift F X` to be `lift F Y`
-- and `hom_to_lift F X` to be `f ≫ hom_to_lift F Y`.
apply induction F
(λ Z k, G.map f ≫ G.map (hom_to_lift F Y) ≫ c.ι.app (lift F Y) = G.map k ≫ c.ι.app Z),
{ intros Z₁ Z₂ k₁ k₂ g a z,
rw [←a, functor.map_comp, category.assoc, ←functor.comp_map, c.w, z], },
{ intros Z₁ Z₂ k₁ k₂ g a z,
rw [←a, functor.map_comp, category.assoc, ←functor.comp_map, c.w] at z,
rw z, },
{ rw [←functor.map_comp_assoc], },
end } },
map := λ X Y f,
{ hom := f.hom, } }
@[simp]
lemma colimit_cocone_comp_aux (s : cocone (F ⋙ G)) (j : C) :
G.map (hom_to_lift F (F.obj j)) ≫ s.ι.app (lift F (F.obj j)) =
s.ι.app j :=
begin
-- This point is that this would be true if we took `lift (F.obj j)` to just be `j`
-- and `hom_to_lift (F.obj j)` to be `𝟙 (F.obj j)`.
apply induction F (λ X k, G.map k ≫ s.ι.app X = (s.ι.app j : _)),
{ intros j₁ j₂ k₁ k₂ f w h, rw ←w, rw ← s.w f at h, simpa using h, },
{ intros j₁ j₂ k₁ k₂ f w h, rw ←w at h, rw ← s.w f, simpa using h, },
{ exact s.w (𝟙 _), },
end
variables {H : Dᵒᵖ ⥤ E}
/-- An auxilliary construction for `extend_cone`, moving `op` around. -/
@[simps]
def extend_cone_cone_to_cocone {F : C ⥤ D} {H : Dᵒᵖ ⥤ E} (c : cone (F.op ⋙ H)) :
cocone (F ⋙ H.right_op) :=
{ X := op c.X,
ι :=
{ app := λ j, (c.π.app (op j)).op,
naturality' := λ j j' f,
begin apply has_hom.hom.unop_inj, dsimp, simp only [category.id_comp], exact c.w f.op, end }}
/-- An auxilliary construction for `extend_cone`, moving `op` around. -/
@[simps]
def extend_cone_cocone_to_cone (c : cocone H.right_op) : cone H :=
{ X := unop c.X,
π :=
{ app := λ j, (c.ι.app (unop j)).unop,
naturality' := λ j j' f,
begin
apply has_hom.hom.op_inj,
dsimp,
simp only [category.comp_id],
exact (c.w f.unop).symm,
end }}
/--
Given a cone over `F.op ⋙ H`, we can construct a `cone H` with the same cone point.
-/
@[simps]
def extend_cone : cone (F.op ⋙ H) ⥤ cone H :=
{ obj := λ c, extend_cone_cocone_to_cone (extend_cocone.obj (extend_cone_cone_to_cocone c)),
map := λ X Y f, { hom := f.hom, } }
@[simp]
lemma limit_cone_comp_aux (s : cone (F.op ⋙ H)) (j : Cᵒᵖ) :
s.π.app (op (lift F (F.obj (unop j)))) ≫ H.map (hom_to_lift F (F.obj (unop j))).op =
s.π.app j :=
begin
apply has_hom.hom.op_inj,
exact colimit_cocone_comp_aux (extend_cone_cone_to_cocone s) (unop j)
end
variables (F G H)
/--
If `F` is cofinal,
the category of cocones on `F ⋙ G` is equivalent to the category of cocones on `G`,
for any `G : D ⥤ E`.
-/
@[simps]
def cocones_equiv : cocone (F ⋙ G) ≌ cocone G :=
{ functor := extend_cocone,
inverse := cocones.whiskering F,
unit_iso := nat_iso.of_components (λ c, cocones.ext (iso.refl _) (by tidy)) (by tidy),
counit_iso := nat_iso.of_components (λ c, cocones.ext (iso.refl _) (by tidy)) (by tidy), }.
/--
If `F` is cofinal,
the category of cones on `F.op ⋙ H` is equivalent to the category of cones on `H`,
for any `H : Dᵒᵖ ⥤ E`.
-/
@[simps]
def cones_equiv : cone (F.op ⋙ H) ≌ cone H :=
{ functor := extend_cone,
inverse := cones.whiskering F.op,
unit_iso := nat_iso.of_components (λ c, cones.ext (iso.refl _) (by tidy)) (by tidy),
counit_iso := nat_iso.of_components (λ c, cones.ext (iso.refl _) (by tidy)) (by tidy), }.
-- We could have done this purely formally in terms of `cocones_equiv`,
-- without having defined `extend_cone` at all,
-- but it comes at the cost of moving a *lot* of opposites around:
-- (((cones.functoriality_equivalence _ (op_op_equivalence E)).symm.trans
-- ((((cocone_equivalence_op_cone_op _).symm.trans
-- (cocones_equiv F (unop_unop _ ⋙ H.op))).trans
-- (cocone_equivalence_op_cone_op _)).unop)).trans
-- (cones.functoriality_equivalence _ (op_op_equivalence E))).trans
-- (cones.postcompose_equivalence (nat_iso.of_components (λ X, iso.refl _) (by tidy) :
-- H ≅ (unop_unop D ⋙ H.op).op ⋙ (op_op_equivalence E).functor)).symm
variables {G H}
/--
When `F : C ⥤ D` is cofinal, and `t : cocone G` for some `G : D ⥤ E`,
`t.whisker F` is a colimit cocone exactly when `t` is.
-/
def is_colimit_whisker_equiv (t : cocone G) : is_colimit (t.whisker F) ≃ is_colimit t :=
is_colimit.of_cocone_equiv (cocones_equiv F G).symm
/--
When `F : C ⥤ D` is cofinal, and `t : cone H` for some `H : Dᵒᵖ ⥤ E`,
`t.whisker F.op` is a limit cone exactly when `t` is.
-/
def is_limit_whisker_equiv (t : cone H) : is_limit (t.whisker F.op) ≃ is_limit t :=
is_limit.of_cone_equiv (cones_equiv F H).symm
/--
When `F` is cofinal, and `t : cocone (F ⋙ G)`,
`extend_cocone.obj t` is a colimit coconne exactly when `t` is.
-/
def is_colimit_extend_cocone_equiv (t : cocone (F ⋙ G)) :
is_colimit (extend_cocone.obj t) ≃ is_colimit t :=
is_colimit.of_cocone_equiv (cocones_equiv F G)
/--
When `F` is cofinal, and `t : cone (F.op ⋙ H)`,
`extend_cone.obj t` is a limit conne exactly when `t` is.
-/
def is_limit_extend_cone_equiv (t : cone (F.op ⋙ H)) :
is_limit (extend_cone.obj t) ≃ is_limit t :=
is_limit.of_cone_equiv (cones_equiv F H)
/-- Given a colimit cocone over `G : D ⥤ E` we can construct a colimit cocone over `F ⋙ G`. -/
@[simps]
def colimit_cocone_comp (t : colimit_cocone G) :
colimit_cocone (F ⋙ G) :=
{ cocone := _,
is_colimit := (is_colimit_whisker_equiv F _).symm (t.is_colimit) }
/-- Given a limit cone over `H : Dᵒᵖ ⥤ E` we can construct a limit cone over `F.op ⋙ H`. -/
@[simps]
def limit_cone_comp (t : limit_cone H) :
limit_cone (F.op ⋙ H) :=
{ cone := _,
is_limit := (is_limit_whisker_equiv F _).symm (t.is_limit) }
@[priority 100]
instance comp_has_colimit [has_colimit G] :
has_colimit (F ⋙ G) :=
has_colimit.mk (colimit_cocone_comp F (get_colimit_cocone G))
@[priority 100]
instance comp_has_limit [has_limit H] :
has_limit (F.op ⋙ H) :=
has_limit.mk (limit_cone_comp F (get_limit_cone H))
lemma colimit_pre_is_iso_aux {t : cocone G} (P : is_colimit t) :
((is_colimit_whisker_equiv F _).symm P).desc (t.whisker F) = 𝟙 t.X :=
begin
dsimp [is_colimit_whisker_equiv],
apply P.hom_ext,
intro j,
dsimp, simp, dsimp, simp, -- See library note [dsimp, simp].
end
instance colimit_pre_is_iso [has_colimit G] :
is_iso (colimit.pre G F) :=
begin
rw colimit.pre_eq (colimit_cocone_comp F (get_colimit_cocone G)) (get_colimit_cocone G),
erw colimit_pre_is_iso_aux,
dsimp,
apply_instance,
end
lemma limit_pre_is_iso_aux {t : cone H} (P : is_limit t) :
((is_limit_whisker_equiv F _).symm P).lift (t.whisker F.op) = 𝟙 t.X :=
begin
dsimp [is_limit_whisker_equiv],
apply P.hom_ext,
intro j,
simp, refl,
end
instance limit_pre_is_iso [has_limit H] :
is_iso (limit.pre H F.op) :=
begin
rw limit.pre_eq (limit_cone_comp F (get_limit_cone H)) (get_limit_cone H),
erw limit_pre_is_iso_aux,
dsimp,
apply_instance,
end
section
variables (G H)
/--
When `F : C ⥤ D` is cofinal, and `G : D ⥤ E` has a colimit, then `F ⋙ G` has a colimit also and
`colimit (F ⋙ G) ≅ colimit G`
https://stacks.math.columbia.edu/tag/04E7
-/
def colimit_iso [has_colimit G] : colimit (F ⋙ G) ≅ colimit G := as_iso (colimit.pre G F)
/--
When `F : C ⥤ D` is cofinal, and `H : Dᵒᵖ ⥤ E` has a limit, then `F.op ⋙ H` has a limit also and
`limit (F.op ⋙ H) ≅ limit H`
https://stacks.math.columbia.edu/tag/04E7
-/
def limit_iso [has_limit H] : limit (F.op ⋙ H) ≅ limit H := (as_iso (limit.pre H F.op)).symm
end
/-- Given a colimit cocone over `F ⋙ G` we can construct a colimit cocone over `G`. -/
@[simps]
def colimit_cocone_of_comp (t : colimit_cocone (F ⋙ G)) :
colimit_cocone G :=
{ cocone := extend_cocone.obj t.cocone,
is_colimit := (is_colimit_extend_cocone_equiv F _).symm (t.is_colimit), }
/-- Given a limit cone over `F.op ⋙ H` we can construct a limit cone over `H`. -/
@[simps]
def limit_cone_of_comp (t : limit_cone (F.op ⋙ H)) :
limit_cone H :=
{ cone := extend_cone.obj t.cone,
is_limit := (is_limit_extend_cone_equiv F _).symm (t.is_limit), }
/--
When `F` is cofinal, and `F ⋙ G` has a colimit, then `G` has a colimit also.
We can't make this an instance, because `F` is not determined by the goal.
(Even if this weren't a problem, it would cause a loop with `comp_has_colimit`.)
-/
lemma has_colimit_of_comp [has_colimit (F ⋙ G)] :
has_colimit G :=
has_colimit.mk (colimit_cocone_of_comp F (get_colimit_cocone (F ⋙ G)))
/--
When `F` is cofinal, and `F.op ⋙ H` has a limit, then `H` has a limit also.
We can't make this an instance, because `F` is not determined by the goal.
(Even if this weren't a problem, it would cause a loop with `comp_has_limit`.)
-/
lemma has_limit_of_comp [has_limit (F.op ⋙ H)] :
has_limit H :=
has_limit.mk (limit_cone_of_comp F (get_limit_cone (F.op ⋙ H)))
section
local attribute [instance] has_colimit_of_comp has_limit_of_comp
/--
When `F` is cofinal, and `F ⋙ G` has a colimit, then `G` has a colimit also and
`colimit (F ⋙ G) ≅ colimit G`
https://stacks.math.columbia.edu/tag/04E7
-/
def colimit_iso' [has_colimit (F ⋙ G)] : colimit (F ⋙ G) ≅ colimit G := as_iso (colimit.pre G F)
/--
When `F` is cofinal, and `F.op ⋙ H` has a limit, then `H` has a limit also and
`limit (F.op ⋙ H) ≅ limit H`
https://stacks.math.columbia.edu/tag/04E7
-/
def limit_iso' [has_limit (F.op ⋙ H)] : limit (F.op ⋙ H) ≅ limit H :=
(as_iso (limit.pre H F.op)).symm
end
/--
If the universal morphism `colimit (F ⋙ coyoneda.obj (op d)) ⟶ colimit (coyoneda.obj (op d))`
is an isomorphism (as it always is when `F` is cofinal),
then `colimit (F ⋙ coyoneda.obj (op d)) ≅ punit`
(simply because `colimit (coyoneda.obj (op d)) ≅ punit`).
-/
def colimit_comp_coyoneda_iso (d : D) [is_iso (colimit.pre (coyoneda.obj (op d)) F)] :
colimit (F ⋙ coyoneda.obj (op d)) ≅ punit :=
as_iso (colimit.pre (coyoneda.obj (op d)) F) ≪≫ coyoneda.colimit_coyoneda_iso (op d)
lemma zigzag_of_eqv_gen_quot_rel {F : C ⥤ D} {d : D} {f₁ f₂ : Σ X, d ⟶ F.obj X}
(t : eqv_gen (types.quot.rel (F ⋙ coyoneda.obj (op d))) f₁ f₂) :
zigzag (structured_arrow.mk f₁.2) (structured_arrow.mk f₂.2) :=
begin
induction t,
case eqv_gen.rel : x y r
{ obtain ⟨f, w⟩ := r,
fconstructor,
swap 2, fconstructor,
left, fsplit,
exact { right := f, } },
case eqv_gen.refl
{ fconstructor, },
case eqv_gen.symm : x y h ih
{ apply zigzag_symmetric,
exact ih, },
case eqv_gen.trans : x y z h₁ h₂ ih₁ ih₂
{ apply relation.refl_trans_gen.trans,
exact ih₁, exact ih₂, }
end
/--
If `colimit (F ⋙ coyoneda.obj (op d)) ≅ punit` for all `d : D`, then `F` is cofinal.
-/
lemma cofinal_of_colimit_comp_coyoneda_iso_punit
(I : Π d, colimit (F ⋙ coyoneda.obj (op d)) ≅ punit) : cofinal F :=
⟨λ d, begin
haveI : nonempty (structured_arrow d F) := by
{ have := (I d).inv punit.star,
obtain ⟨j, y, rfl⟩ := limits.types.jointly_surjective' this,
exact ⟨structured_arrow.mk y⟩, },
apply zigzag_is_connected,
rintros ⟨⟨⟩,X₁,f₁⟩ ⟨⟨⟩,X₂,f₂⟩,
dsimp at *,
let y₁ := colimit.ι (F ⋙ coyoneda.obj (op d)) X₁ f₁,
let y₂ := colimit.ι (F ⋙ coyoneda.obj (op d)) X₂ f₂,
have e : y₁ = y₂,
{ apply (I d).to_equiv.injective, ext, },
have t := types.colimit_eq e,
clear e y₁ y₂,
exact zigzag_of_eqv_gen_quot_rel t,
end⟩
end cofinal
end category_theory
|
5e5cedf8d55782fb91c74507aa1c14a9ee46f6ab
|
35677d2df3f081738fa6b08138e03ee36bc33cad
|
/src/data/padics/hensel.lean
|
78095015831dc5dbdf920ba43dc7f7b4e4c97fe6
|
[
"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
| 21,453
|
lean
|
/-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
-/
import data.padics.padic_integers data.polynomial topology.metric_space.cau_seq_filter
import analysis.specific_limits topology.algebra.polynomial
/-!
# Hensel's lemma on ℤ_p
This file proves Hensel's lemma on ℤ_p, roughly following Keith Conrad's writeup:
<http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf>
Hensel's lemma gives a simple condition for the existence of a root of a polynomial.
The proof and motivation are described in the paper
[R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019].
## References
* <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf>
* [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]
* <https://en.wikipedia.org/wiki/Hensel%27s_lemma>
## Tags
p-adic, p adic, padic, p-adic integer
-/
noncomputable theory
open_locale classical topological_space
-- We begin with some general lemmas that are used below in the computation.
lemma padic_polynomial_dist {p : ℕ} [p.prime] (F : polynomial ℤ_[p]) (x y : ℤ_[p]) :
∥F.eval x - F.eval y∥ ≤ ∥x - y∥ :=
let ⟨z, hz⟩ := F.eval_sub_factor x y in calc
∥F.eval x - F.eval y∥ = ∥z∥ * ∥x - y∥ : by simp [hz]
... ≤ 1 * ∥x - y∥ : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _)
... = ∥x - y∥ : by simp
open filter metric
private lemma comp_tendsto_lim {p : ℕ} [p.prime] {F : polynomial ℤ_[p]} (ncs : cau_seq ℤ_[p] norm) :
tendsto (λ i, F.eval (ncs i)) at_top (𝓝 (F.eval ncs.lim)) :=
(F.continuous_eval.tendsto _).comp ncs.tendsto_limit
section
parameters {p : ℕ} [nat.prime p] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} {a : ℤ_[p]}
(ncs_der_val : ∀ n, ∥F.derivative.eval (ncs n)∥ = ∥F.derivative.eval a∥)
include ncs_der_val
private lemma ncs_tendsto_const :
tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (𝓝 ∥F.derivative.eval a∥) :=
by convert tendsto_const_nhds; ext; rw ncs_der_val
private lemma ncs_tendsto_lim :
tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (𝓝 (∥F.derivative.eval ncs.lim∥)) :=
tendsto.comp (continuous_iff_continuous_at.1 continuous_norm _) (comp_tendsto_lim _)
private lemma norm_deriv_eq : ∥F.derivative.eval ncs.lim∥ = ∥F.derivative.eval a∥ :=
tendsto_nhds_unique at_top_ne_bot ncs_tendsto_lim ncs_tendsto_const
end
section
parameters {p : ℕ} [nat.prime p] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]}
(hnorm : tendsto (λ i, ∥F.eval (ncs i)∥) at_top (𝓝 0))
include hnorm
private lemma tendsto_zero_of_norm_tendsto_zero : tendsto (λ i, F.eval (ncs i)) at_top (𝓝 0) :=
tendsto_iff_norm_tendsto_zero.2 (by simpa using hnorm)
lemma limit_zero_of_norm_tendsto_zero : F.eval ncs.lim = 0 :=
tendsto_nhds_unique at_top_ne_bot (comp_tendsto_lim _) tendsto_zero_of_norm_tendsto_zero
end
section hensel
open nat
parameters {p : ℕ} [nat.prime p] {F : polynomial ℤ_[p]} {a : ℤ_[p]}
(hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) (hnsol : F.eval a ≠ 0)
include hnorm
/-- `T` is an auxiliary value that is used to control the behavior of the polynomial `F`. -/
private def T : ℝ := ∥(F.eval a).val / ((F.derivative.eval a).val)^2∥
private lemma deriv_sq_norm_pos : 0 < ∥F.derivative.eval a∥ ^ 2 :=
lt_of_le_of_lt (norm_nonneg _) hnorm
private lemma deriv_sq_norm_ne_zero : ∥F.derivative.eval a∥^2 ≠ 0 := ne_of_gt deriv_sq_norm_pos
private lemma deriv_norm_ne_zero : ∥F.derivative.eval a∥ ≠ 0 :=
λ h, deriv_sq_norm_ne_zero (by simp [*, _root_.pow_two])
private lemma deriv_norm_pos : 0 < ∥F.derivative.eval a∥ :=
lt_of_le_of_ne (norm_nonneg _) (ne.symm deriv_norm_ne_zero)
private lemma deriv_ne_zero : F.derivative.eval a ≠ 0 := mt norm_eq_zero.2 deriv_norm_ne_zero
private lemma T_def : T = ∥F.eval a∥ / ∥F.derivative.eval a∥^2 :=
calc T = ∥(F.eval a).val∥ / ∥((F.derivative.eval a).val)^2∥ : normed_field.norm_div _ _
... = ∥F.eval a∥ / ∥(F.derivative.eval a)^2∥ : by simp [norm, padic_norm_z]
... = ∥F.eval a∥ / ∥(F.derivative.eval a)∥^2 : by simp [pow, monoid.pow]
private lemma T_lt_one : T < 1 :=
let h := (div_lt_one_iff_lt deriv_sq_norm_pos).2 hnorm in
by rw T_def; apply h
private lemma T_pow {n : ℕ} (hn : n > 0) : T ^ n < 1 :=
have T ^ n ≤ T ^ 1, from pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) (succ_le_of_lt hn),
lt_of_le_of_lt (by simpa) T_lt_one
private lemma T_pow' (n : ℕ) : T ^ (2 ^ n) < 1 := (T_pow (nat.pow_pos (by norm_num) _))
private lemma T_pow_nonneg (n : ℕ) : T ^ n ≥ 0 := pow_nonneg (norm_nonneg _) _
/-- We will construct a sequence of elements of ℤ_p satisfying successive values of `ih`. -/
private def ih (n : ℕ) (z : ℤ_[p]) : Prop :=
∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∥F.eval z∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n)
private lemma ih_0 : ih 0 a :=
⟨ rfl, by simp [T_def, mul_div_cancel' _ (ne_of_gt (deriv_sq_norm_pos hnorm))] ⟩
private lemma calc_norm_le_one {n : ℕ} {z : ℤ_[p]} (hz : ih n z) :
∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1 :=
calc ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥
= ∥(↑(F.eval z) : ℚ_[p])∥ / ∥(↑(F.derivative.eval z) : ℚ_[p])∥ : normed_field.norm_div _ _
... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : by simp [hz.1]
... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ :
(div_le_div_right deriv_norm_pos).2 hz.2
... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _
... ≤ 1 : mul_le_one (padic_norm_z.le_one _) (T_pow_nonneg _) (le_of_lt (T_pow' _))
private lemma calc_deriv_dist {z z' z1 : ℤ_[p]} (hz' : z' = z - z1)
(hz1 : ∥z1∥ = ∥F.eval z∥ / ∥F.derivative.eval a∥) {n} (hz : ih n z) :
∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥ :=
calc
∥F.derivative.eval z' - F.derivative.eval z∥
≤ ∥z' - z∥ : padic_polynomial_dist _ _ _
... = ∥z1∥ : by simp [sub_eq_add_neg, hz']
... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : hz1
... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 hz.2
... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel deriv_norm_ne_zero _
... < ∥F.derivative.eval a∥ : (mul_lt_iff_lt_one_right deriv_norm_pos).2 (T_pow (pow_pos (by norm_num) _))
private def calc_eval_z' {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) {n} (hz : ih n z)
(h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) :
{q : ℤ_[p] // F.eval z' = q * z1^2} :=
have hdzne' : (↑(F.derivative.eval z) : ℚ_[p]) ≠ 0, from
have hdzne : F.derivative.eval z ≠ 0,
from mt norm_eq_zero.2 (by rw hz.1; apply deriv_norm_ne_zero; assumption),
λ h, hdzne $ subtype.ext.2 h,
let ⟨q, hq⟩ := F.binom_expansion z (-z1) in
have ∥(↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)) : ℚ_[p])∥ ≤ 1,
by {rw padic_norm_e.mul, apply mul_le_one, apply padic_norm_z.le_one, apply norm_nonneg, apply h1},
have F.derivative.eval z * (-z1) = -F.eval z, from calc
F.derivative.eval z * (-z1)
= (F.derivative.eval z) * -⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩ : by rw [hzeq]
... = -((F.derivative.eval z) * ⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩) : by simp
... = -(⟨↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)), this⟩) : subtype.ext.2 $ by simp
... = -(F.eval z) : by simp [mul_div_cancel' _ hdzne'],
have heq : F.eval z' = q * z1^2, by simpa [this, hz'] using hq,
⟨q, heq⟩
private def calc_eval_z'_norm {z z' z1 : ℤ_[p]} {n} (hz : ih n z) {q}
(heq : F.eval z' = q * z1^2) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1)
(hzeq : z1 = ⟨_, h1⟩) : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)) :=
calc ∥F.eval z'∥
= ∥q∥ * ∥z1∥^2 : by simp [heq]
... ≤ 1 * ∥z1∥^2 : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (pow_nonneg (norm_nonneg _) _)
... = ∥F.eval z∥^2 / ∥F.derivative.eval a∥^2 :
by simp [hzeq, hz.1, div_pow]
... ≤ (∥F.derivative.eval a∥^2 * T^(2^n))^2 / ∥F.derivative.eval a∥^2 :
(div_le_div_right deriv_sq_norm_pos).2 (pow_le_pow_of_le_left (norm_nonneg _) hz.2 _)
... = (∥F.derivative.eval a∥^2)^2 * (T^(2^n))^2 / ∥F.derivative.eval a∥^2 : by simp only [_root_.mul_pow]
... = ∥F.derivative.eval a∥^2 * (T^(2^n))^2 : div_sq_cancel deriv_sq_norm_ne_zero _
... = ∥F.derivative.eval a∥^2 * T^(2^(n + 1)) : by rw [←pow_mul]; refl
set_option eqn_compiler.zeta true
/-- Given `z : ℤ_[p]` satisfying `ih n z`, construct `z' : ℤ_[p]` satisfying `ih (n+1) z'`. We need
the hypothesis `ih n z`, since otherwise `z'` is not necessarily an integer. -/
private def ih_n {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : {z' : ℤ_[p] // ih (n+1) z'} :=
have h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1, from calc_norm_le_one hz,
let z1 : ℤ_[p] := ⟨_, h1⟩,
z' : ℤ_[p] := z - z1 in
⟨ z',
have hdist : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥,
from calc_deriv_dist rfl (by simp [z1, hz.1]) hz,
have hfeq : ∥F.derivative.eval z'∥ = ∥F.derivative.eval a∥,
begin
rw [sub_eq_add_neg, ← hz.1, ←norm_neg (F.derivative.eval z)] at hdist,
have := padic_norm_z.eq_of_norm_add_lt_right hdist,
rwa [norm_neg, hz.1] at this
end,
let ⟨q, heq⟩ := calc_eval_z' rfl hz h1 rfl in
have hnle : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)),
from calc_eval_z'_norm hz heq h1 rfl,
⟨hfeq, hnle⟩⟩
set_option eqn_compiler.zeta false
-- why doesn't "noncomputable theory" stick here?
private noncomputable def newton_seq_aux : Π n : ℕ, {z : ℤ_[p] // ih n z}
| 0 := ⟨a, ih_0⟩
| (k+1) := ih_n (newton_seq_aux k).2
private def newton_seq (n : ℕ) : ℤ_[p] := (newton_seq_aux n).1
private lemma newton_seq_deriv_norm (n : ℕ) :
∥F.derivative.eval (newton_seq n)∥ = ∥F.derivative.eval a∥ :=
(newton_seq_aux n).2.1
private lemma newton_seq_norm_le (n : ℕ) :
∥F.eval (newton_seq n)∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) :=
(newton_seq_aux n).2.2
private lemma newton_seq_norm_eq (n : ℕ) :
∥newton_seq (n+1) - newton_seq n∥ = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ :=
by induction n; simp [sub_eq_add_neg, add_left_comm, newton_seq, newton_seq_aux, ih_n]
private lemma newton_seq_succ_dist (n : ℕ) :
∥newton_seq (n+1) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) :=
calc ∥newton_seq (n+1) - newton_seq n∥
= ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ : newton_seq_norm_eq _
... = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval a∥ : by rw newton_seq_deriv_norm
... ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) / ∥F.derivative.eval a∥ :
(div_le_div_right deriv_norm_pos).2 (newton_seq_norm_le _)
... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _
include hnsol
private lemma T_pos : T > 0 :=
begin
rw T_def,
exact div_pos_of_pos_of_pos (norm_pos_iff.2 hnsol) (deriv_sq_norm_pos hnorm)
end
private lemma newton_seq_succ_dist_weak (n : ℕ) :
∥newton_seq (n+2) - newton_seq (n+1)∥ < ∥F.eval a∥ / ∥F.derivative.eval a∥ :=
have 2 ≤ 2^(n+1),
from have _, from pow_le_pow (by norm_num : 1 ≤ 2) (nat.le_add_left _ _ : 1 ≤ n + 1),
by simpa using this,
calc ∥newton_seq (n+2) - newton_seq (n+1)∥
≤ ∥F.derivative.eval a∥ * T^(2^(n+1)) : newton_seq_succ_dist _
... ≤ ∥F.derivative.eval a∥ * T^2 : mul_le_mul_of_nonneg_left
(pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this)
(norm_nonneg _)
... < ∥F.derivative.eval a∥ * T^1 : mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_one T_pos T_lt_one (by norm_num))
deriv_norm_pos
... = ∥F.eval a∥ / ∥F.derivative.eval a∥ :
begin
rw [T, _root_.pow_two, _root_.pow_one, normed_field.norm_div, ←mul_div_assoc, padic_norm_e.mul],
apply mul_div_mul_left,
apply deriv_norm_ne_zero; assumption
end
private lemma newton_seq_dist_aux (n : ℕ) :
∀ k : ℕ, ∥newton_seq (n + k) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n)
| 0 := begin simp, apply mul_nonneg, {apply norm_nonneg}, {apply T_pow_nonneg} end
| (k+1) :=
have 2^n ≤ 2^(n+k),
by {rw [←nat.pow_eq_pow, ←nat.pow_eq_pow], apply pow_le_pow, norm_num, apply nat.le_add_right},
calc
∥newton_seq (n + (k + 1)) - newton_seq n∥
= ∥newton_seq ((n + k) + 1) - newton_seq n∥ : by simp
... = ∥(newton_seq ((n + k) + 1) - newton_seq (n+k)) + (newton_seq (n+k) - newton_seq n)∥ : by rw ←sub_add_sub_cancel
... ≤ max (∥newton_seq ((n + k) + 1) - newton_seq (n+k)∥) (∥newton_seq (n+k) - newton_seq n∥) : padic_norm_z.nonarchimedean _ _
... ≤ max (∥F.derivative.eval a∥ * T^(2^((n + k)))) (∥F.derivative.eval a∥ * T^(2^n)) :
max_le_max (newton_seq_succ_dist _) (newton_seq_dist_aux _)
... = ∥F.derivative.eval a∥ * T^(2^n) :
max_eq_right $ mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _)
private lemma newton_seq_dist {n k : ℕ} (hnk : n ≤ k) :
∥newton_seq k - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) :=
have hex : ∃ m, k = n + m, from exists_eq_add_of_le hnk,
let ⟨_, hex'⟩ := hex in
by rw hex'; apply newton_seq_dist_aux; assumption
private lemma newton_seq_dist_to_a : ∀ n : ℕ, 0 < n → ∥newton_seq n - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥
| 1 h := by simp [sub_eq_add_neg, newton_seq, newton_seq_aux, ih_n]; apply normed_field.norm_div
| (k+2) h :=
have hlt : ∥newton_seq (k+2) - newton_seq (k+1)∥ < ∥newton_seq (k+1) - a∥,
by rw newton_seq_dist_to_a (k+1) (succ_pos _); apply newton_seq_succ_dist_weak; assumption,
have hne' : ∥newton_seq (k + 2) - newton_seq (k+1)∥ ≠ ∥newton_seq (k+1) - a∥, from ne_of_lt hlt,
calc ∥newton_seq (k + 2) - a∥
= ∥(newton_seq (k + 2) - newton_seq (k+1)) + (newton_seq (k+1) - a)∥ : by rw ←sub_add_sub_cancel
... = max (∥newton_seq (k + 2) - newton_seq (k+1)∥) (∥newton_seq (k+1) - a∥) : padic_norm_z.add_eq_max_of_ne hne'
... = ∥newton_seq (k+1) - a∥ : max_eq_right_of_lt hlt
... = ∥polynomial.eval a F∥ / ∥polynomial.eval a (polynomial.derivative F)∥ : newton_seq_dist_to_a (k+1) (succ_pos _)
private lemma bound' : tendsto (λ n : ℕ, ∥F.derivative.eval a∥ * T^(2^n)) at_top (𝓝 0) :=
begin
rw ←mul_zero (∥F.derivative.eval a∥),
exact tendsto_const_nhds.mul
(tendsto.comp
(tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) (T_lt_one hnorm))
(tendsto_pow_at_top_at_top_of_gt_1_nat (by norm_num)))
end
private lemma bound : ∀ {ε}, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → ∥F.derivative.eval a∥ * T^(2^n) < ε :=
have mtn : ∀ n : ℕ, ∥polynomial.eval a (polynomial.derivative F)∥ * T ^ (2 ^ n) ≥ 0,
from λ n, mul_nonneg (norm_nonneg _) (T_pow_nonneg _),
begin
have := bound' hnorm hnsol,
simp [tendsto, nhds] at this,
intros ε hε,
cases this (ball 0 ε) (mem_ball_self hε) (is_open_ball) with N hN,
existsi N, intros n hn,
simpa [normed_field.norm_mul, real.norm_eq_abs, abs_of_nonneg (mtn n)] using hN _ hn
end
private lemma bound'_sq : tendsto (λ n : ℕ, ∥F.derivative.eval a∥^2 * T^(2^n)) at_top (𝓝 0) :=
begin
rw [←mul_zero (∥F.derivative.eval a∥), _root_.pow_two],
simp only [mul_assoc],
apply tendsto.mul,
{ apply tendsto_const_nhds },
{ apply bound', assumption }
end
private theorem newton_seq_is_cauchy : is_cau_seq norm newton_seq :=
begin
intros ε hε,
cases bound hnorm hnsol hε with N hN,
existsi N,
intros j hj,
apply lt_of_le_of_lt,
{ apply newton_seq_dist _ _ hj, assumption },
{ apply hN, apply le_refl }
end
private def newton_cau_seq : cau_seq ℤ_[p] norm := ⟨_, newton_seq_is_cauchy⟩
private def soln : ℤ_[p] := newton_cau_seq.lim
private lemma soln_spec {ε : ℝ} (hε : ε > 0) :
∃ (N : ℕ), ∀ {i : ℕ}, i ≥ N → ∥soln - newton_cau_seq i∥ < ε :=
setoid.symm (cau_seq.equiv_lim newton_cau_seq) _ hε
private lemma soln_deriv_norm : ∥F.derivative.eval soln∥ = ∥F.derivative.eval a∥ :=
norm_deriv_eq newton_seq_deriv_norm
private lemma newton_seq_norm_tendsto_zero : tendsto (λ i, ∥F.eval (newton_cau_seq i)∥) at_top (𝓝 0) :=
squeeze_zero (λ _, norm_nonneg _) newton_seq_norm_le bound'_sq
private lemma newton_seq_dist_tendsto :
tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (𝓝 (∥F.eval a∥ / ∥F.derivative.eval a∥)) :=
tendsto.congr'
(suffices ∃ k, ∀ n ≥ k, ∥F.eval a∥ / ∥F.derivative.eval a∥ = ∥newton_cau_seq n - a∥, by simpa,
⟨1, λ _ hx, (newton_seq_dist_to_a _ hx).symm⟩)
(tendsto_const_nhds)
private lemma newton_seq_dist_tendsto' :
tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (𝓝 ∥soln - a∥) :=
(continuous_norm.tendsto _).comp (newton_cau_seq.tendsto_limit.sub tendsto_const_nhds)
private lemma soln_dist_to_a : ∥soln - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ :=
tendsto_nhds_unique at_top_ne_bot newton_seq_dist_tendsto' newton_seq_dist_tendsto
private lemma soln_dist_to_a_lt_deriv : ∥soln - a∥ < ∥F.derivative.eval a∥ :=
begin
rw soln_dist_to_a,
apply div_lt_of_mul_lt_of_pos,
{ apply deriv_norm_pos; assumption },
{ rwa _root_.pow_two at hnorm }
end
private lemma eval_soln : F.eval soln = 0 :=
limit_zero_of_norm_tendsto_zero newton_seq_norm_tendsto_zero
private lemma soln_unique (z : ℤ_[p]) (hev : F.eval z = 0) (hnlt : ∥z - a∥ < ∥F.derivative.eval a∥) :
z = soln :=
have soln_dist : ∥z - soln∥ < ∥F.derivative.eval a∥, from calc
∥z - soln∥ = ∥(z - a) + (a - soln)∥ : by rw sub_add_sub_cancel
... ≤ max (∥z - a∥) (∥a - soln∥) : padic_norm_z.nonarchimedean _ _
... < ∥F.derivative.eval a∥ : max_lt hnlt (by rw norm_sub_rev; apply soln_dist_to_a_lt_deriv),
let h := z - soln,
⟨q, hq⟩ := F.binom_expansion soln h in
have (F.derivative.eval soln + q * h) * h = 0, from eq.symm (calc
0 = F.eval (soln + h) : by simp [hev, h]
... = F.derivative.eval soln * h + q * h^2 : by rw [hq, eval_soln, zero_add]
... = (F.derivative.eval soln + q * h) * h : by rw [_root_.pow_two, right_distrib, mul_assoc]),
have h = 0, from by_contradiction $ λ hne,
have F.derivative.eval soln + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne,
have F.derivative.eval soln = (-q) * h, by simpa using eq_neg_of_add_eq_zero this,
lt_irrefl ∥F.derivative.eval soln∥ (calc
∥F.derivative.eval soln∥ = ∥(-q) * h∥ : by rw this
... ≤ 1 * ∥h∥ : by rw [padic_norm_z.mul]; exact mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _)
... = ∥z - soln∥ : by simp [h]
... < ∥F.derivative.eval soln∥ : by rw soln_deriv_norm; apply soln_dist),
eq_of_sub_eq_zero (by rw ←this; refl)
end hensel
variables {p : ℕ} [nat.prime p] {F : polynomial ℤ_[p]} {a : ℤ_[p]}
private lemma a_soln_is_unique (ha : F.eval a = 0) (z' : ℤ_[p]) (hz' : F.eval z' = 0)
(hnormz' : ∥z' - a∥ < ∥F.derivative.eval a∥) : z' = a :=
let h := z' - a,
⟨q, hq⟩ := F.binom_expansion a h in
have (F.derivative.eval a + q * h) * h = 0, from eq.symm (calc
0 = F.eval (a + h) : show 0 = F.eval (a + (z' - a)), by rw add_comm; simp [hz']
... = F.derivative.eval a * h + q * h^2 : by rw [hq, ha, zero_add]
... = (F.derivative.eval a + q * h) * h : by rw [_root_.pow_two, right_distrib, mul_assoc]),
have h = 0, from by_contradiction $ λ hne,
have F.derivative.eval a + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne,
have F.derivative.eval a = (-q) * h, by simpa using eq_neg_of_add_eq_zero this,
lt_irrefl ∥F.derivative.eval a∥ (calc
∥F.derivative.eval a∥ = ∥q∥*∥h∥ : by simp [this]
... ≤ 1*∥h∥ : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _)
... < ∥F.derivative.eval a∥ : by simpa [h]),
eq_of_sub_eq_zero (by rw ←this; refl)
variable (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2)
include hnorm
private lemma a_is_soln (ha : F.eval a = 0) :
F.eval a = 0 ∧ ∥a - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval a∥ = ∥F.derivative.eval a∥ ∧
∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = a :=
⟨ha, by simp; apply deriv_norm_pos; apply hnorm, rfl, a_soln_is_unique ha⟩
lemma hensels_lemma : ∃ z : ℤ_[p], F.eval z = 0 ∧ ∥z - a∥ < ∥F.derivative.eval a∥ ∧
∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧
∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = z :=
if ha : F.eval a = 0 then ⟨a, a_is_soln hnorm ha⟩ else
by refine ⟨soln _ _, eval_soln _ _, soln_dist_to_a_lt_deriv _ _, soln_deriv_norm _ _, soln_unique _ _⟩;
assumption
|
4ab3b8e7367c304a408b1a43588602c1397cef9d
|
c31182a012eec69da0a1f6c05f42b0f0717d212d
|
/src/locally_constant/analysis.lean
|
54df267caaeb9564319083fe2fb0202968deacb2
|
[] |
no_license
|
Ja1941/lean-liquid
|
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
|
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
|
refs/heads/master
| 1,689,437,983,362
| 1,628,362,719,000
| 1,628,362,719,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 11,306
|
lean
|
import topology.locally_constant.algebra
import analysis.normed_space.normed_group_hom
import for_mathlib.normed_group_hom
/-!
# Analysis of locally constant maps
This file defines the normed group of locally constant maps from a compact topological
space into a normed group (with the sup norm).
## Main construction
* The instance `locally_constant.normed_group`
* `locally_constant.map_hom`: push-forward of locally constant maps as a normed group hom
* `locally_constant.comap_hom`: pull-back of locally constant maps as a normed group hom
-/
noncomputable theory
open_locale nnreal
open set
-- move this
section for_mathlib
lemma real.Sup_mul (r : ℝ) (s : set ℝ) (hr : 0 < r) :
Sup ({x | ∃ y ∈ s, r * y = x}) = r * Sup s :=
begin
by_cases hs : s.nonempty, swap,
{ rw not_nonempty_iff_eq_empty at hs, simp [hs], },
have H : set.nonempty {x : ℝ | ∃ (y : ℝ) (H : y ∈ s), r * y = x},
{ obtain ⟨x, hx⟩ := hs, from ⟨r * x, x, hx, rfl⟩, },
have aux : bdd_above {x : ℝ | ∃ (y : ℝ) (H : y ∈ s), r * y = x} ↔ bdd_above s,
{ split; rintro ⟨x, hx⟩,
{ refine ⟨x / r, λ y hy, _⟩,
rw [le_div_iff' hr],
exact hx ⟨_, hy, rfl⟩, },
{ refine ⟨r * x, _⟩, rintro _ ⟨y, hy, rfl⟩,
apply mul_le_mul_of_nonneg_left _ hr.le,
exact hx hy } },
by_cases s_bdd : bdd_above s, swap,
{ simp only [real.Sup_of_not_bdd_above s_bdd, mul_zero,
real.Sup_of_not_bdd_above ((not_iff_not_of_iff aux).mpr s_bdd)], },
apply le_antisymm,
{ apply cSup_le H,
rintro _ ⟨x, hx, rfl⟩,
exact mul_le_mul_of_nonneg_left (le_cSup s_bdd hx) hr.le },
{ rw [← le_div_iff' hr],
refine cSup_le hs _,
intros x hx,
rw le_div_iff' hr,
exact le_cSup (aux.mpr s_bdd) ⟨_, hx, rfl⟩ }
end
end for_mathlib
open set
namespace locally_constant
variables {X Y Z V V₁ V₂ V₃ : Type*} [topological_space X]
/-- The sup norm on locally constant function -/
protected def has_norm [has_norm Y] : has_norm (locally_constant X Y) :=
{ norm := λ f, ⨆ x, ∥f x∥ }
/-- The sup edist on locally constant function -/
protected def has_edist [has_edist Y] : has_edist (locally_constant X Y) :=
{ edist := λ f g, ⨆ x, edist (f x) (g x) }
/-- The sup edist on locally constant function -/
protected def has_dist [has_dist Y] : has_dist (locally_constant X Y) :=
{ dist := λ f g, ⨆ x, dist (f x) (g x) }
local attribute [instance]
locally_constant.has_norm
locally_constant.has_edist
locally_constant.has_dist
lemma edist_apply_le [has_edist Y] (f g : locally_constant X Y) (x : X) :
edist (f x) (g x) ≤ edist f g :=
le_Sup (set.mem_range_self x)
lemma norm_def [has_norm Y] (f : locally_constant X Y) : ∥f∥ = ⨆ x, ∥f x∥ := rfl
lemma edist_def [has_edist Y] (f g : locally_constant X Y) :
edist f g = ⨆ x, edist (f x) (g x) := rfl
lemma dist_def [has_dist Y] (f g : locally_constant X Y) : dist f g = ⨆ x, dist (f x) (g x) := rfl
section compact_domain
variables [compact_space X]
lemma norm_apply_le [has_norm Y] (f : locally_constant X Y) (x : X) :
∥f x∥ ≤ ∥f∥ :=
begin
refine le_cSup _ (set.mem_range_self _),
apply exists_upper_bound_image,
rw range_comp,
exact f.range_finite.image _
end
lemma exists_ub_range_dist [has_dist Y] (f g : locally_constant X Y) :
∃ x : ℝ, ∀ y : ℝ, y ∈ set.range (λ (x : X), dist (f x) (g x)) → y ≤ x :=
begin
apply exists_upper_bound_image,
simp only [← function.uncurry_apply_pair dist],
rw range_comp,
apply finite.image,
apply (f.range_finite.prod g.range_finite).subset,
apply range_pair_subset,
end
lemma dist_apply_le [has_dist Y] (f g : locally_constant X Y) (x : X) :
dist (f x) (g x) ≤ dist f g :=
le_cSup (exists_ub_range_dist _ _) (set.mem_range_self x)
-- consider giving the `edist` and the `uniform_space` explicitly
/-- The metric space on locally constant functions on a compact space, with sup distance. -/
protected def pseudo_metric_space [pseudo_metric_space Y] :
pseudo_metric_space (locally_constant X Y) :=
{ dist_self := λ f, show (⨆ x, dist (f x) (f x)) = 0,
begin
simp only [dist_self, supr],
by_cases H : nonempty X, swap,
{ rwa [set.range_eq_empty.mpr H, real.Sup_empty] },
resetI,
simp only [set.range_const, cSup_singleton]
end,
dist_comm := λ f g, show Sup _ = Sup _, by { simp only [dist_comm] },
dist_triangle :=
begin
intros f g h,
by_cases H : nonempty X, swap,
{ show Sup _ ≤ Sup _ + Sup _, simp only [set.range_eq_empty.mpr H, real.Sup_empty, add_zero] },
refine cSup_le _ _,
{ obtain ⟨x⟩ := H, exact ⟨_, set.mem_range_self x⟩ },
rintro r ⟨x, rfl⟩,
calc dist (f x) (h x) ≤ dist (f x) (g x) + dist (g x) (h x) : dist_triangle _ _ _
... ≤ dist f g + dist g h : add_le_add (dist_apply_le _ _ _) (dist_apply_le _ _ _)
end,
.. locally_constant.has_dist }
-- consider giving the `edist` and the `uniform_space` explicitly
/-- The metric space on locally constant functions on a compact space, with sup distance. -/
protected def metric_space [metric_space Y] : metric_space (locally_constant X Y) :=
{ dist_self := λ f, show (⨆ x, dist (f x) (f x)) = 0,
begin
simp only [dist_self, supr],
by_cases H : nonempty X, swap,
{ rwa [set.range_eq_empty.mpr H, real.Sup_empty] },
resetI,
simp only [set.range_const, cSup_singleton]
end,
eq_of_dist_eq_zero :=
begin
intros f g h,
ext x,
apply eq_of_dist_eq_zero,
apply le_antisymm _ dist_nonneg,
rw ← h,
exact dist_apply_le _ _ _
end,
dist_comm := λ f g, show Sup _ = Sup _, by { simp only [dist_comm] },
dist_triangle :=
begin
intros f g h,
by_cases H : nonempty X, swap,
{ show Sup _ ≤ Sup _ + Sup _, simp only [set.range_eq_empty.mpr H, real.Sup_empty, add_zero] },
refine cSup_le _ _,
{ obtain ⟨x⟩ := H, exact ⟨_, set.mem_range_self x⟩ },
rintro r ⟨x, rfl⟩,
calc dist (f x) (h x) ≤ dist (f x) (g x) + dist (g x) (h x) : dist_triangle _ _ _
... ≤ dist f g + dist g h : add_le_add (dist_apply_le _ _ _) (dist_apply_le _ _ _)
end,
.. locally_constant.has_dist }
/--
The seminormed group of locally constant functions from a compact space to a seminormed group.
-/
protected def semi_normed_group {G : Type*} [semi_normed_group G] :
semi_normed_group (locally_constant X G) :=
{ dist_eq := λ f g, show Sup _ = Sup _,
by simp only [semi_normed_group.dist_eq, locally_constant.sub_apply],
.. locally_constant.has_norm, .. locally_constant.add_comm_group,
.. locally_constant.pseudo_metric_space }
/-- The normed group of locally constant functions from a compact space to a normed group. -/
protected def normed_group {G : Type*} [normed_group G] : normed_group (locally_constant X G) :=
{ .. locally_constant.semi_normed_group,
.. locally_constant.metric_space }
local attribute [instance] locally_constant.semi_normed_group
section map_hom
variables [semi_normed_group V] [semi_normed_group V₁] [semi_normed_group V₂] [semi_normed_group V₃]
/-- Push-forward of locally constant maps under a normed group hom, as a normed
group hom between types of locally constant functions. -/
@[simps]
def map_hom (f : normed_group_hom V₁ V₂) :
normed_group_hom (locally_constant X V₁) (locally_constant X V₂) :=
{ to_fun := locally_constant.map f,
map_add' := by { intros x y, ext s, apply f.map_add' },
bound' :=
begin
obtain ⟨C, C_pos, hC⟩ := f.bound,
use C,
rintro (g : locally_constant _ _),
calc Sup (set.range (λ x, ∥f (g x)∥))
≤ Sup (set.range (λ x, C * ∥g x∥)) : _
... = C * Sup (set.range (λ x, ∥g x∥)) : _,
{ by_cases H : nonempty X, swap,
{ simp only [set.range_eq_empty.mpr H, real.Sup_empty] },
apply cSup_le,
{ obtain ⟨x⟩ := H, exact ⟨_, set.mem_range_self x⟩ },
rintro _ ⟨x, rfl⟩,
calc ∥f (g x)∥ ≤ C * ∥g x∥ : hC _
... ≤ Sup _ : le_cSup _ _,
{ apply exists_upper_bound_image,
rw [set.range_comp, set.range_comp],
exact (g.range_finite.image _).image _ },
{ exact set.mem_range_self _ } },
{ convert real.Sup_mul C _ C_pos using 2,
ext x,
simp only [set.mem_range, exists_prop, set.set_of_mem_eq, exists_exists_eq_and],
simp only [set.mem_set_of_eq] }
end }
@[simp] lemma map_hom_id :
@map_hom X _ _ _ _ _ _ (@normed_group_hom.id V _) = normed_group_hom.id _ :=
by { ext, refl }
@[simp] lemma map_hom_comp (g : normed_group_hom V₂ V₃) (f : normed_group_hom V₁ V₂) :
(@map_hom X _ _ _ _ _ _ g).comp (map_hom f) = map_hom (g.comp f) :=
by { ext, refl }
end map_hom
section comap_hom
/-!
### comapping as normed_group_hom
-/
variables [topological_space Y] [compact_space Y] [topological_space Z] [compact_space Z]
variables [semi_normed_group V]
/-- Pull-back of locally constant maps under a normed group hom, as a normed
group hom between types of locally constant functions. -/
@[simps]
def comap_hom (f : X → Y) (hf : continuous f) :
normed_group_hom (locally_constant Y V) (locally_constant X V) :=
add_monoid_hom.mk_normed_group_hom
(add_monoid_hom.mk'
(locally_constant.comap f)
(by { intros, ext, simp only [hf, add_apply, function.comp_app, coe_comap] }))
1
begin
assume g,
rw one_mul,
show Sup _ ≤ Sup _,
simp only [hf, function.comp_app, coe_comap, add_monoid_hom.mk'_apply],
by_cases hX : nonempty X, swap,
{ simp only [set.range_eq_empty.mpr hX, real.Sup_empty],
by_cases hY : nonempty Y, swap,
{ simp only [set.range_eq_empty.mpr hY, real.Sup_empty] },
obtain ⟨y⟩ := hY,
calc 0 ≤ ∥g y∥ : norm_nonneg _
... ≤ _ : _,
apply le_cSup,
{ apply exists_upper_bound_image,
rw set.range_comp,
exact g.range_finite.image _ },
{ exact set.mem_range_self _ } },
resetI,
refine cSup_le (range_nonempty _) _,
{ rintro _ ⟨x, rfl⟩,
apply le_cSup,
{ apply exists_upper_bound_image,
rw set.range_comp,
exact g.range_finite.image _ },
{ exact set.mem_range_self _ } },
end
@[simp] lemma comap_hom_id : @comap_hom X X V _ _ _ _ _ id continuous_id = normed_group_hom.id _ :=
begin
ext,
simp only [comap_id, comap_hom_apply, id.def, normed_group_hom.id_apply,
add_monoid_hom.to_fun_eq_coe, add_monoid_hom.id_apply]
end
@[simp] lemma comap_hom_comp (f : X → Y) (g : Y → Z) (hf : continuous f) (hg : continuous g) :
(@comap_hom _ _ V _ _ _ _ _ f hf).comp (comap_hom g hg) = (comap_hom (g ∘ f) (hg.comp hf)) :=
begin
ext φ x,
-- `[simps]` is producing bad lemmas... I don't know how to trick it into creating good ones
-- so we use `show` instead, to get into a defeq shape that is usable
show (comap_hom f hf) ((comap_hom g hg) φ) x = _,
simp only [hg.comp hf, hf, hg, comap_hom_apply, coe_comap]
end
lemma comap_hom_norm_noninc (f : X → Y) (hf : continuous f) :
(@comap_hom _ _ V _ _ _ _ _ f hf).norm_noninc :=
normed_group_hom.norm_noninc.norm_noninc_iff_norm_le_one.2 $
normed_group_hom.mk_normed_group_hom_norm_le _ (zero_le_one) _
end comap_hom
end compact_domain
end locally_constant
#lint- only unused_arguments def_lemma doc_blame
|
5f585abaa015650c247f6c5384b106b90b8d7b23
|
d436468d80b739ba7e06843c4d0d2070e43448e5
|
/src/category/bitraversable/lemmas.lean
|
f93a76e729baa13713acdb690f2921b5672c65c7
|
[
"Apache-2.0"
] |
permissive
|
roro47/mathlib
|
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
|
80aa7d52537571a2ca62a3fdf71c9533a09422cf
|
refs/heads/master
| 1,599,656,410,625
| 1,573,649,488,000
| 1,573,649,488,000
| 221,452,951
| 0
| 0
|
Apache-2.0
| 1,573,647,693,000
| 1,573,647,692,000
| null |
UTF-8
|
Lean
| false
| false
| 3,325
|
lean
|
/-
Copyright (c) 2019 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author(s): Simon Hudon
-/
import category.bitraversable.basic
/-!
# Bitraversable Lemmas
## Main definitions
* tfst - traverse on first functor argument
* tsnd - traverse on second functor argument
## Lemmas
Combination of
* bitraverse
* tfst
* tsnd
with the applicatives `id` and `comp`
## References
* Hackage: https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html
## Tags
traversable bitraversable functor bifunctor applicative
-/
universes u
variables {t : Type u → Type u → Type u} [bitraversable t]
variables {β : Type u}
namespace bitraversable
open functor is_lawful_applicative
variables {F G : Type u → Type u}
[applicative F] [applicative G]
/-- traverse on the first functor argument -/
@[reducible] def tfst {α α'} (f : α → F α') : t α β → F (t α' β) :=
bitraverse f pure
/-- traverse on the second functor argument -/
@[reducible] def tsnd {α α'} (f : α → F α') : t β α → F (t β α') :=
bitraverse pure f
variables [is_lawful_bitraversable t]
[is_lawful_applicative F]
[is_lawful_applicative G]
@[higher_order tfst_id]
lemma id_tfst : Π {α β} (x : t α β), tfst id.mk x = id.mk x :=
@id_bitraverse _ _ _
@[higher_order tsnd_id]
lemma id_tsnd : Π {α β} (x : t α β), tsnd id.mk x = id.mk x :=
@id_bitraverse _ _ _
@[higher_order tfst_comp_tfst]
lemma comp_tfst {α₀ α₁ α₂ β}
(f : α₀ → F α₁) (f' : α₁ → G α₂) (x : t α₀ β) :
comp.mk (tfst f' <$> tfst f x) = tfst (comp.mk ∘ map f' ∘ f) x :=
by rw ← comp_bitraverse; simp [tfst,map_comp_pure,has_pure.pure]
@[higher_order tfst_comp_tsnd]
lemma tfst_tsnd {α₀ α₁ β₀ β₁}
(f : α₀ → F α₁) (f' : β₀ → G β₁) (x : t α₀ β₀) :
comp.mk (tfst f <$> tsnd f' x) =
bitraverse (comp.mk ∘ pure ∘ f) (comp.mk ∘ map pure ∘ f') x :=
by rw ← comp_bitraverse; simp [tfst,tsnd]
@[higher_order tsnd_comp_tfst]
lemma tsnd_tfst {α₀ α₁ β₀ β₁}
(f : α₀ → F α₁) (f' : β₀ → G β₁) (x : t α₀ β₀) :
comp.mk (tsnd f' <$> tfst f x) =
bitraverse (comp.mk ∘ map pure ∘ f) (comp.mk ∘ pure ∘ f') x :=
by rw ← comp_bitraverse; simp [tfst,tsnd]
@[higher_order tsnd_comp_tsnd]
lemma comp_tsnd {α β₀ β₁ β₂}
(g : β₀ → F β₁) (g' : β₁ → G β₂) (x : t α β₀) :
comp.mk (tsnd g' <$> tsnd g x) = tsnd (comp.mk ∘ map g' ∘ g) x :=
by rw ← comp_bitraverse; simp [tsnd]; refl
open bifunctor
private lemma pure_eq_id_mk_comp_id {α} :
pure = id.mk ∘ @id α := rfl
open function
@[higher_order]
lemma tfst_eq_fst_id {α α' β} (f : α → α') (x : t α β) :
tfst (id.mk ∘ f) x = id.mk (fst f x) :=
by simp [tfst,fst,pure_eq_id_mk_comp_id,-comp.right_id,bitraverse_eq_bimap_id]
@[higher_order]
lemma tsnd_eq_snd_id {α β β'} (f : β → β') (x : t α β) :
tsnd (id.mk ∘ f) x = id.mk (snd f x) :=
by simp [tsnd,snd,pure_eq_id_mk_comp_id,-comp.right_id,bitraverse_eq_bimap_id]
attribute [functor_norm] comp_bitraverse comp_tsnd comp_tfst
tsnd_comp_tsnd tsnd_comp_tfst tfst_comp_tsnd tfst_comp_tfst
bitraverse_comp bitraverse_id_id tfst_id tsnd_id
end bitraversable
|
bd1f33ca0b66b2bfacc07f62c55eecb3d2560290
|
5ec8f5218a7c8e87dd0d70dc6b715b36d61a8d61
|
/maps.lean
|
4c12e4c07aab8f6742591e01bb2821de0803bc6a
|
[] |
no_license
|
mbrodersen/kremlin
|
f9f2f9dd77b9744fe0ffd5f70d9fa0f1f8bd8cec
|
d4665929ce9012e93a0b05fc7063b96256bab86f
|
refs/heads/master
| 1,624,057,268,130
| 1,496,957,084,000
| 1,496,957,084,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 3,749
|
lean
|
import data.hash_map .lib
namespace maps
def prev_append : pos_num → pos_num → pos_num
| pos_num.one j := j
| (pos_num.bit1 i') j := prev_append i' (pos_num.bit1 j)
| (pos_num.bit0 i') j := prev_append i' (pos_num.bit0 j)
def prev (i : pos_num) : pos_num :=
prev_append i pos_num.one
inductive PTree (A : Type) : Type
| leaf {} : PTree
| node : PTree → option A → PTree → PTree
open PTree
namespace PTree
instance {A} : has_emptyc (PTree A) := ⟨leaf⟩
def get {A : Type} : pos_num → PTree A → option A :=
by { intros i m, revert i,
induction m with l o r Il Ir; intro i, exact none,
cases i with i' i',
exact o,
exact Il i', exact Ir i' }
def get_or {A : Type} (n : pos_num) (t : PTree A) (dfl : A) : A :=
(t.get n).get_or_else dfl
def set {A : Type} : pos_num → A → PTree A → PTree A
| pos_num.one v leaf := node leaf (some v) leaf
| (pos_num.bit0 i') v leaf := node (set i' v leaf) none leaf
| (pos_num.bit1 i') v leaf := node leaf none (set i' v leaf)
| pos_num.one v (node l o r) := node l (some v) r
| (pos_num.bit0 i') v (node l o r) := node (set i' v l) o r
| (pos_num.bit1 i') v (node l o r) := node l o (set i' v r)
lemma gleaf {A} (i) : get i (leaf : PTree A) = none :=
by induction i; simp [get]
theorem gempty {A} (i) : get i (∅ : PTree A) = none := gleaf i
theorem gss {A} (i x) (m : PTree A) : get i (set i x m) = some x := sorry
theorem gso {A i j} (x : A) (m : PTree A) : i ≠ j → get i (set j x m) = get i m := sorry
theorem gsspec {A} (i j) (x : A) (m : PTree A) :
get i (set j x m) = if i = j then some x else get i m :=
by { by_cases (i = j); simp [h], rw gss, rw gso _ _ h }
theorem gsident {A} (i : pos_num) (m : PTree A) (v : A) :
get i m = some v → set i v m = m := sorry
theorem set2 {A} (i : pos_num) (m : PTree A) (v1 v2 : A) :
set i v2 (set i v1 m) = set i v2 m := sorry
def of_list {A} (l : list (pos_num × A)) : PTree A :=
l.foldl (λ m ⟨k, v⟩, set k v m) ∅
def node' {A} : PTree A → option A → PTree A → PTree A
| leaf none leaf := leaf
| l x r := node l x r
section combine
variables {A B C : Type} (f : option A → option B → option C)
def xcombine_l : PTree A → PTree C
| leaf := leaf
| (node l o r) := node' (xcombine_l l) (f o none) (xcombine_l r)
def xcombine_r : PTree B → PTree C
| leaf := leaf
| (node l o r) := node' (xcombine_r l) (f none o) (xcombine_r r)
def combine : PTree A → PTree B → PTree C
| leaf m2 := xcombine_r f m2
| m1 leaf := xcombine_l f m1
| (node l1 o1 r1) (node l2 o2 r2) := node' (combine l1 l2) (f o1 o2) (combine r1 r2)
theorem combine_commut (f g : option A → option A → option B) :
(∀ i j, f i j = g j i) →
∀ m1 m2, combine f m1 m2 = combine g m2 m1 := sorry
end combine
def xelements {A} : PTree A → pos_num → list (pos_num × A) → list (pos_num × A)
| leaf i k := k
| (node l none r) i k :=
xelements l (pos_num.bit0 i) (xelements r (pos_num.bit1 i) k)
| (node l (some x) r) i k :=
xelements l (pos_num.bit0 i)
((prev i, x) :: xelements r (pos_num.bit1 i) k)
def elements {A} (m : PTree A) := xelements m pos_num.one []
def xfold {A B} (f : B → pos_num → A → B) : pos_num → PTree A → B → B
| i leaf v := v
| i (node l none r) v :=
let v1 := xfold (pos_num.bit0 i) l v in
xfold (pos_num.bit1 i) r v1
| i (node l (some x) r) v :=
let v1 := xfold (pos_num.bit0 i) l v in
let v2 := f v1 (pos_num.pred i) x in
xfold (pos_num.bit1 i) r v2
def fold {A B} (f : B → pos_num → A → B) (m : PTree A) (v : B) :=
xfold f pos_num.one m v
def for_all {A} (m : PTree A) (f : pos_num → A → bool) : bool :=
fold (λ b x a, b && f x a) m tt
notation a `^!` b := get b a
end PTree
end maps
|
ddc880eba785b210da9f4cb0be07ba00856a3c07
|
57fdc8de88f5ea3bfde4325e6ecd13f93a274ab5
|
/data/num/basic.lean
|
ad732ad92afd203f9fb2d300e35956ae5a791757
|
[
"Apache-2.0"
] |
permissive
|
louisanu/mathlib
|
11f56f2d40dc792bc05ee2f78ea37d73e98ecbfe
|
2bd5e2159d20a8f20d04fc4d382e65eea775ed39
|
refs/heads/master
| 1,617,706,993,439
| 1,523,163,654,000
| 1,523,163,654,000
| 124,519,997
| 0
| 0
|
Apache-2.0
| 1,520,588,283,000
| 1,520,588,283,000
| null |
UTF-8
|
Lean
| false
| false
| 13,797
|
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, Mario Carneiro
Binary representation of integers using inductive types.
Note: Unlike in Coq, where this representation is preferred because of
the reliance on kernel reduction, in Lean this representation is discouraged
in favor of the "Peano" natural numbers `nat`, and the purpose of this
collection of theorems is to show the equivalence of the different approaches.
-/
import data.pnat data.bool data.vector data.bitvec
/-- The type of positive binary numbers.
13 = 1101(base 2) = bit1 (bit0 (bit1 one)) -/
inductive pos_num : Type
| one : pos_num
| bit1 : pos_num → pos_num
| bit0 : pos_num → pos_num
instance : has_one pos_num := ⟨pos_num.one⟩
instance : decidable_eq pos_num := by tactic.mk_dec_eq_instance
/-- The type of nonnegative binary numbers, using `pos_num`.
13 = 1101(base 2) = pos (bit1 (bit0 (bit1 one))) -/
inductive num : Type
| zero : num
| pos : pos_num → num
instance : has_zero num := ⟨num.zero⟩
instance : has_one num := ⟨num.pos 1⟩
instance : decidable_eq num := by tactic.mk_dec_eq_instance
/-- Representation of integers using trichotomy around zero.
13 = 1101(base 2) = pos (bit1 (bit0 (bit1 one)))
-13 = -1101(base 2) = neg (bit1 (bit0 (bit1 one))) -/
inductive znum : Type
| zero : znum
| pos : pos_num → znum
| neg : pos_num → znum
instance : has_zero znum := ⟨znum.zero⟩
instance : has_one znum := ⟨znum.pos 1⟩
instance : decidable_eq znum := by tactic.mk_dec_eq_instance
/-- See `snum`. -/
inductive nzsnum : Type
| msb : bool → nzsnum
| bit : bool → nzsnum → nzsnum
/-- Alternative representation of integers using a sign bit at the end.
The convention on sign here is to have the argument to `msb` denote
the sign of the MSB itself, with all higher bits set to the negation
of this sign. The result is interpreted in two's complement.
13 = ..0001101(base 2) = nz (bit1 (bit0 (bit1 (msb tt))))
-13 = ..1110011(base 2) = nz (bit1 (bit1 (bit0 (msb ff))))
As with `num`, a special case must be added for zero, which has no msb,
but by two's complement symmetry there is a second special case for -1.
Here the `bool` field indicates the sign of the number.
0 = ..0000000(base 2) = zero ff
-1 = ..1111111(base 2) = zero tt -/
inductive snum : Type
| zero : bool → snum
| nz : nzsnum → snum
instance : has_coe nzsnum snum := ⟨snum.nz⟩
instance : has_zero snum := ⟨snum.zero ff⟩
instance : has_one nzsnum := ⟨nzsnum.msb tt⟩
instance : has_one snum := ⟨snum.nz 1⟩
instance : decidable_eq nzsnum := by tactic.mk_dec_eq_instance
instance : decidable_eq snum := by tactic.mk_dec_eq_instance
namespace pos_num
def bit (b : bool) : pos_num → pos_num := cond b bit1 bit0
def succ : pos_num → pos_num
| 1 := bit0 one
| (bit1 n) := bit0 (succ n)
| (bit0 n) := bit1 n
def is_one : pos_num → bool
| 1 := tt
| _ := ff
protected def add : pos_num → pos_num → pos_num
| 1 b := succ b
| a 1 := succ a
| (bit0 a) (bit0 b) := bit0 (add a b)
| (bit1 a) (bit1 b) := bit0 (succ (add a b))
| (bit0 a) (bit1 b) := bit1 (add a b)
| (bit1 a) (bit0 b) := bit1 (add a b)
instance : has_add pos_num := ⟨pos_num.add⟩
def pred' : pos_num → num
| 1 := 0
| (bit0 n) := num.pos (num.cases_on (pred' n) 1 bit1)
| (bit1 n) := num.pos (bit0 n)
def pred (a : pos_num) : pos_num :=
num.cases_on (pred' a) 1 id
def size : pos_num → pos_num
| 1 := 1
| (bit0 n) := succ (size n)
| (bit1 n) := succ (size n)
protected def mul (a : pos_num) : pos_num → pos_num
| 1 := a
| (bit0 b) := bit0 (mul b)
| (bit1 b) := bit0 (mul b) + a
instance : has_mul pos_num := ⟨pos_num.mul⟩
def of_nat_succ : ℕ → pos_num
| 0 := 1
| (nat.succ n) := succ (of_nat_succ n)
def of_nat (n : ℕ) : pos_num := of_nat_succ (nat.pred n)
open ordering
def cmp : pos_num → pos_num → ordering
| 1 1 := eq
| _ 1 := gt
| 1 _ := lt
| (bit0 a) (bit0 b) := cmp a b
| (bit0 a) (bit1 b) := ordering.cases_on (cmp a b) lt lt gt
| (bit1 a) (bit0 b) := ordering.cases_on (cmp a b) lt gt gt
| (bit1 a) (bit1 b) := cmp a b
instance : has_lt pos_num := ⟨λa b, cmp a b = ordering.lt⟩
instance : has_le pos_num := ⟨λa b, ¬ b < a⟩
instance decidable_lt : @decidable_rel pos_num (<)
| a b := by dsimp [(<)]; apply_instance
instance decidable_le : @decidable_rel pos_num (≤)
| a b := by dsimp [(≤)]; apply_instance
end pos_num
section
variables {α : Type*} [has_zero α] [has_one α] [has_add α]
def cast_pos_num : pos_num → α
| 1 := 1
| (pos_num.bit0 a) := bit0 (cast_pos_num a)
| (pos_num.bit1 a) := bit1 (cast_pos_num a)
def cast_num : num → α
| 0 := 0
| (num.pos p) := cast_pos_num p
@[priority 0] instance pos_num_coe : has_coe pos_num α := ⟨cast_pos_num⟩
@[priority 0] instance num_nat_coe : has_coe num α := ⟨cast_num⟩
end
namespace num
open pos_num
def succ' : num → pos_num
| 0 := 1
| (pos p) := succ p
def succ (n : num) : num := pos (succ' n)
protected def add : num → num → num
| 0 a := a
| b 0 := b
| (pos a) (pos b) := pos (a + b)
instance : has_add num := ⟨num.add⟩
protected def bit0 : num → num
| 0 := 0
| (pos n) := pos (pos_num.bit0 n)
protected def bit1 : num → num
| 0 := 1
| (pos n) := pos (pos_num.bit1 n)
def bit (b : bool) : num → num := cond b num.bit1 num.bit0
def size : num → num
| 0 := 0
| (pos n) := pos (pos_num.size n)
protected def mul : num → num → num
| 0 _ := 0
| _ 0 := 0
| (pos a) (pos b) := pos (a * b)
instance : has_mul num := ⟨num.mul⟩
open ordering
def cmp : num → num → ordering
| 0 0 := eq
| _ 0 := gt
| 0 _ := lt
| (pos a) (pos b) := pos_num.cmp a b
instance : has_lt num := ⟨λa b, cmp a b = ordering.lt⟩
instance : has_le num := ⟨λa b, ¬ b < a⟩
instance decidable_lt : @decidable_rel num (<)
| a b := by dsimp [(<)]; apply_instance
instance decidable_le : @decidable_rel num (≤)
| a b := by dsimp [(≤)]; apply_instance
def to_znum : num → znum
| 0 := 0
| (pos a) := znum.pos a
def to_znum_neg : num → znum
| 0 := 0
| (pos a) := znum.neg a
end num
namespace znum
open pos_num
def zneg : znum → znum
| 0 := 0
| (pos a) := neg a
| (neg a) := pos a
instance : has_neg znum := ⟨zneg⟩
def succ : znum → znum
| 0 := 1
| (pos a) := pos (pos_num.succ a)
| (neg a) := (pos_num.pred' a).to_znum_neg
def pred : znum → znum
| 0 := neg 1
| (pos a) := (pos_num.pred' a).to_znum
| (neg a) := neg (pos_num.succ a)
protected def bit0 : znum → znum
| 0 := 0
| (pos n) := pos (pos_num.bit0 n)
| (neg n) := neg (pos_num.bit0 n)
protected def bit1 : znum → znum
| 0 := 1
| (pos n) := pos (pos_num.bit1 n)
| (neg n) := neg (num.cases_on (pred' n) 1 pos_num.bit1)
protected def bitm1 : znum → znum
| 0 := neg 1
| (pos n) := pos (num.cases_on (pred' n) 1 pos_num.bit1)
| (neg n) := neg (pos_num.bit1 n)
end znum
namespace pos_num
open znum
def sub' : pos_num → pos_num → znum
| a 1 := (pred' a).to_znum
| 1 b := (pred' b).to_znum_neg
| (bit0 a) (bit0 b) := (sub' a b).bit0
| (bit0 a) (bit1 b) := (sub' a b).bitm1
| (bit1 a) (bit0 b) := (sub' a b).bit1
| (bit1 a) (bit1 b) := (sub' a b).bit0
def of_znum' : znum → option pos_num
| (znum.pos p) := some p
| _ := none
def of_znum : znum → pos_num
| (znum.pos p) := p
| _ := 1
protected def sub (a b : pos_num) : pos_num :=
match sub' a b with
| (znum.pos p) := p
| _ := 1
end
instance : has_sub pos_num := ⟨pos_num.sub⟩
end pos_num
namespace num
def ppred : num → option num
| 0 := none
| (pos p) := some p.pred'
def pred : num → num
| 0 := 0
| (pos p) := p.pred'
def of_znum' : znum → option num
| 0 := some 0
| (znum.pos p) := some (pos p)
| (znum.neg p) := none
def of_znum : znum → num
| (znum.pos p) := pos p
| _ := 0
def sub' : num → num → znum
| 0 0 := 0
| (pos a) 0 := znum.pos a
| 0 (pos b) := znum.neg b
| (pos a) (pos b) := a.sub' b
def psub (a b : num) : option num :=
of_znum' (sub' a b)
protected def sub (a b : num) : num :=
of_znum (sub' a b)
instance : has_sub num := ⟨num.sub⟩
end num
namespace znum
open pos_num
protected def add : znum → znum → znum
| 0 a := a
| b 0 := b
| (pos a) (pos b) := pos (a + b)
| (pos a) (neg b) := sub' a b
| (neg a) (pos b) := sub' b a
| (neg a) (neg b) := neg (a + b)
instance : has_add znum := ⟨znum.add⟩
protected def mul : znum → znum → znum
| 0 a := 0
| b 0 := 0
| (pos a) (pos b) := pos (a * b)
| (pos a) (neg b) := neg (a * b)
| (neg a) (pos b) := neg (a * b)
| (neg a) (neg b) := pos (a * b)
instance : has_mul znum := ⟨znum.mul⟩
open ordering
def cmp : znum → znum → ordering
| 0 0 := eq
| (pos a) (pos b) := pos_num.cmp a b
| (neg a) (neg b) := pos_num.cmp b a
| (pos _) _ := gt
| (neg _) _ := lt
| _ (pos _) := lt
| _ (neg _) := gt
instance : has_lt znum := ⟨λa b, cmp a b = ordering.lt⟩
instance : has_le znum := ⟨λa b, ¬ b < a⟩
instance decidable_lt : @decidable_rel znum (<)
| a b := by dsimp [(<)]; apply_instance
instance decidable_le : @decidable_rel znum (≤)
| a b := by dsimp [(≤)]; apply_instance
end znum
section
variables {α : Type*} [has_zero α] [has_one α] [has_add α] [has_neg α]
def cast_znum : znum → α
| 0 := 0
| (znum.pos p) := p
| (znum.neg p) := -p
@[priority 0] instance znum_coe : has_coe znum α := ⟨cast_znum⟩
end
/- The snum representation uses a bit string, essentially a list of 0 (ff) and 1 (tt) bits,
and the negation of the MSB is sign-extended to all higher bits. -/
namespace nzsnum
notation a :: b := bit a b
def sign : nzsnum → bool
| (msb b) := bnot b
| (b :: p) := sign p
@[pattern] def not : nzsnum → nzsnum
| (msb b) := msb (bnot b)
| (b :: p) := bnot b :: not p
prefix ~ := not
def bit0 : nzsnum → nzsnum := bit ff
def bit1 : nzsnum → nzsnum := bit tt
def head : nzsnum → bool
| (msb b) := b
| (b :: p) := b
def tail : nzsnum → snum
| (msb b) := snum.zero (bnot b)
| (b :: p) := p
end nzsnum
namespace snum
open nzsnum
def sign : snum → bool
| (zero z) := z
| (nz p) := p.sign
@[pattern] def not : snum → snum
| (zero z) := zero (bnot z)
| (nz p) := ~p
prefix ~ := not
@[pattern] def bit : bool → snum → snum
| b (zero z) := if b = z then zero b else msb b
| b (nz p) := p.bit b
notation a :: b := bit a b
def bit0 : snum → snum := bit ff
def bit1 : snum → snum := bit tt
theorem bit_zero (b) : b :: zero b = zero b := by cases b; refl
theorem bit_one (b) : b :: zero (bnot b) = msb b := by cases b; refl
end snum
namespace nzsnum
open snum
def drec' {C : snum → Sort*} (z : Π b, C (snum.zero b))
(s : Π b p, C p → C (b :: p)) : Π p : nzsnum, C p
| (msb b) := by rw ←bit_one; exact s b (snum.zero (bnot b)) (z (bnot b))
| (bit b p) := s b p (drec' p)
end nzsnum
namespace snum
open nzsnum
def head : snum → bool
| (zero z) := z
| (nz p) := p.head
def tail : snum → snum
| (zero z) := zero z
| (nz p) := p.tail
def drec' {C : snum → Sort*} (z : Π b, C (snum.zero b))
(s : Π b p, C p → C (b :: p)) : Π p, C p
| (zero b) := z b
| (nz p) := p.drec' z s
def rec' {α} (z : bool → α) (s : bool → snum → α → α) : snum → α :=
drec' z s
def bits : snum → Π n, vector bool n
| p 0 := vector.nil
| p (n+1) := head p :: bits (tail p) n
def test_bit : nat → snum → bool
| 0 p := head p
| (n+1) p := test_bit n (tail p)
def succ : snum → snum :=
rec' (λ b, cond b 0 1) (λb p succp, cond b (ff :: succp) (tt :: p))
def pred : snum → snum :=
rec' (λ b, cond b (~1) ~0) (λb p predp, cond b (ff :: p) (tt :: predp))
protected def neg (n : snum) : snum := succ ~n
instance : has_neg snum := ⟨snum.neg⟩
-- First bit is 0 or 1 (tt), second bit is 0 or -1 (tt)
def czadd : bool → bool → snum → snum
| ff ff p := p
| ff tt p := pred p
| tt ff p := succ p
| tt tt p := p
def cadd : snum → snum → bool → snum :=
rec' (λ a p c, czadd c a p) $ λa p IH,
rec' (λb c, czadd c b (a :: p)) $ λb q _ c,
bitvec.xor3 a b c :: IH q (bitvec.carry a b c)
protected def add (a b : snum) : snum := cadd a b ff
instance : has_add snum := ⟨snum.add⟩
protected def sub (a b : snum) : snum := a + -b
instance : has_sub snum := ⟨snum.sub⟩
protected def mul (a : snum) : snum → snum :=
rec' (λ b, cond b (-a) 0) $ λb q IH,
cond b (bit0 IH + a) (bit0 IH)
instance : has_mul snum := ⟨snum.mul⟩
end snum
namespace int
def of_snum : snum → ℤ :=
snum.rec' (λ a, cond a (-1) 0) (λa p IH, cond a (bit1 IH) (bit0 IH))
instance snum_coe : has_coe snum ℤ := ⟨of_snum⟩
end int
instance : has_lt snum := ⟨λa b, (a : ℤ) < b⟩
instance : has_le snum := ⟨λa b, (a : ℤ) ≤ b⟩
|
23d81f07f6fcc458e7d063c334bc35c7ca25bf72
|
35677d2df3f081738fa6b08138e03ee36bc33cad
|
/src/algebra/category/Group/limits.lean
|
44800c7aba3d04b0c94b9468f29512a7cbdfe050
|
[
"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
| 4,292
|
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.category.Group.basic
import category_theory.limits.types
import category_theory.limits.preserves
import algebra.pi_instances
/-!
# The category of abelian groups has all limits
Further, these limits are preserved by the forgetful functor --- that is,
the underlying types are just the limits in the category of types.
## Further work
A lot of this should be generalised / automated, as it's quite common for concrete
categories that the forgetful functor preserves limits.
-/
open category_theory
open category_theory.limits
universe u
namespace AddCommGroup
variables {J : Type u} [small_category J]
instance add_comm_group_obj (F : J ⥤ AddCommGroup.{u}) (j) :
add_comm_group ((F ⋙ forget AddCommGroup).obj j) :=
by { change add_comm_group (F.obj j), apply_instance }
instance sections_add_submonoid (F : J ⥤ AddCommGroup.{u}) :
is_add_submonoid (F ⋙ forget AddCommGroup).sections :=
{ zero_mem := λ j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_zero],
refl,
end,
add_mem := λ a b ah bh j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_add],
dsimp [functor.sections] at ah,
rw ah f,
dsimp [functor.sections] at bh,
rw bh f,
refl,
end }
instance sections_add_subgroup (F : J ⥤ AddCommGroup.{u}) :
is_add_subgroup (F ⋙ forget AddCommGroup).sections :=
{ neg_mem := λ a ah j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_neg],
dsimp [functor.sections] at ah,
rw ah f,
refl,
end,
..(AddCommGroup.sections_add_submonoid F) }
instance limit_add_comm_group (F : J ⥤ AddCommGroup.{u}) :
add_comm_group (limit (F ⋙ forget AddCommGroup)) :=
@subtype.add_comm_group ((Π (j : J), (F ⋙ forget _).obj j)) (by apply_instance) _
(by convert (AddCommGroup.sections_add_subgroup F))
/-- `limit.π (F ⋙ forget AddCommGroup) j` as a `add_monoid_hom`. -/
def limit_π_add_monoid_hom (F : J ⥤ AddCommGroup.{u}) (j) :
limit (F ⋙ forget AddCommGroup) →+ (F ⋙ forget AddCommGroup).obj j :=
{ to_fun := limit.π (F ⋙ forget AddCommGroup) j,
map_zero' := by { simp only [types.types_limit_π], refl },
map_add' := λ x y, by { simp only [types.types_limit_π], refl } }
namespace AddCommGroup_has_limits
-- The next two definitions are used in the construction of `has_limits AddCommGroup`.
-- After that, the limits should be constructed using the generic limits API,
-- e.g. `limit F`, `limit.cone F`, and `limit.is_limit F`.
/--
Construction of a limit cone in `AddCommGroup`.
(Internal use only; use the limits API.)
-/
def limit (F : J ⥤ AddCommGroup.{u}) : cone F :=
{ X := ⟨limit (F ⋙ forget _), by apply_instance⟩,
π :=
{ app := limit_π_add_monoid_hom F,
naturality' := λ j j' f,
add_monoid_hom.coe_inj ((limit.cone (F ⋙ forget _)).π.naturality f) } }
/--
Witness that the limit cone in `AddCommGroup` is a limit cone.
(Internal use only; use the limits API.)
-/
def limit_is_limit (F : J ⥤ AddCommGroup.{u}) : is_limit (limit F) :=
begin
refine is_limit.of_faithful
(forget AddCommGroup) (limit.is_limit _)
(λ s, ⟨_, _, _⟩) (λ s, rfl); dsimp,
{ apply subtype.eq, funext, dsimp,
erw (s.π.app j).map_zero, refl },
{ intros x y, apply subtype.eq, funext, dsimp,
erw (s.π.app j).map_add, refl }
end
end AddCommGroup_has_limits
open AddCommGroup_has_limits
/-- The category of abelian groups has all limits. -/
instance AddCommGroup_has_limits : has_limits.{u} AddCommGroup.{u} :=
{ has_limits_of_shape := λ J 𝒥,
{ has_limit := λ F, by exactI
{ cone := limit F,
is_limit := limit_is_limit F } } }
/--
The forgetful functor from abelian groups to types preserves all limits. (That is, the underlying
types could have been computed instead as limits in the category of types.)
-/
instance forget_preserves_limits : preserves_limits (forget AddCommGroup.{u}) :=
{ preserves_limits_of_shape := λ J 𝒥,
{ preserves_limit := λ F,
by exactI preserves_limit_of_preserves_limit_cone
(limit.is_limit F) (limit.is_limit (F ⋙ forget _)) } }
end AddCommGroup
|
045a5178d7c15b48359b2ae3fe94048247a0381a
|
947b78d97130d56365ae2ec264df196ce769371a
|
/src/Lean/Meta/InferType.lean
|
71606cc9185ad1a560cef0a0245be09f4331a619
|
[
"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
| 14,718
|
lean
|
/-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Data.LBool
import Lean.Meta.Basic
namespace Lean
namespace Meta
def throwFunctionExpected {α} (f : Expr) : MetaM α :=
throwError $ "function expected " ++ f
private def inferAppType (f : Expr) (args : Array Expr) : MetaM Expr := do
fType ← inferType f;
(j, fType) ← args.size.foldM
(fun i (acc : Nat × Expr) =>
let (j, type) := acc;
match type with
| Expr.forallE _ _ b _ => pure (j, b)
| _ => do
type ← whnf $ type.instantiateRevRange j i args;
match type with
| Expr.forallE _ _ b _ => pure (i, b)
| _ => throwFunctionExpected $ mkAppRange f 0 (i+1) args)
(0, fType);
pure $ fType.instantiateRevRange j args.size args
def throwIncorrectNumberOfLevels {α} (constName : Name) (us : List Level) : MetaM α :=
throwError $ "incorrect number of universe levels " ++ mkConst constName us
private def inferConstType (c : Name) (us : List Level) : MetaM Expr := do
cinfo ← getConstInfo c;
if cinfo.lparams.length == us.length then
pure $ cinfo.instantiateTypeLevelParams us
else
throwIncorrectNumberOfLevels c us
private def inferProjType (structName : Name) (idx : Nat) (e : Expr) : MetaM Expr := do
let failed : Unit → MetaM Expr := fun _ => throwError $ "invalide projection" ++ indentExpr (mkProj structName idx e);
structType ← inferType e;
structType ← whnf structType;
matchConstStruct structType.getAppFn failed fun structVal structLvls ctorVal =>
let n := structVal.nparams;
let structParams := structType.getAppArgs;
if n != structParams.size then failed ()
else do
ctorType ← inferAppType (mkConst ctorVal.name structLvls) structParams;
ctorType ← idx.foldM
(fun i ctorType => do
ctorType ← whnf ctorType;
match ctorType with
| Expr.forallE _ _ body _ =>
if body.hasLooseBVars then
pure $ body.instantiate1 $ mkProj structName i e
else
pure body
| _ => failed ())
ctorType;
ctorType ← whnf ctorType;
match ctorType with
| Expr.forallE _ d _ _ => pure d
| _ => failed ()
def throwTypeExcepted {α} (type : Expr) : MetaM α :=
throwError $ "type expected " ++ indentExpr type
variables {m : Type → Type} [MonadLiftT MetaM m]
private def getLevelImp (type : Expr) : MetaM Level := do
typeType ← inferType type;
typeType ← whnfD typeType;
match typeType with
| Expr.sort lvl _ => pure lvl
| Expr.mvar mvarId _ =>
condM (isReadOnlyOrSyntheticOpaqueExprMVar mvarId)
(throwTypeExcepted type)
(do lvl ← mkFreshLevelMVar;
assignExprMVar mvarId (mkSort lvl);
pure lvl)
| _ => throwTypeExcepted type
def getLevel (type : Expr) : m Level :=
liftMetaM $ getLevelImp type
private def inferForallType (e : Expr) : MetaM Expr :=
forallTelescope e $ fun xs e => do
lvl ← getLevel e;
lvl ← xs.foldrM
(fun x lvl => do
xType ← inferType x;
xTypeLvl ← getLevel xType;
pure $ mkLevelIMax xTypeLvl lvl)
lvl;
pure $ mkSort lvl.normalize
/- Infer type of lambda and let expressions -/
private def inferLambdaType (e : Expr) : MetaM Expr :=
lambdaLetTelescope e $ fun xs e => do
type ← inferType e;
mkForallFVars xs type
@[inline] private def withLocalDecl {α} (name : Name) (bi : BinderInfo) (type : Expr) (x : Expr → MetaM α) : MetaM α :=
savingCache $ do
fvarId ← mkFreshId;
adaptReader (fun (ctx : Context) => { ctx with lctx := ctx.lctx.mkLocalDecl fvarId name type bi }) $
x (mkFVar fvarId)
def throwUnknownMVar {α} (mvarId : MVarId) : MetaM α :=
throwError $ "unknown metavariable '" ++ mkMVar mvarId ++ "'"
private def inferMVarType (mvarId : MVarId) : MetaM Expr := do
mctx ← getMCtx;
match mctx.findDecl? mvarId with
| some d => pure d.type
| none => throwUnknownMVar mvarId
private def inferFVarType (fvarId : FVarId) : MetaM Expr := do
lctx ← getLCtx;
match lctx.find? fvarId with
| some d => pure d.type
| none => throwUnknownFVar fvarId
@[inline] private def checkInferTypeCache (e : Expr) (inferType : MetaM Expr) : MetaM Expr := do
s ← get;
match s.cache.inferType.find? e with
| some type => pure type
| none => do
type ← inferType;
modify $ fun s => { s with cache := { s.cache with inferType := s.cache.inferType.insert e type } };
pure type
private partial def inferTypeAux : Expr → MetaM Expr
| Expr.const c lvls _ => inferConstType c lvls
| e@(Expr.proj n i s _) => checkInferTypeCache e (inferProjType n i s)
| e@(Expr.app f _ _) => checkInferTypeCache e (inferAppType f.getAppFn e.getAppArgs)
| Expr.mvar mvarId _ => inferMVarType mvarId
| Expr.fvar fvarId _ => inferFVarType fvarId
| Expr.bvar bidx _ => throwError $ "unexpected bound variable " ++ mkBVar bidx
| Expr.mdata _ e _ => inferTypeAux e
| Expr.lit v _ => pure v.type
| Expr.sort lvl _ => pure $ mkSort (mkLevelSucc lvl)
| e@(Expr.forallE _ _ _ _) => checkInferTypeCache e (inferForallType e)
| e@(Expr.lam _ _ _ _) => checkInferTypeCache e (inferLambdaType e)
| e@(Expr.letE _ _ _ _ _) => checkInferTypeCache e (inferLambdaType e)
| Expr.localE _ _ _ _ => unreachable!
def inferTypeImp (e : Expr) : MetaM Expr :=
withTransparency TransparencyMode.default (inferTypeAux e)
@[init] def setInferTypeRef : IO Unit :=
inferTypeRef.set inferTypeImp
/--
Return `LBool.true` if given level is always equivalent to universe level zero.
It is used to implement `isProp`. -/
private def isAlwaysZero : Level → Bool
| Level.zero _ => true
| Level.mvar _ _ => false
| Level.param _ _ => false
| Level.succ _ _ => false
| Level.max u v _ => isAlwaysZero u && isAlwaysZero v
| Level.imax _ u _ => isAlwaysZero u
/--
`isArrowProp type n` is an "approximate" predicate which returns `LBool.true`
if `type` is of the form `A_1 -> ... -> A_n -> Prop`.
Remark: `type` can be a dependent arrow. -/
private partial def isArrowProp : Expr → Nat → MetaM LBool
| Expr.sort u _, 0 => do u ← instantiateLevelMVars u; pure $ (isAlwaysZero u).toLBool
| Expr.forallE _ _ _ _, 0 => pure LBool.false
| Expr.forallE _ _ b _, n+1 => isArrowProp b n
| Expr.letE _ _ _ b _, n => isArrowProp b n
| Expr.mdata _ e _, n => isArrowProp e n
| _, _ => pure LBool.undef
/--
`isPropQuickApp f n` is an "approximate" predicate which returns `LBool.true`
if `f` applied to `n` arguments is a proposition. -/
private partial def isPropQuickApp : Expr → Nat → MetaM LBool
| Expr.const c lvls _, arity => do constType ← inferConstType c lvls; isArrowProp constType arity
| Expr.fvar fvarId _, arity => do fvarType ← inferFVarType fvarId; isArrowProp fvarType arity
| Expr.mvar mvarId _, arity => do mvarType ← inferMVarType mvarId; isArrowProp mvarType arity
| Expr.app f _ _, arity => isPropQuickApp f (arity+1)
| Expr.mdata _ e _, arity => isPropQuickApp e arity
| Expr.letE _ _ _ b _, arity => isPropQuickApp b arity
| Expr.lam _ _ _ _, 0 => pure LBool.false
| Expr.lam _ _ b _, arity+1 => isPropQuickApp b arity
| _, _ => pure LBool.undef
/--
`isPropQuick e` is an "approximate" predicate which returns `LBool.true`
if `e` is a proposition. -/
partial def isPropQuick : Expr → MetaM LBool
| Expr.bvar _ _ => pure LBool.undef
| Expr.lit _ _ => pure LBool.false
| Expr.sort _ _ => pure LBool.false
| Expr.lam _ _ _ _ => pure LBool.false
| Expr.letE _ _ _ b _ => isPropQuick b
| Expr.proj _ _ _ _ => pure LBool.undef
| Expr.forallE _ _ b _ => isPropQuick b
| Expr.mdata _ e _ => isPropQuick e
| Expr.const c lvls _ => do constType ← inferConstType c lvls; isArrowProp constType 0
| Expr.fvar fvarId _ => do fvarType ← inferFVarType fvarId; isArrowProp fvarType 0
| Expr.mvar mvarId _ => do mvarType ← inferMVarType mvarId; isArrowProp mvarType 0
| Expr.app f _ _ => isPropQuickApp f 1
| Expr.localE _ _ _ _ => unreachable!
/-- `isProp whnf e` return `true` if `e` is a proposition.
If `e` contains metavariables, it may not be possible
to decide whether is a proposition or not. We return `false` in this
case. We considered using `LBool` and retuning `LBool.undef`, but
we have no applications for it. -/
private def isPropImp (e : Expr) : MetaM Bool := do
r ← isPropQuick e;
match r with
| LBool.true => pure true
| LBool.false => pure false
| LBool.undef => do
-- dbgTrace ("isPropQuick failed " ++ toString e);
type ← inferType e;
type ← whnfD type;
match type with
| Expr.sort u _ => do u ← instantiateLevelMVars u; pure $ isAlwaysZero u
| _ => pure false
def isProp (e : Expr) : m Bool :=
liftMetaM $ isPropImp e
/--
`isArrowProposition type n` is an "approximate" predicate which returns `LBool.true`
if `type` is of the form `A_1 -> ... -> A_n -> B`, where `B` is a proposition.
Remark: `type` can be a dependent arrow. -/
private partial def isArrowProposition : Expr → Nat → MetaM LBool
| Expr.forallE _ _ b _, n+1 => isArrowProposition b n
| Expr.letE _ _ _ b _, n => isArrowProposition b n
| Expr.mdata _ e _, n => isArrowProposition e n
| type, 0 => isPropQuick type
| _, _ => pure LBool.undef
/--
`isProofQuickApp f n` is an "approximate" predicate which returns `LBool.true`
if `f` applied to `n` arguments is a proof. -/
@[specialize] private partial def isProofQuickApp (isProofQuick : Expr → MetaM LBool) : Expr → Nat → MetaM LBool
| Expr.const c lvls _, arity => do constType ← inferConstType c lvls; isArrowProposition constType arity
| Expr.fvar fvarId _, arity => do fvarType ← inferFVarType fvarId; isArrowProposition fvarType arity
| Expr.mvar mvarId _, arity => do mvarType ← inferMVarType mvarId; isArrowProposition mvarType arity
| Expr.app f _ _, arity => isProofQuickApp f (arity+1)
| Expr.mdata _ e _, arity => isProofQuickApp e arity
| Expr.letE _ _ _ b _, arity => isProofQuickApp b arity
| Expr.lam _ _ b _, 0 => isProofQuick b
| Expr.lam _ _ b _, arity+1 => isProofQuickApp b arity
| _, _ => pure LBool.undef
/--
`isProofQuick e` is an "approximate" predicate which returns `LBool.true`
if `e` is a proof. -/
partial def isProofQuick : Expr → MetaM LBool
| Expr.bvar _ _ => pure LBool.undef
| Expr.lit _ _ => pure LBool.false
| Expr.sort _ _ => pure LBool.false
| Expr.lam _ _ b _ => isProofQuick b
| Expr.letE _ _ _ b _ => isProofQuick b
| Expr.proj _ _ _ _ => pure LBool.undef
| Expr.forallE _ _ b _ => pure LBool.false
| Expr.mdata _ e _ => isProofQuick e
| Expr.const c lvls _ => do constType ← inferConstType c lvls; isArrowProposition constType 0
| Expr.fvar fvarId _ => do fvarType ← inferFVarType fvarId; isArrowProposition fvarType 0
| Expr.mvar mvarId _ => do mvarType ← inferMVarType mvarId; isArrowProposition mvarType 0
| Expr.app f _ _ => isProofQuickApp isProofQuick f 1
| Expr.localE _ _ _ _ => unreachable!
private def isProofImp (e : Expr) : MetaM Bool := do
r ← isProofQuick e;
match r with
| LBool.true => pure true
| LBool.false => pure false
| LBool.undef => do
type ← inferType e;
Meta.isProp type
def isProof (e : Expr) : m Bool :=
liftMetaM $ isProofImp e
/--
`isArrowType type n` is an "approximate" predicate which returns `LBool.true`
if `type` is of the form `A_1 -> ... -> A_n -> Sort _`.
Remark: `type` can be a dependent arrow. -/
private partial def isArrowType : Expr → Nat → MetaM LBool
| Expr.sort u _, 0 => pure LBool.true
| Expr.forallE _ _ _ _, 0 => pure LBool.false
| Expr.forallE _ _ b _, n+1 => isArrowType b n
| Expr.letE _ _ _ b _, n => isArrowType b n
| Expr.mdata _ e _, n => isArrowType e n
| _, _ => pure LBool.undef
/--
`isTypeQuickApp f n` is an "approximate" predicate which returns `LBool.true`
if `f` applied to `n` arguments is a type. -/
private partial def isTypeQuickApp : Expr → Nat → MetaM LBool
| Expr.const c lvls _, arity => do constType ← inferConstType c lvls; isArrowType constType arity
| Expr.fvar fvarId _, arity => do fvarType ← inferFVarType fvarId; isArrowType fvarType arity
| Expr.mvar mvarId _, arity => do mvarType ← inferMVarType mvarId; isArrowType mvarType arity
| Expr.app f _ _, arity => isTypeQuickApp f (arity+1)
| Expr.mdata _ e _, arity => isTypeQuickApp e arity
| Expr.letE _ _ _ b _, arity => isTypeQuickApp b arity
| Expr.lam _ _ _ _, 0 => pure LBool.false
| Expr.lam _ _ b _, arity+1 => isTypeQuickApp b arity
| _, _ => pure LBool.undef
/--
`isTypeQuick e` is an "approximate" predicate which returns `LBool.true`
if `e` is a type. -/
partial def isTypeQuick : Expr → MetaM LBool
| Expr.bvar _ _ => pure LBool.undef
| Expr.lit _ _ => pure LBool.false
| Expr.sort _ _ => pure LBool.true
| Expr.lam _ _ _ _ => pure LBool.false
| Expr.letE _ _ _ b _ => isTypeQuick b
| Expr.proj _ _ _ _ => pure LBool.undef
| Expr.forallE _ _ b _ => pure LBool.true
| Expr.mdata _ e _ => isTypeQuick e
| Expr.const c lvls _ => do constType ← inferConstType c lvls; isArrowType constType 0
| Expr.fvar fvarId _ => do fvarType ← inferFVarType fvarId; isArrowType fvarType 0
| Expr.mvar mvarId _ => do mvarType ← inferMVarType mvarId; isArrowType mvarType 0
| Expr.app f _ _ => isTypeQuickApp f 1
| Expr.localE _ _ _ _ => unreachable!
private def isTypeImp (e : Expr) : m Bool := liftMetaM do
r ← isTypeQuick e;
match r with
| LBool.true => pure true
| LBool.false => pure false
| LBool.undef => do
type ← inferType e;
type ← whnfD type;
match type with
| Expr.sort _ _ => pure true
| _ => pure false
def isType (e : Expr) : m Bool :=
liftMetaM $ isTypeImp e
private partial def isTypeFormerTypeImp : Expr → MetaM Bool
| type => do
type ← whnfD type;
match type with
| Expr.sort _ _ => pure true
| Expr.forallE n d b c =>
withLocalDecl n c.binderInfo d $ fun fvar =>
isTypeFormerTypeImp (b.instantiate1 fvar)
| _ => pure false
def isTypeFormerType (e : Expr) : m Bool :=
liftMetaM $ isTypeFormerTypeImp e
/--
Return true iff `e : Sort _` or `e : (forall As, Sort _)`.
Remark: it subsumes `isType` -/
def isTypeFormer (e : Expr) : m Bool := liftMetaM do
type ← inferType e;
isTypeFormerType type
end Meta
end Lean
|
85dd1c1ea630bba546a8cadb90640fcbe0feff74
|
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
|
/src/field_theory/normal.lean
|
8dd85311f3a716b3f1bc130e2cabc9c68951227f
|
[
"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
| 15,418
|
lean
|
/-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Thomas Browning, Patrick Lutz
-/
import field_theory.adjoin
import field_theory.tower
import group_theory.solvable
import ring_theory.power_basis
/-!
# Normal field extensions
In this file we define normal field extensions and prove that for a finite extension, being normal
is the same as being a splitting field (`normal.of_is_splitting_field` and
`normal.exists_is_splitting_field`).
## Main Definitions
- `normal F K` where `K` is a field extension of `F`.
-/
noncomputable theory
open_locale big_operators
open_locale classical
open polynomial is_scalar_tower
variables (F K : Type*) [field F] [field K] [algebra F K]
--TODO(Commelin): refactor normal to extend `is_algebraic`??
/-- Typeclass for normal field extension: `K` is a normal extension of `F` iff the minimal
polynomial of every element `x` in `K` splits in `K`, i.e. every conjugate of `x` is in `K`. -/
class normal : Prop :=
(is_integral' (x : K) : is_integral F x)
(splits' (x : K) : splits (algebra_map F K) (minpoly F x))
variables {F K}
theorem normal.is_integral (h : normal F K) (x : K) : is_integral F x := normal.is_integral' x
theorem normal.splits (h : normal F K) (x : K) :
splits (algebra_map F K) (minpoly F x) := normal.splits' x
theorem normal_iff : normal F K ↔
∀ x : K, is_integral F x ∧ splits (algebra_map F K) (minpoly F x) :=
⟨λ h x, ⟨h.is_integral x, h.splits x⟩, λ h, ⟨λ x, (h x).1, λ x, (h x).2⟩⟩
theorem normal.out : normal F K →
∀ x : K, is_integral F x ∧ splits (algebra_map F K) (minpoly F x) := normal_iff.1
variables (F K)
instance normal_self : normal F F :=
⟨λ x, is_integral_algebra_map, λ x, by { rw minpoly.eq_X_sub_C', exact splits_X_sub_C _ }⟩
variables {K}
variables (K)
theorem normal.exists_is_splitting_field [h : normal F K] [finite_dimensional F K] :
∃ p : polynomial F, is_splitting_field F K p :=
begin
let s := basis.of_vector_space F K,
refine ⟨∏ x, minpoly F (s x),
splits_prod _ $ λ x hx, h.splits (s x),
subalgebra.to_submodule_injective _⟩,
rw [algebra.top_to_submodule, eq_top_iff, ← s.span_eq, submodule.span_le, set.range_subset_iff],
refine λ x, algebra.subset_adjoin (multiset.mem_to_finset.mpr $
(mem_roots $ mt (map_eq_zero $ algebra_map F K).1 $
finset.prod_ne_zero_iff.2 $ λ x hx, _).2 _),
{ exact minpoly.ne_zero (h.is_integral (s x)) },
rw [is_root.def, eval_map, ← aeval_def, alg_hom.map_prod],
exact finset.prod_eq_zero (finset.mem_univ _) (minpoly.aeval _ _)
end
section normal_tower
variables (E : Type*) [field E] [algebra F E] [algebra K E] [is_scalar_tower F K E]
lemma normal.tower_top_of_normal [h : normal F E] : normal K E :=
normal_iff.2 $ λ x, begin
cases h.out x with hx hhx,
rw algebra_map_eq F K E at hhx,
exact ⟨is_integral_of_is_scalar_tower x hx, polynomial.splits_of_splits_of_dvd (algebra_map K E)
(polynomial.map_ne_zero (minpoly.ne_zero hx))
((polynomial.splits_map_iff (algebra_map F K) (algebra_map K E)).mpr hhx)
(minpoly.dvd_map_of_is_scalar_tower F K x)⟩,
end
lemma alg_hom.normal_bijective [h : normal F E] (ϕ : E →ₐ[F] K) : function.bijective ϕ :=
⟨ϕ.to_ring_hom.injective, λ x, by
{ letI : algebra E K := ϕ.to_ring_hom.to_algebra,
obtain ⟨h1, h2⟩ := h.out (algebra_map K E x),
cases minpoly.mem_range_of_degree_eq_one E x (or.resolve_left h2 (minpoly.ne_zero h1)
(minpoly.irreducible (is_integral_of_is_scalar_tower x
((is_integral_algebra_map_iff (algebra_map K E).injective).mp h1)))
(minpoly.dvd E x ((algebra_map K E).injective (by
{ rw [ring_hom.map_zero, aeval_map, ←is_scalar_tower.to_alg_hom_apply F K E,
←alg_hom.comp_apply, ←aeval_alg_hom],
exact minpoly.aeval F (algebra_map K E x) })))) with y hy,
exact ⟨y, hy⟩ }⟩
variables {F} {E} {E' : Type*} [field E'] [algebra F E']
lemma normal.of_alg_equiv [h : normal F E] (f : E ≃ₐ[F] E') : normal F E' :=
normal_iff.2 $ λ x, begin
cases h.out (f.symm x) with hx hhx,
have H := is_integral_alg_hom f.to_alg_hom hx,
rw [alg_equiv.to_alg_hom_eq_coe, alg_equiv.coe_alg_hom, alg_equiv.apply_symm_apply] at H,
use H,
apply polynomial.splits_of_splits_of_dvd (algebra_map F E') (minpoly.ne_zero hx),
{ rw ← alg_hom.comp_algebra_map f.to_alg_hom,
exact polynomial.splits_comp_of_splits (algebra_map F E) f.to_alg_hom.to_ring_hom hhx },
{ apply minpoly.dvd _ _,
rw ← add_equiv.map_eq_zero_iff f.symm.to_add_equiv,
exact eq.trans (polynomial.aeval_alg_hom_apply f.symm.to_alg_hom x
(minpoly F (f.symm x))).symm (minpoly.aeval _ _) },
end
lemma alg_equiv.transfer_normal (f : E ≃ₐ[F] E') : normal F E ↔ normal F E' :=
⟨λ h, by exactI normal.of_alg_equiv f, λ h, by exactI normal.of_alg_equiv f.symm⟩
lemma normal.of_is_splitting_field (p : polynomial F) [hFEp : is_splitting_field F E p] :
normal F E :=
begin
by_cases hp : p = 0,
{ haveI : is_splitting_field F F p, { rw hp, exact ⟨splits_zero _, subsingleton.elim _ _⟩ },
exactI (alg_equiv.transfer_normal ((is_splitting_field.alg_equiv F p).trans
(is_splitting_field.alg_equiv E p).symm)).mp (normal_self F) },
refine normal_iff.2 (λ x, _),
haveI hFE : finite_dimensional F E := is_splitting_field.finite_dimensional E p,
have Hx : is_integral F x := is_integral_of_noetherian (is_noetherian.iff_fg.2 hFE) x,
refine ⟨Hx, or.inr _⟩,
rintros q q_irred ⟨r, hr⟩,
let D := adjoin_root q,
let pbED := adjoin_root.power_basis q_irred.ne_zero,
haveI : finite_dimensional E D := power_basis.finite_dimensional pbED,
have finrankED : finite_dimensional.finrank E D = q.nat_degree := power_basis.finrank pbED,
letI : algebra F D := ring_hom.to_algebra ((algebra_map E D).comp (algebra_map F E)),
haveI : is_scalar_tower F E D := of_algebra_map_eq (λ _, rfl),
haveI : finite_dimensional F D := finite_dimensional.trans F E D,
suffices : nonempty (D →ₐ[F] E),
{ cases this with ϕ,
rw [←with_bot.coe_one, degree_eq_iff_nat_degree_eq q_irred.ne_zero, ←finrankED],
have nat_lemma : ∀ a b c : ℕ, a * b = c → c ≤ a → 0 < c → b = 1,
{ intros a b c h1 h2 h3, nlinarith },
exact nat_lemma _ _ _ (finite_dimensional.finrank_mul_finrank F E D)
(linear_map.finrank_le_finrank_of_injective (show function.injective ϕ.to_linear_map,
from ϕ.to_ring_hom.injective)) finite_dimensional.finrank_pos, },
let C := adjoin_root (minpoly F x),
have Hx_irred := minpoly.irreducible Hx,
letI : algebra C D := ring_hom.to_algebra (adjoin_root.lift
(algebra_map F D) (adjoin_root.root q) (by rw [algebra_map_eq F E D, ←eval₂_map, hr,
adjoin_root.algebra_map_eq, eval₂_mul, adjoin_root.eval₂_root, zero_mul])),
letI : algebra C E := ring_hom.to_algebra (adjoin_root.lift
(algebra_map F E) x (minpoly.aeval F x)),
haveI : is_scalar_tower F C D := of_algebra_map_eq (λ x, (adjoin_root.lift_of _).symm),
haveI : is_scalar_tower F C E := of_algebra_map_eq (λ x, (adjoin_root.lift_of _).symm),
suffices : nonempty (D →ₐ[C] E),
{ exact nonempty.map (alg_hom.restrict_scalars F) this },
let S : set D := ((p.map (algebra_map F E)).roots.map (algebra_map E D)).to_finset,
suffices : ⊤ ≤ intermediate_field.adjoin C S,
{ refine intermediate_field.alg_hom_mk_adjoin_splits' (top_le_iff.mp this) (λ y hy, _),
rcases multiset.mem_map.mp (multiset.mem_to_finset.mp hy) with ⟨z, hz1, hz2⟩,
have Hz : is_integral F z := is_integral_of_noetherian (is_noetherian.iff_fg.2 hFE) z,
use (show is_integral C y, from is_integral_of_noetherian
(is_noetherian.iff_fg.2 (finite_dimensional.right F C D)) y),
apply splits_of_splits_of_dvd (algebra_map C E) (map_ne_zero (minpoly.ne_zero Hz)),
{ rw [splits_map_iff, ←algebra_map_eq F C E],
exact splits_of_splits_of_dvd _ hp hFEp.splits (minpoly.dvd F z
(eq.trans (eval₂_eq_eval_map _) ((mem_roots (map_ne_zero hp)).mp hz1))) },
{ apply minpoly.dvd,
rw [←hz2, aeval_def, eval₂_map, ←algebra_map_eq F C D, algebra_map_eq F E D, ←hom_eval₂,
←aeval_def, minpoly.aeval F z, ring_hom.map_zero] } },
rw [←intermediate_field.to_subalgebra_le_to_subalgebra, intermediate_field.top_to_subalgebra],
apply ge_trans (intermediate_field.algebra_adjoin_le_adjoin C S),
suffices : (algebra.adjoin C S).restrict_scalars F
= (algebra.adjoin E {adjoin_root.root q}).restrict_scalars F,
{ rw [adjoin_root.adjoin_root_eq_top, subalgebra.restrict_scalars_top,
←@subalgebra.restrict_scalars_top F C] at this,
exact top_le_iff.mpr (subalgebra.restrict_scalars_injective F this) },
dsimp only [S],
rw [←finset.image_to_finset, finset.coe_image],
apply eq.trans (algebra.adjoin_res_eq_adjoin_res F E C D
hFEp.adjoin_roots adjoin_root.adjoin_root_eq_top),
rw [set.image_singleton, ring_hom.algebra_map_to_algebra, adjoin_root.lift_root]
end
instance (p : polynomial F) : normal F p.splitting_field := normal.of_is_splitting_field p
end normal_tower
variables {F} {K} (ϕ ψ : K →ₐ[F] K) (χ ω : K ≃ₐ[F] K)
section restrict
variables (E : Type*) [field E] [algebra F E] [algebra E K] [is_scalar_tower F E K]
/-- Restrict algebra homomorphism to image of normal subfield -/
def alg_hom.restrict_normal_aux [h : normal F E] :
(to_alg_hom F E K).range →ₐ[F] (to_alg_hom F E K).range :=
{ to_fun := λ x, ⟨ϕ x, by
{ suffices : (to_alg_hom F E K).range.map ϕ ≤ _,
{ exact this ⟨x, subtype.mem x, rfl⟩ },
rintros x ⟨y, ⟨z, hy⟩, hx⟩,
rw [←hx, ←hy],
apply minpoly.mem_range_of_degree_eq_one E,
exact or.resolve_left (h.splits z) (minpoly.ne_zero (h.is_integral z))
(minpoly.irreducible $ is_integral_of_is_scalar_tower _ $
is_integral_alg_hom ϕ $ is_integral_alg_hom _ $ h.is_integral z)
(minpoly.dvd E _ $ by rw [aeval_map, aeval_alg_hom, aeval_alg_hom, alg_hom.comp_apply,
alg_hom.comp_apply, minpoly.aeval, alg_hom.map_zero, alg_hom.map_zero]) }⟩,
map_zero' := subtype.ext ϕ.map_zero,
map_one' := subtype.ext ϕ.map_one,
map_add' := λ x y, subtype.ext (ϕ.map_add x y),
map_mul' := λ x y, subtype.ext (ϕ.map_mul x y),
commutes' := λ x, subtype.ext (ϕ.commutes x) }
/-- Restrict algebra homomorphism to normal subfield -/
def alg_hom.restrict_normal [normal F E] : E →ₐ[F] E :=
((alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)).symm.to_alg_hom.comp
(ϕ.restrict_normal_aux E)).comp
(alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)).to_alg_hom
@[simp] lemma alg_hom.restrict_normal_commutes [normal F E] (x : E) :
algebra_map E K (ϕ.restrict_normal E x) = ϕ (algebra_map E K x) :=
subtype.ext_iff.mp (alg_equiv.apply_symm_apply (alg_equiv.of_injective_field
(is_scalar_tower.to_alg_hom F E K)) (ϕ.restrict_normal_aux E
⟨is_scalar_tower.to_alg_hom F E K x, x, rfl⟩))
lemma alg_hom.restrict_normal_comp [normal F E] :
(ϕ.restrict_normal E).comp (ψ.restrict_normal E) = (ϕ.comp ψ).restrict_normal E :=
alg_hom.ext (λ _, (algebra_map E K).injective
(by simp only [alg_hom.comp_apply, alg_hom.restrict_normal_commutes]))
/-- Restrict algebra isomorphism to a normal subfield -/
def alg_equiv.restrict_normal [h : normal F E] : E ≃ₐ[F] E :=
alg_equiv.of_bijective (χ.to_alg_hom.restrict_normal E) (alg_hom.normal_bijective F E E _)
@[simp] lemma alg_equiv.restrict_normal_commutes [normal F E] (x : E) :
algebra_map E K (χ.restrict_normal E x) = χ (algebra_map E K x) :=
χ.to_alg_hom.restrict_normal_commutes E x
lemma alg_equiv.restrict_normal_trans [normal F E] :
(χ.trans ω).restrict_normal E = (χ.restrict_normal E).trans (ω.restrict_normal E) :=
alg_equiv.ext (λ _, (algebra_map E K).injective
(by simp only [alg_equiv.trans_apply, alg_equiv.restrict_normal_commutes]))
/-- Restriction to an normal subfield as a group homomorphism -/
def alg_equiv.restrict_normal_hom [normal F E] : (K ≃ₐ[F] K) →* (E ≃ₐ[F] E) :=
monoid_hom.mk' (λ χ, χ.restrict_normal E) (λ ω χ, (χ.restrict_normal_trans ω E))
end restrict
section lift
variables {F} {K} (E : Type*) [field E] [algebra F E] [algebra K E] [is_scalar_tower F K E]
/-- If `E/K/F` is a tower of fields with `E/F` normal then we can lift
an algebra homomorphism `ϕ : K →ₐ[F] K` to `ϕ.lift_normal E : E →ₐ[F] E`. -/
noncomputable def alg_hom.lift_normal [h : normal F E] : E →ₐ[F] E :=
@alg_hom.restrict_scalars F K E E _ _ _ _ _ _
((is_scalar_tower.to_alg_hom F K E).comp ϕ).to_ring_hom.to_algebra _ _ _ _
(nonempty.some (@intermediate_field.alg_hom_mk_adjoin_splits' K E E _ _ _ _
((is_scalar_tower.to_alg_hom F K E).comp ϕ).to_ring_hom.to_algebra ⊤ rfl
(λ x hx, ⟨is_integral_of_is_scalar_tower x (h.out x).1,
splits_of_splits_of_dvd _ (map_ne_zero (minpoly.ne_zero (h.out x).1))
(by { rw [splits_map_iff, ←is_scalar_tower.algebra_map_eq], exact (h.out x).2 })
(minpoly.dvd_map_of_is_scalar_tower F K x)⟩)))
@[simp] lemma alg_hom.lift_normal_commutes [normal F E] (x : K) :
ϕ.lift_normal E (algebra_map K E x) = algebra_map K E (ϕ x) :=
@alg_hom.commutes K E E _ _ _ _
((is_scalar_tower.to_alg_hom F K E).comp ϕ).to_ring_hom.to_algebra _ x
@[simp] lemma alg_hom.restrict_lift_normal [normal F K] [normal F E] :
(ϕ.lift_normal E).restrict_normal K = ϕ :=
alg_hom.ext (λ x, (algebra_map K E).injective
(eq.trans (alg_hom.restrict_normal_commutes _ K x) (ϕ.lift_normal_commutes E x)))
/-- If `E/K/F` is a tower of fields with `E/F` normal then we can lift
an algebra isomorphism `ϕ : K ≃ₐ[F] K` to `ϕ.lift_normal E : E ≃ₐ[F] E`. -/
noncomputable def alg_equiv.lift_normal [normal F E] : E ≃ₐ[F] E :=
alg_equiv.of_bijective (χ.to_alg_hom.lift_normal E) (alg_hom.normal_bijective F E E _)
@[simp] lemma alg_equiv.lift_normal_commutes [normal F E] (x : K) :
χ.lift_normal E (algebra_map K E x) = algebra_map K E (χ x) :=
χ.to_alg_hom.lift_normal_commutes E x
@[simp] lemma alg_equiv.restrict_lift_normal [normal F K] [normal F E] :
(χ.lift_normal E).restrict_normal K = χ :=
alg_equiv.ext (λ x, (algebra_map K E).injective
(eq.trans (alg_equiv.restrict_normal_commutes _ K x) (χ.lift_normal_commutes E x)))
lemma alg_equiv.restrict_normal_hom_surjective [normal F K] [normal F E] :
function.surjective (alg_equiv.restrict_normal_hom K : (E ≃ₐ[F] E) → (K ≃ₐ[F] K)) :=
λ χ, ⟨χ.lift_normal E, χ.restrict_lift_normal E⟩
variables (F) (K) (E)
lemma is_solvable_of_is_scalar_tower [normal F K] [h1 : is_solvable (K ≃ₐ[F] K)]
[h2 : is_solvable (E ≃ₐ[K] E)] : is_solvable (E ≃ₐ[F] E) :=
begin
let f : (E ≃ₐ[K] E) →* (E ≃ₐ[F] E) :=
{ to_fun := λ ϕ, alg_equiv.of_alg_hom (ϕ.to_alg_hom.restrict_scalars F)
(ϕ.symm.to_alg_hom.restrict_scalars F)
(alg_hom.ext (λ x, ϕ.apply_symm_apply x))
(alg_hom.ext (λ x, ϕ.symm_apply_apply x)),
map_one' := alg_equiv.ext (λ _, rfl),
map_mul' := λ _ _, alg_equiv.ext (λ _, rfl) },
refine solvable_of_ker_le_range f (alg_equiv.restrict_normal_hom K)
(λ ϕ hϕ, ⟨{commutes' := λ x, _, .. ϕ}, alg_equiv.ext (λ _, rfl)⟩),
exact (eq.trans (ϕ.restrict_normal_commutes K x).symm (congr_arg _ (alg_equiv.ext_iff.mp hϕ x))),
end
end lift
|
834b75c7dbe40182bb0a1daed332545ca426525f
|
737dc4b96c97368cb66b925eeea3ab633ec3d702
|
/src/Lean/Elab/Util.lean
|
40c6f701977ccd6b5ff8466cb5c2bd61d6823c20
|
[
"Apache-2.0"
] |
permissive
|
Bioye97/lean4
|
1ace34638efd9913dc5991443777b01a08983289
|
bc3900cbb9adda83eed7e6affeaade7cfd07716d
|
refs/heads/master
| 1,690,589,820,211
| 1,631,051,000,000
| 1,631,067,598,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 7,740
|
lean
|
/-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.Trace
import Lean.Parser.Syntax
import Lean.Parser.Extension
import Lean.KeyedDeclsAttribute
import Lean.Elab.Exception
namespace Lean
def Syntax.prettyPrint (stx : Syntax) : Format :=
match stx.unsetTrailing.reprint with -- TODO use syntax pretty printer
| some str => format str.toFormat
| none => format stx
def MacroScopesView.format (view : MacroScopesView) (mainModule : Name) : Format :=
Std.format $
if view.scopes.isEmpty then
view.name
else if view.mainModule == mainModule then
view.scopes.foldl Name.mkNum (view.name ++ view.imported)
else
view.scopes.foldl Name.mkNum (view.name ++ view.imported ++ view.mainModule)
namespace Elab
def expandOptNamedPrio (stx : Syntax) : MacroM Nat :=
if stx.isNone then
return eval_prio default
else match stx[0] with
| `(Parser.Command.namedPrio| (priority := $prio)) => evalPrio prio
| _ => Macro.throwUnsupported
structure MacroStackElem where
before : Syntax
after : Syntax
abbrev MacroStack := List MacroStackElem
/- If `ref` does not have position information, then try to use macroStack -/
def getBetterRef (ref : Syntax) (macroStack : MacroStack) : Syntax :=
match ref.getPos? with
| some _ => ref
| none =>
match macroStack.find? (·.before.getPos? != none) with
| some elem => elem.before
| none => ref
register_builtin_option pp.macroStack : Bool := {
defValue := false
group := "pp"
descr := "dispaly macro expansion stack"
}
def addMacroStack {m} [Monad m] [MonadOptions m] (msgData : MessageData) (macroStack : MacroStack) : m MessageData := do
if !pp.macroStack.get (← getOptions) then pure msgData else
match macroStack with
| [] => pure msgData
| stack@(top::_) =>
let msgData := msgData ++ Format.line ++ "with resulting expansion" ++ indentD top.after
pure $ stack.foldl
(fun (msgData : MessageData) (elem : MacroStackElem) =>
msgData ++ Format.line ++ "while expanding" ++ indentD elem.before)
msgData
def checkSyntaxNodeKind [Monad m] [MonadEnv m] [MonadError m] (k : Name) : m Name := do
if Parser.isValidSyntaxNodeKind (← getEnv) k then pure k
else throwError "failed"
def checkSyntaxNodeKindAtNamespaces [Monad m] [MonadEnv m] [MonadError m] (k : Name) : Name → m Name
| n@(Name.str p _ _) => checkSyntaxNodeKind (n ++ k) <|> checkSyntaxNodeKindAtNamespaces k p
| Name.anonymous => checkSyntaxNodeKind k
| _ => throwError "failed"
def checkSyntaxNodeKindAtCurrentNamespaces (k : Name) : AttrM Name := do
let ctx ← read
checkSyntaxNodeKindAtNamespaces k ctx.currNamespace
def syntaxNodeKindOfAttrParam (defaultParserNamespace : Name) (stx : Syntax) : AttrM SyntaxNodeKind := do
let k ← Attribute.Builtin.getId stx
checkSyntaxNodeKindAtCurrentNamespaces k
<|>
checkSyntaxNodeKind (defaultParserNamespace ++ k)
<|>
throwError "invalid syntax node kind '{k}'"
private unsafe def evalSyntaxConstantUnsafe (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax :=
env.evalConstCheck Syntax opts `Lean.Syntax constName
@[implementedBy evalSyntaxConstantUnsafe]
constant evalSyntaxConstant (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax := throw ""
unsafe def mkElabAttribute (γ) (attrDeclName attrBuiltinName attrName : Name) (parserNamespace : Name) (typeName : Name) (kind : String)
: IO (KeyedDeclsAttribute γ) :=
KeyedDeclsAttribute.init {
builtinName := attrBuiltinName
name := attrName
descr := kind ++ " elaborator"
valueTypeName := typeName
evalKey := fun _ stx => syntaxNodeKindOfAttrParam parserNamespace stx
} attrDeclName
unsafe def mkMacroAttributeUnsafe : IO (KeyedDeclsAttribute Macro) :=
mkElabAttribute Macro `Lean.Elab.macroAttribute `builtinMacro `macro Name.anonymous `Lean.Macro "macro"
@[implementedBy mkMacroAttributeUnsafe]
constant mkMacroAttribute : IO (KeyedDeclsAttribute Macro)
builtin_initialize macroAttribute : KeyedDeclsAttribute Macro ← mkMacroAttribute
/--
Try to expand macro at syntax tree root and return macro declaration name and new syntax if successful.
Return none if all macros threw `Macro.Exception.unsupportedSyntax`.
-/
def expandMacroImpl? (env : Environment) : Syntax → MacroM (Option (Name × Syntax)) := fun stx => do
for e in macroAttribute.getEntries env stx.getKind do
try
let stx' ← e.value stx
return (e.decl, stx')
catch
| Macro.Exception.unsupportedSyntax => pure ()
| ex => throw ex
return none
class MonadMacroAdapter (m : Type → Type) where
getCurrMacroScope : m MacroScope
getNextMacroScope : m MacroScope
setNextMacroScope : MacroScope → m Unit
instance (m n) [MonadLift m n] [MonadMacroAdapter m] : MonadMacroAdapter n := {
getCurrMacroScope := liftM (MonadMacroAdapter.getCurrMacroScope : m _),
getNextMacroScope := liftM (MonadMacroAdapter.getNextMacroScope : m _),
setNextMacroScope := fun s => liftM (MonadMacroAdapter.setNextMacroScope s : m _)
}
def liftMacroM {α} {m : Type → Type} [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] [MonadResolveName m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] (x : MacroM α) : m α := do
let env ← getEnv
let currNamespace ← getCurrNamespace
let openDecls ← getOpenDecls
let methods := Macro.mkMethods {
-- TODO: record recursive expansions in info tree?
expandMacro? := fun stx => do
match (← expandMacroImpl? env stx) with
| some (_, stx) => some stx
| none => none
hasDecl := fun declName => return env.contains declName
getCurrNamespace := return currNamespace
resolveNamespace? := fun n => return ResolveName.resolveNamespace? env currNamespace openDecls n
resolveGlobalName := fun n => return ResolveName.resolveGlobalName env currNamespace openDecls n
}
match x { methods := methods
ref := ← getRef
currMacroScope := ← MonadMacroAdapter.getCurrMacroScope
mainModule := env.mainModule
currRecDepth := ← MonadRecDepth.getRecDepth
maxRecDepth := ← MonadRecDepth.getMaxRecDepth
} { macroScope := (← MonadMacroAdapter.getNextMacroScope) } with
| EStateM.Result.error Macro.Exception.unsupportedSyntax _ => throwUnsupportedSyntax
| EStateM.Result.error (Macro.Exception.error ref msg) _ => throwErrorAt ref msg
| EStateM.Result.ok a s =>
MonadMacroAdapter.setNextMacroScope s.macroScope
s.traceMsgs.reverse.forM fun (clsName, msg) => trace clsName fun _ => msg
pure a
@[inline] def adaptMacro {m : Type → Type} [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] [MonadResolveName m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] (x : Macro) (stx : Syntax) : m Syntax :=
liftMacroM (x stx)
partial def mkUnusedBaseName (baseName : Name) : MacroM Name := do
let currNamespace ← Macro.getCurrNamespace
if ← Macro.hasDecl (currNamespace ++ baseName) then
let rec loop (idx : Nat) := do
let name := baseName.appendIndexAfter idx
if ← Macro.hasDecl (currNamespace ++ name) then
loop (idx+1)
else
name
loop 1
else
return baseName
builtin_initialize
registerTraceClass `Elab
registerTraceClass `Elab.step
end Lean.Elab
|
f482d968996733a84c72518403150271d83f30da
|
7da5ceac20aaab989eeb795a4be9639982e7b35a
|
/src/category_theory/limits/shapes/pullbacks.lean
|
56d00fc3c51fa678fefdcf7b2730b45a2c1a361e
|
[
"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
| 6,993
|
lean
|
-- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import category_theory.eq_to_hom
import category_theory.limits.cones
import ...basic
open category_theory
namespace category_theory.limits
universes v u
local attribute [tidy] tactic.case_bash
@[derive decidable_eq] inductive walking_cospan : Type v
| left | right | one
@[derive decidable_eq] inductive walking_span : Type v
| zero | left | right
open walking_cospan
open walking_span
inductive walking_cospan_hom : walking_cospan → walking_cospan → Type v
| inl : walking_cospan_hom left one
| inr : walking_cospan_hom right one
| id : Π X : walking_cospan.{v}, walking_cospan_hom X X
inductive walking_span_hom : walking_span → walking_span → Type v
| fst : walking_span_hom zero left
| snd : walking_span_hom zero right
| id : Π X : walking_span.{v}, walking_span_hom X X
open walking_cospan_hom
open walking_span_hom
instance walking_cospan_category : small_category.{v+1} walking_cospan :=
{ hom := walking_cospan_hom,
id := walking_cospan_hom.id,
comp := λ X Y Z f g, match X, Y, Z, f, g with
| _, _ ,_, (id _), h := h
| _, _, _, inl, (id one) := inl
| _, _, _, inr, (id one) := inr
end }
instance walking_span_category : small_category.{v+1} walking_span :=
{ hom := walking_span_hom,
id := walking_span_hom.id,
comp := λ X Y Z f g, match X, Y, Z, f, g with
| _, _ ,_, (id _), h := h
| _, _, _, fst, (id left) := fst
| _, _, _, snd, (id right) := snd
end }
lemma walking_cospan_hom_id (X : walking_cospan.{v}) : walking_cospan_hom.id X = 𝟙 X := rfl
lemma walking_span_hom_id (X : walking_span.{v}) : walking_span_hom.id X = 𝟙 X := rfl
variables {C : Type u} [𝒞 : category.{v+1} C]
include 𝒞
def cospan {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : walking_cospan.{v} ⥤ C :=
{ obj := λ x, match x with
| left := X
| right := Y
| one := Z
end,
map := λ x y h, match x, y, h with
| _, _, (id _) := 𝟙 _
| _, _, inl := f
| _, _, inr := g
end }
def span {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : walking_span.{v} ⥤ C :=
{ obj := λ x, match x with
| zero := X
| left := Y
| right := Z
end,
map := λ x y h, match x, y, h with
| _, _, (id _) := 𝟙 _
| _, _, fst := f
| _, _, snd := g
end }
@[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
@[simp] 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
@[simp] 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
variables {X Y Z : C}
attribute [simp] walking_cospan_hom_id walking_span_hom_id
section pullback
def square (f : X ⟶ Z) (g : Y ⟶ Z) := cone (cospan f g)
variables {f : X ⟶ Z} {g : Y ⟶ Z}
def square.π₁ (t : square f g) : t.X ⟶ X := t.π.app left
def square.π₂ (t : square f g) : t.X ⟶ Y := t.π.app right
def square.mk {W : C} (π₁ : W ⟶ X) (π₂ : W ⟶ Y)
(eq : π₁ ≫ f = π₂ ≫ g) :
square f g :=
{ X := W,
π :=
{ app := λ j, walking_cospan.cases_on j π₁ π₂ (π₁ ≫ f),
naturality' := λ j j' f, by cases f; obviously } }
def square.condition (t : square f g) : (square.π₁ t) ≫ f = (square.π₂ t) ≫ g :=
begin
erw [t.w inl, ← t.w inr], refl
end
end pullback
section pushout
def cosquare (f : X ⟶ Y) (g : X ⟶ Z) := cocone (span f g)
variables {f : X ⟶ Y} {g : X ⟶ Z}
def cosquare.ι₁ (t : cosquare f g) : Y ⟶ t.X := t.ι.app left
def cosquare.ι₂ (t : cosquare f g) : Z ⟶ t.X := t.ι.app right
def cosquare.mk {W : C} (ι₁ : Y ⟶ W) (ι₂ : Z ⟶ W)
(eq : f ≫ ι₁ = g ≫ ι₂) :
cosquare f g :=
{ X := W,
ι :=
{ app := λ j, walking_span.cases_on j (f ≫ ι₁) ι₁ ι₂,
naturality' := λ j j' f, by cases f; obviously } }
def cosquare.condition (t : cosquare f g) : f ≫ (cosquare.ι₁ t) = g ≫ (cosquare.ι₂ t) :=
begin
erw [t.w fst, ← t.w snd], refl
end
end pushout
def cone.of_square
{F : walking_cospan.{v} ⥤ C} (t : square (F.map inl) (F.map inr)) : cone F :=
{ X := t.X,
π :=
{ app := λ X, t.π.app X ≫ eq_to_hom (by tidy),
naturality' := λ j j' g,
begin
cases j; cases j'; cases g; dsimp; simp,
erw ← t.w inl, refl,
erw ← t.w inr, refl,
end } }.
@[simp] lemma cone.of_square_π
{F : walking_cospan.{v} ⥤ C} (t : square (F.map inl) (F.map inr)) (j):
(cone.of_square t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl
def cocone.of_cosquare
{F : walking_span.{v} ⥤ C} (t : cosquare (F.map fst) (F.map snd)) : cocone F :=
{ X := t.X,
ι :=
{ app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X,
naturality' := λ j j' g,
begin
cases j; cases j'; cases g; dsimp; simp,
erw ← t.w fst, refl,
erw ← t.w snd, refl,
end } }.
@[simp] lemma cocone.of_cosquare_ι
{F : walking_span.{v} ⥤ C} (t : cosquare (F.map fst) (F.map snd)) (j):
(cocone.of_cosquare t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl
def square.of_cone
{F : walking_cospan.{v} ⥤ C} (t : cone F) : square (F.map inl) (F.map inr) :=
{ X := t.X,
π :=
{ app := λ j, t.π.app j ≫ eq_to_hom (by tidy) } }
@[simp] lemma square.of_cone_π {F : walking_cospan.{v} ⥤ C} (t : cone F) (j) :
(square.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl
def cosquare.of_cocone
{F : walking_span.{v} ⥤ C} (t : cocone F) : cosquare (F.map fst) (F.map snd) :=
{ X := t.X,
ι :=
{ app := λ j, eq_to_hom (by tidy) ≫ t.ι.app j } }
@[simp] lemma cosquare.of_cocone_ι {F : walking_span.{v} ⥤ C} (t : cocone F) (j) :
(cosquare.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl
end category_theory.limits
|
d9d05eadcefd70287baf98290b09ebdf66e061b6
|
ed27983dd289b3bcad416f0b1927105d6ef19db8
|
/src/inClassNotes/higherOrderFunctions/composeTest.lean
|
7378aa578a2e9e105bd4effc49088a453adc2bf6
|
[] |
no_license
|
liuxin-James/complogic-s21
|
0d55b76dbe25024473d31d98b5b83655c365f811
|
13e03e0114626643b44015c654151fb651603486
|
refs/heads/master
| 1,681,109,264,463
| 1,618,848,261,000
| 1,618,848,261,000
| 337,599,491
| 0
| 0
| null | 1,613,141,619,000
| 1,612,925,555,000
| null |
UTF-8
|
Lean
| false
| false
| 4,614
|
lean
|
/-
Let's build up to notion of
higher-order functions.
-/
namespace hidden
-- Increment functions
def inc (n : nat) := n + 1
def sqr (n : nat) := n * n
def incThenSqr (n : nat) := sqr (inc n)
/-
36 <-- sqr <-- inc <-- 5
Think of data flowing right to left
through a composition of functions:
given n (on the right) first send it
through inc, then send that result
"to the left" through sqr.
-/
def sqrThenInc (n : nat) := inc (sqr n)
/-
26 <-- inc <-- sqr <-- 5
-/
#eval incThenSqr 5
#eval sqrThenInc 5
/-
A diagram of the evaluation order
36 <-- (sqr <-- (inc <-- 5))
26 <-- (inc <-- (sqr <-- 5))
-/
/-
Regrouping parenthesis tells us that
sending the input through two functions
right to left is equivalent to running
it through a single function, one that
"combines" the effects of the two.
36 <-- (sqr <-- inc) <-- 5)
^^^^^^^^^^^^^
a function
26 <-- (inc <-- sqr) <-- 5)
^^^^^^^^^^^^^
a function
-/
/-
36 <-- (compose sqr inc) <-- 5)
26 <-- (compose inc sqr) <-- 5)
^^^^^^^^^^^^^^^^^
a function
-/
/-
36 <-- (compose sqr inc) <-- 5)
26 <-- (compose inc sqr) <-- 5)
^^^^^^^
higher-order function
-/
/-
Remember that a lambda term is
a literal value that represents
a function. What's special about
the form of data is that it can
be *applied* to an argument to
produce a result.
A higher-order function is just
a function that takes a lambda
term (aka "a function") as an
argument and/or returns one as
a result. In particular, we will
often want to define functions
that not only take "functions"
as arguments but that return
new functions as results, where
the new functions, *when applied*
use given functions to compute
results.
Such a higher-order function is a
machine that takes smaller data
consuming and producing machines
(functions) and combines them into
larger/new data consuming and
producing machines. Composition
of functions is a special case in
which a new function is returned
that, when applied to an argument,
applies each of the given functions
in turn.
-/
/-
36 <-- (sqr ∘ inc) <-- 5)
26 <-- (inc ∘ sqr) <-- 5)
-/
/-
Can we write a function that
takes two smaller functions,
f and g, and that returns a
function, (g ∘ f), that first
applies f to its argument and
then applies g to that result?
Let's try this for the special
case of two argument functions,
such as sqr and inc, each being
of type nat → nat.
-/
def compose_nat_nat (g f: ℕ → ℕ) :
(ℕ → ℕ) :=
_
-- let's test it out
#eval (compose_nat_nat sqr inc) 5
-- ^^^^^^^^^^^^^^^^^^^^^^^^^ function!
def sqrinc := compose_nat_nat sqr inc
#eval sqrinc 5
#eval (compose_nat_nat inc sqr) 5
def incsqr := compose_nat_nat inc sqr
#eval incsrq 5
/-
Suppose we want to compose functions
that have different types. The return
type of one has to match the argument
type of the next one in the pipeline.
Parametric polymorphism to the rescue.
-/
def compose_α_β_φ { α β φ : Type }
(g : β → φ) (f: α → β) : α → φ :=
_
#eval (compose_α_β_φ sqr string.length) "Hello!"
/-
The previous version works great as
long as the functions all takes values
of types, α, β, and φ, of type Type.
But in general, we'll want a function
that can operate on functions that
take arguments and that return results
in arbitrary type universes. So here,
then is the most general form of our
higher-order compose function.
-/
universes u₁ u₂ u₃ -- plural of universe
def compose
{α : Type u₁}
{β : Type u₂}
{φ : Type u₃}
(g : β → φ)
(f: α → β) :
α → φ :=
fun a, g (f a)
/-
Return a *function* that takes
one argument, a, and returns the
result of applying g to the result
of applying f to a.
-/
def incThenSqr' := compose sqr inc
def sqrThenInc' := compose inc sqr
def sqrlen := compose sqr string.length
#eval incThenSqr' 5 -- expect 36
#eval incThenSqr 5 -- expect 26
#eval sqrlen "Hello!"
/-
Lean implements function composition
as function.comp, with ∘ as an infix
notation for this binary operation.
-/
#check function.comp
#check @function.comp
/-
function.comp :
Π {α : Sort u_1} {β : Sort u_2} {φ : Sort u_3},
(β → φ) → (α → β) → α → φ
-/
/-
Prop (Sort 0) -- logic
Type (Type 0) Sort 1 -- computation
Type 1 Sort 2
Type 2 Sort 3
etc
-/
universes u₁ u₂ u₃
-- introduce some local assumptions
variables (f : Sort u₁ → Sort u₂) (g : Sort u₂ → Sort u₃)
#check function.comp g f
#check g ∘ f
end hidden
|
f7ae0b36b424e10ba368275ef13968175bac129e
|
cf39355caa609c0f33405126beee2739aa3cb77e
|
/tests/lean/run/sec_var.lean
|
d4ab3b30e45a36b1d7326b3947f0b6a699468e0a
|
[
"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
| 545
|
lean
|
section
parameter A : Type
definition foo : ∀ ⦃ a b : A ⦄, a = b → a = b :=
assume a b H, H
variable a : A
set_option pp.implicit true
#check foo (eq.refl a)
#check foo
#check foo = (λ (a b : A) (H : a = b), H)
end
#check foo = (λ (A : Type) (a b : A) (H : a = b), H)
section
variable A : Type
definition foo2 : ∀ ⦃ a b : A ⦄, a = b → a = b :=
assume a b H, H
variable a : A
set_option pp.implicit true
#check foo2 A (eq.refl a)
#check foo2
#check foo2 A = (λ (a b : A) (H : a = b), H)
end
|
a7d486b6e62b0a52e225be248d9e70b4da246350
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/src/order/category/HeytAlg.lean
|
bc4663ab9a5eace53fcb86cae5fee906bca9cdc1
|
[
"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,863
|
lean
|
/-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import order.category.BddDistLat
import order.heyting.hom
/-!
# The category of Heyting algebras
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines `HeytAlg`, the category of Heyting algebras.
-/
universes u
open category_theory opposite order
/-- The category of Heyting algebras. -/
def HeytAlg := bundled heyting_algebra
namespace HeytAlg
instance : has_coe_to_sort HeytAlg Type* := bundled.has_coe_to_sort
instance (X : HeytAlg) : heyting_algebra X := X.str
/-- Construct a bundled `HeytAlg` from a `heyting_algebra`. -/
def of (α : Type*) [heyting_algebra α] : HeytAlg := bundled.of α
@[simp] lemma coe_of (α : Type*) [heyting_algebra α] : ↥(of α) = α := rfl
instance : inhabited HeytAlg := ⟨of punit⟩
instance bundled_hom : bundled_hom heyting_hom :=
{ to_fun := λ α β [heyting_algebra α] [heyting_algebra β],
by exactI (coe_fn : heyting_hom α β → α → β),
id := heyting_hom.id,
comp := @heyting_hom.comp,
hom_ext := λ α β [heyting_algebra α] [heyting_algebra β], by exactI fun_like.coe_injective }
attribute [derive [large_category, concrete_category]] HeytAlg
@[simps]
instance has_forget_to_Lat : has_forget₂ HeytAlg BddDistLat :=
{ forget₂ := { obj := λ X, BddDistLat.of X,
map := λ X Y f, (f : bounded_lattice_hom X Y) } }
/-- Constructs an isomorphism of Heyting algebras from an order isomorphism between them. -/
@[simps] def iso.mk {α β : HeytAlg.{u}} (e : α ≃o β) : α ≅ β :=
{ hom := e,
inv := e.symm,
hom_inv_id' := by { ext, exact e.symm_apply_apply _ },
inv_hom_id' := by { ext, exact e.apply_symm_apply _ } }
end HeytAlg
|
78dc46085c51d1135e9b1cd4e266861b89694dd8
|
491068d2ad28831e7dade8d6dff871c3e49d9431
|
/tests/lean/run/print_poly.lean
|
3cdfe4193aa2b01b2e38f1f4115810cd9b56239f
|
[
"Apache-2.0"
] |
permissive
|
davidmueller13/lean
|
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
|
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
|
refs/heads/master
| 1,611,278,313,401
| 1,444,021,177,000
| 1,444,021,177,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 263
|
lean
|
import data.nat
open nat
print pp.max_depth
print +
print -
print nat
print nat.zero
print nat.add
print nat.rec
print classical.em
print quot.lift
print nat.of_num
print nat.add.assoc
section
parameter {A : Type}
variable {a : A}
print A
print a
end
|
8fd75b9a255f8ed4e00c6c31e75606603e33b848
|
fa02ed5a3c9c0adee3c26887a16855e7841c668b
|
/src/tactic/scc.lean
|
b8be135fbdd2c9a66a75223099fbc9a30e0a662c
|
[
"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
| 13,493
|
lean
|
/-
Copyright (c) 2018 Simon Hudon All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
Tactics based on the strongly connected components (SCC) of a graph where
the vertices are propositions and the edges are implications found
in the context.
They are used for finding the sets of equivalent propositions in a set
of implications.
-/
import tactic.tauto
import data.sum
/-!
# Strongly Connected Components
This file defines tactics to construct proofs of equivalences between a set of mutually equivalent
propositions. The tactics use implications transitively to find sets of equivalent propositions.
## Implementation notes
The tactics use a strongly connected components algorithm on a graph where propositions are
vertices and edges are proofs that the source implies the target. The strongly connected components
are therefore sets of propositions that are pairwise equivalent to each other.
The resulting strongly connected components are encoded in a disjoint set data structure to
facilitate the construction of equivalence proofs between two arbitrary members of an equivalence
class.
## Possible generalizations
Instead of reasoning about implications and equivalence, we could generalize the machinery to
reason about arbitrary partial orders.
## References
* Tarjan, R. E. (1972), "Depth-first search and linear graph algorithms",
SIAM Journal on Computing, 1 (2): 146–160, doi:10.1137/0201010
* Dijkstra, Edsger (1976), A Discipline of Programming, NJ: Prentice Hall, Ch. 25.
* <https://en.wikipedia.org/wiki/Disjoint-set_data_structure>
## Tags
graphs, tactic, strongly connected components, disjoint sets
-/
namespace tactic
/--
`closure` implements a disjoint set data structure using path compression
optimization. For the sake of the scc algorithm, it also stores the preorder
numbering of the equivalence graph of the local assumptions.
The `expr_map` encodes a directed forest by storing for every non-root
node, a reference to its parent and a proof of equivalence between
that node's expression and its parent's expression. Given that data
structure, checking that two nodes belong to the same tree is easy and
fast by repeatedly following the parent references until a root is reached.
If both nodes have the same root, they belong to the same tree, i.e. their
expressions are equivalent. The proof of equivalence can be formed by
composing the proofs along the edges of the paths to the root.
More concretely, if we ignore preorder numbering, the set
`{ {e₀,e₁,e₂,e₃}, {e₄,e₅} }` is represented as:
```
e₀ → ⊥ -- no parent, i.e. e₀ is a root
e₁ → e₀, p₁ -- with p₁ : e₁ ↔ e₀
e₂ → e₁, p₂ -- with p₂ : e₂ ↔ e₁
e₃ → e₀, p₃ -- with p₃ : e₃ ↔ e₀
e₄ → ⊥ -- no parent, i.e. e₄ is a root
e₅ → e₄, p₅ -- with p₅ : e₅ ↔ e₄
```
We can check that `e₂` and `e₃` are equivalent by seeking the root of
the tree of each. The parent of `e₂` is `e₁`, the parent of `e₁` is
`e₀` and `e₀` does not have a parent, and thus, this is the root of its tree.
The parent of `e₃` is `e₀` and it's also the root, the same as for `e₂` and
they are therefore equivalent. We can build a proof of that equivalence by using
transitivity on `p₂`, `p₁` and `p₃.symm` in that order.
Similarly, we can discover that `e₂` and `e₅` aren't equivalent.
A description of the path compression optimization can be found at:
<https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Path_compression>
-/
meta def closure := ref (expr_map (ℕ ⊕ (expr × expr)))
namespace closure
/-- `with_new_closure f` creates an empty `closure` `c`, executes `f` on `c`, and then deletes `c`,
returning the output of `f`. -/
meta def with_new_closure {α} : (closure → tactic α) → tactic α :=
using_new_ref (expr_map.mk _)
/-- `to_tactic_format cl` pretty-prints the `closure` `cl` as a list. Assuming `cl` was built by
`dfs_at`, each element corresponds to a node `pᵢ : expr` and is one of the folllowing:
- if `pᵢ` is a root: `"pᵢ ⇐ i"`, where `i` is the preorder number of `pᵢ`,
- otherwise: `"(pᵢ, pⱼ) : P"`, where `P` is `pᵢ ↔ pⱼ`.
Useful for debugging. -/
meta def to_tactic_format (cl : closure) : tactic format :=
do m ← read_ref cl,
let l := m.to_list,
fmt ← l.mmap $ λ ⟨x,y⟩, match y with
| sum.inl y := pformat!"{x} ⇐ {y}"
| sum.inr ⟨y,p⟩ := pformat!"({x}, {y}) : {infer_type p}"
end,
pure $ to_fmt fmt
meta instance : has_to_tactic_format closure := ⟨ to_tactic_format ⟩
/-- `(n,r,p) ← root cl e` returns `r` the root of the tree that `e` is a part of (which might be
itself) along with `p` a proof of `e ↔ r` and `n`, the preorder numbering of the root. -/
meta def root (cl : closure) : expr → tactic (ℕ × expr × expr) | e :=
do m ← read_ref cl,
match m.find e with
| none :=
do p ← mk_app ``iff.refl [e],
pure (0,e,p)
| (some (sum.inl n)) :=
do p ← mk_app ``iff.refl [e],
pure (n,e,p)
| (some (sum.inr (e₀,p₀))) :=
do (n,e₁,p₁) ← root e₀,
p ← mk_app ``iff.trans [p₀,p₁],
modify_ref cl $ λ m, m.insert e (sum.inr (e₁,p)),
pure (n,e₁,p)
end
/-- (Implementation of `merge`.) -/
meta def merge_intl (cl : closure) (p e₀ p₀ e₁ p₁ : expr) : tactic unit :=
do p₂ ← mk_app ``iff.symm [p₀],
p ← mk_app ``iff.trans [p₂,p],
p ← mk_app ``iff.trans [p,p₁],
modify_ref cl $ λ m, m.insert e₀ $ sum.inr (e₁,p)
/-- `merge cl p`, with `p` a proof of `e₀ ↔ e₁` for some `e₀` and `e₁`,
merges the trees of `e₀` and `e₁` and keeps the root with the smallest preorder
number as the root. This ensures that, in the depth-first traversal of the graph,
when encountering an edge going into a vertex whose equivalence class includes
a vertex that originated the current search, that vertex will be the root of
the corresponding tree. -/
meta def merge (cl : closure) (p : expr) : tactic unit :=
do `(%%e₀ ↔ %%e₁) ← infer_type p >>= instantiate_mvars,
(n₂,e₂,p₂) ← root cl e₀,
(n₃,e₃,p₃) ← root cl e₁,
if e₂ ≠ e₃ then do
if n₂ < n₃ then do p ← mk_app ``iff.symm [p],
cl.merge_intl p e₃ p₃ e₂ p₂
else cl.merge_intl p e₂ p₂ e₃ p₃
else pure ()
/-- Sequentially assign numbers to the nodes of the graph as they are being visited. -/
meta def assign_preorder (cl : closure) (e : expr) : tactic unit :=
modify_ref cl $ λ m, m.insert e (sum.inl m.size)
/-- `prove_eqv cl e₀ e₁` constructs a proof of equivalence of `e₀` and `e₁` if
they are equivalent. -/
meta def prove_eqv (cl : closure) (e₀ e₁ : expr) : tactic expr :=
do (_,r,p₀) ← root cl e₀,
(_,r',p₁) ← root cl e₁,
guard (r = r') <|> fail!"{e₀} and {e₁} are not equivalent",
p₁ ← mk_app ``iff.symm [p₁],
mk_app ``iff.trans [p₀,p₁]
/-- `prove_impl cl e₀ e₁` constructs a proof of `e₀ -> e₁` if they are equivalent. -/
meta def prove_impl (cl : closure) (e₀ e₁ : expr) : tactic expr :=
cl.prove_eqv e₀ e₁ >>= iff_mp
/-- `is_eqv cl e₀ e₁` checks whether `e₀` and `e₁` are equivalent without building a proof. -/
meta def is_eqv (cl : closure) (e₀ e₁ : expr) : tactic bool :=
do (_,r,p₀) ← root cl e₀,
(_,r',p₁) ← root cl e₁,
return $ r = r'
end closure
/-- mutable graphs between local propositions that imply each other with the proof of implication -/
@[reducible]
meta def impl_graph := ref (expr_map (list $ expr × expr))
/-- `with_impl_graph f` creates an empty `impl_graph` `g`, executes `f` on `g`, and then deletes
`g`, returning the output of `f`. -/
meta def with_impl_graph {α} : (impl_graph → tactic α) → tactic α :=
using_new_ref (expr_map.mk (list $ expr × expr))
namespace impl_graph
/-- `add_edge g p`, with `p` a proof of `v₀ → v₁` or `v₀ ↔ v₁`, adds an edge to the implication
graph `g`. -/
meta def add_edge (g : impl_graph) : expr → tactic unit | p :=
do t ← infer_type p,
match t with
| `(%%v₀ → %%v₁) :=
do is_prop v₀ >>= guardb,
is_prop v₁ >>= guardb,
m ← read_ref g,
let xs := (m.find v₀).get_or_else [],
let xs' := (m.find v₁).get_or_else [],
modify_ref g $ λ m, (m.insert v₀ ((v₁,p) :: xs)).insert v₁ xs'
| `(%%v₀ ↔ %%v₁) :=
do p₀ ← mk_mapp ``iff.mp [none,none,p],
p₁ ← mk_mapp ``iff.mpr [none,none,p],
add_edge p₀, add_edge p₁
| _ := failed
end
section scc
open list
parameter g : expr_map (list $ expr × expr)
parameter visit : ref $ expr_map bool
parameter cl : closure
/-- `merge_path path e`, where `path` and `e` forms a cycle with proofs of implication between
consecutive vertices. The proofs are compiled into proofs of equivalences and added to the closure
structure. `e` and the first vertex of `path` do not have to be the same but they have to be
in the same equivalence class. -/
meta def merge_path (path : list (expr × expr)) (e : expr) : tactic unit :=
do p₁ ← cl.prove_impl e path.head.fst,
p₂ ← mk_mapp ``id [e],
let path := (e,p₁) :: path,
(_,ls) ← path.mmap_accuml (λ p p',
prod.mk <$> mk_mapp ``implies.trans [none,p'.1,none,p,p'.2] <*> pure p) p₂,
(_,rs) ← path.mmap_accumr (λ p p',
prod.mk <$> mk_mapp ``implies.trans [none,none,none,p.2,p'] <*> pure p') p₂,
ps ← mzip_with (λ p₀ p₁, mk_app ``iff.intro [p₀,p₁]) ls.tail rs.init,
ps.mmap' cl.merge
/-- (implementation of `collapse`) -/
meta def collapse' : list (expr × expr) → list (expr × expr) → expr → tactic unit
| acc [] v := merge_path acc v
| acc ((x,pr) :: xs) v :=
do b ← cl.is_eqv x v,
let acc' := (x,pr)::acc,
if b
then merge_path acc' v
else collapse' acc' xs v
/-- `collapse path v`, where `v` is a vertex that originated the current search
(or a vertex in the same equivalence class as the one that originated the current search).
It or its equivalent should be found in `path`. Since the vertices following `v` in the path
form a cycle with `v`, they can all be added to an equivalence class. -/
meta def collapse : list (expr × expr) → expr → tactic unit :=
collapse' []
/--
Strongly connected component algorithm inspired by Tarjan's and
Dijkstra's scc algorithm. Whereas they return strongly connected
components by enumerating them, this algorithm returns a disjoint set
data structure using path compression. This is a compact
representation that allows us, after the fact, to construct a proof of
equivalence between any two members of an equivalence class.
* Tarjan, R. E. (1972), "Depth-first search and linear graph algorithms",
SIAM Journal on Computing, 1 (2): 146–160, doi:10.1137/0201010
* Dijkstra, Edsger (1976), A Discipline of Programming, NJ: Prentice Hall, Ch. 25.
-/
meta def dfs_at :
list (expr × expr) → expr → tactic unit
| vs v :=
do m ← read_ref visit,
(_,v',_) ← cl.root v,
match m.find v' with
| (some tt) :=
pure ()
| (some ff) :=
collapse vs v
| none :=
do cl.assign_preorder v,
modify_ref visit $ λ m, m.insert v ff,
ns ← g.find v,
ns.mmap' $ λ ⟨w,e⟩, dfs_at ((v,e) :: vs) w,
modify_ref visit $ λ m, m.insert v tt,
pure ()
end
end scc
/-- Use the local assumptions to create a set of equivalence classes. -/
meta def mk_scc (cl : closure) : tactic (expr_map (list (expr × expr))) :=
with_impl_graph $ λ g,
using_new_ref (expr_map.mk bool) $ λ visit,
do ls ← local_context,
ls.mmap' $ λ l, try (g.add_edge l),
m ← read_ref g,
m.to_list.mmap $ λ ⟨v,_⟩, impl_graph.dfs_at m visit cl [] v,
pure m
end impl_graph
meta def prove_eqv_target (cl : closure) : tactic unit :=
do `(%%p ↔ %%q) ← target >>= whnf,
cl.prove_eqv p q >>= exact
/--
`scc` uses the available equivalences and implications to prove
a goal of the form `p ↔ q`.
```lean
example (p q r : Prop) (hpq : p → q) (hqr : q ↔ r) (hrp : r → p) : p ↔ r :=
by scc
```
-/
meta def interactive.scc : tactic unit :=
closure.with_new_closure $ λ cl,
do impl_graph.mk_scc cl,
`(%%p ↔ %%q) ← target,
cl.prove_eqv p q >>= exact
/-- Collect all the available equivalences and implications and
add assumptions for every equivalence that can be proven using the
strongly connected components technique. Mostly useful for testing. -/
meta def interactive.scc' : tactic unit :=
closure.with_new_closure $ λ cl,
do m ← impl_graph.mk_scc cl,
let ls := m.to_list.map prod.fst,
let ls' := prod.mk <$> ls <*> ls,
ls'.mmap' $ λ x,
do { h ← get_unused_name `h,
try $ closure.prove_eqv cl x.1 x.2 >>= note h none }
/--
`scc` uses the available equivalences and implications to prove
a goal of the form `p ↔ q`.
```lean
example (p q r : Prop) (hpq : p → q) (hqr : q ↔ r) (hrp : r → p) : p ↔ r :=
by scc
```
The variant `scc'` populates the local context with all equivalences that `scc` is able to prove.
This is mostly useful for testing purposes.
-/
add_tactic_doc
{ name := "scc",
category := doc_category.tactic,
decl_names := [``interactive.scc, ``interactive.scc'],
tags := ["logic"] }
end tactic
|
a7d442d583d179a0418b81bce8e141677acdc319
|
4727251e0cd73359b15b664c3170e5d754078599
|
/src/ring_theory/laurent_series.lean
|
a4b55ca32c77af5d95c1497ee133c8db92184729
|
[
"Apache-2.0"
] |
permissive
|
Vierkantor/mathlib
|
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
|
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
|
refs/heads/master
| 1,658,323,012,449
| 1,652,256,003,000
| 1,652,256,003,000
| 209,296,341
| 0
| 1
|
Apache-2.0
| 1,568,807,655,000
| 1,568,807,655,000
| null |
UTF-8
|
Lean
| false
| false
| 8,474
|
lean
|
/-
Copyright (c) 2021 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import ring_theory.hahn_series
import ring_theory.localization.fraction_ring
/-!
# Laurent Series
## Main Definitions
* Defines `laurent_series` as an abbreviation for `hahn_series ℤ`.
* Provides a coercion `power_series R` into `laurent_series R` given by
`hahn_series.of_power_series`.
* Defines `laurent_series.power_series_part`
* Defines the localization map `laurent_series.of_power_series_localization` which evaluates to
`hahn_series.of_power_series`.
-/
open hahn_series
open_locale big_operators classical polynomial
noncomputable theory
universe u
/-- A `laurent_series` is implemented as a `hahn_series` with value group `ℤ`. -/
abbreviation laurent_series (R : Type*) [has_zero R] := hahn_series ℤ R
variables {R : Type u}
namespace laurent_series
section semiring
variable [semiring R]
instance : has_coe (power_series R) (laurent_series R) :=
⟨hahn_series.of_power_series ℤ R⟩
lemma coe_power_series (x : power_series R) : (x : laurent_series R) =
hahn_series.of_power_series ℤ R x := rfl
@[simp] lemma coeff_coe_power_series (x : power_series R) (n : ℕ) :
hahn_series.coeff (x : laurent_series R) n = power_series.coeff R n x :=
by rw [← int.nat_cast_eq_coe_nat, coe_power_series, of_power_series_apply_coeff]
/-- This is a power series that can be multiplied by an integer power of `X` to give our
Laurent series. If the Laurent series is nonzero, `power_series_part` has a nonzero
constant term. -/
def power_series_part (x : laurent_series R) : power_series R :=
power_series.mk (λ n, x.coeff (x.order + n))
@[simp] lemma power_series_part_coeff (x : laurent_series R) (n : ℕ) :
power_series.coeff R n x.power_series_part = x.coeff (x.order + n) :=
power_series.coeff_mk _ _
@[simp] lemma power_series_part_zero : power_series_part (0 : laurent_series R) = 0 :=
by { ext, simp }
@[simp] lemma power_series_part_eq_zero (x : laurent_series R) :
x.power_series_part = 0 ↔ x = 0 :=
begin
split,
{ contrapose!,
intro h,
rw [power_series.ext_iff, not_forall],
refine ⟨0, _⟩,
simp [coeff_order_ne_zero h] },
{ rintro rfl,
simp }
end
@[simp] lemma single_order_mul_power_series_part (x : laurent_series R) :
(single x.order 1 : laurent_series R) * x.power_series_part = x :=
begin
ext n,
rw [← sub_add_cancel n x.order, single_mul_coeff_add, sub_add_cancel, one_mul],
by_cases h : x.order ≤ n,
{ rw [int.eq_nat_abs_of_zero_le (sub_nonneg_of_le h), coeff_coe_power_series,
power_series_part_coeff, ← int.eq_nat_abs_of_zero_le (sub_nonneg_of_le h),
add_sub_cancel'_right] },
{ rw [coe_power_series, of_power_series_apply, emb_domain_notin_range],
{ contrapose! h,
exact order_le_of_coeff_ne_zero h.symm },
{ contrapose! h,
simp only [set.mem_range, rel_embedding.coe_fn_mk, function.embedding.coe_fn_mk,
int.nat_cast_eq_coe_nat] at h,
obtain ⟨m, hm⟩ := h,
rw [← sub_nonneg, ← hm],
exact int.zero_le_of_nat _ } }
end
lemma of_power_series_power_series_part (x : laurent_series R) :
of_power_series ℤ R x.power_series_part = single (-x.order) 1 * x :=
begin
refine eq.trans _ (congr rfl x.single_order_mul_power_series_part),
rw [← mul_assoc, single_mul_single, neg_add_self, mul_one, ← C_apply, C_one, one_mul,
coe_power_series],
end
end semiring
instance [comm_semiring R] : algebra (power_series R) (laurent_series R) :=
(hahn_series.of_power_series ℤ R).to_algebra
@[simp] lemma coe_algebra_map [comm_semiring R] :
⇑(algebra_map (power_series R) (laurent_series R)) = hahn_series.of_power_series ℤ R :=
rfl
/-- The localization map from power series to Laurent series. -/
@[simps] instance of_power_series_localization [comm_ring R] :
is_localization (submonoid.powers (power_series.X : power_series R)) (laurent_series R) :=
{ map_units := (begin rintro ⟨_, n, rfl⟩,
refine ⟨⟨single (n : ℤ) 1, single (-n : ℤ) 1, _, _⟩, _⟩,
{ simp only [single_mul_single, mul_one, add_right_neg],
refl },
{ simp only [single_mul_single, mul_one, add_left_neg],
refl },
{ simp } end),
surj := (begin intro z,
by_cases h : 0 ≤ z.order,
{ refine ⟨⟨power_series.X ^ (int.nat_abs z.order) * power_series_part z, 1⟩, _⟩,
simp only [ring_hom.map_one, mul_one, ring_hom.map_mul, coe_algebra_map,
of_power_series_X_pow, submonoid.coe_one, int.nat_cast_eq_coe_nat],
rw [int.nat_abs_of_nonneg h, ← coe_power_series, single_order_mul_power_series_part] },
{ refine ⟨⟨power_series_part z, power_series.X ^ (int.nat_abs z.order), ⟨_, rfl⟩⟩, _⟩,
simp only [coe_algebra_map, of_power_series_power_series_part],
rw [mul_comm _ z],
refine congr rfl _,
rw [subtype.coe_mk, of_power_series_X_pow,
int.nat_cast_eq_coe_nat, int.of_nat_nat_abs_of_nonpos],
exact le_of_not_ge h } end),
eq_iff_exists := (begin intros x y,
rw [coe_algebra_map, of_power_series_injective.eq_iff],
split,
{ rintro rfl,
exact ⟨1, rfl⟩ },
{ rintro ⟨⟨_, n, rfl⟩, hc⟩,
rw [← sub_eq_zero, ← sub_mul, power_series.ext_iff] at hc,
rw [← sub_eq_zero, power_series.ext_iff],
intro m,
have h := hc (m + n),
rw [linear_map.map_zero, subtype.coe_mk, power_series.X_pow_eq, power_series.monomial,
power_series.coeff, finsupp.single_add, mv_power_series.coeff_add_mul_monomial,
mul_one] at h,
exact h } end) }
instance {K : Type u} [field K] : is_fraction_ring (power_series K) (laurent_series K) :=
is_localization.of_le (submonoid.powers (power_series.X : power_series K)) _
(powers_le_non_zero_divisors_of_no_zero_divisors power_series.X_ne_zero)
(λ f hf, is_unit_of_mem_non_zero_divisors $ map_mem_non_zero_divisors _
hahn_series.of_power_series_injective hf)
end laurent_series
namespace power_series
open laurent_series
variables {R' : Type*} [semiring R] [ring R'] (f g : power_series R) (f' g' : power_series R')
@[simp, norm_cast] lemma coe_zero : ((0 : power_series R) : laurent_series R) = 0 :=
(of_power_series ℤ R).map_zero
@[simp, norm_cast] lemma coe_one : ((1 : power_series R) : laurent_series R) = 1 :=
(of_power_series ℤ R).map_one
@[simp, norm_cast] lemma coe_add : ((f + g : power_series R) : laurent_series R) = f + g :=
(of_power_series ℤ R).map_add _ _
@[simp, norm_cast] lemma coe_sub : ((f' - g' : power_series R') : laurent_series R') = f' - g' :=
(of_power_series ℤ R').map_sub _ _
@[simp, norm_cast] lemma coe_neg : ((-f' : power_series R') : laurent_series R') = -f' :=
(of_power_series ℤ R').map_neg _
@[simp, norm_cast] lemma coe_mul : ((f * g : power_series R) : laurent_series R) = f * g :=
(of_power_series ℤ R).map_mul _ _
lemma coeff_coe (i : ℤ) :
((f : power_series R) : laurent_series R).coeff i =
if i < 0 then 0 else power_series.coeff R i.nat_abs f :=
begin
cases i,
{ rw [int.nat_abs_of_nat_core, int.of_nat_eq_coe, coeff_coe_power_series,
if_neg (int.coe_nat_nonneg _).not_lt] },
{ rw [coe_power_series, of_power_series_apply, emb_domain_notin_image_support,
if_pos (int.neg_succ_lt_zero _)],
simp only [not_exists, rel_embedding.coe_fn_mk, set.mem_image, not_and,
function.embedding.coe_fn_mk, ne.def, to_power_series_symm_apply_coeff, mem_support,
int.nat_cast_eq_coe_nat, int.coe_nat_eq, implies_true_iff, not_false_iff] }
end
@[simp, norm_cast] lemma coe_C (r : R) : ((C R r : power_series R) : laurent_series R) =
hahn_series.C r :=
of_power_series_C _
@[simp] lemma coe_X : ((X : power_series R) : laurent_series R) = single 1 1 :=
of_power_series_X
@[simp, norm_cast] lemma coe_smul {S : Type*} [semiring S] [module R S]
(r : R) (x : power_series S) : ((r • x : power_series S) : laurent_series S) = r • x :=
by { ext, simp [coeff_coe, coeff_smul, smul_ite] }
@[simp, norm_cast] lemma coe_bit0 :
((bit0 f : power_series R) : laurent_series R) = bit0 f :=
(of_power_series ℤ R).map_bit0 _
@[simp, norm_cast] lemma coe_bit1 :
((bit1 f : power_series R) : laurent_series R) = bit1 f :=
(of_power_series ℤ R).map_bit1 _
@[simp, norm_cast] lemma coe_pow (n : ℕ) :
((f ^ n : power_series R) : laurent_series R) = f ^ n :=
(of_power_series ℤ R).map_pow _ _
end power_series
|
ac1d7e672de96741227a203d00c437c676325606
|
c055f4b7c29cf1aac2223bd8c1ac8d181a7c6447
|
/src/categories/natural_transformation.lean
|
261e1e5f47af81d0f969a6ac389c2226698b9078
|
[
"Apache-2.0"
] |
permissive
|
rwbarton/lean-category-theory-pr
|
77207b6674eeec1e258ec85dea58f3bff8d27065
|
591847d70c6a11c4d5561cd0eaf69b1fe85a70ab
|
refs/heads/master
| 1,584,595,111,303
| 1,528,029,041,000
| 1,528,029,041,000
| 135,919,126
| 0
| 0
| null | 1,528,041,805,000
| 1,528,041,805,000
| null |
UTF-8
|
Lean
| false
| false
| 4,744
|
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 .functor
open categories
open categories.functor
namespace categories.natural_transformation
universes u₁ v₁ u₂ v₂ u₃ v₃
section
variable {C : Type u₁}
variable [C_cat : category.{u₁ v₁} C]
variable {D : Type u₂}
variable [D_cat : category.{u₂ v₂} D]
include C_cat D_cat
structure NaturalTransformation (F G : C ↝ D) : Type (max u₁ v₂) :=
(components: Π X : C, (F +> X) ⟶ (G +> X))
(naturality: ∀ {X Y : C} (f : X ⟶ Y), (F &> f) ≫ (components Y) = (components X) ≫ (G &> f) . obviously)
make_lemma NaturalTransformation.naturality
attribute [ematch] NaturalTransformation.naturality_lemma
infixr ` ⟹ `:50 := NaturalTransformation -- type as \==>
definition IdentityNaturalTransformation (F : C ↝ D) : F ⟹ F :=
{ components := λ X, 𝟙 (F +> X),
naturality := begin
-- `obviously'` says:
intros,
simp
end }
@[simp] lemma IdentityNaturalTransformation.components (F : C ↝ D) (X : C) : (IdentityNaturalTransformation F).components X = 𝟙 (F +> X) := by refl
variables {F G H : C ↝ D}
definition vertical_composition_of_NaturalTransformations (α : F ⟹ G) (β : G ⟹ H) : F ⟹ H :=
{ components := λ X, (α.components X) ≫ (β.components X),
naturality := begin
-- `obviously'` says:
intros,
simp,
erw [←category.associativity_lemma, NaturalTransformation.naturality_lemma, category.associativity_lemma, ←NaturalTransformation.naturality_lemma]
end }
notation α `⊟` β:80 := vertical_composition_of_NaturalTransformations α β
@[simp,ematch] lemma vertical_composition_of_NaturalTransformations.components (α : F ⟹ G) (β : G ⟹ H) (X : C) : (α ⊟ β).components X = (α.components X) ≫ (β.components X) := by refl
-- We'll want to be able to prove that two natural transformations are equal if they are componentwise equal.
@[applicable] lemma NaturalTransformations_componentwise_equal
(α β : F ⟹ G)
(w : ∀ X : C, α.components X = β.components X) : α = β :=
begin
induction α with α_components α_naturality,
induction β with β_components β_naturality,
have hc : α_components = β_components := funext w,
subst hc
end
end
variable {C : Type u₁}
variable [𝒞 : category.{u₁ v₁} C]
variable {D : Type u₂}
variable [𝒟 : category.{u₂ v₂} D]
variable {E : Type u₃}
variable [ℰ : category.{u₃ v₃} E]
include 𝒞 𝒟 ℰ
variables {F G H : C ↝ D}
instance (F : C ↝ D) : has_one (F ⟹ F) :=
{ one := IdentityNaturalTransformation F }
open categories.functor
definition horizontal_composition_of_NaturalTransformations
{F G : C ↝ D}
{H I : D ↝ E}
(α : F ⟹ G)
(β : H ⟹ I) : (F ⋙ H) ⟹ (G ⋙ I) :=
{ components := λ X : C, (β.components (F +> X)) ≫ (I &> (α.components X)),
naturality := begin
-- `obviously'` says:
intros,
simp,
-- Actually, obviously doesn't use exactly this sequence of rewrites, but achieves the same result
rw [← category.associativity_lemma],
rw [NaturalTransformation.naturality_lemma],
rw [category.associativity_lemma],
conv { to_rhs, rw [← Functor.functoriality_lemma] },
rw [← α.naturality_lemma],
rw [Functor.functoriality_lemma],
end }
notation α `◫` β:80 := horizontal_composition_of_NaturalTransformations α β
@[simp,ematch] lemma horizontal_composition_of_NaturalTransformations.components {F G : C ↝ D}
{H I : D ↝ E}
(α : F ⟹ G)
(β : H ⟹ I) (X : C) : (α ◫ β).components X = (β.components (F +> X)) ≫ (I &> (α.components X)) := by refl
@[ematch] lemma NaturalTransformation.exchange
{F G H : C ↝ D}
{I J K : D ↝ E}
(α : F ⟹ G) (β : G ⟹ H) (γ : I ⟹ J) (δ : J ⟹ K) : ((α ⊟ β) ◫ (γ ⊟ δ)) = ((α ◫ γ) ⊟ (β ◫ δ)) :=
begin
-- obviously',
-- `obviously'` says:
apply categories.natural_transformation.NaturalTransformations_componentwise_equal,
intros,
simp,
-- again, this isn't actually what obviously says, but it achieves the same effect.
conv {to_lhs, congr, skip, rw [←category.associativity_lemma] },
rw [←NaturalTransformation.naturality_lemma],
rw [category.associativity_lemma],
end
end categories.natural_transformation
|
5d9525eb6af3ed2895572e280ad10ff6e54e7abb
|
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
|
/src/Lean/Elab/Command.lean
|
1aeb013859686216919984c1cb4d7928516cb4f6
|
[
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"
] |
permissive
|
EdAyers/lean4
|
57ac632d6b0789cb91fab2170e8c9e40441221bd
|
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
|
refs/heads/master
| 1,676,463,245,298
| 1,660,619,433,000
| 1,660,619,433,000
| 183,433,437
| 1
| 0
|
Apache-2.0
| 1,657,612,672,000
| 1,556,196,574,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 20,910
|
lean
|
/-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Log
import Lean.Parser.Command
import Lean.ResolveName
import Lean.Meta.Reduce
import Lean.Elab.Term
import Lean.Elab.Tactic.Cache
import Lean.Elab.Binders
import Lean.Elab.SyntheticMVars
import Lean.Elab.DeclModifiers
import Lean.Elab.InfoTree
import Lean.Elab.SetOption
namespace Lean.Elab.Command
structure Scope where
header : String
opts : Options := {}
currNamespace : Name := Name.anonymous
openDecls : List OpenDecl := []
levelNames : List Name := []
/-- section variables -/
varDecls : Array (TSyntax ``Parser.Term.bracketedBinder) := #[]
/-- Globally unique internal identifiers for the `varDecls` -/
varUIds : Array Name := #[]
/-- noncomputable sections automatically add the `noncomputable` modifier to any declaration we cannot generate code for. -/
isNoncomputable : Bool := false
deriving Inhabited
structure State where
env : Environment
messages : MessageLog := {}
scopes : List Scope := [{ header := "" }]
nextMacroScope : Nat := firstFrontendMacroScope + 1
maxRecDepth : Nat
nextInstIdx : Nat := 1 -- for generating anonymous instance names
ngen : NameGenerator := {}
infoState : InfoState := {}
traceState : TraceState := {}
deriving Inhabited
structure Context where
fileName : String
fileMap : FileMap
currRecDepth : Nat := 0
cmdPos : String.Pos := 0
macroStack : MacroStack := []
currMacroScope : MacroScope := firstFrontendMacroScope
ref : Syntax := Syntax.missing
tacticCache? : Option (IO.Ref Tactic.Cache)
abbrev CommandElabCoreM (ε) := ReaderT Context $ StateRefT State $ EIO ε
abbrev CommandElabM := CommandElabCoreM Exception
abbrev CommandElab := Syntax → CommandElabM Unit
abbrev Linter := Syntax → CommandElabM Unit
-- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the
-- whole monad stack at every use site. May eventually be covered by `deriving`.
instance : Monad CommandElabM := let i := inferInstanceAs (Monad CommandElabM); { pure := i.pure, bind := i.bind }
def mkState (env : Environment) (messages : MessageLog := {}) (opts : Options := {}) : State := {
env := env
messages := messages
scopes := [{ header := "", opts := opts }]
maxRecDepth := maxRecDepth.get opts
}
/- Linters should be loadable as plugins, so store in a global IO ref instead of an attribute managed by the
environment (which only contains `import`ed objects). -/
builtin_initialize lintersRef : IO.Ref (Array Linter) ← IO.mkRef #[]
def addLinter (l : Linter) : IO Unit := do
let ls ← lintersRef.get
lintersRef.set (ls.push l)
instance : MonadInfoTree CommandElabM where
getInfoState := return (← get).infoState
modifyInfoState f := modify fun s => { s with infoState := f s.infoState }
instance : MonadEnv CommandElabM where
getEnv := do pure (← get).env
modifyEnv f := modify fun s => { s with env := f s.env }
instance : MonadOptions CommandElabM where
getOptions := do pure (← get).scopes.head!.opts
protected def getRef : CommandElabM Syntax :=
return (← read).ref
instance : AddMessageContext CommandElabM where
addMessageContext := addMessageContextPartial
instance : MonadRef CommandElabM where
getRef := Command.getRef
withRef ref x := withReader (fun ctx => { ctx with ref := ref }) x
instance : MonadTrace CommandElabM where
getTraceState := return (← get).traceState
modifyTraceState f := modify fun s => { s with traceState := f s.traceState }
instance : AddErrorMessageContext CommandElabM where
add ref msg := do
let ctx ← read
let ref := getBetterRef ref ctx.macroStack
let msg ← addMessageContext msg
let msg ← addMacroStack msg ctx.macroStack
return (ref, msg)
def mkMessageAux (ctx : Context) (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity) : Message :=
let pos := ref.getPos?.getD ctx.cmdPos
let endPos := ref.getTailPos?.getD pos
mkMessageCore ctx.fileName ctx.fileMap msgData severity pos endPos
private def mkCoreContext (ctx : Context) (s : State) (heartbeats : Nat) : Core.Context :=
let scope := s.scopes.head!
{ fileName := ctx.fileName
fileMap := ctx.fileMap
options := scope.opts
currRecDepth := ctx.currRecDepth
maxRecDepth := s.maxRecDepth
ref := ctx.ref
currNamespace := scope.currNamespace
openDecls := scope.openDecls
initHeartbeats := heartbeats
currMacroScope := ctx.currMacroScope }
private def addTraceAsMessagesCore (ctx : Context) (log : MessageLog) (traceState : TraceState) : MessageLog := Id.run do
if traceState.traces.isEmpty then return log
let mut traces : Std.HashMap (String.Pos × String.Pos) (Array MessageData) := ∅
for traceElem in traceState.traces do
let ref := replaceRef traceElem.ref ctx.ref
let pos := ref.getPos?.getD 0
let endPos := ref.getTailPos?.getD pos
traces := traces.insert (pos, endPos) <| traces.findD (pos, endPos) #[] |>.push traceElem.msg
let mut log := log
let traces' := traces.toArray.qsort fun ((a, _), _) ((b, _), _) => a < b
for ((pos, endPos), traceMsg) in traces' do
log := log.add <| mkMessageCore ctx.fileName ctx.fileMap (.joinSep traceMsg.toList "\n") .information pos endPos
return log
private def addTraceAsMessages : CommandElabM Unit := do
let ctx ← read
modify fun s => { s with
messages := addTraceAsMessagesCore ctx s.messages s.traceState
traceState.traces := {}
}
def liftCoreM (x : CoreM α) : CommandElabM α := do
let s ← get
let ctx ← read
let heartbeats ← IO.getNumHeartbeats
let Eα := Except Exception α
let x : CoreM Eα := try let a ← x; pure <| Except.ok a catch ex => pure <| Except.error ex
let x : EIO Exception (Eα × Core.State) := (ReaderT.run x (mkCoreContext ctx s heartbeats)).run { env := s.env, ngen := s.ngen, traceState := s.traceState, messages := {}, infoState.enabled := s.infoState.enabled }
let (ea, coreS) ← liftM x
modify fun s => { s with
env := coreS.env
ngen := coreS.ngen
messages := addTraceAsMessagesCore ctx (s.messages ++ coreS.messages) coreS.traceState
traceState := coreS.traceState
infoState.trees := s.infoState.trees.append coreS.infoState.trees
}
match ea with
| Except.ok a => pure a
| Except.error e => throw e
private def ioErrorToMessage (ctx : Context) (ref : Syntax) (err : IO.Error) : Message :=
let ref := getBetterRef ref ctx.macroStack
mkMessageAux ctx ref (toString err) MessageSeverity.error
@[inline] def liftEIO {α} (x : EIO Exception α) : CommandElabM α := liftM x
@[inline] def liftIO {α} (x : IO α) : CommandElabM α := do
let ctx ← read
IO.toEIO (fun (ex : IO.Error) => Exception.error ctx.ref ex.toString) x
instance : MonadLiftT IO CommandElabM where
monadLift := liftIO
def getScope : CommandElabM Scope := do pure (← get).scopes.head!
instance : MonadResolveName CommandElabM where
getCurrNamespace := return (← getScope).currNamespace
getOpenDecls := return (← getScope).openDecls
instance : MonadLog CommandElabM where
getRef := getRef
getFileMap := return (← read).fileMap
getFileName := return (← read).fileName
hasErrors := return (← get).messages.hasErrors
logMessage msg := do
let currNamespace ← getCurrNamespace
let openDecls ← getOpenDecls
let msg := { msg with data := MessageData.withNamingContext { currNamespace := currNamespace, openDecls := openDecls } msg.data }
modify fun s => { s with messages := s.messages.add msg }
def runLinters (stx : Syntax) : CommandElabM Unit := do profileitM Exception "linting" (← getOptions) do
let linters ← lintersRef.get
unless linters.isEmpty do
for linter in linters do
let savedState ← get
try
linter stx
catch ex =>
logException ex
finally
modify fun s => { savedState with messages := s.messages }
protected def getCurrMacroScope : CommandElabM Nat := do pure (← read).currMacroScope
protected def getMainModule : CommandElabM Name := do pure (← getEnv).mainModule
protected def withFreshMacroScope {α} (x : CommandElabM α) : CommandElabM α := do
let fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 }))
withReader (fun ctx => { ctx with currMacroScope := fresh }) x
instance : MonadQuotation CommandElabM where
getCurrMacroScope := Command.getCurrMacroScope
getMainModule := Command.getMainModule
withFreshMacroScope := Command.withFreshMacroScope
unsafe def mkCommandElabAttributeUnsafe : IO (KeyedDeclsAttribute CommandElab) :=
mkElabAttribute CommandElab `Lean.Elab.Command.commandElabAttribute `builtinCommandElab `commandElab `Lean.Parser.Command `Lean.Elab.Command.CommandElab "command"
@[implementedBy mkCommandElabAttributeUnsafe]
opaque mkCommandElabAttribute : IO (KeyedDeclsAttribute CommandElab)
builtin_initialize commandElabAttribute : KeyedDeclsAttribute CommandElab ← mkCommandElabAttribute
private def mkInfoTree (elaborator : Name) (stx : Syntax) (trees : Std.PersistentArray InfoTree) : CommandElabM InfoTree := do
let ctx ← read
let s ← get
let scope := s.scopes.head!
let tree := InfoTree.node (Info.ofCommandInfo { elaborator, stx }) trees
return InfoTree.context {
env := s.env, fileMap := ctx.fileMap, mctx := {}, currNamespace := scope.currNamespace,
openDecls := scope.openDecls, options := scope.opts, ngen := s.ngen
} tree
private def elabCommandUsing (s : State) (stx : Syntax) : List (KeyedDeclsAttribute.AttributeEntry CommandElab) → CommandElabM Unit
| [] => withInfoTreeContext (mkInfoTree := mkInfoTree `no_elab stx) <| throwError "unexpected syntax{indentD stx}"
| (elabFn::elabFns) =>
catchInternalId unsupportedSyntaxExceptionId
(withInfoTreeContext (mkInfoTree := mkInfoTree elabFn.declName stx) <| elabFn.value stx)
(fun _ => do set s; elabCommandUsing s stx elabFns)
/-- Elaborate `x` with `stx` on the macro stack -/
def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : CommandElabM α) : CommandElabM α :=
withInfoContext (mkInfo := pure <| .ofMacroExpansionInfo { stx := beforeStx, output := afterStx, lctx := .empty }) do
withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x
instance : MonadMacroAdapter CommandElabM where
getCurrMacroScope := getCurrMacroScope
getNextMacroScope := return (← get).nextMacroScope
setNextMacroScope next := modify fun s => { s with nextMacroScope := next }
instance : MonadRecDepth CommandElabM where
withRecDepth d x := withReader (fun ctx => { ctx with currRecDepth := d }) x
getRecDepth := return (← read).currRecDepth
getMaxRecDepth := return (← get).maxRecDepth
register_builtin_option showPartialSyntaxErrors : Bool := {
defValue := false
descr := "show elaboration errors from partial syntax trees (i.e. after parser recovery)"
}
builtin_initialize registerTraceClass `Elab.command
partial def elabCommand (stx : Syntax) : CommandElabM Unit := do
withLogging <| withRef stx <| withIncRecDepth <| withFreshMacroScope do
match stx with
| Syntax.node _ k args =>
if k == nullKind then
-- list of commands => elaborate in order
-- The parser will only ever return a single command at a time, but syntax quotations can return multiple ones
args.forM elabCommand
else do
trace `Elab.command fun _ => stx;
let s ← get
match (← liftMacroM <| expandMacroImpl? s.env stx) with
| some (decl, stxNew?) =>
withInfoTreeContext (mkInfoTree := mkInfoTree decl stx) do
let stxNew ← liftMacroM <| liftExcept stxNew?
withMacroExpansion stx stxNew do
elabCommand stxNew
| _ =>
match commandElabAttribute.getEntries s.env k with
| [] =>
withInfoTreeContext (mkInfoTree := mkInfoTree `no_elab stx) <|
throwError "elaboration function for '{k}' has not been implemented"
| elabFns => elabCommandUsing s stx elabFns
| _ => throwError "unexpected command"
builtin_initialize registerTraceClass `Elab.input
/--
`elabCommand` wrapper that should be used for the initial invocation, not for recursive calls after
macro expansion etc.
-/
def elabCommandTopLevel (stx : Syntax) : CommandElabM Unit := withRef stx do
trace[Elab.input] stx
let initMsgs ← modifyGet fun st => (st.messages, { st with messages := {} })
let initInfoTrees ← getResetInfoTrees
-- We should *not* factor out `elabCommand`'s `withLogging` to here since it would make its error
-- recovery more coarse. In particular, If `c` in `set_option ... in $c` fails, the remaining
-- `end` command of the `in` macro would be skipped and the option would be leaked to the outside!
elabCommand stx
withLogging do
runLinters stx
-- note the order: first process current messages & info trees, then add back old messages & trees,
-- then convert new traces to messages
let mut msgs := (← get).messages
-- `stx.hasMissing` should imply `initMsgs.hasErrors`, but the latter should be cheaper to check in general
if !showPartialSyntaxErrors.get (← getOptions) && initMsgs.hasErrors && stx.hasMissing then
-- discard elaboration errors, except for a few important and unlikely misleading ones, on parse error
msgs := ⟨msgs.msgs.filter fun msg =>
msg.data.hasTag (fun tag => tag == `Elab.synthPlaceholder || tag == `Tactic.unsolvedGoals || (`_traceMsg).isSuffixOf tag)⟩
for tree in (← getInfoTrees) do
trace[Elab.info] (← tree.format)
modify fun st => { st with
messages := initMsgs ++ msgs
infoState := { st.infoState with trees := initInfoTrees ++ st.infoState.trees }
}
addTraceAsMessages
/-- Adapt a syntax transformation to a regular, command-producing elaborator. -/
def adaptExpander (exp : Syntax → CommandElabM Syntax) : CommandElab := fun stx => do
let stx' ← exp stx
withMacroExpansion stx stx' <| elabCommand stx'
private def getVarDecls (s : State) : Array Syntax :=
s.scopes.head!.varDecls
instance {α} : Inhabited (CommandElabM α) where
default := throw default
private def mkMetaContext : Meta.Context := {
config := { foApprox := true, ctxApprox := true, quasiPatternApprox := true }
}
/-- Return identifier names in the given bracketed binder. -/
def getBracketedBinderIds : Syntax → Array Name
| `(bracketedBinder|($ids* $[: $ty?]? $(_annot?)?)) => ids.map Syntax.getId
| `(bracketedBinder|{$ids* $[: $ty?]?}) => ids.map Syntax.getId
| `(bracketedBinder|[$id : $_]) => #[id.getId]
| `(bracketedBinder|[$_]) => #[Name.anonymous]
| _ => #[]
private def mkTermContext (ctx : Context) (s : State) : Term.Context := Id.run do
let scope := s.scopes.head!
let mut sectionVars := {}
for id in scope.varDecls.concatMap getBracketedBinderIds, uid in scope.varUIds do
sectionVars := sectionVars.insert id uid
{ macroStack := ctx.macroStack
sectionVars := sectionVars
isNoncomputableSection := scope.isNoncomputable
tacticCache? := ctx.tacticCache? }
/--
Lift the `TermElabM` monadic action `x` into a `CommandElabM` monadic action.
Note that `x` is executed with an empty message log. Thus, `x` cannot modify/view messages produced by
previous commands.
If you need to access the free variables corresponding to the ones declared using the `variable` command,
consider using `runTermElabM`.
Recall that `TermElabM` actions can automatically lift `MetaM` and `CoreM` actions.
Example:
```
import Lean
open Lean Elab Command Meta
def printExpr (e : Expr) : MetaM Unit := do
IO.println s!"{← ppExpr e} : {← ppExpr (← inferType e)}"
#eval
liftTermElabM do
printExpr (mkConst ``Nat)
```
-/
def liftTermElabM (x : TermElabM α) : CommandElabM α := do
let ctx ← read
let s ← get
let heartbeats ← IO.getNumHeartbeats
-- dbg_trace "heartbeats: {heartbeats}"
let scope := s.scopes.head!
-- We execute `x` with an empty message log. Thus, `x` cannot modify/view messages produced by previous commands.
-- This is useful for implementing `runTermElabM` where we use `Term.resetMessageLog`
let x : TermElabM _ := withSaveInfoContext x
let x : MetaM _ := (observing x).run (mkTermContext ctx s) { levelNames := scope.levelNames }
let x : CoreM _ := x.run mkMetaContext {}
let x : EIO _ _ := x.run (mkCoreContext ctx s heartbeats) { env := s.env, ngen := s.ngen, nextMacroScope := s.nextMacroScope, infoState.enabled := s.infoState.enabled }
let (((ea, _), _), coreS) ← liftEIO x
modify fun s => { s with
env := coreS.env
nextMacroScope := coreS.nextMacroScope
ngen := coreS.ngen
infoState.trees := s.infoState.trees.append coreS.infoState.trees
messages := addTraceAsMessagesCore ctx (s.messages ++ coreS.messages) coreS.traceState
}
match ea with
| Except.ok a => pure a
| Except.error ex => throw ex
/--
Execute the monadic action `elabFn xs` as a `CommandElabM` monadic action, where `xs` are free variables
corresponding to all active scoped variables declared using the `variable` command.
This method is similar to `liftTermElabM`, but it elaborates all scoped variables declared using the `variable`
command.
Example:
```
import Lean
open Lean Elab Command Meta
variable {α : Type u} {f : α → α}
variable (n : Nat)
#eval
runTermElabM fun xs => do
for x in xs do
IO.println s!"{← ppExpr x} : {← ppExpr (← inferType x)}"
```
-/
def runTermElabM (elabFn : Array Expr → TermElabM α) : CommandElabM α := do
let scope ← getScope
liftTermElabM <|
Term.withAutoBoundImplicit <|
Term.elabBinders scope.varDecls fun xs => do
-- We need to synthesize postponed terms because this is a checkpoint for the auto-bound implicit feature
-- If we don't use this checkpoint here, then auto-bound implicits in the postponed terms will not be handled correctly.
Term.synthesizeSyntheticMVarsNoPostponing
let mut sectionFVars := {}
for uid in scope.varUIds, x in xs do
sectionFVars := sectionFVars.insert uid x
withReader ({ · with sectionFVars := sectionFVars }) do
-- We don't want to store messages produced when elaborating `(getVarDecls s)` because they have already been saved when we elaborated the `variable`(s) command.
-- So, we use `Core.resetMessageLog`.
Core.resetMessageLog
let someType := mkSort levelZero
Term.addAutoBoundImplicits' xs someType fun xs _ =>
Term.withoutAutoBoundImplicit <| elabFn xs
@[inline] def catchExceptions (x : CommandElabM Unit) : CommandElabCoreM Empty Unit := fun ctx ref =>
EIO.catchExceptions (withLogging x ctx ref) (fun _ => pure ())
private def liftAttrM {α} (x : AttrM α) : CommandElabM α := do
liftCoreM x
def getScopes : CommandElabM (List Scope) := do
pure (← get).scopes
def modifyScope (f : Scope → Scope) : CommandElabM Unit :=
modify fun s => { s with
scopes := match s.scopes with
| h::t => f h :: t
| [] => unreachable!
}
def withScope (f : Scope → Scope) (x : CommandElabM α) : CommandElabM α := do
match (← get).scopes with
| [] => x
| h :: t =>
try
modify fun s => { s with scopes := f h :: t }
x
finally
modify fun s => { s with scopes := h :: t }
def getLevelNames : CommandElabM (List Name) :=
return (← getScope).levelNames
def addUnivLevel (idStx : Syntax) : CommandElabM Unit := withRef idStx do
let id := idStx.getId
let levelNames ← getLevelNames
if levelNames.elem id then
throwAlreadyDeclaredUniverseLevel id
else
modifyScope fun scope => { scope with levelNames := id :: scope.levelNames }
def expandDeclId (declId : Syntax) (modifiers : Modifiers) : CommandElabM ExpandDeclIdResult := do
let currNamespace ← getCurrNamespace
let currLevelNames ← getLevelNames
let r ← Elab.expandDeclId currNamespace currLevelNames declId modifiers
for id in (← getScope).varDecls.concatMap getBracketedBinderIds do
if id == r.shortName then
throwError "invalid declaration name '{r.shortName}', there is a section variable with the same name"
return r
end Elab.Command
export Elab.Command (Linter addLinter)
end Lean
|
89011ba7496c8b252cc102a42600baf1e42ce84a
|
59a4b050600ed7b3d5826a8478db0a9bdc190252
|
/src/category_theory/locally_ringed.lean
|
006e6bbc3df83eecd9e4ea66ce6d891ab39dc71b
|
[] |
no_license
|
rwbarton/lean-category-theory
|
f720268d800b62a25d69842ca7b5d27822f00652
|
00df814d463406b7a13a56f5dcda67758ba1b419
|
refs/heads/master
| 1,585,366,296,767
| 1,536,151,349,000
| 1,536,151,349,000
| 147,652,096
| 0
| 0
| null | 1,536,226,960,000
| 1,536,226,960,000
| null |
UTF-8
|
Lean
| false
| false
| 760
|
lean
|
import category_theory.sheaves
import category_theory.examples.rings.universal
universes v
open category_theory.examples
open category_theory.limits
variables (α : Type v) [topological_space α]
def structure_sheaf := sheaf.{v+1 v} α CommRing
structure ringed_space :=
(𝒪 : structure_sheaf α)
structure locally_ringed_space extends ringed_space α :=
(locality : ∀ x : α, local_ring (stalk_at.{v+1 v} 𝒪 x).1)
def ringed_space.of_topological_space : ringed_space α :=
{ 𝒪 := { presheaf := { obj := λ U, sorry /- ring of continuous functions U → ℂ -/,
map' := sorry,
map_id' := sorry,
map_comp' := sorry },
sheaf_condition := sorry,
} }
|
38f7af734c84937f91828552fca3dc62da86a346
|
74addaa0e41490cbaf2abd313a764c96df57b05d
|
/Mathlib/tactic/omega/lin_comb.lean
|
fd2aa9a80148979517d3cdb185833a187cb3330e
|
[] |
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,480
|
lean
|
/-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.omega.clause
import Mathlib.PostPort
namespace Mathlib
/-
Linear combination of constraints.
-/
namespace omega
/-- Linear combination of constraints. The second
argument is the list of constraints, and the first
argument is the list of conefficients by which the
constraints are multiplied -/
@[simp] def lin_comb : List ℕ → List term → term :=
sorry
theorem lin_comb_holds {v : ℕ → ℤ} {ts : List term} (ns : List ℕ) : (∀ (t : term), t ∈ ts → 0 ≤ term.val v t) → 0 ≤ term.val v (lin_comb ns ts) := sorry
/-- `unsat_lin_comb ns ts` asserts that the linear combination
`lin_comb ns ts` is unsatisfiable -/
def unsat_lin_comb (ns : List ℕ) (ts : List term) :=
prod.fst (lin_comb ns ts) < 0 ∧ ∀ (x : ℤ), x ∈ prod.snd (lin_comb ns ts) → x = 0
theorem unsat_lin_comb_of (ns : List ℕ) (ts : List term) : prod.fst (lin_comb ns ts) < 0 → (∀ (x : ℤ), x ∈ prod.snd (lin_comb ns ts) → x = 0) → unsat_lin_comb ns ts :=
fun (h1 : prod.fst (lin_comb ns ts) < 0) (h2 : ∀ (x : ℤ), x ∈ prod.snd (lin_comb ns ts) → x = 0) =>
{ left := h1, right := h2 }
theorem unsat_of_unsat_lin_comb (ns : List ℕ) (ts : List term) : unsat_lin_comb ns ts → clause.unsat ([], ts) := sorry
|
69d7025f54948371fd26784e134ac868e5f3b9cc
|
5883d9218e6f144e20eee6ca1dab8529fa1a97c0
|
/src/aexp/category.lean
|
662d38734faabbf2a1502ae287869a728ef24160
|
[] |
no_license
|
spl/alpha-conversion-is-easy
|
0d035bc570e52a6345d4890e4d0c9e3f9b8126c1
|
ed937fe85d8495daffd9412a5524c77b9fcda094
|
refs/heads/master
| 1,607,649,280,020
| 1,517,380,240,000
| 1,517,380,240,000
| 52,174,747
| 4
| 0
| null | 1,456,052,226,000
| 1,456,001,163,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 823
|
lean
|
/-
This file contains the proof that `aexp` is a `category`.
-/
import .properties
import data.category
namespace acie -----------------------------------------------------------------
namespace aexp -----------------------------------------------------------------
variables {V : Type} [decidable_eq V] -- Type of variable names
variables {vs : Type → Type} [vset vs V] -- Type of variable name sets
instance category : category aexp.subst :=
{ comp := @has_comp.comp (vs V) _ _
, id := aexp.subst.id
, left_id := λ X Y, aexp.subst.left_id
, right_id := λ X Y, aexp.subst.right_id
, assoc := λ W X Y Z, aexp.subst.assoc
}
end /- namespace -/ aexp -------------------------------------------------------
end /- namespace -/ acie -------------------------------------------------------
|
fced22e216c43a837997df486f04cac45cd2f3ac
|
76c77df8a58af24dbf1d75c7012076a42244d728
|
/src/ch3.lean
|
50d635bd0bc9a3d2ddb09ff039fff1c89b0229bd
|
[] |
no_license
|
kris-brown/theorem_proving_in_lean
|
7a7a584ba2c657a35335dc895d49d991c997a0c9
|
774460c21bf857daff158210741bd88d1c8323cd
|
refs/heads/master
| 1,668,278,123,743
| 1,593,445,161,000
| 1,593,445,161,000
| 265,748,924
| 0
| 1
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 14,262
|
lean
|
-- Section 3.1: Propositions as Types
namespace s31
constant and : Prop → Prop → Prop
constant or : Prop → Prop → Prop
constant not : Prop → Prop
constant implies : Prop → Prop → Prop
variables p q r A B: Prop
#check and p q -- Prop
#check or (and p q) r -- Prop
#check implies (and p q) (and q p) -- Prop
constant Proof : Prop → Type
constant and_comm : Π p q : Prop,
Proof (implies (and p q) (and q p))
#check and_comm p q -- Proof (implies (and p q) (and q p))
constant modus_ponens :
Π p q : Prop, Proof (implies p q) → Proof p → Proof q
constant implies_intro :
Π p q : Prop, (Proof p → Proof q) → Proof (implies p q).
end s31
-- Section 3.2: Working with P. as T.
namespace s32
constants p q r s: Prop
-- Similar to 'def' but for Prop, not Type
theorem t1_ : p → q → p := λ hp : p, λ hq : q, hp
#print t1_
-- Written with other syntax for readability
theorem t1' : p → q → p :=
assume hp : p,
assume hq : q,
show p, from hp
-- Can also say "lemma" instead of theorem
lemma t1'' : p → q → p := λ hp : p, λ hq : q, hp
-- Can also move arguments to left of colon, like with defs
lemma t1''' (hp : p) (hq : q): p := hp
axiom hp : p -- same as constant
theorem t2' : q → p := t1' hp
#print t2'
-- Want our theorem to be true for any p q, not just those particular constants
theorem t1 (p q : Prop) (hp : p) (hq : q) : p := hp
-- Apply to other constants
#check t1 p q -- p → q → p
#check t1 r s -- r → s → r
#check t1 (r → s) (s → r) -- (r → s) → (s → r) → r → s
variable h : r → s
#check t1 (r → s) (s → r) h -- (s → r) → r → s
-- Function composition says that "implies" is transitive
theorem t2 (h₁ : q → r) (h₂ : p → q) : p → r :=
assume h₃ : p,
show r, from h₁ (h₂ h₃)
end s32
-- Section 3.3: Propositional logic
namespace s33
variables p q r : Prop
#check p → q → p ∧ q
#check ¬p → p ↔ false
#check p ∨ q → q ∨ p
-- Conjunction
--------------
-- 'example' states a theorem without naming/storing it. Essentially is just a typecheck
example (hp : p) (hq : q) : p ∧ q := and.intro hp hq
#check assume (hp : p) (hq : q), and.intro hp hq
example (h : p ∧ q) : p := and.elim_left h
example (h : p ∧ q) : q := and.elim_right h
-- Common abbreviation for elim_left/right
example (h : p ∧ q) : q ∧ p :=
and.intro (and.right h) (and.left h)
-- Anonymous constructor
variables (hp : p) (hq : q)
#check (⟨hp, hq⟩ : p ∧ q)
example : p ∧ q := (|hp, hq|) -- ascii version
-- Dot syntax
variable l : list ℕ
#check list.head l
#check l.head -- equivalent, easier to write
-- Dot syntax for propositions
example (h : p ∧ q) : q ∧ p :=
⟨h.right, h.left⟩
-- Disjunction
--------------
--intro
example (hp : p) : p ∨ q := or.intro_left q hp
example (hq : q) : p ∨ q := or.intro_right p hq
--elim
example (h : p ∨ q) : q ∨ p :=
or.elim h
(λ hp : p,
show q ∨ p, from or.intro_right q hp)
(assume hq : q,
show q ∨ p, from or.intro_left p hq)
-- intro
example (h : p ∨ q) : q ∨ p :=
or.elim h (λ hp, or.inr hp) (λ hq, or.inl hq)
-- or has two constructors,so can't use anonymous constructor
-- still write h.elim instead of or.elim h:
example (h : p ∨ q) : q ∨ p :=
h.elim
(assume hp : p, or.inr hp)
(assume hq : q, or.inl hq)
-- Negation/falsity
example (hpq : p → q) (hnq : ¬q) : ¬p :=
assume hp : p,
show false, from hnq (hpq hp)
-- explosion (q is implicit argument in false.elim)
example (hp : p) (hnp : ¬p) : q := false.elim (hnp hp)
-- Shorthand for explosion
example (hp : p) (hnp : ¬p) : q := absurd hp hnp
-- proof of ¬p → q → (q → p) → r:
example (hnp : ¬p) (hq : q) (hqp : q → p) : r :=
absurd (hqp hq) hnp
-- Logical equivalence
-----------------------
theorem and_swap : p ∧ q ↔ q ∧ p :=
iff.intro
(assume h : p ∧ q,
show q ∧ p, from and.intro (and.right h) (and.left h))
(assume h : q ∧ p,
show p ∧ q, from and.intro (and.right h) (and.left h))
#check and_swap p q -- p ∧ q ↔ q ∧ p
-- Modus ponens
variable h : p ∧ q
example : q ∧ p := iff.mp (and_swap p q) h
end s33
-- Section 3.4: Auxiliary Subgoals
namespace s34
variables p q : Prop
example (h : p ∧ q) : q ∧ p :=
have hp : p, from and.left h,
have hq : q, from and.right h,
show q ∧ p, from and.intro hq hp
-- suffices for backwards reasoning from a goal
example (h : p ∧ q) : q ∧ p :=
have hp : p, from and.left h,
suffices hq : q, from and.intro hq hp,
show q, from and.right h
-- suffices hq : q leaves us with two goals.
--- show that it indeed suffices to show q, by proving the original goal of q ∧ p with the additional hypothesis hq : q.
--- show q.
end s34
-- Section 3.5: Classical logic
namespace s35
open classical
-- Excluded middle
variables p q : Prop
#check em p
-- Double negation as consequence
theorem dne {p : Prop} (h : ¬¬p) : p :=
or.elim (em p)
(assume hp : p, hp)
(assume hnp : ¬p, absurd hnp h)
-- This allows us to construct proofs by contradiction
example (h : ¬¬p) : p :=
by_cases
(assume h1 : p, h1)
(assume h1 : ¬p, absurd h1 h)
example (h : ¬¬p) : p :=
by_contradiction
(assume h1 : ¬p,
show false, from h h1)
example (h : ¬(p ∧ q)) : ¬p ∨ ¬q :=
or.elim (em p)
(assume hp : p,
or.inr
(show ¬q, from
assume hq : q,
h ⟨hp, hq⟩))
(assume hp : ¬p,
or.inl hp)
end s35
-- Section 3.6: Examples of propositional validities
namespace s36
open classical
-- We can use sorry or an underscore to allow us to incrementally build up a proof (with warnings, not errors) to make sure the large structure is correct before tackling subgoals.
variables p q r : Prop
-- distributivity
example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) :=
iff.intro
(assume h : p ∧ (q ∨ r),
have hp : p, from h.left,
or.elim (h.right)
(assume hq : q,
show (p ∧ q) ∨ (p ∧ r), from or.inl ⟨hp, hq⟩)
(assume hr : r,
show (p ∧ q) ∨ (p ∧ r), from or.inr ⟨hp, hr⟩))
(assume h : (p ∧ q) ∨ (p ∧ r),
or.elim h
(assume hpq : p ∧ q,
have hp : p, from hpq.left,
have hq : q, from hpq.right,
show p ∧ (q ∨ r), from ⟨hp, or.inl hq⟩)
(assume hpr : p ∧ r,
have hp : p, from hpr.left,
have hr : r, from hpr.right,
show p ∧ (q ∨ r), from ⟨hp, or.inr hr⟩))
-- an example that requires classical reasoning
example : ¬(p ∧ ¬q) → (p → q) :=
assume h : ¬(p ∧ ¬q),
assume hp : p,
show q, from
or.elim (em q)
(assume hq : q, hq)
(assume hnq : ¬q, absurd (and.intro hp hnq) h)
end s36
-- Exercises
namespace s3x
-- 1
variables p q r s : Prop
-- commutativity of ∧ and ∨
example : p ∧ q ↔ q ∧ p := iff.intro
(λ hpq, and.intro hpq.right hpq.left)
(λ hpq, and.intro hpq.right hpq.left)
example : p ∨ q ↔ q ∨ p := iff.intro
(λ hporq, or.elim hporq
(assume hp: p, or.inr hp)
(assume hq: q, or.inl hq))
(λ hqorp, or.elim hqorp
(assume hq: q, or.inr hq)
(assume hp: p, or.inl hp))
-- associativity of ∧ and ∨
example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := iff.intro
(assume hpq_r : (p ∧ q) ∧ r,
and.intro hpq_r.left.left (and.intro hpq_r.left.right hpq_r.right))
(assume hp_qr : p ∧ (q ∧ r),
and.intro (and.intro hp_qr.left hp_qr.right.left) hp_qr.right.right)
example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := iff.intro
(assume hpq_r : (p ∨ q) ∨ r, or.elim hpq_r
(assume hpq: (p ∨ q), or.elim hpq
(assume hp : p, (or.inl hp))
(assume hq : q, or.inr (or.inl hq)))
(assume hr : r, or.inr (or.inr hr)))
(assume hp_qr : p ∨ (q ∨ r), or.elim hp_qr
(assume hp : p, or.inl (or.inl hp))
(assume hqr: (q ∨ r), or.elim hqr
(assume hq : q, or.inl (or.inr hq))
(assume hr : r, or.inr hr)))
-- distributivity
example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := iff.intro
(assume hpqr : p ∧ (q ∨ r),
have hp:p, from and.left hpqr,
show (p ∧ q) ∨ (p ∧ r), from or.elim
(and.right hpqr)
(assume hq : q, or.inl (and.intro hp hq))
(assume hr : r, or.inr (and.intro hp hr)))
(assume hpqpr : (p ∧ q) ∨ (p ∧ r), or.elim hpqpr
(assume hpq : p ∧ q, and.intro
hpq.left
(or.inl hpq.right))
(assume hpr : p ∧ r, and.intro
hpr.left
(or.inr hpr.right)))
example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := iff.intro
(assume hpqr : p ∨ (q ∧ r), or.elim hpqr
(assume hp : p, and.intro
(or.inl hp)
(or.inl hp))
(assume hqr : q ∧ r, and.intro
(or.inr hqr.left)
(or.inr hqr.right)))
(assume hpqpr: (p ∨ q) ∧ (p ∨ r),
show p ∨ (q ∧ r), from or.elim hpqpr.left
(assume hp: p, or.inl hp)
(assume hq: q,
or.elim hpqpr.right
(assume hp: p, or.inl hp)
(assume hr: r, or.inr (and.intro hq hr))))
-- other properties
example : (p → (q → r)) ↔ (p ∧ q → r) := iff.intro
(assume hpqr : p → (q → r),
(assume hpr : p ∧ q, hpqr hpr.left hpr.right))
(assume hpqr : p ∧ q → r,
(assume hp : p,
(assume hq : q,
have hpq : p ∧ q, from and.intro hp hq,
hpqr hpq)))
example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) := iff.intro
(assume hpqr : (p ∨ q) → r,
have hpr : p → r, from
(assume hp: p, hpqr (or.inl hp)),
have hqr : q → r, from
(assume hq : q, hpqr (or.inr hq)),
and.intro hpr hqr)
(assume hprqr : (p → r) ∧ (q → r),
(assume hpq : p ∨ q, or.elim hpq
(assume hp: p, hprqr.left hp)
(assume hq: q, hprqr.right hq)))
example : ¬(p ∨ q) ↔ ¬p ∧ ¬q := iff.intro
(assume hnpq : ¬(p ∨ q),
have hnp: ¬p, from
(assume hp: p, hnpq (or.inl hp)),
have hnq: ¬q, from
(assume hq: q, hnpq (or.inr hq)),
and.intro hnp hnq)
(assume hnpnq : ¬p ∧ ¬q,
(assume hpq : p ∨ q, or.elim hpq
(assume hp :p, hnpnq.left hp)
(assume hq: q, hnpnq.right hq)))
example : ¬p ∨ ¬q → ¬(p ∧ q) :=
(assume hnpnq : ¬p ∨ ¬q,
(assume hpq : p ∧ q, or.elim hnpnq
(assume hnp :¬p, hnp hpq.left)
(assume hnq :¬q, hnq hpq.right)))
example : ¬(p ∧ ¬p) :=
(assume hpnp: p ∧ ¬p, hpnp.right hpnp.left)
example : p ∧ ¬q → ¬(p → q) :=
assume hpnq : p ∧ ¬q,
assume hpq : p → q,
have hp : p, from hpnq.left,
have hq : q, from hpq hp,
have hnq : ¬ q, from hpnq.right,
hnq hq
example : ¬p → (p → q) :=
assume hnp : ¬p,
assume hp : p,
absurd hp hnp
example : (¬p ∨ q) → (p → q) :=
assume hnpq : ¬p ∨ q,
assume hp : p,
or.elim hnpq
(assume hnp : ¬p, absurd hp hnp)
id
example : p ∨ false ↔ p := iff.intro
(assume hpf : p ∨ false, or.elim hpf
(assume hp : p, hp)
(assume f: false,
false.elim f))
(assume hp : p, or.inl hp)
example : p ∧ false ↔ false := iff.intro
(assume hpf: p ∧ false, hpf.right)
(assume hf : false, false.elim hf)
example : (p → q) → (¬q → ¬p) :=
assume hpq : p → q,
assume hnq : ¬q,
assume hp : p,
absurd (hpq hp) hnq
-- 3
--2 (use classical reasoning)
open classical
example : (p → r ∨ s) → ((p → r) ∨ (p → s)) :=
assume hprs: p → r ∨ s,
have hpnp : p ∨ ¬ p, from em p,
or.elim hpnp
(assume hp : p,
have hrs : r ∨ s, from hprs hp,
or.elim hrs
(assume hr : r, or.inl (assume _ : p, hr))
(assume hs: s, or.inr (assume _ : p, hs)))
(assume hnp : ¬ p, or.inl
(assume hp : p, absurd hp hnp))
example : ¬(p ∧ q) → ¬p ∨ ¬q :=
assume hnpq : ¬(p ∧ q) ,
have emp : p ∨ ¬p , from em p ,
or.elim emp
(assume hp : p,
have emq : q ∨ ¬q , from em q ,
or.elim emq
(assume hq : q, absurd (and.intro hp hq) hnpq)
(assume hnq : ¬q, or.inr hnq))
(assume hnp : ¬p, or.inl hnp)
example : ¬(p → q) → p ∧ ¬q :=
assume h : ¬(p → q),
have emp : p ∨ ¬p , from em p ,
or.elim emp
(assume hp : p,
have emq : q ∨ ¬q , from em q ,
or.elim emq
(assume hq : q,
have imp: p → q, from (λ x: p, hq ),
absurd imp h)
(assume hnq : ¬q, and.intro hp hnq))
(assume hnp : ¬p,
have imp : p → q, from (λ x: p, absurd x hnp),
absurd imp h)
example : (p → q) → (¬p ∨ q) :=
assume hpq : p → q,
have emp : p ∨ ¬p , from em p ,
or.elim emp
(assume hp : p, or.inr (hpq hp))
(assume hnp : ¬p, or.inl hnp)
example : (¬q → ¬p) → (p → q) :=
assume hnqnp : ¬q → ¬p,
assume hp: p,
have emq : q ∨ ¬q , from em q ,
or.elim emq
id
(assume hnq : ¬q, absurd hp (hnqnp hnq))
example : p ∨ ¬p := em p
example : (((p → q) → p) → p) :=
assume hpqp : (p → q) → p,
have hem : p ∨ ¬p, from em p,
or.elim hem
(assume hp: p, id hp)
(assume hnp: ¬p,
absurd
(have hpq: p → q, from
(assume hp: p, absurd hp hnp),
hpqp hpq)
hnp)
end s3x
|
a99da3a7f053fa6b75426eaa84642b85c326a04e
|
da23b545e1653cafd4ab88b3a42b9115a0b1355f
|
/src/tidy/rewrite_search/strategy/edit_distance.lean
|
f356889f8aa522a6fb59079b31106c3fb830ee2b
|
[] |
no_license
|
minchaowu/lean-tidy
|
137f5058896e0e81dae84bf8d02b74101d21677a
|
2d4c52d66cf07c59f8746e405ba861b4fa0e3835
|
refs/heads/master
| 1,585,283,406,120
| 1,535,094,033,000
| 1,535,094,033,000
| 145,945,792
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 2,711
|
lean
|
import tidy.rewrite_search.engine
open tidy.rewrite_search
open tidy.rewrite_search.bound_progress
namespace tidy.rewrite_search.strategy.edit_distance
variables {α : Type} [decidable_eq α]
@[derive decidable_eq]
structure ed_partial :=
(prefix_length : ℕ)
(suffix : list string)
(distances : list ℕ) -- distances from the prefix of l₁ to each non-empty prefix of l₂
def empty_partial_edit_distance_data (l₁ l₂: list string) : ed_partial :=
⟨ 0, l₁, (list.range l₂.length).map(λ n, n + 1) ⟩
meta def ed_searchstate_init : unit := ()
meta def ed_step (g : global_state unit ed_partial) (itr : ℕ) : global_state unit ed_partial × (@strategy_action unit ed_partial) :=
if itr <= 200 then
match g.interesting_pairs with
| [] := (g, strategy_action.abort "all interesting pairs exhausted!")
| (best_p :: rest) :=
(g, strategy_action.examine best_p)
end
else
(g, strategy_action.abort "max iterations reached")
meta def ed_init_bound (l r : vertex) : bound_progress ed_partial :=
at_least 0 (empty_partial_edit_distance_data l.tokens r.tokens)
def triples {α : Type} (p : ed_partial) (l₂ : list α): list (ℕ × ℕ × α) := p.distances.zip ((list.cons p.prefix_length p.distances).zip l₂)
--FIXME rewrite me
meta def fold_fn (h : string) (n : ℕ × list ℕ) (t : ℕ × ℕ × string) :=
let m := (if h = t.2.2 then t.2.1 else 1 + min (min (t.2.1) (t.1)) n.2.head) in
(min m n.1, list.cons m n.2)
--FIXME rewrite me
meta def ed_improve_bound_once (l r : list string) (cur : ℕ) (p : ed_partial) : bound_progress ed_partial :=
match p.suffix with
| [] := exactly p.distances.ilast p
| (h :: t) :=
let initial := (p.prefix_length + 1, [p.prefix_length + 1]) in
let new_distances : ℕ × list ℕ := (triples p r).foldl (fold_fn h) initial in
at_least new_distances.1 ⟨ p.prefix_length + 1, t, new_distances.2.reverse.drop 1 ⟩
end
meta def ed_improve_bound_over (l r : list string) (m : ℕ) : bound_progress ed_partial → bound_progress ed_partial
| (exactly n p) := exactly n p
| (at_least n p) :=
if n > m then
at_least n p
else
ed_improve_bound_over (ed_improve_bound_once l r n p)
meta def ed_improve_estimate_over (m : ℕ) (l r : vertex) (bnd : bound_progress ed_partial) : bound_progress ed_partial :=
ed_improve_bound_over l.tokens r.tokens m bnd
end tidy.rewrite_search.strategy.edit_distance
namespace tidy.rewrite_search.strategy
open tidy.rewrite_search.strategy.edit_distance
meta def edit_distance_strategy : strategy unit ed_partial :=
⟨ ed_searchstate_init, ed_step, ed_init_bound, ed_improve_estimate_over ⟩
end tidy.rewrite_search.strategy
|
4ce25901c78a571fdee43cd4a79f3a3512d0491f
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/archive/miu_language/decision_suf.lean
|
8625a706de47b11c9559688366f874498fc8b61b
|
[
"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
| 14,629
|
lean
|
/-
Copyright (c) 2020 Gihan Marasingha. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gihan Marasingha
-/
import .decision_nec
import tactic.linarith
/-!
# Decision procedure - sufficient condition and decidability
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We give a sufficient condition for a string to be derivable in the MIU language. Together with the
necessary condition, we use this to prove that `derivable` is an instance of `decidable_pred`.
Let `count I st` and `count U st` denote the number of `I`s (respectively `U`s) in `st : miustr`.
We'll show that `st` is derivable if it has the form `M::x` where `x` is a string of `I`s and `U`s
for which `count I x` is congruent to 1 or 2 modulo 3.
To prove this, it suffices to show `derivable M::y` where `y` is any `miustr` consisting only of
`I`s such that the number of `I`s in `y` is `a+3b`, where `a = count I x` and `b = count U x`.
This suffices because Rule 3 permits us to change any string of three consecutive `I`s into a `U`.
As `count I y = (count I x) + 3*(count U x) ≡ (count I x) [MOD 3]`, it suffices to show
`derivable M::z` where `z` is an `miustr` of `I`s such that `count I z` is congruent to
1 or 2 modulo 3.
Let `z` be such an `miustr` and let `c` denote `count I z`, so `c ≡ 1 or 2 [MOD 3]`.
To derive such an `miustr`, it suffices to derive an `miustr` `M::w`, where again w is an
`miustr` of only `I`s with the additional conditions that `count I w` is a power of 2, that
`count I w ≥ c` and that `count I w ≡ c [MOD 3]`.
To see that this suffices, note that we can remove triples of `I`s from the end of `M::w`,
creating `U`s as we go along. Once the number of `I`s equals `m`, we remove `U`s two at a time
until we have no `U`s. The only issue is that we may begin the removal process with an odd number
of `U`s.
Writing `d = count I w`, we see that this happens if and only if `(d-c)/3` is odd.
In this case, we must apply Rule 1 to `z`, prior to removing triples of `I`s. We thereby
introduce an additional `U` and ensure that the final number of `U`s will be even.
## Tags
miu, decision procedure, decidability, decidable_pred, decidable
-/
namespace miu
open miu_atom list nat
/--
We start by showing that an `miustr` `M::w` can be derived, where `w` consists only of `I`s and
where `count I w` is a power of 2.
-/
private lemma der_cons_replicate (n : ℕ) : derivable (M::(replicate (2^n) I)) :=
begin
induction n with k hk,
{ constructor, }, -- base case
{ rw [succ_eq_add_one, pow_add, pow_one 2, mul_two,replicate_add], -- inductive step
exact derivable.r2 hk, },
end
/-!
## Converting `I`s to `U`s
For any given natural number `c ≡ 1 or 2 [MOD 3]`, we need to show that can derive an `miustr`
`M::w` where `w` consists only of `I`s, where `d = count I w` is a power of 2, where `d ≥ c` and
where `d ≡ c [MOD 3]`.
Given the above lemmas, the desired result reduces to an arithmetic result, given in the file
`arithmetic.lean`.
We'll use this result to show we can derive an `miustr` of the form `M::z` where `z` is an string
consisting only of `I`s such that `count I z ≡ 1 or 2 [MOD 3]`.
As an intermediate step, we show that derive `z` from `zt`, where `t` is aN `miustr` consisting of
an even number of `U`s and `z` is any `miustr`.
-/
/--
Any number of successive occurrences of `"UU"` can be removed from the end of a `derivable` `miustr`
to produce another `derivable` `miustr`.
-/
lemma der_of_der_append_replicate_U_even {z : miustr} {m : ℕ}
(h : derivable (z ++ replicate (m*2) U)) : derivable z :=
begin
induction m with k hk,
{ revert h,
simp only [list.replicate, zero_mul, append_nil, imp_self], },
{ apply hk,
simp only [succ_mul, replicate_add] at h,
change replicate 2 U with [U,U] at h,
rw ←(append_nil (z ++ replicate (k*2) U)),
apply derivable.r4,
simp only [append_nil, append_assoc,h], },
end
/-!
In fine-tuning my application of `simp`, I issued the following commend to determine which lemmas
`simp` uses.
`set_option trace.simplify.rewrite true`
-/
/--
We may replace several consecutive occurrences of `"III"` with the same number of `"U"`s.
In application of the following lemma, `xs` will either be `[]` or `[U]`.
-/
lemma der_cons_replicate_I_replicate_U_append_of_der_cons_replicate_I_append (c k : ℕ)
(hc : c % 3 = 1 ∨ c % 3 = 2) (xs : miustr) (hder : derivable (M ::(replicate (c+3*k) I) ++ xs)) :
derivable (M::(replicate c I ++ replicate k U) ++ xs) :=
begin
revert xs,
induction k with a ha,
{ simp only [list.replicate, mul_zero, add_zero, append_nil, forall_true_iff, imp_self],},
{ intro xs,
specialize ha (U::xs),
intro h₂,
simp only [succ_eq_add_one, replicate_add], -- We massage the goal
rw [←append_assoc, ←cons_append], -- into a form amenable
change replicate 1 U with [U], -- to the application of
rw [append_assoc, singleton_append], -- ha.
apply ha,
apply derivable.r3,
change [I,I,I] with replicate 3 I,
simp only [cons_append, ←replicate_add],
convert h₂, },
end
/-!
### Arithmetic
We collect purely arithmetic lemmas: `add_mod2` is used to ensure we have an even number of `U`s
while `le_pow2_and_pow2_eq_mod3` treats the congruence condition modulo 3.
-/
section arithmetic
/--
For every `a`, the number `a + a % 2` is even.
-/
lemma add_mod2 (a : ℕ) : ∃ t, a + a % 2 = t*2 :=
begin
simp only [mul_comm _ 2], -- write `t*2` as `2*t`
apply dvd_of_mod_eq_zero, -- it suffices to prove `(a + a % 2) % 2 = 0`
rw [add_mod, mod_mod, ←two_mul, mul_mod_right],
end
private lemma le_pow2_and_pow2_eq_mod3' (c : ℕ) (x : ℕ) (h : c = 1 ∨ c = 2) :
∃ m : ℕ, c + 3*x ≤ 2^m ∧ 2^m % 3 = c % 3 :=
begin
induction x with k hk,
{ use (c+1),
cases h with hc hc;
{ rw hc, norm_num }, },
rcases hk with ⟨g, hkg, hgmod⟩,
by_cases hp : (c + 3*(k+1) ≤ 2 ^g),
{ use g, exact ⟨hp, hgmod⟩ },
refine ⟨g + 2, _, _⟩,
{ rw [mul_succ, ←add_assoc, pow_add],
change 2^2 with (1+3), rw [mul_add (2^g) 1 3, mul_one],
linarith [hkg, one_le_two_pow g], },
{ rw [pow_add, ←mul_one c],
exact modeq.mul hgmod rfl }
end
/--
If `a` is 1 or 2 modulo 3, then exists `k` a power of 2 for which `a ≤ k` and `a ≡ k [MOD 3]`.
-/
lemma le_pow2_and_pow2_eq_mod3 (a : ℕ) (h : a % 3 = 1 ∨ a % 3 = 2) :
∃ m : ℕ, a ≤ 2^m ∧ 2^m % 3 = a % 3:=
begin
cases le_pow2_and_pow2_eq_mod3' (a%3) (a/3) h with m hm,
use m,
split,
{ convert hm.1, exact (mod_add_div a 3).symm, },
{ rw [hm.2, mod_mod _ 3], },
end
end arithmetic
lemma replicate_pow_minus_append {m : ℕ} :
M :: replicate (2^m - 1) I ++ [I] = M::(replicate (2^m) I) :=
begin
change [I] with replicate 1 I,
rw [cons_append, ←replicate_add, tsub_add_cancel_of_le (one_le_pow' m 1)],
end
/--
`der_replicate_I_of_mod3` states that `M::y` is `derivable` if `y` is any `miustr` consisiting just
of `I`s, where `count I y` is 1 or 2 modulo 3.
-/
lemma der_replicate_I_of_mod3 (c : ℕ) (h : c % 3 = 1 ∨ c % 3 = 2):
derivable (M::(replicate c I)) :=
begin
-- From `der_cons_replicate`, we can derive the `miustr` `M::w` described in the introduction.
cases (le_pow2_and_pow2_eq_mod3 c h) with m hm, -- `2^m` will be the number of `I`s in `M::w`
have hw₂ : derivable (M::(replicate (2^m) I) ++ replicate ((2^m -c)/3 % 2) U),
{ cases mod_two_eq_zero_or_one ((2^m -c)/3) with h_zero h_one,
{ -- `(2^m - c)/3 ≡ 0 [MOD 2]`
simp only [der_cons_replicate m, append_nil,list.replicate, h_zero], },
{ rw [h_one, ←replicate_pow_minus_append, append_assoc], -- case `(2^m - c)/3 ≡ 1 [MOD 2]`
apply derivable.r1,
rw replicate_pow_minus_append,
exact (der_cons_replicate m), }, },
have hw₃ :
derivable (M::(replicate c I) ++ replicate ((2^m-c)/3) U ++ replicate ((2^m-c)/3 % 2) U),
{ apply der_cons_replicate_I_replicate_U_append_of_der_cons_replicate_I_append c ((2^m-c)/3) h,
convert hw₂, -- now we must show `c + 3 * ((2 ^ m - c) / 3) = 2 ^ m`
rw nat.mul_div_cancel',
{ exact add_tsub_cancel_of_le hm.1 },
{ exact (modeq_iff_dvd' hm.1).mp hm.2.symm } },
rw [append_assoc, ←replicate_add _ _] at hw₃,
cases add_mod2 ((2^m-c)/3) with t ht,
rw ht at hw₃,
exact der_of_der_append_replicate_U_even hw₃,
end
example (c : ℕ) (h : c % 3 = 1 ∨ c % 3 = 2):
derivable (M::(replicate c I)) :=
begin
-- From `der_cons_replicate`, we can derive the `miustr` `M::w` described in the introduction.
cases (le_pow2_and_pow2_eq_mod3 c h) with m hm, -- `2^m` will be the number of `I`s in `M::w`
have hw₂ : derivable (M::(replicate (2^m) I) ++ replicate ((2^m -c)/3 % 2) U),
{ cases mod_two_eq_zero_or_one ((2^m -c)/3) with h_zero h_one,
{ -- `(2^m - c)/3 ≡ 0 [MOD 2]`
simp only [der_cons_replicate m, append_nil, list.replicate, h_zero] },
{ rw [h_one, ←replicate_pow_minus_append, append_assoc], -- case `(2^m - c)/3 ≡ 1 [MOD 2]`
apply derivable.r1,
rw replicate_pow_minus_append,
exact (der_cons_replicate m), }, },
have hw₃ :
derivable (M::(replicate c I) ++ replicate ((2^m-c)/3) U ++ replicate ((2^m-c)/3 % 2) U),
{ apply der_cons_replicate_I_replicate_U_append_of_der_cons_replicate_I_append c ((2^m-c)/3) h,
convert hw₂, -- now we must show `c + 3 * ((2 ^ m - c) / 3) = 2 ^ m`
rw nat.mul_div_cancel',
{ exact add_tsub_cancel_of_le hm.1 },
{ exact (modeq_iff_dvd' hm.1).mp hm.2.symm } },
rw [append_assoc, ←replicate_add _ _] at hw₃,
cases add_mod2 ((2^m-c)/3) with t ht,
rw ht at hw₃,
exact der_of_der_append_replicate_U_even hw₃,
end
/-!
### `decstr` is a sufficient condition
The remainder of this file sets up the proof that `dectstr en` is sufficent to ensure
`derivable en`. Decidability of `derivable en` is an easy consequence.
The proof proceeds by induction on the `count U` of `en`.
We tackle first the base case of the induction. This requires auxiliary results giving
conditions under which `count I ys = length ys`.
-/
/--
If an `miustr` has a zero `count U` and contains no `M`, then its `count I` is its length.
-/
lemma count_I_eq_length_of_count_U_zero_and_neg_mem {ys : miustr} (hu : count U ys = 0)
(hm : M ∉ ys) : count I ys = length ys :=
begin
induction ys with x xs hxs,
{ refl, },
{ cases x,
{ exfalso, exact hm (mem_cons_self M xs), }, -- case `x = M` gives a contradiction.
{ rw [count_cons, if_pos (rfl), length, succ_eq_add_one, succ_inj'], -- case `x = I`
apply hxs,
{ simpa only [count], },
{ simp only [mem_cons_iff,false_or] at hm, exact hm, }, },
{ exfalso, simp only [count, countp_cons_of_pos] at hu, -- case `x = U` gives a contradiction.
exact succ_ne_zero _ hu, }, },
end
/--
`base_case_suf` is the base case of the sufficiency result.
-/
lemma base_case_suf (en : miustr) (h : decstr en) (hu : count U en = 0) : derivable en :=
begin
rcases h with ⟨⟨mhead, nmtail⟩, hi ⟩,
have : en ≠ nil,
{ intro k, simp only [k, count, countp, if_false, zero_mod, zero_ne_one, false_or] at hi,
contradiction, },
rcases (exists_cons_of_ne_nil this) with ⟨y,ys,rfl⟩,
rw head at mhead,
rw mhead at *,
rsuffices ⟨c, rfl, hc⟩ : ∃ c, replicate c I = ys ∧ (c % 3 = 1 ∨ c % 3 = 2),
{ exact der_replicate_I_of_mod3 c hc, },
{ simp only [count] at *,
use (count I ys),
refine and.intro _ hi,
apply replicate_count_eq_of_count_eq_length,
exact count_I_eq_length_of_count_U_zero_and_neg_mem hu nmtail, },
end
/-!
Before continuing to the proof of the induction step, we need other auxiliary results that
relate to `count U`.
-/
lemma mem_of_count_U_eq_succ {xs : miustr} {k : ℕ} (h : count U xs = succ k) : U ∈ xs :=
begin
induction xs with z zs hzs,
{ exfalso, rw count at h, contradiction, },
{ simp only [mem_cons_iff],
cases z,
repeat -- cases `z = M` and `z=I`
{ right, apply hzs, simp only [count, countp, if_false] at h, rw ←h, refl, },
{ left, refl, }, }, -- case `z = U`
end
lemma eq_append_cons_U_of_count_U_pos {k : ℕ} {zs : miustr} (h : count U zs = succ k) :
∃ (as bs : miustr), (zs = as ++ U :: bs) :=
mem_split (mem_of_count_U_eq_succ h)
/--
`ind_hyp_suf` is the inductive step of the sufficiency result.
-/
lemma ind_hyp_suf (k : ℕ) (ys : miustr) (hu : count U ys = succ k) (hdec : decstr ys) :
∃ (as bs : miustr), (ys = M::as ++ U:: bs) ∧ (count U (M::as ++ [I,I,I] ++ bs) = k) ∧
decstr (M::as ++ [I,I,I] ++ bs) :=
begin
rcases hdec with ⟨⟨mhead,nmtail⟩, hic⟩,
have : ys ≠ nil,
{ intro k, simp only [k ,count, countp, zero_mod, false_or, zero_ne_one] at hic, contradiction, },
rcases (exists_cons_of_ne_nil this) with ⟨z,zs,rfl⟩,
rw head at mhead,
rw mhead at *,
simp only [count, countp, cons_append, if_false, countp_append] at *,
rcases (eq_append_cons_U_of_count_U_pos hu) with ⟨as,bs,hab⟩,
rw hab at *,
simp only [countp, cons_append, if_pos, if_false, countp_append] at *,
use [as,bs],
apply and.intro rfl (and.intro (succ.inj hu) _),
split,
{ apply and.intro rfl,
simp only [tail, mem_append, mem_cons_iff, false_or, not_mem_nil, or_false] at *,
exact nmtail, },
{ simp only [count, countp, cons_append, if_false, countp_append, if_pos],
rw [add_right_comm, add_mod_right], exact hic, },
end
/--
`der_of_decstr` states that `derivable en` follows from `decstr en`.
-/
theorem der_of_decstr {en : miustr} (h : decstr en) : derivable en :=
begin
/- The next three lines have the effect of introducing `count U en` as a variable that can be used
for induction -/
have hu : ∃ n, count U en = n := exists_eq',
cases hu with n hu,
revert en, /- Crucially, we need the induction hypothesis to quantify over `en` -/
induction n with k hk,
{ exact base_case_suf, },
{ intros ys hdec hus,
rcases ind_hyp_suf k ys hus hdec with ⟨as, bs, hyab, habuc, hdecab⟩,
have h₂ : derivable (M::as ++ [I,I,I] ++ bs) := hk hdecab habuc,
rw hyab,
exact derivable.r3 h₂, },
end
/-!
### Decidability of `derivable`
-/
/--
Finally, we have the main result, namely that `derivable` is a decidable predicate.
-/
instance : decidable_pred derivable :=
λ en, decidable_of_iff _ ⟨der_of_decstr, decstr_of_der⟩
/-!
By decidability, we can automatically determine whether any given `miustr` is `derivable`.
-/
example : ¬(derivable "MU") :=
dec_trivial
example : derivable "MUIUIUIIIIIUUUIUII" :=
dec_trivial
end miu
|
c2479cd163de88e8979119cca17beb69be5af29f
|
a45212b1526d532e6e83c44ddca6a05795113ddc
|
/src/data/char.lean
|
94a651de537d4a65fe75681d2c32dbf357c7b7a3
|
[
"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
| 652
|
lean
|
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Supplementary theorems about the `char` type.
-/
instance : decidable_linear_order char :=
{ le_refl := λ a, @le_refl ℕ _ _,
le_trans := λ a b c, @le_trans ℕ _ _ _ _,
le_antisymm := λ a b h₁ h₂,
char.eq_of_veq $ le_antisymm h₁ h₂,
le_total := λ a b, @le_total ℕ _ _ _,
lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ℕ _ _ _,
decidable_le := char.decidable_le,
decidable_eq := char.decidable_eq,
decidable_lt := char.decidable_lt,
..char.has_le, ..char.has_lt }
|
9e3e3e104ff4d5cc69fb9bedca81a6e0513e867b
|
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
|
/data/padics/padic_norm.lean
|
549ed84975fbaf3e0addba145b90f35240ec306f
|
[
"Apache-2.0"
] |
permissive
|
kckennylau/mathlib
|
21fb810b701b10d6606d9002a4004f7672262e83
|
47b3477e20ffb5a06588dd3abb01fe0fe3205646
|
refs/heads/master
| 1,634,976,409,281
| 1,542,042,832,000
| 1,542,319,733,000
| 109,560,458
| 0
| 0
|
Apache-2.0
| 1,542,369,208,000
| 1,509,867,494,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 20,631
|
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
Define the p-adic valuation on ℤ and ℚ, and the p-adic norm on ℚ
-/
import data.rat data.int.gcd algebra.field_power
import tactic.wlog tactic.ring
universe u
open nat
attribute [class] nat.prime
private lemma exi_div (p : ℕ) (n : ℤ) : ∃ k : ℕ, k ≤ n.nat_abs ∧ ↑(p ^ k) ∣ n :=
⟨0, nat.zero_le _, by simp⟩
private lemma bound {p : ℕ} (hp : p > 1) {n : ℤ} (hn : n ≠ 0) :
∀ k : ℕ, k > n.nat_abs → ¬ (↑(p ^ k) ∣ n) :=
assume k (hkn : k > n.nat_abs),
have n.nat_abs < p^k, from lt.trans (lt_pow_self hp _) (pow_lt_pow_of_lt_right hp hkn),
assume hdvd : ↑(p ^ k) ∣ n,
have hdvd' : (p ^ k) ∣ n.nat_abs, from int.dvd_nat_abs_of_of_nat_dvd hdvd,
let hle := le_of_dvd (int.nat_abs_pos_of_ne_zero hn) hdvd' in
not_le_of_gt this hle
def padic_val (p : ℕ) (n : ℤ) : ℕ :=
if hn : n = 0 then 0
else if hp : p > 1 then nat.find_greatest (λ k, ↑(p ^ k) ∣ n) n.nat_abs
else 0
namespace padic_val
lemma spec {p : ℕ} (hp : p > 1) {n : ℤ} (hn : n ≠ 0) : ↑(p ^ padic_val p n) ∣ n :=
let ha := nat.find_greatest_spec (exi_div p n) in
by simpa [padic_val, hp, hn] using ha
lemma is_greatest {p : ℕ} (hp : p > 1) {n : ℤ} (hn : n ≠ 0) (m : ℕ) (hm : m > padic_val p n) :
¬ ↑(p ^ m) ∣ n :=
let ha := nat.find_greatest_is_greatest (exi_div p n) in
if hmb : m ≤ n.nat_abs then
have hfg : nat.find_greatest (λ (m : ℕ), ↑(p ^ m) ∣ n) (int.nat_abs n) < m,
by simpa [padic_val, hn, hp] using hm,
ha _ ⟨hfg, hmb⟩
else bound hp hn _ $ lt_of_not_ge hmb
lemma unique {p : ℕ} (hp : p > 1) {n : ℤ} (hn : n ≠ 0) {k : ℕ} (hk : ↑(p^k) ∣ n)
(hall : ∀ m : ℕ, m > k → ¬ ↑(p^m) ∣ n) : k = padic_val p n :=
have hle : k ≤ padic_val p n, from le_of_not_gt $ λ h, is_greatest hp hn _ h hk,
have hge : k ≥ padic_val p n, from le_of_not_gt $ λ h, hall _ h (spec hp hn),
le_antisymm hle hge
@[simp] protected lemma neg {p : ℕ} (hp : p > 1) (n : ℤ) : padic_val p (-n) = padic_val p n :=
if hn : n = 0 then by simp [hn] else
have hnn : -n ≠ 0, by simp [hn],
unique hp hn
(have ↑(p ^ padic_val p (-n)) ∣ (-n), from spec hp hnn, dvd_of_dvd_neg this)
(assume m hm (hdiv : (↑(p^m) ∣ n)),
have ↑(p^m) ∣ (-n), from dvd_neg_of_dvd hdiv,
is_greatest hp hnn _ hm this)
lemma le_padic_val_of_pow_dvd {p k : ℕ} (hp : p > 1) {n : ℤ} (hn : n ≠ 0) (h : ↑(p^k) ∣ n) :
k ≤ padic_val p n :=
le_of_not_gt $
assume : k > padic_val p n,
is_greatest hp hn _ this h
lemma pow_dvd_of_le_padic_val {p k : ℕ} (hp : p > 1) {n : ℤ} (hn : n ≠ 0) (h : k ≤ padic_val p n) :
↑(p^k) ∣ n :=
int.pow_dvd_of_le_of_pow_dvd h (spec hp hn)
lemma pow_dvd_iff_le_padic_val {p k : ℕ} (hp : p > 1) {n : ℤ} (hn : n ≠ 0) :
↑(p^k) ∣ n ↔ k ≤ padic_val p n :=
⟨le_padic_val_of_pow_dvd hp hn, pow_dvd_of_le_padic_val hp hn⟩
section
variables {p : ℕ} (hp : p > 1)
@[simp] protected lemma zero : padic_val p 0 = 0 := by simp [padic_val]
include hp
@[simp] protected lemma one : padic_val p 1 = 0 :=
begin
symmetry,
apply unique,
repeat { norm_num },
{ assumption },
{ intros k hk,
have h1k : 1 ^ k < p ^ k, from pow_lt_pow_of_lt_left hp hk,
rw nat.one_pow at h1k,
intro hdvd,
apply not_le_of_gt h1k,
apply le_of_dvd zero_lt_one,
apply int.coe_nat_dvd.1,
simpa }
end
@[simp] lemma padic_val_self : padic_val p p = 1 :=
have h : p ≠ 0, by intro h'; subst h'; exact absurd hp dec_trivial,
begin
symmetry, apply unique; simp *,
intros k hk hdvd,
apply not_pos_pow_dvd hp hk,
rw ← int.coe_nat_dvd, simpa
end
end
lemma padic_val_eq_zero_of_not_dvd {p : ℕ} {n : ℤ} (hnd : ¬ ↑p ∣ n) : padic_val p n = 0 :=
if h : n = 0 then by simp [h] else
if hp : p > 1 then
eq.symm $ padic_val.unique hp h (by simp) $ λ m hm hpm, hnd $
begin
rw [show p = p^1, by simp [hp]],
apply int.pow_dvd_of_le_of_pow_dvd _ hpm,
apply nat.succ_le_of_lt hm
end
else by simp [h, hp, padic_val]
lemma padic_val_eq_zero_of_not_dvd' {p : ℕ} {n : ℕ} (hnd : ¬ p ∣ n) : padic_val p n = 0 :=
by apply padic_val_eq_zero_of_not_dvd; simpa [int.coe_nat_dvd] using hnd
section padic_val
parameters (p : ℕ) [p_prime : prime p]
private lemma hpp : p > 1 := prime.gt_one p_prime
protected lemma mul {m n : ℤ} (hm : m ≠ 0) (hn : n ≠ 0) :
padic_val p m + padic_val p n = padic_val p (m*n) :=
have m*n ≠ 0, from mul_ne_zero hm hn,
have hdivm : ↑(p ^ padic_val p m) ∣ m, from spec hpp hm,
have hdivn : ↑(p ^ padic_val p n) ∣ n, from spec hpp hn,
have hpoweq : (↑(p ^ (padic_val p m + padic_val p n)) : ℤ) =
(↑(p ^ padic_val p m * p ^ padic_val p n) : ℤ),
by simp [nat.pow_add],
have hdiv : ↑(p ^ (padic_val p m + padic_val p n)) ∣ m*n,
by rw [hpoweq, int.coe_nat_mul]; apply mul_dvd_mul; assumption,
have hall : ∀ k : ℕ, k > padic_val p m + padic_val p n → ¬ ↑(p ^ k) ∣ m*n, from
assume (k : ℕ) (hkgt : k > padic_val p m + padic_val p n) (hdiv : ↑(p ^ k) ∣ m*n),
have hpsucc : ↑(p ^ (padic_val p m + padic_val p n + 1)) ∣ m*n, from
int.pow_dvd_of_le_of_pow_dvd hkgt hdiv,
have hsd : _, from int.succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul p_prime hdivm hdivn hpsucc,
or.elim hsd
(assume : ↑(p ^ (padic_val p m + 1)) ∣ m,
is_greatest hpp hm _ (lt_succ_self _) this)
(assume : ↑(p ^ (padic_val p n + 1)) ∣ n,
is_greatest hpp hn _ (lt_succ_self _) this),
have habs : m.nat_abs * n.nat_abs = (m*n).nat_abs, by simp [int.nat_abs_mul],
begin
simp only [habs] at *,
apply unique,
{ apply hpp },
repeat {assumption}
end
include p_prime
protected lemma pow {q : ℤ} (hq : q ≠ 0) {k : ℕ} :
padic_val p (q ^ k) = k * padic_val p q :=
begin
induction k with k ih,
{ rw [_root_.pow_zero, zero_mul, padic_val.one (hpp p)] },
rw [pow_succ', ← padic_val.mul (pow_ne_zero k hq) hq, succ_mul, ih]
end
end padic_val
section
variables {p : ℕ} (hp : p > 1)
include hp
lemma min_le_padic_val_add {m n : ℤ} (hmnz : m + n ≠ 0) :
min (padic_val p m) (padic_val p n) ≤ padic_val p (m + n) :=
if hmz : m = 0 then by simp [hmz, nat.zero_le]
else if hnz : n = 0 then by simp [hnz, nat.zero_le]
else
begin
wlog hle := le_total (padic_val p m) (padic_val p n) using [n m],
have hm : ∃ km, m = ↑(p ^ padic_val p m) * km, from spec hp hmz,
have hn : ∃ kn, n = ↑(p ^ padic_val p n) * kn, from spec hp hnz,
cases hm with km hkm,
cases hn with kn hkn,
have hmn : m + n = ↑(p ^ padic_val p m) * km + ↑(p ^ padic_val p n) * kn, by cc,
have hmn' : m + n = ↑(p ^ padic_val p m) * (km + ↑(p ^ (padic_val p n - padic_val p m)) * kn),
{ rw [left_distrib, hmn, ←nat.pow_eq_mul_pow_sub _ hle], simp [mul_assoc] },
have hpp : ↑(p ^ padic_val p m) ∣ (m + n),
{ rw hmn', apply dvd_mul_of_dvd_left, apply dvd_refl },
have hpvle : padic_val p m ≤ padic_val p (m+n), from
le_padic_val_of_pow_dvd hp hmnz hpp,
transitivity,
{ apply min_le_left },
{ apply hpvle }
end
lemma dvd_of_padic_val_pos {n : ℤ} (hpn : padic_val p n > 0) : ↑p ∣ n :=
if hn : n = 0 then by simp [hn]
else let hps := padic_val.spec hp hn in int.dvd_of_pow_dvd hpn hps
lemma padic_val_eq_zero_of_coprime {a b : ℕ} (hle : padic_val p a ≤ padic_val p b)
(hab : nat.coprime a b) : padic_val p a = 0 :=
by_contradiction $ λ h,
have hap : padic_val p a > 0, from nat.pos_of_ne_zero h,
nat.not_coprime_of_dvd_of_dvd hp
(int.coe_nat_dvd.1 (dvd_of_padic_val_pos hp hap))
(int.coe_nat_dvd.1 (dvd_of_padic_val_pos hp (lt_of_lt_of_le hap hle)))
hab
end
end padic_val
local infix `/.`:70 := rat.mk
def padic_val_rat (p : ℕ) (q : ℚ) : ℤ :=
(padic_val p q.num : ℤ) - (padic_val p q.denom : ℤ)
namespace padic_val_rat
section padic_val_rat
variables {p : ℕ} (hp : p > 1)
include hp
@[simp] protected lemma neg (q : ℚ) : padic_val_rat p (-q) = padic_val_rat p q :=
begin
simp [padic_val_rat, hp]
end
@[simp] protected lemma one : padic_val_rat p 1 = 0 :=
have (1 : ℚ).num = 1, from rfl,
have (1 : ℚ).denom = 1, from rfl,
by simp [padic_val_rat, *]
@[simp] lemma padic_val_rat_self : padic_val_rat p p = 1 :=
by simp [padic_val_rat, hp]
lemma padic_val_rat_of_int (z : ℤ) : padic_val_rat p ↑z = padic_val p z :=
by simp [padic_val_rat, rat.coe_int_denom, padic_val.one hp]
end padic_val_rat
section padic_val_rat
open padic_val
variables (p : ℕ) [p_prime : prime p]
include p_prime
protected lemma defn {q : ℚ} {n d : ℤ} (hqz : q ≠ 0) (qdf : q = n /. d) :
padic_val_rat p q = (padic_val p n : ℤ) - padic_val p d :=
have hn : n ≠ 0, from rat.mk_num_ne_zero_of_ne_zero hqz qdf,
have hd : d ≠ 0, from rat.mk_denom_ne_zero_of_ne_zero hqz qdf,
have h : ∃ c : ℤ, n = c * q.num ∧ d = c * q.denom, from rat.num_denom_mk hn hd qdf,
have hqn : q.num ≠ 0, from rat.num_ne_zero_of_ne_zero hqz,
have hqd : (↑q.denom : ℤ) ≠ 0, by simp [rat.denom_ne_zero],
begin
rcases h with ⟨c, ⟨hc1, hc2⟩⟩,
have hcz : c ≠ 0,
{ intro hc,
subst hc,
apply hn, simpa using hc1 },
unfold padic_val_rat,
rw [hc1, hc2, ←padic_val.mul p hcz hqn, ←padic_val.mul p hcz hqd],
simp [p_prime.gt_one], ring
end
protected lemma mul {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) :
padic_val_rat p (q*r) = padic_val_rat p q + padic_val_rat p r :=
have q*r = (q.num * r.num) /. (↑q.denom * ↑r.denom), by simp [rat.mul_num_denom],
begin
rw padic_val_rat.defn p (mul_ne_zero hq hr) this,
unfold padic_val_rat,
rw [←padic_val.mul, ←padic_val.mul],
{simp},
repeat {apply int.coe_nat_ne_zero.2, apply ne_of_gt, apply rat.pos},
repeat {apply rat.num_ne_zero_of_ne_zero, assumption}
end
protected lemma pow {q : ℚ} (hq : q ≠ 0) {k : ℕ} :
padic_val_rat p (q ^ k) = k * padic_val_rat p q :=
begin
induction k with k ih,
{ rw [_root_.pow_zero, int.coe_nat_zero, zero_mul, padic_val_rat.one p_prime.gt_one] },
rw [pow_succ', padic_val_rat.mul p (pow_ne_zero k hq) hq, int.coe_nat_succ, add_mul, ih, one_mul]
end
protected lemma div {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) :
padic_val_rat p (q / r) = padic_val_rat p q - padic_val_rat p r :=
have hqr : q / r ≠ 0, from div_ne_zero hq hr,
have hnd' : _, from padic_val_rat.defn p hqr (rat.div_num_denom q r),
have _, from rat.denom_ne_zero q, have _, from rat.denom_ne_zero r,
begin
rw [←padic_val.mul, ←padic_val.mul] at hnd',
{ simpa [padic_val_rat] using hnd' },
all_goals { simpa <|> by apply rat.num_ne_zero_of_ne_zero; assumption }
end
theorem min_le_padic_val_rat_add {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) (hqr : q + r ≠ 0) :
min (padic_val_rat p q) (padic_val_rat p r) ≤ padic_val_rat p (q + r) :=
have hqn : q.num ≠ 0, from rat.num_ne_zero_of_ne_zero hq,
have hqd : q.denom ≠ 0, from rat.denom_ne_zero _,
have hrn : r.num ≠ 0, from rat.num_ne_zero_of_ne_zero hr,
have hrd : r.denom ≠ 0, from rat.denom_ne_zero _,
have hqdv : q.num /. q.denom ≠ 0, from rat.mk_ne_zero_of_ne_zero hqn (by simpa),
have hrdv : r.num /. r.denom ≠ 0, from rat.mk_ne_zero_of_ne_zero hrn (by simpa),
have hqreq : q + r = (((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ)),
from calc
q + r = (q.num /. q.denom + r.num /. r.denom) : by rw [←rat.num_denom q, ←rat.num_denom r]
... = (↑q.num : ℚ) / ↑q.denom + ((↑r.num : ℚ) / ↑r.denom) : by simp [rat.mk_eq_div]
... = (q.num * r.denom + q.denom * r.num) / (↑q.denom * ↑r.denom) :
by rw div_add_div _ _ (show (q.denom : ℚ) ≠ 0, by simpa) (show (r.denom : ℚ) ≠ 0, by simpa)
... = ((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ) :
by simp [rat.mk_eq_div],
have hsnz : q.num*r.denom + q.denom*r.num ≠ 0, from
assume heq,
have q + r = 0 /. (q.denom * r.denom), by rwa [heq] at hqreq,
hqr (by simpa),
have hge : (padic_val p (q.num * r.denom + q.denom * r.num) : ℤ) ≥
min ((padic_val p (q.num*r.denom)) : ℤ)
(padic_val p (q.denom*r.num)),
from calc
min ((padic_val p (q.num*r.denom)) : ℤ)
(padic_val p (q.denom*r.num)) =
(min (padic_val p (q.num*r.denom))
(padic_val p (q.denom*r.num)) : ℤ) :
by simp
... ≤ (padic_val p (q.num * r.denom + q.denom * r.num) : ℤ) :
begin
apply min_le_iff.2,
simp only [int.coe_nat_le],
apply min_le_iff.1,
apply min_le_padic_val_add,
exact p_prime.gt_one,
assumption
end,
calc
padic_val_rat p (q + r)
= padic_val_rat p
(((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ)) :
by rw hqreq
... = padic_val p
(q.num * r.denom + q.denom * r.num) -
padic_val p (↑q.denom * ↑r.denom) :
begin apply padic_val_rat.defn p, cc, reflexivity end
... ≥ min (padic_val p (q.num*r.denom))
(padic_val p (q.denom*r.num)) -
padic_val p (↑q.denom * ↑r.denom) :
sub_le_sub hge (le_refl _)
... = min (padic_val p q.num +
padic_val p r.denom)
(padic_val p q.denom +
padic_val p r.num) -
(padic_val p q.denom +
padic_val p r.denom) :
begin rw [←padic_val.mul, ←padic_val.mul, ←padic_val.mul], reflexivity,repeat {simpa <|> assumption} end
... = min (padic_val p q.num +
padic_val p r.denom -
(padic_val p q.denom +
padic_val p r.denom))
(padic_val p q.denom +
padic_val p r.num -
(padic_val p q.denom +
padic_val p r.denom)) :
by apply min_sub
... = min (padic_val p q.num -
padic_val p q.denom)
(padic_val p r.num -
padic_val p r.denom) :
by simp
... = min (padic_val_rat p (q.num /. ↑q.denom))
(padic_val_rat p (r.num /. ↑r.denom)) :
by rw [padic_val_rat.defn p, padic_val_rat.defn p]; simp *
... = min (padic_val_rat p q)
(padic_val_rat p r) :
by rw [←rat.num_denom q, ←rat.num_denom r]
end padic_val_rat
end padic_val_rat
def padic_norm (p : ℕ) (q : ℚ) : ℚ :=
if q = 0 then 0 else fpow (↑p : ℚ) (-(padic_val_rat p q))
namespace padic_norm
section padic_norm
open padic_val_rat
variables (p : ℕ) [hp : prime p]
include hp
@[simp] protected lemma zero : padic_norm p 0 = 0 := by simp [padic_norm]
@[simp] protected lemma eq_fpow_of_nonzero {q : ℚ} (hq : q ≠ 0) :
padic_norm p q = fpow p (-(padic_val_rat p q)) :=
by simp [hq, padic_norm]
protected lemma nonzero {q : ℚ} (hq : q ≠ 0) : padic_norm p q ≠ 0 :=
begin
rw padic_norm.eq_fpow_of_nonzero p hq,
apply fpow_ne_zero_of_ne_zero, simp,
apply ne_of_gt,
simpa using hp.pos
end
@[simp] protected lemma neg (q : ℚ) : padic_norm p (-q) = padic_norm p q :=
if hq : q = 0 then by simp [hq]
else by simp [padic_norm, hq, hp.gt_one]
lemma zero_of_padic_norm_eq_zero {q : ℚ} (h : padic_norm p q = 0) : q = 0 :=
by_contradiction $
assume hq : q ≠ 0,
have padic_norm p q = fpow p (-(padic_val_rat p q)), by simp [hq],
fpow_ne_zero_of_ne_zero
(show (↑p : ℚ) ≠ 0, by simp [prime.ne_zero hp])
(-(padic_val_rat p q)) (by rw [←this, h])
protected lemma nonneg (q : ℚ) : padic_norm p q ≥ 0 :=
if hq : q = 0 then by simp [hq]
else
begin
unfold padic_norm; split_ifs,
apply fpow_nonneg_of_nonneg,
apply nat.cast_nonneg
end
@[simp] protected theorem mul (q r : ℚ) : padic_norm p (q*r) = padic_norm p q * padic_norm p r :=
if hq : q = 0 then
by simp [hq]
else if hr : r = 0 then
by simp [hr]
else
have q*r ≠ 0, from mul_ne_zero hq hr,
have (↑p : ℚ) ≠ 0, by simp [prime.ne_zero hp],
by simp [padic_norm, *, padic_val_rat.mul, fpow_add this]
@[simp] protected theorem div (q r : ℚ) : padic_norm p (q / r) = padic_norm p q / padic_norm p r :=
if hr : r = 0 then by simp [hr] else
eq_div_of_mul_eq _ _ (padic_norm.nonzero _ hr) (by rw [←padic_norm.mul, div_mul_cancel _ hr])
protected theorem of_int (z : ℤ) : padic_norm p ↑z ≤ 1 :=
if hz : z = 0 then by simp [hz] else
begin
suffices : padic_norm p ↑z = fpow (↑p : ℚ) (-(padic_val p z)),
{ convert fpow_le_one_of_nonpos (show (↑p : ℚ) ≥ ↑(1 : ℕ), from _) _,
{ apply le_of_lt, apply nat.cast_lt.2 hp.gt_one },
apply neg_nonpos.2,
apply int.coe_nat_nonneg },
have hnz : padic_val_rat p z = padic_val p z, from padic_val_rat_of_int hp.gt_one z,
simp [padic_val_rat, hz, hnz]
end
--TODO: p implicit
private lemma nonarchimedean_aux {q r : ℚ} (h : padic_val_rat p q ≤ padic_val_rat p r) :
padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) :=
have hnqp : padic_norm p q ≥ 0, from padic_norm.nonneg _ _,
have hnrp : padic_norm p r ≥ 0, from padic_norm.nonneg _ _,
if hq : q = 0 then
by simp [hq, max_eq_right hnrp]
else if hr : r = 0 then
by simp [hr, max_eq_left hnqp]
else if hqr : q + r = 0 then
le_trans (by simpa [hqr] using padic_norm.nonneg) (le_max_left _ _)
else
begin
unfold padic_norm, split_ifs,
apply le_max_iff.2,
left,
have hpge1 : (↑p : ℚ) ≥ ↑(1 : ℕ), from (nat.cast_le.2 $ le_of_lt $ prime.gt_one hp),
apply fpow_le_of_le hpge1,
apply neg_le_neg,
have : padic_val_rat p q =
min (padic_val_rat p q) (padic_val_rat p r),
from (min_eq_left h).symm,
rw this,
apply min_le_padic_val_rat_add; assumption
end
protected theorem nonarchimedean {q r : ℚ} :
padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) :=
begin
wlog hle := le_total (padic_val_rat p q) (padic_val_rat p r) using [q r],
exact nonarchimedean_aux p hle
end
theorem triangle_ineq (q r : ℚ) : padic_norm p (q + r) ≤ padic_norm p q + padic_norm p r :=
calc padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) : padic_norm.nonarchimedean p
... ≤ padic_norm p q + padic_norm p r :
max_le_add_of_nonneg (padic_norm.nonneg p _) (padic_norm.nonneg p _)
protected theorem sub {q r : ℚ} : padic_norm p (q - r) ≤ max (padic_norm p q) (padic_norm p r) :=
by rw [sub_eq_add_neg, ←padic_norm.neg p r]; apply padic_norm.nonarchimedean
lemma add_eq_max_of_ne {q r : ℚ} (hne : padic_norm p q ≠ padic_norm p r) :
padic_norm p (q + r) = max (padic_norm p q) (padic_norm p r) :=
begin
wlog hle := le_total (padic_norm p r) (padic_norm p q) using [q r],
have hlt : padic_norm p r < padic_norm p q, from lt_of_le_of_ne hle hne.symm,
have : padic_norm p q ≤ max (padic_norm p (q + r)) (padic_norm p r), from calc
padic_norm p q = padic_norm p (q + r - r) : by congr; ring
... ≤ max (padic_norm p (q + r)) (padic_norm p (-r)) : padic_norm.nonarchimedean p
... = max (padic_norm p (q + r)) (padic_norm p r) : by simp,
have hnge : padic_norm p r ≤ padic_norm p (q + r),
{ apply le_of_not_gt,
intro hgt,
rw max_eq_right_of_lt hgt at this,
apply not_lt_of_ge this,
assumption },
have : padic_norm p q ≤ padic_norm p (q + r), by rwa [max_eq_left hnge] at this,
apply _root_.le_antisymm,
{ apply padic_norm.nonarchimedean p },
{ rw max_eq_left_of_lt hlt,
assumption }
end
protected theorem image {q : ℚ} (hq : q ≠ 0) : ∃ n : ℤ, padic_norm p q = fpow p (-n) :=
⟨ (padic_val_rat p q), by simp [padic_norm, hq] ⟩
instance : is_absolute_value (padic_norm p) :=
{ abv_nonneg := padic_norm.nonneg p,
abv_eq_zero :=
begin
intros,
constructor; intro,
{ apply zero_of_padic_norm_eq_zero p, assumption },
{ simp [*] }
end,
abv_add := padic_norm.triangle_ineq p,
abv_mul := padic_norm.mul p }
lemma le_of_dvd {n : ℕ} {z : ℤ} (hd : ↑(p^n) ∣ z) : padic_norm p z ≤ fpow ↑p (-n) :=
have hp' : (↑p : ℚ) ≥ 1, from show ↑p ≥ ↑(1 : ℕ), from cast_le.2 (le_of_lt hp.gt_one),
have hpn : (↑p : ℚ) ≥ 0, from le_trans zero_le_one hp',
begin
unfold padic_norm, split_ifs with hz hz,
{ simpa [padic_norm, hz] using fpow_nonneg_of_nonneg hpn _ },
{ apply fpow_le_of_le hp',
apply neg_le_neg,
rw padic_val_rat_of_int hp.gt_one _,
apply int.coe_nat_le.2,
apply padic_val.le_padic_val_of_pow_dvd hp.gt_one,
{ simpa using hz },
{ assumption }}
end
end padic_norm
end padic_norm
|
1f2ee642e47e5babcc6c326eb3e4f9cb09df5f8a
|
63abd62053d479eae5abf4951554e1064a4c45b4
|
/src/linear_algebra/tensor_product.lean
|
3abae6c67a113ee754b51de59a9ea6ff6f711fff
|
[
"Apache-2.0"
] |
permissive
|
Lix0120/mathlib
|
0020745240315ed0e517cbf32e738d8f9811dd80
|
e14c37827456fc6707f31b4d1d16f1f3a3205e91
|
refs/heads/master
| 1,673,102,855,024
| 1,604,151,044,000
| 1,604,151,044,000
| 308,930,245
| 0
| 0
|
Apache-2.0
| 1,604,164,710,000
| 1,604,163,547,000
| null |
UTF-8
|
Lean
| false
| false
| 24,134
|
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 group_theory.congruence
import linear_algebra.basic
/-!
# 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
variables {R : Type*} [comm_semiring R]
variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*}
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q]
[add_comm_monoid S]
variables [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] [semimodule R S]
include R
variables (R)
/-- Create a bilinear map from a function that is linear in each component. -/
def mk₂ (f : M → N → P)
(H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c:R) m n, f (c • m) n = c • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c:R) m n, f m (c • n) = c • f m n) : M →ₗ N →ₗ P :=
⟨λ m, ⟨f m, H3 m, λ c, H4 c m⟩,
λ m₁ m₂, linear_map.ext $ H1 m₁ m₂,
λ c m, linear_map.ext $ H2 c m⟩
variables {R}
@[simp] theorem mk₂_apply
(f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) :
(mk₂ R f H1 H2 H3 H4 : M →ₗ[R] N →ₗ P) m n = f m n := rfl
theorem ext₂ {f g : M →ₗ[R] N →ₗ[R] P}
(H : ∀ m n, f m n = g m n) : f = g :=
linear_map.ext (λ m, linear_map.ext $ λ 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 (f : M →ₗ[R] N →ₗ[R] P) : N →ₗ M →ₗ P :=
mk₂ R (λ n m, f m n)
(λ n₁ n₂ m, (f m).map_add _ _)
(λ c n m, (f m).map_smul _ _)
(λ n m₁ m₂, by rw f.map_add; refl)
(λ c n m, by rw f.map_smul; refl)
variable (f : M →ₗ[R] N →ₗ[R] P)
@[simp] theorem flip_apply (m : M) (n : N) : flip f n m = f m n := rfl
variables {R}
theorem flip_inj {f g : M →ₗ[R] N →ₗ P} (H : flip f = flip g) : f = g :=
ext₂ $ λ m n, show flip f n m = flip g n m, by rw H
variables (R M N P)
/-- 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 : (M →ₗ[R] N →ₗ P) →ₗ[R] N →ₗ M →ₗ P :=
⟨flip, λ _ _, rfl, λ _ _, rfl⟩
variables {R M N P}
@[simp] theorem lflip_apply (m : M) (n : N) : lflip R M N P f n m = f m n := rfl
theorem map_zero₂ (y) : f 0 y = 0 := (flip f y).map_zero
theorem map_neg₂ {R : Type*} [comm_ring R] {M N P : Type*}
[add_comm_group M] [add_comm_group N] [add_comm_group P]
[module R M] [module R N] [module R P] (f : M →ₗ[R] N →ₗ[R] P) (x y) :
f (-x) y = -f x y :=
(flip f y).map_neg _
theorem map_add₂ (x₁ x₂ y) : f (x₁ + x₂) y = f x₁ y + f x₂ y := (flip f y).map_add _ _
theorem map_smul₂ (r:R) (x y) : f (r • x) y = r • f x y := (flip f y).map_smul _ _
variables (R P)
/-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/
def lcomp (f : M →ₗ[R] N) : (N →ₗ[R] P) →ₗ[R] M →ₗ[R] P :=
flip $ linear_map.comp (flip id) f
variables {R P}
@[simp] theorem lcomp_apply (f : M →ₗ[R] N) (g : N →ₗ P) (x : M) :
lcomp R P f g x = g (f x) := rfl
variables (R M N P)
/-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/
def llcomp : (N →ₗ[R] P) →ₗ[R] (M →ₗ[R] N) →ₗ M →ₗ P :=
flip ⟨lcomp R P,
λ f f', ext₂ $ λ g x, g.map_add _ _,
λ c f, ext₂ $ λ g x, g.map_smul _ _⟩
variables {R M N P}
section
@[simp] theorem llcomp_apply (f : N →ₗ[R] P) (g : M →ₗ[R] N) (x : M) :
llcomp R M N P f g x = f (g x) := rfl
end
/-- Composing a linear map `Q → N` and a bilinear map `M → N → P` to
form a bilinear map `M → Q → P`. -/
def compl₂ (g : Q →ₗ N) : M →ₗ Q →ₗ P := (lcomp R _ g).comp f
@[simp] theorem compl₂_apply (g : Q →ₗ[R] N) (m : M) (q : Q) :
f.compl₂ g m q = f m (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₂ (g : P →ₗ Q) : M →ₗ N →ₗ Q :=
linear_map.comp (llcomp R N P Q g) f
@[simp] theorem compr₂_apply (g : P →ₗ[R] Q) (m : M) (n : N) :
f.compr₂ g m n = g (f m n) := rfl
variables (R M)
/-- Scalar multiplication as a bilinear map `R → M → M`. -/
def lsmul : R →ₗ M →ₗ M :=
mk₂ R (•) add_smul (λ _ _ _, mul_smul _ _ _) smul_add
(λ r s m, by simp only [smul_smul, smul_eq_mul, mul_comm])
variables {R M}
@[simp] theorem lsmul_apply (r : R) (m : M) : lsmul R M r m = r • m := rfl
end linear_map
section semiring
variables {R : Type*} [comm_semiring R]
variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*}
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q]
[add_comm_monoid S]
variables [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] [semimodule R S]
include R
variables (M N)
namespace tensor_product
section
-- open free_add_monoid
variables (R)
/-- The relation on `free_add_monoid (M × N)` that generates a congruence whose quotient is
the tensor product. -/
inductive eqv : free_add_monoid (M × N) → free_add_monoid (M × N) → Prop
| of_zero_left : ∀ n : N, eqv (free_add_monoid.of (0, n)) 0
| of_zero_right : ∀ m : M, eqv (free_add_monoid.of (m, 0)) 0
| of_add_left : ∀ (m₁ m₂ : M) (n : N), eqv
(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
(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
(free_add_monoid.of (r • m, n)) (free_add_monoid.of (m, r • n))
| add_comm : ∀ x y, eqv (x + y) (y + x)
end
end tensor_product
variables (R)
/-- 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 : Type* :=
(add_con_gen (tensor_product.eqv R M N)).quotient
variables {R}
localized "infix ` ⊗ `:100 := tensor_product _" in tensor_product
localized "notation M ` ⊗[`:100 R `] ` N:100 := tensor_product R M N" in tensor_product
namespace tensor_product
section module
instance : add_comm_monoid (M ⊗[R] N) :=
{ add_comm := λ x y, add_con.induction_on₂ x y $ λ x y, quotient.sound' $
add_con_gen.rel.of _ _ $ eqv.add_comm _ _,
.. (add_con_gen (tensor_product.eqv R M N)).add_monoid }
instance : inhabited (M ⊗[R] N) := ⟨0⟩
variables (R) {M N}
/-- 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 (m : M) (n : N) : M ⊗[R] N := add_con.mk' _ $ free_add_monoid.of (m, n)
variables {R}
infix ` ⊗ₜ `:100 := tmul _
notation x ` ⊗ₜ[`:100 R `] ` y := tmul R x y
@[elab_as_eliminator]
protected theorem induction_on
{C : (M ⊗[R] N) → Prop}
(z : M ⊗[R] N)
(C0 : C 0)
(C1 : ∀ {x y}, C $ x ⊗ₜ[R] y)
(Cp : ∀ {x y}, C x → C y → C (x + y)) : C z :=
add_con.induction_on z $ λ x, free_add_monoid.rec_on x C0 $ λ ⟨m, n⟩ y ih,
by { rw add_con.coe_add, exact Cp C1 ih }
variables (M)
@[simp] lemma zero_tmul (n : N) : (0 ⊗ₜ n : M ⊗[R] N) = 0 :=
quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_left _
variables {M}
lemma add_tmul (m₁ m₂ : M) (n : N) : (m₁ + m₂) ⊗ₜ n = m₁ ⊗ₜ n + m₂ ⊗ₜ[R] n :=
eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_left _ _ _
variables (N)
@[simp] lemma tmul_zero (m : M) : (m ⊗ₜ 0 : M ⊗[R] N) = 0 :=
quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_right _
variables {N}
lemma tmul_add (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ + n₂) = m ⊗ₜ n₁ + m ⊗ₜ[R] n₂ :=
eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_right _ _ _
lemma smul_tmul (r : R) (m : M) (n : N) : (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n) :=
quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_smul _ _ _
/-- Auxiliary function to defining scalar multiplication on tensor product. -/
def smul.aux (r : R) : free_add_monoid (M × N) →+ M ⊗[R] N :=
free_add_monoid.lift $ λ p : M × N, (r • p.1) ⊗ₜ p.2
theorem smul.aux_of (r : R) (m : M) (n : N) :
smul.aux r (free_add_monoid.of (m, n)) = (r • m) ⊗ₜ n :=
rfl
instance : has_scalar R (M ⊗[R] N) :=
⟨λ r, (add_con_gen (tensor_product.eqv R M N)).lift (smul.aux r) $ add_con.add_con_gen_le $
λ x y hxy, match x, y, hxy with
| _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, smul.aux_of, smul_zero, zero_tmul]
| _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, smul.aux_of, tmul_zero]
| _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, smul.aux_of, smul_add, add_tmul]
| _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, smul.aux_of, tmul_add]
| _, _, (eqv.of_smul s m n) := (add_con.ker_rel _).2 $
by simp_rw [smul.aux_of, smul_tmul, smul_smul, mul_comm]
| _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, add_comm]
end⟩
protected theorem smul_zero (r : R) : (r • 0 : M ⊗[R] N) = 0 :=
add_monoid_hom.map_zero _
protected theorem smul_add (r : R) (x y : M ⊗[R] N) :
r • (x + y) = r • x + r • y :=
add_monoid_hom.map_add _ _ _
theorem smul_tmul' (r : R) (m : M) (n : N) :
r • (m ⊗ₜ n : M ⊗[R] N) = (r • m) ⊗ₜ n :=
rfl
instance : semimodule R (M ⊗[R] N) :=
{ smul := (•),
smul_add := λ r x y, tensor_product.smul_add r x y,
mul_smul := λ r s x, tensor_product.induction_on x
(by simp_rw tensor_product.smul_zero)
(λ m n, by simp_rw [smul_tmul', mul_smul])
(λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy] }),
one_smul := λ x, tensor_product.induction_on x
(by rw tensor_product.smul_zero)
(λ m n, by rw [smul_tmul', one_smul])
(λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy]),
add_smul := λ r s x, tensor_product.induction_on x
(by simp_rw [tensor_product.smul_zero, add_zero])
(λ m n, by simp_rw [smul_tmul', add_smul, add_tmul])
(λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy, add_add_add_comm] }),
smul_zero := λ r, tensor_product.smul_zero r,
zero_smul := λ x, tensor_product.induction_on x
(by rw tensor_product.smul_zero)
(λ m n, by rw [smul_tmul', zero_smul, zero_tmul])
(λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy, add_zero]) }
@[simp] lemma tmul_smul (r : R) (x : M) (y : N) : x ⊗ₜ (r • y) = r • (x ⊗ₜ[R] y) :=
(smul_tmul _ _ _).symm
variables (R M N)
/-- The canonical bilinear map `M → N → M ⊗[R] N`. -/
def mk : M →ₗ N →ₗ M ⊗[R] N :=
linear_map.mk₂ R (⊗ₜ) add_tmul (λ c m n, by rw [smul_tmul, tmul_smul]) tmul_add tmul_smul
variables {R M N}
@[simp] lemma mk_apply (m : M) (n : N) : mk R M N m n = m ⊗ₜ n := rfl
lemma ite_tmul (x₁ : M) (x₂ : N) (P : Prop) [decidable P] :
((if P then x₁ else 0) ⊗ₜ[R] x₂) = if P then (x₁ ⊗ₜ x₂) else 0 :=
by { split_ifs; simp }
lemma tmul_ite (x₁ : M) (x₂ : N) (P : Prop) [decidable P] :
(x₁ ⊗ₜ[R] (if P then x₂ else 0)) = if P then (x₁ ⊗ₜ x₂) else 0 :=
by { split_ifs; simp }
section
open_locale big_operators
lemma sum_tmul {α : Type*} (s : finset α) (m : α → M) (n : N) :
((∑ a in s, m a) ⊗ₜ[R] n) = ∑ a in s, m a ⊗ₜ[R] n :=
begin
classical,
induction s using finset.induction with a s has ih h,
{ simp, },
{ simp [finset.sum_insert has, add_tmul, ih], },
end
lemma tmul_sum (m : M) {α : Type*} (s : finset α) (n : α → N) :
(m ⊗ₜ[R] (∑ a in s, n a)) = ∑ a in s, m ⊗ₜ[R] n a :=
begin
classical,
induction s using finset.induction with a s has ih h,
{ simp, },
{ simp [finset.sum_insert has, tmul_add, ih], },
end
end
end module
section UMP
variables {M N P Q}
variables (f : M →ₗ[R] N →ₗ[R] P)
/-- 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 : (M ⊗[R] N) →+ P :=
(add_con_gen (tensor_product.eqv R M N)).lift (free_add_monoid.lift $ λ p : M × N, f p.1 p.2) $
add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with
| _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, f.map_zero₂]
| _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, (f m).map_zero]
| _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, f.map_add₂]
| _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, (f m).map_add]
| _, _, (eqv.of_smul r m n) := (add_con.ker_rel _).2 $
by simp_rw [free_add_monoid.lift_eval_of, f.map_smul₂, (f m).map_smul]
| _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, add_comm]
end
lemma lift_aux_tmul (m n) : lift_aux f (m ⊗ₜ n) = f m n :=
zero_add _
variable {f}
@[simp] lemma lift_aux.smul (r : R) (x) : lift_aux f (r • x) = r • lift_aux f x :=
tensor_product.induction_on x (smul_zero _).symm
(λ p q, by rw [← tmul_smul, lift_aux_tmul, lift_aux_tmul, (f p).map_smul])
(λ p q ih1 ih2, by rw [smul_add, (lift_aux f).map_add, ih1, ih2, (lift_aux f).map_add, smul_add])
variable (f)
/-- 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 : M ⊗ N →ₗ P :=
{ map_smul' := lift_aux.smul,
.. lift_aux f }
variable {f}
@[simp] lemma lift.tmul (x y) : lift f (x ⊗ₜ y) = f x y :=
zero_add _
@[simp] lemma lift.tmul' (x y) : (lift f).1 (x ⊗ₜ y) = f x y :=
lift.tmul _ _
@[ext]
theorem ext {g h : (M ⊗[R] N) →ₗ[R] P}
(H : ∀ x y, g (x ⊗ₜ y) = h (x ⊗ₜ y)) : g = h :=
linear_map.ext $ λ z, tensor_product.induction_on z (by simp_rw linear_map.map_zero) H $
λ x y ihx ihy, by rw [g.map_add, h.map_add, ihx, ihy]
theorem lift.unique {g : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = f x y) :
g = lift f :=
ext $ λ m n, by rw [H, lift.tmul]
theorem lift_mk : lift (mk R M N) = linear_map.id :=
eq.symm $ lift.unique $ λ x y, rfl
theorem lift_compr₂ (g : P →ₗ Q) : lift (f.compr₂ g) = g.comp (lift f) :=
eq.symm $ lift.unique $ λ x y, by simp
theorem lift_mk_compr₂ (f : M ⊗ N →ₗ P) : lift ((mk R M N).compr₂ f) = f :=
by rw [lift_compr₂ f, lift_mk, linear_map.comp_id]
theorem mk_compr₂_inj {g h : M ⊗ N →ₗ P}
(H : (mk R M N).compr₂ g = (mk R M N).compr₂ h) : g = h :=
by rw [← lift_mk_compr₂ g, H, lift_mk_compr₂]
example : M → N → (M → N → P) → P :=
λ m, flip $ λ f, f m
variables (R M N P)
/-- 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 : (M →ₗ[R] N →ₗ[R] P) →ₗ[R] M ⊗[R] N →ₗ[R] P :=
linear_map.flip $ lift $ (linear_map.lflip _ _ _ _).comp (linear_map.flip linear_map.id)
variables {R M N P}
@[simp] theorem uncurry_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) :
uncurry R M N P f (m ⊗ₜ n) = f m n :=
by rw [uncurry, linear_map.flip_apply, lift.tmul]; refl
variables (R M N P)
/-- 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 : (M →ₗ N →ₗ P) ≃ₗ (M ⊗ N →ₗ P) :=
{ inv_fun := λ f, (mk R M N).compr₂ f,
left_inv := λ f, linear_map.ext₂ $ λ m n, lift.tmul _ _,
right_inv := λ f, ext $ λ m n, lift.tmul _ _,
.. uncurry R M N P }
/-- 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 : (M ⊗[R] N →ₗ[R] P) →ₗ[R] M →ₗ[R] N →ₗ[R] P :=
(lift.equiv R M N P).symm
variables {R M N P}
@[simp] theorem lcurry_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) :
lcurry R M N P f m n = f (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 (f : M ⊗ N →ₗ P) : M →ₗ N →ₗ P := lcurry R M N P f
@[simp] theorem curry_apply (f : M ⊗ N →ₗ[R] P) (m : M) (n : N) :
curry f m n = f (m ⊗ₜ n) := rfl
theorem ext_threefold {g h : (M ⊗[R] N) ⊗[R] P →ₗ[R] Q}
(H : ∀ x y z, g ((x ⊗ₜ y) ⊗ₜ z) = h ((x ⊗ₜ y) ⊗ₜ z)) : g = h :=
begin
let e := linear_equiv.to_equiv (lift.equiv R (M ⊗[R] N) P Q),
apply e.symm.injective,
refine ext _,
intros x y,
ext z,
exact H x y z
end
-- We'll need this one for checking the pentagon identity!
theorem ext_fourfold {g h : ((M ⊗[R] N) ⊗[R] P) ⊗[R] Q →ₗ[R] S}
(H : ∀ w x y z, g (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z) = h (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z)) : g = h :=
begin
let e := linear_equiv.to_equiv (lift.equiv R ((M ⊗[R] N) ⊗[R] P) Q S),
apply e.symm.injective,
refine ext_threefold _,
intros x y z,
ext w,
exact H x y z w,
end
end UMP
variables {M N}
section
variables (R M)
/--
The base ring is a left identity for the tensor product of modules, up to linear equivalence.
-/
protected def lid : R ⊗ M ≃ₗ M :=
linear_equiv.of_linear (lift $ linear_map.lsmul R M) (mk R R M 1)
(linear_map.ext $ λ _, by simp)
(ext $ λ r m, by simp; rw [← tmul_smul, ← smul_tmul, smul_eq_mul, mul_one])
end
@[simp] theorem lid_tmul (m : M) (r : R) :
((tensor_product.lid R M) : (R ⊗ M → M)) (r ⊗ₜ m) = r • m :=
begin
dsimp [tensor_product.lid],
simp,
end
@[simp] lemma lid_symm_apply (m : M) :
(tensor_product.lid R M).symm m = 1 ⊗ₜ m := rfl
section
variables (R M N)
/--
The tensor product of modules is commutative, up to linear equivalence.
-/
protected def comm : M ⊗ N ≃ₗ N ⊗ M :=
linear_equiv.of_linear (lift (mk R N M).flip) (lift (mk R M N).flip)
(ext $ λ m n, rfl)
(ext $ λ m n, rfl)
@[simp] theorem comm_tmul (m : M) (n : N) :
(tensor_product.comm R M N) (m ⊗ₜ n) = n ⊗ₜ m := rfl
@[simp] theorem comm_symm_tmul (m : M) (n : N) :
(tensor_product.comm R M N).symm (n ⊗ₜ m) = m ⊗ₜ n := rfl
end
section
variables (R M)
/--
The base ring is a right identity for the tensor product of modules, up to linear equivalence.
-/
protected def rid : M ⊗[R] R ≃ₗ M :=
linear_equiv.trans (tensor_product.comm R M R) (tensor_product.lid R M)
end
@[simp] theorem rid_tmul (m : M) (r : R) :
(tensor_product.rid R M) (m ⊗ₜ r) = r • m :=
begin
dsimp [tensor_product.rid, tensor_product.comm, tensor_product.lid],
simp,
end
@[simp] lemma rid_symm_apply (m : M) :
(tensor_product.rid R M).symm m = m ⊗ₜ 1 := rfl
open linear_map
section
variables (R M N P)
/-- The associator for tensor product of R-modules, as a linear equivalence. -/
protected def assoc : (M ⊗[R] N) ⊗[R] P ≃ₗ[R] M ⊗[R] (N ⊗[R] P) :=
begin
refine linear_equiv.of_linear
(lift $ lift $ comp (lcurry R _ _ _) $ mk _ _ _)
(lift $ comp (uncurry R _ _ _) $ curry $ mk _ _ _)
(mk_compr₂_inj $ linear_map.ext $ λ m, ext $ λ n p, _)
(mk_compr₂_inj $ flip_inj $ linear_map.ext $ λ p, ext $ λ m n, _);
repeat { rw lift.tmul <|> rw compr₂_apply <|> rw comp_apply <|>
rw mk_apply <|> rw flip_apply <|> rw lcurry_apply <|>
rw uncurry_apply <|> rw curry_apply <|> rw id_apply }
end
end
@[simp] theorem assoc_tmul (m : M) (n : N) (p : P) :
(tensor_product.assoc R M N P) ((m ⊗ₜ n) ⊗ₜ p) = m ⊗ₜ (n ⊗ₜ p) := rfl
@[simp] theorem assoc_symm_tmul (m : M) (n : N) (p : P) :
(tensor_product.assoc R M N P).symm (m ⊗ₜ (n ⊗ₜ p)) = (m ⊗ₜ n) ⊗ₜ p := rfl
/-- The tensor product of a pair of linear maps between modules. -/
def map (f : M →ₗ[R] P) (g : N →ₗ Q) : M ⊗ N →ₗ[R] P ⊗ Q :=
lift $ comp (compl₂ (mk _ _ _) g) f
@[simp] theorem map_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (m : M) (n : N) :
map f g (m ⊗ₜ n) = f m ⊗ₜ g n :=
rfl
section
variables {P' Q' : Type*}
variables [add_comm_monoid P'] [semimodule R P']
variables [add_comm_monoid Q'] [semimodule R Q']
lemma map_comp (f₂ : P →ₗ[R] P') (f₁ : M →ₗ[R] P) (g₂ : Q →ₗ[R] Q') (g₁ : N →ₗ[R] Q) :
map (f₂.comp f₁) (g₂.comp g₁) = (map f₂ g₂).comp (map f₁ g₁) :=
by { ext1, simp only [linear_map.comp_apply, map_tmul] }
lemma lift_comp_map (i : P →ₗ[R] Q →ₗ[R] Q') (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :
(lift i).comp (map f g) = lift ((i.comp f).compl₂ g) :=
by { ext1, simp only [lift.tmul, map_tmul, linear_map.compl₂_apply, linear_map.comp_apply] }
end
/-- 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 (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : M ⊗ N ≃ₗ[R] P ⊗ Q :=
linear_equiv.of_linear (map f g) (map f.symm g.symm)
(ext $ λ m n, by simp; simp only [linear_equiv.apply_symm_apply])
(ext $ λ m n, by simp; simp only [linear_equiv.symm_apply_apply])
@[simp] theorem congr_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (m : M) (n : N) :
congr f g (m ⊗ₜ n) = f m ⊗ₜ g n :=
rfl
@[simp] theorem congr_symm_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (p : P) (q : Q) :
(congr f g).symm (p ⊗ₜ q) = f.symm p ⊗ₜ g.symm q :=
rfl
end tensor_product
end semiring
section ring
namespace tensor_product
variables {R : Type*} [comm_ring R]
variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*}
variables [add_comm_group M] [add_comm_group N] [add_comm_group P] [add_comm_group Q]
[add_comm_group S]
variables [module R M] [module R N] [module R P] [module R Q] [module R S]
open_locale tensor_product
open linear_map
instance : add_comm_group (M ⊗[R] N) := semimodule.add_comm_monoid_to_add_comm_group R
lemma neg_tmul (m : M) (n : N) : (-m) ⊗ₜ n = -(m ⊗ₜ[R] n) := (mk R M N).map_neg₂ _ _
lemma tmul_neg (m : M) (n : N) : m ⊗ₜ (-n) = -(m ⊗ₜ[R] n) := (mk R M N _).map_neg _
end tensor_product
end ring
|
d347f7bed4856678d2c78ba7bf527bafe8da707a
|
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
|
/stage0/src/Lean/Util/FindExpr.lean
|
f43a29305cb681bceb99bb1971b4a5f189343732
|
[
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"
] |
permissive
|
EdAyers/lean4
|
57ac632d6b0789cb91fab2170e8c9e40441221bd
|
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
|
refs/heads/master
| 1,676,463,245,298
| 1,660,619,433,000
| 1,660,619,433,000
| 183,433,437
| 1
| 0
|
Apache-2.0
| 1,657,612,672,000
| 1,556,196,574,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 3,734
|
lean
|
/-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Expr
namespace Lean
namespace Expr
namespace FindImpl
abbrev cacheSize : USize := 8192
structure State where
keys : Array Expr -- Remark: our "unsafe" implementation relies on the fact that `()` is not a valid Expr
abbrev FindM := StateT State Id
unsafe def visited (e : Expr) (size : USize) : FindM Bool := do
let s ← get
let h := ptrAddrUnsafe e
let i := h % size
let k := s.keys.uget i lcProof
if ptrAddrUnsafe k == h then
pure true
else
modify fun s => { keys := s.keys.uset i e lcProof }
pure false
unsafe def findM? (p : Expr → Bool) (size : USize) (e : Expr) : OptionT FindM Expr :=
let rec visit (e : Expr) := do
if (← visited e size) then
failure
else if p e then
pure e
else match e with
| Expr.forallE _ d b _ => visit d <|> visit b
| Expr.lam _ d b _ => visit d <|> visit b
| Expr.mdata _ b => visit b
| Expr.letE _ t v b _ => visit t <|> visit v <|> visit b
| Expr.app f a => visit f <|> visit a
| Expr.proj _ _ b => visit b
| _ => failure
visit e
unsafe def initCache : State :=
{ keys := mkArray cacheSize.toNat (cast lcProof ()) }
unsafe def findUnsafe? (p : Expr → Bool) (e : Expr) : Option Expr :=
Id.run <| findM? p cacheSize e |>.run' initCache
end FindImpl
@[implementedBy FindImpl.findUnsafe?]
def find? (p : Expr → Bool) (e : Expr) : Option Expr :=
/- This is a reference implementation for the unsafe one above -/
if p e then
some e
else match e with
| Expr.forallE _ d b _ => find? p d <|> find? p b
| Expr.lam _ d b _ => find? p d <|> find? p b
| Expr.mdata _ b => find? p b
| Expr.letE _ t v b _ => find? p t <|> find? p v <|> find? p b
| Expr.app f a => find? p f <|> find? p a
| Expr.proj _ _ b => find? p b
| _ => none
/-- Return true if `e` occurs in `t` -/
def occurs (e : Expr) (t : Expr) : Bool :=
(t.find? fun s => s == e).isSome
/--
Return type for `findExt?` function argument.
-/
inductive FindStep where
| /-- Found desired subterm -/ found
| /-- Search subterms -/ visit
| /-- Do not search subterms -/ done
namespace FindExtImpl
unsafe def findM? (p : Expr → FindStep) (size : USize) (e : Expr) : OptionT FindImpl.FindM Expr :=
visit e
where
visitApp (e : Expr) :=
match e with
| Expr.app f a .. => visitApp f <|> visit a
| e => visit e
visit (e : Expr) := do
if (← FindImpl.visited e size) then
failure
else match p e with
| FindStep.done => failure
| FindStep.found => pure e
| FindStep.visit =>
match e with
| Expr.forallE _ d b _ => visit d <|> visit b
| Expr.lam _ d b _ => visit d <|> visit b
| Expr.mdata _ b => visit b
| Expr.letE _ t v b _ => visit t <|> visit v <|> visit b
| Expr.app .. => visitApp e
| Expr.proj _ _ b => visit b
| _ => failure
unsafe def findUnsafe? (p : Expr → FindStep) (e : Expr) : Option Expr :=
Id.run <| findM? p FindImpl.cacheSize e |>.run' FindImpl.initCache
end FindExtImpl
/--
Similar to `find?`, but `p` can return `FindStep.done` to interrupt the search on subterms.
Remark: Differently from `find?`, we do not invoke `p` for partial applications of an application. -/
@[implementedBy FindExtImpl.findUnsafe?]
opaque findExt? (p : Expr → FindStep) (e : Expr) : Option Expr
end Expr
end Lean
|
d04d5f4afcb62e2e2b90f4dc521fdeba781802bd
|
b7f22e51856f4989b970961f794f1c435f9b8f78
|
/tests/lean/run/679b.lean
|
c43356af981f4d616026c3c4e414db2eb05dfe63
|
[
"Apache-2.0"
] |
permissive
|
soonhokong/lean
|
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
|
38607e3eb57f57f77c0ac114ad169e9e4262e24f
|
refs/heads/master
| 1,611,187,284,081
| 1,450,766,737,000
| 1,476,122,547,000
| 11,513,992
| 2
| 0
| null | 1,401,763,102,000
| 1,374,182,235,000
|
C++
|
UTF-8
|
Lean
| false
| false
| 420
|
lean
|
import data.finset
open bool nat list finset
definition fset [class] (A : Type) := finset A
definition fin_nat [instance] : fset nat :=
to_finset [0]
definition fin_bool [instance] : fset bool :=
to_finset [tt, ff]
definition tst (A : Type) [s : fset A] : finset A :=
s
example : tst nat = to_finset [0] :=
rfl
example : tst bool = to_finset [ff, tt] :=
dec_trivial
example : tst bool = to_finset [tt, ff] :=
rfl
|
dc9c3884611171346ae96f5a64ffdf637cf9543f
|
82e44445c70db0f03e30d7be725775f122d72f3e
|
/src/data/list/perm.lean
|
682e49f9c5cfa7124a63e8e4d70aa1e40943728f
|
[
"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
| 43,358
|
lean
|
/-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro
-/
import data.list.bag_inter
import data.list.erase_dup
import data.list.zip
import logic.relation
/-!
# List permutations
-/
open_locale nat
namespace list
universe variables uu vv
variables {α : Type uu} {β : Type vv}
/-- `perm l₁ l₂` or `l₁ ~ l₂` asserts that `l₁` and `l₂` are permutations
of each other. This is defined by induction using pairwise swaps. -/
inductive perm : list α → list α → Prop
| nil : perm [] []
| cons : Π (x : α) {l₁ l₂ : list α}, perm l₁ l₂ → perm (x::l₁) (x::l₂)
| swap : Π (x y : α) (l : list α), perm (y::x::l) (x::y::l)
| trans : Π {l₁ l₂ l₃ : list α}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃
open perm (swap)
infix ~ := perm
@[refl] protected theorem perm.refl : ∀ (l : list α), l ~ l
| [] := perm.nil
| (x::xs) := (perm.refl xs).cons x
@[symm] protected theorem perm.symm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₂ ~ l₁ :=
perm.rec_on p
perm.nil
(λ x l₁ l₂ p₁ r₁, r₁.cons x)
(λ x y l, swap y x l)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₂.trans r₁)
theorem perm_comm {l₁ l₂ : list α} : l₁ ~ l₂ ↔ l₂ ~ l₁ := ⟨perm.symm, perm.symm⟩
theorem perm.swap'
(x y : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : y::x::l₁ ~ x::y::l₂ :=
(swap _ _ _).trans ((p.cons _).cons _)
attribute [trans] perm.trans
theorem perm.eqv (α) : equivalence (@perm α) :=
mk_equivalence (@perm α) (@perm.refl α) (@perm.symm α) (@perm.trans α)
instance is_setoid (α) : setoid (list α) :=
setoid.mk (@perm α) (perm.eqv α)
theorem perm.subset {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ ⊆ l₂ :=
λ a, perm.rec_on p
(λ h, h)
(λ x l₁ l₂ p₁ r₁ i, or.elim i
(λ ax, by simp [ax])
(λ al₁, or.inr (r₁ al₁)))
(λ x y l ayxl, or.elim ayxl
(λ ay, by simp [ay])
(λ axl, or.elim axl
(λ ax, by simp [ax])
(λ al, or.inr (or.inr al))))
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁))
theorem perm.mem_iff {a : α} {l₁ l₂ : list α} (h : l₁ ~ l₂) : a ∈ l₁ ↔ a ∈ l₂ :=
iff.intro (λ m, h.subset m) (λ m, h.symm.subset m)
theorem perm.append_right {l₁ l₂ : list α} (t₁ : list α) (p : l₁ ~ l₂) : l₁++t₁ ~ l₂++t₁ :=
perm.rec_on p
(perm.refl ([] ++ t₁))
(λ x l₁ l₂ p₁ r₁, r₁.cons x)
(λ x y l, swap x y _)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₁.trans r₂)
theorem perm.append_left {t₁ t₂ : list α} : ∀ (l : list α), t₁ ~ t₂ → l++t₁ ~ l++t₂
| [] p := p
| (x::xs) p := (perm.append_left xs p).cons x
theorem perm.append {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁++t₁ ~ l₂++t₂ :=
(p₁.append_right t₁).trans (p₂.append_left l₂)
theorem perm.append_cons (a : α) {h₁ h₂ t₁ t₂ : list α}
(p₁ : h₁ ~ h₂) (p₂ : t₁ ~ t₂) : h₁ ++ a::t₁ ~ h₂ ++ a::t₂ :=
p₁.append (p₂.cons a)
@[simp] theorem perm_middle {a : α} : ∀ {l₁ l₂ : list α}, l₁++a::l₂ ~ a::(l₁++l₂)
| [] l₂ := perm.refl _
| (b::l₁) l₂ := ((@perm_middle l₁ l₂).cons _).trans (swap a b _)
@[simp] theorem perm_append_singleton (a : α) (l : list α) : l ++ [a] ~ a::l :=
perm_middle.trans $ by rw [append_nil]
theorem perm_append_comm : ∀ {l₁ l₂ : list α}, (l₁++l₂) ~ (l₂++l₁)
| [] l₂ := by simp
| (a::t) l₂ := (perm_append_comm.cons _).trans perm_middle.symm
theorem concat_perm (l : list α) (a : α) : concat l a ~ a :: l :=
by simp
theorem perm.length_eq {l₁ l₂ : list α} (p : l₁ ~ l₂) : length l₁ = length l₂ :=
perm.rec_on p
rfl
(λ x l₁ l₂ p r, by simp[r])
(λ x y l, by simp)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂)
theorem perm.eq_nil {l : list α} (p : l ~ []) : l = [] :=
eq_nil_of_length_eq_zero p.length_eq
theorem perm.nil_eq {l : list α} (p : [] ~ l) : [] = l :=
p.symm.eq_nil.symm
@[simp]
theorem perm_nil {l₁ : list α} : l₁ ~ [] ↔ l₁ = [] :=
⟨λ p, p.eq_nil, λ e, e ▸ perm.refl _⟩
@[simp]
theorem nil_perm {l₁ : list α} : [] ~ l₁ ↔ l₁ = [] :=
perm_comm.trans perm_nil
theorem not_perm_nil_cons (x : α) (l : list α) : ¬ [] ~ x::l
| p := by injection p.symm.eq_nil
@[simp] theorem reverse_perm : ∀ (l : list α), reverse l ~ l
| [] := perm.nil
| (a::l) := by { rw reverse_cons,
exact (perm_append_singleton _ _).trans ((reverse_perm l).cons a) }
theorem perm_cons_append_cons {l l₁ l₂ : list α} (a : α) (p : l ~ l₁++l₂) :
a::l ~ l₁++(a::l₂) :=
(p.cons a).trans perm_middle.symm
@[simp] theorem perm_repeat {a : α} {n : ℕ} {l : list α} : l ~ repeat a n ↔ l = repeat a n :=
⟨λ p, (eq_repeat.2
⟨p.length_eq.trans $ length_repeat _ _,
λ b m, eq_of_mem_repeat $ p.subset m⟩),
λ h, h ▸ perm.refl _⟩
@[simp] theorem repeat_perm {a : α} {n : ℕ} {l : list α} : repeat a n ~ l ↔ repeat a n = l :=
(perm_comm.trans perm_repeat).trans eq_comm
@[simp] theorem perm_singleton {a : α} {l : list α} : l ~ [a] ↔ l = [a] :=
@perm_repeat α a 1 l
@[simp] theorem singleton_perm {a : α} {l : list α} : [a] ~ l ↔ [a] = l :=
@repeat_perm α a 1 l
theorem perm.eq_singleton {a : α} {l : list α} (p : l ~ [a]) : l = [a] :=
perm_singleton.1 p
theorem perm.singleton_eq {a : α} {l : list α} (p : [a] ~ l) : [a] = l :=
p.symm.eq_singleton.symm
theorem singleton_perm_singleton {a b : α} : [a] ~ [b] ↔ a = b :=
by simp
theorem perm_cons_erase [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) :
l ~ a :: l.erase a :=
let ⟨l₁, l₂, _, e₁, e₂⟩ := exists_erase_eq h in
e₂.symm ▸ e₁.symm ▸ perm_middle
@[elab_as_eliminator] theorem perm_induction_on
{P : list α → list α → Prop} {l₁ l₂ : list α} (p : l₁ ~ l₂)
(h₁ : P [] [])
(h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂))
(h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂))
(h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) :
P l₁ l₂ :=
have P_refl : ∀ l, P l l, from
assume l,
list.rec_on l h₁ (λ x xs ih, h₂ x xs xs (perm.refl xs) ih),
perm.rec_on p h₁ h₂ (λ x y l, h₃ x y l l (perm.refl l) (P_refl l)) h₄
@[congr] theorem perm.filter_map (f : α → option β) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
filter_map f l₁ ~ filter_map f l₂ :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂,
{ simp },
{ simp only [filter_map], cases f x with a; simp [filter_map, IH, perm.cons] },
{ simp only [filter_map], cases f x with a; cases f y with b; simp [filter_map, swap] },
{ exact IH₁.trans IH₂ }
end
@[congr] theorem perm.map (f : α → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
map f l₁ ~ map f l₂ :=
filter_map_eq_map f ▸ p.filter_map _
theorem perm.pmap {p : α → Prop} (f : Π a, p a → β)
{l₁ l₂ : list α} (p : l₁ ~ l₂) {H₁ H₂} : pmap f l₁ H₁ ~ pmap f l₂ H₂ :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂,
{ simp },
{ simp [IH, perm.cons] },
{ simp [swap] },
{ refine IH₁.trans IH₂,
exact λ a m, H₂ a (p₂.subset m) }
end
theorem perm.filter (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} (s : l₁ ~ l₂) : filter p l₁ ~ filter p l₂ :=
by rw ← filter_map_eq_filter; apply s.filter_map _
theorem exists_perm_sublist {l₁ l₂ l₂' : list α}
(s : l₁ <+ l₂) (p : l₂ ~ l₂') : ∃ l₁' ~ l₁, l₁' <+ l₂' :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂ generalizing l₁ s,
{ exact ⟨[], eq_nil_of_sublist_nil s ▸ perm.refl _, nil_sublist _⟩ },
{ cases s with _ _ _ s l₁ _ _ s,
{ exact let ⟨l₁', p', s'⟩ := IH s in ⟨l₁', p', s'.cons _ _ _⟩ },
{ exact let ⟨l₁', p', s'⟩ := IH s in ⟨x::l₁', p'.cons x, s'.cons2 _ _ _⟩ } },
{ cases s with _ _ _ s l₁ _ _ s; cases s with _ _ _ s l₁ _ _ s,
{ exact ⟨l₁, perm.refl _, (s.cons _ _ _).cons _ _ _⟩ },
{ exact ⟨x::l₁, perm.refl _, (s.cons _ _ _).cons2 _ _ _⟩ },
{ exact ⟨y::l₁, perm.refl _, (s.cons2 _ _ _).cons _ _ _⟩ },
{ exact ⟨x::y::l₁, perm.swap _ _ _, (s.cons2 _ _ _).cons2 _ _ _⟩ } },
{ exact let ⟨m₁, pm, sm⟩ := IH₁ s, ⟨r₁, pr, sr⟩ := IH₂ sm in
⟨r₁, pr.trans pm, sr⟩ }
end
theorem perm.sizeof_eq_sizeof [has_sizeof α] {l₁ l₂ : list α} (h : l₁ ~ l₂) :
l₁.sizeof = l₂.sizeof :=
begin
induction h with hd l₁ l₂ h₁₂ h_sz₁₂ a b l l₁ l₂ l₃ h₁₂ h₂₃ h_sz₁₂ h_sz₂₃,
{ refl },
{ simp only [list.sizeof, h_sz₁₂] },
{ simp only [list.sizeof, add_left_comm] },
{ simp only [h_sz₁₂, h_sz₂₃] }
end
section rel
open relator
variables {γ : Type*} {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
local infixr ` ∘r ` : 80 := relation.comp
lemma perm_comp_perm : (perm ∘r perm : list α → list α → Prop) = perm :=
begin
funext a c, apply propext,
split,
{ exact assume ⟨b, hab, hba⟩, perm.trans hab hba },
{ exact assume h, ⟨a, perm.refl a, h⟩ }
end
lemma perm_comp_forall₂ {l u v} (hlu : perm l u) (huv : forall₂ r u v) : (forall₂ r ∘r perm) l v :=
begin
induction hlu generalizing v,
case perm.nil { cases huv, exact ⟨[], forall₂.nil, perm.nil⟩ },
case perm.cons : a l u hlu ih {
cases huv with _ b _ v hab huv',
rcases ih huv' with ⟨l₂, h₁₂, h₂₃⟩,
exact ⟨b::l₂, forall₂.cons hab h₁₂, h₂₃.cons _⟩
},
case perm.swap : a₁ a₂ l₁ l₂ h₂₃ {
cases h₂₃ with _ b₁ _ l₂ h₁ hr_₂₃,
cases hr_₂₃ with _ b₂ _ l₂ h₂ h₁₂,
exact ⟨b₂::b₁::l₂, forall₂.cons h₂ (forall₂.cons h₁ h₁₂), perm.swap _ _ _⟩
},
case perm.trans : la₁ la₂ la₃ _ _ ih₁ ih₂ {
rcases ih₂ huv with ⟨lb₂, hab₂, h₂₃⟩,
rcases ih₁ hab₂ with ⟨lb₁, hab₁, h₁₂⟩,
exact ⟨lb₁, hab₁, perm.trans h₁₂ h₂₃⟩
}
end
lemma forall₂_comp_perm_eq_perm_comp_forall₂ : forall₂ r ∘r perm = perm ∘r forall₂ r :=
begin
funext l₁ l₃, apply propext,
split,
{ assume h, rcases h with ⟨l₂, h₁₂, h₂₃⟩,
have : forall₂ (flip r) l₂ l₁, from h₁₂.flip ,
rcases perm_comp_forall₂ h₂₃.symm this with ⟨l', h₁, h₂⟩,
exact ⟨l', h₂.symm, h₁.flip⟩ },
{ exact assume ⟨l₂, h₁₂, h₂₃⟩, perm_comp_forall₂ h₁₂ h₂₃ }
end
lemma rel_perm_imp (hr : right_unique r) : (forall₂ r ⇒ forall₂ r ⇒ implies) perm perm :=
assume a b h₁ c d h₂ h,
have (flip (forall₂ r) ∘r (perm ∘r forall₂ r)) b d, from ⟨a, h₁, c, h, h₂⟩,
have ((flip (forall₂ r) ∘r forall₂ r) ∘r perm) b d,
by rwa [← forall₂_comp_perm_eq_perm_comp_forall₂, ← relation.comp_assoc] at this,
let ⟨b', ⟨c', hbc, hcb⟩, hbd⟩ := this in
have b' = b, from right_unique_forall₂' hr hcb hbc,
this ▸ hbd
lemma rel_perm (hr : bi_unique r) : (forall₂ r ⇒ forall₂ r ⇒ (↔)) perm perm :=
assume a b hab c d hcd, iff.intro
(rel_perm_imp hr.2 hab hcd)
(rel_perm_imp (left_unique_flip hr.1) hab.flip hcd.flip)
end rel
section subperm
/-- `subperm l₁ l₂`, denoted `l₁ <+~ l₂`, means that `l₁` is a sublist of
a permutation of `l₂`. This is an analogue of `l₁ ⊆ l₂` which respects
multiplicities of elements, and is used for the `≤` relation on multisets. -/
def subperm (l₁ l₂ : list α) : Prop := ∃ l ~ l₁, l <+ l₂
infix ` <+~ `:50 := subperm
theorem nil_subperm {l : list α} : [] <+~ l :=
⟨[], perm.nil, by simp⟩
theorem perm.subperm_left {l l₁ l₂ : list α} (p : l₁ ~ l₂) : l <+~ l₁ ↔ l <+~ l₂ :=
suffices ∀ {l₁ l₂ : list α}, l₁ ~ l₂ → l <+~ l₁ → l <+~ l₂,
from ⟨this p, this p.symm⟩,
λ l₁ l₂ p ⟨u, pu, su⟩,
let ⟨v, pv, sv⟩ := exists_perm_sublist su p in
⟨v, pv.trans pu, sv⟩
theorem perm.subperm_right {l₁ l₂ l : list α} (p : l₁ ~ l₂) : l₁ <+~ l ↔ l₂ <+~ l :=
⟨λ ⟨u, pu, su⟩, ⟨u, pu.trans p, su⟩,
λ ⟨u, pu, su⟩, ⟨u, pu.trans p.symm, su⟩⟩
theorem sublist.subperm {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁ <+~ l₂ :=
⟨l₁, perm.refl _, s⟩
theorem perm.subperm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ <+~ l₂ :=
⟨l₂, p.symm, sublist.refl _⟩
@[refl] theorem subperm.refl (l : list α) : l <+~ l := (perm.refl _).subperm
@[trans] theorem subperm.trans {l₁ l₂ l₃ : list α} : l₁ <+~ l₂ → l₂ <+~ l₃ → l₁ <+~ l₃
| s ⟨l₂', p₂, s₂⟩ :=
let ⟨l₁', p₁, s₁⟩ := p₂.subperm_left.2 s in ⟨l₁', p₁, s₁.trans s₂⟩
theorem subperm.length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ ≤ length l₂
| ⟨l, p, s⟩ := p.length_eq ▸ length_le_of_sublist s
theorem subperm.perm_of_length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₂ ≤ length l₁ → l₁ ~ l₂
| ⟨l, p, s⟩ h :=
suffices l = l₂, from this ▸ p.symm,
eq_of_sublist_of_length_le s $ p.symm.length_eq ▸ h
theorem subperm.antisymm {l₁ l₂ : list α} (h₁ : l₁ <+~ l₂) (h₂ : l₂ <+~ l₁) : l₁ ~ l₂ :=
h₁.perm_of_length_le h₂.length_le
theorem subperm.subset {l₁ l₂ : list α} : l₁ <+~ l₂ → l₁ ⊆ l₂
| ⟨l, p, s⟩ := subset.trans p.symm.subset s.subset
end subperm
theorem sublist.exists_perm_append : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → ∃ l, l₂ ~ l₁ ++ l
| ._ ._ sublist.slnil := ⟨nil, perm.refl _⟩
| ._ ._ (sublist.cons l₁ l₂ a s) :=
let ⟨l, p⟩ := sublist.exists_perm_append s in
⟨a::l, (p.cons a).trans perm_middle.symm⟩
| ._ ._ (sublist.cons2 l₁ l₂ a s) :=
let ⟨l, p⟩ := sublist.exists_perm_append s in
⟨l, p.cons a⟩
theorem perm.countp_eq (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} (s : l₁ ~ l₂) : countp p l₁ = countp p l₂ :=
by rw [countp_eq_length_filter, countp_eq_length_filter];
exact (s.filter _).length_eq
theorem subperm.countp_le (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} : l₁ <+~ l₂ → countp p l₁ ≤ countp p l₂
| ⟨l, p', s⟩ := p'.countp_eq p ▸ countp_le_of_sublist p s
theorem perm.count_eq [decidable_eq α] {l₁ l₂ : list α}
(p : l₁ ~ l₂) (a) : count a l₁ = count a l₂ :=
p.countp_eq _
theorem subperm.count_le [decidable_eq α] {l₁ l₂ : list α}
(s : l₁ <+~ l₂) (a) : count a l₁ ≤ count a l₂ :=
s.countp_le _
theorem perm.foldl_eq' {f : β → α → β} {l₁ l₂ : list α} (p : l₁ ~ l₂) :
(∀ (x ∈ l₁) (y ∈ l₁) z, f (f z x) y = f (f z y) x) → ∀ b, foldl f b l₁ = foldl f b l₂ :=
perm_induction_on p
(λ H b, rfl)
(λ x t₁ t₂ p r H b, r (λ x hx y hy, H _ (or.inr hx) _ (or.inr hy)) _)
(λ x y t₁ t₂ p r H b,
begin
simp only [foldl],
rw [H x (or.inr $ or.inl rfl) y (or.inl rfl)],
exact r (λ x hx y hy, H _ (or.inr $ or.inr hx) _ (or.inr $ or.inr hy)) _
end)
(λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ H b, eq.trans (r₁ H b)
(r₂ (λ x hx y hy, H _ (p₁.symm.subset hx) _ (p₁.symm.subset hy)) b))
theorem perm.foldl_eq {f : β → α → β} {l₁ l₂ : list α} (rcomm : right_commutative f) (p : l₁ ~ l₂) :
∀ b, foldl f b l₁ = foldl f b l₂ :=
p.foldl_eq' $ λ x hx y hy z, rcomm z x y
theorem perm.foldr_eq {f : α → β → β} {l₁ l₂ : list α} (lcomm : left_commutative f) (p : l₁ ~ l₂) :
∀ b, foldr f b l₁ = foldr f b l₂ :=
perm_induction_on p
(λ b, rfl)
(λ x t₁ t₂ p r b, by simp; rw [r b])
(λ x y t₁ t₂ p r b, by simp; rw [lcomm, r b])
(λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a))
lemma perm.rec_heq {β : list α → Sort*} {f : Πa l, β l → β (a::l)} {b : β []} {l l' : list α}
(hl : perm l l')
(f_congr : ∀{a l l' b b'}, perm l l' → b == b' → f a l b == f a l' b')
(f_swap : ∀{a a' l b}, f a (a'::l) (f a' l b) == f a' (a::l) (f a l b)) :
@list.rec α β b f l == @list.rec α β b f l' :=
begin
induction hl,
case list.perm.nil { refl },
case list.perm.cons : a l l' h ih { exact f_congr h ih },
case list.perm.swap : a a' l { exact f_swap },
case list.perm.trans : l₁ l₂ l₃ h₁ h₂ ih₁ ih₂ { exact heq.trans ih₁ ih₂ }
end
section
variables {op : α → α → α} [is_associative α op] [is_commutative α op]
local notation a * b := op a b
local notation l <*> a := foldl op a l
lemma perm.fold_op_eq {l₁ l₂ : list α} {a : α} (h : l₁ ~ l₂) : l₁ <*> a = l₂ <*> a :=
h.foldl_eq (right_comm _ is_commutative.comm is_associative.assoc) _
end
section comm_monoid
/-- If elements of a list commute with each other, then their product does not
depend on the order of elements-/
@[to_additive]
lemma perm.prod_eq' [monoid α] {l₁ l₂ : list α} (h : l₁ ~ l₂)
(hc : l₁.pairwise (λ x y, x * y = y * x)) :
l₁.prod = l₂.prod :=
h.foldl_eq' (forall_of_forall_of_pairwise (λ x y h z, (h z).symm) (λ x hx z, rfl) $
hc.imp $ λ x y h z, by simp only [mul_assoc, h]) _
variable [comm_monoid α]
@[to_additive]
lemma perm.prod_eq {l₁ l₂ : list α} (h : perm l₁ l₂) : prod l₁ = prod l₂ :=
h.fold_op_eq
@[to_additive]
lemma prod_reverse (l : list α) : prod l.reverse = prod l :=
(reverse_perm l).prod_eq
end comm_monoid
theorem perm_inv_core {a : α} {l₁ l₂ r₁ r₂ : list α} : l₁++a::r₁ ~ l₂++a::r₂ → l₁++r₁ ~ l₂++r₂ :=
begin
generalize e₁ : l₁++a::r₁ = s₁, generalize e₂ : l₂++a::r₂ = s₂,
intro p, revert l₁ l₂ r₁ r₂ e₁ e₂,
refine perm_induction_on p _ (λ x t₁ t₂ p IH, _) (λ x y t₁ t₂ p IH, _)
(λ t₁ t₂ t₃ p₁ p₂ IH₁ IH₂, _); intros l₁ l₂ r₁ r₂ e₁ e₂,
{ apply (not_mem_nil a).elim, rw ← e₁, simp },
{ cases l₁ with y l₁; cases l₂ with z l₂;
dsimp at e₁ e₂; injections; subst x,
{ substs t₁ t₂, exact p },
{ substs z t₁ t₂, exact p.trans perm_middle },
{ substs y t₁ t₂, exact perm_middle.symm.trans p },
{ substs z t₁ t₂, exact (IH rfl rfl).cons y } },
{ rcases l₁ with _|⟨y, _|⟨z, l₁⟩⟩; rcases l₂ with _|⟨u, _|⟨v, l₂⟩⟩;
dsimp at e₁ e₂; injections; substs x y,
{ substs r₁ r₂, exact p.cons a },
{ substs r₁ r₂, exact p.cons u },
{ substs r₁ v t₂, exact (p.trans perm_middle).cons u },
{ substs r₁ r₂, exact p.cons y },
{ substs r₁ r₂ y u, exact p.cons a },
{ substs r₁ u v t₂, exact ((p.trans perm_middle).cons y).trans (swap _ _ _) },
{ substs r₂ z t₁, exact (perm_middle.symm.trans p).cons y },
{ substs r₂ y z t₁, exact (swap _ _ _).trans ((perm_middle.symm.trans p).cons u) },
{ substs u v t₁ t₂, exact (IH rfl rfl).swap' _ _ } },
{ substs t₁ t₃,
have : a ∈ t₂ := p₁.subset (by simp),
rcases mem_split this with ⟨l₂, r₂, e₂⟩,
subst t₂, exact (IH₁ rfl rfl).trans (IH₂ rfl rfl) }
end
theorem perm.cons_inv {a : α} {l₁ l₂ : list α} : a::l₁ ~ a::l₂ → l₁ ~ l₂ :=
@perm_inv_core _ _ [] [] _ _
@[simp] theorem perm_cons (a : α) {l₁ l₂ : list α} : a::l₁ ~ a::l₂ ↔ l₁ ~ l₂ :=
⟨perm.cons_inv, perm.cons a⟩
theorem perm_append_left_iff {l₁ l₂ : list α} : ∀ l, l++l₁ ~ l++l₂ ↔ l₁ ~ l₂
| [] := iff.rfl
| (a::l) := (perm_cons a).trans (perm_append_left_iff l)
theorem perm_append_right_iff {l₁ l₂ : list α} (l) : l₁++l ~ l₂++l ↔ l₁ ~ l₂ :=
⟨λ p, (perm_append_left_iff _).1 $ perm_append_comm.trans $ p.trans perm_append_comm,
perm.append_right _⟩
theorem perm_option_to_list {o₁ o₂ : option α} : o₁.to_list ~ o₂.to_list ↔ o₁ = o₂ :=
begin
refine ⟨λ p, _, λ e, e ▸ perm.refl _⟩,
cases o₁ with a; cases o₂ with b, {refl},
{ cases p.length_eq },
{ cases p.length_eq },
{ exact option.mem_to_list.1 (p.symm.subset $ by simp) }
end
theorem subperm_cons (a : α) {l₁ l₂ : list α} : a::l₁ <+~ a::l₂ ↔ l₁ <+~ l₂ :=
⟨λ ⟨l, p, s⟩, begin
cases s with _ _ _ s' u _ _ s',
{ exact (p.subperm_left.2 $ (sublist_cons _ _).subperm).trans s'.subperm },
{ exact ⟨u, p.cons_inv, s'⟩ }
end, λ ⟨l, p, s⟩, ⟨a::l, p.cons a, s.cons2 _ _ _⟩⟩
theorem cons_subperm_of_mem {a : α} {l₁ l₂ : list α} (d₁ : nodup l₁) (h₁ : a ∉ l₁) (h₂ : a ∈ l₂)
(s : l₁ <+~ l₂) : a :: l₁ <+~ l₂ :=
begin
rcases s with ⟨l, p, s⟩,
induction s generalizing l₁,
case list.sublist.slnil { cases h₂ },
case list.sublist.cons : r₁ r₂ b s' ih {
simp at h₂,
cases h₂ with e m,
{ subst b, exact ⟨a::r₁, p.cons a, s'.cons2 _ _ _⟩ },
{ rcases ih m d₁ h₁ p with ⟨t, p', s'⟩, exact ⟨t, p', s'.cons _ _ _⟩ } },
case list.sublist.cons2 : r₁ r₂ b s' ih {
have bm : b ∈ l₁ := (p.subset $ mem_cons_self _ _),
have am : a ∈ r₂ := h₂.resolve_left (λ e, h₁ $ e.symm ▸ bm),
rcases mem_split bm with ⟨t₁, t₂, rfl⟩,
have st : t₁ ++ t₂ <+ t₁ ++ b :: t₂ := by simp,
rcases ih am (nodup_of_sublist st d₁)
(mt (λ x, st.subset x) h₁)
(perm.cons_inv $ p.trans perm_middle) with ⟨t, p', s'⟩,
exact ⟨b::t, (p'.cons b).trans $ (swap _ _ _).trans (perm_middle.symm.cons a), s'.cons2 _ _ _⟩ }
end
theorem subperm_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+~ l++l₂ ↔ l₁ <+~ l₂
| [] := iff.rfl
| (a::l) := (subperm_cons a).trans (subperm_append_left l)
theorem subperm_append_right {l₁ l₂ : list α} (l) : l₁++l <+~ l₂++l ↔ l₁ <+~ l₂ :=
(perm_append_comm.subperm_left.trans perm_append_comm.subperm_right).trans (subperm_append_left l)
theorem subperm.exists_of_length_lt {l₁ l₂ : list α} :
l₁ <+~ l₂ → length l₁ < length l₂ → ∃ a, a :: l₁ <+~ l₂
| ⟨l, p, s⟩ h :=
suffices length l < length l₂ → ∃ (a : α), a :: l <+~ l₂, from
(this $ p.symm.length_eq ▸ h).imp (λ a, (p.cons a).subperm_right.1),
begin
clear subperm.exists_of_length_lt p h l₁, rename l₂ u,
induction s with l₁ l₂ a s IH _ _ b s IH; intro h,
{ cases h },
{ cases lt_or_eq_of_le (nat.le_of_lt_succ h : length l₁ ≤ length l₂) with h h,
{ exact (IH h).imp (λ a s, s.trans (sublist_cons _ _).subperm) },
{ exact ⟨a, eq_of_sublist_of_length_eq s h ▸ subperm.refl _⟩ } },
{ exact (IH $ nat.lt_of_succ_lt_succ h).imp
(λ a s, (swap _ _ _).subperm_right.1 $ (subperm_cons _).2 s) }
end
theorem subperm_of_subset_nodup
{l₁ l₂ : list α} (d : nodup l₁) (H : l₁ ⊆ l₂) : l₁ <+~ l₂ :=
begin
induction d with a l₁' h d IH,
{ exact ⟨nil, perm.nil, nil_sublist _⟩ },
{ cases forall_mem_cons.1 H with H₁ H₂,
simp at h,
exact cons_subperm_of_mem d h H₁ (IH H₂) }
end
theorem perm_ext {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) :
l₁ ~ l₂ ↔ ∀a, a ∈ l₁ ↔ a ∈ l₂ :=
⟨λ p a, p.mem_iff, λ H, subperm.antisymm
(subperm_of_subset_nodup d₁ (λ a, (H a).1))
(subperm_of_subset_nodup d₂ (λ a, (H a).2))⟩
theorem nodup.sublist_ext {l₁ l₂ l : list α} (d : nodup l)
(s₁ : l₁ <+ l) (s₂ : l₂ <+ l) : l₁ ~ l₂ ↔ l₁ = l₂ :=
⟨λ h, begin
induction s₂ with l₂ l a s₂ IH l₂ l a s₂ IH generalizing l₁,
{ exact h.eq_nil },
{ simp at d,
cases s₁ with _ _ _ s₁ l₁ _ _ s₁,
{ exact IH d.2 s₁ h },
{ apply d.1.elim,
exact subperm.subset ⟨_, h.symm, s₂⟩ (mem_cons_self _ _) } },
{ simp at d,
cases s₁ with _ _ _ s₁ l₁ _ _ s₁,
{ apply d.1.elim,
exact subperm.subset ⟨_, h, s₁⟩ (mem_cons_self _ _) },
{ rw IH d.2 s₁ h.cons_inv } }
end, λ h, by rw h⟩
section
variable [decidable_eq α]
-- attribute [congr]
theorem perm.erase (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
l₁.erase a ~ l₂.erase a :=
if h₁ : a ∈ l₁ then
have h₂ : a ∈ l₂, from p.subset h₁,
perm.cons_inv $ (perm_cons_erase h₁).symm.trans $ p.trans (perm_cons_erase h₂)
else
have h₂ : a ∉ l₂, from mt p.mem_iff.2 h₁,
by rw [erase_of_not_mem h₁, erase_of_not_mem h₂]; exact p
theorem subperm_cons_erase (a : α) (l : list α) : l <+~ a :: l.erase a :=
begin
by_cases h : a ∈ l,
{ exact (perm_cons_erase h).subperm },
{ rw [erase_of_not_mem h],
exact (sublist_cons _ _).subperm }
end
theorem erase_subperm (a : α) (l : list α) : l.erase a <+~ l :=
(erase_sublist _ _).subperm
theorem subperm.erase {l₁ l₂ : list α} (a : α) (h : l₁ <+~ l₂) : l₁.erase a <+~ l₂.erase a :=
let ⟨l, hp, hs⟩ := h in ⟨l.erase a, hp.erase _, hs.erase _⟩
theorem perm.diff_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.diff t ~ l₂.diff t :=
by induction t generalizing l₁ l₂ h; simp [*, perm.erase]
theorem perm.diff_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l.diff t₁ = l.diff t₂ :=
by induction h generalizing l; simp [*, perm.erase, erase_comm]
<|> exact (ih_1 _).trans (ih_2 _)
theorem perm.diff {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) :
l₁.diff t₁ ~ l₂.diff t₂ :=
ht.diff_left l₂ ▸ hl.diff_right _
theorem subperm.diff_right {l₁ l₂ : list α} (h : l₁ <+~ l₂) (t : list α) :
l₁.diff t <+~ l₂.diff t :=
by induction t generalizing l₁ l₂ h; simp [*, subperm.erase]
theorem erase_cons_subperm_cons_erase (a b : α) (l : list α) :
(a :: l).erase b <+~ a :: l.erase b :=
begin
by_cases h : a = b,
{ subst b,
rw [erase_cons_head],
apply subperm_cons_erase },
{ rw [erase_cons_tail _ h] }
end
theorem subperm_cons_diff {a : α} : ∀ {l₁ l₂ : list α}, (a :: l₁).diff l₂ <+~ a :: l₁.diff l₂
| l₁ [] := ⟨a::l₁, by simp⟩
| l₁ (b::l₂) :=
begin
simp only [diff_cons],
refine ((erase_cons_subperm_cons_erase a b l₁).diff_right l₂).trans _,
apply subperm_cons_diff
end
theorem subset_cons_diff {a : α} {l₁ l₂ : list α} : (a :: l₁).diff l₂ ⊆ a :: l₁.diff l₂ :=
subperm_cons_diff.subset
theorem perm.bag_inter_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) :
l₁.bag_inter t ~ l₂.bag_inter t :=
begin
induction h with x _ _ _ _ x y _ _ _ _ _ _ ih_1 ih_2 generalizing t, {simp},
{ by_cases x ∈ t; simp [*, perm.cons] },
{ by_cases x = y, {simp [h]},
by_cases xt : x ∈ t; by_cases yt : y ∈ t,
{ simp [xt, yt, mem_erase_of_ne h, mem_erase_of_ne (ne.symm h), erase_comm, swap] },
{ simp [xt, yt, mt mem_of_mem_erase, perm.cons] },
{ simp [xt, yt, mt mem_of_mem_erase, perm.cons] },
{ simp [xt, yt] } },
{ exact (ih_1 _).trans (ih_2 _) }
end
theorem perm.bag_inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) :
l.bag_inter t₁ = l.bag_inter t₂ :=
begin
induction l with a l IH generalizing t₁ t₂ p, {simp},
by_cases a ∈ t₁,
{ simp [h, p.subset h, IH (p.erase _)] },
{ simp [h, mt p.mem_iff.2 h, IH p] }
end
theorem perm.bag_inter {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) :
l₁.bag_inter t₁ ~ l₂.bag_inter t₂ :=
ht.bag_inter_left l₂ ▸ hl.bag_inter_right _
theorem cons_perm_iff_perm_erase {a : α} {l₁ l₂ : list α} : a::l₁ ~ l₂ ↔ a ∈ l₂ ∧ l₁ ~ l₂.erase a :=
⟨λ h, have a ∈ l₂, from h.subset (mem_cons_self a l₁),
⟨this, (h.trans $ perm_cons_erase this).cons_inv⟩,
λ ⟨m, h⟩, (h.cons a).trans (perm_cons_erase m).symm⟩
theorem perm_iff_count {l₁ l₂ : list α} : l₁ ~ l₂ ↔ ∀ a, count a l₁ = count a l₂ :=
⟨perm.count_eq, λ H, begin
induction l₁ with a l₁ IH generalizing l₂,
{ cases l₂ with b l₂, {refl},
specialize H b, simp at H, contradiction },
{ have : a ∈ l₂ := count_pos.1 (by rw ← H; simp; apply nat.succ_pos),
refine ((IH $ λ b, _).cons a).trans (perm_cons_erase this).symm,
specialize H b,
rw (perm_cons_erase this).count_eq at H,
by_cases b = a; simp [h] at H ⊢; assumption }
end⟩
instance decidable_perm : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂)
| [] [] := is_true $ perm.refl _
| [] (b::l₂) := is_false $ λ h, by have := h.nil_eq; contradiction
| (a::l₁) l₂ := by haveI := decidable_perm l₁ (l₂.erase a);
exact decidable_of_iff' _ cons_perm_iff_perm_erase
-- @[congr]
theorem perm.erase_dup {l₁ l₂ : list α} (p : l₁ ~ l₂) :
erase_dup l₁ ~ erase_dup l₂ :=
perm_iff_count.2 $ λ a,
if h : a ∈ l₁
then by simp [nodup_erase_dup, h, p.subset h]
else by simp [h, mt p.mem_iff.2 h]
-- attribute [congr]
theorem perm.insert (a : α)
{l₁ l₂ : list α} (p : l₁ ~ l₂) : insert a l₁ ~ insert a l₂ :=
if h : a ∈ l₁
then by simpa [h, p.subset h] using p
else by simpa [h, mt p.mem_iff.2 h] using p.cons a
theorem perm_insert_swap (x y : α) (l : list α) :
insert x (insert y l) ~ insert y (insert x l) :=
begin
by_cases xl : x ∈ l; by_cases yl : y ∈ l; simp [xl, yl],
by_cases xy : x = y, { simp [xy] },
simp [not_mem_cons_of_ne_of_not_mem xy xl,
not_mem_cons_of_ne_of_not_mem (ne.symm xy) yl],
constructor
end
theorem perm_insert_nth {α} (x : α) (l : list α) {n} (h : n ≤ l.length) :
insert_nth n x l ~ x :: l :=
begin
induction l generalizing n,
{ cases n, refl, cases h },
cases n,
{ simp [insert_nth] },
{ simp only [insert_nth, modify_nth_tail],
transitivity,
{ apply perm.cons, apply l_ih,
apply nat.le_of_succ_le_succ h },
{ apply perm.swap } }
end
theorem perm.union_right {l₁ l₂ : list α} (t₁ : list α) (h : l₁ ~ l₂) : l₁ ∪ t₁ ~ l₂ ∪ t₁ :=
begin
induction h with a _ _ _ ih _ _ _ _ _ _ _ _ ih_1 ih_2; try {simp},
{ exact ih.insert a },
{ apply perm_insert_swap },
{ exact ih_1.trans ih_2 }
end
theorem perm.union_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l ∪ t₁ ~ l ∪ t₂ :=
by induction l; simp [*, perm.insert]
-- @[congr]
theorem perm.union {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∪ t₁ ~ l₂ ∪ t₂ :=
(p₁.union_right t₁).trans (p₂.union_left l₂)
theorem perm.inter_right {l₁ l₂ : list α} (t₁ : list α) : l₁ ~ l₂ → l₁ ∩ t₁ ~ l₂ ∩ t₁ :=
perm.filter _
theorem perm.inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l ∩ t₁ = l ∩ t₂ :=
by { dsimp [(∩), list.inter], congr, funext a, rw [p.mem_iff] }
-- @[congr]
theorem perm.inter {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∩ t₁ ~ l₂ ∩ t₂ :=
p₂.inter_left l₂ ▸ p₁.inter_right t₁
theorem perm.inter_append {l t₁ t₂ : list α} (h : disjoint t₁ t₂) :
l ∩ (t₁ ++ t₂) ~ l ∩ t₁ ++ l ∩ t₂ :=
begin
induction l,
case list.nil
{ simp },
case list.cons : x xs l_ih
{ by_cases h₁ : x ∈ t₁,
{ have h₂ : x ∉ t₂ := h h₁,
simp * },
by_cases h₂ : x ∈ t₂,
{ simp only [*, inter_cons_of_not_mem, false_or, mem_append, inter_cons_of_mem, not_false_iff],
transitivity,
{ apply perm.cons _ l_ih, },
change [x] ++ xs ∩ t₁ ++ xs ∩ t₂ ~ xs ∩ t₁ ++ ([x] ++ xs ∩ t₂),
rw [← list.append_assoc],
solve_by_elim [perm.append_right, perm_append_comm] },
{ simp * } },
end
end
theorem perm.pairwise_iff {R : α → α → Prop} (S : symmetric R) :
∀ {l₁ l₂ : list α} (p : l₁ ~ l₂), pairwise R l₁ ↔ pairwise R l₂ :=
suffices ∀ {l₁ l₂}, l₁ ~ l₂ → pairwise R l₁ → pairwise R l₂, from λ l₁ l₂ p, ⟨this p, this p.symm⟩,
λ l₁ l₂ p d, begin
induction d with a l₁ h d IH generalizing l₂,
{ rw ← p.nil_eq, constructor },
{ have : a ∈ l₂ := p.subset (mem_cons_self _ _),
rcases mem_split this with ⟨s₂, t₂, rfl⟩,
have p' := (p.trans perm_middle).cons_inv,
refine (pairwise_middle S).2 (pairwise_cons.2 ⟨λ b m, _, IH _ p'⟩),
exact h _ (p'.symm.subset m) }
end
theorem perm.nodup_iff {l₁ l₂ : list α} : l₁ ~ l₂ → (nodup l₁ ↔ nodup l₂) :=
perm.pairwise_iff $ @ne.symm α
theorem perm.bind_right {l₁ l₂ : list α} (f : α → list β) (p : l₁ ~ l₂) :
l₁.bind f ~ l₂.bind f :=
begin
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ simp, exact IH.append_left _ },
{ simp, rw [← append_assoc, ← append_assoc], exact perm_append_comm.append_right _ },
{ exact IH₁.trans IH₂ }
end
theorem perm.bind_left (l : list α) {f g : α → list β} (h : ∀ a, f a ~ g a) :
l.bind f ~ l.bind g :=
by induction l with a l IH; simp; exact (h a).append IH
theorem perm.product_right {l₁ l₂ : list α} (t₁ : list β) (p : l₁ ~ l₂) :
product l₁ t₁ ~ product l₂ t₁ :=
p.bind_right _
theorem perm.product_left (l : list α) {t₁ t₂ : list β} (p : t₁ ~ t₂) :
product l t₁ ~ product l t₂ :=
perm.bind_left _ $ λ a, p.map _
@[congr] theorem perm.product {l₁ l₂ : list α} {t₁ t₂ : list β}
(p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : product l₁ t₁ ~ product l₂ t₂ :=
(p₁.product_right t₁).trans (p₂.product_left l₂)
theorem sublists_cons_perm_append (a : α) (l : list α) :
sublists (a :: l) ~ sublists l ++ map (cons a) (sublists l) :=
begin
simp only [sublists, sublists_aux_cons_cons, cons_append, perm_cons],
refine (perm.cons _ _).trans perm_middle.symm,
induction sublists_aux l cons with b l IH; simp,
exact (IH.cons _).trans perm_middle.symm
end
theorem sublists_perm_sublists' : ∀ l : list α, sublists l ~ sublists' l
| [] := perm.refl _
| (a::l) := let IH := sublists_perm_sublists' l in
by rw sublists'_cons; exact
(sublists_cons_perm_append _ _).trans (IH.append (IH.map _))
theorem revzip_sublists (l : list α) :
∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists → l₁ ++ l₂ ~ l :=
begin
rw revzip,
apply list.reverse_rec_on l,
{ intros l₁ l₂ h, simp at h, simp [h] },
{ intros l a IH l₁ l₂ h,
rw [sublists_concat, reverse_append, zip_append, ← map_reverse,
zip_map_right, zip_map_left] at h; [skip, {simp}],
simp only [prod.mk.inj_iff, mem_map, mem_append, prod.map_mk, prod.exists] at h,
rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩,
{ rw ← append_assoc,
exact (IH _ _ h).append_right _ },
{ rw append_assoc,
apply (perm_append_comm.append_left _).trans,
rw ← append_assoc,
exact (IH _ _ h).append_right _ } }
end
theorem revzip_sublists' (l : list α) :
∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists' → l₁ ++ l₂ ~ l :=
begin
rw revzip,
induction l with a l IH; intros l₁ l₂ h,
{ simp at h, simp [h] },
{ rw [sublists'_cons, reverse_append, zip_append, ← map_reverse,
zip_map_right, zip_map_left] at h; [simp at h, simp],
rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', h, rfl⟩,
{ exact perm_middle.trans ((IH _ _ h).cons _) },
{ exact (IH _ _ h).cons _ } }
end
theorem perm_lookmap (f : α → option α) {l₁ l₂ : list α}
(H : pairwise (λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d) l₁)
(p : l₁ ~ l₂) : lookmap f l₁ ~ lookmap f l₂ :=
begin
let F := λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d,
change pairwise F l₁ at H,
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ cases h : f a,
{ simp [h], exact IH (pairwise_cons.1 H).2 },
{ simp [lookmap_cons_some _ _ h, p] } },
{ cases h₁ : f a with c; cases h₂ : f b with d,
{ simp [h₁, h₂], apply swap },
{ simp [h₁, lookmap_cons_some _ _ h₂], apply swap },
{ simp [lookmap_cons_some _ _ h₁, h₂], apply swap },
{ simp [lookmap_cons_some _ _ h₁, lookmap_cons_some _ _ h₂],
rcases (pairwise_cons.1 H).1 _ (or.inl rfl) _ h₂ _ h₁ with ⟨rfl, rfl⟩,
refl } },
{ refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)),
exact λ a b h c h₁ d h₂, (h d h₂ c h₁).imp eq.symm eq.symm }
end
theorem perm.erasep (f : α → Prop) [decidable_pred f] {l₁ l₂ : list α}
(H : pairwise (λ a b, f a → f b → false) l₁)
(p : l₁ ~ l₂) : erasep f l₁ ~ erasep f l₂ :=
begin
let F := λ a b, f a → f b → false,
change pairwise F l₁ at H,
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ by_cases h : f a,
{ simp [h, p] },
{ simp [h], exact IH (pairwise_cons.1 H).2 } },
{ by_cases h₁ : f a; by_cases h₂ : f b; simp [h₁, h₂],
{ cases (pairwise_cons.1 H).1 _ (or.inl rfl) h₂ h₁ },
{ apply swap } },
{ refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)),
exact λ a b h h₁ h₂, h h₂ h₁ }
end
lemma perm.take_inter {α} [decidable_eq α] {xs ys : list α} (n : ℕ)
(h : xs ~ ys) (h' : ys.nodup) :
xs.take n ~ ys.inter (xs.take n) :=
begin
simp only [list.inter] at *,
induction h generalizing n,
case list.perm.nil : n
{ simp only [not_mem_nil, filter_false, take_nil] },
case list.perm.cons : h_x h_l₁ h_l₂ h_a h_ih n
{ cases n; simp only [mem_cons_iff, true_or, eq_self_iff_true, filter_cons_of_pos,
perm_cons, take, not_mem_nil, filter_false],
cases h' with _ _ h₁ h₂,
convert h_ih h₂ n using 1,
apply filter_congr,
introv h, simp only [(h₁ x h).symm, false_or], },
case list.perm.swap : h_x h_y h_l n
{ cases h' with _ _ h₁ h₂,
cases h₂ with _ _ h₂ h₃,
have := h₁ _ (or.inl rfl),
cases n; simp only [mem_cons_iff, not_mem_nil, filter_false, take],
cases n; simp only [mem_cons_iff, false_or, true_or, filter, *, nat.nat_zero_eq_zero, if_true,
not_mem_nil, eq_self_iff_true, or_false, if_false, perm_cons, take],
{ rw filter_eq_nil.2, intros, solve_by_elim [ne.symm], },
{ convert perm.swap _ _ _, rw @filter_congr _ _ (∈ take n h_l),
{ clear h₁, induction n generalizing h_l; simp only [not_mem_nil, filter_false, take],
cases h_l; simp only [mem_cons_iff, true_or, eq_self_iff_true, filter_cons_of_pos,
true_and, take, not_mem_nil, filter_false, take_nil],
cases h₃ with _ _ h₃ h₄,
rwa [@filter_congr _ _ (∈ take n_n h_l_tl), n_ih],
{ introv h, apply h₂ _ (or.inr h), },
{ introv h, simp only [(h₃ x h).symm, false_or], }, },
{ introv h, simp only [(h₂ x h).symm, (h₁ x (or.inr h)).symm, false_or], } } },
case list.perm.trans : h_l₁ h_l₂ h_l₃ h₀ h₁ h_ih₀ h_ih₁ n
{ transitivity,
{ apply h_ih₀, rwa h₁.nodup_iff },
{ apply perm.filter _ h₁, } },
end
lemma perm.drop_inter {α} [decidable_eq α] {xs ys : list α} (n : ℕ)
(h : xs ~ ys) (h' : ys.nodup) :
xs.drop n ~ ys.inter (xs.drop n) :=
begin
by_cases h'' : n ≤ xs.length,
{ let n' := xs.length - n,
have h₀ : n = xs.length - n',
{ dsimp [n'], rwa nat.sub_sub_self, } ,
have h₁ : n' ≤ xs.length,
{ apply nat.sub_le_self },
have h₂ : xs.drop n = (xs.reverse.take n').reverse,
{ rw [reverse_take _ h₁, h₀, reverse_reverse], },
rw [h₂],
apply (reverse_perm _).trans,
rw inter_reverse,
apply perm.take_inter _ _ h',
apply (reverse_perm _).trans; assumption, },
{ have : drop n xs = [],
{ apply eq_nil_of_length_eq_zero,
rw [length_drop, nat.sub_eq_zero_iff_le],
apply le_of_not_ge h'' },
simp [this, list.inter], }
end
lemma perm.slice_inter {α} [decidable_eq α] {xs ys : list α} (n m : ℕ)
(h : xs ~ ys) (h' : ys.nodup) :
list.slice n m xs ~ ys ∩ (list.slice n m xs) :=
begin
simp only [slice_eq],
have : n ≤ n + m := nat.le_add_right _ _,
have := h.nodup_iff.2 h',
apply perm.trans _ (perm.inter_append _).symm;
solve_by_elim [perm.append, perm.drop_inter, perm.take_inter, disjoint_take_drop, h, h']
{ max_depth := 7 },
end
/- enumerating permutations -/
section permutations
theorem perm_of_mem_permutations_aux :
∀ {ts is l : list α}, l ∈ permutations_aux ts is → l ~ ts ++ is :=
begin
refine permutations_aux.rec (by simp) _,
introv IH1 IH2 m,
rw [permutations_aux_cons, permutations, mem_foldr_permutations_aux2] at m,
rcases m with m | ⟨l₁, l₂, m, _, e⟩,
{ exact (IH1 m).trans perm_middle },
{ subst e,
have p : l₁ ++ l₂ ~ is,
{ simp [permutations] at m,
cases m with e m, {simp [e]},
exact is.append_nil ▸ IH2 m },
exact ((perm_middle.trans (p.cons _)).append_right _).trans (perm_append_comm.cons _) }
end
theorem perm_of_mem_permutations {l₁ l₂ : list α}
(h : l₁ ∈ permutations l₂) : l₁ ~ l₂ :=
(eq_or_mem_of_mem_cons h).elim (λ e, e ▸ perm.refl _)
(λ m, append_nil l₂ ▸ perm_of_mem_permutations_aux m)
theorem length_permutations_aux : ∀ ts is : list α,
length (permutations_aux ts is) + is.length! = (length ts + length is)! :=
begin
refine permutations_aux.rec (by simp) _,
intros t ts is IH1 IH2,
have IH2 : length (permutations_aux is nil) + 1 = is.length!,
{ simpa using IH2 },
simp [-add_comm, nat.factorial, nat.add_succ, mul_comm] at IH1,
rw [permutations_aux_cons,
length_foldr_permutations_aux2' _ _ _ _ _
(λ l m, (perm_of_mem_permutations m).length_eq),
permutations, length, length, IH2,
nat.succ_add, nat.factorial_succ, mul_comm (nat.succ _), ← IH1,
add_comm (_*_), add_assoc, nat.mul_succ, mul_comm]
end
theorem length_permutations (l : list α) : length (permutations l) = (length l)! :=
length_permutations_aux l []
theorem mem_permutations_of_perm_lemma {is l : list α}
(H : l ~ [] ++ is → (∃ ts' ~ [], l = ts' ++ is) ∨ l ∈ permutations_aux is [])
: l ~ is → l ∈ permutations is :=
by simpa [permutations, perm_nil] using H
theorem mem_permutations_aux_of_perm :
∀ {ts is l : list α}, l ~ is ++ ts → (∃ is' ~ is, l = is' ++ ts) ∨ l ∈ permutations_aux ts is :=
begin
refine permutations_aux.rec (by simp) _,
intros t ts is IH1 IH2 l p,
rw [permutations_aux_cons, mem_foldr_permutations_aux2],
rcases IH1 (p.trans perm_middle) with ⟨is', p', e⟩ | m,
{ clear p, subst e,
rcases mem_split (p'.symm.subset (mem_cons_self _ _)) with ⟨l₁, l₂, e⟩,
subst is',
have p := (perm_middle.symm.trans p').cons_inv,
cases l₂ with a l₂',
{ exact or.inl ⟨l₁, by simpa using p⟩ },
{ exact or.inr (or.inr ⟨l₁, a::l₂',
mem_permutations_of_perm_lemma IH2 p, by simp⟩) } },
{ exact or.inr (or.inl m) }
end
@[simp] theorem mem_permutations (s t : list α) : s ∈ permutations t ↔ s ~ t :=
⟨perm_of_mem_permutations, mem_permutations_of_perm_lemma mem_permutations_aux_of_perm⟩
end permutations
end list
|
f702101c206d39417fdd9c04ed98999571ff2914
|
076f5040b63237c6dd928c6401329ed5adcb0e44
|
/assignments/hw7_bool_sat/hw7_sat.lean
|
2ba6864ae3cc48e35f9fd2312475b64de2b48155
|
[] |
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
| 5,744
|
lean
|
import .prop_logic
import .bool_sat
open prop_logic
open prop_logic.var
open prop_logic.pExp
/-
An example: The 0th, 1st, and
2nd bits from the right in 100,
the binary numeral for decimal
4, are 0, 0, and 1, respectively.
-/
#eval mth_bit_from_right_in_n 2 4
/-
#1. Write and evaluate expressions
(using eval) to determine what is
the bit in the 9th position from
the right in the binary expansion
of the decimal number 8485672345?
Hint: don't use reduce here. Eval
uses hardware (machine) int values
to represent nats, while reduce
uses the unary nat representation.
Self-test: How much memory might
it take to represent the decimal
number, 8485672345, as a ℕ value
in unary?
-/
#eval _
/-
The next section presents examples
to set up test cases for definitions
to follow.
-/
/-
We define a few variables to use
in the rest of this assignment.
-/
def P : pExp:= varExp (mkVar 0)
def Q: pExp := varExp (mkVar 1)
def R : pExp := varExp (mkVar 2)
/-
We set parameter values used in
some function definitions to follow.
-/
def max_var_index := 2
def num_vars := max_var_index + 1
/-
An example of a propositional logic
expression.
-/
def theExpr : pExp := (P ⇒ (P ∧ R))
/-
An example using the truth_table_results
function to compute and return a list of
the truth values of theExpr under each of
its possible interpretations.
-/
#eval truth_table_results theExpr num_vars
/-
#2. Define interp5 to be the interpretation
in the six row (m=5) of the truth table that
our interps_for_n_vars functions returns for
our three variables (P, Q, and R).
Hint: use the mth_interp_n_vars function.
Definitely check out the definition of the
function, and any specification text, even
if informal, given with the formal definition.
-/
def interp5 := _
/-
#3. What Boolean values are assigned to
P, Q, and R by this interpretation (interp5)?
Use three #eval commands to compute answers by
evaluating each variable expressions under the
interp5 interpretation.
-/
#eval _
#eval _
#eval _
/-
#4. Write a truth table within this
comment block showing the values for
P, Q, and R, in each row in the truth
table, represented by a corresponding
valule in the list of interpretations
returned by interps_for_n_vars. Label
your columns as R, Q, and P, in that
order. (Try to understand why.)
Hint: Don't just write what you think
the answers are:, evaluate each of
the three variable expression under
each interpretation. You can use the
mth_interp_n_vars function if you want
to obtain interpretation functions for
each of the rows individually if you
want.
Answer:
-/
/-
#5. Write an expression here to
compute the "results" column of
the truth table for "theExpr" as
defined above.
-/
#eval _
/-
#6. Copy and paste the truth table
from question #4 here and extend it
with the results you just obtained.
Check the results for correctness.
Answer here:
-/
/-
#7.
Write a "predicate" function, isModel,
that takes a propositional logic
expression, e, and an interpretation,
i, as its arguments and that returns
the Boolean true (tt) value if and only
if i is a model of e (otherwise false).
-/
def isModel :pExp → (var → bool) → bool
/-
#7. Write a one-line implementation
of a function, is_valid, that takes as
its arguments a propositional expression,
e, and the number of variables, n, in its
truth table, and that returns true if and
only if it is valid, construed to mean
tha every result in the list returned by
the truth_table_results function is true.
To do so, define and use a fold function
to reduce returned lists of Boolean truth
values to single truth values. Define and
use a bool-specific function, fold_bool :
(bool → bool → bool) →
bool →
(list bool) →
bool,
where the arguments are, respectively,
a binary operator, an identity element
for that operator, and a list of bools
to be reduced to a single bool result.
-/
def fold_bool :
(bool → bool → bool) → bool → (list bool) → bool
def is_valid : pExp → ℕ → bool
/-
Write similar one-line implementations of the
functions, is_satisfiable and is_unsatisfiable,
respectively. Do not use fold (directly) in your
implementation of is_unsatisfiable.
-/
def is_satisfiable : pExp → ℕ → bool
def is_unsatisfiable : pExp → ℕ → bool
/-
8. Use your is_valid function to determine which
of the following putative valid laws of reasoning
really are valid, and which ones are not. For each
one that is not, give a real-world scenario that
shows that the rule doesn't always lead to a valid
deduction. Use #eval to evaluate the validity of
each proposition. Use -- to put a comment after
each of the following definitions indicating
either "-- valid" or "-- NOT valid".
-/
def true_intro : pExp := pTrue
def false_elim := pFalse ⇒ P
def and_intro := P ⇒ Q ⇒ (P ∧ Q)
def and_elim_left := (P ∧ Q) ⇒ P
def and_elim_right := (P ∧ Q) ⇒ Q
def or_intro_left := P ⇒ (P ∨ Q)
def or_intro_right := Q ⇒ (P ∨ Q)
def or_elim := (P ∨ Q) ⇒ (P ⇒ R) ⇒ (Q ⇒ R) ⇒ R
def iff_intro := (P ⇒ Q) ⇒ (Q ⇒ P) ⇒ (P ↔ Q)
def iff_elim_left := (P ↔ Q) ⇒ (P ⇒ Q)
def iff_elim_right := (P ↔ Q) ⇒ (Q ⇒ P)
def arrow_elim := (P ⇒ Q) ⇒ P ⇒ Q
def affirm_consequence := (P ⇒ Q) ⇒ Q ⇒ P
def resolution := (P ∨ Q) ⇒ (¬ Q ∨ R) ⇒ (P ∨ R)
def unit_resolution := (P ∨ Q) ⇒ (¬ Q) ⇒ P
def syllogism := (P ⇒ Q) ⇒ (Q ⇒ R) ⇒ (P ⇒ R)
def modus_tollens := (P ⇒ Q) ⇒ ¬ Q ⇒ ¬ P
def neg_elim := ¬ ¬ P ⇒ P
def excluded_middle := P ∨ ¬ P
def neg_intro := (P ⇒ pFalse) ⇒ ¬ P
def affirm_disjunct := (P ∨ Q) ⇒ P ⇒ ¬ Q
def deny_antecedent := (P ⇒ Q) ⇒ (¬ P ⇒ ¬ Q)
-- Answer below
|
58321025244efa2e3d858ede2d50d3ccc7a58932
|
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
|
/tests/lean/run/nested_common_subexpr_issue.lean
|
a824c9ae64752e4a00d0183571e7f339f31e3e9f
|
[
"Apache-2.0"
] |
permissive
|
bre7k30/lean
|
de893411bcfa7b3c5572e61b9e1c52951b310aa4
|
5a924699d076dab1bd5af23a8f910b433e598d7a
|
refs/heads/master
| 1,610,900,145,817
| 1,488,006,845,000
| 1,488,006,845,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 336
|
lean
|
-- set_option trace.compiler true
def fib_aux : ℕ → ℕ × ℕ
| 0 := (0, 1)
| (n+1) := let p := fib_aux n in (p.2, p.1 + p.2)
def fib n := (fib_aux n).2
vm_eval fib 10000
def fib_aux2 : ℕ → ℕ × ℕ
| 0 := (0, 1)
| (n+1) := let (a, b) := fib_aux2 n in (b, a + b)
def fib2 n := (fib_aux2 n).2
vm_eval fib2 10000
|
9e5e7f3084c95a640ec92022df1feaa7fd1d65cf
|
efce24474b28579aba3272fdb77177dc2b11d7aa
|
/src/homotopy_theory/topological_spaces/category.lean
|
1c56251798315499bd9f11691447c7738f24be49
|
[
"Apache-2.0"
] |
permissive
|
rwbarton/lean-homotopy-theory
|
cff499f24268d60e1c546e7c86c33f58c62888ed
|
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
|
refs/heads/lean-3.4.2
| 1,622,711,883,224
| 1,598,550,958,000
| 1,598,550,958,000
| 136,023,667
| 12
| 6
|
Apache-2.0
| 1,573,187,573,000
| 1,528,116,262,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 2,830
|
lean
|
import topology.maps
import category_theory.base
import category_theory.functor_category
import topology.category.Top.basic
open category_theory
universe u
namespace homotopy_theory.topological_spaces
namespace Top
local notation `Top` := Top.{u}
protected def mk_ob (α : Type u) [t : topological_space α] : Top := ⟨α, t⟩
protected def mk_hom {X Y : Top} (f : X → Y) (hf : continuous f . tactic.interactive.continuity') : X ⟶ Y :=
continuous_map.mk f hf
@[ext] protected def hom_eq {X Y : Top} {f g : X ⟶ Y} (h : ∀ x, f x = g x) : f = g :=
continuous_map.ext h
protected lemma hom_eq2 {X Y : Top} {f g : X ⟶ Y} : f = g ↔ f.to_fun = g.to_fun :=
by { cases f, cases g, split; cc }
protected def hom_congr {X Y : Top} {f g : X ⟶ Y} : f = g → ∀ x, f x = g x :=
by intros e x; rw e
section terminal
protected def point : Top := @Top.mk_ob punit ⊥
notation `*` := Top.point
protected def point_induced (A : Top) : A ⟶ * :=
Top.mk_hom (λ _, punit.star) (by continuity)
end terminal
protected def const {A X : Top} (x : X) : A ⟶ X :=
Top.mk_hom (λ a, x) (by continuity)
section product
-- TODO: Generalize all the following definitions using a `has_product` class
protected def prod (X Y : Top) : Top :=
Top.mk_ob (X.α × Y.α)
protected def pr₁ {X Y : Top} : Top.prod X Y ⟶ X :=
Top.mk_hom (λ p, p.1) (by continuity!)
protected def pr₂ {X Y : Top} : Top.prod X Y ⟶ Y :=
Top.mk_hom (λ p, p.2) (by continuity!)
-- TODO: The (by continuity) argument ought to be supplied
-- automatically by auto_param, but for some reason elaboration goes
-- wrong without it
protected def prod_maps {X X' Y Y' : Top} (f : X ⟶ X') (g : Y ⟶ Y') :
Top.prod X Y ⟶ Top.prod X' Y' :=
Top.mk_hom (λ p, (f p.1, g p.2)) (by continuity!)
protected def prod_pt {X Y : Top} (y : Y) : X ⟶ Top.prod X Y :=
Top.mk_hom (λ x, (x, y)) (by continuity)
protected def product_by (Y : Top) : Top ↝ Top :=
{ obj := λ X, Top.prod X Y,
map := λ X X' f, Top.prod_maps f (𝟙 Y) }
notation `-×`:35 Y:34 := Top.product_by Y
protected def product_by_trans {Y Y' : Top} (g : Y ⟶ Y') : -×Y ⟶ -×Y' :=
{ app := λ X, Top.prod_maps (𝟙 X) g }
protected def prod_pt_trans {Y : Top} (y : Y) : functor.id _ ⟶ -×Y :=
{ app := λ X, Top.prod_pt y }
protected def pr₁_trans {Y : Top} : -×Y ⟶ functor.id _ :=
{ app := λ X, Top.pr₁ }
end product
section subtype
/-- The hom sets of Top used to be defined using `subtype`;
this provides the equivalence to the old definition. -/
protected def hom_equiv_subtype (X Y : Top) :
(X ⟶ Y) ≃ {f : X → Y // continuous f} :=
{ to_fun := λ p, ⟨p.1, p.2⟩,
inv_fun := λ p, ⟨p.1, p.2⟩,
left_inv := λ p, by cases p; refl,
right_inv := λ p, by cases p; refl }
end subtype
end «Top»
end homotopy_theory.topological_spaces
|
acfa5d50fe985010644a6774dd21305f4d0aa864
|
a047a4718edfa935d17231e9e6ecec8c7b701e05
|
/src/data/finmap.lean
|
06dea05e27a8c5c06f3b6663745d1178c09a396f
|
[
"Apache-2.0"
] |
permissive
|
utensil-contrib/mathlib
|
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
|
b91909e77e219098a2f8cc031f89d595fe274bd2
|
refs/heads/master
| 1,668,048,976,965
| 1,592,442,701,000
| 1,592,442,701,000
| 273,197,855
| 0
| 0
| null | 1,592,472,812,000
| 1,592,472,811,000
| null |
UTF-8
|
Lean
| false
| false
| 18,199
|
lean
|
/-
Copyright (c) 2018 Sean Leather. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sean Leather, Mario Carneiro
Finite maps over `multiset`.
-/
import data.list.alist
import data.finset
import data.pfun
universes u v w
open list
variables {α : Type u} {β : α → Type v}
namespace multiset
/-- Multiset of keys of an association multiset. -/
def keys (s : multiset (sigma β)) : multiset α :=
s.map sigma.fst
@[simp] theorem coe_keys {l : list (sigma β)} :
keys (l : multiset (sigma β)) = (l.keys : multiset α) :=
rfl
/-- `nodupkeys s` means that `s` has no duplicate keys. -/
def nodupkeys (s : multiset (sigma β)) : Prop :=
quot.lift_on s list.nodupkeys (λ s t p, propext $ perm_nodupkeys p)
@[simp] theorem coe_nodupkeys {l : list (sigma β)} : @nodupkeys α β l ↔ l.nodupkeys := iff.rfl
end multiset
/-- `finmap β` is the type of finite maps over a multiset. It is effectively
a quotient of `alist β` by permutation of the underlying list. -/
structure finmap (β : α → Type v) : Type (max u v) :=
(entries : multiset (sigma β))
(nodupkeys : entries.nodupkeys)
/-- The quotient map from `alist` to `finmap`. -/
def alist.to_finmap (s : alist β) : finmap β := ⟨s.entries, s.nodupkeys⟩
local notation `⟦`:max a `⟧`:0 := alist.to_finmap a
theorem alist.to_finmap_eq {s₁ s₂ : alist β} :
⟦s₁⟧ = ⟦s₂⟧ ↔ s₁.entries ~ s₂.entries :=
by cases s₁; cases s₂; simp [alist.to_finmap]
@[simp] theorem alist.to_finmap_entries (s : alist β) : ⟦s⟧.entries = s.entries := rfl
def list.to_finmap [decidable_eq α] (s : list (sigma β)) : finmap β :=
alist.to_finmap (list.to_alist s)
namespace finmap
open alist
/-- Lift a permutation-respecting function on `alist` to `finmap`. -/
@[elab_as_eliminator] def lift_on
{γ} (s : finmap β) (f : alist β → γ)
(H : ∀ a b : alist β, a.entries ~ b.entries → f a = f b) : γ :=
begin
refine (quotient.lift_on s.1 (λ l, (⟨_, λ nd, f ⟨l, nd⟩⟩ : roption γ))
(λ l₁ l₂ p, roption.ext' (perm_nodupkeys p) _) : roption γ).get _,
{ exact λ h₁ h₂, H _ _ (by exact p) },
{ have := s.nodupkeys, rcases s.entries with ⟨l⟩, exact id }
end
@[simp] theorem lift_on_to_finmap {γ} (s : alist β) (f : alist β → γ) (H) :
lift_on ⟦s⟧ f H = f s := by cases s; refl
/-- Lift a permutation-respecting function on 2 `alist`s to 2 `finmap`s. -/
@[elab_as_eliminator] def lift_on₂
{γ} (s₁ s₂ : finmap β) (f : alist β → alist β → γ)
(H : ∀ a₁ b₁ a₂ b₂ : alist β, a₁.entries ~ a₂.entries → b₁.entries ~ b₂.entries → f a₁ b₁ = f a₂ b₂) : γ :=
lift_on s₁
(λ l₁, lift_on s₂ (f l₁) (λ b₁ b₂ p, H _ _ _ _ (perm.refl _) p))
(λ a₁ a₂ p, have H' : f a₁ = f a₂ := funext (λ _, H _ _ _ _ p (perm.refl _)), by simp only [H'])
@[simp] theorem lift_on₂_to_finmap {γ} (s₁ s₂ : alist β) (f : alist β → alist β → γ) (H) :
lift_on₂ ⟦s₁⟧ ⟦s₂⟧ f H = f s₁ s₂ :=
by cases s₁; cases s₂; refl
@[elab_as_eliminator] theorem induction_on
{C : finmap β → Prop} (s : finmap β) (H : ∀ (a : alist β), C ⟦a⟧) : C s :=
by rcases s with ⟨⟨a⟩, h⟩; exact H ⟨a, h⟩
@[elab_as_eliminator] theorem induction_on₂ {C : finmap β → finmap β → Prop}
(s₁ s₂ : finmap β) (H : ∀ (a₁ a₂ : alist β), C ⟦a₁⟧ ⟦a₂⟧) : C s₁ s₂ :=
induction_on s₁ $ λ l₁, induction_on s₂ $ λ l₂, H l₁ l₂
@[elab_as_eliminator] theorem induction_on₃ {C : finmap β → finmap β → finmap β → Prop}
(s₁ s₂ s₃ : finmap β) (H : ∀ (a₁ a₂ a₃ : alist β), C ⟦a₁⟧ ⟦a₂⟧ ⟦a₃⟧) : C s₁ s₂ s₃ :=
induction_on₂ s₁ s₂ $ λ l₁ l₂, induction_on s₃ $ λ l₃, H l₁ l₂ l₃
@[ext] theorem ext : ∀ {s t : finmap β}, s.entries = t.entries → s = t
| ⟨l₁, h₁⟩ ⟨l₂, h₂⟩ H := by congr'
@[simp] theorem ext_iff {s t : finmap β} : s.entries = t.entries ↔ s = t :=
⟨ext, congr_arg _⟩
/-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/
instance : has_mem α (finmap β) := ⟨λ a s, a ∈ s.entries.keys⟩
theorem mem_def {a : α} {s : finmap β} :
a ∈ s ↔ a ∈ s.entries.keys := iff.rfl
@[simp] theorem mem_to_finmap {a : α} {s : alist β} :
a ∈ ⟦s⟧ ↔ a ∈ s := iff.rfl
/-- The set of keys of a finite map. -/
def keys (s : finmap β) : finset α :=
⟨s.entries.keys, induction_on s keys_nodup⟩
@[simp] theorem keys_val (s : alist β) : (keys ⟦s⟧).val = s.keys := rfl
@[simp] theorem keys_ext {s₁ s₂ : alist β} :
keys ⟦s₁⟧ = keys ⟦s₂⟧ ↔ s₁.keys ~ s₂.keys :=
by simp [keys, alist.keys]
theorem mem_keys {a : α} {s : finmap β} : a ∈ s.keys ↔ a ∈ s :=
induction_on s $ λ s, alist.mem_keys
/-- The empty map. -/
instance : has_emptyc (finmap β) := ⟨⟨0, nodupkeys_nil⟩⟩
instance : inhabited (finmap β) := ⟨∅⟩
@[simp] theorem empty_to_finmap : (⟦∅⟧ : finmap β) = ∅ := rfl
@[simp] theorem to_finmap_nil [decidable_eq α] : (list.to_finmap [] : finmap β) = ∅ := rfl
theorem not_mem_empty {a : α} : a ∉ (∅ : finmap β) :=
multiset.not_mem_zero a
@[simp] theorem keys_empty : (∅ : finmap β).keys = ∅ := rfl
/-- The singleton map. -/
def singleton (a : α) (b : β a) : finmap β :=
⟦ alist.singleton a b ⟧
@[simp] theorem keys_singleton (a : α) (b : β a) :
(singleton a b).keys = {a} := rfl
@[simp] lemma mem_singleton (x y : α) (b : β y) : x ∈ singleton y b ↔ x = y :=
by simp only [singleton]; erw [mem_cons_eq,mem_nil_iff,or_false]
variables [decidable_eq α]
instance has_decidable_eq [∀ a, decidable_eq (β a)] : decidable_eq (finmap β)
| s₁ s₂ := decidable_of_iff _ ext_iff
/-- Look up the value associated to a key in a map. -/
def lookup (a : α) (s : finmap β) : option (β a) :=
lift_on s (lookup a) (λ s t, perm_lookup)
@[simp] theorem lookup_to_finmap (a : α) (s : alist β) :
lookup a ⟦s⟧ = s.lookup a := rfl
@[simp] theorem lookup_list_to_finmap (a : α) (s : list (sigma β)) : lookup a s.to_finmap = s.lookup a :=
by rw [list.to_finmap,lookup_to_finmap,lookup_to_alist]
@[simp] theorem lookup_empty (a) : lookup a (∅ : finmap β) = none :=
rfl
theorem lookup_is_some {a : α} {s : finmap β} :
(s.lookup a).is_some ↔ a ∈ s :=
induction_on s $ λ s, alist.lookup_is_some
theorem lookup_eq_none {a} {s : finmap β} : lookup a s = none ↔ a ∉ s :=
induction_on s $ λ s, alist.lookup_eq_none
@[simp] lemma lookup_singleton_eq {a : α} {b : β a} : (singleton a b).lookup a = some b :=
by rw [singleton,lookup_to_finmap,alist.singleton,alist.lookup,lookup_cons_eq]
instance (a : α) (s : finmap β) : decidable (a ∈ s) :=
decidable_of_iff _ lookup_is_some
/-- Replace a key with a given value in a finite map.
If the key is not present it does nothing. -/
def replace (a : α) (b : β a) (s : finmap β) : finmap β :=
lift_on s (λ t, ⟦replace a b t⟧) $
λ s₁ s₂ p, to_finmap_eq.2 $ perm_replace p
@[simp] theorem replace_to_finmap (a : α) (b : β a) (s : alist β) :
replace a b ⟦s⟧ = ⟦s.replace a b⟧ := by simp [replace]
@[simp] theorem keys_replace (a : α) (b : β a) (s : finmap β) :
(replace a b s).keys = s.keys :=
induction_on s $ λ s, by simp
@[simp] theorem mem_replace {a a' : α} {b : β a} {s : finmap β} :
a' ∈ replace a b s ↔ a' ∈ s :=
induction_on s $ λ s, by simp
/-- Fold a commutative function over the key-value pairs in the map -/
def foldl {δ : Type w} (f : δ → Π a, β a → δ)
(H : ∀ d a₁ b₁ a₂ b₂, f (f d a₁ b₁) a₂ b₂ = f (f d a₂ b₂) a₁ b₁)
(d : δ) (m : finmap β) : δ :=
m.entries.foldl (λ d s, f d s.1 s.2) (λ d s t, H _ _ _ _ _) d
def any (f : Π x, β x → bool) (s : finmap β) : bool :=
s.foldl (λ x y z, x ∨ f y z) (by simp [or_assoc]; intros; congr' 2; rw or_comm) ff
def all (f : Π x, β x → bool) (s : finmap β) : bool :=
s.foldl (λ x y z, x ∧ f y z) (by simp [and_assoc]; intros; congr' 2; rw and_comm) ff
/-- Erase a key from the map. If the key is not present it does nothing. -/
def erase (a : α) (s : finmap β) : finmap β :=
lift_on s (λ t, ⟦erase a t⟧) $
λ s₁ s₂ p, to_finmap_eq.2 $ perm_erase p
@[simp] theorem erase_to_finmap (a : α) (s : alist β) :
erase a ⟦s⟧ = ⟦s.erase a⟧ := by simp [erase]
@[simp] theorem keys_erase_to_finset (a : α) (s : alist β) :
keys ⟦s.erase a⟧ = (keys ⟦s⟧).erase a :=
by simp [finset.erase, keys, alist.erase, keys_kerase]
@[simp] theorem keys_erase (a : α) (s : finmap β) :
(erase a s).keys = s.keys.erase a :=
induction_on s $ λ s, by simp
@[simp] theorem mem_erase {a a' : α} {s : finmap β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s :=
induction_on s $ λ s, by simp
theorem not_mem_erase_self {a : α} {s : finmap β} : ¬ a ∈ erase a s :=
by rw [mem_erase,not_and_distrib,not_not]; left; refl
@[simp] theorem lookup_erase (a) (s : finmap β) : lookup a (erase a s) = none :=
induction_on s $ lookup_erase a
@[simp] theorem lookup_erase_ne {a a'} {s : finmap β} (h : a ≠ a') :
lookup a (erase a' s) = lookup a s :=
induction_on s $ λ s, lookup_erase_ne h
theorem erase_erase {a a' : α} {s : finmap β} : erase a (erase a' s) = erase a' (erase a s) :=
induction_on s $ λ s, ext (by simp [alist.erase_erase])
lemma mem_iff {a : α} {s : finmap β} : a ∈ s ↔ ∃ b, s.lookup a = some b :=
induction_on s $ λ s,
iff.trans list.mem_keys $ exists_congr $ λ b,
(mem_lookup_iff s.nodupkeys).symm
lemma mem_of_lookup_eq_some {a : α} {b : β a} {s : finmap β} (h : s.lookup a = some b) : a ∈ s :=
mem_iff.mpr ⟨_,h⟩
/- sub -/
def sdiff (s s' : finmap β) : finmap β :=
s'.foldl (λ s x _, s.erase x) (λ a₀ a₁ _ a₂ _, erase_erase) s
instance : has_sdiff (finmap β) :=
⟨ sdiff ⟩
/- insert -/
/-- Insert a key-value pair into a finite map, replacing any existing pair with
the same key. -/
def insert (a : α) (b : β a) (s : finmap β) : finmap β :=
lift_on s (λ t, ⟦insert a b t⟧) $
λ s₁ s₂ p, to_finmap_eq.2 $ perm_insert p
@[simp] theorem insert_to_finmap (a : α) (b : β a) (s : alist β) :
insert a b ⟦s⟧ = ⟦s.insert a b⟧ := by simp [insert]
theorem insert_entries_of_neg {a : α} {b : β a} {s : finmap β} : a ∉ s →
(insert a b s).entries = ⟨a, b⟩ :: s.entries :=
induction_on s $ λ s h,
by simp [insert_entries_of_neg (mt mem_to_finmap.1 h)]
@[simp] theorem mem_insert {a a' : α} {b' : β a'} {s : finmap β} :
a ∈ insert a' b' s ↔ a = a' ∨ a ∈ s :=
induction_on s mem_insert
@[simp] theorem lookup_insert {a} {b : β a} (s : finmap β) :
lookup a (insert a b s) = some b :=
induction_on s $ λ s,
by simp only [insert_to_finmap, lookup_to_finmap, lookup_insert]
@[simp] theorem lookup_insert_of_ne {a a'} {b : β a} (s : finmap β) (h : a' ≠ a) :
lookup a' (insert a b s) = lookup a' s :=
induction_on s $ λ s,
by simp only [insert_to_finmap, lookup_to_finmap, lookup_insert_ne h]
@[simp] theorem insert_insert {a} {b b' : β a} (s : finmap β) : (s.insert a b).insert a b' = s.insert a b' :=
induction_on s $ λ s,
by simp only [insert_to_finmap, insert_insert]
theorem insert_insert_of_ne {a a'} {b : β a} {b' : β a'} (s : finmap β) (h : a ≠ a') :
(s.insert a b).insert a' b' = (s.insert a' b').insert a b :=
induction_on s $ λ s,
by simp only [insert_to_finmap,alist.to_finmap_eq,insert_insert_of_ne _ h]
theorem to_finmap_cons (a : α) (b : β a) (xs : list (sigma β)) : list.to_finmap (⟨a,b⟩ :: xs) = insert a b xs.to_finmap := rfl
theorem mem_list_to_finmap (a : α) (xs : list (sigma β)) : a ∈ xs.to_finmap ↔ (∃ b : β a, sigma.mk a b ∈ xs) :=
by { induction xs with x xs; [skip, cases x];
simp only [to_finmap_cons, *, not_mem_empty, exists_or_distrib, list.not_mem_nil, finmap.to_finmap_nil, iff_self,
exists_false, mem_cons_iff, mem_insert, exists_and_distrib_left];
apply or_congr _ iff.rfl,
conv { to_lhs, rw ← and_true (a = x_fst) },
apply and_congr_right, rintro ⟨⟩, simp only [exists_eq, iff_self, heq_iff_eq] }
@[simp] theorem insert_singleton_eq {a : α} {b b' : β a} : insert a b (singleton a b') = singleton a b :=
by simp only [singleton, finmap.insert_to_finmap, alist.insert_singleton_eq]
/- extract -/
/-- Erase a key from the map, and return the corresponding value, if found. -/
def extract (a : α) (s : finmap β) : option (β a) × finmap β :=
lift_on s (λ t, prod.map id to_finmap (extract a t)) $
λ s₁ s₂ p, by simp [perm_lookup p, to_finmap_eq, perm_erase p]
@[simp] theorem extract_eq_lookup_erase (a : α) (s : finmap β) :
extract a s = (lookup a s, erase a s) :=
induction_on s $ λ s, by simp [extract]
/- union -/
/-- `s₁ ∪ s₂` is the key-based union of two finite maps. It is left-biased: if
there exists an `a ∈ s₁`, `lookup a (s₁ ∪ s₂) = lookup a s₁`. -/
def union (s₁ s₂ : finmap β) : finmap β :=
lift_on₂ s₁ s₂ (λ s₁ s₂, ⟦s₁ ∪ s₂⟧) $
λ s₁ s₂ s₃ s₄ p₁₃ p₂₄, to_finmap_eq.mpr $ perm_union p₁₃ p₂₄
instance : has_union (finmap β) := ⟨union⟩
@[simp] theorem mem_union {a} {s₁ s₂ : finmap β} :
a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ :=
induction_on₂ s₁ s₂ $ λ _ _, mem_union
@[simp] theorem union_to_finmap (s₁ s₂ : alist β) : ⟦s₁⟧ ∪ ⟦s₂⟧ = ⟦s₁ ∪ s₂⟧ :=
by simp [(∪), union]
theorem keys_union {s₁ s₂ : finmap β} : (s₁ ∪ s₂).keys = s₁.keys ∪ s₂.keys :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, finset.ext $ by simp [keys]
@[simp] theorem lookup_union_left {a} {s₁ s₂ : finmap β} :
a ∈ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₁ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, lookup_union_left
@[simp] theorem lookup_union_right {a} {s₁ s₂ : finmap β} :
a ∉ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₂ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, lookup_union_right
theorem lookup_union_left_of_not_in {a} {s₁ s₂ : finmap β} :
a ∉ s₂ → lookup a (s₁ ∪ s₂) = lookup a s₁ :=
begin
intros h,
by_cases h' : a ∈ s₁,
{ rw lookup_union_left h' },
{ rw [lookup_union_right h',lookup_eq_none.mpr h,lookup_eq_none.mpr h'] }
end
@[simp] theorem mem_lookup_union {a} {b : β a} {s₁ s₂ : finmap β} :
b ∈ lookup a (s₁ ∪ s₂) ↔ b ∈ lookup a s₁ ∨ a ∉ s₁ ∧ b ∈ lookup a s₂ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂, mem_lookup_union
theorem mem_lookup_union_middle {a} {b : β a} {s₁ s₂ s₃ : finmap β} :
b ∈ lookup a (s₁ ∪ s₃) → a ∉ s₂ → b ∈ lookup a (s₁ ∪ s₂ ∪ s₃) :=
induction_on₃ s₁ s₂ s₃ $ λ s₁ s₂ s₃, mem_lookup_union_middle
theorem insert_union {a} {b : β a} {s₁ s₂ : finmap β} :
insert a b (s₁ ∪ s₂) = insert a b s₁ ∪ s₂ :=
induction_on₂ s₁ s₂ $ λ a₁ a₂, by simp [insert_union]
theorem union_assoc {s₁ s₂ s₃ : finmap β} : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) :=
induction_on₃ s₁ s₂ s₃ $ λ s₁ s₂ s₃,
by simp only [alist.to_finmap_eq,union_to_finmap,alist.union_assoc]
@[simp] theorem empty_union {s₁ : finmap β} : ∅ ∪ s₁ = s₁ :=
induction_on s₁ $ λ s₁,
by rw ← empty_to_finmap; simp [- empty_to_finmap, alist.to_finmap_eq,union_to_finmap,alist.union_assoc]
@[simp] theorem union_empty {s₁ : finmap β} : s₁ ∪ ∅ = s₁ :=
induction_on s₁ $ λ s₁,
by rw ← empty_to_finmap; simp [- empty_to_finmap, alist.to_finmap_eq,union_to_finmap,alist.union_assoc]
theorem ext_lookup {s₁ s₂ : finmap β} : (∀ x, s₁.lookup x = s₂.lookup x) → s₁ = s₂ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂ h,
by simp only [alist.lookup, lookup_to_finmap] at h;
rw [alist.to_finmap_eq]; apply lookup_ext s₁.nodupkeys s₂.nodupkeys;
intros x y; rw h
theorem erase_union_singleton (a : α) (b : β a) (s : finmap β) (h : s.lookup a = some b) :
s.erase a ∪ singleton a b = s :=
ext_lookup
(by { intro, by_cases h' : x = a,
{ subst a, rw [lookup_union_right not_mem_erase_self,lookup_singleton_eq,h], },
{ have : x ∉ singleton a b, { rw mem_singleton, exact h' },
rw [lookup_union_left_of_not_in this,lookup_erase_ne h'] } } )
/- disjoint -/
def disjoint (s₁ s₂ : finmap β) :=
∀ x ∈ s₁, ¬ x ∈ s₂
instance : decidable_rel (@disjoint α β _) :=
by intros x y; dsimp [disjoint]; apply_instance
lemma disjoint_empty (x : finmap β) : disjoint ∅ x .
@[symm]
lemma disjoint.symm (x y : finmap β) (h : disjoint x y) : disjoint y x :=
λ p hy hx, h p hx hy
lemma disjoint.symm_iff (x y : finmap β) : disjoint x y ↔ disjoint y x :=
⟨ disjoint.symm x y, disjoint.symm y x ⟩
lemma disjoint_union_left (x y z : finmap β) : disjoint (x ∪ y) z ↔ disjoint x z ∧ disjoint y z :=
by simp [disjoint,finmap.mem_union,or_imp_distrib,forall_and_distrib]
lemma disjoint_union_right (x y z : finmap β) : disjoint x (y ∪ z) ↔ disjoint x y ∧ disjoint x z :=
by rw [disjoint.symm_iff,disjoint_union_left,disjoint.symm_iff _ x,disjoint.symm_iff _ x]
theorem union_comm_of_disjoint {s₁ s₂ : finmap β} : disjoint s₁ s₂ → s₁ ∪ s₂ = s₂ ∪ s₁ :=
induction_on₂ s₁ s₂ $ λ s₁ s₂,
by { intros h, simp only [alist.to_finmap_eq,union_to_finmap,alist.union_comm_of_disjoint h] }
theorem union_cancel {s₁ s₂ s₃ : finmap β} (h : disjoint s₁ s₃) (h' : disjoint s₂ s₃) : s₁ ∪ s₃ = s₂ ∪ s₃ ↔ s₁ = s₂ :=
⟨λ h'', begin
apply ext_lookup, intro x,
have : (s₁ ∪ s₃).lookup x = (s₂ ∪ s₃).lookup x, from h'' ▸ rfl,
by_cases hs₁ : x ∈ s₁,
{ rw [lookup_union_left hs₁,lookup_union_left_of_not_in (h _ hs₁)] at this,
exact this },
{ by_cases hs₂ : x ∈ s₂,
{ rw [lookup_union_left_of_not_in (h' _ hs₂),lookup_union_left hs₂] at this; exact this },
{ rw [lookup_eq_none.mpr hs₁,lookup_eq_none.mpr hs₂] } }
end,
λ h, h ▸ rfl⟩
end finmap
|
b53be9c04190228d1f457d27d58ae66a7c9c8c2a
|
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
|
/src/measure_theory/function/ess_sup.lean
|
8a406a9281bd9ca1447f19e790e17cfb17958801
|
[
"Apache-2.0"
] |
permissive
|
dexmagic/mathlib
|
ff48eefc56e2412429b31d4fddd41a976eb287ce
|
7a5d15a955a92a90e1d398b2281916b9c41270b2
|
refs/heads/master
| 1,693,481,322,046
| 1,633,360,193,000
| 1,633,360,193,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 7,325
|
lean
|
/-
Copyright (c) 2021 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne
-/
import measure_theory.measure.measure_space
import order.filter.ennreal
/-!
# Essential supremum and infimum
We define the essential supremum and infimum of a function `f : α → β` with respect to a measure
`μ` on `α`. The essential supremum is the infimum of the constants `c : β` such that `f x ≤ c`
almost everywhere.
TODO: The essential supremum of functions `α → ℝ≥0∞` is used in particular to define the norm in
the `L∞` space (see measure_theory/lp_space.lean).
There is a different quantity which is sometimes also called essential supremum: the least
upper-bound among measurable functions of a family of measurable functions (in an almost-everywhere
sense). We do not define that quantity here, which is simply the supremum of a map with values in
`α →ₘ[μ] β` (see measure_theory/ae_eq_fun.lean).
## Main definitions
* `ess_sup f μ := μ.ae.limsup f`
* `ess_inf f μ := μ.ae.liminf f`
-/
open measure_theory filter
open_locale ennreal
variables {α β : Type*} {m : measurable_space α} {μ ν : measure α}
section conditionally_complete_lattice
variable [conditionally_complete_lattice β]
/-- Essential supremum of `f` with respect to measure `μ`: the smallest `c : β` such that
`f x ≤ c` a.e. -/
def ess_sup {m : measurable_space α} (f : α → β) (μ : measure α) := μ.ae.limsup f
/-- Essential infimum of `f` with respect to measure `μ`: the greatest `c : β` such that
`c ≤ f x` a.e. -/
def ess_inf {m : measurable_space α} (f : α → β) (μ : measure α) := μ.ae.liminf f
lemma ess_sup_congr_ae {f g : α → β} (hfg : f =ᵐ[μ] g) : ess_sup f μ = ess_sup g μ :=
limsup_congr hfg
lemma ess_inf_congr_ae {f g : α → β} (hfg : f =ᵐ[μ] g) : ess_inf f μ = ess_inf g μ :=
@ess_sup_congr_ae α (order_dual β) _ _ _ _ _ hfg
end conditionally_complete_lattice
section complete_lattice
variable [complete_lattice β]
@[simp] lemma ess_sup_measure_zero {m : measurable_space α} {f : α → β} :
ess_sup f (0 : measure α) = ⊥ :=
le_bot_iff.mp (Inf_le (by simp [set.mem_set_of_eq, eventually_le, ae_iff]))
@[simp] lemma ess_inf_measure_zero {m : measurable_space α} {f : α → β} :
ess_inf f (0 : measure α) = ⊤ :=
@ess_sup_measure_zero α (order_dual β) _ _ _
lemma ess_sup_mono_ae {f g : α → β} (hfg : f ≤ᵐ[μ] g) : ess_sup f μ ≤ ess_sup g μ :=
limsup_le_limsup hfg
lemma ess_inf_mono_ae {f g : α → β} (hfg : f ≤ᵐ[μ] g) : ess_inf f μ ≤ ess_inf g μ :=
liminf_le_liminf hfg
lemma ess_sup_const (c : β) (hμ : μ ≠ 0) : ess_sup (λ x : α, c) μ = c :=
begin
haveI hμ_ne_bot : μ.ae.ne_bot, { rwa [ne_bot_iff, ne.def, ae_eq_bot] },
exact limsup_const c,
end
lemma ess_sup_le_of_ae_le {f : α → β} (c : β) (hf : f ≤ᵐ[μ] (λ _, c)) : ess_sup f μ ≤ c :=
begin
refine (ess_sup_mono_ae hf).trans _,
by_cases hμ : μ = 0,
{ simp [hμ], },
{ rwa ess_sup_const, },
end
lemma ess_inf_const (c : β) (hμ : μ ≠ 0) : ess_inf (λ x : α, c) μ = c :=
@ess_sup_const α (order_dual β) _ _ _ _ hμ
lemma le_ess_inf_of_ae_le {f : α → β} (c : β) (hf : (λ _, c) ≤ᵐ[μ] f) : c ≤ ess_inf f μ :=
@ess_sup_le_of_ae_le α (order_dual β) _ _ _ _ c hf
lemma ess_sup_const_bot : ess_sup (λ x : α, (⊥ : β)) μ = (⊥ : β) :=
limsup_const_bot
lemma ess_inf_const_top : ess_inf (λ x : α, (⊤ : β)) μ = (⊤ : β) :=
liminf_const_top
lemma order_iso.ess_sup_apply {m : measurable_space α} {γ} [complete_lattice γ]
(f : α → β) (μ : measure α) (g : β ≃o γ) :
g (ess_sup f μ) = ess_sup (λ x, g (f x)) μ :=
begin
refine order_iso.limsup_apply g _ _ _ _,
all_goals { is_bounded_default, },
end
lemma order_iso.ess_inf_apply {m : measurable_space α} {γ} [complete_lattice γ]
(f : α → β) (μ : measure α) (g : β ≃o γ) :
g (ess_inf f μ) = ess_inf (λ x, g (f x)) μ :=
@order_iso.ess_sup_apply α (order_dual β) _ _ (order_dual γ) _ _ _ g.dual
lemma ess_sup_mono_measure {f : α → β} (hμν : ν ≪ μ) : ess_sup f ν ≤ ess_sup f μ :=
begin
refine limsup_le_limsup_of_le (measure.ae_le_iff_absolutely_continuous.mpr hμν) _ _,
all_goals { is_bounded_default, },
end
lemma ess_inf_antitone_measure {f : α → β} (hμν : μ ≪ ν) : ess_inf f ν ≤ ess_inf f μ :=
begin
refine liminf_le_liminf_of_le (measure.ae_le_iff_absolutely_continuous.mpr hμν) _ _,
all_goals { is_bounded_default, },
end
lemma ess_sup_smul_measure {f : α → β} {c : ℝ≥0∞} (hc : c ≠ 0) :
ess_sup f (c • μ) = ess_sup f μ :=
begin
simp_rw ess_sup,
suffices h_smul : (c • μ).ae = μ.ae, by rw h_smul,
ext1,
simp_rw mem_ae_iff,
simp [hc],
end
end complete_lattice
section complete_linear_order
variable [complete_linear_order β]
lemma ae_lt_of_ess_sup_lt {f : α → β} {x : β} (hf : ess_sup f μ < x) : ∀ᵐ y ∂μ, f y < x :=
filter.eventually_lt_of_limsup_lt hf
lemma ae_lt_of_lt_ess_inf {f : α → β} {x : β} (hf : x < ess_inf f μ) : ∀ᵐ y ∂μ, x < f y :=
@ae_lt_of_ess_sup_lt α (order_dual β) _ _ _ _ _ hf
lemma ess_sup_indicator_eq_ess_sup_restrict [has_zero β] {s : set α}
{f : α → β} (hf : 0 ≤ᵐ[μ.restrict s] f) (hs : measurable_set s) (hs_not_null : μ s ≠ 0) :
ess_sup (s.indicator f) μ = ess_sup f (μ.restrict s) :=
begin
refine le_antisymm _ (Limsup_le_Limsup_of_le (map_restrict_ae_le_map_indicator_ae hs)
(by is_bounded_default) (by is_bounded_default)),
refine Limsup_le_Limsup (by is_bounded_default) (by is_bounded_default) (λ c h_restrict_le, _),
rw eventually_map at h_restrict_le ⊢,
rw ae_restrict_iff' hs at h_restrict_le,
have hc : 0 ≤ c,
{ suffices : ∃ x, 0 ≤ f x ∧ f x ≤ c, by { obtain ⟨x, hx⟩ := this, exact hx.1.trans hx.2, },
refine frequently.exists _,
{ exact μ.ae, },
rw [eventually_le, ae_restrict_iff' hs] at hf,
have hs' : ∃ᵐ x ∂μ, x ∈ s,
{ contrapose! hs_not_null,
rw [not_frequently, ae_iff] at hs_not_null,
suffices : {a : α | ¬a ∉ s} = s, by rwa ← this,
simp, },
refine hs'.mp (hf.mp (h_restrict_le.mono (λ x hxs_imp_c hxf_nonneg hxs, _))),
rw pi.zero_apply at hxf_nonneg,
exact ⟨hxf_nonneg hxs, hxs_imp_c hxs⟩, },
refine h_restrict_le.mono (λ x hxc, _),
by_cases hxs : x ∈ s,
{ simpa [hxs] using hxc hxs, },
{ simpa [hxs] using hc, },
end
end complete_linear_order
namespace ennreal
variables {f : α → ℝ≥0∞}
lemma ae_le_ess_sup (f : α → ℝ≥0∞) : ∀ᵐ y ∂μ, f y ≤ ess_sup f μ :=
eventually_le_limsup f
@[simp] lemma ess_sup_eq_zero_iff : ess_sup f μ = 0 ↔ f =ᵐ[μ] 0 :=
limsup_eq_zero_iff
lemma ess_sup_const_mul {a : ℝ≥0∞} : ess_sup (λ (x : α), a * (f x)) μ = a * ess_sup f μ :=
limsup_const_mul
lemma ess_sup_add_le (f g : α → ℝ≥0∞) : ess_sup (f + g) μ ≤ ess_sup f μ + ess_sup g μ :=
limsup_add_le f g
lemma ess_sup_liminf_le {ι} [encodable ι] [linear_order ι] (f : ι → α → ℝ≥0∞) :
ess_sup (λ x, at_top.liminf (λ n, f n x)) μ ≤ at_top.liminf (λ n, ess_sup (λ x, f n x) μ) :=
by { simp_rw ess_sup, exact ennreal.limsup_liminf_le_liminf_limsup (λ a b, f b a), }
end ennreal
|
d794aff7ef2be193ac6e60fad8ca2a4508413005
|
5df84495ec6c281df6d26411cc20aac5c941e745
|
/src/formal_ml/prod_probability_space.lean
|
5be05e91034fd43bfb93adf2d7ab48118d1ae3c1
|
[
"Apache-2.0"
] |
permissive
|
eric-wieser/formal-ml
|
e278df5a8df78aa3947bc8376650419e1b2b0a14
|
630011d19fdd9539c8d6493a69fe70af5d193590
|
refs/heads/master
| 1,681,491,589,256
| 1,612,642,743,000
| 1,612,642,743,000
| 360,114,136
| 0
| 0
|
Apache-2.0
| 1,618,998,189,000
| 1,618,998,188,000
| null |
UTF-8
|
Lean
| false
| false
| 18,125
|
lean
|
/-
Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-/
import measure_theory.measurable_space
import measure_theory.measure_space
import measure_theory.outer_measure
import measure_theory.lebesgue_measure
import measure_theory.integration
import measure_theory.borel_space
import data.set.countable
import formal_ml.nnreal
import formal_ml.sum
import formal_ml.lattice
import formal_ml.measurable_space
import formal_ml.classical
import data.equiv.list
import formal_ml.prod_measure
import formal_ml.finite_pi_measure
import formal_ml.probability_space
/-
This file allows the construction of new probability spaces. This is useful
in particular when you want to consider a hypothetical scenario to relate back
to a real one.
For a family of random variables X indexed over β, there are a variety of operations.
1. pi.random_variable: We can create a new family of random variables Y, where for all (b:β),
X b and Y b are identical, and for any (b b':β), Y b and Y b' are independent.
A new probability measure is created for Y.
2. pi.random_variable_combine: create a new single random variable whose domain is
a function. Note: this does not create a new probability measure.
There are also some functions which work with a single random variable.
1. pi.rv: create a random variable that maps from a product probability measure to
a outcome space of a single measure in the product.
-/
noncomputable def prod.measure_space {α β:Type*} (Mα:measure_theory.measure_space α) (Mβ:measure_theory.measure_space β):measure_theory.measure_space (α × β) :=
@measure_theory.measure_space.mk (α × β) (@prod.measurable_space α β Mα.to_measurable_space Mβ.to_measurable_space) (prod.measure Mα.volume Mβ.volume)
lemma prod.measure_space.apply (α β:Type*) (Mα:measure_theory.measure_space α) (Mβ:measure_theory.measure_space β) (S:set (α × β)):
@measure_theory.measure_space.volume _ (prod.measure_space Mα Mβ) S =
(prod.measure Mα.volume Mβ.volume) S := rfl
lemma prod.measure_space.apply_prod (α β:Type*) (Mα:measure_theory.measure_space α) (Mβ:measure_theory.measure_space β) (A:set α) (B:set β):measurable_set A →
measurable_set B →
@measure_theory.measure_space.volume _ (prod.measure_space Mα Mβ) (A.prod B) =
(@measure_theory.measure_space.volume _ Mα (A)) *
(@measure_theory.measure_space.volume _ Mβ (B)) := begin
intros h1 h2,
rw prod.measure_space.apply,
rw prod.measure.apply_prod,
apply h1,
apply h2,
end
/- This is best understood through the lemma prod.probability_space.apply_prod -/
noncomputable def probability_space.prod {α β:Type*} (Pα:probability_space α) (Pβ:probability_space β):probability_space (α × β) :=
@probability_space.mk (α × β)
(prod.measure_space Pα.to_measure_space Pβ.to_measure_space)
begin
simp,
have A1:(@set.univ α).prod (@set.univ β) = (@set.univ (α × β)),
{ simp },
rw ← A1,
rw prod.measure_space.apply_prod,
repeat { simp },
end
def event.prod {α β:Type*} {Pα:probability_space α} {Pβ:probability_space β}
(A:event Pα) (B:event Pβ):
event (Pα.prod Pβ) := measurable_setB.prod A B
lemma event.prod_def {α β:Type*} {Pα:probability_space α} {Pβ:probability_space β}
(A:event Pα) (B:event Pβ):A.prod B = measurable_setB.prod A B := rfl
/- This proves that events are independent in the resulting probability space. -/
lemma prod.probability_space.apply_prod (α β:Type*) (Pα:probability_space α) (Pβ:probability_space β) (A:event Pα) (B:event Pβ):
Pr[A.prod B] = Pr[A] * Pr[B] := begin
rw ← ennreal.coe_eq_coe,
rw ennreal.coe_mul,
rw event_prob_def,
rw event_prob_def,
rw event_prob_def,
simp,
apply prod.measure_space.apply_prod,
apply A.property,
apply B.property,
end
/- Measurable functions from a product space to each multiplicand. -/
def rv_prod_fst {α β:Type*} (Pα:probability_space α) (Pβ:probability_space β):
(Pα.prod Pβ) →ᵣ Pα.to_measurable_space := mf_fst
def rv_prod_snd {α β:Type*} (Pα:probability_space α) (Pβ:probability_space β):
(Pα.prod Pβ) →ᵣ Pβ.to_measurable_space := mf_snd
/- Now that we have random variables mapping one probability space to another,
we need to compose random variables. -/
def rv_compose_rv {α β γ:Type*} {Pα:probability_space α} {Pβ:probability_space β}
{Mγ:measurable_space γ} (X:Pβ →ᵣ Mγ) (Y:Pα →ᵣ Pβ.to_measurable_space):Pα →ᵣ Mγ :=
compose_measurable_fun X Y
noncomputable def random_variable.on_fst {α β γ:Type*} {Pα:probability_space α} {Mγ:measurable_space γ}
(X:Pα →ᵣ Mγ) (Pβ:probability_space β) := rv_compose_rv X (rv_prod_fst Pα Pβ)
noncomputable def random_variable.on_snd {α β γ:Type*} {Pβ:probability_space β} {Mγ:measurable_space γ}
(X:Pβ →ᵣ Mγ) (Pα:probability_space α) := rv_compose_rv X (rv_prod_snd Pα Pβ)
lemma Pr_rv_prod_fst_eq {α β:Type*} {Pα:probability_space α}
{Pβ:probability_space β} (A:event Pα):
Pr[(rv_prod_fst Pα Pβ) ∈ᵣ A] = Pr[A] :=
begin
have h_event_rw:(rv_prod_fst Pα Pβ ∈ᵣ A) =
A.prod event_univ,
{ apply event.eq, simp [rv_prod_fst, event_univ, event.prod], ext ω, simp,
split; intros h_1; simp [h_1], },
rw h_event_rw,
rw prod.probability_space.apply_prod,
simp [rv_prod_fst, mf_fst],
end
lemma Pr_rv_prod_snd_eq {α β:Type*} {Pα:probability_space α}
{Pβ:probability_space β} (B:event Pβ):
Pr[(rv_prod_snd Pα Pβ) ∈ᵣ B] = Pr[B] :=
begin
have h_event_rw:(rv_prod_snd Pα Pβ ∈ᵣ B) =
event_univ.prod B,
{ apply event.eq, simp [rv_prod_snd, event_univ, event.prod], ext ω, simp,
split; intros h_1; simp [h_1], },
rw h_event_rw,
rw prod.probability_space.apply_prod,
simp [rv_prod_fst, mf_fst],
end
lemma ind_rv_prod_fst_rv_prod_snd {α β:Type*} {Pα:probability_space α}
{Pβ:probability_space β}:
random_variable_independent_pair (rv_prod_fst Pα Pβ) (rv_prod_snd Pα Pβ) :=
begin
intros A B,
let A':event Pα := A,
let B':event Pβ := B,
begin
unfold independent_event_pair,
have h_event_rw:(rv_prod_fst Pα Pβ ∈ᵣ A∧rv_prod_snd Pα Pβ ∈ᵣ B) =
A'.prod B',
{ apply event.eq, simp [rv_prod_fst, rv_prod_snd, A', B', event.prod], ext ω, simp },
rw h_event_rw,
rw Pr_rv_prod_fst_eq,
rw Pr_rv_prod_snd_eq,
rw prod.probability_space.apply_prod,
end
end
lemma random_variable.on_fst_on_snd_ind {α β γ κ:Type*} {Pα:probability_space α}
{Pβ:probability_space β} {Mγ:measurable_space γ} {Mκ:measurable_space κ}
{X:Pα →ᵣ Mγ} {Y:Pβ →ᵣ Mκ}:
random_variable_independent_pair (X.on_fst Pβ) (Y.on_snd Pα) :=
begin
simp [random_variable.on_fst, random_variable.on_snd, rv_compose_rv],
apply compose_independent_pair_left,
apply compose_independent_pair_right,
apply ind_rv_prod_fst_rv_prod_snd,
end
/- Creates a pair of random variables that are independent and defined over the
same probability space that are identical to the given random variables X and Y. -/
noncomputable def random_variable.pair_ind {α β γ κ:Type*} {Pα:probability_space α}
{Pβ:probability_space β} {Mγ:measurable_space γ} {Mκ:measurable_space κ}
(X:Pα →ᵣ Mγ) (Y:Pβ →ᵣ Mκ):prod (Pα.prod Pβ →ᵣ Mγ) (Pα.prod Pβ →ᵣ Mκ) :=
prod.mk (X.on_fst Pβ) (Y.on_snd Pα)
noncomputable def pi.measure_space {α:Type*} [F:fintype α] [N:nonempty α] {β:α → Type*} (M:∀ a, measure_theory.measure_space (β a)):
measure_theory.measure_space (Π a, β a) :=
@measure_theory.measure_space.mk (Π a, β a) (@measurable_space.pi α β (λ a, (M a).to_measurable_space)) (pi.measure (λ a, (M a).volume))
lemma pi.measure_space.apply {α:Type*} [F:fintype α] [N:nonempty α] {β:α → Type*} (M:∀ a, measure_theory.measure_space (β a)) (S:set (Π a, β a)):
@measure_theory.measure_space.volume _ (pi.measure_space M) S =
(pi.measure (λ a, (M a).volume)) S := rfl
lemma pi.measure_space.apply_prod {α:Type*} [F:fintype α] [N:nonempty α] {β:α → Type*} (M:∀ a, measure_theory.measure_space (β a)) {S:Π a, set (β a)}:
(∀ a, measurable_set (S a)) →
@measure_theory.measure_space.volume _ (pi.measure_space M) (set.pi set.univ S) =
finset.univ.prod (λ a, @measure_theory.measure_space.volume _ (M a) (S a)) := begin
intros h1,
rw pi.measure_space.apply,
rw pi.measure.apply_prod,
apply h1,
end
lemma pi.measure_space.Inf_sum2 {α:Type*} [F:fintype α] [N:nonempty α] {β:α → Type*} (M:Π (a:α), measure_theory.measure_space (β a)) {P:set (Π (a:α), β a)}:
measurable_set P →
@measure_theory.measure_space.volume _ (pi.measure_space M) P =
(⨅ (f:ℕ → (Π (a:α), set (β a))) (h₁:∀ n m, measurable_set (f n m))
(h₃:P ⊆ ⋃ (n:ℕ), set.pi set.univ (f n)),
∑' (n:ℕ), finset.univ.prod (λ (m:α),
@measure_theory.measure_space.volume _ (M m) (f n m))) := begin
intros h1,
rw pi.measure_space.apply,
rw pi.measure_apply,
rw pi.outer_measure.Inf_sum2,
apply h1,
end
noncomputable def pi.probability_space {α:Type*} [F:fintype α] [N:nonempty α] {β:α → Type*}
(P:Π a, probability_space (β a)):probability_space (Π a, β a) :=
@probability_space.mk (Π a, β a)
(pi.measure_space (λ a, (P a).to_measure_space))
begin
simp,
have A1:set.pi set.univ (λ a, @set.univ (β a)) = (@set.univ (Π a, β a)),
{ ext1 ω, split;intros A1_1; simp at A1_1, simp, },
rw ← A1,
rw pi.measure_space.apply_prod,
simp,
simp,
end
def set.pi_event {α:Type*} {β:α → Type*} [F:fintype α] [N:nonempty α]
{P:Π a, probability_space (β a)}
(T:set α) (E:Π a, event (P a)):event (pi.probability_space P) := T.pi_measurable E
lemma set.pi_event_univ {α:Type*} [F:fintype α] [N:nonempty α]
{β:α → Type*} {P:Π a, probability_space (β a)}
(S:Π a, event (P a)) (T:set α) [decidable_pred T]:set.pi_event T S = set.pi_event
(@set.univ α) (λ (a:α), if (a∈ T) then (S a) else (@event_univ (β a) (P a))) :=
begin
apply set.pi_measurable_univ,
end
lemma pi.probability_space.apply_prod {α:Type*} {β:α → Type*} [F:fintype α] [N:nonempty α]
{P:Π a, probability_space (β a)}
(E:Π a, event (P a)):Pr[set.pi_event set.univ E] = finset.univ.prod (λ a, Pr[E a]) := begin
rw ← ennreal.coe_eq_coe,
rw ennreal.coe_finset_prod,
simp [event_prob_def],
apply pi.measure_space.apply_prod,
intros a,
apply (E a).property,
end
lemma pi.probability_space.apply_prod' {α:Type*} {β:α → Type*} [F:fintype α] [N:nonempty α]
{P:Π a, probability_space (β a)} {T:finset α}
(E:Π a, event (P a)):Pr[set.pi_event (↑T) E] = T.prod (λ a, Pr[E a]) := begin
classical,
--have A1:=decidable.pred T,
rw set.pi_event_univ,
rw pi.probability_space.apply_prod,
--rw @finset.prod_congr _ _ finset.univ finset.univ,
have A2:finset.univ.prod (λ (a:α), if (a ∈ @coe (finset α) (set α) _ T) then Pr[E a] else 1) =
T.prod (λ (a:α), if (a ∈ @coe (finset α) (set α) _ T) then Pr[E a] else 1),
{ rw ← finset.prod_subset,
{ rw finset.subset_iff, intros x h_1, simp },
intros x h_unused h_x_notin_T,
rw if_neg,
intros contra,
apply h_x_notin_T,
rw ← finset.mem_coe,
apply contra },
have A3:T.prod (λ (a:α), if (a ∈ @coe (finset α) (set α) _ T) then Pr[E a] else 1) =
T.prod (λ (a:α), Pr[E a]),
{ apply finset.prod_congr,
refl,
intros x A3_1,
rw if_pos,
simp,
apply A3_1 },
rw ← A3,
rw ← A2,
apply finset.prod_congr,
{ refl },
{ intros x A4,
cases classical.em (x ∈ @coe (finset α) (set α) _ T) with A5 A5,
rw if_pos A5,
rw if_pos A5,
rw if_neg A5,
rw if_neg A5,
simp },
end
def mf_pi {α:Type*} {β:α → Type*} (M:Π a, measurable_space (β a))
(a:α):measurable_fun (@measurable_space.pi α β M) (M a) := @subtype.mk
((Π a, β a) → (β a))
measurable
(λ (d:Π a, β a), d a)
begin
apply measurable_pi_apply,
end
def pi.rv {α:Type*} {β:α → Type*} [F:fintype α] [N:nonempty α]
(P:Π a, probability_space (β a)) (a:α):(pi.probability_space P) →ᵣ (P a).to_measurable_space := mf_pi (λ a, (P a).to_measurable_space) a
noncomputable def pi.random_variable_proj {α:Type*} {β:α → Type*} {γ:Type*} [F:fintype α] [N:nonempty α]
(P:Π a, probability_space (β a)) (a:α) {M:measurable_space γ} (X:(P a) →ᵣ (M)):(pi.probability_space P) →ᵣ M := X ∘r (pi.rv P a)
/- Unify a collection of random variables to be independent random variables under a single probability measure. -/
noncomputable def pi.random_variable {α:Type*} {β:α → Type*} {γ:α → Type*} [F:fintype α] [N:nonempty α]
{P:Π a, probability_space (β a)} {M:Π a, measurable_space (γ a)} (X:Π a, (P a) →ᵣ (M a)):Π a, (pi.probability_space P) →ᵣ (M a) := (λ a, pi.random_variable_proj P a (X a))
lemma pi.rv_eq {α:Type*} {β:α → Type*} [F:fintype α] [N:nonempty α]
(P:Π a, probability_space (β a)) (a:α) (E:event (P a)):
Pr[(pi.rv P a)∈ᵣ E] = Pr[E] := begin
classical,
have A1:∀ (a':α), ∃ (E':event (P a')), Π (h:a=a'),E = @cast (event (P a'))
(event (P a)) begin rw h end E',
{ intros a', cases classical.em (a=a') with A1_1 A1_1,
{ subst a', apply exists.intro E, intros h, refl },
{ apply exists.intro (@event_univ (β a') (P a')),
intros h, exfalso, apply A1_1, apply h } },
have A2 := classical.axiom_of_choice A1,
cases A2 with E' A2,
have A4:a=a := rfl,
have A5 := A2 a A4,
have A3:(set.pi_event (@coe (finset α) (set α) _ {a}) E') = ((pi.rv P a)∈ᵣ E),
{ apply event.eq,
ext ω,
simp [set.pi_event,pi.rv,set.pi_measurable,mf_pi],
subst E,
refl,
},
rw ← A3,
rw pi.probability_space.apply_prod',
simp,
subst E,
refl,
end
lemma pi.random_variable_proj_identical {α:Type*} {β:α → Type*} {γ:Type*} [F:fintype α] [N:nonempty α]
(P:Π a, probability_space (β a)) (a:α) {M:measurable_space γ} (X:(P a) →ᵣ (M)):
random_variable_identical (pi.random_variable_proj P a X) X :=
begin
intros S,
simp [pi.random_variable_proj],
rw rv_compose_measurable_setB,
apply pi.rv_eq,
end
--(pi.probability_space P) →ᵣ M := X ∘r (pi.rv P a)
lemma pi.rv_independent {α:Type*} {β:α → Type*} [F:fintype α] [N:nonempty α]
(P:Π a, probability_space (β a)):
random_variable_independent (pi.rv P) :=
begin
classical,
intros S,
intros T,
have h1:(∀ᵣ (s : α) in T,(λ (b : α), @pi.rv α (λ (a : α), β a) F N P b ∈ᵣ S b) s) =
set.pi_event (↑T) S,
{ apply event.eq,
ext1 ω,
simp [set.pi_event, set.pi_measurable, pi.rv, mf_pi] },
rw h1,
rw pi.probability_space.apply_prod',
apply finset.prod_congr,
refl,
intros x A1,
rw pi.rv_eq,
end
lemma pi.random_variable_independent {α:Type*} {β:α → Type*} {γ:α → Type*} [F:fintype α]
[N:nonempty α] (P:Π a, probability_space (β a)) {M:Π a, measurable_space (γ a)}
(X:Π a, (P a) →ᵣ (M a)):
random_variable_independent (pi.random_variable X) :=
begin
simp [pi.random_variable, pi.random_variable_proj, rv_compose_rv],
apply compose_independent',
apply pi.rv_independent,
end
noncomputable def pi.random_variable_IID {β γ:Type*} {P:probability_space β}
{M:measurable_space γ} (X:P →ᵣ M) (m:nat):(fin m.succ) →
(pi.probability_space (λ (m:fin m.succ), P) →ᵣ M)
:=
@pi.random_variable (fin m.succ) (λ (a:fin m.succ), β)
(λ (a:fin m.succ), γ) _ _
(λ a, P) (λ a, M) (λ a, X)
lemma pi.random_variable_IID_independent {β γ:Type*} {P:probability_space β}
{M:measurable_space γ} (X:P →ᵣ M) (m:nat):
random_variable_independent (pi.random_variable_IID X m) := begin
simp [random_variable_independent],
apply pi.random_variable_independent,
end
lemma pi.random_variable_IID_identical {β γ:Type*} {P:probability_space β}
{M:measurable_space γ} (X:P →ᵣ M) (m:nat) (i:fin m.succ):
random_variable_identical (pi.random_variable_IID X m i)
X := begin
simp [pi.random_variable_IID, pi.random_variable],
apply pi.random_variable_proj_identical,
end
lemma pi.random_variable_IID_identical' {β γ:Type*} {P:probability_space β}
{M:measurable_space γ} (X:P →ᵣ M) (m:nat) (i j:fin m.succ):
random_variable_identical (pi.random_variable_IID X m i)
(pi.random_variable_IID X m j) := begin
apply random_variable_identical.trans,
apply pi.random_variable_IID_identical,
apply random_variable_identical.symm,
apply pi.random_variable_IID_identical,
end
lemma pi.random_variable_IID_IID {β γ:Type*} {P:probability_space β}
{M:measurable_space γ} (X:P →ᵣ M) (m:nat):
random_variables_IID (pi.random_variable_IID X m) := begin
simp [random_variables_IID],
split,
apply pi.random_variable_IID_independent,
intros i j,
apply pi.random_variable_IID_identical',
end
/- Pair a random variable with a collection of random variables.
Since the collection of random variables already share a probability
measure, we make sure that the resulting random variables
share the product measure of Pα and Pβ. -/
noncomputable def random_variable.pair_collection {α β γ κ δ:Type*}
{Pα:probability_space α}
{Pβ:probability_space β} {Mγ:measurable_space γ} {Mκ:measurable_space κ}
(X:δ → Pα →ᵣ Mγ) (Y:Pβ →ᵣ Mκ):prod (δ → Pα.prod Pβ →ᵣ Mγ) (Pα.prod Pβ →ᵣ Mκ) :=
prod.mk (λ (d:δ), (X d).on_fst Pβ) (Y.on_snd Pα)
|
dd79c8e049b3fda50cada0b2c7a5883a5be9b3f9
|
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
|
/tests/lean/run/sub.lean
|
bcb2b0539e9cf0fab0bf4d3dbd805124a1d32dd6
|
[
"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
| 126
|
lean
|
notation `{` binders:55 ` \ ` r:(scoped P, subtype P) `}` := r
check { x : nat \ x > 0 }
check { (x : nat → nat) \ true }
|
0f29a39fd6f1227025fb66e014d6d7682c856fe8
|
bb31430994044506fa42fd667e2d556327e18dfe
|
/src/field_theory/finite/basic.lean
|
d75cbf123359130ad442bec237177f6defdbe927
|
[
"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
| 20,525
|
lean
|
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Joey van Langen, Casper Putz
-/
import field_theory.separable
import field_theory.splitting_field
import ring_theory.integral_domain
import tactic.apply_fun
/-!
# Finite fields
This file contains basic results about finite fields.
Throughout most of this file, `K` denotes a finite field
and `q` is notation for the cardinality of `K`.
See `ring_theory.integral_domain` for the fact that the unit group of a finite field is a
cyclic group, as well as the fact that every finite integral domain is a field
(`fintype.field_of_domain`).
## Main results
1. `fintype.card_units`: The unit group of a finite field is has cardinality `q - 1`.
2. `sum_pow_units`: The sum of `x^i`, where `x` ranges over the units of `K`, is
- `q-1` if `q-1 ∣ i`
- `0` otherwise
3. `finite_field.card`: The cardinality `q` is a power of the characteristic of `K`.
See `card'` for a variant.
## Notation
Throughout most of this file, `K` denotes a finite field
and `q` is notation for the cardinality of `K`.
## Implementation notes
While `fintype Kˣ` can be inferred from `fintype K` in the presence of `decidable_eq K`,
in this file we take the `fintype Kˣ` argument directly to reduce the chance of typeclass
diamonds, as `fintype` carries data.
-/
variables {K : Type*} {R : Type*}
local notation `q` := fintype.card K
open finset function
open_locale big_operators polynomial
namespace finite_field
section polynomial
variables [comm_ring R] [is_domain R]
open polynomial
/-- The cardinality of a field is at most `n` times the cardinality of the image of a degree `n`
polynomial -/
lemma card_image_polynomial_eval [decidable_eq R] [fintype R] {p : R[X]}
(hp : 0 < p.degree) : fintype.card R ≤ nat_degree p * (univ.image (λ x, eval x p)).card :=
finset.card_le_mul_card_image _ _
(λ a _, calc _ = (p - C a).roots.to_finset.card : congr_arg card
(by simp [finset.ext_iff, mem_roots_sub_C hp])
... ≤ (p - C a).roots.card : multiset.to_finset_card_le _
... ≤ _ : card_roots_sub_C' hp)
/-- If `f` and `g` are quadratic polynomials, then the `f.eval a + g.eval b = 0` has a solution. -/
lemma exists_root_sum_quadratic [fintype R] {f g : R[X]} (hf2 : degree f = 2)
(hg2 : degree g = 2) (hR : fintype.card R % 2 = 1) : ∃ a b, f.eval a + g.eval b = 0 :=
by letI := classical.dec_eq R; exact
suffices ¬ disjoint (univ.image (λ x : R, eval x f)) (univ.image (λ x : R, eval x (-g))),
begin
simp only [disjoint_left, mem_image] at this,
push_neg at this,
rcases this with ⟨x, ⟨a, _, ha⟩, ⟨b, _, hb⟩⟩,
exact ⟨a, b, by rw [ha, ← hb, eval_neg, neg_add_self]⟩
end,
assume hd : disjoint _ _,
lt_irrefl (2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card) $
calc 2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card
≤ 2 * fintype.card R : nat.mul_le_mul_left _ (finset.card_le_univ _)
... = fintype.card R + fintype.card R : two_mul _
... < nat_degree f * (univ.image (λ x : R, eval x f)).card +
nat_degree (-g) * (univ.image (λ x : R, eval x (-g))).card :
add_lt_add_of_lt_of_le
(lt_of_le_of_ne
(card_image_polynomial_eval (by rw hf2; exact dec_trivial))
(mt (congr_arg (%2)) (by simp [nat_degree_eq_of_degree_eq_some hf2, hR])))
(card_image_polynomial_eval (by rw [degree_neg, hg2]; exact dec_trivial))
... = 2 * (univ.image (λ x : R, eval x f) ∪ univ.image (λ x : R, eval x (-g))).card :
by rw [card_disjoint_union hd]; simp [nat_degree_eq_of_degree_eq_some hf2,
nat_degree_eq_of_degree_eq_some hg2, bit0, mul_add]
end polynomial
lemma prod_univ_units_id_eq_neg_one [comm_ring K] [is_domain K] [fintype Kˣ] :
(∏ x : Kˣ, x) = (-1 : Kˣ) :=
begin
classical,
have : (∏ x in (@univ Kˣ _).erase (-1), x) = 1,
from prod_involution (λ x _, x⁻¹) (by simp)
(λ a, by simp [units.inv_eq_self_iff] {contextual := tt})
(λ a, by simp [@inv_eq_iff_inv_eq _ _ a, eq_comm])
(by simp),
rw [← insert_erase (mem_univ (-1 : Kˣ)), prod_insert (not_mem_erase _ _),
this, mul_one]
end
section
variables [group_with_zero K] [fintype K]
lemma pow_card_sub_one_eq_one (a : K) (ha : a ≠ 0) : a ^ (q - 1) = 1 :=
calc a ^ (fintype.card K - 1) = (units.mk0 a ha ^ (fintype.card K - 1) : Kˣ) :
by rw [units.coe_pow, units.coe_mk0]
... = 1 : by { classical, rw [← fintype.card_units, pow_card_eq_one], refl }
lemma pow_card (a : K) : a ^ q = a :=
begin
have hp : 0 < fintype.card K := lt_trans zero_lt_one fintype.one_lt_card,
by_cases h : a = 0, { rw h, apply zero_pow hp },
rw [← nat.succ_pred_eq_of_pos hp, pow_succ, nat.pred_eq_sub_one,
pow_card_sub_one_eq_one a h, mul_one],
end
lemma pow_card_pow (n : ℕ) (a : K) : a ^ q ^ n = a :=
begin
induction n with n ih,
{ simp, },
{ simp [pow_succ, pow_mul, ih, pow_card], },
end
end
variables (K) [field K] [fintype K]
theorem card (p : ℕ) [char_p K p] : ∃ (n : ℕ+), nat.prime p ∧ q = p^(n : ℕ) :=
begin
haveI hp : fact p.prime := ⟨char_p.char_is_prime K p⟩,
letI : module (zmod p) K := { .. (zmod.cast_hom dvd_rfl K : zmod p →+* _).to_module },
obtain ⟨n, h⟩ := vector_space.card_fintype (zmod p) K,
rw zmod.card at h,
refine ⟨⟨n, _⟩, hp.1, h⟩,
apply or.resolve_left (nat.eq_zero_or_pos n),
rintro rfl,
rw pow_zero at h,
have : (0 : K) = 1, { apply fintype.card_le_one_iff.mp (le_of_eq h) },
exact absurd this zero_ne_one,
end
-- this statement doesn't use `q` because we want `K` to be an explicit parameter
theorem card' : ∃ (p : ℕ) (n : ℕ+), nat.prime p ∧ fintype.card K = p^(n : ℕ) :=
let ⟨p, hc⟩ := char_p.exists K in ⟨p, @finite_field.card K _ _ p hc⟩
@[simp] lemma cast_card_eq_zero : (q : K) = 0 :=
begin
rcases char_p.exists K with ⟨p, _char_p⟩, resetI,
rcases card K p with ⟨n, hp, hn⟩,
simp only [char_p.cast_eq_zero_iff K p, hn],
conv { congr, rw [← pow_one p] },
exact pow_dvd_pow _ n.2,
end
lemma forall_pow_eq_one_iff (i : ℕ) :
(∀ x : Kˣ, x ^ i = 1) ↔ q - 1 ∣ i :=
begin
classical,
obtain ⟨x, hx⟩ := is_cyclic.exists_generator Kˣ,
rw [←fintype.card_units, ←order_of_eq_card_of_forall_mem_zpowers hx, order_of_dvd_iff_pow_eq_one],
split,
{ intro h, apply h },
{ intros h y,
simp_rw ← mem_powers_iff_mem_zpowers at hx,
rcases hx y with ⟨j, rfl⟩,
rw [← pow_mul, mul_comm, pow_mul, h, one_pow], }
end
/-- The sum of `x ^ i` as `x` ranges over the units of a finite field of cardinality `q`
is equal to `0` unless `(q - 1) ∣ i`, in which case the sum is `q - 1`. -/
lemma sum_pow_units [fintype Kˣ] (i : ℕ) :
∑ x : Kˣ, (x ^ i : K) = if (q - 1) ∣ i then -1 else 0 :=
begin
let φ : Kˣ →* K :=
{ to_fun := λ x, x ^ i,
map_one' := by rw [units.coe_one, one_pow],
map_mul' := by { intros, rw [units.coe_mul, mul_pow] } },
haveI : decidable (φ = 1), { classical, apply_instance },
calc ∑ x : Kˣ, φ x = if φ = 1 then fintype.card Kˣ else 0 : sum_hom_units φ
... = if (q - 1) ∣ i then -1 else 0 : _,
suffices : (q - 1) ∣ i ↔ φ = 1,
{ simp only [this],
split_ifs with h h, swap, refl,
rw [fintype.card_units, nat.cast_sub, cast_card_eq_zero, nat.cast_one, zero_sub],
show 1 ≤ q, from fintype.card_pos_iff.mpr ⟨0⟩ },
rw [← forall_pow_eq_one_iff, monoid_hom.ext_iff],
apply forall_congr, intro x,
rw [units.ext_iff, units.coe_pow, units.coe_one, monoid_hom.one_apply],
refl,
end
/-- The sum of `x ^ i` as `x` ranges over a finite field of cardinality `q`
is equal to `0` if `i < q - 1`. -/
lemma sum_pow_lt_card_sub_one (i : ℕ) (h : i < q - 1) :
∑ x : K, x ^ i = 0 :=
begin
by_cases hi : i = 0,
{ simp only [hi, nsmul_one, sum_const, pow_zero, card_univ, cast_card_eq_zero], },
classical,
have hiq : ¬ (q - 1) ∣ i, { contrapose! h, exact nat.le_of_dvd (nat.pos_of_ne_zero hi) h },
let φ : Kˣ ↪ K := ⟨coe, units.ext⟩,
have : univ.map φ = univ \ {0},
{ ext x,
simp only [true_and, embedding.coe_fn_mk, mem_sdiff, units.exists_iff_ne_zero,
mem_univ, mem_map, exists_prop_of_true, mem_singleton] },
calc ∑ x : K, x ^ i = ∑ x in univ \ {(0 : K)}, x ^ i :
by rw [← sum_sdiff ({0} : finset K).subset_univ, sum_singleton,
zero_pow (nat.pos_of_ne_zero hi), add_zero]
... = ∑ x : Kˣ, x ^ i : by { rw [← this, univ.sum_map φ], refl }
... = 0 : by { rw [sum_pow_units K i, if_neg], exact hiq, }
end
section is_splitting_field
open polynomial
section
variables (K' : Type*) [field K'] {p n : ℕ}
lemma X_pow_card_sub_X_nat_degree_eq (hp : 1 < p) :
(X ^ p - X : K'[X]).nat_degree = p :=
begin
have h1 : (X : K'[X]).degree < (X ^ p : K'[X]).degree,
{ rw [degree_X_pow, degree_X],
exact_mod_cast hp },
rw [nat_degree_eq_of_degree_eq (degree_sub_eq_left_of_degree_lt h1), nat_degree_X_pow],
end
lemma X_pow_card_pow_sub_X_nat_degree_eq (hn : n ≠ 0) (hp : 1 < p) :
(X ^ p ^ n - X : K'[X]).nat_degree = p ^ n :=
X_pow_card_sub_X_nat_degree_eq K' $ nat.one_lt_pow _ _ (nat.pos_of_ne_zero hn) hp
lemma X_pow_card_sub_X_ne_zero (hp : 1 < p) : (X ^ p - X : K'[X]) ≠ 0 :=
ne_zero_of_nat_degree_gt $
calc 1 < _ : hp
... = _ : (X_pow_card_sub_X_nat_degree_eq K' hp).symm
lemma X_pow_card_pow_sub_X_ne_zero (hn : n ≠ 0) (hp : 1 < p) :
(X ^ p ^ n - X : K'[X]) ≠ 0 :=
X_pow_card_sub_X_ne_zero K' $ nat.one_lt_pow _ _ (nat.pos_of_ne_zero hn) hp
end
variables (p : ℕ) [fact p.prime] [algebra (zmod p) K]
lemma roots_X_pow_card_sub_X : roots (X^q - X : K[X]) = finset.univ.val :=
begin
classical,
have aux : (X^q - X : K[X]) ≠ 0 := X_pow_card_sub_X_ne_zero K fintype.one_lt_card,
have : (roots (X^q - X : K[X])).to_finset = finset.univ,
{ rw eq_univ_iff_forall,
intro x,
rw [multiset.mem_to_finset, mem_roots aux, is_root.def, eval_sub, eval_pow, eval_X, sub_eq_zero,
pow_card] },
rw [←this, multiset.to_finset_val, eq_comm, multiset.dedup_eq_self],
apply nodup_roots,
rw separable_def,
convert is_coprime_one_right.neg_right using 1,
{ rw [derivative_sub, derivative_X, derivative_X_pow, char_p.cast_card_eq_zero K, C_0, zero_mul,
zero_sub] },
end
instance (F : Type*) [field F] [algebra F K] : is_splitting_field F K (X^q - X) :=
{ splits :=
begin
have h : (X^q - X : K[X]).nat_degree = q :=
X_pow_card_sub_X_nat_degree_eq K fintype.one_lt_card,
rw [←splits_id_iff_splits, splits_iff_card_roots, polynomial.map_sub, polynomial.map_pow,
map_X, h, roots_X_pow_card_sub_X K, ←finset.card_def, finset.card_univ],
end,
adjoin_roots :=
begin
classical,
transitivity algebra.adjoin F ((roots (X^q - X : K[X])).to_finset : set K),
{ simp only [polynomial.map_pow, map_X, polynomial.map_sub], },
{ rw [roots_X_pow_card_sub_X, val_to_finset, coe_univ, algebra.adjoin_univ], }
end }
end is_splitting_field
variables {K}
theorem frobenius_pow {p : ℕ} [fact p.prime] [char_p K p] {n : ℕ} (hcard : q = p^n) :
(frobenius K p) ^ n = 1 :=
begin
ext, conv_rhs { rw [ring_hom.one_def, ring_hom.id_apply, ← pow_card x, hcard], }, clear hcard,
induction n, {simp},
rw [pow_succ, pow_succ', pow_mul, ring_hom.mul_def, ring_hom.comp_apply, frobenius_def, n_ih]
end
open polynomial
lemma expand_card (f : K[X]) :
expand K q f = f ^ q :=
begin
cases char_p.exists K with p hp,
letI := hp,
rcases finite_field.card K p with ⟨⟨n, npos⟩, ⟨hp, hn⟩⟩,
haveI : fact p.prime := ⟨hp⟩,
dsimp at hn,
rw [hn, ← map_expand_pow_char, frobenius_pow hn, ring_hom.one_def, map_id]
end
end finite_field
namespace zmod
open finite_field polynomial
lemma sq_add_sq (p : ℕ) [hp : fact p.prime] (x : zmod p) :
∃ a b : zmod p, a^2 + b^2 = x :=
begin
cases hp.1.eq_two_or_odd with hp2 hp_odd,
{ substI p, change fin 2 at x, fin_cases x, { use 0, simp }, { use [0, 1], simp } },
let f : (zmod p)[X] := X^2,
let g : (zmod p)[X] := X^2 - C x,
obtain ⟨a, b, hab⟩ : ∃ a b, f.eval a + g.eval b = 0 :=
@exists_root_sum_quadratic _ _ _ _ f g
(degree_X_pow 2) (degree_X_pow_sub_C dec_trivial _) (by rw [zmod.card, hp_odd]),
refine ⟨a, b, _⟩,
rw ← sub_eq_zero,
simpa only [eval_C, eval_X, eval_pow, eval_sub, ← add_sub_assoc] using hab,
end
end zmod
namespace char_p
lemma sq_add_sq (R : Type*) [comm_ring R] [is_domain R]
(p : ℕ) [ne_zero p] [char_p R p] (x : ℤ) :
∃ a b : ℕ, (a^2 + b^2 : R) = x :=
begin
haveI := char_is_prime_of_pos R p,
obtain ⟨a, b, hab⟩ := zmod.sq_add_sq p x,
refine ⟨a.val, b.val, _⟩,
simpa using congr_arg (zmod.cast_hom dvd_rfl R) hab
end
end char_p
open_locale nat
open zmod
/-- The **Fermat-Euler totient theorem**. `nat.modeq.pow_totient` is an alternative statement
of the same theorem. -/
@[simp] lemma zmod.pow_totient {n : ℕ} (x : (zmod n)ˣ) : x ^ φ n = 1 :=
begin
cases n,
{ rw [nat.totient_zero, pow_zero] },
{ rw [← card_units_eq_totient, pow_card_eq_one] }
end
/-- The **Fermat-Euler totient theorem**. `zmod.pow_totient` is an alternative statement
of the same theorem. -/
lemma nat.modeq.pow_totient {x n : ℕ} (h : nat.coprime x n) : x ^ φ n ≡ 1 [MOD n] :=
begin
rw ← zmod.eq_iff_modeq_nat,
let x' : units (zmod n) := zmod.unit_of_coprime _ h,
have := zmod.pow_totient x',
apply_fun (coe : units (zmod n) → zmod n) at this,
simpa only [-zmod.pow_totient, nat.succ_eq_add_one, nat.cast_pow, units.coe_one,
nat.cast_one, coe_unit_of_coprime, units.coe_pow],
end
section
variables {V : Type*} [fintype K] [division_ring K] [add_comm_group V] [module K V]
-- should this go in a namespace?
-- finite_dimensional would be natural,
-- but we don't assume it...
lemma card_eq_pow_finrank [fintype V] :
fintype.card V = q ^ (finite_dimensional.finrank K V) :=
begin
let b := is_noetherian.finset_basis K V,
rw [module.card_fintype b, ← finite_dimensional.finrank_eq_card_basis b],
end
end
open finite_field
namespace zmod
/-- A variation on Fermat's little theorem. See `zmod.pow_card_sub_one_eq_one` -/
@[simp] lemma pow_card {p : ℕ} [fact p.prime] (x : zmod p) : x ^ p = x :=
by { have h := finite_field.pow_card x, rwa zmod.card p at h }
@[simp] lemma pow_card_pow {n p : ℕ} [fact p.prime] (x : zmod p) : x ^ p ^ n = x :=
begin
induction n with n ih,
{ simp, },
{ simp [pow_succ, pow_mul, ih, pow_card], },
end
@[simp] lemma frobenius_zmod (p : ℕ) [fact p.prime] :
frobenius (zmod p) p = ring_hom.id _ :=
by { ext a, rw [frobenius_def, zmod.pow_card, ring_hom.id_apply] }
@[simp] lemma card_units (p : ℕ) [fact p.prime] : fintype.card ((zmod p)ˣ) = p - 1 :=
by rw [fintype.card_units, card]
/-- **Fermat's Little Theorem**: for every unit `a` of `zmod p`, we have `a ^ (p - 1) = 1`. -/
theorem units_pow_card_sub_one_eq_one (p : ℕ) [fact p.prime] (a : (zmod p)ˣ) :
a ^ (p - 1) = 1 :=
by rw [← card_units p, pow_card_eq_one]
/-- **Fermat's Little Theorem**: for all nonzero `a : zmod p`, we have `a ^ (p - 1) = 1`. -/
theorem pow_card_sub_one_eq_one {p : ℕ} [fact p.prime] {a : zmod p} (ha : a ≠ 0) :
a ^ (p - 1) = 1 :=
by { have h := pow_card_sub_one_eq_one a ha, rwa zmod.card p at h }
theorem order_of_units_dvd_card_sub_one {p : ℕ} [fact p.prime] (u : (zmod p)ˣ) :
order_of u ∣ p - 1 :=
order_of_dvd_of_pow_eq_one $ units_pow_card_sub_one_eq_one _ _
theorem order_of_dvd_card_sub_one {p : ℕ} [fact p.prime] {a : zmod p} (ha : a ≠ 0) :
order_of a ∣ p - 1 :=
order_of_dvd_of_pow_eq_one $ pow_card_sub_one_eq_one ha
open polynomial
lemma expand_card {p : ℕ} [fact p.prime] (f : polynomial (zmod p)) :
expand (zmod p) p f = f ^ p :=
by { have h := finite_field.expand_card f, rwa zmod.card p at h }
end zmod
/-- **Fermat's Little Theorem**: for all `a : ℤ` coprime to `p`, we have
`a ^ (p - 1) ≡ 1 [ZMOD p]`. -/
lemma int.modeq.pow_card_sub_one_eq_one {p : ℕ} (hp : nat.prime p) {n : ℤ} (hpn : is_coprime n p) :
n ^ (p - 1) ≡ 1 [ZMOD p] :=
begin
haveI : fact p.prime := ⟨hp⟩,
have : ¬ (n : zmod p) = 0,
{ rw [char_p.int_cast_eq_zero_iff _ p, ← (nat.prime_iff_prime_int.mp hp).coprime_iff_not_dvd],
{ exact hpn.symm },
exact zmod.char_p p },
simpa [← zmod.int_coe_eq_int_coe_iff] using zmod.pow_card_sub_one_eq_one this
end
section
namespace finite_field
variables {F : Type*} [field F]
section finite
variables [finite F]
/-- In a finite field of characteristic `2`, all elements are squares. -/
lemma is_square_of_char_two (hF : ring_char F = 2) (a : F) : is_square a :=
begin
haveI hF' : char_p F 2 := ring_char.of_eq hF,
exact is_square_of_char_two' a,
end
/-- In a finite field of odd characteristic, not every element is a square. -/
lemma exists_nonsquare (hF : ring_char F ≠ 2) : ∃ (a : F), ¬ is_square a :=
begin
-- Idea: the squaring map on `F` is not injective, hence not surjective
let sq : F → F := λ x, x ^ 2,
have h : ¬ injective sq,
{ simp only [injective, not_forall, exists_prop],
refine ⟨-1, 1, _, ring.neg_one_ne_one_of_char_ne_two hF⟩,
simp only [sq, one_pow, neg_one_sq] },
rw finite.injective_iff_surjective at h, -- sq not surjective
simp_rw [is_square, ←pow_two, @eq_comm _ _ (_ ^ 2)],
push_neg at ⊢ h,
exact h,
end
end finite
variables [fintype F]
/-- The finite field `F` has even cardinality iff it has characteristic `2`. -/
lemma even_card_iff_char_two : ring_char F = 2 ↔ fintype.card F % 2 = 0 :=
begin
rcases finite_field.card F (ring_char F) with ⟨n, hp, h⟩,
rw [h, nat.pow_mod],
split,
{ intro hF,
rw hF,
simp only [nat.bit0_mod_two, zero_pow', ne.def, pnat.ne_zero, not_false_iff, nat.zero_mod], },
{ rw [← nat.even_iff, nat.even_pow],
rintros ⟨hev, hnz⟩,
rw [nat.even_iff, nat.mod_mod] at hev,
exact (nat.prime.eq_two_or_odd hp).resolve_right (ne_of_eq_of_ne hev zero_ne_one), },
end
lemma even_card_of_char_two (hF : ring_char F = 2) : fintype.card F % 2 = 0 :=
even_card_iff_char_two.mp hF
lemma odd_card_of_char_ne_two (hF : ring_char F ≠ 2) : fintype.card F % 2 = 1 :=
nat.mod_two_ne_zero.mp (mt even_card_iff_char_two.mpr hF)
/-- If `F` has odd characteristic, then for nonzero `a : F`, we have that `a ^ (#F / 2) = ±1`. -/
lemma pow_dichotomy (hF : ring_char F ≠ 2) {a : F} (ha : a ≠ 0) :
a ^ (fintype.card F / 2) = 1 ∨ a ^ (fintype.card F / 2) = -1 :=
begin
have h₁ := finite_field.pow_card_sub_one_eq_one a ha,
rw [← nat.two_mul_odd_div_two (finite_field.odd_card_of_char_ne_two hF),
mul_comm, pow_mul, pow_two] at h₁,
exact mul_self_eq_one_iff.mp h₁,
end
/-- A unit `a` of a finite field `F` of odd characteristic is a square
if and only if `a ^ (#F / 2) = 1`. -/
lemma unit_is_square_iff (hF : ring_char F ≠ 2) (a : Fˣ) :
is_square a ↔ a ^ (fintype.card F / 2) = 1 :=
begin
classical,
obtain ⟨g, hg⟩ := is_cyclic.exists_generator Fˣ,
obtain ⟨n, hn⟩ : a ∈ submonoid.powers g, { rw mem_powers_iff_mem_zpowers, apply hg },
have hodd := nat.two_mul_odd_div_two (finite_field.odd_card_of_char_ne_two hF),
split,
{ rintro ⟨y, rfl⟩,
rw [← pow_two, ← pow_mul, hodd],
apply_fun (@coe Fˣ F _) using units.ext,
{ push_cast,
exact finite_field.pow_card_sub_one_eq_one (y : F) (units.ne_zero y), }, },
{ subst a, assume h,
have key : 2 * (fintype.card F / 2) ∣ n * (fintype.card F / 2),
{ rw [← pow_mul] at h,
rw [hodd, ← fintype.card_units, ← order_of_eq_card_of_forall_mem_zpowers hg],
apply order_of_dvd_of_pow_eq_one h },
have : 0 < fintype.card F / 2 := nat.div_pos fintype.one_lt_card (by norm_num),
obtain ⟨m, rfl⟩ := nat.dvd_of_mul_dvd_mul_right this key,
refine ⟨g ^ m, _⟩,
rw [mul_comm, pow_mul, pow_two], },
end
/-- A non-zero `a : F` is a square if and only if `a ^ (#F / 2) = 1`. -/
lemma is_square_iff (hF : ring_char F ≠ 2) {a : F} (ha : a ≠ 0) :
is_square a ↔ a ^ (fintype.card F / 2) = 1 :=
begin
apply (iff_congr _ (by simp [units.ext_iff])).mp
(finite_field.unit_is_square_iff hF (units.mk0 a ha)),
simp only [is_square, units.ext_iff, units.coe_mk0, units.coe_mul],
split,
{ rintro ⟨y, hy⟩, exact ⟨y, hy⟩ },
{ rintro ⟨y, rfl⟩,
have hy : y ≠ 0, { rintro rfl, simpa [zero_pow] using ha, },
refine ⟨units.mk0 y hy, _⟩, simp, }
end
end finite_field
end
|
a5b0e0e36dfd9174b2d22932db5551b6275f3498
|
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
|
/src/order/filter/cofinite.lean
|
55a4f5b50f768fc76f7a3a2c5c844604828d7a71
|
[
"Apache-2.0"
] |
permissive
|
anthony2698/mathlib
|
03cd69fe5c280b0916f6df2d07c614c8e1efe890
|
407615e05814e98b24b2ff322b14e8e3eb5e5d67
|
refs/heads/master
| 1,678,792,774,873
| 1,614,371,563,000
| 1,614,371,563,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 3,133
|
lean
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov
-/
import order.filter.at_top_bot
/-!
# The cofinite filter
In this file we define
`cofinite`: the filter of sets with finite complement
and prove its basic properties. In particular, we prove that for `ℕ` it is equal to `at_top`.
## TODO
Define filters for other cardinalities of the complement.
-/
open set
open_locale classical
variables {α : Type*}
namespace filter
/-- The cofinite filter is the filter of subsets whose complements are finite. -/
def cofinite : filter α :=
{ sets := {s | finite sᶜ},
univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq],
sets_of_superset := assume s t (hs : finite sᶜ) (st: s ⊆ t),
hs.subset $ compl_subset_compl.2 st,
inter_sets := assume s t (hs : finite sᶜ) (ht : finite (tᶜ)),
by simp only [compl_inter, finite.union, ht, hs, mem_set_of_eq] }
@[simp] lemma mem_cofinite {s : set α} : s ∈ (@cofinite α) ↔ finite sᶜ := iff.rfl
@[simp] lemma eventually_cofinite {p : α → Prop} :
(∀ᶠ x in cofinite, p x) ↔ finite {x | ¬p x} := iff.rfl
instance cofinite_ne_bot [infinite α] : ne_bot (@cofinite α) :=
⟨mt empty_in_sets_eq_bot.mpr $ by { simp only [mem_cofinite, compl_empty], exact infinite_univ }⟩
lemma frequently_cofinite_iff_infinite {p : α → Prop} :
(∃ᶠ x in cofinite, p x) ↔ set.infinite {x | p x} :=
by simp only [filter.frequently, filter.eventually, mem_cofinite, compl_set_of, not_not,
set.infinite]
end filter
open filter
lemma set.finite.compl_mem_cofinite {s : set α} (hs : s.finite) : sᶜ ∈ (@cofinite α) :=
mem_cofinite.2 $ (compl_compl s).symm ▸ hs
lemma set.finite.eventually_cofinite_nmem {s : set α} (hs : s.finite) : ∀ᶠ x in cofinite, x ∉ s :=
hs.compl_mem_cofinite
lemma finset.eventually_cofinite_nmem (s : finset α) : ∀ᶠ x in cofinite, x ∉ s :=
s.finite_to_set.eventually_cofinite_nmem
lemma set.infinite_iff_frequently_cofinite {s : set α} :
set.infinite s ↔ (∃ᶠ x in cofinite, x ∈ s) :=
frequently_cofinite_iff_infinite.symm
lemma filter.eventually_cofinite_ne (x : α) : ∀ᶠ a in cofinite, a ≠ x :=
(set.finite_singleton x).eventually_cofinite_nmem
/-- For natural numbers the filters `cofinite` and `at_top` coincide. -/
lemma nat.cofinite_eq_at_top : @cofinite ℕ = at_top :=
begin
ext s,
simp only [mem_cofinite, mem_at_top_sets],
split,
{ assume hs,
use (hs.to_finset.sup id) + 1,
assume b hb,
by_contradiction hbs,
have := hs.to_finset.subset_range_sup_succ (finite.mem_to_finset.2 hbs),
exact not_lt_of_le hb (finset.mem_range.1 this) },
{ rintros ⟨N, hN⟩,
apply (finite_lt_nat N).subset,
assume n hn,
change n < N,
exact lt_of_not_ge (λ hn', hn $ hN n hn') }
end
lemma nat.frequently_at_top_iff_infinite {p : ℕ → Prop} :
(∃ᶠ n in at_top, p n) ↔ set.infinite {n | p n} :=
by simp only [← nat.cofinite_eq_at_top, frequently_cofinite_iff_infinite]
|
e82cd7a34f0d2bd2ef7a612e6a8dbd6b7e171477
|
88892181780ff536a81e794003fe058062f06758
|
/src/lib/tactics.lean
|
156fcb3a980dc96e2bba4fcd69bdda3ab92fb7f2
|
[] |
no_license
|
AtnNn/lean-sandbox
|
fe2c44280444e8bb8146ab8ac391c82b480c0a2e
|
8c68afbdc09213173aef1be195da7a9a86060a97
|
refs/heads/master
| 1,623,004,395,876
| 1,579,969,507,000
| 1,579,969,507,000
| 146,666,368
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 1,385
|
lean
|
import tactic.ring
import tactic.finish
import tactic.interactive
import tactic.find
import tactic.tidy
import tactic.well_founded_tactics
import lib.tactic.dmatch
open lean
open lean.parser
namespace tactic
namespace interactive
open interactive interactive.types expr
-- `let_eq h : x = v` is like `generalize h : v = x`, but without substitution
meta def let_eq (h : parse ident) (x : parse (tk ":" >> ident)) (v : parse (tk "=" *> texpr))
: tactic unit := do
«have» (some h) (some ``(∃ x, x = %%v)) (some ``(Exists.intro %%v rfl)),
hl ← get_local h,
«destruct» ``(%%hl),
«clear» [h],
«intros» [x, h]
meta def cases_on : parse lean.parser.ident → tactic unit
| id := do
«revert» [id],
«intro» id,
co <- resolve_name (id <.> "cases_on"),
`[apply %%co; intros]
end interactive
open well_founded_tactics
meta def dec_tac_by (try : tactic unit) : tactic unit :=
tactic.abstract (do
clear_internals,
unfold_wf_rel,
process_lex (do
unfold_sizeof,
done <|> (cancel_nat_add_lt >> trivial_nat_lt) <|> try))
end tactic
namespace lib
meta def wf_tacs : well_founded_tactics := {dec_tac := tactic.dec_tac_by `[tidy]}
meta def wf_by (try : tactic unit) : well_founded_tactics := {dec_tac := tactic.dec_tac_by try}
end lib
example (a b : ℕ) : ∃ d, d = a - b := begin
let_eq h : d = a - b,
existsi d,
exact h
end
|
7aaf6c307c7d72f1d14214cce69b42cea2053b44
|
94e33a31faa76775069b071adea97e86e218a8ee
|
/src/topology/sheaves/sheaf_condition/opens_le_cover.lean
|
da501d97c8057a6b836424d344b5a15cbf544d46
|
[
"Apache-2.0"
] |
permissive
|
urkud/mathlib
|
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
|
6379d39e6b5b279df9715f8011369a301b634e41
|
refs/heads/master
| 1,658,425,342,662
| 1,658,078,703,000
| 1,658,078,703,000
| 186,910,338
| 0
| 0
|
Apache-2.0
| 1,568,512,083,000
| 1,557,958,709,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 14,002
|
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 topology.sheaves.presheaf
import category_theory.limits.final
import topology.sheaves.sheaf_condition.pairwise_intersections
/-!
# Another version of the sheaf condition.
Given a family of open sets `U : ι → opens X` we can form the subcategory
`{ V : opens X // ∃ i, V ≤ U i }`, which has `supr U` as a cocone.
The sheaf condition on a presheaf `F` is equivalent to
`F` sending the opposite of this cocone to a limit cone in `C`, for every `U`.
This condition is particularly nice when checking the sheaf condition
because we don't need to do any case bashing
(depending on whether we're looking at single or double intersections,
or equivalently whether we're looking at the first or second object in an equalizer diagram).
## References
* This is the definition Lurie uses in [Spectral Algebraic Geometry][LurieSAG].
-/
universes v u
noncomputable theory
open category_theory
open category_theory.limits
open topological_space
open opposite
open topological_space.opens
namespace Top
variables {C : Type u} [category.{v} C]
variables {X : Top.{v}} (F : presheaf C X) {ι : Type v} (U : ι → opens X)
namespace presheaf
namespace sheaf_condition
/--
The category of open sets contained in some element of the cover.
-/
def opens_le_cover : Type v := { V : opens X // ∃ i, V ≤ U i }
instance [inhabited ι] : inhabited (opens_le_cover U) :=
⟨⟨⊥, default, bot_le⟩⟩
instance : category (opens_le_cover U) := category_theory.full_subcategory _
namespace opens_le_cover
variables {U}
/--
An arbitrarily chosen index such that `V ≤ U i`.
-/
def index (V : opens_le_cover U) : ι := V.property.some
/--
The morphism from `V` to `U i` for some `i`.
-/
def hom_to_index (V : opens_le_cover U) : V.val ⟶ U (index V) :=
(V.property.some_spec).hom
end opens_le_cover
/--
`supr U` as a cocone over the opens sets contained in some element of the cover.
(In fact this is a colimit cocone.)
-/
def opens_le_cover_cocone : cocone (full_subcategory_inclusion _ : opens_le_cover U ⥤ opens X) :=
{ X := supr U,
ι := { app := λ V : opens_le_cover U, V.hom_to_index ≫ opens.le_supr U _, } }
end sheaf_condition
open sheaf_condition
/--
An equivalent formulation of the sheaf condition
(which we prove equivalent to the usual one below as
`is_sheaf_iff_is_sheaf_opens_le_cover`).
A presheaf is a sheaf if `F` sends the cone `(opens_le_cover_cocone U).op` to a limit cone.
(Recall `opens_le_cover_cocone U`, has cone point `supr U`,
mapping down to any `V` which is contained in some `U i`.)
-/
def is_sheaf_opens_le_cover : Prop :=
∀ ⦃ι : Type v⦄ (U : ι → opens X), nonempty (is_limit (F.map_cone (opens_le_cover_cocone U).op))
namespace sheaf_condition
open category_theory.pairwise
/--
Implementation detail:
the object level of `pairwise_to_opens_le_cover : pairwise ι ⥤ opens_le_cover U`
-/
@[simp]
def pairwise_to_opens_le_cover_obj : pairwise ι → opens_le_cover U
| (single i) := ⟨U i, ⟨i, le_rfl⟩⟩
| (pair i j) := ⟨U i ⊓ U j, ⟨i, inf_le_left⟩⟩
open category_theory.pairwise.hom
/--
Implementation detail:
the morphism level of `pairwise_to_opens_le_cover : pairwise ι ⥤ opens_le_cover U`
-/
def pairwise_to_opens_le_cover_map :
Π {V W : pairwise ι},
(V ⟶ W) → (pairwise_to_opens_le_cover_obj U V ⟶ pairwise_to_opens_le_cover_obj U W)
| _ _ (id_single i) := 𝟙 _
| _ _ (id_pair i j) := 𝟙 _
| _ _ (left i j) := hom_of_le inf_le_left
| _ _ (right i j) := hom_of_le inf_le_right
/--
The category of single and double intersections of the `U i` maps into the category
of open sets below some `U i`.
-/
@[simps]
def pairwise_to_opens_le_cover : pairwise ι ⥤ opens_le_cover U :=
{ obj := pairwise_to_opens_le_cover_obj U,
map := λ V W i, pairwise_to_opens_le_cover_map U i, }
instance (V : opens_le_cover U) :
nonempty (structured_arrow V (pairwise_to_opens_le_cover U)) :=
⟨{ right := single (V.index), hom := V.hom_to_index }⟩
/--
The diagram consisting of the `U i` and `U i ⊓ U j` is cofinal in the diagram
of all opens contained in some `U i`.
-/
-- This is a case bash: for each pair of types of objects in `pairwise ι`,
-- we have to explicitly construct a zigzag.
instance : functor.final (pairwise_to_opens_le_cover U) :=
⟨λ V, is_connected_of_zigzag $ λ A B, begin
rcases A with ⟨⟨⟨⟩⟩, ⟨i⟩|⟨i,j⟩, a⟩;
rcases B with ⟨⟨⟨⟩⟩, ⟨i'⟩|⟨i',j'⟩, b⟩;
dsimp at *,
{ refine ⟨[
{ left := ⟨⟨⟩⟩, right := pair i i',
hom := (le_inf a.le b.le).hom, }, _], _, rfl⟩,
exact
list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := left i i', }⟩)
(list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := right i i', }⟩) list.chain.nil) },
{ refine ⟨[
{ left := ⟨⟨⟩⟩, right := pair i' i,
hom := (le_inf (b.le.trans inf_le_left) a.le).hom, },
{ left := ⟨⟨⟩⟩, right := single i',
hom := (b.le.trans inf_le_left).hom, }, _], _, rfl⟩,
exact
list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := right i' i, }⟩)
(list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := left i' i, }⟩)
(list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := left i' j', }⟩) list.chain.nil)) },
{ refine ⟨[
{ left := ⟨⟨⟩⟩, right := single i,
hom := (a.le.trans inf_le_left).hom, },
{ left := ⟨⟨⟩⟩, right := pair i i', hom :=
(le_inf (a.le.trans inf_le_left) b.le).hom, }, _], _, rfl⟩,
exact
list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := left i j, }⟩)
(list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := left i i', }⟩)
(list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := right i i', }⟩) list.chain.nil)) },
{ refine ⟨[
{ left := ⟨⟨⟩⟩, right := single i,
hom := (a.le.trans inf_le_left).hom, },
{ left := ⟨⟨⟩⟩, right := pair i i',
hom := (le_inf (a.le.trans inf_le_left) (b.le.trans inf_le_left)).hom, },
{ left := ⟨⟨⟩⟩, right := single i',
hom := (b.le.trans inf_le_left).hom, }, _], _, rfl⟩,
exact
list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := left i j, }⟩)
(list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := left i i', }⟩)
(list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := right i i', }⟩)
(list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := left i' j', }⟩) list.chain.nil))), },
end⟩
/--
The diagram in `opens X` indexed by pairwise intersections from `U` is isomorphic
(in fact, equal) to the diagram factored through `opens_le_cover U`.
-/
def pairwise_diagram_iso :
pairwise.diagram U ≅
pairwise_to_opens_le_cover U ⋙ full_subcategory_inclusion _ :=
{ hom := { app := begin rintro (i|⟨i,j⟩); exact 𝟙 _, end, },
inv := { app := begin rintro (i|⟨i,j⟩); exact 𝟙 _, end, }, }
/--
The cocone `pairwise.cocone U` with cocone point `supr U` over `pairwise.diagram U` is isomorphic
to the cocone `opens_le_cover_cocone U` (with the same cocone point)
after appropriate whiskering and postcomposition.
-/
def pairwise_cocone_iso :
(pairwise.cocone U).op ≅
(cones.postcompose_equivalence (nat_iso.op (pairwise_diagram_iso U : _) : _)).functor.obj
((opens_le_cover_cocone U).op.whisker (pairwise_to_opens_le_cover U).op) :=
cones.ext (iso.refl _) (by tidy)
end sheaf_condition
open sheaf_condition
/--
The sheaf condition
in terms of a limit diagram over all `{ V : opens X // ∃ i, V ≤ U i }`
is equivalent to the reformulation
in terms of a limit diagram over `U i` and `U i ⊓ U j`.
-/
lemma is_sheaf_opens_le_cover_iff_is_sheaf_pairwise_intersections (F : presheaf C X) :
F.is_sheaf_opens_le_cover ↔ F.is_sheaf_pairwise_intersections :=
forall₂_congr $ λ ι U, equiv.nonempty_congr $
calc is_limit (F.map_cone (opens_le_cover_cocone U).op)
≃ is_limit ((F.map_cone (opens_le_cover_cocone U).op).whisker (pairwise_to_opens_le_cover U).op)
: (functor.initial.is_limit_whisker_equiv (pairwise_to_opens_le_cover U).op _).symm
... ≃ is_limit (F.map_cone ((opens_le_cover_cocone U).op.whisker (pairwise_to_opens_le_cover U).op))
: is_limit.equiv_iso_limit F.map_cone_whisker.symm
... ≃ is_limit ((cones.postcompose_equivalence _).functor.obj
(F.map_cone ((opens_le_cover_cocone U).op.whisker (pairwise_to_opens_le_cover U).op)))
: (is_limit.postcompose_hom_equiv _ _).symm
... ≃ is_limit (F.map_cone ((cones.postcompose_equivalence _).functor.obj
((opens_le_cover_cocone U).op.whisker (pairwise_to_opens_le_cover U).op)))
: is_limit.equiv_iso_limit (functor.map_cone_postcompose_equivalence_functor _).symm
... ≃ is_limit (F.map_cone (pairwise.cocone U).op)
: is_limit.equiv_iso_limit
((cones.functoriality _ _).map_iso (pairwise_cocone_iso U : _).symm)
section
variables {Y : opens X} (hY : Y = supr U)
/-- Given a family of opens `U` and an open `Y` equal to the union of opens in `U`, we may
take the presieve on `Y` associated to `U` and the sieve generated by it, and form the
full subcategory (subposet) of opens contained in `Y` (`over Y`) consisting of arrows
in the sieve. This full subcategory is equivalent to `opens_le_cover U`, the (poset)
category of opens contained in some `U i`. -/
@[simps] def generate_equivalence_opens_le :
{f : over Y // (sieve.generate (presieve_of_covering_aux U Y)).arrows f.hom} ≌
opens_le_cover U :=
{ functor :=
{ obj := λ f, ⟨f.1.left, let ⟨_,h,_,⟨i,hY⟩,_⟩ := f.2 in ⟨i, hY ▸ h.le⟩⟩,
map := λ _ _ g, g.left },
inverse :=
{ obj := λ V, ⟨over.mk (hY.substr (let ⟨i,h⟩ := V.2 in h.trans (le_supr U i))).hom,
let ⟨i,h⟩ := V.2 in ⟨U i, h.hom, (hY.substr (le_supr U i)).hom, ⟨i, rfl⟩, rfl⟩⟩,
map := λ _ _ g, over.hom_mk g },
unit_iso := eq_to_iso $ category_theory.functor.ext
(by {rintro ⟨⟨_,_⟩,_⟩, dsimp, congr; ext}) (by {intros, ext}),
counit_iso := eq_to_iso $ category_theory.functor.hext
(by {intro, ext, refl}) (by {intros, refl}) }
/-- Given a family of opens `opens_le_cover_cocone U` is essentially the natural cocone
associated to the sieve generated by the presieve associated to `U` with indexing
category changed using the above equivalence. -/
@[simps] def whisker_iso_map_generate_cocone :
cone.whisker (generate_equivalence_opens_le U hY).op.functor
(F.map_cone (opens_le_cover_cocone U).op) ≅
F.map_cone (sieve.generate (presieve_of_covering_aux U Y)).arrows.cocone.op :=
{ hom :=
{ hom := F.map (eq_to_hom (congr_arg op hY.symm)),
w' := λ j, by { erw ← F.map_comp, congr } },
inv :=
{ hom := F.map (eq_to_hom (congr_arg op hY)),
w' := λ j, by { erw ← F.map_comp, congr } },
hom_inv_id' := by { ext, simp [eq_to_hom_map], },
inv_hom_id' := by { ext, simp [eq_to_hom_map], } }
/-- Given a presheaf `F` on the topological space `X` and a family of opens `U` of `X`,
the natural cone associated to `F` and `U` used in the definition of
`F.is_sheaf_opens_le_cover` is a limit cone iff the natural cone associated to `F`
and the sieve generated by the presieve associated to `U` is a limit cone. -/
def is_limit_opens_le_equiv_generate₁ :
is_limit (F.map_cone (opens_le_cover_cocone U).op) ≃
is_limit (F.map_cone (sieve.generate (presieve_of_covering_aux U Y)).arrows.cocone.op) :=
(is_limit.whisker_equivalence_equiv (generate_equivalence_opens_le U hY).op).trans
(is_limit.equiv_iso_limit (whisker_iso_map_generate_cocone F U hY))
/-- Given a presheaf `F` on the topological space `X` and a presieve `R` whose generated sieve
is covering for the associated Grothendieck topology (equivalently, the presieve is covering
for the associated pretopology), the natural cone associated to `F` and the family of opens
associated to `R` is a limit cone iff the natural cone associated to `F` and the generated
sieve is a limit cone.
Since only the existence of a 1-1 correspondence will be used, the exact definition does
not matter, so tactics are used liberally. -/
def is_limit_opens_le_equiv_generate₂ (R : presieve Y)
(hR : sieve.generate R ∈ opens.grothendieck_topology X Y) :
is_limit (F.map_cone (opens_le_cover_cocone (covering_of_presieve Y R)).op) ≃
is_limit (F.map_cone (sieve.generate R).arrows.cocone.op) :=
begin
convert is_limit_opens_le_equiv_generate₁ F (covering_of_presieve Y R)
(covering_of_presieve.supr_eq_of_mem_grothendieck Y R hR).symm using 2;
rw covering_presieve_eq_self R,
end
/-- A presheaf `(opens X)ᵒᵖ ⥤ C` on a topological space `X` is a sheaf on the site `opens X` iff
it satisfies the `is_sheaf_opens_le_cover` sheaf condition. The latter is not the
official definition of sheaves on spaces, but has the advantage that it does not
require `has_products C`. -/
lemma is_sheaf_sites_iff_is_sheaf_opens_le_cover :
category_theory.presheaf.is_sheaf (opens.grothendieck_topology X) F ↔ F.is_sheaf_opens_le_cover :=
begin
rw presheaf.is_sheaf_iff_is_limit, split,
{ intros h ι U, rw (is_limit_opens_le_equiv_generate₁ F U rfl).nonempty_congr,
apply h, apply presieve_of_covering.mem_grothendieck_topology },
{ intros h Y S, rw ← sieve.generate_sieve S, intro hS,
rw ← (is_limit_opens_le_equiv_generate₂ F S hS).nonempty_congr, apply h },
end
end
variable [has_products.{v} C]
/--
The sheaf condition in terms of an equalizer diagram is equivalent
to the reformulation in terms of a limit diagram over all `{ V : opens X // ∃ i, V ≤ U i }`.
-/
lemma is_sheaf_iff_is_sheaf_opens_le_cover (F : presheaf C X) :
F.is_sheaf ↔ F.is_sheaf_opens_le_cover :=
iff.trans
(is_sheaf_iff_is_sheaf_pairwise_intersections F)
(is_sheaf_opens_le_cover_iff_is_sheaf_pairwise_intersections F).symm
end presheaf
end Top
|
d87f019ddab3b96ab81a638d3fafd9b442986aac
|
4727251e0cd73359b15b664c3170e5d754078599
|
/src/data/nat/with_bot.lean
|
46172cf2b36479cd779da75b732c49b75e6191ba
|
[
"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
| 2,322
|
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 data.nat.basic
import algebra.order.group
/-!
# `with_bot ℕ`
Lemmas about the type of natural numbers with a bottom element adjoined.
-/
namespace nat
lemma with_bot.add_eq_zero_iff : ∀ {n m : with_bot ℕ}, n + m = 0 ↔ n = 0 ∧ m = 0
| none m := iff_of_false dec_trivial (λ h, absurd h.1 dec_trivial)
| n none := iff_of_false (by cases n; exact dec_trivial)
(λ h, absurd h.2 dec_trivial)
| (some n) (some m) := show (n + m : with_bot ℕ) = (0 : ℕ) ↔ (n : with_bot ℕ) = (0 : ℕ) ∧
(m : with_bot ℕ) = (0 : ℕ),
by rw [← with_bot.coe_add, with_bot.coe_eq_coe, with_bot.coe_eq_coe,
with_bot.coe_eq_coe, add_eq_zero_iff' (nat.zero_le _) (nat.zero_le _)]
lemma with_bot.add_eq_one_iff : ∀ {n m : with_bot ℕ}, n + m = 1 ↔ (n = 0 ∧ m = 1) ∨ (n = 1 ∧ m = 0)
| none none := dec_trivial
| none (some m) := dec_trivial
| (some n) none := iff_of_false dec_trivial (λ h, h.elim (λ h, absurd h.2 dec_trivial)
(λ h, absurd h.2 dec_trivial))
| (some n) (some 0) := by erw [with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe,
with_bot.coe_eq_coe]; simp
| (some n) (some (m + 1)) := by erw [with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe,
with_bot.coe_eq_coe, with_bot.coe_eq_coe]; simp [nat.add_succ, nat.succ_inj', nat.succ_ne_zero]
@[simp] lemma with_bot.coe_nonneg {n : ℕ} : 0 ≤ (n : with_bot ℕ) :=
by rw [← with_bot.coe_zero, with_bot.coe_le_coe]; exact nat.zero_le _
@[simp] lemma with_bot.lt_zero_iff (n : with_bot ℕ) : n < 0 ↔ n = ⊥ :=
option.cases_on n dec_trivial (λ n, iff_of_false
(by simp [with_bot.some_eq_coe]) (λ h, option.no_confusion h))
lemma with_bot.one_le_iff_zero_lt {x : with_bot ℕ} : 1 ≤ x ↔ 0 < x :=
begin
refine ⟨λ h, lt_of_lt_of_le (with_bot.coe_lt_coe.mpr zero_lt_one) h, λ h, _⟩,
induction x using with_bot.rec_bot_coe,
{ exact (not_lt_bot h).elim },
{ exact with_bot.coe_le_coe.mpr (nat.succ_le_iff.mpr (with_bot.coe_lt_coe.mp h)) }
end
lemma with_bot.lt_one_iff_le_zero {x : with_bot ℕ} : x < 1 ↔ x ≤ 0 :=
not_iff_not.mp (by simpa using with_bot.one_le_iff_zero_lt)
end nat
|
22068464aea3e5fde22bba66d6c5346ef6755e6b
|
cf39355caa609c0f33405126beee2739aa3cb77e
|
/tests/lean/run/do_match_else.lean
|
be8e843a34b8f22a96df6529cf9983eab18c90a6
|
[
"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
| 571
|
lean
|
open tactic
set_option pp.all true
meta def app2 (f a b : expr) :=
expr.app (expr.app f a) b
example (a b c x y : nat) (H : nat.add (nat.add x y) y = 0) : true :=
by do
a ← get_local `a, b ← get_local `b, c ← get_local `c,
H ← get_local `H >>= infer_type,
(lhs, rhs) ← match_eq H,
nat_add : expr ← mk_const `nat.add,
p : pattern ← mk_pattern [] [a, b] (app2 nat_add a b) [] [app2 nat_add b a, a, b],
trace (pattern.moutput p),
(_, [v₁, v₂, v₃]) ← match_pattern p lhs | failed,
trace v₁, trace v₂, trace v₃,
constructor
|
e1e8bdf7cbd8cbeaa3a4d1d6bbb3e03811b35ad8
|
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
|
/tests/lean/run/frontend1.lean
|
3ab4afc61ba8adaa14b451c7c75cb25d5d225154
|
[
"Apache-2.0"
] |
permissive
|
mhuisi/lean4
|
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
|
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
|
refs/heads/master
| 1,621,225,489,283
| 1,585,142,689,000
| 1,585,142,689,000
| 250,590,438
| 0
| 2
|
Apache-2.0
| 1,602,443,220,000
| 1,585,327,814,000
|
C
|
UTF-8
|
Lean
| false
| false
| 7,310
|
lean
|
import Init.Lean.Elab
open Lean
open Lean.Elab
def run (input : String) (failIff : Bool := true) : MetaIO Unit :=
do env ← MetaIO.getEnv;
opts ← MetaIO.getOptions;
(env, messages) ← liftM $ process input env opts;
messages.forM $ fun msg => IO.println msg;
when (failIff && messages.hasErrors) $ throw (IO.userError "errors have been found");
when (!failIff && !messages.hasErrors) $ throw (IO.userError "there are no errors");
pure ()
def fail (input : String) : MetaIO Unit :=
run input false
def M := IO Unit
def zero := 0
def one := 1
def two := 2
def hello : String := "hello"
def act1 : IO String :=
pure "hello"
#eval run "#check @HasAdd.add"
#eval run "#check [zero, one, two]"
#eval run "#check id $ Nat.succ one"
#eval run "#check HasAdd.add one two"
#eval run "#check one + two > one ∧ True"
#eval run "#check act1 >>= IO.println"
#eval run "#check one + two == one"
#eval fail "#check one + one + hello == hello ++ one"
#eval run "#check Nat.add one $ Nat.add one two"
#eval run
"universe u universe v
export HasToString (toString)
section namespace foo.bla end bla end foo
variable (p q : Prop)
variable (_ b : _)
variable {α : Type}
variable {m : Type → Type}
variable [Monad m]
#check m
#check Type
#check Prop
#check toString zero
#check id Nat.zero (α := Nat)
#check id _ (α := Nat)
#check id Nat.zero
#check id (α := Nat)
#check @id Nat
#check p
#check α
#check Nat.succ
#check Nat.add
#check id
#check forall (α : Type), α → α
#check (α : Type) → α → α
#check {α : Type} → {β : Type} → M → (α → β) → α → β
#check ()
#check _root_.run
end"
structure S1 :=
(x y : Nat := 0)
structure S2 extends S1 :=
(z : Nat := 0)
def fD {α} [HasToString α] (a b : α) : String :=
toString a ++ toString b
structure S3 :=
(w : Nat := 0)
(f : forall {α : Type} [HasToString α], α → α → String := @fD)
structure S4 extends S2, S3 :=
(s : Nat := 0)
def s4 : S4 := {}
structure S (α : Type) :=
(field1 : S4 := {})
(field2 : S4 × S4 := ({}, {}))
(field3 : α)
(field4 : List α × Nat := ([], 0))
(vec : Array (α × α) := #[])
(map : HashMap String α := {})
inductive D (α : Type)
| mk (a : α) (s : S4) : D
def s : S Nat := { field3 := 0 }
def d : D Nat := D.mk 10 {}
def i : Nat := 10
def k : String := "hello"
universes u
class Monoid (α : Type u) :=
(one {} : α)
(mul : α → α → α)
def m : Monoid Nat :=
{ one := 1, mul := Nat.mul }
def f (x y z : Nat) : Nat :=
x + y + z
#eval run "#check s4.x"
#eval run "#check s.field1.x"
#eval run "#check s.field2.fst"
#eval run "#check s.field2.fst.w"
#eval run "#check s.1.x"
#eval run "#check s.2.1.x"
#eval run "#check d.1"
#eval run "#check d.2.x"
#eval run "#check s4.f s4.x"
#eval run "#check m.mul m.one"
#eval run "#check s.field4.1.length.succ"
#eval run "#check s.field4.1.map Nat.succ"
#eval run "#check s.vec[i].1"
#eval run "#check \"hello\""
#eval run "#check 1"
#eval run "#check Nat.succ 1"
#eval run "#check fun _ a (x y : Int) => x + y + a"
#eval run "#check (one)"
#eval run "#check ()"
#eval run "#check (one, two, zero)"
#eval run "#check (one, two, zero)"
#eval run "#check (1 : Int)"
#eval run "#check ((1, 2) : Nat × Int)"
#eval run "#check (· + one)"
#eval run "#check (· + · : Nat → Nat → Nat)"
#eval run "#check (f one · zero)"
#eval run "#check (f · · zero)"
#eval run "#check fun (_ b : Nat) => b + 1"
def foo {α β} (a : α) (b : β) (a' : α) : α :=
a
def bla {α β} (f : α → β) (a : α) : β :=
f a
-- #check fun x => foo x x.w s4 -- fails in old elaborator
-- #check bla (fun x => x.w) s4 -- fails in the old elaborator
-- #check #[1, 2, 3].foldl (fun r a => r.push a) #[] -- fails in the old elaborator
#eval run "#check fun x => foo x x.w s4"
#eval run "#check bla (fun x => x.w) s4"
#eval run "#check #[1, 2, 3].foldl (fun r a => r.push a) #[]"
#eval run "#check #[1, 2, 3].foldl (fun r a => (r.push a).push a) #[]"
#eval run "#check #[1, 2, 3].foldl (fun r a => ((r.push a).push a).push a) #[]"
#eval run "#check #[].push one $.push two $.push zero $.size.succ"
#eval run "#check #[1, 2].foldl (fun r a => r.push a $.push a $.push a) #[]"
#eval run "#check #[1, 2].foldl (init := #[]) $ fun r a => r.push a $.push a"
#eval run "#check let x := one + zero; x + x"
-- set_option trace.Elab true
#eval run "#check (fun x => let v := x.w; v + v) s4"
#eval run "#check fun x => foo x (let v := x.w; v + one) s4"
#eval run "#check fun x => foo x (let v := x.w; let w := x.x; v + w + one) s4"
#eval fail "#check id.{1,1}"
#eval fail "#check @id.{0} Nat"
#eval run "#check @id.{1} Nat"
#eval run "universes u #check id.{u}"
#eval fail "universes u #check id.{v}"
#eval run "universes u #check Type u"
#eval run "universes u #check Sort u"
#eval run "#check Type 1"
#eval run "#check Type 0"
#eval run "universes u v #check Sort (max u v)"
#eval run "universes u v #check Type (max u v)"
#eval run "#check 'a'"
#eval fail "#check #['a', \"hello\"]"
#eval run "#check fun (a : Array Nat) => a.size"
#eval run "#check if 0 = 1 then 'a' else 'b'"
#eval run "#check fun (i : Nat) (a : Array Nat) => if h : i < a.size then a.get (Fin.mk i h) else i"
#eval run "#check { x : Nat // x > 0 }"
#eval run "#check { x // x > 0 }"
#eval run "#check fun (i : Nat) (a : Array Nat) => if h : i < a.size then a.get ⟨i, h⟩ else i"
#eval run "#check Prod.fst ⟨1, 2⟩"
#eval run "#check let x := ⟨1, 2⟩; Prod.fst x"
#eval run "#check show Nat from 1"
#eval run "#check show Int from 1"
#eval run "#check have Nat from one + zero; this + this"
#eval run "#check have x : Nat from one + zero; x + x"
#eval run "#check have Nat := one + zero; this + this"
#eval run "#check have x : Nat := one + zero; x + x"
#eval run "#check x + y where x := 1; where y := x + x"
#eval run "#check let z := 2; x + y where x := z + 1; where y := x + x"
#eval run "variables {α β} axiom x (n : Nat) : α → α #check x 1 0"
#eval run "#check HasToString.toString 0"
#eval run "@[instance] axiom newInst : HasToString Nat #check newInst #check HasToString.toString 0"
#eval run "variables {β σ} universes w1 w2 /-- Testing axiom -/ unsafe axiom Nat.aux.{u, v} (γ : Type w1) (v : Nat) : β → (α : Type _) → v = zero /- Nat.zero -/ → Array α #check @Nat.aux"
#eval run "def x : Nat := Nat.zero #check x"
#eval run "def x := Nat.zero #check x"
#eval run "open Lean.Parser def x := parser! symbol \"foo\" 10 #check x"
#eval run "open Lean.Parser def x := tparser! symbol \"foo\" 0 #check x"
#eval run "def x : Nat := 1 #check x"
def g (x : Nat := zero) (y : Nat := one) (z : Nat := two) : Nat :=
x + y + z
def three := 3
#eval run "#check g"
#eval run "#check g (x := three) (z := zero)"
#eval run "#check g (y := three)"
#eval run "#check g (z := three)"
#eval run "#check g three (z := zero)"
#eval run "open Lean.Parser
@[termParser] def myParser : Lean.Parser.Parser := parser! oldCoe \"hi\"
#check myParser"
#eval run "#check (fun stx => if True then let e := stx; HasPure.pure e else HasPure.pure stx : Nat → Id Nat)"
#eval run "constant n : Nat #check n"
#eval fail "#check Nat.succ 'a'"
#eval run "universes u v #check Type (max u v)"
#eval run "universes u v #check Type (imax u v)"
#eval fail "namespace Boo def f (x : Nat) := x def s := 'a' #check (fun x => f x) s end Boo"
|
3153563a51fdee5b2b1ed563bba2a8b4042dd1cc
|
74addaa0e41490cbaf2abd313a764c96df57b05d
|
/Mathlib/algebra/lie/universal_enveloping_auto.lean
|
bad252c330a1526cc745b92305054eaeb3101bc5
|
[] |
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
| 5,640
|
lean
|
/-
Copyright (c) 2020 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.lie.basic
import Mathlib.algebra.ring_quot
import Mathlib.linear_algebra.tensor_algebra
import Mathlib.PostPort
universes u₁ u₂ u₃
namespace Mathlib
/-!
# Universal enveloping algebra
Given a commutative ring `R` and a Lie algebra `L` over `R`, we construct the universal
enveloping algebra of `L`, together with its universal property.
## Main definitions
* `universal_enveloping_algebra`: the universal enveloping algebra, endowed with an
`R`-algebra structure.
* `universal_enveloping_algebra.ι`: the Lie algebra morphism from `L` to its universal
enveloping algebra.
* `universal_enveloping_algebra.lift`: given an associative algebra `A`, together with a Lie
algebra morphism `f : L →ₗ⁅R⁆ A`, `lift R L f : universal_enveloping_algebra R L →ₐ[R] A` is the
unique morphism of algebras through which `f` factors.
* `universal_enveloping_algebra.ι_comp_lift`: states that the lift of a morphism is indeed part
of a factorisation.
* `universal_enveloping_algebra.lift_unique`: states that lifts of morphisms are indeed unique.
* `universal_enveloping_algebra.hom_ext`: a restatement of `lift_unique` as an extensionality
lemma.
## Tags
lie algebra, universal enveloping algebra, tensor algebra
-/
namespace universal_enveloping_algebra
/-- The quotient by the ideal generated by this relation is the universal enveloping algebra.
Note that we have avoided using the more natural expression:
| lie_compat (x y : L) : rel (ιₜ ⁅x, y⁆) ⁅ιₜ x, ιₜ y⁆
so that our construction needs only the semiring structure of the tensor algebra. -/
inductive rel (R : Type u₁) (L : Type u₂) [comm_ring R] [lie_ring L] [lie_algebra R L] :
tensor_algebra R L → tensor_algebra R L → Prop
where
| lie_compat :
∀ (x y : L),
rel R L
(coe_fn (tensor_algebra.ι R) (has_bracket.bracket x y) +
coe_fn (tensor_algebra.ι R) y * coe_fn (tensor_algebra.ι R) x)
(coe_fn (tensor_algebra.ι R) x * coe_fn (tensor_algebra.ι R) y)
end universal_enveloping_algebra
/-- The universal enveloping algebra of a Lie algebra. -/
def universal_enveloping_algebra (R : Type u₁) (L : Type u₂) [comm_ring R] [lie_ring L]
[lie_algebra R L] :=
ring_quot sorry
namespace universal_enveloping_algebra
/-- The quotient map from the tensor algebra to the universal enveloping algebra as a morphism of
associative algebras. -/
def mk_alg_hom (R : Type u₁) (L : Type u₂) [comm_ring R] [lie_ring L] [lie_algebra R L] :
alg_hom R (tensor_algebra R L) (universal_enveloping_algebra R L) :=
ring_quot.mk_alg_hom R (rel R L)
/-- The natural Lie algebra morphism from a Lie algebra to its universal enveloping algebra. -/
def ι (R : Type u₁) {L : Type u₂} [comm_ring R] [lie_ring L] [lie_algebra R L] :
lie_algebra.morphism R L (universal_enveloping_algebra R L) :=
lie_algebra.morphism.mk
(linear_map.to_fun
(linear_map.comp (alg_hom.to_linear_map (mk_alg_hom R L)) (tensor_algebra.ι R)))
sorry sorry sorry
/-- The universal property of the universal enveloping algebra: Lie algebra morphisms into
associative algebras lift to associative algebra morphisms from the universal enveloping algebra. -/
def lift (R : Type u₁) {L : Type u₂} [comm_ring R] [lie_ring L] [lie_algebra R L] {A : Type u₃}
[ring A] [algebra R A] :
lie_algebra.morphism R L A ≃ alg_hom R (universal_enveloping_algebra R L) A :=
equiv.mk
(fun (f : lie_algebra.morphism R L A) =>
coe_fn (ring_quot.lift_alg_hom R)
{ val := coe_fn (tensor_algebra.lift R) ↑f, property := sorry })
(fun (F : alg_hom R (universal_enveloping_algebra R L) A) =>
lie_algebra.morphism.comp (lie_algebra.of_associative_algebra_hom F) (ι R))
sorry sorry
@[simp] theorem lift_symm_apply (R : Type u₁) {L : Type u₂} [comm_ring R] [lie_ring L]
[lie_algebra R L] {A : Type u₃} [ring A] [algebra R A]
(F : alg_hom R (universal_enveloping_algebra R L) A) :
coe_fn (equiv.symm (lift R)) F =
lie_algebra.morphism.comp (lie_algebra.of_associative_algebra_hom F) (ι R) :=
rfl
@[simp] theorem ι_comp_lift (R : Type u₁) {L : Type u₂} [comm_ring R] [lie_ring L] [lie_algebra R L]
{A : Type u₃} [ring A] [algebra R A] (f : lie_algebra.morphism R L A) :
⇑(coe_fn (lift R) f) ∘ ⇑(ι R) = ⇑f :=
funext (iff.mp lie_algebra.morphism.ext_iff (equiv.symm_apply_apply (lift R) f))
@[simp] theorem lift_ι_apply (R : Type u₁) {L : Type u₂} [comm_ring R] [lie_ring L]
[lie_algebra R L] {A : Type u₃} [ring A] [algebra R A] (f : lie_algebra.morphism R L A)
(x : L) : coe_fn (coe_fn (lift R) f) (coe_fn (ι R) x) = coe_fn f x :=
sorry
theorem lift_unique (R : Type u₁) {L : Type u₂} [comm_ring R] [lie_ring L] [lie_algebra R L]
{A : Type u₃} [ring A] [algebra R A] (f : lie_algebra.morphism R L A)
(g : alg_hom R (universal_enveloping_algebra R L) A) :
⇑g ∘ ⇑(ι R) = ⇑f ↔ g = coe_fn (lift R) f :=
sorry
/-- See note [partially-applied ext lemmas]. -/
theorem hom_ext (R : Type u₁) {L : Type u₂} [comm_ring R] [lie_ring L] [lie_algebra R L]
{A : Type u₃} [ring A] [algebra R A] {g₁ : alg_hom R (universal_enveloping_algebra R L) A}
{g₂ : alg_hom R (universal_enveloping_algebra R L) A} (h : ⇑g₁ ∘ ⇑(ι R) = ⇑g₂ ∘ ⇑(ι R)) :
g₁ = g₂ :=
sorry
end Mathlib
|
4e4716b52cd39d719bb6d7266f9b85451bf8c5e9
|
40ad357bbd0d327dd1e3e7f7beb868bd4e5b0a9d
|
/src/temporal_logic/fairness.lean
|
1dca9a52d2c7f4a3ece3fa55bf2947a682e6bf78
|
[] |
no_license
|
unitb/temporal-logic
|
9966424f015976d5997a9ffa30cbd77cc3a9cb1c
|
accec04d1b09ca841be065511c9e206b725b16e9
|
refs/heads/master
| 1,633,868,382,769
| 1,541,072,223,000
| 1,541,072,223,000
| 114,790,987
| 5
| 3
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 5,476
|
lean
|
-- import temporal_logic.tactic
import temporal_logic.lemmas
universes u u₀ u₁
open predicate temporal
namespace temporal
namespace fairness
section defs
variables p q A : cpred
def wf : cpred :=
◇◻p ⟶ ◻◇A
def sf : cpred :=
◻◇p ⟶ ◻◇A
def sched : cpred :=
◇◻p ⟶ ◻◇q ⟶ ◻◇(p ⋀ q ⋀ A)
instance persistent_sched : persistent (sched p q A) :=
by { unfold sched, apply_instance }
end defs
lemma sched_imp_sched {Γ p q A A' : cpred}
(hA : Γ ⊢ ◻(A ⟶ A'))
: Γ ⊢ sched p q A ⟶ sched p q A' :=
begin [temporal]
dsimp [sched],
mono*, apply hA,
end
-- TODO(Simon) replace ~> with ◻◇_ ⟶ ◻◇_
structure one_to_one_po (S p q A p' q' A' : cpred) : Prop :=
(delay : S ⟹ (p' ⋀ q' ~> p))
(resched : S ⟹ (p' ⋀ q' ~> q))
(stable : S ⟹ (◻◇p ⟶ ◇◻p' ⟶ ◇◻p))
(sim : S ⟹ ◻(p ⟶ q ⟶ A ⟶ p' ⋀ q' ⋀ A'))
structure event (α : Type u₀) :=
(p q : pred' α) (A : act α)
def one_to_one_po' {α β} (S : cpred)
: event α → event β → tvar α → tvar β → Prop
| ⟨p₀,q₀,A₀⟩ ⟨p₁,q₁,A₁⟩ v w :=
one_to_one_po S
(p₀!v) (q₀!v) ⟦ v | A₀ ⟧
(p₁!w) (q₁!w) ⟦ w | A₁ ⟧
namespace one_to_one
section one_to_one
parameters {S p q A : cpred}
parameters {p' q' A' : cpred}
parameters po : one_to_one_po S p q A p' q' A'
parameters Γ : cpred
parameters hS : Γ ⊢ S
private def H₀ : Γ ⊢ p' ⋀ q' ~> p :=
po.delay Γ hS
private def H₁ : Γ ⊢ ◻◇p ⟶ ◇◻p' ⟶ ◇◻p :=
po.stable Γ hS
private def H₂ : Γ ⊢ ◻(p ⟶ q ⟶ A ⟶ p' ⋀ q' ⋀ A') :=
po.sim Γ hS
private def H₃ : Γ ⊢ p' ⋀ q' ~> q :=
po.resched Γ hS
include po hS
lemma replacement
: Γ ⊢ sched p q A ⟶ sched p' q' A' :=
begin [temporal]
simp [sched], intros,
have swc := coincidence a_1 a_2,
have wc : ◇◻p,
{ assume_negation, simp at h,
have H₁ := H₁ po Γ hS,
have H₀ := H₀ po Γ hS,
apply H₁ _ a_1,
apply inf_often_of_leads_to H₀ swc, },
have sc : ◻◇q,
{ have H₃ := H₃ po Γ hS,
apply inf_often_of_leads_to H₃ swc, },
replace a := a wc sc, revert a,
{ have H₂ := H₂ po Γ hS,
intros H₃, replace H₃ := coincidence wc H₃,
henceforth! at H₃ ⊢, eventually H₃ ⊢,
casesm* _ ⋀ _,
apply H₂ ; assumption, },
end
end one_to_one
end one_to_one
export one_to_one (replacement)
namespace splitting
section splitting
parameters (t : Sort u)
-- TODO(Simon) Weaken proof obligation `H₀`. We can do with ◻◇_ ⟶ ◻◇ _
-- instead of _ ~> _. Use w i unless -p'
structure many_to_many_po (S : cpred) (w p q A : t → cpred) (p' q' A' : cpred) : Prop :=
(delay : S ⟹ ∀∀ i, p' ⋀ q' ⋀ w i ~> p i ⋀ q i ⋀ w i)
(stable : S ⟹ ∀∀ i, ◇(p i ⋀ w i) ⟶ ◇◻p' ⟶ ◇◻(p i ⋀ w i))
(wfis : S ⟹ ◻(p' ⋀ q' ⟶ ∃∃ i, w i))
(sim : S ⟹ ∀∀ i, ◻(p i ⟶ q i ⟶ A i ⟶ p' ⋀ q' ⋀ A'))
def many_to_many_po' {α β} (S : cpred) (w : t → cpred)
: (t → event α) → event β → tvar α → tvar β → Prop
| e ⟨p₁,q₁,A₁⟩ cv av :=
many_to_many_po S w
(λ i, (e i).p!cv) (λ i, (e i).q!cv) (λ i, ⟦ cv | (e i).A ⟧)
(p₁!av) (q₁!av) ⟦ av | A₁ ⟧
parameters {t}
parameters {w p q A : t → cpred}
parameters {p' q' A' S : cpred}
parameters po : many_to_many_po S w p q A p' q' A'
parameters {Γ : cpred}
parameters hS : Γ ⊢ S
-- variables H₀ : Γ ⊢ ∀∀ i, ◻◇(p' ⋀ q' ⋀ w i) ⟶ ◻◇p i ⋀ q i ⋀ w i
def H₀ : Γ ⊢ ∀∀ i, p' ⋀ q' ⋀ w i ~> p i ⋀ q i ⋀ w i :=
po.delay Γ hS
def H₁ : Γ ⊢ ∀∀ i, ◇(p i ⋀ w i) ⟶ ◇◻p' ⟶ ◇◻(p i ⋀ w i) :=
po.stable Γ hS
def H₂ : Γ ⊢ ∀∀ i, ◻(p i ⟶ q i ⟶ A i ⟶ p' ⋀ q' ⋀ A') :=
po.sim Γ hS
def H₃ : Γ ⊢ ◻(p' ⋀ q' ⟶ ∃∃ i, w i) :=
po.wfis Γ hS
include hS po H₀ H₁ H₂ H₃
open temporal
lemma splitting
: Γ ⊢ (∀∀ i, sched (p i) (q i) (A i)) ⟶ sched p' q' A' :=
begin [temporal]
intro H₅,
simp [sched] at *, intros hp' hq',
have H₇ := temporal.leads_to_disj_gen temporal.fairness.splitting.H₀,
replace H₇ := inf_often_of_leads_to H₇ _,
replace H₇ : ∃∃ (i : t), ◇(p i ⋀ q i ⋀ w i),
{ henceforth at H₇, rw eventually_exists at H₇, },
{ cases H₇ with i H₇,
have H₉ := temporal.fairness.splitting.H₁ i _ hp',
have : ◻◇q i,
{ have := inf_often_of_leads_to (temporal.fairness.splitting.H₀ i) _, revert this,
{ mono!*, lifted_pred, show _, { intros, assumption } },
rw_using : (p' ⋀ q' ⋀ w i) = (p' ⋀ w i ⋀ q'),
{ lifted_pred, tauto },
apply coincidence _ hq',
{ apply stable_and_of_stable_of_stable hp',
revert H₉, mono! * }, },
replace this := H₅ i _ this,
{ have H₂ := temporal.fairness.splitting.H₂ i,
replace this := coincidence H₉ this,
henceforth! at this ⊢, eventually this ⊢,
casesm* _ ⋀ _, apply H₂ ; assumption },
{ revert H₉, mono!, lifted_pred,
show _, { intros, assumption } },
{ revert H₇, mono!, lifted_pred }, },
{ have := coincidence hp' hq', revert this,
have H₃ := temporal.fairness.splitting.H₃,
mono!,
intros hp,
have := H₃ hp,
revert this, apply p_exists_p_imp_p_exists,
tauto, } ,
end
end splitting
end splitting
export splitting (splitting many_to_many_po many_to_many_po')
end fairness
end temporal
|
851254f4f7870e6d4694a84d5b641d87a0f0d46a
|
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
|
/tests/lean/whnf_core1.lean
|
8ab3497314dc39f09beffbcca3988feebaf88850
|
[
"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
| 327
|
lean
|
open tactic
definition f (a : nat) := a + 2
attribute [reducible]
definition g (a : nat) := a + 2
example (a : nat) : true :=
by do
to_expr `(f a) >>= whnf >>= trace,
to_expr `(g a) >>= whnf >>= trace,
to_expr `(f a) >>= whnf_core reducible >>= trace,
to_expr `(g a) >>= whnf_core reducible >>= trace,
constructor
|
d6438513888d0811ca99701b76ff196da861cec3
|
13d50f9487a2afddb5e1ae1bbe68f7870f70e79a
|
/ExportParser.lean
|
4a5772fa02384f80257f706b56569dede79987fd
|
[] |
no_license
|
gebner/lean4-mathlib-import
|
09a09d9cc30738bcc253e919ab3485e13b8f992d
|
719c0558dfa9c4ec201aa40f4786d5f1c1e4bd1e
|
refs/heads/master
| 1,649,553,984,859
| 1,584,121,837,000
| 1,584,121,837,000
| 238,557,672
| 4
| 1
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 4,053
|
lean
|
-- new_frontend
import Init.Lean
open Lean
namespace Array
partial def write {α} [Inhabited α] : ∀ (arr : Array α) (i : Nat) (x : α), Array α
| arr, i, x =>
if i = arr.size then
arr.push x
else if i > arr.size then
write (arr.push (Inhabited.default _)) i x
else
arr.set! i x
end Array
namespace List
def splitAt {α} (xs : List α) (i : Nat) : List α × List α :=
(xs.take i, xs.drop i)
end List
structure ExportParserState :=
(names : Array Name)
(levels : Array Level)
(exprs : Array Expr)
(decls : Array Declaration)
namespace ExportParserState
def initial : ExportParserState := {
names := #[Name.anonymous],
levels := #[levelZero],
exprs := #[],
decls := #[],
}
instance : Inhabited ExportParserState := ⟨initial⟩
def getExpr! (s : ExportParserState) (i : Nat) : Expr :=
s.exprs.get! i
def getLevel! (s : ExportParserState) (i : Nat) : Level :=
s.levels.get! i
def getName! (s : ExportParserState) (i : Nat) : Name :=
s.names.get! i
def parseBinderInfo : String → BinderInfo
| "#BD" => BinderInfo.default
| "#BI" => BinderInfo.implicit
| "#BS" => BinderInfo.strictImplicit
| "#BC" => BinderInfo.instImplicit
| _ => BinderInfo.default
def parseIntros (s : ExportParserState) : List String → List Constructor
| (n :: t :: is) => { name := s.getName! n.toNat, type := s.getExpr! t.toNat } :: parseIntros is
| _ => []
def processLine (s : ExportParserState) (l : String) : ExportParserState :=
match l.splitOn " " with
| (i :: "#NS" :: j :: rest) =>
{ names := s.names.write i.toNat (mkNameStr (s.getName! j.toNat) (" ".intercalate rest)), ..s}
| [i, "#NI", j, k] =>
{ names := s.names.write i.toNat (mkNameNum (s.getName! j.toNat) k.toNat), ..s}
| [i, "#US", j] =>
{ levels := s.levels.write i.toNat (mkLevelSucc (s.getLevel! j.toNat)), ..s }
| [i, "#UM", j1, j2] =>
{ levels := s.levels.write i.toNat (mkLevelMax (s.getLevel! j1.toNat) (s.getLevel! j2.toNat)), ..s }
| [i, "#UIM", j1, j2] =>
{ levels := s.levels.write i.toNat (mkLevelIMax (s.getLevel! j1.toNat) (s.getLevel! j2.toNat)), ..s }
| [i, "#UP", j] =>
{ levels := s.levels.write i.toNat (mkLevelParam (s.getName! j.toNat)), ..s }
| [i, "#EV", j] =>
{ exprs := s.exprs.write i.toNat (mkBVar j.toNat), ..s }
| [i, "#ES", j] =>
{ exprs := s.exprs.write i.toNat (mkSort (s.getLevel! j.toNat)), ..s }
| (i :: "#EC" :: j :: us) =>
{ exprs := s.exprs.write i.toNat (mkConst (s.getName! j.toNat) (us.map (fun u => s.getLevel! u.toNat))), ..s }
| [i, "#EA", j1, j2] =>
{ exprs := s.exprs.write i.toNat (mkApp (s.getExpr! j1.toNat) (s.getExpr! j2.toNat)), ..s }
| [i, "#EL", bi, j1, j2, j3] =>
{ exprs := s.exprs.write i.toNat (mkLambda (s.getName! j1.toNat) (parseBinderInfo bi) (s.getExpr! j2.toNat) (s.getExpr! j3.toNat)), ..s }
| [i, "#EP", bi, j1, j2, j3] =>
{ exprs := s.exprs.write i.toNat (mkForall (s.getName! j1.toNat) (parseBinderInfo bi) (s.getExpr! j2.toNat) (s.getExpr! j3.toNat)), ..s }
| [i, "#EZ", j1, j2, j3, j4] =>
{ exprs := s.exprs.write i.toNat (mkLet (s.getName! j1.toNat) (s.getExpr! j2.toNat) (s.getExpr! j3.toNat) (s.getExpr! j4.toNat)), ..s }
| ("#AX" :: n :: t :: ups) =>
{ decls := s.decls.push (Declaration.axiomDecl {
name := s.getName! n.toNat,
lparams := ups.map (fun up => s.getName! up.toNat),
type := s.getExpr! t.toNat,
isUnsafe := false,
}), ..s }
| ("#DEF" :: n :: t :: v :: ups) =>
{ decls := s.decls.push (Declaration.defnDecl {
name := s.getName! n.toNat,
lparams := ups.map (fun up => s.getName! up.toNat),
type := s.getExpr! t.toNat,
value := s.getExpr! v.toNat,
isUnsafe := false,
hints := ReducibilityHints.regular 0,
}), ..s }
| ("#IND" :: nps :: n :: t :: nis :: rest) =>
let (is, ups) := rest.splitAt (2 * nis.toNat);
let lparams := ups.map (fun up => s.getName! up.toNat);
{ decls := s.decls.push (Declaration.inductDecl lparams nps.toNat [{
name := s.getName! n.toNat,
type := s.getExpr! t.toNat,
ctors := s.parseIntros is,
}] false), ..s }
| _ => s
end ExportParserState
|
cb216d509eaef32f8ad079bb218c677b434a9af8
|
4727251e0cd73359b15b664c3170e5d754078599
|
/src/algebra/group/commute.lean
|
aea715cf91e11dc9eac7ce720d281e5c7a73f76b
|
[
"Apache-2.0"
] |
permissive
|
Vierkantor/mathlib
|
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
|
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
|
refs/heads/master
| 1,658,323,012,449
| 1,652,256,003,000
| 1,652,256,003,000
| 209,296,341
| 0
| 1
|
Apache-2.0
| 1,568,807,655,000
| 1,568,807,655,000
| null |
UTF-8
|
Lean
| false
| false
| 7,599
|
lean
|
/-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Neil Strickland, Yury Kudryashov
-/
import algebra.group.semiconj
/-!
# Commuting pairs of elements in monoids
We define the predicate `commute a b := a * b = b * a` and provide some operations on terms `(h :
commute a b)`. E.g., if `a`, `b`, and c are elements of a semiring, and that `hb : commute a b` and
`hc : commute a c`. Then `hb.pow_left 5` proves `commute (a ^ 5) b` and `(hb.pow_right 2).add_right
(hb.mul_right hc)` proves `commute a (b ^ 2 + b * c)`.
Lean does not immediately recognise these terms as equations, so for rewriting we need syntax like
`rw [(hb.pow_left 5).eq]` rather than just `rw [hb.pow_left 5]`.
This file defines only a few operations (`mul_left`, `inv_right`, etc). Other operations
(`pow_right`, field inverse etc) are in the files that define corresponding notions.
## Implementation details
Most of the proofs come from the properties of `semiconj_by`.
-/
/-- Two elements commute if `a * b = b * a`. -/
@[to_additive add_commute "Two elements additively commute if `a + b = b + a`"]
def commute {S : Type*} [has_mul S] (a b : S) : Prop := semiconj_by a b b
namespace commute
section has_mul
variables {S : Type*} [has_mul S]
/-- Equality behind `commute a b`; useful for rewriting. -/
@[to_additive "Equality behind `add_commute a b`; useful for rewriting."]
protected lemma eq {a b : S} (h : commute a b) : a * b = b * a := h
/-- Any element commutes with itself. -/
@[refl, simp, to_additive "Any element commutes with itself."]
protected lemma refl (a : S) : commute a a := eq.refl (a * a)
/-- If `a` commutes with `b`, then `b` commutes with `a`. -/
@[symm, to_additive "If `a` commutes with `b`, then `b` commutes with `a`."]
protected lemma symm {a b : S} (h : commute a b) : commute b a := eq.symm h
@[to_additive] protected theorem semiconj_by {a b : S} (h : commute a b) : semiconj_by a b b := h
@[to_additive]
protected theorem symm_iff {a b : S} : commute a b ↔ commute b a :=
⟨commute.symm, commute.symm⟩
end has_mul
section semigroup
variables {S : Type*} [semigroup S] {a b c : S}
/-- If `a` commutes with both `b` and `c`, then it commutes with their product. -/
@[simp, to_additive "If `a` commutes with both `b` and `c`, then it commutes with their sum."]
lemma mul_right (hab : commute a b) (hac : commute a c) : commute a (b * c) := hab.mul_right hac
/-- If both `a` and `b` commute with `c`, then their product commutes with `c`. -/
@[simp, to_additive "If both `a` and `b` commute with `c`, then their product commutes with `c`."]
lemma mul_left (hac : commute a c) (hbc : commute b c) : commute (a * b) c := hac.mul_left hbc
@[to_additive] protected lemma right_comm (h : commute b c) (a : S) :
a * b * c = a * c * b :=
by simp only [mul_assoc, h.eq]
@[to_additive] protected lemma left_comm (h : commute a b) (c) :
a * (b * c) = b * (a * c) :=
by simp only [← mul_assoc, h.eq]
end semigroup
@[to_additive]
protected theorem all {S : Type*} [comm_semigroup S] (a b : S) : commute a b := mul_comm a b
section mul_one_class
variables {M : Type*} [mul_one_class M]
@[simp, to_additive] theorem one_right (a : M) : commute a 1 := semiconj_by.one_right a
@[simp, to_additive] theorem one_left (a : M) : commute 1 a := semiconj_by.one_left a
end mul_one_class
section monoid
variables {M : Type*} [monoid M] {a b : M} {u u₁ u₂ : Mˣ}
@[simp, to_additive]
theorem pow_right (h : commute a b) (n : ℕ) : commute a (b ^ n) := h.pow_right n
@[simp, to_additive]
theorem pow_left (h : commute a b) (n : ℕ) : commute (a ^ n) b := (h.symm.pow_right n).symm
@[simp, to_additive]
theorem pow_pow (h : commute a b) (m n : ℕ) : commute (a ^ m) (b ^ n) :=
(h.pow_left m).pow_right n
@[simp, to_additive]
theorem self_pow (a : M) (n : ℕ) : commute a (a ^ n) := (commute.refl a).pow_right n
@[simp, to_additive]
theorem pow_self (a : M) (n : ℕ) : commute (a ^ n) a := (commute.refl a).pow_left n
@[simp, to_additive]
theorem pow_pow_self (a : M) (m n : ℕ) : commute (a ^ m) (a ^ n) :=
(commute.refl a).pow_pow m n
@[to_additive succ_nsmul'] theorem _root_.pow_succ' (a : M) (n : ℕ) : a ^ (n + 1) = a ^ n * a :=
(pow_succ a n).trans (self_pow _ _)
@[to_additive] theorem units_inv_right : commute a u → commute a ↑u⁻¹ :=
semiconj_by.units_inv_right
@[simp, to_additive] theorem units_inv_right_iff :
commute a ↑u⁻¹ ↔ commute a u :=
semiconj_by.units_inv_right_iff
@[to_additive] theorem units_inv_left : commute ↑u a → commute ↑u⁻¹ a :=
semiconj_by.units_inv_symm_left
@[simp, to_additive]
theorem units_inv_left_iff: commute ↑u⁻¹ a ↔ commute ↑u a :=
semiconj_by.units_inv_symm_left_iff
@[to_additive]
theorem units_coe : commute u₁ u₂ → commute (u₁ : M) u₂ := semiconj_by.units_coe
@[to_additive]
theorem units_of_coe : commute (u₁ : M) u₂ → commute u₁ u₂ := semiconj_by.units_of_coe
@[simp, to_additive]
theorem units_coe_iff : commute (u₁ : M) u₂ ↔ commute u₁ u₂ := semiconj_by.units_coe_iff
@[to_additive] lemma is_unit_mul_iff (h : commute a b) :
is_unit (a * b) ↔ is_unit a ∧ is_unit b :=
begin
refine ⟨_, λ H, H.1.mul H.2⟩,
rintro ⟨u, hu⟩,
have : b * ↑u⁻¹ * a = 1,
{ have : commute a u := hu.symm ▸ (commute.refl _).mul_right h,
rw [← this.units_inv_right.right_comm, ← h.eq, ← hu, u.mul_inv] },
split,
{ refine ⟨⟨a, b * ↑u⁻¹, _, this⟩, rfl⟩,
rw [← mul_assoc, ← hu, u.mul_inv] },
{ rw mul_assoc at this,
refine ⟨⟨b, ↑u⁻¹ * a, this, _⟩, rfl⟩,
rw [mul_assoc, ← hu, u.inv_mul] }
end
@[simp, to_additive] lemma _root_.is_unit_mul_self_iff :
is_unit (a * a) ↔ is_unit a :=
(commute.refl a).is_unit_mul_iff.trans (and_self _)
end monoid
section group
variables {G : Type*} [group G] {a b : G}
@[to_additive]
theorem inv_right : commute a b → commute a b⁻¹ := semiconj_by.inv_right
@[simp, to_additive]
theorem inv_right_iff : commute a b⁻¹ ↔ commute a b := semiconj_by.inv_right_iff
@[to_additive] theorem inv_left : commute a b → commute a⁻¹ b := semiconj_by.inv_symm_left
@[simp, to_additive]
theorem inv_left_iff : commute a⁻¹ b ↔ commute a b := semiconj_by.inv_symm_left_iff
@[to_additive]
theorem inv_inv : commute a b → commute a⁻¹ b⁻¹ := semiconj_by.inv_inv_symm
@[simp, to_additive]
theorem inv_inv_iff : commute a⁻¹ b⁻¹ ↔ commute a b := semiconj_by.inv_inv_symm_iff
@[to_additive]
protected theorem inv_mul_cancel (h : commute a b) : a⁻¹ * b * a = b :=
by rw [h.inv_left.eq, inv_mul_cancel_right]
@[to_additive]
theorem inv_mul_cancel_assoc (h : commute a b) : a⁻¹ * (b * a) = b :=
by rw [← mul_assoc, h.inv_mul_cancel]
@[to_additive]
protected theorem mul_inv_cancel (h : commute a b) : a * b * a⁻¹ = b :=
by rw [h.eq, mul_inv_cancel_right]
@[to_additive]
theorem mul_inv_cancel_assoc (h : commute a b) : a * (b * a⁻¹) = b :=
by rw [← mul_assoc, h.mul_inv_cancel]
end group
end commute
section comm_group
variables {G : Type*} [comm_group G] (a b : G)
@[simp, to_additive] lemma mul_inv_cancel_comm : a * b * a⁻¹ = b :=
(commute.all a b).mul_inv_cancel
@[simp, to_additive] lemma mul_inv_cancel_comm_assoc : a * (b * a⁻¹) = b :=
(commute.all a b).mul_inv_cancel_assoc
@[simp, to_additive] lemma inv_mul_cancel_comm : a⁻¹ * b * a = b :=
(commute.all a b).inv_mul_cancel
@[simp, to_additive] lemma inv_mul_cancel_comm_assoc : a⁻¹ * (b * a) = b :=
(commute.all a b).inv_mul_cancel_assoc
end comm_group
|
a6171a5c22b02f959587a502b76e4549aa293028
|
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
|
/src/data/multiset/basic.lean
|
3b09c50d59c4d59a149fb16840faca505fc90f8f
|
[
"Apache-2.0"
] |
permissive
|
molodiuc/mathlib
|
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
|
98ebe5a6739fbe254f9ee9d401882d4388f91035
|
refs/heads/master
| 1,674,237,127,059
| 1,606,353,533,000
| 1,606,353,533,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 87,429
|
lean
|
/-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import data.list.perm
import algebra.group_power
/-!
# Multisets
These are implemented as the quotient of a list by permutations.
## Notation
We define the global infix notation `::ₘ` for `multiset.cons`.
-/
open list subtype nat
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `multiset α` is the quotient of `list α` by list permutation. The result
is a type of finite sets with duplicates allowed. -/
def {u} multiset (α : Type u) : Type u :=
quotient (list.is_setoid α)
namespace multiset
instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩
@[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl
@[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl
@[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl
@[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq
instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α)
| s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂,
decidable_of_iff' _ quotient.eq
/-- defines a size for a multiset by referring to the size of the underlying list -/
protected def sizeof [has_sizeof α] (s : multiset α) : ℕ :=
quot.lift_on s sizeof $ λ l₁ l₂, perm.sizeof_eq_sizeof
instance has_sizeof [has_sizeof α] : has_sizeof (multiset α) := ⟨multiset.sizeof⟩
/- empty multiset -/
/-- `0 : multiset α` is the empty set -/
protected def zero : multiset α := @nil α
instance : has_zero (multiset α) := ⟨multiset.zero⟩
instance : has_emptyc (multiset α) := ⟨0⟩
instance : inhabited (multiset α) := ⟨0⟩
@[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl
@[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl
theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] :=
iff.trans coe_eq_coe perm_nil
/- cons -/
/-- `cons a s` is the multiset which contains `s` plus one more
instance of `a`. -/
def cons (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (a :: l : multiset α))
(λ l₁ l₂ p, quot.sound (p.cons a))
infixr ` ::ₘ `:67 := multiset.cons
instance : has_insert α (multiset α) := ⟨cons⟩
@[simp] theorem insert_eq_cons (a : α) (s : multiset α) :
insert a s = a ::ₘ s := rfl
@[simp] theorem cons_coe (a : α) (l : list α) :
(a ::ₘ l : multiset α) = (a::l : list α) := rfl
theorem singleton_coe (a : α) : (a ::ₘ 0 : multiset α) = ([a] : list α) := rfl
@[simp] theorem cons_inj_left {a b : α} (s : multiset α) :
a ::ₘ s = b ::ₘ s ↔ a = b :=
⟨quot.induction_on s $ λ l e,
have [a] ++ l ~ [b] ++ l, from quotient.exact e,
singleton_perm_singleton.1 $ (perm_append_right_iff _).1 this, congr_arg _⟩
@[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a ::ₘ s = a ::ₘ t ↔ s = t :=
by rintros ⟨l₁⟩ ⟨l₂⟩; simp
@[recursor 5] protected theorem induction {p : multiset α → Prop}
(h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : ∀s, p s :=
by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih]
@[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop}
(s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : p s :=
multiset.induction h₁ h₂ s
theorem cons_swap (a b : α) (s : multiset α) : a ::ₘ b ::ₘ s = b ::ₘ a ::ₘ s :=
quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _
section rec
variables {C : multiset α → Sort*}
/-- Dependent recursor on multisets.
TODO: should be @[recursor 6], but then the definition of `multiset.pi` fails with a stack
overflow in `whnf`.
-/
protected def rec
(C_0 : C 0)
(C_cons : Πa m, C m → C (a ::ₘ m))
(C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b))
(m : multiset α) : C m :=
quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $
assume l l' h,
h.rec_heq
(assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc)
(assume a a' l, C_cons_heq a a' ⟦l⟧)
@[elab_as_eliminator]
protected def rec_on (m : multiset α)
(C_0 : C 0)
(C_cons : Πa m, C m → C (a ::ₘ m))
(C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) :
C m :=
multiset.rec C_0 C_cons C_cons_heq m
variables {C_0 : C 0} {C_cons : Πa m, C m → C (a ::ₘ m)}
{C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)}
@[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 :=
rfl
@[simp] lemma rec_on_cons (a : α) (m : multiset α) :
(a ::ₘ m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) :=
quotient.induction_on m $ assume l, rfl
end rec
section mem
/-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/
def mem (a : α) (s : multiset α) : Prop :=
quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ e.mem_iff)
instance : has_mem α (multiset α) := ⟨mem⟩
@[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl
instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) :=
quot.rec_on_subsingleton s $ list.decidable_mem a
@[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b ::ₘ s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, iff.rfl
lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b ::ₘ s :=
mem_cons.2 $ or.inr h
@[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a ::ₘ s :=
mem_cons.2 (or.inl rfl)
theorem forall_mem_cons {p : α → Prop} {a : α} {s : multiset α} :
(∀ x ∈ (a ::ₘ s), p x) ↔ p a ∧ ∀ x ∈ s, p x :=
quotient.induction_on' s $ λ L, list.forall_mem_cons
theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a ::ₘ t :=
quot.induction_on s $ λ l (h : a ∈ l),
let ⟨l₁, l₂, e⟩ := mem_split h in
e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩
@[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id
theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 :=
quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl
theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s :=
⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩
theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s :=
quot.induction_on s $ assume l hl,
match l, hl with
| [] := assume h, false.elim $ h rfl
| (a :: l) := assume _, ⟨a, by simp⟩
end
@[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a ::ₘ m :=
assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this
@[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a ::ₘ m ≠ 0 := zero_ne_cons.symm
lemma cons_eq_cons {a b : α} {as bs : multiset α} :
a ::ₘ as = b ::ₘ bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b ::ₘ cs ∧ bs = a ::ₘ cs)) :=
begin
haveI : decidable_eq α := classical.dec_eq α,
split,
{ assume eq,
by_cases a = b,
{ subst h, simp * at * },
{ have : a ∈ b ::ₘ bs, from eq ▸ mem_cons_self _ _,
have : a ∈ bs, by simpa [h],
rcases exists_cons_of_mem this with ⟨cs, hcs⟩,
simp [h, hcs],
have : a ::ₘ as = b ::ₘ a ::ₘ cs, by simp [eq, hcs],
have : a ::ₘ as = a ::ₘ b ::ₘ cs, by rwa [cons_swap],
simpa using this } },
{ assume h,
rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ simp * },
{ simp [*, cons_swap a b] } }
end
end mem
/- subset -/
section subset
/-- `s ⊆ t` is the lift of the list subset relation. It means that any
element with nonzero multiplicity in `s` has nonzero multiplicity in `t`,
but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`;
see `s ≤ t` for this relation. -/
protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t
instance : has_subset (multiset α) := ⟨multiset.subset⟩
@[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl
@[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h
theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u :=
λ h₁ h₂ a m, h₂ (h₁ m)
theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl
theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _
@[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s :=
λ a, (not_mem_nil a).elim
@[simp] theorem cons_subset {a : α} {s t : multiset α} : (a ::ₘ s) ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp [subset_iff, or_imp_distrib, forall_and_distrib]
theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 :=
eq_zero_of_forall_not_mem h
theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 :=
⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩
end subset
section to_list
/-- Produces a list of the elements in the multiset using choice. -/
@[reducible] noncomputable def to_list {α : Type*} (s : multiset α) :=
classical.some (quotient.exists_rep s)
@[simp] lemma to_list_zero {α : Type*} : (multiset.to_list 0 : list α) = [] :=
(multiset.coe_eq_zero _).1 (classical.some_spec (quotient.exists_rep multiset.zero))
lemma coe_to_list {α : Type*} (s : multiset α) : (s.to_list : multiset α) = s :=
classical.some_spec (quotient.exists_rep _)
lemma mem_to_list {α : Type*} (a : α) (s : multiset α) : a ∈ s.to_list ↔ a ∈ s :=
by rw [←multiset.mem_coe, multiset.coe_to_list]
end to_list
/- multiset order -/
/-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation).
Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/
protected def le (s t : multiset α) : Prop :=
quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
propext (p₂.subperm_left.trans p₁.subperm_right)
instance : partial_order (multiset α) :=
{ le := multiset.le,
le_refl := by rintros ⟨l⟩; exact subperm.refl _,
le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _,
le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) }
theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm.subset
theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t :=
mem_of_subset (subset_of_le h)
@[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl
@[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop}
{s t : multiset α} (h : s ≤ t)
(H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t :=
quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩,
(show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h
theorem zero_le (s : multiset α) : 0 ≤ s :=
quot.induction_on s $ λ l, (nil_sublist l).subperm
theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 :=
⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩
theorem lt_cons_self (s : multiset α) (a : α) : s < a ::ₘ s :=
quot.induction_on s $ λ l,
suffices l <+~ a :: l ∧ (¬l ~ a :: l),
by simpa [lt_iff_le_and_ne],
⟨(sublist_cons _ _).subperm,
λ p, ne_of_lt (lt_succ_self (length l)) p.length_eq⟩
theorem le_cons_self (s : multiset α) (a : α) : s ≤ a ::ₘ s :=
le_of_lt $ lt_cons_self _ _
theorem cons_le_cons_iff (a : α) {s t : multiset α} : a ::ₘ s ≤ a ::ₘ t ↔ s ≤ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a
theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a ::ₘ s ≤ a ::ₘ t :=
(cons_le_cons_iff a).2
theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a ::ₘ t ↔ s ≤ t :=
begin
refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩,
suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a ::ₘ s ≤ t',
{ exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) },
introv h, revert m, refine le_induction_on h _,
introv s m₁ m₂,
rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩,
exact perm_middle.subperm_left.2 ((subperm_cons _).2 $
((sublist_or_mem_of_sublist s).resolve_right m₁).subperm)
end
/- cardinality -/
/-- The cardinality of a multiset is the sum of the multiplicities
of all its elements, or simply the length of the underlying list. -/
def card (s : multiset α) : ℕ :=
quot.lift_on s length $ λ l₁ l₂, perm.length_eq
@[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl
@[simp] theorem card_zero : @card α 0 = 0 := rfl
@[simp] theorem card_cons (a : α) (s : multiset α) : card (a ::ₘ s) = card s + 1 :=
quot.induction_on s $ λ l, rfl
@[simp] theorem card_singleton (a : α) : card (a ::ₘ 0) = 1 := by simp
theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t :=
le_induction_on h $ λ l₁ l₂, length_le_of_sublist
theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t :=
le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂
theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t :=
lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂
theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a ::ₘ s ≤ t :=
⟨quotient.induction_on₂ s t $ λ l₁ l₂ h,
subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h),
λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩
@[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 :=
⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩
theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 :=
pos_iff_ne_zero.trans $ not_congr card_eq_zero
theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s :=
quot.induction_on s $ λ l, length_pos_iff_exists_mem
@[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} :
∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s
| s := λ ih, ih s $ λ t h,
have card t < card s, from card_lt_of_lt h,
strong_induction_on t ih
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]}
theorem strong_induction_eq {p : multiset α → Sort*}
(s : multiset α) (H) : @strong_induction_on _ p s H =
H s (λ t h, @strong_induction_on _ p t H) :=
by rw [strong_induction_on]
@[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop}
(s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a ::ₘ s)) : p s :=
multiset.strong_induction_on s $ assume s,
multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $
λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _
/- singleton -/
instance : has_singleton α (multiset α) := ⟨λ a, a ::ₘ 0⟩
instance : is_lawful_singleton α (multiset α) := ⟨λ a, rfl⟩
@[simp] theorem singleton_eq_singleton (a : α) : singleton a = a ::ₘ 0 := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ a ::ₘ 0 ↔ b = a := by simp
theorem mem_singleton_self (a : α) : a ∈ (a ::ₘ 0 : multiset α) := mem_cons_self _ _
theorem singleton_inj {a b : α} : a ::ₘ 0 = b ::ₘ 0 ↔ a = b := cons_inj_left _
@[simp] theorem singleton_ne_zero (a : α) : a ::ₘ 0 ≠ 0 :=
ne_of_gt (lt_cons_self _ _)
@[simp] theorem singleton_le {a : α} {s : multiset α} : a ::ₘ 0 ≤ s ↔ a ∈ s :=
⟨λ h, mem_of_le h (mem_singleton_self _),
λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩
theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a ::ₘ 0 :=
⟨quot.induction_on s $ λ l h,
(list.length_eq_one.1 h).imp $ λ a, congr_arg coe,
λ ⟨a, e⟩, e.symm ▸ rfl⟩
/- add -/
/-- The sum of two multisets is the lift of the list append operation.
This adds the multiplicities of each element,
i.e. `count a (s + t) = count a s + count a t`. -/
protected def add (s₁ s₂ : multiset α) : multiset α :=
quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $
λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.append p₂
instance : has_add (multiset α) := ⟨multiset.add⟩
@[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl
protected theorem add_comm (s t : multiset α) : s + t = t + s :=
quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_append_comm
protected theorem zero_add (s : multiset α) : 0 + s = s :=
quot.induction_on s $ λ l, rfl
theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a ::ₘ s := rfl
protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u :=
quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_append_left _
protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u :=
le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h))
((multiset.add_le_add_left _).1 (le_of_eq h.symm))
instance : ordered_cancel_add_comm_monoid (multiset α) :=
{ zero := 0,
add := (+),
add_comm := multiset.add_comm,
add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃,
congr_arg coe $ append_assoc l₁ l₂ l₃,
zero_add := multiset.zero_add,
add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add],
add_left_cancel := multiset.add_left_cancel,
add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $
by simpa [multiset.add_comm] using h,
add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h,
le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1,
..@multiset.partial_order α }
@[simp] theorem cons_add (a : α) (s t : multiset α) : a ::ₘ s + t = a ::ₘ (s + t) :=
by rw [← singleton_add, ← singleton_add, add_assoc]
@[simp] theorem add_cons (a : α) (s t : multiset α) : s + a ::ₘ t = a ::ₘ (s + t) :=
by rw [add_comm, cons_add, add_comm]
theorem le_add_right (s t : multiset α) : s ≤ s + t :=
by simpa using add_le_add_left (zero_le t) s
theorem le_add_left (s t : multiset α) : s ≤ t + s :=
by simpa using add_le_add_right (zero_le t) s
@[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t :=
quotient.induction_on₂ s t length_append
lemma card_smul (s : multiset α) (n : ℕ) :
(n •ℕ s).card = n * s.card :=
by induction n; simp [succ_nsmul, *, nat.succ_mul]; cc
@[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, mem_append
theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u :=
⟨λ h, le_induction_on h $ λ l₁ l₂ s,
let ⟨l, p⟩ := s.exists_perm_append in ⟨l, quot.sound p⟩,
λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩
instance : canonically_ordered_add_monoid (multiset α) :=
{ lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _,
le_iff_exists_add := @le_iff_exists_add _,
bot := 0,
bot_le := multiset.zero_le,
..multiset.ordered_cancel_add_comm_monoid }
/- repeat -/
/-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/
def repeat (a : α) (n : ℕ) : multiset α := repeat a n
@[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl
@[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a ::ₘ repeat a n := by simp [repeat]
@[simp] lemma repeat_one (a : α) : repeat a 1 = a ::ₘ 0 := by simp
@[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat
theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat
theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
(perm_repeat.1 $ (quotient.exact h)), congr_arg coe⟩ eq_repeat'
theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card :=
eq_repeat'.2
theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a :=
⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a ::ₘ 0 := repeat_subset_singleton
theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l :=
⟨λ ⟨l', p, s⟩, (perm_repeat.1 p) ▸ s, sublist.subperm⟩
/- erase -/
section erase
variables [decidable_eq α] {s t : multiset α} {a b : α}
/-- `erase s a` is the multiset that subtracts 1 from the
multiplicity of `a`. -/
def erase (s : multiset α) (a : α) : multiset α :=
quot.lift_on s (λ l, (l.erase a : multiset α))
(λ l₁ l₂ p, quot.sound (p.erase a))
@[simp] theorem coe_erase (l : list α) (a : α) :
erase (l : multiset α) a = l.erase a := rfl
@[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl
@[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a ::ₘ s).erase a = s :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l
@[simp, priority 990]
theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b ::ₘ s).erase a = b ::ₘ s.erase a :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h
@[simp, priority 980]
theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s :=
quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h
@[simp, priority 980]
theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a ::ₘ s.erase a = s :=
quot.induction_on s $ λ l h, quot.sound (perm_cons_erase h).symm
theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a ::ₘ s.erase a :=
if h : a ∈ s then le_of_eq (cons_erase h).symm
else by rw erase_of_not_mem h; apply le_cons_self
theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h
theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) :
(s + t).erase a = s + t.erase a :=
by rw [add_comm, erase_add_left_pos s h, add_comm]
theorem erase_add_right_neg {a : α} {s : multiset α} (t) :
a ∉ s → (s + t).erase a = s + t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h
theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) :
(s + t).erase a = s.erase a + t :=
by rw [add_comm, erase_add_right_neg s h, add_comm]
theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s :=
quot.induction_on s $ λ l, (erase_sublist a l).subperm
@[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s :=
⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h),
λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩
theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s :=
subset_of_le (erase_le a s)
theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s :=
quot.induction_on s $ λ l, list.mem_erase_of_ne ab
theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s :=
mem_of_subset (erase_subset _ _)
theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a :=
quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b
theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a :=
le_induction_on h $ λ l₁ l₂ h, (h.erase _).subperm
theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a ::ₘ t :=
⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h),
λ h, if m : a ∈ s
then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h
else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩
@[simp] theorem card_erase_of_mem {a : α} {s : multiset α} :
a ∈ s → card (s.erase a) = pred (card s) :=
quot.induction_on s $ λ l, length_erase_of_mem
theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s :=
λ h, card_lt_of_lt (erase_lt.mpr h)
theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s :=
card_le_of_le (erase_le a s)
end erase
@[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l :=
quot.sound $ reverse_perm _
/- map -/
/-- `map f s` is the lift of the list `map` operation. The multiplicity
of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity)
such that `f a = b`. -/
def map (f : α → β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l : list α, (l.map f : multiset β))
(λ l₁ l₂ p, quot.sound (p.map f))
theorem forall_mem_map_iff {f : α → β} {p : β → Prop} {s : multiset α} :
(∀ y ∈ s.map f, p y) ↔ (∀ x ∈ s, p (f x)) :=
quotient.induction_on' s $ λ L, list.forall_mem_map_iff
@[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl
@[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl
@[simp] theorem map_cons (f : α → β) (a s) : map f (a ::ₘ s) = f a ::ₘ map f s :=
quot.induction_on s $ λ l, rfl
lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl
theorem map_repeat (f : α → β) (a : α) (k : ℕ) : (repeat a k).map f = repeat (f a) k := by
{ induction k, simp, simpa }
@[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _
instance (f : α → β) : is_add_monoid_hom (map f) :=
{ map_add := map_add _, map_zero := map_zero _ }
theorem map_nsmul (f : α → β) (n s) : map f (n •ℕ s) = n •ℕ map f s :=
(add_monoid_hom.of (map f)).map_nsmul _ _
@[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} :
b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b :=
quot.induction_on s $ λ l, mem_map
@[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s :=
quot.induction_on s $ λ l, length_map _ _
@[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 :=
by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero]
theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s :=
mem_map.2 ⟨_, h, rfl⟩
theorem mem_map_of_injective {f : α → β} (H : function.injective f) {a : α} {s : multiset α} :
f a ∈ map f s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_map_of_injective H
@[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _
theorem map_id (s : multiset α) : map id s = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_id _
@[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s
@[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card :=
quot.induction_on s $ λ l, congr_arg coe $ map_const _ _
@[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s :=
quot.induction_on s $ λ l H, congr_arg coe $ map_congr H
lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m :=
begin subst h, simp at hf, simp [map_congr hf] end
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ :=
eq_of_mem_repeat $ by rwa map_const at h
@[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t :=
le_induction_on h $ λ l₁ l₂ h, (h.map f).subperm
@[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t :=
λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩
/- fold -/
/-- `foldl f H b s` is the lift of the list operation `foldl f b l`,
which folds `f` over the multiset. It is well defined when `f` is right-commutative,
that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/
def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldl f b l)
(λ l₁ l₂ p, p.foldl_eq H b)
@[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl
@[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a ::ₘ s) = foldl f H (f b a) s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _
/-- `foldr f H b s` is the lift of the list operation `foldr f b l`,
which folds `f` over the multiset. It is well defined when `f` is left-commutative,
that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/
def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldr f b l)
(λ l₁ l₂ p, p.foldr_eq H b)
@[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a ::ₘ s) = f a (foldr f H b s) :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _
@[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldr f b := rfl
@[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) :
foldl f H b l = l.foldl f b := rfl
theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldl (λ x y, f y x) b :=
(congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _
theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) :
foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _
theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) :
foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
(foldr_swap _ _ _ _).symm
/-- Product of a multiset given a commutative monoid structure on `α`.
`prod {a, b, c} = a * b * c` -/
@[to_additive]
def prod [comm_monoid α] : multiset α → α :=
foldr (*) (λ x y z, by simp [mul_left_comm]) 1
@[to_additive]
theorem prod_eq_foldr [comm_monoid α] (s : multiset α) :
prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl
@[to_additive]
theorem prod_eq_foldl [comm_monoid α] (s : multiset α) :
prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s :=
(foldr_swap _ _ _ _).trans (by simp [mul_comm])
@[simp, to_additive]
theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod :=
prod_eq_foldl _
attribute [norm_cast] coe_prod coe_sum
@[simp, to_additive]
theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl
@[simp, to_additive]
theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a ::ₘ s) = a * prod s :=
foldr_cons _ _ _ _ _
@[to_additive]
theorem prod_singleton [comm_monoid α] (a : α) : prod (a ::ₘ 0) = a := by simp
@[simp, to_additive]
theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t :=
quotient.induction_on₂ s t $ λ l₁ l₂, by simp
instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) :=
{ map_add := sum_add, map_zero := sum_zero }
lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) :
∀n, (n •ℕ m).prod = m.prod ^ n
| 0 := rfl
| (n + 1) :=
by rw [add_nsmul, one_nsmul, pow_add, pow_one, prod_add, prod_smul n]
@[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n :=
by simp [repeat, list.prod_repeat]
@[simp] theorem sum_repeat [add_comm_monoid α] :
∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n •ℕ a :=
@prod_repeat (multiplicative α) _
attribute [to_additive] prod_repeat
lemma prod_map_one [comm_monoid γ] {m : multiset α} :
prod (m.map (λa, (1 : γ))) = (1 : γ) :=
by simp
lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} :
sum (m.map (λa, (0 : γ))) = (0 : γ) :=
by simp
attribute [to_additive] prod_map_one
@[simp, to_additive]
lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} :
prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc)
lemma prod_map_prod_map [comm_monoid γ] (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) (assume a m ih, by simp [ih])
lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ},
sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) :=
@prod_map_prod_map _ _ (multiplicative γ) _
attribute [to_additive] prod_map_prod_map
lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, b * f a)) = b * sum (s.map f) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add])
lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, f a * b)) = sum (s.map f) * b :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul])
theorem prod_ne_zero {R : Type*} [integral_domain R] {m : multiset R} :
(∀ x ∈ m, (x : _) ≠ 0) → m.prod ≠ 0 :=
multiset.induction_on m (λ _, one_ne_zero) $ λ hd tl ih H,
by { rw forall_mem_cons at H, rw prod_cons, exact mul_ne_zero H.1 (ih H.2) }
lemma prod_eq_zero {α : Type*} [comm_semiring α] {s : multiset α} (h : (0 : α) ∈ s) :
multiset.prod s = 0 :=
begin
rcases multiset.exists_cons_of_mem h with ⟨s', hs'⟩,
simp [hs', multiset.prod_cons]
end
@[to_additive]
lemma prod_hom [comm_monoid α] [comm_monoid β] (s : multiset α) (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]
theorem prod_hom_rel [comm_monoid β] [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]
lemma dvd_prod [comm_monoid α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod :=
quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a
lemma prod_dvd_prod [comm_monoid α] {s t : multiset α} (h : s ≤ t) :
s.prod ∣ t.prod :=
begin
rcases multiset.le_iff_exists_add.1 h with ⟨z, rfl⟩,
simp,
end
theorem prod_eq_zero_iff [comm_cancel_monoid_with_zero α] [nontrivial α]
{s : multiset α} :
s.prod = 0 ↔ (0 : α) ∈ s :=
multiset.induction_on s (by simp) $
assume a s, by simp [mul_eq_zero, @eq_comm _ 0 a] {contextual := tt}
@[to_additive sum_nonneg]
lemma one_le_prod_of_one_le [ordered_comm_monoid α] {m : multiset α} :
(∀ x ∈ m, (1 : α) ≤ x) → 1 ≤ m.prod :=
quotient.induction_on m $ λ l hl, by simpa using list.one_le_prod_of_one_le hl
@[to_additive]
lemma single_le_prod [ordered_comm_monoid α] {m : multiset α} :
(∀ x ∈ m, (1 : α) ≤ x) → ∀ x ∈ m, x ≤ m.prod :=
quotient.induction_on m $ λ l hl x hx, by simpa using list.single_le_prod hl x hx
@[to_additive all_zero_of_le_zero_le_of_sum_eq_zero]
lemma all_one_of_le_one_le_of_prod_eq_one [ordered_comm_monoid α] {m : multiset α} :
(∀ x ∈ m, (1 : α) ≤ x) → m.prod = 1 → (∀ x ∈ m, x = (1 : α)) :=
begin
apply quotient.induction_on m,
simp only [quot_mk_to_coe, coe_prod, mem_coe],
intros l hl₁ hl₂ x hx,
apply all_one_of_le_one_le_of_prod_eq_one hl₁ hl₂ _ hx,
end
lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] {m : multiset α} :
m.sum = 0 ↔ ∀ x ∈ m, x = (0 : α) :=
quotient.induction_on m $ λ l, by simpa using list.sum_eq_zero_iff l
lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_add_comm_monoid β]
(f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : multiset α) :
f s.sum ≤ (s.map f).sum :=
multiset.induction_on s (le_of_eq h_zero) $
assume a s ih, by rw [sum_cons, map_cons, sum_cons];
from le_trans (h_add a s.sum) (add_le_add_left ih _)
lemma abs_sum_le_sum_abs [linear_ordered_field α] {s : multiset α} :
abs s.sum ≤ (s.map abs).sum :=
le_sum_of_subadditive _ abs_zero abs_add s
theorem dvd_sum [comm_semiring α] {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)))))
@[simp] theorem sum_map_singleton (s : multiset α) : (s.map (λ a, a ::ₘ 0)).sum = s :=
multiset.induction_on s (by simp) (by simp)
/-! ### Join -/
/-- `join S`, where `S` is a multiset of multisets, is the lift of the list join
operation, that is, the union of all the sets.
join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/
def join : multiset (multiset α) → multiset α := sum
theorem coe_join : ∀ L : list (list α),
join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join
| [] := rfl
| (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L)
@[simp] theorem join_zero : @join α 0 = 0 := rfl
@[simp] theorem join_cons (s S) : @join α (s ::ₘ S) = s + join S :=
sum_cons _ _
@[simp] theorem join_add (S T) : @join α (S + T) = join S + join T :=
sum_add _ _
@[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s :=
multiset.induction_on S (by simp) $
by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt}
@[simp] theorem card_join (S) : card (@join α S) = sum (map card S) :=
multiset.induction_on S (by simp) (by simp)
/- bind -/
/-- `bind s f` is the monad bind operation, defined as `join (map f s)`.
It is the union of `f a` as `a` ranges over `s`. -/
def bind (s : multiset α) (f : α → multiset β) : multiset β :=
join (map f s)
@[simp] theorem coe_bind (l : list α) (f : α → list β) :
@bind α β l (λ a, f a) = l.bind f :=
by rw [list.bind, ← coe_join, list.map_map]; refl
@[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl
@[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a ::ₘ s) f = f a + bind s f :=
by simp [bind]
@[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f :=
by simp [bind]
@[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 :=
by simp [bind, join]
@[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) :
bind s (λa, f a + g a) = bind s f + bind s g :=
by simp [bind, join]
@[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) :
bind s (λa, f a ::ₘ g a) = map f s + bind s g :=
multiset.induction_on s (by simp) (by simp [add_comm, add_left_comm] {contextual := tt})
@[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a :=
by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm];
rw exists_swap; simp [and_assoc]
@[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) :=
by simp [bind]
lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g :=
by simp [bind] {contextual := tt}
lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' :=
begin subst h, simp at hf, simp [bind_congr hf] end
lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) :
map f (bind m n) = bind m (λa, map f (n a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) :
bind (map f m) n = bind m (λa, n (f a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} :
(s.bind f).bind g = s.bind (λa, (f a).bind g) :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} :
(bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} :
(bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
@[simp, to_additive]
lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) :
prod (bind s t) = prod (s.map $ λa, prod (t a)) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind])
/- product -/
/-- The multiplicity of `(a, b)` in `product s t` is
the product of the multiplicity of `a` in `s` and `b` in `t`. -/
def product (s : multiset α) (t : multiset β) : multiset (α × β) :=
s.bind $ λ a, t.map $ prod.mk a
@[simp] theorem coe_product (l₁ : list α) (l₂ : list β) :
@product α β l₁ l₂ = l₁.product l₂ :=
by rw [product, list.product, ← coe_bind]; simp
@[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl
@[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) :
product (a ::ₘ s) t = map (prod.mk a) t + product s t :=
by simp [product]
@[simp] theorem product_singleton (a : α) (b : β) : product (a ::ₘ 0) (b ::ₘ 0) = (a,b) ::ₘ 0 := rfl
@[simp] theorem add_product (s t : multiset α) (u : multiset β) :
product (s + t) u = product s u + product t u :=
by simp [product]
@[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β,
product s (t + u) = product s t + product s u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_product, IH]; simp; cc
@[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t
| (a, b) := by simp [product, and.left_comm]
@[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t :=
by simp [product, repeat, (∘), mul_comm]
/- sigma -/
section
variable {σ : α → Type*}
/-- `sigma s t` is the dependent version of `product`. It is the sum of
`(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/
protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) :=
s.bind $ λ a, (t a).map $ sigma.mk a
@[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
@multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ :=
by rw [multiset.sigma, list.sigma, ← coe_bind]; simp
@[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl
@[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) :
(a ::ₘ s).sigma t = map (sigma.mk a) (t a) + s.sigma t :=
by simp [multiset.sigma]
@[simp] theorem sigma_singleton (a : α) (b : α → β) :
(a ::ₘ 0).sigma (λ a, b a ::ₘ 0) = ⟨a, b a⟩ ::ₘ 0 := rfl
@[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) :
(s + t).sigma u = s.sigma u + t.sigma u :=
by simp [multiset.sigma]
@[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a),
s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_sigma, IH]; simp; cc
@[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a},
p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1
| ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm]
@[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) :
card (s.sigma t) = sum (map (λ a, card (t a)) s) :=
by simp [multiset.sigma, (∘)]
end
/- map for partial functions -/
/-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset
`s` whose elements are all in the domain of `f`. -/
def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β :=
quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂),
funext $ λ (H₂ : ∀ a ∈ l₂, p a),
have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a (pp.subset h),
have ∀ {s₂ e H}, @eq.rec (multiset α) l₁
(λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁))
s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e,
this.trans $ quot.sound $ pp.pmap f
@[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β)
(l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl
@[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) :
pmap f 0 h = 0 := rfl
@[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) :
∀(h : ∀b∈a ::ₘ m, p b), pmap f (a ::ₘ m) h =
f a (h a (mem_cons_self a m)) ::ₘ pmap f m (λa ha, h a $ mem_cons_of_mem ha) :=
quotient.induction_on m $ assume l h, rfl
/-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce
a multiset on `{x // x ∈ s}`. -/
def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id)
@[simp] theorem coe_attach (l : list α) :
@eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl
theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : multiset α} (hx : x ∈ s) :
sizeof x < sizeof s := by
{ induction s with l a b, exact list.sizeof_lt_sizeof_of_mem hx, refl }
theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) :
∀ H, @pmap _ _ p (λ a _, f a) s H = map f s :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f s H₁ = pmap g s H₂ :=
quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H :=
quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H
theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s :=
quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l
@[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach :=
quot.induction_on s $ λ l, mem_attach _
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b :=
quot.induction_on s (λ l H, mem_pmap) H
@[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β)
(s H) : card (pmap f s H) = card s :=
quot.induction_on s (λ l H, length_pmap) H
@[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _
@[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl
lemma attach_cons (a : α) (m : multiset α) :
(a ::ₘ m).attach = ⟨a, mem_cons_self a m⟩ ::ₘ (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) :=
quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $
by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl)
section decidable_pi_exists
variables {m : multiset α}
protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] :
decidable (∀a∈m, p a) :=
quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp)
instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∀a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _))
/-- decidable equality for functions whose domain is bounded by multisets -/
instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] :
decidable_eq (Πa∈m, β a) :=
assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff])
def decidable_exists_multiset {p : α → Prop} [decidable_pred p] :
decidable (∃ x ∈ m, p x) :=
quotient.rec_on_subsingleton m list.decidable_exists_mem
instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∃a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩)
(λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩))
end decidable_pi_exists
/- subtraction -/
section
variables [decidable_eq α] {s t u : multiset α} {a b : α}
/-- `s - t` is the multiset such that
`count a (s - t) = count a s - count a t` for all `a`. -/
protected def sub (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ p₁.diff p₂
instance : has_sub (multiset α) := ⟨multiset.sub⟩
@[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl
theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂,
by { rw diff_eq_foldl l₁ l₂, symmetry, exact foldl_hom _ _ _ _ _ (λ x y, rfl) }
@[simp] theorem sub_zero (s : multiset α) : s - 0 = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a ::ₘ t = s.erase a - t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _
theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t :=
begin
revert t,
refine multiset.induction_on s (by simp) (λ a s IH t h, _),
have := cons_erase (mem_of_le h (mem_cons_self _ _)),
rw [cons_add, sub_cons, IH, this],
exact (cons_le_cons_iff a).1 (this.symm ▸ h)
end
theorem sub_add' : s - (t + u) = s - t - u :=
quotient.induction_on₃ s t u $
λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _
theorem sub_add_cancel (h : t ≤ s) : s - t + t = s :=
by rw [add_comm, add_sub_of_le h]
@[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t :=
multiset.induction_on s (by simp)
(λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH])
@[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s :=
by rw [add_comm, add_sub_cancel_left]
theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u :=
by revert s t h; exact
multiset.induction_on u (by simp {contextual := tt})
(λ a u IH s t h, by simp [IH, erase_le_erase a h])
theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s :=
le_induction_on h $ λ l₁ l₂ h, begin
induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u,
{ refl },
{ rw [← cons_coe, sub_cons],
exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) },
{ rw [← cons_coe, sub_cons, ← cons_coe, sub_cons],
exact IH _ }
end
theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t :=
by revert s; exact
multiset.induction_on t (by simp)
(λ a t IH s, by simp [IH, erase_le_iff_le_cons])
theorem le_sub_add (s t : multiset α) : s ≤ s - t + t :=
sub_le_iff_le_add.1 (le_refl _)
theorem sub_le_self (s t : multiset α) : s - t ≤ s :=
sub_le_iff_le_add.2 (le_add_right _ _)
@[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t :=
(nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm
/- union -/
/-- `s ∪ t` is the lattice join operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum
of the multiplicities in `s` and `t`. -/
def union (s t : multiset α) : multiset α := s - t + t
instance : has_union (multiset α) := ⟨union⟩
theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl
theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _
theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _
theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel
theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u :=
add_le_add_right (sub_le_sub_right h _) u
theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u :=
by rw ← eq_union_left h₂; exact union_le_union_right h₁ t
@[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t :=
⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _),
or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩
@[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} :
map f (s ∪ t) = map f s ∪ map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
congr_arg coe (by rw [list.map_append f, list.map_diff finj])
/- inter -/
/-- `s ∩ t` is the lattice meet operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum
of the multiplicities in `s` and `t`. -/
def inter (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ p₁.bag_inter p₂
instance : has_inter (multiset α) := ⟨inter⟩
@[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil
@[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter
@[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} :
a ∈ t → (a ::ₘ s) ∩ t = a ::ₘ s ∩ t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_pos _ h
@[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} :
a ∉ t → (a ::ₘ s) ∩ t = s ∩ t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_neg _ h
theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s :=
quotient.induction_on₂ s t $ λ l₁ l₂,
(bag_inter_sublist_left _ _).subperm
theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t :=
multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $
λ a s IH t, if h : a ∈ t
then by simpa [h] using cons_le_cons a (IH (t.erase a))
else by simp [h, IH]
theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u :=
begin
revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros,
{ simp [h₁] },
by_cases a ∈ u,
{ rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons],
exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) },
{ rw cons_inter_of_neg _ h,
exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ }
end
@[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t :=
⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩,
λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩
instance : lattice (multiset α) :=
{ sup := (∪),
sup_le := @union_le _ _,
le_sup_left := le_union_left,
le_sup_right := le_union_right,
inf := (∩),
le_inf := @le_inter _ _,
inf_le_left := inter_le_left,
inf_le_right := inter_le_right,
..@multiset.partial_order α }
@[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl
@[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl
@[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff
@[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff
instance : semilattice_inf_bot (multiset α) :=
{ bot := 0, bot_le := zero_le, ..multiset.lattice }
theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm
theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm
theorem eq_union_right (h : s ≤ t) : s ∪ t = t :=
by rw [union_comm, eq_union_left h]
theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t :=
sup_le_sup_left h _
theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t :=
union_le (le_add_right _ _) (le_add_left _ _)
theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) :=
by simpa [(∪), union, eq_comm, add_assoc] using show s + u - (t + u) = s - t,
by rw [add_comm t, sub_add', add_sub_cancel]
theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) :=
by rw [add_comm, union_add_distrib, add_comm s, add_comm s]
theorem cons_union_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∪ t) = (a ::ₘ s) ∪ (a ::ₘ t) :=
by simpa using add_union_distrib (a ::ₘ 0) s t
theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) :=
begin
by_contra h,
cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter
(add_le_add_right (inter_le_left s t) u)
(add_le_add_right (inter_le_right s t) u)) h) with a hl,
rw ← cons_add at hl,
exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter
(le_of_add_le_add_right (le_trans hl (inter_le_left _ _)))
(le_of_add_le_add_right (le_trans hl (inter_le_right _ _))))
end
theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) :=
by rw [add_comm, inter_add_distrib, add_comm s, add_comm s]
theorem cons_inter_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∩ t) = (a ::ₘ s) ∩ (a ::ₘ t) :=
by simp
theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t :=
begin
apply le_antisymm,
{ rw union_add_distrib,
refine union_le (add_le_add_left (inter_le_right _ _) _) _,
rw add_comm, exact add_le_add_right (inter_le_left _ _) _ },
{ rw [add_comm, add_inter_distrib],
refine le_inter (add_le_add_right (le_union_right _ _) _) _,
rw add_comm, exact add_le_add_right (le_union_left _ _) _ }
end
theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s :=
begin
rw [inter_comm],
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
by_cases a ∈ s,
{ rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] },
{ rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] }
end
theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t :=
add_right_cancel $
by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)]
end
/- filter -/
section
variables (p : α → Prop) [decidable_pred p]
/-- `filter p s` returns the elements in `s` (with the same multiplicities)
which satisfy `p`, and removes the rest. -/
def filter (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (filter p l : multiset α))
(λ l₁ l₂ h, quot.sound $ h.filter p)
@[simp] theorem coe_filter (l : list α) : filter p (↑l) = l.filter p := rfl
@[simp] theorem filter_zero : filter p 0 = 0 := rfl
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
{s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h
@[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _
@[simp] theorem filter_le (s : multiset α) : filter p s ≤ s :=
quot.induction_on s $ λ l, (filter_sublist _).subperm
@[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s :=
subset_of_le $ filter_le _ _
theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t :=
le_induction_on h $ λ l₁ l₂ h, (filter_sublist_filter p h).subperm
variable {p}
@[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a ::ₘ s) = a ::ₘ filter p s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h
@[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a ::ₘ s) = filter p s :=
quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h
@[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a :=
quot.induction_on s $ λ l, mem_filter
theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a :=
(mem_filter.1 h).2
theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s :=
(mem_filter.1 h).1
theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l :=
mem_filter.2 ⟨m, h⟩
theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_self
theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_nil
theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a :=
⟨λ h, ⟨le_trans h (filter_le _ _), λ a m, of_mem_filter (mem_of_le h m)⟩,
λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter p h⟩
variable (p)
@[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) :
filter p (s - t) = filter p s - filter p t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
rw [sub_cons, IH],
by_cases p a,
{ rw [filter_cons_of_pos _ h, sub_cons], congr,
by_cases m : a ∈ s,
{ rw [← cons_inj_right a, ← filter_cons_of_pos _ h,
cons_erase (mem_filter_of_mem m h), cons_erase m] },
{ rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } },
{ rw [filter_cons_of_neg _ h],
by_cases m : a ∈ s,
{ rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a ::ₘ erase s a)),
cons_erase m] },
{ rw [erase_of_not_mem m] } }
end
@[simp] theorem filter_union [decidable_eq α] (s t : multiset α) :
filter p (s ∪ t) = filter p s ∪ filter p t :=
by simp [(∪), union]
@[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) :
filter p (s ∩ t) = filter p s ∩ filter p t :=
le_antisymm (le_inter
(filter_le_filter _ $ inter_le_left _ _)
(filter_le_filter _ $ inter_le_right _ _)) $ le_filter.2
⟨inf_le_inf (filter_le _ _) (filter_le _ _),
λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩
@[simp] theorem filter_filter (q) [decidable_pred q] (s : multiset α) :
filter p (filter q s) = filter (λ a, p a ∧ q a) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter p q l
theorem filter_add_filter (q) [decidable_pred q] (s : multiset α) :
filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s :=
multiset.induction_on s rfl $ λ a s IH,
by by_cases p a; by_cases q a; simp *
theorem filter_add_not (s : multiset α) :
filter p s + filter (λ a, ¬ p a) s = s :=
by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em]
/- filter_map -/
/-- `filter_map f s` is a combination filter/map operation on `s`.
The function `f : α → option β` is applied to each element of `s`;
if `f a` is `some b` then `b` is added to the result, otherwise
`a` is removed from the resulting multiset. -/
def filter_map (f : α → option β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l, (filter_map f l : multiset β))
(λ l₁ l₂ h, quot.sound $ h.filter_map f)
@[simp] theorem coe_filter_map (f : α → option β) (l : list α) :
filter_map f l = l.filter_map f := rfl
@[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) :
filter_map f (a ::ₘ s) = filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (s : multiset α) {b : β} (h : f a = some b) :
filter_map f (a ::ₘ s) = b ::ₘ filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l
theorem filter_map_eq_filter : filter_map (option.guard p) = filter p :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) :
filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l
theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) :
map g (filter_map f s) = filter_map (λ x, (f x).map g) s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l
theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) :
filter_map g (map f s) = filter_map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) :
filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l
theorem filter_map_filter (f : α → option β) (s : multiset α) :
filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l
@[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l
@[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} :
b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b :=
quot.induction_on s $ λ l, mem_filter_map f l
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (s : multiset α) :
map g (filter_map f s) = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l
theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α}
(h : s ≤ t) : filter_map f s ≤ filter_map f t :=
le_induction_on h $ λ l₁ l₂ h, (h.filter_map _).subperm
/-! ### countp -/
/-- `countp p s` counts the number of elements of `s` (with multiplicity) that
satisfy `p`. -/
def countp (s : multiset α) : ℕ :=
quot.lift_on s (countp p) (λ l₁ l₂, perm.countp_eq p)
@[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl
@[simp] theorem countp_zero : countp p 0 = 0 := rfl
variable {p}
@[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a ::ₘ s) = countp p s + 1 :=
quot.induction_on s $ countp_cons_of_pos p
@[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a ::ₘ s) = countp p s :=
quot.induction_on s $ countp_cons_of_neg p
variable (p)
theorem countp_eq_card_filter (s) : countp p s = card (filter p s) :=
quot.induction_on s $ λ l, countp_eq_length_filter _ _
@[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t :=
by simp [countp_eq_card_filter]
instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) :=
{ map_add := countp_add _, map_zero := countp_zero _ }
@[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) :
countp p (s - t) = countp p s - countp p t :=
by simp [countp_eq_card_filter, h, filter_le_filter]
theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t :=
by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter p h)
@[simp] theorem countp_filter (q) [decidable_pred q] (s : multiset α) :
countp p (filter q s) = countp (λ a, p a ∧ q a) s :=
by simp [countp_eq_card_filter]
variable {p}
theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a :=
by simp [countp_eq_card_filter, card_pos_iff_exists_mem]
theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s :=
countp_pos.2 ⟨_, h, pa⟩
end
/- count -/
section
variable [decidable_eq α]
/-- `count a s` is the multiplicity of `a` in `s`. -/
def count (a : α) : multiset α → ℕ := countp (eq a)
@[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ _
@[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl
@[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a ::ₘ s) = succ (count a s) :=
countp_cons_of_pos _ rfl
@[simp, priority 990]
theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b ::ₘ s) = count a s :=
countp_cons_of_neg _ h
theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t :=
countp_le_of_le _
theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b ::ₘ s) :=
count_le_of_le _ (le_cons_self _ _)
theorem count_cons (a b : α) (s : multiset α) :
count a (b ::ₘ s) = count a s + (if a = b then 1 else 0) :=
by by_cases h : a = b; simp [h]
theorem count_singleton (a : α) : count a (a ::ₘ 0) = 1 :=
by simp
@[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t :=
countp_add _
instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) :=
countp.is_add_monoid_hom _
@[simp] theorem count_smul (a : α) (n s) : count a (n •ℕ s) = n * count a s :=
by induction n; simp [*, succ_nsmul', succ_mul]
theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s :=
by simp [count, countp_pos]
@[simp, priority 980]
theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s :=
iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero
theorem count_ne_zero {a : α} {s : multiset α} : count a s ≠ 0 ↔ a ∈ s :=
by simp [ne.def, count_eq_zero]
@[simp] theorem count_repeat_self (a : α) (n : ℕ) : count a (repeat a n) = n :=
by simp [repeat]
theorem count_repeat (a b : α) (n : ℕ) :
count a (repeat b n) = if (a = b) then n else 0 :=
begin
split_ifs with h₁,
{ rw [h₁, count_repeat_self] },
{ rw [count_eq_zero],
apply mt eq_of_mem_repeat h₁ },
end
@[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) :=
begin
by_cases a ∈ s,
{ rw [(by rw cons_erase h : count a s = count a (a ::ₘ erase s a)),
count_cons_self]; refl },
{ rw [erase_of_not_mem h, count_eq_zero.2 h]; refl }
end
@[simp, priority 980]
theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s :=
begin
by_cases b ∈ s,
{ rw [← count_cons_of_ne ab, cons_erase h] },
{ rw [erase_of_not_mem h] }
end
@[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _),
rw [sub_cons, IH],
by_cases ab : a = b,
{ subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] },
{ rw [count_erase_of_ne ab, count_cons_of_ne ab] }
end
@[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) :=
by simp [(∪), union, sub_add_eq_max, -add_comm]
@[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) :=
begin
apply @nat.add_left_cancel (count a (s - t)),
rw [← count_add, sub_add_inter, count_sub, sub_add_min],
end
lemma count_sum {m : multiset β} {f : β → multiset α} {a : α} :
count a (map f m).sum = sum (m.map $ λb, count a $ f b) :=
multiset.induction_on m (by simp) ( by simp)
lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} :
count a (bind m f) = sum (m.map $ λb, count a $ f b) := count_sum
theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s :=
quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm
@[simp] theorem count_filter_of_pos {p} [decidable_pred p]
{a} {s : multiset α} (h : p a) : count a (filter p s) = count a s :=
quot.induction_on s $ λ l, count_filter h
@[simp] theorem count_filter_of_neg {p} [decidable_pred p]
{a} {s : multiset α} (h : ¬ p a) : count a (filter p s) = 0 :=
multiset.count_eq_zero_of_not_mem (λ t, h (of_mem_filter t))
theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t :=
quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count
@[ext]
theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t :=
ext.2
@[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) :=
by ext; simp
theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t :=
⟨λ h a, count_le_of_le a h, λ al,
by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t);
apply le_union_left⟩
instance : distrib_lattice (multiset α) :=
{ le_sup_inf := λ s t u, le_of_eq $ eq.symm $
ext.2 $ λ a, by simp only [max_min_distrib_left,
multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter],
..multiset.lattice }
instance : semilattice_sup_bot (multiset α) :=
{ bot := 0,
bot_le := zero_le,
..multiset.lattice }
end
@[simp]
lemma mem_nsmul {a : α} {s : multiset α} {n : ℕ} (h0 : n ≠ 0) :
a ∈ n •ℕ s ↔ a ∈ s :=
begin
classical,
cases n,
{ exfalso, apply h0 rfl },
rw [← not_iff_not, ← count_eq_zero, ← count_eq_zero],
simp [h0],
end
/- relator -/
section rel
/-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`,
s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/
@[mk_iff] inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop
| zero : rel 0 0
| cons {a b as bs} : r a b → rel as bs → rel (a ::ₘ as) (b ::ₘ bs)
variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s :=
rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih)
lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s :=
⟨rel_flip_aux, rel_flip_aux⟩
lemma rel_eq_refl {s : multiset α} : rel (=) s s :=
multiset.induction_on s rel.zero (assume a s, rel.cons rfl)
lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t :=
begin
split,
{ assume h, induction h; simp * },
{ assume h, subst h, exact rel_eq_refl }
end
lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t :=
begin
induction hst,
case rel.zero { exact rel.zero },
case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) }
end
lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) :=
begin
induction hst,
case rel.zero { simpa using huv },
case rel.cons : a b s t hab hst ih { simpa using ih.cons hab }
end
lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t :=
show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm]
@[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 :=
by rw [rel_iff]; simp
@[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 :=
by rw [rel_iff]; simp
lemma rel_cons_left {a as bs} :
rel r (a ::ₘ as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b ::ₘ bs') :=
begin
split,
{ generalize hm : a ::ₘ as = m,
assume h,
induction h generalizing as,
case rel.zero { simp at hm, contradiction },
case rel.cons : a' b as' bs ha'b h ih {
rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ },
{ rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩,
exact ⟨b', b ::ₘ bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ }
} },
{ exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h }
end
lemma rel_cons_right {as b bs} :
rel r as (b ::ₘ bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a ::ₘ as') :=
begin
rw [← rel_flip, rel_cons_left],
apply exists_congr, assume a,
apply exists_congr, assume as',
rw [rel_flip, flip]
end
lemma rel_add_left {as₀ as₁} :
∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) :=
multiset.induction_on as₀ (by simp)
begin
assume a s ih bs,
simp only [ih, cons_add, rel_cons_left],
split,
{ assume h,
rcases h with ⟨b, bs', hab, h, rfl⟩,
rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩,
exact ⟨b ::ₘ bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ },
{ assume h,
rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩,
rcases h with ⟨b, bs, hab, h₀, rfl⟩,
exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ }
end
lemma rel_add_right {as bs₀ bs₁} :
rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) :=
by rw [← rel_flip, rel_add_left]; simp [rel_flip]
lemma rel_map_left {s : multiset γ} {f : γ → α} :
∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t :=
multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt})
lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} :
rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t :=
by rw [← rel_flip, rel_map_left, ← rel_flip]; refl
lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join :=
begin
induction h,
case rel.zero { simp },
case rel.cons : a b s t hab hst ih { simpa using hab.add ih }
end
lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) :
rel p (s.map f) (t.map g) :=
by rw [rel_map_left, rel_map_right]; exact hst.mono h
lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ}
(h : (r ⇒ rel p) f g) (hst : rel r s t) :
rel p (s.bind f) (t.bind g) :=
by apply rel_join; apply rel_map; assumption
lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) :
card s = card t :=
by induction h; simp [*]
lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) :
∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b :=
begin
induction h with x y s t hxy hst ih,
{ simp },
{ assume a ha,
cases mem_cons.1 ha with ha ha,
{ exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ },
{ rcases ih ha with ⟨b, hbt, hab⟩,
exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } }
end
end rel
section map
theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} :
s.map f = t.map f ↔ s = t :=
by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff]
theorem map_injective {f : α → β} (hf : function.injective f) :
function.injective (multiset.map f) :=
assume x y, (map_eq_map hf).1
end map
section quot
theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) :
s.map (quot.mk r) = t.map (quot.mk r) :=
rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab]
theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) :
∃t:multiset α, s = t.map (quot.mk r) :=
multiset.induction_on s ⟨0, rfl⟩ $
assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a ::ₘ t, (map_cons _ _ _).symm⟩
theorem induction_on_multiset_quot
{r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) :
(∀s:multiset α, p (s.map (quot.mk r))) → p s :=
match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end
end quot
/- disjoint -/
/-- `disjoint s t` means that `s` and `t` have no elements in common. -/
def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false
@[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl
theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s
| a i₂ i₁ := d i₁ i₂
theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl
theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
disjoint_comm
theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp [disjoint_left, imp_not_comm]
theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t
| x m₁ := d (h m₁)
theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t
| x m m₁ := d m (h m₁)
theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t :=
disjoint_of_subset_left (subset_of_le h)
theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t :=
disjoint_of_subset_right (subset_of_le h)
@[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l
| a := (not_mem_nil a).elim
@[simp, priority 1100]
theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a ::ₘ 0) l ↔ a ∉ l :=
by simp [disjoint]; refl
@[simp, priority 1100]
theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a ::ₘ 0) ↔ a ∉ l :=
by rw disjoint_comm; simp
@[simp] theorem disjoint_add_left {s t u : multiset α} :
disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_add_right {s t u : multiset α} :
disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u :=
by rw [disjoint_comm, disjoint_add_left]; tauto
@[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} :
disjoint (a ::ₘ s) t ↔ a ∉ t ∧ disjoint s t :=
(@disjoint_add_left _ (a ::ₘ 0) s t).trans $ by simp
@[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} :
disjoint s (a ::ₘ t) ↔ a ∉ s ∧ disjoint s t :=
by rw [disjoint_comm, disjoint_cons_left]; tauto
theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
@[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} :
disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) :=
by { simp [disjoint, @eq_comm _ (f _) (g _)], refl }
/-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/
def pairwise (r : α → α → Prop) (m : multiset α) : Prop :=
∃l:list α, m = l ∧ l.pairwise r
lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} :
multiset.pairwise r l ↔ l.pairwise r :=
iff.intro
(assume ⟨l', eq, h⟩, ((quotient.exact eq).pairwise_iff hr).2 h)
(assume h, ⟨l, rfl, h⟩)
end multiset
namespace multiset
section choose
variables (p : α → Prop) [decidable_pred p] (l : multiset α)
/-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose p l hp` returns
that `a`. -/
def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } :=
quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin
intros,
funext hp,
suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y,
{ apply all_equal },
{ rintros ⟨x, px⟩ ⟨y, py⟩,
rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩,
congr,
calc x = z : z_unique x px
... = y : (z_unique y py).symm }
end
def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp
lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
variable (α)
/-- The equivalence between lists and multisets of a subsingleton type. -/
def subsingleton_equiv [subsingleton α] : list α ≃ multiset α :=
{ to_fun := coe,
inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b),
list.ext_le h.length_eq $ λ n h₁ h₂, subsingleton.elim _ _,
left_inv := λ l, rfl,
right_inv := λ m, quot.induction_on m $ λ l, rfl }
end multiset
@[to_additive]
theorem monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β) (s : multiset α) :
f s.prod = (s.map f).prod :=
(s.prod_hom f).symm
|
cdd6526859c15b00a5ec7b62f7826be1c4273bd9
|
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
|
/library/algebra/group.lean
|
75b2d5b453be3c709905de6e71f89c84c71d797e
|
[
"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
| 21,667
|
lean
|
/-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
Various multiplicative and additive structures. Partially modeled on Isabelle's library.
-/
import logic.eq data.unit data.sigma data.prod
import algebra.binary algebra.priority
open binary
variable {A : Type}
/- semigroup -/
attribute inv [light 3]
attribute neg [light 3]
structure semigroup [class] (A : Type) extends has_mul A :=
(mul_assoc : ∀a b c, mul (mul a b) c = mul a (mul b c))
-- We add pattern hints to the following lemma because we want it to be used in both directions
-- at inst_simp strategy.
theorem mul.assoc [simp] [semigroup A] (a b c : A) : (: a * b * c :) = (: a * (b * c) :) :=
!semigroup.mul_assoc
structure comm_semigroup [class] (A : Type) extends semigroup A :=
(mul_comm : ∀a b, mul a b = mul b a)
theorem mul.comm [simp] [comm_semigroup A] (a b : A) : a * b = b * a :=
!comm_semigroup.mul_comm
theorem mul.left_comm [simp] [comm_semigroup A] (a b c : A) : a * (b * c) = b * (a * c) :=
binary.left_comm (@mul.comm A _) (@mul.assoc A _) a b c
theorem mul.right_comm [comm_semigroup A] (a b c : A) : (a * b) * c = (a * c) * b :=
by simp
structure left_cancel_semigroup [class] (A : Type) extends semigroup A :=
(mul_left_cancel : ∀a b c, mul a b = mul a c → b = c)
theorem mul.left_cancel [left_cancel_semigroup A] {a b c : A} : a * b = a * c → b = c :=
!left_cancel_semigroup.mul_left_cancel
abbreviation eq_of_mul_eq_mul_left' := @mul.left_cancel
structure right_cancel_semigroup [class] (A : Type) extends semigroup A :=
(mul_right_cancel : ∀a b c, mul a b = mul c b → a = c)
theorem mul.right_cancel [right_cancel_semigroup A] {a b c : A} : a * b = c * b → a = c :=
!right_cancel_semigroup.mul_right_cancel
abbreviation eq_of_mul_eq_mul_right' := @mul.right_cancel
/- additive semigroup -/
structure add_semigroup [class] (A : Type) extends has_add A :=
(add_assoc : ∀a b c, add (add a b) c = add a (add b c))
theorem add.assoc [simp] [add_semigroup A] (a b c : A) : (: a + b + c :) = (: a + (b + c) :) :=
!add_semigroup.add_assoc
structure add_comm_semigroup [class] (A : Type) extends add_semigroup A :=
(add_comm : ∀a b, add a b = add b a)
theorem add.comm [simp] [add_comm_semigroup A] (a b : A) : a + b = b + a :=
!add_comm_semigroup.add_comm
theorem add.left_comm [simp] [add_comm_semigroup A] (a b c : A) : a + (b + c) = b + (a + c) :=
binary.left_comm (@add.comm A _) (@add.assoc A _) a b c
theorem add.right_comm [add_comm_semigroup A] (a b c : A) : (a + b) + c = (a + c) + b :=
by simp
structure add_left_cancel_semigroup [class] (A : Type) extends add_semigroup A :=
(add_left_cancel : ∀a b c, add a b = add a c → b = c)
theorem add.left_cancel [add_left_cancel_semigroup A] {a b c : A} : a + b = a + c → b = c :=
!add_left_cancel_semigroup.add_left_cancel
abbreviation eq_of_add_eq_add_left := @add.left_cancel
structure add_right_cancel_semigroup [class] (A : Type) extends add_semigroup A :=
(add_right_cancel : ∀a b c, add a b = add c b → a = c)
theorem add.right_cancel [add_right_cancel_semigroup A] {a b c : A} : a + b = c + b → a = c :=
!add_right_cancel_semigroup.add_right_cancel
abbreviation eq_of_add_eq_add_right := @add.right_cancel
/- monoid -/
structure monoid [class] (A : Type) extends semigroup A, has_one A :=
(one_mul : ∀a, mul one a = a) (mul_one : ∀a, mul a one = a)
theorem one_mul [simp] [monoid A] (a : A) : 1 * a = a := !monoid.one_mul
theorem mul_one [simp] [monoid A] (a : A) : a * 1 = a := !monoid.mul_one
structure comm_monoid [class] (A : Type) extends monoid A, comm_semigroup A
/- additive monoid -/
structure add_monoid [class] (A : Type) extends add_semigroup A, has_zero A :=
(zero_add : ∀a, add zero a = a) (add_zero : ∀a, add a zero = a)
theorem zero_add [simp] [add_monoid A] (a : A) : 0 + a = a := !add_monoid.zero_add
theorem add_zero [simp] [add_monoid A] (a : A) : a + 0 = a := !add_monoid.add_zero
structure add_comm_monoid [class] (A : Type) extends add_monoid A, add_comm_semigroup A
definition add_monoid.to_monoid {A : Type} [add_monoid A] : monoid A :=
⦃ monoid,
mul := add_monoid.add,
mul_assoc := add_monoid.add_assoc,
one := add_monoid.zero A,
mul_one := add_monoid.add_zero,
one_mul := add_monoid.zero_add
⦄
definition add_comm_monoid.to_comm_monoid {A : Type} [add_comm_monoid A] : comm_monoid A :=
⦃ comm_monoid,
add_monoid.to_monoid,
mul_comm := add_comm_monoid.add_comm
⦄
section add_comm_monoid
variables [add_comm_monoid A]
theorem add_comm_three (a b c : A) : a + b + c = c + b + a :=
by simp
theorem add.comm4 : ∀ (n m k l : A), n + m + (k + l) = n + k + (m + l) :=
by simp
end add_comm_monoid
/- group -/
structure group [class] (A : Type) extends monoid A, has_inv A :=
(mul_left_inv : ∀a, mul (inv a) a = one)
-- Note: with more work, we could derive the axiom one_mul
section group
variable [group A]
theorem mul.left_inv [simp] (a : A) : a⁻¹ * a = 1 := !group.mul_left_inv
theorem inv_mul_cancel_left [simp] (a b : A) : a⁻¹ * (a * b) = b :=
by rewrite [-mul.assoc, mul.left_inv, one_mul]
theorem inv_mul_cancel_right [simp] (a b : A) : a * b⁻¹ * b = a :=
by simp
theorem inv_eq_of_mul_eq_one {a b : A} (H : a * b = 1) : a⁻¹ = b :=
assert a⁻¹ * 1 = b, by inst_simp,
by inst_simp
theorem one_inv [simp] : 1⁻¹ = (1 : A) :=
inv_eq_of_mul_eq_one (one_mul 1)
theorem inv_inv [simp] (a : A) : (a⁻¹)⁻¹ = a :=
inv_eq_of_mul_eq_one (mul.left_inv a)
theorem inv.inj {a b : A} (H : a⁻¹ = b⁻¹) : a = b :=
assert a = a⁻¹⁻¹, by simp_nohyps,
by inst_simp
theorem inv_eq_inv_iff_eq (a b : A) : a⁻¹ = b⁻¹ ↔ a = b :=
iff.intro (assume H, inv.inj H) (by simp)
theorem inv_eq_one_iff_eq_one (a : A) : a⁻¹ = 1 ↔ a = 1 :=
assert a⁻¹ = 1⁻¹ ↔ a = 1, from inv_eq_inv_iff_eq a 1,
by simp
theorem eq_one_of_inv_eq_one (a : A) : a⁻¹ = 1 → a = 1 :=
iff.mp !inv_eq_one_iff_eq_one
theorem eq_inv_of_eq_inv {a b : A} (H : a = b⁻¹) : b = a⁻¹ :=
by simp
theorem eq_inv_iff_eq_inv (a b : A) : a = b⁻¹ ↔ b = a⁻¹ :=
iff.intro !eq_inv_of_eq_inv !eq_inv_of_eq_inv
theorem eq_inv_of_mul_eq_one {a b : A} (H : a * b = 1) : a = b⁻¹ :=
assert a⁻¹ = b, from inv_eq_of_mul_eq_one H,
by inst_simp
theorem mul.right_inv [simp] (a : A) : a * a⁻¹ = 1 :=
assert a = a⁻¹⁻¹, by simp,
by inst_simp
theorem mul_inv_cancel_left [simp] (a b : A) : a * (a⁻¹ * b) = b :=
by inst_simp
theorem mul_inv_cancel_right [simp] (a b : A) : a * b * b⁻¹ = a :=
by inst_simp
theorem mul_inv [simp] (a b : A) : (a * b)⁻¹ = b⁻¹ * a⁻¹ :=
inv_eq_of_mul_eq_one (by inst_simp)
theorem eq_of_mul_inv_eq_one {a b : A} (H : a * b⁻¹ = 1) : a = b :=
assert a⁻¹ * 1 = a⁻¹, by inst_simp,
by inst_simp
theorem eq_mul_inv_of_mul_eq {a b c : A} (H : a * c = b) : a = b * c⁻¹ :=
by simp
theorem eq_inv_mul_of_mul_eq {a b c : A} (H : b * a = c) : a = b⁻¹ * c :=
by simp
theorem inv_mul_eq_of_eq_mul {a b c : A} (H : b = a * c) : a⁻¹ * b = c :=
by simp
theorem mul_inv_eq_of_eq_mul {a b c : A} (H : a = c * b) : a * b⁻¹ = c :=
by simp
theorem eq_mul_of_mul_inv_eq {a b c : A} (H : a * c⁻¹ = b) : a = b * c :=
by simp
theorem eq_mul_of_inv_mul_eq {a b c : A} (H : b⁻¹ * a = c) : a = b * c :=
by simp
theorem mul_eq_of_eq_inv_mul {a b c : A} (H : b = a⁻¹ * c) : a * b = c :=
by simp
theorem mul_eq_of_eq_mul_inv {a b c : A} (H : a = c * b⁻¹) : a * b = c :=
by simp
theorem mul_eq_iff_eq_inv_mul (a b c : A) : a * b = c ↔ b = a⁻¹ * c :=
iff.intro eq_inv_mul_of_mul_eq mul_eq_of_eq_inv_mul
theorem mul_eq_iff_eq_mul_inv (a b c : A) : a * b = c ↔ a = c * b⁻¹ :=
iff.intro eq_mul_inv_of_mul_eq mul_eq_of_eq_mul_inv
theorem mul_left_cancel {a b c : A} (H : a * b = a * c) : b = c :=
assert a⁻¹ * (a * b) = b, by inst_simp,
by inst_simp
theorem mul_right_cancel {a b c : A} (H : a * b = c * b) : a = c :=
assert a * b * b⁻¹ = a, by inst_simp,
by inst_simp
theorem mul_eq_one_of_mul_eq_one {a b : A} (H : b * a = 1) : a * b = 1 :=
by rewrite [-inv_eq_of_mul_eq_one H, mul.left_inv]
theorem mul_eq_one_iff_mul_eq_one (a b : A) : a * b = 1 ↔ b * a = 1 :=
iff.intro !mul_eq_one_of_mul_eq_one !mul_eq_one_of_mul_eq_one
definition conj_by (g a : A) := g * a * g⁻¹
definition is_conjugate (a b : A) := ∃ x, conj_by x b = a
local infixl ` ~ ` := is_conjugate
local infixr ` ∘c `:55 := conj_by
local attribute conj_by [reducible]
lemma conj_compose [simp] (f g a : A) : f ∘c g ∘c a = f*g ∘c a :=
by inst_simp
lemma conj_id [simp] (a : A) : 1 ∘c a = a :=
by inst_simp
lemma conj_one [simp] (g : A) : g ∘c 1 = 1 :=
by inst_simp
lemma conj_inv_cancel [simp] (g : A) : ∀ a, g⁻¹ ∘c g ∘c a = a :=
by inst_simp
lemma conj_inv [simp] (g : A) : ∀ a, (g ∘c a)⁻¹ = g ∘c a⁻¹ :=
by inst_simp
lemma is_conj.refl (a : A) : a ~ a := exists.intro 1 (conj_id a)
lemma is_conj.symm (a b : A) : a ~ b → b ~ a :=
assume Pab, obtain x (Pconj : x ∘c b = a), from Pab,
assert Pxinv : x⁻¹ ∘c x ∘c b = x⁻¹ ∘c a, by simp,
exists.intro x⁻¹ (by simp)
lemma is_conj.trans (a b c : A) : a ~ b → b ~ c → a ~ c :=
assume Pab, assume Pbc,
obtain x (Px : x ∘c b = a), from Pab,
obtain y (Py : y ∘c c = b), from Pbc,
exists.intro (x*y) (by inst_simp)
end group
definition group.to_left_cancel_semigroup [trans_instance] [reducible] [s : group A] :
left_cancel_semigroup A :=
⦃ left_cancel_semigroup, s,
mul_left_cancel := @mul_left_cancel A s ⦄
definition group.to_right_cancel_semigroup [trans_instance] [reducible] [s : group A] :
right_cancel_semigroup A :=
⦃ right_cancel_semigroup, s,
mul_right_cancel := @mul_right_cancel A s ⦄
structure comm_group [class] (A : Type) extends group A, comm_monoid A
/- additive group -/
structure add_group [class] (A : Type) extends add_monoid A, has_neg A :=
(add_left_inv : ∀a, add (neg a) a = zero)
definition add_group.to_group {A : Type} [add_group A] : group A :=
⦃ group, add_monoid.to_monoid,
mul_left_inv := add_group.add_left_inv ⦄
section add_group
variables [s : add_group A]
include s
theorem add.left_inv [simp] (a : A) : -a + a = 0 := !add_group.add_left_inv
theorem neg_add_cancel_left [simp] (a b : A) : -a + (a + b) = b :=
calc -a + (a + b) = (-a + a) + b : by rewrite add.assoc
... = b : by simp
theorem neg_add_cancel_right [simp] (a b : A) : a + -b + b = a :=
by simp
theorem neg_eq_of_add_eq_zero {a b : A} (H : a + b = 0) : -a = b :=
assert -a + 0 = b, by inst_simp,
by inst_simp
theorem neg_zero [simp] : -0 = (0 : A) := neg_eq_of_add_eq_zero (zero_add 0)
theorem neg_neg [simp] (a : A) : -(-a) = a := neg_eq_of_add_eq_zero (add.left_inv a)
theorem eq_neg_of_add_eq_zero {a b : A} (H : a + b = 0) : a = -b :=
assert -a = b, from neg_eq_of_add_eq_zero H,
by inst_simp
theorem neg.inj {a b : A} (H : -a = -b) : a = b :=
assert a = -(-a), by simp_nohyps,
by inst_simp
theorem neg_eq_neg_iff_eq (a b : A) : -a = -b ↔ a = b :=
iff.intro (assume H, neg.inj H) (by simp)
theorem eq_of_neg_eq_neg {a b : A} : -a = -b → a = b :=
iff.mp !neg_eq_neg_iff_eq
theorem neg_eq_zero_iff_eq_zero (a : A) : -a = 0 ↔ a = 0 :=
assert -a = -0 ↔ a = 0, from neg_eq_neg_iff_eq a 0,
by simp
theorem eq_zero_of_neg_eq_zero {a : A} : -a = 0 → a = 0 :=
iff.mp !neg_eq_zero_iff_eq_zero
theorem eq_neg_of_eq_neg {a b : A} (H : a = -b) : b = -a :=
by simp
theorem eq_neg_iff_eq_neg (a b : A) : a = -b ↔ b = -a :=
iff.intro !eq_neg_of_eq_neg !eq_neg_of_eq_neg
theorem add.right_inv [simp] (a : A) : a + -a = 0 :=
assert a = -(-a), by simp,
by inst_simp
theorem add_neg_cancel_left [simp] (a b : A) : a + (-a + b) = b :=
by inst_simp
theorem add_neg_cancel_right [simp] (a b : A) : a + b + -b = a :=
by simp
theorem neg_add_rev [simp] (a b : A) : -(a + b) = -b + -a :=
neg_eq_of_add_eq_zero (by simp)
-- TODO: delete these in favor of sub rules?
theorem eq_add_neg_of_add_eq {a b c : A} (H : a + c = b) : a = b + -c :=
by simp
theorem eq_neg_add_of_add_eq {a b c : A} (H : b + a = c) : a = -b + c :=
by simp
theorem neg_add_eq_of_eq_add {a b c : A} (H : b = a + c) : -a + b = c :=
by simp
theorem add_neg_eq_of_eq_add {a b c : A} (H : a = c + b) : a + -b = c :=
by simp
theorem eq_add_of_add_neg_eq {a b c : A} (H : a + -c = b) : a = b + c :=
by simp
theorem eq_add_of_neg_add_eq {a b c : A} (H : -b + a = c) : a = b + c :=
by simp
theorem add_eq_of_eq_neg_add {a b c : A} (H : b = -a + c) : a + b = c :=
by simp
theorem add_eq_of_eq_add_neg {a b c : A} (H : a = c + -b) : a + b = c :=
by simp
theorem add_eq_iff_eq_neg_add (a b c : A) : a + b = c ↔ b = -a + c :=
iff.intro eq_neg_add_of_add_eq add_eq_of_eq_neg_add
theorem add_eq_iff_eq_add_neg (a b c : A) : a + b = c ↔ a = c + -b :=
iff.intro eq_add_neg_of_add_eq add_eq_of_eq_add_neg
theorem add_left_cancel {a b c : A} (H : a + b = a + c) : b = c :=
assert -a + (a + b) = b, by inst_simp,
by inst_simp
theorem add_right_cancel {a b c : A} (H : a + b = c + b) : a = c :=
assert a + b + -b = a, by inst_simp,
by inst_simp
definition add_group.to_left_cancel_semigroup [trans_instance] [reducible] :
add_left_cancel_semigroup A :=
⦃ add_left_cancel_semigroup, s,
add_left_cancel := @add_left_cancel A s ⦄
definition add_group.to_add_right_cancel_semigroup [trans_instance] [reducible] :
add_right_cancel_semigroup A :=
⦃ add_right_cancel_semigroup, s,
add_right_cancel := @add_right_cancel A s ⦄
theorem add_neg_eq_neg_add_rev {a b : A} : a + -b = -(b + -a) :=
by simp
theorem ne_add_of_ne_zero_right (a : A) {b : A} (H : b ≠ 0) : a ≠ b + a :=
begin
intro Heq,
apply H,
rewrite [-zero_add a at Heq{1}],
let Heq' := eq_of_add_eq_add_right Heq,
apply eq.symm Heq'
end
theorem ne_add_of_ne_zero_left (a : A) {b : A} (H : b ≠ 0) : a ≠ a + b :=
begin
intro Heq,
apply H,
rewrite [-add_zero a at Heq{1}],
let Heq' := eq_of_add_eq_add_left Heq,
apply eq.symm Heq'
end
/- sub -/
-- TODO: derive corresponding facts for div in a field
protected definition algebra.sub [reducible] (a b : A) : A := a + -b
definition add_group_has_sub [reducible] [instance] : has_sub A :=
has_sub.mk algebra.sub
theorem sub_eq_add_neg [simp] (a b : A) : a - b = a + -b := rfl
theorem sub_self (a : A) : a - a = 0 := !add.right_inv
theorem sub_add_cancel (a b : A) : a - b + b = a := !neg_add_cancel_right
theorem add_sub_cancel (a b : A) : a + b - b = a := !add_neg_cancel_right
theorem add_sub_assoc (a b c : A) : a + b - c = a + (b - c) :=
by rewrite [sub_eq_add_neg, add.assoc, -sub_eq_add_neg]
theorem eq_of_sub_eq_zero {a b : A} (H : a - b = 0) : a = b :=
assert -a + 0 = -a, by inst_simp,
by inst_simp
theorem eq_iff_sub_eq_zero (a b : A) : a = b ↔ a - b = 0 :=
iff.intro (assume H, eq.subst H !sub_self) (assume H, eq_of_sub_eq_zero H)
theorem zero_sub (a : A) : 0 - a = -a := !zero_add
theorem sub_zero (a : A) : a - 0 = a :=
by simp
theorem sub_ne_zero_of_ne {a b : A} (H : a ≠ b) : a - b ≠ 0 :=
begin
intro Hab,
apply H,
apply eq_of_sub_eq_zero Hab
end
theorem sub_neg_eq_add (a b : A) : a - (-b) = a + b :=
by simp
theorem neg_sub (a b : A) : -(a - b) = b - a :=
neg_eq_of_add_eq_zero (by inst_simp)
theorem add_sub (a b c : A) : a + (b - c) = a + b - c :=
by simp
theorem sub_add_eq_sub_sub_swap (a b c : A) : a - (b + c) = a - c - b :=
by inst_simp
theorem sub_eq_iff_eq_add (a b c : A) : a - b = c ↔ a = c + b :=
iff.intro (assume H, eq_add_of_add_neg_eq H) (assume H, add_neg_eq_of_eq_add H)
theorem eq_sub_iff_add_eq (a b c : A) : a = b - c ↔ a + c = b :=
iff.intro (assume H, add_eq_of_eq_add_neg H) (assume H, eq_add_neg_of_add_eq H)
theorem eq_iff_eq_of_sub_eq_sub {a b c d : A} (H : a - b = c - d) : a = b ↔ c = d :=
calc
a = b ↔ a - b = 0 : eq_iff_sub_eq_zero
... = (c - d = 0) : H
... ↔ c = d : iff.symm (eq_iff_sub_eq_zero c d)
theorem eq_sub_of_add_eq {a b c : A} (H : a + c = b) : a = b - c :=
by simp
theorem sub_eq_of_eq_add {a b c : A} (H : a = c + b) : a - b = c :=
by simp
theorem eq_add_of_sub_eq {a b c : A} (H : a - c = b) : a = b + c :=
by simp
theorem add_eq_of_eq_sub {a b c : A} (H : a = c - b) : a + b = c :=
by simp
end add_group
structure add_comm_group [class] (A : Type) extends add_group A, add_comm_monoid A
section add_comm_group
variable [s : add_comm_group A]
include s
theorem sub_add_eq_sub_sub (a b c : A) : a - (b + c) = a - b - c :=
by simp
theorem neg_add_eq_sub (a b : A) : -a + b = b - a :=
by simp
theorem neg_add (a b : A) : -(a + b) = -a + -b :=
by simp
theorem sub_add_eq_add_sub (a b c : A) : a - b + c = a + c - b :=
by simp
theorem sub_sub (a b c : A) : a - b - c = a - (b + c) :=
by simp
theorem add_sub_add_left_eq_sub (a b c : A) : (c + a) - (c + b) = a - b :=
by simp
theorem eq_sub_of_add_eq' {a b c : A} (H : c + a = b) : a = b - c :=
by simp
theorem sub_eq_of_eq_add' {a b c : A} (H : a = b + c) : a - b = c :=
by simp
theorem eq_add_of_sub_eq' {a b c : A} (H : a - b = c) : a = b + c :=
by simp
theorem add_eq_of_eq_sub' {a b c : A} (H : b = c - a) : a + b = c :=
by simp
theorem sub_sub_self (a b : A) : a - (a - b) = b :=
by simp
theorem add_sub_comm (a b c d : A) : a + b - (c + d) = (a - c) + (b - d) :=
by simp
theorem sub_eq_sub_add_sub (a b c : A) : a - b = c - b + (a - c) :=
by simp
theorem neg_neg_sub_neg (a b : A) : - (-a - -b) = a - b :=
by simp
end add_comm_group
definition group_of_add_group (A : Type) [G : add_group A] : group A :=
⦃group,
mul := has_add.add,
mul_assoc := add.assoc,
one := !has_zero.zero,
one_mul := zero_add,
mul_one := add_zero,
inv := has_neg.neg,
mul_left_inv := add.left_inv⦄
namespace norm_num
reveal add.assoc
definition add1 [has_add A] [has_one A] (a : A) : A := add a one
local attribute add1 bit0 bit1 [reducible]
theorem add_comm_four [add_comm_semigroup A] (a b : A) : a + a + (b + b) = (a + b) + (a + b) :=
by simp
theorem add_comm_middle [add_comm_semigroup A] (a b c : A) : a + b + c = a + c + b :=
by simp
theorem bit0_add_bit0 [add_comm_semigroup A] (a b : A) : bit0 a + bit0 b = bit0 (a + b) :=
by simp
theorem bit0_add_bit0_helper [add_comm_semigroup A] (a b t : A) (H : a + b = t) :
bit0 a + bit0 b = bit0 t :=
by rewrite -H; simp
theorem bit1_add_bit0 [add_comm_semigroup A] [has_one A] (a b : A) :
bit1 a + bit0 b = bit1 (a + b) :=
by simp
theorem bit1_add_bit0_helper [add_comm_semigroup A] [has_one A] (a b t : A)
(H : a + b = t) : bit1 a + bit0 b = bit1 t :=
by rewrite -H; simp
theorem bit0_add_bit1 [add_comm_semigroup A] [has_one A] (a b : A) :
bit0 a + bit1 b = bit1 (a + b) :=
by simp
theorem bit0_add_bit1_helper [add_comm_semigroup A] [has_one A] (a b t : A)
(H : a + b = t) : bit0 a + bit1 b = bit1 t :=
by rewrite -H; simp
theorem bit1_add_bit1 [add_comm_semigroup A] [has_one A] (a b : A) :
bit1 a + bit1 b = bit0 (add1 (a + b)) :=
by simp
theorem bit1_add_bit1_helper [add_comm_semigroup A] [has_one A] (a b t s: A)
(H : (a + b) = t) (H2 : add1 t = s) : bit1 a + bit1 b = bit0 s :=
by inst_simp
theorem bin_add_zero [add_monoid A] (a : A) : a + zero = a :=
by simp
theorem bin_zero_add [add_monoid A] (a : A) : zero + a = a :=
by simp
theorem one_add_bit0 [add_comm_semigroup A] [has_one A] (a : A) : one + bit0 a = bit1 a :=
by simp
theorem bit0_add_one [has_add A] [has_one A] (a : A) : bit0 a + one = bit1 a :=
rfl
theorem bit1_add_one [has_add A] [has_one A] (a : A) : bit1 a + one = add1 (bit1 a) :=
rfl
theorem bit1_add_one_helper [has_add A] [has_one A] (a t : A) (H : add1 (bit1 a) = t) :
bit1 a + one = t :=
by inst_simp
theorem one_add_bit1 [add_comm_semigroup A] [has_one A] (a : A) : one + bit1 a = add1 (bit1 a) :=
by simp
theorem one_add_bit1_helper [add_comm_semigroup A] [has_one A] (a t : A)
(H : add1 (bit1 a) = t) : one + bit1 a = t :=
by inst_simp
theorem add1_bit0 [has_add A] [has_one A] (a : A) : add1 (bit0 a) = bit1 a :=
rfl
theorem add1_bit1 [add_comm_semigroup A] [has_one A] (a : A) :
add1 (bit1 a) = bit0 (add1 a) :=
by simp
theorem add1_bit1_helper [add_comm_semigroup A] [has_one A] (a t : A) (H : add1 a = t) :
add1 (bit1 a) = bit0 t :=
by inst_simp
theorem add1_one [has_add A] [has_one A] : add1 (one : A) = bit0 one :=
rfl
theorem add1_zero [add_monoid A] [has_one A] : add1 (zero : A) = one :=
by simp
theorem one_add_one [has_add A] [has_one A] : (one : A) + one = bit0 one :=
rfl
theorem subst_into_sum [has_add A] (l r tl tr t : A) (prl : l = tl) (prr : r = tr)
(prt : tl + tr = t) : l + r = t :=
by simp
theorem neg_zero_helper [add_group A] (a : A) (H : a = 0) : - a = 0 :=
by simp
end norm_num
attribute [simp]
zero_add add_zero one_mul mul_one
at simplifier.unit
attribute [simp]
neg_neg sub_eq_add_neg
at simplifier.neg
attribute [simp]
add.assoc add.comm add.left_comm
mul.left_comm mul.comm mul.assoc
at simplifier.ac
|
4954dfbb6a709a4971056c3e80bd2d5133901c22
|
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
|
/src/Lean/Server/Rpc.lean
|
d4d6c0ab0ca918792d06c9496140a766f7362858
|
[
"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
| 265
|
lean
|
/-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Wojciech Nawrocki
-/
import Lean.Server.Rpc.Basic
import Lean.Server.Rpc.Deriving
import Lean.Server.Rpc.RequestHandling
|
1f62aa9217fe7bd48352b51254c7aa55ec6bc16c
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/src/topology/algebra/infinite_sum/basic.lean
|
69334b3838d575a1633f47b7aa64c9fd236ae2cf
|
[
"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
| 59,291
|
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.nat.parity
import logic.encodable.lattice
import topology.algebra.uniform_group
import topology.algebra.star
/-!
# Infinite sum over a topological monoid
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This sum is known as unconditionally convergent, as it sums to the same value under all possible
permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute
convergence.
Note: There are summable sequences which are not unconditionally convergent! The other way holds
generally, see `has_sum.tendsto_sum_nat`.
## References
* Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups)
-/
noncomputable theory
open classical filter finset function
open_locale big_operators classical topology
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
section has_sum
variables [add_comm_monoid α] [topological_space α]
/-- Infinite sum on a topological monoid
The `at_top` filter on `finset β` is the limit of all finite sets towards the entire type. So we sum
up bigger and bigger sets. This sum operation is invariant under reordering. In particular,
the function `ℕ → ℝ` sending `n` to `(-1)^n / (n+1)` does not have a
sum for this definition, but a series which is absolutely convergent will have the correct sum.
This is based on Mario Carneiro's
[infinite sum `df-tsms` in Metamath](http://us.metamath.org/mpeuni/df-tsms.html).
For the definition or many statements, `α` does not need to be a topological monoid. We only add
this assumption later, for the lemmas where it is relevant.
-/
def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, ∑ b in s, f b) at_top (𝓝 a)
/-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/
def summable (f : β → α) : Prop := ∃a, has_sum f a
/-- `∑' i, f i` is the sum of `f` it exists, or 0 otherwise -/
@[irreducible] def tsum {β} (f : β → α) := if h : summable f then classical.some h else 0
-- see Note [operator precedence of big operators]
notation `∑'` binders `, ` r:(scoped:67 f, tsum f) := r
variables {f g : β → α} {a b : α} {s : finset β}
lemma summable.has_sum (ha : summable f) : has_sum f (∑'b, f b) :=
by simp [ha, tsum]; exact some_spec ha
lemma has_sum.summable (h : has_sum f a) : summable f := ⟨a, h⟩
/-- Constant zero function has sum `0` -/
lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 :=
by simp [has_sum, tendsto_const_nhds]
lemma has_sum_empty [is_empty β] : has_sum f 0 :=
by convert has_sum_zero
lemma summable_zero : summable (λb, 0 : β → α) := has_sum_zero.summable
lemma summable_empty [is_empty β] : summable f := has_sum_empty.summable
lemma tsum_eq_zero_of_not_summable (h : ¬ summable f) : ∑'b, f b = 0 :=
by simp [tsum, h]
lemma summable_congr (hfg : ∀b, f b = g b) :
summable f ↔ summable g :=
iff_of_eq (congr_arg summable $ funext hfg)
lemma summable.congr (hf : summable f) (hfg : ∀b, f b = g b) :
summable g :=
(summable_congr hfg).mp hf
lemma has_sum.has_sum_of_sum_eq {g : γ → α}
(h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b)
(hf : has_sum g a) :
has_sum f a :=
le_trans (map_at_top_finset_sum_le_of_sum_eq h_eq) hf
lemma has_sum_iff_has_sum {g : γ → α}
(h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b)
(h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ ∑ b in v', f b = ∑ x in u', g x) :
has_sum f a ↔ has_sum g a :=
⟨has_sum.has_sum_of_sum_eq h₂, has_sum.has_sum_of_sum_eq h₁⟩
lemma function.injective.has_sum_iff {g : γ → β} (hg : injective g)
(hf : ∀ x ∉ set.range g, f x = 0) :
has_sum (f ∘ g) a ↔ has_sum f a :=
by simp only [has_sum, tendsto, hg.map_at_top_finset_sum_eq hf]
lemma function.injective.summable_iff {g : γ → β} (hg : injective g)
(hf : ∀ x ∉ set.range g, f x = 0) :
summable (f ∘ g) ↔ summable f :=
exists_congr $ λ _, hg.has_sum_iff hf
lemma has_sum_subtype_iff_of_support_subset {s : set β} (hf : support f ⊆ s) :
has_sum (f ∘ coe : s → α) a ↔ has_sum f a :=
subtype.coe_injective.has_sum_iff $ by simpa using support_subset_iff'.1 hf
lemma has_sum_subtype_iff_indicator {s : set β} :
has_sum (f ∘ coe : s → α) a ↔ has_sum (s.indicator f) a :=
by rw [← set.indicator_range_comp, subtype.range_coe,
has_sum_subtype_iff_of_support_subset set.support_indicator_subset]
lemma summable_subtype_iff_indicator {s : set β} :
summable (f ∘ coe : s → α) ↔ summable (s.indicator f) :=
exists_congr (λ _, has_sum_subtype_iff_indicator)
@[simp] lemma has_sum_subtype_support : has_sum (f ∘ coe : support f → α) a ↔ has_sum f a :=
has_sum_subtype_iff_of_support_subset $ set.subset.refl _
lemma has_sum_fintype [fintype β] (f : β → α) : has_sum f (∑ b, f b) :=
order_top.tendsto_at_top_nhds _
protected lemma finset.has_sum (s : finset β) (f : β → α) :
has_sum (f ∘ coe : (↑s : set β) → α) (∑ b in s, f b) :=
by { rw ← sum_attach, exact has_sum_fintype _ }
protected lemma finset.summable (s : finset β) (f : β → α) :
summable (f ∘ coe : (↑s : set β) → α) :=
(s.has_sum f).summable
protected lemma set.finite.summable {s : set β} (hs : s.finite) (f : β → α) :
summable (f ∘ coe : s → α) :=
by convert hs.to_finset.summable f; simp only [hs.coe_to_finset]
/-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `∑ b in s, f b`. -/
lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (∑ b in s, f b) :=
(has_sum_subtype_iff_of_support_subset $ support_subset_iff'.2 hf).1 $ s.has_sum f
lemma summable_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f :=
(has_sum_sum_of_ne_finset_zero hf).summable
lemma has_sum_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) :
has_sum f (f b) :=
suffices has_sum f (∑ b' in {b}, f b'),
by simpa using this,
has_sum_sum_of_ne_finset_zero $ by simpa [hf]
lemma has_sum_ite_eq (b : β) [decidable_pred (= b)] (a : α) :
has_sum (λb', if b' = b then a else 0) a :=
begin
convert has_sum_single b _,
{ exact (if_pos rfl).symm },
assume b' hb',
exact if_neg hb'
end
lemma has_sum_pi_single [decidable_eq β] (b : β) (a : α) :
has_sum (pi.single b a) a :=
show has_sum (λ x, pi.single b a x) a, by simpa only [pi.single_apply] using has_sum_ite_eq b a
lemma equiv.has_sum_iff (e : γ ≃ β) :
has_sum (f ∘ e) a ↔ has_sum f a :=
e.injective.has_sum_iff $ by simp
lemma function.injective.has_sum_range_iff {g : γ → β} (hg : injective g) :
has_sum (λ x : set.range g, f x) a ↔ has_sum (f ∘ g) a :=
(equiv.of_injective g hg).has_sum_iff.symm
lemma equiv.summable_iff (e : γ ≃ β) :
summable (f ∘ e) ↔ summable f :=
exists_congr $ λ a, e.has_sum_iff
lemma summable.prod_symm {f : β × γ → α} (hf : summable f) : summable (λ p : γ × β, f p.swap) :=
(equiv.prod_comm γ β).summable_iff.2 hf
lemma equiv.has_sum_iff_of_support {g : γ → α} (e : support f ≃ support g)
(he : ∀ x : support f, g (e x) = f x) :
has_sum f a ↔ has_sum g a :=
have (g ∘ coe) ∘ e = f ∘ coe, from funext he,
by rw [← has_sum_subtype_support, ← this, e.has_sum_iff, has_sum_subtype_support]
lemma has_sum_iff_has_sum_of_ne_zero_bij {g : γ → α} (i : support g → β)
(hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y)
(hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) :
has_sum f a ↔ has_sum g a :=
iff.symm $ equiv.has_sum_iff_of_support
(equiv.of_bijective (λ x, ⟨i x, λ hx, x.coe_prop $ hfg x ▸ hx⟩)
⟨λ x y h, subtype.ext $ hi $ subtype.ext_iff.1 h,
λ y, (hf y.coe_prop).imp $ λ x hx, subtype.ext hx⟩)
hfg
lemma equiv.summable_iff_of_support {g : γ → α} (e : support f ≃ support g)
(he : ∀ x : support f, g (e x) = f x) :
summable f ↔ summable g :=
exists_congr $ λ _, e.has_sum_iff_of_support he
protected lemma has_sum.map [add_comm_monoid γ] [topological_space γ] (hf : has_sum f a)
{G} [add_monoid_hom_class G α γ] (g : G) (hg : continuous g) :
has_sum (g ∘ f) (g a) :=
have g ∘ (λs:finset β, ∑ b in s, f b) = (λs:finset β, ∑ b in s, g (f b)),
from funext $ map_sum g _,
show tendsto (λs:finset β, ∑ b in s, g (f b)) at_top (𝓝 (g a)),
from this ▸ (hg.tendsto a).comp hf
protected lemma summable.map [add_comm_monoid γ] [topological_space γ] (hf : summable f)
{G} [add_monoid_hom_class G α γ] (g : G) (hg : continuous g) :
summable (g ∘ f) :=
(hf.has_sum.map g hg).summable
protected lemma summable.map_iff_of_left_inverse [add_comm_monoid γ] [topological_space γ]
{G G'} [add_monoid_hom_class G α γ] [add_monoid_hom_class G' γ α] (g : G) (g' : G')
(hg : continuous g) (hg' : continuous g') (hinv : function.left_inverse g' g) :
summable (g ∘ f) ↔ summable f :=
⟨λ h, begin
have := h.map _ hg',
rwa [←function.comp.assoc, hinv.id] at this,
end, λ h, h.map _ hg⟩
/-- A special case of `summable.map_iff_of_left_inverse` for convenience -/
protected lemma summable.map_iff_of_equiv [add_comm_monoid γ] [topological_space γ]
{G} [add_equiv_class G α γ] (g : G)
(hg : continuous g) (hg' : continuous (add_equiv_class.inv g : γ → α)) :
summable (g ∘ f) ↔ summable f :=
summable.map_iff_of_left_inverse g (g : α ≃+ γ).symm hg hg' (add_equiv_class.left_inv g)
/-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/
lemma has_sum.tendsto_sum_nat {f : ℕ → α} (h : has_sum f a) :
tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) :=
h.comp tendsto_finset_range
lemma has_sum.unique {a₁ a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ :=
tendsto_nhds_unique
lemma summable.has_sum_iff_tendsto_nat [t2_space α] {f : ℕ → α} {a : α} (hf : summable f) :
has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) :=
begin
refine ⟨λ h, h.tendsto_sum_nat, λ h, _⟩,
rw tendsto_nhds_unique h hf.has_sum.tendsto_sum_nat,
exact hf.has_sum
end
lemma function.surjective.summable_iff_of_has_sum_iff {α' : Type*} [add_comm_monoid α']
[topological_space α'] {e : α' → α} (hes : function.surjective e) {f : β → α} {g : γ → α'}
(he : ∀ {a}, has_sum f (e a) ↔ has_sum g a) :
summable f ↔ summable g :=
hes.exists.trans $ exists_congr $ @he
variable [has_continuous_add α]
lemma has_sum.add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) :=
by simp only [has_sum, sum_add_distrib]; exact hf.add hg
lemma summable.add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) :=
(hf.has_sum.add hg.has_sum).summable
lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} :
(∀i∈s, has_sum (f i) (a i)) → has_sum (λb, ∑ i in s, f i b) (∑ i in s, a i) :=
finset.induction_on s (by simp only [has_sum_zero, sum_empty, forall_true_iff])
(by simp only [has_sum.add, sum_insert, mem_insert, forall_eq_or_imp,
forall_2_true_iff, not_false_iff, forall_true_iff] {contextual := tt})
lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) :
summable (λb, ∑ i in s, f i b) :=
(has_sum_sum $ assume i hi, (hf i hi).has_sum).summable
lemma has_sum.add_disjoint {s t : set β} (hs : disjoint s t)
(ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) :
has_sum (f ∘ coe : s ∪ t → α) (a + b) :=
begin
rw has_sum_subtype_iff_indicator at *,
rw set.indicator_union_of_disjoint hs,
exact ha.add hb
end
lemma has_sum_sum_disjoint {ι} (s : finset ι) {t : ι → set β} {a : ι → α}
(hs : (s : set ι).pairwise (disjoint on t))
(hf : ∀ i ∈ s, has_sum (f ∘ coe : t i → α) (a i)) :
has_sum (f ∘ coe : (⋃ i ∈ s, t i) → α) (∑ i in s, a i) :=
begin
simp_rw has_sum_subtype_iff_indicator at *,
rw set.indicator_finset_bUnion _ _ hs,
exact has_sum_sum hf,
end
lemma has_sum.add_is_compl {s t : set β} (hs : is_compl s t)
(ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) :
has_sum f (a + b) :=
by simpa [← hs.compl_eq]
using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb)
lemma has_sum.add_compl {s : set β} (ha : has_sum (f ∘ coe : s → α) a)
(hb : has_sum (f ∘ coe : sᶜ → α) b) :
has_sum f (a + b) :=
ha.add_is_compl is_compl_compl hb
lemma summable.add_compl {s : set β} (hs : summable (f ∘ coe : s → α))
(hsc : summable (f ∘ coe : sᶜ → α)) :
summable f :=
(hs.has_sum.add_compl hsc.has_sum).summable
lemma has_sum.compl_add {s : set β} (ha : has_sum (f ∘ coe : sᶜ → α) a)
(hb : has_sum (f ∘ coe : s → α) b) :
has_sum f (a + b) :=
ha.add_is_compl is_compl_compl.symm hb
lemma has_sum.even_add_odd {f : ℕ → α} (he : has_sum (λ k, f (2 * k)) a)
(ho : has_sum (λ k, f (2 * k + 1)) b) :
has_sum f (a + b) :=
begin
have := mul_right_injective₀ (two_ne_zero' ℕ),
replace he := this.has_sum_range_iff.2 he,
replace ho := ((add_left_injective 1).comp this).has_sum_range_iff.2 ho,
refine he.add_is_compl _ ho,
simpa [(∘)] using nat.is_compl_even_odd
end
lemma summable.compl_add {s : set β} (hs : summable (f ∘ coe : sᶜ → α))
(hsc : summable (f ∘ coe : s → α)) :
summable f :=
(hs.has_sum.compl_add hsc.has_sum).summable
lemma summable.even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k)))
(ho : summable (λ k, f (2 * k + 1))) :
summable f :=
(he.has_sum.even_add_odd ho.has_sum).summable
lemma has_sum.sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α}
(ha : has_sum f a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) : has_sum g a :=
begin
refine (at_top_basis.tendsto_iff (closed_nhds_basis a)).mpr _,
rintros s ⟨hs, hsc⟩,
rcases mem_at_top_sets.mp (ha hs) with ⟨u, hu⟩,
use [u.image sigma.fst, trivial],
intros bs hbs,
simp only [set.mem_preimage, ge_iff_le, finset.le_iff_subset] at hu,
have : tendsto (λ t : finset (Σ b, γ b), ∑ p in t.filter (λ p, p.1 ∈ bs), f p)
at_top (𝓝 $ ∑ b in bs, g b),
{ simp only [← sigma_preimage_mk, sum_sigma],
refine tendsto_finset_sum _ (λ b hb, _),
change tendsto (λ t, (λ t, ∑ s in t, f ⟨b, s⟩) (preimage t (sigma.mk b) _)) at_top (𝓝 (g b)),
exact tendsto.comp (hf b) (tendsto_finset_preimage_at_top_at_top _) },
refine hsc.mem_of_tendsto this (eventually_at_top.2 ⟨u, λ t ht, hu _ (λ x hx, _)⟩),
exact mem_filter.2 ⟨ht hx, hbs $ mem_image_of_mem _ hx⟩
end
/-- If a series `f` on `β × γ` has sum `a` and for each `b` the restriction of `f` to `{b} × γ`
has sum `g b`, then the series `g` has sum `a`. -/
lemma has_sum.prod_fiberwise [regular_space α] {f : β × γ → α} {g : β → α} {a : α}
(ha : has_sum f a) (hf : ∀b, has_sum (λc, f (b, c)) (g b)) :
has_sum g a :=
has_sum.sigma ((equiv.sigma_equiv_prod β γ).has_sum_iff.2 ha) hf
lemma summable.sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) (hf : ∀b, summable (λc, f ⟨b, c⟩)) :
summable (λb, ∑'c, f ⟨b, c⟩) :=
(ha.has_sum.sigma (assume b, (hf b).has_sum)).summable
lemma has_sum.sigma_of_has_sum [t3_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α}
{a : α} (ha : has_sum g a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (hf' : summable f) :
has_sum f a :=
by simpa [(hf'.has_sum.sigma hf).unique ha] using hf'.has_sum
/-- Version of `has_sum.update` for `add_comm_monoid` rather than `add_comm_group`.
Rather than showing that `f.update` has a specific sum in terms of `has_sum`,
it gives a relationship between the sums of `f` and `f.update` given that both exist. -/
lemma has_sum.update' {α β : Type*} [topological_space α] [add_comm_monoid α] [t2_space α]
[has_continuous_add α] {f : β → α} {a a' : α} (hf : has_sum f a)
(b : β) (x : α) (hf' : has_sum (f.update b x) a') : a + x = a' + f b :=
begin
have : ∀ b', f b' + ite (b' = b) x 0 = f.update b x b' + ite (b' = b) (f b) 0,
{ intro b',
split_ifs with hb',
{ simpa only [function.update_apply, hb', eq_self_iff_true] using add_comm (f b) x },
{ simp only [function.update_apply, hb', if_false] } },
have h := hf.add ((has_sum_ite_eq b x)),
simp_rw this at h,
exact has_sum.unique h (hf'.add (has_sum_ite_eq b (f b)))
end
/-- Version of `has_sum_ite_sub_has_sum` for `add_comm_monoid` rather than `add_comm_group`.
Rather than showing that the `ite` expression has a specific sum in terms of `has_sum`,
it gives a relationship between the sums of `f` and `ite (n = b) 0 (f n)` given that both exist. -/
lemma eq_add_of_has_sum_ite {α β : Type*} [topological_space α] [add_comm_monoid α]
[t2_space α] [has_continuous_add α] {f : β → α} {a : α} (hf : has_sum f a) (b : β) (a' : α)
(hf' : has_sum (λ n, ite (n = b) 0 (f n)) a') : a = a' + f b :=
begin
refine (add_zero a).symm.trans (hf.update' b 0 _),
convert hf',
exact funext (f.update_apply b 0),
end
end has_sum
section tsum
variables [add_comm_monoid α] [topological_space α]
lemma tsum_congr_subtype (f : β → α) {s t : set β} (h : s = t) :
∑' (x : s), f x = ∑' (x : t), f x :=
by rw h
lemma tsum_zero' (hz : is_closed ({0} : set α)) : ∑' b : β, (0 : α) = 0 :=
begin
classical,
rw [tsum, dif_pos summable_zero],
suffices : ∀ (x : α), has_sum (λ (b : β), (0 : α)) x → x = 0,
{ exact this _ (classical.some_spec _) },
intros x hx,
contrapose! hx,
simp only [has_sum, tendsto_nhds, finset.sum_const_zero, filter.mem_at_top_sets, ge_iff_le,
finset.le_eq_subset, set.mem_preimage, not_forall, not_exists, exists_prop,
exists_and_distrib_right],
refine ⟨{0}ᶜ, ⟨is_open_compl_iff.mpr hz, _⟩, λ y, ⟨⟨y, subset_refl _⟩, _⟩⟩,
{ simpa using hx },
{ simp }
end
@[simp] lemma tsum_zero [t1_space α] : ∑' b : β, (0 : α) = 0 := tsum_zero' is_closed_singleton
variables [t2_space α] {f g : β → α} {a a₁ a₂ : α}
lemma has_sum.tsum_eq (ha : has_sum f a) : ∑'b, f b = a :=
(summable.has_sum ⟨a, ha⟩).unique ha
lemma summable.has_sum_iff (h : summable f) : has_sum f a ↔ ∑'b, f b = a :=
iff.intro has_sum.tsum_eq (assume eq, eq ▸ h.has_sum)
@[simp] lemma tsum_empty [is_empty β] : ∑'b, f b = 0 := has_sum_empty.tsum_eq
lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) :
∑' b, f b = ∑ b in s, f b :=
(has_sum_sum_of_ne_finset_zero hf).tsum_eq
lemma sum_eq_tsum_indicator (f : β → α) (s : finset β) :
∑ x in s, f x = ∑' x, set.indicator ↑s f x :=
have ∀ x ∉ s, set.indicator ↑s f x = 0,
from λ x hx, set.indicator_apply_eq_zero.2 (λ hx', (hx $ finset.mem_coe.1 hx').elim),
(finset.sum_congr rfl (λ x hx, (set.indicator_apply_eq_self.2 $
λ hx', (hx' $ finset.mem_coe.2 hx).elim).symm)).trans (tsum_eq_sum this).symm
lemma tsum_congr {α β : Type*} [add_comm_monoid α] [topological_space α]
{f g : β → α} (hfg : ∀ b, f b = g b) : ∑' b, f b = ∑' b, g b :=
congr_arg tsum (funext hfg)
lemma tsum_fintype [fintype β] (f : β → α) : ∑'b, f b = ∑ b, f b :=
(has_sum_fintype f).tsum_eq
lemma tsum_bool (f : bool → α) : ∑' i : bool, f i = f false + f true :=
by { rw [tsum_fintype, finset.sum_eq_add]; simp }
lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) :
∑'b, f b = f b :=
(has_sum_single b hf).tsum_eq
lemma tsum_tsum_eq_single (f : β → γ → α) (b : β) (c : γ) (hfb : ∀ b' ≠ b, f b' c = 0)
(hfc : ∀ (b' : β) (c' : γ), c' ≠ c → f b' c' = 0) :
∑' b' c', f b' c' = f b c :=
calc ∑' b' c', f b' c' = ∑' b', f b' c : tsum_congr $ λ b', tsum_eq_single _ (hfc b')
... = f b c : tsum_eq_single _ hfb
@[simp] lemma tsum_ite_eq (b : β) [decidable_pred (= b)] (a : α) :
∑' b', (if b' = b then a else 0) = a :=
(has_sum_ite_eq b a).tsum_eq
@[simp] lemma tsum_pi_single [decidable_eq β] (b : β) (a : α) :
∑' b', pi.single b a b' = a :=
(has_sum_pi_single b a).tsum_eq
lemma tsum_dite_right (P : Prop) [decidable P] (x : β → ¬ P → α) :
∑' (b : β), (if h : P then (0 : α) else x b h) = if h : P then (0 : α) else ∑' (b : β), x b h :=
by by_cases hP : P; simp [hP]
lemma tsum_dite_left (P : Prop) [decidable P] (x : β → P → α) :
∑' (b : β), (if h : P then x b h else 0) = if h : P then (∑' (b : β), x b h) else 0 :=
by by_cases hP : P; simp [hP]
lemma function.surjective.tsum_eq_tsum_of_has_sum_iff_has_sum {α' : Type*} [add_comm_monoid α']
[topological_space α'] {e : α' → α} (hes : function.surjective e) (h0 : e 0 = 0)
{f : β → α} {g : γ → α'}
(h : ∀ {a}, has_sum f (e a) ↔ has_sum g a) :
∑' b, f b = e (∑' c, g c) :=
by_cases
(assume : summable g, (h.mpr this.has_sum).tsum_eq)
(assume hg : ¬ summable g,
have hf : ¬ summable f, from mt (hes.summable_iff_of_has_sum_iff @h).1 hg,
by simp [tsum, hf, hg, h0])
lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α}
(h : ∀{a}, has_sum f a ↔ has_sum g a) :
∑'b, f b = ∑'c, g c :=
surjective_id.tsum_eq_tsum_of_has_sum_iff_has_sum rfl @h
lemma equiv.tsum_eq (j : γ ≃ β) (f : β → α) : ∑'c, f (j c) = ∑'b, f b :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ λ a, j.has_sum_iff
lemma equiv.tsum_eq_tsum_of_support {f : β → α} {g : γ → α} (e : support f ≃ support g)
(he : ∀ x, g (e x) = f x) :
(∑' x, f x) = ∑' y, g y :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, e.has_sum_iff_of_support he
lemma tsum_eq_tsum_of_ne_zero_bij {g : γ → α} (i : support g → β)
(hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y)
(hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) :
∑' x, f x = ∑' y, g y :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_iff_has_sum_of_ne_zero_bij i hi hf hfg
/-! ### `tsum` on subsets -/
@[simp] lemma finset.tsum_subtype (s : finset β) (f : β → α) :
∑' x : {x // x ∈ s}, f x = ∑ x in s, f x :=
(s.has_sum f).tsum_eq
@[simp] lemma finset.tsum_subtype' (s : finset β) (f : β → α) :
∑' x : (s : set β), f x = ∑ x in s, f x :=
s.tsum_subtype f
lemma tsum_subtype (s : set β) (f : β → α) :
∑' x : s, f x = ∑' x, s.indicator f x :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_subtype_iff_indicator
lemma tsum_subtype_eq_of_support_subset {f : β → α} {s : set β} (hs : support f ⊆ s) :
∑' x : s, f x = ∑' x, f x :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ λ x, has_sum_subtype_iff_of_support_subset hs
@[simp] lemma tsum_univ (f : β → α) : ∑' x : (set.univ : set β), f x = ∑' x, f x :=
tsum_subtype_eq_of_support_subset $ set.subset_univ _
@[simp] lemma tsum_singleton (b : β) (f : β → α) :
∑' x : ({b} : set β), f x = f b :=
begin
rw [tsum_subtype, tsum_eq_single b],
{ simp },
{ intros b' hb',
rw set.indicator_of_not_mem,
rwa set.mem_singleton_iff },
{ apply_instance }
end
lemma tsum_image {g : γ → β} (f : β → α) {s : set γ} (hg : set.inj_on g s) :
∑' x : g '' s, f x = ∑' x : s, f (g x) :=
((equiv.set.image_of_inj_on _ _ hg).tsum_eq (λ x, f x)).symm
lemma tsum_range {g : γ → β} (f : β → α) (hg : injective g) :
∑' x : set.range g, f x = ∑' x, f (g x) :=
by rw [← set.image_univ, tsum_image f (hg.inj_on _), tsum_univ (f ∘ g)]
section has_continuous_add
variable [has_continuous_add α]
lemma tsum_add (hf : summable f) (hg : summable g) : ∑'b, (f b + g b) = (∑'b, f b) + (∑'b, g b) :=
(hf.has_sum.add hg.has_sum).tsum_eq
lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) :
∑'b, ∑ i in s, f i b = ∑ i in s, ∑'b, f i b :=
(has_sum_sum $ assume i hi, (hf i hi).has_sum).tsum_eq
/-- Version of `tsum_eq_add_tsum_ite` for `add_comm_monoid` rather than `add_comm_group`.
Requires a different convergence assumption involving `function.update`. -/
lemma tsum_eq_add_tsum_ite' {f : β → α} (b : β) (hf : summable (f.update b 0)) :
∑' x, f x = f b + ∑' x, ite (x = b) 0 (f x) :=
calc ∑' x, f x = ∑' x, ((ite (x = b) (f x) 0) + (f.update b 0 x)) :
tsum_congr (λ n, by split_ifs; simp [function.update_apply, h])
... = ∑' x, ite (x = b) (f x) 0 + ∑' x, f.update b 0 x :
tsum_add ⟨ite (b = b) (f b) 0, has_sum_single b (λ b hb, if_neg hb)⟩ (hf)
... = (ite (b = b) (f b) 0) + ∑' x, f.update b 0 x :
by { congr, exact (tsum_eq_single b (λ b' hb', if_neg hb')) }
... = f b + ∑' x, ite (x = b) 0 (f x) :
by simp only [function.update, eq_self_iff_true, if_true, eq_rec_constant, dite_eq_ite]
variables [add_comm_monoid δ] [topological_space δ] [t3_space δ] [has_continuous_add δ]
lemma tsum_sigma' {γ : β → Type*} {f : (Σb:β, γ b) → δ} (h₁ : ∀b, summable (λc, f ⟨b, c⟩))
(h₂ : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ :=
(h₂.has_sum.sigma (assume b, (h₁ b).has_sum)).tsum_eq.symm
lemma tsum_prod' {f : β × γ → δ} (h : summable f) (h₁ : ∀b, summable (λc, f (b, c))) :
∑'p, f p = ∑'b c, f (b, c) :=
(h.has_sum.prod_fiberwise (assume b, (h₁ b).has_sum)).tsum_eq.symm
lemma tsum_comm' {f : β → γ → δ} (h : summable (function.uncurry f)) (h₁ : ∀b, summable (f b))
(h₂ : ∀ c, summable (λ b, f b c)) :
∑' c b, f b c = ∑' b c, f b c :=
begin
erw [← tsum_prod' h h₁, ← tsum_prod' h.prod_symm h₂, ← (equiv.prod_comm γ β).tsum_eq (uncurry f)],
refl
end
end has_continuous_add
open encodable
section encodable
variable [encodable γ]
/-- You can compute a sum over an encodably type by summing over the natural numbers and
taking a supremum. This is useful for outer measures. -/
theorem tsum_supr_decode₂ [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0)
(s : γ → β) : ∑' i : ℕ, m (⨆ b ∈ decode₂ γ i, s b) = ∑' b : γ, m (s b) :=
begin
have H : ∀ n, m (⨆ b ∈ decode₂ γ n, s b) ≠ 0 → (decode₂ γ n).is_some,
{ intros n h,
cases decode₂ γ n with b,
{ refine (h $ by simp [m0]).elim },
{ exact rfl } },
symmetry, refine tsum_eq_tsum_of_ne_zero_bij (λ a, option.get (H a.1 a.2)) _ _ _,
{ rintros ⟨m, hm⟩ ⟨n, hn⟩ e,
have := mem_decode₂.1 (option.get_mem (H n hn)),
rwa [← e, mem_decode₂.1 (option.get_mem (H m hm))] at this },
{ intros b h,
refine ⟨⟨encode b, _⟩, _⟩,
{ simp only [mem_support, encodek₂] at h ⊢, convert h, simp [set.ext_iff, encodek₂] },
{ exact option.get_of_mem _ (encodek₂ _) } },
{ rintros ⟨n, h⟩, dsimp only [subtype.coe_mk],
transitivity, swap,
rw [show decode₂ γ n = _, from option.get_mem (H n h)],
congr, simp [ext_iff, -option.some_get] }
end
/-- `tsum_supr_decode₂` specialized to the complete lattice of sets. -/
theorem tsum_Union_decode₂ (m : set β → α) (m0 : m ∅ = 0)
(s : γ → set β) : ∑' i, m (⋃ b ∈ decode₂ γ i, s b) = ∑' b, m (s b) :=
tsum_supr_decode₂ m m0 s
end encodable
/-! Some properties about measure-like functions.
These could also be functions defined on complete sublattices of sets, with the property
that they are countably sub-additive.
`R` will probably be instantiated with `(≤)` in all applications.
-/
section countable
variables [countable γ]
/-- If a function is countably sub-additive then it is sub-additive on countable types -/
theorem rel_supr_tsum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0)
(R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) ∑' i, m (s i))
(s : γ → β) : R (m (⨆ b : γ, s b)) ∑' b : γ, m (s b) :=
by { casesI nonempty_encodable γ, rw [←supr_decode₂, ←tsum_supr_decode₂ _ m0 s], exact m_supr _ }
/-- If a function is countably sub-additive then it is sub-additive on finite sets -/
theorem rel_supr_sum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0)
(R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i)))
(s : δ → β) (t : finset δ) :
R (m (⨆ d ∈ t, s d)) (∑ d in t, m (s d)) :=
by { rw [supr_subtype', ←finset.tsum_subtype], exact rel_supr_tsum m m0 R m_supr _ }
/-- If a function is countably sub-additive then it is binary sub-additive -/
theorem rel_sup_add [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0)
(R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i)))
(s₁ s₂ : β) : R (m (s₁ ⊔ s₂)) (m s₁ + m s₂) :=
begin
convert rel_supr_tsum m m0 R m_supr (λ b, cond b s₁ s₂),
{ simp only [supr_bool_eq, cond] },
{ rw [tsum_fintype, fintype.sum_bool, cond, cond] }
end
end countable
variables [has_continuous_add α]
lemma tsum_add_tsum_compl {s : set β} (hs : summable (f ∘ coe : s → α))
(hsc : summable (f ∘ coe : sᶜ → α)) :
(∑' x : s, f x) + (∑' x : sᶜ, f x) = ∑' x, f x :=
(hs.has_sum.add_compl hsc.has_sum).tsum_eq.symm
lemma tsum_union_disjoint {s t : set β} (hd : disjoint s t)
(hs : summable (f ∘ coe : s → α)) (ht : summable (f ∘ coe : t → α)) :
(∑' x : s ∪ t, f x) = (∑' x : s, f x) + (∑' x : t, f x) :=
(hs.has_sum.add_disjoint hd ht.has_sum).tsum_eq
lemma tsum_finset_bUnion_disjoint {ι} {s : finset ι} {t : ι → set β}
(hd : (s : set ι).pairwise (disjoint on t))
(hf : ∀ i ∈ s, summable (f ∘ coe : t i → α)) :
(∑' x : (⋃ i ∈ s, t i), f x) = ∑ i in s, ∑' x : t i, f x :=
(has_sum_sum_disjoint _ hd (λ i hi, (hf i hi).has_sum)).tsum_eq
lemma tsum_even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k)))
(ho : summable (λ k, f (2 * k + 1))) :
(∑' k, f (2 * k)) + (∑' k, f (2 * k + 1)) = ∑' k, f k :=
(he.has_sum.even_add_odd ho.has_sum).tsum_eq.symm
end tsum
section topological_group
variables [add_comm_group α] [topological_space α] [topological_add_group α]
variables {f g : β → α} {a a₁ a₂ : α}
-- `by simpa using` speeds up elaboration. Why?
lemma has_sum.neg (h : has_sum f a) : has_sum (λb, - f b) (- a) :=
by simpa only using h.map (-add_monoid_hom.id α) continuous_neg
lemma summable.neg (hf : summable f) : summable (λb, - f b) :=
hf.has_sum.neg.summable
lemma summable.of_neg (hf : summable (λb, - f b)) : summable f :=
by simpa only [neg_neg] using hf.neg
lemma summable_neg_iff : summable (λ b, - f b) ↔ summable f :=
⟨summable.of_neg, summable.neg⟩
lemma has_sum.sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) :=
by { simp only [sub_eq_add_neg], exact hf.add hg.neg }
lemma summable.sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) :=
(hf.has_sum.sub hg.has_sum).summable
lemma summable.trans_sub (hg : summable g) (hfg : summable (λb, f b - g b)) :
summable f :=
by simpa only [sub_add_cancel] using hfg.add hg
lemma summable_iff_of_summable_sub (hfg : summable (λb, f b - g b)) :
summable f ↔ summable g :=
⟨λ hf, hf.trans_sub $ by simpa only [neg_sub] using hfg.neg, λ hg, hg.trans_sub hfg⟩
lemma has_sum.update (hf : has_sum f a₁) (b : β) [decidable_eq β] (a : α) :
has_sum (update f b a) (a - f b + a₁) :=
begin
convert ((has_sum_ite_eq b _).add hf),
ext b',
by_cases h : b' = b,
{ rw [h, update_same],
simp only [eq_self_iff_true, if_true, sub_add_cancel] },
simp only [h, update_noteq, if_false, ne.def, zero_add, not_false_iff],
end
lemma summable.update (hf : summable f) (b : β) [decidable_eq β] (a : α) :
summable (update f b a) :=
(hf.has_sum.update b a).summable
lemma has_sum.has_sum_compl_iff {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) :
has_sum (f ∘ coe : sᶜ → α) a₂ ↔ has_sum f (a₁ + a₂) :=
begin
refine ⟨λ h, hf.add_compl h, λ h, _⟩,
rw [has_sum_subtype_iff_indicator] at hf ⊢,
rw [set.indicator_compl],
simpa only [add_sub_cancel'] using h.sub hf
end
lemma has_sum.has_sum_iff_compl {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) :
has_sum f a₂ ↔ has_sum (f ∘ coe : sᶜ → α) (a₂ - a₁) :=
iff.symm $ hf.has_sum_compl_iff.trans $ by rw [add_sub_cancel'_right]
lemma summable.summable_compl_iff {s : set β} (hf : summable (f ∘ coe : s → α)) :
summable (f ∘ coe : sᶜ → α) ↔ summable f :=
⟨λ ⟨a, ha⟩, (hf.has_sum.has_sum_compl_iff.1 ha).summable,
λ ⟨a, ha⟩, (hf.has_sum.has_sum_iff_compl.1 ha).summable⟩
protected lemma finset.has_sum_compl_iff (s : finset β) :
has_sum (λ x : {x // x ∉ s}, f x) a ↔ has_sum f (a + ∑ i in s, f i) :=
(s.has_sum f).has_sum_compl_iff.trans $ by rw [add_comm]
protected lemma finset.has_sum_iff_compl (s : finset β) :
has_sum f a ↔ has_sum (λ x : {x // x ∉ s}, f x) (a - ∑ i in s, f i) :=
(s.has_sum f).has_sum_iff_compl
protected lemma finset.summable_compl_iff (s : finset β) :
summable (λ x : {x // x ∉ s}, f x) ↔ summable f :=
(s.summable f).summable_compl_iff
lemma set.finite.summable_compl_iff {s : set β} (hs : s.finite) :
summable (f ∘ coe : sᶜ → α) ↔ summable f :=
(hs.summable f).summable_compl_iff
lemma has_sum_ite_sub_has_sum [decidable_eq β] (hf : has_sum f a) (b : β) :
has_sum (λ n, ite (n = b) 0 (f n)) (a - f b) :=
begin
convert hf.update b 0 using 1,
{ ext n, rw function.update_apply, },
{ rw [sub_add_eq_add_sub, zero_add], },
end
section tsum
variables [t2_space α]
lemma tsum_neg : ∑'b, - f b = - ∑'b, f b :=
begin
by_cases hf : summable f,
{ exact hf.has_sum.neg.tsum_eq, },
{ simp [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt summable.of_neg hf)] },
end
lemma tsum_sub (hf : summable f) (hg : summable g) : ∑'b, (f b - g b) = ∑'b, f b - ∑'b, g b :=
(hf.has_sum.sub hg.has_sum).tsum_eq
lemma sum_add_tsum_compl {s : finset β} (hf : summable f) :
(∑ x in s, f x) + (∑' x : (↑s : set β)ᶜ, f x) = ∑' x, f x :=
((s.has_sum f).add_compl (s.summable_compl_iff.2 hf).has_sum).tsum_eq.symm
/-- Let `f : β → α` be a sequence with summable series and let `b ∈ β` be an index.
Lemma `tsum_eq_add_tsum_ite` writes `Σ f n` as the sum of `f b` plus the series of the
remaining terms. -/
lemma tsum_eq_add_tsum_ite [decidable_eq β] (hf : summable f) (b : β) :
∑' n, f n = f b + ∑' n, ite (n = b) 0 (f n) :=
begin
rw (has_sum_ite_sub_has_sum hf.has_sum b).tsum_eq,
exact (add_sub_cancel'_right _ _).symm,
end
end tsum
/-!
### Sums on nat
We show the formula `(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i)`, in
`sum_add_tsum_nat_add`, as well as several results relating sums on `ℕ` and `ℤ`.
-/
section nat
lemma has_sum_nat_add_iff {f : ℕ → α} (k : ℕ) {a : α} :
has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) :=
begin
refine iff.trans _ ((range k).has_sum_compl_iff),
rw [← (not_mem_range_equiv k).symm.has_sum_iff],
refl
end
lemma summable_nat_add_iff {f : ℕ → α} (k : ℕ) : summable (λ n, f (n + k)) ↔ summable f :=
iff.symm $ (equiv.add_right (∑ i in range k, f i)).surjective.summable_iff_of_has_sum_iff $
λ a, (has_sum_nat_add_iff k).symm
lemma has_sum_nat_add_iff' {f : ℕ → α} (k : ℕ) {a : α} :
has_sum (λ n, f (n + k)) (a - ∑ i in range k, f i) ↔ has_sum f a :=
by simp [has_sum_nat_add_iff]
lemma sum_add_tsum_nat_add [t2_space α] {f : ℕ → α} (k : ℕ) (h : summable f) :
(∑ i in range k, f i) + (∑' i, f (i + k)) = ∑' i, f i :=
by simpa only [add_comm] using
((has_sum_nat_add_iff k).1 ((summable_nat_add_iff k).2 h).has_sum).unique h.has_sum
lemma tsum_eq_zero_add [t2_space α] {f : ℕ → α} (hf : summable f) :
∑'b, f b = f 0 + ∑'b, f (b + 1) :=
by simpa only [sum_range_one] using (sum_add_tsum_nat_add 1 hf).symm
/-- For `f : ℕ → α`, then `∑' k, f (k + i)` tends to zero. This does not require a summability
assumption on `f`, as otherwise all sums are zero. -/
lemma tendsto_sum_nat_add [t2_space α] (f : ℕ → α) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) :=
begin
by_cases hf : summable f,
{ have h₀ : (λ i, (∑' i, f i) - ∑ j in range i, f j) = λ i, ∑' (k : ℕ), f (k + i),
{ ext1 i,
rw [sub_eq_iff_eq_add, add_comm, sum_add_tsum_nat_add i hf] },
have h₁ : tendsto (λ i : ℕ, ∑' i, f i) at_top (𝓝 (∑' i, f i)) := tendsto_const_nhds,
simpa only [h₀, sub_self] using tendsto.sub h₁ hf.has_sum.tendsto_sum_nat },
{ convert tendsto_const_nhds,
ext1 i,
rw ← summable_nat_add_iff i at hf,
{ exact tsum_eq_zero_of_not_summable hf },
{ apply_instance } }
end
/-- If `f₀, f₁, f₂, ...` and `g₀, g₁, g₂, ...` are both convergent then so is the `ℤ`-indexed
sequence: `..., g₂, g₁, g₀, f₀, f₁, f₂, ...`. -/
lemma has_sum.int_rec {b : α} {f g : ℕ → α} (hf : has_sum f a) (hg : has_sum g b) :
@has_sum α _ _ _ (@int.rec (λ _, α) f g : ℤ → α) (a + b) :=
begin
-- note this proof works for any two-case inductive
have h₁ : injective (coe : ℕ → ℤ) := @int.of_nat.inj,
have h₂ : injective int.neg_succ_of_nat := @int.neg_succ_of_nat.inj,
have : is_compl (set.range (coe : ℕ → ℤ)) (set.range int.neg_succ_of_nat),
{ split,
{ rw disjoint_iff_inf_le,
rintros _ ⟨⟨i, rfl⟩, ⟨j, ⟨⟩⟩⟩ },
{ rw codisjoint_iff_le_sup,
rintros (i | j) h,
exacts [or.inl ⟨_, rfl⟩, or.inr ⟨_, rfl⟩] } },
exact has_sum.add_is_compl this (h₁.has_sum_range_iff.mpr hf) (h₂.has_sum_range_iff.mpr hg),
end
lemma has_sum.nonneg_add_neg {b : α} {f : ℤ → α}
(hnonneg : has_sum (λ n : ℕ, f n) a) (hneg : has_sum (λ (n : ℕ), f (-n.succ)) b) :
has_sum f (a + b) :=
begin
simp_rw ← int.neg_succ_of_nat_coe at hneg,
convert hnonneg.int_rec hneg using 1,
ext (i | j); refl,
end
lemma has_sum.pos_add_zero_add_neg {b : α} {f : ℤ → α}
(hpos : has_sum (λ n:ℕ, f(n + 1)) a) (hneg : has_sum (λ (n : ℕ), f (-n.succ)) b) :
has_sum f (a + f 0 + b) :=
begin
have : ∀ g : ℕ → α, has_sum (λ k, g (k + 1)) a → has_sum g (a + g 0),
{ intros g hg, simpa using (has_sum_nat_add_iff _).mp hg },
exact (this (λ n, f n) hpos).nonneg_add_neg hneg,
end
lemma summable_int_of_summable_nat {f : ℤ → α}
(hp : summable (λ n:ℕ, f n)) (hn : summable (λ n:ℕ, f (-n))) : summable f :=
(has_sum.nonneg_add_neg hp.has_sum $ summable.has_sum $ (summable_nat_add_iff 1).mpr hn).summable
lemma has_sum.sum_nat_of_sum_int {α : Type*} [add_comm_monoid α] [topological_space α]
[has_continuous_add α] {a : α} {f : ℤ → α} (hf : has_sum f a) :
has_sum (λ n:ℕ, f n + f (-n)) (a + f 0) :=
begin
apply (hf.add (has_sum_ite_eq (0 : ℤ) (f 0))).has_sum_of_sum_eq (λ u, _),
refine ⟨u.image int.nat_abs, λ v' hv', _⟩,
let u1 := v'.image (λ (x : ℕ), (x : ℤ)),
let u2 := v'.image (λ (x : ℕ), - (x : ℤ)),
have A : u ⊆ u1 ∪ u2,
{ assume x hx,
simp only [mem_union, mem_image, exists_prop],
rcases le_total 0 x with h'x|h'x,
{ left,
refine ⟨int.nat_abs x, hv' _, _⟩,
{ simp only [mem_image, exists_prop],
exact ⟨x, hx, rfl⟩ },
{ simp only [h'x, int.coe_nat_abs, abs_eq_self] } },
{ right,
refine ⟨int.nat_abs x, hv' _, _⟩,
{ simp only [mem_image, exists_prop],
exact ⟨x, hx, rfl⟩ },
{ simp only [abs_of_nonpos h'x, int.coe_nat_abs, neg_neg] } } },
refine ⟨u1 ∪ u2, A, _⟩,
calc ∑ x in u1 ∪ u2, (f x + ite (x = 0) (f 0) 0)
= ∑ x in u1 ∪ u2, f x + ∑ x in u1 ∩ u2, f x :
begin
rw sum_add_distrib,
congr' 1,
refine (sum_subset_zero_on_sdiff inter_subset_union _ _).symm,
{ assume x hx,
suffices : x ≠ 0, by simp only [this, if_false],
rintros rfl,
simpa only [mem_sdiff, mem_union, mem_image, neg_eq_zero, or_self, mem_inter, and_self,
and_not_self] using hx },
{ assume x hx,
simp only [mem_inter, mem_image, exists_prop] at hx,
have : x = 0,
{ apply le_antisymm,
{ rcases hx.2 with ⟨a, ha, rfl⟩,
simp only [right.neg_nonpos_iff, nat.cast_nonneg] },
{ rcases hx.1 with ⟨a, ha, rfl⟩,
simp only [nat.cast_nonneg] } },
simp only [this, eq_self_iff_true, if_true] }
end
... = ∑ x in u1, f x + ∑ x in u2, f x : sum_union_inter
... = ∑ b in v', f b + ∑ b in v', f (-b) :
by simp only [sum_image, nat.cast_inj, imp_self, implies_true_iff, neg_inj]
... = ∑ b in v', (f b + f (-b)) : sum_add_distrib.symm
end
end nat
end topological_group
section uniform_group
variables [add_comm_group α] [uniform_space α]
/-- The **Cauchy criterion** for infinite sums, also known as the **Cauchy convergence test** -/
lemma summable_iff_cauchy_seq_finset [complete_space α] {f : β → α} :
summable f ↔ cauchy_seq (λ (s : finset β), ∑ b in s, f b) :=
cauchy_map_iff_exists_tendsto.symm
variables [uniform_add_group α] {f g : β → α} {a a₁ a₂ : α}
lemma cauchy_seq_finset_iff_vanishing :
cauchy_seq (λ (s : finset β), ∑ b in s, f b)
↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) :=
begin
simp only [cauchy_seq, cauchy_map_iff, and_iff_right at_top_ne_bot,
prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)],
rw [tendsto_at_top'],
split,
{ assume h e he,
rcases h e he with ⟨⟨s₁, s₂⟩, h⟩,
use [s₁ ∪ s₂],
assume t ht,
specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_of_le_left le_sup_right⟩,
simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h },
{ assume h e he,
rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩,
rcases h d hd with ⟨s, h⟩,
use [(s, s)],
rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩,
have : ∑ b in t₂, f b - ∑ b in t₁, f b = ∑ b in t₂ \ s, f b - ∑ b in t₁ \ s, f b,
{ simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm,
add_sub_add_right_eq_sub] },
simp only [this],
exact hde _ (h _ finset.sdiff_disjoint) _ (h _ finset.sdiff_disjoint) }
end
/-- The sum over the complement of a finset tends to `0` when the finset grows to cover the whole
space. This does not need a summability assumption, as otherwise all sums are zero. -/
lemma tendsto_tsum_compl_at_top_zero (f : β → α) :
tendsto (λ (s : finset β), ∑' b : {x // x ∉ s}, f b) at_top (𝓝 0) :=
begin
by_cases H : summable f,
{ assume e he,
rcases exists_mem_nhds_is_closed_subset he with ⟨o, ho, o_closed, oe⟩,
simp only [le_eq_subset, set.mem_preimage, mem_at_top_sets, filter.mem_map, ge_iff_le],
obtain ⟨s, hs⟩ : ∃ (s : finset β), ∀ (t : finset β), disjoint t s → ∑ (b : β) in t, f b ∈ o :=
cauchy_seq_finset_iff_vanishing.1 (tendsto.cauchy_seq H.has_sum) o ho,
refine ⟨s, λ a sa, oe _⟩,
have A : summable (λ b : {x // x ∉ a}, f b) := a.summable_compl_iff.2 H,
apply is_closed.mem_of_tendsto o_closed A.has_sum (eventually_of_forall (λ b, _)),
have : disjoint (finset.image (λ (i : {x // x ∉ a}), (i : β)) b) s,
{ apply disjoint_left.2 (λ i hi his, _),
rcases mem_image.1 hi with ⟨i', hi', rfl⟩,
exact i'.2 (sa his), },
convert hs _ this using 1,
rw sum_image,
assume i hi j hj hij,
exact subtype.ext hij },
{ convert tendsto_const_nhds,
ext s,
apply tsum_eq_zero_of_not_summable,
rwa finset.summable_compl_iff }
end
variable [complete_space α]
lemma summable_iff_vanishing :
summable f ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) :=
by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing]
/- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/
lemma summable.summable_of_eq_zero_or_self (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) :
summable g :=
summable_iff_vanishing.2 $
assume e he,
let ⟨s, hs⟩ := summable_iff_vanishing.1 hf e he in
⟨s, assume t ht,
have eq : ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t, g b :=
calc ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t.filter (λb, g b = f b), g b :
finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm)
... = ∑ b in t, g b :
begin
refine finset.sum_subset (finset.filter_subset _ _) _,
assume b hbt hb,
simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb,
exact (h b).resolve_right hb
end,
eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _ _) ht⟩
protected lemma summable.indicator (hf : summable f) (s : set β) :
summable (s.indicator f) :=
hf.summable_of_eq_zero_or_self $ set.indicator_eq_zero_or_self _ _
lemma summable.comp_injective {i : γ → β} (hf : summable f) (hi : injective i) :
summable (f ∘ i) :=
begin
simpa only [set.indicator_range_comp]
using (hi.summable_iff _).2 (hf.indicator (set.range i)),
exact λ x hx, set.indicator_of_not_mem hx _
end
lemma summable.subtype (hf : summable f) (s : set β) : summable (f ∘ coe : s → α) :=
hf.comp_injective subtype.coe_injective
lemma summable_subtype_and_compl {s : set β} :
summable (λ x : s, f x) ∧ summable (λ x : sᶜ, f x) ↔ summable f :=
⟨and_imp.2 summable.add_compl, λ h, ⟨h.subtype s, h.subtype sᶜ⟩⟩
lemma summable.sigma_factor {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) (b : β) : summable (λc, f ⟨b, c⟩) :=
ha.comp_injective sigma_mk_injective
lemma summable.sigma {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) : summable (λb, ∑'c, f ⟨b, c⟩) :=
ha.sigma' (λ b, ha.sigma_factor b)
lemma summable.prod_factor {f : β × γ → α} (h : summable f) (b : β) :
summable (λ c, f (b, c)) :=
h.comp_injective $ λ c₁ c₂ h, (prod.ext_iff.1 h).2
section loc_instances
-- enable inferring a T3-topological space from a topological group
local attribute [instance] topological_add_group.t3_space
-- disable getting a T0-space from a T3-space as this causes loops
local attribute [-instance] t3_space.to_t0_space
lemma tsum_sigma [t0_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ :=
tsum_sigma' (λ b, ha.sigma_factor b) ha
lemma tsum_prod [t0_space α] {f : β × γ → α} (h : summable f) :
∑'p, f p = ∑'b c, f ⟨b, c⟩ :=
tsum_prod' h h.prod_factor
lemma tsum_comm [t0_space α] {f : β → γ → α} (h : summable (function.uncurry f)) :
∑' c b, f b c = ∑' b c, f b c :=
tsum_comm' h h.prod_factor h.prod_symm.prod_factor
end loc_instances
lemma tsum_subtype_add_tsum_subtype_compl [t2_space α] {f : β → α} (hf : summable f) (s : set β) :
∑' x : s, f x + ∑' x : sᶜ, f x = ∑' x, f x :=
((hf.subtype s).has_sum.add_compl (hf.subtype {x | x ∉ s}).has_sum).unique hf.has_sum
lemma sum_add_tsum_subtype_compl [t2_space α] {f : β → α} (hf : summable f) (s : finset β) :
∑ x in s, f x + ∑' x : {x // x ∉ s}, f x = ∑' x, f x :=
begin
rw ← tsum_subtype_add_tsum_subtype_compl hf s,
simp only [finset.tsum_subtype', add_right_inj],
refl,
end
end uniform_group
section topological_group
variables {G : Type*} [topological_space G] [add_comm_group G] [topological_add_group G]
{f : α → G}
lemma summable.vanishing (hf : summable f) ⦃e : set G⦄ (he : e ∈ 𝓝 (0 : G)) :
∃ s : finset α, ∀ t, disjoint t s → ∑ k in t, f k ∈ e :=
begin
letI : uniform_space G := topological_add_group.to_uniform_space G,
letI : uniform_add_group G := topological_add_comm_group_is_uniform,
rcases hf with ⟨y, hy⟩,
exact cauchy_seq_finset_iff_vanishing.1 hy.cauchy_seq e he
end
/-- Series divergence test: if `f` is a convergent series, then `f x` tends to zero along
`cofinite`. -/
lemma summable.tendsto_cofinite_zero (hf : summable f) : tendsto f cofinite (𝓝 0) :=
begin
intros e he,
rw [filter.mem_map],
rcases hf.vanishing he with ⟨s, hs⟩,
refine s.eventually_cofinite_nmem.mono (λ x hx, _),
by simpa using hs {x} (disjoint_singleton_left.2 hx)
end
lemma summable.tendsto_at_top_zero {f : ℕ → G} (hf : summable f) : tendsto f at_top (𝓝 0) :=
by { rw ←nat.cofinite_eq_at_top, exact hf.tendsto_cofinite_zero }
end topological_group
section const_smul
variables [monoid γ] [topological_space α] [add_comm_monoid α] [distrib_mul_action γ α]
[has_continuous_const_smul γ α] {f : β → α}
lemma has_sum.const_smul {a : α} (b : γ) (hf : has_sum f a) : has_sum (λ i, b • f i) (b • a) :=
hf.map (distrib_mul_action.to_add_monoid_hom α _) $ continuous_const_smul _
lemma summable.const_smul (b : γ) (hf : summable f) : summable (λ i, b • f i) :=
(hf.has_sum.const_smul _).summable
/-- Infinite sums commute with scalar multiplication. Version for scalars living in a `monoid`, but
requiring a summability hypothesis. -/
lemma tsum_const_smul [t2_space α] (b : γ) (hf : summable f) : ∑' i, b • f i = b • ∑' i, f i :=
(hf.has_sum.const_smul _).tsum_eq
/-- Infinite sums commute with scalar multiplication. Version for scalars living in a `group`, but
not requiring any summability hypothesis. -/
lemma tsum_const_smul' {γ : Type*} [group γ] [distrib_mul_action γ α]
[has_continuous_const_smul γ α] [t2_space α] (g : γ) :
∑' (i : β), g • f i = g • ∑' (i : β), f i :=
begin
by_cases hf : summable f,
{ exact tsum_const_smul _ hf, },
rw tsum_eq_zero_of_not_summable hf,
simp only [smul_zero],
let mul_g : α ≃+ α := distrib_mul_action.to_add_equiv α g,
apply tsum_eq_zero_of_not_summable,
change ¬ summable (mul_g ∘ f),
rwa summable.map_iff_of_equiv mul_g; apply continuous_const_smul,
end
/-- Infinite sums commute with scalar multiplication. Version for scalars living in a
`division_ring`; no summability hypothesis. This could be made to work for a
`[group_with_zero γ]` if there was such a thing as `distrib_mul_action_with_zero`. -/
lemma tsum_const_smul'' {γ : Type*} [division_ring γ] [module γ α] [has_continuous_const_smul γ α]
[t2_space α] (g : γ) :
∑' (i : β), g • f i = g • ∑' (i : β), f i :=
begin
by_cases hf : summable f,
{ exact tsum_const_smul _ hf, },
rw tsum_eq_zero_of_not_summable hf,
simp only [smul_zero],
by_cases hg : g = 0,
{ simp [hg], },
let mul_g : α ≃+ α := distrib_mul_action.to_add_equiv₀ α g hg,
apply tsum_eq_zero_of_not_summable,
change ¬ summable (mul_g ∘ f),
rwa summable.map_iff_of_equiv mul_g; apply continuous_const_smul,
end
end const_smul
/-! ### Product and pi types -/
section prod
variables [add_comm_monoid α] [topological_space α] [add_comm_monoid γ] [topological_space γ]
lemma has_sum.prod_mk {f : β → α} {g : β → γ} {a : α} {b : γ}
(hf : has_sum f a) (hg : has_sum g b) :
has_sum (λ x, (⟨f x, g x⟩ : α × γ)) ⟨a, b⟩ :=
by simp [has_sum, ← prod_mk_sum, filter.tendsto.prod_mk_nhds hf hg]
end prod
section pi
variables {ι : Type*} {π : α → Type*} [∀ x, add_comm_monoid (π x)] [∀ x, topological_space (π x)]
lemma pi.has_sum {f : ι → ∀ x, π x} {g : ∀ x, π x} :
has_sum f g ↔ ∀ x, has_sum (λ i, f i x) (g x) :=
by simp only [has_sum, tendsto_pi_nhds, sum_apply]
lemma pi.summable {f : ι → ∀ x, π x} : summable f ↔ ∀ x, summable (λ i, f i x) :=
by simp only [summable, pi.has_sum, skolem]
lemma tsum_apply [∀ x, t2_space (π x)] {f : ι → ∀ x, π x}{x : α} (hf : summable f) :
(∑' i, f i) x = ∑' i, f i x :=
(pi.has_sum.mp hf.has_sum x).tsum_eq.symm
end pi
/-! ### Multiplicative opposite -/
section mul_opposite
open mul_opposite
variables [add_comm_monoid α] [topological_space α] {f : β → α} {a : α}
lemma has_sum.op (hf : has_sum f a) : has_sum (λ a, op (f a)) (op a) :=
(hf.map (@op_add_equiv α _) continuous_op : _)
lemma summable.op (hf : summable f) : summable (op ∘ f) := hf.has_sum.op.summable
lemma has_sum.unop {f : β → αᵐᵒᵖ} {a : αᵐᵒᵖ} (hf : has_sum f a) :
has_sum (λ a, unop (f a)) (unop a) :=
(hf.map (@op_add_equiv α _).symm continuous_unop : _)
lemma summable.unop {f : β → αᵐᵒᵖ} (hf : summable f) : summable (unop ∘ f) :=
hf.has_sum.unop.summable
@[simp] lemma has_sum_op : has_sum (λ a, op (f a)) (op a) ↔ has_sum f a :=
⟨has_sum.unop, has_sum.op⟩
@[simp] lemma has_sum_unop {f : β → αᵐᵒᵖ} {a : αᵐᵒᵖ} :
has_sum (λ a, unop (f a)) (unop a) ↔ has_sum f a :=
⟨has_sum.op, has_sum.unop⟩
@[simp] lemma summable_op : summable (λ a, op (f a)) ↔ summable f := ⟨summable.unop, summable.op⟩
@[simp] lemma summable_unop {f : β → αᵐᵒᵖ} : summable (λ a, unop (f a)) ↔ summable f :=
⟨summable.op, summable.unop⟩
variables [t2_space α]
lemma tsum_op : ∑' x, mul_opposite.op (f x) = mul_opposite.op (∑' x, f x) :=
begin
by_cases h : summable f,
{ exact h.has_sum.op.tsum_eq },
{ have ho := summable_op.not.mpr h,
rw [tsum_eq_zero_of_not_summable h, tsum_eq_zero_of_not_summable ho, mul_opposite.op_zero] }
end
lemma tsum_unop {f : β → αᵐᵒᵖ} : ∑' x, mul_opposite.unop (f x) = mul_opposite.unop (∑' x, f x) :=
mul_opposite.op_injective tsum_op.symm
end mul_opposite
/-! ### Interaction with the star -/
section has_continuous_star
variables [add_comm_monoid α] [topological_space α] [star_add_monoid α] [has_continuous_star α]
{f : β → α} {a : α}
lemma has_sum.star (h : has_sum f a) : has_sum (λ b, star (f b)) (star a) :=
by simpa only using h.map (star_add_equiv : α ≃+ α) continuous_star
lemma summable.star (hf : summable f) : summable (λ b, star (f b)) :=
hf.has_sum.star.summable
lemma summable.of_star (hf : summable (λ b, star (f b))) : summable f :=
by simpa only [star_star] using hf.star
@[simp] lemma summable_star_iff : summable (λ b, star (f b)) ↔ summable f :=
⟨summable.of_star, summable.star⟩
@[simp] lemma summable_star_iff' : summable (star f) ↔ summable f := summable_star_iff
variables [t2_space α]
lemma tsum_star : star (∑' b, f b) = ∑' b, star (f b) :=
begin
by_cases hf : summable f,
{ exact hf.has_sum.star.tsum_eq.symm, },
{ rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt summable.of_star hf),
star_zero] },
end
end has_continuous_star
section automorphize
variables {M : Type*} [topological_space M] [add_comm_monoid M] [t2_space M] {R : Type*}
[division_ring R] [module R M] [has_continuous_const_smul R M]
/-- Given a group `α` acting on a type `β`, and a function `f : β → M`, we "automorphize" `f` to a
function `β ⧸ α → M` by summing over `α` orbits, `b ↦ ∑' (a : α), f(a • b)`. -/
@[to_additive "Given an additive group `α` acting on a type `β`, and a function `f : β → M`,
we automorphize `f` to a function `β ⧸ α → M` by summing over `α` orbits,
`b ↦ ∑' (a : α), f(a • b)`."]
def mul_action.automorphize [group α] [mul_action α β] (f : β → M) :
quotient (mul_action.orbit_rel α β) → M :=
@quotient.lift _ _ (mul_action.orbit_rel α β) (λ b, ∑' (a : α), f(a • b))
begin
rintros b₁ b₂ ⟨a, (rfl : a • b₂ = b₁)⟩,
simpa [mul_smul] using (equiv.mul_right a).tsum_eq (λ a', f (a' • b₂)),
end
/-- Automorphization of a function into an `R`-`module` distributes, that is, commutes with the
`R`-scalar multiplication. -/
lemma mul_action.automorphize_smul_left [group α] [mul_action α β] (f : β → M)
(g : quotient (mul_action.orbit_rel α β) → R) :
mul_action.automorphize ((g ∘ quotient.mk') • f)
= g • (mul_action.automorphize f : quotient (mul_action.orbit_rel α β) → M) :=
begin
ext x,
apply quotient.induction_on' x,
intro b,
simp only [mul_action.automorphize, pi.smul_apply', function.comp_app],
set π : β → quotient (mul_action.orbit_rel α β) := quotient.mk',
have H₁ : ∀ a : α, π (a • b) = π b,
{ intro a,
rw quotient.eq_rel,
fconstructor,
exact a,
simp, },
change ∑' a : α, g (π (a • b)) • f (a • b) = g (π b) • ∑' a : α, f (a • b),
simp_rw [H₁],
exact tsum_const_smul'' _,
end
/-- Automorphization of a function into an `R`-`module` distributes, that is, commutes with the
`R`-scalar multiplication. -/
lemma add_action.automorphize_smul_left [add_group α] [add_action α β] (f : β → M)
(g : quotient (add_action.orbit_rel α β) → R) :
add_action.automorphize ((g ∘ quotient.mk') • f)
= g • (add_action.automorphize f : quotient (add_action.orbit_rel α β) → M) :=
begin
ext x,
apply quotient.induction_on' x,
intro b,
simp only [add_action.automorphize, pi.smul_apply', function.comp_app],
set π : β → quotient (add_action.orbit_rel α β) := quotient.mk',
have H₁ : ∀ a : α, π (a +ᵥ b) = π b,
{ intro a,
rw quotient.eq_rel,
fconstructor,
exact a,
simp, },
change ∑' a : α, g (π (a +ᵥ b)) • f (a +ᵥ b) = g (π b) • ∑' a : α, f (a +ᵥ b),
simp_rw [H₁],
exact tsum_const_smul'' _,
end
attribute [to_additive mul_action.automorphize_smul_left] add_action.automorphize_smul_left
section
variables {G : Type*} [group G] {Γ : subgroup G}
/-- Given a subgroup `Γ` of a group `G`, and a function `f : G → M`, we "automorphize" `f` to a
function `G ⧸ Γ → M` by summing over `Γ` orbits, `g ↦ ∑' (γ : Γ), f(γ • g)`. -/
@[to_additive "Given a subgroup `Γ` of an additive group `G`, and a function `f : G → M`, we
automorphize `f` to a function `G ⧸ Γ → M` by summing over `Γ` orbits,
`g ↦ ∑' (γ : Γ), f(γ • g)`."]
def quotient_group.automorphize (f : G → M) : G ⧸ Γ → M := mul_action.automorphize f
/-- Automorphization of a function into an `R`-`module` distributes, that is, commutes with the
`R`-scalar multiplication. -/
lemma quotient_group.automorphize_smul_left (f : G → M) (g : G ⧸ Γ → R) :
quotient_group.automorphize ((g ∘ quotient.mk') • f)
= g • (quotient_group.automorphize f : G ⧸ Γ → M) :=
mul_action.automorphize_smul_left f g
end
section
variables {G : Type*} [add_group G] {Γ : add_subgroup G}
/-- Automorphization of a function into an `R`-`module` distributes, that is, commutes with the `R`
-scalar multiplication. -/
lemma quotient_add_group.automorphize_smul_left (f : G → M) (g : G ⧸ Γ → R) :
quotient_add_group.automorphize ((g ∘ quotient.mk') • f)
= g • (quotient_add_group.automorphize f : G ⧸ Γ → M) :=
add_action.automorphize_smul_left f g
end
attribute [to_additive quotient_group.automorphize_smul_left]
quotient_add_group.automorphize_smul_left
end automorphize
|
83cf85f2ebd473fb3b156ba4e49aa151b694cd88
|
e30ff3aabdac29f8ea40ad76887544d0f9be9018
|
/ircbot/bitvec.lean
|
a3f582fc70932dac7d550f45f566ee7c46c33f84
|
[] |
no_license
|
forked-from-1kasper/leanbot
|
bdef0efa3e4d0eb75b06c1707fb4e35086bb57fa
|
c61c8c7fdad7b05877e0d232719ce23d2999557f
|
refs/heads/master
| 1,651,846,081,986
| 1,646,404,009,000
| 1,646,404,009,000
| 127,132,795
| 12
| 1
| null | 1,605,183,650,000
| 1,522,237,998,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 494
|
lean
|
import data.vector
def bitvec := vector bool
def {u} vector.singleton {α : Type u} : α → vector α 1 :=
λ b, ⟨[b], rfl⟩
namespace bitvec
def of_nat : Π (n : ℕ), nat → bitvec n
| 0 x := vector.nil
| (n + 1) x := vector.append (of_nat n (x / 2))
(vector.singleton (to_bool (x % 2 = 1)))
def add_lsb (r : ℕ) (b : bool) := r + r + cond b 1 0
def bits_to_nat (v : list bool) : nat :=
v.foldl add_lsb 0
end bitvec
|
29f0b0eeee141f6ab84e416578c8c8005d1dcbb7
|
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
|
/tests/lean/run/localNameResolutionWithProj.lean
|
d15d59d7fbfcd0adbcf035a3174a03afeb9bb4ad
|
[
"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
| 252
|
lean
|
macro "foo!" x:term : term => `(let xs := $x; xs.succ + xs)
def f1 (x : Nat) : Nat :=
foo! x+1
theorem ex1 (x : Nat) : f1 x = Nat.succ (x+1) + (x + 1) :=
rfl
def f2 (xs : Nat) : Nat :=
foo! xs
theorem ex2 (x : Nat) : f2 x = Nat.succ x + x :=
rfl
|
836290339f86c8a7be2c3e4151eb7065b481f3d2
|
74addaa0e41490cbaf2abd313a764c96df57b05d
|
/Mathlib/tactic/delta_instance_auto.lean
|
48913f6f3a78f19c2c5d8a595da9359f27bcbee2
|
[] |
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
| 788
|
lean
|
/-
Copyright (c) 2019 Rob Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rob Lewis
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.simp_result
import Mathlib.PostPort
namespace Mathlib
namespace tactic
/--
`delta_instance ids` tries to solve the goal by calling `apply_instance`,
first unfolding the definitions in `ids`.
-/
-- We call `dsimp_result` here because otherwise
-- `delta_target` will insert an `id` in the result.
-- See the note [locally reducible category instances]
-- https://github.com/leanprover-community/mathlib/blob/c9fca15420e2ad443707ace831679fd1762580fe/src/algebra/category/Mon/basic.lean#L27
-- for an example where this used to cause a problem.
end Mathlib
|
c3846b293fffb9665a8a6541d2fdf124ea972fb9
|
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
|
/tactic/chain.lean
|
337d9c490415a670dd807408a379048d6ac0732a
|
[
"Apache-2.0"
] |
permissive
|
kckennylau/mathlib
|
21fb810b701b10d6606d9002a4004f7672262e83
|
47b3477e20ffb5a06588dd3abb01fe0fe3205646
|
refs/heads/master
| 1,634,976,409,281
| 1,542,042,832,000
| 1,542,319,733,000
| 109,560,458
| 0
| 0
|
Apache-2.0
| 1,542,369,208,000
| 1,509,867,494,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 4,958
|
lean
|
-- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison, Mario Carneiro
import tactic
import data.option
open interactive
namespace tactic
/-
This file defines a `chain` tactic, which takes a list of tactics, and exhaustively tries to apply them
to the goals, until no tactic succeeds on any goal.
Along the way, it generates auxiliary declarations, in order to speed up elaboration time
of the resulting (sometimes long!) proofs.
This tactic is used by the `tidy` tactic.
-/
-- α is the return type of our tactics. When `chain` is called by `tidy`, this is string,
-- describing what that tactic did as an interactive tactic.
variable {α : Type}
/-
Because chain sometimes pauses work on the first goal and works on later goals, we need a method
for combining a list of results generated while working on a later goal into a single result.
This enables `tidy {trace_result := tt}` to output faithfully reproduces its operation, e.g.
````
intros,
simp,
apply lemma_1,
work_on_goal 2 {
dsimp,
simp
},
refl
````
-/
namespace interactive
open lean.parser
meta def work_on_goal : parse small_nat → itactic → tactic unit
| n t := do goals ← get_goals,
let earlier_goals := goals.take n,
let later_goals := goals.drop (n+1),
set_goals (goals.nth n).to_list,
t,
new_goals ← get_goals,
set_goals (earlier_goals ++ new_goals ++ later_goals)
end interactive
inductive tactic_script (α : Type) : Type
| base : α → tactic_script
| work (index : ℕ) (first : α) (later : list tactic_script) (closed : bool) : tactic_script
meta def tactic_script.to_string : tactic_script string → string
| (tactic_script.base a) := a
| (tactic_script.work n a l c) := "work_on_goal " ++ (to_string n) ++ " { " ++ (", ".intercalate (a :: l.map tactic_script.to_string)) ++ " }"
meta instance : has_to_string (tactic_script string) :=
{ to_string := λ s, s.to_string }
meta instance tactic_script_unit_has_to_string : has_to_string (tactic_script unit) :=
{ to_string := λ s, "[chain tactic]" }
meta def abstract_if_success (tac : expr → tactic α) (g : expr) : tactic α :=
do
type ← infer_type g,
is_lemma ← is_prop type,
if is_lemma then -- there's no point making the abstraction, and indeed it's slower
tac g
else do
m ← mk_meta_var type,
a ← tac m,
do {
val ← instantiate_mvars m,
guard (val.list_meta_vars = []),
c ← new_aux_decl_name,
gs ← get_goals,
set_goals [g],
add_aux_decl c type val ff >>= unify g,
set_goals gs }
<|> unify m g,
return a
/--
`chain_many tac` recursively tries `tac` on all goals, working depth-first on generated subgoals,
until it no longer succeeds on any goal. `chain_many` automatically makes auxiliary definitions.
-/
meta mutual def chain_single, chain_many, chain_iter {α} (tac : tactic α)
with chain_single : expr → tactic (α × list (tactic_script α)) | g :=
do set_goals [g],
a ← tac,
l ← get_goals >>= chain_many,
return (a, l)
with chain_many : list expr → tactic (list (tactic_script α))
| [] := return []
| [g] := do {
(a, l) ← chain_single g,
return (tactic_script.base a :: l) } <|> return []
| gs := chain_iter gs []
with chain_iter : list expr → list expr → tactic (list (tactic_script α))
| [] _ := return []
| (g :: later_goals) stuck_goals := do {
(a, l) ← abstract_if_success chain_single g,
new_goals ← get_goals,
let w := tactic_script.work stuck_goals.length a l (new_goals = []),
let current_goals := stuck_goals.reverse ++ new_goals ++ later_goals,
set_goals current_goals, -- we keep the goals up to date, so they are correct at the end
l' ← chain_many current_goals,
return (w :: l') } <|> chain_iter later_goals (g :: stuck_goals)
meta def chain_core {α : Type} [has_to_string (tactic_script α)] (tactics : list (tactic α)) : tactic (list string) :=
do results ← (get_goals >>= chain_many (first tactics)),
when results.empty (fail "`chain` tactic made no progress"),
return (results.map to_string)
variables [has_to_string (tactic_script α)] [has_to_format α]
declare_trace chain
meta def trace_output (t : tactic α) : tactic α :=
do tgt ← target,
r ← t,
name ← decl_name,
trace format!"`chain` successfully applied a tactic during elaboration of {name}:",
tgt ← pp tgt,
trace format!"previous target: {tgt}",
trace format!"tactic result: {r}",
tgt ← try_core target,
tgt ← match tgt with
| (some tgt) := pp tgt
| none := return "no goals"
end,
trace format!"new target: {tgt}",
pure r
meta def chain (tactics : list (tactic α)) : tactic (list string) :=
if is_trace_enabled_for `chain then
chain_core (tactics.map trace_output)
else
chain_core tactics
end tactic
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.