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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a62e5fa2b8db702527031736401f760299c10682 | 59aed81a2ce7741e690907fc374be338f4f88b6f | /src/walks.lean | c93257a9e9f9d2f04555db1c91e142f316928570 | [] | no_license | agusakov/math-688-lean | c84d5e1423eb208a0281135f0214b91b30d0ef48 | 67dc27ebff55a74c6b5a1c469ba04e7981d2e550 | refs/heads/main | 1,679,699,340,788 | 1,616,602,782,000 | 1,616,602,782,000 | 332,894,454 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 19,688 | lean | /-
Copyright (c) 2020 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Kyle Miller
-/
import data.finset.basic
import combinatorics.simple_graph.basic
import tactic.omega
/-!
# Walks and paths
A walk in a simple graph is a finite sequence of adjacent vertices. A path is a walk that visits
each vertex only once.
## Main definitions
* `simple_graph.walk` is the type of walks between pairs of vertices
* `simple_graph.walk.is_path` is a predicate that determines whether a walk is a path.
* `simple_graph.walk.to_path` constructs a path from a walk with the same endpoints.
* `simple_graph.exists_walk` is the walk-connectivity relation.
* `simple_graph.connected_components` is the quotient of the vertex type by walk-connectivity.
* `simple_graph.exists_walk_eq_exists_path` and `simple_graph.exists_walk_eq_eqv_gen` give that
walk-connectivity, path-connectivity, and `eqv_gen G.adj` are the each the same relation.
* `simple_graph.walk.get_vert` parameterizes the vertices of a walk by natural numbers.
* `simple_graph.walk.is_path_iff` characterizes paths as walks for which `get_vert` is injective.
## Tags
walks, paths
-/
universes u
namespace simple_graph
variables {V : Type u} (G : simple_graph V)
-- lemma that says card of support is equal to length iff it's a path
/-- A walk is a sequence of incident edges in a graph, represented here as a sequence of adjacent
vertices. -/
inductive walk : V β V β Type u
| nil {u : V} : walk u u
| cons {u v w : V} (h : G.adj u v) (p : walk v w) : walk u w
attribute [refl] walk.nil
instance walk.inhabited (v : V) : inhabited (G.walk v v) := β¨walk.nilβ©
namespace walk
variables {G}
/-- The length of a walk is the number of edges along it. -/
def length : Ξ {u v : V}, G.walk u v β β
| _ _ nil := 0
| _ _ (cons _ q) := q.length.succ
/-- The concatenation of two compatible walks. -/
@[trans]
def concat : Ξ {u v w : V}, G.walk u v β G.walk v w β G.walk u w
| _ _ _ nil q := q
| _ _ _ (cons h p) q := cons h (concat p q)
/-- The concatenation of the reverse of the first walk with the second walk. -/
protected def reverse_aux : Ξ {u v w : V}, G.walk u v β G.walk u w β G.walk v w
| _ _ _ nil q := q
| _ _ _ (cons h p) q := reverse_aux p (cons (G.sym h) q)
/-- Reverse the orientation of a walk. -/
@[symm]
def reverse {u v : V} (w : G.walk u v) : G.walk v u := w.reverse_aux nil
/-- Get the nth vertex from a path, where if i is greater than the length of the path
the result is the endpoint of the path. -/
def get_vert : Ξ {u v : V} (p : G.walk u v) (i : β), V
| u v nil _ := u
| u v (cons _ _) 0 := u
| u v (cons _ q) (i+1) := q.get_vert i
variables [decidable_eq V]
/-- The support of a walk is the finite set of vertices it visits. -/
def support : Ξ {u v : V}, G.walk u v β finset V
| u v nil := {u}
| u v (cons h p) := insert u p.support
-- ?????
def count (w : V) : Ξ {u v : V}, G.walk u v β β
| u v nil := if u = w β¨ v = w then 1 else 0
| u v (cons h p) := if u = w then nat.succ (count p) else (count p)
/-- A path is a walk that visits each vertex at most once. -/
def is_path : Ξ {u v : V}, G.walk u v β Prop
| u v nil := true
| u v (cons h p) := p.is_path β§ Β¬ u β p.support
end walk
/-- The relation on vertices of whether there exists a walk between them.
This is an equivalence relation. -/
def exists_walk : V β V β Prop := Ξ» v w, nonempty (G.walk v w)
/-- The relation on vertices of whether there exists a path between them.
This is equal to `simple_graph.exists_walk`. -/
def exists_path [decidable_eq V]: V β V β Prop := Ξ» v w, β (p : G.walk v w), p.is_path
@[refl] lemma exists_walk.refl (v : V) : G.exists_walk v v :=
by { fsplit, refl, }
@[symm] lemma exists_walk.symm β¦v w : Vβ¦ (hvw : G.exists_walk v w) : G.exists_walk w v :=
by { tactic.unfreeze_local_instances, cases hvw, use hvw.reverse, }
@[trans] lemma exists_walk.trans β¦u v w : Vβ¦ (huv : G.exists_walk u v) (hvw : G.exists_walk v w) :
G.exists_walk u w :=
by { tactic.unfreeze_local_instances, cases hvw, cases huv, use huv.concat hvw, }
lemma exists_walk.is_equivalence : equivalence G.exists_walk :=
mk_equivalence _ (exists_walk.refl G) (exists_walk.symm G) (exists_walk.trans G)
/-- The equivalence relation on vertices given by `simple_graph.exists_walk`. -/
def exists_walk.setoid : setoid V := setoid.mk _ (exists_walk.is_equivalence G)
/-- A connected component is an element of the quotient of the vertex type by the relation
`simple_graph.exists_walk`. -/
def connected_components := quotient (exists_walk.setoid G)
/-- A graph is connected if every vertex is connected to every other by a walk. -/
def is_connected : Prop := β v w, exists_walk G v w
instance connected_components.inhabited [inhabited V]: inhabited G.connected_components :=
β¨@quotient.mk _ (exists_walk.setoid G) (default _)β©
namespace walk
variables {G}
@[simp] lemma nil_length {u : V} : (nil : G.walk u u).length = 0 := rfl
@[simp] lemma cons_length {u v w : V} (h : G.adj u v) (p : G.walk v w) :
(cons h p).length = p.length + 1 := rfl
@[simp] lemma nil_reverse {u : V} : (nil : G.walk u u).reverse = nil := rfl
lemma singleton_reverse {u v : V} (h : G.adj u v) :
(cons h nil).reverse = cons (G.sym h) nil := rfl
@[simp] lemma cons_concat {u v w x : V} (h : G.adj u v) (p : G.walk v w) (q : G.walk w x) :
(cons h p).concat q = cons h (p.concat q) := rfl
lemma cons_as_concat {u v w : V} (h : G.adj u v) (p : G.walk v w) :
cons h p = concat (cons h nil) p := rfl
@[simp] lemma concat_nil : Ξ {u v : V} (p : G.walk u v), p.concat nil = p
| _ _ nil := rfl
| _ _ (cons h p) := by rw [cons_concat, concat_nil]
@[simp] lemma nil_concat {u v : V} (p : G.walk u v) : nil.concat p = p := rfl
lemma concat_assoc : Ξ {u v w x : V} (p : G.walk u v) (q : G.walk v w) (r : G.walk w x),
p.concat (q.concat r) = (p.concat q).concat r
| _ _ _ _ nil _ _ := rfl
| _ _ _ _ (cons h p') q r := by { dsimp only [concat], rw concat_assoc, }
@[simp]
protected lemma reverse_aux_eq_reverse_concat {u v w : V} (p : G.walk u v) (q : G.walk u w) :
p.reverse_aux q = p.reverse.concat q :=
begin
induction p generalizing q w,
{ refl },
{ dsimp [walk.reverse_aux, walk.reverse],
repeat { rw p_ih },
rw βconcat_assoc,
refl, }
end
@[simp] lemma concat_reverse {u v w : V} (p : G.walk u v) (q : G.walk v w) :
(p.concat q).reverse = q.reverse.concat p.reverse :=
begin
induction p generalizing q w,
{ simp },
{ dsimp only [cons_concat, reverse, walk.reverse_aux],
simp only [p_ih, walk.reverse_aux_eq_reverse_concat, concat_nil],
rw concat_assoc, }
end
@[simp] lemma cons_reverse {u v w : V} (h : G.adj u v) (p : G.walk v w) :
(cons h p).reverse = p.reverse.concat (cons (G.sym h) nil) :=
begin
dsimp [reverse, walk.reverse_aux],
simp only [walk.reverse_aux_eq_reverse_concat, concat_nil],
end
@[simp] lemma reverse_reverse : Ξ {u v : V} (p : G.walk u v), p.reverse.reverse = p
| _ _ nil := rfl
| _ _ (cons h p) := by simp [reverse_reverse]
@[simp] lemma concat_length : Ξ {u v w : V} (p : G.walk u v) (q : G.walk v w),
(p.concat q).length = p.length + q.length
| _ _ _ nil _ := by simp
| _ _ _ (cons _ p') _ := by simp [concat_length, add_left_comm, add_comm]
protected lemma reverse_aux_length {u v w : V} (p : G.walk u v) (q : G.walk u w) :
(p.reverse_aux q).length = p.length + q.length :=
begin
induction p,
{ dunfold walk.reverse_aux, simp, },
{ dunfold reverse_aux, rw p_ih, simp only [cons_length], ring, },
end
@[simp] lemma reverse_length {u v : V} (p : G.walk u v) : p.reverse.length = p.length :=
by { convert walk.reverse_aux_length p nil }
@[simp] lemma get_vert_0 {u v : V} (p : G.walk u v) : p.get_vert 0 = u :=
by { cases p; refl }
@[simp] lemma get_vert_n {u v : V} (p : G.walk u v) : p.get_vert p.length = v :=
by { induction p, refl, exact p_ih }
@[simp] lemma get_vert_nil {u : V} (i : β) : (nil : G.walk u u).get_vert i = u :=
by cases i; simp [get_vert]
@[simp] lemma get_vert_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) (i : β) :
(cons h p).get_vert (i + 1) = p.get_vert i := rfl
lemma concat_get_vert {u v w : V} (p : G.walk u v) (p' : G.walk v w) (i : β) :
(p.concat p').get_vert i = if i β€ p.length then p.get_vert i else p'.get_vert (i - p.length) :=
begin
induction p generalizing i,
{ simp only [get_vert_nil, nil_length, nil_concat, nat.sub_zero, nonpos_iff_eq_zero],
split_ifs,
{ subst i, simp, },
{ refl } },
{ simp only [cons_length, cons_concat],
cases i,
{ simp, },
{ simp [p_ih, nat.succ_le_succ_iff], } }
end
@[simp] lemma get_vert_reverse {u v : V} (p : G.walk u v) (i : β) :
p.reverse.get_vert i = p.get_vert (p.length - i) :=
begin
induction i generalizing u v,
{ simp },
{ induction p,
{ simp },
{ simp only [cons_reverse, concat_get_vert, p_ih, i_ih,
cons_length, reverse_length, nat.succ_sub_succ_eq_sub, cons_reverse],
split_ifs,
{ have h' : p_p.length - i_n = (p_p.length - i_n.succ).succ := by omega,
simp [h'], },
{ have h' : p_p.length - i_n = 0 := by omega,
have h'' : i_n.succ - p_p.length = (i_n - p_p.length).succ := by omega,
simp [h', h''], } } }
end
protected lemma ext_aux : Ξ {u v : V} (n : β) (p p' : G.walk u v)
(hβ : p.length = n) (hβ' : p'.length = n)
(hβ : β i, i β€ n β p.get_vert i = p'.get_vert i), p = p'
| _ _ 0 nil nil _ _ _ := rfl
| u v (n+1) (@cons _ _ _ w _ huw q) (@cons _ _ _ w' _ huw' q') hβ hβ' hβ :=
begin
have hw : w = w',
{ specialize hβ 1 (nat.le_add_left _ _),
simpa using hβ, },
subst w',
congr,
apply ext_aux n q q' (nat.succ.inj hβ) (nat.succ.inj hβ'),
intros i h,
exact hβ i.succ (nat.succ_le_succ h),
end
@[ext]
lemma ext {u v : V} (p p' : G.walk u v)
(hβ : p.length = p'.length)
(hβ : β i, i β€ p.length β p.get_vert i = p'.get_vert i) :
p = p' :=
walk.ext_aux p.length p p' rfl hβ.symm hβ
lemma adj_get_vert : Ξ {u v : V} (p : G.walk u v) (i : β) (h : i < p.length),
G.adj (p.get_vert i) (p.get_vert (i + 1))
| u v (cons huv p) 0 _ := by simp [huv]
| u v (cons huv p) (i+1) h := begin
rw cons_length at h,
simp only [get_vert_cons],
exact adj_get_vert _ i (nat.lt_of_succ_lt_succ h),
end
section paths
variables [decidable_eq V]
@[simp] lemma nil_support {u : V} : (nil : G.walk u u).support = {u} := rfl
@[simp] lemma cons_support {u v w : V} (h : G.adj u v) (p : G.walk v w) :
(cons h p).support = insert u p.support := rfl
@[simp] lemma start_mem_support {u v : V} (p : G.walk u v) : u β p.support :=
by cases p; simp [support]
@[simp] lemma end_mem_support {u v : V} (p : G.walk u v) : v β p.support :=
begin
induction p,
{ simp [support], },
{ simp [support, p_ih], },
end
/-- Given a walk and a vertex in that walk, give a sub-walk starting at that vertex. -/
def subwalk_from : Ξ {u v w : V} (p : G.walk u v), w β p.support β G.walk w v
| _ _ w nil h := by { rw [nil_support, finset.mem_singleton] at h, subst w }
| u v w (@cons _ _ _ x _ ha p) hs := begin
rw [cons_support, finset.mem_insert] at hs,
by_cases hw : w = u,
{ subst w, exact cons ha p },
{ have : w β p.support, { cases hs, exact false.elim (hw hs), exact hs },
exact p.subwalk_from this, },
end
lemma subwalk_from_path_is_path {u v w : V} (p : G.walk u v) (h : p.is_path) (hs : w β p.support) :
(p.subwalk_from hs).is_path :=
begin
induction p,
{ rw [nil_support, finset.mem_singleton] at hs,
subst w,
trivial },
{ rw [cons_support, finset.mem_insert] at hs,
dsimp only [is_path] at h,
simp only [subwalk_from],
split_ifs,
{ subst p_u,
simp [is_path, h] },
{ cases hs,
{ exact false.elim (h_1 hs_1), },
{ exact p_ih h.1 _, } } },
end
/-- Given a walk, form a path between the same endpoints by splicing out unnecessary detours.
See `simple_graph.walk.to_path_is_path` -/
def to_path : Ξ {u v : V}, G.walk u v β G.walk u v
| u v nil := nil
| u v (@cons _ _ _ x _ ha p) :=
let p' := p.to_path
in if hs : u β p'.support
then p'.subwalk_from hs
else cons ha p'
lemma subwalk_from_support_subset.aux (n' : β) :
Ξ {u v w : V} (p : G.walk u v) (hl : p.length = n') (h : w β p.support),
(p.subwalk_from h).support β p.support :=
begin
refine nat.strong_induction_on n' (Ξ» n ih, _),
intros u v w p hl h,
cases p,
{ rw [nil_support, finset.mem_singleton] at h,
subst w,
trivial, },
{ dsimp only [subwalk_from, support],
rw [cons_support, finset.mem_insert] at h,
split_ifs,
{ subst h_1,
simp, },
{ have h' : w β p_p.support := by cc,
refine finset.subset.trans _ (finset.subset_insert _ _),
convert_to (p_p.subwalk_from h').support β p_p.support,
rw cons_length at hl,
apply ih p_p.length (by linarith) _ rfl, }, },
end
lemma subwalk_from_support_subset {u v w : V} (p : G.walk u v) (h : w β p.support) :
(p.subwalk_from h).support β p.support :=
subwalk_from_support_subset.aux p.length p rfl h
lemma to_path_support_subset {u v : V} (p : G.walk u v) : p.to_path.support β p.support :=
begin
induction p,
{ trivial, },
{ dsimp only [to_path, support],
split_ifs,
{ refine finset.subset.trans (finset.subset.trans _ p_ih) (finset.subset_insert _ _),
apply subwalk_from_support_subset, },
{ intro x,
simp only [cons_support, finset.mem_insert],
intro h,
cases h,
{ subst p_u,
exact or.inl rfl, },
{ exact or.inr (p_ih h_1), }, }, },
end
lemma to_path_is_path {u v : V} (p : G.walk u v) : p.to_path.is_path :=
begin
induction p,
{ trivial, },
{ dsimp [to_path, is_path],
split_ifs,
{ apply subwalk_from_path_is_path _ p_ih, },
{ use p_ih, }, },
end
@[simp] lemma nil_is_path {u : V} : (nil : G.walk u u).is_path := by trivial
@[simp] lemma singleton_is_path {u v : V} (h : G.adj u v) : (cons h nil).is_path :=
begin
simp only [is_path, true_and, nil_support, finset.mem_singleton],
intro h',
subst u,
exact G.loopless _ h,
end
@[simp]
lemma concat_support {u v w : V} (p : G.walk u v) (p' : G.walk v w) :
(p.concat p').support = p.support βͺ p'.support :=
begin
induction p generalizing p' w,
{ simp, },
{ simp only [finset.insert_union, cons_concat, cons_support],
apply congr_arg _ (p_ih _), },
end
@[simp]
lemma reverse_support {u v : V} (p : G.walk u v) : p.reverse.support = p.support :=
begin
induction p,
{ trivial, },
{ simp only [support, finset.insert_eq_of_mem, end_mem_support, concat_support,
true_or, cons_reverse, finset.mem_union, finset.union_insert],
rw [finset.union_comm, βfinset.insert_eq],
apply congr_arg _ p_ih, },
end
lemma get_vert_mem_support {u v} (p : G.walk u v) (i : β) : p.get_vert i β p.support :=
begin
induction p generalizing i,
{ simp, },
{ cases i,
{ simp, },
{ simp only [cons_support, finset.mem_insert, get_vert_cons],
right,
apply p_ih, }, },
end
lemma mem_support_exists_get_vert {u v w} (p : G.walk u v) (h : w β p.support) :
β i, i β€ p.length β§ p.get_vert i = w :=
begin
induction p,
{ rw [nil_support, finset.mem_singleton] at h,
subst w,
simp, },
{ rw [cons_support, finset.mem_insert] at h,
cases h,
{ subst w, use 0, simp, },
{ specialize p_ih h,
rcases p_ih with β¨i, hi, hvβ©,
use i+1, subst w, simp [hi],}, },
end
protected lemma is_path_iff.aux {u v : V} (p : G.walk u v) :
p.is_path β β (i k : β) (hi : i β€ p.length) (hk : i + k β€ p.length),
p.get_vert i = p.get_vert (i + k) β k = 0 :=
begin
split,
{ intros hp i,
induction i generalizing u v,
{ intro k,
induction k generalizing u v,
{ simp },
{ simp only [forall_prop_of_true, get_vert_0, zero_le, zero_add],
intros hk hu,
cases p,
{ simpa using hk },
{ simp only [get_vert_cons] at hu,
subst u,
exact false.elim (hp.2 (get_vert_mem_support _ _)) } } },
{ cases p,
{ simp, },
{ simp only [cons_length, get_vert_cons],
simp only [is_path] at hp,
intros k hi hk,
rw [add_comm, nat.add_succ], simp [get_vert],
intro hv,
rw [add_comm, nat.add_succ, add_comm] at hk,
apply i_ih p_p hp.1 _ (nat.succ_le_succ_iff.mp hi) (nat.succ_le_succ_iff.mp hk),
rw [hv, add_comm], } } },
{ intro h,
induction p,
{ simp },
{ simp only [is_path],
split,
{ apply p_ih,
intros i k hi hk hv,
apply h i.succ k (nat.succ_le_succ hi) _,
rw [add_comm, nat.add_succ, add_comm],
simp only [get_vert, hv, cons_length],
rw [add_comm, nat.add_succ, add_comm],
exact nat.succ_le_succ hk, },
{ intro hs,
rcases mem_support_exists_get_vert _ hs with β¨i, hl, rflβ©,
have h' := h 0 i.succ,
simp only [cons_length, forall_prop_of_true, get_vert_0,
zero_le, zero_add, get_vert_cons] at h',
specialize h' (nat.succ_le_succ hl),
exact nat.succ_ne_zero _ h', } } }
end
lemma is_path_iff {u v : V} (p : G.walk u v) :
p.is_path β β (i j : β) (hi : i β€ p.length) (hj : j β€ p.length),
p.get_vert i = p.get_vert j β i = j :=
begin
convert walk.is_path_iff.aux p,
simp only [eq_iff_iff],
split,
{ intros h i k hi hk hv,
specialize h i (i+k) hi hk hv,
linarith, },
{ intros h i j hi hj hv,
wlog : i β€ j using i j,
specialize h i (j-i) hi,
rw nat.add_sub_of_le case at h,
specialize h hj hv,
rw [(nat.sub_eq_iff_eq_add case).mp h, zero_add], }
end
lemma reverse_path {u v : V} (p : G.walk u v) (h : p.is_path) : p.reverse.is_path :=
begin
rw is_path_iff,
simp only [reverse_length, get_vert_reverse],
intros i j hi hj hp,
have hi' : p.length - i β€ p.length := by omega,
have hj' : p.length - j β€ p.length := by omega,
have h' := (is_path_iff p).mp h _ _ hi' hj' hp,
omega,
end
lemma is_path_if_concat_is_path {u v w} (p : G.walk u v) (p' : G.walk v w)
(h : (p.concat p').is_path) : p.is_path :=
begin
rw is_path_iff at h,
rw is_path_iff,
simp only [concat_get_vert, concat_length] at h,
intros i j hi hj hp,
specialize h i j (by omega) (by omega),
simp only [hi, hj, if_true] at h,
exact h hp,
end
lemma get_vert_image {u v} (p : G.walk u v) :
finset.image (Ξ» i, p.get_vert i) (finset.range (p.length + 1)) = p.support :=
begin
ext w,
simp only [exists_prop, finset.mem_image, finset.mem_range],
split,
{ simp only [and_imp, exists_imp_distrib],
rintros i ih rfl,
apply get_vert_mem_support, },
{ intro hw,
rcases mem_support_exists_get_vert p hw with β¨i, hi, hw'β©,
exact β¨i, by linarith, hw'β©, },
end
end paths
end walk
variables (G)
lemma exists_walk_eq_exists_path [decidable_eq V] : exists_walk G = exists_path G :=
begin
ext u v,
dsimp [exists_walk, exists_path],
split,
{ intro p, cases p, fsplit, use p.to_path, apply walk.to_path_is_path, },
{ intro p, cases p, fsplit, use p_w, },
end
lemma exists_walk_eq_eqv_gen : exists_walk G = eqv_gen G.adj :=
begin
ext v w,
split,
{ intro h,
cases h,
induction h,
{ exact eqv_gen.refl _ },
{ exact eqv_gen.trans _ _ _ (eqv_gen.rel _ _ h_h) h_ih } },
{ intro h,
induction h with x y h _ x y he h_ih x y z hxy hyz hxy_ih hyz_ih,
{ exact β¨walk.cons h walk.nilβ©, },
{ refl, },
{ cases h_ih,
exact β¨h_ih.reverseβ©, },
{ cases hxy_ih,
cases hyz_ih,
exact β¨hxy_ih.concat hyz_ihβ©, } }
end
end simple_graph
|
6cc0844fa47aad8c22451c0eb99c0831faf2db9a | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/lean/interactive/533.lean | e96fe253f32367452c612b0e88522d9a896cfb0b | [
"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 | 67 | lean | inductive Foo where
| bar : F
--^ textDocument/completion
|
90d59bb6bda70164372aa6e0f74bd83410f47dae | c777c32c8e484e195053731103c5e52af26a25d1 | /src/geometry/euclidean/angle/unoriented/basic.lean | d332c358a4407f9a6a8ab4d6ab14239f75e6f13b | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 15,403 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Manuel Candales
-/
import analysis.inner_product_space.basic
import analysis.special_functions.trigonometric.inverse
/-!
# Angles between vectors
This file defines unoriented angles in real inner product spaces.
## Main definitions
* `inner_product_geometry.angle` is the undirected angle between two vectors.
-/
assert_not_exists has_fderiv_at
assert_not_exists conformal_at
noncomputable theory
open real set
open_locale big_operators
open_locale real
open_locale real_inner_product_space
namespace inner_product_geometry
variables {V : Type*} [normed_add_comm_group V] [inner_product_space β V] {x y : V}
/-- The undirected angle between two vectors. If either vector is 0,
this is Ο/2. See `orientation.oangle` for the corresponding oriented angle
definition. -/
def angle (x y : V) : β := real.arccos (βͺx, yβ« / (βxβ * βyβ))
lemma continuous_at_angle {x : V Γ V} (hx1 : x.1 β 0) (hx2 : x.2 β 0) :
continuous_at (Ξ» y : V Γ V, angle y.1 y.2) x :=
real.continuous_arccos.continuous_at.comp $ continuous_inner.continuous_at.div
((continuous_norm.comp continuous_fst).mul (continuous_norm.comp continuous_snd)).continuous_at
(by simp [hx1, hx2])
lemma angle_smul_smul {c : β} (hc : c β 0) (x y : V) :
angle (c β’ x) (c β’ y) = angle x y :=
have c * c β 0, from mul_ne_zero hc hc,
by rw [angle, angle, real_inner_smul_left, inner_smul_right, norm_smul, norm_smul, real.norm_eq_abs,
mul_mul_mul_comm _ (βxβ), abs_mul_abs_self, β mul_assoc c c, mul_div_mul_left _ _ this]
@[simp] lemma _root_.linear_isometry.angle_map {E F : Type*}
[normed_add_comm_group E] [normed_add_comm_group F]
[inner_product_space β E] [inner_product_space β F] (f : E ββα΅’[β] F) (u v : E) :
angle (f u) (f v) = angle u v :=
by rw [angle, angle, f.inner_map_map, f.norm_map, f.norm_map]
@[simp, norm_cast] lemma _root_.submodule.angle_coe {s : submodule β V} (x y : s) :
angle (x : V) (y : V) = angle x y :=
s.subtypeβα΅’.angle_map x y
/-- The cosine of the angle between two vectors. -/
lemma cos_angle (x y : V) : real.cos (angle x y) = βͺx, yβ« / (βxβ * βyβ) :=
real.cos_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1
(abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2
/-- The angle between two vectors does not depend on their order. -/
lemma angle_comm (x y : V) : angle x y = angle y x :=
begin
unfold angle,
rw [real_inner_comm, mul_comm]
end
/-- The angle between the negation of two vectors. -/
@[simp] lemma angle_neg_neg (x y : V) : angle (-x) (-y) = angle x y :=
begin
unfold angle,
rw [inner_neg_neg, norm_neg, norm_neg]
end
/-- The angle between two vectors is nonnegative. -/
lemma angle_nonneg (x y : V) : 0 β€ angle x y :=
real.arccos_nonneg _
/-- The angle between two vectors is at most Ο. -/
lemma angle_le_pi (x y : V) : angle x y β€ Ο :=
real.arccos_le_pi _
/-- The angle between a vector and the negation of another vector. -/
lemma angle_neg_right (x y : V) : angle x (-y) = Ο - angle x y :=
begin
unfold angle,
rw [βreal.arccos_neg, norm_neg, inner_neg_right, neg_div]
end
/-- The angle between the negation of a vector and another vector. -/
lemma angle_neg_left (x y : V) : angle (-x) y = Ο - angle x y :=
by rw [βangle_neg_neg, neg_neg, angle_neg_right]
/-- The angle between the zero vector and a vector. -/
@[simp] lemma angle_zero_left (x : V) : angle 0 x = Ο / 2 :=
begin
unfold angle,
rw [inner_zero_left, zero_div, real.arccos_zero]
end
/-- The angle between a vector and the zero vector. -/
@[simp] lemma angle_zero_right (x : V) : angle x 0 = Ο / 2 :=
begin
unfold angle,
rw [inner_zero_right, zero_div, real.arccos_zero]
end
/-- The angle between a nonzero vector and itself. -/
@[simp] lemma angle_self {x : V} (hx : x β 0) : angle x x = 0 :=
begin
unfold angle,
rw [βreal_inner_self_eq_norm_mul_norm, div_self (inner_self_ne_zero.2 hx : βͺx, xβ« β 0),
real.arccos_one]
end
/-- The angle between a nonzero vector and its negation. -/
@[simp] lemma angle_self_neg_of_nonzero {x : V} (hx : x β 0) : angle x (-x) = Ο :=
by rw [angle_neg_right, angle_self hx, sub_zero]
/-- The angle between the negation of a nonzero vector and that
vector. -/
@[simp] lemma angle_neg_self_of_nonzero {x : V} (hx : x β 0) : angle (-x) x = Ο :=
by rw [angle_comm, angle_self_neg_of_nonzero hx]
/-- The angle between a vector and a positive multiple of a vector. -/
@[simp] lemma angle_smul_right_of_pos (x y : V) {r : β} (hr : 0 < r) :
angle x (r β’ y) = angle x y :=
begin
unfold angle,
rw [inner_smul_right, norm_smul, real.norm_eq_abs, abs_of_nonneg (le_of_lt hr), βmul_assoc,
mul_comm _ r, mul_assoc, mul_div_mul_left _ _ (ne_of_gt hr)]
end
/-- The angle between a positive multiple of a vector and a vector. -/
@[simp] lemma angle_smul_left_of_pos (x y : V) {r : β} (hr : 0 < r) :
angle (r β’ x) y = angle x y :=
by rw [angle_comm, angle_smul_right_of_pos y x hr, angle_comm]
/-- The angle between a vector and a negative multiple of a vector. -/
@[simp] lemma angle_smul_right_of_neg (x y : V) {r : β} (hr : r < 0) :
angle x (r β’ y) = angle x (-y) :=
by rw [βneg_neg r, neg_smul, angle_neg_right, angle_smul_right_of_pos x y (neg_pos_of_neg hr),
angle_neg_right]
/-- The angle between a negative multiple of a vector and a vector. -/
@[simp] lemma angle_smul_left_of_neg (x y : V) {r : β} (hr : r < 0) :
angle (r β’ x) y = angle (-x) y :=
by rw [angle_comm, angle_smul_right_of_neg y x hr, angle_comm]
/-- The cosine of the angle between two vectors, multiplied by the
product of their norms. -/
lemma cos_angle_mul_norm_mul_norm (x y : V) : real.cos (angle x y) * (βxβ * βyβ) = βͺx, yβ« :=
begin
rw [cos_angle, div_mul_cancel_of_imp],
simp [or_imp_distrib] { contextual := tt },
end
/-- The sine of the angle between two vectors, multiplied by the
product of their norms. -/
lemma sin_angle_mul_norm_mul_norm (x y : V) : real.sin (angle x y) * (βxβ * βyβ) =
real.sqrt (βͺx, xβ« * βͺy, yβ« - βͺx, yβ« * βͺx, yβ«) :=
begin
unfold angle,
rw [real.sin_arccos,
βreal.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)),
βreal.sqrt_mul' _ (mul_self_nonneg _), sq,
real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)),
real_inner_self_eq_norm_mul_norm,
real_inner_self_eq_norm_mul_norm],
by_cases h : (βxβ * βyβ) = 0,
{ rw [(show βxβ * βxβ * (βyβ * βyβ) = (βxβ * βyβ) * (βxβ * βyβ), by ring), h, mul_zero, mul_zero,
zero_sub],
cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy,
{ rw norm_eq_zero at hx,
rw [hx, inner_zero_left, zero_mul, neg_zero] },
{ rw norm_eq_zero at hy,
rw [hy, inner_zero_right, zero_mul, neg_zero] } },
{ field_simp [h], ring_nf }
end
/-- The angle between two vectors is zero if and only if they are
nonzero and one is a positive multiple of the other. -/
lemma angle_eq_zero_iff {x y : V} : angle x y = 0 β (x β 0 β§ β (r : β), 0 < r β§ y = r β’ x) :=
begin
rw [angle, β real_inner_div_norm_mul_norm_eq_one_iff, real.arccos_eq_zero, has_le.le.le_iff_eq,
eq_comm],
exact (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2
end
/-- The angle between two vectors is Ο if and only if they are nonzero
and one is a negative multiple of the other. -/
lemma angle_eq_pi_iff {x y : V} : angle x y = Ο β (x β 0 β§ β (r : β), r < 0 β§ y = r β’ x) :=
begin
rw [angle, β real_inner_div_norm_mul_norm_eq_neg_one_iff, real.arccos_eq_pi, has_le.le.le_iff_eq],
exact (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1
end
/-- If the angle between two vectors is Ο, the angles between those
vectors and a third vector add to Ο. -/
lemma angle_add_angle_eq_pi_of_angle_eq_pi {x y : V} (z : V) (h : angle x y = Ο) :
angle x z + angle y z = Ο :=
begin
rcases angle_eq_pi_iff.1 h with β¨hx, β¨r, β¨hr, rflβ©β©β©,
rw [angle_smul_left_of_neg x z hr, angle_neg_left, add_sub_cancel'_right]
end
/-- Two vectors have inner product 0 if and only if the angle between
them is Ο/2. -/
lemma inner_eq_zero_iff_angle_eq_pi_div_two (x y : V) : βͺx, yβ« = 0 β angle x y = Ο / 2 :=
iff.symm $ by simp [angle, or_imp_distrib] { contextual := tt }
/-- If the angle between two vectors is Ο, the inner product equals the negative product
of the norms. -/
lemma inner_eq_neg_mul_norm_of_angle_eq_pi {x y : V} (h : angle x y = Ο) : βͺx, yβ« = - (βxβ * βyβ) :=
by simp [β cos_angle_mul_norm_mul_norm, h]
/-- If the angle between two vectors is 0, the inner product equals the product of the norms. -/
lemma inner_eq_mul_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) : βͺx, yβ« = βxβ * βyβ :=
by simp [β cos_angle_mul_norm_mul_norm, h]
/-- The inner product of two non-zero vectors equals the negative product of their norms
if and only if the angle between the two vectors is Ο. -/
lemma inner_eq_neg_mul_norm_iff_angle_eq_pi {x y : V} (hx : x β 0) (hy : y β 0) :
βͺx, yβ« = - (βxβ * βyβ) β angle x y = Ο :=
begin
refine β¨Ξ» h, _, inner_eq_neg_mul_norm_of_angle_eq_piβ©,
have hβ : (βxβ * βyβ) β 0 := (mul_pos (norm_pos_iff.mpr hx) (norm_pos_iff.mpr hy)).ne',
rw [angle, h, neg_div, div_self hβ, real.arccos_neg_one],
end
/-- The inner product of two non-zero vectors equals the product of their norms
if and only if the angle between the two vectors is 0. -/
lemma inner_eq_mul_norm_iff_angle_eq_zero {x y : V} (hx : x β 0) (hy : y β 0) :
βͺx, yβ« = βxβ * βyβ β angle x y = 0 :=
begin
refine β¨Ξ» h, _, inner_eq_mul_norm_of_angle_eq_zeroβ©,
have hβ : (βxβ * βyβ) β 0 := (mul_pos (norm_pos_iff.mpr hx) (norm_pos_iff.mpr hy)).ne',
rw [angle, h, div_self hβ, real.arccos_one],
end
/-- If the angle between two vectors is Ο, the norm of their difference equals
the sum of their norms. -/
lemma norm_sub_eq_add_norm_of_angle_eq_pi {x y : V} (h : angle x y = Ο) : βx - yβ = βxβ + βyβ :=
begin
rw β sq_eq_sq (norm_nonneg (x - y)) (add_nonneg (norm_nonneg x) (norm_nonneg y)),
rw [norm_sub_pow_two_real, inner_eq_neg_mul_norm_of_angle_eq_pi h],
ring,
end
/-- If the angle between two vectors is 0, the norm of their sum equals
the sum of their norms. -/
lemma norm_add_eq_add_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) : βx + yβ = βxβ + βyβ :=
begin
rw β sq_eq_sq (norm_nonneg (x + y)) (add_nonneg (norm_nonneg x) (norm_nonneg y)),
rw [norm_add_pow_two_real, inner_eq_mul_norm_of_angle_eq_zero h],
ring,
end
/-- If the angle between two vectors is 0, the norm of their difference equals
the absolute value of the difference of their norms. -/
lemma norm_sub_eq_abs_sub_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) :
βx - yβ = |βxβ - βyβ| :=
begin
rw [β sq_eq_sq (norm_nonneg (x - y)) (abs_nonneg (βxβ - βyβ)),
norm_sub_pow_two_real, inner_eq_mul_norm_of_angle_eq_zero h, sq_abs (βxβ - βyβ)],
ring,
end
/-- The norm of the difference of two non-zero vectors equals the sum of their norms
if and only the angle between the two vectors is Ο. -/
lemma norm_sub_eq_add_norm_iff_angle_eq_pi {x y : V} (hx : x β 0) (hy : y β 0) :
βx - yβ = βxβ + βyβ β angle x y = Ο :=
begin
refine β¨Ξ» h, _, norm_sub_eq_add_norm_of_angle_eq_piβ©,
rw β inner_eq_neg_mul_norm_iff_angle_eq_pi hx hy,
obtain β¨hxyβ, hxyββ© := β¨norm_nonneg (x - y), add_nonneg (norm_nonneg x) (norm_nonneg y)β©,
rw [β sq_eq_sq hxyβ hxyβ, norm_sub_pow_two_real] at h,
calc βͺx, yβ« = (βxβ ^ 2 + βyβ ^ 2 - (βxβ + βyβ) ^ 2) / 2 : by linarith
... = -(βxβ * βyβ) : by ring,
end
/-- The norm of the sum of two non-zero vectors equals the sum of their norms
if and only the angle between the two vectors is 0. -/
lemma norm_add_eq_add_norm_iff_angle_eq_zero {x y : V} (hx : x β 0) (hy : y β 0) :
βx + yβ = βxβ + βyβ β angle x y = 0 :=
begin
refine β¨Ξ» h, _, norm_add_eq_add_norm_of_angle_eq_zeroβ©,
rw β inner_eq_mul_norm_iff_angle_eq_zero hx hy,
obtain β¨hxyβ, hxyββ© := β¨norm_nonneg (x + y), add_nonneg (norm_nonneg x) (norm_nonneg y)β©,
rw [β sq_eq_sq hxyβ hxyβ, norm_add_pow_two_real] at h,
calc βͺx, yβ« = ((βxβ + βyβ) ^ 2 - βxβ ^ 2 - βyβ ^ 2)/ 2 : by linarith
... = βxβ * βyβ : by ring,
end
/-- The norm of the difference of two non-zero vectors equals the absolute value
of the difference of their norms if and only the angle between the two vectors is 0. -/
lemma norm_sub_eq_abs_sub_norm_iff_angle_eq_zero {x y : V} (hx : x β 0) (hy : y β 0) :
βx - yβ = |βxβ - βyβ| β angle x y = 0 :=
begin
refine β¨Ξ» h, _, norm_sub_eq_abs_sub_norm_of_angle_eq_zeroβ©,
rw β inner_eq_mul_norm_iff_angle_eq_zero hx hy,
have h1 : βx - yβ ^ 2 = (βxβ - βyβ) ^ 2, { rw h, exact sq_abs (βxβ - βyβ) },
rw norm_sub_pow_two_real at h1,
calc βͺx, yβ« = ((βxβ + βyβ) ^ 2 - βxβ ^ 2 - βyβ ^ 2)/ 2 : by linarith
... = βxβ * βyβ : by ring,
end
/-- The norm of the sum of two vectors equals the norm of their difference if and only if
the angle between them is Ο/2. -/
lemma norm_add_eq_norm_sub_iff_angle_eq_pi_div_two (x y : V) :
βx + yβ = βx - yβ β angle x y = Ο / 2 :=
begin
rw [β sq_eq_sq (norm_nonneg (x + y)) (norm_nonneg (x - y)),
β inner_eq_zero_iff_angle_eq_pi_div_two x y, norm_add_pow_two_real, norm_sub_pow_two_real],
split; intro h; linarith,
end
/-- The cosine of the angle between two vectors is 1 if and only if the angle is 0. -/
lemma cos_eq_one_iff_angle_eq_zero : cos (angle x y) = 1 β angle x y = 0 :=
begin
rw β cos_zero,
exact inj_on_cos.eq_iff β¨angle_nonneg x y, angle_le_pi x yβ© (left_mem_Icc.2 pi_pos.le),
end
/-- The cosine of the angle between two vectors is 0 if and only if the angle is Ο / 2. -/
lemma cos_eq_zero_iff_angle_eq_pi_div_two : cos (angle x y) = 0 β angle x y = Ο / 2 :=
begin
rw β cos_pi_div_two,
apply inj_on_cos.eq_iff β¨angle_nonneg x y, angle_le_pi x yβ©,
split; linarith [pi_pos],
end
/-- The cosine of the angle between two vectors is -1 if and only if the angle is Ο. -/
lemma cos_eq_neg_one_iff_angle_eq_pi : cos (angle x y) = -1 β angle x y = Ο :=
begin
rw β cos_pi,
exact inj_on_cos.eq_iff β¨angle_nonneg x y, angle_le_pi x yβ© (right_mem_Icc.2 pi_pos.le),
end
/-- The sine of the angle between two vectors is 0 if and only if the angle is 0 or Ο. -/
lemma sin_eq_zero_iff_angle_eq_zero_or_angle_eq_pi :
sin (angle x y) = 0 β angle x y = 0 β¨ angle x y = Ο :=
by rw [sin_eq_zero_iff_cos_eq, cos_eq_one_iff_angle_eq_zero, cos_eq_neg_one_iff_angle_eq_pi]
/-- The sine of the angle between two vectors is 1 if and only if the angle is Ο / 2. -/
lemma sin_eq_one_iff_angle_eq_pi_div_two : sin (angle x y) = 1 β angle x y = Ο / 2 :=
begin
refine β¨Ξ» h, _, Ξ» h, by rw [h, sin_pi_div_two]β©,
rw [βcos_eq_zero_iff_angle_eq_pi_div_two, βabs_eq_zero, abs_cos_eq_sqrt_one_sub_sin_sq, h],
simp,
end
end inner_product_geometry
|
545dbc35a619b2be3cd9b317b61abdfa1b08b343 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/linear_algebra/char_poly/coeff.lean | 6c60c04cc0c7785d12030a062fc4f09c899d8254 | [
"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 | 10,825 | lean | /-
Copyright (c) 2020 Aaron Anderson, Jalex Stark. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson, Jalex Stark
-/
import algebra.polynomial.big_operators
import data.matrix.char_p
import field_theory.finite.basic
import group_theory.perm.cycles
import linear_algebra.char_poly.basic
import linear_algebra.matrix.trace
import ring_theory.polynomial.basic
import ring_theory.power_basis
/-!
# Characteristic polynomials
We give methods for computing coefficients of the characteristic polynomial.
## Main definitions
- `char_poly_degree_eq_dim` proves that the degree of the characteristic polynomial
over a nonzero ring is the dimension of the matrix
- `det_eq_sign_char_poly_coeff` proves that the determinant is the constant term of the
characteristic polynomial, up to sign.
- `trace_eq_neg_char_poly_coeff` proves that the trace is the negative of the (d-1)th coefficient of
the characteristic polynomial, where d is the dimension of the matrix.
For a nonzero ring, this is the second-highest coefficient.
-/
noncomputable theory
universes u v w z
open polynomial matrix
open_locale big_operators
variables {R : Type u} [comm_ring R]
variables {n G : Type v} [decidable_eq n] [fintype n]
variables {Ξ± Ξ² : Type v} [decidable_eq Ξ±]
open finset
open polynomial
variable {M : matrix n n R}
lemma char_matrix_apply_nat_degree [nontrivial R] (i j : n) :
(char_matrix M i j).nat_degree = ite (i = j) 1 0 :=
by { by_cases i = j; simp [h, β degree_eq_iff_nat_degree_eq_of_pos (nat.succ_pos 0)], }
lemma char_matrix_apply_nat_degree_le (i j : n) :
(char_matrix M i j).nat_degree β€ ite (i = j) 1 0 :=
by split_ifs; simp [h, nat_degree_X_sub_C_le]
variable (M)
lemma char_poly_sub_diagonal_degree_lt :
(char_poly M - β (i : n), (X - C (M i i))).degree < β(fintype.card n - 1) :=
begin
rw [char_poly, det_apply', β insert_erase (mem_univ (equiv.refl n)),
sum_insert (not_mem_erase (equiv.refl n) univ), add_comm],
simp only [char_matrix_apply_eq, one_mul, equiv.perm.sign_refl, id.def, int.cast_one,
units.coe_one, add_sub_cancel, equiv.coe_refl],
rw β mem_degree_lt, apply submodule.sum_mem (degree_lt R (fintype.card n - 1)),
intros c hc, rw [β C_eq_int_cast, C_mul'],
apply submodule.smul_mem (degree_lt R (fintype.card n - 1)) ββ(equiv.perm.sign c),
rw mem_degree_lt, apply lt_of_le_of_lt degree_le_nat_degree _, rw with_bot.coe_lt_coe,
apply lt_of_le_of_lt _ (equiv.perm.fixed_point_card_lt_of_ne_one (ne_of_mem_erase hc)),
apply le_trans (polynomial.nat_degree_prod_le univ (Ξ» i : n, (char_matrix M (c i) i))) _,
rw card_eq_sum_ones, rw sum_filter, apply sum_le_sum,
intros, apply char_matrix_apply_nat_degree_le,
end
lemma char_poly_coeff_eq_prod_coeff_of_le {k : β} (h : fintype.card n - 1 β€ k) :
(char_poly M).coeff k = (β i : n, (X - C (M i i))).coeff k :=
begin
apply eq_of_sub_eq_zero, rw β coeff_sub, apply polynomial.coeff_eq_zero_of_degree_lt,
apply lt_of_lt_of_le (char_poly_sub_diagonal_degree_lt M) _, rw with_bot.coe_le_coe, apply h,
end
lemma det_of_card_zero (h : fintype.card n = 0) (M : matrix n n R) : M.det = 1 :=
by { rw fintype.card_eq_zero_iff at h, suffices : M = 1, { simp [this] }, ext i, exact h.elim i }
theorem char_poly_degree_eq_dim [nontrivial R] (M : matrix n n R) :
(char_poly M).degree = fintype.card n :=
begin
by_cases fintype.card n = 0,
{ rw h, unfold char_poly, rw det_of_card_zero, {simp}, {assumption} },
rw β sub_add_cancel (char_poly M) (β (i : n), (X - C (M i i))),
have h1 : (β (i : n), (X - C (M i i))).degree = fintype.card n,
{ rw degree_eq_iff_nat_degree_eq_of_pos, swap, apply nat.pos_of_ne_zero h,
rw nat_degree_prod', simp_rw nat_degree_X_sub_C, unfold fintype.card, simp,
simp_rw (monic_X_sub_C _).leading_coeff, simp, },
rw degree_add_eq_right_of_degree_lt, exact h1, rw h1,
apply lt_trans (char_poly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe,
rw β nat.pred_eq_sub_one, apply nat.pred_lt, apply h,
end
theorem char_poly_nat_degree_eq_dim [nontrivial R] (M : matrix n n R) :
(char_poly M).nat_degree = fintype.card n :=
nat_degree_eq_of_degree_eq_some (char_poly_degree_eq_dim M)
lemma char_poly_monic (M : matrix n n R) :
monic (char_poly M) :=
begin
nontriviality,
by_cases fintype.card n = 0, {rw [char_poly, det_of_card_zero h], apply monic_one},
have mon : (β (i : n), (X - C (M i i))).monic,
{ apply monic_prod_of_monic univ (Ξ» i : n, (X - C (M i i))), simp [monic_X_sub_C], },
rw β sub_add_cancel (β (i : n), (X - C (M i i))) (char_poly M) at mon,
rw monic at *, rw leading_coeff_add_of_degree_lt at mon, rw β mon,
rw char_poly_degree_eq_dim, rw β neg_sub, rw degree_neg,
apply lt_trans (char_poly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe,
rw β nat.pred_eq_sub_one, apply nat.pred_lt, apply h,
end
theorem trace_eq_neg_char_poly_coeff [nonempty n] (M : matrix n n R) :
(matrix.trace n R R) M = -(char_poly M).coeff (fintype.card n - 1) :=
begin
nontriviality,
rw char_poly_coeff_eq_prod_coeff_of_le, swap, refl,
rw [fintype.card, prod_X_sub_C_coeff_card_pred univ (Ξ» i : n, M i i)], simp,
rw [β fintype.card, fintype.card_pos_iff], apply_instance,
end
-- I feel like this should use polynomial.alg_hom_evalβ_algebra_map
lemma mat_poly_equiv_eval (M : matrix n n (polynomial R)) (r : R) (i j : n) :
(mat_poly_equiv M).eval ((scalar n) r) i j = (M i j).eval r :=
begin
unfold polynomial.eval, unfold evalβ,
transitivity polynomial.sum (mat_poly_equiv M) (Ξ» (e : β) (a : matrix n n R),
(a * (scalar n) r ^ e) i j),
{ unfold polynomial.sum, rw matrix.sum_apply, dsimp, refl },
{ simp_rw [βring_hom.map_pow, β(matrix.scalar.commute _ _).eq],
simp only [coe_scalar, matrix.one_mul, ring_hom.id_apply,
pi.smul_apply, smul_eq_mul, mul_eq_mul, algebra.smul_mul_assoc],
have h : β x : β, (Ξ» (e : β) (a : R), r ^ e * a) x 0 = 0 := by simp,
simp only [polynomial.sum, mat_poly_equiv_coeff_apply, mul_comm],
apply (finset.sum_subset (support_subset_support_mat_poly_equiv _ _ _) _).symm,
assume n hn h'n,
rw not_mem_support_iff at h'n,
simp only [h'n, zero_mul] }
end
lemma eval_det (M : matrix n n (polynomial R)) (r : R) :
polynomial.eval r M.det = (polynomial.eval (matrix.scalar n r) (mat_poly_equiv M)).det :=
begin
rw [polynomial.eval, β coe_evalβ_ring_hom, ring_hom.map_det],
apply congr_arg det, ext, symmetry, convert mat_poly_equiv_eval _ _ _ _,
end
theorem det_eq_sign_char_poly_coeff (M : matrix n n R) :
M.det = (-1)^(fintype.card n) * (char_poly M).coeff 0:=
begin
rw [coeff_zero_eq_eval_zero, char_poly, eval_det, mat_poly_equiv_char_matrix, β det_smul],
simp
end
variables {p : β} [fact p.prime]
lemma mat_poly_equiv_eq_X_pow_sub_C {K : Type*} (k : β) [field K] (M : matrix n n K) :
mat_poly_equiv
((expand K (k) : polynomial K β+* polynomial K).map_matrix (char_matrix (M ^ k))) =
X ^ k - C (M ^ k) :=
begin
ext m,
rw [coeff_sub, coeff_C, mat_poly_equiv_coeff_apply, ring_hom.map_matrix_apply, matrix.map_apply,
alg_hom.coe_to_ring_hom, dmatrix.sub_apply, coeff_X_pow],
by_cases hij : i = j,
{ rw [hij, char_matrix_apply_eq, alg_hom.map_sub, expand_C, expand_X, coeff_sub, coeff_X_pow,
coeff_C],
split_ifs with mp m0;
simp only [matrix.one_apply_eq, dmatrix.zero_apply] },
{ rw [char_matrix_apply_ne _ _ _ hij, alg_hom.map_neg, expand_C, coeff_neg, coeff_C],
split_ifs with m0 mp;
simp only [hij, zero_sub, dmatrix.zero_apply, sub_zero, neg_zero, matrix.one_apply_ne, ne.def,
not_false_iff] }
end
@[simp] lemma finite_field.char_poly_pow_card {K : Type*} [field K] [fintype K] (M : matrix n n K) :
char_poly (M ^ (fintype.card K)) = char_poly M :=
begin
casesI (is_empty_or_nonempty n).symm,
{ cases char_p.exists K with p hp, letI := hp,
rcases finite_field.card K p with β¨β¨k, kposβ©, β¨hp, hkβ©β©,
haveI : fact p.prime := β¨hpβ©,
dsimp at hk, rw hk at *,
apply (frobenius_inj (polynomial K) p).iterate k,
repeat { rw iterate_frobenius, rw β hk },
rw β finite_field.expand_card,
unfold char_poly, rw [alg_hom.map_det, β coe_det_monoid_hom,
β (det_monoid_hom : matrix n n (polynomial K) β* polynomial K).map_pow],
apply congr_arg det,
refine mat_poly_equiv.injective _,
rw [alg_equiv.map_pow, mat_poly_equiv_char_matrix, hk, sub_pow_char_pow_of_commute, β C_pow],
{ exact (id (mat_poly_equiv_eq_X_pow_sub_C (p ^ k) M) : _) },
{ exact (C M).commute_X } },
{ -- TODO[gh-6025]: remove this `haveI` once `subsingleton_of_empty_right` is a global instance
haveI : subsingleton (matrix n n K) := matrix.subsingleton_of_empty_right,
exact congr_arg _ (subsingleton.elim _ _), },
end
@[simp] lemma zmod.char_poly_pow_card (M : matrix n n (zmod p)) :
char_poly (M ^ p) = char_poly M :=
by { have h := finite_field.char_poly_pow_card M, rwa zmod.card at h, }
lemma finite_field.trace_pow_card {K : Type*} [field K] [fintype K] [nonempty n]
(M : matrix n n K) : trace n K K (M ^ (fintype.card K)) = (trace n K K M) ^ (fintype.card K) :=
by rw [trace_eq_neg_char_poly_coeff, trace_eq_neg_char_poly_coeff,
finite_field.char_poly_pow_card, finite_field.pow_card]
lemma zmod.trace_pow_card {p:β} [fact p.prime] [nonempty n] (M : matrix n n (zmod p)) :
trace n (zmod p) (zmod p) (M ^ p) = (trace n (zmod p) (zmod p) M)^p :=
by { have h := finite_field.trace_pow_card M, rwa zmod.card at h, }
namespace matrix
theorem is_integral : is_integral R M := β¨char_poly M, β¨char_poly_monic M, aeval_self_char_poly Mβ©β©
theorem min_poly_dvd_char_poly {K : Type*} [field K] (M : matrix n n K) :
(minpoly K M) β£ char_poly M :=
minpoly.dvd _ _ (aeval_self_char_poly M)
end matrix
section power_basis
open algebra
/-- The characteristic polynomial of the map `Ξ» x, a * x` is the minimal polynomial of `a`.
In combination with `det_eq_sign_char_poly_coeff` or `trace_eq_neg_char_poly_coeff`
and a bit of rewriting, this will allow us to conclude the
field norm resp. trace of `x` is the product resp. sum of `x`'s conjugates.
-/
lemma char_poly_left_mul_matrix {K S : Type*} [field K] [comm_ring S] [algebra K S]
(h : power_basis K S) :
char_poly (left_mul_matrix h.basis h.gen) = minpoly K h.gen :=
begin
apply minpoly.unique,
{ apply char_poly_monic },
{ apply (left_mul_matrix _).injective_iff.mp (left_mul_matrix_injective h.basis),
rw [β polynomial.aeval_alg_hom_apply, aeval_self_char_poly] },
{ intros q q_monic root_q,
rw [char_poly_degree_eq_dim, fintype.card_fin, degree_eq_nat_degree q_monic.ne_zero],
apply with_bot.some_le_some.mpr,
exact h.dim_le_nat_degree_of_root q_monic.ne_zero root_q }
end
end power_basis
|
810247d9df224121300ab1d8a64393a19cd143f4 | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/category_theory/limits/cones.lean | 32a42ae4b3b2406ef01bf11990f091e9a7ed0178 | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 13,327 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Stephen Morgan, Scott Morrison, Floris van Doorn
-/
import category_theory.const
import category_theory.yoneda
universes v u u' -- declare the `v`'s first; see `category_theory.category` for an explanation
open category_theory
-- There is an awkward difficulty with universes here.
-- If we allowed `J` to be a small category in `Prop`, we'd run into trouble
-- because `yoneda.obj (F : (J β₯€ C)α΅α΅)` will be a functor into `Sort (max v 1)`,
-- not into `Sort v`.
-- So we don't allow this case; it's not particularly useful anyway.
variables {J : Type v} [small_category J]
variables {C : Type u} [category.{v} C]
open category_theory
open category_theory.category
open category_theory.functor
open opposite
namespace category_theory
namespace functor
variables {J C} (F : J β₯€ C)
/--
`F.cones` is the functor assigning to an object `X` the type of
natural transformations from the constant functor with value `X` to `F`.
An object representing this functor is a limit of `F`.
-/
def cones : Cα΅α΅ β₯€ Type v := (const J).op β (yoneda.obj F)
lemma cones_obj (X : Cα΅α΅) : F.cones.obj X = ((const J).obj (unop X) βΆ F) := rfl
@[simp] lemma cones_map_app {Xβ Xβ : Cα΅α΅} (f : Xβ βΆ Xβ) (t : F.cones.obj Xβ) (j : J) :
(F.cones.map f t).app j = f.unop β« t.app j := rfl
/--
`F.cocones` is the functor assigning to an object `X` the type of
natural transformations from `F` to the constant functor with value `X`.
An object corepresenting this functor is a colimit of `F`.
-/
def cocones : C β₯€ Type v := const J β coyoneda.obj (op F)
lemma cocones_obj (X : C) : F.cocones.obj X = (F βΆ (const J).obj X) := rfl
@[simp] lemma cocones_map_app {Xβ Xβ : C} (f : Xβ βΆ Xβ) (t : F.cocones.obj Xβ) (j : J) :
(F.cocones.map f t).app j = t.app j β« f := rfl
end functor
section
variables (J C)
/--
Functorially associated to each functor `J β₯€ C`, we have the `C`-presheaf consisting of
cones with a given cone point.
-/
@[simps] def cones : (J β₯€ C) β₯€ (Cα΅α΅ β₯€ Type v) :=
{ obj := functor.cones,
map := Ξ» F G f, whisker_left (const J).op (yoneda.map f) }
/--
Contravariantly associated to each functor `J β₯€ C`, we have the `C`-copresheaf consisting of
cocones with a given cocone point.
-/
@[simps] def cocones : (J β₯€ C)α΅α΅ β₯€ (C β₯€ Type v) :=
{ obj := Ξ» F, functor.cocones (unop F),
map := Ξ» F G f, whisker_left (const J) (coyoneda.map f) }
end
namespace limits
/--
A `c : cone F` is:
* an object `c.X` and
* a natural transformation `c.Ο : c.X βΆ F` from the constant `c.X` functor to `F`.
`cone F` is equivalent, via `cone.equiv` below, to `Ξ£ X, F.cones.obj X`.
-/
structure cone (F : J β₯€ C) :=
(X : C)
(Ο : (const J).obj X βΆ F)
@[simp] lemma cone.w {F : J β₯€ C} (c : cone F) {j j' : J} (f : j βΆ j') :
c.Ο.app j β« F.map f = c.Ο.app j' :=
by convert β(c.Ο.naturality f).symm; apply id_comp
/--
A `c : cocone F` is
* an object `c.X` and
* a natural transformation `c.ΞΉ : F βΆ c.X` from `F` to the constant `c.X` functor.
`cocone F` is equivalent, via `cone.equiv` below, to `Ξ£ X, F.cocones.obj X`.
-/
structure cocone (F : J β₯€ C) :=
(X : C)
(ΞΉ : F βΆ (const J).obj X)
@[simp] lemma cocone.w {F : J β₯€ C} (c : cocone F) {j j' : J} (f : j βΆ j') :
F.map f β« c.ΞΉ.app j' = c.ΞΉ.app j :=
by convert β(c.ΞΉ.naturality f); apply comp_id
variables {F : J β₯€ C}
namespace cone
def equiv (F : J β₯€ C) : cone F β
Ξ£ X, F.cones.obj X :=
{ hom := Ξ» c, β¨op c.X, c.Οβ©,
inv := Ξ» c, { X := unop c.1, Ο := c.2 },
hom_inv_id' := begin ext, cases x, refl, end,
inv_hom_id' := begin ext, cases x, refl, end }
@[simp] def extensions (c : cone F) : yoneda.obj c.X βΆ F.cones :=
{ app := Ξ» X f, ((const J).map f) β« c.Ο }
/-- A map to the vertex of a cone induces a cone by composition. -/
@[simp] def extend (c : cone F) {X : C} (f : X βΆ c.X) : cone F :=
{ X := X,
Ο := c.extensions.app (op X) f }
@[simp] lemma extend_Ο (c : cone F) {X : Cα΅α΅} (f : unop X βΆ c.X) :
(extend c f).Ο = c.extensions.app X f :=
rfl
@[simps] def whisker {K : Type v} [small_category K] (E : K β₯€ J) (c : cone F) : cone (E β F) :=
{ X := c.X,
Ο := whisker_left E c.Ο }
end cone
namespace cocone
def equiv (F : J β₯€ C) : cocone F β
Ξ£ X, F.cocones.obj X :=
{ hom := Ξ» c, β¨c.X, c.ΞΉβ©,
inv := Ξ» c, { X := c.1, ΞΉ := c.2 },
hom_inv_id' := begin ext, cases x, refl, end,
inv_hom_id' := begin ext, cases x, refl, end }
@[simp] def extensions (c : cocone F) : coyoneda.obj (op c.X) βΆ F.cocones :=
{ app := Ξ» X f, c.ΞΉ β« (const J).map f }
/-- A map from the vertex of a cocone induces a cocone by composition. -/
@[simp] def extend (c : cocone F) {X : C} (f : c.X βΆ X) : cocone F :=
{ X := X,
ΞΉ := c.extensions.app X f }
@[simp] lemma extend_ΞΉ (c : cocone F) {X : C} (f : c.X βΆ X) :
(extend c f).ΞΉ = c.extensions.app X f :=
rfl
@[simps] def whisker {K : Type v} [small_category K] (E : K β₯€ J) (c : cocone F) : cocone (E β F) :=
{ X := c.X,
ΞΉ := whisker_left E c.ΞΉ }
end cocone
@[ext] structure cone_morphism (A B : cone F) :=
(hom : A.X βΆ B.X)
(w' : β j : J, hom β« B.Ο.app j = A.Ο.app j . obviously)
restate_axiom cone_morphism.w'
attribute [simp] cone_morphism.w
@[simps] instance cone.category : category.{v} (cone F) :=
{ hom := Ξ» A B, cone_morphism A B,
comp := Ξ» X Y Z f g,
{ hom := f.hom β« g.hom,
w' := by intro j; rw [assoc, g.w, f.w] },
id := Ξ» B, { hom := π B.X } }
namespace cones
/-- To give an isomorphism between cones, it suffices to give an
isomorphism between their vertices which commutes with the cone
maps. -/
@[ext, simps] def ext {c c' : cone F}
(Ο : c.X β
c'.X) (w : β j, c.Ο.app j = Ο.hom β« c'.Ο.app j) : c β
c' :=
{ hom := { hom := Ο.hom },
inv := { hom := Ο.inv, w' := Ξ» j, Ο.inv_comp_eq.mpr (w j) } }
@[simps] def postcompose {G : J β₯€ C} (Ξ± : F βΆ G) : cone F β₯€ cone G :=
{ obj := Ξ» c, { X := c.X, Ο := c.Ο β« Ξ± },
map := Ξ» cβ cβ f, { hom := f.hom, w' :=
by intro; erw β category.assoc; simp [-category.assoc] } }
def postcompose_comp {G H : J β₯€ C} (Ξ± : F βΆ G) (Ξ² : G βΆ H) :
postcompose (Ξ± β« Ξ²) β
postcompose Ξ± β postcompose Ξ² :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def postcompose_id : postcompose (π F) β
π (cone F) :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def postcompose_equivalence {G : J β₯€ C} (Ξ± : F β
G) : cone F β cone G :=
begin
refine equivalence.mk (postcompose Ξ±.hom) (postcompose Ξ±.inv) _ _,
{ symmetry,
refine (postcompose_comp _ _).symm.trans _, rw [iso.hom_inv_id], exact postcompose_id },
{ refine (postcompose_comp _ _).symm.trans _, rw [iso.inv_hom_id], exact postcompose_id }
end
section
variable (F)
@[simps]
def forget : cone F β₯€ C :=
{ obj := Ξ» t, t.X, map := Ξ» s t f, f.hom }
variables {D : Type u'} [category.{v} D]
@[simps] def functoriality (G : C β₯€ D) : cone F β₯€ cone (F β G) :=
{ obj := Ξ» A,
{ X := G.obj A.X,
Ο := { app := Ξ» j, G.map (A.Ο.app j), naturality' := by intros; erw βG.map_comp; tidy } },
map := Ξ» X Y f,
{ hom := G.map f.hom,
w' := by intros; rw [βfunctor.map_comp, f.w] } }
end
end cones
@[ext] structure cocone_morphism (A B : cocone F) :=
(hom : A.X βΆ B.X)
(w' : β j : J, A.ΞΉ.app j β« hom = B.ΞΉ.app j . obviously)
restate_axiom cocone_morphism.w'
attribute [simp] cocone_morphism.w
@[simps] instance cocone.category : category.{v} (cocone F) :=
{ hom := Ξ» A B, cocone_morphism A B,
comp := Ξ» _ _ _ f g,
{ hom := f.hom β« g.hom,
w' := by intro j; rw [βassoc, f.w, g.w] },
id := Ξ» B, { hom := π B.X } }
namespace cocones
/-- To give an isomorphism between cocones, it suffices to give an
isomorphism between their vertices which commutes with the cocone
maps. -/
@[ext, simps] def ext {c c' : cocone F}
(Ο : c.X β
c'.X) (w : β j, c.ΞΉ.app j β« Ο.hom = c'.ΞΉ.app j) : c β
c' :=
{ hom := { hom := Ο.hom },
inv := { hom := Ο.inv, w' := Ξ» j, Ο.comp_inv_eq.mpr (w j).symm } }
@[simps] def precompose {G : J β₯€ C} (Ξ± : G βΆ F) : cocone F β₯€ cocone G :=
{ obj := Ξ» c, { X := c.X, ΞΉ := Ξ± β« c.ΞΉ },
map := Ξ» cβ cβ f, { hom := f.hom } }
def precompose_comp {G H : J β₯€ C} (Ξ± : F βΆ G) (Ξ² : G βΆ H) :
precompose (Ξ± β« Ξ²) β
precompose Ξ² β precompose Ξ± :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def precompose_id : precompose (π F) β
π (cocone F) :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def precompose_equivalence {G : J β₯€ C} (Ξ± : G β
F) : cocone F β cocone G :=
begin
refine equivalence.mk (precompose Ξ±.hom) (precompose Ξ±.inv) _ _,
{ symmetry, refine (precompose_comp _ _).symm.trans _, rw [iso.inv_hom_id], exact precompose_id },
{ refine (precompose_comp _ _).symm.trans _, rw [iso.hom_inv_id], exact precompose_id }
end
section
variable (F)
@[simps]
def forget : cocone F β₯€ C :=
{ obj := Ξ» t, t.X, map := Ξ» s t f, f.hom }
variables {D : Type u'} [category.{v} D]
@[simps] def functoriality (G : C β₯€ D) : cocone F β₯€ cocone (F β G) :=
{ obj := Ξ» A,
{ X := G.obj A.X,
ΞΉ := { app := Ξ» j, G.map (A.ΞΉ.app j), naturality' := by intros; erw βG.map_comp; tidy } },
map := Ξ» _ _ f,
{ hom := G.map f.hom,
w' := by intros; rw [βfunctor.map_comp, cocone_morphism.w] } }
end
end cocones
end limits
namespace functor
variables {D : Type u'} [category.{v} D]
variables {F : J β₯€ C} {G : J β₯€ C} (H : C β₯€ D)
open category_theory.limits
/-- The image of a cone in C under a functor G : C β₯€ D is a cone in D. -/
def map_cone (c : cone F) : cone (F β H) := (cones.functoriality F H).obj c
/-- The image of a cocone in C under a functor G : C β₯€ D is a cocone in D. -/
def map_cocone (c : cocone F) : cocone (F β H) := (cocones.functoriality F H).obj c
@[simp] lemma map_cone_X (c : cone F) : (H.map_cone c).X = H.obj c.X := rfl
@[simp] lemma map_cocone_X (c : cocone F) : (H.map_cocone c).X = H.obj c.X := rfl
@[simps]
def map_cone_inv [is_equivalence H]
(c : cone (F β H)) : cone F :=
let t := (inv H).map_cone c in
let Ξ± : (F β H) β inv H βΆ F :=
((whisker_left F is_equivalence.unit_iso.inv) : F β (H β inv H) βΆ _) β« (functor.right_unitor _).hom in
{ X := t.X,
Ο := ((category_theory.cones J C).map Ξ±).app (op t.X) t.Ο }
def map_cone_morphism {c c' : cone F} (f : c βΆ c') :
(H.map_cone c) βΆ (H.map_cone c') := (cones.functoriality F H).map f
def map_cocone_morphism {c c' : cocone F} (f : c βΆ c') :
(H.map_cocone c) βΆ (H.map_cocone c') := (cocones.functoriality F H).map f
@[simp] lemma map_cone_Ο (c : cone F) (j : J) :
(map_cone H c).Ο.app j = H.map (c.Ο.app j) := rfl
@[simp] lemma map_cocone_ΞΉ (c : cocone F) (j : J) :
(map_cocone H c).ΞΉ.app j = H.map (c.ΞΉ.app j) := rfl
/-- `map_cone` is the left inverse to `map_cone_inv`. -/
def map_cone_map_cone_inv {F : J β₯€ D} (H : D β₯€ C) [is_equivalence H] (c : cone (F β H)) :
map_cone H (map_cone_inv H c) β
c :=
begin
apply cones.ext _ (Ξ» j, _),
{ exact H.inv_fun_id.app c.X },
{ dsimp,
erw [comp_id, β H.inv_fun_id.hom.naturality (c.Ο.app j), comp_map, H.map_comp],
congr' 1,
erw [β cancel_epi (H.inv_fun_id.inv.app (H.obj (F.obj j))), nat_iso.inv_hom_id_app,
β (functor.as_equivalence H).functor_unit _, β H.map_comp, nat_iso.hom_inv_id_app,
H.map_id],
refl }
end
end functor
end category_theory
namespace category_theory.limits
variables {F : J β₯€ Cα΅α΅}
-- Here and below we only automatically generate the `@[simp]` lemma for the `X` field,
-- as we can be a simpler `rfl` lemma for the components of the natural transformation by hand.
@[simps X] def cone_of_cocone_left_op (c : cocone F.left_op) : cone F :=
{ X := op c.X,
Ο := nat_trans.right_op (c.ΞΉ β« (const.op_obj_unop (op c.X)).hom) }
@[simp] lemma cone_of_cocone_left_op_Ο_app (c : cocone F.left_op) (j) :
(cone_of_cocone_left_op c).Ο.app j = (c.ΞΉ.app (op j)).op :=
by { dsimp [cone_of_cocone_left_op], simp }
@[simps X] def cocone_left_op_of_cone (c : cone F) : cocone (F.left_op) :=
{ X := unop c.X,
ΞΉ := nat_trans.left_op c.Ο }
@[simp] lemma cocone_left_op_of_cone_ΞΉ_app (c : cone F) (j) :
(cocone_left_op_of_cone c).ΞΉ.app j = (c.Ο.app (unop j)).unop :=
by { dsimp [cocone_left_op_of_cone], simp }
@[simps X] def cocone_of_cone_left_op (c : cone F.left_op) : cocone F :=
{ X := op c.X,
ΞΉ := nat_trans.right_op ((const.op_obj_unop (op c.X)).hom β« c.Ο) }
@[simp] lemma cocone_of_cone_left_op_ΞΉ_app (c : cone F.left_op) (j) :
(cocone_of_cone_left_op c).ΞΉ.app j = (c.Ο.app (op j)).op :=
by { dsimp [cocone_of_cone_left_op], simp }
@[simps X] def cone_left_op_of_cocone (c : cocone F) : cone (F.left_op) :=
{ X := unop c.X,
Ο := nat_trans.left_op c.ΞΉ }
@[simp] lemma cone_left_op_of_cocone_Ο_app (c : cocone F) (j) :
(cone_left_op_of_cocone c).Ο.app j = (c.ΞΉ.app (unop j)).unop :=
by { dsimp [cone_left_op_of_cocone], simp }
end category_theory.limits
|
aecf6d57879e55fe648f71a1d1e32e8d03046f54 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/bad_structures.lean | f0aeab7cce60fdb70e5eda9cc4a1fc4e4c29bae9 | [
"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 | 341 | lean | prelude namespace foo structure {l} prod (A : Sort l) (B : Sort l) :=
(pr1 : A) (pr2 : B)
structure {l} prod1 (A : Sort l) (B : Sort l) : Type :=
(pr1 : A) (pr2 : B)
structure {l} prod2 (A : Sort l) (B : Sort l) : Sort l :=
(pr1 : A) (pr2 : B)
structure {l} prod3 (A : Sort l) (B : Sort l) : Sort (max 1 l) :=
(pr1 : A) (pr2 : B)
end foo
|
ee46d639a4f65a1e980e8b99742d7bfa71a373b0 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/data/real/cau_seq.lean | 82fee058380cf365e3e5f1313e413cc05415be87 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 30,777 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.order.absolute_value
import algebra.big_operators.order
/-!
# Cauchy sequences
A basic theory of Cauchy sequences, used in the construction of the reals and p-adic numbers. Where
applicable, lemmas that will be reused in other contexts have been stated in extra generality.
There are other "versions" of Cauchyness in the library, in particular Cauchy filters in topology.
This is a concrete implementation that is useful for simplicity and computability reasons.
## Important definitions
* `is_cau_seq`: a predicate that says `f : β β Ξ²` is Cauchy.
* `cau_seq`: the type of Cauchy sequences valued in type `Ξ²` with respect to an absolute value
function `abv`.
## Tags
sequence, cauchy, abs val, absolute value
-/
open_locale big_operators
open is_absolute_value
theorem exists_forall_ge_and {Ξ±} [linear_order Ξ±] {P Q : Ξ± β Prop} :
(β i, β j β₯ i, P j) β (β i, β j β₯ i, Q j) β
β i, β j β₯ i, P j β§ Q j
| β¨a, hββ© β¨b, hββ© := let β¨c, ac, bcβ© := exists_ge_of_linear a b in
β¨c, Ξ» j hj, β¨hβ _ (le_trans ac hj), hβ _ (le_trans bc hj)β©β©
section
variables {Ξ± : Type*} [linear_ordered_field Ξ±]
{Ξ² : Type*} [ring Ξ²] (abv : Ξ² β Ξ±) [is_absolute_value abv]
theorem rat_add_continuous_lemma
{Ξ΅ : Ξ±} (Ξ΅0 : 0 < Ξ΅) : β Ξ΄ > 0, β {aβ aβ bβ bβ : Ξ²},
abv (aβ - bβ) < Ξ΄ β abv (aβ - bβ) < Ξ΄ β abv (aβ + aβ - (bβ + bβ)) < Ξ΅ :=
β¨Ξ΅ / 2, half_pos Ξ΅0, Ξ» aβ aβ bβ bβ hβ hβ,
by simpa [add_halves, sub_eq_add_neg, add_comm, add_left_comm, add_assoc]
using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add hβ hβ)β©
theorem rat_mul_continuous_lemma
{Ξ΅ Kβ Kβ : Ξ±} (Ξ΅0 : 0 < Ξ΅) :
β Ξ΄ > 0, β {aβ aβ bβ bβ : Ξ²}, abv aβ < Kβ β abv bβ < Kβ β
abv (aβ - bβ) < Ξ΄ β abv (aβ - bβ) < Ξ΄ β abv (aβ * aβ - bβ * bβ) < Ξ΅ :=
begin
have K0 : (0 : Ξ±) < max 1 (max Kβ Kβ) := lt_of_lt_of_le zero_lt_one (le_max_left _ _),
have Ξ΅K := div_pos (half_pos Ξ΅0) K0,
refine β¨_, Ξ΅K, Ξ» aβ aβ bβ bβ haβ hbβ hβ hβ, _β©,
replace haβ := lt_of_lt_of_le haβ (le_trans (le_max_left _ Kβ) (le_max_right 1 _)),
replace hbβ := lt_of_lt_of_le hbβ (le_trans (le_max_right Kβ _) (le_max_right 1 _)),
have := add_lt_add
(mul_lt_mul' (le_of_lt hβ) hbβ (abv_nonneg abv _) Ξ΅K)
(mul_lt_mul' (le_of_lt hβ) haβ (abv_nonneg abv _) Ξ΅K),
rw [β abv_mul abv, mul_comm, div_mul_cancel _ (ne_of_gt K0), β abv_mul abv, add_halves] at this,
simpa [mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm]
using lt_of_le_of_lt (abv_add abv _ _) this
end
theorem rat_inv_continuous_lemma
{Ξ² : Type*} [field Ξ²] (abv : Ξ² β Ξ±) [is_absolute_value abv]
{Ξ΅ K : Ξ±} (Ξ΅0 : 0 < Ξ΅) (K0 : 0 < K) :
β Ξ΄ > 0, β {a b : Ξ²}, K β€ abv a β K β€ abv b β
abv (a - b) < Ξ΄ β abv (aβ»ΒΉ - bβ»ΒΉ) < Ξ΅ :=
begin
have KK := mul_pos K0 K0,
have Ξ΅K := mul_pos Ξ΅0 KK,
refine β¨_, Ξ΅K, Ξ» a b ha hb h, _β©,
have a0 := lt_of_lt_of_le K0 ha,
have b0 := lt_of_lt_of_le K0 hb,
rw [inv_sub_inv ((abv_pos abv).1 a0) ((abv_pos abv).1 b0),
abv_div abv, abv_mul abv, mul_comm, abv_sub abv,
β mul_div_cancel Ξ΅ (ne_of_gt KK)],
exact div_lt_div h
(mul_le_mul hb ha (le_of_lt K0) (abv_nonneg abv _))
(le_of_lt $ mul_pos Ξ΅0 KK) KK
end
end
/-- A sequence is Cauchy if the distance between its entries tends to zero. -/
def is_cau_seq {Ξ± : Type*} [linear_ordered_field Ξ±]
{Ξ² : Type*} [ring Ξ²] (abv : Ξ² β Ξ±) (f : β β Ξ²) : Prop :=
β Ξ΅ > 0, β i, β j β₯ i, abv (f j - f i) < Ξ΅
namespace is_cau_seq
variables {Ξ± : Type*} [linear_ordered_field Ξ±]
{Ξ² : Type*} [ring Ξ²] {abv : Ξ² β Ξ±} [is_absolute_value abv] {f : β β Ξ²}
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem cauchyβ (hf : is_cau_seq abv f) {Ξ΅ : Ξ±} (Ξ΅0 : 0 < Ξ΅) :
β i, β j k β₯ i, abv (f j - f k) < Ξ΅ :=
begin
refine (hf _ (half_pos Ξ΅0)).imp (Ξ» i hi j ij k ik, _),
rw β add_halves Ξ΅,
refine lt_of_le_of_lt (abv_sub_le abv _ _ _) (add_lt_add (hi _ ij) _),
rw abv_sub abv, exact hi _ ik
end
theorem cauchyβ (hf : is_cau_seq abv f) {Ξ΅ : Ξ±} (Ξ΅0 : 0 < Ξ΅) :
β i, β j β₯ i, β k β₯ j, abv (f k - f j) < Ξ΅ :=
let β¨i, Hβ© := hf.cauchyβ Ξ΅0 in β¨i, Ξ» j ij k jk, H _ (le_trans ij jk) _ ijβ©
end is_cau_seq
/-- `cau_seq Ξ² abv` is the type of `Ξ²`-valued Cauchy sequences, with respect to the absolute value
function `abv`. -/
def cau_seq {Ξ± : Type*} [linear_ordered_field Ξ±]
(Ξ² : Type*) [ring Ξ²] (abv : Ξ² β Ξ±) : Type* :=
{f : β β Ξ² // is_cau_seq abv f}
namespace cau_seq
variables {Ξ± : Type*} [linear_ordered_field Ξ±]
section ring
variables {Ξ² : Type*} [ring Ξ²] {abv : Ξ² β Ξ±}
instance : has_coe_to_fun (cau_seq Ξ² abv) (Ξ» _, β β Ξ²) := β¨subtype.valβ©
@[simp] theorem mk_to_fun (f) (hf : is_cau_seq abv f) :
@coe_fn (cau_seq Ξ² abv) _ _ β¨f, hfβ© = f := rfl
theorem ext {f g : cau_seq Ξ² abv} (h : β i, f i = g i) : f = g :=
subtype.eq (funext h)
theorem is_cau (f : cau_seq Ξ² abv) : is_cau_seq abv f := f.2
theorem cauchy (f : cau_seq Ξ² abv) :
β {Ξ΅}, 0 < Ξ΅ β β i, β j β₯ i, abv (f j - f i) < Ξ΅ := f.2
/-- Given a Cauchy sequence `f`, create a Cauchy sequence from a sequence `g` with
the same values as `f`. -/
def of_eq (f : cau_seq Ξ² abv) (g : β β Ξ²) (e : β i, f i = g i) : cau_seq Ξ² abv :=
β¨g, Ξ» Ξ΅, by rw [show g = f, from (funext e).symm]; exact f.cauchyβ©
variable [is_absolute_value abv]
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem cauchyβ (f : cau_seq Ξ² abv) {Ξ΅} : 0 < Ξ΅ β
β i, β j k β₯ i, abv (f j - f k) < Ξ΅ := f.2.cauchyβ
theorem cauchyβ (f : cau_seq Ξ² abv) {Ξ΅} : 0 < Ξ΅ β
β i, β j β₯ i, β k β₯ j, abv (f k - f j) < Ξ΅ := f.2.cauchyβ
theorem bounded (f : cau_seq Ξ² abv) : β r, β i, abv (f i) < r :=
begin
cases f.cauchy zero_lt_one with i h,
let R := β j in finset.range (i+1), abv (f j),
have : β j β€ i, abv (f j) β€ R,
{ intros j ij, change (Ξ» j, abv (f j)) j β€ R,
apply finset.single_le_sum,
{ intros, apply abv_nonneg abv },
{ rwa [finset.mem_range, nat.lt_succ_iff] } },
refine β¨R + 1, Ξ» j, _β©,
cases lt_or_le j i with ij ij,
{ exact lt_of_le_of_lt (this _ (le_of_lt ij)) (lt_add_one _) },
{ have := lt_of_le_of_lt (abv_add abv _ _)
(add_lt_add_of_le_of_lt (this _ le_rfl) (h _ ij)),
rw [add_sub, add_comm] at this, simpa }
end
theorem bounded' (f : cau_seq Ξ² abv) (x : Ξ±) : β r > x, β i, abv (f i) < r :=
let β¨r, hβ© := f.bounded in
β¨max r (x+1), lt_of_lt_of_le (lt_add_one _) (le_max_right _ _),
Ξ» i, lt_of_lt_of_le (h i) (le_max_left _ _)β©
instance : has_add (cau_seq Ξ² abv) :=
β¨Ξ» f g, β¨Ξ» i, (f i + g i : Ξ²), Ξ» Ξ΅ Ξ΅0,
let β¨Ξ΄, Ξ΄0, HΞ΄β© := rat_add_continuous_lemma abv Ξ΅0,
β¨i, Hβ© := exists_forall_ge_and (f.cauchyβ Ξ΄0) (g.cauchyβ Ξ΄0) in
β¨i, Ξ» j ij, let β¨Hβ, Hββ© := H _ le_rfl in HΞ΄ (Hβ _ ij) (Hβ _ ij)β©β©β©
@[simp] theorem add_apply (f g : cau_seq Ξ² abv) (i : β) : (f + g) i = f i + g i := rfl
variable (abv)
/-- The constant Cauchy sequence. -/
def const (x : Ξ²) : cau_seq Ξ² abv :=
β¨Ξ» i, x, Ξ» Ξ΅ Ξ΅0, β¨0, Ξ» j ij, by simpa [abv_zero abv] using Ξ΅0β©β©
variable {abv}
local notation `const` := const abv
@[simp] theorem const_apply (x : Ξ²) (i : β) : (const x : β β Ξ²) i = x := rfl
theorem const_inj {x y : Ξ²} : (const x : cau_seq Ξ² abv) = const y β x = y :=
β¨Ξ» h, congr_arg (Ξ» f:cau_seq Ξ² abv, (f:ββΞ²) 0) h, congr_arg _β©
instance : has_zero (cau_seq Ξ² abv) := β¨const 0β©
instance : has_one (cau_seq Ξ² abv) := β¨const 1β©
instance : inhabited (cau_seq Ξ² abv) := β¨0β©
@[simp] theorem zero_apply (i) : (0 : cau_seq Ξ² abv) i = 0 := rfl
@[simp] theorem one_apply (i) : (1 : cau_seq Ξ² abv) i = 1 := rfl
@[simp] theorem const_zero : const 0 = 0 := rfl
theorem const_add (x y : Ξ²) : const (x + y) = const x + const y :=
rfl
instance : has_mul (cau_seq Ξ² abv) :=
β¨Ξ» f g, β¨Ξ» i, (f i * g i : Ξ²), Ξ» Ξ΅ Ξ΅0,
let β¨F, F0, hFβ© := f.bounded' 0, β¨G, G0, hGβ© := g.bounded' 0,
β¨Ξ΄, Ξ΄0, HΞ΄β© := rat_mul_continuous_lemma abv Ξ΅0,
β¨i, Hβ© := exists_forall_ge_and (f.cauchyβ Ξ΄0) (g.cauchyβ Ξ΄0) in
β¨i, Ξ» j ij, let β¨Hβ, Hββ© := H _ le_rfl in
HΞ΄ (hF j) (hG i) (Hβ _ ij) (Hβ _ ij)β©β©β©
@[simp] theorem mul_apply (f g : cau_seq Ξ² abv) (i : β) : (f * g) i = f i * g i := rfl
theorem const_mul (x y : Ξ²) : const (x * y) = const x * const y :=
ext $ Ξ» i, rfl
instance : has_neg (cau_seq Ξ² abv) :=
β¨Ξ» f, of_eq (const (-1) * f) (Ξ» x, -f x) (Ξ» i, by simp)β©
@[simp] theorem neg_apply (f : cau_seq Ξ² abv) (i) : (-f) i = -f i := rfl
theorem const_neg (x : Ξ²) : const (-x) = -const x :=
ext $ Ξ» i, rfl
instance : has_sub (cau_seq Ξ² abv) :=
β¨Ξ» f g, of_eq (f + -g) (Ξ» x, f x - g x) (Ξ» i, by simp [sub_eq_add_neg])β©
@[simp] theorem sub_apply (f g : cau_seq Ξ² abv) (i : β) : (f - g) i = f i - g i := rfl
theorem const_sub (x y : Ξ²) : const (x - y) = const x - const y :=
ext $ Ξ» i, rfl
instance : add_group (cau_seq Ξ² abv) :=
by refine_struct
{ add := (+),
neg := has_neg.neg,
zero := (0 : cau_seq Ξ² abv),
sub := has_sub.sub,
zsmul := @zsmul_rec (cau_seq Ξ² abv) β¨0β© β¨(+)β© β¨has_neg.negβ©,
nsmul := @nsmul_rec (cau_seq Ξ² abv) β¨0β© β¨(+)β© };
intros; try { refl }; apply ext; simp [add_comm, add_left_comm, sub_eq_add_neg]
instance : add_group_with_one (cau_seq Ξ² abv) :=
{ one := 1,
nat_cast := Ξ» n, const n,
nat_cast_zero := congr_arg const nat.cast_zero,
nat_cast_succ := Ξ» n, congr_arg const (nat.cast_succ n),
int_cast := Ξ» n, const n,
int_cast_of_nat := Ξ» n, congr_arg const (int.cast_of_nat n),
int_cast_neg_succ_of_nat := Ξ» n, congr_arg const (int.cast_neg_succ_of_nat n),
.. cau_seq.add_group }
instance : ring (cau_seq Ξ² abv) :=
by refine_struct
{ add := (+),
zero := (0 : cau_seq Ξ² abv),
mul := (*),
one := 1,
npow := @npow_rec (cau_seq Ξ² abv) β¨1β© β¨(*)β©,
.. cau_seq.add_group_with_one };
intros; try { refl }; apply ext;
simp [mul_add, mul_assoc, add_mul, add_comm, add_left_comm, sub_eq_add_neg]
instance {Ξ² : Type*} [comm_ring Ξ²] {abv : Ξ² β Ξ±} [is_absolute_value abv] :
comm_ring (cau_seq Ξ² abv) :=
{ mul_comm := by intros; apply ext; simp [mul_left_comm, mul_comm],
..cau_seq.ring }
/-- `lim_zero f` holds when `f` approaches 0. -/
def lim_zero {abv : Ξ² β Ξ±} (f : cau_seq Ξ² abv) : Prop := β Ξ΅ > 0, β i, β j β₯ i, abv (f j) < Ξ΅
theorem add_lim_zero {f g : cau_seq Ξ² abv}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f + g)
| Ξ΅ Ξ΅0 := (exists_forall_ge_and
(hf _ $ half_pos Ξ΅0) (hg _ $ half_pos Ξ΅0)).imp $
Ξ» i H j ij, let β¨Hβ, Hββ© := H _ ij in
by simpa [add_halves Ξ΅] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add Hβ Hβ)
theorem mul_lim_zero_right (f : cau_seq Ξ² abv) {g}
(hg : lim_zero g) : lim_zero (f * g)
| Ξ΅ Ξ΅0 := let β¨F, F0, hFβ© := f.bounded' 0 in
(hg _ $ div_pos Ξ΅0 F0).imp $ Ξ» i H j ij,
by have := mul_lt_mul' (le_of_lt $ hF j) (H _ ij) (abv_nonneg abv _) F0;
rwa [mul_comm F, div_mul_cancel _ (ne_of_gt F0), β abv_mul abv] at this
theorem mul_lim_zero_left {f} (g : cau_seq Ξ² abv)
(hg : lim_zero f) : lim_zero (f * g)
| Ξ΅ Ξ΅0 := let β¨G, G0, hGβ© := g.bounded' 0 in
(hg _ $ div_pos Ξ΅0 G0).imp $ Ξ» i H j ij,
by have := mul_lt_mul'' (H _ ij) (hG j) (abv_nonneg abv _) (abv_nonneg abv _);
rwa [div_mul_cancel _ (ne_of_gt G0), β abv_mul abv] at this
theorem neg_lim_zero {f : cau_seq Ξ² abv} (hf : lim_zero f) : lim_zero (-f) :=
by rw β neg_one_mul; exact mul_lim_zero_right _ hf
theorem sub_lim_zero {f g : cau_seq Ξ² abv}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f - g) :=
by simpa only [sub_eq_add_neg] using add_lim_zero hf (neg_lim_zero hg)
theorem lim_zero_sub_rev {f g : cau_seq Ξ² abv} (hfg : lim_zero (f - g)) : lim_zero (g - f) :=
by simpa using neg_lim_zero hfg
theorem zero_lim_zero : lim_zero (0 : cau_seq Ξ² abv)
| Ξ΅ Ξ΅0 := β¨0, Ξ» j ij, by simpa [abv_zero abv] using Ξ΅0β©
theorem const_lim_zero {x : Ξ²} : lim_zero (const x) β x = 0 :=
β¨Ξ» H, (abv_eq_zero abv).1 $
eq_of_le_of_forall_le_of_dense (abv_nonneg abv _) $
Ξ» Ξ΅ Ξ΅0, let β¨i, hiβ© := H _ Ξ΅0 in le_of_lt $ hi _ le_rfl,
Ξ» e, e.symm βΈ zero_lim_zeroβ©
instance equiv : setoid (cau_seq Ξ² abv) :=
β¨Ξ» f g, lim_zero (f - g),
β¨Ξ» f, by simp [zero_lim_zero],
Ξ» f g h, by simpa using neg_lim_zero h,
Ξ» f g h fg gh, by simpa [sub_eq_add_neg, add_assoc] using add_lim_zero fg ghβ©β©
lemma add_equiv_add {f1 f2 g1 g2 : cau_seq Ξ² abv} (hf : f1 β f2) (hg : g1 β g2) :
f1 + g1 β f2 + g2 :=
by simpa only [βadd_sub_add_comm] using add_lim_zero hf hg
lemma neg_equiv_neg {f g : cau_seq Ξ² abv} (hf : f β g) : -f β -g :=
by simpa only [neg_sub'] using neg_lim_zero hf
lemma sub_equiv_sub {f1 f2 g1 g2 : cau_seq Ξ² abv} (hf : f1 β f2) (hg : g1 β g2) :
f1 - g1 β f2 - g2 :=
by simpa only [sub_eq_add_neg] using add_equiv_add hf (neg_equiv_neg hg)
theorem equiv_defβ {f g : cau_seq Ξ² abv} (h : f β g) {Ξ΅ : Ξ±} (Ξ΅0 : 0 < Ξ΅) :
β i, β j β₯ i, β k β₯ j, abv (f k - g j) < Ξ΅ :=
(exists_forall_ge_and (h _ $ half_pos Ξ΅0) (f.cauchyβ $ half_pos Ξ΅0)).imp $
Ξ» i H j ij k jk, let β¨hβ, hββ© := H _ ij in
by have := lt_of_le_of_lt (abv_add abv (f j - g j) _) (add_lt_add hβ (hβ _ jk));
rwa [sub_add_sub_cancel', add_halves] at this
theorem lim_zero_congr {f g : cau_seq Ξ² abv} (h : f β g) : lim_zero f β lim_zero g :=
β¨Ξ» l, by simpa using add_lim_zero (setoid.symm h) l,
Ξ» l, by simpa using add_lim_zero h lβ©
theorem abv_pos_of_not_lim_zero {f : cau_seq Ξ² abv} (hf : Β¬ lim_zero f) :
β K > 0, β i, β j β₯ i, K β€ abv (f j) :=
begin
haveI := classical.prop_decidable,
by_contra nk,
refine hf (Ξ» Ξ΅ Ξ΅0, _),
simp [not_forall] at nk,
cases f.cauchyβ (half_pos Ξ΅0) with i hi,
rcases nk _ (half_pos Ξ΅0) i with β¨j, ij, hjβ©,
refine β¨j, Ξ» k jk, _β©,
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi j ij k jk) hj),
rwa [sub_add_cancel, add_halves] at this
end
theorem of_near (f : β β Ξ²) (g : cau_seq Ξ² abv)
(h : β Ξ΅ > 0, β i, β j β₯ i, abv (f j - g j) < Ξ΅) : is_cau_seq abv f
| Ξ΅ Ξ΅0 :=
let β¨i, hiβ© := exists_forall_ge_and
(h _ (half_pos $ half_pos Ξ΅0)) (g.cauchyβ $ half_pos Ξ΅0) in
β¨i, Ξ» j ij, begin
cases hi _ le_rfl with hβ hβ, rw abv_sub abv at hβ,
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi _ ij).1 hβ),
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add this (hβ _ ij)),
rwa [add_halves, add_halves, add_right_comm,
sub_add_sub_cancel, sub_add_sub_cancel] at this
endβ©
lemma not_lim_zero_of_not_congr_zero {f : cau_seq _ abv} (hf : Β¬ f β 0) : Β¬ lim_zero f :=
assume : lim_zero f,
have lim_zero (f - 0), by simpa,
hf this
lemma mul_equiv_zero (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f β 0) : g * f β 0 :=
have lim_zero (f - 0), from hf,
have lim_zero (g*f), from mul_lim_zero_right _ $ by simpa,
show lim_zero (g*f - 0), by simpa
lemma mul_not_equiv_zero {f g : cau_seq _ abv} (hf : Β¬ f β 0) (hg : Β¬ g β 0) : Β¬ (f * g) β 0 :=
assume : lim_zero (f*g - 0),
have hlz : lim_zero (f*g), by simpa,
have hf' : Β¬ lim_zero f, by simpa using (show Β¬ lim_zero (f - 0), from hf),
have hg' : Β¬ lim_zero g, by simpa using (show Β¬ lim_zero (g - 0), from hg),
begin
rcases abv_pos_of_not_lim_zero hf' with β¨a1, ha1, N1, hN1β©,
rcases abv_pos_of_not_lim_zero hg' with β¨a2, ha2, N2, hN2β©,
have : 0 < a1 * a2, from mul_pos ha1 ha2,
cases hlz _ this with N hN,
let i := max N (max N1 N2),
have hN' := hN i (le_max_left _ _),
have hN1' := hN1 i (le_trans (le_max_left _ _) (le_max_right _ _)),
have hN1' := hN2 i (le_trans (le_max_right _ _) (le_max_right _ _)),
apply not_le_of_lt hN',
change _ β€ abv (_ * _),
rw is_absolute_value.abv_mul abv,
apply mul_le_mul; try { assumption },
{ apply le_of_lt ha2 },
{ apply is_absolute_value.abv_nonneg abv }
end
theorem const_equiv {x y : Ξ²} : const x β const y β x = y :=
show lim_zero _ β _, by rw [β const_sub, const_lim_zero, sub_eq_zero]
end ring
section comm_ring
variables {Ξ² : Type*} [comm_ring Ξ²] {abv : Ξ² β Ξ±} [is_absolute_value abv]
lemma mul_equiv_zero' (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f β 0) : f * g β 0 :=
by rw mul_comm; apply mul_equiv_zero _ hf
lemma mul_equiv_mul {f1 f2 g1 g2 : cau_seq Ξ² abv} (hf : f1 β f2) (hg : g1 β g2) :
f1 * g1 β f2 * g2 :=
by simpa only [mul_sub, mul_comm, sub_add_sub_cancel]
using add_lim_zero (mul_lim_zero_right g1 hf) (mul_lim_zero_right f2 hg)
end comm_ring
section is_domain
variables {Ξ² : Type*} [ring Ξ²] [is_domain Ξ²] (abv : Ξ² β Ξ±) [is_absolute_value abv]
lemma one_not_equiv_zero : Β¬ (const abv 1) β (const abv 0) :=
assume h,
have β Ξ΅ > 0, β i, β k, i β€ k β abv (1 - 0) < Ξ΅, from h,
have h1 : abv 1 β€ 0, from le_of_not_gt $
assume h2 : 0 < abv 1,
exists.elim (this _ h2) $ Ξ» i hi,
lt_irrefl (abv 1) $ by simpa using hi _ le_rfl,
have h2 : 0 β€ abv 1, from is_absolute_value.abv_nonneg _ _,
have abv 1 = 0, from le_antisymm h1 h2,
have (1 : Ξ²) = 0, from (is_absolute_value.abv_eq_zero abv).1 this,
absurd this one_ne_zero
end is_domain
section field
variables {Ξ² : Type*} [field Ξ²] {abv : Ξ² β Ξ±} [is_absolute_value abv]
theorem inv_aux {f : cau_seq Ξ² abv} (hf : Β¬ lim_zero f) :
β Ξ΅ > 0, β i, β j β₯ i, abv ((f j)β»ΒΉ - (f i)β»ΒΉ) < Ξ΅ | Ξ΅ Ξ΅0 :=
let β¨K, K0, HKβ© := abv_pos_of_not_lim_zero hf,
β¨Ξ΄, Ξ΄0, HΞ΄β© := rat_inv_continuous_lemma abv Ξ΅0 K0,
β¨i, Hβ© := exists_forall_ge_and HK (f.cauchyβ Ξ΄0) in
β¨i, Ξ» j ij, let β¨iK, H'β© := H _ le_rfl in HΞ΄ (H _ ij).1 iK (H' _ ij)β©
/-- Given a Cauchy sequence `f` with nonzero limit, create a Cauchy sequence with values equal to
the inverses of the values of `f`. -/
def inv (f : cau_seq Ξ² abv) (hf : Β¬ lim_zero f) : cau_seq Ξ² abv := β¨_, inv_aux hfβ©
@[simp] theorem inv_apply {f : cau_seq Ξ² abv} (hf i) : inv f hf i = (f i)β»ΒΉ := rfl
theorem inv_mul_cancel {f : cau_seq Ξ² abv} (hf) : inv f hf * f β 1 :=
Ξ» Ξ΅ Ξ΅0, let β¨K, K0, i, Hβ© := abv_pos_of_not_lim_zero hf in
β¨i, Ξ» j ij,
by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)),
abv_zero abv] using Ξ΅0β©
theorem const_inv {x : Ξ²} (hx : x β 0) :
const abv (xβ»ΒΉ) = inv (const abv x) (by rwa const_lim_zero) :=
ext (assume n, by simp[inv_apply, const_apply])
end field
section abs
local notation `const` := const abs
/-- The entries of a positive Cauchy sequence eventually have a positive lower bound. -/
def pos (f : cau_seq Ξ± abs) : Prop := β K > 0, β i, β j β₯ i, K β€ f j
theorem not_lim_zero_of_pos {f : cau_seq Ξ± abs} : pos f β Β¬ lim_zero f
| β¨F, F0, hFβ© H :=
let β¨i, hβ© := exists_forall_ge_and hF (H _ F0),
β¨hβ, hββ© := h _ le_rfl in
not_lt_of_le hβ (abs_lt.1 hβ).2
theorem const_pos {x : Ξ±} : pos (const x) β 0 < x :=
β¨Ξ» β¨K, K0, i, hβ©, lt_of_lt_of_le K0 (h _ le_rfl),
Ξ» h, β¨x, h, 0, Ξ» j _, le_rflβ©β©
theorem add_pos {f g : cau_seq Ξ± abs} : pos f β pos g β pos (f + g)
| β¨F, F0, hFβ© β¨G, G0, hGβ© :=
let β¨i, hβ© := exists_forall_ge_and hF hG in
β¨_, _root_.add_pos F0 G0, i,
Ξ» j ij, let β¨hβ, hββ© := h _ ij in add_le_add hβ hββ©
theorem pos_add_lim_zero {f g : cau_seq Ξ± abs} : pos f β lim_zero g β pos (f + g)
| β¨F, F0, hFβ© H :=
let β¨i, hβ© := exists_forall_ge_and hF (H _ (half_pos F0)) in
β¨_, half_pos F0, i, Ξ» j ij, begin
cases h j ij with hβ hβ,
have := add_le_add hβ (le_of_lt (abs_lt.1 hβ).1),
rwa [β sub_eq_add_neg, sub_self_div_two] at this
endβ©
protected theorem mul_pos {f g : cau_seq Ξ± abs} : pos f β pos g β pos (f * g)
| β¨F, F0, hFβ© β¨G, G0, hGβ© :=
let β¨i, hβ© := exists_forall_ge_and hF hG in
β¨_, _root_.mul_pos F0 G0, i,
Ξ» j ij, let β¨hβ, hββ© := h _ ij in
mul_le_mul hβ hβ (le_of_lt G0) (le_trans (le_of_lt F0) hβ)β©
theorem trichotomy (f : cau_seq Ξ± abs) : pos f β¨ lim_zero f β¨ pos (-f) :=
begin
cases classical.em (lim_zero f); simp *,
rcases abv_pos_of_not_lim_zero h with β¨K, K0, hKβ©,
rcases exists_forall_ge_and hK (f.cauchyβ K0) with β¨i, hiβ©,
refine (le_total 0 (f i)).imp _ _;
refine (Ξ» h, β¨K, K0, i, Ξ» j ij, _β©);
have := (hi _ ij).1;
cases hi _ le_rfl with hβ hβ,
{ rwa abs_of_nonneg at this,
rw abs_of_nonneg h at hβ,
exact (le_add_iff_nonneg_right _).1
(le_trans hβ $ neg_le_sub_iff_le_add'.1 $
le_of_lt (abs_lt.1 $ hβ _ ij).1) },
{ rwa abs_of_nonpos at this,
rw abs_of_nonpos h at hβ,
rw [β sub_le_sub_iff_right, zero_sub],
exact le_trans (le_of_lt (abs_lt.1 $ hβ _ ij).2) hβ }
end
instance : has_lt (cau_seq Ξ± abs) := β¨Ξ» f g, pos (g - f)β©
instance : has_le (cau_seq Ξ± abs) := β¨Ξ» f g, f < g β¨ f β gβ©
theorem lt_of_lt_of_eq {f g h : cau_seq Ξ± abs}
(fg : f < g) (gh : g β h) : f < h :=
show pos (h - f),
by simpa [sub_eq_add_neg, add_comm, add_left_comm] using pos_add_lim_zero fg (neg_lim_zero gh)
theorem lt_of_eq_of_lt {f g h : cau_seq Ξ± abs}
(fg : f β g) (gh : g < h) : f < h :=
by have := pos_add_lim_zero gh (neg_lim_zero fg);
rwa [β sub_eq_add_neg, sub_sub_sub_cancel_right] at this
theorem lt_trans {f g h : cau_seq Ξ± abs} (fg : f < g) (gh : g < h) : f < h :=
show pos (h - f),
by simpa [sub_eq_add_neg, add_comm, add_left_comm] using add_pos fg gh
theorem lt_irrefl {f : cau_seq Ξ± abs} : Β¬ f < f
| h := not_lim_zero_of_pos h (by simp [zero_lim_zero])
lemma le_of_eq_of_le {f g h : cau_seq Ξ± abs}
(hfg : f β g) (hgh : g β€ h) : f β€ h :=
hgh.elim (or.inl β cau_seq.lt_of_eq_of_lt hfg)
(or.inr β setoid.trans hfg)
lemma le_of_le_of_eq {f g h : cau_seq Ξ± abs}
(hfg : f β€ g) (hgh : g β h) : f β€ h :=
hfg.elim (Ξ» h, or.inl (cau_seq.lt_of_lt_of_eq h hgh))
(Ξ» h, or.inr (setoid.trans h hgh))
instance : preorder (cau_seq Ξ± abs) :=
{ lt := (<),
le := Ξ» f g, f < g β¨ f β g,
le_refl := Ξ» f, or.inr (setoid.refl _),
le_trans := Ξ» f g h fg, match fg with
| or.inl fg, or.inl gh := or.inl $ lt_trans fg gh
| or.inl fg, or.inr gh := or.inl $ lt_of_lt_of_eq fg gh
| or.inr fg, or.inl gh := or.inl $ lt_of_eq_of_lt fg gh
| or.inr fg, or.inr gh := or.inr $ setoid.trans fg gh
end,
lt_iff_le_not_le := Ξ» f g,
β¨Ξ» h, β¨or.inl h,
not_or (mt (lt_trans h) lt_irrefl) (not_lim_zero_of_pos h)β©,
Ξ» β¨hβ, hββ©, hβ.resolve_right
(mt (Ξ» h, or.inr (setoid.symm h)) hβ)β© }
theorem le_antisymm {f g : cau_seq Ξ± abs} (fg : f β€ g) (gf : g β€ f) : f β g :=
fg.resolve_left (not_lt_of_le gf)
theorem lt_total (f g : cau_seq Ξ± abs) : f < g β¨ f β g β¨ g < f :=
(trichotomy (g - f)).imp_right
(Ξ» h, h.imp (Ξ» h, setoid.symm h) (Ξ» h, by rwa neg_sub at h))
theorem le_total (f g : cau_seq Ξ± abs) : f β€ g β¨ g β€ f :=
(or.assoc.2 (lt_total f g)).imp_right or.inl
theorem const_lt {x y : Ξ±} : const x < const y β x < y :=
show pos _ β _, by rw [β const_sub, const_pos, sub_pos]
theorem const_le {x y : Ξ±} : const x β€ const y β x β€ y :=
by rw le_iff_lt_or_eq; exact or_congr const_lt const_equiv
lemma le_of_exists {f g : cau_seq Ξ± abs}
(h : β i, β j β₯ i, f j β€ g j) : f β€ g :=
let β¨i, hiβ© := h in
(or.assoc.2 (cau_seq.lt_total f g)).elim
id
(Ξ» hgf, false.elim (let β¨K, hK0, j, hKjβ© := hgf in
not_lt_of_ge (hi (max i j) (le_max_left _ _))
(sub_pos.1 (lt_of_lt_of_le hK0 (hKj _ (le_max_right _ _))))))
theorem exists_gt (f : cau_seq Ξ± abs) : β a : Ξ±, f < const a :=
let β¨K, Hβ© := f.bounded in
β¨K + 1, 1, zero_lt_one, 0, Ξ» i _, begin
rw [sub_apply, const_apply, le_sub_iff_add_le', add_le_add_iff_right],
exact le_of_lt (abs_lt.1 (H _)).2
endβ©
theorem exists_lt (f : cau_seq Ξ± abs) : β a : Ξ±, const a < f :=
let β¨a, hβ© := (-f).exists_gt in β¨-a, show pos _,
by rwa [const_neg, sub_neg_eq_add, add_comm, β sub_neg_eq_add]β©
-- so named to match `rat_add_continuous_lemma`
theorem _root_.rat_sup_continuous_lemma {Ξ΅ : Ξ±} {aβ aβ bβ bβ : Ξ±} :
abs (aβ - bβ) < Ξ΅ β abs (aβ - bβ) < Ξ΅ β abs (aβ β aβ - (bβ β bβ)) < Ξ΅ :=
Ξ» hβ hβ, (abs_max_sub_max_le_max _ _ _ _).trans_lt (max_lt hβ hβ)
-- so named to match `rat_add_continuous_lemma`
theorem _root_.rat_inf_continuous_lemma {Ξ΅ : Ξ±} {aβ aβ bβ bβ : Ξ±} :
abs (aβ - bβ) < Ξ΅ β abs (aβ - bβ) < Ξ΅ β abs (aβ β aβ - (bβ β bβ)) < Ξ΅ :=
Ξ» hβ hβ, (abs_min_sub_min_le_max _ _ _ _).trans_lt (max_lt hβ hβ)
instance : has_sup (cau_seq Ξ± abs) :=
β¨Ξ» f g, β¨f β g, Ξ» Ξ΅ Ξ΅0,
(exists_forall_ge_and (f.cauchyβ Ξ΅0) (g.cauchyβ Ξ΅0)).imp $ Ξ» i H j ij,
let β¨Hβ, Hββ© := H _ le_rfl in rat_sup_continuous_lemma (Hβ _ ij) (Hβ _ ij)β©β©
instance : has_inf (cau_seq Ξ± abs) :=
β¨Ξ» f g, β¨f β g, Ξ» Ξ΅ Ξ΅0,
(exists_forall_ge_and (f.cauchyβ Ξ΅0) (g.cauchyβ Ξ΅0)).imp $ Ξ» i H j ij,
let β¨Hβ, Hββ© := H _ le_rfl in rat_inf_continuous_lemma (Hβ _ ij) (Hβ _ ij)β©β©
@[simp, norm_cast] lemma coe_sup (f g : cau_seq Ξ± abs) : β(f β g) = f β g := rfl
@[simp, norm_cast] lemma coe_inf (f g : cau_seq Ξ± abs) : β(f β g) = f β g := rfl
theorem sup_lim_zero {f g : cau_seq Ξ± abs}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f β g)
| Ξ΅ Ξ΅0 := (exists_forall_ge_and (hf _ Ξ΅0) (hg _ Ξ΅0)).imp $
Ξ» i H j ij, let β¨Hβ, Hββ© := H _ ij in begin
rw abs_lt at Hβ Hβ β’,
exact β¨lt_sup_iff.mpr (or.inl Hβ.1), sup_lt_iff.mpr β¨Hβ.2, Hβ.2β©β©
end
theorem inf_lim_zero {f g : cau_seq Ξ± abs}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f β g)
| Ξ΅ Ξ΅0 := (exists_forall_ge_and (hf _ Ξ΅0) (hg _ Ξ΅0)).imp $
Ξ» i H j ij, let β¨Hβ, Hββ© := H _ ij in begin
rw abs_lt at Hβ Hβ β’,
exact β¨lt_inf_iff.mpr β¨Hβ.1, Hβ.1β©, inf_lt_iff.mpr (or.inl Hβ.2), β©
end
lemma sup_equiv_sup {aβ bβ aβ bβ : cau_seq Ξ± abs} (ha : aβ β aβ) (hb : bβ β bβ) :
aβ β bβ β aβ β bβ :=
begin
intros Ξ΅ Ξ΅0,
obtain β¨ai, haiβ© := ha Ξ΅ Ξ΅0,
obtain β¨bi, hbiβ© := hb Ξ΅ Ξ΅0,
exact β¨ai β bi, Ξ» i hi,
(abs_max_sub_max_le_max (aβ i) (bβ i) (aβ i) (bβ i)).trans_lt
(max_lt (hai i (sup_le_iff.mp hi).1) (hbi i (sup_le_iff.mp hi).2))β©,
end
lemma inf_equiv_inf {aβ bβ aβ bβ : cau_seq Ξ± abs} (ha : aβ β aβ) (hb : bβ β bβ) :
aβ β bβ β aβ β bβ :=
begin
intros Ξ΅ Ξ΅0,
obtain β¨ai, haiβ© := ha Ξ΅ Ξ΅0,
obtain β¨bi, hbiβ© := hb Ξ΅ Ξ΅0,
exact β¨ai β bi, Ξ» i hi,
(abs_min_sub_min_le_max (aβ i) (bβ i) (aβ i) (bβ i)).trans_lt
(max_lt (hai i (sup_le_iff.mp hi).1) (hbi i (sup_le_iff.mp hi).2))β©,
end
protected lemma sup_lt {a b c : cau_seq Ξ± abs} (ha : a < c) (hb : b < c) : a β b < c :=
begin
obtain β¨β¨Ξ΅a, Ξ΅a0, ia, haβ©, β¨Ξ΅b, Ξ΅b0, ib, hbβ©β© := β¨ha, hbβ©,
refine β¨Ξ΅a β Ξ΅b, lt_inf_iff.mpr β¨Ξ΅a0, Ξ΅b0β©, ia β ib, Ξ» i hi, _β©,
have := min_le_min (ha _ (sup_le_iff.mp hi).1) (hb _ (sup_le_iff.mp hi).2),
exact this.trans_eq (min_sub_sub_left _ _ _)
end
protected lemma lt_inf {a b c : cau_seq Ξ± abs} (hb : a < b) (hc : a < c) : a < b β c :=
begin
obtain β¨β¨Ξ΅b, Ξ΅b0, ib, hbβ©, β¨Ξ΅c, Ξ΅c0, ic, hcβ©β© := β¨hb, hcβ©,
refine β¨Ξ΅b β Ξ΅c, lt_inf_iff.mpr β¨Ξ΅b0, Ξ΅c0β©, ib β ic, Ξ» i hi, _β©,
have := min_le_min (hb _ (sup_le_iff.mp hi).1) (hc _ (sup_le_iff.mp hi).2),
exact this.trans_eq (min_sub_sub_right _ _ _),
end
@[simp] protected lemma sup_idem (a : cau_seq Ξ± abs) : a β a = a := subtype.ext sup_idem
@[simp] protected lemma inf_idem (a : cau_seq Ξ± abs) : a β a = a := subtype.ext inf_idem
protected lemma sup_comm (a b : cau_seq Ξ± abs) : a β b = b β a := subtype.ext sup_comm
protected lemma inf_comm (a b : cau_seq Ξ± abs) : a β b = b β a := subtype.ext inf_comm
protected lemma sup_eq_right {a b : cau_seq Ξ± abs} (h : a β€ b) :
a β b β b :=
begin
obtain β¨Ξ΅, Ξ΅0 : _ < _, i, hβ© | h := h,
{ intros _ _,
refine β¨i, Ξ» j hj, _β©,
dsimp,
erw βmax_sub_sub_right,
rwa [sub_self, max_eq_right, abs_zero],
rw [sub_nonpos, βsub_nonneg],
exact Ξ΅0.le.trans (h _ hj) },
{ refine setoid.trans (sup_equiv_sup h (setoid.refl _)) _,
rw cau_seq.sup_idem,
exact setoid.refl _ },
end
protected lemma inf_eq_right {a b : cau_seq Ξ± abs} (h : b β€ a) :
a β b β b :=
begin
obtain β¨Ξ΅, Ξ΅0 : _ < _, i, hβ© | h := h,
{ intros _ _,
refine β¨i, Ξ» j hj, _β©,
dsimp,
erw βmin_sub_sub_right,
rwa [sub_self, min_eq_right, abs_zero],
exact Ξ΅0.le.trans (h _ hj) },
{ refine setoid.trans (inf_equiv_inf (setoid.symm h) (setoid.refl _)) _,
rw cau_seq.inf_idem,
exact setoid.refl _ },
end
protected lemma sup_eq_left {a b : cau_seq Ξ± abs} (h : b β€ a) :
a β b β a :=
by simpa only [cau_seq.sup_comm] using cau_seq.sup_eq_right h
protected lemma inf_eq_left {a b : cau_seq Ξ± abs} (h : a β€ b) :
a β b β a :=
by simpa only [cau_seq.inf_comm] using cau_seq.inf_eq_right h
protected lemma sup_le {a b c : cau_seq Ξ± abs} (ha : a β€ c) (hb : b β€ c) : a β b β€ c :=
begin
cases ha with ha ha,
{ cases hb with hb hb,
{ exact or.inl (cau_seq.sup_lt ha hb) },
{ replace ha := le_of_le_of_eq ha.le (setoid.symm hb),
refine le_of_le_of_eq (or.inr _) hb,
exact cau_seq.sup_eq_right ha }, },
{ replace hb := le_of_le_of_eq hb (setoid.symm ha),
refine le_of_le_of_eq (or.inr _) ha,
exact cau_seq.sup_eq_left hb }
end
protected lemma le_inf {a b c : cau_seq Ξ± abs} (hb : a β€ b) (hc : a β€ c) : a β€ b β c :=
begin
cases hb with hb hb,
{ cases hc with hc hc,
{ exact or.inl (cau_seq.lt_inf hb hc) },
{ replace hb := le_of_eq_of_le (setoid.symm hc) hb.le,
refine le_of_eq_of_le hc (or.inr _),
exact setoid.symm (cau_seq.inf_eq_right hb) }, },
{ replace hc := le_of_eq_of_le (setoid.symm hb) hc,
refine le_of_eq_of_le hb (or.inr _),
exact setoid.symm (cau_seq.inf_eq_left hc) }
end
/-! Note that `distrib_lattice (cau_seq Ξ± abs)` is not true because there is no `partial_order`. -/
end abs
end cau_seq
|
c53845c03fb876973470d58a58994025e84f8778 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/analysis/normed/group/quotient.lean | 856999c847c2c52507c0cce970becc70a252593b | [
"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 | 21,869 | lean | /-
Copyright (c) 2021 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Riccardo Brasca
-/
import analysis.normed.group.hom
/-!
# Quotients of seminormed groups
For any `semi_normed_group M` and any `S : add_subgroup M`, we provide a `semi_normed_group`
the group quotient `M β§Έ S`.
If `S` is closed, we provide `normed_group (M β§Έ S)` (regardless of whether `M` itself is
separated). The two main properties of these structures are the underlying topology is the quotient
topology and the projection is a normed group homomorphism which is norm non-increasing
(better, it has operator norm exactly one unless `S` is dense in `M`). The corresponding
universal property is that every normed group hom defined on `M` which vanishes on `S` descends
to a normed group hom defined on `M β§Έ S`.
This file also introduces a predicate `is_quotient` characterizing normed group homs that
are isomorphic to the canonical projection onto a normed group quotient.
## Main definitions
We use `M` and `N` to denote seminormed groups and `S : add_subgroup M`.
All the following definitions are in the `add_subgroup` namespace. Hence we can access
`add_subgroup.normed_mk S` as `S.normed_mk`.
* `semi_normed_group_quotient` : The seminormed group structure on the quotient by
an additive subgroup. This is an instance so there is no need to explictly use it.
* `normed_group_quotient` : The normed group structure on the quotient by
a closed additive subgroup. This is an instance so there is no need to explictly use it.
* `normed_mk S` : the normed group hom from `M` to `M β§Έ S`.
* `lift S f hf`: implements the universal property of `M β§Έ S`. Here
`(f : normed_group_hom M N)`, `(hf : β s β S, f s = 0)` and
`lift S f hf : normed_group_hom (M β§Έ S) N`.
* `is_quotient`: given `f : normed_group_hom M N`, `is_quotient f` means `N` is isomorphic
to a quotient of `M` by a subgroup, with projection `f`. Technically it asserts `f` is
surjective and the norm of `f x` is the infimum of the norms of `x + m` for `m` in `f.ker`.
## Main results
* `norm_normed_mk` : the operator norm of the projection is `1` if the subspace is not dense.
* `is_quotient.norm_lift`: Provided `f : normed_hom M N` satisfies `is_quotient f`, for every
`n : N` and positive `Ξ΅`, there exists `m` such that `f m = n β§ β₯mβ₯ < β₯nβ₯ + Ξ΅`.
## Implementation details
For any `semi_normed_group M` and any `S : add_subgroup M` we define a norm on `M β§Έ S` by
`β₯xβ₯ = Inf (norm '' {m | mk' S m = x})`. This formula is really an implementation detail, it
shouldn't be needed outside of this file setting up the theory.
Since `M β§Έ S` is automatically a topological space (as any quotient of a topological space),
one needs to be careful while defining the `semi_normed_group` instance to avoid having two
different topologies on this quotient. This is not purely a technological issue.
Mathematically there is something to prove. The main point is proved in the auxiliary lemma
`quotient_nhd_basis` that has no use beyond this verification and states that zero in the quotient
admits as basis of neighborhoods in the quotient topology the sets `{x | β₯xβ₯ < Ξ΅}` for positive `Ξ΅`.
Once this mathematical point it settled, we have two topologies that are propositionaly equal. This
is not good enough for the type class system. As usual we ensure *definitional* equality
using forgetful inheritance, see Note [forgetful inheritance]. A (semi)-normed group structure
includes a uniform space structure which includes a topological space structure, together
with propositional fields asserting compatibility conditions.
The usual way to define a `semi_normed_group` is to let Lean build a uniform space structure
using the provided norm, and then trivially build a proof that the norm and uniform structure are
compatible. Here the uniform structure is provided using `topological_add_group.to_uniform_space`
which uses the topological structure and the group structure to build the uniform structure. This
uniform structure induces the correct topological structure by construction, but the fact that it
is compatible with the norm is not obvious; this is where the mathematical content explained in
the previous paragraph kicks in.
-/
noncomputable theory
open quotient_add_group metric set
open_locale topological_space nnreal
variables {M N : Type*} [semi_normed_group M] [semi_normed_group N]
/-- The definition of the norm on the quotient by an additive subgroup. -/
noncomputable
instance norm_on_quotient (S : add_subgroup M) : has_norm (M β§Έ S) :=
{ norm := Ξ» x, Inf (norm '' {m | mk' S m = x}) }
lemma image_norm_nonempty {S : add_subgroup M} :
β x : M β§Έ S, (norm '' {m | mk' S m = x}).nonempty :=
begin
rintro β¨mβ©,
rw set.nonempty_image_iff,
use m,
change mk' S m = _,
refl
end
lemma bdd_below_image_norm (s : set M) : bdd_below (norm '' s) :=
begin
use 0,
rintro _ β¨x, hx, rflβ©,
apply norm_nonneg
end
/-- The norm on the quotient satisfies `β₯-xβ₯ = β₯xβ₯`. -/
lemma quotient_norm_neg {S : add_subgroup M} (x : M β§Έ S) : β₯-xβ₯ = β₯xβ₯ :=
begin
suffices : norm '' {m | mk' S m = x} = norm '' {m | mk' S m = -x},
by simp only [this, norm],
ext r,
split,
{ rintros β¨m, hm : mk' S m = x, rflβ©,
subst hm,
rw β norm_neg,
exact β¨-m, by simp only [(mk' S).map_neg, set.mem_set_of_eq], rflβ© },
{ rintros β¨m, hm : mk' S m = -x, rflβ©,
use -m,
simp at hm,
simp [hm], }
end
lemma quotient_norm_sub_rev {S : add_subgroup M} (x y : M β§Έ S) : β₯x - yβ₯ = β₯y - xβ₯ :=
by rw [show x - y = -(y - x), by abel, quotient_norm_neg]
/-- The norm of the projection is smaller or equal to the norm of the original element. -/
lemma quotient_norm_mk_le (S : add_subgroup M) (m : M) :
β₯mk' S mβ₯ β€ β₯mβ₯ :=
begin
apply cInf_le,
use 0,
{ rintros _ β¨n, h, rflβ©,
apply norm_nonneg },
{ apply set.mem_image_of_mem,
rw set.mem_set_of_eq }
end
/-- The norm of the projection is smaller or equal to the norm of the original element. -/
lemma quotient_norm_mk_le' (S : add_subgroup M) (m : M) :
β₯(m : M β§Έ S)β₯ β€ β₯mβ₯ := quotient_norm_mk_le S m
/-- The norm of the image under the natural morphism to the quotient. -/
lemma quotient_norm_mk_eq (S : add_subgroup M) (m : M) :
β₯mk' S mβ₯ = Inf ((Ξ» x, β₯m + xβ₯) '' S) :=
begin
change Inf _ = _,
congr' 1,
ext r,
simp_rw [coe_mk', eq_iff_sub_mem],
split,
{ rintros β¨y, h, rflβ©,
use [y - m, h],
simp },
{ rintros β¨y, h, rflβ©,
use m + y,
simpa using h },
end
/-- The quotient norm is nonnegative. -/
lemma quotient_norm_nonneg (S : add_subgroup M) : β x : M β§Έ S, 0 β€ β₯xβ₯ :=
begin
rintros β¨mβ©,
change 0 β€ β₯mk' S mβ₯,
apply le_cInf (image_norm_nonempty _),
rintros _ β¨n, h, rflβ©,
apply norm_nonneg
end
/-- The quotient norm is nonnegative. -/
lemma norm_mk_nonneg (S : add_subgroup M) (m : M) : 0 β€ β₯mk' S mβ₯ :=
quotient_norm_nonneg S _
/-- The norm of the image of `m : M` in the quotient by `S` is zero if and only if `m` belongs
to the closure of `S`. -/
lemma quotient_norm_eq_zero_iff (S : add_subgroup M) (m : M) :
β₯mk' S mβ₯ = 0 β m β closure (S : set M) :=
begin
have : 0 β€ β₯mk' S mβ₯ := norm_mk_nonneg S m,
rw [β this.le_iff_eq, quotient_norm_mk_eq, real.Inf_le_iff],
simp_rw [zero_add],
{ calc (β Ξ΅ > (0 : β), β r β (Ξ» x, β₯m + xβ₯) '' (S : set M), r < Ξ΅) β
(β Ξ΅ > 0, (β x β S, β₯m + xβ₯ < Ξ΅)) : by simp [set.bex_image_iff]
... β β Ξ΅ > 0, (β x β S, β₯m + -xβ₯ < Ξ΅) : _
... β β Ξ΅ > 0, (β x β S, x β metric.ball m Ξ΅) : by simp [dist_eq_norm, β sub_eq_add_neg,
norm_sub_rev]
... β m β closure βS : by simp [metric.mem_closure_iff, dist_comm],
refine forallβ_congr (Ξ» Ξ΅ Ξ΅_pos, _),
rw [β S.exists_neg_mem_iff_exists_mem],
simp },
{ use 0,
rintro _ β¨x, x_in, rflβ©,
apply norm_nonneg },
rw set.nonempty_image_iff,
use [0, S.zero_mem]
end
/-- For any `x : M β§Έ S` and any `0 < Ξ΅`, there is `m : M` such that `mk' S m = x`
and `β₯mβ₯ < β₯xβ₯ + Ξ΅`. -/
lemma norm_mk_lt {S : add_subgroup M} (x : M β§Έ S) {Ξ΅ : β} (hΞ΅ : 0 < Ξ΅) :
β (m : M), mk' S m = x β§ β₯mβ₯ < β₯xβ₯ + Ξ΅ :=
begin
obtain β¨_, β¨m : M, H : mk' S m = x, rflβ©, hnorm : β₯mβ₯ < β₯xβ₯ + Ξ΅β© :=
real.lt_Inf_add_pos (image_norm_nonempty x) hΞ΅,
subst H,
exact β¨m, rfl, hnormβ©,
end
/-- For any `m : M` and any `0 < Ξ΅`, there is `s β S` such that `β₯m + sβ₯ < β₯mk' S mβ₯ + Ξ΅`. -/
lemma norm_mk_lt' (S : add_subgroup M) (m : M) {Ξ΅ : β} (hΞ΅ : 0 < Ξ΅) :
β s β S, β₯m + sβ₯ < β₯mk' S mβ₯ + Ξ΅ :=
begin
obtain β¨n : M, hn : mk' S n = mk' S m, hn' : β₯nβ₯ < β₯mk' S mβ₯ + Ξ΅β© :=
norm_mk_lt (quotient_add_group.mk' S m) hΞ΅,
erw [eq_comm, quotient_add_group.eq] at hn,
use [- m + n, hn],
rwa [add_neg_cancel_left]
end
/-- The quotient norm satisfies the triangle inequality. -/
lemma quotient_norm_add_le (S : add_subgroup M) (x y : M β§Έ S) : β₯x + yβ₯ β€ β₯xβ₯ + β₯yβ₯ :=
begin
refine le_of_forall_pos_le_add (Ξ» Ξ΅ hΞ΅, _),
replace hΞ΅ := half_pos hΞ΅,
obtain β¨m, rfl, hm : β₯mβ₯ < β₯mk' S mβ₯ + Ξ΅ / 2β© := norm_mk_lt x hΞ΅,
obtain β¨n, rfl, hn : β₯nβ₯ < β₯mk' S nβ₯ + Ξ΅ / 2β© := norm_mk_lt y hΞ΅,
calc β₯mk' S m + mk' S nβ₯ = β₯mk' S (m + n)β₯ : by rw (mk' S).map_add
... β€ β₯m + nβ₯ : quotient_norm_mk_le S (m + n)
... β€ β₯mβ₯ + β₯nβ₯ : norm_add_le _ _
... β€ β₯mk' S mβ₯ + β₯mk' S nβ₯ + Ξ΅ : by linarith
end
/-- The quotient norm of `0` is `0`. -/
lemma norm_mk_zero (S : add_subgroup M) : β₯(0 : M β§Έ S)β₯ = 0 :=
begin
erw quotient_norm_eq_zero_iff,
exact subset_closure S.zero_mem
end
/-- If `(m : M)` has norm equal to `0` in `M β§Έ S` for a closed subgroup `S` of `M`, then
`m β S`. -/
lemma norm_zero_eq_zero (S : add_subgroup M) (hS : is_closed (S : set M)) (m : M)
(h : β₯mk' S mβ₯ = 0) : m β S :=
by rwa [quotient_norm_eq_zero_iff, hS.closure_eq] at h
lemma quotient_nhd_basis (S : add_subgroup M) :
(π (0 : M β§Έ S)).has_basis (Ξ» Ξ΅ : β, 0 < Ξ΅) (Ξ» Ξ΅, {x | β₯xβ₯ < Ξ΅}) :=
β¨begin
intros U,
split,
{ intros U_in,
rw β (mk' S).map_zero at U_in,
have := preimage_nhds_coinduced U_in,
rcases metric.mem_nhds_iff.mp this with β¨Ξ΅, Ξ΅_pos, Hβ©,
use [Ξ΅/2, half_pos Ξ΅_pos],
intros x x_in,
dsimp at x_in,
rcases norm_mk_lt x (half_pos Ξ΅_pos) with β¨y, rfl, ryβ©,
apply H,
rw ball_zero_eq,
dsimp,
linarith },
{ rintros β¨Ξ΅, Ξ΅_pos, hβ©,
have : (mk' S) '' (ball (0 : M) Ξ΅) β {x | β₯xβ₯ < Ξ΅},
{ rintros - β¨x, x_in, rflβ©,
rw mem_ball_zero_iff at x_in,
exact lt_of_le_of_lt (quotient_norm_mk_le S x) x_in },
apply filter.mem_of_superset _ (set.subset.trans this h),
clear h U this,
apply is_open.mem_nhds,
{ change is_open ((mk' S) β»ΒΉ' _),
erw quotient_add_group.preimage_image_coe,
apply is_open_Union,
rintros β¨s, s_inβ©,
exact (continuous_add_right s).is_open_preimage _ is_open_ball },
{ exact β¨(0 : M), mem_ball_self Ξ΅_pos, (mk' S).map_zeroβ© } },
endβ©
/-- The seminormed group structure on the quotient by an additive subgroup. -/
noncomputable
instance add_subgroup.semi_normed_group_quotient (S : add_subgroup M) :
semi_normed_group (M β§Έ S) :=
{ dist := Ξ» x y, β₯x - yβ₯,
dist_self := Ξ» x, by simp only [norm_mk_zero, sub_self],
dist_comm := quotient_norm_sub_rev,
dist_triangle := Ξ» x y z,
begin
unfold dist,
have : x - z = (x - y) + (y - z) := by abel,
rw this,
exact quotient_norm_add_le S (x - y) (y - z)
end,
dist_eq := Ξ» x y, rfl,
to_uniform_space := topological_add_group.to_uniform_space (M β§Έ S),
uniformity_dist :=
begin
rw uniformity_eq_comap_nhds_zero',
have := (quotient_nhd_basis S).comap (Ξ» (p : (M β§Έ S) Γ M β§Έ S), p.2 - p.1),
apply this.eq_of_same_basis,
have : β Ξ΅ : β, (Ξ» (p : (M β§Έ S) Γ M β§Έ S), p.snd - p.fst) β»ΒΉ' {x | β₯xβ₯ < Ξ΅} =
{p : (M β§Έ S) Γ M β§Έ S | β₯p.fst - p.sndβ₯ < Ξ΅},
{ intro Ξ΅,
ext x,
dsimp,
rw quotient_norm_sub_rev },
rw funext this,
refine filter.has_basis_binfi_principal _ set.nonempty_Ioi,
rintros Ξ΅ (Ξ΅_pos : 0 < Ξ΅) Ξ· (Ξ·_pos : 0 < Ξ·),
refine β¨min Ξ΅ Ξ·, lt_min Ξ΅_pos Ξ·_pos, _, _β©,
{ suffices : β (a b : M β§Έ S), β₯a - bβ₯ < Ξ΅ β β₯a - bβ₯ < Ξ· β β₯a - bβ₯ < Ξ΅, by simpa,
exact Ξ» a b h h', h },
{ simp }
end }
-- This is a sanity check left here on purpose to ensure that potential refactors won't destroy
-- this important property.
example (S : add_subgroup M) : (quotient.topological_space : topological_space $ M β§Έ S) =
S.semi_normed_group_quotient.to_uniform_space.to_topological_space :=
rfl
/-- The quotient in the category of normed groups. -/
noncomputable
instance add_subgroup.normed_group_quotient (S : add_subgroup M) [hS : is_closed (S : set M)] :
normed_group (M β§Έ S) :=
{ eq_of_dist_eq_zero :=
begin
rintros β¨mβ© β¨m'β© (h : β₯mk' S m - mk' S m'β₯ = 0),
erw [β (mk' S).map_sub, quotient_norm_eq_zero_iff, hS.closure_eq,
β quotient_add_group.eq_iff_sub_mem] at h,
exact h
end,
.. add_subgroup.semi_normed_group_quotient S }
-- This is a sanity check left here on purpose to ensure that potential refactors won't destroy
-- this important property.
example (S : add_subgroup M) [is_closed (S : set M)] :
S.semi_normed_group_quotient = normed_group.to_semi_normed_group := rfl
namespace add_subgroup
open normed_group_hom
/-- The morphism from a seminormed group to the quotient by a subgroup. -/
noncomputable
def normed_mk (S : add_subgroup M) : normed_group_hom M (M β§Έ S) :=
{ bound' := β¨1, Ξ» m, by simpa [one_mul] using quotient_norm_mk_le _ mβ©,
.. quotient_add_group.mk' S }
/-- `S.normed_mk` agrees with `quotient_add_group.mk' S`. -/
@[simp]
lemma normed_mk.apply (S : add_subgroup M) (m : M) : normed_mk S m = quotient_add_group.mk' S m :=
rfl
/-- `S.normed_mk` is surjective. -/
lemma surjective_normed_mk (S : add_subgroup M) : function.surjective (normed_mk S) :=
surjective_quot_mk _
/-- The kernel of `S.normed_mk` is `S`. -/
lemma ker_normed_mk (S : add_subgroup M) : S.normed_mk.ker = S :=
quotient_add_group.ker_mk _
/-- The operator norm of the projection is at most `1`. -/
lemma norm_normed_mk_le (S : add_subgroup M) : β₯S.normed_mkβ₯ β€ 1 :=
normed_group_hom.op_norm_le_bound _ zero_le_one (Ξ» m, by simp [quotient_norm_mk_le'])
/-- The operator norm of the projection is `1` if the subspace is not dense. -/
lemma norm_normed_mk (S : add_subgroup M) (h : (S.topological_closure : set M) β univ) :
β₯S.normed_mkβ₯ = 1 :=
begin
obtain β¨x, hxβ© := set.nonempty_compl.2 h,
let y := S.normed_mk x,
have hy : β₯yβ₯ β 0,
{ intro h0,
exact set.not_mem_of_mem_compl hx ((quotient_norm_eq_zero_iff S x).1 h0) },
refine le_antisymm (norm_normed_mk_le S) (le_of_forall_pos_le_add (Ξ» Ξ΅ hΞ΅, _)),
suffices : 1 β€ β₯S.normed_mkβ₯ + min Ξ΅ ((1 : β)/2),
{ exact le_add_of_le_add_left this (min_le_left Ξ΅ ((1 : β)/2)) },
have hΞ΄ := sub_pos.mpr (lt_of_le_of_lt (min_le_right Ξ΅ ((1 : β)/2)) one_half_lt_one),
have hΞ΄pos : 0 < min Ξ΅ ((1 : β)/2) := lt_min hΞ΅ one_half_pos,
have hΞ΄norm := mul_pos (div_pos hΞ΄pos hΞ΄) (lt_of_le_of_ne (norm_nonneg y) hy.symm),
obtain β¨m, hm, hltβ© := norm_mk_lt y hΞ΄norm,
have hrw : β₯yβ₯ + min Ξ΅ (1 / 2) / (1 - min Ξ΅ (1 / 2)) * β₯yβ₯ =
β₯yβ₯ * (1 + min Ξ΅ (1 / 2) / (1 - min Ξ΅ (1 / 2))) := by ring,
rw [hrw] at hlt,
have hm0 : β₯mβ₯ β 0,
{ intro h0,
have hnorm := quotient_norm_mk_le S m,
rw [h0, hm] at hnorm,
replace hnorm := le_antisymm hnorm (norm_nonneg _),
simpa [hnorm] using hy },
replace hlt := (div_lt_div_right (lt_of_le_of_ne (norm_nonneg m) hm0.symm)).2 hlt,
simp only [hm0, div_self, ne.def, not_false_iff] at hlt,
have hrwβ : β₯yβ₯ * (1 + min Ξ΅ (1 / 2) / (1 - min Ξ΅ (1 / 2))) / β₯mβ₯ =
(β₯yβ₯ / β₯mβ₯) * (1 + min Ξ΅ (1 / 2) / (1 - min Ξ΅ (1 / 2))) := by ring,
rw [hrwβ] at hlt,
replace hlt := (inv_pos_lt_iff_one_lt_mul (lt_trans (div_pos hΞ΄pos hΞ΄) (lt_one_add _))).2 hlt,
suffices : β₯S.normed_mkβ₯ β₯ 1 - min Ξ΅ (1 / 2),
{ exact sub_le_iff_le_add.mp this },
calc β₯S.normed_mkβ₯ β₯ β₯(S.normed_mk) mβ₯ / β₯mβ₯ : ratio_le_op_norm S.normed_mk m
... = β₯yβ₯ / β₯mβ₯ : by rw [normed_mk.apply, hm]
... β₯ (1 + min Ξ΅ (1 / 2) / (1 - min Ξ΅ (1 / 2)))β»ΒΉ : le_of_lt hlt
... = 1 - min Ξ΅ (1 / 2) : by field_simp [(ne_of_lt hΞ΄).symm]
end
/-- The operator norm of the projection is `0` if the subspace is dense. -/
lemma norm_trivial_quotient_mk (S : add_subgroup M)
(h : (S.topological_closure : set M) = set.univ) : β₯S.normed_mkβ₯ = 0 :=
begin
refine le_antisymm (op_norm_le_bound _ le_rfl (Ξ» x, _)) (norm_nonneg _),
have hker : x β (S.normed_mk).ker.topological_closure,
{ rw [S.ker_normed_mk],
exact set.mem_of_eq_of_mem h trivial },
rw [ker_normed_mk] at hker,
simp only [(quotient_norm_eq_zero_iff S x).mpr hker, normed_mk.apply, zero_mul],
end
end add_subgroup
namespace normed_group_hom
/-- `is_quotient f`, for `f : M βΆ N` means that `N` is isomorphic to the quotient of `M`
by the kernel of `f`. -/
structure is_quotient (f : normed_group_hom M N) : Prop :=
(surjective : function.surjective f)
(norm : β x, β₯f xβ₯ = Inf ((Ξ» m, β₯x + mβ₯) '' f.ker))
/-- Given `f : normed_group_hom M N` such that `f s = 0` for all `s β S`, where,
`S : add_subgroup M` is closed, the induced morphism `normed_group_hom (M β§Έ S) N`. -/
noncomputable
def lift {N : Type*} [semi_normed_group N] (S : add_subgroup M)
(f : normed_group_hom M N) (hf : β s β S, f s = 0) :
normed_group_hom (M β§Έ S) N :=
{ bound' :=
begin
obtain β¨c : β, hcpos : (0 : β) < c, hc : β x, β₯f xβ₯ β€ c * β₯xβ₯β© := f.bound,
refine β¨c, Ξ» mbar, le_of_forall_pos_le_add (Ξ» Ξ΅ hΞ΅, _)β©,
obtain β¨m : M, rfl : mk' S m = mbar, hmnorm : β₯mβ₯ < β₯mk' S mβ₯ + Ξ΅/cβ© :=
norm_mk_lt mbar (div_pos hΞ΅ hcpos),
calc β₯f mβ₯ β€ c * β₯mβ₯ : hc m
... β€ c*(β₯mk' S mβ₯ + Ξ΅/c) : ((mul_lt_mul_left hcpos).mpr hmnorm).le
... = c * β₯mk' S mβ₯ + Ξ΅ : by rw [mul_add, mul_div_cancel' _ hcpos.ne.symm]
end,
.. quotient_add_group.lift S f.to_add_monoid_hom hf }
lemma lift_mk {N : Type*} [semi_normed_group N] (S : add_subgroup M)
(f : normed_group_hom M N) (hf : β s β S, f s = 0) (m : M) :
lift S f hf (S.normed_mk m) = f m := rfl
lemma lift_unique {N : Type*} [semi_normed_group N] (S : add_subgroup M)
(f : normed_group_hom M N) (hf : β s β S, f s = 0)
(g : normed_group_hom (M β§Έ S) N) :
g.comp (S.normed_mk) = f β g = lift S f hf :=
begin
intro h,
ext,
rcases add_subgroup.surjective_normed_mk _ x with β¨x,rflβ©,
change (g.comp (S.normed_mk) x) = _,
simpa only [h]
end
/-- `S.normed_mk` satisfies `is_quotient`. -/
lemma is_quotient_quotient (S : add_subgroup M) : is_quotient (S.normed_mk) :=
β¨S.surjective_normed_mk, Ξ» m, by simpa [S.ker_normed_mk] using quotient_norm_mk_eq _ mβ©
lemma is_quotient.norm_lift {f : normed_group_hom M N} (hquot : is_quotient f) {Ξ΅ : β} (hΞ΅ : 0 < Ξ΅)
(n : N) : β (m : M), f m = n β§ β₯mβ₯ < β₯nβ₯ + Ξ΅ :=
begin
obtain β¨m, rflβ© := hquot.surjective n,
have nonemp : ((Ξ» m', β₯m + m'β₯) '' f.ker).nonempty,
{ rw set.nonempty_image_iff,
exact β¨0, f.ker.zero_memβ© },
rcases real.lt_Inf_add_pos nonemp hΞ΅ with
β¨_, β¨β¨x, hx, rflβ©, H : β₯m + xβ₯ < Inf ((Ξ» (m' : M), β₯m + m'β₯) '' f.ker) + Ξ΅β©β©,
exact β¨m+x, by rw [f.map_add,(normed_group_hom.mem_ker f x).mp hx, add_zero],
by rwa hquot.normβ©,
end
lemma is_quotient.norm_le {f : normed_group_hom M N} (hquot : is_quotient f) (m : M) :
β₯f mβ₯ β€ β₯mβ₯ :=
begin
rw hquot.norm,
apply cInf_le,
{ use 0,
rintros _ β¨m', hm', rflβ©,
apply norm_nonneg },
{ exact β¨0, f.ker.zero_mem, by simpβ© }
end
lemma lift_norm_le {N : Type*} [semi_normed_group N] (S : add_subgroup M)
(f : normed_group_hom M N) (hf : β s β S, f s = 0)
{c : ββ₯0} (fb : β₯fβ₯ β€ c) :
β₯lift S f hfβ₯ β€ c :=
begin
apply op_norm_le_bound _ c.coe_nonneg,
intros x,
by_cases hc : c = 0,
{ simp only [hc, nnreal.coe_zero, zero_mul] at fb β’,
obtain β¨x, rflβ© := surjective_quot_mk _ x,
show β₯f xβ₯ β€ 0,
calc β₯f xβ₯ β€ 0 * β₯xβ₯ : f.le_of_op_norm_le fb x
... = 0 : zero_mul _ },
{ replace hc : 0 < c := pos_iff_ne_zero.mpr hc,
apply le_of_forall_pos_le_add,
intros Ξ΅ hΞ΅,
have aux : 0 < (Ξ΅ / c) := div_pos hΞ΅ hc,
obtain β¨x, rfl, Hxβ© : β x', S.normed_mk x' = x β§ β₯x'β₯ < β₯xβ₯ + (Ξ΅ / c) :=
(is_quotient_quotient _).norm_lift aux _,
rw lift_mk,
calc β₯f xβ₯ β€ c * β₯xβ₯ : f.le_of_op_norm_le fb x
... β€ c * (β₯S.normed_mk xβ₯ + Ξ΅ / c) : (mul_le_mul_left _).mpr Hx.le
... = c * _ + Ξ΅ : _,
{ exact_mod_cast hc },
{ rw [mul_add, mul_div_cancel'], exact_mod_cast hc.ne' } },
end
lemma lift_norm_noninc {N : Type*} [semi_normed_group N] (S : add_subgroup M)
(f : normed_group_hom M N) (hf : β s β S, f s = 0)
(fb : f.norm_noninc) :
(lift S f hf).norm_noninc :=
Ξ» x,
begin
have fb' : β₯fβ₯ β€ (1 : ββ₯0) := norm_noninc.norm_noninc_iff_norm_le_one.mp fb,
simpa using le_of_op_norm_le _ (f.lift_norm_le _ _ fb') _,
end
end normed_group_hom
|
df3c71d6564ab23a3cc3c47a8b63e644a74cbddc | 69bc7d0780be17e452d542a93f9599488f1c0c8e | /10-17-2019.lean | fe073c377ee4974f6b5ea826f125cbb72169c06c | [] | no_license | joek13/cs2102-notes | b7352285b1d1184fae25594f89f5926d74e6d7b4 | 25bb18788641b20af9cf3c429afe1da9b2f5eafb | refs/heads/master | 1,673,461,162,867 | 1,575,561,090,000 | 1,575,561,090,000 | 207,573,549 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,675 | lean | -- Notes 10/17/2019
-- Most of the work for today is in ./prop_logic.lean ./prop_logic_test.lean
/- Notes on operator syntax
Prefix, infix, and postfix
Prefix: (+ 3 5)
Infix: 3 + 5
Postfix (3 5 +)
Functions are supplied in prefix notation
Infix is standard for arithmetic, etc.
Postfix -- accessor operator '.' , subscripting/indexing operator '[]'
Some terms that are relevant to boolean algebra:
- satisfiable -- whether an interpretation exists that makes this true
- unsatisfiable -- no interpretation exists that makes this true
- valid -- the value is true regardless of interpretation
Example:
X β§ Β¬X -- unsatisfiable
X β¨ Β¬X -- valid
x | y | (x β§ y) β¨ (Β¬y)
---+-----+---------------
tt | tt | t
tt | ff | t
ff | tt | f
ff | ff | t
There is one interpretation that makes the expression true, so it is satisfiable
... but it's not always true (under any interpretation), so it isn't valid
Boolean satisfiability problem: given a boolean expression, determine if at least one interpretation exists to make it true
... boolean satisfiability problems have O(2^n) worst-case time complexityβan NP-complete problem
Let's describe these terms in predicate logic
Unsatisfiable:
unsat e β Β¬ β (i: var β bool), pEval e i = tt -- "there does not exist an interpretation such that the expression evaluates to true"
sat e β Β¬ unsat e β β (i: var β bool), pEval e i = tt -- "there exists an interpretation such that the expression evaluates to true"
valid e β β (i: var β bool), pEval e i = tt -- "for every interpretation, the expression evaluates to true"
-/ |
c0c8d65c69c7d8ee35b93b0322187c249ca40a86 | 1d02a718c550dba762f0c3d2ad13d16a43649ca1 | /src/ast.lean | b7a15ffe7c6799b219141d456cb15e32ec3603c4 | [
"Apache-2.0"
] | permissive | mhuisi/rc-correctness | 48488dfbbe18e222399b0c5252d2803a9dd1be74 | 2b7878ac594ba285b0b5cdabe96f41c6e3bbcc87 | refs/heads/master | 1,590,988,773,033 | 1,585,334,858,000 | 1,585,334,858,000 | 190,653,803 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 4,089 | lean | import util
namespace rc_correctness
-- ast defs
def var := β
def const := β
def cnstr := β
inductive expr : Type
| const_app_full (c : const) (ys : list var) : expr
| const_app_part (c : const) (ys : list var) : expr
| var_app (x : var) (y : var) : expr
| ctor (i : cnstr) (ys : list var) : expr
| proj (i : cnstr) (x : var) : expr
inductive fn_body : Type
| ret (x : var) : fn_body
| Β«letΒ» (x : var) (e : expr) (F : fn_body) : fn_body
| case (x : var) (Fs : list fn_body) : fn_body
| inc (x : var) (F : fn_body) : fn_body
| dec (x : var) (F : fn_body) : fn_body
structure fn := (ys : list var) (F : fn_body)
def program := const β fn
inductive rc : Type
| expr (e : expr) : rc
| fn_body (F : fn_body) : rc
-- notation
open rc_correctness.expr
open rc_correctness.fn_body
-- expr
notation c `β¦` ys `β¦` `β§` := expr.const_app_full c ys
notation c `β¦` ys `β¦` `, ` `_` `β§` := expr.const_app_part c ys
notation x `β¦` y `β§` := expr.var_app x y
notation `βͺ` ys `β«` i := expr.ctor i ys
notation x `[` i `]` := expr.proj i x
-- fn_body
notation x ` β ` e `; `F := fn_body.let x e F
notation `case ` x ` of ` Fs := fn_body.case x Fs
notation `inc ` x `; ` F := fn_body.inc x F
notation `dec ` x `; ` F := fn_body.dec x F
-- rc
instance expr_to_rc : has_coe expr rc := β¨rc.exprβ©
instance fn_body_to_rc : has_coe fn_body rc := β¨rc.fn_bodyβ©
-- fn_body recursor, courtesy of Sebastian Ullrich
def {l} fn_body.rec_wf (C : fn_body β Sort l)
(Β«retΒ» : Ξ (x : var), C (ret x))
(Β«letΒ» : Ξ (x : var) (e : expr) (F : fn_body) (F_ih : C F), C (x β e; F))
(Β«caseΒ» : Ξ (x : var) (Fs : list fn_body) (Fs_ih : β F β Fs, C F), C (case x of Fs))
(Β«incΒ» : Ξ (x : var) (F : fn_body) (F_ih : C F), C (inc x; F))
(Β«decΒ» : Ξ (x : var) (F : fn_body) (F_ih : C F), C (dec x; F)) : Ξ (x : fn_body), C x
| (fn_body.ret x) := Β«retΒ» x
| (x β e; F) := Β«letΒ» x e F (fn_body.rec_wf F)
| (case x of Fs) := Β«caseΒ» x Fs (Ξ» F h,
have sizeof F < 1 + sizeof Fs,
from nat.lt_add_left _ _ _
(list.sizeof_lt_sizeof_of_mem h),
fn_body.rec_wf F)
| (inc x; F) := Β«incΒ» x F (fn_body.rec_wf F)
| (dec x; F) := Β«decΒ» x F (fn_body.rec_wf F)
-- free variables
def FV_expr : expr β finset var
| (cβ¦xsβ¦β§) := xs.to_finset
| (cβ¦xsβ¦, _β§) := xs.to_finset
| (xβ¦yβ§) := {x, y}
| (βͺxsβ«i) := xs.to_finset
| (x[i]) := {x}
def FV : fn_body β finset var
| (ret x) := {x}
| (x β e; F) := FV_expr e βͺ ((FV F).erase x)
| (case x of Fs) := insert x (finset.join (Fs.map_wf (Ξ» F h, FV F)))
| (inc x; F) := insert x (FV F)
| (dec x; F) := insert x (FV F)
-- var order
local attribute [reducible] var
abbreviation var_le : var β var β Prop := nat.le
instance var_le_is_trans : is_trans var var_le := β¨@nat.le_transβ©
instance var_le_is_antisymm : is_antisymm var var_le := β¨@nat.le_antisymmβ©
instance var_le_is_total : is_total var var_le := β¨@nat.le_totalβ©
local attribute [semireducible] var
-- repr
-- var
local attribute [reducible] var
instance var_has_repr : has_repr var := β¨reprβ©
local attribute [semireducible] var
-- const
local attribute [reducible] const
instance const_has_repr : has_repr const := β¨reprβ©
local attribute [semireducible] const
-- expr
def expr_repr : expr β string
| (cβ¦ysβ¦β§) := c.repr ++ "β¦" ++ ys.repr ++ "β¦β§"
| (cβ¦ysβ¦, _β§) := c.repr ++ "β¦" ++ ys.repr ++ "β¦, _β§"
| (xβ¦yβ§) := x.repr ++ "β¦" ++ y.repr ++ "β§"
| (βͺysβ«i) := "βͺ" ++ ys.repr ++ "β«" ++ i.repr
| (x[i]) := x.repr ++ "[" ++ i.repr ++ "]"
instance expr_has_repr : has_repr expr := β¨expr_reprβ©
-- fn_body
def fn_body_repr : fn_body β string
| (ret x) := "ret " ++ x.repr
| (x β e; F) := x.repr ++ " β " ++ repr e ++ "; " ++ fn_body_repr F
| (case x of Fs) := "case " ++ x.repr ++ " of " ++ (Fs.map_wf (Ξ» F h, fn_body_repr F)).repr
| (inc x; F) := "inc " ++ x.repr ++ "; " ++ fn_body_repr F
| (dec x; F) := "dec " ++ x.repr ++ "; " ++ fn_body_repr F
instance fn_body_has_repr : has_repr fn_body := β¨fn_body_reprβ©
end rc_correctness |
bd714b5fd0ff5e777051da2b740b599a400e81fb | 5883d9218e6f144e20eee6ca1dab8529fa1a97c0 | /src/aeq/equiv.lean | c40595670ddfdbe1b4eefaca84327d94f3f0e5a0 | [] | 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 | 3,757 | lean | /-
This file contains equivalence properties of `aeq`.
-/
import .map
namespace acie ------------------------------------------------------------------
namespace aeq ------------------------------------------------------------------
variables {V : Type} [decidable_eq V] -- Type of variable names
variables {vs : Type β Type} [vset vs V] -- Type of variable name sets
variables {X Y Z : vs V} -- Variable name sets
variables {R : X ΓΞ½ Y} {S : Y ΓΞ½ Z} -- Variable name set relations
variables {eX : exp X} {eY eYβ eYβ : exp Y} {eZ : exp Z} -- Expressions
-- Reflexivity
-- Paper: Proposition 2.1
@[refl]
protected
theorem refl (e : exp X) : e β‘Ξ±β¨vrel.id Xβ© e :=
begin
induction e with
/- var -/ X x
/- app -/ X f e rf re
/- lam -/ X a e r,
begin /- var -/
exact var (vrel.refl x)
end,
begin /- app -/
exact app rf re
end,
begin /- lam -/
exact lam (map.simple (Ξ» x y, vrel.update.of_id) r)
end
end
-- Symmetry
-- Paper: Proposition 2.2
@[symm]
protected
theorem symm : eX β‘Ξ±β¨Rβ© eY β eY β‘Ξ±β¨RΒ°β© eX :=
begin
intro H,
induction H with
/- var -/ X Y R x y x_R_y
/- app -/ X Y R fX eX fY eY af ae rf re
/- lam -/ X Y R a b eX eY ae r,
begin /- var -/
exact var (vrel.symm x_R_y)
end,
begin /- app -/
exact app rf re
end,
begin /- lam -/
exact lam (map.simple (Ξ» x y, vrel.update.of_inv) r)
end
end
-- Transitivity implementation
private
theorem trans.core (P : eYβ = eYβ) (aR : eX β‘Ξ±β¨Rβ© eYβ) (aS : eYβ β‘Ξ±β¨Sβ© eZ)
: eX β‘Ξ±β¨R β¨Ύ Sβ© eZ :=
begin
induction aR with
/- var -/ X Y R x yβ x_R_yβ
/- app -/ X Y R fX eX fYβ eYβ afXY aeXY rf re
/- lam -/ X Y R x yβ eX eYβ aXY r
generalizing Z S eYβ eZ P aS,
begin /- aR: var -/
cases aS with
/- var -/ Y Z S yβ z yβ_S_z
/- app -/ Y Z S fYβ eYβ fZ eZ afYZ aeYZ
/- lam -/ Y Z S yβ z eYβ eZ aYZ,
begin /- aS: var -/
injection P with yβ_eq_yβ _,
induction yβ_eq_yβ,
exact var (vrel.trans x_R_yβ yβ_S_z)
end,
begin /- aS: app -/
exact exp.no_confusion P
end,
begin /- aS: lam -/
exact exp.no_confusion P
end
end,
begin /- aR: app -/
cases aS with
/- var -/ Y Z S yβ z yβ_S_z
/- app -/ Y Z S fYβ eYβ fZ eZ afYZ aeYZ
/- lam -/ Y Z S yβ z eYβ eZ aYZ,
begin /- aS: var -/
exact exp.no_confusion P
end,
begin /- aS: app -/
injection P with fYβ_eq_fYβ eYβ_eq_eYβ,
exact app (rf fYβ_eq_fYβ afYZ) (re eYβ_eq_eYβ aeYZ)
end,
begin /- aS: lam -/
exact exp.no_confusion P
end
end,
begin /- aR: lam -/
cases aS with
/- var -/ Y Z S yβ z yβ_S_z
/- app -/ Y Z S fYβ eYβ fZ eZ afYZ aeYZ
/- lam -/ Y Z S yβ z eYβ eZ aYZ,
begin /- aS: var -/
exact exp.no_confusion P
end,
begin /- aS: app -/
exact exp.no_confusion P
end,
begin /- aS: lam -/
injection P with yβ_eq_yβ eYβ_heq_eYβ,
induction yβ_eq_yβ,
exact lam
(map.simple (Ξ» x z, vrel.update.of_comp)
(r (eq_of_heq eYβ_heq_eYβ) aYZ))
end
end
end
-- Transitivity
-- Paper: Proposition 2.3
@[trans]
protected
theorem trans : eX β‘Ξ±β¨Rβ© eY β eY β‘Ξ±β¨Sβ© eZ β eX β‘Ξ±β¨R β¨Ύ Sβ© eZ :=
trans.core (eq.refl eY)
end /- namespace -/ aeq --------------------------------------------------------
end /- namespace -/ acie -------------------------------------------------------
|
3ef6d3daacbd0ced95be1ba7a02611694998e65b | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/tactic/linarith/preprocessing.lean | c2296c93c274d8b0fb7ee4ffd7229161d8fe455c | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,225 | lean | /-
Copyright (c) 2020 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
-/
import tactic.linarith.datatypes
import tactic.zify
import tactic.cancel_denoms
/-!
# Linarith preprocessing
This file contains methods used to preprocess inputs to `linarith`.
In particular, `linarith` works over comparisons of the form `t R 0`, where `R β {<,β€,=}`.
It assumes that expressions in `t` have integer coefficients and that the type of `t` has
well-behaved subtraction.
## Implementation details
A `global_preprocessor` is a function `list expr β tactic(list expr)`. Users can add custom
preprocessing steps by adding them to the `linarith_config` object. `linarith.default_preprocessors`
is the main list, and generally none of these should be skipped unless you know what you're doing.
-/
open native tactic expr
namespace linarith
/-! ### Preprocessing -/
open tactic
set_option eqn_compiler.max_steps 50000
/--
If `prf` is a proof of `Β¬ e`, where `e` is a comparison,
`rem_neg prf e` flips the comparison in `e` and returns a proof.
For example, if `prf : Β¬ a < b`, ``rem_neg prf `(a < b)`` returns a proof of `a β₯ b`.
-/
meta def rem_neg (prf : expr) : expr β tactic expr
| `(_ β€ _) := mk_app ``lt_of_not_ge [prf]
| `(_ < _) := mk_app ``le_of_not_gt [prf]
| `(_ > _) := mk_app ``le_of_not_gt [prf]
| `(_ β₯ _) := mk_app ``lt_of_not_ge [prf]
| e := failed
private meta def rearr_comp_aux : expr β expr β tactic expr
| prf `(%%a β€ 0) := return prf
| prf `(%%a < 0) := return prf
| prf `(%%a = 0) := return prf
| prf `(%%a β₯ 0) := mk_app ``neg_nonpos_of_nonneg [prf]
| prf `(%%a > 0) := mk_app `neg_neg_of_pos [prf]
| prf `(0 β₯ %%a) := to_expr ``(id_rhs (%%a β€ 0) %%prf)
| prf `(0 > %%a) := to_expr ``(id_rhs (%%a < 0) %%prf)
| prf `(0 = %%a) := mk_app `eq.symm [prf]
| prf `(0 β€ %%a) := mk_app ``neg_nonpos_of_nonneg [prf]
| prf `(0 < %%a) := mk_app `neg_neg_of_pos [prf]
| prf `(%%a β€ %%b) := mk_app ``sub_nonpos_of_le [prf]
| prf `(%%a < %%b) := mk_app `sub_neg_of_lt [prf]
| prf `(%%a = %%b) := mk_app `sub_eq_zero_of_eq [prf]
| prf `(%%a > %%b) := mk_app `sub_neg_of_lt [prf]
| prf `(%%a β₯ %%b) := mk_app ``sub_nonpos_of_le [prf]
| prf `(Β¬ %%t) := do nprf β rem_neg prf t, tp β infer_type nprf, rearr_comp_aux nprf tp
| prf a := trace a >> fail "couldn't rearrange comp"
/--
`rearr_comp e` takes a proof `e` of an equality, inequality, or negation thereof,
and turns it into a proof of a comparison `_ R 0`, where `R β {=, β€, <}`.
-/
meta def rearr_comp (e : expr) : tactic expr :=
infer_type e >>= rearr_comp_aux e
/-- If `e` is of the form `((n : β) : β€)`, `is_nat_int_coe e` returns `n : β`. -/
meta def is_nat_int_coe : expr β option expr
| `(@coe β β€ %%_ %%n) := some n
| _ := none
/-- If `e : β`, returns a proof of `0 β€ (e : β€)`. -/
meta def mk_coe_nat_nonneg_prf (e : expr) : tactic expr :=
mk_app `int.coe_nat_nonneg [e]
/-- `get_nat_comps e` returns a list of all subexpressions of `e` of the form `((t : β) : β€)`. -/
meta def get_nat_comps : expr β list expr
| `(%%a + %%b) := (get_nat_comps a).append (get_nat_comps b)
| `(%%a * %%b) := (get_nat_comps a).append (get_nat_comps b)
| e := match is_nat_int_coe e with
| some e' := [e']
| none := []
end
/--
If `pf` is a proof of a strict inequality `(a : β€) < b`,
`mk_non_strict_int_pf_of_strict_int_pf pf` returns a proof of `a + 1 β€ b`,
and similarly if `pf` proves a negated weak inequality.
-/
meta def mk_non_strict_int_pf_of_strict_int_pf (pf : expr) : tactic expr :=
do tp β infer_type pf,
match tp with
| `(%%a < %%b) := to_expr ``(int.add_one_le_iff.mpr %%pf)
| `(%%a > %%b) := to_expr ``(int.add_one_le_iff.mpr %%pf)
| `(Β¬ %%a β€ %%b) := to_expr ``(int.add_one_le_iff.mpr (le_of_not_gt %%pf))
| `(Β¬ %%a β₯ %%b) := to_expr ``(int.add_one_le_iff.mpr (le_of_not_gt %%pf))
| _ := fail "mk_non_strict_int_pf_of_strict_int_pf failed: proof is not an inequality"
end
/--
`is_nat_prop tp` is true iff `tp` is an inequality or equality between natural numbers
or the negation thereof.
-/
meta def is_nat_prop : expr β bool
| `(@eq β %%_ _) := tt
| `(@has_le.le β %%_ _ _) := tt
| `(@has_lt.lt β %%_ _ _) := tt
| `(@ge β %%_ _ _) := tt
| `(@gt β %%_ _ _) := tt
| `(Β¬ %%p) := is_nat_prop p
| _ := ff
/--
`is_strict_int_prop tp` is true iff `tp` is a strict inequality between integers
or the negation of a weak inequality between integers.
-/
meta def is_strict_int_prop : expr β bool
| `(@has_lt.lt β€ %%_ _ _) := tt
| `(@gt β€ %%_ _ _) := tt
| `(Β¬ @has_le.le β€ %%_ _ _) := tt
| `(Β¬ @ge β€ %%_ _ _) := tt
| _ := ff
private meta def filter_comparisons_aux : expr β bool
| `(Β¬ %%p) := p.app_symbol_in [`has_lt.lt, `has_le.le, `gt, `ge]
| tp := tp.app_symbol_in [`has_lt.lt, `has_le.le, `gt, `ge, `eq]
/--
Removes any expressions that are not proofs of inequalities, equalities, or negations thereof.
-/
meta def filter_comparisons : preprocessor :=
{ name := "filter terms that are not proofs of comparisons",
transform := Ξ» h,
(do tp β infer_type h,
is_prop tp >>= guardb,
guardb (filter_comparisons_aux tp),
return [h])
<|> return [] }
/--
Replaces proofs of negations of comparisons with proofs of the reversed comparisons.
For example, a proof of `Β¬ a < b` will become a proof of `a β₯ b`.
-/
meta def remove_negations : preprocessor :=
{ name := "replace negations of comparisons",
transform := Ξ» h,
do tp β infer_type h,
match tp with
| `(Β¬ %%p) := singleton <$> rem_neg h p
| _ := return [h]
end }
/--
If `h` is an equality or inequality between natural numbers,
`nat_to_int` lifts this inequality to the integers.
It also adds the facts that the integers involved are nonnegative.
To avoid adding the same nonnegativity facts many times, it is a global preprocessor.
-/
meta def nat_to_int : global_preprocessor :=
{ name := "move nats to ints",
transform := Ξ» l,
do l β l.mmap (Ξ» h, infer_type h >>= guardb β is_nat_prop >> zify_proof [] h <|> return h),
nonnegs β l.mfoldl (Ξ» (es : expr_set) h, do
(a, b) β infer_type h >>= get_rel_sides,
return $ (es.insert_list (get_nat_comps a)).insert_list (get_nat_comps b)) mk_rb_set,
(++) l <$> nonnegs.to_list.mmap mk_coe_nat_nonneg_prf }
/-- `strengthen_strict_int h` turns a proof `h` of a strict integer inequality `t1 < t2`
into a proof of `t1 β€ t2 + 1`. -/
meta def strengthen_strict_int : preprocessor :=
{ name := "strengthen strict inequalities over int",
transform := Ξ» h,
do tp β infer_type h,
guardb (is_strict_int_prop tp) >> singleton <$> mk_non_strict_int_pf_of_strict_int_pf h
<|> return [h] }
/--
`mk_comp_with_zero h` takes a proof `h` of an equality, inequality, or negation thereof,
and turns it into a proof of a comparison `_ R 0`, where `R β {=, β€, <}`.
-/
meta def make_comp_with_zero : preprocessor :=
{ name := "make comparisons with zero",
transform := Ξ» e, singleton <$> rearr_comp e <|> return [] }
/--
`normalize_denominators_in_lhs h lhs` assumes that `h` is a proof of `lhs R 0`.
It creates a proof of `lhs' R 0`, where all numeric division in `lhs` has been cancelled.
-/
meta def normalize_denominators_in_lhs (h lhs : expr) : tactic expr :=
do (v, lhs') β cancel_factors.derive lhs,
if v = 1 then return h else do
(ih, h'') β mk_single_comp_zero_pf v h,
(_, nep, _) β infer_type h'' >>= rewrite_core lhs',
mk_eq_mp nep h''
/--
`cancel_denoms pf` assumes `pf` is a proof of `t R 0`. If `t` contains the division symbol `/`,
it tries to scale `t` to cancel out division by numerals.
-/
meta def cancel_denoms : preprocessor :=
{ name := "cancel denominators",
transform := Ξ» pf,
(do some (_, lhs) β parse_into_comp_and_expr <$> infer_type pf,
guardb $ lhs.contains_constant (= `has_div.div),
singleton <$> normalize_denominators_in_lhs pf lhs)
<|> return [pf] }
/--
`find_squares m e` collects all terms of the form `a ^ 2` and `a * a` that appear in `e`
and adds them to the set `m`.
A pair `(a, tt)` is added to `m` when `a^2` appears in `e`, and `(a, ff)` is added to `m`
when `a*a` appears in `e`. -/
meta def find_squares : rb_set (expr Γ bool) β expr β tactic (rb_set (expr Γ bool))
| s `(%%a ^ 2) := do s β find_squares s a, return (s.insert (a, tt))
| s e@`(%%e1 * %%e2) := if e1 = e2 then do s β find_squares s e1, return (s.insert (e1, ff)) else e.mfoldl find_squares s
| s e := e.mfoldl find_squares s
/--
`nlinarith_extras` is the preprocessor corresponding to the `nlinarith` tactic.
* For every term `t` such that `t^2` or `t*t` appears in the input, adds a proof of `t^2 β₯ 0`
or `t*t β₯ 0`.
* For every pair of comparisons `t1 R1 0` and `t2 R2 0`, adds a proof of `t1*t2 R 0`.
This preprocessor is typically run last, after all inputs have been canonized.
-/
meta def nlinarith_extras : global_preprocessor :=
{ name := "nonlinear arithmetic extras",
transform := Ξ» ls,
do s β ls.mfoldr (Ξ» h s', infer_type h >>= find_squares s') mk_rb_set,
new_es β s.mfold ([] : list expr) $ Ξ» β¨e, is_sqβ© new_es,
((do p β mk_app (if is_sq then ``sq_nonneg else ``mul_self_nonneg) [e],
return $ p::new_es) <|> return new_es),
new_es β make_comp_with_zero.globalize.transform new_es,
linarith_trace "nlinarith preprocessing found squares",
linarith_trace s,
linarith_trace_proofs "so we added proofs" new_es,
with_comps β (new_es ++ ls).mmap (Ξ» e, do
tp β infer_type e,
return $ (parse_into_comp_and_expr tp).elim (ineq.lt, e) (Ξ» β¨ine, _β©, (ine, e))),
products β with_comps.mmap_upper_triangle $ Ξ» β¨posa, aβ© β¨posb, bβ©,
some <$> match posa, posb with
| ineq.eq, _ := mk_app ``zero_mul_eq [a, b]
| _, ineq.eq := mk_app ``mul_zero_eq [a, b]
| ineq.lt, ineq.lt := mk_app ``mul_pos_of_neg_of_neg [a, b]
| ineq.lt, ineq.le := do a β mk_app ``le_of_lt [a], mk_app ``mul_nonneg_of_nonpos_of_nonpos [a, b]
| ineq.le, ineq.lt := do b β mk_app ``le_of_lt [b], mk_app ``mul_nonneg_of_nonpos_of_nonpos [a, b]
| ineq.le, ineq.le := mk_app ``mul_nonneg_of_nonpos_of_nonpos [a, b]
end <|> return none,
products β make_comp_with_zero.globalize.transform products.reduce_option,
return $ new_es ++ ls ++ products }
/--
`remove_ne_aux` case splits on any proof `h : a β b` in the input, turning it into `a < b β¨ a > b`.
This produces `2^n` branches when there are `n` such hypotheses in the input.
-/
meta def remove_ne_aux : list expr β tactic (list branch) :=
Ξ» hs,
(do e β hs.mfind (Ξ» e : expr, do e β infer_type e, guard $ e.is_ne.is_some),
[(_, ng1), (_, ng2)] β to_expr ``(or.elim (lt_or_gt_of_ne %%e)) >>= apply,
let do_goal : expr β tactic (list branch) := Ξ» g,
do set_goals [g],
h β intro1,
ls β remove_ne_aux $ hs.remove_all [e],
return $ ls.map (Ξ» b : branch, (b.1, h::b.2)) in
(++) <$> do_goal ng1 <*> do_goal ng2)
<|> do g β get_goal, return [(g, hs)]
/--
`remove_ne` case splits on any proof `h : a β b` in the input, turning it into `a < b β¨ a > b`,
by calling `linarith.remove_ne_aux`.
This produces `2^n` branches when there are `n` such hypotheses in the input.
-/
meta def remove_ne : global_branching_preprocessor :=
{ name := "remove_ne",
transform := remove_ne_aux }
/--
The default list of preprocessors, in the order they should typically run.
-/
meta def default_preprocessors : list global_branching_preprocessor :=
[filter_comparisons, remove_negations, nat_to_int, strengthen_strict_int,
make_comp_with_zero, cancel_denoms]
/--
`preprocess pps l` takes a list `l` of proofs of propositions.
It maps each preprocessor `pp β pps` over this list.
The preprocessors are run sequentially: each recieves the output of the previous one.
Note that a preprocessor may produce multiple or no expressions from each input expression,
so the size of the list may change.
-/
meta def preprocess (pps : list global_branching_preprocessor) (l : list expr) : tactic (list branch) :=
do g β get_goal,
pps.mfoldl (Ξ» ls pp,
list.join <$> (ls.mmap $ Ξ» b, set_goals [b.1] >> pp.process b.2))
[(g, l)]
end linarith
|
bdad18461f568c82460274959dadce8d5d777947 | 41ebf3cb010344adfa84907b3304db00e02db0a6 | /uexp/src/uexp/rules/mergeJoinFilter.lean | 2a90ff8f8f67c29b0cc4dd3f4dd0a1892ad2d545 | [
"BSD-2-Clause"
] | permissive | ReinierKoops/Cosette | e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb | eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29 | refs/heads/master | 1,686,483,953,198 | 1,624,293,498,000 | 1,624,293,498,000 | 378,997,885 | 0 | 0 | BSD-2-Clause | 1,624,293,485,000 | 1,624,293,484,000 | null | UTF-8 | Lean | false | false | 1,591 | lean | import ..sql
import ..tactics
import ..u_semiring
import ..extra_constants
import ..meta.ucongr
import ..meta.TDP
set_option profiler true
open Expr
open Proj
open Pred
open SQL
open tree
notation `int` := datatypes.int
variable integer_10: const datatypes.int
theorem rule:
forall ( Ξ scm_dept scm_emp: Schema) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp),
denoteSQL ((SELECT * FROM1 ((SELECT1 (combine (rightβ
rightβ
dept_deptno) (rightβ
leftβ
emp_ename)) FROM1 (product (table rel_emp) (table rel_dept)) WHERE (and (equal (uvariable (rightβ
leftβ
emp_deptno)) (uvariable (rightβ
rightβ
dept_deptno))) (equal (uvariable (rightβ
rightβ
dept_deptno)) (constantExpr integer_10))))) WHERE (equal (uvariable (rightβ
left)) (constantExpr integer_10))) :SQL Ξ _)
=
denoteSQL ((SELECT1 (combine (rightβ
rightβ
dept_deptno) (rightβ
leftβ
emp_ename)) FROM1 (product (table rel_emp) ((SELECT * FROM1 (table rel_dept) WHERE (equal (uvariable (rightβ
dept_deptno)) (constantExpr integer_10))))) WHERE (equal (uvariable (rightβ
leftβ
emp_deptno)) (uvariable (rightβ
rightβ
dept_deptno)))) :SQL Ξ _) :=
begin
intros,
unfold_all_denotations,
funext,
simp,
print_size,
TDP' ucongr,
end |
c2525d575d1569062a1f1fb3bdbc9bfc8d3595cf | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/category/Mon/filtered_colimits.lean | 8372540ebe6f1f33aaef0d382d3547a4f98d1216 | [
"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 | 14,290 | lean | /-
Copyright (c) 2021 Justus Springer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Justus Springer
-/
import algebra.category.Mon.basic
import category_theory.limits.concrete_category
import category_theory.limits.preserves.filtered
/-!
# The forgetful functor from (commutative) (additive) monoids preserves filtered colimits.
Forgetful functors from algebraic categories usually don't preserve colimits. However, they tend
to preserve _filtered_ colimits.
In this file, we start with a small filtered category `J` and a functor `F : J β₯€ Mon`.
We then construct a monoid structure on the colimit of `F β forget Mon` (in `Type`), thereby
showing that the forgetful functor `forget Mon` preserves filtered colimits. Similarly for `AddMon`,
`CommMon` and `AddCommMon`.
-/
universe v
noncomputable theory
open_locale classical
open category_theory
open category_theory.limits
open category_theory.is_filtered (renaming max β max') -- avoid name collision with `_root_.max`.
namespace Mon.filtered_colimits
section
-- We use parameters here, mainly so we can have the abbreviations `M` and `M.mk` below, without
-- passing around `F` all the time.
parameters {J : Type v} [small_category J] (F : J β₯€ Mon.{v})
/--
The colimit of `F β forget Mon` in the category of types.
In the following, we will construct a monoid structure on `M`.
-/
@[to_additive "The colimit of `F β forget AddMon` in the category of types.
In the following, we will construct an additive monoid structure on `M`."]
abbreviation M : Type v := types.quot (F β forget Mon)
/-- The canonical projection into the colimit, as a quotient type. -/
@[to_additive "The canonical projection into the colimit, as a quotient type."]
abbreviation M.mk : (Ξ£ j, F.obj j) β M := quot.mk (types.quot.rel (F β forget Mon))
@[to_additive]
lemma M.mk_eq (x y : Ξ£ j, F.obj j)
(h : β (k : J) (f : x.1 βΆ k) (g : y.1 βΆ k), F.map f x.2 = F.map g y.2) :
M.mk x = M.mk y :=
quot.eqv_gen_sound (types.filtered_colimit.eqv_gen_quot_rel_of_rel (F β forget Mon) x y h)
variables [is_filtered J]
/--
As `J` is nonempty, we can pick an arbitrary object `jβ : J`. We use this object to define the
"one" in the colimit as the equivalence class of `β¨jβ, 1 : F.obj jββ©`.
-/
@[to_additive "As `J` is nonempty, we can pick an arbitrary object `jβ : J`. We use this object to
define the \"zero\" in the colimit as the equivalence class of `β¨jβ, 0 : F.obj jββ©`."]
instance colimit_has_one : has_one M :=
{ one := M.mk β¨is_filtered.nonempty.some, 1β© }
/--
The definition of the "one" in the colimit is independent of the chosen object of `J`.
In particular, this lemma allows us to "unfold" the definition of `colimit_one` at a custom chosen
object `j`.
-/
@[to_additive "The definition of the \"zero\" in the colimit is independent of the chosen object
of `J`. In particular, this lemma allows us to \"unfold\" the definition of `colimit_zero` at a
custom chosen object `j`."]
lemma colimit_one_eq (j : J) : (1 : M) = M.mk β¨j, 1β© :=
begin
apply M.mk_eq,
refine β¨max' _ j, left_to_max _ j, right_to_max _ j, _β©,
simp,
end
/--
The "unlifted" version of multiplication in the colimit. To multiply two dependent pairs
`β¨jβ, xβ©` and `β¨jβ, yβ©`, we pass to a common successor of `jβ` and `jβ` (given by `is_filtered.max`)
and multiply them there.
-/
@[to_additive "The \"unlifted\" version of addition in the colimit. To add two dependent pairs
`β¨jβ, xβ©` and `β¨jβ, yβ©`, we pass to a common successor of `jβ` and `jβ` (given by `is_filtered.max`)
and add them there."]
def colimit_mul_aux (x y : Ξ£ j, F.obj j) : M :=
M.mk β¨max' x.1 y.1, F.map (left_to_max x.1 y.1) x.2 * F.map (right_to_max x.1 y.1) y.2β©
/-- Multiplication in the colimit is well-defined in the left argument. -/
@[to_additive "Addition in the colimit is well-defined in the left argument."]
lemma colimit_mul_aux_eq_of_rel_left {x x' y : Ξ£ j, F.obj j}
(hxx' : types.filtered_colimit.rel (F β forget Mon) x x') :
colimit_mul_aux x y = colimit_mul_aux x' y :=
begin
cases x with jβ x, cases y with jβ y, cases x' with jβ x',
obtain β¨l, f, g, hfgβ© := hxx',
simp at hfg,
obtain β¨s, Ξ±, Ξ², Ξ³, hβ, hβ, hββ© := tulip (left_to_max jβ jβ) (right_to_max jβ jβ)
(right_to_max jβ jβ) (left_to_max jβ jβ) f g,
apply M.mk_eq,
use [s, Ξ±, Ξ³],
dsimp,
simp_rw [monoid_hom.map_mul, β comp_apply, β F.map_comp, hβ, hβ, hβ, F.map_comp, comp_apply, hfg]
end
/-- Multiplication in the colimit is well-defined in the right argument. -/
@[to_additive "Addition in the colimit is well-defined in the right argument."]
lemma colimit_mul_aux_eq_of_rel_right {x y y' : Ξ£ j, F.obj j}
(hyy' : types.filtered_colimit.rel (F β forget Mon) y y') :
colimit_mul_aux x y = colimit_mul_aux x y' :=
begin
cases y with jβ y, cases x with jβ x, cases y' with jβ y',
obtain β¨l, f, g, hfgβ© := hyy',
simp at hfg,
obtain β¨s, Ξ±, Ξ², Ξ³, hβ, hβ, hββ© := tulip (right_to_max jβ jβ) (left_to_max jβ jβ)
(left_to_max jβ jβ) (right_to_max jβ jβ) f g,
apply M.mk_eq,
use [s, Ξ±, Ξ³],
dsimp,
simp_rw [monoid_hom.map_mul, β comp_apply, β F.map_comp, hβ, hβ, hβ, F.map_comp, comp_apply, hfg]
end
/-- Multiplication in the colimit. See also `colimit_mul_aux`. -/
@[to_additive "Addition in the colimit. See also `colimit_add_aux`."]
instance colimit_has_mul : has_mul M :=
{ mul := Ξ» x y, begin
refine quot.liftβ (colimit_mul_aux F) _ _ x y,
{ intros x y y' h,
apply colimit_mul_aux_eq_of_rel_right,
apply types.filtered_colimit.rel_of_quot_rel,
exact h },
{ intros x x' y h,
apply colimit_mul_aux_eq_of_rel_left,
apply types.filtered_colimit.rel_of_quot_rel,
exact h },
end }
/--
Multiplication in the colimit is independent of the chosen "maximum" in the filtered category.
In particular, this lemma allows us to "unfold" the definition of the multiplication of `x` and `y`,
using a custom object `k` and morphisms `f : x.1 βΆ k` and `g : y.1 βΆ k`.
-/
@[to_additive "Addition in the colimit is independent of the chosen \"maximum\" in the filtered
category. In particular, this lemma allows us to \"unfold\" the definition of the addition of `x`
and `y`, using a custom object `k` and morphisms `f : x.1 βΆ k` and `g : y.1 βΆ k`."]
lemma colimit_mul_mk_eq (x y : Ξ£ j, F.obj j) (k : J) (f : x.1 βΆ k) (g : y.1 βΆ k) :
(M.mk x) * (M.mk y) = M.mk β¨k, F.map f x.2 * F.map g y.2β© :=
begin
cases x with jβ x, cases y with jβ y,
obtain β¨s, Ξ±, Ξ², hβ, hββ© := bowtie (left_to_max jβ jβ) f (right_to_max jβ jβ) g,
apply M.mk_eq,
use [s, Ξ±, Ξ²],
dsimp,
simp_rw [monoid_hom.map_mul, β comp_apply, β F.map_comp, hβ, hβ],
end
@[to_additive]
instance colimit_monoid : monoid M :=
{ one_mul := Ξ» x, begin
apply quot.induction_on x, clear x, intro x, cases x with j x,
rw [colimit_one_eq F j, colimit_mul_mk_eq F β¨j, 1β© β¨j, xβ© j (π j) (π j),
monoid_hom.map_one, one_mul, F.map_id, id_apply],
end,
mul_one := Ξ» x, begin
apply quot.induction_on x, clear x, intro x, cases x with j x,
rw [colimit_one_eq F j, colimit_mul_mk_eq F β¨j, xβ© β¨j, 1β© j (π j) (π j),
monoid_hom.map_one, mul_one, F.map_id, id_apply],
end,
mul_assoc := Ξ» x y z, begin
apply quot.induction_onβ x y z, clear x y z, intros x y z,
cases x with jβ x, cases y with jβ y, cases z with jβ z,
rw [colimit_mul_mk_eq F β¨jβ, xβ© β¨jβ, yβ© _ (first_to_maxβ jβ jβ jβ) (second_to_maxβ jβ jβ jβ),
colimit_mul_mk_eq F β¨maxβ jβ jβ jβ, _β© β¨jβ, zβ© _ (π _) (third_to_maxβ jβ jβ jβ),
colimit_mul_mk_eq F β¨jβ, yβ© β¨jβ, zβ© _ (second_to_maxβ jβ jβ jβ) (third_to_maxβ jβ jβ jβ),
colimit_mul_mk_eq F β¨jβ, xβ© β¨maxβ jβ jβ jβ, _β© _ (first_to_maxβ jβ jβ jβ) (π _)],
simp only [F.map_id, id_apply, mul_assoc],
end,
..colimit_has_one,
..colimit_has_mul }
/-- The bundled monoid giving the filtered colimit of a diagram. -/
@[to_additive "The bundled additive monoid giving the filtered colimit of a diagram."]
def colimit : Mon := Mon.of M
/-- The monoid homomorphism from a given monoid in the diagram to the colimit monoid. -/
@[to_additive "The additive monoid homomorphism from a given additive monoid in the diagram to the
colimit additive monoid."]
def cocone_morphism (j : J) : F.obj j βΆ colimit :=
{ to_fun := (types.colimit_cocone (F β forget Mon)).ΞΉ.app j,
map_one' := (colimit_one_eq j).symm,
map_mul' := Ξ» x y, begin
convert (colimit_mul_mk_eq F β¨j, xβ© β¨j, yβ© j (π j) (π j)).symm,
rw [F.map_id, id_apply, id_apply], refl,
end }
@[simp, to_additive]
lemma cocone_naturality {j j' : J} (f : j βΆ j') :
F.map f β« (cocone_morphism j') = cocone_morphism j :=
monoid_hom.coe_inj ((types.colimit_cocone (F β forget Mon)).ΞΉ.naturality f)
/-- The cocone over the proposed colimit monoid. -/
@[to_additive "The cocone over the proposed colimit additive monoid."]
def colimit_cocone : cocone F :=
{ X := colimit,
ΞΉ := { app := cocone_morphism } }.
/--
Given a cocone `t` of `F`, the induced monoid homomorphism from the colimit to the cocone point.
As a function, this is simply given by the induced map of the corresponding cocone in `Type`.
The only thing left to see is that it is a monoid homomorphism.
-/
@[to_additive "Given a cocone `t` of `F`, the induced additive monoid homomorphism from the colimit
to the cocone point. As a function, this is simply given by the induced map of the corresponding
cocone in `Type`. The only thing left to see is that it is an additive monoid homomorphism."]
def colimit_desc (t : cocone F) : colimit βΆ t.X :=
{ to_fun := (types.colimit_cocone_is_colimit (F β forget Mon)).desc ((forget Mon).map_cocone t),
map_one' := begin
rw colimit_one_eq F is_filtered.nonempty.some,
exact monoid_hom.map_one _,
end,
map_mul' := Ξ» x y, begin
apply quot.induction_onβ x y, clear x y, intros x y,
cases x with i x, cases y with j y,
rw colimit_mul_mk_eq F β¨i, xβ© β¨j, yβ© (max' i j) (left_to_max i j) (right_to_max i j),
dsimp [types.colimit_cocone_is_colimit],
rw [monoid_hom.map_mul, t.w_apply, t.w_apply],
end }
/-- The proposed colimit cocone is a colimit in `Mon`. -/
@[to_additive "The proposed colimit cocone is a colimit in `AddMon`."]
def colimit_cocone_is_colimit : is_colimit colimit_cocone :=
{ desc := colimit_desc,
fac' := Ξ» t j, monoid_hom.coe_inj
((types.colimit_cocone_is_colimit (F β forget Mon)).fac ((forget Mon).map_cocone t) j),
uniq' := Ξ» t m h, monoid_hom.coe_inj $
(types.colimit_cocone_is_colimit (F β forget Mon)).uniq ((forget Mon).map_cocone t) m
(Ξ» j, funext $ Ξ» x, monoid_hom.congr_fun (h j) x) }
@[to_additive]
instance forget_preserves_filtered_colimits : preserves_filtered_colimits (forget Mon) :=
{ preserves_filtered_colimits := Ξ» J _ _, by exactI
{ preserves_colimit := Ξ» F, preserves_colimit_of_preserves_colimit_cocone
(colimit_cocone_is_colimit F) (types.colimit_cocone_is_colimit (F β forget Mon)) } }
end
end Mon.filtered_colimits
namespace CommMon.filtered_colimits
open Mon.filtered_colimits (colimit_mul_mk_eq)
section
-- We use parameters here, mainly so we can have the abbreviation `M` below, without
-- passing around `F` all the time.
parameters {J : Type v} [small_category J] [is_filtered J] (F : J β₯€ CommMon.{v})
/--
The colimit of `F β forgetβ CommMon Mon` in the category `Mon`.
In the following, we will show that this has the structure of a _commutative_ monoid.
-/
@[to_additive "The colimit of `F β forgetβ AddCommMon AddMon` in the category `AddMon`. In the
following, we will show that this has the structure of a _commutative_ additive monoid."]
abbreviation M : Mon := Mon.filtered_colimits.colimit (F β forgetβ CommMon Mon.{v})
@[to_additive]
instance colimit_comm_monoid : comm_monoid M :=
{ mul_comm := Ξ» x y, begin
apply quot.induction_onβ x y, clear x y, intros x y,
let k := max' x.1 y.1,
let f := left_to_max x.1 y.1,
let g := right_to_max x.1 y.1,
rw [colimit_mul_mk_eq _ x y k f g, colimit_mul_mk_eq _ y x k g f],
dsimp,
rw mul_comm,
end
..M.monoid }
/-- The bundled commutative monoid giving the filtered colimit of a diagram. -/
@[to_additive "The bundled additive commutative monoid giving the filtered colimit of a diagram."]
def colimit : CommMon := CommMon.of M
/-- The cocone over the proposed colimit commutative monoid. -/
@[to_additive "The cocone over the proposed colimit additive commutative monoid."]
def colimit_cocone : cocone F :=
{ X := colimit,
ΞΉ := { ..(Mon.filtered_colimits.colimit_cocone (F β forgetβ CommMon Mon.{v})).ΞΉ } }
/-- The proposed colimit cocone is a colimit in `CommMon`. -/
@[to_additive "The proposed colimit cocone is a colimit in `AddCommMon`."]
def colimit_cocone_is_colimit : is_colimit colimit_cocone :=
{ desc := Ξ» t, Mon.filtered_colimits.colimit_desc (F β forgetβ CommMon Mon.{v})
((forgetβ CommMon Mon.{v}).map_cocone t),
fac' := Ξ» t j, monoid_hom.coe_inj $
(types.colimit_cocone_is_colimit (F β forget CommMon)).fac ((forget CommMon).map_cocone t) j,
uniq' := Ξ» t m h, monoid_hom.coe_inj $
(types.colimit_cocone_is_colimit (F β forget CommMon)).uniq ((forget CommMon).map_cocone t) m
((Ξ» j, funext $ Ξ» x, monoid_hom.congr_fun (h j) x)) }
@[to_additive forgetβ_AddMon_preserves_filtered_colimits]
instance forgetβ_Mon_preserves_filtered_colimits :
preserves_filtered_colimits (forgetβ CommMon Mon.{v}) :=
{ preserves_filtered_colimits := Ξ» J _ _, by exactI
{ preserves_colimit := Ξ» F, preserves_colimit_of_preserves_colimit_cocone
(colimit_cocone_is_colimit F)
(Mon.filtered_colimits.colimit_cocone_is_colimit (F β forgetβ CommMon Mon.{v})) } }
@[to_additive]
instance forget_preserves_filtered_colimits : preserves_filtered_colimits (forget CommMon) :=
limits.comp_preserves_filtered_colimits (forgetβ CommMon Mon) (forget Mon)
end
end CommMon.filtered_colimits
|
5d26216270dcc6c38626149f4f45b58f0c11d4a9 | 8e31b9e0d8cec76b5aa1e60a240bbd557d01047c | /scratch/dead_simplex.lean | 5a740a69843c0304707ff712008e77446b67b1e6 | [] | no_license | ChrisHughes24/LP | 7bdd62cb648461c67246457f3ddcb9518226dd49 | e3ed64c2d1f642696104584e74ae7226d8e916de | refs/heads/master | 1,685,642,642,858 | 1,578,070,602,000 | 1,578,070,602,000 | 195,268,102 | 4 | 3 | null | 1,569,229,518,000 | 1,562,255,287,000 | Lean | UTF-8 | Lean | false | false | 43,408 | lean | import tableau order.lexicographic
open matrix fintype finset function pequiv partition
variables {m n : β}
local notation `rvec`:2000 n := matrix (fin 1) (fin n) β
local notation `cvec`:2000 m := matrix (fin m) (fin 1) β
local infix ` β¬ `:70 := matrix.mul
local postfix `α΅` : 1500 := transpose
namespace tableau
def pivot_linear_order (T : tableau m n) : decidable_linear_order (fin n) :=
decidable_linear_order.lift T.to_partition.colg (injective_colg _) (by apply_instance)
def pivot_col (T : tableau m n) (obj : fin m) : option (fin n) :=
option.cases_on
(fin.find (Ξ» c : fin n, T.to_matrix obj c β 0 β§ T.to_partition.colg c β T.restricted
β§ c β T.dead))
(((list.fin_range n).filter (Ξ» c : fin n, 0 < T.to_matrix obj c β§ c β T.dead)).argmin
T.to_partition.colg)
some
def pivot_row_linear_order (T : tableau m n) (c : fin n) : decidable_linear_order (fin m) :=
decidable_linear_order.lift
(show fin m β lex β (fin (m + n)),
from Ξ» r', (abs (T.const r' 0 / T.to_matrix r' c), T.to_partition.rowg r'))
(Ξ» x y, by simp [T.to_partition.injective_rowg.eq_iff])
(by apply_instance)
section
local attribute [instance, priority 0] fin.has_le fin.decidable_linear_order
lemma pivot_row_linear_order_le_def (T : tableau m n) (c : fin n) :
@has_le.le (fin m)
(by haveI := pivot_row_linear_order T c; apply_instance) =
(Ξ» i i', abs (T.const i 0 / T.to_matrix i c) < abs (T.const i' 0 / T.to_matrix i' c) β¨
(abs (T.const i 0 / T.to_matrix i c) = abs (T.const i' 0 / T.to_matrix i' c) β§
T.to_partition.rowg i β€ T.to_partition.rowg i')) :=
funext $ Ξ» i, funext $ Ξ» i', propext $ prod.lex_def _ _
end
def pivot_row (T : tableau m n) (obj: fin m) (c : fin n) : option (fin m) :=
let l := (list.fin_range m).filter (Ξ» r : fin m, obj β r β§ T.to_partition.rowg r β T.restricted
β§ T.to_matrix obj c / T.to_matrix r c < 0) in
@list.minimum _ (pivot_row_linear_order T c) l
lemma pivot_col_spec {T : tableau m n} {obj : fin m} {c : fin n} :
c β pivot_col T obj β ((T.to_matrix obj c β 0 β§ T.to_partition.colg c β T.restricted)
β¨ (0 < T.to_matrix obj c β§ T.to_partition.colg c β T.restricted)) β§ c β T.dead :=
begin
simp [pivot_col],
cases h : fin.find (Ξ» c : fin n, T.to_matrix obj c β 0 β§ T.to_partition.colg c β T.restricted
β§ c β T.dead),
{ finish [h, fin.find_eq_some_iff, fin.find_eq_none_iff, lt_irrefl, list.argmin_eq_some_iff] },
{ finish [fin.find_eq_some_iff] }
end
lemma nonpos_of_lt_pivot_col {T : tableau m n} {obj : fin m} {c j : fin n}
(hc : c β pivot_col T obj) (hcres : T.to_partition.colg c β T.restricted)
(hdead : j β T.dead) (hjc : T.to_partition.colg j < T.to_partition.colg c) :
T.to_matrix obj j β€ 0 :=
begin
rw [pivot_col] at hc,
cases h : fin.find (Ξ» c, T.to_matrix obj c β 0 β§ colg (T.to_partition) c β T.restricted
β§ c β T.dead),
{ rw h at hc,
refine le_of_not_lt (Ξ» hj0, _),
exact not_le_of_gt hjc ((list.mem_argmin_iff.1 hc).2.1 j
(list.mem_filter.2 (by simp [hj0, hdead]))) },
{ rw h at hc,
simp [*, fin.find_eq_some_iff] at * }
end
lemma pivot_col_eq_none {T : tableau m n} {obj : fin m} (hT : T.feasible)
(h : pivot_col T obj = none) : T.is_optimal (T.of_col 0) (T.to_partition.rowg obj) :=
is_optimal_of_col_zero hT
begin
revert h,
simp [pivot_col],
cases h : fin.find (Ξ» c : fin n, T.to_matrix obj c β 0 β§ T.to_partition.colg c β T.restricted
β§ c β T.dead),
{ simp only [list.filter_eq_nil, forall_prop_of_true, list.argmin_eq_none,
list.mem_fin_range, not_and, not_not, fin.find_eq_none_iff] at *,
assume hj j hdead,
exact β¨le_of_not_gt (Ξ» h0, hdead (hj j h0)), by finishβ© },
{ simp [h] }
end
lemma pivot_row_spec {T : tableau m n} {obj r : fin m} {c : fin n} :
r β pivot_row T obj c β
obj β r β§ T.to_partition.rowg r β T.restricted β§
T.to_matrix obj c / T.to_matrix r c < 0 β§
(β r' : fin m, obj β r' β T.to_partition.rowg r' β T.restricted β
T.to_matrix obj c / T.to_matrix r' c < 0 β
abs (T.const r 0 / T.to_matrix r c) β€ abs (T.const r' 0 / T.to_matrix r' c)) :=
begin
simp only [list.mem_filter, pivot_row, option.mem_def, with_bot.some_eq_coe,
list.minimum_eq_coe_iff, list.mem_fin_range, true_and, and_imp],
rw [pivot_row_linear_order_le_def],
intros hor hres hr0 h,
simp only [*, true_and, ne.def, not_false_iff],
intros r' hor' hres' hr0',
cases h r' hor' hres' hr0',
{ exact le_of_lt (by assumption) },
{ exact le_of_eq (by tauto) }
end
lemma nonneg_of_lt_pivot_row {T : tableau m n} {obj : fin m} {r i : fin m} {c : fin n}
(hc0 : 0 < T.to_matrix obj c) (hres : T.to_partition.rowg i β T.restricted)
(hc : c β pivot_col T obj) (hr : r β pivot_row T obj c)
(hconst : T.const i 0 = 0)
(hjc : T.to_partition.rowg i < T.to_partition.rowg r) :
0 β€ T.to_matrix i c :=
if hobj : obj = i then le_of_lt $ hobj βΈ hc0
else
le_of_not_gt $ Ξ» hic, not_le_of_lt hjc
begin
have := ((@list.minimum_eq_coe_iff _ (id _) _ _).1 hr).2 i
(list.mem_filter.2 β¨list.mem_fin_range _, hobj, hres, div_neg_of_pos_of_neg hc0 hicβ©),
rw [pivot_row_linear_order_le_def] at this,
simp [hconst, not_lt_of_ge (abs_nonneg _), *] at *
end
lemma ne_zero_of_mem_pivot_row {T : tableau m n} {obj r : fin m} {c : fin n}
(hr : r β pivot_row T obj c) : T.to_matrix r c β 0 :=
assume hrc, by simpa [lt_irrefl, hrc] using pivot_row_spec hr
lemma ne_zero_of_mem_pivot_col {T : tableau m n} {obj : fin m} {c : fin n}
(hc : c β pivot_col T obj) : T.to_matrix obj c β 0 :=
Ξ» h, by simpa [h, lt_irrefl] using pivot_col_spec hc
lemma pivot_row_eq_none_aux {T : tableau m n} {obj : fin m} {c : fin n}
(hrow : pivot_row T obj c = none) (hs : c β pivot_col T obj) :
β r, obj β r β T.to_partition.rowg r β T.restricted β 0 β€ T.to_matrix obj c / T.to_matrix r c :=
by simpa [pivot_row, list.filter_eq_nil] using hrow
lemma pivot_row_eq_none {T : tableau m n} {obj : fin m} {c : fin n} (hT : T.feasible)
(hrow : pivot_row T obj c = none) (hs : c β pivot_col T obj) :
T.is_unbounded_above (T.to_partition.rowg obj) :=
have hrow : β r, obj β r β T.to_partition.rowg r β T.restricted β
0 β€ T.to_matrix obj c / T.to_matrix r c,
from pivot_row_eq_none_aux hrow hs,
have hc : ((T.to_matrix obj c β 0 β§ T.to_partition.colg c β T.restricted)
β¨ (0 < T.to_matrix obj c β§ T.to_partition.colg c β T.restricted)) β§ c β T.dead,
from pivot_col_spec hs,
have hToc : T.to_matrix obj c β 0, from Ξ» h, by simpa [h, lt_irrefl] using hc,
(lt_or_gt_of_ne hToc).elim
(Ξ» hToc : T.to_matrix obj c < 0, is_unbounded_above_rowg_of_nonpos hT c
(hc.1.elim and.right (Ξ» h, (not_lt_of_gt hToc h.1).elim)) hc.2
(Ξ» i hi, classical.by_cases
(Ξ» hoi : obj = i, le_of_lt (hoi βΈ hToc))
(Ξ» hoi : obj β i, inv_nonpos.1 $ nonpos_of_mul_nonneg_right (hrow _ hoi hi) hToc))
hToc)
(Ξ» hToc : 0 < T.to_matrix obj c, is_unbounded_above_rowg_of_nonneg hT c
(Ξ» i hi, classical.by_cases
(Ξ» hoi : obj = i, le_of_lt (hoi βΈ hToc))
(Ξ» hoi : obj β i, inv_nonneg.1 $ nonneg_of_mul_nonneg_left (hrow _ hoi hi) hToc))
hc.2 hToc)
def feasible_of_mem_pivot_row_and_col {T : tableau m n} {obj : fin m} (hT : T.feasible) {c}
(hc : c β pivot_col T obj) {r} (hr : r β pivot_row T obj c) :
feasible (T.pivot r c) :=
begin
have := pivot_col_spec hc,
have := pivot_row_spec hr,
have := @feasible_simplex_pivot _ _ _ obj hT r c,
tauto
end
section blands_rule
local attribute [instance, priority 0] classical.dec
variable (obj : fin m)
lemma not_unique_row_and_unique_col {T T' : tableau m n} {r c c'}
(hcobj0 : 0 < T.to_matrix obj c)
(hc'obj0 : 0 < T'.to_matrix obj c')
(hrc0 : T.to_matrix r c < 0)
(hflat : T.flat = T'.flat)
(hs : T.to_partition.rowg r = T'.to_partition.colg c')
(hrobj : T.to_partition.rowg obj = T'.to_partition.rowg obj)
(hfickle : β i, T.to_partition.rowg i β T'.to_partition.rowg i β T.const i 0 = 0)
(hobj : T.const obj 0 = T'.const obj 0)
(nonpos_of_colg_ne : β j,
T'.to_partition.colg j β T.to_partition.colg j β j β c' β T'.to_matrix obj j β€ 0)
(nonpos_of_colg_eq : β j, j β c' β
T'.to_partition.colg j = T.to_partition.colg c β T'.to_matrix obj j β€ 0)
(unique_row : β i β r, T.const i 0 = 0 β T.to_partition.rowg i β T'.to_partition.rowg i β
0 β€ T.to_matrix i c) :
false :=
let objr := T.to_partition.rowg obj in
let x := Ξ» y : β, T.of_col (y β’ (single c 0).to_matrix) in
have hxflatT' : β {y}, x y β flat T', from hflat βΈ Ξ» _, of_col_mem_flat _ _,
have hxrow : β y i, x y (T.to_partition.rowg i) 0 = T.const i 0 + y * T.to_matrix i c,
by simp [x, of_col_single_rowg],
have hxcol : β {y j}, j β c β x y (T.to_partition.colg j) 0 = 0,
from Ξ» y j hjc, by simp [x, of_col_colg, pequiv.to_matrix, single_apply_of_ne hjc.symm],
have hxcolc : β {y}, x y (T.to_partition.colg c) 0 = y, by simp [x, of_col_colg, pequiv.to_matrix],
let c_star : fin (m + n) β β := Ξ» v, option.cases_on (T'.to_partition.colp.symm v) 0
(T'.to_matrix obj) in
have hxobj : β y, x y objr 0 = T.const obj 0 + y * T.to_matrix obj c, from Ξ» y, hxrow _ _,
have hgetr : β {y v}, c_star v * x y v 0 β 0 β (T'.to_partition.colp.symm v).is_some,
from Ξ» y v, by cases h : T'.to_partition.colp.symm v; dsimp [c_star]; rw h; simp,
have c_star_eq_get : β {v} (hv : (T'.to_partition.colp.symm v).is_some),
c_star v = T'.to_matrix obj (option.get hv),
from Ξ» v hv, by dsimp only [c_star]; conv_lhs{rw [β option.some_get hv]}; refl,
have hsummmn : β {y}, sum univ (Ξ» j, T'.to_matrix obj j * x y (T'.to_partition.colg j) 0) =
sum univ (Ξ» v, c_star v * x y v 0),
from Ξ» y, sum_bij_ne_zero (Ξ» j _ _, T'.to_partition.colg j) (Ξ» _ _ _, mem_univ _)
(Ξ» _ _ _ _ _ _ h, T'.to_partition.injective_colg h)
(Ξ» v _ h0, β¨option.get (hgetr h0), mem_univ _,
by rw [β c_star_eq_get (hgetr h0)]; simpa using h0, by simpβ©)
(Ξ» _ _ h0, by dsimp [c_star]; rw [colp_colg]),
have hgetc : β {y v}, c_star v * x y v 0 β 0 β v β T.to_partition.colg c β
(T.to_partition.rowp.symm v).is_some,
from Ξ» y v, (eq_rowg_or_colg T.to_partition v).elim
(Ξ» β¨i, hiβ©, by rw [hi, rowp_rowg]; simp)
(Ξ» β¨j, hjβ© h0 hvc,
by rw [hj, hxcol (mt (congr_arg T.to_partition.colg) (hvc β hj.trans)), mul_zero] at h0;
exact (h0 rfl).elim),
have hsummmnn : β {y}, (univ.erase (T.to_partition.colg c)).sum (Ξ» v, c_star v * x y v 0) =
univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * x y (T.to_partition.rowg i) 0),
from Ξ» y, eq.symm $ sum_bij_ne_zero (Ξ» i _ _, T.to_partition.rowg i) (by simp)
(Ξ» _ _ _ _ _ _ h, T.to_partition.injective_rowg h)
(Ξ» v hvc h0, β¨option.get (hgetc h0 (mem_erase.1 hvc).1), mem_univ _, by simpa using h0β©)
(by intros; refl),
have hsumm : β {y}, univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * x y (T.to_partition.rowg i) 0) =
univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.const i 0) +
y * univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.to_matrix i c),
from Ξ» y, by simp only [hxrow, mul_add, add_mul, sum_add_distrib, mul_assoc,
mul_left_comm _ y, mul_sum.symm],
have hxobj' : β y, x y objr 0 = univ.sum (Ξ» v, c_star v * x y v 0) + T'.const obj 0,
from Ξ» y, by dsimp [objr]; rw [hrobj, mem_flat_iff.1 hxflatT', hsummmn],
have hy : β {y}, y * T.to_matrix obj c = c_star (T.to_partition.colg c) * y +
univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.const i 0) +
y * univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.to_matrix i c),
from Ξ» y, by rw [β add_left_inj (T.const obj 0), β hxobj, hxobj',
β insert_erase (mem_univ (T.to_partition.colg c)), sum_insert (not_mem_erase _ _),
hsummmnn, hobj, hsumm, hxcolc]; simp,
have hy' : β (y), y * (T.to_matrix obj c - c_star (T.to_partition.colg c) -
univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.to_matrix i c)) =
univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.const i 0),
from Ξ» y, by rw [mul_sub, mul_sub, hy]; simp [mul_comm, mul_assoc, mul_left_comm],
have h0 : T.to_matrix obj c - c_star (T.to_partition.colg c) -
univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.to_matrix i c) = 0,
by rw [β (domain.mul_left_inj (@one_ne_zero β _)), hy', β hy' 0, zero_mul, mul_zero],
have hcolnec' : T'.to_partition.colp.symm (T.to_partition.colg c) β some c',
from Ξ» h,
by simpa [hs.symm] using congr_arg T'.to_partition.colg (option.eq_some_iff_get_eq.1 h).snd,
have eq_of_roweqc' : β {i}, T'.to_partition.colp.symm (T.to_partition.rowg i) = some c' β i = r,
from Ξ» i h, by simpa [hs.symm, T.to_partition.injective_rowg.eq_iff] using
congr_arg T'.to_partition.colg (option.eq_some_iff_get_eq.1 h).snd,
have sumpos : 0 < univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.to_matrix i c),
by rw [β sub_eq_zero.1 h0]; exact add_pos_of_pos_of_nonneg hcobj0
(begin
simp only [c_star, neg_nonneg],
cases h : T'.to_partition.colp.symm (T.to_partition.colg c) with j,
{ refl },
{ exact nonpos_of_colg_eq j (mt (congr_arg some) (h βΈ hcolnec'))
(by rw [β (option.eq_some_iff_get_eq.1 h).snd]; simp) }
end),
have hexi : β i, 0 < c_star (T.to_partition.rowg i) * T.to_matrix i c,
from imp_of_not_imp_not _ _ (by simpa using @sum_nonpos _ _ (@univ (fin m) _)
(Ξ» i, c_star (T.to_partition.rowg i) * T.to_matrix i c) _ _) sumpos,
let β¨i, hiβ© := hexi in
have hi0 : T.const i 0 = 0, from hfickle i
(Ξ» h, by dsimp [c_star] at hi; rw [h, colp_rowg_eq_none] at hi; simpa [lt_irrefl] using hi),
have hi_some : (T'.to_partition.colp.symm (T.to_partition.rowg i)).is_some,
from option.ne_none_iff_is_some.1 (Ξ» h, by dsimp only [c_star] at hi; rw h at hi;
simpa [lt_irrefl] using hi),
have hi' : 0 < T'.to_matrix obj (option.get hi_some) * T.to_matrix i c,
by dsimp only [c_star] at hi; rwa [β option.some_get hi_some] at hi,
have hir : i β r, from Ξ» hir, begin
have : option.get hi_some = c', from T'.to_partition.injective_colg
(by rw [colg_get_colp_symm, β hs, hir]),
rw [this, hir] at hi',
exact not_lt_of_gt hi' (mul_neg_of_pos_of_neg hc'obj0 hrc0)
end,
have hnec' : option.get hi_some β c',
from Ξ» eq_c', hir $ @eq_of_roweqc' i (eq_c' βΈ by simp),
have hic0 : T.to_matrix i c < 0,
from neg_of_mul_pos_right hi' (nonpos_of_colg_ne _ (by simp) hnec'),
not_le_of_gt hic0 (unique_row _ hir hi0
(by rw [β colg_get_colp_symm _ _ hi_some]; exact colg_ne_rowg _ _ _))
inductive rel : tableau m n β tableau m n β Prop
| pivot : β {T}, feasible T β β {r c}, c β pivot_col T obj β
r β pivot_row T obj c β rel (T.pivot r c) T
| trans_pivot : β {Tβ Tβ r c}, rel Tβ Tβ β c β pivot_col Tβ obj β
r β pivot_row Tβ obj c β rel (Tβ.pivot r c) Tβ
lemma feasible_of_rel_right {T T' : tableau m n} (h : rel obj T' T) : T.feasible :=
rel.rec_on h (by tauto) (by tauto)
lemma feasible_of_rel_left {T T' : tableau m n} (h : rel obj T' T) : T'.feasible :=
rel.rec_on h (Ξ» _ hT _ _ hc hr, feasible_of_mem_pivot_row_and_col hT hc hr)
(Ξ» _ _ _ _ _ hc hr hT, feasible_of_mem_pivot_row_and_col hT hc hr)
/-- Slightly stronger recursor than the default recursor -/
@[elab_as_eliminator]
lemma rel.rec_on' {obj : fin m} {C : tableau m n β tableau m n β Prop} {T T' : tableau m n}
(hrel : rel obj T T')
(hpivot : β {T : tableau m n} {r : fin m} {c : fin n},
feasible T β c β pivot_col T obj β r β pivot_row T obj c β C (pivot T r c) T)
(hpivot_trans : β {Tβ Tβ : tableau m n} {r : fin m} {c : fin n},
rel obj (Tβ.pivot r c) Tβ β rel obj Tβ Tβ β
c β pivot_col Tβ obj β
r β pivot_row Tβ obj c β C (Tβ.pivot r c) Tβ β C Tβ Tβ β C (pivot Tβ r c) Tβ) :
C T T' :=
rel.rec_on hrel (Ξ» T hT r c hc hr, hpivot hT hc hr) (Ξ» Tβ Tβ r c hrelTββ hc hr ih, hpivot_trans
(rel.pivot (feasible_of_rel_left obj hrelTββ) hc hr) hrelTββ hc hr
(hpivot (feasible_of_rel_left obj hrelTββ) hc hr) ih)
lemma rel.trans {obj : fin m} {Tβ Tβ Tβ : tableau m n} (hββ : rel obj Tβ Tβ) :
rel obj Tβ Tβ β rel obj Tβ Tβ :=
rel.rec_on hββ
(Ξ» T r c hT hc hr hrelT, rel.trans_pivot hrelT hc hr)
(Ξ» Tβ Tβ r c hrelTββ hc hr ih hrelTββ, rel.trans_pivot (ih hrelTββ) hc hr)
instance : is_trans (tableau m n) (rel obj) := β¨@rel.trans _ _ objβ©
lemma flat_eq_of_rel {T T' : tableau m n} (h : rel obj T' T) : flat T' = flat T :=
rel.rec_on' h (Ξ» _ _ _ _ _ hr, flat_pivot (ne_zero_of_mem_pivot_row hr))
(Ξ» _ _ _ _ _ _ _ _, eq.trans)
lemma rowg_obj_eq_of_rel {T T' : tableau m n} (h : rel obj T T') : T.to_partition.rowg obj =
T'.to_partition.rowg obj :=
rel.rec_on' h (Ξ» T r c hfT hc hr, by simp [rowg_swap_of_ne _ (pivot_row_spec hr).1])
(Ξ» _ _ _ _ _ _ _ _, eq.trans)
lemma restricted_eq_of_rel {T T' : tableau m n} (h : rel obj T T') : T.restricted = T'.restricted :=
rel.rec_on' h (Ξ» _ _ _ _ _ _, rfl) (Ξ» _ _ _ _ _ _ _ _, eq.trans)
lemma dead_eq_of_rel {T T' : tableau m n} (h : rel obj T T') : T.dead = T'.dead :=
rel.rec_on' h (Ξ» _ _ _ _ _ _, rfl) (Ξ» _ _ _ _ _ _ _ _, eq.trans)
lemma dead_eq_of_rel_or_eq {T T' : tableau m n} (h : T = T' β¨ rel obj T T') : T.dead = T'.dead :=
h.elim (congr_arg _) $ dead_eq_of_rel _
lemma exists_mem_pivot_row_col_of_rel {T T' : tableau m n} (h : rel obj T' T) :
β r c, c β pivot_col T obj β§ r β pivot_row T obj c :=
rel.rec_on' h (Ξ» _ r c _ hc hr, β¨r, c, hc, hrβ©) (Ξ» _ _ _ _ _ _ _ _ _, id)
lemma exists_mem_pivot_row_of_rel {T T' : tableau m n} (h : rel obj T' T) {c : fin n}
(hc : c β pivot_col T obj) : β r, r β pivot_row T obj c :=
let β¨r, c', hc', hrβ© := exists_mem_pivot_row_col_of_rel obj h in β¨r, by simp * at *β©
lemma colg_eq_or_exists_mem_pivot_col {Tβ Tβ : tableau m n} (h : rel obj Tβ Tβ) {c : fin n} :
Tβ.to_partition.colg c = Tβ.to_partition.colg c β¨
β Tβ, (Tβ = Tβ β¨ rel obj Tβ Tβ) β§ (rel obj Tβ Tβ) β§
Tβ.to_partition.colg c = Tβ.to_partition.colg c β§
c β pivot_col Tβ obj :=
rel.rec_on' h begin
assume T r c' hT hc' hr,
by_cases hcc : c = c',
{ subst hcc,
exact or.inr β¨T, or.inl rfl, rel.pivot hT hc' hr, rfl, hc'β© },
{ simp [colg_swap_of_ne _ hcc] }
end
(Ξ» Tβ Tβ r c hrelpβ hrelββ hc hr ihpβ ihββ,
ihββ.elim
(Ξ» ihββ, ihpβ.elim
(Ξ» ihpβ, or.inl (ihββ.trans ihpβ))
(Ξ» β¨Tβ, hTββ©, or.inr β¨Tβ,
hTβ.1.elim (Ξ» h, h.symm βΈ or.inr hrelββ) (Ξ» h, or.inr $ h.trans hrelββ),
hTβ.2.1, hTβ.2.2.1.trans ihββ.symm, hTβ.2.2.2β©))
(Ξ» β¨Tβ, hTββ©, or.inr β¨Tβ, hTβ.1, hrelpβ.trans hTβ.2.1, hTβ.2.2β©))
lemma rowg_eq_or_exists_mem_pivot_row {Tβ Tβ : tableau m n} (h : rel obj Tβ Tβ) (r : fin m) :
Tβ.to_partition.rowg r = Tβ.to_partition.rowg r β¨
β (Tβ : tableau m n) c, (Tβ = Tβ β¨ rel obj Tβ Tβ) β§ (rel obj Tβ Tβ) β§
Tβ.to_partition.rowg r = Tβ.to_partition.rowg r β§
c β pivot_col Tβ obj β§ r β pivot_row Tβ obj c :=
rel.rec_on' h
begin
assume T r' c hT hc hr',
by_cases hrr : r = r',
{ subst hrr,
exact or.inr β¨T, c, or.inl rfl, rel.pivot hT hc hr', rfl, hc, hr'β© },
{ simp [rowg_swap_of_ne _ hrr] }
end
(Ξ» Tβ Tβ r c hrelpβ hrelββ hc hr ihpβ ihββ,
ihββ.elim
(Ξ» ihββ, ihpβ.elim
(Ξ» ihpβ, or.inl $ ihββ.trans ihpβ)
(Ξ» β¨Tβ, c', hTββ©, or.inr β¨Tβ, c', hTβ.1.elim (Ξ» h, h.symm βΈ or.inr hrelββ)
(Ξ» h, or.inr $ h.trans hrelββ), hTβ.2.1, ihββ.symm βΈ hTβ.2.2.1, hTβ.2.2.2β©))
(Ξ» β¨Tβ, c', hTββ©, or.inr β¨Tβ, c', hTβ.1,
(rel.pivot (feasible_of_rel_left _ hrelββ) hc hr).trans hTβ.2.1, hTβ.2.2β©))
lemma eq_or_rel_pivot_of_rel {Tβ Tβ : tableau m n} (h : rel obj Tβ Tβ) : β {r c}
(hc : c β pivot_col Tβ obj) (hr : r β pivot_row Tβ obj c),
Tβ = Tβ.pivot r c β¨ rel obj Tβ (Tβ.pivot r c) :=
rel.rec_on' h (Ξ» T r c hT hc hr r' c' hc' hr', by simp * at *)
(Ξ» Tβ Tβ r c hrelpβ hrelββ hc hr ihpβ ihββ r' c' hc' hr',
(ihββ hc' hr').elim
(Ξ» ihββ, or.inr $ ihββ βΈ rel.pivot (feasible_of_rel_left _ hrelββ) hc hr)
(Ξ» ihββ, or.inr $ (rel.pivot (feasible_of_rel_left _ hrelββ) hc hr).trans ihββ))
lemma exists_mem_pivot_col_of_mem_pivot_row {T : tableau m n} (hrelTT : rel obj T T)
{r c} (hc : c β pivot_col T obj) (hr : r β pivot_row T obj c) :
β (T' : tableau m n), c β pivot_col T' obj β§ T'.to_partition.colg c =
T.to_partition.rowg r β§ rel obj T' T β§ rel obj T T' :=
have hrelTTp : rel obj T (T.pivot r c),
from (eq_or_rel_pivot_of_rel _ hrelTT hc hr).elim (Ξ» h, h βΈ hrelTT ) id,
let β¨T', hT'β© := (colg_eq_or_exists_mem_pivot_col obj hrelTTp).resolve_left
(show (T.pivot r c).to_partition.colg c β T.to_partition.colg c, by simp) in
β¨T', hT'.2.2.2, by simp [hT'.2.2.1], hT'.1.elim
(Ξ» h, h.symm βΈ rel.pivot (feasible_of_rel_left _ hrelTT) hc hr)
(Ξ» h, h.trans $ rel.pivot (feasible_of_rel_left _ hrelTT) hc hr), hT'.2.1β©
lemma exists_mem_pivot_col_of_rowg_ne {T T' : tableau m n} (hrelTT' : rel obj T T') {r : fin m}
(hrelT'T : rel obj T' T) (hrow : T.to_partition.rowg r β T'.to_partition.rowg r) :
β (Tβ : tableau m n) c, c β pivot_col Tβ obj β§ Tβ.to_partition.colg c =
T.to_partition.rowg r β§ rel obj Tβ T β§ rel obj T Tβ :=
let β¨Tβ, c, hTβ, hrelTβT, hrowβ, hc, hrβ© :=
(rowg_eq_or_exists_mem_pivot_row obj hrelT'T _).resolve_left hrow in
let β¨Tβ, hTββ© := exists_mem_pivot_col_of_mem_pivot_row obj
(show rel obj Tβ Tβ, from hTβ.elim (Ξ» h, h.symm βΈ hrelTT'.trans hrelT'T)
(Ξ» h, h.trans $ hrelTT'.trans hrelTβT)) hc hr in
β¨Tβ, c, hTβ.1, hTβ.2.1.trans hrowβ, hTβ.2.2.1.trans $ hTβ.elim (Ξ» h, h.symm βΈ hrelTT'.trans hrelT'T)
(Ξ» h, h.trans $ hrelTT'.trans hrelT'T), hrelTT'.trans (hrelTβT.trans hTβ.2.2.2)β©
lemma const_obj_le_of_rel {Tβ Tβ : tableau m n} (h : rel obj Tβ Tβ) :
Tβ.const obj 0 β€ Tβ.const obj 0 :=
rel.rec_on' h (Ξ» T r c hT hc hr,
have hr' : _ := pivot_row_spec hr,
simplex_const_obj_le hT (by tauto) (by tauto))
(Ξ» _ _ _ _ _ _ _ _ hβ hβ, le_trans hβ hβ)
lemma const_obj_eq_of_rel_of_rel {Tβ Tβ : tableau m n} (hββ : rel obj Tβ Tβ)
(hββ : rel obj Tβ Tβ) : Tβ.const obj 0 = Tβ.const obj 0 :=
le_antisymm (const_obj_le_of_rel _ hββ) (const_obj_le_of_rel _ hββ)
lemma const_eq_const_of_const_obj_eq {Tβ Tβ : tableau m n} (hββ : rel obj Tβ Tβ) :
β (hobj : Tβ.const obj 0 = Tβ.const obj 0) (i : fin m), Tβ.const i 0 = Tβ.const i 0 :=
rel.rec_on' hββ
(Ξ» T r c hfT hc hr hobj i,
have hr0 : T.const r 0 = 0, from const_eq_zero_of_const_obj_eq hfT
(ne_zero_of_mem_pivot_col hc) (ne_zero_of_mem_pivot_row hr)
(pivot_row_spec hr).1 hobj,
if hir : i = r
then by simp [hir, hr0]
else by simp [const_pivot_of_ne _ hir, hr0])
(Ξ» Tβ Tβ r c hrelpβ hrelββ hc hr ihpβ ihββ hobj i,
have hobjp : (pivot Tβ r c).const obj 0 = Tβ.const obj 0,
from le_antisymm (hobj.symm βΈ const_obj_le_of_rel _ hrelββ)
(const_obj_le_of_rel _ hrelpβ),
by rw [ihpβ hobjp, ihββ (hobjp.symm.trans hobj)])
lemma const_eq_zero_of_rowg_ne_of_rel_self {T T' : tableau m n} (hrelTT' : rel obj T T')
(hrelT'T : rel obj T' T) (i : fin m) (hrow : T.to_partition.rowg i β T'.to_partition.rowg i) :
T.const i 0 = 0 :=
let β¨Tβ, c, hTββ, hT'β, hrowβ, hc, hiβ© := (rowg_eq_or_exists_mem_pivot_row obj hrelT'T _).resolve_left hrow in
have Tβ.const i 0 = 0, from const_eq_zero_of_const_obj_eq
(feasible_of_rel_right _ hT'β) (ne_zero_of_mem_pivot_col hc)
(ne_zero_of_mem_pivot_row hi) (pivot_row_spec hi).1
(const_obj_eq_of_rel_of_rel _ (rel.pivot (feasible_of_rel_right _ hT'β) hc hi)
((eq_or_rel_pivot_of_rel _ hT'β hc hi).elim
(Ξ» h, h βΈ hTββ.elim (Ξ» h, h.symm βΈ hrelTT') (Ξ» h, h.trans hrelTT'))
(Ξ» hrelT'p, hTββ.elim (Ξ» h, h.symm βΈ hrelTT'.trans (h βΈ hrelT'p))
(Ξ» h, h.trans $ hrelTT'.trans hrelT'p)))),
have hobj : Tβ.const obj 0 = T.const obj 0,
from hTββ.elim (Ξ» h, h βΈ rfl) (Ξ» h, const_obj_eq_of_rel_of_rel _ h (hrelTT'.trans hT'β)),
hTββ.elim (Ξ» h, h βΈ this) (Ξ» h, const_eq_const_of_const_obj_eq obj h hobj i βΈ this)
lemma colg_mem_restricted_of_rel_self {T : tableau m n} (hrelTT : rel obj T T)
{c} (hc : c β pivot_col T obj) : T.to_partition.colg c β T.restricted :=
let β¨r, hrβ© := exists_mem_pivot_row_of_rel obj hrelTT hc in
let β¨T', c', hT', hrelTT', hrowcol, _, hr'β© := (rowg_eq_or_exists_mem_pivot_row obj
((eq_or_rel_pivot_of_rel _ hrelTT hc hr).elim
(Ξ» h, show rel obj T (T.pivot r c), from h βΈ hrelTT) id) _).resolve_left
(show (T.pivot r c).to_partition.rowg r β T.to_partition.rowg r, by simp) in
(restricted_eq_of_rel _ hrelTT').symm βΈ by convert (pivot_row_spec hr').2.1; simp [hrowcol]
lemma eq_zero_of_not_mem_restricted_of_rel_self {T : tableau m n} (hrelTT : rel obj T T)
{j} (hjres : T.to_partition.colg j β T.restricted) (hdead : j β T.dead) : T.to_matrix obj j = 0 :=
let β¨r, c, hc, hrβ© := exists_mem_pivot_row_col_of_rel obj hrelTT in
have hcres : T.to_partition.colg c β T.restricted,
from colg_mem_restricted_of_rel_self obj hrelTT hc,
by_contradiction $ Ξ» h0,
begin
simp [pivot_col] at hc,
cases h : fin.find (Ξ» c, T.to_matrix obj c β 0 β§ colg (T.to_partition) c β T.restricted
β§ c β T.dead),
{ simp [*, fin.find_eq_none_iff] at * },
{ rw h at hc, clear_aux_decl,
have := (fin.find_eq_some_iff.1 h).1,
simp * at * }
end
lemma rel.irrefl {obj : fin m} : β (T : tableau m n), Β¬ rel obj T T :=
Ξ» T1 hrelT1,
let β¨rT1 , cT1, hrT1, hcT1β© := exists_mem_pivot_row_col_of_rel obj hrelT1 in
let β¨t, htβ© := finset.max_of_mem
(show T1.to_partition.colg cT1 β univ.filter (Ξ» v, β (T' : tableau m n) (c : fin n),
rel obj T' T' β§ c β pivot_col T' obj β§ T'.to_partition.colg c = v),
by simp only [true_and, mem_filter, mem_univ, exists_and_distrib_left];
exact β¨T1, hrelT1, cT1, hrT1, rflβ©) in
let β¨_, T', c', hrelTT'', hcT', hctβ© := finset.mem_filter.1 (finset.mem_of_max ht) in
have htmax : β (s : fin (m + n)) (T : tableau m n),
rel obj T T β β (j : fin n), pivot_col T obj = some j β
T.to_partition.colg j = s β s β€ t,
by simpa using Ξ» s (h : s β _), finset.le_max_of_mem h ht,
let β¨r, hrT'β© := exists_mem_pivot_row_of_rel obj hrelTT'' hcT' in
have hrelTT''p : rel obj T' (T'.pivot r c'),
from (eq_or_rel_pivot_of_rel obj hrelTT'' hcT' hrT').elim (Ξ» h, h βΈ hrelTT'') id,
let β¨T, c, hTT', hrelT'T, hT'Tr, hc, hrβ© := (rowg_eq_or_exists_mem_pivot_row obj
hrelTT''p r).resolve_left (by simp) in
have hfT' : feasible T', from feasible_of_rel_left _ hrelTT'',
have hfT : feasible T, from feasible_of_rel_right _ hrelT'T,
have hrelT'pT' : rel obj (T'.pivot r c') T', from rel.pivot hfT' hcT' hrT',
have hrelTT' : rel obj T T', from hTT'.elim (Ξ» h, h.symm βΈ hrelT'pT') (Ξ» h, h.trans hrelT'pT'),
have hrelTT : rel obj T T, from hrelTT'.trans hrelT'T,
have hc't : T.to_partition.colg c β€ t, from htmax _ T hrelTT _ hc rfl,
have hoT'T : T'.const obj 0 = T.const obj 0, from const_obj_eq_of_rel_of_rel _ hrelT'T hrelTT',
have hfickle : β i, T.to_partition.rowg i β T'.to_partition.rowg i β T.const i 0 = 0,
from const_eq_zero_of_rowg_ne_of_rel_self obj hrelTT' hrelT'T,
have hobj : T.const obj 0 = T'.const obj 0, from const_obj_eq_of_rel_of_rel _ hrelTT' hrelT'T,
have hflat : T.flat = T'.flat, from flat_eq_of_rel obj hrelTT',
have hrobj : T.to_partition.rowg obj = T'.to_partition.rowg obj, from rowg_obj_eq_of_rel _ hrelTT',
have hs : T.to_partition.rowg r = T'.to_partition.colg c', by simpa using hT'Tr,
have hc'res : T'.to_partition.colg c' β T'.restricted,
from hs βΈ restricted_eq_of_rel _ hrelTT' βΈ (pivot_row_spec hr).2.1,
have hc'obj0 : 0 < T'.to_matrix obj c' β§ c' β T'.dead,
by simpa [hc'res] using pivot_col_spec hcT',
have hcres : T.to_partition.colg c β T.restricted,
from colg_mem_restricted_of_rel_self obj hrelTT hc,
have hcobj0 : 0 < to_matrix T obj c β§ c β T.dead,
by simpa [hcres] using pivot_col_spec hc,
have hrc0 : T.to_matrix r c < 0,
from inv_neg'.1 $ neg_of_mul_neg_left (pivot_row_spec hr).2.2.1 (le_of_lt hcobj0.1),
have nonpos_of_colg_ne : β j, T'.to_partition.colg j β T.to_partition.colg j β j β c' β
T'.to_matrix obj j β€ 0,
from Ξ» j hj hjc',
let β¨Tβ, hTββ© := (colg_eq_or_exists_mem_pivot_col obj hrelTT').resolve_left hj in
nonpos_of_lt_pivot_col hcT' hc'res
(dead_eq_of_rel_or_eq obj hTβ.1 βΈ (pivot_col_spec hTβ.2.2.2).2)
(lt_of_le_of_ne
(hct.symm βΈ hTβ.2.2.1 βΈ htmax _ Tβ (hTβ.1.elim (Ξ» h, h.symm βΈ hrelTT'')
(Ξ» h, h.trans (hrelT'T.trans hTβ.2.1))) _ hTβ.2.2.2 rfl)
(by rwa [ne.def, T'.to_partition.injective_colg.eq_iff])),
have nonpos_of_colg_eq : β j, j β c' β
T'.to_partition.colg j = T.to_partition.colg c β T'.to_matrix obj j β€ 0,
from Ξ» j hjc' hj,
if hjc : j = c
then by clear_aux_decl; subst j; exact nonpos_of_lt_pivot_col hcT' hc'res
(dead_eq_of_rel obj hrelTT' βΈ hcobj0.2)
(lt_of_le_of_ne
(hj.symm βΈ hct.symm βΈ htmax _ _ hrelTT _ hc rfl)
(hs βΈ hj.symm βΈ colg_ne_rowg _ _ _))
else let β¨Tβ, hTββ© := (colg_eq_or_exists_mem_pivot_col obj hrelTT').resolve_left
(show T'.to_partition.colg j β T.to_partition.colg j,
by simpa [hj, T.to_partition.injective_colg.eq_iff, eq_comm] using hjc) in
nonpos_of_lt_pivot_col hcT' hc'res
(dead_eq_of_rel_or_eq obj hTβ.1 βΈ (pivot_col_spec hTβ.2.2.2).2)
(lt_of_le_of_ne
(hct.symm βΈ hTβ.2.2.1 βΈ htmax _ Tβ (hTβ.1.elim (Ξ» h, h.symm βΈ hrelTT'')
(Ξ» h, h.trans (hrelT'T.trans hTβ.2.1))) _ hTβ.2.2.2 rfl)
(by rwa [ne.def, T'.to_partition.injective_colg.eq_iff])),
have unique_row : β i β r, T.const i 0 = 0 β T.to_partition.rowg i β T'.to_partition.rowg i β
0 β€ T.to_matrix i c,
from Ξ» i hir hi0 hrow,
let β¨Tβ, cβ, hcβ, hrowβ, hrelTβT, hrelTTββ© :=
exists_mem_pivot_col_of_rowg_ne _ hrelTT' hrelT'T hrow in
have hrelTβTβ : rel obj Tβ Tβ, from hrelTβT.trans hrelTTβ,
nonneg_of_lt_pivot_row (by exact hcobj0.1)
(by rw [β hrowβ, β restricted_eq_of_rel _ hrelTβT];
exact colg_mem_restricted_of_rel_self _ hrelTβTβ hcβ) hc hr hi0
(lt_of_le_of_ne (by rw [hs, hct, β hrowβ]; exact htmax _ _ hrelTβTβ _ hcβ rfl)
(by simpa [T.to_partition.injective_rowg.eq_iff])),
not_unique_row_and_unique_col obj hcobj0.1 hc'obj0.1 hrc0 hflat hs hrobj hfickle hobj
nonpos_of_colg_ne nonpos_of_colg_eq unique_row
noncomputable instance fintype_rel (T : tableau m n) : fintype {T' | rel obj T' T} :=
fintype.of_injective (Ξ» T', T'.val.to_partition)
(Ξ» Tβ Tβ h, subtype.eq $ tableau.ext
(by rw [flat_eq_of_rel _ Tβ.2, flat_eq_of_rel _ Tβ.2]) h
(by rw [dead_eq_of_rel _ Tβ.2, dead_eq_of_rel _ Tβ.2])
(by rw [restricted_eq_of_rel _ Tβ.2, restricted_eq_of_rel _ Tβ.2]))
lemma rel_wf (m n : β) (obj : fin m): well_founded (@rel m n obj) :=
subrelation.wf
(show subrelation (@rel m n obj) (measure (Ξ» T, fintype.card {T' | rel obj T' T})),
from assume Tβ Tβ h,
set.card_lt_card (set.ssubset_iff_subset_not_subset.2 β¨Ξ» T' hT', hT'.trans h,
classical.not_forall.2 β¨Tβ, Ξ» h', rel.irrefl _ (h' h)β©β©))
(measure_wf (Ξ» T, fintype.card {T' | rel obj T' T}))
end blands_rule
@[derive _root_.decidable_eq] inductive termination : Type
| while : termination
| unbounded : termination
| optimal : termination
open termination
instance : has_repr termination := β¨Ξ» t, termination.cases_on t "while" "unbounded" "optimal"β©
instance : fintype termination := β¨β¨quotient.mk [while, unbounded, optimal], dec_trivialβ©,
Ξ» x, by cases x; exact dec_trivialβ©
open termination
/-- The simplex algorithm -/
def simplex (w : tableau m n β bool) (obj : fin m) : Ξ (T : tableau m n) (hT : feasible T),
tableau m n Γ termination
| T := Ξ» hT, cond (w T)
(match pivot_col T obj, @feasible_of_mem_pivot_row_and_col _ _ _ obj hT,
@rel.pivot m n obj _ hT with
| none, hc, hrel := (T, optimal)
| some c, hc, hrel :=
match pivot_row T obj c, @hc _ rfl, (Ξ» r, @hrel r c rfl) with
| none, hr, hrel := (T, unbounded)
| some r, hr, hrel := have wf : rel obj (pivot T r c) T, from hrel _ rfl,
simplex (T.pivot r c) (hr rfl)
end
end)
(T, while)
using_well_founded {rel_tac := Ξ» _ _, `[exact β¨_, rel_wf m n objβ©],
dec_tac := tactic.assumption}
lemma simplex_pivot {w : tableau m n β bool} {T : tableau m n} (hT : feasible T)
(hw : w T = tt) {obj : fin m} {r : fin m} {c : fin n}
(hc : c β pivot_col T obj) (hr : r β pivot_row T obj c) :
(T.pivot r c).simplex w obj (feasible_of_mem_pivot_row_and_col hT hc hr) =
T.simplex w obj hT :=
by conv_rhs { rw simplex };
simp [hw, show _ = _, from hr, show _ = _, from hc, simplex._match_1, simplex._match_2]
lemma simplex_spec_aux (w : tableau m n β bool) (obj : fin m) :
Ξ (T : tableau m n) (hT : feasible T),
((T.simplex w obj hT).2 = while β§ w (T.simplex w obj hT).1 = ff) β¨
((T.simplex w obj hT).2 = optimal β§ w (T.simplex w obj hT).1 = tt β§
pivot_col (T.simplex w obj hT).1 obj = none) β¨
((T.simplex w obj hT).2 = unbounded β§ w (T.simplex w obj hT).1 = tt β§
β c, c β pivot_col (T.simplex w obj hT).1 obj β§
pivot_row (T.simplex w obj hT).1 obj c = none)
| T := Ξ» hT,
begin
cases hw : w T,
{ rw simplex, simp [hw] },
{ cases hc : pivot_col T obj with c,
{ rw simplex, simp [hc, hw, simplex._match_1] },
{ cases hr : pivot_row T obj c with r,
{ rw simplex, simp [hr, hc, hw, simplex._match_1, simplex._match_2] },
{ rw [β simplex_pivot hT hw hc hr],
exact have wf : rel obj (T.pivot r c) T, from rel.pivot hT hc hr,
simplex_spec_aux _ _ } } }
end
using_well_founded {rel_tac := Ξ» _ _, `[exact β¨_, rel_wf m n objβ©],
dec_tac := tactic.assumption}
lemma simplex_while_eq_ff {w : tableau m n β bool} {T : tableau m n} {hT : feasible T}
{obj : fin m} (hw : w T = ff) : T.simplex w obj hT = (T, while) :=
by rw [simplex, hw]; refl
lemma simplex_pivot_col_eq_none {w : tableau m n β bool} {T : tableau m n} {hT : feasible T}
(hw : w T = tt) {obj : fin m} (hc : pivot_col T obj = none) :
T.simplex w obj hT = (T, optimal) :=
by rw simplex; simp [hc, hw, simplex._match_1]
lemma simplex_pivot_row_eq_none {w : tableau m n β bool} {T : tableau m n} {hT : feasible T}
{obj : fin m} (hw : w T = tt) {c} (hc : c β pivot_col T obj)
(hr : pivot_row T obj c = none) : T.simplex w obj hT = (T, unbounded) :=
by rw simplex; simp [hw, show _ = _, from hc, hr, simplex._match_1, simplex._match_2]
lemma simplex_induction (P : tableau m n β Prop) (w : tableau m n β bool) (obj : fin m):
Ξ {T : tableau m n} (hT : feasible T) (h0 : P T)
(hpivot : β {T' r c}, w T' = tt β c β pivot_col T' obj β r β pivot_row T' obj c
β feasible T' β P T' β P (T'.pivot r c)),
P (T.simplex w obj hT).1
| T := Ξ» hT h0 hpivot,
begin
cases hw : w T,
{ rwa [simplex_while_eq_ff hw] },
{ cases hc : pivot_col T obj with c,
{ rwa [simplex_pivot_col_eq_none hw hc] },
{ cases hr : pivot_row T obj c with r,
{ rwa simplex_pivot_row_eq_none hw hc hr },
{ rw [β simplex_pivot _ hw hc hr],
exact have wf : rel obj (pivot T r c) T, from rel.pivot hT hc hr,
simplex_induction (feasible_of_mem_pivot_row_and_col hT hc hr)
(hpivot hw hc hr hT h0) @hpivot } } }
end
using_well_founded {rel_tac := Ξ» _ _, `[exact β¨_, rel_wf m n objβ©],
dec_tac := `[tauto]}
@[simp] lemma feasible_simplex {w : tableau m n β bool} {T : tableau m n}
{hT : feasible T} {obj : fin m} : feasible (T.simplex w obj hT).1 :=
simplex_induction feasible _ _ hT hT
(Ξ» _ _ _ _ hc hr _ hT', feasible_of_mem_pivot_row_and_col hT' hc hr)
@[simp] lemma simplex_simplex {w : tableau m n β bool} {T : tableau m n} {hT : feasible T}
{obj : fin m} : (T.simplex w obj hT).1.simplex w obj feasible_simplex = T.simplex w obj hT :=
simplex_induction (Ξ» T', β (hT' : feasible T'), T'.simplex w obj hT' = T.simplex w obj hT) w _ _
(Ξ» _, rfl) (Ξ» T' r c hw hc hr hT' ih hpivot, by rw [simplex_pivot hT' hw hc hr, ih]) _
/-- `simplex` does not move the row variable it is trying to maximise. -/
@[simp] lemma rowg_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n β bool)
(obj : fin m) : (T.simplex w obj hT).1.to_partition.rowg obj = T.to_partition.rowg obj :=
simplex_induction (Ξ» T', T'.to_partition.rowg obj = T.to_partition.rowg obj) _ _ _ rfl
(Ξ» T' r c hw hc hr, by simp [rowg_swap_of_ne _ (pivot_row_spec hr).1])
@[simp] lemma colg_simplex_of_dead_aux {T : tableau m n} {hT : feasible T} {w : tableau m n β bool}
{obj : fin m} {c' : fin n} : c' β (T.simplex w obj hT).1.dead β
(T.simplex w obj hT).1.to_partition.colg c' = T.to_partition.colg c' :=
simplex_induction (Ξ» T', c' β T'.dead β T'.to_partition.colg c' = T.to_partition.colg c') _ obj _
(Ξ» _, rfl)
(Ξ» T' r c hw hc hr hfT' ih hdead,
have c' β c, from Ξ» hcc, (pivot_col_spec hc).2 (by simp * at *),
by simp [colg_swap_of_ne _ this, ih hdead])
@[simp] lemma flat_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n β bool)
(obj : fin m) : (T.simplex w obj hT).1.flat = T.flat :=
simplex_induction (Ξ» T', T'.flat = T.flat) w obj _ rfl
(Ξ» T' r c hw hc hr hT' ih,
have T'.to_matrix r c β 0,
from Ξ» h, by simpa [h, lt_irrefl] using pivot_row_spec hr,
by rw [flat_pivot this, ih])
@[simp] lemma restricted_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n β bool)
(obj : fin m) : (T.simplex w obj hT).1.restricted = T.restricted :=
simplex_induction (Ξ» T', T'.restricted = T.restricted) _ _ _ rfl (by simp { contextual := tt })
@[simp] lemma dead_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n β bool)
(obj : fin m) : (T.simplex w obj hT).1.dead = T.dead :=
simplex_induction (Ξ» T', T'.dead = T.dead) _ _ _ rfl (by simp { contextual := tt })
@[simp] lemma res_set_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n β bool)
(obj : fin m) : (T.simplex w obj hT).1.res_set = T.res_set :=
simplex_induction (Ξ» T', T'.res_set = T.res_set) w obj _ rfl
(Ξ» T' r c hw hc hr, by simp [res_set_pivot (ne_zero_of_mem_pivot_row hr)] {contextual := tt})
@[simp] lemma dead_set_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n β bool)
(obj : fin m) : (T.simplex w obj hT).1.dead_set = T.dead_set :=
simplex_induction (Ξ» T', T'.dead_set = T.dead_set) w obj _ rfl
(Ξ» T' r c hw hc hr,
by simp [dead_set_pivot (ne_zero_of_mem_pivot_row hr) (pivot_col_spec hc).2] {contextual := tt})
@[simp] lemma sol_set_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n β bool)
(obj : fin m) : (T.simplex w obj hT).1.sol_set = T.sol_set :=
by simp [sol_set_eq_res_set_inter_dead_set]
@[simp] lemma of_col_simplex_zero_mem_sol_set {w : tableau m n β bool} {T : tableau m n}
{hT : feasible T} {obj : fin m} : (T.simplex w obj hT).1.of_col 0 β sol_set T :=
by rw [β sol_set_simplex, of_col_zero_mem_sol_set_iff]; exact feasible_simplex
@[simp] lemma of_col_simplex_rowg {w : tableau m n β bool} {T : tableau m n}
{hT : feasible T} {obj : fin m} (x : cvec n) :
(T.simplex w obj hT).1.of_col x (T.to_partition.rowg obj) =
((T.simplex w obj hT).1.to_matrix β¬ x + (T.simplex w obj hT).1.const) obj :=
by rw [β of_col_rowg (T.simplex w obj hT).1 x obj, rowg_simplex]
@[simp] lemma is_unbounded_above_simplex {T : tableau m n} {hT : feasible T} {w : tableau m n β bool}
{obj : fin m} {v : fin (m + n)} : is_unbounded_above (T.simplex w obj hT).1 v β
is_unbounded_above T v := by simp [is_unbounded_above]
@[simp] lemma is_optimal_simplex {T : tableau m n} {hT : feasible T} {w : tableau m n β bool}
{obj : fin m} {x : cvec (m + n)} {v : fin (m + n)} : is_optimal (T.simplex w obj hT).1 x v β
is_optimal T x v := by simp [is_optimal]
lemma termination_eq_while_iff {T : tableau m n} {hT : feasible T} {w : tableau m n β bool}
{obj : fin m} : (T.simplex w obj hT).2 = while β w (T.simplex w obj hT).1 = ff :=
by have := simplex_spec_aux w obj T hT; finish
lemma termination_eq_optimal_iff_pivot_col_eq_none {T : tableau m n}
{hT : feasible T} {w : tableau m n β bool} {obj : fin m} : (T.simplex w obj hT).2 = optimal β
w (T.simplex w obj hT).1 = tt β§ pivot_col (T.simplex w obj hT).1 obj = none :=
by have := simplex_spec_aux w obj T hT; finish
lemma termination_eq_unbounded_iff_pivot_row_eq_none {T : tableau m n} {hT : feasible T}
{w : tableau m n β bool} {obj : fin m} : (T.simplex w obj hT).2 = unbounded β
w (T.simplex w obj hT).1 = tt β§ β c, c β pivot_col (T.simplex w obj hT).1 obj β§
pivot_row (T.simplex w obj hT).1 obj c = none :=
by have := simplex_spec_aux w obj T hT; finish
lemma termination_eq_unbounded_iff_aux {T : tableau m n} {hT : feasible T}
{w : tableau m n β bool} {obj : fin m} : (T.simplex w obj hT).2 = unbounded β
w (T.simplex w obj hT).1 = tt β§
is_unbounded_above T (T.to_partition.rowg obj) :=
begin
rw termination_eq_unbounded_iff_pivot_row_eq_none,
rintros β¨_, c, hcβ©,
simpa * using pivot_row_eq_none feasible_simplex hc.2 hc.1
end
lemma termination_eq_optimal_iff {T : tableau m n} {hT : feasible T}
{w : tableau m n β bool} {obj : fin m} : (T.simplex w obj hT).2 = optimal β
w (T.simplex w obj hT).1 = tt β§
is_optimal T ((T.simplex w obj hT).1.of_col 0) (T.to_partition.rowg obj) :=
begin
rw [termination_eq_optimal_iff_pivot_col_eq_none],
split,
{ rintros β¨_, hcβ©,
simpa * using pivot_col_eq_none feasible_simplex hc },
{ cases ht : (T.simplex w obj hT).2,
{ simp [*, termination_eq_while_iff] at * },
{ cases termination_eq_unbounded_iff_aux ht,
simp [*, not_optimal_of_unbounded_above right] },
{ simp [*, termination_eq_optimal_iff_pivot_col_eq_none] at * } }
end
lemma termination_eq_unbounded_iff {T : tableau m n} {hT : feasible T}
{w : tableau m n β bool} {obj : fin m} : (T.simplex w obj hT).2 = unbounded β
w (T.simplex w obj hT).1 = tt β§ is_unbounded_above T (T.to_partition.rowg obj) :=
β¨termination_eq_unbounded_iff_aux,
begin
have := @not_optimal_of_unbounded_above m n (T.simplex w obj hT).1 (T.to_partition.rowg obj)
((T.simplex w obj hT).1.of_col 0),
cases ht : (T.simplex w obj hT).2;
simp [termination_eq_optimal_iff, termination_eq_while_iff, *] at *
endβ©
end tableau
|
60496af9a7df5cf67e726ad85e7c948c7cffdcb0 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/group_theory/free_group.lean | bf1a9fd72c30a7759a5635ad2099dbfb530f25c4 | [
"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 | 32,569 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import data.fintype.basic
import group_theory.subgroup.basic
/-!
# Free groups
This file defines free groups over a type. Furthermore, it is shown that the free group construction
is an instance of a monad. For the result that `free_group` is the left adjoint to the forgetful
functor from groups to types, see `algebra/category/Group/adjunctions`.
## Main definitions
* `free_group`: the free group associated to a type `Ξ±` defined as the words over `a : Ξ± Γ bool `
modulo the relation `a * x * xβ»ΒΉ * b = a * b`.
* `mk`: the canonical quotient map `list (Ξ± Γ bool) β free_group Ξ±`.
* `of`: the canoical injection `Ξ± β free_group Ξ±`.
* `lift f`: the canonical group homomorphism `free_group Ξ± β* G` given a group `G` and a
function `f : Ξ± β G`.
## Main statements
* `church_rosser`: The Church-Rosser theorem for word reduction (also known as Newman's diamond
lemma).
* `free_group_unit_equiv_int`: The free group over the one-point type is isomorphic to the integers.
* The free group construction is an instance of a monad.
## Implementation details
First we introduce the one step reduction relation `free_group.red.step`:
`w * x * xβ»ΒΉ * v ~> w * v`, its reflexive transitive closure `free_group.red.trans`
and prove that its join is an equivalence relation. Then we introduce `free_group Ξ±` as a quotient
over `free_group.red.step`.
## Tags
free group, Newman's diamond lemma, Church-Rosser theorem
-/
open relation
universes u v w
variables {Ξ± : Type u}
local attribute [simp] list.append_eq_has_append
namespace free_group
variables {L Lβ Lβ Lβ Lβ : list (Ξ± Γ bool)}
/-- Reduction step: `w * x * xβ»ΒΉ * v ~> w * v` -/
inductive red.step : list (Ξ± Γ bool) β list (Ξ± Γ bool) β Prop
| bnot {Lβ Lβ x b} : red.step (Lβ ++ (x, b) :: (x, bnot b) :: Lβ) (Lβ ++ Lβ)
attribute [simp] red.step.bnot
/-- Reflexive-transitive closure of red.step -/
def red : list (Ξ± Γ bool) β list (Ξ± Γ bool) β Prop := refl_trans_gen red.step
@[refl] lemma red.refl : red L L := refl_trans_gen.refl
@[trans] lemma red.trans : red Lβ Lβ β red Lβ Lβ β red Lβ Lβ := refl_trans_gen.trans
namespace red
/-- Predicate asserting that word `wβ` can be reduced to `wβ` in one step, i.e. there are words
`wβ wβ` and letter `x` such that `wβ = wβxxβ»ΒΉwβ` and `wβ = wβwβ` -/
theorem step.length : β {Lβ Lβ : list (Ξ± Γ bool)}, step Lβ Lβ β Lβ.length + 2 = Lβ.length
| _ _ (@red.step.bnot _ L1 L2 x b) := by rw [list.length_append, list.length_append]; refl
@[simp] lemma step.bnot_rev {x b} : step (Lβ ++ (x, bnot b) :: (x, b) :: Lβ) (Lβ ++ Lβ) :=
by cases b; from step.bnot
@[simp] lemma step.cons_bnot {x b} : red.step ((x, b) :: (x, bnot b) :: L) L :=
@step.bnot _ [] _ _ _
@[simp] lemma step.cons_bnot_rev {x b} : red.step ((x, bnot b) :: (x, b) :: L) L :=
@red.step.bnot_rev _ [] _ _ _
theorem step.append_left : β {Lβ Lβ Lβ : list (Ξ± Γ bool)}, step Lβ Lβ β step (Lβ ++ Lβ) (Lβ ++ Lβ)
| _ _ _ red.step.bnot := by rw [β list.append_assoc, β list.append_assoc]; constructor
theorem step.cons {x} (H : red.step Lβ Lβ) : red.step (x :: Lβ) (x :: Lβ) :=
@step.append_left _ [x] _ _ H
theorem step.append_right : β {Lβ Lβ Lβ : list (Ξ± Γ bool)}, step Lβ Lβ β step (Lβ ++ Lβ) (Lβ ++ Lβ)
| _ _ _ red.step.bnot := by simp
lemma not_step_nil : Β¬ step [] L :=
begin
generalize h' : [] = L',
assume h,
cases h with Lβ Lβ,
simp [list.nil_eq_append_iff] at h',
contradiction
end
lemma step.cons_left_iff {a : Ξ±} {b : bool} :
step ((a, b) :: Lβ) Lβ β (βL, step Lβ L β§ Lβ = (a, b) :: L) β¨ (Lβ = (a, bnot b)::Lβ) :=
begin
split,
{ generalize hL : ((a, b) :: Lβ : list _) = L,
assume h,
rcases h with β¨_ | β¨p, s'β©, e, a', b'β©,
{ simp at hL, simp [*] },
{ simp at hL,
rcases hL with β¨rfl, rflβ©,
refine or.inl β¨s' ++ e, step.bnot, _β©,
simp } },
{ assume h,
rcases h with β¨L, h, rflβ© | rfl,
{ exact step.cons h },
{ exact step.cons_bnot } }
end
lemma not_step_singleton : β {p : Ξ± Γ bool}, Β¬ step [p] L
| (a, b) := by simp [step.cons_left_iff, not_step_nil]
lemma step.cons_cons_iff : β{p : Ξ± Γ bool}, step (p :: Lβ) (p :: Lβ) β step Lβ Lβ :=
by simp [step.cons_left_iff, iff_def, or_imp_distrib] {contextual := tt}
lemma step.append_left_iff : βL, step (L ++ Lβ) (L ++ Lβ) β step Lβ Lβ
| [] := by simp
| (p :: l) := by simp [step.append_left_iff l, step.cons_cons_iff]
private theorem step.diamond_aux : β {Lβ Lβ Lβ Lβ : list (Ξ± Γ bool)} {x1 b1 x2 b2},
Lβ ++ (x1, b1) :: (x1, bnot b1) :: Lβ = Lβ ++ (x2, b2) :: (x2, bnot b2) :: Lβ β
Lβ ++ Lβ = Lβ ++ Lβ β¨ β Lβ
, red.step (Lβ ++ Lβ) Lβ
β§ red.step (Lβ ++ Lβ) Lβ
| [] _ [] _ _ _ _ _ H := by injections; subst_vars; simp
| [] _ [(x3,b3)] _ _ _ _ _ H := by injections; subst_vars; simp
| [(x3,b3)] _ [] _ _ _ _ _ H := by injections; subst_vars; simp
| [] _ ((x3,b3)::(x4,b4)::tl) _ _ _ _ _ H :=
by injections; subst_vars; simp; right; exact β¨_, red.step.bnot, red.step.cons_bnotβ©
| ((x3,b3)::(x4,b4)::tl) _ [] _ _ _ _ _ H :=
by injections; subst_vars; simp; right; exact β¨_, red.step.cons_bnot, red.step.bnotβ©
| ((x3,b3)::tl) _ ((x4,b4)::tl2) _ _ _ _ _ H :=
let β¨H1, H2β© := list.cons.inj H in
match step.diamond_aux H2 with
| or.inl H3 := or.inl $ by simp [H1, H3]
| or.inr β¨Lβ
, H3, H4β© := or.inr
β¨_, step.cons H3, by simpa [H1] using step.cons H4β©
end
theorem step.diamond : β {Lβ Lβ Lβ Lβ : list (Ξ± Γ bool)},
red.step Lβ Lβ β red.step Lβ Lβ β Lβ = Lβ β
Lβ = Lβ β¨ β Lβ
, red.step Lβ Lβ
β§ red.step Lβ Lβ
| _ _ _ _ red.step.bnot red.step.bnot H := step.diamond_aux H
lemma step.to_red : step Lβ Lβ β red Lβ Lβ :=
refl_trans_gen.single
/-- **Church-Rosser theorem** for word reduction: If `w1 w2 w3` are words such that `w1` reduces
to `w2` and `w3` respectively, then there is a word `w4` such that `w2` and `w3` reduce to `w4`
respectively. This is also known as Newman's diamond lemma. -/
theorem church_rosser : red Lβ Lβ β red Lβ Lβ β join red Lβ Lβ :=
relation.church_rosser (assume a b c hab hac,
match b, c, red.step.diamond hab hac rfl with
| b, _, or.inl rfl := β¨b, by refl, by reflβ©
| b, c, or.inr β¨d, hbd, hcdβ© := β¨d, refl_gen.single hbd, hcd.to_redβ©
end)
lemma cons_cons {p} : red Lβ Lβ β red (p :: Lβ) (p :: Lβ) :=
refl_trans_gen.lift (list.cons p) (assume a b, step.cons)
lemma cons_cons_iff (p) : red (p :: Lβ) (p :: Lβ) β red Lβ Lβ :=
iff.intro
begin
generalize eqβ : (p :: Lβ : list _) = LLβ,
generalize eqβ : (p :: Lβ : list _) = LLβ,
assume h,
induction h using relation.refl_trans_gen.head_induction_on
with Lβ Lβ hββ h ih
generalizing Lβ Lβ,
{ subst_vars, cases eqβ, constructor },
{ subst_vars,
cases p with a b,
rw [step.cons_left_iff] at hββ,
rcases hββ with β¨L, hββ, rflβ© | rfl,
{ exact (ih rfl rfl).head hββ },
{ exact (cons_cons h).tail step.cons_bnot_rev } }
end
cons_cons
lemma append_append_left_iff : βL, red (L ++ Lβ) (L ++ Lβ) β red Lβ Lβ
| [] := iff.rfl
| (p :: L) := by simp [append_append_left_iff L, cons_cons_iff]
lemma append_append (hβ : red Lβ Lβ) (hβ : red Lβ Lβ) : red (Lβ ++ Lβ) (Lβ ++ Lβ) :=
(hβ.lift (Ξ»L, L ++ Lβ) (assume a b, step.append_right)).trans ((append_append_left_iff _).2 hβ)
lemma to_append_iff : red L (Lβ ++ Lβ) β (βLβ Lβ, L = Lβ ++ Lβ β§ red Lβ Lβ β§ red Lβ Lβ) :=
iff.intro
begin
generalize eq : Lβ ++ Lβ = Lββ,
assume h,
induction h with L' Lββ hLL' h ih generalizing Lβ Lβ,
{ exact β¨_, _, eq.symm, by refl, by reflβ© },
{ cases h with s e a b,
rcases list.append_eq_append_iff.1 eq with β¨s', rfl, rflβ© | β¨e', rfl, rflβ©,
{ have : Lβ ++ (s' ++ ((a, b) :: (a, bnot b) :: e)) =
(Lβ ++ s') ++ ((a, b) :: (a, bnot b) :: e),
{ simp },
rcases ih this with β¨wβ, wβ, rfl, hβ, hββ©,
exact β¨wβ, wβ, rfl, hβ, hβ.tail step.bnotβ© },
{ have : (s ++ ((a, b) :: (a, bnot b) :: e')) ++ Lβ =
s ++ ((a, b) :: (a, bnot b) :: (e' ++ Lβ)),
{ simp },
rcases ih this with β¨wβ, wβ, rfl, hβ, hββ©,
exact β¨wβ, wβ, rfl, hβ.tail step.bnot, hββ© }, }
end
(assume β¨Lβ, Lβ, eq, hβ, hββ©, eq.symm βΈ append_append hβ hβ)
/-- The empty word `[]` only reduces to itself. -/
theorem nil_iff : red [] L β L = [] :=
refl_trans_gen_iff_eq (assume l, red.not_step_nil)
/-- A letter only reduces to itself. -/
theorem singleton_iff {x} : red [x] Lβ β Lβ = [x] :=
refl_trans_gen_iff_eq (assume l, not_step_singleton)
/-- If `x` is a letter and `w` is a word such that `xw` reduces to the empty word, then `w` reduces
to `xβ»ΒΉ` -/
theorem cons_nil_iff_singleton {x b} : red ((x, b) :: L) [] β red L [(x, bnot b)] :=
iff.intro
(assume h,
have hβ : red ((x, bnot b) :: (x, b) :: L) [(x, bnot b)], from cons_cons h,
have hβ : red ((x, bnot b) :: (x, b) :: L) L, from refl_trans_gen.single step.cons_bnot_rev,
let β¨L', hβ, hββ© := church_rosser hβ hβ in
by rw [singleton_iff] at hβ; subst L'; assumption)
(assume h, (cons_cons h).tail step.cons_bnot)
theorem red_iff_irreducible {x1 b1 x2 b2} (h : (x1, b1) β (x2, b2)) :
red [(x1, bnot b1), (x2, b2)] L β L = [(x1, bnot b1), (x2, b2)] :=
begin
apply refl_trans_gen_iff_eq,
generalize eq : [(x1, bnot b1), (x2, b2)] = L',
assume L h',
cases h',
simp [list.cons_eq_append_iff, list.nil_eq_append_iff] at eq,
rcases eq with β¨rfl, β¨rfl, rflβ©, β¨rfl, rflβ©, rflβ©, subst_vars,
simp at h,
contradiction
end
/-- If `x` and `y` are distinct letters and `wβ wβ` are words such that `xwβ` reduces to `ywβ`, then
`wβ` reduces to `xβ»ΒΉywβ`. -/
theorem inv_of_red_of_ne {x1 b1 x2 b2}
(H1 : (x1, b1) β (x2, b2))
(H2 : red ((x1, b1) :: Lβ) ((x2, b2) :: Lβ)) :
red Lβ ((x1, bnot b1) :: (x2, b2) :: Lβ) :=
begin
have : red ((x1, b1) :: Lβ) ([(x2, b2)] ++ Lβ), from H2,
rcases to_append_iff.1 this with β¨_ | β¨p, Lββ©, Lβ, eq, hβ, hββ©,
{ simp [nil_iff] at hβ, contradiction },
{ cases eq,
show red (Lβ ++ Lβ) ([(x1, bnot b1), (x2, b2)] ++ Lβ),
apply append_append _ hβ,
have hβ : red ((x1, bnot b1) :: (x1, b1) :: Lβ) [(x1, bnot b1), (x2, b2)],
{ exact cons_cons hβ },
have hβ : red ((x1, bnot b1) :: (x1, b1) :: Lβ) Lβ,
{ exact step.cons_bnot_rev.to_red },
rcases church_rosser hβ hβ with β¨L', hβ, hββ©,
rw [red_iff_irreducible H1] at hβ,
rwa [hβ] at hβ }
end
theorem step.sublist (H : red.step Lβ Lβ) : Lβ <+ Lβ :=
by cases H; simp; constructor; constructor; refl
/-- If `wβ wβ` are words such that `wβ` reduces to `wβ`, then `wβ` is a sublist of `wβ`. -/
theorem sublist : red Lβ Lβ β Lβ <+ Lβ :=
refl_trans_gen_of_transitive_reflexive
(Ξ»l, list.sublist.refl l) (Ξ»a b c hab hbc, list.sublist.trans hbc hab) (Ξ»a b, red.step.sublist)
theorem sizeof_of_step : β {Lβ Lβ : list (Ξ± Γ bool)}, step Lβ Lβ β Lβ.sizeof < Lβ.sizeof
| _ _ (@step.bnot _ L1 L2 x b) :=
begin
induction L1 with hd tl ih,
case list.nil
{ dsimp [list.sizeof],
have H : 1 + sizeof (x, b) + (1 + sizeof (x, bnot b) + list.sizeof L2)
= (list.sizeof L2 + 1) + (sizeof (x, b) + sizeof (x, bnot b) + 1),
{ ac_refl },
rw H,
exact nat.le_add_right _ _ },
case list.cons
{ dsimp [list.sizeof],
exact nat.add_lt_add_left ih _ }
end
theorem length (h : red Lβ Lβ) : β n, Lβ.length = Lβ.length + 2 * n :=
begin
induction h with Lβ Lβ hββ hββ ih,
{ exact β¨0, rflβ© },
{ rcases ih with β¨n, eqβ©,
existsi (1 + n),
simp [mul_add, eq, (step.length hββ).symm, add_assoc] }
end
theorem antisymm (hββ : red Lβ Lβ) : red Lβ Lβ β Lβ = Lβ :=
match Lβ, hββ.cases_head with
| _, or.inl rfl := assume h, rfl
| Lβ, or.inr β¨Lβ, hββ, hβββ© := assume hββ,
let β¨n, eqβ© := length (hββ.trans hββ) in
have list.length Lβ + 0 = list.length Lβ + (2 * n + 2),
by simpa [(step.length hββ).symm, add_comm, add_assoc] using eq,
(nat.no_confusion $ nat.add_left_cancel this)
end
end red
theorem equivalence_join_red : equivalence (join (@red Ξ±)) :=
equivalence_join_refl_trans_gen $ assume a b c hab hac,
(match b, c, red.step.diamond hab hac rfl with
| b, _, or.inl rfl := β¨b, by refl, by reflβ©
| b, c, or.inr β¨d, hbd, hcdβ© := β¨d, refl_gen.single hbd, refl_trans_gen.single hcdβ©
end)
theorem join_red_of_step (h : red.step Lβ Lβ) : join red Lβ Lβ :=
join_of_single reflexive_refl_trans_gen h.to_red
theorem eqv_gen_step_iff_join_red : eqv_gen red.step Lβ Lβ β join red Lβ Lβ :=
iff.intro
(assume h,
have eqv_gen (join red) Lβ Lβ := h.mono (assume a b, join_red_of_step),
equivalence_join_red.eqv_gen_iff.1 this)
(join_of_equivalence (eqv_gen.is_equivalence _) $ assume a b,
refl_trans_gen_of_equivalence (eqv_gen.is_equivalence _) eqv_gen.rel)
end free_group
/-- The free group over a type, i.e. the words formed by the elements of the type and their formal
inverses, quotient by one step reduction. -/
def free_group (Ξ± : Type u) : Type u :=
quot $ @free_group.red.step Ξ±
namespace free_group
variables {Ξ±} {L Lβ Lβ Lβ Lβ : list (Ξ± Γ bool)}
/-- The canonical map from `list (Ξ± Γ bool)` to the free group on `Ξ±`. -/
def mk (L) : free_group Ξ± := quot.mk red.step L
@[simp] lemma quot_mk_eq_mk : quot.mk red.step L = mk L := rfl
@[simp] lemma quot_lift_mk (Ξ² : Type v) (f : list (Ξ± Γ bool) β Ξ²)
(H : β Lβ Lβ, red.step Lβ Lβ β f Lβ = f Lβ) :
quot.lift f H (mk L) = f L := rfl
@[simp] lemma quot_lift_on_mk (Ξ² : Type v) (f : list (Ξ± Γ bool) β Ξ²)
(H : β Lβ Lβ, red.step Lβ Lβ β f Lβ = f Lβ) :
quot.lift_on (mk L) f H = f L := rfl
instance : has_one (free_group Ξ±) := β¨mk []β©
lemma one_eq_mk : (1 : free_group Ξ±) = mk [] := rfl
instance : inhabited (free_group Ξ±) := β¨1β©
instance : has_mul (free_group Ξ±) :=
β¨Ξ» x y, quot.lift_on x
(Ξ» Lβ, quot.lift_on y (Ξ» Lβ, mk $ Lβ ++ Lβ) (Ξ» Lβ Lβ H, quot.sound $ red.step.append_left H))
(Ξ» Lβ Lβ H, quot.induction_on y $ Ξ» Lβ, quot.sound $ red.step.append_right H)β©
@[simp] lemma mul_mk : mk Lβ * mk Lβ = mk (Lβ ++ Lβ) := rfl
instance : has_inv (free_group Ξ±) :=
β¨Ξ»x, quot.lift_on x (Ξ» L, mk (L.map $ Ξ» x : Ξ± Γ bool, (x.1, bnot x.2)).reverse)
(assume a b h, quot.sound $ by cases h; simp)β©
@[simp] lemma inv_mk : (mk L)β»ΒΉ = mk (L.map $ Ξ» x : Ξ± Γ bool, (x.1, bnot x.2)).reverse := rfl
instance : group (free_group Ξ±) :=
{ mul := (*),
one := 1,
inv := has_inv.inv,
mul_assoc := by rintros β¨Lββ© β¨Lββ© β¨Lββ©; simp,
one_mul := by rintros β¨Lβ©; refl,
mul_one := by rintros β¨Lβ©; simp [one_eq_mk],
mul_left_inv := by rintros β¨Lβ©; exact (list.rec_on L rfl $
Ξ» β¨x, bβ© tl ih, eq.trans (quot.sound $ by simp [one_eq_mk]) ih) }
/-- `of` is the canonical injection from the type to the free group over that type by sending each
element to the equivalence class of the letter that is the element. -/
def of (x : Ξ±) : free_group Ξ± :=
mk [(x, tt)]
theorem red.exact : mk Lβ = mk Lβ β join red Lβ Lβ :=
calc (mk Lβ = mk Lβ) β eqv_gen red.step Lβ Lβ : iff.intro (quot.exact _) quot.eqv_gen_sound
... β join red Lβ Lβ : eqv_gen_step_iff_join_red
/-- The canonical injection from the type to the free group is an injection. -/
theorem of_injective : function.injective (@of Ξ±) :=
Ξ» _ _ H, let β¨Lβ, hx, hyβ© := red.exact.1 H in
by simp [red.singleton_iff] at hx hy; cc
section lift
variables {Ξ² : Type v} [group Ξ²] (f : Ξ± β Ξ²) {x y : free_group Ξ±}
/-- Given `f : Ξ± β Ξ²` with `Ξ²` a group, the canonical map `list (Ξ± Γ bool) β Ξ²` -/
def lift.aux : list (Ξ± Γ bool) β Ξ² :=
Ξ» L, list.prod $ L.map $ Ξ» x, cond x.2 (f x.1) (f x.1)β»ΒΉ
theorem red.step.lift {f : Ξ± β Ξ²} (H : red.step Lβ Lβ) :
lift.aux f Lβ = lift.aux f Lβ :=
by cases H with _ _ _ b; cases b; simp [lift.aux]
/-- If `Ξ²` is a group, then any function from `Ξ±` to `Ξ²`
extends uniquely to a group homomorphism from
the free group over `Ξ±` to `Ξ²` -/
@[simps symm_apply]
def lift : (Ξ± β Ξ²) β (free_group Ξ± β* Ξ²) :=
{ to_fun := Ξ» f,
monoid_hom.mk' (quot.lift (lift.aux f) $ Ξ» Lβ Lβ, red.step.lift) $ begin
rintros β¨Lββ© β¨Lββ©, simp [lift.aux],
end,
inv_fun := Ξ» g, g β of,
left_inv := Ξ» f, one_mul _,
right_inv := Ξ» g, monoid_hom.ext $ begin
rintros β¨Lβ©,
apply list.rec_on L,
{ exact g.map_one.symm, },
{ rintros β¨x, _ | _β© t (ih : _ = g (mk t)),
{ show _ = g ((of x)β»ΒΉ * mk t),
simpa [lift.aux] using ih },
{ show _ = g (of x * mk t),
simpa [lift.aux] using ih }, },
end }
variable {f}
@[simp] lemma lift.mk : lift f (mk L) =
list.prod (L.map $ Ξ» x, cond x.2 (f x.1) (f x.1)β»ΒΉ) :=
rfl
@[simp] lemma lift.of {x} : lift f (of x) = f x :=
one_mul _
theorem lift.unique (g : free_group Ξ± β* Ξ²)
(hg : β x, g (of x) = f x) : β{x}, g x = lift f x :=
monoid_hom.congr_fun $ (lift.symm_apply_eq).mp (funext hg : g β of = f)
/-- Two homomorphisms out of a free group are equal if they are equal on generators.
See note [partially-applied ext lemmas]. -/
@[ext]
lemma ext_hom {G : Type*} [group G] (f g : free_group Ξ± β* G) (h : β a, f (of a) = g (of a)) :
f = g :=
lift.symm.injective $ funext h
theorem lift.of_eq (x : free_group Ξ±) : lift of x = x :=
monoid_hom.congr_fun (lift.apply_symm_apply (monoid_hom.id _)) x
theorem lift.range_subset {s : subgroup Ξ²} (H : set.range f β s) :
set.range (lift f) β s :=
by rintros _ β¨β¨Lβ©, rflβ©; exact list.rec_on L s.one_mem
(Ξ» β¨x, bβ© tl ih, bool.rec_on b
(by simp at ih β’; from s.mul_mem
(s.inv_mem $ H β¨x, rflβ©) ih)
(by simp at ih β’; from s.mul_mem (H β¨x, rflβ©) ih))
theorem closure_subset {G : Type*} [group G] {s : set G} {t : subgroup G}
(h : s β t) : subgroup.closure s β€ t :=
begin
simp only [h, subgroup.closure_le],
end
theorem lift.range_eq_closure :
set.range (lift f) = subgroup.closure (set.range f) :=
set.subset.antisymm
(lift.range_subset subgroup.subset_closure)
begin
suffices : (subgroup.closure (set.range f)) β€ monoid_hom.range (lift f),
simpa,
rw subgroup.closure_le,
rintros y β¨x, hxβ©,
exact β¨of x, by simpaβ©
end
end lift
section map
variables {Ξ² : Type v} (f : Ξ± β Ξ²) {x y : free_group Ξ±}
/-- Given `f : Ξ± β Ξ²`, the canonical map `list (Ξ± Γ bool) β list (Ξ² Γ bool)`. -/
def map.aux (L : list (Ξ± Γ bool)) : list (Ξ² Γ bool) :=
L.map $ Ξ» x, (f x.1, x.2)
/-- Any function from `Ξ±` to `Ξ²` extends uniquely
to a group homomorphism from the free group
over `Ξ±` to the free group over `Ξ²`. Note that this is the bare function;
for the group homomorphism use `map`. -/
def map.to_fun (x : free_group Ξ±) : free_group Ξ² :=
x.lift_on (Ξ» L, mk $ map.aux f L) $
Ξ» Lβ Lβ H, quot.sound $ by cases H; simp [map.aux]
/-- Any function from `Ξ±` to `Ξ²` extends uniquely
to a group homomorphism from the free group
ver `Ξ±` to the free group over `Ξ²`. -/
def map : free_group Ξ± β* free_group Ξ² := monoid_hom.mk' (map.to_fun f)
begin
rintros β¨Lββ© β¨Lββ©,
simp [map.to_fun, map.aux]
end
--by rintros β¨Lββ© β¨Lββ©; simp [map, map.aux]
variable {f}
@[simp] lemma map.mk : map f (mk L) = mk (L.map (Ξ» x, (f x.1, x.2))) :=
rfl
@[simp] lemma map.id : map id x = x :=
have H1 : (Ξ» (x : Ξ± Γ bool), x) = id := rfl,
by rcases x with β¨Lβ©; simp [H1]
@[simp] lemma map.id' : map (Ξ» z, z) x = x := map.id
theorem map.comp {Ξ³ : Type w} {f : Ξ± β Ξ²} {g : Ξ² β Ξ³} {x} :
map g (map f x) = map (g β f) x :=
by rcases x with β¨Lβ©; simp
@[simp] lemma map.of {x} : map f (of x) = of (f x) := rfl
theorem map.unique (g : free_group Ξ± β* free_group Ξ²)
(hg : β x, g (of x) = of (f x)) : β{x}, g x = map f x :=
by rintros β¨Lβ©; exact list.rec_on L g.map_one
(Ξ» β¨x, bβ© t (ih : g (mk t) = map f (mk t)), bool.rec_on b
(show g ((of x)β»ΒΉ * mk t) = map f ((of x)β»ΒΉ * mk t),
by simp [g.map_mul, g.map_inv, hg, ih])
(show g (of x * mk t) = map f (of x * mk t),
by simp [g.map_mul, hg, ih]))
/-- Equivalent types give rise to equivalent free groups. -/
def free_group_congr {Ξ± Ξ²} (e : Ξ± β Ξ²) : free_group Ξ± β free_group Ξ² :=
β¨map e, map e.symm,
Ξ» x, by simp [function.comp, map.comp],
Ξ» x, by simp [function.comp, map.comp]β©
theorem map_eq_lift : map f x = lift (of β f) x :=
eq.symm $ map.unique _ $ Ξ» x, by simp
end map
section prod
variables [group Ξ±] (x y : free_group Ξ±)
/-- If `Ξ±` is a group, then any function from `Ξ±` to `Ξ±`
extends uniquely to a homomorphism from the
free group over `Ξ±` to `Ξ±`. This is the multiplicative
version of `sum`. -/
def prod : free_group Ξ± β* Ξ± := lift id
variables {x y}
@[simp] lemma prod_mk :
prod (mk L) = list.prod (L.map $ Ξ» x, cond x.2 x.1 x.1β»ΒΉ) :=
rfl
@[simp] lemma prod.of {x : Ξ±} : prod (of x) = x :=
lift.of
lemma prod.unique (g : free_group Ξ± β* Ξ±)
(hg : β x, g (of x) = x) {x} :
g x = prod x :=
lift.unique g hg
end prod
theorem lift_eq_prod_map {Ξ² : Type v} [group Ξ²] {f : Ξ± β Ξ²} {x} :
lift f x = prod (map f x) :=
begin
rw βlift.unique (prod.comp (map f)),
{ refl },
{ simp }
end
section sum
variables [add_group Ξ±] (x y : free_group Ξ±)
/-- If `Ξ±` is a group, then any function from `Ξ±` to `Ξ±`
extends uniquely to a homomorphism from the
free group over `Ξ±` to `Ξ±`. This is the additive
version of `prod`. -/
def sum : Ξ± :=
@prod (multiplicative _) _ x
variables {x y}
@[simp] lemma sum_mk :
sum (mk L) = list.sum (L.map $ Ξ» x, cond x.2 x.1 (-x.1)) :=
rfl
@[simp] lemma sum.of {x : Ξ±} : sum (of x) = x :=
prod.of
-- note: there are no bundled homs with different notation in the domain and codomain, so we copy
-- these manually
@[simp] lemma sum.map_mul : sum (x * y) = sum x + sum y :=
(@prod (multiplicative _) _).map_mul _ _
@[simp] lemma sum.map_one : sum (1:free_group Ξ±) = 0 :=
(@prod (multiplicative _) _).map_one
@[simp] lemma sum.map_inv : sum xβ»ΒΉ = -sum x :=
(@prod (multiplicative _) _).map_inv _
end sum
/-- The bijection between the free group on the empty type, and a type with one element. -/
def free_group_empty_equiv_unit : free_group empty β unit :=
{ to_fun := Ξ» _, (),
inv_fun := Ξ» _, 1,
left_inv := by rintros β¨_ | β¨β¨β¨β©, _β©, _β©β©; refl,
right_inv := Ξ» β¨β©, rfl }
/-- The bijection between the free group on a singleton, and the integers. -/
def free_group_unit_equiv_int : free_group unit β β€ :=
{ to_fun := Ξ» x,
sum begin revert x, apply monoid_hom.to_fun,
apply map (Ξ» _, (1 : β€)),
end,
inv_fun := Ξ» x, of () ^ x,
left_inv :=
begin
rintros β¨Lβ©,
refine list.rec_on L rfl _,
exact (Ξ» β¨β¨β©, bβ© tl ih, by cases b; simp [zpow_add] at ih β’; rw ih; refl),
end,
right_inv :=
Ξ» x, int.induction_on x (by simp)
(Ξ» i ih, by simp at ih; simp [zpow_add, ih])
(Ξ» i ih, by simp at ih; simp [zpow_add, ih, sub_eq_add_neg, -int.add_neg_one])
}
section category
variables {Ξ² : Type u}
instance : monad free_group.{u} :=
{ pure := Ξ» Ξ±, of,
map := Ξ» Ξ± Ξ² f, (map f),
bind := Ξ» Ξ± Ξ² x f, lift f x }
@[elab_as_eliminator]
protected theorem induction_on
{C : free_group Ξ± β Prop}
(z : free_group Ξ±)
(C1 : C 1)
(Cp : β x, C $ pure x)
(Ci : β x, C (pure x) β C (pure x)β»ΒΉ)
(Cm : β x y, C x β C y β C (x * y)) : C z :=
quot.induction_on z $ Ξ» L, list.rec_on L C1 $ Ξ» β¨x, bβ© tl ih,
bool.rec_on b (Cm _ _ (Ci _ $ Cp x) ih) (Cm _ _ (Cp x) ih)
@[simp] lemma map_pure (f : Ξ± β Ξ²) (x : Ξ±) : f <$> (pure x : free_group Ξ±) = pure (f x) :=
map.of
@[simp] lemma map_one (f : Ξ± β Ξ²) : f <$> (1 : free_group Ξ±) = 1 :=
(map f).map_one
@[simp] lemma map_mul (f : Ξ± β Ξ²) (x y : free_group Ξ±) : f <$> (x * y) = f <$> x * f <$> y :=
(map f).map_mul x y
@[simp] lemma map_inv (f : Ξ± β Ξ²) (x : free_group Ξ±) : f <$> (xβ»ΒΉ) = (f <$> x)β»ΒΉ :=
(map f).map_inv x
@[simp] lemma pure_bind (f : Ξ± β free_group Ξ²) (x) : pure x >>= f = f x :=
lift.of
@[simp] lemma one_bind (f : Ξ± β free_group Ξ²) : 1 >>= f = 1 :=
(lift f).map_one
@[simp] lemma mul_bind (f : Ξ± β free_group Ξ²) (x y : free_group Ξ±) :
x * y >>= f = (x >>= f) * (y >>= f) :=
(lift f).map_mul _ _
@[simp] lemma inv_bind (f : Ξ± β free_group Ξ²) (x : free_group Ξ±) : xβ»ΒΉ >>= f = (x >>= f)β»ΒΉ :=
(lift f).map_inv _
instance : is_lawful_monad free_group.{u} :=
{ id_map := Ξ» Ξ± x, free_group.induction_on x (map_one id) (Ξ» x, map_pure id x)
(Ξ» x ih, by rw [map_inv, ih]) (Ξ» x y ihx ihy, by rw [map_mul, ihx, ihy]),
pure_bind := Ξ» Ξ± Ξ² x f, pure_bind f x,
bind_assoc := Ξ» Ξ± Ξ² Ξ³ x f g, free_group.induction_on x
(by iterate 3 { rw one_bind }) (Ξ» x, by iterate 2 { rw pure_bind })
(Ξ» x ih, by iterate 3 { rw inv_bind }; rw ih)
(Ξ» x y ihx ihy, by iterate 3 { rw mul_bind }; rw [ihx, ihy]),
bind_pure_comp_eq_map := Ξ» Ξ± Ξ² f x, free_group.induction_on x
(by rw [one_bind, map_one]) (Ξ» x, by rw [pure_bind, map_pure])
(Ξ» x ih, by rw [inv_bind, map_inv, ih]) (Ξ» x y ihx ihy, by rw [mul_bind, map_mul, ihx, ihy]) }
end category
section reduce
variable [decidable_eq Ξ±]
/-- The maximal reduction of a word. It is computable
iff `Ξ±` has decidable equality. -/
def reduce (L : list (Ξ± Γ bool)) : list (Ξ± Γ bool) :=
list.rec_on L [] $ Ξ» hd1 tl1 ih,
list.cases_on ih [hd1] $ Ξ» hd2 tl2,
if hd1.1 = hd2.1 β§ hd1.2 = bnot hd2.2 then tl2
else hd1 :: hd2 :: tl2
@[simp] lemma reduce.cons (x) : reduce (x :: L) =
list.cases_on (reduce L) [x] (Ξ» hd tl,
if x.1 = hd.1 β§ x.2 = bnot hd.2 then tl
else x :: hd :: tl) := rfl
/-- The first theorem that characterises the function
`reduce`: a word reduces to its maximal reduction. -/
theorem reduce.red : red L (reduce L) :=
begin
induction L with hd1 tl1 ih,
case list.nil
{ constructor },
case list.cons
{ dsimp,
revert ih,
generalize htl : reduce tl1 = TL,
intro ih,
cases TL with hd2 tl2,
case list.nil
{ exact red.cons_cons ih },
case list.cons
{ dsimp,
by_cases h : hd1.fst = hd2.fst β§ hd1.snd = bnot (hd2.snd),
{ rw [if_pos h],
transitivity,
{ exact red.cons_cons ih },
{ cases hd1, cases hd2, cases h,
dsimp at *, subst_vars,
exact red.step.cons_bnot_rev.to_red } },
{ rw [if_neg h],
exact red.cons_cons ih } } }
end
theorem reduce.not {p : Prop} :
β {Lβ Lβ Lβ : list (Ξ± Γ bool)} {x b}, reduce Lβ = Lβ ++ (x, b) :: (x, bnot b) :: Lβ β p
| [] L2 L3 _ _ := Ξ» h, by cases L2; injections
| ((x,b)::L1) L2 L3 x' b' := begin
dsimp,
cases r : reduce L1,
{ dsimp, intro h,
have := congr_arg list.length h,
simp [-add_comm] at this,
exact absurd this dec_trivial },
cases hd with y c,
by_cases x = y β§ b = bnot c; simp [h]; intro H,
{ rw H at r,
exact @reduce.not L1 ((y,c)::L2) L3 x' b' r },
rcases L2 with _|β¨a, L2β©,
{ injections, subst_vars,
simp at h, cc },
{ refine @reduce.not L1 L2 L3 x' b' _,
injection H with _ H,
rw [r, H], refl }
end
/-- The second theorem that characterises the
function `reduce`: the maximal reduction of a word
only reduces to itself. -/
theorem reduce.min (H : red (reduce Lβ) Lβ) : reduce Lβ = Lβ :=
begin
induction H with L1 L' L2 H1 H2 ih,
{ refl },
{ cases H1 with L4 L5 x b,
exact reduce.not H2 }
end
/-- `reduce` is idempotent, i.e. the maximal reduction
of the maximal reduction of a word is the maximal
reduction of the word. -/
theorem reduce.idem : reduce (reduce L) = reduce L :=
eq.symm $ reduce.min reduce.red
theorem reduce.step.eq (H : red.step Lβ Lβ) : reduce Lβ = reduce Lβ :=
let β¨Lβ, HR13, HR23β© := red.church_rosser reduce.red (reduce.red.head H) in
(reduce.min HR13).trans (reduce.min HR23).symm
/-- If a word reduces to another word, then they have
a common maximal reduction. -/
theorem reduce.eq_of_red (H : red Lβ Lβ) : reduce Lβ = reduce Lβ :=
let β¨Lβ, HR13, HR23β© := red.church_rosser reduce.red (red.trans H reduce.red) in
(reduce.min HR13).trans (reduce.min HR23).symm
/-- If two words correspond to the same element in
the free group, then they have a common maximal
reduction. This is the proof that the function that
sends an element of the free group to its maximal
reduction is well-defined. -/
theorem reduce.sound (H : mk Lβ = mk Lβ) : reduce Lβ = reduce Lβ :=
let β¨Lβ, H13, H23β© := red.exact.1 H in
(reduce.eq_of_red H13).trans (reduce.eq_of_red H23).symm
/-- If two words have a common maximal reduction,
then they correspond to the same element in the free group. -/
theorem reduce.exact (H : reduce Lβ = reduce Lβ) : mk Lβ = mk Lβ :=
red.exact.2 β¨reduce Lβ, H βΈ reduce.red, reduce.redβ©
/-- A word and its maximal reduction correspond to
the same element of the free group. -/
theorem reduce.self : mk (reduce L) = mk L :=
reduce.exact reduce.idem
/-- If words `wβ wβ` are such that `wβ` reduces to `wβ`,
then `wβ` reduces to the maximal reduction of `wβ`. -/
theorem reduce.rev (H : red Lβ Lβ) : red Lβ (reduce Lβ) :=
(reduce.eq_of_red H).symm βΈ reduce.red
/-- The function that sends an element of the free
group to its maximal reduction. -/
def to_word : free_group Ξ± β list (Ξ± Γ bool) :=
quot.lift reduce $ Ξ» Lβ Lβ H, reduce.step.eq H
lemma to_word.mk : β{x : free_group Ξ±}, mk (to_word x) = x :=
by rintros β¨Lβ©; exact reduce.self
lemma to_word.inj : β(x y : free_group Ξ±), to_word x = to_word y β x = y :=
by rintros β¨Lββ© β¨Lββ©; exact reduce.exact
/-- Constructive Church-Rosser theorem (compare `church_rosser`). -/
def reduce.church_rosser (H12 : red Lβ Lβ) (H13 : red Lβ Lβ) :
{ Lβ // red Lβ Lβ β§ red Lβ Lβ } :=
β¨reduce Lβ, reduce.rev H12, reduce.rev H13β©
instance : decidable_eq (free_group Ξ±) :=
function.injective.decidable_eq to_word.inj
instance red.decidable_rel : decidable_rel (@red Ξ±)
| [] [] := is_true red.refl
| [] (hd2::tl2) := is_false $ Ξ» H, list.no_confusion (red.nil_iff.1 H)
| ((x,b)::tl) [] := match red.decidable_rel tl [(x, bnot b)] with
| is_true H := is_true $ red.trans (red.cons_cons H) $
(@red.step.bnot _ [] [] _ _).to_red
| is_false H := is_false $ Ξ» H2, H $ red.cons_nil_iff_singleton.1 H2
end
| ((x1,b1)::tl1) ((x2,b2)::tl2) := if h : (x1, b1) = (x2, b2)
then match red.decidable_rel tl1 tl2 with
| is_true H := is_true $ h βΈ red.cons_cons H
| is_false H := is_false $ Ξ» H2, H $ h βΈ (red.cons_cons_iff _).1 $ H2
end
else match red.decidable_rel tl1 ((x1,bnot b1)::(x2,b2)::tl2) with
| is_true H := is_true $ (red.cons_cons H).tail red.step.cons_bnot
| is_false H := is_false $ Ξ» H2, H $ red.inv_of_red_of_ne h H2
end
/-- A list containing every word that `wβ` reduces to. -/
def red.enum (Lβ : list (Ξ± Γ bool)) : list (list (Ξ± Γ bool)) :=
list.filter (Ξ» Lβ, red Lβ Lβ) (list.sublists Lβ)
theorem red.enum.sound (H : Lβ β red.enum Lβ) : red Lβ Lβ :=
list.of_mem_filter H
theorem red.enum.complete (H : red Lβ Lβ) : Lβ β red.enum Lβ :=
list.mem_filter_of_mem (list.mem_sublists.2 $ red.sublist H) H
instance : fintype { Lβ // red Lβ Lβ } :=
fintype.subtype (list.to_finset $ red.enum Lβ) $
Ξ» Lβ, β¨Ξ» H, red.enum.sound $ list.mem_to_finset.1 H,
Ξ» H, list.mem_to_finset.2 $ red.enum.complete Hβ©
end reduce
end free_group
|
262761bbddcb09f450f6ee7db10931049972c53a | 46125763b4dbf50619e8846a1371029346f4c3db | /src/measure_theory/outer_measure.lean | c565884aa0b996361af55c9adfd12bd3ce55aa71 | [
"Apache-2.0"
] | permissive | thjread/mathlib | a9d97612cedc2c3101060737233df15abcdb9eb1 | 7cffe2520a5518bba19227a107078d83fa725ddc | refs/heads/master | 1,615,637,696,376 | 1,583,953,063,000 | 1,583,953,063,000 | 246,680,271 | 0 | 0 | Apache-2.0 | 1,583,960,875,000 | 1,583,960,875,000 | null | UTF-8 | Lean | false | false | 19,690 | 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
Outer measures -- overapproximations of measures
-/
import algebra.big_operators algebra.module
topology.instances.ennreal analysis.specific_limits
measure_theory.measurable_space
noncomputable theory
open set lattice finset function filter encodable
open_locale classical
namespace measure_theory
structure outer_measure (Ξ± : Type*) :=
(measure_of : set Ξ± β ennreal)
(empty : measure_of β
= 0)
(mono : β{sβ sβ}, sβ β sβ β measure_of sβ β€ measure_of sβ)
(Union_nat : β(s:β β set Ξ±), measure_of (βi, s i) β€ (βi, measure_of (s i)))
namespace outer_measure
instance {Ξ±} : has_coe_to_fun (outer_measure Ξ±) := β¨_, Ξ» m, m.measure_ofβ©
section basic
variables {Ξ± : Type*} {ms : set (outer_measure Ξ±)} {m : outer_measure Ξ±}
@[simp] theorem empty' (m : outer_measure Ξ±) : m β
= 0 := m.empty
theorem mono' (m : outer_measure Ξ±) {sβ sβ}
(h : sβ β sβ) : m sβ β€ m sβ := m.mono h
theorem Union_aux (m : set Ξ± β ennreal) (m0 : m β
= 0)
{Ξ²} [encodable Ξ²] (s : Ξ² β set Ξ±) :
(β b, m (s b)) = β i, m (β b β decode2 Ξ² i, s b) :=
begin
have H : β n, m (β b β decode2 Ξ² n, s b) β 0 β (decode2 Ξ² n).is_some,
{ intros n h,
cases decode2 Ξ² n with b,
{ exact (h (by simp [m0])).elim },
{ exact rfl } },
refine tsum_eq_tsum_of_ne_zero_bij (Ξ» n h, option.get (H n h)) _ _ _,
{ intros m n hm hn e,
have := mem_decode2.1 (option.get_mem (H n hn)),
rwa [β e, mem_decode2.1 (option.get_mem (H m hm))] at this },
{ intros b h,
refine β¨encode b, _, _β©,
{ convert h, simp [ext_iff, encodek2] },
{ exact option.get_of_mem _ (encodek2 _) } },
{ intros n h,
transitivity, swap,
rw [show decode2 Ξ² n = _, from option.get_mem (H n h)],
congr, simp [ext_iff, -option.some_get] }
end
protected theorem Union (m : outer_measure Ξ±)
{Ξ²} [encodable Ξ²] (s : Ξ² β set Ξ±) :
m (βi, s i) β€ (βi, m (s i)) :=
by rw [Union_decode2, Union_aux _ m.empty' s]; exact m.Union_nat _
lemma Union_null (m : outer_measure Ξ±)
{Ξ²} [encodable Ξ²] {s : Ξ² β set Ξ±} (h : β i, m (s i) = 0) : m (βi, s i) = 0 :=
by simpa [h] using m.Union s
protected lemma union (m : outer_measure Ξ±) (sβ sβ : set Ξ±) :
m (sβ βͺ sβ) β€ m sβ + m sβ :=
begin
convert m.Union (Ξ» b, cond b sβ sβ),
{ simp [union_eq_Union] },
{ rw tsum_fintype, change _ = _ + _, simp }
end
lemma union_null (m : outer_measure Ξ±) {sβ sβ : set Ξ±}
(hβ : m sβ = 0) (hβ : m sβ = 0) : m (sβ βͺ sβ) = 0 :=
by simpa [hβ, hβ] using m.union sβ sβ
@[ext] lemma ext : β{ΞΌβ ΞΌβ : outer_measure Ξ±},
(βs, ΞΌβ s = ΞΌβ s) β ΞΌβ = ΞΌβ
| β¨mβ, eβ, _, uββ© β¨mβ, eβ, _, uββ© h := by congr; exact funext h
instance : has_zero (outer_measure Ξ±) :=
β¨{ measure_of := Ξ»_, 0,
empty := rfl,
mono := assume _ _ _, le_refl 0,
Union_nat := assume s, zero_le _ }β©
@[simp] theorem zero_apply (s : set Ξ±) : (0 : outer_measure Ξ±) s = 0 := rfl
instance : inhabited (outer_measure Ξ±) := β¨0β©
instance : has_add (outer_measure Ξ±) :=
β¨Ξ»mβ mβ,
{ measure_of := Ξ»s, mβ s + mβ s,
empty := show mβ β
+ mβ β
= 0, by simp [outer_measure.empty],
mono := assume sβ sβ h, add_le_add' (mβ.mono h) (mβ.mono h),
Union_nat := assume s,
calc mβ (βi, s i) + mβ (βi, s i) β€
(βi, mβ (s i)) + (βi, mβ (s i)) :
add_le_add' (mβ.Union_nat s) (mβ.Union_nat s)
... = _ : ennreal.tsum_add.symm}β©
@[simp] theorem add_apply (mβ mβ : outer_measure Ξ±) (s : set Ξ±) :
(mβ + mβ) s = mβ s + mβ s := rfl
instance add_comm_monoid : add_comm_monoid (outer_measure Ξ±) :=
{ zero := 0,
add := (+),
add_comm := assume a b, ext $ assume s, add_comm _ _,
add_assoc := assume a b c, ext $ assume s, add_assoc _ _ _,
add_zero := assume a, ext $ assume s, add_zero _,
zero_add := assume a, ext $ assume s, zero_add _ }
instance : has_bot (outer_measure Ξ±) := β¨0β©
instance outer_measure.order_bot : order_bot (outer_measure Ξ±) :=
{ le := Ξ»mβ mβ, βs, mβ s β€ mβ s,
bot := 0,
le_refl := assume a s, le_refl _,
le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s),
le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s),
bot_le := assume a s, zero_le _ }
section supremum
instance : has_Sup (outer_measure Ξ±) :=
β¨Ξ»ms, {
measure_of := Ξ»s, β¨m:ms, m.val s,
empty := le_zero_iff_eq.1 $ supr_le $ Ξ» β¨m, hβ©, le_of_eq m.empty,
mono := assume sβ sβ hs, supr_le_supr $ assume β¨m, hmβ©, m.mono hs,
Union_nat := assume f, supr_le $ assume m,
calc m.val (βi, f i) β€ (β (i : β), m.val (f i)) : m.val.Union_nat _
... β€ (βi, β¨m:ms, m.val (f i)) :
ennreal.tsum_le_tsum $ assume i, le_supr (Ξ»m:ms, m.val (f i)) m }β©
private lemma le_Sup (hm : m β ms) : m β€ Sup ms :=
Ξ» s, le_supr (Ξ»m:ms, m.val s) β¨m, hmβ©
private lemma Sup_le (hm : βm' β ms, m' β€ m) : Sup ms β€ m :=
Ξ» s, (supr_le $ assume β¨m', h'β©, (hm m' h') s)
instance : has_Inf (outer_measure Ξ±) := β¨Ξ»s, Sup {m | βm'βs, m β€ m'}β©
private lemma Inf_le (hm : m β ms) : Inf ms β€ m := Sup_le $ assume m' h', h' _ hm
private lemma le_Inf (hm : βm' β ms, m β€ m') : m β€ Inf ms := le_Sup hm
instance : complete_lattice (outer_measure Ξ±) :=
{ top := Sup univ,
le_top := assume a, le_Sup (mem_univ a),
Sup := Sup,
Sup_le := assume s m, Sup_le,
le_Sup := assume s m, le_Sup,
Inf := Inf,
Inf_le := assume s m, Inf_le,
le_Inf := assume s m, le_Inf,
sup := Ξ»a b, Sup {a, b},
le_sup_left := assume a b, le_Sup $ by simp,
le_sup_right := assume a b, le_Sup $ by simp,
sup_le := assume a b c ha hb, Sup_le $ by simp [or_imp_distrib, ha, hb] {contextual:=tt},
inf := Ξ»a b, Inf {a, b},
inf_le_left := assume a b, Inf_le $ by simp,
inf_le_right := assume a b, Inf_le $ by simp,
le_inf := assume a b c ha hb, le_Inf $ by simp [or_imp_distrib, ha, hb] {contextual:=tt},
.. outer_measure.order_bot }
@[simp] theorem Sup_apply (ms : set (outer_measure Ξ±)) (s : set Ξ±) :
(Sup ms) s = β¨ m : ms, m s := rfl
@[simp] theorem supr_apply {ΞΉ} (f : ΞΉ β outer_measure Ξ±) (s : set Ξ±) :
(β¨ i : ΞΉ, f i) s = β¨ i, f i s :=
le_antisymm
(supr_le $ Ξ» β¨_, i, rflβ©, le_supr _ i)
(supr_le $ Ξ» i, le_supr
(Ξ» (m : {a : outer_measure Ξ± // β i, f i = a}), m.1 s)
β¨f i, i, rflβ©)
@[simp] theorem sup_apply (mβ mβ : outer_measure Ξ±) (s : set Ξ±) :
(mβ β mβ) s = mβ s β mβ s :=
by have := supr_apply (Ξ» b, cond b mβ mβ) s;
rwa [supr_bool_eq, supr_bool_eq] at this
end supremum
def map {Ξ²} (f : Ξ± β Ξ²) (m : outer_measure Ξ±) : outer_measure Ξ² :=
{ measure_of := Ξ»s, m (f β»ΒΉ' s),
empty := m.empty,
mono := Ξ» s t h, m.mono (preimage_mono h),
Union_nat := Ξ» s, by rw [preimage_Union]; exact
m.Union_nat (Ξ» i, f β»ΒΉ' s i) }
@[simp] theorem map_apply {Ξ²} (f : Ξ± β Ξ²)
(m : outer_measure Ξ±) (s : set Ξ²) : map f m s = m (f β»ΒΉ' s) := rfl
@[simp] theorem map_id (m : outer_measure Ξ±) : map id m = m :=
ext $ Ξ» s, rfl
@[simp] theorem map_map {Ξ² Ξ³} (f : Ξ± β Ξ²) (g : Ξ² β Ξ³)
(m : outer_measure Ξ±) : map g (map f m) = map (g β f) m :=
ext $ Ξ» s, rfl
instance : functor outer_measure := {map := Ξ» Ξ± Ξ², map}
instance : is_lawful_functor outer_measure :=
{ id_map := Ξ» Ξ±, map_id,
comp_map := Ξ» Ξ± Ξ² Ξ³ f g m, (map_map f g m).symm }
/-- The dirac outer measure. -/
def dirac (a : Ξ±) : outer_measure Ξ± :=
{ measure_of := Ξ»s, β¨ h : a β s, 1,
empty := by simp,
mono := Ξ» s t h, supr_le_supr2 (Ξ» h', β¨h h', le_refl _β©),
Union_nat := Ξ» s, supr_le $ Ξ» h,
let β¨i, hβ© := mem_Union.1 h in
le_trans (by exact le_supr _ h) (ennreal.le_tsum i) }
@[simp] theorem dirac_apply (a : Ξ±) (s : set Ξ±) :
dirac a s = β¨ h : a β s, 1 := rfl
def sum {ΞΉ} (f : ΞΉ β outer_measure Ξ±) : outer_measure Ξ± :=
{ measure_of := Ξ»s, β i, f i s,
empty := by simp,
mono := Ξ» s t h, ennreal.tsum_le_tsum (Ξ» i, (f i).mono' h),
Union_nat := Ξ» s, by rw ennreal.tsum_comm; exact
ennreal.tsum_le_tsum (Ξ» i, (f i).Union_nat _) }
@[simp] theorem sum_apply {ΞΉ} (f : ΞΉ β outer_measure Ξ±) (s : set Ξ±) :
sum f s = β i, f i s := rfl
instance : has_scalar ennreal (outer_measure Ξ±) :=
β¨Ξ» a m, {
measure_of := Ξ»s, a * m s,
empty := by simp,
mono := Ξ» s t h, canonically_ordered_semiring.mul_le_mul (le_refl _) (m.mono' h),
Union_nat := Ξ» s, by rw ennreal.mul_tsum; exact
canonically_ordered_semiring.mul_le_mul (le_refl _) (m.Union_nat _) }β©
@[simp] theorem smul_apply (a : ennreal) (m : outer_measure Ξ±) (s : set Ξ±) :
(a β’ m) s = a * m s := rfl
instance : semimodule ennreal (outer_measure Ξ±) :=
{ smul_add := Ξ» a mβ mβ, ext $ Ξ» s, mul_add _ _ _,
add_smul := Ξ» a b m, ext $ Ξ» s, add_mul _ _ _,
mul_smul := Ξ» a b m, ext $ Ξ» s, mul_assoc _ _ _,
one_smul := Ξ» m, ext $ Ξ» s, one_mul _,
zero_smul := Ξ» m, ext $ Ξ» s, zero_mul _,
smul_zero := Ξ» a, ext $ Ξ» s, mul_zero _,
..outer_measure.has_scalar }
theorem smul_dirac_apply (a : ennreal) (b : Ξ±) (s : set Ξ±) :
(a β’ dirac b) s = β¨ h : b β s, a :=
by by_cases b β s; simp [h]
theorem top_apply {s : set Ξ±} (h : s.nonempty) : (β€ : outer_measure Ξ±) s = β€ :=
let β¨a, asβ© := h in
top_unique $ le_supr_of_le β¨(β€ : ennreal) β’ dirac a, trivialβ© $
by simp [smul_dirac_apply, as]
end basic
section of_function
set_option eqn_compiler.zeta true
/-- Given any function `m` assigning measures to sets satisying `m β
= 0`, there is
a unique maximal outer measure `ΞΌ` satisfying `ΞΌ s β€ m s` for all `s : set Ξ±`. -/
protected def of_function {Ξ± : Type*} (m : set Ξ± β ennreal) (m_empty : m β
= 0) :
outer_measure Ξ± :=
let ΞΌ := Ξ»s, β¨
{f : β β set Ξ±} (h : s β βi, f i), βi, m (f i) in
{ measure_of := ΞΌ,
empty := le_antisymm
(infi_le_of_le (Ξ»_, β
) $ infi_le_of_le (empty_subset _) $ by simp [m_empty])
(zero_le _),
mono := assume sβ sβ hs, infi_le_infi $ assume f,
infi_le_infi2 $ assume hb, β¨subset.trans hs hb, le_refl _β©,
Union_nat := assume s, ennreal.le_of_forall_epsilon_le $ begin
assume Ξ΅ hΞ΅ (hb : (βi, ΞΌ (s i)) < β€),
rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hΞ΅) β with β¨Ξ΅', hΞ΅', hlβ©,
refine le_trans _ (add_le_add_left' (le_of_lt hl)),
rw β ennreal.tsum_add,
choose f hf using show
βi, βf:β β set Ξ±, s i β (βi, f i) β§ (βi, m (f i)) < ΞΌ (s i) + Ξ΅' i,
{ intro,
have : ΞΌ (s i) < ΞΌ (s i) + Ξ΅' i :=
ennreal.lt_add_right
(lt_of_le_of_lt (by apply ennreal.le_tsum) hb)
(by simpa using hΞ΅' i),
simpa [ΞΌ, infi_lt_iff] },
refine le_trans _ (ennreal.tsum_le_tsum $ Ξ» i, le_of_lt (hf i).2),
rw [β ennreal.tsum_prod, β tsum_equiv equiv.nat_prod_nat_equiv_nat.symm],
swap, {apply_instance},
refine infi_le_of_le _ (infi_le _ _),
exact Union_subset (Ξ» i, subset.trans (hf i).1 $
Union_subset $ Ξ» j, subset.trans (by simp) $
subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)),
end }
theorem of_function_le {Ξ± : Type*} (m : set Ξ± β ennreal) (m_empty s) :
outer_measure.of_function m m_empty s β€ m s :=
let f : β β set Ξ± := Ξ»i, nat.rec_on i s (Ξ»n s, β
) in
infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $
calc (βi, m (f i)) = ({0} : finset β).sum (Ξ»i, m (f i)) :
tsum_eq_sum $ by intro i; cases i; simp [m_empty]
... = m s : by simp; refl
theorem le_of_function {Ξ± : Type*} {m m_empty} {ΞΌ : outer_measure Ξ±} :
ΞΌ β€ outer_measure.of_function m m_empty β β s, ΞΌ s β€ m s :=
β¨Ξ» H s, le_trans (H _) (of_function_le _ _ _),
Ξ» H s, le_infi $ Ξ» f, le_infi $ Ξ» hs,
le_trans (ΞΌ.mono hs) $ le_trans (ΞΌ.Union f) $
ennreal.tsum_le_tsum $ Ξ» i, H _β©
end of_function
section caratheodory_measurable
universe u
parameters {Ξ± : Type u} (m : outer_measure Ξ±)
include m
local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc
variables {s sβ sβ : set Ξ±}
private def C (s : set Ξ±) := βt, m t = m (t β© s) + m (t \ s)
private lemma C_iff_le {s : set Ξ±} : C s β βt, m (t β© s) + m (t \ s) β€ m t :=
forall_congr $ Ξ» t, le_antisymm_iff.trans $ and_iff_right $
by convert m.union _ _; rw inter_union_diff t s
@[simp] private lemma C_empty : C β
:= by simp [C, m.empty, diff_empty]
private lemma C_compl : C sβ β C (- sβ) := by simp [C, diff_eq, add_comm]
@[simp] private lemma C_compl_iff : C (- s) β C s :=
β¨Ξ» h, by simpa using C_compl m h, C_complβ©
private lemma C_union (hβ : C sβ) (hβ : C sβ) : C (sβ βͺ sβ) :=
Ξ» t, begin
rw [hβ t, hβ (t β© sβ), hβ (t \ sβ), hβ (t β© (sβ βͺ sβ)),
inter_diff_assoc _ _ sβ, set.inter_assoc _ _ sβ,
inter_eq_self_of_subset_right (set.subset_union_left _ _),
union_diff_left, hβ (t β© sβ)],
simp [diff_eq]
end
private lemma measure_inter_union (h : sβ β© sβ β β
) (hβ : C sβ) {t : set Ξ±} :
m (t β© (sβ βͺ sβ)) = m (t β© sβ) + m (t β© sβ) :=
by rw [hβ, set.inter_assoc, set.union_inter_cancel_left,
inter_diff_assoc, union_diff_cancel_left h]
private lemma C_Union_lt {s : β β set Ξ±} : β{n:β}, (βi<n, C (s i)) β C (βi<n, s i)
| 0 h := by simp [nat.not_lt_zero]
| (n + 1) h := by rw Union_lt_succ; exact C_union m
(h n (le_refl (n + 1)))
(C_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _)
private lemma C_inter (hβ : C sβ) (hβ : C sβ) : C (sβ β© sβ) :=
by rw [β C_compl_iff, compl_inter]; from C_union _ (C_compl _ hβ) (C_compl _ hβ)
private lemma C_sum {s : β β set Ξ±} (h : βi, C (s i)) (hd : pairwise (disjoint on s)) {t : set Ξ±} :
β {n}, (finset.range n).sum (Ξ»i, m (t β© s i)) = m (t β© βi<n, s i)
| 0 := by simp [nat.not_lt_zero, m.empty]
| (nat.succ n) := begin
simp [Union_lt_succ, range_succ],
rw [measure_inter_union m _ (h n), C_sum],
intro a, simpa [range_succ] using Ξ» hβ i hi hβ, hd _ _ (ne_of_gt hi) β¨hβ, hββ©
end
private lemma C_Union_nat {s : β β set Ξ±} (h : βi, C (s i))
(hd : pairwise (disjoint on s)) : C (βi, s i) :=
C_iff_le.2 $ Ξ» t, begin
have hp : m (t β© βi, s i) β€ (β¨n, m (t β© βi<n, s i)),
{ convert m.Union (Ξ» i, t β© s i),
{ rw inter_Union },
{ simp [ennreal.tsum_eq_supr_nat, C_sum m h hd] } },
refine le_trans (add_le_add_right' hp) _,
rw ennreal.supr_add,
refine supr_le (Ξ» n, le_trans (add_le_add_left' _)
(ge_of_eq (C_Union_lt m (Ξ» i _, h i) _))),
refine m.mono (diff_subset_diff_right _),
exact bUnion_subset (Ξ» i _, subset_Union _ i),
end
private lemma f_Union {s : β β set Ξ±} (h : βi, C (s i))
(hd : pairwise (disjoint on s)) : m (βi, s i) = βi, m (s i) :=
begin
refine le_antisymm (m.Union_nat s) _,
rw ennreal.tsum_eq_supr_nat,
refine supr_le (Ξ» n, _),
have := @C_sum _ m _ h hd univ n,
simp at this, simp [this],
exact m.mono (bUnion_subset (Ξ» i _, subset_Union _ i)),
end
private def caratheodory_dynkin : measurable_space.dynkin_system Ξ± :=
{ has := C,
has_empty := C_empty,
has_compl := assume s, C_compl,
has_Union_nat := assume f hf hn, C_Union_nat hn hf }
/-- Given an outer measure `ΞΌ`, the Caratheodory measurable space is
defined such that `s` is measurable if `βt, ΞΌ t = ΞΌ (t β© s) + ΞΌ (t \ s)`. -/
protected def caratheodory : measurable_space Ξ± :=
caratheodory_dynkin.to_measurable_space $ assume sβ sβ, C_inter
lemma is_caratheodory {s : set Ξ±} :
caratheodory.is_measurable s β βt, m t = m (t β© s) + m (t \ s) :=
iff.rfl
lemma is_caratheodory_le {s : set Ξ±} :
caratheodory.is_measurable s β βt, m (t β© s) + m (t \ s) β€ m t :=
C_iff_le
protected lemma Union_eq_of_caratheodory {s : β β set Ξ±}
(h : βi, caratheodory.is_measurable (s i)) (hd : pairwise (disjoint on s)) :
m (βi, s i) = βi, m (s i) :=
f_Union h hd
end caratheodory_measurable
variables {Ξ± : Type*}
lemma caratheodory_is_measurable {m : set Ξ± β ennreal} {s : set Ξ±}
{hβ : m β
= 0} (hs : βt, m (t β© s) + m (t \ s) β€ m t) :
(outer_measure.of_function m hβ).caratheodory.is_measurable s :=
let o := (outer_measure.of_function m hβ) in
(is_caratheodory_le o).2 $ Ξ» t,
le_infi $ Ξ» f, le_infi $ Ξ» hf, begin
refine le_trans (add_le_add'
(infi_le_of_le (Ξ»i, f i β© s) $ infi_le _ _)
(infi_le_of_le (Ξ»i, f i \ s) $ infi_le _ _)) _,
{ rw β Union_inter,
exact inter_subset_inter_left _ hf },
{ rw β Union_diff,
exact diff_subset_diff_left hf },
{ rw β ennreal.tsum_add,
exact ennreal.tsum_le_tsum (Ξ» i, hs _) }
end
@[simp] theorem zero_caratheodory : (0 : outer_measure Ξ±).caratheodory = β€ :=
top_unique $ Ξ» s _ t, (add_zero _).symm
theorem top_caratheodory : (β€ : outer_measure Ξ±).caratheodory = β€ :=
top_unique $ assume s hs, (is_caratheodory_le _).2 $ assume t,
t.eq_empty_or_nonempty.elim (Ξ» ht, by simp [ht])
(Ξ» ht, by simp only [ht, top_apply, le_top])
theorem le_add_caratheodory (mβ mβ : outer_measure Ξ±) :
mβ.caratheodory β mβ.caratheodory β€ (mβ + mβ : outer_measure Ξ±).caratheodory :=
Ξ» s β¨hsβ, hsββ© t, by simp [hsβ t, hsβ t, add_left_comm]
theorem le_sum_caratheodory {ΞΉ} (m : ΞΉ β outer_measure Ξ±) :
(β¨
i, (m i).caratheodory) β€ (sum m).caratheodory :=
Ξ» s h t, by simp [Ξ» i,
measurable_space.is_measurable_infi.1 h i t, ennreal.tsum_add]
theorem le_smul_caratheodory (a : ennreal) (m : outer_measure Ξ±) :
m.caratheodory β€ (a β’ m).caratheodory :=
Ξ» s h t, by simp [h t, mul_add]
@[simp] theorem dirac_caratheodory (a : Ξ±) : (dirac a).caratheodory = β€ :=
top_unique $ Ξ» s _ t, begin
by_cases a β t; simp [h],
by_cases a β s; simp [h]
end
section Inf_gen
def Inf_gen (m : set (outer_measure Ξ±)) (s : set Ξ±) : ennreal :=
β¨(h : s.nonempty), β¨
(ΞΌ : outer_measure Ξ±) (h : ΞΌ β m), ΞΌ s
@[simp] lemma Inf_gen_empty (m : set (outer_measure Ξ±)) : Inf_gen m β
= 0 :=
by simp [Inf_gen, empty_not_nonempty]
lemma Inf_gen_nonempty1 (m : set (outer_measure Ξ±)) (t : set Ξ±) (h : t.nonempty) :
Inf_gen m t = (β¨
(ΞΌ : outer_measure Ξ±) (h : ΞΌ β m), ΞΌ t) :=
by rw [Inf_gen, supr_pos h]
lemma Inf_gen_nonempty2 (m : set (outer_measure Ξ±)) (ΞΌ) (h : ΞΌ β m) (t) :
Inf_gen m t = (β¨
(ΞΌ : outer_measure Ξ±) (h : ΞΌ β m), ΞΌ t) :=
begin
cases t.eq_empty_or_nonempty with ht ht,
{ simp [ht],
refine (bot_unique $ infi_le_of_le ΞΌ $ _).symm,
refine infi_le_of_le h (le_refl β₯) },
{ exact Inf_gen_nonempty1 m t ht }
end
lemma Inf_eq_of_function_Inf_gen (m : set (outer_measure Ξ±)) :
Inf m = outer_measure.of_function (Inf_gen m) (Inf_gen_empty m) :=
begin
refine le_antisymm
(assume t', le_of_function.2 (assume t, _) _)
(lattice.le_Inf $ assume ΞΌ hΞΌ t, le_trans (outer_measure.of_function_le _ _ _) _);
cases t.eq_empty_or_nonempty with ht ht; simp [ht, Inf_gen_nonempty1],
{ assume ΞΌ hΞΌ, exact (show Inf m β€ ΞΌ, from lattice.Inf_le hΞΌ) t },
{ exact infi_le_of_le ΞΌ (infi_le _ hΞΌ) }
end
end Inf_gen
end outer_measure
end measure_theory
|
c7a4d9aa23b3fbd356248f3b58a4f38c517e2031 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/data/dfinsupp.lean | d00a035aa27e214f585d25f60f37c2bbaec55aac | [
"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 | 32,058 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes HΓΆlzl, Kenny Lau
Dependent functions with finite support (see `data/finsupp.lean`).
-/
import data.finset data.set.finite algebra.big_operators algebra.module algebra.pi_instances
universes u uβ uβ v vβ vβ vβ w x y l
variables (ΞΉ : Type u) (Ξ² : ΞΉ β Type v)
def decidable_zero_symm {Ξ³ : Type w} [has_zero Ξ³] [decidable_pred (eq (0 : Ξ³))] : decidable_pred (Ξ» x, x = (0:Ξ³)) :=
Ξ» x, decidable_of_iff (0 = x) eq_comm
local attribute [instance] decidable_zero_symm
namespace dfinsupp
variable [Ξ i, has_zero (Ξ² i)]
structure pre : Type (max u v) :=
(to_fun : Ξ i, Ξ² i)
(pre_support : multiset ΞΉ)
(zero : β i, i β pre_support β¨ to_fun i = 0)
instance : setoid (pre ΞΉ Ξ²) :=
{ r := Ξ» x y, β i, x.to_fun i = y.to_fun i,
iseqv := β¨Ξ» f i, rfl, Ξ» f g H i, (H i).symm,
Ξ» f g h H1 H2 i, (H1 i).trans (H2 i)β© }
end dfinsupp
variable {ΞΉ}
@[reducible] def dfinsupp [Ξ i, has_zero (Ξ² i)] : Type* :=
quotient (dfinsupp.setoid ΞΉ Ξ²)
variable {Ξ²}
notation `Ξ β` binders `, ` r:(scoped f, dfinsupp f) := r
infix ` ββ `:25 := dfinsupp
namespace dfinsupp
section basic
variables [Ξ i, has_zero (Ξ² i)]
variables {Ξ²β : ΞΉ β Type vβ} {Ξ²β : ΞΉ β Type vβ}
variables [Ξ i, has_zero (Ξ²β i)] [Ξ i, has_zero (Ξ²β i)]
instance : has_coe_to_fun (Ξ β i, Ξ² i) :=
β¨Ξ» _, Ξ i, Ξ² i, Ξ» f, quotient.lift_on f pre.to_fun $ Ξ» _ _, funextβ©
instance : has_zero (Ξ β i, Ξ² i) := β¨β¦β¨Ξ» i, 0, β
, Ξ» i, or.inr rflβ©β§β©
instance : inhabited (Ξ β i, Ξ² i) := β¨0β©
@[simp] lemma zero_apply {i : ΞΉ} : (0 : Ξ β i, Ξ² i) i = 0 := rfl
@[extensionality]
lemma ext {f g : Ξ β i, Ξ² i} (H : β i, f i = g i) : f = g :=
quotient.induction_onβ f g (Ξ» _ _ H, quotient.sound H) H
/-- The composition of `f : Ξ²β β Ξ²β` and `g : Ξ β i, Ξ²β i` is
`map_range f hf g : Ξ β i, Ξ²β i`, well defined when `f 0 = 0`. -/
def map_range (f : Ξ i, Ξ²β i β Ξ²β i) (hf : β i, f i 0 = 0) (g : Ξ β i, Ξ²β i) : Ξ β i, Ξ²β i :=
quotient.lift_on g (Ξ» x, β¦(β¨Ξ» i, f i (x.1 i), x.2,
Ξ» i, or.cases_on (x.3 i) or.inl $ Ξ» H, or.inr $ by rw [H, hf]β© : pre ΞΉ Ξ²β)β§) $ Ξ» x y H,
quotient.sound $ Ξ» i, by simp only [H i]
@[simp] lemma map_range_apply
{f : Ξ i, Ξ²β i β Ξ²β i} {hf : β i, f i 0 = 0} {g : Ξ β i, Ξ²β i} {i : ΞΉ} :
map_range f hf g i = f i (g i) :=
quotient.induction_on g $ Ξ» x, rfl
def zip_with (f : Ξ i, Ξ²β i β Ξ²β i β Ξ² i) (hf : β i, f i 0 0 = 0) (gβ : Ξ β i, Ξ²β i) (gβ : Ξ β i, Ξ²β i) : (Ξ β i, Ξ² i) :=
begin
refine quotient.lift_onβ gβ gβ (Ξ» x y, β¦(β¨Ξ» i, f i (x.1 i) (y.1 i), x.2 + y.2,
Ξ» i, _β© : pre ΞΉ Ξ²)β§) _,
{ cases x.3 i with h1 h1,
{ left, rw multiset.mem_add, left, exact h1 },
cases y.3 i with h2 h2,
{ left, rw multiset.mem_add, right, exact h2 },
right, rw [h1, h2, hf] },
exact Ξ» xβ xβ yβ yβ H1 H2, quotient.sound $ Ξ» i, by simp only [H1 i, H2 i]
end
@[simp] lemma zip_with_apply
{f : Ξ i, Ξ²β i β Ξ²β i β Ξ² i} {hf : β i, f i 0 0 = 0} {gβ : Ξ β i, Ξ²β i} {gβ : Ξ β i, Ξ²β i} {i : ΞΉ} :
zip_with f hf gβ gβ i = f i (gβ i) (gβ i) :=
quotient.induction_onβ gβ gβ $ Ξ» _ _, rfl
end basic
section algebra
instance [Ξ i, add_monoid (Ξ² i)] : has_add (Ξ β i, Ξ² i) :=
β¨zip_with (Ξ» _, (+)) (Ξ» _, add_zero 0)β©
@[simp] lemma add_apply [Ξ i, add_monoid (Ξ² i)] {gβ gβ : Ξ β i, Ξ² i} {i : ΞΉ} :
(gβ + gβ) i = gβ i + gβ i :=
zip_with_apply
instance [Ξ i, add_monoid (Ξ² i)] : add_monoid (Ξ β i, Ξ² i) :=
{ add_monoid .
zero := 0,
add := (+),
add_assoc := Ξ» f g h, ext $ Ξ» i, by simp only [add_apply, add_assoc],
zero_add := Ξ» f, ext $ Ξ» i, by simp only [add_apply, zero_apply, zero_add],
add_zero := Ξ» f, ext $ Ξ» i, by simp only [add_apply, zero_apply, add_zero] }
instance [Ξ i, add_monoid (Ξ² i)] {i : ΞΉ} : is_add_monoid_hom (Ξ» g : Ξ β i : ΞΉ, Ξ² i, g i) :=
{ map_add := Ξ» _ _, add_apply, map_zero := zero_apply }
instance [Ξ i, add_group (Ξ² i)] : has_neg (Ξ β i, Ξ² i) :=
β¨Ξ» f, f.map_range (Ξ» _, has_neg.neg) (Ξ» _, neg_zero)β©
instance [Ξ i, add_comm_monoid (Ξ² i)] : add_comm_monoid (Ξ β i, Ξ² i) :=
{ add_comm := Ξ» f g, ext $ Ξ» i, by simp only [add_apply, add_comm],
.. dfinsupp.add_monoid }
@[simp] lemma neg_apply [Ξ i, add_group (Ξ² i)] {g : Ξ β i, Ξ² i} {i : ΞΉ} : (- g) i = - g i :=
map_range_apply
instance [Ξ i, add_group (Ξ² i)] : add_group (Ξ β i, Ξ² i) :=
{ add_left_neg := Ξ» f, ext $ Ξ» i, by simp only [add_apply, neg_apply, zero_apply, add_left_neg],
.. dfinsupp.add_monoid,
.. (infer_instance : has_neg (Ξ β i, Ξ² i)) }
@[simp] lemma sub_apply [Ξ i, add_group (Ξ² i)] {gβ gβ : Ξ β i, Ξ² i} {i : ΞΉ} : (gβ - gβ) i = gβ i - gβ i :=
by rw [sub_eq_add_neg]; simp
instance [Ξ i, add_comm_group (Ξ² i)] : add_comm_group (Ξ β i, Ξ² i) :=
{ add_comm := Ξ» f g, ext $ Ξ» i, by simp only [add_apply, add_comm],
..dfinsupp.add_group }
def to_has_scalar {Ξ³ : Type w} [ring Ξ³] [Ξ i, add_comm_group (Ξ² i)] [Ξ i, module Ξ³ (Ξ² i)] : has_scalar Ξ³ (Ξ β i, Ξ² i) :=
β¨Ξ»c v, v.map_range (Ξ» _, (β’) c) (Ξ» _, smul_zero _)β©
local attribute [instance] to_has_scalar
@[simp] lemma smul_apply {Ξ³ : Type w} [ring Ξ³] [Ξ i, add_comm_group (Ξ² i)] [Ξ i, module Ξ³ (Ξ² i)] {i : ΞΉ} {b : Ξ³} {v : Ξ β i, Ξ² i} :
(b β’ v) i = b β’ (v i) :=
map_range_apply
def to_module {Ξ³ : Type w} [ring Ξ³] [Ξ i, add_comm_group (Ξ² i)] [Ξ i, module Ξ³ (Ξ² i)] : module Ξ³ (Ξ β i, Ξ² i) :=
module.of_core {
smul_add := Ξ» c x y, ext $ Ξ» i, by simp only [add_apply, smul_apply, smul_add],
add_smul := Ξ» c x y, ext $ Ξ» i, by simp only [add_apply, smul_apply, add_smul],
one_smul := Ξ» x, ext $ Ξ» i, by simp only [smul_apply, one_smul],
mul_smul := Ξ» r s x, ext $ Ξ» i, by simp only [smul_apply, smul_smul],
.. (infer_instance : has_scalar Ξ³ (Ξ β i, Ξ² i)) }
end algebra
section filter_and_subtype_domain
/-- `filter p f` is the function which is `f i` if `p i` is true and 0 otherwise. -/
def filter [Ξ i, has_zero (Ξ² i)] (p : ΞΉ β Prop) [decidable_pred p] (f : Ξ β i, Ξ² i) : Ξ β i, Ξ² i :=
quotient.lift_on f (Ξ» x, β¦(β¨Ξ» i, if p i then x.1 i else 0, x.2,
Ξ» i, or.cases_on (x.3 i) or.inl $ Ξ» H, or.inr $ by rw [H, if_t_t]β© : pre ΞΉ Ξ²)β§) $ Ξ» x y H,
quotient.sound $ Ξ» i, by simp only [H i]
@[simp] lemma filter_apply [Ξ i, has_zero (Ξ² i)]
{p : ΞΉ β Prop} [decidable_pred p] {i : ΞΉ} {f : Ξ β i, Ξ² i} :
f.filter p i = if p i then f i else 0 :=
quotient.induction_on f $ Ξ» x, rfl
@[simp] lemma filter_apply_pos [Ξ i, has_zero (Ξ² i)]
{p : ΞΉ β Prop} [decidable_pred p] {f : Ξ β i, Ξ² i} {i : ΞΉ} (h : p i) :
f.filter p i = f i :=
by simp only [filter_apply, if_pos h]
@[simp] lemma filter_apply_neg [Ξ i, has_zero (Ξ² i)]
{p : ΞΉ β Prop} [decidable_pred p] {f : Ξ β i, Ξ² i} {i : ΞΉ} (h : Β¬ p i) :
f.filter p i = 0 :=
by simp only [filter_apply, if_neg h]
lemma filter_pos_add_filter_neg [Ξ i, add_monoid (Ξ² i)] {f : Ξ β i, Ξ² i}
{p : ΞΉ β Prop} [decidable_pred p] :
f.filter p + f.filter (Ξ»i, Β¬ p i) = f :=
ext $ Ξ» i, by simp only [add_apply, filter_apply]; split_ifs; simp only [add_zero, zero_add]
/-- `subtype_domain p f` is the restriction of the finitely supported function
`f` to the subtype `p`. -/
def subtype_domain [Ξ i, has_zero (Ξ² i)] (p : ΞΉ β Prop) [decidable_pred p]
(f : Ξ β i, Ξ² i) : Ξ β i : subtype p, Ξ² i.1 :=
begin
fapply quotient.lift_on f,
{ intro x, refine β¦β¨Ξ» i, x.1 i.1, (x.2.filter p).attach.map $ Ξ» j, β¨j.1, (multiset.mem_filter.1 j.2).2β©, _β©β§,
refine Ξ» i, or.cases_on (x.3 i.1) (Ξ» H, _) or.inr,
left, rw multiset.mem_map, refine β¨β¨i.1, multiset.mem_filter.2 β¨H, i.2β©β©, _, subtype.eta _ _β©,
apply multiset.mem_attach },
intros x y H,
exact quotient.sound (Ξ» i, H i.1)
end
@[simp] lemma subtype_domain_zero [Ξ i, has_zero (Ξ² i)] {p : ΞΉ β Prop} [decidable_pred p] :
subtype_domain p (0 : Ξ β i, Ξ² i) = 0 :=
rfl
@[simp] lemma subtype_domain_apply [Ξ i, has_zero (Ξ² i)] {p : ΞΉ β Prop} [decidable_pred p]
{i : subtype p} {v : Ξ β i, Ξ² i} :
(subtype_domain p v) i = v (i.val) :=
quotient.induction_on v $ Ξ» x, rfl
@[simp] lemma subtype_domain_add [Ξ i, add_monoid (Ξ² i)] {p : ΞΉ β Prop} [decidable_pred p] {v v' : Ξ β i, Ξ² i} :
(v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p :=
ext $ Ξ» i, by simp only [add_apply, subtype_domain_apply]
instance subtype_domain.is_add_monoid_hom [Ξ i, add_monoid (Ξ² i)] {p : ΞΉ β Prop} [decidable_pred p] :
is_add_monoid_hom (subtype_domain p : (Ξ β i : ΞΉ, Ξ² i) β Ξ β i : subtype p, Ξ² i) :=
{ map_add := Ξ» _ _, subtype_domain_add, map_zero := subtype_domain_zero }
@[simp] lemma subtype_domain_neg [Ξ i, add_group (Ξ² i)] {p : ΞΉ β Prop} [decidable_pred p] {v : Ξ β i, Ξ² i} :
(- v).subtype_domain p = - v.subtype_domain p :=
ext $ Ξ» i, by simp only [neg_apply, subtype_domain_apply]
@[simp] lemma subtype_domain_sub [Ξ i, add_group (Ξ² i)] {p : ΞΉ β Prop} [decidable_pred p] {v v' : Ξ β i, Ξ² i} :
(v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p :=
ext $ Ξ» i, by simp only [sub_apply, subtype_domain_apply]
end filter_and_subtype_domain
variable [decidable_eq ΞΉ]
section basic
variable [Ξ i, has_zero (Ξ² i)]
lemma finite_supp (f : Ξ β i, Ξ² i) : set.finite {i | f i β 0} :=
quotient.induction_on f $ Ξ» x, set.finite_subset
(finset.finite_to_set x.2.to_finset) $ Ξ» i H,
multiset.mem_to_finset.2 $ (x.3 i).resolve_right H
def mk (s : finset ΞΉ) (x : Ξ i : (βs : set ΞΉ), Ξ² i.1) : Ξ β i, Ξ² i :=
β¦β¨Ξ» i, if H : i β s then x β¨i, Hβ© else 0, s.1,
Ξ» i, if H : i β s then or.inl H else or.inr $ dif_neg Hβ©β§
@[simp] lemma mk_apply {s : finset ΞΉ} {x : Ξ i : (βs : set ΞΉ), Ξ² i.1} {i : ΞΉ} :
(mk s x : Ξ i, Ξ² i) i = if H : i β s then x β¨i, Hβ© else 0 :=
rfl
theorem mk_inj (s : finset ΞΉ) : function.injective (@mk ΞΉ Ξ² _ _ s) :=
begin
intros x y H,
ext i,
have h1 : (mk s x : Ξ i, Ξ² i) i = (mk s y : Ξ i, Ξ² i) i, {rw H},
cases i with i hi,
change i β s at hi,
dsimp only [mk_apply, subtype.coe_mk] at h1,
simpa only [dif_pos hi] using h1
end
def single (i : ΞΉ) (b : Ξ² i) : Ξ β i, Ξ² i :=
mk (finset.singleton i) $ Ξ» j, eq.rec_on (finset.mem_singleton.1 j.2).symm b
@[simp] lemma single_apply {i i' b} : (single i b : Ξ β i, Ξ² i) i' = (if h : i = i' then eq.rec_on h b else 0) :=
begin
dsimp only [single],
by_cases h : i = i',
{ have h1 : i' β finset.singleton i, { simp only [h, finset.mem_singleton] },
simp only [mk_apply, dif_pos h, dif_pos h1] },
{ have h1 : i' β finset.singleton i, { simp only [ne.symm h, finset.mem_singleton, not_false_iff] },
simp only [mk_apply, dif_neg h, dif_neg h1] }
end
@[simp] lemma single_zero {i} : (single i 0 : Ξ β i, Ξ² i) = 0 :=
quotient.sound $ Ξ» j, if H : j β finset.singleton i
then by dsimp only; rw [dif_pos H]; cases finset.mem_singleton.1 H; refl
else dif_neg H
@[simp] lemma single_eq_same {i b} : (single i b : Ξ β i, Ξ² i) i = b :=
by simp only [single_apply, dif_pos rfl]
@[simp] lemma single_eq_of_ne {i i' b} (h : i β i') : (single i b : Ξ β i, Ξ² i) i' = 0 :=
by simp only [single_apply, dif_neg h]
def erase (i : ΞΉ) (f : Ξ β i, Ξ² i) : Ξ β i, Ξ² i :=
quotient.lift_on f (Ξ» x, β¦(β¨Ξ» j, if j = i then 0 else x.1 j, x.2,
Ξ» j, or.cases_on (x.3 j) or.inl $ Ξ» H, or.inr $ by simp only [H, if_t_t]β© : pre ΞΉ Ξ²)β§) $ Ξ» x y H,
quotient.sound $ Ξ» j, if h : j = i then by simp only [if_pos h]
else by simp only [if_neg h, H j]
@[simp] lemma erase_apply {i j : ΞΉ} {f : Ξ β i, Ξ² i} :
(f.erase i) j = if j = i then 0 else f j :=
quotient.induction_on f $ Ξ» x, rfl
@[simp] lemma erase_same {i : ΞΉ} {f : Ξ β i, Ξ² i} : (f.erase i) i = 0 :=
by simp
@[simp] lemma erase_ne {i i' : ΞΉ} {f : Ξ β i, Ξ² i} (h : i' β i) : (f.erase i) i' = f i' :=
by simp [h]
end basic
section add_monoid
variable [Ξ i, add_monoid (Ξ² i)]
@[simp] lemma single_add {i : ΞΉ} {bβ bβ : Ξ² i} : single i (bβ + bβ) = single i bβ + single i bβ :=
ext $ assume i',
begin
by_cases h : i = i',
{ subst h, simp only [add_apply, single_eq_same] },
{ simp only [add_apply, single_eq_of_ne h, zero_add] }
end
lemma single_add_erase {i : ΞΉ} {f : Ξ β i, Ξ² i} : single i (f i) + f.erase i = f :=
ext $ Ξ» i',
if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, add_zero]
else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), zero_add]
lemma erase_add_single {i : ΞΉ} {f : Ξ β i, Ξ² i} : f.erase i + single i (f i) = f :=
ext $ Ξ» i',
if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, zero_add]
else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), add_zero]
protected theorem induction {p : (Ξ β i, Ξ² i) β Prop} (f : Ξ β i, Ξ² i)
(h0 : p 0) (ha : βi b (f : Ξ β i, Ξ² i), f i = 0 β b β 0 β p f β p (single i b + f)) :
p f :=
begin
refine quotient.induction_on f (Ξ» x, _),
cases x with f s H, revert f H,
apply multiset.induction_on s,
{ intros f H, convert h0, ext i, exact (H i).resolve_left id },
intros i s ih f H,
by_cases H1 : i β s,
{ have H2 : β j, j β s β¨ f j = 0,
{ intro j, cases H j with H2 H2,
{ cases multiset.mem_cons.1 H2 with H3 H3,
{ left, rw H3, exact H1 },
{ left, exact H3 } },
right, exact H2 },
have H3 : (β¦{to_fun := f, pre_support := i :: s, zero := H}β§ : Ξ β i, Ξ² i)
= β¦{to_fun := f, pre_support := s, zero := H2}β§,
{ exact quotient.sound (Ξ» i, rfl) },
rw H3, apply ih },
have H2 : p (erase i β¦{to_fun := f, pre_support := i :: s, zero := H}β§),
{ dsimp only [erase, quotient.lift_on_beta],
have H2 : β j, j β s β¨ ite (j = i) 0 (f j) = 0,
{ intro j, cases H j with H2 H2,
{ cases multiset.mem_cons.1 H2 with H3 H3,
{ right, exact if_pos H3 },
{ left, exact H3 } },
right, split_ifs; [refl, exact H2] },
have H3 : (β¦{to_fun := Ξ» (j : ΞΉ), ite (j = i) 0 (f j), pre_support := i :: s, zero := _}β§ : Ξ β i, Ξ² i)
= β¦{to_fun := Ξ» (j : ΞΉ), ite (j = i) 0 (f j), pre_support := s, zero := H2}β§ :=
quotient.sound (Ξ» i, rfl),
rw H3, apply ih },
have H3 : single i _ + _ = (β¦{to_fun := f, pre_support := i :: s, zero := H}β§ : Ξ β i, Ξ² i) := single_add_erase,
rw β H3,
change p (single i (f i) + _),
cases classical.em (f i = 0) with h h,
{ rw [h, single_zero, zero_add], exact H2 },
refine ha _ _ _ _ h H2,
rw erase_same
end
lemma inductionβ {p : (Ξ β i, Ξ² i) β Prop} (f : Ξ β i, Ξ² i)
(h0 : p 0) (ha : βi b (f : Ξ β i, Ξ² i), f i = 0 β b β 0 β p f β p (f + single i b)) :
p f :=
dfinsupp.induction f h0 $ Ξ» i b f h1 h2 h3,
have h4 : f + single i b = single i b + f,
{ ext j, by_cases H : i = j,
{ subst H, simp [h1] },
{ simp [H] } },
eq.rec_on h4 $ ha i b f h1 h2 h3
end add_monoid
@[simp] lemma mk_add [Ξ i, add_monoid (Ξ² i)] {s : finset ΞΉ} {x y : Ξ i : (βs : set ΞΉ), Ξ² i.1} :
mk s (x + y) = mk s x + mk s y :=
ext $ Ξ» i, by simp only [add_apply, mk_apply]; split_ifs; [refl, rw zero_add]
@[simp] lemma mk_zero [Ξ i, has_zero (Ξ² i)] {s : finset ΞΉ} :
mk s (0 : Ξ i : (βs : set ΞΉ), Ξ² i.1) = 0 :=
ext $ Ξ» i, by simp only [mk_apply]; split_ifs; refl
@[simp] lemma mk_neg [Ξ i, add_group (Ξ² i)] {s : finset ΞΉ} {x : Ξ i : (βs : set ΞΉ), Ξ² i.1} :
mk s (-x) = -mk s x :=
ext $ Ξ» i, by simp only [neg_apply, mk_apply]; split_ifs; [refl, rw neg_zero]
@[simp] lemma mk_sub [Ξ i, add_group (Ξ² i)] {s : finset ΞΉ} {x y : Ξ i : (βs : set ΞΉ), Ξ² i.1} :
mk s (x - y) = mk s x - mk s y :=
ext $ Ξ» i, by simp only [sub_apply, mk_apply]; split_ifs; [refl, rw sub_zero]
instance [Ξ i, add_group (Ξ² i)] {s : finset ΞΉ} : is_add_group_hom (@mk ΞΉ Ξ² _ _ s) :=
β¨Ξ» _ _, mk_addβ©
section
local attribute [instance] to_module
variables (Ξ³ : Type w) [ring Ξ³] [Ξ i, add_comm_group (Ξ² i)] [Ξ i, module Ξ³ (Ξ² i)]
include Ξ³
@[simp] lemma mk_smul {s : finset ΞΉ} {c : Ξ³} (x : Ξ i : (βs : set ΞΉ), Ξ² i.1) :
mk s (c β’ x) = c β’ mk s x :=
ext $ Ξ» i, by simp only [smul_apply, mk_apply]; split_ifs; [refl, rw smul_zero]
@[simp] lemma single_smul {i : ΞΉ} {c : Ξ³} {x : Ξ² i} :
single i (c β’ x) = c β’ single i x :=
ext $ Ξ» i, by simp only [smul_apply, single_apply]; split_ifs; [cases h, rw smul_zero]; refl
variable Ξ²
def lmk (s : finset ΞΉ) : (Ξ i : (βs : set ΞΉ), Ξ² i.1) ββ[Ξ³] Ξ β i, Ξ² i :=
β¨mk s, Ξ» _ _, mk_add, Ξ» c x, by rw [mk_smul Ξ³ x]β©
def lsingle (i) : Ξ² i ββ[Ξ³] Ξ β i, Ξ² i :=
β¨single i, Ξ» _ _, single_add, Ξ» _ _, single_smul _β©
variable {Ξ²}
@[simp] lemma lmk_apply {s : finset ΞΉ} {x} : lmk Ξ² Ξ³ s x = mk s x := rfl
@[simp] lemma lsingle_apply {i : ΞΉ} {x : Ξ² i} : lsingle Ξ² Ξ³ i x = single i x := rfl
end
section support_basic
variables [Ξ i, has_zero (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))]
def support (f : Ξ β i, Ξ² i) : finset ΞΉ :=
quotient.lift_on f (Ξ» x, x.2.to_finset.filter $ Ξ» i, x.1 i β 0) $
begin
intros x y Hxy,
ext i, split,
{ intro H,
rcases finset.mem_filter.1 H with β¨h1, h2β©,
rw Hxy i at h2,
exact finset.mem_filter.2 β¨multiset.mem_to_finset.2 $ (y.3 i).resolve_right h2, h2β© },
{ intro H,
rcases finset.mem_filter.1 H with β¨h1, h2β©,
rw β Hxy i at h2,
exact finset.mem_filter.2 β¨multiset.mem_to_finset.2 $ (x.3 i).resolve_right h2, h2β© },
end
@[simp] theorem support_mk_subset {s : finset ΞΉ} {x : Ξ i : (βs : set ΞΉ), Ξ² i.1} : (mk s x).support β s :=
Ξ» i H, multiset.mem_to_finset.1 (finset.mem_filter.1 H).1
@[simp] theorem mem_support_to_fun (f : Ξ β i, Ξ² i) (i) : i β f.support β f i β 0 :=
begin
refine quotient.induction_on f (Ξ» x, _),
dsimp only [support, quotient.lift_on_beta],
rw [finset.mem_filter, multiset.mem_to_finset],
exact and_iff_right_of_imp (x.3 i).resolve_right
end
theorem eq_mk_support (f : Ξ β i, Ξ² i) : f = mk f.support (Ξ» i, f i.1) :=
by ext i; by_cases h : f i = 0; try {simp at h}; simp [h]
@[simp] lemma support_zero : (0 : Ξ β i, Ξ² i).support = β
:= rfl
@[simp] lemma mem_support_iff (f : Ξ β i, Ξ² i) : βi:ΞΉ, i β f.support β f i β 0 :=
f.mem_support_to_fun
@[simp] lemma support_eq_empty {f : Ξ β i, Ξ² i} : f.support = β
β f = 0 :=
β¨Ξ» H, ext $ by simpa [finset.ext] using H, by simp {contextual:=tt}β©
instance decidable_zero : decidable_pred (eq (0 : Ξ β i, Ξ² i)) :=
Ξ» f, decidable_of_iff _ $ support_eq_empty.trans eq_comm
lemma support_subset_iff {s : set ΞΉ} {f : Ξ β i, Ξ² i} :
βf.support β s β (βiβs, f i = 0) :=
by simp [set.subset_def];
exact forall_congr (assume i, @not_imp_comm _ _ (classical.dec _) (classical.dec _))
lemma support_single_ne_zero {i : ΞΉ} {b : Ξ² i} (hb : b β 0) : (single i b).support = {i} :=
begin
ext j, by_cases h : i = j,
{ subst h, simp [hb] },
simp [ne.symm h, h]
end
lemma support_single_subset {i : ΞΉ} {b : Ξ² i} : (single i b).support β {i} :=
support_mk_subset
section map_range_and_zip_with
variables {Ξ²β : ΞΉ β Type vβ} {Ξ²β : ΞΉ β Type vβ}
variables [Ξ i, has_zero (Ξ²β i)] [Ξ i, has_zero (Ξ²β i)]
variables [Ξ i, decidable_pred (eq (0 : Ξ²β i))] [Ξ i, decidable_pred (eq (0 : Ξ²β i))]
lemma map_range_def {f : Ξ i, Ξ²β i β Ξ²β i} {hf : β i, f i 0 = 0} {g : Ξ β i, Ξ²β i} :
map_range f hf g = mk g.support (Ξ» i, f i.1 (g i.1)) :=
begin
ext i,
by_cases h : g i = 0,
{ simp [h, hf] },
{ simp at h, simp [h, hf] }
end
lemma support_map_range {f : Ξ i, Ξ²β i β Ξ²β i} {hf : β i, f i 0 = 0} {g : Ξ β i, Ξ²β i} :
(map_range f hf g).support β g.support :=
by simp [map_range_def]
@[simp] lemma map_range_single {f : Ξ i, Ξ²β i β Ξ²β i} {hf : β i, f i 0 = 0} {i : ΞΉ} {b : Ξ²β i} :
map_range f hf (single i b) = single i (f i b) :=
dfinsupp.ext $ Ξ» i', by by_cases i = i'; [{subst i', simp}, simp [h, hf]]
lemma zip_with_def {f : Ξ i, Ξ²β i β Ξ²β i β Ξ² i} {hf : β i, f i 0 0 = 0} {gβ : Ξ β i, Ξ²β i} {gβ : Ξ β i, Ξ²β i} :
zip_with f hf gβ gβ = mk (gβ.support βͺ gβ.support) (Ξ» i, f i.1 (gβ i.1) (gβ i.1)) :=
begin
ext i,
by_cases h1 : gβ i = 0; by_cases h2 : gβ i = 0;
try {simp at h1 h2}; simp [h1, h2, hf]
end
lemma support_zip_with {f : Ξ i, Ξ²β i β Ξ²β i β Ξ² i} {hf : β i, f i 0 0 = 0} {gβ : Ξ β i, Ξ²β i} {gβ : Ξ β i, Ξ²β i} :
(zip_with f hf gβ gβ).support β gβ.support βͺ gβ.support :=
by simp [zip_with_def]
end map_range_and_zip_with
lemma erase_def (i : ΞΉ) (f : Ξ β i, Ξ² i) :
f.erase i = mk (f.support.erase i) (Ξ» j, f j.1) :=
begin
ext j,
by_cases h1 : j = i; by_cases h2 : f j = 0;
try {simp at h2}; simp [h1, h2]
end
@[simp] lemma support_erase (i : ΞΉ) (f : Ξ β i, Ξ² i) :
(f.erase i).support = f.support.erase i :=
begin
ext j,
by_cases h1 : j = i; by_cases h2 : f j = 0;
try {simp at h2}; simp [h1, h2]
end
section filter_and_subtype_domain
variables {p : ΞΉ β Prop} [decidable_pred p]
lemma filter_def (f : Ξ β i, Ξ² i) :
f.filter p = mk (f.support.filter p) (Ξ» i, f i.1) :=
by ext i; by_cases h1 : p i; by_cases h2 : f i = 0;
try {simp at h2}; simp [h1, h2]
@[simp] lemma support_filter (f : Ξ β i, Ξ² i) :
(f.filter p).support = f.support.filter p :=
by ext i; by_cases h : p i; simp [h]
lemma subtype_domain_def (f : Ξ β i, Ξ² i) :
f.subtype_domain p = mk (f.support.subtype p) (Ξ» i, f i.1) :=
by ext i; cases i with i hi;
by_cases h1 : p i; by_cases h2 : f i = 0;
try {simp at h2}; dsimp; simp [h1, h2]
@[simp] lemma support_subtype_domain {f : Ξ β i, Ξ² i} :
(subtype_domain p f).support = f.support.subtype p :=
by ext i; cases i with i hi;
by_cases h1 : p i; by_cases h2 : f i = 0;
try {simp at h2}; dsimp; simp [h1, h2]
end filter_and_subtype_domain
end support_basic
lemma support_add [Ξ i, add_monoid (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))] {gβ gβ : Ξ β i, Ξ² i} :
(gβ + gβ).support β gβ.support βͺ gβ.support :=
support_zip_with
@[simp] lemma support_neg [Ξ i, add_group (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))] {f : Ξ β i, Ξ² i} :
support (-f) = support f :=
by ext i; simp
instance [decidable_eq ΞΉ] [Ξ i, has_zero (Ξ² i)] [Ξ i, decidable_eq (Ξ² i)] : decidable_eq (Ξ β i, Ξ² i) :=
assume f g, decidable_of_iff (f.support = g.support β§ (βiβf.support, f i = g i))
β¨assume β¨hβ, hββ©, ext $ assume i,
if h : i β f.support then hβ i h else
have hf : f i = 0, by rwa [f.mem_support_iff, not_not] at h,
have hg : g i = 0, by rwa [hβ, g.mem_support_iff, not_not] at h,
by rw [hf, hg],
by intro h; subst h; simpβ©
section prod_and_sum
variables {Ξ³ : Type w}
-- [to_additive dfinsupp.sum] for dfinsupp.prod doesn't work, the equation lemmas are not generated
/-- `sum f g` is the sum of `g i (f i)` over the support of `f`. -/
def sum [Ξ i, has_zero (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))] [add_comm_monoid Ξ³]
(f : Ξ β i, Ξ² i) (g : Ξ i, Ξ² i β Ξ³) : Ξ³ :=
f.support.sum (Ξ»i, g i (f i))
/-- `prod f g` is the product of `g i (f i)` over the support of `f`. -/
@[to_additive dfinsupp.sum]
def prod [Ξ i, has_zero (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))] [comm_monoid Ξ³]
(f : Ξ β i, Ξ² i) (g : Ξ i, Ξ² i β Ξ³) : Ξ³ :=
f.support.prod (Ξ»i, g i (f i))
attribute [to_additive dfinsupp.sum.equations._eqn_1] dfinsupp.prod.equations._eqn_1
@[to_additive dfinsupp.sum_map_range_index]
lemma prod_map_range_index {Ξ²β : ΞΉ β Type vβ} {Ξ²β : ΞΉ β Type vβ}
[Ξ i, has_zero (Ξ²β i)] [Ξ i, has_zero (Ξ²β i)]
[Ξ i, decidable_pred (eq (0 : Ξ²β i))] [Ξ i, decidable_pred (eq (0 : Ξ²β i))] [comm_monoid Ξ³]
{f : Ξ i, Ξ²β i β Ξ²β i} {hf : β i, f i 0 = 0} {g : Ξ β i, Ξ²β i} {h : Ξ i, Ξ²β i β Ξ³} (h0 : βi, h i 0 = 1) :
(map_range f hf g).prod h = g.prod (Ξ»i b, h i (f i b)) :=
begin
rw [map_range_def],
refine (finset.prod_subset support_mk_subset _).trans _,
{ intros i h1 h2,
dsimp, simp [h1] at h2, dsimp at h2,
simp [h1, h2, h0] },
{ refine finset.prod_congr rfl _,
intros i h1,
simp [h1] }
end
@[to_additive dfinsupp.sum_zero_index]
lemma prod_zero_index [Ξ i, add_comm_monoid (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))] [comm_monoid Ξ³]
{h : Ξ i, Ξ² i β Ξ³} : (0 : Ξ β i, Ξ² i).prod h = 1 :=
rfl
@[to_additive dfinsupp.sum_single_index]
lemma prod_single_index [Ξ i, has_zero (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))] [comm_monoid Ξ³]
{i : ΞΉ} {b : Ξ² i} {h : Ξ i, Ξ² i β Ξ³} (h_zero : h i 0 = 1) :
(single i b).prod h = h i b :=
begin
by_cases h : b = 0,
{ simp [h, prod_zero_index, h_zero], refl },
{ simp [dfinsupp.prod, support_single_ne_zero h] }
end
@[to_additive dfinsupp.sum_neg_index]
lemma prod_neg_index [Ξ i, add_group (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))] [comm_monoid Ξ³]
{g : Ξ β i, Ξ² i} {h : Ξ i, Ξ² i β Ξ³} (h0 : βi, h i 0 = 1) :
(-g).prod h = g.prod (Ξ»i b, h i (- b)) :=
prod_map_range_index h0
@[simp] lemma sum_apply {ΞΉβ : Type uβ} [decidable_eq ΞΉβ] {Ξ²β : ΞΉβ β Type vβ}
[Ξ iβ, has_zero (Ξ²β iβ)] [Ξ i, decidable_pred (eq (0 : Ξ²β i))]
[Ξ i, add_comm_monoid (Ξ² i)]
{f : Ξ β iβ, Ξ²β iβ} {g : Ξ iβ, Ξ²β iβ β Ξ β i, Ξ² i} {iβ : ΞΉ} :
(f.sum g) iβ = f.sum (Ξ»iβ b, g iβ b iβ) :=
(finset.sum_hom (Ξ»f : Ξ β i, Ξ² i, f iβ)).symm
lemma support_sum {ΞΉβ : Type uβ} [decidable_eq ΞΉβ] {Ξ²β : ΞΉβ β Type vβ}
[Ξ iβ, has_zero (Ξ²β iβ)] [Ξ i, decidable_pred (eq (0 : Ξ²β i))]
[Ξ i, add_comm_monoid (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))]
{f : Ξ β iβ, Ξ²β iβ} {g : Ξ iβ, Ξ²β iβ β Ξ β i, Ξ² i} :
(f.sum g).support β f.support.bind (Ξ»i, (g i (f i)).support) :=
have βiβ : ΞΉ, f.sum (Ξ» (i : ΞΉβ) (b : Ξ²β i), (g i b) iβ) β 0 β
(β (i : ΞΉβ), f i β 0 β§ Β¬ (g i (f i)) iβ = 0),
from assume iβ h,
let β¨i, hi, neβ© := finset.exists_ne_zero_of_sum_ne_zero h in
β¨i, (f.mem_support_iff i).mp hi, neβ©,
by simpa [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply] using this
@[simp] lemma sum_zero [Ξ i, add_comm_monoid (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))]
[add_comm_monoid Ξ³] {f : Ξ β i, Ξ² i} :
f.sum (Ξ»i b, (0 : Ξ³)) = 0 :=
finset.sum_const_zero
@[simp] lemma sum_add [Ξ i, add_comm_monoid (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))]
[add_comm_monoid Ξ³] {f : Ξ β i, Ξ² i} {hβ hβ : Ξ i, Ξ² i β Ξ³} :
f.sum (Ξ»i b, hβ i b + hβ i b) = f.sum hβ + f.sum hβ :=
finset.sum_add_distrib
@[simp] lemma sum_neg [Ξ i, add_comm_monoid (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))]
[add_comm_group Ξ³] {f : Ξ β i, Ξ² i} {h : Ξ i, Ξ² i β Ξ³} :
f.sum (Ξ»i b, - h i b) = - f.sum h :=
finset.sum_hom (@has_neg.neg Ξ³ _)
@[to_additive dfinsupp.sum_add_index]
lemma prod_add_index [Ξ i, add_comm_monoid (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))]
[comm_monoid Ξ³] {f g : Ξ β i, Ξ² i}
{h : Ξ i, Ξ² i β Ξ³} (h_zero : βi, h i 0 = 1) (h_add : βi bβ bβ, h i (bβ + bβ) = h i bβ * h i bβ) :
(f + g).prod h = f.prod h * g.prod h :=
have f_eq : (f.support βͺ g.support).prod (Ξ»i, h i (f i)) = f.prod h,
from (finset.prod_subset (finset.subset_union_left _ _) $
by simp [mem_support_iff, h_zero] {contextual := tt}).symm,
have g_eq : (f.support βͺ g.support).prod (Ξ»i, h i (g i)) = g.prod h,
from (finset.prod_subset (finset.subset_union_right _ _) $
by simp [mem_support_iff, h_zero] {contextual := tt}).symm,
calc (f + g).support.prod (Ξ»i, h i ((f + g) i)) =
(f.support βͺ g.support).prod (Ξ»i, h i ((f + g) i)) :
finset.prod_subset support_add $
by simp [mem_support_iff, h_zero] {contextual := tt}
... = (f.support βͺ g.support).prod (Ξ»i, h i (f i)) *
(f.support βͺ g.support).prod (Ξ»i, h i (g i)) :
by simp [h_add, finset.prod_mul_distrib]
... = _ : by rw [f_eq, g_eq]
lemma sum_sub_index [Ξ i, add_comm_group (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))]
[add_comm_group Ξ³] {f g : Ξ β i, Ξ² i}
{h : Ξ i, Ξ² i β Ξ³} (h_sub : βi bβ bβ, h i (bβ - bβ) = h i bβ - h i bβ) :
(f - g).sum h = f.sum h - g.sum h :=
have h_zero : βi, h i 0 = 0,
from assume i,
have h i (0 - 0) = h i 0 - h i 0, from h_sub i 0 0,
by simpa using this,
have h_neg : βi b, h i (- b) = - h i b,
from assume i b,
have h i (0 - b) = h i 0 - h i b, from h_sub i 0 b,
by simpa [h_zero] using this,
have h_add : βi bβ bβ, h i (bβ + bβ) = h i bβ + h i bβ,
from assume i bβ bβ,
have h i (bβ - (- bβ)) = h i bβ - h i (- bβ), from h_sub i bβ (-bβ),
by simpa [h_neg] using this,
by simp [@sum_add_index ΞΉ Ξ² _ Ξ³ _ _ _ f (-g) h h_zero h_add];
simp [@sum_neg_index ΞΉ Ξ² _ Ξ³ _ _ _ g h h_zero, h_neg];
simp [@sum_neg ΞΉ Ξ² _ Ξ³ _ _ _ g h]
@[to_additive dfinsupp.sum_finset_sum_index]
lemma prod_finset_sum_index {Ξ³ : Type w} {Ξ± : Type x}
[Ξ i, add_comm_monoid (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))]
[comm_monoid Ξ³] [decidable_eq Ξ±]
{s : finset Ξ±} {g : Ξ± β Ξ β i, Ξ² i}
{h : Ξ i, Ξ² i β Ξ³} (h_zero : βi, h i 0 = 1) (h_add : βi bβ bβ, h i (bβ + bβ) = h i bβ * h i bβ):
s.prod (Ξ»i, (g i).prod h) = (s.sum g).prod h :=
finset.induction_on s
(by simp [prod_zero_index])
(by simp [prod_add_index, h_zero, h_add] {contextual := tt})
@[to_additive dfinsupp.sum_sum_index]
lemma prod_sum_index {ΞΉβ : Type uβ} [decidable_eq ΞΉβ] {Ξ²β : ΞΉβ β Type vβ}
[Ξ iβ, has_zero (Ξ²β iβ)] [Ξ i, decidable_pred (eq (0 : Ξ²β i))]
[Ξ i, add_comm_monoid (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))]
[comm_monoid Ξ³]
{f : Ξ β iβ, Ξ²β iβ} {g : Ξ iβ, Ξ²β iβ β Ξ β i, Ξ² i}
{h : Ξ i, Ξ² i β Ξ³} (h_zero : βi, h i 0 = 1) (h_add : βi bβ bβ, h i (bβ + bβ) = h i bβ * h i bβ):
(f.sum g).prod h = f.prod (Ξ»i b, (g i b).prod h) :=
(prod_finset_sum_index h_zero h_add).symm
@[simp] lemma sum_single [Ξ i, add_comm_monoid (Ξ² i)]
[Ξ i, decidable_pred (eq (0 : Ξ² i))] {f : Ξ β i, Ξ² i} :
f.sum single = f :=
begin
apply dfinsupp.induction f, {rw [sum_zero_index]},
intros i b f H hb ih,
rw [sum_add_index, ih, sum_single_index],
all_goals { intros, simp }
end
@[to_additive dfinsupp.sum_subtype_domain_index]
lemma prod_subtype_domain_index [Ξ i, has_zero (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))]
[comm_monoid Ξ³] {v : Ξ β i, Ξ² i} {p : ΞΉ β Prop} [decidable_pred p]
{h : Ξ i, Ξ² i β Ξ³} (hp : βxβv.support, p x) :
(v.subtype_domain p).prod (Ξ»i b, h i.1 b) = v.prod h :=
finset.prod_bij (Ξ»p _, p.val)
(by simp)
(by simp)
(assume β¨aβ, haββ© β¨aβ, haββ©, by simp)
(Ξ» i hi, β¨β¨i, hp i hiβ©, by simpa using hi, rflβ©)
lemma subtype_domain_sum [Ξ i, add_comm_monoid (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))]
{s : finset Ξ³} {h : Ξ³ β Ξ β i, Ξ² i} {p : ΞΉ β Prop} [decidable_pred p] :
(s.sum h).subtype_domain p = s.sum (Ξ»c, (h c).subtype_domain p) :=
eq.symm (finset.sum_hom _)
lemma subtype_domain_finsupp_sum {Ξ΄ : Ξ³ β Type x} [decidable_eq Ξ³]
[Ξ c, has_zero (Ξ΄ c)] [Ξ c, decidable_pred (eq (0 : Ξ΄ c))]
[Ξ i, add_comm_monoid (Ξ² i)] [Ξ i, decidable_pred (eq (0 : Ξ² i))]
{p : ΞΉ β Prop} [decidable_pred p]
{s : Ξ β c, Ξ΄ c} {h : Ξ c, Ξ΄ c β Ξ β i, Ξ² i} :
(s.sum h).subtype_domain p = s.sum (Ξ»c d, (h c d).subtype_domain p) :=
subtype_domain_sum
end prod_and_sum
end dfinsupp
|
397b7f6dee8cb0c16f39e9fd5adde20e1f76df45 | c09f5945267fd905e23a77be83d9a78580e04a4a | /src/data/equiv/basic.lean | c6619b8dc28d8b64ec35ea0cc51aa4abf54b04f5 | [
"Apache-2.0"
] | permissive | OHIHIYA20/mathlib | 023a6df35355b5b6eb931c404f7dd7535dccfa89 | 1ec0a1f49db97d45e8666a3bf33217ff79ca1d87 | refs/heads/master | 1,587,964,529,965 | 1,551,819,319,000 | 1,551,819,319,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 32,862 | 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, Mario Carneiro
In the standard library we cannot assume the univalence axiom.
We say two types are equivalent if they are isomorphic.
Two equivalent types have the same cardinality.
-/
import logic.function logic.unique data.set.basic data.bool data.quot
open function
universes u v w
variables {Ξ± : Sort u} {Ξ² : Sort v} {Ξ³ : Sort w}
/-- `Ξ± β Ξ²` is the type of functions from `Ξ± β Ξ²` with a two-sided inverse. -/
structure equiv (Ξ± : Sort*) (Ξ² : Sort*) :=
(to_fun : Ξ± β Ξ²)
(inv_fun : Ξ² β Ξ±)
(left_inv : left_inverse inv_fun to_fun)
(right_inv : right_inverse inv_fun to_fun)
namespace equiv
/-- `perm Ξ±` is the type of bijections from `Ξ±` to itself. -/
@[reducible] def perm (Ξ± : Sort*) := equiv Ξ± Ξ±
infix ` β `:50 := equiv
instance : has_coe_to_fun (Ξ± β Ξ²) :=
β¨_, to_funβ©
@[simp] theorem coe_fn_mk (f : Ξ± β Ξ²) (g l r) : (equiv.mk f g l r : Ξ± β Ξ²) = f :=
rfl
theorem eq_of_to_fun_eq : β {eβ eβ : equiv Ξ± Ξ²}, (eβ : Ξ± β Ξ²) = eβ β eβ = eβ
| β¨fβ, gβ, lβ, rββ© β¨fβ, gβ, lβ, rββ© h :=
have fβ = fβ, from h,
have gβ = gβ, from funext $ assume x,
have fβ (gβ x) = fβ (gβ x), from (rβ x).trans (rβ x).symm,
have fβ (gβ x) = fβ (gβ x), by subst fβ; exact this,
show gβ x = gβ x, from injective_of_left_inverse lβ this,
by simp *
@[extensionality] lemma ext (f g : equiv Ξ± Ξ²) (H : β x, f x = g x) : f = g :=
eq_of_to_fun_eq (funext H)
@[extensionality] lemma perm.ext (Ο Ο : equiv.perm Ξ±) (H : β x, Ο x = Ο x) : Ο = Ο :=
equiv.ext _ _ H
@[refl] protected def refl (Ξ± : Sort*) : Ξ± β Ξ± := β¨id, id, Ξ» x, rfl, Ξ» x, rflβ©
@[symm] protected def symm (e : Ξ± β Ξ²) : Ξ² β Ξ± := β¨e.inv_fun, e.to_fun, e.right_inv, e.left_invβ©
@[trans] protected def trans (eβ : Ξ± β Ξ²) (eβ : Ξ² β Ξ³) : Ξ± β Ξ³ :=
β¨eβ.to_fun β eβ.to_fun, eβ.inv_fun β eβ.inv_fun,
eβ.left_inv.comp eβ.left_inv, eβ.right_inv.comp eβ.right_invβ©
protected theorem bijective : β f : Ξ± β Ξ², bijective f
| β¨f, g, hβ, hββ© :=
β¨injective_of_left_inverse hβ, surjective_of_has_right_inverse β¨_, hββ©β©
protected theorem subsingleton (e : Ξ± β Ξ²) : β [subsingleton Ξ²], subsingleton Ξ±
| β¨Hβ© := β¨Ξ» a b, e.bijective.1 (H _ _)β©
protected def decidable_eq (e : Ξ± β Ξ²) [H : decidable_eq Ξ²] : decidable_eq Ξ±
| a b := decidable_of_iff _ e.bijective.1.eq_iff
protected def cast {Ξ± Ξ² : Sort*} (h : Ξ± = Ξ²) : Ξ± β Ξ² :=
β¨cast h, cast h.symm, Ξ» x, by cases h; refl, Ξ» x, by cases h; reflβ©
@[simp] theorem coe_fn_symm_mk (f : Ξ± β Ξ²) (g l r) : ((equiv.mk f g l r).symm : Ξ² β Ξ±) = g :=
rfl
@[simp] theorem refl_apply (x : Ξ±) : equiv.refl Ξ± x = x := rfl
@[simp] theorem trans_apply (f : Ξ± β Ξ²) (g : Ξ² β Ξ³) (a : Ξ±) : (f.trans g) a = g (f a) := rfl
@[simp] theorem apply_inverse_apply : β (e : Ξ± β Ξ²) (x : Ξ²), e (e.symm x) = x
| β¨fβ, gβ, lβ, rββ© x := by simp [equiv.symm]; rw rβ
@[simp] theorem inverse_apply_apply : β (e : Ξ± β Ξ²) (x : Ξ±), e.symm (e x) = x
| β¨fβ, gβ, lβ, rββ© x := by simp [equiv.symm]; rw lβ
@[simp] lemma inverse_trans_apply (f : Ξ± β Ξ²) (g : Ξ² β Ξ³) (a : Ξ³) :
(f.trans g).symm a = f.symm (g.symm a) := rfl
@[simp] theorem apply_eq_iff_eq : β (f : Ξ± β Ξ²) (x y : Ξ±), f x = f y β x = y
| β¨fβ, gβ, lβ, rββ© x y := (injective_of_left_inverse lβ).eq_iff
@[simp] theorem cast_apply {Ξ± Ξ²} (h : Ξ± = Ξ²) (x : Ξ±) : equiv.cast h x = cast h x := rfl
lemma symm_apply_eq {Ξ± Ξ²} (e : Ξ± β Ξ²) {x y} : e.symm x = y β x = e y :=
β¨Ξ» H, by simp [H.symm], Ξ» H, by simp [H]β©
lemma eq_symm_apply {Ξ± Ξ²} (e : Ξ± β Ξ²) {x y} : y = e.symm x β e y = x :=
(eq_comm.trans e.symm_apply_eq).trans eq_comm
@[simp] theorem symm_symm (e : Ξ± β Ξ²) : e.symm.symm = e := by cases e; refl
@[simp] theorem trans_refl (e : Ξ± β Ξ²) : e.trans (equiv.refl Ξ²) = e := by cases e; refl
@[simp] theorem refl_trans (e : Ξ± β Ξ²) : (equiv.refl Ξ±).trans e = e := by cases e; refl
@[simp] theorem symm_trans (e : Ξ± β Ξ²) : e.symm.trans e = equiv.refl Ξ² := ext _ _ (by simp)
@[simp] theorem trans_symm (e : Ξ± β Ξ²) : e.trans e.symm = equiv.refl Ξ± := ext _ _ (by simp)
lemma trans_assoc {Ξ΄} (ab : Ξ± β Ξ²) (bc : Ξ² β Ξ³) (cd : Ξ³ β Ξ΄) :
(ab.trans bc).trans cd = ab.trans (bc.trans cd) :=
equiv.ext _ _ $ assume a, rfl
theorem left_inverse_symm (f : equiv Ξ± Ξ²) : left_inverse f.symm f := f.left_inv
theorem right_inverse_symm (f : equiv Ξ± Ξ²) : function.right_inverse f.symm f := f.right_inv
def equiv_congr {Ξ΄} (ab : Ξ± β Ξ²) (cd : Ξ³ β Ξ΄) : (Ξ± β Ξ³) β (Ξ² β Ξ΄) :=
β¨ Ξ»ac, (ab.symm.trans ac).trans cd, Ξ»bd, ab.trans $ bd.trans $ cd.symm,
assume ac, begin simp [trans_assoc], rw [β trans_assoc], simp end,
assume ac, begin simp [trans_assoc], rw [β trans_assoc], simp end, β©
def perm_congr {Ξ± : Type*} {Ξ² : Type*} (e : Ξ± β Ξ²) : perm Ξ± β perm Ξ² :=
equiv_congr e e
protected lemma image_eq_preimage {Ξ± Ξ²} (e : Ξ± β Ξ²) (s : set Ξ±) : e '' s = e.symm β»ΒΉ' s :=
set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv
protected lemma subset_image {Ξ± Ξ²} (e : Ξ± β Ξ²) (s : set Ξ±) (t : set Ξ²) : t β e '' s β e.symm '' t β s :=
by rw [set.image_subset_iff, e.image_eq_preimage]
lemma symm_image_image {Ξ± Ξ²} (f : equiv Ξ± Ξ²) (s : set Ξ±) : f.symm '' (f '' s) = s :=
by rw [β set.image_comp]; simpa using set.image_id s
protected lemma image_compl {Ξ± Ξ²} (f : equiv Ξ± Ξ²) (s : set Ξ±) :
f '' -s = -(f '' s) :=
set.image_compl_eq f.bijective
/- The group of permutations (self-equivalences) of a type `Ξ±` -/
namespace perm
instance perm_group {Ξ± : Type u} : group (perm Ξ±) :=
begin
refine { mul := Ξ» f g, equiv.trans g f, one := equiv.refl Ξ±, inv:= equiv.symm, ..};
intros; apply equiv.ext; try { apply trans_apply },
apply inverse_apply_apply
end
@[simp] theorem mul_apply {Ξ± : Type u} (f g : perm Ξ±) (x) : (f * g) x = f (g x) :=
equiv.trans_apply _ _ _
@[simp] theorem one_apply {Ξ± : Type u} (x) : (1 : perm Ξ±) x = x := rfl
@[simp] lemma inv_apply_self {Ξ± : Type u} (f : perm Ξ±) (x) :
fβ»ΒΉ (f x) = x := equiv.inverse_apply_apply _ _
@[simp] lemma apply_inv_self {Ξ± : Type u} (f : perm Ξ±) (x) :
f (fβ»ΒΉ x) = x := equiv.apply_inverse_apply _ _
lemma one_def {Ξ± : Type u} : (1 : perm Ξ±) = equiv.refl Ξ± := rfl
lemma mul_def {Ξ± : Type u} (f g : perm Ξ±) : f * g = g.trans f := rfl
lemma inv_def {Ξ± : Type u} (f : perm Ξ±) : fβ»ΒΉ = f.symm := rfl
end perm
def equiv_empty (h : Ξ± β false) : Ξ± β empty :=
β¨Ξ» x, (h x).elim, Ξ» e, e.rec _, Ξ» x, (h x).elim, Ξ» e, e.rec _β©
def false_equiv_empty : false β empty :=
equiv_empty _root_.id
def equiv_pempty (h : Ξ± β false) : Ξ± β pempty :=
β¨Ξ» x, (h x).elim, Ξ» e, e.rec _, Ξ» x, (h x).elim, Ξ» e, e.rec _β©
def false_equiv_pempty : false β pempty :=
equiv_pempty _root_.id
def empty_equiv_pempty : empty β pempty :=
equiv_pempty $ empty.rec _
def pempty_equiv_pempty : pempty.{v} β pempty.{w} :=
equiv_pempty pempty.elim
def empty_of_not_nonempty {Ξ± : Sort*} (h : Β¬ nonempty Ξ±) : Ξ± β empty :=
equiv_empty $ assume a, h β¨aβ©
def pempty_of_not_nonempty {Ξ± : Sort*} (h : Β¬ nonempty Ξ±) : Ξ± β pempty :=
equiv_pempty $ assume a, h β¨aβ©
def prop_equiv_punit {p : Prop} (h : p) : p β punit :=
β¨Ξ» x, (), Ξ» x, h, Ξ» _, rfl, Ξ» β¨β©, rflβ©
def true_equiv_punit : true β punit := prop_equiv_punit trivial
protected def ulift {Ξ± : Type u} : ulift Ξ± β Ξ± :=
β¨ulift.down, ulift.up, ulift.up_down, Ξ» a, rflβ©
protected def plift : plift Ξ± β Ξ± :=
β¨plift.down, plift.up, plift.up_down, plift.down_upβ©
@[congr] def arrow_congr {Ξ±β Ξ²β Ξ±β Ξ²β : Sort*} : Ξ±β β Ξ±β β Ξ²β β Ξ²β β (Ξ±β β Ξ²β) β (Ξ±β β Ξ²β)
| β¨fβ, gβ, lβ, rββ© β¨fβ, gβ, lβ, rββ© :=
β¨Ξ» (h : Ξ±β β Ξ²β) (a : Ξ±β), fβ (h (gβ a)),
Ξ» (h : Ξ±β β Ξ²β) (a : Ξ±β), gβ (h (fβ a)),
Ξ» h, by funext a; dsimp; rw [lβ, lβ],
Ξ» h, by funext a; dsimp; rw [rβ, rβ]β©
def punit_equiv_punit : punit.{v} β punit.{w} :=
β¨Ξ» _, punit.star, Ξ» _, punit.star, Ξ» u, by cases u; refl, Ξ» u, by cases u; reflexivityβ©
section
@[simp] def arrow_punit_equiv_punit (Ξ± : Sort*) : (Ξ± β punit.{v}) β punit.{w} :=
β¨Ξ» f, punit.star, Ξ» u f, punit.star, Ξ» f, by funext x; cases f x; refl, Ξ» u, by cases u; reflexivityβ©
@[simp] def punit_arrow_equiv (Ξ± : Sort*) : (punit.{u} β Ξ±) β Ξ± :=
β¨Ξ» f, f punit.star, Ξ» a u, a, Ξ» f, by funext x; cases x; refl, Ξ» u, rflβ©
@[simp] def empty_arrow_equiv_punit (Ξ± : Sort*) : (empty β Ξ±) β punit.{u} :=
β¨Ξ» f, punit.star, Ξ» u e, e.rec _, Ξ» f, funext $ Ξ» x, x.rec _, Ξ» u, by cases u; reflβ©
@[simp] def pempty_arrow_equiv_punit (Ξ± : Sort*) : (pempty β Ξ±) β punit.{u} :=
β¨Ξ» f, punit.star, Ξ» u e, e.rec _, Ξ» f, funext $ Ξ» x, x.rec _, Ξ» u, by cases u; reflβ©
@[simp] def false_arrow_equiv_punit (Ξ± : Sort*) : (false β Ξ±) β punit.{u} :=
calc (false β Ξ±) β (empty β Ξ±) : arrow_congr false_equiv_empty (equiv.refl _)
... β punit : empty_arrow_equiv_punit _
end
@[congr] def prod_congr {Ξ±β Ξ²β Ξ±β Ξ²β : Sort*} (eβ : Ξ±β β Ξ±β) (eβ :Ξ²β β Ξ²β) : (Ξ±β Γ Ξ²β) β (Ξ±β Γ Ξ²β) :=
β¨Ξ»p, (eβ p.1, eβ p.2), Ξ»p, (eβ.symm p.1, eβ.symm p.2),
Ξ» β¨a, bβ©, show (eβ.symm (eβ a), eβ.symm (eβ b)) = (a, b), by rw [inverse_apply_apply, inverse_apply_apply],
Ξ» β¨a, bβ©, show (eβ (eβ.symm a), eβ (eβ.symm b)) = (a, b), by rw [apply_inverse_apply, apply_inverse_apply]β©
@[simp] theorem prod_congr_apply {Ξ±β Ξ²β Ξ±β Ξ²β : Sort*} (eβ : Ξ±β β Ξ±β) (eβ : Ξ²β β Ξ²β) (a : Ξ±β) (b : Ξ²β) :
prod_congr eβ eβ (a, b) = (eβ a, eβ b) :=
rfl
@[simp] def prod_comm (Ξ± Ξ² : Sort*) : (Ξ± Γ Ξ²) β (Ξ² Γ Ξ±) :=
β¨Ξ» p, (p.2, p.1), Ξ» p, (p.2, p.1), Ξ»β¨a, bβ©, rfl, Ξ»β¨a, bβ©, rflβ©
@[simp] def prod_assoc (Ξ± Ξ² Ξ³ : Sort*) : ((Ξ± Γ Ξ²) Γ Ξ³) β (Ξ± Γ (Ξ² Γ Ξ³)) :=
β¨Ξ» p, β¨p.1.1, β¨p.1.2, p.2β©β©, Ξ»p, β¨β¨p.1, p.2.1β©, p.2.2β©, Ξ» β¨β¨a, bβ©, cβ©, rfl, Ξ» β¨a, β¨b, cβ©β©, rflβ©
@[simp] theorem prod_assoc_apply {Ξ± Ξ² Ξ³ : Sort*} (p : (Ξ± Γ Ξ²) Γ Ξ³) :
prod_assoc Ξ± Ξ² Ξ³ p = β¨p.1.1, β¨p.1.2, p.2β©β© := rfl
section
@[simp] def prod_punit (Ξ± : Sort*) : (Ξ± Γ punit.{u+1}) β Ξ± :=
β¨Ξ» p, p.1, Ξ» a, (a, punit.star), Ξ» β¨_, punit.starβ©, rfl, Ξ» a, rflβ©
@[simp] theorem prod_punit_apply {Ξ± : Sort*} (a : Ξ± Γ punit.{u+1}) : prod_punit Ξ± a = a.1 := rfl
@[simp] def punit_prod (Ξ± : Sort*) : (punit.{u+1} Γ Ξ±) β Ξ± :=
calc (punit Γ Ξ±) β (Ξ± Γ punit) : prod_comm _ _
... β Ξ± : prod_punit _
@[simp] theorem punit_prod_apply {Ξ± : Sort*} (a : punit.{u+1} Γ Ξ±) : punit_prod Ξ± a = a.2 := rfl
@[simp] def prod_empty (Ξ± : Sort*) : (Ξ± Γ empty) β empty :=
equiv_empty (Ξ» β¨_, eβ©, e.rec _)
@[simp] def empty_prod (Ξ± : Sort*) : (empty Γ Ξ±) β empty :=
equiv_empty (Ξ» β¨e, _β©, e.rec _)
@[simp] def prod_pempty (Ξ± : Sort*) : (Ξ± Γ pempty) β pempty :=
equiv_pempty (Ξ» β¨_, eβ©, e.rec _)
@[simp] def pempty_prod (Ξ± : Sort*) : (pempty Γ Ξ±) β pempty :=
equiv_pempty (Ξ» β¨e, _β©, e.rec _)
end
section
open sum
def psum_equiv_sum (Ξ± Ξ² : Sort*) : psum Ξ± Ξ² β (Ξ± β Ξ²) :=
β¨Ξ» s, psum.cases_on s inl inr,
Ξ» s, sum.cases_on s psum.inl psum.inr,
Ξ» s, by cases s; refl,
Ξ» s, by cases s; reflβ©
def sum_congr {Ξ±β Ξ²β Ξ±β Ξ²β : Sort*} : Ξ±β β Ξ±β β Ξ²β β Ξ²β β (Ξ±β β Ξ²β) β (Ξ±β β Ξ²β)
| β¨fβ, gβ, lβ, rββ© β¨fβ, gβ, lβ, rββ© :=
β¨Ξ» s, match s with inl aβ := inl (fβ aβ) | inr bβ := inr (fβ bβ) end,
Ξ» s, match s with inl aβ := inl (gβ aβ) | inr bβ := inr (gβ bβ) end,
Ξ» s, match s with inl a := congr_arg inl (lβ a) | inr a := congr_arg inr (lβ a) end,
Ξ» s, match s with inl a := congr_arg inl (rβ a) | inr a := congr_arg inr (rβ a) endβ©
@[simp] theorem sum_congr_apply_inl {Ξ±β Ξ²β Ξ±β Ξ²β : Sort*} (eβ : Ξ±β β Ξ±β) (eβ : Ξ²β β Ξ²β) (a : Ξ±β) :
sum_congr eβ eβ (inl a) = inl (eβ a) :=
by cases eβ; cases eβ; refl
@[simp] theorem sum_congr_apply_inr {Ξ±β Ξ²β Ξ±β Ξ²β : Sort*} (eβ : Ξ±β β Ξ±β) (eβ : Ξ²β β Ξ²β) (b : Ξ²β) :
sum_congr eβ eβ (inr b) = inr (eβ b) :=
by cases eβ; cases eβ; refl
def bool_equiv_punit_sum_punit : bool β (punit.{u+1} β punit.{v+1}) :=
β¨Ξ» b, cond b (inr punit.star) (inl punit.star),
Ξ» s, sum.rec_on s (Ξ»_, ff) (Ξ»_, tt),
Ξ» b, by cases b; refl,
Ξ» s, by rcases s with β¨β¨β©β© | β¨β¨β©β©; reflβ©
noncomputable def Prop_equiv_bool : Prop β bool :=
β¨Ξ» p, @to_bool p (classical.prop_decidable _),
Ξ» b, b, Ξ» p, by simp, Ξ» b, by simpβ©
@[simp] def sum_comm (Ξ± Ξ² : Sort*) : (Ξ± β Ξ²) β (Ξ² β Ξ±) :=
β¨Ξ» s, match s with inl a := inr a | inr b := inl b end,
Ξ» s, match s with inl b := inr b | inr a := inl a end,
Ξ» s, by cases s; refl,
Ξ» s, by cases s; reflβ©
@[simp] def sum_assoc (Ξ± Ξ² Ξ³ : Sort*) : ((Ξ± β Ξ²) β Ξ³) β (Ξ± β (Ξ² β Ξ³)) :=
β¨Ξ» s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end,
Ξ» s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end,
Ξ» s, by rcases s with β¨_ | _β© | _; refl,
Ξ» s, by rcases s with _ | _ | _; reflβ©
@[simp] theorem sum_assoc_apply_in1 {Ξ± Ξ² Ξ³} (a) : sum_assoc Ξ± Ξ² Ξ³ (inl (inl a)) = inl a := rfl
@[simp] theorem sum_assoc_apply_in2 {Ξ± Ξ² Ξ³} (b) : sum_assoc Ξ± Ξ² Ξ³ (inl (inr b)) = inr (inl b) := rfl
@[simp] theorem sum_assoc_apply_in3 {Ξ± Ξ² Ξ³} (c) : sum_assoc Ξ± Ξ² Ξ³ (inr c) = inr (inr c) := rfl
@[simp] def sum_empty (Ξ± : Sort*) : (Ξ± β empty) β Ξ± :=
β¨Ξ» s, match s with inl a := a | inr e := empty.rec _ e end,
inl,
Ξ» s, by rcases s with _ | β¨β¨β©β©; refl,
Ξ» a, rflβ©
@[simp] def empty_sum (Ξ± : Sort*) : (empty β Ξ±) β Ξ± :=
(sum_comm _ _).trans $ sum_empty _
@[simp] def sum_pempty (Ξ± : Sort*) : (Ξ± β pempty) β Ξ± :=
β¨Ξ» s, match s with inl a := a | inr e := pempty.rec _ e end,
inl,
Ξ» s, by rcases s with _ | β¨β¨β©β©; refl,
Ξ» a, rflβ©
@[simp] def pempty_sum (Ξ± : Sort*) : (pempty β Ξ±) β Ξ± :=
(sum_comm _ _).trans $ sum_pempty _
@[simp] def option_equiv_sum_punit (Ξ± : Sort*) : option Ξ± β (Ξ± β punit.{u+1}) :=
β¨Ξ» o, match o with none := inr punit.star | some a := inl a end,
Ξ» s, match s with inr _ := none | inl a := some a end,
Ξ» o, by cases o; refl,
Ξ» s, by rcases s with _ | β¨β¨β©β©; reflβ©
def sum_equiv_sigma_bool (Ξ± Ξ² : Sort*) : (Ξ± β Ξ²) β (Ξ£ b: bool, cond b Ξ± Ξ²) :=
β¨Ξ» s, match s with inl a := β¨tt, aβ© | inr b := β¨ff, bβ© end,
Ξ» s, match s with β¨tt, aβ© := inl a | β¨ff, bβ© := inr b end,
Ξ» s, by cases s; refl,
Ξ» s, by rcases s with β¨_|_, _β©; reflβ©
def equiv_fib {Ξ± Ξ² : Type*} (f : Ξ± β Ξ²) :
Ξ± β Ξ£ y : Ξ², {x // f x = y} :=
β¨Ξ» x, β¨f x, x, rflβ©, Ξ» x, x.2.1, Ξ» x, rfl, Ξ» β¨y, x, rflβ©, rflβ©
end
section
def Pi_congr_right {Ξ±} {Ξ²β Ξ²β : Ξ± β Sort*} (F : β a, Ξ²β a β Ξ²β a) : (Ξ a, Ξ²β a) β (Ξ a, Ξ²β a) :=
β¨Ξ» H a, F a (H a), Ξ» H a, (F a).symm (H a),
Ξ» H, funext $ by simp, Ξ» H, funext $ by simpβ©
end
section
def psigma_equiv_sigma {Ξ±} (Ξ² : Ξ± β Sort*) : psigma Ξ² β sigma Ξ² :=
β¨Ξ» β¨a, bβ©, β¨a, bβ©, Ξ» β¨a, bβ©, β¨a, bβ©, Ξ» β¨a, bβ©, rfl, Ξ» β¨a, bβ©, rflβ©
def sigma_congr_right {Ξ±} {Ξ²β Ξ²β : Ξ± β Sort*} (F : β a, Ξ²β a β Ξ²β a) : sigma Ξ²β β sigma Ξ²β :=
β¨Ξ» β¨a, bβ©, β¨a, F a bβ©, Ξ» β¨a, bβ©, β¨a, (F a).symm bβ©,
Ξ» β¨a, bβ©, congr_arg (sigma.mk a) $ inverse_apply_apply (F a) b,
Ξ» β¨a, bβ©, congr_arg (sigma.mk a) $ apply_inverse_apply (F a) bβ©
def sigma_congr_left {Ξ±β Ξ±β} {Ξ² : Ξ±β β Sort*} : β f : Ξ±β β Ξ±β, (Ξ£ a:Ξ±β, Ξ² (f a)) β (Ξ£ a:Ξ±β, Ξ² a)
| β¨f, g, l, rβ© :=
β¨Ξ» β¨a, bβ©, β¨f a, bβ©, Ξ» β¨a, bβ©, β¨g a, @@eq.rec Ξ² b (r a).symmβ©,
Ξ» β¨a, bβ©, match g (f a), l a : β a' (h : a' = a),
@sigma.mk _ (Ξ² β f) _ (@@eq.rec Ξ² b (congr_arg f h.symm)) = β¨a, bβ© with
| _, rfl := rfl end,
Ξ» β¨a, bβ©, match f (g a), _ : β a' (h : a' = a), sigma.mk a' (@@eq.rec Ξ² b h.symm) = β¨a, bβ© with
| _, rfl := rfl endβ©
def sigma_equiv_prod (Ξ± Ξ² : Sort*) : (Ξ£_:Ξ±, Ξ²) β (Ξ± Γ Ξ²) :=
β¨Ξ» β¨a, bβ©, β¨a, bβ©, Ξ» β¨a, bβ©, β¨a, bβ©, Ξ» β¨a, bβ©, rfl, Ξ» β¨a, bβ©, rflβ©
def sigma_equiv_prod_of_equiv {Ξ± Ξ²} {Ξ²β : Ξ± β Sort*} (F : β a, Ξ²β a β Ξ²) : sigma Ξ²β β (Ξ± Γ Ξ²) :=
(sigma_congr_right F).trans (sigma_equiv_prod Ξ± Ξ²)
end
section
def arrow_prod_equiv_prod_arrow (Ξ± Ξ² Ξ³ : Type*) : (Ξ³ β Ξ± Γ Ξ²) β ((Ξ³ β Ξ±) Γ (Ξ³ β Ξ²)) :=
β¨Ξ» f, (Ξ» c, (f c).1, Ξ» c, (f c).2),
Ξ» p c, (p.1 c, p.2 c),
Ξ» f, funext $ Ξ» c, prod.mk.eta,
Ξ» p, by cases p; reflβ©
def arrow_arrow_equiv_prod_arrow (Ξ± Ξ² Ξ³ : Sort*) : (Ξ± β Ξ² β Ξ³) β (Ξ± Γ Ξ² β Ξ³) :=
β¨Ξ» f, Ξ» p, f p.1 p.2,
Ξ» f, Ξ» a b, f (a, b),
Ξ» f, rfl,
Ξ» f, by funext p; cases p; reflβ©
open sum
def sum_arrow_equiv_prod_arrow (Ξ± Ξ² Ξ³ : Type*) : ((Ξ± β Ξ²) β Ξ³) β ((Ξ± β Ξ³) Γ (Ξ² β Ξ³)) :=
β¨Ξ» f, (f β inl, f β inr),
Ξ» p s, sum.rec_on s p.1 p.2,
Ξ» f, by funext s; cases s; refl,
Ξ» p, by cases p; reflβ©
def sum_prod_distrib (Ξ± Ξ² Ξ³ : Sort*) : ((Ξ± β Ξ²) Γ Ξ³) β ((Ξ± Γ Ξ³) β (Ξ² Γ Ξ³)) :=
β¨Ξ» p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end,
Ξ» s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end,
Ξ» p, by rcases p with β¨_ | _, _β©; refl,
Ξ» s, by rcases s with β¨_, _β© | β¨_, _β©; reflβ©
@[simp] theorem sum_prod_distrib_apply_left {Ξ± Ξ² Ξ³} (a : Ξ±) (c : Ξ³) :
sum_prod_distrib Ξ± Ξ² Ξ³ (sum.inl a, c) = sum.inl (a, c) := rfl
@[simp] theorem sum_prod_distrib_apply_right {Ξ± Ξ² Ξ³} (b : Ξ²) (c : Ξ³) :
sum_prod_distrib Ξ± Ξ² Ξ³ (sum.inr b, c) = sum.inr (b, c) := rfl
def prod_sum_distrib (Ξ± Ξ² Ξ³ : Sort*) : (Ξ± Γ (Ξ² β Ξ³)) β ((Ξ± Γ Ξ²) β (Ξ± Γ Ξ³)) :=
calc (Ξ± Γ (Ξ² β Ξ³)) β ((Ξ² β Ξ³) Γ Ξ±) : prod_comm _ _
... β ((Ξ² Γ Ξ±) β (Ξ³ Γ Ξ±)) : sum_prod_distrib _ _ _
... β ((Ξ± Γ Ξ²) β (Ξ± Γ Ξ³)) : sum_congr (prod_comm _ _) (prod_comm _ _)
@[simp] theorem prod_sum_distrib_apply_left {Ξ± Ξ² Ξ³} (a : Ξ±) (b : Ξ²) :
prod_sum_distrib Ξ± Ξ² Ξ³ (a, sum.inl b) = sum.inl (a, b) := rfl
@[simp] theorem prod_sum_distrib_apply_right {Ξ± Ξ² Ξ³} (a : Ξ±) (c : Ξ³) :
prod_sum_distrib Ξ± Ξ² Ξ³ (a, sum.inr c) = sum.inr (a, c) := rfl
def bool_prod_equiv_sum (Ξ± : Type u) : (bool Γ Ξ±) β (Ξ± β Ξ±) :=
calc (bool Γ Ξ±) β ((unit β unit) Γ Ξ±) : prod_congr bool_equiv_punit_sum_punit (equiv.refl _)
... β (Ξ± Γ (unit β unit)) : prod_comm _ _
... β ((Ξ± Γ unit) β (Ξ± Γ unit)) : prod_sum_distrib _ _ _
... β (Ξ± β Ξ±) : sum_congr (prod_punit _) (prod_punit _)
end
section
open sum nat
def nat_equiv_nat_sum_punit : β β (β β punit.{u+1}) :=
β¨Ξ» n, match n with zero := inr punit.star | succ a := inl a end,
Ξ» s, match s with inl n := succ n | inr punit.star := zero end,
Ξ» n, begin cases n, repeat { refl } end,
Ξ» s, begin cases s with a u, { refl }, {cases u, { refl }} endβ©
@[simp] def nat_sum_punit_equiv_nat : (β β punit.{u+1}) β β :=
nat_equiv_nat_sum_punit.symm
def int_equiv_nat_sum_nat : β€ β (β β β) :=
by refine β¨_, _, _, _β©; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl}
end
def list_equiv_of_equiv {Ξ± Ξ² : Type*} : Ξ± β Ξ² β list Ξ± β list Ξ²
| β¨f, g, l, rβ© :=
by refine β¨list.map f, list.map g, Ξ» x, _, Ξ» x, _β©;
simp [id_of_left_inverse l, id_of_right_inverse r]
def fin_equiv_subtype (n : β) : fin n β {m // m < n} :=
β¨Ξ» x, β¨x.1, x.2β©, Ξ» x, β¨x.1, x.2β©, Ξ» β¨a, bβ©, rfl,Ξ» β¨a, bβ©, rflβ©
def decidable_eq_of_equiv [decidable_eq Ξ²] (e : Ξ± β Ξ²) : decidable_eq Ξ±
| aβ aβ := decidable_of_iff (e aβ = e aβ) e.bijective.1.eq_iff
def inhabited_of_equiv [inhabited Ξ²] (e : Ξ± β Ξ²) : inhabited Ξ± :=
β¨e.symm (default _)β©
def unique_of_equiv (e : Ξ± β Ξ²) (h : unique Ξ²) : unique Ξ± :=
unique.of_surjective e.symm.bijective.2
def unique_congr (e : Ξ± β Ξ²) : unique Ξ± β unique Ξ² :=
{ to_fun := e.symm.unique_of_equiv,
inv_fun := e.unique_of_equiv,
left_inv := Ξ» _, subsingleton.elim _ _,
right_inv := Ξ» _, subsingleton.elim _ _ }
section
open subtype
def subtype_congr {p : Ξ± β Prop} {q : Ξ² β Prop}
(e : Ξ± β Ξ²) (h : β a, p a β q (e a)) : {a : Ξ± // p a} β {b : Ξ² // q b} :=
β¨Ξ» x, β¨e x.1, (h _).1 x.2β©,
Ξ» y, β¨e.symm y.1, (h _).2 (by simp; exact y.2)β©,
Ξ» β¨x, hβ©, subtype.eq' $ by simp,
Ξ» β¨y, hβ©, subtype.eq' $ by simpβ©
def subtype_equiv_of_subtype' {p : Ξ± β Prop} (e : Ξ± β Ξ²) :
{a : Ξ± // p a} β {b : Ξ² // p (e.symm b)} :=
subtype_congr e $ by simp
def subtype_congr_prop {Ξ± : Type*} {p q : Ξ± β Prop} (h : p = q) : subtype p β subtype q :=
subtype_congr (equiv.refl Ξ±) (assume a, h βΈ iff.refl _)
def set_congr {Ξ± : Type*} {s t : set Ξ±} (h : s = t) : s β t :=
subtype_congr_prop h
def subtype_subtype_equiv_subtype {Ξ± : Type u} (p : Ξ± β Prop) (q : subtype p β Prop) :
subtype q β {a : Ξ± // βh:p a, q β¨a, hβ© } :=
β¨Ξ»β¨β¨a, haβ©, ha'β©, β¨a, ha, ha'β©,
Ξ»β¨a, haβ©, β¨β¨a, ha.cases_on $ assume h _, hβ©, by cases ha; exact ha_hβ©,
assume β¨β¨a, haβ©, hβ©, rfl, assume β¨a, hβ, hββ©, rflβ©
/-- aka coimage -/
def equiv_sigma_subtype {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β Ξ²) : Ξ± β Ξ£ b, {x : Ξ± // f x = b} :=
β¨Ξ» x, β¨f x, x, rflβ©, Ξ» x, x.2.1, Ξ» x, rfl, Ξ» β¨b, x, Hβ©, sigma.eq H $ eq.drec_on H $ subtype.eq rflβ©
def pi_equiv_subtype_sigma (ΞΉ : Type*) (Ο : ΞΉ β Type*) :
(Ξ i, Ο i) β {f : ΞΉ β Ξ£i, Ο i | βi, (f i).1 = i } :=
β¨ Ξ»f, β¨Ξ»i, β¨i, f iβ©, assume i, rflβ©, Ξ»f i, begin rw β f.2 i, exact (f.1 i).2 end,
assume f, funext $ assume i, rfl,
assume β¨f, hfβ©, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $
eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _β©
def subtype_pi_equiv_pi {Ξ± : Sort u} {Ξ² : Ξ± β Sort v} {p : Ξ a, Ξ² a β Prop} :
{f : Ξ a, Ξ² a // βa, p a (f a) } β Ξ a, { b : Ξ² a // p a b } :=
β¨Ξ»f a, β¨f.1 a, f.2 aβ©, Ξ»f, β¨Ξ»a, (f a).1, Ξ»a, (f a).2β©,
by rintro β¨f, hβ©; refl,
by rintro f; funext a; exact subtype.eq' rflβ©
end
section
local attribute [elab_with_expected_type] quot.lift
def quot_equiv_of_quot' {r : Ξ± β Ξ± β Prop} {s : Ξ² β Ξ² β Prop} (e : Ξ± β Ξ²)
(h : β a a', r a a' β s (e a) (e a')) : quot r β quot s :=
β¨quot.lift (Ξ» a, quot.mk _ (e a)) (Ξ» a a' H, quot.sound ((h a a').mp H)),
quot.lift (Ξ» b, quot.mk _ (e.symm b)) (Ξ» b b' H, quot.sound ((h _ _).mpr (by convert H; simp))),
quot.ind $ by simp,
quot.ind $ by simpβ©
def quot_equiv_of_quot {r : Ξ± β Ξ± β Prop} (e : Ξ± β Ξ²) :
quot r β quot (Ξ» b b', r (e.symm b) (e.symm b')) :=
quot_equiv_of_quot' e (by simp)
end
namespace set
open set
protected def univ (Ξ±) : @univ Ξ± β Ξ± :=
β¨subtype.val, Ξ» a, β¨a, trivialβ©, Ξ» β¨a, _β©, rfl, Ξ» a, rflβ©
protected def empty (Ξ±) : (β
: set Ξ±) β empty :=
equiv_empty $ Ξ» β¨x, hβ©, not_mem_empty x h
protected def pempty (Ξ±) : (β
: set Ξ±) β pempty :=
equiv_pempty $ Ξ» β¨x, hβ©, not_mem_empty x h
protected def union' {Ξ±} {s t : set Ξ±}
(p : Ξ± β Prop) [decidable_pred p]
(hs : β x β s, p x)
(ht : β x β t, Β¬ p x) : (s βͺ t : set Ξ±) β (s β t) :=
β¨Ξ» β¨x, hβ©, if hp : p x
then sum.inl β¨_, h.resolve_right (Ξ» xt, ht _ xt hp)β©
else sum.inr β¨_, h.resolve_left (Ξ» xs, hp (hs _ xs))β©,
Ξ» o, match o with
| (sum.inl β¨x, hβ©) := β¨x, or.inl hβ©
| (sum.inr β¨x, hβ©) := β¨x, or.inr hβ©
end,
Ξ» β¨x, h'β©, by by_cases p x; simp [union'._match_1, union'._match_2, h]; congr,
Ξ» o, by rcases o with β¨x, hβ© | β¨x, hβ©; simp [union'._match_1, union'._match_2, h];
[simp [hs _ h], simp [ht _ h]]β©
protected def union {Ξ±} {s t : set Ξ±} [decidable_pred s] (H : s β© t = β
) :
(s βͺ t : set Ξ±) β (s β t) :=
set.union' s (Ξ» _, id) (Ξ» x xt xs, subset_empty_iff.2 H β¨xs, xtβ©)
protected def singleton {Ξ±} (a : Ξ±) : ({a} : set Ξ±) β punit.{u} :=
β¨Ξ» _, punit.star, Ξ» _, β¨a, mem_singleton _β©,
Ξ» β¨x, hβ©, by simp at h; subst x,
Ξ» β¨β©, rflβ©
protected def insert {Ξ±} {s : set.{u} Ξ±} [decidable_pred s] {a : Ξ±} (H : a β s) :
(insert a s : set Ξ±) β (s β punit.{u+1}) :=
by rw β union_singleton; exact
(set.union $ inter_singleton_eq_empty.2 H).trans
(sum_congr (equiv.refl _) (set.singleton _))
protected def sum_compl {Ξ±} (s : set Ξ±) [decidable_pred s] :
(s β (-s : set Ξ±)) β Ξ± :=
(set.union (inter_compl_self _)).symm.trans
(by rw union_compl_self; exact set.univ _)
protected def union_sum_inter {Ξ± : Type u} (s t : set Ξ±) [decidable_pred s] :
((s βͺ t : set Ξ±) β (s β© t : set Ξ±)) β (s β t) :=
calc ((s βͺ t : set Ξ±) β (s β© t : set Ξ±))
β ((s βͺ t \ s : set Ξ±) β (s β© t : set Ξ±)) : by rw [union_diff_self]
... β ((s β (t \ s : set Ξ±)) β (s β© t : set Ξ±)) :
sum_congr (set.union (inter_diff_self _ _)) (equiv.refl _)
... β (s β (t \ s : set Ξ±) β (s β© t : set Ξ±)) : sum_assoc _ _ _
... β (s β (t \ s βͺ s β© t : set Ξ±)) : sum_congr (equiv.refl _) begin
refine (set.union' (β s) _ _).symm,
exacts [Ξ» x hx, hx.2, Ξ» x hx, not_not_intro hx.1]
end
... β (s β t) : by rw (_ : t \ s βͺ s β© t = t);
rw [union_comm, inter_comm, inter_union_diff]
protected def prod {Ξ± Ξ²} (s : set Ξ±) (t : set Ξ²) :
(s.prod t) β (s Γ t) :=
β¨Ξ»p, β¨β¨p.1.1, p.2.1β©, β¨p.1.2, p.2.2β©β©,
Ξ»p, β¨β¨p.1.1, p.2.1β©, β¨p.1.2, p.2.2β©β©,
Ξ» β¨β¨x, yβ©, β¨hβ, hββ©β©, rfl,
Ξ» β¨β¨x, hββ©, β¨y, hββ©β©, rflβ©
protected noncomputable def image {Ξ± Ξ²} (f : Ξ± β Ξ²) (s : set Ξ±) (H : injective f) :
s β (f '' s) :=
β¨Ξ» β¨x, hβ©, β¨f x, mem_image_of_mem _ hβ©,
Ξ» β¨y, hβ©, β¨classical.some h, (classical.some_spec h).1β©,
Ξ» β¨x, hβ©, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).2),
Ξ» β¨y, hβ©, subtype.eq (classical.some_spec h).2β©
@[simp] theorem image_apply {Ξ± Ξ²} (f : Ξ± β Ξ²) (s : set Ξ±) (H : injective f) (a h) :
set.image f s H β¨a, hβ© = β¨f a, mem_image_of_mem _ hβ© := rfl
protected noncomputable def range {Ξ± Ξ²} (f : Ξ± β Ξ²) (H : injective f) :
Ξ± β range f :=
(set.univ _).symm.trans $ (set.image f univ H).trans (equiv.cast $ by rw image_univ)
@[simp] theorem range_apply {Ξ± Ξ²} (f : Ξ± β Ξ²) (H : injective f) (a) :
set.range f H a = β¨f a, set.mem_range_self _β© :=
by dunfold equiv.set.range equiv.set.univ;
simp [set_coe_cast, -image_univ, image_univ.symm]
end set
noncomputable def of_bijective {Ξ± Ξ²} {f : Ξ± β Ξ²} (hf : bijective f) : Ξ± β Ξ² :=
β¨f, Ξ» x, classical.some (hf.2 x), Ξ» x, hf.1 (classical.some_spec (hf.2 (f x))),
Ξ» x, classical.some_spec (hf.2 x)β©
@[simp] theorem of_bijective_to_fun {Ξ± Ξ²} {f : Ξ± β Ξ²} (hf : bijective f) : (of_bijective hf : Ξ± β Ξ²) = f := rfl
lemma subtype_quotient_equiv_quotient_subtype (pβ : Ξ± β Prop) [sβ : setoid Ξ±]
[sβ : setoid (subtype pβ)] (pβ : quotient sβ β Prop) (hpβ : β a, pβ a β pβ β¦aβ§)
(h : β x y : subtype pβ, @setoid.r _ sβ x y β (x : Ξ±) β y) :
{x // pβ x} β quotient sβ :=
{ to_fun := Ξ» a, quotient.hrec_on a.1 (Ξ» a h, β¦β¨a, (hpβ _).2 hβ©β§)
(Ξ» a b hab, hfunext (by rw quotient.sound hab)
(Ξ» hβ hβ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2,
inv_fun := Ξ» a, quotient.lift_on a (Ξ» a, (β¨β¦a.1β§, (hpβ _).1 a.2β© : {x // pβ x}))
(Ξ» a b hab, subtype.eq' (quotient.sound ((h _ _).1 hab))),
left_inv := Ξ» β¨a, haβ©, quotient.induction_on a (Ξ» a ha, rfl) ha,
right_inv := Ξ» a, quotient.induction_on a (Ξ» β¨a, haβ©, rfl) }
section swap
variable [decidable_eq Ξ±]
open decidable
def swap_core (a b r : Ξ±) : Ξ± :=
if r = a then b
else if r = b then a
else r
theorem swap_core_self (r a : Ξ±) : swap_core a a r = r :=
by unfold swap_core; split_ifs; cc
theorem swap_core_swap_core (r a b : Ξ±) : swap_core a b (swap_core a b r) = r :=
by unfold swap_core; split_ifs; cc
theorem swap_core_comm (r a b : Ξ±) : swap_core a b r = swap_core b a r :=
by unfold swap_core; split_ifs; cc
/-- `swap a b` is the permutation that swaps `a` and `b` and
leaves other values as is. -/
def swap (a b : Ξ±) : perm Ξ± :=
β¨swap_core a b, swap_core a b, Ξ»r, swap_core_swap_core r a b, Ξ»r, swap_core_swap_core r a bβ©
theorem swap_self (a : Ξ±) : swap a a = equiv.refl _ :=
eq_of_to_fun_eq $ funext $ Ξ» r, swap_core_self r a
theorem swap_comm (a b : Ξ±) : swap a b = swap b a :=
eq_of_to_fun_eq $ funext $ Ξ» r, swap_core_comm r _ _
theorem swap_apply_def (a b x : Ξ±) : swap a b x = if x = a then b else if x = b then a else x :=
rfl
@[simp] theorem swap_apply_left (a b : Ξ±) : swap a b a = b :=
if_pos rfl
@[simp] theorem swap_apply_right (a b : Ξ±) : swap a b b = a :=
by by_cases b = a; simp [swap_apply_def, *]
theorem swap_apply_of_ne_of_ne {a b x : Ξ±} : x β a β x β b β swap a b x = x :=
by simp [swap_apply_def] {contextual := tt}
@[simp] theorem swap_swap (a b : Ξ±) : (swap a b).trans (swap a b) = equiv.refl _ :=
eq_of_to_fun_eq $ funext $ Ξ» x, swap_core_swap_core _ _ _
theorem swap_comp_apply {a b x : Ξ±} (Ο : perm Ξ±) :
Ο.trans (swap a b) x = if Ο x = a then b else if Ο x = b then a else Ο x :=
by cases Ο; refl
@[simp] lemma swap_inv {Ξ± : Type*} [decidable_eq Ξ±] (x y : Ξ±) :
(swap x y)β»ΒΉ = swap x y := rfl
@[simp] lemma symm_trans_swap_trans [decidable_eq Ξ±] [decidable_eq Ξ²] (a b : Ξ±)
(e : Ξ± β Ξ²) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) :=
equiv.ext _ _ (Ξ» x, begin
have : β a, e.symm x = a β x = e a :=
Ξ» a, by rw @eq_comm _ (e.symm x); split; intros; simp * at *,
simp [swap_apply_def, this],
split_ifs; simp
end)
@[simp] lemma swap_mul_self {Ξ± : Type*} [decidable_eq Ξ±] (i j : Ξ±) : swap i j * swap i j = 1 :=
equiv.swap_swap i j
@[simp] lemma swap_apply_self {Ξ± : Type*} [decidable_eq Ξ±] (i j a : Ξ±) : swap i j (swap i j a) = a :=
by rw [β perm.mul_apply, swap_mul_self, perm.one_apply]
/-- Augment an equivalence with a prescribed mapping `f a = b` -/
def set_value (f : Ξ± β Ξ²) (a : Ξ±) (b : Ξ²) : Ξ± β Ξ² :=
(swap a (f.symm b)).trans f
@[simp] theorem set_value_eq (f : Ξ± β Ξ²) (a : Ξ±) (b : Ξ²) : set_value f a b a = b :=
by dsimp [set_value]; simp [swap_apply_left]
end swap
end equiv
instance {Ξ±} [subsingleton Ξ±] : subsingleton (ulift Ξ±) := equiv.ulift.subsingleton
instance {Ξ±} [subsingleton Ξ±] : subsingleton (plift Ξ±) := equiv.plift.subsingleton
instance {Ξ±} [decidable_eq Ξ±] : decidable_eq (ulift Ξ±) := equiv.ulift.decidable_eq
instance {Ξ±} [decidable_eq Ξ±] : decidable_eq (plift Ξ±) := equiv.plift.decidable_eq
def unique_unique_equiv : unique (unique Ξ±) β unique Ξ± :=
{ to_fun := Ξ» h, h.default,
inv_fun := Ξ» h, { default := h, uniq := Ξ» _, subsingleton.elim _ _ },
left_inv := Ξ» _, subsingleton.elim _ _,
right_inv := Ξ» _, subsingleton.elim _ _ }
def equiv_of_unique_of_unique [unique Ξ±] [unique Ξ²] : Ξ± β Ξ² :=
{ to_fun := Ξ» _, default Ξ²,
inv_fun := Ξ» _, default Ξ±,
left_inv := Ξ» _, subsingleton.elim _ _,
right_inv := Ξ» _, subsingleton.elim _ _ }
def equiv_punit_of_unique [unique Ξ±] : Ξ± β punit.{v} :=
equiv_of_unique_of_unique
namespace quot
/-- Quotients are congruent on equivalences under equality of their relation.
An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/
protected def congr {Ξ±} {r r' : Ξ± β Ξ± β Prop} (eq : βa b, r a b β r' a b) : quot r β quot r' :=
β¨quot.map r r' (assume a b, (eq a b).1), quot.map r' r (assume a b, (eq a b).2),
by rintros β¨aβ©; refl, by rintros β¨aβ©; reflβ©
end quot
namespace quotient
protected def congr {Ξ±} {r r' : setoid Ξ±} (eq : βa b, @setoid.r Ξ± r a b β @setoid.r Ξ± r' a b) :
quotient r β quotient r' :=
quot.congr eq
end quotient
|
9ba90c99b46f57e6bf2a27021d977a22ca233b76 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/ring_theory/polynomial/scale_roots.lean | 1db0705f98b5b574cc0c7e9c309d7d66a4d4363e | [
"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 | 5,325 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen, Devon Tuma
-/
import ring_theory.non_zero_divisors
import data.polynomial.algebra_map
/-!
# Scaling the roots of a polynomial
This file defines `scale_roots p s` for a polynomial `p` in one variable and a ring element `s` to
be the polynomial with root `r * s` for each root `r` of `p` and proves some basic results about it.
-/
section scale_roots
variables {A K R S : Type*} [comm_ring A] [is_domain A] [field K] [comm_ring R] [comm_ring S]
variables {M : submonoid A}
open polynomial
open_locale big_operators
/-- `scale_roots p s` is a polynomial with root `r * s` for each root `r` of `p`. -/
noncomputable def scale_roots (p : polynomial R) (s : R) : polynomial R :=
β i in p.support, monomial i (p.coeff i * s ^ (p.nat_degree - i))
@[simp] lemma coeff_scale_roots (p : polynomial R) (s : R) (i : β) :
(scale_roots p s).coeff i = coeff p i * s ^ (p.nat_degree - i) :=
by simp [scale_roots, coeff_monomial] {contextual := tt}
lemma coeff_scale_roots_nat_degree (p : polynomial R) (s : R) :
(scale_roots p s).coeff p.nat_degree = p.leading_coeff :=
by rw [leading_coeff, coeff_scale_roots, tsub_self, pow_zero, mul_one]
@[simp] lemma zero_scale_roots (s : R) : scale_roots 0 s = 0 := by { ext, simp }
lemma scale_roots_ne_zero {p : polynomial R} (hp : p β 0) (s : R) :
scale_roots p s β 0 :=
begin
intro h,
have : p.coeff p.nat_degree β 0 := mt leading_coeff_eq_zero.mp hp,
have : (scale_roots p s).coeff p.nat_degree = 0 :=
congr_fun (congr_arg (coeff : polynomial R β β β R) h) p.nat_degree,
rw [coeff_scale_roots_nat_degree] at this,
contradiction
end
lemma support_scale_roots_le (p : polynomial R) (s : R) :
(scale_roots p s).support β€ p.support :=
by { intro, simpa using left_ne_zero_of_mul }
lemma support_scale_roots_eq (p : polynomial R) {s : R} (hs : s β non_zero_divisors R) :
(scale_roots p s).support = p.support :=
le_antisymm (support_scale_roots_le p s)
begin
intro i,
simp only [coeff_scale_roots, polynomial.mem_support_iff],
intros p_ne_zero ps_zero,
have := ((non_zero_divisors R).pow_mem hs (p.nat_degree - i)) _ ps_zero,
contradiction
end
@[simp] lemma degree_scale_roots (p : polynomial R) {s : R} :
degree (scale_roots p s) = degree p :=
begin
haveI := classical.prop_decidable,
by_cases hp : p = 0,
{ rw [hp, zero_scale_roots] },
have := scale_roots_ne_zero hp s,
refine le_antisymm (finset.sup_mono (support_scale_roots_le p s)) (degree_le_degree _),
rw coeff_scale_roots_nat_degree,
intro h,
have := leading_coeff_eq_zero.mp h,
contradiction,
end
@[simp] lemma nat_degree_scale_roots (p : polynomial R) (s : R) :
nat_degree (scale_roots p s) = nat_degree p :=
by simp only [nat_degree, degree_scale_roots]
lemma monic_scale_roots_iff {p : polynomial R} (s : R) :
monic (scale_roots p s) β monic p :=
by simp only [monic, leading_coeff, nat_degree_scale_roots, coeff_scale_roots_nat_degree]
lemma scale_roots_evalβ_eq_zero {p : polynomial S} (f : S β+* R)
{r : R} {s : S} (hr : evalβ f r p = 0) :
evalβ f (f s * r) (scale_roots p s) = 0 :=
calc evalβ f (f s * r) (scale_roots p s) =
(scale_roots p s).support.sum (Ξ» i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) :
by simp [evalβ_eq_sum, sum_def]
... = p.support.sum (Ξ» i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) :
finset.sum_subset (support_scale_roots_le p s)
(Ξ» i hi hi', let this : coeff p i * s ^ (p.nat_degree - i) = 0 :=
by simpa using hi' in by simp [this])
... = p.support.sum (Ξ» (i : β), f (p.coeff i) * f s ^ (p.nat_degree - i + i) * r ^ i) :
finset.sum_congr rfl
(Ξ» i hi, by simp_rw [f.map_mul, f.map_pow, pow_add, mul_pow, mul_assoc])
... = p.support.sum (Ξ» (i : β), f s ^ p.nat_degree * (f (p.coeff i) * r ^ i)) :
finset.sum_congr rfl
(Ξ» i hi, by { rw [mul_assoc, mul_left_comm, tsub_add_cancel_of_le],
exact le_nat_degree_of_ne_zero (polynomial.mem_support_iff.mp hi) })
... = f s ^ p.nat_degree * p.support.sum (Ξ» (i : β), (f (p.coeff i) * r ^ i)) : finset.mul_sum.symm
... = f s ^ p.nat_degree * evalβ f r p : by { simp [evalβ_eq_sum, sum_def] }
... = 0 : by rw [hr, _root_.mul_zero]
lemma scale_roots_aeval_eq_zero [algebra S R] {p : polynomial S}
{r : R} {s : S} (hr : aeval r p = 0) :
aeval (algebra_map S R s * r) (scale_roots p s) = 0 :=
scale_roots_evalβ_eq_zero (algebra_map S R) hr
lemma scale_roots_evalβ_eq_zero_of_evalβ_div_eq_zero
{p : polynomial A} {f : A β+* K} (hf : function.injective f)
{r s : A} (hr : evalβ f (f r / f s) p = 0) (hs : s β non_zero_divisors A) :
evalβ f (f r) (scale_roots p s) = 0 :=
begin
convert scale_roots_evalβ_eq_zero f hr,
rw [βmul_div_assoc, mul_comm, mul_div_cancel],
exact map_ne_zero_of_mem_non_zero_divisors _ hf hs
end
lemma scale_roots_aeval_eq_zero_of_aeval_div_eq_zero [algebra A K]
(inj : function.injective (algebra_map A K)) {p : polynomial A} {r s : A}
(hr : aeval (algebra_map A K r / algebra_map A K s) p = 0) (hs : s β non_zero_divisors A) :
aeval (algebra_map A K r) (scale_roots p s) = 0 :=
scale_roots_evalβ_eq_zero_of_evalβ_div_eq_zero inj hr hs
end scale_roots
|
4f23476748a7a82c73513b7e23081c8475af857b | d450724ba99f5b50b57d244eb41fef9f6789db81 | /src/mywork/lectures/lecture_27b copy.lean | e9d9ce87aa4b71caa00d0afc7eb3099e93426aa7 | [] | no_license | jakekauff/CS2120F21 | 4f009adeb4ce4a148442b562196d66cc6c04530c | e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad | refs/heads/main | 1,693,841,880,030 | 1,637,604,848,000 | 1,637,604,848,000 | 399,946,698 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,912 | lean | import .lecture_26
import data.set
namespace relations
section functions
variables {Ξ± Ξ² Ξ³ : Type} (r : Ξ± β Ξ² β Prop)
local infix `βΊ`:50 := r
/-
SINGLE-VALUED BINARY RELATION
-/
def single_valued :=
β {x : Ξ±} {y z : Ξ²}, r x y β r x z β y = z
#check @single_valued -- property of a relation
/-
Exercises: Which of the following are single-valued?
- r = {(0,1), (0,2)}
- r = {(1,0), (2,0)}
- the unit circle on β
- r = {(-1,0), (0,-1), (1,0), (0,1)}
- y = x^2
- x = y^2
- y = + / - square root x
- f(x) = 3x+1
- y = sin x
- x = sin y
-/
/- FUNCTION
A single-valued binary relation is also called a
function (sometimes a functional binary relation).
-/
def function := single_valued r
/-
One possible property of a relation, r, is the
property of being a function, i.e., of r being
single-valued. Single-valuedness is a predicate
on relations. (This idea is isn't definable in
first order predicate logic.)
-/
#check @function
/-
The same vocabulary applies to functions as to
relations, as functions are just special cases
(single-valued) of otherwise arbitrary binary
relations.
As with any relation, for example, a function
has a domain, Ξ±, a domain of definition, and a
co-domain, Ξ². As with any relation, the set of
pairs of a function (that we're specifying) is
is some subset of Ξ± Γ Ξ²; or equivalently it is
in the powerset of Ξ± Γ Ξ².
When you want to express the idea that you have
an arbitrary relation (possible a function) from
Ξ± to Ξ², you may write either of the following:
- let r β Ξ± Γ Ξ² be any relation from Ξ± β Ξ²
- let r β π« (Ξ± Γ Ξ²) be any relation, Ξ± β Ξ²
- let r : Ξ± β Ξ² be any binary relation
Be sure you see that these are equivalent
statements! A key point is that in addition
to a set of pairs a function (or relation)
has a domain of definition and a co-domain.
Keeping track of exactly how a set of pairs
relates to its domain and codomain sets is
essential.
-/
/- FOR A RELATION TO BE "DEFINED" FOR A VALUE
Property: We say that a function is "defined" for some
value, (a : Ξ±), if there is some (b : Ξ²), such that the
pair, (a,b) is "in" r, i.e., (r a b) is true.
-/
def defined (a : Ξ±) := β (b : Ξ²), r a b
/-
Examples: Which is partial, which is total?
- the positive square root function for x β β (dom def)
- the positive square root function for x β β, x β₯ 0
-/
/- THE TOTAL vs PARTIAL FUNCTION DICHOTOMY
Property: We say that a function is "total" if it is
defined for every value in its domain. Note that this
usage of the word "total" is completely distinct from
what we learned earlier for relations in general. It's
thus better to use "strongly connected" for relations
to mean every object is related to another in at least
one direction, and to use total to refer to a function
that is defined on every element of its domain.
-/
def total_function := function r β§ β (a : Ξ±), defined r a
/-
At this point we expect that for a total function, r,
dom_of_def r = domain r. At one key juncture you use
the axiom of set extensionality to convert the goal
as an equality into that goal as a bi-implication.
After that it's basic predicate logical reasoning,
rather than more reasoning in set theory terms.
-/
example : total_function r β dom_of_def r = dom r :=
begin
assume total_r,
cases total_r with func_r defall,
unfold dom_of_def,
unfold dom,
apply set.ext,
assume x,
split,
-- forwards
assume h,
unfold defined at defall,
unfold defined at defall,
-- goal completed
-- backwards
assume h,
exact defall x,
end
/-
With that proof down as an example, we return to complete
our list of properties of functions:
- total
- partial
- strictly partial
Here are the definitions for the remaning two.
-/
def strictly_partial_fun := function r β§ Β¬total_function r
def partial_function := function r -- includes total funs
/-
Mathematicians generally consider the set of partial
functions to include the total functions. We will use
the term "strictly partial" function to mean a function,
f, that is not total, where dom_of_def f β dom f. (Be
sure you see that the subset symbol here means subset
but not equal. That's what the slash through the bottom
line in the symbol means: strict subset.)
-/
/- SURJECTIVE FUNCTIONS
A function that "covers" its codomain (where every value in
the codomain is an "output" for some value in its domain)
is said to map its domain *onto* its entire codomain.
Mathematicians will say that such a function is "onto,"
or "surjective."
-/
def surjective :=
total_function r β§
β (b : Ξ²), β a : Ξ±, r a b
/-
Should this be true?
-/
example :
surjective r β
image_set r (dom r) = { b : Ξ² | true } :=
begin
-- homework (on your own ungraded but please do it!)
end
/-
Which of the following functions are surjective?
- y = log x, viewed as a function from β β ββΊ
As written, the question is, um, tricky. Let's
analyze it. Then we'll give simpler questions.
First a little background on logarithmic and
exponential functions. Simply put, exponentiation
raises a base to an exponent to produce an output,
while the logarithm takes and converts it into
the exponent to which the base is raised to give
the input.
From basic algebra, the log (base 10) function,
y = log(x), is defined for any positive real, x,
and is equal to the exponent to which the base
(here 10) must be raised to produce x. Therefore
as usually defined its domain of definition is
the *positive reals* and its co-domain is (*all
of*) the reals.
Now consider the question again. The domain of
definition of log is the positive reals, so if
we expand the domain to all the reals, then the
resulting function becomes partial. On the other
side, if we restrict the range to the positive
reals, then we are excluding from the function
all those values in the interval (0,1) from the
input side in order to restrict the output to
values greater than 0.
Self homework: Graph this function.
- Ξ» x, log x : β+ β β, bijective?
- y = x^2, viewed as a function from β β β
- y = x, viewed as a function from β β β
- y = sin x, viewed as a function from β β β
- y = sin x, as a function from β to [-1,1] β β
-/
/- INJECTIVE FUNCTION
We have seen that for a relation to be a function, it
cannot be "one-to-many" (some x value is associated
with more than one y value). On the other hand, it is
possible for a function to associate many x values
with a single y value. There can be no fan-out from
x/domain values to y/codomain values, but there can
be fan-in from x to y values.
Which is the following functions exhibits "fan-in",
with different x values associated with the same y
values?
y = x
y = sin x
x = 1 (trick question)
y = 1
y = x^2 on β
y = x^2 on ββΊ (the positive reals)
-/
def injective :=
total_function r β§
β {x y : Ξ±} {z : Ξ²},
r x z β r y z β x = y
/-
We will often want to know that a function does not
map multiple x values to the same y value. Example:
in a company, we will very like want a function that
maps each employee to an employee ID number *unique*
to that employee. Rather than being "many to one" we
call such a function "one-to-one." We also say that
such a function has the property of being *injective*.
-/
/-
We will often want to know that a function does not
map multiple x values to the same y value. Example:
in a company, we will very like want a function that
maps each employee to an employee ID number *unique*
to that employee. Rather than being "many to one" we
call such a function "one-to-one." We also say that
such a function has the property of being *injective*.
There is yet another way to understand the concept.
-/
/- BIJECTIVE FUNCTIONS
-/
/-
Finally, a function is called one-to-one and onto, or
*bijective* if it is both surjective and injective. In
this case, it has to map every element of its domain
-/
def bijective := surjective r β§ injective r
/-
An essential property of any bijective relation is that
it puts the elements of the domain and codomain into a
one-to-one correspondence.
That we've assumed that a function is total is important
here. Here's a counterexample: consider the relation from
dom = {1,2,3} to codom = {A, B} with r = {(1,A), (2,B)}.
This function is injective and surjective but it clearly
does not establish a 1-1 correspondence.
We can define what it means for a strictly partial function
to be surjective or injective (we don't do it formally here).
We say that a partial function is surjective or injective if
its domain restriction to its domain of definition (making it
total) meets the definitions given above.
Note that our use of the term, one-to-one, here is
completely distinct from its use in the definition of
an injective function. An injective function is said
to be "one-to-one" in the sense that it's not many to
one: you can't have f(x) = k and f(y)=k where x β y.
A one-to-one correspondence *between two sets*, on the
other hand, is a pairing of elements that associates
each element of one set with a unique single element
of the other set, and vice versa.
-/
/-
Question: Is the inverse of a function always a function.
Think about the function, y = x^2. What is its inverse?
Is it's inverse a function? There's your answer.
A critical property of a bijective function, on the other
hand, is that its inverse is also a bijective function. It
is easy to see: just reverse the "arrows" in a one-to-one
correspondence between two sets. A function who inverse
is a function is said to be invertible (as a function, as
every relation has and inverse that is again a relation).
-/
/-
EXERCISE #1: Prove that the inverse of a
bijective function is a function. Ok, yes,
we will work this one out for you! But you
should really read and understand it. Then
the rest shouldn't be too bad.
-/
example : bijective r β function (inverse r) :=
begin
/-
Assume hypothesis
-/
assume r_bij,
/-
Unfold definitions and, from definitions,
deduce all the basic facts we'll have to
work with.
-/
cases r_bij with r_sur r_inj,
cases r_inj with r_tot r_one_to_one,
cases r_sur with r_tot r_onto,
unfold total_function at r_tot,
cases r_tot with r_fun alldef,
unfold function at r_fun,
unfold single_valued at r_fun,
unfold defined at alldef,
/-
What remains to be shown is that the
inverse of r is function. Expanding
the definition of function, that means
r inverse is single-valued. Let's see.
-/
unfold function,
unfold single_valued,
/-
To show that r inverse (mapping Ξ² values
back to Ξ± values) r is single-valued,
assume that b is some value of type Ξ²
(in the codomain of r) and show that if
r inverse maps b is mapped to both a1 and
a2 then a1 = a2.
-/
assume b a1 a2 irba1 irba2,
/-
Key insight: (inverse r) b a means r a b.
In other words, r b a is in r inverse (it
contains the pair (b, a)) if and only if
(a, b) is in r, i.e., r a b.
-/
unfold inverse at irba1 irba2,
/-
With those pairs now turned around, by the
injectivity of r, we're there!
-/
apply r_one_to_one irba1 irba2,
end
/-
Just to set expectations: The reality is that
I explored numerous ways of writing this proof.
Often a first proof will be confusing, messy,
etc. Most proofs of theorems you see in most
mathematics books are gems, polished in their
presentations by generations of mathematicians.
It took me a little while to get to this proof
script and the sequence of reasoning steps and
intermediate proof states it traverses.
-/
/- INJECTIVE AND SURJECTIVE *PARTIAL* FUNCTIONS
Okay, we actually are now able to to define just
what is means for a *partial* function to be
injective, surjective, bijective, which is that
it is so when its domain is restricted to its
domain of definition, rendering it total (at
which point the preceding definition applies).
-/
def injectivep := function r β§ injective (dom_res r (dom_of_def r))
def surjectivep := function r β§ surjective (dom_res r (dom_of_def r))
def bijectivep := function r β§ bijective (dom_res r (dom_of_def r))
-- EXERCISE #2: Prove that the inverse of a bijective function is bijective.
example : bijective r β bijective (inverse r) :=
begin
assume bij_r,
unfold bijective,
unfold bijective at bij_r,
cases bij_r with surj_r inj_r,
unfold surjective at surj_r,
unfold injective at inj_r,
cases surj_r with r_tot r_onto,
cases inj_r with r_tot r_one_to_one,
cases r_tot with r_fun alldef,
unfold function at r_fun,
unfold single_valued at r_fun,
apply and.intro _ _,
unfold surjective,
unfold total_function,
split,
split,
unfold function,
unfold single_valued,
unfold inverse,
assume b a x rab rxb,
apply r_one_to_one rab,
exact rxb,
assume b,
apply r_onto b,
unfold inverse,
unfold defined at alldef,
exact alldef,
unfold injective inverse,
split,
unfold total_function,
split,
unfold function,
unfold single_valued,
assume b a z rab rzb,
apply r_one_to_one rab rzb,
assume b,
unfold defined at alldef,
apply r_onto b,
assume c b a rac rab,
apply r_fun rac rab,
end
/-
EXERCISE #3: Prove that the inverse of the inverse of a bijective
function is that function.
-/
example : bijective r β (r = inverse (inverse r)) :=
begin
assume bijr,
unfold inverse,
end
/-
EXERCISE #4: Formally state and prove that every injective function
has a *function* as an inverse.
-/
example : injective r β function (inverse r) :=
begin
assume injr,-- hint: remember recent work
unfold function,
unfold single_valued,
cases injr with r_tot r_one_to_one,
unfold total_function at r_tot,
unfold function at r_tot,
unfold single_valued at r_tot,
unfold defined at r_tot,
cases r_tot with r_fun alldef,
assume x y z rxy rxz,
unfold inverse at rxy,
unfold inverse at rxz,
apply r_one_to_one rxy rxz,
end
/-
EXERCISE #5. Is bijectivity transitive? In other words, if the
relations, s and r, are both bijective, then is the
composition, s after r, also always bijective? Now
we'll see.
-/
open relations -- for definition of composition
/-
Check the following proposition. True? prove it for all.
False? Present a counterexample.
-/
def bij_trans (s : Ξ² β Ξ³ β Prop) (r : Ξ± β Ξ² β Prop) :
bijective r β bijective s β bijective (composition s r) :=
begin
assume bijr bijs,
unfold bijective,
apply and.intro _ _,
unfold bijective at bijr bijs,
cases bijr with r_sur r_inj,
cases bijs with s_sur s_inj,
unfold surjective,
unfold total_function,
unfold function,
unfold single_valued,
unfold surjective at r_sur s_sur,
unfold total_function at r_sur s_sur,
cases r_sur with r_tot r_onto,
cases s_sur with s_tot s_onto,
unfold function at r_tot s_tot,
unfold single_valued at r_tot s_tot,
cases r_tot with r_fun r_alldef,
cases s_tot with s_fun s_alldef,
unfold injective at r_inj s_inj,
cases r_inj with r_tot r_one_to_one,
cases s_inj with s_tot s_one_to_one,
unfold total_function at r_tot s_tot,
unfold function at r_tot s_tot,
unfold single_valued at r_tot s_tot,
unfold defined at r_tot s_tot r_alldef s_alldef,
cases r_tot with r_fun alldef_r,
cases s_tot with s_fun alldef_s,
split,
split,
unfold composition,
assume x y z,
assume h i,
apply exists.elim h,
apply exists.elim i,
assume b sbz_rxb,
assume t sty_rxt,
have rxb := sbz_rxb.right,
have rxt := sty_rxt.right,
have bt := r_fun rxb rxt,
have sbz := sbz_rxb.left,
have sty := sty_rxt.left,
have stz : s t z := eq.subst bt sbz,
apply s_fun sty stz,
assume i,
unfold defined,
have sr := composition s r,
have idd := sr i,
have idd2 := alldef_r i,
unfold composition,
cases idd2 with beta ribeta,
have idd3 := alldef_s beta,
cases idd3 with g sbetag,
apply exists.intro,
apply exists.intro,
apply and.intro sbetag ribeta,
assume g,
unfold composition,
have sr := composition s r,
have idd := s_onto g,
cases idd with b sbg,
have idd2:= r_onto b,
cases idd2 with a rab,
apply exists.intro,
apply exists.intro,
apply and.intro sbg rab,
unfold bijective at bijr bijs,
cases bijr with r_sur r_inj,
cases bijs with s_sur s_inj,
unfold injective,
unfold total_function,
unfold function,
unfold single_valued,
unfold surjective at r_sur s_sur,
unfold total_function at r_sur s_sur,
cases r_sur with r_tot r_onto,
cases s_sur with s_tot s_onto,
unfold function at r_tot s_tot,
unfold single_valued at r_tot s_tot,
cases r_tot with r_fun r_alldef,
cases s_tot with s_fun s_alldef,
unfold injective at r_inj s_inj,
cases r_inj with r_tot r_one_to_one,
cases s_inj with s_tot s_one_to_one,
unfold total_function at r_tot s_tot,
unfold function at r_tot s_tot,
unfold single_valued at r_tot s_tot,
unfold defined at r_tot s_tot r_alldef s_alldef,
cases r_tot with r_fun alldef_r,
cases s_tot with s_fun alldef_s,
split,
split,
unfold composition,
assume x y z,
assume h i,
apply exists.elim h,
apply exists.elim i,
assume b sbz_rxb,
assume t sty_rxt,
have sbz := sbz_rxb.left,
have sty := sty_rxt.left,
have rxb := sbz_rxb.right,
have rxt := sty_rxt.right,
have bt := r_fun rxb rxt,
have stz : s t z := eq.subst bt sbz,
apply s_fun sty stz,
assume i,
unfold defined,
have sr := composition s r,
have idd := sr i,
have idd2 := alldef_r i,
unfold composition,
cases idd2 with beta ribeta,
have idd3 := alldef_s beta,
cases idd3 with g sbetag,
apply exists.intro,
apply exists.intro,
apply and.intro sbetag ribeta,
assume i,
unfold composition,
have sr := composition s r,
assume a g,
assume e_sbg_rib e_sbg_rab,
cases e_sbg_rib with b sbg_rib,
cases e_sbg_rab with t stg_rat,
have sbg := sbg_rib.left,
have stg := stg_rat.left,
have rib := sbg_rib.right,
have rat := stg_rat.right,
have bt := s_one_to_one sbg stg,
have rit : r i t := eq.subst bt rib,
apply r_one_to_one rit rat,
end
/-
In general, an operation (such as inverse, here) that,
when applied twice, is the identity, is said to be an
involution. Relational inverse on bijective functions
is involutive in this sense.
A visualization: each green ball here goes to a red
ball there and the inverse takes each red ball right
back to the green ball from which it came, leaving
the original green ball as the end result, as well.
An identity function.
-/
end functions
end relations
|
a8fff60a75d41d03aeb2d04f246e78b2ec9091ed | c777c32c8e484e195053731103c5e52af26a25d1 | /src/analysis/special_functions/log/base.lean | 55ad5d89c3c362c58fbaaf0ed25d9764b62369b4 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 12,413 | lean | /-
Copyright (c) 2022 Bolton Bailey. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bolton Bailey, Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle SΓΆnne
-/
import analysis.special_functions.pow
import data.int.log
/-!
# Real logarithm base `b`
In this file we define `real.logb` to be the logarithm of a real number in a given base `b`. We
define this as the division of the natural logarithms of the argument and the base, so that we have
a globally defined function with `logb b 0 = 0`, `logb b (-x) = logb b x` `logb 0 x = 0` and
`logb (-b) x = logb b x`.
We prove some basic properties of this function and its relation to `rpow`.
## Tags
logarithm, continuity
-/
open set filter function
open_locale topology
noncomputable theory
namespace real
variables {b x y : β}
/-- The real logarithm in a given base. As with the natural logarithm, we define `logb b x` to
be `logb b |x|` for `x < 0`, and `0` for `x = 0`.-/
@[pp_nodot] noncomputable def logb (b x : β) : β := log x / log b
lemma log_div_log : log x / log b = logb b x := rfl
@[simp] lemma logb_zero : logb b 0 = 0 := by simp [logb]
@[simp] lemma logb_one : logb b 1 = 0 := by simp [logb]
@[simp] lemma logb_abs (x : β) : logb b (|x|) = logb b x := by rw [logb, logb, log_abs]
@[simp] lemma logb_neg_eq_logb (x : β) : logb b (-x) = logb b x :=
by rw [β logb_abs x, β logb_abs (-x), abs_neg]
lemma logb_mul (hx : x β 0) (hy : y β 0) : logb b (x * y) = logb b x + logb b y :=
by simp_rw [logb, log_mul hx hy, add_div]
lemma logb_div (hx : x β 0) (hy : y β 0) : logb b (x / y) = logb b x - logb b y :=
by simp_rw [logb, log_div hx hy, sub_div]
@[simp] lemma logb_inv (x : β) : logb b (xβ»ΒΉ) = -logb b x := by simp [logb, neg_div]
section b_pos_and_ne_one
variable (b_pos : 0 < b)
variable (b_ne_one : b β 1)
include b_pos b_ne_one
private lemma log_b_ne_zero : log b β 0 :=
begin
have b_ne_zero : b β 0, linarith,
have b_ne_minus_one : b β -1, linarith,
simp [b_ne_one, b_ne_zero, b_ne_minus_one],
end
@[simp] lemma logb_rpow :
logb b (b ^ x) = x :=
begin
rw [logb, div_eq_iff, log_rpow b_pos],
exact log_b_ne_zero b_pos b_ne_one,
end
lemma rpow_logb_eq_abs (hx : x β 0) : b ^ (logb b x) = |x| :=
begin
apply log_inj_on_pos,
simp only [set.mem_Ioi],
apply rpow_pos_of_pos b_pos,
simp only [abs_pos, mem_Ioi, ne.def, hx, not_false_iff],
rw [log_rpow b_pos, logb, log_abs],
field_simp [log_b_ne_zero b_pos b_ne_one],
end
@[simp] lemma rpow_logb (hx : 0 < x) : b ^ (logb b x) = x :=
by { rw rpow_logb_eq_abs b_pos b_ne_one (hx.ne'), exact abs_of_pos hx, }
lemma rpow_logb_of_neg (hx : x < 0) : b ^ (logb b x) = -x :=
by { rw rpow_logb_eq_abs b_pos b_ne_one (ne_of_lt hx), exact abs_of_neg hx }
lemma surj_on_logb : surj_on (logb b) (Ioi 0) univ :=
Ξ» x _, β¨rpow b x, rpow_pos_of_pos b_pos x, logb_rpow b_pos b_ne_oneβ©
lemma logb_surjective : surjective (logb b) :=
Ξ» x, β¨b ^ x, logb_rpow b_pos b_ne_oneβ©
@[simp] lemma range_logb : range (logb b) = univ :=
(logb_surjective b_pos b_ne_one).range_eq
lemma surj_on_logb' : surj_on (logb b) (Iio 0) univ :=
begin
intros x x_in_univ,
use -b ^ x,
split,
{ simp only [right.neg_neg_iff, set.mem_Iio], apply rpow_pos_of_pos b_pos, },
{ rw [logb_neg_eq_logb, logb_rpow b_pos b_ne_one], },
end
end b_pos_and_ne_one
section one_lt_b
variable (hb : 1 < b)
include hb
private lemma b_pos : 0 < b := by linarith
private lemma b_ne_one : b β 1 := by linarith
@[simp] lemma logb_le_logb (h : 0 < x) (hβ : 0 < y) :
logb b x β€ logb b y β x β€ y :=
by { rw [logb, logb, div_le_div_right (log_pos hb), log_le_log h hβ], }
lemma logb_lt_logb (hx : 0 < x) (hxy : x < y) : logb b x < logb b y :=
by { rw [logb, logb, div_lt_div_right (log_pos hb)], exact log_lt_log hx hxy, }
@[simp] lemma logb_lt_logb_iff (hx : 0 < x) (hy : 0 < y) :
logb b x < logb b y β x < y :=
by { rw [logb, logb, div_lt_div_right (log_pos hb)], exact log_lt_log_iff hx hy, }
lemma logb_le_iff_le_rpow (hx : 0 < x) : logb b x β€ y β x β€ b ^ y :=
by rw [βrpow_le_rpow_left_iff hb, rpow_logb (b_pos hb) (b_ne_one hb) hx]
lemma logb_lt_iff_lt_rpow (hx : 0 < x) : logb b x < y β x < b ^ y :=
by rw [βrpow_lt_rpow_left_iff hb, rpow_logb (b_pos hb) (b_ne_one hb) hx]
lemma le_logb_iff_rpow_le (hy : 0 < y) : x β€ logb b y β b ^ x β€ y :=
by rw [βrpow_le_rpow_left_iff hb, rpow_logb (b_pos hb) (b_ne_one hb) hy]
lemma lt_logb_iff_rpow_lt (hy : 0 < y) : x < logb b y β b ^ x < y :=
by rw [βrpow_lt_rpow_left_iff hb, rpow_logb (b_pos hb) (b_ne_one hb) hy]
lemma logb_pos_iff (hx : 0 < x) : 0 < logb b x β 1 < x :=
by { rw β @logb_one b, rw logb_lt_logb_iff hb zero_lt_one hx, }
lemma logb_pos (hx : 1 < x) : 0 < logb b x :=
by { rw logb_pos_iff hb (lt_trans zero_lt_one hx), exact hx, }
lemma logb_neg_iff (h : 0 < x) : logb b x < 0 β x < 1 :=
by { rw β logb_one, exact logb_lt_logb_iff hb h zero_lt_one, }
lemma logb_neg (h0 : 0 < x) (h1 : x < 1) : logb b x < 0 :=
(logb_neg_iff hb h0).2 h1
lemma logb_nonneg_iff (hx : 0 < x) : 0 β€ logb b x β 1 β€ x :=
by rw [β not_lt, logb_neg_iff hb hx, not_lt]
lemma logb_nonneg (hx : 1 β€ x) : 0 β€ logb b x :=
(logb_nonneg_iff hb (zero_lt_one.trans_le hx)).2 hx
lemma logb_nonpos_iff (hx : 0 < x) : logb b x β€ 0 β x β€ 1 :=
by rw [β not_lt, logb_pos_iff hb hx, not_lt]
lemma logb_nonpos_iff' (hx : 0 β€ x) : logb b x β€ 0 β x β€ 1 :=
begin
rcases hx.eq_or_lt with (rfl|hx),
{ simp [le_refl, zero_le_one] },
exact logb_nonpos_iff hb hx,
end
lemma logb_nonpos (hx : 0 β€ x) (h'x : x β€ 1) : logb b x β€ 0 :=
(logb_nonpos_iff' hb hx).2 h'x
lemma strict_mono_on_logb : strict_mono_on (logb b) (set.Ioi 0) :=
Ξ» x hx y hy hxy, logb_lt_logb hb hx hxy
lemma strict_anti_on_logb : strict_anti_on (logb b) (set.Iio 0) :=
begin
rintros x (hx : x < 0) y (hy : y < 0) hxy,
rw [β logb_abs y, β logb_abs x],
refine logb_lt_logb hb (abs_pos.2 hy.ne) _,
rwa [abs_of_neg hy, abs_of_neg hx, neg_lt_neg_iff],
end
lemma logb_inj_on_pos : set.inj_on (logb b) (set.Ioi 0) :=
(strict_mono_on_logb hb).inj_on
lemma eq_one_of_pos_of_logb_eq_zero (hβ : 0 < x) (hβ : logb b x = 0) :
x = 1 :=
logb_inj_on_pos hb (set.mem_Ioi.2 hβ) (set.mem_Ioi.2 zero_lt_one)
(hβ.trans real.logb_one.symm)
lemma logb_ne_zero_of_pos_of_ne_one (hx_pos : 0 < x) (hx : x β 1) :
logb b x β 0 :=
mt (eq_one_of_pos_of_logb_eq_zero hb hx_pos) hx
lemma tendsto_logb_at_top : tendsto (logb b) at_top at_top :=
tendsto.at_top_div_const (log_pos hb) tendsto_log_at_top
end one_lt_b
section b_pos_and_b_lt_one
variable (b_pos : 0 < b)
variable (b_lt_one : b < 1)
include b_lt_one
private lemma b_ne_one : b β 1 := by linarith
include b_pos
@[simp] lemma logb_le_logb_of_base_lt_one (h : 0 < x) (hβ : 0 < y) :
logb b x β€ logb b y β y β€ x :=
by { rw [logb, logb, div_le_div_right_of_neg (log_neg b_pos b_lt_one), log_le_log hβ h], }
lemma logb_lt_logb_of_base_lt_one (hx : 0 < x) (hxy : x < y) : logb b y < logb b x :=
by { rw [logb, logb, div_lt_div_right_of_neg (log_neg b_pos b_lt_one)], exact log_lt_log hx hxy, }
@[simp] lemma logb_lt_logb_iff_of_base_lt_one (hx : 0 < x) (hy : 0 < y) :
logb b x < logb b y β y < x :=
by { rw [logb, logb, div_lt_div_right_of_neg (log_neg b_pos b_lt_one)], exact log_lt_log_iff hy hx }
lemma logb_le_iff_le_rpow_of_base_lt_one (hx : 0 < x) : logb b x β€ y β b ^ y β€ x :=
by rw [βrpow_le_rpow_left_iff_of_base_lt_one b_pos b_lt_one, rpow_logb b_pos (b_ne_one b_lt_one) hx]
lemma logb_lt_iff_lt_rpow_of_base_lt_one (hx : 0 < x) : logb b x < y β b ^ y < x :=
by rw [βrpow_lt_rpow_left_iff_of_base_lt_one b_pos b_lt_one, rpow_logb b_pos (b_ne_one b_lt_one) hx]
lemma le_logb_iff_rpow_le_of_base_lt_one (hy : 0 < y) : x β€ logb b y β y β€ b ^ x :=
by rw [βrpow_le_rpow_left_iff_of_base_lt_one b_pos b_lt_one, rpow_logb b_pos (b_ne_one b_lt_one) hy]
lemma lt_logb_iff_rpow_lt_of_base_lt_one (hy : 0 < y) : x < logb b y β y < b ^ x :=
by rw [βrpow_lt_rpow_left_iff_of_base_lt_one b_pos b_lt_one, rpow_logb b_pos (b_ne_one b_lt_one) hy]
lemma logb_pos_iff_of_base_lt_one (hx : 0 < x) : 0 < logb b x β x < 1 :=
by rw [β @logb_one b, logb_lt_logb_iff_of_base_lt_one b_pos b_lt_one zero_lt_one hx]
lemma logb_pos_of_base_lt_one (hx : 0 < x) (hx' : x < 1) : 0 < logb b x :=
by { rw logb_pos_iff_of_base_lt_one b_pos b_lt_one hx, exact hx', }
lemma logb_neg_iff_of_base_lt_one (h : 0 < x) : logb b x < 0 β 1 < x :=
by rw [β @logb_one b, logb_lt_logb_iff_of_base_lt_one b_pos b_lt_one h zero_lt_one]
lemma logb_neg_of_base_lt_one (h1 : 1 < x) : logb b x < 0 :=
(logb_neg_iff_of_base_lt_one b_pos b_lt_one (lt_trans zero_lt_one h1)).2 h1
lemma logb_nonneg_iff_of_base_lt_one (hx : 0 < x) : 0 β€ logb b x β x β€ 1 :=
by rw [β not_lt, logb_neg_iff_of_base_lt_one b_pos b_lt_one hx, not_lt]
lemma logb_nonneg_of_base_lt_one (hx : 0 < x) (hx' : x β€ 1) : 0 β€ logb b x :=
by {rw [logb_nonneg_iff_of_base_lt_one b_pos b_lt_one hx], exact hx' }
lemma logb_nonpos_iff_of_base_lt_one (hx : 0 < x) : logb b x β€ 0 β 1 β€ x :=
by rw [β not_lt, logb_pos_iff_of_base_lt_one b_pos b_lt_one hx, not_lt]
lemma strict_anti_on_logb_of_base_lt_one : strict_anti_on (logb b) (set.Ioi 0) :=
Ξ» x hx y hy hxy, logb_lt_logb_of_base_lt_one b_pos b_lt_one hx hxy
lemma strict_mono_on_logb_of_base_lt_one : strict_mono_on (logb b) (set.Iio 0) :=
begin
rintros x (hx : x < 0) y (hy : y < 0) hxy,
rw [β logb_abs y, β logb_abs x],
refine logb_lt_logb_of_base_lt_one b_pos b_lt_one (abs_pos.2 hy.ne) _,
rwa [abs_of_neg hy, abs_of_neg hx, neg_lt_neg_iff],
end
lemma logb_inj_on_pos_of_base_lt_one : set.inj_on (logb b) (set.Ioi 0) :=
(strict_anti_on_logb_of_base_lt_one b_pos b_lt_one).inj_on
lemma eq_one_of_pos_of_logb_eq_zero_of_base_lt_one (hβ : 0 < x) (hβ : logb b x = 0) :
x = 1 :=
logb_inj_on_pos_of_base_lt_one b_pos b_lt_one (set.mem_Ioi.2 hβ) (set.mem_Ioi.2 zero_lt_one)
(hβ.trans real.logb_one.symm)
lemma logb_ne_zero_of_pos_of_ne_one_of_base_lt_one (hx_pos : 0 < x) (hx : x β 1) :
logb b x β 0 :=
mt (eq_one_of_pos_of_logb_eq_zero_of_base_lt_one b_pos b_lt_one hx_pos) hx
lemma tendsto_logb_at_top_of_base_lt_one : tendsto (logb b) at_top at_bot :=
begin
rw tendsto_at_top_at_bot,
intro e,
use 1 β b ^ e,
intro a,
simp only [and_imp, sup_le_iff],
intro ha,
rw logb_le_iff_le_rpow_of_base_lt_one b_pos b_lt_one,
tauto,
exact lt_of_lt_of_le zero_lt_one ha,
end
end b_pos_and_b_lt_one
lemma floor_logb_nat_cast {b : β} {r : β} (hb : 1 < b) (hr : 0 β€ r) : βlogb b rβ = int.log b r :=
begin
obtain rfl | hr := hr.eq_or_lt,
{ rw [logb_zero, int.log_zero_right, int.floor_zero] },
have hb1' : 1 < (b : β) := nat.one_lt_cast.mpr hb,
apply le_antisymm,
{ rw [βint.zpow_le_iff_le_log hb hr, βrpow_int_cast b],
refine le_of_le_of_eq _ (rpow_logb (zero_lt_one.trans hb1') hb1'.ne' hr),
exact rpow_le_rpow_of_exponent_le hb1'.le (int.floor_le _) },
{ rw [int.le_floor, le_logb_iff_rpow_le hb1' hr, rpow_int_cast],
exact int.zpow_log_le_self hb hr }
end
lemma ceil_logb_nat_cast {b : β} {r : β} (hb : 1 < b) (hr : 0 β€ r) : βlogb b rβ = int.clog b r :=
begin
obtain rfl | hr := hr.eq_or_lt,
{ rw [logb_zero, int.clog_zero_right, int.ceil_zero] },
have hb1' : 1 < (b : β) := nat.one_lt_cast.mpr hb,
apply le_antisymm,
{ rw [int.ceil_le, logb_le_iff_le_rpow hb1' hr, rpow_int_cast],
refine int.self_le_zpow_clog hb r },
{ rw [βint.le_zpow_iff_clog_le hb hr, βrpow_int_cast b],
refine (rpow_logb (zero_lt_one.trans hb1') hb1'.ne' hr).symm.trans_le _,
exact rpow_le_rpow_of_exponent_le hb1'.le (int.le_ceil _) },
end
@[simp] lemma logb_eq_zero :
logb b x = 0 β b = 0 β¨ b = 1 β¨ b = -1 β¨ x = 0 β¨ x = 1 β¨ x = -1 :=
begin
simp_rw [logb, div_eq_zero_iff, log_eq_zero],
tauto,
end
/- TODO add other limits and continuous API lemmas analogous to those in log.lean -/
open_locale big_operators
lemma logb_prod {Ξ± : Type*} (s : finset Ξ±) (f : Ξ± β β) (hf : β x β s, f x β 0):
logb b (β i in s, f i) = β i in s, logb b (f i) :=
begin
classical,
induction s using finset.induction_on with a s ha ih,
{ simp },
simp only [finset.mem_insert, forall_eq_or_imp] at hf,
simp [ha, ih hf.2, logb_mul hf.1 (finset.prod_ne_zero_iff.2 hf.2)],
end
end real
|
5a3f3f0b0472612bb7234bfa2268c27d405dc48a | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /src/Lean/Data/Json/Parser.lean | c3d8b434fc95ff8799ee02fe7133d8722d983a6d | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 7,410 | lean | /-
Copyright (c) 2019 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Marc Huisinga
-/
import Lean.Data.Json.Basic
namespace Lean
open Std (RBNode RBNode.singleton RBNode.leaf)
inductive Quickparse.Result (Ξ± : Type) where
| success (pos : String.Iterator) (res : Ξ±) : Result Ξ±
| error (pos : String.Iterator) (err : String) : Result Ξ±
def Quickparse (Ξ± : Type) : Type := String.Iterator β Lean.Quickparse.Result Ξ±
instance (Ξ± : Type) : Inhabited (Quickparse Ξ±) :=
β¨fun it => Quickparse.Result.error it ""β©
namespace Quickparse
open Result
partial def skipWs (it : String.Iterator) : String.Iterator :=
if it.hasNext then
let c := it.curr
if c = '\u0009' β¨ c = '\u000a' β¨ c = '\u000d' β¨ c = '\u0020' then
skipWs it.next
else
it
else
it
@[inline]
protected def pure (a : Ξ±) : Quickparse Ξ± := fun it =>
success it a
@[inline]
protected def bind {Ξ± Ξ² : Type} (f : Quickparse Ξ±) (g : Ξ± β Quickparse Ξ²) : Quickparse Ξ² := fun it =>
match f it with
| success rem a => g a rem
| error pos msg => error pos msg
@[inline]
def fail (msg : String) : Quickparse Ξ± := fun it =>
error it msg
@[inline]
instance : Monad Quickparse :=
{ pure := @Quickparse.pure, bind := @Quickparse.bind }
def unexpectedEndOfInput := "unexpected end of input"
@[inline]
def peek? : Quickparse (Option Char) := fun it =>
if it.hasNext then
success it it.curr
else
success it none
@[inline]
def peek! : Quickparse Char := do
let some c β peek? | fail unexpectedEndOfInput
c
@[inline]
def skip : Quickparse Unit := fun it =>
success it.next ()
@[inline]
def next : Quickparse Char := do
let c β peek!
skip
c
def expect (s : String) : Quickparse Unit := fun it =>
if it.extract (it.forward s.length) = s then
success (it.forward s.length) ()
else
error it s!"expected: {s}"
@[inline]
def ws : Quickparse Unit := fun it =>
success (skipWs it) ()
def expectedEndOfInput := "expected end of input"
@[inline]
def eoi : Quickparse Unit := fun it =>
if it.hasNext then
error it expectedEndOfInput
else
success it ()
end Quickparse
namespace Json.Parser
open Quickparse
@[inline]
def hexChar : Quickparse Nat := do
let c β next
if '0' β€ c β§ c β€ '9' then
pure $ c.val.toNat - '0'.val.toNat
else if 'a' β€ c β§ c β€ 'f' then
pure $ c.val.toNat - 'a'.val.toNat
else if 'A' β€ c β§ c β€ 'F' then
pure $ c.val.toNat - 'A'.val.toNat
else
fail "invalid hex character"
def escapedChar : Quickparse Char := do
let c β next
match c with
| '\\' => '\\'
| '"' => '"'
| '/' => '/'
| 'b' => '\x08'
| 'f' => '\x0c'
| 'n' => '\n'
| 'r' => '\x0d'
| 't' => '\t'
| 'u' =>
let u1 β hexChar; let u2 β hexChar; let u3 β hexChar; let u4 β hexChar
Char.ofNat $ 4096*u1 + 256*u2 + 16*u3 + u4
| _ => fail "illegal \\u escape"
partial def strCore (acc : String) : Quickparse String := do
let c β peek!
if c = '"' then -- "
skip
acc
else
let c β next
let ec β
if c = '\\' then
escapedChar
-- as to whether c.val > 0xffff should be split up and encoded with multiple \u,
-- the JSON standard is not definite: both directly printing the character
-- and encoding it with multiple \u is allowed. we choose the former.
else if 0x0020 β€ c.val β§ c.val β€ 0x10ffff then
c
else
fail "unexpected character in string"
strCore (acc.push ec)
def str : Quickparse String := strCore ""
partial def natCore (acc digits : Nat) : Quickparse (Nat Γ Nat) := do
let some c β peek? | (acc, digits)
if '0' β€ c β§ c β€ '9' then
skip
let acc' := 10*acc + (c.val.toNat - '0'.val.toNat)
natCore acc' (digits+1)
else
(acc, digits)
@[inline]
def lookahead (p : Char β Prop) (desc : String) [DecidablePred p] : Quickparse Unit := do
let c β peek!
if p c then
()
else
fail $ "expected " ++ desc
@[inline]
def natNonZero : Quickparse Nat := do
lookahead (fun c => '1' β€ c β§ c β€ '9') "1-9"
let (n, _) β natCore 0 0
n
@[inline]
def natNumDigits : Quickparse (Nat Γ Nat) := do
lookahead (fun c => '0' β€ c β§ c β€ '9') "digit"
natCore 0 0
@[inline]
def natMaybeZero : Quickparse Nat := do
let (n, _) β natNumDigits
n
def num : Quickparse JsonNumber := do
let c β peek!
let sign : Int β
if c = '-' then
skip
pure (-1 : Int)
else
pure 1
let c β peek!
let res β
if c = '0' then
skip
pure 0
else
natNonZero
let c? β peek?
let res : JsonNumber β
if c? = some '.' then
skip
let (n, d) β natNumDigits
if d > USize.size then fail "too many decimals"
let mantissa' := sign * (res * (10^d : Nat) + n)
let exponent' := d
JsonNumber.mk mantissa' exponent'
else
JsonNumber.fromInt (sign * res)
let c? β peek?
if c? = some 'e' β¨ c? = some 'E' then
skip
let c β peek!
if c = '-' then
skip
let n β natMaybeZero
res.shiftr n
else
if c = '+' then skip
let n β natMaybeZero
if n > USize.size then fail "exp too large"
res.shiftl n
else
res
partial def arrayCore (anyCore : Unit β Quickparse Json) (acc : Array Json) : Quickparse (Array Json) := do
let hd β anyCore ()
let acc' := acc.push hd
let c β next
if c = ']' then
ws
acc'
else if c = ',' then
ws
arrayCore anyCore acc'
else
fail "unexpected character in array"
partial def objectCore (anyCore : Unit β Quickparse Json) : Quickparse (RBNode String (fun _ => Json)) := do
lookahead (fun c => c = '"') "\""; skip; -- "
let k β strCore ""; ws
lookahead (fun c => c = ':') ":"; skip; ws
let v β anyCore ()
let c β next
if c = '}' then
ws
RBNode.singleton k v
else if c = ',' then
ws
let kvs β objectCore anyCore
kvs.insert compare k v
else
fail "unexpected character in object"
-- takes a unit parameter so that
-- we can use the equation compiler and recursion
partial def anyCore (u : Unit) : Quickparse Json := do
let c β peek!
if c = '[' then
skip; ws
let c β peek!
if c = ']' then
skip; ws
Json.arr (Array.mkEmpty 0)
else
let a β arrayCore anyCore (Array.mkEmpty 4)
Json.arr a
else if c = '{' then
skip; ws
let c β peek!
if c = '}' then
skip; ws
Json.obj (RBNode.leaf)
else
let kvs β objectCore anyCore
Json.obj kvs
else if c = '\"' then
skip
let s β strCore ""
ws
Json.str s
else if c = 'f' then
expect "false"; ws
Json.bool false
else if c = 't' then
expect "true"; ws
Json.bool true
else if c = 'n' then
expect "null"; ws
Json.null
else if c = '-' β¨ ('0' β€ c β§ c β€ '9') then
let n β num
ws
Json.num n
else
fail "unexpected input"
def any : Quickparse Json := do
ws
let res β anyCore ()
eoi
res
end Json.Parser
namespace Json
def parse (s : String) : Except String Lean.Json :=
match Json.Parser.any s.mkIterator with
| Quickparse.Result.success _ res => Except.ok res
| Quickparse.Result.error it err => Except.error s!"offset {it.i.repr}: {err}"
end Json
end Lean
|
9c7283a30c10fb786cdfa373a2fb3bf0834b8e5c | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/opaque_hint_bug.lean | 12df20a2900703524ac64a7941cd6b84e2bd19b6 | [
"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 | 245 | lean | inductive list (T : Type) : Type :=
| nil {} : list T
| cons : T β list T β list T
section
variable {T : Type}
definition concat (s t : list T) : list T
:= list.rec t (fun x l u, list.cons x u) s
attribute concat [reducible]
end
|
e42b7623bbafe153155f05712f11e5d01e8740e7 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/analysis/normed_space/ordered.lean | 83fda0a83baf30b1678d65c734d93ef9169c3055 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,429 | lean | /-
Copyright (c) 2020 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.analysis.normed_space.basic
import Mathlib.algebra.ring.basic
import Mathlib.analysis.asymptotics
import Mathlib.PostPort
universes u_1 l
namespace Mathlib
/-!
# Ordered normed spaces
In this file, we define classes for fields and groups that are both normed and ordered.
These are mostly useful to avoid diamonds during type class inference.
-/
/-- A `normed_linear_ordered_group` is an additive group that is both a `normed_group` and
a `linear_ordered_add_comm_group`. This class is necessary to avoid diamonds. -/
class normed_linear_ordered_group (Ξ± : Type u_1)
extends has_norm Ξ±, linear_ordered_add_comm_group Ξ±, metric_space Ξ±
where
dist_eq : β (x y : Ξ±), dist x y = norm (x - y)
protected instance normed_linear_ordered_group.to_normed_group (Ξ± : Type u_1) [normed_linear_ordered_group Ξ±] : normed_group Ξ± :=
normed_group.mk normed_linear_ordered_group.dist_eq
/-- A `normed_linear_ordered_field` is a field that is both a `normed_field` and a
`linear_ordered_field`. This class is necessary to avoid diamonds. -/
class normed_linear_ordered_field (Ξ± : Type u_1)
extends linear_ordered_field Ξ±, metric_space Ξ±, has_norm Ξ±
where
dist_eq : β (x y : Ξ±), dist x y = norm (x - y)
norm_mul' : β (a b : Ξ±), norm (a * b) = norm a * norm b
protected instance normed_linear_ordered_field.to_normed_field (Ξ± : Type u_1) [normed_linear_ordered_field Ξ±] : normed_field Ξ± :=
normed_field.mk normed_linear_ordered_field.dist_eq normed_linear_ordered_field.norm_mul'
protected instance normed_linear_ordered_field.to_normed_linear_ordered_group (Ξ± : Type u_1) [normed_linear_ordered_field Ξ±] : normed_linear_ordered_group Ξ± :=
normed_linear_ordered_group.mk normed_linear_ordered_field.dist_eq
theorem tendsto_pow_div_pow_at_top_of_lt {Ξ± : Type u_1} [normed_linear_ordered_field Ξ±] [order_topology Ξ±] {p : β} {q : β} (hpq : p < q) : filter.tendsto (fun (x : Ξ±) => x ^ p / x ^ q) filter.at_top (nhds 0) := sorry
theorem is_o_pow_pow_at_top_of_lt {Ξ± : Type} [normed_linear_ordered_field Ξ±] [order_topology Ξ±] {p : β} {q : β} (hpq : p < q) : asymptotics.is_o (fun (x : Ξ±) => x ^ p) (fun (x : Ξ±) => x ^ q) filter.at_top := sorry
|
543a83670898f72b2221aa95e3123fdc23b5d23b | 88fb7558b0636ec6b181f2a548ac11ad3919f8a5 | /library/init/coe.lean | f9a9e13264906a901b10c3deeef0ff4360a64052 | [
"Apache-2.0"
] | permissive | moritayasuaki/lean | 9f666c323cb6fa1f31ac597d777914aed41e3b7a | ae96ebf6ee953088c235ff7ae0e8c95066ba8001 | refs/heads/master | 1,611,135,440,814 | 1,493,852,869,000 | 1,493,852,869,000 | 90,269,903 | 0 | 0 | null | 1,493,906,291,000 | 1,493,906,291,000 | null | UTF-8 | Lean | false | false | 6,606 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
/-
The elaborator tries to insert coercions automatically.
Only instances of has_coe type class are considered in the process.
Lean also provides a "lifting" operator: βa.
It uses all instances of has_lift type class.
Every has_coe instance is also a has_lift instance.
We recommend users only use has_coe for coercions that do not produce a lot
of ambiguity.
All coercions and lifts can be identified with the constant coe.
We use the has_coe_to_fun type class for encoding coercions from
a type to a function space.
We use the has_coe_to_sort type class for encoding coercions from
a type to a sort.
-/
prelude
import init.data.list.basic init.data.subtype.basic init.data.prod
universes u v
class has_lift (a : Sort u) (b : Sort v) :=
(lift : a β b)
/- Auxiliary class that contains the transitive closure of has_lift. -/
class has_lift_t (a : Sort u) (b : Sort v) :=
(lift : a β b)
class has_coe (a : Sort u) (b : Sort v) :=
(coe : a β b)
/- Auxiliary class that contains the transitive closure of has_coe. -/
class has_coe_t (a : Sort u) (b : Sort v) :=
(coe : a β b)
class has_coe_to_fun (a : Sort u) : Sort (max u (v+1)) :=
(F : a β Sort v) (coe : Ξ x, F x)
class has_coe_to_sort (a : Sort u) : Type (max u (v+1)) :=
(S : Sort v) (coe : a β S)
def lift {a : Sort u} {b : Sort v} [has_lift a b] : a β b :=
@has_lift.lift a b _
def lift_t {a : Sort u} {b : Sort v} [has_lift_t a b] : a β b :=
@has_lift_t.lift a b _
def coe_b {a : Sort u} {b : Sort v} [has_coe a b] : a β b :=
@has_coe.coe a b _
def coe_t {a : Sort u} {b : Sort v} [has_coe_t a b] : a β b :=
@has_coe_t.coe a b _
def coe_fn_b {a : Sort u} [has_coe_to_fun.{u v} a] : Ξ x : a, has_coe_to_fun.F.{u v} x :=
has_coe_to_fun.coe
/- User level coercion operators -/
@[reducible] def coe {a : Sort u} {b : Sort v} [has_lift_t a b] : a β b :=
lift_t
@[reducible] def coe_fn {a : Sort u} [has_coe_to_fun.{u v} a] : Ξ x : a, has_coe_to_fun.F.{u v} x :=
has_coe_to_fun.coe
@[reducible] def coe_sort {a : Sort u} [has_coe_to_sort.{u v} a] : a β has_coe_to_sort.S.{u v} a :=
has_coe_to_sort.coe
/- Notation -/
notation `β`:max x:max := coe x
notation `β`:max x:max := coe_fn x
notation `β₯`:max x:max := coe_sort x
universes uβ uβ uβ
/- Transitive closure for has_lift, has_coe, has_coe_to_fun -/
instance lift_trans {a : Sort uβ} {b : Sort uβ} {c : Sort uβ} [has_lift a b] [has_lift_t b c] : has_lift_t a c :=
β¨Ξ» x, lift_t (lift x : b)β©
instance lift_base {a : Sort u} {b : Sort v} [has_lift a b] : has_lift_t a b :=
β¨liftβ©
instance coe_trans {a : Sort uβ} {b : Sort uβ} {c : Sort uβ} [has_coe a b] [has_coe_t b c] : has_coe_t a c :=
β¨Ξ» x, coe_t (coe_b x : b)β©
instance coe_base {a : Sort u} {b : Sort v} [has_coe a b] : has_coe_t a b :=
β¨coe_bβ©
/- We add this instance directly into has_coe_t to avoid non-termination.
Suppose coe_option had type (has_coe a (option a)).
Then, we can loop when searching a coercion from Ξ± to Ξ² (has_coe_t Ξ± Ξ²)
1- coe_trans at (has_coe_t Ξ± Ξ²)
(has_coe Ξ± ?bβ) and (has_coe_t ?bβ c)
2- coe_option at (has_coe Ξ± ?bβ)
?bβ := option Ξ±
3- coe_trans at (has_coe_t (option Ξ±) Ξ²)
(has_coe (option Ξ±) ?bβ) and (has_coe_t ?bβ Ξ²)
4- coe_option at (has_coe (option Ξ±) ?bβ)
?bβ := option (option Ξ±))
...
-/
instance coe_option {a : Type u} : has_coe_t a (option a) :=
β¨Ξ» x, some xβ©
/- Auxiliary transitive closure for has_coe which does not contain
instances such as coe_option.
They would produce non-termination when combined with coe_fn_trans and coe_sort_trans.
-/
class has_coe_t_aux (a : Sort u) (b : Sort v) :=
(coe : a β b)
instance coe_trans_aux {a : Sort uβ} {b : Sort uβ} {c : Sort uβ} [has_coe a b] [has_coe_t_aux b c] : has_coe_t_aux a c :=
β¨Ξ» x : a, @has_coe_t_aux.coe b c _ (coe_b x)β©
instance coe_base_aux {a : Sort u} {b : Sort v} [has_coe a b] : has_coe_t_aux a b :=
β¨coe_bβ©
instance coe_fn_trans {a : Sort uβ} {b : Sort uβ} [has_coe_t_aux a b] [has_coe_to_fun.{uβ uβ} b] : has_coe_to_fun.{uβ uβ} a :=
{ F := Ξ» x, @has_coe_to_fun.F.{uβ uβ} b _ (@has_coe_t_aux.coe a b _ x),
coe := Ξ» x, coe_fn (@has_coe_t_aux.coe a b _ x) }
instance coe_sort_trans {a : Sort uβ} {b : Sort uβ} [has_coe_t_aux a b] [has_coe_to_sort.{uβ uβ} b] : has_coe_to_sort.{uβ uβ} a :=
{ S := has_coe_to_sort.S.{uβ uβ} b,
coe := Ξ» x, coe_sort (@has_coe_t_aux.coe a b _ x) }
/- Every coercion is also a lift -/
instance coe_to_lift {a : Sort u} {b : Sort v} [has_coe_t a b] : has_lift_t a b :=
β¨coe_tβ©
/- basic coercions -/
instance coe_bool_to_Prop : has_coe bool Prop :=
β¨Ξ» y, y = ttβ©
instance coe_decidable_eq (x : bool) : decidable (coe x) :=
show decidable (x = tt), from bool.decidable_eq x tt
instance coe_subtype {a : Type u} {p : a β Prop} : has_coe {x // p x} a :=
β¨subtype.valβ©
/- basic lifts -/
universes ua uaβ uaβ ub ubβ ubβ
/- Remark: we cant use [has_lift_t aβ aβ] since it will produce non-termination whenever a type class resolution
problem does not have a solution. -/
instance lift_fn {aβ : Sort uaβ} {aβ : Sort uaβ} {bβ : Sort ubβ} {bβ : Sort ubβ} [has_lift aβ aβ] [has_lift_t bβ bβ] : has_lift (aβ β bβ) (aβ β bβ) :=
β¨Ξ» f x, β(f βx)β©
instance lift_fn_range {a : Sort ua} {bβ : Sort ubβ} {bβ : Sort ubβ} [has_lift_t bβ bβ] : has_lift (a β bβ) (a β bβ) :=
β¨Ξ» f x, β(f x)β©
instance lift_fn_dom {aβ : Sort uaβ} {aβ : Sort uaβ} {b : Sort ub} [has_lift aβ aβ] : has_lift (aβ β b) (aβ β b) :=
β¨Ξ» f x, f βxβ©
instance lift_pair {aβ : Type uaβ} {aβ : Type ubβ} {bβ : Type ubβ} {bβ : Type ubβ} [has_lift_t aβ aβ] [has_lift_t bβ bβ] : has_lift (aβ Γ bβ) (aβ Γ bβ) :=
β¨Ξ» p, prod.cases_on p (Ξ» x y, (βx, βy))β©
instance lift_pairβ {aβ : Type uaβ} {aβ : Type uaβ} {b : Type ub} [has_lift_t aβ aβ] : has_lift (aβ Γ b) (aβ Γ b) :=
β¨Ξ» p, prod.cases_on p (Ξ» x y, (βx, y))β©
instance lift_pairβ {a : Type ua} {bβ : Type ubβ} {bβ : Type ubβ} [has_lift_t bβ bβ] : has_lift (a Γ bβ) (a Γ bβ) :=
β¨Ξ» p, prod.cases_on p (Ξ» x y, (x, βy))β©
instance lift_list {a : Type u} {b : Type v} [has_lift_t a b] : has_lift (list a) (list b) :=
β¨Ξ» l, list.map (@coe a b _) lβ©
|
2e815b08aaf31a60254048f1c706cc049f26c1c4 | cabd1ea95170493667c024ef2045eb86d981b133 | /src/super/prover_state.lean | 72796ee3d62e1197907b51b1cd1dc7d339749c19 | [] | no_license | semorrison/super | 31db4b5aa5ef4c2313dc5803b8c79a95f809815b | 0c6c03ba9c7470f801eb4d055294f424ff090308 | refs/heads/master | 1,630,272,140,541 | 1,511,054,739,000 | 1,511,054,756,000 | 114,317,807 | 0 | 0 | null | 1,513,304,776,000 | 1,513,304,775,000 | null | UTF-8 | Lean | false | false | 15,641 | lean | /-
Copyright (c) 2017 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import .clause .lpo .cdcl_solver
open tactic functor monad expr native
namespace super
structure score :=
(priority : β)
(in_sos : bool)
(cost : β)
(age : β)
namespace score
def prio.immediate : β := 0
def prio.default : β := 1
def prio.never : β := 2
def sched_default (sc : score) : score := { sc with priority := prio.default }
def sched_now (sc : score) : score := { sc with priority := prio.immediate }
def inc_cost (sc : score) (n : β) : score := { sc with cost := sc.cost + n }
def min (a b : score) : score :=
{ priority := nat.min a.priority b.priority,
in_sos := a.in_sos && b.in_sos,
cost := nat.min a.cost b.cost,
age := nat.min a.age b.age }
def combine (a b : score) : score :=
{ priority := nat.max a.priority b.priority,
in_sos := a.in_sos && b.in_sos,
cost := a.cost + b.cost,
age := nat.max a.age b.age }
end score
namespace score
meta instance : has_to_string score :=
β¨Ξ»e, "[" ++ to_string e.priority ++
"," ++ to_string e.cost ++
"," ++ to_string e.age ++
",sos=" ++ to_string e.in_sos ++ "]"β©
end score
def clause_id := β
namespace clause_id
def to_nat (id : clause_id) : β := id
instance : decidable_eq clause_id := nat.decidable_eq
instance : has_lt clause_id := nat.has_lt
instance : decidable_rel ((<) : clause_id β clause_id β Prop) := nat.decidable_lt
end clause_id
meta structure derived_clause :=
(id : clause_id)
(c : clause)
(selected : list β)
(assertions : list expr)
(sc : score)
namespace derived_clause
meta instance : has_to_tactic_format derived_clause :=
β¨Ξ»c, do
prf_fmt β pp c.c.proof,
c_fmt β pp c.c,
ass_fmt β pp (c.assertions.map (Ξ»a, a.local_type)),
return $
to_string c.sc ++ " " ++
prf_fmt ++ " " ++
c_fmt ++ " <- " ++ ass_fmt ++
" (selected: " ++ to_fmt c.selected ++
")"
β©
meta def clause_with_assertions (ac : derived_clause) : clause :=
ac.c.close_constn ac.assertions
meta def update_proof (dc : derived_clause) (p : expr) : derived_clause :=
{ dc with c := { (dc.c) with proof := p } }
end derived_clause
meta structure locked_clause :=
(dc : derived_clause)
(reasons : list (list expr))
namespace locked_clause
meta instance : has_to_tactic_format locked_clause :=
β¨Ξ»c, do
c_fmt β pp c.dc,
reasons_fmt β pp (c.reasons.map (Ξ»r, r.map (Ξ»a, a.local_type))),
return $ c_fmt ++ " (locked in case of: " ++ reasons_fmt ++ ")"
β©
end locked_clause
meta structure prover_state :=
(active : rb_map clause_id derived_clause)
(passive : rb_map clause_id derived_clause)
(newly_derived : list derived_clause)
(prec : list expr)
(locked : list locked_clause)
(local_false : expr)
(sat_solver : cdcl.state)
(current_model : rb_map expr bool)
(sat_hyps : rb_map expr (expr Γ expr))
(needs_sat_run : bool)
(clause_counter : nat)
open prover_state
private meta def join_with_nl : list format β format :=
list.foldl (Ξ»x y, x ++ format.line ++ y) format.nil
private meta def prover_state_tactic_fmt (s : prover_state) : tactic format := do
active_fmts β mapm pp $ rb_map.values s.active,
passive_fmts β mapm pp $ rb_map.values s.passive,
new_fmts β mapm pp s.newly_derived,
locked_fmts β mapm pp s.locked,
sat_fmts β mapm pp s.sat_solver.clauses,
sat_model_fmts β s.current_model.to_list.mmap (Ξ»x, if x.2 = tt then pp x.1 else pp `(not %%x.1)),
prec_fmts β mapm pp s.prec,
return (join_with_nl
([to_fmt "active:"] ++ ((append (to_fmt " ")) <$> active_fmts) ++
[to_fmt "passive:"] ++ ((append (to_fmt " ")) <$> passive_fmts) ++
[to_fmt "new:"] ++ ((append (to_fmt " ")) <$> new_fmts) ++
[to_fmt "locked:"] ++ ((append (to_fmt " ")) <$> locked_fmts) ++
[to_fmt "sat formulas:"] ++ ((append (to_fmt " ")) <$> sat_fmts) ++
[to_fmt "sat model:"] ++ ((append (to_fmt " ")) <$> sat_model_fmts) ++
[to_fmt "precedence order: " ++ to_fmt prec_fmts]))
meta instance : has_to_tactic_format prover_state :=
β¨prover_state_tactic_fmtβ©
meta def prover := state_t prover_state tactic
namespace prover
meta instance : monad prover := state_t.monad _ _
meta instance : has_monad_lift tactic prover :=
monad.monad_transformer_lift (state_t prover_state) tactic
meta instance (Ξ± : Type) : has_coe (tactic Ξ±) (prover Ξ±) :=
β¨monad.monad_liftβ©
meta def fail {Ξ± Ξ² : Type} [has_to_format Ξ²] (msg : Ξ²) : prover Ξ± :=
tactic.fail msg
meta def orelse (A : Type) (p1 p2 : prover A) : prover A :=
assume state, p1 state <|> p2 state
meta instance : alternative prover :=
{ prover.monad with
failure := λα, fail "failed",
orelse := orelse }
end prover
meta def selection_strategy := derived_clause β prover derived_clause
meta def get_active : prover (rb_map clause_id derived_clause) :=
do state β state_t.read, return state.active
meta def add_active (a : derived_clause) : prover unit :=
do state β state_t.read,
state_t.write { state with active := state.active.insert a.id a }
meta def get_passive : prover (rb_map clause_id derived_clause) :=
lift passive state_t.read
meta def get_precedence : prover (list expr) :=
do state β state_t.read, return state.prec
meta def get_term_order : prover (expr β expr β bool) := do
state β state_t.read,
return $ mk_lpo (name_of_funsym <$> state.prec)
private meta def set_precedence (new_prec : list expr) : prover unit :=
do state β state_t.read, state_t.write { state with prec := new_prec }
meta def register_consts_in_precedence (consts : list expr) := do
p β get_precedence,
p_set β return (rb_map.set_of_list (name_of_funsym <$> p)),
new_syms β return $ list.filter (Ξ»c, Β¬p_set.contains (name_of_funsym c)) consts,
set_precedence (new_syms ++ p)
meta def in_sat_solver {A} (cmd : cdcl.solver A) : prover A := do
state β state_t.read,
result β cmd state.sat_solver,
state_t.write { state with sat_solver := result.2 },
return result.1
meta def collect_ass_hyps (c : clause) : prover (list expr) :=
let lcs := contained_lconsts c.proof in
do st β state_t.read,
return (do
hs β st.sat_hyps.values,
h β [hs.1, hs.2],
guard $ lcs.contains h.local_uniq_name,
[h])
meta def get_clause_count : prover β :=
do s β state_t.read, return s.clause_counter
meta def get_new_cls_id : prover clause_id := do
state β state_t.read,
state_t.write { state with clause_counter := state.clause_counter + 1 },
return state.clause_counter
meta def mk_derived (c : clause) (sc : score) : prover derived_clause := do
ass β collect_ass_hyps c,
id β get_new_cls_id,
return { id := id, c := c, selected := [], assertions := ass, sc := sc }
meta def add_inferred (c : derived_clause) : prover unit := do
c' β c.c.normalize, c' β return { c with c := c' },
register_consts_in_precedence (contained_funsyms c'.c.type).values,
state β state_t.read,
state_t.write { state with newly_derived := c' :: state.newly_derived }
-- FIXME: what if we've seen the variable before, but with a weaker score?
meta def mk_sat_var (v : expr) (suggested_ph : bool) (suggested_ev : score) : prover unit :=
do st β state_t.read, if st.sat_hyps.contains v then return () else do
hpv β mk_local_def `h v,
hnv β mk_local_def `hn $ imp v st.local_false,
state_t.modify $ Ξ»st, { st with sat_hyps := st.sat_hyps.insert v (hpv, hnv) },
in_sat_solver $ cdcl.mk_var_core v suggested_ph,
match v with
| (pi _ _ _ _) := do
c β clause.of_proof st.local_false hpv,
mk_derived c suggested_ev >>= add_inferred
| _ := do cp β clause.of_proof st.local_false hpv, mk_derived cp suggested_ev >>= add_inferred,
cn β clause.of_proof st.local_false hnv, mk_derived cn suggested_ev >>= add_inferred
end
meta def get_sat_hyp_core (v : expr) (ph : bool) : prover (option expr) :=
flip monad.lift state_t.read $ Ξ»st,
match st.sat_hyps.find v with
| some (hp, hn) := some $ if ph then hp else hn
| none := none
end
meta def get_sat_hyp (v : expr) (ph : bool) : prover expr :=
do hyp_opt β get_sat_hyp_core v ph,
match hyp_opt with
| some hyp := return hyp
| none := fail $ "unknown sat variable: " ++ v.to_string
end
meta def add_sat_clause (c : clause) (suggested_ev : score) : prover unit := do
c β c.distinct,
already_added β flip monad.lift state_t.read $ Ξ»st, decidable.to_bool $
c.type β st.sat_solver.clauses.map (Ξ»d, d.type),
if already_added then return () else do
c.get_lits.mmap' $ Ξ»l, mk_sat_var l.formula l.is_neg suggested_ev,
in_sat_solver $ cdcl.mk_clause c,
state_t.modify $ Ξ»st, { st with needs_sat_run := tt }
meta def sat_eval_lit (v : expr) (pol : bool) : prover bool :=
do v_st β flip monad.lift state_t.read $ Ξ»st, st.current_model.find v,
match v_st with
| some ph := return $ if pol then ph else bnot ph
| none := return tt
end
meta def sat_eval_assertion (assertion : expr) : prover bool :=
do lf β flip monad.lift state_t.read $ Ξ»st, st.local_false,
match is_local_not lf assertion.local_type with
| some v := sat_eval_lit v ff
| none := sat_eval_lit assertion.local_type tt
end
meta def sat_eval_assertions : list expr β prover bool
| (a::ass) := do v_a β sat_eval_assertion a,
if v_a then
sat_eval_assertions ass
else
return ff
| [] := return tt
private meta def intern_clause (c : derived_clause) : prover derived_clause := do
hyp_name β get_unused_name (mk_simple_name $ "clause_" ++ to_string c.id.to_nat) none,
c' β return $ c.c.close_constn c.assertions,
assertv hyp_name c'.type c'.proof,
proof' β get_local hyp_name,
type β infer_type proof', -- FIXME: otherwise ""
return $ c.update_proof $ app_of_list proof' c.assertions
meta def register_as_passive (c : derived_clause) : prover unit := do
c β intern_clause c,
ass_v β sat_eval_assertions c.assertions,
if c.c.num_quants = 0 β§ c.c.num_lits = 0 then
add_sat_clause c.clause_with_assertions c.sc
else if Β¬ass_v then do
state_t.modify $ Ξ»st, { st with locked := β¨c, []β© :: st.locked }
else do
state_t.modify $ Ξ»st, { st with passive := st.passive.insert c.id c }
meta def remove_passive (id : clause_id) : prover unit :=
do state β state_t.read, state_t.write { state with passive := state.passive.erase id }
meta def move_locked_to_passive : prover unit := do
locked β flip monad.lift state_t.read (Ξ»st, st.locked),
new_locked β flip filter locked (Ξ»lc, do
reason_vals β mapm sat_eval_assertions lc.reasons,
c_val β sat_eval_assertions lc.dc.assertions,
if reason_vals.for_all (Ξ»r, r = ff) β§ c_val then do
state_t.modify $ Ξ»st, { st with passive := st.passive.insert lc.dc.id lc.dc },
return ff
else
return tt
),
state_t.modify $ Ξ»st, { st with locked := new_locked }
meta def move_active_to_locked : prover unit :=
do active β get_active, active.values.mmap' $ Ξ»ac, do
c_val β sat_eval_assertions ac.assertions,
if Β¬c_val then do
state_t.modify $ Ξ»st, { st with
active := st.active.erase ac.id,
locked := β¨ac, []β© :: st.locked
}
else
return ()
meta def move_passive_to_locked : prover unit :=
do passive β flip monad.lift state_t.read $ Ξ»st, st.passive, passive.to_list.mmap' $ Ξ»pc, do
c_val β sat_eval_assertions pc.2.assertions,
if Β¬c_val then do
state_t.modify $ Ξ»st, { st with
passive := st.passive.erase pc.1,
locked := β¨pc.2, []β© :: st.locked
}
else
return ()
def super_cc_config : cc_config :=
{ em := ff }
meta def do_sat_run : prover (option expr) :=
do sat_result β in_sat_solver $ cdcl.run (cdcl.theory_solver_of_tactic $ using_smt $ return ()),
state_t.modify $ Ξ»st, { st with needs_sat_run := ff },
old_model β lift prover_state.current_model state_t.read,
match sat_result with
| (cdcl.result.unsat proof) := return (some proof)
| (cdcl.result.sat new_model) := do
state_t.modify $ Ξ»st, { st with current_model := new_model },
move_locked_to_passive,
move_active_to_locked,
move_passive_to_locked,
return none
end
meta def take_newly_derived : prover (list derived_clause) := do
state β state_t.read,
state_t.write { state with newly_derived := [] },
return state.newly_derived
meta def remove_redundant (id : clause_id) (parents : list derived_clause) : prover unit := do
when (not $ parents.for_all $ Ξ»p, p.id β id) (fail "clause is redundant because of itself"),
red β flip monad.lift state_t.read (Ξ»st, st.active.find id),
match red with
| none := return ()
| some red := do
let reasons := parents.map (Ξ»p, p.assertions),
let assertion := red.assertions,
if reasons.for_all $ Ξ»r, r.subset_of assertion then do
state_t.modify $ Ξ»st, { st with active := st.active.erase id }
else do
state_t.modify $ Ξ»st, { st with active := st.active.erase id,
locked := β¨red, reasonsβ© :: st.locked }
end
meta def inference := derived_clause β prover unit
meta structure inf_decl := (prio : β) (inf : inference)
@[user_attribute]
meta def inf_attr : user_attribute :=
{name := `super.inf, descr := "inference for the super prover"}
meta def seq_inferences : list inference β inference
| [] := Ξ»given, return ()
| (inf::infs) := Ξ»given, do
inf given,
now_active β get_active,
if rb_map.contains now_active given.id then
seq_inferences infs given
else
return ()
meta def simp_inference (simpl : derived_clause β prover (option clause)) : inference :=
Ξ»given, do maybe_simpld β simpl given,
match maybe_simpld with
| some simpld := do
derived_simpld β mk_derived simpld given.sc.sched_now,
add_inferred derived_simpld,
remove_redundant given.id []
| none := return ()
end
meta def preprocessing_rule (f : list derived_clause β prover (list derived_clause)) : prover unit := do
state β state_t.read,
newly_derived' β f state.newly_derived,
state' β state_t.read,
state_t.write { state' with newly_derived := newly_derived' }
meta def clause_selection_strategy := β β prover clause_id
namespace prover_state
meta def empty (local_false : expr) : prover_state :=
{ active := rb_map.mk _ _, passive := rb_map.mk _ _,
newly_derived := [], prec := [], clause_counter := 0,
local_false := local_false,
locked := [], sat_solver := cdcl.state.initial local_false,
current_model := rb_map.mk _ _, sat_hyps := rb_map.mk _ _, needs_sat_run := ff }
meta def initial (local_false : expr) (clauses : list clause) : tactic prover_state := do
after_setup β clauses.mmap' (Ξ»c : clause,
let in_sos := ((contained_lconsts c.proof).erase local_false.local_uniq_name).size = 0 in
do mk_derived c { priority := score.prio.immediate, in_sos := in_sos,
age := 0, cost := 0 } >>= add_inferred
) $ empty local_false,
return after_setup.2
end prover_state
meta def inf_score (add_cost : β) (scores : list score) : prover score := do
age β get_clause_count,
return $ list.foldl score.combine { priority := score.prio.default,
in_sos := tt,
age := age,
cost := add_cost
} scores
meta def inf_if_successful (add_cost : β) (parent : derived_clause) (tac : tactic (list clause)) : prover unit :=
(do inferred β tac,
inferred.mmap' $ Ξ»c,
inf_score add_cost [parent.sc] >>= mk_derived c >>= add_inferred)
<|> return ()
meta def simp_if_successful (parent : derived_clause) (tac : tactic (list clause)) : prover unit :=
(do inferred β tac,
inferred.mmap' $ Ξ»c,
mk_derived c parent.sc.sched_now >>= add_inferred,
remove_redundant parent.id [])
<|> return ()
end super
|
7dfb9848362c48d3f0a1cf4c203270083e0cc2a3 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/control/traversable/basic.lean | 0d2ac30d2ac111d853381f22ebf289d1f9bd757e | [
"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 | 9,533 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import control.functor
/-!
# Traversable type class
Type classes for traversing collections. The concepts and laws are taken from
<http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-Traversable.html>
Traversable collections are a generalization of functors. Whereas
functors (such as `list`) allow us to apply a function to every
element, it does not allow functions which external effects encoded in
a monad. Consider for instance a functor `invite : email β io response`
that takes an email address, sends an email and waits for a
response. If we have a list `guests : list email`, using calling
`invite` using `map` gives us the following: `map invite guests : list
(io response)`. It is not what we need. We need something of type `io
(list response)`. Instead of using `map`, we can use `traverse` to
send all the invites: `traverse invite guests : io (list response)`.
`traverse` applies `invite` to every element of `guests` and combines
all the resulting effects. In the example, the effect is encoded in the
monad `io` but any applicative functor is accepted by `traverse`.
For more on how to use traversable, consider the Haskell tutorial:
<https://en.wikibooks.org/wiki/Haskell/Traversable>
## Main definitions
* `traversable` type class - exposes the `traverse` function
* `sequence` - based on `traverse`,
turns a collection of effects into an effect returning a collection
* `is_lawful_traversable` - laws for a traversable functor
* `applicative_transformation` - the notion of a natural transformation for applicative functors
## Tags
traversable iterator functor applicative
## References
* "Applicative Programming with Effects", by Conor McBride and Ross Paterson,
Journal of Functional Programming 18:1 (2008) 1-13, online at
<http://www.soi.city.ac.uk/~ross/papers/Applicative.html>
* "The Essence of the Iterator Pattern", by Jeremy Gibbons and Bruno Oliveira,
in Mathematically-Structured Functional Programming, 2006, online at
<http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator>
* "An Investigation of the Laws of Traversals", by Mauro Jaskelioff and Ondrej Rypacek,
in Mathematically-Structured Functional Programming, 2012,
online at <http://arxiv.org/pdf/1202.2919>
-/
open function (hiding comp)
universes u v w
section applicative_transformation
variables (F : Type u β Type v) [applicative F] [is_lawful_applicative F]
variables (G : Type u β Type w) [applicative G] [is_lawful_applicative G]
/-- A transformation between applicative functors. It a natural
transformation such that `app` preserves the `has_pure.pure` and
`functor.map` (`<*>`) operations. See
`applicative_transformation.preserves_map` for naturality. -/
structure applicative_transformation : Type (max (u+1) v w) :=
(app : Ξ Ξ± : Type u, F Ξ± β G Ξ±)
(preserves_pure' : β {Ξ± : Type u} (x : Ξ±), app _ (pure x) = pure x)
(preserves_seq' : β {Ξ± Ξ² : Type u} (x : F (Ξ± β Ξ²)) (y : F Ξ±), app _ (x <*> y) = app _ x <*> app _ y)
end applicative_transformation
namespace applicative_transformation
variables (F : Type u β Type v) [applicative F] [is_lawful_applicative F]
variables (G : Type u β Type w) [applicative G] [is_lawful_applicative G]
instance : has_coe_to_fun (applicative_transformation F G) :=
{ F := Ξ» _, Ξ {Ξ±}, F Ξ± β G Ξ±,
coe := Ξ» a, a.app }
variables {F G}
@[simp]
lemma app_eq_coe (Ξ· : applicative_transformation F G) : Ξ·.app = Ξ· := rfl
@[simp]
lemma coe_mk (f : Ξ (Ξ± : Type u), F Ξ± β G Ξ±) (pp ps) :
β(applicative_transformation.mk f pp ps) = f := rfl
protected
lemma congr_fun (Ξ· Ξ·' : applicative_transformation F G) (h : Ξ· = Ξ·') {Ξ± : Type u} (x : F Ξ±) :
Ξ· x = Ξ·' x :=
congr_arg (Ξ» Ξ·'' : applicative_transformation F G, Ξ·'' x) h
protected
lemma congr_arg (Ξ· : applicative_transformation F G) {Ξ± : Type u} {x y : F Ξ±} (h : x = y) :
Ξ· x = Ξ· y :=
congr_arg (Ξ» z : F Ξ±, Ξ· z) h
lemma coe_inj β¦Ξ· Ξ·' : applicative_transformation F Gβ¦ (h : (Ξ· : Ξ Ξ±, F Ξ± β G Ξ±) = Ξ·') : Ξ· = Ξ·' :=
by { cases Ξ·, cases Ξ·', congr, exact h }
@[ext]
lemma ext β¦Ξ· Ξ·' : applicative_transformation F Gβ¦ (h : β (Ξ± : Type u) (x : F Ξ±), Ξ· x = Ξ·' x) :
Ξ· = Ξ·' :=
by { apply coe_inj, ext1 Ξ±, exact funext (h Ξ±) }
lemma ext_iff {Ξ· Ξ·' : applicative_transformation F G} :
Ξ· = Ξ·' β β (Ξ± : Type u) (x : F Ξ±), Ξ· x = Ξ·' x :=
β¨Ξ» h Ξ± x, h βΈ rfl, Ξ» h, ext hβ©
section preserves
variables (Ξ· : applicative_transformation F G)
@[functor_norm]
lemma preserves_pure : β {Ξ±} (x : Ξ±), Ξ· (pure x) = pure x := Ξ·.preserves_pure'
@[functor_norm]
lemma preserves_seq :
β {Ξ± Ξ² : Type u} (x : F (Ξ± β Ξ²)) (y : F Ξ±), Ξ· (x <*> y) = Ξ· x <*> Ξ· y :=
Ξ·.preserves_seq'
@[functor_norm]
lemma preserves_map {Ξ± Ξ²} (x : Ξ± β Ξ²) (y : F Ξ±) : Ξ· (x <$> y) = x <$> Ξ· y :=
by rw [β pure_seq_eq_map, Ξ·.preserves_seq]; simp with functor_norm
lemma preserves_map' {Ξ± Ξ²} (x : Ξ± β Ξ²) : @Ξ· _ β functor.map x = functor.map x β @Ξ· _ :=
by { ext y, exact preserves_map Ξ· x y }
end preserves
/-- The identity applicative transformation from an applicative functor to itself. -/
def id_transformation : applicative_transformation F F :=
{ app := Ξ» Ξ±, id,
preserves_pure' := by simp,
preserves_seq' := Ξ» Ξ± Ξ² x y, by simp }
instance : inhabited (applicative_transformation F F) := β¨id_transformationβ©
universes s t
variables {H : Type u β Type s} [applicative H] [is_lawful_applicative H]
/-- The composition of applicative transformations. -/
def comp (Ξ·' : applicative_transformation G H) (Ξ· : applicative_transformation F G) :
applicative_transformation F H :=
{ app := Ξ» Ξ± x, Ξ·' (Ξ· x),
preserves_pure' := Ξ» Ξ± x, by simp with functor_norm,
preserves_seq' := Ξ» Ξ± Ξ² x y, by simp with functor_norm }
@[simp]
lemma comp_apply (Ξ·' : applicative_transformation G H) (Ξ· : applicative_transformation F G)
{Ξ± : Type u} (x : F Ξ±) :
Ξ·'.comp Ξ· x = Ξ·' (Ξ· x) := rfl
lemma comp_assoc {I : Type u β Type t} [applicative I] [is_lawful_applicative I]
(Ξ·'' : applicative_transformation H I)
(Ξ·' : applicative_transformation G H)
(Ξ· : applicative_transformation F G) :
(Ξ·''.comp Ξ·').comp Ξ· = Ξ·''.comp (Ξ·'.comp Ξ·) := rfl
@[simp]
lemma comp_id (Ξ· : applicative_transformation F G) : Ξ·.comp id_transformation = Ξ· :=
ext $ Ξ» Ξ± x, rfl
@[simp]
lemma id_comp (Ξ· : applicative_transformation F G) : id_transformation.comp Ξ· = Ξ· :=
ext $ Ξ» Ξ± x, rfl
end applicative_transformation
open applicative_transformation
/-- A traversable functor is a functor along with a way to commute
with all applicative functors (see `sequence`). For example, if `t`
is the traversable functor `list` and `m` is the applicative functor
`io`, then given a function `f : Ξ± β io Ξ²`, the function `functor.map f` is
`list Ξ± β list (io Ξ²)`, but `traverse f` is `list Ξ± β io (list Ξ²)`. -/
class traversable (t : Type u β Type u) extends functor t :=
(traverse : Ξ {m : Type u β Type u} [applicative m] {Ξ± Ξ²},
(Ξ± β m Ξ²) β t Ξ± β m (t Ξ²))
open functor
export traversable (traverse)
section functions
variables {t : Type u β Type u}
variables {m : Type u β Type v} [applicative m]
variables {Ξ± Ξ² : Type u}
variables {f : Type u β Type u} [applicative f]
/-- A traversable functor commutes with all applicative functors. -/
def sequence [traversable t] : t (f Ξ±) β f (t Ξ±) := traverse id
end functions
/-- A traversable functor is lawful if its `traverse` satisfies a
number of additional properties. It must send `id.mk` to `id.mk`,
send the composition of applicative functors to the composition of the
`traverse` of each, send each function `f` to `Ξ» x, f <$> x`, and
satisfy a naturality condition with respect to applicative
transformations. -/
class is_lawful_traversable (t : Type u β Type u) [traversable t]
extends is_lawful_functor t : Type (u+1) :=
(id_traverse : β {Ξ±} (x : t Ξ±), traverse id.mk x = x )
(comp_traverse : β {F G} [applicative F] [applicative G]
[is_lawful_applicative F] [is_lawful_applicative G]
{Ξ± Ξ² Ξ³} (f : Ξ² β F Ξ³) (g : Ξ± β G Ξ²) (x : t Ξ±),
traverse (comp.mk β map f β g) x =
comp.mk (map (traverse f) (traverse g x)))
(traverse_eq_map_id : β {Ξ± Ξ²} (f : Ξ± β Ξ²) (x : t Ξ±),
traverse (id.mk β f) x = id.mk (f <$> x))
(naturality : β {F G} [applicative F] [applicative G]
[is_lawful_applicative F] [is_lawful_applicative G]
(Ξ· : applicative_transformation F G) {Ξ± Ξ²} (f : Ξ± β F Ξ²) (x : t Ξ±),
Ξ· (traverse f x) = traverse (@Ξ· _ β f) x)
instance : traversable id := β¨Ξ» _ _ _ _, idβ©
instance : is_lawful_traversable id := by refine {..}; intros; refl
section
variables {F : Type u β Type v} [applicative F]
instance : traversable option := β¨@option.traverseβ©
instance : traversable list := β¨@list.traverseβ©
end
namespace sum
variables {Ο : Type u}
variables {F : Type u β Type u}
variables [applicative F]
/-- Defines a `traverse` function on the second component of a sum type.
This is used to give a `traversable` instance for the functor `Ο β -`. -/
protected def traverse {Ξ± Ξ²} (f : Ξ± β F Ξ²) : Ο β Ξ± β F (Ο β Ξ²)
| (sum.inl x) := pure (sum.inl x)
| (sum.inr x) := sum.inr <$> f x
end sum
instance {Ο : Type u} : traversable.{u} (sum Ο) := β¨@sum.traverse _β©
|
d8bf16c30a61c13f787cff766c387a464cec455f | 38ee9024fb5974f555fb578fcf5a5a7b71e669b5 | /Mathlib/Data/Prod.lean | 36b1a39181abd24a50ca9a01d7a1d0538e143faa | [
"Apache-2.0"
] | permissive | denayd/mathlib4 | 750e0dcd106554640a1ac701e51517501a574715 | 7f40a5c514066801ab3c6d431e9f405baa9b9c58 | refs/heads/master | 1,693,743,991,894 | 1,636,618,048,000 | 1,636,618,048,000 | 373,926,241 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,764 | 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 Mathlib.Init.Function
import Mathlib.Logic.Basic
import Mathlib.Logic.Function.Basic
import Mathlib.Tactic.Basic
import Mathlib.Tactic.Ext
/-!
# Extra facts about `Prod`
This file defines `Prod.swap : Ξ± Γ Ξ² β Ξ² Γ Ξ±` and proves various simple lemmas about `Prod`.
-/
variable {Ξ± : Type _} {Ξ² : Type _} {Ξ³ : Type _} {Ξ΄ : Type _}
@[simp] lemma prod_map (f : Ξ± β Ξ³) (g : Ξ² β Ξ΄) (p : Ξ± Γ Ξ²) : Prod.map f g p = (f p.1, g p.2) :=
by have : p = β¨p.1, p.2β© := (Prod.ext _).symm
rw [this]
exact rfl
namespace Prod
@[simp] theorem Β«forallΒ» {p : Ξ± Γ Ξ² β Prop} : (β x, p x) β (β a b, p (a, b)) :=
β¨Ξ» h a b => h (a, b), Ξ» h β¨a, bβ© => h a bβ©
@[simp] theorem Β«existsΒ» {p : Ξ± Γ Ξ² β Prop} : (β x, p x) β (β a b, p (a, b)) :=
β¨Ξ» β¨β¨a, bβ©, hβ© => β¨a, b, hβ©, Ξ» β¨a, b, hβ© => β¨β¨a, bβ©, hβ©β©
theorem forall' {p : Ξ± β Ξ² β Prop} : (β x : Ξ± Γ Ξ², p x.1 x.2) β β a b, p a b :=
Prod.forall
theorem exists' {p : Ξ± β Ξ² β Prop} : (β x : Ξ± Γ Ξ², p x.1 x.2) β β a b, p a b :=
Prod.exists
@[simp] lemma map_mk (f : Ξ± β Ξ³) (g : Ξ² β Ξ΄) (a : Ξ±) (b : Ξ²) : map f g (a, b) = (f a, g b) := rfl
@[simp]
lemma map_fst (f : Ξ± β Ξ³) (g : Ξ² β Ξ΄) (p : Ξ± Γ Ξ²) : (map f g p).1 = f (p.1) := by simp
@[simp]
lemma map_snd (f : Ξ± β Ξ³) (g : Ξ² β Ξ΄) (p : Ξ± Γ Ξ²) : (map f g p).2 = g (p.2) := by simp
lemma map_fst' (f : Ξ± β Ξ³) (g : Ξ² β Ξ΄) : (Prod.fst β map f g) = f β Prod.fst :=
funext $ map_fst f g
lemma map_snd' (f : Ξ± β Ξ³) (g : Ξ² β Ξ΄) : (Prod.snd β map f g) = g β Prod.snd :=
funext $ map_snd f g
/--
Composing a `prod.map` with another `prod.map` is equal to
a single `prod.map` of composed functions.
-/
lemma map_comp_map {Ξ΅ ΞΆ : Type _}
(f : Ξ± β Ξ²) (f' : Ξ³ β Ξ΄) (g : Ξ² β Ξ΅) (g' : Ξ΄ β ΞΆ) :
Prod.map g g' β Prod.map f f' = Prod.map (g β f) (g' β f') :=
by ext x; simp
/--
Composing a `prod.map` with another `prod.map` is equal to
a single `prod.map` of composed functions, fully applied.
-/
lemma map_map {Ξ΅ ΞΆ : Type _}
(f : Ξ± β Ξ²) (f' : Ξ³ β Ξ΄) (g : Ξ² β Ξ΅) (g' : Ξ΄ β ΞΆ) (x : Ξ± Γ Ξ³) :
Prod.map g g' (Prod.map f f' x) = Prod.map (g β f) (g' β f') x := by simp
@[simp] theorem mk.inj_iff {aβ aβ : Ξ±} {bβ bβ : Ξ²} : (aβ, bβ) = (aβ, bβ) β (aβ = aβ β§ bβ = bβ) :=
β¨Prod.mk.inj,
by intro hab; rw [hab.left, hab.right]β©
lemma mk.inj_left {Ξ± Ξ² : Type _} (a : Ξ±) :
Function.injective (Prod.mk a : Ξ² β Ξ± Γ Ξ²) :=
fun h => (Prod.mk.inj h).right
lemma mk.inj_right {Ξ± Ξ² : Type _} (b : Ξ²) :
Function.injective (Ξ» a => Prod.mk a b : Ξ± β Ξ± Γ Ξ²) :=
fun h => (Prod.mk.inj h).left
-- Port note: this lemma comes from lean3/library/init/data/prod.lean.
@[simp] lemma mk.eta : β{p : Ξ± Γ Ξ²}, (p.1, p.2) = p
| (a,b) => rfl
lemma ext_iff {p q : Ξ± Γ Ξ²} : p = q β p.1 = q.1 β§ p.2 = q.2 :=
by rw [β @mk.eta _ _ p, β @mk.eta _ _ q, mk.inj_iff]
-- Port note: in mathlib this is named `ext`, but Lean4 has already defined that to be something
-- with a slightly different signature.
@[ext]
lemma ext' {Ξ± Ξ²} {p q : Ξ± Γ Ξ²} (hβ : p.1 = q.1) (hβ : p.2 = q.2) : p = q :=
ext_iff.2 β¨hβ, hββ©
lemma map_def {f : Ξ± β Ξ³} {g : Ξ² β Ξ΄} : Prod.map f g = Ξ» p => (f p.1, g p.2) :=
by ext <;> simp
lemma id_prod : (Ξ» (p : Ξ± Γ Ξ±) => (p.1, p.2)) = id :=
funext $ Ξ» β¨a, bβ© => rfl
lemma fst_surjective [h : Nonempty Ξ²] : Function.surjective (@fst Ξ± Ξ²) :=
Ξ» x => h.elim $ Ξ» y => β¨β¨x, yβ©, rflβ©
lemma snd_surjective [h : Nonempty Ξ±] : Function.surjective (@snd Ξ± Ξ²) :=
Ξ» y => h.elim $ Ξ» x => β¨β¨x, yβ©, rflβ©
lemma fst_injective [Subsingleton Ξ²] : Function.injective (@fst Ξ± Ξ²) :=
Ξ» {x y} h => ext' h (Subsingleton.elim x.snd y.snd)
lemma snd_injective [Subsingleton Ξ±] : Function.injective (@snd Ξ± Ξ²) :=
Ξ» {x y} h => ext' (Subsingleton.elim _ _) h
/-- Swap the factors of a product. `swap (a, b) = (b, a)` -/
def swap : Ξ± Γ Ξ² β Ξ² Γ Ξ± := Ξ»p => (p.2, p.1)
@[simp] lemma swap_swap : β x : Ξ± Γ Ξ², swap (swap x) = x
| β¨a, bβ© => rfl
@[simp] lemma fst_swap {p : Ξ± Γ Ξ²} : (swap p).1 = p.2 := rfl
@[simp] lemma snd_swap {p : Ξ± Γ Ξ²} : (swap p).2 = p.1 := rfl
@[simp] lemma swap_prod_mk {a : Ξ±} {b : Ξ²} : swap (a, b) = (b, a) := rfl
@[simp] lemma swap_swap_eq : swap β swap = @id (Ξ± Γ Ξ²) :=
funext swap_swap
@[simp] lemma swap_left_inverse : Function.left_inverse (@swap Ξ± Ξ²) swap :=
swap_swap
@[simp] lemma swap_right_inverse : Function.right_inverse (@swap Ξ± Ξ²) swap :=
swap_swap
lemma swap_injective : Function.injective (@swap Ξ± Ξ²) :=
swap_left_inverse.injective
lemma swap_surjective : Function.surjective (@swap Ξ± Ξ²) :=
Function.right_inverse.surjective swap_left_inverse
lemma swap_bijective : Function.bijective (@swap Ξ± Ξ²) :=
β¨swap_injective, swap_surjectiveβ©
@[simp] lemma swap_inj {p q : Ξ± Γ Ξ²} : swap p = swap q β p = q :=
swap_injective.eq_iff
lemma eq_iff_fst_eq_snd_eq : β{p q : Ξ± Γ Ξ²}, p = q β (p.1 = q.1 β§ p.2 = q.2)
| β¨pβ, pββ©, β¨qβ, qββ© => by simp
lemma fst_eq_iff : β {p : Ξ± Γ Ξ²} {x : Ξ±}, p.1 = x β p = (x, p.2)
| β¨a, bβ©, x => by simp
lemma snd_eq_iff : β {p : Ξ± Γ Ξ²} {x : Ξ²}, p.2 = x β p = (p.1, x)
| β¨a, bβ©, x => by simp
theorem lex_def (r : Ξ± β Ξ± β Prop) (s : Ξ² β Ξ² β Prop)
{p q : Ξ± Γ Ξ²} : Prod.Lex r s p q β r p.1 q.1 β¨ p.1 = q.1 β§ s p.2 q.2 :=
β¨(Ξ» h => match h with
| Lex.left b1 b2 h1 => by simp [h1]
| Lex.right a h1 => by simp [h1] ),
Ξ» h => match p, q, h with
| (a, b), (c, d), Or.inl h => Lex.left _ _ h
| (a, b), (c, d), Or.inr β¨e, hβ© =>
by subst e; exact Lex.right _ h β©
instance Lex.decidable [DecidableEq Ξ±]
(r : Ξ± β Ξ± β Prop) (s : Ξ² β Ξ² β Prop) [DecidableRel r] [DecidableRel s] :
DecidableRel (Prod.Lex r s) :=
Ξ» p q => decidable_of_decidable_of_iff (by infer_instance) (lex_def r s).symm
end Prod
open Function
lemma Function.injective.prod_map {f : Ξ± β Ξ³} {g : Ξ² β Ξ΄} (hf : injective f) (hg : injective g) :
injective (Prod.map f g) :=
by intros x y h
have h1 := (Prod.ext_iff.1 h).1
rw [Prod.map_fst, Prod.map_fst] at h1
have h2 := (Prod.ext_iff.1 h).2
rw [Prod.map_snd, Prod.map_snd] at h2
exact Prod.ext' (hf h1) (hg h2)
lemma Function.surjective.prod_map {f : Ξ± β Ξ³} {g : Ξ² β Ξ΄} (hf : surjective f) (hg : surjective g) :
surjective (Prod.map f g) :=
Ξ» p => let β¨x, hxβ© := hf p.1
let β¨y, hyβ© := hg p.2
β¨(x, y), Prod.ext' hx hyβ©
|
474100eb97649df356f46c568aeaa297b47cae87 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/ring_theory/is_tensor_product.lean | dceb63548b86c501da2f9331173e849d9296cae7 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 18,211 | lean | /-
Copyright (c) 2022 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import ring_theory.tensor_product
import algebra.module.ulift
/-!
# The characteristice predicate of tensor product
## Main definitions
- `is_tensor_product`: A predicate on `f : Mβ ββ[R] Mβ ββ[R] M` expressing that `f` realizes `M` as
the tensor product of `Mβ β[R] Mβ`. This is defined by requiring the lift `Mβ β[R] Mβ β M` to be
bijective.
- `is_base_change`: A predicate on an `R`-algebra `S` and a map `f : M ββ[R] N` with `N` being a
`S`-module, expressing that `f` realizes `N` as the base change of `M` along `R β S`.
- `algebra.is_pushout`: A predicate on the following diagram of scalar towers
```
R β S
β β
R' β S'
```
asserting that is a pushout diagram (i.e. `S' = S β[R] R'`)
## Main results
- `tensor_product.is_base_change`: `S β[R] M` is the base change of `M` along `R β S`.
-/
universes u vβ vβ vβ vβ
open_locale tensor_product
open tensor_product
section is_tensor_product
variables {R : Type*} [comm_ring R]
variables {Mβ Mβ M M' : Type*}
variables [add_comm_monoid Mβ] [add_comm_monoid Mβ] [add_comm_monoid M] [add_comm_monoid M']
variables [module R Mβ] [module R Mβ] [module R M] [module R M']
variable (f : Mβ ββ[R] Mβ ββ[R] M)
variables {Nβ Nβ N : Type*} [add_comm_monoid Nβ] [add_comm_monoid Nβ] [add_comm_monoid N]
variables [module R Nβ] [module R Nβ] [module R N]
variable {g : Nβ ββ[R] Nβ ββ[R] N}
/--
Given a bilinear map `f : Mβ ββ[R] Mβ ββ[R] M`, `is_tensor_product f` means that
`M` is the tensor product of `Mβ` and `Mβ` via `f`.
This is defined by requiring the lift `Mβ β[R] Mβ β M` to be bijective.
-/
def is_tensor_product : Prop := function.bijective (tensor_product.lift f)
variables (R M N) {f}
lemma tensor_product.is_tensor_product : is_tensor_product (tensor_product.mk R M N) :=
begin
delta is_tensor_product,
convert_to function.bijective linear_map.id using 2,
{ apply tensor_product.ext', simp },
{ exact function.bijective_id }
end
variables {R M N}
/-- If `M` is the tensor product of `Mβ` and `Mβ`, it is linearly equivalent to `Mβ β[R] Mβ`. -/
@[simps apply] noncomputable
def is_tensor_product.equiv (h : is_tensor_product f) : Mβ β[R] Mβ ββ[R] M :=
linear_equiv.of_bijective _ h
@[simp] lemma is_tensor_product.equiv_to_linear_map (h : is_tensor_product f) :
h.equiv.to_linear_map = tensor_product.lift f := rfl
@[simp] lemma is_tensor_product.equiv_symm_apply (h : is_tensor_product f) (xβ : Mβ) (xβ : Mβ) :
h.equiv.symm (f xβ xβ) = xβ ββ xβ :=
begin
apply h.equiv.injective,
refine (h.equiv.apply_symm_apply _).trans _,
simp
end
/-- If `M` is the tensor product of `Mβ` and `Mβ`, we may lift a bilinear map `Mβ ββ[R] Mβ ββ[R] M'`
to a `M ββ[R] M'`. -/
noncomputable
def is_tensor_product.lift (h : is_tensor_product f) (f' : Mβ ββ[R] Mβ ββ[R] M') : M ββ[R] M' :=
(tensor_product.lift f').comp h.equiv.symm.to_linear_map
lemma is_tensor_product.lift_eq (h : is_tensor_product f) (f' : Mβ ββ[R] Mβ ββ[R] M')
(xβ : Mβ) (xβ : Mβ) : h.lift f' (f xβ xβ) = f' xβ xβ :=
begin
delta is_tensor_product.lift,
simp,
end
/-- The tensor product of a pair of linear maps between modules. -/
noncomputable
def is_tensor_product.map (hf : is_tensor_product f) (hg : is_tensor_product g)
(iβ : Mβ ββ[R] Nβ) (iβ : Mβ ββ[R] Nβ) : M ββ[R] N :=
hg.equiv.to_linear_map.comp ((tensor_product.map iβ iβ).comp hf.equiv.symm.to_linear_map)
lemma is_tensor_product.map_eq (hf : is_tensor_product f) (hg : is_tensor_product g)
(iβ : Mβ ββ[R] Nβ) (iβ : Mβ ββ[R] Nβ) (xβ : Mβ) (xβ : Mβ) :
hf.map hg iβ iβ (f xβ xβ) = g (iβ xβ) (iβ xβ) :=
begin
delta is_tensor_product.map,
simp
end
lemma is_tensor_product.induction_on (h : is_tensor_product f) {C : M β Prop}
(m : M) (h0 : C 0) (htmul : β x y, C (f x y)) (hadd : β x y, C x β C y β C (x + y)) : C m :=
begin
rw β h.equiv.right_inv m,
generalize : h.equiv.inv_fun m = y,
change C (tensor_product.lift f y),
induction y using tensor_product.induction_on,
{ rwa map_zero },
{ rw tensor_product.lift.tmul, apply htmul },
{ rw map_add, apply hadd; assumption }
end
end is_tensor_product
section is_base_change
variables {R : Type*} {M : Type vβ} {N : Type vβ} (S : Type vβ)
variables [add_comm_monoid M] [add_comm_monoid N] [comm_ring R]
variables [comm_ring S] [algebra R S] [module R M] [module R N] [module S N] [is_scalar_tower R S N]
variables (f : M ββ[R] N)
include f
/-- Given an `R`-algebra `S` and an `R`-module `M`, an `S`-module `N` together with a map
`f : M ββ[R] N` is the base change of `M` to `S` if the map `S Γ M β N, (s, m) β¦ s β’ f m` is the
tensor product. -/
def is_base_change : Prop := is_tensor_product
(((algebra.of_id S $ module.End S (M ββ[R] N)).to_linear_map.flip f).restrict_scalars R)
variables {S f} (h : is_base_change S f)
variables {P Q : Type*} [add_comm_monoid P] [module R P]
variables [add_comm_monoid Q] [module S Q]
section
variables [module R Q] [is_scalar_tower R S Q]
/-- Suppose `f : M ββ[R] N` is the base change of `M` along `R β S`. Then any `R`-linear map from
`M` to an `S`-module factors thorugh `f`. -/
noncomputable
def is_base_change.lift (g : M ββ[R] Q) : N ββ[S] Q :=
{ map_smul' := Ξ» r x, begin
let F := ((algebra.of_id S $ module.End S (M ββ[R] Q))
.to_linear_map.flip g).restrict_scalars R,
have hF : β (s : S) (m : M), h.lift F (s β’ f m) = s β’ g m := h.lift_eq F,
change h.lift F (r β’ x) = r β’ h.lift F x,
apply h.induction_on x,
{ rw [smul_zero, map_zero, smul_zero] },
{ intros s m,
change h.lift F (r β’ s β’ f m) = r β’ h.lift F (s β’ f m),
rw [β mul_smul, hF, hF, mul_smul] },
{ intros xβ xβ eβ eβ, rw [map_add, smul_add, map_add, smul_add, eβ, eβ] }
end,
..(h.lift (((algebra.of_id S $ module.End S (M ββ[R] Q))
.to_linear_map.flip g).restrict_scalars R)) }
lemma is_base_change.lift_eq (g : M ββ[R] Q) (x : M) : h.lift g (f x) = g x :=
begin
have hF : β (s : S) (m : M), h.lift g (s β’ f m) = s β’ g m := h.lift_eq _,
convert hF 1 x; rw one_smul,
end
lemma is_base_change.lift_comp (g : M ββ[R] Q) : ((h.lift g).restrict_scalars R).comp f = g :=
linear_map.ext (h.lift_eq g)
end
include h
@[elab_as_eliminator]
lemma is_base_change.induction_on (x : N) (P : N β Prop)
(hβ : P 0)
(hβ : β m : M, P (f m))
(hβ : β (s : S) n, P n β P (s β’ n))
(hβ : β nβ nβ, P nβ β P nβ β P (nβ + nβ)) : P x :=
h.induction_on x hβ (Ξ» s y, hβ _ _ (hβ _)) hβ
lemma is_base_change.alg_hom_ext (gβ gβ : N ββ[S] Q) (e : β x, gβ (f x) = gβ (f x)) :
gβ = gβ :=
begin
ext x,
apply h.induction_on x,
{ rw [map_zero, map_zero] },
{ assumption },
{ intros s n e', rw [gβ.map_smul, gβ.map_smul, e'] },
{ intros x y eβ eβ, rw [map_add, map_add, eβ, eβ] }
end
lemma is_base_change.alg_hom_ext' [module R Q] [is_scalar_tower R S Q] (gβ gβ : N ββ[S] Q)
(e : (gβ.restrict_scalars R).comp f = (gβ.restrict_scalars R).comp f) :
gβ = gβ :=
h.alg_hom_ext gβ gβ (linear_map.congr_fun e)
variables (R M N S)
omit h f
lemma tensor_product.is_base_change : is_base_change S (tensor_product.mk R S M 1) :=
begin
delta is_base_change,
convert tensor_product.is_tensor_product R S M using 1,
ext s x,
change s β’ 1 ββ x = s ββ x,
rw tensor_product.smul_tmul',
congr' 1,
exact mul_one _,
end
variables {R M N S}
/-- The base change of `M` along `R β S` is linearly equivalent to `S β[R] M`. -/
noncomputable
def is_base_change.equiv : S β[R] M ββ[S] N :=
{ map_smul' := Ξ» r x, begin
change h.equiv (r β’ x) = r β’ h.equiv x,
apply tensor_product.induction_on x,
{ rw [smul_zero, map_zero, smul_zero] },
{ intros x y, simp [smul_tmul', algebra.of_id_apply] },
{ intros x y hx hy, rw [map_add, smul_add, map_add, smul_add, hx, hy] },
end,
..h.equiv }
lemma is_base_change.equiv_tmul (s : S) (m : M) : h.equiv (s ββ m) = s β’ (f m) :=
tensor_product.lift.tmul s m
lemma is_base_change.equiv_symm_apply (m : M) : h.equiv.symm (f m) = 1 ββ m :=
by rw [h.equiv.symm_apply_eq, h.equiv_tmul, one_smul]
variable (f)
lemma is_base_change.of_lift_unique
(h : β (Q : Type (max vβ vβ vβ)) [add_comm_monoid Q], by exactI β [module R Q] [module S Q],
by exactI β [is_scalar_tower R S Q], by exactI β (g : M ββ[R] Q),
β! (g' : N ββ[S] Q), (g'.restrict_scalars R).comp f = g) : is_base_change S f :=
begin
obtain β¨g, hg, -β© := h (ulift.{vβ} $ S β[R] M)
(ulift.module_equiv.symm.to_linear_map.comp $ tensor_product.mk R S M 1),
let f' : S β[R] M ββ[R] N := _, change function.bijective f',
let f'' : S β[R] M ββ[S] N,
{ refine { to_fun := f', map_smul' := Ξ» s x,
tensor_product.induction_on x _ (Ξ» s' y, smul_assoc s s' _) (Ξ» x y hx hy, _), .. f' },
{ rw [map_zero, smul_zero, map_zero, smul_zero] },
{ rw [smul_add, map_add, map_add, smul_add, hx, hy] } },
simp_rw [fun_like.ext_iff, linear_map.comp_apply, linear_map.restrict_scalars_apply] at hg,
let fe : S β[R] M ββ[S] N :=
linear_equiv.of_linear f'' (ulift.module_equiv.to_linear_map.comp g) _ _,
{ exact fe.bijective },
{ rw β (linear_map.cancel_left (ulift.module_equiv : ulift.{max vβ vβ} N ββ[S] N).symm.injective),
refine (h (ulift.{max vβ vβ} N) $ ulift.module_equiv.symm.to_linear_map.comp f).unique _ rfl,
{ apply_instance },
ext x,
simp only [linear_map.comp_apply, linear_map.restrict_scalars_apply, hg],
apply one_smul },
{ ext x, change (g $ (1 : S) β’ f x).down = _, rw [one_smul, hg], refl },
end
variable {f}
lemma is_base_change.iff_lift_unique :
is_base_change S f β
β (Q : Type (max vβ vβ vβ)) [add_comm_monoid Q], by exactI β [module R Q] [module S Q],
by exactI β [is_scalar_tower R S Q], by exactI β (g : M ββ[R] Q),
β! (g' : N ββ[S] Q), (g'.restrict_scalars R).comp f = g :=
β¨Ξ» h, by { introsI,
exact β¨h.lift g, h.lift_comp g, Ξ» g' e, h.alg_hom_ext' _ _ (e.trans (h.lift_comp g).symm)β© },
is_base_change.of_lift_unique fβ©
lemma is_base_change.of_equiv (e : M ββ[R] N) : is_base_change R e.to_linear_map :=
begin
apply is_base_change.of_lift_unique,
introsI Q Iβ Iβ Iβ Iβ g,
have : Iβ = Iβ,
{ ext r q,
rw [β one_smul R q, smul_smul, β smul_assoc, smul_eq_mul, mul_one] },
unfreezingI { cases this },
refine β¨g.comp e.symm.to_linear_map, by { ext, simp }, _β©,
rintros y (rfl : _ = _),
ext,
simp,
end
variables {T O : Type*} [comm_ring T] [algebra R T] [algebra S T] [is_scalar_tower R S T]
variables [add_comm_monoid O] [module R O] [module S O] [module T O] [is_scalar_tower S T O]
variables [is_scalar_tower R S O] [is_scalar_tower R T O]
lemma is_base_change.comp {f : M ββ[R] N} (hf : is_base_change S f) {g : N ββ[S] O}
(hg : is_base_change T g) : is_base_change T ((g.restrict_scalars R).comp f) :=
begin
apply is_base_change.of_lift_unique,
introsI Q _ _ _ _ i,
letI := module.comp_hom Q (algebra_map S T),
haveI : is_scalar_tower S T Q := β¨Ξ» x y z, by { rw [algebra.smul_def, mul_smul], refl }β©,
haveI : is_scalar_tower R S Q,
{ refine β¨Ξ» x y z, _β©,
change (is_scalar_tower.to_alg_hom R S T) (x β’ y) β’ z = x β’ (algebra_map S T y β’ z),
rw [alg_hom.map_smul, smul_assoc],
refl },
refine β¨hg.lift (hf.lift i), by { ext, simp [is_base_change.lift_eq] }, _β©,
rintros g' (e : _ = _),
refine hg.alg_hom_ext' _ _ (hf.alg_hom_ext' _ _ _),
rw [is_base_change.lift_comp, is_base_change.lift_comp, β e],
ext,
refl
end
variables {R' S' : Type*} [comm_ring R'] [comm_ring S']
variables [algebra R R'] [algebra S S'] [algebra R' S'] [algebra R S']
variables [is_scalar_tower R R' S'] [is_scalar_tower R S S']
open is_scalar_tower (to_alg_hom)
variables (R S R' S')
/--
A type-class stating that the following diagram of scalar towers
R β S
β β
R' β S'
is a pushout diagram (i.e. `S' = S β[R] R'`)
-/
@[mk_iff]
class algebra.is_pushout : Prop :=
(out : is_base_change S (to_alg_hom R R' S').to_linear_map)
variables {R S R' S'}
lemma algebra.is_pushout.symm
(h : algebra.is_pushout R S R' S') :
algebra.is_pushout R R' S S' :=
begin
letI := (algebra.tensor_product.include_right : R' ββ[R] S β R').to_ring_hom.to_algebra,
let e : R' β[R] S ββ[R'] S',
{ refine { map_smul' := _, ..(tensor_product.comm R R' S).trans $ h.1.equiv.restrict_scalars R },
intros r x,
change
h.1.equiv (tensor_product.comm R R' S (r β’ x)) = r β’ h.1.equiv (tensor_product.comm R R' S x),
apply tensor_product.induction_on x,
{ simp only [smul_zero, map_zero] },
{ intros x y,
simp [smul_tmul', algebra.smul_def, ring_hom.algebra_map_to_algebra, h.1.equiv_tmul],
ring },
{ intros x y hx hy, simp only [map_add, smul_add, hx, hy] } },
have : (to_alg_hom R S S').to_linear_map
= (e.to_linear_map.restrict_scalars R).comp (tensor_product.mk R R' S 1),
{ ext, simp [e, h.1.equiv_tmul, algebra.smul_def] },
constructor,
rw this,
exact (tensor_product.is_base_change R S R').comp (is_base_change.of_equiv e),
end
variables (R S R' S')
lemma algebra.is_pushout.comm :
algebra.is_pushout R S R' S' β algebra.is_pushout R R' S S' :=
β¨algebra.is_pushout.symm, algebra.is_pushout.symmβ©
variables {R S R'}
local attribute [instance] algebra.tensor_product.right_algebra
instance tensor_product.is_pushout {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T]
[algebra R S] [algebra R T] :
algebra.is_pushout R S T (tensor_product R S T) :=
β¨tensor_product.is_base_change R T Sβ©
instance tensor_product.is_pushout' {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T]
[algebra R S] [algebra R T] :
algebra.is_pushout R T S (tensor_product R S T) :=
algebra.is_pushout.symm infer_instance
/--
If `S' = S β[R] R'`, then any pair of `R`-algebra homomorphisms `f : S β A` and `g : R' β A`
such that `f x` and `g y` commutes for all `x, y` descends to a (unique) homomoprhism `S' β A`.
-/
@[simps apply (lemmas_only)] noncomputable
def algebra.pushout_desc [H : algebra.is_pushout R S R' S']
{A : Type*} [semiring A] [algebra R A] (f : S ββ[R] A) (g : R' ββ[R] A)
(hf : β x y, f x * g y = g y * f x) : S' ββ[R] A :=
begin
letI := module.comp_hom A f.to_ring_hom,
haveI : is_scalar_tower R S A :=
{ smul_assoc := Ξ» r s a, show f (r β’ s) * a = r β’ (f s * a), by rw [f.map_smul, smul_mul_assoc] },
haveI : is_scalar_tower S A A :=
{ smul_assoc := Ξ» r a b, mul_assoc _ _ _ },
have : β x, H.out.lift g.to_linear_map (algebra_map R' S' x) = g x := H.out.lift_eq _,
refine alg_hom.of_linear_map ((H.out.lift g.to_linear_map).restrict_scalars R) _ _,
{ dsimp only [linear_map.restrict_scalars_apply],
rw [β (algebra_map R' S').map_one, this, g.map_one] },
{ intros x y,
apply H.out.induction_on x,
{ rw [zero_mul, map_zero, zero_mul] },
rotate,
{ intros s s' e, dsimp only [linear_map.restrict_scalars_apply] at e β’,
rw [linear_map.map_smul, smul_mul_assoc, linear_map.map_smul, e, smul_mul_assoc] },
{ intros s s' eβ eβ, dsimp only [linear_map.restrict_scalars_apply] at eβ eβ β’,
rw [add_mul, map_add, map_add, add_mul, eβ, eβ] },
intro x, dsimp, rw this, apply H.out.induction_on y,
{ rw [mul_zero, map_zero, mul_zero] },
{ intro y, dsimp, rw [β _root_.map_mul, this, this, _root_.map_mul] },
{ intros s s' e,
rw [mul_comm, smul_mul_assoc, linear_map.map_smul, linear_map.map_smul, mul_comm, e],
change f s * (g x * _) = g x * (f s * _),
rw [β mul_assoc, β mul_assoc, hf] },
{ intros s s' eβ eβ, rw [mul_add, map_add, map_add, mul_add, eβ, eβ] }, }
end
@[simp]
lemma algebra.pushout_desc_left [H : algebra.is_pushout R S R' S']
{A : Type*} [semiring A] [algebra R A] (f : S ββ[R] A) (g : R' ββ[R] A) (H) (x : S) :
algebra.pushout_desc S' f g H (algebra_map S S' x) = f x :=
begin
rw [algebra.pushout_desc_apply, algebra.algebra_map_eq_smul_one, linear_map.map_smul,
β algebra.pushout_desc_apply S' f g H, _root_.map_one],
exact mul_one (f x)
end
lemma algebra.lift_alg_hom_comp_left [H : algebra.is_pushout R S R' S']
{A : Type*} [semiring A] [algebra R A] (f : S ββ[R] A) (g : R' ββ[R] A) (H) :
(algebra.pushout_desc S' f g H).comp (to_alg_hom R S S') = f :=
alg_hom.ext (Ξ» x, (algebra.pushout_desc_left S' f g H x : _))
@[simp]
lemma algebra.pushout_desc_right [H : algebra.is_pushout R S R' S']
{A : Type*} [semiring A] [algebra R A] (f : S ββ[R] A) (g : R' ββ[R] A) (H) (x : R') :
algebra.pushout_desc S' f g H (algebra_map R' S' x) = g x :=
begin
apply_with @@is_base_change.lift_eq { instances := ff },
end
lemma algebra.lift_alg_hom_comp_right [H : algebra.is_pushout R S R' S']
{A : Type*} [semiring A] [algebra R A] (f : S ββ[R] A) (g : R' ββ[R] A) (H) :
(algebra.pushout_desc S' f g H).comp (to_alg_hom R R' S') = g :=
alg_hom.ext (Ξ» x, (algebra.pushout_desc_right S' f g H x : _))
@[ext]
lemma algebra.is_pushout.alg_hom_ext [H : algebra.is_pushout R S R' S']
{A : Type*} [semiring A] [algebra R A] {f g : S' ββ[R] A}
(hβ : f.comp (to_alg_hom R R' S') = g.comp (to_alg_hom R R' S'))
(hβ : f.comp (to_alg_hom R S S') = g.comp (to_alg_hom R S S')) : f = g :=
begin
ext x,
apply H.1.induction_on x,
{ simp only [map_zero] },
{ exact alg_hom.congr_fun hβ },
{ intros s s' e, rw [algebra.smul_def, f.map_mul, g.map_mul, e],
congr' 1, exact (alg_hom.congr_fun hβ s : _) },
{ intros sβ sβ eβ eβ, rw [map_add, map_add, eβ, eβ] }
end
end is_base_change
|
29d6a81643be7ad7e85df5aa97822aa5f97d0beb | c777c32c8e484e195053731103c5e52af26a25d1 | /src/topology/metric_space/isometry.lean | ef29d1dcb320098192d07d857becf26a7cc892fc | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 20,544 | lean | /-
Copyright (c) 2018 SΓ©bastien GouΓ«zel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Isometries of emetric and metric spaces
Authors: SΓ©bastien GouΓ«zel
-/
import topology.metric_space.antilipschitz
/-!
# Isometries
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define isometries, i.e., maps between emetric spaces that preserve
the edistance (on metric spaces, these are exactly the maps that preserve distances),
and prove their basic properties. We also introduce isometric bijections.
Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the
theory for `pseudo_metric_space` and we specialize to `metric_space` when needed.
-/
noncomputable theory
universes u v w
variables {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w}
open function set
open_locale topology ennreal
/-- An isometry (also known as isometric embedding) is a map preserving the edistance
between pseudoemetric spaces, or equivalently the distance between pseudometric space. -/
def isometry [pseudo_emetric_space Ξ±] [pseudo_emetric_space Ξ²] (f : Ξ± β Ξ²) : Prop :=
βx1 x2 : Ξ±, edist (f x1) (f x2) = edist x1 x2
/-- On pseudometric spaces, a map is an isometry if and only if it preserves nonnegative
distances. -/
lemma isometry_iff_nndist_eq [pseudo_metric_space Ξ±] [pseudo_metric_space Ξ²] {f : Ξ± β Ξ²} :
isometry f β (βx y, nndist (f x) (f y) = nndist x y) :=
by simp only [isometry, edist_nndist, ennreal.coe_eq_coe]
/-- On pseudometric spaces, a map is an isometry if and only if it preserves distances. -/
lemma isometry_iff_dist_eq [pseudo_metric_space Ξ±] [pseudo_metric_space Ξ²] {f : Ξ± β Ξ²} :
isometry f β (βx y, dist (f x) (f y) = dist x y) :=
by simp only [isometry_iff_nndist_eq, β coe_nndist, nnreal.coe_eq]
/-- An isometry preserves distances. -/
alias isometry_iff_dist_eq β isometry.dist_eq _
/-- A map that preserves distances is an isometry -/
alias isometry_iff_dist_eq β _ isometry.of_dist_eq
/-- An isometry preserves non-negative distances. -/
alias isometry_iff_nndist_eq β isometry.nndist_eq _
/-- A map that preserves non-negative distances is an isometry. -/
alias isometry_iff_nndist_eq β _ isometry.of_nndist_eq
namespace isometry
section pseudo_emetric_isometry
variables [pseudo_emetric_space Ξ±] [pseudo_emetric_space Ξ²] [pseudo_emetric_space Ξ³]
variables {f : Ξ± β Ξ²} {x y z : Ξ±} {s : set Ξ±}
/-- An isometry preserves edistances. -/
theorem edist_eq (hf : isometry f) (x y : Ξ±) : edist (f x) (f y) = edist x y := hf x y
lemma lipschitz (h : isometry f) : lipschitz_with 1 f :=
lipschitz_with.of_edist_le $ Ξ» x y, (h x y).le
lemma antilipschitz (h : isometry f) : antilipschitz_with 1 f :=
Ξ» x y, by simp only [h x y, ennreal.coe_one, one_mul, le_refl]
/-- Any map on a subsingleton is an isometry -/
@[nontriviality] theorem _root_.isometry_subsingleton [subsingleton Ξ±] : isometry f :=
Ξ»x y, by rw subsingleton.elim x y; simp
/-- The identity is an isometry -/
lemma _root_.isometry_id : isometry (id : Ξ± β Ξ±) := Ξ» x y, rfl
lemma prod_map {Ξ΄} [pseudo_emetric_space Ξ΄] {f : Ξ± β Ξ²} {g : Ξ³ β Ξ΄} (hf : isometry f)
(hg : isometry g) : isometry (prod.map f g) :=
Ξ» x y, by simp only [prod.edist_eq, hf.edist_eq, hg.edist_eq, prod_map]
lemma _root_.isometry_dcomp {ΞΉ} [fintype ΞΉ] {Ξ± Ξ² : ΞΉ β Type*} [Ξ i, pseudo_emetric_space (Ξ± i)]
[Ξ i, pseudo_emetric_space (Ξ² i)] (f : Ξ i, Ξ± i β Ξ² i) (hf : β i, isometry (f i)) :
isometry (dcomp f) :=
Ξ» x y, by simp only [edist_pi_def, (hf _).edist_eq]
/-- The composition of isometries is an isometry. -/
theorem comp {g : Ξ² β Ξ³} {f : Ξ± β Ξ²} (hg : isometry g) (hf : isometry f) : isometry (g β f) :=
Ξ» x y, (hg _ _).trans (hf _ _)
/-- An isometry from a metric space is a uniform continuous map -/
protected theorem uniform_continuous (hf : isometry f) : uniform_continuous f :=
hf.lipschitz.uniform_continuous
/-- An isometry from a metric space is a uniform inducing map -/
protected theorem uniform_inducing (hf : isometry f) : uniform_inducing f :=
hf.antilipschitz.uniform_inducing hf.uniform_continuous
lemma tendsto_nhds_iff {ΞΉ : Type*} {f : Ξ± β Ξ²} {g : ΞΉ β Ξ±} {a : filter ΞΉ} {b : Ξ±}
(hf : isometry f) :
filter.tendsto g a (π b) β filter.tendsto (f β g) a (π (f b)) :=
hf.uniform_inducing.inducing.tendsto_nhds_iff
/-- An isometry is continuous. -/
protected lemma continuous (hf : isometry f) : continuous f := hf.lipschitz.continuous
/-- The right inverse of an isometry is an isometry. -/
lemma right_inv {f : Ξ± β Ξ²} {g : Ξ² β Ξ±} (h : isometry f) (hg : right_inverse g f) :
isometry g :=
Ξ» x y, by rw [β h, hg _, hg _]
lemma preimage_emetric_closed_ball (h : isometry f) (x : Ξ±) (r : ββ₯0β) :
f β»ΒΉ' (emetric.closed_ball (f x) r) = emetric.closed_ball x r :=
by { ext y, simp [h.edist_eq] }
lemma preimage_emetric_ball (h : isometry f) (x : Ξ±) (r : ββ₯0β) :
f β»ΒΉ' (emetric.ball (f x) r) = emetric.ball x r :=
by { ext y, simp [h.edist_eq] }
/-- Isometries preserve the diameter in pseudoemetric spaces. -/
lemma ediam_image (hf : isometry f) (s : set Ξ±) : emetric.diam (f '' s) = emetric.diam s :=
eq_of_forall_ge_iff $ Ξ» d,
by simp only [emetric.diam_le_iff, ball_image_iff, hf.edist_eq]
lemma ediam_range (hf : isometry f) : emetric.diam (range f) = emetric.diam (univ : set Ξ±) :=
by { rw β image_univ, exact hf.ediam_image univ }
lemma maps_to_emetric_ball (hf : isometry f) (x : Ξ±) (r : ββ₯0β) :
maps_to f (emetric.ball x r) (emetric.ball (f x) r) :=
(hf.preimage_emetric_ball x r).ge
lemma maps_to_emetric_closed_ball (hf : isometry f) (x : Ξ±) (r : ββ₯0β) :
maps_to f (emetric.closed_ball x r) (emetric.closed_ball (f x) r) :=
(hf.preimage_emetric_closed_ball x r).ge
/-- The injection from a subtype is an isometry -/
lemma _root_.isometry_subtype_coe {s : set Ξ±} : isometry (coe : s β Ξ±) :=
Ξ»x y, rfl
lemma comp_continuous_on_iff {Ξ³} [topological_space Ξ³] (hf : isometry f) {g : Ξ³ β Ξ±} {s : set Ξ³} :
continuous_on (f β g) s β continuous_on g s :=
hf.uniform_inducing.inducing.continuous_on_iff.symm
lemma comp_continuous_iff {Ξ³} [topological_space Ξ³] (hf : isometry f) {g : Ξ³ β Ξ±} :
continuous (f β g) β continuous g :=
hf.uniform_inducing.inducing.continuous_iff.symm
end pseudo_emetric_isometry --section
section emetric_isometry
variables [emetric_space Ξ±] [pseudo_emetric_space Ξ²] {f : Ξ± β Ξ²}
/-- An isometry from an emetric space is injective -/
protected lemma injective (h : isometry f) : injective f := h.antilipschitz.injective
/-- An isometry from an emetric space is a uniform embedding -/
protected theorem uniform_embedding (hf : isometry f) : uniform_embedding f :=
hf.antilipschitz.uniform_embedding hf.lipschitz.uniform_continuous
/-- An isometry from an emetric space is an embedding -/
protected theorem embedding (hf : isometry f) : embedding f :=
hf.uniform_embedding.embedding
/-- An isometry from a complete emetric space is a closed embedding -/
theorem closed_embedding [complete_space Ξ±] [emetric_space Ξ³]
{f : Ξ± β Ξ³} (hf : isometry f) : closed_embedding f :=
hf.antilipschitz.closed_embedding hf.lipschitz.uniform_continuous
end emetric_isometry --section
section pseudo_metric_isometry
variables [pseudo_metric_space Ξ±] [pseudo_metric_space Ξ²] {f : Ξ± β Ξ²}
/-- An isometry preserves the diameter in pseudometric spaces. -/
lemma diam_image (hf : isometry f) (s : set Ξ±) : metric.diam (f '' s) = metric.diam s :=
by rw [metric.diam, metric.diam, hf.ediam_image]
lemma diam_range (hf : isometry f) : metric.diam (range f) = metric.diam (univ : set Ξ±) :=
by { rw β image_univ, exact hf.diam_image univ }
lemma preimage_set_of_dist (hf : isometry f) (x : Ξ±) (p : β β Prop) :
f β»ΒΉ' {y | p (dist y (f x))} = {y | p (dist y x)} :=
by { ext y, simp [hf.dist_eq] }
lemma preimage_closed_ball (hf : isometry f) (x : Ξ±) (r : β) :
f β»ΒΉ' (metric.closed_ball (f x) r) = metric.closed_ball x r :=
hf.preimage_set_of_dist x (β€ r)
lemma preimage_ball (hf : isometry f) (x : Ξ±) (r : β) :
f β»ΒΉ' (metric.ball (f x) r) = metric.ball x r :=
hf.preimage_set_of_dist x (< r)
lemma preimage_sphere (hf : isometry f) (x : Ξ±) (r : β) :
f β»ΒΉ' (metric.sphere (f x) r) = metric.sphere x r :=
hf.preimage_set_of_dist x (= r)
lemma maps_to_ball (hf : isometry f) (x : Ξ±) (r : β) :
maps_to f (metric.ball x r) (metric.ball (f x) r) :=
(hf.preimage_ball x r).ge
lemma maps_to_sphere (hf : isometry f) (x : Ξ±) (r : β) :
maps_to f (metric.sphere x r) (metric.sphere (f x) r) :=
(hf.preimage_sphere x r).ge
lemma maps_to_closed_ball (hf : isometry f) (x : Ξ±) (r : β) :
maps_to f (metric.closed_ball x r) (metric.closed_ball (f x) r) :=
(hf.preimage_closed_ball x r).ge
end pseudo_metric_isometry -- section
end isometry -- namespace
/-- A uniform embedding from a uniform space to a metric space is an isometry with respect to the
induced metric space structure on the source space. -/
lemma uniform_embedding.to_isometry {Ξ± Ξ²} [uniform_space Ξ±] [metric_space Ξ²] {f : Ξ± β Ξ²}
(h : uniform_embedding f) :
@isometry Ξ± Ξ²
(@pseudo_metric_space.to_pseudo_emetric_space Ξ±
(@metric_space.to_pseudo_metric_space Ξ± (h.comap_metric_space f)))
(by apply_instance) f :=
begin
apply isometry.of_dist_eq,
assume x y,
refl
end
/-- An embedding from a topological space to a metric space is an isometry with respect to the
induced metric space structure on the source space. -/
lemma embedding.to_isometry {Ξ± Ξ²} [topological_space Ξ±] [metric_space Ξ²] {f : Ξ± β Ξ²}
(h : embedding f) :
@isometry Ξ± Ξ²
(@pseudo_metric_space.to_pseudo_emetric_space Ξ±
(@metric_space.to_pseudo_metric_space Ξ± (h.comap_metric_space f)))
(by apply_instance) f :=
begin
apply isometry.of_dist_eq,
assume x y,
refl
end
/-- `Ξ±` and `Ξ²` are isometric if there is an isometric bijection between them. -/
@[nolint has_nonempty_instance] -- such a bijection need not exist
structure isometry_equiv (Ξ± Ξ² : Type*) [pseudo_emetric_space Ξ±] [pseudo_emetric_space Ξ²]
extends Ξ± β Ξ² :=
(isometry_to_fun : isometry to_fun)
infix ` βα΅’ `:25 := isometry_equiv
namespace isometry_equiv
section pseudo_emetric_space
variables [pseudo_emetric_space Ξ±] [pseudo_emetric_space Ξ²] [pseudo_emetric_space Ξ³]
instance : has_coe_to_fun (Ξ± βα΅’ Ξ²) (Ξ» _, Ξ± β Ξ²) := β¨Ξ»e, e.to_equivβ©
lemma coe_eq_to_equiv (h : Ξ± βα΅’ Ξ²) (a : Ξ±) : h a = h.to_equiv a := rfl
@[simp] lemma coe_to_equiv (h : Ξ± βα΅’ Ξ²) : βh.to_equiv = h := rfl
protected lemma isometry (h : Ξ± βα΅’ Ξ²) : isometry h := h.isometry_to_fun
protected lemma bijective (h : Ξ± βα΅’ Ξ²) : bijective h := h.to_equiv.bijective
protected lemma injective (h : Ξ± βα΅’ Ξ²) : injective h := h.to_equiv.injective
protected lemma surjective (h : Ξ± βα΅’ Ξ²) : surjective h := h.to_equiv.surjective
protected lemma edist_eq (h : Ξ± βα΅’ Ξ²) (x y : Ξ±) : edist (h x) (h y) = edist x y :=
h.isometry.edist_eq x y
protected lemma dist_eq {Ξ± Ξ² : Type*} [pseudo_metric_space Ξ±] [pseudo_metric_space Ξ²] (h : Ξ± βα΅’ Ξ²)
(x y : Ξ±) : dist (h x) (h y) = dist x y :=
h.isometry.dist_eq x y
protected lemma nndist_eq {Ξ± Ξ² : Type*} [pseudo_metric_space Ξ±] [pseudo_metric_space Ξ²] (h : Ξ± βα΅’ Ξ²)
(x y : Ξ±) : nndist (h x) (h y) = nndist x y :=
h.isometry.nndist_eq x y
protected lemma continuous (h : Ξ± βα΅’ Ξ²) : continuous h := h.isometry.continuous
@[simp] lemma ediam_image (h : Ξ± βα΅’ Ξ²) (s : set Ξ±) : emetric.diam (h '' s) = emetric.diam s :=
h.isometry.ediam_image s
lemma to_equiv_inj : β β¦hβ hβ : Ξ± βα΅’ Ξ²β¦, (hβ.to_equiv = hβ.to_equiv) β hβ = hβ
| β¨eβ, hββ© β¨eβ, hββ© H := by { dsimp at H, subst eβ }
@[ext] lemma ext β¦hβ hβ : Ξ± βα΅’ Ξ²β¦ (H : β x, hβ x = hβ x) : hβ = hβ :=
to_equiv_inj $ equiv.ext H
/-- Alternative constructor for isometric bijections,
taking as input an isometry, and a right inverse. -/
def mk' {Ξ± : Type u} [emetric_space Ξ±] (f : Ξ± β Ξ²) (g : Ξ² β Ξ±) (hfg : β x, f (g x) = x)
(hf : isometry f) : Ξ± βα΅’ Ξ² :=
{ to_fun := f,
inv_fun := g,
left_inv := Ξ» x, hf.injective $ hfg _,
right_inv := hfg,
isometry_to_fun := hf }
/-- The identity isometry of a space. -/
protected def refl (Ξ± : Type*) [pseudo_emetric_space Ξ±] : Ξ± βα΅’ Ξ± :=
{ isometry_to_fun := isometry_id, .. equiv.refl Ξ± }
/-- The composition of two isometric isomorphisms, as an isometric isomorphism. -/
protected def trans (hβ : Ξ± βα΅’ Ξ²) (hβ : Ξ² βα΅’ Ξ³) : Ξ± βα΅’ Ξ³ :=
{ isometry_to_fun := hβ.isometry_to_fun.comp hβ.isometry_to_fun,
.. equiv.trans hβ.to_equiv hβ.to_equiv }
@[simp] lemma trans_apply (hβ : Ξ± βα΅’ Ξ²) (hβ : Ξ² βα΅’ Ξ³) (x : Ξ±) : hβ.trans hβ x = hβ (hβ x) := rfl
/-- The inverse of an isometric isomorphism, as an isometric isomorphism. -/
protected def symm (h : Ξ± βα΅’ Ξ²) : Ξ² βα΅’ Ξ± :=
{ isometry_to_fun := h.isometry.right_inv h.right_inv,
to_equiv := h.to_equiv.symm }
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.apply (h : Ξ± βα΅’ Ξ²) : Ξ± β Ξ² := h
/-- See Note [custom simps projection] -/
def simps.symm_apply (h : Ξ± βα΅’ Ξ²) : Ξ² β Ξ± := h.symm
initialize_simps_projections isometry_equiv
(to_equiv_to_fun β apply, to_equiv_inv_fun β symm_apply)
@[simp] lemma symm_symm (h : Ξ± βα΅’ Ξ²) : h.symm.symm = h := to_equiv_inj h.to_equiv.symm_symm
@[simp] lemma apply_symm_apply (h : Ξ± βα΅’ Ξ²) (y : Ξ²) : h (h.symm y) = y :=
h.to_equiv.apply_symm_apply y
@[simp] lemma symm_apply_apply (h : Ξ± βα΅’ Ξ²) (x : Ξ±) : h.symm (h x) = x :=
h.to_equiv.symm_apply_apply x
lemma symm_apply_eq (h : Ξ± βα΅’ Ξ²) {x : Ξ±} {y : Ξ²} :
h.symm y = x β y = h x :=
h.to_equiv.symm_apply_eq
lemma eq_symm_apply (h : Ξ± βα΅’ Ξ²) {x : Ξ±} {y : Ξ²} :
x = h.symm y β h x = y :=
h.to_equiv.eq_symm_apply
lemma symm_comp_self (h : Ξ± βα΅’ Ξ²) : βh.symm β βh = id :=
funext $ assume a, h.to_equiv.left_inv a
lemma self_comp_symm (h : Ξ± βα΅’ Ξ²) : βh β βh.symm = id :=
funext $ assume a, h.to_equiv.right_inv a
@[simp] lemma range_eq_univ (h : Ξ± βα΅’ Ξ²) : range h = univ :=
h.to_equiv.range_eq_univ
lemma image_symm (h : Ξ± βα΅’ Ξ²) : image h.symm = preimage h :=
image_eq_preimage_of_inverse h.symm.to_equiv.left_inv h.symm.to_equiv.right_inv
lemma preimage_symm (h : Ξ± βα΅’ Ξ²) : preimage h.symm = image h :=
(image_eq_preimage_of_inverse h.to_equiv.left_inv h.to_equiv.right_inv).symm
@[simp] lemma symm_trans_apply (hβ : Ξ± βα΅’ Ξ²) (hβ : Ξ² βα΅’ Ξ³) (x : Ξ³) :
(hβ.trans hβ).symm x = hβ.symm (hβ.symm x) := rfl
lemma ediam_univ (h : Ξ± βα΅’ Ξ²) : emetric.diam (univ : set Ξ±) = emetric.diam (univ : set Ξ²) :=
by rw [β h.range_eq_univ, h.isometry.ediam_range]
@[simp] lemma ediam_preimage (h : Ξ± βα΅’ Ξ²) (s : set Ξ²) : emetric.diam (h β»ΒΉ' s) = emetric.diam s :=
by rw [β image_symm, ediam_image]
@[simp] lemma preimage_emetric_ball (h : Ξ± βα΅’ Ξ²) (x : Ξ²) (r : ββ₯0β) :
h β»ΒΉ' (emetric.ball x r) = emetric.ball (h.symm x) r :=
by rw [β h.isometry.preimage_emetric_ball (h.symm x) r, h.apply_symm_apply]
@[simp] lemma preimage_emetric_closed_ball (h : Ξ± βα΅’ Ξ²) (x : Ξ²) (r : ββ₯0β) :
h β»ΒΉ' (emetric.closed_ball x r) = emetric.closed_ball (h.symm x) r :=
by rw [β h.isometry.preimage_emetric_closed_ball (h.symm x) r, h.apply_symm_apply]
@[simp] lemma image_emetric_ball (h : Ξ± βα΅’ Ξ²) (x : Ξ±) (r : ββ₯0β) :
h '' (emetric.ball x r) = emetric.ball (h x) r :=
by rw [β h.preimage_symm, h.symm.preimage_emetric_ball, symm_symm]
@[simp] lemma image_emetric_closed_ball (h : Ξ± βα΅’ Ξ²) (x : Ξ±) (r : ββ₯0β) :
h '' (emetric.closed_ball x r) = emetric.closed_ball (h x) r :=
by rw [β h.preimage_symm, h.symm.preimage_emetric_closed_ball, symm_symm]
/-- The (bundled) homeomorphism associated to an isometric isomorphism. -/
@[simps to_equiv] protected def to_homeomorph (h : Ξ± βα΅’ Ξ²) : Ξ± ββ Ξ² :=
{ continuous_to_fun := h.continuous,
continuous_inv_fun := h.symm.continuous,
to_equiv := h.to_equiv }
@[simp] lemma coe_to_homeomorph (h : Ξ± βα΅’ Ξ²) : β(h.to_homeomorph) = h := rfl
@[simp] lemma coe_to_homeomorph_symm (h : Ξ± βα΅’ Ξ²) : β(h.to_homeomorph.symm) = h.symm := rfl
@[simp] lemma comp_continuous_on_iff {Ξ³} [topological_space Ξ³] (h : Ξ± βα΅’ Ξ²)
{f : Ξ³ β Ξ±} {s : set Ξ³} :
continuous_on (h β f) s β continuous_on f s :=
h.to_homeomorph.comp_continuous_on_iff _ _
@[simp] lemma comp_continuous_iff {Ξ³} [topological_space Ξ³] (h : Ξ± βα΅’ Ξ²) {f : Ξ³ β Ξ±} :
continuous (h β f) β continuous f :=
h.to_homeomorph.comp_continuous_iff
@[simp] lemma comp_continuous_iff' {Ξ³} [topological_space Ξ³] (h : Ξ± βα΅’ Ξ²) {f : Ξ² β Ξ³} :
continuous (f β h) β continuous f :=
h.to_homeomorph.comp_continuous_iff'
/-- The group of isometries. -/
instance : group (Ξ± βα΅’ Ξ±) :=
{ one := isometry_equiv.refl _,
mul := Ξ» eβ eβ, eβ.trans eβ,
inv := isometry_equiv.symm,
mul_assoc := Ξ» eβ eβ eβ, rfl,
one_mul := Ξ» e, ext $ Ξ» _, rfl,
mul_one := Ξ» e, ext $ Ξ» _, rfl,
mul_left_inv := Ξ» e, ext e.symm_apply_apply }
@[simp] lemma coe_one : β(1 : Ξ± βα΅’ Ξ±) = id := rfl
@[simp] lemma coe_mul (eβ eβ : Ξ± βα΅’ Ξ±) : β(eβ * eβ) = eβ β eβ := rfl
lemma mul_apply (eβ eβ : Ξ± βα΅’ Ξ±) (x : Ξ±) : (eβ * eβ) x = eβ (eβ x) := rfl
@[simp] lemma inv_apply_self (e : Ξ± βα΅’ Ξ±) (x: Ξ±) : eβ»ΒΉ (e x) = x := e.symm_apply_apply x
@[simp] lemma apply_inv_self (e : Ξ± βα΅’ Ξ±) (x: Ξ±) : e (eβ»ΒΉ x) = x := e.apply_symm_apply x
protected lemma complete_space [complete_space Ξ²] (e : Ξ± βα΅’ Ξ²) : complete_space Ξ± :=
complete_space_of_is_complete_univ $ is_complete_of_complete_image e.isometry.uniform_inducing $
by rwa [set.image_univ, isometry_equiv.range_eq_univ, β complete_space_iff_is_complete_univ]
lemma complete_space_iff (e : Ξ± βα΅’ Ξ²) : complete_space Ξ± β complete_space Ξ² :=
by { split; introI H, exacts [e.symm.complete_space, e.complete_space] }
end pseudo_emetric_space
section pseudo_metric_space
variables [pseudo_metric_space Ξ±] [pseudo_metric_space Ξ²] (h : Ξ± βα΅’ Ξ²)
@[simp] lemma diam_image (s : set Ξ±) : metric.diam (h '' s) = metric.diam s :=
h.isometry.diam_image s
@[simp] lemma diam_preimage (s : set Ξ²) : metric.diam (h β»ΒΉ' s) = metric.diam s :=
by rw [β image_symm, diam_image]
lemma diam_univ : metric.diam (univ : set Ξ±) = metric.diam (univ : set Ξ²) :=
congr_arg ennreal.to_real h.ediam_univ
@[simp] lemma preimage_ball (h : Ξ± βα΅’ Ξ²) (x : Ξ²) (r : β) :
h β»ΒΉ' (metric.ball x r) = metric.ball (h.symm x) r :=
by rw [β h.isometry.preimage_ball (h.symm x) r, h.apply_symm_apply]
@[simp] lemma preimage_sphere (h : Ξ± βα΅’ Ξ²) (x : Ξ²) (r : β) :
h β»ΒΉ' (metric.sphere x r) = metric.sphere (h.symm x) r :=
by rw [β h.isometry.preimage_sphere (h.symm x) r, h.apply_symm_apply]
@[simp] lemma preimage_closed_ball (h : Ξ± βα΅’ Ξ²) (x : Ξ²) (r : β) :
h β»ΒΉ' (metric.closed_ball x r) = metric.closed_ball (h.symm x) r :=
by rw [β h.isometry.preimage_closed_ball (h.symm x) r, h.apply_symm_apply]
@[simp] lemma image_ball (h : Ξ± βα΅’ Ξ²) (x : Ξ±) (r : β) :
h '' (metric.ball x r) = metric.ball (h x) r :=
by rw [β h.preimage_symm, h.symm.preimage_ball, symm_symm]
@[simp] lemma image_sphere (h : Ξ± βα΅’ Ξ²) (x : Ξ±) (r : β) :
h '' (metric.sphere x r) = metric.sphere (h x) r :=
by rw [β h.preimage_symm, h.symm.preimage_sphere, symm_symm]
@[simp] lemma image_closed_ball (h : Ξ± βα΅’ Ξ²) (x : Ξ±) (r : β) :
h '' (metric.closed_ball x r) = metric.closed_ball (h x) r :=
by rw [β h.preimage_symm, h.symm.preimage_closed_ball, symm_symm]
end pseudo_metric_space
end isometry_equiv
/-- An isometry induces an isometric isomorphism between the source space and the
range of the isometry. -/
@[simps to_equiv apply { simp_rhs := tt }]
def isometry.isometry_equiv_on_range [emetric_space Ξ±] [pseudo_emetric_space Ξ²] {f : Ξ± β Ξ²}
(h : isometry f) : Ξ± βα΅’ range f :=
{ isometry_to_fun := Ξ»x y, by simpa [subtype.edist_eq] using h x y,
to_equiv := equiv.of_injective f h.injective }
|
611186ddef4f0eccd6ce5a3751e8ea32456c42c9 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebra/algebra/bilinear.lean | ab8021367987bb9c99292a757e47aaa62d48805d | [
"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 | 5,367 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov
-/
import algebra.algebra.basic
import algebra.hom.iterate
import linear_algebra.tensor_product
/-!
# Facts about algebras involving bilinear maps and tensor products
We move a few basic statements about algebras out of `algebra.algebra.basic`,
in order to avoid importing `linear_algebra.bilinear_map` and
`linear_algebra.tensor_product` unnecessarily.
-/
universes u v w
namespace algebra
open_locale tensor_product
open module
section
variables (R A : Type*) [comm_semiring R] [semiring A] [algebra R A]
/-- The multiplication in an algebra is a bilinear map.
A weaker version of this for semirings exists as `add_monoid_hom.mul`. -/
def lmul : A ββ[R] (End R A) :=
{ map_one' := by { ext a, exact one_mul a },
map_mul' := by { intros a b, ext c, exact mul_assoc a b c },
map_zero' := by { ext a, exact zero_mul a },
commutes' := by { intro r, ext a, dsimp, rw [smul_def] },
.. (show A ββ[R] A ββ[R] A, from linear_map.mkβ R (*)
(Ξ» x y z, add_mul x y z)
(Ξ» c x y, by rw [smul_def, smul_def, mul_assoc _ x y])
(Ξ» x y z, mul_add x y z)
(Ξ» c x y, by rw [smul_def, smul_def, left_comm])) }
variables {R A}
@[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl
variables (R)
/-- The multiplication on the left in an algebra is a linear map. -/
def lmul_left (r : A) : A ββ[R] A :=
lmul R A r
@[simp] lemma lmul_left_to_add_monoid_hom (r : A) :
(lmul_left R r : A β+ A) = add_monoid_hom.mul_left r :=
fun_like.coe_injective rfl
/-- The multiplication on the right in an algebra is a linear map. -/
def lmul_right (r : A) : A ββ[R] A :=
(lmul R A).to_linear_map.flip r
@[simp] lemma lmul_right_to_add_monoid_hom (r : A) :
(lmul_right R r : A β+ A) = add_monoid_hom.mul_right r :=
fun_like.coe_injective rfl
/-- Simultaneous multiplication on the left and right is a linear map. -/
def lmul_left_right (vw: A Γ A) : A ββ[R] A :=
(lmul_right R vw.2).comp (lmul_left R vw.1)
lemma commute_lmul_left_right (a b : A) :
commute (lmul_left R a) (lmul_right R b) :=
by { ext c, exact (mul_assoc a c b).symm, }
/-- The multiplication map on an algebra, as an `R`-linear map from `A β[R] A` to `A`. -/
def lmul' : A β[R] A ββ[R] A :=
tensor_product.lift (lmul R A).to_linear_map
variables {R A}
@[simp] lemma lmul'_apply {x y : A} : lmul' R (x ββ y) = x * y :=
by simp only [algebra.lmul', tensor_product.lift.tmul, alg_hom.to_linear_map_apply, lmul_apply]
@[simp] lemma lmul_left_apply (p q : A) : lmul_left R p q = p * q := rfl
@[simp] lemma lmul_right_apply (p q : A) : lmul_right R p q = q * p := rfl
@[simp] lemma lmul_left_right_apply (vw : A Γ A) (p : A) :
lmul_left_right R vw p = vw.1 * p * vw.2 := rfl
@[simp] lemma lmul_left_one : lmul_left R (1:A) = linear_map.id :=
by { ext, simp only [linear_map.id_coe, one_mul, id.def, lmul_left_apply] }
@[simp] lemma lmul_left_mul (a b : A) :
lmul_left R (a * b) = (lmul_left R a).comp (lmul_left R b) :=
by { ext, simp only [lmul_left_apply, linear_map.comp_apply, mul_assoc] }
@[simp] lemma lmul_right_one : lmul_right R (1:A) = linear_map.id :=
by { ext, simp only [linear_map.id_coe, mul_one, id.def, lmul_right_apply] }
@[simp] lemma lmul_right_mul (a b : A) :
lmul_right R (a * b) = (lmul_right R b).comp (lmul_right R a) :=
by { ext, simp only [lmul_right_apply, linear_map.comp_apply, mul_assoc] }
@[simp] lemma lmul_left_zero_eq_zero :
lmul_left R (0 : A) = 0 :=
(lmul R A).map_zero
@[simp] lemma lmul_right_zero_eq_zero :
lmul_right R (0 : A) = 0 :=
(lmul R A).to_linear_map.flip.map_zero
@[simp] lemma lmul_left_eq_zero_iff (a : A) :
lmul_left R a = 0 β a = 0 :=
begin
split; intros h,
{ rw [β mul_one a, β lmul_left_apply a 1, h, linear_map.zero_apply], },
{ rw h, exact lmul_left_zero_eq_zero, },
end
@[simp] lemma lmul_right_eq_zero_iff (a : A) :
lmul_right R a = 0 β a = 0 :=
begin
split; intros h,
{ rw [β one_mul a, β lmul_right_apply a 1, h, linear_map.zero_apply], },
{ rw h, exact lmul_right_zero_eq_zero, },
end
@[simp] lemma pow_lmul_left (a : A) (n : β) :
(lmul_left R a) ^ n = lmul_left R (a ^ n) :=
((lmul R A).map_pow a n).symm
@[simp] lemma pow_lmul_right (a : A) (n : β) :
(lmul_right R a) ^ n = lmul_right R (a ^ n) :=
linear_map.coe_injective $ ((lmul_right R a).coe_pow n).symm βΈ (mul_right_iterate a n)
end
section
variables {R A : Type*} [comm_semiring R] [ring A] [algebra R A]
lemma lmul_left_injective [no_zero_divisors A] {x : A} (hx : x β 0) :
function.injective (lmul_left R x) :=
by { letI : is_domain A := { exists_pair_ne := β¨x, 0, hxβ©, ..βΉring AβΊ, ..βΉno_zero_divisors AβΊ },
exact mul_right_injectiveβ hx }
lemma lmul_right_injective [no_zero_divisors A] {x : A} (hx : x β 0) :
function.injective (lmul_right R x) :=
by { letI : is_domain A := { exists_pair_ne := β¨x, 0, hxβ©, ..βΉring AβΊ, ..βΉno_zero_divisors AβΊ },
exact mul_left_injectiveβ hx }
lemma lmul_injective [no_zero_divisors A] {x : A} (hx : x β 0) :
function.injective (lmul R A x) :=
by { letI : is_domain A := { exists_pair_ne := β¨x, 0, hxβ©, ..βΉring AβΊ, ..βΉno_zero_divisors AβΊ },
exact mul_right_injectiveβ hx }
end
end algebra
|
ea6cfc7445ed46adbb6bd73398dfdeae81c7104b | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /src/Lean/Meta/Match/Match.lean | e9bd6efbef9e9b792114f5147faecfe54f694c84 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 43,880 | 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.Check
import Lean.Meta.Closure
import Lean.Meta.Tactic.Cases
import Lean.Meta.Tactic.Contradiction
import Lean.Meta.GeneralizeTelescope
import Lean.Meta.Match.Basic
namespace Lean.Meta.Match
/-- The number of patterns in each AltLHS must be equal to the number of discriminants. -/
private def checkNumPatterns (numDiscrs : Nat) (lhss : List AltLHS) : MetaM Unit := do
if lhss.any fun lhs => lhs.patterns.length != numDiscrs then
throwError "incorrect number of patterns"
/--
Execute `k hs` where `hs` contains new equalities `h : lhs[i] = rhs[i]` for each `discrInfos[i] = some h`.
Assume `lhs.size == rhs.size == discrInfos.size`
-/
private partial def withEqs (lhs rhs : Array Expr) (discrInfos : Array DiscrInfo) (k : Array Expr β MetaM Ξ±) : MetaM Ξ± := do
go 0 #[]
where
go (i : Nat) (hs : Array Expr) : MetaM Ξ± := do
if i < lhs.size then
if let some hName := discrInfos[i]!.hName? then
withLocalDeclD hName (β mkEqHEq lhs[i]! rhs[i]!) fun h =>
go (i+1) (hs.push h)
else
go (i+1) hs
else
k hs
/-- Given a list of `AltLHS`, create a minor premise for each one, convert them into `Alt`, and then execute `k` -/
private def withAlts {Ξ±} (motive : Expr) (discrs : Array Expr) (discrInfos : Array DiscrInfo) (lhss : List AltLHS) (k : List Alt β Array (Expr Γ Nat) β MetaM Ξ±) : MetaM Ξ± :=
loop lhss [] #[]
where
mkMinorType (xs : Array Expr) (lhs : AltLHS) : MetaM Expr :=
withExistingLocalDecls lhs.fvarDecls do
let args β lhs.patterns.toArray.mapM (Pattern.toExpr Β· (annotate := true))
let minorType := mkAppN motive args
withEqs discrs args discrInfos fun eqs => do
mkForallFVars (xs ++ eqs) minorType
loop (lhss : List AltLHS) (alts : List Alt) (minors : Array (Expr Γ Nat)) : MetaM Ξ± := do
match lhss with
| [] => k alts.reverse minors
| lhs::lhss =>
let xs := lhs.fvarDecls.toArray.map LocalDecl.toExpr
let minorType β mkMinorType xs lhs
let hasParams := !xs.isEmpty || discrInfos.any fun info => info.hName?.isSome
let (minorType, minorNumParams) := if hasParams then (minorType, xs.size) else (mkSimpleThunkType minorType, 1)
let idx := alts.length
let minorName := (`h).appendIndexAfter (idx+1)
trace[Meta.Match.debug] "minor premise {minorName} : {minorType}"
withLocalDeclD minorName minorType fun minor => do
let rhs := if hasParams then mkAppN minor xs else mkApp minor (mkConst `Unit.unit)
let minors := minors.push (minor, minorNumParams)
let fvarDecls β lhs.fvarDecls.mapM instantiateLocalDeclMVars
let alts := { ref := lhs.ref, idx := idx, rhs := rhs, fvarDecls := fvarDecls, patterns := lhs.patterns, cnstrs := [] } :: alts
loop lhss alts minors
structure State where
used : HashSet Nat := {} -- used alternatives
counterExamples : List (List Example) := []
/-- Return true if the given (sub-)problem has been solved. -/
private def isDone (p : Problem) : Bool :=
p.vars.isEmpty
/-- Return true if the next element on the `p.vars` list is a variable. -/
private def isNextVar (p : Problem) : Bool :=
match p.vars with
| .fvar _ :: _ => true
| _ => false
private def hasAsPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| .as .. :: _ => true
| _ => false
private def hasCtorPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| .ctor .. :: _ => true
| _ => false
private def hasValPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| .val _ :: _ => true
| _ => false
private def hasNatValPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| .val v :: _ => v.isNatLit
| _ => false
private def hasVarPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| .var _ :: _ => true
| _ => false
private def hasArrayLitPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| .arrayLit .. :: _ => true
| _ => false
private def isVariableTransition (p : Problem) : Bool :=
p.alts.all fun alt => match alt.patterns with
| .inaccessible _ :: _ => true
| .var _ :: _ => true
| _ => false
private def isConstructorTransition (p : Problem) : Bool :=
(hasCtorPattern p || p.alts.isEmpty)
&& p.alts.all fun alt => match alt.patterns with
| .ctor .. :: _ => true
| .var _ :: _ => true
| .inaccessible _ :: _ => true
| _ => false
private def isValueTransition (p : Problem) : Bool :=
hasVarPattern p && hasValPattern p
&& p.alts.all fun alt => match alt.patterns with
| .val _ :: _ => true
| .var _ :: _ => true
| _ => false
private def isArrayLitTransition (p : Problem) : Bool :=
hasArrayLitPattern p && hasVarPattern p
&& p.alts.all fun alt => match alt.patterns with
| .arrayLit .. :: _ => true
| .var _ :: _ => true
| _ => false
private def isNatValueTransition (p : Problem) : Bool :=
hasNatValPattern p
&& (!isNextVar p ||
p.alts.any fun alt => match alt.patterns with
| .ctor .. :: _ => true
| .inaccessible _ :: _ => true
| _ => false)
private def processSkipInaccessible (p : Problem) : Problem := Id.run do
let x :: xs := p.vars | unreachable!
let alts := p.alts.map fun alt => Id.run do
let .inaccessible e :: ps := alt.patterns | unreachable!
{ alt with patterns := ps, cnstrs := (x, e) :: alt.cnstrs }
{ p with alts := alts, vars := xs }
/--
If contraint is of the form `e β x` where `x` is a free variable, reorient it
as `x β e` If
- `x` is an `alt`-local declaration
- `e` is not a free variable.
-/
private def reorientCnstrs (alt : Alt) : Alt :=
let cnstrs := alt.cnstrs.map fun (lhs, rhs) =>
if rhs.isFVar && alt.isLocalDecl rhs.fvarId! then
(rhs, lhs)
else if !lhs.isFVar && rhs.isFVar then
(rhs, lhs)
else
(lhs, rhs)
{ alt with cnstrs }
/--
Remove constraints of the form `lhs β rhs` where `lhs` and `rhs` are definitionally equal,
or `lhs` is a free variable.
-/
private def filterTrivialCnstrs (alt : Alt) : MetaM Alt := do
let cnstrs β withExistingLocalDecls alt.fvarDecls do
alt.cnstrs.filterM fun (lhs, rhs) => do
if (β isDefEqGuarded lhs rhs) then
return false
else if lhs.isFVar then
return false
else
return true
return { alt with cnstrs }
/--
Find an alternative constraint of the form `x β e` where `x` is an alternative
local declarations, and `x` and `e` have definitionally equal types.
Then, replace `x` with `e` in the alternative, and return it.
Return `none` if the alternative does not contain a constraint of this form.
-/
private def solveSomeLocalFVarIdCnstr? (alt : Alt) : MetaM (Option Alt) :=
withExistingLocalDecls alt.fvarDecls do
let (some (fvarId, val), cnstrs) β go alt.cnstrs | return none
trace[Meta.Match.match] "found cnstr to solve {mkFVar fvarId} β¦ {val}"
return some <| { alt with cnstrs }.replaceFVarId fvarId val
where
go (cnstrs : List (Expr Γ Expr)) := do
match cnstrs with
| [] => return (none, [])
| (lhs, rhs) :: cnstrs =>
if lhs.isFVar && alt.isLocalDecl lhs.fvarId! then
if !(β dependsOn rhs lhs.fvarId!) && (β isDefEqGuarded (β inferType lhs) (β inferType rhs)) then
return (some (lhs.fvarId!, rhs), cnstrs)
let (p, cnstrs) β go cnstrs
return (p, (lhs, rhs) :: cnstrs)
/--
Solve pending alternative constraints. If all constraints can be solved perform assignment
`mvarId := alt.rhs`, and return true.
-/
private partial def solveCnstrs (mvarId : MVarId) (alt : Alt) : StateRefT State MetaM Bool := do
go (reorientCnstrs alt)
where
go (alt : Alt) : StateRefT State MetaM Bool := do
match (β solveSomeLocalFVarIdCnstr? alt) with
| some alt => go alt
| none =>
let alt β filterTrivialCnstrs alt
if alt.cnstrs.isEmpty then
let eType β inferType alt.rhs
let targetType β mvarId.getType
unless (β isDefEqGuarded targetType eType) do
trace[Meta.Match.match] "assignGoalOf failed {eType} =?= {targetType}"
throwError "dependent elimination failed, type mismatch when solving alternative with type{indentExpr eType}\nbut expected{indentExpr targetType}"
mvarId.assign alt.rhs
modify fun s => { s with used := s.used.insert alt.idx }
return true
else
trace[Meta.Match.match] "alt has unsolved cnstrs:\n{β alt.toMessageData}"
return false
/--
Try to solve the problem by using the first alternative whose pending constraints can be resolved.
-/
private def processLeaf (p : Problem) : StateRefT State MetaM Unit :=
p.mvarId.withContext do
withPPForTacticGoal do trace[Meta.Match.match] "local context at processLeaf:\n{(β mkFreshTypeMVar).mvarId!}"
go p.alts
where
go (alts : List Alt) : StateRefT State MetaM Unit := do
match alts with
| [] =>
/- TODO: allow users to configure which tactic is used to close leaves. -/
unless (β p.mvarId.contradictionCore {}) do
trace[Meta.Match.match] "missing alternative"
p.mvarId.admit
modify fun s => { s with counterExamples := p.examples :: s.counterExamples }
| alt :: alts =>
unless (β solveCnstrs p.mvarId alt) do
go alts
private def processAsPattern (p : Problem) : MetaM Problem := withGoalOf p do
let x :: _ := p.vars | unreachable!
let alts β p.alts.mapM fun alt => do
match alt.patterns with
| .as fvarId p h :: ps =>
/- We used to use `checkAndReplaceFVarId` here, but `x` and `fvarId` may have different types
when dependent types are beind used. Let's consider the repro for issue #471
```
inductive vec : Nat β Type
| nil : vec 0
| cons : Int β vec n β vec n.succ
def vec_len : vec n β Nat
| vec.nil => 0
| x@(vec.cons h t) => vec_len t + 1
```
we reach the state
```
[Meta.Match.match] remaining variables: [xβ:(vec nβ)]
alternatives:
[n:(Nat), x:(vec (Nat.succ n)), h:(Int), t:(vec n)] |- [x@(vec.cons n h t)] => h_1 n x h t
[xβ:(vec nβ)] |- [xβ] => h_2 nβ xβ
```
The variables `xβ:(vec nβ)` and `x:(vec (Nat.succ n))` have different types, but we perform the substitution anyway,
because we claim the "discrepancy" will be corrected after we process the pattern `(vec.cons n h t)`.
The right-hand-side is temporarily type incorrect, but we claim this is fine because it will be type correct again after
we the pattern `(vec.cons n h t)`. TODO: try to find a cleaner solution.
-/
let r β mkEqRefl x
return { alt with patterns := p :: ps }.replaceFVarId fvarId x |>.replaceFVarId h r
| _ => return alt
return { p with alts := alts }
private def processVariable (p : Problem) : MetaM Problem := withGoalOf p do
let x :: xs := p.vars | unreachable!
let alts β p.alts.mapM fun alt => do
match alt.patterns with
| .inaccessible e :: ps => return { alt with patterns := ps, cnstrs := (x, e) :: alt.cnstrs }
| .var fvarId :: ps =>
withExistingLocalDecls alt.fvarDecls do
if (β isDefEqGuarded (β fvarId.getType) (β inferType x)) then
return { alt with patterns := ps }.replaceFVarId fvarId x
else
return { alt with patterns := ps, cnstrs := (mkFVar fvarId, x) :: alt.cnstrs }
| _ => unreachable!
return { p with alts := alts, vars := xs }
/-!
Note that we decided to store pending constraints to address issues exposed by #1279 and #1361.
Here is a simplified version of the example on this issue (see test: `1279_simplified.lean`)
```lean
inductive Arrow : Type β Type β Type 1
| id : Arrow a a
| unit : Arrow Unit Unit
| comp : Arrow Ξ² Ξ³ β Arrow Ξ± Ξ² β Arrow Ξ± Ξ³
deriving Repr
def Arrow.compose (f : Arrow Ξ² Ξ³) (g : Arrow Ξ± Ξ²) : Arrow Ξ± Ξ³ :=
match f, g with
| id, g => g
| f, id => f
| f, g => comp f g
```
The initial state for the `match`-expression above is
```lean
[Meta.Match.match] remaining variables: [Ξ²β:(Type), Ξ³β:(Type), fβ:(Arrow Ξ²β Ξ³β), gβ:(Arrow Ξ± Ξ²β)]
alternatives:
[Ξ²:(Type), g:(Arrow Ξ± Ξ²)] |- [Ξ², .(Ξ²), (Arrow.id .(Ξ²)), g] => h_1 Ξ² g
[Ξ³:(Type), f:(Arrow Ξ± Ξ³)] |- [.(Ξ±), Ξ³, f, (Arrow.id .(Ξ±))] => h_2 Ξ³ f
[Ξ²:(Type), Ξ³:(Type), f:(Arrow Ξ² Ξ³), g:(Arrow Ξ± Ξ²)] |- [Ξ², Ξ³, f, g] => h_3 Ξ² Ξ³ f g
```
The first step is a variable-transition which replaces `Ξ²` with `Ξ²β` in the first and third alternatives.
The constraint `Ξ²β β Ξ±` in the second alternative used to be discarded. We now store it at the
alternative `cnstrs` field.
-/
private def inLocalDecls (localDecls : List LocalDecl) (fvarId : FVarId) : Bool :=
localDecls.any fun d => d.fvarId == fvarId
private def expandVarIntoCtor? (alt : Alt) (fvarId : FVarId) (ctorName : Name) : MetaM (Option Alt) :=
withExistingLocalDecls alt.fvarDecls do
trace[Meta.Match.unify] "expandVarIntoCtor? fvarId: {mkFVar fvarId}, ctorName: {ctorName}, alt:\n{β alt.toMessageData}"
let expectedType β inferType (mkFVar fvarId)
let expectedType β whnfD expectedType
let (ctorLevels, ctorParams) β getInductiveUniverseAndParams expectedType
let ctor := mkAppN (mkConst ctorName ctorLevels) ctorParams
let ctorType β inferType ctor
forallTelescopeReducing ctorType fun ctorFields resultType => do
let ctor := mkAppN ctor ctorFields
let alt := alt.replaceFVarId fvarId ctor
let ctorFieldDecls β ctorFields.mapM fun ctorField => ctorField.fvarId!.getDecl
let newAltDecls := ctorFieldDecls.toList ++ alt.fvarDecls
let mut cnstrs := alt.cnstrs
unless (β isDefEqGuarded resultType expectedType) do
cnstrs := (resultType, expectedType) :: cnstrs
trace[Meta.Match.unify] "expandVarIntoCtor? {mkFVar fvarId} : {expectedType}, ctor: {ctor}"
let ctorFieldPatterns := ctorFieldDecls.toList.map fun decl => Pattern.var decl.fvarId
return some { alt with fvarDecls := newAltDecls, patterns := ctorFieldPatterns ++ alt.patterns, cnstrs }
private def getInductiveVal? (x : Expr) : MetaM (Option InductiveVal) := do
let xType β inferType x
let xType β whnfD xType
match xType.getAppFn with
| Expr.const constName _ =>
let cinfo β getConstInfo constName
match cinfo with
| ConstantInfo.inductInfo val => return some val
| _ => return none
| _ => return none
private def hasRecursiveType (x : Expr) : MetaM Bool := do
match (β getInductiveVal? x) with
| some val => return val.isRec
| _ => return false
/-- Given `alt` s.t. the next pattern is an inaccessible pattern `e`,
try to normalize `e` into a constructor application.
If it is not a constructor, throw an error.
Otherwise, if it is a constructor application of `ctorName`,
update the next patterns with the fields of the constructor.
Otherwise, return none. -/
def processInaccessibleAsCtor (alt : Alt) (ctorName : Name) : MetaM (Option Alt) := do
let env β getEnv
match alt.patterns with
| p@(.inaccessible e) :: ps =>
trace[Meta.Match.match] "inaccessible in ctor step {e}"
withExistingLocalDecls alt.fvarDecls do
-- Try to push inaccessible annotations.
let e β whnfD e
match e.constructorApp? env with
| some (ctorVal, ctorArgs) =>
if ctorVal.name == ctorName then
let fields := ctorArgs.extract ctorVal.numParams ctorArgs.size
let fields := fields.toList.map .inaccessible
return some { alt with patterns := fields ++ ps }
else
return none
| _ => throwErrorAt alt.ref "dependent match elimination failed, inaccessible pattern found{indentD p.toMessageData}\nconstructor expected"
| _ => unreachable!
private def hasNonTrivialExample (p : Problem) : Bool :=
p.examples.any fun | Example.underscore => false | _ => true
private def throwCasesException (p : Problem) (ex : Exception) : MetaM Ξ± := do
match ex with
| .error ref msg =>
let exampleMsg :=
if hasNonTrivialExample p then m!" after processing{indentD <| examplesToMessageData p.examples}" else ""
throw <| Exception.error ref <| m!"{msg}{exampleMsg}\n" ++
"the dependent pattern matcher can solve the following kinds of equations\n" ++
"- <var> = <term> and <term> = <var>\n" ++
"- <term> = <term> where the terms are definitionally equal\n" ++
"- <constructor> = <constructor>, examples: List.cons x xs = List.cons y ys, and List.cons x xs = List.nil"
| _ => throw ex
private def processConstructor (p : Problem) : MetaM (Array Problem) := do
trace[Meta.Match.match] "constructor step"
let x :: xs := p.vars | unreachable!
let subgoals? β commitWhenSome? do
let subgoals β
try
p.mvarId.cases x.fvarId!
catch ex =>
if p.alts.isEmpty then
/- If we have no alternatives and dependent pattern matching fails, then a "missing cases" error is bettern than a "stuck" error message. -/
return none
else
throwCasesException p ex
if subgoals.isEmpty then
/- Easy case: we have solved problem `p` since there are no subgoals -/
return some #[]
else if !p.alts.isEmpty then
return some subgoals
else do
let isRec β withGoalOf p <| hasRecursiveType x
/- If there are no alternatives and the type of the current variable is recursive, we do NOT consider
a constructor-transition to avoid nontermination.
TODO: implement a more general approach if this is not sufficient in practice -/
if isRec then
return none
else
return some subgoals
let some subgoals := subgoals? | return #[{ p with vars := xs }]
subgoals.mapM fun subgoal => subgoal.mvarId.withContext do
let subst := subgoal.subst
let fields := subgoal.fields.toList
let newVars := fields ++ xs
let newVars := newVars.map fun x => x.applyFVarSubst subst
let subex := Example.ctor subgoal.ctorName <| fields.map fun field => match field with
| .fvar fvarId => Example.var fvarId
| _ => Example.underscore -- This case can happen due to dependent elimination
let examples := p.examples.map <| Example.replaceFVarId x.fvarId! subex
let examples := examples.map <| Example.applyFVarSubst subst
let newAlts := p.alts.filter fun alt => match alt.patterns with
| .ctor n .. :: _ => n == subgoal.ctorName
| .var _ :: _ => true
| .inaccessible _ :: _ => true
| _ => false
let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst
let newAlts β newAlts.filterMapM fun alt => do
match alt.patterns with
| .ctor _ _ _ fields :: ps => return some { alt with patterns := fields ++ ps }
| .var fvarId :: ps => expandVarIntoCtor? { alt with patterns := ps } fvarId subgoal.ctorName
| .inaccessible _ :: _ => processInaccessibleAsCtor alt subgoal.ctorName
| _ => unreachable!
return { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples }
private def altsAreCtorLike (p : Problem) : MetaM Bool := withGoalOf p do
p.alts.allM fun alt => do match alt.patterns with
| .ctor .. :: _ => return true
| .inaccessible e :: _ => return (β whnfD e).isConstructorApp (β getEnv)
| _ => return false
private def processNonVariable (p : Problem) : MetaM Problem := withGoalOf p do
let x :: xs := p.vars | unreachable!
if let some (ctorVal, xArgs) := (β whnfD x).constructorApp? (β getEnv) then
if (β altsAreCtorLike p) then
let alts β p.alts.filterMapM fun alt => do
match alt.patterns with
| .ctor ctorName _ _ fields :: ps =>
if ctorName != ctorVal.name then
return none
else
return some { alt with patterns := fields ++ ps }
| .inaccessible _ :: _ => processInaccessibleAsCtor alt ctorVal.name
| _ => unreachable!
let xFields := xArgs.extract ctorVal.numParams xArgs.size
return { p with alts := alts, vars := xFields.toList ++ xs }
let alts β p.alts.mapM fun alt => do
match alt.patterns with
| p :: ps => return { alt with patterns := ps, cnstrs := (x, β p.toExpr) :: alt.cnstrs }
| _ => unreachable!
return { p with alts := alts, vars := xs }
private def collectValues (p : Problem) : Array Expr :=
p.alts.foldl (init := #[]) fun values alt =>
match alt.patterns with
| .val v :: _ => if values.contains v then values else values.push v
| _ => values
private def isFirstPatternVar (alt : Alt) : Bool :=
match alt.patterns with
| .var _ :: _ => true
| _ => false
private def processValue (p : Problem) : MetaM (Array Problem) := do
trace[Meta.Match.match] "value step"
let x :: xs := p.vars | unreachable!
let values := collectValues p
let subgoals β caseValues p.mvarId x.fvarId! values (substNewEqs := true)
subgoals.mapIdxM fun i subgoal => do
trace[Meta.Match.match] "processValue subgoal\n{MessageData.ofGoal subgoal.mvarId}"
if h : i.val < values.size then
let value := values.get β¨i, hβ©
-- (x = value) branch
let subst := subgoal.subst
trace[Meta.Match.match] "processValue subst: {subst.map.toList.map fun p => mkFVar p.1}, {subst.map.toList.map fun p => p.2}"
let examples := p.examples.map <| Example.replaceFVarId x.fvarId! (Example.val value)
let examples := examples.map <| Example.applyFVarSubst subst
let newAlts := p.alts.filter fun alt => match alt.patterns with
| .val v :: _ => v == value
| .var _ :: _ => true
| _ => false
let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst
let newAlts := newAlts.map fun alt => match alt.patterns with
| .val _ :: ps => { alt with patterns := ps }
| .var fvarId :: ps =>
let alt := { alt with patterns := ps }
alt.replaceFVarId fvarId value
| _ => unreachable!
let newVars := xs.map fun x => x.applyFVarSubst subst
return { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples }
else
-- else branch for value
let newAlts := p.alts.filter isFirstPatternVar
return { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs }
private def collectArraySizes (p : Problem) : Array Nat :=
p.alts.foldl (init := #[]) fun sizes alt =>
match alt.patterns with
| .arrayLit _ ps :: _ => let sz := ps.length; if sizes.contains sz then sizes else sizes.push sz
| _ => sizes
private def expandVarIntoArrayLit (alt : Alt) (fvarId : FVarId) (arrayElemType : Expr) (arraySize : Nat) : MetaM Alt :=
withExistingLocalDecls alt.fvarDecls do
let fvarDecl β fvarId.getDecl
let varNamePrefix := fvarDecl.userName
let rec loop (n : Nat) (newVars : Array Expr) := do
match n with
| n+1 =>
withLocalDeclD (varNamePrefix.appendIndexAfter (n+1)) arrayElemType fun x =>
loop n (newVars.push x)
| 0 =>
let arrayLit β mkArrayLit arrayElemType newVars.toList
let alt := alt.replaceFVarId fvarId arrayLit
let newDecls β newVars.toList.mapM fun newVar => newVar.fvarId!.getDecl
let newPatterns := newVars.toList.map fun newVar => .var newVar.fvarId!
return { alt with fvarDecls := newDecls ++ alt.fvarDecls, patterns := newPatterns ++ alt.patterns }
loop arraySize #[]
private def processArrayLit (p : Problem) : MetaM (Array Problem) := do
trace[Meta.Match.match] "array literal step"
let x :: xs := p.vars | unreachable!
let sizes := collectArraySizes p
let subgoals β caseArraySizes p.mvarId x.fvarId! sizes
subgoals.mapIdxM fun i subgoal => do
if i.val < sizes.size then
let size := sizes.get! i
let subst := subgoal.subst
let elems := subgoal.elems.toList
let newVars := elems.map mkFVar ++ xs
let newVars := newVars.map fun x => x.applyFVarSubst subst
let subex := Example.arrayLit <| elems.map Example.var
let examples := p.examples.map <| Example.replaceFVarId x.fvarId! subex
let examples := examples.map <| Example.applyFVarSubst subst
let newAlts := p.alts.filter fun alt => match alt.patterns with
| .arrayLit _ ps :: _ => ps.length == size
| .var _ :: _ => true
| _ => false
let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst
let newAlts β newAlts.mapM fun alt => do
match alt.patterns with
| .arrayLit _ pats :: ps => return { alt with patterns := pats ++ ps }
| .var fvarId :: ps =>
let Ξ± β getArrayArgType <| subst.apply x
expandVarIntoArrayLit { alt with patterns := ps } fvarId Ξ± size
| _ => unreachable!
return { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples }
else
-- else branch
let newAlts := p.alts.filter isFirstPatternVar
return { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs }
private def expandNatValuePattern (p : Problem) : Problem :=
let alts := p.alts.map fun alt => match alt.patterns with
| .val (.lit (.natVal 0)) :: ps => { alt with patterns := .ctor ``Nat.zero [] [] [] :: ps }
| .val (.lit (.natVal (n+1))) :: ps => { alt with patterns := .ctor ``Nat.succ [] [] [.val (mkRawNatLit n)] :: ps }
| _ => alt
{ p with alts := alts }
private def traceStep (msg : String) : StateRefT State MetaM Unit := do
trace[Meta.Match.match] "{msg} step"
private def traceState (p : Problem) : MetaM Unit :=
withGoalOf p (traceM `Meta.Match.match p.toMessageData)
private def throwNonSupported (p : Problem) : MetaM Unit :=
withGoalOf p do
let msg β p.toMessageData
throwError "failed to compile pattern matching, stuck at{indentD msg}"
def isCurrVarInductive (p : Problem) : MetaM Bool := do
match p.vars with
| [] => return false
| x::_ => withGoalOf p do
let val? β getInductiveVal? x
return val?.isSome
private def checkNextPatternTypes (p : Problem) : MetaM Unit := do
match p.vars with
| [] => return ()
| x::_ => withGoalOf p do
for alt in p.alts do
withRef alt.ref do
match alt.patterns with
| [] => return ()
| p::_ =>
let e β p.toExpr
let xType β inferType x
let eType β inferType e
unless (β isDefEq xType eType) do
throwError "pattern{indentExpr e}\n{β mkHasTypeButIsExpectedMsg eType xType}"
private partial def process (p : Problem) : StateRefT State MetaM Unit := do
traceState p
let isInductive β isCurrVarInductive p
if isDone p then
traceStep ("leaf")
processLeaf p
else if hasAsPattern p then
traceStep ("as-pattern")
let p β processAsPattern p
process p
else if isNatValueTransition p then
traceStep ("nat value to constructor")
process (expandNatValuePattern p)
else if !isNextVar p then
traceStep ("non variable")
let p β processNonVariable p
process p
else if isInductive && isConstructorTransition p then
let ps β processConstructor p
ps.forM process
else if isVariableTransition p then
traceStep ("variable")
let p β processVariable p
process p
else if isValueTransition p then
let ps β processValue p
ps.forM process
else if isArrayLitTransition p then
let ps β processArrayLit p
ps.forM process
else if hasNatValPattern p then
-- This branch is reachable when `p`, for example, is just values without an else-alternative.
-- We added it just to get better error messages.
traceStep ("nat value to constructor")
process (expandNatValuePattern p)
else
checkNextPatternTypes p
throwNonSupported p
private def getUElimPos? (matcherLevels : List Level) (uElim : Level) : MetaM (Option Nat) :=
if uElim == levelZero then
return none
else match matcherLevels.toArray.indexOf? uElim with
| none => throwError "dependent match elimination failed, universe level not found"
| some pos => return some pos.val
/- See comment at `mkMatcher` before `mkAuxDefinition` -/
register_builtin_option bootstrap.genMatcherCode : Bool := {
defValue := true
group := "bootstrap"
descr := "disable code generation for auxiliary matcher function"
}
builtin_initialize matcherExt : EnvExtension (PHashMap (Expr Γ Bool) Name) β registerEnvExtension (pure {})
/-- Similar to `mkAuxDefinition`, but uses the cache `matcherExt`.
It also returns an Boolean that indicates whether a new matcher function was added to the environment or not. -/
def mkMatcherAuxDefinition (name : Name) (type : Expr) (value : Expr) : MetaM (Expr Γ Option (MatcherInfo β MetaM Unit)) := do
trace[Meta.Match.debug] "{name} : {type} := {value}"
let compile := bootstrap.genMatcherCode.get (β getOptions)
let result β Closure.mkValueTypeClosure type value (zeta := false)
let env β getEnv
let mkMatcherConst name :=
mkAppN (mkConst name result.levelArgs.toList) result.exprArgs
match (matcherExt.getState env).find? (result.value, compile) with
| some nameNew => return (mkMatcherConst nameNew, none)
| none =>
let decl := Declaration.defnDecl {
name
levelParams := result.levelParams.toList
type := result.type
value := result.value
hints := ReducibilityHints.abbrev
safety := if env.hasUnsafe result.type || env.hasUnsafe result.value then DefinitionSafety.unsafe else DefinitionSafety.safe
}
trace[Meta.Match.debug] "{name} : {result.type} := {result.value}"
let addMatcher : MatcherInfo β MetaM Unit := fun mi => do
addDecl decl
modifyEnv fun env => matcherExt.modifyState env fun s => s.insert (result.value, compile) name
addMatcherInfo name mi
setInlineAttribute name
if compile then
compileDecl decl
return (mkMatcherConst name, some addMatcher)
structure MkMatcherInput where
matcherName : Name
matchType : Expr
discrInfos : Array DiscrInfo
lhss : List AltLHS
def MkMatcherInput.numDiscrs (m : MkMatcherInput) :=
m.discrInfos.size
def MkMatcherInput.collectFVars (m : MkMatcherInput) : StateRefT CollectFVars.State MetaM Unit := do
m.matchType.collectFVars
m.lhss.forM fun alt => alt.collectFVars
def MkMatcherInput.collectDependencies (m : MkMatcherInput) : MetaM FVarIdSet := do
let (_, s) β m.collectFVars |>.run {}
let s β s.addDependencies
return s.fvarSet
/--
Auxiliary method used at `mkMatcher`. It executes `k` in a local context that contains only
the local declarations `m` depends on. This is important because otherwise dependent elimination
may "refine" the types of unnecessary declarations and accidentally introduce unnecessary dependencies
in the auto-generated auxiliary declaration. Note that this is not just an optimization because the
unnecessary dependencies may prevent the termination checker from succeeding. For an example,
see issue #1237.
-/
def withCleanLCtxFor (m : MkMatcherInput) (k : MetaM Ξ±) : MetaM Ξ± := do
let s β m.collectDependencies
let lctx β getLCtx
let lctx := lctx.foldr (init := lctx) fun localDecl lctx =>
if s.contains localDecl.fvarId then lctx else lctx.erase localDecl.fvarId
let localInstances := (β getLocalInstances).filter fun localInst => s.contains localInst.fvar.fvarId!
withLCtx lctx localInstances k
/--
Create a dependent matcher for `matchType` where `matchType` is of the form
`(a_1 : A_1) -> (a_2 : A_2[a_1]) -> ... -> (a_n : A_n[a_1, a_2, ... a_{n-1}]) -> B[a_1, ..., a_n]`
where `n = numDiscrs`, and the `lhss` are the left-hand-sides of the `match`-expression alternatives.
Each `AltLHS` has a list of local declarations and a list of patterns.
The number of patterns must be the same in each `AltLHS`.
The generated matcher has the structure described at `MatcherInfo`. The motive argument is of the form
`(motive : (a_1 : A_1) -> (a_2 : A_2[a_1]) -> ... -> (a_n : A_n[a_1, a_2, ... a_{n-1}]) -> Sort v)`
where `v` is a universe parameter or 0 if `B[a_1, ..., a_n]` is a proposition. -/
def mkMatcher (input : MkMatcherInput) : MetaM MatcherResult := withCleanLCtxFor input do
let β¨matcherName, matchType, discrInfos, lhssβ© := input
let numDiscrs := discrInfos.size
let numEqs := getNumEqsFromDiscrInfos discrInfos
checkNumPatterns numDiscrs lhss
forallBoundedTelescope matchType numDiscrs fun discrs matchTypeBody => do
/- We generate an matcher that can eliminate using different motives with different universe levels.
`uElim` is the universe level the caller wants to eliminate to.
If it is not levelZero, we create a matcher that can eliminate in any universe level.
This is useful for implementing `MatcherApp.addArg` because it may have to change the universe level. -/
let uElim β getLevel matchTypeBody
let uElimGen β if uElim == levelZero then pure levelZero else mkFreshLevelMVar
let mkMatcher (type val : Expr) (minors : Array (Expr Γ Nat)) (s : State) : MetaM MatcherResult := do
trace[Meta.Match.debug] "matcher value: {val}\ntype: {type}"
trace[Meta.Match.debug] "minors num params: {minors.map (Β·.2)}"
/- The option `bootstrap.gen_matcher_code` is a helper hack. It is useful, for example,
for compiling `src/Init/Data/Int`. It is needed because the compiler uses `Int.decLt`
for generating code for `Int.casesOn` applications, but `Int.casesOn` is used to
give the reference implementation for
```
@[extern "lean_int_neg"] def neg (n : @& Int) : Int :=
match n with
| ofNat n => negOfNat n
| negSucc n => succ n
```
which is defined **before** `Int.decLt` -/
let (matcher, addMatcher) β mkMatcherAuxDefinition matcherName type val
trace[Meta.Match.debug] "matcher levels: {matcher.getAppFn.constLevels!}, uElim: {uElimGen}"
let uElimPos? β getUElimPos? matcher.getAppFn.constLevels! uElimGen
discard <| isLevelDefEq uElimGen uElim
let addMatcher :=
match addMatcher with
| some addMatcher => addMatcher <|
{ numParams := matcher.getAppNumArgs
altNumParams := minors.map fun minor => minor.2 + numEqs
discrInfos
numDiscrs
uElimPos?
}
| none => pure ()
trace[Meta.Match.debug] "matcher: {matcher}"
let unusedAltIdxs := lhss.length.fold (init := []) fun i r =>
if s.used.contains i then r else i::r
return {
matcher,
counterExamples := s.counterExamples,
unusedAltIdxs := unusedAltIdxs.reverse,
addMatcher
}
let motiveType β mkForallFVars discrs (mkSort uElimGen)
trace[Meta.Match.debug] "motiveType: {motiveType}"
withLocalDeclD `motive motiveType fun motive => do
if discrInfos.any fun info => info.hName?.isSome then
forallBoundedTelescope matchType numDiscrs fun discrs' _ => do
let (mvarType, isEqMask) β withEqs discrs discrs' discrInfos fun eqs => do
let mvarType β mkForallFVars eqs (mkAppN motive discrs')
let isEqMask β eqs.mapM fun eq => return (β inferType eq).isEq
return (mvarType, isEqMask)
trace[Meta.Match.debug] "target: {mvarType}"
withAlts motive discrs discrInfos lhss fun alts minors => do
let mvar β mkFreshExprMVar mvarType
trace[Meta.Match.debug] "goal\n{mvar.mvarId!}"
let examples := discrs'.toList.map fun discr => Example.var discr.fvarId!
let (_, s) β (process { mvarId := mvar.mvarId!, vars := discrs'.toList, alts := alts, examples := examples }).run {}
let val β mkLambdaFVars discrs' mvar
trace[Meta.Match.debug] "matcher\nvalue: {val}\ntype: {β inferType val}"
let mut rfls := #[]
let mut isEqMaskIdx := 0
for discr in discrs, info in discrInfos do
if info.hName?.isSome then
if isEqMask[isEqMaskIdx]! then
rfls := rfls.push (β mkEqRefl discr)
else
rfls := rfls.push (β mkHEqRefl discr)
isEqMaskIdx := isEqMaskIdx + 1
let val := mkAppN (mkAppN val discrs) rfls
let args := #[motive] ++ discrs ++ minors.map Prod.fst
let val β mkLambdaFVars args val
let type β mkForallFVars args (mkAppN motive discrs)
mkMatcher type val minors s
else
let mvarType := mkAppN motive discrs
trace[Meta.Match.debug] "target: {mvarType}"
withAlts motive discrs discrInfos lhss fun alts minors => do
let mvar β mkFreshExprMVar mvarType
let examples := discrs.toList.map fun discr => Example.var discr.fvarId!
let (_, s) β (process { mvarId := mvar.mvarId!, vars := discrs.toList, alts := alts, examples := examples }).run {}
let args := #[motive] ++ discrs ++ minors.map Prod.fst
let type β mkForallFVars args mvarType
let val β mkLambdaFVars args mvar
mkMatcher type val minors s
def getMkMatcherInputInContext (matcherApp : MatcherApp) : MetaM MkMatcherInput := do
let matcherName := matcherApp.matcherName
let some matcherInfo β getMatcherInfo? matcherName | throwError "not a matcher: {matcherName}"
let matcherConst β getConstInfo matcherName
let matcherType β instantiateForall matcherConst.type <| matcherApp.params ++ #[matcherApp.motive]
let matchType β do
let u :=
if let some idx := matcherInfo.uElimPos?
then mkLevelParam matcherConst.levelParams.toArray[idx]!
else levelZero
forallBoundedTelescope matcherType (some matcherInfo.numDiscrs) fun discrs _ => do
mkForallFVars discrs (mkConst ``PUnit [u])
let matcherType β instantiateForall matcherType matcherApp.discrs
let lhss β forallBoundedTelescope matcherType (some matcherApp.alts.size) fun alts _ =>
alts.mapM fun alt => do
let ty β inferType alt
forallTelescope ty fun xs body => do
let xs β xs.filterM fun x => dependsOn body x.fvarId!
body.withApp fun _ args => do
let ctx β getLCtx
let localDecls := xs.map ctx.getFVar!
let patterns β args.mapM Match.toPattern
return {
ref := Syntax.missing
fvarDecls := localDecls.toList
patterns := patterns.toList : Match.AltLHS }
return { matcherName, matchType, discrInfos := matcherInfo.discrInfos, lhss := lhss.toList }
/-- This function is only used for testing purposes -/
def withMkMatcherInput (matcherName : Name) (k : MkMatcherInput β MetaM Ξ±) : MetaM Ξ± := do
let some matcherInfo β getMatcherInfo? matcherName | throwError "not a matcher: {matcherName}"
let matcherConst β getConstInfo matcherName
forallBoundedTelescope matcherConst.type (some matcherInfo.arity) fun xs _ => do
let matcherApp β mkConstWithLevelParams matcherConst.name
let matcherApp := mkAppN matcherApp xs
let some matcherApp β matchMatcherApp? matcherApp | throwError "not a matcher app: {matcherApp}"
let mkMatcherInput β getMkMatcherInputInContext matcherApp
k mkMatcherInput
end Match
/-- Auxiliary function for MatcherApp.addArg -/
private partial def updateAlts (typeNew : Expr) (altNumParams : Array Nat) (alts : Array Expr) (i : Nat) : MetaM (Array Nat Γ Array Expr) := do
if h : i < alts.size then
let alt := alts.get β¨i, hβ©
let numParams := altNumParams[i]!
let typeNew β whnfD typeNew
match typeNew with
| Expr.forallE _ d b _ =>
let alt β forallBoundedTelescope d (some numParams) fun xs d => do
let alt β try instantiateLambda alt xs catch _ => throwError "unexpected matcher application, insufficient number of parameters in alternative"
forallBoundedTelescope d (some 1) fun x _ => do
let alt β mkLambdaFVars x alt -- x is the new argument we are adding to the alternative
mkLambdaFVars xs alt
updateAlts (b.instantiate1 alt) (altNumParams.set! i (numParams+1)) (alts.set β¨i, hβ© alt) (i+1)
| _ => throwError "unexpected type at MatcherApp.addArg"
else
return (altNumParams, alts)
/-- Given
- matcherApp `match_i As (fun xs => motive[xs]) discrs (fun ys_1 => (alt_1 : motive (C_1[ys_1])) ... (fun ys_n => (alt_n : motive (C_n[ys_n]) remaining`, and
- expression `e : B[discrs]`,
Construct the term
`match_i As (fun xs => B[xs] -> motive[xs]) discrs (fun ys_1 (y : B[C_1[ys_1]]) => alt_1) ... (fun ys_n (y : B[C_n[ys_n]]) => alt_n) e remaining`, and
We use `kabstract` to abstract the discriminants from `B[discrs]`.
This method assumes
- the `matcherApp.motive` is a lambda abstraction where `xs.size == discrs.size`
- each alternative is a lambda abstraction where `ys_i.size == matcherApp.altNumParams[i]`
-/
def MatcherApp.addArg (matcherApp : MatcherApp) (e : Expr) : MetaM MatcherApp :=
lambdaTelescope matcherApp.motive fun motiveArgs motiveBody => do
unless motiveArgs.size == matcherApp.discrs.size do
-- This error can only happen if someone implemented a transformation that rewrites the motive created by `mkMatcher`.
throwError "unexpected matcher application, motive must be lambda expression with #{matcherApp.discrs.size} arguments"
let eType β inferType e
let eTypeAbst β matcherApp.discrs.size.foldRevM (init := eType) fun i eTypeAbst => do
let motiveArg := motiveArgs[i]!
let discr := matcherApp.discrs[i]!
let eTypeAbst β kabstract eTypeAbst discr
return eTypeAbst.instantiate1 motiveArg
let motiveBody β mkArrow eTypeAbst motiveBody
let matcherLevels β match matcherApp.uElimPos? with
| none => pure matcherApp.matcherLevels
| some pos =>
let uElim β getLevel motiveBody
pure <| matcherApp.matcherLevels.set! pos uElim
let motive β mkLambdaFVars motiveArgs motiveBody
-- Construct `aux` `match_i As (fun xs => B[xs] β motive[xs]) discrs`, and infer its type `auxType`.
-- We use `auxType` to infer the type `B[C_i[ys_i]]` of the new argument in each alternative.
let aux := mkAppN (mkConst matcherApp.matcherName matcherLevels.toList) matcherApp.params
let aux := mkApp aux motive
let aux := mkAppN aux matcherApp.discrs
unless (β isTypeCorrect aux) do
throwError "failed to add argument to matcher application, type error when constructing the new motive"
let auxType β inferType aux
let (altNumParams, alts) β updateAlts auxType matcherApp.altNumParams matcherApp.alts 0
return { matcherApp with
matcherLevels := matcherLevels,
motive := motive,
alts := alts,
altNumParams := altNumParams,
remaining := #[e] ++ matcherApp.remaining
}
/-- Similar `MatcherApp.addArg?`, but returns `none` on failure. -/
def MatcherApp.addArg? (matcherApp : MatcherApp) (e : Expr) : MetaM (Option MatcherApp) :=
try
return some (β matcherApp.addArg e)
catch _ =>
return none
builtin_initialize
registerTraceClass `Meta.Match.match
registerTraceClass `Meta.Match.debug
registerTraceClass `Meta.Match.unify
end Lean.Meta
|
5af891bc8eab8daee0cf56fca331a5618430f302 | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /src/Lean/Parser/Tactic.lean | 339eb4d78a66f7a96a1315312491d2e6adb2fc71 | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,235 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Parser.Term
namespace Lean
namespace Parser
namespace Tactic
builtin_initialize
register_parser_alias tacticSeq
@[builtinTacticParser] def Β«unknownΒ» := leading_parser withPosition (ident >> errorAtSavedPos "unknown tactic" true)
@[builtinTacticParser] def nestedTactic := tacticSeqBracketed
/- Auxiliary parser for expanding `match` tactic -/
@[builtinTacticParser] def eraseAuxDiscrs := leading_parser:maxPrec "eraseAuxDiscrs!"
def matchRhs := Term.hole <|> Term.syntheticHole <|> tacticSeq
def matchAlts := Term.matchAlts (rhsParser := matchRhs)
@[builtinTacticParser] def Β«matchΒ» := leading_parser:leadPrec "match " >> optional Term.generalizingParam >> sepBy1 Term.matchDiscr ", " >> Term.optType >> " with " >> matchAlts
@[builtinTacticParser] def introMatch := leading_parser nonReservedSymbol "intro " >> matchAlts
@[builtinTacticParser] def decide := leading_parser nonReservedSymbol "decide"
@[builtinTacticParser] def nativeDecide := leading_parser nonReservedSymbol "nativeDecide"
end Tactic
end Parser
end Lean
|
7b21266b4a69f88c647787495d7113f16c04ef4d | 66a6486e19b71391cc438afee5f081a4257564ec | /algebra/quotient_group.hlean | 575b4797693ef7371aab5057ed6cf26f816fe713 | [
"Apache-2.0"
] | permissive | spiceghello/Spectral | c8ccd1e32d4b6a9132ccee20fcba44b477cd0331 | 20023aa3de27c22ab9f9b4a177f5a1efdec2b19f | refs/heads/master | 1,611,263,374,078 | 1,523,349,717,000 | 1,523,349,717,000 | 92,312,239 | 0 | 0 | null | 1,495,642,470,000 | 1,495,642,470,000 | null | UTF-8 | Lean | false | false | 28,857 | 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, Egbert Rijke, Jeremy Avigad
Constructions with groups
-/
import hit.set_quotient .subgroup ..move_to_lib types.equiv
open eq algebra is_trunc set_quotient relation sigma sigma.ops prod trunc function equiv is_equiv
open property
namespace group
variables {G G' : Group}
(H : property G) [is_subgroup G H]
(N : property G) [is_normal_subgroup G N]
{g g' h h' k : G}
(N' : property G') [is_normal_subgroup G' N']
variables {A B : AbGroup}
/- Quotient Group -/
definition homotopy_of_homomorphism_eq {f g : G βg G'}(p : f = g) : f ~ g :=
Ξ»x : G , ap010 group_fun p x
definition quotient_rel [constructor] (g h : G) : Prop := g * hβ»ΒΉ β N
variable {N}
-- We prove that quotient_rel is an equivalence relation
theorem quotient_rel_refl (g : G) : quotient_rel N g g :=
transport (Ξ»x, N x) !mul.right_invβ»ΒΉ (subgroup_one_mem N)
theorem quotient_rel_symm (r : quotient_rel N g h) : quotient_rel N h g :=
transport (Ξ»x, N x) (!mul_inv β¬ ap (Ξ»x, x * _) !inv_inv)
begin apply subgroup_inv_mem r end
theorem quotient_rel_trans (r : quotient_rel N g h) (s : quotient_rel N h k)
: quotient_rel N g k :=
have H1 : N ((g * hβ»ΒΉ) * (h * kβ»ΒΉ)), from subgroup_mul_mem r s,
have H2 : (g * hβ»ΒΉ) * (h * kβ»ΒΉ) = g * kβ»ΒΉ, from calc
(g * hβ»ΒΉ) * (h * kβ»ΒΉ) = ((g * hβ»ΒΉ) * h) * kβ»ΒΉ : by rewrite [mul.assoc (g * hβ»ΒΉ)]
... = g * kβ»ΒΉ : by rewrite inv_mul_cancel_right,
show N (g * kβ»ΒΉ), by rewrite [-H2]; exact H1
theorem is_equivalence_quotient_rel : is_equivalence (quotient_rel N) :=
is_equivalence.mk quotient_rel_refl
(Ξ»g h, quotient_rel_symm)
(Ξ»g h k, quotient_rel_trans)
-- We prove that quotient_rel respects inverses and multiplication, so
-- it is a congruence relation
theorem quotient_rel_resp_inv (r : quotient_rel N g h) : quotient_rel N gβ»ΒΉ hβ»ΒΉ :=
have H1 : gβ»ΒΉ * (h * gβ»ΒΉ) * g β N, from
is_normal_subgroup' g (quotient_rel_symm r),
have H2 : gβ»ΒΉ * (h * gβ»ΒΉ) * g = gβ»ΒΉ * hβ»ΒΉβ»ΒΉ, from calc
gβ»ΒΉ * (h * gβ»ΒΉ) * g = gβ»ΒΉ * h * gβ»ΒΉ * g : by rewrite -mul.assoc
... = gβ»ΒΉ * h : inv_mul_cancel_right
... = gβ»ΒΉ * hβ»ΒΉβ»ΒΉ : by rewrite algebra.inv_inv,
show gβ»ΒΉ * hβ»ΒΉβ»ΒΉ β N, by rewrite [-H2]; exact H1
theorem quotient_rel_resp_mul (r : quotient_rel N g h) (r' : quotient_rel N g' h')
: quotient_rel N (g * g') (h * h') :=
have H1 : g * ((g' * h'β»ΒΉ) * hβ»ΒΉ) β N, from
normal_subgroup_insert r' r,
have H2 : g * ((g' * h'β»ΒΉ) * hβ»ΒΉ) = (g * g') * (h * h')β»ΒΉ, from calc
g * ((g' * h'β»ΒΉ) * hβ»ΒΉ) = g * (g' * (h'β»ΒΉ * hβ»ΒΉ)) : by rewrite [mul.assoc]
... = (g * g') * (h'β»ΒΉ * hβ»ΒΉ) : mul.assoc
... = (g * g') * (h * h')β»ΒΉ : by rewrite [mul_inv],
show N ((g * g') * (h * h')β»ΒΉ), from transport (Ξ»x, N x) H2 H1
local attribute is_equivalence_quotient_rel [instance]
variable (N)
definition qg : Type := set_quotient (quotient_rel N)
variable {N}
local attribute qg [reducible]
definition quotient_one [constructor] : qg N := class_of one
definition quotient_inv [unfold 3] : qg N β qg N :=
quotient_unary_map has_inv.inv (Ξ»g g' r, quotient_rel_resp_inv r)
definition quotient_mul [unfold 3 4] : qg N β qg N β qg N :=
quotient_binary_map has_mul.mul (Ξ»g g' r h h' r', quotient_rel_resp_mul r r')
section
local notation 1 := quotient_one
local postfix β»ΒΉ := quotient_inv
local infix * := quotient_mul
theorem quotient_mul_assoc (gβ gβ gβ : qg N) : gβ * gβ * gβ = gβ * (gβ * gβ) :=
begin
refine set_quotient.rec_prop _ gβ,
refine set_quotient.rec_prop _ gβ,
refine set_quotient.rec_prop _ gβ,
clear gβ gβ gβ, intro gβ gβ gβ,
exact ap class_of !mul.assoc
end
theorem quotient_one_mul (g : qg N) : 1 * g = g :=
begin
refine set_quotient.rec_prop _ g, clear g, intro g,
exact ap class_of !one_mul
end
theorem quotient_mul_one (g : qg N) : g * 1 = g :=
begin
refine set_quotient.rec_prop _ g, clear g, intro g,
exact ap class_of !mul_one
end
theorem quotient_mul_left_inv (g : qg N) : gβ»ΒΉ * g = 1 :=
begin
refine set_quotient.rec_prop _ g, clear g, intro g,
exact ap class_of !mul.left_inv
end
theorem quotient_mul_comm {G : AbGroup} {N : property G} [is_normal_subgroup G N] (g h : qg N)
: g * h = h * g :=
begin
refine set_quotient.rec_prop _ g, clear g, intro g,
refine set_quotient.rec_prop _ h, clear h, intro h,
apply ap class_of, esimp, apply mul.comm
end
end
variable (N)
definition group_qg [constructor] : group (qg N) :=
group.mk _ quotient_mul quotient_mul_assoc quotient_one quotient_one_mul quotient_mul_one
quotient_inv quotient_mul_left_inv
definition quotient_group [constructor] : Group :=
Group.mk _ (group_qg N)
definition ab_group_qg [constructor] {G : AbGroup} (N : property G) [is_normal_subgroup G N]
: ab_group (qg N) :=
β¦ab_group, group_qg N, mul_comm := quotient_mul_commβ¦
definition quotient_ab_group [constructor] {G : AbGroup} (N : property G) [is_subgroup G N]
: AbGroup :=
AbGroup.mk _ (@ab_group_qg G N (is_normal_subgroup_ab _))
definition qg_map [constructor] : G βg quotient_group N :=
homomorphism.mk class_of (Ξ» g h, idp)
definition ab_qg_map {G : AbGroup} (N : property G) [is_subgroup G N] : G βg quotient_ab_group N :=
@qg_map _ N (is_normal_subgroup_ab _)
definition is_surjective_ab_qg_map {A : AbGroup} (N : property A) [is_subgroup A N] : is_surjective (ab_qg_map N) :=
begin
intro x, induction x,
fapply image.mk,
exact a, reflexivity,
apply is_prop.elimo
end
namespace quotient
notation `β¦`:max a `β§`:0 := qg_map _ a
end quotient
open quotient
variables {N N'}
definition qg_map_eq_one (g : G) (H : N g) : qg_map N g = 1 :=
begin
apply eq_of_rel,
have e : (g * 1β»ΒΉ = g),
from calc
g * 1β»ΒΉ = g * 1 : one_inv
... = g : mul_one,
unfold quotient_rel, rewrite e, exact H
end
definition ab_qg_map_eq_one {K : property A} [is_subgroup A K] (g :A) (H : K g) : ab_qg_map K g = 1 :=
begin
apply eq_of_rel,
have e : (g * 1β»ΒΉ = g),
from calc
g * 1β»ΒΉ = g * 1 : one_inv
... = g : mul_one,
unfold quotient_rel, xrewrite e, exact H
end
--- there should be a smarter way to do this!! Please have a look, Floris.
definition rel_of_qg_map_eq_one (g : G) (H : qg_map N g = 1) : g β N :=
begin
have e : (g * 1β»ΒΉ = g),
from calc
g * 1β»ΒΉ = g * 1 : one_inv
... = g : mul_one,
rewrite (inverse e),
apply rel_of_eq _ H
end
definition rel_of_ab_qg_map_eq_one {K : property A} [is_subgroup A K] (a :A) (H : ab_qg_map K a = 1) : a β K :=
begin
have e : (a * 1β»ΒΉ = a),
from calc
a * 1β»ΒΉ = a * 1 : one_inv
... = a : mul_one,
rewrite (inverse e),
have is_normal_subgroup A K, from is_normal_subgroup_ab _,
apply rel_of_eq (quotient_rel K) H
end
definition quotient_group_elim_fun [unfold 6] (f : G βg G') (H : Ξ β¦gβ¦, N g β f g = 1)
(g : quotient_group N) : G' :=
begin
refine set_quotient.elim f _ g,
intro g h K,
apply eq_of_mul_inv_eq_one,
have e : f (g * hβ»ΒΉ) = f g * (f h)β»ΒΉ,
from calc
f (g * hβ»ΒΉ) = f g * (f hβ»ΒΉ) : to_respect_mul
... = f g * (f h)β»ΒΉ : to_respect_inv,
rewrite (inverse e),
apply H, exact K
end
definition quotient_group_elim [constructor] (f : G βg G') (H : Ξ β¦gβ¦, g β N β f g = 1) : quotient_group N βg G' :=
begin
fapply homomorphism.mk,
-- define function
{ exact quotient_group_elim_fun f H },
{ intro g h, induction g using set_quotient.rec_prop with g,
induction h using set_quotient.rec_prop with h,
krewrite (inverse (to_respect_mul (qg_map N) g h)),
unfold qg_map, esimp, exact to_respect_mul f g h }
end
example {K : property A} [is_subgroup A K] :
quotient_ab_group K = @quotient_group A K (is_normal_subgroup_ab _) := rfl
definition quotient_ab_group_elim [constructor] {K : property A} [is_subgroup A K] (f : A βg B)
(H : Ξ β¦gβ¦, g β K β f g = 1) : quotient_ab_group K βg B :=
@quotient_group_elim A B K (is_normal_subgroup_ab _) f H
definition quotient_group_compute (f : G βg G') (H : Ξ β¦gβ¦, N g β f g = 1) (g : G) :
quotient_group_elim f H (qg_map N g) = f g :=
begin
reflexivity
end
definition gelim_unique (f : G βg G') (H : Ξ β¦gβ¦, g β N β f g = 1) (k : quotient_group N βg G')
: ( k βg qg_map N ~ f ) β k ~ quotient_group_elim f H :=
begin
intro K cg, induction cg using set_quotient.rec_prop with g,
exact K g
end
definition ab_gelim_unique {K : property A} [is_subgroup A K] (f : A βg B) (H : Ξ (a :A), a β K β f a = 1) (k : quotient_ab_group K βg B)
: ( k βg ab_qg_map K ~ f) β k ~ quotient_ab_group_elim f H :=
--@quotient_group_elim A B K (is_normal_subgroup_ab _) f H :=
@gelim_unique _ _ K (is_normal_subgroup_ab _) f H _
definition qg_universal_property (f : G βg G') (H : Ξ β¦gβ¦, N g β f g = 1) :
is_contr (Ξ£(g : quotient_group N βg G'), g β qg_map N ~ f) :=
begin
fapply is_contr.mk,
-- give center of contraction
{ fapply sigma.mk, exact quotient_group_elim f H, exact quotient_group_compute f H },
-- give contraction
{ intro pair, induction pair with g p, fapply sigma_eq,
{esimp, apply homomorphism_eq, symmetry, exact gelim_unique f H g p},
{fapply is_prop.elimo} }
end
definition ab_qg_universal_property {K : property A} [is_subgroup A K] (f : A βg B) (H : Ξ (a :A), K a β f a = 1) :
is_contr ((Ξ£(g : quotient_ab_group K βg B), g βg ab_qg_map K ~ f) ) :=
begin
fapply @qg_universal_property _ _ K (is_normal_subgroup_ab _),
exact H
end
definition quotient_group_functor_contr {K L : property A} [is_subgroup A K] [is_subgroup A L]
(H : Ξ (a : A), K a β L a) :
is_contr ((Ξ£(g : quotient_ab_group K βg quotient_ab_group L), g βg ab_qg_map K ~ ab_qg_map L) ) :=
begin
fapply ab_qg_universal_property,
intro a p,
fapply ab_qg_map_eq_one,
exact H a p
end
definition quotient_group_functor_id {K : property A} [is_subgroup A K] (H : Ξ (a : A), K a β K a) :
center' (@quotient_group_functor_contr _ K K _ _ H) = β¨gid (quotient_ab_group K), Ξ» x, rflβ© :=
begin
note p := @quotient_group_functor_contr _ K K _ _ H,
fapply eq_of_is_contr,
end
section quotient_group_iso_ua
set_option pp.universes true
definition subgroup_rel_eq' {K L : property A} [HK : is_subgroup A K] [HL : is_subgroup A L] (htpy : Ξ (a : A), K a β L a) : K = L :=
begin
induction HK with Rone Rmul Rinv, induction HL with Rone' Rmul' Rinv', esimp at *,
assert q : K = L,
begin
fapply eq_of_homotopy,
intro a,
fapply tua,
exact htpy a,
end,
induction q,
assert q : Rone = Rone',
begin
fapply is_prop.elim,
end,
induction q,
assert q2 : @Rmul = @Rmul',
begin
fapply is_prop.elim,
end,
induction q2,
assert q : @Rinv = @Rinv',
begin
fapply is_prop.elim,
end,
induction q,
reflexivity
end
definition subgroup_rel_eq {K L : property A} [is_subgroup A K] [is_subgroup A L] (K_in_L : Ξ (a : A), a β K β a β L) (L_in_K : Ξ (a : A), a β L β a β K) : K = L :=
begin
have htpy : Ξ (a : A), K a β L a,
begin
intro a,
apply @equiv_of_is_prop (a β K) (a β L) _ _ (K_in_L a) (L_in_K a),
end,
exact subgroup_rel_eq' htpy,
end
definition eq_of_ab_qg_group' {K L : property A} [HK : is_subgroup A K] [HL : is_subgroup A L] (p : K = L) : quotient_ab_group K = quotient_ab_group L :=
begin
revert HK, revert HL, induction p, intros,
have HK = HL, begin apply @is_prop.elim _ _ HK HL end,
rewrite this
end
definition iso_of_eq {B : AbGroup} (p : A = B) : A βg B :=
begin
induction p, fapply isomorphism.mk, exact gid A, fapply adjointify, exact id, intro a, reflexivity, intro a, reflexivity
end
definition iso_of_ab_qg_group' {K L : property A} [is_subgroup A K] [is_subgroup A L] (p : K = L) : quotient_ab_group K βg quotient_ab_group L :=
iso_of_eq (eq_of_ab_qg_group' p)
/-
definition htpy_of_ab_qg_group' {K L : property A} [HK : is_subgroup A K] [HL : is_subgroup A L] (p : K = L) : (iso_of_ab_qg_group' p) βg ab_qg_map K ~ ab_qg_map L :=
begin
revert HK, revert HL, induction p, intros HK HL, unfold iso_of_ab_qg_group', unfold ab_qg_map
-- have HK = HL, begin apply @is_prop.elim _ _ HK HL end,
-- rewrite this
-- induction p, reflexivity
end
-/
definition eq_of_ab_qg_group {K L : property A} [is_subgroup A K] [is_subgroup A L] (K_in_L : Ξ (a : A), K a β L a) (L_in_K : Ξ (a : A), L a β K a) : quotient_ab_group K = quotient_ab_group L :=
eq_of_ab_qg_group' (subgroup_rel_eq K_in_L L_in_K)
definition iso_of_ab_qg_group {K L : property A} [is_subgroup A K] [is_subgroup A L] (K_in_L : Ξ (a : A), K a β L a) (L_in_K : Ξ (a : A), L a β K a) : quotient_ab_group K βg quotient_ab_group L :=
iso_of_eq (eq_of_ab_qg_group K_in_L L_in_K)
/-
definition htpy_of_ab_qg_group {K L : property A} [is_subgroup A K] [is_subgroup A L] (K_in_L : Ξ (a : A), K a β L a) (L_in_K : Ξ (a : A), L a β K a) : iso_of_ab_qg_group K_in_L L_in_K βg ab_qg_map K ~ ab_qg_map L :=
begin
fapply htpy_of_ab_qg_group'
end
-/
end quotient_group_iso_ua
section quotient_group_iso
variables {K L : property A} [is_subgroup A K] [is_subgroup A L] (H1 : Ξ (a : A), K a β L a) (H2 : Ξ (a : A), L a β K a)
include H1
include H2
definition quotient_group_iso_contr_KL_map :
quotient_ab_group K βg quotient_ab_group L :=
pr1 (center' (quotient_group_functor_contr H1))
definition quotient_group_iso_contr_KL_triangle :
quotient_group_iso_contr_KL_map H1 H2 βg ab_qg_map K ~ ab_qg_map L :=
pr2 (center' (quotient_group_functor_contr H1))
definition quotient_group_iso_contr_KK :
is_contr (Ξ£ (g : quotient_ab_group K βg quotient_ab_group K), g βg ab_qg_map K ~ ab_qg_map K) :=
@quotient_group_functor_contr A K K _ _ (Ξ» a, H2 a β H1 a)
definition quotient_group_iso_contr_LK :
quotient_ab_group L βg quotient_ab_group K :=
pr1 (center' (@quotient_group_functor_contr A L K _ _ H2))
definition quotient_group_iso_contr_LL :
quotient_ab_group L βg quotient_ab_group L :=
pr1 (center' (@quotient_group_functor_contr A L L _ _ (Ξ» a, H1 a β H2 a)))
/-
definition quotient_group_iso : quotient_ab_group K βg quotient_ab_group L :=
begin
fapply isomorphism.mk,
exact pr1 (center' (quotient_group_iso_contr_KL H1 H2)),
fapply adjointify,
exact quotient_group_iso_contr_LK H1 H2,
intro x,
induction x, reflexivity,
end
-/
definition quotient_group_iso_contr_aux :
is_contr (Ξ£(gh : Ξ£ (g : quotient_ab_group K βg quotient_ab_group L), g βg ab_qg_map K ~ ab_qg_map L), is_equiv (group_fun (pr1 gh))) :=
begin
fapply is_trunc_sigma,
exact quotient_group_functor_contr H1,
intro a, induction a with g h,
fapply is_contr_of_inhabited_prop,
fapply adjointify,
rexact group_fun (pr1 (center' (@quotient_group_functor_contr A L K _ _ H2))),
note htpy := homotopy_of_eq (ap group_fun (ap sigma.pr1 (@quotient_group_functor_id _ L _ (Ξ» a, (H1 a) β (H2 a))))),
have KK : is_contr ((Ξ£(g' : quotient_ab_group K βg quotient_ab_group K), g' βg ab_qg_map K ~ ab_qg_map K) ), from
quotient_group_functor_contr (Ξ» a, (H2 a) β (H1 a)),
-- have KK_path : β¨g, hβ© = β¨id, Ξ» a, refl (ab_qg_map K a)β©, from eq_of_is_contr β¨g, hβ© β¨id, Ξ» a, refl (ab_qg_map K a)β©,
repeat exact sorry
end
/-
definition quotient_group_iso_contr {K L : property A} [is_subgroup A K] [is_subgroup A L] (H1 : Ξ (a : A), K a β L a) (H2 : Ξ (a : A), L a β K a) :
is_contr (Ξ£ (g : quotient_ab_group K βg quotient_ab_group L), g βg ab_qg_map K ~ ab_qg_map L) :=
begin
refine @is_trunc_equiv_closed (Ξ£(gh : Ξ£ (g : quotient_ab_group K βg quotient_ab_group L), g βg ab_qg_map K ~ ab_qg_map L), is_equiv (group_fun (pr1 gh))) (Ξ£ (g : quotient_ab_group K βg quotient_ab_group L), g βg ab_qg_map K ~ ab_qg_map L) -2 _ (quotient_group_iso_contr_aux H1 H2),
exact calc
(Ξ£ gh, is_equiv (group_fun gh.1)) β Ξ£ (g : quotient_ab_group K βg quotient_ab_group L) (h : g βg ab_qg_map K ~ ab_qg_map L), is_equiv (group_fun g) : by exact (sigma_assoc_equiv (Ξ» gh, is_equiv (group_fun gh.1)))β»ΒΉ
... β (Ξ£ (g : quotient_ab_group K βg quotient_ab_group L), g βg ab_qg_map K ~ ab_qg_map L) : _
end
-/
end quotient_group_iso
definition quotient_group_functor [constructor] (Ο : G βg G') (h : Ξ g, g β N β Ο g β N') :
quotient_group N βg quotient_group N' :=
begin
apply quotient_group_elim (qg_map N' βg Ο),
intro g Ng, esimp,
refine qg_map_eq_one (Ο g) (h g Ng)
end
------------------------------------------------
-- FIRST ISOMORPHISM THEOREM
------------------------------------------------
definition kernel_quotient_extension {A B : AbGroup} (f : A βg B) : quotient_ab_group (kernel f) βg B :=
begin
unfold quotient_ab_group,
fapply @quotient_group_elim A B _ (@is_normal_subgroup_ab _ (kernel f) _) f,
intro a, intro p, exact p
end
definition kernel_quotient_extension_triangle {A B : AbGroup} (f : A βg B) :
kernel_quotient_extension f β ab_qg_map (kernel f) ~ f :=
begin
intro a,
apply @quotient_group_compute _ _ _ (@is_normal_subgroup_ab _ (kernel f) _)
end
definition is_embedding_kernel_quotient_extension {A B : AbGroup} (f : A βg B) :
is_embedding (kernel_quotient_extension f) :=
begin
fapply is_embedding_of_is_mul_hom,
intro x,
note H := is_surjective_ab_qg_map (kernel f) x,
induction H, induction p,
intro q,
apply @qg_map_eq_one _ _ (@is_normal_subgroup_ab _ (kernel f) _),
refine _ β¬ q,
symmetry,
rexact kernel_quotient_extension_triangle f a
end
definition ab_group_quotient_homomorphism (A B : AbGroup)(K : property A)(L : property B) [is_subgroup A K] [is_subgroup B L] (f : A βg B)
(p : Ξ (a:A), a β K β f a β L) : quotient_ab_group K βg quotient_ab_group L :=
begin
fapply @quotient_group_elim,
exact (ab_qg_map L) βg f,
intro a,
intro k,
exact @ab_qg_map_eq_one B L _ (f a) (p a k),
end
definition ab_group_kernel_factor {A B C: AbGroup} (f : A βg B)(g : A βg C){i : C βg B}(H : f = i βg g )
: kernel g β kernel f :=
begin
intro a,
intro p,
exact calc
f a = i (g a) : homotopy_of_eq (ap group_fun H) a
... = i 1 : ap i p
... = 1 : respect_one i
end
definition ab_group_triv_kernel_factor {A B C: AbGroup} (f : A βg B)(g : A βg C){i : C βg B}(H : f = i βg g ) :
kernel f β '{1} β kernel g β '{1} :=
Ξ» p, subproperty.trans (ab_group_kernel_factor f g H) p
definition is_embedding_of_kernel_subproperty_one {A B : AbGroup} (f : A βg B) :
kernel f β '{1} β is_embedding f :=
Ξ» p, is_embedding_of_is_mul_hom _
(take x, assume h : f x = 1,
show x = 1, from eq_of_mem_singleton (p _ h))
definition kernel_subproperty_one {A B : AbGroup} (f : A βg B) :
is_embedding f β kernel f β '{1} :=
Ξ» h x hx,
have x = 1, from eq_one_of_is_mul_hom hx,
show x β '{1}, from mem_singleton_of_eq this
definition ab_group_kernel_equivalent {A B : AbGroup} (C : AbGroup) (f : A βg B)(g : A βg C)(i : C βg B)(H : f = i βg g )(K : is_embedding i)
: Ξ a:A, a β kernel g β a β kernel f :=
exteq_of_subproperty_of_subproperty
(show kernel g β kernel f, from ab_group_kernel_factor f g H)
(show kernel f β kernel g, from
take a,
suppose f a = 1,
have i (g a) = i 1, from calc
i (g a) = f a : (homotopy_of_eq (ap group_fun H) a)β»ΒΉ
... = 1 : this
... = i 1 : (respect_one i)β»ΒΉ,
is_injective_of_is_embedding this)
definition ab_group_kernel_image_lift (A B : AbGroup) (f : A βg B)
: Ξ a : A, a β kernel (image_lift f) β a β kernel f :=
begin
fapply ab_group_kernel_equivalent (ab_Image f) (f) (image_lift(f)) (image_incl(f)),
exact image_factor f,
exact is_embedding_of_is_injective (image_incl_injective(f)),
end
definition ab_group_kernel_quotient_to_image {A B : AbGroup} (f : A βg B)
: quotient_ab_group (kernel f) βg ab_Image (f) :=
begin
fapply quotient_ab_group_elim (image_lift f), intro a, intro p,
apply iff.mpr (ab_group_kernel_image_lift _ _ f a) p
end
definition ab_group_kernel_quotient_to_image_domain_triangle {A B : AbGroup} (f : A βg B)
: ab_group_kernel_quotient_to_image (f) βg ab_qg_map (kernel f) ~ image_lift(f) :=
begin
intros a,
esimp,
end
definition ab_group_kernel_quotient_to_image_codomain_triangle {A B : AbGroup} (f : A βg B)
: image_incl f βg ab_group_kernel_quotient_to_image f ~ kernel_quotient_extension f :=
begin
intro x,
induction x,
reflexivity,
fapply is_prop.elimo
end
definition is_surjective_kernel_quotient_to_image {A B : AbGroup} (f : A βg B)
: is_surjective (ab_group_kernel_quotient_to_image f) :=
begin
fapply is_surjective_factor (group_fun (ab_qg_map (kernel f))),
exact image_lift f,
apply @quotient_group_compute _ _ _ (@is_normal_subgroup_ab _ (kernel f) _),
exact is_surjective_image_lift f
end
definition is_embedding_kernel_quotient_to_image {A B : AbGroup} (f : A βg B)
: is_embedding (ab_group_kernel_quotient_to_image f) :=
begin
fapply is_embedding_factor (ab_group_kernel_quotient_to_image f) (image_incl f) (kernel_quotient_extension f),
exact ab_group_kernel_quotient_to_image_codomain_triangle f,
exact is_embedding_kernel_quotient_extension f
end
definition ab_group_first_iso_thm {A B : AbGroup} (f : A βg B)
: quotient_ab_group (kernel f) βg ab_Image f :=
begin
fapply isomorphism.mk,
exact ab_group_kernel_quotient_to_image f,
fapply is_equiv_of_is_surjective_of_is_embedding,
exact is_embedding_kernel_quotient_to_image f,
exact is_surjective_kernel_quotient_to_image f
end
definition codomain_surjection_is_quotient {A B : AbGroup} (f : A βg B)( H : is_surjective f)
: quotient_ab_group (kernel f) βg B :=
begin
exact (ab_group_first_iso_thm f) β¬g (iso_surjection_ab_image_incl f H)
end
definition codomain_surjection_is_quotient_triangle {A B : AbGroup} (f : A βg B)( H : is_surjective f)
: codomain_surjection_is_quotient (f)(H) βg ab_qg_map (kernel f) ~ f :=
begin
intro a,
esimp
end
-- print iff.mpr
/- set generating normal subgroup -/
section
parameters {Aβ : AbGroup} (S : Aβ β Prop)
variable {Aβ : AbGroup}
inductive generating_relation' : Aβ β Type :=
| rincl : Ξ {g}, S g β generating_relation' g
| rmul : Ξ {g h}, generating_relation' g β generating_relation' h β generating_relation' (g * h)
| rinv : Ξ {g}, generating_relation' g β generating_relation' gβ»ΒΉ
| rone : generating_relation' 1
open generating_relation'
definition generating_relation (g : Aβ) : Prop := β₯ generating_relation' g β₯
local abbreviation R := generating_relation
definition gr_one : R 1 := tr (rone S)
definition gr_inv (g : Aβ) : R g β R gβ»ΒΉ :=
trunc_functor -1 rinv
definition gr_mul (g h : Aβ) : R g β R h β R (g * h) :=
trunc_functor2 rmul
definition normal_generating_relation [instance] : is_subgroup Aβ generating_relation :=
β¦ is_subgroup,
one_mem := gr_one,
inv_mem := gr_inv,
mul_mem := gr_mulβ¦
parameter (Aβ)
definition quotient_ab_group_gen : AbGroup := quotient_ab_group generating_relation
definition gqg_map [constructor] : Aβ βg quotient_ab_group_gen :=
ab_qg_map _
parameter {Aβ}
definition gqg_eq_of_rel {g h : Aβ} (H : S (g * hβ»ΒΉ)) : gqg_map g = gqg_map h :=
eq_of_rel (tr (rincl H))
-- this one might work if the previous one doesn't (maybe make this the default one?)
definition gqg_eq_of_rel' {g h : Aβ} (H : S (g * hβ»ΒΉ)) : class_of g = class_of h :> quotient_ab_group_gen :=
gqg_eq_of_rel H
definition gqg_elim [constructor] (f : Aβ βg Aβ) (H : Ξ β¦gβ¦, S g β f g = 1)
: quotient_ab_group_gen βg Aβ :=
begin
apply quotient_ab_group_elim f,
intro g r, induction r with r,
induction r with g s g h r r' IH1 IH2 g r IH,
{ exact H s },
{ exact !respect_mul β¬ ap011 mul IH1 IH2 β¬ !one_mul },
{ exact !respect_inv β¬ ap inv IH β¬ !one_inv },
{ apply respect_one }
end
definition gqg_elim_compute (f : Aβ βg Aβ) (H : Ξ β¦gβ¦, S g β f g = 1)
: gqg_elim f H β gqg_map ~ f :=
begin
intro g, reflexivity
end
definition gqg_elim_unique (f : Aβ βg Aβ) (H : Ξ β¦gβ¦, S g β f g = 1)
(k : quotient_ab_group_gen βg Aβ) : ( k βg gqg_map ~ f ) β k ~ gqg_elim f H :=
!ab_gelim_unique
end
end group
namespace group
variables {G H K : Group} {R : property G} [is_normal_subgroup G R]
{S : property H} [is_normal_subgroup H S]
{T : property K} [is_normal_subgroup K T]
theorem quotient_group_functor_compose (Ο : H βg K) (Ο : G βg H)
(hΟ : Ξ g, g β S β Ο g β T) (hΟ : Ξ g, g β R β Ο g β S) :
quotient_group_functor Ο hΟ βg quotient_group_functor Ο hΟ ~
quotient_group_functor (Ο βg Ο) (Ξ»g, proof hΟ (Ο g) qed β hΟ g) :=
begin
intro g, induction g using set_quotient.rec_prop with g hg, reflexivity
end
definition quotient_group_functor_gid :
quotient_group_functor (gid G) (Ξ»g, id) ~ gid (quotient_group R) :=
begin
intro g, induction g using set_quotient.rec_prop with g hg, reflexivity
end
definition quotient_group_functor_homotopy {Ο Ο : G βg H} (hΟ : Ξ g, R g β S (Ο g))
(hΟ : Ξ g, g β R β Ο g β S) (p : Ο ~ Ο) :
quotient_group_functor Ο hΟ ~ quotient_group_functor Ο hΟ :=
begin
intro g, induction g using set_quotient.rec_prop with g hg,
exact ap set_quotient.class_of (p g)
end
end group
namespace group
variables {G H K : AbGroup} {R : property G} [is_subgroup G R]
{S : property H} [is_subgroup H S]
{T : property K} [is_subgroup K T]
definition quotient_ab_group_functor [constructor] (Ο : G βg H)
(h : Ξ g, g β R β Ο g β S) : quotient_ab_group R βg quotient_ab_group S :=
@quotient_group_functor G H R (is_normal_subgroup_ab _) S (is_normal_subgroup_ab _) Ο h
definition quotient_ab_group_functor_mul
(Ο Ο : G βg H) (hΟ : Ξ g, g β R β Ο g β S) (hΟ : Ξ g, g β R β Ο g β S) :
homomorphism_mul (quotient_ab_group_functor Ο hΟ) (quotient_ab_group_functor Ο hΟ) ~
quotient_ab_group_functor (homomorphism_mul Ο Ο)
(Ξ»g hg, is_subgroup.mul_mem (hΟ g hg) (hΟ g hg)) :=
begin
intro g, induction g using set_quotient.rec_prop with g hg, reflexivity
end
theorem quotient_ab_group_functor_compose (Ο : H βg K) (Ο : G βg H)
(hΟ : Ξ g, g β S β Ο g β T) (hΟ : Ξ g, g β R β Ο g β S) :
quotient_ab_group_functor Ο hΟ βg quotient_ab_group_functor Ο hΟ ~
quotient_ab_group_functor (Ο βg Ο) (Ξ»g, proof hΟ (Ο g) qed β hΟ g) :=
@quotient_group_functor_compose G H K R _ S _ T _ Ο Ο hΟ hΟ
definition quotient_ab_group_functor_gid :
quotient_ab_group_functor (gid G) (Ξ»g, id) ~ gid (quotient_ab_group R) :=
@quotient_group_functor_gid G R _
definition quotient_ab_group_functor_homotopy {Ο Ο : G βg H} (hΟ : Ξ g, R g β S (Ο g))
(hΟ : Ξ g, g β R β Ο g β S) (p : Ο ~ Ο) :
quotient_ab_group_functor Ο hΟ ~ quotient_ab_group_functor Ο hΟ :=
@quotient_group_functor_homotopy G H R _ S _ Ο Ο hΟ hΟ p
end group
|
55be21c78fc8e5cbdff8e33d360b140be60551b4 | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/analysis/hofer.lean | ee80f85a31ce1277c5ec931ae0a158eff2857d7c | [
"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 | 4,585 | lean | /-
Copyright (c) 2020 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
-/
import analysis.specific_limits
/-!
# Hofer's lemma
This is an elementary lemma about complete metric spaces. It is motivated by an
application to the bubbling-off analysis for holomorphic curves in symplectic topology.
We are *very* far away from having these applications, but the proof here is a nice
example of a proof needing to construct a sequence by induction in the middle of the proof.
## References:
* H. Hofer and C. Viterbo, *The Weinstein conjecture in the presence of holomorphic spheres*
-/
open_locale classical topological_space big_operators
open filter finset
local notation `d` := dist
lemma hofer {X: Type*} [metric_space X] [complete_space X]
(x : X) (Ξ΅ : β) (Ξ΅_pos : 0 < Ξ΅)
{Ο : X β β} (cont : continuous Ο) (nonneg : β y, 0 β€ Ο y) :
β (Ξ΅' > 0) (x' : X), Ξ΅' β€ Ξ΅ β§
d x' x β€ 2*Ξ΅ β§
Ξ΅ * Ο(x) β€ Ξ΅' * Ο x' β§
β y, d x' y β€ Ξ΅' β Ο y β€ 2*Ο x' :=
begin
by_contradiction H,
have reformulation : β x' (k : β), Ξ΅ * Ο x β€ Ξ΅ / 2 ^ k * Ο x' β 2^k * Ο x β€ Ο x',
{ intros x' k,
rw [div_mul_eq_mul_div, le_div_iff, mul_assoc, mul_le_mul_left Ξ΅_pos, mul_comm],
exact pow_pos (by norm_num) k, },
-- Now let's specialize to `Ξ΅/2^k`
replace H : β k : β, β x', d x' x β€ 2 * Ξ΅ β§ 2^k * Ο x β€ Ο x' β β y, d x' y β€ Ξ΅/2^k β§ 2 * Ο x' < Ο y,
{ intros k x',
push_neg at H,
simpa [reformulation] using
H (Ξ΅/2^k) (by simp [Ξ΅_pos, zero_lt_two]) x' (by simp [Ξ΅_pos, zero_lt_two, one_le_two]) },
clear reformulation,
haveI : nonempty X := β¨xβ©,
choose! F hF using H, -- Use the axiom of choice
-- Now define u by induction starting at x, with u_{n+1} = F(n, u_n)
let u : β β X := Ξ» n, nat.rec_on n x F,
have hu0 : u 0 = x := rfl,
-- The properties of F translate to properties of u
have hu :
β n,
d (u n) x β€ 2 * Ξ΅ β§ 2^n * Ο x β€ Ο (u n) β
d (u n) (u $ n + 1) β€ Ξ΅ / 2 ^ n β§ 2 * Ο (u n) < Ο (u $ n + 1),
{ intro n,
exact hF n (u n) },
clear hF,
-- Key properties of u, to be proven by induction
have key : β n, d (u n) (u (n + 1)) β€ Ξ΅ / 2 ^ n β§ 2 * Ο (u n) < Ο (u (n + 1)),
{ intro n,
induction n using nat.case_strong_induction_on with n IH,
{ specialize hu 0,
simpa [hu0, mul_nonneg_iff, zero_le_one, Ξ΅_pos.le] using hu },
have A : d (u (n+1)) x β€ 2 * Ξ΅,
{ rw [dist_comm],
let r := range (n+1), -- range (n+1) = {0, ..., n}
calc
d (u 0) (u (n + 1))
β€ β i in r, d (u i) (u $ i+1) : dist_le_range_sum_dist u (n + 1)
... β€ β i in r, Ξ΅/2^i : sum_le_sum (Ξ» i i_in, (IH i $ nat.lt_succ_iff.mp $
finset.mem_range.mp i_in).1)
... = β i in r, (1/2)^i*Ξ΅ : by { congr' with i, field_simp }
... = (β i in r, (1/2)^i)*Ξ΅ : finset.sum_mul.symm
... β€ 2*Ξ΅ : mul_le_mul_of_nonneg_right (sum_geometric_two_le _)
(le_of_lt Ξ΅_pos), },
have B : 2^(n+1) * Ο x β€ Ο (u (n + 1)),
{ refine @geom_le (Ο β u) _ zero_le_two (n + 1) (Ξ» m hm, _),
exact (IH _ $ nat.lt_add_one_iff.1 hm).2.le },
exact hu (n+1) β¨A, Bβ©, },
cases forall_and_distrib.mp key with keyβ keyβ,
clear hu key,
-- Hence u is Cauchy
have cauchy_u : cauchy_seq u,
{ refine cauchy_seq_of_le_geometric _ Ξ΅ one_half_lt_one (Ξ» n, _),
simpa only [one_div, inv_pow'] using keyβ n },
-- So u converges to some y
obtain β¨y, limyβ© : β y, tendsto u at_top (π y),
from complete_space.complete cauchy_u,
-- And Ο β u goes to +β
have lim_top : tendsto (Ο β u) at_top at_top,
{ let v := Ξ» n, (Ο β u) (n+1),
suffices : tendsto v at_top at_top,
by rwa tendsto_add_at_top_iff_nat at this,
have hvβ : 0 < v 0,
{ have : 0 β€ Ο (u 0) := nonneg x,
calc 0 β€ 2 * Ο (u 0) : by linarith
... < Ο (u (0 + 1)) : keyβ 0 },
apply tendsto_at_top_of_geom_le hvβ one_lt_two,
exact Ξ» n, (keyβ (n+1)).le },
-- But Ο β u also needs to go to Ο(y)
have lim : tendsto (Ο β u) at_top (π (Ο y)),
from tendsto.comp cont.continuous_at limy,
-- So we have our contradiction!
exact not_tendsto_at_top_of_tendsto_nhds lim lim_top,
end
|
0c9f20a61618bfec0d41e33cf7f8f6da6a65ce2b | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/order/filter/interval.lean | a55264d92dec7fe47a231d2b244632da010f6599 | [
"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 | 10,817 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import data.set.intervals.ord_connected
import order.filter.lift
import order.filter.at_top_bot
/-!
# Convergence of intervals
If both `a` and `b` tend to some filter `lβ`, sometimes this implies that `Ixx a b` tends to
`lβ.lift' powerset`, i.e., for any `s β lβ` eventually `Ixx a b` becomes a subset of `s`. Here and
below `Ixx` is one of `Icc`, `Ico`, `Ioc`, and `Ioo`. We define `filter.tendsto_Ixx_class Ixx lβ lβ`
to be a typeclass representing this property.
The instances provide the best `lβ` for a given `lβ`. In many cases `lβ = lβ` but sometimes we can
drop an endpoint from an interval: e.g., we prove `tendsto_Ixx_class Ico (π $ Iic a) (π $ Iio a)`,
i.e., if `uβ n` and `uβ n` belong eventually to `Iic a`, then the interval `Ico (uβ n) (uβ n)` is
eventually included in `Iio a`.
The next table shows βoutputβ filters `lβ` for different values of `Ixx` and `lβ`. The instances
that need topology are defined in `topology/algebra/ordered`.
| Input filter | `Ixx = Icc` | `Ixx = Ico` | `Ixx = Ioc` | `Ixx = Ioo` |
| -----------: | :-----------: | :-----------: | :-----------: | :-----------: |
| `at_top` | `at_top` | `at_top` | `at_top` | `at_top` |
| `at_bot` | `at_bot` | `at_bot` | `at_bot` | `at_bot` |
| `pure a` | `pure a` | `β₯` | `β₯` | `β₯` |
| `π (Iic a)` | `π (Iic a)` | `π (Iio a)` | `π (Iic a)` | `π (Iio a)` |
| `π (Ici a)` | `π (Ici a)` | `π (Ici a)` | `π (Ioi a)` | `π (Ioi a)` |
| `π (Ioi a)` | `π (Ioi a)` | `π (Ioi a)` | `π (Ioi a)` | `π (Ioi a)` |
| `π (Iio a)` | `π (Iio a)` | `π (Iio a)` | `π (Iio a)` | `π (Iio a)` |
| `π a` | `π a` | `π a` | `π a` | `π a` |
| `π[Iic a] b` | `π[Iic a] b` | `π[Iio a] b` | `π[Iic a] b` | `π[Iio a] b` |
| `π[Ici a] b` | `π[Ici a] b` | `π[Ici a] b` | `π[Ioi a] b` | `π[Ioi a] b` |
| `π[Ioi a] b` | `π[Ioi a] b` | `π[Ioi a] b` | `π[Ioi a] b` | `π[Ioi a] b` |
| `π[Iio a] b` | `π[Iio a] b` | `π[Iio a] b` | `π[Iio a] b` | `π[Iio a] b` |
-/
variables {Ξ± Ξ² : Type*}
open_locale classical filter interval
open set function
namespace filter
section preorder
variables [preorder Ξ±]
/-- A pair of filters `lβ`, `lβ` has `tendsto_Ixx_class Ixx` property if `Ixx a b` tends to
`lβ.lift' powerset` as `a` and `b` tend to `lβ`. In all instances `Ixx` is one of `Icc`, `Ico`,
`Ioc`, or `Ioo`. The instances provide the best `lβ` for a given `lβ`. In many cases `lβ = lβ` but
sometimes we can drop an endpoint from an interval: e.g., we prove `tendsto_Ixx_class Ico (π $ Iic
a) (π $ Iio a)`, i.e., if `uβ n` and `uβ n` belong eventually to `Iic a`, then the interval `Ico (uβ
n) (uβ n)` is eventually included in `Iio a`.
We mark `lβ` as an `out_param` so that Lean can automatically find an appropriate `lβ` based on
`Ixx` and `lβ`. This way, e.g., `tendsto.Ico hβ hβ` works without specifying explicitly `lβ`. -/
class tendsto_Ixx_class (Ixx : Ξ± β Ξ± β set Ξ±) (lβ : filter Ξ±) (lβ : out_param $ filter Ξ±) : Prop :=
(tendsto_Ixx : tendsto (Ξ» p : Ξ± Γ Ξ±, Ixx p.1 p.2) (lβ ΓαΆ lβ) (lβ.lift' powerset))
lemma tendsto.Icc {lβ lβ : filter Ξ±} [tendsto_Ixx_class Icc lβ lβ]
{lb : filter Ξ²} {uβ uβ : Ξ² β Ξ±} (hβ : tendsto uβ lb lβ) (hβ : tendsto uβ lb lβ) :
tendsto (Ξ» x, Icc (uβ x) (uβ x)) lb (lβ.lift' powerset) :=
tendsto_Ixx_class.tendsto_Ixx.comp $ hβ.prod_mk hβ
lemma tendsto.Ioc {lβ lβ : filter Ξ±} [tendsto_Ixx_class Ioc lβ lβ]
{lb : filter Ξ²} {uβ uβ : Ξ² β Ξ±} (hβ : tendsto uβ lb lβ) (hβ : tendsto uβ lb lβ) :
tendsto (Ξ» x, Ioc (uβ x) (uβ x)) lb (lβ.lift' powerset) :=
tendsto_Ixx_class.tendsto_Ixx.comp $ hβ.prod_mk hβ
lemma tendsto.Ico {lβ lβ : filter Ξ±} [tendsto_Ixx_class Ico lβ lβ]
{lb : filter Ξ²} {uβ uβ : Ξ² β Ξ±} (hβ : tendsto uβ lb lβ) (hβ : tendsto uβ lb lβ) :
tendsto (Ξ» x, Ico (uβ x) (uβ x)) lb (lβ.lift' powerset) :=
tendsto_Ixx_class.tendsto_Ixx.comp $ hβ.prod_mk hβ
lemma tendsto.Ioo {lβ lβ : filter Ξ±} [tendsto_Ixx_class Ioo lβ lβ]
{lb : filter Ξ²} {uβ uβ : Ξ² β Ξ±} (hβ : tendsto uβ lb lβ) (hβ : tendsto uβ lb lβ) :
tendsto (Ξ» x, Ioo (uβ x) (uβ x)) lb (lβ.lift' powerset) :=
tendsto_Ixx_class.tendsto_Ixx.comp $ hβ.prod_mk hβ
lemma tendsto_Ixx_class_principal {s t : set Ξ±} {Ixx : Ξ± β Ξ± β set Ξ±} :
tendsto_Ixx_class Ixx (π s) (π t) β β (x β s) (y β s), Ixx x y β t :=
begin
refine iff.trans β¨Ξ» h, h.1, Ξ» h, β¨hβ©β© _,
simp [lift'_principal monotone_powerset, -mem_prod, -prod.forall, forall_prod_set]
end
lemma tendsto_Ixx_class_inf {lβ lβ' lβ lβ' : filter Ξ±} {Ixx}
[h : tendsto_Ixx_class Ixx lβ lβ] [h' : tendsto_Ixx_class Ixx lβ' lβ'] :
tendsto_Ixx_class Ixx (lβ β lβ') (lβ β lβ') :=
β¨by simpa only [prod_inf_prod, lift'_inf_powerset] using h.1.inf h'.1β©
lemma tendsto_Ixx_class_of_subset {lβ lβ : filter Ξ±} {Ixx Ixx' : Ξ± β Ξ± β set Ξ±}
(h : β a b, Ixx a b β Ixx' a b) [h' : tendsto_Ixx_class Ixx' lβ lβ] :
tendsto_Ixx_class Ixx lβ lβ :=
β¨tendsto_lift'_powerset_mono h'.1 $ eventually_of_forall $ prod.forall.2 hβ©
lemma has_basis.tendsto_Ixx_class {ΞΉ : Type*} {p : ΞΉ β Prop} {s} {l : filter Ξ±}
(hl : l.has_basis p s) {Ixx : Ξ± β Ξ± β set Ξ±}
(H : β i, p i β β (x β s i) (y β s i), Ixx x y β s i) :
tendsto_Ixx_class Ixx l l :=
β¨(hl.prod_self.tendsto_iff (hl.lift' monotone_powerset)).2 $ Ξ» i hi,
β¨i, hi, Ξ» x hx, H i hi _ hx.1 _ hx.2β©β©
instance tendsto_Icc_at_top_at_top : tendsto_Ixx_class Icc (at_top : filter Ξ±) at_top :=
(has_basis_infi_principal_finite _).tendsto_Ixx_class $ Ξ» s hs,
set.ord_connected.out $ ord_connected_bInter $ Ξ» i hi, ord_connected_Ici
instance tendsto_Ico_at_top_at_top : tendsto_Ixx_class Ico (at_top : filter Ξ±) at_top :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ico_subset_Icc_self)
instance tendsto_Ioc_at_top_at_top : tendsto_Ixx_class Ioc (at_top : filter Ξ±) at_top :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ioc_subset_Icc_self)
instance tendsto_Ioo_at_top_at_top : tendsto_Ixx_class Ioo (at_top : filter Ξ±) at_top :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ioo_subset_Icc_self)
instance tendsto_Icc_at_bot_at_bot : tendsto_Ixx_class Icc (at_bot : filter Ξ±) at_bot :=
(has_basis_infi_principal_finite _).tendsto_Ixx_class $ Ξ» s hs,
set.ord_connected.out $ ord_connected_bInter $ Ξ» i hi, ord_connected_Iic
instance tendsto_Ico_at_bot_at_bot : tendsto_Ixx_class Ico (at_bot : filter Ξ±) at_bot :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ico_subset_Icc_self)
instance tendsto_Ioc_at_bot_at_bot : tendsto_Ixx_class Ioc (at_bot : filter Ξ±) at_bot :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ioc_subset_Icc_self)
instance tendsto_Ioo_at_bot_at_bot : tendsto_Ixx_class Ioo (at_bot : filter Ξ±) at_bot :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ioo_subset_Icc_self)
instance ord_connected.tendsto_Icc {s : set Ξ±} [hs : ord_connected s] :
tendsto_Ixx_class Icc (π s) (π s) :=
tendsto_Ixx_class_principal.2 hs.out
instance tendsto_Ico_Ici_Ici {a : Ξ±} : tendsto_Ixx_class Ico (π (Ici a)) (π (Ici a)) :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ico_subset_Icc_self)
instance tendsto_Ico_Ioi_Ioi {a : Ξ±} : tendsto_Ixx_class Ico (π (Ioi a)) (π (Ioi a)) :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ico_subset_Icc_self)
instance tendsto_Ico_Iic_Iio {a : Ξ±} : tendsto_Ixx_class Ico (π (Iic a)) (π (Iio a)) :=
tendsto_Ixx_class_principal.2 $ Ξ» a ha b hb x hx, lt_of_lt_of_le hx.2 hb
instance tendsto_Ico_Iio_Iio {a : Ξ±} : tendsto_Ixx_class Ico (π (Iio a)) (π (Iio a)) :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ico_subset_Icc_self)
instance tendsto_Ioc_Ici_Ioi {a : Ξ±} : tendsto_Ixx_class Ioc (π (Ici a)) (π (Ioi a)) :=
tendsto_Ixx_class_principal.2 $ Ξ» x hx y hy t ht, lt_of_le_of_lt hx ht.1
instance tendsto_Ioc_Iic_Iic {a : Ξ±} : tendsto_Ixx_class Ioc (π (Iic a)) (π (Iic a)) :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ioc_subset_Icc_self)
instance tendsto_Ioc_Iio_Iio {a : Ξ±} : tendsto_Ixx_class Ioc (π (Iio a)) (π (Iio a)) :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ioc_subset_Icc_self)
instance tendsto_Ioc_Ioi_Ioi {a : Ξ±} : tendsto_Ixx_class Ioc (π (Ioi a)) (π (Ioi a)) :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ioc_subset_Icc_self)
instance tendsto_Ioo_Ici_Ioi {a : Ξ±} : tendsto_Ixx_class Ioo (π (Ici a)) (π (Ioi a)) :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ioo_subset_Ioc_self)
instance tendsto_Ioo_Iic_Iio {a : Ξ±} : tendsto_Ixx_class Ioo (π (Iic a)) (π (Iio a)) :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ioo_subset_Ico_self)
instance tendsto_Ioo_Ioi_Ioi {a : Ξ±} : tendsto_Ixx_class Ioo (π (Ioi a)) (π (Ioi a)) :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ioo_subset_Ioc_self)
instance tendsto_Ioo_Iio_Iio {a : Ξ±} : tendsto_Ixx_class Ioo (π (Iio a)) (π (Iio a)) :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ioo_subset_Ioc_self)
instance tendsto_Icc_Icc_icc {a b : Ξ±} :
tendsto_Ixx_class Icc (π (Icc a b)) (π (Icc a b)) :=
tendsto_Ixx_class_principal.mpr $ Ξ» x hx y hy, Icc_subset_Icc hx.1 hy.2
instance tendsto_Ioc_Icc_Icc {a b : Ξ±} : tendsto_Ixx_class Ioc (π (Icc a b)) (π (Icc a b)) :=
tendsto_Ixx_class_of_subset $ Ξ» _ _, Ioc_subset_Icc_self
end preorder
section partial_order
variable [partial_order Ξ±]
instance tendsto_Icc_pure_pure {a : Ξ±} : tendsto_Ixx_class Icc (pure a) (pure a : filter Ξ±) :=
by { rw β principal_singleton, exact tendsto_Ixx_class_principal.2 ord_connected_singleton.out }
instance tendsto_Ico_pure_bot {a : Ξ±} : tendsto_Ixx_class Ico (pure a) β₯ :=
β¨by simp [lift'_bot monotone_powerset]β©
instance tendsto_Ioc_pure_bot {a : Ξ±} : tendsto_Ixx_class Ioc (pure a) β₯ :=
β¨by simp [lift'_bot monotone_powerset]β©
instance tendsto_Ioo_pure_bot {a : Ξ±} : tendsto_Ixx_class Ioo (pure a) β₯ :=
tendsto_Ixx_class_of_subset (Ξ» _ _, Ioo_subset_Ioc_self)
end partial_order
section linear_order
variables [linear_order Ξ±]
instance tendsto_Icc_interval_interval {a b : Ξ±} : tendsto_Ixx_class Icc (π [a, b]) (π [a, b]) :=
filter.tendsto_Icc_Icc_icc
instance tendsto_Ioc_interval_interval {a b : Ξ±} : tendsto_Ixx_class Ioc (π [a, b]) (π [a, b]) :=
tendsto_Ixx_class_of_subset $ Ξ» _ _, Ioc_subset_Icc_self
end linear_order
end filter
|
1921ce4c134279134481457583532cefc167be92 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/algebra/continued_fractions/convergents_equiv.lean | 0197e0112a302ab24acb5874969b7377d86fcaaa | [
"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 | 20,583 | lean | /-
Copyright (c) 2020 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import algebra.continued_fractions.continuants_recurrence
import algebra.continued_fractions.terminated_stable
import tactic.linarith
/-!
# Equivalence of Recursive and Direct Computations of `gcf` Convergents
## Summary
We show the equivalence of two computations of convergents (recurrence relation (`convergents`) vs.
direct evaluation (`convergents'`)) for `gcf`s on linear ordered fields. We follow the proof from
[hardy2008introduction], Chapter 10. Here's a sketch:
Let `c` be a continued fraction `[h; (aβ, bβ), (aβ, bβ), (aβ, bβ),...]`, visually:
aβ
h + ---------------------------
aβ
bβ + --------------------
aβ
bβ + --------------
aβ
bβ + --------
bβ + ...
One can compute the convergents of `c` in two ways:
1. Directly evaluating the fraction described by `c` up to a given `n` (`convergents'`)
2. Using the recurrence (`convergents`):
- `Aββ = 1, Aβ = h, Aβ = bβββ * Aβββ + aβββ * Aβββ`, and
- `Bββ = 0, Bβ = 1, Bβ = bβββ * Bβββ + aβββ * Bβββ`.
To show the equivalence of the computations in the main theorem of this file
`convergents_eq_convergents'`, we proceed by induction. The case `n = 0` is trivial.
For `n + 1`, we first "squash" the `n + 1`th position of `c` into the `n`th position to obtain
another continued fraction
`c' := [h; (aβ, bβ),..., (aβ-β, bβ-β), (aβ, bβ + aβββ / bβββ), (aβββ, bβββ),...]`.
This squashing process is formalised in section `squash`. Note that directly evaluating `c` up to
position `n + 1` is equal to evaluating `c'` up to `n`. This is shown in lemma
`succ_nth_convergent'_eq_squash_gcf_nth_convergent'`.
By the inductive hypothesis, the two computations for the `n`th convergent of `c` coincide.
So all that is left to show is that the recurrence relation for `c` at `n + 1` and and `c'` at
`n` coincide. This can be shown by another induction.
The corresponding lemma in this file is `succ_nth_convergent_eq_squash_gcf_nth_convergent`.
## Main Theorems
- `generalized_continued_fraction.convergents_eq_convergents'` shows the equivalence under a strict
positivity restriction on the sequence.
- `continued_fractions.convergents_eq_convergents'` shows the equivalence for (regular) continued
fractions.
## References
- https://en.wikipedia.org/wiki/Generalized_continued_fraction
- [*Hardy, GH and Wright, EM and Heath-Brown, Roger and Silverman, Joseph*][hardy2008introduction]
## Tags
fractions, recurrence, equivalence
-/
variables {K : Type*} {n : β}
namespace generalized_continued_fraction
open generalized_continued_fraction as gcf
variables {g : gcf K} {s : seq $ gcf.pair K}
section squash
/-!
We will show the equivalence of the computations by induction. To make the induction work, we need
to be able to *squash* the nth and (n + 1)th value of a sequence. This squashing itself and the
lemmas about it are not very interesting. As a reader, you hence might want to skip this section.
-/
section with_division_ring
variable [division_ring K]
/--
Given a sequence of gcf.pairs `s = [(aβ, bβ), (aβ, bβ), ...]`, `squash_seq s n`
combines `β¨aβ, bββ©` and `β¨aβββ, bββββ©` at position `n` to `β¨aβ, bβ + aβββ / bββββ©`. For example,
`squash_seq s 0 = [(aβ, bβ + aβ / bβ), (aβ, bβ),...]`.
If `s.terminated_at (n + 1)`, then `squash_seq s n = s`.
-/
def squash_seq (s : seq $ gcf.pair K) (n : β) : seq (gcf.pair K) :=
match prod.mk (s.nth n) (s.nth (n + 1)) with
| β¨some gp_n, some gp_succ_nβ© := seq.nats.zip_with
-- return the squashed value at position `n`; otherwise, do nothing.
(Ξ» n' gp, if n' = n then β¨gp_n.a, gp_n.b + gp_succ_n.a / gp_succ_n.bβ© else gp) s
| _ := s
end
/-! We now prove some simple lemmas about the squashed sequence -/
/-- If the sequence already terminated at position `n + 1`, nothing gets squashed. -/
lemma squash_seq_eq_self_of_terminated (terminated_at_succ_n : s.terminated_at (n + 1)) :
squash_seq s n = s :=
begin
change s.nth (n + 1) = none at terminated_at_succ_n,
cases s_nth_eq : (s.nth n);
simp only [*, squash_seq]
end
/-- If the sequence has not terminated before position `n + 1`, the value at `n + 1` gets
squashed into position `n`. -/
lemma squash_seq_nth_of_not_terminated {gp_n gp_succ_n : gcf.pair K}
(s_nth_eq : s.nth n = some gp_n) (s_succ_nth_eq : s.nth (n + 1) = some gp_succ_n) :
(squash_seq s n).nth n = some β¨gp_n.a, gp_n.b + gp_succ_n.a / gp_succ_n.bβ© :=
by simp [*, squash_seq, (seq.zip_with_nth_some (seq.nats_nth n) s_nth_eq _)]
/-- The values before the squashed position stay the same. -/
lemma squash_seq_nth_of_lt {m : β} (m_lt_n : m < n) : (squash_seq s n).nth m = s.nth m :=
begin
cases s_succ_nth_eq : s.nth (n + 1),
case option.none { rw (squash_seq_eq_self_of_terminated s_succ_nth_eq) },
case option.some
{ obtain β¨gp_n, s_nth_eqβ© : β gp_n, s.nth n = some gp_n, from
s.ge_stable n.le_succ s_succ_nth_eq,
obtain β¨gp_m, s_mth_eqβ© : β gp_m, s.nth m = some gp_m, from
s.ge_stable (le_of_lt m_lt_n) s_nth_eq,
simp [*, squash_seq, (seq.zip_with_nth_some (seq.nats_nth m) s_mth_eq _),
(ne_of_lt m_lt_n)] }
end
/-- Squashing at position `n + 1` and taking the tail is the same as squashing the tail of the
sequence at position `n`. -/
lemma squash_seq_succ_n_tail_eq_squash_seq_tail_n :
(squash_seq s (n + 1)).tail = squash_seq s.tail n :=
begin
cases s_succ_succ_nth_eq : s.nth (n + 2) with gp_succ_succ_n,
case option.none
{ have : squash_seq s (n + 1) = s, from squash_seq_eq_self_of_terminated s_succ_succ_nth_eq,
cases s_succ_nth_eq : (s.nth (n + 1));
simp only [squash_seq, seq.nth_tail, s_succ_nth_eq, s_succ_succ_nth_eq] },
case option.some
{ obtain β¨gp_succ_n, s_succ_nth_eqβ© : β gp_succ_n, s.nth (n + 1) = some gp_succ_n, from
s.ge_stable (n + 1).le_succ s_succ_succ_nth_eq,
-- apply extensionality with `m` and continue by cases `m = n`.
ext m,
cases decidable.em (m = n) with m_eq_n m_ne_n,
{ have : s.tail.nth n = some gp_succ_n, from (s.nth_tail n).trans s_succ_nth_eq,
simp [*, squash_seq, seq.nth_tail, (seq.zip_with_nth_some (seq.nats_nth n) this),
(seq.zip_with_nth_some (seq.nats_nth (n + 1)) s_succ_nth_eq)] },
{ have : s.tail.nth m = s.nth (m + 1), from s.nth_tail m,
cases s_succ_mth_eq : s.nth (m + 1),
all_goals { have s_tail_mth_eq, from this.trans s_succ_mth_eq },
{ simp only [*, squash_seq, seq.nth_tail, (seq.zip_with_nth_none' s_succ_mth_eq),
(seq.zip_with_nth_none' s_tail_mth_eq)] },
{ simp [*, squash_seq, seq.nth_tail,
(seq.zip_with_nth_some (seq.nats_nth (m + 1)) s_succ_mth_eq),
(seq.zip_with_nth_some (seq.nats_nth m) s_tail_mth_eq)] } } }
end
/-- The auxiliary function `convergents'_aux` returns the same value for a sequence and the
corresponding squashed sequence at the squashed position. -/
lemma succ_succ_nth_convergent'_aux_eq_succ_nth_convergent'_aux_squash_seq :
convergents'_aux s (n + 2) = convergents'_aux (squash_seq s n) (n + 1) :=
begin
cases s_succ_nth_eq : (s.nth $ n + 1) with gp_succ_n,
case option.none
{ rw [(squash_seq_eq_self_of_terminated s_succ_nth_eq),
(convergents'_aux_stable_step_of_terminated s_succ_nth_eq)] },
case option.some
{ induction n with m IH generalizing s gp_succ_n,
case nat.zero
{ obtain β¨gp_head, s_head_eqβ© : β gp_head, s.head = some gp_head, from
s.ge_stable zero_le_one s_succ_nth_eq,
have : (squash_seq s 0).head = some β¨gp_head.a, gp_head.b + gp_succ_n.a / gp_succ_n.bβ©,
from squash_seq_nth_of_not_terminated s_head_eq s_succ_nth_eq,
simp [*, convergents'_aux, seq.head, seq.nth_tail] },
case nat.succ
{ obtain β¨gp_head, s_head_eqβ© : β gp_head, s.head = some gp_head, from
s.ge_stable (m + 2).zero_le s_succ_nth_eq,
suffices : gp_head.a / (gp_head.b + convergents'_aux s.tail (m + 2))
= convergents'_aux (squash_seq s (m + 1)) (m + 2), by
simpa only [convergents'_aux, s_head_eq],
have : convergents'_aux s.tail (m + 2) = convergents'_aux (squash_seq s.tail m) (m + 1), by
{ have : s.tail.nth (m + 1) = some gp_succ_n, by simpa [seq.nth_tail] using s_succ_nth_eq,
exact (IH _ this) },
have : (squash_seq s (m + 1)).head = some gp_head, from
(squash_seq_nth_of_lt m.succ_pos).trans s_head_eq,
simp only [*, convergents'_aux, squash_seq_succ_n_tail_eq_squash_seq_tail_n] } }
end
/-! Let us now lift the squashing operation to gcfs. -/
/--
Given a gcf `g = [h; (aβ, bβ), (aβ, bβ), ...]`, we have
- `squash_nth.gcf g 0 = [h + aβ / bβ); (aβ, bβ), ...]`,
- `squash_nth.gcf g (n + 1) = β¨g.h, squash_seq g.s nβ©`
-/
def squash_gcf (g : gcf K) : β β gcf K
| 0 := match g.s.nth 0 with
| none := g
| some gp := β¨g.h + gp.a / gp.b, g.sβ©
end
| (n + 1) := β¨g.h, squash_seq g.s nβ©
/-! Again, we derive some simple lemmas that are not really of interest. This time for the
squashed gcf. -/
/-- If the gcf already terminated at position `n`, nothing gets squashed. -/
lemma squash_gcf_eq_self_of_terminated (terminated_at_n : terminated_at g n) :
squash_gcf g n = g :=
begin
cases n,
case nat.zero
{ change g.s.nth 0 = none at terminated_at_n,
simp only [convergents', squash_gcf, convergents'_aux, terminated_at_n] },
case nat.succ
{ cases g, simp [(squash_seq_eq_self_of_terminated terminated_at_n), squash_gcf] }
end
/-- The values before the squashed position stay the same. -/
lemma squash_gcf_nth_of_lt {m : β} (m_lt_n : m < n) :
(squash_gcf g (n + 1)).s.nth m = g.s.nth m :=
by simp only [squash_gcf, (squash_seq_nth_of_lt m_lt_n)]
/-- `convergents'` returns the same value for a gcf and the corresponding squashed gcf at the
squashed position. -/
lemma succ_nth_convergent'_eq_squash_gcf_nth_convergent' :
g.convergents' (n + 1) = (squash_gcf g n).convergents' n :=
begin
cases n,
case nat.zero
{ cases g_s_head_eq : (g.s.nth 0);
simp [g_s_head_eq, squash_gcf, convergents', convergents'_aux, seq.head] },
case nat.succ
{ simp only [succ_succ_nth_convergent'_aux_eq_succ_nth_convergent'_aux_squash_seq,
convergents', squash_gcf] }
end
/-- The auxiliary continuants before the squashed position stay the same. -/
lemma continuants_aux_eq_continuants_aux_squash_gcf_of_le {m : β} :
m β€ n β continuants_aux g m = (squash_gcf g n).continuants_aux m :=
nat.strong_induction_on m
(begin
clear m,
assume m IH m_le_n,
cases m with m',
{ refl },
{ cases n with n',
{ have : false, from m'.not_succ_le_zero m_le_n, contradiction }, -- 1 β° 0
{ cases m' with m'',
{ refl },
{ -- get some inequalities to instantiate the IH for m'' and m'' + 1
have m'_lt_n : m'' + 1 < n' + 1, from m_le_n,
have : m'' + 1 < m'' + 2, by linarith,
have succ_m''th_conts_aux_eq := IH (m'' + 1) this (le_of_lt m'_lt_n),
have : m'' < m'' + 2, by linarith,
have m''th_conts_aux_eq := IH m'' this (le_of_lt $ lt_of_lt_of_le (by linarith) n'.le_succ),
have : (squash_gcf g (n' + 1)).s.nth m'' = g.s.nth m'', from
squash_gcf_nth_of_lt (by linarith),
simp [continuants_aux, succ_m''th_conts_aux_eq, m''th_conts_aux_eq, this] } } }
end)
end with_division_ring
/-- The convergents coincide in the expected way at the squashed position if the partial denominator
at the squashed position is not zero. -/
lemma succ_nth_convergent_eq_squash_gcf_nth_convergent [field K]
(nth_part_denom_ne_zero : β {b : K}, g.partial_denominators.nth n = some b β b β 0) :
g.convergents (n + 1) = (squash_gcf g n).convergents n :=
begin
cases decidable.em (g.terminated_at n) with terminated_at_n not_terminated_at_n,
{ have : squash_gcf g n = g, from squash_gcf_eq_self_of_terminated terminated_at_n,
simp only [this, (convergents_stable_of_terminated n.le_succ terminated_at_n)] },
{ obtain β¨β¨a, bβ©, s_nth_eqβ© : β gp_n, g.s.nth n = some gp_n, from
option.ne_none_iff_exists'.mp not_terminated_at_n,
have b_ne_zero : b β 0, from nth_part_denom_ne_zero (part_denom_eq_s_b s_nth_eq),
cases n with n',
case nat.zero
{ suffices : (b * g.h + a) / b = g.h + a / b, by
simpa [squash_gcf, s_nth_eq, convergent_eq_conts_a_div_conts_b,
(continuants_recurrence_aux s_nth_eq zeroth_continuant_aux_eq_one_zero
first_continuant_aux_eq_h_one)],
calc
(b * g.h + a) / b = b * g.h / b + a / b : by ring -- requires `field` rather than `division_ring`
... = g.h + a / b : by rw (mul_div_cancel_left _ b_ne_zero) },
case nat.succ
{ obtain β¨β¨pa, pbβ©, s_n'th_eqβ© : β gp_n', g.s.nth n' = some gp_n' :=
g.s.ge_stable n'.le_succ s_nth_eq,
-- Notations
let g' := squash_gcf g (n' + 1),
set pred_conts := g.continuants_aux (n' + 1) with succ_n'th_conts_aux_eq,
set ppred_conts := g.continuants_aux n' with n'th_conts_aux_eq,
let pA := pred_conts.a, let pB := pred_conts.b,
let ppA := ppred_conts.a, let ppB := ppred_conts.b,
set pred_conts' := g'.continuants_aux (n' + 1) with succ_n'th_conts_aux_eq',
set ppred_conts' := g'.continuants_aux n' with n'th_conts_aux_eq',
let pA' := pred_conts'.a, let pB' := pred_conts'.b, let ppA' := ppred_conts'.a,
let ppB' := ppred_conts'.b,
-- first compute the convergent of the squashed gcf
have : g'.convergents (n' + 1)
= ((pb + a / b) * pA' + pa * ppA') / ((pb + a / b) * pB' + pa * ppB'),
{ have : g'.s.nth n' = some β¨pa, pb + a / bβ©,
{ simpa only [squash_nth_gcf] using
(squash_seq_nth_of_not_terminated s_n'th_eq s_nth_eq) },
rw [convergent_eq_conts_a_div_conts_b,
(continuants_recurrence_aux this n'th_conts_aux_eq'.symm succ_n'th_conts_aux_eq'.symm)], },
rw this,
-- then compute the convergent of the original gcf by recursively unfolding the continuants
-- computation twice
have : g.convergents (n' + 2)
= (b * (pb * pA + pa * ppA) + a * pA) / (b * (pb * pB + pa * ppB) + a * pB),
{ -- use the recurrence once
have : g.continuants_aux (n' + 2) = β¨pb * pA + pa * ppA, pb * pB + pa * ppBβ© :=
continuants_aux_recurrence s_n'th_eq n'th_conts_aux_eq.symm succ_n'th_conts_aux_eq.symm,
-- and a second time
rw [convergent_eq_conts_a_div_conts_b,
(continuants_recurrence_aux s_nth_eq succ_n'th_conts_aux_eq.symm this)] },
rw this,
suffices : ((pb + a / b) * pA + pa * ppA) / ((pb + a / b) * pB + pa * ppB)
= (b * (pb * pA + pa * ppA) + a * pA) / (b * (pb * pB + pa * ppB) + a * pB),
{ obtain β¨eq1, eq2, eq3, eq4β© : pA' = pA β§ pB' = pB β§ ppA' = ppA β§ ppB' = ppB,
{ simp [*, (continuants_aux_eq_continuants_aux_squash_gcf_of_le $ le_refl $ n' + 1).symm,
(continuants_aux_eq_continuants_aux_squash_gcf_of_le n'.le_succ).symm] },
symmetry,
simpa only [eq1, eq2, eq3, eq4, mul_div_cancel _ b_ne_zero] },
field_simp [b_ne_zero],
congr' 1; ring } }
end
end squash
/-- Shows that the recurrence relation (`convergents`) and direct evaluation (`convergents'`) of the
gcf coincide at position `n` if the sequence of fractions contains strictly positive values only.
Requiring positivity of all values is just one possible condition to obtain this result.
For example, the dual - sequences with strictly negative values only - would also work.
In practice, one most commonly deals with (regular) continued fractions, which satisfy the
positivity criterion required here. The analogous result for them
(see `continued_fractions.convergents_eq_convergents`) hence follows directly from this theorem.
-/
theorem convergents_eq_convergents' [linear_ordered_field K]
(s_pos : β {gp : gcf.pair K} {m : β}, m < n β g.s.nth m = some gp β 0 < gp.a β§ 0 < gp.b) :
g.convergents n = g.convergents' n :=
begin
induction n with n IH generalizing g,
case nat.zero { simp },
case nat.succ
{ let g' := squash_gcf g n, -- first replace the rhs with the squashed computation
suffices : g.convergents (n + 1) = g'.convergents' n, by
rwa [succ_nth_convergent'_eq_squash_gcf_nth_convergent'],
cases decidable.em (terminated_at g n) with terminated_at_n not_terminated_at_n,
{ have g'_eq_g : g' = g, from squash_gcf_eq_self_of_terminated terminated_at_n,
have : β β¦gp mβ¦, m < n β g.s.nth m = some gp β 0 < gp.a β§ 0 < gp.b, by
{ assume _ _ m_lt_n s_mth_eq, exact (s_pos (nat.lt.step m_lt_n) s_mth_eq) },
rw [(convergents_stable_of_terminated n.le_succ terminated_at_n), g'_eq_g, (IH this)] },
{ suffices : g.convergents (n + 1) = g'.convergents n, by -- invoke the IH for the squashed gcf
{ have : β β¦gp' mβ¦, m < n β g'.s.nth m = some gp' β 0 < gp'.a β§ 0 < gp'.b, by
{ assume gp' m m_lt_n s_mth_eq',
-- case distinction on m + 1 = n or m + 1 < n
cases m_lt_n with n succ_m_lt_n,
{ -- the difficult case at the squashed position: we first obtain the values from
-- the sequence
obtain β¨gp_succ_m, s_succ_mth_eqβ© : β gp_succ_m, g.s.nth (m + 1) = some gp_succ_m, from
option.ne_none_iff_exists'.mp not_terminated_at_n,
obtain β¨gp_m, mth_s_eqβ© : β gp_m, g.s.nth m = some gp_m, from
g.s.ge_stable m.le_succ s_succ_mth_eq,
-- we then plug them into the recurrence
suffices : 0 < gp_m.a β§ 0 < gp_m.b + gp_succ_m.a / gp_succ_m.b, by {
have : g'.s.nth m = some β¨gp_m.a, gp_m.b + gp_succ_m.a / gp_succ_m.bβ©, from
squash_seq_nth_of_not_terminated mth_s_eq s_succ_mth_eq,
have : gp' = β¨gp_m.a, gp_m.b + gp_succ_m.a / gp_succ_m.bβ©, by cc,
rwa this },
split,
{ exact (s_pos (nat.lt.step m_lt_n) mth_s_eq).left },
{ have : 0 < gp_m.b, from (s_pos (nat.lt.step m_lt_n) mth_s_eq).right,
have : 0 < gp_succ_m.a / gp_succ_m.b, by
{ have : 0 < gp_succ_m.a β§ 0 < gp_succ_m.b, from
s_pos (lt_add_one $ m + 1) s_succ_mth_eq,
exact (div_pos this.left this.right) },
linarith } },
{ -- the easy case: before the squashed position, nothing changes
have : g.s.nth m = some gp', by {
have : g'.s.nth m = g.s.nth m, from squash_gcf_nth_of_lt succ_m_lt_n,
rwa this at s_mth_eq' },
exact s_pos (nat.lt.step $ nat.lt.step succ_m_lt_n) this } },
rwa [(IH this).symm] },
-- now the result follows from the fact that the convergents coincide at the squashed position
-- as established in `succ_nth_convergent_eq_squash_gcf_nth_convergent`.
have : β β¦bβ¦, g.partial_denominators.nth n = some b β b β 0, by
{ assume b nth_part_denom_eq,
obtain β¨gp, s_nth_eq, β¨reflβ©β© : β gp, g.s.nth n = some gp β§ gp.b = b, from
exists_s_b_of_part_denom nth_part_denom_eq,
exact (ne_of_lt (s_pos (lt_add_one n) s_nth_eq).right).symm },
exact succ_nth_convergent_eq_squash_gcf_nth_convergent this } }
end
end generalized_continued_fraction
namespace continued_fraction
open generalized_continued_fraction as gcf
open simple_continued_fraction as scf
open continued_fraction as cf
/-- Shows that the recurrence relation (`convergents`) and direct evaluation (`convergents'`) of a
(regular) continued fraction coincide. -/
theorem convergents_eq_convergents' [linear_ordered_field K] {c : cf K} :
(βc : gcf K).convergents = (βc : gcf K).convergents' :=
begin
ext n,
apply gcf.convergents_eq_convergents',
assume gp m m_lt_n s_nth_eq,
split,
{ have : gp.a = 1, from (c : scf K).property m gp.a (gcf.part_num_eq_s_a s_nth_eq),
simp only [zero_lt_one, this] },
{ exact (c.property m gp.b $ gcf.part_denom_eq_s_b s_nth_eq) }
end
end continued_fraction
|
551a953cce7838e59334dfd9072622cc25158312 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/topology/compact_open_auto.lean | 24d2ca54ace62a4a6a68ac8b7d55433f5478ea3d | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,621 | lean | /-
Copyright (c) 2018 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton
Type of continuous maps and the compact-open topology on them.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.topology.subset_properties
import Mathlib.topology.continuous_map
import Mathlib.tactic.tidy
import Mathlib.PostPort
universes u_1 u_2 u_3
namespace Mathlib
namespace continuous_map
def compact_open.gen {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±] [topological_space Ξ²]
(s : set Ξ±) (u : set Ξ²) : set (continuous_map Ξ± Ξ²) :=
set_of fun (f : continuous_map Ξ± Ξ²) => βf '' s β u
-- The compact-open topology on the space of continuous maps Ξ± β Ξ².
protected instance compact_open {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±]
[topological_space Ξ²] : topological_space (continuous_map Ξ± Ξ²) :=
topological_space.generate_from
(set_of
fun (m : set (continuous_map Ξ± Ξ²)) =>
β (s : set Ξ±), β (hs : is_compact s), β (u : set Ξ²), β (hu : is_open u), m = sorry)
def induced {Ξ± : Type u_1} {Ξ² : Type u_2} {Ξ³ : Type u_3} [topological_space Ξ±] [topological_space Ξ²]
[topological_space Ξ³] {g : Ξ² β Ξ³} (hg : continuous g) (f : continuous_map Ξ± Ξ²) :
continuous_map Ξ± Ξ³ :=
mk (g β βf)
/-- C(Ξ±, -) is a functor. -/
theorem continuous_induced {Ξ± : Type u_1} {Ξ² : Type u_2} {Ξ³ : Type u_3} [topological_space Ξ±]
[topological_space Ξ²] [topological_space Ξ³] {g : Ξ² β Ξ³} (hg : continuous g) :
continuous (induced hg) :=
sorry
def ev (Ξ± : Type u_1) (Ξ² : Type u_2) [topological_space Ξ±] [topological_space Ξ²]
(p : continuous_map Ξ± Ξ² Γ Ξ±) : Ξ² :=
coe_fn (prod.fst p) (prod.snd p)
-- The evaluation map C(Ξ±, Ξ²) Γ Ξ± β Ξ² is continuous if Ξ± is locally compact.
theorem continuous_ev {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±] [topological_space Ξ²]
[locally_compact_space Ξ±] : continuous (ev Ξ± Ξ²) :=
sorry
def coev (Ξ± : Type u_1) (Ξ² : Type u_2) [topological_space Ξ±] [topological_space Ξ²] (b : Ξ²) :
continuous_map Ξ± (Ξ² Γ Ξ±) :=
mk fun (a : Ξ±) => (b, a)
theorem image_coev {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±] [topological_space Ξ²] {y : Ξ²}
(s : set Ξ±) : β(coev Ξ± Ξ² y) '' s = set.prod (singleton y) s :=
sorry
-- The coevaluation map Ξ² β C(Ξ±, Ξ² Γ Ξ±) is continuous (always).
theorem continuous_coev {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±] [topological_space Ξ²] :
continuous (coev Ξ± Ξ²) :=
sorry
end Mathlib |
5c2b83a9268675081953d5507a4f44480ee3ce63 | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/algebra/direct_limit.lean | 7ade971ce2a4a6d5682a1ad2b2cfcefcf2e3efc2 | [
"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 | 25,237 | lean | /-
Copyright (c) 2019 Kenny Lau, Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Chris Hughes
Direct limit of modules, abelian groups, rings, and fields.
See Atiyah-Macdonald PP.32-33, Matsumura PP.269-270
Generalizes the notion of "union", or "gluing", of incomparable modules over the same ring,
or incomparable abelian groups, or rings, or fields.
It is constructed as a quotient of the free module (for the module case) or quotient of
the free commutative ring (for the ring case) instead of a quotient of the disjoint union
so as to make the operations (addition etc.) "computable".
-/
import ring_theory.free_comm_ring
universes u v w uβ
open submodule
variables {R : Type u} [ring R]
variables {ΞΉ : Type v} [nonempty ΞΉ]
variables [decidable_eq ΞΉ] [directed_order ΞΉ]
variables (G : ΞΉ β Type w) [Ξ i, decidable_eq (G i)]
/-- A directed system is a functor from the category (directed poset) to another category.
This is used for abelian groups and rings and fields because their maps are not bundled.
See module.directed_system -/
class directed_system (f : Ξ i j, i β€ j β G i β G j) : Prop :=
(map_self [] : β i x h, f i i h x = x)
(map_map [] : β i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x)
namespace module
variables [Ξ i, add_comm_group (G i)] [Ξ i, module R (G i)]
/-- A directed system is a functor from the category (directed poset) to the category of R-modules. -/
class directed_system (f : Ξ i j, i β€ j β G i ββ[R] G j) : Prop :=
(map_self [] : β i x h, f i i h x = x)
(map_map [] : β i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x)
variables (f : Ξ i j, i β€ j β G i ββ[R] G j) [directed_system G f]
/-- The direct limit of a directed system is the modules glued together along the maps. -/
def direct_limit : Type (max v w) :=
(span R $ { a | β (i j) (H : i β€ j) x,
direct_sum.lof R ΞΉ G i x - direct_sum.lof R ΞΉ G j (f i j H x) = a }).quotient
namespace direct_limit
instance : add_comm_group (direct_limit G f) := quotient.add_comm_group _
instance : semimodule R (direct_limit G f) := quotient.semimodule _
variables (R ΞΉ)
/-- The canonical map from a component to the direct limit. -/
def of (i) : G i ββ[R] direct_limit G f :=
(mkq _).comp $ direct_sum.lof R ΞΉ G i
variables {R ΞΉ G f}
@[simp] lemma of_f {i j hij x} : (of R ΞΉ G f j (f i j hij x)) = of R ΞΉ G f i x :=
eq.symm $ (submodule.quotient.eq _).2 $ subset_span β¨i, j, hij, x, rflβ©
/-- Every element of the direct limit corresponds to some element in
some component of the directed system. -/
theorem exists_of (z : direct_limit G f) : β i x, of R ΞΉ G f i x = z :=
nonempty.elim (by apply_instance) $ assume ind : ΞΉ,
quotient.induction_on' z $ Ξ» z, direct_sum.induction_on z
β¨ind, 0, linear_map.map_zero _β©
(Ξ» i x, β¨i, x, rflβ©)
(Ξ» p q β¨i, x, ihxβ© β¨j, y, ihyβ©, let β¨k, hik, hjkβ© := directed_order.directed i j in
β¨k, f i k hik x + f j k hjk y, by rw [linear_map.map_add, of_f, of_f, ihx, ihy]; reflβ©)
@[elab_as_eliminator]
protected theorem induction_on {C : direct_limit G f β Prop} (z : direct_limit G f)
(ih : β i x, C (of R ΞΉ G f i x)) : C z :=
let β¨i, x, hβ© := exists_of z in h βΈ ih i x
variables {P : Type uβ} [add_comm_group P] [module R P] (g : Ξ i, G i ββ[R] P)
variables (Hg : β i j hij x, g j (f i j hij x) = g i x)
include Hg
variables (R ΞΉ G f)
/-- The universal property of the direct limit: maps from the components to another module
that respect the directed system structure (i.e. make some diagram commute) give rise
to a unique map out of the direct limit. -/
def lift : direct_limit G f ββ[R] P :=
liftq _ (direct_sum.to_module R ΞΉ P g)
(span_le.2 $ Ξ» a β¨i, j, hij, x, hxβ©, by rw [β hx, mem_coe, linear_map.sub_mem_ker_iff,
direct_sum.to_module_lof, direct_sum.to_module_lof, Hg])
variables {R ΞΉ G f}
omit Hg
lemma lift_of {i} (x) : lift R ΞΉ G f g Hg (of R ΞΉ G f i x) = g i x :=
direct_sum.to_module_lof R _ _
theorem lift_unique (F : direct_limit G f ββ[R] P) (x) :
F x = lift R ΞΉ G f (Ξ» i, F.comp $ of R ΞΉ G f i)
(Ξ» i j hij x, by rw [linear_map.comp_apply, of_f]; refl) x :=
direct_limit.induction_on x $ Ξ» i x, by rw lift_of; refl
section totalize
open_locale classical
variables (G f)
noncomputable def totalize : Ξ i j, G i ββ[R] G j :=
Ξ» i j, if h : i β€ j then f i j h else 0
variables {G f}
lemma totalize_apply (i j x) :
totalize G f i j x = if h : i β€ j then f i j h x else 0 :=
if h : i β€ j
then by dsimp only [totalize]; rw [dif_pos h, dif_pos h]
else by dsimp only [totalize]; rw [dif_neg h, dif_neg h, linear_map.zero_apply]
end totalize
lemma to_module_totalize_of_le {x : direct_sum ΞΉ G} {i j : ΞΉ}
(hij : i β€ j) (hx : β k β x.support, k β€ i) :
direct_sum.to_module R ΞΉ (G j) (Ξ» k, totalize G f k j) x =
f i j hij (direct_sum.to_module R ΞΉ (G i) (Ξ» k, totalize G f k i) x) :=
begin
rw [β @dfinsupp.sum_single ΞΉ G _ _ _ x],
unfold dfinsupp.sum,
simp only [linear_map.map_sum],
refine finset.sum_congr rfl (Ξ» k hk, _),
rw direct_sum.single_eq_lof R k (x k),
simp [totalize_apply, hx k hk, le_trans (hx k hk) hij, directed_system.map_map f]
end
lemma of.zero_exact_aux {x : direct_sum ΞΉ G} (H : submodule.quotient.mk x = (0 : direct_limit G f)) :
β j, (β k β x.support, k β€ j) β§ direct_sum.to_module R ΞΉ (G j) (Ξ» i, totalize G f i j) x = (0 : G j) :=
nonempty.elim (by apply_instance) $ assume ind : ΞΉ,
span_induction ((quotient.mk_eq_zero _).1 H)
(Ξ» x β¨i, j, hij, y, hxyβ©, let β¨k, hik, hjkβ© := directed_order.directed i j in
β¨k, begin
clear_,
subst hxy,
split,
{ intros i0 hi0,
rw [dfinsupp.mem_support_iff, dfinsupp.sub_apply, β direct_sum.single_eq_lof,
β direct_sum.single_eq_lof, dfinsupp.single_apply, dfinsupp.single_apply] at hi0,
split_ifs at hi0 with hi hj hj, { rwa hi at hik }, { rwa hi at hik }, { rwa hj at hjk },
exfalso, apply hi0, rw sub_zero },
simp [linear_map.map_sub, totalize_apply, hik, hjk,
directed_system.map_map f, direct_sum.apply_eq_component,
direct_sum.component.of],
endβ©)
β¨ind, Ξ» _ h, (finset.not_mem_empty _ h).elim, linear_map.map_zero _β©
(Ξ» x y β¨i, hi, hxiβ© β¨j, hj, hyjβ©,
let β¨k, hik, hjkβ© := directed_order.directed i j in
β¨k, Ξ» l hl,
(finset.mem_union.1 (dfinsupp.support_add hl)).elim
(Ξ» hl, le_trans (hi _ hl) hik)
(Ξ» hl, le_trans (hj _ hl) hjk),
by simp [linear_map.map_add, hxi, hyj,
to_module_totalize_of_le hik hi,
to_module_totalize_of_le hjk hj]β©)
(Ξ» a x β¨i, hi, hxiβ©,
β¨i, Ξ» k hk, hi k (dfinsupp.support_smul hk),
by simp [linear_map.map_smul, hxi]β©)
/-- A component that corresponds to zero in the direct limit is already zero in some
bigger module in the directed system. -/
theorem of.zero_exact {i x} (H : of R ΞΉ G f i x = 0) :
β j hij, f i j hij x = (0 : G j) :=
let β¨j, hj, hxjβ© := of.zero_exact_aux H in
if hx0 : x = 0 then β¨i, le_refl _, by simp [hx0]β©
else
have hij : i β€ j, from hj _ $
by simp [direct_sum.apply_eq_component, hx0],
β¨j, hij, by simpa [totalize_apply, hij] using hxjβ©
end direct_limit
end module
namespace add_comm_group
variables [Ξ i, add_comm_group (G i)]
/-- The direct limit of a directed system is the abelian groups glued together along the maps. -/
def direct_limit (f : Ξ i j, i β€ j β G i β G j)
[Ξ i j hij, is_add_group_hom (f i j hij)] [directed_system G f] : Type* :=
@module.direct_limit β€ _ ΞΉ _ _ _ G _ _ _
(Ξ» i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map)
β¨directed_system.map_self f, directed_system.map_map fβ©
namespace direct_limit
variables (f : Ξ i j, i β€ j β G i β G j)
variables [Ξ i j hij, is_add_group_hom (f i j hij)] [directed_system G f]
lemma directed_system :
module.directed_system G (Ξ» i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) :=
β¨directed_system.map_self f, directed_system.map_map fβ©
local attribute [instance] directed_system
instance : add_comm_group (direct_limit G f) :=
module.direct_limit.add_comm_group G (Ξ» i j hij, (add_monoid_hom.of $f i j hij).to_int_linear_map)
/-- The canonical map from a component to the direct limit. -/
def of (i) : G i β direct_limit G f :=
module.direct_limit.of β€ ΞΉ G (Ξ» i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) i
variables {G f}
instance of.is_add_group_hom (i) : is_add_group_hom (of G f i) :=
linear_map.is_add_group_hom _
@[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x :=
module.direct_limit.of_f
@[simp] lemma of_zero (i) : of G f i 0 = 0 := is_add_group_hom.map_zero _
@[simp] lemma of_add (i x y) : of G f i (x + y) = of G f i x + of G f i y := is_add_hom.map_add _ _ _
@[simp] lemma of_neg (i x) : of G f i (-x) = -of G f i x := is_add_group_hom.map_neg _ _
@[simp] lemma of_sub (i x y) : of G f i (x - y) = of G f i x - of G f i y := is_add_group_hom.map_sub _ _ _
@[elab_as_eliminator]
protected theorem induction_on {C : direct_limit G f β Prop} (z : direct_limit G f)
(ih : β i x, C (of G f i x)) : C z :=
module.direct_limit.induction_on z ih
/-- A component that corresponds to zero in the direct limit is already zero in some
bigger module in the directed system. -/
theorem of.zero_exact (i x) (h : of G f i x = 0) : β j hij, f i j hij x = 0 :=
module.direct_limit.of.zero_exact h
variables (P : Type uβ) [add_comm_group P]
variables (g : Ξ i, G i β P) [Ξ i, is_add_group_hom (g i)]
variables (Hg : β i j hij x, g j (f i j hij x) = g i x)
variables (G f)
/-- The universal property of the direct limit: maps from the components to another abelian group
that respect the directed system structure (i.e. make some diagram commute) give rise
to a unique map out of the direct limit. -/
def lift : direct_limit G f β P :=
module.direct_limit.lift β€ ΞΉ G (Ξ» i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map)
(Ξ» i, (add_monoid_hom.of $ g i).to_int_linear_map) Hg
variables {G f}
instance lift.is_add_group_hom : is_add_group_hom (lift G f P g Hg) :=
linear_map.is_add_group_hom _
@[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x :=
module.direct_limit.lift_of _ _ _
@[simp] lemma lift_zero : lift G f P g Hg 0 = 0 := is_add_group_hom.map_zero _
@[simp] lemma lift_add (x y) : lift G f P g Hg (x + y) = lift G f P g Hg x + lift G f P g Hg y := is_add_hom.map_add _ _ _
@[simp] lemma lift_neg (x) : lift G f P g Hg (-x) = -lift G f P g Hg x := is_add_group_hom.map_neg _ _
@[simp] lemma lift_sub (x y) : lift G f P g Hg (x - y) = lift G f P g Hg x - lift G f P g Hg y := is_add_group_hom.map_sub _ _ _
lemma lift_unique (F : direct_limit G f β P) [is_add_group_hom F] (x) :
F x = @lift _ _ _ _ G _ _ f _ _ P _ (Ξ» i x, F $ of G f i x) (Ξ» i, is_add_group_hom.comp _ _)
(Ξ» i j hij x, by dsimp; rw of_f) x :=
direct_limit.induction_on x $ Ξ» i x, by rw lift_of
end direct_limit
end add_comm_group
namespace ring
variables [Ξ i, comm_ring (G i)]
variables (f : Ξ i j, i β€ j β G i β G j)
variables [Ξ i j hij, is_ring_hom (f i j hij)]
variables [directed_system G f]
open free_comm_ring
/-- The direct limit of a directed system is the rings glued together along the maps. -/
def direct_limit : Type (max v w) :=
(ideal.span { a | (β i j H x, of (β¨j, f i j H xβ© : Ξ£ i, G i) - of β¨i, xβ© = a) β¨
(β i, of (β¨i, 1β© : Ξ£ i, G i) - 1 = a) β¨
(β i x y, of (β¨i, x + yβ© : Ξ£ i, G i) - (of β¨i, xβ© + of β¨i, yβ©) = a) β¨
(β i x y, of (β¨i, x * yβ© : Ξ£ i, G i) - (of β¨i, xβ© * of β¨i, yβ©) = a) }).quotient
namespace direct_limit
instance : comm_ring (direct_limit G f) :=
ideal.quotient.comm_ring _
instance : ring (direct_limit G f) :=
comm_ring.to_ring _
/-- The canonical map from a component to the direct limit. -/
def of (i) (x : G i) : direct_limit G f :=
ideal.quotient.mk _ $ of β¨i, xβ©
variables {G f}
instance of.is_ring_hom (i) : is_ring_hom (of G f i) :=
{ map_one := ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inl β¨i, rflβ©,
map_mul := Ξ» x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inr β¨i, x, y, rflβ©,
map_add := Ξ» x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inl β¨i, x, y, rflβ© }
@[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x :=
ideal.quotient.eq.2 $ subset_span $ or.inl β¨i, j, hij, x, rflβ©
@[simp] lemma of_zero (i) : of G f i 0 = 0 := is_ring_hom.map_zero _
@[simp] lemma of_one (i) : of G f i 1 = 1 := is_ring_hom.map_one _
@[simp] lemma of_add (i x y) : of G f i (x + y) = of G f i x + of G f i y := is_ring_hom.map_add _
@[simp] lemma of_neg (i x) : of G f i (-x) = -of G f i x := is_ring_hom.map_neg _
@[simp] lemma of_sub (i x y) : of G f i (x - y) = of G f i x - of G f i y := is_ring_hom.map_sub _
@[simp] lemma of_mul (i x y) : of G f i (x * y) = of G f i x * of G f i y := is_ring_hom.map_mul _
@[simp] lemma of_pow (i x) (n : β) : of G f i (x ^ n) = of G f i x ^ n := is_semiring_hom.map_pow _ _ _
/-- Every element of the direct limit corresponds to some element in
some component of the directed system. -/
theorem exists_of (z : direct_limit G f) : β i x, of G f i x = z :=
nonempty.elim (by apply_instance) $ assume ind : ΞΉ,
quotient.induction_on' z $ Ξ» x, free_abelian_group.induction_on x
β¨ind, 0, of_zero indβ©
(Ξ» s, multiset.induction_on s
β¨ind, 1, of_one indβ©
(Ξ» a s ih, let β¨i, xβ© := a, β¨j, y, hsβ© := ih, β¨k, hik, hjkβ© := directed_order.directed i j in
β¨k, f i k hik x * f j k hjk y, by rw [of_mul, of_f, of_f, hs]; reflβ©))
(Ξ» s β¨i, x, ihβ©, β¨i, -x, by rw [of_neg, ih]; reflβ©)
(Ξ» p q β¨i, x, ihxβ© β¨j, y, ihyβ©, let β¨k, hik, hjkβ© := directed_order.directed i j in
β¨k, f i k hik x + f j k hjk y, by rw [of_add, of_f, of_f, ihx, ihy]; reflβ©)
@[elab_as_eliminator] theorem induction_on {C : direct_limit G f β Prop} (z : direct_limit G f)
(ih : β i x, C (of G f i x)) : C z :=
let β¨i, x, hxβ© := exists_of z in hx βΈ ih i x
section of_zero_exact
open_locale classical
variables (G f)
lemma of.zero_exact_aux2 {x : free_comm_ring Ξ£ i, G i} {s t} (hxs : is_supported x s) {j k}
(hj : β z : Ξ£ i, G i, z β s β z.1 β€ j) (hk : β z : Ξ£ i, G i, z β t β z.1 β€ k)
(hjk : j β€ k) (hst : s β t) :
f j k hjk (lift (Ξ» ix : s, f ix.1.1 j (hj ix ix.2) ix.1.2) (restriction s x)) =
lift (Ξ» ix : t, f ix.1.1 k (hk ix ix.2) ix.1.2) (restriction t x) :=
begin
refine ring.in_closure.rec_on hxs _ _ _ _,
{ rw [restriction_one, lift_one, is_ring_hom.map_one (f j k hjk), restriction_one, lift_one] },
{ rw [restriction_neg, restriction_one, lift_neg, lift_one,
is_ring_hom.map_neg (f j k hjk), is_ring_hom.map_one (f j k hjk),
restriction_neg, restriction_one, lift_neg, lift_one] },
{ rintros _ β¨p, hps, rflβ© n ih,
rw [restriction_mul, lift_mul, is_ring_hom.map_mul (f j k hjk), ih, restriction_mul, lift_mul,
restriction_of, dif_pos hps, lift_of, restriction_of, dif_pos (hst hps), lift_of],
dsimp only, rw directed_system.map_map f, refl },
{ rintros x y ihx ihy,
rw [restriction_add, lift_add, is_ring_hom.map_add (f j k hjk), ihx, ihy, restriction_add, lift_add] }
end
variables {G f}
lemma of.zero_exact_aux {x : free_comm_ring Ξ£ i, G i} (H : ideal.quotient.mk _ x = (0 : direct_limit G f)) :
β j s, β H : (β k : Ξ£ i, G i, k β s β k.1 β€ j), is_supported x s β§
lift (Ξ» ix : s, f ix.1.1 j (H ix ix.2) ix.1.2) (restriction s x) = (0 : G j) :=
begin
refine span_induction (ideal.quotient.eq_zero_iff_mem.1 H) _ _ _ _,
{ rintros x (β¨i, j, hij, x, rflβ© | β¨i, rflβ© | β¨i, x, y, rflβ© | β¨i, x, y, rflβ©),
{ refine β¨j, {β¨i, xβ©, β¨j, f i j hij xβ©}, _,
is_supported_sub (is_supported_of.2 $ or.inr rfl) (is_supported_of.2 $ or.inl rfl), _β©,
{ rintros k (rfl | β¨rfl | _β©), exact hij, refl },
{ rw [restriction_sub, lift_sub, restriction_of, dif_pos, restriction_of, dif_pos, lift_of, lift_of],
dsimp only, rw directed_system.map_map f, exact sub_self _,
exacts [or.inr rfl, or.inl rfl] } },
{ refine β¨i, {β¨i, 1β©}, _, is_supported_sub (is_supported_of.2 rfl) is_supported_one, _β©,
{ rintros k (rfl|h), refl },
{ rw [restriction_sub, lift_sub, restriction_of, dif_pos, restriction_one, lift_of, lift_one],
dsimp only, rw [is_ring_hom.map_one (f i i _), sub_self], exacts [_inst_7 i i _, rfl] } },
{ refine β¨i, {β¨i, x+yβ©, β¨i, xβ©, β¨i, yβ©}, _,
is_supported_sub (is_supported_of.2 $ or.inl rfl)
(is_supported_add (is_supported_of.2 $ or.inr $ or.inl rfl)
(is_supported_of.2 $ or.inr $ or.inr rfl)), _β©,
{ rintros k (rfl | β¨rfl | β¨rfl | hkβ©β©); refl },
{ rw [restriction_sub, restriction_add, restriction_of, restriction_of, restriction_of,
dif_pos, dif_pos, dif_pos, lift_sub, lift_add, lift_of, lift_of, lift_of],
dsimp only, rw is_ring_hom.map_add (f i i _), exact sub_self _,
exacts [or.inl rfl, by apply_instance, or.inr (or.inr rfl), or.inr (or.inl rfl)] } },
{ refine β¨i, {β¨i, x*yβ©, β¨i, xβ©, β¨i, yβ©}, _,
is_supported_sub (is_supported_of.2 $ or.inl rfl)
(is_supported_mul (is_supported_of.2 $ or.inr $ or.inl rfl)
(is_supported_of.2 $ or.inr $ or.inr rfl)), _β©,
{ rintros k (rfl | β¨rfl | β¨rfl | hkβ©β©); refl },
{ rw [restriction_sub, restriction_mul, restriction_of, restriction_of, restriction_of,
dif_pos, dif_pos, dif_pos, lift_sub, lift_mul, lift_of, lift_of, lift_of],
dsimp only, rw is_ring_hom.map_mul (f i i _),
exacts [sub_self _, or.inl rfl, by apply_instance, or.inr (or.inr rfl),
or.inr (or.inl rfl)] } } },
{ refine nonempty.elim (by apply_instance) (assume ind : ΞΉ, _),
refine β¨ind, β
, Ξ» _, false.elim, is_supported_zero, _β©,
rw [restriction_zero, lift_zero] },
{ rintros x y β¨i, s, hi, hxs, ihsβ© β¨j, t, hj, hyt, ihtβ©,
rcases directed_order.directed i j with β¨k, hik, hjkβ©,
have : β z : Ξ£ i, G i, z β s βͺ t β z.1 β€ k,
{ rintros z (hz | hz), exact le_trans (hi z hz) hik, exact le_trans (hj z hz) hjk },
refine β¨k, s βͺ t, this, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t)
(is_supported_upwards hyt $ set.subset_union_right s t), _β©,
{ rw [restriction_add, lift_add,
β of.zero_exact_aux2 G f hxs hi this hik (set.subset_union_left s t),
β of.zero_exact_aux2 G f hyt hj this hjk (set.subset_union_right s t),
ihs, is_ring_hom.map_zero (f i k hik), iht, is_ring_hom.map_zero (f j k hjk), zero_add] } },
{ rintros x y β¨j, t, hj, hyt, ihtβ©, rw smul_eq_mul,
rcases exists_finset_support x with β¨s, hxsβ©,
rcases (s.image sigma.fst).exists_le with β¨i, hiβ©,
rcases directed_order.directed i j with β¨k, hik, hjkβ©,
have : β z : Ξ£ i, G i, z β βs βͺ t β z.1 β€ k,
{ rintros z (hz | hz), exact le_trans (hi z.1 $ finset.mem_image.2 β¨z, hz, rflβ©) hik, exact le_trans (hj z hz) hjk },
refine β¨k, βs βͺ t, this, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left βs t)
(is_supported_upwards hyt $ set.subset_union_right βs t), _β©,
rw [restriction_mul, lift_mul,
β of.zero_exact_aux2 G f hyt hj this hjk (set.subset_union_right βs t),
iht, is_ring_hom.map_zero (f j k hjk), mul_zero] }
end
/-- A component that corresponds to zero in the direct limit is already zero in some
bigger module in the directed system. -/
lemma of.zero_exact {i x} (hix : of G f i x = 0) : β j, β hij : i β€ j, f i j hij x = 0 :=
let β¨j, s, H, hxs, hxβ© := of.zero_exact_aux hix in
have hixs : (β¨i, xβ© : Ξ£ i, G i) β s, from is_supported_of.1 hxs,
β¨j, H β¨i, xβ© hixs, by rw [restriction_of, dif_pos hixs, lift_of] at hx; exact hxβ©
end of_zero_exact
/-- If the maps in the directed system are injective, then the canonical maps
from the components to the direct limits are injective. -/
theorem of_injective (hf : β i j hij, function.injective (f i j hij)) (i) :
function.injective (of G f i) :=
begin
suffices : β x, of G f i x = 0 β x = 0,
{ intros x y hxy, rw β sub_eq_zero_iff_eq, apply this,
rw [is_ring_hom.map_sub (of G f i), hxy, sub_self] },
intros x hx, rcases of.zero_exact hx with β¨j, hij, hfxβ©,
apply hf i j hij, rw [hfx, is_ring_hom.map_zero (f i j hij)]
end
variables (P : Type uβ) [comm_ring P]
variables (g : Ξ i, G i β P) [Ξ i, is_ring_hom (g i)]
variables (Hg : β i j hij x, g j (f i j hij x) = g i x)
include Hg
open free_comm_ring
variables (G f)
/-- The universal property of the direct limit: maps from the components to another ring
that respect the directed system structure (i.e. make some diagram commute) give rise
to a unique map out of the direct limit.
We don't use this function as the canonical form because Lean 3 fails to automatically coerce
it to a function; use `lift` instead. -/
def lift_hom : direct_limit G f β+* P :=
ideal.quotient.lift _ (free_comm_ring.lift_hom $ Ξ» x, g x.1 x.2) begin
suffices : ideal.span _ β€
ideal.comap (free_comm_ring.lift_hom (Ξ» (x : Ξ£ (i : ΞΉ), G i), g (x.fst) (x.snd))) β₯,
{ intros x hx, exact (mem_bot P).1 (this hx) },
rw ideal.span_le, intros x hx,
rw [mem_coe, ideal.mem_comap, mem_bot],
rcases hx with β¨i, j, hij, x, rflβ© | β¨i, rflβ© | β¨i, x, y, rflβ© | β¨i, x, y, rflβ©;
simp only [coe_lift_hom, lift_sub, lift_of, Hg, lift_one, lift_add, lift_mul,
is_ring_hom.map_one (g i), is_ring_hom.map_add (g i), is_ring_hom.map_mul (g i), sub_self]
end
/-- The universal property of the direct limit: maps from the components to another ring
that respect the directed system structure (i.e. make some diagram commute) give rise
to a unique map out of the direct limit. -/
def lift : direct_limit G f β P := lift_hom G f P g Hg
instance lift_is_ring_hom : is_ring_hom (lift G f P g Hg) := (lift_hom G f P g Hg).is_ring_hom
variables {G f}
omit Hg
@[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := free_comm_ring.lift_of _ _
@[simp] lemma lift_zero : lift G f P g Hg 0 = 0 := (lift_hom G f P g Hg).map_zero
@[simp] lemma lift_one : lift G f P g Hg 1 = 1 := (lift_hom G f P g Hg).map_one
@[simp] lemma lift_add (x y) : lift G f P g Hg (x + y) = lift G f P g Hg x + lift G f P g Hg y :=
(lift_hom G f P g Hg).map_add x y
@[simp] lemma lift_neg (x) : lift G f P g Hg (-x) = -lift G f P g Hg x :=
(lift_hom G f P g Hg).map_neg x
@[simp] lemma lift_sub (x y) : lift G f P g Hg (x - y) = lift G f P g Hg x - lift G f P g Hg y :=
(lift_hom G f P g Hg).map_sub x y
@[simp] lemma lift_mul (x y) : lift G f P g Hg (x * y) = lift G f P g Hg x * lift G f P g Hg y :=
(lift_hom G f P g Hg).map_mul x y
@[simp] lemma lift_pow (x) (n : β) : lift G f P g Hg (x ^ n) = lift G f P g Hg x ^ n :=
(lift_hom G f P g Hg).map_pow x n
local attribute [instance, priority 100] is_ring_hom.comp
theorem lift_unique (F : direct_limit G f β P) [is_ring_hom F] (x) :
F x = lift G f P (Ξ» i x, F $ of G f i x) (Ξ» i j hij x, by rw [of_f]) x :=
direct_limit.induction_on x $ Ξ» i x, by rw lift_of
end direct_limit
end ring
namespace field
variables [Ξ i, field (G i)]
variables (f : Ξ i j, i β€ j β G i β G j) [Ξ i j hij, is_ring_hom (f i j hij)]
variables [directed_system G f]
namespace direct_limit
instance nontrivial : nontrivial (ring.direct_limit G f) :=
β¨β¨0, 1, nonempty.elim (by apply_instance) $ assume i : ΞΉ, begin
change (0 : ring.direct_limit G f) β 1,
rw β ring.direct_limit.of_one,
intros H, rcases ring.direct_limit.of.zero_exact H.symm with β¨j, hij, hfβ©,
rw is_ring_hom.map_one (f i j hij) at hf,
exact one_ne_zero hf
end β©β©
theorem exists_inv {p : ring.direct_limit G f} : p β 0 β β y, p * y = 1 :=
ring.direct_limit.induction_on p $ Ξ» i x H,
β¨ring.direct_limit.of G f i (xβ»ΒΉ), by erw [β ring.direct_limit.of_mul,
mul_inv_cancel (assume h : x = 0, H $ by rw [h, ring.direct_limit.of_zero]),
ring.direct_limit.of_one]β©
section
open_locale classical
noncomputable def inv (p : ring.direct_limit G f) : ring.direct_limit G f :=
if H : p = 0 then 0 else classical.some (direct_limit.exists_inv G f H)
protected theorem mul_inv_cancel {p : ring.direct_limit G f} (hp : p β 0) : p * inv G f p = 1 :=
by rw [inv, dif_neg hp, classical.some_spec (direct_limit.exists_inv G f hp)]
protected theorem inv_mul_cancel {p : ring.direct_limit G f} (hp : p β 0) : inv G f p * p = 1 :=
by rw [_root_.mul_comm, direct_limit.mul_inv_cancel G f hp]
protected noncomputable def field : field (ring.direct_limit G f) :=
{ inv := inv G f,
mul_inv_cancel := Ξ» p, direct_limit.mul_inv_cancel G f,
inv_zero := dif_pos rfl,
.. ring.direct_limit.comm_ring G f,
.. direct_limit.nontrivial G f }
end
end direct_limit
end field
|
309fcebb03f8dfdd180310d06ebf64b4c83dd14a | 26bff4ed296b8373c92b6b025f5d60cdf02104b9 | /tests/lean/run/rewrite10.lean | 38597d1308468d9e3394780dbd87d03b91d05374 | [
"Apache-2.0"
] | permissive | guiquanz/lean | b8a878ea24f237b84b0e6f6be2f300e8bf028229 | 242f8ba0486860e53e257c443e965a82ee342db3 | refs/heads/master | 1,526,680,092,098 | 1,427,492,833,000 | 1,427,493,281,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 818 | lean | import data.nat
open nat
section
variables (a b c d e : nat)
theorem T (H1 : a = b) (H2 : b = c + 1) (H3 : c = d) (H4 : e = 1 + d) : a = e :=
by rewrite β¨H1, H2, H3, add.comm, -H4β©
end
example (x y : β) : (x + y) * (x + y) = x * x + y * x + x * y + y * y :=
by rewrite β¨*mul.left_distrib, *mul.right_distrib, -add.assocβ©
definition even (a : nat) := βb, a = 2*b
theorem even_plus_even {a b : nat} (H1 : even a) (H2 : even b) : even (a + b) :=
exists.elim H1 (fun (w1 : nat) (Hw1 : a = 2*w1),
exists.elim H2 (fun (w2 : nat) (Hw2 : b = 2*w2),
exists.intro (w1 + w2)
begin
rewrite β¨Hw1, Hw2, mul.left_distribβ©
end))
theorem T2 (a b c : nat) (H1 : a = b) (H2 : b = c + 1) : a β 0 :=
calc
a = succ c : by rewrite β¨H1, H2, add_oneβ©
... β 0 : succ_ne_zero c
|
5ffbc90f578f4a02a99ed83bfc07fa5629759215 | c76cc4eaee3c806716844e49b5175747d1aa170a | /src/solutions_sheet_two.lean | 7771ede67a2b555e1b1bd067a73988a7dd7b460a | [] | no_license | ImperialCollegeLondon/M40002 | 0fb55848adbb0d8bc4a65ca5d7ed6edd18764c28 | a499db70323bd5ccae954c680ec9afbf15ffacca | refs/heads/master | 1,674,878,059,748 | 1,607,624,828,000 | 1,607,624,828,000 | 309,696,750 | 3 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,458 | lean | import data.real.basic
import data.nat.choose.sum -- binomial theorem
import data.real.ereal
import data.pnat.basic
-- namespace problem_sheet_two
section Q2
/-!
# Q2
-/
/-
2. Fix nonempty sets S_n β R, n= 1,2,3,....
Prove that sup{sup S1,sup S2,sup S3,...} = sup(β_{n=1}^{infty} S_n),
in the sense that if either exists then so does the other, and they are equal.
-/
/-
Let's first answer a better question with fewer restrictions,
using extended reals.
Then Sup {Sup (S_i) : i β I} = Sup (β_{i β I} S_i) is *always* true
-/
example (I : Type) (S : I β set (ereal)) :
Sup (set.range (Ξ» i, Sup (S i))) = Sup (β i, S i) :=
begin
apply le_antisymm,
{ rw Sup_le_iff,
rintro - β¨i, rflβ©,
dsimp only,
refine Sup_le_Sup _,
exact set.subset_Union S i },
{ rw Sup_le_iff,
rintros x β¨-, β¨i, rflβ©, (hix : x β S i)β©,
apply le_trans (le_Sup hix),
apply le_Sup _,
use i }
end
lemma exists_lub (S : set β) :
S.nonempty β§ (upper_bounds S).nonempty β (β B, is_lub S B) :=
begin
rintros β¨h1, h2β©,
cases real.exists_sup S h1 h2 with B hB,
use B,
split,
{ apply (hB B).1,
refl },
{ intros x hx,
rw hB,
exact hx }
end
-- "All the S_i have a sup and the set {sup S1, sup S2, ...} has a sup, if and
-- only if the union of the S_i has a sup"
theorem Q2a (S : β+ β set β)
(hS : β i : β+, (S i).nonempty) :
(β n : β+, β B, is_lub (S n) B) β§ (β B, is_lub (set.range (Ξ» i, Sup (S i))) B) β
β B, is_lub (β i, S i) B :=
begin
split,
{ rintro β¨h1, B, hB1, hB2β©,
apply exists_lub,
cases hS 37 with x hx,
use [x, S 37, 37, hx],
use B,
rintros y β¨-, β¨i, rflβ©, (hiY : y β S i)β©,
specialize hB1 β¨i, rflβ©,
refine le_trans _ hB1,
apply real.le_Sup _ _ hiY,
rcases h1 i with β¨C, hC1, hC2β©,
use C,
exact hC1 },
{ rintro β¨B, hB1, hB2β©,
split,
{ intro n,
apply exists_lub,
use hS n,
use B,
apply upper_bounds_mono_set _ hB1,
exact set.subset_Union S n },
{ apply exists_lub,
split,
{ apply set.range_nonempty },
{ use B,
rintro - β¨i, rflβ©,
dsimp only,
rw real.Sup_le _ (hS i),
{ intros z hz,
apply hB1,
use [S i, i, hz] },
{ use B,
intros z hz,
apply hB1,
use [S i, i, hz] } } } }
end
-- assuming both sides make sense, prove the sups are equal
theorem Q2b (S : β+ β set β)
(hS : β i : β+, (S i).nonempty)
(hLHS: β n : β+, β B, is_lub (S n) B) (hLHS' : β B, is_lub (set.range (Ξ» i, Sup (S i))) B)
(hRHS : β B, is_lub (β i, S i) B) :
Sup (set.range (Ξ» i, Sup (S i))) = Sup (β i, S i) :=
begin
-- suffices to prove LHS β€ RHS and RHS β€ LHS
apply le_antisymm,
{ -- to prove Sup β€ something, suffices to prove all elements are β€ it
rw real.Sup_le,
rintro - β¨j, rflβ©,
dsimp only,
-- so it suffices to prove Sup (S j) β€ Sup (β_i S i)
rw real.Sup_le,
-- so it even suffices to prove every element of S j is β€ the Sup
intros x hx,
-- but this is clear because the elements are in the set
apply real.le_Sup, swap,
use [S j, j, hx],
-- now just check that all sets were nonempty and had least upper bounds,
-- this follows from our assumptions.
{ rcases hRHS with β¨B, hB1, hB2β©,
use B,
exact hB1 },
{ exact hS j},
{ rcases hLHS j with β¨B, hB1, hB2β©,
use B,
exact hB1 },
{ apply set.range_nonempty },
{ rcases hLHS' with β¨B, hB1, hB2β©,
use B,
exact hB1 } },
{ -- to prove Sup β€ somthing, suffices to prove all elements are β€ it
rw real.Sup_le,
-- so assume z is in one of the S i's, call it S j
rintro z β¨-, β¨j, rflβ©, (hzj : z β S j)β©,
-- then z β€ Sup (S j)
apply le_trans (real.le_Sup _ _ hzj),
-- so it's certainly β€ Sup of a set containing Sup (S j)
apply real.le_Sup,
-- now tidy up
{ rcases hLHS' with β¨B, hB1, hB2β©,
use B,
exact hB1 },
{ use j },
{ rcases hLHS j with β¨B, hB1, hB2β©,
use B,
exact hB1 },
{ cases hS 37 with x hx,
use [x, S 37, 37, hx],
},
{ rcases hRHS with β¨B, hB1, hB2β©,
use B,
exact hB1 } }
end
end Q2
/-!
# Q3
Take bounded, nonempty `S, T β β`.
Define `S + T := { s + t : s β S, t β T}`.
Prove `sup(S+T) = sup(S)+ sup(T)`
-/
theorem is_lub_def {S : set β} {a : β} :
is_lub S a β a β upper_bounds S β§ β x, x β upper_bounds S β a β€ x :=
begin
refl
end
-- #check mem_upper_bounds -- a β upper_bounds S β β x, x β S β x β€ a
--example (P Q : Prop) : P β Q β Β¬ Q β Β¬ P :=
--by library_search
theorem useful_lemma {S : set β} {a : β} (haS : is_lub S a) (t : β)
(ht : t < a) : β s, s β S β§ t < s :=
begin
rw is_lub_def at haS,
cases haS with haS1 haS2,
specialize haS2 t,
replace haS2 := mt haS2,
push_neg at haS2,
specialize haS2 ht,
rw mem_upper_bounds at haS2,
push_neg at haS2,
exact haS2,
end
theorem problem_sheet_two.Q3 (S T : set β) (a b : β) :
is_lub S a β is_lub T b β is_lub (S + T) (a + b) :=
begin
intros hSa hTb,
rw is_lub_def,
split,
{ rw mem_upper_bounds,
intro x,
intro hx,
rcases hx with β¨s, t, hsS, htT, rflβ©,
rw is_lub_def at hSa hTb,
rcases hSa with β¨ha1, ha2β©,
rcases hTb with β¨hb1, hb2β©,
rw mem_upper_bounds at ha1 hb1,
specialize ha1 s hsS,
specialize hb1 t htT,
linarith,
},
{ intro x,
intro hx,
rw mem_upper_bounds at hx,
by_contra,
push_neg at h,
set Ξ΅ := a + b - x with hΞ΅,
have hΞ΅2 : 0 < Ξ΅,
linarith,
set a' := a - Ξ΅/2 with ha',
set b' := b - Ξ΅/2 with hb',
rcases useful_lemma hSa a' (by linarith) with β¨s', hs', hs'2β©,
rcases useful_lemma hTb b' (by linarith) with β¨t', ht', ht'2β©,
specialize hx (s' + t') β¨s', t', hs', ht', rflβ©,
linarith,
}
end
/-!
# Q4
Fix `a β (0,β)` and `n : β`. We will prove
`β x : β, x^n = a`.
-/
section Q4
noncomputable theory
section one
-- this first section, a and n are going to be variables
variables {a : β} (ha : 0 < a) {n : β} (hn : 0 < n)
include ha hn
/- Note: We do things in a slightly different order to the question
on the sheet, because the way it's set up on the sheet, `x` is
defined to be `Sup(S_a)` very early on, which technically forces
us to prove that `1/x` is `Sup(S_{1/a})` -- this is unnecessary
with the approach below. I broke this question into five "parts".
-/
/-
2) For `Ξ΅ β (0,1)` and arbitrary `x β₯ 0` show `(x+Ξ΅)βΏ β€ x^n + Ξ΅[(x + 1)βΏ β xβΏ].`
(Hint: multiply out.)
-/
theorem part2 {x : β} (x_nonneg : 0 β€ x) (Ξ΅ : β) (hΞ΅0 : 0 < Ξ΅) (hΞ΅1 : Ξ΅ < 1) :
(x + Ξ΅)^n β€ x^n + Ξ΅ * ((x + 1)^n - x^n) :=
begin
rw [ add_pow, add_pow ],
simp_rw [one_pow, mul_one],
rw [finset.sum_range_succ, nat.sub_self, pow_zero, mul_one],
rw [nat.choose_self, nat.cast_one, mul_one],
apply add_le_add_left,
rw [finset.sum_range_succ, nat.choose_self, nat.cast_one, mul_one],
rw [add_sub_cancel', finset.mul_sum],
apply finset.sum_le_sum,
intros i hi,
rw [finset.mem_range, nat.lt_iff_add_one_le, le_iff_exists_add] at hi,
-- rcases hi with β¨c, rflβ©, -- rcases bug?
cases hi with c hc,
have hni : n - i = c + 1,
omega,
rw [hni, mul_comm (x ^ i), mul_assoc, pow_succ, mul_comm Ξ΅, mul_assoc],
apply mul_le_of_le_one_left,
{ apply mul_nonneg (le_of_lt hΞ΅0),
apply mul_nonneg (pow_nonneg x_nonneg i),
norm_cast, simp },
{ apply pow_le_one; linarith }
end
/-
3) Hence show that if `x β₯ 0` and `xβΏ < a` then
`β Ξ΅ β (0,1)` such that `(x+Ξ΅)βΏ < a.` (*)
-/
theorem part3 {x : β} (x_nonneg : 0 β€ x) (h : x ^ n < a) :
β Ξ΅ : β, 0 < Ξ΅ β§ Ξ΅ < 1 β§ (x+Ξ΅)^n < a :=
begin
set Ξ΅ := min (1 / 2) ((a - x ^ n) / ((x + 1) ^ n - x ^ n) / 2) with hΞ΅,
use Ξ΅,
have hx1 : 0 < (x + 1) ^ n - x ^ n,
rw sub_pos,
apply pow_lt_pow_of_lt_left (lt_add_one _) x_nonneg hn,
have hΞ΅0 : 0 < Ξ΅,
rw [hΞ΅, lt_min_iff],
split, { linarith },
refine div_pos _ (by linarith),
refine div_pos (by linarith) hx1,
use hΞ΅0,
have hΞ΅1 : Ξ΅ < 1,
suffices : Ξ΅ β€ 1/2, linarith,
rw hΞ΅,
exact min_le_left _ _,
use hΞ΅1,
apply lt_of_le_of_lt (part2 ha hn x_nonneg Ξ΅ hΞ΅0 hΞ΅1),
rw β lt_sub_iff_add_lt',
rw β lt_div_iff hx1,
apply lt_of_le_of_lt (min_le_right _ _),
apply div_two_lt_of_pos,
exact div_pos (by linarith) hx1,
end
/-
4) If `x > 0` is arbitrary and `xβΏ > a`, deduce from (β) (i.e. part 3) that
`β Ξ΅ β (0,1)` such that `(1/x+Ξ΅)βΏ < 1/a`. (ββ)
Note that here it makes life much easier to have x a variable and not
the fixed Sup(S_a); with the approach on the sheet one would have to
technical prove that 1/x is Sup(S_{1/a}), which is not necessary
with this approach.
-/
theorem part4 {x : β} (hx : 0 < x) (h : a < x^n) :
β Ξ΅ : β, 0 < Ξ΅ β§ Ξ΅ < 1 β§ (1/x + Ξ΅)^n < 1/a :=
begin
have h1x_pos : 0 < 1/x,
rwa one_div_pos,
have h1xa : (1/x)^n < 1/a,
rw [div_pow, one_pow],
apply div_lt_div_of_lt_left ha h zero_lt_one,
exact part3 (one_div_pos.2 ha) hn (le_of_lt h1x_pos) h1xa,
end
end one
section two
-- in this section, a and n are going to be fixed parameters
parameters {a : β} (ha : 0 < a) {n : β} (hn : 0 < n)
include ha hn
/-
1) Set `Sβ := {s β [0,β) : s^n < a}` and show `Sβ` is nonempty and
bounded above, so we may define `x := sup Sβ`
-/
def S := {s : β | 0 β€ s β§ s ^ n < a}
theorem part1 : (β s : β, s β S) β§ (β B : β, β s β S, s β€ B ) :=
begin
split,
{ use 0,
split, { refl },
convert ha,
simp [hn] },
{ use a + 1,
rintro s β¨hs1, hs2β©,
by_contra hsa,
push_neg at hsa,
have hs3 : 1 β€ s,
linarith,
have hs4 : s β€ s ^ n,
cases n, cases hn,
suffices : 1 β€ s ^ n,
convert mul_le_mul (le_refl s) this (by linarith) hs1,
{ simp },
exact one_le_pow_of_one_le hs3 _,
linarith, }
end
def x := Sup S
theorem is_lub_x : is_lub S x :=
begin
cases part1 with nonempty bdd,
cases nonempty with x hx,
cases bdd with y hy,
exact real.is_lub_Sup hx hy,
end
lemma x_nonneg : 0 β€ x :=
begin
rcases is_lub_x with β¨h, -β©,
apply h,
split, refl,
convert ha,
simp [hn],
end
lemma easy (h : a < x^n) : x β 0 :=
begin
intro hx,
rw hx at h,
suffices : a < 0,
linarith,
convert h,
symmetry, -- todo add simp lemma to mathlib
simp [hn],
end
/-
5) Deduce contradictions from (β) and (ββ) to show that `xβΏ = a`.
-/
-- lemma le_of_pow_le_pow (n : β) (hn : 0 < n) (x y : β) (h : x^n β€ y^n) : x β€ y :=
-- begin
-- by_contra hxy,
-- push_neg at hxy,
-- sorry,
-- -- have h2 : pow_lt_pow
-- end
theorem part5 : x^n = a :=
begin
rcases lt_trichotomy (x^n) a with (hlt | heq | hgt),
{ exfalso,
obtain β¨Ξ΅, hΞ΅0, -, hΞ΅β© := part3 ha hn (x_nonneg) hlt,
have ZZZ := is_lub_x.1 β¨_, hΞ΅β©, linarith,
linarith [x_nonneg] },
{ assumption },
{ exfalso,
have hxpow : 0 < x,
rw lt_iff_le_and_ne,
exact β¨x_nonneg, (easy hgt).symmβ©,
obtain β¨Ξ΅, hΞ΅0, -, hΞ΅β© := part4 ha hn hxpow hgt,
have huseful : 0 < 1 / x + Ξ΅,
refine add_pos _ hΞ΅0,
exact one_div_pos.mpr hxpow,
have ha' : a < (1 / (1 / x + Ξ΅)) ^ n,
{ rw [div_pow, one_pow],
rwa lt_one_div _ ha at hΞ΅,
apply pow_pos,
assumption },
have hproblem : (1 / (1 / x + Ξ΅)) β upper_bounds S,
{ rintro t β¨ht0, htaβ©,
apply le_of_lt,
apply lt_of_pow_lt_pow n,
{ apply le_of_lt,
rwa one_div_pos },
{ linarith } },
have ZZZ := is_lub_x.2 hproblem,
rw le_one_div at ZZZ,
{ linarith },
{ assumption },
{ assumption } }
end
end two
end Q4
section Q6
/-!
# Q6
"Do (a) from first principles and then do parts (b)-(g) from (a)"
-/
-- We introduce the usual mathematical notation for absolute value
local notation `|` x `|` := abs x
/-
Useful for this one: `unfold`, `split_ifs` if you want to prove
from first principles, or guessing the name of the library function
if you want to use the library.
-/
theorem Q6a (x y : β) : | x + y | β€ | x | + | y | :=
begin
unfold abs max,
split_ifs;
linarith
end
-- all the rest you're supposed to do using Q6a somehow:
-- `simp` and `linarith` are useful.
theorem Q6b (x y : β) : |x + y| β₯ |x| - |y| :=
begin
have h := Q6a (x + y) (-y),
simp at h,
linarith,
end
theorem Q6c (x y : β) : |x + y| β₯ |y| - |x| :=
begin
have h := Q6a (x + y) (-x),
simp at h,
linarith,
end
theorem Q6d (x y : β) : |x - y| β₯ | |x| - |y| | :=
begin
show _ β€ _,
rw abs_le,
split,
{ -- |y|<=|x|+|y-x|
have h := Q6a x (y-x),
simp at h,
rw abs_sub,
linarith },
{ have h := Q6a (x-y) y,
simp at h,
linarith }
end
theorem Q6e (x y : β) : |x| β€ |y| + |x - y| :=
begin
have h := Q6a y (x-y),
convert h,
ring,
end
theorem Q6f (x y : β) : |x| β₯ |y| - |x - y| :=
begin
have h := Q6a x (y-x),
simp at h,
rw abs_sub at h,
linarith,
end
theorem Q6g (x y z : β) : |x - y| β€ |x - z| + |y - z| :=
begin
have h := Q6a (x-z) (z-y),
rw abs_sub z y at h,
convert h,
ring,
end
end Q6 |
067382034884a4bba72af24eacd4f212486a9c6d | e61a235b8468b03aee0120bf26ec615c045005d2 | /tests/lean/run/parseCore.lean | a6953f6b2cd4b83f0fd1b95e5633b9979a8ea2f0 | [
"Apache-2.0"
] | permissive | SCKelemen/lean4 | 140dc63a80539f7c61c8e43e1c174d8500ec3230 | e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc | refs/heads/master | 1,660,973,595,917 | 1,590,278,033,000 | 1,590,278,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 330 | lean | import Init.Lean.Parser
def test : IO Unit :=
if System.Platform.isWindows then
pure () -- TODO investigate why the following doesn't work on Windows
else do
env β Lean.mkEmptyEnvironment;
_ β Lean.Parser.parseFile env (System.mkFilePath ["..", "..", "..", "src", "Init", "Core.lean"]);
IO.println "done"
#eval test
|
fc8fac4a0c6378e9321f8905c1734c8d59dcf7ee | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/PrePort.lean | c0fdd880d1fdd980b51cdb1471d8545d82613080 | [] | 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 | 191 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Daniel Selsam
-/
import Mathlib.PrePort.Numbers
|
41253d00d310c3324734d1783f775b0f2a6db916 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/set/pointwise.lean | 2aee3dc85b08b1d3daf06d7fe792fd2549bb1307 | [
"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 | 57,604 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Floris van Doorn
-/
import algebra.module.basic
import data.set.finite
import group_theory.submonoid.basic
/-!
# Pointwise operations of sets
This file defines pointwise algebraic operations on sets.
## Main declarations
For sets `s` and `t` and scalar `a`:
* `s * t`: Multiplication, set of all `x * y` where `x β s` and `y β t`.
* `s + t`: Addition, set of all `x + y` where `x β s` and `y β t`.
* `sβ»ΒΉ`: Inversion, set of all `xβ»ΒΉ` where `x β s`.
* `-s`: Negation, set of all `-x` where `x β s`.
* `s / t`: Division, set of all `x / y` where `x β s` and `y β t`.
* `s - t`: Subtraction, set of all `x - y` where `x β s` and `y β t`.
* `s β’ t`: Scalar multiplication, set of all `x β’ y` where `x β s` and `y β t`.
* `s +α΅₯ t`: Scalar addition, set of all `x +α΅₯ y` where `x β s` and `y β t`.
* `s -α΅₯ t`: Scalar subtraction, set of all `x -α΅₯ y` where `x β s` and `y β t`.
* `a β’ s`: Scaling, set of all `a β’ x` where `x β s`.
* `a +α΅₯ s`: Translation, set of all `a +α΅₯ x` where `x β s`.
For `Ξ±` a semigroup/monoid, `set Ξ±` is a semigroup/monoid.
As an unfortunate side effect, this means that `n β’ s`, where `n : β`, is ambiguous between
pointwise scaling and repeated pointwise addition; the former has `(2 : β) β’ {1, 2} = {2, 4}`, while
the latter has `(2 : β) β’ {1, 2} = {2, 3, 4}`.
We define `set_semiring Ξ±`, an alias of `set Ξ±`, which we endow with `βͺ` as addition and `*` as
multiplication. If `Ξ±` is a (commutative) monoid, `set_semiring Ξ±` is a (commutative) semiring.
Appropriate definitions and results are also transported to the additive theory via `to_additive`.
## Implementation notes
* The following expressions are considered in simp-normal form in a group:
`(Ξ» h, h * g) β»ΒΉ' s`, `(Ξ» h, g * h) β»ΒΉ' s`, `(Ξ» h, h * gβ»ΒΉ) β»ΒΉ' s`, `(Ξ» h, gβ»ΒΉ * h) β»ΒΉ' s`,
`s * t`, `sβ»ΒΉ`, `(1 : set _)` (and similarly for additive variants).
Expressions equal to one of these will be simplified.
* We put all instances in the locale `pointwise`, so that these instances are not available by
default. Note that we do not mark them as reducible (as argued by note [reducible non-instances])
since we expect the locale to be open whenever the instances are actually used (and making the
instances reducible changes the behavior of `simp`.
## Tags
set multiplication, set addition, pointwise addition, pointwise multiplication,
pointwise subtraction
-/
open function
variables {F Ξ± Ξ² Ξ³ : Type*}
namespace set
/-! ### `0`/`1` as sets -/
section one
variables [has_one Ξ±] {s : set Ξ±} {a : Ξ±}
/-- The set `1 : set Ξ±` is defined as `{1}` in locale `pointwise`. -/
@[to_additive "The set `0 : set Ξ±` is defined as `{0}` in locale `pointwise`."]
protected def has_one : has_one (set Ξ±) := β¨{1}β©
localized "attribute [instance] set.has_one set.has_zero" in pointwise
@[to_additive] lemma singleton_one : ({1} : set Ξ±) = 1 := rfl
@[simp, to_additive] lemma mem_one : a β (1 : set Ξ±) β a = 1 := iff.rfl
@[to_additive] lemma one_mem_one : (1 : Ξ±) β (1 : set Ξ±) := eq.refl _
@[simp, to_additive] lemma one_subset : 1 β s β (1 : Ξ±) β s := singleton_subset_iff
@[to_additive] lemma one_nonempty : (1 : set Ξ±).nonempty := β¨1, rflβ©
@[simp, to_additive] lemma image_one {f : Ξ± β Ξ²} : f '' 1 = {f 1} := image_singleton
@[to_additive] lemma subset_one_iff_eq : s β 1 β s = β
β¨ s = 1 := subset_singleton_iff_eq
@[to_additive] lemma nonempty.subset_one_iff (h : s.nonempty) : s β 1 β s = 1 :=
h.subset_singleton_iff
end one
/-! ### Set negation/inversion -/
section inv
/-- The pointwise inversion of set `sβ»ΒΉ` is defined as `{x | xβ»ΒΉ β s}` in locale `pointwise`. It i
equal to `{xβ»ΒΉ | x β s}`, see `set.image_inv`. -/
@[to_additive "The pointwise negation of set `-s` is defined as `{x | -x β s}` in locale
`pointwise`. It is equal to `{-x | x β s}`, see `set.image_neg`."]
protected def has_inv [has_inv Ξ±] : has_inv (set Ξ±) := β¨preimage has_inv.invβ©
localized "attribute [instance] set.has_inv set.has_neg" in pointwise
section has_inv
variables {ΞΉ : Sort*} [has_inv Ξ±] {s t : set Ξ±} {a : Ξ±}
@[simp, to_additive] lemma mem_inv : a β sβ»ΒΉ β aβ»ΒΉ β s := iff.rfl
@[simp, to_additive] lemma inv_preimage : has_inv.inv β»ΒΉ' s = sβ»ΒΉ := rfl
@[simp, to_additive] lemma inv_empty : (β
: set Ξ±)β»ΒΉ = β
:= rfl
@[simp, to_additive] lemma inv_univ : (univ : set Ξ±)β»ΒΉ = univ := rfl
@[simp, to_additive] lemma inter_inv : (s β© t)β»ΒΉ = sβ»ΒΉ β© tβ»ΒΉ := preimage_inter
@[simp, to_additive] lemma union_inv : (s βͺ t)β»ΒΉ = sβ»ΒΉ βͺ tβ»ΒΉ := preimage_union
@[simp, to_additive] lemma Inter_inv (s : ΞΉ β set Ξ±) : (β i, s i)β»ΒΉ = β i, (s i)β»ΒΉ := preimage_Inter
@[simp, to_additive] lemma Union_inv (s : ΞΉ β set Ξ±) : (β i, s i)β»ΒΉ = β i, (s i)β»ΒΉ := preimage_Union
@[simp, to_additive] lemma compl_inv : (sαΆ)β»ΒΉ = (sβ»ΒΉ)αΆ := preimage_compl
end has_inv
section has_involutive_inv
variables [has_involutive_inv Ξ±] {s t : set Ξ±} {a : Ξ±}
@[to_additive] lemma inv_mem_inv : aβ»ΒΉ β sβ»ΒΉ β a β s := by simp only [mem_inv, inv_inv]
@[simp, to_additive] lemma nonempty_inv : sβ»ΒΉ.nonempty β s.nonempty :=
inv_involutive.surjective.nonempty_preimage
@[to_additive] lemma nonempty.inv (h : s.nonempty) : sβ»ΒΉ.nonempty := nonempty_inv.2 h
@[to_additive] lemma finite.inv (hs : finite s) : finite sβ»ΒΉ :=
hs.preimage $ inv_injective.inj_on _
@[simp, to_additive]
lemma image_inv : has_inv.inv '' s = sβ»ΒΉ :=
congr_fun (image_eq_preimage_of_inverse inv_involutive.left_inverse inv_involutive.right_inverse) _
@[simp, to_additive]
instance : has_involutive_inv (set Ξ±) :=
{ inv := has_inv.inv,
inv_inv := Ξ» s, by { simp only [β inv_preimage, preimage_preimage, inv_inv, preimage_id'] } }
@[simp, to_additive]
lemma inv_subset_inv : sβ»ΒΉ β tβ»ΒΉ β s β t :=
(equiv.inv Ξ±).surjective.preimage_subset_preimage_iff
@[to_additive] lemma inv_subset : sβ»ΒΉ β t β s β tβ»ΒΉ := by { rw [β inv_subset_inv, inv_inv] }
@[simp, to_additive] lemma inv_singleton (a : Ξ±) : ({a} : set Ξ±)β»ΒΉ = {aβ»ΒΉ} :=
by rw [βimage_inv, image_singleton]
open mul_opposite
@[to_additive]
lemma image_op_inv : op '' sβ»ΒΉ = (op '' s)β»ΒΉ := by simp_rw [βimage_inv, image_comm op_inv]
end has_involutive_inv
end inv
open_locale pointwise
/-! ### Set addition/multiplication -/
section has_mul
variables {ΞΉ : Sort*} {ΞΊ : ΞΉ β Sort*} [has_mul Ξ±] {s sβ sβ t tβ tβ u : set Ξ±} {a b : Ξ±}
/-- The pointwise multiplication of sets `s * t` and `t` is defined as `{x * y | x β s, y β t}` in
locale `pointwise`. -/
@[to_additive "The pointwise addition of sets `s + t` is defined as `{x + y | x β s, y β t}` in
locale `pointwise`."]
protected def has_mul : has_mul (set Ξ±) := β¨image2 (*)β©
localized "attribute [instance] set.has_mul set.has_add" in pointwise
@[simp, to_additive]
lemma image2_mul : image2 has_mul.mul s t = s * t := rfl
@[to_additive]
lemma mem_mul : a β s * t β β x y, x β s β§ y β t β§ x * y = a := iff.rfl
@[to_additive] lemma mul_mem_mul : a β s β b β t β a * b β s * t := mem_image2_of_mem
@[to_additive add_image_prod]
lemma image_mul_prod : (Ξ» x : Ξ± Γ Ξ±, x.fst * x.snd) '' s ΓΛ’ t = s * t := image_prod _
@[simp, to_additive] lemma empty_mul : β
* s = β
:= image2_empty_left
@[simp, to_additive] lemma mul_empty : s * β
= β
:= image2_empty_right
@[simp, to_additive] lemma mul_eq_empty : s * t = β
β s = β
β¨ t = β
:= image2_eq_empty_iff
@[simp, to_additive] lemma mul_nonempty : (s * t).nonempty β s.nonempty β§ t.nonempty :=
image2_nonempty_iff
@[to_additive] lemma nonempty.mul : s.nonempty β t.nonempty β (s * t).nonempty := nonempty.image2
@[to_additive] lemma nonempty.of_mul_left : (s * t).nonempty β s.nonempty := nonempty.of_image2_left
@[to_additive] lemma nonempty.of_mul_right : (s * t).nonempty β t.nonempty :=
nonempty.of_image2_right
@[simp, to_additive] lemma mul_singleton : s * {b} = (* b) '' s := image2_singleton_right
@[simp, to_additive] lemma singleton_mul : {a} * t = ((*) a) '' t := image2_singleton_left
@[simp, to_additive] lemma singleton_mul_singleton : ({a} : set Ξ±) * {b} = {a * b} :=
image2_singleton
@[to_additive, mono] lemma mul_subset_mul : sβ β tβ β sβ β tβ β sβ * sβ β tβ * tβ := image2_subset
@[to_additive] lemma mul_subset_mul_left : tβ β tβ β s * tβ β s * tβ := image2_subset_left
@[to_additive] lemma mul_subset_mul_right : sβ β sβ β sβ * t β sβ * t := image2_subset_right
@[to_additive] lemma mul_subset_iff : s * t β u β β (x β s) (y β t), x * y β u := image2_subset_iff
attribute [mono] add_subset_add
@[to_additive] lemma union_mul : (sβ βͺ sβ) * t = sβ * t βͺ sβ * t := image2_union_left
@[to_additive] lemma mul_union : s * (tβ βͺ tβ) = s * tβ βͺ s * tβ := image2_union_right
@[to_additive] lemma inter_mul_subset : (sβ β© sβ) * t β sβ * t β© (sβ * t) :=
image2_inter_subset_left
@[to_additive] lemma mul_inter_subset : s * (tβ β© tβ) β s * tβ β© (s * tβ) :=
image2_inter_subset_right
@[to_additive] lemma Union_mul_left_image : (β a β s, ((*) a) '' t) = s * t := Union_image_left _
@[to_additive] lemma Union_mul_right_image : (β a β t, (* a) '' s) = s * t := Union_image_right _
@[to_additive] lemma Union_mul (s : ΞΉ β set Ξ±) (t : set Ξ±) : (β i, s i) * t = β i, s i * t :=
image2_Union_left _ _ _
@[to_additive] lemma mul_Union (s : set Ξ±) (t : ΞΉ β set Ξ±) : s * (β i, t i) = β i, s * t i :=
image2_Union_right _ _ _
@[to_additive]
lemma Unionβ_mul (s : Ξ i, ΞΊ i β set Ξ±) (t : set Ξ±) : (β i j, s i j) * t = β i j, s i j * t :=
image2_Unionβ_left _ _ _
@[to_additive]
lemma mul_Unionβ (s : set Ξ±) (t : Ξ i, ΞΊ i β set Ξ±) : s * (β i j, t i j) = β i j, s * t i j :=
image2_Unionβ_right _ _ _
@[to_additive]
lemma Inter_mul_subset (s : ΞΉ β set Ξ±) (t : set Ξ±) : (β i, s i) * t β β i, s i * t :=
image2_Inter_subset_left _ _ _
@[to_additive]
lemma mul_Inter_subset (s : set Ξ±) (t : ΞΉ β set Ξ±) : s * (β i, t i) β β i, s * t i :=
image2_Inter_subset_right _ _ _
@[to_additive]
lemma Interβ_mul_subset (s : Ξ i, ΞΊ i β set Ξ±) (t : set Ξ±) :
(β i j, s i j) * t β β i j, s i j * t :=
image2_Interβ_subset_left _ _ _
@[to_additive]
lemma mul_Interβ_subset (s : set Ξ±) (t : Ξ i, ΞΊ i β set Ξ±) :
s * (β i j, t i j) β β i j, s * t i j :=
image2_Interβ_subset_right _ _ _
@[to_additive] lemma finite.mul : finite s β finite t β finite (s * t) := finite.image2 _
/-- Multiplication preserves finiteness. -/
@[to_additive "Addition preserves finiteness."]
def fintype_mul [decidable_eq Ξ±] (s t : set Ξ±) [fintype s] [fintype t] : fintype (s * t : set Ξ±) :=
set.fintype_image2 _ _ _
/-- Under `[has_mul M]`, the `singleton` map from `M` to `set M` as a `mul_hom`, that is, a map
which preserves multiplication. -/
@[to_additive "Under `[has_add A]`, the `singleton` map from `A` to `set A` as an `add_hom`,
that is, a map which preserves addition.", simps]
def singleton_mul_hom : Ξ± ββ* (set Ξ±) :=
{ to_fun := singleton,
map_mul' := Ξ» a b, singleton_mul_singleton.symm }
open mul_opposite
@[simp, to_additive]
lemma image_op_mul : op '' (s * t) = op '' t * op '' s := image_image2_antidistrib op_mul
end has_mul
/-! ### Set subtraction/division -/
section has_div
variables {ΞΉ : Sort*} {ΞΊ : ΞΉ β Sort*} [has_div Ξ±] {s sβ sβ t tβ tβ u : set Ξ±} {a b : Ξ±}
/-- The pointwise division of sets `s / t` is defined as `{x / y | x β s, y β t}` in locale
`pointwise`. -/
@[to_additive "The pointwise subtraction of sets `s - t` is defined as `{x - y | x β s, y β t}` in
locale `pointwise`."]
protected def has_div : has_div (set Ξ±) := β¨image2 (/)β©
localized "attribute [instance] set.has_div set.has_sub" in pointwise
@[simp, to_additive]
lemma image2_div : image2 has_div.div s t = s / t := rfl
@[to_additive]
lemma mem_div : a β s / t β β x y, x β s β§ y β t β§ x / y = a := iff.rfl
@[to_additive] lemma div_mem_div : a β s β b β t β a / b β s / t := mem_image2_of_mem
@[to_additive add_image_prod]
lemma image_div_prod : (Ξ» x : Ξ± Γ Ξ±, x.fst / x.snd) '' s ΓΛ’ t = s / t := image_prod _
@[simp, to_additive] lemma empty_div : β
/ s = β
:= image2_empty_left
@[simp, to_additive] lemma div_empty : s / β
= β
:= image2_empty_right
@[simp, to_additive] lemma div_eq_empty : s / t = β
β s = β
β¨ t = β
:= image2_eq_empty_iff
@[simp, to_additive] lemma div_nonempty : (s / t).nonempty β s.nonempty β§ t.nonempty :=
image2_nonempty_iff
@[to_additive] lemma nonempty.div : s.nonempty β t.nonempty β (s / t).nonempty := nonempty.image2
@[to_additive] lemma nonempty.of_div_left : (s / t).nonempty β s.nonempty := nonempty.of_image2_left
@[to_additive] lemma nonempty.of_div_right : (s / t).nonempty β t.nonempty :=
nonempty.of_image2_right
@[simp, to_additive] lemma div_singleton : s / {b} = (/ b) '' s := image2_singleton_right
@[simp, to_additive] lemma singleton_div : {a} / t = ((/) a) '' t := image2_singleton_left
@[simp, to_additive] lemma singleton_div_singleton : ({a} : set Ξ±) / {b} = {a / b} :=
image2_singleton
@[to_additive, mono] lemma div_subset_div : sβ β tβ β sβ β tβ β sβ / sβ β tβ / tβ := image2_subset
@[to_additive] lemma div_subset_div_left : tβ β tβ β s / tβ β s / tβ := image2_subset_left
@[to_additive] lemma div_subset_div_right : sβ β sβ β sβ / t β sβ / t := image2_subset_right
@[to_additive] lemma div_subset_iff : s / t β u β β (x β s) (y β t), x / y β u := image2_subset_iff
attribute [mono] sub_subset_sub
@[to_additive] lemma union_div : (sβ βͺ sβ) / t = sβ / t βͺ sβ / t := image2_union_left
@[to_additive] lemma div_union : s / (tβ βͺ tβ) = s / tβ βͺ s / tβ := image2_union_right
@[to_additive] lemma inter_div_subset : (sβ β© sβ) / t β sβ / t β© (sβ / t) :=
image2_inter_subset_left
@[to_additive] lemma div_inter_subset : s / (tβ β© tβ) β s / tβ β© (s / tβ) :=
image2_inter_subset_right
@[to_additive] lemma Union_div_left_image : (β a β s, ((/) a) '' t) = s / t := Union_image_left _
@[to_additive] lemma Union_div_right_image : (β a β t, (/ a) '' s) = s / t := Union_image_right _
@[to_additive] lemma Union_div (s : ΞΉ β set Ξ±) (t : set Ξ±) : (β i, s i) / t = β i, s i / t :=
image2_Union_left _ _ _
@[to_additive] lemma div_Union (s : set Ξ±) (t : ΞΉ β set Ξ±) : s / (β i, t i) = β i, s / t i :=
image2_Union_right _ _ _
@[to_additive]
lemma Unionβ_div (s : Ξ i, ΞΊ i β set Ξ±) (t : set Ξ±) : (β i j, s i j) / t = β i j, s i j / t :=
image2_Unionβ_left _ _ _
@[to_additive]
lemma div_Unionβ (s : set Ξ±) (t : Ξ i, ΞΊ i β set Ξ±) : s / (β i j, t i j) = β i j, s / t i j :=
image2_Unionβ_right _ _ _
@[to_additive]
lemma Inter_div_subset (s : ΞΉ β set Ξ±) (t : set Ξ±) : (β i, s i) / t β β i, s i / t :=
image2_Inter_subset_left _ _ _
@[to_additive]
lemma div_Inter_subset (s : set Ξ±) (t : ΞΉ β set Ξ±) : s / (β i, t i) β β i, s / t i :=
image2_Inter_subset_right _ _ _
@[to_additive]
lemma Interβ_div_subset (s : Ξ i, ΞΊ i β set Ξ±) (t : set Ξ±) :
(β i j, s i j) / t β β i j, s i j / t :=
image2_Interβ_subset_left _ _ _
@[to_additive]
lemma div_Interβ_subset (s : set Ξ±) (t : Ξ i, ΞΊ i β set Ξ±) :
s / (β i j, t i j) β β i j, s / t i j :=
image2_Interβ_subset_right _ _ _
end has_div
/-- `set Ξ±` is a `semigroup` under pointwise operations if `Ξ±` is. -/
@[to_additive "`set Ξ±` is an `add_semigroup` under pointwise operations if `Ξ±` is."]
protected def semigroup [semigroup Ξ±] : semigroup (set Ξ±) :=
{ mul_assoc := Ξ» _ _ _, image2_assoc mul_assoc,
..set.has_mul }
/-- `set Ξ±` is a `comm_semigroup` under pointwise operations if `Ξ±` is. -/
@[to_additive "`set Ξ±` is an `add_comm_semigroup` under pointwise operations if `Ξ±` is."]
protected def comm_semigroup [comm_semigroup Ξ±] : comm_semigroup (set Ξ±) :=
{ mul_comm := Ξ» s t, image2_comm mul_comm
..set.semigroup }
section mul_one_class
variables [mul_one_class Ξ±]
/-- `set Ξ±` is a `mul_one_class` under pointwise operations if `Ξ±` is. -/
@[to_additive "`set Ξ±` is an `add_zero_class` under pointwise operations if `Ξ±` is."]
protected def mul_one_class : mul_one_class (set Ξ±) :=
{ mul_one := Ξ» s, by { simp only [β singleton_one, mul_singleton, mul_one, image_id'] },
one_mul := Ξ» s, by { simp only [β singleton_one, singleton_mul, one_mul, image_id'] },
..set.has_one, ..set.has_mul }
localized "attribute [instance] set.mul_one_class set.add_zero_class set.semigroup set.add_semigroup
set.comm_semigroup set.add_comm_semigroup" in pointwise
@[to_additive] lemma subset_mul_left (s : set Ξ±) {t : set Ξ±} (ht : (1 : Ξ±) β t) : s β s * t :=
Ξ» x hx, β¨x, 1, hx, ht, mul_one _β©
@[to_additive] lemma subset_mul_right {s : set Ξ±} (t : set Ξ±) (hs : (1 : Ξ±) β s) : t β s * t :=
Ξ» x hx, β¨1, x, hs, hx, one_mul _β©
end mul_one_class
section monoid
variables [monoid Ξ±] {s t : set Ξ±} {a : Ξ±}
/-- `set Ξ±` is a `monoid` under pointwise operations if `Ξ±` is. -/
@[to_additive "`set Ξ±` is an `add_monoid` under pointwise operations if `Ξ±` is."]
protected def monoid : monoid (set Ξ±) := { ..set.semigroup, ..set.mul_one_class }
localized "attribute [instance] set.monoid set.add_monoid" in pointwise
@[to_additive] lemma pow_mem_pow (ha : a β s) : β n : β, a ^ n β s ^ n
| 0 := by { rw pow_zero, exact one_mem_one }
| (n + 1) := by { rw pow_succ, exact mul_mem_mul ha (pow_mem_pow _) }
@[to_additive] lemma pow_subset_pow (hst : s β t) : β n : β, s ^ n β t ^ n
| 0 := by { rw pow_zero, exact subset.rfl }
| (n + 1) := by { rw pow_succ, exact mul_subset_mul hst (pow_subset_pow _) }
@[to_additive] lemma empty_pow (n : β) (hn : n β 0) : (β
: set Ξ±) ^ n = β
:=
by rw [β tsub_add_cancel_of_le (nat.succ_le_of_lt $ nat.pos_of_ne_zero hn), pow_succ, empty_mul]
@[to_additive]
instance decidable_mem_mul [fintype Ξ±] [decidable_eq Ξ±] [decidable_pred (β s)]
[decidable_pred (β t)] :
decidable_pred (β s * t) :=
Ξ» _, decidable_of_iff _ mem_mul.symm
@[to_additive]
instance decidable_mem_pow [fintype Ξ±] [decidable_eq Ξ±] [decidable_pred (β s)] (n : β) :
decidable_pred (β (s ^ n)) :=
begin
induction n with n ih,
{ simp_rw [pow_zero, mem_one], apply_instance },
{ letI := ih, rw pow_succ, apply_instance }
end
@[simp, to_additive] lemma univ_mul_univ : (univ : set Ξ±) * univ = univ :=
begin
have : β x, β a b : Ξ±, a * b = x := Ξ» x, β¨x, 1, mul_one xβ©,
simpa only [mem_mul, eq_univ_iff_forall, mem_univ, true_and]
end
end monoid
/-- `set Ξ±` is a `comm_monoid` under pointwise operations if `Ξ±` is. -/
@[to_additive "`set Ξ±` is an `add_comm_monoid` under pointwise operations if `Ξ±` is."]
protected def comm_monoid [comm_monoid Ξ±] : comm_monoid (set Ξ±) :=
{ ..set.monoid, ..set.comm_semigroup }
localized "attribute [instance] set.comm_monoid set.add_comm_monoid" in pointwise
open_locale pointwise
section group
variables [group Ξ±] {s t : set Ξ±} {a b : Ξ±}
/-! Note that `set` is not a `group` because `s / s β 1` in general. -/
@[simp, to_additive] lemma image_mul_left : ((*) a) '' t = ((*) aβ»ΒΉ) β»ΒΉ' t :=
by { rw image_eq_preimage_of_inverse; intro c; simp }
@[simp, to_additive] lemma image_mul_right : (* b) '' t = (* bβ»ΒΉ) β»ΒΉ' t :=
by { rw image_eq_preimage_of_inverse; intro c; simp }
@[to_additive] lemma image_mul_left' : (Ξ» b, aβ»ΒΉ * b) '' t = (Ξ» b, a * b) β»ΒΉ' t := by simp
@[to_additive] lemma image_mul_right' : (* bβ»ΒΉ) '' t = (* b) β»ΒΉ' t := by simp
@[simp, to_additive] lemma preimage_mul_left_singleton : ((*) a) β»ΒΉ' {b} = {aβ»ΒΉ * b} :=
by rw [β image_mul_left', image_singleton]
@[simp, to_additive] lemma preimage_mul_right_singleton : (* a) β»ΒΉ' {b} = {b * aβ»ΒΉ} :=
by rw [β image_mul_right', image_singleton]
@[simp, to_additive] lemma preimage_mul_left_one : ((*) a) β»ΒΉ' 1 = {aβ»ΒΉ} :=
by rw [β image_mul_left', image_one, mul_one]
@[simp, to_additive] lemma preimage_mul_right_one : (* b) β»ΒΉ' 1 = {bβ»ΒΉ} :=
by rw [β image_mul_right', image_one, one_mul]
@[to_additive] lemma preimage_mul_left_one' : (Ξ» b, aβ»ΒΉ * b) β»ΒΉ' 1 = {a} := by simp
@[to_additive] lemma preimage_mul_right_one' : (* bβ»ΒΉ) β»ΒΉ' 1 = {b} := by simp
@[simp, to_additive] lemma mul_univ (hs : s.nonempty) : s * (univ : set Ξ±) = univ :=
let β¨a, haβ© := hs in eq_univ_of_forall $ Ξ» b, β¨a, aβ»ΒΉ * b, ha, trivial, mul_inv_cancel_left _ _β©
@[simp, to_additive] lemma univ_mul (ht : t.nonempty) : (univ : set Ξ±) * t = univ :=
let β¨a, haβ© := ht in eq_univ_of_forall $ Ξ» b, β¨b * aβ»ΒΉ, a, trivial, ha, inv_mul_cancel_right _ _β©
end group
@[to_additive]
lemma bdd_above_mul [ordered_comm_monoid Ξ±] {A B : set Ξ±} :
bdd_above A β bdd_above B β bdd_above (A * B) :=
begin
rintro β¨bA, hbAβ© β¨bB, hbBβ©,
use bA * bB,
rintro x β¨xa, xb, hxa, hxb, rflβ©,
exact mul_le_mul' (hbA hxa) (hbB hxb),
end
open_locale pointwise
section big_operators
open_locale big_operators
variables {ΞΉ : Type*} [comm_monoid Ξ±]
/-- The n-ary version of `set.mem_mul`. -/
@[to_additive /-" The n-ary version of `set.mem_add`. "-/]
lemma mem_finset_prod (t : finset ΞΉ) (f : ΞΉ β set Ξ±) (a : Ξ±) :
a β β i in t, f i β β (g : ΞΉ β Ξ±) (hg : β {i}, i β t β g i β f i), β i in t, g i = a :=
begin
classical,
induction t using finset.induction_on with i is hi ih generalizing a,
{ simp_rw [finset.prod_empty, set.mem_one],
exact β¨Ξ» h, β¨Ξ» i, a, Ξ» i, false.elim, h.symmβ©, Ξ» β¨f, _, hfβ©, hf.symmβ© },
rw [finset.prod_insert hi, set.mem_mul],
simp_rw [finset.prod_insert hi],
simp_rw ih,
split,
{ rintro β¨x, y, hx, β¨g, hg, rflβ©, rflβ©,
refine β¨function.update g i x, Ξ» j hj, _, _β©,
obtain rfl | hj := finset.mem_insert.mp hj,
{ rw function.update_same, exact hx },
{ rw update_noteq (ne_of_mem_of_not_mem hj hi), exact hg hj, },
rw [finset.prod_update_of_not_mem hi, function.update_same], },
{ rintro β¨g, hg, rflβ©,
exact β¨g i, is.prod g, hg (is.mem_insert_self _),
β¨g, Ξ» i hi, hg (finset.mem_insert_of_mem hi), rflβ©, rflβ© },
end
/-- A version of `set.mem_finset_prod` with a simpler RHS for products over a fintype. -/
@[to_additive /-" A version of `set.mem_finset_sum` with a simpler RHS for sums over a fintype. "-/]
lemma mem_fintype_prod [fintype ΞΉ] (f : ΞΉ β set Ξ±) (a : Ξ±) :
a β β i, f i β β (g : ΞΉ β Ξ±) (hg : β i, g i β f i), β i, g i = a :=
by { rw mem_finset_prod, simp }
/-- The n-ary version of `set.mul_mem_mul`. -/
@[to_additive /-" The n-ary version of `set.add_mem_add`. "-/]
lemma finset_prod_mem_finset_prod (t : finset ΞΉ) (f : ΞΉ β set Ξ±)
(g : ΞΉ β Ξ±) (hg : β i β t, g i β f i) :
β i in t, g i β β i in t, f i :=
by { rw mem_finset_prod, exact β¨g, hg, rflβ© }
/-- The n-ary version of `set.mul_subset_mul`. -/
@[to_additive /-" The n-ary version of `set.add_subset_add`. "-/]
lemma finset_prod_subset_finset_prod (t : finset ΞΉ) (fβ fβ : ΞΉ β set Ξ±)
(hf : β {i}, i β t β fβ i β fβ i) :
β i in t, fβ i β β i in t, fβ i :=
begin
intro a,
rw [mem_finset_prod, mem_finset_prod],
rintro β¨g, hg, rflβ©,
exact β¨g, Ξ» i hi, hf hi $ hg hi, rflβ©
end
@[to_additive]
lemma finset_prod_singleton {M ΞΉ : Type*} [comm_monoid M] (s : finset ΞΉ) (I : ΞΉ β M) :
β (i : ΞΉ) in s, ({I i} : set M) = {β (i : ΞΉ) in s, I i} :=
begin
letI := classical.dec_eq ΞΉ,
refine finset.induction_on s _ _,
{ simpa },
{ intros _ _ H ih,
rw [finset.prod_insert H, finset.prod_insert H, ih],
simp }
end
/-! TODO: define `decidable_mem_finset_prod` and `decidable_mem_finset_sum`. -/
end big_operators
open_locale pointwise
/-- Repeated pointwise addition (not the same as pointwise repeated addition!) of a `finset`. -/
protected def has_nsmul [has_zero Ξ±] [has_add Ξ±] : has_scalar β (set Ξ±) := β¨nsmul_recβ©
/-- Repeated pointwise multiplication (not the same as pointwise repeated multiplication!) of a
`set`. -/
@[to_additive]
protected def has_npow [has_one Ξ±] [has_mul Ξ±] : has_pow (set Ξ±) β := β¨Ξ» s n, npow_rec n sβ©
/-- Repeated pointwise addition/subtraction (not the same as pointwise repeated
addition/subtraction!) of a `set`. -/
protected def has_zsmul [has_zero Ξ±] [has_add Ξ±] [has_neg Ξ±] : has_scalar β€ (set Ξ±) := β¨zsmul_recβ©
/-- Repeated pointwise multiplication/division (not the same as pointwise repeated
multiplication/division!) of a `set`. -/
@[to_additive] protected def has_zpow [has_one Ξ±] [has_mul Ξ±] [has_inv Ξ±] : has_pow (set Ξ±) β€ :=
β¨Ξ» s n, zpow_rec n sβ©
-- TODO: Generalize the duplicated lemmas and instances below to `division_monoid`
@[to_additive] protected lemma mul_inv_rev [group Ξ±] (s t : set Ξ±) : (s * t)β»ΒΉ = tβ»ΒΉ * sβ»ΒΉ :=
by { simp_rw βimage_inv, exact image_image2_antidistrib mul_inv_rev }
protected lemma mul_inv_revβ [group_with_zero Ξ±] (s t : set Ξ±) : (s * t)β»ΒΉ = tβ»ΒΉ * sβ»ΒΉ :=
by { simp_rw βimage_inv, exact image_image2_antidistrib mul_inv_rev }
/-- `s / t = s * tβ»ΒΉ` for all `s t : set Ξ±` if `a / b = a * bβ»ΒΉ` for all `a b : Ξ±`. -/
@[to_additive "`s - t = s + -t` for all `s t : set Ξ±` if `a - b = a + -b` for all `a b : Ξ±`."]
protected def div_inv_monoid [group Ξ±] : div_inv_monoid (set Ξ±) :=
{ div_eq_mul_inv := Ξ» s t,
by { rw [βimage_id (s / t), βimage_inv], exact image_image2_distrib_right div_eq_mul_inv },
..set.monoid, ..set.has_inv, ..set.has_div }
/-- `s / t = s * tβ»ΒΉ` for all `s t : set Ξ±` if `a / b = a * bβ»ΒΉ` for all `a b : Ξ±`. -/
protected def div_inv_monoid' [group_with_zero Ξ±] : div_inv_monoid (set Ξ±) :=
{ div_eq_mul_inv := Ξ» s t,
by { rw [βimage_id (s / t), βimage_inv], exact image_image2_distrib_right div_eq_mul_inv },
..set.monoid, ..set.has_inv, ..set.has_div }
localized "attribute [instance] set.has_nsmul set.has_npow set.has_zsmul set.has_zpow
set.div_inv_monoid set.div_inv_monoid' set.sub_neg_add_monoid" in pointwise
/-! ### Translation/scaling of sets -/
section smul
/-- The dilation of set `x β’ s` is defined as `{x β’ y | y β s}` in locale `pointwise`. -/
@[to_additive has_vadd_set "The translation of set `x +α΅₯ s` is defined as `{x +α΅₯ y | y β s}` in
locale `pointwise`."]
protected def has_scalar_set [has_scalar Ξ± Ξ²] : has_scalar Ξ± (set Ξ²) :=
β¨Ξ» a, image (has_scalar.smul a)β©
/-- The pointwise scalar multiplication of sets `s β’ t` is defined as `{x β’ y | x β s, y β t}` in
locale `pointwise`. -/
@[to_additive has_vadd "The pointwise scalar addition of sets `s +α΅₯ t` is defined as
`{x +α΅₯ y | x β s, y β t}` in locale `pointwise`."]
protected def has_scalar [has_scalar Ξ± Ξ²] : has_scalar (set Ξ±) (set Ξ²) :=
β¨image2 has_scalar.smulβ©
localized "attribute [instance] set.has_scalar_set set.has_scalar" in pointwise
localized "attribute [instance] set.has_vadd_set set.has_vadd" in pointwise
section has_scalar
variables {ΞΉ : Sort*} {ΞΊ : ΞΉ β Sort*} [has_scalar Ξ± Ξ²] {s sβ sβ : set Ξ±} {t tβ tβ u : set Ξ²} {a : Ξ±}
{b : Ξ²}
@[simp, to_additive]
lemma image2_smul : image2 has_scalar.smul s t = s β’ t := rfl
@[to_additive add_image_prod]
lemma image_smul_prod : (Ξ» x : Ξ± Γ Ξ², x.fst β’ x.snd) '' s ΓΛ’ t = s β’ t := image_prod _
@[to_additive]
lemma mem_smul : b β s β’ t β β x y, x β s β§ y β t β§ x β’ y = b := iff.rfl
@[to_additive] lemma smul_mem_smul : a β s β b β t β a β’ b β s β’ t := mem_image2_of_mem
@[simp, to_additive] lemma empty_smul : (β
: set Ξ±) β’ t = β
:= image2_empty_left
@[simp, to_additive] lemma smul_empty : s β’ (β
: set Ξ²) = β
:= image2_empty_right
@[simp, to_additive] lemma smul_eq_empty : s β’ t = β
β s = β
β¨ t = β
:= image2_eq_empty_iff
@[simp, to_additive] lemma smul_nonempty : (s β’ t).nonempty β s.nonempty β§ t.nonempty :=
image2_nonempty_iff
@[to_additive] lemma nonempty.smul : s.nonempty β t.nonempty β (s β’ t).nonempty := nonempty.image2
@[to_additive] lemma nonempty.of_smul_left : (s β’ t).nonempty β s.nonempty :=
nonempty.of_image2_left
@[to_additive] lemma nonempty.of_smul_right : (s β’ t).nonempty β t.nonempty :=
nonempty.of_image2_right
@[simp, to_additive] lemma smul_singleton : s β’ {b} = (β’ b) '' s := image2_singleton_right
@[simp, to_additive] lemma singleton_smul : ({a} : set Ξ±) β’ t = a β’ t := image2_singleton_left
@[simp, to_additive] lemma singleton_smul_singleton : ({a} : set Ξ±) β’ ({b} : set Ξ²) = {a β’ b} :=
image2_singleton
@[to_additive, mono] lemma smul_subset_smul : sβ β sβ β tβ β tβ β sβ β’ tβ β sβ β’ tβ := image2_subset
@[to_additive] lemma smul_subset_smul_left : tβ β tβ β s β’ tβ β s β’ tβ := image2_subset_left
@[to_additive] lemma smul_subset_smul_right : sβ β sβ β sβ β’ t β sβ β’ t := image2_subset_right
@[to_additive] lemma smul_subset_iff : s β’ t β u β β (a β s) (b β t), a β’ b β u := image2_subset_iff
attribute [mono] vadd_subset_vadd
@[to_additive] lemma union_smul : (sβ βͺ sβ) β’ t = sβ β’ t βͺ sβ β’ t := image2_union_left
@[to_additive] lemma smul_union : s β’ (tβ βͺ tβ) = s β’ tβ βͺ s β’ tβ := image2_union_right
@[to_additive] lemma inter_smul_subset : (sβ β© sβ) β’ t β sβ β’ t β© sβ β’ t := image2_inter_subset_left
@[to_additive] lemma smul_inter_subset : s β’ (tβ β© tβ) β s β’ tβ β© s β’ tβ :=
image2_inter_subset_right
@[to_additive] lemma Union_smul_left_image : (β a β s, a β’ t) = s β’ t := Union_image_left _
@[to_additive] lemma Union_smul_right_image : (β a β t, (β’ a) '' s) = s β’ t := Union_image_right _
@[to_additive] lemma Union_smul (s : ΞΉ β set Ξ±) (t : set Ξ²) : (β i, s i) β’ t = β i, s i β’ t :=
image2_Union_left _ _ _
@[to_additive] lemma smul_Union (s : set Ξ±) (t : ΞΉ β set Ξ²) : s β’ (β i, t i) = β i, s β’ t i :=
image2_Union_right _ _ _
@[to_additive]
lemma Unionβ_smul (s : Ξ i, ΞΊ i β set Ξ±) (t : set Ξ²) : (β i j, s i j) β’ t = β i j, s i j β’ t :=
image2_Unionβ_left _ _ _
@[to_additive]
lemma smul_Unionβ (s : set Ξ±) (t : Ξ i, ΞΊ i β set Ξ²) : s β’ (β i j, t i j) = β i j, s β’ t i j :=
image2_Unionβ_right _ _ _
@[to_additive]
lemma Inter_smul_subset (s : ΞΉ β set Ξ±) (t : set Ξ²) : (β i, s i) β’ t β β i, s i β’ t :=
image2_Inter_subset_left _ _ _
@[to_additive]
lemma smul_Inter_subset (s : set Ξ±) (t : ΞΉ β set Ξ²) : s β’ (β i, t i) β β i, s β’ t i :=
image2_Inter_subset_right _ _ _
@[to_additive]
lemma Interβ_smul_subset (s : Ξ i, ΞΊ i β set Ξ±) (t : set Ξ²) :
(β i j, s i j) β’ t β β i j, s i j β’ t :=
image2_Interβ_subset_left _ _ _
@[to_additive]
lemma smul_Interβ_subset (s : set Ξ±) (t : Ξ i, ΞΊ i β set Ξ²) :
s β’ (β i j, t i j) β β i j, s β’ t i j :=
image2_Interβ_subset_right _ _ _
@[to_additive] lemma finite.smul : finite s β finite t β finite (s β’ t) := finite.image2 _
end has_scalar
section has_scalar_set
variables {ΞΉ : Sort*} {ΞΊ : ΞΉ β Sort*} [has_scalar Ξ± Ξ²] {s t tβ tβ : set Ξ²} {a : Ξ±} {b : Ξ²} {x y : Ξ²}
@[simp, to_additive] lemma image_smul : (Ξ» x, a β’ x) '' t = a β’ t := rfl
@[to_additive] lemma mem_smul_set : x β a β’ t β β y, y β t β§ a β’ y = x := iff.rfl
@[to_additive] lemma smul_mem_smul_set : b β s β a β’ b β a β’ s := mem_image_of_mem _
@[simp, to_additive] lemma smul_set_empty : a β’ (β
: set Ξ²) = β
:= image_empty _
@[simp, to_additive] lemma smul_set_eq_empty : a β’ s = β
β s = β
:= image_eq_empty
@[simp, to_additive] lemma smul_set_nonempty : (a β’ s).nonempty β s.nonempty := nonempty_image_iff
@[simp, to_additive] lemma smul_set_singleton : a β’ ({b} : set Ξ²) = {a β’ b} := image_singleton
@[to_additive] lemma smul_set_mono (h : s β t) : a β’ s β a β’ t := image_subset _ h
@[to_additive] lemma smul_set_union : a β’ (tβ βͺ tβ) = a β’ tβ βͺ a β’ tβ := image_union _ _ _
@[to_additive]
lemma smul_set_inter_subset : a β’ (tβ β© tβ) β a β’ tβ β© (a β’ tβ) := image_inter_subset _ _ _
@[to_additive]
lemma smul_set_Union (a : Ξ±) (s : ΞΉ β set Ξ²) : a β’ (β i, s i) = β i, a β’ s i := image_Union
@[to_additive]
lemma smul_set_Unionβ (a : Ξ±) (s : Ξ i, ΞΊ i β set Ξ²) : a β’ (β i j, s i j) = β i j, a β’ s i j :=
image_Unionβ _ _
@[to_additive]
lemma smul_set_Inter_subset (a : Ξ±) (t : ΞΉ β set Ξ²) : a β’ (β i, t i) β β i, a β’ t i :=
image_Inter_subset _ _
@[to_additive]
lemma smul_set_Interβ_subset (a : Ξ±) (t : Ξ i, ΞΊ i β set Ξ²) :
a β’ (β i j, t i j) β β i j, a β’ t i j :=
image_Interβ_subset _ _
@[to_additive] lemma nonempty.smul_set : s.nonempty β (a β’ s).nonempty := nonempty.image _
@[to_additive] lemma finite.smul_set : finite s β finite (a β’ s) := finite.image _
end has_scalar_set
variables {s sβ sβ : set Ξ±} {t tβ tβ : set Ξ²} {a : Ξ±} {b : Ξ²}
@[to_additive]
lemma smul_set_inter [group Ξ±] [mul_action Ξ± Ξ²] {s t : set Ξ²} :
a β’ (s β© t) = a β’ s β© a β’ t :=
(image_inter $ mul_action.injective a).symm
lemma smul_set_interβ [group_with_zero Ξ±] [mul_action Ξ± Ξ²] {s t : set Ξ²} (ha : a β 0) :
a β’ (s β© t) = a β’ s β© a β’ t :=
show units.mk0 a ha β’ _ = _, from smul_set_inter
@[simp, to_additive]
lemma smul_set_univ [group Ξ±] [mul_action Ξ± Ξ²] {a : Ξ±} : a β’ (univ : set Ξ²) = univ :=
eq_univ_of_forall $ Ξ» b, β¨aβ»ΒΉ β’ b, trivial, smul_inv_smul _ _β©
@[simp, to_additive]
lemma smul_univ [group Ξ±] [mul_action Ξ± Ξ²] {s : set Ξ±} (hs : s.nonempty) :
s β’ (univ : set Ξ²) = univ :=
let β¨a, haβ© := hs in eq_univ_of_forall $ Ξ» b, β¨a, aβ»ΒΉ β’ b, ha, trivial, smul_inv_smul _ _β©
@[to_additive]
theorem range_smul_range {ΞΉ ΞΊ : Type*} [has_scalar Ξ± Ξ²] (b : ΞΉ β Ξ±) (c : ΞΊ β Ξ²) :
range b β’ range c = range (Ξ» p : ΞΉ Γ ΞΊ, b p.1 β’ c p.2) :=
ext $ Ξ» x, β¨Ξ» hx, let β¨p, q, β¨i, hiβ©, β¨j, hjβ©, hpqβ© := set.mem_smul.1 hx in
β¨(i, j), hpq βΈ hi βΈ hj βΈ rflβ©,
Ξ» β¨β¨i, jβ©, hβ©, set.mem_smul.2 β¨b i, c j, β¨i, rflβ©, β¨j, rflβ©, hβ©β©
@[to_additive]
instance smul_comm_class_set [has_scalar Ξ± Ξ³] [has_scalar Ξ² Ξ³] [smul_comm_class Ξ± Ξ² Ξ³] :
smul_comm_class Ξ± (set Ξ²) (set Ξ³) :=
β¨Ξ» _ _ _, image_image2_distrib_right $ smul_comm _β©
@[to_additive]
instance smul_comm_class_set' [has_scalar Ξ± Ξ³] [has_scalar Ξ² Ξ³] [smul_comm_class Ξ± Ξ² Ξ³] :
smul_comm_class (set Ξ±) Ξ² (set Ξ³) :=
by haveI := smul_comm_class.symm Ξ± Ξ² Ξ³; exact smul_comm_class.symm _ _ _
@[to_additive]
instance smul_comm_class [has_scalar Ξ± Ξ³] [has_scalar Ξ² Ξ³] [smul_comm_class Ξ± Ξ² Ξ³] :
smul_comm_class (set Ξ±) (set Ξ²) (set Ξ³) :=
β¨Ξ» _ _ _, image2_left_comm smul_commβ©
instance is_scalar_tower [has_scalar Ξ± Ξ²] [has_scalar Ξ± Ξ³] [has_scalar Ξ² Ξ³]
[is_scalar_tower Ξ± Ξ² Ξ³] :
is_scalar_tower Ξ± Ξ² (set Ξ³) :=
{ smul_assoc := Ξ» a b T, by simp only [βimage_smul, image_image, smul_assoc] }
instance is_scalar_tower' [has_scalar Ξ± Ξ²] [has_scalar Ξ± Ξ³] [has_scalar Ξ² Ξ³]
[is_scalar_tower Ξ± Ξ² Ξ³] :
is_scalar_tower Ξ± (set Ξ²) (set Ξ³) :=
β¨Ξ» _ _ _, image2_image_left_comm $ smul_assoc _β©
instance is_scalar_tower'' [has_scalar Ξ± Ξ²] [has_scalar Ξ± Ξ³] [has_scalar Ξ² Ξ³]
[is_scalar_tower Ξ± Ξ² Ξ³] :
is_scalar_tower (set Ξ±) (set Ξ²) (set Ξ³) :=
{ smul_assoc := Ξ» T T' T'', image2_assoc smul_assoc }
instance is_central_scalar [has_scalar Ξ± Ξ²] [has_scalar Ξ±α΅α΅α΅ Ξ²] [is_central_scalar Ξ± Ξ²] :
is_central_scalar Ξ± (set Ξ²) :=
β¨Ξ» a S, congr_arg (Ξ» f, f '' S) $ by exact funext (Ξ» _, op_smul_eq_smul _ _)β©
/-- A multiplicative action of a monoid `Ξ±` on a type `Ξ²` gives a multiplicative action of `set Ξ±`
on `set Ξ²`. -/
@[to_additive "An additive action of an additive monoid `Ξ±` on a type `Ξ²` gives an additive action
of `set Ξ±` on `set Ξ²`"]
protected def mul_action [monoid Ξ±] [mul_action Ξ± Ξ²] : mul_action (set Ξ±) (set Ξ²) :=
{ mul_smul := Ξ» _ _ _, image2_assoc mul_smul,
one_smul := Ξ» s, image2_singleton_left.trans $ by simp_rw [one_smul, image_id'] }
/-- A multiplicative action of a monoid on a type `Ξ²` gives a multiplicative action on `set Ξ²`. -/
@[to_additive "An additive action of an additive monoid on a type `Ξ²` gives an additive action
on `set Ξ²`."]
protected def mul_action_set [monoid Ξ±] [mul_action Ξ± Ξ²] : mul_action Ξ± (set Ξ²) :=
{ mul_smul := by { intros, simp only [β image_smul, image_image, β mul_smul] },
one_smul := by { intros, simp only [β image_smul, one_smul, image_id'] } }
localized "attribute [instance] set.mul_action_set set.add_action_set
set.mul_action set.add_action" in pointwise
/-- A distributive multiplicative action of a monoid on an additive monoid `Ξ²` gives a distributive
multiplicative action on `set Ξ²`. -/
protected def distrib_mul_action_set [monoid Ξ±] [add_monoid Ξ²] [distrib_mul_action Ξ± Ξ²] :
distrib_mul_action Ξ± (set Ξ²) :=
{ smul_add := Ξ» _ _ _, image_image2_distrib $ smul_add _,
smul_zero := Ξ» _, image_singleton.trans $ by rw [smul_zero, singleton_zero] }
/-- A multiplicative action of a monoid on a monoid `Ξ²` gives a multiplicative action on `set Ξ²`. -/
protected def mul_distrib_mul_action_set [monoid Ξ±] [monoid Ξ²] [mul_distrib_mul_action Ξ± Ξ²] :
mul_distrib_mul_action Ξ± (set Ξ²) :=
{ smul_mul := Ξ» _ _ _, image_image2_distrib $ smul_mul' _,
smul_one := Ξ» _, image_singleton.trans $ by rw [smul_one, singleton_one] }
localized "attribute [instance] set.distrib_mul_action_set set.mul_distrib_mul_action_set"
in pointwise
end smul
section vsub
variables {ΞΉ : Sort*} {ΞΊ : ΞΉ β Sort*} [has_vsub Ξ± Ξ²] {s sβ sβ t tβ tβ : set Ξ²} {u : set Ξ±} {a : Ξ±}
{b c : Ξ²}
include Ξ±
instance has_vsub : has_vsub (set Ξ±) (set Ξ²) := β¨image2 (-α΅₯)β©
@[simp] lemma image2_vsub : (image2 has_vsub.vsub s t : set Ξ±) = s -α΅₯ t := rfl
lemma image_vsub_prod : (Ξ» x : Ξ² Γ Ξ², x.fst -α΅₯ x.snd) '' s ΓΛ’ t = s -α΅₯ t := image_prod _
lemma mem_vsub : a β s -α΅₯ t β β x y, x β s β§ y β t β§ x -α΅₯ y = a := iff.rfl
lemma vsub_mem_vsub (hb : b β s) (hc : c β t) : b -α΅₯ c β s -α΅₯ t := mem_image2_of_mem hb hc
@[simp] lemma empty_vsub (t : set Ξ²) : β
-α΅₯ t = β
:= image2_empty_left
@[simp] lemma vsub_empty (s : set Ξ²) : s -α΅₯ β
= β
:= image2_empty_right
@[simp] lemma vsub_eq_empty : s -α΅₯ t = β
β s = β
β¨ t = β
:= image2_eq_empty_iff
@[simp] lemma vsub_nonempty : (s -α΅₯ t : set Ξ±).nonempty β s.nonempty β§ t.nonempty :=
image2_nonempty_iff
lemma nonempty.vsub : s.nonempty β t.nonempty β (s -α΅₯ t : set Ξ±).nonempty := nonempty.image2
lemma nonempty.of_vsub_left : (s -α΅₯ t :set Ξ±).nonempty β s.nonempty := nonempty.of_image2_left
lemma nonempty.of_vsub_right : (s -α΅₯ t : set Ξ±).nonempty β t.nonempty := nonempty.of_image2_right
@[simp] lemma vsub_singleton (s : set Ξ²) (b : Ξ²) : s -α΅₯ {b} = (-α΅₯ b) '' s := image2_singleton_right
@[simp] lemma singleton_vsub (t : set Ξ²) (b : Ξ²) : {b} -α΅₯ t = ((-α΅₯) b) '' t := image2_singleton_left
@[simp] lemma singleton_vsub_singleton : ({b} : set Ξ²) -α΅₯ {c} = {b -α΅₯ c} := image2_singleton
@[mono] lemma vsub_subset_vsub : sβ β sβ β tβ β tβ β sβ -α΅₯ tβ β sβ -α΅₯ tβ := image2_subset
lemma vsub_subset_vsub_left : tβ β tβ β s -α΅₯ tβ β s -α΅₯ tβ := image2_subset_left
lemma vsub_subset_vsub_right : sβ β sβ β sβ -α΅₯ t β sβ -α΅₯ t := image2_subset_right
lemma vsub_subset_iff : s -α΅₯ t β u β β (x β s) (y β t), x -α΅₯ y β u := image2_subset_iff
lemma vsub_self_mono (h : s β t) : s -α΅₯ s β t -α΅₯ t := vsub_subset_vsub h h
lemma union_vsub : (sβ βͺ sβ) -α΅₯ t = sβ -α΅₯ t βͺ (sβ -α΅₯ t) := image2_union_left
lemma vsub_union : s -α΅₯ (tβ βͺ tβ) = s -α΅₯ tβ βͺ (s -α΅₯ tβ) := image2_union_right
lemma inter_vsub_subset : sβ β© sβ -α΅₯ t β (sβ -α΅₯ t) β© (sβ -α΅₯ t) := image2_inter_subset_left
lemma vsub_inter_subset : s -α΅₯ tβ β© tβ β (s -α΅₯ tβ) β© (s -α΅₯ tβ) := image2_inter_subset_right
lemma Union_vsub_left_image : (β a β s, ((-α΅₯) a) '' t) = s -α΅₯ t := Union_image_left _
lemma Union_vsub_right_image : (β a β t, (-α΅₯ a) '' s) = s -α΅₯ t := Union_image_right _
lemma Union_vsub (s : ΞΉ β set Ξ²) (t : set Ξ²) : (β i, s i) -α΅₯ t = β i, s i -α΅₯ t :=
image2_Union_left _ _ _
lemma vsub_Union (s : set Ξ²) (t : ΞΉ β set Ξ²) : s -α΅₯ (β i, t i) = β i, s -α΅₯ t i :=
image2_Union_right _ _ _
lemma Unionβ_vsub (s : Ξ i, ΞΊ i β set Ξ²) (t : set Ξ²) : (β i j, s i j) -α΅₯ t = β i j, s i j -α΅₯ t :=
image2_Unionβ_left _ _ _
lemma vsub_Unionβ (s : set Ξ²) (t : Ξ i, ΞΊ i β set Ξ²) : s -α΅₯ (β i j, t i j) = β i j, s -α΅₯ t i j :=
image2_Unionβ_right _ _ _
lemma Inter_vsub_subset (s : ΞΉ β set Ξ²) (t : set Ξ²) : (β i, s i) -α΅₯ t β β i, s i -α΅₯ t :=
image2_Inter_subset_left _ _ _
lemma vsub_Inter_subset (s : set Ξ²) (t : ΞΉ β set Ξ²) : s -α΅₯ (β i, t i) β β i, s -α΅₯ t i :=
image2_Inter_subset_right _ _ _
lemma Interβ_vsub_subset (s : Ξ i, ΞΊ i β set Ξ²) (t : set Ξ²) :
(β i j, s i j) -α΅₯ t β β i j, s i j -α΅₯ t :=
image2_Interβ_subset_left _ _ _
lemma vsub_Interβ_subset (s : set Ξ²) (t : Ξ i, ΞΊ i β set Ξ²) :
s -α΅₯ (β i j, t i j) β β i j, s -α΅₯ t i j :=
image2_Interβ_subset_right _ _ _
lemma finite.vsub (hs : finite s) (ht : finite t) : finite (s -α΅₯ t) := hs.image2 _ ht
end vsub
open_locale pointwise
section ring
variables [ring Ξ±] [add_comm_group Ξ²] [module Ξ± Ξ²] {s : set Ξ±} {t : set Ξ²} {a : Ξ±}
@[simp] lemma neg_smul_set : -a β’ t = -(a β’ t) :=
by simp_rw [βimage_smul, βimage_neg, image_image, neg_smul]
@[simp] lemma smul_set_neg : a β’ -t = -(a β’ t) :=
by simp_rw [βimage_smul, βimage_neg, image_image, smul_neg]
@[simp] protected lemma neg_smul : -s β’ t = -(s β’ t) :=
by simp_rw [βimage2_smul, βimage_neg, image2_image_left, image_image2, neg_smul]
@[simp] protected lemma smul_neg : s β’ -t = -(s β’ t) :=
by simp_rw [βimage2_smul, βimage_neg, image2_image_right, image_image2, smul_neg]
end ring
section monoid
/-! ### `set Ξ±` as a `(βͺ, *)`-semiring -/
/-- An alias for `set Ξ±`, which has a semiring structure given by `βͺ` as "addition" and pointwise
multiplication `*` as "multiplication". -/
@[derive [inhabited, partial_order, order_bot]] def set_semiring (Ξ± : Type*) : Type* := set Ξ±
/-- The identity function `set Ξ± β set_semiring Ξ±`. -/
protected def up (s : set Ξ±) : set_semiring Ξ± := s
/-- The identity function `set_semiring Ξ± β set Ξ±`. -/
protected def set_semiring.down (s : set_semiring Ξ±) : set Ξ± := s
@[simp] protected lemma down_up {s : set Ξ±} : s.up.down = s := rfl
@[simp] protected lemma up_down {s : set_semiring Ξ±} : s.down.up = s := rfl
/- This lemma is not tagged `simp`, since otherwise the linter complains. -/
lemma up_le_up {s t : set Ξ±} : s.up β€ t.up β s β t := iff.rfl
/- This lemma is not tagged `simp`, since otherwise the linter complains. -/
lemma up_lt_up {s t : set Ξ±} : s.up < t.up β s β t := iff.rfl
@[simp] lemma down_subset_down {s t : set_semiring Ξ±} : s.down β t.down β s β€ t := iff.rfl
@[simp] lemma down_ssubset_down {s t : set_semiring Ξ±} : s.down β t.down β s < t := iff.rfl
instance set_semiring.add_comm_monoid : add_comm_monoid (set_semiring Ξ±) :=
{ add := Ξ» s t, (s βͺ t : set Ξ±),
zero := (β
: set Ξ±),
add_assoc := union_assoc,
zero_add := empty_union,
add_zero := union_empty,
add_comm := union_comm, }
instance set_semiring.non_unital_non_assoc_semiring [has_mul Ξ±] :
non_unital_non_assoc_semiring (set_semiring Ξ±) :=
{ zero_mul := Ξ» s, empty_mul,
mul_zero := Ξ» s, mul_empty,
left_distrib := Ξ» _ _ _, mul_union,
right_distrib := Ξ» _ _ _, union_mul,
..set.has_mul, ..set_semiring.add_comm_monoid }
instance set_semiring.non_assoc_semiring [mul_one_class Ξ±] : non_assoc_semiring (set_semiring Ξ±) :=
{ ..set_semiring.non_unital_non_assoc_semiring, ..set.mul_one_class }
instance set_semiring.non_unital_semiring [semigroup Ξ±] : non_unital_semiring (set_semiring Ξ±) :=
{ ..set_semiring.non_unital_non_assoc_semiring, ..set.semigroup }
instance set_semiring.semiring [monoid Ξ±] : semiring (set_semiring Ξ±) :=
{ ..set_semiring.non_assoc_semiring, ..set_semiring.non_unital_semiring }
instance set_semiring.non_unital_comm_semiring [comm_semigroup Ξ±] :
non_unital_comm_semiring (set_semiring Ξ±) :=
{ ..set_semiring.non_unital_semiring, ..set.comm_semigroup }
instance set_semiring.comm_semiring [comm_monoid Ξ±] : comm_semiring (set_semiring Ξ±) :=
{ ..set.comm_monoid, ..set_semiring.semiring }
section mul_hom
variables [has_mul Ξ±] [has_mul Ξ²] [mul_hom_class F Ξ± Ξ²] (m : F) {s t : set Ξ±}
@[to_additive]
lemma image_mul : (m : Ξ± β Ξ²) '' (s * t) = m '' s * m '' t := image_image2_distrib $ map_mul m
@[to_additive]
lemma preimage_mul_preimage_subset {s t : set Ξ²} : (m : Ξ± β Ξ²) β»ΒΉ' s * m β»ΒΉ' t β m β»ΒΉ' (s * t) :=
by { rintro _ β¨_, _, _, _, rflβ©, exact β¨_, _, βΉ_βΊ, βΉ_βΊ, (map_mul m _ _).symm β© }
instance set_semiring.no_zero_divisors : no_zero_divisors (set_semiring Ξ±) :=
β¨Ξ» a b ab, a.eq_empty_or_nonempty.imp_right $ Ξ» ha, b.eq_empty_or_nonempty.resolve_right $
Ξ» hb, nonempty.ne_empty β¨_, mul_mem_mul ha.some_mem hb.some_memβ© abβ©
/- Since addition on `set_semiring` is commutative (it is set union), there is no need
to also have the instance `covariant_class (set_semiring Ξ±) (set_semiring Ξ±) (swap (+)) (β€)`. -/
instance set_semiring.covariant_class_add :
covariant_class (set_semiring Ξ±) (set_semiring Ξ±) (+) (β€) :=
{ elim := Ξ» a b c, union_subset_union_right _ }
instance set_semiring.covariant_class_mul_left :
covariant_class (set_semiring Ξ±) (set_semiring Ξ±) (*) (β€) :=
{ elim := Ξ» a b c, mul_subset_mul_left }
instance set_semiring.covariant_class_mul_right :
covariant_class (set_semiring Ξ±) (set_semiring Ξ±) (swap (*)) (β€) :=
{ elim := Ξ» a b c, mul_subset_mul_right }
end mul_hom
/-- The image of a set under a multiplicative homomorphism is a ring homomorphism
with respect to the pointwise operations on sets. -/
def image_hom [monoid Ξ±] [monoid Ξ²] (f : Ξ± β* Ξ²) : set_semiring Ξ± β+* set_semiring Ξ² :=
{ to_fun := image f,
map_zero' := image_empty _,
map_one' := by simp only [β singleton_one, image_singleton, f.map_one],
map_add' := image_union _,
map_mul' := Ξ» _ _, image_mul f }
end monoid
section comm_monoid
variable [comm_monoid Ξ±]
instance : canonically_ordered_comm_semiring (set_semiring Ξ±) :=
{ add_le_add_left := Ξ» a b, add_le_add_left,
le_iff_exists_add := Ξ» a b, β¨Ξ» ab, β¨b, (union_eq_right_iff_subset.2 ab).symmβ©,
by { rintro β¨c, rflβ©, exact subset_union_left _ _ }β©,
..(infer_instance : comm_semiring (set_semiring Ξ±)),
..(infer_instance : partial_order (set_semiring Ξ±)),
..(infer_instance : order_bot (set_semiring Ξ±)),
..(infer_instance : no_zero_divisors (set_semiring Ξ±)) }
end comm_monoid
end set
open set
open_locale pointwise
section
section smul_with_zero
variables [has_zero Ξ±] [has_zero Ξ²] [smul_with_zero Ξ± Ξ²]
/-- A nonempty set is scaled by zero to the singleton set containing 0. -/
lemma zero_smul_set {s : set Ξ²} (h : s.nonempty) : (0 : Ξ±) β’ s = (0 : set Ξ²) :=
by simp only [β image_smul, image_eta, zero_smul, h.image_const, singleton_zero]
lemma zero_smul_subset (s : set Ξ²) : (0 : Ξ±) β’ s β 0 := image_subset_iff.2 $ Ξ» x _, zero_smul Ξ± x
lemma subsingleton_zero_smul_set (s : set Ξ²) : ((0 : Ξ±) β’ s).subsingleton :=
subsingleton_singleton.mono (zero_smul_subset s)
lemma zero_mem_smul_set {t : set Ξ²} {a : Ξ±} (h : (0 : Ξ²) β t) : (0 : Ξ²) β a β’ t :=
β¨0, h, smul_zero' _ _β©
variables [no_zero_smul_divisors Ξ± Ξ²] {s : set Ξ±} {t : set Ξ²} {a : Ξ±}
lemma zero_mem_smul_iff : (0 : Ξ²) β s β’ t β (0 : Ξ±) β s β§ t.nonempty β¨ (0 : Ξ²) β t β§ s.nonempty :=
begin
split,
{ rintro β¨a, b, ha, hb, hβ©,
obtain rfl | rfl := eq_zero_or_eq_zero_of_smul_eq_zero h,
{ exact or.inl β¨ha, b, hbβ© },
{ exact or.inr β¨hb, a, haβ© } },
{ rintro (β¨hs, b, hbβ© | β¨ht, a, haβ©),
{ exact β¨0, b, hs, hb, zero_smul _ _β© },
{ exact β¨a, 0, ha, ht, smul_zero' _ _β© } }
end
lemma zero_mem_smul_set_iff (ha : a β 0) : (0 : Ξ²) β a β’ t β (0 : Ξ²) β t :=
begin
refine β¨_, zero_mem_smul_setβ©,
rintro β¨b, hb, hβ©,
rwa (eq_zero_or_eq_zero_of_smul_eq_zero h).resolve_left ha at hb,
end
end smul_with_zero
lemma smul_add_set [monoid Ξ±] [add_monoid Ξ²] [distrib_mul_action Ξ± Ξ²] (c : Ξ±) (s t : set Ξ²) :
c β’ (s + t) = c β’ s + c β’ t :=
image_add (distrib_mul_action.to_add_monoid_hom Ξ² c).to_add_hom
section group
variables [group Ξ±] [mul_action Ξ± Ξ²] {A B : set Ξ²} {a : Ξ±} {x : Ξ²}
@[simp, to_additive]
lemma smul_mem_smul_set_iff : a β’ x β a β’ A β x β A :=
β¨Ξ» h, begin
rw [βinv_smul_smul a x, βinv_smul_smul a A],
exact smul_mem_smul_set h,
end, smul_mem_smul_setβ©
@[to_additive]
lemma mem_smul_set_iff_inv_smul_mem : x β a β’ A β aβ»ΒΉ β’ x β A :=
show x β mul_action.to_perm a '' A β _, from mem_image_equiv
@[to_additive]
lemma mem_inv_smul_set_iff : x β aβ»ΒΉ β’ A β a β’ x β A :=
by simp only [β image_smul, mem_image, inv_smul_eq_iff, exists_eq_right]
@[to_additive]
lemma preimage_smul (a : Ξ±) (t : set Ξ²) : (Ξ» x, a β’ x) β»ΒΉ' t = aβ»ΒΉ β’ t :=
((mul_action.to_perm a).symm.image_eq_preimage _).symm
@[to_additive]
lemma preimage_smul_inv (a : Ξ±) (t : set Ξ²) : (Ξ» x, aβ»ΒΉ β’ x) β»ΒΉ' t = a β’ t :=
preimage_smul (to_units a)β»ΒΉ t
@[simp, to_additive]
lemma set_smul_subset_set_smul_iff : a β’ A β a β’ B β A β B :=
image_subset_image_iff $ mul_action.injective _
@[to_additive]
lemma set_smul_subset_iff : a β’ A β B β A β aβ»ΒΉ β’ B :=
(image_subset_iff).trans $ iff_of_eq $ congr_arg _ $
preimage_equiv_eq_image_symm _ $ mul_action.to_perm _
@[to_additive]
lemma subset_set_smul_iff : A β a β’ B β aβ»ΒΉ β’ A β B :=
iff.symm $ (image_subset_iff).trans $ iff.symm $ iff_of_eq $ congr_arg _ $
image_equiv_eq_preimage_symm _ $ mul_action.to_perm _
end group
section group_with_zero
variables [group_with_zero Ξ±] [mul_action Ξ± Ξ²] {s : set Ξ±} {a : Ξ±}
@[simp] lemma smul_mem_smul_set_iffβ (ha : a β 0) (A : set Ξ²)
(x : Ξ²) : a β’ x β a β’ A β x β A :=
show units.mk0 a ha β’ _ β _ β _, from smul_mem_smul_set_iff
lemma mem_smul_set_iff_inv_smul_memβ (ha : a β 0) (A : set Ξ²) (x : Ξ²) :
x β a β’ A β aβ»ΒΉ β’ x β A :=
show _ β units.mk0 a ha β’ _ β _, from mem_smul_set_iff_inv_smul_mem
lemma mem_inv_smul_set_iffβ (ha : a β 0) (A : set Ξ²) (x : Ξ²) : x β aβ»ΒΉ β’ A β a β’ x β A :=
show _ β (units.mk0 a ha)β»ΒΉ β’ _ β _, from mem_inv_smul_set_iff
lemma preimage_smulβ (ha : a β 0) (t : set Ξ²) : (Ξ» x, a β’ x) β»ΒΉ' t = aβ»ΒΉ β’ t :=
preimage_smul (units.mk0 a ha) t
lemma preimage_smul_invβ (ha : a β 0) (t : set Ξ²) :
(Ξ» x, aβ»ΒΉ β’ x) β»ΒΉ' t = a β’ t :=
preimage_smul ((units.mk0 a ha)β»ΒΉ) t
@[simp] lemma set_smul_subset_set_smul_iffβ (ha : a β 0) {A B : set Ξ²} :
a β’ A β a β’ B β A β B :=
show units.mk0 a ha β’ _ β _ β _, from set_smul_subset_set_smul_iff
lemma set_smul_subset_iffβ (ha : a β 0) {A B : set Ξ²} : a β’ A β B β A β aβ»ΒΉ β’ B :=
show units.mk0 a ha β’ _ β _ β _, from set_smul_subset_iff
lemma subset_set_smul_iffβ (ha : a β 0) {A B : set Ξ²} : A β a β’ B β aβ»ΒΉ β’ A β B :=
show _ β units.mk0 a ha β’ _ β _, from subset_set_smul_iff
lemma smul_univβ (hs : Β¬ s β 0) : s β’ (univ : set Ξ²) = univ :=
let β¨a, ha, haββ© := not_subset.1 hs in eq_univ_of_forall $ Ξ» b,
β¨a, aβ»ΒΉ β’ b, ha, trivial, smul_inv_smulβ haβ _β©
lemma smul_set_univβ (ha : a β 0) : a β’ (univ : set Ξ²) = univ :=
eq_univ_of_forall $ Ξ» b, β¨aβ»ΒΉ β’ b, trivial, smul_inv_smulβ ha _β©
end group_with_zero
end
/-! Some lemmas about pointwise multiplication and submonoids. Ideally we put these in
`group_theory.submonoid.basic`, but currently we cannot because that file is imported by this. -/
namespace submonoid
variables {M : Type*} [monoid M] {s t u : set M}
@[to_additive]
lemma mul_subset {S : submonoid M} (hs : s β S) (ht : t β S) : s * t β S :=
by { rintro _ β¨p, q, hp, hq, rflβ©, exact submonoid.mul_mem _ (hs hp) (ht hq) }
@[to_additive]
lemma mul_subset_closure (hs : s β u) (ht : t β u) : s * t β submonoid.closure u :=
mul_subset (subset.trans hs submonoid.subset_closure) (subset.trans ht submonoid.subset_closure)
@[to_additive]
lemma coe_mul_self_eq (s : submonoid M) : (s : set M) * s = s :=
begin
ext x,
refine β¨_, Ξ» h, β¨x, 1, h, s.one_mem, mul_one xβ©β©,
rintro β¨a, b, ha, hb, rflβ©,
exact s.mul_mem ha hb
end
@[to_additive]
lemma closure_mul_le (S T : set M) : closure (S * T) β€ closure S β closure T :=
Inf_le $ Ξ» x β¨s, t, hs, ht, hxβ©, hx βΈ (closure S β closure T).mul_mem
(set_like.le_def.mp le_sup_left $ subset_closure hs)
(set_like.le_def.mp le_sup_right $ subset_closure ht)
@[to_additive]
lemma sup_eq_closure (H K : submonoid M) : H β K = closure (H * K) :=
le_antisymm
(sup_le
(Ξ» h hh, subset_closure β¨h, 1, hh, K.one_mem, mul_one hβ©)
(Ξ» k hk, subset_closure β¨1, k, H.one_mem, hk, one_mul kβ©))
(by conv_rhs { rw [β closure_eq H, β closure_eq K] }; apply closure_mul_le)
lemma pow_smul_mem_closure_smul {N : Type*} [comm_monoid N] [mul_action M N]
[is_scalar_tower M N N] (r : M) (s : set N) {x : N} (hx : x β closure s) :
β n : β, r ^ n β’ x β closure (r β’ s) :=
begin
apply @closure_induction N _ s
(Ξ» (x : N), β n : β, r ^ n β’ x β closure (r β’ s)) _ hx,
{ intros x hx,
exact β¨1, subset_closure β¨_, hx, by rw pow_oneβ©β© },
{ exact β¨0, by simpa using one_mem _β© },
{ rintro x y β¨nx, hxβ© β¨ny, hyβ©,
use nx + ny,
convert mul_mem hx hy,
rw [pow_add, smul_mul_assoc, mul_smul, mul_comm, β smul_mul_assoc, mul_comm] }
end
end submonoid
namespace group
lemma card_pow_eq_card_pow_card_univ_aux {f : β β β} (h1 : monotone f)
{B : β} (h2 : β n, f n β€ B) (h3 : β n, f n = f (n + 1) β f (n + 1) = f (n + 2)) :
β k, B β€ k β f k = f B :=
begin
have key : β n : β, n β€ B β§ f n = f (n + 1),
{ contrapose! h2,
suffices : β n : β, n β€ B + 1 β n β€ f n,
{ exact β¨B + 1, this (B + 1) (le_refl (B + 1))β© },
exact Ξ» n, nat.rec (Ξ» h, nat.zero_le (f 0)) (Ξ» n ih h, lt_of_le_of_lt (ih (n.le_succ.trans h))
(lt_of_le_of_ne (h1 n.le_succ) (h2 n (nat.succ_le_succ_iff.mp h)))) n },
{ obtain β¨n, hn1, hn2β© := key,
replace key : β k : β, f (n + k) = f (n + k + 1) β§ f (n + k) = f n :=
Ξ» k, nat.rec β¨hn2, rflβ© (Ξ» k ih, β¨h3 _ ih.1, ih.1.symm.trans ih.2β©) k,
replace key : β k : β, n β€ k β f k = f n :=
Ξ» k hk, (congr_arg f (add_tsub_cancel_of_le hk)).symm.trans (key (k - n)).2,
exact Ξ» k hk, (key k (hn1.trans hk)).trans (key B hn1).symm },
end
variables {G : Type*} [group G] [fintype G] (S : set G)
@[to_additive]
lemma card_pow_eq_card_pow_card_univ [β (k : β), decidable_pred (β (S ^ k))] :
β k, fintype.card G β€ k β fintype.card β₯(S ^ k) = fintype.card β₯(S ^ (fintype.card G)) :=
begin
have hG : 0 < fintype.card G := fintype.card_pos_iff.mpr β¨1β©,
by_cases hS : S = β
,
{ refine Ξ» k hk, fintype.card_congr _,
rw [hS, empty_pow _ (ne_of_gt (lt_of_lt_of_le hG hk)), empty_pow _ (ne_of_gt hG)] },
obtain β¨a, haβ© := set.ne_empty_iff_nonempty.mp hS,
classical,
have key : β a (s t : set G), (β b : G, b β s β a * b β t) β fintype.card s β€ fintype.card t,
{ refine Ξ» a s t h, fintype.card_le_of_injective (Ξ» β¨b, hbβ©, β¨a * b, h b hbβ©) _,
rintro β¨b, hbβ© β¨c, hcβ© hbc,
exact subtype.ext (mul_left_cancel (subtype.ext_iff.mp hbc)) },
have mono : monotone (Ξ» n, fintype.card β₯(S ^ n) : β β β) :=
monotone_nat_of_le_succ (Ξ» n, key a _ _ (Ξ» b hb, set.mul_mem_mul ha hb)),
convert card_pow_eq_card_pow_card_univ_aux mono (Ξ» n, set_fintype_card_le_univ (S ^ n))
(Ξ» n h, le_antisymm (mono (n + 1).le_succ) (key aβ»ΒΉ _ _ _)),
{ simp only [finset.filter_congr_decidable, fintype.card_of_finset] },
replace h : {a} * S ^ n = S ^ (n + 1),
{ refine set.eq_of_subset_of_card_le _ (le_trans (ge_of_eq h) _),
{ exact mul_subset_mul (set.singleton_subset_iff.mpr ha) set.subset.rfl },
{ convert key a (S ^ n) ({a} * S ^ n) (Ξ» b hb, set.mul_mem_mul (set.mem_singleton a) hb) } },
rw [pow_succ', βh, mul_assoc, βpow_succ', h],
rintro _ β¨b, c, hb, hc, rflβ©,
rwa [set.mem_singleton_iff.mp hb, inv_mul_cancel_left],
end
end group
|
019c167fbad4b05a091120d25a0d3795f6b122d7 | f1a12d4db0f46eee317d703e3336d33950a2fe7e | /lia/common/correctness.lean | 956009ae7837eab1e6cd1e706a2c8139e8741a41 | [
"Apache-2.0"
] | permissive | avigad/qelim | bce89b79c717b7649860d41a41a37e37c982624f | b7d22864f1f0a2d21adad0f4fb3fc7ba665f8e60 | refs/heads/master | 1,584,548,938,232 | 1,526,773,708,000 | 1,526,773,708,000 | 134,967,693 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,868 | lean | import .atom
import ...common.lnq ...common.ldq ...common.predicates
variables {Ξ± Ξ² : Type}
namespace lia
lemma down_closed_fnormal : @down_closed (lia.atom) (fnormal int)
| β€' _ hd _ := by cases hd
| β₯' _ hd _ := by cases hd
| (A' a) _ hd _ := by cases hd
| (p β§' q) r hd hn :=
by {unfold fnormal at hn, cases hn, cases hd; assumption}
| (p β¨' q) r hd hn :=
by {unfold fnormal at hn, cases hn, cases hd; assumption}
| (Β¬' p) r hd hn := by {cases hd, apply hn}
| (β' p) r hd hn := by {cases hd, apply hn}
lemma prop_up_closed_fnormal : @prop_up_closed (lia.atom) (fnormal int)
| β€' := trivial
| β₯' := trivial
| (A' a) := trivial
| (p β§' q) := begin intros hp hq, apply and.intro hp hq end
| (p β¨' q) := begin intros hp hq, apply and.intro hp hq end
| (Β¬' p) := id
| (β' p) := trivial
lemma fnormal_and_o : β (p q : fm atom), fnormal int p β fnormal int q β fnormal int (and_o p q)
:= pred_and_o (fnormal int) prop_up_closed_fnormal
lemma fnormal_or_o : β (p q : fm atom), fnormal int p β fnormal int q β fnormal int (or_o p q)
:= pred_or_o (fnormal int) prop_up_closed_fnormal
lemma fnormal_list_disj : β (ps : list (fm atom)), (β p β ps, fnormal int p) β fnormal int (list_disj ps) :=
pred_list_disj _ prop_up_closed_fnormal
lemma fnormal_disj : β (bs : list Ξ²) (f : Ξ² β fm atom), (β b β bs, fnormal int (f b)) β fnormal int (disj bs f) :=
pred_disj _ prop_up_closed_fnormal
meta def nnf_closed_fnormal_aux :=
`[unfold nnf, unfold fnormal,
unfold fnormal at hn, cases hn with hnp hnq,
cases (nnf_closed_fnormal_core hnp) with hnp1 hnp2,
cases (nnf_closed_fnormal_core hnq) with hnq1 hnq2,
apply and.intro; apply and.intro; assumption]
lemma nnf_closed_fnormal_core : β {p : fm lia.atom},
fnormal int p β fnormal int (nnf int p) β§ fnormal int (nnf int (Β¬' p))
| β€' hn := and.intro trivial trivial
| β₯' hn := and.intro trivial trivial
| (A' a) hn :=
begin
unfold nnf, apply and.intro,
apply hn, rewrite fnormal_iff_fnormal_alt,
apply atom_type.neg_prsv_normal, apply hn
end
| (p β§' q) hn := by nnf_closed_fnormal_aux
| (p β¨' q) hn := by nnf_closed_fnormal_aux
| (Β¬' p) hn :=
begin
apply and.symm, unfold fnormal at hn,
unfold nnf, apply nnf_closed_fnormal_core hn
end
| (β' p) hn :=
begin unfold nnf, apply and.intro; trivial end
lemma nnf_closed_fnormal : preserves (@nnf lia.atom int _) (fnormal int) :=
Ξ» p hn, (nnf_closed_fnormal_core hn)^.elim_left
lemma atoms_and_o_subset {p q : fm lia.atom} :
atoms (and_o p q) β atoms p βͺ atoms q :=
begin
apply cases_and_o' (Ξ» p' q' r, atoms r β atoms p' βͺ atoms q') p q;
intros a ha,
apply list.mem_union_right, apply ha,
apply list.mem_union_left, apply ha,
apply list.mem_union_left, apply ha,
apply list.mem_union_right, apply ha,
apply ha
end
lemma lnq_closed_fnormal (f : fm atom β fm atom)
(hc : preserves f (fnormal β€)) : preserves (lift_nnf_qe β€ f) (fnormal β€)
| β€' hn := trivial
| β₯' hn := trivial
| (A' a) hn := by {unfold lift_nnf_qe, apply hn}
| (p β§' q) hn :=
begin
unfold fnormal at hn , cases hn with hnp hnq,
unfold lift_nnf_qe, apply cases_and_o, trivial,
apply lnq_closed_fnormal, apply hnp,
apply lnq_closed_fnormal, apply hnq,
apply and.intro; apply lnq_closed_fnormal; assumption,
end
| (p β¨' q) hn :=
begin
unfold fnormal at hn , cases hn with hnp hnq,
unfold lift_nnf_qe, apply cases_or_o, trivial,
apply lnq_closed_fnormal, apply hnp,
apply lnq_closed_fnormal, apply hnq,
apply and.intro; apply lnq_closed_fnormal; assumption,
end
| (Β¬' p) hn :=
begin
unfold fnormal at hn, unfold lift_nnf_qe, apply cases_not_o,
trivial, trivial, apply lnq_closed_fnormal, apply hn
end
| (β' p) hn :=
begin
unfold lift_nnf_qe, apply hc,
apply nnf_closed_fnormal,
apply lnq_closed_fnormal, apply hn
end
theorem lnq_prsv
(qe : fm lia.atom β fm lia.atom)
(hqe : preserves qe (fnormal int))
(hqf : qfree_res_of_nqfree_arg qe)
(hi : β p, nqfree p β fnormal int p β β (bs : list int), I (qe p) bs β β b, (I p (b::bs))) :
β p, fnormal int p β β (bs : list int), I (lift_nnf_qe int qe p) bs β I p bs :=
@lnq_prsv_gen lia.atom int lia.atom_type
qe hqf (fnormal int) down_closed_fnormal hqe
nnf_closed_fnormal lnq_closed_fnormal hi
theorem ldq_prsv
(qe : list lia.atom β fm lia.atom)
(hqf : β as, (β a β as, dep0 a) β qfree (qe as))
(hn : β as, (β a β as, dep0 a) β (β a β as, normal a) β fnormal int (qe as))
(he : β as, (β a β as, dep0 a) β (β a β as, normal a) β qe_prsv int qe as) :
β p, fnormal int p β β (bs : list int), I (lift_dnf_qe int qe p) bs β I p bs :=
@ldq_prsv_gen lia.atom int lia.atom_type _ hqf hn he
end lia
|
14f30052864407dd58e47896dd25fcb89da06e8e | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/linear_algebra/multilinear.lean | 52658d431157afad6fa6afc8694cf3714cd403d7 | [
"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 | 54,408 | lean | /-
Copyright (c) 2020 SΓ©bastien GouΓ«zel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: SΓ©bastien GouΓ«zel
-/
import linear_algebra.basic
import algebra.algebra.basic
import algebra.big_operators.order
import data.fintype.sort
/-!
# Multilinear maps
We define multilinear maps as maps from `Ξ (i : ΞΉ), Mβ i` to `Mβ` which are linear in each
coordinate. Here, `Mβ i` and `Mβ` are modules over a ring `R`, and `ΞΉ` is an arbitrary type
(although some statements will require it to be a fintype). This space, denoted by
`multilinear_map R Mβ Mβ`, inherits a module structure by pointwise addition and multiplication.
## Main definitions
* `multilinear_map R Mβ Mβ` is the space of multilinear maps from `Ξ (i : ΞΉ), Mβ i` to `Mβ`.
* `f.map_smul` is the multiplicativity of the multilinear map `f` along each coordinate.
* `f.map_add` is the additivity of the multilinear map `f` along each coordinate.
* `f.map_smul_univ` expresses the multiplicativity of `f` over all coordinates at the same time,
writing `f (Ξ»i, c i β’ m i)` as `(β i, c i) β’ f m`.
* `f.map_add_univ` expresses the additivity of `f` over all coordinates at the same time, writing
`f (m + m')` as the sum over all subsets `s` of `ΞΉ` of `f (s.piecewise m m')`.
* `f.map_sum` expresses `f (Ξ£_{jβ} gβ jβ, ..., Ξ£_{jβ} gβ jβ)` as the sum of
`f (gβ (r 1), ..., gβ (r n))` where `r` ranges over all possible functions.
We also register isomorphisms corresponding to currying or uncurrying variables, transforming a
multilinear function `f` on `n+1` variables into a linear function taking values in multilinear
functions in `n` variables, and into a multilinear function in `n` variables taking values in linear
functions. These operations are called `f.curry_left` and `f.curry_right` respectively
(with inverses `f.uncurry_left` and `f.uncurry_right`). These operations induce linear equivalences
between spaces of multilinear functions in `n+1` variables and spaces of linear functions into
multilinear functions in `n` variables (resp. multilinear functions in `n` variables taking values
in linear functions), called respectively `multilinear_curry_left_equiv` and
`multilinear_curry_right_equiv`.
## Implementation notes
Expressing that a map is linear along the `i`-th coordinate when all other coordinates are fixed
can be done in two (equivalent) different ways:
* fixing a vector `m : Ξ (j : ΞΉ - i), Mβ j.val`, and then choosing separately the `i`-th coordinate
* fixing a vector `m : Ξ j, Mβ j`, and then modifying its `i`-th coordinate
The second way is more artificial as the value of `m` at `i` is not relevant, but it has the
advantage of avoiding subtype inclusion issues. This is the definition we use, based on
`function.update` that allows to change the value of `m` at `i`.
-/
open function fin set
open_locale big_operators
universes u v v' vβ vβ vβ w u'
variables {R : Type u} {ΞΉ : Type u'} {n : β}
{M : fin n.succ β Type v} {Mβ : ΞΉ β Type vβ} {Mβ : Type vβ} {Mβ : Type vβ} {M' : Type v'}
[decidable_eq ΞΉ]
/-- Multilinear maps over the ring `R`, from `Ξ i, Mβ i` to `Mβ` where `Mβ i` and `Mβ` are modules
over `R`. -/
structure multilinear_map (R : Type u) {ΞΉ : Type u'} (Mβ : ΞΉ β Type v) (Mβ : Type w)
[decidable_eq ΞΉ] [semiring R] [βi, add_comm_monoid (Mβ i)] [add_comm_monoid Mβ]
[βi, module R (Mβ i)] [module R Mβ] :=
(to_fun : (Ξ i, Mβ i) β Mβ)
(map_add' : β(m : Ξ i, Mβ i) (i : ΞΉ) (x y : Mβ i),
to_fun (update m i (x + y)) = to_fun (update m i x) + to_fun (update m i y))
(map_smul' : β(m : Ξ i, Mβ i) (i : ΞΉ) (c : R) (x : Mβ i),
to_fun (update m i (c β’ x)) = c β’ to_fun (update m i x))
namespace multilinear_map
section semiring
variables [semiring R]
[βi, add_comm_monoid (M i)] [βi, add_comm_monoid (Mβ i)] [add_comm_monoid Mβ] [add_comm_monoid Mβ]
[add_comm_monoid M']
[βi, module R (M i)] [βi, module R (Mβ i)] [module R Mβ] [module R Mβ]
[module R M']
(f f' : multilinear_map R Mβ Mβ)
instance : has_coe_to_fun (multilinear_map R Mβ Mβ) := β¨_, to_funβ©
initialize_simps_projections multilinear_map (to_fun β apply)
@[simp] lemma to_fun_eq_coe : f.to_fun = f := rfl
@[simp] lemma coe_mk (f : (Ξ i, Mβ i) β Mβ) (hβ hβ ) :
β(β¨f, hβ, hββ© : multilinear_map R Mβ Mβ) = f := rfl
theorem congr_fun {f g : multilinear_map R Mβ Mβ} (h : f = g) (x : Ξ i, Mβ i) : f x = g x :=
congr_arg (Ξ» h : multilinear_map R Mβ Mβ, h x) h
theorem congr_arg (f : multilinear_map R Mβ Mβ) {x y : Ξ i, Mβ i} (h : x = y) : f x = f y :=
congr_arg (Ξ» x : Ξ i, Mβ i, f x) h
theorem coe_inj β¦f g : multilinear_map R Mβ Mββ¦ (h : βf = g) : f = g :=
by cases f; cases g; cases h; refl
@[ext] theorem ext {f f' : multilinear_map R Mβ Mβ} (H : β x, f x = f' x) : f = f' :=
coe_inj (funext H)
theorem ext_iff {f g : multilinear_map R Mβ Mβ} : f = g β β x, f x = g x :=
β¨Ξ» h x, h βΈ rfl, Ξ» h, ext hβ©
@[simp] lemma map_add (m : Ξ i, Mβ i) (i : ΞΉ) (x y : Mβ i) :
f (update m i (x + y)) = f (update m i x) + f (update m i y) :=
f.map_add' m i x y
@[simp] lemma map_smul (m : Ξ i, Mβ i) (i : ΞΉ) (c : R) (x : Mβ i) :
f (update m i (c β’ x)) = c β’ f (update m i x) :=
f.map_smul' m i c x
lemma map_coord_zero {m : Ξ i, Mβ i} (i : ΞΉ) (h : m i = 0) : f m = 0 :=
begin
have : (0 : R) β’ (0 : Mβ i) = 0, by simp,
rw [β update_eq_self i m, h, β this, f.map_smul, zero_smul]
end
@[simp] lemma map_update_zero (m : Ξ i, Mβ i) (i : ΞΉ) : f (update m i 0) = 0 :=
f.map_coord_zero i (update_same i 0 m)
@[simp] lemma map_zero [nonempty ΞΉ] : f 0 = 0 :=
begin
obtain β¨i, _β© : βi:ΞΉ, i β set.univ := set.exists_mem_of_nonempty ΞΉ,
exact map_coord_zero f i rfl
end
instance : has_add (multilinear_map R Mβ Mβ) :=
β¨Ξ»f f', β¨Ξ»x, f x + f' x, Ξ»m i x y, by simp [add_left_comm, add_assoc],
Ξ»m i c x, by simp [smul_add]β©β©
@[simp] lemma add_apply (m : Ξ i, Mβ i) : (f + f') m = f m + f' m := rfl
instance : has_zero (multilinear_map R Mβ Mβ) :=
β¨β¨Ξ» _, 0, Ξ»m i x y, by simp, Ξ»m i c x, by simpβ©β©
instance : inhabited (multilinear_map R Mβ Mβ) := β¨0β©
@[simp] lemma zero_apply (m : Ξ i, Mβ i) : (0 : multilinear_map R Mβ Mβ) m = 0 := rfl
instance : add_comm_monoid (multilinear_map R Mβ Mβ) :=
{ zero := (0 : multilinear_map R Mβ Mβ),
add := (+),
add_assoc := by intros; ext; simp [add_comm, add_left_comm],
zero_add := by intros; ext; simp [add_comm, add_left_comm],
add_zero := by intros; ext; simp [add_comm, add_left_comm],
add_comm := by intros; ext; simp [add_comm, add_left_comm],
nsmul := Ξ» n f, β¨Ξ» m, n β’ f m, Ξ»m i x y, by simp [smul_add], Ξ»l i x d, by simp [βsmul_comm x n] β©,
nsmul_zero' := Ξ» f, by { ext, simp },
nsmul_succ' := Ξ» n f, by { ext, simp [add_smul, nat.succ_eq_one_add] } }
@[simp] lemma sum_apply {Ξ± : Type*} (f : Ξ± β multilinear_map R Mβ Mβ)
(m : Ξ i, Mβ i) : β {s : finset Ξ±}, (β a in s, f a) m = β a in s, f a m :=
begin
classical,
apply finset.induction,
{ rw finset.sum_empty, simp },
{ assume a s has H, rw finset.sum_insert has, simp [H, has] }
end
/-- If `f` is a multilinear map, then `f.to_linear_map m i` is the linear map obtained by fixing all
coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/
def to_linear_map (m : Ξ i, Mβ i) (i : ΞΉ) : Mβ i ββ[R] Mβ :=
{ to_fun := Ξ»x, f (update m i x),
map_add' := Ξ»x y, by simp,
map_smul' := Ξ»c x, by simp }
/-- The cartesian product of two multilinear maps, as a multilinear map. -/
def prod (f : multilinear_map R Mβ Mβ) (g : multilinear_map R Mβ Mβ) :
multilinear_map R Mβ (Mβ Γ Mβ) :=
{ to_fun := Ξ» m, (f m, g m),
map_add' := Ξ» m i x y, by simp,
map_smul' := Ξ» m i c x, by simp }
/-- Combine a family of multilinear maps with the same domain and codomains `M' i` into a
multilinear map taking values in the space of functions `Ξ i, M' i`. -/
@[simps] def pi {ΞΉ' : Type*} {M' : ΞΉ' β Type*} [Ξ i, add_comm_monoid (M' i)]
[Ξ i, module R (M' i)] (f : Ξ i, multilinear_map R Mβ (M' i)) :
multilinear_map R Mβ (Ξ i, M' i) :=
{ to_fun := Ξ» m i, f i m,
map_add' := Ξ» m i x y, funext $ Ξ» j, (f j).map_add _ _ _ _,
map_smul' := Ξ» m i c x, funext $ Ξ» j, (f j).map_smul _ _ _ _ }
/-- Given a multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k`
of these variables, one gets a new multilinear map on `fin k` by varying these variables, and fixing
the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a
proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that
we use is the canonical (increasing) bijection. -/
def restr {k n : β} (f : multilinear_map R (Ξ» i : fin n, M') Mβ) (s : finset (fin n))
(hk : s.card = k) (z : M') :
multilinear_map R (Ξ» i : fin k, M') Mβ :=
{ to_fun := Ξ» v, f (Ξ» j, if h : j β s then v ((s.order_iso_of_fin hk).symm β¨j, hβ©) else z),
map_add' := Ξ» v i x y,
by { erw [dite_comp_equiv_update, dite_comp_equiv_update, dite_comp_equiv_update], simp },
map_smul' := Ξ» v i c x, by { erw [dite_comp_equiv_update, dite_comp_equiv_update], simp } }
variable {R}
/-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build
an element of `Ξ (i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a
multilinear map along the first variable. -/
lemma cons_add (f : multilinear_map R M Mβ) (m : Ξ (i : fin n), M i.succ) (x y : M 0) :
f (cons (x+y) m) = f (cons x m) + f (cons y m) :=
by rw [β update_cons_zero x m (x+y), f.map_add, update_cons_zero, update_cons_zero]
/-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build
an element of `Ξ (i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity
of a multilinear map along the first variable. -/
lemma cons_smul (f : multilinear_map R M Mβ) (m : Ξ (i : fin n), M i.succ) (c : R) (x : M 0) :
f (cons (c β’ x) m) = c β’ f (cons x m) :=
by rw [β update_cons_zero x m (c β’ x), f.map_smul, update_cons_zero]
/-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build
an element of `Ξ (i : fin (n+1)), M i` using `snoc`, one can express directly the additivity of a
multilinear map along the first variable. -/
lemma snoc_add (f : multilinear_map R M Mβ) (m : Ξ (i : fin n), M i.cast_succ) (x y : M (last n)) :
f (snoc m (x+y)) = f (snoc m x) + f (snoc m y) :=
by rw [β update_snoc_last x m (x+y), f.map_add, update_snoc_last, update_snoc_last]
/-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build
an element of `Ξ (i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity
of a multilinear map along the first variable. -/
lemma snoc_smul (f : multilinear_map R M Mβ)
(m : Ξ (i : fin n), M i.cast_succ) (c : R) (x : M (last n)) :
f (snoc m (c β’ x)) = c β’ f (snoc m x) :=
by rw [β update_snoc_last x m (c β’ x), f.map_smul, update_snoc_last]
section
variables {Mβ' : ΞΉ β Type*} [Ξ i, add_comm_monoid (Mβ' i)] [Ξ i, module R (Mβ' i)]
/-- If `g` is a multilinear map and `f` is a collection of linear maps,
then `g (fβ mβ, ..., fβ mβ)` is again a multilinear map, that we call
`g.comp_linear_map f`. -/
def comp_linear_map (g : multilinear_map R Mβ' Mβ) (f : Ξ i, Mβ i ββ[R] Mβ' i) :
multilinear_map R Mβ Mβ :=
{ to_fun := Ξ» m, g $ Ξ» i, f i (m i),
map_add' := Ξ» m i x y,
have β j z, f j (update m i z j) = update (Ξ» k, f k (m k)) i (f i z) j :=
Ξ» j z, function.apply_update (Ξ» k, f k) _ _ _ _,
by simp [this],
map_smul' := Ξ» m i c x,
have β j z, f j (update m i z j) = update (Ξ» k, f k (m k)) i (f i z) j :=
Ξ» j z, function.apply_update (Ξ» k, f k) _ _ _ _,
by simp [this] }
@[simp] lemma comp_linear_map_apply (g : multilinear_map R Mβ' Mβ) (f : Ξ i, Mβ i ββ[R] Mβ' i)
(m : Ξ i, Mβ i) :
g.comp_linear_map f m = g (Ξ» i, f i (m i)) :=
rfl
end
/-- If one adds to a vector `m'` another vector `m`, but only for coordinates in a finset `t`, then
the image under a multilinear map `f` is the sum of `f (s.piecewise m m')` along all subsets `s` of
`t`. This is mainly an auxiliary statement to prove the result when `t = univ`, given in
`map_add_univ`, although it can be useful in its own right as it does not require the index set `ΞΉ`
to be finite.-/
lemma map_piecewise_add (m m' : Ξ i, Mβ i) (t : finset ΞΉ) :
f (t.piecewise (m + m') m') = β s in t.powerset, f (s.piecewise m m') :=
begin
revert m',
refine finset.induction_on t (by simp) _,
assume i t hit Hrec m',
have A : (insert i t).piecewise (m + m') m' = update (t.piecewise (m + m') m') i (m i + m' i) :=
t.piecewise_insert _ _ _,
have B : update (t.piecewise (m + m') m') i (m' i) = t.piecewise (m + m') m',
{ ext j,
by_cases h : j = i,
{ rw h, simp [hit] },
{ simp [h] } },
let m'' := update m' i (m i),
have C : update (t.piecewise (m + m') m') i (m i) = t.piecewise (m + m'') m'',
{ ext j,
by_cases h : j = i,
{ rw h, simp [m'', hit] },
{ by_cases h' : j β t; simp [h, hit, m'', h'] } },
rw [A, f.map_add, B, C, finset.sum_powerset_insert hit, Hrec, Hrec, add_comm],
congr' 1,
apply finset.sum_congr rfl (Ξ»s hs, _),
have : (insert i s).piecewise m m' = s.piecewise m m'',
{ ext j,
by_cases h : j = i,
{ rw h, simp [m'', finset.not_mem_of_mem_powerset_of_not_mem hs hit] },
{ by_cases h' : j β s; simp [h, m'', h'] } },
rw this
end
/-- Additivity of a multilinear map along all coordinates at the same time,
writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/
lemma map_add_univ [fintype ΞΉ] (m m' : Ξ i, Mβ i) :
f (m + m') = β s : finset ΞΉ, f (s.piecewise m m') :=
by simpa using f.map_piecewise_add m m' finset.univ
section apply_sum
variables {Ξ± : ΞΉ β Type*} (g : Ξ i, Ξ± i β Mβ i) (A : Ξ i, finset (Ξ± i))
open_locale classical
open fintype finset
/-- If `f` is multilinear, then `f (Ξ£_{jβ β Aβ} gβ jβ, ..., Ξ£_{jβ β Aβ} gβ jβ)` is the sum of
`f (gβ (r 1), ..., gβ (r n))` where `r` ranges over all functions with `r 1 β Aβ`, ...,
`r n β Aβ`. This follows from multilinearity by expanding successively with respect to each
coordinate. Here, we give an auxiliary statement tailored for an inductive proof. Use instead
`map_sum_finset`. -/
lemma map_sum_finset_aux [fintype ΞΉ] {n : β} (h : β i, (A i).card = n) :
f (Ξ» i, β j in A i, g i j) = β r in pi_finset A, f (Ξ» i, g i (r i)) :=
begin
induction n using nat.strong_induction_on with n IH generalizing A,
-- If one of the sets is empty, then all the sums are zero
by_cases Ai_empty : β i, A i = β
,
{ rcases Ai_empty with β¨i, hiβ©,
have : β j in A i, g i j = 0, by convert sum_empty,
rw f.map_coord_zero i this,
have : pi_finset A = β
,
{ apply finset.eq_empty_of_forall_not_mem (Ξ» r hr, _),
have : r i β A i := mem_pi_finset.mp hr i,
rwa hi at this },
convert sum_empty.symm },
push_neg at Ai_empty,
-- Otherwise, if all sets are at most singletons, then they are exactly singletons and the result
-- is again straightforward
by_cases Ai_singleton : β i, (A i).card β€ 1,
{ have Ai_card : β i, (A i).card = 1,
{ assume i,
have pos : finset.card (A i) β 0, by simp [finset.card_eq_zero, Ai_empty i],
have : finset.card (A i) β€ 1 := Ai_singleton i,
exact le_antisymm this (nat.succ_le_of_lt (_root_.pos_iff_ne_zero.mpr pos)) },
have : β (r : Ξ i, Ξ± i), r β pi_finset A β f (Ξ» i, g i (r i)) = f (Ξ» i, β j in A i, g i j),
{ assume r hr,
unfold_coes,
congr' with i,
have : β j β A i, g i j = g i (r i),
{ assume j hj,
congr,
apply finset.card_le_one_iff.1 (Ai_singleton i) hj,
exact mem_pi_finset.mp hr i },
simp only [finset.sum_congr rfl this, finset.mem_univ, finset.sum_const, Ai_card i,
one_nsmul] },
simp only [sum_congr rfl this, Ai_card, card_pi_finset, prod_const_one, one_nsmul,
finset.sum_const] },
-- Remains the interesting case where one of the `A i`, say `A iβ`, has cardinality at least 2.
-- We will split into two parts `B iβ` and `C iβ` of smaller cardinality, let `B i = C i = A i`
-- for `i β iβ`, apply the inductive assumption to `B` and `C`, and add up the corresponding
-- parts to get the sum for `A`.
push_neg at Ai_singleton,
obtain β¨iβ, hiββ© : β i, 1 < (A i).card := Ai_singleton,
obtain β¨jβ, jβ, hjβ, hjβ, jβ_ne_jββ© : β jβ jβ, (jβ β A iβ) β§ (jβ β A iβ) β§ jβ β jβ :=
finset.one_lt_card_iff.1 hiβ,
let B := function.update A iβ (A iβ \ {jβ}),
let C := function.update A iβ {jβ},
have B_subset_A : β i, B i β A i,
{ assume i,
by_cases hi : i = iβ,
{ rw hi, simp only [B, sdiff_subset, update_same]},
{ simp only [hi, B, update_noteq, ne.def, not_false_iff, finset.subset.refl] } },
have C_subset_A : β i, C i β A i,
{ assume i,
by_cases hi : i = iβ,
{ rw hi, simp only [C, hjβ, finset.singleton_subset_iff, update_same] },
{ simp only [hi, C, update_noteq, ne.def, not_false_iff, finset.subset.refl] } },
-- split the sum at `iβ` as the sum over `B iβ` plus the sum over `C iβ`, to use additivity.
have A_eq_BC : (Ξ» i, β j in A i, g i j) =
function.update (Ξ» i, β j in A i, g i j) iβ (β j in B iβ, g iβ j + β j in C iβ, g iβ j),
{ ext i,
by_cases hi : i = iβ,
{ rw [hi],
simp only [function.update_same],
have : A iβ = B iβ βͺ C iβ,
{ simp only [B, C, function.update_same, finset.sdiff_union_self_eq_union],
symmetry,
simp only [hjβ, finset.singleton_subset_iff, union_eq_left_iff_subset] },
rw this,
apply finset.sum_union,
apply finset.disjoint_right.2 (Ξ» j hj, _),
have : j = jβ, by { dsimp [C] at hj, simpa using hj },
rw this,
dsimp [B],
simp only [mem_sdiff, eq_self_iff_true, not_true, not_false_iff, finset.mem_singleton,
update_same, and_false] },
{ simp [hi] } },
have Beq : function.update (Ξ» i, β j in A i, g i j) iβ (β j in B iβ, g iβ j) =
(Ξ» i, β j in B i, g i j),
{ ext i,
by_cases hi : i = iβ,
{ rw hi, simp only [update_same] },
{ simp only [hi, B, update_noteq, ne.def, not_false_iff] } },
have Ceq : function.update (Ξ» i, β j in A i, g i j) iβ (β j in C iβ, g iβ j) =
(Ξ» i, β j in C i, g i j),
{ ext i,
by_cases hi : i = iβ,
{ rw hi, simp only [update_same] },
{ simp only [hi, C, update_noteq, ne.def, not_false_iff] } },
-- Express the inductive assumption for `B`
have Brec : f (Ξ» i, β j in B i, g i j) = β r in pi_finset B, f (Ξ» i, g i (r i)),
{ have : β i, finset.card (B i) < β i, finset.card (A i),
{ refine finset.sum_lt_sum (Ξ» i hi, finset.card_le_of_subset (B_subset_A i))
β¨iβ, finset.mem_univ _, _β©,
have : {jβ} β A iβ, by simp [hjβ],
simp only [B, finset.card_sdiff this, function.update_same, finset.card_singleton],
exact nat.pred_lt (ne_of_gt (lt_trans nat.zero_lt_one hiβ)) },
rw h at this,
exact IH _ this B rfl },
-- Express the inductive assumption for `C`
have Crec : f (Ξ» i, β j in C i, g i j) = β r in pi_finset C, f (Ξ» i, g i (r i)),
{ have : β i, finset.card (C i) < β i, finset.card (A i) :=
finset.sum_lt_sum (Ξ» i hi, finset.card_le_of_subset (C_subset_A i))
β¨iβ, finset.mem_univ _, by simp [C, hiβ]β©,
rw h at this,
exact IH _ this C rfl },
have D : disjoint (pi_finset B) (pi_finset C),
{ have : disjoint (B iβ) (C iβ), by simp [B, C],
exact pi_finset_disjoint_of_disjoint B C this },
have pi_BC : pi_finset A = pi_finset B βͺ pi_finset C,
{ apply finset.subset.antisymm,
{ assume r hr,
by_cases hriβ : r iβ = jβ,
{ apply finset.mem_union_right,
apply mem_pi_finset.2 (Ξ» i, _),
by_cases hi : i = iβ,
{ have : r iβ β C iβ, by simp [C, hriβ],
convert this },
{ simp [C, hi, mem_pi_finset.1 hr i] } },
{ apply finset.mem_union_left,
apply mem_pi_finset.2 (Ξ» i, _),
by_cases hi : i = iβ,
{ have : r iβ β B iβ,
by simp [B, hriβ, mem_pi_finset.1 hr iβ],
convert this },
{ simp [B, hi, mem_pi_finset.1 hr i] } } },
{ exact finset.union_subset (pi_finset_subset _ _ (Ξ» i, B_subset_A i))
(pi_finset_subset _ _ (Ξ» i, C_subset_A i)) } },
rw A_eq_BC,
simp only [multilinear_map.map_add, Beq, Ceq, Brec, Crec, pi_BC],
rw β finset.sum_union D,
end
/-- If `f` is multilinear, then `f (Ξ£_{jβ β Aβ} gβ jβ, ..., Ξ£_{jβ β Aβ} gβ jβ)` is the sum of
`f (gβ (r 1), ..., gβ (r n))` where `r` ranges over all functions with `r 1 β Aβ`, ...,
`r n β Aβ`. This follows from multilinearity by expanding successively with respect to each
coordinate. -/
lemma map_sum_finset [fintype ΞΉ] :
f (Ξ» i, β j in A i, g i j) = β r in pi_finset A, f (Ξ» i, g i (r i)) :=
f.map_sum_finset_aux _ _ rfl
/-- If `f` is multilinear, then `f (Ξ£_{jβ} gβ jβ, ..., Ξ£_{jβ} gβ jβ)` is the sum of
`f (gβ (r 1), ..., gβ (r n))` where `r` ranges over all functions `r`. This follows from
multilinearity by expanding successively with respect to each coordinate. -/
lemma map_sum [fintype ΞΉ] [β i, fintype (Ξ± i)] :
f (Ξ» i, β j, g i j) = β r : Ξ i, Ξ± i, f (Ξ» i, g i (r i)) :=
f.map_sum_finset g (Ξ» i, finset.univ)
lemma map_update_sum {Ξ± : Type*} (t : finset Ξ±) (i : ΞΉ) (g : Ξ± β Mβ i) (m : Ξ i, Mβ i):
f (update m i (β a in t, g a)) = β a in t, f (update m i (g a)) :=
begin
induction t using finset.induction with a t has ih h,
{ simp },
{ simp [finset.sum_insert has, ih] }
end
end apply_sum
section restrict_scalar
variables (R) {A : Type*} [semiring A] [has_scalar R A] [Ξ (i : ΞΉ), module A (Mβ i)]
[module A Mβ] [β i, is_scalar_tower R A (Mβ i)] [is_scalar_tower R A Mβ]
/-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R`
and their actions on all involved modules agree with the action of `R` on `A`. -/
def restrict_scalars (f : multilinear_map A Mβ Mβ) : multilinear_map R Mβ Mβ :=
{ to_fun := f,
map_add' := f.map_add,
map_smul' := Ξ» m i, (f.to_linear_map m i).map_smul_of_tower }
@[simp] lemma coe_restrict_scalars (f : multilinear_map A Mβ Mβ) :
β(f.restrict_scalars R) = f := rfl
end restrict_scalar
section
variables {ΞΉβ ΞΉβ ΞΉβ : Type*} [decidable_eq ΞΉβ] [decidable_eq ΞΉβ] [decidable_eq ΞΉβ]
/-- Transfer the arguments to a map along an equivalence between argument indices.
The naming is derived from `finsupp.dom_congr`, noting that here the permutation applies to the
domain of the domain. -/
@[simps apply]
def dom_dom_congr (Ο : ΞΉβ β ΞΉβ) (m : multilinear_map R (Ξ» i : ΞΉβ, Mβ) Mβ) :
multilinear_map R (Ξ» i : ΞΉβ, Mβ) Mβ :=
{ to_fun := Ξ» v, m (Ξ» i, v (Ο i)),
map_add' := Ξ» v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_add, },
map_smul' := Ξ» v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_smul, }, }
lemma dom_dom_congr_trans (Οβ : ΞΉβ β ΞΉβ) (Οβ : ΞΉβ β ΞΉβ) (m : multilinear_map R (Ξ» i : ΞΉβ, Mβ) Mβ) :
m.dom_dom_congr (Οβ.trans Οβ) = (m.dom_dom_congr Οβ).dom_dom_congr Οβ := rfl
lemma dom_dom_congr_mul (Οβ : equiv.perm ΞΉβ) (Οβ : equiv.perm ΞΉβ)
(m : multilinear_map R (Ξ» i : ΞΉβ, Mβ) Mβ) :
m.dom_dom_congr (Οβ * Οβ) = (m.dom_dom_congr Οβ).dom_dom_congr Οβ := rfl
/-- `multilinear_map.dom_dom_congr` as an equivalence.
This is declared separately because it does not work with dot notation. -/
@[simps apply symm_apply]
def dom_dom_congr_equiv (Ο : ΞΉβ β ΞΉβ) :
multilinear_map R (Ξ» i : ΞΉβ, Mβ) Mβ β+ multilinear_map R (Ξ» i : ΞΉβ, Mβ) Mβ :=
{ to_fun := dom_dom_congr Ο,
inv_fun := dom_dom_congr Ο.symm,
left_inv := Ξ» m, by {ext, simp},
right_inv := Ξ» m, by {ext, simp},
map_add' := Ξ» a b, by {ext, simp} }
end
end semiring
end multilinear_map
namespace linear_map
variables [semiring R]
[Ξ i, add_comm_monoid (Mβ i)] [add_comm_monoid Mβ] [add_comm_monoid Mβ] [add_comm_monoid M']
[βi, module R (Mβ i)] [module R Mβ] [module R Mβ] [module R M']
/-- Composing a multilinear map with a linear map gives again a multilinear map. -/
def comp_multilinear_map (g : Mβ ββ[R] Mβ) (f : multilinear_map R Mβ Mβ) :
multilinear_map R Mβ Mβ :=
{ to_fun := g β f,
map_add' := Ξ» m i x y, by simp,
map_smul' := Ξ» m i c x, by simp }
@[simp] lemma coe_comp_multilinear_map (g : Mβ ββ[R] Mβ) (f : multilinear_map R Mβ Mβ) :
β(g.comp_multilinear_map f) = g β f := rfl
lemma comp_multilinear_map_apply (g : Mβ ββ[R] Mβ) (f : multilinear_map R Mβ Mβ) (m : Ξ i, Mβ i) :
g.comp_multilinear_map f m = g (f m) := rfl
variables {ΞΉβ ΞΉβ : Type*} [decidable_eq ΞΉβ] [decidable_eq ΞΉβ]
@[simp] lemma comp_multilinear_map_dom_dom_congr (Ο : ΞΉβ β ΞΉβ) (g : Mβ ββ[R] Mβ)
(f : multilinear_map R (Ξ» i : ΞΉβ, M') Mβ) :
(g.comp_multilinear_map f).dom_dom_congr Ο = g.comp_multilinear_map (f.dom_dom_congr Ο) :=
by { ext, simp }
end linear_map
namespace multilinear_map
section comm_semiring
variables [comm_semiring R] [βi, add_comm_monoid (Mβ i)] [βi, add_comm_monoid (M i)]
[add_comm_monoid Mβ] [βi, module R (M i)] [βi, module R (Mβ i)] [module R Mβ]
(f f' : multilinear_map R Mβ Mβ)
/-- If one multiplies by `c i` the coordinates in a finset `s`, then the image under a multilinear
map is multiplied by `β i in s, c i`. This is mainly an auxiliary statement to prove the result when
`s = univ`, given in `map_smul_univ`, although it can be useful in its own right as it does not
require the index set `ΞΉ` to be finite. -/
lemma map_piecewise_smul (c : ΞΉ β R) (m : Ξ i, Mβ i) (s : finset ΞΉ) :
f (s.piecewise (Ξ»i, c i β’ m i) m) = (β i in s, c i) β’ f m :=
begin
refine s.induction_on (by simp) _,
assume j s j_not_mem_s Hrec,
have A : function.update (s.piecewise (Ξ»i, c i β’ m i) m) j (m j) =
s.piecewise (Ξ»i, c i β’ m i) m,
{ ext i,
by_cases h : i = j,
{ rw h, simp [j_not_mem_s] },
{ simp [h] } },
rw [s.piecewise_insert, f.map_smul, A, Hrec],
simp [j_not_mem_s, mul_smul]
end
/-- Multiplicativity of a multilinear map along all coordinates at the same time,
writing `f (Ξ»i, c i β’ m i)` as `(β i, c i) β’ f m`. -/
lemma map_smul_univ [fintype ΞΉ] (c : ΞΉ β R) (m : Ξ i, Mβ i) :
f (Ξ»i, c i β’ m i) = (β i, c i) β’ f m :=
by simpa using map_piecewise_smul f c m finset.univ
section distrib_mul_action
variables {R' A : Type*} [monoid R'] [semiring A]
[Ξ i, module A (Mβ i)] [distrib_mul_action R' Mβ] [module A Mβ] [smul_comm_class A R' Mβ]
instance : has_scalar R' (multilinear_map A Mβ Mβ) := β¨Ξ» c f,
β¨Ξ» m, c β’ f m, Ξ»m i x y, by simp [smul_add], Ξ»l i x d, by simp [βsmul_comm x c] β©β©
@[simp] lemma smul_apply (f : multilinear_map A Mβ Mβ) (c : R') (m : Ξ i, Mβ i) :
(c β’ f) m = c β’ f m := rfl
instance : distrib_mul_action R' (multilinear_map A Mβ Mβ) :=
{ one_smul := Ξ» f, ext $ Ξ» x, one_smul _ _,
mul_smul := Ξ» cβ cβ f, ext $ Ξ» x, mul_smul _ _ _,
smul_zero := Ξ» r, ext $ Ξ» x, smul_zero _,
smul_add := Ξ» r fβ fβ, ext $ Ξ» x, smul_add _ _ _ }
end distrib_mul_action
section module
variables {R' A : Type*} [semiring R'] [semiring A]
[Ξ i, module A (Mβ i)] [module A Mβ]
[add_comm_monoid Mβ] [module R' Mβ] [module A Mβ] [smul_comm_class A R' Mβ]
/-- The space of multilinear maps over an algebra over `R` is a module over `R`, for the pointwise
addition and scalar multiplication. -/
instance [module R' Mβ] [smul_comm_class A R' Mβ] : module R' (multilinear_map A Mβ Mβ) :=
{ add_smul := Ξ» rβ rβ f, ext $ Ξ» x, add_smul _ _ _,
zero_smul := Ξ» f, ext $ Ξ» x, zero_smul _ _ }
variables (Mβ Mβ R' A)
/-- `multilinear_map.dom_dom_congr` as a `linear_equiv`. -/
@[simps apply symm_apply]
def dom_dom_congr_linear_equiv {ΞΉβ ΞΉβ} [decidable_eq ΞΉβ] [decidable_eq ΞΉβ] (Ο : ΞΉβ β ΞΉβ) :
multilinear_map A (Ξ» i : ΞΉβ, Mβ) Mβ ββ[R'] multilinear_map A (Ξ» i : ΞΉβ, Mβ) Mβ :=
{ map_smul' := Ξ» c f, by { ext, simp },
.. (dom_dom_congr_equiv Ο : multilinear_map A (Ξ» i : ΞΉβ, Mβ) Mβ β+
multilinear_map A (Ξ» i : ΞΉβ, Mβ) Mβ) }
end module
section dom_coprod
open_locale tensor_product
variables {ΞΉβ ΞΉβ ΞΉβ ΞΉβ : Type*}
variables [decidable_eq ΞΉβ] [decidable_eq ΞΉβ][decidable_eq ΞΉβ] [decidable_eq ΞΉβ]
variables {Nβ : Type*} [add_comm_monoid Nβ] [module R Nβ]
variables {Nβ : Type*} [add_comm_monoid Nβ] [module R Nβ]
variables {N : Type*} [add_comm_monoid N] [module R N]
/-- Given two multilinear maps `(ΞΉβ β N) β Nβ` and `(ΞΉβ β N) β Nβ`, this produces the map
`(ΞΉβ β ΞΉβ β N) β Nβ β Nβ` by taking the coproduct of the domain and the tensor product
of the codomain.
This can be thought of as combining `equiv.sum_arrow_equiv_prod_arrow.symm` with
`tensor_product.map`, noting that the two operations can't be separated as the intermediate result
is not a `multilinear_map`.
While this can be generalized to work for dependent `Ξ i : ΞΉβ, N'β i` instead of `ΞΉβ β N`, doing so
introduces `sum.elim N'β N'β` types in the result which are difficult to work with and not defeq
to the simple case defined here. See [this zulip thread](
https://leanprover.zulipchat.com/#narrow/stream/217875-Is-there.20code.20for.20X.3F/topic/Instances.20on.20.60sum.2Eelim.20A.20B.20i.60/near/218484619).
-/
@[simps apply]
def dom_coprod
(a : multilinear_map R (Ξ» _ : ΞΉβ, N) Nβ) (b : multilinear_map R (Ξ» _ : ΞΉβ, N) Nβ) :
multilinear_map R (Ξ» _ : ΞΉβ β ΞΉβ, N) (Nβ β[R] Nβ) :=
{ to_fun := Ξ» v, a (Ξ» i, v (sum.inl i)) ββ b (Ξ» i, v (sum.inr i)),
map_add' := Ξ» v i p q, by cases i; simp [tensor_product.add_tmul, tensor_product.tmul_add],
map_smul' := Ξ» v i c p, by cases i; simp [tensor_product.smul_tmul', tensor_product.tmul_smul] }
/-- A more bundled version of `multilinear_map.dom_coprod` that maps
`((ΞΉβ β N) β Nβ) β ((ΞΉβ β N) β Nβ)` to `(ΞΉβ β ΞΉβ β N) β Nβ β Nβ`. -/
def dom_coprod' :
multilinear_map R (Ξ» _ : ΞΉβ, N) Nβ β[R] multilinear_map R (Ξ» _ : ΞΉβ, N) Nβ ββ[R]
multilinear_map R (Ξ» _ : ΞΉβ β ΞΉβ, N) (Nβ β[R] Nβ) :=
tensor_product.lift $ linear_map.mkβ R (dom_coprod)
(Ξ» mβ mβ n, by { ext, simp only [dom_coprod_apply, tensor_product.add_tmul, add_apply] })
(Ξ» c m n, by { ext, simp only [dom_coprod_apply, tensor_product.smul_tmul', smul_apply] })
(Ξ» m nβ nβ, by { ext, simp only [dom_coprod_apply, tensor_product.tmul_add, add_apply] })
(Ξ» c m n, by { ext, simp only [dom_coprod_apply, tensor_product.tmul_smul, smul_apply] })
@[simp]
lemma dom_coprod'_apply
(a : multilinear_map R (Ξ» _ : ΞΉβ, N) Nβ) (b : multilinear_map R (Ξ» _ : ΞΉβ, N) Nβ) :
dom_coprod' (a ββ[R] b) = dom_coprod a b := rfl
/-- When passed an `equiv.sum_congr`, `multilinear_map.dom_dom_congr` distributes over
`multilinear_map.dom_coprod`. -/
lemma dom_coprod_dom_dom_congr_sum_congr
(a : multilinear_map R (Ξ» _ : ΞΉβ, N) Nβ) (b : multilinear_map R (Ξ» _ : ΞΉβ, N) Nβ)
(Οa : ΞΉβ β ΞΉβ) (Οb : ΞΉβ β ΞΉβ) :
(a.dom_coprod b).dom_dom_congr (Οa.sum_congr Οb) =
(a.dom_dom_congr Οa).dom_coprod (b.dom_dom_congr Οb) := rfl
end dom_coprod
section
variables (R ΞΉ) (A : Type*) [comm_semiring A] [algebra R A] [fintype ΞΉ]
/-- Given an `R`-algebra `A`, `mk_pi_algebra` is the multilinear map on `A^ΞΉ` associating
to `m` the product of all the `m i`.
See also `multilinear_map.mk_pi_algebra_fin` for a version that works with a non-commutative
algebra `A` but requires `ΞΉ = fin n`. -/
protected def mk_pi_algebra : multilinear_map R (Ξ» i : ΞΉ, A) A :=
{ to_fun := Ξ» m, β i, m i,
map_add' := Ξ» m i x y, by simp [finset.prod_update_of_mem, add_mul],
map_smul' := Ξ» m i c x, by simp [finset.prod_update_of_mem] }
variables {R A ΞΉ}
@[simp] lemma mk_pi_algebra_apply (m : ΞΉ β A) :
multilinear_map.mk_pi_algebra R ΞΉ A m = β i, m i :=
rfl
end
section
variables (R n) (A : Type*) [semiring A] [algebra R A]
/-- Given an `R`-algebra `A`, `mk_pi_algebra_fin` is the multilinear map on `A^n` associating
to `m` the product of all the `m i`.
See also `multilinear_map.mk_pi_algebra` for a version that assumes `[comm_semiring A]` but works
for `A^ΞΉ` with any finite type `ΞΉ`. -/
protected def mk_pi_algebra_fin : multilinear_map R (Ξ» i : fin n, A) A :=
{ to_fun := Ξ» m, (list.of_fn m).prod,
map_add' :=
begin
intros m i x y,
have : (list.fin_range n).index_of i < n,
by simpa using list.index_of_lt_length.2 (list.mem_fin_range i),
simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, add_mul,
this, mul_add, add_mul]
end,
map_smul' :=
begin
intros m i c x,
have : (list.fin_range n).index_of i < n,
by simpa using list.index_of_lt_length.2 (list.mem_fin_range i),
simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, this]
end }
variables {R A n}
@[simp] lemma mk_pi_algebra_fin_apply (m : fin n β A) :
multilinear_map.mk_pi_algebra_fin R n A m = (list.of_fn m).prod :=
rfl
lemma mk_pi_algebra_fin_apply_const (a : A) :
multilinear_map.mk_pi_algebra_fin R n A (Ξ» _, a) = a ^ n :=
by simp
end
/-- Given an `R`-multilinear map `f` taking values in `R`, `f.smul_right z` is the map
sending `m` to `f m β’ z`. -/
def smul_right (f : multilinear_map R Mβ R) (z : Mβ) : multilinear_map R Mβ Mβ :=
(linear_map.smul_right linear_map.id z).comp_multilinear_map f
@[simp] lemma smul_right_apply (f : multilinear_map R Mβ R) (z : Mβ) (m : Ξ i, Mβ i) :
f.smul_right z m = f m β’ z :=
rfl
variables (R ΞΉ)
/-- The canonical multilinear map on `R^ΞΉ` when `ΞΉ` is finite, associating to `m` the product of
all the `m i` (multiplied by a fixed reference element `z` in the target module). See also
`mk_pi_algebra` for a more general version. -/
protected def mk_pi_ring [fintype ΞΉ] (z : Mβ) : multilinear_map R (Ξ»(i : ΞΉ), R) Mβ :=
(multilinear_map.mk_pi_algebra R ΞΉ R).smul_right z
variables {R ΞΉ}
@[simp] lemma mk_pi_ring_apply [fintype ΞΉ] (z : Mβ) (m : ΞΉ β R) :
(multilinear_map.mk_pi_ring R ΞΉ z : (ΞΉ β R) β Mβ) m = (β i, m i) β’ z := rfl
lemma mk_pi_ring_apply_one_eq_self [fintype ΞΉ] (f : multilinear_map R (Ξ»(i : ΞΉ), R) Mβ) :
multilinear_map.mk_pi_ring R ΞΉ (f (Ξ»i, 1)) = f :=
begin
ext m,
have : m = (Ξ»i, m i β’ 1), by { ext j, simp },
conv_rhs { rw [this, f.map_smul_univ] },
refl
end
end comm_semiring
section range_add_comm_group
variables [semiring R] [βi, add_comm_monoid (Mβ i)] [add_comm_group Mβ]
[βi, module R (Mβ i)] [module R Mβ]
(f g : multilinear_map R Mβ Mβ)
instance : has_neg (multilinear_map R Mβ Mβ) :=
β¨Ξ» f, β¨Ξ» m, - f m, Ξ»m i x y, by simp [add_comm], Ξ»m i c x, by simpβ©β©
@[simp] lemma neg_apply (m : Ξ i, Mβ i) : (-f) m = - (f m) := rfl
instance : has_sub (multilinear_map R Mβ Mβ) :=
β¨Ξ» f g,
β¨Ξ» m, f m - g m,
Ξ» m i x y, by { simp only [map_add, sub_eq_add_neg, neg_add], cc },
Ξ» m i c x, by { simp only [map_smul, smul_sub] }β©β©
@[simp] lemma sub_apply (m : Ξ i, Mβ i) : (f - g) m = f m - g m := rfl
instance : add_comm_group (multilinear_map R Mβ Mβ) :=
by refine
{ zero := (0 : multilinear_map R Mβ Mβ),
add := (+),
neg := has_neg.neg,
sub := has_sub.sub,
sub_eq_add_neg := _,
nsmul := Ξ» n f, β¨Ξ» m, n β’ f m, Ξ»m i x y, by simp [smul_add], Ξ»l i x d, by simp [βsmul_comm x n] β©,
gsmul := Ξ» n f, β¨Ξ» m, n β’ f m, Ξ»m i x y, by simp [smul_add], Ξ»l i x d, by simp [βsmul_comm x n] β©,
gsmul_zero' := _,
gsmul_succ' := _,
gsmul_neg' := _,
.. multilinear_map.add_comm_monoid, .. };
intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg, add_smul, nat.succ_eq_add_one]
end range_add_comm_group
section add_comm_group
variables [semiring R] [βi, add_comm_group (Mβ i)] [add_comm_group Mβ]
[βi, module R (Mβ i)] [module R Mβ]
(f : multilinear_map R Mβ Mβ)
@[simp] lemma map_neg (m : Ξ i, Mβ i) (i : ΞΉ) (x : Mβ i) :
f (update m i (-x)) = -f (update m i x) :=
eq_neg_of_add_eq_zero $ by rw [βmap_add, add_left_neg, f.map_coord_zero i (update_same i 0 m)]
@[simp] lemma map_sub (m : Ξ i, Mβ i) (i : ΞΉ) (x y : Mβ i) :
f (update m i (x - y)) = f (update m i x) - f (update m i y) :=
by rw [sub_eq_add_neg, sub_eq_add_neg, map_add, map_neg]
end add_comm_group
section comm_semiring
variables [comm_semiring R] [βi, add_comm_monoid (Mβ i)] [add_comm_monoid Mβ]
[βi, module R (Mβ i)] [module R Mβ]
/-- When `ΞΉ` is finite, multilinear maps on `R^ΞΉ` with values in `Mβ` are in bijection with `Mβ`,
as such a multilinear map is completely determined by its value on the constant vector made of ones.
We register this bijection as a linear equivalence in `multilinear_map.pi_ring_equiv`. -/
protected def pi_ring_equiv [fintype ΞΉ] : Mβ ββ[R] (multilinear_map R (Ξ»(i : ΞΉ), R) Mβ) :=
{ to_fun := Ξ» z, multilinear_map.mk_pi_ring R ΞΉ z,
inv_fun := Ξ» f, f (Ξ»i, 1),
map_add' := Ξ» z z', by { ext m, simp [smul_add] },
map_smul' := Ξ» c z, by { ext m, simp [smul_smul, mul_comm] },
left_inv := Ξ» z, by simp,
right_inv := Ξ» f, f.mk_pi_ring_apply_one_eq_self }
end comm_semiring
end multilinear_map
section currying
/-!
### Currying
We associate to a multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two
curried functions, named `f.curry_left` (which is a linear map on `E 0` taking values
in multilinear maps in `n` variables) and `f.curry_right` (wich is a multilinear map in `n`
variables taking values in linear maps on `E 0`). In both constructions, the variable that is
singled out is `0`, to take advantage of the operations `cons` and `tail` on `fin n`.
The inverse operations are called `uncurry_left` and `uncurry_right`.
We also register linear equiv versions of these correspondences, in
`multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`.
-/
open multilinear_map
variables {R M Mβ}
[comm_semiring R] [βi, add_comm_monoid (M i)] [add_comm_monoid M'] [add_comm_monoid Mβ]
[βi, module R (M i)] [module R M'] [module R Mβ]
/-! #### Left currying -/
/-- Given a linear map `f` from `M 0` to multilinear maps on `n` variables,
construct the corresponding multilinear map on `n+1` variables obtained by concatenating
the variables, given by `m β¦ f (m 0) (tail m)`-/
def linear_map.uncurry_left
(f : M 0 ββ[R] (multilinear_map R (Ξ»(i : fin n), M i.succ) Mβ)) :
multilinear_map R M Mβ :=
{ to_fun := Ξ»m, f (m 0) (tail m),
map_add' := Ξ»m i x y, begin
by_cases h : i = 0,
{ subst i,
rw [update_same, update_same, update_same, f.map_add, add_apply,
tail_update_zero, tail_update_zero, tail_update_zero] },
{ rw [update_noteq (ne.symm h), update_noteq (ne.symm h), update_noteq (ne.symm h)],
revert x y,
rw β succ_pred i h,
assume x y,
rw [tail_update_succ, map_add, tail_update_succ, tail_update_succ] }
end,
map_smul' := Ξ»m i c x, begin
by_cases h : i = 0,
{ subst i,
rw [update_same, update_same, tail_update_zero, tail_update_zero,
β smul_apply, f.map_smul] },
{ rw [update_noteq (ne.symm h), update_noteq (ne.symm h)],
revert x,
rw β succ_pred i h,
assume x,
rw [tail_update_succ, tail_update_succ, map_smul] }
end }
@[simp] lemma linear_map.uncurry_left_apply
(f : M 0 ββ[R] (multilinear_map R (Ξ»(i : fin n), M i.succ) Mβ)) (m : Ξ i, M i) :
f.uncurry_left m = f (m 0) (tail m) := rfl
/-- Given a multilinear map `f` in `n+1` variables, split the first variable to obtain
a linear map into multilinear maps in `n` variables, given by `x β¦ (m β¦ f (cons x m))`. -/
def multilinear_map.curry_left
(f : multilinear_map R M Mβ) :
M 0 ββ[R] (multilinear_map R (Ξ»(i : fin n), M i.succ) Mβ) :=
{ to_fun := Ξ»x,
{ to_fun := Ξ»m, f (cons x m),
map_add' := Ξ»m i y y', by simp,
map_smul' := Ξ»m i y c, by simp },
map_add' := Ξ»x y, by { ext m, exact cons_add f m x y },
map_smul' := Ξ»c x, by { ext m, exact cons_smul f m c x } }
@[simp] lemma multilinear_map.curry_left_apply
(f : multilinear_map R M Mβ) (x : M 0) (m : Ξ (i : fin n), M i.succ) :
f.curry_left x m = f (cons x m) := rfl
@[simp] lemma linear_map.curry_uncurry_left
(f : M 0 ββ[R] (multilinear_map R (Ξ»(i : fin n), M i.succ) Mβ)) :
f.uncurry_left.curry_left = f :=
begin
ext m x,
simp only [tail_cons, linear_map.uncurry_left_apply, multilinear_map.curry_left_apply],
rw cons_zero
end
@[simp] lemma multilinear_map.uncurry_curry_left
(f : multilinear_map R M Mβ) :
f.curry_left.uncurry_left = f :=
by { ext m, simp, }
variables (R M Mβ)
/-- The space of multilinear maps on `Ξ (i : fin (n+1)), M i` is canonically isomorphic to
the space of linear maps from `M 0` to the space of multilinear maps on
`Ξ (i : fin n), M i.succ `, by separating the first variable. We register this isomorphism as a
linear isomorphism in `multilinear_curry_left_equiv R M Mβ`.
The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these
unless you need the full framework of linear equivs. -/
def multilinear_curry_left_equiv :
(M 0 ββ[R] (multilinear_map R (Ξ»(i : fin n), M i.succ) Mβ)) ββ[R] (multilinear_map R M Mβ) :=
{ to_fun := linear_map.uncurry_left,
map_add' := Ξ»fβ fβ, by { ext m, refl },
map_smul' := Ξ»c f, by { ext m, refl },
inv_fun := multilinear_map.curry_left,
left_inv := linear_map.curry_uncurry_left,
right_inv := multilinear_map.uncurry_curry_left }
variables {R M Mβ}
/-! #### Right currying -/
/-- Given a multilinear map `f` in `n` variables to the space of linear maps from `M (last n)` to
`Mβ`, construct the corresponding multilinear map on `n+1` variables obtained by concatenating
the variables, given by `m β¦ f (init m) (m (last n))`-/
def multilinear_map.uncurry_right
(f : (multilinear_map R (Ξ»(i : fin n), M i.cast_succ) (M (last n) ββ[R] Mβ))) :
multilinear_map R M Mβ :=
{ to_fun := Ξ»m, f (init m) (m (last n)),
map_add' := Ξ»m i x y, begin
by_cases h : i.val < n,
{ have : last n β i := ne.symm (ne_of_lt h),
rw [update_noteq this, update_noteq this, update_noteq this],
revert x y,
rw [(cast_succ_cast_lt i h).symm],
assume x y,
rw [init_update_cast_succ, map_add, init_update_cast_succ, init_update_cast_succ,
linear_map.add_apply] },
{ revert x y,
rw eq_last_of_not_lt h,
assume x y,
rw [init_update_last, init_update_last, init_update_last,
update_same, update_same, update_same, linear_map.map_add] }
end,
map_smul' := Ξ»m i c x, begin
by_cases h : i.val < n,
{ have : last n β i := ne.symm (ne_of_lt h),
rw [update_noteq this, update_noteq this],
revert x,
rw [(cast_succ_cast_lt i h).symm],
assume x,
rw [init_update_cast_succ, init_update_cast_succ, map_smul, linear_map.smul_apply] },
{ revert x,
rw eq_last_of_not_lt h,
assume x,
rw [update_same, update_same, init_update_last, init_update_last,
linear_map.map_smul] }
end }
@[simp] lemma multilinear_map.uncurry_right_apply
(f : (multilinear_map R (Ξ»(i : fin n), M i.cast_succ) ((M (last n)) ββ[R] Mβ))) (m : Ξ i, M i) :
f.uncurry_right m = f (init m) (m (last n)) := rfl
/-- Given a multilinear map `f` in `n+1` variables, split the last variable to obtain
a multilinear map in `n` variables taking values in linear maps from `M (last n)` to `Mβ`, given by
`m β¦ (x β¦ f (snoc m x))`. -/
def multilinear_map.curry_right (f : multilinear_map R M Mβ) :
multilinear_map R (Ξ»(i : fin n), M (fin.cast_succ i)) ((M (last n)) ββ[R] Mβ) :=
{ to_fun := Ξ»m,
{ to_fun := Ξ»x, f (snoc m x),
map_add' := Ξ»x y, by rw f.snoc_add,
map_smul' := Ξ»c x, by rw f.snoc_smul },
map_add' := Ξ»m i x y, begin
ext z,
change f (snoc (update m i (x + y)) z)
= f (snoc (update m i x) z) + f (snoc (update m i y) z),
rw [snoc_update, snoc_update, snoc_update, f.map_add]
end,
map_smul' := Ξ»m i c x, begin
ext z,
change f (snoc (update m i (c β’ x)) z) = c β’ f (snoc (update m i x) z),
rw [snoc_update, snoc_update, f.map_smul]
end }
@[simp] lemma multilinear_map.curry_right_apply
(f : multilinear_map R M Mβ) (m : Ξ (i : fin n), M i.cast_succ) (x : M (last n)) :
f.curry_right m x = f (snoc m x) := rfl
@[simp] lemma multilinear_map.curry_uncurry_right
(f : (multilinear_map R (Ξ»(i : fin n), M i.cast_succ) ((M (last n)) ββ[R] Mβ))) :
f.uncurry_right.curry_right = f :=
begin
ext m x,
simp only [snoc_last, multilinear_map.curry_right_apply, multilinear_map.uncurry_right_apply],
rw init_snoc
end
@[simp] lemma multilinear_map.uncurry_curry_right
(f : multilinear_map R M Mβ) : f.curry_right.uncurry_right = f :=
by { ext m, simp }
variables (R M Mβ)
/-- The space of multilinear maps on `Ξ (i : fin (n+1)), M i` is canonically isomorphic to
the space of linear maps from the space of multilinear maps on `Ξ (i : fin n), M i.cast_succ` to the
space of linear maps on `M (last n)`, by separating the last variable. We register this isomorphism
as a linear isomorphism in `multilinear_curry_right_equiv R M Mβ`.
The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these
unless you need the full framework of linear equivs. -/
def multilinear_curry_right_equiv :
(multilinear_map R (Ξ»(i : fin n), M i.cast_succ) ((M (last n)) ββ[R] Mβ))
ββ[R] (multilinear_map R M Mβ) :=
{ to_fun := multilinear_map.uncurry_right,
map_add' := Ξ»fβ fβ, by { ext m, refl },
map_smul' := Ξ»c f, by { ext m, rw [smul_apply], refl },
inv_fun := multilinear_map.curry_right,
left_inv := multilinear_map.curry_uncurry_right,
right_inv := multilinear_map.uncurry_curry_right }
namespace multilinear_map
variables {ΞΉ' : Type*} [decidable_eq ΞΉ'] [decidable_eq (ΞΉ β ΞΉ')] {R Mβ}
/-- A multilinear map on `Ξ i : ΞΉ β ΞΉ', M'` defines a multilinear map on `Ξ i : ΞΉ, M'`
taking values in the space of multilinear maps on `Ξ i : ΞΉ', M'`. -/
def curry_sum (f : multilinear_map R (Ξ» x : ΞΉ β ΞΉ', M') Mβ) :
multilinear_map R (Ξ» x : ΞΉ, M') (multilinear_map R (Ξ» x : ΞΉ', M') Mβ) :=
{ to_fun := Ξ» u,
{ to_fun := Ξ» v, f (sum.elim u v),
map_add' := Ξ» v i x y, by simp only [β sum.update_elim_inr, f.map_add],
map_smul' := Ξ» v i c x, by simp only [β sum.update_elim_inr, f.map_smul] },
map_add' := Ξ» u i x y, ext $ Ξ» v,
by simp only [multilinear_map.coe_mk, add_apply, β sum.update_elim_inl, f.map_add],
map_smul' := Ξ» u i c x, ext $ Ξ» v,
by simp only [multilinear_map.coe_mk, smul_apply, β sum.update_elim_inl, f.map_smul] }
@[simp] lemma curry_sum_apply (f : multilinear_map R (Ξ» x : ΞΉ β ΞΉ', M') Mβ)
(u : ΞΉ β M') (v : ΞΉ' β M') :
f.curry_sum u v = f (sum.elim u v) :=
rfl
/-- A multilinear map on `Ξ i : ΞΉ, M'` taking values in the space of multilinear maps
on `Ξ i : ΞΉ', M'` defines a multilinear map on `Ξ i : ΞΉ β ΞΉ', M'`. -/
def uncurry_sum (f : multilinear_map R (Ξ» x : ΞΉ, M') (multilinear_map R (Ξ» x : ΞΉ', M') Mβ)) :
multilinear_map R (Ξ» x : ΞΉ β ΞΉ', M') Mβ :=
{ to_fun := Ξ» u, f (u β sum.inl) (u β sum.inr),
map_add' := Ξ» u i x y, by cases i;
simp only [map_add, add_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr,
sum.update_inr_comp_inl, sum.update_inr_comp_inr],
map_smul' := Ξ» u i c x, by cases i;
simp only [map_smul, smul_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr,
sum.update_inr_comp_inl, sum.update_inr_comp_inr] }
@[simp] lemma uncurry_sum_aux_apply
(f : multilinear_map R (Ξ» x : ΞΉ, M') (multilinear_map R (Ξ» x : ΞΉ', M') Mβ)) (u : ΞΉ β ΞΉ' β M') :
f.uncurry_sum u = f (u β sum.inl) (u β sum.inr) :=
rfl
variables (ΞΉ ΞΉ' R Mβ M')
/-- Linear equivalence between the space of multilinear maps on `Ξ i : ΞΉ β ΞΉ', M'` and the space
of multilinear maps on `Ξ i : ΞΉ, M'` taking values in the space of multilinear maps
on `Ξ i : ΞΉ', M'`. -/
def curry_sum_equiv : multilinear_map R (Ξ» x : ΞΉ β ΞΉ', M') Mβ ββ[R]
multilinear_map R (Ξ» x : ΞΉ, M') (multilinear_map R (Ξ» x : ΞΉ', M') Mβ) :=
{ to_fun := curry_sum,
inv_fun := uncurry_sum,
left_inv := Ξ» f, ext $ Ξ» u, by simp,
right_inv := Ξ» f, by { ext, simp },
map_add' := Ξ» f g, by { ext, refl },
map_smul' := Ξ» c f, by { ext, refl } }
variables {ΞΉ ΞΉ' R Mβ M'}
@[simp] lemma coe_curry_sum_equiv : β(curry_sum_equiv R ΞΉ Mβ M' ΞΉ') = curry_sum := rfl
@[simp] lemma coe_curr_sum_equiv_symm : β(curry_sum_equiv R ΞΉ Mβ M' ΞΉ').symm = uncurry_sum := rfl
variables (R Mβ M')
/-- If `s : finset (fin n)` is a finite set of cardinality `k` and its complement has cardinality
`l`, then the space of multilinear maps on `Ξ» i : fin n, M'` is isomorphic to the space of
multilinear maps on `Ξ» i : fin k, M'` taking values in the space of multilinear maps
on `Ξ» i : fin l, M'`. -/
def curry_fin_finset {k l n : β} {s : finset (fin n)} [decidable_pred (s : set (fin n))]
(hk : s.card = k) (hl : sαΆ.card = l) :
multilinear_map R (Ξ» x : fin n, M') Mβ ββ[R]
multilinear_map R (Ξ» x : fin k, M') (multilinear_map R (Ξ» x : fin l, M') Mβ) :=
(dom_dom_congr_linear_equiv M' Mβ R R (fin_sum_equiv_of_finset hk hl).symm).trans
(curry_sum_equiv R (fin k) Mβ M' (fin l))
variables {R Mβ M'}
@[simp]
lemma curry_fin_finset_apply {k l n : β} {s : finset (fin n)} [decidable_pred (s : set (fin n))]
(hk : s.card = k) (hl : sαΆ.card = l) (f : multilinear_map R (Ξ» x : fin n, M') Mβ)
(mk : fin k β M') (ml : fin l β M') :
curry_fin_finset R Mβ M' hk hl f mk ml =
f (Ξ» i, sum.elim mk ml ((fin_sum_equiv_of_finset hk hl).symm i)) :=
rfl
@[simp] lemma curry_fin_finset_symm_apply {k l n : β} {s : finset (fin n)}
[decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sαΆ.card = l)
(f : multilinear_map R (Ξ» x : fin k, M') (multilinear_map R (Ξ» x : fin l, M') Mβ))
(m : fin n β M') :
(curry_fin_finset R Mβ M' hk hl).symm f m =
f (Ξ» i, m $ fin_sum_equiv_of_finset hk hl (sum.inl i))
(Ξ» i, m $ fin_sum_equiv_of_finset hk hl (sum.inr i)) :=
rfl
@[simp] lemma curry_fin_finset_symm_apply_piecewise_const {k l n : β} {s : finset (fin n)}
[decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sαΆ.card = l)
(f : multilinear_map R (Ξ» x : fin k, M') (multilinear_map R (Ξ» x : fin l, M') Mβ)) (x y : M') :
(curry_fin_finset R Mβ M' hk hl).symm f (s.piecewise (Ξ» _, x) (Ξ» _, y)) = f (Ξ» _, x) (Ξ» _, y) :=
begin
rw curry_fin_finset_symm_apply, congr,
{ ext i, rw [fin_sum_equiv_of_finset_inl, finset.piecewise_eq_of_mem],
apply finset.order_emb_of_fin_mem },
{ ext i, rw [fin_sum_equiv_of_finset_inr, finset.piecewise_eq_of_not_mem],
exact finset.mem_compl.1 (finset.order_emb_of_fin_mem _ _ _) }
end
@[simp] lemma curry_fin_finset_symm_apply_const {k l n : β} {s : finset (fin n)}
[decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sαΆ.card = l)
(f : multilinear_map R (Ξ» x : fin k, M') (multilinear_map R (Ξ» x : fin l, M') Mβ)) (x : M') :
(curry_fin_finset R Mβ M' hk hl).symm f (Ξ» _, x) = f (Ξ» _, x) (Ξ» _, x) :=
rfl
@[simp] lemma curry_fin_finset_apply_const {k l n : β} {s : finset (fin n)}
[decidable_pred (s : set (fin n))]
(hk : s.card = k) (hl : sαΆ.card = l) (f : multilinear_map R (Ξ» x : fin n, M') Mβ) (x y : M') :
curry_fin_finset R Mβ M' hk hl f (Ξ» _, x) (Ξ» _, y) = f (s.piecewise (Ξ» _, x) (Ξ» _, y)) :=
begin
refine (curry_fin_finset_symm_apply_piecewise_const hk hl _ _ _).symm.trans _, -- `rw` fails
rw linear_equiv.symm_apply_apply
end
end multilinear_map
end currying
section submodule
variables {R M Mβ}
[ring R] [βi, add_comm_monoid (Mβ i)] [add_comm_monoid M'] [add_comm_monoid Mβ]
[βi, module R (Mβ i)] [module R M'] [module R Mβ]
namespace multilinear_map
/-- The pushforward of an indexed collection of submodule `p i β Mβ i` by `f : Mβ β Mβ`.
Note that this is not a submodule - it is not closed under addition. -/
def map [nonempty ΞΉ] (f : multilinear_map R Mβ Mβ) (p : Ξ i, submodule R (Mβ i)) :
sub_mul_action R Mβ :=
{ carrier := f '' { v | β i, v i β p i},
smul_mem' := Ξ» c _ β¨x, hx, hfβ©, let β¨iβ© := βΉnonempty ΞΉβΊ in by {
refine β¨update x i (c β’ x i), Ξ» j, if hij : j = i then _ else _, hf βΈ _β©,
{ rw [hij, update_same], exact (p i).smul_mem _ (hx i) },
{ rw [update_noteq hij], exact hx j },
{ rw [f.map_smul, update_eq_self] } } }
/-- The map is always nonempty. This lemma is needed to apply `sub_mul_action.zero_mem`. -/
lemma map_nonempty [nonempty ΞΉ] (f : multilinear_map R Mβ Mβ) (p : Ξ i, submodule R (Mβ i)) :
(map f p : set Mβ).nonempty :=
β¨f 0, 0, Ξ» i, (p i).zero_mem, rflβ©
/-- The range of a multilinear map, closed under scalar multiplication. -/
def range [nonempty ΞΉ] (f : multilinear_map R Mβ Mβ) : sub_mul_action R Mβ :=
f.map (Ξ» i, β€)
end multilinear_map
end submodule
|
7d4cc6cb09d4b92d5a55ee5ff588f1f7eca05574 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/ring_theory/polynomial/chebyshev/defs.lean | c4418ed557c10a4b9b87a8bf90d6d00fb0e369ba | [
"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 | 11,242 | 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 data.polynomial.derivative
import tactic.ring
/-!
# Chebyshev polynomials
The Chebyshev polynomials are two families of polynomials indexed by `β`,
with integral coefficients.
See the file `ring_theory.polynomial.chebyshev.basic` for more properties.
## Main definitions
* `polynomial.chebyshevβ`: the Chebyshev polynomials of the first kind.
* `polynomial.chebyshevβ`: the Chebyshev polynomials of the second kind.
## Main statements
* The formal derivative of the Chebyshev polynomials of the first kind is a scalar multiple of the
Chebyshev polynomials of the second kind.
## Implementation details
In this file we only give definitions and some very elementary simp-lemmas.
This way, we can import this file in `analysis.special_functions.trigonometric`,
and import that file in turn, in `ring_theory.polynomial.chebyshev.basic`.
## References
[Lionel Ponton, _Roots of the Chebyshev polynomials: A purely algebraic approach_]
[ponton2020chebyshev]
## TODO
* Redefine and/or relate the definition of Chebyshev polynomials to `linear_recurrence`.
* Add explicit formula involving square roots for Chebyshev polynomials
`ring_theory.polynomial.chebyshev.basic`.
* Compute zeroes and extrema of Chebyshev polynomials.
* Prove that the roots of the Chebyshev polynomials (except 0) are irrational.
* Prove minimax properties of Chebyshev polynomials.
-/
noncomputable theory
namespace polynomial
variables (R S : Type*) [comm_ring R] [comm_ring S]
/-- `chebyshevβ n` is the `n`-th Chebyshev polynomial of the first kind -/
noncomputable def chebyshevβ : β β polynomial R
| 0 := 1
| 1 := X
| (n + 2) := 2 * X * chebyshevβ (n + 1) - chebyshevβ n
@[simp] lemma chebyshevβ_zero : chebyshevβ R 0 = 1 := rfl
@[simp] lemma chebyshevβ_one : chebyshevβ R 1 = X := rfl
lemma chebyshevβ_two : chebyshevβ R 2 = 2 * X ^ 2 - 1 :=
by simp only [chebyshevβ, sub_left_inj, pow_two, mul_assoc]
@[simp] lemma chebyshevβ_add_two (n : β) :
chebyshevβ R (n + 2) = 2 * X * chebyshevβ R (n + 1) - chebyshevβ R n :=
by rw chebyshevβ
lemma chebyshevβ_of_two_le (n : β) (h : 2 β€ n) :
chebyshevβ R n = 2 * X * chebyshevβ R (n - 1) - chebyshevβ R (n - 2) :=
begin
obtain β¨n, rflβ© := nat.exists_eq_add_of_le h,
rw add_comm,
exact chebyshevβ_add_two R n
end
variables {R S}
lemma map_chebyshevβ (f : R β+* S) :
β (n : β), map f (chebyshevβ R n) = chebyshevβ S n
| 0 := by simp only [chebyshevβ_zero, map_one]
| 1 := by simp only [chebyshevβ_one, map_X]
| (n + 2) :=
begin
simp only [chebyshevβ_add_two, map_mul, map_sub, map_X, bit0, map_add, map_one],
rw [map_chebyshevβ (n + 1), map_chebyshevβ n],
end
end polynomial
namespace polynomial
variables (R S : Type*) [comm_ring R] [comm_ring S]
/-- `chebyshevβ n` is the `n`-th Chebyshev polynomial of the second kind -/
noncomputable def chebyshevβ : β β polynomial R
| 0 := 1
| 1 := 2 * X
| (n + 2) := 2 * X * chebyshevβ (n + 1) - chebyshevβ n
@[simp] lemma chebyshevβ_zero : chebyshevβ R 0 = 1 := rfl
@[simp] lemma chebyshevβ_one : chebyshevβ R 1 = 2 * X := rfl
lemma chebyshevβ_two : chebyshevβ R 2 = 4 * X ^ 2 - 1 :=
by { simp only [chebyshevβ], ring, }
@[simp] lemma chebyshevβ_add_two (n : β) :
chebyshevβ R (n + 2) = 2 * X * chebyshevβ R (n + 1) - chebyshevβ R n :=
by rw chebyshevβ
lemma chebyshevβ_of_two_le (n : β) (h : 2 β€ n) :
chebyshevβ R n = 2 * X * chebyshevβ R (n - 1) - chebyshevβ R (n - 2) :=
begin
obtain β¨n, rflβ© := nat.exists_eq_add_of_le h,
rw add_comm,
exact chebyshevβ_add_two R n
end
lemma chebyshevβ_eq_X_mul_chebyshevβ_add_chebyshevβ :
β (n : β), chebyshevβ R (n+1) = X * chebyshevβ R n + chebyshevβ R (n+1)
| 0 := by { simp only [chebyshevβ_zero, chebyshevβ_one, chebyshevβ_one], ring }
| 1 := by { simp only [chebyshevβ_one, chebyshevβ_two, chebyshevβ_two], ring }
| (n + 2) :=
calc chebyshevβ R (n + 2 + 1) = 2 * X * (X * chebyshevβ R (n + 1) + chebyshevβ R (n + 2))
- (X * chebyshevβ R n + chebyshevβ R (n + 1)) :
by simp only [chebyshevβ_add_two, chebyshevβ_eq_X_mul_chebyshevβ_add_chebyshevβ n,
chebyshevβ_eq_X_mul_chebyshevβ_add_chebyshevβ (n + 1)]
... = X * (2 * X * chebyshevβ R (n + 1) - chebyshevβ R n)
+ (2 * X * chebyshevβ R (n + 2) - chebyshevβ R (n + 1)) :
by ring
... = X * chebyshevβ R (n + 2) + chebyshevβ R (n + 2 + 1) :
by simp only [chebyshevβ_add_two, chebyshevβ_add_two]
lemma chebyshevβ_eq_chebyshevβ_sub_X_mul_chebyshevβ (n : β) :
chebyshevβ R (n+1) = chebyshevβ R (n+1) - X * chebyshevβ R n :=
by rw [chebyshevβ_eq_X_mul_chebyshevβ_add_chebyshevβ, add_comm (X * chebyshevβ R n), add_sub_cancel]
lemma chebyshevβ_eq_X_mul_chebyshevβ_sub_pol_chebyshevβ :
β (n : β), chebyshevβ R (n+2) = X * chebyshevβ R (n+1) - (1 - X ^ 2) * chebyshevβ R n
| 0 := by { simp only [chebyshevβ_one, chebyshevβ_two, chebyshevβ_zero], ring }
| 1 := by { simp only [chebyshevβ_add_two, chebyshevβ_zero, chebyshevβ_add_two,
chebyshevβ_one, chebyshevβ_one], ring }
| (n + 2) :=
calc chebyshevβ R (n + 2 + 2)
= 2 * X * chebyshevβ R (n + 2 + 1) - chebyshevβ R (n + 2) : chebyshevβ_add_two _ _
... = 2 * X * (X * chebyshevβ R (n + 2) - (1 - X ^ 2) * chebyshevβ R (n + 1))
- (X * chebyshevβ R (n + 1) - (1 - X ^ 2) * chebyshevβ R n) :
by simp only [chebyshevβ_eq_X_mul_chebyshevβ_sub_pol_chebyshevβ]
... = X * (2 * X * chebyshevβ R (n + 2) - chebyshevβ R (n + 1))
- (1 - X ^ 2) * (2 * X * chebyshevβ R (n + 1) - chebyshevβ R n) :
by ring
... = X * chebyshevβ R (n + 2 + 1) - (1 - X ^ 2) * chebyshevβ R (n + 2) :
by rw [chebyshevβ_add_two _ (n + 1), chebyshevβ_add_two]
lemma one_sub_X_pow_two_mul_chebyshevβ_eq_pol_in_chebyshevβ (n : β) :
(1 - X ^ 2) * chebyshevβ R n = X * chebyshevβ R (n + 1) - chebyshevβ R (n + 2) :=
by rw [chebyshevβ_eq_X_mul_chebyshevβ_sub_pol_chebyshevβ, βsub_add, sub_self, zero_add]
variables {R S}
@[simp] lemma map_chebyshevβ (f : R β+* S) :
β (n : β), map f (chebyshevβ R n) = chebyshevβ S n
| 0 := by simp only [chebyshevβ_zero, map_one]
| 1 :=
begin
simp only [chebyshevβ_one, map_X, map_mul, map_add, map_one],
change map f (1+1) * X = 2 * X,
simpa only [map_add, map_one]
end
| (n + 2) :=
begin
simp only [chebyshevβ_add_two, map_mul, map_sub, map_X, bit0, map_add, map_one],
rw [map_chebyshevβ (n + 1), map_chebyshevβ n],
end
lemma chebyshevβ_derivative_eq_chebyshevβ :
β (n : β), derivative (chebyshevβ R (n + 1)) = (n + 1) * chebyshevβ R n
| 0 := by simp only [chebyshevβ_one, chebyshevβ_zero, derivative_X, nat.cast_zero, zero_add,
mul_one]
| 1 := by { simp only [chebyshevβ_two, chebyshevβ_one, derivative_sub, derivative_one,
derivative_mul, derivative_X_pow, nat.cast_one,
nat.cast_two],
norm_num }
| (n + 2) :=
calc derivative (chebyshevβ R (n + 2 + 1))
= 2 * chebyshevβ R (n + 2) + 2 * X * derivative (chebyshevβ R (n + 1 + 1))
- derivative (chebyshevβ R (n + 1)) :
by simp only [chebyshevβ_add_two _ (n + 1), derivative_sub, derivative_mul,
derivative_X, derivative_bit0, derivative_one, bit0_zero,
zero_mul, zero_add, mul_one]
... = 2 * (chebyshevβ R (n + 1 + 1) - X * chebyshevβ R (n + 1))
+ 2 * X * ((n + 1 + 1) * chebyshevβ R (n + 1)) - (n + 1) * chebyshevβ R n :
by rw_mod_cast [chebyshevβ_derivative_eq_chebyshevβ,
chebyshevβ_derivative_eq_chebyshevβ, chebyshevβ_eq_chebyshevβ_sub_X_mul_chebyshevβ]
... = (n + 1) * (2 * X * chebyshevβ R (n + 1) - chebyshevβ R n) + 2 * chebyshevβ R (n + 2) :
by ring
... = (n + 1) * chebyshevβ R (n + 2) + 2 * chebyshevβ R (n + 2) :
by rw chebyshevβ_add_two
... = (n + 2 + 1) * chebyshevβ R (n + 2) :
by ring
... = (β(n + 2) + 1) * chebyshevβ R (n + 2) :
by norm_cast
lemma one_sub_X_pow_two_mul_derivative_chebyshevβ_eq_poly_in_chebyshevβ (n : β) :
(1 - X ^ 2) * (derivative (chebyshevβ R (n+1))) =
(n + 1) * (chebyshevβ R n - X * chebyshevβ R (n+1)) :=
calc
(1 - X ^ 2) * (derivative (chebyshevβ R (n+1)))
= (1 - X ^ 2 ) * ((n + 1) * chebyshevβ R n) :
by rw chebyshevβ_derivative_eq_chebyshevβ
... = (n + 1) * ((1 - X ^ 2) * chebyshevβ R n) :
by ring
... = (n + 1) * (X * chebyshevβ R (n + 1) - (2 * X * chebyshevβ R (n + 1) - chebyshevβ R n)) :
by rw [one_sub_X_pow_two_mul_chebyshevβ_eq_pol_in_chebyshevβ, chebyshevβ_add_two]
... = (n + 1) * (chebyshevβ R n - X * chebyshevβ R (n+1)) :
by ring
lemma add_one_mul_chebyshevβ_eq_poly_in_chebyshevβ (n : β) :
((n : polynomial R) + 1) * chebyshevβ R (n+1) =
X * chebyshevβ R n - (1 - X ^ 2) * derivative ( chebyshevβ R n) :=
begin
have h : derivative (chebyshevβ R (n + 2)) = (chebyshevβ R (n + 1) - X * chebyshevβ R n)
+ X * derivative (chebyshevβ R (n + 1)) + 2 * X * chebyshevβ R n
- (1 - X ^ 2) * derivative (chebyshevβ R n),
{ conv_lhs { rw chebyshevβ_eq_X_mul_chebyshevβ_sub_pol_chebyshevβ },
simp only [derivative_sub, derivative_mul, derivative_X, derivative_one, derivative_X_pow,
one_mul, chebyshevβ_derivative_eq_chebyshevβ],
rw [chebyshevβ_eq_chebyshevβ_sub_X_mul_chebyshevβ, nat.cast_bit0, nat.cast_one],
ring },
calc ((n : polynomial R) + 1) * chebyshevβ R (n + 1)
= ((n : polynomial R) + 1 + 1) * (X * chebyshevβ R n + chebyshevβ R (n + 1))
- X * ((n + 1) * chebyshevβ R n) - (X * chebyshevβ R n + chebyshevβ R (n + 1)) :
by ring
... = derivative (chebyshevβ R (n + 2)) - X * derivative (chebyshevβ R (n + 1))
- chebyshevβ R (n + 1) :
by rw [βchebyshevβ_eq_X_mul_chebyshevβ_add_chebyshevβ,
βchebyshevβ_derivative_eq_chebyshevβ, βnat.cast_one, βnat.cast_add,
nat.cast_one, βchebyshevβ_derivative_eq_chebyshevβ (n + 1)]
... = (chebyshevβ R (n + 1) - X * chebyshevβ R n) + X * derivative (chebyshevβ R (n + 1))
+ 2 * X * chebyshevβ R n - (1 - X ^ 2) * derivative (chebyshevβ R n)
- X * derivative (chebyshevβ R (n + 1)) - chebyshevβ R (n + 1) :
by rw h
... = X * chebyshevβ R n - (1 - X ^ 2) * derivative (chebyshevβ R n) :
by ring,
end
end polynomial
|
4b69ea3aff3fbb3ba1352a33d47be825a8767c14 | 01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab | /categories/adjunctions/default.lean | b7803a8d37ce248bd8df2115fa9d9fdec4a62e97 | [] | no_license | PatrickMassot/lean-category-theory | 0f56a83464396a253c28a42dece16c93baf8ad74 | ef239978e91f2e1c3b8e88b6e9c64c155dc56c99 | refs/heads/master | 1,629,739,187,316 | 1,512,422,659,000 | 1,512,422,659,000 | 113,098,786 | 0 | 0 | null | 1,512,424,022,000 | 1,512,424,022,000 | null | UTF-8 | Lean | false | false | 3,479 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Stephen Morgan, Scott Morrison
import ..natural_transformation
import ..opposites
import ..types
open categories
open categories.functor
open categories.natural_transformation
open categories.types
namespace categories.adjunctions
structure Adjunction { C D : Category } ( L : Functor C D ) ( R : Functor D C ) :=
( unit : NaturalTransformation (IdentityFunctor C) (FunctorComposition L R) )
( counit : NaturalTransformation (FunctorComposition R L) (IdentityFunctor D) )
( triangle_1 : β X : D.Obj, C.compose (unit.components (R.onObjects X)) (R.onMorphisms (counit.components X)) = C.identity (R.onObjects X) )
( triangle_2 : β X : C.Obj, D.compose (L.onMorphisms (unit.components X)) (counit.components (L.onObjects X)) = D.identity (L.onObjects X) )
attribute [simp,ematch] Adjunction.triangle_1 Adjunction.triangle_2
@[applicable] lemma Adjunctions_pointwise_equal
{ C D : Category } ( L : Functor C D ) ( R : Functor D C )
( A B : Adjunction L R )
( w1 : A.unit = B.unit ) ( w2 : A.counit = B.counit ) : A = B :=
begin
induction A,
induction B,
blast
end
-- PROJECT: from an adjunction construct the triangles as equations between natural transformations.
-- definition Triangle_1
-- { C D : Category }
-- { L : Functor C D }
-- { R : Functor D C }
-- ( unit : NaturalTransformation (IdentityFunctor C) (FunctorComposition L R) )
-- ( counit : NaturalTransformation (FunctorComposition R L) (IdentityFunctor D) ) :=
-- @vertical_composition_of_NaturalTransformations D C R (FunctorComposition (FunctorComposition R L) R) R β¦ whisker_on_left R unit β§ β¦ whisker_on_right counit R β§
-- = IdentityNaturalTransformation R
-- definition Triangle_2
-- { C D : Category }
-- { L : Functor C D }
-- { R : Functor D C }
-- ( unit : NaturalTransformation (IdentityFunctor C) (FunctorComposition L R) )
-- ( counit : NaturalTransformation (FunctorComposition R L) (IdentityFunctor D) ) :=
-- @vertical_composition_of_NaturalTransformations C D L (FunctorComposition (FunctorComposition L R) L) L β¦ whisker_on_right unit L β§ β¦ whisker_on_left L counit β§
-- = IdentityNaturalTransformation L
@[simp,ematch] lemma Adjunction.unit_naturality
{ C D : Category }
{ L : Functor C D } { R : Functor D C }
( A : Adjunction L R )
{ X Y : C.Obj } ( f : C.Hom X Y ) : C.compose (A.unit.components X) (R.onMorphisms (L.onMorphisms f)) = C.compose f (A.unit.components Y) :=
begin
refine ( cast _ (A.unit.naturality f) ),
blast
end
@[simp,ematch] lemma Adjunction.counit_naturality
{ C D : Category }
{ L : Functor C D } { R : Functor D C }
( A : Adjunction L R )
{ X Y : D.Obj } ( f : D.Hom X Y ) : D.compose (L.onMorphisms (R.onMorphisms f)) (A.counit.components Y) = D.compose (A.counit.components X) f :=
begin
refine ( cast _ (A.counit.naturality f) ),
blast
end
-- PROJECT examples
-- PROJECT existence in terms of initial objects in comma categories
-- PROJECT adjoints for functors between functor categories
-- PROJECT adjoints are unique
-- PROJECT equivalences can be lifted to adjoint equivalences
-- PROJECT universal properties of adjunctions
-- PROJECT show these are a special case of a duality in a 2-category.
-- PROJECT adjoints of monoidal functors are (op)lax
end categories.adjunctions |
aab7da89b0294d8de88b55f8199a71ffd2f522f9 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/euclidean_domain/instances.lean | 3d1841412230d0ca80486aabad126a6705fe9ada | [
"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 | 2,001 | lean | /-
Copyright (c) 2018 Louis Carlin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Louis Carlin, Mario Carneiro
-/
import algebra.euclidean_domain.defs
import algebra.field.defs
import algebra.group_with_zero.units.lemmas
import data.nat.order.basic
import data.int.order.basic
/-!
# Instances for Euclidean domains
* `int.euclidean_domain`: shows that `β€` is a Euclidean domain.
* `field.to_euclidean_domain`: shows that any field is a Euclidean domain.
-/
instance int.euclidean_domain : euclidean_domain β€ :=
{ add := (+),
mul := (*),
one := 1,
zero := 0,
neg := has_neg.neg,
quotient := (/),
quotient_zero := int.div_zero,
remainder := (%),
quotient_mul_add_remainder_eq := Ξ» a b, int.div_add_mod _ _,
r := Ξ» a b, a.nat_abs < b.nat_abs,
r_well_founded := measure_wf (Ξ» a, int.nat_abs a),
remainder_lt := Ξ» a b b0, int.coe_nat_lt.1 $
by { rw [int.nat_abs_of_nonneg (int.mod_nonneg _ b0), β int.abs_eq_nat_abs],
exact int.mod_lt _ b0 },
mul_left_not_lt := Ξ» a b b0, not_lt_of_ge $
by {rw [β mul_one a.nat_abs, int.nat_abs_mul],
exact mul_le_mul_of_nonneg_left (int.nat_abs_pos_of_ne_zero b0) (nat.zero_le _) },
.. int.comm_ring,
.. int.nontrivial }
@[priority 100] -- see Note [lower instance priority]
instance field.to_euclidean_domain {K : Type*} [field K] : euclidean_domain K :=
{ add := (+),
mul := (*),
one := 1,
zero := 0,
neg := has_neg.neg,
quotient := (/),
remainder := Ξ» a b, a - a * b / b,
quotient_zero := div_zero,
quotient_mul_add_remainder_eq := Ξ» a b,
by { classical, by_cases b = 0; simp [h, mul_div_cancel'] },
r := Ξ» a b, a = 0 β§ b β 0,
r_well_founded := well_founded.intro $ Ξ» a, acc.intro _ $ Ξ» b β¨hb, hnaβ©,
acc.intro _ $ Ξ» c β¨hc, hnbβ©, false.elim $ hnb hb,
remainder_lt := Ξ» a b hnb, by simp [hnb],
mul_left_not_lt := Ξ» a b hnb β¨hab, hnaβ©, or.cases_on (mul_eq_zero.1 hab) hna hnb,
.. βΉfield KβΊ }
|
edb22dea9f53f56ec455cd30bd541b80062532c0 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /src/Lean/Elab/App.lean | 6b2bf774c9399c9d42b93664fb5282cc87b48cc4 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 66,607 | 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.FindMVar
import Lean.Parser.Term
import Lean.Meta.KAbstract
import Lean.Meta.Tactic.ElimInfo
import Lean.Elab.Term
import Lean.Elab.Binders
import Lean.Elab.SyntheticMVars
import Lean.Elab.Arg
import Lean.Elab.RecAppSyntax
namespace Lean.Elab.Term
open Meta
builtin_initialize elabWithoutExpectedTypeAttr : TagAttribute β
registerTagAttribute `elabWithoutExpectedType "mark that applications of the given declaration should be elaborated without the expected type"
def hasElabWithoutExpectedType (env : Environment) (declName : Name) : Bool :=
elabWithoutExpectedTypeAttr.hasTag env declName
instance : ToString Arg where
toString
| .stx val => toString val
| .expr val => toString val
instance : ToString NamedArg where
toString s := "(" ++ toString s.name ++ " := " ++ toString s.val ++ ")"
def throwInvalidNamedArg (namedArg : NamedArg) (fn? : Option Name) : TermElabM Ξ± :=
withRef namedArg.ref <| match fn? with
| some fn => throwError "invalid argument name '{namedArg.name}' for function '{fn}'"
| none => throwError "invalid argument name '{namedArg.name}' for function"
private def ensureArgType (f : Expr) (arg : Expr) (expectedType : Expr) : TermElabM Expr := do
try
ensureHasTypeAux expectedType (β inferType arg) arg f
catch
| ex@(.error ..) =>
if (β read).errToSorry then
exceptionToSorry ex expectedType
else
throw ex
| ex => throw ex
private def mkProjAndCheck (structName : Name) (idx : Nat) (e : Expr) : MetaM Expr := do
let r := mkProj structName idx e
let eType β inferType e
if (β isProp eType) then
let rType β inferType r
if !(β isProp rType) then
throwError "invalid projection, the expression{indentExpr e}\nis a proposition and has type{indentExpr eType}\nbut the projected value is not, it has type{indentExpr rType}"
return r
/--
Relevant definitions:
```
class CoeFun (Ξ± : Sort u) (Ξ³ : Ξ± β outParam (Sort v))
```
-/
private def tryCoeFun? (Ξ± : Expr) (a : Expr) : TermElabM (Option Expr) := do
let v β mkFreshLevelMVar
let type β mkArrow Ξ± (mkSort v)
let Ξ³ β mkFreshExprMVar type
let u β getLevel Ξ±
let coeFunInstType := mkAppN (Lean.mkConst ``CoeFun [u, v]) #[Ξ±, Ξ³]
let mvar β mkFreshExprMVar coeFunInstType MetavarKind.synthetic
let mvarId := mvar.mvarId!
try
if (β synthesizeCoeInstMVarCore mvarId) then
expandCoe <| mkAppN (Lean.mkConst ``CoeFun.coe [u, v]) #[Ξ±, Ξ³, mvar, a]
else
return none
catch _ =>
return none
def synthesizeAppInstMVars (instMVars : Array MVarId) (app : Expr) : TermElabM Unit :=
for mvarId in instMVars do
unless (β synthesizeInstMVarCore mvarId) do
registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass
registerMVarErrorImplicitArgInfo mvarId (β getRef) app
/-- Return `some namedArg` if `namedArgs` contains an entry for `binderName`. -/
private def findBinderName? (namedArgs : List NamedArg) (binderName : Name) : Option NamedArg :=
namedArgs.find? fun namedArg => namedArg.name == binderName
/-- Erase entry for `binderName` from `namedArgs`. -/
def eraseNamedArg (namedArgs : List NamedArg) (binderName : Name) : List NamedArg :=
namedArgs.filter (Β·.name != binderName)
/-- Return true if the given type contains `OptParam` or `AutoParams` -/
private def hasOptAutoParams (type : Expr) : MetaM Bool := do
forallTelescopeReducing type fun xs _ =>
xs.anyM fun x => do
let xType β inferType x
return xType.getOptParamDefault?.isSome || xType.getAutoParamTactic?.isSome
/-! # Default application elaborator -/
namespace ElabAppArgs
structure Context where
/--
`true` if `..` was used
-/
ellipsis : Bool --
/--
`true` if `@` modifier was used
-/
explicit : Bool
/--
If the result type of an application is the `outParam` of some local instance, then special support may be needed
because type class resolution interacts poorly with coercions in this kind of situation.
This flag enables the special support.
The idea is quite simple, if the result type is the `outParam` of some local instance, we simply
execute `synthesizeSyntheticMVarsUsingDefault`. We added this feature to make sure examples as follows
are correctly elaborated.
```lean
class GetElem (Cont : Type u) (Idx : Type v) (Elem : outParam (Type w)) where
getElem (xs : Cont) (i : Idx) : Elem
export GetElem (getElem)
instance : GetElem (Array Ξ±) Nat Ξ± where
getElem xs i := xs.get β¨i, sorryβ©
opaque f : Option Bool β Bool
opaque g : Bool β Bool
def bad (xs : Array Bool) : Bool :=
let x := getElem xs 0
f x && g x
```
Without the special support, Lean fails at `g x` saying `x` has type `Option Bool` but is expected to have type `Bool`.
From the users point of view this is a bug, since `let x := getElem xs 0` clearly constraints `x` to be `Bool`, but
we only obtain this information after we apply the `OfNat` default instance for `0`.
Before converging to this solution, we have tried to create a "coercion placeholder" when `resultIsOutParamSupport = true`,
but it did not work well in practice. For example, it failed in the example above.
-/
resultIsOutParamSupport : Bool
/-- Auxiliary structure for elaborating the application `f args namedArgs`. -/
structure State where
f : Expr
fType : Expr
/-- Remaining regular arguments. -/
args : List Arg
/-- remaining named arguments to be processed. -/
namedArgs : List NamedArg
expectedType? : Option Expr
/--
When named arguments are provided and explicit arguments occurring before them are missing,
the elaborator eta-expands the declaration. For example,
```
def f (x y : Nat) := x + y
#check f (y := 5)
-- fun x => f x 5
```
`etaArgs` stores the fresh free variables for implementing the eta-expansion.
When `..` is used, eta-expansion is disabled, and missing arguments are treated as `_`.
-/
etaArgs : Array Expr := #[]
/-- Metavariables that we need the set the error context using the application being built. -/
toSetErrorCtx : Array MVarId := #[]
/-- Metavariables for the instance implicit arguments that have already been processed. -/
instMVars : Array MVarId := #[]
/--
The following field is used to implement the `propagateExpectedType` heuristic.
It is set to `true` true when `expectedType` still has to be propagated.
-/
propagateExpected : Bool
/--
If the result type may be the `outParam` of some local instance.
See comment at `Context.resultIsOutParamSupport`
-/
resultTypeOutParam? : Option MVarId := none
abbrev M := ReaderT Context (StateRefT State TermElabM)
/-- Add the given metavariable to the collection of metavariables associated with instance-implicit arguments. -/
private def addInstMVar (mvarId : MVarId) : M Unit :=
modify fun s => { s with instMVars := s.instMVars.push mvarId }
/--
Try to synthesize metavariables are `instMVars` using type class resolution.
The ones that cannot be synthesized yet are registered.
Remark: we use this method before trying to apply coercions to function. -/
def synthesizeAppInstMVars : M Unit := do
let s β get
let instMVars := s.instMVars
modify fun s => { s with instMVars := #[] }
Term.synthesizeAppInstMVars instMVars s.f
/-- fType may become a forallE after we synthesize pending metavariables. -/
private def synthesizePendingAndNormalizeFunType : M Unit := do
synthesizeAppInstMVars
synthesizeSyntheticMVars
let s β get
let fType β whnfForall s.fType
if fType.isForall then
modify fun s => { s with fType }
else
match (β tryCoeFun? fType s.f) with
| some f =>
let fType β inferType f
modify fun s => { s with f, fType }
| none =>
for namedArg in s.namedArgs do
let f := s.f.getAppFn
if f.isConst then
throwInvalidNamedArg namedArg f.constName!
else
throwInvalidNamedArg namedArg none
throwError "function expected at{indentExpr s.f}\nterm has type{indentExpr fType}"
/-- Normalize and return the function type. -/
private def normalizeFunType : M Expr := do
let s β get
let fType β whnfForall s.fType
modify fun s => { s with fType }
return fType
/-- Return the binder name at `fType`. This method assumes `fType` is a function type. -/
private def getBindingName : M Name := return (β get).fType.bindingName!
/-- Return the next argument expected type. This method assumes `fType` is a function type. -/
private def getArgExpectedType : M Expr := return (β get).fType.bindingDomain!
/-- Remove named argument with name `binderName` from `namedArgs`. -/
def eraseNamedArg (binderName : Name) : M Unit :=
modify fun s => { s with namedArgs := Term.eraseNamedArg s.namedArgs binderName }
/--
Add a new argument to the result. That is, `f := f arg`, update `fType`.
This method assumes `fType` is a function type. -/
private def addNewArg (argName : Name) (arg : Expr) : M Unit := do
modify fun s => { s with f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg }
if arg.isMVar then
let mvarId := arg.mvarId!
if let some mvarErrorInfo β getMVarErrorInfo? mvarId then
registerMVarErrorInfo { mvarErrorInfo with argName? := argName }
/--
Elaborate the given `Arg` and add it to the result. See `addNewArg`.
Recall that, `Arg` may be wrapping an already elaborated `Expr`. -/
private def elabAndAddNewArg (argName : Name) (arg : Arg) : M Unit := do
let s β get
let expectedType := (β getArgExpectedType).consumeTypeAnnotations
match arg with
| Arg.expr val =>
let arg β ensureArgType s.f val expectedType
addNewArg argName arg
| Arg.stx stx =>
let val β elabTerm stx expectedType
let arg β withRef stx <| ensureArgType s.f val expectedType
addNewArg argName arg
/-- Return true if `fType` contains `OptParam` or `AutoParams` -/
private def fTypeHasOptAutoParams : M Bool := do
hasOptAutoParams (β get).fType
/--
Auxiliary function for retrieving the resulting type of a function application.
See `propagateExpectedType`.
Remark: `(explicit : Bool) == true` when `@` modifier is used. -/
private partial def getForallBody (explicit : Bool) : Nat β List NamedArg β Expr β Option Expr
| i, namedArgs, type@(.forallE n d b bi) =>
match findBinderName? namedArgs n with
| some _ => getForallBody explicit i (Term.eraseNamedArg namedArgs n) b
| none =>
if !explicit && !bi.isExplicit then
getForallBody explicit i namedArgs b
else if i > 0 then
getForallBody explicit (i-1) namedArgs b
else if d.isAutoParam || d.isOptParam then
getForallBody explicit i namedArgs b
else
some type
| 0, [], type => some type
| _, _, _ => none
private def shouldPropagateExpectedTypeFor (nextArg : Arg) : Bool :=
match nextArg with
| .expr _ => false -- it has already been elaborated
| .stx stx =>
-- TODO: make this configurable?
stx.getKind != ``Lean.Parser.Term.hole &&
stx.getKind != ``Lean.Parser.Term.syntheticHole &&
stx.getKind != ``Lean.Parser.Term.byTactic
/--
Auxiliary method for propagating the expected type. We call it as soon as we find the first explict
argument. The goal is to propagate the expected type in applications of functions such as
```lean
Add.add {Ξ± : Type u} : Ξ± β Ξ± β Ξ±
List.cons {Ξ± : Type u} : Ξ± β List Ξ± β List Ξ±
```
This is particularly useful when there applicable coercions. For example,
assume we have a coercion from `Nat` to `Int`, and we have
`(x : Nat)` and the expected type is `List Int`. Then, if we don't use this function,
the elaborator will fail to elaborate
```
List.cons x []
```
First, the elaborator creates a new metavariable `?Ξ±` for the implicit argument `{Ξ± : Type u}`.
Then, when it processes `x`, it assigns `?Ξ± := Nat`, and then obtain the
resultant type `List Nat` which is **not** definitionally equal to `List Int`.
We solve the problem by executing this method before we elaborate the first explicit argument (`x` in this example).
This method infers that the resultant type is `List ?Ξ±` and unifies it with `List Int`.
Then, when we elaborate `x`, the elaborate realizes the coercion from `Nat` to `Int` must be used, and the
term
```
@List.cons Int (coe x) (@List.nil Int)
```
is produced.
The method will do nothing if
1- The resultant type depends on the remaining arguments (i.e., `!eTypeBody.hasLooseBVars`).
2- The resultant type contains optional/auto params.
We have considered adding the following extra conditions
a) The resultant type does not contain any type metavariable.
b) The resultant type contains a nontype metavariable.
These two conditions would restrict the method to simple functions that are "morally" in
the Hindley&Milner fragment.
If users need to disable expected type propagation, we can add an attribute `[elabWithoutExpectedType]`.
-/
private def propagateExpectedType (arg : Arg) : M Unit := do
if shouldPropagateExpectedTypeFor arg then
let s β get
-- TODO: handle s.etaArgs.size > 0
unless !s.etaArgs.isEmpty || !s.propagateExpected do
match s.expectedType? with
| none => pure ()
| some expectedType =>
/- We don't propagate `Prop` because we often use `Prop` as a more general "Bool" (e.g., `if-then-else`).
If we propagate `expectedType == Prop` in the following examples, the elaborator would fail
```
def f1 (s : Nat Γ Bool) : Bool := if s.2 then false else true
def f2 (s : List Bool) : Bool := if s.head! then false else true
def f3 (s : List Bool) : Bool := if List.head! (s.map not) then false else true
```
They would all fail for the same reason. So, let's focus on the first one.
We would elaborate `s.2` with `expectedType == Prop`.
Before we elaborate `s`, this method would be invoked, and `s.fType` is `?Ξ± Γ ?Ξ² β ?Ξ²` and after
propagation we would have `?Ξ± Γ Prop β Prop`. Then, when we would try to elaborate `s`, and
get a type error because `?Ξ± Γ Prop` cannot be unified with `Nat Γ Bool`
Most users would have a hard time trying to understand why these examples failed.
Here is a possible alternative workarounds. We give up the idea of using `Prop` at `if-then-else`.
Drawback: users use `if-then-else` with conditions that are not Decidable.
So, users would have to embrace `propDecidable` and `choice`.
This may not be that bad since the developers and users don't seem to care about constructivism.
We currently use a different workaround, we just don't propagate the expected type when it is `Prop`. -/
if expectedType.isProp then
modify fun s => { s with propagateExpected := false }
else
let numRemainingArgs := s.args.length
trace[Elab.app.propagateExpectedType] "etaArgs.size: {s.etaArgs.size}, numRemainingArgs: {numRemainingArgs}, fType: {s.fType}"
match getForallBody (β read).explicit numRemainingArgs s.namedArgs s.fType with
| none => pure ()
| some fTypeBody =>
unless fTypeBody.hasLooseBVars do
unless (β hasOptAutoParams fTypeBody) do
trace[Elab.app.propagateExpectedType] "{expectedType} =?= {fTypeBody}"
if (β isDefEq expectedType fTypeBody) then
/- Note that we only set `propagateExpected := false` when propagation has succeeded. -/
modify fun s => { s with propagateExpected := false }
/-- This method executes after all application arguments have been processed. -/
private def finalize : M Expr := do
let s β get
let mut e := s.f
-- all user explicit arguments have been consumed
trace[Elab.app.finalize] e
let ref β getRef
-- Register the error context of implicits
for mvarId in s.toSetErrorCtx do
registerMVarErrorImplicitArgInfo mvarId ref e
if !s.etaArgs.isEmpty then
e β mkLambdaFVars s.etaArgs e
/-
Remark: we should not use `s.fType` as `eType` even when
`s.etaArgs.isEmpty`. Reason: it may have been unfolded.
-/
let eType β inferType e
trace[Elab.app.finalize] "after etaArgs, {e} : {eType}"
/- Recall that `resultTypeOutParam? = some mvarId` if the function result type is the output parameter
of a local instance. The value of this parameter may be inferable using other arguments. For example,
suppose we have
```lean
def add_one {X} [Trait X] [One (Trait.R X)] [HAdd X (Trait.R X) X] (x : X) : X := x + (One.one : (Trait.R X))
```
from test `948.lean`. There are multiple ways to infer `X`, and we don't want to mark it as `syntheticOpaque`.
-/
if let some outParamMVarId := s.resultTypeOutParam? then
synthesizeAppInstMVars
/- If `eType != mkMVar outParamMVarId`, then the
function is partially applied, and we do not apply default instances. -/
if !(β outParamMVarId.isAssigned) && eType.isMVar && eType.mvarId! == outParamMVarId then
synthesizeSyntheticMVarsUsingDefault
return e
else
return e
if let some expectedType := s.expectedType? then
-- Try to propagate expected type. Ignore if types are not definitionally equal, caller must handle it.
trace[Elab.app.finalize] "expected type: {expectedType}"
discard <| isDefEq expectedType eType
synthesizeAppInstMVars
return e
/-- Return `true` if there is a named argument that depends on the next argument. -/
private def anyNamedArgDependsOnCurrent : M Bool := do
let s β get
if s.namedArgs.isEmpty then
return false
else
forallTelescopeReducing s.fType fun xs _ => do
let curr := xs[0]!
for i in [1:xs.size] do
let xDecl β xs[i]!.fvarId!.getDecl
if s.namedArgs.any fun arg => arg.name == xDecl.userName then
if (β localDeclDependsOn xDecl curr.fvarId!) then
return true
return false
/-- Return `true` if there are regular or named arguments to be processed. -/
private def hasArgsToProcess : M Bool := do
let s β get
return !s.args.isEmpty || !s.namedArgs.isEmpty
/-- Return `true` if the next argument at `args` is of the form `_` -/
private def isNextArgHole : M Bool := do
match (β get).args with
| Arg.stx (Syntax.node _ ``Lean.Parser.Term.hole _) :: _ => pure true
| _ => pure false
/--
Return `true` if the next argument to be processed is the outparam of a local instance, and it the result type
of the function.
For example, suppose we have the class
```lean
class Get (Cont : Type u) (Idx : Type v) (Elem : outParam (Type w)) where
get (xs : Cont) (i : Idx) : Elem
```
And the current value of `fType` is
```
{Cont : Type u_1} β {Idx : Type u_2} β {Elem : Type u_3} β [self : Get Cont Idx Elem] β Cont β Idx β Elem
```
then the result returned by this method is `false` since `Cont` is not the output param of any local instance.
Now assume `fType` is
```
{Elem : Type u_3} β [self : Get Cont Idx Elem] β Cont β Idx β Elem
```
then, the method returns `true` because `Elem` is an output parameter for the local instance `[self : Get Cont Idx Elem]`.
Remark: if `resultIsOutParamSupport` is `false`, this method returns `false`.
-/
private partial def isNextOutParamOfLocalInstanceAndResult : M Bool := do
if !(β read).resultIsOutParamSupport then
return false
let type := (β get).fType.bindingBody!
unless isResultType type 0 do
return false
if (β hasLocalInstaceWithOutParams type) then
let x := mkFVar (β mkFreshFVarId)
isOutParamOfLocalInstance x (type.instantiate1 x)
else
return false
where
isResultType (type : Expr) (i : Nat) : Bool :=
match type with
| .forallE _ _ b _ => isResultType b (i + 1)
| .bvar idx => idx == i
| _ => false
/-- (quick filter) Return true if `type` constains a binder `[C ...]` where `C` is a class containing outparams. -/
hasLocalInstaceWithOutParams (type : Expr) : CoreM Bool := do
let .forallE _ d b bi := type | return false
if bi.isInstImplicit then
if let .const declName .. := d.getAppFn then
if hasOutParams (β getEnv) declName then
return true
hasLocalInstaceWithOutParams b
isOutParamOfLocalInstance (x : Expr) (type : Expr) : MetaM Bool := do
let .forallE _ d b bi := type | return false
if bi.isInstImplicit then
if let .const declName .. := d.getAppFn then
if hasOutParams (β getEnv) declName then
let cType β inferType d.getAppFn
if (β isOutParamOf x 0 d.getAppArgs cType) then
return true
isOutParamOfLocalInstance x b
isOutParamOf (x : Expr) (i : Nat) (args : Array Expr) (cType : Expr) : MetaM Bool := do
if h : i < args.size then
match (β whnf cType) with
| .forallE _ d b _ =>
let arg := args.get β¨i, hβ©
if arg == x && d.isOutParam then
return true
isOutParamOf x (i+1) args b
| _ => return false
else
return false
mutual
/--
Create a fresh local variable with the current binder name and argument type, add it to `etaArgs` and `f`,
and then execute the main loop.-/
private partial def addEtaArg (argName : Name) : M Expr := do
let n β getBindingName
let type β getArgExpectedType
withLocalDeclD n type fun x => do
modify fun s => { s with etaArgs := s.etaArgs.push x }
addNewArg argName x
main
private partial def addImplicitArg (argName : Name) : M Expr := do
let argType β getArgExpectedType
let arg β if (β isNextOutParamOfLocalInstanceAndResult) then
let arg β mkFreshExprMVar argType
/- When the result type is an output parameter, we don't want to propagate the expected type.
So, we just mark `propagateExpected := false` to disable it.
At `finalize`, we check whether `arg` is still unassigned, if it is, we apply default instances,
and try to synthesize pending mvars. -/
modify fun s => { s with resultTypeOutParam? := some arg.mvarId!, propagateExpected := false }
pure arg
else
mkFreshExprMVar argType
modify fun s => { s with toSetErrorCtx := s.toSetErrorCtx.push arg.mvarId! }
addNewArg argName arg
main
/--
Process a `fType` of the form `(x : A) β B x`.
This method assume `fType` is a function type -/
private partial def processExplictArg (argName : Name) : M Expr := do
match (β get).args with
| arg::args =>
propagateExpectedType arg
modify fun s => { s with args }
elabAndAddNewArg argName arg
main
| _ =>
let argType β getArgExpectedType
match (β read).explicit, argType.getOptParamDefault?, argType.getAutoParamTactic? with
| false, some defVal, _ => addNewArg argName defVal; main
| false, _, some (.const tacticDecl _) =>
let env β getEnv
let opts β getOptions
match evalSyntaxConstant env opts tacticDecl with
| Except.error err => throwError err
| Except.ok tacticSyntax =>
-- TODO(Leo): does this work correctly for tactic sequences?
let tacticBlock β `(by $(β¨tacticSyntaxβ©))
let argNew := Arg.stx tacticBlock
propagateExpectedType argNew
elabAndAddNewArg argName argNew
main
| false, _, some _ =>
throwError "invalid autoParam, argument must be a constant"
| _, _, _ =>
if !(β get).namedArgs.isEmpty then
if (β anyNamedArgDependsOnCurrent) then
addImplicitArg argName
else if (β read).ellipsis then
addImplicitArg argName
else
addEtaArg argName
else if !(β read).explicit then
if (β read).ellipsis then
addImplicitArg argName
else if (β fTypeHasOptAutoParams) then
addEtaArg argName
else
finalize
else
finalize
/--
Process a `fType` of the form `{x : A} β B x`.
This method assume `fType` is a function type -/
private partial def processImplicitArg (argName : Name) : M Expr := do
if (β read).explicit then
processExplictArg argName
else
addImplicitArg argName
/--
Process a `fType` of the form `{{x : A}} β B x`.
This method assume `fType` is a function type -/
private partial def processStrictImplicitArg (argName : Name) : M Expr := do
if (β read).explicit then
processExplictArg argName
else if (β hasArgsToProcess) then
addImplicitArg argName
else
finalize
/--
Process a `fType` of the form `[x : A] β B x`.
This method assume `fType` is a function type -/
private partial def processInstImplicitArg (argName : Name) : M Expr := do
if (β read).explicit then
if (β isNextArgHole) then
/- Recall that if '@' has been used, and the argument is '_', then we still use type class resolution -/
let arg β mkFreshExprMVar (β getArgExpectedType) MetavarKind.synthetic
modify fun s => { s with args := s.args.tail! }
addInstMVar arg.mvarId!
addNewArg argName arg
main
else
processExplictArg argName
else
let arg β mkFreshExprMVar (β getArgExpectedType) MetavarKind.synthetic
addInstMVar arg.mvarId!
addNewArg argName arg
main
/-- Elaborate function application arguments. -/
partial def main : M Expr := do
let fType β normalizeFunType
if fType.isForall then
let binderName := fType.bindingName!
let binfo := fType.bindingInfo!
let s β get
match findBinderName? s.namedArgs binderName with
| some namedArg =>
propagateExpectedType namedArg.val
eraseNamedArg binderName
elabAndAddNewArg binderName namedArg.val
main
| none =>
match binfo with
| .implicit => processImplicitArg binderName
| .instImplicit => processInstImplicitArg binderName
| .strictImplicit => processStrictImplicitArg binderName
| _ => processExplictArg binderName
else if (β hasArgsToProcess) then
synthesizePendingAndNormalizeFunType
main
else
finalize
end
end ElabAppArgs
builtin_initialize elabAsElim : TagAttribute β
registerTagAttribute `elabAsElim
"instructs elaborator that the arguments of the function application should be elaborated as were an eliminator"
fun declName => do
let go : MetaM Unit := do
discard <| getElimInfo declName
let info β getConstInfo declName
if (β hasOptAutoParams info.type) then
throwError "[elabAsElim] attribute cannot be used in declarations containing optional and auto parameters"
go.run' {} {}
/-! # Eliminator-like function application elaborator -/
namespace ElabElim
/-- Context of the `elabAsElim` elaboration procedure. -/
structure Context where
elimInfo : ElimInfo
expectedType : Expr
/-- State of the `elabAsElim` elaboration procedure. -/
structure State where
/-- The resultant expression being built. -/
f : Expr
/-- `f : fType -/
fType : Expr
/-- User-provided named arguments that still have to be processed. -/
namedArgs : List NamedArg
/-- User-providedarguments that still have to be processed. -/
args : List Arg
/-- Discriminants processed so far. -/
discrs : Array Expr := #[]
/-- Instance implicit arguments collected so far. -/
instMVars : Array MVarId := #[]
/-- Position of the next argument to be processed. We use it to decide whether the argument is the motive or a discriminant. -/
idx : Nat := 0
/-- Store the metavariable used to represent the motive that will be computed at `finalize`. -/
motive? : Option Expr := none
abbrev M := ReaderT Context $ StateRefT State TermElabM
/-- Infer the `motive` using the expected type by `kabstract`ing the discriminants. -/
def mkMotive (discrs : Array Expr) (expectedType : Expr): MetaM Expr := do
discrs.foldrM (init := expectedType) fun discr motive => do
let discr β instantiateMVars discr
let motiveBody β kabstract motive discr
/- We use `transform (usedLetOnly := true)` to eliminate unnecessary let-expressions. -/
let discrType β transform (usedLetOnly := true) (β instantiateMVars (β inferType discr))
return Lean.mkLambda (β mkFreshBinderName) BinderInfo.default discrType motiveBody
/-- If the eliminator is over-applied, we "revert" the extra arguments. -/
def revertArgs (args : List Arg) (f : Expr) (expectedType : Expr) : TermElabM (Expr Γ Expr) :=
args.foldrM (init := (f, expectedType)) fun arg (f, expectedType) => do
let val β
match arg with
| .expr val => pure val
| .stx stx => elabTerm stx none
let val β instantiateMVars val
let expectedTypeBody β kabstract expectedType val
/- We use `transform (usedLetOnly := true)` to eliminate unnecessary let-expressions. -/
let valType β transform (usedLetOnly := true) (β instantiateMVars (β inferType val))
return (mkApp f val, mkForall (β mkFreshBinderName) BinderInfo.default valType expectedTypeBody)
/--
Contruct the resulting application after all discriminants have bee elaborated, and we have
consumed as many given arguments as possible.
-/
def finalize : M Expr := do
unless (β get).namedArgs.isEmpty do
throwError "failed to elaborate eliminator, unused named arguments: {(β get).namedArgs.map (Β·.name)}"
let some motive := (β get).motive?
| throwError "failed to elaborate eliminator, insufficient number of arguments"
forallTelescope (β get).fType fun xs _ => do
let mut expectedType := (β read).expectedType
let mut f := (β get).f
if xs.size > 0 then
assert! (β get).args.isEmpty
try
expectedType β instantiateForall expectedType xs
catch _ =>
throwError "failed to elaborate eliminator, insufficient number of arguments, expected type:{indentExpr expectedType}"
else
-- over-application, simulate `revert`
(f, expectedType) β revertArgs (β get).args f expectedType
let result := mkAppN f xs
let mut discrs := (β get).discrs
let idx := (β get).idx
if (β get).discrs.size < (β read).elimInfo.targetsPos.size then
for i in [idx:idx + xs.size], x in xs do
if (β read).elimInfo.targetsPos.contains i then
discrs := discrs.push x
let motiveVal β mkMotive discrs expectedType
unless (β isDefEq motive motiveVal) do
throwError "failed to elaborate eliminator, invalid motive{indentExpr motiveVal}"
synthesizeAppInstMVars (β get).instMVars result
let result β mkLambdaFVars xs (β instantiateMVars result)
return result
/--
Return the next argument to be processed.
The result is `.none` if it is an implicit argument which was not provided using a named argument.
The result is `.undef` if `args` is empty and `namedArgs` does contain an entry for `binderName`.
-/
def getNextArg? (binderName : Name) (binderInfo : BinderInfo) : M (LOption Arg) := do
match findBinderName? (β get).namedArgs binderName with
| some namedArg =>
modify fun s => { s with namedArgs := eraseNamedArg s.namedArgs binderName }
return .some namedArg.val
| none =>
if binderInfo.isExplicit then
match (β get).args with
| [] => return .undef
| arg :: args =>
modify fun s => { s with args }
return .some arg
else
return .none
/-- Set the `motive` field in the state. -/
def setMotive (motive : Expr) : M Unit :=
modify fun s => { s with motive? := motive }
/-- Push the given expression into the `discrs` field in the state. -/
def addDiscr (discr : Expr) : M Unit :=
modify fun s => { s with discrs := s.discrs.push discr }
/-- Elaborate the given argument with the given expected type. -/
private def elabArg (arg : Arg) (argExpectedType : Expr) : M Expr := do
match arg with
| Arg.expr val => ensureArgType (β get).f val argExpectedType
| Arg.stx stx =>
let val β elabTerm stx argExpectedType
withRef stx <| ensureArgType (β get).f val argExpectedType
/-- Save information for producing error messages. -/
def saveArgInfo (arg : Expr) (binderName : Name) : M Unit := do
if arg.isMVar then
let mvarId := arg.mvarId!
if let some mvarErrorInfo β getMVarErrorInfo? mvarId then
registerMVarErrorInfo { mvarErrorInfo with argName? := binderName }
/-- Create an implicit argument using the given `BinderInfo`. -/
def mkImplicitArg (argExpectedType : Expr) (bi : BinderInfo) : M Expr := do
let arg β mkFreshExprMVar argExpectedType (if bi.isInstImplicit then .synthetic else .natural)
if bi.isInstImplicit then
modify fun s => { s with instMVars := s.instMVars.push arg.mvarId! }
return arg
/-- Main loop of the `elimAsElab` procedure. -/
partial def main : M Expr := do
let .forallE binderName binderType body binderInfo β whnfForall (β get).fType |
finalize
let addArgAndContinue (arg : Expr) : M Expr := do
modify fun s => { s with idx := s.idx + 1, f := mkApp s.f arg, fType := body.instantiate1 arg }
saveArgInfo arg binderName
main
let idx := (β get).idx
if (β read).elimInfo.motivePos == idx then
let motive β mkImplicitArg binderType binderInfo
setMotive motive
addArgAndContinue motive
else if (β read).elimInfo.targetsPos.contains idx then
match (β getNextArg? binderName binderInfo) with
| .some arg => let discr β elabArg arg binderType; addDiscr discr; addArgAndContinue discr
| .undef => finalize
| .none => let discr β mkImplicitArg binderType binderInfo; addDiscr discr; addArgAndContinue discr
else match (β getNextArg? binderName binderInfo) with
| .some (.stx stx) => addArgAndContinue (β postponeElabTerm stx binderType)
| .some (.expr val) => addArgAndContinue (β ensureArgType (β get).f val binderType)
| .undef => finalize
| .none => addArgAndContinue (β mkImplicitArg binderType binderInfo)
end ElabElim
/-- Return `true` if `declName` is a candidate for `ElabElim.main` elaboration. -/
private def shouldElabAsElim (declName : Name) : CoreM Bool := do
if (β isRec declName) then return true
let env β getEnv
if isCasesOnRecursor env declName then return true
if isBRecOnRecursor env declName then return true
if isRecOnRecursor env declName then return true
return elabAsElim.hasTag env declName
private def propagateExpectedTypeFor (f : Expr) : TermElabM Bool :=
match f.getAppFn.constName? with
| some declName => return !hasElabWithoutExpectedType (β getEnv) declName
| _ => return true
/-! # Function application elaboration -/
/--
Elaborate a `f`-application using `namedArgs` and `args` as the arguments.
- `expectedType?` the expected type if available. It is used to propagate typing information only. This method does **not** ensure the result has this type.
- `explicit = true` when notation `@` is used, and implicit arguments are assumed to be provided at `namedArgs` and `args`.
- `ellipsis = true` when notation `..` is used. That is, we add `_` for missing arguments.
- `resultIsOutParamSupport` is used to control whether special support is used when processing applications of functions that return
output parameter of some local instance. Example:
```
GetElem.getElem : {Cont : Type u_1} β {Idx : Type u_2} β {elem : Type u_3} β {dom : cont β idx β Prop} β [self : GetElem cont idx elem dom] β (xs : cont) β (i : idx) β dom xs i β elem
```
The result type `elem` is the output parameter of the local instance `self`.
When this parameter is set to `true`, we execute `synthesizeSyntheticMVarsUsingDefault`. For additional details, see comment at
`ElabAppArgs.resultIsOutParam`.
-/
def elabAppArgs (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg)
(expectedType? : Option Expr) (explicit ellipsis : Bool) (resultIsOutParamSupport := true) : TermElabM Expr := do
-- Coercions must be available to use this flag.
-- If `@` is used (i.e., `explicit = true`), we disable `resultIsOutParamSupport`.
let resultIsOutParamSupport := ((β getEnv).contains ``Lean.Internal.coeM) && resultIsOutParamSupport && !explicit
let fType β inferType f
let fType β instantiateMVars fType
unless namedArgs.isEmpty && args.isEmpty do
tryPostponeIfMVar fType
trace[Elab.app.args] "explicit: {explicit}, ellipsis: {ellipsis}, {f} : {fType}"
trace[Elab.app.args] "namedArgs: {namedArgs}"
trace[Elab.app.args] "args: {args}"
if let some elimInfo β elabAsElim? then
tryPostponeIfNoneOrMVar expectedType?
let some expectedType := expectedType? | throwError "failed to elaborate eliminator, expected type is not available"
let expectedType β instantiateMVars expectedType
if expectedType.getAppFn.isMVar then throwError "failed to elaborate eliminator, expected type is not available"
ElabElim.main.run { elimInfo, expectedType } |>.run' {
f, fType
args := args.toList
namedArgs := namedArgs.toList
}
else
ElabAppArgs.main.run { explicit, ellipsis, resultIsOutParamSupport } |>.run' {
args := args.toList
expectedType?, f, fType
namedArgs := namedArgs.toList
propagateExpected := (β propagateExpectedTypeFor f)
}
where
/-- Return `some info` if we should elaborate as an eliminator. -/
elabAsElim? : TermElabM (Option ElimInfo) := do
if explicit || ellipsis then return none
let .const declName _ := f | return none
unless (β shouldElabAsElim declName) do return none
let elimInfo β getElimInfo declName
forallTelescopeReducing (β inferType f) fun xs _ => do
if h : elimInfo.motivePos < xs.size then
let x := xs[elimInfo.motivePos]
let localDecl β x.fvarId!.getDecl
if findBinderName? namedArgs.toList localDecl.userName matches some _ then
-- motive has been explicitly provided, so we should use standard app elaborator
return none
return some elimInfo
else
return none
/-- Auxiliary inductive datatype that represents the resolution of an `LVal`. -/
inductive LValResolution where
| projFn (baseStructName : Name) (structName : Name) (fieldName : Name)
| projIdx (structName : Name) (idx : Nat)
| const (baseStructName : Name) (structName : Name) (constName : Name)
| localRec (baseName : Name) (fullName : Name) (fvar : Expr)
private def throwLValError (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM Ξ± :=
throwError "{msg}{indentExpr e}\nhas type{indentExpr eType}"
/--
`findMethod? env S fName`.
- If `env` contains `S ++ fName`, return `(S, S++fName)`
- Otherwise if `env` contains private name `prv` for `S ++ fName`, return `(S, prv)`, o
- Otherwise for each parent structure `S'` of `S`, we try `findMethod? env S' fname`
-/
private partial def findMethod? (env : Environment) (structName fieldName : Name) : Option (Name Γ Name) :=
let fullName := structName ++ fieldName
match env.find? fullName with
| some _ => some (structName, fullName)
| none =>
let fullNamePrv := mkPrivateName env fullName
match env.find? fullNamePrv with
| some _ => some (structName, fullNamePrv)
| none =>
if isStructure env structName then
(getParentStructures env structName).findSome? fun parentStructName => findMethod? env parentStructName fieldName
else
none
/--
Return `some (structName', fullName)` if `structName ++ fieldName` is an alias for `fullName`, and
`fullName` is of the form `structName' ++ fieldName`.
TODO: if there is more than one applicable alias, it returns `none`. We should consider throwing an error or
warning.
-/
private def findMethodAlias? (env : Environment) (structName fieldName : Name) : Option (Name Γ Name) :=
let fullName := structName ++ fieldName
-- We never skip `protected` aliases when resolving dot-notation.
let aliasesCandidates := getAliases env fullName (skipProtected := false) |>.filterMap fun alias =>
match alias.eraseSuffix? fieldName with
| none => none
| some structName' => some (structName', alias)
match aliasesCandidates with
| [r] => some r
| _ => none
private def throwInvalidFieldNotation (e eType : Expr) : TermElabM Ξ± :=
throwLValError e eType "invalid field notation, type is not of the form (C ...) where C is a constant"
private def resolveLValAux (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution := do
if eType.isForall then
match lval with
| LVal.fieldName _ fieldName _ _ =>
let fullName := `Function ++ fieldName
if (β getEnv).contains fullName then
return LValResolution.const `Function `Function fullName
| _ => pure ()
match eType.getAppFn.constName?, lval with
| some structName, LVal.fieldIdx _ idx =>
if idx == 0 then
throwError "invalid projection, index must be greater than 0"
let env β getEnv
unless isStructureLike env structName do
throwLValError e eType "invalid projection, structure expected"
let numFields := getStructureLikeNumFields env structName
if idx - 1 < numFields then
if isStructure env structName then
let fieldNames := getStructureFields env structName
return LValResolution.projFn structName structName fieldNames[idx - 1]!
else
/- `structName` was declared using `inductive` command.
So, we don't projection functions for it. Thus, we use `Expr.proj` -/
return LValResolution.projIdx structName (idx - 1)
else
throwLValError e eType m!"invalid projection, structure has only {numFields} field(s)"
| some structName, LVal.fieldName _ fieldName _ _ =>
let env β getEnv
let searchEnv : Unit β TermElabM LValResolution := fun _ => do
if let some (baseStructName, fullName) := findMethod? env structName fieldName then
return LValResolution.const baseStructName structName fullName
else if let some (structName', fullName) := findMethodAlias? env structName fieldName then
return LValResolution.const structName' structName' fullName
else
throwLValError e eType
m!"invalid field '{fieldName}', the environment does not contain '{Name.mkStr structName fieldName}'"
-- search local context first, then environment
let searchCtx : Unit β TermElabM LValResolution := fun _ => do
let fullName := Name.mkStr structName fieldName
for localDecl in (β getLCtx) do
if localDecl.binderInfo == BinderInfo.auxDecl then
if let some localDeclFullName := (β read).auxDeclToFullName.find? localDecl.fvarId then
if fullName == (privateToUserName? localDeclFullName).getD localDeclFullName then
/- LVal notation is being used to make a "local" recursive call. -/
return LValResolution.localRec structName fullName localDecl.toExpr
searchEnv ()
if isStructure env structName then
match findField? env structName (Name.mkSimple fieldName) with
| some baseStructName => return LValResolution.projFn baseStructName structName (Name.mkSimple fieldName)
| none => searchCtx ()
else
searchCtx ()
| none, LVal.fieldName _ _ (some suffix) _ =>
if e.isConst then
throwUnknownConstant (e.constName! ++ suffix)
else
throwInvalidFieldNotation e eType
| _, _ => throwInvalidFieldNotation e eType
/-- whnfCore + implicit consumption.
Example: given `e` with `eType := {Ξ± : Type} β (fun Ξ² => List Ξ²) Ξ± `, it produces `(e ?m, List ?m)` where `?m` is fresh metavariable. -/
private partial def consumeImplicits (stx : Syntax) (e eType : Expr) (hasArgs : Bool) : TermElabM (Expr Γ Expr) := do
let eType β whnfCore eType
match eType with
| .forallE _ d b bi =>
if bi.isImplicit || (hasArgs && bi.isStrictImplicit) then
let mvar β mkFreshExprMVar d
registerMVarErrorHoleInfo mvar.mvarId! stx
consumeImplicits stx (mkApp e mvar) (b.instantiate1 mvar) hasArgs
else if bi.isInstImplicit then
let mvar β mkInstMVar d
let r := mkApp e mvar
registerMVarErrorImplicitArgInfo mvar.mvarId! stx r
consumeImplicits stx r (b.instantiate1 mvar) hasArgs
else match d.getOptParamDefault? with
| some defVal => consumeImplicits stx (mkApp e defVal) (b.instantiate1 defVal) hasArgs
-- TODO: we do not handle autoParams here.
| _ => return (e, eType)
| _ => return (e, eType)
private partial def resolveLValLoop (lval : LVal) (e eType : Expr) (previousExceptions : Array Exception) (hasArgs : Bool) : TermElabM (Expr Γ LValResolution) := do
let (e, eType) β consumeImplicits lval.getRef e eType hasArgs
tryPostponeIfMVar eType
/- If `eType` is still a metavariable application, we try to apply default instances to "unblock" it. -/
if (β isMVarApp eType) then
synthesizeSyntheticMVarsUsingDefault
let eType β instantiateMVars eType
try
let lvalRes β resolveLValAux e eType lval
return (e, lvalRes)
catch
| ex@(Exception.error _ _) =>
let eType? β unfoldDefinition? eType
match eType? with
| some eType => resolveLValLoop lval e eType (previousExceptions.push ex) hasArgs
| none =>
previousExceptions.forM fun ex => logException ex
throw ex
| ex@(Exception.internal _ _) => throw ex
private def resolveLVal (e : Expr) (lval : LVal) (hasArgs : Bool) : TermElabM (Expr Γ LValResolution) := do
let eType β inferType e
resolveLValLoop lval e eType #[] hasArgs
private partial def mkBaseProjections (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do
let env β getEnv
match getPathToBaseStructure? env baseStructName structName with
| none => throwError "failed to access field in parent structure"
| some path =>
let mut e := e
for projFunName in path do
let projFn β mkConst projFunName
e β elabAppArgs projFn #[{ name := `self, val := Arg.expr e }] (args := #[]) (expectedType? := none) (explicit := false) (ellipsis := false)
return e
private def typeMatchesBaseName (type : Expr) (baseName : Name) : MetaM Bool := do
if baseName == `Function then
return (β whnfR type).isForall
else if type.consumeMData.isAppOf baseName then
return true
else
return (β whnfR type).isAppOf baseName
/-- Auxiliary method for field notation. It tries to add `e` as a new argument to `args` or `namedArgs`.
This method first finds the parameter with a type of the form `(baseName ...)`.
When the parameter is found, if it an explicit one and `args` is big enough, we add `e` to `args`.
Otherwise, if there isn't another parameter with the same name, we add `e` to `namedArgs`.
Remark: `fullName` is the name of the resolved "field" access function. It is used for reporting errors -/
private def addLValArg (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) (namedArgs : Array NamedArg) (fType : Expr)
: TermElabM (Array Arg Γ Array NamedArg) :=
forallTelescopeReducing fType fun xs _ => do
let mut argIdx := 0 -- position of the next explicit argument
let mut remainingNamedArgs := namedArgs
for i in [:xs.size] do
let x := xs[i]!
let xDecl β x.fvarId!.getDecl
/- If there is named argument with name `xDecl.userName`, then we skip it. -/
match remainingNamedArgs.findIdx? (fun namedArg => namedArg.name == xDecl.userName) with
| some idx =>
remainingNamedArgs := remainingNamedArgs.eraseIdx idx
| none =>
let type := xDecl.type
if (β typeMatchesBaseName type baseName) then
/- We found a type of the form (baseName ...).
First, we check if the current argument is an explicit one,
and the current explicit position "fits" at `args` (i.e., it must be β€ arg.size) -/
if argIdx β€ args.size && xDecl.binderInfo.isExplicit then
/- We insert `e` as an explicit argument -/
return (args.insertAt! argIdx (Arg.expr e), namedArgs)
/- If we can't add `e` to `args`, we try to add it using a named argument, but this is only possible
if there isn't an argument with the same name occurring before it. -/
for j in [:i] do
let prev := xs[j]!
let prevDecl β prev.fvarId!.getDecl
if prevDecl.userName == xDecl.userName then
throwError "invalid field notation, function '{fullName}' has argument with the expected type{indentExpr type}\nbut it cannot be used"
return (args, namedArgs.push { name := xDecl.userName, val := Arg.expr e })
if xDecl.binderInfo.isExplicit then
-- advance explicit argument position
argIdx := argIdx + 1
throwError "invalid field notation, function '{fullName}' does not have argument with type ({baseName} ...) that can be used, it must be explicit or implicit with an unique name"
private def elabAppLValsAux (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool)
(f : Expr) (lvals : List LVal) : TermElabM Expr :=
let rec loop : Expr β List LVal β TermElabM Expr
| f, [] => elabAppArgs f namedArgs args expectedType? explicit ellipsis
| f, lval::lvals => do
if let LVal.fieldName (ref := fieldStx) (targetStx := targetStx) .. := lval then
addDotCompletionInfo targetStx f expectedType? fieldStx
let hasArgs := !namedArgs.isEmpty || !args.isEmpty
let (f, lvalRes) β resolveLVal f lval hasArgs
match lvalRes with
| LValResolution.projIdx structName idx =>
let f β mkProjAndCheck structName idx f
let f β addTermInfo lval.getRef f
loop f lvals
| LValResolution.projFn baseStructName structName fieldName =>
let f β mkBaseProjections baseStructName structName f
if let some info := getFieldInfo? (β getEnv) baseStructName fieldName then
if isPrivateNameFromImportedModule (β getEnv) info.projFn then
throwError "field '{fieldName}' from structure '{structName}' is private"
let projFn β mkConst info.projFn
let projFn β addTermInfo lval.getRef projFn
if lvals.isEmpty then
let namedArgs β addNamedArg namedArgs { name := `self, val := Arg.expr f }
elabAppArgs projFn namedArgs args expectedType? explicit ellipsis
else
let f β elabAppArgs projFn #[{ name := `self, val := Arg.expr f }] #[] (expectedType? := none) (explicit := false) (ellipsis := false)
loop f lvals
else
unreachable!
| LValResolution.const baseStructName structName constName =>
let f β if baseStructName != structName then mkBaseProjections baseStructName structName f else pure f
let projFn β mkConst constName
let projFn β addTermInfo lval.getRef projFn
if lvals.isEmpty then
let projFnType β inferType projFn
let (args, namedArgs) β addLValArg baseStructName constName f args namedArgs projFnType
elabAppArgs projFn namedArgs args expectedType? explicit ellipsis
else
let f β elabAppArgs projFn #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false)
loop f lvals
| LValResolution.localRec baseName fullName fvar =>
let fvar β addTermInfo lval.getRef fvar
if lvals.isEmpty then
let fvarType β inferType fvar
let (args, namedArgs) β addLValArg baseName fullName f args namedArgs fvarType
elabAppArgs fvar namedArgs args expectedType? explicit ellipsis
else
let f β elabAppArgs fvar #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false)
loop f lvals
loop f lvals
private def elabAppLVals (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg)
(expectedType? : Option Expr) (explicit ellipsis : Bool) : TermElabM Expr := do
if !lvals.isEmpty && explicit then
throwError "invalid use of field notation with `@` modifier"
elabAppLValsAux namedArgs args expectedType? explicit ellipsis f lvals
def elabExplicitUnivs (lvls : Array Syntax) : TermElabM (List Level) := do
lvls.foldrM (init := []) fun stx lvls => return (β elabLevel stx)::lvls
/-!
# Interaction between `errToSorry` and `observing`.
- The method `elabTerm` catches exceptions, log them, and returns a synthetic sorry (IF `ctx.errToSorry` == true).
- When we elaborate choice nodes (and overloaded identifiers), we track multiple results using the `observing x` combinator.
The `observing x` executes `x` and returns a `TermElabResult`.
`observing `x does not check for synthetic sorry's, just an exception. Thus, it may think `x` worked when it didn't
if a synthetic sorry was introduced. We decided that checking for synthetic sorrys at `observing` is not a good solution
because it would not be clear to decide what the "main" error message for the alternative is. When the result contains
a synthetic `sorry`, it is not clear which error message corresponds to the `sorry`. Moreover, while executing `x`, many
error messages may have been logged. Recall that we need an error per alternative at `mergeFailures`.
Thus, we decided to set `errToSorry` to `false` whenever processing choice nodes and overloaded symbols.
Important: we rely on the property that after `errToSorry` is set to
false, no elaboration function executed by `x` will reset it to
`true`.
-/
private partial def elabAppFnId (fIdent : Syntax) (fExplicitUnivs : List Level) (lvals : List LVal)
(namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array (TermElabResult Expr))
: TermElabM (Array (TermElabResult Expr)) := do
let funLVals β withRef fIdent <| resolveName' fIdent fExplicitUnivs expectedType?
let overloaded := overloaded || funLVals.length > 1
-- Set `errToSorry` to `false` if `funLVals` > 1. See comment above about the interaction between `errToSorry` and `observing`.
withReader (fun ctx => { ctx with errToSorry := funLVals.length == 1 && ctx.errToSorry }) do
funLVals.foldlM (init := acc) fun acc (f, fIdent, fields) => do
let lvals' := toLVals fields (first := true)
let s β observing do
let f β addTermInfo fIdent f expectedType?
let e β elabAppLVals f (lvals' ++ lvals) namedArgs args expectedType? explicit ellipsis
if overloaded then ensureHasType expectedType? e else return e
return acc.push s
where
toName (fields : List Syntax) : Name :=
let rec go
| [] => .anonymous
| field :: fields => .mkStr (go fields) field.getId.toString
go fields.reverse
toLVals : List Syntax β (first : Bool) β List LVal
| [], _ => []
| field::fields, true => .fieldName field field.getId.toString (toName (field::fields)) fIdent :: toLVals fields false
| field::fields, false => .fieldName field field.getId.toString none fIdent :: toLVals fields false
/-- Resolve `(.$id:ident)` using the expected type to infer namespace. -/
private partial def resolveDotName (id : Syntax) (expectedType? : Option Expr) : TermElabM Name := do
tryPostponeIfNoneOrMVar expectedType?
let some expectedType := expectedType?
| throwError "invalid dotted identifier notation, expected type must be known"
forallTelescopeReducing expectedType fun _ resultType => do
go resultType expectedType #[]
where
go (resultType : Expr) (expectedType : Expr) (previousExceptions : Array Exception) : TermElabM Name := do
let resultType β instantiateMVars resultType
let resultTypeFn := resultType.cleanupAnnotations.getAppFn
try
tryPostponeIfMVar resultTypeFn
let .const declName .. := resultTypeFn.cleanupAnnotations
| throwError "invalid dotted identifier notation, expected type is not of the form (... β C ...) where C is a constant{indentExpr expectedType}"
let idNew := declName ++ id.getId.eraseMacroScopes
unless (β getEnv).contains idNew do
throwError "invalid dotted identifier notation, unknown identifier `{idNew}` from expected type{indentExpr expectedType}"
return idNew
catch
| ex@(.error ..) =>
match (β unfoldDefinition? resultType) with
| some resultType =>
go (β whnfCore resultType) expectedType (previousExceptions.push ex)
| none =>
previousExceptions.forM fun ex => logException ex
throw ex
| ex@(.internal _ _) => throw ex
private partial def elabAppFn (f : Syntax) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg)
(expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array (TermElabResult Expr)) : TermElabM (Array (TermElabResult Expr)) := do
if f.getKind == choiceKind then
-- Set `errToSorry` to `false` when processing choice nodes. See comment above about the interaction between `errToSorry` and `observing`.
withReader (fun ctx => { ctx with errToSorry := false }) do
f.getArgs.foldlM (init := acc) fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit ellipsis true acc
else
let elabFieldName (e field : Syntax) := do
let newLVals := field.identComponents.map fun comp =>
-- We use `none` in `suffix?` since `field` can't be part of a composite name
LVal.fieldName comp (toString comp.getId) none e
elabAppFn e (newLVals ++ lvals) namedArgs args expectedType? explicit ellipsis overloaded acc
let elabFieldIdx (e idxStx : Syntax) := do
let idx := idxStx.isFieldIdx?.get!
elabAppFn e (LVal.fieldIdx idxStx idx :: lvals) namedArgs args expectedType? explicit ellipsis overloaded acc
match f with
| `($(e).$idx:fieldIdx) => elabFieldIdx e idx
| `($e |>.$idx:fieldIdx) => elabFieldIdx e idx
| `($(e).$field:ident) => elabFieldName e field
| `($e |>.$field:ident) => elabFieldName e field
| `($_:ident@$_:term) =>
throwError "unexpected occurrence of named pattern"
| `($id:ident) => do
elabAppFnId id [] lvals namedArgs args expectedType? explicit ellipsis overloaded acc
| `($id:ident.{$us,*}) => do
let us β elabExplicitUnivs us
elabAppFnId id us lvals namedArgs args expectedType? explicit ellipsis overloaded acc
| `(@$id:ident) =>
elabAppFn id lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc
| `(@$_:ident.{$_us,*}) =>
elabAppFn (f.getArg 1) lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc
| `(@$_) => throwUnsupportedSyntax -- invalid occurrence of `@`
| `(_) => throwError "placeholders '_' cannot be used where a function is expected"
| `(.$id:ident) =>
addCompletionInfo <| CompletionInfo.dotId f id.getId (β getLCtx) expectedType?
let fConst β mkConst (β resolveDotName id expectedType?)
let s β observing do
-- Use (force := true) because we want to record the result of .ident resolution even in patterns
let fConst β addTermInfo f fConst expectedType? (force := true)
let e β elabAppLVals fConst lvals namedArgs args expectedType? explicit ellipsis
if overloaded then ensureHasType expectedType? e else return e
return acc.push s
| _ => do
let catchPostpone := !overloaded
/- If we are processing a choice node, then we should use `catchPostpone == false` when elaborating terms.
Recall that `observing` does not catch `postponeExceptionId`. -/
if lvals.isEmpty && namedArgs.isEmpty && args.isEmpty then
/- Recall that elabAppFn is used for elaborating atomics terms **and** choice nodes that may contain
arbitrary terms. If they are not being used as a function, we should elaborate using the expectedType. -/
let s β observing do
if overloaded then
elabTermEnsuringType f expectedType? catchPostpone
else
elabTerm f expectedType?
return acc.push s
else
let s β observing do
let f β elabTerm f none catchPostpone
let e β elabAppLVals f lvals namedArgs args expectedType? explicit ellipsis
if overloaded then ensureHasType expectedType? e else return e
return acc.push s
/-- Return the successful candidates. Recall we have Syntax `choice` nodes and overloaded symbols when we open multiple namespaces. -/
private def getSuccesses (candidates : Array (TermElabResult Expr)) : TermElabM (Array (TermElabResult Expr)) := do
let rβ := candidates.filter fun | EStateM.Result.ok .. => true | _ => false
if rβ.size β€ 1 then return rβ
let rβ β candidates.filterM fun
| .ok e s => do
if e.isMVar then
/- Make sure `e` is not a delayed coercion.
Recall that coercion insertion may be delayed when the type and expected type contains
metavariables that block TC resolution.
When processing overloaded notation, we disallow delayed coercions at `e`. -/
try
s.restore
synthesizeSyntheticMVars -- Tries to process pending coercions (and elaboration tasks)
let e β instantiateMVars e
if e.isMVar then
/- If `e` is still a metavariable, and its `SyntheticMVarDecl` is a coercion, we discard this solution -/
if let some synDecl β getSyntheticMVarDecl? e.mvarId! then
if synDecl.kind matches SyntheticMVarKind.coe .. then
return false
catch _ =>
-- If `synthesizeSyntheticMVars` failed, we just eliminate the candidate.
return false
return true
| _ => return false
if rβ.size == 0 then return rβ else return rβ
/--
Throw an error message that describes why each possible interpretation for the overloaded notation and symbols did not work.
We use a nested error message to aggregate the exceptions produced by each failure.
-/
private def mergeFailures (failures : Array (TermElabResult Expr)) : TermElabM Ξ± := do
let exs := failures.map fun | .error ex _ => ex | _ => unreachable!
throwErrorWithNestedErrors "overloaded" exs
private def elabAppAux (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) (expectedType? : Option Expr) : TermElabM Expr := do
let candidates β elabAppFn f [] namedArgs args expectedType? (explicit := false) (ellipsis := ellipsis) (overloaded := false) #[]
if candidates.size == 1 then
applyResult candidates[0]!
else
let successes β getSuccesses candidates
if successes.size == 1 then
applyResult successes[0]!
else if successes.size > 1 then
let msgs : Array MessageData β successes.mapM fun success => do
match success with
| .ok e s => withMCtx s.meta.meta.mctx <| withEnv s.meta.core.env do addMessageContext m!"{e} : {β inferType e}"
| _ => unreachable!
throwErrorAt f "ambiguous, possible interpretations {toMessageList msgs}"
else
withRef f <| mergeFailures candidates
/--
We annotate recursive applications with their `Syntax` node to make sure we can produce error messages with
correct position information at `WF` and `Structural`.
-/
-- TODO: It is overkill to store the whole `Syntax` object, and we have to make sure we erase it later.
-- We should store only the position information in the future.
-- Recall that we will need to have a compact way of storing position information in the future anyway, if we
-- want to support debugging information
private def annotateIfRec (stx : Syntax) (e : Expr) : TermElabM Expr := do
if (β read).saveRecAppSyntax then
let resultFn := e.getAppFn
if resultFn.isFVar then
let localDecl β resultFn.fvarId!.getDecl
if localDecl.isAuxDecl then
return mkRecAppWithSyntax e stx
return e
@[builtinTermElab app] def elabApp : TermElab := fun stx expectedType? =>
universeConstraintsCheckpoint do
let (f, namedArgs, args, ellipsis) β expandApp stx
annotateIfRec stx (β elabAppAux f namedArgs args (ellipsis := ellipsis) expectedType?)
private def elabAtom : TermElab := fun stx expectedType? => do
annotateIfRec stx (β elabAppAux stx #[] #[] (ellipsis := false) expectedType?)
@[builtinTermElab ident] def elabIdent : TermElab := elabAtom
@[builtinTermElab namedPattern] def elabNamedPattern : TermElab := elabAtom
@[builtinTermElab dotIdent] def elabDotIdent : TermElab := elabAtom
@[builtinTermElab explicitUniv] def elabExplicitUniv : TermElab := elabAtom
@[builtinTermElab pipeProj] def elabPipeProj : TermElab
| `($e |>.$f $args*), expectedType? =>
universeConstraintsCheckpoint do
let (namedArgs, args, ellipsis) β expandArgs args
elabAppAux (β `($e |>.$f)) namedArgs args (ellipsis := ellipsis) expectedType?
| _, _ => throwUnsupportedSyntax
@[builtinTermElab explicit] def elabExplicit : TermElab := fun stx expectedType? =>
match stx with
| `(@$_:ident) => elabAtom stx expectedType? -- Recall that `elabApp` also has support for `@`
| `(@$_:ident.{$_us,*}) => elabAtom stx expectedType?
| `(@($t)) => elabTerm t expectedType? (implicitLambda := false) -- `@` is being used just to disable implicit lambdas
| `(@$t) => elabTerm t expectedType? (implicitLambda := false) -- `@` is being used just to disable implicit lambdas
| _ => throwUnsupportedSyntax
@[builtinTermElab choice] def elabChoice : TermElab := elabAtom
@[builtinTermElab proj] def elabProj : TermElab := elabAtom
builtin_initialize
registerTraceClass `Elab.app
end Lean.Elab.Term
|
d6113a33af29835d9c396bb6286e69d776e3265e | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /src/Init/Data/Array/Basic.lean | c6ad928274a8debef67f842a7356ce7b16f4e484 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 29,879 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.Nat.Basic
import Init.Data.Fin.Basic
import Init.Data.UInt
import Init.Data.Repr
import Init.Data.ToString
import Init.Control.Id
import Init.Util
universes u v w
/-
The Compiler has special support for arrays.
They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array
-/
structure Array (Ξ± : Type u) :=
(sz : Nat)
(data : Fin sz β Ξ±)
attribute [extern "lean_array_mk"] Array.mk
attribute [extern "lean_array_data"] Array.data
attribute [extern "lean_array_sz"] Array.sz
@[reducible, extern "lean_array_get_size"]
def Array.size {Ξ± : Type u} (a : @& Array Ξ±) : Nat :=
a.sz
namespace Array
variables {Ξ± : Type u}
/- The parameter `c` is the initial capacity -/
@[extern "lean_mk_empty_array_with_capacity"]
def mkEmpty (c : @& Nat) : Array Ξ± :=
{ sz := 0,
data := fun β¨x, hβ© => absurd h (Nat.notLtZero x) }
@[extern "lean_array_push"]
def push (a : Array Ξ±) (v : Ξ±) : Array Ξ± :=
{ sz := Nat.succ a.sz,
data := fun β¨j, hββ© =>
if hβ : j = a.sz then v
else a.data β¨j, Nat.ltOfLeOfNe (Nat.leOfLtSucc hβ) hββ© }
@[extern "lean_mk_array"]
def mkArray {Ξ± : Type u} (n : Nat) (v : Ξ±) : Array Ξ± :=
{ sz := n,
data := fun _ => v}
theorem szMkArrayEq {Ξ± : Type u} (n : Nat) (v : Ξ±) : (mkArray n v).sz = n :=
rfl
def empty : Array Ξ± :=
mkEmpty 0
instance : HasEmptyc (Array Ξ±) :=
β¨Array.emptyβ©
instance : Inhabited (Array Ξ±) :=
β¨Array.emptyβ©
def isEmpty (a : Array Ξ±) : Bool :=
a.size = 0
def singleton (v : Ξ±) : Array Ξ± :=
mkArray 1 v
@[extern "lean_array_fget"]
def get (a : @& Array Ξ±) (i : @& Fin a.size) : Ξ± :=
a.data i
/- Low-level version of `fget` which is as fast as a C array read.
`Fin` values are represented as tag pointers in the Lean runtime. Thus,
`fget` may be slightly slower than `uget`. -/
@[extern "lean_array_uget"]
def uget (a : @& Array Ξ±) (i : USize) (h : i.toNat < a.size) : Ξ± :=
a.get β¨i.toNat, hβ©
/- "Comfortable" version of `fget`. It performs a bound check at runtime. -/
@[extern "lean_array_get"]
def get! [Inhabited Ξ±] (a : @& Array Ξ±) (i : @& Nat) : Ξ± :=
if h : i < a.size then a.get β¨i, hβ© else arbitrary Ξ±
def back [Inhabited Ξ±] (a : Array Ξ±) : Ξ± :=
a.get! (a.size - 1)
def get? (a : Array Ξ±) (i : Nat) : Option Ξ± :=
if h : i < a.size then some (a.get β¨i, hβ©) else none
def getD (a : Array Ξ±) (i : Nat) (vβ : Ξ±) : Ξ± :=
if h : i < a.size then a.get β¨i, hβ© else vβ
def getOp [Inhabited Ξ±] (self : Array Ξ±) (idx : Nat) : Ξ± :=
self.get! idx
-- auxiliary declaration used in the equation compiler when pattern matching array literals.
abbrev getLit {Ξ± : Type u} {n : Nat} (a : Array Ξ±) (i : Nat) (hβ : a.size = n) (hβ : i < n) : Ξ± :=
a.get β¨i, hβ.symm βΈ hββ©
@[extern "lean_array_fset"]
def set (a : Array Ξ±) (i : @& Fin a.size) (v : Ξ±) : Array Ξ± :=
{ sz := a.sz,
data := fun j => if h : i = j then v else a.data j }
theorem szFSetEq (a : Array Ξ±) (i : Fin a.size) (v : Ξ±) : (set a i v).size = a.size :=
rfl
theorem szPushEq (a : Array Ξ±) (v : Ξ±) : (push a v).size = a.size + 1 :=
rfl
/- Low-level version of `fset` which is as fast as a C array fset.
`Fin` values are represented as tag pointers in the Lean runtime. Thus,
`fset` may be slightly slower than `uset`. -/
@[extern "lean_array_uset"]
def uset (a : Array Ξ±) (i : USize) (v : Ξ±) (h : i.toNat < a.size) : Array Ξ± :=
a.set β¨i.toNat, hβ© v
/- "Comfortable" version of `fset`. It performs a bound check at runtime. -/
@[extern "lean_array_set"]
def set! (a : Array Ξ±) (i : @& Nat) (v : Ξ±) : Array Ξ± :=
if h : i < a.size then a.set β¨i, hβ© v else panic! "index out of bounds"
@[extern "lean_array_fswap"]
def swap (a : Array Ξ±) (i j : @& Fin a.size) : Array Ξ± :=
let vβ := a.get i;
let vβ := a.get j;
let a := a.set i vβ;
a.set j vβ
@[extern "lean_array_swap"]
def swap! (a : Array Ξ±) (i j : @& Nat) : Array Ξ± :=
if hβ : i < a.size then
if hβ : j < a.size then swap a β¨i, hββ© β¨j, hββ©
else panic! "index out of bounds"
else panic! "index out of bounds"
@[inline] def swapAt {Ξ± : Type} (a : Array Ξ±) (i : Fin a.size) (v : Ξ±) : Ξ± Γ Array Ξ± :=
let e := a.get i;
let a := a.set i v;
(e, a)
-- TODO: delete as soon as we can define local instances
@[neverExtract] private def swapAtPanic! [Inhabited Ξ±] (i : Nat) : Ξ± Γ Array Ξ± :=
panic! ("index " ++ toString i ++ " out of bounds")
@[inline] def swapAt! {Ξ± : Type} (a : Array Ξ±) (i : Nat) (v : Ξ±) : Ξ± Γ Array Ξ± :=
if h : i < a.size then swapAt a β¨i, hβ© v else @swapAtPanic! _ β¨vβ© i
@[extern "lean_array_pop"]
def pop (a : Array Ξ±) : Array Ξ± :=
{ sz := Nat.pred a.size,
data := fun β¨j, hβ© => a.get β¨j, Nat.ltOfLtOfLe h (Nat.predLe _)β© }
-- TODO(Leo): justify termination using wf-rec
partial def shrink : Array Ξ± β Nat β Array Ξ±
| a, n => if n β₯ a.size then a else shrink a.pop n
section
variables {m : Type v β Type w} [Monad m]
variables {Ξ² : Type v} {Ο : Type u}
-- TODO(Leo): justify termination using wf-rec
@[specialize] partial def iterateMAux (a : Array Ξ±) (f : β (i : Fin a.size), Ξ± β Ξ² β m Ξ²) : Nat β Ξ² β m Ξ²
| i, b =>
if h : i < a.size then
let idx : Fin a.size := β¨i, hβ©;
f idx (a.get idx) b >>= iterateMAux (i+1)
else pure b
@[inline] def iterateM (a : Array Ξ±) (b : Ξ²) (f : β (i : Fin a.size), Ξ± β Ξ² β m Ξ²) : m Ξ² :=
iterateMAux a f 0 b
@[inline] def foldlM (f : Ξ² β Ξ± β m Ξ²) (init : Ξ²) (a : Array Ξ±) : m Ξ² :=
iterateM a init (fun _ b a => f a b)
@[inline] def foldlFromM (f : Ξ² β Ξ± β m Ξ²) (init : Ξ²) (beginIdx : Nat) (a : Array Ξ±) : m Ξ² :=
iterateMAux a (fun _ b a => f a b) beginIdx init
-- TODO(Leo): justify termination using wf-rec
@[specialize] partial def iterateMβAux (aβ : Array Ξ±) (aβ : Array Ο) (f : β (i : Fin aβ.size), Ξ± β Ο β Ξ² β m Ξ²) : Nat β Ξ² β m Ξ²
| i, b =>
if hβ : i < aβ.size then
let idxβ : Fin aβ.size := β¨i, hββ©;
if hβ : i < aβ.size then
let idxβ : Fin aβ.size := β¨i, hββ©;
f idxβ (aβ.get idxβ) (aβ.get idxβ) b >>= iterateMβAux (i+1)
else pure b
else pure b
@[inline] def iterateMβ (aβ : Array Ξ±) (aβ : Array Ο) (b : Ξ²) (f : β (i : Fin aβ.size), Ξ± β Ο β Ξ² β m Ξ²) : m Ξ² :=
iterateMβAux aβ aβ f 0 b
@[inline] def foldlMβ (f : Ξ² β Ξ± β Ο β m Ξ²) (b : Ξ²) (aβ : Array Ξ±) (aβ : Array Ο): m Ξ² :=
iterateMβ aβ aβ b (fun _ aβ aβ b => f b aβ aβ)
@[specialize] partial def findSomeMAux (a : Array Ξ±) (f : Ξ± β m (Option Ξ²)) : Nat β m (Option Ξ²)
| i =>
if h : i < a.size then
let idx : Fin a.size := β¨i, hβ©;
do r β f (a.get idx);
match r with
| some v => pure r
| none => findSomeMAux (i+1)
else pure none
@[inline] def findSomeM? (a : Array Ξ±) (f : Ξ± β m (Option Ξ²)) : m (Option Ξ²) :=
findSomeMAux a f 0
@[specialize] partial def findSomeRevMAux (a : Array Ξ±) (f : Ξ± β m (Option Ξ²)) : β (idx : Nat), idx β€ a.size β m (Option Ξ²)
| i, h =>
if hLt : 0 < i then
have i - 1 < i from Nat.subLt hLt (Nat.zeroLtSucc 0);
have i - 1 < a.size from Nat.ltOfLtOfLe this h;
let idx : Fin a.size := β¨i - 1, thisβ©;
do
r β f (a.get idx);
match r with
| some v => pure r
| none =>
have i - 1 β€ a.size from Nat.leOfLt this;
findSomeRevMAux (i-1) this
else pure none
@[inline] def findSomeRevM? (a : Array Ξ±) (f : Ξ± β m (Option Ξ²)) : m (Option Ξ²) :=
findSomeRevMAux a f a.size (Nat.leRefl _)
end
-- TODO(Leo): justify termination using wf-rec
@[specialize] partial def findMAux {Ξ± : Type} {m : Type β Type} [Monad m] (a : Array Ξ±) (p : Ξ± β m Bool) : Nat β m (Option Ξ±)
| i =>
if h : i < a.size then do
let v := a.get β¨i, hβ©;
condM (p v) (pure (some v)) (findMAux (i+1))
else pure none
@[inline] def findM? {Ξ± : Type} {m : Type β Type} [Monad m] (a : Array Ξ±) (p : Ξ± β m Bool) : m (Option Ξ±) :=
findMAux a p 0
@[inline] def find? {Ξ± : Type} (a : Array Ξ±) (p : Ξ± β Bool) : Option Ξ± :=
Id.run $ a.findM? p
@[specialize] partial def findRevMAux {Ξ± : Type} {m : Type β Type} [Monad m] (a : Array Ξ±) (p : Ξ± β m Bool) : β (idx : Nat), idx β€ a.size β m (Option Ξ±)
| i, h =>
if hLt : 0 < i then
have i - 1 < i from Nat.subLt hLt (Nat.zeroLtSucc 0);
have i - 1 < a.size from Nat.ltOfLtOfLe this h;
let v := a.get β¨i - 1, thisβ©;
do {
condM (p v) (pure (some v)) $
have i - 1 β€ a.size from Nat.leOfLt this;
findRevMAux (i-1) this
}
else pure none
@[inline] def findRevM? {Ξ± : Type} {m : Type β Type} [Monad m] (a : Array Ξ±) (p : Ξ± β m Bool) : m (Option Ξ±) :=
findRevMAux a p a.size (Nat.leRefl _)
@[inline] def findRev? {Ξ± : Type} (a : Array Ξ±) (p : Ξ± β Bool) : Option Ξ± :=
Id.run $ a.findRevM? p
section
variables {Ξ² : Type w} {Ο : Type u}
@[inline] def iterate (a : Array Ξ±) (b : Ξ²) (f : β (i : Fin a.size), Ξ± β Ξ² β Ξ²) : Ξ² :=
Id.run $ iterateMAux a f 0 b
@[inline] def iterateFrom (a : Array Ξ±) (b : Ξ²) (i : Nat) (f : β (i : Fin a.size), Ξ± β Ξ² β Ξ²) : Ξ² :=
Id.run $ iterateMAux a f i b
@[inline] def foldl (f : Ξ² β Ξ± β Ξ²) (init : Ξ²) (a : Array Ξ±) : Ξ² :=
iterate a init (fun _ a b => f b a)
@[inline] def foldlFrom (f : Ξ² β Ξ± β Ξ²) (init : Ξ²) (beginIdx : Nat) (a : Array Ξ±) : Ξ² :=
Id.run $ foldlFromM f init beginIdx a
@[inline] def iterateβ (aβ : Array Ξ±) (aβ : Array Ο) (b : Ξ²) (f : β (i : Fin aβ.size), Ξ± β Ο β Ξ² β Ξ²) : Ξ² :=
Id.run $ iterateMβAux aβ aβ f 0 b
@[inline] def foldlβ (f : Ξ² β Ξ± β Ο β Ξ²) (b : Ξ²) (aβ : Array Ξ±) (aβ : Array Ο) : Ξ² :=
iterateβ aβ aβ b (fun _ aβ aβ b => f b aβ aβ)
@[inline] def findSome? (a : Array Ξ±) (f : Ξ± β Option Ξ²) : Option Ξ² :=
Id.run $ findSomeMAux a f 0
@[inline] def findSome! [Inhabited Ξ²] (a : Array Ξ±) (f : Ξ± β Option Ξ²) : Ξ² :=
match findSome? a f with
| some b => b
| none => panic! "failed to find element"
@[inline] def findSomeRev? (a : Array Ξ±) (f : Ξ± β Option Ξ²) : Option Ξ² :=
Id.run $ findSomeRevMAux a f a.size (Nat.leRefl _)
@[inline] def findSomeRev! [Inhabited Ξ²] (a : Array Ξ±) (f : Ξ± β Option Ξ²) : Ξ² :=
match findSomeRev? a f with
| some b => b
| none => panic! "failed to find element"
@[specialize] partial def findIdxMAux {m : Type β Type u} [Monad m] (a : Array Ξ±) (p : Ξ± β m Bool) : Nat β m (Option Nat)
| i =>
if h : i < a.size then
condM (p (a.get β¨i, hβ©)) (pure (some i)) (findIdxMAux (i+1))
else
pure none
@[inline] def findIdxM? {m : Type β Type u} [Monad m] (a : Array Ξ±) (p : Ξ± β m Bool) : m (Option Nat) :=
findIdxMAux a p 0
@[specialize] partial def findIdxAux (a : Array Ξ±) (p : Ξ± β Bool) : Nat β Option Nat
| i =>
if h : i < a.size then
if p (a.get β¨i, hβ©) then some i else findIdxAux (i+1)
else
none
@[inline] def findIdx? (a : Array Ξ±) (p : Ξ± β Bool) : Option Nat :=
findIdxAux a p 0
@[inline] def findIdx! (a : Array Ξ±) (p : Ξ± β Bool) : Nat :=
match findIdxAux a p 0 with
| some i => i
| none => panic! "failed to find element"
def getIdx? [HasBeq Ξ±] (a : Array Ξ±) (v : Ξ±) : Option Nat :=
a.findIdx? $ fun a => a == v
end
section
variables {m : Type β Type w} [Monad m]
@[specialize] partial def anyRangeMAux (a : Array Ξ±) (endIdx : Nat) (hlt : endIdx β€ a.size) (p : Ξ± β m Bool) : Nat β m Bool
| i =>
if h : i < endIdx then
let idx : Fin a.size := β¨i, Nat.ltOfLtOfLe h hltβ©;
do b β p (a.get idx);
match b with
| true => pure true
| false => anyRangeMAux (i+1)
else pure false
@[inline] def anyM (a : Array Ξ±) (p : Ξ± β m Bool) : m Bool :=
anyRangeMAux a a.size (Nat.leRefl _) p 0
@[inline] def allM (a : Array Ξ±) (p : Ξ± β m Bool) : m Bool := do
b β anyM a (fun v => do b β p v; pure (!b)); pure (!b)
@[inline] def anyRangeM (a : Array Ξ±) (beginIdx endIdx : Nat) (p : Ξ± β m Bool) : m Bool :=
if h : endIdx β€ a.size then
anyRangeMAux a endIdx h p beginIdx
else
anyRangeMAux a a.size (Nat.leRefl _) p beginIdx
@[inline] def allRangeM (a : Array Ξ±) (beginIdx endIdx : Nat) (p : Ξ± β m Bool) : m Bool := do
b β anyRangeM a beginIdx endIdx (fun v => do b β p v; pure b); pure (!b)
end
@[inline] def any (a : Array Ξ±) (p : Ξ± β Bool) : Bool :=
Id.run $ anyM a p
@[inline] def anyRange (a : Array Ξ±) (beginIdx endIdx : Nat) (p : Ξ± β Bool) : Bool :=
Id.run $ anyRangeM a beginIdx endIdx p
@[inline] def anyFrom (a : Array Ξ±) (beginIdx : Nat) (p : Ξ± β Bool) : Bool :=
Id.run $ anyRangeM a beginIdx a.size p
@[inline] def all (a : Array Ξ±) (p : Ξ± β Bool) : Bool :=
!any a (fun v => !p v)
@[inline] def allRange (a : Array Ξ±) (beginIdx endIdx : Nat) (p : Ξ± β Bool) : Bool :=
!anyRange a beginIdx endIdx (fun v => !p v)
section
variables {m : Type v β Type w} [Monad m]
variable {Ξ² : Type v}
@[specialize] private def iterateRevMAux (a : Array Ξ±) (f : β (i : Fin a.size), Ξ± β Ξ² β m Ξ²) : β (i : Nat), i β€ a.size β Ξ² β m Ξ²
| 0, h, b => pure b
| j+1, h, b => do
let i : Fin a.size := β¨j, hβ©;
b β f i (a.get i) b;
iterateRevMAux j (Nat.leOfLt h) b
@[inline] def iterateRevM (a : Array Ξ±) (b : Ξ²) (f : β (i : Fin a.size), Ξ± β Ξ² β m Ξ²) : m Ξ² :=
iterateRevMAux a f a.size (Nat.leRefl _) b
@[inline] def foldrM (f : Ξ± β Ξ² β m Ξ²) (init : Ξ²) (a : Array Ξ±) : m Ξ² :=
iterateRevM a init (fun _ => f)
@[specialize] private def foldrRangeMAux (a : Array Ξ±) (f : Ξ± β Ξ² β m Ξ²) (beginIdx : Nat) : β (i : Nat), i β€ a.size β Ξ² β m Ξ²
| 0, h, b => pure b
| j+1, h, b => do
let i : Fin a.size := β¨j, hβ©;
b β f (a.get i) b;
if j == beginIdx then pure b else foldrRangeMAux j (Nat.leOfLt h) b
@[inline] def foldrRangeM (beginIdx endIdx : Nat) (f : Ξ± β Ξ² β m Ξ²) (ini : Ξ²) (a : Array Ξ±) : m Ξ² :=
if h : endIdx β€ a.size then
foldrRangeMAux a f beginIdx endIdx h ini
else
foldrRangeMAux a f beginIdx a.size (Nat.leRefl _) ini
@[specialize] partial def foldlStepMAux (step : Nat) (a : Array Ξ±) (f : Ξ² β Ξ± β m Ξ²) : Nat β Ξ² β m Ξ²
| i, b =>
if h : i < a.size then do
let curr := a.get β¨i, hβ©;
b β f b curr;
foldlStepMAux (i+step) b
else
pure b
@[inline] def foldlStepM (f : Ξ² β Ξ± β m Ξ²) (init : Ξ²) (step : Nat) (a : Array Ξ±) : m Ξ² :=
foldlStepMAux step a f 0 init
end
@[inline] def iterateRev {Ξ²} (a : Array Ξ±) (b : Ξ²) (f : β (i : Fin a.size), Ξ± β Ξ² β Ξ²) : Ξ² :=
Id.run $ iterateRevM a b f
@[inline] def foldr {Ξ²} (f : Ξ± β Ξ² β Ξ²) (init : Ξ²) (a : Array Ξ±) : Ξ² :=
Id.run $ foldrM f init a
@[inline] def foldrRange {Ξ²} (beginIdx endIdx : Nat) (f : Ξ± β Ξ² β Ξ²) (init : Ξ²) (a : Array Ξ±) : Ξ² :=
Id.run $ foldrRangeM beginIdx endIdx f init a
@[inline] def foldlStep {Ξ²} (f : Ξ² β Ξ± β Ξ²) (init : Ξ²) (step : Nat) (a : Array Ξ±) : Ξ² :=
Id.run $ foldlStepM f init step a
@[inline] def getEvenElems (a : Array Ξ±) : Array Ξ± :=
a.foldlStep (fun r a => Array.push r a) empty 2
def toList (a : Array Ξ±) : List Ξ± :=
a.foldr List.cons []
instance [HasRepr Ξ±] : HasRepr (Array Ξ±) :=
β¨fun a => "#" ++ repr a.toListβ©
instance [HasToString Ξ±] : HasToString (Array Ξ±) :=
β¨fun a => "#" ++ toString a.toListβ©
section
variables {m : Type v β Type w} [Monad m]
variable {Ξ² : Type v}
@[specialize] unsafe partial def umapMAux (f : Nat β Ξ± β m Ξ²) : Nat β Array NonScalar β m (Array PNonScalar.{v})
| i, a =>
if h : i < a.size then
let idx : Fin a.size := β¨i, hβ©;
let v : NonScalar := a.get idx;
let a := a.set idx (arbitrary _);
do newV β f i (unsafeCast v); umapMAux (i+1) (a.set idx (unsafeCast newV))
else
pure (unsafeCast a)
@[inline] unsafe partial def umapM (f : Ξ± β m Ξ²) (as : Array Ξ±) : m (Array Ξ²) :=
@unsafeCast (m (Array PNonScalar.{v})) (m (Array Ξ²)) $ umapMAux (fun i a => f a) 0 (unsafeCast as)
@[inline] unsafe partial def umapIdxM (f : Nat β Ξ± β m Ξ²) (as : Array Ξ±) : m (Array Ξ²) :=
@unsafeCast (m (Array PNonScalar.{v})) (m (Array Ξ²)) $ umapMAux f 0 (unsafeCast as)
@[implementedBy Array.umapM] def mapM (f : Ξ± β m Ξ²) (as : Array Ξ±) : m (Array Ξ²) :=
as.foldlM (fun bs a => do b β f a; pure (bs.push b)) (mkEmpty as.size)
@[implementedBy Array.umapIdxM] def mapIdxM (f : Nat β Ξ± β m Ξ²) (as : Array Ξ±) : m (Array Ξ²) :=
as.iterateM (mkEmpty as.size) (fun i a bs => do b β f i.val a; pure (bs.push b))
end
section
variables {m : Type u β Type v} [Monad m]
@[inline] def modifyM [Inhabited Ξ±] (a : Array Ξ±) (i : Nat) (f : Ξ± β m Ξ±) : m (Array Ξ±) :=
if h : i < a.size then do
let idx : Fin a.size := β¨i, hβ©;
let v := a.get idx;
let a := a.set idx (arbitrary Ξ±);
v β f v;
pure $ (a.set idx v)
else
pure a
end
section
variable {Ξ² : Type v}
@[inline] def modify [Inhabited Ξ±] (a : Array Ξ±) (i : Nat) (f : Ξ± β Ξ±) : Array Ξ± :=
Id.run $ a.modifyM i f
@[inline] def modifyOp [Inhabited Ξ±] (self : Array Ξ±) (idx : Nat) (f : Ξ± β Ξ±) : Array Ξ± :=
self.modify idx f
@[inline] def mapIdx (f : Nat β Ξ± β Ξ²) (a : Array Ξ±) : Array Ξ² :=
Id.run $ mapIdxM f a
@[inline] def map (f : Ξ± β Ξ²) (as : Array Ξ±) : Array Ξ² :=
Id.run $ mapM f as
end
section
variables {m : Type v β Type w} [Monad m]
variable {Ξ² : Type v}
@[specialize]
partial def forMAux (f : Ξ± β m PUnit) (a : Array Ξ±) : Nat β m PUnit
| i =>
if h : i < a.size then
let idx : Fin a.size := β¨i, hβ©;
let v : Ξ± := a.get idx;
do f v; forMAux (i+1)
else
pure β¨β©
@[inline] def forM (f : Ξ± β m PUnit) (a : Array Ξ±) : m PUnit :=
a.forMAux f 0
@[inline] def forFromM (f : Ξ± β m PUnit) (beginIdx : Nat) (a : Array Ξ±) : m PUnit :=
a.forMAux f beginIdx
@[specialize]
partial def forRevMAux (f : Ξ± β m PUnit) (a : Array Ξ±) : forall (i : Nat), i β€ a.size β m PUnit
| i, h =>
if hLt : 0 < i then
have i - 1 < i from Nat.subLt hLt (Nat.zeroLtSucc 0);
have i - 1 < a.size from Nat.ltOfLtOfLe this h;
let v : Ξ± := a.get β¨i-1, thisβ©;
have i - 1 β€ a.size from Nat.leOfLt this;
do f v; forRevMAux (i-1) this
else
pure β¨β©
@[inline] def forRevM (f : Ξ± β m PUnit) (a : Array Ξ±) : m PUnit :=
a.forRevMAux f a.size (Nat.leRefl _)
end
-- TODO(Leo): justify termination using wf-rec
partial def extractAux (a : Array Ξ±) : Nat β β (e : Nat), e β€ a.size β Array Ξ± β Array Ξ±
| i, e, hle, r =>
if hlt : i < e then
let idx : Fin a.size := β¨i, Nat.ltOfLtOfLe hlt hleβ©;
extractAux (i+1) e hle (r.push (a.get idx))
else r
def extract (a : Array Ξ±) (b e : Nat) : Array Ξ± :=
let r : Array Ξ± := mkEmpty (e - b);
if h : e β€ a.size then extractAux a b e h r
else r
protected def append (a : Array Ξ±) (b : Array Ξ±) : Array Ξ± :=
b.foldl (fun a v => a.push v) a
instance : HasAppend (Array Ξ±) := β¨Array.appendβ©
-- TODO(Leo): justify termination using wf-rec
@[specialize] partial def isEqvAux (a b : Array Ξ±) (hsz : a.size = b.size) (p : Ξ± β Ξ± β Bool) : Nat β Bool
| i =>
if h : i < a.size then
let aidx : Fin a.size := β¨i, hβ©;
let bidx : Fin b.size := β¨i, hsz βΈ hβ©;
match p (a.get aidx) (b.get bidx) with
| true => isEqvAux (i+1)
| false => false
else
true
@[inline] def isEqv (a b : Array Ξ±) (p : Ξ± β Ξ± β Bool) : Bool :=
if h : a.size = b.size then
isEqvAux a b h p 0
else
false
instance [HasBeq Ξ±] : HasBeq (Array Ξ±) :=
β¨fun a b => isEqv a b HasBeq.beqβ©
-- TODO(Leo): justify termination using wf-rec, and use `swap`
partial def reverseAux : Array Ξ± β Nat β Array Ξ±
| a, i =>
let n := a.size;
if i < n / 2 then
reverseAux (a.swap! i (n - i - 1)) (i+1)
else
a
def reverse (a : Array Ξ±) : Array Ξ± :=
reverseAux a 0
-- TODO(Leo): justify termination using wf-rec
@[specialize] partial def filterAux (p : Ξ± β Bool) : Array Ξ± β Nat β Nat β Array Ξ±
| a, i, j =>
if hβ : i < a.size then
if p (a.get β¨i, hββ©) then
if hβ : j < i then
filterAux (a.swap β¨i, hββ© β¨j, Nat.ltTrans hβ hββ©) (i+1) (j+1)
else
filterAux a (i+1) (j+1)
else
filterAux a (i+1) j
else
a.shrink j
@[inline] def filter (p : Ξ± β Bool) (as : Array Ξ±) : Array Ξ± :=
filterAux p as 0 0
@[specialize] partial def filterMAux {m : Type β Type} [Monad m] {Ξ± : Type} (p : Ξ± β m Bool) : Array Ξ± β Nat β Nat β m (Array Ξ±)
| a, i, j =>
if hβ : i < a.size then
condM (p (a.get β¨i, hββ©))
(if hβ : j < i then
filterMAux (a.swap β¨i, hββ© β¨j, Nat.ltTrans hβ hββ©) (i+1) (j+1)
else
filterMAux a (i+1) (j+1))
(filterMAux a (i+1) j)
else
pure $ a.shrink j
@[inline] def filterM {m : Type β Type} [Monad m] {Ξ± : Type} (p : Ξ± β m Bool) (as : Array Ξ±) : m (Array Ξ±) :=
filterMAux p as 0 0
@[inline] def filterFromM {m : Type β Type} [Monad m] {Ξ± : Type} (p : Ξ± β m Bool) (beginIdx : Nat) (as : Array Ξ±) : m (Array Ξ±) :=
filterMAux p as beginIdx beginIdx
@[specialize] partial def filterMapMAux {m : Type u β Type v} [Monad m] {Ξ± Ξ² : Type u} (f : Ξ± β m (Option Ξ²)) (as : Array Ξ±) : Nat β Array Ξ² β m (Array Ξ²)
| i, bs =>
if h : i < as.size then do
let a := as.get β¨i, hβ©;
b? β f a;
match b? with
| none => filterMapMAux (i+1) bs
| some b => filterMapMAux (i+1) (bs.push b)
else
pure bs
@[inline] def filterMapM {m : Type u β Type v} [Monad m] {Ξ± Ξ² : Type u} (f : Ξ± β m (Option Ξ²)) (as : Array Ξ±) : m (Array Ξ²) :=
filterMapMAux f as 0 Array.empty
@[inline] def filterMap {Ξ± Ξ² : Type u} (f : Ξ± β Option Ξ²) (as : Array Ξ±) : Array Ξ² :=
Id.run $ filterMapM f as
partial def indexOfAux {Ξ±} [HasBeq Ξ±] (a : Array Ξ±) (v : Ξ±) : Nat β Option (Fin a.size)
| i =>
if h : i < a.size then
let idx : Fin a.size := β¨i, hβ©;
if a.get idx == v then some idx
else indexOfAux (i+1)
else none
def indexOf {Ξ±} [HasBeq Ξ±] (a : Array Ξ±) (v : Ξ±) : Option (Fin a.size) :=
indexOfAux a v 0
partial def eraseIdxAux {Ξ±} : Nat β Array Ξ± β Array Ξ±
| i, a =>
if h : i < a.size then
let idx : Fin a.size := β¨i, hβ©;
let idx1 : Fin a.size := β¨i - 1, Nat.ltOfLeOfLt (Nat.predLe i) hβ©;
eraseIdxAux (i+1) (a.swap idx idx1)
else
a.pop
def feraseIdx {Ξ±} (a : Array Ξ±) (i : Fin a.size) : Array Ξ± :=
eraseIdxAux (i.val + 1) a
def eraseIdx {Ξ±} (a : Array Ξ±) (i : Nat) : Array Ξ± :=
if i < a.size then eraseIdxAux (i+1) a else a
theorem szFSwapEq (a : Array Ξ±) (i j : Fin a.size) : (a.swap i j).size = a.size :=
rfl
theorem szPopEq (a : Array Ξ±) : a.pop.size = a.size - 1 :=
rfl
section
/- Instance for justifying `partial` declaration.
We should be able to delete it as soon as we restore support for well-founded recursion. -/
instance eraseIdxSzAuxInstance (a : Array Ξ±) : Inhabited { r : Array Ξ± // r.size = a.size - 1 } :=
β¨β¨a.pop, szPopEq aβ©β©
partial def eraseIdxSzAux {Ξ±} (a : Array Ξ±) : β (i : Nat) (r : Array Ξ±), r.size = a.size β { r : Array Ξ± // r.size = a.size - 1 }
| i, r, heq =>
if h : i < r.size then
let idx : Fin r.size := β¨i, hβ©;
let idx1 : Fin r.size := β¨i - 1, Nat.ltOfLeOfLt (Nat.predLe i) hβ©;
eraseIdxSzAux (i+1) (r.swap idx idx1) ((szFSwapEq r idx idx1).trans heq)
else
β¨r.pop, (szPopEq r).trans (heq βΈ rfl)β©
end
def eraseIdx' {Ξ±} (a : Array Ξ±) (i : Fin a.size) : { r : Array Ξ± // r.size = a.size - 1 } :=
eraseIdxSzAux a (i.val + 1) a rfl
def contains [HasBeq Ξ±] (as : Array Ξ±) (a : Ξ±) : Bool :=
as.any $ fun b => a == b
def elem [HasBeq Ξ±] (a : Ξ±) (as : Array Ξ±) : Bool :=
as.contains a
def erase [HasBeq Ξ±] (as : Array Ξ±) (a : Ξ±) : Array Ξ± :=
match as.indexOf a with
| none => as
| some i => as.feraseIdx i
partial def insertAtAux {Ξ±} (i : Nat) : Array Ξ± β Nat β Array Ξ±
| as, j =>
if i == j then as
else
let as := as.swap! (j-1) j;
insertAtAux as (j-1)
/--
Insert element `a` at position `i`.
Pre: `i < as.size` -/
def insertAt {Ξ±} (as : Array Ξ±) (i : Nat) (a : Ξ±) : Array Ξ± :=
if i > as.size then panic! "invalid index"
else
let as := as.push a;
as.insertAtAux i as.size
theorem ext {Ξ± : Type u} (a b : Array Ξ±) : a.size = b.size β (β (i : Nat) (hiβ : i < a.size) (hiβ : i < b.size) , a.get β¨i, hiββ© = b.get β¨i, hiββ©) β a = b :=
match a, b with
| β¨szβ, fββ©, β¨szβ, fββ© =>
show szβ = szβ β (β (i : Nat) (hiβ : i < szβ) (hiβ : i < szβ) , fβ β¨i, hiββ© = fβ β¨i, hiββ©) β Array.mk szβ fβ = Array.mk szβ fβ from
fun hβ hβ =>
match szβ, szβ, fβ, fβ, hβ, hβ with
| sz, _, fβ, fβ, rfl, hβ =>
have fβ = fβ from funext $ fun β¨i, hiββ© => hβ i hiβ hiβ;
congrArg _ this
theorem extLit {Ξ± : Type u} {n : Nat}
(a b : Array Ξ±)
(hszβ : a.size = n) (hszβ : b.size = n)
(h : β (i : Nat) (hi : i < n), a.getLit i hszβ hi = b.getLit i hszβ hi) : a = b :=
Array.ext a b (hszβ.trans hszβ.symm) $ fun i hiβ hiβ => h i (hszβ βΈ hiβ)
end Array
export Array (mkArray)
@[inlineIfReduce] def List.toArrayAux {Ξ± : Type u} : List Ξ± β Array Ξ± β Array Ξ±
| [], r => r
| a::as, r => List.toArrayAux as (r.push a)
@[inlineIfReduce] def List.redLength {Ξ± : Type u} : List Ξ± β Nat
| [] => 0
| _::as => as.redLength + 1
@[inline, matchPattern] def List.toArray {Ξ± : Type u} (as : List Ξ±) : Array Ξ± :=
as.toArrayAux (Array.mkEmpty as.redLength)
namespace Array
def toListLitAux {Ξ± : Type u} (a : Array Ξ±) (n : Nat) (hsz : a.size = n) : β (i : Nat), i β€ a.size β List Ξ± β List Ξ±
| 0, hi, acc => acc
| (i+1), hi, acc => toListLitAux i (Nat.leOfSuccLe hi) (a.getLit i hsz (Nat.ltOfLtOfEq (Nat.ltOfLtOfLe (Nat.ltSuccSelf i) hi) hsz) :: acc)
def toArrayLit {Ξ± : Type u} (a : Array Ξ±) (n : Nat) (hsz : a.size = n) : Array Ξ± :=
List.toArray $ toListLitAux a n hsz n (hsz βΈ Nat.leRefl _) []
theorem toArrayLitEq {Ξ± : Type u} (a : Array Ξ±) (n : Nat) (hsz : a.size = n) : a = toArrayLit a n hsz :=
-- TODO: this is painful to prove without proper automation
sorry
/-
First, we need to prove
β i j acc, i β€ a.size β (toListLitAux a n hsz (i+1) hi acc).index j = if j < i then a.getLit j hsz _ else acc.index (j - i)
by induction
Base case is trivial
(j : Nat) (acc : List Ξ±) (hi : 0 β€ a.size)
|- (toListLitAux a n hsz 0 hi acc).index j = if j < 0 then a.getLit j hsz _ else acc.index (j - 0)
... |- acc.index j = acc.index j
Induction
(j : Nat) (acc : List Ξ±) (hi : i+1 β€ a.size)
|- (toListLitAux a n hsz (i+1) hi acc).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1))
... |- (toListLitAux a n hsz i hi' (a.getLit i hsz _ :: acc)).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) * by def
... |- if j < i then a.getLit j hsz _ else (a.getLit i hsz _ :: acc).index (j-i) * by induction hypothesis
=
if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1))
If j < i, then both are a.getLit j hsz _
If j = i, then lhs reduces else-branch to (a.getLit i hsz _) and rhs is then-brachn (a.getLit i hsz _)
If j >= i + 1, we use
- j - i >= 1 > 0
- (a::as).index k = as.index (k-1) If k > 0
- j - (i + 1) = (j - i) - 1
Then lhs = (a.getLit i hsz _ :: acc).index (j-i) = acc.index (j-i-1) = acc.index (j-(i+1)) = rhs
With this proof, we have
β j, j < n β (toListLitAux a n hsz n _ []).index j = a.getLit j hsz _
We also need
- (toListLitAux a n hsz n _ []).length = n
- j < n -> (List.toArray as).getLit j _ _ = as.index j
Then using Array.extLit, we have that a = List.toArray $ toListLitAux a n hsz n _ []
-/
@[specialize] def getMax? {Ξ± : Type u} (as : Array Ξ±) (lt : Ξ± β Ξ± β Bool) : Option Ξ± :=
if h : 0 < as.size then
let a0 := as.get β¨0, hβ©;
some $ as.foldlFrom (fun best a => if lt best a then a else best) a0 1
else
none
@[specialize] partial def partitionAux {Ξ± : Type u} (p : Ξ± β Bool) (as : Array Ξ±) : Nat β Array Ξ± β Array Ξ± β Array Ξ± Γ Array Ξ±
| i, bs, cs =>
if h : i < as.size then
let a := as.get β¨i, hβ©;
match p a with
| true => partitionAux (i+1) (bs.push a) cs
| false => partitionAux (i+1) bs (cs.push a)
else
(bs, cs)
@[inline] def partition {Ξ± : Type u} (p : Ξ± β Bool) (as : Array Ξ±) : Array Ξ± Γ Array Ξ± :=
partitionAux p as 0 #[] #[]
partial def isPrefixOfAux {Ξ± : Type u} [HasBeq Ξ±] (as bs : Array Ξ±) (hle : as.size β€ bs.size) : Nat β Bool
| i =>
if h : i < as.size then
let a := as.get β¨i, hβ©;
let b := bs.get β¨i, Nat.ltOfLtOfLe h hleβ©;
if a == b then
isPrefixOfAux (i+1)
else
false
else
true
/- Return true iff `as` is a prefix of `bs` -/
def isPrefixOf {Ξ± : Type u} [HasBeq Ξ±] (as bs : Array Ξ±) : Bool :=
if h : as.size β€ bs.size then
isPrefixOfAux as bs h 0
else
false
private def allDiffAuxAux {Ξ±} [HasBeq Ξ±] (as : Array Ξ±) (a : Ξ±) : forall (i : Nat), i < as.size β Bool
| 0, h => true
| i+1, h =>
have i < as.size from Nat.ltTrans (Nat.ltSuccSelf _) h;
a != as.get β¨i, thisβ© && allDiffAuxAux i this
private partial def allDiffAux {Ξ±} [HasBeq Ξ±] (as : Array Ξ±) : Nat β Bool
| i =>
if h : i < as.size then
allDiffAuxAux as (as.get β¨i, hβ©) i h && allDiffAux (i+1)
else
true
def allDiff {Ξ±} [HasBeq Ξ±] (as : Array Ξ±) : Bool :=
allDiffAux as 0
end Array
|
621ed55d0f54012f6c6ee27cbb86b2663e3db9e8 | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/group_theory/submonoid/basic.lean | e59e7d70bec65ccb242698279dde6c01a7f91f48 | [
"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 | 15,985 | 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, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard,
Amelia Livingston, Yury Kudryashov
-/
import algebra.group.basic
import data.set.lattice
/-!
# Submonoids: definition and `complete_lattice` structure
This file defines bundled multiplicative and additive submonoids. We also define
a `complete_lattice` structure on `submonoid`s, define the closure of a set as the minimal submonoid
that includes this set, and prove a few results about extending properties from a dense set (i.e.
a set with `closure s = β€`) to the whole monoid, see `submonoid.dense_induction` and
`monoid_hom.of_mdense`.
## Main definitions
* `submonoid M`: the type of bundled submonoids of a monoid `M`; the underlying set is given in
the `carrier` field of the structure, and should be accessed through coercion as in `(S : set M)`.
* `add_submonoid M` : the type of bundled submonoids of an additive monoid `M`.
For each of the following definitions in the `submonoid` namespace, there is a corresponding
definition in the `add_submonoid` namespace.
* `submonoid.copy` : copy of a submonoid with `carrier` replaced by a set that is equal but possibly
not definitionally equal to the carrier of the original `submonoid`.
* `submonoid.closure` : monoid closure of a set, i.e., the least submonoid that includes the set.
* `submonoid.gi` : `closure : set M β submonoid M` and coercion `coe : submonoid M β set M`
form a `galois_insertion`;
* `monoid_hom.eq_mlocus`: the submonoid of elements `x : M` such that `f x = g x`;
* `monoid_hom.of_mdense`: if a map `f : M β N` between two monoids satisfies `f 1 = 1` and
`f (x * y) = f x * f y` for `y` from some dense set `s`, then `f` is a monoid homomorphism.
E.g., if `f : β β M` satisfies `f 0 = 0` and `f (x + 1) = f x + f 1`, then `f` is an additive
monoid homomorphism.
## Implementation notes
Submonoid inclusion is denoted `β€` rather than `β`, although `β` is defined as
membership of a submonoid's underlying set.
This file is designed to have very few dependencies. In particular, it should not use natural
numbers.
## Tags
submonoid, submonoids
-/
variables {M : Type*} [monoid M] {s : set M}
variables {A : Type*} [add_monoid A] {t : set A}
/-- A submonoid of a monoid `M` is a subset containing 1 and closed under multiplication. -/
structure submonoid (M : Type*) [monoid M] :=
(carrier : set M)
(one_mem' : (1 : M) β carrier)
(mul_mem' {a b} : a β carrier β b β carrier β a * b β carrier)
/-- An additive submonoid of an additive monoid `M` is a subset containing 0 and
closed under addition. -/
structure add_submonoid (M : Type*) [add_monoid M] :=
(carrier : set M)
(zero_mem' : (0 : M) β carrier)
(add_mem' {a b} : a β carrier β b β carrier β a + b β carrier)
attribute [to_additive add_submonoid] submonoid
namespace submonoid
@[to_additive]
instance : has_coe (submonoid M) (set M) := β¨submonoid.carrierβ©
@[to_additive]
instance : has_coe_to_sort (submonoid M) := β¨Type*, Ξ» S, S.carrierβ©
@[to_additive]
instance : has_mem M (submonoid M) := β¨Ξ» m S, m β (S:set M)β©
@[simp, to_additive]
lemma mem_carrier {s : submonoid M} {x : M} : x β s.carrier β x β s := iff.rfl
@[simp, norm_cast, to_additive]
lemma mem_coe {S : submonoid M} {m : M} : m β (S : set M) β m β S := iff.rfl
@[simp, norm_cast, to_additive]
lemma coe_coe (s : submonoid M) : β₯(s : set M) = s := rfl
attribute [norm_cast] add_submonoid.mem_coe add_submonoid.coe_coe
@[to_additive]
protected lemma Β«existsΒ» {s : submonoid M} {p : s β Prop} :
(β x : s, p x) β β x β s, p β¨x, βΉx β sβΊβ© :=
set_coe.exists
@[to_additive]
protected lemma Β«forallΒ» {s : submonoid M} {p : s β Prop} :
(β x : s, p x) β β x β s, p β¨x, βΉx β sβΊβ© :=
set_coe.forall
/-- Two submonoids are equal if the underlying subsets are equal. -/
@[to_additive "Two `add_submonoid`s are equal if the underlying subsets are equal."]
theorem ext' β¦S T : submonoid Mβ¦ (h : (S : set M) = T) : S = T :=
by cases S; cases T; congr'
/-- Two submonoids are equal if and only if the underlying subsets are equal. -/
@[to_additive "Two `add_submonoid`s are equal if and only if the underlying subsets are equal."]
protected theorem ext'_iff {S T : submonoid M} : S = T β (S : set M) = T :=
β¨Ξ» h, h βΈ rfl, Ξ» h, ext' hβ©
/-- Two submonoids are equal if they have the same elements. -/
@[ext, to_additive "Two `add_submonoid`s are equal if they have the same elements."]
theorem ext {S T : submonoid M}
(h : β x, x β S β x β T) : S = T := ext' $ set.ext h
attribute [ext] add_submonoid.ext
/-- Copy a submonoid replacing `carrier` with a set that is equal to it. -/
@[to_additive "Copy an additive submonoid replacing `carrier` with a set that is equal to it."]
def copy (S : submonoid M) (s : set M) (hs : s = S) : submonoid M :=
{ carrier := s,
one_mem' := hs.symm βΈ S.one_mem',
mul_mem' := hs.symm βΈ S.mul_mem' }
variable {S : submonoid M}
@[simp, to_additive] lemma coe_copy {s : set M} (hs : s = S) :
(S.copy s hs : set M) = s := rfl
@[to_additive] lemma copy_eq {s : set M} (hs : s = S) : S.copy s hs = S := ext' hs
variable (S)
/-- A submonoid contains the monoid's 1. -/
@[to_additive "An `add_submonoid` contains the monoid's 0."]
theorem one_mem : (1 : M) β S := S.one_mem'
/-- A submonoid is closed under multiplication. -/
@[to_additive "An `add_submonoid` is closed under addition."]
theorem mul_mem {x y : M} : x β S β y β S β x * y β S := submonoid.mul_mem' S
@[to_additive] lemma coe_injective : function.injective (coe : S β M) := subtype.val_injective
@[simp, to_additive] lemma coe_eq_coe (x y : S) : (x : M) = y β x = y := set_coe.ext_iff
attribute [norm_cast] coe_eq_coe add_submonoid.coe_eq_coe
@[to_additive]
instance : has_le (submonoid M) := β¨Ξ» S T, β β¦xβ¦, x β S β x β Tβ©
@[to_additive]
lemma le_def {S T : submonoid M} : S β€ T β β β¦x : Mβ¦, x β S β x β T := iff.rfl
@[simp, norm_cast, to_additive]
lemma coe_subset_coe {S T : submonoid M} : (S : set M) β T β S β€ T := iff.rfl
@[to_additive]
instance : partial_order (submonoid M) :=
{ le := Ξ» S T, β β¦xβ¦, x β S β x β T,
.. partial_order.lift (coe : submonoid M β set M) ext' }
@[simp, norm_cast, to_additive]
lemma coe_ssubset_coe {S T : submonoid M} : (S : set M) β T β S < T := iff.rfl
attribute [norm_cast] add_submonoid.coe_subset_coe add_submonoid.coe_ssubset_coe
/-- The submonoid `M` of the monoid `M`. -/
@[to_additive "The additive submonoid `M` of the `add_monoid M`."]
instance : has_top (submonoid M) :=
β¨{ carrier := set.univ,
one_mem' := set.mem_univ 1,
mul_mem' := Ξ» _ _ _ _, set.mem_univ _ }β©
/-- The trivial submonoid `{1}` of an monoid `M`. -/
@[to_additive "The trivial `add_submonoid` `{0}` of an `add_monoid` `M`."]
instance : has_bot (submonoid M) :=
β¨{ carrier := {1},
one_mem' := set.mem_singleton 1,
mul_mem' := Ξ» a b ha hb, by { simp only [set.mem_singleton_iff] at *, rw [ha, hb, mul_one] }}β©
@[to_additive]
instance : inhabited (submonoid M) := β¨β₯β©
@[simp, to_additive] lemma mem_bot {x : M} : x β (β₯ : submonoid M) β x = 1 := set.mem_singleton_iff
@[simp, to_additive] lemma mem_top (x : M) : x β (β€ : submonoid M) := set.mem_univ x
@[simp, to_additive] lemma coe_top : ((β€ : submonoid M) : set M) = set.univ := rfl
@[simp, to_additive] lemma coe_bot : ((β₯ : submonoid M) : set M) = {1} := rfl
/-- The inf of two submonoids is their intersection. -/
@[to_additive "The inf of two `add_submonoid`s is their intersection."]
instance : has_inf (submonoid M) :=
β¨Ξ» Sβ Sβ,
{ carrier := Sβ β© Sβ,
one_mem' := β¨Sβ.one_mem, Sβ.one_memβ©,
mul_mem' := Ξ» _ _ β¨hx, hx'β© β¨hy, hy'β©,
β¨Sβ.mul_mem hx hy, Sβ.mul_mem hx' hy'β© }β©
@[simp, to_additive]
lemma coe_inf (p p' : submonoid M) : ((p β p' : submonoid M) : set M) = p β© p' := rfl
@[simp, to_additive]
lemma mem_inf {p p' : submonoid M} {x : M} : x β p β p' β x β p β§ x β p' := iff.rfl
@[to_additive]
instance : has_Inf (submonoid M) :=
β¨Ξ» s, {
carrier := β t β s, βt,
one_mem' := set.mem_bInter $ Ξ» i h, i.one_mem,
mul_mem' := Ξ» x y hx hy, set.mem_bInter $ Ξ» i h,
i.mul_mem (by apply set.mem_bInter_iff.1 hx i h) (by apply set.mem_bInter_iff.1 hy i h) }β©
@[simp, to_additive]
lemma coe_Inf (S : set (submonoid M)) : ((Inf S : submonoid M) : set M) = β s β S, βs := rfl
@[to_additive]
lemma mem_Inf {S : set (submonoid M)} {x : M} : x β Inf S β β p β S, x β p := set.mem_bInter_iff
@[to_additive]
lemma mem_infi {ΞΉ : Sort*} {S : ΞΉ β submonoid M} {x : M} : (x β β¨
i, S i) β β i, x β S i :=
by simp only [infi, mem_Inf, set.forall_range_iff]
@[simp, to_additive]
lemma coe_infi {ΞΉ : Sort*} {S : ΞΉ β submonoid M} : (β(β¨
i, S i) : set M) = β i, S i :=
by simp only [infi, coe_Inf, set.bInter_range]
attribute [norm_cast] coe_Inf coe_infi
/-- Submonoids of a monoid form a complete lattice. -/
@[to_additive "The `add_submonoid`s of an `add_monoid` form a complete lattice."]
instance : complete_lattice (submonoid M) :=
{ le := (β€),
lt := (<),
bot := (β₯),
bot_le := Ξ» S x hx, (mem_bot.1 hx).symm βΈ S.one_mem,
top := (β€),
le_top := Ξ» S x hx, mem_top x,
inf := (β),
Inf := has_Inf.Inf,
le_inf := Ξ» a b c ha hb x hx, β¨ha hx, hb hxβ©,
inf_le_left := Ξ» a b x, and.left,
inf_le_right := Ξ» a b x, and.right,
.. complete_lattice_of_Inf (submonoid M) $ Ξ» s,
is_glb.of_image (Ξ» S T, show (S : set M) β€ T β S β€ T, from coe_subset_coe) is_glb_binfi }
/-- The `submonoid` generated by a set. -/
@[to_additive "The `add_submonoid` generated by a set"]
def closure (s : set M) : submonoid M := Inf {S | s β S}
@[to_additive]
lemma mem_closure {x : M} : x β closure s β β S : submonoid M, s β S β x β S :=
mem_Inf
/-- The submonoid generated by a set includes the set. -/
@[simp, to_additive "The `add_submonoid` generated by a set includes the set."]
lemma subset_closure : s β closure s := Ξ» x hx, mem_closure.2 $ Ξ» S hS, hS hx
variable {S}
open set
/-- A submonoid `S` includes `closure s` if and only if it includes `s`. -/
@[simp, to_additive "An additive submonoid `S` includes `closure s` if and only if it includes `s`"]
lemma closure_le : closure s β€ S β s β S :=
β¨subset.trans subset_closure, Ξ» h, Inf_le hβ©
/-- Submonoid closure of a set is monotone in its argument: if `s β t`,
then `closure s β€ closure t`. -/
@[to_additive "Additive submonoid closure of a set is monotone in its argument: if `s β t`,
then `closure s β€ closure t`"]
lemma closure_mono β¦s t : set Mβ¦ (h : s β t) : closure s β€ closure t :=
closure_le.2 $ subset.trans h subset_closure
@[to_additive]
lemma closure_eq_of_le (hβ : s β S) (hβ : S β€ closure s) : closure s = S :=
le_antisymm (closure_le.2 hβ) hβ
variable (S)
/-- An induction principle for closure membership. If `p` holds for `1` and all elements of `s`, and
is preserved under multiplication, then `p` holds for all elements of the closure of `s`. -/
@[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all
elements of `s`, and is preserved under addition, then `p` holds for all elements
of the additive closure of `s`."]
lemma closure_induction {p : M β Prop} {x} (h : x β closure s)
(Hs : β x β s, p x) (H1 : p 1)
(Hmul : β x y, p x β p y β p (x * y)) : p x :=
(@closure_le _ _ _ β¨p, H1, Hmulβ©).2 Hs h
attribute [elab_as_eliminator] submonoid.closure_induction add_submonoid.closure_induction
/-- If `s` is a dense set in a monoid `M`, `submonoid.closure s = β€`, then in order to prove that
some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x β s`, verify `p 1`,
and verify that `p x` and `p y` imply `p (x * y)`. -/
@[to_additive]
lemma dense_induction {p : M β Prop} (x : M) {s : set M} (hs : closure s = β€)
(Hs : β x β s, p x) (H1 : p 1)
(Hmul : β x y, p x β p y β p (x * y)) : p x :=
have β x β closure s, p x, from Ξ» x hx, closure_induction hx Hs H1 Hmul,
by simpa [hs] using this x
/-- If `s` is a dense set in an additive monoid `M`, `add_submonoid.closure s = β€`, then in order
to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x β s`,
verify `p 0`, and verify that `p x` and `p y` imply `p (x + y)`. -/
add_decl_doc add_submonoid.dense_induction
attribute [elab_as_eliminator] dense_induction add_submonoid.dense_induction
variable (M)
/-- `closure` forms a Galois insertion with the coercion to set. -/
@[to_additive "`closure` forms a Galois insertion with the coercion to set."]
protected def gi : galois_insertion (@closure M _) coe :=
{ choice := Ξ» s _, closure s,
gc := Ξ» s t, closure_le,
le_l_u := Ξ» s, subset_closure,
choice_eq := Ξ» s h, rfl }
variable {M}
/-- Closure of a submonoid `S` equals `S`. -/
@[simp, to_additive "Additive closure of an additive submonoid `S` equals `S`"]
lemma closure_eq : closure (S : set M) = S := (submonoid.gi M).l_u_eq S
@[simp, to_additive] lemma closure_empty : closure (β
: set M) = β₯ :=
(submonoid.gi M).gc.l_bot
@[simp, to_additive] lemma closure_univ : closure (univ : set M) = β€ :=
@coe_top M _ βΈ closure_eq β€
@[to_additive]
lemma closure_union (s t : set M) : closure (s βͺ t) = closure s β closure t :=
(submonoid.gi M).gc.l_sup
@[to_additive]
lemma closure_Union {ΞΉ} (s : ΞΉ β set M) : closure (β i, s i) = β¨ i, closure (s i) :=
(submonoid.gi M).gc.l_supr
end submonoid
namespace monoid_hom
variables {N : Type*} {P : Type*} [monoid N] [monoid P] (S : submonoid M)
open submonoid
/-- The submonoid of elements `x : M` such that `f x = g x` -/
@[to_additive "The additive submonoid of elements `x : M` such that `f x = g x`"]
def eq_mlocus (f g : M β* N) : submonoid M :=
{ carrier := {x | f x = g x},
one_mem' := by rw [set.mem_set_of_eq, f.map_one, g.map_one],
mul_mem' := Ξ» x y (hx : _ = _) (hy : _ = _), by simp [*] }
/-- If two monoid homomorphisms are equal on a set, then they are equal on its submonoid closure. -/
@[to_additive]
lemma eq_on_mclosure {f g : M β* N} {s : set M} (h : set.eq_on f g s) :
set.eq_on f g (closure s) :=
show closure s β€ f.eq_mlocus g, from closure_le.2 h
@[to_additive]
lemma eq_of_eq_on_mtop {f g : M β* N} (h : set.eq_on f g (β€ : submonoid M)) :
f = g :=
ext $ Ξ» x, h trivial
@[to_additive]
lemma eq_of_eq_on_mdense {s : set M} (hs : closure s = β€) {f g : M β* N} (h : s.eq_on f g) :
f = g :=
eq_of_eq_on_mtop $ hs βΈ eq_on_mclosure h
/-- Let `s` be a subset of a monoid `M` such that the closure of `s` is the whole monoid.
Then `monoid_hom.of_mdense` defines a monoid homomorphism from `M` asking for a proof
of `f (x * y) = f x * f y` only for `y β s`. -/
@[to_additive]
def of_mdense (f : M β N) (hs : closure s = β€) (h1 : f 1 = 1)
(hmul : β x (y β s), f (x * y) = f x * f y) :
M β* N :=
{ to_fun := f,
map_one' := h1,
map_mul' := Ξ» x y, dense_induction y hs (Ξ» y hy x, hmul x y hy) (by simp [h1])
(Ξ» yβ yβ hβ hβ x, by simp only [β mul_assoc, hβ, hβ]) x }
/-- Let `s` be a subset of an additive monoid `M` such that the closure of `s` is the whole monoid.
Then `add_monoid_hom.of_mdense` defines an additive monoid homomorphism from `M` asking for a proof
of `f (x + y) = f x + f y` only for `y β s`. -/
add_decl_doc add_monoid_hom.of_mdense
@[simp, to_additive] lemma coe_of_mdense (f : M β N) (hs : closure s = β€) (h1 hmul) :
β(of_mdense f hs h1 hmul) = f := rfl
attribute [norm_cast] coe_of_mdense add_monoid_hom.coe_of_mdense
end monoid_hom
|
430a8179b515613f8e78034198f944da77a13638 | fc086f79b20cf002d6f34b023749998408e94fbf | /test/tidy_problem.lean | 9f6a4abe51f56ff44e05b1526a69929c32710469 | [] | no_license | semorrison/lean-tidy | f039460136b898fb282f75efedd92f2d5c5d90f8 | 6c1d46de6cff05e1c2c4c9692af812bca3e13b6c | refs/heads/master | 1,624,461,332,392 | 1,559,655,744,000 | 1,559,655,744,000 | 96,569,994 | 9 | 4 | null | 1,538,287,895,000 | 1,499,455,306,000 | Lean | UTF-8 | Lean | false | false | 612 | lean | import data.polynomial
-- compare the result when you uncomment this import -- error!
-- import tidy.tidy
-- This is now broken without this include, too!
class algebra (R : out_param $ Type*) [comm_ring R] (A : Type*) extends ring A :=
(f : R β A) [hom : is_ring_hom f]
(commutes : β r s, s * f r = f r * s)
variables (R : Type*) [ring R]
-- instance ring.to_β€_algebra : algebra β€ R :=
-- { f := coe,
-- hom := by constructor; intros; simp,
-- commutes := Ξ» n r, int.induction_on n (by simp)
-- (Ξ» i ih, by simp [mul_add, add_mul, ih])
-- (Ξ» i ih, by simp [mul_add, add_mul, ih]), }
|
17db5bd79c987acd6d01ce7be77a09b56caeae50 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/limits/opposites.lean | 0b0e88529db86081593860da84ed44fdaa4d1a84 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 25,753 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Floris van Doorn
-/
import category_theory.limits.shapes.finite_products
import category_theory.discrete_category
import tactic.equiv_rw
/-!
# Limits in `C` give colimits in `Cα΅α΅`.
We also give special cases for (co)products,
(co)equalizers, and pullbacks / pushouts.
-/
universes vβ vβ uβ uβ
noncomputable theory
open category_theory
open category_theory.functor
open opposite
namespace category_theory.limits
variables {C : Type uβ} [category.{vβ} C]
variables {J : Type uβ} [category.{vβ} J]
/-- Turn a colimit for `F : J β₯€ C` into a limit for `F.op : Jα΅α΅ β₯€ Cα΅α΅`. -/
@[simps] def is_limit_cocone_op (F : J β₯€ C) {c : cocone F} (hc : is_colimit c) :
is_limit c.op :=
{ lift := Ξ» s, (hc.desc s.unop).op,
fac' := Ξ» s j, quiver.hom.unop_inj (by simpa),
uniq' := Ξ» s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_colimit.fac] using w (op j)
end }
/-- Turn a limit for `F : J β₯€ C` into a colimit for `F.op : Jα΅α΅ β₯€ Cα΅α΅`. -/
@[simps] def is_colimit_cone_op (F : J β₯€ C) {c : cone F} (hc : is_limit c) :
is_colimit c.op :=
{ desc := Ξ» s, (hc.lift s.unop).op,
fac' := Ξ» s j, quiver.hom.unop_inj (by simpa),
uniq' := Ξ» s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_limit.fac] using w (op j)
end }
/-- Turn a colimit for `F : J β₯€ Cα΅α΅` into a limit for `F.left_op : Jα΅α΅ β₯€ C`. -/
@[simps] def is_limit_cone_left_op_of_cocone (F : J β₯€ Cα΅α΅) {c : cocone F} (hc : is_colimit c) :
is_limit (cone_left_op_of_cocone c) :=
{ lift := Ξ» s, (hc.desc (cocone_of_cone_left_op s)).unop,
fac' := Ξ» s j, quiver.hom.op_inj $ by simpa only [cone_left_op_of_cocone_Ο_app, op_comp,
quiver.hom.op_unop, is_colimit.fac, cocone_of_cone_left_op_ΞΉ_app],
uniq' := Ξ» s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_colimit.fac, cocone_of_cone_left_op_ΞΉ_app] using w (op j)
end }
/-- Turn a limit of `F : J β₯€ Cα΅α΅` into a colimit of `F.left_op : Jα΅α΅ β₯€ C`. -/
@[simps] def is_colimit_cocone_left_op_of_cone (F : J β₯€ Cα΅α΅) {c : cone F} (hc : is_limit c) :
is_colimit (cocone_left_op_of_cone c) :=
{ desc := Ξ» s, (hc.lift (cone_of_cocone_left_op s)).unop,
fac' := Ξ» s j, quiver.hom.op_inj $ by simpa only [cocone_left_op_of_cone_ΞΉ_app, op_comp,
quiver.hom.op_unop, is_limit.fac, cone_of_cocone_left_op_Ο_app],
uniq' := Ξ» s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_limit.fac, cone_of_cocone_left_op_Ο_app] using w (op j)
end }
/-- Turn a colimit for `F : Jα΅α΅ β₯€ C` into a limit for `F.right_op : J β₯€ Cα΅α΅`. -/
@[simps] def is_limit_cone_right_op_of_cocone (F : Jα΅α΅ β₯€ C) {c : cocone F} (hc : is_colimit c) :
is_limit (cone_right_op_of_cocone c) :=
{ lift := Ξ» s, (hc.desc (cocone_of_cone_right_op s)).op,
fac' := Ξ» s j, quiver.hom.unop_inj (by simpa),
uniq' := Ξ» s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_colimit.fac] using w (unop j)
end }
/-- Turn a limit for `F : Jα΅α΅ β₯€ C` into a colimit for `F.right_op : J β₯€ Cα΅α΅`. -/
@[simps] def is_colimit_cocone_right_op_of_cone (F : Jα΅α΅ β₯€ C) {c : cone F} (hc : is_limit c) :
is_colimit (cocone_right_op_of_cone c) :=
{ desc := Ξ» s, (hc.lift (cone_of_cocone_right_op s)).op,
fac' := Ξ» s j, quiver.hom.unop_inj (by simpa),
uniq' := Ξ» s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_limit.fac] using w (unop j)
end }
/-- Turn a colimit for `F : Jα΅α΅ β₯€ Cα΅α΅` into a limit for `F.unop : J β₯€ C`. -/
@[simps] def is_limit_cone_unop_of_cocone (F : Jα΅α΅ β₯€ Cα΅α΅) {c : cocone F} (hc : is_colimit c) :
is_limit (cone_unop_of_cocone c) :=
{ lift := Ξ» s, (hc.desc (cocone_of_cone_unop s)).unop,
fac' := Ξ» s j, quiver.hom.op_inj (by simpa),
uniq' := Ξ» s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_colimit.fac] using w (unop j)
end }
/-- Turn a limit of `F : Jα΅α΅ β₯€ Cα΅α΅` into a colimit of `F.unop : J β₯€ C`. -/
@[simps] def is_colimit_cocone_unop_of_cone (F : Jα΅α΅ β₯€ Cα΅α΅) {c : cone F} (hc : is_limit c) :
is_colimit (cocone_unop_of_cone c) :=
{ desc := Ξ» s, (hc.lift (cone_of_cocone_unop s)).unop,
fac' := Ξ» s j, quiver.hom.op_inj (by simpa),
uniq' := Ξ» s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_limit.fac] using w (unop j)
end }
/-- Turn a colimit for `F.op : Jα΅α΅ β₯€ Cα΅α΅` into a limit for `F : J β₯€ C`. -/
@[simps] def is_limit_cocone_unop (F : J β₯€ C) {c : cocone F.op} (hc : is_colimit c) :
is_limit c.unop :=
{ lift := Ξ» s, (hc.desc s.op).unop,
fac' := Ξ» s j, quiver.hom.op_inj (by simpa),
uniq' := Ξ» s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_colimit.fac] using w (unop j)
end }
/-- Turn a limit for `F.op : Jα΅α΅ β₯€ Cα΅α΅` into a colimit for `F : J β₯€ C`. -/
@[simps] def is_colimit_cone_unop (F : J β₯€ C) {c : cone F.op} (hc : is_limit c) :
is_colimit c.unop :=
{ desc := Ξ» s, (hc.lift s.op).unop,
fac' := Ξ» s j, quiver.hom.op_inj (by simpa),
uniq' := Ξ» s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_limit.fac] using w (unop j)
end }
/-- Turn a colimit for `F.left_op : Jα΅α΅ β₯€ C` into a limit for `F : J β₯€ Cα΅α΅`. -/
@[simps] def is_limit_cone_of_cocone_left_op (F : J β₯€ Cα΅α΅) {c : cocone F.left_op}
(hc : is_colimit c) : is_limit (cone_of_cocone_left_op c) :=
{ lift := Ξ» s, (hc.desc (cocone_left_op_of_cone s)).op,
fac' := Ξ» s j, quiver.hom.unop_inj $ by simpa only [cone_of_cocone_left_op_Ο_app, unop_comp,
quiver.hom.unop_op, is_colimit.fac, cocone_left_op_of_cone_ΞΉ_app],
uniq' := Ξ» s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_colimit.fac, cone_of_cocone_left_op_Ο_app] using w (unop j)
end }
/-- Turn a limit of `F.left_op : Jα΅α΅ β₯€ C` into a colimit of `F : J β₯€ Cα΅α΅`. -/
@[simps] def is_colimit_cocone_of_cone_left_op (F : J β₯€ Cα΅α΅) {c : cone (F.left_op)}
(hc : is_limit c) : is_colimit (cocone_of_cone_left_op c) :=
{ desc := Ξ» s, (hc.lift (cone_left_op_of_cocone s)).op,
fac' := Ξ» s j, quiver.hom.unop_inj $ by simpa only [cocone_of_cone_left_op_ΞΉ_app, unop_comp,
quiver.hom.unop_op, is_limit.fac, cone_left_op_of_cocone_Ο_app],
uniq' := Ξ» s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_limit.fac, cocone_of_cone_left_op_ΞΉ_app] using w (unop j)
end }
/-- Turn a colimit for `F.right_op : J β₯€ Cα΅α΅` into a limit for `F : Jα΅α΅ β₯€ C`. -/
@[simps] def is_limit_cone_of_cocone_right_op (F : Jα΅α΅ β₯€ C) {c : cocone F.right_op}
(hc : is_colimit c) : is_limit (cone_of_cocone_right_op c) :=
{ lift := Ξ» s, (hc.desc (cocone_right_op_of_cone s)).unop,
fac' := Ξ» s j, quiver.hom.op_inj (by simpa),
uniq' := Ξ» s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_colimit.fac] using w (op j)
end }
/-- Turn a limit for `F.right_op : J β₯€ Cα΅α΅` into a limit for `F : Jα΅α΅ β₯€ C`. -/
@[simps] def is_colimit_cocone_of_cone_right_op (F : Jα΅α΅ β₯€ C) {c : cone F.right_op}
(hc : is_limit c) : is_colimit (cocone_of_cone_right_op c) :=
{ desc := Ξ» s, (hc.lift (cone_right_op_of_cocone s)).unop,
fac' := Ξ» s j, quiver.hom.op_inj (by simpa),
uniq' := Ξ» s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_limit.fac] using w (op j)
end }
/-- Turn a colimit for `F.unop : J β₯€ C` into a limit for `F : Jα΅α΅ β₯€ Cα΅α΅`. -/
@[simps] def is_limit_cone_of_cocone_unop (F : Jα΅α΅ β₯€ Cα΅α΅) {c : cocone F.unop} (hc : is_colimit c) :
is_limit (cone_of_cocone_unop c) :=
{ lift := Ξ» s, (hc.desc (cocone_unop_of_cone s)).op,
fac' := Ξ» s j, quiver.hom.unop_inj (by simpa),
uniq' := Ξ» s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_colimit.fac] using w (op j)
end }
/-- Turn a limit for `F.unop : J β₯€ C` into a colimit for `F : Jα΅α΅ β₯€ Cα΅α΅`. -/
@[simps] def is_colimit_cone_of_cocone_unop (F : Jα΅α΅ β₯€ Cα΅α΅) {c : cone F.unop} (hc : is_limit c) :
is_colimit (cocone_of_cone_unop c) :=
{ desc := Ξ» s, (hc.lift (cone_unop_of_cocone s)).op,
fac' := Ξ» s j, quiver.hom.unop_inj (by simpa),
uniq' := Ξ» s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_limit.fac] using w (op j)
end }
/--
If `F.left_op : Jα΅α΅ β₯€ C` has a colimit, we can construct a limit for `F : J β₯€ Cα΅α΅`.
-/
lemma has_limit_of_has_colimit_left_op (F : J β₯€ Cα΅α΅) [has_colimit F.left_op] : has_limit F :=
has_limit.mk
{ cone := cone_of_cocone_left_op (colimit.cocone F.left_op),
is_limit := is_limit_cone_of_cocone_left_op _ (colimit.is_colimit _) }
/--
If `C` has colimits of shape `Jα΅α΅`, we can construct limits in `Cα΅α΅` of shape `J`.
-/
lemma has_limits_of_shape_op_of_has_colimits_of_shape [has_colimits_of_shape Jα΅α΅ C] :
has_limits_of_shape J Cα΅α΅ :=
{ has_limit := Ξ» F, has_limit_of_has_colimit_left_op F }
local attribute [instance] has_limits_of_shape_op_of_has_colimits_of_shape
/--
If `C` has colimits, we can construct limits for `Cα΅α΅`.
-/
instance has_limits_op_of_has_colimits [has_colimits C] : has_limits Cα΅α΅ := β¨infer_instanceβ©
/--
If `F.left_op : Jα΅α΅ β₯€ C` has a limit, we can construct a colimit for `F : J β₯€ Cα΅α΅`.
-/
lemma has_colimit_of_has_limit_left_op (F : J β₯€ Cα΅α΅) [has_limit F.left_op] : has_colimit F :=
has_colimit.mk
{ cocone := cocone_of_cone_left_op (limit.cone F.left_op),
is_colimit := is_colimit_cocone_of_cone_left_op _ (limit.is_limit _) }
/--
If `C` has colimits of shape `Jα΅α΅`, we can construct limits in `Cα΅α΅` of shape `J`.
-/
lemma has_colimits_of_shape_op_of_has_limits_of_shape [has_limits_of_shape Jα΅α΅ C] :
has_colimits_of_shape J Cα΅α΅ :=
{ has_colimit := Ξ» F, has_colimit_of_has_limit_left_op F }
local attribute [instance] has_colimits_of_shape_op_of_has_limits_of_shape
/--
If `C` has limits, we can construct colimits for `Cα΅α΅`.
-/
instance has_colimits_op_of_has_limits [has_limits C] : has_colimits Cα΅α΅ := β¨infer_instanceβ©
variables (X : Type vβ)
/--
If `C` has products indexed by `X`, then `Cα΅α΅` has coproducts indexed by `X`.
-/
instance has_coproducts_opposite [has_products_of_shape X C] :
has_coproducts_of_shape X Cα΅α΅ :=
begin
haveI : has_limits_of_shape (discrete X)α΅α΅ C :=
has_limits_of_shape_of_equivalence (discrete.opposite X).symm,
apply_instance
end
/--
If `C` has coproducts indexed by `X`, then `Cα΅α΅` has products indexed by `X`.
-/
instance has_products_opposite [has_coproducts_of_shape X C] :
has_products_of_shape X Cα΅α΅ :=
begin
haveI : has_colimits_of_shape (discrete X)α΅α΅ C :=
has_colimits_of_shape_of_equivalence (discrete.opposite X).symm,
apply_instance
end
instance has_finite_coproducts_opposite [has_finite_products C] : has_finite_coproducts Cα΅α΅ :=
{ out := Ξ» J π, begin
resetI,
haveI : has_limits_of_shape (discrete J)α΅α΅ C :=
has_limits_of_shape_of_equivalence (discrete.opposite J).symm,
apply_instance,
end }
instance has_finite_products_opposite [has_finite_coproducts C] : has_finite_products Cα΅α΅ :=
{ out := Ξ» J π, begin
resetI,
haveI : has_colimits_of_shape (discrete J)α΅α΅ C :=
has_colimits_of_shape_of_equivalence (discrete.opposite J).symm,
apply_instance,
end }
instance has_equalizers_opposite [has_coequalizers C] : has_equalizers Cα΅α΅ :=
begin
haveI : has_colimits_of_shape walking_parallel_pairα΅α΅ C :=
has_colimits_of_shape_of_equivalence walking_parallel_pair_op_equiv,
apply_instance
end
instance has_coequalizers_opposite [has_equalizers C] : has_coequalizers Cα΅α΅ :=
begin
haveI : has_limits_of_shape walking_parallel_pairα΅α΅ C :=
has_limits_of_shape_of_equivalence walking_parallel_pair_op_equiv,
apply_instance
end
instance has_finite_colimits_opposite [has_finite_limits C] :
has_finite_colimits Cα΅α΅ :=
{ out := Ξ» J π π₯, by { resetI, apply_instance, }, }
instance has_finite_limits_opposite [has_finite_colimits C] :
has_finite_limits Cα΅α΅ :=
{ out := Ξ» J π π₯, by { resetI, apply_instance, }, }
instance has_pullbacks_opposite [has_pushouts C] : has_pullbacks Cα΅α΅ :=
begin
haveI : has_colimits_of_shape walking_cospanα΅α΅ C :=
has_colimits_of_shape_of_equivalence walking_cospan_op_equiv.symm,
apply has_limits_of_shape_op_of_has_colimits_of_shape,
end
instance has_pushouts_opposite [has_pullbacks C] : has_pushouts Cα΅α΅ :=
begin
haveI : has_limits_of_shape walking_spanα΅α΅ C :=
has_limits_of_shape_of_equivalence walking_span_op_equiv.symm,
apply has_colimits_of_shape_op_of_has_limits_of_shape,
end
/-- The canonical isomorphism relating `span f.op g.op` and `(cospan f g).op` -/
@[simps]
def span_op {X Y Z : C} (f : X βΆ Z) (g : Y βΆ Z) :
span f.op g.op β
walking_cospan_op_equiv.inverse β (cospan f g).op :=
nat_iso.of_components (by { rintro (_|_|_); refl, })
(by { rintros (_|_|_) (_|_|_) f; cases f; tidy, })
/-- The canonical isomorphism relating `(cospan f g).op` and `span f.op g.op` -/
@[simps]
def op_cospan {X Y Z : C} (f : X βΆ Z) (g : Y βΆ Z) :
(cospan f g).op β
walking_cospan_op_equiv.functor β span f.op g.op :=
calc (cospan f g).op β
π _ β (cospan f g).op : by refl
... β
(walking_cospan_op_equiv.functor β walking_cospan_op_equiv.inverse) β (cospan f g).op :
iso_whisker_right walking_cospan_op_equiv.unit_iso _
... β
walking_cospan_op_equiv.functor β (walking_cospan_op_equiv.inverse β (cospan f g).op) :
functor.associator _ _ _
... β
walking_cospan_op_equiv.functor β span f.op g.op : iso_whisker_left _ (span_op f g).symm
/-- The canonical isomorphism relating `cospan f.op g.op` and `(span f g).op` -/
@[simps]
def cospan_op {X Y Z : C} (f : X βΆ Y) (g : X βΆ Z) :
cospan f.op g.op β
walking_span_op_equiv.inverse β (span f g).op :=
nat_iso.of_components (by { rintro (_|_|_); refl, })
(by { rintros (_|_|_) (_|_|_) f; cases f; tidy, })
/-- The canonical isomorphism relating `(span f g).op` and `cospan f.op g.op` -/
@[simps]
def op_span {X Y Z : C} (f : X βΆ Y) (g : X βΆ Z) :
(span f g).op β
walking_span_op_equiv.functor β cospan f.op g.op :=
calc (span f g).op β
π _ β (span f g).op : by refl
... β
(walking_span_op_equiv.functor β walking_span_op_equiv.inverse) β (span f g).op :
iso_whisker_right walking_span_op_equiv.unit_iso _
... β
walking_span_op_equiv.functor β (walking_span_op_equiv.inverse β (span f g).op) :
functor.associator _ _ _
... β
walking_span_op_equiv.functor β cospan f.op g.op :
iso_whisker_left _ (cospan_op f g).symm
namespace pushout_cocone
/-- The obvious map `pushout_cocone f g β pullback_cone f.unop g.unop` -/
@[simps (lemmas_only)]
def unop {X Y Z : Cα΅α΅} {f : X βΆ Y} {g : X βΆ Z} (c : pushout_cocone f g) :
pullback_cone f.unop g.unop :=
cocone.unop ((cocones.precompose (op_cospan f.unop g.unop).hom).obj
(cocone.whisker walking_cospan_op_equiv.functor c))
@[simp]
lemma unop_fst {X Y Z : Cα΅α΅} {f : X βΆ Y} {g : X βΆ Z} (c : pushout_cocone f g) :
c.unop.fst = c.inl.unop :=
by { change (_ : limits.cone _).Ο.app _ = _,
simp only [pushout_cocone.ΞΉ_app_left, pushout_cocone.unop_Ο_app], tidy }
@[simp]
lemma unop_snd {X Y Z : Cα΅α΅} {f : X βΆ Y} {g : X βΆ Z} (c : pushout_cocone f g) :
c.unop.snd = c.inr.unop :=
by { change (_ : limits.cone _).Ο.app _ = _,
simp only [pushout_cocone.unop_Ο_app, pushout_cocone.ΞΉ_app_right], tidy, }
/-- The obvious map `pushout_cocone f.op g.op β pullback_cone f g` -/
@[simps (lemmas_only)]
def op {X Y Z : C} {f : X βΆ Y} {g : X βΆ Z} (c : pushout_cocone f g) :
pullback_cone f.op g.op :=
(cones.postcompose ((cospan_op f g).symm).hom).obj
(cone.whisker walking_span_op_equiv.inverse (cocone.op c))
@[simp]
lemma op_fst {X Y Z : C} {f : X βΆ Y} {g : X βΆ Z} (c : pushout_cocone f g) :
c.op.fst = c.inl.op :=
by { change (_ : limits.cone _).Ο.app _ = _, apply category.comp_id, }
@[simp]
lemma op_snd {X Y Z : C} {f : X βΆ Y} {g : X βΆ Z} (c : pushout_cocone f g) :
c.op.snd = c.inr.op :=
by { change (_ : limits.cone _).Ο.app _ = _, apply category.comp_id, }
end pushout_cocone
namespace pullback_cone
/-- The obvious map `pullback_cone f g β pushout_cocone f.unop g.unop` -/
@[simps (lemmas_only)]
def unop {X Y Z : Cα΅α΅} {f : X βΆ Z} {g : Y βΆ Z} (c : pullback_cone f g) :
pushout_cocone f.unop g.unop :=
cone.unop ((cones.postcompose (op_span f.unop g.unop).symm.hom).obj
(cone.whisker walking_span_op_equiv.functor c))
@[simp]
lemma unop_inl {X Y Z : Cα΅α΅} {f : X βΆ Z} {g : Y βΆ Z} (c : pullback_cone f g) :
c.unop.inl = c.fst.unop :=
begin
change ((_ : limits.cocone _).ΞΉ.app _) = _,
dsimp only [unop, op_span],
simp, dsimp, simp, dsimp, simp
end
@[simp]
lemma unop_inr {X Y Z : Cα΅α΅} {f : X βΆ Z} {g : Y βΆ Z} (c : pullback_cone f g) :
c.unop.inr = c.snd.unop :=
begin
change ((_ : limits.cocone _).ΞΉ.app _) = _,
apply quiver.hom.op_inj,
simp [unop_ΞΉ_app], dsimp, simp,
apply category.comp_id,
end
/-- The obvious map `pullback_cone f g β pushout_cocone f.op g.op` -/
@[simps (lemmas_only)]
def op {X Y Z : C} {f : X βΆ Z} {g : Y βΆ Z} (c : pullback_cone f g) :
pushout_cocone f.op g.op :=
(cocones.precompose (span_op f g).hom).obj
(cocone.whisker walking_cospan_op_equiv.inverse (cone.op c))
@[simp] lemma op_inl {X Y Z : C} {f : X βΆ Z} {g : Y βΆ Z} (c : pullback_cone f g) :
c.op.inl = c.fst.op :=
by { change (_ : limits.cocone _).ΞΉ.app _ = _, apply category.id_comp, }
@[simp] lemma op_inr {X Y Z : C} {f : X βΆ Z} {g : Y βΆ Z} (c : pullback_cone f g) :
c.op.inr = c.snd.op :=
by { change (_ : limits.cocone _).ΞΉ.app _ = _, apply category.id_comp, }
/-- If `c` is a pullback cone, then `c.op.unop` is isomorphic to `c`. -/
def op_unop {X Y Z : C} {f : X βΆ Z} {g : Y βΆ Z} (c : pullback_cone f g) : c.op.unop β
c :=
pullback_cone.ext (iso.refl _) (by simp) (by simp)
/-- If `c` is a pullback cone in `Cα΅α΅`, then `c.unop.op` is isomorphic to `c`. -/
def unop_op {X Y Z : Cα΅α΅} {f : X βΆ Z} {g : Y βΆ Z} (c : pullback_cone f g) : c.unop.op β
c :=
pullback_cone.ext (iso.refl _) (by simp) (by simp)
end pullback_cone
namespace pushout_cocone
/-- If `c` is a pushout cocone, then `c.op.unop` is isomorphic to `c`. -/
def op_unop {X Y Z : C} {f : X βΆ Y} {g : X βΆ Z} (c : pushout_cocone f g) : c.op.unop β
c :=
pushout_cocone.ext (iso.refl _) (by simp) (by simp)
/-- If `c` is a pushout cocone in `Cα΅α΅`, then `c.unop.op` is isomorphic to `c`. -/
def unop_op {X Y Z : Cα΅α΅} {f : X βΆ Y} {g : X βΆ Z} (c : pushout_cocone f g) : c.unop.op β
c :=
pushout_cocone.ext (iso.refl _) (by simp) (by simp)
/-- A pushout cone is a colimit cocone if and only if the corresponding pullback cone
in the opposite category is a limit cone. -/
def is_colimit_equiv_is_limit_op {X Y Z : C} {f : X βΆ Y} {g : X βΆ Z} (c : pushout_cocone f g) :
is_colimit c β is_limit c.op :=
begin
apply equiv_of_subsingleton_of_subsingleton,
{ intro h,
equiv_rw is_limit.postcompose_hom_equiv _ _,
equiv_rw (is_limit.whisker_equivalence_equiv walking_span_op_equiv.symm).symm,
exact is_limit_cocone_op _ h, },
{ intro h,
equiv_rw is_colimit.equiv_iso_colimit c.op_unop.symm,
apply is_colimit_cone_unop,
equiv_rw is_limit.postcompose_hom_equiv _ _,
equiv_rw (is_limit.whisker_equivalence_equiv _).symm,
exact h, }
end
/-- A pushout cone is a colimit cocone in `Cα΅α΅` if and only if the corresponding pullback cone
in `C` is a limit cone. -/
def is_colimit_equiv_is_limit_unop {X Y Z : Cα΅α΅} {f : X βΆ Y} {g : X βΆ Z}
(c : pushout_cocone f g) : is_colimit c β is_limit c.unop :=
begin
apply equiv_of_subsingleton_of_subsingleton,
{ intro h,
apply is_limit_cocone_unop,
equiv_rw is_colimit.precompose_hom_equiv _ _,
equiv_rw (is_colimit.whisker_equivalence_equiv _).symm,
exact h, },
{ intro h,
equiv_rw is_colimit.equiv_iso_colimit c.unop_op.symm,
equiv_rw is_colimit.precompose_hom_equiv _ _,
equiv_rw (is_colimit.whisker_equivalence_equiv walking_cospan_op_equiv.symm).symm,
exact is_colimit_cone_op _ h, },
end
end pushout_cocone
namespace pullback_cone
/-- A pullback cone is a limit cone if and only if the corresponding pushout cocone
in the opposite category is a colimit cocone. -/
def is_limit_equiv_is_colimit_op {X Y Z : C} {f : X βΆ Z} {g : Y βΆ Z}
(c : pullback_cone f g) : is_limit c β is_colimit c.op :=
(is_limit.equiv_iso_limit c.op_unop).symm.trans c.op.is_colimit_equiv_is_limit_unop.symm
/-- A pullback cone is a limit cone in `Cα΅α΅` if and only if the corresponding pushout cocone
in `C` is a colimit cocone. -/
def is_limit_equiv_is_colimit_unop {X Y Z : Cα΅α΅} {f : X βΆ Z} {g : Y βΆ Z}
(c : pullback_cone f g) : is_limit c β is_colimit c.unop :=
(is_limit.equiv_iso_limit c.unop_op).symm.trans c.unop.is_colimit_equiv_is_limit_op.symm
end pullback_cone
section pullback
open opposite
/-- The pullback of `f` and `g` in `C` is isomorphic to the pushout of
`f.op` and `g.op` in `Cα΅α΅`. -/
noncomputable
def pullback_iso_unop_pushout {X Y Z : C} (f : X βΆ Z) (g : Y βΆ Z)
[has_pullback f g] [has_pushout f.op g.op] : pullback f g β
unop (pushout f.op g.op) :=
is_limit.cone_point_unique_up_to_iso (limit.is_limit _)
((pushout_cocone.is_colimit_equiv_is_limit_unop _) (colimit.is_colimit (span f.op g.op)))
@[simp, reassoc]
lemma pullback_iso_unop_pushout_inv_fst {X Y Z : C} (f : X βΆ Z) (g : Y βΆ Z)
[has_pullback f g] [has_pushout f.op g.op] :
(pullback_iso_unop_pushout f g).inv β« pullback.fst =
(pushout.inl : _ βΆ pushout f.op g.op).unop :=
(is_limit.cone_point_unique_up_to_iso_inv_comp _ _ _).trans (by simp)
@[simp, reassoc]
lemma pullback_iso_unop_pushout_inv_snd {X Y Z : C} (f : X βΆ Z)
(g : Y βΆ Z) [has_pullback f g] [has_pushout f.op g.op] :
(pullback_iso_unop_pushout f g).inv β« pullback.snd =
(pushout.inr : _ βΆ pushout f.op g.op).unop :=
(is_limit.cone_point_unique_up_to_iso_inv_comp _ _ _).trans (by simp)
@[simp, reassoc]
lemma pullback_iso_unop_pushout_hom_inl {X Y Z : C} (f : X βΆ Z)
(g : Y βΆ Z) [has_pullback f g] [has_pushout f.op g.op] :
pushout.inl β« (pullback_iso_unop_pushout f g).hom.op = pullback.fst.op :=
begin
apply quiver.hom.unop_inj,
dsimp,
rw [β pullback_iso_unop_pushout_inv_fst, iso.hom_inv_id_assoc],
end
@[simp, reassoc]
lemma pullback_iso_unop_pushout_hom_inr {X Y Z : C} (f : X βΆ Z)
(g : Y βΆ Z) [has_pullback f g] [has_pushout f.op g.op] :
pushout.inr β« (pullback_iso_unop_pushout f g).hom.op = pullback.snd.op :=
begin
apply quiver.hom.unop_inj,
dsimp,
rw [β pullback_iso_unop_pushout_inv_snd, iso.hom_inv_id_assoc],
end
end pullback
section pushout
/-- The pushout of `f` and `g` in `C` is isomorphic to the pullback of
`f.op` and `g.op` in `Cα΅α΅`. -/
noncomputable
def pushout_iso_unop_pullback {X Y Z : C} (f : X βΆ Z) (g : X βΆ Y)
[has_pushout f g] [has_pullback f.op g.op] : pushout f g β
unop (pullback f.op g.op) :=
is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _)
((pullback_cone.is_limit_equiv_is_colimit_unop _) (limit.is_limit (cospan f.op g.op)))
.
@[simp, reassoc]
lemma pushout_iso_unop_pullback_inl_hom {X Y Z : C} (f : X βΆ Z) (g : X βΆ Y)
[has_pushout f g] [has_pullback f.op g.op] :
pushout.inl β« (pushout_iso_unop_pullback f g).hom =
(pullback.fst : pullback f.op g.op βΆ _).unop :=
(is_colimit.comp_cocone_point_unique_up_to_iso_hom _ _ _).trans (by simp)
@[simp, reassoc]
lemma pushout_iso_unop_pullback_inr_hom {X Y Z : C} (f : X βΆ Z) (g : X βΆ Y)
[has_pushout f g] [has_pullback f.op g.op] :
pushout.inr β« (pushout_iso_unop_pullback f g).hom =
(pullback.snd : pullback f.op g.op βΆ _).unop :=
(is_colimit.comp_cocone_point_unique_up_to_iso_hom _ _ _).trans (by simp)
@[simp]
lemma pushout_iso_unop_pullback_inv_fst {X Y Z : C} (f : X βΆ Z) (g : X βΆ Y)
[has_pushout f g] [has_pullback f.op g.op] :
(pushout_iso_unop_pullback f g).inv.op β« pullback.fst = pushout.inl.op :=
begin
apply quiver.hom.unop_inj,
dsimp,
rw [β pushout_iso_unop_pullback_inl_hom, category.assoc, iso.hom_inv_id, category.comp_id],
end
@[simp]
lemma pushout_iso_unop_pullback_inv_snd {X Y Z : C} (f : X βΆ Z) (g : X βΆ Y)
[has_pushout f g] [has_pullback f.op g.op] :
(pushout_iso_unop_pullback f g).inv.op β« pullback.snd = pushout.inr.op :=
begin
apply quiver.hom.unop_inj,
dsimp,
rw [β pushout_iso_unop_pullback_inr_hom, category.assoc, iso.hom_inv_id, category.comp_id],
end
end pushout
end category_theory.limits
|
9873bf419662aa2df7dbbea95761cd6388afd0b5 | f0f12a5b81106a798deda31dca238c11997a605e | /Playlean4/Group/Subgroup.lean | 662b119b3a8cbb739962a8b6e99ea9e2ecf46999 | [
"MIT"
] | permissive | thejohncrafter/playlean4 | fe7119d492aab07048f78333eeda9862f6471740 | 81df180a71b8d84d0f45bc98db367aad203cf5df | refs/heads/master | 1,683,152,783,765 | 1,621,879,382,000 | 1,621,879,382,000 | 366,563,501 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,839 | lean |
import Playlean4.Group.Basic
namespace Group
section
variable (G : Type) (law : G β G β G) [grp : Group G law] (H : Set G)
local infixl:70 " * " => id' law
@[appUnexpander id'] def subgroup.unexpandMul : Lean.PrettyPrinter.Unexpander
| `(id' law G $x $y) => `($x * $y)
| _ => throw ()
local notation "one" => grp.one' -- HACK
local notation g"β»ΒΉ" => grp.inv g
class Subgroup where
oneMem : one β H
mulMem : β {g}, g β H β β {g'}, g' β H β g * g' β H
invMem : β {g}, g β H β (gβ»ΒΉ) β H
end
namespace Subgroup
variable {G : Type} (law : G β G β G) [grp : Group G law]
local infixl:70 " * " => id' law
@[appUnexpander id'] def unexpandGMul : Lean.PrettyPrinter.Unexpander
| `(id' Magma.law G $x $y) => `($x * $y)
| _ => throw ()
local notation "one" => grp.one' -- HACK
local notation g"β»ΒΉ" => grp.inv g
def subgroupLaw (H : Set G) [Subgroup G law H] : H β H β H :=
Ξ» g g' => β¨ (g : G) * (g' : G), mulMem g.2 g'.2 β©
instance GroupOfSubgroup (H : Set G) [Subgroup G law H] : Group H (subgroupLaw law H) where
one' := β¨ one, oneMem β©
assoc := Ξ» g g' g'' => Subtype.eq <| grp.assoc g.val g'.val g''.val
oneNeutralRight := Ξ» g => Subtype.eq <| grp.oneNeutralRight g.val
invertible := Ξ» g => β¨ β¨ (g.val)β»ΒΉ, invMem g.2 β©, Subtype.eq <| invCancelRight (g.val : G) β©
section -- "variable" doesn't work here for some reason
theorem lemmaβ {H : G β Prop}
(inhabited : β g : G, g β H)
(mulInvStable : β {g}, g β H β β {g'}, g' β H β g * g'β»ΒΉ β H) : one β H :=
match inhabited with
| β¨ g, h β© => invCancelRight g βΈ mulInvStable h h
theorem lemmaβ {H : G β Prop}
(inhabited : β g : G, g β H)
(mulInvStable : β {g}, g β H β β {g'}, g' β H β g * g'β»ΒΉ β H) :
β {g}, g β H β gβ»ΒΉ β H := Ξ» {g} hg =>
oneNeutralLeft (gβ»ΒΉ) βΈ mulInvStable (lemmaβ law inhabited mulInvStable) hg
theorem lemmaβ {H : G β Prop}
(inhabited : β g : G, g β H)
(mulInvStable : β {g : G}, g β H β β {g' : G}, g' β H β g * g'β»ΒΉ β H) :
β {g}, g β H β β {g'}, g' β H β g * g' β H := Ξ» {g} hg {g'} hg' =>
invInvolutive g' βΈ mulInvStable hg (lemmaβ law inhabited mulInvStable hg')
end
instance ofInhabitedMulInvStable {H : G β Prop}
(inhabited : β g : G, g β H)
(mulInvStable : β {g}, g β H β β {g'}, g' β H β g * g'β»ΒΉ β H) : Subgroup G law H where
oneMem := lemmaβ law inhabited mulInvStable
mulMem := lemmaβ law inhabited mulInvStable
invMem := lemmaβ law inhabited mulInvStable
variable (H : Set G) [sg : Subgroup G law H]
instance opIsSubgroup : Subgroup G (lawα΅α΅) H where
oneMem := sg.oneMem
mulMem := Ξ» {g} hg {g'} hg' => sg.mulMem hg' hg
invMem := sg.invMem
end Subgroup
end Group
|
5f46413c6d91317c694f3679ddc1b82d1f56969d | 6b5bcacd7d748a6e81562eac1e2e89819ea3b1d8 | /src/compiler.lean | d07b86a10e9d21961ccf663b2ff18b37aba51953 | [] | no_license | hermetique/compiler.lean | 7a481e289ee8315ecd3bcfd7d97ba817135b9692 | bdb80356d668d7a8a31e477ab7fd2d6d648af4f4 | refs/heads/main | 1,674,374,677,132 | 1,606,671,179,000 | 1,606,671,179,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,344 | lean | import tactic
namespace compiler
/- expressions are values and add-expressions -/
inductive Expr
| Val : β -> Expr
| Add : Expr -> Expr -> Expr
open Expr
/-- evaluate an expression directly -/
@[simp] def eval : Expr -> β
| (Val n) := n
| (Add a b) := eval a + eval b
/-
we'll compile our expressions to instructions of a stack machine
which supports push and add operations
-/
inductive Instr
| PUSH : β -> Instr
| ADD : Instr
open Instr
/-- compile an expression to an instruction list -/
@[simp] def compile : Expr -> list Instr
| (Val n) := [PUSH n]
| (Add a b) := compile a ++ compile b ++ [ADD]
/-- execute a list of instructions on a stack -/
@[simp] def exec : list Instr -> list β -> list β
| ((PUSH n) :: rest) s := exec rest (n :: s)
| (ADD :: rest) (a :: b :: s) := exec rest ((a + b) :: s)
| _ s := s
/-- compiled expressions only add to the stack when `exec`d -/
@[simp] lemma exec_compile_concat (e : Expr) : β instrs stack,
exec (compile e ++ instrs) stack = exec instrs (eval e :: stack) :=
begin
induction e with n a b iha ihb,
case Val {
intros,
simp,
},
case Add {
intros,
simp [iha, ihb, add_comm],
}
end
/-- exec (compile e) = eval e -/
theorem exec_compile_eq_eval (e : Expr) : exec (compile e) [] = [eval e] :=
by simpa using exec_compile_concat e [] []
end compiler
|
a143529973cf27221e3239074540119e0b538bae | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/bicategory/free.lean | 6b78babfdbf1cfbeb1616c1fb499a6ada23c0307 | [
"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,055 | lean | /-
Copyright (c) 2022 Yuma Mizuno. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yuma Mizuno
-/
import category_theory.bicategory.functor
/-!
# Free bicategories
We define the free bicategory over a quiver. In this bicategory, the 1-morphisms are freely
generated by the arrows in the quiver, and the 2-morphisms are freely generated by the formal
identities, the formal unitors, and the formal associators modulo the relation derived from the
axioms of a bicategory.
## Main definitions
* `free_bicategory B`: the free bicategory over a quiver `B`.
* `free_bicategory.lift F`: the pseudofunctor from `free_bicategory B` to `C` associated with a
prefunctor `F` from `B` to `C`.
-/
universes w wβ wβ v vβ vβ u uβ uβ
namespace category_theory
open category bicategory
open_locale bicategory
/-- Free bicategory over a quiver. Its objects are the same as those in the underlying quiver. -/
def free_bicategory (B : Type u) := B
instance (B : Type u) : Ξ [inhabited B], inhabited (free_bicategory B) := id
namespace free_bicategory
section
variables {B : Type u} [quiver.{v+1} B]
/-- 1-morphisms in the free bicategory. -/
inductive hom : B β B β Type (max u v)
| of {a b : B} (f : a βΆ b) : hom a b
| id (a : B) : hom a a
| comp {a b c : B} (f : hom a b) (g : hom b c) : hom a c
instance (a b : B) [inhabited (a βΆ b)] : inhabited (hom a b) := β¨hom.of defaultβ©
/-- Representatives of 2-morphisms in the free bicategory. -/
@[nolint has_inhabited_instance]
inductive homβ : Ξ {a b : B}, hom a b β hom a b β Type (max u v)
| id {a b} (f : hom a b) : homβ f f
| vcomp {a b} {f g h : hom a b} (Ξ· : homβ f g) (ΞΈ : homβ g h) : homβ f h
| whisker_left {a b c} (f : hom a b) {g h : hom b c} (Ξ· : homβ g h) : homβ (f.comp g) (f.comp h)
-- `Ξ·` cannot be earlier than `h` since it is a recursive argument.
| whisker_right {a b c} {f g : hom a b} (h : hom b c) (Ξ· : homβ f g) : homβ (f.comp h) (g.comp h)
| associator {a b c d} (f : hom a b) (g : hom b c) (h : hom c d) :
homβ ((f.comp g).comp h) (f.comp (g.comp h))
| associator_inv {a b c d} (f : hom a b) (g : hom b c) (h : hom c d) :
homβ (f.comp (g.comp h)) ((f.comp g).comp h)
| right_unitor {a b} (f : hom a b) : homβ (f.comp (hom.id b)) f
| right_unitor_inv {a b} (f : hom a b) : homβ f (f.comp (hom.id b))
| left_unitor {a b} (f : hom a b) : homβ ((hom.id a).comp f) f
| left_unitor_inv {a b} (f : hom a b) : homβ f ((hom.id a).comp f)
section
variables {B}
-- The following notations are only used in the definition of `rel` to simplify the notation.
local infixr ` β« ` := homβ.vcomp
local notation `π` := homβ.id
local notation f ` β ` Ξ· := homβ.whisker_left f Ξ·
local notation Ξ· ` β· ` h := homβ.whisker_right h Ξ·
local notation `Ξ±_` := homβ.associator
local notation `Ξ»_` := homβ.left_unitor
local notation `Ο_` := homβ.right_unitor
local notation `Ξ±β»ΒΉ_` := homβ.associator_inv
local notation `Ξ»β»ΒΉ_` := homβ.left_unitor_inv
local notation `Οβ»ΒΉ_` := homβ.right_unitor_inv
/-- Relations between 2-morphisms in the free bicategory. -/
inductive rel : Ξ {a b : B} {f g : hom a b}, homβ f g β homβ f g β Prop
| vcomp_right {a b} {f g h : hom a b} (Ξ· : homβ f g) (ΞΈβ ΞΈβ : homβ g h) :
rel ΞΈβ ΞΈβ β rel (Ξ· β« ΞΈβ) (Ξ· β« ΞΈβ)
| vcomp_left {a b} {f g h : hom a b} (Ξ·β Ξ·β : homβ f g) (ΞΈ : homβ g h) :
rel Ξ·β Ξ·β β rel (Ξ·β β« ΞΈ) (Ξ·β β« ΞΈ)
| id_comp {a b} {f g : hom a b} (Ξ· : homβ f g) :
rel (π f β« Ξ·) Ξ·
| comp_id {a b} {f g : hom a b} (Ξ· : homβ f g) :
rel (Ξ· β« π g) Ξ·
| assoc {a b} {f g h i : hom a b} (Ξ· : homβ f g) (ΞΈ : homβ g h) (ΞΉ : homβ h i) :
rel ((Ξ· β« ΞΈ) β« ΞΉ) (Ξ· β« (ΞΈ β« ΞΉ))
| whisker_left {a b c} (f : hom a b) (g h : hom b c) (Ξ· Ξ·' : homβ g h) :
rel Ξ· Ξ·' β rel (f β Ξ·) (f β Ξ·')
| whisker_left_id {a b c} (f : hom a b) (g : hom b c) :
rel (f β π g) (π (f.comp g))
| whisker_left_comp {a b c} (f : hom a b) {g h i : hom b c} (Ξ· : homβ g h) (ΞΈ : homβ h i) :
rel (f β (Ξ· β« ΞΈ)) (f β Ξ· β« f β ΞΈ)
| id_whisker_left {a b} {f g : hom a b} (Ξ· : homβ f g) :
rel (hom.id a β Ξ·) (Ξ»_ f β« Ξ· β« Ξ»β»ΒΉ_ g)
| comp_whisker_left
{a b c d} (f : hom a b) (g : hom b c) {h h' : hom c d} (Ξ· : homβ h h') :
rel ((f.comp g) β Ξ·) (Ξ±_ f g h β« f β g β Ξ· β« Ξ±β»ΒΉ_ f g h')
| whisker_right {a b c} (f g : hom a b) (h : hom b c) (Ξ· Ξ·' : homβ f g) :
rel Ξ· Ξ·' β rel (Ξ· β· h) (Ξ·' β· h)
| id_whisker_right {a b c} (f : hom a b) (g : hom b c) :
rel (π f β· g) (π (f.comp g))
| comp_whisker_right {a b c} {f g h : hom a b} (i : hom b c) (Ξ· : homβ f g) (ΞΈ : homβ g h) :
rel ((Ξ· β« ΞΈ) β· i) (Ξ· β· i β« ΞΈ β· i)
| whisker_right_id {a b} {f g : hom a b} (Ξ· : homβ f g) :
rel (Ξ· β· hom.id b) (Ο_ f β« Ξ· β« Οβ»ΒΉ_ g)
| whisker_right_comp
{a b c d} {f f' : hom a b} (g : hom b c) (h : hom c d) (Ξ· : homβ f f') :
rel (Ξ· β· (g.comp h)) (Ξ±β»ΒΉ_ f g h β« Ξ· β· g β· h β« Ξ±_ f' g h)
| whisker_assoc
{a b c d} (f : hom a b) {g g' : hom b c} (Ξ· : homβ g g') (h : hom c d) :
rel ((f β Ξ·) β· h) (Ξ±_ f g h β« f β (Ξ· β· h)β« Ξ±β»ΒΉ_ f g' h)
| whisker_exchange {a b c} {f g : hom a b} {h i : hom b c} (Ξ· : homβ f g) (ΞΈ : homβ h i) :
rel (f β ΞΈ β« Ξ· β· i) (Ξ· β· h β« g β ΞΈ)
| associator_hom_inv {a b c d} (f : hom a b) (g : hom b c) (h : hom c d) :
rel (Ξ±_ f g h β« Ξ±β»ΒΉ_ f g h) (π ((f.comp g).comp h))
| associator_inv_hom {a b c d} (f : hom a b) (g : hom b c) (h : hom c d) :
rel (Ξ±β»ΒΉ_ f g h β« Ξ±_ f g h) (π (f.comp (g.comp h)))
| left_unitor_hom_inv {a b} (f : hom a b) :
rel (Ξ»_ f β« Ξ»β»ΒΉ_ f) (π ((hom.id a).comp f))
| left_unitor_inv_hom {a b} (f : hom a b) :
rel (Ξ»β»ΒΉ_ f β« Ξ»_ f) (π f)
| right_unitor_hom_inv {a b} (f : hom a b) :
rel (Ο_ f β« Οβ»ΒΉ_ f) (π (f.comp (hom.id b)))
| right_unitor_inv_hom {a b} (f : hom a b) :
rel (Οβ»ΒΉ_ f β« Ο_ f) (π f)
| pentagon {a b c d e} (f : hom a b) (g : hom b c) (h : hom c d) (i : hom d e) :
rel (Ξ±_ f g h β· i β« Ξ±_ f (g.comp h) i β« f β Ξ±_ g h i)
(Ξ±_ (f.comp g) h i β« Ξ±_ f g (h.comp i))
| triangle {a b c} (f : hom a b) (g : hom b c) :
rel (Ξ±_ f (hom.id b) g β« f β Ξ»_ g) (Ο_ f β· g)
end
variables {B}
instance hom_category (a b : B) : category (hom a b) :=
{ hom := Ξ» f g, quot (@rel _ _ _ _ f g),
id := Ξ» f, quot.mk rel (homβ.id f),
comp := Ξ» f g h, quot.mapβ homβ.vcomp rel.vcomp_right rel.vcomp_left,
id_comp' := by { rintros f g β¨Ξ·β©, exact quot.sound (rel.id_comp Ξ·) },
comp_id' := by { rintros f g β¨Ξ·β©, exact quot.sound (rel.comp_id Ξ·) },
assoc' := by { rintros f g h i β¨Ξ·β© β¨ΞΈβ© β¨ΞΉβ©, exact quot.sound (rel.assoc Ξ· ΞΈ ΞΉ) } }
/-- Bicategory structure on the free bicategory. -/
instance bicategory : bicategory (free_bicategory B) :=
{ hom := Ξ» a b : B, hom a b,
id := hom.id,
comp := Ξ» a b c, hom.comp,
hom_category := free_bicategory.hom_category,
whisker_left := Ξ» a b c f g h Ξ·,
quot.map (homβ.whisker_left f) (rel.whisker_left f g h) Ξ·,
whisker_left_id' := Ξ» a b c f g, quot.sound (rel.whisker_left_id f g),
whisker_left_comp' := by
{ rintros a b c f g h i β¨Ξ·β© β¨ΞΈβ©, exact quot.sound (rel.whisker_left_comp f Ξ· ΞΈ) },
id_whisker_left' := by
{ rintros a b f g β¨Ξ·β©, exact quot.sound (rel.id_whisker_left Ξ·) },
comp_whisker_left' := by
{ rintros a b c d f g h h' β¨Ξ·β©, exact quot.sound (rel.comp_whisker_left f g Ξ·) },
whisker_right := Ξ» a b c f g Ξ· h,
quot.map (homβ.whisker_right h) (rel.whisker_right f g h) Ξ·,
id_whisker_right' := Ξ» a b c f g, quot.sound (rel.id_whisker_right f g),
comp_whisker_right' := by
{ rintros a b c f g h β¨Ξ·β© β¨ΞΈβ© i, exact quot.sound (rel.comp_whisker_right i Ξ· ΞΈ) },
whisker_right_id' := by
{ rintros a b f g β¨Ξ·β©, exact quot.sound (rel.whisker_right_id Ξ·) },
whisker_right_comp' := by
{ rintros a b c d f f' β¨Ξ·β© g h, exact quot.sound (rel.whisker_right_comp g h Ξ·) },
whisker_assoc' := by
{ rintros a b c d f g g' β¨Ξ·β© h, exact quot.sound (rel.whisker_assoc f Ξ· h) },
whisker_exchange' := by
{ rintros a b c f g h i β¨Ξ·β© β¨ΞΈβ©, exact quot.sound (rel.whisker_exchange Ξ· ΞΈ) },
associator := Ξ» a b c d f g h,
{ hom := quot.mk rel (homβ.associator f g h),
inv := quot.mk rel (homβ.associator_inv f g h),
hom_inv_id' := quot.sound (rel.associator_hom_inv f g h),
inv_hom_id' := quot.sound (rel.associator_inv_hom f g h) },
left_unitor := Ξ» a b f,
{ hom := quot.mk rel (homβ.left_unitor f),
inv := quot.mk rel (homβ.left_unitor_inv f),
hom_inv_id' := quot.sound (rel.left_unitor_hom_inv f),
inv_hom_id' := quot.sound (rel.left_unitor_inv_hom f) },
right_unitor := Ξ» a b f,
{ hom := quot.mk rel (homβ.right_unitor f),
inv := quot.mk rel (homβ.right_unitor_inv f),
hom_inv_id' := quot.sound (rel.right_unitor_hom_inv f),
inv_hom_id' := quot.sound (rel.right_unitor_inv_hom f) },
pentagon' := Ξ» a b c d e f g h i, quot.sound (rel.pentagon f g h i),
triangle' := Ξ» a b c f g, quot.sound (rel.triangle f g) }
variables {a b c d : free_bicategory B}
@[simp] lemma mk_vcomp {f g h : a βΆ b} (Ξ· : homβ f g) (ΞΈ : homβ g h) :
quot.mk rel (Ξ·.vcomp ΞΈ) = (quot.mk rel Ξ· β« quot.mk rel ΞΈ : f βΆ h) := rfl
@[simp] lemma mk_whisker_left (f : a βΆ b) {g h : b βΆ c} (Ξ· : homβ g h) :
quot.mk rel (homβ.whisker_left f Ξ·) = (f β quot.mk rel Ξ· : f β« g βΆ f β« h) := rfl
@[simp] lemma mk_whisker_right {f g : a βΆ b} (Ξ· : homβ f g) (h : b βΆ c) :
quot.mk rel (homβ.whisker_right h Ξ·) = (quot.mk rel Ξ· β· h : f β« h βΆ g β« h) := rfl
variables (f : a βΆ b) (g : b βΆ c) (h : c βΆ d)
lemma id_def : hom.id a = π a := rfl
lemma comp_def : hom.comp f g = f β« g := rfl
@[simp] lemma mk_id : quot.mk _ (homβ.id f) = π f := rfl
@[simp] lemma mk_associator_hom : quot.mk _ (homβ.associator f g h) = (Ξ±_ f g h).hom := rfl
@[simp] lemma mk_associator_inv : quot.mk _ (homβ.associator_inv f g h) = (Ξ±_ f g h).inv := rfl
@[simp] lemma mk_left_unitor_hom : quot.mk _ (homβ.left_unitor f) = (Ξ»_ f).hom := rfl
@[simp] lemma mk_left_unitor_inv : quot.mk _ (homβ.left_unitor_inv f) = (Ξ»_ f).inv := rfl
@[simp] lemma mk_right_unitor_hom : quot.mk _ (homβ.right_unitor f) = (Ο_ f).hom := rfl
@[simp] lemma mk_right_unitor_inv : quot.mk _ (homβ.right_unitor_inv f) = (Ο_ f).inv := rfl
/-- Canonical prefunctor from `B` to `free_bicategory B`. -/
@[simps]
def of : prefunctor B (free_bicategory B) :=
{ obj := id,
map := Ξ» a b, hom.of }
end
section
variables {B : Type uβ} [quiver.{vβ+1} B] {C : Type uβ} [category_struct.{vβ} C]
variables (F : prefunctor B C)
/-- Auxiliary definition for `lift`. -/
@[simp]
def lift_hom : β {a b : B}, hom a b β (F.obj a βΆ F.obj b)
| _ _ (hom.of f) := F.map f
| _ _ (hom.id a) := π (F.obj a)
| _ _ (hom.comp f g) := lift_hom f β« lift_hom g
@[simp] lemma lift_hom_id (a : free_bicategory B) : lift_hom F (π a) = π (F.obj a) := rfl
@[simp] lemma lift_hom_comp {a b c : free_bicategory B} (f : a βΆ b) (g : b βΆ c) :
lift_hom F (f β« g) = lift_hom F f β« lift_hom F g := rfl
end
section
variables {B : Type uβ} [quiver.{vβ+1} B] {C : Type uβ} [bicategory.{wβ vβ} C]
variables (F : prefunctor B C)
/-- Auxiliary definition for `lift`. -/
@[simp]
def lift_homβ : β {a b : B} {f g : hom a b}, homβ f g β (lift_hom F f βΆ lift_hom F g)
| _ _ _ _ (homβ.id _) := π _
| _ _ _ _ (homβ.associator _ _ _) := (Ξ±_ _ _ _).hom
| _ _ _ _ (homβ.associator_inv _ _ _) := (Ξ±_ _ _ _).inv
| _ _ _ _ (homβ.left_unitor _) := (Ξ»_ _).hom
| _ _ _ _ (homβ.left_unitor_inv _) := (Ξ»_ _).inv
| _ _ _ _ (homβ.right_unitor _) := (Ο_ _).hom
| _ _ _ _ (homβ.right_unitor_inv _) := (Ο_ _).inv
| _ _ _ _ (homβ.vcomp Ξ· ΞΈ) := lift_homβ Ξ· β« lift_homβ ΞΈ
| _ _ _ _ (homβ.whisker_left f Ξ·) := lift_hom F f β lift_homβ Ξ·
| _ _ _ _ (homβ.whisker_right h Ξ·) := lift_homβ Ξ· β· lift_hom F h
local attribute [simp] whisker_exchange
lemma lift_homβ_congr {a b : B} {f g : hom a b} {Ξ· ΞΈ : homβ f g} (H : rel Ξ· ΞΈ) :
lift_homβ F Ξ· = lift_homβ F ΞΈ :=
by induction H; tidy
/--
A prefunctor from a quiver `B` to a bicategory `C` can be lifted to a pseudofunctor from
`free_bicategory B` to `C`.
-/
@[simps]
def lift : pseudofunctor (free_bicategory B) C :=
{ obj := F.obj,
map := Ξ» a b, lift_hom F,
mapβ := Ξ» a b f g, quot.lift (lift_homβ F) (Ξ» Ξ· ΞΈ H, lift_homβ_congr F H),
map_id := Ξ» a, iso.refl _,
map_comp := Ξ» a b c f g, iso.refl _ }
end
end free_bicategory
end category_theory
|
5ccc99067fed0721d83638c044bacfbc6f0a4443 | 39ef80a23ca45a679ce3047fabd002248e3ee410 | /src/real-analysis/09_limits_final.lean | 8936bce5f605f610a3519cce7e400a450a1e67ae | [
"MIT"
] | permissive | sanjitdp/lean-projects | 5baa4d97f38b0d5af41e4960dc69ecc7c65a1e4c | 05b9a58e8bda3baebd4269536db39815a73cb123 | refs/heads/main | 1,690,059,014,811 | 1,630,696,075,000 | 1,630,696,075,000 | 399,831,128 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 7,196 | lean | import tuto_lib
set_option pp.beta true
set_option pp.coercions false
/-
This is the final file in the series. Here we use everything covered
in previous files to prove a couple of famous theorems from
elementary real analysis. Of course they all have more general versions
in mathlib.
As usual, keep in mind the following:
abs_le (x y : β) : |x| β€ y β -y β€ x β§ x β€ y
ge_max_iff (p q r) : r β₯ max p q β r β₯ p β§ r β₯ q
le_max_left p q : p β€ max p q
le_max_right p q : q β€ max p q
as well as a lemma from the previous file:
le_of_le_add_all : (β Ξ΅ > 0, y β€ x + Ξ΅) β y β€ x
Let's start with a variation on a known exercise.
-/
-- 0071
lemma le_lim {x y : β} {u : β β β} (hu : seq_limit u x)
(ineg : β N, β n β₯ N, y β€ u n) : y β€ x :=
begin
sorry
end
/-
Let's now return to the result proved in the `00_` file of this series,
and prove again the sequential characterization of upper bounds (with a slighly
different proof).
For this, and other exercises below, we'll need many things that we proved in previous files,
and a couple of extras.
From the 5th file:
limit_const (x : β) : seq_limit (Ξ» n, x) x
squeeze (lim_u : seq_limit u l) (lim_w : seq_limit w l)
(hu : β n, u n β€ v n) (hw : β n, v n β€ w n) : seq_limit v l
From the 8th:
def upper_bound (A : set β) (x : β) := β a β A, a β€ x
def is_sup (A : set β) (x : β) := upper_bound A x β§ β y, upper_bound A y β x β€ y
lt_sup (hx : is_sup A x) : β y, y < x β β a β A, y < a :=
You can also use:
nat.one_div_pos_of_nat {n : β} : 0 < 1 / (n + 1 : β)
inv_succ_le_all : β Ξ΅ > 0, β N : β, β n β₯ N, 1/(n + 1 : β) β€ Ξ΅
and their easy consequences:
limit_of_sub_le_inv_succ (h : β n, |u n - x| β€ 1/(n+1)) : seq_limit u x
limit_const_add_inv_succ (x : β) : seq_limit (Ξ» n, x + 1/(n+1)) x
limit_const_sub_inv_succ (x : β) : seq_limit (Ξ» n, x - 1/(n+1)) x
The structure of the proof is offered. It features a new tactic:
`choose` which invokes the axiom of choice (observing the tactic state before and
after using it should be enough to understand everything).
-/
-- 0072
lemma is_sup_iff (A : set β) (x : β) :
(is_sup A x) β (upper_bound A x β§ β u : β β β, seq_limit u x β§ β n, u n β A ) :=
begin
split,
{ intro h,
split,
{
sorry
},
{ have : β n : β, β a β A, x - 1/(n+1) < a,
{ intros n,
have : 1/(n+1 : β) > 0,
exact nat.one_div_pos_of_nat,
sorry
},
choose u hu using this,
sorry
} },
{ rintro β¨maj, u, limu, u_inβ©,
sorry
},
end
/-- Continuity of a function at a point -/
def continuous_at_pt (f : β β β) (xβ : β) : Prop :=
β Ξ΅ > 0, β Ξ΄ > 0, β x, |x - xβ| β€ Ξ΄ β |f x - f xβ| β€ Ξ΅
variables {f : β β β} {xβ : β} {u : β β β}
-- 0073
lemma seq_continuous_of_continuous (hf : continuous_at_pt f xβ)
(hu : seq_limit u xβ) : seq_limit (f β u) (f xβ) :=
begin
sorry
end
-- 0074
example :
(β u : β β β, seq_limit u xβ β seq_limit (f β u) (f xβ)) β
continuous_at_pt f xβ :=
begin
sorry
end
/-
Recall from the 6th file:
def extraction (Ο : β β β) := β n m, n < m β Ο n < Ο m
def cluster_point (u : β β β) (a : β) :=
β Ο, extraction Ο β§ seq_limit (u β Ο) a
id_le_extraction : extraction Ο β β n, n β€ Ο n
and from the 8th file:
def tendsto_infinity (u : β β β) := β A, β N, β n β₯ N, u n β₯ A
not_seq_limit_of_tendstoinfinity : tendsto_infinity u β β l, Β¬ seq_limit u l
-/
variables {Ο : β β β}
-- 0075
lemma subseq_tendstoinfinity
(h : tendsto_infinity u) (hΟ : extraction Ο) :
tendsto_infinity (u β Ο) :=
begin
sorry
end
-- 0076
lemma squeeze_infinity {u v : β β β} (hu : tendsto_infinity u)
(huv : β n, u n β€ v n) : tendsto_infinity v :=
begin
sorry
end
/-
We will use segments: Icc a b := { x | a β€ x β§ x β€ b }
The notation stands for Interval-closed-closed. Variations exist with
o or i instead of c, where o stands for open and i for infinity.
We will use the following version of Bolzano-Weierstrass
bolzano_weierstrass (h : β n, u n β [a, b]) :
β c β [a, b], cluster_point u c
as well as the obvious
seq_limit_id : tendsto_infinity (Ξ» n, n)
-/
open set
-- 0077
lemma bdd_above_segment {f : β β β} {a b : β} (hf : β x β Icc a b, continuous_at_pt f x) :
β M, β x β Icc a b, f x β€ M :=
begin
sorry
end
/-
In the next exercise, we can use:
abs_neg x : |-x| = |x|
-/
-- 0078
lemma continuous_opposite {f : β β β} {xβ : β} (h : continuous_at_pt f xβ) :
continuous_at_pt (Ξ» x, -f x) xβ :=
begin
sorry
end
/-
Now let's combine the two exercises above
-/
-- 0079
lemma bdd_below_segment {f : β β β} {a b : β} (hf : β x β Icc a b, continuous_at_pt f x) :
β m, β x β Icc a b, m β€ f x :=
begin
sorry
end
/-
Remember from the 5th file:
unique_limit : seq_limit u l β seq_limit u l' β l = l'
and from the 6th one:
subseq_tendsto_of_tendsto (h : seq_limit u l) (hΟ : extraction Ο) :
seq_limit (u β Ο) l
We now admit the following version of the least upper bound theorem
(that cannot be proved without discussing the construction of real numbers
or admitting another strong theorem).
sup_segment {a b : β} {A : set β} (hnonvide : β x, x β A) (h : A β Icc a b) :
β x β Icc a b, is_sup A x
In the next exercise, it can be useful to prove inclusions of sets of real number.
By definition, A β B means : β x, x β A β x β B.
Hence one can start a proof of A β B by `intros x x_in`,
which brings `x : β` and `x_in : x β A` in the local context,
and then prove `x β B`.
Note also the use of
{x | P x}
which denotes the set of x satisfying predicate P.
Hence `x' β { x | P x} β P x'`, by definition.
-/
-- 0080
example {a b : β} (hab : a β€ b) (hf : β x β Icc a b, continuous_at_pt f x) :
β xβ β Icc a b, β x β Icc a b, f x β€ f xβ :=
begin
sorry
end
lemma stupid {a b x : β} (h : x β Icc a b) (h' : x β b) : x < b :=
lt_of_le_of_ne h.right h'
/-
And now the final boss...
-/
def I := (Icc 0 1 : set β) -- the type ascription makes sure 0 and 1 are real numbers here
-- 0081
example (f : β β β) (hf : β x, continuous_at_pt f x) (hβ : f 0 < 0) (hβ : f 1 > 0) :
β xβ β I, f xβ = 0 :=
begin
let A := { x | x β I β§ f x < 0},
have ex_xβ : β xβ β I, is_sup A xβ,
{
sorry
},
rcases ex_xβ with β¨xβ, xβ_in, xβ_supβ©,
use [xβ, xβ_in],
have : f xβ β€ 0,
{
sorry
},
have xβ_1: xβ < 1,
{
sorry
},
have : f xβ β₯ 0,
{ have in_I : β N : β, β n β₯ N, xβ + 1/(n+1) β I,
{ have : β N : β, β nβ₯ N, 1/(n+1 : β) β€ 1-xβ,
{
sorry
},
sorry
},
have not_in : β n : β, xβ + 1/(n+1) β A,
-- By definition, x β A means Β¬ (x β A).
{
sorry
},
dsimp [A] at not_in,
sorry
},
linarith,
end
|
03737caffc772f5212a7cc50353074a0e1f05dc9 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/analysis/calculus/darboux.lean | 6a63b6fe8e464df0358fa898ab2feaa9955bcd80 | [
"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,668 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.calculus.mean_value
/-!
# Darboux's theorem
In this file we prove that the derivative of a differentiable function on an interval takes all
intermediate values. The proof is based on the
[Wikipedia](https://en.wikipedia.org/wiki/Darboux%27s_theorem_(analysis)) page about this theorem.
-/
open filter set
open_locale topological_space classical
variables {a b : β} {f f' : β β β}
/-- Darboux's theorem: if `a β€ b` and `f' a < m < f' b`, then `f' c = m` for some `c β [a, b]`. -/
theorem exists_has_deriv_within_at_eq_of_gt_of_lt
(hab : a β€ b) (hf : β x β (Icc a b), has_deriv_within_at f (f' x) (Icc a b) x)
{m : β} (hma : f' a < m) (hmb : m < f' b) :
m β f' '' (Icc a b) :=
begin
have hab' : a < b,
{ refine lt_of_le_of_ne hab (Ξ» hab', _),
subst b,
exact lt_asymm hma hmb },
set g : β β β := Ξ» x, f x - m * x,
have hg : β x β Icc a b, has_deriv_within_at g (f' x - m) (Icc a b) x,
{ intros x hx,
simpa using (hf x hx).sub ((has_deriv_within_at_id x _).const_mul m) },
obtain β¨c, cmem, hcβ© : β c β Icc a b, is_min_on g (Icc a b) c,
from compact_Icc.exists_forall_le (nonempty_Icc.2 $ hab)
(Ξ» x hx, (hg x hx).continuous_within_at),
have cmem' : c β Ioo a b,
{ cases eq_or_lt_of_le cmem.1 with hac hac,
-- Show that `c` can't be equal to `a`
{ subst c,
refine absurd (sub_nonneg.1 $ nonneg_of_mul_nonneg_left _ (sub_pos.2 hab'))
(not_le_of_lt hma),
have : b - a β pos_tangent_cone_at (Icc a b) a,
from mem_pos_tangent_cone_at_of_segment_subset (segment_eq_Icc hab βΈ subset.refl _),
simpa using hc.localize.has_fderiv_within_at_nonneg (hg a (left_mem_Icc.2 hab)) this },
cases eq_or_lt_of_le cmem.2 with hbc hbc,
-- Show that `c` can't be equal to `a`
{ subst c,
refine absurd (sub_nonpos.1 $ nonpos_of_mul_nonneg_right _ (sub_lt_zero.2 hab'))
(not_le_of_lt hmb),
have : a - b β pos_tangent_cone_at (Icc a b) b,
from mem_pos_tangent_cone_at_of_segment_subset (by rw [segment_symm, segment_eq_Icc hab]),
simpa using hc.localize.has_fderiv_within_at_nonneg (hg b (right_mem_Icc.2 hab)) this },
exact β¨hac, hbcβ© },
use [c, cmem],
rw [β sub_eq_zero],
have : Icc a b β π c, by rwa [β mem_interior_iff_mem_nhds, interior_Icc],
exact (hc.is_local_min this).has_deriv_at_eq_zero ((hg c cmem).has_deriv_at this)
end
/-- Darboux's theorem: if `a β€ b` and `f' a > m > f' b`, then `f' c = m` for some `c β [a, b]`. -/
theorem exists_has_deriv_within_at_eq_of_lt_of_gt
(hab : a β€ b) (hf : β x β (Icc a b), has_deriv_within_at f (f' x) (Icc a b) x)
{m : β} (hma : m < f' a) (hmb : f' b < m) :
m β f' '' (Icc a b) :=
let β¨c, cmem, hcβ© := exists_has_deriv_within_at_eq_of_gt_of_lt hab (Ξ» x hx, (hf x hx).neg)
(neg_lt_neg hma) (neg_lt_neg hmb)
in β¨c, cmem, neg_inj hcβ©
/-- Darboux's theorem: the image of a convex set under `f'` is a convex set. -/
theorem convex_image_has_deriv_at {s : set β} (hs : convex s)
(hf : β x β s, has_deriv_at f (f' x) x) :
convex (f' '' s) :=
begin
refine convex_real_iff.2 _,
rintros _ _ β¨a, ha, rflβ© β¨b, hb, rflβ© m β¨hma, hmbβ©,
cases eq_or_lt_of_le hma with hma hma,
by exact hma βΈ mem_image_of_mem f' ha,
cases eq_or_lt_of_le hmb with hmb hmb,
by exact hmb.symm βΈ mem_image_of_mem f' hb,
cases le_total a b with hab hab,
{ have : Icc a b β s, from convex_real_iff.1 hs ha hb,
rcases exists_has_deriv_within_at_eq_of_gt_of_lt hab
(Ξ» x hx, (hf x $ this hx).has_deriv_within_at) hma hmb
with β¨c, cmem, hcβ©,
exact β¨c, this cmem, hcβ© },
{ have : Icc b a β s, from convex_real_iff.1 hs hb ha,
rcases exists_has_deriv_within_at_eq_of_lt_of_gt hab
(Ξ» x hx, (hf x $ this hx).has_deriv_within_at) hmb hma
with β¨c, cmem, hcβ©,
exact β¨c, this cmem, hcβ© }
end
/-- If the derivative of a function is never equal to `m`, then either
it is always greater than `m`, or it is always less than `m`. -/
theorem deriv_forall_lt_or_forall_gt_of_forall_ne {s : set β} (hs : convex s)
(hf : β x β s, has_deriv_at f (f' x) x) {m : β} (hf' : β x β s, f' x β m) :
(β x β s, f' x < m) β¨ (β x β s, m < f' x) :=
begin
contrapose! hf',
rcases hf' with β¨β¨b, hb, hmbβ©, β¨a, ha, hmaβ©β©,
exact convex_real_iff.1 (convex_image_has_deriv_at hs hf) (mem_image_of_mem f' ha)
(mem_image_of_mem f' hb) β¨hma, hmbβ©
end
|
b2623bfe11b1ca750730c5cc53dbd2c06082c7d2 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/locally_convex/with_seminorms.lean | 12bef187ce7d9c200c182424bc68f4f5c631667a | [
"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 | 19,142 | lean | /-
Copyright (c) 2022 Moritz Doll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Moritz Doll, Anatole Dedecker
-/
import analysis.seminorm
import analysis.locally_convex.bounded
/-!
# Topology induced by a family of seminorms
## Main definitions
* `seminorm_family.basis_sets`: The set of open seminorm balls for a family of seminorms.
* `seminorm_family.module_filter_basis`: A module filter basis formed by the open balls.
* `seminorm.is_bounded`: A linear map `f : E ββ[π] F` is bounded iff every seminorm in `F` can be
bounded by a finite number of seminorms in `E`.
## Main statements
* `continuous_from_bounded`: A bounded linear map `f : E ββ[π] F` is continuous.
* `seminorm_family.to_locally_convex_space`: A space equipped with a family of seminorms is locally
convex.
## TODO
Show that for any locally convex space there exist seminorms that induce the topology.
## Tags
seminorm, locally convex
-/
open normed_field set seminorm
open_locale big_operators nnreal pointwise topological_space
variables {π E F G ΞΉ ΞΉ' : Type*}
section filter_basis
variables [normed_field π] [add_comm_group E] [module π E]
variables (π E ΞΉ)
/-- An abbreviation for indexed families of seminorms. This is mainly to allow for dot-notation. -/
abbreviation seminorm_family := ΞΉ β seminorm π E
variables {π E ΞΉ}
namespace seminorm_family
/-- The sets of a filter basis for the neighborhood filter of 0. -/
def basis_sets (p : seminorm_family π E ΞΉ) : set (set E) :=
β (s : finset ΞΉ) r (hr : 0 < r), singleton $ ball (s.sup p) (0 : E) r
variables (p : seminorm_family π E ΞΉ)
lemma basis_sets_iff {U : set E} :
U β p.basis_sets β β (i : finset ΞΉ) r (hr : 0 < r), U = ball (i.sup p) 0 r :=
by simp only [basis_sets, mem_Union, mem_singleton_iff]
lemma basis_sets_mem (i : finset ΞΉ) {r : β} (hr : 0 < r) :
(i.sup p).ball 0 r β p.basis_sets :=
(basis_sets_iff _).mpr β¨i,_,hr,rflβ©
lemma basis_sets_singleton_mem (i : ΞΉ) {r : β} (hr : 0 < r) :
(p i).ball 0 r β p.basis_sets :=
(basis_sets_iff _).mpr β¨{i},_,hr, by rw finset.sup_singletonβ©
lemma basis_sets_nonempty [nonempty ΞΉ] : p.basis_sets.nonempty :=
begin
let i := classical.arbitrary ΞΉ,
refine set.nonempty_def.mpr β¨(p i).ball 0 1, _β©,
exact p.basis_sets_singleton_mem i zero_lt_one,
end
lemma basis_sets_intersect
(U V : set E) (hU : U β p.basis_sets) (hV : V β p.basis_sets) :
β (z : set E) (H : z β p.basis_sets), z β U β© V :=
begin
classical,
rcases p.basis_sets_iff.mp hU with β¨s, rβ, hrβ, hUβ©,
rcases p.basis_sets_iff.mp hV with β¨t, rβ, hrβ, hVβ©,
use ((s βͺ t).sup p).ball 0 (min rβ rβ),
refine β¨p.basis_sets_mem (s βͺ t) (lt_min_iff.mpr β¨hrβ, hrββ©), _β©,
rw [hU, hV, ball_finset_sup_eq_Inter _ _ _ (lt_min_iff.mpr β¨hrβ, hrββ©),
ball_finset_sup_eq_Inter _ _ _ hrβ, ball_finset_sup_eq_Inter _ _ _ hrβ],
exact set.subset_inter
(set.Interβ_mono' $ Ξ» i hi, β¨i, finset.subset_union_left _ _ hi, ball_mono $ min_le_left _ _β©)
(set.Interβ_mono' $ Ξ» i hi, β¨i, finset.subset_union_right _ _ hi, ball_mono $
min_le_right _ _β©),
end
lemma basis_sets_zero (U) (hU : U β p.basis_sets) :
(0 : E) β U :=
begin
rcases p.basis_sets_iff.mp hU with β¨ΞΉ', r, hr, hUβ©,
rw [hU, mem_ball_zero, (ΞΉ'.sup p).zero],
exact hr,
end
lemma basis_sets_add (U) (hU : U β p.basis_sets) :
β (V : set E) (H : V β p.basis_sets), V + V β U :=
begin
rcases p.basis_sets_iff.mp hU with β¨s, r, hr, hUβ©,
use (s.sup p).ball 0 (r/2),
refine β¨p.basis_sets_mem s (div_pos hr zero_lt_two), _β©,
refine set.subset.trans (ball_add_ball_subset (s.sup p) (r/2) (r/2) 0 0) _,
rw [hU, add_zero, add_halves'],
end
lemma basis_sets_neg (U) (hU' : U β p.basis_sets) :
β (V : set E) (H : V β p.basis_sets), V β (Ξ» (x : E), -x) β»ΒΉ' U :=
begin
rcases p.basis_sets_iff.mp hU' with β¨s, r, hr, hUβ©,
rw [hU, neg_preimage, neg_ball (s.sup p), neg_zero],
exact β¨U, hU', eq.subset hUβ©,
end
/-- The `add_group_filter_basis` induced by the filter basis `seminorm_basis_zero`. -/
protected def add_group_filter_basis [nonempty ΞΉ] : add_group_filter_basis E :=
add_group_filter_basis_of_comm p.basis_sets p.basis_sets_nonempty
p.basis_sets_intersect p.basis_sets_zero p.basis_sets_add p.basis_sets_neg
lemma basis_sets_smul_right (v : E) (U : set E)
(hU : U β p.basis_sets) : βαΆ (x : π) in π 0, x β’ v β U :=
begin
rcases p.basis_sets_iff.mp hU with β¨s, r, hr, hUβ©,
rw [hU, filter.eventually_iff],
simp_rw [(s.sup p).mem_ball_zero, (s.sup p).smul],
by_cases h : 0 < (s.sup p) v,
{ simp_rw (lt_div_iff h).symm,
rw β_root_.ball_zero_eq,
exact metric.ball_mem_nhds 0 (div_pos hr h) },
simp_rw [le_antisymm (not_lt.mp h) ((s.sup p).nonneg v), mul_zero, hr],
exact is_open.mem_nhds is_open_univ (mem_univ 0),
end
variables [nonempty ΞΉ]
lemma basis_sets_smul (U) (hU : U β p.basis_sets) :
β (V : set π) (H : V β π (0 : π)) (W : set E)
(H : W β p.add_group_filter_basis.sets), V β’ W β U :=
begin
rcases p.basis_sets_iff.mp hU with β¨s, r, hr, hUβ©,
refine β¨metric.ball 0 r.sqrt, metric.ball_mem_nhds 0 (real.sqrt_pos.mpr hr), _β©,
refine β¨(s.sup p).ball 0 r.sqrt, p.basis_sets_mem s (real.sqrt_pos.mpr hr), _β©,
refine set.subset.trans (ball_smul_ball (s.sup p) r.sqrt r.sqrt) _,
rw [hU, real.mul_self_sqrt (le_of_lt hr)],
end
lemma basis_sets_smul_left (x : π) (U : set E)
(hU : U β p.basis_sets) : β (V : set E)
(H : V β p.add_group_filter_basis.sets), V β (Ξ» (y : E), x β’ y) β»ΒΉ' U :=
begin
rcases p.basis_sets_iff.mp hU with β¨s, r, hr, hUβ©,
rw hU,
by_cases h : x β 0,
{ rw [(s.sup p).smul_ball_preimage 0 r x h, smul_zero],
use (s.sup p).ball 0 (r / β₯xβ₯),
exact β¨p.basis_sets_mem s (div_pos hr (norm_pos_iff.mpr h)), subset.rflβ© },
refine β¨(s.sup p).ball 0 r, p.basis_sets_mem s hr, _β©,
simp only [not_ne_iff.mp h, subset_def, mem_ball_zero, hr, mem_univ, seminorm.zero,
implies_true_iff, preimage_const_of_mem, zero_smul],
end
/-- The `module_filter_basis` induced by the filter basis `seminorm_basis_zero`. -/
protected def module_filter_basis : module_filter_basis π E :=
{ to_add_group_filter_basis := p.add_group_filter_basis,
smul' := p.basis_sets_smul,
smul_left' := p.basis_sets_smul_left,
smul_right' := p.basis_sets_smul_right }
lemma filter_eq_infi (p : seminorm_family π E ΞΉ) :
p.module_filter_basis.to_filter_basis.filter = β¨
i, (π 0).comap (p i) :=
begin
refine le_antisymm (le_infi $ Ξ» i, _) _,
{ rw p.module_filter_basis.to_filter_basis.has_basis.le_basis_iff
(metric.nhds_basis_ball.comap _),
intros Ξ΅ hΞ΅,
refine β¨(p i).ball 0 Ξ΅, _, _β©,
{ rw β (finset.sup_singleton : _ = p i),
exact p.basis_sets_mem {i} hΞ΅, },
{ rw [id, (p i).ball_zero_eq_preimage_ball] } },
{ rw p.module_filter_basis.to_filter_basis.has_basis.ge_iff,
rintros U (hU : U β p.basis_sets),
rcases p.basis_sets_iff.mp hU with β¨s, r, hr, rflβ©,
rw [id, seminorm.ball_finset_sup_eq_Inter _ _ _ hr, s.Inter_mem_sets],
exact Ξ» i hi, filter.mem_infi_of_mem i β¨metric.ball 0 r, metric.ball_mem_nhds 0 hr,
eq.subset ((p i).ball_zero_eq_preimage_ball).symmβ©, },
end
end seminorm_family
end filter_basis
section bounded
namespace seminorm
variables [normed_field π] [add_comm_group E] [module π E] [add_comm_group F] [module π F]
-- Todo: This should be phrased entirely in terms of the von Neumann bornology.
/-- The proposition that a linear map is bounded between spaces with families of seminorms. -/
def is_bounded (p : ΞΉ β seminorm π E) (q : ΞΉ' β seminorm π F) (f : E ββ[π] F) : Prop :=
β i, β s : finset ΞΉ, β C : ββ₯0, C β 0 β§ (q i).comp f β€ C β’ s.sup p
lemma is_bounded_const (ΞΉ' : Type*) [nonempty ΞΉ']
{p : ΞΉ β seminorm π E} {q : seminorm π F} (f : E ββ[π] F) :
is_bounded p (Ξ» _ : ΞΉ', q) f β β (s : finset ΞΉ) C : ββ₯0, C β 0 β§ q.comp f β€ C β’ s.sup p :=
by simp only [is_bounded, forall_const]
lemma const_is_bounded (ΞΉ : Type*) [nonempty ΞΉ]
{p : seminorm π E} {q : ΞΉ' β seminorm π F} (f : E ββ[π] F) :
is_bounded (Ξ» _ : ΞΉ, p) q f β β i, β C : ββ₯0, C β 0 β§ (q i).comp f β€ C β’ p :=
begin
split; intros h i,
{ rcases h i with β¨s, C, hC, hβ©,
exact β¨C, hC, le_trans h (smul_le_smul (finset.sup_le (Ξ» _ _, le_rfl)) le_rfl)β© },
use [{classical.arbitrary ΞΉ}],
simp only [h, finset.sup_singleton],
end
lemma is_bounded_sup {p : ΞΉ β seminorm π E} {q : ΞΉ' β seminorm π F}
{f : E ββ[π] F} (hf : is_bounded p q f) (s' : finset ΞΉ') :
β (C : ββ₯0) (s : finset ΞΉ), 0 < C β§ (s'.sup q).comp f β€ C β’ (s.sup p) :=
begin
classical,
by_cases hs' : Β¬s'.nonempty,
{ refine β¨1, β
, zero_lt_one, _β©,
rw [finset.not_nonempty_iff_eq_empty.mp hs', finset.sup_empty, seminorm.bot_eq_zero, zero_comp],
exact seminorm.nonneg _ },
rw not_not at hs',
choose fβ fC hf using hf,
use [s'.card β’ s'.sup fC, finset.bUnion s' fβ],
split,
{ refine nsmul_pos _ (ne_of_gt (finset.nonempty.card_pos hs')),
cases finset.nonempty.bex hs' with j hj,
exact lt_of_lt_of_le (zero_lt_iff.mpr (and.elim_left (hf j))) (finset.le_sup hj) },
have hs : β i : ΞΉ', i β s' β (q i).comp f β€ s'.sup fC β’ ((finset.bUnion s' fβ).sup p) :=
begin
intros i hi,
refine le_trans (and.elim_right (hf i)) (smul_le_smul _ (finset.le_sup hi)),
exact finset.sup_mono (finset.subset_bUnion_of_mem fβ hi),
end,
refine le_trans (comp_mono f (finset_sup_le_sum q s')) _,
simp_rw [βpullback_apply, add_monoid_hom.map_sum, pullback_apply],
refine le_trans (finset.sum_le_sum hs) _,
rw [finset.sum_const, smul_assoc],
exact le_rfl,
end
end seminorm
end bounded
section topology
variables [normed_field π] [add_comm_group E] [module π E] [nonempty ΞΉ]
/-- The proposition that the topology of `E` is induced by a family of seminorms `p`. -/
class with_seminorms (p : seminorm_family π E ΞΉ) [t : topological_space E] : Prop :=
(topology_eq_with_seminorms : t = p.module_filter_basis.topology)
lemma seminorm_family.with_seminorms_eq (p : seminorm_family π E ΞΉ) [t : topological_space E]
[with_seminorms p] : t = p.module_filter_basis.topology :=
with_seminorms.topology_eq_with_seminorms
variables [topological_space E]
variables (p : seminorm_family π E ΞΉ) [with_seminorms p]
lemma seminorm_family.has_basis : (π (0 : E)).has_basis
(Ξ» (s : set E), s β p.basis_sets) id :=
begin
rw (congr_fun (congr_arg (@nhds E) p.with_seminorms_eq) 0),
exact add_group_filter_basis.nhds_zero_has_basis _,
end
end topology
section topological_add_group
variables [normed_field π] [add_comm_group E] [module π E]
variables [topological_space E] [topological_add_group E]
variables [nonempty ΞΉ]
lemma seminorm_family.with_seminorms_of_nhds (p : seminorm_family π E ΞΉ)
(h : π (0 : E) = p.module_filter_basis.to_filter_basis.filter) :
with_seminorms p :=
begin
refine β¨topological_add_group.ext (by apply_instance)
(p.add_group_filter_basis.is_topological_add_group) _β©,
rw add_group_filter_basis.nhds_zero_eq,
exact h,
end
lemma seminorm_family.with_seminorms_of_has_basis (p : seminorm_family π E ΞΉ)
(h : (π (0 : E)).has_basis (Ξ» (s : set E), s β p.basis_sets) id) :
with_seminorms p :=
p.with_seminorms_of_nhds $ filter.has_basis.eq_of_same_basis h
p.add_group_filter_basis.to_filter_basis.has_basis
lemma seminorm_family.with_seminorms_iff_nhds_eq_infi (p : seminorm_family π E ΞΉ) :
with_seminorms p β (π 0 : filter E) = β¨
i, (π 0).comap (p i) :=
begin
rw β p.filter_eq_infi,
refine β¨Ξ» h, _, p.with_seminorms_of_nhdsβ©,
rw h.topology_eq_with_seminorms,
exact add_group_filter_basis.nhds_zero_eq _,
end
end topological_add_group
section normed_space
/-- The topology of a `normed_space π E` is induced by the seminorm `norm_seminorm π E`. -/
instance norm_with_seminorms (π E) [normed_field π] [semi_normed_group E] [normed_space π E] :
with_seminorms (Ξ» (_ : fin 1), norm_seminorm π E) :=
begin
let p : seminorm_family π E (fin 1) := Ξ» _, norm_seminorm π E,
refine β¨topological_add_group.ext normed_top_group
(p.add_group_filter_basis.is_topological_add_group) _β©,
refine filter.has_basis.eq_of_same_basis metric.nhds_basis_ball _,
rw βball_norm_seminorm π E,
refine filter.has_basis.to_has_basis p.add_group_filter_basis.nhds_zero_has_basis _
(Ξ» r hr, β¨(norm_seminorm π E).ball 0 r, p.basis_sets_singleton_mem 0 hr, rfl.subsetβ©),
rintros U (hU : U β p.basis_sets),
rcases p.basis_sets_iff.mp hU with β¨s, r, hr, hUβ©,
use [r, hr],
rw [hU, id.def],
by_cases h : s.nonempty,
{ rw finset.sup_const h },
rw [finset.not_nonempty_iff_eq_empty.mp h, finset.sup_empty, ball_bot _ hr],
exact set.subset_univ _,
end
end normed_space
section nondiscrete_normed_field
variables [nondiscrete_normed_field π] [add_comm_group E] [module π E] [nonempty ΞΉ]
variables (p : seminorm_family π E ΞΉ)
variables [topological_space E] [with_seminorms p]
lemma bornology.is_vonN_bounded_iff_finset_seminorm_bounded {s : set E} :
bornology.is_vonN_bounded π s β β I : finset ΞΉ, β r (hr : 0 < r), β (x β s), I.sup p x < r :=
begin
rw (p.has_basis).is_vonN_bounded_basis_iff,
split,
{ intros h I,
simp only [id.def] at h,
specialize h ((I.sup p).ball 0 1) (p.basis_sets_mem I zero_lt_one),
rcases h with β¨r, hr, hβ©,
cases normed_field.exists_lt_norm π r with a ha,
specialize h a (le_of_lt ha),
rw [seminorm.smul_ball_zero (lt_trans hr ha), mul_one] at h,
refine β¨β₯aβ₯, lt_trans hr ha, _β©,
intros x hx,
specialize h hx,
exact (finset.sup I p).mem_ball_zero.mp h },
intros h s' hs',
rcases p.basis_sets_iff.mp hs' with β¨I, r, hr, hs'β©,
rw [id.def, hs'],
rcases h I with β¨r', hr', h'β©,
simp_rw β(I.sup p).mem_ball_zero at h',
refine absorbs.mono_right _ h',
exact (finset.sup I p).ball_zero_absorbs_ball_zero hr,
end
lemma bornology.is_vonN_bounded_iff_seminorm_bounded {s : set E} :
bornology.is_vonN_bounded π s β β i : ΞΉ, β r (hr : 0 < r), β (x β s), p i x < r :=
begin
rw bornology.is_vonN_bounded_iff_finset_seminorm_bounded p,
split,
{ intros hI i,
convert hI {i},
rw [finset.sup_singleton] },
intros hi I,
by_cases hI : I.nonempty,
{ choose r hr h using hi,
have h' : 0 < I.sup' hI r :=
by { rcases hI.bex with β¨i, hiβ©, exact lt_of_lt_of_le (hr i) (finset.le_sup' r hi) },
refine β¨I.sup' hI r, h', Ξ» x hx, finset_sup_apply_lt h' (Ξ» i hi, _)β©,
refine lt_of_lt_of_le (h i x hx) _,
simp only [finset.le_sup'_iff, exists_prop],
exact β¨i, hi, (eq.refl _).leβ© },
simp only [finset.not_nonempty_iff_eq_empty.mp hI, finset.sup_empty, coe_bot, pi.zero_apply,
exists_prop],
exact β¨1, zero_lt_one, Ξ» _ _, zero_lt_oneβ©,
end
end nondiscrete_normed_field
section continuous_bounded
namespace seminorm
variables [normed_field π] [add_comm_group E] [module π E] [add_comm_group F] [module π F]
variables [nonempty ΞΉ] [nonempty ΞΉ']
lemma continuous_from_bounded (p : seminorm_family π E ΞΉ) (q : seminorm_family π F ΞΉ')
[uniform_space E] [uniform_add_group E] [with_seminorms p]
[uniform_space F] [uniform_add_group F] [with_seminorms q]
(f : E ββ[π] F) (hf : seminorm.is_bounded p q f) : continuous f :=
begin
refine uniform_continuous.continuous _,
refine add_monoid_hom.uniform_continuous_of_continuous_at_zero f.to_add_monoid_hom _,
rw [f.to_add_monoid_hom_coe, continuous_at_def, f.map_zero, p.with_seminorms_eq],
intros U hU,
rw [q.with_seminorms_eq, add_group_filter_basis.nhds_zero_eq, filter_basis.mem_filter_iff] at hU,
rcases hU with β¨V, hV : V β q.basis_sets, hUβ©,
rcases q.basis_sets_iff.mp hV with β¨sβ, r, hr, hVβ©,
rw hV at hU,
rw [p.add_group_filter_basis.nhds_zero_eq, filter_basis.mem_filter_iff],
rcases (seminorm.is_bounded_sup hf sβ) with β¨C, sβ, hC, hfβ©,
refine β¨(sβ.sup p).ball 0 (r/C), p.basis_sets_mem _ (div_pos hr (nnreal.coe_pos.mpr hC)), _β©,
refine subset.trans _ (preimage_mono hU),
simp_rw [βlinear_map.map_zero f, βball_comp],
refine subset.trans _ (ball_antitone hf),
rw ball_smul (sβ.sup p) hC,
end
lemma cont_with_seminorms_normed_space (F) [semi_normed_group F] [normed_space π F]
[uniform_space E] [uniform_add_group E]
(p : ΞΉ β seminorm π E) [with_seminorms p] (f : E ββ[π] F)
(hf : β (s : finset ΞΉ) C : ββ₯0, C β 0 β§ (norm_seminorm π F).comp f β€ C β’ s.sup p) :
continuous f :=
begin
rw βseminorm.is_bounded_const (fin 1) at hf,
exact continuous_from_bounded p (Ξ» _ : fin 1, norm_seminorm π F) f hf,
end
lemma cont_normed_space_to_with_seminorms (E) [semi_normed_group E] [normed_space π E]
[uniform_space F] [uniform_add_group F]
(q : ΞΉ β seminorm π F) [with_seminorms q] (f : E ββ[π] F)
(hf : β i : ΞΉ, β C : ββ₯0, C β 0 β§ (q i).comp f β€ C β’ (norm_seminorm π E)) : continuous f :=
begin
rw βseminorm.const_is_bounded (fin 1) at hf,
exact continuous_from_bounded (Ξ» _ : fin 1, norm_seminorm π E) q f hf,
end
end seminorm
end continuous_bounded
section locally_convex_space
open locally_convex_space
variables [nonempty ΞΉ] [normed_field π] [normed_space β π]
[add_comm_group E] [module π E] [module β E] [is_scalar_tower β π E] [topological_space E]
[topological_add_group E]
lemma seminorm_family.to_locally_convex_space (p : seminorm_family π E ΞΉ) [with_seminorms p] :
locally_convex_space β E :=
begin
apply of_basis_zero β E id (Ξ» s, s β p.basis_sets),
{ rw [p.with_seminorms_eq, add_group_filter_basis.nhds_eq _, add_group_filter_basis.N_zero],
exact filter_basis.has_basis _ },
{ intros s hs,
change s β set.Union _ at hs,
simp_rw [set.mem_Union, set.mem_singleton_iff] at hs,
rcases hs with β¨I, r, hr, rflβ©,
exact convex_ball _ _ _ }
end
end locally_convex_space
section normed_space
variables (π) [normed_field π] [normed_space β π] [semi_normed_group E]
/-- Not an instance since `π` can't be inferred. See `normed_space.to_locally_convex_space` for a
slightly weaker instance version. -/
lemma normed_space.to_locally_convex_space' [normed_space π E] [module β E]
[is_scalar_tower β π E] : locally_convex_space β E :=
seminorm_family.to_locally_convex_space (Ξ» _ : fin 1, norm_seminorm π E)
/-- See `normed_space.to_locally_convex_space'` for a slightly stronger version which is not an
instance. -/
instance normed_space.to_locally_convex_space [normed_space β E] :
locally_convex_space β E :=
normed_space.to_locally_convex_space' β
end normed_space
|
d3e3fbb467007ebde6f8baae4426075a8a833e8f | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/ring_theory/euclidean_domain.lean | ff05debc3a231830aea906a9dd695453dd455635 | [] | 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,490 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Chris Hughes
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.ring_theory.coprime
import Mathlib.ring_theory.ideal.basic
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Lemmas about Euclidean domains
Various about Euclidean domains are proved; all of them seem to be true
more generally for principal ideal domains, so these lemmas should
probably be reproved in more generality and this file perhaps removed?
## Tags
euclidean domain
-/
-- TODO -- this should surely be proved for PIDs instead?
theorem span_gcd {Ξ± : Type u_1} [euclidean_domain Ξ±] (x : Ξ±) (y : Ξ±) : ideal.span (singleton (euclidean_domain.gcd x y)) = ideal.span (insert x (singleton y)) := sorry
-- this should be proved for PIDs?
theorem gcd_is_unit_iff {Ξ± : Type u_1} [euclidean_domain Ξ±] {x : Ξ±} {y : Ξ±} : is_unit (euclidean_domain.gcd x y) β is_coprime x y := sorry
-- this should be proved for UFDs surely?
theorem is_coprime_of_dvd {Ξ± : Type u_1} [euclidean_domain Ξ±] {x : Ξ±} {y : Ξ±} (z : Β¬(x = 0 β§ y = 0)) (H : β (z : Ξ±), z β nonunits Ξ± β z β 0 β z β£ x β Β¬z β£ y) : is_coprime x y := sorry
-- this should be proved for UFDs surely?
theorem dvd_or_coprime {Ξ± : Type u_1} [euclidean_domain Ξ±] (x : Ξ±) (y : Ξ±) (h : irreducible x) : x β£ y β¨ is_coprime x y := sorry
|
db492c1c079082ac3e80082cb72a2199bdcd420e | ea4aee6b11f86433e69bb5e50d0259e056d0ae61 | /src/tidy/fsplit.lean | 4743086cd057f48850128b2caec5f5bf5ffc931b | [] | no_license | timjb/lean-tidy | e18feff0b7f0aad08c614fb4d34aaf527bf21e20 | e767e259bf76c69edfd4ab8af1b76e6f1ed67f48 | refs/heads/master | 1,624,861,693,182 | 1,504,411,006,000 | 1,504,411,006,000 | 103,740,824 | 0 | 0 | null | 1,505,553,968,000 | 1,505,553,968,000 | null | UTF-8 | Lean | false | false | 372 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
open tactic
meta def fsplit : tactic unit :=
do [c] β target >>= get_constructors_for | tactic.fail "fsplit tactic failed, target is not an inductive datatype with only one constructor",
mk_const c >>= fapply |
b47cb458bf9bdb9d50dcb627516f574bcb18cd25 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /library/logic/examples/propositional/deceq.lean | e998bf56705fa9d5e970b3a9525162d3fbbbc763 | [
"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 | 1,869 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
PropF has decidable equality
-/
import .soundness
open bool decidable nat
namespace PropF
-- Show that PropF has decidable equality
definition equal : PropF β PropF β bool
| (Var x) (Var y) := if x = y then tt else ff
| Bot Bot := tt
| (Conj pβ pβ) (Conj qβ qβ) := equal pβ qβ && equal pβ qβ
| (Disj pβ pβ) (Disj qβ qβ) := equal pβ qβ && equal pβ qβ
| (Impl pβ pβ) (Impl qβ qβ) := equal pβ qβ && equal pβ qβ
| _ _ := ff
lemma equal_refl : β p, equal p p = tt
| (Var x) := if_pos rfl
| Bot := rfl
| (Conj pβ pβ) := begin change (equal pβ pβ && equal pβ pβ = tt), rewrite *equal_refl end
| (Disj pβ pβ) := begin change (equal pβ pβ && equal pβ pβ = tt), rewrite *equal_refl end
| (Impl pβ pβ) := begin change (equal pβ pβ && equal pβ pβ = tt), rewrite *equal_refl end
lemma equal_to_eq : β β¦p qβ¦, equal p q = tt β p = q
| (Var x) (Var y) H :=
if Hβ : x = y then congr_arg Var Hβ
else by rewrite [βΈ (if x = y then tt else ff) = tt at H, if_neg Hβ at H]; exact (absurd H ff_ne_tt)
| Bot Bot H := rfl
| (Conj pβ pβ) (Conj qβ qβ) H :=
by rewrite [equal_to_eq (band_elim_left H), equal_to_eq (band_elim_right H)]
| (Disj pβ pβ) (Disj qβ qβ) H :=
by rewrite [equal_to_eq (band_elim_left H), equal_to_eq (band_elim_right H)]
| (Impl pβ pβ) (Impl qβ qβ) H :=
by rewrite [equal_to_eq (band_elim_left H), equal_to_eq (band_elim_right H)]
lemma has_decidable_eq [instance] : decidable_eq PropF :=
decidable_eq_of_bool_pred equal_to_eq equal_refl
end PropF
|
361c0da57fa0724f7e59a3cfd48050ba7b618419 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/tactic/positivity.lean | 65443879731441adb63f6ae5c53b14acb11f7e32 | [
"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 | 33,466 | lean | /-
Copyright (c) 2022 Mario Carneiro, Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Heather Macbeth, YaΓ«l Dillies
-/
import tactic.norm_num
import algebra.order.field.power
import algebra.order.hom.basic
import data.nat.factorial.basic
/-! # `positivity` tactic
The `positivity` tactic in this file solves goals of the form `0 β€ x`, `0 < x` and `x β 0`. The
tactic works recursively according to the syntax of the expression `x`. For example, a goal of the
form `0 β€ 3 * a ^ 2 + b * c` can be solved either
* by a hypothesis such as `5 β€ 3 * a ^ 2 + b * c` which directly implies the nonegativity of
`3 * a ^ 2 + b * c`; or,
* by the application of the lemma `add_nonneg` and the success of the `positivity` tactic on the two
sub-expressions `3 * a ^ 2` and `b * c`.
For each supported operation, one must write a small tactic, tagged with the attribute
`@[positivity]`, which operates only on goals whose leading function application is that operation.
Typically, this small tactic will run the full `positivity` tactic on one or more of the function's
arguments (which is where the recursion comes in), and if successful will combine this with an
appropriate lemma to give positivity of the full expression.
This file contains the core `positivity` logic and the small tactics handling the basic operations:
`min`, `max`, `+`, `*`, `/`, `β»ΒΉ`, raising to natural powers, and taking absolute values. Further
extensions, e.g. to handle `real.sqrt` and norms, can be found in the files of the library which
introduce these operations.
## Main declarations
* `tactic.norm_num.positivity` tries to prove positivity of an expression by running `norm_num` on
it. This is one of the base cases of the recursion.
* `tactic.positivity.compare_hyp` tries to prove positivity of an expression by comparing with a
provided hypothesis. If the hypothesis is of the form `a β€ b` or similar, with `b` matching the
expression whose proof of positivity is desired, then it will check whether `a` can be proved
positive via `tactic.norm_num.positivity` and if so apply a transitivity lemma. This is the other
base case of the recursion.
* `tactic.positivity.attr` creates the `positivity` user attribute for tagging the extension
tactics handling specific operations, and specifies the behaviour for a single step of the
recursion
* `tactic.positivity.core` collects the list of tactics with the `@[positivity]` attribute and
calls the first recursion step as specified in `tactic.positivity.attr`. Its input is `e : expr`
and its output (if it succeeds) is a term of a custom inductive type
`tactic.positivity.strictness`, containing an `expr` which is a proof of the
strict-positivity/nonnegativity of `e` as well as an indication of whether what could be proved
was strict-positivity or nonnegativity
* `tactic.positivity.order_rel` is a custom inductive type recording whether the goal is
`0 β€ e`/`e β₯ 0`, `0 < e`/`e > 0`, `e β 0` or `0 β e`.
* `tactic.interactive.positivity` is the user-facing tactic. It parses the goal and, if it is of
one of the forms `0 β€ e`, `0 < e`, `e > 0`, `e β₯ 0`, `e β 0`, `0 β e`, it sends `e` to
`tactic.positivity.core`.
## TODO
Implement extensions for other operations (raising to non-numeral powers, `log`).
-/
namespace tactic
/-- Inductive type recording either `positive` and an expression (typically a proof of a fact
`0 < x`) or `nonnegative` and an expression (typically a proof of a fact `0 β€ x`). -/
@[derive [decidable_eq]]
meta inductive positivity.strictness : Type
| positive : expr β positivity.strictness
| nonnegative : expr β positivity.strictness
| nonzero : expr β positivity.strictness
export positivity.strictness (positive nonnegative nonzero)
meta instance : has_to_string strictness :=
β¨Ξ» s, match s with
| positive p := "strictness.positive (" ++ to_string p ++ ")"
| nonnegative p := "strictness.nonnegative (" ++ to_string p ++ ")"
| nonzero p := "strictness.nonzero (" ++ to_string p ++ ")"
endβ©
meta instance : has_to_format strictness := β¨Ξ» s, to_string sβ©
private lemma lt_of_eq_of_lt'' {Ξ±} [preorder Ξ±] {b b' a : Ξ±} : b = b' β a < b' β a < b :=
Ξ» h1 h2, lt_of_lt_of_eq h2 h1.symm
/-- First base case of the `positivity` tactic. We try `norm_num` to prove directly that an
expression `e` is positive, nonnegative or non-zero. -/
meta def norm_num.positivity (e : expr) : tactic strictness := do
(e', p) β norm_num.derive e <|> refl_conv e,
e'' β e'.to_rat,
typ β infer_type e',
ic β mk_instance_cache typ,
if e'' > 0 then do
(ic, pβ) β norm_num.prove_pos ic e',
positive <$> mk_app ``lt_of_eq_of_lt'' [p, pβ]
else if e'' = 0 then
nonnegative <$> mk_app ``ge_of_eq [p]
else do
(ic, pβ) β norm_num.prove_ne_zero' ic e',
nonzero <$> to_expr ``(ne_of_eq_of_ne %%p %%pβ)
/-- Second base case of the `positivity` tactic: Any element of a canonically ordered additive
monoid is nonnegative. -/
meta def positivity_canon : expr β tactic strictness
| `(%%a) := nonnegative <$> mk_app ``zero_le [a]
namespace positivity
/-- Inductive type recording whether the goal `positivity` is called on is nonnegativity, positivity
or different from `0`. -/
@[derive inhabited]
inductive order_rel : Type
| le : order_rel -- `0 β€ a`
| lt : order_rel -- `0 < a`
| ne : order_rel -- `a β 0`
| ne' : order_rel -- `0 β a`
meta instance : has_to_format order_rel :=
β¨Ξ» r, match r with
| order_rel.le := "order_rel.le"
| order_rel.lt := "order_rel.lt"
| order_rel.ne := "order_rel.ne"
| order_rel.ne' := "order_rel.ne'"
endβ©
/-- Given two tactics whose result is `strictness`, report a `strictness`:
- if at least one gives `positive`, report `positive` and one of the expressions giving a proof of
positivity
- if one reports `nonnegative` and the other reports `nonzero`, report `positive`
- else if at least one reports `nonnegative`, report `nonnegative` and one of the
expressions giving a proof of nonnegativity
- else if at least one reports `nonzero`, report `nonzero` and one of the expressions giving a proof
of nonzeroness
- if both fail, fail -/
protected meta def orelse (tac1 tac2 : tactic strictness) : tactic strictness := do
res1 β try_core tac1,
match res1 with
| none := tac2
| some p1@(positive _) := pure p1
| some (nonnegative e1) := do
res2 β try_core tac2,
match res2 with
| some p2@(positive _) := pure p2
| some (nonzero e2) := positive <$> mk_app ``lt_of_le_of_ne' [e1, e2]
| _ := pure (nonnegative e1)
end
| some (nonzero e1) := do
res2 β try_core tac2,
match res2 with
| some p2@(positive _) := pure p2
| some (nonnegative e2) := positive <$> mk_app ``lt_of_le_of_ne' [e2, e1]
| _ := pure (nonzero e1)
end
end
localized "infixr ` β€|β₯ `:2 := tactic.positivity.orelse" in positivity
/-- This tactic fails with a message saying that `positivity` couldn't prove anything about `e`
if we only know that `a` and `b` are positive/nonnegative/nonzero (according to `pa` and `pb`). -/
meta def positivity_fail {Ξ± : Type*} (e a b : expr) (pa pb : strictness) : tactic Ξ± :=
do
e' β pp e,
a' β pp a,
b' β pp b,
let f : strictness β format β format := Ξ» p c, match p with
| positive _ := "0 < " ++ c
| nonnegative _ := "0 β€ " ++ c
| nonzero _ := c ++ " β 0"
end,
fail (β"`positivity` can't say anything about `" ++ e' ++ "` knowing only `" ++ f pa a' ++
"` and `" ++ f pb b' ++ "`")
/-! ### Core logic of the `positivity` tactic -/
private lemma ne_of_ne_of_eq' {Ξ± : Type*} {a b c : Ξ±} (ha : a β c) (h : a = b) : b β c := by rwa βh
/-- Calls `norm_num` on `a` to prove positivity/nonnegativity of `e` assuming `b` is defeq to `e`
and `pβ : a β€ b`. -/
meta def compare_hyp_le (e a b pβ : expr) : tactic strictness := do
is_def_eq e b,
strict_a β norm_num.positivity a,
match strict_a with
| positive pβ := positive <$> mk_app ``lt_of_lt_of_le [pβ, pβ]
| nonnegative pβ := nonnegative <$> mk_app ``le_trans [pβ, pβ]
| _ := do
e' β pp e,
pβ' β pp pβ,
fail (β"`norm_num` can't prove nonnegativity of " ++ e' ++ " using " ++ pβ')
end
/-- Calls `norm_num` on `a` to prove positivity/nonnegativity of `e` assuming `b` is defeq to `e`
and `pβ : a < b`. -/
meta def compare_hyp_lt (e a b pβ : expr) : tactic strictness := do
is_def_eq e b,
strict_a β norm_num.positivity a,
match strict_a with
| positive pβ := positive <$> mk_app ``lt_trans [pβ, pβ]
| nonnegative pβ := positive <$> mk_app ``lt_of_le_of_lt [pβ, pβ]
| _ := do
e' β pp e,
pβ' β pp pβ,
fail (β"`norm_num` can't prove positivity of " ++ e' ++ " using " ++ pβ')
end
/-- Calls `norm_num` on `a` to prove positivity/nonnegativity/nonzeroness of `e` assuming `b` is
defeq to `e` and `pβ : a = b`. -/
meta def compare_hyp_eq (e a b pβ : expr) : tactic strictness := do
is_def_eq e b,
strict_a β norm_num.positivity a,
match strict_a with
| positive pβ := positive <$> mk_app ``lt_of_lt_of_eq [pβ, pβ]
| nonnegative pβ := nonnegative <$> mk_app ``le_of_le_of_eq [pβ, pβ]
| nonzero pβ := nonzero <$> to_expr ``(ne_of_ne_of_eq' %%pβ %%pβ)
end
/-- Calls `norm_num` on `a` to prove nonzeroness of `e` assuming `b` is defeq to `e` and
`pβ : b β a`. -/
meta def compare_hyp_ne (e a b pβ : expr) : tactic strictness := do
is_def_eq e b,
(a', pβ) β norm_num.derive a <|> refl_conv a,
a'' β a'.to_rat,
if a'' = 0 then
nonzero <$> mk_mapp ``ne_of_ne_of_eq [none, none, none, none, pβ, pβ]
else do
e' β pp e,
pβ' β pp pβ,
a' β pp a,
fail (β"`norm_num` can't prove non-zeroness of " ++ e' ++ " using " ++ pβ' ++ " because "
++ a' ++ " is non-zero")
/-- Third base case of the `positivity` tactic. Prove an expression `e` is
positive/nonnegative/nonzero by finding a hypothesis of the form `a < e`, `a β€ e` or `a = e` in
which `a` can be proved positive/nonnegative/nonzero by `norm_num`. -/
meta def compare_hyp (e pβ : expr) : tactic strictness := do
p_typ β infer_type pβ,
match p_typ with
| `(%%lo β€ %%hi) := compare_hyp_le e lo hi pβ
| `(%%hi β₯ %%lo) := compare_hyp_le e lo hi pβ
| `(%%lo < %%hi) := compare_hyp_lt e lo hi pβ
| `(%%hi > %%lo) := compare_hyp_lt e lo hi pβ
| `(%%lo = %%hi) := compare_hyp_eq e lo hi pβ <|> do
pβ' β mk_app ``eq.symm [pβ],
compare_hyp_eq e hi lo pβ'
| `(%%hi β %%lo) := compare_hyp_ne e lo hi pβ <|> do
pβ' β mk_mapp ``ne.symm [none, none, none, pβ],
compare_hyp_ne e hi lo pβ'
| e := do
pβ' β pp pβ,
fail (pβ' ++ "is not of the form `a β€ b`, `a < b`, `a = b` or `a β b`")
end
/-- Attribute allowing a user to tag a tactic as an extension for `tactic.interactive.positivity`.
The main (recursive) step of this tactic is to try successively all the extensions tagged with this
attribute on the expression at hand, and also to try the two "base case" tactics
`tactic.norm_num.positivity`, `tactic.positivity.compare_hyp` on the expression at hand. -/
@[user_attribute]
meta def attr : user_attribute (expr β tactic strictness) unit :=
{ name := `positivity,
descr := "extensions handling particular operations for the `positivity` tactic",
cache_cfg :=
{ mk_cache := Ξ» ns, do
{ t β ns.mfoldl
(Ξ» (t : expr β tactic strictness) n, do
t' β eval_expr (expr β tactic strictness) (expr.const n []),
pure (Ξ» e, t' e β€|β₯ t e))
(Ξ» _, failed),
pure $ Ξ» e,
t e -- run all the extensions on `e`
β€|β₯ norm_num.positivity e -- directly try `norm_num` on `e`
β€|β₯ positivity_canon e -- try showing nonnegativity from canonicity of the order
-- loop over hypotheses and try to compare with `e`
β€|β₯ local_context >>= list.foldl (Ξ» tac h, tac β€|β₯ compare_hyp e h)
(fail "no applicable positivity extension found") },
dependencies := [] } }
/-- Look for a proof of positivity/nonnegativity of an expression `e`; if found, return the proof
together with a `strictness` stating whether the proof found was for strict positivity
(`positive p`), nonnegativity (`nonnegative p`), or nonzeroness (`nonzero p`). -/
meta def core (e : expr) : tactic strictness := do
f β attr.get_cache,
f e <|> fail "failed to prove positivity/nonnegativity/nonzeroness"
end positivity
open positivity
open_locale positivity
namespace interactive
setup_tactic_parser
/-- Tactic solving goals of the form `0 β€ x`, `0 < x` and `x β 0`. The tactic works recursively
according to the syntax of the expression `x`, if the atoms composing the expression all have
numeric lower bounds which can be proved positive/nonnegative/nonzero by `norm_num`. This tactic
either closes the goal or fails.
Examples:
```
example {a : β€} (ha : 3 < a) : 0 β€ a ^ 3 + a := by positivity
example {a : β€} (ha : 1 < a) : 0 < |(3:β€) + a| := by positivity
example {b : β€} : 0 β€ max (-3) (b ^ 2) := by positivity
```
-/
meta def positivity : tactic unit := focus1 $ do
t β target >>= instantiate_mvars,
(rel_desired, a) β match t with
| `(0 β€ %%e) := pure (order_rel.le, e)
| `(%%e β₯ 0) := pure (order_rel.le, e)
| `(0 < %%e) := pure (order_rel.lt, e)
| `(%%e > 0) := pure (order_rel.lt, e)
| `(%%eβ β %%eβ) := do
match eβ with
| `(has_zero.zero) := pure (order_rel.ne, eβ)
| _ := match eβ with
| `(has_zero.zero) := pure (order_rel.ne', eβ)
| _ := fail "not a positivity/nonnegativity/nonzeroness goal"
end
end
| _ := fail "not a positivity/nonnegativity/nonzeroness goal"
end,
strictness_proved β tactic.positivity.core a,
match rel_desired, strictness_proved with
| order_rel.lt, positive p := pure p
| order_rel.lt, nonnegative _ := fail ("failed to prove strict positivity, but it would be " ++
"possible to prove nonnegativity if desired")
| order_rel.lt, nonzero _ := fail ("failed to prove strict positivity, but it would be " ++
"possible to prove nonzeroness if desired")
| order_rel.le, positive p := mk_app ``le_of_lt [p]
| order_rel.le, nonnegative p := pure p
| order_rel.le, nonzero _ := fail ("failed to prove nonnegativity, but it would be " ++
"possible to prove nonzeroness if desired")
| order_rel.ne, positive p := to_expr ``(ne_of_gt %%p)
| order_rel.ne, nonnegative _ := fail ("failed to prove nonzeroness, but it would be " ++
"possible to prove nonnegativity if desired")
| order_rel.ne, nonzero p := pure p
| order_rel.ne', positive p := to_expr ``(ne_of_lt %%p)
| order_rel.ne', nonnegative _ := fail ("failed to prove nonzeroness, but it would be " ++
"possible to prove nonnegativity if desired")
| order_rel.ne', nonzero p := to_expr ``(ne.symm %%p)
end >>= tactic.exact
add_tactic_doc
{ name := "positivity",
category := doc_category.tactic,
decl_names := [`tactic.interactive.positivity],
tags := ["arithmetic", "monotonicity", "finishing"] }
end interactive
variables {ΞΉ Ξ± R : Type*}
/-! ### `positivity` extensions for particular arithmetic operations -/
section linear_order
variables [linear_order R] {a b c : R}
private lemma le_min_of_lt_of_le (ha : a < b) (hb : a β€ c) : a β€ min b c := le_min ha.le hb
private lemma le_min_of_le_of_lt (ha : a β€ b) (hb : a < c) : a β€ min b c := le_min ha hb.le
private lemma min_ne (ha : a β c) (hb : b β c) : min a b β c :=
by { rw min_def, split_ifs; assumption }
private lemma min_ne_of_ne_of_lt (ha : a β c) (hb : c < b) : min a b β c := min_ne ha hb.ne'
private lemma min_ne_of_lt_of_ne (ha : c < a) (hb : b β c) : min a b β c := min_ne ha.ne' hb
private lemma max_ne (ha : a β c) (hb : b β c) : max a b β c :=
by { rw max_def, split_ifs; assumption }
end linear_order
/-- Extension for the `positivity` tactic: the `min` of two numbers is nonnegative if both are
nonnegative, and strictly positive if both are. -/
@[positivity]
meta def positivity_min : expr β tactic strictness
| e@`(min %%a %%b) := do
strictness_a β core a,
strictness_b β core b,
match strictness_a, strictness_b with
| (positive pa), (positive pb) := positive <$> mk_app ``lt_min [pa, pb]
| (positive pa), (nonnegative pb) := nonnegative <$> mk_app ``le_min_of_lt_of_le [pa, pb]
| (nonnegative pa), (positive pb) := nonnegative <$> mk_app ``le_min_of_le_of_lt [pa, pb]
| (nonnegative pa), (nonnegative pb) := nonnegative <$> mk_app ``le_min [pa, pb]
| positive pa, nonzero pb := nonzero <$> to_expr ``(min_ne_of_lt_of_ne %%pa %%pb)
| nonzero pa, positive pb := nonzero <$> to_expr ``(min_ne_of_ne_of_lt %%pa %%pb)
| nonzero pa, nonzero pb := nonzero <$> to_expr ``(min_ne %%pa %%pb)
| sa@_, sb@ _ := positivity_fail e a b sa sb
end
| e := pp e >>= fail β format.bracket "The expression `" "` isn't of the form `min a b`"
/-- Extension for the `positivity` tactic: the `max` of two numbers is nonnegative if at least one
is nonnegative, strictly positive if at least one is positive, and nonzero if both are nonzero. -/
@[positivity]
meta def positivity_max : expr β tactic strictness
| `(max %%a %%b) := do
strictness_a β try_core (core a),
(do
match strictness_a with
| some (positive pa) := positive <$> mk_mapp ``lt_max_of_lt_left [none, none, none, a, b, pa]
| some (nonnegative pa) :=
nonnegative <$> mk_mapp ``le_max_of_le_left [none, none, none, a, b, pa]
| _ := failed
-- If `a β 0`, we might prove `max a b β 0` if `b β 0` but we don't want to evaluate
-- `b` before having ruled out `0 < a`, for performance. So we do that in the second branch
-- of the `orelse'`.
end) β€|β₯
(do
strictness_b β core b,
match strictness_b with
| (positive pb) := positive <$> mk_mapp ``lt_max_of_lt_right [none, none, none, a, b, pb]
| (nonnegative pb) :=
nonnegative <$> mk_mapp ``le_max_of_le_right [none, none, none, a, b, pb]
| nonzero pb := do
nonzero pa β strictness_a,
nonzero <$> to_expr ``(max_ne %%pa %%pb)
end)
| e := pp e >>= fail β format.bracket "The expression `" "` isn't of the form `max a b`"
/-- Extension for the `positivity` tactic: addition is nonnegative if both summands are nonnegative,
and strictly positive if at least one summand is. -/
@[positivity]
meta def positivity_add : expr β tactic strictness
| e@`(%%a + %%b) := do
strictness_a β core a,
strictness_b β core b,
match strictness_a, strictness_b with
| (positive pa), (positive pb) := positive <$> mk_app ``add_pos [pa, pb]
| (positive pa), (nonnegative pb) := positive <$> mk_app ``lt_add_of_pos_of_le [pa, pb]
| (nonnegative pa), (positive pb) := positive <$> mk_app ``lt_add_of_le_of_pos [pa, pb]
| (nonnegative pa), (nonnegative pb) := nonnegative <$> mk_app ``add_nonneg [pa, pb]
| sa@_, sb@ _ := positivity_fail e a b sa sb
end
| e := pp e >>= fail β format.bracket "The expression `" "` isn't of the form `a + b`"
section ordered_semiring
variables [ordered_semiring R] {a b : R}
private lemma mul_nonneg_of_pos_of_nonneg (ha : 0 < a) (hb : 0 β€ b) : 0 β€ a * b :=
mul_nonneg ha.le hb
private lemma mul_nonneg_of_nonneg_of_pos (ha : 0 β€ a) (hb : 0 < b) : 0 β€ a * b :=
mul_nonneg ha hb.le
private lemma mul_ne_zero_of_pos_of_ne_zero [no_zero_divisors R] (ha : 0 < a) (hb : b β 0) :
a * b β 0 :=
mul_ne_zero ha.ne' hb
private lemma mul_ne_zero_of_ne_zero_of_pos [no_zero_divisors R] (ha : a β 0) (hb : 0 < b) :
a * b β 0 :=
mul_ne_zero ha hb.ne'
end ordered_semiring
/-- Extension for the `positivity` tactic: multiplication is nonnegative/positive/nonzero if both
multiplicands are. -/
@[positivity]
meta def positivity_mul : expr β tactic strictness
| e@`(%%a * %%b) := do
strictness_a β core a,
strictness_b β core b,
match strictness_a, strictness_b with
| (positive pa), (positive pb) := positive <$> mk_app ``mul_pos [pa, pb]
| (positive pa), (nonnegative pb) := nonnegative <$> mk_app ``mul_nonneg_of_pos_of_nonneg [pa, pb]
| (nonnegative pa), (positive pb) := nonnegative <$> mk_app ``mul_nonneg_of_nonneg_of_pos [pa, pb]
| (nonnegative pa), (nonnegative pb) := nonnegative <$> mk_app ``mul_nonneg [pa, pb]
| positive pa, nonzero pb := nonzero <$> to_expr ``(mul_ne_zero_of_pos_of_ne_zero %%pa %%pb)
| nonzero pa, positive pb := nonzero <$> to_expr ``(mul_ne_zero_of_ne_zero_of_pos %%pa %%pb)
| nonzero pa, nonzero pb := nonzero <$> to_expr ``(mul_ne_zero %%pa %%pb)
| sa@_, sb@ _ := positivity_fail e a b sa sb
end
| e := pp e >>= fail β format.bracket "The expression `" "` isn't of the form `a * b`"
section linear_ordered_semifield
variables [linear_ordered_semifield R] {a b : R}
private lemma div_nonneg_of_pos_of_nonneg (ha : 0 < a) (hb : 0 β€ b) : 0 β€ a / b :=
div_nonneg ha.le hb
private lemma div_nonneg_of_nonneg_of_pos (ha : 0 β€ a) (hb : 0 < b) : 0 β€ a / b :=
div_nonneg ha hb.le
private lemma div_ne_zero_of_pos_of_ne_zero (ha : 0 < a) (hb : b β 0) : a / b β 0 :=
div_ne_zero ha.ne' hb
private lemma div_ne_zero_of_ne_zero_of_pos (ha : a β 0) (hb : 0 < b) : a / b β 0 :=
div_ne_zero ha hb.ne'
end linear_ordered_semifield
private lemma int_div_self_pos {a : β€} (ha : 0 < a) : 0 < a / a :=
by { rw int.div_self ha.ne', exact zero_lt_one }
private lemma int_div_nonneg_of_pos_of_nonneg {a b : β€} (ha : 0 < a) (hb : 0 β€ b) : 0 β€ a / b :=
int.div_nonneg ha.le hb
private lemma int_div_nonneg_of_nonneg_of_pos {a b : β€} (ha : 0 β€ a) (hb : 0 < b) : 0 β€ a / b :=
int.div_nonneg ha hb.le
private lemma int_div_nonneg_of_pos_of_pos {a b : β€} (ha : 0 < a) (hb : 0 < b) : 0 β€ a / b :=
int.div_nonneg ha.le hb.le
/-- Extension for the `positivity` tactic: division is nonnegative if both numerator and denominator
are nonnegative, and strictly positive if both numerator and denominator are. -/
@[positivity]
meta def positivity_div : expr β tactic strictness
| e@`(@has_div.div β€ _ %%a %%b) := do
strictness_a β core a,
strictness_b β core b,
match strictness_a, strictness_b with
| positive pa, positive pb :=
if a = b then -- Only attempts to prove `0 < a / a`, otherwise falls back to `0 β€ a / b`
positive <$> mk_app ``int_div_self_pos [pa]
else
nonnegative <$> mk_app ``int_div_nonneg_of_pos_of_pos [pa, pb]
| positive pa, nonnegative pb :=
nonnegative <$> mk_app ``int_div_nonneg_of_pos_of_nonneg [pa, pb]
| nonnegative pa, positive pb :=
nonnegative <$> mk_app ``int_div_nonneg_of_nonneg_of_pos [pa, pb]
| nonnegative pa, nonnegative pb := nonnegative <$> mk_app ``int.div_nonneg [pa, pb]
| sa@_, sb@ _ := positivity_fail e a b sa sb
end
| e@`(%%a / %%b) := do
strictness_a β core a,
strictness_b β core b,
match strictness_a, strictness_b with
| positive pa, positive pb := positive <$> mk_app ``div_pos [pa, pb]
| positive pa, nonnegative pb := nonnegative <$> mk_app ``div_nonneg_of_pos_of_nonneg [pa, pb]
| nonnegative pa, positive pb := nonnegative <$> mk_app ``div_nonneg_of_nonneg_of_pos [pa, pb]
| nonnegative pa, nonnegative pb := nonnegative <$> mk_app ``div_nonneg [pa, pb]
| positive pa, nonzero pb := nonzero <$> to_expr ``(div_ne_zero_of_pos_of_ne_zero %%pa %%pb)
| nonzero pa, positive pb := nonzero <$> to_expr ``(div_ne_zero_of_ne_zero_of_pos %%pa %%pb)
| nonzero pa, nonzero pb := nonzero <$> to_expr ``(div_ne_zero %%pa %%pb)
| sa@_, sb@ _ := positivity_fail e a b sa sb
end
| e := pp e >>= fail β format.bracket "The expression `" "` isn't of the form `a / b`"
/-- Extension for the `positivity` tactic: an inverse of a positive number is positive, an inverse
of a nonnegative number is nonnegative. -/
@[positivity]
meta def positivity_inv : expr β tactic strictness
| `((%%a)β»ΒΉ) := do
strictness_a β core a,
match strictness_a with
| (positive pa) := positive <$> mk_app ``inv_pos_of_pos [pa]
| (nonnegative pa) := nonnegative <$> mk_app ``inv_nonneg_of_nonneg [pa]
| nonzero pa := nonzero <$> to_expr ``(inv_ne_zero %%pa)
end
| e := pp e >>= fail β format.bracket "The expression `" "` isn't of the form `aβ»ΒΉ`"
private lemma pow_zero_pos [ordered_semiring R] [nontrivial R] (a : R) : 0 < a ^ 0 :=
zero_lt_one.trans_le (pow_zero a).ge
private lemma zpow_zero_pos [linear_ordered_semifield R] (a : R) : 0 < a ^ (0 : β€) :=
zero_lt_one.trans_le (zpow_zero a).ge
/-- Extension for the `positivity` tactic: raising a number `a` to a natural/integer power `n` is
positive if `n = 0` (since `a ^ 0 = 1`) or if `0 < a`, and is nonnegative if `n` is even (squares
are nonnegative) or if `0 β€ a`. -/
@[positivity]
meta def positivity_pow : expr β tactic strictness
| e@`(%%a ^ %%n) := do
typ β infer_type n,
(do
unify typ `(β),
if n = `(0) then
positive <$> mk_app ``pow_zero_pos [a]
else
do -- even powers are nonnegative
-- Note this is automatically strengthened to `0 < a ^ n` when `a β 0` thanks to the `orelse'`
match n with -- TODO: Decision procedure for parity
| `(bit0 %% n) := nonnegative <$> mk_app ``pow_bit0_nonneg [a, n]
| _ := do
e' β pp e,
fail (e' ++ "is not an even power so positivity can't prove it's nonnegative")
end β€|β₯
do -- `a ^ n` is positive if `a` is, and nonnegative if `a` is
strictness_a β core a,
match strictness_a with
| positive p := positive <$> mk_app ``pow_pos [p, n]
| nonnegative p := nonnegative <$> mk_app `pow_nonneg [p, n]
| nonzero p := nonzero <$> to_expr ``(pow_ne_zero %%n %%p)
end) <|>
(do
unify typ `(β€),
if n = `(0 : β€) then
positive <$> mk_app ``zpow_zero_pos [a]
else
do -- even powers are nonnegative
-- Note this is automatically strengthened to `0 < a ^ n` when `a β 0` thanks to the `orelse'`
match n with -- TODO: Decision procedure for parity
| `(bit0 %%n) := nonnegative <$> mk_app ``zpow_bit0_nonneg [a, n]
| _ := do
e' β pp e,
fail (e' ++ "is not an even power so positivity can't prove it's nonnegative")
end β€|β₯
do -- `a ^ n` is positive if `a` is, and nonnegative if `a` is
strictness_a β core a,
match strictness_a with
| positive p := positive <$> mk_app ``zpow_pos_of_pos [p, n]
| nonnegative p := nonnegative <$> mk_app ``zpow_nonneg [p, n]
| nonzero p := nonzero <$> to_expr ``(zpow_ne_zero %%n %%p)
end)
| e := pp e >>= fail β format.bracket "The expression `" "` isn't of the form `a ^ n`"
/-- Extension for the `positivity` tactic: raising a positive number in a canonically ordered
semiring gives a positive number. -/
@[positivity]
meta def positivity_canon_pow : expr β tactic strictness
| `(%%r ^ %%n) := do
typ_n β infer_type n,
unify typ_n `(β),
positive p β core r,
positive <$> mk_app ``canonically_ordered_comm_semiring.pow_pos [p, n]
-- The nonzero never happens because of `tactic.positivity_canon`
| e := pp e >>= fail β format.bracket "The expression `"
"` is not of the form `a ^ n` for `a` in a `canonically_ordered_comm_semiring` and `n : β`"
private alias abs_pos β _ abs_pos_of_ne_zero
/-- Extension for the `positivity` tactic: an absolute value is nonnegative, and is strictly
positive if its input is nonzero. -/
@[positivity]
meta def positivity_abs : expr β tactic strictness
| `(|%%a|) := do
(do -- if can prove `0 < a` or `a β 0`, report positivity
strict_a β core a,
match strict_a with
| positive p := positive <$> mk_app ``abs_pos_of_pos [p]
| nonzero p := positive <$> mk_app ``abs_pos_of_ne_zero [p]
| _ := failed
end) <|>
nonnegative <$> mk_app ``abs_nonneg [a] -- else report nonnegativity
| e := pp e >>= fail β format.bracket "The expression `" "` isn't of the form `|a|`"
private lemma int_nat_abs_pos {n : β€} (hn : 0 < n) : 0 < n.nat_abs :=
int.nat_abs_pos_of_ne_zero hn.ne'
/-- Extension for the `positivity` tactic: `int.nat_abs` is positive when its input is.
Since the output type of `int.nat_abs` is `β`, the nonnegative case is handled by the default
`positivity` tactic.
-/
@[positivity]
meta def positivity_nat_abs : expr β tactic strictness
| `(int.nat_abs %%a) := do
strict_a β core a,
match strict_a with
| positive p := positive <$> mk_app ``int_nat_abs_pos [p]
| nonzero p := positive <$> mk_app ``int.nat_abs_pos_of_ne_zero [p]
| _ := failed
end
| _ := failed
private lemma nat_cast_pos [ordered_semiring Ξ±] [nontrivial Ξ±] {n : β} : 0 < n β 0 < (n : Ξ±) :=
nat.cast_pos.2
private lemma int_coe_nat_nonneg (n : β) : 0 β€ (n : β€) := n.cast_nonneg
private lemma int_coe_nat_pos {n : β} : 0 < n β 0 < (n : β€) := nat.cast_pos.2
private lemma int_cast_ne_zero [add_group_with_one Ξ±] [char_zero Ξ±] {n : β€} : n β 0 β (n : Ξ±) β 0 :=
int.cast_ne_zero.2
private lemma int_cast_nonneg [ordered_ring Ξ±] {n : β€} (hn : 0 β€ n) : 0 β€ (n : Ξ±) :=
by { rw βint.cast_zero, exact int.cast_mono hn }
private lemma int_cast_pos [ordered_ring Ξ±] [nontrivial Ξ±] {n : β€} : 0 < n β 0 < (n : Ξ±) :=
int.cast_pos.2
private lemma rat_cast_ne_zero [division_ring Ξ±] [char_zero Ξ±] {q : β} : q β 0 β (q : Ξ±) β 0 :=
rat.cast_ne_zero.2
private lemma rat_cast_nonneg [linear_ordered_field Ξ±] {q : β} : 0 β€ q β 0 β€ (q : Ξ±) :=
rat.cast_nonneg.2
private lemma rat_cast_pos [linear_ordered_field Ξ±] {q : β} : 0 < q β 0 < (q : Ξ±) := rat.cast_pos.2
/-- Extension for the `positivity` tactic: casts from `β`, `β€`, `β`. -/
@[positivity]
meta def positivity_coe : expr β tactic strictness
| `(@coe _ %%typ %%inst %%a) := do
-- TODO: Using `match` here might turn out too strict since we really want the instance to *unify*
-- with one of the instances below rather than being equal on the nose.
-- If this turns out to indeed be a problem, we should figure out the right way to pattern match
-- up to defeq rather than equality of expressions.
-- See also "Reflexive tactics for algebra, revisited" by Kazuhiko Sakaguchi at ITP 2022.
match inst with
| `(@coe_to_lift _ _ %%inst) := do
strictness_a β core a,
match inst, strictness_a with -- `mk_mapp` is necessary in some places. Why?
| `(nat.cast_coe), positive p := positive <$> mk_mapp ``nat_cast_pos [typ, none, none, none, p]
| `(nat.cast_coe), _ := nonnegative <$> mk_mapp ``nat.cast_nonneg [typ, none, a]
| `(int.cast_coe), positive p := positive <$> mk_mapp ``int_cast_pos [typ, none, none, none, p]
| `(int.cast_coe), nonnegative p := nonnegative <$>
mk_mapp ``int_cast_nonneg [typ, none, none, p]
| `(int.cast_coe), nonzero p := nonzero <$>
mk_mapp ``int_cast_ne_zero [typ, none, none, none, p]
| `(rat.cast_coe), positive p := positive <$> mk_mapp ``rat_cast_pos [typ, none, none, p]
| `(rat.cast_coe), nonnegative p := nonnegative <$>
mk_mapp ``rat_cast_nonneg [typ, none, none, p]
| `(rat.cast_coe), nonzero p := nonzero <$>
mk_mapp ``rat_cast_ne_zero [typ, none, none, none, p]
| `(@coe_base _ _ int.has_coe), positive p := positive <$> mk_app ``int_coe_nat_pos [p]
| `(@coe_base _ _ int.has_coe), _ := nonnegative <$> mk_app ``int_coe_nat_nonneg [a]
| _, _ := failed
end
| _ := failed
end
| _ := failed
/-- Extension for the `positivity` tactic: `nat.succ` is always positive. -/
@[positivity]
meta def positivity_succ : expr β tactic strictness
| `(nat.succ %%a) := positive <$> mk_app `nat.succ_pos [a]
| e := pp e >>= fail β format.bracket "The expression `" "` isn't of the form `nat.succ n`"
/-- Extension for the `positivity` tactic: `nat.factorial` is always positive. -/
@[positivity]
meta def positivity_factorial : expr β tactic strictness
| `(nat.factorial %%a) := positive <$> mk_app ``nat.factorial_pos [a]
| e := pp e >>= fail β format.bracket "The expression `" "` isn't of the form `n!`"
/-- Extension for the `positivity` tactic: `nat.asc_factorial` is always positive. -/
@[positivity]
meta def positivity_asc_factorial : expr β tactic strictness
| `(nat.asc_factorial %%a %%b) := positive <$> mk_app ``nat.asc_factorial_pos [a, b]
| e := pp e >>= fail β format.bracket "The expression `"
"` isn't of the form `nat.asc_factorial n k`"
/-- Extension for the `positivity` tactic: nonnegative maps take nonnegative values. -/
@[positivity]
meta def positivity_map : expr β tactic strictness
| (expr.app `(β%%f) `(%%a)) := nonnegative <$> mk_app ``map_nonneg [f, a]
| _ := failed
end tactic
|
0a9cf9040cfbe2fc219617a2b880ada29819f1c0 | 8e6cad62ec62c6c348e5faaa3c3f2079012bdd69 | /src/ring_theory/polynomial/scale_roots.lean | 28d4d573eeccbeb809fb294714c3b951ff2d41c2 | [
"Apache-2.0"
] | permissive | benjamindavidson/mathlib | 8cc81c865aa8e7cf4462245f58d35ae9a56b150d | fad44b9f670670d87c8e25ff9cdf63af87ad731e | refs/heads/master | 1,679,545,578,362 | 1,615,343,014,000 | 1,615,343,014,000 | 312,926,983 | 0 | 0 | Apache-2.0 | 1,615,360,301,000 | 1,605,399,418,000 | Lean | UTF-8 | Lean | false | false | 5,350 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen, Devon Tuma
-/
import ring_theory.polynomial.basic
import ring_theory.non_zero_divisors
/-!
# Scaling the roots of a polynomial
This file defines `scale_roots p s` for a polynomial `p` in one variable and a ring element `s` to
be the polynomial with root `r * s` for each root `r` of `p` and proves some basic results about it.
-/
section scale_roots
variables {A K R S : Type*} [integral_domain A] [field K] [comm_ring R] [comm_ring S]
variables {M : submonoid A}
open finsupp polynomial
/-- `scale_roots p s` is a polynomial with root `r * s` for each root `r` of `p`. -/
noncomputable def scale_roots (p : polynomial R) (s : R) : polynomial R :=
on_finset p.support
(Ξ» i, coeff p i * s ^ (p.nat_degree - i))
(Ξ» i h, mem_support_iff.mpr (left_ne_zero_of_mul h))
@[simp] lemma coeff_scale_roots (p : polynomial R) (s : R) (i : β) :
(scale_roots p s).coeff i = coeff p i * s ^ (p.nat_degree - i) :=
rfl
lemma coeff_scale_roots_nat_degree (p : polynomial R) (s : R) :
(scale_roots p s).coeff p.nat_degree = p.leading_coeff :=
by rw [leading_coeff, coeff_scale_roots, nat.sub_self, pow_zero, mul_one]
@[simp] lemma zero_scale_roots (s : R) : scale_roots 0 s = 0 := by { ext, simp }
lemma scale_roots_ne_zero {p : polynomial R} (hp : p β 0) (s : R) :
scale_roots p s β 0 :=
begin
intro h,
have : p.coeff p.nat_degree β 0 := mt leading_coeff_eq_zero.mp hp,
have : (scale_roots p s).coeff p.nat_degree = 0 :=
congr_fun (congr_arg (coeff : polynomial R β β β R) h) p.nat_degree,
rw [coeff_scale_roots_nat_degree] at this,
contradiction
end
lemma support_scale_roots_le (p : polynomial R) (s : R) :
(scale_roots p s).support β€ p.support :=
begin
intros i,
simp only [mem_support_iff, scale_roots, on_finset_apply],
exact left_ne_zero_of_mul
end
lemma support_scale_roots_eq (p : polynomial R) {s : R} (hs : s β non_zero_divisors R) :
(scale_roots p s).support = p.support :=
le_antisymm (support_scale_roots_le p s)
begin
intro i,
simp only [mem_support_iff, scale_roots, on_finset_apply],
intros p_ne_zero ps_zero,
have := ((non_zero_divisors R).pow_mem hs (p.nat_degree - i)) _ ps_zero,
contradiction
end
@[simp] lemma degree_scale_roots (p : polynomial R) {s : R} :
degree (scale_roots p s) = degree p :=
begin
haveI := classical.prop_decidable,
by_cases hp : p = 0,
{ rw [hp, zero_scale_roots] },
have := scale_roots_ne_zero hp s,
refine le_antisymm (finset.sup_mono (support_scale_roots_le p s)) (degree_le_degree _),
rw coeff_scale_roots_nat_degree,
intro h,
have := leading_coeff_eq_zero.mp h,
contradiction,
end
@[simp] lemma nat_degree_scale_roots (p : polynomial R) (s : R) :
nat_degree (scale_roots p s) = nat_degree p :=
by simp only [nat_degree, degree_scale_roots]
lemma monic_scale_roots_iff {p : polynomial R} (s : R) :
monic (scale_roots p s) β monic p :=
by simp only [monic, leading_coeff, nat_degree_scale_roots, coeff_scale_roots_nat_degree]
lemma scale_roots_evalβ_eq_zero {p : polynomial S} (f : S β+* R)
{r : R} {s : S} (hr : evalβ f r p = 0) :
evalβ f (f s * r) (scale_roots p s) = 0 :=
calc evalβ f (f s * r) (scale_roots p s) =
(scale_roots p s).support.sum (Ξ» i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) :
evalβ_eq_sum
... = p.support.sum (Ξ» i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) :
finset.sum_subset (support_scale_roots_le p s)
(Ξ» i hi hi', let this : coeff p i * s ^ (p.nat_degree - i) = 0 :=
by simpa using hi' in by simp [this])
... = p.support.sum (Ξ» (i : β), f (p.coeff i) * f s ^ (p.nat_degree - i + i) * r ^ i) :
finset.sum_congr rfl
(Ξ» i hi, by simp_rw [f.map_mul, f.map_pow, pow_add, mul_pow, mul_assoc])
... = p.support.sum (Ξ» (i : β), f s ^ p.nat_degree * (f (p.coeff i) * r ^ i)) :
finset.sum_congr rfl
(Ξ» i hi, by { rw [mul_assoc, mul_left_comm, nat.sub_add_cancel],
exact le_nat_degree_of_ne_zero (mem_support_iff.mp hi) })
... = f s ^ p.nat_degree * p.support.sum (Ξ» (i : β), (f (p.coeff i) * r ^ i)) : finset.mul_sum.symm
... = f s ^ p.nat_degree * evalβ f r p : by { rw [evalβ_eq_sum], refl }
... = 0 : by rw [hr, _root_.mul_zero]
lemma scale_roots_aeval_eq_zero [algebra S R] {p : polynomial S}
{r : R} {s : S} (hr : aeval r p = 0) :
aeval (algebra_map S R s * r) (scale_roots p s) = 0 :=
scale_roots_evalβ_eq_zero (algebra_map S R) hr
lemma scale_roots_evalβ_eq_zero_of_evalβ_div_eq_zero
{p : polynomial A} {f : A β+* K} (hf : function.injective f)
{r s : A} (hr : evalβ f (f r / f s) p = 0) (hs : s β non_zero_divisors A) :
evalβ f (f r) (scale_roots p s) = 0 :=
begin
convert scale_roots_evalβ_eq_zero f hr,
rw [βmul_div_assoc, mul_comm, mul_div_cancel],
exact @map_ne_zero_of_mem_non_zero_divisors _ _ _ _ _ _ hf β¨s, hsβ©
end
lemma scale_roots_aeval_eq_zero_of_aeval_div_eq_zero [algebra A K]
(inj : function.injective (algebra_map A K)) {p : polynomial A} {r s : A}
(hr : aeval (algebra_map A K r / algebra_map A K s) p = 0) (hs : s β non_zero_divisors A) :
aeval (algebra_map A K r) (scale_roots p s) = 0 :=
scale_roots_evalβ_eq_zero_of_evalβ_div_eq_zero inj hr hs
end scale_roots
|
5f29123c4dc9e7c75dcf07c5675b51993a9cfa30 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/ring/units.lean | 5005f799cbd520200dd7d953d7d25b6a3b591b8d | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 3,537 | 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, Floris van Doorn, Yury Kudryashov, Neil Strickland
-/
import algebra.ring.inj_surj
import algebra.group.units
/-!
# Units in semirings and rings
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> https://github.com/leanprover-community/mathlib4/pull/746
> Any changes to this file require a corresponding PR to mathlib4.
-/
universes u v w x
variables {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} {R : Type x}
open function
namespace units
section has_distrib_neg
variables [monoid Ξ±] [has_distrib_neg Ξ±] {a b : Ξ±}
/-- Each element of the group of units of a ring has an additive inverse. -/
instance : has_neg Ξ±Λ£ := β¨Ξ»u, β¨-βu, -βuβ»ΒΉ, by simp, by simpβ© β©
/-- Representing an element of a ring's unit group as an element of the ring commutes with
mapping this element to its additive inverse. -/
@[simp, norm_cast] protected theorem coe_neg (u : Ξ±Λ£) : (β-u : Ξ±) = -u := rfl
@[simp, norm_cast] protected theorem coe_neg_one : ((-1 : Ξ±Λ£) : Ξ±) = -1 := rfl
instance : has_distrib_neg Ξ±Λ£ := units.ext.has_distrib_neg _ units.coe_neg units.coe_mul
@[field_simps] lemma neg_divp (a : Ξ±) (u : Ξ±Λ£) : -(a /β u) = (-a) /β u :=
by simp only [divp, neg_mul]
end has_distrib_neg
section ring
variables [ring Ξ±] {a b : Ξ±}
@[field_simps] lemma divp_add_divp_same (a b : Ξ±) (u : Ξ±Λ£) :
a /β u + b /β u = (a + b) /β u :=
by simp only [divp, add_mul]
@[field_simps] lemma divp_sub_divp_same (a b : Ξ±) (u : Ξ±Λ£) :
a /β u - b /β u = (a - b) /β u :=
by rw [sub_eq_add_neg, sub_eq_add_neg, neg_divp, divp_add_divp_same]
@[field_simps] lemma add_divp (a b : Ξ±) (u : Ξ±Λ£) : a + b /β u = (a * u + b) /β u :=
by simp only [divp, add_mul, units.mul_inv_cancel_right]
@[field_simps] lemma sub_divp (a b : Ξ±) (u : Ξ±Λ£) : a - b /β u = (a * u - b) /β u :=
by simp only [divp, sub_mul, units.mul_inv_cancel_right]
@[field_simps] lemma divp_add (a b : Ξ±) (u : Ξ±Λ£) : a /β u + b = (a + b * u) /β u :=
by simp only [divp, add_mul, units.mul_inv_cancel_right]
@[field_simps] lemma divp_sub (a b : Ξ±) (u : Ξ±Λ£) : a /β u - b = (a - b * u) /β u :=
begin
simp only [divp, sub_mul, sub_right_inj],
assoc_rw [units.mul_inv, mul_one],
end
end ring
end units
lemma is_unit.neg [monoid Ξ±] [has_distrib_neg Ξ±] {a : Ξ±} : is_unit a β is_unit (-a)
| β¨x, hxβ© := hx βΈ (-x).is_unit
@[simp]
lemma is_unit.neg_iff [monoid Ξ±] [has_distrib_neg Ξ±] (a : Ξ±) : is_unit (-a) β is_unit a :=
β¨Ξ» h, neg_neg a βΈ h.neg, is_unit.negβ©
lemma is_unit.sub_iff [ring Ξ±] {x y : Ξ±} :
is_unit (x - y) β is_unit (y - x) :=
(is_unit.neg_iff _).symm.trans $ neg_sub x y βΈ iff.rfl
namespace units
@[field_simps] lemma divp_add_divp [comm_ring Ξ±] (a b : Ξ±) (uβ uβ : Ξ±Λ£) :
a /β uβ + b /β uβ = (a * uβ + uβ * b) /β (uβ * uβ) :=
begin
simp only [divp, add_mul, mul_inv_rev, coe_mul],
rw [mul_comm (βuβ * b), mul_comm b],
assoc_rw [mul_inv, mul_inv, mul_one, mul_one],
end
@[field_simps] lemma divp_sub_divp [comm_ring Ξ±] (a b : Ξ±) (uβ uβ : Ξ±Λ£) :
(a /β uβ) - (b /β uβ) = ((a * uβ) - (uβ * b)) /β (uβ * uβ) :=
by simp_rw [sub_eq_add_neg, neg_divp, divp_add_divp, mul_neg]
lemma add_eq_mul_one_add_div [semiring R] {a : RΛ£} {b : R} : βa + b = a * (1 + βaβ»ΒΉ * b) :=
by rwa [mul_add, mul_one, β mul_assoc, units.mul_inv, one_mul]
end units
|
359ceac22f0d7d3fd8b923a34a7636d9a892fa44 | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /tests/lean/run/univ_problem.lean | 08d91e52be3e1beee498c883b6ab6360f3bd9364 | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,104 | lean | import logic data.nat.basic data.prod data.unit
open nat prod
inductive vector (A : Type) : nat β Type :=
vnil {} : vector A zero,
vcons : Ξ {n : nat}, A β vector A n β vector A (succ n)
namespace vector
print definition no_confusion
infixr `::` := vcons
namespace play
section
universe variables lβ lβ
variable {A : Type.{lβ}}
variable {C : Ξ (n : nat), vector A n β Type.{lβ+1}}
definition brec_on {n : nat} (v : vector A n) (H : Ξ (n : nat) (v : vector A n), @below A C n v β C n v) : C n v :=
have general : C n v Γ @below A C n v, from
rec_on v
(pair (H zero vnil unit.star) unit.star)
(Ξ» (nβ : nat) (aβ : A) (vβ : vector A nβ) (rβ : C nβ vβ Γ @below A C nβ vβ),
have b : @below A C _ (vcons aβ vβ), from
rβ,
have c : C (succ nβ) (vcons aβ vβ), from
H (succ nβ) (vcons aβ vβ) b,
pair c b),
prβ general
end
end play
print "====================="
definition append {A : Type} {n m : nat} (w : vector A m) (v : vector A n) : vector A (n + m) :=
brec_on w (Ξ» (n : nat) (w : vector A n),
cases_on w
(Ξ» (B : below vnil), v)
(Ξ» (nβ : nat) (aβ : A) (vβ : vector A nβ) (B : below (vcons aβ vβ)),
vcons aβ (prβ B)))
exit
check brec_on
definition bw := @below
definition sum {n : nat} (v : vector nat n) : nat :=
brec_on v (Ξ» (n : nat) (v : vector nat n),
cases_on v
(Ξ» (B : bw vnil), zero)
(Ξ» (nβ : nat) (a : nat) (vβ : vector nat nβ) (B : bw (vcons a vβ)),
a + prβ B))
example : sum (10 :: 20 :: vnil) = 30 :=
rfl
definition addk {n : nat} (v : vector nat n) (k : nat) : vector nat n :=
brec_on v (Ξ» (n : nat) (v : vector nat n),
cases_on v
(Ξ» (B : bw vnil), vnil)
(Ξ» (nβ : nat) (aβ : nat) (vβ : vector nat nβ) (B : bw (vcons aβ vβ)),
vcons (aβ+k) (prβ B)))
example : addk (1 :: 2 :: vnil) 3 = 4 :: 5 :: vnil :=
rfl
example : append (1 :: 2 :: vnil) (3 :: vnil) = 1 :: 2 :: 3 :: vnil :=
rfl
definition head {A : Type} {n : nat} (v : vector A (succ n)) : A :=
cases_on v
(Ξ» H : succ n = 0, nat.no_confusion H)
(Ξ»n' h t (H : succ n = succ n'), h)
rfl
definition tail {A : Type} {n : nat} (v : vector A (succ n)) : vector A n :=
@cases_on A (Ξ»n' v, succ n = n' β vector A (pred n')) (succ n) v
(Ξ» H : succ n = 0, nat.no_confusion H)
(Ξ» (n' : nat) (h : A) (t : vector A n') (H : succ n = succ n'),
t)
rfl
definition add {n : nat} (w v : vector nat n) : vector nat n :=
@brec_on nat (Ξ» (n : nat) (v : vector nat n), vector nat n β vector nat n) n w
(Ξ» (n : nat) (w : vector nat n),
cases_on w
(Ξ» (B : bw vnil) (w : vector nat zero), vnil)
(Ξ» (nβ : nat) (aβ : nat) (vβ : vector nat nβ) (B : bw (vcons aβ vβ)) (v : vector nat (succ nβ)),
vcons (aβ + head v) (prβ B (tail v)))) v
example : add (1 :: 2 :: vnil) (3 :: 5 :: vnil) = 4 :: 7 :: vnil :=
rfl
end vector
|
54e1063173201d6d89b5163b7a7b71b04377a252 | 6b9565799c5c4b76978fc138a9aa7becedecd541 | /library/standard/nat.lean | e97127b5757c291a497085554c764afca048f3ea | [
"Apache-2.0"
] | permissive | leanparikshit/libraries | 657c9c09723523592b1d2021496f6f8041659130 | cbe08140e93fbde4cc81ef212fc65fbe357c5b59 | refs/heads/master | 1,586,305,043,220 | 1,401,535,624,000 | 1,401,535,624,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 39,911 | lean | ----------------------------------------------------------------------------------------------------
-- Copyright (c) 2014 Floris van Doorn. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Author: Floris van Doorn
----------------------------------------------------------------------------------------------------
--TODO:
--more about minus
--replace positivity requirement (succ _ ==> _ > 0)
-------------------------------------------------- axioms
import kernel
import macros
variable nat : Type
alias β : nat
--builtin numeral -- When transitioning to numerals, first replace "(succ zero)" and "succ zero" by "1" and then "zero" by "0" (except in names)
namespace nat
variable zero : nat
alias z : zero
variable succ : nat -> nat
alias s : succ
axiom nat_rec {P : nat β Type} (x : P zero) (f : βm : nat, P m β P (s m)) (m:nat) : P m
axiom nat_rec_zero {P : nat β Type} (x : P zero) (f : βm : nat, P m β P (s m)) :
nat_rec x f zero = x
axiom nat_rec_succ {P : nat β Type} (x : P zero) (f : βm : nat, P m β P (s m)) (n : nat) :
nat_rec x f (succ n) = f n (nat_rec x f n)
-------------------------------------------------- succ pred
theorem induction_on {P : nat β Bool} (a : nat) (H1 : P zero)
(H2 : β (n : nat) (IH : P n), P (succ n)) : P a
:= nat_rec H1 H2 a
theorem succ_ne_zero (n : nat) : succ n β zero
:=
not_intro
(take H : succ n = zero,
have H2 : true = false, from
(let f : nat -> Bool := (nat_rec false (fun a b,true))
in calc
true = f (succ n) : symm (nat_rec_succ _ _ _)
... = f zero : {H}
... = false : nat_rec_zero _ _),
absurd H2 true_ne_false)
definition pred (n : nat) := nat_rec zero (fun m x, m) n
theorem pred_zero : pred zero = zero
:= nat_rec_zero _ _
theorem pred_succ (n : nat) : pred (succ n) = n
:= nat_rec_succ _ _ _
set_opaque pred true
theorem zero_or_succ (n : nat) : n = zero β¨ n = succ (pred n)
:=
induction_on n
(or_intro_left _ (refl zero))
(take m IH, or_intro_right _
(show succ m = succ (pred (succ m)), from congr2 succ (symm (pred_succ m))))
theorem zero_or_succ2 (n : nat) : n = zero β¨ βk, n = succ k
:= or_imp_or (zero_or_succ n) (assume H, H) (assume H : n = succ (pred n), exists_intro (pred n) H)
theorem nat_case {P : nat β Bool} (n : nat) (H1: P zero) (H2 : βm, P (succ m)) : P n
:=
induction_on n H1 (take m IH, H2 m)
theorem nat_discriminate {B : Bool} {n : nat} (H1: n = zero β B) (H2 : βm, n = succ m β B) : B
:=
or_elim (zero_or_succ n)
(take H3 : n = zero, H1 H3)
(take H3 : n = succ (pred n), H2 (pred n) H3)
theorem succ_inj {n m : nat} (H : succ n = succ m) : n = m
:=
calc
n = pred (succ n) : symm (pred_succ n)
... = pred (succ m) : {H}
... = m : pred_succ m
theorem succ_ne_self (n : nat) : succ n β n
:=
not_intro (induction_on n
(take H : succ zero = zero,
have ne : succ zero β zero, from succ_ne_zero zero,
absurd H ne)
(take k IH H, IH (succ_inj H)))
theorem decidable_equality (n m : nat) : n = m β¨ n β m
:=
have general : βn, n = m β¨ n β m, from
induction_on m
(take n : nat,
nat_discriminate
(assume H : n = zero, or_intro_left _ H)
(take l : nat,
assume H : n = succ l,
have H2 : n β zero, from subst (succ_ne_zero l) (symm H),
or_intro_right _ H2))
(take k : nat,
assume IH : βn, n = k β¨ n β k,
take n : nat,
nat_discriminate
(assume H : n = zero,
have H2 : n β succ k, from subst (ne_symm (succ_ne_zero k)) (symm H),
or_intro_right _ H2)
(take l : nat,
assume H : n = succ l,
or_imp_or (IH l)
(take H2 : l = k,
show n = succ k, from trans H (congr2 succ H2))
(take H2 : l β k,
show n β succ k, from
not_intro
(take H4 : n = succ k,
have H5 : succ l = succ k, from trans (symm H) H4,
have H6 : l = k, from succ_inj H5,
absurd H6 H2)))),
general n
theorem two_step_induction_on {P : nat β Bool} (a : nat) (H1 : P zero) (H2 : P (succ zero))
(H3 : β (n : nat) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : P a
:=
have stronger : P a β§ P (succ a), from
induction_on a
(and_intro H1 H2)
(take k IH,
have IH1 : P k, from and_elim_left IH,
have IH2 : P (succ k), from and_elim_right IH,
and_intro IH2 (H3 k IH1 IH2)),
and_elim_left stronger
--theorem nat_double_induction {P : nat β nat β Bool} (n m : nat) (H1 : βn, P zero n)
-- (H2 : βn, P (succ n) zero) (H3 : βn m, P n m β P (succ n) (succ m)) : P n m
--:= _
-------------------------------------------------- add
definition add (n m : nat) := nat_rec n (fun k x, succ x) m
infixl 65 + : add
theorem add_zero_right (n:nat) : n + zero = n
:= nat_rec_zero _ _
theorem add_succ_right (n m:nat) : n + succ m = succ (n + m)
:= nat_rec_succ _ _ _
set_opaque add true
---------- comm, assoc
theorem add_zero_left (n:nat) : zero + n = n
:=
induction_on n
(add_zero_right zero)
(take m IH, show zero + succ m = succ m, from
calc
zero + succ m = succ (zero + m) : add_succ_right _ _
... = succ m : {IH})
theorem add_succ_left (n m:nat) : (succ n) + m = succ (n + m)
:=
induction_on m
(calc
succ n + zero = succ n : add_zero_right (succ n)
... = succ (n + zero) : {symm (add_zero_right n)})
(take k IH,
calc
succ n + succ k = succ (succ n + k) : add_succ_right _ _
... = succ (succ (n + k)) : {IH}
... = succ (n + succ k) : {symm (add_succ_right _ _)})
theorem add_comm (n m:nat) : n + m = m + n
:=
induction_on m
(trans (add_zero_right _) (symm (add_zero_left _)))
(take k IH,
calc
n + succ k = succ (n+k) : add_succ_right _ _
... = succ (k + n) : {IH}
... = succ k + n : symm (add_succ_left _ _))
theorem add_move_succ (n m:nat) : succ n + m = n + succ m
:=
calc
succ n + m = succ (n + m) : add_succ_left n m
... = n +succ m : symm (add_succ_right n m)
theorem add_comm_succ (n m:nat) : n + succ m = m + succ n
:=
calc
n + succ m = succ n + m : symm (add_move_succ n m)
... = m + succ n : add_comm (succ n) m
theorem add_assoc (n m k:nat) : (n + m) + k = n + (m + k)
:=
induction_on k
(calc
(n + m) + zero = n + m : add_zero_right _
... = n + (m + zero) : {symm (add_zero_right m)})
(take l IH,
calc
(n + m) + succ l = succ ((n + m) + l) : add_succ_right _ _
... = succ (n + (m + l)) : {IH}
... = n + succ (m + l) : symm (add_succ_right _ _)
... = n + (m + succ l) : {symm (add_succ_right _ _)})
theorem add_comm_left (n m k : nat) : n + (m + k) = m + (n + k)
:= left_comm add_comm add_assoc n m k
theorem add_comm_right (n m k : nat) : n + m + k = n + k + m
:= right_comm add_comm add_assoc n m k
---------- inversion
theorem add_right_inj {n m k : nat} : n + m = n + k β m = k
:=
induction_on n
(take H : zero + m = zero + k,
calc
m = zero + m : symm (add_zero_left m)
... = zero + k : H
... = k : add_zero_left k)
(take (n : nat) (IH : n + m = n + k β m = k) (H : succ n + m = succ n + k),
have H2 : succ (n + m) = succ (n + k),
from calc
succ (n + m) = succ n + m : symm (add_succ_left n m)
... = succ n + k : H
... = succ (n + k) : add_succ_left n k,
have H3 : n + m = n + k, from succ_inj H2,
IH H3)
theorem add_left_inj {n m k : nat} (H : n + m = k + m) : n = k
:=
have H2 : m + n = m + k,
from calc
m + n = n + m : add_comm m n
... = k + m : H
... = m + k : add_comm k m,
add_right_inj H2
theorem add_eq_zero_left {n m : nat} : n + m = zero β n = zero
:=
induction_on n
(take (H : zero + m = zero), refl zero)
(take k IH,
assume (H : succ k + m = zero),
absurd_elim (succ k = zero)
(show succ (k + m) = zero, from
calc
succ (k + m) = succ k + m : symm (add_succ_left k m)
... = zero : H)
(succ_ne_zero (k + m)))
theorem add_eq_zero_right {n m : nat} (H : n + m = zero) : m = zero
:= add_eq_zero_left (trans (add_comm m n) H)
theorem add_eq_zero {n m : nat} (H : n + m = zero) : n = zero β§ m = zero
:= and_intro (add_eq_zero_left H) (add_eq_zero_right H)
-- add_eq_self below
---------- misc
theorem add_one (n:nat) : n + succ zero = succ n
:=
calc
n + succ zero = succ (n + zero) : add_succ_right _ _
... = succ n : {add_zero_right _}
theorem add_one_left (n:nat) : succ zero + n = succ n
:=
calc
succ zero + n = succ (zero + n) : add_succ_left _ _
... = succ n : {add_zero_left _}
--the following theorem has a terrible name, but since the name is not a substring or superstring of another name, it is at least easy to globally replace it
theorem induction_plus_one {P : nat β Bool} (a : nat) (H1 : P zero)
(H2 : β (n : nat) (IH : P n), P (n + succ zero)) : P a
:= nat_rec H1 (take n IH, subst (H2 n IH) (add_one n)) a
-------------------------------------------------- mul
definition mul (n m : nat) := nat_rec zero (fun m x, x + n) m
infixl 70 * : mul
theorem mul_zero_right (n:nat) : n * zero = zero
:= nat_rec_zero _ _
theorem mul_succ_right (n m:nat) : n * succ m = n * m + n
:= nat_rec_succ _ _ _
set_opaque mul true
---------- comm, distr, assoc, identity
theorem mul_zero_left (n:nat) : zero * n = zero
:=
induction_on n
(mul_zero_right zero)
(take m IH,
calc
zero * succ m = zero * m + zero : mul_succ_right _ _
... = zero * m : add_zero_right _
... = zero : IH)
theorem mul_succ_left (n m:nat) : (succ n) * m = (n * m) + m
:=
induction_on m
(calc
succ n * zero = zero : mul_zero_right _
... = n * zero : symm (mul_zero_right _)
... = n * zero + zero : symm (add_zero_right _))
(take k IH,
calc
succ n * succ k = (succ n * k) + succ n : mul_succ_right _ _
... = (n * k) + k + succ n : { IH }
... = (n * k) + (k + succ n) : add_assoc _ _ _
-- ... = (n * k) + succ (k + n) : {add_succ_right _ _}
-- ... = (n * k) + (succ k + n) : {symm (add_succ_left _ _)}
-- ... = (n * k) + (n + succ k) : {add_comm _ _}
--use either next line or three previous lines
... = (n * k) + (n + succ k) : {add_comm_succ _ _}
... = (n * k) + n + succ k : symm (add_assoc _ _ _)
... = (n * succ k) + succ k : {symm (mul_succ_right n k)})
theorem mul_comm (n m:nat) : n * m = m * n
:=
induction_on m
(trans (mul_zero_right _) (symm (mul_zero_left _)))
(take k IH,
calc
n * succ k = n * k + n : mul_succ_right _ _
... = k * n + n : {IH}
... = (succ k) * n : symm (mul_succ_left _ _))
theorem mul_add_distr_left (n m k : nat) : (n + m) * k = n * k + m * k
:=
induction_on k
(calc
(n + m) * zero = zero : mul_zero_right _
... = zero + zero : symm (add_zero_right _)
... = n * zero + zero : {symm (mul_zero_right _)}
... = n * zero + m * zero : {symm (mul_zero_right _)})
(take l IH,
calc
(n + m) * succ l = (n + m) * l + (n + m) : mul_succ_right _ _
... = n * l + m * l + (n + m) : {IH}
... = n * l + m * l + n + m : symm (add_assoc _ _ _)
... = n * l + n + m * l + m : {add_comm_right _ _ _}
... = n * l + n + (m * l + m) : add_assoc _ _ _
... = n * succ l + (m * l + m) : {symm (mul_succ_right _ _)}
... = n * succ l + m * succ l : {symm (mul_succ_right _ _)})
theorem mul_add_distr_right (n m k : nat) : n * (m + k) = n * m + n * k
:=
calc
n * (m + k) = (m + k) * n : mul_comm _ _
... = m * n + k * n : mul_add_distr_left _ _ _
... = n * m + k * n : {mul_comm _ _}
... = n * m + n * k : {mul_comm _ _}
theorem mul_assoc (n m k:nat) : (n * m) * k = n * (m * k)
:=
induction_on k
(calc
(n * m) * zero = zero : mul_zero_right _
... = n * zero : symm (mul_zero_right _)
... = n * (m * zero) : {symm (mul_zero_right _)})
(take l IH,
calc
(n * m) * succ l = (n * m) * l + n * m : mul_succ_right _ _
... = n * (m * l) + n * m : {IH}
... = n * (m * l + m) : symm (mul_add_distr_right _ _ _)
... = n * (m * succ l) : {symm (mul_succ_right _ _)})
theorem mul_comm_left (n m k : nat) : n * (m * k) = m * (n * k)
:= left_comm mul_comm mul_assoc n m k
theorem mul_comm_right (n m k : nat) : n * m * k = n * k * m
:= right_comm mul_comm mul_assoc n m k
theorem mul_one_right (n : nat) : n * succ zero = n
:=
calc
n * succ zero = n * zero + n : mul_succ_right n zero
... = zero + n : {mul_zero_right n}
... = n : add_zero_left n
theorem mul_one_left (n : nat) : succ zero * n = n
:=
calc
succ zero * n = n * succ zero : mul_comm _ _
... = n : mul_one_right n
---------- inversion
theorem mul_eq_zero {n m : nat} (H : n * m = zero) : n = zero β¨ m = zero
:=
nat_discriminate
(take Hn : n = zero, or_intro_left _ Hn)
(take (k : nat),
assume (Hk : n = succ k),
nat_discriminate
(take (Hm : m = zero), or_intro_right _ Hm)
(take (l : nat),
assume (Hl : m = succ l),
have Heq : succ (k * succ l + l) = n * m, from
symm (calc
n * m = n * succ l : { Hl }
... = succ k * succ l : { Hk }
... = k * succ l + succ l : mul_succ_left _ _
... = succ (k * succ l + l) : add_succ_right _ _),
absurd_elim _ (trans Heq H) (succ_ne_zero _)))
theorem mul_eq_succ_left {n m k : nat} (H : n * m = succ k) : exists l, n = succ l
:=
nat_discriminate
(assume H2 : n = zero,
absurd_elim _
(calc
succ k = n * m : symm H
... = zero * m : {H2}
... = zero : mul_zero_left m)
(succ_ne_zero k))
(take l Hl, exists_intro l Hl)
theorem mul_eq_succ_right {n m k : nat} (H : n * m = succ k) : exists l, m = succ l
:= mul_eq_succ_left (subst H (mul_comm n m))
theorem mul_left_inj {n m k : nat} (H : succ n * m = succ n * k) : m = k
:=
have general : β m, succ n * m = succ n * k β m = k, from
induction_on k
(take m:nat,
assume H : succ n * m = succ n * zero,
have H2 : succ n * m = zero,
from calc
succ n * m = succ n * zero : H
... = zero : mul_zero_right (succ n),
have H3 : succ n = zero β¨ m = zero, from mul_eq_zero H2,
resolve_right H3 (succ_ne_zero n))
(take (l : nat),
assume (IH : β m, succ n * m = succ n * l β m = l),
take (m : nat),
assume (H : succ n * m = succ n * succ l),
have H2 : succ n * m = succ (succ n * l + n),
from calc
succ n * m = succ n * succ l : H
... = succ n * l + succ n : mul_succ_right (succ n) l
... = succ (succ n * l + n) : add_succ_right _ n,
obtain (l2:nat) (Hm : m = succ l2), from mul_eq_succ_right H2,
have H3 : succ n * l2 + succ n = succ n * l + succ n,
from calc
succ n * l2 + succ n = succ n * succ l2 : symm (mul_succ_right (succ n) l2)
... = succ n * m : {symm Hm}
... = succ n * succ l : H
... = succ n * l + succ n : mul_succ_right (succ n) l,
have H4 : succ n * l2 = succ n * l, from add_left_inj H3,
calc
m = succ l2 : Hm
... = succ l : {IH l2 H4}),
general m H
theorem mul_right_inj {n m k : nat} (H : n * succ m = k * succ m) : n = k
:=
have H2 : succ m * n = succ m * k,
from calc
succ m * n = n * succ m : mul_comm (succ m) n
... = k * succ m : H
... = succ m * k : mul_comm k (succ m),
mul_left_inj H2
theorem mul_eq_one_left {n m : nat} (H : n * m = succ zero) : n = succ zero
:=
obtain (k : nat) (Hm : m = succ k), from (mul_eq_succ_right H),
obtain (l1 : nat) (Hn : n = succ l1), from (mul_eq_succ_left H),
nat_discriminate
(take Hl : l1 = zero,
calc
n = succ l1 : Hn
... = succ zero : {Hl})
(take (l2 : nat),
assume (Hl : l1 = succ l2),
have H2 : succ zero = succ (succ (succ (succ l2) * k + l2)),
from calc
succ zero = n * m : symm H
... = n * succ k : { Hm }
... = succ l1 * succ k : { Hn }
... = succ (succ l2) * succ k : { Hl }
... = succ (succ l2) * k + succ (succ l2) : { mul_succ_right _ _ }
... = succ (succ (succ l2) * k + succ l2): add_succ_right _ _
... = succ (succ (succ (succ l2) * k + l2)) : { add_succ_right _ _ },
have H3 : zero = succ (succ (succ l2) * k + l2), from succ_inj H2,
absurd_elim _ (symm H3) (succ_ne_zero _))
theorem mul_eq_one_right {n m : nat} (H : n * m = succ zero) : m = succ zero
:= mul_eq_one_left (subst H (mul_comm n m))
theorem mul_eq_one {n m : nat} (H : n * m = succ zero) : n = succ zero β§ m = succ zero
:= and_intro (mul_eq_one_left H) (mul_eq_one_right H)
-------------------------------------------------- le
definition le (n m:nat) : Bool := exists k:nat, n + k = m
infix 50 <= : le
infix 50 β€ : le
theorem le_intro {n m k : nat} (H : n + k = m) : n β€ m
:= exists_intro k H
theorem le_elim {n m : nat} (H : n β€ m) : β k, n + k = m
:= H
set_opaque le true
---------- partial order (totality is part of lt)
theorem le_intro2 (n m : nat) : n β€ n + m
:= le_intro (refl (n + m))
theorem le_refl (n : nat) : n β€ n
:= le_intro (add_zero_right n)
theorem le_zero (n : nat) : zero β€ n
:= le_intro (add_zero_left n)
theorem le_zero_inv {n:nat} (H : n β€ zero) : n = zero
:=
obtain (k : nat) (Hk : n + k = zero), from le_elim H,
add_eq_zero_left Hk
theorem le_trans {n m k : nat} (H1 : n β€ m) (H2 : m β€ k) : n β€ k
:=
obtain (l1 : nat) (Hl1 : n + l1 = m), from le_elim H1,
obtain (l2 : nat) (Hl2 : m + l2 = k), from le_elim H2,
le_intro
(calc
n + (l1 + l2) = n + l1 + l2 : symm (add_assoc n l1 l2)
... = m + l2 : { Hl1 }
... = k : Hl2)
theorem le_antisym {n m : nat} (H1 : n β€ m) (H2 : m β€ n) : n = m
:=
obtain (k : nat) (Hk : n + k = m), from (le_elim H1),
obtain (l : nat) (Hl : m + l = n), from (le_elim H2),
have L1 : k + l = zero, from
add_right_inj
(calc
n + (k + l) = n + k + l : { symm (add_assoc n k l) }
... = m + l : { Hk }
... = n : Hl
... = n + zero : symm (add_zero_right n)),
have L2 : k = zero, from add_eq_zero_left L1,
calc
n = n + zero : symm (add_zero_right n)
... = n + k : { symm L2 }
... = m : Hk
---------- interaction with add
theorem add_le_left {n m : nat} (H : n β€ m) (k : nat) : k + n β€ k + m
:=
obtain (l : nat) (Hl : n + l = m), from (le_elim H),
le_intro
(calc
k + n + l = k + (n + l) : add_assoc k n l
... = k + m : { Hl })
theorem add_le_right {n m : nat} (H : n β€ m) (k : nat) : n + k β€ m + k
:= subst (subst (add_le_left H k) (add_comm k n)) (add_comm k m)
theorem add_le {n m k l : nat} (H1 : n β€ k) (H2 : m β€ l) : n + m β€ k + l
:= le_trans (add_le_right H1 m) (add_le_left H2 k)
theorem add_le_left_inv {n m k : nat} (H : k + n β€ k + m) : n β€ m
:=
obtain (l : nat) (Hl : k + n + l = k + m), from (le_elim H),
le_intro (add_right_inj
calc
k + (n + l) = k + n + l : symm (add_assoc k n l)
... = k + m : Hl )
theorem add_le_right_inv {n m k : nat} (H : n + k β€ m + k) : n β€ m
:= add_le_left_inv (subst (subst H (add_comm n k)) (add_comm m k))
---------- interaction with succ and pred
theorem succ_le {n m : nat} (H : n β€ m) : succ n β€ succ m
:= subst (subst (add_le_right H (succ zero)) (add_one n)) (add_one m)
theorem succ_le_inv {n m : nat} (H : succ n β€ succ m) : n β€ m
:= add_le_right_inv (subst (subst H (symm (add_one n))) (symm (add_one m)))
theorem le_self_succ (n : nat) : n β€ succ n
:= le_intro (add_one n)
theorem succ_le_right {n m : nat} (H : n β€ m) : n β€ succ m
:= le_trans H (le_self_succ m)
theorem succ_le_left_or {n m : nat} (H : n β€ m) : succ n β€ m β¨ n = m
:=
obtain (k : nat) (Hk : n + k = m), from (le_elim H),
nat_discriminate
(assume H3 : k = zero,
have Heq : n = m,
from calc
n = n + zero : symm (add_zero_right n)
... = n + k : {symm H3}
... = m : Hk,
or_intro_right _ Heq)
(take l:nat,
assume H3 : k = succ l,
have Hlt : succ n β€ m, from
(le_intro
(calc
succ n + l = n + succ l : add_move_succ n l
... = n + k : {symm H3}
... = m : Hk)),
or_intro_left _ Hlt)
theorem succ_le_left {n m : nat} (H1 : n β€ m) (H2 : n β m) : succ n β€ m
:= resolve_left (succ_le_left_or H1) H2
theorem succ_le_right_inv {n m : nat} (H : n β€ succ m) : n β€ m β¨ n = succ m
:=
or_imp_or (succ_le_left_or H)
(take H2 : succ n β€ succ m, show n β€ m, from succ_le_inv H2)
(take H2 : n = succ m, H2)
theorem succ_le_left_inv {n m : nat} (H : succ n β€ m) : n β€ m β§ n β m
:=
obtain (k : nat) (H2 : succ n + k = m), from (le_elim H),
and_intro
(have H3 : n + succ k = m,
from calc
n + succ k = succ n + k : symm (add_move_succ n k)
... = m : H2,
show n β€ m, from le_intro H3)
(not_intro
(assume H3 : n = m,
have H4 : succ n β€ n, from subst H (symm H3),
have H5 : succ n = n, from le_antisym H4 (le_self_succ n),
show false, from absurd H5 (succ_ne_self n)))
theorem le_pred_self (n : nat) : pred n β€ n
:=
nat_case n
(subst (le_refl zero) (symm pred_zero))
(take k : nat, subst (le_self_succ k) (symm (pred_succ k)))
theorem pred_le {n m : nat} (H : n β€ m) : pred n β€ pred m
:=
nat_discriminate
(take Hn : n = zero,
have H2 : pred n = zero,
from calc
pred n = pred zero : {Hn}
... = zero : pred_zero,
subst (le_zero (pred m)) (symm H2))
(take k : nat,
assume Hn : n = succ k,
obtain (l : nat) (Hl : n + l = m), from le_elim H,
have H2 : pred n + l = pred m,
from calc
pred n + l = pred (succ k) + l : {Hn}
... = k + l : {pred_succ k}
... = pred (succ (k + l)) : symm (pred_succ (k + l))
... = pred (succ k + l) : {symm (add_succ_left k l)}
... = pred (n + l) : {symm Hn}
... = pred m : {Hl},
le_intro H2)
theorem pred_le_left_inv {n m : nat} (H : pred n β€ m) : n β€ m β¨ n = succ m
:=
nat_discriminate
(take Hn : n = zero,
or_intro_left _ (subst (le_zero m) (symm Hn)))
(take k : nat,
assume Hn : n = succ k,
have H2 : pred n = k,
from calc
pred n = pred (succ k) : {Hn}
... = k : pred_succ k,
have H3 : k β€ m, from subst H H2,
have H4 : succ k β€ m β¨ k = m, from succ_le_left_or H3,
show n β€ m β¨ n = succ m, from
or_imp_or H4
(take H5 : succ k β€ m, show n β€ m, from subst H5 (symm Hn))
(take H5 : k = m, show n = succ m, from subst Hn H5))
---------- interaction with mul
theorem mul_le_left {n m : nat} (H : n β€ m) (k : nat) : k * n β€ k * m
:=
obtain (l : nat) (Hl : n + l = m), from (le_elim H),
induction_on k
(have H2 : zero * n = zero * m,
from calc
zero * n = zero : mul_zero_left n
... = zero * m : symm (mul_zero_left m),
show zero * n β€ zero * m, from subst (le_refl (zero * n)) H2)
(take (l : nat),
assume IH : l * n β€ l * m,
have H2 : l * n + n β€ l * m + m, from add_le IH H,
have H3 : succ l * n β€ l * m + m, from subst H2 (symm (mul_succ_left l n)),
show succ l * n β€ succ l * m, from subst H3 (symm (mul_succ_left l m)))
theorem mul_le_right {n m : nat} (H : n β€ m) (k : nat) : n * k β€ m * k
:= subst (subst (mul_le_left H k) (mul_comm k n)) (mul_comm k m)
theorem mul_le {n m k l : nat} (H1 : n β€ k) (H2 : m β€ l) : n * m β€ k * l
:= le_trans (mul_le_right H1 m) (mul_le_left H2 k)
-- mul_le_[left|right]_inv below
-------------------------------------------------- lt
definition lt (n m : nat) := succ n β€ m
infix 50 < : lt
theorem lt_intro {n m k : nat} (H : succ n + k = m) : n < m
:= le_intro H
theorem lt_elim {n m : nat} (H : n < m) : β k, succ n + k = m
:= le_elim H
theorem lt_intro2 (n m : nat) : n < n + succ m
:= lt_intro (add_move_succ n m)
---------- basic facts
theorem lt_ne {n m : nat} (H : n < m) : n β m
:= and_elim_right (succ_le_left_inv H)
theorem lt_irrefl (n : nat) : Β¬ n < n
:= not_intro (assume H : n < n, absurd (refl n) (lt_ne H))
theorem lt_zero (n : nat) : zero < succ n
:= succ_le (le_zero n)
theorem lt_zero_inv (n : nat) : Β¬ n < zero
:=
not_intro
(assume H : n < zero,
have H2 : succ n = zero, from le_zero_inv H,
absurd H2 (succ_ne_zero n))
theorem lt_positive {n m : nat} (H : n < m) : exists k, m = succ k
:=
nat_discriminate
(take (Hm : m = zero), absurd_elim _ (subst H Hm) (lt_zero_inv n))
(take (l : nat) (Hm : m = succ l), exists_intro l Hm)
---------- interaction with le
theorem lt_le_succ {n m : nat} (H : n < m) : succ n β€ m
:= H
theorem le_succ_lt {n m : nat} (H : succ n β€ m) : n < m
:= H
theorem lt_le {n m : nat} (H : n < m) : n β€ m
:= and_elim_left (succ_le_left_inv H)
theorem le_lt_or {n m : nat} (H : n β€ m) : n < m β¨ n = m
:= succ_le_left_or H
theorem le_lt {n m : nat} (H1 : n β€ m) (H2 : n β m) : n < m
:= succ_le_left H1 H2
theorem le_lt_succ {n m : nat} (H : n β€ m) : n < succ m
:= succ_le H
theorem lt_succ_le {n m : nat} (H : n < succ m) : n β€ m
:= succ_le_inv H
---------- trans, antisym
theorem lt_le_trans {n m k : nat} (H1 : n < m) (H2 : m β€ k) : n < k
:= le_trans H1 H2
theorem lt_trans {n m k : nat} (H1 : n < m) (H2 : m < k) : n < k
:= lt_le_trans H1 (lt_le H2)
theorem le_lt_trans {n m k : nat} (H1 : n β€ m) (H2 : m < k) : n < k
:= le_trans (succ_le H1) H2
theorem lt_antisym {n m : nat} (H : n < m) : Β¬ m < n
:= not_intro (take H2 : m < n, absurd (lt_trans H H2) (lt_irrefl n))
---------- interaction with add
theorem add_lt_left {n m : nat} (H : n < m) (k : nat) : k + n < k + m
:= @subst _ _ _ (fun x, x β€ k + m) (add_le_left H k) (add_succ_right k n)
theorem add_lt_right {n m : nat} (H : n < m) (k : nat) : n + k < m + k
:= subst (subst (add_lt_left H k) (add_comm k n)) (add_comm k m)
theorem add_le_lt {n m k l : nat} (H1 : n β€ k) (H2 : m < l) : n + m < k + l
:= le_lt_trans (add_le_right H1 m) (add_lt_left H2 k)
theorem add_lt_le {n m k l : nat} (H1 : n < k) (H2 : m β€ l) : n + m < k + l
:= lt_le_trans (add_lt_right H1 m) (add_le_left H2 k)
theorem add_lt {n m k l : nat} (H1 : n < k) (H2 : m < l) : n + m < k + l
:= add_lt_le H1 (lt_le H2)
theorem add_lt_left_inv {n m k : nat} (H : k + n < k + m) : n < m
:= add_le_left_inv (subst H (symm (add_succ_right k n)))
theorem add_lt_right_inv {n m k : nat} (H : n + k < m + k) : n < m
:= add_lt_left_inv (subst (subst H (add_comm n k)) (add_comm m k))
---------- interaction with succ (see also the interaction with le)
theorem succ_lt {n m : nat} (H : n < m) : succ n < succ m
:= subst (subst (add_lt_right H (succ zero)) (add_one n)) (add_one m)
theorem succ_lt_inv {n m : nat} (H : succ n < succ m) : n < m
:= add_lt_right_inv (subst (subst H (symm (add_one n))) (symm (add_one m)))
theorem lt_self_succ (n : nat) : n < succ n
:= le_refl (succ n)
theorem succ_lt_right {n m : nat} (H : n < m) : n < succ m
:= lt_trans H (lt_self_succ m)
---------- totality of lt and le
theorem le_or_lt (n m : nat) : n β€ m β¨ m < n
:=
induction_on n
(or_intro_left _ (le_zero m))
(take (k : nat),
assume IH : k β€ m β¨ m < k,
or_elim IH
(assume H : k β€ m,
obtain (l : nat) (Hl : k + l = m), from le_elim H,
nat_discriminate
(assume H2 : l = zero,
have H3 : m = k,
from calc
m = k + l : symm Hl
... = k + zero : {H2}
... = k : add_zero_right k,
have H4 : m < succ k, from subst (lt_self_succ m) H3,
or_intro_right _ H4)
(take l2 : nat,
assume H2 : l = succ l2,
have H3 : succ k + l2 = m,
from calc
succ k + l2 = k + succ l2 : add_move_succ k l2
... = k + l : {symm H2}
... = m : Hl,
or_intro_left _ (le_intro H3)))
(assume H : m < k, or_intro_right _ (succ_lt_right H)))
theorem trichotomy_alt (n m : nat) : (n < m β¨ n = m) β¨ m < n
:= or_imp_or (le_or_lt n m) (assume H : n β€ m, le_lt_or H) (assume H : m < n, H)
theorem trichotomy (n m : nat) : n < m β¨ n = m β¨ m < n
:= iff_elim_left (or_assoc _ _ _) (trichotomy_alt n m)
theorem le_total (n m : nat) : n β€ m β¨ m β€ n
:= or_imp_or (le_or_lt n m) (assume H : n β€ m, H) (assume H : m < n, lt_le H)
---------- interaction with mul
theorem mul_lt_left {n m : nat} (H : n < m) (k : nat) : succ k * n < succ k * m
:=
have H2 : succ k * n < succ k * n + succ k, from lt_intro2 _ _,
have H3 : succ k * n + succ k β€ succ k * m,
from subst (mul_le_left H (succ k)) (mul_succ_right (succ k) n),
lt_le_trans H2 H3
theorem mul_lt_right {n m : nat} (H : n < m) (k : nat) : n * succ k < m * succ k
:= subst (subst (mul_lt_left H k) (mul_comm (succ k) n)) (mul_comm (succ k) m)
theorem mul_le_lt {n m k l : nat} (H1 : n β€ succ k) (H2 : m < l) : n * m < succ k * l
:= le_lt_trans (mul_le_right H1 m) (mul_lt_left H2 k)
theorem mul_lt_le {n m k l : nat} (H1 : n < k) (H2 : m β€ succ l) : n * m < k * succ l
:= le_lt_trans (mul_le_left H2 n) (mul_lt_right H1 l)
theorem mul_lt {n m k l : nat} (H1 : n < k) (H2 : m < l) : n * m < k * l
:=
obtain (k2 : nat) (Hk : k = succ k2), from lt_positive H1,
have H3 : n * m β€ k * m, from mul_le_right (lt_le H1) m,
have H4 : k * m < k * l, from subst (mul_lt_left H2 k2) (symm Hk),
le_lt_trans H3 H4
theorem mul_lt_left_inv {n m k : nat} (H : k * n < k * m) : n < m
:=
have general : β m, k * n < k * m β n < m, from
induction_on n
(take m : nat,
assume H2 : k * zero < k * m,
obtain (l : nat) (Hl : k * m = succ l), from lt_positive H2,
obtain (l2 : nat) (Hl2 : m = succ l2), from mul_eq_succ_right Hl,
show zero < m, from subst (lt_zero l2) (symm Hl2))
(take l : nat,
assume IH : β m, k * l < k * m β l < m,
take m : nat,
assume H2 : k * succ l < k * m,
obtain (l' : nat) (Hl : k * m = succ l'), from lt_positive H2,
obtain (l2 : nat) (Hl2 : m = succ l2), from mul_eq_succ_right Hl,
have H3 : k * l + k < k * m, from subst H2 (mul_succ_right k l),
have H4 : k * l + k < k * succ l2, from subst H3 Hl2,
have H5 : k * l + k < k * l2 + k, from subst H4 (mul_succ_right k l2),
have H6 : k * l < k * l2, from add_lt_right_inv H5,
have H7 : l < l2, from IH l2 H6,
have H8 : succ l < succ l2, from succ_lt H7,
show succ l < m, from subst H8 (symm Hl2)),
general m H
theorem mul_lt_right_inv {n m k : nat} (H : n * k < m * k) : n < m
:= mul_lt_left_inv (subst (subst H (mul_comm n k)) (mul_comm m k))
theorem mul_le_left_inv {n m k : nat} (H : succ k * n β€ succ k * m) : n β€ m
:=
have H2 : succ k * n < succ k * m + succ k, from le_lt_trans H (lt_intro2 _ _),
have H3 : succ k * n < succ k * succ m, from subst H2 (symm (mul_succ_right (succ k) m)),
have H4 : n < succ m, from mul_lt_left_inv H3,
show n β€ m, from lt_succ_le H4
theorem mul_le_right_inv {n m k : nat} (H : n * succ m β€ k * succ m) : n β€ k
:= mul_le_left_inv (subst (subst H (mul_comm n (succ m))) (mul_comm k (succ m)))
theorem strong_induction {P : nat β Bool} (n : nat) (IH : βn, (βm, m < n β P m) β P n) : P n
:=
have stronger : βk, k β€ n β P k, from
induction_on n
(take (k : nat),
assume H : k β€ zero,
have H2 : k = zero, from le_zero_inv H,
have H3 : βm, m < k β P m, from
(take m : nat,
assume H4 : m < k,
have H5 : m < zero, from subst H4 H2,
absurd_elim _ H5 (lt_zero_inv m)),
show P k, from IH k H3)
(take l : nat,
assume IHl : βk, k β€ l β P k,
take k : nat,
assume H : k β€ succ l,
or_elim (succ_le_right_inv H)
(assume H2 : k β€ l, show P k, from IHl k H2)
(assume H2 : k = succ l,
have H3 : βm, m < k β P m, from
(take m : nat,
assume H4 : m < k,
have H5 : m β€ l, from lt_succ_le (subst H4 H2),
show P m, from IHl m H5),
show P k, from IH k H3)),
stronger n (le_refl n)
theorem add_eq_self {n m : nat} (H : n + m = n) : m = zero
:=
nat_discriminate
(take Hm : m = zero, Hm)
(take k : nat,
assume Hm : m = succ k,
have H2 : succ n + k = n,
from calc
succ n + k = n + succ k : add_move_succ n k
... = n + m : {symm Hm}
... = n : H,
have H3 : n < n, from lt_intro H2,
have H4 : n β n, from lt_ne H3,
absurd_elim _ (refl n) H4)
set_opaque lt true
-------------------------------------------------- ge, gt
definition ge (n m : nat) := m β€ n
infix 50 >= : ge
infix 50 β₯ : ge
definition gt (n m : nat) := m < n
infix 50 > : gt
-- prove some theorems, like ge_le le_ge lt_gt gt_lt
-------------------------------------------------- minus
definition minus (n m : nat) : nat := nat_rec n (fun m x, pred x) m
infixl 65 - : minus
theorem minus_zero_right (n : nat) : n - zero = n
:= nat_rec_zero _ _
theorem minus_succ_right (n m : nat) : n - succ m = pred (n - m)
:= nat_rec_succ _ _ _
set_opaque minus true
theorem minus_zero_left (n : nat) : zero - n = zero
:=
induction_on n (minus_zero_right zero)
(take k : nat,
assume IH : zero - k = zero,
calc
zero - succ k = pred (zero - k) : minus_succ_right zero k
... = pred zero : {IH}
... = zero : pred_zero)
--theorem minus_succ_left (n m : nat) : pred (succ n - m) = n - m
-- :=
-- induction_on m
-- (calc
-- pred (succ n - zero) = pred (succ n) : {minus_zero_right (succ n)}
-- ... = n : pred_succ n
-- ... = n - zero : symm (minus_zero_right n))
-- (take k : nat,
-- assume IH : pred (succ n - k) = n - k,
-- _)
theorem minus_succ_succ (n m : nat) : succ n - succ m = n - m
:=
induction_on m
(calc
succ n - succ zero = pred (succ n - zero) : minus_succ_right (succ n) zero
... = pred (succ n) : {minus_zero_right (succ n)}
... = n : pred_succ n
... = n - zero : symm (minus_zero_right n))
(take k : nat,
assume IH : succ n - succ k = n - k,
calc
succ n - succ (succ k) = pred (succ n - succ k) : minus_succ_right (succ n) (succ k)
... = pred (n - k) : {IH}
... = n - succ k : symm (minus_succ_right n k))
theorem minus_one (n : nat) : n - succ zero = pred n
:=
calc
n - succ zero = pred (n - zero) : minus_succ_right n zero
... = pred n : {minus_zero_right n}
theorem minus_self (n : nat) : n - n = zero
:= induction_on n (minus_zero_right zero) (take k IH, trans (minus_succ_succ k k) IH)
theorem minus_add_add_right (n m k : nat) : (n + k) - (m + k) = n - m
:=
induction_on k
(calc
(n + zero) - (m + zero) = n - (m + zero) : {add_zero_right _}
... = n - m : {add_zero_right _})
(take l : nat,
assume IH : (n + l) - (m + l) = n - m,
calc
(n + succ l) - (m + succ l) = succ (n + l) - (m + succ l) : {add_succ_right _ _}
... = succ (n + l) - succ (m + l) : {add_succ_right _ _}
... = (n + l) - (m + l) : minus_succ_succ _ _
... = n - m : IH)
theorem minus_add_add_left (n m k : nat) : (k + n) - (k + m) = n - m
:= subst (subst (minus_add_add_right n m k) (add_comm n k)) (add_comm m k)
theorem minus_add_left (n m : nat) : n + m - m = n
:=
induction_on m
(subst (minus_zero_right n) (symm (add_zero_right n)))
(take k : nat,
assume IH : n + k - k = n,
calc
n + succ k - succ k = succ (n + k) - succ k : {add_succ_right n k}
... = n + k - k : minus_succ_succ _ _
... = n : IH)
theorem minus_minus (n m k : nat) : n - m - k = n - (m + k)
:=
induction_on k
(calc
n - m - zero = n - m : minus_zero_right _
... = n - (m + zero) : {symm (add_zero_right m)})
(take l : nat,
assume IH : n - m - l = n - (m + l),
calc
n - m - succ l = pred (n - m - l) : minus_succ_right (n - m) l
... = pred (n - (m + l)) : {IH}
... = n - succ (m + l) : symm (minus_succ_right n (m + l))
... = n - (m + succ l) : {symm (add_succ_right m l)})
theorem succ_minus_minus (n m k : nat) : succ n - m - succ k = n - m - k
:=
calc
succ n - m - succ k = succ n - (m + succ k) : minus_minus _ _ _
... = succ n - succ (m + k) : {add_succ_right m k}
... = n - (m + k) : minus_succ_succ _ _
... = n - m - k : symm (minus_minus n m k)
theorem minus_add_right (n m : nat) : n - (n + m) = zero
:=
calc
n - (n + m) = n - n - m : symm (minus_minus n n m)
... = zero - m : {minus_self n}
... = zero : minus_zero_left m
theorem minus_comm (m n k : nat) : m - n - k = m - k - n
:=
calc
m - n - k = m - (n + k) : minus_minus m n k
... = m - (k + n) : {add_comm n k}
... = m - k - n : symm (minus_minus m k n)
theorem succ_minus_one (n : nat) : succ n - succ zero = n
:= trans (minus_succ_succ n zero) (minus_zero_right n)
---------- mul
theorem mul_pred_left (n m : nat) : pred n * m = n * m - m
:=
induction_on n
(calc
pred zero * m = zero * m : {pred_zero}
... = zero : mul_zero_left _
... = zero - m : symm (minus_zero_left m)
... = zero * m - m : {symm (mul_zero_left m)})
(take k : nat,
assume IH : pred k * m = k * m - m,
calc
pred (succ k) * m = k * m : {pred_succ k}
... = k * m + m - m : symm (minus_add_left _ _)
... = succ k * m - m : {symm (mul_succ_left k m)})
theorem mul_pred_right (n m : nat) : n * pred m = n * m - n
:=
calc n * pred m = pred m * n : mul_comm _ _
... = m * n - n : mul_pred_left m n
... = n * m - n : {mul_comm m n}
theorem mul_minus_distr_left (n m k : nat) : (n - m) * k = n * k - m * k
:=
induction_on m
(calc
(n - zero) * k = n * k : {minus_zero_right n}
... = n * k - zero : symm (minus_zero_right _)
... = n * k - zero * k : {symm (mul_zero_left _)})
(take l : nat,
assume IH : (n - l) * k = n * k - l * k,
calc
(n - succ l) * k = pred (n - l) * k : {minus_succ_right n l}
... = (n - l) * k - k : mul_pred_left _ _
... = n * k - l * k - k : {IH}
... = n * k - (l * k + k) : minus_minus _ _ _
... = n * k - (succ l * k) : {symm (mul_succ_left l k)})
theorem mul_minus_distr_right (n m k : nat) : n * (m - k) = n * m - n * k
:=
calc
n * (m - k) = (m - k) * n : mul_comm _ _
... = m * n - k * n : mul_minus_distr_left _ _ _
... = n * m - k * n : {mul_comm _ _}
... = n * m - n * k : {mul_comm _ _}
-------------------------------------------------- max, min, iteration, maybe: minus, div
-- n - m + m = max n m
end --namespace nat |
a1b2252d7ab4658c849bf249200df97e5aa9ddb9 | 8cd68b0e4eb405ef573e16a6d92dcbcdb92d1c29 | /library/init/meta/level.lean | aa56420cac34b431afb31ef1fe8c19d87dcd78b7 | [
"Apache-2.0"
] | permissive | ratmice/lean | 5d7a7bbaa652899941fe73dff2154ddc5ab2f20a | 139ac0d773dbf0f54cc682612bf8f02297c211dd | refs/heads/master | 1,590,259,859,627 | 1,557,951,491,000 | 1,558,099,319,000 | 186,896,142 | 0 | 0 | Apache-2.0 | 1,557,951,143,000 | 1,557,951,143,000 | null | UTF-8 | Lean | false | false | 2,144 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.name init.meta.format
/-- A type universe term. eg `max u v`. Reflect a C++ level object. The VM replaces it with the C++ implementation. -/
meta inductive level
| zero : level
| succ : level β level
| max : level β level β level
| imax : level β level β level
| param : name β level
| mvar : name β level
meta instance : inhabited level :=
β¨level.zeroβ©
/- TODO(Leo): provide a definition in Lean. -/
meta constant level.has_decidable_eq : decidable_eq level
attribute [instance] level.has_decidable_eq
meta constant level.lt : level β level β bool
meta constant level.lex_lt : level β level β bool
meta constant level.fold {Ξ± :Type} : level β Ξ± β (level β Ξ± β Ξ±) β Ξ±
/-- Return the given level expression normal form -/
meta constant level.normalize : level β level
/-- Return tt iff lhs and rhs denote the same level.
The check is done by normalization. -/
meta constant level.eqv : level β level β bool
/-- Return tt iff the first level occurs in the second -/
meta constant level.occurs : level β level β bool
/-- Replace a parameter named n with l in the first level if the list contains the pair (n, l) -/
meta constant level.instantiate : level β list (name Γ level) β list level
meta constant level.to_format : level β options β format
meta constant level.to_string : level β string
meta instance : has_to_string level :=
β¨level.to_stringβ©
meta instance : has_to_format level :=
β¨Ξ» l, level.to_format l options.mkβ©
meta def level.of_nat : nat β level
| 0 := level.zero
| (nat.succ n) := level.succ (level.of_nat n)
meta def level.has_param : level β name β bool
| (level.succ l) n := level.has_param l n
| (level.max lβ lβ) n := level.has_param lβ n || level.has_param lβ n
| (level.imax lβ lβ) n := level.has_param lβ n || level.has_param lβ n
| (level.param nβ) n := nβ = n
| l n := ff
|
c99bc1efab79a9459e494ad44af471e66ff08714 | 7850aae797be6c31052ce4633d86f5991178d3df | /stage0/src/Lean/Elab/Do.lean | 66961b5d789f3b45722ce76820f9ff87366ec2b7 | [
"Apache-2.0"
] | permissive | miriamgoetze/lean4 | 4dc24d4dbd360cc969713647c2958c6691947d16 | 062cc5d5672250be456a168e9c7b9299a9c69bdb | refs/heads/master | 1,685,865,971,011 | 1,624,107,703,000 | 1,624,107,703,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 69,607 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Term
import Lean.Elab.Binders
import Lean.Elab.Match
import Lean.Elab.Quotation.Util
import Lean.Parser.Do
namespace Lean.Elab.Term
open Lean.Parser.Term
open Meta
private def getDoSeqElems (doSeq : Syntax) : List Syntax :=
if doSeq.getKind == `Lean.Parser.Term.doSeqBracketed then
doSeq[1].getArgs.toList.map fun arg => arg[0]
else if doSeq.getKind == `Lean.Parser.Term.doSeqIndent then
doSeq[0].getArgs.toList.map fun arg => arg[0]
else
[]
private def getDoSeq (doStx : Syntax) : Syntax :=
doStx[1]
@[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ =>
throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression"
/-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/
private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool :=
k == ``Lean.Parser.Term.do ||
k == ``Lean.Parser.Term.doSeqIndent ||
k == ``Lean.Parser.Term.doSeqBracketed ||
k == ``Lean.Parser.Term.termReturn ||
k == ``Lean.Parser.Term.termUnless ||
k == ``Lean.Parser.Term.termTry ||
k == ``Lean.Parser.Term.termFor
/-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/
private def letDeclArgHasBinders (letDeclArg : Syntax) : Bool :=
let k := letDeclArg.getKind
if k == ``Lean.Parser.Term.letPatDecl then
false
else if k == ``Lean.Parser.Term.letEqnsDecl then
true
else if k == ``Lean.Parser.Term.letIdDecl then
-- letIdLhs := ident >> checkWsBefore "expected space before binders" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType
let binders := letDeclArg[1]
binders.getNumArgs > 0
else
false
/-- Return `true` if the given `letDecl` contains binders. -/
private def letDeclHasBinders (letDecl : Syntax) : Bool :=
letDeclArgHasBinders letDecl[0]
/-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/
private def liftMethodForbiddenBinder (stx : Syntax) : Bool :=
let k := stx.getKind
if k == ``Lean.Parser.Term.fun || k == ``Lean.Parser.Term.matchAlts ||
k == ``Lean.Parser.Term.doLetRec || k == ``Lean.Parser.Term.letrec then
-- It is never ok to lift over this kind of binder
true
-- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not
else if k == ``Lean.Parser.Term.let then
letDeclHasBinders stx[1]
else if k == ``Lean.Parser.Term.doLet then
letDeclHasBinders stx[2]
else if k == ``Lean.Parser.Term.doLetArrow then
letDeclArgHasBinders stx[2]
else
false
private partial def hasLiftMethod : Syntax β Bool
| Syntax.node k args =>
if liftMethodDelimiter k then false
-- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a
-- bit slower
else if k == `Lean.Parser.Term.liftMethod then true
else args.any hasLiftMethod
| _ => false
structure ExtractMonadResult where
m : Expr
Ξ± : Expr
hasBindInst : Expr
expectedType : Expr
private def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do
let u β getDecLevel type
let id := Lean.mkConst `Id [u]
let idBindVal := Lean.mkConst `Id.hasBind [u]
pure { m := id, hasBindInst := idBindVal, Ξ± := type, expectedType := mkApp id type }
private partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do
match expectedType? with
| none => throwError "invalid 'do' notation, expected type is not available"
| some expectedType =>
let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do
match type with
| Expr.app m Ξ± _ =>
try
let bindInstType β mkAppM `Bind #[m]
let bindInstVal β Meta.synthInstance bindInstType
return some { m := m, hasBindInst := bindInstVal, Ξ± := Ξ±, expectedType := expectedType }
catch _ =>
return none
| _ =>
return none
let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do
match (β extractStep? type) with
| some r => return r
| none =>
let typeNew β whnfCore type
if typeNew != type then
extract? typeNew
else
if typeNew.getAppFn.isMVar then throwError "invalid 'do' notation, expected type is not available"
match (β unfoldDefinition? typeNew) with
| some typeNew => extract? typeNew
| none => return none
match (β extract? expectedType) with
| some r => return r
| none => mkIdBindFor expectedType
namespace Do
/- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/
structure Alt (Ο : Type) where
ref : Syntax
vars : Array Name
patterns : Syntax
rhs : Ο
deriving Inhabited
/-
Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`).
We convert `Code` into a `Syntax` term representing the:
- `do`-block, or
- the visitor argument for the `forIn` combinator.
We say the following constructors are terminals:
- `break`: for interrupting a `for x in s`
- `continue`: for interrupting the current iteration of a `for x in s`
- `return e`: for returning `e` as the result for the whole `do` computation block
- `action a`: for executing action `a` as a terminal
- `ite`: if-then-else
- `match`: pattern matching
- `jmp` a goto to a join-point
We say the terminals `break`, `continue`, `action`, and `return` are "exit points"
Note that, `return e` is not equivalent to `action (pure e)`. Here is an example:
```
def f (x : Nat) : IO Unit := do
if x == 0 then
return ()
IO.println "hello"
```
Executing `#eval f 0` will not print "hello". Now, consider
```
def g (x : Nat) : IO Unit := do
if x == 0 then
pure ()
IO.println "hello"
```
The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`.
- `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`).
The field `stx` is the actual `doElem`,
`vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block.
`vars` is an array since we have declarations such as `let (a, b) := s`.
- `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`).
- `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow.
- `seq a k` executes action `a`, ignores its result, and then executes `k`.
We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`.
A code block `C` is well-formed if
- For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and
`ps.size == as.size` -/
inductive Code where
| decl (xs : Array Name) (doElem : Syntax) (k : Code)
| reassign (xs : Array Name) (doElem : Syntax) (k : Code)
/- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/
| joinpoint (name : Name) (params : Array (Name Γ Bool)) (body : Code) (k : Code)
| seq (action : Syntax) (k : Code)
| action (action : Syntax)
| Β«breakΒ» (ref : Syntax)
| Β«continueΒ» (ref : Syntax)
| Β«returnΒ» (ref : Syntax) (val : Syntax)
/- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/
| ite (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code)
| Β«matchΒ» (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code))
| jmp (ref : Syntax) (jpName : Name) (args : Array Syntax)
deriving Inhabited
/- A code block, and the collection of variables updated by it. -/
structure CodeBlock where
code : Code
uvars : NameSet := {} -- set of variables updated by `code`
private def nameSetToArray (s : NameSet) : Array Name :=
s.fold (fun (xs : Array Name) x => xs.push x) #[]
private def varsToMessageData (vars : Array Name) : MessageData :=
MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) " "
partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData :=
let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName
let rec loop : Code β MessageData
| Code.decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}"
| Code.reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}"
| Code.joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}"
| Code.seq e k => m!"{e}\n{loop k}"
| Code.action e => e
| Code.ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}"
| Code.jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}"
| Code.Β«breakΒ» _ => m!"break {us}"
| Code.Β«continueΒ» _ => m!"continue {us}"
| Code.Β«returnΒ» _ v => m!"return {v} {us}"
| Code.Β«matchΒ» _ _ ds t alts =>
m!"match {ds} with"
++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}"
loop codeBlock.code
/- Return true if the give code contains an exit point that satisfies `p` -/
@[inline] partial def hasExitPointPred (c : Code) (p : Code β Bool) : Bool :=
let rec @[specialize] loop : Code β Bool
| Code.decl _ _ k => loop k
| Code.reassign _ _ k => loop k
| Code.joinpoint _ _ b k => loop b || loop k
| Code.seq _ k => loop k
| Code.ite _ _ _ _ t e => loop t || loop e
| Code.Β«matchΒ» _ _ _ _ alts => alts.any (loop Β·.rhs)
| Code.jmp _ _ _ => false
| c => p c
loop c
def hasExitPoint (c : Code) : Bool :=
hasExitPointPred c fun c => true
def hasReturn (c : Code) : Bool :=
hasExitPointPred c fun
| Code.Β«returnΒ» _ _ => true
| _ => false
def hasTerminalAction (c : Code) : Bool :=
hasExitPointPred c fun
| Code.Β«actionΒ» _ => true
| _ => false
def hasBreakContinue (c : Code) : Bool :=
hasExitPointPred c fun
| Code.Β«breakΒ» _ => true
| Code.Β«continueΒ» _ => true
| _ => false
def hasBreakContinueReturn (c : Code) : Bool :=
hasExitPointPred c fun
| Code.Β«breakΒ» _ => true
| Code.Β«continueΒ» _ => true
| Code.Β«returnΒ» _ _ => true
| _ => false
def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax β m Code) : m Code := withRef e <| withFreshMacroScope do
let y β `(y)
let yName := y.getId
let doElem β `(doElem| let y β $e:term)
-- Add elaboration hint for producing sane error message
let y β `(ensureExpectedType% "type mismatch, result value" $y)
let k β mkCont y
pure $ Code.decl #[yName] doElem k
/- Convert `action _ e` instructions in `c` into `let y β e; jmp _ jp (xs y)`. -/
partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code :=
let rec loop : Code β MacroM Code
| Code.decl xs stx k => do Code.decl xs stx (β loop k)
| Code.reassign xs stx k => do Code.reassign xs stx (β loop k)
| Code.joinpoint n ps b k => do Code.joinpoint n ps (β loop b) (β loop k)
| Code.seq e k => do Code.seq e (β loop k)
| Code.ite ref x? h c t e => do Code.ite ref x? h c (β loop t) (β loop e)
| Code.Β«matchΒ» ref g ds t alts => do Code.Β«matchΒ» ref g ds t (β alts.mapM fun alt => do pure { alt with rhs := (β loop alt.rhs) })
| Code.action e => mkAuxDeclFor e fun y =>
let ref := e
-- We jump to `jp` with xs **and** y
let jmpArgs := xs.map $ mkIdentFrom ref
let jmpArgs := jmpArgs.push y
pure $ Code.jmp ref jp jmpArgs
| c => pure c
loop code
structure JPDecl where
name : Name
params : Array (Name Γ Bool)
body : Code
def attachJP (jpDecl : JPDecl) (k : Code) : Code :=
Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k
def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code :=
jpDecls.foldr attachJP k
def mkFreshJP (ps : Array (Name Γ Bool)) (body : Code) : TermElabM JPDecl := do
let ps β
if ps.isEmpty then
let y β mkFreshUserName `y
pure #[(y, false)]
else
pure ps
-- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by
-- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp`
-- We will remove this hack when we re-implement the compiler frontend in Lean.
let name β mkFreshUserName `_do_jp
pure { name := name, params := ps, body := body }
def mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl :=
mkFreshJP (xs.map fun x => (x, true)) body
def addFreshJP (ps : Array (Name Γ Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do
let jp β mkFreshJP ps body
modify fun (jps : Array JPDecl) => jps.push jp
pure jp.name
def insertVars (rs : NameSet) (xs : Array Name) : NameSet :=
xs.foldl (Β·.insert Β·) rs
def eraseVars (rs : NameSet) (xs : Array Name) : NameSet :=
xs.foldl (Β·.erase Β·) rs
def eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet :=
match x? with
| none => rs
| some x => rs.insert x
/- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/
def mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do
let xs := nameSetToArray rs
let jp β addFreshJP (xs.map fun x => (x, true)) c
if xs.isEmpty then
let unit β ``(Unit.unit)
return Code.jmp ref jp #[unit]
else
return Code.jmp ref jp (xs.map $ mkIdentFrom ref)
/- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value.
The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh`
is a fresh variable created by this method. -/
def mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax β MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do
let xs := nameSetToArray rs
let args := xs.map $ mkIdentFrom ref
let args := args.push val
let yFresh β mkFreshUserName `y
let ps := xs.map fun x => (x, true)
let ps := ps.push (yFresh, false)
let jpBody β liftMacroM $ mkJPBody (mkIdentFrom ref yFresh)
let jp β addFreshJP ps jpBody
pure $ Code.jmp ref jp args
/- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/
partial def pullExitPointsAux : NameSet β Code β StateRefT (Array JPDecl) TermElabM Code
| rs, Code.decl xs stx k => do Code.decl xs stx (β pullExitPointsAux (eraseVars rs xs) k)
| rs, Code.reassign xs stx k => do Code.reassign xs stx (β pullExitPointsAux (insertVars rs xs) k)
| rs, Code.joinpoint j ps b k => do Code.joinpoint j ps (β pullExitPointsAux rs b) (β pullExitPointsAux rs k)
| rs, Code.seq e k => do Code.seq e (β pullExitPointsAux rs k)
| rs, Code.ite ref x? o c t e => do Code.ite ref x? o c (β pullExitPointsAux (eraseOptVar rs x?) t) (β pullExitPointsAux (eraseOptVar rs x?) e)
| rs, Code.Β«matchΒ» ref g ds t alts => do
Code.Β«matchΒ» ref g ds t (β alts.mapM fun alt => do pure { alt with rhs := (β pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) })
| rs, c@(Code.jmp _ _ _) => pure c
| rs, Code.Β«breakΒ» ref => mkSimpleJmp ref rs (Code.Β«breakΒ» ref)
| rs, Code.Β«continueΒ» ref => mkSimpleJmp ref rs (Code.Β«continueΒ» ref)
| rs, Code.Β«returnΒ» ref val => mkJmp ref rs val (fun y => pure $ Code.Β«returnΒ» ref y)
| rs, Code.action e =>
-- We use `mkAuxDeclFor` because `e` is not pure.
mkAuxDeclFor e fun y =>
let ref := e
mkJmp ref rs y (fun yFresh => do pure $ Code.action (β ``(Pure.pure $yFresh)))
/-
Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock.
When a new variable is not already in the collection, but is shadowed by some declaration in `c`,
we create auxiliary join points to make sure we preserve the semantics of the code block.
Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it
with the reassignment `x := x + 1`. We first use `pullExitPoints` to create
```
let jp (x!1) := return x!1;
print x;
let x := 10;
jmp jp x
```
and then we add the reassignment
```
x := x + 1
let jp (x!1) := return x!1;
print x;
let x := 10;
jmp jp x
```
Note that we created a fresh variable `x!1` to avoid accidental name capture.
As another example, consider
```
print x;
let x := 10
y := y + 1;
return x;
```
We transform it into
```
let jp (y x!1) := return x!1;
print x;
let x := 10
y := y + 1;
jmp jp y x
```
and then we add the reassignment as in the previous example.
We need to include `y` in the jump, because each exit point is implicitly returning the set of
update variables.
We implement the method as follows. Let `us` be `c.uvars`, then
1- for each `return _ y` in `c`, we create a join point
`let j (us y!1) := return y!1`
and replace the `return _ y` with `jmp us y`
2- for each `break`, we create a join point
`let j (us) := break`
and replace the `break` with `jmp us`.
3- Same as 2 for `continue`.
-/
def pullExitPoints (c : Code) : TermElabM Code := do
if hasExitPoint c then
let (c, jpDecls) β (pullExitPointsAux {} c).run #[]
pure $ attachJPs jpDecls c
else
pure c
partial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code :=
let rec update : Code β TermElabM Code
| Code.joinpoint j ps b k => do Code.joinpoint j ps (β update b) (β update k)
| Code.seq e k => do Code.seq e (β update k)
| c@(Code.Β«matchΒ» ref g ds t alts) => do
if alts.any fun alt => alt.vars.any fun x => ws.contains x then
-- If a pattern variable is shadowing a variable in ws, we `pullExitPoints`
pullExitPoints c
else
Code.Β«matchΒ» ref g ds t (β alts.mapM fun alt => do pure { alt with rhs := (β update alt.rhs) })
| Code.ite ref none o c t e => do Code.ite ref none o c (β update t) (β update e)
| c@(Code.ite ref (some h) o cond t e) => do
if ws.contains h then
-- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints`
pullExitPoints c
else
Code.ite ref (some h) o cond (β update t) (β update e)
| Code.reassign xs stx k => do Code.reassign xs stx (β update k)
| c@(Code.decl xs stx k) => do
if xs.any fun x => ws.contains x then
-- One the declared variables is shadowing a variable in `ws`
pullExitPoints c
else
Code.decl xs stx (β update k)
| c => pure c
update c
/-
Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`.
We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`.
See discussion at `pullExitPoints`.
-/
partial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do
if ws.any fun x => !c.uvars.contains x then
-- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed)
pure { code := (β extendUpdatedVarsAux c.code ws), uvars := ws }
else
pure { c with uvars := ws }
private def union (sβ sβ : NameSet) : NameSet :=
sβ.fold (Β·.insert Β·) sβ
/-
Given two code blocks `cβ` and `cβ`, make sure they have the same set of updated variables.
Let `ws` the union of the updated variables in `cββ΅ and β΅cβ`.
We use `extendUpdatedVars cβ ws` and `extendUpdatedVars cβ ws`
-/
def homogenize (cβ cβ : CodeBlock) : TermElabM (CodeBlock Γ CodeBlock) := do
let ws := union cβ.uvars cβ.uvars
let cβ β extendUpdatedVars cβ ws
let cβ β extendUpdatedVars cβ ws
pure (cβ, cβ)
/-
Extending code blocks with variable declarations: `let x : t := v` and `let x : t β v`.
We remove `x` from the collection of updated varibles.
Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables
declared by it. It is an array because we have let-declarations that declare multiple variables.
Example: `let (x, y) := t`
-/
def mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := {
code := Code.decl xs stx c.code,
uvars := eraseVars c.uvars xs
}
/-
Extending code blocks with reassignments: `x : t := v` and `x : t β v`.
Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables
declared by it. It is an array because we have let-declarations that declare multiple variables.
Example: `(x, y) β t`
-/
def mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do
let us := c.uvars
let ws := insertVars us xs
-- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`.
-- See discussion at `pullExitPoints`
let code β if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code
pure { code := Code.reassign xs stx code, uvars := ws }
def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock :=
{ c with code := Code.seq action c.code }
def mkTerminalAction (action : Syntax) : CodeBlock :=
{ code := Code.action action }
def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock :=
{ code := Code.Β«returnΒ» ref val }
def mkBreak (ref : Syntax) : CodeBlock :=
{ code := Code.Β«breakΒ» ref }
def mkContinue (ref : Syntax) : CodeBlock :=
{ code := Code.Β«continueΒ» ref }
def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do
let x? := if optIdent.isNone then none else some optIdent[0].getId
let (thenBranch, elseBranch) β homogenize thenBranch elseBranch
pure {
code := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code,
uvars := thenBranch.uvars,
}
private def mkUnit : MacroM Syntax :=
``((β¨β© : PUnit))
private def mkPureUnit : MacroM Syntax :=
``(pure PUnit.unit)
def mkPureUnitAction : MacroM CodeBlock := do
mkTerminalAction (β mkPureUnit)
def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do
let thenBranch β mkPureUnitAction
pure { c with code := Code.ite (β getRef) none mkNullNode cond thenBranch.code c.code }
def mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do
-- nary version of homogenize
let ws := alts.foldl (union Β· Β·.rhs.uvars) {}
let alts β alts.mapM fun alt => do
let rhs β extendUpdatedVars alt.rhs ws
pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code }
pure { code := Code.Β«matchΒ» ref genParam discrs optType alts, uvars := ws }
/- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`.
This method assumes `terminal` is a terminal -/
def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do
unless hasTerminalAction terminal.code do
throwErrorAt kRef "'do' element is unreachable"
let (terminal, k) β homogenize terminal k
let xs := nameSetToArray k.uvars
let y β match y? with | some y => pure y | none => mkFreshUserName `y
let ps := xs.map fun x => (x, true)
let ps := ps.push (y, false)
let jpDecl β mkFreshJP ps k.code
let jp := jpDecl.name
let terminal β liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs
pure { code := attachJP jpDecl terminal, uvars := k.uvars }
def getLetIdDeclVar (letIdDecl : Syntax) : Name :=
letIdDecl[0].getId
-- support both regular and syntax match
def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Name) :=
getPatternVarNames <$> getPatternVars pattern <|>
Array.map Syntax.getId <$> Quotation.getPatternVars pattern
def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Name) :=
getPatternVarNames <$> getPatternsVars patterns <|>
Array.map Syntax.getId <$> Quotation.getPatternsVars patterns
def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do
let pattern := letPatDecl[0]
getPatternVarsEx pattern
def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name :=
letEqnsDecl[0].getId
def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do
let arg := letDecl[0]
if arg.getKind == `Lean.Parser.Term.letIdDecl then
pure #[getLetIdDeclVar arg]
else if arg.getKind == `Lean.Parser.Term.letPatDecl then
getLetPatDeclVars arg
else if arg.getKind == `Lean.Parser.Term.letEqnsDecl then
pure #[getLetEqnsDeclVar arg]
else
throwError "unexpected kind of let declaration"
def getDoLetVars (doLet : Syntax) : TermElabM (Array Name) :=
-- leading_parser "let " >> optional "mut " >> letDecl
getLetDeclVars doLet[2]
def getDoHaveVar (doHave : Syntax) : Name :=
/-
`leading_parser "have " >> Term.haveDecl`
where
```
haveDecl := leading_parser optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic)
optIdent := optional (try (ident >> " : "))
```
-/
let optIdent := doHave[1][0]
if optIdent.isNone then
`this
else
optIdent[0].getId
def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do
-- letRecDecls is an array of `(group (optional attributes >> letDecl))`
let letRecDecls := doLetRec[1][0].getSepArgs
let letDecls := letRecDecls.map fun p => p[2]
let mut allVars := #[]
for letDecl in letDecls do
let vars β getLetDeclVars letDecl
allVars := allVars ++ vars
pure allVars
-- ident >> optType >> leftArrow >> termParser
def getDoIdDeclVar (doIdDecl : Syntax) : Name :=
doIdDecl[0].getId
-- termParser >> leftArrow >> termParser >> optional (" | " >> termParser)
def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do
let pattern := doPatDecl[0]
getPatternVarsEx pattern
-- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl)
def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do
let decl := doLetArrow[2]
if decl.getKind == `Lean.Parser.Term.doIdDecl then
pure #[getDoIdDeclVar decl]
else if decl.getKind == `Lean.Parser.Term.doPatDecl then
getDoPatDeclVars decl
else
throwError "unexpected kind of 'do' declaration"
def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do
let arg := doReassign[0]
if arg.getKind == `Lean.Parser.Term.letIdDecl then
pure #[getLetIdDeclVar arg]
else if arg.getKind == `Lean.Parser.Term.letPatDecl then
getLetPatDeclVars arg
else
throwError "unexpected kind of reassignment"
def mkDoSeq (doElems : Array Syntax) : Syntax :=
mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]]
def mkSingletonDoSeq (doElem : Syntax) : Syntax :=
mkDoSeq #[doElem]
/-
If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s. -/
private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with
| `(doElem|if $p:doIfProp then $t else $e) => pure none
| `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do
let mut e := e?.getD (β `(doSeq|pure PUnit.unit))
let mut eIsSeq := true
for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do
e β if eIsSeq then e else `(doSeq|$e:doElem)
e β withRef cond <| match cond with
| `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e)
| `(doIfCond|let $pat β $d) => `(doElem| match%$i β $d with | $pat:term => $t | _ => $e)
| `(doIfCond|$cond:doIfProp) => `(doElem| if%$i $cond:doIfProp then $t else $e)
| _ => `(doElem| if%$i $(Syntax.missing) then $t else $e)
eIsSeq := false
return some e
| _ => pure none
structure DoIfView where
ref : Syntax
optIdent : Syntax
cond : Syntax
thenBranch : Syntax
elseBranch : Syntax
/- This method assumes `expandDoIf?` is not applicable. -/
private def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do
pure {
ref := doIf,
optIdent := doIf[1][0],
cond := doIf[1][1],
thenBranch := doIf[3],
elseBranch := doIf[5][1]
}
/-
We use `MProd` instead of `Prod` to group values when expanding the
`do` notation. `MProd` is a universe monomorphic product.
The motivation is to generate simpler universe constraints in code
that was not written by the user.
Note that we are not restricting the macro power since the
`Bind.bind` combinator already forces values computed by monadic
actions to be in the same universe.
-/
private def mkTuple (elems : Array Syntax) : MacroM Syntax := do
if elems.size == 0 then
mkUnit
else if elems.size == 1 then
pure elems[0]
else
(elems.extract 0 (elems.size - 1)).foldrM
(fun elem tuple => ``(MProd.mk $elem $tuple))
(elems.back)
/- Return `some action` if `doElem` is a `doExpr <action>`-/
def isDoExpr? (doElem : Syntax) : Option Syntax :=
if doElem.getKind == `Lean.Parser.Term.doExpr then
some doElem[0]
else
none
/--
Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term
```
let a_1 := x.1
let x := x.2
let a_2 := x.1
let x := x.2
...
let a_n := x.1
let a_{n+1} := x.2
body
```
Special cases
- `uvars := #[]` => `body`
- `uvars := #[a]` => `let a := x; body`
We use this method when expanding the `for-in` notation.
-/
private def destructTuple (uvars : Array Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do
if uvars.size == 0 then
return body
else if uvars.size == 1 then
`(let $(β mkIdentFromRef uvars[0]):ident := $x; $body)
else
destruct uvars.toList x body
where
destruct (as : List Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do
match as with
| [a, b] => `(let $(β mkIdentFromRef a):ident := $x.1; let $(β mkIdentFromRef b):ident := $x.2; $body)
| a :: as => withFreshMacroScope do
let rest β destruct as (β `(x)) body
`(let $(β mkIdentFromRef a):ident := $x.1; let x := $x.2; $rest)
| _ => unreachable!
/-
The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term.
We use this method to convert
1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of
`CodeBlock` never contains `break` nor `continue`. Moreover, the collection
of updated variables is not packed into the result.
Thus, we have two kinds of exit points
- `Code.action e` which is converted into `e`
- `Code.return _ e` which is converted into `pure e`
We use `Kind.regular` for this case.
2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate
a `Syntax` term representing a function for the `xs.forIn` combinator.
a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term
has type `m (ForInStep (Option Ξ± Γ Ο))`, where `a : Ξ±`, and the `Ο` is the type
of the tuple of variables reassigned by `b`.
We use `Kind.forInWithReturn` for this case
b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated
`Syntax` term has type `m (ForInStep Ο)`.
We use `Kind.forIn` for this case.
3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`).
The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`,
`Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information.
For example, the auxiliary type `DoResultPBC Ξ± Ο` is used for a code block that exits with `Code.action`,
**and** `Code.break`/`Code.continue`, `Ξ±` is the type of values produced by the exit `action`, and
`Ο` is the type of the tuple of reassigned variables.
The type `DoResult Ξ± Ξ² Ο` is usedf for code blocks that exit with
`Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `Ξ²` is the type of the returned values.
We don't use `DoResult Ξ± Ξ² Ο` for all cases because:
a) The elaborator would not be able to infer all type parameters without extra annotations. For example,
if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `Ξ²`.
b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`),
but we don't want to consider "unreachable" cases.
We do not distinguish between cases that contain `break`, but not `continue`, and vice versa.
When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`,
and `b/c` for a code block that contains `Code.break _` or `Code.continue _`.
- `a`: `Kind.regular`, type `m (Ξ± Γ Ο)`
- `r`: `Kind.regular`, type `m (Ξ± Γ Ο)`
Note that the code that pattern matches on the result will behave differently in this case.
It produces `return a` for this case, and `pure a` for the previous one.
- `b/c`: `Kind.nestedBC`, type `m (DoResultBC Ο)`
- `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR Ξ± Ξ² Ο)`
- `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC Ξ± Ο)`
- `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC Ξ± Ο)`
Again the code that pattern matches on the result will behave differently in this case and
the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for
this case, and `pure a` for the previous case.
- `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC Ξ± Ξ² Ο)`
Here is the recipe for adding new combinators with nested `do`s.
Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m Ξ± β m Ξ±`
1- Convert `doSeq` into `codeBlock : CodeBlock`
2- Create term `term` using `mkNestedTerm code m uvars a r bc` where
`code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`,
`m` is a `Syntax` representing the Monad, and
`a` is true if `code` contains `Code.action _`,
`r` is true if `code` contains `Code.return _ _`,
`bc` is true if `code` contains `Code.break _` or `Code.continue _`.
Remark: for combinators such as `repeat` that take a single `doSeq`, all
arguments, but `m`, are extracted from `codeBlock`.
3- Create the term `repeat $term`
4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc`
-/
namespace ToTerm
inductive Kind where
| regular
| forIn
| forInWithReturn
| nestedBC
| nestedPR
| nestedSBC
| nestedPRBC
instance : Inhabited Kind := β¨Kind.regularβ©
def Kind.isRegular : Kind β Bool
| Kind.regular => true
| _ => false
structure Context where
m : Syntax -- Syntax to reference the monad associated with the do notation.
uvars : Array Name
kind : Kind
abbrev M := ReaderT Context MacroM
def mkUVarTuple : M Syntax := do
let ctx β read
let uvarIdents β ctx.uvars.mapM mkIdentFromRef
mkTuple uvarIdents
def returnToTerm (val : Syntax) : M Syntax := do
let ctx β read
let u β mkUVarTuple
match ctx.kind with
| Kind.regular => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u))
| Kind.forIn => ``(Pure.pure (ForInStep.done $u))
| Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u)))
| Kind.nestedBC => unreachable!
| Kind.nestedPR => ``(Pure.pure (DoResultPR.Β«returnΒ» $val $u))
| Kind.nestedSBC => ``(Pure.pure (DoResultSBC.Β«pureReturnΒ» $val $u))
| Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.Β«returnΒ» $val $u))
def continueToTerm : M Syntax := do
let ctx β read
let u β mkUVarTuple
match ctx.kind with
| Kind.regular => unreachable!
| Kind.forIn => ``(Pure.pure (ForInStep.yield $u))
| Kind.forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u)))
| Kind.nestedBC => ``(Pure.pure (DoResultBC.Β«continueΒ» $u))
| Kind.nestedPR => unreachable!
| Kind.nestedSBC => ``(Pure.pure (DoResultSBC.Β«continueΒ» $u))
| Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.Β«continueΒ» $u))
def breakToTerm : M Syntax := do
let ctx β read
let u β mkUVarTuple
match ctx.kind with
| Kind.regular => unreachable!
| Kind.forIn => ``(Pure.pure (ForInStep.done $u))
| Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u)))
| Kind.nestedBC => ``(Pure.pure (DoResultBC.Β«breakΒ» $u))
| Kind.nestedPR => unreachable!
| Kind.nestedSBC => ``(Pure.pure (DoResultSBC.Β«breakΒ» $u))
| Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.Β«breakΒ» $u))
def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do
let ctx β read
let u β mkUVarTuple
match ctx.kind with
| Kind.regular => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u))
| Kind.forIn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u))
| Kind.forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u)))
| Kind.nestedBC => unreachable!
| Kind.nestedPR => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.Β«pureΒ» y $u)))
| Kind.nestedSBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.Β«pureReturnΒ» y $u)))
| Kind.nestedPRBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.Β«pureΒ» y $u)))
def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do
if action.getKind == `Lean.Parser.Term.doDbgTrace then
let msg := action[1]
`(dbg_trace $msg; $k)
else if action.getKind == `Lean.Parser.Term.doAssert then
let cond := action[1]
`(assert! $cond; $k)
else
let action β withRef action ``(($action : $((βread).m) PUnit))
``(Bind.bind $action (fun (_ : PUnit) => $k))
def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do
let kind := decl.getKind
if kind == `Lean.Parser.Term.doLet then
let letDecl := decl[2]
`(let $letDecl:letDecl; $k)
else if kind == `Lean.Parser.Term.doLetRec then
let letRecToken := decl[0]
let letRecDecls := decl[1]
pure $ mkNode `Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k]
else if kind == `Lean.Parser.Term.doLetArrow then
let arg := decl[2]
let ref := arg
if arg.getKind == `Lean.Parser.Term.doIdDecl then
let id := arg[0]
let type := expandOptType ref arg[1]
let doElem := arg[3]
-- `doElem` must be a `doExpr action`. See `doLetArrowToCode`
match isDoExpr? doElem with
| some action =>
let action β withRef action `(($action : $((β read).m) $type))
``(Bind.bind $action (fun ($id:ident : $type) => $k))
| none => Macro.throwErrorAt decl "unexpected kind of 'do' declaration"
else
Macro.throwErrorAt decl "unexpected kind of 'do' declaration"
else if kind == `Lean.Parser.Term.doHave then
-- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser`
let args := decl.getArgs
let args := args ++ #[mkNullNode /- optional ';' -/, k]
pure $ mkNode `Lean.Parser.Term.Β«haveΒ» args
else
Macro.throwErrorAt decl "unexpected kind of 'do' declaration"
def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do
let kind := reassign.getKind
if kind == `Lean.Parser.Term.doReassign then
-- doReassign := leading_parser (letIdDecl <|> letPatDecl)
let arg := reassign[0]
if arg.getKind == `Lean.Parser.Term.letIdDecl then
-- letIdDecl := leading_parser ident >> many (ppSpace >> bracketedBinder) >> optType >> " := " >> termParser
let x := arg[0]
let val := arg[4]
let newVal β `(ensureTypeOf% $x $(quote "invalid reassignment, value") $val)
let arg := arg.setArg 4 newVal
let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]
`(let $letDecl:letDecl; $k)
else
-- TODO: ensure the types did not change
let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]
`(let $letDecl:letDecl; $k)
else
-- Note that `doReassignArrow` is expanded by `doReassignArrowToCode
Macro.throwErrorAt reassign "unexpected kind of 'do' reassignment"
def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do
if optIdent.isNone then
``(ite $cond $thenBranch $elseBranch)
else
let h := optIdent[0]
``(dite $cond (fun $h => $thenBranch) (fun $h => $elseBranch))
def mkJoinPoint (j : Name) (ps : Array (Name Γ Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do
let pTypes β ps.mapM fun β¨id, useTypeOfβ© => do if useTypeOf then `(typeOf% $(β mkIdentFromRef id)) else `(_)
let ps β ps.mapM fun β¨id, useTypeOfβ© => mkIdentFromRef id
/-
We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`.
By elaborating `$k` first, we "learn" more about `$body`'s type.
For example, consider the following example `do` expression
```
def f (x : Nat) : IO Unit := do
if x > 0 then
IO.println "x is not zero" -- Error is here
IO.mkRef true
```
it is expanded into
```
def f (x : Nat) : IO Unit := do
let jp (u : Unit) : IO _ :=
IO.mkRef true;
if x > 0 then
IO.println "not zero"
jp ()
else
jp ()
```
If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit β IO (IO.Ref Bool)`.
Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit β IO Unit`.
Then, we get the expected type mismatch error at `IO.mkRef true`. -/
`(let_delayed $(β mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((β read).m) _ := $body; $k)
def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax :=
Syntax.mkApp (mkIdentFrom ref j) args
partial def toTerm : Code β M Syntax
| Code.Β«returnΒ» ref val => withRef ref <| returnToTerm val
| Code.Β«continueΒ» ref => withRef ref continueToTerm
| Code.Β«breakΒ» ref => withRef ref breakToTerm
| Code.action e => actionTerminalToTerm e
| Code.joinpoint j ps b k => do mkJoinPoint j ps (β toTerm b) (β toTerm k)
| Code.jmp ref j args => pure $ mkJmp ref j args
| Code.decl _ stx k => do declToTerm stx (β toTerm k)
| Code.reassign _ stx k => do reassignToTerm stx (β toTerm k)
| Code.seq stx k => do seqToTerm stx (β toTerm k)
| Code.ite ref _ o c t e => withRef ref <| do mkIte o c (β toTerm t) (β toTerm e)
| Code.Β«matchΒ» ref genParam discrs optType alts => do
let mut termAlts := #[]
for alt in alts do
let rhs β toTerm alt.rhs
let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", alt.patterns, mkAtomFrom alt.ref "=>", rhs]
termAlts := termAlts.push termAlt
let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts]
pure $ mkNode `Lean.Parser.Term.Β«matchΒ» #[mkAtomFrom ref "match", genParam, discrs, optType, mkAtomFrom ref "with", termMatchAlts]
def run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do
let term β toTerm code { m := m, kind := kind, uvars := uvars }
pure term
/- Given
- `a` is true if the code block has a `Code.action _` exit point
- `r` is true if the code block has a `Code.return _ _` exit point
- `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point
generate Kind. See comment at the beginning of the `ToTerm` namespace. -/
def mkNestedKind (a r bc : Bool) : Kind :=
match a, r, bc with
| true, false, false => Kind.regular
| false, true, false => Kind.regular
| false, false, true => Kind.nestedBC
| true, true, false => Kind.nestedPR
| true, false, true => Kind.nestedSBC
| false, true, true => Kind.nestedSBC
| true, true, true => Kind.nestedPRBC
| false, false, false => unreachable!
def mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do
ToTerm.run code m uvars (mkNestedKind a r bc)
/- Given a term `term` produced by `ToTerm.run`, pattern match on its result.
See comment at the beginning of the `ToTerm` namespace.
- `a` is true if the code block has a `Code.action _` exit point
- `r` is true if the code block has a `Code.return _ _` exit point
- `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point
The result is a sequence of `doElem` -/
def matchNestedTermResult (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do
let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo)
let u β mkTuple (β uvars.mapM mkIdentFromRef)
match a, r, bc with
| true, false, false =>
if uvars.isEmpty then
toDoElems (β `(do $term:term))
else
toDoElems (β `(do let r β $term:term; $u:term := r.2; pure r.1))
| false, true, false =>
if uvars.isEmpty then
toDoElems (β `(do let r β $term:term; return r))
else
toDoElems (β `(do let r β $term:term; $u:term := r.2; return r.1))
| false, false, true => toDoElems <$>
`(do let r β $term:term;
match r with
| DoResultBC.Β«breakΒ» u => $u:term := u; break
| DoResultBC.Β«continueΒ» u => $u:term := u; continue)
| true, true, false => toDoElems <$>
`(do let r β $term:term;
match r with
| DoResultPR.Β«pureΒ» a u => $u:term := u; pure a
| DoResultPR.Β«returnΒ» b u => $u:term := u; return b)
| true, false, true => toDoElems <$>
`(do let r β $term:term;
match r with
| DoResultSBC.Β«pureReturnΒ» a u => $u:term := u; pure a
| DoResultSBC.Β«breakΒ» u => $u:term := u; break
| DoResultSBC.Β«continueΒ» u => $u:term := u; continue)
| false, true, true => toDoElems <$>
`(do let r β $term:term;
match r with
| DoResultSBC.Β«pureReturnΒ» a u => $u:term := u; return a
| DoResultSBC.Β«breakΒ» u => $u:term := u; break
| DoResultSBC.Β«continueΒ» u => $u:term := u; continue)
| true, true, true => toDoElems <$>
`(do let r β $term:term;
match r with
| DoResultPRBC.Β«pureΒ» a u => $u:term := u; pure a
| DoResultPRBC.Β«returnΒ» a u => $u:term := u; return a
| DoResultPRBC.Β«breakΒ» u => $u:term := u; break
| DoResultPRBC.Β«continueΒ» u => $u:term := u; continue)
| false, false, false => unreachable!
end ToTerm
def isMutableLet (doElem : Syntax) : Bool :=
let kind := doElem.getKind
(kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet)
&&
!doElem[1].isNone
namespace ToCodeBlock
structure Context where
ref : Syntax
m : Syntax -- Syntax representing the monad associated with the do notation.
mutableVars : NameSet := {}
insideFor : Bool := false
abbrev M := ReaderT Context TermElabM
@[inline] def withNewMutableVars {Ξ±} (newVars : Array Name) (mutable : Bool) (x : M Ξ±) : M Ξ± :=
withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x
def checkReassignable (xs : Array Name) : M Unit := do
let throwInvalidReassignment (x : Name) : M Unit :=
throwError "'{x.simpMacroScopes}' cannot be reassigned"
let ctx β read
for x in xs do
unless ctx.mutableVars.contains x do
throwInvalidReassignment x
def checkNotShadowingMutable (xs : Array Name) : M Unit := do
let throwInvalidShadowing (x : Name) : M Unit :=
throwError "mutable variable '{x.simpMacroScopes}' cannot be shadowed"
let ctx β read
for x in xs do
if ctx.mutableVars.contains x then
throwInvalidShadowing x
@[inline] def withFor {Ξ±} (x : M Ξ±) : M Ξ± :=
withReader (fun ctx => { ctx with insideFor := true }) x
structure ToForInTermResult where
uvars : Array Name
term : Syntax
def mkForInBody (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do
let ctx β read
let uvars := forInBody.uvars
let uvars := nameSetToArray uvars
let term β liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn)
pure β¨uvars, termβ©
def ensureInsideFor : M Unit :=
unless (β read).insideFor do
throwError "invalid 'do' element, it must be inside 'for'"
def ensureEOS (doElems : List Syntax) : M Unit :=
unless doElems.isEmpty do
throwError "must be last element in a 'do' sequence"
private partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax β StateT (List Syntax) MacroM Syntax
| stx@(Syntax.node k args) =>
if liftMethodDelimiter k then
return stx
else if k == `Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do
if inBinder then
Macro.throwErrorAt stx "cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`"
let term := args[1]
let term β expandLiftMethodAux inQuot inBinder term
let auxDoElem β `(doElem| let a β $term:term)
modify fun s => s ++ [auxDoElem]
`(a)
else do
let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot
let inBinder := inBinder || (!inQuot && liftMethodForbiddenBinder stx)
let args β args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder)
return Syntax.node k args
| stx => pure stx
def expandLiftMethod (doElem : Syntax) : MacroM (List Syntax Γ Syntax) := do
if !hasLiftMethod doElem then
pure ([], doElem)
else
let (doElem, doElemsNew) β (expandLiftMethodAux false false doElem).run []
pure (doElemsNew, doElem)
def checkLetArrowRHS (doElem : Syntax) : M Unit := do
let kind := doElem.getKind
if kind == `Lean.Parser.Term.doLetArrow ||
kind == `Lean.Parser.Term.doLet ||
kind == `Lean.Parser.Term.doLetRec ||
kind == `Lean.Parser.Term.doHave ||
kind == `Lean.Parser.Term.doReassign ||
kind == `Lean.Parser.Term.doReassignArrow then
throwErrorAt doElem "invalid kind of value '{kind}' in an assignment"
/- Generate `CodeBlock` for `doReturn` which is of the form
```
"return " >> optional termParser
```
`doElems` is only used for sanity checking. -/
def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do
ensureEOS doElems
let argOpt := doReturn[1]
let arg β if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0]
return mkReturn (β getRef) arg
structure Catch where
x : Syntax
optType : Syntax
codeBlock : CodeBlock
def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet :=
let ws := tryCode.uvars
let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws
let ws := match finallyCode? with
| none => ws
| some c => union c.uvars ws
ws
def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code β Bool) : Bool :=
p tryCode.code ||
catches.any (fun Β«catchΒ» => p Β«catchΒ».codeBlock.code) ||
match finallyCode? with
| none => false
| some finallyCode => p finallyCode.code
mutual
/- "Concatenate" `c` with `doSeqToCode doElems` -/
partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock :=
match doElems with
| [] => pure c
| nextDoElem :: _ => do
let k β doSeqToCode doElems
let ref := nextDoElem
concat c ref none k
/- Generate `CodeBlock` for `doLetArrow; doElems`
`doLetArrow` is of the form
```
"let " >> optional "mut " >> (doIdDecl <|> doPatDecl)
```
where
```
def doIdDecl := leading_parser ident >> optType >> leftArrow >> doElemParser
def doPatDecl := leading_parser termParser >> leftArrow >> doElemParser >> optional (" | " >> doElemParser)
```
-/
partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do
let ref := doLetArrow
let decl := doLetArrow[2]
if decl.getKind == `Lean.Parser.Term.doIdDecl then
let y := decl[0].getId
checkNotShadowingMutable #[y]
let doElem := decl[3]
let k β withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems)
match isDoExpr? doElem with
| some action => pure $ mkVarDeclCore #[y] doLetArrow k
| none =>
checkLetArrowRHS doElem
let c β doSeqToCode [doElem]
match doElems with
| [] => pure c
| kRef::_ => concat c kRef y k
else if decl.getKind == `Lean.Parser.Term.doPatDecl then
let pattern := decl[0]
let doElem := decl[2]
let optElse := decl[3]
if optElse.isNone then withFreshMacroScope do
let auxDo β
if isMutableLet doLetArrow then
`(do let discr β $doElem; let mut $pattern:term := discr)
else
`(do let discr β $doElem; let $pattern:term := discr)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else
if isMutableLet doLetArrow then
throwError "'mut' is currently not supported in let-decls with 'else' case"
let contSeq := mkDoSeq doElems.toArray
let elseSeq := mkSingletonDoSeq optElse[1]
let auxDo β `(do let discr β $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo)
else
throwError "unexpected kind of 'do' declaration"
/- Generate `CodeBlock` for `doReassignArrow; doElems`
`doReassignArrow` is of the form
```
(doIdDecl <|> doPatDecl)
```
-/
partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do
let ref := doReassignArrow
let decl := doReassignArrow[0]
if decl.getKind == `Lean.Parser.Term.doIdDecl then
let doElem := decl[3]
let y := decl[0]
let auxDo β `(do let r β $doElem; $y:ident := r)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else if decl.getKind == `Lean.Parser.Term.doPatDecl then
let pattern := decl[0]
let doElem := decl[2]
let optElse := decl[3]
if optElse.isNone then withFreshMacroScope do
let auxDo β `(do let discr β $doElem; $pattern:term := discr)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else
throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported"
else
throwError "unexpected kind of 'do' reassignment"
/- Generate `CodeBlock` for `doIf; doElems`
`doIf` is of the form
```
"if " >> optIdent >> termParser >> " then " >> doSeq
>> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq))
>> optional (" else " >> doSeq)
``` -/
partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do
let view β liftMacroM $ mkDoIfView doIf
let thenBranch β doSeqToCode (getDoSeqElems view.thenBranch)
let elseBranch β doSeqToCode (getDoSeqElems view.elseBranch)
let ite β mkIte view.ref view.optIdent view.cond thenBranch elseBranch
concatWith ite doElems
/- Generate `CodeBlock` for `doUnless; doElems`
`doUnless` is of the form
```
"unless " >> termParser >> "do " >> doSeq
``` -/
partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do
let ref := doUnless
let cond := doUnless[1]
let doSeq := doUnless[3]
let body β doSeqToCode (getDoSeqElems doSeq)
let unlessCode β liftMacroM <| mkUnless cond body
concatWith unlessCode doElems
/- Generate `CodeBlock` for `doFor; doElems`
`doFor` is of the form
```
def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser
def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq
```
-/
partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do
let doForDecls := doFor[1].getSepArgs
if doForDecls.size > 1 then
/-
Expand
```
for x in xs, y in ys do
body
```
into
```
let s := toStream ys
for x in xs do
match Stream.next? s with
| none => break
| some (y, s') =>
s := s'
body
```
-/
-- Extract second element
let doForDecl := doForDecls[1]
let y := doForDecl[0]
let ys := doForDecl[2]
let doForDecls := doForDecls.eraseIdx 1
let body := doFor[3]
withFreshMacroScope do
let toStreamFn β withRef ys ``(toStream)
let auxDo β
`(do let mut s := $toStreamFn:ident $ys
for $doForDecls:doForDecl,* do
match Stream.next? s with
| none => break
| some ($y, s') =>
s := s'
do $body)
doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)
else withRef doFor do
let x := doForDecls[0][0]
withRef x <| checkNotShadowingMutable (β getPatternVarsEx x)
let xs := doForDecls[0][2]
let forElems := getDoSeqElems doFor[3]
let forInBodyCodeBlock β withFor (doSeqToCode forElems)
let β¨uvars, forInBodyβ© β mkForInBody x forInBodyCodeBlock
let uvarsTuple β liftMacroM do mkTuple (β uvars.mapM mkIdentFromRef)
if hasReturn forInBodyCodeBlock.code then
let forInBody β liftMacroM <| destructTuple uvars (β `(r)) forInBody
let forInTerm β `(forIn% $(xs) (MProd.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody)
let auxDo β `(do let r β $forInTerm:term;
$uvarsTuple:term := r.2;
match r.1 with
| none => Pure.pure (ensureExpectedType% "type mismatch, 'for'" PUnit.unit)
| some a => return ensureExpectedType% "type mismatch, 'for'" a)
doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)
else
let forInBody β liftMacroM <| destructTuple uvars (β `(r)) forInBody
let forInTerm β `(forIn% $(xs) $uvarsTuple fun $x r => $forInBody)
if doElems.isEmpty then
let auxDo β `(do let r β $forInTerm:term;
$uvarsTuple:term := r;
Pure.pure (ensureExpectedType% "type mismatch, 'for'" PUnit.unit))
doSeqToCode <| getDoSeqElems (getDoSeq auxDo)
else
let auxDo β `(do let r β $forInTerm:term; $uvarsTuple:term := r)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
/-- Generate `CodeBlock` for `doMatch; doElems` -/
partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do
let ref := doMatch
let genParam := doMatch[1]
let discrs := doMatch[2]
let optType := doMatch[3]
let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt`
let alts β matchAlts.mapM fun matchAlt => do
let patterns := matchAlt[1]
let vars β getPatternsVarsEx patterns.getSepArgs
withRef patterns <| checkNotShadowingMutable vars
let rhs := matchAlt[3]
let rhs β doSeqToCode (getDoSeqElems rhs)
pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock }
let matchCode β mkMatch ref genParam discrs optType alts
concatWith matchCode doElems
/--
Generate `CodeBlock` for `doTry; doElems`
```
def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally
def doCatch := leading_parser "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq
def doCatchMatch := leading_parser "catch " >> doMatchAlts
def doFinally := leading_parser "finally " >> doSeq
```
-/
partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do
let ref := doTry
let tryCode β doSeqToCode (getDoSeqElems doTry[1])
let optFinally := doTry[3]
let catches β doTry[2].getArgs.mapM fun catchStx => do
if catchStx.getKind == `Lean.Parser.Term.doCatch then
let x := catchStx[1]
if x.isIdent then
withRef x <| checkNotShadowingMutable #[x.getId]
let optType := catchStx[2]
let c β doSeqToCode (getDoSeqElems catchStx[4])
pure { x := x, optType := optType, codeBlock := c : Catch }
else if catchStx.getKind == `Lean.Parser.Term.doCatchMatch then
let matchAlts := catchStx[1]
let x β `(ex)
let auxDo β `(do match ex with $matchAlts)
let c β doSeqToCode (getDoSeqElems (getDoSeq auxDo))
pure { x := x, codeBlock := c, optType := mkNullNode : Catch }
else
throwError "unexpected kind of 'catch'"
let finallyCode? β if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1])
if catches.isEmpty && finallyCode?.isNone then
throwError "invalid 'try', it must have a 'catch' or 'finally'"
let ctx β read
let ws := getTryCatchUpdatedVars tryCode catches finallyCode?
let uvars := nameSetToArray ws
let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction
let r := tryCatchPred tryCode catches finallyCode? hasReturn
let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue
let toTerm (codeBlock : CodeBlock) : M Syntax := do
let codeBlock β liftM $ extendUpdatedVars codeBlock ws
liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc
let term β toTerm tryCode
let term β catches.foldlM
(fun term Β«catchΒ» => do
let catchTerm β toTerm Β«catchΒ».codeBlock
if catch.optType.isNone then
``(MonadExcept.tryCatch $term (fun $(Β«catchΒ».x):ident => $catchTerm))
else
let type := Β«catchΒ».optType[1]
``(tryCatchThe $type $term (fun $(Β«catchΒ».x):ident => $catchTerm)))
term
let term β match finallyCode? with
| none => pure term
| some finallyCode => withRef optFinally do
unless finallyCode.uvars.isEmpty do
throwError "'finally' currently does not support reassignments"
if hasBreakContinueReturn finallyCode.code then
throwError "'finally' currently does 'return', 'break', nor 'continue'"
let finallyTerm β liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular
``(tryFinally $term $finallyTerm)
let doElemsNew β liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc
doSeqToCode (doElemsNew ++ doElems)
partial def doSeqToCode : List Syntax β M CodeBlock
| [] => do liftMacroM mkPureUnitAction
| doElem::doElems => withIncRecDepth <| withRef doElem do
checkMaxHeartbeats "'do'-expander"
match (β liftMacroM <| expandMacro? doElem) with
| some doElem => doSeqToCode (doElem::doElems)
| none =>
match (β liftMacroM <| expandDoIf? doElem) with
| some doElem => doSeqToCode (doElem::doElems)
| none =>
let (liftedDoElems, doElem) β liftM (liftMacroM <| expandLiftMethod doElem : TermElabM _)
if !liftedDoElems.isEmpty then
doSeqToCode (liftedDoElems ++ [doElem] ++ doElems)
else
let ref := doElem
let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems
let k := doElem.getKind
if k == `Lean.Parser.Term.doLet then
let vars β getDoLetVars doElem
checkNotShadowingMutable vars
mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems)
else if k == `Lean.Parser.Term.doHave then
let var := getDoHaveVar doElem
checkNotShadowingMutable #[var]
mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems)
else if k == `Lean.Parser.Term.doLetRec then
let vars β getDoLetRecVars doElem
checkNotShadowingMutable vars
mkVarDeclCore vars doElem <$> (doSeqToCode doElems)
else if k == `Lean.Parser.Term.doReassign then
let vars β getDoReassignVars doElem
checkReassignable vars
let k β doSeqToCode doElems
mkReassignCore vars doElem k
else if k == `Lean.Parser.Term.doLetArrow then
doLetArrowToCode doElem doElems
else if k == `Lean.Parser.Term.doReassignArrow then
doReassignArrowToCode doElem doElems
else if k == `Lean.Parser.Term.doIf then
doIfToCode doElem doElems
else if k == `Lean.Parser.Term.doUnless then
doUnlessToCode doElem doElems
else if k == `Lean.Parser.Term.doFor then withFreshMacroScope do
doForToCode doElem doElems
else if k == `Lean.Parser.Term.doMatch then
doMatchToCode doElem doElems
else if k == `Lean.Parser.Term.doTry then
doTryToCode doElem doElems
else if k == `Lean.Parser.Term.doBreak then
ensureInsideFor
ensureEOS doElems
return mkBreak ref
else if k == `Lean.Parser.Term.doContinue then
ensureInsideFor
ensureEOS doElems
return mkContinue ref
else if k == `Lean.Parser.Term.doReturn then
doReturnToCode doElem doElems
else if k == `Lean.Parser.Term.doDbgTrace then
return mkSeq doElem (β doSeqToCode doElems)
else if k == `Lean.Parser.Term.doAssert then
return mkSeq doElem (β doSeqToCode doElems)
else if k == `Lean.Parser.Term.doNested then
let nestedDoSeq := doElem[1]
doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems)
else if k == `Lean.Parser.Term.doExpr then
let term := doElem[0]
if doElems.isEmpty then
return mkTerminalAction term
else
return mkSeq term (β doSeqToCode doElems)
else
throwError "unexpected do-element of kind {doElem.getKind}:\n{doElem}"
end
def run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock :=
(doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m := m }
end ToCodeBlock
/- Create a synthetic metavariable `?m` and assign `m` to it.
We use `?m` to refer to `m` when expanding the `do` notation. -/
private def mkMonadAlias (m : Expr) : TermElabM Syntax := do
let result β `(?m)
let mType β inferType m
let mvar β elabTerm result mType
assignExprMVar mvar.mvarId! m
pure result
@[builtinTermElab Β«doΒ»]
def elabDo : TermElab := fun stx expectedType? => do
tryPostponeIfNoneOrMVar expectedType?
let bindInfo β extractBind expectedType?
let m β mkMonadAlias bindInfo.m
let codeBlock β ToCodeBlock.run stx m
let stxNew β liftMacroM $ ToTerm.run codeBlock.code m
trace[Elab.do] stxNew
withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType
end Do
builtin_initialize registerTraceClass `Elab.do
private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do
let stx := stx.setKind newKind
withRef stx `(do $stx:doElem)
@[builtinMacro Lean.Parser.Term.termFor]
def expandTermFor : Macro := toDoElem `Lean.Parser.Term.doFor
@[builtinMacro Lean.Parser.Term.termTry]
def expandTermTry : Macro := toDoElem `Lean.Parser.Term.doTry
@[builtinMacro Lean.Parser.Term.termUnless]
def expandTermUnless : Macro := toDoElem `Lean.Parser.Term.doUnless
@[builtinMacro Lean.Parser.Term.termReturn]
def expandTermReturn : Macro := toDoElem `Lean.Parser.Term.doReturn
end Lean.Elab.Term
|
94c799ff3bb800e25ccd0fe42bf1359a2c1c617b | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/measure_theory/indicator_function.lean | 8be40ceae035fbf85ccd1f429cb307837266a5ab | [
"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 | 5,641 | lean | /-
Copyright (c) 2020 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import data.indicator_function
import measure_theory.measure_space
import analysis.normed_space.basic
/-!
# Indicator function
Properties of indicator functions.
## Tags
indicator, characteristic
-/
noncomputable theory
open_locale classical
open set measure_theory filter
universes u v
variables {Ξ± : Type u} {Ξ² : Type v}
section has_zero
variables [has_zero Ξ²] {s t : set Ξ±} {f g : Ξ± β Ξ²} {a : Ξ±}
lemma indicator_congr_ae [measure_space Ξ±] (h : ββ a, a β s β f a = g a) :
ββ a, indicator s f a = indicator s g a :=
begin
filter_upwards [h],
simp only [mem_set_of_eq, indicator],
assume a ha,
split_ifs with hβ,
{ exact ha hβ },
refl
end
lemma indicator_congr_of_set [measure_space Ξ±] (h : ββ a, a β s β a β t) :
ββ a, indicator s f a = indicator t f a :=
begin
filter_upwards [h],
simp only [mem_set_of_eq, indicator],
assume a ha,
split_ifs with hβ hβ hβ,
{ refl },
{ have := ha.1 hβ, contradiction },
{ have := ha.2 hβ, contradiction },
refl
end
end has_zero
section has_add
variables [add_monoid Ξ²] {s t : set Ξ±} {f g : Ξ± β Ξ²} {a : Ξ±}
lemma indicator_union_ae [measure_space Ξ±] {Ξ² : Type*} [add_monoid Ξ²]
(h : ββ a, a β s β© t) (f : Ξ± β Ξ²) :
ββ a, indicator (s βͺ t) f a = indicator s f a + indicator t f a :=
begin
filter_upwards [h],
simp only [mem_set_of_eq],
assume a ha,
exact indicator_union_of_not_mem_inter ha _
end
end has_add
section norm
variables [normed_group Ξ²] {s t : set Ξ±} {f g : Ξ± β Ξ²} {a : Ξ±}
lemma norm_indicator_le_of_subset (h : s β t) (f : Ξ± β Ξ²) (a : Ξ±) :
β₯indicator s f aβ₯ β€ β₯indicator t f aβ₯ :=
begin
simp only [indicator],
split_ifs with hβ hβ,
{ refl },
{ exact absurd (h hβ) hβ },
{ simp only [norm_zero, norm_nonneg] },
refl
end
lemma norm_indicator_le_norm_self (f : Ξ± β Ξ²) (a : Ξ±) : β₯indicator s f aβ₯ β€ β₯f aβ₯ :=
by { convert norm_indicator_le_of_subset (subset_univ s) f a, rw indicator_univ }
lemma norm_indicator_eq_indicator_norm (f : Ξ± β Ξ²) (a : Ξ±) : β₯indicator s f aβ₯ = indicator s (Ξ»a, β₯f aβ₯) a :=
by { simp only [indicator], split_ifs, { refl }, rw norm_zero }
lemma indicator_norm_le_norm_self (f : Ξ± β Ξ²) (a : Ξ±) : indicator s (Ξ»a, β₯f aβ₯) a β€ β₯f aβ₯ :=
by { rw β norm_indicator_eq_indicator_norm, exact norm_indicator_le_norm_self _ _ }
end norm
section order
variables [has_zero Ξ²] [preorder Ξ²] {s t : set Ξ±} {f g : Ξ± β Ξ²} {a : Ξ±}
lemma indicator_le_indicator_ae [measure_space Ξ±] (h : ββ a, a β s β f a β€ g a) :
ββ a, indicator s f a β€ indicator s g a :=
begin
refine h.mono (Ξ» a h, _),
simp only [indicator],
split_ifs with ha,
{ exact h ha },
refl
end
end order
section tendsto
variables {ΞΉ : Type*} [semilattice_sup ΞΉ] [has_zero Ξ²]
lemma tendsto_indicator_of_monotone [nonempty ΞΉ] (s : ΞΉ β set Ξ±) (hs : monotone s) (f : Ξ± β Ξ²)
(a : Ξ±) : tendsto (Ξ»i, indicator (s i) f a) at_top (pure $ indicator (Union s) f a) :=
begin
by_cases h : βi, a β s i,
{ simp only [tendsto_pure, mem_at_top_sets, mem_set_of_eq],
rcases h with β¨i, hiβ©,
use i, assume n hn,
rw [indicator_of_mem (hs hn hi) _, indicator_of_mem ((subset_Union _ _) hi) _] },
{ rw [not_exists] at h,
have : (Ξ»i, indicator (s i) f a) = Ξ»i, 0 := funext (Ξ»i, indicator_of_not_mem (h i) _),
rw this,
have : indicator (Union s) f a = 0,
{ apply indicator_of_not_mem, simpa only [not_exists, mem_Union] },
rw this,
exact tendsto_const_pure }
end
lemma tendsto_indicator_of_antimono [nonempty ΞΉ] (s : ΞΉ β set Ξ±) (hs : βi j, i β€ j β s j β s i) (f : Ξ± β Ξ²)
(a : Ξ±) : tendsto (Ξ»i, indicator (s i) f a) at_top (pure $ indicator (Inter s) f a) :=
begin
by_cases h : βi, a β s i,
{ simp only [tendsto_pure, mem_at_top_sets, mem_set_of_eq],
rcases h with β¨i, hiβ©,
use i, assume n hn,
rw [indicator_of_not_mem _ _, indicator_of_not_mem _ _],
{ simp only [mem_Inter, not_forall], exact β¨i, hiβ© },
{ assume h, have := hs i _ hn h, contradiction } },
{ simp only [not_exists, not_not_mem] at h,
have : (Ξ»i, indicator (s i) f a) = Ξ»i, f a := funext (Ξ»i, indicator_of_mem (h i) _),
rw this,
have : indicator (Inter s) f a = f a,
{ apply indicator_of_mem, simpa only [mem_Inter] },
rw this,
exact tendsto_const_pure }
end
lemma tendsto_indicator_bUnion_finset (s : ΞΉ β set Ξ±) (f : Ξ± β Ξ²) (a : Ξ±) :
tendsto (Ξ» (n : finset ΞΉ), indicator (βiβn, s i) f a) at_top (pure $ indicator (Union s) f a) :=
begin
by_cases h : βi, a β s i,
{ simp only [mem_at_top_sets, tendsto_pure, mem_set_of_eq, ge_iff_le, finset.le_iff_subset],
rcases h with β¨i, hiβ©,
use {i}, assume n hn,
replace hn : i β n := hn (finset.mem_singleton_self _),
rw [indicator_of_mem, indicator_of_mem],
{ rw [mem_Union], use i, assumption },
{ rw [mem_Union], use i, rw [mem_Union], use hn, assumption } },
{ rw [not_exists] at h,
have : (Ξ» (n : finset ΞΉ), indicator (β (i : ΞΉ) (H : i β n), s i) f a) = Ξ»i, 0,
{ funext,
rw indicator_of_not_mem,
simp only [not_exists, exists_prop, mem_Union, not_and],
intros, apply h },
rw this,
have : indicator (Union s) f a = 0,
{ apply indicator_of_not_mem, simpa only [not_exists, mem_Union] },
rw this,
exact tendsto_const_pure }
end
end tendsto
|
4036e6be766b3895effd0bb449367f2463a412da | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/limits/constructions/finite_products_of_binary_products.lean | b85b98d01021d3e812e8e07307e3a1c7e683c38e | [
"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 | 12,065 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.limits.preserves.shapes.binary_products
import category_theory.limits.preserves.shapes.products
import category_theory.limits.shapes.binary_products
import category_theory.limits.shapes.finite_products
import logic.equiv.fin
/-!
# Constructing finite products from binary products and terminal.
If a category has binary products and a terminal object then it has finite products.
If a functor preserves binary products and the terminal object then it preserves finite products.
# TODO
Provide the dual results.
Show the analogous results for functors which reflect or create (co)limits.
-/
universes v v' u u'
noncomputable theory
open category_theory category_theory.category category_theory.limits
namespace category_theory
variables {J : Type v} [small_category J]
variables {C : Type u} [category.{v} C]
variables {D : Type u'} [category.{v'} D]
/--
Given `n+1` objects of `C`, a fan for the last `n` with point `cβ.X` and a binary fan on `cβ.X` and
`f 0`, we can build a fan for all `n+1`.
In `extend_fan_is_limit` we show that if the two given fans are limits, then this fan is also a
limit.
-/
@[simps {rhs_md := semireducible}]
def extend_fan {n : β} {f : fin (n+1) β C}
(cβ : fan (Ξ» (i : fin n), f i.succ))
(cβ : binary_fan (f 0) cβ.X) :
fan f :=
fan.mk cβ.X
begin
refine fin.cases _ _,
{ apply cβ.fst },
{ intro i, apply cβ.snd β« cβ.Ο.app β¨iβ© },
end
/--
Show that if the two given fans in `extend_fan` are limits, then the constructed fan is also a
limit.
-/
def extend_fan_is_limit {n : β} (f : fin (n+1) β C)
{cβ : fan (Ξ» (i : fin n), f i.succ)} {cβ : binary_fan (f 0) cβ.X}
(tβ : is_limit cβ) (tβ : is_limit cβ) :
is_limit (extend_fan cβ cβ) :=
{ lift := Ξ» s,
begin
apply (binary_fan.is_limit.lift' tβ (s.Ο.app β¨0β©) _).1,
apply tβ.lift β¨_, discrete.nat_trans (Ξ» β¨iβ©, s.Ο.app β¨i.succβ©)β©
end,
fac' := Ξ» s β¨jβ©,
begin
apply fin.induction_on j,
{ apply (binary_fan.is_limit.lift' tβ _ _).2.1 },
{ rintro i -,
dsimp only [extend_fan_Ο_app],
rw [fin.cases_succ, β assoc, (binary_fan.is_limit.lift' tβ _ _).2.2, tβ.fac],
refl }
end,
uniq' := Ξ» s m w,
begin
apply binary_fan.is_limit.hom_ext tβ,
{ rw (binary_fan.is_limit.lift' tβ _ _).2.1,
apply w β¨0β© },
{ rw (binary_fan.is_limit.lift' tβ _ _).2.2,
apply tβ.uniq β¨_, _β©,
rintro β¨jβ©,
rw assoc,
dsimp only [discrete.nat_trans_app, extend_fan_is_limit._match_1],
rw β w β¨j.succβ©,
dsimp only [extend_fan_Ο_app],
rw fin.cases_succ }
end }
section
variables [has_binary_products C] [has_terminal C]
/--
If `C` has a terminal object and binary products, then it has a product for objects indexed by
`fin n`.
This is a helper lemma for `has_finite_products_of_has_binary_and_terminal`, which is more general
than this.
-/
private lemma has_product_fin :
Ξ (n : β) (f : fin n β C), has_product f
| 0 := Ξ» f,
begin
letI : has_limits_of_shape (discrete (fin 0)) C :=
has_limits_of_shape_of_equivalence (discrete.equivalence.{0} fin_zero_equiv'.symm),
apply_instance,
end
| (n+1) := Ξ» f,
begin
haveI := has_product_fin n,
apply has_limit.mk β¨_, extend_fan_is_limit f (limit.is_limit _) (limit.is_limit _)β©,
end
/-- If `C` has a terminal object and binary products, then it has finite products. -/
lemma has_finite_products_of_has_binary_and_terminal : has_finite_products C :=
begin
refine β¨Ξ» n, β¨Ξ» K, _β©β©,
letI := has_product_fin n (Ξ» n, K.obj β¨nβ©),
let : discrete.functor (Ξ» n, K.obj β¨nβ©) β
K := discrete.nat_iso (Ξ» β¨iβ©, iso.refl _),
apply has_limit_of_iso this,
end
end
section preserves
variables (F : C β₯€ D)
variables [preserves_limits_of_shape (discrete walking_pair) F]
variables [preserves_limits_of_shape (discrete.{0} pempty) F]
variables [has_finite_products.{v} C]
/--
If `F` preserves the terminal object and binary products, then it preserves products indexed by
`fin n` for any `n`.
-/
noncomputable def preserves_fin_of_preserves_binary_and_terminal :
Ξ (n : β) (f : fin n β C), preserves_limit (discrete.functor f) F
| 0 := Ξ» f,
begin
letI : preserves_limits_of_shape (discrete (fin 0)) F :=
preserves_limits_of_shape_of_equiv.{0 0}
(discrete.equivalence fin_zero_equiv'.symm) _,
apply_instance,
end
| (n+1) :=
begin
haveI := preserves_fin_of_preserves_binary_and_terminal n,
intro f,
refine preserves_limit_of_preserves_limit_cone
(extend_fan_is_limit f (limit.is_limit _) (limit.is_limit _)) _,
apply (is_limit_map_cone_fan_mk_equiv _ _ _).symm _,
let := extend_fan_is_limit (Ξ» i, F.obj (f i))
(is_limit_of_has_product_of_preserves_limit F _)
(is_limit_of_has_binary_product_of_preserves_limit F _ _),
refine is_limit.of_iso_limit this _,
apply cones.ext _ _,
apply iso.refl _,
rintro β¨jβ©,
apply fin.induction_on j,
{ apply (category.id_comp _).symm },
{ rintro i -,
dsimp only [extend_fan_Ο_app, iso.refl_hom, fan.mk_Ο_app],
rw [fin.cases_succ, fin.cases_succ],
change F.map _ β« _ = π _ β« _,
rw [id_comp, βF.map_comp],
refl }
end
/--
If `F` preserves the terminal object and binary products, then it preserves limits of shape
`discrete (fin n)`.
-/
def preserves_shape_fin_of_preserves_binary_and_terminal (n : β) :
preserves_limits_of_shape (discrete (fin n)) F :=
{ preserves_limit := Ξ» K,
begin
let : discrete.functor (Ξ» n, K.obj β¨nβ©) β
K := discrete.nat_iso (Ξ» β¨iβ©, iso.refl _),
haveI := preserves_fin_of_preserves_binary_and_terminal F n (Ξ» n, K.obj β¨nβ©),
apply preserves_limit_of_iso_diagram F this,
end }
/-- If `F` preserves the terminal object and binary products then it preserves finite products. -/
def preserves_finite_products_of_preserves_binary_and_terminal
(J : Type) [fintype J] :
preserves_limits_of_shape (discrete J) F :=
begin
classical,
let e := fintype.equiv_fin J,
haveI := preserves_shape_fin_of_preserves_binary_and_terminal F (fintype.card J),
apply preserves_limits_of_shape_of_equiv.{0 0}
(discrete.equivalence e).symm,
end
end preserves
/--
Given `n+1` objects of `C`, a cofan for the last `n` with point `cβ.X`
and a binary cofan on `cβ.X` and `f 0`, we can build a cofan for all `n+1`.
In `extend_cofan_is_colimit` we show that if the two given cofans are colimits,
then this cofan is also a colimit.
-/
@[simps {rhs_md := semireducible}]
def extend_cofan {n : β} {f : fin (n+1) β C}
(cβ : cofan (Ξ» (i : fin n), f i.succ))
(cβ : binary_cofan (f 0) cβ.X) :
cofan f :=
cofan.mk cβ.X
begin
refine fin.cases _ _,
{ apply cβ.inl },
{ intro i,
apply cβ.ΞΉ.app β¨iβ© β« cβ.inr },
end
/--
Show that if the two given cofans in `extend_cofan` are colimits,
then the constructed cofan is also a colimit.
-/
def extend_cofan_is_colimit {n : β} (f : fin (n+1) β C)
{cβ : cofan (Ξ» (i : fin n), f i.succ)} {cβ : binary_cofan (f 0) cβ.X}
(tβ : is_colimit cβ) (tβ : is_colimit cβ) :
is_colimit (extend_cofan cβ cβ) :=
{ desc := Ξ» s,
begin
apply (binary_cofan.is_colimit.desc' tβ (s.ΞΉ.app β¨0β©) _).1,
apply tβ.desc β¨_, discrete.nat_trans (Ξ» i, s.ΞΉ.app β¨i.as.succβ©)β©
end,
fac' := Ξ» s,
begin
rintro β¨jβ©,
apply fin.induction_on j,
{ apply (binary_cofan.is_colimit.desc' tβ _ _).2.1 },
{ rintro i -,
dsimp only [extend_cofan_ΞΉ_app],
rw [fin.cases_succ, assoc, (binary_cofan.is_colimit.desc' tβ _ _).2.2, tβ.fac],
refl }
end,
uniq' := Ξ» s m w,
begin
apply binary_cofan.is_colimit.hom_ext tβ,
{ rw (binary_cofan.is_colimit.desc' tβ _ _).2.1,
apply w β¨0β© },
{ rw (binary_cofan.is_colimit.desc' tβ _ _).2.2,
apply tβ.uniq β¨_, _β©,
rintro β¨jβ©,
dsimp only [discrete.nat_trans_app],
rw β w β¨j.succβ©,
dsimp only [extend_cofan_ΞΉ_app],
rw [fin.cases_succ, assoc], }
end }
section
variables [has_binary_coproducts C] [has_initial C]
/--
If `C` has an initial object and binary coproducts, then it has a coproduct for objects indexed by
`fin n`.
This is a helper lemma for `has_cofinite_products_of_has_binary_and_terminal`, which is more general
than this.
-/
private lemma has_coproduct_fin :
Ξ (n : β) (f : fin n β C), has_coproduct f
| 0 := Ξ» f,
begin
letI : has_colimits_of_shape (discrete (fin 0)) C :=
has_colimits_of_shape_of_equivalence (discrete.equivalence.{0} fin_zero_equiv'.symm),
apply_instance,
end
| (n+1) := Ξ» f,
begin
haveI := has_coproduct_fin n,
apply has_colimit.mk
β¨_, extend_cofan_is_colimit f (colimit.is_colimit _) (colimit.is_colimit _)β©,
end
/-- If `C` has an initial object and binary coproducts, then it has finite coproducts. -/
lemma has_finite_coproducts_of_has_binary_and_initial : has_finite_coproducts C :=
begin
refine β¨Ξ» n, β¨Ξ» K, _β©β©,
letI := has_coproduct_fin n (Ξ» n, K.obj β¨nβ©),
let : K β
discrete.functor (Ξ» n, K.obj β¨nβ©) := discrete.nat_iso (Ξ» β¨iβ©, iso.refl _),
apply has_colimit_of_iso this,
end
end
section preserves
variables (F : C β₯€ D)
variables [preserves_colimits_of_shape (discrete walking_pair) F]
variables [preserves_colimits_of_shape (discrete.{0} pempty) F]
variables [has_finite_coproducts.{v} C]
/--
If `F` preserves the initial object and binary coproducts, then it preserves products indexed by
`fin n` for any `n`.
-/
noncomputable def preserves_fin_of_preserves_binary_and_initial :
Ξ (n : β) (f : fin n β C), preserves_colimit (discrete.functor f) F
| 0 := Ξ» f,
begin
letI : preserves_colimits_of_shape (discrete (fin 0)) F :=
preserves_colimits_of_shape_of_equiv.{0 0}
(discrete.equivalence fin_zero_equiv'.symm) _,
apply_instance,
end
| (n+1) :=
begin
haveI := preserves_fin_of_preserves_binary_and_initial n,
intro f,
refine preserves_colimit_of_preserves_colimit_cocone
(extend_cofan_is_colimit f (colimit.is_colimit _) (colimit.is_colimit _)) _,
apply (is_colimit_map_cocone_cofan_mk_equiv _ _ _).symm _,
let := extend_cofan_is_colimit (Ξ» i, F.obj (f i))
(is_colimit_of_has_coproduct_of_preserves_colimit F _)
(is_colimit_of_has_binary_coproduct_of_preserves_colimit F _ _),
refine is_colimit.of_iso_colimit this _,
apply cocones.ext _ _,
apply iso.refl _,
rintro β¨jβ©,
apply fin.induction_on j,
{ apply category.comp_id },
{ rintro i -,
dsimp only [extend_cofan_ΞΉ_app, iso.refl_hom, cofan.mk_ΞΉ_app],
rw [fin.cases_succ, fin.cases_succ],
erw [comp_id, βF.map_comp],
refl, }
end
/--
If `F` preserves the initial object and binary coproducts, then it preserves colimits of shape
`discrete (fin n)`.
-/
def preserves_shape_fin_of_preserves_binary_and_initial (n : β) :
preserves_colimits_of_shape (discrete (fin n)) F :=
{ preserves_colimit := Ξ» K,
begin
let : discrete.functor (Ξ» n, K.obj β¨nβ©) β
K := discrete.nat_iso (Ξ» β¨iβ©, iso.refl _),
haveI := preserves_fin_of_preserves_binary_and_initial F n (Ξ» n, K.obj β¨nβ©),
apply preserves_colimit_of_iso_diagram F this,
end }
/-- If `F` preserves the initial object and binary coproducts then it preserves finite products. -/
def preserves_finite_coproducts_of_preserves_binary_and_initial
(J : Type) [fintype J] :
preserves_colimits_of_shape (discrete J) F :=
begin
classical,
let e := fintype.equiv_fin J,
haveI := preserves_shape_fin_of_preserves_binary_and_initial F (fintype.card J),
apply preserves_colimits_of_shape_of_equiv.{0 0} (discrete.equivalence e).symm,
end
end preserves
end category_theory
|
4abaa97ff49af047565c2305778e1536fa13de78 | 8eeb99d0fdf8125f5d39a0ce8631653f588ee817 | /src/measure_theory/integration.lean | 993b025888c5ec5d0dd5b62be63075a651ea52d2 | [
"Apache-2.0"
] | permissive | jesse-michael-han/mathlib | a15c58378846011b003669354cbab7062b893cfe | fa6312e4dc971985e6b7708d99a5bc3062485c89 | refs/heads/master | 1,625,200,760,912 | 1,602,081,753,000 | 1,602,081,753,000 | 181,787,230 | 0 | 0 | null | 1,555,460,682,000 | 1,555,460,682,000 | null | UTF-8 | Lean | false | false | 70,178 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johannes HΓΆlzl
-/
import measure_theory.measure_space
import measure_theory.borel_space
import data.indicator_function
import data.support
/-!
# Lebesgue integral for `ennreal`-valued functions
We define simple functions and show that each Borel measurable function on `ennreal` can be
approximated by a sequence of simple functions.
To prove something for an arbitrary measurable function into `ennreal`, the theorem
`measurable.ennreal_induction` shows that is it sufficient to show that the property holds for
(multiples of) characteristic functions and is closed under addition and supremum of increasing
sequences of functions.
## Notation
We introduce the following notation for the lower Lebesgue integral of a function `f : Ξ± β ennreal`.
* `β«β» x, f x βΞΌ`: integral of a function `f : Ξ± β ennreal` with respect to a measure `ΞΌ`;
* `β«β» x, f x`: integral of a function `f : Ξ± β ennreal` with respect to the canonical measure
`volume` on `Ξ±`;
* `β«β» x in s, f x βΞΌ`: integral of a function `f : Ξ± β ennreal` over a set `s` with respect
to a measure `ΞΌ`, defined as `β«β» x, f x β(ΞΌ.restrict s)`;
* `β«β» x in s, f x`: integral of a function `f : Ξ± β ennreal` over a set `s` with respect
to the canonical measure `volume`, defined as `β«β» x, f x β(volume.restrict s)`.
-/
noncomputable theory
open set (hiding restrict restrict_apply) filter ennreal
open_locale classical topological_space big_operators nnreal
namespace measure_theory
variables {Ξ± Ξ² Ξ³ Ξ΄ : Type*}
/-- A function `f` from a measurable space to any type is called *simple*,
if every preimage `f β»ΒΉ' {x}` is measurable, and the range is finite. This structure bundles
a function with these properties. -/
structure {u v} simple_func (Ξ± : Type u) [measurable_space Ξ±] (Ξ² : Type v) :=
(to_fun : Ξ± β Ξ²)
(is_measurable_fiber' : β x, is_measurable (to_fun β»ΒΉ' {x}))
(finite_range' : (set.range to_fun).finite)
local infixr ` ββ `:25 := simple_func
namespace simple_func
section measurable
variables [measurable_space Ξ±]
instance has_coe_to_fun : has_coe_to_fun (Ξ± ββ Ξ²) := β¨_, to_funβ©
lemma coe_injective β¦f g : Ξ± ββ Ξ²β¦ (H : βf = g) : f = g :=
by cases f; cases g; congr; exact H
@[ext] theorem ext {f g : Ξ± ββ Ξ²} (H : β a, f a = g a) : f = g :=
coe_injective $ funext H
lemma finite_range (f : Ξ± ββ Ξ²) : (set.range f).finite := f.finite_range'
lemma is_measurable_fiber (f : Ξ± ββ Ξ²) (x : Ξ²) : is_measurable (f β»ΒΉ' {x}) :=
f.is_measurable_fiber' x
/-- Range of a simple function `Ξ± ββ Ξ²` as a `finset Ξ²`. -/
protected def range (f : Ξ± ββ Ξ²) : finset Ξ² := f.finite_range.to_finset
@[simp] theorem mem_range {f : Ξ± ββ Ξ²} {b} : b β f.range β b β range f :=
finite.mem_to_finset
theorem mem_range_self (f : Ξ± ββ Ξ²) (x : Ξ±) : f x β f.range := mem_range.2 β¨x, rflβ©
@[simp] lemma coe_range (f : Ξ± ββ Ξ²) : (βf.range : set Ξ²) = set.range f :=
f.finite_range.coe_to_finset
theorem mem_range_of_measure_ne_zero {f : Ξ± ββ Ξ²} {x : Ξ²} {ΞΌ : measure Ξ±} (H : ΞΌ (f β»ΒΉ' {x}) β 0) :
x β f.range :=
let β¨a, haβ© := nonempty_of_measure_ne_zero H in
mem_range.2 β¨a, haβ©
lemma forall_range_iff {f : Ξ± ββ Ξ²} {p : Ξ² β Prop} :
(β y β f.range, p y) β β x, p (f x) :=
by simp only [mem_range, set.forall_range_iff]
lemma exists_range_iff {f : Ξ± ββ Ξ²} {p : Ξ² β Prop} :
(β y β f.range, p y) β β x, p (f x) :=
by simpa only [mem_range, exists_prop] using set.exists_range_iff
lemma preimage_eq_empty_iff (f : Ξ± ββ Ξ²) (b : Ξ²) : f β»ΒΉ' {b} = β
β b β f.range :=
preimage_singleton_eq_empty.trans $ not_congr mem_range.symm
/-- Constant function as a `simple_func`. -/
def const (Ξ±) {Ξ²} [measurable_space Ξ±] (b : Ξ²) : Ξ± ββ Ξ² :=
β¨Ξ» a, b, Ξ» x, is_measurable.const _, finite_range_constβ©
instance [inhabited Ξ²] : inhabited (Ξ± ββ Ξ²) := β¨const _ (default _)β©
theorem const_apply (a : Ξ±) (b : Ξ²) : (const Ξ± b) a = b := rfl
@[simp] theorem coe_const (b : Ξ²) : β(const Ξ± b) = function.const Ξ± b := rfl
@[simp] lemma range_const (Ξ±) [measurable_space Ξ±] [nonempty Ξ±] (b : Ξ²) :
(const Ξ± b).range = {b} :=
finset.coe_injective $ by simp
lemma is_measurable_cut (r : Ξ± β Ξ² β Prop) (f : Ξ± ββ Ξ²)
(h : βb, is_measurable {a | r a b}) : is_measurable {a | r a (f a)} :=
begin
have : {a | r a (f a)} = β b β range f, {a | r a b} β© f β»ΒΉ' {b},
{ ext a,
suffices : r a (f a) β β i, r a (f i) β§ f a = f i, by simpa,
exact β¨Ξ» h, β¨a, β¨h, rflβ©β©, Ξ» β¨a', β¨h', eβ©β©, e.symm βΈ h'β© },
rw this,
exact is_measurable.bUnion f.finite_range.countable
(Ξ» b _, is_measurable.inter (h b) (f.is_measurable_fiber _))
end
theorem is_measurable_preimage (f : Ξ± ββ Ξ²) (s) : is_measurable (f β»ΒΉ' s) :=
is_measurable_cut (Ξ» _ b, b β s) f (Ξ» b, is_measurable.const (b β s))
/-- A simple function is measurable -/
protected theorem measurable [measurable_space Ξ²] (f : Ξ± ββ Ξ²) : measurable f :=
Ξ» s _, is_measurable_preimage f s
protected lemma sum_measure_preimage_singleton (f : Ξ± ββ Ξ²) {ΞΌ : measure Ξ±} (s : finset Ξ²) :
β y in s, ΞΌ (f β»ΒΉ' {y}) = ΞΌ (f β»ΒΉ' βs) :=
sum_measure_preimage_singleton _ (Ξ» _ _, f.is_measurable_fiber _)
lemma sum_range_measure_preimage_singleton (f : Ξ± ββ Ξ²) (ΞΌ : measure Ξ±) :
β y in f.range, ΞΌ (f β»ΒΉ' {y}) = ΞΌ univ :=
by rw [f.sum_measure_preimage_singleton, coe_range, preimage_range]
/-- If-then-else as a `simple_func`. -/
def piecewise (s : set Ξ±) (hs : is_measurable s) (f g : Ξ± ββ Ξ²) : Ξ± ββ Ξ² :=
β¨s.piecewise f g,
Ξ» x, by letI : measurable_space Ξ² := β€; exact
f.measurable.piecewise hs g.measurable trivial,
(f.finite_range.union g.finite_range).subset range_ite_subsetβ©
@[simp] theorem coe_piecewise {s : set Ξ±} (hs : is_measurable s) (f g : Ξ± ββ Ξ²) :
β(piecewise s hs f g) = s.piecewise f g :=
rfl
theorem piecewise_apply {s : set Ξ±} (hs : is_measurable s) (f g : Ξ± ββ Ξ²) (a) :
piecewise s hs f g a = if a β s then f a else g a :=
rfl
@[simp] lemma piecewise_compl {s : set Ξ±} (hs : is_measurable sαΆ) (f g : Ξ± ββ Ξ²) :
piecewise sαΆ hs f g = piecewise s hs.of_compl g f :=
coe_injective $ by simp [hs]
@[simp] lemma piecewise_univ (f g : Ξ± ββ Ξ²) : piecewise univ is_measurable.univ f g = f :=
coe_injective $ by simp
@[simp] lemma piecewise_empty (f g : Ξ± ββ Ξ²) : piecewise β
is_measurable.empty f g = g :=
coe_injective $ by simp
lemma measurable_bind [measurable_space Ξ³] (f : Ξ± ββ Ξ²) (g : Ξ² β Ξ± β Ξ³)
(hg : β b, measurable (g b)) : measurable (Ξ» a, g (f a) a) :=
Ξ» s hs, f.is_measurable_cut (Ξ» a b, g b a β s) $ Ξ» b, hg b hs
/-- If `f : Ξ± ββ Ξ²` is a simple function and `g : Ξ² β Ξ± ββ Ξ³` is a family of simple functions,
then `f.bind g` binds the first argument of `g` to `f`. In other words, `f.bind g a = g (f a) a`. -/
def bind (f : Ξ± ββ Ξ²) (g : Ξ² β Ξ± ββ Ξ³) : Ξ± ββ Ξ³ :=
β¨Ξ»a, g (f a) a,
Ξ» c, f.is_measurable_cut (Ξ» a b, g b a = c) $ Ξ» b, (g b).is_measurable_preimage {c},
(f.finite_range.bUnion (Ξ» b _, (g b).finite_range)).subset $
by rintro _ β¨a, rflβ©; simp; exact β¨a, a, rflβ©β©
@[simp] theorem bind_apply (f : Ξ± ββ Ξ²) (g : Ξ² β Ξ± ββ Ξ³) (a) :
f.bind g a = g (f a) a := rfl
/-- Given a function `g : Ξ² β Ξ³` and a simple function `f : Ξ± ββ Ξ²`, `f.map g` return the simple
function `g β f : Ξ± ββ Ξ³` -/
def map (g : Ξ² β Ξ³) (f : Ξ± ββ Ξ²) : Ξ± ββ Ξ³ := bind f (const Ξ± β g)
theorem map_apply (g : Ξ² β Ξ³) (f : Ξ± ββ Ξ²) (a) : f.map g a = g (f a) := rfl
theorem map_map (g : Ξ² β Ξ³) (h: Ξ³ β Ξ΄) (f : Ξ± ββ Ξ²) : (f.map g).map h = f.map (h β g) := rfl
@[simp] theorem coe_map (g : Ξ² β Ξ³) (f : Ξ± ββ Ξ²) : (f.map g : Ξ± β Ξ³) = g β f := rfl
@[simp] theorem range_map [decidable_eq Ξ³] (g : Ξ² β Ξ³) (f : Ξ± ββ Ξ²) :
(f.map g).range = f.range.image g :=
finset.coe_injective $ by simp [range_comp]
@[simp] theorem map_const (g : Ξ² β Ξ³) (b : Ξ²) : (const Ξ± b).map g = const Ξ± (g b) := rfl
lemma map_preimage (f : Ξ± ββ Ξ²) (g : Ξ² β Ξ³) (s : set Ξ³) :
(f.map g) β»ΒΉ' s = f β»ΒΉ' β(f.range.filter (Ξ»b, g b β s)) :=
by { simp only [coe_range, sep_mem_eq, set.mem_range, function.comp_app, coe_map, finset.coe_filter,
β mem_preimage, inter_comm, preimage_inter_range], apply preimage_comp }
lemma map_preimage_singleton (f : Ξ± ββ Ξ²) (g : Ξ² β Ξ³) (c : Ξ³) :
(f.map g) β»ΒΉ' {c} = f β»ΒΉ' β(f.range.filter (Ξ» b, g b = c)) :=
map_preimage _ _ _
/-- Composition of a `simple_fun` and a measurable function is a `simple_func`. -/
def comp [measurable_space Ξ²] (f : Ξ² ββ Ξ³) (g : Ξ± β Ξ²) (hgm : measurable g) : Ξ± ββ Ξ³ :=
{ to_fun := f β g,
finite_range' := f.finite_range.subset $ set.range_comp_subset_range _ _,
is_measurable_fiber' := Ξ» z, hgm (f.is_measurable_fiber z) }
@[simp] lemma coe_comp [measurable_space Ξ²] (f : Ξ² ββ Ξ³) {g : Ξ± β Ξ²} (hgm : measurable g) :
β(f.comp g hgm) = f β g :=
rfl
lemma range_comp_subset_range [measurable_space Ξ²] (f : Ξ² ββ Ξ³) {g : Ξ± β Ξ²} (hgm : measurable g) :
(f.comp g hgm).range β f.range :=
finset.coe_subset.1 $ by simp only [coe_range, coe_comp, set.range_comp_subset_range]
/-- If `f` is a simple function taking values in `Ξ² β Ξ³` and `g` is another simple function
with the same domain and codomain `Ξ²`, then `f.seq g = f a (g a)`. -/
def seq (f : Ξ± ββ (Ξ² β Ξ³)) (g : Ξ± ββ Ξ²) : Ξ± ββ Ξ³ := f.bind (Ξ»f, g.map f)
@[simp] lemma seq_apply (f : Ξ± ββ (Ξ² β Ξ³)) (g : Ξ± ββ Ξ²) (a : Ξ±) : f.seq g a = f a (g a) := rfl
/-- Combine two simple functions `f : Ξ± ββ Ξ²` and `g : Ξ± ββ Ξ²`
into `Ξ» a, (f a, g a)`. -/
def pair (f : Ξ± ββ Ξ²) (g : Ξ± ββ Ξ³) : Ξ± ββ (Ξ² Γ Ξ³) := (f.map prod.mk).seq g
@[simp] lemma pair_apply (f : Ξ± ββ Ξ²) (g : Ξ± ββ Ξ³) (a) : pair f g a = (f a, g a) := rfl
lemma pair_preimage (f : Ξ± ββ Ξ²) (g : Ξ± ββ Ξ³) (s : set Ξ²) (t : set Ξ³) :
(pair f g) β»ΒΉ' (set.prod s t) = (f β»ΒΉ' s) β© (g β»ΒΉ' t) := rfl
/- A special form of `pair_preimage` -/
lemma pair_preimage_singleton (f : Ξ± ββ Ξ²) (g : Ξ± ββ Ξ³) (b : Ξ²) (c : Ξ³) :
(pair f g) β»ΒΉ' {(b, c)} = (f β»ΒΉ' {b}) β© (g β»ΒΉ' {c}) :=
by { rw β singleton_prod_singleton, exact pair_preimage _ _ _ _ }
theorem bind_const (f : Ξ± ββ Ξ²) : f.bind (const Ξ±) = f := by ext; simp
instance [has_zero Ξ²] : has_zero (Ξ± ββ Ξ²) := β¨const Ξ± 0β©
instance [has_add Ξ²] : has_add (Ξ± ββ Ξ²) := β¨Ξ»f g, (f.map (+)).seq gβ©
instance [has_mul Ξ²] : has_mul (Ξ± ββ Ξ²) := β¨Ξ»f g, (f.map (*)).seq gβ©
instance [has_sup Ξ²] : has_sup (Ξ± ββ Ξ²) := β¨Ξ»f g, (f.map (β)).seq gβ©
instance [has_inf Ξ²] : has_inf (Ξ± ββ Ξ²) := β¨Ξ»f g, (f.map (β)).seq gβ©
instance [has_le Ξ²] : has_le (Ξ± ββ Ξ²) := β¨Ξ»f g, βa, f a β€ g aβ©
@[simp, norm_cast] lemma coe_zero [has_zero Ξ²] : β(0 : Ξ± ββ Ξ²) = 0 := rfl
@[simp] lemma const_zero [has_zero Ξ²] : const Ξ± (0:Ξ²) = 0 := rfl
@[simp, norm_cast] lemma coe_add [has_add Ξ²] (f g : Ξ± ββ Ξ²) : β(f + g) = f + g := rfl
@[simp, norm_cast] lemma coe_mul [has_mul Ξ²] (f g : Ξ± ββ Ξ²) : β(f * g) = f * g := rfl
@[simp, norm_cast] lemma coe_le [preorder Ξ²] {f g : Ξ± ββ Ξ²} : (f : Ξ± β Ξ²) β€ g β f β€ g := iff.rfl
@[simp] lemma range_zero [nonempty Ξ±] [has_zero Ξ²] : (0 : Ξ± ββ Ξ²).range = {0} :=
finset.ext $ Ξ» x, by simp [eq_comm]
lemma eq_zero_of_mem_range_zero [has_zero Ξ²] : β {y : Ξ²}, y β (0 : Ξ± ββ Ξ²).range β y = 0 :=
forall_range_iff.2 $ Ξ» x, rfl
lemma sup_apply [has_sup Ξ²] (f g : Ξ± ββ Ξ²) (a : Ξ±) : (f β g) a = f a β g a := rfl
lemma mul_apply [has_mul Ξ²] (f g : Ξ± ββ Ξ²) (a : Ξ±) : (f * g) a = f a * g a := rfl
lemma add_apply [has_add Ξ²] (f g : Ξ± ββ Ξ²) (a : Ξ±) : (f + g) a = f a + g a := rfl
lemma add_eq_mapβ [has_add Ξ²] (f g : Ξ± ββ Ξ²) : f + g = (pair f g).map (Ξ»p:Ξ²ΓΞ², p.1 + p.2) :=
rfl
lemma mul_eq_mapβ [has_mul Ξ²] (f g : Ξ± ββ Ξ²) : f * g = (pair f g).map (Ξ»p:Ξ²ΓΞ², p.1 * p.2) :=
rfl
lemma sup_eq_mapβ [has_sup Ξ²] (f g : Ξ± ββ Ξ²) : f β g = (pair f g).map (Ξ»p:Ξ²ΓΞ², p.1 β p.2) :=
rfl
lemma const_mul_eq_map [has_mul Ξ²] (f : Ξ± ββ Ξ²) (b : Ξ²) : const Ξ± b * f = f.map (Ξ»a, b * a) := rfl
instance [add_monoid Ξ²] : add_monoid (Ξ± ββ Ξ²) :=
function.injective.add_monoid (Ξ» f, show Ξ± β Ξ², from f) coe_injective coe_zero coe_add
instance add_comm_monoid [add_comm_monoid Ξ²] : add_comm_monoid (Ξ± ββ Ξ²) :=
function.injective.add_comm_monoid (Ξ» f, show Ξ± β Ξ², from f) coe_injective coe_zero coe_add
instance [has_neg Ξ²] : has_neg (Ξ± ββ Ξ²) := β¨Ξ»f, f.map (has_neg.neg)β©
@[simp, norm_cast] lemma coe_neg [has_neg Ξ²] (f : Ξ± ββ Ξ²) : β(-f) = -f := rfl
instance [add_group Ξ²] : add_group (Ξ± ββ Ξ²) :=
function.injective.add_group (Ξ» f, show Ξ± β Ξ², from f) coe_injective coe_zero coe_add coe_neg
@[simp, norm_cast] lemma coe_sub [add_group Ξ²] (f g : Ξ± ββ Ξ²) : β(f - g) = f - g := rfl
instance [add_comm_group Ξ²] : add_comm_group (Ξ± ββ Ξ²) :=
function.injective.add_comm_group (Ξ» f, show Ξ± β Ξ², from f) coe_injective
coe_zero coe_add coe_neg
variables {K : Type*}
instance [has_scalar K Ξ²] : has_scalar K (Ξ± ββ Ξ²) := β¨Ξ»k f, f.map ((β’) k)β©
@[simp] lemma coe_smul [has_scalar K Ξ²] (c : K) (f : Ξ± ββ Ξ²) : β(c β’ f) = c β’ f := rfl
lemma smul_apply [has_scalar K Ξ²] (k : K) (f : Ξ± ββ Ξ²) (a : Ξ±) : (k β’ f) a = k β’ f a := rfl
instance [semiring K] [add_comm_monoid Ξ²] [semimodule K Ξ²] : semimodule K (Ξ± ββ Ξ²) :=
function.injective.semimodule K β¨Ξ» f, show Ξ± β Ξ², from f, coe_zero, coe_addβ©
coe_injective coe_smul
lemma smul_eq_map [has_scalar K Ξ²] (k : K) (f : Ξ± ββ Ξ²) : k β’ f = f.map ((β’) k) := rfl
instance [preorder Ξ²] : preorder (Ξ± ββ Ξ²) :=
{ le_refl := Ξ»f a, le_refl _,
le_trans := Ξ»f g h hfg hgh a, le_trans (hfg _) (hgh a),
.. simple_func.has_le }
instance [partial_order Ξ²] : partial_order (Ξ± ββ Ξ²) :=
{ le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a),
.. simple_func.preorder }
instance [order_bot Ξ²] : order_bot (Ξ± ββ Ξ²) :=
{ bot := const Ξ± β₯, bot_le := Ξ»f a, bot_le, .. simple_func.partial_order }
instance [order_top Ξ²] : order_top (Ξ± ββ Ξ²) :=
{ top := const Ξ± β€, le_top := Ξ»f a, le_top, .. simple_func.partial_order }
instance [semilattice_inf Ξ²] : semilattice_inf (Ξ± ββ Ξ²) :=
{ inf := (β),
inf_le_left := assume f g a, inf_le_left,
inf_le_right := assume f g a, inf_le_right,
le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a),
.. simple_func.partial_order }
instance [semilattice_sup Ξ²] : semilattice_sup (Ξ± ββ Ξ²) :=
{ sup := (β),
le_sup_left := assume f g a, le_sup_left,
le_sup_right := assume f g a, le_sup_right,
sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a),
.. simple_func.partial_order }
instance [semilattice_sup_bot Ξ²] : semilattice_sup_bot (Ξ± ββ Ξ²) :=
{ .. simple_func.semilattice_sup,.. simple_func.order_bot }
instance [lattice Ξ²] : lattice (Ξ± ββ Ξ²) :=
{ .. simple_func.semilattice_sup,.. simple_func.semilattice_inf }
instance [bounded_lattice Ξ²] : bounded_lattice (Ξ± ββ Ξ²) :=
{ .. simple_func.lattice, .. simple_func.order_bot, .. simple_func.order_top }
lemma finset_sup_apply [semilattice_sup_bot Ξ²] {f : Ξ³ β Ξ± ββ Ξ²} (s : finset Ξ³) (a : Ξ±) :
s.sup f a = s.sup (Ξ»c, f c a) :=
begin
refine finset.induction_on s rfl _,
assume a s hs ih,
rw [finset.sup_insert, finset.sup_insert, sup_apply, ih]
end
section restrict
variables [has_zero Ξ²]
/-- Restrict a simple function `f : Ξ± ββ Ξ²` to a set `s`. If `s` is measurable,
then `f.restrict s a = if a β s then f a else 0`, otherwise `f.restrict s = const Ξ± 0`. -/
def restrict (f : Ξ± ββ Ξ²) (s : set Ξ±) : Ξ± ββ Ξ² :=
if hs : is_measurable s then piecewise s hs f 0 else 0
theorem restrict_of_not_measurable {f : Ξ± ββ Ξ²} {s : set Ξ±}
(hs : Β¬is_measurable s) :
restrict f s = 0 :=
dif_neg hs
@[simp] theorem coe_restrict (f : Ξ± ββ Ξ²) {s : set Ξ±} (hs : is_measurable s) :
β(restrict f s) = indicator s f :=
by { rw [restrict, dif_pos hs], refl }
@[simp] theorem restrict_univ (f : Ξ± ββ Ξ²) : restrict f univ = f :=
by simp [restrict]
@[simp] theorem restrict_empty (f : Ξ± ββ Ξ²) : restrict f β
= 0 :=
by simp [restrict]
theorem map_restrict_of_zero [has_zero Ξ³] {g : Ξ² β Ξ³} (hg : g 0 = 0) (f : Ξ± ββ Ξ²) (s : set Ξ±) :
(f.restrict s).map g = (f.map g).restrict s :=
ext $ Ξ» x,
if hs : is_measurable s then by simp [hs, set.indicator_comp_of_zero hg]
else by simp [restrict_of_not_measurable hs, hg]
theorem map_coe_ennreal_restrict (f : Ξ± ββ nnreal) (s : set Ξ±) :
(f.restrict s).map (coe : nnreal β ennreal) = (f.map coe).restrict s :=
map_restrict_of_zero ennreal.coe_zero _ _
theorem map_coe_nnreal_restrict (f : Ξ± ββ nnreal) (s : set Ξ±) :
(f.restrict s).map (coe : nnreal β β) = (f.map coe).restrict s :=
map_restrict_of_zero nnreal.coe_zero _ _
theorem restrict_apply (f : Ξ± ββ Ξ²) {s : set Ξ±} (hs : is_measurable s) (a) :
restrict f s a = if a β s then f a else 0 :=
by simp only [hs, coe_restrict]
theorem restrict_preimage (f : Ξ± ββ Ξ²) {s : set Ξ±} (hs : is_measurable s)
{t : set Ξ²} (ht : (0:Ξ²) β t) : restrict f s β»ΒΉ' t = s β© f β»ΒΉ' t :=
by simp [hs, indicator_preimage_of_not_mem _ _ ht]
theorem restrict_preimage_singleton (f : Ξ± ββ Ξ²) {s : set Ξ±} (hs : is_measurable s)
{r : Ξ²} (hr : r β 0) : restrict f s β»ΒΉ' {r} = s β© f β»ΒΉ' {r} :=
f.restrict_preimage hs hr.symm
lemma mem_restrict_range {r : Ξ²} {s : set Ξ±} {f : Ξ± ββ Ξ²} (hs : is_measurable s) :
r β (restrict f s).range β (r = 0 β§ s β univ) β¨ (r β f '' s) :=
by rw [β finset.mem_coe, coe_range, coe_restrict _ hs, mem_range_indicator]
lemma mem_image_of_mem_range_restrict {r : Ξ²} {s : set Ξ±} {f : Ξ± ββ Ξ²}
(hr : r β (restrict f s).range) (h0 : r β 0) :
r β f '' s :=
if hs : is_measurable s then by simpa [mem_restrict_range hs, h0] using hr
else by { rw [restrict_of_not_measurable hs] at hr,
exact (h0 $ eq_zero_of_mem_range_zero hr).elim }
@[mono] lemma restrict_mono [preorder Ξ²] (s : set Ξ±) {f g : Ξ± ββ Ξ²} (H : f β€ g) :
f.restrict s β€ g.restrict s :=
if hs : is_measurable s then Ξ» x, by simp only [coe_restrict _ hs, indicator_le_indicator (H x)]
else by simp only [restrict_of_not_measurable hs, le_refl]
end restrict
section approx
section
variables [semilattice_sup_bot Ξ²] [has_zero Ξ²]
/-- Fix a sequence `i : β β Ξ²`. Given a function `Ξ± β Ξ²`, its `n`-th approximation
by simple functions is defined so that in case `Ξ² = ennreal` it sends each `a` to the supremum
of the set `{i k | k β€ n β§ i k β€ f a}`, see `approx_apply` and `supr_approx_apply` for details. -/
def approx (i : β β Ξ²) (f : Ξ± β Ξ²) (n : β) : Ξ± ββ Ξ² :=
(finset.range n).sup (Ξ»k, restrict (const Ξ± (i k)) {a:Ξ± | i k β€ f a})
lemma approx_apply [topological_space Ξ²] [order_closed_topology Ξ²] [measurable_space Ξ²]
[opens_measurable_space Ξ²] {i : β β Ξ²} {f : Ξ± β Ξ²} {n : β} (a : Ξ±) (hf : measurable f) :
(approx i f n : Ξ± ββ Ξ²) a = (finset.range n).sup (Ξ»k, if i k β€ f a then i k else 0) :=
begin
dsimp only [approx],
rw [finset_sup_apply],
congr,
funext k,
rw [restrict_apply],
refl,
exact (hf is_measurable_Ici)
end
lemma monotone_approx (i : β β Ξ²) (f : Ξ± β Ξ²) : monotone (approx i f) :=
assume n m h, finset.sup_mono $ finset.range_subset.2 h
lemma approx_comp [topological_space Ξ²] [order_closed_topology Ξ²] [measurable_space Ξ²]
[opens_measurable_space Ξ²] [measurable_space Ξ³]
{i : β β Ξ²} {f : Ξ³ β Ξ²} {g : Ξ± β Ξ³} {n : β} (a : Ξ±)
(hf : measurable f) (hg : measurable g) :
(approx i (f β g) n : Ξ± ββ Ξ²) a = (approx i f n : Ξ³ ββ Ξ²) (g a) :=
by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)]
end
lemma supr_approx_apply [topological_space Ξ²] [complete_lattice Ξ²] [order_closed_topology Ξ²] [has_zero Ξ²]
[measurable_space Ξ²] [opens_measurable_space Ξ²]
(i : β β Ξ²) (f : Ξ± β Ξ²) (a : Ξ±) (hf : measurable f) (h_zero : (0 : Ξ²) = β₯) :
(β¨n, (approx i f n : Ξ± ββ Ξ²) a) = (β¨k (h : i k β€ f a), i k) :=
begin
refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _),
{ rw [approx_apply a hf, h_zero],
refine finset.sup_le (assume k hk, _),
split_ifs,
exact le_supr_of_le k (le_supr _ h),
exact bot_le },
{ refine le_supr_of_le (k+1) _,
rw [approx_apply a hf],
have : k β finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _),
refine le_trans (le_of_eq _) (finset.le_sup this),
rw [if_pos hk] }
end
end approx
section eapprox
/-- A sequence of `ennreal`s such that its range is the set of non-negative rational numbers. -/
def ennreal_rat_embed (n : β) : ennreal :=
ennreal.of_real ((encodable.decode β n).get_or_else (0 : β))
lemma ennreal_rat_embed_encode (q : β) :
ennreal_rat_embed (encodable.encode q) = nnreal.of_real q :=
by rw [ennreal_rat_embed, encodable.encodek]; refl
/-- Approximate a function `Ξ± β ennreal` by a sequence of simple functions. -/
def eapprox : (Ξ± β ennreal) β β β Ξ± ββ ennreal :=
approx ennreal_rat_embed
lemma monotone_eapprox (f : Ξ± β ennreal) : monotone (eapprox f) :=
monotone_approx _ f
lemma supr_eapprox_apply (f : Ξ± β ennreal) (hf : measurable f) (a : Ξ±) :
(β¨n, (eapprox f n : Ξ± ββ ennreal) a) = f a :=
begin
rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl],
refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _),
assume h,
rcases ennreal.lt_iff_exists_rat_btwn.1 h with β¨q, hq, lt_q, q_ltβ©,
have : (nnreal.of_real q : ennreal) β€
(β¨ (k : β) (h : ennreal_rat_embed k β€ f a), ennreal_rat_embed k),
{ refine le_supr_of_le (encodable.encode q) _,
rw [ennreal_rat_embed_encode q],
refine le_supr_of_le (le_of_lt q_lt) _,
exact le_refl _ },
exact lt_irrefl _ (lt_of_le_of_lt this lt_q)
end
lemma eapprox_comp [measurable_space Ξ³] {f : Ξ³ β ennreal} {g : Ξ± β Ξ³} {n : β}
(hf : measurable f) (hg : measurable g) :
(eapprox (f β g) n : Ξ± β ennreal) = (eapprox f n : Ξ³ ββ ennreal) β g :=
funext $ assume a, approx_comp a hf hg
end eapprox
end measurable
section measure
variables [measurable_space Ξ±] {ΞΌ : measure Ξ±}
/-- Integral of a simple function whose codomain is `ennreal`. -/
def lintegral (f : Ξ± ββ ennreal) (ΞΌ : measure Ξ±) : ennreal :=
β x in f.range, x * ΞΌ (f β»ΒΉ' {x})
lemma lintegral_eq_of_subset (f : Ξ± ββ ennreal) {s : finset ennreal}
(hs : β x, f x β 0 β ΞΌ (f β»ΒΉ' {f x}) β 0 β f x β s) :
f.lintegral ΞΌ = β x in s, x * ΞΌ (f β»ΒΉ' {x}) :=
begin
refine finset.sum_bij_ne_zero (Ξ»r _ _, r) _ _ _ _,
{ simpa only [forall_range_iff, mul_ne_zero_iff, and_imp] },
{ intros, assumption },
{ intros b _ hb,
refine β¨b, _, hb, rflβ©,
rw [mem_range, β preimage_singleton_nonempty],
exact nonempty_of_measure_ne_zero (mul_ne_zero_iff.1 hb).2 },
{ intros, refl }
end
/-- Calculate the integral of `(g β f)`, where `g : Ξ² β ennreal` and `f : Ξ± ββ Ξ²`. -/
lemma map_lintegral (g : Ξ² β ennreal) (f : Ξ± ββ Ξ²) :
(f.map g).lintegral ΞΌ = β x in f.range, g x * ΞΌ (f β»ΒΉ' {x}) :=
begin
simp only [lintegral, range_map],
refine finset.sum_image' _ (assume b hb, _),
rcases mem_range.1 hb with β¨a, rflβ©,
rw [map_preimage_singleton, β f.sum_measure_preimage_singleton, finset.mul_sum],
refine finset.sum_congr _ _,
{ congr },
{ assume x, simp only [finset.mem_filter], rintro β¨_, hβ©, rw h },
end
lemma add_lintegral (f g : Ξ± ββ ennreal) : (f + g).lintegral ΞΌ = f.lintegral ΞΌ + g.lintegral ΞΌ :=
calc (f + g).lintegral ΞΌ =
β x in (pair f g).range, (x.1 * ΞΌ (pair f g β»ΒΉ' {x}) + x.2 * ΞΌ (pair f g β»ΒΉ' {x})) :
by rw [add_eq_mapβ, map_lintegral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _)
... = β x in (pair f g).range, x.1 * ΞΌ (pair f g β»ΒΉ' {x}) +
β x in (pair f g).range, x.2 * ΞΌ (pair f g β»ΒΉ' {x}) : by rw [finset.sum_add_distrib]
... = ((pair f g).map prod.fst).lintegral ΞΌ + ((pair f g).map prod.snd).lintegral ΞΌ :
by rw [map_lintegral, map_lintegral]
... = lintegral f ΞΌ + lintegral g ΞΌ : rfl
lemma const_mul_lintegral (f : Ξ± ββ ennreal) (x : ennreal) :
(const Ξ± x * f).lintegral ΞΌ = x * f.lintegral ΞΌ :=
calc (f.map (Ξ»a, x * a)).lintegral ΞΌ = β r in f.range, x * r * ΞΌ (f β»ΒΉ' {r}) :
map_lintegral _ _
... = β r in f.range, x * (r * ΞΌ (f β»ΒΉ' {r})) :
finset.sum_congr rfl (assume a ha, mul_assoc _ _ _)
... = x * f.lintegral ΞΌ :
finset.mul_sum.symm
/-- Integral of a simple function `Ξ± ββ ennreal` as a bilinear map. -/
def lintegralβ : (Ξ± ββ ennreal) ββ[ennreal] measure Ξ± ββ[ennreal] ennreal :=
{ to_fun := Ξ» f,
{ to_fun := lintegral f,
map_add' := by simp [lintegral, mul_add, finset.sum_add_distrib],
map_smul' := Ξ» c ΞΌ, by simp [lintegral, mul_left_comm _ c, finset.mul_sum] },
map_add' := Ξ» f g, linear_map.ext (Ξ» ΞΌ, add_lintegral f g),
map_smul' := Ξ» c f, linear_map.ext (Ξ» ΞΌ, const_mul_lintegral f c) }
@[simp] lemma zero_lintegral : (0 : Ξ± ββ ennreal).lintegral ΞΌ = 0 :=
linear_map.ext_iff.1 lintegralβ.map_zero ΞΌ
lemma lintegral_add {Ξ½} (f : Ξ± ββ ennreal) : f.lintegral (ΞΌ + Ξ½) = f.lintegral ΞΌ + f.lintegral Ξ½ :=
(lintegralβ f).map_add ΞΌ Ξ½
lemma lintegral_smul (f : Ξ± ββ ennreal) (c : ennreal) :
f.lintegral (c β’ ΞΌ) = c β’ f.lintegral ΞΌ :=
(lintegralβ f).map_smul c ΞΌ
@[simp] lemma lintegral_zero (f : Ξ± ββ ennreal) :
f.lintegral 0 = 0 :=
(lintegralβ f).map_zero
lemma lintegral_sum {ΞΉ} (f : Ξ± ββ ennreal) (ΞΌ : ΞΉ β measure Ξ±) :
f.lintegral (measure.sum ΞΌ) = β' i, f.lintegral (ΞΌ i) :=
begin
simp only [lintegral, measure.sum_apply, f.is_measurable_preimage, β finset.tsum_subtype,
β ennreal.tsum_mul_left],
apply ennreal.tsum_comm
end
lemma restrict_lintegral (f : Ξ± ββ ennreal) {s : set Ξ±} (hs : is_measurable s) :
(restrict f s).lintegral ΞΌ = β r in f.range, r * ΞΌ (f β»ΒΉ' {r} β© s) :=
calc (restrict f s).lintegral ΞΌ = β r in f.range, r * ΞΌ (restrict f s β»ΒΉ' {r}) :
lintegral_eq_of_subset _ $ Ξ» x hx, if hxs : x β s
then by simp [f.restrict_apply hs, if_pos hxs, mem_range_self]
else false.elim $ hx $ by simp [*]
... = β r in f.range, r * ΞΌ (f β»ΒΉ' {r} β© s) :
finset.sum_congr rfl $ forall_range_iff.2 $ Ξ» b, if hb : f b = 0 then by simp only [hb, zero_mul]
else by rw [restrict_preimage_singleton _ hs hb, inter_comm]
lemma lintegral_restrict (f : Ξ± ββ ennreal) (s : set Ξ±) (ΞΌ : measure Ξ±) :
f.lintegral (ΞΌ.restrict s) = β y in f.range, y * ΞΌ (f β»ΒΉ' {y} β© s) :=
by simp only [lintegral, measure.restrict_apply, f.is_measurable_preimage]
lemma restrict_lintegral_eq_lintegral_restrict (f : Ξ± ββ ennreal) {s : set Ξ±}
(hs : is_measurable s) :
(restrict f s).lintegral ΞΌ = f.lintegral (ΞΌ.restrict s) :=
by rw [f.restrict_lintegral hs, lintegral_restrict]
lemma const_lintegral (c : ennreal) : (const Ξ± c).lintegral ΞΌ = c * ΞΌ univ :=
begin
rw [lintegral],
by_cases ha : nonempty Ξ±,
{ resetI, simp [preimage_const_of_mem] },
{ simp [ΞΌ.eq_zero_of_not_nonempty ha] }
end
lemma const_lintegral_restrict (c : ennreal) (s : set Ξ±) :
(const Ξ± c).lintegral (ΞΌ.restrict s) = c * ΞΌ s :=
by rw [const_lintegral, measure.restrict_apply is_measurable.univ, univ_inter]
lemma restrict_const_lintegral (c : ennreal) {s : set Ξ±} (hs : is_measurable s) :
((const Ξ± c).restrict s).lintegral ΞΌ = c * ΞΌ s :=
by rw [restrict_lintegral_eq_lintegral_restrict _ hs, const_lintegral_restrict]
lemma le_sup_lintegral (f g : Ξ± ββ ennreal) : f.lintegral ΞΌ β g.lintegral ΞΌ β€ (f β g).lintegral ΞΌ :=
calc f.lintegral ΞΌ β g.lintegral ΞΌ =
((pair f g).map prod.fst).lintegral ΞΌ β ((pair f g).map prod.snd).lintegral ΞΌ : rfl
... β€ β x in (pair f g).range, (x.1 β x.2) * ΞΌ (pair f g β»ΒΉ' {x}) :
begin
rw [map_lintegral, map_lintegral],
refine sup_le _ _;
refine finset.sum_le_sum (Ξ» a _, canonically_ordered_semiring.mul_le_mul _ (le_refl _)),
exact le_sup_left,
exact le_sup_right
end
... = (f β g).lintegral ΞΌ : by rw [sup_eq_mapβ, map_lintegral]
/-- `simple_func.lintegral` is monotone both in function and in measure. -/
@[mono] lemma lintegral_mono {f g : Ξ± ββ ennreal} (hfg : f β€ g) {ΞΌ Ξ½ : measure Ξ±} (hΞΌΞ½ : ΞΌ β€ Ξ½) :
f.lintegral ΞΌ β€ g.lintegral Ξ½ :=
calc f.lintegral ΞΌ β€ f.lintegral ΞΌ β g.lintegral ΞΌ : le_sup_left
... β€ (f β g).lintegral ΞΌ : le_sup_lintegral _ _
... = g.lintegral ΞΌ : by rw [sup_of_le_right hfg]
... β€ g.lintegral Ξ½ : finset.sum_le_sum $ Ξ» y hy, ennreal.mul_left_mono $
hΞΌΞ½ _ (g.is_measurable_preimage _)
/-- `simple_func.lintegral` depends only on the measures of `f β»ΒΉ' {y}`. -/
lemma lintegral_eq_of_measure_preimage [measurable_space Ξ²] {f : Ξ± ββ ennreal} {g : Ξ² ββ ennreal}
{Ξ½ : measure Ξ²} (H : β y, ΞΌ (f β»ΒΉ' {y}) = Ξ½ (g β»ΒΉ' {y})) :
f.lintegral ΞΌ = g.lintegral Ξ½ :=
begin
simp only [lintegral, β H],
apply lintegral_eq_of_subset,
simp only [H],
intros,
exact mem_range_of_measure_ne_zero βΉ_βΊ
end
/-- If two simple functions are equal a.e., then their `lintegral`s are equal. -/
lemma lintegral_congr {f g : Ξ± ββ ennreal} (h : f =α΅[ΞΌ] g) :
f.lintegral ΞΌ = g.lintegral ΞΌ :=
lintegral_eq_of_measure_preimage $ Ξ» y, measure_congr $
eventually.set_eq $ h.mono $ Ξ» x hx, by simp [hx]
lemma lintegral_map {Ξ²} [measurable_space Ξ²] {ΞΌ' : measure Ξ²} (f : Ξ± ββ ennreal) (g : Ξ² ββ ennreal)
(m : Ξ± β Ξ²) (eq : βa:Ξ±, f a = g (m a)) (h : βs:set Ξ², is_measurable s β ΞΌ' s = ΞΌ (m β»ΒΉ' s)) :
f.lintegral ΞΌ = g.lintegral ΞΌ' :=
lintegral_eq_of_measure_preimage $ Ξ» y,
by { simp only [preimage, eq], exact (h (g β»ΒΉ' {y}) (g.is_measurable_preimage _)).symm }
end measure
section fin_meas_supp
variables [measurable_space Ξ±] [has_zero Ξ²] [has_zero Ξ³] {ΞΌ : measure Ξ±}
open finset ennreal function
lemma support_eq (f : Ξ± ββ Ξ²) : support f = β y β f.range.filter (Ξ» y, y β 0), f β»ΒΉ' {y} :=
set.ext $ Ξ» x, by simp only [finset.bUnion_preimage_singleton, mem_support, set.mem_preimage,
finset.mem_coe, mem_filter, mem_range_self, true_and]
/-- A `simple_func` has finite measure support if it is equal to `0` outside of a set of finite
measure. -/
protected def fin_meas_supp (f : Ξ± ββ Ξ²) (ΞΌ : measure Ξ±) : Prop :=
f =αΆ [ΞΌ.cofinite] 0
lemma fin_meas_supp_iff_support {f : Ξ± ββ Ξ²} {ΞΌ : measure Ξ±} :
f.fin_meas_supp ΞΌ β ΞΌ (support f) < β€ :=
iff.rfl
lemma fin_meas_supp_iff {f : Ξ± ββ Ξ²} {ΞΌ : measure Ξ±} :
f.fin_meas_supp ΞΌ β β y β 0, ΞΌ (f β»ΒΉ' {y}) < β€ :=
begin
split,
{ refine Ξ» h y hy, lt_of_le_of_lt (measure_mono _) h,
exact Ξ» x hx (H : f x = 0), hy $ H βΈ eq.symm hx },
{ intro H,
rw [fin_meas_supp_iff_support, support_eq],
refine lt_of_le_of_lt (measure_bUnion_finset_le _ _) (sum_lt_top _),
exact Ξ» y hy, H y (finset.mem_filter.1 hy).2 }
end
namespace fin_meas_supp
lemma meas_preimage_singleton_ne_zero {f : Ξ± ββ Ξ²} (h : f.fin_meas_supp ΞΌ) {y : Ξ²} (hy : y β 0) :
ΞΌ (f β»ΒΉ' {y}) < β€ :=
fin_meas_supp_iff.1 h y hy
protected lemma map {f : Ξ± ββ Ξ²} {g : Ξ² β Ξ³} (hf : f.fin_meas_supp ΞΌ) (hg : g 0 = 0) :
(f.map g).fin_meas_supp ΞΌ :=
flip lt_of_le_of_lt hf (measure_mono $ support_comp_subset hg f)
lemma of_map {f : Ξ± ββ Ξ²} {g : Ξ² β Ξ³} (h : (f.map g).fin_meas_supp ΞΌ) (hg : βb, g b = 0 β b = 0) :
f.fin_meas_supp ΞΌ :=
flip lt_of_le_of_lt h $ measure_mono $ support_subset_comp hg _
lemma map_iff {f : Ξ± ββ Ξ²} {g : Ξ² β Ξ³} (hg : β {b}, g b = 0 β b = 0) :
(f.map g).fin_meas_supp ΞΌ β f.fin_meas_supp ΞΌ :=
β¨Ξ» h, h.of_map $ Ξ» b, hg.1, Ξ» h, h.map $ hg.2 rflβ©
protected lemma pair {f : Ξ± ββ Ξ²} {g : Ξ± ββ Ξ³} (hf : f.fin_meas_supp ΞΌ) (hg : g.fin_meas_supp ΞΌ) :
(pair f g).fin_meas_supp ΞΌ :=
calc ΞΌ (support $ pair f g) = ΞΌ (support f βͺ support g) : congr_arg ΞΌ $ support_prod_mk f g
... β€ ΞΌ (support f) + ΞΌ (support g) : measure_union_le _ _
... < _ : add_lt_top.2 β¨hf, hgβ©
protected lemma mapβ [has_zero Ξ΄] {ΞΌ : measure Ξ±} {f : Ξ± ββ Ξ²} (hf : f.fin_meas_supp ΞΌ)
{g : Ξ± ββ Ξ³} (hg : g.fin_meas_supp ΞΌ) {op : Ξ² β Ξ³ β Ξ΄} (H : op 0 0 = 0) :
((pair f g).map (function.uncurry op)).fin_meas_supp ΞΌ :=
(hf.pair hg).map H
protected lemma add {Ξ²} [add_monoid Ξ²] {f g : Ξ± ββ Ξ²} (hf : f.fin_meas_supp ΞΌ)
(hg : g.fin_meas_supp ΞΌ) :
(f + g).fin_meas_supp ΞΌ :=
by { rw [add_eq_mapβ], exact hf.mapβ hg (zero_add 0) }
protected lemma mul {Ξ²} [monoid_with_zero Ξ²] {f g : Ξ± ββ Ξ²} (hf : f.fin_meas_supp ΞΌ)
(hg : g.fin_meas_supp ΞΌ) :
(f * g).fin_meas_supp ΞΌ :=
by { rw [mul_eq_mapβ], exact hf.mapβ hg (zero_mul 0) }
lemma lintegral_lt_top {f : Ξ± ββ ennreal} (hm : f.fin_meas_supp ΞΌ) (hf : βα΅ a βΞΌ, f a < β€) :
f.lintegral ΞΌ < β€ :=
begin
refine sum_lt_top (Ξ» a ha, _),
rcases eq_or_lt_of_le (le_top : a β€ β€) with rfl|ha,
{ simp only [ae_iff, lt_top_iff_ne_top, ne.def, not_not] at hf,
simp [set.preimage, hf] },
{ by_cases ha0 : a = 0,
{ subst a, rwa [zero_mul] },
{ exact mul_lt_top ha (fin_meas_supp_iff.1 hm _ ha0) } }
end
lemma of_lintegral_lt_top {f : Ξ± ββ ennreal} (h : f.lintegral ΞΌ < β€) : f.fin_meas_supp ΞΌ :=
begin
refine fin_meas_supp_iff.2 (Ξ» b hb, _),
rw [lintegral, sum_lt_top_iff] at h,
by_cases b_mem : b β f.range,
{ rw ennreal.lt_top_iff_ne_top,
have h : Β¬ _ = β€ := ennreal.lt_top_iff_ne_top.1 (h b b_mem),
simp only [mul_eq_top, not_or_distrib, not_and_distrib] at h,
rcases h with β¨h, h'β©,
refine or.elim h (Ξ»h, by contradiction) (Ξ»h, h) },
{ rw β preimage_eq_empty_iff at b_mem,
rw [b_mem, measure_empty],
exact with_top.zero_lt_top }
end
lemma iff_lintegral_lt_top {f : Ξ± ββ ennreal} (hf : βα΅ a βΞΌ, f a < β€) :
f.fin_meas_supp ΞΌ β f.lintegral ΞΌ < β€ :=
β¨Ξ» h, h.lintegral_lt_top hf, Ξ» h, of_lintegral_lt_top hβ©
end fin_meas_supp
end fin_meas_supp
/-- To prove something for an arbitrary simple function, it suffices to show
that the property holds for (multiples of) characteristic functions and is closed under
addition (of functions with disjoint support).
It is possible to make the hypotheses in `h_sum` a bit stronger, and such conditions can be added
once we need them (for example it is only necessary to consider the case where `g` is a multiple
of a characteristic function, and that this multiple doesn't appear in the image of `f`) -/
@[elab_as_eliminator]
protected lemma induction {Ξ± Ξ³} [measurable_space Ξ±] [add_monoid Ξ³] {P : simple_func Ξ± Ξ³ β Prop}
(h_ind : β c {s} (hs : is_measurable s),
P (simple_func.piecewise s hs (simple_func.const _ c) (simple_func.const _ 0)))
(h_sum : β β¦f g : simple_func Ξ± Ξ³β¦, set.univ β f β»ΒΉ' {0} βͺ g β»ΒΉ' {0} β P f β P g β P (f + g))
(f : simple_func Ξ± Ξ³) : P f :=
begin
generalize' h : f.range \ {0} = s,
rw [β finset.coe_inj, finset.coe_sdiff, finset.coe_singleton, simple_func.coe_range] at h,
revert s f h, refine finset.induction _ _,
{ intros f hf, rw [finset.coe_empty, diff_eq_empty, range_subset_singleton] at hf,
convert h_ind 0 is_measurable.univ, ext x, simp [hf] },
{ intros x s hxs ih f hf,
have mx := f.is_measurable_preimage {x},
let g := simple_func.piecewise (f β»ΒΉ' {x}) mx 0 f,
have Pg : P g,
{ apply ih, simp only [g, simple_func.coe_piecewise, range_piecewise],
rw [image_compl_preimage, union_diff_distrib, diff_diff_comm, hf, finset.coe_insert,
insert_diff_self_of_not_mem, diff_eq_empty.mpr, set.empty_union],
{ rw [set.image_subset_iff], convert set.subset_univ _,
exact preimage_const_of_mem (mem_singleton _) },
{ rwa [finset.mem_coe] }},
convert h_sum _ Pg (h_ind x mx),
{ ext1 y, by_cases hy : y β f β»ΒΉ' {x}; [simpa [hy], simp [hy]] },
{ rintro y -, by_cases hy : y β f β»ΒΉ' {x}; simp [hy] } }
end
end simple_func
section lintegral
open simple_func
variables [measurable_space Ξ±] {ΞΌ : measure Ξ±}
/-- The lower Lebesgue integral of a function `f` with respect to a measure `ΞΌ`. -/
def lintegral (ΞΌ : measure Ξ±) (f : Ξ± β ennreal) : ennreal :=
β¨ (g : Ξ± ββ ennreal) (hf : βg β€ f), g.lintegral ΞΌ
notation `β«β»` binders `, ` r:(scoped:60 f, f) ` β` ΞΌ:70 := lintegral ΞΌ r
notation `β«β»` binders `, ` r:(scoped:60 f, lintegral volume f) := r
notation `β«β»` binders ` in ` s `, ` r:(scoped:60 f, f) ` β` ΞΌ:70 :=
lintegral (measure.restrict ΞΌ s) r
notation `β«β»` binders ` in ` s `, ` r:(scoped:60 f, lintegral (measure.restrict volume s) f) := r
theorem simple_func.lintegral_eq_lintegral (f : Ξ± ββ ennreal) (ΞΌ : measure Ξ±) :
β«β» a, f a β ΞΌ = f.lintegral ΞΌ :=
le_antisymm
(bsupr_le $ Ξ» g hg, lintegral_mono hg $ le_refl _)
(le_supr_of_le f $ le_supr_of_le (le_refl _) (le_refl _))
@[mono] lemma lintegral_mono' β¦ΞΌ Ξ½ : measure Ξ±β¦ (hΞΌΞ½ : ΞΌ β€ Ξ½) β¦f g : Ξ± β ennrealβ¦ (hfg : f β€ g) :
β«β» a, f a βΞΌ β€ β«β» a, g a βΞ½ :=
supr_le_supr $ Ξ» Ο, supr_le_supr2 $ Ξ» hΟ, β¨le_trans hΟ hfg, lintegral_mono (le_refl Ο) hΞΌΞ½β©
lemma lintegral_mono β¦f g : Ξ± β ennrealβ¦ (hfg : f β€ g) :
β«β» a, f a βΞΌ β€ β«β» a, g a βΞΌ :=
lintegral_mono' (le_refl ΞΌ) hfg
lemma monotone_lintegral (ΞΌ : measure Ξ±) : monotone (lintegral ΞΌ) :=
lintegral_mono
@[simp] lemma lintegral_const (c : ennreal) : β«β» a, c βΞΌ = c * ΞΌ univ :=
by rw [β simple_func.const_lintegral, β simple_func.lintegral_eq_lintegral, simple_func.coe_const]
lemma set_lintegral_one (s) : β«β» a in s, 1 βΞΌ = ΞΌ s :=
by rw [lintegral_const, one_mul, measure.restrict_apply_univ]
/-- `β«β» a in s, f a βΞΌ` is defined as the supremum of integrals of simple functions
`Ο : Ξ± ββ ennreal` such that `Ο β€ f`. This lemma says that it suffices to take
functions `Ο : Ξ± ββ ββ₯0`. -/
lemma lintegral_eq_nnreal (f : Ξ± β ennreal) (ΞΌ : measure Ξ±) :
(β«β» a, f a βΞΌ) = (β¨ (Ο : Ξ± ββ ββ₯0) (hf : β x, β(Ο x) β€ f x),
(Ο.map (coe : nnreal β ennreal)).lintegral ΞΌ) :=
begin
refine le_antisymm
(bsupr_le $ assume Ο hΟ, _)
(supr_le_supr2 $ Ξ» Ο, β¨Ο.map (coe : ββ₯0 β ennreal), le_refl _β©),
by_cases h : βα΅ a βΞΌ, Ο a β β€,
{ let Ο := Ο.map ennreal.to_nnreal,
replace h : Ο.map (coe : ββ₯0 β ennreal) =α΅[ΞΌ] Ο :=
h.mono (Ξ» a, ennreal.coe_to_nnreal),
have : β x, β(Ο x) β€ f x := Ξ» x, le_trans ennreal.coe_to_nnreal_le_self (hΟ x),
exact le_supr_of_le (Ο.map ennreal.to_nnreal)
(le_supr_of_le this (ge_of_eq $ lintegral_congr h)) },
{ have h_meas : ΞΌ (Ο β»ΒΉ' {β€}) β 0, from mt measure_zero_iff_ae_nmem.1 h,
refine le_trans le_top (ge_of_eq $ (supr_eq_top _).2 $ Ξ» b hb, _),
obtain β¨n, hnβ© : β n : β, b < n * ΞΌ (Ο β»ΒΉ' {β€}), from exists_nat_mul_gt h_meas (ne_of_lt hb),
use (const Ξ± (n : ββ₯0)).restrict (Ο β»ΒΉ' {β€}),
simp only [lt_supr_iff, exists_prop, coe_restrict, Ο.is_measurable_preimage, coe_const,
ennreal.coe_indicator, map_coe_ennreal_restrict, map_const, ennreal.coe_nat,
restrict_const_lintegral],
refine β¨indicator_le (Ξ» x hx, le_trans _ (hΟ _)), hnβ©,
simp only [mem_preimage, mem_singleton_iff] at hx,
simp only [hx, le_top] }
end
theorem supr_lintegral_le {ΞΉ : Sort*} (f : ΞΉ β Ξ± β ennreal) :
(β¨i, β«β» a, f i a βΞΌ) β€ (β«β» a, β¨i, f i a βΞΌ) :=
begin
simp only [β supr_apply],
exact (monotone_lintegral ΞΌ).le_map_supr
end
theorem supr2_lintegral_le {ΞΉ : Sort*} {ΞΉ' : ΞΉ β Sort*} (f : Ξ i, ΞΉ' i β Ξ± β ennreal) :
(β¨i (h : ΞΉ' i), β«β» a, f i h a βΞΌ) β€ (β«β» a, β¨i (h : ΞΉ' i), f i h a βΞΌ) :=
by { convert (monotone_lintegral ΞΌ).le_map_supr2 f, ext1 a, simp only [supr_apply] }
theorem le_infi_lintegral {ΞΉ : Sort*} (f : ΞΉ β Ξ± β ennreal) :
(β«β» a, β¨
i, f i a βΞΌ) β€ (β¨
i, β«β» a, f i a βΞΌ) :=
by { simp only [β infi_apply], exact (monotone_lintegral ΞΌ).map_infi_le }
theorem le_infi2_lintegral {ΞΉ : Sort*} {ΞΉ' : ΞΉ β Sort*} (f : Ξ i, ΞΉ' i β Ξ± β ennreal) :
(β«β» a, β¨
i (h : ΞΉ' i), f i h a βΞΌ) β€ (β¨
i (h : ΞΉ' i), β«β» a, f i h a βΞΌ) :=
by { convert (monotone_lintegral ΞΌ).map_infi2_le f, ext1 a, simp only [infi_apply] }
/-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence.
See `lintegral_supr_directed` for a more general form. -/
theorem lintegral_supr
{f : β β Ξ± β ennreal} (hf : βn, measurable (f n)) (h_mono : monotone f) :
(β«β» a, β¨n, f n a βΞΌ) = (β¨n, β«β» a, f n a βΞΌ) :=
begin
set c : nnreal β ennreal := coe,
set F := Ξ» a:Ξ±, β¨n, f n a,
have hF : measurable F := measurable_supr hf,
refine le_antisymm _ (supr_lintegral_le _),
rw [lintegral_eq_nnreal],
refine supr_le (assume s, supr_le (assume hsf, _)),
refine ennreal.le_of_forall_lt_one_mul_lt (assume a ha, _),
rcases ennreal.lt_iff_exists_coe.1 ha with β¨r, rfl, haβ©,
have ha : r < 1 := ennreal.coe_lt_coe.1 ha,
let rs := s.map (Ξ»a, r * a),
have eq_rs : (const Ξ± r : Ξ± ββ ennreal) * map c s = rs.map c,
{ ext1 a, exact ennreal.coe_mul.symm },
have eq : βp, (rs.map c) β»ΒΉ' {p} = (βn, (rs.map c) β»ΒΉ' {p} β© {a | p β€ f n a}),
{ assume p,
rw [β inter_Union, β inter_univ ((map c rs) β»ΒΉ' {p})] {occs := occurrences.pos [1]},
refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _),
by_cases p_eq : p = 0, { simp [p_eq] },
simp at hx, subst hx,
have : r * s x β 0, { rwa [(β ), β ennreal.coe_eq_zero] },
have : s x β 0, { refine mt _ this, assume h, rw [h, mul_zero] },
have : (rs.map c) x < β¨ (n : β), f n x,
{ refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x),
suffices : r * s x < 1 * s x, simpa [rs],
exact mul_lt_mul_of_pos_right ha (zero_lt_iff_ne_zero.2 this) },
rcases lt_supr_iff.1 this with β¨i, hiβ©,
exact mem_Union.2 β¨i, le_of_lt hiβ© },
have mono : βr:ennreal, monotone (Ξ»n, (rs.map c) β»ΒΉ' {r} β© {a | r β€ f n a}),
{ assume r i j h,
refine inter_subset_inter (subset.refl _) _,
assume x hx, exact le_trans hx (h_mono h x) },
have h_meas : βn, is_measurable {a : Ξ± | β(map c rs) a β€ f n a} :=
assume n, is_measurable_le (simple_func.measurable _) (hf n),
calc (r:ennreal) * (s.map c).lintegral ΞΌ = β r in (rs.map c).range, r * ΞΌ ((rs.map c) β»ΒΉ' {r}) :
by rw [β const_mul_lintegral, eq_rs, simple_func.lintegral]
... β€ β r in (rs.map c).range, r * ΞΌ (βn, (rs.map c) β»ΒΉ' {r} β© {a | r β€ f n a}) :
le_of_eq (finset.sum_congr rfl $ assume x hx, by rw β eq)
... β€ β r in (rs.map c).range, (β¨n, r * ΞΌ ((rs.map c) β»ΒΉ' {r} β© {a | r β€ f n a})) :
le_of_eq (finset.sum_congr rfl $ assume x hx,
begin
rw [measure_Union_eq_supr _ (directed_of_sup $ mono x), ennreal.mul_supr],
{ assume i,
refine ((rs.map c).is_measurable_preimage _).inter _,
exact hf i is_measurable_Ici }
end)
... β€ β¨n, β r in (rs.map c).range, r * ΞΌ ((rs.map c) β»ΒΉ' {r} β© {a | r β€ f n a}) :
begin
refine le_of_eq _,
rw [ennreal.finset_sum_supr_nat],
assume p i j h,
exact canonically_ordered_semiring.mul_le_mul (le_refl _) (measure_mono $ mono p h)
end
... β€ (β¨n:β, ((rs.map c).restrict {a | (rs.map c) a β€ f n a}).lintegral ΞΌ) :
begin
refine supr_le_supr (assume n, _),
rw [restrict_lintegral _ (h_meas n)],
{ refine le_of_eq (finset.sum_congr rfl $ assume r hr, _),
congr' 2 with a,
refine and_congr_right _,
simp {contextual := tt} }
end
... β€ (β¨n, β«β» a, f n a βΞΌ) :
begin
refine supr_le_supr (assume n, _),
rw [β simple_func.lintegral_eq_lintegral],
refine lintegral_mono (assume a, _),
dsimp,
rw [restrict_apply],
split_ifs; simp, simpa using h,
exact h_meas n
end
end
lemma lintegral_eq_supr_eapprox_lintegral {f : Ξ± β ennreal} (hf : measurable f) :
(β«β» a, f a βΞΌ) = (β¨n, (eapprox f n).lintegral ΞΌ) :=
calc (β«β» a, f a βΞΌ) = (β«β» a, β¨n, (eapprox f n : Ξ± β ennreal) a βΞΌ) :
by congr; ext a; rw [supr_eapprox_apply f hf]
... = (β¨n, β«β» a, (eapprox f n : Ξ± β ennreal) a βΞΌ) :
begin
rw [lintegral_supr],
{ assume n, exact (eapprox f n).measurable },
{ assume i j h, exact (monotone_eapprox f h) }
end
... = (β¨n, (eapprox f n).lintegral ΞΌ) : by congr; ext n; rw [(eapprox f n).lintegral_eq_lintegral]
@[simp] lemma lintegral_add {f g : Ξ± β ennreal} (hf : measurable f) (hg : measurable g) :
(β«β» a, f a + g a βΞΌ) = (β«β» a, f a βΞΌ) + (β«β» a, g a βΞΌ) :=
calc (β«β» a, f a + g a βΞΌ) =
(β«β» a, (β¨n, (eapprox f n : Ξ± β ennreal) a) + (β¨n, (eapprox g n : Ξ± β ennreal) a) βΞΌ) :
by congr; funext a; rw [supr_eapprox_apply f hf, supr_eapprox_apply g hg]
... = (β«β» a, (β¨n, (eapprox f n + eapprox g n : Ξ± β ennreal) a) βΞΌ) :
begin
congr, funext a,
rw [ennreal.supr_add_supr_of_monotone], { refl },
{ assume i j h, exact monotone_eapprox _ h a },
{ assume i j h, exact monotone_eapprox _ h a },
end
... = (β¨n, (eapprox f n).lintegral ΞΌ + (eapprox g n).lintegral ΞΌ) :
begin
rw [lintegral_supr],
{ congr,
funext n, rw [β simple_func.add_lintegral, β simple_func.lintegral_eq_lintegral],
refl },
{ assume n, exact measurable.add (eapprox f n).measurable (eapprox g n).measurable },
{ assume i j h a, exact add_le_add (monotone_eapprox _ h _) (monotone_eapprox _ h _) }
end
... = (β¨n, (eapprox f n).lintegral ΞΌ) + (β¨n, (eapprox g n).lintegral ΞΌ) :
by refine (ennreal.supr_add_supr_of_monotone _ _).symm;
{ assume i j h, exact simple_func.lintegral_mono (monotone_eapprox _ h) (le_refl ΞΌ) }
... = (β«β» a, f a βΞΌ) + (β«β» a, g a βΞΌ) :
by rw [lintegral_eq_supr_eapprox_lintegral hf, lintegral_eq_supr_eapprox_lintegral hg]
lemma lintegral_zero : (β«β» a:Ξ±, 0 βΞΌ) = 0 := by simp
@[simp] lemma lintegral_smul_measure (c : ennreal) (f : Ξ± β ennreal) :
β«β» a, f a β (c β’ ΞΌ) = c * β«β» a, f a βΞΌ :=
by simp only [lintegral, supr_subtype', simple_func.lintegral_smul, ennreal.mul_supr, smul_eq_mul]
@[simp] lemma lintegral_sum_measure {ΞΉ} (f : Ξ± β ennreal) (ΞΌ : ΞΉ β measure Ξ±) :
β«β» a, f a β(measure.sum ΞΌ) = β' i, β«β» a, f a β(ΞΌ i) :=
begin
simp only [lintegral, supr_subtype', simple_func.lintegral_sum, ennreal.tsum_eq_supr_sum],
rw [supr_comm],
congr, funext s,
induction s using finset.induction_on with i s hi hs, { apply bot_unique, simp },
simp only [finset.sum_insert hi, β hs],
refine (ennreal.supr_add_supr _).symm,
intros Ο Ο,
exact β¨β¨Ο β Ο, Ξ» x, sup_le (Ο.2 x) (Ο.2 x)β©,
add_le_add (simple_func.lintegral_mono le_sup_left (le_refl _))
(finset.sum_le_sum $ Ξ» j hj, simple_func.lintegral_mono le_sup_right (le_refl _))β©
end
@[simp] lemma lintegral_add_measure (f : Ξ± β ennreal) (ΞΌ Ξ½ : measure Ξ±) :
β«β» a, f a β (ΞΌ + Ξ½) = β«β» a, f a βΞΌ + β«β» a, f a βΞ½ :=
by simpa [tsum_fintype] using lintegral_sum_measure f (Ξ» b, cond b ΞΌ Ξ½)
@[simp] lemma lintegral_zero_measure (f : Ξ± β ennreal) : β«β» a, f a β0 = 0 :=
bot_unique $ by simp [lintegral]
lemma lintegral_finset_sum (s : finset Ξ²) {f : Ξ² β Ξ± β ennreal} (hf : βb, measurable (f b)) :
(β«β» a, β b in s, f b a βΞΌ) = β b in s, β«β» a, f b a βΞΌ :=
begin
refine finset.induction_on s _ _,
{ simp },
{ assume a s has ih,
simp only [finset.sum_insert has],
rw [lintegral_add (hf _) (s.measurable_sum hf), ih] }
end
@[simp] lemma lintegral_const_mul (r : ennreal) {f : Ξ± β ennreal} (hf : measurable f) :
(β«β» a, r * f a βΞΌ) = r * (β«β» a, f a βΞΌ) :=
calc (β«β» a, r * f a βΞΌ) = (β«β» a, (β¨n, (const Ξ± r * eapprox f n) a) βΞΌ) :
by { congr, funext a, rw [β supr_eapprox_apply f hf, ennreal.mul_supr], refl }
... = (β¨n, r * (eapprox f n).lintegral ΞΌ) :
begin
rw [lintegral_supr],
{ congr, funext n,
rw [β simple_func.const_mul_lintegral, β simple_func.lintegral_eq_lintegral] },
{ assume n, exact simple_func.measurable _ },
{ assume i j h a, exact canonically_ordered_semiring.mul_le_mul (le_refl _)
(monotone_eapprox _ h _) }
end
... = r * (β«β» a, f a βΞΌ) : by rw [β ennreal.mul_supr, lintegral_eq_supr_eapprox_lintegral hf]
lemma lintegral_const_mul_le (r : ennreal) (f : Ξ± β ennreal) :
r * (β«β» a, f a βΞΌ) β€ (β«β» a, r * f a βΞΌ) :=
begin
rw [lintegral, ennreal.mul_supr],
refine supr_le (Ξ»s, _),
rw [ennreal.mul_supr],
simp only [supr_le_iff, ge_iff_le],
assume hs,
rw β simple_func.const_mul_lintegral,
refine le_supr_of_le (const Ξ± r * s) (le_supr_of_le (Ξ»x, _) (le_refl _)),
exact canonically_ordered_semiring.mul_le_mul (le_refl _) (hs x)
end
lemma lintegral_const_mul' (r : ennreal) (f : Ξ± β ennreal) (hr : r β β€) :
(β«β» a, r * f a βΞΌ) = r * (β«β» a, f a βΞΌ) :=
begin
by_cases h : r = 0,
{ simp [h] },
apply le_antisymm _ (lintegral_const_mul_le r f),
have rinv : r * rβ»ΒΉ = 1 := ennreal.mul_inv_cancel h hr,
have rinv' : r β»ΒΉ * r = 1, by { rw mul_comm, exact rinv },
have := lintegral_const_mul_le (rβ»ΒΉ) (Ξ»x, r * f x),
simp [(mul_assoc _ _ _).symm, rinv'] at this,
simpa [(mul_assoc _ _ _).symm, rinv]
using canonically_ordered_semiring.mul_le_mul (le_refl r) this
end
lemma lintegral_mono_ae {f g : Ξ± β ennreal} (h : βα΅ a βΞΌ, f a β€ g a) :
(β«β» a, f a βΞΌ) β€ (β«β» a, g a βΞΌ) :=
begin
rcases exists_is_measurable_superset_of_measure_eq_zero h with β¨t, hts, ht, ht0β©,
have : βα΅ x βΞΌ, x β t := measure_zero_iff_ae_nmem.1 ht0,
refine (supr_le $ assume s, supr_le $ assume hfs,
le_supr_of_le (s.restrict tαΆ) $ le_supr_of_le _ _),
{ assume a,
by_cases a β t;
simp [h, restrict_apply, ht.compl],
exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) },
{ refine le_of_eq (simple_func.lintegral_congr $ this.mono $ Ξ» a hnt, _),
by_cases hat : a β t; simp [hat, ht.compl],
exact (hnt hat).elim }
end
lemma lintegral_congr_ae {f g : Ξ± β ennreal} (h : f =α΅[ΞΌ] g) :
(β«β» a, f a βΞΌ) = (β«β» a, g a βΞΌ) :=
le_antisymm (lintegral_mono_ae $ h.le) (lintegral_mono_ae $ h.symm.le)
lemma lintegral_congr {f g : Ξ± β ennreal} (h : β a, f a = g a) :
(β«β» a, f a βΞΌ) = (β«β» a, g a βΞΌ) :=
by simp only [h]
lemma set_lintegral_congr {f : Ξ± β ennreal} {s t : set Ξ±} (h : s =α΅[ΞΌ] t) :
β«β» x in s, f x βΞΌ = β«β» x in t, f x βΞΌ :=
by rw [restrict_congr_set h]
-- TODO: Need a better way of rewriting inside of a integral
lemma lintegral_rwβ {f f' : Ξ± β Ξ²} (h : f =α΅[ΞΌ] f') (g : Ξ² β ennreal) :
(β«β» a, g (f a) βΞΌ) = (β«β» a, g (f' a) βΞΌ) :=
lintegral_congr_ae $ h.mono $ Ξ» a h, by rw h
-- TODO: Need a better way of rewriting inside of a integral
lemma lintegral_rwβ {fβ fβ' : Ξ± β Ξ²} {fβ fβ' : Ξ± β Ξ³} (hβ : fβ =α΅[ΞΌ] fβ')
(hβ : fβ =α΅[ΞΌ] fβ') (g : Ξ² β Ξ³ β ennreal) :
(β«β» a, g (fβ a) (fβ a) βΞΌ) = (β«β» a, g (fβ' a) (fβ' a) βΞΌ) :=
lintegral_congr_ae $ hβ.mp $ hβ.mono $ Ξ» _ hβ hβ, by rw [hβ, hβ]
@[simp] lemma lintegral_indicator (f : Ξ± β ennreal) {s : set Ξ±} (hs : is_measurable s) :
β«β» a, s.indicator f a βΞΌ = β«β» a in s, f a βΞΌ :=
begin
simp only [lintegral, β restrict_lintegral_eq_lintegral_restrict _ hs, supr_subtype'],
apply le_antisymm; refine supr_le_supr2 (subtype.forall.2 $ Ξ» Ο hΟ, _),
{ refine β¨β¨Ο, le_trans hΟ (indicator_le_self _ _)β©, _β©,
refine simple_func.lintegral_mono (Ξ» x, _) (le_refl _),
by_cases hx : x β s,
{ simp [hx, hs, le_refl] },
{ apply le_trans (hΟ x),
simp [hx, hs, le_refl] } },
{ refine β¨β¨Ο.restrict s, Ξ» x, _β©, le_refl _β©,
simp [hΟ x, hs, indicator_le_indicator] }
end
/-- Chebyshev's inequality -/
lemma mul_meas_ge_le_lintegral {f : Ξ± β ennreal} (hf : measurable f) (Ξ΅ : ennreal) :
Ξ΅ * ΞΌ {x | Ξ΅ β€ f x} β€ β«β» a, f a βΞΌ :=
begin
have : is_measurable {a : Ξ± | Ξ΅ β€ f a }, from hf is_measurable_Ici,
rw [β simple_func.restrict_const_lintegral _ this, β simple_func.lintegral_eq_lintegral],
refine lintegral_mono (Ξ» a, _),
simp only [restrict_apply _ this],
split_ifs; [assumption, exact zero_le _]
end
lemma meas_ge_le_lintegral_div {f : Ξ± β ennreal} (hf : measurable f) {Ξ΅ : ennreal}
(hΞ΅ : Ξ΅ β 0) (hΞ΅' : Ξ΅ β β€) :
ΞΌ {x | Ξ΅ β€ f x} β€ (β«β» a, f a βΞΌ) / Ξ΅ :=
(ennreal.le_div_iff_mul_le (or.inl hΞ΅) (or.inl hΞ΅')).2 $
by { rw [mul_comm], exact mul_meas_ge_le_lintegral hf Ξ΅ }
@[simp] lemma lintegral_eq_zero_iff {f : Ξ± β ennreal} (hf : measurable f) :
β«β» a, f a βΞΌ = 0 β (f =α΅[ΞΌ] 0) :=
begin
refine iff.intro (assume h, _) (assume h, _),
{ have : βn:β, βα΅ a βΞΌ, f a < nβ»ΒΉ,
{ assume n,
rw [ae_iff, β le_zero_iff_eq, β @ennreal.zero_div nβ»ΒΉ,
ennreal.le_div_iff_mul_le, mul_comm],
simp only [not_lt],
-- TODO: why `rw β h` fails with "not an equality or an iff"?
exacts [h βΈ mul_meas_ge_le_lintegral hf nβ»ΒΉ,
or.inl (ennreal.inv_ne_zero.2 ennreal.coe_nat_ne_top),
or.inr ennreal.zero_ne_top] },
refine (ae_all_iff.2 this).mono (Ξ» a ha, _),
by_contradiction h,
rcases ennreal.exists_inv_nat_lt h with β¨n, hnβ©,
exact (lt_irrefl _ $ lt_trans hn $ ha n).elim },
{ calc β«β» a, f a βΞΌ = β«β» a, 0 βΞΌ : lintegral_congr_ae h
... = 0 : lintegral_zero }
end
lemma lintegral_pos_iff_support {f : Ξ± β ennreal} (hf : measurable f) :
0 < β«β» a, f a βΞΌ β 0 < ΞΌ (function.support f) :=
by simp [zero_lt_iff_ne_zero, hf, filter.eventually_eq, ae_iff, function.support]
/-- Weaker version of the monotone convergence theorem-/
lemma lintegral_supr_ae {f : β β Ξ± β ennreal} (hf : βn, measurable (f n))
(h_mono : βn, βα΅ a βΞΌ, f n a β€ f n.succ a) :
(β«β» a, β¨n, f n a βΞΌ) = (β¨n, β«β» a, f n a βΞΌ) :=
let β¨s, hsβ© := exists_is_measurable_superset_of_measure_eq_zero
(ae_iff.1 (ae_all_iff.2 h_mono)) in
let g := Ξ» n a, if a β s then 0 else f n a in
have g_eq_f : βα΅ a βΞΌ, βn, g n a = f n a,
from (measure_zero_iff_ae_nmem.1 hs.2.2).mono (assume a ha n, if_neg ha),
calc
β«β» a, β¨n, f n a βΞΌ = β«β» a, β¨n, g n a βΞΌ :
lintegral_congr_ae $ g_eq_f.mono $ Ξ» a ha, by simp only [ha]
... = β¨n, (β«β» a, g n a βΞΌ) :
lintegral_supr
(assume n, measurable_const.piecewise hs.2.1 (hf n))
(monotone_of_monotone_nat $ assume n a, classical.by_cases
(assume h : a β s, by simp [g, if_pos h])
(assume h : a β s,
begin
simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h,
simp only [not_not, mem_set_of_eq] at this, exact this n
end))
... = β¨n, (β«β» a, f n a βΞΌ) :
by simp only [lintegral_congr_ae (g_eq_f.mono $ Ξ» a ha, ha _)]
lemma lintegral_sub {f g : Ξ± β ennreal} (hf : measurable f) (hg : measurable g)
(hg_fin : β«β» a, g a βΞΌ < β€) (h_le : g β€α΅[ΞΌ] f) :
β«β» a, f a - g a βΞΌ = β«β» a, f a βΞΌ - β«β» a, g a βΞΌ :=
begin
rw [β ennreal.add_left_inj hg_fin,
ennreal.sub_add_cancel_of_le (lintegral_mono_ae h_le),
β lintegral_add (hf.ennreal_sub hg) hg],
refine lintegral_congr_ae (h_le.mono $ Ξ» x hx, _),
exact ennreal.sub_add_cancel_of_le hx
end
/-- Monotone convergence theorem for nonincreasing sequences of functions -/
lemma lintegral_infi_ae
{f : β β Ξ± β ennreal} (h_meas : βn, measurable (f n))
(h_mono : βn:β, f n.succ β€α΅[ΞΌ] f n) (h_fin : β«β» a, f 0 a βΞΌ < β€) :
β«β» a, β¨
n, f n a βΞΌ = β¨
n, β«β» a, f n a βΞΌ :=
have fn_le_f0 : β«β» a, β¨
n, f n a βΞΌ β€ β«β» a, f 0 a βΞΌ, from
lintegral_mono (assume a, infi_le_of_le 0 (le_refl _)),
have fn_le_f0' : (β¨
n, β«β» a, f n a βΞΌ) β€ β«β» a, f 0 a βΞΌ, from infi_le_of_le 0 (le_refl _),
(ennreal.sub_right_inj h_fin fn_le_f0 fn_le_f0').1 $
show β«β» a, f 0 a βΞΌ - β«β» a, β¨
n, f n a βΞΌ = β«β» a, f 0 a βΞΌ - (β¨
n, β«β» a, f n a βΞΌ), from
calc
β«β» a, f 0 a βΞΌ - (β«β» a, β¨
n, f n a βΞΌ) = β«β» a, f 0 a - β¨
n, f n a βΞΌ:
(lintegral_sub (h_meas 0) (measurable_infi h_meas)
(calc
(β«β» a, β¨
n, f n a βΞΌ) β€ β«β» a, f 0 a βΞΌ : lintegral_mono (assume a, infi_le _ _)
... < β€ : h_fin )
(ae_of_all _ $ assume a, infi_le _ _)).symm
... = β«β» a, β¨n, f 0 a - f n a βΞΌ : congr rfl (funext (assume a, ennreal.sub_infi))
... = β¨n, β«β» a, f 0 a - f n a βΞΌ :
lintegral_supr_ae
(assume n, (h_meas 0).ennreal_sub (h_meas n))
(assume n, (h_mono n).mono $ assume a ha, ennreal.sub_le_sub (le_refl _) ha)
... = β¨n, β«β» a, f 0 a βΞΌ - β«β» a, f n a βΞΌ :
have h_mono : βα΅ a βΞΌ, βn:β, f n.succ a β€ f n a := ae_all_iff.2 h_mono,
have h_mono : βn, βα΅ a βΞΌ, f n a β€ f 0 a := assume n, h_mono.mono $ assume a h,
begin
induction n with n ih,
{exact le_refl _}, {exact le_trans (h n) ih}
end,
congr rfl (funext $ assume n, lintegral_sub (h_meas _) (h_meas _)
(calc
β«β» a, f n a βΞΌ β€ β«β» a, f 0 a βΞΌ : lintegral_mono_ae $ h_mono n
... < β€ : h_fin)
(h_mono n))
... = β«β» a, f 0 a βΞΌ - β¨
n, β«β» a, f n a βΞΌ : ennreal.sub_infi.symm
/-- Monotone convergence theorem for nonincreasing sequences of functions -/
lemma lintegral_infi
{f : β β Ξ± β ennreal} (h_meas : βn, measurable (f n))
(h_mono : β β¦m nβ¦, m β€ n β f n β€ f m) (h_fin : β«β» a, f 0 a βΞΌ < β€) :
β«β» a, β¨
n, f n a βΞΌ = β¨
n, β«β» a, f n a βΞΌ :=
lintegral_infi_ae h_meas (Ξ» n, ae_of_all _ $ h_mono $ le_of_lt n.lt_succ_self) h_fin
/-- Known as Fatou's lemma -/
lemma lintegral_liminf_le {f : β β Ξ± β ennreal} (h_meas : βn, measurable (f n)) :
β«β» a, liminf at_top (Ξ» n, f n a) βΞΌ β€ liminf at_top (Ξ» n, β«β» a, f n a βΞΌ) :=
calc
β«β» a, liminf at_top (Ξ» n, f n a) βΞΌ = β«β» a, β¨n:β, β¨
iβ₯n, f i a βΞΌ :
by simp only [liminf_eq_supr_infi_of_nat]
... = β¨n:β, β«β» a, β¨
iβ₯n, f i a βΞΌ :
lintegral_supr
(assume n, measurable_binfi _ (countable_encodable _) h_meas)
(assume n m hnm a, infi_le_infi_of_subset $ Ξ» i hi, le_trans hnm hi)
... β€ β¨n:β, β¨
iβ₯n, β«β» a, f i a βΞΌ :
supr_le_supr $ Ξ» n, le_infi2_lintegral _
... = liminf at_top (Ξ» n, β«β» a, f n a βΞΌ) : liminf_eq_supr_infi_of_nat.symm
lemma limsup_lintegral_le {f : β β Ξ± β ennreal} {g : Ξ± β ennreal}
(hf_meas : β n, measurable (f n)) (h_bound : βn, f n β€α΅[ΞΌ] g) (h_fin : β«β» a, g a βΞΌ < β€) :
limsup at_top (Ξ»n, β«β» a, f n a βΞΌ) β€ β«β» a, limsup at_top (Ξ»n, f n a) βΞΌ :=
calc
limsup at_top (Ξ»n, β«β» a, f n a βΞΌ) = β¨
n:β, β¨iβ₯n, β«β» a, f i a βΞΌ :
limsup_eq_infi_supr_of_nat
... β€ β¨
n:β, β«β» a, β¨iβ₯n, f i a βΞΌ :
infi_le_infi $ assume n, supr2_lintegral_le _
... = β«β» a, β¨
n:β, β¨iβ₯n, f i a βΞΌ :
begin
refine (lintegral_infi _ _ _).symm,
{ assume n, exact measurable_bsupr _ (countable_encodable _) hf_meas },
{ assume n m hnm a, exact (supr_le_supr_of_subset $ Ξ» i hi, le_trans hnm hi) },
{ refine lt_of_le_of_lt (lintegral_mono_ae _) h_fin,
refine (ae_all_iff.2 h_bound).mono (Ξ» n hn, _),
exact supr_le (Ξ» i, supr_le $ Ξ» hi, hn i) }
end
... = β«β» a, limsup at_top (Ξ»n, f n a) βΞΌ :
by simp only [limsup_eq_infi_supr_of_nat]
/-- Dominated convergence theorem for nonnegative functions -/
lemma tendsto_lintegral_of_dominated_convergence
{F : β β Ξ± β ennreal} {f : Ξ± β ennreal} (bound : Ξ± β ennreal)
(hF_meas : βn, measurable (F n)) (h_bound : βn, F n β€α΅[ΞΌ] bound)
(h_fin : β«β» a, bound a βΞΌ < β€)
(h_lim : βα΅ a βΞΌ, tendsto (Ξ» n, F n a) at_top (π (f a))) :
tendsto (Ξ»n, β«β» a, F n a βΞΌ) at_top (π (β«β» a, f a βΞΌ)) :=
tendsto_of_le_liminf_of_limsup_le
(calc β«β» a, f a βΞΌ = β«β» a, liminf at_top (Ξ» (n : β), F n a) βΞΌ :
lintegral_congr_ae $ h_lim.mono $ assume a h, h.liminf_eq.symm
... β€ liminf at_top (Ξ» n, β«β» a, F n a βΞΌ) : lintegral_liminf_le hF_meas)
(calc limsup at_top (Ξ» (n : β), β«β» a, F n a βΞΌ) β€ β«β» a, limsup at_top (Ξ»n, F n a) βΞΌ :
limsup_lintegral_le hF_meas h_bound h_fin
... = β«β» a, f a βΞΌ : lintegral_congr_ae $ h_lim.mono $ Ξ» a h, h.limsup_eq)
/-- Dominated convergence theorem for filters with a countable basis -/
lemma tendsto_lintegral_filter_of_dominated_convergence {ΞΉ} {l : filter ΞΉ}
{F : ΞΉ β Ξ± β ennreal} {f : Ξ± β ennreal} (bound : Ξ± β ennreal)
(hl_cb : l.is_countably_generated)
(hF_meas : βαΆ n in l, measurable (F n))
(h_bound : βαΆ n in l, βα΅ a βΞΌ, F n a β€ bound a)
(h_fin : β«β» a, bound a βΞΌ < β€)
(h_lim : βα΅ a βΞΌ, tendsto (Ξ» n, F n a) l (π (f a))) :
tendsto (Ξ»n, β«β» a, F n a βΞΌ) l (π $ β«β» a, f a βΞΌ) :=
begin
rw hl_cb.tendsto_iff_seq_tendsto,
{ intros x xl,
have hxl, { rw tendsto_at_top' at xl, exact xl },
have h := inter_mem_sets hF_meas h_bound,
replace h := hxl _ h,
rcases h with β¨k, hβ©,
rw β tendsto_add_at_top_iff_nat k,
refine tendsto_lintegral_of_dominated_convergence _ _ _ _ _,
{ exact bound },
{ intro, refine (h _ _).1, exact nat.le_add_left _ _ },
{ intro, refine (h _ _).2, exact nat.le_add_left _ _ },
{ assumption },
{ refine h_lim.mono (Ξ» a h_lim, _),
apply @tendsto.comp _ _ _ (Ξ»n, x (n + k)) (Ξ»n, F n a),
{ assumption },
rw tendsto_add_at_top_iff_nat,
assumption } },
end
section
open encodable
/-- Monotone convergence for a suprema over a directed family and indexed by an encodable type -/
theorem lintegral_supr_directed [encodable Ξ²] {f : Ξ² β Ξ± β ennreal}
(hf : βb, measurable (f b)) (h_directed : directed (β€) f) :
β«β» a, β¨b, f b a βΞΌ = β¨b, β«β» a, f b a βΞΌ :=
begin
by_cases hΞ² : nonempty Ξ², swap,
{ simp [supr_of_empty hΞ²] },
resetI, inhabit Ξ²,
have : βa, (β¨ b, f b a) = (β¨ n, f (h_directed.sequence f n) a),
{ assume a,
refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (Ξ»n, f n a) _),
exact le_supr_of_le (encode b + 1) (h_directed.le_sequence b a) },
calc β«β» a, β¨ b, f b a βΞΌ = β«β» a, β¨ n, f (h_directed.sequence f n) a βΞΌ :
by simp only [this]
... = β¨ n, β«β» a, f (h_directed.sequence f n) a βΞΌ :
lintegral_supr (assume n, hf _) h_directed.sequence_mono
... = β¨ b, β«β» a, f b a βΞΌ :
begin
refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _),
{ exact le_supr (Ξ»b, β«β» a, f b a βΞΌ) _ },
{ exact le_supr_of_le (encode b + 1)
(lintegral_mono $ h_directed.le_sequence b) }
end
end
end
lemma lintegral_tsum [encodable Ξ²] {f : Ξ² β Ξ± β ennreal} (hf : βi, measurable (f i)) :
β«β» a, β' i, f i a βΞΌ = β' i, β«β» a, f i a βΞΌ :=
begin
simp only [ennreal.tsum_eq_supr_sum],
rw [lintegral_supr_directed],
{ simp [lintegral_finset_sum _ hf] },
{ assume b, exact finset.measurable_sum _ hf },
{ assume s t,
use [s βͺ t],
split,
exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _),
exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) }
end
open measure
lemma lintegral_Union [encodable Ξ²] {s : Ξ² β set Ξ±} (hm : β i, is_measurable (s i))
(hd : pairwise (disjoint on s)) (f : Ξ± β ennreal) :
β«β» a in β i, s i, f a βΞΌ = β' i, β«β» a in s i, f a βΞΌ :=
by simp only [measure.restrict_Union hd hm, lintegral_sum_measure]
lemma lintegral_Union_le [encodable Ξ²] (s : Ξ² β set Ξ±) (f : Ξ± β ennreal) :
β«β» a in β i, s i, f a βΞΌ β€ β' i, β«β» a in s i, f a βΞΌ :=
begin
rw [β lintegral_sum_measure],
exact lintegral_mono' restrict_Union_le (le_refl _)
end
lemma lintegral_map [measurable_space Ξ²] {f : Ξ² β ennreal} {g : Ξ± β Ξ²}
(hf : measurable f) (hg : measurable g) :
β«β» a, f a β(map g ΞΌ) = β«β» a, f (g a) βΞΌ :=
begin
simp only [lintegral_eq_supr_eapprox_lintegral, hf, hf.comp hg],
{ congr, funext n, symmetry,
apply simple_func.lintegral_map,
{ assume a, exact congr_fun (simple_func.eapprox_comp hf hg) a },
{ assume s hs, exact map_apply hg hs } },
end
lemma set_lintegral_map [measurable_space Ξ²] {f : Ξ² β ennreal} {g : Ξ± β Ξ²}
{s : set Ξ²} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) :
β«β» y in s, f y β(map g ΞΌ) = β«β» x in g β»ΒΉ' s, f (g x) βΞΌ :=
by rw [restrict_map hg hs, lintegral_map hf hg]
lemma lintegral_dirac (a : Ξ±) {f : Ξ± β ennreal} (hf : measurable f) :
β«β» a, f a β(dirac a) = f a :=
by simp [lintegral_congr_ae (eventually_eq_dirac hf)]
/-- Given a measure `ΞΌ : measure Ξ±` and a function `f : Ξ± β ennreal`, `ΞΌ.with_density f` is the
measure such that for a measurable set `s` we have `ΞΌ.with_density f s = β«β» a in s, f a βΞΌ`. -/
def measure.with_density (ΞΌ : measure Ξ±) (f : Ξ± β ennreal) : measure Ξ± :=
measure.of_measurable (Ξ»s hs, β«β» a in s, f a βΞΌ) (by simp) (Ξ» s hs hd, lintegral_Union hs hd _)
@[simp] lemma with_density_apply (f : Ξ± β ennreal) {s : set Ξ±} (hs : is_measurable s) :
ΞΌ.with_density f s = β«β» a in s, f a βΞΌ :=
measure.of_measurable_apply s hs
end lintegral
end measure_theory
open measure_theory measure_theory.simple_func
/-- To prove something for an arbitrary measurable function into `ennreal`, it suffices to show
that the property holds for (multiples of) characteristic functions and is closed under addition
and supremum of increasing sequences of functions.
It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions
can be added once we need them (for example in `h_sum` it is only necessary to consider the sum of
a simple function with a multiple of a characteristic function and that the intersection
of their images is a subset of `{0}`. -/
@[elab_as_eliminator]
theorem measurable.ennreal_induction {Ξ±} [measurable_space Ξ±] {P : (Ξ± β ennreal) β Prop}
(h_ind : β (c : ennreal) β¦sβ¦, is_measurable s β P (indicator s (Ξ» _, c)))
(h_sum : β β¦f g : Ξ± β ennrealβ¦, set.univ β f β»ΒΉ' {0} βͺ g β»ΒΉ' {0} β measurable f β measurable g β
P f β P g β P (f + g))
(h_supr : β β¦f : β β Ξ± β ennrealβ¦ (hf : βn, measurable (f n)) (h_mono : monotone f)
(hP : β n, P (f n)), P (Ξ» x, β¨ n, f n x))
β¦f : Ξ± β ennrealβ¦ (hf : measurable f) : P f :=
begin
convert h_supr (Ξ» n, (eapprox f n).measurable) (monotone_eapprox f) _,
{ ext1 x, rw [supr_eapprox_apply f hf] },
{ exact Ξ» n, simple_func.induction (Ξ» c s hs, h_ind c hs)
(Ξ» f g hfg hf hg, h_sum hfg f.measurable g.measurable hf hg) (eapprox f n) }
end
namespace measure_theory
/-- This is Exercise 1.2.1 from [tao2010]. It allows you to express integration of a measurable
function with respect to `(ΞΌ.with_density f)` as an integral with respect to `ΞΌ`, called the base
measure. `ΞΌ` is often the Lebesgue measure, and in this circumstance `f` is the probability density
function, and `(ΞΌ.with_density f)` represents any continuous random variable as a
probability measure, such as the uniform distribution between 0 and 1, the Gaussian distribution,
the exponential distribution, the Beta distribution, or the Cauchy distribution (see Section 2.4
of [wasserman2004]). Thus, this method shows how to one can calculate expectations, variances,
and other moments as a function of the probability density function.
-/
lemma lintegral_with_density_eq_lintegral_mul {Ξ±} [measurable_space Ξ±] (ΞΌ : measure Ξ±)
{f : Ξ± β ennreal} (h_mf : measurable f) : β {g : Ξ± β ennreal}, measurable g β
β«β» a, g a β(ΞΌ.with_density f) = β«β» a, (f * g) a βΞΌ :=
begin
apply measurable.ennreal_induction,
{ intros c s h_ms,
simp [*, mul_comm _ c] },
{ intros g h h_univ h_mea_g h_mea_h h_ind_g h_ind_h,
simp [mul_add, *, measurable.ennreal_mul] },
{ intros g h_mea_g h_mono_g h_ind,
have : monotone (Ξ» n a, f a * g n a) := Ξ» m n hmn x, ennreal.mul_le_mul le_rfl (h_mono_g hmn x),
simp [lintegral_supr, ennreal.mul_supr, h_mf.ennreal_mul (h_mea_g _), *] }
end
end measure_theory
|
654e30a66e92ec27b79f4fa42687318361abc29d | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/topology/list.lean | dcd1539fa2661797bed80b929a4a34184ffe5eed | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,731 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes HΓΆlzl
-/
import topology.constructions
import topology.algebra.group
/-!
# Topology on lists and vectors
-/
open topological_space set filter
open_locale topological_space filter
variables {Ξ± : Type*} {Ξ² : Type*} [topological_space Ξ±] [topological_space Ξ²]
instance : topological_space (list Ξ±) :=
topological_space.mk_of_nhds (traverse nhds)
lemma nhds_list (as : list Ξ±) : π as = traverse π as :=
begin
refine nhds_mk_of_nhds _ _ _ _,
{ assume l, induction l,
case list.nil { exact le_refl _ },
case list.cons : a l ih {
suffices : list.cons <$> pure a <*> pure l β€ list.cons <$> π a <*> traverse π l,
{ simpa only [] with functor_norm using this },
exact filter.seq_mono (filter.map_mono $ pure_le_nhds a) ih } },
{ assume l s hs,
rcases (mem_traverse_iff _ _).1 hs with β¨u, hu, husβ©, clear as hs,
have : βv:list (set Ξ±), l.forallβ (Ξ»a s, is_open s β§ a β s) v β§ sequence v β s,
{ induction hu generalizing s,
case list.forallβ.nil : hs this
{ existsi [], simpa only [list.forallβ_nil_left_iff, exists_eq_left] },
case list.forallβ.cons : a s as ss ht h ih t hts {
rcases mem_nhds_iff.1 ht with β¨u, hut, huβ©,
rcases ih (subset.refl _) with β¨v, hv, hvssβ©,
exact β¨u::v, list.forallβ.cons hu hv,
subset.trans (set.seq_mono (set.image_subset _ hut) hvss) htsβ© } },
rcases this with β¨v, hv, hvsβ©,
refine β¨sequence v, mem_traverse _ _ _, hvs, _β©,
{ exact hv.imp (assume a s β¨hs, haβ©, is_open.mem_nhds hs ha) },
{ assume u hu,
have hu := (list.mem_traverse _ _).1 hu,
have : list.forallβ (Ξ»a s, is_open s β§ a β s) u v,
{ refine list.forallβ.flip _,
replace hv := hv.flip,
simp only [list.forallβ_and_left, flip] at β’ hv,
exact β¨hv.1, hu.flipβ© },
refine mem_of_superset _ hvs,
exact mem_traverse _ _ (this.imp $ assume a s β¨hs, haβ©, is_open.mem_nhds hs ha) } }
end
@[simp] lemma nhds_nil : π ([] : list Ξ±) = pure [] :=
by rw [nhds_list, list.traverse_nil _]; apply_instance
lemma nhds_cons (a : Ξ±) (l : list Ξ±) :
π (a :: l) = list.cons <$> π a <*> π l :=
by rw [nhds_list, list.traverse_cons _, β nhds_list]; apply_instance
lemma list.tendsto_cons {a : Ξ±} {l : list Ξ±} :
tendsto (Ξ»p:Ξ±Γlist Ξ±, list.cons p.1 p.2) (π a ΓαΆ π l) (π (a :: l)) :=
by rw [nhds_cons, tendsto, map_prod]; exact le_refl _
lemma filter.tendsto.cons {Ξ± : Type*} {f : Ξ± β Ξ²} {g : Ξ± β list Ξ²}
{a : _root_.filter Ξ±} {b : Ξ²} {l : list Ξ²} (hf : tendsto f a (π b)) (hg : tendsto g a (π l)) :
tendsto (Ξ»a, list.cons (f a) (g a)) a (π (b :: l)) :=
list.tendsto_cons.comp (tendsto.prod_mk hf hg)
namespace list
lemma tendsto_cons_iff {Ξ² : Type*} {f : list Ξ± β Ξ²} {b : _root_.filter Ξ²} {a : Ξ±} {l : list Ξ±} :
tendsto f (π (a :: l)) b β tendsto (Ξ»p:Ξ±Γlist Ξ±, f (p.1 :: p.2)) (π a ΓαΆ π l) b :=
have π (a :: l) = (π a ΓαΆ π l).map (Ξ»p:Ξ±Γlist Ξ±, (p.1 :: p.2)),
begin
simp only
[nhds_cons, filter.prod_eq, (filter.map_def _ _).symm, (filter.seq_eq_filter_seq _ _).symm],
simp [-filter.seq_eq_filter_seq, -filter.map_def, (β)] with functor_norm,
end,
by rw [this, filter.tendsto_map'_iff]
lemma continuous_cons : continuous (Ξ» x : Ξ± Γ list Ξ±, (x.1 :: x.2 : list Ξ±)) :=
continuous_iff_continuous_at.mpr $ Ξ» β¨x, yβ©, continuous_at_fst.cons continuous_at_snd
lemma tendsto_nhds {Ξ² : Type*} {f : list Ξ± β Ξ²} {r : list Ξ± β _root_.filter Ξ²}
(h_nil : tendsto f (pure []) (r []))
(h_cons : βl a, tendsto f (π l) (r l) β
tendsto (Ξ»p:Ξ±Γlist Ξ±, f (p.1 :: p.2)) (π a ΓαΆ π l) (r (a::l))) :
βl, tendsto f (π l) (r l)
| [] := by rwa [nhds_nil]
| (a::l) := by rw [tendsto_cons_iff]; exact h_cons l a (tendsto_nhds l)
lemma continuous_at_length :
β(l : list Ξ±), continuous_at list.length l :=
begin
simp only [continuous_at, nhds_discrete],
refine tendsto_nhds _ _,
{ exact tendsto_pure_pure _ _ },
{ assume l a ih,
dsimp only [list.length],
refine tendsto.comp (tendsto_pure_pure (Ξ»x, x + 1) _) _,
refine tendsto.comp ih tendsto_snd }
end
lemma tendsto_insert_nth' {a : Ξ±} : β{n : β} {l : list Ξ±},
tendsto (Ξ»p:Ξ±Γlist Ξ±, insert_nth n p.1 p.2) (π a ΓαΆ π l) (π (insert_nth n a l))
| 0 l := tendsto_cons
| (n+1) [] := by simp
| (n+1) (a'::l) :=
have π a ΓαΆ π (a' :: l) =
(π a ΓαΆ (π a' ΓαΆ π l)).map (Ξ»p:Ξ±ΓΞ±Γlist Ξ±, (p.1, p.2.1 :: p.2.2)),
begin
simp only [nhds_cons, filter.prod_eq, β filter.map_def, β filter.seq_eq_filter_seq],
simp [-filter.seq_eq_filter_seq, -filter.map_def, (β)] with functor_norm
end,
begin
rw [this, tendsto_map'_iff],
exact (tendsto_fst.comp tendsto_snd).cons
((@tendsto_insert_nth' n l).comp $ tendsto_fst.prod_mk $ tendsto_snd.comp tendsto_snd)
end
lemma tendsto_insert_nth {Ξ²} {n : β} {a : Ξ±} {l : list Ξ±} {f : Ξ² β Ξ±} {g : Ξ² β list Ξ±}
{b : _root_.filter Ξ²} (hf : tendsto f b (π a)) (hg : tendsto g b (π l)) :
tendsto (Ξ»b:Ξ², insert_nth n (f b) (g b)) b (π (insert_nth n a l)) :=
tendsto_insert_nth'.comp (tendsto.prod_mk hf hg)
lemma continuous_insert_nth {n : β} : continuous (Ξ»p:Ξ±Γlist Ξ±, insert_nth n p.1 p.2) :=
continuous_iff_continuous_at.mpr $
assume β¨a, lβ©, by rw [continuous_at, nhds_prod_eq]; exact tendsto_insert_nth'
lemma tendsto_remove_nth : β{n : β} {l : list Ξ±},
tendsto (Ξ»l, remove_nth l n) (π l) (π (remove_nth l n))
| _ [] := by rw [nhds_nil]; exact tendsto_pure_nhds _ _
| 0 (a::l) := by rw [tendsto_cons_iff]; exact tendsto_snd
| (n+1) (a::l) :=
begin
rw [tendsto_cons_iff],
dsimp [remove_nth],
exact tendsto_fst.cons ((@tendsto_remove_nth n l).comp tendsto_snd)
end
lemma continuous_remove_nth {n : β} : continuous (Ξ»l : list Ξ±, remove_nth l n) :=
continuous_iff_continuous_at.mpr $ assume a, tendsto_remove_nth
@[to_additive]
lemma tendsto_prod [monoid Ξ±] [has_continuous_mul Ξ±] {l : list Ξ±} :
tendsto list.prod (π l) (π l.prod) :=
begin
induction l with x l ih,
{ simp [nhds_nil, mem_of_mem_nhds, tendsto_pure_left] {contextual := tt} },
simp_rw [tendsto_cons_iff, prod_cons],
have := continuous_iff_continuous_at.mp continuous_mul (x, l.prod),
rw [continuous_at, nhds_prod_eq] at this,
exact this.comp (tendsto_id.prod_map ih)
end
@[to_additive]
lemma continuous_prod [monoid Ξ±] [has_continuous_mul Ξ±] : continuous (prod : list Ξ± β Ξ±) :=
continuous_iff_continuous_at.mpr $ Ξ» l, tendsto_prod
end list
namespace vector
open list
instance (n : β) : topological_space (vector Ξ± n) :=
by unfold vector; apply_instance
lemma tendsto_cons {n : β} {a : Ξ±} {l : vector Ξ± n}:
tendsto (Ξ»p:Ξ±Γvector Ξ± n, p.1 ::α΅₯ p.2) (π a ΓαΆ π l) (π (a ::α΅₯ l)) :=
by { simp [tendsto_subtype_rng, βsubtype.val_eq_coe, cons_val],
exact tendsto_fst.cons (tendsto.comp continuous_at_subtype_coe tendsto_snd) }
lemma tendsto_insert_nth
{n : β} {i : fin (n+1)} {a:Ξ±} :
β{l:vector Ξ± n}, tendsto (Ξ»p:Ξ±Γvector Ξ± n, insert_nth p.1 i p.2)
(π a ΓαΆ π l) (π (insert_nth a i l))
| β¨l, hlβ© :=
begin
rw [insert_nth, tendsto_subtype_rng],
simp [insert_nth_val],
exact list.tendsto_insert_nth tendsto_fst (tendsto.comp continuous_at_subtype_coe tendsto_snd : _)
end
lemma continuous_insert_nth' {n : β} {i : fin (n+1)} :
continuous (Ξ»p:Ξ±Γvector Ξ± n, insert_nth p.1 i p.2) :=
continuous_iff_continuous_at.mpr $ assume β¨a, lβ©,
by rw [continuous_at, nhds_prod_eq]; exact tendsto_insert_nth
lemma continuous_insert_nth {n : β} {i : fin (n+1)}
{f : Ξ² β Ξ±} {g : Ξ² β vector Ξ± n} (hf : continuous f) (hg : continuous g) :
continuous (Ξ»b, insert_nth (f b) i (g b)) :=
continuous_insert_nth'.comp (hf.prod_mk hg : _)
lemma continuous_at_remove_nth {n : β} {i : fin (n+1)} :
β{l:vector Ξ± (n+1)}, continuous_at (remove_nth i) l
| β¨l, hlβ© :=
-- β{l:vector Ξ± (n+1)}, tendsto (remove_nth i) (π l) (π (remove_nth i l))
--| β¨l, hlβ© :=
begin
rw [continuous_at, remove_nth, tendsto_subtype_rng],
simp only [β subtype.val_eq_coe, vector.remove_nth_val],
exact tendsto.comp list.tendsto_remove_nth continuous_at_subtype_coe,
end
lemma continuous_remove_nth {n : β} {i : fin (n+1)} :
continuous (remove_nth i : vector Ξ± (n+1) β vector Ξ± n) :=
continuous_iff_continuous_at.mpr $ assume β¨a, lβ©, continuous_at_remove_nth
end vector
|
46c54d67e2e55a9140ca001b733260e8b2fec349 | 07c6143268cfb72beccd1cc35735d424ebcb187b | /src/computability/partrec.lean | f0256177417382aab0357557bd8cece9bd9aeb58 | [
"Apache-2.0"
] | permissive | khoek/mathlib | bc49a842910af13a3c372748310e86467d1dc766 | aa55f8b50354b3e11ba64792dcb06cccb2d8ee28 | refs/heads/master | 1,588,232,063,837 | 1,587,304,803,000 | 1,587,304,803,000 | 176,688,517 | 0 | 0 | Apache-2.0 | 1,553,070,585,000 | 1,553,070,585,000 | null | UTF-8 | Lean | false | false | 28,358 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import computability.primrec data.pfun
/-!
# The partial recursive functions
The partial recursive functions are defined similarly to the primitive
recursive functions, but now all functions are partial, implemented
using the `roption` monad, and there is an additional operation, called
ΞΌ-recursion, which performs unbounded minimization.
## References
* [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019]
-/
open encodable denumerable roption
namespace nat
section rfind
parameter (p : β β. bool)
private def lbp (m n : β) : Prop := m = n + 1 β§ β k β€ n, ff β p k
parameter (H : β n, tt β p n β§ β k < n, (p k).dom)
private def wf_lbp : well_founded lbp :=
β¨let β¨n, pnβ© := H in begin
suffices : βm k, n β€ k + m β acc (lbp p) k,
{ from Ξ»a, this _ _ (nat.le_add_left _ _) },
intros m k kn,
induction m with m IH generalizing k;
refine β¨_, Ξ» y r, _β©; rcases r with β¨rfl, aβ©,
{ injection mem_unique pn.1 (a _ kn) },
{ exact IH _ (by rw nat.add_right_comm; exact kn) }
endβ©
def rfind_x : {n // tt β p n β§ βm < n, ff β p m} :=
suffices β k, (βn < k, ff β p n) β {n // tt β p n β§ βm < n, ff β p m},
from this 0 (Ξ» n, (nat.not_lt_zero _).elim),
@well_founded.fix _ _ lbp wf_lbp begin
intros m IH al,
have pm : (p m).dom,
{ rcases H with β¨n, hβ, hββ©,
rcases decidable.lt_trichotomy m n with hβ|hβ|hβ,
{ exact hβ _ hβ },
{ rw hβ, exact hβ.fst },
{ injection mem_unique hβ (al _ hβ) } },
cases e : (p m).get pm,
{ suffices,
exact IH _ β¨rfl, thisβ© (Ξ» n h, this _ (le_of_lt_succ h)),
intros n h, cases decidable.lt_or_eq_of_le h with h h,
{ exact al _ h },
{ rw h, exact β¨_, eβ© } },
{ exact β¨m, β¨_, eβ©, alβ© }
end
end rfind
def rfind (p : β β. bool) : roption β :=
β¨_, Ξ» h, (rfind_x p h).1β©
theorem rfind_spec {p : β β. bool} {n : β} (h : n β rfind p) : tt β p n :=
h.snd βΈ (rfind_x p h.fst).2.1
theorem rfind_min {p : β β. bool} {n : β} (h : n β rfind p) :
β {m : β}, m < n β ff β p m :=
h.snd βΈ (rfind_x p h.fst).2.2
@[simp] theorem rfind_dom {p : β β. bool} :
(rfind p).dom β β n, tt β p n β§ β {m : β}, m < n β (p m).dom :=
iff.rfl
theorem rfind_dom' {p : β β. bool} :
(rfind p).dom β β n, tt β p n β§ β {m : β}, m β€ n β (p m).dom :=
exists_congr $ Ξ» n, and_congr_right $ Ξ» pn,
β¨Ξ» H m h, (eq_or_lt_of_le h).elim (Ξ» e, e.symm βΈ pn.fst) (H _),
Ξ» H m h, H (le_of_lt h)β©
@[simp] theorem mem_rfind {p : β β. bool} {n : β} :
n β rfind p β tt β p n β§ β {m : β}, m < n β ff β p m :=
β¨Ξ» h, β¨rfind_spec h, @rfind_min _ _ hβ©,
Ξ» β¨hβ, hββ©, let β¨m, hmβ© := dom_iff_mem.1 $
(@rfind_dom p).2 β¨_, hβ, Ξ» m mn, (hβ mn).fstβ© in
begin
rcases lt_trichotomy m n with h|h|h,
{ injection mem_unique (hβ h) (rfind_spec hm) },
{ rwa β h },
{ injection mem_unique hβ (rfind_min hm h) },
endβ©
theorem rfind_min' {p : β β bool} {m : β} (pm : p m) :
β n β rfind p, n β€ m :=
have tt β (p : β β. bool) m, from β¨trivial, pmβ©,
let β¨n, hnβ© := dom_iff_mem.1 $
(@rfind_dom p).2 β¨m, this, Ξ» k h, β¨β©β© in
β¨n, hn, not_lt.1 $ Ξ» h,
by injection mem_unique this (rfind_min hn h)β©
theorem rfind_zero_none
(p : β β. bool) (p0 : p 0 = none) : rfind p = none :=
eq_none_iff.2 $ Ξ» a h,
let β¨n, hβ, hββ© := rfind_dom'.1 h.fst in
(p0 βΈ hβ (zero_le _) : (@roption.none bool).dom)
def rfind_opt {Ξ±} (f : β β option Ξ±) : roption Ξ± :=
(rfind (Ξ» n, (f n).is_some)).bind (Ξ» n, f n)
theorem rfind_opt_spec {Ξ±} {f : β β option Ξ±} {a}
(h : a β rfind_opt f) : β n, a β f n :=
let β¨n, hβ, hββ© := mem_bind_iff.1 h in β¨n, mem_coe.1 hββ©
theorem rfind_opt_dom {Ξ±} {f : β β option Ξ±} :
(rfind_opt f).dom β β n a, a β f n :=
β¨Ξ» h, (rfind_opt_spec β¨h, rflβ©).imp (Ξ» n h, β¨_, hβ©),
Ξ» h, begin
have h' : β n, (f n).is_some :=
h.imp (Ξ» n, option.is_some_iff_exists.2),
have s := nat.find_spec h',
have fd : (rfind (Ξ» n, (f n).is_some)).dom :=
β¨nat.find h', by simpa using s.symm, Ξ» _ _, trivialβ©,
refine β¨fd, _β©,
have := rfind_spec (get_mem fd),
simp at this β’,
cases option.is_some_iff_exists.1 this.symm with a e,
rw e, trivial
endβ©
theorem rfind_opt_mono {Ξ±} {f : β β option Ξ±}
(H : β {a m n}, m β€ n β a β f m β a β f n)
{a} : a β rfind_opt f β β n, a β f n :=
β¨rfind_opt_spec, Ξ» β¨n, hβ©, begin
have h' := rfind_opt_dom.2 β¨_, _, hβ©,
cases rfind_opt_spec β¨h', rflβ© with k hk,
have := (H (le_max_left _ _) h).symm.trans
(H (le_max_right _ _) hk),
simp at this, simp [this, get_mem]
endβ©
inductive partrec : (β β. β) β Prop
| zero : partrec (pure 0)
| succ : partrec succ
| left : partrec (Ξ» n, n.unpair.1)
| right : partrec (Ξ» n, n.unpair.2)
| pair {f g} : partrec f β partrec g β partrec (Ξ» n, mkpair <$> f n <*> g n)
| comp {f g} : partrec f β partrec g β partrec (Ξ» n, g n >>= f)
| prec {f g} : partrec f β partrec g β partrec (unpaired (Ξ» a n,
n.elim (f a) (Ξ» y IH, do i β IH, g (mkpair a (mkpair y i)))))
| rfind {f} : partrec f β partrec (Ξ» a,
rfind (Ξ» n, (Ξ» m, m = 0) <$> f (mkpair a n)))
namespace partrec
theorem of_eq {f g : β β. β} (hf : partrec f) (H : β n, f n = g n) : partrec g :=
(funext H : f = g) βΈ hf
theorem of_eq_tot {f : β β. β} {g : β β β}
(hf : partrec f) (H : β n, g n β f n) : partrec g :=
hf.of_eq (Ξ» n, eq_some_iff.2 (H n))
theorem of_primrec {f : β β β} (hf : primrec f) : partrec f :=
begin
induction hf,
case nat.primrec.zero { exact zero },
case nat.primrec.succ { exact succ },
case nat.primrec.left { exact left },
case nat.primrec.right { exact right },
case nat.primrec.pair : f g hf hg pf pg {
refine (pf.pair pg).of_eq_tot (Ξ» n, _),
simp [has_seq.seq] },
case nat.primrec.comp : f g hf hg pf pg {
refine (pf.comp pg).of_eq_tot (Ξ» n, _),
simp },
case nat.primrec.prec : f g hf hg pf pg {
refine (pf.prec pg).of_eq_tot (Ξ» n, _),
simp,
induction n.unpair.2 with m IH, {simp},
simp, exact β¨_, IH, rflβ© },
end
protected theorem some : partrec some := of_primrec primrec.id
theorem none : partrec (Ξ» n, none) :=
(of_primrec (nat.primrec.const 1)).rfind.of_eq $
Ξ» n, eq_none_iff.2 $ Ξ» a β¨h, eβ©, by simpa using h
theorem prec' {f g h}
(hf : partrec f) (hg : partrec g) (hh : partrec h) :
partrec (Ξ» a, (f a).bind (Ξ» n, n.elim (g a)
(Ξ» y IH, do i β IH, h (mkpair a (mkpair y i))))) :=
((prec hg hh).comp (pair partrec.some hf)).of_eq $
Ξ» a, ext $ Ξ» s, by simp [(<*>)]; exact
β¨Ξ» β¨n, hβ, hββ©, β¨_, β¨_, hβ, rflβ©, by simpa using hββ©,
Ξ» β¨_, β¨n, hβ, rflβ©, hββ©, β¨_, hβ, by simpa using hββ©β©
theorem ppred : partrec (Ξ» n, ppred n) :=
have primrecβ (Ξ» n m, if n = nat.succ m then 0 else 1),
from (primrec.ite
(@@primrec_rel.comp _ _ _ _ _ _ _ primrec.eq
primrec.fst
(_root_.primrec.succ.comp primrec.snd))
(_root_.primrec.const 0) (_root_.primrec.const 1)).toβ,
(of_primrec (primrecβ.unpaired'.2 this)).rfind.of_eq $
Ξ» n, begin
cases n; simp,
{ exact eq_none_iff.2 (Ξ» a β¨β¨m, h, _β©, _β©,
by simpa [show 0 β m.succ, by intro h; injection h] using h) },
{ refine eq_some_iff.2 _,
simp, intros m h, simp [ne_of_gt h] }
end
end partrec
end nat
def partrec {Ξ± Ο} [primcodable Ξ±] [primcodable Ο]
(f : Ξ± β. Ο) := nat.partrec (Ξ» n,
roption.bind (decode Ξ± n) (Ξ» a, (f a).map encode))
def partrecβ {Ξ± Ξ² Ο} [primcodable Ξ±] [primcodable Ξ²] [primcodable Ο]
(f : Ξ± β Ξ² β. Ο) := partrec (Ξ» p : Ξ± Γ Ξ², f p.1 p.2)
def computable {Ξ± Ο} [primcodable Ξ±] [primcodable Ο] (f : Ξ± β Ο) := partrec (f : Ξ± β. Ο)
def computableβ {Ξ± Ξ² Ο} [primcodable Ξ±] [primcodable Ξ²] [primcodable Ο]
(f : Ξ± β Ξ² β Ο) := computable (Ξ» p : Ξ± Γ Ξ², f p.1 p.2)
theorem primrec.to_comp {Ξ± Ο} [primcodable Ξ±] [primcodable Ο]
{f : Ξ± β Ο} (hf : primrec f) : computable f :=
(nat.partrec.ppred.comp (nat.partrec.of_primrec hf)).of_eq $
Ξ» n, by simp; cases decode Ξ± n; simp
theorem primrecβ.to_comp {Ξ± Ξ² Ο} [primcodable Ξ±] [primcodable Ξ²] [primcodable Ο]
{f : Ξ± β Ξ² β Ο} (hf : primrecβ f) : computableβ f := hf.to_comp
theorem computable.part {Ξ± Ο} [primcodable Ξ±] [primcodable Ο]
{f : Ξ± β Ο} (hf : computable f) : partrec (f : Ξ± β. Ο) := hf
theorem computableβ.part {Ξ± Ξ² Ο} [primcodable Ξ±] [primcodable Ξ²] [primcodable Ο]
{f : Ξ± β Ξ² β Ο} (hf : computableβ f) : partrecβ (Ξ» a, (f a : Ξ² β. Ο)) := hf
namespace computable
variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ο : Type*}
variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Ο]
theorem of_eq {f g : Ξ± β Ο} (hf : computable f) (H : β n, f n = g n) : computable g :=
(funext H : f = g) βΈ hf
theorem const (s : Ο) : computable (Ξ» a : Ξ±, s) :=
(primrec.const _).to_comp
theorem of_option {f : Ξ± β option Ξ²}
(hf : computable f) : partrec (Ξ» a, (f a : roption Ξ²)) :=
(nat.partrec.ppred.comp hf).of_eq $ Ξ» n, begin
cases decode Ξ± n with a; simp,
cases f a with b; simp
end
theorem toβ {f : Ξ± Γ Ξ² β Ο} (hf : computable f) : computableβ (Ξ» a b, f (a, b)) :=
hf.of_eq $ Ξ» β¨a, bβ©, rfl
protected theorem id : computable (@id Ξ±) := primrec.id.to_comp
theorem fst : computable (@prod.fst Ξ± Ξ²) := primrec.fst.to_comp
theorem snd : computable (@prod.snd Ξ± Ξ²) := primrec.snd.to_comp
theorem pair {f : Ξ± β Ξ²} {g : Ξ± β Ξ³}
(hf : computable f) (hg : computable g) : computable (Ξ» a, (f a, g a)) :=
(hf.pair hg).of_eq $
Ξ» n, by cases decode Ξ± n; simp [(<*>)]
theorem unpair : computable nat.unpair := primrec.unpair.to_comp
theorem succ : computable nat.succ := primrec.succ.to_comp
theorem pred : computable nat.pred := primrec.pred.to_comp
theorem nat_bodd : computable nat.bodd := primrec.nat_bodd.to_comp
theorem nat_div2 : computable nat.div2 := primrec.nat_div2.to_comp
theorem sum_inl : computable (@sum.inl Ξ± Ξ²) := primrec.sum_inl.to_comp
theorem sum_inr : computable (@sum.inr Ξ± Ξ²) := primrec.sum_inr.to_comp
theorem list_cons : computableβ (@list.cons Ξ±) := primrec.list_cons.to_comp
theorem list_reverse : computable (@list.reverse Ξ±) := primrec.list_reverse.to_comp
theorem list_nth : computableβ (@list.nth Ξ±) := primrec.list_nth.to_comp
theorem list_append : computableβ ((++) : list Ξ± β list Ξ± β list Ξ±) := primrec.list_append.to_comp
theorem list_concat : computableβ (Ξ» l (a:Ξ±), l ++ [a]) := primrec.list_concat.to_comp
theorem list_length : computable (@list.length Ξ±) := primrec.list_length.to_comp
theorem vector_cons {n} : computableβ (@vector.cons Ξ± n) := primrec.vector_cons.to_comp
theorem vector_to_list {n} : computable (@vector.to_list Ξ± n) := primrec.vector_to_list.to_comp
theorem vector_length {n} : computable (@vector.length Ξ± n) := primrec.vector_length.to_comp
theorem vector_head {n} : computable (@vector.head Ξ± n) := primrec.vector_head.to_comp
theorem vector_tail {n} : computable (@vector.tail Ξ± n) := primrec.vector_tail.to_comp
theorem vector_nth {n} : computableβ (@vector.nth Ξ± n) := primrec.vector_nth.to_comp
theorem vector_nth' {n} : computable (@vector.nth Ξ± n) := primrec.vector_nth'.to_comp
theorem vector_of_fn' {n} : computable (@vector.of_fn Ξ± n) := primrec.vector_of_fn'.to_comp
theorem fin_app {n} : computableβ (@id (fin n β Ο)) := primrec.fin_app.to_comp
protected theorem encode : computable (@encode Ξ± _) :=
primrec.encode.to_comp
protected theorem decode : computable (decode Ξ±) :=
primrec.decode.to_comp
protected theorem of_nat (Ξ±) [denumerable Ξ±] : computable (of_nat Ξ±) :=
(primrec.of_nat _).to_comp
theorem encode_iff {f : Ξ± β Ο} : computable (Ξ» a, encode (f a)) β computable f :=
iff.rfl
theorem option_some : computable (@option.some Ξ±) :=
primrec.option_some.to_comp
end computable
namespace partrec
variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ο : Type*}
variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Ο]
open computable
theorem of_eq {f g : Ξ± β. Ο} (hf : partrec f) (H : β n, f n = g n) : partrec g :=
(funext H : f = g) βΈ hf
theorem of_eq_tot {f : Ξ± β. Ο} {g : Ξ± β Ο}
(hf : partrec f) (H : β n, g n β f n) : computable g :=
hf.of_eq (Ξ» a, eq_some_iff.2 (H a))
theorem none : partrec (Ξ» a : Ξ±, @roption.none Ο) :=
nat.partrec.none.of_eq $ Ξ» n, by cases decode Ξ± n; simp
protected theorem some : partrec (@roption.some Ξ±) := computable.id
theorem const' (s : roption Ο) : partrec (Ξ» a : Ξ±, s) :=
by haveI := classical.dec s.dom; exact
(of_option (const (to_option s))).of_eq (Ξ» a, of_to_option s)
protected theorem bind {f : Ξ± β. Ξ²} {g : Ξ± β Ξ² β. Ο}
(hf : partrec f) (hg : partrecβ g) : partrec (Ξ» a, (f a).bind (g a)) :=
(hg.comp (nat.partrec.some.pair hf)).of_eq $
Ξ» n, by simp [(<*>)]; cases e : decode Ξ± n with a;
simp [e, encodek]
theorem map {f : Ξ± β. Ξ²} {g : Ξ± β Ξ² β Ο}
(hf : partrec f) (hg : computableβ g) : partrec (Ξ» a, (f a).map (g a)) :=
by simpa [bind_some_eq_map] using
@@partrec.bind _ _ _ (Ξ» a b, roption.some (g a b)) hf hg
theorem toβ {f : Ξ± Γ Ξ² β. Ο} (hf : partrec f) : partrecβ (Ξ» a b, f (a, b)) :=
hf.of_eq $ Ξ» β¨a, bβ©, rfl
theorem nat_elim
{f : Ξ± β β} {g : Ξ± β. Ο} {h : Ξ± β β Γ Ο β. Ο}
(hf : computable f) (hg : partrec g) (hh : partrecβ h) :
partrec (Ξ» a, (f a).elim (g a) (Ξ» y IH, IH.bind (Ξ» i, h a (y, i)))) :=
(nat.partrec.prec' hf hg hh).of_eq $ Ξ» n, begin
cases e : decode Ξ± n with a; simp [e],
induction f a with m IH; simp,
rw [IH, bind_map],
congr, funext s,
simp [encodek]
end
theorem comp {f : Ξ² β. Ο} {g : Ξ± β Ξ²}
(hf : partrec f) (hg : computable g) : partrec (Ξ» a, f (g a)) :=
(hf.comp hg).of_eq $
Ξ» n, by simp; cases e : decode Ξ± n with a;
simp [e, encodek]
theorem nat_iff {f : β β. β} : partrec f β nat.partrec f :=
by simp [partrec, map_id']
theorem map_encode_iff {f : Ξ± β. Ο} : partrec (Ξ» a, (f a).map encode) β partrec f :=
iff.rfl
end partrec
namespace partrecβ
variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ξ΄ : Type*} {Ο : Type*}
variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Ξ΄] [primcodable Ο]
theorem unpaired {f : β β β β. Ξ±} : partrec (nat.unpaired f) β partrecβ f :=
β¨Ξ» h, by simpa using h.comp primrecβ.mkpair.to_comp,
Ξ» h, h.comp primrec.unpair.to_compβ©
theorem unpaired' {f : β β β β. β} : nat.partrec (nat.unpaired f) β partrecβ f :=
partrec.nat_iff.symm.trans unpaired
theorem comp
{f : Ξ² β Ξ³ β. Ο} {g : Ξ± β Ξ²} {h : Ξ± β Ξ³}
(hf : partrecβ f) (hg : computable g) (hh : computable h) :
partrec (Ξ» a, f (g a) (h a)) := hf.comp (hg.pair hh)
theorem compβ
{f : Ξ³ β Ξ΄ β. Ο} {g : Ξ± β Ξ² β Ξ³} {h : Ξ± β Ξ² β Ξ΄}
(hf : partrecβ f) (hg : computableβ g) (hh : computableβ h) :
partrecβ (Ξ» a b, f (g a b) (h a b)) := hf.comp hg hh
end partrecβ
namespace computable
variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ο : Type*}
variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Ο]
theorem comp {f : Ξ² β Ο} {g : Ξ± β Ξ²}
(hf : computable f) (hg : computable g) :
computable (Ξ» a, f (g a)) := hf.comp hg
theorem compβ {f : Ξ³ β Ο} {g : Ξ± β Ξ² β Ξ³}
(hf : computable f) (hg : computableβ g) :
computableβ (Ξ» a b, f (g a b)) := hf.comp hg
end computable
namespace computableβ
variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ξ΄ : Type*} {Ο : Type*}
variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Ξ΄] [primcodable Ο]
theorem comp
{f : Ξ² β Ξ³ β Ο} {g : Ξ± β Ξ²} {h : Ξ± β Ξ³}
(hf : computableβ f) (hg : computable g) (hh : computable h) :
computable (Ξ» a, f (g a) (h a)) := hf.comp (hg.pair hh)
theorem compβ
{f : Ξ³ β Ξ΄ β Ο} {g : Ξ± β Ξ² β Ξ³} {h : Ξ± β Ξ² β Ξ΄}
(hf : computableβ f) (hg : computableβ g) (hh : computableβ h) :
computableβ (Ξ» a b, f (g a b) (h a b)) := hf.comp hg hh
end computableβ
namespace partrec
variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ο : Type*}
variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Ο]
open computable
theorem rfind {p : Ξ± β β β. bool} (hp : partrecβ p) :
partrec (Ξ» a, nat.rfind (p a)) :=
(nat.partrec.rfind $ hp.map
((primrec.dom_bool (Ξ» b, cond b 0 1))
.comp primrec.snd).toβ.to_comp).of_eq $
Ξ» n, begin
cases e : decode Ξ± n with a;
simp [e, nat.rfind_zero_none, map_id'],
congr, funext n,
simp [roption.map_map, (β)],
apply map_id' (Ξ» b, _),
cases b; refl
end
theorem rfind_opt {f : Ξ± β β β option Ο} (hf : computableβ f) :
partrec (Ξ» a, nat.rfind_opt (f a)) :=
(rfind (primrec.option_is_some.to_comp.comp hf).part.toβ).bind
(of_option hf)
theorem nat_cases_right
{f : Ξ± β β} {g : Ξ± β Ο} {h : Ξ± β β β. Ο}
(hf : computable f) (hg : computable g) (hh : partrecβ h) :
partrec (Ξ» a, (f a).cases (some (g a)) (h a)) :=
(nat_elim hf hg (hh.comp fst (pred.comp $ hf.comp fst)).toβ).of_eq $
Ξ» a, begin
simp, cases f a; simp,
refine ext (Ξ» b, β¨Ξ» H, _, Ξ» H, _β©),
{ rcases mem_bind_iff.1 H with β¨c, hβ, hββ©, exact hβ },
{ have : β m, (nat.elim (roption.some (g a))
(Ξ» y IH, IH.bind (Ξ» _, h a n)) m).dom,
{ intro, induction m; simp [*, H.fst] },
exact β¨β¨this n, H.fstβ©, H.sndβ© }
end
theorem bind_decode2_iff {f : Ξ± β. Ο} : partrec f β
nat.partrec (Ξ» n, roption.bind (decode2 Ξ± n) (Ξ» a, (f a).map encode)) :=
β¨Ξ» hf, nat_iff.1 $ (of_option primrec.decode2.to_comp).bind $
(map hf (computable.encode.comp snd).toβ).comp snd,
Ξ» h, map_encode_iff.1 $ by simpa [encodek2]
using (nat_iff.2 h).comp (@computable.encode Ξ± _)β©
theorem vector_m_of_fn : β {n} {f : fin n β Ξ± β. Ο}, (β i, partrec (f i)) β
partrec (Ξ» (a : Ξ±), vector.m_of_fn (Ξ» i, f i a))
| 0 f hf := const _
| (n+1) f hf := by simp [vector.m_of_fn]; exact
(hf 0).bind (partrec.bind ((vector_m_of_fn (Ξ» i, hf i.succ)).comp fst)
(primrec.vector_cons.to_comp.comp (snd.comp fst) snd))
end partrec
@[simp] theorem vector.m_of_fn_roption_some {Ξ± n} : β (f : fin n β Ξ±),
vector.m_of_fn (Ξ» i, roption.some (f i)) = roption.some (vector.of_fn f) :=
vector.m_of_fn_pure
namespace computable
variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ο : Type*}
variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Ο]
theorem option_some_iff {f : Ξ± β Ο} : computable (Ξ» a, some (f a)) β computable f :=
β¨Ξ» h, encode_iff.1 $ primrec.pred.to_comp.comp $ encode_iff.2 h,
option_some.compβ©
theorem bind_decode_iff {f : Ξ± β Ξ² β option Ο} : computableβ (Ξ» a n,
(decode Ξ² n).bind (f a)) β computableβ f :=
β¨Ξ» hf, nat.partrec.of_eq
(((partrec.nat_iff.2 (nat.partrec.ppred.comp $
nat.partrec.of_primrec $ primcodable.prim Ξ²)).comp snd).bind
(computable.comp hf fst).toβ.part) $
Ξ» n, by simp;
cases decode Ξ± n.unpair.1; simp;
cases decode Ξ² n.unpair.2; simp,
Ξ» hf, begin
have : partrec (Ξ» a : Ξ± Γ β, (encode (decode Ξ² a.2)).cases
(some option.none) (Ξ» n, roption.map (f a.1) (decode Ξ² n))) :=
partrec.nat_cases_right (primrec.encdec.to_comp.comp snd)
(const none) ((of_option (computable.decode.comp snd)).map
(hf.comp (fst.comp $ fst.comp fst) snd).toβ),
refine this.of_eq (Ξ» a, _),
simp, cases decode Ξ² a.2; simp [encodek]
endβ©
theorem map_decode_iff {f : Ξ± β Ξ² β Ο} : computableβ (Ξ» a n,
(decode Ξ² n).map (f a)) β computableβ f :=
bind_decode_iff.trans option_some_iff
theorem nat_elim
{f : Ξ± β β} {g : Ξ± β Ο} {h : Ξ± β β Γ Ο β Ο}
(hf : computable f) (hg : computable g) (hh : computableβ h) :
computable (Ξ» a, (f a).elim (g a) (Ξ» y IH, h a (y, IH))) :=
(partrec.nat_elim hf hg hh.part).of_eq $
Ξ» a, by simp; induction f a; simp *
theorem nat_cases {f : Ξ± β β} {g : Ξ± β Ο} {h : Ξ± β β β Ο}
(hf : computable f) (hg : computable g) (hh : computableβ h) :
computable (Ξ» a, (f a).cases (g a) (h a)) :=
nat_elim hf hg (hh.comp fst $ fst.comp snd).toβ
theorem cond {c : Ξ± β bool} {f : Ξ± β Ο} {g : Ξ± β Ο}
(hc : computable c) (hf : computable f) (hg : computable g) :
computable (Ξ» a, cond (c a) (f a) (g a)) :=
(nat_cases (encode_iff.2 hc) hg (hf.comp fst).toβ).of_eq $
Ξ» a, by cases c a; refl
theorem option_cases {o : Ξ± β option Ξ²} {f : Ξ± β Ο} {g : Ξ± β Ξ² β Ο}
(ho : computable o) (hf : computable f) (hg : computableβ g) :
@computable _ Ο _ _ (Ξ» a, option.cases_on (o a) (f a) (g a)) :=
option_some_iff.1 $
(nat_cases (encode_iff.2 ho) (option_some_iff.2 hf)
(map_decode_iff.2 hg)).of_eq $
Ξ» a, by cases o a; simp [encodek]; refl
theorem option_bind {f : Ξ± β option Ξ²} {g : Ξ± β Ξ² β option Ο}
(hf : computable f) (hg : computableβ g) :
computable (Ξ» a, (f a).bind (g a)) :=
(option_cases hf (const option.none) hg).of_eq $
Ξ» a, by cases f a; refl
theorem option_map {f : Ξ± β option Ξ²} {g : Ξ± β Ξ² β Ο}
(hf : computable f) (hg : computableβ g) : computable (Ξ» a, (f a).map (g a)) :=
option_bind hf (option_some.compβ hg)
theorem sum_cases
{f : Ξ± β Ξ² β Ξ³} {g : Ξ± β Ξ² β Ο} {h : Ξ± β Ξ³ β Ο}
(hf : computable f) (hg : computableβ g) (hh : computableβ h) :
@computable _ Ο _ _ (Ξ» a, sum.cases_on (f a) (g a) (h a)) :=
option_some_iff.1 $
(cond (nat_bodd.comp $ encode_iff.2 hf)
(option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh)
(option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $
Ξ» a, by cases f a with b c;
simp [nat.div2_bit, nat.bodd_bit, encodek]; refl
theorem nat_strong_rec
(f : Ξ± β β β Ο) {g : Ξ± β list Ο β option Ο} (hg : computableβ g)
(H : β a n, g a ((list.range n).map (f a)) = some (f a n)) : computableβ f :=
suffices computableβ (Ξ» a n, (list.range n).map (f a)), from
option_some_iff.1 $
(list_nth.comp (this.comp fst (succ.comp snd)) snd).toβ.of_eq $
Ξ» a, by simp [list.nth_range (nat.lt_succ_self a.2)]; refl,
option_some_iff.1 $
(nat_elim snd (const (option.some [])) (toβ $
option_bind (snd.comp snd) $ toβ $
option_map
(hg.comp (fst.comp $ fst.comp fst) snd)
(toβ $ list_concat.comp (snd.comp fst) snd))).of_eq $
Ξ» a, begin
simp, induction a.2 with n IH, {refl},
simp [IH, H, list.range_concat]
end
theorem list_of_fn : β {n} {f : fin n β Ξ± β Ο},
(β i, computable (f i)) β computable (Ξ» a, list.of_fn (Ξ» i, f i a))
| 0 f hf := const []
| (n+1) f hf := by simp [list.of_fn_succ]; exact
list_cons.comp (hf 0) (list_of_fn (Ξ» i, hf i.succ))
theorem vector_of_fn {n} {f : fin n β Ξ± β Ο}
(hf : β i, computable (f i)) : computable (Ξ» a, vector.of_fn (Ξ» i, f i a)) :=
(partrec.vector_m_of_fn hf).of_eq $ Ξ» a, by simp
end computable
namespace partrec
variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ο : Type*}
variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Ο]
open computable
theorem option_some_iff {f : Ξ± β. Ο} :
partrec (Ξ» a, (f a).map option.some) β partrec f :=
β¨Ξ» h, (nat.partrec.ppred.comp h).of_eq $
Ξ» n, by simp [roption.bind_assoc, bind_some_eq_map],
Ξ» hf, hf.map (option_some.comp snd).toββ©
theorem option_cases_right {o : Ξ± β option Ξ²} {f : Ξ± β Ο} {g : Ξ± β Ξ² β. Ο}
(ho : computable o) (hf : computable f) (hg : partrecβ g) :
@partrec _ Ο _ _ (Ξ» a, option.cases_on (o a) (some (f a)) (g a)) :=
have partrec (Ξ» (a : Ξ±), nat.cases (roption.some (f a))
(Ξ» n, roption.bind (decode Ξ² n) (g a)) (encode (o a))) :=
nat_cases_right (encode_iff.2 ho) hf.part $
((@computable.decode Ξ² _).comp snd).of_option.bind
(hg.comp (fst.comp fst) snd).toβ,
this.of_eq $ Ξ» a, by cases o a with b; simp [encodek]
theorem sum_cases_right
{f : Ξ± β Ξ² β Ξ³} {g : Ξ± β Ξ² β Ο} {h : Ξ± β Ξ³ β. Ο}
(hf : computable f) (hg : computableβ g) (hh : partrecβ h) :
@partrec _ Ο _ _ (Ξ» a, sum.cases_on (f a) (Ξ» b, some (g a b)) (h a)) :=
have partrec (Ξ» a, (option.cases_on
(sum.cases_on (f a) (Ξ» b, option.none) option.some : option Ξ³)
(some (sum.cases_on (f a) (Ξ» b, some (g a b))
(Ξ» c, option.none)))
(Ξ» c, (h a c).map option.some) : roption (option Ο))) :=
option_cases_right
(sum_cases hf (const option.none).toβ (option_some.comp snd).toβ)
(sum_cases hf (option_some.comp hg) (const option.none).toβ)
(option_some_iff.2 hh),
option_some_iff.1 $ this.of_eq $ Ξ» a, by cases f a; simp
theorem sum_cases_left
{f : Ξ± β Ξ² β Ξ³} {g : Ξ± β Ξ² β. Ο} {h : Ξ± β Ξ³ β Ο}
(hf : computable f) (hg : partrecβ g) (hh : computableβ h) :
@partrec _ Ο _ _ (Ξ» a, sum.cases_on (f a) (g a) (Ξ» c, some (h a c))) :=
(sum_cases_right (sum_cases hf
(sum_inr.comp snd).toβ (sum_inl.comp snd).toβ) hh hg).of_eq $
Ξ» a, by cases f a; simp
private lemma fix_aux
{f : Ξ± β. Ο β Ξ±} (hf : partrec f)
(a : Ξ±) (b : Ο) :
let F : Ξ± β β β. Ο β Ξ± := Ξ» a n,
n.elim (some (sum.inr a)) $ Ξ» y IH, IH.bind $ Ξ» s,
sum.cases_on s (Ξ» _, roption.some s) f in
(β (n : β), ((β (b' : Ο), sum.inl b' β F a n) β§
β {m : β}, m < n β (β (b : Ξ±), sum.inr b β F a m)) β§
sum.inl b β F a n) β b β pfun.fix f a :=
begin
intro, refine β¨Ξ» h, _, Ξ» h, _β©,
{ rcases h with β¨n, β¨_x, hββ©, hββ©,
have : β m a' (_: sum.inr a' β F a m)
(_: b β pfun.fix f a'), b β pfun.fix f a,
{ intros m a' am ba,
induction m with m IH generalizing a'; simp [F] at am,
{ rwa β am },
rcases am with β¨aβ, amβ, faββ©,
exact IH _ amβ (pfun.mem_fix_iff.2 (or.inr β¨_, faβ, baβ©)) },
cases n; simp [F] at hβ, {cases hβ},
rcases hβ with hβ | β¨a', am', fa'β©,
{ cases hβ (nat.lt_succ_self _) with a' h,
injection mem_unique h hβ },
{ exact this _ _ am' (pfun.mem_fix_iff.2 (or.inl fa')) } },
{ suffices : β a' (_: b β pfun.fix f a') k (_: sum.inr a' β F a k),
β n, sum.inl b β F a n β§
β (m < n) (_ : k β€ m), β aβ, sum.inr aβ β F a m,
{ rcases this _ h 0 (by simp [F]) with β¨n, hnβ, hnββ©,
exact β¨_, β¨β¨_, hnββ©, Ξ» m mn, hnβ m mn (nat.zero_le _)β©, hnββ© },
intros aβ hβ,
apply pfun.fix_induction hβ, intros aβ hβ IH k hk,
rcases pfun.mem_fix_iff.1 hβ with hβ | β¨aβ, amβ, faββ©,
{ refine β¨k.succ, _, Ξ» m mk km, β¨aβ, _β©β©,
{ simp [F], exact or.inr β¨_, hk, hββ© },
{ rwa le_antisymm (nat.le_of_lt_succ mk) km } },
{ rcases IH _ faβ amβ k.succ _ with β¨n, hnβ, hnββ©,
{ refine β¨n, hnβ, Ξ» m mn km, _β©,
cases lt_or_eq_of_le km with km km,
{ exact hnβ _ mn km },
{ exact km βΈ β¨_, hkβ© } },
{ simp [F], exact β¨_, hk, amββ© } } }
end
theorem fix
{f : Ξ± β. Ο β Ξ±} (hf : partrec f) : partrec (pfun.fix f) :=
let F : Ξ± β β β. Ο β Ξ± := Ξ» a n,
n.elim (some (sum.inr a)) $ Ξ» y IH, IH.bind $ Ξ» s,
sum.cases_on s (Ξ» _, roption.some s) f in
have hF : partrecβ F :=
partrec.nat_elim snd (sum_inr.comp fst).part
(sum_cases_right (snd.comp snd)
(snd.comp $ snd.comp fst).toβ
(hf.comp snd).toβ).toβ,
let p := Ξ» a n, @roption.map _ bool
(Ξ» s, sum.cases_on s (Ξ»_, tt) (Ξ» _, ff)) (F a n) in
have hp : partrecβ p := hF.map ((sum_cases computable.id
(const tt).toβ (const ff).toβ).comp snd).toβ,
(hp.rfind.bind (hF.bind
(sum_cases_right snd snd.toβ none.toβ).toβ).toβ).of_eq $
Ξ» a, ext $ Ξ» b, by simp; apply fix_aux hf
end partrec
|
84071c8bd303046b5f20a8db6250f611d794d343 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/nat/cast/prod.lean | 4c218abee4acdb9b4e4afb6fa9bdf36c7683e500 | [
"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 | 813 | lean | /-
Copyright (c) 2014 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.nat.cast.basic
import algebra.group.prod
/-!
# The product of two `add_monoid_with_one`s.
-/
variables {Ξ± Ξ² : Type*}
namespace prod
variables [add_monoid_with_one Ξ±] [add_monoid_with_one Ξ²]
instance : add_monoid_with_one (Ξ± Γ Ξ²) :=
{ nat_cast := Ξ» n, (n, n),
nat_cast_zero := congr_arg2 prod.mk nat.cast_zero nat.cast_zero,
nat_cast_succ := Ξ» n, congr_arg2 prod.mk (nat.cast_succ _) (nat.cast_succ _),
.. prod.add_monoid, .. prod.has_one }
@[simp] lemma fst_nat_cast (n : β) : (n : Ξ± Γ Ξ²).fst = n :=
by induction n; simp *
@[simp] lemma snd_nat_cast (n : β) : (n : Ξ± Γ Ξ²).snd = n :=
by induction n; simp *
end prod
|
e1b7a3a6e7b79a9e0093c8f001381231d8ba0d0f | 76df16d6c3760cb415f1294caee997cc4736e09b | /lean/src/generation/printer.lean | 9836160a2f693d57b1b801230a5f4db5bbd38647 | [
"MIT"
] | permissive | uw-unsat/leanette-popl22-artifact | 70409d9cbd8921d794d27b7992bf1d9a4087e9fe | 80fea2519e61b45a283fbf7903acdf6d5528dbe7 | refs/heads/master | 1,681,592,449,670 | 1,637,037,431,000 | 1,637,037,431,000 | 414,331,908 | 6 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 4,603 | lean | import ..op.sym
open op.sym
def vars.to_str : list β β string
| [] := ""
| (x :: xs) := " " ++ to_string x ++ vars.to_str xs
def op.sym.typedop_int.to_str : typedop type.int β string
| typedop.add := "add"
| typedop.mul := "mul"
def op.sym.typedop_bool.to_str : typedop type.bool β string
| typedop.lt := "lt"
| typedop.eq := "eq"
def op.lang.op.to_str : op.lang.op β string
| (op.lang.op.int_2 op.lang.op_int_2.add) := "+"
| (op.lang.op.int_2 op.lang.op_int_2.mul) := "*"
| (op.lang.op.int_2 op.lang.op_int_2.lt) := "<"
| (op.lang.op.int_2 op.lang.op_int_2.eq) := "="
| (op.lang.op.list_proj op.lang.op_list_proj.first) := "first"
| (op.lang.op.list_proj op.lang.op_list_proj.rest) := "rest"
| op.lang.op.list_null := "make-null"
| op.lang.op.list_cons := "link"
| op.lang.op.list_is_null := "null?"
def op.lang.exp.to_str : op.lang.exp β string
| (lang.exp.let0 x e_v e_b) :=
"(let0 " ++ to_string x ++ " " ++
op.lang.exp.to_str e_v ++ " " ++ op.lang.exp.to_str e_b ++ ")"
| (lang.exp.datum (op.lang.datum.int z)) := "(datum (op.lang.datum.int " ++ to_string z ++ "))"
| (lang.exp.datum op.lang.datum.undef) := "undef"
| (lang.exp.app o xs) := "(app " ++ o.to_str ++ vars.to_str xs ++ ")"
| (lang.exp.call x y) := "(call " ++ to_string x ++ " " ++ to_string y ++ ")"
| (lang.exp.var x) := "(var " ++ to_string x ++ ")"
| (lang.exp.if0 x e_t e_e) :=
"(if0 " ++ to_string x ++ " " ++
op.lang.exp.to_str e_t ++ " " ++
op.lang.exp.to_str e_e ++ ")"
| (lang.exp.bool tt) := "#t"
| (lang.exp.bool ff) := "#f"
| (lang.exp.lam x e_b) := "(Ξ» " ++ to_string x ++ " " ++ op.lang.exp.to_str e_b ++ ")"
| lang.exp.error := "(make-error)"
| lang.exp.abort := "(make-abort)"
mutual def op.sym.term_int.to_str, op.sym.term_bool.to_str
with op.sym.term_int.to_str : term type.int β string
| (term.lit (lit.int z)) := to_string z
| (term.var (@var.mk type.int x)) := "(var " ++ to_string x ++ ")"
| (term.ite c t e) :=
"(ite " ++ op.sym.term_bool.to_str c ++ " " ++
op.sym.term_int.to_str t ++ " " ++
op.sym.term_int.to_str e ++ ")"
| (term.expr o l r) :=
"(expr " ++ op.sym.typedop_int.to_str o ++ " " ++
op.sym.term_int.to_str l ++ " " ++
op.sym.term_int.to_str r ++ ")"
with op.sym.term_bool.to_str : term type.bool β string
| (term.lit (lit.bool tt)) := "#t"
| (term.lit (lit.bool ff)) := "#f"
| (term.var (@var.mk type.bool x)) := "(var " ++ to_string x ++ ")"
| (term.ite c t e) :=
"(ite " ++ op.sym.term_bool.to_str c ++ " " ++
op.sym.term_bool.to_str t ++ " " ++
op.sym.term_bool.to_str e ++ ")"
| (term.expr o l r) :=
"(expr " ++ op.sym.typedop_bool.to_str o ++ " " ++
op.sym.term_int.to_str l ++ " " ++
op.sym.term_int.to_str r ++ ")"
mutual def op.sym.val_atom.to_str, op.sym.val.to_str, op.sym.vals.to_str, op.sym.vals.to_str_aux, op.sym.choices'.to_str
with op.sym.val_atom.to_str : val_atom β string
| (op.sym.val_atom.list vs) := op.sym.vals.to_str vs
| (@op.sym.val_atom.term type.int t) := "(term_int " ++ op.sym.term_int.to_str t ++ ")"
| (@op.sym.val_atom.term type.bool t) := "(term_bool " ++ op.sym.term_bool.to_str t ++ ")"
| (op.sym.val_atom.clos x e_b Ξ΅) := "(clos " ++ to_string x ++ " " ++ e_b.to_str ++ " " ++ op.sym.vals.to_str Ξ΅ ++ ")"
with op.sym.val.to_str : val β string
| (op.sym.val.atom a) := a.to_str
| (op.sym.val.union gvs) := "(union" ++ gvs.to_str ++ ")"
with op.sym.vals.to_str : list val β string
-- we really need only one case, but the well-foundedness for mutual recursion
-- is stupid, so let's unroll one more iteration
| [] := "(list)"
| (v :: vs) := "(list " ++ op.sym.val.to_str v ++ op.sym.vals.to_str_aux vs ++ ")"
with op.sym.vals.to_str_aux : list val β string
| [] := ""
| (v :: vs) := " " ++ op.sym.val.to_str v ++ op.sym.vals.to_str_aux vs
with op.sym.choices'.to_str : choices' val_atom β string
| [] := ""
| (β¨g, vaβ© :: xs) := " (choice " ++ op.sym.term_bool.to_str g ++ " " ++
op.sym.val_atom.to_str va ++ ")" ++
op.sym.choices'.to_str xs
def sym.state.to_str : sym.state (term type.bool) β string
| β¨assumes, assertsβ© := "(state " ++ op.sym.term_bool.to_str assumes ++ " " ++
op.sym.term_bool.to_str asserts ++ ")"
def result.to_str : option op.sym.result β string
| none := "none"
| (some (sym.result.ans Ο v)) := "(ans " ++ Ο.to_str ++ " " ++ v.to_str ++ ")"
| (some (sym.result.halt Ο)) := "(halt " ++ Ο.to_str ++ ")"
|
f990027ccd68068af7d2dc8366a426baa35aaca2 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/ring_theory/integral_closure.lean | 873207d98da7ffe7961f44f82e239225b9d56cf9 | [
"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 | 21,482 | lean | /-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import ring_theory.algebra_tower
import ring_theory.polynomial.scale_roots
/-!
# Integral closure of a subring.
If A is an R-algebra then `a : A` is integral over R if it is a root of a monic polynomial
with coefficients in R. Enough theory is developed to prove that integral elements
form a sub-R-algebra of A.
## Main definitions
Let `R` be a `comm_ring` and let `A` be an R-algebra.
* `ring_hom.is_integral_elem (f : R β+* A) (x : A)` : `x` is integral with respect to the map `f`,
* `is_integral (x : A)` : `x` is integral over `R`, i.e., is a root of a monic polynomial with
coefficients in `R`.
* `integral_closure R A` : the integral closure of `R` in `A`, regarded as a sub-`R`-algebra of `A`.
-/
open_locale classical
open_locale big_operators
open polynomial submodule
section ring
variables {R A : Type*}
variables [comm_ring R] [ring A]
/-- An element `x` of `A` is said to be integral over `R` with respect to `f`
if it is a root of a monic polynomial `p : polynomial R` evaluated under `f` -/
def ring_hom.is_integral_elem (f : R β+* A) (x : A) :=
β p : polynomial R, monic p β§ evalβ f x p = 0
/-- A ring homomorphism `f : R β+* A` is said to be integral
if every element `A` is integral with respect to the map `f` -/
def ring_hom.is_integral (f : R β+* A) :=
β x : A, f.is_integral_elem x
variables [algebra R A] (R)
/-- An element `x` of an algebra `A` over a commutative ring `R` is said to be *integral*,
if it is a root of some monic polynomial `p : polynomial R`.
Equivalently, the element is integral over `R` with respect to the induced `algebra_map` -/
def is_integral (x : A) : Prop :=
(algebra_map R A).is_integral_elem x
variable (A)
/-- An algebra is integral if every element of the extension is integral over the base ring -/
def algebra.is_integral : Prop :=
(algebra_map R A).is_integral
variables {R A}
theorem is_integral_algebra_map {x : R} : is_integral R (algebra_map R A x) :=
β¨X - C x, monic_X_sub_C _,
by simpβ©
theorem is_integral_of_noetherian (H : is_noetherian R A) (x : A) :
is_integral R x :=
begin
let leval : @linear_map R (polynomial R) A _ _ _ _ _ := (aeval x).to_linear_map,
let D : β β submodule R A := Ξ» n, (degree_le R n).map leval,
let M := well_founded.min (is_noetherian_iff_well_founded.1 H)
(set.range D) β¨_, β¨0, rflβ©β©,
have HM : M β set.range D := well_founded.min_mem _ _ _,
cases HM with N HN,
have HM : Β¬M < D (N+1) := well_founded.not_lt_min
(is_noetherian_iff_well_founded.1 H) (set.range D) _ β¨N+1, rflβ©,
rw β HN at HM,
have HN2 : D (N+1) β€ D N := classical.by_contradiction (Ξ» H, HM
(lt_of_le_not_le (map_mono (degree_le_mono
(with_bot.coe_le_coe.2 (nat.le_succ N)))) H)),
have HN3 : leval (X^(N+1)) β D N,
{ exact HN2 (mem_map_of_mem (mem_degree_le.2 (degree_X_pow_le _))) },
rcases HN3 with β¨p, hdp, hpeβ©,
refine β¨X^(N+1) - p, monic_X_pow_sub (mem_degree_le.1 hdp), _β©,
show leval (X ^ (N + 1) - p) = 0,
rw [linear_map.map_sub, hpe, sub_self]
end
theorem is_integral_of_submodule_noetherian (S : subalgebra R A)
(H : is_noetherian R (S : submodule R A)) (x : A) (hx : x β S) :
is_integral R x :=
begin
letI : algebra R S := S.algebra,
letI : ring S := S.ring R A,
suffices : is_integral R (β¨x, hxβ© : S),
{ rcases this with β¨p, hpm, hpxβ©,
replace hpx := congr_arg subtype.val hpx,
refine β¨p, hpm, eq.trans _ hpxβ©,
simp only [aeval_def, evalβ, finsupp.sum],
rw β p.support.sum_hom subtype.val,
{ refine finset.sum_congr rfl (Ξ» n hn, _),
change _ = _ * _,
rw is_monoid_hom.map_pow coe, refl,
split; intros; refl },
refine { map_add := _, map_zero := _ }; intros; refl },
refine is_integral_of_noetherian H β¨x, hxβ©
end
end ring
section
variables {R : Type*} {A : Type*} {B : Type*}
variables [comm_ring R] [comm_ring A] [comm_ring B]
variables [algebra R A] [algebra R B]
theorem is_integral_alg_hom (f : A ββ[R] B) {x : A} (hx : is_integral R x) : is_integral R (f x) :=
let β¨p, hp, hpxβ© := hx in β¨p, hp, by rw [β aeval_def, aeval_alg_hom_apply, aeval_def, hpx, f.map_zero]β©
theorem is_integral_of_is_scalar_tower [algebra A B] [is_scalar_tower R A B]
(x : B) (hx : is_integral R x) : is_integral A x :=
let β¨p, hp, hpxβ© := hx in
β¨p.map $ algebra_map R A, monic_map _ hp, by rw [β aeval_def, β is_scalar_tower.aeval_apply, aeval_def, hpx]β©
theorem is_integral_of_subring {x : A} (T : set R) [is_subring T]
(hx : is_integral T x) : is_integral R x :=
is_integral_of_is_scalar_tower x hx
theorem is_integral_iff_is_integral_closure_finite {r : A} :
is_integral R r β β s : set R, s.finite β§ is_integral (ring.closure s) r :=
begin
split; intro hr,
{ rcases hr with β¨p, hmp, hprβ©,
refine β¨_, set.finite_mem_finset _, p.restriction, subtype.eq hmp, _β©,
erw [β aeval_def, is_scalar_tower.aeval_apply _ R, map_restriction, aeval_def, hpr] },
rcases hr with β¨s, hs, hsrβ©,
exact is_integral_of_subring _ hsr
end
theorem fg_adjoin_singleton_of_integral (x : A) (hx : is_integral R x) :
(algebra.adjoin R ({x} : set A) : submodule R A).fg :=
begin
rcases hx with β¨f, hfm, hfxβ©,
existsi finset.image ((^) x) (finset.range (nat_degree f + 1)),
apply le_antisymm,
{ rw span_le, intros s hs, rw finset.mem_coe at hs,
rcases finset.mem_image.1 hs with β¨k, hk, rflβ©, clear hk,
exact is_submonoid.pow_mem (algebra.subset_adjoin (set.mem_singleton _)) },
intros r hr, change r β algebra.adjoin R ({x} : set A) at hr,
rw algebra.adjoin_singleton_eq_range at hr,
rcases (aeval x).mem_range.mp hr with β¨p, rflβ©,
rw β mod_by_monic_add_div p hfm,
rw β aeval_def at hfx,
rw [alg_hom.map_add, alg_hom.map_mul, hfx, zero_mul, add_zero],
have : degree (p %β f) β€ degree f := degree_mod_by_monic_le p hfm,
generalize_hyp : p %β f = q at this β’,
rw [β sum_C_mul_X_eq q, aeval_def, evalβ_sum, finsupp.sum],
refine sum_mem _ (Ξ» k hkq, _),
rw [evalβ_mul, evalβ_C, evalβ_pow, evalβ_X, β algebra.smul_def],
refine smul_mem _ _ (subset_span _),
rw finset.mem_coe, refine finset.mem_image.2 β¨_, _, rflβ©,
rw [finset.mem_range, nat.lt_succ_iff], refine le_of_not_lt (Ξ» hk, _),
rw [degree_le_iff_coeff_zero] at this,
rw [finsupp.mem_support_iff] at hkq, apply hkq, apply this,
exact lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 hk)
end
theorem fg_adjoin_of_finite {s : set A} (hfs : s.finite)
(his : β x β s, is_integral R x) : (algebra.adjoin R s : submodule R A).fg :=
set.finite.induction_on hfs (Ξ» _, β¨{1}, submodule.ext $ Ξ» x,
by { erw [algebra.adjoin_empty, finset.coe_singleton, β one_eq_span, one_eq_map_top,
map_top, linear_map.mem_range, algebra.mem_bot], refl }β©)
(Ξ» a s has hs ih his, by rw [β set.union_singleton, algebra.adjoin_union_coe_submodule]; exact
fg_mul _ _ (ih $ Ξ» i hi, his i $ set.mem_insert_of_mem a hi)
(fg_adjoin_singleton_of_integral _ $ his a $ set.mem_insert a s)) his
theorem is_integral_of_mem_of_fg (S : subalgebra R A)
(HS : (S : submodule R A).fg) (x : A) (hx : x β S) : is_integral R x :=
begin
cases HS with y hy,
obtain β¨lx, hlx1, hlx2β© :
β (l : A ββ R) (H : l β finsupp.supported R R βy), (finsupp.total A A R id) l = x,
{ rwa [β(@finsupp.mem_span_iff_total A A R _ _ _ id βy x), set.image_id βy, hy] },
have hyS : β {p}, p β y β p β S := Ξ» p hp, show p β (S : submodule R A),
by { rw β hy, exact subset_span hp },
have : β (jk : (β(y.product y) : set (A Γ A))), jk.1.1 * jk.1.2 β (S : submodule R A) :=
Ξ» jk, S.mul_mem (hyS (finset.mem_product.1 jk.2).1) (hyS (finset.mem_product.1 jk.2).2),
rw [β hy, β set.image_id βy] at this, simp only [finsupp.mem_span_iff_total] at this,
choose ly hly1 hly2,
let Sβ : set R := ring.closure β(lx.frange βͺ finset.bind finset.univ (finsupp.frange β ly)),
refine is_integral_of_subring Sβ _,
have : span Sβ (insert 1 βy : set A) * span Sβ (insert 1 βy : set A) β€ span Sβ (insert 1 βy : set A),
{ rw span_mul_span, refine span_le.2 (Ξ» z hz, _),
rcases set.mem_mul.1 hz with β¨p, q, rfl | hp, hq, rflβ©,
{ rw one_mul, exact subset_span hq },
rcases hq with rfl | hq,
{ rw mul_one, exact subset_span (or.inr hp) },
erw β hly2 β¨(p, q), finset.mem_product.2 β¨hp, hqβ©β©,
rw [finsupp.total_apply, finsupp.sum],
refine (span Sβ (insert 1 βy : set A)).sum_mem (Ξ» t ht, _),
have : ly β¨(p, q), finset.mem_product.2 β¨hp, hqβ©β© t β Sβ :=
ring.subset_closure (finset.mem_union_right _ $ finset.mem_bind.2
β¨β¨(p, q), finset.mem_product.2 β¨hp, hqβ©β©, finset.mem_univ _,
finsupp.mem_frange.2 β¨finsupp.mem_support_iff.1 ht, _, rflβ©β©),
change (β¨_, thisβ© : Sβ) β’ t β _, exact smul_mem _ _ (subset_span $ or.inr $ hly1 _ ht) },
haveI : is_subring (span Sβ (insert 1 βy : set A) : set A) :=
{ one_mem := subset_span $ or.inl rfl,
mul_mem := Ξ» p q hp hq, this $ mul_mem_mul hp hq,
zero_mem := (span Sβ (insert 1 βy : set A)).zero_mem,
add_mem := Ξ» _ _, (span Sβ (insert 1 βy : set A)).add_mem,
neg_mem := Ξ» _, (span Sβ (insert 1 βy : set A)).neg_mem },
have : span Sβ (insert 1 βy : set A) = algebra.adjoin Sβ (βy : set A),
{ refine le_antisymm (span_le.2 $ set.insert_subset.2
β¨(algebra.adjoin Sβ βy).one_mem, algebra.subset_adjoinβ©) (Ξ» z hz, _),
rw [subalgebra.mem_to_submodule, algebra.mem_adjoin_iff] at hz, rw β submodule.mem_coe,
refine ring.closure_subset (set.union_subset (set.range_subset_iff.2 $ Ξ» t, _)
(Ξ» t ht, subset_span $ or.inr ht)) hz,
rw algebra.algebra_map_eq_smul_one,
exact smul_mem (span Sβ (insert 1 βy : set A)) _ (subset_span $ or.inl rfl) },
haveI : is_noetherian_ring β₯Sβ := is_noetherian_ring_closure _ (finset.finite_to_set _),
refine is_integral_of_submodule_noetherian (algebra.adjoin Sβ βy)
(is_noetherian_of_fg_of_noetherian _ β¨insert 1 y, by rw [finset.coe_insert, this]β©) _ _,
rw [β hlx2, finsupp.total_apply, finsupp.sum], refine subalgebra.sum_mem _ (Ξ» r hr, _),
have : lx r β Sβ := ring.subset_closure (finset.mem_union_left _ (finset.mem_image_of_mem _ hr)),
change (β¨_, thisβ© : Sβ) β’ r β _,
rw finsupp.mem_supported at hlx1,
exact subalgebra.smul_mem _ (algebra.subset_adjoin $ hlx1 hr) _
end
theorem is_integral_of_mem_closure {x y z : A}
(hx : is_integral R x) (hy : is_integral R y)
(hz : z β ring.closure ({x, y} : set A)) :
is_integral R z :=
begin
have := fg_mul _ _ (fg_adjoin_singleton_of_integral x hx) (fg_adjoin_singleton_of_integral y hy),
rw [β algebra.adjoin_union_coe_submodule, set.singleton_union] at this,
exact is_integral_of_mem_of_fg (algebra.adjoin R {x, y}) this z
(algebra.mem_adjoin_iff.2 $ ring.closure_mono (set.subset_union_right _ _) hz)
end
theorem is_integral_zero : is_integral R (0:A) :=
(algebra_map R A).map_zero βΈ is_integral_algebra_map
theorem is_integral_one : is_integral R (1:A) :=
(algebra_map R A).map_one βΈ is_integral_algebra_map
theorem is_integral_add {x y : A}
(hx : is_integral R x) (hy : is_integral R y) :
is_integral R (x + y) :=
is_integral_of_mem_closure hx hy (is_add_submonoid.add_mem
(ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl)))
theorem is_integral_neg {x : A}
(hx : is_integral R x) : is_integral R (-x) :=
is_integral_of_mem_closure hx hx (is_add_subgroup.neg_mem
(ring.subset_closure (or.inl rfl)))
theorem is_integral_sub {x y : A}
(hx : is_integral R x) (hy : is_integral R y) : is_integral R (x - y) :=
is_integral_add hx (is_integral_neg hy)
theorem is_integral_mul {x y : A}
(hx : is_integral R x) (hy : is_integral R y) :
is_integral R (x * y) :=
is_integral_of_mem_closure hx hy (is_submonoid.mul_mem
(ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl)))
variables (R A)
/-- The integral closure of R in an R-algebra A. -/
def integral_closure : subalgebra R A :=
{ carrier := { r | is_integral R r },
zero_mem' := is_integral_zero,
one_mem' := is_integral_one,
add_mem' := Ξ» _ _, is_integral_add,
mul_mem' := Ξ» _ _, is_integral_mul,
algebra_map_mem' := Ξ» x, is_integral_algebra_map }
theorem mem_integral_closure_iff_mem_fg {r : A} :
r β integral_closure R A β β M : subalgebra R A, (M : submodule R A).fg β§ r β M :=
β¨Ξ» hr, β¨algebra.adjoin R {r}, fg_adjoin_singleton_of_integral _ hr, algebra.subset_adjoin rflβ©,
Ξ» β¨M, Hf, hrMβ©, is_integral_of_mem_of_fg M Hf _ hrMβ©
variables {R} {A}
/-- Mapping an integral closure along an `alg_equiv` gives the integral closure. -/
lemma integral_closure_map_alg_equiv (f : A ββ[R] B) :
(integral_closure R A).map (f : A ββ[R] B) = integral_closure R B :=
begin
ext y,
rw subalgebra.mem_map,
split,
{ rintros β¨x, hx, rflβ©,
exact is_integral_alg_hom f hx },
{ intro hy,
use [f.symm y, is_integral_alg_hom (f.symm : B ββ[R] A) hy],
simp }
end
lemma integral_closure.is_integral (x : integral_closure R A) : is_integral R x :=
let β¨p, hpm, hpxβ© := x.2 in β¨p, hpm, subtype.eq $
by rwa [β aeval_def, subtype.val_eq_coe, β subalgebra.val_apply, aeval_alg_hom_apply] at hpxβ©
theorem is_integral_of_is_integral_mul_unit {x y : A} {r : R} (hr : algebra_map R A r * y = 1)
(hx : is_integral R (x * y)) : is_integral R x :=
begin
obtain β¨p, β¨p_monic, hpβ©β© := hx,
refine β¨scale_roots p r, β¨(monic_scale_roots_iff r).2 p_monic, _β©β©,
convert scale_roots_aeval_eq_zero hp,
rw [mul_comm x y, β mul_assoc, hr, one_mul],
end
end
section algebra
open algebra
variables {R : Type*} {A : Type*} {B : Type*}
variables [comm_ring R] [comm_ring A] [comm_ring B]
variables [algebra A B] [algebra R B]
lemma is_integral_trans_aux (x : B) {p : polynomial A} (pmonic : monic p) (hp : aeval x p = 0) :
is_integral (adjoin R (β(p.map $ algebra_map A B).frange : set B)) x :=
begin
generalize hS : (β(p.map $ algebra_map A B).frange : set B) = S,
have coeffs_mem : β i, (p.map $ algebra_map A B).coeff i β adjoin R S,
{ intro i, by_cases hi : (p.map $ algebra_map A B).coeff i = 0,
{ rw hi, exact subalgebra.zero_mem _ },
rw β hS, exact subset_adjoin (finsupp.mem_frange.2 β¨hi, i, rflβ©) },
obtain β¨q, hqβ© : β q : polynomial (adjoin R S), q.map (algebra_map (adjoin R S) B) =
(p.map $ algebra_map A B),
{ rw β set.mem_range, exact (polynomial.mem_map_range _).2 (Ξ» i, β¨β¨_, coeffs_mem iβ©, rflβ©) },
use q,
split,
{ suffices h : (q.map (algebra_map (adjoin R S) B)).monic,
{ refine monic_of_injective _ h,
exact subtype.val_injective },
{ rw hq, exact monic_map _ pmonic } },
{ convert hp using 1,
replace hq := congr_arg (eval x) hq,
convert hq using 1; symmetry; apply eval_map },
end
variables [algebra R A] [is_scalar_tower R A B]
/-- If A is an R-algebra all of whose elements are integral over R,
and x is an element of an A-algebra that is integral over A, then x is integral over R.-/
lemma is_integral_trans (A_int : is_integral R A) (x : B) (hx : is_integral A x) :
is_integral R x :=
begin
rcases hx with β¨p, pmonic, hpβ©,
let S : set B := β(p.map $ algebra_map A B).frange,
refine is_integral_of_mem_of_fg (adjoin R (S βͺ {x})) _ _ (subset_adjoin $ or.inr rfl),
refine fg_trans (fg_adjoin_of_finite (finset.finite_to_set _) (Ξ» x hx, _)) _,
{ rw [finset.mem_coe, finsupp.mem_frange] at hx, rcases hx with β¨_, i, rflβ©,
show is_integral R ((p.map $ algebra_map A B).coeff i), rw coeff_map,
convert is_integral_alg_hom (is_scalar_tower.to_alg_hom R A B) (A_int _) },
{ apply fg_adjoin_singleton_of_integral,
exact is_integral_trans_aux _ pmonic hp }
end
/-- If A is an R-algebra all of whose elements are integral over R,
and B is an A-algebra all of whose elements are integral over A,
then all elements of B are integral over R.-/
lemma algebra.is_integral_trans (hA : is_integral R A) (hB : is_integral A B) : is_integral R B :=
Ξ» x, is_integral_trans hA x (hB x)
lemma is_integral_of_surjective (h : function.surjective (algebra_map R A)) : is_integral R A :=
Ξ» x, (h x).rec_on (Ξ» y hy, (hy βΈ is_integral_algebra_map : is_integral R x))
/-- If `R β A β B` is an algebra tower with `A β B` injective,
then if the entire tower is an integral extension so is `R β A` -/
lemma is_integral_tower_bot_of_is_integral (H : function.injective (algebra_map A B))
{x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x :=
begin
rcases h with β¨p, β¨hp, hp'β©β©,
refine β¨p, β¨hp, _β©β©,
rw [is_scalar_tower.algebra_map_eq R A B, β evalβ_map,
evalβ_hom, β ring_hom.map_zero (algebra_map A B)] at hp',
rw [evalβ_eq_eval_map],
exact H hp',
end
lemma is_integral_tower_bot_of_is_integral_field {R A B : Type*} [comm_ring R] [field A]
[comm_ring B] [nontrivial B] [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B]
{x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x :=
is_integral_tower_bot_of_is_integral (algebra_map A B).injective h
/-- If `R β A β B` is an algebra tower,
then if the entire tower is an integral extension so is `A β B` -/
lemma is_integral_tower_top_of_is_integral {x : B} (h : is_integral R x) : is_integral A x :=
begin
rcases h with β¨p, β¨hp, hp'β©β©,
refine β¨p.map (algebra_map R A), β¨monic_map (algebra_map R A) hp, _β©β©,
rw [is_scalar_tower.algebra_map_eq R A B, β evalβ_map] at hp',
exact hp',
end
lemma is_integral_quotient_of_is_integral {I : ideal A} (hRA : is_integral R A) :
is_integral (I.comap (algebra_map R A)).quotient I.quotient :=
begin
rintros β¨xβ©,
obtain β¨p, β¨p_monic, hpxβ©β© := hRA x,
refine β¨p.map (ideal.quotient.mk _), β¨monic_map _ p_monic, _β©β©,
simpa only [aeval_def, hom_evalβ, evalβ_map] using congr_arg (ideal.quotient.mk I) hpx
end
/-- If the integral extension `R β S` is injective, and `S` is a field, then `R` is also a field -/
lemma is_field_of_is_integral_of_is_field {R S : Type*} [integral_domain R] [integral_domain S]
[algebra R S] (H : is_integral R S) (hRS : function.injective (algebra_map R S))
(hS : is_field S) : is_field R :=
begin
refine β¨β¨0, 1, zero_ne_oneβ©, mul_comm, Ξ» a ha, _β©,
-- Let `a_inv` be the inverse of `algebra_map R S a`,
-- then we need to show that `a_inv` is of the form `algebra_map R S b`.
obtain β¨a_inv, ha_invβ© := hS.mul_inv_cancel (Ξ» h, ha (hRS (trans h (ring_hom.map_zero _).symm))),
-- Let `p : polynomial R` be monic with root `a_inv`,
-- and `q` be `p` with coefficients reversed (so `q(a) = q'(a) * a + 1`).
-- We claim that `q(a) = 0`, so `-q'(a)` is the inverse of `a`.
obtain β¨p, p_monic, hpβ© := H a_inv,
use -β (i : β) in finset.range p.nat_degree, (p.coeff i) * a ^ (p.nat_degree - i - 1),
-- `q(a) = 0`, because multiplying everything with `a_inv^n` gives `p(a_inv) = 0`.
-- TODO: this could be a lemma for `polynomial.reverse`.
have hq : β (i : β) in finset.range (p.nat_degree + 1), (p.coeff i) * a ^ (p.nat_degree - i) = 0,
{ apply (algebra_map R S).injective_iff.mp hRS,
have a_inv_ne_zero : a_inv β 0 := right_ne_zero_of_mul (mt ha_inv.symm.trans one_ne_zero),
refine (mul_eq_zero.mp _).resolve_right (pow_ne_zero p.nat_degree a_inv_ne_zero),
rw [evalβ_eq_sum_range] at hp,
rw [ring_hom.map_sum, finset.sum_mul],
refine (finset.sum_congr rfl (Ξ» i hi, _)).trans hp,
rw [ring_hom.map_mul, mul_assoc],
congr,
have : a_inv ^ p.nat_degree = a_inv ^ (p.nat_degree - i) * a_inv ^ i,
{ rw [β pow_add a_inv, nat.sub_add_cancel (nat.le_of_lt_succ (finset.mem_range.mp hi))] },
rw [ring_hom.map_pow, this, β mul_assoc, β mul_pow, ha_inv, one_pow, one_mul] },
-- Since `q(a) = 0` and `q(a) = q'(a) * a + 1`, we have `a * -q'(a) = 1`.
-- TODO: we could use a lemma for `polynomial.div_X` here.
rw [finset.sum_range_succ, p_monic.coeff_nat_degree, one_mul, nat.sub_self, pow_zero,
add_eq_zero_iff_eq_neg, eq_comm] at hq,
rw [mul_comm, β neg_mul_eq_neg_mul, finset.sum_mul],
convert hq using 2,
refine finset.sum_congr rfl (Ξ» i hi, _),
have : 1 β€ p.nat_degree - i := nat.le_sub_left_of_add_le (finset.mem_range.mp hi),
rw [mul_assoc, β pow_succ', nat.sub_add_cancel this]
end
end algebra
theorem integral_closure_idem {R : Type*} {A : Type*} [comm_ring R] [comm_ring A] [algebra R A] :
integral_closure (integral_closure R A : set A) A = β₯ :=
eq_bot_iff.2 $ Ξ» x hx, algebra.mem_bot.2
β¨β¨x, @is_integral_trans _ _ _ _ _ _ _ _ (integral_closure R A).algebra
_ integral_closure.is_integral x hxβ©, rflβ©
section integral_domain
variables {R S : Type*} [comm_ring R] [integral_domain S] [algebra R S]
instance : integral_domain (integral_closure R S) :=
{ exists_pair_ne := β¨0, 1, mt subtype.ext_iff_val.mp zero_ne_oneβ©,
eq_zero_or_eq_zero_of_mul_eq_zero := Ξ» β¨a, haβ© β¨b, hbβ© h,
or.imp subtype.ext_iff_val.mpr subtype.ext_iff_val.mpr (eq_zero_or_eq_zero_of_mul_eq_zero (subtype.ext_iff_val.mp h)),
..(integral_closure R S).comm_ring R S }
end integral_domain
|
53f89687c95c4989c20dd8ce8ec146660d638b43 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/measure_theory/group/action.lean | 3fa13676beccd56843931d082288294504f19887 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 10,566 | lean | /-
Copyright (c) 2021 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import measure_theory.group.measurable_equiv
import measure_theory.measure.regular
import dynamics.ergodic.measure_preserving
import dynamics.minimal
/-!
# Measures invariant under group actions
A measure `ΞΌ : measure Ξ±` is said to be *invariant* under an action of a group `G` if scalar
multiplication by `c : G` is a measure preserving map for all `c`. In this file we define a
typeclass for measures invariant under action of an (additive or multiplicative) group and prove
some basic properties of such measures.
-/
open_locale ennreal nnreal pointwise topology
open measure_theory measure_theory.measure set function
namespace measure_theory
variables {G M Ξ± : Type*} {s : set Ξ±}
/-- A measure `ΞΌ : measure Ξ±` is invariant under an additive action of `M` on `Ξ±` if for any
measurable set `s : set Ξ±` and `c : M`, the measure of its preimage under `Ξ» x, c +α΅₯ x` is equal to
the measure of `s`. -/
class vadd_invariant_measure (M Ξ± : Type*) [has_vadd M Ξ±] {_ : measurable_space Ξ±}
(ΞΌ : measure Ξ±) : Prop :=
(measure_preimage_vadd [] : β (c : M) β¦s : set Ξ±β¦, measurable_set s β ΞΌ ((Ξ» x, c +α΅₯ x) β»ΒΉ' s) = ΞΌ s)
/-- A measure `ΞΌ : measure Ξ±` is invariant under a multiplicative action of `M` on `Ξ±` if for any
measurable set `s : set Ξ±` and `c : M`, the measure of its preimage under `Ξ» x, c β’ x` is equal to
the measure of `s`. -/
@[to_additive] class smul_invariant_measure (M Ξ± : Type*) [has_smul M Ξ±] {_ : measurable_space Ξ±}
(ΞΌ : measure Ξ±) : Prop :=
(measure_preimage_smul [] : β (c : M) β¦s : set Ξ±β¦, measurable_set s β ΞΌ ((Ξ» x, c β’ x) β»ΒΉ' s) = ΞΌ s)
namespace smul_invariant_measure
@[to_additive] instance zero [measurable_space Ξ±] [has_smul M Ξ±] : smul_invariant_measure M Ξ± 0 :=
β¨Ξ» _ _ _, rflβ©
variables [has_smul M Ξ±] {m : measurable_space Ξ±} {ΞΌ Ξ½ : measure Ξ±}
@[to_additive] instance add [smul_invariant_measure M Ξ± ΞΌ] [smul_invariant_measure M Ξ± Ξ½] :
smul_invariant_measure M Ξ± (ΞΌ + Ξ½) :=
β¨Ξ» c s hs, show _ + _ = _ + _,
from congr_arg2 (+) (measure_preimage_smul ΞΌ c hs) (measure_preimage_smul Ξ½ c hs)β©
@[to_additive] instance smul [smul_invariant_measure M Ξ± ΞΌ] (c : ββ₯0β) :
smul_invariant_measure M Ξ± (c β’ ΞΌ) :=
β¨Ξ» a s hs, show c β’ _ = c β’ _, from congr_arg ((β’) c) (measure_preimage_smul ΞΌ a hs)β©
@[to_additive] instance smul_nnreal [smul_invariant_measure M Ξ± ΞΌ] (c : ββ₯0) :
smul_invariant_measure M Ξ± (c β’ ΞΌ) :=
smul_invariant_measure.smul c
end smul_invariant_measure
section has_measurable_smul
variables {m : measurable_space Ξ±} [measurable_space M] [has_smul M Ξ±] [has_measurable_smul M Ξ±]
(c : M) (ΞΌ : measure Ξ±) [smul_invariant_measure M Ξ± ΞΌ]
@[simp, to_additive] lemma measure_preserving_smul : measure_preserving ((β’) c) ΞΌ ΞΌ :=
{ measurable := measurable_const_smul c,
map_eq :=
begin
ext1 s hs,
rw map_apply (measurable_const_smul c) hs,
exact smul_invariant_measure.measure_preimage_smul ΞΌ c hs,
end }
@[simp, to_additive] lemma map_smul : map ((β’) c) ΞΌ = ΞΌ :=
(measure_preserving_smul c ΞΌ).map_eq
end has_measurable_smul
variables (G) {m : measurable_space Ξ±} [group G] [mul_action G Ξ±] [measurable_space G]
[has_measurable_smul G Ξ±] (c : G) (ΞΌ : measure Ξ±)
/-- Equivalent definitions of a measure invariant under a multiplicative action of a group.
- 0: `smul_invariant_measure G Ξ± ΞΌ`;
- 1: for every `c : G` and a measurable set `s`, the measure of the preimage of `s` under scalar
multiplication by `c` is equal to the measure of `s`;
- 2: for every `c : G` and a measurable set `s`, the measure of the image `c β’ s` of `s` under
scalar multiplication by `c` is equal to the measure of `s`;
- 3, 4: properties 2, 3 for any set, including non-measurable ones;
- 5: for any `c : G`, scalar multiplication by `c` maps `ΞΌ` to `ΞΌ`;
- 6: for any `c : G`, scalar multiplication by `c` is a measure preserving map. -/
@[to_additive] lemma smul_invariant_measure_tfae :
tfae [smul_invariant_measure G Ξ± ΞΌ,
β (c : G) s, measurable_set s β ΞΌ (((β’) c) β»ΒΉ' s) = ΞΌ s,
β (c : G) s, measurable_set s β ΞΌ (c β’ s) = ΞΌ s,
β (c : G) s, ΞΌ (((β’) c) β»ΒΉ' s) = ΞΌ s,
β (c : G) s, ΞΌ (c β’ s) = ΞΌ s,
β c : G, measure.map ((β’) c) ΞΌ = ΞΌ,
β c : G, measure_preserving ((β’) c) ΞΌ ΞΌ] :=
begin
tfae_have : 1 β 2, from β¨Ξ» h, h.1, Ξ» h, β¨hβ©β©,
tfae_have : 1 β 6, { introsI h c, exact (measure_preserving_smul c ΞΌ).map_eq, },
tfae_have : 6 β 7, from Ξ» H c, β¨measurable_const_smul c, H cβ©,
tfae_have : 7 β 4, from Ξ» H c, (H c).measure_preimage_emb (measurable_embedding_const_smul c),
tfae_have : 4 β 5, from Ξ» H c s, by { rw [β preimage_smul_inv], apply H },
tfae_have : 5 β 3, from Ξ» H c s hs, H c s,
tfae_have : 3 β 2, { intros H c s hs, rw preimage_smul, exact H cβ»ΒΉ s hs },
tfae_finish
end
/-- Equivalent definitions of a measure invariant under an additive action of a group.
- 0: `vadd_invariant_measure G Ξ± ΞΌ`;
- 1: for every `c : G` and a measurable set `s`, the measure of the preimage of `s` under
vector addition `(+α΅₯) c` is equal to the measure of `s`;
- 2: for every `c : G` and a measurable set `s`, the measure of the image `c +α΅₯ s` of `s` under
vector addition `(+α΅₯) c` is equal to the measure of `s`;
- 3, 4: properties 2, 3 for any set, including non-measurable ones;
- 5: for any `c : G`, vector addition of `c` maps `ΞΌ` to `ΞΌ`;
- 6: for any `c : G`, vector addition of `c` is a measure preserving map. -/
add_decl_doc vadd_invariant_measure_tfae
variables {G} [smul_invariant_measure G Ξ± ΞΌ]
@[simp, to_additive] lemma measure_preimage_smul (s : set Ξ±) : ΞΌ ((β’) c β»ΒΉ' s) = ΞΌ s :=
((smul_invariant_measure_tfae G ΞΌ).out 0 3).mp βΉ_βΊ c s
@[simp, to_additive] lemma measure_smul (s : set Ξ±) : ΞΌ (c β’ s) = ΞΌ s :=
((smul_invariant_measure_tfae G ΞΌ).out 0 4).mp βΉ_βΊ c s
variable {ΞΌ}
@[to_additive] lemma null_measurable_set.smul {s} (hs : null_measurable_set s ΞΌ) (c : G) :
null_measurable_set (c β’ s) ΞΌ :=
by simpa only [β preimage_smul_inv]
using hs.preimage (measure_preserving_smul _ _).quasi_measure_preserving
lemma measure_smul_null {s} (h : ΞΌ s = 0) (c : G) : ΞΌ (c β’ s) = 0 := by rwa measure_smul
section is_minimal
variables (G) [topological_space Ξ±] [has_continuous_const_smul G Ξ±] [mul_action.is_minimal G Ξ±]
{K U : set Ξ±}
/-- If measure `ΞΌ` is invariant under a group action and is nonzero on a compact set `K`, then it is
positive on any nonempty open set. In case of a regular measure, one can assume `ΞΌ β 0` instead of
`ΞΌ K β 0`, see `measure_theory.measure_is_open_pos_of_smul_invariant_of_ne_zero`. -/
@[to_additive] lemma measure_is_open_pos_of_smul_invariant_of_compact_ne_zero (hK : is_compact K)
(hΞΌK : ΞΌ K β 0) (hU : is_open U) (hne : U.nonempty) : 0 < ΞΌ U :=
let β¨t, htβ© := hK.exists_finite_cover_smul G hU hne
in pos_iff_ne_zero.2 $ Ξ» hΞΌU, hΞΌK $ measure_mono_null ht $
(measure_bUnion_null_iff t.countable_to_set).2 $ Ξ» _ _, by rwa measure_smul
/-- If measure `ΞΌ` is invariant under an additive group action and is nonzero on a compact set `K`,
then it is positive on any nonempty open set. In case of a regular measure, one can assume `ΞΌ β 0`
instead of `ΞΌ K β 0`, see `measure_theory.measure_is_open_pos_of_vadd_invariant_of_ne_zero`. -/
add_decl_doc measure_is_open_pos_of_vadd_invariant_of_compact_ne_zero
@[to_additive] lemma is_locally_finite_measure_of_smul_invariant (hU : is_open U) (hne : U.nonempty)
(hΞΌU : ΞΌ U β β) : is_locally_finite_measure ΞΌ :=
β¨Ξ» x, let β¨g, hgβ© := hU.exists_smul_mem G x hne in
β¨(β’) g β»ΒΉ' U, (hU.preimage (continuous_id.const_smul _)).mem_nhds hg, ne.lt_top $
by rwa [measure_preimage_smul]β©β©
variables [measure.regular ΞΌ]
@[to_additive] lemma measure_is_open_pos_of_smul_invariant_of_ne_zero (hΞΌ : ΞΌ β 0) (hU : is_open U)
(hne : U.nonempty) : 0 < ΞΌ U :=
let β¨K, hK, hΞΌKβ© := regular.exists_compact_not_null.mpr hΞΌ
in measure_is_open_pos_of_smul_invariant_of_compact_ne_zero G hK hΞΌK hU hne
@[to_additive] lemma measure_pos_iff_nonempty_of_smul_invariant (hΞΌ : ΞΌ β 0) (hU : is_open U) :
0 < ΞΌ U β U.nonempty :=
β¨Ξ» h, nonempty_of_measure_ne_zero h.ne', measure_is_open_pos_of_smul_invariant_of_ne_zero G hΞΌ hUβ©
include G
@[to_additive] lemma measure_eq_zero_iff_eq_empty_of_smul_invariant (hΞΌ : ΞΌ β 0) (hU : is_open U) :
ΞΌ U = 0 β U = β
:=
by rw [β not_iff_not, β ne.def, β pos_iff_ne_zero,
measure_pos_iff_nonempty_of_smul_invariant G hΞΌ hU, nonempty_iff_ne_empty]
end is_minimal
lemma smul_ae_eq_self_of_mem_zpowers
{x y : G} (hs : (x β’ s : set Ξ±) =α΅[ΞΌ] s) (hy : y β subgroup.zpowers x) :
(y β’ s : set Ξ±) =α΅[ΞΌ] s :=
begin
obtain β¨k, rflβ© := subgroup.mem_zpowers_iff.mp hy,
let e : Ξ± β Ξ± := mul_action.to_perm_hom G Ξ± x,
have he : quasi_measure_preserving e ΞΌ ΞΌ :=
(measure_preserving_smul x ΞΌ).quasi_measure_preserving,
have he' : quasi_measure_preserving e.symm ΞΌ ΞΌ :=
(measure_preserving_smul xβ»ΒΉ ΞΌ).quasi_measure_preserving,
simpa only [mul_action.to_perm_hom_apply, mul_action.to_perm_apply, image_smul,
β monoid_hom.map_zpow] using he.image_zpow_ae_eq he' k hs,
end
lemma vadd_ae_eq_self_of_mem_zmultiples {G : Type*} [measurable_space G]
[add_group G] [add_action G Ξ±] [vadd_invariant_measure G Ξ± ΞΌ] [has_measurable_vadd G Ξ±]
{x y : G} (hs : (x +α΅₯ s : set Ξ±) =α΅[ΞΌ] s) (hy : y β add_subgroup.zmultiples x) :
(y +α΅₯ s : set Ξ±) =α΅[ΞΌ] s :=
begin
letI : measurable_space (multiplicative G) := (by apply_instance : measurable_space G),
letI : smul_invariant_measure (multiplicative G) Ξ± ΞΌ :=
β¨Ξ» g, vadd_invariant_measure.measure_preimage_vadd ΞΌ (multiplicative.to_add g)β©,
letI : has_measurable_smul (multiplicative G) Ξ± :=
{ measurable_const_smul := Ξ» g, measurable_const_vadd (multiplicative.to_add g),
measurable_smul_const := Ξ» a, @measurable_vadd_const (multiplicative G) Ξ±
(by apply_instance : has_vadd G Ξ±) _ _ (by apply_instance : has_measurable_vadd G Ξ±) a },
exact @smul_ae_eq_self_of_mem_zpowers (multiplicative G) Ξ± _ _ _ _ _ _ _ _ _ _ hs hy,
end
attribute [to_additive vadd_ae_eq_self_of_mem_zmultiples] smul_ae_eq_self_of_mem_zpowers
end measure_theory
|
13966a2289c83a39e05f398626845e375c78fa96 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/computability/partrec_code.lean | 80f8f4f17aa3a42213d8befc94c9ad19ba6a1269 | [
"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 | 38,823 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
Godel numbering for partial recursive functions.
-/
import computability.partrec
open encodable denumerable
namespace nat.partrec
open nat (mkpair)
theorem rfind' {f} (hf : nat.partrec f) : nat.partrec (nat.unpaired (Ξ» a m,
(nat.rfind (Ξ» n, (Ξ» m, m = 0) <$> f (mkpair a (n + m)))).map (+ m))) :=
partrecβ.unpaired'.2 $
begin
refine partrec.map
((@partrecβ.unpaired' (Ξ» (a b : β),
nat.rfind (Ξ» n, (Ξ» m, m = 0) <$> f (mkpair a (n + b))))).1 _)
(primrec.nat_add.comp primrec.snd $
primrec.snd.comp primrec.fst).to_comp.toβ,
have := rfind (partrecβ.unpaired'.2 ((partrec.nat_iff.2 hf).comp
(primrecβ.mkpair.comp
(primrec.fst.comp $ primrec.unpair.comp primrec.fst)
(primrec.nat_add.comp primrec.snd
(primrec.snd.comp $ primrec.unpair.comp primrec.fst))).to_comp).toβ),
simp at this, exact this
end
inductive code : Type
| zero : code
| succ : code
| left : code
| right : code
| pair : code β code β code
| comp : code β code β code
| prec : code β code β code
| rfind' : code β code
end nat.partrec
namespace nat.partrec.code
open nat (mkpair unpair)
open nat.partrec (code)
instance : inhabited code := β¨zeroβ©
protected def const : β β code
| 0 := zero
| (n+1) := comp succ (const n)
theorem const_inj : Ξ {nβ nβ}, nat.partrec.code.const nβ = nat.partrec.code.const nβ β nβ = nβ
| 0 0 h := by simp
| (nβ+1) (nβ+1) h := by { dsimp [nat.partrec.code.const] at h,
injection h with hβ hβ,
simp only [const_inj hβ] }
protected def id : code := pair left right
def curry (c : code) (n : β) : code :=
comp c (pair (code.const n) code.id)
def encode_code : code β β
| zero := 0
| succ := 1
| left := 2
| right := 3
| (pair cf cg) := bit0 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4
| (comp cf cg) := bit0 (bit1 $ mkpair (encode_code cf) (encode_code cg)) + 4
| (prec cf cg) := bit1 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4
| (rfind' cf) := bit1 (bit1 $ encode_code cf) + 4
def of_nat_code : β β code
| 0 := zero
| 1 := succ
| 2 := left
| 3 := right
| (n+4) := let m := n.div2.div2 in
have hm : m < n + 4, by simp [m, nat.div2_val];
from lt_of_le_of_lt
(le_trans (nat.div_le_self _ _) (nat.div_le_self _ _))
(nat.succ_le_succ (nat.le_add_right _ _)),
have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm,
have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm,
match n.bodd, n.div2.bodd with
| ff, ff := pair (of_nat_code m.unpair.1) (of_nat_code m.unpair.2)
| ff, tt := comp (of_nat_code m.unpair.1) (of_nat_code m.unpair.2)
| tt, ff := prec (of_nat_code m.unpair.1) (of_nat_code m.unpair.2)
| tt, tt := rfind' (of_nat_code m)
end
private theorem encode_of_nat_code : β n, encode_code (of_nat_code n) = n
| 0 := by simp [of_nat_code, encode_code]
| 1 := by simp [of_nat_code, encode_code]
| 2 := by simp [of_nat_code, encode_code]
| 3 := by simp [of_nat_code, encode_code]
| (n+4) := let m := n.div2.div2 in
have hm : m < n + 4, by simp [m, nat.div2_val];
from lt_of_le_of_lt
(le_trans (nat.div_le_self _ _) (nat.div_le_self _ _))
(nat.succ_le_succ (nat.le_add_right _ _)),
have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm,
have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm,
have IH : _ := encode_of_nat_code m,
have IH1 : _ := encode_of_nat_code m.unpair.1,
have IH2 : _ := encode_of_nat_code m.unpair.2,
begin
transitivity, swap,
rw [β nat.bit_decomp n, β nat.bit_decomp n.div2],
simp [encode_code, of_nat_code, -add_comm],
cases n.bodd; cases n.div2.bodd;
simp [encode_code, of_nat_code, -add_comm, IH, IH1, IH2, m, nat.bit]
end
instance : denumerable code :=
mk' β¨encode_code, of_nat_code,
Ξ» c, by induction c; try {refl}; simp [
encode_code, of_nat_code, -add_comm, *],
encode_of_nat_codeβ©
theorem encode_code_eq : encode = encode_code := rfl
theorem of_nat_code_eq : of_nat code = of_nat_code := rfl
theorem encode_lt_pair (cf cg) :
encode cf < encode (pair cf cg) β§
encode cg < encode (pair cf cg) :=
begin
simp [encode_code_eq, encode_code, -add_comm],
have := nat.mul_le_mul_right _ (dec_trivial : 1 β€ 2*2),
rw [one_mul, mul_assoc, β bit0_eq_two_mul, β bit0_eq_two_mul] at this,
have := lt_of_le_of_lt this (lt_add_of_pos_right _ (dec_trivial:0<4)),
exact β¨
lt_of_le_of_lt (nat.left_le_mkpair _ _) this,
lt_of_le_of_lt (nat.right_le_mkpair _ _) thisβ©
end
theorem encode_lt_comp (cf cg) :
encode cf < encode (comp cf cg) β§
encode cg < encode (comp cf cg) :=
begin
suffices, exact (encode_lt_pair cf cg).imp
(Ξ» h, lt_trans h this) (Ξ» h, lt_trans h this),
change _, simp [encode_code_eq, encode_code]
end
theorem encode_lt_prec (cf cg) :
encode cf < encode (prec cf cg) β§
encode cg < encode (prec cf cg) :=
begin
suffices, exact (encode_lt_pair cf cg).imp
(Ξ» h, lt_trans h this) (Ξ» h, lt_trans h this),
change _, simp [encode_code_eq, encode_code],
end
theorem encode_lt_rfind' (cf) : encode cf < encode (rfind' cf) :=
begin
simp [encode_code_eq, encode_code, -add_comm],
have := nat.mul_le_mul_right _ (dec_trivial : 1 β€ 2*2),
rw [one_mul, mul_assoc, β bit0_eq_two_mul, β bit0_eq_two_mul] at this,
refine lt_of_le_of_lt (le_trans this _)
(lt_add_of_pos_right _ (dec_trivial:0<4)),
exact le_of_lt (nat.bit0_lt_bit1 $ le_of_lt $
nat.bit0_lt_bit1 $ le_rfl),
end
section
open primrec
theorem pair_prim : primrecβ pair :=
primrecβ.of_nat_iff.2 $ primrecβ.encode_iff.1 $ nat_add.comp
(nat_bit0.comp $ nat_bit0.comp $
primrecβ.mkpair.comp
(encode_iff.2 $ (primrec.of_nat code).comp fst)
(encode_iff.2 $ (primrec.of_nat code).comp snd))
(primrecβ.const 4)
theorem comp_prim : primrecβ comp :=
primrecβ.of_nat_iff.2 $ primrecβ.encode_iff.1 $ nat_add.comp
(nat_bit0.comp $ nat_bit1.comp $
primrecβ.mkpair.comp
(encode_iff.2 $ (primrec.of_nat code).comp fst)
(encode_iff.2 $ (primrec.of_nat code).comp snd))
(primrecβ.const 4)
theorem prec_prim : primrecβ prec :=
primrecβ.of_nat_iff.2 $ primrecβ.encode_iff.1 $ nat_add.comp
(nat_bit1.comp $ nat_bit0.comp $
primrecβ.mkpair.comp
(encode_iff.2 $ (primrec.of_nat code).comp fst)
(encode_iff.2 $ (primrec.of_nat code).comp snd))
(primrecβ.const 4)
theorem rfind_prim : primrec rfind' :=
of_nat_iff.2 $ encode_iff.1 $ nat_add.comp
(nat_bit1.comp $ nat_bit1.comp $
encode_iff.2 $ primrec.of_nat code)
(const 4)
theorem rec_prim' {Ξ± Ο} [primcodable Ξ±] [primcodable Ο]
{c : Ξ± β code} (hc : primrec c)
{z : Ξ± β Ο} (hz : primrec z)
{s : Ξ± β Ο} (hs : primrec s)
{l : Ξ± β Ο} (hl : primrec l)
{r : Ξ± β Ο} (hr : primrec r)
{pr : Ξ± β code Γ code Γ Ο Γ Ο β Ο} (hpr : primrecβ pr)
{co : Ξ± β code Γ code Γ Ο Γ Ο β Ο} (hco : primrecβ co)
{pc : Ξ± β code Γ code Γ Ο Γ Ο β Ο} (hpc : primrecβ pc)
{rf : Ξ± β code Γ Ο β Ο} (hrf : primrecβ rf) :
let PR (a) := Ξ» cf cg hf hg, pr a (cf, cg, hf, hg),
CO (a) := Ξ» cf cg hf hg, co a (cf, cg, hf, hg),
PC (a) := Ξ» cf cg hf hg, pc a (cf, cg, hf, hg),
RF (a) := Ξ» cf hf, rf a (cf, hf),
F (a : Ξ±) (c : code) : Ο := nat.partrec.code.rec_on c
(z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in
primrec (Ξ» a, F a (c a) : Ξ± β Ο) :=
begin
intros,
let Gβ : (Ξ± Γ list Ο) Γ β Γ β β option Ο := Ξ» p,
let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in
(IH.nth m).bind $ Ξ» s,
(IH.nth m.unpair.1).bind $ Ξ» sβ,
(IH.nth m.unpair.2).map $ Ξ» sβ,
cond n.bodd
(cond n.div2.bodd
(rf a (of_nat code m, s))
(pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, sβ, sβ)))
(cond n.div2.bodd
(co a (of_nat code m.unpair.1, of_nat code m.unpair.2, sβ, sβ))
(pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, sβ, sβ))),
have : primrec Gβ,
{ refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _,
refine option_bind ((list_nth.comp (snd.comp fst)
(fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _,
refine option_map ((list_nth.comp (snd.comp fst)
(snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _,
have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst),
have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst),
have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst),
have mβ := fst.comp (primrec.unpair.comp m),
have mβ := snd.comp (primrec.unpair.comp m),
have s := snd.comp (fst.comp fst),
have sβ := snd.comp fst,
have sβ := snd,
exact (nat_bodd.comp n).cond
((nat_bodd.comp $ nat_div2.comp n).cond
(hrf.comp a (((primrec.of_nat code).comp m).pair s))
(hpc.comp a (((primrec.of_nat code).comp mβ).pair $
((primrec.of_nat code).comp mβ).pair $ sβ.pair sβ)))
(primrec.cond (nat_bodd.comp $ nat_div2.comp n)
(hco.comp a (((primrec.of_nat code).comp mβ).pair $
((primrec.of_nat code).comp mβ).pair $ sβ.pair sβ))
(hpr.comp a (((primrec.of_nat code).comp mβ).pair $
((primrec.of_nat code).comp mβ).pair $ sβ.pair sβ))) },
let G : Ξ± β list Ο β option Ο := Ξ» a IH,
IH.length.cases (some (z a)) $ Ξ» n,
n.cases (some (s a)) $ Ξ» n,
n.cases (some (l a)) $ Ξ» n,
n.cases (some (r a)) $ Ξ» n,
Gβ ((a, IH), n, n.div2.div2),
have : primrecβ G := (nat_cases
(list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $
nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $
nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $
nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst)))
(this.comp $
((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $
snd.pair $ nat_div2.comp $ nat_div2.comp snd)),
refine ((nat_strong_rec
(Ξ» a n, F a (of_nat code n)) this.toβ $ Ξ» a n, _).comp
primrec.id $ encode_iff.2 hc).of_eq (Ξ» a, by simp),
simp,
iterate 4 {cases n with n, {simp [of_nat_code_eq, of_nat_code]; refl}},
simp [G], rw [list.length_map, list.length_range],
let m := n.div2.div2,
show Gβ ((a, (list.range (n+4)).map (Ξ» n, F a (of_nat code n))), n, m)
= some (F a (of_nat code (n+4))),
have hm : m < n + 4, by simp [nat.div2_val, m];
from lt_of_le_of_lt
(le_trans (nat.div_le_self _ _) (nat.div_le_self _ _))
(nat.succ_le_succ (nat.le_add_right _ _)),
have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm,
have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm,
simp [Gβ], simp [list.nth_map, list.nth_range, hm, m1, m2],
change of_nat code (n+4) with of_nat_code (n+4),
simp [of_nat_code],
cases n.bodd; cases n.div2.bodd; refl
end
theorem rec_prim {Ξ± Ο} [primcodable Ξ±] [primcodable Ο]
{c : Ξ± β code} (hc : primrec c)
{z : Ξ± β Ο} (hz : primrec z)
{s : Ξ± β Ο} (hs : primrec s)
{l : Ξ± β Ο} (hl : primrec l)
{r : Ξ± β Ο} (hr : primrec r)
{pr : Ξ± β code β code β Ο β Ο β Ο}
(hpr : primrec (Ξ» a : Ξ± Γ code Γ code Γ Ο Γ Ο,
pr a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2))
{co : Ξ± β code β code β Ο β Ο β Ο}
(hco : primrec (Ξ» a : Ξ± Γ code Γ code Γ Ο Γ Ο,
co a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2))
{pc : Ξ± β code β code β Ο β Ο β Ο}
(hpc : primrec (Ξ» a : Ξ± Γ code Γ code Γ Ο Γ Ο,
pc a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2))
{rf : Ξ± β code β Ο β Ο}
(hrf : primrec (Ξ» a : Ξ± Γ code Γ Ο, rf a.1 a.2.1 a.2.2)) :
let F (a : Ξ±) (c : code) : Ο := nat.partrec.code.rec_on c
(z a) (s a) (l a) (r a) (pr a) (co a) (pc a) (rf a) in
primrec (Ξ» a, F a (c a)) :=
begin
intros,
let Gβ : (Ξ± Γ list Ο) Γ β Γ β β option Ο := Ξ» p,
let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in
(IH.nth m).bind $ Ξ» s,
(IH.nth m.unpair.1).bind $ Ξ» sβ,
(IH.nth m.unpair.2).map $ Ξ» sβ,
cond n.bodd
(cond n.div2.bodd
(rf a (of_nat code m) s)
(pc a (of_nat code m.unpair.1) (of_nat code m.unpair.2) sβ sβ))
(cond n.div2.bodd
(co a (of_nat code m.unpair.1) (of_nat code m.unpair.2) sβ sβ)
(pr a (of_nat code m.unpair.1) (of_nat code m.unpair.2) sβ sβ)),
have : primrec Gβ,
{ refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _,
refine option_bind ((list_nth.comp (snd.comp fst)
(fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _,
refine option_map ((list_nth.comp (snd.comp fst)
(snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _,
have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst),
have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst),
have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst),
have mβ := fst.comp (primrec.unpair.comp m),
have mβ := snd.comp (primrec.unpair.comp m),
have s := snd.comp (fst.comp fst),
have sβ := snd.comp fst,
have sβ := snd,
exact (nat_bodd.comp n).cond
((nat_bodd.comp $ nat_div2.comp n).cond
(hrf.comp $ a.pair (((primrec.of_nat code).comp m).pair s))
(hpc.comp $ a.pair (((primrec.of_nat code).comp mβ).pair $
((primrec.of_nat code).comp mβ).pair $ sβ.pair sβ)))
(primrec.cond (nat_bodd.comp $ nat_div2.comp n)
(hco.comp $ a.pair (((primrec.of_nat code).comp mβ).pair $
((primrec.of_nat code).comp mβ).pair $ sβ.pair sβ))
(hpr.comp $ a.pair (((primrec.of_nat code).comp mβ).pair $
((primrec.of_nat code).comp mβ).pair $ sβ.pair sβ))) },
let G : Ξ± β list Ο β option Ο := Ξ» a IH,
IH.length.cases (some (z a)) $ Ξ» n,
n.cases (some (s a)) $ Ξ» n,
n.cases (some (l a)) $ Ξ» n,
n.cases (some (r a)) $ Ξ» n,
Gβ ((a, IH), n, n.div2.div2),
have : primrecβ G := (nat_cases
(list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $
nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $
nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $
nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst)))
(this.comp $
((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $
snd.pair $ nat_div2.comp $ nat_div2.comp snd)),
refine ((nat_strong_rec
(Ξ» a n, F a (of_nat code n)) this.toβ $ Ξ» a n, _).comp
primrec.id $ encode_iff.2 hc).of_eq (Ξ» a, by simp),
simp,
iterate 4 {cases n with n, {simp [of_nat_code_eq, of_nat_code]; refl}},
simp [G], rw [list.length_map, list.length_range],
let m := n.div2.div2,
show Gβ ((a, (list.range (n+4)).map (Ξ» n, F a (of_nat code n))), n, m)
= some (F a (of_nat code (n+4))),
have hm : m < n + 4, by simp [nat.div2_val, m];
from lt_of_le_of_lt
(le_trans (nat.div_le_self _ _) (nat.div_le_self _ _))
(nat.succ_le_succ (nat.le_add_right _ _)),
have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm,
have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm,
simp [Gβ], simp [list.nth_map, list.nth_range, hm, m1, m2],
change of_nat code (n+4) with of_nat_code (n+4),
simp [of_nat_code],
cases n.bodd; cases n.div2.bodd; refl
end
end
section
open computable
/- TODO(Mario): less copy-paste from previous proof -/
theorem rec_computable {Ξ± Ο} [primcodable Ξ±] [primcodable Ο]
{c : Ξ± β code} (hc : computable c)
{z : Ξ± β Ο} (hz : computable z)
{s : Ξ± β Ο} (hs : computable s)
{l : Ξ± β Ο} (hl : computable l)
{r : Ξ± β Ο} (hr : computable r)
{pr : Ξ± β code Γ code Γ Ο Γ Ο β Ο} (hpr : computableβ pr)
{co : Ξ± β code Γ code Γ Ο Γ Ο β Ο} (hco : computableβ co)
{pc : Ξ± β code Γ code Γ Ο Γ Ο β Ο} (hpc : computableβ pc)
{rf : Ξ± β code Γ Ο β Ο} (hrf : computableβ rf) :
let PR (a) := Ξ» cf cg hf hg, pr a (cf, cg, hf, hg),
CO (a) := Ξ» cf cg hf hg, co a (cf, cg, hf, hg),
PC (a) := Ξ» cf cg hf hg, pc a (cf, cg, hf, hg),
RF (a) := Ξ» cf hf, rf a (cf, hf),
F (a : Ξ±) (c : code) : Ο := nat.partrec.code.rec_on c
(z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in
computable (Ξ» a, F a (c a)) :=
begin
intros,
let Gβ : (Ξ± Γ list Ο) Γ β Γ β β option Ο := Ξ» p,
let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in
(IH.nth m).bind $ Ξ» s,
(IH.nth m.unpair.1).bind $ Ξ» sβ,
(IH.nth m.unpair.2).map $ Ξ» sβ,
cond n.bodd
(cond n.div2.bodd
(rf a (of_nat code m, s))
(pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, sβ, sβ)))
(cond n.div2.bodd
(co a (of_nat code m.unpair.1, of_nat code m.unpair.2, sβ, sβ))
(pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, sβ, sβ))),
have : computable Gβ,
{ refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _,
refine option_bind ((list_nth.comp (snd.comp fst)
(fst.comp $ computable.unpair.comp (snd.comp snd))).comp fst) _,
refine option_map ((list_nth.comp (snd.comp fst)
(snd.comp $ computable.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _,
have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst),
have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst),
have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst),
have mβ := fst.comp (computable.unpair.comp m),
have mβ := snd.comp (computable.unpair.comp m),
have s := snd.comp (fst.comp fst),
have sβ := snd.comp fst,
have sβ := snd,
exact (nat_bodd.comp n).cond
((nat_bodd.comp $ nat_div2.comp n).cond
(hrf.comp a (((computable.of_nat code).comp m).pair s))
(hpc.comp a (((computable.of_nat code).comp mβ).pair $
((computable.of_nat code).comp mβ).pair $ sβ.pair sβ)))
(computable.cond (nat_bodd.comp $ nat_div2.comp n)
(hco.comp a (((computable.of_nat code).comp mβ).pair $
((computable.of_nat code).comp mβ).pair $ sβ.pair sβ))
(hpr.comp a (((computable.of_nat code).comp mβ).pair $
((computable.of_nat code).comp mβ).pair $ sβ.pair sβ))) },
let G : Ξ± β list Ο β option Ο := Ξ» a IH,
IH.length.cases (some (z a)) $ Ξ» n,
n.cases (some (s a)) $ Ξ» n,
n.cases (some (l a)) $ Ξ» n,
n.cases (some (r a)) $ Ξ» n,
Gβ ((a, IH), n, n.div2.div2),
have : computableβ G := (nat_cases
(list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $
nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $
nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $
nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst)))
(this.comp $
((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $
snd.pair $ nat_div2.comp $ nat_div2.comp snd)),
refine ((nat_strong_rec
(Ξ» a n, F a (of_nat code n)) this.toβ $ Ξ» a n, _).comp
computable.id $ encode_iff.2 hc).of_eq (Ξ» a, by simp),
simp,
iterate 4 {cases n with n, {simp [of_nat_code_eq, of_nat_code]; refl}},
simp [G], rw [list.length_map, list.length_range],
let m := n.div2.div2,
show Gβ ((a, (list.range (n+4)).map (Ξ» n, F a (of_nat code n))), n, m)
= some (F a (of_nat code (n+4))),
have hm : m < n + 4, by simp [nat.div2_val, m];
from lt_of_le_of_lt
(le_trans (nat.div_le_self _ _) (nat.div_le_self _ _))
(nat.succ_le_succ (nat.le_add_right _ _)),
have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm,
have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm,
simp [Gβ], simp [list.nth_map, list.nth_range, hm, m1, m2],
change of_nat code (n+4) with of_nat_code (n+4),
simp [of_nat_code],
cases n.bodd; cases n.div2.bodd; refl
end
end
def eval : code β β β. β
| zero := pure 0
| succ := nat.succ
| left := β(Ξ» n : β, n.unpair.1)
| right := β(Ξ» n : β, n.unpair.2)
| (pair cf cg) := Ξ» n, mkpair <$> eval cf n <*> eval cg n
| (comp cf cg) := Ξ» n, eval cg n >>= eval cf
| (prec cf cg) := nat.unpaired (Ξ» a n,
n.elim (eval cf a) (Ξ» y IH, do i β IH, eval cg (mkpair a (mkpair y i))))
| (rfind' cf) := nat.unpaired (Ξ» a m,
(nat.rfind (Ξ» n, (Ξ» m, m = 0) <$>
eval cf (mkpair a (n + m)))).map (+ m))
instance : has_mem (β β. β) code := β¨Ξ» f c, eval c = fβ©
@[simp] theorem eval_const : β n m, eval (code.const n) m = part.some n
| 0 m := rfl
| (n+1) m := by simp! *
@[simp] theorem eval_id (n) : eval code.id n = part.some n := by simp! [(<*>)]
@[simp] theorem eval_curry (c n x) : eval (curry c n) x = eval c (mkpair n x) :=
by simp! [(<*>)]
theorem const_prim : primrec code.const :=
(primrec.id.nat_iterate (primrec.const zero)
(comp_prim.comp (primrec.const succ) primrec.snd).toβ).of_eq $
Ξ» n, by simp; induction n; simp [*, code.const, function.iterate_succ']
theorem curry_prim : primrecβ curry :=
comp_prim.comp primrec.fst $
pair_prim.comp (const_prim.comp primrec.snd) (primrec.const code.id)
theorem curry_inj {cβ cβ nβ nβ} (h : curry cβ nβ = curry cβ nβ) : cβ = cβ β§ nβ = nβ :=
β¨by injection h, by { injection h,
injection h with hβ hβ,
injection hβ with hβ hβ,
exact const_inj hβ }β©
theorem smn : β f : code β β β code,
computableβ f β§ β c n x, eval (f c n) x = eval c (mkpair n x) :=
β¨curry, primrecβ.to_comp curry_prim, eval_curryβ©
theorem exists_code {f : β β. β} : nat.partrec f β β c : code, eval c = f :=
β¨Ξ» h, begin
induction h,
case nat.partrec.zero { exact β¨zero, rflβ© },
case nat.partrec.succ { exact β¨succ, rflβ© },
case nat.partrec.left { exact β¨left, rflβ© },
case nat.partrec.right { exact β¨right, rflβ© },
case nat.partrec.pair : f g pf pg hf hg
{ rcases hf with β¨cf, rflβ©, rcases hg with β¨cg, rflβ©,
exact β¨pair cf cg, rflβ© },
case nat.partrec.comp : f g pf pg hf hg
{ rcases hf with β¨cf, rflβ©, rcases hg with β¨cg, rflβ©,
exact β¨comp cf cg, rflβ© },
case nat.partrec.prec : f g pf pg hf hg
{ rcases hf with β¨cf, rflβ©, rcases hg with β¨cg, rflβ©,
exact β¨prec cf cg, rflβ© },
case nat.partrec.rfind : f pf hf
{ rcases hf with β¨cf, rflβ©,
refine β¨comp (rfind' cf) (pair code.id zero), _β©,
simp [eval, (<*>), pure, pfun.pure, part.map_id'] },
end, Ξ» h, begin
rcases h with β¨c, rflβ©, induction c,
case nat.partrec.code.zero { exact nat.partrec.zero },
case nat.partrec.code.succ { exact nat.partrec.succ },
case nat.partrec.code.left { exact nat.partrec.left },
case nat.partrec.code.right { exact nat.partrec.right },
case nat.partrec.code.pair : cf cg pf pg { exact pf.pair pg },
case nat.partrec.code.comp : cf cg pf pg { exact pf.comp pg },
case nat.partrec.code.prec : cf cg pf pg { exact pf.prec pg },
case nat.partrec.code.rfind' : cf pf { exact pf.rfind' },
endβ©
def evaln : β k : β, code β β β option β
| 0 _ := Ξ» m, none
| (k+1) zero := Ξ» n, guard (n β€ k) >> pure 0
| (k+1) succ := Ξ» n, guard (n β€ k) >> pure (nat.succ n)
| (k+1) left := Ξ» n, guard (n β€ k) >> pure n.unpair.1
| (k+1) right := Ξ» n, guard (n β€ k) >> pure n.unpair.2
| (k+1) (pair cf cg) := Ξ» n, guard (n β€ k) >>
mkpair <$> evaln (k+1) cf n <*> evaln (k+1) cg n
| (k+1) (comp cf cg) := Ξ» n, guard (n β€ k) >>
do x β evaln (k+1) cg n, evaln (k+1) cf x
| (k+1) (prec cf cg) := Ξ» n, guard (n β€ k) >>
n.unpaired (Ξ» a n,
n.cases (evaln (k+1) cf a) $ Ξ» y, do
i β evaln k (prec cf cg) (mkpair a y),
evaln (k+1) cg (mkpair a (mkpair y i)))
| (k+1) (rfind' cf) := Ξ» n, guard (n β€ k) >>
n.unpaired (Ξ» a m, do
x β evaln (k+1) cf (mkpair a m),
if x = 0 then pure m else
evaln k (rfind' cf) (mkpair a (m+1)))
theorem evaln_bound : β {k c n x}, x β evaln k c n β n < k
| 0 c n x h := by simp [evaln] at h; cases h
| (k+1) c n x h := begin
suffices : β {o : option β}, x β guard (n β€ k) >> o β n < k + 1,
{ cases c; rw [evaln] at h; exact this h },
simpa [(>>)] using nat.lt_succ_of_le
end
theorem evaln_mono : β {kβ kβ c n x}, kβ β€ kβ β x β evaln kβ c n β x β evaln kβ c n
| 0 kβ c n x hl h := by simp [evaln] at h; cases h
| (k+1) (kβ+1) c n x hl h := begin
have hl' := nat.le_of_succ_le_succ hl,
have : β {k kβ n x : β} {oβ oβ : option β},
k β€ kβ β (x β oβ β x β oβ) β x β guard (n β€ k) >> oβ β x β guard (n β€ kβ) >> oβ,
{ simp [(>>)], introv h hβ hβ hβ, exact β¨le_trans hβ h, hβ hββ© },
simp at h β’,
induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n;
rw [evaln] at h β’; refine this hl' (Ξ» h, _) h,
iterate 4 {exact h},
{ -- pair cf cg
simp [(<*>)] at h β’,
exact h.imp (Ξ» a, and.imp (hf _ _) $ Exists.imp $ Ξ» b, and.imp_left (hg _ _)) },
{ -- comp cf cg
simp at h β’,
exact h.imp (Ξ» a, and.imp (hg _ _) (hf _ _)) },
{ -- prec cf cg
revert h, simp,
induction n.unpair.2; simp,
{ apply hf },
{ exact Ξ» y hβ hβ, β¨y, evaln_mono hl' hβ, hg _ _ hββ© } },
{ -- rfind' cf
simp at h β’,
refine h.imp (Ξ» x, and.imp (hf _ _) _),
by_cases x0 : x = 0; simp [x0],
exact evaln_mono hl' }
end
theorem evaln_sound : β {k c n x}, x β evaln k c n β x β eval c n
| 0 _ n x h := by simp [evaln] at h; cases h
| (k+1) c n x h := begin
induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n;
simp [eval, evaln, (>>), (<*>)] at h β’; cases h with _ h,
iterate 4 {simpa [pure, pfun.pure, eq_comm] using h},
{ -- pair cf cg
rcases h with β¨y, ef, z, eg, rflβ©,
exact β¨_, hf _ _ ef, _, hg _ _ eg, rflβ© },
{ --comp hf hg
rcases h with β¨y, eg, efβ©,
exact β¨_, hg _ _ eg, hf _ _ efβ© },
{ -- prec cf cg
revert h,
induction n.unpair.2 with m IH generalizing x; simp,
{ apply hf },
{ refine Ξ» y hβ hβ, β¨y, IH _ _, _β©,
{ have := evaln_mono k.le_succ hβ,
simp [evaln, (>>)] at this,
exact this.2 },
{ exact hg _ _ hβ } } },
{ -- rfind' cf
rcases h with β¨m, hβ, hββ©,
by_cases m0 : m = 0; simp [m0] at hβ,
{ exact β¨0,
β¨by simpa [m0] using hf _ _ hβ,
Ξ» m, (nat.not_lt_zero _).elimβ©,
by injection hβ with hβ; simp [hβ]β© },
{ have := evaln_sound hβ, simp [eval] at this,
rcases this with β¨y, β¨hyβ, hyββ©, rflβ©,
refine β¨ y+1, β¨by simpa [add_comm, add_left_comm] using hyβ, Ξ» i im, _β©,
by simp [add_comm, add_left_comm] β©,
cases i with i,
{ exact β¨m, by simpa using hf _ _ hβ, m0β© },
{ rcases hyβ (nat.lt_of_succ_lt_succ im) with β¨z, hz, z0β©,
exact β¨z, by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hz, z0β© } } }
end
theorem evaln_complete {c n x} : x β eval c n β β k, x β evaln k c n :=
β¨Ξ» h, begin
suffices : β k, x β evaln (k+1) c n,
{ exact let β¨k, hβ© := this in β¨k+1, hβ© },
induction c generalizing n x;
simp [eval, evaln, pure, pfun.pure, (<*>), (>>)] at h β’,
iterate 4 { exact β¨β¨_, le_rflβ©, h.symmβ© },
case nat.partrec.code.pair : cf cg hf hg
{ rcases h with β¨x, hx, y, hy, rflβ©,
rcases hf hx with β¨kβ, hkββ©, rcases hg hy with β¨kβ, hkββ©,
refine β¨max kβ kβ, _β©,
refine β¨le_max_of_le_left $ nat.le_of_lt_succ $ evaln_bound hkβ,
_, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hkβ,
_, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hkβ, rflβ© },
case nat.partrec.code.comp : cf cg hf hg
{ rcases h with β¨y, hy, hxβ©,
rcases hg hy with β¨kβ, hkββ©, rcases hf hx with β¨kβ, hkββ©,
refine β¨max kβ kβ, _β©,
exact β¨le_max_of_le_left $ nat.le_of_lt_succ $ evaln_bound hkβ, _,
evaln_mono (nat.succ_le_succ $ le_max_left _ _) hkβ,
evaln_mono (nat.succ_le_succ $ le_max_right _ _) hkββ© },
case nat.partrec.code.prec : cf cg hf hg
{ revert h,
generalize : n.unpair.1 = nβ, generalize : n.unpair.2 = nβ,
induction nβ with m IH generalizing x n; simp,
{ intro, rcases hf h with β¨k, hkβ©,
exact β¨_, le_max_left _ _,
evaln_mono (nat.succ_le_succ $ le_max_right _ _) hkβ© },
{ intros y hy hx,
rcases IH hy with β¨kβ, nkβ, hkββ©, rcases hg hx with β¨kβ, hkββ©,
refine β¨(max kβ kβ).succ, nat.le_succ_of_le $ le_max_of_le_left $
le_trans (le_max_left _ (mkpair nβ m)) nkβ, y,
evaln_mono (nat.succ_le_succ $ le_max_left _ _) _,
evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_right _ _) hkββ©,
simp [evaln, (>>)],
exact β¨le_trans (le_max_right _ _) nkβ, hkββ© } },
case nat.partrec.code.rfind' : cf hf
{ rcases h with β¨y, β¨hyβ, hyββ©, rflβ©,
suffices : β k, y + n.unpair.2 β evaln (k+1) (rfind' cf)
(mkpair n.unpair.1 n.unpair.2), {simpa [evaln, (>>)]},
revert hyβ hyβ, generalize : n.unpair.2 = m, intros,
induction y with y IH generalizing m; simp [evaln, (>>)],
{ simp at hyβ, rcases hf hyβ with β¨k, hkβ©,
exact β¨_, nat.le_of_lt_succ $ evaln_bound hk, _, hk, by simp; reflβ© },
{ rcases hyβ (nat.succ_pos _) with β¨a, ha, a0β©,
rcases hf ha with β¨kβ, hkββ©,
rcases IH m.succ
(by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hyβ)
(Ξ» i hi, by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using
hyβ (nat.succ_lt_succ hi))
with β¨kβ, hkββ©,
use (max kβ kβ).succ,
rw [zero_add] at hkβ,
use (nat.le_succ_of_le $ le_max_of_le_left $ nat.le_of_lt_succ $ evaln_bound hkβ),
use a,
use evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_left _ _) hkβ,
simpa [nat.succ_eq_add_one, a0, -max_eq_left, -max_eq_right, add_comm, add_left_comm] using
evaln_mono (nat.succ_le_succ $ le_max_right _ _) hkβ } }
end, Ξ» β¨k, hβ©, evaln_sound hβ©
section
open primrec
private def lup (L : list (list (option β))) (p : β Γ code) (n : β) :=
do l β L.nth (encode p), o β l.nth n, o
private lemma hlup : primrec (Ξ» p:_Γ(_Γ_)Γ_, lup p.1 p.2.1 p.2.2) :=
option_bind
(list_nth.comp fst (primrec.encode.comp $ fst.comp snd))
(option_bind (list_nth.comp snd $ snd.comp $ snd.comp fst) snd)
private def G (L : list (list (option β))) : option (list (option β)) :=
option.some $
let a := of_nat (β Γ code) L.length,
k := a.1, c := a.2 in
(list.range k).map (Ξ» n,
k.cases none $ Ξ» k',
nat.partrec.code.rec_on c
(some 0) -- zero
(some (nat.succ n))
(some n.unpair.1)
(some n.unpair.2)
(Ξ» cf cg _ _, do
x β lup L (k, cf) n,
y β lup L (k, cg) n,
some (mkpair x y))
(Ξ» cf cg _ _, do
x β lup L (k, cg) n,
lup L (k, cf) x)
(Ξ» cf cg _ _,
let z := n.unpair.1 in
n.unpair.2.cases
(lup L (k, cf) z)
(Ξ» y, do
i β lup L (k', c) (mkpair z y),
lup L (k, cg) (mkpair z (mkpair y i))))
(Ξ» cf _,
let z := n.unpair.1, m := n.unpair.2 in do
x β lup L (k, cf) (mkpair z m),
x.cases
(some m)
(Ξ» _, lup L (k', c) (mkpair z (m+1)))))
private lemma hG : primrec G :=
begin
have a := (primrec.of_nat (β Γ code)).comp list_length,
have k := fst.comp a,
refine option_some.comp
(list_map (list_range.comp k) (_ : primrec _)),
replace k := k.comp fst, have n := snd,
refine nat_cases k (const none) (_ : primrec _),
have k := k.comp fst, have n := n.comp fst, have k' := snd,
have c := snd.comp (a.comp $ fst.comp fst),
apply rec_prim c
(const (some 0))
(option_some.comp (primrec.succ.comp n))
(option_some.comp (fst.comp $ primrec.unpair.comp n))
(option_some.comp (snd.comp $ primrec.unpair.comp n)),
{ have L := (fst.comp fst).comp fst,
have k := k.comp fst, have n := n.comp fst,
have cf := fst.comp snd,
have cg := (fst.comp snd).comp snd,
exact option_bind
(hlup.comp $ L.pair $ (k.pair cf).pair n)
(option_map ((hlup.comp $
L.pair $ (k.pair cg).pair n).comp fst)
(primrecβ.mkpair.comp (snd.comp fst) snd)) },
{ have L := (fst.comp fst).comp fst,
have k := k.comp fst, have n := n.comp fst,
have cf := fst.comp snd,
have cg := (fst.comp snd).comp snd,
exact option_bind
(hlup.comp $ L.pair $ (k.pair cg).pair n)
(hlup.comp ((L.comp fst).pair $
((k.pair cf).comp fst).pair snd)) },
{ have L := (fst.comp fst).comp fst,
have k := k.comp fst, have n := n.comp fst,
have cf := fst.comp snd,
have cg := (fst.comp snd).comp snd,
have z := fst.comp (primrec.unpair.comp n),
refine nat_cases
(snd.comp (primrec.unpair.comp n))
(hlup.comp $ L.pair $ (k.pair cf).pair z)
(_ : primrec _),
have L := L.comp fst, have z := z.comp fst, have y := snd,
refine option_bind
(hlup.comp $ L.pair $
(((k'.pair c).comp fst).comp fst).pair
(primrecβ.mkpair.comp z y))
(_ : primrec _),
have z := z.comp fst, have y := y.comp fst, have i := snd,
exact hlup.comp ((L.comp fst).pair $
((k.pair cg).comp $ fst.comp fst).pair $
primrecβ.mkpair.comp z $ primrecβ.mkpair.comp y i) },
{ have L := (fst.comp fst).comp fst,
have k := k.comp fst, have n := n.comp fst,
have cf := fst.comp snd,
have z := fst.comp (primrec.unpair.comp n),
have m := snd.comp (primrec.unpair.comp n),
refine option_bind
(hlup.comp $ L.pair $ (k.pair cf).pair (primrecβ.mkpair.comp z m))
(_ : primrec _),
have m := m.comp fst,
exact nat_cases snd (option_some.comp m)
((hlup.comp ((L.comp fst).pair $
((k'.pair c).comp $ fst.comp fst).pair
(primrecβ.mkpair.comp (z.comp fst)
(primrec.succ.comp m)))).comp fst) }
end
private lemma evaln_map (k c n) :
(((list.range k).nth n).map (evaln k c)).bind (Ξ» b, b) = evaln k c n :=
begin
by_cases kn : n < k,
{ simp [list.nth_range kn] },
{ rw list.nth_len_le,
{ cases e : evaln k c n, {refl},
exact kn.elim (evaln_bound e) },
simpa using kn }
end
theorem evaln_prim : primrec (Ξ» (a : (β Γ code) Γ β), evaln a.1.1 a.1.2 a.2) :=
have primrecβ (Ξ» (_:unit) (n : β),
let a := of_nat (β Γ code) n in
(list.range a.1).map (evaln a.1 a.2)), from
primrec.nat_strong_rec _ (hG.comp snd).toβ $
Ξ» _ p, begin
simp [G],
rw (_ : (of_nat (β Γ code) _).snd =
of_nat code p.unpair.2), swap, {simp},
apply list.map_congr (Ξ» n, _),
rw (by simp : list.range p = list.range
(mkpair p.unpair.1 (encode (of_nat code p.unpair.2)))),
generalize : p.unpair.1 = k,
generalize : of_nat code p.unpair.2 = c,
intro nk,
cases k with k', {simp [evaln]},
let k := k'+1, change k'.succ with k,
simp [nat.lt_succ_iff] at nk,
have hg : β {k' c' n},
mkpair k' (encode c') < mkpair k (encode c) β
lup ((list.range (mkpair k (encode c))).map (Ξ» n,
(list.range n.unpair.1).map
(evaln n.unpair.1 (of_nat code n.unpair.2))))
(k', c') n = evaln k' c' n,
{ intros kβ cβ nβ hl,
simp [lup, list.nth_range hl, evaln_map, (>>=)] },
cases c with cf cg cf cg cf cg cf;
simp [evaln, nk, (>>), (>>=), (<$>), (<*>), pure],
{ cases encode_lt_pair cf cg with lf lg,
rw [hg (nat.mkpair_lt_mkpair_right _ lf),
hg (nat.mkpair_lt_mkpair_right _ lg)],
cases evaln k cf n, {refl},
cases evaln k cg n; refl },
{ cases encode_lt_comp cf cg with lf lg,
rw hg (nat.mkpair_lt_mkpair_right _ lg),
cases evaln k cg n, {refl},
simp [hg (nat.mkpair_lt_mkpair_right _ lf)] },
{ cases encode_lt_prec cf cg with lf lg,
rw hg (nat.mkpair_lt_mkpair_right _ lf),
cases n.unpair.2, {refl},
simp,
rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self),
cases evaln k' _ _, {refl},
simp [hg (nat.mkpair_lt_mkpair_right _ lg)] },
{ have lf := encode_lt_rfind' cf,
rw hg (nat.mkpair_lt_mkpair_right _ lf),
cases evaln k cf n with x, {refl},
simp,
cases x; simp [nat.succ_ne_zero],
rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self) }
end,
(option_bind (list_nth.comp
(this.comp (const ()) (encode_iff.2 fst)) snd)
snd.toβ).of_eq $ Ξ» β¨β¨k, cβ©, nβ©, by simp [evaln_map]
end
section
open partrec computable
theorem eval_eq_rfind_opt (c n) :
eval c n = nat.rfind_opt (Ξ» k, evaln k c n) :=
part.ext $ Ξ» x, begin
refine evaln_complete.trans (nat.rfind_opt_mono _).symm,
intros a m n hl, apply evaln_mono hl,
end
theorem eval_part : partrecβ eval :=
(rfind_opt (evaln_prim.to_comp.comp
((snd.pair (fst.comp fst)).pair (snd.comp fst))).toβ).of_eq $
Ξ» a, by simp [eval_eq_rfind_opt]
theorem fixed_point
{f : code β code} (hf : computable f) : β c : code, eval (f c) = eval c :=
let g (x y : β) : part β :=
eval (of_nat code x) x >>= Ξ» b, eval (of_nat code b) y in
have partrecβ g :=
(eval_part.comp ((computable.of_nat _).comp fst) fst).bind
(eval_part.comp ((computable.of_nat _).comp snd) (snd.comp fst)).toβ,
let β¨cg, egβ© := exists_code.1 this in
have eg' : β a n, eval cg (mkpair a n) = part.map encode (g a n) :=
by simp [eg],
let F (x : β) : code := f (curry cg x) in
have computable F :=
hf.comp (curry_prim.comp (primrec.const cg) primrec.id).to_comp,
let β¨cF, eFβ© := exists_code.1 this in
have eF' : eval cF (encode cF) = part.some (encode (F (encode cF))),
by simp [eF],
β¨curry cg (encode cF), funext (Ξ» n,
show eval (f (curry cg (encode cF))) n = eval (curry cg (encode cF)) n,
by simp [eg', eF', part.map_id', g])β©
theorem fixed_pointβ
{f : code β β β. β} (hf : partrecβ f) : β c : code, eval c = f c :=
let β¨cf, efβ© := exists_code.1 hf in
(fixed_point (curry_prim.comp
(primrec.const cf) primrec.encode).to_comp).imp $
Ξ» c e, funext $ Ξ» n, by simp [e.symm, ef, part.map_id']
end
end nat.partrec.code
|
6285cf4e87f67a724dd95ca0a5a7b49f2cf388f8 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/lean/run/evalconst.lean | f054de2a8f9fb012b20cdb0d372682703e26aaed | [
"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 | 340 | lean | import Init.Lean
open Lean
def x := 10
unsafe def tst : MetaIO Unit := do
env β MetaIO.getEnv;
IO.println $ env.evalConst Nat `x;
pure ()
#eval tst
def f (x : Nat) := x + 1
unsafe def tst2 : MetaIO Unit := do
env β MetaIO.getEnv;
f β liftM $ IO.ofExcept $ env.evalConst (Nat β Nat) `f;
IO.println $ (f 10);
pure ()
#eval tst2
|
c10127039924eb4f0400fb6b093dc9c94690c41f | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/968.lean | 1710d734856ff5b2251d59aa9b4aa32cc10ade5a | [
"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 | 224 | lean | variables (A : Type) [inhabited A]
definition f (a : A) : A := a
check @f nat nat.is_inhabited
structure foo :=
(a : A)
check @foo nat nat.is_inhabited
inductive bla :=
| mk : A β bla
check @bla nat nat.is_inhabited
|
898a541cae70b6e0d2609a26cde597062a21d46a | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/category_theory/concrete_category/bundled_hom.lean | 4a012f2a5c1f2294706ef1698d1dc795ce7d8162 | [
"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 | 5,778 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Yury Kudryashov
-/
import category_theory.concrete_category.basic
import category_theory.concrete_category.bundled
import category_theory.fully_faithful
/-!
# Category instances for algebraic structures that use bundled homs.
Many algebraic structures in Lean initially used unbundled homs (e.g. a bare function between types,
along with an `is_monoid_hom` typeclass), but the general trend is towards using bundled homs.
This file provides a basic infrastructure to define concrete categories using bundled homs, and
define forgetful functors between them.
-/
universes u
namespace category_theory
variables {c : Type u β Type u} (hom : Ξ β¦Ξ± Ξ² : Type uβ¦ (IΞ± : c Ξ±) (IΞ² : c Ξ²), Type u)
/-- Class for bundled homs. Note that the arguments order follows that of lemmas for `monoid_hom`.
This way we can use `β¨@monoid_hom.to_fun, @monoid_hom.id ...β©` in an instance. -/
structure bundled_hom :=
(to_fun : Ξ {Ξ± Ξ² : Type u} (IΞ± : c Ξ±) (IΞ² : c Ξ²), hom IΞ± IΞ² β Ξ± β Ξ²)
(id : Ξ {Ξ± : Type u} (I : c Ξ±), hom I I)
(comp : Ξ {Ξ± Ξ² Ξ³ : Type u} (IΞ± : c Ξ±) (IΞ² : c Ξ²) (IΞ³ : c Ξ³),
hom IΞ² IΞ³ β hom IΞ± IΞ² β hom IΞ± IΞ³)
(hom_ext : β {Ξ± Ξ² : Type u} (IΞ± : c Ξ±) (IΞ² : c Ξ²), function.injective (to_fun IΞ± IΞ²) . obviously)
(id_to_fun : β {Ξ± : Type u} (I : c Ξ±), to_fun I I (id I) = _root_.id . obviously)
(comp_to_fun : β {Ξ± Ξ² Ξ³ : Type u} (IΞ± : c Ξ±) (IΞ² : c Ξ²) (IΞ³ : c Ξ³)
(f : hom IΞ± IΞ²) (g : hom IΞ² IΞ³),
to_fun IΞ± IΞ³ (comp IΞ± IΞ² IΞ³ g f) = (to_fun IΞ² IΞ³ g) β (to_fun IΞ± IΞ² f) . obviously)
attribute [class] bundled_hom
attribute [simp] bundled_hom.id_to_fun bundled_hom.comp_to_fun
namespace bundled_hom
variable [π : bundled_hom hom]
include π
/-- Every `@bundled_hom c _` defines a category with objects in `bundled c`.
This instance generates the type-class problem `bundled_hom ?m` (which is why this is marked as
`[nolint]`). Currently that is not a problem, as there are almost no instances of `bundled_hom`. -/
@[nolint dangerous_instance] instance category : category (bundled c) :=
by refine
{ hom := Ξ» X Y, @hom X Y X.str Y.str,
id := Ξ» X, @bundled_hom.id c hom π X X.str,
comp := Ξ» X Y Z f g, @bundled_hom.comp c hom π X Y Z X.str Y.str Z.str g f,
comp_id' := _,
id_comp' := _,
assoc' := _};
intros; apply π.hom_ext;
simp only [π.id_to_fun, π.comp_to_fun, function.left_id, function.right_id]
/-- A category given by `bundled_hom` is a concrete category.
This instance generates the type-class problem `bundled_hom ?m` (which is why this is marked as
`[nolint]`). Currently that is not a problem, as there are almost no instances of `bundled_hom`. -/
@[nolint dangerous_instance] instance : concrete_category.{u} (bundled c) :=
{ forget := { obj := Ξ» X, X,
map := Ξ» X Y f, π.to_fun X.str Y.str f,
map_id' := Ξ» X, π.id_to_fun X.str,
map_comp' := by intros; erw π.comp_to_fun; refl },
forget_faithful := { map_injective' := by intros; apply π.hom_ext } }
variables {hom}
local attribute [instance] concrete_category.has_coe_to_fun
/-- A version of `has_forgetβ.mk'` for categories defined using `@bundled_hom`. -/
def mk_has_forgetβ {d : Type u β Type u} {hom_d : Ξ β¦Ξ± Ξ² : Type uβ¦ (IΞ± : d Ξ±) (IΞ² : d Ξ²), Type u}
[bundled_hom hom_d] (obj : Ξ β¦Ξ±β¦, c Ξ± β d Ξ±)
(map : Ξ {X Y : bundled c}, (X βΆ Y) β ((bundled.map obj X) βΆ (bundled.map obj Y)))
(h_map : β {X Y : bundled c} (f : X βΆ Y), (map f : X β Y) = f)
: has_forgetβ (bundled c) (bundled d) :=
has_forgetβ.mk'
(bundled.map @obj)
(Ξ» _, rfl)
@map
(by intros; apply heq_of_eq; apply h_map)
variables {d : Type u β Type u}
variables (hom)
section
omit π
/--
The `hom` corresponding to first forgetting along `F`, then taking the `hom` associated to `c`.
For typical usage, see the construction of `CommMon` from `Mon`.
-/
@[reducible] def map_hom (F : Ξ {Ξ±}, d Ξ± β c Ξ±) : Ξ β¦Ξ± Ξ² : Type uβ¦ (IΞ± : d Ξ±) (IΞ² : d Ξ²), Type u :=
Ξ» Ξ± Ξ² iΞ± iΞ², hom (F iΞ±) (F iΞ²)
end
/--
Construct the `bundled_hom` induced by a map between type classes.
This is useful for building categories such as `CommMon` from `Mon`.
-/
def map (F : Ξ {Ξ±}, d Ξ± β c Ξ±) : bundled_hom (map_hom hom @F) :=
{ to_fun := Ξ» Ξ± Ξ² iΞ± iΞ² f, π.to_fun (F iΞ±) (F iΞ²) f,
id := Ξ» Ξ± iΞ±, π.id (F iΞ±),
comp := Ξ» Ξ± Ξ² Ξ³ iΞ± iΞ² iΞ³ f g, π.comp (F iΞ±) (F iΞ²) (F iΞ³) f g,
hom_ext := Ξ» Ξ± Ξ² iΞ± iΞ² f g h, π.hom_ext (F iΞ±) (F iΞ²) h }
section
omit π
/--
We use the empty `parent_projection` class to label functions like `comm_monoid.to_monoid`,
which we would like to use to automatically construct `bundled_hom` instances from.
Once we've set up `Mon` as the category of bundled monoids,
this allows us to set up `CommMon` by defining an instance
```instance : parent_projection (comm_monoid.to_monoid) := β¨β©```
-/
class parent_projection (F : Ξ {Ξ±}, d Ξ± β c Ξ±)
end
@[nolint unused_arguments] -- The `parent_projection` typeclass is just a marker, so won't be used.
instance bundled_hom_of_parent_projection (F : Ξ {Ξ±}, d Ξ± β c Ξ±) [parent_projection @F] :
bundled_hom (map_hom hom @F) :=
map hom @F
instance forgetβ (F : Ξ {Ξ±}, d Ξ± β c Ξ±) [parent_projection @F] :
has_forgetβ (bundled d) (bundled c) :=
{ forgetβ :=
{ obj := Ξ» X, β¨X, F X.2β©,
map := Ξ» X Y f, f } }
instance forgetβ_full (F : Ξ {Ξ±}, d Ξ± β c Ξ±) [parent_projection @F] :
full (forgetβ (bundled d) (bundled c)) :=
{ preimage := Ξ» X Y f, f }
end bundled_hom
end category_theory
|
dccdbbb14ff4afaecc3e34cb7cf4c9cdff1224b9 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/data/polynomial/basic.lean | 3841580de0b4824bdca2b6eed75dfc22ac624968 | [
"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 | 32,299 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes HΓΆlzl, Scott Morrison, Jens Wagemaker
-/
import algebra.monoid_algebra.basic
/-!
# Theory of univariate polynomials
This file defines `polynomial R`, the type of univariate polynomials over the semiring `R`, builds
a semiring structure on it, and gives basic definitions that are expanded in other files in this
directory.
## Main definitions
* `monomial n a` is the polynomial `a X^n`. Note that `monomial n` is defined as an `R`-linear map.
* `C a` is the constant polynomial `a`. Note that `C` is defined as a ring homomorphism.
* `X` is the polynomial `X`, i.e., `monomial 1 1`.
* `p.sum f` is `β n in p.support, f n (p.coeff n)`, i.e., one sums the values of functions applied
to coefficients of the polynomial `p`.
* `p.erase n` is the polynomial `p` in which one removes the `c X^n` term.
There are often two natural variants of lemmas involving sums, depending on whether one acts on the
polynomials, or on the function. The naming convention is that one adds `index` when acting on
the polynomials. For instance,
* `sum_add_index` states that `(p + q).sum f = p.sum f + q.sum f`;
* `sum_add` states that `p.sum (Ξ» n x, f n x + g n x) = p.sum f + p.sum g`.
* Notation to refer to `polynomial R`, as `R[X]` or `R[t]`.
## Implementation
Polynomials are defined using `add_monoid_algebra R β`, where `R` is a semiring.
The variable `X` commutes with every polynomial `p`: lemma `X_mul` proves the identity
`X * p = `p * X`. The relationship to `add_monoid_algebra R β` is through a structure
to make polynomials irreducible from the point of view of the kernel. Most operations
are irreducible since Lean can not compute anyway with `add_monoid_algebra`. There are two
exceptions that we make semireducible:
* The zero polynomial, so that its coefficients are definitionally equal to `0`.
* The scalar action, to permit typeclass search to unfold it to resolve potential instance
diamonds.
The raw implementation of the equivalence between `polynomial R` and `add_monoid_algebra R β` is
done through `of_finsupp` and `to_finsupp` (or, equivalently, `rcases p` when `p` is a polynomial
gives an element `q` of `add_monoid_algebra R β`, and conversely `β¨qβ©` gives back `p`). The
equivalence is also registered as a ring equiv in `polynomial.to_finsupp_iso`. These should
in general not be used once the basic API for polynomials is constructed.
-/
noncomputable theory
/-- `polynomial R` is the type of univariate polynomials over `R`.
Polynomials should be seen as (semi-)rings with the additional constructor `X`.
The embedding from `R` is called `C`. -/
structure polynomial (R : Type*) [semiring R] := of_finsupp ::
(to_finsupp : add_monoid_algebra R β)
localized "notation R`[X]`:9000 := polynomial R" in polynomial
open finsupp add_monoid_algebra
open_locale big_operators polynomial
namespace polynomial
universes u
variables {R : Type u} {a b : R} {m n : β}
section semiring
variables [semiring R] {p q : R[X]}
lemma forall_iff_forall_finsupp (P : R[X] β Prop) :
(β p, P p) β β (q : add_monoid_algebra R β), P β¨qβ© :=
β¨Ξ» h q, h β¨qβ©, Ξ» h β¨pβ©, h pβ©
lemma exists_iff_exists_finsupp (P : R[X] β Prop) :
(β p, P p) β β (q : add_monoid_algebra R β), P β¨qβ© :=
β¨Ξ» β¨β¨pβ©, hpβ©, β¨p, hpβ©, Ξ» β¨q, hqβ©, β¨β¨qβ©, hqβ© β©
/-! ### Conversions to and from `add_monoid_algebra`
Since `polynomial R` is not defeq to `add_monoid_algebra R β`, but instead is a structure wrapping
it, we have to copy across all the arithmetic operators manually, along with the lemmas about how
they unfold around `polynomial.of_finsupp` and `polynomial.to_finsupp`.
-/
section add_monoid_algebra
/-- The function version of `monomial`. Use `monomial` instead of this one. -/
@[irreducible] def monomial_fun (n : β) (a : R) : R[X] := β¨finsupp.single n aβ©
@[irreducible] private def add : R[X] β R[X] β R[X]
| β¨aβ© β¨bβ© := β¨a + bβ©
@[irreducible] private def neg {R : Type u} [ring R] : R[X] β R[X]
| β¨aβ© := β¨-aβ©
@[irreducible] private def mul : R[X] β R[X] β R[X]
| β¨aβ© β¨bβ© := β¨a * bβ©
instance : has_zero R[X] := β¨β¨0β©β©
instance : has_one R[X] := β¨monomial_fun 0 (1 : R)β©
instance : has_add R[X] := β¨addβ©
instance {R : Type u} [ring R] : has_neg R[X] := β¨negβ©
instance {R : Type u} [ring R] : has_sub R[X] := β¨Ξ» a b, a + -bβ©
instance : has_mul R[X] := β¨mulβ©
instance {S : Type*} [monoid S] [distrib_mul_action S R] : has_smul S R[X] :=
β¨Ξ» r p, β¨r β’ p.to_finsuppβ©β©
@[priority 1] -- to avoid a bug in the `ring` tactic
instance has_pow : has_pow R[X] β := { pow := Ξ» p n, npow_rec n p }
@[simp] lemma of_finsupp_zero : (β¨0β© : R[X]) = 0 :=
rfl
@[simp] lemma of_finsupp_one : (β¨1β© : R[X]) = 1 :=
begin
change (β¨1β© : R[X]) = monomial_fun 0 (1 : R),
rw [monomial_fun],
refl
end
@[simp] lemma of_finsupp_add {a b} : (β¨a + bβ© : R[X]) = β¨aβ© + β¨bβ© := show _ = add _ _, by rw add
@[simp] lemma of_finsupp_neg {R : Type u} [ring R] {a} : (β¨-aβ© : R[X]) = -β¨aβ© :=
show _ = neg _, by rw neg
@[simp] lemma of_finsupp_sub {R : Type u} [ring R] {a b} : (β¨a - bβ© : R[X]) = β¨aβ© - β¨bβ© :=
by { rw [sub_eq_add_neg, of_finsupp_add, of_finsupp_neg], refl }
@[simp] lemma of_finsupp_mul (a b) : (β¨a * bβ© : R[X]) = β¨aβ© * β¨bβ© := show _ = mul _ _, by rw mul
@[simp] lemma of_finsupp_smul {S : Type*} [monoid S] [distrib_mul_action S R] (a : S) (b) :
(β¨a β’ bβ© : R[X]) = (a β’ β¨bβ© : R[X]) := rfl
@[simp] lemma of_finsupp_pow (a) (n : β) : (β¨a ^ nβ© : R[X]) = β¨aβ© ^ n :=
begin
change _ = npow_rec n _,
induction n,
{ simp [npow_rec], } ,
{ simp [npow_rec, n_ih, pow_succ] }
end
@[simp] lemma to_finsupp_zero : (0 : R[X]).to_finsupp = 0 :=
rfl
@[simp] lemma to_finsupp_one : (1 : R[X]).to_finsupp = 1 :=
begin
change to_finsupp (monomial_fun _ _) = _,
rw monomial_fun,
refl,
end
@[simp] lemma to_finsupp_add (a b : R[X]) : (a + b).to_finsupp = a.to_finsupp + b.to_finsupp :=
by { cases a, cases b, rw βof_finsupp_add }
@[simp] lemma to_finsupp_neg {R : Type u} [ring R] (a : R[X]) : (-a).to_finsupp = -a.to_finsupp :=
by { cases a, rw βof_finsupp_neg }
@[simp] lemma to_finsupp_sub {R : Type u} [ring R] (a b : R[X]) :
(a - b).to_finsupp = a.to_finsupp - b.to_finsupp :=
by { rw [sub_eq_add_neg, βto_finsupp_neg, βto_finsupp_add], refl }
@[simp] lemma to_finsupp_mul (a b : R[X]) : (a * b).to_finsupp = a.to_finsupp * b.to_finsupp :=
by { cases a, cases b, rw βof_finsupp_mul }
@[simp] lemma to_finsupp_smul {S : Type*} [monoid S] [distrib_mul_action S R] (a : S) (b : R[X]) :
(a β’ b).to_finsupp = a β’ b.to_finsupp := rfl
@[simp] lemma to_finsupp_pow (a : R[X]) (n : β) : (a ^ n).to_finsupp = a.to_finsupp ^ n :=
by { cases a, rw βof_finsupp_pow }
lemma _root_.is_smul_regular.polynomial {S : Type*} [monoid S] [distrib_mul_action S R] {a : S}
(ha : is_smul_regular R a) : is_smul_regular R[X] a
| β¨xβ© β¨yβ© h := congr_arg _ $ ha.finsupp (polynomial.of_finsupp.inj h)
lemma to_finsupp_injective : function.injective (to_finsupp : R[X] β add_monoid_algebra _ _) :=
Ξ» β¨xβ© β¨yβ©, congr_arg _
@[simp] lemma to_finsupp_inj {a b : R[X]} : a.to_finsupp = b.to_finsupp β a = b :=
to_finsupp_injective.eq_iff
@[simp] lemma to_finsupp_eq_zero {a : R[X]} : a.to_finsupp = 0 β a = 0 :=
by rw [βto_finsupp_zero, to_finsupp_inj]
@[simp] lemma to_finsupp_eq_one {a : R[X]} : a.to_finsupp = 1 β a = 1 :=
by rw [βto_finsupp_one, to_finsupp_inj]
/-- A more convenient spelling of `polynomial.of_finsupp.inj_eq` in terms of `iff`. -/
lemma of_finsupp_inj {a b} : (β¨aβ© : R[X]) = β¨bβ© β a = b :=
iff_of_eq of_finsupp.inj_eq
@[simp] lemma of_finsupp_eq_zero {a} : (β¨aβ© : R[X]) = 0 β a = 0 :=
by rw [βof_finsupp_zero, of_finsupp_inj]
@[simp] lemma of_finsupp_eq_one {a} : (β¨aβ© : R[X]) = 1 β a = 1 :=
by rw [βof_finsupp_one, of_finsupp_inj]
instance : inhabited R[X] := β¨0β©
instance : has_nat_cast R[X] := β¨Ξ» n, polynomial.of_finsupp nβ©
instance : semiring R[X] :=
function.injective.semiring to_finsupp to_finsupp_injective
to_finsupp_zero to_finsupp_one to_finsupp_add to_finsupp_mul
(Ξ» _ _, to_finsupp_smul _ _) to_finsupp_pow (Ξ» _, rfl)
instance {S} [monoid S] [distrib_mul_action S R] : distrib_mul_action S R[X] :=
function.injective.distrib_mul_action
β¨to_finsupp, to_finsupp_zero, to_finsupp_addβ© to_finsupp_injective to_finsupp_smul
instance {S} [monoid S] [distrib_mul_action S R] [has_faithful_smul S R] :
has_faithful_smul S R[X] :=
{ eq_of_smul_eq_smul := Ξ» sβ sβ h, eq_of_smul_eq_smul $ Ξ» a : β ββ R, congr_arg to_finsupp (h β¨aβ©) }
instance {S} [semiring S] [module S R] : module S R[X] :=
function.injective.module _
β¨to_finsupp, to_finsupp_zero, to_finsupp_addβ© to_finsupp_injective to_finsupp_smul
instance {Sβ Sβ} [monoid Sβ] [monoid Sβ] [distrib_mul_action Sβ R] [distrib_mul_action Sβ R]
[smul_comm_class Sβ Sβ R] : smul_comm_class Sβ Sβ R[X] :=
β¨by { rintros _ _ β¨β©, simp_rw [βof_finsupp_smul, smul_comm] }β©
instance {Sβ Sβ} [has_smul Sβ Sβ] [monoid Sβ] [monoid Sβ] [distrib_mul_action Sβ R]
[distrib_mul_action Sβ R] [is_scalar_tower Sβ Sβ R] : is_scalar_tower Sβ Sβ R[X] :=
β¨by { rintros _ _ β¨β©, simp_rw [βof_finsupp_smul, smul_assoc] }β©
instance {S} [monoid S] [distrib_mul_action S R] [distrib_mul_action Sα΅α΅α΅ R]
[is_central_scalar S R] : is_central_scalar S R[X] :=
β¨by { rintros _ β¨β©, simp_rw [βof_finsupp_smul, op_smul_eq_smul] }β©
instance [subsingleton R] : unique R[X] :=
{ uniq := by { rintros β¨xβ©, refine congr_arg of_finsupp _, simp },
.. polynomial.inhabited }
variable (R)
/-- Ring isomorphism between `R[X]` and `add_monoid_algebra R β`. This is just an
implementation detail, but it can be useful to transfer results from `finsupp` to polynomials. -/
@[simps apply symm_apply]
def to_finsupp_iso : R[X] β+* add_monoid_algebra R β :=
{ to_fun := to_finsupp,
inv_fun := of_finsupp,
left_inv := Ξ» β¨pβ©, rfl,
right_inv := Ξ» p, rfl,
map_mul' := to_finsupp_mul,
map_add' := to_finsupp_add }
end add_monoid_algebra
variable {R}
lemma of_finsupp_sum {ΞΉ : Type*} (s : finset ΞΉ) (f : ΞΉ β add_monoid_algebra R β) :
(β¨β i in s, f iβ© : R[X]) = β i in s, β¨f iβ© :=
map_sum (to_finsupp_iso R).symm f s
lemma to_finsupp_sum {ΞΉ : Type*} (s : finset ΞΉ) (f : ΞΉ β R[X]) :
(β i in s, f i : R[X]).to_finsupp = β i in s, (f i).to_finsupp :=
map_sum (to_finsupp_iso R) f s
/--
The set of all `n` such that `X^n` has a non-zero coefficient.
-/
@[simp]
def support : R[X] β finset β
| β¨pβ© := p.support
@[simp] lemma support_of_finsupp (p) : support (β¨pβ© : R[X]) = p.support :=
by rw support
@[simp] lemma support_zero : (0 : R[X]).support = β
:=
rfl
@[simp] lemma support_eq_empty : p.support = β
β p = 0 :=
by { rcases p, simp [support] }
lemma card_support_eq_zero : p.support.card = 0 β p = 0 :=
by simp
/-- `monomial s a` is the monomial `a * X^s` -/
def monomial (n : β) : R ββ[R] R[X] :=
{ to_fun := monomial_fun n,
map_add' := by simp [monomial_fun],
map_smul' := by simp [monomial_fun, βof_finsupp_smul] }
@[simp] lemma to_finsupp_monomial (n : β) (r : R) :
(monomial n r).to_finsupp = finsupp.single n r :=
by simp [monomial, monomial_fun]
@[simp] lemma of_finsupp_single (n : β) (r : R) :
(β¨finsupp.single n rβ© : R[X]) = monomial n r :=
by simp [monomial, monomial_fun]
@[simp]
lemma monomial_zero_right (n : β) :
monomial n (0 : R) = 0 :=
(monomial n).map_zero
-- This is not a `simp` lemma as `monomial_zero_left` is more general.
lemma monomial_zero_one : monomial 0 (1 : R) = 1 := rfl
-- TODO: can't we just delete this one?
lemma monomial_add (n : β) (r s : R) :
monomial n (r + s) = monomial n r + monomial n s :=
(monomial n).map_add _ _
lemma monomial_mul_monomial (n m : β) (r s : R) :
monomial n r * monomial m s = monomial (n + m) (r * s) :=
to_finsupp_injective $
by simp only [to_finsupp_monomial, to_finsupp_mul, add_monoid_algebra.single_mul_single]
@[simp]
lemma monomial_pow (n : β) (r : R) (k : β) :
(monomial n r)^k = monomial (n*k) (r^k) :=
begin
induction k with k ih,
{ simp [pow_zero, monomial_zero_one], },
{ simp [pow_succ, ih, monomial_mul_monomial, nat.succ_eq_add_one, mul_add, add_comm] },
end
lemma smul_monomial {S} [monoid S] [distrib_mul_action S R] (a : S) (n : β) (b : R) :
a β’ monomial n b = monomial n (a β’ b) :=
to_finsupp_injective $ by simp
lemma monomial_injective (n : β) :
function.injective (monomial n : R β R[X]) :=
begin
convert (to_finsupp_iso R).symm.injective.comp (single_injective n),
ext,
simp
end
@[simp] lemma monomial_eq_zero_iff (t : R) (n : β) :
monomial n t = 0 β t = 0 :=
linear_map.map_eq_zero_iff _ (polynomial.monomial_injective n)
lemma support_add : (p + q).support β p.support βͺ q.support :=
begin
rcases p, rcases q,
simp only [βof_finsupp_add, support],
exact support_add
end
/--
`C a` is the constant polynomial `a`.
`C` is provided as a ring homomorphism.
-/
def C : R β+* R[X] :=
{ map_one' := by simp [monomial_zero_one],
map_mul' := by simp [monomial_mul_monomial],
map_zero' := by simp,
.. monomial 0 }
@[simp] lemma monomial_zero_left (a : R) : monomial 0 a = C a := rfl
@[simp] lemma to_finsupp_C (a : R) : (C a).to_finsupp = single 0 a :=
by rw [βmonomial_zero_left, to_finsupp_monomial]
lemma C_0 : C (0 : R) = 0 := by simp
lemma C_1 : C (1 : R) = 1 := rfl
lemma C_mul : C (a * b) = C a * C b := C.map_mul a b
lemma C_add : C (a + b) = C a + C b := C.map_add a b
@[simp] lemma smul_C {S} [monoid S] [distrib_mul_action S R] (s : S) (r : R) :
s β’ C r = C (s β’ r) :=
smul_monomial _ _ r
@[simp] lemma C_bit0 : C (bit0 a) = bit0 (C a) := C_add
@[simp] lemma C_bit1 : C (bit1 a) = bit1 (C a) := by simp [bit1, C_bit0]
lemma C_pow : C (a ^ n) = C a ^ n := C.map_pow a n
@[simp]
lemma C_eq_nat_cast (n : β) : C (n : R) = (n : R[X]) :=
map_nat_cast C n
@[simp] lemma C_mul_monomial : C a * monomial n b = monomial n (a * b) :=
by simp only [βmonomial_zero_left, monomial_mul_monomial, zero_add]
@[simp] lemma monomial_mul_C : monomial n a * C b = monomial n (a * b) :=
by simp only [βmonomial_zero_left, monomial_mul_monomial, add_zero]
/-- `X` is the polynomial variable (aka indeterminate). -/
def X : R[X] := monomial 1 1
lemma monomial_one_one_eq_X : monomial 1 (1 : R) = X := rfl
lemma monomial_one_right_eq_X_pow (n : β) : monomial n (1 : R) = X^n :=
begin
induction n with n ih,
{ simp [monomial_zero_one], },
{ rw [pow_succ, βih, βmonomial_one_one_eq_X, monomial_mul_monomial, add_comm, one_mul], }
end
/-- `X` commutes with everything, even when the coefficients are noncommutative. -/
lemma X_mul : X * p = p * X :=
begin
rcases p,
simp only [X, βof_finsupp_single, βof_finsupp_mul, linear_map.coe_mk],
ext,
simp [add_monoid_algebra.mul_apply, sum_single_index, add_comm],
end
lemma X_pow_mul {n : β} : X^n * p = p * X^n :=
begin
induction n with n ih,
{ simp, },
{ conv_lhs { rw pow_succ', },
rw [mul_assoc, X_mul, βmul_assoc, ih, mul_assoc, βpow_succ'], }
end
/-- Prefer putting constants to the left of `X`.
This lemma is the loop-avoiding `simp` version of `polynomial.X_mul`. -/
@[simp] lemma X_mul_C (r : R) : X * C r = C r * X :=
X_mul
/-- Prefer putting constants to the left of `X ^ n`.
This lemma is the loop-avoiding `simp` version of `X_pow_mul`. -/
@[simp] lemma X_pow_mul_C (r : R) (n : β) : X^n * C r = C r * X^n :=
X_pow_mul
lemma X_pow_mul_assoc {n : β} : (p * X^n) * q = (p * q) * X^n :=
by rw [mul_assoc, X_pow_mul, βmul_assoc]
/-- Prefer putting constants to the left of `X ^ n`.
This lemma is the loop-avoiding `simp` version of `X_pow_mul_assoc`. -/
@[simp] lemma X_pow_mul_assoc_C {n : β} (r : R) : (p * X^n) * C r = p * C r * X^n :=
X_pow_mul_assoc
lemma commute_X (p : R[X]) : commute X p := X_mul
lemma commute_X_pow (p : R[X]) (n : β) : commute (X ^ n) p := X_pow_mul
@[simp]
lemma monomial_mul_X (n : β) (r : R) : monomial n r * X = monomial (n+1) r :=
by erw [monomial_mul_monomial, mul_one]
@[simp]
lemma monomial_mul_X_pow (n : β) (r : R) (k : β) : monomial n r * X^k = monomial (n+k) r :=
begin
induction k with k ih,
{ simp, },
{ simp [ih, pow_succ', βmul_assoc, add_assoc], },
end
@[simp]
lemma X_mul_monomial (n : β) (r : R) : X * monomial n r = monomial (n+1) r :=
by rw [X_mul, monomial_mul_X]
@[simp]
lemma X_pow_mul_monomial (k n : β) (r : R) : X^k * monomial n r = monomial (n+k) r :=
by rw [X_pow_mul, monomial_mul_X_pow]
/-- `coeff p n` (often denoted `p.coeff n`) is the coefficient of `X^n` in `p`. -/
@[simp] def coeff : R[X] β β β R
| β¨pβ© := p
lemma coeff_monomial : coeff (monomial n a) m = if n = m then a else 0 :=
by { simp only [βof_finsupp_single, coeff, linear_map.coe_mk], rw finsupp.single_apply }
@[simp] lemma coeff_zero (n : β) : coeff (0 : R[X]) n = 0 := rfl
@[simp] lemma coeff_one_zero : coeff (1 : R[X]) 0 = 1 :=
by { rw [β monomial_zero_one, coeff_monomial], simp }
@[simp] lemma coeff_X_one : coeff (X : R[X]) 1 = 1 := coeff_monomial
@[simp] lemma coeff_X_zero : coeff (X : R[X]) 0 = 0 := coeff_monomial
@[simp] lemma coeff_monomial_succ : coeff (monomial (n+1) a) 0 = 0 :=
by simp [coeff_monomial]
lemma coeff_X : coeff (X : R[X]) n = if 1 = n then 1 else 0 := coeff_monomial
lemma coeff_X_of_ne_one {n : β} (hn : n β 1) : coeff (X : R[X]) n = 0 :=
by rw [coeff_X, if_neg hn.symm]
@[simp] lemma mem_support_iff : n β p.support β p.coeff n β 0 :=
by { rcases p, simp }
lemma not_mem_support_iff : n β p.support β p.coeff n = 0 :=
by simp
lemma coeff_C : coeff (C a) n = ite (n = 0) a 0 :=
by { convert coeff_monomial using 2, simp [eq_comm], }
@[simp] lemma coeff_C_zero : coeff (C a) 0 = a := coeff_monomial
lemma coeff_C_ne_zero (h : n β 0) : (C a).coeff n = 0 :=
by rw [coeff_C, if_neg h]
theorem nontrivial.of_polynomial_ne (h : p β q) : nontrivial R :=
nontrivial_of_ne 0 1 $ Ξ» h01, h $
by rw [β mul_one p, β mul_one q, β C_1, β h01, C_0, mul_zero, mul_zero]
lemma monomial_eq_C_mul_X : β{n}, monomial n a = C a * X^n
| 0 := (mul_one _).symm
| (n+1) :=
calc monomial (n + 1) a = monomial n a * X : by { rw [X, monomial_mul_monomial, mul_one], }
... = (C a * X^n) * X : by rw [monomial_eq_C_mul_X]
... = C a * X^(n+1) : by simp only [pow_add, mul_assoc, pow_one]
@[simp] lemma C_inj : C a = C b β a = b :=
β¨Ξ» h, coeff_C_zero.symm.trans (h.symm βΈ coeff_C_zero), congr_arg Cβ©
@[simp] lemma C_eq_zero : C a = 0 β a = 0 :=
calc C a = 0 β C a = C 0 : by rw C_0
... β a = 0 : C_inj
theorem ext_iff {p q : R[X]} : p = q β β n, coeff p n = coeff q n :=
by { rcases p, rcases q, simp [coeff, finsupp.ext_iff] }
@[ext] lemma ext {p q : R[X]} : (β n, coeff p n = coeff q n) β p = q :=
ext_iff.2
/-- Monomials generate the additive monoid of polynomials. -/
lemma add_submonoid_closure_set_of_eq_monomial :
add_submonoid.closure {p : R[X] | β n a, p = monomial n a} = β€ :=
begin
apply top_unique,
rw [β add_submonoid.map_equiv_top (to_finsupp_iso R).symm.to_add_equiv,
β finsupp.add_closure_set_of_eq_single, add_monoid_hom.map_mclosure],
refine add_submonoid.closure_mono (set.image_subset_iff.2 _),
rintro _ β¨n, a, rflβ©,
exact β¨n, a, polynomial.of_finsupp_single _ _β©,
end
lemma add_hom_ext {M : Type*} [add_monoid M] {f g : R[X] β+ M}
(h : β n a, f (monomial n a) = g (monomial n a)) :
f = g :=
add_monoid_hom.eq_of_eq_on_mdense add_submonoid_closure_set_of_eq_monomial $
by { rintro p β¨n, a, rflβ©, exact h n a }
@[ext] lemma add_hom_ext' {M : Type*} [add_monoid M] {f g : R[X] β+ M}
(h : β n, f.comp (monomial n).to_add_monoid_hom = g.comp (monomial n).to_add_monoid_hom) :
f = g :=
add_hom_ext (Ξ» n, add_monoid_hom.congr_fun (h n))
@[ext] lemma lhom_ext' {M : Type*} [add_comm_monoid M] [module R M] {f g : R[X] ββ[R] M}
(h : β n, f.comp (monomial n) = g.comp (monomial n)) :
f = g :=
linear_map.to_add_monoid_hom_injective $ add_hom_ext $ Ξ» n, linear_map.congr_fun (h n)
-- this has the same content as the subsingleton
lemma eq_zero_of_eq_zero (h : (0 : R) = (1 : R)) (p : R[X]) : p = 0 :=
by rw [βone_smul R p, βh, zero_smul]
section fewnomials
lemma support_monomial (n) {a : R} (H : a β 0) : (monomial n a).support = singleton n :=
by rw [βof_finsupp_single, support, finsupp.support_single_ne_zero _ H]
lemma support_monomial' (n) (a : R) : (monomial n a).support β singleton n :=
by { rw [βof_finsupp_single, support], exact finsupp.support_single_subset }
lemma support_C_mul_X_pow (n : β) {c : R} (h : c β 0) : (C c * X ^ n).support = singleton n :=
by rw [βmonomial_eq_C_mul_X, support_monomial n h]
lemma support_C_mul_X_pow' (n : β) (c : R) : (C c * X ^ n).support β singleton n :=
begin
rw β monomial_eq_C_mul_X,
exact support_monomial' n c,
end
open finset
lemma support_binomial' (k m : β) (x y : R) : (C x * X ^ k + C y * X ^ m).support β {k, m} :=
support_add.trans (union_subset ((support_C_mul_X_pow' k x).trans
(singleton_subset_iff.mpr (mem_insert_self k {m}))) ((support_C_mul_X_pow' m y).trans
(singleton_subset_iff.mpr (mem_insert_of_mem (mem_singleton_self m)))))
lemma support_trinomial' (k m n : β) (x y z : R) :
(C x * X ^ k + C y * X ^ m + C z * X ^ n).support β {k, m, n} :=
support_add.trans (union_subset (support_add.trans (union_subset ((support_C_mul_X_pow' k x).trans
(singleton_subset_iff.mpr (mem_insert_self k {m, n}))) ((support_C_mul_X_pow' m y).trans
(singleton_subset_iff.mpr (mem_insert_of_mem (mem_insert_self m {n}))))))
((support_C_mul_X_pow' n z).trans (singleton_subset_iff.mpr
(mem_insert_of_mem (mem_insert_of_mem (mem_singleton_self n))))))
end fewnomials
lemma X_pow_eq_monomial (n) : X ^ n = monomial n (1:R) :=
begin
induction n with n hn,
{ rw [pow_zero, monomial_zero_one] },
{ rw [pow_succ', hn, X, monomial_mul_monomial, one_mul] },
end
lemma monomial_eq_smul_X {n} : monomial n (a : R) = a β’ X^n :=
calc monomial n a = monomial n (a * 1) : by simp
... = a β’ monomial n 1 : by rw [smul_monomial, smul_eq_mul]
... = a β’ X^n : by rw X_pow_eq_monomial
lemma support_X_pow (H : Β¬ (1:R) = 0) (n : β) : (X^n : R[X]).support = singleton n :=
begin
convert support_monomial n H,
exact X_pow_eq_monomial n,
end
lemma support_X_empty (H : (1:R)=0) : (X : R[X]).support = β
:=
begin
rw [X, H, monomial_zero_right, support_zero],
end
lemma support_X (H : Β¬ (1 : R) = 0) : (X : R[X]).support = singleton 1 :=
begin
rw [β pow_one X, support_X_pow H 1],
end
lemma monomial_left_inj {a : R} (ha : a β 0) {i j : β} : (monomial i a) = (monomial j a) β i = j :=
by simp_rw [βof_finsupp_single, finsupp.single_left_inj ha]
lemma binomial_eq_binomial {k l m n : β} {u v : R} (hu : u β 0) (hv : v β 0) :
C u * X ^ k + C v * X ^ l = C u * X ^ m + C v * X ^ n β
(k = m β§ l = n) β¨ (u = v β§ k = n β§ l = m) β¨ (u + v = 0 β§ k = l β§ m = n) :=
begin
simp_rw [βmonomial_eq_C_mul_X, βto_finsupp_inj, to_finsupp_add, to_finsupp_monomial],
exact finsupp.single_add_single_eq_single_add_single hu hv,
end
lemma nat_cast_mul (n : β) (p : R[X]) : (n : R[X]) * p = n β’ p :=
(nsmul_eq_mul _ _).symm
/-- Summing the values of a function applied to the coefficients of a polynomial -/
def sum {S : Type*} [add_comm_monoid S] (p : R[X]) (f : β β R β S) : S :=
β n in p.support, f n (p.coeff n)
lemma sum_def {S : Type*} [add_comm_monoid S] (p : R[X]) (f : β β R β S) :
p.sum f = β n in p.support, f n (p.coeff n) := rfl
lemma sum_eq_of_subset {S : Type*} [add_comm_monoid S] (p : R[X])
(f : β β R β S) (hf : β i, f i 0 = 0) (s : finset β) (hs : p.support β s) :
p.sum f = β n in s, f n (p.coeff n) :=
begin
apply finset.sum_subset hs (Ξ» n hn h'n, _),
rw not_mem_support_iff at h'n,
simp [h'n, hf]
end
/-- Expressing the product of two polynomials as a double sum. -/
lemma mul_eq_sum_sum :
p * q = β i in p.support, q.sum (Ξ» j a, (monomial (i + j)) (p.coeff i * a)) :=
begin
apply to_finsupp_injective,
rcases p, rcases q,
simp [support, sum, coeff, to_finsupp_sum],
refl
end
@[simp] lemma sum_zero_index {S : Type*} [add_comm_monoid S] (f : β β R β S) :
(0 : R[X]).sum f = 0 :=
by simp [sum]
@[simp] lemma sum_monomial_index {S : Type*} [add_comm_monoid S]
(n : β) (a : R) (f : β β R β S) (hf : f n 0 = 0) :
(monomial n a : R[X]).sum f = f n a :=
begin
by_cases h : a = 0,
{ simp [h, hf] },
{ simp [sum, support_monomial, h, coeff_monomial] }
end
@[simp] lemma sum_C_index {a} {Ξ²} [add_comm_monoid Ξ²] {f : β β R β Ξ²} (h : f 0 0 = 0) :
(C a).sum f = f 0 a :=
sum_monomial_index 0 a f h
-- the assumption `hf` is only necessary when the ring is trivial
@[simp] lemma sum_X_index {S : Type*} [add_comm_monoid S] {f : β β R β S} (hf : f 1 0 = 0) :
(X : R[X]).sum f = f 1 1 :=
sum_monomial_index 1 1 f hf
lemma sum_add_index {S : Type*} [add_comm_monoid S] (p q : R[X])
(f : β β R β S) (hf : β i, f i 0 = 0) (h_add : βa bβ bβ, f a (bβ + bβ) = f a bβ + f a bβ) :
(p + q).sum f = p.sum f + q.sum f :=
begin
rcases p, rcases q,
simp only [βof_finsupp_add, sum, support, coeff, pi.add_apply, coe_add],
exact finsupp.sum_add_index' hf h_add,
end
lemma sum_add' {S : Type*} [add_comm_monoid S] (p : R[X]) (f g : β β R β S) :
p.sum (f + g) = p.sum f + p.sum g :=
by simp [sum_def, finset.sum_add_distrib]
lemma sum_add {S : Type*} [add_comm_monoid S] (p : R[X]) (f g : β β R β S) :
p.sum (Ξ» n x, f n x + g n x) = p.sum f + p.sum g :=
sum_add' _ _ _
lemma sum_smul_index {S : Type*} [add_comm_monoid S] (p : R[X]) (b : R)
(f : β β R β S) (hf : β i, f i 0 = 0) : (b β’ p).sum f = p.sum (Ξ» n a, f n (b * a)) :=
begin
rcases p,
simpa [sum, support, coeff] using finsupp.sum_smul_index hf,
end
/-- `erase p n` is the polynomial `p` in which the `X^n` term has been erased. -/
@[irreducible] definition erase (n : β) : R[X] β R[X]
| β¨pβ© := β¨p.erase nβ©
@[simp] lemma to_finsupp_erase (p : R[X]) (n : β) :
to_finsupp (p.erase n) = (p.to_finsupp).erase n :=
by { rcases p, simp only [erase] }
@[simp] lemma of_finsupp_erase (p : add_monoid_algebra R β) (n : β) :
(β¨p.erase nβ© : R[X]) = (β¨pβ© : R[X]).erase n :=
by { rcases p, simp only [erase] }
@[simp] lemma support_erase (p : R[X]) (n : β) :
support (p.erase n) = (support p).erase n :=
by { rcases p, simp only [support, erase, support_erase] }
lemma monomial_add_erase (p : R[X]) (n : β) : monomial n (coeff p n) + p.erase n = p :=
to_finsupp_injective $ begin
rcases p,
rw [to_finsupp_add, to_finsupp_monomial, to_finsupp_erase, coeff],
exact finsupp.single_add_erase _ _,
end
lemma coeff_erase (p : R[X]) (n i : β) :
(p.erase n).coeff i = if i = n then 0 else p.coeff i :=
begin
rcases p,
simp only [erase, coeff],
convert rfl
end
@[simp] lemma erase_zero (n : β) : (0 : R[X]).erase n = 0 :=
to_finsupp_injective $ by simp
@[simp] lemma erase_monomial {n : β} {a : R} : erase n (monomial n a) = 0 :=
to_finsupp_injective $ by simp
@[simp] lemma erase_same (p : R[X]) (n : β) : coeff (p.erase n) n = 0 :=
by simp [coeff_erase]
@[simp] lemma erase_ne (p : R[X]) (n i : β) (h : i β n) :
coeff (p.erase n) i = coeff p i :=
by simp [coeff_erase, h]
section update
/-- Replace the coefficient of a `p : polynomial p` at a given degree `n : β`
by a given value `a : R`. If `a = 0`, this is equal to `p.erase n`
If `p.nat_degree < n` and `a β 0`, this increases the degree to `n`. -/
def update (p : R[X]) (n : β) (a : R) :
R[X] :=
polynomial.of_finsupp (p.to_finsupp.update n a)
lemma coeff_update (p : R[X]) (n : β) (a : R) :
(p.update n a).coeff = function.update p.coeff n a :=
begin
ext,
cases p,
simp only [coeff, update, function.update_apply, coe_update],
end
lemma coeff_update_apply (p : R[X]) (n : β) (a : R) (i : β) :
(p.update n a).coeff i = if (i = n) then a else p.coeff i :=
by rw [coeff_update, function.update_apply]
@[simp] lemma coeff_update_same (p : R[X]) (n : β) (a : R) :
(p.update n a).coeff n = a :=
by rw [p.coeff_update_apply, if_pos rfl]
lemma coeff_update_ne (p : R[X]) {n : β} (a : R) {i : β} (h : i β n) :
(p.update n a).coeff i = p.coeff i :=
by rw [p.coeff_update_apply, if_neg h]
@[simp] lemma update_zero_eq_erase (p : R[X]) (n : β) :
p.update n 0 = p.erase n :=
by { ext, rw [coeff_update_apply, coeff_erase] }
lemma support_update (p : R[X]) (n : β) (a : R) [decidable (a = 0)] :
support (p.update n a) = if a = 0 then p.support.erase n else insert n p.support :=
by { cases p, simp only [support, update, support_update], congr }
lemma support_update_zero (p : R[X]) (n : β) :
support (p.update n 0) = p.support.erase n :=
by rw [update_zero_eq_erase, support_erase]
lemma support_update_ne_zero (p : R[X]) (n : β) {a : R} (ha : a β 0) :
support (p.update n a) = insert n p.support :=
by classical; rw [support_update, if_neg ha]
end update
end semiring
section comm_semiring
variables [comm_semiring R]
instance : comm_semiring R[X] :=
function.injective.comm_semiring to_finsupp to_finsupp_injective
to_finsupp_zero to_finsupp_one to_finsupp_add to_finsupp_mul
(Ξ» _ _, to_finsupp_smul _ _) to_finsupp_pow (Ξ» _, rfl)
end comm_semiring
section ring
variables [ring R]
instance : has_int_cast R[X] := β¨Ξ» n, of_finsupp nβ©
instance : ring R[X] :=
function.injective.ring to_finsupp to_finsupp_injective
to_finsupp_zero to_finsupp_one to_finsupp_add to_finsupp_mul to_finsupp_neg to_finsupp_sub
(Ξ» _ _, to_finsupp_smul _ _) (Ξ» _ _, to_finsupp_smul _ _) to_finsupp_pow (Ξ» _, rfl) (Ξ» _, rfl)
@[simp] lemma coeff_neg (p : R[X]) (n : β) : coeff (-p) n = -coeff p n :=
by { rcases p, rw [βof_finsupp_neg, coeff, coeff, finsupp.neg_apply] }
@[simp]
lemma coeff_sub (p q : R[X]) (n : β) : coeff (p - q) n = coeff p n - coeff q n :=
by { rcases p, rcases q, rw [βof_finsupp_sub, coeff, coeff, coeff, finsupp.sub_apply] }
@[simp] lemma monomial_neg (n : β) (a : R) : monomial n (-a) = -(monomial n a) :=
by rw [eq_neg_iff_add_eq_zero, βmonomial_add, neg_add_self, monomial_zero_right]
@[simp] lemma support_neg {p : R[X]} : (-p).support = p.support :=
by { rcases p, rw [βof_finsupp_neg, support, support, finsupp.support_neg] }
@[simp]
lemma C_eq_int_cast (n : β€) : C (n : R) = n :=
(C : R β+* _).map_int_cast n
end ring
instance [comm_ring R] : comm_ring R[X] :=
function.injective.comm_ring to_finsupp to_finsupp_injective
to_finsupp_zero to_finsupp_one to_finsupp_add to_finsupp_mul to_finsupp_neg to_finsupp_sub
(Ξ» _ _, to_finsupp_smul _ _) (Ξ» _ _, to_finsupp_smul _ _) to_finsupp_pow (Ξ» _, rfl) (Ξ» _, rfl)
section nonzero_semiring
variables [semiring R] [nontrivial R]
instance : nontrivial R[X] :=
begin
have h : nontrivial (add_monoid_algebra R β) := by apply_instance,
rcases h.exists_pair_ne with β¨x, y, hxyβ©,
refine β¨β¨β¨xβ©, β¨yβ©, _β©β©,
simp [hxy],
end
lemma X_ne_zero : (X : R[X]) β 0 :=
mt (congr_arg (Ξ» p, coeff p 1)) (by simp)
end nonzero_semiring
@[simp] lemma nontrivial_iff [semiring R] : nontrivial R[X] β nontrivial R :=
β¨Ξ» h, let β¨r, s, hrsβ© := @exists_pair_ne _ h in nontrivial.of_polynomial_ne hrs,
Ξ» h, @polynomial.nontrivial _ _ hβ©
section repr
variables [semiring R]
open_locale classical
instance [has_repr R] : has_repr R[X] :=
β¨Ξ» p, if p = 0 then "0"
else (p.support.sort (β€)).foldr
(Ξ» n a, a ++ (if a = "" then "" else " + ") ++
if n = 0
then "C (" ++ repr (coeff p n) ++ ")"
else if n = 1
then if (coeff p n) = 1 then "X" else "C (" ++ repr (coeff p n) ++ ") * X"
else if (coeff p n) = 1 then "X ^ " ++ repr n
else "C (" ++ repr (coeff p n) ++ ") * X ^ " ++ repr n) ""β©
end repr
end polynomial
|
c343006aafe253e403cfc67635da502ccee098bf | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /library/data/nat/div.lean | 9d8fbc300a44c321bddfe6faaf9d36ce34906664 | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 19,274 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: data.nat.div
Authors: Jeremy Avigad, Leonardo de Moura
Definitions of div, mod, and gcd on the natural numbers.
-/
import data.nat.sub data.nat.comm_semiring tools.fake_simplifier
open eq.ops well_founded decidable fake_simplifier prod
namespace nat
/- div and mod -/
-- auxiliary lemma used to justify div
private definition div_rec_lemma {x y : nat} (H : 0 < y β§ y β€ x) : x - y < x :=
and.rec_on H (Ξ» ypos ylex, sub_lt (lt_of_lt_of_le ypos ylex) ypos)
private definition div.F (x : nat) (f : Ξ xβ, xβ < x β nat β nat) (y : nat) : nat :=
if H : 0 < y β§ y β€ x then f (x - y) (div_rec_lemma H) y + 1 else zero
definition divide (x y : nat) := fix div.F x y
theorem divide_def (x y : nat) : divide x y = if 0 < y β§ y β€ x then divide (x - y) y + 1 else 0 :=
congr_fun (fix_eq div.F x) y
notation a div b := divide a b
theorem div_zero (a : β) : a div 0 = 0 :=
divide_def a 0 β¬ if_neg (!not_and_of_not_left (lt.irrefl 0))
theorem div_eq_zero_of_lt {a b : β} (h : a < b) : a div b = 0 :=
divide_def a b β¬ if_neg (!not_and_of_not_right (not_le_of_lt h))
theorem zero_div (b : β) : 0 div b = 0 :=
divide_def 0 b β¬ if_neg (Ξ» h, and.rec_on h (Ξ» l r, absurd (lt_of_lt_of_le l r) (lt.irrefl 0)))
theorem div_eq_succ_sub_div {a b : β} (hβ : b > 0) (hβ : a β₯ b) : a div b = succ ((a - b) div b) :=
divide_def a b β¬ if_pos (and.intro hβ hβ)
theorem add_div_left {x z : β} (H : z > 0) : (x + z) div z = succ (x div z) :=
calc
(x + z) div z = if 0 < z β§ z β€ x + z then (x + z - z) div z + 1 else 0 : !divide_def
... = (x + z - z) div z + 1 : if_pos (and.intro H (le_add_left z x))
... = succ (x div z) : {!add_sub_cancel}
theorem add_div_right {x z : β} (H : x > 0) : (x + z) div x = succ (z div x) :=
!add.comm βΈ add_div_left H
theorem add_mul_div_left {x y z : β} (H : z > 0) : (x + y * z) div z = x div z + y :=
induction_on y
(calc (x + zero * z) div z = (x + zero) div z : zero_mul
... = x div z : add_zero
... = x div z + zero : add_zero)
(take y,
assume IH : (x + y * z) div z = x div z + y, calc
(x + succ y * z) div z = (x + y * z + z) div z : by simp
... = succ ((x + y * z) div z) : add_div_left H
... = x div z + succ y : by simp)
theorem add_mul_div_right {x y z : β} (H : y > 0) : (x + y * z) div y = x div y + z :=
!mul.comm βΈ add_mul_div_left H
private definition mod.F (x : nat) (f : Ξ xβ, xβ < x β nat β nat) (y : nat) : nat :=
if H : 0 < y β§ y β€ x then f (x - y) (div_rec_lemma H) y else x
definition modulo (x y : nat) := fix mod.F x y
notation a mod b := modulo a b
theorem modulo_def (x y : nat) : modulo x y = if 0 < y β§ y β€ x then modulo (x - y) y else x :=
congr_fun (fix_eq mod.F x) y
theorem mod_zero (a : β) : a mod 0 = a :=
modulo_def a 0 β¬ if_neg (!not_and_of_not_left (lt.irrefl 0))
theorem mod_eq_of_lt {a b : β} (h : a < b) : a mod b = a :=
modulo_def a b β¬ if_neg (!not_and_of_not_right (not_le_of_lt h))
theorem zero_mod (b : β) : 0 mod b = 0 :=
modulo_def 0 b β¬ if_neg (Ξ» h, and.rec_on h (Ξ» l r, absurd (lt_of_lt_of_le l r) (lt.irrefl 0)))
theorem mod_eq_sub_mod {a b : β} (hβ : b > 0) (hβ : a β₯ b) : a mod b = (a - b) mod b :=
modulo_def a b β¬ if_pos (and.intro hβ hβ)
theorem add_mod_left {x z : β} (H : z > 0) : (x + z) mod z = x mod z :=
calc
(x + z) mod z = if 0 < z β§ z β€ x + z then (x + z - z) mod z else _ : modulo_def
... = (x + z - z) mod z : if_pos (and.intro H (le_add_left z x))
... = x mod z : add_sub_cancel
theorem add_mod_right {x z : β} (H : x > 0) : (x + z) mod x = z mod x :=
!add.comm βΈ add_mod_left H
theorem add_mul_mod_left {x y z : β} (H : z > 0) : (x + y * z) mod z = x mod z :=
induction_on y
(calc (x + zero * z) mod z = (x + zero) mod z : zero_mul
... = x mod z : add_zero)
(take y,
assume IH : (x + y * z) mod z = x mod z,
calc
(x + succ y * z) mod z = (x + (y * z + z)) mod z : succ_mul
... = (x + y * z + z) mod z : add.assoc
... = (x + y * z) mod z : add_mod_left H
... = x mod z : IH)
theorem add_mul_mod_right {x y z : β} (H : y > 0) : (x + y * z) mod y = x mod y :=
!mul.comm βΈ add_mul_mod_left H
theorem mul_mod_left {m n : β} : (m * n) mod n = 0 :=
by_cases_zero_pos n (by simp)
(take n,
assume npos : n > 0,
(by simp) βΈ (@add_mul_mod_left 0 m _ npos))
theorem mul_mod_right {m n : β} : (m * n) mod m = 0 :=
!mul.comm βΈ !mul_mod_left
theorem mod_lt {x y : β} (H : y > 0) : x mod y < y :=
case_strong_induction_on x
(show 0 mod y < y, from !zero_modβ»ΒΉ βΈ H)
(take x,
assume IH : βx', x' β€ x β x' mod y < y,
show succ x mod y < y, from
by_cases -- (succ x < y)
(assume H1 : succ x < y,
have H2 : succ x mod y = succ x, from mod_eq_of_lt H1,
show succ x mod y < y, from H2β»ΒΉ βΈ H1)
(assume H1 : Β¬ succ x < y,
have H2 : y β€ succ x, from le_of_not_lt H1,
have H3 : succ x mod y = (succ x - y) mod y, from mod_eq_sub_mod H H2,
have H4 : succ x - y < succ x, from sub_lt !succ_pos H,
have H5 : succ x - y β€ x, from le_of_lt_succ H4,
show succ x mod y < y, from H3β»ΒΉ βΈ IH _ H5))
/- properties of div and mod together -/
-- the quotient / remainder theorem
theorem eq_div_mul_add_mod {x y : β} : x = x div y * y + x mod y :=
by_cases_zero_pos y
(show x = x div 0 * 0 + x mod 0, from
(calc
x div 0 * 0 + x mod 0 = 0 + x mod 0 : mul_zero
... = x mod 0 : zero_add
... = x : mod_zero)β»ΒΉ)
(take y,
assume H : y > 0,
show x = x div y * y + x mod y, from
case_strong_induction_on x
(show 0 = (0 div y) * y + 0 mod y, by simp)
(take x,
assume IH : βx', x' β€ x β x' = x' div y * y + x' mod y,
show succ x = succ x div y * y + succ x mod y, from
by_cases -- (succ x < y)
(assume H1 : succ x < y,
have H2 : succ x div y = 0, from div_eq_zero_of_lt H1,
have H3 : succ x mod y = succ x, from mod_eq_of_lt H1,
by simp)
(assume H1 : Β¬ succ x < y,
have H2 : y β€ succ x, from le_of_not_lt H1,
have H3 : succ x div y = succ ((succ x - y) div y), from div_eq_succ_sub_div H H2,
have H4 : succ x mod y = (succ x - y) mod y, from mod_eq_sub_mod H H2,
have H5 : succ x - y < succ x, from sub_lt !succ_pos H,
have H6 : succ x - y β€ x, from le_of_lt_succ H5,
(calc
succ x div y * y + succ x mod y =
succ ((succ x - y) div y) * y + succ x mod y : H3
... = ((succ x - y) div y) * y + y + succ x mod y : succ_mul
... = ((succ x - y) div y) * y + y + (succ x - y) mod y : H4
... = ((succ x - y) div y) * y + (succ x - y) mod y + y : add.right_comm
... = succ x - y + y : {!(IH _ H6)β»ΒΉ}
... = succ x : sub_add_cancel H2)β»ΒΉ)))
theorem mod_le {x y : β} : x mod y β€ x :=
eq_div_mul_add_modβ»ΒΉ βΈ !le_add_left
theorem eq_remainder {y : β} (H : y > 0) {q1 r1 q2 r2 : β} (H1 : r1 < y) (H2 : r2 < y)
(H3 : q1 * y + r1 = q2 * y + r2) : r1 = r2 :=
calc
r1 = r1 mod y : by simp
... = (r1 + q1 * y) mod y : (add_mul_mod_left H)β»ΒΉ
... = (q1 * y + r1) mod y : add.comm
... = (r2 + q2 * y) mod y : by simp
... = r2 mod y : add_mul_mod_left H
... = r2 : by simp
theorem eq_quotient {y : β} (H : y > 0) {q1 r1 q2 r2 : β} (H1 : r1 < y) (H2 : r2 < y)
(H3 : q1 * y + r1 = q2 * y + r2) : q1 = q2 :=
have H4 : q1 * y + r2 = q2 * y + r2, from (eq_remainder H H1 H2 H3) βΈ H3,
have H5 : q1 * y = q2 * y, from add.cancel_right H4,
have H6 : y > 0, from lt_of_le_of_lt !zero_le H1,
show q1 = q2, from eq_of_mul_eq_mul_right H6 H5
theorem mul_div_mul_left {z x y : β} (zpos : z > 0) : (z * x) div (z * y) = x div y :=
by_cases -- (y = 0)
(assume H : y = 0, by simp)
(assume H : y β 0,
have ypos : y > 0, from pos_of_ne_zero H,
have zypos : z * y > 0, from mul_pos zpos ypos,
have H1 : (z * x) mod (z * y) < z * y, from mod_lt zypos,
have H2 : z * (x mod y) < z * y, from mul_lt_mul_of_pos_left (mod_lt ypos) zpos,
eq_quotient zypos H1 H2
(calc
((z * x) div (z * y)) * (z * y) + (z * x) mod (z * y) = z * x : eq_div_mul_add_mod
... = z * (x div y * y + x mod y) : eq_div_mul_add_mod
... = z * (x div y * y) + z * (x mod y) : mul.left_distrib
... = (x div y) * (z * y) + z * (x mod y) : mul.left_comm))
theorem mul_div_mul_right {x z y : β} (zpos : z > 0) : (x * z) div (y * z) = x div y :=
!mul.comm βΈ !mul.comm βΈ mul_div_mul_left zpos
theorem mul_mod_mul_left {z x y : β} (zpos : z > 0) : (z * x) mod (z * y) = z * (x mod y) :=
by_cases -- (y = 0)
(assume H : y = 0, by simp)
(assume H : y β 0,
have ypos : y > 0, from pos_of_ne_zero H,
have zypos : z * y > 0, from mul_pos zpos ypos,
have H1 : (z * x) mod (z * y) < z * y, from mod_lt zypos,
have H2 : z * (x mod y) < z * y, from mul_lt_mul_of_pos_left (mod_lt ypos) zpos,
eq_remainder zypos H1 H2
(calc
((z * x) div (z * y)) * (z * y) + (z * x) mod (z * y) = z * x : eq_div_mul_add_mod
... = z * (x div y * y + x mod y) : eq_div_mul_add_mod
... = z * (x div y * y) + z * (x mod y) : mul.left_distrib
... = (x div y) * (z * y) + z * (x mod y) : mul.left_comm))
theorem mul_mod_mul_right {x z y : β} (zpos : z > 0) : (x * z) mod (y * z) = (x mod y) * z :=
mul.comm z x βΈ mul.comm z y βΈ !mul.comm βΈ mul_mod_mul_left zpos
theorem mod_one (x : β) : x mod 1 = 0 :=
have H1 : x mod 1 < 1, from mod_lt !succ_pos,
eq_zero_of_le_zero (le_of_lt_succ H1)
theorem mod_self (n : β) : n mod n = 0 :=
cases_on n (by simp)
(take n,
have H : (succ n * 1) mod (succ n * 1) = succ n * (1 mod 1),
from mul_mod_mul_left !succ_pos,
(by simp) βΈ H)
theorem div_one (n : β) : n div 1 = n :=
have H : n div 1 * 1 + n mod 1 = n, from eq_div_mul_add_modβ»ΒΉ,
(by simp) βΈ H
theorem div_self {n : β} (H : n > 0) : n div n = 1 :=
have H1 : (n * 1) div (n * 1) = 1 div 1, from mul_div_mul_left H,
(by simp) βΈ H1
theorem div_mul_eq_of_mod_eq_zero {x y : β} (H : x mod y = 0) : x div y * y = x :=
(calc
x = x div y * y + x mod y : eq_div_mul_add_mod
... = x div y * y + 0 : H
... = x div y * y : !add_zero)β»ΒΉ
/- divides -/
theorem dvd_of_mod_eq_zero {x y : β} (H : y mod x = 0) : x | y :=
dvd.intro (!mul.comm βΈ div_mul_eq_of_mod_eq_zero H)
theorem mod_eq_zero_of_dvd {x y : β} (H : x | y) : y mod x = 0 :=
dvd.elim H
(take z,
assume H1 : x * z = y,
H1 βΈ !mul_mod_right)
theorem dvd_iff_mod_eq_zero (x y : β) : x | y β y mod x = 0 :=
iff.intro mod_eq_zero_of_dvd dvd_of_mod_eq_zero
definition dvd.decidable_rel [instance] : decidable_rel dvd :=
take m n, decidable_of_decidable_of_iff _ (iff.symm !dvd_iff_mod_eq_zero)
theorem div_mul_eq_of_dvd {x y : β} (H : y | x) : x div y * y = x :=
div_mul_eq_of_mod_eq_zero (mod_eq_zero_of_dvd H)
theorem dvd_of_dvd_add_left {m n1 n2 : β} : m | (n1 + n2) β m | n1 β m | n2 :=
by_cases_zero_pos m
(assume (H1 : 0 | n1 + n2) (H2 : 0 | n1),
have H3 : n1 + n2 = 0, from eq_zero_of_zero_dvd H1,
have H4 : n1 = 0, from eq_zero_of_zero_dvd H2,
have H5 : n2 = 0, from calc
n2 = 0 + n2 : zero_add
... = n1 + n2 : H4
... = 0 : H3,
show 0 | n2, from H5 βΈ dvd.refl n2)
(take m,
assume mpos : m > 0,
assume H1 : m | (n1 + n2),
assume H2 : m | n1,
have H3 : n1 + n2 = n1 + n2 div m * m, from calc
n1 + n2 = (n1 + n2) div m * m : div_mul_eq_of_dvd H1
... = (n1 div m * m + n2) div m * m : div_mul_eq_of_dvd H2
... = (n2 + n1 div m * m) div m * m : add.comm
... = (n2 div m + n1 div m) * m : add_mul_div_left mpos
... = n2 div m * m + n1 div m * m : mul.right_distrib
... = n1 div m * m + n2 div m * m : add.comm
... = n1 + n2 div m * m : div_mul_eq_of_dvd H2,
have H4 : n2 = n2 div m * m, from add.cancel_left H3,
have H5 : m * (n2 div m) = n2, from !mul.comm βΈ H4β»ΒΉ,
dvd.intro H5)
theorem dvd_of_dvd_add_right {m n1 n2 : β} (H : m | (n1 + n2)) : m | n2 β m | n1 :=
dvd_of_dvd_add_left (!add.comm βΈ H)
theorem dvd_sub {m n1 n2 : β} (H1 : m | n1) (H2 : m | n2) : m | (n1 - n2) :=
by_cases
(assume H3 : n1 β₯ n2,
have H4 : n1 = n1 - n2 + n2, from (sub_add_cancel H3)β»ΒΉ,
show m | n1 - n2, from dvd_of_dvd_add_right (H4 βΈ H1) H2)
(assume H3 : Β¬ (n1 β₯ n2),
have H4 : n1 - n2 = 0, from sub_eq_zero_of_le (le_of_lt (lt_of_not_le H3)),
show m | n1 - n2, from H4β»ΒΉ βΈ dvd_zero _)
theorem dvd.antisymm {m n : β} : m | n β n | m β m = n :=
by_cases_zero_pos n
(assume H1, assume H2 : 0 | m, eq_zero_of_zero_dvd H2)
(take n,
assume Hpos : n > 0,
assume H1 : m | n,
assume H2 : n | m,
obtain k (Hk : m * k = n), from dvd.ex H1,
obtain l (Hl : n * l = m), from dvd.ex H2,
have H3 : n * (l * k) = n, from !mul.assoc βΈ Hlβ»ΒΉ βΈ Hk,
have H4 : l * k = 1, from eq_one_of_mul_eq_self_right Hpos H3,
have H5 : k = 1, from eq_one_of_mul_eq_one_left H4,
show m = n, from (mul_one m)β»ΒΉ β¬ (H5 βΈ Hk))
/- gcd and lcm -/
private definition pair_nat.lt : nat Γ nat β nat Γ nat β Prop := measure prβ
private definition pair_nat.lt.wf : well_founded pair_nat.lt :=
intro_k (measure.wf prβ) 20 -- we use intro_k to be able to execute gcd efficiently in the kernel
local attribute pair_nat.lt.wf [instance] -- instance will not be saved in .olean
local infixl `βΊ`:50 := pair_nat.lt
private definition gcd.lt.dec (x yβ : nat) : (succ yβ, x mod succ yβ) βΊ (x, succ yβ) :=
mod_lt (succ_pos yβ)
definition gcd.F (pβ : nat Γ nat) : (Ξ pβ : nat Γ nat, pβ βΊ pβ β nat) β nat :=
prod.cases_on pβ (Ξ»x y, cases_on y
(Ξ» f, x)
(Ξ» yβ (f : Ξ pβ, pβ βΊ (x, succ yβ) β nat), f (succ yβ, x mod succ yβ) !gcd.lt.dec))
definition gcd (x y : nat) := fix gcd.F (pair x y)
theorem gcd_zero (x : nat) : gcd x 0 = x :=
well_founded.fix_eq gcd.F (x, 0)
theorem gcd_succ (x y : nat) : gcd x (succ y) = gcd (succ y) (x mod succ y) :=
well_founded.fix_eq gcd.F (x, succ y)
theorem gcd_one (n : β) : gcd n 1 = 1 :=
calc gcd n 1 = gcd 1 (n mod 1) : gcd_succ n zero
... = gcd 1 0 : mod_one
... = 1 : gcd_zero
theorem gcd_def (x y : β) : gcd x y = if y = 0 then x else gcd y (x mod y) :=
cases_on y
(calc gcd x 0 = x : gcd_zero x
... = if 0 = 0 then x else gcd zero (x mod zero) : (if_pos rfl)β»ΒΉ)
(Ξ»yβ, calc
gcd x (succ yβ) = gcd (succ yβ) (x mod succ yβ) : gcd_succ x yβ
... = if succ yβ = 0 then x else gcd (succ yβ) (x mod succ yβ) : (if_neg (succ_ne_zero yβ))β»ΒΉ)
theorem gcd_rec (m : β) {n : β} (H : n > 0) : gcd m n = gcd n (m mod n) :=
gcd_def m n β¬ if_neg (ne_zero_of_pos H)
theorem gcd_self (n : β) : gcd n n = n :=
cases_on n
rfl
(Ξ»nβ, calc
gcd (succ nβ) (succ nβ) = gcd (succ nβ) (succ nβ mod succ nβ) : gcd_succ (succ nβ) nβ
... = gcd (succ nβ) 0 : mod_self (succ nβ)
... = succ nβ : gcd_zero)
theorem gcd_zero_left (n : nat) : gcd 0 n = n :=
cases_on n
rfl
(Ξ» nβ, calc
gcd 0 (succ nβ) = gcd (succ nβ) (0 mod succ nβ) : gcd_succ
... = gcd (succ nβ) 0 : zero_mod
... = (succ nβ) : gcd_zero)
theorem gcd.induction {P : β β β β Prop}
(m n : β)
(H0 : βm, P m 0)
(H1 : βm n, 0 < n β P n (m mod n) β P m n) :
P m n :=
let Q : nat Γ nat β Prop := Ξ» p : nat Γ nat, P (prβ p) (prβ p) in
have aux : Q (m, n), from
well_founded.induction (m, n) (Ξ»p, prod.cases_on p
(Ξ»m n, cases_on n
(Ξ» ih, show P (prβ (m, 0)) (prβ (m, 0)), from H0 m)
(Ξ» nβ (ih : βpβ, pβ βΊ (m, succ nβ) β P (prβ pβ) (prβ pβ)),
have hltβ : 0 < succ nβ, from succ_pos nβ,
have hltβ : (succ nβ, m mod succ nβ) βΊ (m, succ nβ), from gcd.lt.dec _ _,
have hp : P (succ nβ) (m mod succ nβ), from ih _ hltβ,
show P m (succ nβ), from
H1 m (succ nβ) hltβ hp))),
aux
theorem gcd_dvd (m n : β) : (gcd m n | m) β§ (gcd m n | n) :=
gcd.induction m n
(take m,
show (gcd m 0 | m) β§ (gcd m 0 | 0), by simp)
(take m n,
assume npos : 0 < n,
assume IH : (gcd n (m mod n) | n) β§ (gcd n (m mod n) | (m mod n)),
have H : gcd n (m mod n) | (m div n * n + m mod n), from
dvd_add (dvd.trans (and.elim_left IH) !dvd_mul_left) (and.elim_right IH),
have H1 : gcd n (m mod n) | m, from eq_div_mul_add_modβ»ΒΉ βΈ H,
have gcd_eq : gcd n (m mod n) = gcd m n, from (gcd_rec _ npos)β»ΒΉ,
show (gcd m n | m) β§ (gcd m n | n), from gcd_eq βΈ (and.intro H1 (and.elim_left IH)))
theorem gcd_dvd_left (m n : β) : (gcd m n | m) := and.elim_left !gcd_dvd
theorem gcd_dvd_right (m n : β) : (gcd m n | n) := and.elim_right !gcd_dvd
theorem dvd_gcd {m n k : β} : k | m β k | n β k | (gcd m n) :=
gcd.induction m n
(take m, assume (hβ : k | m) (hβ : k | 0),
show k | gcd m 0, from !gcd_zeroβ»ΒΉ βΈ hβ)
(take m n,
assume npos : n > 0,
assume IH : k | n β k | (m mod n) β k | gcd n (m mod n),
assume H1 : k | m,
assume H2 : k | n,
have H3 : k | m div n * n + m mod n, from eq_div_mul_add_mod βΈ H1,
have H4 : k | m mod n, from nat.dvd_of_dvd_add_left H3 (dvd.trans H2 (by simp)),
have gcd_eq : gcd n (m mod n) = gcd m n, from (gcd_rec _ npos)β»ΒΉ,
show k | gcd m n, from gcd_eq βΈ IH H2 H4)
theorem gcd.comm (m n : β) : gcd m n = gcd n m :=
dvd.antisymm
(dvd_gcd !gcd_dvd_right !gcd_dvd_left)
(dvd_gcd !gcd_dvd_right !gcd_dvd_left)
theorem gcd.assoc (m n k : β) : gcd (gcd m n) k = gcd m (gcd n k) :=
dvd.antisymm
(dvd_gcd
(dvd.trans !gcd_dvd_left !gcd_dvd_left)
(dvd_gcd (dvd.trans !gcd_dvd_left !gcd_dvd_right) !gcd_dvd_right))
(dvd_gcd
(dvd_gcd !gcd_dvd_left (dvd.trans !gcd_dvd_right !gcd_dvd_left))
(dvd.trans !gcd_dvd_right !gcd_dvd_right))
end nat
|
46ba294c5f91bf28585593701e4e35dfc9d8b013 | b392eb79fb36952401156496daa60628ccb07438 | /MathPort/Number.lean | aa317ac77764cd06452984fc7f0cf83edf96cc18 | [
"Apache-2.0"
] | permissive | AurelienSaue/mathportsource | d9eabe74e3ab7774baa6a10a6dc8d4855ff92266 | 1a164e4fff7204c522c1f4ecc5024fd909be3b0b | refs/heads/master | 1,685,214,377,305 | 1,623,621,223,000 | 1,623,621,223,000 | 364,191,042 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,868 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Daniel Selsam
These functions mimic the ones in lean3/src/library/num.cpp
and must be called *before* translating the constants into Lean4.
-/
import MathPort.Util
import MathPort.Basic
import MathPort.ActionItem
import MathPort.Rules
import MathPort.OldRecursor
import Lean
namespace MathPort
open Lean
partial def isConcreteNat? (e : Expr) : Option Nat := OptionM.run $
if e.isConstOf `Nat.zero then
some 0
else if e.isAppOfArity `Nat.succ 1 then do
let n β isConcreteNat? e.appArg!
some (n+1)
else
none
structure NumInfo where
number : Nat
level : Level
type : Expr
hasZero? : Option Expr := none
hasOne? : Option Expr := none
hasAdd? : Option Expr := none
partial def isNumber? (e : Expr) : Option NumInfo := do
if e.isAppOfArity `Mathlib.HasZero.zero 2 then some {
number := 0,
level := e.getAppFn.constLevels!.head!,
type := e.getArg! 0
hasZero? := e.getArg! 1
}
else if e.isAppOfArity `Mathlib.HasOne.one 2 then some {
number := 1,
level := e.getAppFn.constLevels!.head!,
type := e.getArg! 0,
hasOne? := e.getArg! 1
}
-- TODO: may need to check if these instances are def-eq
-- (I am hoping that mathlib does not produce terms in which they are not)
else if e.isAppOfArity `bit0 3 then OptionM.run $ do
let info β isNumber? $ e.getArg! 2
some { info with
number := info.number * 2,
hasAdd? := info.hasAdd? <|> e.getArg! 1 }
else if e.isAppOfArity `bit1 4 then OptionM.run $ do
let info β isNumber? $ e.getArg! 2
some { info with
number := info.number * 2 + 1,
hasAdd? := info.hasAdd? <|> e.getArg! 2 }
else none
end MathPort
|
ec2aed196d5507eaab7ba4fb71ee3ee7ef0b5fe9 | e61a235b8468b03aee0120bf26ec615c045005d2 | /src/Init/Control/Reader.lean | 887c71ee13c2e6a745ea4c2d4afec137a6aa0c21 | [
"Apache-2.0"
] | permissive | SCKelemen/lean4 | 140dc63a80539f7c61c8e43e1c174d8500ec3230 | e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc | refs/heads/master | 1,660,973,595,917 | 1,590,278,033,000 | 1,590,278,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,365 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
The Reader monad transformer for passing immutable State.
-/
prelude
import Init.Control.Lift
import Init.Control.Id
import Init.Control.Alternative
import Init.Control.Except
universes u v w
/-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/
def ReaderT (Ο : Type u) (m : Type u β Type v) (Ξ± : Type u) : Type (max u v) :=
Ο β m Ξ±
@[inline] def ReaderT.run {Ο : Type u} {m : Type u β Type v} {Ξ± : Type u} (x : ReaderT Ο m Ξ±) (r : Ο) : m Ξ± :=
x r
@[reducible] def Reader (Ο : Type u) := ReaderT Ο id
namespace ReaderT
section
variables {Ο : Type u} {m : Type u β Type v} [Monad m] {Ξ± Ξ² : Type u}
@[inline] protected def read : ReaderT Ο m Ο :=
pure
@[inline] protected def pure (a : Ξ±) : ReaderT Ο m Ξ± :=
fun r => pure a
@[inline] protected def bind (x : ReaderT Ο m Ξ±) (f : Ξ± β ReaderT Ο m Ξ²) : ReaderT Ο m Ξ² :=
fun r => do a β x r; f a r
@[inline] protected def map (f : Ξ± β Ξ²) (x : ReaderT Ο m Ξ±) : ReaderT Ο m Ξ² :=
fun r => f <$> x r
instance : Monad (ReaderT Ο m) :=
{ pure := @ReaderT.pure _ _ _, bind := @ReaderT.bind _ _ _, map := @ReaderT.map _ _ _ }
@[inline] protected def lift (a : m Ξ±) : ReaderT Ο m Ξ± :=
fun r => a
instance (m) [Monad m] : HasMonadLift m (ReaderT Ο m) :=
β¨@ReaderT.lift Ο m _β©
instance (Ο m m') [Monad m] [Monad m'] : MonadFunctor m m' (ReaderT Ο m) (ReaderT Ο m') :=
β¨fun _ f x r => f (x r)β©
@[inline] protected def adapt {Ο' : Type u} [Monad m] {Ξ± : Type u} (f : Ο' β Ο) : ReaderT Ο m Ξ± β ReaderT Ο' m Ξ± :=
fun x r => x (f r)
@[inline] protected def orelse [Alternative m] {Ξ± : Type u} (xβ xβ : ReaderT Ο m Ξ±) : ReaderT Ο m Ξ± :=
fun s => xβ s <|> xβ s
@[inline] protected def failure [Alternative m] {Ξ± : Type u} : ReaderT Ο m Ξ± :=
fun s => failure
instance [Alternative m] : Alternative (ReaderT Ο m) :=
{ ReaderT.Monad with
failure := @ReaderT.failure _ _ _ _,
orelse := @ReaderT.orelse _ _ _ _ }
instance (Ξ΅) [Monad m] [MonadExcept Ξ΅ m] : MonadExcept Ξ΅ (ReaderT Ο m) :=
{ throw := fun Ξ± => ReaderT.lift β throw,
catch := fun Ξ± x c r => catch (x r) (fun e => (c e) r) }
end
end ReaderT
/-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader).
It does not contain `local` because this Function cannot be lifted using `monadLift`.
Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function.
Note: This class can be seen as a simplification of the more "principled" definition
```
class MonadReader (Ο : outParam (Type u)) (n : Type u β Type u) :=
(lift {Ξ± : Type u} : (β {m : Type u β Type u} [Monad m], ReaderT Ο m Ξ±) β n Ξ±)
```
-/
class MonadReader (Ο : outParam (Type u)) (m : Type u β Type v) :=
(read : m Ο)
export MonadReader (read)
instance monadReaderTrans {Ο : Type u} {m : Type u β Type v} {n : Type u β Type w}
[MonadReader Ο m] [HasMonadLift m n] : MonadReader Ο n :=
β¨monadLift (MonadReader.read : m Ο)β©
instance {Ο : Type u} {m : Type u β Type v} [Monad m] : MonadReader Ο (ReaderT Ο m) :=
β¨ReaderT.readβ©
/-- Adapt a Monad stack, changing the Type of its top-most environment.
This class is comparable to [Control.Lens.Magnify](https://hackage.haskell.org/package/lens-4.15.4/docs/Control-Lens-Zoom.html#t:Magnify), but does not use lenses (why would it), and is derived automatically for any transformer implementing `MonadFunctor`.
Note: This class can be seen as a simplification of the more "principled" definition
```
class MonadReaderFunctor (Ο Ο' : outParam (Type u)) (n n' : Type u β Type u) :=
(map {Ξ± : Type u} : (β {m : Type u β Type u} [Monad m], ReaderT Ο m Ξ± β ReaderT Ο' m Ξ±) β n Ξ± β n' Ξ±)
```
-/
class MonadReaderAdapter (Ο Ο' : outParam (Type u)) (m m' : Type u β Type v) :=
(adaptReader {Ξ± : Type u} : (Ο' β Ο) β m Ξ± β m' Ξ±)
export MonadReaderAdapter (adaptReader)
section
variables {Ο Ο' : Type u} {m m' : Type u β Type v}
instance monadReaderAdapterTrans {n n' : Type u β Type v} [MonadReaderAdapter Ο Ο' m m'] [MonadFunctor m m' n n'] : MonadReaderAdapter Ο Ο' n n' :=
β¨fun Ξ± f => monadMap (fun Ξ± => (adaptReader f : m Ξ± β m' Ξ±))β©
instance [Monad m] : MonadReaderAdapter Ο Ο' (ReaderT Ο m) (ReaderT Ο' m) :=
β¨fun Ξ± => ReaderT.adaptβ©
end
instance (Ο : Type u) (m out) [MonadRun out m] : MonadRun (fun Ξ± => Ο β out Ξ±) (ReaderT Ο m) :=
β¨fun Ξ± x => run β xβ©
class MonadReaderRunner (Ο : Type u) (m m' : Type u β Type u) :=
(runReader {Ξ± : Type u} : m Ξ± β Ο β m' Ξ±)
export MonadReaderRunner (runReader)
section
variables {Ο Ο' : Type u} {m m' : Type u β Type u}
instance monadReaderRunnerTrans {n n' : Type u β Type u} [MonadReaderRunner Ο m m'] [MonadFunctor m m' n n'] : MonadReaderRunner Ο n n' :=
β¨fun Ξ± x r => monadMap (fun (Ξ±) (y : m Ξ±) => (runReader y r : m' Ξ±)) xβ©
instance ReaderT.MonadStateRunner [Monad m] : MonadReaderRunner Ο (ReaderT Ο m) m :=
β¨fun Ξ± x r => x rβ©
end
|
710d0bdd251bdb1f5875436e0a1ef8e59362fb46 | bb31430994044506fa42fd667e2d556327e18dfe | /src/analysis/convex/specific_functions.lean | a6a8429d91153ac9ed136940811acbeca6123671 | [
"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 | 13,119 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, SΓ©bastien GouΓ«zel
-/
import analysis.calculus.mean_value
import analysis.special_functions.pow_deriv
import analysis.special_functions.sqrt
/-!
# Collection of convex functions
In this file we prove that the following functions are convex:
* `strict_convex_on_exp` : The exponential function is strictly convex.
* `even.convex_on_pow`, `even.strict_convex_on_pow` : For an even `n : β`, `Ξ» x, x ^ n` is convex
and strictly convex when `2 β€ n`.
* `convex_on_pow`, `strict_convex_on_pow` : For `n : β`, `Ξ» x, x ^ n` is convex on $[0, +β)$ and
strictly convex when `2 β€ n`.
* `convex_on_zpow`, `strict_convex_on_zpow` : For `m : β€`, `Ξ» x, x ^ m` is convex on $[0, +β)$ and
strictly convex when `m β 0, 1`.
* `convex_on_rpow`, `strict_convex_on_rpow` : For `p : β`, `Ξ» x, x ^ p` is convex on $[0, +β)$ when
`1 β€ p` and strictly convex when `1 < p`.
* `strict_concave_on_log_Ioi`, `strict_concave_on_log_Iio`: `real.log` is strictly concave on
$(0, +β)$ and $(-β, 0)$ respectively.
## TODO
For `p : β`, prove that `Ξ» x, x ^ p` is concave when `0 β€ p β€ 1` and strictly concave when
`0 < p < 1`.
-/
open real set
open_locale big_operators nnreal
/-- `exp` is strictly convex on the whole real line. -/
lemma strict_convex_on_exp : strict_convex_on β univ exp :=
strict_convex_on_univ_of_deriv2_pos continuous_exp (Ξ» x, (iter_deriv_exp 2).symm βΈ exp_pos x)
/-- `exp` is convex on the whole real line. -/
lemma convex_on_exp : convex_on β univ exp := strict_convex_on_exp.convex_on
/-- `x^n`, `n : β` is convex on the whole real line whenever `n` is even -/
lemma even.convex_on_pow {n : β} (hn : even n) : convex_on β set.univ (Ξ» x : β, x^n) :=
begin
apply convex_on_univ_of_deriv2_nonneg (differentiable_pow n),
{ simp only [deriv_pow', differentiable.mul, differentiable_const, differentiable_pow] },
{ intro x,
obtain β¨k, hkβ© := (hn.tsub $ even_bit0 _).exists_two_nsmul _,
rw [iter_deriv_pow, finset.prod_range_cast_nat_sub, hk, nsmul_eq_mul, pow_mul'],
exact mul_nonneg (nat.cast_nonneg _) (pow_two_nonneg _) }
end
/-- `x^n`, `n : β` is strictly convex on the whole real line whenever `n β 0` is even. -/
lemma even.strict_convex_on_pow {n : β} (hn : even n) (h : n β 0) :
strict_convex_on β set.univ (Ξ» x : β, x^n) :=
begin
apply strict_mono.strict_convex_on_univ_of_deriv (continuous_pow n),
rw deriv_pow',
replace h := nat.pos_of_ne_zero h,
exact strict_mono.const_mul (odd.strict_mono_pow $ nat.even.sub_odd h hn $ nat.odd_iff.2 rfl)
(nat.cast_pos.2 h),
end
/-- `x^n`, `n : β` is convex on `[0, +β)` for all `n` -/
lemma convex_on_pow (n : β) : convex_on β (Ici 0) (Ξ» x : β, x^n) :=
begin
apply convex_on_of_deriv2_nonneg (convex_Ici _) (continuous_pow n).continuous_on
(differentiable_on_pow n),
{ simp only [deriv_pow'], exact (@differentiable_on_pow β _ _ _).const_mul (n : β) },
{ intros x hx,
rw [iter_deriv_pow, finset.prod_range_cast_nat_sub],
exact mul_nonneg (nat.cast_nonneg _) (pow_nonneg (interior_subset hx) _) }
end
/-- `x^n`, `n : β` is strictly convex on `[0, +β)` for all `n` greater than `2`. -/
lemma strict_convex_on_pow {n : β} (hn : 2 β€ n) : strict_convex_on β (Ici 0) (Ξ» x : β, x^n) :=
begin
apply strict_mono_on.strict_convex_on_of_deriv (convex_Ici _) (continuous_on_pow _),
rw [deriv_pow', interior_Ici],
exact Ξ» x (hx : 0 < x) y hy hxy, mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_left hxy hx.le $
nat.sub_pos_of_lt hn) (nat.cast_pos.2 $ zero_lt_two.trans_le hn),
end
/-- Specific case of Jensen's inequality for sums of powers -/
lemma real.pow_sum_div_card_le_sum_pow {Ξ± : Type*} {s : finset Ξ±} {f : Ξ± β β} (n : β)
(hf : β a β s, 0 β€ f a) : (β x in s, f x) ^ (n + 1) / s.card ^ n β€ β x in s, (f x) ^ (n + 1) :=
begin
rcases s.eq_empty_or_nonempty with rfl | hs,
{ simp_rw [finset.sum_empty, zero_pow' _ (nat.succ_ne_zero n), zero_div] },
{ have hs0 : 0 < (s.card : β) := nat.cast_pos.2 hs.card_pos,
suffices : (β x in s, f x / s.card) ^ (n + 1) β€ β x in s, (f x ^ (n + 1) / s.card),
{ rwa [β finset.sum_div, β finset.sum_div, div_pow, pow_succ' (s.card : β),
β div_div, div_le_iff hs0, div_mul, div_self hs0.ne', div_one] at this },
have := @convex_on.map_sum_le β β β Ξ± _ _ _ _ _ _ (set.Ici 0) (Ξ» x, x ^ (n + 1)) s
(Ξ» _, 1 / s.card) (coe β f) (convex_on_pow (n + 1)) _ _ (Ξ» i hi, set.mem_Ici.2 (hf i hi)),
{ simpa only [inv_mul_eq_div, one_div, algebra.id.smul_eq_mul] using this },
{ simp only [one_div, inv_nonneg, nat.cast_nonneg, implies_true_iff] },
{ simpa only [one_div, finset.sum_const, nsmul_eq_mul] using mul_inv_cancel hs0.ne' } }
end
lemma nnreal.pow_sum_div_card_le_sum_pow {Ξ± : Type*} (s : finset Ξ±) (f : Ξ± β ββ₯0) (n : β) :
(β x in s, f x) ^ (n + 1) / s.card ^ n β€ β x in s, (f x) ^ (n + 1) :=
by simpa only [β nnreal.coe_le_coe, nnreal.coe_sum, nonneg.coe_div, nnreal.coe_pow] using
@real.pow_sum_div_card_le_sum_pow Ξ± s (coe β f) n (Ξ» _ _, nnreal.coe_nonneg _)
lemma finset.prod_nonneg_of_card_nonpos_even
{Ξ± Ξ² : Type*} [linear_ordered_comm_ring Ξ²]
{f : Ξ± β Ξ²} [decidable_pred (Ξ» x, f x β€ 0)]
{s : finset Ξ±} (h0 : even (s.filter (Ξ» x, f x β€ 0)).card) :
0 β€ β x in s, f x :=
calc 0 β€ (β x in s, ((if f x β€ 0 then (-1:Ξ²) else 1) * f x)) :
finset.prod_nonneg (Ξ» x _, by
{ split_ifs with hx hx, by simp [hx], simp at hx β’, exact le_of_lt hx })
... = _ : by rw [finset.prod_mul_distrib, finset.prod_ite, finset.prod_const_one,
mul_one, finset.prod_const, neg_one_pow_eq_pow_mod_two, nat.even_iff.1 h0, pow_zero, one_mul]
lemma int_prod_range_nonneg (m : β€) (n : β) (hn : even n) :
0 β€ β k in finset.range n, (m - k) :=
begin
rcases hn with β¨n, rflβ©,
induction n with n ihn, { simp },
rw β two_mul at ihn,
rw [β two_mul, nat.succ_eq_add_one, mul_add, mul_one, bit0, β add_assoc, finset.prod_range_succ,
finset.prod_range_succ, mul_assoc],
refine mul_nonneg ihn _, generalize : (1 + 1) * n = k,
cases le_or_lt m k with hmk hmk,
{ have : m β€ k + 1, from hmk.trans (lt_add_one βk).le,
convert mul_nonneg_of_nonpos_of_nonpos (sub_nonpos_of_le hmk) _,
convert sub_nonpos_of_le this },
{ exact mul_nonneg (sub_nonneg_of_le hmk.le) (sub_nonneg_of_le hmk) }
end
lemma int_prod_range_pos {m : β€} {n : β} (hn : even n) (hm : m β Ico (0 : β€) n) :
0 < β k in finset.range n, (m - k) :=
begin
refine (int_prod_range_nonneg m n hn).lt_of_ne (Ξ» h, hm _),
rw [eq_comm, finset.prod_eq_zero_iff] at h,
obtain β¨a, ha, hβ© := h,
rw sub_eq_zero.1 h,
exact β¨int.coe_zero_le _, int.coe_nat_lt.2 $ finset.mem_range.1 haβ©,
end
/-- `x^m`, `m : β€` is convex on `(0, +β)` for all `m` -/
lemma convex_on_zpow (m : β€) : convex_on β (Ioi 0) (Ξ» x : β, x^m) :=
begin
have : β n : β€, differentiable_on β (Ξ» x, x ^ n) (Ioi (0 : β)),
from Ξ» n, differentiable_on_zpow _ _ (or.inl $ lt_irrefl _),
apply convex_on_of_deriv2_nonneg (convex_Ioi 0);
try { simp only [interior_Ioi, deriv_zpow'] },
{ exact (this _).continuous_on },
{ exact this _ },
{ exact (this _).const_mul _ },
{ intros x hx,
rw iter_deriv_zpow,
refine mul_nonneg _ (zpow_nonneg (le_of_lt hx) _),
exact_mod_cast int_prod_range_nonneg _ _ (even_bit0 1) }
end
/-- `x^m`, `m : β€` is convex on `(0, +β)` for all `m` except `0` and `1`. -/
lemma strict_convex_on_zpow {m : β€} (hmβ : m β 0) (hmβ : m β 1) :
strict_convex_on β (Ioi 0) (Ξ» x : β, x^m) :=
begin
apply strict_convex_on_of_deriv2_pos' (convex_Ioi 0),
{ exact (continuous_on_zpowβ m).mono (Ξ» x hx, ne_of_gt hx) },
intros x hx,
rw iter_deriv_zpow,
refine mul_pos _ (zpow_pos_of_pos hx _),
exact_mod_cast int_prod_range_pos (even_bit0 1) (Ξ» hm, _),
norm_cast at hm,
rw β finset.coe_Ico at hm,
fin_cases hm; cc,
end
lemma convex_on_rpow {p : β} (hp : 1 β€ p) : convex_on β (Ici 0) (Ξ» x : β, x^p) :=
begin
have A : deriv (Ξ» (x : β), x ^ p) = Ξ» x, p * x^(p-1), by { ext x, simp [hp] },
apply convex_on_of_deriv2_nonneg (convex_Ici 0),
{ exact continuous_on_id.rpow_const (Ξ» x _, or.inr (zero_le_one.trans hp)) },
{ exact (differentiable_rpow_const hp).differentiable_on },
{ rw A,
assume x hx,
replace hx : x β 0, by { simp at hx, exact ne_of_gt hx },
simp [differentiable_at.differentiable_within_at, hx] },
{ assume x hx,
replace hx : 0 < x, by simpa using hx,
suffices : 0 β€ p * ((p - 1) * x ^ (p - 1 - 1)), by simpa [ne_of_gt hx, A],
apply mul_nonneg (le_trans zero_le_one hp),
exact mul_nonneg (sub_nonneg_of_le hp) (rpow_nonneg_of_nonneg hx.le _) }
end
lemma strict_convex_on_rpow {p : β} (hp : 1 < p) : strict_convex_on β (Ici 0) (Ξ» x : β, x^p) :=
begin
have A : deriv (Ξ» (x : β), x ^ p) = Ξ» x, p * x^(p-1), by { ext x, simp [hp.le] },
apply strict_convex_on_of_deriv2_pos (convex_Ici 0),
{ exact continuous_on_id.rpow_const (Ξ» x _, or.inr (zero_le_one.trans hp.le)) },
rw interior_Ici,
rintro x (hx : 0 < x),
suffices : 0 < p * ((p - 1) * x ^ (p - 1 - 1)), by simpa [ne_of_gt hx, A],
exact mul_pos (zero_lt_one.trans hp) (mul_pos (sub_pos_of_lt hp) (rpow_pos_of_pos hx _)),
end
lemma strict_concave_on_log_Ioi : strict_concave_on β (Ioi 0) log :=
begin
have hβ : Ioi 0 β ({0} : set β)αΆ,
{ exact Ξ» x (hx : 0 < x) (hx' : x = 0), hx.ne' hx' },
refine strict_concave_on_of_deriv2_neg' (convex_Ioi 0)
(continuous_on_log.mono hβ) (Ξ» x (hx : 0 < x), _),
rw [function.iterate_succ, function.iterate_one],
change (deriv (deriv log)) x < 0,
rw [deriv_log', deriv_inv],
exact neg_neg_of_pos (inv_pos.2 $ sq_pos_of_ne_zero _ hx.ne'),
end
lemma strict_concave_on_log_Iio : strict_concave_on β (Iio 0) log :=
begin
have hβ : Iio 0 β ({0} : set β)αΆ,
{ exact Ξ» x (hx : x < 0) (hx' : x = 0), hx.ne hx' },
refine strict_concave_on_of_deriv2_neg' (convex_Iio 0)
(continuous_on_log.mono hβ) (Ξ» x (hx : x < 0), _),
rw [function.iterate_succ, function.iterate_one],
change (deriv (deriv log)) x < 0,
rw [deriv_log', deriv_inv],
exact neg_neg_of_pos (inv_pos.2 $ sq_pos_of_ne_zero _ hx.ne),
end
section sqrt_mul_log
lemma has_deriv_at_sqrt_mul_log {x : β} (hx : x β 0) :
has_deriv_at (Ξ» x, sqrt x * log x) ((2 + log x) / (2 * sqrt x)) x :=
begin
convert (has_deriv_at_sqrt hx).mul (has_deriv_at_log hx),
rw [add_div, div_mul_right (sqrt x) two_ne_zero, βdiv_eq_mul_inv, sqrt_div_self',
add_comm, div_eq_mul_one_div, mul_comm],
end
lemma deriv_sqrt_mul_log (x : β) : deriv (Ξ» x, sqrt x * log x) x = (2 + log x) / (2 * sqrt x) :=
begin
cases lt_or_le 0 x with hx hx,
{ exact (has_deriv_at_sqrt_mul_log hx.ne').deriv },
{ rw [sqrt_eq_zero_of_nonpos hx, mul_zero, div_zero],
refine has_deriv_within_at.deriv_eq_zero _ (unique_diff_on_Iic 0 x hx),
refine (has_deriv_within_at_const x _ 0).congr_of_mem (Ξ» x hx, _) hx,
rw [sqrt_eq_zero_of_nonpos hx, zero_mul] },
end
lemma deriv_sqrt_mul_log' : deriv (Ξ» x, sqrt x * log x) = Ξ» x, (2 + log x) / (2 * sqrt x) :=
funext deriv_sqrt_mul_log
lemma deriv2_sqrt_mul_log (x : β) :
deriv^[2] (Ξ» x, sqrt x * log x) x = -log x / (4 * sqrt x ^ 3) :=
begin
simp only [nat.iterate, deriv_sqrt_mul_log'],
cases le_or_lt x 0 with hx hx,
{ rw [sqrt_eq_zero_of_nonpos hx, zero_pow zero_lt_three, mul_zero, div_zero],
refine has_deriv_within_at.deriv_eq_zero _ (unique_diff_on_Iic 0 x hx),
refine (has_deriv_within_at_const _ _ 0).congr_of_mem (Ξ» x hx, _) hx,
rw [sqrt_eq_zero_of_nonpos hx, mul_zero, div_zero] },
{ have hβ : sqrt x β 0, from sqrt_ne_zero'.2 hx,
convert (((has_deriv_at_log hx.ne').const_add 2).div
((has_deriv_at_sqrt hx.ne').const_mul 2) $ mul_ne_zero two_ne_zero hβ).deriv using 1,
nth_rewrite 2 [β mul_self_sqrt hx.le],
field_simp, ring },
end
lemma strict_concave_on_sqrt_mul_log_Ioi : strict_concave_on β (set.Ioi 1) (Ξ» x, sqrt x * log x) :=
begin
apply strict_concave_on_of_deriv2_neg' (convex_Ioi 1) _ (Ξ» x hx, _),
{ exact continuous_sqrt.continuous_on.mul
(continuous_on_log.mono (Ξ» x hx, ne_of_gt (zero_lt_one.trans hx))) },
{ rw [deriv2_sqrt_mul_log x],
exact div_neg_of_neg_of_pos (neg_neg_of_pos (log_pos hx))
(mul_pos four_pos (pow_pos (sqrt_pos.mpr (zero_lt_one.trans hx)) 3)) },
end
end sqrt_mul_log
open_locale real
lemma strict_concave_on_sin_Icc : strict_concave_on β (Icc 0 Ο) sin :=
begin
apply strict_concave_on_of_deriv2_neg (convex_Icc _ _) continuous_on_sin (Ξ» x hx, _),
rw interior_Icc at hx,
simp [sin_pos_of_mem_Ioo hx],
end
lemma strict_concave_on_cos_Icc : strict_concave_on β (Icc (-(Ο/2)) (Ο/2)) cos :=
begin
apply strict_concave_on_of_deriv2_neg (convex_Icc _ _) continuous_on_cos (Ξ» x hx, _),
rw interior_Icc at hx,
simp [cos_pos_of_mem_Ioo hx],
end
|
0d7748258d1dbb64c41cd209987ce5ba1759f0be | 7541ac8517945d0f903ff5397e13e2ccd7c10573 | /src/category_theory/iso_induction.lean | 63fe838861950b4fcebcd44202cac619e32e3ce4 | [] | no_license | ramonfmir/lean-category-theory | 29b6bad9f62c2cdf7517a3135e5a12b340b4ed90 | be516bcbc2dc21b99df2bcb8dde0d1e8de79c9ad | refs/heads/master | 1,586,110,684,637 | 1,541,927,184,000 | 1,541,927,184,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,503 | lean | import category_theory.isomorphism
import category_theory.types
universes u v
def isos (C : Type u) := C
open category_theory
instance category_isos {C : Type u} [category.{u v} C] : category (isos C) :=
{ hom := Ξ» X Y, @iso C _ X Y,
id := iso.refl,
comp := Ξ» X Y Z, iso.trans }
instance category_isos_type : large_category (isos (Type u)) :=
by apply_instance
@[extensionality] lemma monoid.ext {Ξ± : Type u} (m n : monoid Ξ±)
(mul : β x y : Ξ±, (by haveI := m; exact x * y) = (by haveI := n; exact x * y)) : m = n :=
begin
tactic.unfreeze_local_instances,
induction m, induction n,
congr,
{ ext x y,
exact mul x y },
{ dsimp at *,
rw β n_one_mul m_one,
rw β mul,
erw m_mul_one n_one },
end
def monoid_type_constructor : isos (Type u) β₯€ Type u :=
{ obj := monoid,
map := Ξ» Ξ± Ξ² f m,
{ one := f.hom (by resetI; exact 1),
mul := Ξ» x y, begin resetI, exact f.hom (f.inv x * f.inv y) end,
one_mul := sorry,
mul_one := sorry,
mul_assoc := sorry },
}
def monoid_type_constructor_indirection (Ξ± : Type u) : monoid Ξ± = monoid_type_constructor.obj Ξ± := rfl
def monoid_transport {Ξ± Ξ² : Type u} (f : Ξ± β
Ξ²) (m : monoid Ξ±) : monoid Ξ² :=
begin
-- iso_induction f, --
-- This tactic doesn't exist yet, but 'just' needs to do:
rw monoid_type_constructor_indirection Ξ± at m,
replace m := monoid_type_constructor.map f m,
rw β monoid_type_constructor_indirection Ξ² at m,
clear f,
clear Ξ±,
exact m,
end
|
f3b3eda92aad02c8bd871bb552bcfc5b0a7fcd5c | 6b2a480f27775cba4f3ae191b1c1387a29de586e | /group_rep1/equiv.lean | b6baf84cdc61a54d67a2cb14607f7f520cfde118 | [] | no_license | Or7ando/group_representation | a681de2e19d1930a1e1be573d6735a2f0b8356cb | 9b576984f17764ebf26c8caa2a542d248f1b50d2 | refs/heads/master | 1,662,413,107,324 | 1,590,302,389,000 | 1,590,302,389,000 | 258,130,829 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 293 | lean | import linear_algebra.basic
import algebra.module
variables (M : Type )(R :Type) [ring R] [add_comm_group M] [add_comm_group M] [module R M]
variables (f g : Mββ[R]M)
example : f * g = linear_map.id := sorry
#check (by apply_instance : has_mul (Mββ[R]M ))
linear_map.has_scalar |
5f43f5035565fb90803e33fe18ecf93848653f3f | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/data/equiv/ring.lean | d19f6b4785407c6bf2ed0d9055227a3c2fff13e3 | [
"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 | 10,235 | lean | /-
Copyright (c) 2018 Johannes HΓΆlzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes HΓΆlzl, Callum Sutton, Yury Kudryashov
-/
import data.equiv.mul_add
import algebra.field
import algebra.opposites
import deprecated.ring
/-!
# (Semi)ring equivs
In this file we define extension of `equiv` called `ring_equiv`, which is a datatype representing an
isomorphism of `semiring`s, `ring`s, `division_ring`s, or `field`s. We also introduce the
corresponding group of automorphisms `ring_aut`.
## Notations
The extended equiv have coercions to functions, and the coercion is the canonical notation when
treating the isomorphism as maps.
## Implementation notes
The fields for `ring_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are
deprecated.
Definition of multiplication in the groups of automorphisms agrees with function composition,
multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with
`category_theory.comp`.
## Tags
equiv, mul_equiv, add_equiv, ring_equiv, mul_aut, add_aut, ring_aut
-/
variables {R : Type*} {S : Type*} {S' : Type*}
set_option old_structure_cmd true
/- (semi)ring equivalence. -/
structure ring_equiv (R S : Type*) [has_mul R] [has_add R] [has_mul S] [has_add S]
extends R β S, R β* S, R β+ S
infix ` β+* `:25 := ring_equiv
namespace ring_equiv
section basic
variables [has_mul R] [has_add R] [has_mul S] [has_add S] [has_mul S'] [has_add S']
instance : has_coe_to_fun (R β+* S) := β¨_, ring_equiv.to_funβ©
@[simp] lemma to_fun_eq_coe_fun (f : R β+* S) : f.to_fun = f := rfl
instance has_coe_to_mul_equiv : has_coe (R β+* S) (R β* S) := β¨ring_equiv.to_mul_equivβ©
instance has_coe_to_add_equiv : has_coe (R β+* S) (R β+ S) := β¨ring_equiv.to_add_equivβ©
@[norm_cast] lemma coe_mul_equiv (f : R β+* S) (a : R) :
(f : R β* S) a = f a := rfl
@[norm_cast] lemma coe_add_equiv (f : R β+* S) (a : R) :
(f : R β+ S) a = f a := rfl
variable (R)
/-- The identity map is a ring isomorphism. -/
@[refl] protected def refl : R β+* R := { .. mul_equiv.refl R, .. add_equiv.refl R }
@[simp] lemma refl_apply (x : R) : ring_equiv.refl R x = x := rfl
@[simp] lemma coe_add_equiv_refl : (ring_equiv.refl R : R β+ R) = add_equiv.refl R := rfl
@[simp] lemma coe_mul_equiv_refl : (ring_equiv.refl R : R β* R) = mul_equiv.refl R := rfl
variables {R}
/-- The inverse of a ring isomorphism is a ring isomorphism. -/
@[symm] protected def symm (e : R β+* S) : S β+* R :=
{ .. e.to_mul_equiv.symm, .. e.to_add_equiv.symm }
/-- Transitivity of `ring_equiv`. -/
@[trans] protected def trans (eβ : R β+* S) (eβ : S β+* S') : R β+* S' :=
{ .. (eβ.to_mul_equiv.trans eβ.to_mul_equiv), .. (eβ.to_add_equiv.trans eβ.to_add_equiv) }
protected lemma bijective (e : R β+* S) : function.bijective e := e.to_equiv.bijective
protected lemma injective (e : R β+* S) : function.injective e := e.to_equiv.injective
protected lemma surjective (e : R β+* S) : function.surjective e := e.to_equiv.surjective
@[simp] lemma apply_symm_apply (e : R β+* S) : β x, e (e.symm x) = x := e.to_equiv.apply_symm_apply
@[simp] lemma symm_apply_apply (e : R β+* S) : β x, e.symm (e x) = x := e.to_equiv.symm_apply_apply
lemma image_eq_preimage (e : R β+* S) (s : set R) : e '' s = e.symm β»ΒΉ' s :=
e.to_equiv.image_eq_preimage s
end basic
section comm_semiring
open opposite
variables (R) [comm_semiring R]
/-- A commutative ring is isomorphic to its opposite. -/
def to_opposite : R β+* Rα΅α΅ :=
{ map_add' := Ξ» x y, rfl,
map_mul' := Ξ» x y, mul_comm (op y) (op x),
..equiv_to_opposite }
@[simp]
lemma to_opposite_apply (r : R) : to_opposite R r = op r := rfl
@[simp]
lemma to_opposite_symm_apply (r : Rα΅α΅) : (to_opposite R).symm r = unop r := rfl
end comm_semiring
section
variables [semiring R] [semiring S] (f : R β+* S) (x y : R)
/-- A ring isomorphism preserves multiplication. -/
@[simp] lemma map_mul : f (x * y) = f x * f y := f.map_mul' x y
/-- A ring isomorphism sends one to one. -/
@[simp] lemma map_one : f 1 = 1 := (f : R β* S).map_one
/-- A ring isomorphism preserves addition. -/
@[simp] lemma map_add : f (x + y) = f x + f y := f.map_add' x y
/-- A ring isomorphism sends zero to zero. -/
@[simp] lemma map_zero : f 0 = 0 := (f : R β+ S).map_zero
variable {x}
@[simp] lemma map_eq_one_iff : f x = 1 β x = 1 := (f : R β* S).map_eq_one_iff
@[simp] lemma map_eq_zero_iff : f x = 0 β x = 0 := (f : R β+ S).map_eq_zero_iff
lemma map_ne_one_iff : f x β 1 β x β 1 := (f : R β* S).map_ne_one_iff
lemma map_ne_zero_iff : f x β 0 β x β 0 := (f : R β+ S).map_ne_zero_iff
end
section
variables [ring R] [ring S] (f : R β+* S) (x y : R)
@[simp] lemma map_neg : f (-x) = -f x := (f : R β+ S).map_neg x
@[simp] lemma map_sub : f (x - y) = f x - f y := (f : R β+ S).map_sub x y
@[simp] lemma map_neg_one : f (-1) = -1 := f.map_one βΈ f.map_neg 1
end
section semiring_hom
variables [semiring R] [semiring S]
/-- Reinterpret a ring equivalence as a ring homomorphism. -/
def to_ring_hom (e : R β+* S) : R β+* S :=
{ .. e.to_mul_equiv.to_monoid_hom, .. e.to_add_equiv.to_add_monoid_hom }
/-- Reinterpret a ring equivalence as a monoid homomorphism. -/
abbreviation to_monoid_hom (e : R β+* S) : R β* S := e.to_ring_hom.to_monoid_hom
/-- Reinterpret a ring equivalence as an `add_monoid` homomorphism. -/
abbreviation to_add_monoid_hom (e : R β+* S) : R β+ S := e.to_ring_hom.to_add_monoid_hom
/-- Interpret an equivalence `f : R β S` as a ring equivalence `R β+* S`. -/
def of (e : R β S) [is_semiring_hom e] : R β+* S :=
{ .. e, .. monoid_hom.of e, .. add_monoid_hom.of e }
instance (e : R β+* S) : is_semiring_hom e := e.to_ring_hom.is_semiring_hom
@[simp]
lemma to_ring_hom_refl : (ring_equiv.refl R).to_ring_hom = ring_hom.id R := rfl
@[simp]
lemma to_monoid_hom_refl : (ring_equiv.refl R).to_monoid_hom = monoid_hom.id R := rfl
@[simp]
lemma to_add_monoid_hom_refl : (ring_equiv.refl R).to_add_monoid_hom = add_monoid_hom.id R := rfl
@[simp]
lemma to_ring_hom_apply_symm_to_ring_hom_apply {R S} [semiring R] [semiring S] (e : R β+* S) :
β (y : S), e.to_ring_hom (e.symm.to_ring_hom y) = y :=
e.to_equiv.apply_symm_apply
@[simp]
lemma symm_to_ring_hom_apply_to_ring_hom_apply {R S} [semiring R] [semiring S] (e : R β+* S) :
β (x : R), e.symm.to_ring_hom (e.to_ring_hom x) = x :=
equiv.symm_apply_apply (e.to_equiv)
end semiring_hom
end ring_equiv
namespace mul_equiv
/-- Gives a `ring_equiv` from a `mul_equiv` preserving addition.-/
def to_ring_equiv {R : Type*} {S : Type*} [has_add R] [has_add S] [has_mul R] [has_mul S]
(h : R β* S) (H : β x y : R, h (x + y) = h x + h y) : R β+* S :=
{..h.to_equiv, ..h, ..add_equiv.mk' h.to_equiv H }
end mul_equiv
namespace ring_equiv
section ring_hom
variables [ring R] [ring S]
/-- Interpret an equivalence `f : R β S` as a ring equivalence `R β+* S`. -/
def of' (e : R β S) [is_ring_hom e] : R β+* S :=
{ .. e, .. monoid_hom.of e, .. add_monoid_hom.of e }
instance (e : R β+* S) : is_ring_hom e := e.to_ring_hom.is_ring_hom
end ring_hom
/-- Two ring isomorphisms agree if they are defined by the
same underlying function. -/
@[ext] lemma ext {R S : Type*} [has_mul R] [has_add R] [has_mul S] [has_add S]
{f g : R β+* S} (h : β x, f x = g x) : f = g :=
begin
have hβ : f.to_equiv = g.to_equiv := equiv.ext h,
cases f, cases g, congr,
{ exact (funext h) },
{ exact congr_arg equiv.inv_fun hβ }
end
/-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/
protected lemma is_integral_domain {A : Type*} (B : Type*) [ring A] [ring B]
(hB : is_integral_domain B) (e : A β+* B) : is_integral_domain A :=
{ mul_comm := Ξ» x y, have e.symm (e x * e y) = e.symm (e y * e x), by rw hB.mul_comm, by simpa,
eq_zero_or_eq_zero_of_mul_eq_zero := Ξ» x y hxy,
have e x * e y = 0, by rw [β e.map_mul, hxy, e.map_zero],
(hB.eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).imp (Ξ» hx, by simpa using congr_arg e.symm hx)
(Ξ» hy, by simpa using congr_arg e.symm hy),
exists_pair_ne := β¨e.symm 0, e.symm 1,
by { haveI : nontrivial B := hB.to_nontrivial, exact e.symm.injective.ne zero_ne_one }β© }
/-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/
protected def integral_domain {A : Type*} (B : Type*) [ring A] [integral_domain B]
(e : A β+* B) : integral_domain A :=
{ .. (βΉ_βΊ : ring A), .. e.is_integral_domain B (integral_domain.to_is_integral_domain B) }
end ring_equiv
/-- The group of ring automorphisms. -/
@[reducible] def ring_aut (R : Type*) [has_mul R] [has_add R] := ring_equiv R R
namespace ring_aut
variables (R) [has_mul R] [has_add R]
/--
The group operation on automorphisms of a ring is defined by
Ξ» g h, ring_equiv.trans h g.
This means that multiplication agrees with composition, (g*h)(x) = g (h x) .
-/
instance : group (ring_aut R) :=
by refine_struct
{ mul := Ξ» g h, ring_equiv.trans h g,
one := ring_equiv.refl R,
inv := ring_equiv.symm };
intros; ext; try { refl }; apply equiv.left_inv
instance : inhabited (ring_aut R) := β¨1β©
/-- Monoid homomorphism from ring automorphisms to additive automorphisms. -/
def to_add_aut : ring_aut R β* add_aut R :=
by refine_struct { to_fun := ring_equiv.to_add_equiv }; intros; refl
/-- Monoid homomorphism from ring automorphisms to multiplicative automorphisms. -/
def to_mul_aut : ring_aut R β* mul_aut R :=
by refine_struct { to_fun := ring_equiv.to_mul_equiv }; intros; refl
/-- Monoid homomorphism from ring automorphisms to permutations. -/
def to_perm : ring_aut R β* equiv.perm R :=
by refine_struct { to_fun := ring_equiv.to_equiv }; intros; refl
end ring_aut
namespace equiv
variables (K : Type*) [division_ring K]
def units_equiv_ne_zero : units K β {a : K | a β 0} :=
β¨Ξ» a, β¨a.1, a.coe_ne_zeroβ©, Ξ» a, units.mk0 _ a.2, Ξ» β¨_, _, _, _β©, units.ext rfl, Ξ» β¨_, _β©, rflβ©
variable {K}
@[simp]
lemma coe_units_equiv_ne_zero (a : units K) :
((units_equiv_ne_zero K a) : K) = a := rfl
end equiv
|
67417b65760f4b7a57fda876f3794b7279862c16 | 947b78d97130d56365ae2ec264df196ce769371a | /stage0/src/Lean/ParserCompiler.lean | 4a792d78481e6206f2ea366b4ffcd7e021cc83b0 | [
"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 | 6,073 | lean | /-
Copyright (c) 2020 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
/-!
Gadgets for compiling parser declarations into other programs, such as pretty printers.
-/
import Lean.Util.ReplaceExpr
import Lean.Meta.Basic
import Lean.Meta.WHNF
import Lean.ParserCompiler.Attribute
import Lean.Parser.Extension
namespace Lean
namespace ParserCompiler
structure Context (Ξ± : Type) :=
(varName : Name)
(runtimeAttr : KeyedDeclsAttribute Ξ±)
(combinatorAttr : CombinatorAttribute)
(interpretParserDescr : ParserDescr β AttrM Ξ±)
def Context.tyName {Ξ±} (ctx : Context Ξ±) : Name := ctx.runtimeAttr.defn.valueTypeName
-- replace all references of `Parser` with `tyName` as a first approximation
def preprocessParserBody {Ξ±} (ctx : Context Ξ±) (e : Expr) : Expr :=
e.replace fun e => if e.isConstOf `Lean.Parser.Parser then mkConst ctx.tyName else none
section
open Meta
-- translate an expression of type `Parser` into one of type `tyName`
partial def compileParserBody {Ξ±} (ctx : Context Ξ±) : Expr β MetaM Expr | e => do
e β whnfCore e;
match e with
| e@(Expr.lam _ _ _ _) => lambdaLetTelescope e fun xs b => compileParserBody b >>= mkLambdaFVars xs
| e@(Expr.fvar _ _) => pure e
| _ => do
let fn := e.getAppFn;
Expr.const c _ _ β pure fn
| throwError $ "call of unknown parser at '" ++ toString e ++ "'";
let args := e.getAppArgs;
-- call the translated `p` with (a prefix of) the arguments of `e`, recursing for arguments
-- of type `ty` (i.e. formerly `Parser`)
let mkCall (p : Name) := do {
ty β inferType (mkConst p);
forallTelescope ty fun params _ =>
params.foldlMβ (fun p param arg => do
paramTy β inferType param;
resultTy β forallTelescope paramTy fun _ b => pure b;
arg β if resultTy.isConstOf ctx.tyName then compileParserBody arg
else pure arg;
pure $ mkApp p arg)
(mkConst p)
e.getAppArgs
};
env β getEnv;
match ctx.combinatorAttr.getDeclFor env c with
| some p => mkCall p
| none => do
let c' := c ++ ctx.varName;
cinfo β getConstInfo c;
resultTy β forallTelescope cinfo.type fun _ b => pure b;
if resultTy.isConstOf `Lean.Parser.TrailingParser || resultTy.isConstOf `Lean.Parser.Parser then do
-- synthesize a new `[combinatorAttr c]`
some value β pure cinfo.value?
| throwError $ "don't know how to generate " ++ ctx.varName ++ " for non-definition '" ++ toString e ++ "'";
value β compileParserBody $ preprocessParserBody ctx value;
ty β forallTelescope cinfo.type fun params _ =>
params.foldrM (fun param ty => do
paramTy β inferType param;
paramTy β forallTelescope paramTy fun _ b => pure $
if b.isConstOf `Lean.Parser.Parser then mkConst ctx.tyName
else b;
pure $ mkForall `_ BinderInfo.default paramTy ty)
(mkConst ctx.tyName);
let decl := Declaration.defnDecl { name := c', lparams := [],
type := ty, value := value, hints := ReducibilityHints.opaque, isUnsafe := false };
env β getEnv;
env β match env.addAndCompile {} decl with
| Except.ok env => pure env
| Except.error kex => do { d β liftIO $ (kex.toMessageData {}).toString; throwError d };
setEnv $ ctx.combinatorAttr.setDeclFor env c c';
mkCall c'
else do
-- if this is a generic function, e.g. `HasAndthen.andthen`, it's easier to just unfold it until we are
-- back to parser combinators
some e' β unfoldDefinition? e
| throwError $ "don't know how to generate " ++ ctx.varName ++ " for non-parser combinator '" ++ toString e ++ "'";
compileParserBody e'
end
open Core
/-- Compile the given declaration into a `[(builtin)runtimeAttr declName]` -/
def compileParser {Ξ±} (ctx : Context Ξ±) (declName : Name) (builtin : Bool) : AttrM Unit := do
-- This will also tag the declaration as a `[combinatorParenthesizer declName]` in case the parser is used by other parsers.
-- Note that simply having `[(builtin)Parenthesizer]` imply `[combinatorParenthesizer]` is not ideal since builtin
-- attributes are active only in the next stage, while `[combinatorParenthesizer]` is active immediately (since we never
-- call them at compile time but only reference them).
(Expr.const c' _ _) β liftM $ (compileParserBody ctx (mkConst declName)).run'
| unreachable!;
-- We assume that for tagged parsers, the kind is equal to the declaration name. This is automatically true for parsers
-- using `parser!` or `syntax`.
let kind := declName;
addAttribute c' (if builtin then ctx.runtimeAttr.defn.builtinName else ctx.runtimeAttr.defn.name) (mkNullNode #[mkIdent kind])
-- When called from `interpretParserDescr`, `declName` might not be a tagged parser, so ignore "not a valid syntax kind" failures
<|> pure ()
unsafe def interpretParser {Ξ±} (ctx : Context Ξ±) (constName : Name) : AttrM Ξ± := do
info β getConstInfo constName;
env β getEnv;
if info.type.isConstOf `Lean.Parser.TrailingParser || info.type.isConstOf `Lean.Parser.Parser then
match ctx.runtimeAttr.getValues env constName with
| p::_ => pure p
| _ => do
compileParser ctx constName /- builtin -/ false;
env β getEnv;
ofExcept $ env.evalConst Ξ± (constName ++ ctx.varName)
else do
d β ofExcept $ env.evalConst TrailingParserDescr constName;
ctx.interpretParserDescr d
unsafe def registerParserCompiler {Ξ±} (ctx : Context Ξ±) : IO Unit := do
Parser.registerParserAttributeHook {
postAdd := fun catName declName builtin =>
if builtin then
compileParser ctx declName builtin
else do
p β interpretParser ctx declName;
-- Register `p` without exporting it to the .olean file. It will be re-interpreted and registered
-- when the parser is imported.
env β getEnv;
setEnv $ ctx.runtimeAttr.ext.modifyState env fun st => { st with table := st.table.insert declName p }
}
end ParserCompiler
end Lean
|
cf8a80ce4b0ec0f8233239fbdc4be6128cea9628 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/polynomial/coeff.lean | 099ef2d77a6d9fb9bec8b1e93409df3def9d4ddd | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,899 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes HΓΆlzl, Scott Morrison, Jens Wagemaker
-/
import data.polynomial.basic
import data.finset.nat_antidiagonal
import data.nat.choose.sum
/-!
# Theory of univariate polynomials
The theorems include formulas for computing coefficients, such as
`coeff_add`, `coeff_sum`, `coeff_mul`
-/
noncomputable theory
open finsupp finset add_monoid_algebra
open_locale big_operators
namespace polynomial
universes u v
variables {R : Type u} {S : Type v} {a b : R} {n m : β}
variables [semiring R] {p q r : polynomial R}
section coeff
lemma coeff_one (n : β) : coeff (1 : polynomial R) n = if 0 = n then 1 else 0 :=
coeff_monomial
@[simp]
lemma coeff_add (p q : polynomial R) (n : β) : coeff (p + q) n = coeff p n + coeff q n :=
by { rcases p, rcases q, simp [coeff, add_to_finsupp] }
@[simp] lemma coeff_smul [monoid S] [distrib_mul_action S R] (r : S) (p : polynomial R) (n : β) :
coeff (r β’ p) n = r β’ coeff p n :=
by { rcases p, simp [coeff, smul_to_finsupp] }
lemma support_smul [monoid S] [distrib_mul_action S R] (r : S) (p : polynomial R) :
support (r β’ p) β support p :=
begin
assume i hi,
simp [mem_support_iff] at hi β’,
contrapose! hi,
simp [hi]
end
/-- `polynomial.sum` as a linear map. -/
@[simps] def lsum {R A M : Type*} [semiring R] [semiring A] [add_comm_monoid M]
[module R A] [module R M] (f : β β A ββ[R] M) :
polynomial A ββ[R] M :=
{ to_fun := Ξ» p, p.sum (Ξ» n r, f n r),
map_add' := Ξ» p q, sum_add_index p q _ (Ξ» n, (f n).map_zero) (Ξ» n _ _, (f n).map_add _ _),
map_smul' := Ξ» c p,
begin
rw [sum_eq_of_subset _ (Ξ» n r, f n r) (Ξ» n, (f n).map_zero) _ (support_smul c p)],
simp only [sum_def, finset.smul_sum, coeff_smul, linear_map.map_smul, ring_hom.id_apply]
end }
variable (R)
/-- The nth coefficient, as a linear map. -/
def lcoeff (n : β) : polynomial R ββ[R] R :=
{ to_fun := Ξ» p, coeff p n,
map_add' := Ξ» p q, coeff_add p q n,
map_smul' := Ξ» r p, coeff_smul r p n }
variable {R}
@[simp] lemma lcoeff_apply (n : β) (f : polynomial R) : lcoeff R n f = coeff f n := rfl
@[simp] lemma finset_sum_coeff {ΞΉ : Type*} (s : finset ΞΉ) (f : ΞΉ β polynomial R) (n : β) :
coeff (β b in s, f b) n = β b in s, coeff (f b) n :=
(lcoeff R n).map_sum
lemma coeff_sum [semiring S] (n : β) (f : β β R β polynomial S) :
coeff (p.sum f) n = p.sum (Ξ» a b, coeff (f a b) n) :=
by { rcases p, simp [polynomial.sum, support, coeff] }
/-- Decomposes the coefficient of the product `p * q` as a sum
over `nat.antidiagonal`. A version which sums over `range (n + 1)` can be obtained
by using `finset.nat.sum_antidiagonal_eq_sum_range_succ`. -/
lemma coeff_mul (p q : polynomial R) (n : β) :
coeff (p * q) n = β x in nat.antidiagonal n, coeff p x.1 * coeff q x.2 :=
begin
rcases p, rcases q,
simp only [coeff, mul_to_finsupp],
exact add_monoid_algebra.mul_apply_antidiagonal p q n _ (Ξ» x, nat.mem_antidiagonal)
end
@[simp] lemma mul_coeff_zero (p q : polynomial R) : coeff (p * q) 0 = coeff p 0 * coeff q 0 :=
by simp [coeff_mul]
lemma coeff_mul_X_zero (p : polynomial R) : coeff (p * X) 0 = 0 :=
by simp
lemma coeff_X_mul_zero (p : polynomial R) : coeff (X * p) 0 = 0 :=
by simp
lemma coeff_C_mul_X (x : R) (k n : β) :
coeff (C x * X^k : polynomial R) n = if n = k then x else 0 :=
by { rw [β monomial_eq_C_mul_X, coeff_monomial], congr' 1, simp [eq_comm] }
@[simp] lemma coeff_C_mul (p : polynomial R) : coeff (C a * p) n = a * coeff p n :=
by { rcases p, simp only [C, monomial, monomial_fun, mul_to_finsupp, ring_hom.coe_mk,
coeff, add_monoid_algebra.single_zero_mul_apply p a n] }
lemma C_mul' (a : R) (f : polynomial R) : C a * f = a β’ f :=
by { ext, rw [coeff_C_mul, coeff_smul, smul_eq_mul] }
@[simp] lemma coeff_mul_C (p : polynomial R) (n : β) (a : R) :
coeff (p * C a) n = coeff p n * a :=
by { rcases p, simp only [C, monomial, monomial_fun, mul_to_finsupp, ring_hom.coe_mk,
coeff, add_monoid_algebra.mul_single_zero_apply p a n] }
lemma coeff_X_pow (k n : β) :
coeff (X^k : polynomial R) n = if n = k then 1 else 0 :=
by simp only [one_mul, ring_hom.map_one, β coeff_C_mul_X]
@[simp]
lemma coeff_X_pow_self (n : β) :
coeff (X^n : polynomial R) n = 1 :=
by simp [coeff_X_pow]
theorem coeff_mul_X_pow (p : polynomial R) (n d : β) :
coeff (p * polynomial.X ^ n) (d + n) = coeff p d :=
begin
rw [coeff_mul, sum_eq_single (d,n), coeff_X_pow, if_pos rfl, mul_one],
{ rintros β¨i,jβ© h1 h2, rw [coeff_X_pow, if_neg, mul_zero], rintro rfl, apply h2,
rw [nat.mem_antidiagonal, add_right_cancel_iff] at h1, subst h1 },
{ exact Ξ» h1, (h1 (nat.mem_antidiagonal.2 rfl)).elim }
end
lemma coeff_mul_X_pow' (p : polynomial R) (n d : β) :
(p * X ^ n).coeff d = ite (n β€ d) (p.coeff (d - n)) 0 :=
begin
split_ifs,
{ rw [β tsub_add_cancel_of_le h, coeff_mul_X_pow, add_tsub_cancel_right] },
{ refine (coeff_mul _ _ _).trans (finset.sum_eq_zero (Ξ» x hx, _)),
rw [coeff_X_pow, if_neg, mul_zero],
exact ne_of_lt (lt_of_le_of_lt (nat.le_of_add_le_right
(le_of_eq (finset.nat.mem_antidiagonal.mp hx))) (not_le.mp h)) },
end
@[simp] theorem coeff_mul_X (p : polynomial R) (n : β) :
coeff (p * X) (n + 1) = coeff p n :=
by simpa only [pow_one] using coeff_mul_X_pow p 1 n
theorem mul_X_pow_eq_zero {p : polynomial R} {n : β}
(H : p * X ^ n = 0) : p = 0 :=
ext $ Ξ» k, (coeff_mul_X_pow p n k).symm.trans $ ext_iff.1 H (k+n)
lemma C_mul_X_pow_eq_monomial (c : R) (n : β) : C c * X^n = monomial n c :=
by { ext1, rw [monomial_eq_smul_X, coeff_smul, coeff_C_mul, smul_eq_mul] }
lemma support_mul_X_pow (c : R) (n : β) (H : c β 0) : (C c * X^n).support = singleton n :=
by rw [C_mul_X_pow_eq_monomial, support_monomial n c H]
lemma support_C_mul_X_pow' {c : R} {n : β} : (C c * X^n).support β singleton n :=
by { rw [C_mul_X_pow_eq_monomial], exact support_monomial' n c }
lemma coeff_X_add_one_pow (R : Type*) [semiring R] (n k : β) :
((X + 1) ^ n).coeff k = (n.choose k : R) :=
begin
rw [(commute_X (1 : polynomial R)).add_pow, β lcoeff_apply, linear_map.map_sum],
simp only [one_pow, mul_one, lcoeff_apply, β C_eq_nat_cast, coeff_mul_C, nat.cast_id],
rw [finset.sum_eq_single k, coeff_X_pow_self, one_mul],
{ intros _ _,
simp only [coeff_X_pow, boole_mul, ite_eq_right_iff, ne.def] {contextual := tt},
rintro h rfl, contradiction },
{ simp only [coeff_X_pow_self, one_mul, not_lt, finset.mem_range],
intro h, rw [nat.choose_eq_zero_of_lt h, nat.cast_zero], }
end
lemma coeff_one_add_X_pow (R : Type*) [semiring R] (n k : β) :
((1 + X) ^ n).coeff k = (n.choose k : R) :=
by rw [add_comm _ X, coeff_X_add_one_pow]
lemma C_dvd_iff_dvd_coeff (r : R) (Ο : polynomial R) :
C r β£ Ο β β i, r β£ Ο.coeff i :=
begin
split,
{ rintros β¨Ο, rflβ© c, rw coeff_C_mul, apply dvd_mul_right },
{ intro h,
choose c hc using h,
classical,
let c' : β β R := Ξ» i, if i β Ο.support then c i else 0,
let Ο : polynomial R := β i in Ο.support, monomial i (c' i),
use Ο,
ext i,
simp only [Ο, c', coeff_C_mul, mem_support_iff, coeff_monomial,
finset_sum_coeff, finset.sum_ite_eq'],
split_ifs with hi hi,
{ rw hc },
{ rw [not_not] at hi, rwa mul_zero } },
end
lemma coeff_bit0_mul (P Q : polynomial R) (n : β) :
coeff (bit0 P * Q) n = 2 * coeff (P * Q) n :=
by simp [bit0, add_mul]
lemma coeff_bit1_mul (P Q : polynomial R) (n : β) :
coeff (bit1 P * Q) n = 2 * coeff (P * Q) n + coeff Q n :=
by simp [bit1, add_mul, coeff_bit0_mul]
lemma smul_eq_C_mul (a : R) : a β’ p = C a * p := by simp [ext_iff]
lemma update_eq_add_sub_coeff {R : Type*} [ring R] (p : polynomial R) (n : β) (a : R) :
p.update n a = p + (polynomial.C (a - p.coeff n) * polynomial.X ^ n) :=
begin
ext,
rw [coeff_update_apply, coeff_add, coeff_C_mul_X],
split_ifs with h;
simp [h]
end
end coeff
section cast
@[simp] lemma nat_cast_coeff_zero {n : β} {R : Type*} [semiring R] :
(n : polynomial R).coeff 0 = n :=
begin
induction n with n ih,
{ simp, },
{ simp [ih], },
end
@[simp, norm_cast] theorem nat_cast_inj
{m n : β} {R : Type*} [semiring R] [char_zero R] : (βm : polynomial R) = βn β m = n :=
begin
fsplit,
{ intro h,
apply_fun (Ξ» p, p.coeff 0) at h,
simpa using h, },
{ rintro rfl, refl, },
end
@[simp] lemma int_cast_coeff_zero {i : β€} {R : Type*} [ring R] :
(i : polynomial R).coeff 0 = i :=
by cases i; simp
@[simp, norm_cast] theorem int_cast_inj
{m n : β€} {R : Type*} [ring R] [char_zero R] : (βm : polynomial R) = βn β m = n :=
begin
fsplit,
{ intro h,
apply_fun (Ξ» p, p.coeff 0) at h,
simpa using h, },
{ rintro rfl, refl, },
end
end cast
end polynomial
|
76ae9ebf7440907ef6d11719ad21707e9ef58f35 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/unfold_cases.lean | 5ee52a444ef20ac1db053cceb0efba88d4da13ca | [] | 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,228 | lean | /-
Copyright (c) 2020 Dany Fabian. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Dany Fabian
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.split_ifs
import Mathlib.PostPort
namespace Mathlib
/-!
# Unfold cases tactic
In Lean, pattern matching expressions are not atomic parts of the syntax, but
rather they are compiled down into simpler terms that are later checked by the kernel.
This allows Lean to have a minimalistic kernel but can occasionally lead an explosion
of cases that need to be considered. What looks like one case in the `match` expression
can in fact be compiled into many different cases that all need to proved by case analysis.
This tactic automates the process by allowing us to write down an equation `f x = y`
where we know that `f x = y` is provably true, but does not hold definitionally. In that
case the `unfold_cases` tactic will continue unfolding `f` and introducing `cases` where
necessary until the left hand side becomes definitionally equal to the right hand side.
Consider a definition as follows:
```lean
def myand : bool β bool β bool
| ff _ := ff
| _ ff := ff
| _ _ := tt
```
The equation compiler generates 4 equation lemmas for us:
```lean
myand ff ff = ff
myand ff tt = ff
myand tt ff = ff
myand tt tt = tt
```
This is not in line with what one might expect looking at the definition.
Whilst it is provably true, that `β x, myand ff x = ff` and `β x, myand x ff = ff`,
we do not get these stronger lemmas from the compiler for free but must in fact
prove them using `cases` or some other local reasoning.
In other words, the following does not constitute a proof that lean accepts.
```lean
example : β x, myand ff x = ff :=
begin
intros, refl
end
```
However, you can use `unfold_cases { refl }` to prove `β x, myand ff x = ff` and
`β x, myand x ff = ff`. For definitions with many cases, the savings can be very
significant.
The term that gets generated for the above definition looks like this:
```lean
Ξ» (a a_1 : bool),
a.cases_on
(a_1.cases_on (id_rhs bool ff) (id_rhs bool ff))
(a_1.cases_on (id_rhs bool ff) (id_rhs bool tt))
```
When the tactic tries to prove the goal `β x, myand ff x = ff`, it starts by `intros`,
followed by unfolding the definition:
```lean
β’ ff.cases_on
(x.cases_on (id_rhs bool ff) (id_rhs bool ff))
(x.cases_on (id_rhs bool ff) (id_rhs bool tt)) = ff
```
At this point, it can make progress using `dsimp`. But then it gets stuck:
```lean
β’ bool.rec (id_rhs bool ff) (id_rhs bool ff) x = ff
```
Next, it can introduce a case split on `x`. At this point, it has to prove two
goals:
```lean
β’ bool.rec (id_rhs bool ff) (id_rhs bool ff) ff = ff
β’ bool.rec (id_rhs bool ff) (id_rhs bool ff) tt = ff
```
Now, however, both goals can be discharged using `refl`.
-/
namespace tactic
namespace unfold_cases
/--
Given an equation `f x = y`, this tactic tries to infer an expression that can be
used to do distinction by cases on to make progress.
Pre-condition: assumes that the outer-most application cannot be beta-reduced
(e.g. `whnf` or `dsimp`).
-/
/--
Tries to finish the current goal using the `inner` tactic. If the tactic
fails, it tries to find an expression on which to do a distinction by
cases and calls itself recursively.
The order of operations is significant. Because the unfolding can potentially
be infinite, it is important to apply the `inner` tactic at every step.
Notice, that if the `inner` tactic succeeds, the recursive unfolding is stopped.
-/
/--
Given a target of the form `β’ f xβ ... xβ = y`, unfolds `f` using a delta reduction.
-/
end unfold_cases
namespace interactive
/--
This tactic unfolds the definition of a function or `match` expression.
Then it recursively introduces a distinction by cases. The decision what expression
to do the distinction on is driven by the pattern matching expression.
A typical use case is using `unfold_cases { refl }` to collapse cases that need to be
considered in a pattern matching.
```lean
have h : foo x = y, by unfold_cases { refl },
rw h,
```
The tactic expects a goal in the form of an equation, possibly universally quantified.
We can prove a theorem, even if the various case do not directly correspond to the
function definition. Here is an example application of the tactic:
```lean
def foo : β β β β β
| 0 0 := 17
| (n+2) 17 := 17
| 1 0 := 23
| 0 (n+18) := 15
| 0 17 := 17
| 1 17 := 17
| _ (n+18) := 27
| _ _ := 15
example : β x, foo x 17 = 17 :=
begin
unfold_cases { refl },
end
```
The compiler generates 57 cases for `foo`. However, when we look at the definition, we see
that whenever the function is applied to `17` in the second argument, it returns `17`.
Proving this property consists of merely considering all the cases, eliminating invalid ones
and applying `refl` on the ones which remain.
Further examples can be found in `test/unfold_cases.lean`.
-/
|
659600b047e7505696973670d1ea27ba1511ae4a | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/monoidal/Mod.lean | 0a351deb1f418c09a79b91f2e98179ceb2c1cd1b | [] | 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,479 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.monoidal.Mon_
import Mathlib.PostPort
universes vβ uβ l
namespace Mathlib
/-!
# The category of module objects over a monoid object.
-/
/-- A module object for a monoid object, all internal to some monoidal category. -/
structure Mod {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] (A : Mon_ C)
where
X : C
act : Mon_.X A β X βΆ X
one_act' : autoParam ((Mon_.one A β π) β« act = category_theory.iso.hom Ξ»_)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
assoc' : autoParam ((Mon_.mul A β π) β« act = category_theory.iso.hom Ξ±_ β« (π β act) β« act)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
@[simp] theorem Mod.one_act {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (c : Mod A) : (Mon_.one A β π) β« Mod.act c = category_theory.iso.hom Ξ»_ := sorry
@[simp] theorem Mod.assoc {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (c : Mod A) : (Mon_.mul A β π) β« Mod.act c = category_theory.iso.hom Ξ±_ β« (π β Mod.act c) β« Mod.act c := sorry
@[simp] theorem Mod.one_act_assoc {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (c : Mod A) {X' : C} (f' : Mod.X c βΆ X') : (Mon_.one A β π) β« Mod.act c β« f' = category_theory.iso.hom Ξ»_ β« f' := sorry
namespace Mod
theorem assoc_flip {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (M : Mod A) : (π β act M) β« act M = category_theory.iso.inv Ξ±_ β« (Mon_.mul A β π) β« act M := sorry
/-- A morphism of module objects. -/
structure hom {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (M : Mod A) (N : Mod A)
where
hom : X M βΆ X N
act_hom' : autoParam (act M β« hom = (π β hom) β« act N)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
@[simp] theorem hom.act_hom {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} {M : Mod A} {N : Mod A} (c : hom M N) : act M β« hom.hom c = (π β hom.hom c) β« act N := sorry
@[simp] theorem hom.act_hom_assoc {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} {M : Mod A} {N : Mod A} (c : hom M N) {X' : C} (f' : X N βΆ X') : act M β« hom.hom c β« f' = (π β hom.hom c) β« act N β« f' := sorry
/-- The identity morphism on a module object. -/
def id {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (M : Mod A) : hom M M :=
hom.mk π
protected instance hom_inhabited {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (M : Mod A) : Inhabited (hom M M) :=
{ default := id M }
/-- Composition of module object morphisms. -/
def comp {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} {M : Mod A} {N : Mod A} {O : Mod A} (f : hom M N) (g : hom N O) : hom M O :=
hom.mk (hom.hom f β« hom.hom g)
protected instance category_theory.category {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} : category_theory.category (Mod A) :=
category_theory.category.mk
@[simp] theorem id_hom' {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (M : Mod A) : hom.hom π = π :=
rfl
@[simp] theorem comp_hom' {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} {M : Mod A} {N : Mod A} {K : Mod A} (f : M βΆ N) (g : N βΆ K) : hom.hom (f β« g) = hom.hom f β« hom.hom g :=
rfl
/-- A monoid object as a module over itself. -/
@[simp] theorem regular_X {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] (A : Mon_ C) : X (regular A) = Mon_.X A :=
Eq.refl (X (regular A))
protected instance inhabited {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] (A : Mon_ C) : Inhabited (Mod A) :=
{ default := regular A }
/-- The forgetful functor from module objects to the ambient category. -/
def forget {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] (A : Mon_ C) : Mod A β₯€ C :=
category_theory.functor.mk (fun (A_1 : Mod A) => X A_1) fun (A_1 B : Mod A) (f : A_1 βΆ B) => hom.hom f
/--
A morphism of monoid objects induces a "restriction" or "comap" functor
between the categories of module objects.
-/
@[simp] theorem comap_obj_act {C : Type uβ} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} {B : Mon_ C} (f : A βΆ B) (M : Mod B) : act (category_theory.functor.obj (comap f) M) = (Mon_.hom.hom f β π) β« act M :=
Eq.refl (act (category_theory.functor.obj (comap f) M))
|
2113f55a2782463a586a9afd9db0fc14600a4711 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/ring_theory/class_group.lean | 6ad944e45c7be561384ebce8c5daac118ac65853 | [
"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 | 10,439 | lean | /-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import group_theory.quotient_group
import ring_theory.dedekind_domain
/-!
# The ideal class group
This file defines the ideal class group `class_group R K` of fractional ideals of `R`
inside `A`'s field of fractions `K`.
## Main definitions
- `to_principal_ideal` sends an invertible `x : K` to an invertible fractional ideal
- `class_group` is the quotient of invertible fractional ideals modulo `to_principal_ideal.range`
- `class_group.mk0` sends a nonzero integral ideal in a Dedekind domain to its class
## Main results
- `class_group.mk0_eq_mk0_iff` shows the equivalence with the "classical" definition,
where `I ~ J` iff `x I = y J` for `x y β (0 : R)`
-/
variables {R K L : Type*} [comm_ring R]
variables [field K] [field L] [decidable_eq L]
variables [algebra R K] [is_fraction_ring R K]
variables [algebra K L] [finite_dimensional K L]
variables [algebra R L] [is_scalar_tower R K L]
open_locale non_zero_divisors
open is_localization is_fraction_ring fractional_ideal units
section
variables (R K)
/-- `to_principal_ideal R K x` sends `x β 0 : K` to the fractional `R`-ideal generated by `x` -/
@[irreducible]
def to_principal_ideal : KΛ£ β* (fractional_ideal Rβ° K)Λ£ :=
{ to_fun := Ξ» x,
β¨span_singleton _ x,
span_singleton _ xβ»ΒΉ,
by simp only [span_singleton_one, units.mul_inv', span_singleton_mul_span_singleton],
by simp only [span_singleton_one, units.inv_mul', span_singleton_mul_span_singleton]β©,
map_mul' := Ξ» x y, ext
(by simp only [units.coe_mk, units.coe_mul, span_singleton_mul_span_singleton]),
map_one' := ext (by simp only [span_singleton_one, units.coe_mk, units.coe_one]) }
local attribute [semireducible] to_principal_ideal
variables {R K}
@[simp] lemma coe_to_principal_ideal (x : KΛ£) :
(to_principal_ideal R K x : fractional_ideal Rβ° K) = span_singleton _ x :=
rfl
@[simp] lemma to_principal_ideal_eq_iff {I : (fractional_ideal Rβ° K)Λ£} {x : KΛ£} :
to_principal_ideal R K x = I β span_singleton Rβ° (x : K) = I :=
units.ext_iff
end
instance principal_ideals.normal : (to_principal_ideal R K).range.normal :=
subgroup.normal_of_comm _
section
variables (R K)
/-- The ideal class group of `R` in a field of fractions `K`
is the group of invertible fractional ideals modulo the principal ideals. -/
@[derive(comm_group)]
def class_group := (fractional_ideal Rβ° K)Λ£ β§Έ (to_principal_ideal R K).range
instance : inhabited (class_group R K) := β¨1β©
variables {R} [is_domain R]
/-- Send a nonzero integral ideal to an invertible fractional ideal. -/
@[simps]
noncomputable def fractional_ideal.mk0 [is_dedekind_domain R] :
(ideal R)β° β* (fractional_ideal Rβ° K)Λ£ :=
{ to_fun := Ξ» I, units.mk0 I ((fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl Rβ°)).mpr
(mem_non_zero_divisors_iff_ne_zero.mp I.2)),
map_one' := by simp,
map_mul' := Ξ» x y, by simp }
/-- Send a nonzero ideal to the corresponding class in the class group. -/
@[simps]
noncomputable def class_group.mk0 [is_dedekind_domain R] :
(ideal R)β° β* class_group R K :=
(quotient_group.mk' _).comp (fractional_ideal.mk0 K)
variables {K}
lemma quotient_group.mk'_eq_mk' {G : Type*} [group G] {N : subgroup G} [hN : N.normal] {x y : G} :
quotient_group.mk' N x = quotient_group.mk' N y β β z β N, x * z = y :=
(@quotient.eq _ (quotient_group.left_rel _) _ _).trans
β¨Ξ» (h : xβ»ΒΉ * y β N), β¨_, h, by rw [β mul_assoc, mul_right_inv, one_mul]β©,
Ξ» β¨z, z_mem, eq_yβ©,
by { rw β eq_y, show xβ»ΒΉ * (x * z) β N, rwa [β mul_assoc, mul_left_inv, one_mul] }β©
lemma class_group.mk0_eq_mk0_iff_exists_fraction_ring [is_dedekind_domain R] {I J : (ideal R)β°} :
class_group.mk0 K I = class_group.mk0 K J β
β (x β (0 : K)), span_singleton Rβ° x * I = J :=
begin
simp only [class_group.mk0, monoid_hom.comp_apply, quotient_group.mk'_eq_mk'],
split,
{ rintros β¨_, β¨x, rflβ©, hxβ©,
refine β¨x, x.ne_zero, _β©,
simpa only [mul_comm, coe_mk0, monoid_hom.to_fun_eq_coe, coe_to_principal_ideal, units.coe_mul]
using congr_arg (coe : _ β fractional_ideal Rβ° K) hx },
{ rintros β¨x, hx, eq_Jβ©,
refine β¨_, β¨units.mk0 x hx, rflβ©, units.ext _β©,
simpa only [fractional_ideal.mk0_apply, units.coe_mk0, mul_comm, coe_to_principal_ideal,
coe_coe, units.coe_mul] using eq_J }
end
lemma class_group.mk0_eq_mk0_iff [is_dedekind_domain R] {I J : (ideal R)β°} :
class_group.mk0 K I = class_group.mk0 K J β
β (x y : R) (hx : x β 0) (hy : y β 0), ideal.span {x} * (I : ideal R) = ideal.span {y} * J :=
begin
refine class_group.mk0_eq_mk0_iff_exists_fraction_ring.trans β¨_, _β©,
{ rintros β¨z, hz, hβ©,
obtain β¨x, β¨y, hyβ©, rflβ© := is_localization.mk'_surjective Rβ° z,
refine β¨x, y, _, mem_non_zero_divisors_iff_ne_zero.mp hy, _β©,
{ rintro hx, apply hz,
rw [hx, is_fraction_ring.mk'_eq_div, (algebra_map R K).map_zero, zero_div] },
{ exact (fractional_ideal.mk'_mul_coe_ideal_eq_coe_ideal K hy).mp h } },
{ rintros β¨x, y, hx, hy, hβ©,
have hy' : y β Rβ° := mem_non_zero_divisors_iff_ne_zero.mpr hy,
refine β¨is_localization.mk' K x β¨y, hy'β©, _, _β©,
{ contrapose! hx,
rwa [is_localization.mk'_eq_iff_eq_mul, zero_mul, β (algebra_map R K).map_zero,
(is_fraction_ring.injective R K).eq_iff] at hx },
{ exact (fractional_ideal.mk'_mul_coe_ideal_eq_coe_ideal K hy').mpr h } },
end
lemma class_group.mk0_surjective [is_dedekind_domain R] :
function.surjective (class_group.mk0 K : (ideal R)β° β class_group R K) :=
begin
rintros β¨Iβ©,
obtain β¨a, a_ne_zero', haβ© := I.1.2,
have a_ne_zero := mem_non_zero_divisors_iff_ne_zero.mp a_ne_zero',
have fa_ne_zero : (algebra_map R K) a β 0 :=
is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors a_ne_zero',
refine β¨β¨{ carrier := { x | (algebra_map R K a)β»ΒΉ * algebra_map R K x β I.1 }, .. }, _β©, _β©,
{ simp only [ring_hom.map_zero, set.mem_set_of_eq, mul_zero, ring_hom.map_mul],
exact submodule.zero_mem I },
{ simp only [ring_hom.map_add, set.mem_set_of_eq, mul_zero, ring_hom.map_mul, mul_add],
exact Ξ» _ _ ha hb, submodule.add_mem I ha hb },
{ intros c _ hb,
simp only [smul_eq_mul, set.mem_set_of_eq, mul_zero, ring_hom.map_mul, mul_add,
mul_left_comm ((algebra_map R K) a)β»ΒΉ],
rw β algebra.smul_def c,
exact submodule.smul_mem I c hb },
{ rw [mem_non_zero_divisors_iff_ne_zero, submodule.zero_eq_bot, submodule.ne_bot_iff],
obtain β¨x, x_ne, x_memβ© := exists_ne_zero_mem_is_integer I.ne_zero,
refine β¨a * x, _, mul_ne_zero a_ne_zero x_neβ©,
change ((algebra_map R K) a)β»ΒΉ * (algebra_map R K) (a * x) β I.1,
rwa [ring_hom.map_mul, β mul_assoc, inv_mul_cancel fa_ne_zero, one_mul] },
{ symmetry,
apply quotient.sound,
refine β¨units.mk0 (algebra_map R K a) fa_ne_zero, _β©,
apply @mul_left_cancel _ _ I,
rw [β mul_assoc, mul_right_inv, one_mul, eq_comm, mul_comm I],
apply units.ext,
simp only [monoid_hom.coe_mk, subtype.coe_mk, ring_hom.map_mul, coe_coe,
units.coe_mul, coe_to_principal_ideal, coe_mk0,
fractional_ideal.eq_span_singleton_mul],
split,
{ intros zJ' hzJ',
obtain β¨zJ, hzJ : (algebra_map R K a)β»ΒΉ * algebra_map R K zJ β βI, rflβ© :=
(mem_coe_ideal Rβ°).mp hzJ',
refine β¨_, hzJ, _β©,
rw [β mul_assoc, mul_inv_cancel fa_ne_zero, one_mul] },
{ intros zI' hzI',
obtain β¨y, hyβ© := ha zI' hzI',
rw [β algebra.smul_def, fractional_ideal.mk0_apply, coe_mk0, coe_coe, mem_coe_ideal],
refine β¨y, _, hyβ©,
show (algebra_map R K a)β»ΒΉ * algebra_map R K y β (I : fractional_ideal Rβ° K),
rwa [hy, algebra.smul_def, β mul_assoc, inv_mul_cancel fa_ne_zero, one_mul] } }
end
end
lemma class_group.mk_eq_one_iff
{I : (fractional_ideal Rβ° K)Λ£} :
quotient_group.mk' (to_principal_ideal R K).range I = 1 β
(I : submodule R K).is_principal :=
begin
rw [β (quotient_group.mk' _).map_one, eq_comm, quotient_group.mk'_eq_mk'],
simp only [exists_prop, one_mul, exists_eq_right, to_principal_ideal_eq_iff,
monoid_hom.mem_range, coe_coe],
refine β¨Ξ» β¨x, hxβ©, β¨β¨x, by rw [β hx, coe_span_singleton]β©β©, _β©,
unfreezingI { intros hI },
obtain β¨x, hxβ© := @submodule.is_principal.principal _ _ _ _ _ _ hI,
have hx' : (I : fractional_ideal Rβ° K) = span_singleton Rβ° x,
{ apply subtype.coe_injective, rw [hx, coe_span_singleton] },
refine β¨units.mk0 x _, _β©,
{ intro x_eq, apply units.ne_zero I, simp [hx', x_eq] },
simp [hx']
end
variables [is_domain R]
lemma class_group.mk0_eq_one_iff [is_dedekind_domain R]
{I : ideal R} (hI : I β (ideal R)β°) :
class_group.mk0 K β¨I, hIβ© = 1 β I.is_principal :=
class_group.mk_eq_one_iff.trans (coe_submodule_is_principal R K)
/-- The class group of principal ideal domain is finite (in fact a singleton).
TODO: generalize to Dedekind domains -/
instance [is_principal_ideal_ring R] :
fintype (class_group R K) :=
{ elems := {1},
complete :=
begin
rintros β¨Iβ©,
rw [finset.mem_singleton],
exact class_group.mk_eq_one_iff.mpr (I : fractional_ideal Rβ° K).is_principal
end }
/-- The class number of a principal ideal domain is `1`. -/
lemma card_class_group_eq_one [is_principal_ideal_ring R] :
fintype.card (class_group R K) = 1 :=
begin
rw fintype.card_eq_one_iff,
use 1,
rintros β¨Iβ©,
exact class_group.mk_eq_one_iff.mpr (I : fractional_ideal Rβ° K).is_principal
end
/-- The class number is `1` iff the ring of integers is a principal ideal domain. -/
lemma card_class_group_eq_one_iff [is_dedekind_domain R] [fintype (class_group R K)] :
fintype.card (class_group R K) = 1 β is_principal_ideal_ring R :=
begin
split, swap, { introsI, convert card_class_group_eq_one, assumption, assumption, },
rw fintype.card_eq_one_iff,
rintros β¨I, hIβ©,
have eq_one : β J : class_group R K, J = 1 := Ξ» J, trans (hI J) (hI 1).symm,
refine β¨Ξ» I, _β©,
by_cases hI : I = β₯,
{ rw hI, exact bot_is_principal },
exact (class_group.mk0_eq_one_iff (mem_non_zero_divisors_iff_ne_zero.mpr hI)).mp (eq_one _),
end
|
28ef71cd535d51a6c2ff7053c422cc44104b5e4c | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/order/conditionally_complete_lattice.lean | 918585e263151e36cb74bb60e45073bd6e70b76b | [
"Apache-2.0"
] | permissive | troyjlee/mathlib | e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5 | 45e7eb8447555247246e3fe91c87066506c14875 | refs/heads/master | 1,689,248,035,046 | 1,629,470,528,000 | 1,629,470,528,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 49,687 | lean | /-
Copyright (c) 2018 SΓ©bastien GouΓ«zel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: SΓ©bastien GouΓ«zel
-/
import data.nat.enat
import data.set.intervals.ord_connected
/-!
# Theory of conditionally complete lattices.
A conditionally complete lattice is a lattice in which every non-empty bounded subset s
has a least upper bound and a greatest lower bound, denoted below by Sup s and Inf s.
Typical examples are real, nat, int with their usual orders.
The theory is very comparable to the theory of complete lattices, except that suitable
boundedness and nonemptiness assumptions have to be added to most statements.
We introduce two predicates bdd_above and bdd_below to express this boundedness, prove
their basic properties, and then go on to prove most useful properties of Sup and Inf
in conditionally complete lattices.
To differentiate the statements between complete lattices and conditionally complete
lattices, we prefix Inf and Sup in the statements by c, giving cInf and cSup. For instance,
Inf_le is a statement in complete lattices ensuring Inf s β€ x, while cInf_le is the same
statement in conditionally complete lattices with an additional assumption that s is
bounded below.
-/
set_option old_structure_cmd true
open set
variables {Ξ± Ξ² : Type*} {ΞΉ : Sort*}
section
/-!
Extension of Sup and Inf from a preorder `Ξ±` to `with_top Ξ±` and `with_bot Ξ±`
-/
open_locale classical
noncomputable instance {Ξ± : Type*} [preorder Ξ±] [has_Sup Ξ±] : has_Sup (with_top Ξ±) :=
β¨Ξ» S, if β€ β S then β€ else
if bdd_above (coe β»ΒΉ' S : set Ξ±) then β(Sup (coe β»ΒΉ' S : set Ξ±)) else β€β©
noncomputable instance {Ξ± : Type*} [has_Inf Ξ±] : has_Inf (with_top Ξ±) :=
β¨Ξ» S, if S β {β€} then β€ else β(Inf (coe β»ΒΉ' S : set Ξ±))β©
noncomputable instance {Ξ± : Type*} [has_Sup Ξ±] : has_Sup (with_bot Ξ±) :=
β¨(@with_top.has_Inf (order_dual Ξ±) _).Infβ©
noncomputable instance {Ξ± : Type*} [preorder Ξ±] [has_Inf Ξ±] : has_Inf (with_bot Ξ±) :=
β¨(@with_top.has_Sup (order_dual Ξ±) _ _).Supβ©
@[simp]
theorem with_top.cInf_empty {Ξ± : Type*} [has_Inf Ξ±] : Inf (β
: set (with_top Ξ±)) = β€ :=
if_pos $ set.empty_subset _
@[simp]
theorem with_bot.cSup_empty {Ξ± : Type*} [has_Sup Ξ±] : Sup (β
: set (with_bot Ξ±)) = β₯ :=
if_pos $ set.empty_subset _
end -- section
/-- A conditionally complete lattice is a lattice in which
every nonempty subset which is bounded above has a supremum, and
every nonempty subset which is bounded below has an infimum.
Typical examples are real numbers or natural numbers.
To differentiate the statements from the corresponding statements in (unconditional)
complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should
hold in both worlds, sometimes with additional assumptions of nonemptiness or
boundedness.-/
class conditionally_complete_lattice (Ξ± : Type*) extends lattice Ξ±, has_Sup Ξ±, has_Inf Ξ± :=
(le_cSup : βs a, bdd_above s β a β s β a β€ Sup s)
(cSup_le : β s a, set.nonempty s β a β upper_bounds s β Sup s β€ a)
(cInf_le : βs a, bdd_below s β a β s β Inf s β€ a)
(le_cInf : βs a, set.nonempty s β a β lower_bounds s β a β€ Inf s)
/-- A conditionally complete linear order is a linear order in which
every nonempty subset which is bounded above has a supremum, and
every nonempty subset which is bounded below has an infimum.
Typical examples are real numbers or natural numbers.
To differentiate the statements from the corresponding statements in (unconditional)
complete linear orders, we prefix Inf and Sup by a c everywhere. The same statements should
hold in both worlds, sometimes with additional assumptions of nonemptiness or
boundedness.-/
class conditionally_complete_linear_order (Ξ± : Type*)
extends conditionally_complete_lattice Ξ±, linear_order Ξ±
/-- A conditionally complete linear order with `bot` is a linear order with least element, in which
every nonempty subset which is bounded above has a supremum, and every nonempty subset (necessarily
bounded below) has an infimum. A typical example is the natural numbers.
To differentiate the statements from the corresponding statements in (unconditional)
complete linear orders, we prefix Inf and Sup by a c everywhere. The same statements should
hold in both worlds, sometimes with additional assumptions of nonemptiness or
boundedness.-/
class conditionally_complete_linear_order_bot (Ξ± : Type*)
extends conditionally_complete_linear_order Ξ±, order_bot Ξ± :=
(cSup_empty : Sup β
= β₯)
/- A complete lattice is a conditionally complete lattice, as there are no restrictions
on the properties of Inf and Sup in a complete lattice.-/
@[priority 100] -- see Note [lower instance priority]
instance conditionally_complete_lattice_of_complete_lattice [complete_lattice Ξ±]:
conditionally_complete_lattice Ξ± :=
{ le_cSup := by intros; apply le_Sup; assumption,
cSup_le := by intros; apply Sup_le; assumption,
cInf_le := by intros; apply Inf_le; assumption,
le_cInf := by intros; apply le_Inf; assumption,
..βΉcomplete_lattice Ξ±βΊ }
@[priority 100] -- see Note [lower instance priority]
instance conditionally_complete_linear_order_of_complete_linear_order [complete_linear_order Ξ±]:
conditionally_complete_linear_order Ξ± :=
{ ..conditionally_complete_lattice_of_complete_lattice, .. βΉcomplete_linear_order Ξ±βΊ }
section order_dual
instance (Ξ± : Type*) [conditionally_complete_lattice Ξ±] :
conditionally_complete_lattice (order_dual Ξ±) :=
{ le_cSup := @conditionally_complete_lattice.cInf_le Ξ± _,
cSup_le := @conditionally_complete_lattice.le_cInf Ξ± _,
le_cInf := @conditionally_complete_lattice.cSup_le Ξ± _,
cInf_le := @conditionally_complete_lattice.le_cSup Ξ± _,
..order_dual.has_Inf Ξ±,
..order_dual.has_Sup Ξ±,
..order_dual.lattice Ξ± }
instance (Ξ± : Type*) [conditionally_complete_linear_order Ξ±] :
conditionally_complete_linear_order (order_dual Ξ±) :=
{ ..order_dual.conditionally_complete_lattice Ξ±,
..order_dual.linear_order Ξ± }
end order_dual
section conditionally_complete_lattice
variables [conditionally_complete_lattice Ξ±] {s t : set Ξ±} {a b : Ξ±}
theorem le_cSup (hβ : bdd_above s) (hβ : a β s) : a β€ Sup s :=
conditionally_complete_lattice.le_cSup s a hβ hβ
theorem cSup_le (hβ : s.nonempty) (hβ : βbβs, b β€ a) : Sup s β€ a :=
conditionally_complete_lattice.cSup_le s a hβ hβ
theorem cInf_le (hβ : bdd_below s) (hβ : a β s) : Inf s β€ a :=
conditionally_complete_lattice.cInf_le s a hβ hβ
theorem le_cInf (hβ : s.nonempty) (hβ : βbβs, a β€ b) : a β€ Inf s :=
conditionally_complete_lattice.le_cInf s a hβ hβ
theorem le_cSup_of_le (_ : bdd_above s) (hb : b β s) (h : a β€ b) : a β€ Sup s :=
le_trans h (le_cSup βΉbdd_above sβΊ hb)
theorem cInf_le_of_le (_ : bdd_below s) (hb : b β s) (h : b β€ a) : Inf s β€ a :=
le_trans (cInf_le βΉbdd_below sβΊ hb) h
theorem cSup_le_cSup (_ : bdd_above t) (_ : s.nonempty) (h : s β t) : Sup s β€ Sup t :=
cSup_le βΉ_βΊ (assume (a) (ha : a β s), le_cSup βΉbdd_above tβΊ (h ha))
theorem cInf_le_cInf (_ : bdd_below t) (_ : s.nonempty) (h : s β t) : Inf t β€ Inf s :=
le_cInf βΉ_βΊ (assume (a) (ha : a β s), cInf_le βΉbdd_below tβΊ (h ha))
lemma is_lub_cSup (ne : s.nonempty) (H : bdd_above s) : is_lub s (Sup s) :=
β¨assume x, le_cSup H, assume x, cSup_le neβ©
lemma is_lub_csupr [nonempty ΞΉ] {f : ΞΉ β Ξ±} (H : bdd_above (range f)) :
is_lub (range f) (β¨ i, f i) :=
is_lub_cSup (range_nonempty f) H
lemma is_lub_csupr_set {f : Ξ² β Ξ±} {s : set Ξ²} (H : bdd_above (f '' s)) (Hne : s.nonempty) :
is_lub (f '' s) (β¨ i : s, f i) :=
by { rw β Sup_image', exact is_lub_cSup (Hne.image _) H }
lemma is_glb_cInf (ne : s.nonempty) (H : bdd_below s) : is_glb s (Inf s) :=
β¨assume x, cInf_le H, assume x, le_cInf neβ©
lemma is_glb_cinfi [nonempty ΞΉ] {f : ΞΉ β Ξ±} (H : bdd_below (range f)) :
is_glb (range f) (β¨
i, f i) :=
is_glb_cInf (range_nonempty f) H
lemma is_glb_cinfi_set {f : Ξ² β Ξ±} {s : set Ξ²} (H : bdd_below (f '' s)) (Hne : s.nonempty) :
is_glb (f '' s) (β¨
i : s, f i) :=
@is_lub_csupr_set (order_dual Ξ±) _ _ _ _ H Hne
lemma is_lub.cSup_eq (H : is_lub s a) (ne : s.nonempty) : Sup s = a :=
(is_lub_cSup ne β¨a, H.1β©).unique H
lemma is_lub.csupr_eq [nonempty ΞΉ] {f : ΞΉ β Ξ±} (H : is_lub (range f) a) : (β¨ i, f i) = a :=
H.cSup_eq (range_nonempty f)
lemma is_lub.csupr_set_eq {s : set Ξ²} {f : Ξ² β Ξ±} (H : is_lub (f '' s) a) (Hne : s.nonempty) :
(β¨ i : s, f i) = a :=
is_lub.cSup_eq (image_eq_range f s βΈ H) (image_eq_range f s βΈ Hne.image f)
/-- A greatest element of a set is the supremum of this set. -/
lemma is_greatest.cSup_eq (H : is_greatest s a) : Sup s = a :=
H.is_lub.cSup_eq H.nonempty
lemma is_greatest.Sup_mem (H : is_greatest s a) : Sup s β s :=
H.cSup_eq.symm βΈ H.1
lemma is_glb.cInf_eq (H : is_glb s a) (ne : s.nonempty) : Inf s = a :=
(is_glb_cInf ne β¨a, H.1β©).unique H
lemma is_glb.cinfi_eq [nonempty ΞΉ] {f : ΞΉ β Ξ±} (H : is_lub (range f) a) : (β¨ i, f i) = a :=
H.cSup_eq (range_nonempty f)
lemma is_glb.cinfi_set_eq {s : set Ξ²} {f : Ξ² β Ξ±} (H : is_glb (f '' s) a) (Hne : s.nonempty) :
(β¨
i : s, f i) = a :=
is_glb.cInf_eq (image_eq_range f s βΈ H) (image_eq_range f s βΈ Hne.image f)
/-- A least element of a set is the infimum of this set. -/
lemma is_least.cInf_eq (H : is_least s a) : Inf s = a :=
H.is_glb.cInf_eq H.nonempty
lemma is_least.Inf_mem (H : is_least s a) : Inf s β s :=
H.cInf_eq.symm βΈ H.1
lemma subset_Icc_cInf_cSup (hb : bdd_below s) (ha : bdd_above s) :
s β Icc (Inf s) (Sup s) :=
Ξ» x hx, β¨cInf_le hb hx, le_cSup ha hxβ©
theorem cSup_le_iff (hb : bdd_above s) (ne : s.nonempty) : Sup s β€ a β (βb β s, b β€ a) :=
is_lub_le_iff (is_lub_cSup ne hb)
theorem le_cInf_iff (hb : bdd_below s) (ne : s.nonempty) : a β€ Inf s β (βb β s, a β€ b) :=
le_is_glb_iff (is_glb_cInf ne hb)
lemma cSup_lower_bounds_eq_cInf {s : set Ξ±} (h : bdd_below s) (hs : s.nonempty) :
Sup (lower_bounds s) = Inf s :=
(is_lub_cSup h $ hs.mono $ Ξ» x hx y hy, hy hx).unique (is_glb_cInf hs h).is_lub
lemma cInf_upper_bounds_eq_cSup {s : set Ξ±} (h : bdd_above s) (hs : s.nonempty) :
Inf (upper_bounds s) = Sup s :=
(is_glb_cInf h $ hs.mono $ Ξ» x hx y hy, hy hx).unique (is_lub_cSup hs h).is_glb
/--Introduction rule to prove that `b` is the supremum of `s`: it suffices to check that `b`
is larger than all elements of `s`, and that this is not the case of any `w<b`.
See `Sup_eq_of_forall_le_of_forall_lt_exists_gt` for a version in complete lattices. -/
theorem cSup_eq_of_forall_le_of_forall_lt_exists_gt (_ : s.nonempty)
(_ : βaβs, a β€ b) (H : βw, w < b β (βaβs, w < a)) : Sup s = b :=
have bdd_above s := β¨b, by assumptionβ©,
have (Sup s < b) β¨ (Sup s = b) := lt_or_eq_of_le (cSup_le βΉ_βΊ βΉβaβs, a β€ bβΊ),
have Β¬(Sup s < b) :=
assume: Sup s < b,
let β¨a, _, _β© := (H (Sup s) βΉSup s < bβΊ) in /- a β s, Sup s < a-/
have Sup s < Sup s := lt_of_lt_of_le βΉSup s < aβΊ (le_cSup βΉbdd_above sβΊ βΉa β sβΊ),
show false, by finish [lt_irrefl (Sup s)],
show Sup s = b, by finish
/--Introduction rule to prove that `b` is the infimum of `s`: it suffices to check that `b`
is smaller than all elements of `s`, and that this is not the case of any `w>b`.
See `Inf_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in complete lattices. -/
theorem cInf_eq_of_forall_ge_of_forall_gt_exists_lt (_ : s.nonempty) (_ : βaβs, b β€ a)
(H : βw, b < w β (βaβs, a < w)) : Inf s = b :=
@cSup_eq_of_forall_le_of_forall_lt_exists_gt (order_dual Ξ±) _ _ _ βΉ_βΊ βΉ_βΊ βΉ_βΊ
/--b < Sup s when there is an element a in s with b < a, when s is bounded above.
This is essentially an iff, except that the assumptions for the two implications are
slightly different (one needs boundedness above for one direction, nonemptiness and linear
order for the other one), so we formulate separately the two implications, contrary to
the complete_lattice case.-/
lemma lt_cSup_of_lt (_ : bdd_above s) (_ : a β s) (_ : b < a) : b < Sup s :=
lt_of_lt_of_le βΉb < aβΊ (le_cSup βΉbdd_above sβΊ βΉa β sβΊ)
/--Inf s < b when there is an element a in s with a < b, when s is bounded below.
This is essentially an iff, except that the assumptions for the two implications are
slightly different (one needs boundedness below for one direction, nonemptiness and linear
order for the other one), so we formulate separately the two implications, contrary to
the complete_lattice case.-/
lemma cInf_lt_of_lt (_ : bdd_below s) (_ : a β s) (_ : a < b) : Inf s < b :=
@lt_cSup_of_lt (order_dual Ξ±) _ _ _ _ βΉ_βΊ βΉ_βΊ βΉ_βΊ
/-- If all elements of a nonempty set `s` are less than or equal to all elements
of a nonempty set `t`, then there exists an element between these sets. -/
lemma exists_between_of_forall_le (sne : s.nonempty) (tne : t.nonempty)
(hst : β (x β s) (y β t), x β€ y) :
(upper_bounds s β© lower_bounds t).nonempty :=
β¨Inf t, Ξ» x hx, le_cInf tne $ hst x hx, Ξ» y hy, cInf_le (sne.mono hst) hyβ©
/--The supremum of a singleton is the element of the singleton-/
@[simp] theorem cSup_singleton (a : Ξ±) : Sup {a} = a :=
is_greatest_singleton.cSup_eq
/--The infimum of a singleton is the element of the singleton-/
@[simp] theorem cInf_singleton (a : Ξ±) : Inf {a} = a :=
is_least_singleton.cInf_eq
/--If a set is bounded below and above, and nonempty, its infimum is less than or equal to
its supremum.-/
theorem cInf_le_cSup (hb : bdd_below s) (ha : bdd_above s) (ne : s.nonempty) : Inf s β€ Sup s :=
is_glb_le_is_lub (is_glb_cInf ne hb) (is_lub_cSup ne ha) ne
/--The sup of a union of two sets is the max of the suprema of each subset, under the assumptions
that all sets are bounded above and nonempty.-/
theorem cSup_union (hs : bdd_above s) (sne : s.nonempty) (ht : bdd_above t) (tne : t.nonempty) :
Sup (s βͺ t) = Sup s β Sup t :=
((is_lub_cSup sne hs).union (is_lub_cSup tne ht)).cSup_eq sne.inl
/--The inf of a union of two sets is the min of the infima of each subset, under the assumptions
that all sets are bounded below and nonempty.-/
theorem cInf_union (hs : bdd_below s) (sne : s.nonempty) (ht : bdd_below t) (tne : t.nonempty) :
Inf (s βͺ t) = Inf s β Inf t :=
@cSup_union (order_dual Ξ±) _ _ _ hs sne ht tne
/--The supremum of an intersection of two sets is bounded by the minimum of the suprema of each
set, if all sets are bounded above and nonempty.-/
theorem cSup_inter_le (_ : bdd_above s) (_ : bdd_above t) (hst : (s β© t).nonempty) :
Sup (s β© t) β€ Sup s β Sup t :=
begin
apply cSup_le hst, simp only [le_inf_iff, and_imp, set.mem_inter_eq], intros b _ _, split,
apply le_cSup βΉbdd_above sβΊ βΉb β sβΊ,
apply le_cSup βΉbdd_above tβΊ βΉb β tβΊ
end
/--The infimum of an intersection of two sets is bounded below by the maximum of the
infima of each set, if all sets are bounded below and nonempty.-/
theorem le_cInf_inter (_ : bdd_below s) (_ : bdd_below t) (hst : (s β© t).nonempty) :
Inf s β Inf t β€ Inf (s β© t) :=
@cSup_inter_le (order_dual Ξ±) _ _ _ βΉ_βΊ βΉ_βΊ hst
/-- The supremum of insert a s is the maximum of a and the supremum of s, if s is
nonempty and bounded above.-/
theorem cSup_insert (hs : bdd_above s) (sne : s.nonempty) : Sup (insert a s) = a β Sup s :=
((is_lub_cSup sne hs).insert a).cSup_eq (insert_nonempty a s)
/-- The infimum of insert a s is the minimum of a and the infimum of s, if s is
nonempty and bounded below.-/
theorem cInf_insert (hs : bdd_below s) (sne : s.nonempty) : Inf (insert a s) = a β Inf s :=
@cSup_insert (order_dual Ξ±) _ _ _ hs sne
@[simp] lemma cInf_Icc (h : a β€ b) : Inf (Icc a b) = a :=
(is_glb_Icc h).cInf_eq (nonempty_Icc.2 h)
@[simp] lemma cInf_Ici : Inf (Ici a) = a := is_least_Ici.cInf_eq
@[simp] lemma cInf_Ico (h : a < b) : Inf (Ico a b) = a :=
(is_glb_Ico h).cInf_eq (nonempty_Ico.2 h)
@[simp] lemma cInf_Ioc [densely_ordered Ξ±] (h : a < b) : Inf (Ioc a b) = a :=
(is_glb_Ioc h).cInf_eq (nonempty_Ioc.2 h)
@[simp] lemma cInf_Ioi [no_top_order Ξ±] [densely_ordered Ξ±] : Inf (Ioi a) = a :=
cInf_eq_of_forall_ge_of_forall_gt_exists_lt nonempty_Ioi (Ξ» _, le_of_lt)
(Ξ» w hw, by simpa using exists_between hw)
@[simp] lemma cInf_Ioo [densely_ordered Ξ±] (h : a < b) : Inf (Ioo a b) = a :=
(is_glb_Ioo h).cInf_eq (nonempty_Ioo.2 h)
@[simp] lemma cSup_Icc (h : a β€ b) : Sup (Icc a b) = b :=
(is_lub_Icc h).cSup_eq (nonempty_Icc.2 h)
@[simp] lemma cSup_Ico [densely_ordered Ξ±] (h : a < b) : Sup (Ico a b) = b :=
(is_lub_Ico h).cSup_eq (nonempty_Ico.2 h)
@[simp] lemma cSup_Iic : Sup (Iic a) = a := is_greatest_Iic.cSup_eq
@[simp] lemma cSup_Iio [no_bot_order Ξ±] [densely_ordered Ξ±] : Sup (Iio a) = a :=
cSup_eq_of_forall_le_of_forall_lt_exists_gt nonempty_Iio (Ξ» _, le_of_lt)
(Ξ» w hw, by simpa [and_comm] using exists_between hw)
@[simp] lemma cSup_Ioc (h : a < b) : Sup (Ioc a b) = b :=
(is_lub_Ioc h).cSup_eq (nonempty_Ioc.2 h)
@[simp] lemma cSup_Ioo [densely_ordered Ξ±] (h : a < b) : Sup (Ioo a b) = b :=
(is_lub_Ioo h).cSup_eq (nonempty_Ioo.2 h)
/--The indexed supremum of two functions are comparable if the functions are pointwise comparable-/
lemma csupr_le_csupr {f g : ΞΉ β Ξ±} (B : bdd_above (range g)) (H : βx, f x β€ g x) :
supr f β€ supr g :=
begin
classical, by_cases hΞΉ : nonempty ΞΉ,
{ have Rf : (range f).nonempty, { exactI range_nonempty _ },
apply cSup_le Rf,
rintros y β¨x, rflβ©,
have : g x β range g := β¨x, rflβ©,
exact le_cSup_of_le B this (H x) },
{ have Rf : range f = β
, from range_eq_empty.2 hΞΉ,
have Rg : range g = β
, from range_eq_empty.2 hΞΉ,
unfold supr, rw [Rf, Rg] }
end
/--The indexed supremum of a function is bounded above by a uniform bound-/
lemma csupr_le [nonempty ΞΉ] {f : ΞΉ β Ξ±} {c : Ξ±} (H : βx, f x β€ c) : supr f β€ c :=
cSup_le (range_nonempty f) (by rwa forall_range_iff)
/--The indexed supremum of a function is bounded below by the value taken at one point-/
lemma le_csupr {f : ΞΉ β Ξ±} (H : bdd_above (range f)) (c : ΞΉ) : f c β€ supr f :=
le_cSup H (mem_range_self _)
lemma le_csupr_of_le {f : ΞΉ β Ξ±} (H : bdd_above (range f)) (c : ΞΉ) (h : a β€ f c) : a β€ supr f :=
le_trans h (le_csupr H c)
/--The indexed infimum of two functions are comparable if the functions are pointwise comparable-/
lemma cinfi_le_cinfi {f g : ΞΉ β Ξ±} (B : bdd_below (range f)) (H : βx, f x β€ g x) :
infi f β€ infi g :=
@csupr_le_csupr (order_dual Ξ±) _ _ _ _ B H
/--The indexed minimum of a function is bounded below by a uniform lower bound-/
lemma le_cinfi [nonempty ΞΉ] {f : ΞΉ β Ξ±} {c : Ξ±} (H : βx, c β€ f x) : c β€ infi f :=
@csupr_le (order_dual Ξ±) _ _ _ _ _ H
/--The indexed infimum of a function is bounded above by the value taken at one point-/
lemma cinfi_le {f : ΞΉ β Ξ±} (H : bdd_below (range f)) (c : ΞΉ) : infi f β€ f c :=
@le_csupr (order_dual Ξ±) _ _ _ H c
lemma cinfi_le_of_le {f : ΞΉ β Ξ±} (H : bdd_below (range f)) (c : ΞΉ) (h : f c β€ a) : infi f β€ a :=
@le_csupr_of_le (order_dual Ξ±) _ _ _ _ H c h
@[simp] theorem csupr_const [hΞΉ : nonempty ΞΉ] {a : Ξ±} : (β¨ b:ΞΉ, a) = a :=
by rw [supr, range_const, cSup_singleton]
@[simp] theorem cinfi_const [hΞΉ : nonempty ΞΉ] {a : Ξ±} : (β¨
b:ΞΉ, a) = a :=
@csupr_const (order_dual Ξ±) _ _ _ _
theorem supr_unique [unique ΞΉ] {s : ΞΉ β Ξ±} : (β¨ i, s i) = s (default ΞΉ) :=
have β i, s i = s (default ΞΉ) := Ξ» i, congr_arg s (unique.eq_default i),
by simp only [this, csupr_const]
theorem infi_unique [unique ΞΉ] {s : ΞΉ β Ξ±} : (β¨
i, s i) = s (default ΞΉ) :=
@supr_unique (order_dual Ξ±) _ _ _ _
@[simp] theorem supr_unit {f : unit β Ξ±} : (β¨ x, f x) = f () :=
by { convert supr_unique, apply_instance }
@[simp] theorem infi_unit {f : unit β Ξ±} : (β¨
x, f x) = f () :=
@supr_unit (order_dual Ξ±) _ _
@[simp] lemma csupr_pos {p : Prop} {f : p β Ξ±} (hp : p) : (β¨ h : p, f h) = f hp :=
by haveI := unique_prop hp; exact supr_unique
@[simp] lemma cinfi_pos {p : Prop} {f : p β Ξ±} (hp : p) : (β¨
h : p, f h) = f hp :=
@csupr_pos (order_dual Ξ±) _ _ _ hp
/--Introduction rule to prove that `b` is the supremum of `f`: it suffices to check that `b`
is larger than `f i` for all `i`, and that this is not the case of any `w<b`.
See `supr_eq_of_forall_le_of_forall_lt_exists_gt` for a version in complete lattices. -/
theorem csupr_eq_of_forall_le_of_forall_lt_exists_gt [nonempty ΞΉ] {f : ΞΉ β Ξ±} (hβ : β i, f i β€ b)
(hβ : β w, w < b β (β i, w < f i)) : (β¨ (i : ΞΉ), f i) = b :=
cSup_eq_of_forall_le_of_forall_lt_exists_gt (range_nonempty f) (forall_range_iff.mpr hβ)
(Ξ» w hw, exists_range_iff.mpr $ hβ w hw)
/--Introduction rule to prove that `b` is the infimum of `f`: it suffices to check that `b`
is smaller than `f i` for all `i`, and that this is not the case of any `w>b`.
See `infi_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in complete lattices. -/
theorem cinfi_eq_of_forall_ge_of_forall_gt_exists_lt [nonempty ΞΉ] {f : ΞΉ β Ξ±} (hβ : β i, b β€ f i)
(hβ : β w, b < w β (β i, f i < w)) : (β¨
(i : ΞΉ), f i) = b :=
@csupr_eq_of_forall_le_of_forall_lt_exists_gt (order_dual Ξ±) _ _ _ _ βΉ_βΊ βΉ_βΊ βΉ_βΊ
/-- Nested intervals lemma: if `f` is a monotonically increasing sequence, `g` is a monotonically
decreasing sequence, and `f n β€ g n` for all `n`, then `β¨ n, f n` belongs to all the intervals
`[f n, g n]`. -/
lemma csupr_mem_Inter_Icc_of_mono_incr_of_mono_decr [nonempty Ξ²] [semilattice_sup Ξ²]
{f g : Ξ² β Ξ±} (hf : monotone f) (hg : β β¦m nβ¦, m β€ n β g n β€ g m) (h : β n, f n β€ g n) :
(β¨ n, f n) β β n, Icc (f n) (g n) :=
begin
inhabit Ξ²,
refine mem_Inter.2 (Ξ» n, β¨le_csupr β¨g $ default Ξ², forall_range_iff.2 $ Ξ» m, _β© _,
csupr_le $ Ξ» m, _β©); exact forall_le_of_monotone_of_mono_decr hf hg h _ _
end
/-- Nested intervals lemma: if `[f n, g n]` is a monotonically decreasing sequence of nonempty
closed intervals, then `β¨ n, f n` belongs to all the intervals `[f n, g n]`. -/
lemma csupr_mem_Inter_Icc_of_mono_decr_Icc [nonempty Ξ²] [semilattice_sup Ξ²]
{f g : Ξ² β Ξ±} (h : β β¦m nβ¦, m β€ n β Icc (f n) (g n) β Icc (f m) (g m)) (h' : β n, f n β€ g n) :
(β¨ n, f n) β β n, Icc (f n) (g n) :=
csupr_mem_Inter_Icc_of_mono_incr_of_mono_decr (Ξ» m n hmn, ((Icc_subset_Icc_iff (h' n)).1 (h hmn)).1)
(Ξ» m n hmn, ((Icc_subset_Icc_iff (h' n)).1 (h hmn)).2) h'
/-- Nested intervals lemma: if `[f n, g n]` is a monotonically decreasing sequence of nonempty
closed intervals, then `β¨ n, f n` belongs to all the intervals `[f n, g n]`. -/
lemma csupr_mem_Inter_Icc_of_mono_decr_Icc_nat
{f g : β β Ξ±} (h : β n, Icc (f (n + 1)) (g (n + 1)) β Icc (f n) (g n)) (h' : β n, f n β€ g n) :
(β¨ n, f n) β β n, Icc (f n) (g n) :=
csupr_mem_Inter_Icc_of_mono_decr_Icc
(@monotone_nat_of_le_succ (order_dual $ set Ξ±) _ (Ξ» n, Icc (f n) (g n)) h) h'
end conditionally_complete_lattice
instance pi.conditionally_complete_lattice {ΞΉ : Type*} {Ξ± : Ξ i : ΞΉ, Type*}
[Ξ i, conditionally_complete_lattice (Ξ± i)] :
conditionally_complete_lattice (Ξ i, Ξ± i) :=
{ le_cSup := Ξ» s f β¨g, hgβ© hf i, le_cSup β¨g i, set.forall_range_iff.2 $ Ξ» β¨f', hf'β©, hg hf' iβ©
β¨β¨f, hfβ©, rflβ©,
cSup_le := Ξ» s f hs hf i, cSup_le (by haveI := hs.to_subtype; apply range_nonempty) $
Ξ» b β¨β¨g, hgβ©, hbβ©, hb βΈ hf hg i,
cInf_le := Ξ» s f β¨g, hgβ© hf i, cInf_le β¨g i, set.forall_range_iff.2 $ Ξ» β¨f', hf'β©, hg hf' iβ©
β¨β¨f, hfβ©, rflβ©,
le_cInf := Ξ» s f hs hf i, le_cInf (by haveI := hs.to_subtype; apply range_nonempty) $
Ξ» b β¨β¨g, hgβ©, hbβ©, hb βΈ hf hg i,
.. pi.lattice, .. pi.has_Sup, .. pi.has_Inf }
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order Ξ±] {s t : set Ξ±} {a b : Ξ±}
lemma set.nonempty.cSup_mem (h : s.nonempty) (hs : finite s) : Sup s β s :=
begin
classical,
revert h,
apply finite.induction_on hs,
{ simp },
rintros a t hat t_fin ih -,
rcases t.eq_empty_or_nonempty with rfl | ht,
{ simp },
{ rw cSup_insert t_fin.bdd_above ht,
by_cases ha : a β€ Sup t,
{ simp [sup_eq_right.mpr ha, ih ht] },
{ simp only [sup_eq_left, mem_insert_iff, (not_le.mp ha).le, true_or] } }
end
lemma finset.nonempty.cSup_mem {s : finset Ξ±} (h : s.nonempty) : Sup (s : set Ξ±) β s :=
set.nonempty.cSup_mem h s.finite_to_set
lemma set.nonempty.cInf_mem (h : s.nonempty) (hs : finite s) : Inf s β s :=
@set.nonempty.cSup_mem (order_dual Ξ±) _ _ h hs
lemma finset.nonempty.cInf_mem {s : finset Ξ±} (h : s.nonempty) : Inf (s : set Ξ±) β s :=
set.nonempty.cInf_mem h s.finite_to_set
/-- When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is
a linear order. -/
lemma exists_lt_of_lt_cSup (hs : s.nonempty) (hb : b < Sup s) : βaβs, b < a :=
begin
classical, contrapose! hb,
exact cSup_le hs hb
end
/--
Indexed version of the above lemma `exists_lt_of_lt_cSup`.
When `b < supr f`, there is an element `i` such that `b < f i`.
-/
lemma exists_lt_of_lt_csupr [nonempty ΞΉ] {f : ΞΉ β Ξ±} (h : b < supr f) :
βi, b < f i :=
let β¨_, β¨i, rflβ©, hβ© := exists_lt_of_lt_cSup (range_nonempty f) h in β¨i, hβ©
/--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is
a linear order.-/
lemma exists_lt_of_cInf_lt (hs : s.nonempty) (hb : Inf s < b) : βaβs, a < b :=
@exists_lt_of_lt_cSup (order_dual Ξ±) _ _ _ hs hb
/--
Indexed version of the above lemma `exists_lt_of_cInf_lt`
When `infi f < a`, there is an element `i` such that `f i < a`.
-/
lemma exists_lt_of_cinfi_lt [nonempty ΞΉ] {f : ΞΉ β Ξ±} (h : infi f < a) :
(βi, f i < a) :=
@exists_lt_of_lt_csupr (order_dual Ξ±) _ _ _ _ _ h
/--Introduction rule to prove that b is the supremum of s: it suffices to check that
1) b is an upper bound
2) every other upper bound b' satisfies b β€ b'.-/
theorem cSup_eq_of_is_forall_le_of_forall_le_imp_ge (_ : s.nonempty)
(h_is_ub : β a β s, a β€ b) (h_b_le_ub : βub, (β a β s, a β€ ub) β (b β€ ub)) : Sup s = b :=
le_antisymm
(show Sup s β€ b, from cSup_le βΉs.nonemptyβΊ h_is_ub)
(show b β€ Sup s, from h_b_le_ub _ $ assume a, le_cSup β¨b, h_is_ubβ©)
end conditionally_complete_linear_order
section conditionally_complete_linear_order_bot
variables [conditionally_complete_linear_order_bot Ξ±]
lemma cSup_empty : (Sup β
: Ξ±) = β₯ :=
conditionally_complete_linear_order_bot.cSup_empty
@[simp] lemma csupr_neg {p : Prop} {f : p β Ξ±} (hp : Β¬ p) : (β¨ h : p, f h) = β₯ :=
begin
have : Β¬nonempty p := by simp [hp],
rw [supr, range_eq_empty.mpr this, cSup_empty],
end
end conditionally_complete_linear_order_bot
namespace nat
open_locale classical
noncomputable instance : has_Inf β :=
β¨Ξ»s, if h : βn, n β s then @nat.find (Ξ»n, n β s) _ h else 0β©
noncomputable instance : has_Sup β :=
β¨Ξ»s, if h : βn, βaβs, a β€ n then @nat.find (Ξ»n, βaβs, a β€ n) _ h else 0β©
lemma Inf_def {s : set β} (h : s.nonempty) : Inf s = @nat.find (Ξ»n, n β s) _ h :=
dif_pos _
lemma Sup_def {s : set β} (h : βn, βaβs, a β€ n) :
Sup s = @nat.find (Ξ»n, βaβs, a β€ n) _ h :=
dif_pos _
@[simp] lemma Inf_eq_zero {s : set β} : Inf s = 0 β 0 β s β¨ s = β
:=
begin
cases eq_empty_or_nonempty s,
{ subst h, simp only [or_true, eq_self_iff_true, iff_true, Inf, has_Inf.Inf,
mem_empty_eq, exists_false, dif_neg, not_false_iff] },
{ have := ne_empty_iff_nonempty.mpr h,
simp only [this, or_false, nat.Inf_def, h, nat.find_eq_zero] }
end
lemma Inf_mem {s : set β} (h : s.nonempty) : Inf s β s :=
by { rw [nat.Inf_def h], exact nat.find_spec h }
lemma not_mem_of_lt_Inf {s : set β} {m : β} (hm : m < Inf s) : m β s :=
begin
cases eq_empty_or_nonempty s,
{ subst h, apply not_mem_empty },
{ rw [nat.Inf_def h] at hm, exact nat.find_min h hm }
end
protected lemma Inf_le {s : set β} {m : β} (hm : m β s) : Inf s β€ m :=
by { rw [nat.Inf_def β¨m, hmβ©], exact nat.find_min' β¨m, hmβ© hm }
lemma nonempty_of_pos_Inf {s : set β} (h : 0 < Inf s) : s.nonempty :=
begin
by_contradiction contra, rw set.not_nonempty_iff_eq_empty at contra,
have h' : Inf s β 0, { exact ne_of_gt h, }, apply h',
rw nat.Inf_eq_zero, right, assumption,
end
lemma nonempty_of_Inf_eq_succ {s : set β} {k : β} (h : Inf s = k + 1) : s.nonempty :=
nonempty_of_pos_Inf (h.symm βΈ (succ_pos k) : Inf s > 0)
lemma eq_Ici_of_nonempty_of_upward_closed {s : set β} (hs : s.nonempty)
(hs' : β (kβ kβ : β), kβ β€ kβ β kβ β s β kβ β s) : s = Ici (Inf s) :=
ext (Ξ» n, β¨Ξ» H, nat.Inf_le H, Ξ» H, hs' (Inf s) n H (Inf_mem hs)β©)
lemma Inf_upward_closed_eq_succ_iff {s : set β}
(hs : β (kβ kβ : β), kβ β€ kβ β kβ β s β kβ β s) (k : β) :
Inf s = k + 1 β k + 1 β s β§ k β s :=
begin
split,
{ intro H,
rw [eq_Ici_of_nonempty_of_upward_closed (nonempty_of_Inf_eq_succ H) hs, H, mem_Ici, mem_Ici],
exact β¨le_refl _, k.not_succ_le_selfβ©, },
{ rintro β¨H, H'β©,
rw [Inf_def (β¨_, Hβ© : s.nonempty), find_eq_iff],
exact β¨H, Ξ» n hnk hns, H' $ hs n k (lt_succ_iff.mp hnk) hnsβ©, },
end
/-- This instance is necessary, otherwise the lattice operations would be derived via
conditionally_complete_linear_order_bot and marked as noncomputable. -/
instance : lattice β := lattice_of_linear_order
noncomputable instance : conditionally_complete_linear_order_bot β :=
{ Sup := Sup, Inf := Inf,
le_cSup := assume s a hb ha, by rw [Sup_def hb]; revert a ha; exact @nat.find_spec _ _ hb,
cSup_le := assume s a hs ha, by rw [Sup_def β¨a, haβ©]; exact nat.find_min' _ ha,
le_cInf := assume s a hs hb,
by rw [Inf_def hs]; exact hb (@nat.find_spec (Ξ»n, n β s) _ _),
cInf_le := assume s a hb ha, by rw [Inf_def β¨a, haβ©]; exact nat.find_min' _ ha,
cSup_empty :=
begin
simp only [Sup_def, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff,
exists_const],
apply bot_unique (nat.find_min' _ _),
trivial
end,
.. (infer_instance : order_bot β), .. (lattice_of_linear_order : lattice β),
.. (infer_instance : linear_order β) }
end nat
namespace with_top
open_locale classical
variables [conditionally_complete_linear_order_bot Ξ±]
/-- The Sup of a non-empty set is its least upper bound for a conditionally
complete lattice with a top. -/
lemma is_lub_Sup' {Ξ² : Type*} [conditionally_complete_lattice Ξ²]
{s : set (with_top Ξ²)} (hs : s.nonempty) : is_lub s (Sup s) :=
begin
split,
{ show ite _ _ _ β _,
split_ifs,
{ intros _ _, exact le_top },
{ rintro (β¨β©|a) ha,
{ contradiction },
apply some_le_some.2,
exact le_cSup h_1 ha },
{ intros _ _, exact le_top } },
{ show ite _ _ _ β _,
split_ifs,
{ rintro (β¨β©|a) ha,
{ exact _root_.le_refl _ },
{ exact false.elim (not_top_le_coe a (ha h)) } },
{ rintro (β¨β©|b) hb,
{ exact le_top },
refine some_le_some.2 (cSup_le _ _),
{ rcases hs with β¨β¨β©|b, hbβ©,
{ exact absurd hb h },
{ exact β¨b, hbβ© } },
{ intros a ha, exact some_le_some.1 (hb ha) } },
{ rintro (β¨β©|b) hb,
{ exact _root_.le_refl _ },
{ exfalso, apply h_1, use b, intros a ha, exact some_le_some.1 (hb ha) } } }
end
lemma is_lub_Sup (s : set (with_top Ξ±)) : is_lub s (Sup s) :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ rw hs,
show is_lub β
(ite _ _ _),
split_ifs,
{ cases h },
{ rw [preimage_empty, cSup_empty], exact is_lub_empty },
{ exfalso, apply h_1, use β₯, rintro a β¨β© } },
exact is_lub_Sup' hs,
end
/-- The Inf of a bounded-below set is its greatest lower bound for a conditionally
complete lattice with a top. -/
lemma is_glb_Inf' {Ξ² : Type*} [conditionally_complete_lattice Ξ²]
{s : set (with_top Ξ²)} (hs : bdd_below s) : is_glb s (Inf s) :=
begin
split,
{ show ite _ _ _ β _,
split_ifs,
{ intros a ha, exact top_le_iff.2 (set.mem_singleton_iff.1 (h ha)) },
{ rintro (β¨β©|a) ha,
{ exact le_top },
refine some_le_some.2 (cInf_le _ ha),
rcases hs with β¨β¨β©|b, hbβ©,
{ exfalso,
apply h,
intros c hc,
rw [mem_singleton_iff, βtop_le_iff],
exact hb hc },
use b,
intros c hc,
exact some_le_some.1 (hb hc) } },
{ show ite _ _ _ β _,
split_ifs,
{ intros _ _, exact le_top },
{ rintro (β¨β©|a) ha,
{ exfalso, apply h, intros b hb, exact set.mem_singleton_iff.2 (top_le_iff.1 (ha hb)) },
{ refine some_le_some.2 (le_cInf _ _),
{ classical, contrapose! h,
rintros (β¨β©|a) ha,
{ exact mem_singleton β€ },
{ exact (h β¨a, haβ©).elim }},
{ intros b hb,
rw βsome_le_some,
exact ha hb } } } }
end
lemma is_glb_Inf (s : set (with_top Ξ±)) : is_glb s (Inf s) :=
begin
by_cases hs : bdd_below s,
{ exact is_glb_Inf' hs },
{ exfalso, apply hs, use β₯, intros _ _, exact bot_le },
end
noncomputable instance : complete_linear_order (with_top Ξ±) :=
{ Sup := Sup, le_Sup := assume s, (is_lub_Sup s).1, Sup_le := assume s, (is_lub_Sup s).2,
Inf := Inf, le_Inf := assume s, (is_glb_Inf s).2, Inf_le := assume s, (is_glb_Inf s).1,
decidable_le := classical.dec_rel _,
.. with_top.linear_order, ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot }
lemma coe_Sup {s : set Ξ±} (hb : bdd_above s) : (β(Sup s) : with_top Ξ±) = (β¨aβs, βa) :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ rw [hs, cSup_empty], simp only [set.mem_empty_eq, supr_bot, supr_false], refl },
apply le_antisymm,
{ refine (coe_le_iff.2 $ assume b hb, cSup_le hs $ assume a has, coe_le_coe.1 $ hb βΈ _),
exact (le_supr_of_le a $ le_supr_of_le has $ _root_.le_refl _) },
{ exact (supr_le $ assume a, supr_le $ assume ha, coe_le_coe.2 $ le_cSup hb ha) }
end
lemma coe_Inf {s : set Ξ±} (hs : s.nonempty) : (β(Inf s) : with_top Ξ±) = (β¨
aβs, βa) :=
let β¨x, hxβ© := hs in
have (β¨
aβs, βa : with_top Ξ±) β€ x, from infi_le_of_le x $ infi_le_of_le hx $ _root_.le_refl _,
let β¨r, r_eq, hrβ© := le_coe_iff.1 this in
le_antisymm
(le_infi $ assume a, le_infi $ assume ha, coe_le_coe.2 $ cInf_le (order_bot.bdd_below s) ha)
begin
refine (r_eq.symm βΈ coe_le_coe.2 $ le_cInf hs $ assume a has, coe_le_coe.1 $ _),
refine (r_eq βΈ infi_le_of_le a _),
exact (infi_le_of_le has $ _root_.le_refl _),
end
end with_top
namespace enat
open_locale classical
noncomputable instance : complete_linear_order enat :=
{ Sup := Ξ» s, with_top_equiv.symm $ Sup (with_top_equiv '' s),
Inf := Ξ» s, with_top_equiv.symm $ Inf (with_top_equiv '' s),
le_Sup := by intros; rw β with_top_equiv_le; simp; apply le_Sup _; simpa,
Inf_le := by intros; rw β with_top_equiv_le; simp; apply Inf_le _; simpa,
Sup_le := begin
intros s a h1,
rw [β with_top_equiv_le, with_top_equiv.right_inverse_symm],
apply Sup_le _,
rintros b β¨x, h2, rflβ©,
rw with_top_equiv_le,
apply h1,
assumption
end,
le_Inf := begin
intros s a h1,
rw [β with_top_equiv_le, with_top_equiv.right_inverse_symm],
apply le_Inf _,
rintros b β¨x, h2, rflβ©,
rw with_top_equiv_le,
apply h1,
assumption
end,
..enat.linear_order,
..enat.bounded_lattice }
end enat
namespace monotone
variables [preorder Ξ±] [conditionally_complete_lattice Ξ²] {f : Ξ± β Ξ²} (h_mono : monotone f)
/-! A monotone function into a conditionally complete lattice preserves the ordering properties of
`Sup` and `Inf`. -/
lemma le_cSup_image {s : set Ξ±} {c : Ξ±} (hcs : c β s) (h_bdd : bdd_above s) :
f c β€ Sup (f '' s) :=
le_cSup (map_bdd_above h_mono h_bdd) (mem_image_of_mem f hcs)
lemma cSup_image_le {s : set Ξ±} (hs : s.nonempty) {B : Ξ±} (hB: B β upper_bounds s) :
Sup (f '' s) β€ f B :=
cSup_le (nonempty.image f hs) (h_mono.mem_upper_bounds_image hB)
lemma cInf_image_le {s : set Ξ±} {c : Ξ±} (hcs : c β s) (h_bdd : bdd_below s) :
Inf (f '' s) β€ f c :=
@le_cSup_image (order_dual Ξ±) (order_dual Ξ²) _ _ _ (Ξ» x y hxy, h_mono hxy) _ _ hcs h_bdd
lemma le_cInf_image {s : set Ξ±} (hs : s.nonempty) {B : Ξ±} (hB: B β lower_bounds s) :
f B β€ Inf (f '' s) :=
@cSup_image_le (order_dual Ξ±) (order_dual Ξ²) _ _ _ (Ξ» x y hxy, h_mono hxy) _ hs _ hB
end monotone
namespace galois_connection
variables {Ξ³ : Type*} [conditionally_complete_lattice Ξ±] [conditionally_complete_lattice Ξ²]
[nonempty ΞΉ] {l : Ξ± β Ξ²} {u : Ξ² β Ξ±}
lemma l_cSup (gc : galois_connection l u) {s : set Ξ±} (hne : s.nonempty)
(hbdd : bdd_above s) :
l (Sup s) = β¨ x : s, l x :=
eq.symm $ is_lub.csupr_set_eq (gc.is_lub_l_image $ is_lub_cSup hne hbdd) hne
lemma l_csupr (gc : galois_connection l u) {f : ΞΉ β Ξ±}
(hf : bdd_above (range f)) :
l (β¨ i, f i) = β¨ i, l (f i) :=
by rw [supr, gc.l_cSup (range_nonempty _) hf, supr_range']
lemma l_csupr_set (gc : galois_connection l u) {s : set Ξ³} {f : Ξ³ β Ξ±}
(hf : bdd_above (f '' s)) (hne : s.nonempty) :
l (β¨ i : s, f i) = β¨ i : s, l (f i) :=
by { haveI := hne.to_subtype, rw image_eq_range at hf, exact gc.l_csupr hf }
lemma u_cInf (gc : galois_connection l u) {s : set Ξ²} (hne : s.nonempty)
(hbdd : bdd_below s) :
u (Inf s) = β¨
x : s, u x :=
gc.dual.l_cSup hne hbdd
lemma u_cinfi (gc : galois_connection l u) {f : ΞΉ β Ξ²}
(hf : bdd_below (range f)) :
u (β¨
i, f i) = β¨
i, u (f i) :=
gc.dual.l_csupr hf
lemma u_cinfi_set (gc : galois_connection l u) {s : set Ξ³} {f : Ξ³ β Ξ²}
(hf : bdd_below (f '' s)) (hne : s.nonempty) :
u (β¨
i : s, f i) = β¨
i : s, u (f i) :=
gc.dual.l_csupr_set hf hne
end galois_connection
namespace order_iso
variables {Ξ³ : Type*} [conditionally_complete_lattice Ξ±] [conditionally_complete_lattice Ξ²]
[nonempty ΞΉ]
lemma map_cSup (e : Ξ± βo Ξ²) {s : set Ξ±} (hne : s.nonempty) (hbdd : bdd_above s) :
e (Sup s) = β¨ x : s, e x :=
e.to_galois_connection.l_cSup hne hbdd
lemma map_csupr (e : Ξ± βo Ξ²) {f : ΞΉ β Ξ±} (hf : bdd_above (range f)) :
e (β¨ i, f i) = β¨ i, e (f i) :=
e.to_galois_connection.l_csupr hf
lemma map_csupr_set (e : Ξ± βo Ξ²) {s : set Ξ³} {f : Ξ³ β Ξ±}
(hf : bdd_above (f '' s)) (hne : s.nonempty) :
e (β¨ i : s, f i) = β¨ i : s, e (f i) :=
e.to_galois_connection.l_csupr_set hf hne
lemma map_cInf (e : Ξ± βo Ξ²) {s : set Ξ±} (hne : s.nonempty) (hbdd : bdd_below s) :
e (Inf s) = β¨
x : s, e x :=
e.dual.map_cSup hne hbdd
lemma map_cinfi (e : Ξ± βo Ξ²) {f : ΞΉ β Ξ±} (hf : bdd_below (range f)) :
e (β¨
i, f i) = β¨
i, e (f i) :=
e.dual.map_csupr hf
lemma map_cinfi_set (e : Ξ± βo Ξ²) {s : set Ξ³} {f : Ξ³ β Ξ±}
(hf : bdd_below (f '' s)) (hne : s.nonempty) :
e (β¨
i : s, f i) = β¨
i : s, e (f i) :=
e.dual.map_csupr_set hf hne
end order_iso
/-!
### Relation between `Sup` / `Inf` and `finset.sup'` / `finset.inf'`
Like the `Sup` of a `conditionally_complete_lattice`, `finset.sup'` also requires the set to be
non-empty. As a result, we can translate between the two.
-/
namespace finset
lemma sup'_eq_cSup_image [conditionally_complete_lattice Ξ²] (s : finset Ξ±) (H) (f : Ξ± β Ξ²) :
s.sup' H f = Sup (f '' s) :=
begin
apply le_antisymm,
{ refine (finset.sup'_le _ _ $ Ξ» a ha, _),
refine le_cSup β¨s.sup' H f, _β© β¨a, ha, rflβ©,
rintros i β¨j, hj, rflβ©,
exact finset.le_sup' _ hj },
{ apply cSup_le ((coe_nonempty.mpr H).image _),
rintros _ β¨a, ha, rflβ©,
exact finset.le_sup' _ ha, }
end
lemma inf'_eq_cInf_image [conditionally_complete_lattice Ξ²] (s : finset Ξ±) (H) (f : Ξ± β Ξ²) :
s.inf' H f = Inf (f '' s) :=
@sup'_eq_cSup_image _ (order_dual Ξ²) _ _ _ _
lemma sup'_id_eq_cSup [conditionally_complete_lattice Ξ±] (s : finset Ξ±) (H) :
s.sup' H id = Sup s :=
by rw [sup'_eq_cSup_image s H, set.image_id]
lemma inf'_id_eq_cInf [conditionally_complete_lattice Ξ±] (s : finset Ξ±) (H) :
s.inf' H id = Inf s :=
@sup'_id_eq_cSup (order_dual Ξ±) _ _ _
end finset
section with_top_bot
/-!
### Complete lattice structure on `with_top (with_bot Ξ±)`
If `Ξ±` is a `conditionally_complete_lattice`, then we show that `with_top Ξ±` and `with_bot Ξ±`
also inherit the structure of conditionally complete lattices. Furthermore, we show
that `with_top (with_bot Ξ±)` naturally inherits the structure of a complete lattice. Note that
for Ξ± a conditionally complete lattice, `Sup` and `Inf` both return junk values
for sets which are empty or unbounded. The extension of `Sup` to `with_top Ξ±` fixes
the unboundedness problem and the extension to `with_bot Ξ±` fixes the problem with
the empty set.
This result can be used to show that the extended reals [-β, β] are a complete lattice.
-/
open_locale classical
/-- Adding a top element to a conditionally complete lattice
gives a conditionally complete lattice -/
noncomputable instance with_top.conditionally_complete_lattice
{Ξ± : Type*} [conditionally_complete_lattice Ξ±] :
conditionally_complete_lattice (with_top Ξ±) :=
{ le_cSup := Ξ» S a hS haS, (with_top.is_lub_Sup' β¨a, haSβ©).1 haS,
cSup_le := Ξ» S a hS haS, (with_top.is_lub_Sup' hS).2 haS,
cInf_le := Ξ» S a hS haS, (with_top.is_glb_Inf' hS).1 haS,
le_cInf := Ξ» S a hS haS, (with_top.is_glb_Inf' β¨a, haSβ©).2 haS,
..with_top.lattice,
..with_top.has_Sup,
..with_top.has_Inf }
/-- Adding a bottom element to a conditionally complete lattice
gives a conditionally complete lattice -/
noncomputable instance with_bot.conditionally_complete_lattice
{Ξ± : Type*} [conditionally_complete_lattice Ξ±] :
conditionally_complete_lattice (with_bot Ξ±) :=
{ le_cSup := (@with_top.conditionally_complete_lattice (order_dual Ξ±) _).cInf_le,
cSup_le := (@with_top.conditionally_complete_lattice (order_dual Ξ±) _).le_cInf,
cInf_le := (@with_top.conditionally_complete_lattice (order_dual Ξ±) _).le_cSup,
le_cInf := (@with_top.conditionally_complete_lattice (order_dual Ξ±) _).cSup_le,
..with_bot.lattice,
..with_bot.has_Sup,
..with_bot.has_Inf }
/-- Adding a bottom and a top to a conditionally complete lattice gives a bounded lattice-/
noncomputable instance with_top.with_bot.bounded_lattice {Ξ± : Type*}
[conditionally_complete_lattice Ξ±] : bounded_lattice (with_top (with_bot Ξ±)) :=
{ ..with_top.order_bot,
..with_top.order_top,
..conditionally_complete_lattice.to_lattice _ }
noncomputable instance with_top.with_bot.complete_lattice {Ξ± : Type*}
[conditionally_complete_lattice Ξ±] : complete_lattice (with_top (with_bot Ξ±)) :=
{ le_Sup := Ξ» S a haS, (with_top.is_lub_Sup' β¨a, haSβ©).1 haS,
Sup_le := Ξ» S a ha,
begin
cases S.eq_empty_or_nonempty with h,
{ show ite _ _ _ β€ a,
split_ifs,
{ rw h at h_1, cases h_1 },
{ convert bot_le, convert with_bot.cSup_empty, rw h, refl },
{ exfalso, apply h_2, use β₯, rw h, rintro b β¨β© } },
{ refine (with_top.is_lub_Sup' h).2 ha }
end,
Inf_le := Ξ» S a haS,
show ite _ _ _ β€ a,
begin
split_ifs,
{ cases a with a, exact _root_.le_refl _,
cases (h haS); tauto },
{ cases a,
{ exact le_top },
{ apply with_top.some_le_some.2, refine cInf_le _ haS, use β₯, intros b hb, exact bot_le } }
end,
le_Inf := Ξ» S a haS, (with_top.is_glb_Inf' β¨a, haSβ©).2 haS,
..with_top.has_Inf,
..with_top.has_Sup,
..with_top.with_bot.bounded_lattice }
noncomputable instance with_top.with_bot.complete_linear_order {Ξ± : Type*}
[conditionally_complete_linear_order Ξ±] : complete_linear_order (with_top (with_bot Ξ±)) :=
{ .. with_top.with_bot.complete_lattice,
.. with_top.linear_order }
end with_top_bot
section subtype
variables (s : set Ξ±)
/-! ### Subtypes of conditionally complete linear orders
In this section we give conditions on a subset of a conditionally complete linear order, to ensure
that the subtype is itself conditionally complete.
We check that an `ord_connected` set satisfies these conditions.
TODO There are several possible variants; the `conditionally_complete_linear_order` could be changed
to `conditionally_complete_linear_order_bot` or `complete_linear_order`.
-/
open_locale classical
section has_Sup
variables [has_Sup Ξ±]
/-- `has_Sup` structure on a nonempty subset `s` of an object with `has_Sup`. This definition is
non-canonical (it uses `default s`); it should be used only as here, as an auxiliary instance in the
construction of the `conditionally_complete_linear_order` structure. -/
noncomputable def subset_has_Sup [inhabited s] : has_Sup s := {Sup := Ξ» t,
if ht : Sup (coe '' t : set Ξ±) β s then β¨Sup (coe '' t : set Ξ±), htβ© else default s}
local attribute [instance] subset_has_Sup
@[simp] lemma subset_Sup_def [inhabited s] :
@Sup s _ = Ξ» t,
if ht : Sup (coe '' t : set Ξ±) β s then β¨Sup (coe '' t : set Ξ±), htβ© else default s :=
rfl
lemma subset_Sup_of_within [inhabited s] {t : set s} (h : Sup (coe '' t : set Ξ±) β s) :
Sup (coe '' t : set Ξ±) = (@Sup s _ t : Ξ±) :=
by simp [dif_pos h]
end has_Sup
section has_Inf
variables [has_Inf Ξ±]
/-- `has_Inf` structure on a nonempty subset `s` of an object with `has_Inf`. This definition is
non-canonical (it uses `default s`); it should be used only as here, as an auxiliary instance in the
construction of the `conditionally_complete_linear_order` structure. -/
noncomputable def subset_has_Inf [inhabited s] : has_Inf s := {Inf := Ξ» t,
if ht : Inf (coe '' t : set Ξ±) β s then β¨Inf (coe '' t : set Ξ±), htβ© else default s}
local attribute [instance] subset_has_Inf
@[simp] lemma subset_Inf_def [inhabited s] :
@Inf s _ = Ξ» t,
if ht : Inf (coe '' t : set Ξ±) β s then β¨Inf (coe '' t : set Ξ±), htβ© else default s :=
rfl
lemma subset_Inf_of_within [inhabited s] {t : set s} (h : Inf (coe '' t : set Ξ±) β s) :
Inf (coe '' t : set Ξ±) = (@Inf s _ t : Ξ±) :=
by simp [dif_pos h]
end has_Inf
variables [conditionally_complete_linear_order Ξ±]
local attribute [instance] subset_has_Sup
local attribute [instance] subset_has_Inf
/-- For a nonempty subset of a conditionally complete linear order to be a conditionally complete
linear order, it suffices that it contain the `Sup` of all its nonempty bounded-above subsets, and
the `Inf` of all its nonempty bounded-below subsets. -/
noncomputable def subset_conditionally_complete_linear_order [inhabited s]
(h_Sup : β {t : set s} (ht : t.nonempty) (h_bdd : bdd_above t), Sup (coe '' t : set Ξ±) β s)
(h_Inf : β {t : set s} (ht : t.nonempty) (h_bdd : bdd_below t), Inf (coe '' t : set Ξ±) β s) :
conditionally_complete_linear_order s :=
{ le_cSup := begin
rintros t c h_bdd hct,
-- The following would be a more natural way to finish, but gives a "deep recursion" error:
-- simpa [subset_Sup_of_within (h_Sup t)] using
-- (strict_mono_coe s).monotone.le_cSup_image hct h_bdd,
have := (subtype.mono_coe s).le_cSup_image hct h_bdd,
rwa subset_Sup_of_within s (h_Sup β¨c, hctβ© h_bdd) at this,
end,
cSup_le := begin
rintros t B ht hB,
have := (subtype.mono_coe s).cSup_image_le ht hB,
rwa subset_Sup_of_within s (h_Sup ht β¨B, hBβ©) at this,
end,
le_cInf := begin
intros t B ht hB,
have := (subtype.mono_coe s).le_cInf_image ht hB,
rwa subset_Inf_of_within s (h_Inf ht β¨B, hBβ©) at this,
end,
cInf_le := begin
rintros t c h_bdd hct,
have := (subtype.mono_coe s).cInf_image_le hct h_bdd,
rwa subset_Inf_of_within s (h_Inf β¨c, hctβ© h_bdd) at this,
end,
..subset_has_Sup s,
..subset_has_Inf s,
..distrib_lattice.to_lattice s,
..(infer_instance : linear_order s) }
section ord_connected
/-- The `Sup` function on a nonempty `ord_connected` set `s` in a conditionally complete linear
order takes values within `s`, for all nonempty bounded-above subsets of `s`. -/
lemma Sup_within_of_ord_connected
{s : set Ξ±} [hs : ord_connected s] β¦t : set sβ¦ (ht : t.nonempty) (h_bdd : bdd_above t) :
Sup (coe '' t : set Ξ±) β s :=
begin
obtain β¨c, hctβ© : β c, c β t := ht,
obtain β¨B, hBβ© : β B, B β upper_bounds t := h_bdd,
refine hs.out c.2 B.2 β¨_, _β©,
{ exact (subtype.mono_coe s).le_cSup_image hct β¨B, hBβ© },
{ exact (subtype.mono_coe s).cSup_image_le β¨c, hctβ© hB },
end
/-- The `Inf` function on a nonempty `ord_connected` set `s` in a conditionally complete linear
order takes values within `s`, for all nonempty bounded-below subsets of `s`. -/
lemma Inf_within_of_ord_connected
{s : set Ξ±} [hs : ord_connected s] β¦t : set sβ¦ (ht : t.nonempty) (h_bdd : bdd_below t) :
Inf (coe '' t : set Ξ±) β s :=
begin
obtain β¨c, hctβ© : β c, c β t := ht,
obtain β¨B, hBβ© : β B, B β lower_bounds t := h_bdd,
refine hs.out B.2 c.2 β¨_, _β©,
{ exact (subtype.mono_coe s).le_cInf_image β¨c, hctβ© hB },
{ exact (subtype.mono_coe s).cInf_image_le hct β¨B, hBβ© },
end
/-- A nonempty `ord_connected` set in a conditionally complete linear order is naturally a
conditionally complete linear order. -/
noncomputable instance ord_connected_subset_conditionally_complete_linear_order
[inhabited s] [ord_connected s] :
conditionally_complete_linear_order s :=
subset_conditionally_complete_linear_order s Sup_within_of_ord_connected Inf_within_of_ord_connected
end ord_connected
end subtype
|
1835f3ede0a49eaa8531bbb7d213ff4904691bf6 | 22e97a5d648fc451e25a06c668dc03ac7ed7bc25 | /src/data/pnat/factors.lean | 176e65dfc1cbd1bdb4340e697bfc8385031428f8 | [
"Apache-2.0"
] | permissive | keeferrowan/mathlib | f2818da875dbc7780830d09bd4c526b0764a4e50 | aad2dfc40e8e6a7e258287a7c1580318e865817e | refs/heads/master | 1,661,736,426,952 | 1,590,438,032,000 | 1,590,438,032,000 | 266,892,663 | 0 | 0 | Apache-2.0 | 1,590,445,835,000 | 1,590,445,835,000 | null | UTF-8 | Lean | false | false | 13,940 | lean | /-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Neil Strickland
-/
import data.pnat.basic
import data.multiset
import data.int.gcd
import algebra.group
/-- The type of multisets of prime numbers. Unique factorization
gives an equivalence between this set and β+, as we will formalize
below. -/
def prime_multiset := multiset nat.primes
namespace prime_multiset
instance : inhabited prime_multiset :=
by unfold prime_multiset; apply_instance
instance : has_repr prime_multiset :=
by { dsimp [prime_multiset], apply_instance }
instance : canonically_ordered_add_monoid prime_multiset :=
by { dsimp [prime_multiset], apply_instance }
instance : distrib_lattice prime_multiset :=
by { dsimp [prime_multiset], apply_instance }
instance : semilattice_sup_bot prime_multiset :=
by { dsimp [prime_multiset], apply_instance }
instance : has_sub prime_multiset :=
by { dsimp [prime_multiset], apply_instance }
theorem add_sub_of_le {u v : prime_multiset} : u β€ v β u + (v - u) = v :=
multiset.add_sub_of_le
/-- The multiset consisting of a single prime
-/
def of_prime (p : nat.primes) : prime_multiset := (p :: 0)
theorem card_of_prime (p : nat.primes) : multiset.card (of_prime p) = 1 := rfl
/-- We can forget the primality property and regard a multiset
of primes as just a multiset of positive integers, or a multiset
of natural numbers. In the opposite direction, if we have a
multiset of positive integers or natural numbers, together with
a proof that all the elements are prime, then we can regard it
as a multiset of primes. The next block of results records
obvious properties of these coercions.
-/
def to_nat_multiset : prime_multiset β multiset β :=
Ξ» v, v.map (Ξ» p, (p : β))
instance coe_nat : has_coe prime_multiset (multiset β) := β¨to_nat_multisetβ©
instance coe_nat_hom : is_add_monoid_hom (coe : prime_multiset β multiset β) :=
by { unfold_coes, dsimp [to_nat_multiset], apply_instance }
theorem coe_nat_inj : function.injective (coe : prime_multiset β multiset β) :=
multiset.injective_map nat.primes.coe_nat_inj
theorem coe_nat_of_prime (p : nat.primes) :
((of_prime p) : multiset β) = (p : β) :: 0 := rfl
theorem coe_nat_prime (v : prime_multiset)
(p : β) (h : p β (v : multiset β)) : p.prime :=
by { rcases multiset.mem_map.mp h with β¨β¨p', hp'β©, β¨h_mem, h_eqβ©β©,
exact h_eq βΈ hp' }
def to_pnat_multiset : prime_multiset β multiset β+ :=
Ξ» v, v.map (Ξ» p, (p : β+))
instance coe_pnat : has_coe prime_multiset (multiset β+) := β¨to_pnat_multisetβ©
instance coe_pnat_hom : is_add_monoid_hom (coe : prime_multiset β multiset β+) :=
by { unfold_coes, dsimp [to_pnat_multiset], apply_instance }
theorem coe_pnat_inj : function.injective (coe : prime_multiset β multiset β+) :=
multiset.injective_map nat.primes.coe_pnat_inj
theorem coe_pnat_of_prime (p : nat.primes) :
((of_prime p) : multiset β+) = (p : β+) :: 0 := rfl
theorem coe_pnat_prime (v : prime_multiset)
(p : β+) (h : p β (v : multiset β+)) : p.prime :=
by { rcases multiset.mem_map.mp h with β¨β¨p', hp'β©, β¨h_mem, h_eqβ©β©,
exact h_eq βΈ hp' }
instance coe_multiset_pnat_nat : has_coe (multiset β+) (multiset β) :=
β¨Ξ» v, v.map (Ξ» n, (n : β))β©
theorem coe_pnat_nat (v : prime_multiset) :
((v : (multiset β+)) : (multiset β)) = (v : multiset β) :=
by { change (v.map (coe : nat.primes β β+)).map subtype.val = v.map subtype.val,
rw [multiset.map_map], congr }
def prod (v : prime_multiset) : β+ := (v : multiset pnat).prod
theorem coe_prod (v : prime_multiset) : (v.prod : β) = (v : multiset β).prod :=
begin
let h : (v.prod : β) = ((v.map coe).map coe).prod :=
(v.to_pnat_multiset.prod_hom coe).symm,
rw [multiset.map_map] at h,
have : (coe : β+ β β) β (coe : nat.primes β β+) = coe := funext (Ξ» p, rfl),
rw[this] at h, exact h,
end
theorem prod_of_prime (p : nat.primes) : (of_prime p).prod = (p : β+) :=
by { change multiset.prod ((p : β+) :: 0) = (p : β+),
rw [multiset.prod_cons, multiset.prod_zero, mul_one] }
def of_nat_multiset
(v : multiset β) (h : β (p : β), p β v β p.prime) : prime_multiset :=
@multiset.pmap β nat.primes nat.prime (Ξ» p hp, β¨p, hpβ©) v h
theorem to_of_nat_multiset (v : multiset β) (h) :
((of_nat_multiset v h) : multiset β) = v :=
begin
unfold_coes,
dsimp [of_nat_multiset, to_nat_multiset],
have : (Ξ» (p : β) (h : p.prime), ((β¨p, hβ© : nat.primes) : β)) = (Ξ» p h, id p) :=
by {funext p h, refl},
rw [multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id]
end
theorem prod_of_nat_multiset (v : multiset β) (h) :
((of_nat_multiset v h).prod : β) = (v.prod : β) :=
by rw[coe_prod, to_of_nat_multiset]
def of_pnat_multiset
(v : multiset β+) (h : β (p : β+), p β v β p.prime) : prime_multiset :=
@multiset.pmap β+ nat.primes pnat.prime (Ξ» p hp, β¨(p : β), hpβ©) v h
theorem to_of_pnat_multiset (v : multiset β+) (h) :
((of_pnat_multiset v h) : multiset β+) = v :=
begin
unfold_coes, dsimp[of_pnat_multiset, to_pnat_multiset],
have : (Ξ» (p : β+) (h : p.prime), ((coe : nat.primes β β+) β¨p, hβ©)) = (Ξ» p h, id p) :=
by {funext p h, apply subtype.eq, refl},
rw[multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id]
end
theorem prod_of_pnat_multiset (v : multiset β+) (h) :
((of_pnat_multiset v h).prod : β+) = v.prod :=
by { dsimp [prod], rw [to_of_pnat_multiset] }
/-- Lists can be coerced to multisets; here we have some results
about how this interacts with our constructions on multisets.
-/
def of_nat_list (l : list β) (h : β (p : β), p β l β p.prime) : prime_multiset :=
of_nat_multiset (l : multiset β) h
theorem prod_of_nat_list (l : list β) (h) : ((of_nat_list l h).prod : β) = l.prod :=
by { have := prod_of_nat_multiset (l : multiset β) h,
rw [multiset.coe_prod] at this, exact this }
def of_pnat_list (l : list β+) (h : β (p : β+), p β l β p.prime) : prime_multiset :=
of_pnat_multiset (l : multiset β+) h
theorem prod_of_pnat_list (l : list β+) (h) : (of_pnat_list l h).prod = l.prod :=
by { have := prod_of_pnat_multiset (l : multiset β+) h,
rw [multiset.coe_prod] at this, exact this }
/-- The product map gives a homomorphism from the additive monoid
of multisets to the multiplicative monoid β+.
-/
theorem prod_zero : (0 : prime_multiset).prod = 1 :=
by { dsimp [prod], exact multiset.prod_zero }
theorem prod_add (u v : prime_multiset) : (u + v).prod = u.prod * v.prod :=
by { dsimp [prod],
rw [is_add_monoid_hom.map_add (coe : prime_multiset β multiset β+)],
rw [multiset.prod_add] }
theorem prod_smul (d : β) (u : prime_multiset) :
(add_monoid.smul d u).prod = u.prod ^ d :=
by { induction d with d ih, refl,
rw[succ_smul, prod_add, ih, nat.succ_eq_add_one, pow_succ, mul_comm] }
end prime_multiset
namespace pnat
/-- The prime factors of n, regarded as a multiset -/
def factor_multiset (n : β+) : prime_multiset :=
prime_multiset.of_nat_list (nat.factors n) (@nat.mem_factors n)
/-- The product of the factors is the original number -/
theorem prod_factor_multiset (n : β+) : (factor_multiset n).prod = n :=
eq $ by { dsimp [factor_multiset],
rw [prime_multiset.prod_of_nat_list],
exact nat.prod_factors n.pos }
theorem coe_nat_factor_multiset (n : β+) :
((factor_multiset n) : (multiset β)) = ((nat.factors n) : multiset β) :=
prime_multiset.to_of_nat_multiset (nat.factors n) (@nat.mem_factors n)
end pnat
namespace prime_multiset
/-- If we start with a multiset of primes, take the product and
then factor it, we get back the original multiset. -/
theorem factor_multiset_prod (v : prime_multiset) :
v.prod.factor_multiset = v :=
begin
apply prime_multiset.coe_nat_inj,
rw [v.prod.coe_nat_factor_multiset, prime_multiset.coe_prod],
rcases v with l,
unfold_coes,
dsimp [prime_multiset.to_nat_multiset],
rw [multiset.coe_prod],
let l' := l.map (coe : nat.primes β β),
have : β (p : β), p β l' β p.prime :=
Ξ» p hp, by {rcases list.mem_map.mp hp with β¨β¨p', hp'β©, β¨h_mem, h_eqβ©β©,
exact h_eq βΈ hp'},
exact multiset.coe_eq_coe.mpr (@nat.factors_unique _ l' rfl this).symm,
end
end prime_multiset
namespace pnat
/-- Positive integers biject with multisets of primes. -/
def factor_multiset_equiv : β+ β prime_multiset :=
{ to_fun := factor_multiset,
inv_fun := prime_multiset.prod,
left_inv := prod_factor_multiset,
right_inv := prime_multiset.factor_multiset_prod }
/-- Factoring gives a homomorphism from the multiplicative
monoid β+ to the additive monoid of multisets. -/
theorem factor_multiset_one : factor_multiset 1 = 0 := rfl
theorem factor_multiset_mul (n m : β+) :
factor_multiset (n * m) = (factor_multiset n) + (factor_multiset m) :=
begin
let u := factor_multiset n,
let v := factor_multiset m,
have : n = u.prod := (prod_factor_multiset n).symm, rw[this],
have : m = v.prod := (prod_factor_multiset m).symm, rw[this],
rw[β prime_multiset.prod_add],
repeat {rw[prime_multiset.factor_multiset_prod]},
end
theorem factor_multiset_pow (n : β+) (m : β) :
factor_multiset (n ^ m) = add_monoid.smul m (factor_multiset n) :=
begin
let u := factor_multiset n,
have : n = u.prod := (prod_factor_multiset n).symm,
rw[this, β prime_multiset.prod_smul],
repeat {rw[prime_multiset.factor_multiset_prod]},
end
/-- Factoring a prime gives the corresponding one-element multiset. -/
theorem factor_multiset_of_prime (p : nat.primes) :
(p : β+).factor_multiset = prime_multiset.of_prime p :=
begin
apply factor_multiset_equiv.symm.injective,
change (p : β+).factor_multiset.prod = (prime_multiset.of_prime p).prod,
rw[(p : β+).prod_factor_multiset, prime_multiset.prod_of_prime],
end
/-- We now have four different results that all encode the
idea that inequality of multisets corresponds to divisibility
of positive integers. -/
theorem factor_multiset_le_iff {m n : β+} :
factor_multiset m β€ factor_multiset n β m β£ n :=
begin
split,
{ intro h,
rw [β prod_factor_multiset m, β prod_factor_multiset m],
apply dvd_intro (n.factor_multiset - m.factor_multiset).prod,
rw [β prime_multiset.prod_add, prime_multiset.factor_multiset_prod,
prime_multiset.add_sub_of_le h, prod_factor_multiset] },
{ intro h,
rw [β mul_div_exact h, factor_multiset_mul],
exact le_add_right (le_refl _) }
end
theorem factor_multiset_le_iff' {m : β+} {v : prime_multiset}:
factor_multiset m β€ v β m β£ v.prod :=
by { let h := @factor_multiset_le_iff m v.prod,
rw [v.factor_multiset_prod] at h, exact h }
end pnat
namespace prime_multiset
theorem prod_dvd_iff {u v : prime_multiset} : u.prod β£ v.prod β u β€ v :=
by { let h := @pnat.factor_multiset_le_iff' u.prod v,
rw [u.factor_multiset_prod] at h, exact h.symm }
theorem prod_dvd_iff' {u : prime_multiset} {n : β+} : u.prod β£ n β u β€ n.factor_multiset :=
by { let h := @prod_dvd_iff u n.factor_multiset,
rw [n.prod_factor_multiset] at h, exact h }
end prime_multiset
namespace pnat
/-- The gcd and lcm operations on positive integers correspond
to the inf and sup operations on multisets.
-/
theorem factor_multiset_gcd (m n : β+) :
factor_multiset (gcd m n) = (factor_multiset m) β (factor_multiset n) :=
begin
apply le_antisymm,
{ apply le_inf_iff.mpr; split; apply factor_multiset_le_iff.mpr,
exact gcd_dvd_left m n, exact gcd_dvd_right m n},
{ rw[β prime_multiset.prod_dvd_iff, prod_factor_multiset],
apply dvd_gcd; rw[prime_multiset.prod_dvd_iff'],
exact inf_le_left, exact inf_le_right}
end
theorem factor_multiset_lcm (m n : β+) :
factor_multiset (lcm m n) = (factor_multiset m) β (factor_multiset n) :=
begin
apply le_antisymm,
{ rw[β prime_multiset.prod_dvd_iff, prod_factor_multiset],
apply lcm_dvd; rw[β factor_multiset_le_iff'],
exact le_sup_left, exact le_sup_right},
{ apply sup_le_iff.mpr; split; apply factor_multiset_le_iff.mpr,
exact dvd_lcm_left m n, exact dvd_lcm_right m n },
end
/-- The number of occurrences of p in the factor multiset of m
is the same as the p-adic valuation of m. -/
theorem count_factor_multiset (m : β+) (p : nat.primes) (k : β) :
(p : β+) ^ k β£ m β k β€ m.factor_multiset.count p :=
begin
intros,
rw [multiset.le_count_iff_repeat_le],
rw [β factor_multiset_le_iff, factor_multiset_pow, factor_multiset_of_prime],
congr' 2,
apply multiset.eq_repeat.mpr,
split,
{ rw [multiset.card_smul, prime_multiset.card_of_prime, mul_one] },
{ have : β (m : β), add_monoid.smul m (p::0) = multiset.repeat p m :=
Ξ» m, by {induction m with m ih, { refl },
rw [succ_smul, multiset.repeat_succ, ih],
rw[multiset.cons_add, zero_add] },
intros q h, rw [prime_multiset.of_prime, this k] at h,
exact multiset.eq_of_mem_repeat h }
end
end pnat
namespace prime_multiset
theorem prod_inf (u v : prime_multiset) :
(u β v).prod = pnat.gcd u.prod v.prod :=
begin
let n := u.prod,
let m := v.prod,
change (u β v).prod = pnat.gcd n m,
have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this],
have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this],
rw [β pnat.factor_multiset_gcd n m, pnat.prod_factor_multiset]
end
theorem prod_sup (u v : prime_multiset) :
(u β v).prod = pnat.lcm u.prod v.prod :=
begin
let n := u.prod,
let m := v.prod,
change (u β v).prod = pnat.lcm n m,
have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this],
have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this],
rw[β pnat.factor_multiset_lcm n m, pnat.prod_factor_multiset]
end
end prime_multiset
|
b6bac2142f1bc218e6a6413d68a1c8d567f539b6 | 8c02fed42525b65813b55c064afe2484758d6d09 | /src/proptest.lean | 6988de6a29a583123ad92908bfeb803dec29753e | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | microsoft/AliveInLean | 3eac351a34154efedd3ffc4fe2fa4ec01b219e0d | 4b739dd6e4266b26a045613849df221374119871 | refs/heads/master | 1,691,419,737,939 | 1,689,365,567,000 | 1,689,365,568,000 | 131,156,103 | 23 | 18 | NOASSERTION | 1,660,342,040,000 | 1,524,747,538,000 | Lean | UTF-8 | Lean | false | false | 27,402 | lean | -- Copyright (c) Microsoft Corporation. All rights reserved.
-- Licensed under the MIT license.
import system.io
import .smtexpr
import .smtcompile
import .spec.spec
import smt2.tactic
open tactic
open spec
namespace proptest
@[reducible]
meta def var := expr -- name and its type
meta def var.ty (v:var) :=
match v with
| (expr.local_const n1 n2 b itsty) := itsty
| _ := v
end
meta def var.setty (v:var) (newty:expr):var :=
match v with
| (expr.local_const n1 n2 b itsty) :=
(expr.local_const n1 n2 b newty)
| _ := v
end
meta def tys (l:list var):list expr :=
l.map (Ξ» v, v.ty)
meta def print_detail: expr β nat β tactic unit
| (expr.local_const n1 n2 b itsty) icnt := do
let indent := list.as_string (list.repeat ' ' icnt),
trace format!"{indent}(local_const {n1} {n2} _",
print_detail itsty (icnt + 2),
trace format!"{indent})"
| (expr.app a1 a2) icnt := do
let indent := list.as_string (list.repeat ' ' icnt),
trace format!"{indent}(app",
print_detail a1 (icnt + 2),
print_detail a2 (icnt + 2),
trace format!"{indent})"
| (expr.lam n b e e') icnt := do
let indent := list.as_string (list.repeat ' ' icnt),
trace format!"{indent}(lam {n}",
print_detail e (icnt + 2),
print_detail e' (icnt + 2),
trace format!"{indent})"
| (expr.pi n b e e') icnt := do
let indent := list.as_string (list.repeat ' ' icnt),
trace format!"{indent}(pi {n}",
print_detail e (icnt + 2),
print_detail e' (icnt + 2),
trace format!"{indent})"
| (expr.elet n e1 e2 e3) icnt := do
let indent := list.as_string (list.repeat ' ' icnt),
trace format!"{indent}(elet {n}",
print_detail e1 (icnt + 2),
print_detail e2 (icnt + 2),
print_detail e3 (icnt + 2),
trace format!"{indent})"
| (expr.macro _ _) _ := fail "Unsupported case"
| (expr.var v) icnt := do
let indent := list.as_string (list.repeat ' ' icnt),
trace format!"{indent}(var {v})"
| (expr.sort lvl) icnt := do
let indent := list.as_string (list.repeat ' ' icnt),
trace format!"{indent}(sort {lvl})"
| (expr.const n levels) icnt := do
let indent := list.as_string (list.repeat ' ' icnt),
trace format!"{indent}(const {n} {levels})"
| (expr.mvar n1 n2 _) icnt := do
let indent := list.as_string (list.repeat ' ' icnt),
trace format!"{indent}(mvar {n1} {n2} _)"
meta def is_inequality (tyname:name):bool :=
tyname = `has_lt.lt β¨ tyname = `has_le.le β¨
tyname = `gt β¨ tyname = `ge β¨ tyname = `lt β¨ tyname = `le
-- Utility functions
-- Replaces name with val.
-- If nested_only is tt, it replaces things only inside
-- the expression.
meta def replace (name:expr) (val:expr): bool β expr β expr
| nested_only x@(expr.local_const n m b itsty) :=
if x = name β§ Β¬ nested_only then val
else expr.local_const n m b (replace ff itsty)
| nested_only (expr.app e1 e2) :=
expr.app (replace ff e1) (replace ff e2)
| nested_only (expr.pi n b nty e) :=
expr.pi n b (replace ff nty) (replace ff e)
| nested_only (expr.lam n b nty e) :=
expr.lam n b (replace ff nty) (replace ff e)
| nested_only x := x -- for all other cases - just give up! :(
-- Get all bound variables inside an expression.
meta def get_allvars: expr β tactic (list var)
| e@(expr.local_const _ n _ itsty) := return [e]
| (expr.app f g) := do
l1 β get_allvars f,
l2 β get_allvars g,
return (l1.union l2)
| (expr.lam n b nty e2) := do
l1 β get_allvars nty,
l2 β get_allvars e2,
return (l1.union (l2.filter (Ξ» i,
Β¬ (n = i.local_uniq_name β§ nty = i.local_type))))
| (expr.pi n b nty e2) := do
l1 β get_allvars nty,
l2 β get_allvars e2,
return (l1.union (l2.filter (Ξ» i,
Β¬ (n = i.local_uniq_name β§ nty = i.local_type))))
| (expr.elet _ _ _ _) := fail "Unsupported case"
| (expr.macro _ _) := fail "Unsupported case"
| (expr.var _) := return []
| (expr.sort _) := return []
| (expr.const _ _) := return []
| (expr.mvar _ _ _) := return []
-- Remove parameters and return the type name of e.
-- ex) bitvector 8 -> bitvector
meta def get_typename (e:expr): tactic name :=
match (e.get_app_fn) with
| expr.const n _ := return n
| _ := do
trace "??",
print_detail e 2,
fail "cannot get typename"
end
-- A list of assignments.
@[reducible]
meta def assns := list (var Γ expr)
namespace assns
meta def assign (a:assns) (v:var) (val:expr) :=
(v, val)::a
meta def get (a:assns) (v:var): option expr :=
match (list.filter (Ξ» (i:var Γ expr), i.1 = v) a) with
| head::tail := some head.2
| _ := none
end
meta def erase (a:assns) (v:var):assns :=
list.filter (Ξ» itm, itm.1 β v) a
-- Replaces all occurrences of variables in e
-- with corresponding value if there exists an assignment.
-- If `nested_only` is tt, it replaces only nested expressions
-- inside e.
meta def replace_all (a:assns) (e:expr) (nested_only:bool): expr :=
list.foldl (Ξ» (s:expr) (y:var Γ expr),
-- Replace y.1.1 in s with y.2.
replace y.1 y.2 nested_only s) e a
end assns
-- Random value generator.
meta def valgen := (assns Γ std_gen) β tactic (expr Γ assns Γ std_gen)
meta structure test_env :=
(vars:list var) -- Variables
(goal:expr) -- goal
(a:assns) -- Assignments to the variables
(g:std_gen) -- Random value generator
-- Lazy evaluator of variables.
(f:var β valgen)
namespace test_env
-- Creates an empty testing context
meta def new (vars:list var) (goal:expr) (randgen:std_gen):test_env :=
test_env.mk vars goal [] randgen
(Ξ» (x:var) (y:assns Γ std_gen), do
trace "Uninitialized variable:",
print_detail x 2,
fail "Uninitialized variable")
-- Adds a new uninitializd variable.
meta def add_var (tenv:test_env) (v:var):test_env :=
β¨tenv.vars ++ [v], -- preserves order
tenv.goal, tenv.a, tenv.g, tenv.fβ©
-- Replace v in tenv.vars with v'
meta def replace_var_at (tenv:test_env) (idx:nat) (newv:var):tactic test_env :=
do
v β tenv.vars.nth idx,
return β¨tenv.vars.map (Ξ» x, if x = v then newv else x),
tenv.goal, tenv.a.map (Ξ» x, if x.1 = v then (newv, x.2) else x),
tenv.g,
(Ξ» x, if x = newv then tenv.f v else tenv.f x)β©
-- Updates random value generator
meta def update_gen (tenv:test_env) (newgen:std_gen):test_env :=
β¨tenv.vars, tenv.goal, tenv.a, newgen, tenv.fβ©
-- Updates goal.
meta def update_goal (tenv:test_env) (newgoal:expr):test_env :=
β¨tenv.vars, newgoal, tenv.a, tenv.g, tenv.fβ©
meta def has_value (tenv:test_env) (v:var):bool :=
tenv.a.get v β none
-- Get the assigned value.
meta def get (tenv:test_env) (v:var):tactic expr :=
let err:tactic expr := do
trace format!"test_env.get:Unknown variable",
trace "finding variable:",
print_detail v 0,
trace "each vars:",
monad.foldl (Ξ» _ (v:var), do
print_detail v 0) () tenv.vars,
fail format!"test_env.get:Unknown variable {v}" in
if tenv.vars.mem v then
match tenv.a.get v with
| none := err
| some n := return n
end
else err
-- Gets the value expression assigned to the variable.
-- If there's no such value, create a new value and assign it.
meta def get_or_init (tenv:test_env) (v:var):tactic (expr Γ test_env) :=
if tenv.vars.mem v then
match tenv.a.get v with
| none := do
(val, a, g) β tenv.f v (tenv.a, tenv.g),
return (val, β¨tenv.vars, tenv.goal, a.assign v val, g, tenv.fβ©)
| some n :=
return (n, tenv)
end
else do
trace format!"test_env.get_or_init:Unknown variable",
trace "finding variable:",
print_detail v 0,
trace "each vars:",
monad.foldl (Ξ» _ (v:var), do
print_detail v 0) () tenv.vars,
fail format!"test_env.get_or_init:Unknown variable {v}"
-- Evaluate the expression which is assigned to the variable.
meta def eval (tenv:test_env) (v:var) (retty:Type) [reflected retty]
:tactic retty :=
match (tenv.a.get v) with
| some vexpr := do
v β eval_expr retty vexpr,
return v
| none := fail "Cannot find assignment to the variable"
end
-- Replace all occurrences of variable v in vars and goal
-- into its assigned value.
meta def replace_all (tenv:test_env) (v:var): test_env :=
β¨tenv.vars.map (Ξ» (i:var),
if v β i then
-- variable name contains type as well.
-- However,
(tenv.a.replace_all i tt)
else i),
tenv.a.replace_all tenv.goal ff,
tenv.a, tenv.g, tenv.fβ©
-- Adds a lazy evalutor for the variable.
meta def add_evaluator (tenv:test_env) (v:var) (f:valgen)
:test_env :=
β¨tenv.vars, tenv.goal, tenv.a, tenv.g,
(Ξ» v0, if v0 = v then f else tenv.f v0)β©
end test_env
-- Pick a random value of given type and assign to it.
-- valgen = (assns Γ std_gen) β tactic (expr Γ assns Γ std_gen)
meta def pick :var β valgen
| v f :=
let (a, gen) := f in
do
tyname β get_typename v.ty,
if tyname = `size then
do
let (n,gen') := std_next gen,
let n := n % 5,
let ne := `(n),
return (`(size.incr_nat %%ne), a, gen')
else if tyname = `bitvector then
do
-- size of bitvector is already concretized by process_type.
`(bitvector %%sze) β pure v.ty,
sz β eval_expr size sze,
let (n,gen') := std_next gen,
let n' := n % (2^sz.val),
let n'e := `(n'),
e β to_expr ``(bitvector.of_int %%sze %%n'e),
return (e, a, gen')
else if tyname = `sbitvec then
do
-- size of sbitvec is already concretized by process_type.
-- Assign sbitvec.var!
`(sbitvec %%sze) β pure v.ty,
sz β eval_expr size sze,
let vname := to_string v,
let vnamee := `(vname),
e β to_expr ``(sbitvec.var %%sze %%vnamee),
return (e, a, gen)
else if tyname = `bool then
do
let (n, gen') := std_next gen,
let b:bool := n % 2 = 0,
let be := `(b),
return (be, a, gen')
else if tyname = `sbool then
do
-- Assign sbool.var!
let vname := to_string v,
let vnamee := `(vname),
be' β to_expr ``(sbool.var %%vnamee),
return (be', a, gen)
else if tyname = `int then
do
let (n, gen') := std_next gen,
let ne := `(((int.of_nat n) - (int.of_nat n) * 2)),
return (ne, a, gen')
else if tyname = `nat then
do
let (n, gen') := std_next gen,
let ne := `(n),
return (ne, a, gen')
else
do
trace v,
fail "Unknown type!"
-- Checks whether the type can be encoded into SMT.
meta def can_encode_to_smt (tyexpr:expr): tactic bool :=
if tyexpr.is_arrow then return tt
else do
n β get_typename tyexpr,
return (n = `eq β¨ n = `or β¨ n = `and β¨
n = `spec.bv_equiv β¨ n = `spec.b_equiv β¨ n = `true β¨ n = `false β¨
n = `bitvector β¨ n = `sbitvec β¨
n = `bool β¨ n = `int) -- no natural number now.
-- Replace all occurrences of variables in e with its value,
-- as well as all other occurences in test_env.
-- If leave_vars is tt, variables are not instantiated unless
-- it is used by functions which cannot be encoded to SMT.
-- For example, if leave_vars = tt, then term `x op y` does not
-- instantiate x and y if it is known that 'op has its corresponding
-- SMT operation.
meta def concretize: test_env β expr β bool β tactic (test_env Γ expr)
| tenv e leave_vars := do
if leave_vars β§ e.is_local_constant then do
-- Don't initialize it if e is just a variable.
-- Otherwise it removes opportunity to use 'forall' in SMT.
return (tenv, e)
else do
flag β can_encode_to_smt e,
if flag β§ leave_vars then do
-- ex: "p = q"
let args := e.get_app_args,
let f := e.get_app_fn,
(tenv, args') β monad.foldl (Ξ» (x:test_env Γ list expr) (arg:expr), do
let tenv := x.1,
-- Replace all initialized variables with
-- its corresponding value.
let arg := tenv.a.replace_all arg ff,
(tenv, arg') β concretize tenv arg leave_vars,
return (tenv, x.2 ++ [arg']))
(tenv, []) args,
return (tenv, f.app_of_list args')
else do
vars β get_allvars e,
res β monad.foldl (Ξ» (x:test_env Γ expr) v, do
--print_detail v 2,
let (tenv, e) := x,
(val, tenv) β tenv.get_or_init v, -- Give random value to v
-- Replace all occurrences of v with its value
let tenv := tenv.replace_all v,
let e := replace v val ff e,
return (tenv, e))
(tenv, e) vars,
return res
meta mutual def process_eq, process_ineq,
process_implies, process_and,
process_or, process_bv_equiv_opt,
process_bv_equiv, process_b_equiv_opt,
process_b_equiv, process_type
-- Processes `P = Q`
-- Currently equality does nothing special.
with process_eq: test_env β expr β tactic (test_env Γ option expr)
| tenv pty := do
(tenv, e) β concretize tenv pty tt,
return (tenv, some e)
-- Processes 'P > Q', 'P β€ Q', ...
with process_ineq: test_env β expr β tactic (test_env Γ option expr)
| tenv pty := do
(tenv, e) β concretize tenv pty tt,
b β try_core (do
pre_cast β to_expr ``(to_bool %%e),
b β eval_expr bool pre_cast,
return b),
match b with
| some b :=
return (tenv, if b then some `(true) else some `(false))
| none := fail "Converting inequality into SMT is not supported ; should be eagerly evaluated"
end
-- Processes `P β Q`
with process_implies: test_env β expr β tactic (test_env Γ option expr)
| tenv pty@(expr.pi n bi pre post) :=
do
(tenv, pre) β concretize tenv pre tt, -- Let's concretize precondition first.
-- Can we evaluate this precondition in Lean?
-- (e.g. is all local variables in precondition initialized?)
pre_b β try_core (do
pre_cast β to_expr ``(to_bool %%pre),
b β eval_expr bool pre_cast,
return b),
match pre_b with
| some ff := -- Precondition evaluates to false!
-- We can just remove this implies term, if allowed.
return (tenv, none)
| some tt := -- Precondition is true, equivalent to postcondition only.
process_type tenv post
| none := -- Let's process postcondition now.
do
(tenv, post) β concretize tenv post tt,
return (tenv, expr.pi n bi pre post)
end
| _ _ := fail "Invalid argument"
-- Processes `P β§ Q`
with process_and: test_env β expr β tactic (test_env Γ option expr)
| tenv pty :=
do
`(and %%e1 %%e2) β pure pty,
(tenv, oe1) β process_type tenv e1,
(tenv, oe2) β process_type tenv e2,
match oe1, oe2 with
| none, none := return (tenv, none)
| some e1, none := return (tenv, some e1)
| none, some e2 := return (tenv, some e2)
| some e1, some e2 := do
e β to_expr ``(and %%e1 %%e2),
return (tenv, e)
end
-- Processes `P β¨ Q`
with process_or: test_env β expr β tactic (test_env Γ option expr)
| tenv pty :=
do
`(or %%e1 %%e2) β pure pty,
(tenv, e1) β concretize tenv e1 tt,
(tenv, e2) β concretize tenv e2 tt,
e β to_expr ``(or %%e1 %%e2),
return (tenv, some e)
-- Processes `bv_equiv s b`, assign s = (sbitvec.of_bv b) if possible
with process_bv_equiv_opt: test_env β expr β tactic (test_env Γ option expr)
| tenv pty :=
do
`(spec.bv_equiv %%s %%b) β pure pty,
if s.is_local_constant then do
-- s is just a simple variable.
-- Let's replace s with (sbitvec.of_bv b).
-- Then, this bv_equiv can be removed.
b' β to_expr ``(sbitvec.of_bv %%b),
(tenv, b') β concretize tenv b' tt,
let f:valgen := (Ξ»l, return (b', l.1, l.2)),
let tenv := tenv.add_evaluator s f,
return (tenv, none)
else do
-- Eagerly assign all variables in s.
(tenv, s) β concretize tenv s tt,
(tenv, b) β concretize tenv b tt,
e β to_expr ``(spec.bv_equiv %%s %%b),
return (tenv, some e)
-- Processes `bv_equiv s b`
with process_bv_equiv: test_env β expr β tactic (test_env Γ option expr)
| tenv pty :=
do
`(spec.bv_equiv %%s %%b) β pure pty,
(tenv, s) β concretize tenv s tt,
(tenv, b) β concretize tenv b tt,
e β to_expr ``(spec.bv_equiv %%s %%b),
return (tenv, some e)
-- Processes `b_equiv s b`, assign s = (sbool.of_bool b) if possible
with process_b_equiv_opt: test_env β expr β tactic (test_env Γ option expr)
| tenv pty :=
do
`(b_equiv %%s %%b) β pure pty,
if s.is_local_constant then do
-- s is just a simple variable.
-- Let's replace s with (sbool.of_bool b).
-- Then, this b_equiv can be removed.
sty β infer_type s,
b' β to_expr ``(sbool.of_bool %%b),
(tenv, b') β concretize tenv b' tt,
let f:valgen := (Ξ»l, return (b', l.1, l.2)),
let tenv := tenv.add_evaluator s f,
return (tenv, none)
else do
-- Eagerly assign all variables in s.
(tenv, s) β concretize tenv s tt,
(tenv, b) β concretize tenv b tt,
e β to_expr ``(b_equiv %%s %%b),
return (tenv, some e)
-- Processes `bv_equiv s b`
with process_b_equiv: test_env β expr β tactic (test_env Γ option expr)
| tenv pty :=
do
`(spec.b_equiv %%s %%b) β pure pty,
(tenv, s) β concretize tenv s tt,
(tenv, b) β concretize tenv b tt,
e β to_expr ``(spec.b_equiv %%s %%b),
return (tenv, some e)
-- Returns new test environmen Γ optimized expression.
-- (ex: bitvector sz -> bitvector 8)
-- If the expression can be totally removed, it returns none.
-- Otherwise, it returns the updated expression.
with process_type: test_env β expr β tactic (test_env Γ option expr)
| tenv pty :=
do
is_prop β is_prop pty,
match is_prop with
| tt := do -- it is Prop!
(tenv, oe) β (
if pty.is_arrow then
process_implies tenv pty
else do
tyname β get_typename pty,
if tyname = `eq then process_eq tenv pty
else if is_inequality tyname then
process_ineq tenv pty
else if tyname = `or then process_or tenv pty
else if tyname = `and then process_and tenv pty
else if tyname = `spec.bv_equiv then process_bv_equiv tenv pty
else if tyname = `spec.b_equiv then process_b_equiv tenv pty
else fail "."),
return (tenv, oe)
| ff := do -- it is not Prop.
-- Eagerly assign parameters of the type.
-- eg) bitvector sz
-- Here, sz should be initialized immediately.
(tenv, pty) β concretize tenv pty ff,
return (tenv, some pty)
end
-- Evaluates e(ex: `1+1` -> 2), and returns a string that encodes e
-- so it can be used in SMT code.
meta def eval_and_tosmtstr (e:expr):tactic string :=
do
ty β infer_type e,
tn β get_typename ty,
ostr β try_core (
if tn = `bitvector then do
e β to_expr ``(to_string (sbitvec.of_bv %%e)),
str β eval_expr string e,
return str
else if tn = `sbitvec then do
e β to_expr ``(to_string (%%e)),
str β eval_expr string e,
return str
else if tn = `int then do
i β eval_expr int e,
return (to_string i)
else if tn = `bool then do
if e = `(bool.tt) then
return "true"
else if e = `(bool.ff) then
return "false"
else do
b β eval_expr bool e,
return (if b then "true" else "false")
else fail ""),
match ostr with
| none := do
-- I wish this will work in general..
fmt β tactic_format_expr e,
return (to_string fmt)
| some s := return s
end
-- smt2.term does not have has_to_pexpr, so expr_to_string / prop_to_smt
-- is currently returning string instead of smt2.term.
meta mutual def expr_to_smt, prop_to_smt
with expr_to_smt: test_env β expr β tactic string
| tenv e :=
do
is_prop β is_prop e,
match is_prop with
| tt := prop_to_smt tenv e
| ff := do
str β eval_and_tosmtstr e,
return str
end
with prop_to_smt: test_env β expr β tactic string
| tenv ty :=
do
e β (
if ty.is_arrow then do
let p := ty.binding_domain,
let q := ty.binding_body,
sp β prop_to_smt tenv p,
sq β prop_to_smt tenv q,
--e β to_expr ``(smt2.builder.implies %%sp %%sq),
return $ to_string (format!"(=> {sp} {sq})")
else do
tyname β get_typename ty,
if tyname = `eq then do
`(eq %%p %%q) β pure ty,
sp β expr_to_smt tenv p,
sq β expr_to_smt tenv q,
return $ to_string (format!"(= {sp} {sq})")
else if tyname = `or then do
`(or %%p %%q) β pure ty,
sp β prop_to_smt tenv p,
sq β prop_to_smt tenv q,
return $ to_string (format!"(or {sp} {sq})")
else if tyname = `and then do
`(and %%p %%q) β pure ty,
sp β prop_to_smt tenv p,
sq β prop_to_smt tenv q,
return $ to_string (format!"(and {sp} {sq})")
else if tyname = `spec.bv_equiv then do
`(@spec.bv_equiv %%sz %%s %%b) β pure ty,
se β to_expr ``(to_string (%%s)),
sstr β eval_expr string se,
be β to_expr ``(to_string (sbitvec.of_bv %%b)),
bstr β eval_expr string be,
return $ to_string (format!"(= {sstr} {bstr})")
else if tyname = `spec.b_equiv then do
`(b_equiv %%s %%b) β pure ty,
se β to_expr ``(to_string (%%s)),
sstr β eval_expr string se,
bse β to_expr ``(to_string (sbool.of_bool %%b)),
bstr β eval_expr string bse,
return $ to_string (format!"(= {sstr} {bstr})")
else if tyname = `true then do
return "true"
else if tyname = `false then do
return "false"
else
do
trace ty,
fail "Unknown goal type"),
return e
-- Creates a variable which can be used for forall quantifier.
meta def var_to_smtvar (tenv:test_env) (v:var): tactic (option (string Γ smt2.sort)) :=
do
tyname β get_typename v.ty,
if tyname = `size then
-- size should be initialized in Lean.
if tenv.has_value v then return none
else fail "size should be initialized in Lean."
else if tyname = `bitvector then
if tenv.has_value v then return none
else do
-- sz should be already concretized.
`(bitvector %%sz) β pure v.ty,
sz β eval_expr size sz,
return (to_string v,
smt2.sort.apply "_" ["BitVec", to_string sz])
else if tyname = `sbitvec then
-- a BitVec variable creator.
let newvar := Ξ» (sze:expr) (vname:string), do
-- sz should be already concretized.
sz β eval_expr size sze,
return (some (vname,
smt2.sort.apply "_" ["BitVec", to_string sz]))
in
if tenv.has_value v then do
val β tenv.get v,
-- If sbitvec.var is assigned, it can be forall quantified.
o β try_core (do
`(sbitvec.var %%sze %%varnamee) β pure val,
varname β eval_expr string varnamee,
return (sze, varname)
),
match o with
| none := return none -- it's not variable.
| some (sz, vname) := newvar sz vname
end
else do
`(sbitvec %%sz) β pure v.ty,
newvar sz (to_string v)
else if tyname = `bool then
if tenv.has_value v then return none
else return (to_string v,
smt2.sort.id "Bool")
else if tyname = `sbool then
if tenv.has_value v then do
val β tenv.get v,
-- If sbitvec.var is assigned, it can be forall quantified.
o β try_core (do
`(sbool.var %%varnamee) β pure val,
varname β eval_expr string varnamee,
return varname
),
match o with
| none := return none -- it's not variable.
| some vname :=
return (some (vname, smt2.sort.id "Bool"))
end
else do
return (some (to_string v, smt2.sort.id "Bool"))
else if tyname = `int then
if tenv.has_value v then return none
else return (to_string v,
smt2.sort.id "Int")
else
do
trace v,
fail "Unknown type!"
meta def update_smt (tenv:test_env) (orgsmt: string) (v:var): tactic string :=
do
is_prop β is_prop v.ty,
match is_prop with
| tt := do
t β prop_to_smt tenv v.ty,
return $ to_string (format!"(=> {t} {orgsmt})")
| ff := do
ovar β var_to_smtvar tenv v,
match ovar with
| none := -- Isn't needed to create forall.
return orgsmt
| some (vname, sort) :=
-- Make (forall x, P).
return $ to_string (format!"(forall (({vname} {sort})) {orgsmt})")
end
end
meta def build_smt (tenv:test_env): tactic string :=
do
-- First, synthesize goal.
smt β prop_to_smt tenv tenv.goal,
smt β monad.foldl (update_smt tenv) smt (tenv.vars.reverse),
return $ to_string (format!"(assert {smt})")
meta def run_smt (smtcode:string) : io smt2.response :=
do
z3i β z3_instance.start,
smtres β z3_instance.raw z3i (smtcode ++ " (check-sat)"),
pure (parse_smt2_result smtres)
meta def visit_each_param :test_env β nat β tactic test_env
| tenv n :=
if tenv.vars.length β€ n then return tenv
else do
v β tenv.vars.nth n,
(tenv, oe) β process_type tenv v.ty,
match oe with
| none :=
-- This parameter is optimized out.
-- Remove the param from testing environment later.
visit_each_param tenv (n+1)
| some e' := do
let newv := v.setty e',
is_prop β is_prop v.ty,
tenv β tenv.replace_var_at n newv,
visit_each_param (if Β¬ is_prop then
-- register a random value generator for newv
tenv.add_evaluator newv (pick newv)
else tenv) (n+1)
end
meta def test_can_be_omitted (tenv:test_env): bool :=
tenv.vars.any (Ξ» v, v.ty = `(false))
inductive test_result:Type
| success | fail | unknown | error : string β test_result | omitted
instance : decidable_eq test_result :=
by tactic.mk_dec_eq_instance
instance : has_to_string test_result :=
β¨Ξ» r, match r with
| test_result.success := "success"
| test_result.fail := "fail"
| test_result.unknown := "unknown"
| test_result.error s := "error(" ++ s ++ ")"
| test_result.omitted := "omitted"
end β©
-- Main function.
meta def test (spec : expr) (gen:std_gen)
:tactic (string Γ test_result Γ std_gen) :=
do
-- 1. Infer the type of specificaton
t β infer_type spec,
-- 2. Segregate arguments from the type, and
-- infer types of the input arguments.
-- ex) get a, b from Ξ (a:nat) (b:nat), P a b
(params, goal) β mk_local_pis t,
-- 3. Create the test environment.
let tenv := test_env.new params goal gen,
-- 4. Process each parameter.
tenv β visit_each_param tenv 0,
-- 5. Process goal.
(tenv, some newgoal) β process_type tenv tenv.goal,
let tenv := tenv.update_goal newgoal,
-- 6. If a test can be omitted, stop here.
-- ex) if there is a false in its premise, it isn't needed to invoke smt
if test_can_be_omitted tenv then
return ("", test_result.omitted, tenv.g)
else do
-- 7. Synthesize SMT code.
smtcode β build_smt tenv,
let smtcode_expr := `(smtcode),
tgt β to_expr ``(run_smt %%smtcode_expr),
tgt β eval_expr (io smt2.response) tgt,
res β unsafe_run_io tgt,
return (smtcode, match res with
| smt2.response.sat := test_result.success
| smt2.response.unsat := test_result.fail
| smt2.response.unknown := test_result.unknown
| smt2.response.other s := test_result.error s
end, tenv.g)
end proptest
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.