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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
602dbe0fdeee5db6431180f4121fd15810be888e | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/list/defs.lean | cd55b14e59892c4d8b7c18b3ab4f1211c1f128c6 | [
"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 | 41,496 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import logic.basic
import tactic.cache
import data.rbmap.basic
import data.rbtree.default_lt
/-!
## Definitions on lists
This file contains various definitions on lists. It does not contain
proofs about these definitions, those are contained in other files in `data/list`
-/
namespace list
open function nat
universes u v w x
variables {α β γ δ ε ζ : Type*}
instance [decidable_eq α] : has_sdiff (list α) :=
⟨ list.diff ⟩
/-- Split a list at an index.
split_at 2 [a, b, c] = ([a, b], [c]) -/
def split_at : ℕ → list α → list α × list α
| 0 a := ([], a)
| (succ n) [] := ([], [])
| (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r)
/-- An auxiliary function for `split_on_p`. -/
def split_on_p_aux {α : Type u} (P : α → Prop) [decidable_pred P] :
list α → (list α → list α) → list (list α)
| [] f := [f []]
| (h :: t) f :=
if P h then f [] :: split_on_p_aux t id
else split_on_p_aux t (λ l, f (h :: l))
/-- Split a list at every element satisfying a predicate. -/
def split_on_p {α : Type u} (P : α → Prop) [decidable_pred P] (l : list α) : list (list α) :=
split_on_p_aux P l id
/-- Split a list at every occurrence of an element.
[1,1,2,3,2,4,4].split_on 2 = [[1,1],[3],[4,4]] -/
def split_on {α : Type u} [decidable_eq α] (a : α) (as : list α) : list (list α) :=
as.split_on_p (=a)
/-- Concatenate an element at the end of a list.
concat [a, b] c = [a, b, c] -/
@[simp] def concat : list α → α → list α
| [] a := [a]
| (b::l) a := b :: concat l a
/-- `head' xs` returns the first element of `xs` if `xs` is non-empty;
it returns `none` otherwise -/
@[simp] def head' : list α → option α
| [] := none
| (a :: l) := some a
/-- Convert a list into an array (whose length is the length of `l`). -/
def to_array (l : list α) : array l.length α :=
{data := λ v, l.nth_le v.1 v.2}
/-- "default" `nth` function: returns `d` instead of `none` in the case
that the index is out of bounds. -/
def nthd (d : α) : Π (l : list α) (n : ℕ), α
| [] _ := d
| (x::xs) 0 := x
| (x::xs) (n + 1) := nthd xs n
/-- "inhabited" `nth` function: returns `default` instead of `none` in the case
that the index is out of bounds. -/
def inth [h : inhabited α] (l : list α) (n : nat) : α := nthd default l n
/-- Apply a function to the nth tail of `l`. Returns the input without
using `f` if the index is larger than the length of the list.
modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c] -/
@[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α
| 0 l := f l
| (n+1) [] := []
| (n+1) (a::l) := a :: modify_nth_tail n l
/-- Apply `f` to the head of the list, if it exists. -/
@[simp] def modify_head (f : α → α) : list α → list α
| [] := []
| (a::l) := f a :: l
/-- Apply `f` to the nth element of the list, if it exists. -/
def modify_nth (f : α → α) : ℕ → list α → list α :=
modify_nth_tail (modify_head f)
/-- Apply `f` to the last element of `l`, if it exists. -/
@[simp] def modify_last (f : α → α) : list α → list α
| [] := []
| [x] := [f x]
| (x :: xs) := x :: modify_last xs
/-- `insert_nth n a l` inserts `a` into the list `l` after the first `n` elements of `l`
`insert_nth 2 1 [1, 2, 3, 4] = [1, 2, 1, 3, 4]`-/
def insert_nth (n : ℕ) (a : α) : list α → list α := modify_nth_tail (list.cons a) n
section take'
variable [inhabited α]
/-- Take `n` elements from a list `l`. If `l` has less than `n` elements, append `n - length l`
elements `default`. -/
def take' : ∀ n, list α → list α
| 0 l := []
| (n+1) l := l.head :: take' n l.tail
end take'
/-- Get the longest initial segment of the list whose members all satisfy `p`.
take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2] -/
def take_while (p : α → Prop) [decidable_pred p] : list α → list α
| [] := []
| (a::l) := if p a then a :: take_while l else []
/-- Fold a function `f` over the list from the left, returning the list
of partial results.
scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6] -/
def scanl (f : α → β → α) : α → list β → list α
| a [] := [a]
| a (b::l) := a :: scanl (f a b) l
/-- Auxiliary definition used to define `scanr`. If `scanr_aux f b l = (b', l')`
then `scanr f b l = b' :: l'` -/
def scanr_aux (f : α → β → β) (b : β) : list α → β × list β
| [] := (b, [])
| (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l')
/-- Fold a function `f` over the list from the right, returning the list
of partial results.
scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0] -/
def scanr (f : α → β → β) (b : β) (l : list α) : list β :=
let (b', l') := scanr_aux f b l in b' :: l'
/-- Product of a list.
prod [a, b, c] = ((1 * a) * b) * c -/
def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1
/-- Sum of a list.
sum [a, b, c] = ((0 + a) + b) + c -/
-- Later this will be tagged with `to_additive`, but this can't be done yet because of import
-- dependencies.
def sum [has_add α] [has_zero α] : list α → α := foldl (+) 0
/-- The alternating sum of a list. -/
def alternating_sum {G : Type*} [has_zero G] [has_add G] [has_neg G] : list G → G
| [] := 0
| (g :: []) := g
| (g :: h :: t) := g + -h + alternating_sum t
/-- The alternating product of a list. -/
def alternating_prod {G : Type*} [has_one G] [has_mul G] [has_inv G] : list G → G
| [] := 1
| (g :: []) := g
| (g :: h :: t) := g * h⁻¹ * alternating_prod t
/-- Given a function `f : α → β ⊕ γ`, `partition_map f l` maps the list by `f`
whilst partitioning the result it into a pair of lists, `list β × list γ`,
partitioning the `sum.inl _` into the left list, and the `sum.inr _` into the right list.
`partition_map (id : ℕ ⊕ ℕ → ℕ ⊕ ℕ) [inl 0, inr 1, inl 2] = ([0,2], [1])` -/
def partition_map (f : α → β ⊕ γ) : list α → list β × list γ
| [] := ([],[])
| (x::xs) :=
match f x with
| (sum.inr r) := prod.map id (cons r) $ partition_map xs
| (sum.inl l) := prod.map (cons l) id $ partition_map xs
end
/-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such
element exists. -/
def find (p : α → Prop) [decidable_pred p] : list α → option α
| [] := none
| (a::l) := if p a then some a else find l
/-- `mfind tac l` returns the first element of `l` on which `tac` succeeds, and
fails otherwise. -/
def mfind {α} {m : Type u → Type v} [monad m] [alternative m] (tac : α → m punit) : list α → m α :=
list.mfirst $ λ a, tac a $> a
/-- `mbfind' p l` returns the first element `a` of `l` for which `p a` returns
true. `mbfind'` short-circuits, so `p` is not necessarily run on every `a` in
`l`. This is a monadic version of `list.find`. -/
def mbfind' {m : Type u → Type v} [monad m] {α : Type u} (p : α → m (ulift bool)) :
list α → m (option α)
| [] := pure none
| (x :: xs) := do
⟨px⟩ ← p x,
if px then pure (some x) else mbfind' xs
section
variables {m : Type → Type v} [monad m]
/-- A variant of `mbfind'` with more restrictive universe levels. -/
def mbfind {α} (p : α → m bool) (xs : list α) : m (option α) :=
xs.mbfind' (functor.map ulift.up ∘ p)
/-- `many p as` returns true iff `p` returns true for any element of `l`.
`many` short-circuits, so if `p` returns true for any element of `l`, later
elements are not checked. This is a monadic version of `list.any`. -/
-- Implementing this via `mbfind` would give us less universe polymorphism.
def many {α : Type u} (p : α → m bool) : list α → m bool
| [] := pure false
| (x :: xs) := do px ← p x, if px then pure tt else many xs
/-- `mall p as` returns true iff `p` returns true for all elements of `l`.
`mall` short-circuits, so if `p` returns false for any element of `l`, later
elements are not checked. This is a monadic version of `list.all`. -/
def mall {α : Type u} (p : α → m bool) (as : list α) : m bool :=
bnot <$> many (λ a, bnot <$> p a) as
/-- `mbor xs` runs the actions in `xs`, returning true if any of them returns
true. `mbor` short-circuits, so if an action returns true, later actions are
not run. This is a monadic version of `list.bor`. -/
def mbor : list (m bool) → m bool :=
many id
/-- `mband xs` runs the actions in `xs`, returning true if all of them return
true. `mband` short-circuits, so if an action returns false, later actions are
not run. This is a monadic version of `list.band`. -/
def mband : list (m bool) → m bool :=
mall id
end
/-- Auxiliary definition for `foldl_with_index`. -/
def foldl_with_index_aux (f : ℕ → α → β → α) : ℕ → α → list β → α
| _ a [] := a
| i a (b :: l) := foldl_with_index_aux (i + 1) (f i a b) l
/-- Fold a list from left to right as with `foldl`, but the combining function
also receives each element's index. -/
def foldl_with_index (f : ℕ → α → β → α) (a : α) (l : list β) : α :=
foldl_with_index_aux f 0 a l
/-- Auxiliary definition for `foldr_with_index`. -/
def foldr_with_index_aux (f : ℕ → α → β → β) : ℕ → β → list α → β
| _ b [] := b
| i b (a :: l) := f i a (foldr_with_index_aux (i + 1) b l)
/-- Fold a list from right to left as with `foldr`, but the combining function
also receives each element's index. -/
def foldr_with_index (f : ℕ → α → β → β) (b : β) (l : list α) : β :=
foldr_with_index_aux f 0 b l
/-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/
def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat :=
foldr_with_index (λ i a is, if p a then i :: is else is) [] l
/-- Returns the elements of `l` that satisfy `p` together with their indexes in
`l`. The returned list is ordered by index. -/
def indexes_values (p : α → Prop) [decidable_pred p] (l : list α) : list (ℕ × α) :=
foldr_with_index (λ i a l, if p a then (i , a) :: l else l) [] l
/-- `indexes_of a l` is the list of all indexes of `a` in `l`. For example:
```
indexes_of a [a, b, a, a] = [0, 2, 3]
```
-/
def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a)
section mfold_with_index
variables {m : Type v → Type w} [monad m]
/-- Monadic variant of `foldl_with_index`. -/
def mfoldl_with_index {α β} (f : ℕ → β → α → m β) (b : β) (as : list α) : m β :=
as.foldl_with_index (λ i ma b, do a ← ma, f i a b) (pure b)
/-- Monadic variant of `foldr_with_index`. -/
def mfoldr_with_index {α β} (f : ℕ → α → β → m β) (b : β) (as : list α) : m β :=
as.foldr_with_index (λ i a mb, do b ← mb, f i a b) (pure b)
end mfold_with_index
section mmap_with_index
variables {m : Type v → Type w} [applicative m]
/-- Auxiliary definition for `mmap_with_index`. -/
def mmap_with_index_aux {α β} (f : ℕ → α → m β) : ℕ → list α → m (list β)
| _ [] := pure []
| i (a :: as) := list.cons <$> f i a <*> mmap_with_index_aux (i + 1) as
/-- Applicative variant of `map_with_index`. -/
def mmap_with_index {α β} (f : ℕ → α → m β) (as : list α) : m (list β) :=
mmap_with_index_aux f 0 as
/-- Auxiliary definition for `mmap_with_index'`. -/
def mmap_with_index'_aux {α} (f : ℕ → α → m punit) : ℕ → list α → m punit
| _ [] := pure ⟨⟩
| i (a :: as) := f i a *> mmap_with_index'_aux (i + 1) as
/-- A variant of `mmap_with_index` specialised to applicative actions which
return `unit`. -/
def mmap_with_index' {α} (f : ℕ → α → m punit) (as : list α) : m punit :=
mmap_with_index'_aux f 0 as
end mmap_with_index
/-- `lookmap` is a combination of `lookup` and `filter_map`.
`lookmap f l` will apply `f : α → option α` to each element of the list,
replacing `a → b` at the first value `a` in the list such that `f a = some b`. -/
def lookmap (f : α → option α) : list α → list α
| [] := []
| (a::l) :=
match f a with
| some b := b :: l
| none := a :: lookmap l
end
/-- `countp p l` is the number of elements of `l` that satisfy `p`. -/
def countp (p : α → Prop) [decidable_pred p] : list α → nat
| [] := 0
| (x::xs) := if p x then succ (countp xs) else countp xs
/-- `count a l` is the number of occurrences of `a` in `l`. -/
def count [decidable_eq α] (a : α) : list α → nat := countp (eq a)
/-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`,
that is, `l₂` has the form `l₁ ++ t` for some `t`. -/
def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂
/-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`,
that is, `l₂` has the form `t ++ l₁` for some `t`. -/
def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂
/-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous
substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/
def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂
infix ` <+: `:50 := is_prefix
infix ` <:+ `:50 := is_suffix
infix ` <:+: `:50 := is_infix
/-- `inits l` is the list of initial segments of `l`.
inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]] -/
@[simp] def inits : list α → list (list α)
| [] := [[]]
| (a::l) := [] :: map (λt, a::t) (inits l)
/-- `tails l` is the list of terminal segments of `l`.
tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []] -/
@[simp] def tails : list α → list (list α)
| [] := [[]]
| (a::l) := (a::l) :: tails l
def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β)
| [] f r := f [] :: r
| (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r)
/-- `sublists' l` is the list of all (non-contiguous) sublists of `l`.
It differs from `sublists` only in the order of appearance of the sublists;
`sublists'` uses the first element of the list as the MSB,
`sublists` uses the first element of the list as the LSB.
sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] -/
def sublists' (l : list α) : list (list α) :=
sublists'_aux l id []
def sublists_aux : list α → (list α → list β → list β) → list β
| [] f := []
| (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r)))
/-- `sublists l` is the list of all (non-contiguous) sublists of `l`; cf. `sublists'`
for a different ordering.
sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] -/
def sublists (l : list α) : list (list α) :=
[] :: sublists_aux l cons
def sublists_aux₁ : list α → (list α → list β) → list β
| [] f := []
| (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys))
section forall₂
variables {r : α → β → Prop} {p : γ → δ → Prop}
/-- `forall₂ R l₁ l₂` means that `l₁` and `l₂` have the same length,
and whenever `a` is the nth element of `l₁`, and `b` is the nth element of `l₂`,
then `R a b` is satisfied. -/
inductive forall₂ (R : α → β → Prop) : list α → list β → Prop
| nil : forall₂ [] []
| cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂)
attribute [simp] forall₂.nil
end forall₂
/-- `l.all₂ p` is equivalent to `∀ a ∈ l, p a`, but unfolds directly to a conjunction, i.e.
`list.all₂ p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/
@[simp] def all₂ (p : α → Prop) : list α → Prop
| [] := true
| (x :: []) := p x
| (x :: l) := p x ∧ all₂ l
/-- Auxiliary definition used to define `transpose`.
`transpose_aux l L` takes each element of `l` and appends it to the start of
each element of `L`.
`transpose_aux [a, b, c] [l₁, l₂, l₃] = [a::l₁, b::l₂, c::l₃]` -/
def transpose_aux : list α → list (list α) → list (list α)
| [] ls := ls
| (a::i) [] := [a] :: transpose_aux i []
| (a::i) (l::ls) := (a::l) :: transpose_aux i ls
/-- transpose of a list of lists, treated as a matrix.
transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]] -/
def transpose : list (list α) → list (list α)
| [] := []
| (l::ls) := transpose_aux l (transpose ls)
/-- List of all sections through a list of lists. A section
of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from
`L₁`, whose second element comes from `L₂`, and so on. -/
def sections : list (list α) → list (list α)
| [] := [[]]
| (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l
section permutations
/-- An auxiliary function for defining `permutations`. `permutations_aux2 t ts r ys f` is equal to
`(ys ++ ts, (insert_left ys t ts).map f ++ r)`, where `insert_left ys t ts` (not explicitly
defined) is the list of lists of the form `insert_nth n t (ys ++ ts)` for `0 ≤ n < length ys`.
permutations_aux2 10 [4, 5, 6] [] [1, 2, 3] id =
([1, 2, 3, 4, 5, 6],
[[10, 1, 2, 3, 4, 5, 6],
[1, 10, 2, 3, 4, 5, 6],
[1, 2, 10, 3, 4, 5, 6]]) -/
def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β
| [] f := (ts, r)
| (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in
(y :: us, f (t :: y :: us) :: zs)
private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l)
local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas
/-- A recursor for pairs of lists. To have `C l₁ l₂` for all `l₁`, `l₂`, it suffices to have it for
`l₂ = []` and to be able to pour the elements of `l₁` into `l₂`. -/
@[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v}
(H0 : ∀ is, C [] is)
(H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂
| [] is := H0 is
| (t::ts) is :=
have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from
show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is,
length (t :: ts)),
by rw nat.succ_add; exact prod.lex.right _ (lt_succ_self _),
have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ (nat.lt_add_of_pos_left (succ_pos _)),
H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is [])
using_well_founded
{ dec_tac := tactic.assumption,
rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] }
/-- An auxiliary function for defining `permutations`. `permutations_aux ts is` is the set of all
permutations of `is ++ ts` that do not fix `ts`. -/
def permutations_aux : list α → list α → list (list α) :=
@@permutations_aux.rec (λ _ _, list (list α)) (λ is, [])
(λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2))
/-- List of all permutations of `l`.
permutations [1, 2, 3] =
[[1, 2, 3], [2, 1, 3], [3, 2, 1],
[2, 3, 1], [3, 1, 2], [1, 3, 2]] -/
def permutations (l : list α) : list (list α) :=
l :: permutations_aux l []
/-- `permutations'_aux t ts` inserts `t` into every position in `ts`, including the last.
This function is intended for use in specifications, so it is simpler than `permutations_aux2`,
which plays roughly the same role in `permutations`.
Note that `(permutations_aux2 t [] [] ts id).2` is similar to this function, but skips the last
position:
permutations'_aux 10 [1, 2, 3] =
[[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3], [1, 2, 3, 10]]
(permutations_aux2 10 [] [] [1, 2, 3] id).2 =
[[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3]] -/
@[simp] def permutations'_aux (t : α) : list α → list (list α)
| [] := [[t]]
| (y::ys) := (t :: y :: ys) :: (permutations'_aux ys).map (cons y)
/-- List of all permutations of `l`. This version of `permutations` is less efficient but has
simpler definitional equations. The permutations are in a different order,
but are equal up to permutation, as shown by `list.permutations_perm_permutations'`.
permutations [1, 2, 3] =
[[1, 2, 3], [2, 1, 3], [2, 3, 1],
[1, 3, 2], [3, 1, 2], [3, 2, 1]] -/
@[simp] def permutations' : list α → list (list α)
| [] := [[]]
| (t::ts) := (permutations' ts).bind $ permutations'_aux t
end permutations
/-- `erasep p l` removes the first element of `l` satisfying the predicate `p`. -/
def erasep (p : α → Prop) [decidable_pred p] : list α → list α
| [] := []
| (a::l) := if p a then l else a :: erasep l
/-- `extractp p l` returns a pair of an element `a` of `l` satisfying the predicate
`p`, and `l`, with `a` removed. If there is no such element `a` it returns `(none, l)`. -/
def extractp (p : α → Prop) [decidable_pred p] : list α → option α × list α
| [] := (none, [])
| (a::l) := if p a then (some a, l) else
let (a', l') := extractp l in (a', a :: l')
/-- `revzip l` returns a list of pairs of the elements of `l` paired
with the elements of `l` in reverse order.
`revzip [1,2,3,4,5] = [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]`
-/
def revzip (l : list α) : list (α × α) := zip l l.reverse
/-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`.
product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/
def product (l₁ : list α) (l₂ : list β) : list (α × β) :=
l₁.bind $ λ a, l₂.map $ prod.mk a
/- This notation binds more strongly than (pre)images, unions and intersections. -/
infixr (name := list.product) ` ×ˢ `:82 := list.product
/-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`.
sigma [1, 2] (λ_, [(5 : ℕ), 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/
protected def sigma {σ : α → Type*} (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) :=
l₁.bind $ λ a, (l₂ a).map $ sigma.mk a
/-- Auxliary definition used to define `of_fn`.
`of_fn_aux f m h l` returns the first `m` elements of `of_fn f`
appended to `l` -/
def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α
| 0 h l := l
| (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l)
/-- `of_fn f` with `f : fin n → α` returns the list whose ith element is `f i`
`of_fun f = [f 0, f 1, ... , f(n - 1)]` -/
def of_fn {n} (f : fin n → α) : list α :=
of_fn_aux f n (le_refl _) []
/-- `of_fn_nth_val f i` returns `some (f i)` if `i < n` and `none` otherwise. -/
def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α :=
if h : i < n then some (f ⟨i, h⟩) else none
/-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/
def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false
section pairwise
variables (R : α → α → Prop)
/-- `pairwise R l` means that all the elements with earlier indexes are
`R`-related to all the elements with later indexes.
pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3
For example if `R = (≠)` then it asserts `l` has no duplicates,
and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/
inductive pairwise : list α → Prop
| nil : pairwise []
| cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l)
variables {R}
@[simp] theorem pairwise_cons {a : α} {l : list α} :
pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l :=
⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩
attribute [simp] pairwise.nil
instance decidable_pairwise [decidable_rel R] (l : list α) : decidable (pairwise R l) :=
by induction l with hd tl ih; [exact is_true pairwise.nil,
exactI decidable_of_iff' _ pairwise_cons]
end pairwise
/-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`.
`pw_filter (≠)` is the erase duplicates function (cf. `dedup`), and `pw_filter (<)` finds
a maximal increasing subsequence in `l`. For example,
pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] -/
def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α
| [] := []
| (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH
section chain
variable (R : α → α → Prop)
/-- `chain R a l` means that `R` holds between adjacent elements of `a::l`.
chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d -/
inductive chain : α → list α → Prop
| nil {a : α} : chain a []
| cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l)
/-- `chain' R l` means that `R` holds between adjacent elements of `l`.
chain' R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d -/
def chain' : list α → Prop
| [] := true
| (a :: l) := chain R a l
variable {R}
@[simp] theorem chain_cons {a b : α} {l : list α} :
chain R a (b::l) ↔ R a b ∧ chain R b l :=
⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩
attribute [simp] chain.nil
instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) :=
by induction l generalizing a; simp only [chain.nil, chain_cons]; resetI; apply_instance
instance decidable_chain' [decidable_rel R] (l : list α) : decidable (chain' R l) :=
by cases l; dunfold chain'; apply_instance
end chain
/-- `nodup l` means that `l` has no duplicates, that is, any element appears at most
once in the list. It is defined as `pairwise (≠)`. -/
def nodup : list α → Prop := pairwise (≠)
instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) :=
list.decidable_pairwise
/-- `dedup l` removes duplicates from `l` (taking only the last occurrence).
Defined as `pw_filter (≠)`.
dedup [1, 0, 2, 2, 1] = [0, 2, 1] -/
def dedup [decidable_eq α] : list α → list α := pw_filter (≠)
/-- Greedily create a sublist of `a :: l` such that, for every two adjacent elements `a, b`,
`R a b` holds. Mostly used with ≠; for example, `destutter' (≠) 1 [2, 2, 1, 1] = [1, 2, 1]`,
`destutter' (≠) 1, [2, 3, 3] = [1, 2, 3]`, `destutter' (<) 1 [2, 5, 2, 3, 4, 9] = [1, 2, 5, 9]`. -/
def destutter' (R : α → α → Prop) [decidable_rel R] : α → list α → list α
| a [] := [a]
| a (h :: l) := if R a h then a :: destutter' h l else destutter' a l
/-- Greedily create a sublist of `l` such that, for every two adjacent elements `a, b ∈ l`,
`R a b` holds. Mostly used with ≠; for example, `destutter (≠) [1, 2, 2, 1, 1] = [1, 2, 1]`,
`destutter (≠) [1, 2, 3, 3] = [1, 2, 3]`, `destutter (<) [1, 2, 5, 2, 3, 4, 9] = [1, 2, 5, 9]`. -/
def destutter (R : α → α → Prop) [decidable_rel R] : list α → list α
| (h :: l) := destutter' R h l
| [] := []
/-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`.
It is intended mainly for proving properties of `range` and `iota`. -/
@[simp] def range' : ℕ → ℕ → list ℕ
| s 0 := []
| s (n+1) := s :: range' (s+1) n
/-- Drop `none`s from a list, and replace each remaining `some a` with `a`. -/
def reduce_option {α} : list (option α) → list α :=
list.filter_map id
/-- `ilast' x xs` returns the last element of `xs` if `xs` is non-empty;
it returns `x` otherwise -/
@[simp] def ilast' {α} : α → list α → α
| a [] := a
| a (b::l) := ilast' b l
/-- `last' xs` returns the last element of `xs` if `xs` is non-empty;
it returns `none` otherwise -/
@[simp] def last' {α} : list α → option α
| [] := none
| [a] := some a
| (b::l) := last' l
/-- `rotate l n` rotates the elements of `l` to the left by `n`
rotate [0, 1, 2, 3, 4, 5] 2 = [2, 3, 4, 5, 0, 1] -/
def rotate (l : list α) (n : ℕ) : list α :=
let (l₁, l₂) := list.split_at (n % l.length) l in l₂ ++ l₁
/-- rotate' is the same as `rotate`, but slower. Used for proofs about `rotate`-/
def rotate' : list α → ℕ → list α
| [] n := []
| l 0 := l
| (a::l) (n+1) := rotate' (l ++ [a]) n
section choose
variables (p : α → Prop) [decidable_pred p] (l : list α)
/-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`,
choose the first element with this property. This version returns both `a` and proofs
of `a ∈ l` and `p a`. -/
def choose_x : Π l : list α, Π hp : (∃ a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a }
| [] hp := false.elim (exists.elim hp (assume a h, not_mem_nil a h.left))
| (l :: ls) hp := if pl : p l then ⟨l, ⟨or.inl rfl, pl⟩⟩ else
let ⟨a, ⟨a_mem_ls, pa⟩⟩ := choose_x ls (hp.imp
(λ b ⟨o, h₂⟩, ⟨o.resolve_left (λ e, pl $ e ▸ h₂), h₂⟩)) in
⟨a, ⟨or.inr a_mem_ls, pa⟩⟩
/-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`,
choose the first element with this property. This version returns `a : α`, and properties
are given by `choose_mem` and `choose_property`. -/
def choose (hp : ∃ a, a ∈ l ∧ p a) : α := choose_x p l hp
end choose
/-- Filters and maps elements of a list -/
def mmap_filter {m : Type → Type v} [monad m] {α β} (f : α → m (option β)) :
list α → m (list β)
| [] := return []
| (h :: t) := do b ← f h, t' ← t.mmap_filter, return $
match b with none := t' | (some x) := x::t' end
/--
`mmap_upper_triangle f l` calls `f` on all elements in the upper triangular part of `l × l`.
That is, for each `e ∈ l`, it will run `f e e` and then `f e e'`
for each `e'` that appears after `e` in `l`.
Example: suppose `l = [1, 2, 3]`. `mmap_upper_triangle f l` will produce the list
`[f 1 1, f 1 2, f 1 3, f 2 2, f 2 3, f 3 3]`.
-/
def mmap_upper_triangle {m} [monad m] {α β : Type u} (f : α → α → m β) : list α → m (list β)
| [] := return []
| (h::t) := do v ← f h h, l ← t.mmap (f h), t ← t.mmap_upper_triangle, return $ (v::l) ++ t
/--
`mmap'_diag f l` calls `f` on all elements in the upper triangular part of `l × l`.
That is, for each `e ∈ l`, it will run `f e e` and then `f e e'`
for each `e'` that appears after `e` in `l`.
Example: suppose `l = [1, 2, 3]`. `mmap'_diag f l` will evaluate, in this order,
`f 1 1`, `f 1 2`, `f 1 3`, `f 2 2`, `f 2 3`, `f 3 3`.
-/
def mmap'_diag {m} [monad m] {α} (f : α → α → m unit) : list α → m unit
| [] := return ()
| (h::t) := f h h >> t.mmap' (f h) >> t.mmap'_diag
protected def traverse {F : Type u → Type v} [applicative F] {α β : Type*} (f : α → F β) :
list α → F (list β)
| [] := pure []
| (x :: xs) := list.cons <$> f x <*> traverse xs
/-- `get_rest l l₁` returns `some l₂` if `l = l₁ ++ l₂`.
If `l₁` is not a prefix of `l`, returns `none` -/
def get_rest [decidable_eq α] : list α → list α → option (list α)
| l [] := some l
| [] _ := none
| (x::l) (y::l₁) := if x = y then get_rest l l₁ else none
/--
`list.slice n m xs` removes a slice of length `m` at index `n` in list `xs`.
-/
def slice {α} : ℕ → ℕ → list α → list α
| 0 n xs := xs.drop n
| (succ n) m [] := []
| (succ n) m (x :: xs) := x :: slice n m xs
/--
Left-biased version of `list.map₂`. `map₂_left' f as bs` applies `f` to each
pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is
applied to `none` for the remaining `aᵢ`. Returns the results of the `f`
applications and the remaining `bs`.
```
map₂_left' prod.mk [1, 2] ['a'] = ([(1, some 'a'), (2, none)], [])
map₂_left' prod.mk [1] ['a', 'b'] = ([(1, some 'a')], ['b'])
```
-/
@[simp] def map₂_left' (f : α → option β → γ) : list α → list β → (list γ × list β)
| [] bs := ([], bs)
| (a :: as) [] :=
((a :: as).map (λ a, f a none), [])
| (a :: as) (b :: bs) :=
let rec := map₂_left' as bs in
(f a (some b) :: rec.fst, rec.snd)
/--
Right-biased version of `list.map₂`. `map₂_right' f as bs` applies `f` to each
pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is
applied to `none` for the remaining `bᵢ`. Returns the results of the `f`
applications and the remaining `as`.
```
map₂_right' prod.mk [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], [])
map₂_right' prod.mk [1, 2] ['a'] = ([(some 1, 'a')], [2])
```
-/
def map₂_right' (f : option α → β → γ) (as : list α) (bs : list β) : (list γ × list α) :=
map₂_left' (flip f) bs as
/--
Left-biased version of `list.zip`. `zip_left' as bs` returns the list of
pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the
remaining `aᵢ` are paired with `none`. Also returns the remaining `bs`.
```
zip_left' [1, 2] ['a'] = ([(1, some 'a'), (2, none)], [])
zip_left' [1] ['a', 'b'] = ([(1, some 'a')], ['b'])
zip_left' = map₂_left' prod.mk
```
-/
def zip_left' : list α → list β → list (α × option β) × list β :=
map₂_left' prod.mk
/--
Right-biased version of `list.zip`. `zip_right' as bs` returns the list of
pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the
remaining `bᵢ` are paired with `none`. Also returns the remaining `as`.
```
zip_right' [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], [])
zip_right' [1, 2] ['a'] = ([(some 1, 'a')], [2])
zip_right' = map₂_right' prod.mk
```
-/
def zip_right' : list α → list β → list (option α × β) × list α :=
map₂_right' prod.mk
/--
Left-biased version of `list.map₂`. `map₂_left f as bs` applies `f` to each pair
`aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none`
for the remaining `aᵢ`.
```
map₂_left prod.mk [1, 2] ['a'] = [(1, some 'a'), (2, none)]
map₂_left prod.mk [1] ['a', 'b'] = [(1, some 'a')]
map₂_left f as bs = (map₂_left' f as bs).fst
```
-/
@[simp] def map₂_left (f : α → option β → γ) : list α → list β → list γ
| [] _ := []
| (a :: as) [] := (a :: as).map (λ a, f a none)
| (a :: as) (b :: bs) := f a (some b) :: map₂_left as bs
/--
Right-biased version of `list.map₂`. `map₂_right f as bs` applies `f` to each
pair `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is applied to
`none` for the remaining `bᵢ`.
```
map₂_right prod.mk [1, 2] ['a'] = [(some 1, 'a')]
map₂_right prod.mk [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')]
map₂_right f as bs = (map₂_right' f as bs).fst
```
-/
def map₂_right (f : option α → β → γ) (as : list α) (bs : list β) :
list γ :=
map₂_left (flip f) bs as
/--
Left-biased version of `list.zip`. `zip_left as bs` returns the list of pairs
`(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the
remaining `aᵢ` are paired with `none`.
```
zip_left [1, 2] ['a'] = [(1, some 'a'), (2, none)]
zip_left [1] ['a', 'b'] = [(1, some 'a')]
zip_left = map₂_left prod.mk
```
-/
def zip_left : list α → list β → list (α × option β) :=
map₂_left prod.mk
/--
Right-biased version of `list.zip`. `zip_right as bs` returns the list of pairs
`(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the
remaining `bᵢ` are paired with `none`.
```
zip_right [1, 2] ['a'] = [(some 1, 'a')]
zip_right [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')]
zip_right = map₂_right prod.mk
```
-/
def zip_right : list α → list β → list (option α × β) :=
map₂_right prod.mk
/--
If all elements of `xs` are `some xᵢ`, `all_some xs` returns the `xᵢ`. Otherwise
it returns `none`.
```
all_some [some 1, some 2] = some [1, 2]
all_some [some 1, none ] = none
```
-/
def all_some : list (option α) → option (list α)
| [] := some []
| (some a :: as) := cons a <$> all_some as
| (none :: as) := none
/--
`fill_nones xs ys` replaces the `none`s in `xs` with elements of `ys`. If there
are not enough `ys` to replace all the `none`s, the remaining `none`s are
dropped from `xs`.
```
fill_nones [none, some 1, none, none] [2, 3] = [2, 1, 3]
```
-/
def fill_nones {α} : list (option α) → list α → list α
| [] _ := []
| (some a :: as) as' := a :: fill_nones as as'
| (none :: as) [] := as.reduce_option
| (none :: as) (a :: as') := a :: fill_nones as as'
/--
`take_list as ns` extracts successive sublists from `as`. For `ns = n₁ ... nₘ`,
it first takes the `n₁` initial elements from `as`, then the next `n₂` ones,
etc. It returns the sublists of `as` -- one for each `nᵢ` -- and the remaining
elements of `as`. If `as` does not have at least as many elements as the sum of
the `nᵢ`, the corresponding sublists will have less than `nᵢ` elements.
```
take_list ['a', 'b', 'c', 'd', 'e'] [2, 1, 1] = ([['a', 'b'], ['c'], ['d']], ['e'])
take_list ['a', 'b'] [3, 1] = ([['a', 'b'], []], [])
```
-/
def take_list {α} : list α → list ℕ → list (list α) × list α
| xs [] := ([], xs)
| xs (n :: ns) :=
let ⟨xs₁, xs₂⟩ := xs.split_at n in
let ⟨xss, rest⟩ := take_list xs₂ ns in
(xs₁ :: xss, rest)
/--
`to_rbmap as` is the map that associates each index `i` of `as` with the
corresponding element of `as`.
```
to_rbmap ['a', 'b', 'c'] = rbmap_of [(0, 'a'), (1, 'b'), (2, 'c')]
```
-/
def to_rbmap {α : Type*} : list α → rbmap ℕ α :=
foldl_with_index (λ i mapp a, mapp.insert i a) (mk_rbmap ℕ α)
/-- Auxliary definition used to define `to_chunks`.
`to_chunks_aux n xs i` returns `(xs.take i, (xs.drop i).to_chunks (n+1))`,
that is, the first `i` elements of `xs`, and the remaining elements chunked into
sublists of length `n+1`. -/
def to_chunks_aux {α} (n : ℕ) : list α → ℕ → list α × list (list α)
| [] i := ([], [])
| (x::xs) 0 := let (l, L) := to_chunks_aux xs n in ([], (x::l)::L)
| (x::xs) (i+1) := let (l, L) := to_chunks_aux xs i in (x::l, L)
/--
`xs.to_chunks n` splits the list into sublists of size at most `n`,
such that `(xs.to_chunks n).join = xs`.
```
[1, 2, 3, 4, 5, 6, 7, 8].to_chunks 10 = [[1, 2, 3, 4, 5, 6, 7, 8]]
[1, 2, 3, 4, 5, 6, 7, 8].to_chunks 3 = [[1, 2, 3], [4, 5, 6], [7, 8]]
[1, 2, 3, 4, 5, 6, 7, 8].to_chunks 2 = [[1, 2], [3, 4], [5, 6], [7, 8]]
[1, 2, 3, 4, 5, 6, 7, 8].to_chunks 0 = [[1, 2, 3, 4, 5, 6, 7, 8]]
```
-/
def to_chunks {α} : ℕ → list α → list (list α)
| _ [] := []
| 0 xs := [xs]
| (n+1) (x::xs) := let (l, L) := to_chunks_aux n xs n in (x::l)::L
/--
Asynchronous version of `list.map`.
-/
meta def map_async_chunked {α β} (f : α → β) (xs : list α) (chunk_size := 1024) : list β :=
((xs.to_chunks chunk_size).map (λ xs, task.delay (λ _, list.map f xs))).bind task.get
/-!
We add some n-ary versions of `list.zip_with` for functions with more than two arguments.
These can also be written in terms of `list.zip` or `list.zip_with`.
For example, `zip_with3 f xs ys zs` could also be written as
`zip_with id (zip_with f xs ys) zs`
or as
`(zip xs $ zip ys zs).map $ λ ⟨x, y, z⟩, f x y z`.
-/
/-- Ternary version of `list.zip_with`. -/
def zip_with3 (f : α → β → γ → δ) : list α → list β → list γ → list δ
| (x::xs) (y::ys) (z::zs) := f x y z :: zip_with3 xs ys zs
| _ _ _ := []
/-- Quaternary version of `list.zip_with`. -/
def zip_with4 (f : α → β → γ → δ → ε) : list α → list β → list γ → list δ → list ε
| (x::xs) (y::ys) (z::zs) (u::us) := f x y z u :: zip_with4 xs ys zs us
| _ _ _ _ := []
/-- Quinary version of `list.zip_with`. -/
def zip_with5 (f : α → β → γ → δ → ε → ζ) : list α → list β → list γ → list δ → list ε → list ζ
| (x::xs) (y::ys) (z::zs) (u::us) (v::vs) := f x y z u v :: zip_with5 xs ys zs us vs
| _ _ _ _ _ := []
/-- Given a starting list `old`, a list of booleans and a replacement list `new`,
read the items in `old` in succession and either replace them with the next element of `new` or
not, according as to whether the corresponding boolean is `tt` or `ff`. -/
def replace_if : list α → list bool → list α → list α
| l _ [] := l
| [] _ _ := []
| l [] _ := l
| (n::ns) (tf::bs) e@(c::cs) := if tf then c :: ns.replace_if bs cs else n :: ns.replace_if bs e
/-- An auxiliary function for `list.map_with_prefix_suffix`. -/
def map_with_prefix_suffix_aux {α β} (f : list α → α → list α → β) : list α → list α → list β
| prev [] := []
| prev (h::t) := f prev h t :: map_with_prefix_suffix_aux (prev.concat h) t
/--
`list.map_with_prefix_suffix f l` maps `f` across a list `l`.
For each `a ∈ l` with `l = pref ++ [a] ++ suff`, `a` is mapped to `f pref a suff`.
Example: if `f : list ℕ → ℕ → list ℕ → β`,
`list.map_with_prefix_suffix f [1, 2, 3]` will produce the list
`[f [] 1 [2, 3], f [1] 2 [3], f [1, 2] 3 []]`.
-/
def map_with_prefix_suffix {α β} (f : list α → α → list α → β) (l : list α) : list β :=
map_with_prefix_suffix_aux f [] l
/--
`list.map_with_complement f l` is a variant of `list.map_with_prefix_suffix`
that maps `f` across a list `l`.
For each `a ∈ l` with `l = pref ++ [a] ++ suff`, `a` is mapped to `f a (pref ++ suff)`,
i.e., the list input to `f` is `l` with `a` removed.
Example: if `f : ℕ → list ℕ → β`, `list.map_with_complement f [1, 2, 3]` will produce the list
`[f 1 [2, 3], f 2 [1, 3], f 3 [1, 2]]`.
-/
def map_with_complement {α β} (f : α → list α → β) : list α → list β :=
map_with_prefix_suffix $ λ pref a suff, f a (pref ++ suff)
end list
|
656d844099f3de1ca17203f22fa7147fd2d3c07a | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /tests/lean/run/meta2.lean | 7275f7648230fbbff2b9e61c8886400ff42607c8 | [
"Apache-2.0"
] | permissive | williamdemeo/lean4 | 72161c58fe65c3ad955d6a3050bb7d37c04c0d54 | 6d00fcf1d6d873e195f9220c668ef9c58e9c4a35 | refs/heads/master | 1,678,305,356,877 | 1,614,708,995,000 | 1,614,708,995,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,270 | lean | import Lean.Meta
open Lean
open Lean.Meta
-- set_option trace.Meta true
--set_option trace.Meta.isDefEq.step false
-- set_option trace.Meta.isDefEq.delta false
set_option trace.Meta.debug true
def print (msg : MessageData) : MetaM Unit :=
trace! `Meta.debug msg
def checkM (x : MetaM Bool) : MetaM Unit :=
unless (← x) do throwError "check failed"
def getAssignment (m : Expr) : MetaM Expr :=
do let v? ← getExprMVarAssignment? m.mvarId!;
(match v? with
| some v => pure v
| none => throwError "metavariable is not assigned")
def nat := mkConst `Nat
def boolE := mkConst `Bool
def succ := mkConst `Nat.succ
def zero := mkConst `Nat.zero
def add := mkConst `Nat.add
def io := mkConst `IO
def type := mkSort levelOne
def boolFalse := mkConst `Bool.false
def boolTrue := mkConst `Bool.true
def tst1 : MetaM Unit :=
do print "----- tst1 -----";
let mvar <- mkFreshExprMVar nat;
checkM $ isExprDefEq mvar (mkNatLit 10);
checkM $ isExprDefEq mvar (mkNatLit 10);
pure ()
#eval tst1
def tst2 : MetaM Unit :=
do print "----- tst2 -----";
let mvar <- mkFreshExprMVar nat;
checkM $ isExprDefEq (mkApp succ mvar) (mkApp succ (mkNatLit 10));
checkM $ isExprDefEq mvar (mkNatLit 10);
pure ()
#eval tst2
def tst3 : MetaM Unit :=
do print "----- tst3 -----";
let t := mkLambda `x BinderInfo.default nat $ mkBVar 0;
let mvar ← mkFreshExprMVar (mkForall `x BinderInfo.default nat nat);
lambdaTelescope t fun xs _ => do
let x := xs[0];
checkM $ isExprDefEq (mkApp mvar x) (mkAppN add #[x, mkAppN add #[mkNatLit 10, x]]);
pure ();
let v ← getAssignment mvar;
print v;
pure ()
#eval tst3
def tst4 : MetaM Unit :=
do print "----- tst4 -----";
let t := mkLambda `x BinderInfo.default nat $ mkBVar 0;
lambdaTelescope t fun xs _ => do
let x := xs[0];
let mvar ← mkFreshExprMVar (mkForall `x BinderInfo.default nat nat);
-- the following `isExprDefEq` fails because `x` is also in the context of `mvar`
checkM $ not <$> isExprDefEq (mkApp mvar x) (mkAppN add #[x, mkAppN add #[mkNatLit 10, x]]);
checkM $ approxDefEq $ isExprDefEq (mkApp mvar x) (mkAppN add #[x, mkAppN add #[mkNatLit 10, x]]);
let v ← getAssignment mvar;
print v;
pure ();
pure ()
#eval tst4
def mkAppC (c : Name) (xs : Array Expr) : MetaM Expr :=
do let r ← mkAppM c xs;
check r;
pure r
def mkProd (a b : Expr) : MetaM Expr := mkAppC `Prod #[a, b]
def mkPair (a b : Expr) : MetaM Expr := mkAppC `Prod.mk #[a, b]
def mkFst (s : Expr) : MetaM Expr := mkAppC `Prod.fst #[s]
def mkSnd (s : Expr) : MetaM Expr := mkAppC `Prod.snd #[s]
def tst5 : MetaM Unit :=
do print "----- tst5 -----";
let p₁ ← mkPair (mkNatLit 1) (mkNatLit 2);
let x ← mkFst p₁;
print x;
let v ← whnf x;
print v;
let v ← withTransparency TransparencyMode.reducible $ whnf x;
print v;
let x ← mkId x;
print x;
let prod ← mkProd nat nat;
let m ← mkFreshExprMVar prod;
let y ← mkFst m;
checkM $ isExprDefEq y x;
print y;
let x ← mkProjection p₁ `fst;
print x;
let y ← mkProjection p₁ `snd;
print y
#eval tst5
def tst6 : MetaM Unit :=
do print "----- tst6 -----";
withLocalDeclD `x nat $ fun x => do
let m ← mkFreshExprMVar nat;
let t := mkAppN add #[m, mkNatLit 4];
let s := mkAppN add #[x, mkNatLit 3];
checkM $ not <$> isExprDefEq t s;
let s := mkAppN add #[x, mkNatLit 6];
checkM $ isExprDefEq t s;
let v ← getAssignment m;
checkM $ pure $ v == mkAppN add #[x, mkNatLit 2];
print v;
let m ← mkFreshExprMVar nat;
let t := mkAppN add #[m, mkNatLit 4];
let s := mkNatLit 3;
checkM $ not <$> isExprDefEq t s;
let s := mkNatLit 10;
checkM $ isExprDefEq t s;
let v ← getAssignment m;
checkM $ pure $ v == mkNatLit 6;
print v;
pure ()
#eval tst6
def tst7 : MetaM Unit :=
do print "----- tst7 -----";
withLocalDeclD `x type $ fun x => do
let m1 ← mkFreshExprMVar (← mkArrow type type);
let m2 ← mkFreshExprMVar type;
let t := mkApp io x;
-- we need to use foApprox to solve `?m1 ?m2 =?= IO x`
checkM $ not <$> isDefEq (mkApp m1 m2) t;
checkM $ approxDefEq $ isDefEq (mkApp m1 m2) t;
let v ← getAssignment m1;
checkM $ pure $ v == io;
let v ← getAssignment m2;
checkM $ pure $ v == x;
pure ()
#eval tst7
def tst9 : MetaM Unit :=
do print "----- tst9 -----";
let env ← getEnv;
print (toString (← isReducible `Prod.fst))
print (toString (← isReducible `Add.add))
pure ()
#eval tst9
def tst10 : MetaM Unit :=
do print "----- tst10 -----";
let t ← withLocalDeclD `x nat $ fun x => do {
let b := mkAppN add #[x, mkAppN add #[mkNatLit 2, mkNatLit 3]];
mkLambdaFVars #[x] b
};
print t;
let t ← reduce t;
print t;
pure ()
#eval tst10
def tst11 : MetaM Unit :=
do print "----- tst11 -----";
checkM $ isType nat;
checkM $ isType (← mkArrow nat nat);
checkM $ not <$> isType add;
checkM $ not <$> isType (mkNatLit 1);
withLocalDeclD `x nat fun x => do
checkM $ not <$> isType x;
checkM $ not <$> (mkLambdaFVars #[x] x >>= isType);
checkM $ not <$> (mkLambdaFVars #[x] nat >>= isType);
let t ← mkEq x (mkNatLit 0);
let t ← mkForallFVars #[x] t (usedOnly := true);
print t;
checkM $ isType t;
pure ();
pure ()
#eval tst11
def tst12 : MetaM Unit :=
do print "----- tst12 -----";
withLocalDeclD `x nat $ fun x => do
let t ← mkEqRefl x >>= mkLambdaFVars #[x];
print t;
let type ← inferType t;
print type;
isProofQuick t >>= fun b => print (toString b);
isProofQuick nat >>= fun b => print (toString b);
isProofQuick type >>= fun b => print (toString b);
pure ();
pure ()
#eval tst12
def tst13 : MetaM Unit :=
do print "----- tst13 -----";
let m₁ ← mkFreshExprMVar (← mkArrow type type);
let m₂ ← mkFreshExprMVar (mkApp m₁ nat);
let t ← mkId m₂;
print t;
let r ← abstractMVars t;
print r.expr;
let (_, _, e) ← openAbstractMVarsResult r;
print e;
pure ()
def mkDecEq (type : Expr) : MetaM Expr := mkAppC `DecidableEq #[type]
def mkStateM (σ : Expr) : MetaM Expr := mkAppC `StateM #[σ]
def mkMonad (m : Expr) : MetaM Expr := mkAppC `Monad #[m]
def mkMonadState (σ m : Expr) : MetaM Expr := mkAppC `MonadState #[σ, m]
def mkAdd (a : Expr) : MetaM Expr := mkAppC `Add #[a]
def mkToString (a : Expr) : MetaM Expr := mkAppC `ToString #[a]
def tst14 : MetaM Unit :=
do print "----- tst14 -----";
let stateM ← mkStateM nat;
print stateM;
let monad ← mkMonad stateM;
let globalInsts ← getGlobalInstancesIndex;
let insts ← globalInsts.getUnify monad;
print (insts.map (·.val));
pure ()
#eval tst14
def tst15 : MetaM Unit :=
do print "----- tst15 -----";
let inst ← _root_.mkAdd nat;
let r ← synthInstance inst;
print r;
pure ()
#eval tst15
def tst16 : MetaM Unit :=
do print "----- tst16 -----";
let prod ← mkProd nat nat;
let inst ← mkToString prod;
print inst;
let r ← synthInstance inst;
print r;
pure ()
#eval tst16
def tst17 : MetaM Unit :=
do print "----- tst17 -----";
let prod ← mkProd nat nat;
let prod ← mkProd boolE prod;
let inst ← mkToString prod;
print inst;
let r ← synthInstance inst;
print r;
pure ()
#eval tst17
def tst18 : MetaM Unit :=
do print "----- tst18 -----";
let decEqNat ← mkDecEq nat;
let r ← synthInstance decEqNat;
print r;
pure ()
#eval tst18
def tst19 : MetaM Unit :=
do print "----- tst19 -----";
let stateM ← mkStateM nat;
print stateM;
let monad ← mkMonad stateM;
print monad;
let r ← synthInstance monad;
print r;
pure ()
#eval tst19
def tst20 : MetaM Unit :=
do print "----- tst20 -----";
let stateM ← mkStateM nat;
print stateM;
let monadState ← mkMonadState nat stateM;
print monadState;
let r ← synthInstance monadState;
print r;
pure ()
#eval tst20
def tst21 : MetaM Unit :=
do print "----- tst21 -----";
withLocalDeclD `x nat $ fun x => do
withLocalDeclD `y nat $ fun y => do
withLocalDeclD `z nat $ fun z => do
let eq₁ ← mkEq x y;
let eq₂ ← mkEq y z;
withLocalDeclD `h₁ eq₁ $ fun h₁ => do
withLocalDeclD `h₂ eq₂ $ fun h₂ => do
let h ← mkEqTrans h₁ h₂;
let h ← mkEqSymm h;
let h ← mkCongrArg succ h;
let h₂ ← mkEqRefl succ;
let h ← mkCongr h₂ h;
let t ← inferType h;
check h;
print h;
print t;
let h ← mkCongrFun h₂ x;
let t ← inferType h;
check h;
print t;
pure ()
#eval tst21
def tst22 : MetaM Unit :=
do print "----- tst22 -----";
withLocalDeclD `x nat $ fun x => do
withLocalDeclD `y nat $ fun y => do
let t ← mkAppC `Add.add #[x, y];
print t;
let t ← mkAppC `Add.add #[y, x];
print t;
let t ← mkAppC `ToString.toString #[x];
print t;
pure ()
#eval tst22
def test1 : Nat := (fun x y => x + y) 0 1
def tst23 : MetaM Unit :=
do print "----- tst23 -----";
let cinfo ← getConstInfo `test1;
let v := cinfo.value?.get!;
print v;
print v.headBeta
#eval tst23
def tst26 : MetaM Unit := do
print "----- tst26 -----";
let m1 ← mkFreshExprMVar (← mkArrow nat nat);
let m2 ← mkFreshExprMVar nat;
let m3 ← mkFreshExprMVar nat;
checkM $ approxDefEq $ isDefEq (mkApp m1 m2) m3;
checkM $ do { let b ← isExprMVarAssigned $ m1.mvarId!; pure (!b) };
checkM $ isExprMVarAssigned $ m3.mvarId!;
pure ()
#eval tst26
section
set_option trace.Meta.isDefEq.step true
set_option trace.Meta.isDefEq.delta true
set_option trace.Meta.isDefEq.assign true
def tst27 : MetaM Unit := do
print "----- tst27 -----";
let m ← mkFreshExprMVar nat;
checkM $ isDefEq (mkNatLit 1) (mkApp (mkConst `Nat.succ) m);
pure ()
#eval tst27
end
def tst28 : MetaM Unit := do
print "----- tst28 -----";
withLocalDeclD `x nat $ fun x =>
withLocalDeclD `y nat $ fun y =>
withLocalDeclD `z nat $ fun z => do
let t1 ← mkAppM `Add.add #[x, y];
let t1 ← mkAppM `Add.add #[x, t1];
let t1 ← mkAppM `Add.add #[t1, t1];
let t2 ← mkAppM `Add.add #[z, y];
let t3 ← mkAppM `Eq #[t2, t1];
let t3 ← mkForallFVars #[z] t3;
let m ← mkFreshExprMVar nat;
let p ← mkAppM `Add.add #[x, m];
print t3;
let r ← kabstract t3 p;
print r;
let p ← mkAppM `Add.add #[x, y];
let r ← kabstract t3 p;
print r;
pure ()
#eval tst28
def norm : Level → Level := @Lean.Level.normalize
def tst29 : MetaM Unit := do
print "----- tst29 -----";
let u := mkLevelParam `u;
let v := mkLevelParam `v;
let u1 := mkLevelSucc u;
let m := mkLevelMax levelOne u1;
print (norm m);
checkM $ pure $ norm m == u1;
let m := mkLevelMax u1 levelOne;
print (norm m);
checkM $ pure $ norm m == u1;
let m := mkLevelMax (mkLevelMax levelOne (mkLevelSucc u1)) (mkLevelSucc levelOne);
checkM $ pure $ norm m == mkLevelSucc u1;
print m;
print (norm m);
let m := mkLevelMax (mkLevelMax (mkLevelSucc (mkLevelSucc u1)) (mkLevelSucc u1)) (mkLevelSucc levelOne);
print m;
print (norm m);
checkM $ pure $ norm m == mkLevelSucc (mkLevelSucc u1);
let m := mkLevelMax (mkLevelMax (mkLevelSucc v) (mkLevelSucc u1)) (mkLevelSucc levelOne);
print m;
print (norm m);
pure ()
#eval tst29
def tst30 : MetaM Unit := do
print "----- tst30 -----";
let m1 ← mkFreshExprMVar nat;
let m2 ← mkFreshExprMVar (← mkArrow nat nat);
withLocalDeclD `x nat $ fun x => do
let t := mkApp succ $ mkApp m2 x;
print t;
checkM $ approxDefEq $ isDefEq m1 t;
let r ← instantiateMVars m1;
print r;
let r ← instantiateMVars m2;
print r;
pure ()
#eval tst30
def tst31 : MetaM Unit := do
print "----- tst31 -----";
let m ← mkFreshExprMVar nat;
let t := mkLet `x nat zero m;
print t;
checkM $ isDefEq t m;
pure ()
def tst32 : MetaM Unit := do
print "----- tst32 -----";
withLocalDeclD `a nat $ fun a => do
withLocalDeclD `b nat $ fun b => do
let aeqb ← mkEq a b;
withLocalDeclD `h2 aeqb $ fun h2 => do
let t ← mkEq (mkApp2 add a a) a;
print t;
let motive := mkLambda `x BinderInfo.default nat (mkApp3 (mkConst `Eq [levelOne]) nat (mkApp2 add a (mkBVar 0)) a);
withLocalDeclD `h1 t $ fun h1 => do
let r ← mkEqNDRec motive h1 h2;
print r;
let rType ← inferType r >>= whnf;
print rType;
check r;
pure ()
#eval tst32
def tst33 : MetaM Unit := do
print "----- tst33 -----";
withLocalDeclD `a nat $ fun a => do
withLocalDeclD `b nat $ fun b => do
let aeqb ← mkEq a b;
withLocalDeclD `h2 aeqb $ fun h2 => do
let t ← mkEq (mkApp2 add a a) a;
let motive :=
mkLambda `x BinderInfo.default nat $
mkLambda `h BinderInfo.default (mkApp3 (mkConst `Eq [levelOne]) nat a (mkBVar 0)) $
(mkApp3 (mkConst `Eq [levelOne]) nat (mkApp2 add a (mkBVar 1)) a);
withLocalDeclD `h1 t $ fun h1 => do
let r ← mkEqRec motive h1 h2;
print r;
let rType ← inferType r >>= whnf;
print rType;
check r;
pure ()
#eval tst33
def tst34 : MetaM Unit := do
print "----- tst34 -----";
let type := mkSort levelOne;
withLocalDeclD `α type $ fun α => do
let m ← mkFreshExprMVar type;
let t ← mkLambdaFVars #[α] (← mkArrow m m);
print t;
pure ()
#eval tst34
def tst35 : MetaM Unit := do
print "----- tst35 -----";
let type := mkSort levelOne;
withLocalDeclD `α type $ fun α => do
let m1 ← mkFreshExprMVar type;
let m2 ← mkFreshExprMVar (← mkArrow nat type);
let v := mkLambda `x BinderInfo.default nat m1;
assignExprMVar m2.mvarId! v;
let w := mkApp m2 zero;
let t1 ← mkLambdaFVars #[α] (← mkArrow w w);
print t1;
let m3 ← mkFreshExprMVar type;
let t2 ← mkLambdaFVars #[α] (← mkArrow (mkBVar 0) (mkBVar 1));
print t2;
checkM $ isDefEq t1 t2;
pure ()
#eval tst35
#check @Id
def tst36 : MetaM Unit := do
print "----- tst36 -----";
let type := mkSort levelOne;
let m1 ← mkFreshExprMVar (← mkArrow type type);
withLocalDeclD `α type $ fun α => do
let m2 ← mkFreshExprMVar type;
let t ← mkAppM `Id #[m2];
checkM $ approxDefEq $ isDefEq (mkApp m1 α) t;
checkM $ approxDefEq $ isDefEq m1 (mkConst `Id [levelZero]);
pure ()
#eval tst36
def tst37 : MetaM Unit := do
print "----- tst37 -----";
let m1 ← mkFreshExprMVar (←mkArrow nat (←mkArrow type type));
let m2 ← mkFreshExprMVar (←mkArrow nat type);
withLocalDeclD `v nat $ fun v => do
let lhs := mkApp2 m1 v (mkApp m2 v);
let rhs ← mkAppM `StateM #[nat, nat];
print lhs;
print rhs;
checkM $ approxDefEq $ isDefEq lhs rhs;
pure ()
#eval tst37
def tst38 : MetaM Unit := do
print "----- tst38 -----";
let m1 ← mkFreshExprMVar nat;
withLocalDeclD `x nat $ fun x => do
let m2 ← mkFreshExprMVar type;
withLocalDeclD `y m2 $ fun y => do
let m3 ← mkFreshExprMVar (←mkArrow m2 nat);
let rhs := mkApp m3 y;
checkM $ approxDefEq $ isDefEq m2 nat;
print m2;
checkM $ getAssignment m2 >>= fun v => pure $ v == nat;
checkM $ approxDefEq $ isDefEq m1 rhs;
print m2;
checkM $ getAssignment m2 >>= fun v => pure $ v == nat;
pure ()
set_option pp.all true
set_option trace.Meta.isDefEq.step true
set_option trace.Meta.isDefEq.delta true
set_option trace.Meta.isDefEq.assign true
#eval tst38
def tst39 : MetaM Unit := do
print "----- tst39 -----";
withLocalDeclD `α type $ fun α =>
withLocalDeclD `β type $ fun β => do
let p ← mkProd α β;
let t ← mkForallFVars #[α, β] p;
print t;
let e ← instantiateForall t #[nat, boolE];
print e;
pure ()
#eval tst39
def tst40 : MetaM Unit := do
print "----- tst40 -----";
withLocalDeclD `α type $ fun α =>
withLocalDeclD `β type $ fun β =>
withLocalDeclD `a α $ fun a =>
withLocalDeclD `b β $ fun b =>
do
let p ← mkProd α β;
let t1 ← mkForallFVars #[α, β] p;
let t2 ← mkForallFVars #[α, β, a, b] p;
print t1;
print $ toString $ t1.bindingBody!.hasLooseBVarInExplicitDomain 0 false;
print $ toString $ t1.bindingBody!.hasLooseBVarInExplicitDomain 0 true;
print $ toString $ t2.bindingBody!.hasLooseBVarInExplicitDomain 0 false;
print $ t1.inferImplicit 2 false;
checkM $ pure $ ((t1.inferImplicit 2 false).bindingInfo! == BinderInfo.default);
checkM $ pure $ ((t1.inferImplicit 2 false).bindingBody!.bindingInfo! == BinderInfo.default);
print $ t1.inferImplicit 2 true;
checkM $ pure $ ((t1.inferImplicit 2 true).bindingInfo! == BinderInfo.implicit);
checkM $ pure $ ((t1.inferImplicit 2 true).bindingBody!.bindingInfo! == BinderInfo.implicit);
print t2;
print $ t2.inferImplicit 2 false;
checkM $ pure $ ((t2.inferImplicit 2 false).bindingInfo! == BinderInfo.implicit);
checkM $ pure $ ((t2.inferImplicit 2 false).bindingBody!.bindingInfo! == BinderInfo.implicit);
print $ t2.inferImplicit 1 false;
checkM $ pure $ ((t2.inferImplicit 1 false).bindingInfo! == BinderInfo.implicit);
checkM $ pure $ ((t2.inferImplicit 1 false).bindingBody!.bindingInfo! == BinderInfo.default);
pure ()
#eval tst40
universes u
structure A (α : Type u) :=
(x y : α)
structure B (α : Type u) :=
(z : α)
structure C (α : Type u) extends A α, B α :=
(w : Bool)
def mkA (x y : Expr) : MetaM Expr := mkAppC `A.mk #[x, y]
def mkB (z : Expr) : MetaM Expr := mkAppC `B.mk #[z]
def mkC (x y z w : Expr) : MetaM Expr := do
let a ← mkA x y;
let b ← mkB z;
mkAppC `C.mk #[a, b, w]
def tst41 : MetaM Unit := do
print "----- tst41 -----";
let c ← mkC (mkNatLit 1) (mkNatLit 2) (mkNatLit 3) boolTrue;
print c;
let x ← mkProjection c `x;
check x;
print x;
let y ← mkProjection c `y;
check y;
print y;
let z ← mkProjection c `z;
check z;
print z;
let w ← mkProjection c `w;
check w;
print w;
pure ()
set_option trace.Meta.isDefEq.step false
set_option trace.Meta.isDefEq.delta false
set_option trace.Meta.isDefEq.assign false
#eval tst41
set_option pp.all false
def tst42 : MetaM Unit := do
print "----- tst42 -----";
let t ← mkListLit nat [mkNatLit 1, mkNatLit 2];
print t;
check t;
let t ← mkArrayLit nat [mkNatLit 1, mkNatLit 2];
print t;
check t;
(match t.arrayLit? with
| some (_, xs) => do
checkM $ pure $ xs.length == 2;
(match (xs.get! 0).natLit?, (xs.get! 1).natLit? with
| some 1, some 2 => pure ()
| _, _ => throwError "nat lits expected")
| none => throwError "array lit expected")
#eval tst42
|
ee8eecb78a85bd42bcbf17efaf389cd5daca8f26 | f3849be5d845a1cb97680f0bbbe03b85518312f0 | /library/data/list/set.lean | d2effb2feefc30d703e3b3d5f002211cf75852bb | [
"Apache-2.0"
] | permissive | bjoeris/lean | 0ed95125d762b17bfcb54dad1f9721f953f92eeb | 4e496b78d5e73545fa4f9a807155113d8e6b0561 | refs/heads/master | 1,611,251,218,281 | 1,495,337,658,000 | 1,495,337,658,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,893 | lean | /-
Copyright (c) 2015 Leonardo de Moura. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad
Set-like operations on lists.
-/
universe variables uu vv
variables {α : Type uu} {β : Type vv}
namespace list
/- disjoint -/
section disjoint
def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, (a ∈ l₁ → a ∈ l₂ → false)
lemma disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ → ∀ {a}, a ∈ l₁ → a ∉ l₂ :=
λ d, d
lemma disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ → ∀ {a}, a ∈ l₂ → a ∉ l₁ :=
λ d a i₂ i₁, d i₁ i₂
lemma disjoint.comm {l₁ l₂ : list α} : disjoint l₁ l₂ → disjoint l₂ l₁ :=
λ d a i₂ i₁, d i₁ i₂
lemma disjoint_of_subset_left {l₁ l₂ l : list α} : list.subset l₁ l → disjoint l l₂ → disjoint l₁ l₂ :=
λ ss d x xinl₁, d (ss xinl₁)
lemma disjoint_of_subset_right {l₁ l₂ l : list α} : list.subset l₂ l → disjoint l₁ l → disjoint l₁ l₂ :=
λ ss d x xinl xinl₁, d xinl (ss xinl₁)
lemma disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ :=
disjoint_of_subset_left (list.subset_cons _ _)
lemma disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ :=
disjoint_of_subset_right (list.subset_cons _ _)
lemma disjoint_nil_left (l : list α) : disjoint [] l :=
λ a ab, absurd ab (not_mem_nil a)
lemma disjoint_nil_right (l : list α) : disjoint l [] :=
disjoint.comm (disjoint_nil_left l)
lemma disjoint_cons_of_not_mem_of_disjoint {a : α} {l₁ l₂ : list α} :
a ∉ l₂ → disjoint l₁ l₂ → disjoint (a::l₁) l₂ :=
λ nainl₂ d x (xinal₁ : x ∈ a::l₁),
or.elim (eq_or_mem_of_mem_cons xinal₁)
(λ xeqa : x = a, eq.symm xeqa ▸ nainl₂)
(λ xinl₁ : x ∈ l₁, disjoint_left d xinl₁)
lemma disjoint_append_of_disjoint_left {l₁ l₂ l : list α} :
disjoint l₁ l → disjoint l₂ l → disjoint (l₁++l₂) l :=
λ d₁ d₂ x h, or.elim (mem_or_mem_of_mem_append h) (@d₁ x) (@d₂ x)
lemma disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l → disjoint l₁ l :=
disjoint_of_subset_left (list.subset_append_left _ _)
lemma disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} : disjoint (l₁++l₂) l → disjoint l₂ l :=
disjoint_of_subset_left (list.subset_append_right _ _)
lemma disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} : disjoint l (l₁++l₂) → disjoint l l₁ :=
disjoint_of_subset_right (list.subset_append_left _ _)
lemma disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} : disjoint l (l₁++l₂) → disjoint l l₂ :=
disjoint_of_subset_right (list.subset_append_right _ _)
end disjoint
/- no duplicates predicate -/
inductive nodup {α : Type uu} : list α → Prop
| ndnil : nodup []
| ndcons : ∀ {a : α} {l : list α}, a ∉ l → nodup l → nodup (a::l)
section nodup
open nodup
theorem nodup_nil : @nodup α [] :=
ndnil
theorem nodup_cons {a : α} {l : list α} : a ∉ l → nodup l → nodup (a::l) :=
λ i n, ndcons i n
theorem nodup_singleton (a : α) : nodup [a] :=
nodup_cons (not_mem_nil a) nodup_nil
theorem nodup_of_nodup_cons : ∀ {a : α} {l : list α}, nodup (a::l) → nodup l
| a xs (ndcons i n) := n
theorem not_mem_of_nodup_cons : ∀ {a : α} {l : list α}, nodup (a::l) → a ∉ l
| a xs (ndcons i n) := i
theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) :=
λ ainl d, absurd ainl (not_mem_of_nodup_cons d)
theorem nodup_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → nodup l₂ → nodup l₁
| ._ ._ sublist.slnil h := h
| ._ ._ (sublist.cons l₁ l₂ a s) (ndcons i n) := nodup_of_sublist s n
| ._ ._ (sublist.cons2 l₁ l₂ a s) (ndcons i n) :=
ndcons (λh, i (subset_of_sublist s h)) (nodup_of_sublist s n)
theorem not_nodup_cons_of_not_nodup {a : α} {l : list α} : ¬ nodup l → ¬ nodup (a :: l) :=
contrapos nodup_of_nodup_cons
theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ :=
nodup_of_sublist (sublist_append_left l₁ l₂)
theorem nodup_of_nodup_append_right : ∀ {l₁ l₂ : list α}, nodup (l₁++l₂) → nodup l₂
| [] l₂ n := n
| (x::xs) l₂ n := nodup_of_nodup_append_right (nodup_of_nodup_cons n)
theorem disjoint_of_nodup_append : ∀ {l₁ l₂ : list α}, nodup (l₁++l₂) → disjoint l₁ l₂
| [] l₂ d := disjoint_nil_left l₂
| (x::xs) l₂ d :=
have nodup (x::(xs++l₂)), from d,
have x ∉ xs++l₂, from not_mem_of_nodup_cons this,
have nxinl₂ : x ∉ l₂, from not_mem_of_not_mem_append_right this,
take a, suppose a ∈ x::xs,
or.elim (eq_or_mem_of_mem_cons this)
(suppose a = x, eq.symm this ▸ nxinl₂)
(suppose ainxs : a ∈ xs,
have nodup (x::(xs++l₂)), from d,
have nodup (xs++l₂), from nodup_of_nodup_cons this,
have disjoint xs l₂, from disjoint_of_nodup_append this,
disjoint_left this ainxs)
theorem nodup_append_of_nodup_of_nodup_of_disjoint :
∀ {l₁ l₂ : list α}, nodup l₁ → nodup l₂ → disjoint l₁ l₂ → nodup (l₁++l₂)
| [] l₂ d₁ d₂ dsj := begin rw [nil_append], exact d₂ end
| (x::xs) l₂ d₁ d₂ dsj :=
have ndxs : nodup xs, from nodup_of_nodup_cons d₁,
have disjoint xs l₂, from disjoint_of_disjoint_cons_left dsj,
have ndxsl₂ : nodup (xs++l₂), from nodup_append_of_nodup_of_nodup_of_disjoint ndxs d₂ this,
have nxinxs : x ∉ xs, from not_mem_of_nodup_cons d₁,
have x ∉ l₂, from disjoint_left dsj (mem_cons_self x xs),
have x ∉ xs++l₂, from not_mem_append nxinxs this,
nodup_cons this ndxsl₂
theorem nodup_app_comm {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : nodup (l₂++l₁) :=
have d₁ : nodup l₁, from nodup_of_nodup_append_left d,
have d₂ : nodup l₂, from nodup_of_nodup_append_right d,
have dsj : disjoint l₁ l₂, from disjoint_of_nodup_append d,
nodup_append_of_nodup_of_nodup_of_disjoint d₂ d₁ (disjoint.comm dsj)
theorem nodup_head {a : α} {l₁ l₂ : list α} (d : nodup (l₁++(a::l₂))) : nodup (a::(l₁++l₂)) :=
have d₁ : nodup (a::(l₂++l₁)), from nodup_app_comm d,
have d₂ : nodup (l₂++l₁), from nodup_of_nodup_cons d₁,
have d₃ : nodup (l₁++l₂), from nodup_app_comm d₂,
have nain : a ∉ l₂++l₁, from not_mem_of_nodup_cons d₁,
have nain₂ : a ∉ l₂, from not_mem_of_not_mem_append_left nain,
have nain₁ : a ∉ l₁, from not_mem_of_not_mem_append_right nain,
nodup_cons (not_mem_append nain₁ nain₂) d₃
theorem nodup_middle {a : α} {l₁ l₂ : list α} (d : nodup (a::(l₁++l₂))) : nodup (l₁++(a::l₂)) :=
have d₁ : nodup (l₁++l₂), from nodup_of_nodup_cons d,
have nain : a ∉ l₁++l₂, from not_mem_of_nodup_cons d,
have disj : disjoint l₁ l₂, from disjoint_of_nodup_append d₁,
have d₂ : nodup l₁, from nodup_of_nodup_append_left d₁,
have d₃ : nodup l₂, from nodup_of_nodup_append_right d₁,
have nain₂ : a ∉ l₂, from not_mem_of_not_mem_append_right nain,
have nain₁ : a ∉ l₁, from not_mem_of_not_mem_append_left nain,
have d₄ : nodup (a::l₂), from nodup_cons nain₂ d₃,
have disj₂ : disjoint l₁ (a::l₂), from disjoint.comm (disjoint_cons_of_not_mem_of_disjoint nain₁
(disjoint.comm disj)),
nodup_append_of_nodup_of_nodup_of_disjoint d₂ d₄ disj₂
end nodup
end list
|
c983e30c805a09155204415e8879553c7f9a5190 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/complex/polynomial.lean | db5074f4ea35865a7b4eb99e92a68937f4cc22f4 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 1,411 | lean | /-
Copyright (c) 2019 Chris Hughes All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Junyan Xu
-/
import analysis.complex.liouville
import field_theory.is_alg_closed.basic
/-!
# The fundamental theorem of algebra
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file proves that every nonconstant complex polynomial has a root using Liouville's theorem.
As a consequence, the complex numbers are algebraically closed.
-/
open polynomial
open_locale polynomial
namespace complex
/-- **Fundamental theorem of algebra**: every non constant complex polynomial
has a root -/
lemma exists_root {f : ℂ[X]} (hf : 0 < degree f) : ∃ z : ℂ, is_root f z :=
begin
contrapose! hf,
obtain ⟨c, hc⟩ := (f.differentiable.inv hf).exists_const_forall_eq_of_bounded _,
{ obtain rfl : f = C c⁻¹ := polynomial.funext (λ z, by rw [eval_C, ← hc z, inv_inv]),
exact degree_C_le },
{ obtain ⟨z₀, h₀⟩ := f.exists_forall_norm_le,
simp only [bounded_iff_forall_norm_le, set.forall_range_iff, norm_inv],
exact ⟨‖eval z₀ f‖⁻¹, λ z, inv_le_inv_of_le (norm_pos_iff.2 $ hf z₀) (h₀ z)⟩ },
end
instance is_alg_closed : is_alg_closed ℂ :=
is_alg_closed.of_exists_root _ $ λ p _ hp, complex.exists_root $ degree_pos_of_irreducible hp
end complex
|
625bb0378636900130d77f8ddb53131aefc387fd | 8cd68b0e4eb405ef573e16a6d92dcbcdb92d1c29 | /library/init/meta/lean/parser.lean | 45a93b35843ee59df9dfff791a31d7824c37ee25 | [
"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 | 4,140 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
prelude
import init.meta.tactic init.meta.has_reflect init.category.alternative
namespace lean
-- TODO: make inspectable (and pure)
meta constant parser_state : Type
meta constant parser_state.env : parser_state → environment
meta constant parser_state.options : parser_state → options
meta constant parser_state.cur_pos : parser_state → pos
@[reducible] meta def parser := interaction_monad parser_state
@[reducible] meta def parser_result := interaction_monad.result parser_state
open interaction_monad
open interaction_monad.result
namespace parser
variable {α : Type}
meta def val (p : lean.parser (reflected_value α)) : lean.parser α :=
reflected_value.val <$> p
protected meta class reflectable (p : parser α) :=
(full : parser (reflected_value α))
namespace reflectable
meta def expr {p : parser α} (r : reflectable p) : parser expr :=
reflected_value.expr <$> r.full
meta def to_parser {p : parser α} (r : reflectable p) : parser α :=
val r.full
end reflectable
meta constant set_env : environment → parser unit
/-- Make sure the next token is an identifier, consume it, and
produce the quoted name `t, where t is the identifier. -/
meta constant ident : parser name
/-- Make sure the next token is a small nat, consume it, and produce it -/
meta constant small_nat : parser nat
/-- Check that the next token is `tk` and consume it. `tk` must be a registered token. -/
meta constant tk (tk : string) : parser unit
/-- Parse an unelaborated expression using the given right-binding power. -/
protected meta constant pexpr (rbp := std.prec.max) : parser pexpr
protected meta constant itactic_reflected : parser (reflected_value (tactic unit))
/-- Parse an interactive tactic block: `begin` .. `end` -/
@[reducible] protected meta def itactic : parser (tactic unit) := val parser.itactic_reflected
/-- Do not report info from content parsed by `p`. -/
meta constant skip_info (p : parser α) : parser α
/-- Set goal info position of content parsed by `p` to current position. Nested calls take precedence. -/
meta constant set_goal_info_pos (p : parser α) : parser α
/-- Return the current parser position without consuming any input. -/
meta def cur_pos : parser pos := λ s, success (parser_state.cur_pos s) s
/-- Temporarily replace input of the parser state, run `p`, and return remaining input. -/
meta constant with_input (p : parser α) (input : string) : parser (α × string)
/-- Parse a top-level command. -/
meta constant command_like : parser unit
meta def parser_orelse (p₁ p₂ : parser α) : parser α :=
λ s,
let pos₁ := parser_state.cur_pos s in
result.cases_on (p₁ s)
success
(λ e₁ ref₁ s',
let pos₂ := parser_state.cur_pos s' in
if pos₁ ≠ pos₂ then
exception e₁ ref₁ s'
else result.cases_on (p₂ s)
success
exception)
meta instance : alternative parser :=
{ failure := @interaction_monad.failed _,
orelse := @parser_orelse,
..interaction_monad.monad }
-- TODO: move
meta def {u v} many {f : Type u → Type v} [monad f] [alternative f] {a : Type u} : f a → f (list a)
| x := (do y ← x,
ys ← many x,
return $ y::ys) <|> pure list.nil
local postfix `?`:100 := optional
local postfix `*`:100 := many
meta def sep_by : parser unit → parser α → parser (list α)
| s p := (list.cons <$> p <*> (s *> p)*) <|> return []
meta constant of_tactic : tactic α → parser α
meta instance : has_coe (tactic α) (parser α) :=
⟨of_tactic⟩
namespace reflectable
meta instance cast (p : lean.parser (reflected_value α)) : reflectable (val p) :=
{full := p}
meta instance has_reflect [r : has_reflect α] (p : lean.parser α) : reflectable p :=
{full := do rp ← p, return ⟨rp⟩}
meta instance optional {α : Type} [reflected α] (p : parser α)
[r : reflectable p] : reflectable (optional p) :=
{full := reflected_value.subst some <$> r.full <|> return ⟨none⟩}
end reflectable
end parser
end lean
|
a7cb2b04c82fab05371f25bfd7ab01e3b4adb89a | 35b83be3126daae10419b573c55e1fed009d3ae8 | /_target/deps/mathlib/data/int/basic.lean | ce4cb535e96f610b1419db3029867139ee591e39 | [] | no_license | AHassan1024/Lean_Playground | ccb25b72029d199c0d23d002db2d32a9f2689ebc | a00b004c3a2eb9e3e863c361aa2b115260472414 | refs/heads/master | 1,586,221,905,125 | 1,544,951,310,000 | 1,544,951,310,000 | 157,934,290 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 45,922 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
The integers, with addition, multiplication, and subtraction.
-/
import data.nat.basic algebra.char_zero algebra.order_functions
open nat
namespace int
instance : inhabited ℤ := ⟨0⟩
meta instance : has_to_format ℤ := ⟨λ z, int.rec_on z (λ k, ↑k) (λ k, "-("++↑k++"+1)")⟩
attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ
@[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl
@[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl
@[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl
theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n
theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n
theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n
@[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n :=
by rw [← int.coe_nat_zero, coe_nat_lt]
@[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 :=
by rw [← int.coe_nat_zero, coe_nat_inj']
@[simp] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 :=
not_congr coe_nat_eq_zero
lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _)
lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n :=
⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h),
λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩
lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n)
/- succ and pred -/
/-- Immediate successor of an integer: `succ n = n + 1` -/
def succ (a : ℤ) := a + 1
/-- Immediate predecessor of an integer: `pred n = n - 1` -/
def pred (a : ℤ) := a - 1
theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl
theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _
theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _
theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _
theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a :=
by rw [neg_succ, succ_pred]
theorem neg_pred (a : ℤ) : -pred a = succ (-a) :=
by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg]
theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a :=
by rw [neg_pred, pred_succ]
theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n
theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n
theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n
theorem lt_succ_self (a : ℤ) : a < succ a :=
lt_add_of_pos_right _ zero_lt_one
theorem pred_self_lt (a : ℤ) : pred a < a :=
sub_lt_self _ zero_lt_one
theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl
theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b :=
@add_le_add_iff_right _ _ a b 1
theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b :=
sub_lt_iff_lt_add.trans lt_add_one_iff
theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b :=
le_sub_iff_add_le
@[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop}
(i : ℤ) (hz : p 0) (hp : ∀i, p i → p (i + 1)) (hn : ∀i, p i → p (i - 1)) : p i :=
begin
induction i,
{ induction i,
{ exact hz },
{ exact hp _ i_ih } },
{ have : ∀n:ℕ, p (- n),
{ intro n, induction n,
{ simp [hz] },
{ have := hn _ n_ih, simpa } },
exact this (i + 1) }
end
/- nat abs -/
attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one
theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b :=
begin
have, {
refine (λ a b : ℕ, sub_nat_nat_elim a b.succ
(λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl);
intros i n e,
{ subst e, rw [add_comm _ i, add_assoc],
exact nat.le_add_right i (b.succ + b).succ },
{ apply succ_le_succ,
rw [← succ_inj e, ← add_assoc, add_comm],
apply nat.le_add_right } },
cases a; cases b with b b; simp [nat_abs, nat.succ_add];
try {refl}; [skip, rw add_comm a b]; apply this
end
theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n :=
by cases n; refl
theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) :=
by cases a; cases b; simp [(*), int.mul, nat_abs_neg_of_nat]
theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 :=
by simp [neg_succ_of_nat_eq]
lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 :=
λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h
/- / -/
@[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl
@[simp] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl
theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : b > 0) :
-[1+m] / b = -(m / b + 1) :=
match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end
@[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b)
| (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl
| (m : ℕ) (n+1:ℕ) := rfl
| 0 -[1+ n] := rfl
| (m+1:ℕ) -[1+ n] := (neg_neg _).symm
| -[1+ m] 0 := rfl
| -[1+ m] (n+1:ℕ) := rfl
| -[1+ m] -[1+ n] := rfl
theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b = -((-a - 1) / b + 1) :=
match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ :=
by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl
end
protected theorem div_nonneg {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≥ 0) : a / b ≥ 0 :=
match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _
end
protected theorem div_nonpos {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≤ 0) : a / b ≤ 0 :=
nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb)
theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b < 0 :=
match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _
end
@[simp] protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0
| 0 := rfl
| (n+1:ℕ) := rfl
| -[1+ n] := rfl
@[simp] protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0
| 0 := rfl
| (n+1:ℕ) := rfl
| -[1+ n] := rfl
@[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a
| 0 := rfl
| (n+1:ℕ) := congr_arg of_nat (nat.div_one _)
| -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _)
theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 :=
match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 :=
congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2
end
theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 :=
match b, abs b, abs_eq_nat_abs b, H2 with
| (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2
| -[1+ n], ._, rfl, H2 := neg_inj $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2
end
protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) :
(a + b * c) / c = a / c + b :=
have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from
λ k n a, match a with
| (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos
| -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ =
n - (m / k.succ + 1 : ℕ), begin
cases lt_or_ge m (n*k.succ) with h h,
{ rw [← int.coe_nat_sub h,
← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)],
apply congr_arg of_nat,
rw [mul_comm, nat.mul_sub_div], rwa mul_comm },
{ change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) =
↑n - ((m / nat.succ k : ℕ) + 1),
rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ),
← int.coe_nat_sub h,
← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h),
← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'],
{ apply congr_arg neg_succ_of_nat,
rw [mul_comm, nat.sub_mul_div], rwa mul_comm } }
end
end,
have ∀ {a b c : ℤ}, c > 0 → (a + b * c) / c = a / c + b, from
λ a b c H, match c, eq_succ_of_zero_lt H, b with
| ._, ⟨k, rfl⟩, (n : ℕ) := this
| ._, ⟨k, rfl⟩, -[1+ n] :=
show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from
eq_sub_of_add_eq $ by rw [← this, sub_add_cancel]
end,
match lt_trichotomy c 0 with
| or.inl hlt := neg_inj $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg];
apply this (neg_pos_of_neg hlt)
| or.inr (or.inl heq) := absurd heq H
| or.inr (or.inr hgt) := this hgt
end
protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) :
(a + b * c) / b = a / b + c :=
by rw [mul_comm, int.add_mul_div_right _ _ H]
@[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a :=
by have := int.add_mul_div_right 0 a H;
rwa [zero_add, int.zero_div, zero_add] at this
@[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b :=
by rw [mul_comm, int.mul_div_cancel _ H]
@[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 :=
by have := int.mul_div_cancel 1 H; rwa one_mul at this
/- mod -/
theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl
@[simp] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl
theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : b > 0) :
-[1+m] % b = b - 1 - m % b :=
by rw [sub_sub, add_comm]; exact
match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end
@[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b
| (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _)
| -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _)
@[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b :=
abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _)
@[simp] theorem zero_mod (b : ℤ) : 0 % b = 0 :=
congr_arg of_nat $ nat.zero_mod _
@[simp] theorem mod_zero : ∀ (a : ℤ), a % 0 = a
| (m : ℕ) := congr_arg of_nat $ nat.mod_zero _
| -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _
@[simp] theorem mod_one : ∀ (a : ℤ), a % 1 = 0
| (m : ℕ) := congr_arg of_nat $ nat.mod_one _
| -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl
theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a :=
match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 :=
congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2)
end
theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → a % b ≥ 0
| (m : ℕ) n H := coe_zero_le _
| -[1+ m] n H :=
sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H)
theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : b > 0) : a % b < b :=
match a, b, eq_succ_of_zero_lt H with
| (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _))
| -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _)
end
theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b :=
by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos_of_ne_zero H)
theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] :=
begin
rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)],
apply eq_neg_of_eq_neg,
rw [neg_sub, sub_sub_self, add_right_comm],
exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm
end
theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a
| (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _)
| (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _)
| 0 -[1+ n] := rfl
| (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _,
by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _)
| -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl
| -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ
| -[1+ m] -[1+ n] := mod_add_div_aux m n.succ
theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) :=
eq_sub_of_add_eq (mod_add_div _ _)
@[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c :=
if cz : c = 0 then by rw [cz, mul_zero, add_zero] else
by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz,
mul_add, mul_comm, add_sub_add_right_eq_sub]
@[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b :=
by rw [mul_comm, add_mul_mod_self]
@[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b :=
by have := add_mul_mod_self_left a b 1; rwa mul_one at this
@[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a :=
by rw [add_comm, add_mod_self]
@[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n :=
by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm;
rwa [add_right_comm, mod_add_div] at this
@[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k :=
by rw [add_comm, mod_add_mod, add_comm]
theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) :
(m + i) % n = (k + i) % n :=
by rw [← mod_add_mod, ← mod_add_mod k, H]
theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) :
(i + m) % n = (i + k) % n :=
by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm]
theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔
m % n = k % n :=
⟨λ H, by have := add_mod_eq_add_mod_right (-i) H;
rwa [add_neg_cancel_right, add_neg_cancel_right] at this,
add_mod_eq_add_mod_right _⟩
theorem mod_add_cancel_left {m n k i : ℤ} :
(i + m) % n = (i + k) % n ↔ m % n = k % n :=
by rw [add_comm, add_comm i, mod_add_cancel_right]
theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔
m % n = k % n :=
mod_add_cancel_right _
theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 :=
(mod_sub_cancel_right k).symm.trans $ by simp
@[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 :=
by rw [← zero_add (a * b), add_mul_mod_self, zero_mod]
@[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 :=
by rw [mul_comm, mul_mod_left]
@[simp] theorem mod_self {a : ℤ} : a % a = 0 :=
by have := mul_mod_left 1 a; rwa one_mul at this
@[simp] lemma mod_mod (a b : ℤ) : a % b % b = a % b :=
by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]}
/- properties of / and % -/
@[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b / (a * c) = b / c :=
suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from
match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with
| ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _
| ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ :=
by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg];
apply congr_arg has_neg.neg; apply this
end,
λ m k b, match b, k with
| (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos)
| -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero]
| -[1+ n], k+1 := congr_arg neg_succ_of_nat $
show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin
apply nat.div_eq_of_lt_le,
{ refine le_trans _ (nat.le_add_right _ _),
rw [← nat.mul_div_mul _ _ m.succ_pos],
apply nat.div_mul_le_self },
{ change m.succ * n.succ ≤ _,
rw [mul_left_comm],
apply nat.mul_le_mul_left,
apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1,
apply nat.lt_succ_self }
end
end
@[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b > 0) :
a * b / (c * b) = a / c :=
by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H]
@[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b % (a * c) = a * (b % c) :=
by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc]
theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : b > 0) : a < (a / b + 1) * b :=
by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt;
rw [← mod_def]; apply mod_lt_of_pos _ H
theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a :=
suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from
λ a b, match b, eq_coe_or_neg b with
| ._, ⟨n, or.inl rfl⟩ := this _ _
| ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this
end,
λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact
coe_nat_le_coe_nat_of_le (match a, n with
| (m : ℕ), n := nat.div_le_self _ _
| -[1+ m], 0 := nat.zero_le _
| -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _)
end)
theorem div_le_self {a : ℤ} (b : ℤ) (Ha : a ≥ 0) : a / b ≤ a :=
by have := le_trans (le_abs_self _) (abs_div_le_abs a b);
rwa [abs_of_nonneg Ha] at this
theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a :=
by have := mod_add_div a b; rwa [H, zero_add] at this
theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a :=
by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H]
lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 :=
have h : n % 2 < 2 := abs_of_nonneg (show (2 : ℤ) ≥ 0, from dec_trivial) ▸ int.mod_lt _ dec_trivial,
have h₁ : n % 2 ≥ 0 := int.mod_nonneg _ dec_trivial,
match (n % 2), h, h₁ with
| (0 : ℕ) := λ _ _, or.inl rfl
| (1 : ℕ) := λ _ _, or.inr rfl
| (k + 2 : ℕ) := λ h _, absurd h dec_trivial
| -[1+ a] := λ _ h₁, absurd h₁ dec_trivial
end
/- dvd -/
theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n :=
⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim
(λm0, by simp [m0] at ae; simp [ae, m0])
(λm0l, by {
cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a
(by simp [ae.symm]) (by simpa using m0l)) with k e,
subst a, exact ⟨k, int.coe_nat_inj ae⟩ }),
λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩
theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs :=
by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd]
theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n :=
by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd]
theorem dvd_antisymm {a b : ℤ} (H1 : a ≥ 0) (H2 : b ≥ 0) : a ∣ b → b ∣ a → a = b :=
begin
rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs],
rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'],
apply nat.dvd_antisymm
end
theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b :=
⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩
theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0
| a ._ ⟨c, rfl⟩ := mul_mod_right _ _
theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 :=
⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩
theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b :=
(nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e])
theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b :=
(nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e])
instance decidable_dvd : @decidable_rel ℤ (∣) :=
assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm
protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a :=
div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H)
protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b :=
by rw [mul_comm, int.div_mul_cancel H]
protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c)
| ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else
by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz]
theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a
| a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else
by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az];
apply dvd_mul_right
protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) :
a = b * c :=
by rw [← H2, int.mul_div_cancel' H1]
protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) :
a / b = c :=
by rw [H2, int.mul_div_cancel_left _ H1]
protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) :
a / b = c ↔ a = b * c :=
⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩
protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) :
a / b = c ↔ a = c * b :=
by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H'
protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) :
a = c * b :=
by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2]
protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) :
a / b = c :=
int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2])
theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b)
| ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else
by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz]
theorem div_sign : ∀ a b, a / sign b = a * sign b
| a (n+1:ℕ) := by unfold sign; simp
| a 0 := by simp [sign]
| a -[1+ n] := by simp [sign]
@[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b
| a 0 := by simp
| 0 b := by simp
| (m+1:ℕ) (n+1:ℕ) := rfl
| (m+1:ℕ) -[1+ n] := rfl
| -[1+ m] (n+1:ℕ) := rfl
| -[1+ m] -[1+ n] := rfl
protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) :=
if az : a = 0 then by simp [az] else
(int.div_eq_of_eq_mul_left (mt eq_zero_of_abs_eq_zero az)
(sign_mul_abs _).symm).symm
theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i
| (n+1:ℕ) := mul_one _
| 0 := mul_zero _
| -[1+ n] := mul_neg_one _
theorem le_of_dvd {a b : ℤ} (bpos : b > 0) (H : a ∣ b) : a ≤ b :=
match a, b, eq_succ_of_zero_lt bpos, H with
| (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $
nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H
| -[1+ m], ._, ⟨n, rfl⟩, _ :=
le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _)
end
theorem eq_one_of_dvd_one {a : ℤ} (H : a ≥ 0) (H' : a ∣ 1) : a = 1 :=
match a, eq_coe_of_zero_le H, H' with
| ._, ⟨n, rfl⟩, H' := congr_arg coe $
nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H'
end
theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : a ≥ 0) (H' : a * b = 1) : a = 1 :=
eq_one_of_dvd_one H ⟨b, H'.symm⟩
theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : b ≥ 0) (H' : a * b = 1) : b = 1 :=
eq_one_of_mul_eq_one_right H (by rw [mul_comm, H'])
lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z
| (int.of_nat _) haz := int.coe_nat_dvd.2 haz
| -[1+k] haz :=
begin
change ↑a ∣ -(k+1 : ℤ),
apply dvd_neg_of_dvd,
apply int.coe_nat_dvd.2,
exact haz
end
lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs
| (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz)
| -[1+k] haz :=
have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz,
int.coe_nat_dvd.1 haz'
lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) :
↑(p ^ m) ∣ k :=
begin
induction k,
{ apply int.coe_nat_dvd.2,
apply pow_dvd_of_le_of_pow_dvd hmn,
apply int.coe_nat_dvd.1 hdiv },
{ change -[1+k] with -(↑(k+1) : ℤ),
apply dvd_neg_of_dvd,
apply int.coe_nat_dvd.2,
apply pow_dvd_of_le_of_pow_dvd hmn,
apply int.coe_nat_dvd.1,
apply dvd_of_dvd_neg,
exact hdiv }
end
lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m :=
by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk
/- / and ordering -/
protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a :=
le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H
protected theorem div_le_of_le_mul {a b c : ℤ} (H : c > 0) (H' : a ≤ b * c) : a / c ≤ b :=
le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H
protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : c > 0) (H3 : a < b / c) : a * c < b :=
lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3)
protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : c > 0) (H2 : a ≤ b / c) : a * c ≤ b :=
le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1))
protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : c > 0) (H2 : a * c ≤ b) : a ≤ b / c :=
le_of_lt_add_one $ lt_of_mul_lt_mul_right
(lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1)
protected theorem le_div_iff_mul_le {a b c : ℤ} (H : c > 0) : a ≤ b / c ↔ a * c ≤ b :=
⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩
protected theorem div_le_div {a b c : ℤ} (H : c > 0) (H' : a ≤ b) : a / c ≤ b / c :=
int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H')
protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : c > 0) (H' : a < b * c) : a / c < b :=
lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H')
protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : c > 0) (H2 : a / c < b) : a < b * c :=
lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2)
protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : c > 0) : a / c < b ↔ a < b * c :=
⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩
protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : b ≥ 0) (H2 : b ∣ a) (H3 : a / b ≤ c) :
a ≤ c * b :=
by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1
protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : b ≥ 0) (H2 : b ∣ c) (H3 : a * b < c) :
a < c / b :=
lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3)
protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : c > 0) (H' : c ∣ b) :
a < b / c ↔ a * c < b :=
⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩
theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : a > 0) (H2 : b ≥ 0) (H3 : b ∣ a) : a / b > 0 :=
int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul)
theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H1 : b ∣ a) (H2 : d ∣ c) (H3 : b ≠ 0)
(H4 : d ≠ 0) (H5 : a * d = b * c) :
a / b = c / d :=
int.div_eq_of_eq_mul_right H3 $
by rw [← int.mul_div_assoc _ H2]; exact
(int.div_eq_of_eq_mul_left H4 H5.symm).symm
theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0) (hbc : b ∣ c)
(h : b * a = c * d) : a = c / b * d :=
begin
cases hbc with k hk,
subst hk,
rw int.mul_div_cancel_left, rw mul_assoc at h,
apply _root_.eq_of_mul_eq_mul_left _ h,
repeat {assumption}
end
theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ}
(h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] :=
begin
change sub_nat_nat _ _ = _,
have h' : n.succ - m = (n - m).succ,
apply succ_sub,
apply le_of_lt_succ h,
simp [*, sub_nat_nat]
end
theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ}
(h : m ≥ n.succ) : of_nat m + -[1+n] = of_nat (m - n.succ) :=
begin
change sub_nat_nat _ _ = _,
have h' : n.succ - m = 0,
apply sub_eq_zero_of_le h,
simp [*, sub_nat_nat]
end
@[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl
/- to_nat -/
theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0
| (n : ℕ) := (max_eq_left (coe_zero_le n)).symm
| -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm
@[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a :=
by rw [to_nat_eq_max, max_eq_left h]
@[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl
theorem le_to_nat (a : ℤ) : a ≤ to_nat a :=
by rw [to_nat_eq_max]; apply le_max_left
@[simp] theorem to_nat_le (a : ℤ) (n : ℕ) : to_nat a ≤ n ↔ a ≤ n :=
by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff];
exact and_iff_left (coe_zero_le _)
def to_nat' : ℤ → option ℕ
| (n : ℕ) := some n
| -[1+ n] := none
theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n
| (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm
| -[1+ m] n := by split; intro h; cases h
/- units -/
@[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 :=
units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹,
by rw [← nat_abs_mul, units.mul_inv]; refl,
by rw [← nat_abs_mul, units.inv_mul]; refl⟩
theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 :=
by simpa [units.ext_iff, units_nat_abs] using nat_abs_eq u
lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u :=
(units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl)
/- bitwise ops -/
@[simp] lemma bodd_zero : bodd 0 = ff := rfl
@[simp] lemma bodd_one : bodd 1 = tt := rfl
@[simp] lemma bodd_two : bodd 2 = ff := rfl
@[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd :=
by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd);
intros i m; simp [bodd]; cases i.bodd; cases m.bodd; refl
@[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd :=
by cases n; simp; refl
@[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n :=
by cases n; unfold has_neg.neg; simp [int.coe_nat_eq, int.neg, bodd]
@[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) :=
by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, bodd];
cases m.bodd; cases n.bodd; refl
@[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n :=
by cases m with m m; cases n with n n; unfold has_mul.mul; simp [int.mul, bodd];
cases m.bodd; cases n.bodd; refl
theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n
| (n : ℕ) :=
by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ),
by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2
| -[1+ n] := begin
refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2),
dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul],
{ change -[1+ 2 * nat.div2 n] = _, rw zero_add },
{ rw [zero_add, add_comm], refl }
end
theorem div2_val : ∀ n, div2 n = n / 2
| (n : ℕ) := congr_arg of_nat n.div2_val
| -[1+ n] := congr_arg neg_succ_of_nat n.div2_val
lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm
lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _)
lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 :=
by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val }
lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n :=
(bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _
def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n :=
by rw [← bit_decomp n]; apply h
@[simp] lemma bit_zero : bit ff 0 = 0 := rfl
@[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bodd_bit (b n) : bodd (bit b n) = b :=
by rw bit_val; simp; cases b; cases bodd n; refl
@[simp] lemma div2_bit (b n) : div2 (bit b n) = n :=
begin
rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add],
cases b, all_goals {exact dec_trivial}
end
@[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b
| (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero];
clear test_bit_zero; cases b; refl
@[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m
| (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ]
private meta def bitwise_tac : tactic unit := `[
funext m,
funext n,
cases m with m m; cases n with n n; try {refl},
all_goals {
apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat,
try {dsimp [nat.land, nat.ldiff, nat.lor]},
try {rw [
show nat.bitwise (λ a b, a && bnot b) n m =
nat.bitwise (λ a b, b && bnot a) m n, from
congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]},
apply congr_arg (λ f, nat.bitwise f m n),
funext a,
funext b,
cases a; cases b; refl
},
all_goals {unfold nat.land nat.ldiff nat.lor}
]
theorem bitwise_or : bitwise bor = lor := by bitwise_tac
theorem bitwise_and : bitwise band = land := by bitwise_tac
theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac
theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac
@[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) :
bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) :=
begin
cases m with m m; cases n with n n;
repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ };
unfold bitwise nat_bitwise bnot;
[ induction h : f ff ff,
induction h : f ff tt,
induction h : f tt ff,
induction h : f tt tt ],
all_goals {
unfold cond, rw nat.bitwise_bit,
repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } },
all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl }
end
@[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) :=
by rw [← bitwise_or, bitwise_bit]
@[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) :=
by rw [← bitwise_and, bitwise_bit]
@[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) :=
by rw [← bitwise_diff, bitwise_bit]
@[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) :=
by rw [← bitwise_xor, bitwise_bit]
@[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n)
| (n : ℕ) := by simp [lnot]
| -[1+ n] := by simp [lnot]
@[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) :
test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) :=
begin
induction k with k IH generalizing m n;
apply bit_cases_on m; intros a m';
apply bit_cases_on n; intros b n';
rw bitwise_bit,
{ simp [test_bit_zero] },
{ simp [test_bit_succ, IH] }
end
@[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k :=
by rw [← bitwise_or, test_bit_bitwise]
@[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k :=
by rw [← bitwise_and, test_bit_bitwise]
@[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) :=
by rw [← bitwise_diff, test_bit_bitwise]
@[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) :=
by rw [← bitwise_xor, test_bit_bitwise]
@[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k)
| (n : ℕ) k := by simp [lnot, test_bit]
| -[1+ n] k := by simp [lnot, test_bit]
lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k
| (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _)
| -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _)
| (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ
(λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k)
(λ i n, congr_arg coe $
by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right)
(λ i n, congr_arg coe $
by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl)
| -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ
(λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k])
(λ i n, congr_arg neg_succ_of_nat $
by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right)
(λ i n, congr_arg neg_succ_of_nat $
by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl)
lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k :=
shiftl_add _ _ _
@[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl
@[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg]
@[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl
@[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl
@[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl
@[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl
lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k
| (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat,
← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add]
| -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ,
← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add]
lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n)
| (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _)
| -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _)
lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n)
| (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _)
| -[1+ m] n := begin
rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl,
exact coe_nat_lt_coe_nat_of_lt (nat.pos_pow_of_pos _ dec_trivial)
end
lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) :=
congr_arg coe (nat.one_shiftl _)
@[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0
| (n : ℕ) := congr_arg coe (nat.zero_shiftl _)
| -[1+ n] := congr_arg coe (nat.zero_shiftr _)
@[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _
/- Least upper bound property for integers -/
theorem exists_least_of_bdd {P : ℤ → Prop} [HP : decidable_pred P]
(Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z)
(Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) :=
let ⟨b, Hb⟩ := Hbdd in
have EX : ∃ n : ℕ, P (b + n), from
let ⟨elt, Helt⟩ := Hinh in
match elt, le.dest (Hb _ Helt), Helt with
| ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩
end,
⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h,
match z, le.dest (Hb _ h), h with
| ._, ⟨n, rfl⟩, h := add_le_add_left
(int.coe_nat_le.2 $ nat.find_min' _ h) _
end⟩
theorem exists_greatest_of_bdd {P : ℤ → Prop} [HP : decidable_pred P]
(Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b)
(Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) :=
have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from
let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩,
have Hinh' : ∃ z : ℤ, P (-z), from
let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩,
let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in
⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩
/- cast (injection into groups with one) -/
@[simp] theorem nat_cast_eq_coe_nat : ∀ n,
@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n =
@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n
| 0 := rfl
| (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n)
section cast
variables {α : Type*}
section
variables [has_zero α] [has_one α] [has_add α] [has_neg α]
/-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/
protected def cast : ℤ → α
| (n : ℕ) := n
| -[1+ n] := -(n+1)
@[priority 0] instance cast_coe : has_coe ℤ α := ⟨int.cast⟩
@[simp] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl
@[simp] theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl
@[simp] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl
@[simp] theorem cast_coe_nat' (n : ℕ) :
(@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n : α) = n :=
by simp
@[simp] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl
end
@[simp] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one
@[simp] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n :=
begin
unfold sub_nat_nat, cases e : n - m,
{ simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] },
{ rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e,
nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] },
end
@[simp] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n
| 0 := neg_zero.symm
| (n+1) := rfl
@[simp] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n
| (m : ℕ) (n : ℕ) := nat.cast_add _ _
| (m : ℕ) -[1+ n] := cast_sub_nat_nat _ _
| -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $
show (n:α) = -(m+1) + n + (m+1),
by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm,
nat.cast_add, cast_succ, neg_add_cancel_left]
| -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1),
by rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add];
apply congr_arg (λ x:ℕ, -(x:α)); simp
@[simp] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n
| (n : ℕ) := cast_neg_of_nat _
| -[1+ n] := (neg_neg _).symm
theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n :=
by simp
@[simp] theorem cast_eq_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) = 0 ↔ n = 0 :=
⟨λ h, begin cases n,
{ exact congr_arg coe (nat.cast_eq_zero.1 h) },
{ rw [cast_neg_succ_of_nat, neg_eq_zero, ← cast_succ, nat.cast_eq_zero] at h,
contradiction }
end, λ h, by rw [h, cast_zero]⟩
@[simp] theorem cast_inj [add_group α] [has_one α] [char_zero α] {m n : ℤ} : (m : α) = n ↔ m = n :=
by rw [← sub_eq_zero, ← cast_sub, cast_eq_zero, sub_eq_zero]
theorem cast_injective [add_group α] [has_one α] [char_zero α] : function.injective (coe : ℤ → α)
| m n := cast_inj.1
@[simp] theorem cast_ne_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) ≠ 0 ↔ n ≠ 0 :=
not_congr cast_eq_zero
@[simp] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n
| (m : ℕ) (n : ℕ) := nat.cast_mul _ _
| (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $
show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1),
by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg]
| -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $
show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n,
by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul]
| -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1),
by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg]
theorem mul_cast_comm [ring α] (a : α) (n : ℤ) : a * n = n * a :=
by cases n; simp [nat.mul_cast_comm, left_distrib, right_distrib, *]
@[simp] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _
@[simp] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n :=
by rw [bit1, cast_add, cast_one, cast_bit0]; refl
lemma cast_two [ring α] : ((2 : ℤ) : α) = 2 := by simp
theorem cast_nonneg [linear_ordered_ring α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n
| (n : ℕ) := by simp
| -[1+ n] := by simpa [not_le_of_gt (neg_succ_lt_zero n)] using
show -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one
@[simp] theorem cast_le [linear_ordered_ring α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n :=
by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg]
@[simp] theorem cast_lt [linear_ordered_ring α] {m n : ℤ} : (m : α) < n ↔ m < n :=
by simpa [-cast_le] using not_congr (@cast_le α _ n m)
@[simp] theorem cast_nonpos [linear_ordered_ring α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 :=
by rw [← cast_zero, cast_le]
@[simp] theorem cast_pos [linear_ordered_ring α] {n : ℤ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_lt_zero [linear_ordered_ring α] {n : ℤ} : (n : α) < 0 ↔ n < 0 :=
by rw [← cast_zero, cast_lt]
theorem eq_cast [add_group α] [has_one α] (f : ℤ → α)
(H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (n : ℤ) : f n = n :=
begin
have H : ∀ (n : ℕ), f n = n :=
nat.eq_cast' (λ n, f n) H1 (λ x y, Hadd x y),
cases n, {apply H},
apply eq_neg_of_add_eq_zero,
rw [← nat.cast_zero, ← H 0, int.coe_nat_zero,
← show -[1+ n] + (↑n + 1) = 0, from neg_add_self (↑n+1),
Hadd, show f (n+1) = n+1, from H (n+1)]
end
@[simp] theorem cast_id (n : ℤ) : ↑n = n :=
(eq_cast id rfl (λ _ _, rfl) n).symm
@[simp] theorem cast_min [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b :=
by by_cases a ≤ b; simp [h, min]
@[simp] theorem cast_max [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b :=
by by_cases a ≤ b; simp [h, max]
@[simp] theorem cast_abs [decidable_linear_ordered_comm_ring α] {q : ℤ} : ((abs q : ℤ) : α) = abs q :=
by simp [abs]
end cast
end int
|
85a002f79d3b5e38dd480af50aed080d1ce2d29d | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /stage0/src/Lean/Elab/Macro.lean | 2148877203b5fdccb2e23c8cca8cf5986f868a52 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 2,009 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.MacroArgUtil
namespace Lean.Elab.Command
open Lean.Syntax
open Lean.Parser.Term hiding macroArg
open Lean.Parser.Command
@[builtinCommandElab Lean.Parser.Command.macro] def elabMacro : CommandElab
| `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind
macro%$tk$[:$prec?]? $[(name := $name?)]? $[(priority := $prio?)]? $args:macroArg* : $cat => $rhs) =>
-- exclude command prefix from synthetic position used for e.g. jumping to the macro definition
withRef (mkNullNode #[tk, rhs]) do
let prio ← liftMacroM <| evalOptPrio prio?
let (stxParts, patArgs) := (← args.mapM expandMacroArg).unzip
-- name
let name ← match name? with
| some name => pure name.getId
| none => liftMacroM <| mkNameFromParserSyntax cat.getId (mkNullNode stxParts)
/- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind.
So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/
let pat := ⟨mkNode ((← getCurrNamespace) ++ name) patArgs⟩
let stxCmd ← `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind
syntax$[:$prec?]?
(name := $(name?.getD (mkIdentFrom tk name (canonical := true))))
(priority := $(quote prio):num)
$[$stxParts]* : $cat)
let rhs := rhs.raw
let macroRulesCmd ← if rhs.getArgs.size == 1 then
-- `rhs` is a `term`
let rhs := ⟨rhs[0]⟩
`($[$doc?:docComment]? macro_rules | `($pat) => $rhs)
else
-- `rhs` is of the form `` `( $body ) ``
let rhsBody := ⟨rhs[1]⟩
`($[$doc?:docComment]? macro_rules | `($pat) => `($rhsBody))
elabCommand <| mkNullNode #[stxCmd, macroRulesCmd]
| _ => throwUnsupportedSyntax
end Lean.Elab.Command
|
3095f1bfdb650576e9ada35b90424f6ef62fc094 | 130c49f47783503e462c16b2eff31933442be6ff | /stage0/src/Init/Data/Option/Basic.lean | 669e61b40079ea45ae5b9a276bf262ade27f3576 | [
"Apache-2.0"
] | permissive | Hazel-Brown/lean4 | 8aa5860e282435ffc30dcdfccd34006c59d1d39c | 79e6732fc6bbf5af831b76f310f9c488d44e7a16 | refs/heads/master | 1,689,218,208,951 | 1,629,736,869,000 | 1,629,736,896,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,217 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Core
import Init.Control.Basic
import Init.Coe
namespace Option
def toMonad [Monad m] [Alternative m] : Option α → m α
| none => failure
| some a => pure a
@[inline] def toBool : Option α → Bool
| some _ => true
| none => false
@[inline] def isSome : Option α → Bool
| some _ => true
| none => false
@[inline] def isNone : Option α → Bool
| some _ => false
| none => true
@[inline] def isEqSome [BEq α] : Option α → α → Bool
| some a, b => a == b
| none, _ => false
@[inline] protected def bind : Option α → (α → Option β) → Option β
| none, b => none
| some a, b => b a
@[inline] protected def map (f : α → β) (o : Option α) : Option β :=
Option.bind o (some ∘ f)
theorem map_id : (Option.map id : Option α → Option α) = id :=
funext (fun o => match o with | none => rfl | some x => rfl)
instance : Functor Option where
map := Option.map
@[inline] protected def filter (p : α → Bool) : Option α → Option α
| some a => if p a then some a else none
| none => none
@[inline] protected def all (p : α → Bool) : Option α → Bool
| some a => p a
| none => true
@[inline] protected def any (p : α → Bool) : Option α → Bool
| some a => p a
| none => false
@[macroInline] protected def orElse : Option α → Option α → Option α
| some a, _ => some a
| none, b => b
instance : OrElse (Option α) where
orElse := Option.orElse
@[inline] protected def lt (r : α → α → Prop) : Option α → Option α → Prop
| none, some x => True
| some x, some y => r x y
| _, _ => False
instance (r : α → α → Prop) [s : DecidableRel r] : DecidableRel (Option.lt r)
| none, some y => isTrue trivial
| some x, some y => s x y
| some x, none => isFalse not_false
| none, none => isFalse not_false
end Option
deriving instance DecidableEq for Option
deriving instance BEq for Option
instance [LT α] : LT (Option α) where
lt := Option.lt (· < ·)
|
731aca4845656aaa3918db51f0567fcbfd35980a | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/run/e3.lean | 9c1b11e03260207cee5946f74c22d57d99141ebe | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 381 | lean | definition Prop := Type.{0}
definition false := ∀x : Prop, x
check false
theorem false_elim (C : Prop) (H : false) : C
:= H C
definition eq {A : Type} (a b : A)
:= ∀ {P : A → Prop}, P a → P b
check eq
infix `=`:50 := eq
theorem refl {A : Type} (a : A) : a = a
:= λ P H, H
theorem subst {A : Type} {P : A -> Prop} {a b : A} (H1 : a = b) (H2 : P a) : P b
:= @H1 P H2
|
ca522e4587ff9cde88208b0a490b9e592c4807b9 | 07c6143268cfb72beccd1cc35735d424ebcb187b | /src/data/equiv/ring.lean | 4d3636f4da5e5791b15a3179a6563c8f654e4a17 | [
"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 | 9,487 | 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 algebra.field
/-!
# (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⟩
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 }
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) }
@[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
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_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 an `is_semiring_hom` instance from a `mul_equiv` of semirings that preserves addition. -/
protected lemma to_semiring_hom {R : Type*} {S : Type*} [semiring R] [semiring S]
(h : R ≃* S) (H : ∀ x y : R, h (x + y) = h x + h y) : is_semiring_hom h :=
⟨add_equiv.map_zero $ add_equiv.mk' h.to_equiv H, h.map_one, H, h.5⟩
/-- 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 add_equiv
/-- Gives an `is_semiring_hom` instance from a `mul_equiv` of semirings that preserves addition. -/
protected lemma to_semiring_hom {R : Type*} {S : Type*} [semiring R] [semiring S]
(h : R ≃+ S) (H : ∀ x y : R, h (x * y) = h x * h y) : is_semiring_hom h :=
⟨h.map_zero, mul_equiv.map_one $ mul_equiv.mk' h.to_equiv H, h.5, H⟩
end add_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₁ := equiv.ext f.to_equiv g.to_equiv 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),
zero_ne_one := λ H, hB.zero_ne_one $ by rw [← e.map_zero, ← e.map_one, H] }
/-- 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. -/
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, units.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
|
f6401fc56f6211ce23484538d4f0e57e4fdbbfc8 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/find_auto.lean | cfccf17d3c74169dbd68fea2696d97ce716db355 | [] | 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 | 631 | lean | /-
Copyright (c) 2017 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.core
import Mathlib.PostPort
namespace Mathlib
/--
The `find` command from `tactic.find` allows to find definitions lemmas using
pattern matching on the type. For instance:
```lean
import tactic.find
run_cmd tactic.skip
#find _ + _ = _ + _
#find (_ : ℕ) + _ = _ + _
#find ℕ → ℕ
```
The tactic `library_search` is an alternate way to find lemmas in the library.
-/
end Mathlib |
4d2a4c854f244667bb17279df744af243ff9fd25 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/measure_theory/measurable_space_def.lean | 642af17ecd600646fc852533d42f529d0080e434 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 19,996 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import data.set.countable
import logic.encodable.lattice
import order.disjointed
/-!
# Measurable spaces and measurable functions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines measurable spaces and measurable functions.
A measurable space is a set equipped with a σ-algebra, a collection of
subsets closed under complementation and countable union. A function
between measurable spaces is measurable if the preimage of each
measurable subset is measurable.
σ-algebras on a fixed set `α` form a complete lattice. Here we order
σ-algebras by writing `m₁ ≤ m₂` if every set which is `m₁`-measurable is
also `m₂`-measurable (that is, `m₁` is a subset of `m₂`). In particular, any
collection of subsets of `α` generates a smallest σ-algebra which
contains all of them.
Do not add measurability lemmas (which could be tagged with
@[measurability]) to this file, since the measurability tactic is downstream
from here. Use `measure_theory.measurable_space` instead.
## References
* <https://en.wikipedia.org/wiki/Measurable_space>
* <https://en.wikipedia.org/wiki/Sigma-algebra>
* <https://en.wikipedia.org/wiki/Dynkin_system>
## Tags
measurable space, σ-algebra, measurable function
-/
open set encodable function equiv
open_locale classical
variables {α β γ δ δ' : Type*} {ι : Sort*} {s t u : set α}
/-- A measurable space is a space equipped with a σ-algebra. -/
structure measurable_space (α : Type*) :=
(measurable_set' : set α → Prop)
(measurable_set_empty : measurable_set' ∅)
(measurable_set_compl : ∀ s, measurable_set' s → measurable_set' sᶜ)
(measurable_set_Union : ∀ f : ℕ → set α, (∀ i, measurable_set' (f i)) → measurable_set' (⋃ i, f i))
attribute [class] measurable_space
instance [h : measurable_space α] : measurable_space αᵒᵈ := h
section
/-- `measurable_set s` means that `s` is measurable (in the ambient measure space on `α`) -/
def measurable_set [measurable_space α] : set α → Prop := ‹measurable_space α›.measurable_set'
localized "notation (name := measurable_set_of)
`measurable_set[` m `]` := @measurable_set hole! m" in measure_theory
@[simp] lemma measurable_set.empty [measurable_space α] : measurable_set (∅ : set α) :=
‹measurable_space α›.measurable_set_empty
variable {m : measurable_space α}
include m
lemma measurable_set.compl : measurable_set s → measurable_set sᶜ :=
‹measurable_space α›.measurable_set_compl s
lemma measurable_set.of_compl (h : measurable_set sᶜ) : measurable_set s :=
compl_compl s ▸ h.compl
@[simp] lemma measurable_set.compl_iff : measurable_set sᶜ ↔ measurable_set s :=
⟨measurable_set.of_compl, measurable_set.compl⟩
@[simp] lemma measurable_set.univ : measurable_set (univ : set α) :=
by simpa using (@measurable_set.empty α _).compl
@[nontriviality] lemma subsingleton.measurable_set [subsingleton α] {s : set α} :
measurable_set s :=
subsingleton.set_cases measurable_set.empty measurable_set.univ s
lemma measurable_set.congr {s t : set α} (hs : measurable_set s) (h : s = t) :
measurable_set t :=
by rwa ← h
lemma measurable_set.bUnion_decode₂ [encodable β] ⦃f : β → set α⦄ (h : ∀ b, measurable_set (f b))
(n : ℕ) : measurable_set (⋃ b ∈ decode₂ β n, f b) :=
encodable.Union_decode₂_cases measurable_set.empty h
lemma measurable_set.Union [countable ι] ⦃f : ι → set α⦄ (h : ∀ b, measurable_set (f b)) :
measurable_set (⋃ b, f b) :=
begin
casesI nonempty_encodable (plift ι),
rw [←Union_plift_down, ←encodable.Union_decode₂],
exact ‹measurable_space α›.measurable_set_Union _ (measurable_set.bUnion_decode₂ $ λ _, h _),
end
lemma measurable_set.bUnion {f : β → set α} {s : set β} (hs : s.countable)
(h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) :=
begin
rw bUnion_eq_Union,
haveI := hs.to_encodable,
exact measurable_set.Union (by simpa using h)
end
lemma set.finite.measurable_set_bUnion {f : β → set α} {s : set β} (hs : s.finite)
(h : ∀ b ∈ s, measurable_set (f b)) :
measurable_set (⋃ b ∈ s, f b) :=
measurable_set.bUnion hs.countable h
lemma finset.measurable_set_bUnion {f : β → set α} (s : finset β)
(h : ∀ b ∈ s, measurable_set (f b)) :
measurable_set (⋃ b ∈ s, f b) :=
s.finite_to_set.measurable_set_bUnion h
lemma measurable_set.sUnion {s : set (set α)} (hs : s.countable) (h : ∀ t ∈ s, measurable_set t) :
measurable_set (⋃₀ s) :=
by { rw sUnion_eq_bUnion, exact measurable_set.bUnion hs h }
lemma set.finite.measurable_set_sUnion {s : set (set α)} (hs : s.finite)
(h : ∀ t ∈ s, measurable_set t) :
measurable_set (⋃₀ s) :=
measurable_set.sUnion hs.countable h
lemma measurable_set.Inter [countable ι] {f : ι → set α} (h : ∀ b, measurable_set (f b)) :
measurable_set (⋂ b, f b) :=
measurable_set.compl_iff.1 $
by { rw compl_Inter, exact measurable_set.Union (λ b, (h b).compl) }
lemma measurable_set.bInter {f : β → set α} {s : set β} (hs : s.countable)
(h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) :=
measurable_set.compl_iff.1 $
by { rw compl_Inter₂, exact measurable_set.bUnion hs (λ b hb, (h b hb).compl) }
lemma set.finite.measurable_set_bInter {f : β → set α} {s : set β} (hs : s.finite)
(h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) :=
measurable_set.bInter hs.countable h
lemma finset.measurable_set_bInter {f : β → set α} (s : finset β)
(h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) :=
s.finite_to_set.measurable_set_bInter h
lemma measurable_set.sInter {s : set (set α)} (hs : s.countable) (h : ∀ t ∈ s, measurable_set t) :
measurable_set (⋂₀ s) :=
by { rw sInter_eq_bInter, exact measurable_set.bInter hs h }
lemma set.finite.measurable_set_sInter {s : set (set α)} (hs : s.finite)
(h : ∀ t ∈ s, measurable_set t) : measurable_set (⋂₀ s) :=
measurable_set.sInter hs.countable h
@[simp] lemma measurable_set.union {s₁ s₂ : set α} (h₁ : measurable_set s₁)
(h₂ : measurable_set s₂) :
measurable_set (s₁ ∪ s₂) :=
by { rw union_eq_Union, exact measurable_set.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) }
@[simp] lemma measurable_set.inter {s₁ s₂ : set α} (h₁ : measurable_set s₁)
(h₂ : measurable_set s₂) :
measurable_set (s₁ ∩ s₂) :=
by { rw inter_eq_compl_compl_union_compl, exact (h₁.compl.union h₂.compl).compl }
@[simp] lemma measurable_set.diff {s₁ s₂ : set α} (h₁ : measurable_set s₁)
(h₂ : measurable_set s₂) :
measurable_set (s₁ \ s₂) :=
h₁.inter h₂.compl
@[simp] lemma measurable_set.symm_diff {s₁ s₂ : set α}
(h₁ : measurable_set s₁) (h₂ : measurable_set s₂) :
measurable_set (s₁ ∆ s₂) :=
(h₁.diff h₂).union (h₂.diff h₁)
@[simp] lemma measurable_set.ite {t s₁ s₂ : set α} (ht : measurable_set t) (h₁ : measurable_set s₁)
(h₂ : measurable_set s₂) :
measurable_set (t.ite s₁ s₂) :=
(h₁.inter ht).union (h₂.diff ht)
lemma measurable_set.ite' {s t : set α} {p : Prop}
(hs : p → measurable_set s) (ht : ¬ p → measurable_set t) :
measurable_set (ite p s t) :=
by { split_ifs, exacts [hs h, ht h], }
@[simp] lemma measurable_set.cond {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂)
{i : bool} : measurable_set (cond i s₁ s₂) :=
by { cases i, exacts [h₂, h₁] }
@[simp] lemma measurable_set.disjointed {f : ℕ → set α} (h : ∀ i, measurable_set (f i)) (n) :
measurable_set (disjointed f n) :=
disjointed_rec (λ t i ht, measurable_set.diff ht $ h _) (h n)
@[simp] lemma measurable_set.const (p : Prop) : measurable_set {a : α | p} :=
by { by_cases p; simp [h, measurable_set.empty]; apply measurable_set.univ }
/-- Every set has a measurable superset. Declare this as local instance as needed. -/
lemma nonempty_measurable_superset (s : set α) : nonempty { t // s ⊆ t ∧ measurable_set t} :=
⟨⟨univ, subset_univ s, measurable_set.univ⟩⟩
end
open_locale measure_theory
@[ext] lemma measurable_space.ext : ∀ {m₁ m₂ : measurable_space α},
(∀ s : set α, measurable_set[m₁] s ↔ measurable_set[m₂] s) → m₁ = m₂
| ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h :=
have s₁ = s₂, from funext $ assume x, propext $ h x,
by subst this
@[ext] lemma measurable_space.ext_iff {m₁ m₂ : measurable_space α} :
m₁ = m₂ ↔ (∀ s : set α, measurable_set[m₁] s ↔ measurable_set[m₂] s) :=
⟨by { unfreezingI {rintro rfl}, intro s, refl }, measurable_space.ext⟩
/-- A typeclass mixin for `measurable_space`s such that each singleton is measurable. -/
class measurable_singleton_class (α : Type*) [measurable_space α] : Prop :=
(measurable_set_singleton : ∀ x, measurable_set ({x} : set α))
export measurable_singleton_class (measurable_set_singleton)
attribute [simp] measurable_set_singleton
section measurable_singleton_class
variables [measurable_space α] [measurable_singleton_class α]
lemma measurable_set_eq {a : α} : measurable_set {x | x = a} :=
measurable_set_singleton a
lemma measurable_set.insert {s : set α} (hs : measurable_set s) (a : α) :
measurable_set (insert a s) :=
(measurable_set_singleton a).union hs
@[simp] lemma measurable_set_insert {a : α} {s : set α} :
measurable_set (insert a s) ↔ measurable_set s :=
⟨λ h, if ha : a ∈ s then by rwa ← insert_eq_of_mem ha
else insert_diff_self_of_not_mem ha ▸ h.diff (measurable_set_singleton _),
λ h, h.insert a⟩
lemma set.subsingleton.measurable_set {s : set α} (hs : s.subsingleton) : measurable_set s :=
hs.induction_on measurable_set.empty measurable_set_singleton
lemma set.finite.measurable_set {s : set α} (hs : s.finite) : measurable_set s :=
finite.induction_on hs measurable_set.empty $ λ a s ha hsf hsm, hsm.insert _
protected lemma finset.measurable_set (s : finset α) : measurable_set (↑s : set α) :=
s.finite_to_set.measurable_set
lemma set.countable.measurable_set {s : set α} (hs : s.countable) : measurable_set s :=
begin
rw [← bUnion_of_singleton s],
exact measurable_set.bUnion hs (λ b hb, measurable_set_singleton b)
end
end measurable_singleton_class
namespace measurable_space
section complete_lattice
instance : has_le (measurable_space α) :=
{ le := λ m₁ m₂, ∀ s, measurable_set[m₁] s → measurable_set[m₂] s }
lemma le_def {α} {a b : measurable_space α} :
a ≤ b ↔ a.measurable_set' ≤ b.measurable_set' := iff.rfl
instance : partial_order (measurable_space α) :=
{ lt := λ m₁ m₂, m₁ ≤ m₂ ∧ ¬m₂ ≤ m₁,
.. measurable_space.has_le,
.. partial_order.lift (@measurable_set α) (λ m₁ m₂ h, ext $ λ s, h ▸ iff.rfl) }
/-- The smallest σ-algebra containing a collection `s` of basic sets -/
inductive generate_measurable (s : set (set α)) : set α → Prop
| basic : ∀ u ∈ s, generate_measurable u
| empty : generate_measurable ∅
| compl : ∀ s, generate_measurable s → generate_measurable sᶜ
| union : ∀ f : ℕ → set α, (∀ n, generate_measurable (f n)) → generate_measurable (⋃ i, f i)
/-- Construct the smallest measure space containing a collection of basic sets -/
def generate_from (s : set (set α)) : measurable_space α :=
{ measurable_set' := generate_measurable s,
measurable_set_empty := generate_measurable.empty,
measurable_set_compl := generate_measurable.compl,
measurable_set_Union := generate_measurable.union }
lemma measurable_set_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) :
@measurable_set _ (generate_from s) t :=
generate_measurable.basic t ht
@[elab_as_eliminator]
lemma generate_from_induction (p : set α → Prop) (C : set (set α))
(hC : ∀ t ∈ C, p t) (h_empty : p ∅) (h_compl : ∀ t, p t → p tᶜ)
(h_Union : ∀ f : ℕ → set α, (∀ n, p (f n)) → p (⋃ i, f i))
{s : set α} (hs : measurable_set[generate_from C] s) :
p s :=
by { induction hs, exacts [hC _ hs_H, h_empty, h_compl _ hs_ih, h_Union hs_f hs_ih], }
lemma generate_from_le {s : set (set α)} {m : measurable_space α}
(h : ∀ t ∈ s, measurable_set[m] t) : generate_from s ≤ m :=
assume t (ht : generate_measurable s t), ht.rec_on h
(measurable_set_empty m)
(assume s _ hs, measurable_set_compl m s hs)
(assume f _ hf, measurable_set_Union m f hf)
lemma generate_from_le_iff {s : set (set α)} (m : measurable_space α) :
generate_from s ≤ m ↔ s ⊆ {t | measurable_set[m] t} :=
iff.intro
(assume h u hu, h _ $ measurable_set_generate_from hu)
(assume h, generate_from_le h)
@[simp] lemma generate_from_measurable_set [measurable_space α] :
generate_from {s : set α | measurable_set s} = ‹_› :=
le_antisymm (generate_from_le $ λ _, id) $ λ s, measurable_set_generate_from
/-- If `g` is a collection of subsets of `α` such that the `σ`-algebra generated from `g` contains
the same sets as `g`, then `g` was already a `σ`-algebra. -/
protected def mk_of_closure (g : set (set α)) (hg : {t | measurable_set[generate_from g] t} = g) :
measurable_space α :=
{ measurable_set' := λ s, s ∈ g,
measurable_set_empty := hg ▸ measurable_set_empty _,
measurable_set_compl := hg ▸ measurable_set_compl _,
measurable_set_Union := hg ▸ measurable_set_Union _ }
lemma mk_of_closure_sets {s : set (set α)}
{hs : {t | measurable_set[generate_from s] t} = s} :
measurable_space.mk_of_closure s hs = generate_from s :=
measurable_space.ext $ assume t, show t ∈ s ↔ _, by { conv_lhs { rw [← hs] }, refl }
/-- We get a Galois insertion between `σ`-algebras on `α` and `set (set α)` by using `generate_from`
on one side and the collection of measurable sets on the other side. -/
def gi_generate_from : galois_insertion (@generate_from α) (λ m, {t | @measurable_set α m t}) :=
{ gc := assume s, generate_from_le_iff,
le_l_u := assume m s, measurable_set_generate_from,
choice :=
λ g hg, measurable_space.mk_of_closure g $ le_antisymm hg $ (generate_from_le_iff _).1 le_rfl,
choice_eq := assume g hg, mk_of_closure_sets }
instance : complete_lattice (measurable_space α) :=
gi_generate_from.lift_complete_lattice
instance : inhabited (measurable_space α) := ⟨⊤⟩
@[mono] lemma generate_from_mono {s t : set (set α)} (h : s ⊆ t) :
generate_from s ≤ generate_from t :=
gi_generate_from.gc.monotone_l h
lemma generate_from_sup_generate_from {s t : set (set α)} :
generate_from s ⊔ generate_from t = generate_from (s ∪ t) :=
(@gi_generate_from α).gc.l_sup.symm
@[simp] lemma generate_from_insert_univ (S : set (set α)) :
generate_from (insert set.univ S) = generate_from S :=
begin
refine le_antisymm _ (generate_from_mono (set.subset_insert _ _)),
rw generate_from_le_iff,
intros t ht,
cases ht,
{ rw ht,
exact measurable_set.univ, },
{ exact measurable_set_generate_from ht, },
end
@[simp] lemma generate_from_insert_empty (S : set (set α)) :
generate_from (insert ∅ S) = generate_from S :=
begin
refine le_antisymm _ (generate_from_mono (set.subset_insert _ _)),
rw generate_from_le_iff,
intros t ht,
cases ht,
{ rw ht,
exact @measurable_set.empty _ (generate_from S), },
{ exact measurable_set_generate_from ht, },
end
@[simp] lemma generate_from_singleton_empty : generate_from {∅} = (⊥ : measurable_space α) :=
by { rw [eq_bot_iff, generate_from_le_iff], simp, }
@[simp] lemma generate_from_singleton_univ : generate_from {set.univ} = (⊥ : measurable_space α) :=
by { rw [eq_bot_iff, generate_from_le_iff], simp, }
lemma measurable_set_bot_iff {s : set α} : @measurable_set α ⊥ s ↔ (s = ∅ ∨ s = univ) :=
let b : measurable_space α :=
{ measurable_set' := λ s, s = ∅ ∨ s = univ,
measurable_set_empty := or.inl rfl,
measurable_set_compl := by simp [or_imp_distrib] {contextual := tt},
measurable_set_Union := assume f hf, classical.by_cases
(assume h : ∃i, f i = univ,
let ⟨i, hi⟩ := h in
or.inr $ eq_univ_of_univ_subset $ hi ▸ le_supr f i)
(assume h : ¬ ∃i, f i = univ,
or.inl $ eq_empty_of_subset_empty $ Union_subset $ assume i,
(hf i).elim (by simp {contextual := tt}) (assume hi, false.elim $ h ⟨i, hi⟩)) } in
have b = ⊥, from bot_unique $ assume s hs,
hs.elim (λ s, s.symm ▸ @measurable_set_empty _ ⊥) (λ s, s.symm ▸ @measurable_set.univ _ ⊥),
this ▸ iff.rfl
@[simp] theorem measurable_set_top {s : set α} : @measurable_set _ ⊤ s := trivial
@[simp] theorem measurable_set_inf {m₁ m₂ : measurable_space α} {s : set α} :
@measurable_set _ (m₁ ⊓ m₂) s ↔ @measurable_set _ m₁ s ∧ @measurable_set _ m₂ s :=
iff.rfl
@[simp] theorem measurable_set_Inf {ms : set (measurable_space α)} {s : set α} :
@measurable_set _ (Inf ms) s ↔ ∀ m ∈ ms, @measurable_set _ m s :=
show s ∈ (⋂₀ _) ↔ _, by simp
@[simp] theorem measurable_set_infi {ι} {m : ι → measurable_space α} {s : set α} :
@measurable_set _ (infi m) s ↔ ∀ i, @measurable_set _ (m i) s :=
by rw [infi, measurable_set_Inf, forall_range_iff]
theorem measurable_set_sup {m₁ m₂ : measurable_space α} {s : set α} :
measurable_set[m₁ ⊔ m₂] s ↔ generate_measurable (measurable_set[m₁] ∪ measurable_set[m₂]) s :=
iff.refl _
theorem measurable_set_Sup {ms : set (measurable_space α)} {s : set α} :
measurable_set[Sup ms] s ↔
generate_measurable {s : set α | ∃ m ∈ ms, measurable_set[m] s} s :=
begin
change @measurable_set' _ (generate_from $ ⋃₀ _) _ ↔ _,
simp [generate_from, ← set_of_exists]
end
theorem measurable_set_supr {ι} {m : ι → measurable_space α} {s : set α} :
@measurable_set _ (supr m) s ↔
generate_measurable {s : set α | ∃ i, measurable_set[m i] s} s :=
by simp only [supr, measurable_set_Sup, exists_range_iff]
lemma measurable_space_supr_eq (m : ι → measurable_space α) :
(⨆ n, m n) = generate_from {s | ∃ n, measurable_set[m n] s} :=
by { ext s, rw measurable_set_supr, refl, }
lemma generate_from_Union_measurable_set (m : ι → measurable_space α) :
generate_from (⋃ n, {t | measurable_set[m n] t}) = ⨆ n, m n :=
(@gi_generate_from α).l_supr_u m
end complete_lattice
end measurable_space
section measurable_functions
open measurable_space
/-- A function `f` between measurable spaces is measurable if the preimage of every
measurable set is measurable. -/
def measurable [measurable_space α] [measurable_space β] (f : α → β) : Prop :=
∀ ⦃t : set β⦄, measurable_set t → measurable_set (f ⁻¹' t)
localized "notation (name := measurable_of)
`measurable[` m `]` := @measurable hole! hole! m hole!" in measure_theory
lemma measurable_id {ma : measurable_space α} : measurable (@id α) := λ t, id
lemma measurable_id' {ma : measurable_space α} : measurable (λ a : α, a) := measurable_id
lemma measurable.comp {mα : measurable_space α} {mβ : measurable_space β}
{mγ : measurable_space γ} {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) :
measurable (g ∘ f) :=
λ t ht, hf (hg ht)
@[simp] lemma measurable_const {ma : measurable_space α} {mb : measurable_space β} {a : α} :
measurable (λ b : β, a) :=
assume s hs, measurable_set.const (a ∈ s)
lemma measurable.le {α} {m m0 : measurable_space α} {mb : measurable_space β} (hm : m ≤ m0)
{f : α → β}
(hf : measurable[m] f) : measurable[m0] f :=
λ s hs, hm _ (hf hs)
lemma measurable_space.top.measurable {α β : Type*} [measurable_space β] (f : α → β) :
@measurable α β ⊤ _ f :=
λ s hs, measurable_space.measurable_set_top
end measurable_functions
|
260efe285205c2a3649e745718212269fac8d359 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/char_p/default.lean | 2d9c522c12429fd668f4613fe63f340c68a11321 | [] | 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 | 250 | lean | import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.char_p.basic
import Mathlib.algebra.char_p.pi
import Mathlib.algebra.char_p.quotient
import Mathlib.algebra.char_p.subring
import Mathlib.PostPort
namespace Mathlib
|
fc4ac09a41b6cdbd99e5b3dbd8c2f6386439a9ec | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /test/compute_degree.lean | c62448030fc25a387883f80f1cacc4bf0e40161d | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,822 | lean | import tactic.compute_degree
open polynomial
open_locale polynomial
variables {R : Type*} [semiring R] {a b c d e : R}
example {R : Type*} [ring R] (h : ∀ {p q : R[X]}, p.nat_degree ≤ 0 → (p * q).nat_degree = 0) :
nat_degree (- 1 * 1 : R[X]) = 0 :=
begin
apply h _,
compute_degree_le,
end
example {p : R[X]} {n : ℕ} {p0 : p.nat_degree = 0} :
(p ^ n).nat_degree ≤ 0 :=
by compute_degree_le
example {p : R[X]} {n : ℕ} {p0 : p.nat_degree = 0} :
(p ^ n).nat_degree ≤ 0 :=
by cases n; compute_degree_le
example {p q r : R[X]} {a b c d e f m n : ℕ} {p0 : p.nat_degree = a} {q0 : q.nat_degree = b}
{r0 : r.nat_degree = c} :
(((q ^ e * p ^ d) ^ m * r ^ f) ^ n).nat_degree ≤ ((b * e + a * d) * m + c * f) * n :=
begin
compute_degree_le,
rw [p0, q0, r0],
end
example {F} [ring F] {p : F[X]} (p0 : p.nat_degree ≤ 0) :
p.nat_degree ≤ 0 :=
begin
success_if_fail_with_msg {compute_degree_le} "Goal did not change",
exact p0,
end
example {F} [ring F] {p q : F[X]} (h : p.nat_degree + 1 ≤ q.nat_degree) :
(- p * X).nat_degree ≤ q.nat_degree :=
by compute_degree_le
example {F} [ring F] {a : F} {n : ℕ} (h : n ≤ 10) :
nat_degree (X ^ n - C a * X ^ 10 : F[X]) ≤ 10 :=
by compute_degree_le
example {F} [ring F] {a : F} {n : ℕ} (h : n ≤ 10) :
nat_degree (X ^ n + C a * X ^ 10 : F[X]) ≤ 10 :=
by compute_degree_le
example (n : ℕ) (h : 1 + n < 11) :
degree (5 * X ^ n + (X * monomial n 1 + X * X) + C a + C a * X ^ 10) ≤ 10 :=
begin
compute_degree_le,
{ exact nat.lt_succ_iff.mp h },
{ exact nat.lt_succ_iff.mp ((lt_one_add n).trans h) },
end
example {n : ℕ} (h : 1 + n < 11) :
degree (X + (X * monomial 2 1 + X * X) ^ 2) ≤ 10 :=
by compute_degree_le
example {m s: ℕ} (ms : m ≤ s) (s1 : 1 ≤ s) : nat_degree (C a * X ^ m + X + 5) ≤ s :=
by compute_degree_le; assumption
example : nat_degree (7 * X : R[X]) ≤ 1 :=
by compute_degree_le
example : (1 : R[X]).nat_degree ≤ 0 :=
by compute_degree_le
example : nat_degree (monomial 5 c * monomial 1 c + monomial 7 d +
C a * X ^ 0 + C b * X ^ 5 + C c * X ^ 2 + X ^ 10 + C e * X) ≤ 10 :=
by compute_degree_le
example {n : ℕ} : nat_degree (0 * (X ^ 0 + X ^ n) * monomial 5 c * monomial 6 c) ≤ 9 :=
begin
success_if_fail_with_msg {compute_degree_le}
"the given polynomial has a term of expected degree
at least '11'",
rw [zero_mul, zero_mul, zero_mul, nat_degree_zero],
exact nat.zero_le _
end
example : nat_degree (monomial 0 c * (monomial 0 c * C 1) + monomial 0 d + C 1 + C a * X ^ 0) ≤ 0 :=
by compute_degree_le
example {F} [ring F] {n m : ℕ} (n4 : n ≤ 4) (m4 : m ≤ 4) {a : F} :
nat_degree (C a * X ^ n + X ^ m + bit1 1 : F[X]) ≤ 4 :=
by compute_degree_le; assumption
example {F} [ring F] : nat_degree (X ^ 4 + bit1 1 : F[X]) ≤ 4 :=
by compute_degree_le
|
173e0a919223a0d90327026b0ceeda4b20648701 | 8930e38ac0fae2e5e55c28d0577a8e44e2639a6d | /analysis/topology/infinite_sum.lean | 61e6a9c9b2ef7125e1408272bd1f8dbaf1afd205 | [
"Apache-2.0"
] | permissive | SG4316/mathlib | 3d64035d02a97f8556ad9ff249a81a0a51a3321a | a7846022507b531a8ab53b8af8a91953fceafd3a | refs/heads/master | 1,584,869,960,527 | 1,530,718,645,000 | 1,530,724,110,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 21,022 | 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
Infinite sum over a topological monoid
This sum is known as unconditionally convergent, as it sums to the same value under all possible
permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute
convergence.
-/
import logic.function algebra.big_operators data.set data.finset
analysis.metric_space analysis.topology.topological_structures
noncomputable theory
open lattice finset filter function classical
local attribute [instance] prop_decidable
variables {α : Type*} {β : Type*} {γ : Type*}
section is_sum
variables [add_comm_monoid α] [topological_space α] [topological_add_monoid α]
/-- Infinite sum on a topological monoid
The `at_top` filter on `finset α` is the limit of all finite sets towards the entire type. So we sum
up bigger and bigger sets. This sum operation is still invariant under reordering, and a absolute
sum operator.
This is based on Mario Carneiro's infinite sum in Metamath.
-/
def is_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, s.sum f) at_top (nhds a)
/-- `has_sum f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/
def has_sum (f : β → α) : Prop := ∃a, is_sum f a
/-- `tsum f` is the sum of `f` it exists, or 0 otherwise -/
def tsum (f : β → α) := if h : has_sum f then classical.some h else 0
notation `∑` binders `, ` r:(scoped f, tsum f) := r
variables {f g : β → α} {a b : α} {s : finset β}
lemma is_sum_tsum (ha : has_sum f) : is_sum f (∑b, f b) :=
by simp [ha, tsum]; exact some_spec ha
lemma has_sum_spec (ha : is_sum f a) : has_sum f := ⟨a, ha⟩
lemma is_sum_zero : is_sum (λb, 0 : β → α) 0 :=
by simp [is_sum, tendsto_const_nhds]
lemma has_sum_zero : has_sum (λb, 0 : β → α) := has_sum_spec is_sum_zero
lemma is_sum_add (hf : is_sum f a) (hg : is_sum g b) : is_sum (λb, f b + g b) (a + b) :=
by simp [is_sum, sum_add_distrib]; exact tendsto_add hf hg
lemma has_sum_add (hf : has_sum f) (hg : has_sum g) : has_sum (λb, f b + g b) :=
has_sum_spec $ is_sum_add (is_sum_tsum hf)(is_sum_tsum hg)
lemma is_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} :
(∀i∈s, is_sum (f i) (a i)) → is_sum (λb, s.sum $ λi, f i b) (s.sum a) :=
finset.induction_on s (by simp [is_sum_zero]) (by simp [is_sum_add] {contextual := tt})
lemma has_sum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, has_sum (f i)) :
has_sum (λb, s.sum $ λi, f i b) :=
has_sum_spec $ is_sum_sum $ assume i hi, is_sum_tsum $ hf i hi
lemma is_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : is_sum f (s.sum f) :=
tendsto_infi' s $ tendsto_cong tendsto_const_nhds $
assume t (ht : s ⊆ t), show s.sum f = t.sum f, from sum_subset ht $ assume x _, hf _
lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f :=
has_sum_spec $ is_sum_sum_of_ne_finset_zero hf
lemma is_sum_ite (b : β) (a : α) : is_sum (λb', if b' = b then a else 0) a :=
suffices
is_sum (λb', if b' = b then a else 0) (({b} : finset β).sum (λb', if b' = b then a else 0)), from
by simpa,
is_sum_sum_of_ne_finset_zero $ assume b' hb,
have b' ≠ b, by simpa using hb,
by rw [if_neg this]
lemma is_sum_of_iso {j : γ → β} {i : β → γ}
(hf : is_sum f a) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : is_sum (f ∘ j) a :=
have ∀x y, j x = j y → x = y,
from assume x y h,
have i (j x) = i (j y), by rw [h],
by rwa [h₁, h₁] at this,
have (λs:finset γ, s.sum (f ∘ j)) = (λs:finset β, s.sum f) ∘ (λs:finset γ, s.image j),
from funext $ assume s, (sum_image $ assume x _ y _, this x y).symm,
show tendsto (λs:finset γ, s.sum (f ∘ j)) at_top (nhds a),
by rw [this]; apply (tendsto_finset_image_at_top_at_top h₂).comp hf
lemma is_sum_iff_is_sum_of_iso {j : γ → β} (i : β → γ)
(h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) :
is_sum (f ∘ j) a ↔ is_sum f a :=
iff.intro
(assume hfj,
have is_sum ((f ∘ j) ∘ i) a, from is_sum_of_iso hfj h₂ h₁,
by simp [(∘), h₂] at this; assumption)
(assume hf, is_sum_of_iso hf h₁ h₂)
lemma is_sum_hom (g : α → γ) [add_comm_monoid γ] [topological_space γ] [topological_add_monoid γ]
(h₁ : g 0 = 0) (h₂ : ∀x y, g (x + y) = g x + g y) (h₃ : continuous g) (hf : is_sum f a) :
is_sum (g ∘ f) (g a) :=
have (λs:finset β, s.sum (g ∘ f)) = g ∘ (λs:finset β, s.sum f),
from funext $ assume s, sum_hom g h₁ h₂,
show tendsto (λs:finset β, s.sum (g ∘ f)) at_top (nhds (g a)),
by rw [this]; exact hf.comp (continuous_iff_tendsto.mp h₃ a)
lemma tendsto_sum_nat_of_is_sum {f : ℕ → α} (h : is_sum f a) :
tendsto (λn:ℕ, (range n).sum f) at_top (nhds a) :=
suffices map (λ (n : ℕ), sum (range n) f) at_top ≤ map (λ (s : finset ℕ), sum s f) at_top,
from le_trans this h,
assume s (hs : {t : finset ℕ | t.sum f ∈ s} ∈ at_top.sets),
let ⟨t, ht⟩ := mem_at_top_sets.mp hs, ⟨n, hn⟩ := @exists_nat_subset_range t in
mem_at_top_sets.mpr ⟨n, assume n' hn', ht _ $ finset.subset.trans hn $ range_subset.mpr hn'⟩
lemma is_sum_sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α}
(hf : ∀b, is_sum (λc, f ⟨b, c⟩) (g b)) (ha : is_sum f a) : is_sum g a :=
assume s' hs',
let
⟨s, hs, hss', hsc⟩ := nhds_is_closed hs',
⟨u, hu⟩ := mem_at_top_sets.mp $ ha $ hs,
fsts := u.image sigma.fst,
snds := λb, u.bind (λp, (if h : p.1 = b then {cast (congr_arg γ h) p.2} else ∅ : finset (γ b)))
in
have u_subset : u ⊆ fsts.sigma snds,
from subset_iff.mpr $ assume ⟨b, c⟩ hu,
have hb : b ∈ fsts, from finset.mem_image.mpr ⟨_, hu, rfl⟩,
have hc : c ∈ snds b, from mem_bind.mpr ⟨_, hu, by simp; refl⟩,
by simp [mem_sigma, hb, hc] ,
mem_at_top_sets.mpr $ exists.intro fsts $ assume bs (hbs : fsts ⊆ bs),
have h : ∀cs : Π b ∈ bs, finset (γ b),
(⋂b (hb : b ∈ bs), (λp:Πb, finset (γ b), p b) ⁻¹' {cs' | cs b hb ⊆ cs' }) ∩
(λp, bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩))) ⁻¹' s ≠ ∅,
from assume cs,
let cs' := λb, (if h : b ∈ bs then cs b h else ∅) ∪ snds b in
have sum_eq : bs.sum (λb, (cs' b).sum (λc, f ⟨b, c⟩)) = (bs.sigma cs').sum f,
from sum_sigma.symm,
have (bs.sigma cs').sum f ∈ s,
from hu _ $ finset.subset.trans u_subset $ sigma_mono hbs $
assume b, @finset.subset_union_right (γ b) _ _ _,
set.ne_empty_iff_exists_mem.mpr $ exists.intro cs' $
by simp [sum_eq, this]; { intros b hb, simp [cs', hb, finset.subset_union_right] },
have tendsto (λp:(Πb:β, finset (γ b)), bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩)))
(⨅b (h : b ∈ bs), at_top.vmap (λp, p b)) (nhds (bs.sum g)),
from tendsto_finset_sum bs $
assume c hc, tendsto_infi' c $ tendsto_infi' hc $ tendsto_vmap.comp (hf c),
have bs.sum g ∈ s,
from mem_closure_of_tendsto this hsc $ forall_sets_neq_empty_iff_neq_bot.mp $
by simp [mem_inf_sets, exists_imp_distrib, and_imp, forall_and_distrib,
filter.mem_infi_sets_finset, mem_vmap_sets, skolem, mem_at_top_sets,
and_comm];
from
assume s₁ s₂ s₃ hs₁ hs₃ p hs₂ p' hp cs hp',
have (⋂b (h : b ∈ bs), (λp:(Πb, finset (γ b)), p b) ⁻¹' {cs' | cs b h ⊆ cs' }) ≤ (⨅b∈bs, p b),
from infi_le_infi $ assume b, infi_le_infi $ assume hb,
le_trans (set.preimage_mono $ hp' b hb) (hp b hb),
neq_bot_of_le_neq_bot (h _) (le_trans (set.inter_subset_inter (le_trans this hs₂) hs₃) hs₁),
hss' this
lemma has_sum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(hf : ∀b, has_sum (λc, f ⟨b, c⟩)) (ha : has_sum f) : has_sum (λb, ∑c, f ⟨b, c⟩):=
has_sum_spec $ is_sum_sigma (assume b, is_sum_tsum $ hf b) (is_sum_tsum ha)
end is_sum
section is_sum_iff_is_sum_of_iso_ne_zero
variables [add_comm_monoid α] [topological_space α] [topological_add_monoid α]
variables {f : β → α} {g : γ → α} {a : α}
lemma is_sum_of_is_sum
(h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f)
(hf : is_sum g a) : is_sum f a :=
suffices at_top.map (λs:finset β, s.sum f) ≤ at_top.map (λs:finset γ, s.sum g),
from le_trans this hf,
by rw [map_at_top_eq, map_at_top_eq];
from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $
by simp [set.image_subset_iff]; exact hv)
lemma is_sum_iff_is_sum
(h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f)
(h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ v'.sum f = u'.sum g) :
is_sum f a ↔ is_sum g a :=
⟨is_sum_of_is_sum h₂, is_sum_of_is_sum h₁⟩
variables
(i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0)
(j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0)
(hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c)
(hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b)
(hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b)
include hi hj hji hij hgj
lemma is_sum_of_is_sum_ne_zero : is_sum g a → is_sum f a :=
have j_inj : ∀x y (hx : f x ≠ 0) (hy : f y ≠ 0), (j hx = j hy ↔ x = y),
from assume x y hx hy,
⟨assume h,
have i (hj hx) = i (hj hy), by simp [h],
by rwa [hij, hij] at this; assumption,
by simp {contextual := tt}⟩,
let ii : finset γ → finset β := λu, u.bind $ λc, if h : g c = 0 then ∅ else {i h} in
let jj : finset β → finset γ := λv, v.bind $ λb, if h : f b = 0 then ∅ else {j h} in
is_sum_of_is_sum $ assume u, exists.intro (ii u) $
assume v hv, exists.intro (u ∪ jj v) $ and.intro subset_union_left $
have ∀c:γ, c ∈ u ∪ jj v → c ∉ jj v → g c = 0,
from assume c hc hnc, classical.by_contradiction $ assume h : g c ≠ 0,
have c ∈ u,
from (finset.mem_union.1 hc).resolve_right hnc,
have i h ∈ v,
from hv $ by simp [mem_bind]; existsi c; simp [h, this],
have j (hi h) ∈ jj v,
by simp [mem_bind]; existsi i h; simp [h, hi, this],
by rw [hji h] at this; exact hnc this,
calc (u ∪ jj v).sum g = (jj v).sum g : (sum_subset subset_union_right this).symm
... = v.sum _ : sum_bind $ by intros x hx y hy hxy; by_cases f x = 0; by_cases f y = 0; simp [*]
... = v.sum f : sum_congr rfl $ by intros x hx; by_cases f x = 0; simp [*]
lemma is_sum_iff_is_sum_of_ne_zero : is_sum f a ↔ is_sum g a :=
iff.intro
(is_sum_of_is_sum_ne_zero j hj i hi hij hji $ assume b hb, by rw [←hgj (hi _), hji])
(is_sum_of_is_sum_ne_zero i hi j hj hji hij hgj)
lemma has_sum_iff_has_sum_ne_zero : has_sum g ↔ has_sum f :=
exists_congr $
assume a, is_sum_iff_is_sum_of_ne_zero j hj i hi hij hji $
assume b hb, by rw [←hgj (hi _), hji]
end is_sum_iff_is_sum_of_iso_ne_zero
section tsum
variables [add_comm_monoid α] [topological_space α] [topological_add_monoid α] [t2_space α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma is_sum_unique : is_sum f a₁ → is_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique at_top_ne_bot
lemma tsum_eq_is_sum (ha : is_sum f a) : (∑b, f b) = a := is_sum_unique (is_sum_tsum ⟨a, ha⟩) ha
lemma is_sum_iff_of_has_sum (h : has_sum f) : is_sum f a ↔ (∑b, f b) = a :=
iff.intro tsum_eq_is_sum (assume eq, eq ▸ is_sum_tsum h)
@[simp] lemma tsum_zero : (∑b:β, 0:α) = 0 := tsum_eq_is_sum is_sum_zero
lemma tsum_add (hf : has_sum f) (hg : has_sum g) : (∑b, f b + g b) = (∑b, f b) + (∑b, g b) :=
tsum_eq_is_sum $ is_sum_add (is_sum_tsum hf) (is_sum_tsum hg)
lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, has_sum (f i)) :
(∑b, s.sum (λi, f i b)) = s.sum (λi, ∑b, f i b) :=
tsum_eq_is_sum $ is_sum_sum $ assume i hi, is_sum_tsum $ hf i hi
lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) :
(∑b, f b) = s.sum f :=
tsum_eq_is_sum $ is_sum_sum_of_ne_finset_zero hf
lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) :
(∑b, f b) = f b :=
calc (∑b, f b) = (finset.singleton b).sum f : tsum_eq_sum $ by simp [hf] {contextual := tt}
... = f b : by simp
lemma tsum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(h₁ : ∀b, has_sum (λc, f ⟨b, c⟩)) (h₂ : has_sum f) : (∑p, f p) = (∑b c, f ⟨b, c⟩):=
(tsum_eq_is_sum $ is_sum_sigma (assume b, is_sum_tsum $ h₁ b) $ is_sum_tsum h₂).symm
@[simp] lemma tsum_ite (b : β) (a : α) : (∑b', if b' = b then a else 0) = a :=
tsum_eq_is_sum (is_sum_ite b a)
lemma tsum_eq_tsum_of_is_sum_iff_is_sum {f : β → α} {g : γ → α}
(h : ∀{a}, is_sum f a ↔ is_sum g a) : (∑b, f b) = (∑c, g c) :=
by_cases
(assume : ∃a, is_sum f a,
let ⟨a, hfa⟩ := this in
have hga : is_sum g a, from h.mp hfa,
by rw [tsum_eq_is_sum hfa, tsum_eq_is_sum hga])
(assume hf : ¬ has_sum f,
have hg : ¬ has_sum g, from assume ⟨a, hga⟩, hf ⟨a, h.mpr hga⟩,
by simp [tsum, hf, hg])
lemma tsum_eq_tsum_of_ne_zero {f : β → α} {g : γ → α}
(i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0)
(j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0)
(hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c)
(hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b)
(hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b) :
(∑i, f i) = (∑j, g j) :=
tsum_eq_tsum_of_is_sum_iff_is_sum $ assume a, is_sum_iff_is_sum_of_ne_zero i hi j hj hji hij hgj
lemma tsum_eq_tsum_of_ne_zero_bij {f : β → α} {g : γ → α}
(i : Π⦃c⦄, g c ≠ 0 → β)
(h₁ : ∀⦃c₁ c₂⦄ (h₁ : g c₁ ≠ 0) (h₂ : g c₂ ≠ 0), i h₁ = i h₂ → c₁ = c₂)
(h₂ : ∀⦃b⦄, f b ≠ 0 → ∃c (h : g c ≠ 0), i h = b)
(h₃ : ∀⦃c⦄ (h : g c ≠ 0), f (i h) = g c) :
(∑i, f i) = (∑j, g j) :=
have hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0,
from assume c h, by simp [h₃, h],
let j : Π⦃b⦄, f b ≠ 0 → γ := λb h, some $ h₂ h in
have hj : ∀⦃b⦄ (h : f b ≠ 0), ∃(h : g (j h) ≠ 0), i h = b,
from assume b h, some_spec $ h₂ h,
have hj₁ : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0,
from assume b h, let ⟨h₁, _⟩ := hj h in h₁,
have hj₂ : ∀⦃b⦄ (h : f b ≠ 0), i (hj₁ h) = b,
from assume b h, let ⟨h₁, h₂⟩ := hj h in h₂,
tsum_eq_tsum_of_ne_zero i hi j hj₁
(assume c h, h₁ (hj₁ _) h $ hj₂ _) hj₂ (assume b h, by rw [←h₃ (hj₁ _), hj₂])
lemma tsum_eq_tsum_of_iso (j : γ → β) (i : β → γ)
(h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) :
(∑c, f (j c)) = (∑b, f b) :=
tsum_eq_tsum_of_is_sum_iff_is_sum $ assume a, is_sum_iff_is_sum_of_iso i h₁ h₂
end tsum
section topological_group
variables [add_comm_group α] [topological_space α] [topological_add_group α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma is_sum_neg : is_sum f a → is_sum (λb, - f b) (- a) :=
is_sum_hom has_neg.neg (by simp) (by simp) continuous_neg'
lemma has_sum_neg (hf : has_sum f) : has_sum (λb, - f b) :=
has_sum_spec $ is_sum_neg $ is_sum_tsum $ hf
lemma is_sum_sub (hf : is_sum f a₁) (hg : is_sum g a₂) : is_sum (λb, f b - g b) (a₁ - a₂) :=
by simp; exact is_sum_add hf (is_sum_neg hg)
lemma has_sum_sub (hf : has_sum f) (hg : has_sum g) : has_sum (λb, f b - g b) :=
has_sum_spec $ is_sum_sub (is_sum_tsum hf) (is_sum_tsum hg)
section tsum
variables [t2_space α]
lemma tsum_neg (hf : has_sum f) : (∑b, - f b) = - (∑b, f b) :=
tsum_eq_is_sum $ is_sum_neg $ is_sum_tsum $ hf
lemma tsum_sub (hf : has_sum f) (hg : has_sum g) : (∑b, f b - g b) = (∑b, f b) - (∑b, g b) :=
tsum_eq_is_sum $ is_sum_sub (is_sum_tsum hf) (is_sum_tsum hg)
end tsum
end topological_group
section topological_semiring
variables [semiring α] [topological_space α] [topological_semiring α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma is_sum_mul_left : is_sum f a₁ → is_sum (λb, a₂ * f b) (a₂ * a₁) :=
is_sum_hom _ (by simp) (by simp [mul_add]) (continuous_mul continuous_const continuous_id)
lemma is_sum_mul_right (hf : is_sum f a₁) : is_sum (λb, f b * a₂) (a₁ * a₂) :=
@is_sum_hom _ _ _ _ _ _ f a₁ (λa, a * a₂) _ _ _
(by simp) (by simp [add_mul]) (continuous_mul continuous_id continuous_const) hf
lemma has_sum_mul_left (hf : has_sum f) : has_sum (λb, a * f b) :=
has_sum_spec $ is_sum_mul_left $ is_sum_tsum hf
lemma has_sum_mul_right (hf : has_sum f) : has_sum (λb, f b * a) :=
has_sum_spec $ is_sum_mul_right $ is_sum_tsum hf
section tsum
variables [t2_space α]
lemma tsum_mul_left (hf : has_sum f) : (∑b, a * f b) = a * (∑b, f b) :=
tsum_eq_is_sum $ is_sum_mul_left $ is_sum_tsum hf
lemma tsum_mul_right (hf : has_sum f) : (∑b, f b * a) = (∑b, f b) * a :=
tsum_eq_is_sum $ is_sum_mul_right $ is_sum_tsum hf
end tsum
end topological_semiring
section order_topology
variables [ordered_comm_monoid α] [topological_space α] [ordered_topology α] [topological_add_monoid α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma is_sum_le (h : ∀b, f b ≤ g b) (hf : is_sum f a₁) (hg : is_sum g a₂) : a₁ ≤ a₂ :=
le_of_tendsto at_top_ne_bot hf hg $ univ_mem_sets' $ assume s, sum_le_sum' $ assume b _, h b
lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : has_sum f) (hg : has_sum g) : (∑b, f b) ≤ (∑b, g b) :=
is_sum_le h (is_sum_tsum hf) (is_sum_tsum hg)
end order_topology
section uniform_group
variables [add_comm_group α] [uniform_space α] [complete_space α] [uniform_add_group α]
variables {f g : β → α} {a a₁ a₂ : α}
/- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/
lemma has_sum_of_has_sum_of_sub {f' : β → α} (hf : has_sum f) (h : ∀b, f' b = 0 ∨ f' b = f b) :
has_sum f' :=
let ⟨a, hf⟩ := hf in
suffices cauchy (at_top.map (λs:finset β, s.sum f')),
from complete_space.complete this,
⟨map_ne_bot at_top_ne_bot,
assume s' hs',
have ∃t∈(@uniformity α _).sets, ∀{a₁ a₂ a₃ a₄}, (a₁, a₂) ∈ t → (a₃, a₄) ∈ t → (a₁ - a₃, a₂ - a₄) ∈ s',
begin
have h : {p:(α×α)×(α×α)| (p.1.1 - p.1.2, p.2.1 - p.2.2) ∈ s'} ∈ (@uniformity (α × α) _).sets,
from uniform_continuous_sub' hs',
rw [uniformity_prod_eq_prod, filter.mem_map, mem_prod_same_iff] at h,
rcases h with ⟨t, ht, h⟩,
exact ⟨t, ht, assume a₁ a₂ a₃ a₄ h₁ h₂, @h ((a₁, a₂), (a₃, a₄)) ⟨h₁, h₂⟩⟩
end,
let ⟨s, hs, hss'⟩ := this in
have cauchy (at_top.map (λs:finset β, s.sum f)),
from cauchy_downwards cauchy_nhds (map_ne_bot at_top_ne_bot) hf,
have ∃t, ∀u₁ u₂:finset β, t ⊆ u₁ → t ⊆ u₂ → (u₁.sum f, u₂.sum f) ∈ s,
by simp [cauchy_iff, mem_at_top_sets, and.assoc, and.left_comm, and.comm] at this;
from let ⟨t, ht, u, hu⟩ := this s hs in
⟨u, assume u₁ u₂ h₁ h₂, ht $ set.prod_mk_mem_set_prod_eq.mpr ⟨hu _ h₁, hu _ h₂⟩⟩,
let ⟨t, ht⟩ := this in
let d := (t.filter (λb, f' b = 0)).sum f in
have eq : ∀{u}, t ⊆ u → (t ∪ u.filter (λb, f' b ≠ 0)).sum f - d = u.sum f',
from assume u hu,
have t ∪ u.filter (λb, f' b ≠ 0) = t.filter (λb, f' b = 0) ∪ u.filter (λb, f' b ≠ 0),
from finset.ext.2 $ assume b, by by_cases f' b = 0;
simp [h, subset_iff.mp hu, iff_def, or_imp_distrib] {contextual := tt},
calc (t ∪ u.filter (λb, f' b ≠ 0)).sum f - d =
(t.filter (λb, f' b = 0) ∪ u.filter (λb, f' b ≠ 0)).sum f - d : by rw [this]
... = (d + (u.filter (λb, f' b ≠ 0)).sum f) - d :
by rw [sum_union]; exact (finset.ext.2 $ by simp {contextual := tt})
... = (u.filter (λb, f' b ≠ 0)).sum f :
by simp
... = (u.filter (λb, f' b ≠ 0)).sum f' :
sum_congr rfl $ assume b, by have h := h b; cases h with h h; simp [*]
... = u.sum f' :
by apply sum_subset; by simp [subset_iff, not_not] {contextual := tt},
have ∀{u₁ u₂}, t ⊆ u₁ → t ⊆ u₂ → (u₁.sum f', u₂.sum f') ∈ s',
from assume u₁ u₂ h₁ h₂,
have ((t ∪ u₁.filter (λb, f' b ≠ 0)).sum f, (t ∪ u₂.filter (λb, f' b ≠ 0)).sum f) ∈ s,
from ht _ _ subset_union_left subset_union_left,
have ((t ∪ u₁.filter (λb, f' b ≠ 0)).sum f - d, (t ∪ u₂.filter (λb, f' b ≠ 0)).sum f - d) ∈ s',
from hss' this $ refl_mem_uniformity hs,
by rwa [eq h₁, eq h₂] at this,
mem_prod_same_iff.mpr ⟨(λu:finset β, u.sum f') '' {u | t ⊆ u},
image_mem_map $ mem_at_top t,
assume ⟨a₁, a₂⟩ ⟨⟨t₁, h₁, eq₁⟩, ⟨t₂, h₂, eq₂⟩⟩, by simp at eq₁ eq₂; rw [←eq₁, ←eq₂]; exact this h₁ h₂⟩⟩
end uniform_group
|
c9a9e6272f6292f9c7a417c75a56c94c4d2e7046 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/logic/function/basic.lean | d5f1888bec8bf4352abc3b7d37cebd721bdf2472 | [
"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 | 20,347 | lean | /-
Copyright (c) 2016 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import logic.basic
import data.option.defs
/-!
# Miscellaneous function constructions and lemmas
-/
universes u v w
namespace function
section
variables {α β γ : Sort*} {f : α → β}
/-- Evaluate a function at an argument. Useful if you want to talk about the partially applied
`function.eval x : (Π x, β x) → β x`. -/
@[reducible] def eval {β : α → Sort*} (x : α) (f : Π x, β x) : β x := f x
@[simp] lemma eval_apply {β : α → Sort*} (x : α) (f : Π x, β x) : eval x f = f x := rfl
lemma comp_apply {α : Sort u} {β : Sort v} {φ : Sort w} (f : β → φ) (g : α → β) (a : α) :
(f ∘ g) a = f (g a) := rfl
lemma const_def {y : β} : (λ x : α, y) = const α y := rfl
@[simp] lemma const_apply {y : β} {x : α} : const α y x = y := rfl
@[simp] lemma const_comp {f : α → β} {c : γ} : const β c ∘ f = const α c := rfl
@[simp] lemma comp_const {f : β → γ} {b : β} : f ∘ const α b = const α (f b) := rfl
lemma hfunext {α α': Sort u} {β : α → Sort v} {β' : α' → Sort v} {f : Πa, β a} {f' : Πa, β' a}
(hα : α = α') (h : ∀a a', a == a' → f a == f' a') : f == f' :=
begin
subst hα,
have : ∀a, f a == f' a,
{ intro a, exact h a a (heq.refl a) },
have : β = β',
{ funext a, exact type_eq_of_heq (this a) },
subst this,
apply heq_of_eq,
funext a,
exact eq_of_heq (this a)
end
lemma funext_iff {β : α → Sort*} {f₁ f₂ : Π (x : α), β x} : f₁ = f₂ ↔ (∀a, f₁ a = f₂ a) :=
iff.intro (assume h a, h ▸ rfl) funext
@[simp] theorem injective.eq_iff (I : injective f) {a b : α} :
f a = f b ↔ a = b :=
⟨@I _ _, congr_arg f⟩
theorem injective.eq_iff' (I : injective f) {a b : α} {c : β} (h : f b = c) :
f a = c ↔ a = b :=
h ▸ I.eq_iff
lemma injective.ne (hf : injective f) {a₁ a₂ : α} : a₁ ≠ a₂ → f a₁ ≠ f a₂ :=
mt (assume h, hf h)
lemma injective.ne_iff (hf : injective f) {x y : α} : f x ≠ f y ↔ x ≠ y :=
⟨mt $ congr_arg f, hf.ne⟩
lemma injective.ne_iff' (hf : injective f) {x y : α} {z : β} (h : f y = z) :
f x ≠ z ↔ x ≠ y :=
h ▸ hf.ne_iff
/-- If the co-domain `β` of an injective function `f : α → β` has decidable equality, then
the domain `α` also has decidable equality. -/
def injective.decidable_eq [decidable_eq β] (I : injective f) : decidable_eq α :=
λ a b, decidable_of_iff _ I.eq_iff
lemma injective.of_comp {g : γ → α} (I : injective (f ∘ g)) : injective g :=
λ x y h, I $ show f (g x) = f (g y), from congr_arg f h
lemma surjective.of_comp {g : γ → α} (S : surjective (f ∘ g)) : surjective f :=
λ y, let ⟨x, h⟩ := S y in ⟨g x, h⟩
instance decidable_eq_pfun (p : Prop) [decidable p] (α : p → Type*)
[Π hp, decidable_eq (α hp)] : decidable_eq (Π hp, α hp)
| f g := decidable_of_iff (∀ hp, f hp = g hp) funext_iff.symm
theorem surjective.forall {f : α → β} (hf : surjective f) {p : β → Prop} :
(∀ y, p y) ↔ ∀ x, p (f x) :=
⟨λ h x, h (f x), λ h y, let ⟨x, hx⟩ := hf y in hx ▸ h x⟩
theorem surjective.forall₂ {f : α → β} (hf : surjective f) {p : β → β → Prop} :
(∀ y₁ y₂, p y₁ y₂) ↔ ∀ x₁ x₂, p (f x₁) (f x₂) :=
hf.forall.trans $ forall_congr $ λ x, hf.forall
theorem surjective.forall₃ {f : α → β} (hf : surjective f) {p : β → β → β → Prop} :
(∀ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∀ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) :=
hf.forall.trans $ forall_congr $ λ x, hf.forall₂
theorem surjective.exists {f : α → β} (hf : surjective f) {p : β → Prop} :
(∃ y, p y) ↔ ∃ x, p (f x) :=
⟨λ ⟨y, hy⟩, let ⟨x, hx⟩ := hf y in ⟨x, hx.symm ▸ hy⟩, λ ⟨x, hx⟩, ⟨f x, hx⟩⟩
theorem surjective.exists₂ {f : α → β} (hf : surjective f) {p : β → β → Prop} :
(∃ y₁ y₂, p y₁ y₂) ↔ ∃ x₁ x₂, p (f x₁) (f x₂) :=
hf.exists.trans $ exists_congr $ λ x, hf.exists
theorem surjective.exists₃ {f : α → β} (hf : surjective f) {p : β → β → β → Prop} :
(∃ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∃ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) :=
hf.exists.trans $ exists_congr $ λ x, hf.exists₂
/-- Cantor's diagonal argument implies that there are no surjective functions from `α`
to `set α`. -/
theorem cantor_surjective {α} (f : α → set α) : ¬ function.surjective f | h :=
let ⟨D, e⟩ := h (λ a, ¬ f a a) in
(iff_not_self (f D D)).1 $ iff_of_eq (congr_fun e D)
/-- Cantor's diagonal argument implies that there are no injective functions from `set α` to `α`. -/
theorem cantor_injective {α : Type*} (f : (set α) → α) :
¬ function.injective f | i :=
cantor_surjective (λ a b, ∀ U, a = f U → U b) $
right_inverse.surjective (λ U, funext $ λ a, propext ⟨λ h, h U rfl, λ h' U' e, i e ▸ h'⟩)
/-- `g` is a partial inverse to `f` (an injective but not necessarily
surjective function) if `g y = some x` implies `f x = y`, and `g y = none`
implies that `y` is not in the range of `f`. -/
def is_partial_inv {α β} (f : α → β) (g : β → option α) : Prop :=
∀ x y, g y = some x ↔ f x = y
theorem is_partial_inv_left {α β} {f : α → β} {g} (H : is_partial_inv f g) (x) : g (f x) = some x :=
(H _ _).2 rfl
theorem injective_of_partial_inv {α β} {f : α → β} {g} (H : is_partial_inv f g) : injective f :=
λ a b h, option.some.inj $ ((H _ _).2 h).symm.trans ((H _ _).2 rfl)
theorem injective_of_partial_inv_right {α β} {f : α → β} {g} (H : is_partial_inv f g)
(x y b) (h₁ : b ∈ g x) (h₂ : b ∈ g y) : x = y :=
((H _ _).1 h₁).symm.trans ((H _ _).1 h₂)
theorem left_inverse.comp_eq_id {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id :=
funext h
theorem left_inverse_iff_comp {f : α → β} {g : β → α} : left_inverse f g ↔ f ∘ g = id :=
⟨left_inverse.comp_eq_id, congr_fun⟩
theorem right_inverse.comp_eq_id {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id :=
funext h
theorem right_inverse_iff_comp {f : α → β} {g : β → α} : right_inverse f g ↔ g ∘ f = id :=
⟨right_inverse.comp_eq_id, congr_fun⟩
theorem left_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β}
(hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) :=
assume a, show h (f (g (i a))) = a, by rw [hf (i a), hh a]
theorem right_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β}
(hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) :=
left_inverse.comp hh hf
theorem left_inverse.right_inverse {f : α → β} {g : β → α} (h : left_inverse g f) :
right_inverse f g := h
theorem right_inverse.left_inverse {f : α → β} {g : β → α} (h : right_inverse g f) :
left_inverse f g := h
theorem left_inverse.surjective {f : α → β} {g : β → α} (h : left_inverse f g) :
surjective f :=
h.right_inverse.surjective
theorem right_inverse.injective {f : α → β} {g : β → α} (h : right_inverse f g) :
injective f :=
h.left_inverse.injective
theorem left_inverse.eq_right_inverse {f : α → β} {g₁ g₂ : β → α} (h₁ : left_inverse g₁ f)
(h₂ : right_inverse g₂ f) :
g₁ = g₂ :=
calc g₁ = g₁ ∘ f ∘ g₂ : by rw [h₂.comp_eq_id, comp.right_id]
... = g₂ : by rw [← comp.assoc, h₁.comp_eq_id, comp.left_id]
local attribute [instance, priority 10] classical.prop_decidable
/-- We can use choice to construct explicitly a partial inverse for
a given injective function `f`. -/
noncomputable def partial_inv {α β} (f : α → β) (b : β) : option α :=
if h : ∃ a, f a = b then some (classical.some h) else none
theorem partial_inv_of_injective {α β} {f : α → β} (I : injective f) :
is_partial_inv f (partial_inv f) | a b :=
⟨λ h, if h' : ∃ a, f a = b then begin
rw [partial_inv, dif_pos h'] at h,
injection h with h, subst h,
apply classical.some_spec h'
end else by rw [partial_inv, dif_neg h'] at h; contradiction,
λ e, e ▸ have h : ∃ a', f a' = f a, from ⟨_, rfl⟩,
(dif_pos h).trans (congr_arg _ (I $ classical.some_spec h))⟩
theorem partial_inv_left {α β} {f : α → β} (I : injective f) : ∀ x, partial_inv f (f x) = some x :=
is_partial_inv_left (partial_inv_of_injective I)
end
section inv_fun
variables {α : Type u} [n : nonempty α] {β : Sort v} {f : α → β} {s : set α} {a : α} {b : β}
include n
local attribute [instance, priority 10] classical.prop_decidable
/-- Construct the inverse for a function `f` on domain `s`. This function is a right inverse of `f`
on `f '' s`. -/
noncomputable def inv_fun_on (f : α → β) (s : set α) (b : β) : α :=
if h : ∃a, a ∈ s ∧ f a = b then classical.some h else classical.choice n
theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b :=
by rw [bex_def] at h; rw [inv_fun_on, dif_pos h]; exact classical.some_spec h
theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left
theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right
theorem inv_fun_on_eq' (h : ∀ (x ∈ s) (y ∈ s), f x = f y → x = y) (ha : a ∈ s) :
inv_fun_on f s (f a) = a :=
have ∃a'∈s, f a' = f a, from ⟨a, ha, rfl⟩,
h _ (inv_fun_on_mem this) _ ha (inv_fun_on_eq this)
theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = classical.choice n :=
by rw [bex_def] at h; rw [inv_fun_on, dif_neg h]
/-- The inverse of a function (which is a left inverse if `f` is injective
and a right inverse if `f` is surjective). -/
noncomputable def inv_fun (f : α → β) : β → α := inv_fun_on f set.univ
theorem inv_fun_eq (h : ∃a, f a = b) : f (inv_fun f b) = b :=
inv_fun_on_eq $ let ⟨a, ha⟩ := h in ⟨a, trivial, ha⟩
lemma inv_fun_neg (h : ¬ ∃ a, f a = b) : inv_fun f b = classical.choice n :=
by refine inv_fun_on_neg (mt _ h); exact assume ⟨a, _, ha⟩, ⟨a, ha⟩
theorem inv_fun_eq_of_injective_of_right_inverse {g : β → α}
(hf : injective f) (hg : right_inverse g f) : inv_fun f = g :=
funext $ assume b,
hf begin rw [hg b], exact inv_fun_eq ⟨g b, hg b⟩ end
lemma right_inverse_inv_fun (hf : surjective f) : right_inverse (inv_fun f) f :=
assume b, inv_fun_eq $ hf b
lemma left_inverse_inv_fun (hf : injective f) : left_inverse (inv_fun f) f :=
assume b,
have f (inv_fun f (f b)) = f b,
from inv_fun_eq ⟨b, rfl⟩,
hf this
lemma inv_fun_surjective (hf : injective f) : surjective (inv_fun f) :=
(left_inverse_inv_fun hf).surjective
lemma inv_fun_comp (hf : injective f) : inv_fun f ∘ f = id := funext $ left_inverse_inv_fun hf
end inv_fun
section inv_fun
variables {α : Type u} [i : nonempty α] {β : Sort v} {f : α → β}
include i
lemma injective.has_left_inverse (hf : injective f) : has_left_inverse f :=
⟨inv_fun f, left_inverse_inv_fun hf⟩
lemma injective_iff_has_left_inverse : injective f ↔ has_left_inverse f :=
⟨injective.has_left_inverse, has_left_inverse.injective⟩
end inv_fun
section surj_inv
variables {α : Sort u} {β : Sort v} {f : α → β}
/-- The inverse of a surjective function. (Unlike `inv_fun`, this does not require
`α` to be inhabited.) -/
noncomputable def surj_inv {f : α → β} (h : surjective f) (b : β) : α := classical.some (h b)
lemma surj_inv_eq (h : surjective f) (b) : f (surj_inv h b) = b := classical.some_spec (h b)
lemma right_inverse_surj_inv (hf : surjective f) : right_inverse (surj_inv hf) f :=
surj_inv_eq hf
lemma left_inverse_surj_inv (hf : bijective f) : left_inverse (surj_inv hf.2) f :=
right_inverse_of_injective_of_left_inverse hf.1 (right_inverse_surj_inv hf.2)
lemma surjective.has_right_inverse (hf : surjective f) : has_right_inverse f :=
⟨_, right_inverse_surj_inv hf⟩
lemma surjective_iff_has_right_inverse : surjective f ↔ has_right_inverse f :=
⟨surjective.has_right_inverse, has_right_inverse.surjective⟩
lemma bijective_iff_has_inverse : bijective f ↔ ∃ g, left_inverse g f ∧ right_inverse g f :=
⟨λ hf, ⟨_, left_inverse_surj_inv hf, right_inverse_surj_inv hf.2⟩,
λ ⟨g, gl, gr⟩, ⟨gl.injective, gr.surjective⟩⟩
lemma injective_surj_inv (h : surjective f) : injective (surj_inv h) :=
(right_inverse_surj_inv h).injective
end surj_inv
section update
variables {α : Sort u} {β : α → Sort v} {α' : Sort w} [decidable_eq α] [decidable_eq α']
/-- Replacing the value of a function at a given point by a given value. -/
def update (f : Πa, β a) (a' : α) (v : β a') (a : α) : β a :=
if h : a = a' then eq.rec v h.symm else f a
@[simp] lemma update_same (a : α) (v : β a) (f : Πa, β a) : update f a v a = v :=
dif_pos rfl
@[simp] lemma update_noteq {a a' : α} (h : a ≠ a') (v : β a') (f : Πa, β a) : update f a' v a = f a :=
dif_neg h
@[simp] lemma update_eq_self (a : α) (f : Πa, β a) : update f a (f a) = f :=
begin
refine funext (λi, _),
by_cases h : i = a,
{ rw h, simp },
{ simp [h] }
end
lemma update_comp {β : Sort v} (f : α → β) {g : α' → α} (hg : injective g) (a : α') (v : β) :
(update f (g a) v) ∘ g = update (f ∘ g) a v :=
begin
refine funext (λi, _),
by_cases h : i = a,
{ rw h, simp },
{ simp [h, hg.ne] }
end
lemma apply_update {ι : Sort*} [decidable_eq ι] {α β : ι → Sort*}
(f : Π i, α i → β i) (g : Π i, α i) (i : ι) (v : α i) (j : ι) :
f j (update g i v j) = update (λ k, f k (g k)) i (f i v) j :=
begin
by_cases h : j = i,
{ subst j, simp },
{ simp [h] }
end
lemma comp_update {α' : Sort*} {β : Sort*} (f : α' → β) (g : α → α') (i : α) (v : α') :
f ∘ (update g i v) = update (f ∘ g) i (f v) :=
funext $ apply_update _ _ _ _
theorem update_comm {α} [decidable_eq α] {β : α → Sort*}
{a b : α} (h : a ≠ b) (v : β a) (w : β b) (f : Πa, β a) :
update (update f a v) b w = update (update f b w) a v :=
begin
funext c, simp [update],
by_cases h₁ : c = b; by_cases h₂ : c = a; try {simp [h₁, h₂]},
cases h (h₂.symm.trans h₁),
end
@[simp] theorem update_idem {α} [decidable_eq α] {β : α → Sort*}
{a : α} (v w : β a) (f : Πa, β a) : update (update f a v) a w = update f a w :=
by {funext b, by_cases b = a; simp [update, h]}
end update
section extend
noncomputable theory
local attribute [instance, priority 10] classical.prop_decidable
variables {α β γ : Type*} {f : α → β}
/-- `extend f g e'` extends a function `g : α → γ`
along a function `f : α → β` to a function `β → γ`,
by using the values of `g` on the range of `f`
and the values of an auxiliary function `e' : β → γ` elsewhere.
Mostly useful when `f` is injective. -/
def extend (f : α → β) (g : α → γ) (e' : β → γ) : β → γ :=
λ b, if h : ∃ a, f a = b then g (classical.some h) else e' b
lemma extend_def (f : α → β) (g : α → γ) (e' : β → γ) (b : β) :
extend f g e' b = if h : ∃ a, f a = b then g (classical.some h) else e' b := rfl
@[simp] lemma extend_apply (hf : injective f) (g : α → γ) (e' : β → γ) (a : α) :
extend f g e' (f a) = g a :=
begin
simp only [extend_def, dif_pos, exists_apply_eq_apply],
exact congr_arg g (hf $ classical.some_spec (exists_apply_eq_apply f a))
end
@[simp] lemma extend_comp (hf : injective f) (g : α → γ) (e' : β → γ) :
extend f g e' ∘ f = g :=
funext $ λ a, extend_apply hf g e' a
end extend
lemma uncurry_def {α β γ} (f : α → β → γ) : uncurry f = (λp, f p.1 p.2) :=
rfl
section bicomp
variables {α β γ δ ε : Type*}
/-- Compose a binary function `f` with a pair of unary functions `g` and `h`.
If both arguments of `f` have the same type and `g = h`, then `bicompl f g g = f on g`. -/
def bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) (a b) :=
f (g a) (h b)
/-- Compose an unary function `f` with a binary function `g`. -/
def bicompr (f : γ → δ) (g : α → β → γ) (a b) :=
f (g a b)
-- Suggested local notation:
local notation f `∘₂` g := bicompr f g
lemma uncurry_bicompr (f : α → β → γ) (g : γ → δ) :
uncurry (g ∘₂ f) = (g ∘ uncurry f) := rfl
lemma uncurry_bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) :
uncurry (bicompl f g h) = (uncurry f) ∘ (prod.map g h) :=
rfl
end bicomp
section uncurry
variables {α β γ δ : Type*}
/-- Records a way to turn an element of `α` into a function from `β` to `γ`. The most generic use
is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into
`↿f : α × β × γ → δ`. One can also add instances for bundled maps. -/
class has_uncurry (α : Type*) (β : out_param Type*) (γ : out_param Type*) := (uncurry : α → (β → γ))
/-- Uncurrying operator. The most generic use is to recursively uncurry. For instance
`f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances
for bundled maps.-/
add_decl_doc has_uncurry.uncurry
notation `↿`:max x:max := has_uncurry.uncurry x
instance has_uncurry_base : has_uncurry (α → β) α β := ⟨id⟩
instance has_uncurry_induction [has_uncurry β γ δ] : has_uncurry (α → β) (α × γ) δ :=
⟨λ f p, ↿(f p.1) p.2⟩
end uncurry
/-- A function is involutive, if `f ∘ f = id`. -/
def involutive {α} (f : α → α) : Prop := ∀ x, f (f x) = x
lemma involutive_iff_iter_2_eq_id {α} {f : α → α} : involutive f ↔ (f^[2] = id) :=
funext_iff.symm
namespace involutive
variables {α : Sort u} {f : α → α} (h : involutive f)
include h
@[simp]
lemma comp_self : f ∘ f = id := funext h
protected lemma left_inverse : left_inverse f f := h
protected lemma right_inverse : right_inverse f f := h
protected lemma injective : injective f := h.left_inverse.injective
protected lemma surjective : surjective f := λ x, ⟨f x, h x⟩
protected lemma bijective : bijective f := ⟨h.injective, h.surjective⟩
/-- Involuting an `ite` of an involuted value `x : α` negates the `Prop` condition in the `ite`. -/
protected lemma ite_not (P : Prop) [decidable P] (x : α) :
f (ite P x (f x)) = ite (¬ P) x (f x) :=
by rw [apply_ite f, h, ite_not]
end involutive
/-- The property of a binary function `f : α → β → γ` being injective.
Mathematically this should be thought of as the corresponding function `α × β → γ` being injective.
-/
@[reducible] def injective2 {α β γ} (f : α → β → γ) : Prop :=
∀ ⦃a₁ a₂ b₁ b₂⦄, f a₁ b₁ = f a₂ b₂ → a₁ = a₂ ∧ b₁ = b₂
namespace injective2
variables {α β γ : Type*} (f : α → β → γ)
protected lemma left (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ (h : f a₁ b₁ = f a₂ b₂) : a₁ = a₂ :=
(hf h).1
protected lemma right (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ (h : f a₁ b₁ = f a₂ b₂) : b₁ = b₂ :=
(hf h).2
lemma eq_iff (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ : f a₁ b₁ = f a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ :=
⟨λ h, hf h, λ⟨h1, h2⟩, congr_arg2 f h1 h2⟩
end injective2
section sometimes
local attribute [instance, priority 10] classical.prop_decidable
/-- `sometimes f` evaluates to some value of `f`, if it exists. This function is especially
interesting in the case where `α` is a proposition, in which case `f` is necessarily a
constant function, so that `sometimes f = f a` for all `a`. -/
noncomputable def sometimes {α β} [nonempty β] (f : α → β) : β :=
if h : nonempty α then f (classical.choice h) else classical.choice ‹_›
theorem sometimes_eq {p : Prop} {α} [nonempty α] (f : p → α) (a : p) : sometimes f = f a :=
dif_pos ⟨a⟩
theorem sometimes_spec {p : Prop} {α} [nonempty α]
(P : α → Prop) (f : p → α) (a : p) (h : P (f a)) : P (sometimes f) :=
by rwa sometimes_eq
end sometimes
end function
/-- `s.piecewise f g` is the function equal to `f` on the set `s`, and to `g` on its complement. -/
def set.piecewise {α : Type u} {β : α → Sort v} (s : set α) (f g : Πi, β i) [∀j, decidable (j ∈ s)] :
Πi, β i :=
λi, if i ∈ s then f i else g i
|
251f127317494c6f397c4c2dccf095e443f67bcb | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/homology/exact.lean | 7c69449a420ddd0b00a9cdc4801cb344bfe02a13 | [
"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 | 11,164 | lean | /-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import algebra.homology.image_to_kernel
/-!
# Exact sequences
In a category with zero morphisms, images, and equalizers we say that `f : A ⟶ B` and `g : B ⟶ C`
are exact if `f ≫ g = 0` and the natural map `image f ⟶ kernel g` is an epimorphism.
In any preadditive category this is equivalent to the homology at `B` vanishing.
However in general it is weaker than other reasonable definitions of exactness,
particularly that
1. the inclusion map `image.ι f` is a kernel of `g` or
2. `image f ⟶ kernel g` is an isomorphism or
3. `image_subobject f = kernel_subobject f`.
However when the category is abelian, these all become equivalent;
these results are found in `category_theory/abelian/exact.lean`.
# Main results
* Suppose that cokernels exist and that `f` and `g` are exact.
If `s` is any kernel fork over `g` and `t` is any cokernel cofork over `f`,
then `fork.ι s ≫ cofork.π t = 0`.
* Precomposing the first morphism with an epimorphism retains exactness.
Postcomposing the second morphism with a monomorphism retains exactness.
* If `f` and `g` are exact and `i` is an isomorphism,
then `f ≫ i.hom` and `i.inv ≫ g` are also exact.
# Future work
* Short exact sequences, split exact sequences, the splitting lemma (maybe only for abelian
categories?)
* Two adjacent maps in a chain complex are exact iff the homology vanishes
-/
universes v u
open category_theory
open category_theory.limits
variables {V : Type u} [category.{v} V]
variables [has_images V]
namespace category_theory
/--
Two morphisms `f : A ⟶ B`, `g : B ⟶ C` are called exact if `w : f ≫ g = 0` and the natural map
`image_to_kernel f g w : image_subobject f ⟶ kernel_subobject g` is an epimorphism.
In any preadditive category, this is equivalent to `w : f ≫ g = 0` and `homology f g w ≅ 0`.
In an abelian category, this is equivalent to `image_to_kernel f g w` being an isomorphism,
and hence equivalent to the usual definition,
`image_subobject f = kernel_subobject g`.
-/
-- One nice feature of this definition is that we have
-- `epi f → exact g h → exact (f ≫ g) h` and `exact f g → mono h → exact f (g ≫ h)`,
-- which do not necessarily hold in a non-abelian category with the usual definition of `exact`.
class exact [has_zero_morphisms V] [has_kernels V] {A B C : V} (f : A ⟶ B) (g : B ⟶ C) : Prop :=
(w : f ≫ g = 0)
(epi : epi (image_to_kernel f g w))
attribute [instance] exact.epi
attribute [simp, reassoc] exact.w
section
variables [has_zero_object V] [preadditive V] [has_kernels V] [has_cokernels V]
open_locale zero_object
/--
In any preadditive category,
composable morphisms `f g` are exact iff they compose to zero and the homology vanishes.
-/
lemma preadditive.exact_iff_homology_zero {A B C : V} (f : A ⟶ B) (g : B ⟶ C) :
exact f g ↔ ∃ w : f ≫ g = 0, nonempty (homology f g w ≅ 0) :=
⟨λ h, ⟨h.w, ⟨cokernel.of_epi _⟩⟩,
λ h, begin
obtain ⟨w, ⟨i⟩⟩ := h,
exact ⟨w, preadditive.epi_of_cokernel_zero ((cancel_mono i.hom).mp (by ext))⟩,
end⟩
lemma preadditive.exact_of_iso_of_exact {A₁ B₁ C₁ A₂ B₂ C₂ : V}
(f₁ : A₁ ⟶ B₁) (g₁ : B₁ ⟶ C₁) (f₂ : A₂ ⟶ B₂) (g₂ : B₂ ⟶ C₂)
(α : arrow.mk f₁ ≅ arrow.mk f₂) (β : arrow.mk g₁ ≅ arrow.mk g₂) (p : α.hom.right = β.hom.left)
(h : exact f₁ g₁) :
exact f₂ g₂ :=
begin
rw preadditive.exact_iff_homology_zero at h ⊢,
rcases h with ⟨w₁, ⟨i⟩⟩,
suffices w₂ : f₂ ≫ g₂ = 0, from ⟨w₂, ⟨(homology.map_iso w₁ w₂ α β p).symm.trans i⟩⟩,
rw [← cancel_epi α.hom.left, ← cancel_mono β.inv.right, comp_zero, zero_comp, ← w₁],
simp only [← arrow.mk_hom f₁, ← arrow.left_hom_inv_right α.hom,
← arrow.mk_hom g₁, ← arrow.left_hom_inv_right β.hom, p],
simp only [arrow.mk_hom, is_iso.inv_hom_id_assoc, category.assoc, ← arrow.inv_right,
is_iso.iso.inv_hom]
end
lemma preadditive.exact_iff_exact_of_iso {A₁ B₁ C₁ A₂ B₂ C₂ : V}
(f₁ : A₁ ⟶ B₁) (g₁ : B₁ ⟶ C₁) (f₂ : A₂ ⟶ B₂) (g₂ : B₂ ⟶ C₂)
(α : arrow.mk f₁ ≅ arrow.mk f₂) (β : arrow.mk g₁ ≅ arrow.mk g₂) (p : α.hom.right = β.hom.left) :
exact f₁ g₁ ↔ exact f₂ g₂ :=
⟨preadditive.exact_of_iso_of_exact _ _ _ _ _ _ p,
preadditive.exact_of_iso_of_exact _ _ _ _ α.symm β.symm
begin
rw ← cancel_mono α.hom.right,
simp only [iso.symm_hom, ← comma.comp_right, α.inv_hom_id],
simp only [p, ←comma.comp_left, arrow.id_right, arrow.id_left, iso.inv_hom_id],
refl
end⟩
end
section
variables [has_zero_morphisms V] [has_kernels V]
lemma comp_eq_zero_of_image_eq_kernel {A B C : V} (f : A ⟶ B) (g : B ⟶ C)
(p : image_subobject f = kernel_subobject g) : f ≫ g = 0 :=
begin
rw [←image_subobject_arrow_comp f, category.assoc],
convert comp_zero,
rw p,
simp,
end
lemma image_to_kernel_is_iso_of_image_eq_kernel {A B C : V} (f : A ⟶ B) (g : B ⟶ C)
(p : image_subobject f = kernel_subobject g) :
is_iso (image_to_kernel f g (comp_eq_zero_of_image_eq_kernel f g p)) :=
begin
refine ⟨⟨subobject.of_le _ _ p.ge, _⟩⟩,
dsimp [image_to_kernel],
simp only [subobject.of_le_comp_of_le, subobject.of_le_refl],
simp,
end
-- We'll prove the converse later, when `V` is abelian.
lemma exact_of_image_eq_kernel {A B C : V} (f : A ⟶ B) (g : B ⟶ C)
(p : image_subobject f = kernel_subobject g) : exact f g :=
{ w := comp_eq_zero_of_image_eq_kernel f g p,
epi := begin
haveI := image_to_kernel_is_iso_of_image_eq_kernel f g p,
apply_instance,
end }
end
variables {A B C D : V} {f : A ⟶ B} {g : B ⟶ C} {h : C ⟶ D}
local attribute [instance] epi_comp
section
variables [has_zero_morphisms V] [has_equalizers V]
instance exact_comp_hom_inv_comp [exact f g] (i : B ≅ D) : exact (f ≫ i.hom) (i.inv ≫ g) :=
begin
refine ⟨by simp, _⟩,
rw image_to_kernel_comp_hom_inv_comp,
apply_instance,
end
instance exact_comp_inv_hom_comp [exact f g] (i : D ≅ B) : exact (f ≫ i.inv) (i.hom ≫ g) :=
category_theory.exact_comp_hom_inv_comp i.symm
lemma exact_comp_hom_inv_comp_iff (i : B ≅ D) : exact (f ≫ i.hom) (i.inv ≫ g) ↔ exact f g :=
begin
refine ⟨_, by { introI, apply_instance }⟩,
introI,
have : exact ((f ≫ i.hom) ≫ i.inv) (i.hom ≫ i.inv ≫ g) := infer_instance,
simpa using this
end
lemma exact_epi_comp [exact g h] [epi f] : exact (f ≫ g) h :=
begin
refine ⟨by simp, _⟩,
rw image_to_kernel_comp_left,
apply_instance,
end
@[simp]
lemma exact_iso_comp [is_iso f] : exact (f ≫ g) h ↔ exact g h :=
⟨λ w, by { rw ←is_iso.inv_hom_id_assoc f g, exactI exact_epi_comp, }, λ w, by exactI exact_epi_comp⟩
lemma exact_comp_mono [exact f g] [mono h] : exact f (g ≫ h) :=
begin
refine ⟨by simp, _⟩,
rw image_to_kernel_comp_right f g h exact.w,
apply_instance,
end
@[simp]
lemma exact_comp_iso [is_iso h] : exact f (g ≫ h) ↔ exact f g :=
⟨λ w, begin
rw [←category.comp_id g, ←is_iso.hom_inv_id h, ←category.assoc],
exactI exact_comp_mono,
end,
λ w, by exactI exact_comp_mono⟩
lemma exact_kernel_subobject_arrow : exact (kernel_subobject f).arrow f :=
begin
refine ⟨by simp, _⟩,
apply @is_iso.epi_of_iso _ _ _ _ _ _,
exact ⟨⟨factor_thru_image_subobject _, by { ext, simp, }, by { ext, simp, }⟩⟩,
end
lemma exact_kernel_ι : exact (kernel.ι f) f :=
by { rw [←kernel_subobject_arrow', exact_iso_comp], exact exact_kernel_subobject_arrow }
instance [exact f g] : epi (factor_thru_kernel_subobject g f (by simp)) :=
begin
rw ←factor_thru_image_subobject_comp_image_to_kernel,
apply epi_comp,
end
instance [exact f g] : epi (kernel.lift g f (by simp)) :=
begin
rw ←factor_thru_kernel_subobject_comp_kernel_subobject_iso,
apply epi_comp
end
variables (A)
lemma kernel_subobject_arrow_eq_zero_of_exact_zero_left [exact (0 : A ⟶ B) g] :
(kernel_subobject g).arrow = 0 :=
begin
rw [←cancel_epi (image_to_kernel (0 : A ⟶ B) g exact.w),
←cancel_epi (factor_thru_image_subobject (0 : A ⟶ B))],
simp
end
lemma kernel_ι_eq_zero_of_exact_zero_left [exact (0 : A ⟶ B) g] :
kernel.ι g = 0 :=
by { rw ←kernel_subobject_arrow', simp [kernel_subobject_arrow_eq_zero_of_exact_zero_left A], }
lemma exact_zero_left_of_mono [has_zero_object V] [mono g] : exact (0 : A ⟶ B) g :=
⟨by simp, image_to_kernel_epi_of_zero_of_mono _⟩
end
section has_cokernels
variables [has_zero_morphisms V] [has_equalizers V] [has_cokernels V] (f g)
@[simp, reassoc] lemma kernel_comp_cokernel [exact f g] : kernel.ι g ≫ cokernel.π f = 0 :=
begin
rw [←kernel_subobject_arrow', category.assoc],
convert comp_zero,
apply zero_of_epi_comp (image_to_kernel f g exact.w) _,
rw [image_to_kernel_arrow_assoc, ←image_subobject_arrow, category.assoc, ←iso.eq_inv_comp],
ext,
simp,
end
lemma comp_eq_zero_of_exact [exact f g] {X Y : V} {ι : X ⟶ B} (hι : ι ≫ g = 0) {π : B ⟶ Y}
(hπ : f ≫ π = 0) : ι ≫ π = 0 :=
by rw [←kernel.lift_ι _ _ hι, ←cokernel.π_desc _ _ hπ, category.assoc, kernel_comp_cokernel_assoc,
zero_comp, comp_zero]
@[simp, reassoc] lemma fork_ι_comp_cofork_π [exact f g] (s : kernel_fork g)
(t : cokernel_cofork f) : fork.ι s ≫ cofork.π t = 0 :=
comp_eq_zero_of_exact f g (kernel_fork.condition s) (cokernel_cofork.condition t)
end has_cokernels
section
variables [has_zero_object V]
open_locale zero_object
section
variables [has_zero_morphisms V] [has_kernels V]
instance exact_of_zero {A C : V} (f : A ⟶ 0) (g : 0 ⟶ C) : exact f g :=
begin
obtain rfl : f = 0 := by ext,
obtain rfl : g = 0 := by ext,
fsplit,
{ simp, },
{ exact image_to_kernel_epi_of_zero_of_mono 0, },
end
instance exact_zero_mono {B C : V} (f : B ⟶ C) [mono f] : exact (0 : (0 ⟶ B)) f :=
⟨by simp, infer_instance⟩
instance exact_epi_zero {A B : V} (f : A ⟶ B) [epi f] : exact f (0 : (B ⟶ 0)) :=
⟨by simp, infer_instance⟩
end
section
variables [preadditive V]
lemma mono_iff_exact_zero_left [has_kernels V]{B C : V} (f : B ⟶ C) :
mono f ↔ exact (0 : (0 ⟶ B)) f :=
⟨λ h, by { resetI, apply_instance, },
λ h, preadditive.mono_of_kernel_iso_zero
((kernel_subobject_iso f).symm ≪≫ iso_zero_of_epi_zero (by simpa using h.epi))⟩
lemma epi_iff_exact_zero_right [has_equalizers V] {A B : V} (f : A ⟶ B) :
epi f ↔ exact f (0 : (B ⟶ 0)) :=
⟨λ h, by { resetI, apply_instance, },
λ h, begin
have e₁ := h.epi,
rw image_to_kernel_zero_right at e₁,
have e₂ : epi (((image_subobject f).arrow ≫ inv (kernel_subobject 0).arrow) ≫
(kernel_subobject 0).arrow) := @epi_comp _ _ _ _ _ _ e₁ _ _,
rw [category.assoc, is_iso.inv_hom_id, category.comp_id] at e₂,
rw [←image_subobject_arrow] at e₂,
resetI,
haveI : epi (image.ι f) := epi_of_epi (image_subobject_iso f).hom (image.ι f),
apply epi_of_epi_image,
end⟩
end
end
end category_theory
|
2899170730be9c5e86d8d9b5948b3b73b0a82aa2 | fddcf4b659baa121761c71be606b3f74b86fa695 | /practice_questions.lean | a81e48535611e2556d519d17a5efefaecae59bdf | [] | no_license | swarnpriya/Lean | 4218df9392f396cd7e5e745de35a917536ebd2bb | a0a9978fd058041eb1a09aec0e2dd7d19a7436a7 | refs/heads/master | 1,595,831,634,399 | 1,568,673,127,000 | 1,568,673,127,000 | 208,903,604 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,339 | lean | -- Chapter 3 Exercises
-- Question 1
-- Commutativity of ∧
example (p q : Prop) : p ∧ q <-> q ∧ p :=
begin
apply iff.intro,
intro h,
have hp : p, from and.left h,
have hq : q, from and.right h,
show q ∧ p, from and.intro hq hp,
intro g,
have hq' : q, from and.left g,
have hp' : p, from and.right g,
show p ∧ q, from and.intro hp' hq'
end
-- Question 2
-- Commutativity of ∨
example (p q : Prop) : p ∨ q <-> q ∨ p :=
begin
apply iff.intro,
intro h,
apply or.elim h,
intro h1,
apply or.inr,
exact h1,
intro h2,
apply or.inl,
exact h2,
intro h',
apply or.elim h',
intro h1,
apply or.inr,
exact h1,
intro h2,
apply or.inl,
exact h2,
end
--Question 3
-- Associativity of ∧
example (p q r : Prop) :
(p ∧ q) ∧ r ↔ p ∧ (q ∧ r) :=
begin
apply iff.intro,
intro h,
apply and.intro,
have hp : (p ∧ q), from and.left h,
have hp' : p, from and.left hp,
show p, from hp',
apply and.intro,
have hp : (p ∧ q), from and.left h,
have hp' : p, from and.left hp,
have hq : q, from and.right hp,
show q, from hq,
have hr : r, from and.right h,
show r, from hr,
intro h',
apply and.intro,
apply and.elim h',
intro h1,
intro h2,
apply and.intro,
exact h1,
apply and.left h2,
apply and.elim h',
intro h1,
intro h2,
apply and.right h2
end
-- Question 4
-- Associativity of ∨
example (p q r : Prop) : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) :=
begin
apply iff.intro,
intro h,
apply or.elim h,
intro h1,
apply or.elim h1,
intro h2,
apply or.inl,
apply h2,
intro h3,
apply or.inr,
apply or.inl,
exact h3,
intro h4,
apply or.inr,
apply or.inr,
exact h4,
intro,
apply or.inl,
apply or.elim a,
intro,
apply or.inl,
assumption,
intro,
apply or.inr,
apply or.elim a_1,
intro,
assumption,
intro,
exfalso,
admit
end
-- Question 5
-- Distributivity of ∧
example (p q r : Prop) :
p ∧ (q ∨ r) <-> (p ∧ q) ∨ (p ∧ r) :=
begin
apply iff.intro,
intro h,
apply or.elim (and.right h),
intro hq,
apply or.inl,
apply and.intro,
apply and.left h,
exact hq,
intro hr,
apply or.inr,
apply and.intro,
apply and.left h,
exact hr,
intro h',
apply or.elim h',
intro h1,
apply and.intro,
apply and.left h1,
apply or.inl,
apply and.right h1,
intro h'',
apply and.intro,
apply and.left h'',
apply or.inr,
apply and.right h'',
end
-- Question 6
-- Distributivity of ∨
example (p q r : Prop) :
p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) :=
begin
apply iff.intro,
intro h,
apply and.intro,
apply or.elim h,
intro h1,
apply or.inl,
exact h1,
intro h2,
apply or.inr,
apply and.left h2,
apply or.elim h,
intro h3,
apply or.inl,
exact h3,
intro h4,
apply or.inr,
apply and.right h4,
intro h',
apply or.elim (and.left h'),
intro h1,
apply or.inl,
exact h1,
intro h2,
apply or.inr,
apply and.intro,
exact h2,
admit
end
--Question 7
example (p q : Prop) : p ∧ ¬q → ¬(p → q) :=
begin
intro h,
intro h',
apply and.right h,
apply h',
apply and.left h
end
--Question 8
example (p : Prop) : ¬(p ∧ ¬p) :=
begin
intro h,
apply and.right h,
apply and.left h
end
--Question 9
example (p q : Prop) : ¬p ∨ ¬q → ¬(p ∧ q) :=
begin
intro h,
intro h',
apply or.elim h,
intro h'',
apply h'',
apply and.left h',
intro h1,
apply h1,
apply and.right h'
end
--Question 10
example (p q r : Prop) : (p → (q → r)) ↔ (p ∧ q → r) :=
begin
apply iff.intro,
intros,
apply a,
apply a_1.left,
apply a_1.right,
intros,
apply a,
apply and.intro,
assumption,
assumption
end
--Question 11
example (p q: Prop) : (p → q) → (¬q → ¬p) :=
begin
intros,
intro,
apply a_1,
apply a,
apply a_2
end
--Question 12
example (p : Prop) : ¬(p ↔ ¬p) :=
begin
intro,
apply iff.elim_left a,
apply iff.elim_right a,
intro,
apply iff.elim_left a,
assumption,
assumption,
apply iff.elim_right a,
intro,
apply iff.elim_left a,
assumption,
assumption
end
--Question 13
example (p : Prop) : p ∧ false ↔ false :=
begin
apply iff.intro,
intro,
apply and.right a,
intro,
apply and.intro,
exfalso,
assumption,
assumption
end
--Question 14
example (p : Prop) : p ∨ false ↔ p :=
begin
apply iff.intro,
intro,
apply or.elim a,
intro,
assumption,
intro,
exfalso,
assumption,
intro,
apply or.inl,
assumption
end
--Question 15
example (p q : Prop) : (¬p ∨ q) → (p → q) :=
begin
intro,
intro,
apply or.elim a,
intro,
exfalso,
apply a_2,
assumption,
intro,
apply a_2
end
--Question 16
example (p q : Prop) : ¬p → (p → q) :=
begin
intro,
intro,
exfalso,
apply a,
assumption
end
--Question 17
example (p : Prop) : p ∨ ¬p :=
begin
apply or.inr,
admit
end
--Question 18
example (p q : Prop) : (¬q → ¬p) → (p → q) :=
begin
intro,
intro,
admit
end
--Question 19
example (p q : Prop) : (p → q) → (¬p ∨ q) :=
begin
intro,
apply or.inr,
apply a,
admit
end
--Question 20
example (p q : Prop) : (((p → q) → p) → p) :=
begin
intro,
apply a,
intro,
admit
end
--Question 21
example (p q : Prop) : ¬(p → q) → p ∧ ¬q :=
begin
intro,
apply and.intro,
exfalso,
admit
end
--Question 22
example (p q : Prop) : ¬(p ∧ q) → ¬p ∨ ¬q :=
begin
intro,
apply or.inl,
intro,
apply a,
apply and.intro,
assumption,
exfalso,
apply a,
admit
end
--Question 23
example (p r s : Prop) : (p → r ∨ s) → ((p → r) ∨ (p → s)) :=
begin
intro,
apply or.inr,
intro,
admit
end
--Question 24
example (p q r : Prop) : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) :=
begin
apply iff.intro,
intro,
apply and.intro,
intro,
apply a,
apply or.inl,
assumption,
intro,
apply a,
apply or.inr,
assumption,
intro,
intro,
apply and.left a,
admit
end
--Question 25
example (p q : Prop) : ¬(p ∨ q) ↔ ¬p ∧ ¬q :=
begin
apply iff.intro,
intro,
apply and.intro,
intro,
apply a,
apply or.inl,
assumption,
intro,
apply a,
right,
assumption,
intro,
intro,
apply and.left a,
apply or.elim a_1,
intro,
assumption,
intro,
exfalso,
apply and.right a,
assumption
end
--Question 26
example (p : Prop) : ¬(p ↔ ¬ p) :=
begin
intro,
apply iff.elim_left a,
admit
end
--Chapter 4 Exercises
variables (α : Type) (p q : α → Prop)
variable a : α
variable r : Prop
--Question 1
example : (∃ x : α, r) → r :=
begin
intro h,
cases h with x r,
assumption
end
--Question 2
example : r → (∃ x : α, r) :=
begin
intro h,
admit
end
--Question 3
example: (∃x: α, true) → (∀x, p x ∧ r) → (∀x, p x) ∧ r :=
begin
intro h,
assume H1 : (∃x: α, true),
assume H2 : (∀x, p x ∧ r),
obtain x0 T0, from H₁,
have H₃ : p x₀ ∧ r, from H₂ x₀,
have Hpx : p x₀, from and.left H₃,
have Hr : r, from and.right H₃,
have Hapx : (∀x, p x), from
(take x, and.left (H₂ x)),
show (∀x, p x) ∧ r, from and.intro Hapx Hr
example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) :=
begin
apply iff.intro,
intro h,
apply or.inl,
apply or.elim h,
apply iff.intro
(assume ⟨a, (h1 : p a ∨ q a)⟩,
or.elim h1
(assume hpa : p a, or.inl ⟨a, hpa⟩)
(assume hqa : q a, or.inr ⟨a, hqa⟩))
(assume h : (∃ x, p x) ∨ (∃ x, q x),
or.elim h
(assume ⟨a, hpa⟩, ⟨a, (or.inl hpa)⟩)
(assume ⟨a, hqa⟩, ⟨a, (or.inr hqa)⟩))
|
7508993fc93e0bdb4542219a61bfe0816c8334b1 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/data/seq/seq.lean | 74d600162366b23ed9bae8559c018098d9b5c774 | [
"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 | 28,835 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.list.basic
import data.lazy_list
import data.nat.basic
import data.stream.init
import data.seq.computation
universes u v w
/-
coinductive seq (α : Type u) : Type u
| nil : seq α
| cons : α → seq α → seq α
-/
/--
A stream `s : option α` is a sequence if `s.nth n = none` implies `s.nth (n + 1) = none`.
-/
def stream.is_seq {α : Type u} (s : stream (option α)) : Prop :=
∀ {n : ℕ}, s n = none → s (n + 1) = none
/-- `seq α` is the type of possibly infinite lists (referred here as sequences).
It is encoded as an infinite stream of options such that if `f n = none`, then
`f m = none` for all `m ≥ n`. -/
def seq (α : Type u) : Type u := {f : stream (option α) // f.is_seq}
/-- `seq1 α` is the type of nonempty sequences. -/
def seq1 (α) := α × seq α
namespace seq
variables {α : Type u} {β : Type v} {γ : Type w}
/-- The empty sequence -/
def nil : seq α := ⟨stream.const none, λ n h, rfl⟩
instance : inhabited (seq α) := ⟨nil⟩
/-- Prepend an element to a sequence -/
def cons (a : α) (s : seq α) : seq α :=
⟨some a :: s.1, begin
rintros (n | _) h,
{ contradiction },
{ exact s.2 h }
end⟩
/-- Get the nth element of a sequence (if it exists) -/
def nth : seq α → ℕ → option α := subtype.val
@[simp] theorem nth_mk (f hf) : @nth α ⟨f, hf⟩ = f := rfl
@[simp] theorem nth_nil (n : ℕ) : (@nil α).nth n = none := rfl
@[simp] theorem nth_cons_zero (a : α) (s : seq α) : (cons a s).nth 0 = some a := rfl
@[simp] theorem nth_cons_succ (a : α) (s : seq α) (n : ℕ) : (cons a s).nth (n + 1) = s.nth n := rfl
@[ext] protected lemma ext {s t : seq α} (h : ∀ n : ℕ, s.nth n = t.nth n) : s = t :=
subtype.eq $ funext h
lemma cons_injective2 : function.injective2 (cons : α → seq α → seq α) :=
λ x y s t h, ⟨by rw [←option.some_inj, ←nth_cons_zero, h, nth_cons_zero],
seq.ext $ λ n, by simp_rw [←nth_cons_succ x s n, h, nth_cons_succ]⟩
lemma cons_left_injective (s : seq α) : function.injective (λ x, cons x s) :=
cons_injective2.left _
lemma cons_right_injective (x : α) : function.injective (cons x) :=
cons_injective2.right _
/-- A sequence has terminated at position `n` if the value at position `n` equals `none`. -/
def terminated_at (s : seq α) (n : ℕ) : Prop := s.nth n = none
/-- It is decidable whether a sequence terminates at a given position. -/
instance terminated_at_decidable (s : seq α) (n : ℕ) : decidable (s.terminated_at n) :=
decidable_of_iff' (s.nth n).is_none $ by unfold terminated_at; cases s.nth n; simp
/-- A sequence terminates if there is some position `n` at which it has terminated. -/
def terminates (s : seq α) : Prop := ∃ (n : ℕ), s.terminated_at n
theorem not_terminates_iff {s : seq α} : ¬ s.terminates ↔ ∀ n, (s.nth n).is_some :=
by simp [terminates, terminated_at, ←ne.def, option.ne_none_iff_is_some]
/-- Functorial action of the functor `option (α × _)` -/
@[simp] def omap (f : β → γ) : option (α × β) → option (α × γ)
| none := none
| (some (a, b)) := some (a, f b)
/-- Get the first element of a sequence -/
def head (s : seq α) : option α := nth s 0
/-- Get the tail of a sequence (or `nil` if the sequence is `nil`) -/
def tail (s : seq α) : seq α := ⟨s.1.tail, λ n, by { cases s with f al, exact al }⟩
protected def mem (a : α) (s : seq α) := some a ∈ s.1
instance : has_mem α (seq α) :=
⟨seq.mem⟩
theorem le_stable (s : seq α) {m n} (h : m ≤ n) : s.nth m = none → s.nth n = none :=
by { cases s with f al, induction h with n h IH, exacts [id, λ h2, al (IH h2)] }
/-- If a sequence terminated at position `n`, it also terminated at `m ≥ n `. -/
lemma terminated_stable : ∀ (s : seq α) {m n : ℕ}, m ≤ n → s.terminated_at m →
s.terminated_at n :=
le_stable
/--
If `s.nth n = some aₙ` for some value `aₙ`, then there is also some value `aₘ` such
that `s.nth = some aₘ` for `m ≤ n`.
-/
lemma ge_stable (s : seq α) {aₙ : α} {n m : ℕ} (m_le_n : m ≤ n)
(s_nth_eq_some : s.nth n = some aₙ) :
∃ (aₘ : α), s.nth m = some aₘ :=
have s.nth n ≠ none, by simp [s_nth_eq_some],
have s.nth m ≠ none, from mt (s.le_stable m_le_n) this,
option.ne_none_iff_exists'.mp this
theorem not_mem_nil (a : α) : a ∉ @nil α :=
λ ⟨n, (h : some a = none)⟩, by injection h
theorem mem_cons (a : α) : ∀ (s : seq α), a ∈ cons a s
| ⟨f, al⟩ := stream.mem_cons (some a) _
theorem mem_cons_of_mem (y : α) {a : α} : ∀ {s : seq α}, a ∈ s → a ∈ cons y s
| ⟨f, al⟩ := stream.mem_cons_of_mem (some y)
theorem eq_or_mem_of_mem_cons {a b : α} : ∀ {s : seq α}, a ∈ cons b s → a = b ∨ a ∈ s
| ⟨f, al⟩ h := (stream.eq_or_mem_of_mem_cons h).imp_left (λ h, by injection h)
@[simp] theorem mem_cons_iff {a b : α} {s : seq α} : a ∈ cons b s ↔ a = b ∨ a ∈ s :=
⟨eq_or_mem_of_mem_cons, by rintro (rfl|m); [apply mem_cons, exact mem_cons_of_mem _ m]⟩
/-- Destructor for a sequence, resulting in either `none` (for `nil`) or
`some (a, s)` (for `cons a s`). -/
def destruct (s : seq α) : option (seq1 α) :=
(λ a', (a', s.tail)) <$> nth s 0
theorem destruct_eq_nil {s : seq α} : destruct s = none → s = nil :=
begin
dsimp [destruct],
induction f0 : nth s 0; intro h,
{ apply subtype.eq,
funext n,
induction n with n IH, exacts [f0, s.2 IH] },
{ contradiction }
end
theorem destruct_eq_cons {s : seq α} {a s'} : destruct s = some (a, s') → s = cons a s' :=
begin
dsimp [destruct],
induction f0 : nth s 0 with a'; intro h,
{ contradiction },
{ cases s with f al,
injections with _ h1 h2,
rw ←h2, apply subtype.eq, dsimp [tail, cons],
rw h1 at f0, rw ←f0,
exact (stream.eta f).symm }
end
@[simp] theorem destruct_nil : destruct (nil : seq α) = none := rfl
@[simp] theorem destruct_cons (a : α) : ∀ s, destruct (cons a s) = some (a, s)
| ⟨f, al⟩ := begin
unfold cons destruct functor.map,
apply congr_arg (λ s, some (a, s)),
apply subtype.eq, dsimp [tail], rw [stream.tail_cons]
end
theorem head_eq_destruct (s : seq α) : head s = prod.fst <$> destruct s :=
by unfold destruct head; cases nth s 0; refl
@[simp] theorem head_nil : head (nil : seq α) = none := rfl
@[simp] theorem head_cons (a : α) (s) : head (cons a s) = some a :=
by rw [head_eq_destruct, destruct_cons]; refl
@[simp] theorem tail_nil : tail (nil : seq α) = nil := rfl
@[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s :=
by cases s with f al; apply subtype.eq; dsimp [tail, cons]; rw [stream.tail_cons]
@[simp] theorem nth_tail (s : seq α) (n) : nth (tail s) n = nth s (n + 1) := rfl
def cases_on {C : seq α → Sort v} (s : seq α)
(h1 : C nil) (h2 : ∀ x s, C (cons x s)) : C s := begin
induction H : destruct s with v v,
{ rw destruct_eq_nil H, apply h1 },
{ cases v with a s', rw destruct_eq_cons H, apply h2 }
end
theorem mem_rec_on {C : seq α → Prop} {a s} (M : a ∈ s)
(h1 : ∀ b s', (a = b ∨ C s') → C (cons b s')) : C s :=
begin
cases M with k e, unfold stream.nth at e,
induction k with k IH generalizing s,
{ have TH : s = cons a (tail s),
{ apply destruct_eq_cons,
unfold destruct nth functor.map, rw ←e, refl },
rw TH, apply h1 _ _ (or.inl rfl) },
revert e, apply s.cases_on _ (λ b s', _); intro e,
{ injection e },
{ have h_eq : (cons b s').val (nat.succ k) = s'.val k, { cases s'; refl },
rw [h_eq] at e,
apply h1 _ _ (or.inr (IH e)) }
end
def corec.F (f : β → option (α × β)) : option β → option α × option β
| none := (none, none)
| (some b) := match f b with none := (none, none) | some (a, b') := (some a, some b') end
/-- Corecursor for `seq α` as a coinductive type. Iterates `f` to produce new elements
of the sequence until `none` is obtained. -/
def corec (f : β → option (α × β)) (b : β) : seq α :=
begin
refine ⟨stream.corec' (corec.F f) (some b), λ n h, _⟩,
rw stream.corec'_eq,
change stream.corec' (corec.F f) (corec.F f (some b)).2 n = none,
revert h, generalize : some b = o, revert o,
induction n with n IH; intro o,
{ change (corec.F f o).1 = none → (corec.F f (corec.F f o).2).1 = none,
cases o with b; intro h, { refl },
dsimp [corec.F] at h, dsimp [corec.F],
cases f b with s, { refl },
{ cases s with a b', contradiction } },
{ rw [stream.corec'_eq (corec.F f) (corec.F f o).2,
stream.corec'_eq (corec.F f) o],
exact IH (corec.F f o).2 }
end
@[simp] theorem corec_eq (f : β → option (α × β)) (b : β) :
destruct (corec f b) = omap (corec f) (f b) :=
begin
dsimp [corec, destruct, nth],
change stream.corec' (corec.F f) (some b) 0 with (corec.F f (some b)).1,
dsimp [corec.F],
induction h : f b with s, { refl },
cases s with a b', dsimp [corec.F],
apply congr_arg (λ b', some (a, b')),
apply subtype.eq,
dsimp [corec, tail],
rw [stream.corec'_eq, stream.tail_cons],
dsimp [corec.F], rw h, refl
end
section bisim
variable (R : seq α → seq α → Prop)
local infix (name := R) ` ~ `:50 := R
def bisim_o : option (seq1 α) → option (seq1 α) → Prop
| none none := true
| (some (a, s)) (some (a', s')) := a = a' ∧ R s s'
| _ _ := false
attribute [simp] bisim_o
def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → bisim_o R (destruct s₁) (destruct s₂)
-- If two streams are bisimilar, then they are equal
theorem eq_of_bisim (bisim : is_bisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ :=
begin
apply subtype.eq,
apply stream.eq_of_bisim (λ x y, ∃ s s' : seq α, s.1 = x ∧ s'.1 = y ∧ R s s'),
dsimp [stream.is_bisimulation],
intros t₁ t₂ e,
exact match t₁, t₂, e with ._, ._, ⟨s, s', rfl, rfl, r⟩ :=
suffices head s = head s' ∧ R (tail s) (tail s'), from
and.imp id (λ r, ⟨tail s, tail s',
by cases s; refl, by cases s'; refl, r⟩) this,
begin
have := bisim r, revert r this,
apply cases_on s _ _; intros; apply cases_on s' _ _; intros; intros r this,
{ constructor, refl, assumption },
{ rw [destruct_nil, destruct_cons] at this,
exact false.elim this },
{ rw [destruct_nil, destruct_cons] at this,
exact false.elim this },
{ rw [destruct_cons, destruct_cons] at this,
rw [head_cons, head_cons, tail_cons, tail_cons],
cases this with h1 h2,
constructor, rw h1, exact h2 }
end
end,
exact ⟨s₁, s₂, rfl, rfl, r⟩
end
end bisim
theorem coinduction : ∀ {s₁ s₂ : seq α}, head s₁ = head s₂ →
(∀ (β : Type u) (fr : seq α → β),
fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂
| ⟨f₁, a₁⟩ ⟨f₂, a₂⟩ hh ht :=
subtype.eq (stream.coinduction hh (λ β fr, ht β (λ s, fr s.1)))
theorem coinduction2 (s) (f g : seq α → seq β)
(H : ∀ s, bisim_o (λ (s1 s2 : seq β), ∃ (s : seq α), s1 = f s ∧ s2 = g s)
(destruct (f s)) (destruct (g s)))
: f s = g s :=
begin
refine eq_of_bisim (λ s1 s2, ∃ s, s1 = f s ∧ s2 = g s) _ ⟨s, rfl, rfl⟩,
intros s1 s2 h, rcases h with ⟨s, h1, h2⟩,
rw [h1, h2], apply H
end
/-- Embed a list as a sequence -/
def of_list (l : list α) : seq α :=
⟨list.nth l, λ n h, begin
rw list.nth_eq_none_iff at h ⊢,
exact h.trans (nat.le_succ n)
end⟩
instance coe_list : has_coe (list α) (seq α) := ⟨of_list⟩
@[simp] theorem of_list_nil : of_list [] = (nil : seq α) := rfl
@[simp] theorem of_list_nth (l : list α) (n : ℕ) : (of_list l).nth n = l.nth n := rfl
@[simp] theorem of_list_cons (a : α) (l : list α) : of_list (a :: l) = cons a (of_list l) :=
by ext1 (_|n); refl
/-- Embed an infinite stream as a sequence -/
def of_stream (s : stream α) : seq α :=
⟨s.map some, λ n h, by contradiction⟩
instance coe_stream : has_coe (stream α) (seq α) := ⟨of_stream⟩
/-- Embed a `lazy_list α` as a sequence. Note that even though this
is non-meta, it will produce infinite sequences if used with
cyclic `lazy_list`s created by meta constructions. -/
def of_lazy_list : lazy_list α → seq α :=
corec (λ l, match l with
| lazy_list.nil := none
| lazy_list.cons a l' := some (a, l' ())
end)
instance coe_lazy_list : has_coe (lazy_list α) (seq α) := ⟨of_lazy_list⟩
/-- Translate a sequence into a `lazy_list`. Since `lazy_list` and `list`
are isomorphic as non-meta types, this function is necessarily meta. -/
meta def to_lazy_list : seq α → lazy_list α | s :=
match destruct s with
| none := lazy_list.nil
| some (a, s') := lazy_list.cons a (to_lazy_list s')
end
/-- Translate a sequence to a list. This function will run forever if
run on an infinite sequence. -/
meta def force_to_list (s : seq α) : list α := (to_lazy_list s).to_list
/-- The sequence of natural numbers some 0, some 1, ... -/
def nats : seq ℕ := stream.nats
@[simp]
lemma nats_nth (n : ℕ) : nats.nth n = some n := rfl
/-- Append two sequences. If `s₁` is infinite, then `s₁ ++ s₂ = s₁`,
otherwise it puts `s₂` at the location of the `nil` in `s₁`. -/
def append (s₁ s₂ : seq α) : seq α :=
@corec α (seq α × seq α) (λ ⟨s₁, s₂⟩,
match destruct s₁ with
| none := omap (λ s₂, (nil, s₂)) (destruct s₂)
| some (a, s₁') := some (a, s₁', s₂)
end) (s₁, s₂)
/-- Map a function over a sequence. -/
def map (f : α → β) : seq α → seq β | ⟨s, al⟩ :=
⟨s.map (option.map f),
λ n, begin
dsimp [stream.map, stream.nth],
induction e : s n; intro,
{ rw al e, assumption }, { contradiction }
end⟩
/-- Flatten a sequence of sequences. (It is required that the
sequences be nonempty to ensure productivity; in the case
of an infinite sequence of `nil`, the first element is never
generated.) -/
def join : seq (seq1 α) → seq α :=
corec (λ S, match destruct S with
| none := none
| some ((a, s), S') := some (a, match destruct s with
| none := S'
| some s' := cons s' S'
end)
end)
/-- Remove the first `n` elements from the sequence. -/
def drop (s : seq α) : ℕ → seq α
| 0 := s
| (n+1) := tail (drop n)
attribute [simp] drop
/-- Take the first `n` elements of the sequence (producing a list) -/
def take : ℕ → seq α → list α
| 0 s := []
| (n+1) s := match destruct s with
| none := []
| some (x, r) := list.cons x (take n r)
end
/-- Split a sequence at `n`, producing a finite initial segment
and an infinite tail. -/
def split_at : ℕ → seq α → list α × seq α
| 0 s := ([], s)
| (n+1) s := match destruct s with
| none := ([], nil)
| some (x, s') := let (l, r) := split_at n s' in (list.cons x l, r)
end
section zip_with
/-- Combine two sequences with a function -/
def zip_with (f : α → β → γ) : seq α → seq β → seq γ
| ⟨f₁, a₁⟩ ⟨f₂, a₂⟩ := ⟨λ n,
match f₁ n, f₂ n with
| some a, some b := some (f a b)
| _, _ := none
end,
λ n, begin
induction h1 : f₁ n,
{ intro H, simp only [(a₁ h1)], refl },
induction h2 : f₂ n; dsimp [seq.zip_with._match_1]; intro H,
{ rw (a₂ h2), cases f₁ (n + 1); refl },
{ rw [h1, h2] at H, contradiction }
end⟩
variables {s : seq α} {s' : seq β} {n : ℕ}
lemma zip_with_nth_some {a : α} {b : β} (s_nth_eq_some : s.nth n = some a)
(s_nth_eq_some' : s'.nth n = some b) (f : α → β → γ) :
(zip_with f s s').nth n = some (f a b) :=
begin
cases s with st,
have : st n = some a, from s_nth_eq_some,
cases s' with st',
have : st' n = some b, from s_nth_eq_some',
simp only [zip_with, seq.nth, *]
end
lemma zip_with_nth_none (s_nth_eq_none : s.nth n = none) (f : α → β → γ) :
(zip_with f s s').nth n = none :=
begin
cases s with st,
have : st n = none, from s_nth_eq_none,
cases s' with st',
cases st'_nth_eq : st' n;
simp only [zip_with, seq.nth, *]
end
lemma zip_with_nth_none' (s'_nth_eq_none : s'.nth n = none) (f : α → β → γ) :
(zip_with f s s').nth n = none :=
begin
cases s' with st',
have : st' n = none, from s'_nth_eq_none,
cases s with st,
cases st_nth_eq : st n;
simp only [zip_with, seq.nth, *]
end
end zip_with
/-- Pair two sequences into a sequence of pairs -/
def zip : seq α → seq β → seq (α × β) := zip_with prod.mk
/-- Separate a sequence of pairs into two sequences -/
def unzip (s : seq (α × β)) : seq α × seq β := (map prod.fst s, map prod.snd s)
/-- Convert a sequence which is known to terminate into a list -/
def to_list (s : seq α) (h : s.terminates) : list α :=
take (nat.find h) s
/-- Convert a sequence which is known not to terminate into a stream -/
def to_stream (s : seq α) (h : ¬ s.terminates) : stream α :=
λ n, option.get $ not_terminates_iff.1 h n
/-- Convert a sequence into either a list or a stream depending on whether
it is finite or infinite. (Without decidability of the infiniteness predicate,
this is not constructively possible.) -/
def to_list_or_stream (s : seq α) [decidable s.terminates] : list α ⊕ stream α :=
if h : s.terminates
then sum.inl (to_list s h)
else sum.inr (to_stream s h)
@[simp] theorem nil_append (s : seq α) : append nil s = s :=
begin
apply coinduction2, intro s,
dsimp [append], rw [corec_eq],
dsimp [append], apply cases_on s _ _,
{ trivial },
{ intros x s,
rw [destruct_cons], dsimp,
exact ⟨rfl, s, rfl, rfl⟩ }
end
@[simp] theorem cons_append (a : α) (s t) : append (cons a s) t = cons a (append s t) :=
destruct_eq_cons $ begin
dsimp [append], rw [corec_eq],
dsimp [append], rw [destruct_cons],
dsimp [append], refl
end
@[simp] theorem append_nil (s : seq α) : append s nil = s :=
begin
apply coinduction2 s, intro s,
apply cases_on s _ _,
{ trivial },
{ intros x s,
rw [cons_append, destruct_cons, destruct_cons], dsimp,
exact ⟨rfl, s, rfl, rfl⟩ }
end
@[simp] theorem append_assoc (s t u : seq α) :
append (append s t) u = append s (append t u) :=
begin
apply eq_of_bisim (λ s1 s2, ∃ s t u,
s1 = append (append s t) u ∧ s2 = append s (append t u)),
{ intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, t, u, rfl, rfl⟩ := begin
apply cases_on s; simp,
{ apply cases_on t; simp,
{ apply cases_on u; simp,
{ intros x u, refine ⟨nil, nil, u, _, _⟩; simp } },
{ intros x t, refine ⟨nil, t, u, _, _⟩; simp } },
{ intros x s, exact ⟨s, t, u, rfl, rfl⟩ }
end end },
{ exact ⟨s, t, u, rfl, rfl⟩ }
end
@[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl
@[simp] theorem map_cons (f : α → β) (a) : ∀ s, map f (cons a s) = cons (f a) (map f s)
| ⟨s, al⟩ := by apply subtype.eq; dsimp [cons, map]; rw stream.map_cons; refl
@[simp] theorem map_id : ∀ (s : seq α), map id s = s
| ⟨s, al⟩ := begin
apply subtype.eq; dsimp [map],
rw [option.map_id, stream.map_id]; refl
end
@[simp] theorem map_tail (f : α → β) : ∀ s, map f (tail s) = tail (map f s)
| ⟨s, al⟩ := by apply subtype.eq; dsimp [tail, map]; rw stream.map_tail; refl
theorem map_comp (f : α → β) (g : β → γ) : ∀ (s : seq α), map (g ∘ f) s = map g (map f s)
| ⟨s, al⟩ := begin
apply subtype.eq; dsimp [map],
rw stream.map_map,
apply congr_arg (λ f : _ → option γ, stream.map f s),
ext ⟨⟩; refl
end
@[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) :=
begin
apply eq_of_bisim (λ s1 s2, ∃ s t,
s1 = map f (append s t) ∧ s2 = append (map f s) (map f t)) _ ⟨s, t, rfl, rfl⟩,
intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl⟩ := begin
apply cases_on s; simp,
{ apply cases_on t; simp,
{ intros x t, refine ⟨nil, t, _, _⟩; simp } },
{ intros x s, refine ⟨s, t, rfl, rfl⟩ }
end end
end
@[simp] theorem map_nth (f : α → β) : ∀ s n, nth (map f s) n = (nth s n).map f
| ⟨s, al⟩ n := rfl
instance : functor seq := {map := @map}
instance : is_lawful_functor seq :=
{ id_map := @map_id, comp_map := @map_comp }
@[simp] theorem join_nil : join nil = (nil : seq α) := destruct_eq_nil rfl
@[simp] theorem join_cons_nil (a : α) (S) :
join (cons (a, nil) S) = cons a (join S) :=
destruct_eq_cons $ by simp [join]
@[simp] theorem join_cons_cons (a b : α) (s S) :
join (cons (a, cons b s) S) = cons a (join (cons (b, s) S)) :=
destruct_eq_cons $ by simp [join]
@[simp, priority 990] theorem join_cons (a : α) (s S) :
join (cons (a, s) S) = cons a (append s (join S)) :=
begin
apply eq_of_bisim (λ s1 s2, s1 = s2 ∨
∃ a s S, s1 = join (cons (a, s) S) ∧
s2 = cons a (append s (join S))) _ (or.inr ⟨a, s, S, rfl, rfl⟩),
intros s1 s2 h,
exact match s1, s2, h with
| _, _, (or.inl $ eq.refl s) := begin
apply cases_on s, { trivial },
{ intros x s, rw [destruct_cons], exact ⟨rfl, or.inl rfl⟩ }
end
| ._, ._, (or.inr ⟨a, s, S, rfl, rfl⟩) := begin
apply cases_on s,
{ simp },
{ intros x s, simp, refine or.inr ⟨x, s, S, rfl, rfl⟩ }
end
end
end
@[simp] theorem join_append (S T : seq (seq1 α)) :
join (append S T) = append (join S) (join T) :=
begin
apply eq_of_bisim (λ s1 s2, ∃ s S T,
s1 = append s (join (append S T)) ∧
s2 = append s (append (join S) (join T))),
{ intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin
apply cases_on s; simp,
{ apply cases_on S; simp,
{ apply cases_on T, { simp },
{ intros s T, cases s with a s; simp,
refine ⟨s, nil, T, _, _⟩; simp } },
{ intros s S, cases s with a s; simp,
exact ⟨s, S, T, rfl, rfl⟩ } },
{ intros x s, exact ⟨s, S, T, rfl, rfl⟩ }
end end },
{ refine ⟨nil, S, T, _, _⟩; simp }
end
@[simp] theorem of_stream_cons (a : α) (s) :
of_stream (a :: s) = cons a (of_stream s) :=
by apply subtype.eq; simp [of_stream, cons]; rw stream.map_cons
@[simp] theorem of_list_append (l l' : list α) :
of_list (l ++ l') = append (of_list l) (of_list l') :=
by induction l; simp [*]
@[simp] theorem of_stream_append (l : list α) (s : stream α) :
of_stream (l ++ₛ s) = append (of_list l) (of_stream s) :=
by induction l; simp [*, stream.nil_append_stream, stream.cons_append_stream]
/-- Convert a sequence into a list, embedded in a computation to allow for
the possibility of infinite sequences (in which case the computation
never returns anything). -/
def to_list' {α} (s : seq α) : computation (list α) :=
@computation.corec (list α) (list α × seq α) (λ ⟨l, s⟩,
match destruct s with
| none := sum.inl l.reverse
| some (a, s') := sum.inr (a::l, s')
end) ([], s)
theorem dropn_add (s : seq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n
| 0 := rfl
| (n+1) := congr_arg tail (dropn_add n)
theorem dropn_tail (s : seq α) (n) : drop (tail s) n = drop s (n + 1) :=
by rw add_comm; symmetry; apply dropn_add
@[simp] theorem head_dropn (s : seq α) (n) : head (drop s n) = nth s n :=
begin
induction n with n IH generalizing s, { refl },
rw [nat.succ_eq_add_one, ←nth_tail, ←dropn_tail], apply IH
end
theorem mem_map (f : α → β) {a : α} : ∀ {s : seq α}, a ∈ s → f a ∈ map f s
| ⟨g, al⟩ := stream.mem_map (option.map f)
theorem exists_of_mem_map {f} {b : β} : ∀ {s : seq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b
| ⟨g, al⟩ h := let ⟨o, om, oe⟩ := stream.exists_of_mem_map h in
by cases o with a; injection oe with h'; exact ⟨a, om, h'⟩
theorem of_mem_append {s₁ s₂ : seq α} {a : α} (h : a ∈ append s₁ s₂) : a ∈ s₁ ∨ a ∈ s₂ :=
begin
have := h, revert this,
generalize e : append s₁ s₂ = ss, intro h, revert s₁,
apply mem_rec_on h _,
intros b s' o s₁,
apply s₁.cases_on _ (λ c t₁, _); intros m e;
have := congr_arg destruct e,
{ apply or.inr, simpa using m },
{ cases (show a = c ∨ a ∈ append t₁ s₂, by simpa using m) with e' m,
{ rw e', exact or.inl (mem_cons _ _) },
{ cases (show c = b ∧ append t₁ s₂ = s', by simpa) with i1 i2,
cases o with e' IH,
{ simp [i1, e'] },
{ exact or.imp_left (mem_cons_of_mem _) (IH m i2) } } }
end
theorem mem_append_left {s₁ s₂ : seq α} {a : α} (h : a ∈ s₁) : a ∈ append s₁ s₂ :=
by apply mem_rec_on h; intros; simp [*]
end seq
namespace seq1
variables {α : Type u} {β : Type v} {γ : Type w}
open seq
/-- Convert a `seq1` to a sequence. -/
def to_seq : seq1 α → seq α
| (a, s) := cons a s
instance coe_seq : has_coe (seq1 α) (seq α) := ⟨to_seq⟩
/-- Map a function on a `seq1` -/
def map (f : α → β) : seq1 α → seq1 β
| (a, s) := (f a, seq.map f s)
theorem map_id : ∀ (s : seq1 α), map id s = s | ⟨a, s⟩ := by simp [map]
/-- Flatten a nonempty sequence of nonempty sequences -/
def join : seq1 (seq1 α) → seq1 α
| ((a, s), S) := match destruct s with
| none := (a, seq.join S)
| some s' := (a, seq.join (cons s' S))
end
@[simp] theorem join_nil (a : α) (S) : join ((a, nil), S) = (a, seq.join S) := rfl
@[simp] theorem join_cons (a b : α) (s S) :
join ((a, cons b s), S) = (a, seq.join (cons (b, s) S)) :=
by dsimp [join]; rw [destruct_cons]; refl
/-- The `return` operator for the `seq1` monad,
which produces a singleton sequence. -/
def ret (a : α) : seq1 α := (a, nil)
instance [inhabited α] : inhabited (seq1 α) := ⟨ret default⟩
/-- The `bind` operator for the `seq1` monad,
which maps `f` on each element of `s` and appends the results together.
(Not all of `s` may be evaluated, because the first few elements of `s`
may already produce an infinite result.) -/
def bind (s : seq1 α) (f : α → seq1 β) : seq1 β :=
join (map f s)
@[simp] theorem join_map_ret (s : seq α) : seq.join (seq.map ret s) = s :=
by apply coinduction2 s; intro s; apply cases_on s; simp [ret]
@[simp] theorem bind_ret (f : α → β) : ∀ s, bind s (ret ∘ f) = map f s
| ⟨a, s⟩ := begin
dsimp [bind, map], change (λ x, ret (f x)) with (ret ∘ f),
rw [map_comp], simp [function.comp, ret]
end
@[simp] theorem ret_bind (a : α) (f : α → seq1 β) : bind (ret a) f = f a :=
begin
simp [ret, bind, map],
cases f a with a s,
apply cases_on s; intros; simp
end
@[simp] theorem map_join' (f : α → β) (S) :
seq.map f (seq.join S) = seq.join (seq.map (map f) S) :=
begin
apply eq_of_bisim (λ s1 s2,
∃ s S, s1 = append s (seq.map f (seq.join S)) ∧
s2 = append s (seq.join (seq.map (map f) S))),
{ intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin
apply cases_on s; simp,
{ apply cases_on S; simp,
{ intros x S, cases x with a s; simp [map],
exact ⟨_, _, rfl, rfl⟩ } },
{ intros x s, refine ⟨s, S, rfl, rfl⟩ }
end end },
{ refine ⟨nil, S, _, _⟩; simp }
end
@[simp] theorem map_join (f : α → β) : ∀ S, map f (join S) = join (map (map f) S)
| ((a, s), S) := by apply cases_on s; intros; simp [map]
@[simp] theorem join_join (SS : seq (seq1 (seq1 α))) :
seq.join (seq.join SS) = seq.join (seq.map join SS) :=
begin
apply eq_of_bisim (λ s1 s2,
∃ s SS, s1 = seq.append s (seq.join (seq.join SS)) ∧
s2 = seq.append s (seq.join (seq.map join SS))),
{ intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, SS, rfl, rfl⟩ := begin
apply cases_on s; simp,
{ apply cases_on SS; simp,
{ intros S SS, cases S with s S; cases s with x s; simp [map],
apply cases_on s; simp,
{ exact ⟨_, _, rfl, rfl⟩ },
{ intros x s,
refine ⟨cons x (append s (seq.join S)), SS, _, _⟩; simp } } },
{ intros x s, exact ⟨s, SS, rfl, rfl⟩ }
end end },
{ refine ⟨nil, SS, _, _⟩; simp }
end
@[simp] theorem bind_assoc (s : seq1 α) (f : α → seq1 β) (g : β → seq1 γ) :
bind (bind s f) g = bind s (λ (x : α), bind (f x) g) :=
begin
cases s with a s,
simp [bind, map],
rw [←map_comp],
change (λ x, join (map g (f x))) with (join ∘ ((map g) ∘ f)),
rw [map_comp _ join],
generalize : seq.map (map g ∘ f) s = SS,
rcases map g (f a) with ⟨⟨a, s⟩, S⟩,
apply cases_on s; intros; apply cases_on S; intros; simp,
{ cases x with x t, apply cases_on t; intros; simp },
{ cases x_1 with y t; simp }
end
instance : monad seq1 :=
{ map := @map,
pure := @ret,
bind := @bind }
instance : is_lawful_monad seq1 :=
{ id_map := @map_id,
bind_pure_comp_eq_map := @bind_ret,
pure_bind := @ret_bind,
bind_assoc := @bind_assoc }
end seq1
|
47d02b90ff36dcaf4676b890107a6bac4f35e719 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /stage0/src/Init/Data/Array/InsertionSort.lean | 4aca4e50d9db278ab94809675ef9a33262cecfc6 | [
"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 | 926 | 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.Array.Basic
@[inline] def Array.insertionSort (a : Array α) (lt : α → α → Bool) : Array α :=
traverse a 0 a.size
where
@[specialize] traverse (a : Array α) (i : Nat) (fuel : Nat) : Array α :=
match fuel with
| 0 => a
| fuel+1 =>
if h : i < a.size then
traverse (swapLoop a i h) (i+1) fuel
else
a
@[specialize] swapLoop (a : Array α) (j : Nat) (h : j < a.size) : Array α :=
match he:j with
| 0 => a
| j'+1 =>
have h' : j' < a.size := by subst j; exact Nat.ltTrans (Nat.ltSuccSelf _) h
if lt (a.get ⟨j, h⟩) (a.get ⟨j', h'⟩) then
swapLoop (a.swap ⟨j, h⟩ ⟨j', h'⟩) j' (by rw [size_swap]; assumption done)
else
a
|
96875206c15e7eae86852862e4cea43418b30730 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/topology/algebra/multilinear.lean | 591188f26ec4bdf29ad6555b080f218f036cb812 | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,204 | 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 topology.algebra.module
import linear_algebra.multilinear.basic
/-!
# Continuous multilinear maps
We define continuous multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are multilinear
and continuous, by extending the space of multilinear maps with a continuity assumption.
Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type, and all these
spaces are also topological spaces.
## Main definitions
* `continuous_multilinear_map R M₁ M₂` is the space of continuous multilinear maps from
`Π(i : ι), M₁ i` to `M₂`. We show that it is an `R`-module.
## Implementation notes
We mostly follow the API of multilinear maps.
## Notation
We introduce the notation `M [×n]→L[R] M'` for the space of continuous `n`-multilinear maps from
`M^n` to `M'`. This is a particular case of the general notion (where we allow varying dependent
types as the arguments of our continuous multilinear maps), but arguably the most important one,
especially when defining iterated derivatives.
-/
open function fin set
open_locale big_operators
universes u v w w₁ w₁' w₂ w₃ w₄
variables {R : Type u} {ι : Type v} {n : ℕ} {M : fin n.succ → Type w} {M₁ : ι → Type w₁}
{M₁' : ι → Type w₁'} {M₂ : Type w₂} {M₃ : Type w₃} {M₄ : Type w₄} [decidable_eq ι]
/-- Continuous multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂`
are modules over `R` with a topological structure. In applications, there will be compatibility
conditions between the algebraic and the topological structures, but this is not needed for the
definition. -/
structure continuous_multilinear_map (R : Type u) {ι : Type v} (M₁ : ι → Type w₁) (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₂] [∀i, topological_space (M₁ i)] [topological_space M₂]
extends multilinear_map R M₁ M₂ :=
(cont : continuous to_fun)
notation M `[×`:25 n `]→L[`:25 R `] ` M' := continuous_multilinear_map R (λ (i : fin n), M) M'
namespace continuous_multilinear_map
section semiring
variables [semiring R]
[Πi, add_comm_monoid (M i)] [Π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)] [Π i, module R (M₁' i)] [module R M₂]
[module R M₃] [module R M₄]
[Π i, topological_space (M i)] [Π i, topological_space (M₁ i)] [Π i, topological_space (M₁' i)]
[topological_space M₂] [topological_space M₃] [topological_space M₄]
(f f' : continuous_multilinear_map R M₁ M₂)
instance : has_coe_to_fun (continuous_multilinear_map R M₁ M₂) :=
⟨_, λ f, f.to_multilinear_map.to_fun⟩
@[continuity] lemma coe_continuous : continuous (f : (Π i, M₁ i) → M₂) := f.cont
@[simp] lemma coe_coe : (f.to_multilinear_map : (Π i, M₁ i) → M₂) = f := rfl
theorem to_multilinear_map_inj :
function.injective (continuous_multilinear_map.to_multilinear_map :
continuous_multilinear_map R M₁ M₂ → multilinear_map R M₁ M₂)
| ⟨f, hf⟩ ⟨g, hg⟩ rfl := rfl
@[ext] theorem ext {f f' : continuous_multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' :=
to_multilinear_map_inj $ multilinear_map.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 :=
f.to_multilinear_map.map_coord_zero i h
@[simp] lemma map_zero [nonempty ι] : f 0 = 0 :=
f.to_multilinear_map.map_zero
instance : has_zero (continuous_multilinear_map R M₁ M₂) :=
⟨{ cont := continuous_const, ..(0 : multilinear_map R M₁ M₂) }⟩
instance : inhabited (continuous_multilinear_map R M₁ M₂) := ⟨0⟩
@[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : continuous_multilinear_map R M₁ M₂) m = 0 := rfl
section has_continuous_add
variable [has_continuous_add M₂]
instance : has_add (continuous_multilinear_map R M₁ M₂) :=
⟨λ f f', ⟨f.to_multilinear_map + f'.to_multilinear_map, f.cont.add f'.cont⟩⟩
@[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl
@[simp] lemma to_multilinear_map_add (f g : continuous_multilinear_map R M₁ M₂) :
(f + g).to_multilinear_map = f.to_multilinear_map + g.to_multilinear_map :=
rfl
instance add_comm_monoid : add_comm_monoid (continuous_multilinear_map R M₁ M₂) :=
to_multilinear_map_inj.add_comm_monoid _ rfl (λ _ _, rfl)
/-- Evaluation of a `continuous_multilinear_map` at a vector as an `add_monoid_hom`. -/
def apply_add_hom (m : Π i, M₁ i) : continuous_multilinear_map R M₁ M₂ →+ M₂ :=
⟨λ f, f m, rfl, λ _ _, rfl⟩
@[simp] lemma sum_apply {α : Type*} (f : α → continuous_multilinear_map R M₁ M₂)
(m : Πi, M₁ i) {s : finset α} : (∑ a in s, f a) m = ∑ a in s, f a m :=
(apply_add_hom m).map_sum f s
end has_continuous_add
/-- If `f` is a continuous multilinear map, then `f.to_continuous_linear_map m i` is the continuous
linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the
`i`-th coordinate. -/
def to_continuous_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →L[R] M₂ :=
{ cont := f.cont.comp (continuous_const.update i continuous_id),
.. f.to_multilinear_map.to_linear_map m i }
/-- The cartesian product of two continuous multilinear maps, as a continuous multilinear map. -/
def prod (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) :
continuous_multilinear_map R M₁ (M₂ × M₃) :=
{ cont := f.cont.prod_mk g.cont,
.. f.to_multilinear_map.prod g.to_multilinear_map }
@[simp] lemma prod_apply
(f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) (m : Πi, M₁ i) :
(f.prod g) m = (f m, g m) := rfl
/-- Combine a family of continuous multilinear maps with the same domain and codomains `M' i` into a
continuous multilinear map taking values in the space of functions `Π i, M' i`. -/
def pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)]
[Π i, module R (M' i)] (f : Π i, continuous_multilinear_map R M₁ (M' i)) :
continuous_multilinear_map R M₁ (Π i, M' i) :=
{ cont := continuous_pi $ λ i, (f i).coe_continuous,
to_multilinear_map := multilinear_map.pi (λ i, (f i).to_multilinear_map) }
@[simp] lemma coe_pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)]
[Π i, topological_space (M' i)] [Π i, module R (M' i)]
(f : Π i, continuous_multilinear_map R M₁ (M' i)) :
⇑(pi f) = λ m j, f j m :=
rfl
lemma pi_apply {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)]
[Π i, topological_space (M' i)] [Π i, module R (M' i)]
(f : Π i, continuous_multilinear_map R M₁ (M' i)) (m : Π i, M₁ i) (j : ι') :
pi f m j = f j m :=
rfl
/-- If `g` is continuous multilinear and `f` is a collection of continuous linear maps,
then `g (f₁ m₁, ..., fₙ mₙ)` is again a continuous multilinear map, that we call
`g.comp_continuous_linear_map f`. -/
def comp_continuous_linear_map
(g : continuous_multilinear_map R M₁' M₄) (f : Π i : ι, M₁ i →L[R] M₁' i) :
continuous_multilinear_map R M₁ M₄ :=
{ cont := g.cont.comp $ continuous_pi $ λj, (f j).cont.comp $ continuous_apply _,
.. g.to_multilinear_map.comp_linear_map (λ i, (f i).to_linear_map) }
@[simp] lemma comp_continuous_linear_map_apply (g : continuous_multilinear_map R M₁' M₄)
(f : Π i : ι, M₁ i →L[R] M₁' i) (m : Π i, M₁ i) :
g.comp_continuous_linear_map f m = g (λ i, f i $ m i) :=
rfl
/-- Composing a continuous multilinear map with a continuous linear map gives again a
continuous multilinear map. -/
def _root_.continuous_linear_map.comp_continuous_multilinear_map
(g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) :
continuous_multilinear_map R M₁ M₃ :=
{ cont := g.cont.comp f.cont,
.. g.to_linear_map.comp_multilinear_map f.to_multilinear_map }
@[simp] lemma _root_.continuous_linear_map.comp_continuous_multilinear_map_coe (g : M₂ →L[R] M₃)
(f : continuous_multilinear_map R M₁ M₂) :
((g.comp_continuous_multilinear_map f) : (Πi, M₁ i) → M₃) =
(g : M₂ → M₃) ∘ (f : (Πi, M₁ i) → M₂) :=
by { ext m, refl }
/-- `continuous_multilinear_map.pi` as an `equiv`. -/
@[simps]
def pi_equiv {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)]
[Π i, topological_space (M' i)] [Π i, module R (M' i)] :
(Π i, continuous_multilinear_map R M₁ (M' i)) ≃
continuous_multilinear_map R M₁ (Π i, M' i) :=
{ to_fun := continuous_multilinear_map.pi,
inv_fun := λ f i, (continuous_linear_map.proj i : _ →L[R] M' i).comp_continuous_multilinear_map f,
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, refl } }
/-- In the specific case of continuous 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 : continuous_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) :=
f.to_multilinear_map.cons_add m x y
/-- In the specific case of continuous 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 : continuous_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) :=
f.to_multilinear_map.cons_smul m c x
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') :=
f.to_multilinear_map.map_piecewise_add _ _ _
/-- Additivity of a continuous 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') :=
f.to_multilinear_map.map_add_univ _ _
section apply_sum
open fintype finset
variables {α : ι → Type*} [fintype ι] (g : Π i, α i → M₁ i) (A : Π i, finset (α i))
/-- If `f` is continuous 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 :
f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) :=
f.to_multilinear_map.map_sum_finset _ _
/-- If `f` is continuous 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 [∀ i, fintype (α i)] :
f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) :=
f.to_multilinear_map.map_sum _
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 : continuous_multilinear_map A M₁ M₂) :
continuous_multilinear_map R M₁ M₂ :=
{ to_multilinear_map := f.to_multilinear_map.restrict_scalars R,
cont := f.cont }
@[simp] lemma coe_restrict_scalars (f : continuous_multilinear_map A M₁ M₂) :
⇑(f.restrict_scalars R) = f := rfl
end restrict_scalar
end semiring
section ring
variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂]
[∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂]
(f f' : continuous_multilinear_map R M₁ 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) :=
f.to_multilinear_map.map_sub _ _ _ _
section topological_add_group
variable [topological_add_group M₂]
instance : has_neg (continuous_multilinear_map R M₁ M₂) :=
⟨λ f, {cont := f.cont.neg, ..(-f.to_multilinear_map)}⟩
@[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl
instance : has_sub (continuous_multilinear_map R M₁ M₂) :=
⟨λ f g, { cont := f.cont.sub g.cont, .. (f.to_multilinear_map - g.to_multilinear_map) }⟩
@[simp] lemma sub_apply (m : Πi, M₁ i) : (f - f') m = f m - f' m := rfl
instance : add_comm_group (continuous_multilinear_map R M₁ M₂) :=
to_multilinear_map_inj.add_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
end topological_add_group
end ring
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₂]
[∀i, topological_space (M₁ i)] [topological_space M₂]
(f : continuous_multilinear_map R M₁ M₂)
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 :=
f.to_multilinear_map.map_piecewise_smul _ _ _
/-- Multiplicativity of a continuous 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 :=
f.to_multilinear_map.map_smul_univ _ _
variables {R' A : Type*} [comm_semiring R'] [semiring A] [algebra R' A]
[Π i, module A (M₁ i)] [module R' M₂] [module A M₂] [is_scalar_tower R' A M₂]
[topological_space R'] [has_continuous_smul R' M₂]
instance : has_scalar R' (continuous_multilinear_map A M₁ M₂) :=
⟨λ c f, { cont := continuous_const.smul f.cont, .. c • f.to_multilinear_map }⟩
@[simp] lemma smul_apply (f : continuous_multilinear_map A M₁ M₂) (c : R') (m : Πi, M₁ i) :
(c • f) m = c • f m := rfl
@[simp] lemma to_multilinear_map_smul (c : R') (f : continuous_multilinear_map A M₁ M₂) :
(c • f).to_multilinear_map = c • f.to_multilinear_map :=
rfl
instance {R''} [comm_semiring R''] [has_scalar R' R''] [algebra R'' A]
[module R'' M₂] [is_scalar_tower R'' A M₂] [is_scalar_tower R' R'' M₂]
[topological_space R''] [has_continuous_smul R'' M₂]:
is_scalar_tower R' R'' (continuous_multilinear_map A M₁ M₂) :=
⟨λ c₁ c₂ f, ext $ λ x, smul_assoc _ _ _⟩
variable [has_continuous_add M₂]
/-- The space of continuous multilinear maps over an algebra over `R` is a module over `R`, for the
pointwise addition and scalar multiplication. -/
instance : module R' (continuous_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 _ _ _,
add_smul := λ r₁ r₂ f, ext $ λ x, add_smul _ _ _,
zero_smul := λ f, ext $ λ x, zero_smul _ _ }
/-- Linear map version of the map `to_multilinear_map` associating to a continuous multilinear map
the corresponding multilinear map. -/
@[simps] def to_multilinear_map_linear :
(continuous_multilinear_map A M₁ M₂) →ₗ[R'] (multilinear_map A M₁ M₂) :=
{ to_fun := λ f, f.to_multilinear_map,
map_add' := λ f g, rfl,
map_smul' := λ c f, rfl }
/-- `continuous_multilinear_map.pi` as a `linear_equiv`. -/
@[simps {simp_rhs := tt}]
def pi_linear_equiv {ι' : Type*} {M' : ι' → Type*}
[Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [∀ i, has_continuous_add (M' i)]
[Π i, module R' (M' i)] [Π i, module A (M' i)] [∀ i, is_scalar_tower R' A (M' i)]
[Π i, has_continuous_smul R' (M' i)] :
-- typeclass search doesn't find this instance, presumably due to struggles converting
-- `Π i, module R (M' i)` to `Π i, has_scalar R (M' i)` in dependent arguments.
let inst : has_continuous_smul R' (Π i, M' i) := pi.has_continuous_smul in
(Π i, continuous_multilinear_map A M₁ (M' i)) ≃ₗ[R']
continuous_multilinear_map A M₁ (Π i, M' i) :=
{ map_add' := λ x y, rfl,
map_smul' := λ c x, rfl,
.. pi_equiv }
end comm_semiring
end continuous_multilinear_map
|
5f189ffe9055f6877d79f765b078d95e08f3b1e0 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/calculus/parametric_integral.lean | 1d52b259e285719283ad653f3c750c1e6e4ac4c8 | [
"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 | 15,240 | lean | /-
Copyright (c) 2021 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
-/
import measure_theory.integral.set_integral
import analysis.calculus.mean_value
/-!
# Derivatives of integrals depending on parameters
A parametric integral is a function with shape `f = λ x : H, ∫ a : α, F x a ∂μ` for some
`F : H → α → E`, where `H` and `E` are normed spaces and `α` is a measured space with measure `μ`.
We already know from `continuous_of_dominated` in `measure_theory.integral.bochner` how to
guarantee that `f` is continuous using the dominated convergence theorem. In this file,
we want to express the derivative of `f` as the integral of the derivative of `F` with respect
to `x`.
## Main results
As explained above, all results express the derivative of a parametric integral as the integral of
a derivative. The variations come from the assumptions and from the different ways of expressing
derivative, especially Fréchet derivatives vs elementary derivative of function of one real
variable.
* `has_fderiv_at_integral_of_dominated_loc_of_lip`: this version assumes that
- `F x` is ae-measurable for x near `x₀`,
- `F x₀` is integrable,
- `λ x, F x a` has derivative `F' a : H →L[ℝ] E` at `x₀` which is ae-measurable,
- `λ x, F x a` is locally Lipschitz near `x₀` for almost every `a`, with a Lipschitz bound which
is integrable with respect to `a`.
A subtle point is that the "near x₀" in the last condition has to be uniform in `a`. This is
controlled by a positive number `ε`.
* `has_fderiv_at_integral_of_dominated_of_fderiv_le`: this version assume `λ x, F x a` has
derivative `F' x a` for `x` near `x₀` and `F' x` is bounded by an integrable function independent
from `x` near `x₀`.
`has_deriv_at_integral_of_dominated_loc_of_lip` and
`has_deriv_at_integral_of_dominated_loc_of_deriv_le` are versions of the above two results that
assume `H = ℝ` or `H = ℂ` and use the high-school derivative `deriv` instead of Fréchet derivative
`fderiv`.
We also provide versions of these theorems for set integrals.
## Tags
integral, derivative
-/
noncomputable theory
open topological_space measure_theory filter metric
open_locale topological_space filter
variables {α : Type*} [measurable_space α] {μ : measure α} {𝕜 : Type*} [is_R_or_C 𝕜]
{E : Type*} [normed_group E] [normed_space ℝ E] [normed_space 𝕜 E]
[complete_space E]
{H : Type*} [normed_group H] [normed_space 𝕜 H]
/-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is
integrable, `∥F x a - F x₀ a∥ ≤ bound a * ∥x - x₀∥` for `x` in a ball around `x₀` for ae `a` with
integrable Lipschitz bound `bound` (with a ball radius independent of `a`), and `F x` is
ae-measurable for `x` in the same ball. See `has_fderiv_at_integral_of_dominated_loc_of_lip` for a
slightly less general but usually more useful version. -/
lemma has_fderiv_at_integral_of_dominated_loc_of_lip' {F : H → α → E} {F' : α → (H →L[𝕜] E)}
{x₀ : H} {bound : α → ℝ}
{ε : ℝ} (ε_pos : 0 < ε)
(hF_meas : ∀ x ∈ ball x₀ ε, ae_strongly_measurable (F x) μ)
(hF_int : integrable (F x₀) μ)
(hF'_meas : ae_strongly_measurable F' μ)
(h_lipsch : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, ∥F x a - F x₀ a∥ ≤ bound a * ∥x - x₀∥)
(bound_integrable : integrable (bound : α → ℝ) μ)
(h_diff : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' a) x₀) :
integrable F' μ ∧ has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ :=
begin
have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos,
have nneg : ∀ x, 0 ≤ ∥x - x₀∥⁻¹ := λ x, inv_nonneg.mpr (norm_nonneg _) ,
set b : α → ℝ := λ a, |bound a|,
have b_int : integrable b μ := bound_integrable.norm,
have b_nonneg : ∀ a, 0 ≤ b a := λ a, abs_nonneg _,
replace h_lipsch : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, ∥F x a - F x₀ a∥ ≤ b a * ∥x - x₀∥,
from h_lipsch.mono (λ a ha x hx, (ha x hx).trans $
mul_le_mul_of_nonneg_right (le_abs_self _) (norm_nonneg _)),
have hF_int' : ∀ x ∈ ball x₀ ε, integrable (F x) μ,
{ intros x x_in,
have : ∀ᵐ a ∂μ, ∥F x₀ a - F x a∥ ≤ ε * b a,
{ simp only [norm_sub_rev (F x₀ _)],
refine h_lipsch.mono (λ a ha, (ha x x_in).trans _),
rw mul_comm ε,
rw [mem_ball, dist_eq_norm] at x_in,
exact mul_le_mul_of_nonneg_left x_in.le (b_nonneg _) },
exact integrable_of_norm_sub_le (hF_meas x x_in) hF_int
(integrable.const_mul bound_integrable.norm ε) this },
have hF'_int : integrable F' μ,
{ have : ∀ᵐ a ∂μ, ∥F' a∥ ≤ b a,
{ apply (h_diff.and h_lipsch).mono,
rintros a ⟨ha_diff, ha_lip⟩,
refine ha_diff.le_of_lip' (b_nonneg a) (mem_of_superset (ball_mem_nhds _ ε_pos) $ ha_lip) },
exact b_int.mono' hF'_meas this },
refine ⟨hF'_int, _⟩,
have h_ball: ball x₀ ε ∈ 𝓝 x₀ := ball_mem_nhds x₀ ε_pos,
have : ∀ᶠ x in 𝓝 x₀,
∥x - x₀∥⁻¹ * ∥∫ a, F x a ∂μ - ∫ a, F x₀ a ∂μ - (∫ a, F' a ∂μ) (x - x₀)∥ =
∥∫ a, ∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀)) ∂μ∥,
{ apply mem_of_superset (ball_mem_nhds _ ε_pos),
intros x x_in,
rw [set.mem_set_of_eq, ← norm_smul_of_nonneg (nneg _), integral_smul,
integral_sub, integral_sub, ← continuous_linear_map.integral_apply hF'_int],
exacts [hF_int' x x_in, hF_int, (hF_int' x x_in).sub hF_int,
hF'_int.apply_continuous_linear_map _] },
rw [has_fderiv_at_iff_tendsto, tendsto_congr' this, ← tendsto_zero_iff_norm_tendsto_zero,
← show ∫ (a : α), ∥x₀ - x₀∥⁻¹ • (F x₀ a - F x₀ a - (F' a) (x₀ - x₀)) ∂μ = 0, by simp],
apply tendsto_integral_filter_of_dominated_convergence,
{ filter_upwards [h_ball] with _ x_in,
apply ae_strongly_measurable.const_smul,
exact ((hF_meas _ x_in).sub (hF_meas _ x₀_in)).sub (hF'_meas.apply_continuous_linear_map _) },
{ apply mem_of_superset h_ball,
intros x hx,
apply (h_diff.and h_lipsch).mono,
rintros a ⟨ha_deriv, ha_bound⟩,
show ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥ ≤ b a + ∥F' a∥,
replace ha_bound : ∥F x a - F x₀ a∥ ≤ b a * ∥x - x₀∥ := ha_bound x hx,
calc ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥
= ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a) - ∥x - x₀∥⁻¹ • F' a (x - x₀)∥ : by rw smul_sub
... ≤ ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a)∥ + ∥∥x - x₀∥⁻¹ • F' a (x - x₀)∥ : norm_sub_le _ _
... = ∥x - x₀∥⁻¹ * ∥F x a - F x₀ a∥ + ∥x - x₀∥⁻¹ * ∥F' a (x - x₀)∥ :
by { rw [norm_smul_of_nonneg, norm_smul_of_nonneg] ; exact nneg _}
... ≤ ∥x - x₀∥⁻¹ * (b a * ∥x - x₀∥) + ∥x - x₀∥⁻¹ * (∥F' a∥ * ∥x - x₀∥) : add_le_add _ _
... ≤ b a + ∥F' a∥ : _,
exact mul_le_mul_of_nonneg_left ha_bound (nneg _),
apply mul_le_mul_of_nonneg_left ((F' a).le_op_norm _) (nneg _),
by_cases h : ∥x - x₀∥ = 0,
{ simpa [h] using add_nonneg (b_nonneg a) (norm_nonneg (F' a)) },
{ field_simp [h] } },
{ exact b_int.add hF'_int.norm },
{ apply h_diff.mono,
intros a ha,
suffices : tendsto (λ x, ∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))) (𝓝 x₀) (𝓝 0),
by simpa,
rw tendsto_zero_iff_norm_tendsto_zero,
have : (λ x, ∥x - x₀∥⁻¹ * ∥F x a - F x₀ a - F' a (x - x₀)∥) =
λ x, ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥,
{ ext x,
rw norm_smul_of_nonneg (nneg _) },
rwa [has_fderiv_at_iff_tendsto, this] at ha },
end
/-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming
`F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a`
(with a ball radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable
for `x` in a possibly smaller neighborhood of `x₀`. -/
lemma has_fderiv_at_integral_of_dominated_loc_of_lip {F : H → α → E} {F' : α → (H →L[𝕜] E)} {x₀ : H}
{bound : α → ℝ}
{ε : ℝ} (ε_pos : 0 < ε)
(hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) μ)
(hF_int : integrable (F x₀) μ)
(hF'_meas : ae_strongly_measurable F' μ)
(h_lip : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε))
(bound_integrable : integrable (bound : α → ℝ) μ)
(h_diff : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' a) x₀) :
integrable F' μ ∧ has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ :=
begin
obtain ⟨δ, δ_pos, hδ⟩ : ∃ δ > 0, ∀ x ∈ ball x₀ δ, ae_strongly_measurable (F x) μ ∧ x ∈ ball x₀ ε,
from eventually_nhds_iff_ball.mp (hF_meas.and (ball_mem_nhds x₀ ε_pos)),
choose hδ_meas hδε using hδ,
replace h_lip : ∀ᵐ (a : α) ∂μ, ∀ x ∈ ball x₀ δ, ∥F x a - F x₀ a∥ ≤ |bound a| * ∥x - x₀∥,
from h_lip.mono (λ a lip x hx, lip.norm_sub_le (hδε x hx) (mem_ball_self ε_pos)),
replace bound_integrable := bound_integrable.norm,
apply has_fderiv_at_integral_of_dominated_loc_of_lip' δ_pos; assumption
end
/-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming
`F x₀` is integrable, `x ↦ F x a` is differentiable on a ball around `x₀` for ae `a` with
derivative norm uniformly bounded by an integrable function (the ball radius is independent of `a`),
and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/
lemma has_fderiv_at_integral_of_dominated_of_fderiv_le {F : H → α → E} {F' : H → α → (H →L[𝕜] E)}
{x₀ : H} {bound : α → ℝ}
{ε : ℝ} (ε_pos : 0 < ε)
(hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) μ)
(hF_int : integrable (F x₀) μ)
(hF'_meas : ae_strongly_measurable (F' x₀) μ)
(h_bound : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, ∥F' x a∥ ≤ bound a)
(bound_integrable : integrable (bound : α → ℝ) μ)
(h_diff : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, has_fderiv_at (λ x, F x a) (F' x a) x) :
has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' x₀ a ∂μ) x₀ :=
begin
letI : normed_space ℝ H := normed_space.restrict_scalars ℝ 𝕜 H,
have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos,
have diff_x₀ : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' x₀ a) x₀ :=
h_diff.mono (λ a ha, ha x₀ x₀_in),
have : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs (bound a)) (λ x, F x a) (ball x₀ ε),
{ apply (h_diff.and h_bound).mono,
rintros a ⟨ha_deriv, ha_bound⟩,
refine (convex_ball _ _).lipschitz_on_with_of_nnnorm_has_fderiv_within_le
(λ x x_in, (ha_deriv x x_in).has_fderiv_within_at) (λ x x_in, _),
rw [← nnreal.coe_le_coe, coe_nnnorm, real.coe_nnabs],
exact (ha_bound x x_in).trans (le_abs_self _) },
exact (has_fderiv_at_integral_of_dominated_loc_of_lip ε_pos hF_meas hF_int
hF'_meas this bound_integrable diff_x₀).2
end
/-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : 𝕜`, `𝕜 = ℝ` or `𝕜 = ℂ`,
assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a`
(with ball radius independent of `a`) with integrable Lipschitz bound, and `F x` is
ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/
lemma has_deriv_at_integral_of_dominated_loc_of_lip {F : 𝕜 → α → E} {F' : α → E} {x₀ : 𝕜}
{ε : ℝ} (ε_pos : 0 < ε)
(hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) μ)
(hF_int : integrable (F x₀) μ)
(hF'_meas : ae_strongly_measurable F' μ) {bound : α → ℝ}
(h_lipsch : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε))
(bound_integrable : integrable (bound : α → ℝ) μ)
(h_diff : ∀ᵐ a ∂μ, has_deriv_at (λ x, F x a) (F' a) x₀) :
(integrable F' μ) ∧ has_deriv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ :=
begin
set L : E →L[𝕜] (𝕜 →L[𝕜] E) := (continuous_linear_map.smul_rightL 𝕜 𝕜 E 1),
replace h_diff : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (L (F' a)) x₀ :=
h_diff.mono (λ x hx, hx.has_fderiv_at),
have hm : ae_strongly_measurable (L ∘ F') μ := L.continuous.comp_ae_strongly_measurable hF'_meas,
cases has_fderiv_at_integral_of_dominated_loc_of_lip ε_pos hF_meas hF_int hm h_lipsch
bound_integrable h_diff with hF'_int key,
replace hF'_int : integrable F' μ,
{ rw [← integrable_norm_iff hm] at hF'_int,
simpa only [L, (∘), integrable_norm_iff, hF'_meas, one_mul, norm_one,
continuous_linear_map.comp_apply, continuous_linear_map.coe_restrict_scalarsL',
continuous_linear_map.norm_restrict_scalars, continuous_linear_map.norm_smul_rightL_apply]
using hF'_int },
refine ⟨hF'_int, _⟩,
simp_rw has_deriv_at_iff_has_fderiv_at at h_diff ⊢,
rwa continuous_linear_map.integral_comp_comm _ hF'_int at key,
all_goals { apply_instance, },
end
/-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : ℝ`, assuming
`F x₀` is integrable, `x ↦ F x a` is differentiable on an interval around `x₀` for ae `a`
(with interval radius independent of `a`) with derivative uniformly bounded by an integrable
function, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/
lemma has_deriv_at_integral_of_dominated_loc_of_deriv_le {F : 𝕜 → α → E} {F' : 𝕜 → α → E} {x₀ : 𝕜}
{ε : ℝ} (ε_pos : 0 < ε)
(hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) μ)
(hF_int : integrable (F x₀) μ)
(hF'_meas : ae_strongly_measurable (F' x₀) μ)
{bound : α → ℝ}
(h_bound : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, ∥F' x a∥ ≤ bound a)
(bound_integrable : integrable bound μ)
(h_diff : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, has_deriv_at (λ x, F x a) (F' x a) x) :
(integrable (F' x₀) μ) ∧ has_deriv_at (λn, ∫ a, F n a ∂μ) (∫ a, F' x₀ a ∂μ) x₀ :=
begin
have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos,
have diff_x₀ : ∀ᵐ a ∂μ, has_deriv_at (λ x, F x a) (F' x₀ a) x₀ :=
h_diff.mono (λ a ha, ha x₀ x₀_in),
have : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs (bound a)) (λ (x : 𝕜), F x a) (ball x₀ ε),
{ apply (h_diff.and h_bound).mono,
rintros a ⟨ha_deriv, ha_bound⟩,
refine (convex_ball _ _).lipschitz_on_with_of_nnnorm_has_deriv_within_le
(λ x x_in, (ha_deriv x x_in).has_deriv_within_at) (λ x x_in, _),
rw [← nnreal.coe_le_coe, coe_nnnorm, real.coe_nnabs],
exact (ha_bound x x_in).trans (le_abs_self _) },
exact has_deriv_at_integral_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas this
bound_integrable diff_x₀
end
|
9bd92a32f470f3047e14ae2c5deaf50b5f5fee88 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebra/big_operators/multiset.lean | f183c8b829d7a17b11b2b0272afe46ced5badb15 | [
"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 | 15,876 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.group_with_zero.power
import data.list.big_operators
import data.multiset.basic
/-!
# Sums and products over multisets
In this file we define products and sums indexed by multisets. This is later used to define products
and sums indexed by finite sets.
## Main declarations
* `multiset.prod`: `s.prod f` is the product of `f i` over all `i ∈ s`. Not to be mistaken with
the cartesian product `multiset.product`.
* `multiset.sum`: `s.sum f` is the sum of `f i` over all `i ∈ s`.
-/
variables {ι α β γ : Type*}
namespace multiset
section comm_monoid
variables [comm_monoid α] {s t : multiset α} {a : α} {m : multiset ι} {f g : ι → α}
/-- Product of a multiset given a commutative monoid structure on `α`.
`prod {a, b, c} = a * b * c` -/
@[to_additive "Sum of a multiset given a commutative additive monoid structure on `α`.
`sum {a, b, c} = a + b + c`"]
def prod : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1
@[to_additive]
lemma prod_eq_foldr (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s :=
rfl
@[to_additive]
lemma prod_eq_foldl (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s :=
(foldr_swap _ _ _ _).trans (by simp [mul_comm])
@[simp, norm_cast, to_additive] lemma coe_prod (l : list α) : prod ↑l = l.prod := prod_eq_foldl _
@[simp, to_additive]
lemma prod_to_list (s : multiset α) : s.to_list.prod = s.prod :=
begin
conv_rhs { rw ←coe_to_list s },
rw coe_prod,
end
@[simp, to_additive] lemma prod_zero : @prod α _ 0 = 1 := rfl
@[simp, to_additive]
lemma prod_cons (a : α) (s) : prod (a ::ₘ s) = a * prod s := foldr_cons _ _ _ _ _
@[simp, to_additive]
lemma prod_erase [decidable_eq α] (h : a ∈ s) : a * (s.erase a).prod = s.prod :=
by rw [← s.coe_to_list, coe_erase, coe_prod, coe_prod, list.prod_erase ((s.mem_to_list a).2 h)]
@[simp, to_additive]
lemma prod_singleton (a : α) : prod {a} = a :=
by simp only [mul_one, prod_cons, singleton_eq_cons, eq_self_iff_true, prod_zero]
@[to_additive]
lemma prod_pair (a b : α) : ({a, b} : multiset α).prod = a * b :=
by rw [insert_eq_cons, prod_cons, prod_singleton]
@[simp, to_additive]
lemma prod_add (s t : multiset α) : prod (s + t) = prod s * prod t :=
quotient.induction_on₂ s t $ λ l₁ l₂, by simp
lemma prod_nsmul (m : multiset α) : ∀ (n : ℕ), (n • m).prod = m.prod ^ n
| 0 := by { rw [zero_nsmul, pow_zero], refl }
| (n + 1) :=
by rw [add_nsmul, one_nsmul, pow_add, pow_one, prod_add, prod_nsmul n]
@[simp, to_additive] lemma prod_repeat (a : α) (n : ℕ) : (repeat a n).prod = a ^ n :=
by simp [repeat, list.prod_repeat]
@[to_additive]
lemma pow_count [decidable_eq α] (a : α) : a ^ s.count a = (s.filter (eq a)).prod :=
by rw [filter_eq, prod_repeat]
@[to_additive]
lemma prod_hom [comm_monoid β] (s : multiset α) {F : Type*} [monoid_hom_class F α β] (f : F) :
(s.map f).prod = f s.prod :=
quotient.induction_on s $ λ l, by simp only [l.prod_hom f, quot_mk_to_coe, coe_map, coe_prod]
@[to_additive]
lemma prod_hom' [comm_monoid β] (s : multiset ι) {F : Type*} [monoid_hom_class F α β] (f : F)
(g : ι → α) : (s.map $ λ i, f $ g i).prod = f (s.map g).prod :=
by { convert (s.map g).prod_hom f, exact (map_map _ _ _).symm }
@[to_additive]
lemma prod_hom₂ [comm_monoid β] [comm_monoid γ] (s : multiset ι) (f : α → β → γ)
(hf : ∀ a b c d, f (a * b) (c * d) = f a c * f b d) (hf' : f 1 1 = 1) (f₁ : ι → α) (f₂ : ι → β) :
(s.map $ λ i, f (f₁ i) (f₂ i)).prod = f (s.map f₁).prod (s.map f₂).prod :=
quotient.induction_on s $ λ l,
by simp only [l.prod_hom₂ f hf hf', quot_mk_to_coe, coe_map, coe_prod]
@[to_additive]
lemma prod_hom_rel [comm_monoid β] (s : multiset ι) {r : α → β → Prop} {f : ι → α} {g : ι → β}
(h₁ : r 1 1) (h₂ : ∀ ⦃a b c⦄, r b c → r (f a * b) (g a * c)) :
r (s.map f).prod (s.map g).prod :=
quotient.induction_on s $ λ l,
by simp only [l.prod_hom_rel h₁ h₂, quot_mk_to_coe, coe_map, coe_prod]
@[to_additive]
lemma prod_map_one : prod (m.map (λ i, (1 : α))) = 1 := by rw [map_const, prod_repeat, one_pow]
@[simp, to_additive]
lemma prod_map_mul : (m.map $ λ i, f i * g i).prod = (m.map f).prod * (m.map g).prod :=
m.prod_hom₂ (*) mul_mul_mul_comm (mul_one _) _ _
@[to_additive]
lemma prod_map_pow {n : ℕ} : (m.map $ λ i, f i ^ n).prod = (m.map f).prod ^ n :=
m.prod_hom' (pow_monoid_hom n : α →* α) f
@[to_additive]
lemma prod_map_prod_map (m : multiset β) (n : multiset γ) {f : β → γ → α} :
prod (m.map $ λ a, prod $ n.map $ λ b, f a b) = prod (n.map $ λ b, prod $ m.map $ λ a, f a b) :=
multiset.induction_on m (by simp) (λ a m ih, by simp [ih])
@[to_additive]
lemma prod_induction (p : α → Prop) (s : multiset α) (p_mul : ∀ a b, p a → p b → p (a * b))
(p_one : p 1) (p_s : ∀ a ∈ s, p a) :
p s.prod :=
begin
rw prod_eq_foldr,
exact foldr_induction (*) (λ x y z, by simp [mul_left_comm]) 1 p s p_mul p_one p_s,
end
@[to_additive]
lemma prod_induction_nonempty (p : α → Prop) (p_mul : ∀ a b, p a → p b → p (a * b))
(hs : s ≠ ∅) (p_s : ∀ a ∈ s, p a) :
p s.prod :=
begin
revert s,
refine multiset.induction _ _,
{ intro h,
exfalso,
simpa using h },
intros a s hs hsa hpsa,
rw prod_cons,
by_cases hs_empty : s = ∅,
{ simp [hs_empty, hpsa a] },
have hps : ∀ x, x ∈ s → p x, from λ x hxs, hpsa x (mem_cons_of_mem hxs),
exact p_mul a s.prod (hpsa a (mem_cons_self a s)) (hs hs_empty hps),
end
lemma dvd_prod : a ∈ s → a ∣ s.prod :=
quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a
lemma prod_dvd_prod_of_le (h : s ≤ t) : s.prod ∣ t.prod :=
begin
obtain ⟨z, rfl⟩ := multiset.le_iff_exists_add.1 h,
simp only [prod_add, dvd_mul_right],
end
end comm_monoid
lemma prod_dvd_prod_of_dvd [comm_monoid β] {S : multiset α} (g1 g2 : α → β)
(h : ∀ a ∈ S, g1 a ∣ g2 a) :
(multiset.map g1 S).prod ∣ (multiset.map g2 S).prod :=
begin
apply multiset.induction_on' S, { simp },
intros a T haS _ IH,
simp [mul_dvd_mul (h a haS) IH]
end
section add_comm_monoid
variables [add_comm_monoid α]
/-- `multiset.sum`, the sum of the elements of a multiset, promoted to a morphism of
`add_comm_monoid`s. -/
def sum_add_monoid_hom : multiset α →+ α :=
{ to_fun := sum,
map_zero' := sum_zero,
map_add' := sum_add }
@[simp] lemma coe_sum_add_monoid_hom : (sum_add_monoid_hom : multiset α → α) = sum := rfl
end add_comm_monoid
section comm_monoid_with_zero
variables [comm_monoid_with_zero α]
lemma prod_eq_zero {s : multiset α} (h : (0 : α) ∈ s) : s.prod = 0 :=
begin
rcases multiset.exists_cons_of_mem h with ⟨s', hs'⟩,
simp [hs', multiset.prod_cons]
end
variables [no_zero_divisors α] [nontrivial α] {s : multiset α}
lemma prod_eq_zero_iff : s.prod = 0 ↔ (0 : α) ∈ s :=
quotient.induction_on s $ λ l, by { rw [quot_mk_to_coe, coe_prod], exact list.prod_eq_zero_iff }
lemma prod_ne_zero (h : (0 : α) ∉ s) : s.prod ≠ 0 := mt prod_eq_zero_iff.1 h
end comm_monoid_with_zero
section comm_group
variables [comm_group α] {m : multiset ι} {f g : ι → α}
@[simp, to_additive]
lemma prod_map_inv' : (m.map $ λ i, (f i)⁻¹).prod = (m.map f).prod ⁻¹ :=
by { convert (m.map f).prod_hom (comm_group.inv_monoid_hom : α →* α), rw map_map, refl }
@[simp, to_additive]
lemma prod_map_div : (m.map $ λ i, f i / g i).prod = (m.map f).prod / (m.map g).prod :=
m.prod_hom₂ (/) mul_div_mul_comm (div_one _) _ _
@[to_additive]
lemma prod_map_zpow {n : ℤ} : (m.map $ λ i, f i ^ n).prod = (m.map f).prod ^ n :=
by { convert (m.map f).prod_hom (zpow_group_hom _ : α →* α), rw map_map, refl }
@[simp] lemma coe_inv_monoid_hom : (comm_group.inv_monoid_hom : α → α) = has_inv.inv := rfl
@[simp, to_additive]
lemma prod_map_inv (m : multiset α) : (m.map has_inv.inv).prod = m.prod⁻¹ :=
m.prod_hom (comm_group.inv_monoid_hom : α →* α)
end comm_group
section comm_group_with_zero
variables [comm_group_with_zero α] {m : multiset ι} {f g : ι → α}
@[simp]
lemma prod_map_inv₀ : (m.map $ λ i, (f i)⁻¹).prod = (m.map f).prod ⁻¹ :=
by { convert (m.map f).prod_hom (inv_monoid_with_zero_hom : α →*₀ α), rw map_map, refl }
@[simp]
lemma prod_map_div₀ : (m.map $ λ i, f i / g i).prod = (m.map f).prod / (m.map g).prod :=
m.prod_hom₂ (/) (λ _ _ _ _, (div_mul_div_comm _ _ _ _).symm) (div_one _) _ _
lemma prod_map_zpow₀ {n : ℤ} : prod (m.map $ λ i, f i ^ n) = (m.map f).prod ^ n :=
by { convert (m.map f).prod_hom (zpow_group_hom₀ _ : α →* α), rw map_map, refl }
end comm_group_with_zero
section non_unital_non_assoc_semiring
variables [non_unital_non_assoc_semiring α] {a : α} {s : multiset ι} {f : ι → α}
lemma _root_.commute.multiset_sum_right (s : multiset α) (a : α) (h : ∀ b ∈ s, commute a b) :
commute a s.sum :=
begin
induction s using quotient.induction_on,
rw [quot_mk_to_coe, coe_sum],
exact commute.list_sum_right _ _ h,
end
lemma _root_.commute.multiset_sum_left (s : multiset α) (b : α) (h : ∀ a ∈ s, commute a b) :
commute s.sum b :=
(commute.multiset_sum_right _ _ $ λ a ha, (h _ ha).symm).symm
lemma sum_map_mul_left : sum (s.map (λ i, a * f i)) = a * sum (s.map f) :=
multiset.induction_on s (by simp) (λ i s ih, by simp [ih, mul_add])
lemma sum_map_mul_right : sum (s.map (λ i, f i * a)) = sum (s.map f) * a :=
multiset.induction_on s (by simp) (λ a s ih, by simp [ih, add_mul])
end non_unital_non_assoc_semiring
section semiring
variables [semiring α]
lemma dvd_sum {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum :=
multiset.induction_on s (λ _, dvd_zero _)
(λ x s ih h, by { rw sum_cons, exact dvd_add
(h _ (mem_cons_self _ _)) (ih $ λ y hy, h _ $ mem_cons.2 $ or.inr hy) })
end semiring
/-! ### Order -/
section ordered_comm_monoid
variables [ordered_comm_monoid α] {s t : multiset α} {a : α}
@[to_additive sum_nonneg]
lemma one_le_prod_of_one_le : (∀ x ∈ s, (1 : α) ≤ x) → 1 ≤ s.prod :=
quotient.induction_on s $ λ l hl, by simpa using list.one_le_prod_of_one_le hl
@[to_additive]
lemma single_le_prod : (∀ x ∈ s, (1 : α) ≤ x) → ∀ x ∈ s, x ≤ s.prod :=
quotient.induction_on s $ λ l hl x hx, by simpa using list.single_le_prod hl x hx
@[to_additive sum_le_card_nsmul]
lemma prod_le_pow_card (s : multiset α) (n : α) (h : ∀ x ∈ s, x ≤ n) : s.prod ≤ n ^ s.card :=
begin
induction s using quotient.induction_on,
simpa using list.prod_le_pow_card _ _ h,
end
@[to_additive all_zero_of_le_zero_le_of_sum_eq_zero]
lemma all_one_of_le_one_le_of_prod_eq_one :
(∀ x ∈ s, (1 : α) ≤ x) → s.prod = 1 → ∀ x ∈ s, x = (1 : α) :=
begin
apply quotient.induction_on s,
simp only [quot_mk_to_coe, coe_prod, mem_coe],
exact λ l, list.all_one_of_le_one_le_of_prod_eq_one,
end
@[to_additive]
lemma prod_le_prod_of_rel_le (h : s.rel (≤) t) : s.prod ≤ t.prod :=
begin
induction h with _ _ _ _ rh _ rt,
{ refl },
{ rw [prod_cons, prod_cons],
exact mul_le_mul' rh rt }
end
@[to_additive]
lemma prod_map_le_prod (f : α → α) (h : ∀ x, x ∈ s → f x ≤ x) : (s.map f).prod ≤ s.prod :=
prod_le_prod_of_rel_le $ rel_map_left.2 $ rel_refl_of_refl_on h
@[to_additive]
lemma prod_le_sum_prod (f : α → α) (h : ∀ x, x ∈ s → x ≤ f x) : s.prod ≤ (s.map f).prod :=
@prod_map_le_prod αᵒᵈ _ _ f h
@[to_additive card_nsmul_le_sum]
lemma pow_card_le_prod (h : ∀ x ∈ s, a ≤ x) : a ^ s.card ≤ s.prod :=
by { rw [←multiset.prod_repeat, ←multiset.map_const], exact prod_map_le_prod _ h }
end ordered_comm_monoid
lemma prod_nonneg [ordered_comm_semiring α] {m : multiset α} (h : ∀ a ∈ m, (0 : α) ≤ a) :
0 ≤ m.prod :=
begin
revert h,
refine m.induction_on _ _,
{ rintro -, rw prod_zero, exact zero_le_one },
intros a s hs ih,
rw prod_cons,
exact mul_nonneg (ih _ $ mem_cons_self _ _) (hs $ λ a ha, ih _ $ mem_cons_of_mem ha),
end
@[to_additive]
lemma prod_eq_one_iff [canonically_ordered_monoid α] {m : multiset α} :
m.prod = 1 ↔ ∀ x ∈ m, x = (1 : α) :=
quotient.induction_on m $ λ l, by simpa using list.prod_eq_one_iff l
@[to_additive]
lemma le_prod_of_mem [canonically_ordered_monoid α] {m : multiset α} {a : α} (h : a ∈ m) :
a ≤ m.prod :=
begin
obtain ⟨m', rfl⟩ := exists_cons_of_mem h,
rw [prod_cons],
exact _root_.le_mul_right (le_refl a),
end
@[to_additive le_sum_of_subadditive_on_pred]
lemma le_prod_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (p : α → Prop) (h_one : f 1 = 1) (hp_one : p 1)
(h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b)
(hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hps : ∀ a, a ∈ s → p a) :
f s.prod ≤ (s.map f).prod :=
begin
revert s,
refine multiset.induction _ _,
{ simp [le_of_eq h_one] },
intros a s hs hpsa,
have hps : ∀ x, x ∈ s → p x, from λ x hx, hpsa x (mem_cons_of_mem hx),
have hp_prod : p s.prod, from prod_induction p s hp_mul hp_one hps,
rw [prod_cons, map_cons, prod_cons],
exact (h_mul a s.prod (hpsa a (mem_cons_self a s)) hp_prod).trans (mul_le_mul_left' (hs hps) _),
end
@[to_additive le_sum_of_subadditive]
lemma le_prod_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (h_one : f 1 = 1) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) :
f s.prod ≤ (s.map f).prod :=
le_prod_of_submultiplicative_on_pred f (λ i, true) h_one trivial (λ x y _ _ , h_mul x y) (by simp)
s (by simp)
@[to_additive le_sum_nonempty_of_subadditive_on_pred]
lemma le_prod_nonempty_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (p : α → Prop) (h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b)
(hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hs_nonempty : s ≠ ∅)
(hs : ∀ a, a ∈ s → p a) :
f s.prod ≤ (s.map f).prod :=
begin
revert s,
refine multiset.induction _ _,
{ intro h,
exfalso,
exact h rfl },
rintros a s hs hsa_nonempty hsa_prop,
rw [prod_cons, map_cons, prod_cons],
by_cases hs_empty : s = ∅,
{ simp [hs_empty] },
have hsa_restrict : (∀ x, x ∈ s → p x), from λ x hx, hsa_prop x (mem_cons_of_mem hx),
have hp_sup : p s.prod,
from prod_induction_nonempty p hp_mul hs_empty hsa_restrict,
have hp_a : p a, from hsa_prop a (mem_cons_self a s),
exact (h_mul a _ hp_a hp_sup).trans (mul_le_mul_left' (hs hs_empty hsa_restrict) _),
end
@[to_additive le_sum_nonempty_of_subadditive]
lemma le_prod_nonempty_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) (hs_nonempty : s ≠ ∅) :
f s.prod ≤ (s.map f).prod :=
le_prod_nonempty_of_submultiplicative_on_pred f (λ i, true) (by simp [h_mul]) (by simp) s
hs_nonempty (by simp)
@[simp] lemma sum_map_singleton (s : multiset α) : (s.map (λ a, ({a} : multiset α))).sum = s :=
multiset.induction_on s (by simp) (by simp [singleton_eq_cons])
lemma abs_sum_le_sum_abs [linear_ordered_add_comm_group α] {s : multiset α} :
abs s.sum ≤ (s.map abs).sum :=
le_sum_of_subadditive _ abs_zero abs_add s
end multiset
@[to_additive]
lemma map_multiset_prod [comm_monoid α] [comm_monoid β] {F : Type*} [monoid_hom_class F α β]
(f : F) (s : multiset α) : f s.prod = (s.map f).prod :=
(s.prod_hom f).symm
@[to_additive]
protected lemma monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β)
(s : multiset α) : f s.prod = (s.map f).prod :=
(s.prod_hom f).symm
|
90388317f5a2c150e59a6f864b5a25e7da1de872 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/topology/category/CompHaus/default.lean | 9edabf81fac5ea5847fd5d60663afe95284243c7 | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,616 | lean | /-
Copyright (c) 2020 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz, Bhavik Mehta
-/
import category_theory.adjunction.reflective
import topology.category.Top
import topology.stone_cech
import category_theory.monad.limits
import topology.urysohns_lemma
/-!
# The category of Compact Hausdorff Spaces
We construct the category of compact Hausdorff spaces.
The type of compact Hausdorff spaces is denoted `CompHaus`, and it is endowed with a category
instance making it a full subcategory of `Top`.
The fully faithful functor `CompHaus ⥤ Top` is denoted `CompHaus_to_Top`.
**Note:** The file `topology/category/Compactum.lean` provides the equivalence between `Compactum`,
which is defined as the category of algebras for the ultrafilter monad, and `CompHaus`.
`Compactum_to_CompHaus` is the functor from `Compactum` to `CompHaus` which is proven to be an
equivalence of categories in `Compactum_to_CompHaus.is_equivalence`.
See `topology/category/Compactum.lean` for a more detailed discussion where these definitions are
introduced.
-/
universe u
open category_theory
/-- The type of Compact Hausdorff topological spaces. -/
structure CompHaus :=
(to_Top : Top)
[is_compact : compact_space to_Top]
[is_hausdorff : t2_space to_Top]
namespace CompHaus
instance : inhabited CompHaus := ⟨{to_Top := { α := pempty }}⟩
instance : has_coe_to_sort CompHaus := ⟨Type*, λ X, X.to_Top⟩
instance {X : CompHaus} : compact_space X := X.is_compact
instance {X : CompHaus} : t2_space X := X.is_hausdorff
instance category : category CompHaus := induced_category.category to_Top
instance concrete_category : concrete_category CompHaus :=
induced_category.concrete_category _
@[simp]
lemma coe_to_Top {X : CompHaus} : (X.to_Top : Type*) = X :=
rfl
variables (X : Type*) [topological_space X] [compact_space X] [t2_space X]
/-- A constructor for objects of the category `CompHaus`,
taking a type, and bundling the compact Hausdorff topology
found by typeclass inference. -/
def of : CompHaus :=
{ to_Top := Top.of X,
is_compact := ‹_›,
is_hausdorff := ‹_› }
@[simp] lemma coe_of : (CompHaus.of X : Type _) = X := rfl
/-- Any continuous function on compact Hausdorff spaces is a closed map. -/
lemma is_closed_map {X Y : CompHaus.{u}} (f : X ⟶ Y) : is_closed_map f :=
λ C hC, (hC.is_compact.image f.continuous).is_closed
/-- Any continuous bijection of compact Hausdorff spaces is an isomorphism. -/
lemma is_iso_of_bijective {X Y : CompHaus.{u}} (f : X ⟶ Y) (bij : function.bijective f) :
is_iso f :=
begin
let E := equiv.of_bijective _ bij,
have hE : continuous E.symm,
{ rw continuous_iff_is_closed,
intros S hS,
rw ← E.image_eq_preimage,
exact is_closed_map f S hS },
refine ⟨⟨⟨E.symm, hE⟩, _, _⟩⟩,
{ ext x,
apply E.symm_apply_apply },
{ ext x,
apply E.apply_symm_apply }
end
/-- Any continuous bijection of compact Hausdorff spaces induces an isomorphism. -/
noncomputable
def iso_of_bijective {X Y : CompHaus.{u}} (f : X ⟶ Y) (bij : function.bijective f) : X ≅ Y :=
by letI := is_iso_of_bijective _ bij; exact as_iso f
end CompHaus
/-- The fully faithful embedding of `CompHaus` in `Top`. -/
@[simps {rhs_md := semireducible}, derive [full, faithful]]
def CompHaus_to_Top : CompHaus.{u} ⥤ Top.{u} := induced_functor _
instance CompHaus.forget_reflects_isomorphisms : reflects_isomorphisms (forget CompHaus.{u}) :=
⟨by introsI A B f hf; exact CompHaus.is_iso_of_bijective _ ((is_iso_iff_bijective ⇑f).mp hf)⟩
/--
(Implementation) The object part of the compactification functor from topological spaces to
compact Hausdorff spaces.
-/
@[simps]
def StoneCech_obj (X : Top) : CompHaus := CompHaus.of (stone_cech X)
/--
(Implementation) The bijection of homsets to establish the reflective adjunction of compact
Hausdorff spaces in topological spaces.
-/
noncomputable def stone_cech_equivalence (X : Top.{u}) (Y : CompHaus.{u}) :
(StoneCech_obj X ⟶ Y) ≃ (X ⟶ CompHaus_to_Top.obj Y) :=
{ to_fun := λ f,
{ to_fun := f ∘ stone_cech_unit,
continuous_to_fun := f.2.comp (@continuous_stone_cech_unit X _) },
inv_fun := λ f,
{ to_fun := stone_cech_extend f.2,
continuous_to_fun := continuous_stone_cech_extend f.2 },
left_inv :=
begin
rintro ⟨f : stone_cech X ⟶ Y, hf : continuous f⟩,
ext (x : stone_cech X),
refine congr_fun _ x,
apply continuous.ext_on dense_range_stone_cech_unit (continuous_stone_cech_extend _) hf,
rintro _ ⟨y, rfl⟩,
apply congr_fun (stone_cech_extend_extends (hf.comp _)) y,
end,
right_inv :=
begin
rintro ⟨f : ↥X ⟶ Y, hf : continuous f⟩,
ext,
exact congr_fun (stone_cech_extend_extends hf) x,
end }
/--
The Stone-Cech compactification functor from topological spaces to compact Hausdorff spaces,
left adjoint to the inclusion functor.
-/
noncomputable def Top_to_CompHaus : Top.{u} ⥤ CompHaus.{u} :=
adjunction.left_adjoint_of_equiv stone_cech_equivalence.{u} (λ _ _ _ _ _, rfl)
lemma Top_to_CompHaus_obj (X : Top) : ↥(Top_to_CompHaus.obj X) = stone_cech X :=
rfl
/--
The category of compact Hausdorff spaces is reflective in the category of topological spaces.
-/
noncomputable instance CompHaus_to_Top.reflective : reflective CompHaus_to_Top :=
{ to_is_right_adjoint := ⟨Top_to_CompHaus, adjunction.adjunction_of_equiv_left _ _⟩ }
noncomputable instance CompHaus_to_Top.creates_limits : creates_limits CompHaus_to_Top :=
monadic_creates_limits _
instance CompHaus.has_limits : limits.has_limits CompHaus :=
has_limits_of_has_limits_creates_limits CompHaus_to_Top
instance CompHaus.has_colimits : limits.has_colimits CompHaus :=
has_colimits_of_reflective CompHaus_to_Top
namespace CompHaus
/-- An explicit limit cone for a functor `F : J ⥤ CompHaus`, defined in terms of
`Top.limit_cone`. -/
def limit_cone {J : Type u} [small_category J] (F : J ⥤ CompHaus.{u}) :
limits.cone F :=
{ X :=
{ to_Top := (Top.limit_cone (F ⋙ CompHaus_to_Top)).X,
is_compact := begin
show compact_space ↥{u : Π j, (F.obj j) | ∀ {i j : J} (f : i ⟶ j), (F.map f) (u i) = u j},
rw ← is_compact_iff_compact_space,
apply is_closed.is_compact,
have : {u : Π j, F.obj j | ∀ {i j : J} (f : i ⟶ j), F.map f (u i) = u j} =
⋂ (i j : J) (f : i ⟶ j), {u | F.map f (u i) = u j},
{ ext1, simp only [set.mem_Inter, set.mem_set_of_eq], },
rw this,
apply is_closed_Inter, intros i,
apply is_closed_Inter, intros j,
apply is_closed_Inter, intros f,
apply is_closed_eq,
{ exact (continuous_map.continuous (F.map f)).comp (continuous_apply i), },
{ exact continuous_apply j, }
end,
is_hausdorff :=
show t2_space ↥{u : Π j, (F.obj j) | ∀ {i j : J} (f : i ⟶ j), (F.map f) (u i) = u j},
from infer_instance },
π :=
{ app := λ j, (Top.limit_cone (F ⋙ CompHaus_to_Top)).π.app j,
naturality' := by { intros _ _ _, ext ⟨x, hx⟩,
simp only [comp_apply, functor.const.obj_map, id_apply], exact (hx f).symm, } } }
/-- The limit cone `CompHaus.limit_cone F` is indeed a limit cone. -/
def limit_cone_is_limit {J : Type u} [small_category J] (F : J ⥤ CompHaus.{u}) :
limits.is_limit (limit_cone F) :=
{ lift := λ S,
(Top.limit_cone_is_limit (F ⋙ CompHaus_to_Top)).lift (CompHaus_to_Top.map_cone S),
uniq' := λ S m h, (Top.limit_cone_is_limit _).uniq (CompHaus_to_Top.map_cone S) _ h }
lemma epi_iff_surjective {X Y : CompHaus.{u}} (f : X ⟶ Y) : epi f ↔ function.surjective f :=
begin
split,
{ contrapose!,
rintros ⟨y, hy⟩ hf,
let C := set.range f,
have hC : is_closed C := (is_compact_range f.continuous).is_closed,
let D := {y},
have hD : is_closed D := is_closed_singleton,
have hCD : disjoint C D,
{ rw set.disjoint_singleton_right, rintro ⟨y', hy'⟩, exact hy y' hy' },
haveI : normal_space ↥(Y.to_Top) := normal_of_compact_t2,
obtain ⟨φ, hφ0, hφ1, hφ01⟩ := exists_continuous_zero_one_of_closed hC hD hCD,
haveI : compact_space (ulift.{u} $ set.Icc (0:ℝ) 1) := homeomorph.ulift.symm.compact_space,
haveI : t2_space (ulift.{u} $ set.Icc (0:ℝ) 1) := homeomorph.ulift.symm.t2_space,
let Z := of (ulift.{u} $ set.Icc (0:ℝ) 1),
let g : Y ⟶ Z := ⟨λ y', ⟨⟨φ y', hφ01 y'⟩⟩,
continuous_ulift_up.comp (continuous_subtype_mk (λ y', hφ01 y') φ.continuous)⟩,
let h : Y ⟶ Z := ⟨λ _, ⟨⟨0, set.left_mem_Icc.mpr zero_le_one⟩⟩, continuous_const⟩,
have H : h = g,
{ rw ← cancel_epi f,
ext x, dsimp,
simp only [comp_apply, continuous_map.coe_mk, subtype.coe_mk, hφ0 (set.mem_range_self x),
pi.zero_apply], },
apply_fun (λ e, (e y).down) at H,
dsimp at H,
simp only [subtype.mk_eq_mk, hφ1 (set.mem_singleton y), pi.one_apply] at H,
exact zero_ne_one H, },
{ rw ← category_theory.epi_iff_surjective,
apply faithful_reflects_epi (forget CompHaus) },
end
lemma mono_iff_injective {X Y : CompHaus.{u}} (f : X ⟶ Y) : mono f ↔ function.injective f :=
begin
split,
{ introsI hf x₁ x₂ h,
let g₁ : of punit ⟶ X := ⟨λ _, x₁, continuous_of_discrete_topology⟩,
let g₂ : of punit ⟶ X := ⟨λ _, x₂, continuous_of_discrete_topology⟩,
have : g₁ ≫ f = g₂ ≫ f, by { ext, exact h },
rw cancel_mono at this,
apply_fun (λ e, e punit.star) at this,
exact this },
{ rw ← category_theory.mono_iff_injective,
apply faithful_reflects_mono (forget CompHaus) }
end
end CompHaus
|
3b4f39318fd30b53e9b75790dbb743e6b196aa16 | b9def12ac9858ba514e44c0758ebb4e9b73ae5ed | /src/monoidal_categories_reboot/hypergraph_category.lean | b5e9aab6716d34c38dc15b448a37b555a2daf417 | [
"Apache-2.0"
] | permissive | cipher1024/monoidal-categories-reboot | 5f826017db2f71920336331739a0f84be2f97bf7 | 998f2a0553c22369d922195dc20a20fa7dccc6e5 | refs/heads/master | 1,586,710,273,395 | 1,543,592,573,000 | 1,543,592,573,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,963 | lean | -- Copyright (c) 2018 Michael Jendrusch. All rights reserved.
import .monoidal_category
import .braided_monoidal_category
import .monoid_object
universes u v
namespace category_theory.hypergraph
open category_theory.monoidal
open category_theory.monoidal.monoidal_category
open category_theory.monoidal.braided_monoidal_category
@[reducible]
def reassociate_and_braid_product {C : Type u} (X Y : C) [symmetric_monoidal_category.{u v} C] :=
(associator X Y (X ⊗ Y)).hom ≫ ((𝟙 X) ⊗ (associator Y X Y).inv) ≫
((𝟙 X) ⊗ (braiding Y X).hom ⊗ (𝟙 Y)) ≫ (associator X (X ⊗ Y) Y).inv ≫
((associator X X Y).inv ⊗ (𝟙 Y)) ≫ (associator (X ⊗ X) Y Y).hom
@[reducible]
def reassociate_and_braid_coproduct {C : Type u} (X Y : C) [symmetric_monoidal_category.{u v} C] :=
(associator X X (Y ⊗ Y)).hom ≫ ((𝟙 X) ⊗ (associator X Y Y).inv) ≫
((𝟙 X) ⊗ (braiding X Y).hom ⊗ (𝟙 Y)) ≫
((𝟙 X) ⊗ (associator Y X Y).hom) ≫ (associator X Y (X ⊗ Y)).inv
class hypergraph_category (C : Type u) extends symmetric_monoidal_category.{u v} C :=
-- each object is equipped with the structure of a special commutative Frobenius monoid:
(frobenius_structure : Π X : C, special_commutative_frobenius_object X)
-- the Frobenius structure and the tensor product interact in the obvious way:
(product_tensor' : Π X Y : C,
reassociate_and_braid_product X Y ≫
((frobenius_structure X).product ⊗ (frobenius_structure Y).product)
= (frobenius_structure (X ⊗ Y)).product
. obviously)
(coproduct_tensor' : Π X Y : C,
((frobenius_structure X).coproduct ⊗ (frobenius_structure Y).coproduct) ≫
reassociate_and_braid_coproduct X Y
= (frobenius_structure (X ⊗ Y)).coproduct
. obviously)
(unit_tensor' : Π X Y : C,
(left_unitor tensor_unit).inv ≫
((frobenius_structure X).unit ⊗ (frobenius_structure Y).unit)
= (frobenius_structure (X ⊗ Y)).unit
. obviously)
(counit_tensor' : Π X Y : C,
((frobenius_structure X).counit ⊗ (frobenius_structure Y).counit) ≫
(left_unitor tensor_unit).hom
= (frobenius_structure (X ⊗ Y)).counit
. obviously)
restate_axiom hypergraph_category.product_tensor'
attribute [search] hypergraph_category.product_tensor
restate_axiom hypergraph_category.coproduct_tensor'
attribute [search] hypergraph_category.coproduct_tensor
restate_axiom hypergraph_category.unit_tensor'
attribute [search] hypergraph_category.unit_tensor
restate_axiom hypergraph_category.counit_tensor'
attribute [search] hypergraph_category.counit_tensor
end category_theory.hypergraph
|
15a21594f8e7e340f3245a837644f0b66b507ead | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/complex/determinant.lean | 7e1fc42dd016ccfb6f3536dbe0a5fcda7dcc6329 | [
"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 | 958 | lean | /-
Copyright (c) 2022 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import data.complex.module
import linear_algebra.determinant
/-!
# Determinants of maps in the complex numbers as a vector space over `ℝ`
This file provides results about the determinants of maps in the complex numbers as a vector
space over `ℝ`.
-/
namespace complex
/-- The determinant of `conj_ae`, as a linear map. -/
@[simp] lemma det_conj_ae : conj_ae.to_linear_map.det = -1 :=
begin
rw [←linear_map.det_to_matrix basis_one_I, to_matrix_conj_ae, matrix.det_fin_two],
simp
end
/-- The determinant of `conj_ae`, as a linear equiv. -/
@[simp] lemma linear_equiv_det_conj_ae : conj_ae.to_linear_equiv.det = -1 :=
by rw [←units.eq_iff, linear_equiv.coe_det, ←linear_equiv.to_linear_map_eq_coe,
alg_equiv.to_linear_equiv_to_linear_map, det_conj_ae, units.coe_neg_one]
end complex
|
00f83e3caeb28a99a589551d2bbdf44cbebe140a | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/measure_theory/ae_eq_fun.lean | 79009cc4d18853417e02a166dee574569bc3d72a | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 22,541 | lean | /-
Copyright (c) 2019 Johannes Hölzl, Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Zhouhang Zhou
-/
import measure_theory.integration
/-!
# Almost everywhere equal functions
Two measurable functions are treated as identical if they are almost everywhere equal. We form the
set of equivalence classes under the relation of being almost everywhere equal, which is sometimes
known as the `L⁰` space.
See `l1_space.lean` for `L¹` space.
## Notation
* `α →ₘ β` is the type of `L⁰` space, where `α` is a measure space and `β` is a measurable space.
`f : α →ₘ β` is a "function" in `L⁰`. In comments, `[f]` is also used to denote an `L⁰` function.
`ₘ` can be typed as `\_m`. Sometimes it is shown as a box if font is missing.
## Main statements
* The linear structure of `L⁰` :
Addition and scalar multiplication are defined on `L⁰` in the natural way, i.e.,
`[f] + [g] := [f + g]`, `c • [f] := [c • f]`. So defined, `α →ₘ β` inherits the linear structure
of `β`. For example, if `β` is a module, then `α →ₘ β` is a module over the same ring.
See `mk_add_mk`, `neg_mk`, `mk_sub_mk`, `smul_mk`,
`add_to_fun`, `neg_to_fun`, `sub_to_fun`, `smul_to_fun`
* The order structure of `L⁰` :
`≤` can be defined in a similar way: `[f] ≤ [g]` if `f a ≤ g a` for almost all `a` in domain.
And `α →ₘ β` inherits the preorder and partial order of `β`.
TODO: Define `sup` and `inf` on `L⁰` so that it forms a lattice. It seems that `β` must be a
linear order, since otherwise `f ⊔ g` may not be a measurable function.
* Emetric on `L⁰` :
If `β` is an `emetric_space`, then `L⁰` can be made into an `emetric_space`, where
`edist [f] [g]` is defined to be `∫⁻ a, edist (f a) (g a)`.
The integral used here is `lintegral : (α → ennreal) → ennreal`, which is defined in the file
`integration.lean`.
See `edist_mk_mk` and `edist_to_fun`.
## Implementation notes
* `f.to_fun` : To find a representative of `f : α →ₘ β`, use `f.to_fun`.
For each operation `op` in `L⁰`, there is a lemma called `op_to_fun`, characterizing,
say, `(f op g).to_fun`.
* `ae_eq_fun.mk` : To constructs an `L⁰` function `α →ₘ β` from a measurable function `f : α → β`,
use `ae_eq_fun.mk`
* `comp` : Use `comp g f` to get `[g ∘ f]` from `g : β → γ` and `[f] : α →ₘ γ`
* `comp₂` : Use `comp₂ g f₁ f₂ to get `[λa, g (f₁ a) (f₂ a)]`.
For example, `[f + g]` is `comp₂ (+)`
## Tags
function space, almost everywhere equal, `L⁰`, ae_eq_fun
-/
noncomputable theory
open_locale classical
namespace measure_theory
open set lattice filter topological_space
universes u v
variables {α : Type u} {β : Type v} [measure_space α]
section measurable_space
variables [measurable_space β]
variables (α β)
/-- The equivalence relation of being almost everywhere equal -/
instance ae_eq_fun.setoid : setoid { f : α → β // measurable f } :=
⟨ λf g, ∀ₘ a, f.1 a = g.1 a,
assume ⟨f, hf⟩, by filter_upwards [] assume a, rfl,
assume ⟨f, hf⟩ ⟨g, hg⟩ hfg, by filter_upwards [hfg] assume a, eq.symm,
assume ⟨f, hf⟩ ⟨g, hg⟩ ⟨h, hh⟩ hfg hgh, by filter_upwards [hfg, hgh] assume a, eq.trans ⟩
/-- The space of equivalence classes of measurable functions, where two measurable functions are
equivalent if they agree almost everywhere, i.e., they differ on a set of measure `0`. -/
def ae_eq_fun : Type (max u v) := quotient (ae_eq_fun.setoid α β)
variables {α β}
infixr ` →ₘ `:25 := ae_eq_fun
end measurable_space
namespace ae_eq_fun
variables [measurable_space β]
/-- Construct the equivalence class `[f]` of a measurable function `f`, based on the equivalence
relation of being almost everywhere equal. -/
def mk (f : α → β) (hf : measurable f) : α →ₘ β := quotient.mk ⟨f, hf⟩
/-- A representative of an `ae_eq_fun` [f] -/
protected def to_fun (f : α →ₘ β) : α → β := @quotient.out _ (ae_eq_fun.setoid α β) f
protected lemma measurable (f : α →ₘ β) : measurable f.to_fun :=
(@quotient.out _ (ae_eq_fun.setoid α β) f).2
instance : has_coe (α →ₘ β) (α → β) := ⟨λf, f.to_fun⟩
@[simp] lemma quot_mk_eq_mk (f : {f : α → β // measurable f}) : quot.mk setoid.r f = mk f.1 f.2 :=
by cases f; refl
@[simp] lemma mk_eq_mk (f g : α → β) (hf hg) :
mk f hf = mk g hg ↔ (∀ₘ a, f a = g a) :=
⟨quotient.exact, assume h, quotient.sound h⟩
@[ext] lemma ext (f g : α →ₘ β) (f' g' : α → β) (hf' hg') (hf : mk f' hf' = f)
(hg : mk g' hg' = g) (h : ∀ₘ a, f' a = g' a) : f = g :=
by { rw [← hf, ← hg], rw mk_eq_mk, assumption }
lemma self_eq_mk (f : α →ₘ β) : f = mk (f.to_fun) f.measurable :=
by simp [mk, ae_eq_fun.to_fun]
lemma all_ae_mk_to_fun (f : α → β) (hf) : ∀ₘ a, (mk f hf).to_fun a = f a :=
by rw [← mk_eq_mk _ f _ hf, ← self_eq_mk (mk f hf)]
/-- Given a measurable function `g : β → γ`, and an almost everywhere equal function `[f] : α →ₘ β`,
return the equivalence class of `g ∘ f`, i.e., the almost everywhere equal function
`[g ∘ f] : α →ₘ γ`. -/
def comp {γ : Type*} [measurable_space γ] (g : β → γ) (hg : measurable g) (f : α →ₘ β) : α →ₘ γ :=
quotient.lift_on f (λf, mk (g ∘ f.1) (measurable.comp hg f.2)) $ assume f₁ f₂ eq,
by refine quotient.sound _; filter_upwards [eq] assume a, congr_arg g
@[simp] lemma comp_mk {γ : Type*} [measurable_space γ] (g : β → γ) (hg : measurable g)
(f : α → β) (hf) : comp g hg (mk f hf) = mk (g ∘ f) (measurable.comp hg hf) :=
rfl
lemma comp_eq_mk_to_fun {γ : Type*} [measurable_space γ] (g : β → γ) (hg : measurable g) (f : α →ₘ β) :
comp g hg f = mk (g ∘ f.to_fun) (hg.comp f.measurable) :=
by conv_lhs { rw [self_eq_mk f, comp_mk] }
lemma comp_to_fun {γ : Type*} [measurable_space γ] (g : β → γ) (hg : measurable g) (f : α →ₘ β) :
∀ₘ a, (comp g hg f).to_fun a = (g ∘ f.to_fun) a :=
by { rw comp_eq_mk_to_fun, apply all_ae_mk_to_fun }
/-- Given a measurable function `g : β → γ → δ`, and almost everywhere equal functions
`[f₁] : α →ₘ β` and `[f₂] : α →ₘ γ`, return the equivalence class of the function
`λa, g (f₁ a) (f₂ a)`, i.e., the almost everywhere equal function
`[λa, g (f₁ a) (f₂ a)] : α →ₘ γ` -/
def comp₂ {γ δ : Type*} [measurable_space γ] [measurable_space δ]
(g : β → γ → δ) (hg : measurable (λp:β×γ, g p.1 p.2)) (f₁ : α →ₘ β) (f₂ : α →ₘ γ) : α →ₘ δ :=
begin
refine quotient.lift_on₂ f₁ f₂ (λf₁ f₂, mk (λa, g (f₁.1 a) (f₂.1 a)) $ _) _,
{ exact measurable.comp hg (measurable.prod_mk f₁.2 f₂.2) },
{ rintros ⟨f₁, hf₁⟩ ⟨f₂, hf₂⟩ ⟨g₁, hg₁⟩ ⟨g₂, hg₂⟩ h₁ h₂,
refine quotient.sound _,
filter_upwards [h₁, h₂],
simp {contextual := tt} }
end
@[simp] lemma comp₂_mk_mk {γ δ : Type*} [measurable_space γ] [measurable_space δ]
(g : β → γ → δ) (hg : measurable (λp:β×γ, g p.1 p.2)) (f₁ : α → β) (f₂ : α → γ) (hf₁ hf₂) :
comp₂ g hg (mk f₁ hf₁) (mk f₂ hf₂) =
mk (λa, g (f₁ a) (f₂ a)) (measurable.comp hg (measurable.prod_mk hf₁ hf₂)) :=
rfl
lemma comp₂_eq_mk_to_fun {γ δ : Type*} [measurable_space γ] [measurable_space δ]
(g : β → γ → δ) (hg : measurable (λp:β×γ, g p.1 p.2)) (f₁ : α →ₘ β) (f₂ : α →ₘ γ) :
comp₂ g hg f₁ f₂ = mk (λa, g (f₁.to_fun a) (f₂.to_fun a))
(hg.comp (measurable.prod_mk f₁.measurable f₂.measurable)) :=
by conv_lhs { rw [self_eq_mk f₁, self_eq_mk f₂, comp₂_mk_mk] }
lemma comp₂_to_fun {γ δ : Type*} [measurable_space γ] [measurable_space δ]
(g : β → γ → δ) (hg : measurable (λp:β×γ, g p.1 p.2)) (f₁ : α →ₘ β) (f₂ : α →ₘ γ) :
∀ₘ a, (comp₂ g hg f₁ f₂).to_fun a = g (f₁.to_fun a) (f₂.to_fun a) :=
by { rw comp₂_eq_mk_to_fun, apply all_ae_mk_to_fun }
/-- Given a predicate `p` and an equivalence class `[f]`, return true if `p` holds of `f a`
for almost all `a` -/
def lift_pred (p : β → Prop) (f : α →ₘ β) : Prop :=
quotient.lift_on f (λf, ∀ₘ a, p (f.1 a))
begin
assume f g h, dsimp, refine propext (all_ae_congr _),
filter_upwards [h], simp {contextual := tt}
end
/-- Given a relation `r` and equivalence class `[f]` and `[g]`, return true if `r` holds of
`(f a, g a)` for almost all `a` -/
def lift_rel {γ : Type*} [measurable_space γ] (r : β → γ → Prop) (f : α →ₘ β) (g : α →ₘ γ) : Prop :=
lift_pred (λp:β×γ, r p.1 p.2)
(comp₂ prod.mk (measurable.prod_mk
(measurable.fst measurable_id) (measurable.snd measurable_id)) f g)
lemma lift_rel_mk_mk {γ : Type*} [measurable_space γ] (r : β → γ → Prop)
(f : α → β) (g : α → γ) (hf hg) : lift_rel r (mk f hf) (mk g hg) ↔ ∀ₘ a, r (f a) (g a) :=
iff.rfl
lemma lift_rel_iff_to_fun {γ : Type*} [measurable_space γ] (r : β → γ → Prop) (f : α →ₘ β)
(g : α →ₘ γ) : lift_rel r f g ↔ ∀ₘ a, r (f.to_fun a) (g.to_fun a) :=
by conv_lhs { rw [self_eq_mk f, self_eq_mk g, lift_rel_mk_mk] }
section order
instance [preorder β] : preorder (α →ₘ β) :=
{ le := lift_rel (≤),
le_refl := by rintros ⟨⟨f, hf⟩⟩; exact univ_mem_sets' (assume a, le_refl _),
le_trans :=
begin
rintros ⟨⟨f, hf⟩⟩ ⟨⟨g, hg⟩⟩ ⟨⟨h, hh⟩⟩ hfg hgh,
filter_upwards [hfg, hgh] assume a, le_trans
end }
lemma mk_le_mk [preorder β] {f g : α → β} (hf hg) : mk f hf ≤ mk g hg ↔ ∀ₘ a, f a ≤ g a :=
iff.rfl
lemma le_iff_to_fun_le [preorder β] {f g : α →ₘ β} : f ≤ g ↔ ∀ₘ a, f.to_fun a ≤ g.to_fun a :=
by { conv_lhs { rw [self_eq_mk f, self_eq_mk g] }, rw mk_le_mk }
instance [partial_order β] : partial_order (α →ₘ β) :=
{ le_antisymm :=
begin
rintros ⟨⟨f, hf⟩⟩ ⟨⟨g, hg⟩⟩ hfg hgf,
refine quotient.sound _,
filter_upwards [hfg, hgf] assume a, le_antisymm
end,
.. ae_eq_fun.preorder }
/- TODO: Prove `L⁰` space is a lattice if β is linear order.
What if β is only a lattice? -/
-- instance [linear_order β] : semilattice_sup (α →ₘ β) :=
-- { sup := comp₂ (⊔) (_),
-- .. ae_eq_fun.partial_order }
end order
variable (α)
/-- The equivalence class of a constant function: `[λa:α, b]`, based on the equivalence relation of
being almost everywhere equal -/
def const (b : β) : α →ₘ β := mk (λa:α, b) measurable_const
lemma const_to_fun (b : β) : ∀ₘ a, (const α b).to_fun a = b := all_ae_mk_to_fun _ _
variable {α}
instance [has_zero β] : has_zero (α →ₘ β) := ⟨const α 0⟩
lemma zero_def [has_zero β] : (0 : α →ₘ β) = mk (λa:α, 0) measurable_const := rfl
lemma zero_to_fun [has_zero β] : ∀ₘ a, (0 : α →ₘ β).to_fun a = 0 := const_to_fun _ _
instance [has_one β] : has_one (α →ₘ β) := ⟨const α 1⟩
lemma one_def [has_one β] : (1 : α →ₘ β) = mk (λa:α, 1) measurable_const := rfl
lemma one_to_fun [has_one β] : ∀ₘ a, (1 : α →ₘ β).to_fun a = 1 := const_to_fun _ _
section add_monoid
variables {γ : Type*}
[topological_space γ] [second_countable_topology γ] [add_monoid γ] [topological_add_monoid γ]
protected def add : (α →ₘ γ) → (α →ₘ γ) → (α →ₘ γ) :=
comp₂ (+) (measurable.add (measurable.fst measurable_id) (measurable.snd measurable_id))
instance : has_add (α →ₘ γ) := ⟨ae_eq_fun.add⟩
@[simp] lemma mk_add_mk (f g : α → γ) (hf hg) :
(mk f hf) + (mk g hg) = mk (f + g) (measurable.add hf hg) := rfl
lemma add_to_fun (f g : α →ₘ γ) : ∀ₘ a, (f + g).to_fun a = f.to_fun a + g.to_fun a :=
comp₂_to_fun _ _ _ _
instance : add_monoid (α →ₘ γ) :=
{ zero := 0,
add := ae_eq_fun.add,
add_zero := by rintros ⟨a⟩; exact quotient.sound (univ_mem_sets' $ assume a, add_zero _),
zero_add := by rintros ⟨a⟩; exact quotient.sound (univ_mem_sets' $ assume a, zero_add _),
add_assoc :=
by rintros ⟨a⟩ ⟨b⟩ ⟨c⟩; exact quotient.sound (univ_mem_sets' $ assume a, add_assoc _ _ _) }
end add_monoid
section add_comm_monoid
variables {γ : Type*}
[topological_space γ] [second_countable_topology γ] [add_comm_monoid γ] [topological_add_monoid γ]
instance add_comm_monoid : add_comm_monoid (α →ₘ γ) :=
{ add_comm := by rintros ⟨a⟩ ⟨b⟩; exact quotient.sound (univ_mem_sets' $ assume a, add_comm _ _),
.. ae_eq_fun.add_monoid }
end add_comm_monoid
section add_group
variables {γ : Type*} [topological_space γ] [add_group γ] [topological_add_group γ]
protected def neg : (α →ₘ γ) → (α →ₘ γ) := comp has_neg.neg (measurable.neg measurable_id)
instance : has_neg (α →ₘ γ) := ⟨ae_eq_fun.neg⟩
@[simp] lemma neg_mk (f : α → γ) (hf) : -(mk f hf) = mk (-f) (measurable.neg hf) := rfl
lemma neg_to_fun (f : α →ₘ γ) : ∀ₘ a, (-f).to_fun a = - f.to_fun a := comp_to_fun _ _ _
variables [second_countable_topology γ]
instance : add_group (α →ₘ γ) :=
{ neg := ae_eq_fun.neg,
add_left_neg := by rintros ⟨a⟩; exact quotient.sound (univ_mem_sets' $ assume a, add_left_neg _),
.. ae_eq_fun.add_monoid
}
@[simp] lemma mk_sub_mk (f g : α → γ) (hf hg) :
(mk f hf) - (mk g hg) = mk (λa, (f a) - (g a)) (measurable.sub hf hg) := rfl
lemma sub_to_fun (f g : α →ₘ γ) : ∀ₘ a, (f - g).to_fun a = f.to_fun a - g.to_fun a :=
begin
rw sub_eq_add_neg,
filter_upwards [add_to_fun f (-g), neg_to_fun g],
assume a,
simp only [mem_set_of_eq],
repeat {assume h, rw h},
refl
end
end add_group
section add_comm_group
variables {γ : Type*}
[topological_space γ] [second_countable_topology γ] [add_comm_group γ] [topological_add_group γ]
instance : add_comm_group (α →ₘ γ) :=
{ add_comm := ae_eq_fun.add_comm_monoid.add_comm
.. ae_eq_fun.add_group
}
end add_comm_group
section semimodule
variables {𝕜 : Type*} [semiring 𝕜] [topological_space 𝕜]
variables {γ : Type*} [topological_space γ]
[add_comm_monoid γ] [semimodule 𝕜 γ] [topological_semimodule 𝕜 γ]
protected def smul : 𝕜 → (α →ₘ γ) → (α →ₘ γ) :=
λ c f, comp (has_scalar.smul c) (measurable_smul _ measurable_id) f
instance : has_scalar 𝕜 (α →ₘ γ) := ⟨ae_eq_fun.smul⟩
@[simp] lemma smul_mk (c : 𝕜) (f : α → γ) (hf) : c • (mk f hf) = mk (c • f) (measurable_smul _ hf) :=
rfl
lemma smul_to_fun (c : 𝕜) (f : α →ₘ γ) : ∀ₘ a, (c • f).to_fun a = c • f.to_fun a :=
comp_to_fun _ _ _
variables [second_countable_topology γ] [topological_add_monoid γ]
instance : semimodule 𝕜 (α →ₘ γ) :=
{ one_smul := by { rintros ⟨f, hf⟩, simp only [quot_mk_eq_mk, smul_mk, one_smul] },
mul_smul :=
by { rintros x y ⟨f, hf⟩, simp only [quot_mk_eq_mk, smul_mk, mul_action.mul_smul x y f], refl },
smul_add :=
begin
rintros x ⟨f, hf⟩ ⟨g, hg⟩, simp only [quot_mk_eq_mk, smul_mk, mk_add_mk],
congr, exact smul_add x f g
end,
smul_zero := by { intro x, simp only [zero_def, smul_mk], congr, exact smul_zero x },
add_smul :=
begin
intros x y, rintro ⟨f, hf⟩, simp only [quot_mk_eq_mk, smul_mk, mk_add_mk], congr,
exact add_smul x y f
end,
zero_smul :=
by { rintro ⟨f, hf⟩, simp only [quot_mk_eq_mk, smul_mk, zero_def], congr, exact zero_smul 𝕜 f }}
instance : mul_action 𝕜 (α →ₘ γ) := by apply_instance
end semimodule
section module
variables {𝕜 : Type*} [ring 𝕜] [topological_space 𝕜]
variables {γ : Type*} [topological_space γ] [second_countable_topology γ] [add_comm_group γ]
[topological_add_group γ] [module 𝕜 γ] [topological_semimodule 𝕜 γ]
instance : module 𝕜 (α →ₘ γ) := { .. ae_eq_fun.semimodule }
end module
section vector_space
variables {𝕜 : Type*} [discrete_field 𝕜] [topological_space 𝕜]
variables {γ : Type*} [topological_space γ] [second_countable_topology γ] [add_comm_group γ]
[topological_add_group γ] [vector_space 𝕜 γ] [topological_semimodule 𝕜 γ]
instance : vector_space 𝕜 (α →ₘ γ) := { .. ae_eq_fun.semimodule }
end vector_space
/- TODO : Prove that `L⁰` is a complete space if the codomain is complete. -/
/- TODO : Multiplicative structure of `L⁰` if useful -/
open ennreal
/-- For `f : α → ennreal`, Define `∫ [f]` to be `∫ f` -/
def eintegral (f : α →ₘ ennreal) : ennreal :=
quotient.lift_on f (λf, lintegral f.1) (assume ⟨f, hf⟩ ⟨g, hg⟩ eq, lintegral_congr_ae eq)
@[simp] lemma eintegral_mk (f : α → ennreal) (hf) : eintegral (mk f hf) = lintegral f := rfl
lemma eintegral_to_fun (f : α →ₘ ennreal) : eintegral f = lintegral (f.to_fun) :=
by conv_lhs { rw [self_eq_mk f, eintegral_mk] }
@[simp] lemma eintegral_zero : eintegral (0 : α →ₘ ennreal) = 0 := lintegral_zero
@[simp] lemma eintegral_eq_zero_iff (f : α →ₘ ennreal) : eintegral f = 0 ↔ f = 0 :=
begin
rcases f with ⟨f, hf⟩,
refine iff.trans (lintegral_eq_zero_iff hf) ⟨_, _⟩,
{ assume h, exact quotient.sound h },
{ assume h, exact quotient.exact h }
end
lemma eintegral_add : ∀(f g : α →ₘ ennreal), eintegral (f + g) = eintegral f + eintegral g :=
by { rintros ⟨f⟩ ⟨g⟩, simp only [quot_mk_eq_mk, mk_add_mk, eintegral_mk], exact lintegral_add f.2 g.2 }
lemma eintegral_le_eintegral {f g : α →ₘ ennreal} (h : f ≤ g) : eintegral f ≤ eintegral g :=
begin
rcases f with ⟨f, hf⟩, rcases g with ⟨g, hg⟩,
simp only [quot_mk_eq_mk, eintegral_mk, mk_le_mk] at *,
refine lintegral_le_lintegral_ae _,
filter_upwards [h], simp
end
section
variables {γ : Type*} [emetric_space γ] [second_countable_topology γ]
/-- `comp_edist [f] [g] a` will return `edist (f a) (g a) -/
def comp_edist (f g : α →ₘ γ) : α →ₘ ennreal := comp₂ edist measurable_edist' f g
lemma comp_edist_to_fun (f g : α →ₘ γ) :
∀ₘ a, (comp_edist f g).to_fun a = edist (f.to_fun a) (g.to_fun a) :=
comp₂_to_fun _ _ _ _
lemma comp_edist_self : ∀ (f : α →ₘ γ), comp_edist f f = 0 :=
by rintro ⟨f⟩; refine quotient.sound _; simp only [edist_self]
/-- Almost everywhere equal functions form an `emetric_space`, with the emetric defined as
`edist f g = ∫⁻ a, edist (f a) (g a)`. -/
instance : emetric_space (α →ₘ γ) :=
{ edist := λf g, eintegral (comp_edist f g),
edist_self := assume f, (eintegral_eq_zero_iff _).2 (comp_edist_self _),
edist_comm :=
by rintros ⟨f⟩ ⟨g⟩; simp only [comp_edist, quot_mk_eq_mk, comp₂_mk_mk, edist_comm],
edist_triangle :=
begin
rintros ⟨f⟩ ⟨g⟩ ⟨h⟩,
simp only [comp_edist, quot_mk_eq_mk, comp₂_mk_mk, (eintegral_add _ _).symm],
exact lintegral_le_lintegral _ _ (assume a, edist_triangle _ _ _)
end,
eq_of_edist_eq_zero :=
begin
rintros ⟨f⟩ ⟨g⟩,
simp only [edist, comp_edist, quot_mk_eq_mk, comp₂_mk_mk, eintegral_eq_zero_iff],
simp only [zero_def, mk_eq_mk, edist_eq_zero],
assume h, assumption
end }
lemma edist_mk_mk {f g : α → γ} (hf hg) : edist (mk f hf) (mk g hg) = ∫⁻ x, edist (f x) (g x) := rfl
lemma edist_to_fun (f g : α →ₘ γ) : edist f g = ∫⁻ x, edist (f.to_fun x) (g.to_fun x) :=
by conv_lhs { rw [self_eq_mk f, self_eq_mk g, edist_mk_mk] }
lemma edist_zero_to_fun [has_zero γ] (f : α →ₘ γ) : edist f 0 = ∫⁻ x, edist (f.to_fun x) 0 :=
begin
rw edist_to_fun,
apply lintegral_congr_ae,
have : ∀ₘ a:α, (0 : α →ₘ γ).to_fun a = 0 := zero_to_fun,
filter_upwards [this],
assume a h,
simp only [mem_set_of_eq] at *,
rw h
end
end
section metric
variables {γ : Type*} [metric_space γ] [second_countable_topology γ]
lemma edist_mk_mk' {f g : α → γ} (hf hg) :
edist (mk f hf) (mk g hg) = ∫⁻ x, nndist (f x) (g x) :=
show (∫⁻ x, edist (f x) (g x)) = ∫⁻ x, nndist (f x) (g x), from
lintegral_congr_ae $all_ae_of_all $ assume a, edist_nndist _ _
lemma edist_to_fun' (f g : α →ₘ γ) : edist f g = ∫⁻ x, nndist (f.to_fun x) (g.to_fun x) :=
by conv_lhs { rw [self_eq_mk f, self_eq_mk g, edist_mk_mk'] }
end metric
section normed_group
variables {γ : Type*} [normed_group γ] [second_countable_topology γ]
lemma edist_eq_add_add : ∀ {f g h : α →ₘ γ}, edist f g = edist (f + h) (g + h) :=
begin
rintros ⟨f⟩ ⟨g⟩ ⟨h⟩,
simp only [quot_mk_eq_mk, mk_add_mk, edist_mk_mk'],
apply lintegral_congr_ae,
filter_upwards [], simp [nndist_eq_nnnorm]
end
end normed_group
section normed_space
set_option class.instance_max_depth 100
variables {𝕜 : Type*} [normed_field 𝕜]
variables {γ : Type*} [normed_group γ] [second_countable_topology γ] [normed_space 𝕜 γ]
lemma edist_smul (x : 𝕜) : ∀ f : α →ₘ γ, edist (x • f) 0 = (ennreal.of_real ∥x∥) * edist f 0 :=
begin
rintros ⟨f, hf⟩, simp only [zero_def, edist_mk_mk', quot_mk_eq_mk, smul_mk],
exact calc
(∫⁻ (a : α), nndist (x • f a) 0) = (∫⁻ (a : α), (nnnorm x) * nnnorm (f a)) :
lintegral_congr_ae $ by { filter_upwards [], assume a, simp [nndist_eq_nnnorm, nnnorm_smul] }
... = _ : lintegral_const_mul _ (measurable_coe_nnnorm hf)
... = _ :
begin
convert rfl,
{ rw ← coe_nnnorm, rw [ennreal.of_real], congr, exact nnreal.of_real_coe },
{ funext, simp [nndist_eq_nnnorm] }
end,
end
end normed_space
section pos_part
variables {γ : Type*} [topological_space γ] [decidable_linear_order γ] [ordered_topology γ]
[second_countable_topology γ] [has_zero γ]
/-- Positive part of an `ae_eq_fun`. -/
def pos_part (f : α →ₘ γ) : α →ₘ γ :=
comp₂ max (measurable.max (measurable.fst measurable_id) (measurable.snd measurable_id)) f 0
lemma pos_part_to_fun (f : α →ₘ γ) : ∀ₘ a, (pos_part f).to_fun a = max (f.to_fun a) (0:γ) :=
begin
filter_upwards [comp₂_to_fun max (measurable.max (measurable.fst measurable_id)
(measurable.snd measurable_id)) f 0, @ae_eq_fun.zero_to_fun α γ],
simp only [mem_set_of_eq],
assume a h₁ h₂,
rw [pos_part, h₁, h₂]
end
end pos_part
end ae_eq_fun
end measure_theory
|
80a9fb930bcf19d70d665c55d490bee6a5fce4ea | 1fd908b06e3f9c1252cb2285ada1102623a67f72 | /cubical/squareover.lean | 7c7218ae128e0cc2296e17410780adb92d9183e5 | [
"Apache-2.0"
] | permissive | avigad/hott3 | 609a002849182721e7c7ae536d9f1e2956d6d4d3 | f64750cd2de7a81e87d4828246d1369d59f16f43 | refs/heads/master | 1,629,027,243,322 | 1,510,946,717,000 | 1,510,946,717,000 | 103,570,461 | 0 | 0 | null | 1,505,415,620,000 | 1,505,415,620,000 | null | UTF-8 | Lean | false | false | 16,731 | lean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Squareovers
-/
import .square
universe u
hott_theory
namespace hott
open eq hott.equiv hott.is_equiv hott.sigma
namespace eq
-- we give the argument B explicitly, because Lean would find (λa, B a) by itself, which
-- makes the type uglier (of course the two terms are definitionally equal)
inductive squareover {A : Type _} (B : A → Type _) {a₀₀ : A} {b₀₀ : B a₀₀} :
Π{a₂₀ a₀₂ a₂₂ : A}
{p₁₀ : a₀₀ = a₂₀} {p₁₂ : a₀₂ = a₂₂} {p₀₁ : a₀₀ = a₀₂} {p₂₁ : a₂₀ = a₂₂}
(s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
{b₂₀ : B a₂₀} {b₀₂ : B a₀₂} {b₂₂ : B a₂₂}
(q₁₀ : b₀₀ =[p₁₀; B] b₂₀) (q₁₂ : b₀₂ =[p₁₂; B] b₂₂)
(q₀₁ : b₀₀ =[p₀₁; B] b₀₂) (q₂₁ : b₂₀ =[p₂₁; B] b₂₂),
Type _
| idsquareo : squareover ids idpo idpo idpo idpo
variables {A : Type _} {A' : Type _} {B : A → Type _}
{a a' a'' a₀₀ a₂₀ a₄₀ a₀₂ a₂₂ a₂₄ a₀₄ a₄₂ a₄₄ : A}
/-a₀₀-/ {p₁₀ : a₀₀ = a₂₀} /-a₂₀-/ {p₃₀ : a₂₀ = a₄₀} /-a₄₀-/
{p₀₁ : a₀₀ = a₀₂} /-s₁₁-/ {p₂₁ : a₂₀ = a₂₂} /-s₃₁-/ {p₄₁ : a₄₀ = a₄₂}
/-a₀₂-/ {p₁₂ : a₀₂ = a₂₂} /-a₂₂-/ {p₃₂ : a₂₂ = a₄₂} /-a₄₂-/
{p₀₃ : a₀₂ = a₀₄} /-s₁₃-/ {p₂₃ : a₂₂ = a₂₄} /-s₃₃-/ {p₄₃ : a₄₂ = a₄₄}
/-a₀₄-/ {p₁₄ : a₀₄ = a₂₄} /-a₂₄-/ {p₃₄ : a₂₄ = a₄₄} /-a₄₄-/
{s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁}
{s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃} {s₃₃ : square p₃₂ p₃₄ p₂₃ p₄₃}
{b₀₀ : B a₀₀} {b₂₀ : B a₂₀} {b₄₀ : B a₄₀}
{b₀₂ : B a₀₂} {b₂₂ : B a₂₂} {b₄₂ : B a₄₂}
{b₀₄ : B a₀₄} {b₂₄ : B a₂₄} {b₄₄ : B a₄₄}
/-b₀₀-/ {q₁₀ : b₀₀ =[p₁₀] b₂₀} /-b₂₀-/ {q₃₀ : b₂₀ =[p₃₀] b₄₀} /-b₄₀-/
{q₀₁ : b₀₀ =[p₀₁] b₀₂} /-t₁₁-/ {q₂₁ : b₂₀ =[p₂₁] b₂₂} /-t₃₁-/ {q₄₁ : b₄₀ =[p₄₁] b₄₂}
/-b₀₂-/ {q₁₂ : b₀₂ =[p₁₂] b₂₂} /-b₂₂-/ {q₃₂ : b₂₂ =[p₃₂] b₄₂} /-b₄₂-/
{q₀₃ : b₀₂ =[p₀₃] b₀₄} /-t₁₃-/ {q₂₃ : b₂₂ =[p₂₃] b₂₄} /-t₃₃-/ {q₄₃ : b₄₂ =[p₄₃] b₄₄}
/-b₀₄-/ {q₁₄ : b₀₄ =[p₁₄] b₂₄} /-b₂₄-/ {q₃₄ : b₂₄ =[p₃₄] b₄₄} /-b₄₄-/
@[hott] def squareo := @squareover A B a₀₀
@[hott, reducible] def idsquareo (b₀₀ : B a₀₀) := @squareover.idsquareo A B a₀₀ b₀₀
@[hott, reducible] def idso := @squareover.idsquareo A B a₀₀ b₀₀
@[hott] def apds (f : Πa, B a) (s : square p₁₀ p₁₂ p₀₁ p₂₁)
: squareover B s (apd f p₁₀) (apd f p₁₂) (apd f p₀₁) (apd f p₂₁) :=
by induction s; constructor
@[hott] def vrflo : squareover B vrfl q₁₀ q₁₀ idpo idpo :=
by induction q₁₀; exact idso
@[hott] def hrflo : squareover B hrfl idpo idpo q₁₀ q₁₀ :=
by induction q₁₀; exact idso
@[hott] def vdeg_squareover {p₁₀'} {s : p₁₀ = p₁₀'} {q₁₀' : b₀₀ =[p₁₀'] b₂₀}
(r : change_path s q₁₀ = q₁₀')
: squareover B (vdeg_square s) q₁₀ q₁₀' idpo idpo :=
by induction s; induction r; exact vrflo
@[hott] def hdeg_squareover {p₀₁'} {s : p₀₁ = p₀₁'} {q₀₁' : b₀₀ =[p₀₁'] b₀₂}
(r : change_path s q₀₁ = q₀₁')
: squareover B (hdeg_square s) idpo idpo q₀₁ q₀₁' :=
by induction s; induction r; exact hrflo
@[hott] def hconcato
(t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (t₃₁ : squareover B s₃₁ q₃₀ q₃₂ q₂₁ q₄₁)
: squareover B (hconcat s₁₁ s₃₁) (q₁₀ ⬝o q₃₀) (q₁₂ ⬝o q₃₂) q₀₁ q₄₁ :=
by induction t₃₁; exact t₁₁
@[hott] def vconcato
(t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (t₁₃ : squareover B s₁₃ q₁₂ q₁₄ q₀₃ q₂₃)
: squareover B (vconcat s₁₁ s₁₃) q₁₀ q₁₄ (q₀₁ ⬝o q₀₃) (q₂₁ ⬝o q₂₃) :=
by induction t₁₃; exact t₁₁
@[hott] def hinverseo (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁)
: squareover B (hinverse s₁₁) q₁₀⁻¹ᵒ q₁₂⁻¹ᵒ q₂₁ q₀₁ :=
by induction t₁₁; constructor
@[hott] def vinverseo (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁)
: squareover B (vinverse s₁₁) q₁₂ q₁₀ q₀₁⁻¹ᵒ q₂₁⁻¹ᵒ :=
by induction t₁₁; constructor
@[hott] def eq_vconcato {q : b₀₀ =[p₁₀] b₂₀}
(r : q = q₁₀) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q q₁₂ q₀₁ q₂₁ :=
by induction r; exact t₁₁
@[hott] def vconcato_eq {q : b₀₂ =[p₁₂] b₂₂}
(t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : q₁₂ = q) : squareover B s₁₁ q₁₀ q q₀₁ q₂₁ :=
by induction r; exact t₁₁
@[hott] def eq_hconcato {q : b₀₀ =[p₀₁] b₀₂}
(r : q = q₀₁) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ q q₂₁ :=
by induction r; exact t₁₁
@[hott] def hconcato_eq {q : b₂₀ =[p₂₁] b₂₂}
(t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : q₂₁ = q) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q :=
by induction r; exact t₁₁
@[hott] def pathover_vconcato {p : a₀₀ = a₂₀} {sp : p = p₁₀} {q : b₀₀ =[p] b₂₀}
(r : change_path sp q = q₁₀) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁)
: squareover B (sp ⬝pv s₁₁) q q₁₂ q₀₁ q₂₁ :=
by induction sp; induction r; exact t₁₁
@[hott] def vconcato_pathover {p : a₀₂ = a₂₂} {sp : p₁₂ = p} {q : b₀₂ =[p] b₂₂}
(t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : change_path sp q₁₂ = q)
: squareover B (s₁₁ ⬝vp sp) q₁₀ q q₀₁ q₂₁ :=
by induction sp; induction r; exact t₁₁
@[hott] def pathover_hconcato {p : a₀₀ = a₀₂} {sp : p = p₀₁} {q : b₀₀ =[p] b₀₂}
(r : change_path sp q = q₀₁) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) :
squareover B (sp ⬝ph s₁₁) q₁₀ q₁₂ q q₂₁ :=
by induction sp; induction r; exact t₁₁
@[hott] def hconcato_pathover {p : a₂₀ = a₂₂} {sp : p₂₁ = p} {q : b₂₀ =[p] b₂₂}
(t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : change_path sp q₂₁ = q) :
squareover B (s₁₁ ⬝hp sp) q₁₀ q₁₂ q₀₁ q :=
by induction sp; induction r; exact t₁₁
infix ` ⬝ho `:69 := hconcato --type using \tr
infix ` ⬝vo `:70 := vconcato --type using \tr
infix ` ⬝hop `:72 := hconcato_eq --type using \tr
infix ` ⬝vop `:74 := vconcato_eq --type using \tr
infix ` ⬝pho `:71 := eq_hconcato --type using \tr
infix ` ⬝pvo `:73 := eq_vconcato --type using \tr
@[hott] def square_of_squareover (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) :
square (con_tr p₁₀ p₂₁ b₀₀ ⬝ ap (λa : B a₂₀, p₂₁ ▸ a) (tr_eq_of_pathover q₁₀))
(tr_eq_of_pathover q₁₂)
(transport2 _ (eq_of_square s₁₁) b₀₀ ⬝ con_tr _ _ _ ⬝ ap (λa : B a₀₂, p₁₂ ▸ a) (tr_eq_of_pathover q₀₁))
(tr_eq_of_pathover q₂₁) :=
by induction t₁₁; constructor
@[hott] lemma square_of_squareover_ids {b₀₀ b₀₂ b₂₀ b₂₂ : B a}
{t : b₀₀ = b₂₀} {b : b₀₂ = b₂₂} {l : b₀₀ = b₀₂} {r : b₂₀ = b₂₂}
(so : squareover B ids (pathover_idp_of_eq B t)
(pathover_idp_of_eq B b)
(pathover_idp_of_eq B l)
(pathover_idp_of_eq B r)) : square t b l r :=
begin
let H := square_of_squareover so, hsimp at H,
exact whisker_square (to_right_inv (pathover_equiv_tr_eq (refl a) _ _) _)
(to_right_inv (pathover_equiv_tr_eq (refl a) _ _) _)
(to_right_inv (pathover_equiv_tr_eq (refl a) _ _) _)
(to_right_inv (pathover_equiv_tr_eq (refl a) _ _) _) H
end
@[hott] def squareover_ids_of_square {b₀₀ b₀₂ b₂₀ b₂₂ : B a}
{t : b₀₀ = b₂₀} {b : b₀₂ = b₂₂} {l : b₀₀ = b₀₂} {r : b₂₀ = b₂₂} (q : square t b l r)
: squareover B ids (pathover_idp_of_eq B t)
(pathover_idp_of_eq B b)
(pathover_idp_of_eq B l)
(pathover_idp_of_eq B r) :=
by induction q; constructor
-- relating pathovers to squareovers
@[hott] def pathover_of_squareover' (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁)
: pathover (λp, b₀₀ =[p] b₂₂) (q₁₀ ⬝o q₂₁) (eq_of_square s₁₁) (q₀₁ ⬝o q₁₂) :=
by induction t₁₁; constructor
@[hott] def pathover_of_squareover {s : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂}
(t₁₁ : squareover B (square_of_eq s) q₁₀ q₁₂ q₀₁ q₂₁)
: q₁₀ ⬝o q₂₁ =[s; λp, b₀₀ =[p] b₂₂] q₀₁ ⬝o q₁₂ :=
begin
revert s t₁₁,
refine equiv_rect' (square_equiv_eq p₁₀ p₁₂ p₀₁ p₂₁)⁻¹ᵉ
(λa b, squareover B b q₁₀ q₁₂ q₀₁ q₂₁ → pathover (λp, b₀₀ =[p] b₂₂) (q₁₀ ⬝o q₂₁) a (q₀₁ ⬝o q₁₂)) _,
intro s, exact pathover_of_squareover'
end
@[hott] def squareover_of_pathover {s : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂}
(r : q₁₀ ⬝o q₂₁ =[s; λp, b₀₀ =[p] b₂₂] q₀₁ ⬝o q₁₂) :
squareover B (square_of_eq s) q₁₀ q₁₂ q₀₁ q₂₁ :=
by induction q₁₂; hsimp at r; induction r; induction q₁₀; induction q₂₁; constructor
@[hott] def pathover_top_of_squareover (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁)
: q₁₀ =[eq_top_of_square s₁₁; λp, b₀₀ =[p] b₂₀] q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ :=
by induction t₁₁; constructor
@[hott] def squareover_of_pathover_top {s : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹}
(r : q₁₀ =[s; λp, b₀₀ =[p] b₂₀] q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ)
: squareover B (square_of_eq_top s) q₁₀ q₁₂ q₀₁ q₂₁ :=
by induction q₂₁; induction q₁₂; dsimp at r; induction r; induction q₁₀; constructor
@[hott] def pathover_of_hdeg_squareover {p₀₁' : a₀₀ = a₀₂} {r : p₀₁ = p₀₁'} {q₀₁' : b₀₀ =[p₀₁'] b₀₂}
(t : squareover B (hdeg_square r) idpo idpo q₀₁ q₀₁') : q₀₁ =[r; λp, b₀₀ =[p] b₀₂] q₀₁' :=
by induction r; induction q₀₁'; exact (pathover_of_squareover' t)⁻¹ᵒ
@[hott] def pathover_of_vdeg_squareover {p₁₀' : a₀₀ = a₂₀} {r : p₁₀ = p₁₀'} {q₁₀' : b₀₀ =[p₁₀'] b₂₀}
(t : squareover B (vdeg_square r) q₁₀ q₁₀' idpo idpo) : q₁₀ =[r; λp, b₀₀ =[p] b₂₀] q₁₀' :=
by induction r; induction q₁₀'; exact pathover_of_squareover' t
@[hott] def squareover_of_eq_top (r : change_path (eq_top_of_square s₁₁) q₁₀ = q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ)
: squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁ :=
begin
induction s₁₁, revert q₁₂ q₁₀ r,
refine idp_rec_on q₂₁ _, clear q₂₁,
intro q₁₂,
refine idp_rec_on q₁₂ _, clear q₁₂,
dsimp, intros,
induction r, eapply idp_rec_on q₁₀,
constructor
end
@[hott] def eq_top_of_squareover (r : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁)
: change_path (eq_top_of_square s₁₁) q₁₀ = q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ :=
by induction r; reflexivity
@[hott] def change_square {s₁₁'} (p : s₁₁ = s₁₁') (r : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁)
: squareover B s₁₁' q₁₀ q₁₂ q₀₁ q₂₁ :=
by induction p; exact r -- in Lean 2 defined using transport
@[hott] lemma eq_of_vdeg_squareover {q₁₀' : b₀₀ =[p₁₀] b₂₀}
(p : squareover B vrfl q₁₀ q₁₀' idpo idpo) : q₁₀ = q₁₀' :=
begin
let H := square_of_squareover p,
induction p₁₀,
hsimp at H,
let H' := eq_of_vdeg_square H,
exact eq_of_fn_eq_fn (pathover_equiv_tr_eq _ _ _) H'
end
/- A version of eq_pathover where the type of the equality also varies -/
@[hott] lemma eq_pathover_dep {f g : Πa, B a} {p : a = a'} {q : f a = g a}
{r : f a' = g a'} (s : squareover B hrfl (pathover_idp_of_eq B q) (pathover_idp_of_eq B r)
(apd f p) (apd g p)) : q =[p; λx, f x = g x] r :=
begin
induction p, apply pathover_idp_of_eq, apply eq_of_vdeg_square, exact square_of_squareover_ids s
end
/- charcaterization of pathovers in pathovers -/
-- in this version the fibration (B) of the pathover does not depend on the variable (a)
@[hott] lemma pathover_pathover {a' a₂' : A'} {p : a' = a₂'} {f g : A' → A}
{b : Πa, B (f a)} {b₂ : Πa, B (g a)} {q : Π(a' : A'), f a' = g a'}
(r : pathover B (b a') (q a') (b₂ a'))
(r₂ : pathover B (b a₂') (q a₂') (b₂ a₂'))
(s : squareover B (natural_square q p) r r₂
(pathover_ap B f (apd b p)) (pathover_ap B g (apd b₂ p)))
: pathover (λa, pathover B (b a) (q a) (b₂ a)) r p r₂ :=
begin
induction p, apply pathover_idp_of_eq, apply eq_of_vdeg_squareover, exact s
end
@[hott] def squareover_change_path_left {p₀₁' : a₀₀ = a₀₂} (r : p₀₁' = p₀₁)
{q₀₁ : b₀₀ =[p₀₁'] b₀₂} (t : squareover B (r ⬝ph s₁₁) q₁₀ q₁₂ q₀₁ q₂₁)
: squareover B s₁₁ q₁₀ q₁₂ (change_path r q₀₁) q₂₁ :=
by induction r; exact t
@[hott] def squareover_change_path_right {p₂₁' : a₂₀ = a₂₂} (r : p₂₁' = p₂₁)
{q₂₁ : b₂₀ =[p₂₁'] b₂₂} (t : squareover B (s₁₁ ⬝hp r⁻¹) q₁₀ q₁₂ q₀₁ q₂₁)
: squareover B s₁₁ q₁₀ q₁₂ q₀₁ (change_path r q₂₁) :=
by induction r; exact t
@[hott] def squareover_change_path_right' {p₂₁' : a₂₀ = a₂₂} (r : p₂₁ = p₂₁')
{q₂₁ : b₂₀ =[p₂₁'] b₂₂} (t : squareover B (s₁₁ ⬝hp r) q₁₀ q₁₂ q₀₁ q₂₁)
: squareover B s₁₁ q₁₀ q₁₂ q₀₁ (change_path r⁻¹ q₂₁) :=
by induction r; exact t
/- You can construct a square in a sigma-type by giving a squareover -/
@[hott] def square_dpair_eq_dpair {a₀₀ a₂₀ a₀₂ a₂₂ : A}
{p₁₀ : a₀₀ = a₂₀} {p₀₁ : a₀₀ = a₀₂} {p₂₁ : a₂₀ = a₂₂} {p₁₂ : a₀₂ = a₂₂}
(s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) {b₀₀ : B a₀₀} {b₂₀ : B a₂₀} {b₀₂ : B a₀₂} {b₂₂ : B a₂₂}
{q₁₀ : b₀₀ =[p₁₀] b₂₀} {q₀₁ : b₀₀ =[p₀₁] b₀₂} {q₂₁ : b₂₀ =[p₂₁] b₂₂} {q₁₂ : b₀₂ =[p₁₂] b₂₂}
(t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) :
square (sigma.dpair_eq_dpair p₁₀ q₁₀) (dpair_eq_dpair p₁₂ q₁₂)
(dpair_eq_dpair p₀₁ q₀₁) (dpair_eq_dpair p₂₁ q₂₁) :=
by induction t₁₁; constructor
@[hott] lemma sigma_square {v₀₀ v₂₀ v₀₂ v₂₂ : Σa, B a}
{p₁₀ : v₀₀ = v₂₀} {p₀₁ : v₀₀ = v₀₂} {p₂₁ : v₂₀ = v₂₂} {p₁₂ : v₀₂ = v₂₂}
(s₁₁ : square p₁₀..1 p₁₂..1 p₀₁..1 p₂₁..1)
(t₁₁ : squareover B s₁₁ p₁₀..2 p₁₂..2 p₀₁..2 p₂₁..2) : square p₁₀ p₁₂ p₀₁ p₂₁ :=
begin
induction v₀₀, induction v₂₀, induction v₀₂, induction v₂₂,
rwr [(sigma_eq_eta p₁₀)⁻¹, (sigma_eq_eta p₀₁)⁻¹, (sigma_eq_eta p₁₂)⁻¹, (sigma_eq_eta p₂₁)⁻¹],
exact square_dpair_eq_dpair s₁₁ t₁₁
end
end eq
end hott
|
0c7f05bc697e02ff1892c8d27baf35f8b87534cd | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/topology/homotopy.lean | 2588411ed87b4448b107f958008eb8a5a03c15dc | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,947 | lean | /-
Copyright (c) 2021 Shing Tak Lam. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Shing Tak Lam
-/
import topology.unit_interval
import topology.algebra.ordered.proj_Icc
import topology.continuous_function.basic
import topology.compact_open
/-!
# Homotopy between functions
In this file, we define a `homotopy` between two functions `f₀` and `f₁`.
## Definitions
* `homotopy f₀ f₁` is the type of homotopies between `f₀` and `f₁`
* `homotopy.refl f₀` is the constant homotopy between `f₀` and `f₀`
* `homotopy.symm f₀ f₁` is a `homotopy f₁ f₀` defined by reversing the homotopy
* `homotopy.trans F G`, where `F : homotopy f₀ f₁`, `G : homotopy f₁ f₂` is a `homotopy f₀ f₂`
defined by putting the first homotopy on `[0, 1/2]` and the second on `[1/2, 1]`.
-/
noncomputable theory
universes u v
variables {X : Type u} {Y : Type v} [topological_space X] [topological_space Y]
open_locale unit_interval
namespace continuous_map
/--
The type of homotopies between two functions.
-/
structure homotopy (f₀ f₁ : C(X, Y)) extends C(I × X, Y) :=
(to_fun_zero : ∀ x, to_fun (0, x) = f₀ x)
(to_fun_one : ∀ x, to_fun (1, x) = f₁ x)
namespace homotopy
section
variables {f₀ f₁ : C(X, Y)}
instance : has_coe_to_fun (homotopy f₀ f₁) := ⟨_, λ F, F.to_fun⟩
@[ext]
lemma ext {F G : homotopy f₀ f₁} (h : ∀ x, F x = G x) : F = G :=
begin
cases F, cases G,
congr' 1,
ext x,
exact h x,
end
@[continuity]
protected lemma continuous (F : homotopy f₀ f₁) : continuous F := F.continuous_to_fun
@[simp]
lemma apply_zero (F : homotopy f₀ f₁) (x : X) : F (0, x) = f₀ x := F.to_fun_zero x
@[simp]
lemma apply_one (F : homotopy f₀ f₁) (x : X) : F (1, x) = f₁ x := F.to_fun_one x
@[simp]
lemma to_continuous_map_apply (F : homotopy f₀ f₁) (k : I × X) : F.to_continuous_map k = F k := rfl
/--
Currying a homotopy to a continuous function fron `I` to `C(X, Y)`.
-/
def curry (F : homotopy f₀ f₁) : C(I, C(X, Y)) := F.to_continuous_map.curry
/--
Continuously extending a curried homotopy to a function from `ℝ` to `C(X, Y)`.
-/
def extend (F : homotopy f₀ f₁) : C(ℝ, C(X, Y)) := F.curry.Icc_extend zero_le_one
@[simp]
lemma extend_apply_zero (F : homotopy f₀ f₁) (x : X) : F.extend 0 x = f₀ x :=
by simp [extend, curry]
@[simp]
lemma extend_apply_one (F : homotopy f₀ f₁) (x : X) : F.extend 1 x = f₁ x := by simp [extend, curry]
end
/--
Given a continuous function `f`, we can define a `homotopy f f` by `F (x, t) = f x`
-/
def refl (f : C(X, Y)) : homotopy f f :=
{ to_fun := λ x, f x.2,
continuous_to_fun := by continuity,
to_fun_zero := λ _, rfl,
to_fun_one := λ _, rfl }
instance : inhabited (homotopy (continuous_map.id : C(X, X)) continuous_map.id) :=
⟨homotopy.refl continuous_map.id⟩
/--
Given a `homotopy f₀ f₁`, we can define a `homotopy f₁ f₀` by reversing the homotopy.
-/
def symm {f₀ f₁ : C(X, Y)} (F : homotopy f₀ f₁) : homotopy f₁ f₀ :=
{ to_fun := λ x, F (σ x.1, x.2),
continuous_to_fun := by continuity,
to_fun_zero := by norm_num,
to_fun_one := by norm_num }
@[simp]
lemma symm_apply {f₀ f₁ : C(X, Y)} (F : homotopy f₀ f₁) (x : X) (t : I) :
F.symm (t, x) = F (σ t, x) := rfl
@[simp]
lemma symm_symm {f₀ f₁ : C(X, Y)} (F : homotopy f₀ f₁) : F.symm.symm = F :=
begin
ext x,
cases x,
simp,
end
/--
Given `homotopy f₀ f₁` and `homotopy f₁ f₂`, we can define a `homotopy f₀ f₂` by putting the first
homotopy on `[0, 1/2]` and the second on `[1/2, 1]`.
-/
def trans {f₀ f₁ f₂ : C(X, Y)} (F : homotopy f₀ f₁) (G : homotopy f₁ f₂) : homotopy f₀ f₂ :=
{ to_fun := λ x, if (x.1 : ℝ) ≤ 1/2 then F.extend (2 * x.1) x.2 else G.extend (2 * x.1 - 1) x.2,
continuous_to_fun := begin
refine continuous_if_le _ _ (continuous.continuous_on _) (continuous.continuous_on _) _,
swap 5,
{ rintros x hx,
norm_num [hx] },
exact continuous_induced_dom.comp continuous_fst,
exact continuous_const,
-- TODO: Work out why `continuity` doesn't work here.
exact (homotopy.continuous F).comp
((continuous_proj_Icc.comp (continuous_const.mul
(continuous_induced_dom.comp continuous_fst))).prod_mk continuous_snd),
exact (homotopy.continuous G).comp
((continuous_proj_Icc.comp
((continuous_const.mul
(continuous_induced_dom.comp continuous_fst)).sub continuous_const)).prod_mk
continuous_snd),
end,
to_fun_zero := λ x, by norm_num,
to_fun_one := λ x, by norm_num }
lemma trans_apply {f₀ f₁ f₂ : C(X, Y)} (F : homotopy f₀ f₁) (G : homotopy f₁ f₂) (x : I × X) :
(F.trans G) x = if h : (x.1 : ℝ) ≤ 1/2 then
F (⟨2 * x.1, (unit_interval.mul_pos_mem_iff zero_lt_two).2 ⟨x.1.2.1, h⟩⟩, x.2)
else
G (⟨2 * x.1 - 1, unit_interval.two_mul_sub_one_mem_iff.2 ⟨(not_le.1 h).le, x.1.2.2⟩⟩, x.2) :=
begin
change ite _ _ _ = _,
split_ifs,
{ rw [extend, continuous_map.coe_Icc_extend, set.Icc_extend_of_mem],
refl },
{ rw [extend, continuous_map.coe_Icc_extend, set.Icc_extend_of_mem],
refl }
end
lemma symm_trans {f₀ f₁ f₂ : C(X, Y)} (F : homotopy f₀ f₁) (G : homotopy f₁ f₂) :
(F.trans G).symm = G.symm.trans F.symm :=
begin
ext,
cases x with t x,
simp only [symm_apply, trans_apply],
split_ifs with h₁ h₂,
{ change (t : ℝ) ≤ _ at h₂,
change (1 : ℝ) - t ≤ _ at h₁,
have ht : (t : ℝ) = 1/2,
{ linarith },
norm_num [ht] },
{ congr' 2,
apply subtype.ext,
simp only [unit_interval.coe_symm_eq, subtype.coe_mk],
linarith },
{ congr' 2,
apply subtype.ext,
simp only [unit_interval.coe_symm_eq, subtype.coe_mk],
linarith },
{ change ¬ (t : ℝ) ≤ _ at h,
change ¬ (1 : ℝ) - t ≤ _ at h₁,
exfalso, linarith }
end
end homotopy
end continuous_map
|
84157e21ae5cc4a63e296782d8e084a8643e6713 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/data/list/sigma.lean | 9193d63705804dd8396f22e6d6ea2c540f078aaa | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 23,997 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Sean Leather
Functions on lists of sigma types.
-/
import data.list.perm data.list.range data.sigma
universes u v
namespace list
variables {α : Type u} {β : α → Type v}
/- keys -/
/-- List of keys from a list of key-value pairs -/
def keys : list (sigma β) → list α :=
map sigma.fst
@[simp] theorem keys_nil : @keys α β [] = [] :=
rfl
@[simp] theorem keys_cons {s} {l : list (sigma β)} : (s :: l).keys = s.1 :: l.keys :=
rfl
theorem mem_keys_of_mem {s : sigma β} {l : list (sigma β)} : s ∈ l → s.1 ∈ l.keys :=
mem_map_of_mem sigma.fst
theorem exists_of_mem_keys {a} {l : list (sigma β)} (h : a ∈ l.keys) :
∃ (b : β a), sigma.mk a b ∈ l :=
let ⟨⟨a', b'⟩, m, e⟩ := exists_of_mem_map h in
eq.rec_on e (exists.intro b' m)
theorem mem_keys {a} {l : list (sigma β)} : a ∈ l.keys ↔ ∃ (b : β a), sigma.mk a b ∈ l :=
⟨exists_of_mem_keys, λ ⟨b, h⟩, mem_keys_of_mem h⟩
theorem not_mem_keys {a} {l : list (sigma β)} : a ∉ l.keys ↔ ∀ b : β a, sigma.mk a b ∉ l :=
(not_iff_not_of_iff mem_keys).trans not_exists
theorem not_eq_key {a} {l : list (sigma β)} : a ∉ l.keys ↔ ∀ s : sigma β, s ∈ l → a ≠ s.1 :=
iff.intro
(λ h₁ s h₂ e, absurd (mem_keys_of_mem h₂) (by rwa e at h₁))
(λ f h₁, let ⟨b, h₂⟩ := exists_of_mem_keys h₁ in f _ h₂ rfl)
/- nodupkeys -/
def nodupkeys (l : list (sigma β)) : Prop :=
l.keys.nodup
theorem nodupkeys_iff_pairwise {l} : nodupkeys l ↔
pairwise (λ s s' : sigma β, s.1 ≠ s'.1) l := pairwise_map _
@[simp] theorem nodupkeys_nil : @nodupkeys α β [] := pairwise.nil
@[simp] theorem nodupkeys_cons {s : sigma β} {l : list (sigma β)} :
nodupkeys (s::l) ↔ s.1 ∉ l.keys ∧ nodupkeys l :=
by simp [keys, nodupkeys]
theorem nodupkeys.eq_of_fst_eq {l : list (sigma β)}
(nd : nodupkeys l) {s s' : sigma β} (h : s ∈ l) (h' : s' ∈ l) :
s.1 = s'.1 → s = s' :=
@forall_of_forall_of_pairwise _
(λ s s' : sigma β, s.1 = s'.1 → s = s')
(λ s s' H h, (H h.symm).symm) _ (λ x h _, rfl)
((nodupkeys_iff_pairwise.1 nd).imp (λ s s' h h', (h h').elim)) _ h _ h'
theorem nodupkeys.eq_of_mk_mem {a : α} {b b' : β a} {l : list (sigma β)}
(nd : nodupkeys l) (h : sigma.mk a b ∈ l) (h' : sigma.mk a b' ∈ l) : b = b' :=
by cases nd.eq_of_fst_eq h h' rfl; refl
theorem nodupkeys_singleton (s : sigma β) : nodupkeys [s] := nodup_singleton _
theorem nodupkeys_of_sublist {l₁ l₂ : list (sigma β)} (h : l₁ <+ l₂) : nodupkeys l₂ → nodupkeys l₁ :=
nodup_of_sublist (map_sublist_map _ h)
theorem nodup_of_nodupkeys {l : list (sigma β)} : nodupkeys l → nodup l :=
nodup_of_nodup_map _
theorem perm_nodupkeys {l₁ l₂ : list (sigma β)} (h : l₁ ~ l₂) : nodupkeys l₁ ↔ nodupkeys l₂ :=
perm_nodup $ perm_map _ h
theorem nodupkeys_join {L : list (list (sigma β))} :
nodupkeys (join L) ↔ (∀ l ∈ L, nodupkeys l) ∧ pairwise disjoint (L.map keys) :=
begin
rw [nodupkeys_iff_pairwise, pairwise_join, pairwise_map],
refine and_congr (ball_congr $ λ l h, by simp [nodupkeys_iff_pairwise]) _,
apply iff_of_eq, congr', ext l₁ l₂,
simp [keys, disjoint_iff_ne]
end
theorem nodup_enum_map_fst (l : list α) : (l.enum.map prod.fst).nodup :=
by simp [list.nodup_range]
lemma mem_ext {l₀ l₁ : list (sigma β)}
(nd₀ : l₀.nodup) (nd₁ : l₁.nodup)
(h : ∀ x, x ∈ l₀ ↔ x ∈ l₁) : l₀ ~ l₁ :=
begin
induction l₀ with x xs generalizing l₁; cases l₁ with x ys,
{ constructor },
iterate 2
{ specialize h x, simp at h,
cases h },
simp at nd₀ nd₁, rename x y, classical,
cases nd₀, cases nd₁,
by_cases h' : x = y,
{ subst y, constructor, apply l₀_ih ‹ _ › ‹ nodup ys ›,
intro a, specialize h a, simp at h,
by_cases h' : a = x,
{ subst a, rw ← not_iff_not, split; intro; assumption },
{ simp [h'] at h, exact h } },
{ transitivity x :: y :: ys.erase x,
{ constructor, apply l₀_ih ‹ _ ›,
{ simp, split, { intro, apply nd₁_left, apply mem_of_mem_erase a },
apply nodup_erase_of_nodup; assumption },
{ intro a, specialize h a, simp at h,
by_cases h' : a = x,
{ subst a, rw ← not_iff_not, split; intro, simp [mem_erase_of_nodup,*], assumption },
{ simp [h'] at h, simp [h], apply or_congr, refl,
simp [mem_erase_of_ne,*] } } },
transitivity y :: x :: ys.erase x,
{ constructor },
{ constructor, symmetry, apply perm_erase,
specialize h x, simp [h'] at h, exact h } }
end
variables [decidable_eq α]
/- lookup -/
/-- `lookup a l` is the first value in `l` corresponding to the key `a`,
or `none` if no such element exists. -/
def lookup (a : α) : list (sigma β) → option (β a)
| [] := none
| (⟨a', b⟩ :: l) := if h : a' = a then some (eq.rec_on h b) else lookup l
@[simp] theorem lookup_nil (a : α) : lookup a [] = @none (β a) := rfl
@[simp] theorem lookup_cons_eq (l) (a : α) (b : β a) : lookup a (⟨a, b⟩::l) = some b :=
dif_pos rfl
@[simp] theorem lookup_cons_ne (l) {a} :
∀ s : sigma β, a ≠ s.1 → lookup a (s::l) = lookup a l
| ⟨a', b⟩ h := dif_neg h.symm
theorem lookup_is_some {a : α} : ∀ {l : list (sigma β)},
(lookup a l).is_some ↔ a ∈ l.keys
| [] := by simp
| (⟨a', b⟩ :: l) := begin
by_cases h : a = a',
{ subst a', simp },
{ simp [h, lookup_is_some] },
end
theorem lookup_eq_none {a : α} {l : list (sigma β)} :
lookup a l = none ↔ a ∉ l.keys :=
begin
have := not_congr (@lookup_is_some _ _ _ a l),
simp at this, refine iff.trans _ this,
cases lookup a l; exact dec_trivial
end
theorem of_mem_lookup
{a : α} {b : β a} : ∀ {l : list (sigma β)}, b ∈ lookup a l → sigma.mk a b ∈ l
| (⟨a', b'⟩ :: l) H := begin
by_cases h : a = a',
{ subst a', simp at H, simp [H] },
{ simp [h] at H, exact or.inr (of_mem_lookup H) }
end
theorem mem_lookup {a} {b : β a} {l : list (sigma β)} (nd : l.nodupkeys)
(h : sigma.mk a b ∈ l) : b ∈ lookup a l :=
begin
cases option.is_some_iff_exists.mp (lookup_is_some.mpr (mem_keys_of_mem h)) with b' h',
cases nd.eq_of_mk_mem h (of_mem_lookup h'),
exact h'
end
theorem map_lookup_eq_find (a : α) : ∀ l : list (sigma β),
(lookup a l).map (sigma.mk a) = find (λ s, a = s.1) l
| [] := rfl
| (⟨a', b'⟩ :: l) := begin
by_cases h : a = a',
{ subst a', simp },
{ simp [h, map_lookup_eq_find] }
end
theorem mem_lookup_iff {a : α} {b : β a} {l : list (sigma β)} (nd : l.nodupkeys) :
b ∈ lookup a l ↔ sigma.mk a b ∈ l :=
⟨of_mem_lookup, mem_lookup nd⟩
theorem perm_lookup (a : α) {l₁ l₂ : list (sigma β)}
(nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) (p : l₁ ~ l₂) : lookup a l₁ = lookup a l₂ :=
by ext b; simp [mem_lookup_iff, nd₁, nd₂]; exact mem_of_perm p
lemma lookup_ext {l₀ l₁ : list (sigma β)}
(nd₀ : l₀.nodupkeys) (nd₁ : l₁.nodupkeys)
(h : ∀ x y, y ∈ l₀.lookup x ↔ y ∈ l₁.lookup x) : l₀ ~ l₁ :=
mem_ext (nodup_of_nodupkeys nd₀) (nodup_of_nodupkeys nd₁)
(λ ⟨a,b⟩, by rw [← mem_lookup_iff, ← mem_lookup_iff, h]; assumption)
/- lookup_all -/
/-- `lookup_all a l` is the list of all values in `l` corresponding to the key `a`. -/
def lookup_all (a : α) : list (sigma β) → list (β a)
| [] := []
| (⟨a', b⟩ :: l) := if h : a' = a then eq.rec_on h b :: lookup_all l else lookup_all l
@[simp] theorem lookup_all_nil (a : α) : lookup_all a [] = @nil (β a) := rfl
@[simp] theorem lookup_all_cons_eq (l) (a : α) (b : β a) :
lookup_all a (⟨a, b⟩::l) = b :: lookup_all a l :=
dif_pos rfl
@[simp] theorem lookup_all_cons_ne (l) {a} :
∀ s : sigma β, a ≠ s.1 → lookup_all a (s::l) = lookup_all a l
| ⟨a', b⟩ h := dif_neg h.symm
theorem lookup_all_eq_nil {a : α} : ∀ {l : list (sigma β)},
lookup_all a l = [] ↔ ∀ b : β a, sigma.mk a b ∉ l
| [] := by simp
| (⟨a', b⟩ :: l) := begin
by_cases h : a = a',
{ subst a', simp, exact ⟨_, or.inl rfl⟩ },
{ simp [h, lookup_all_eq_nil] },
end
theorem head_lookup_all (a : α) : ∀ l : list (sigma β),
head' (lookup_all a l) = lookup a l
| [] := by simp
| (⟨a', b⟩ :: l) := by by_cases h : a = a'; [{subst h, simp}, simp *]
theorem mem_lookup_all {a : α} {b : β a} :
∀ {l : list (sigma β)}, b ∈ lookup_all a l ↔ sigma.mk a b ∈ l
| [] := by simp
| (⟨a', b'⟩ :: l) := by by_cases h : a = a'; [{subst h, simp *}, simp *]
theorem lookup_all_sublist (a : α) :
∀ l : list (sigma β), (lookup_all a l).map (sigma.mk a) <+ l
| [] := by simp
| (⟨a', b'⟩ :: l) := begin
by_cases h : a = a',
{ subst h, simp, exact (lookup_all_sublist l).cons2 _ _ _ },
{ simp [h], exact (lookup_all_sublist l).cons _ _ _ }
end
theorem lookup_all_length_le_one (a : α) {l : list (sigma β)} (h : l.nodupkeys) :
length (lookup_all a l) ≤ 1 :=
by have := nodup_of_sublist (map_sublist_map _ $ lookup_all_sublist a l) h;
rw map_map at this; rwa [← nodup_repeat, ← map_const _ a]
theorem lookup_all_eq_lookup (a : α) {l : list (sigma β)} (h : l.nodupkeys) :
lookup_all a l = (lookup a l).to_list :=
begin
rw ← head_lookup_all,
have := lookup_all_length_le_one a h, revert this,
rcases lookup_all a l with _|⟨b, _|⟨c, l⟩⟩; intro; try {refl},
exact absurd this dec_trivial
end
theorem lookup_all_nodup (a : α) {l : list (sigma β)} (h : l.nodupkeys) :
(lookup_all a l).nodup :=
by rw lookup_all_eq_lookup a h; apply option.to_list_nodup
theorem perm_lookup_all (a : α) {l₁ l₂ : list (sigma β)}
(nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) (p : l₁ ~ l₂) : lookup_all a l₁ = lookup_all a l₂ :=
by simp [lookup_all_eq_lookup, nd₁, nd₂, perm_lookup a nd₁ nd₂ p]
/- kreplace -/
def kreplace (a : α) (b : β a) : list (sigma β) → list (sigma β) :=
lookmap $ λ s, if h : a = s.1 then some ⟨a, b⟩ else none
theorem kreplace_of_forall_not (a : α) (b : β a) {l : list (sigma β)}
(H : ∀ b : β a, sigma.mk a b ∉ l) : kreplace a b l = l :=
lookmap_of_forall_not _ $ begin
rintro ⟨a', b'⟩ h, dsimp, split_ifs,
{ subst a', exact H _ h }, {refl}
end
theorem kreplace_self {a : α} {b : β a} {l : list (sigma β)}
(nd : nodupkeys l) (h : sigma.mk a b ∈ l) : kreplace a b l = l :=
begin
refine (lookmap_congr _).trans
(lookmap_id' (option.guard (λ s, a = s.1)) _ _),
{ rintro ⟨a', b'⟩ h', dsimp [option.guard], split_ifs,
{ subst a', exact ⟨rfl, heq_of_eq $ nd.eq_of_mk_mem h h'⟩ },
{ refl } },
{ rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, dsimp [option.guard], split_ifs,
{ subst a₁, rintro ⟨⟩, simp }, { rintro ⟨⟩ } },
end
theorem keys_kreplace (a : α) (b : β a) : ∀ l : list (sigma β),
(kreplace a b l).keys = l.keys :=
lookmap_map_eq _ _ $ by rintro ⟨a₁, b₂⟩ ⟨a₂, b₂⟩;
dsimp; split_ifs; simp [h] {contextual := tt}
theorem kreplace_nodupkeys (a : α) (b : β a) {l : list (sigma β)} :
(kreplace a b l).nodupkeys ↔ l.nodupkeys :=
by simp [nodupkeys, keys_kreplace]
theorem perm_kreplace {a : α} {b : β a} {l₁ l₂ : list (sigma β)}
(nd : l₁.nodupkeys) : l₁ ~ l₂ →
kreplace a b l₁ ~ kreplace a b l₂ :=
perm_lookmap _ $ begin
refine (nodupkeys_iff_pairwise.1 nd).imp _,
intros x y h z h₁ w h₂,
split_ifs at h₁ h₂; cases h₁; cases h₂,
exact (h (h_2.symm.trans h_1)).elim
end
/- kerase -/
/-- Remove the first pair with the key `a`. -/
def kerase (a : α) : list (sigma β) → list (sigma β) :=
erasep $ λ s, a = s.1
@[simp] theorem kerase_nil {a} : @kerase _ β _ a [] = [] :=
rfl
@[simp, priority 990]
theorem kerase_cons_eq {a} {s : sigma β} {l : list (sigma β)} (h : a = s.1) :
kerase a (s :: l) = l :=
by simp [kerase, h]
@[simp, priority 990]
theorem kerase_cons_ne {a} {s : sigma β} {l : list (sigma β)} (h : a ≠ s.1) :
kerase a (s :: l) = s :: kerase a l :=
by simp [kerase, h]
@[simp, priority 980]
theorem kerase_of_not_mem_keys {a} {l : list (sigma β)} (h : a ∉ l.keys) :
kerase a l = l :=
by induction l with _ _ ih;
[refl, { simp [not_or_distrib] at h, simp [h.1, ih h.2] }]
theorem kerase_sublist (a : α) (l : list (sigma β)) : kerase a l <+ l :=
erasep_sublist _
theorem kerase_keys_subset (a) (l : list (sigma β)) :
(kerase a l).keys ⊆ l.keys :=
subset_of_sublist (map_sublist_map _ (kerase_sublist a l))
theorem mem_keys_of_mem_keys_kerase {a₁ a₂} {l : list (sigma β)} :
a₁ ∈ (kerase a₂ l).keys → a₁ ∈ l.keys :=
@kerase_keys_subset _ _ _ _ _ _
theorem exists_of_kerase {a : α} {l : list (sigma β)} (h : a ∈ l.keys) :
∃ (b : β a) (l₁ l₂ : list (sigma β)),
a ∉ l₁.keys ∧
l = l₁ ++ ⟨a, b⟩ :: l₂ ∧
kerase a l = l₁ ++ l₂ :=
begin
induction l,
case list.nil { cases h },
case list.cons : hd tl ih {
by_cases e : a = hd.1,
{ subst e,
exact ⟨hd.2, [], tl, by simp, by cases hd; refl, by simp⟩ },
{ simp at h,
cases h,
case or.inl : h { exact absurd h e },
case or.inr : h {
rcases ih h with ⟨b, tl₁, tl₂, h₁, h₂, h₃⟩,
exact ⟨b, hd :: tl₁, tl₂, not_mem_cons_of_ne_of_not_mem e h₁,
by rw h₂; refl, by simp [e, h₃]⟩ } } }
end
@[simp, priority 990]
theorem mem_keys_kerase_of_ne {a₁ a₂} {l : list (sigma β)} (h : a₁ ≠ a₂) :
a₁ ∈ (kerase a₂ l).keys ↔ a₁ ∈ l.keys :=
iff.intro mem_keys_of_mem_keys_kerase $ λ p,
if q : a₂ ∈ l.keys then
match l, kerase a₂ l, exists_of_kerase q, p with
| _, _, ⟨_, _, _, _, rfl, rfl⟩, p := by simpa [keys, h] using p
end
else
by simp [q, p]
theorem keys_kerase {a} {l : list (sigma β)} : (kerase a l).keys = l.keys.erase a :=
by rw [keys, kerase, ←erasep_map sigma.fst l, erase_eq_erasep]
theorem kerase_kerase {a a'} {l : list (sigma β)} : (kerase a' l).kerase a = (kerase a l).kerase a' :=
begin
by_cases a = a',
{ subst a' },
induction l with x xs, { refl },
{ by_cases a' = x.1,
{ subst a', simp [kerase_cons_ne h,kerase_cons_eq rfl] },
by_cases h' : a = x.1,
{ subst a, simp [kerase_cons_eq rfl,kerase_cons_ne (ne.symm h)] },
{ simp [kerase_cons_ne,*] } }
end
theorem kerase_nodupkeys (a : α) {l : list (sigma β)} : nodupkeys l → (kerase a l).nodupkeys :=
nodupkeys_of_sublist $ kerase_sublist _ _
theorem perm_kerase {a : α} {l₁ l₂ : list (sigma β)}
(nd : l₁.nodupkeys) : l₁ ~ l₂ → kerase a l₁ ~ kerase a l₂ :=
perm_erasep _ $ (nodupkeys_iff_pairwise.1 nd).imp $
by rintro x y h rfl; exact h
@[simp] theorem not_mem_keys_kerase (a) {l : list (sigma β)} (nd : l.nodupkeys) :
a ∉ (kerase a l).keys :=
begin
induction l,
case list.nil { simp },
case list.cons : hd tl ih {
simp at nd,
by_cases h : a = hd.1,
{ subst h, simp [nd.1] },
{ simp [h, ih nd.2] } }
end
@[simp] theorem lookup_kerase (a) {l : list (sigma β)} (nd : l.nodupkeys) :
lookup a (kerase a l) = none :=
lookup_eq_none.mpr (not_mem_keys_kerase a nd)
@[simp] theorem lookup_kerase_ne {a a'} {l : list (sigma β)} (h : a ≠ a') :
lookup a (kerase a' l) = lookup a l :=
begin
induction l,
case list.nil { refl },
case list.cons : hd tl ih {
cases hd with ah bh,
by_cases h₁ : a = ah; by_cases h₂ : a' = ah,
{ substs h₁ h₂, cases ne.irrefl h },
{ subst h₁, simp [h₂] },
{ subst h₂, simp [h] },
{ simp [h₁, h₂, ih] }
}
end
theorem kerase_append_left {a} : ∀ {l₁ l₂ : list (sigma β)},
a ∈ l₁.keys → kerase a (l₁ ++ l₂) = kerase a l₁ ++ l₂
| [] _ h := by cases h
| (s :: l₁) l₂ h₁ :=
if h₂ : a = s.1 then
by simp [h₂]
else
by simp at h₁;
cases h₁;
[exact absurd h₁ h₂, simp [h₂, kerase_append_left h₁]]
theorem kerase_append_right {a} : ∀ {l₁ l₂ : list (sigma β)},
a ∉ l₁.keys → kerase a (l₁ ++ l₂) = l₁ ++ kerase a l₂
| [] _ h := rfl
| (_ :: l₁) l₂ h := by simp [not_or_distrib] at h;
simp [h.1, kerase_append_right h.2]
theorem kerase_comm (a₁ a₂) (l : list (sigma β)) :
kerase a₂ (kerase a₁ l) = kerase a₁ (kerase a₂ l) :=
if h : a₁ = a₂ then
by simp [h]
else if ha₁ : a₁ ∈ l.keys then
if ha₂ : a₂ ∈ l.keys then
match l, kerase a₁ l, exists_of_kerase ha₁, ha₂ with
| _, _, ⟨b₁, l₁, l₂, a₁_nin_l₁, rfl, rfl⟩, a₂_in_l₁_app_l₂ :=
if h' : a₂ ∈ l₁.keys then
by simp [kerase_append_left h',
kerase_append_right (mt (mem_keys_kerase_of_ne h).mp a₁_nin_l₁)]
else
by simp [kerase_append_right h', kerase_append_right a₁_nin_l₁,
@kerase_cons_ne _ _ _ a₂ ⟨a₁, b₁⟩ _ (ne.symm h)]
end
else
by simp [ha₂, mt mem_keys_of_mem_keys_kerase ha₂]
else
by simp [ha₁, mt mem_keys_of_mem_keys_kerase ha₁]
/- kinsert -/
/-- Insert the pair `⟨a, b⟩` and erase the first pair with the key `a`. -/
def kinsert (a : α) (b : β a) (l : list (sigma β)) : list (sigma β) :=
⟨a, b⟩ :: kerase a l
@[simp] theorem kinsert_def {a} {b : β a} {l : list (sigma β)} :
kinsert a b l = ⟨a, b⟩ :: kerase a l := rfl
theorem mem_keys_kinsert {a a'} {b' : β a'} {l : list (sigma β)} :
a ∈ (kinsert a' b' l).keys ↔ a = a' ∨ a ∈ l.keys :=
by by_cases h : a = a'; simp [h]
theorem kinsert_nodupkeys (a) (b : β a) {l : list (sigma β)} (nd : l.nodupkeys) :
(kinsert a b l).nodupkeys :=
nodupkeys_cons.mpr ⟨not_mem_keys_kerase a nd, kerase_nodupkeys a nd⟩
theorem perm_kinsert {a} {b : β a} {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys)
(p : l₁ ~ l₂) : kinsert a b l₁ ~ kinsert a b l₂ :=
perm.skip ⟨a, b⟩ $ perm_kerase nd₁ p
theorem lookup_kinsert {a} {b : β a} (l : list (sigma β)) :
lookup a (kinsert a b l) = some b :=
by simp only [kinsert, lookup_cons_eq]
theorem lookup_kinsert_ne {a a'} {b' : β a'} {l : list (sigma β)} (h : a ≠ a') :
lookup a (kinsert a' b' l) = lookup a l :=
by simp [h]
/- kextract -/
def kextract (a : α) : list (sigma β) → option (β a) × list (sigma β)
| [] := (none, [])
| (s::l) := if h : s.1 = a then (some (eq.rec_on h s.2), l) else
let (b', l') := kextract l in (b', s :: l')
@[simp] theorem kextract_eq_lookup_kerase (a : α) :
∀ l : list (sigma β), kextract a l = (lookup a l, kerase a l)
| [] := rfl
| (⟨a', b⟩::l) := begin
simp [kextract], dsimp, split_ifs,
{ subst a', simp [kerase] },
{ simp [kextract, ne.symm h, kextract_eq_lookup_kerase l, kerase] }
end
/- erase_dupkeys -/
def erase_dupkeys : list (sigma β) → list (sigma β) :=
list.foldr (λ ⟨x,y⟩, kinsert x y) []
lemma erase_dupkeys_cons {x : α} {y : β x} (l : list (sigma β)) : erase_dupkeys (⟨x,y⟩ :: l) = kinsert x y (erase_dupkeys l) := rfl
lemma nodupkeys_erase_dupkeys (l : list (sigma β)) : nodupkeys (erase_dupkeys l) :=
begin
dsimp [erase_dupkeys], generalize hl : nil = l',
have : nodupkeys l', { rw ← hl, apply nodup_nil },
clear hl,
induction l with x xs,
{ apply this },
{ cases x, simp [erase_dupkeys], split,
{ simp [keys_kerase], apply mem_erase_of_nodup l_ih },
apply kerase_nodupkeys _ l_ih, }
end
lemma lookup_erase_dupkeys (a : α) (l : list (sigma β)) : lookup a (erase_dupkeys l) = lookup a l :=
begin
induction l, refl,
cases l_hd with a' b,
by_cases a = a',
{ subst a', rw [erase_dupkeys_cons,lookup_kinsert,lookup_cons_eq] },
{ rw [erase_dupkeys_cons,lookup_kinsert_ne h,l_ih,lookup_cons_ne], exact h },
end
/- kunion -/
/-- `kunion l₁ l₂` is the append to l₁ of l₂ after, for each key in l₁, the
first matching pair in l₂ is erased. -/
def kunion : list (sigma β) → list (sigma β) → list (sigma β)
| [] l₂ := l₂
| (s :: l₁) l₂ := s :: kunion l₁ (kerase s.1 l₂)
@[simp] theorem nil_kunion {l : list (sigma β)} : kunion [] l = l :=
rfl
@[simp] theorem kunion_nil : ∀ {l : list (sigma β)}, kunion l [] = l
| [] := rfl
| (_ :: l) := by rw [kunion, kerase_nil, kunion_nil]
@[simp] theorem kunion_cons {s} {l₁ l₂ : list (sigma β)} :
kunion (s :: l₁) l₂ = s :: kunion l₁ (kerase s.1 l₂) :=
rfl
@[simp] theorem mem_keys_kunion {a} {l₁ l₂ : list (sigma β)} :
a ∈ (kunion l₁ l₂).keys ↔ a ∈ l₁.keys ∨ a ∈ l₂.keys :=
begin
induction l₁ generalizing l₂,
case list.nil { simp },
case list.cons : s l₁ ih { by_cases h : a = s.1; [simp [h], simp [h, ih]] }
end
@[simp] theorem kunion_kerase {a} : ∀ {l₁ l₂ : list (sigma β)},
kunion (kerase a l₁) (kerase a l₂) = kerase a (kunion l₁ l₂)
| [] _ := rfl
| (s :: _) l := by by_cases h : a = s.1;
simp [h, kerase_comm a s.1 l, kunion_kerase]
theorem kunion_nodupkeys {l₁ l₂ : list (sigma β)}
(nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) : (kunion l₁ l₂).nodupkeys :=
begin
induction l₁ generalizing l₂,
case list.nil { simp only [nil_kunion, nd₂] },
case list.cons : s l₁ ih {
simp at nd₁,
simp [not_or_distrib, nd₁.1, nd₂, ih nd₁.2 (kerase_nodupkeys s.1 nd₂)] }
end
theorem perm_kunion_left {l₁ l₂ : list (sigma β)} (p : l₁ ~ l₂) (l) :
kunion l₁ l ~ kunion l₂ l :=
begin
induction p generalizing l,
case list.perm.nil { refl },
case list.perm.skip : hd tl₁ tl₂ p ih {
simp [ih (kerase hd.1 l), perm.skip] },
case list.perm.swap : s₁ s₂ l {
simp [kerase_comm, perm.swap] },
case list.perm.trans : l₁ l₂ l₃ p₁₂ p₂₃ ih₁₂ ih₂₃ {
exact perm.trans (ih₁₂ l) (ih₂₃ l) }
end
theorem perm_kunion_right : ∀ l {l₁ l₂ : list (sigma β)},
l₁.nodupkeys → l₁ ~ l₂ → kunion l l₁ ~ kunion l l₂
| [] _ _ _ p := p
| (s :: l) l₁ l₂ nd₁ p :=
by simp [perm.skip s
(perm_kunion_right l (kerase_nodupkeys s.1 nd₁) (perm_kerase nd₁ p))]
theorem perm_kunion {l₁ l₂ l₃ l₄ : list (sigma β)} (nd₃ : l₃.nodupkeys)
(p₁₂ : l₁ ~ l₂) (p₃₄ : l₃ ~ l₄) : kunion l₁ l₃ ~ kunion l₂ l₄ :=
perm.trans (perm_kunion_left p₁₂ l₃) (perm_kunion_right l₂ nd₃ p₃₄)
@[simp] theorem lookup_kunion_left {a} {l₁ l₂ : list (sigma β)} (h : a ∈ l₁.keys) :
lookup a (kunion l₁ l₂) = lookup a l₁ :=
begin
induction l₁ with s _ ih generalizing l₂; simp at h; cases h; cases s with a',
{ subst h, simp },
{ rw kunion_cons,
by_cases h' : a = a',
{ subst h', simp },
{ simp [h', ih h] } }
end
@[simp] theorem lookup_kunion_right {a} {l₁ l₂ : list (sigma β)} (h : a ∉ l₁.keys) :
lookup a (kunion l₁ l₂) = lookup a l₂ :=
begin
induction l₁ generalizing l₂,
case list.nil { simp },
case list.cons : _ _ ih { simp [not_or_distrib] at h, simp [h.1, ih h.2] }
end
@[simp] theorem mem_lookup_kunion {a} {b : β a} {l₁ l₂ : list (sigma β)} :
b ∈ lookup a (kunion l₁ l₂) ↔ b ∈ lookup a l₁ ∨ a ∉ l₁.keys ∧ b ∈ lookup a l₂ :=
begin
induction l₁ generalizing l₂,
case list.nil { simp },
case list.cons : s _ ih {
cases s with a',
by_cases h₁ : a = a',
{ subst h₁, simp },
{ let h₂ := @ih (kerase a' l₂), simp [h₁] at h₂, simp [h₁, h₂] } }
end
theorem mem_lookup_kunion_middle {a} {b : β a} {l₁ l₂ l₃ : list (sigma β)}
(h₁ : b ∈ lookup a (kunion l₁ l₃)) (h₂ : a ∉ keys l₂) :
b ∈ lookup a (kunion (kunion l₁ l₂) l₃) :=
match mem_lookup_kunion.mp h₁ with
| or.inl h := mem_lookup_kunion.mpr (or.inl (mem_lookup_kunion.mpr (or.inl h)))
| or.inr h := mem_lookup_kunion.mpr $
or.inr ⟨mt mem_keys_kunion.mp (not_or_distrib.mpr ⟨h.1, h₂⟩), h.2⟩
end
end list
|
2fb751da278fc9bcb2613ead0bf1896bfc0f1a96 | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/analysis/convex/cone.lean | fbe563c28bea4464e9cee94a9f05e8c321fa8ec5 | [
"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 | 23,980 | lean | /-
Copyright (c) 2020 Yury Kudryashov All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Frédéric Dupuis
-/
import analysis.convex.basic
import analysis.normed_space.inner_product
/-!
# Convex cones
In a vector space `E` over `ℝ`, we define a convex cone as a subset `s` such that
`a • x + b • y ∈ s` whenever `x, y ∈ s` and `a, b > 0`. We prove that convex cones form
a `complete_lattice`, and define their images (`convex_cone.map`) and preimages
(`convex_cone.comap`) under linear maps.
We define pointed, blunt, flat and salient cones, and prove the correspondence between
convex cones and ordered modules.
We also define `convex.to_cone` to be the minimal cone that includes a given convex set.
We define `set.inner_dual_cone` to be the cone consisting of all points `y` such that for
all points `x` in a given set `0 ≤ ⟪ x, y ⟫`.
## Main statements
We prove two extension theorems:
* `riesz_extension`:
[M. Riesz extension theorem](https://en.wikipedia.org/wiki/M._Riesz_extension_theorem) says that
if `s` is a convex cone in a real vector space `E`, `p` is a submodule of `E`
such that `p + s = E`, and `f` is a linear function `p → ℝ` which is
nonnegative on `p ∩ s`, then there exists a globally defined linear function
`g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`.
* `exists_extension_of_le_sublinear`:
Hahn-Banach theorem: if `N : E → ℝ` is a sublinear map, `f` is a linear map
defined on a subspace of `E`, and `f x ≤ N x` for all `x` in the domain of `f`,
then `f` can be extended to the whole space to a linear map `g` such that `g x ≤ N x`
for all `x`
## Implementation notes
While `convex` is a predicate on sets, `convex_cone` is a bundled convex cone.
## References
* https://en.wikipedia.org/wiki/Convex_cone
-/
universes u v
open set linear_map
open_locale classical pointwise
variables (E : Type*) [add_comm_group E] [module ℝ E]
{F : Type*} [add_comm_group F] [module ℝ F]
{G : Type*} [add_comm_group G] [module ℝ G]
/-!
### Definition of `convex_cone` and basic properties
-/
/-- A convex cone is a subset `s` of a vector space over `ℝ` such that `a • x + b • y ∈ s`
whenever `a, b > 0` and `x, y ∈ s`. -/
structure convex_cone :=
(carrier : set E)
(smul_mem' : ∀ ⦃c : ℝ⦄, 0 < c → ∀ ⦃x : E⦄, x ∈ carrier → c • x ∈ carrier)
(add_mem' : ∀ ⦃x⦄ (hx : x ∈ carrier) ⦃y⦄ (hy : y ∈ carrier), x + y ∈ carrier)
variable {E}
namespace convex_cone
variables (S T : convex_cone E)
instance : has_coe (convex_cone E) (set E) := ⟨convex_cone.carrier⟩
instance : has_mem E (convex_cone E) := ⟨λ m S, m ∈ S.carrier⟩
instance : has_le (convex_cone E) := ⟨λ S T, S.carrier ⊆ T.carrier⟩
instance : has_lt (convex_cone E) := ⟨λ S T, S.carrier ⊂ T.carrier⟩
@[simp, norm_cast] lemma mem_coe {x : E} : x ∈ (S : set E) ↔ x ∈ S := iff.rfl
@[simp] lemma mem_mk {s : set E} {h₁ h₂ x} : x ∈ mk s h₁ h₂ ↔ x ∈ s := iff.rfl
/-- Two `convex_cone`s are equal if the underlying subsets are equal. -/
theorem ext' {S T : convex_cone E} (h : (S : set E) = T) : S = T :=
by cases S; cases T; congr'
/-- Two `convex_cone`s are equal if and only if the underlying subsets are equal. -/
protected theorem ext'_iff {S T : convex_cone E} : (S : set E) = T ↔ S = T :=
⟨ext', λ h, h ▸ rfl⟩
/-- Two `convex_cone`s are equal if they have the same elements. -/
@[ext] theorem ext {S T : convex_cone E} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h
lemma smul_mem {c : ℝ} {x : E} (hc : 0 < c) (hx : x ∈ S) : c • x ∈ S := S.smul_mem' hc hx
lemma add_mem ⦃x⦄ (hx : x ∈ S) ⦃y⦄ (hy : y ∈ S) : x + y ∈ S := S.add_mem' hx hy
lemma smul_mem_iff {c : ℝ} (hc : 0 < c) {x : E} :
c • x ∈ S ↔ x ∈ S :=
⟨λ h, by simpa only [smul_smul, inv_mul_cancel (ne_of_gt hc), one_smul]
using S.smul_mem (inv_pos.2 hc) h, λ h, S.smul_mem hc h⟩
lemma convex : convex (S : set E) :=
convex_iff_forall_pos.2 $ λ x y hx hy a b ha hb hab,
S.add_mem (S.smul_mem ha hx) (S.smul_mem hb hy)
instance : has_inf (convex_cone E) :=
⟨λ S T, ⟨S ∩ T, λ c hc x hx, ⟨S.smul_mem hc hx.1, T.smul_mem hc hx.2⟩,
λ x hx y hy, ⟨S.add_mem hx.1 hy.1, T.add_mem hx.2 hy.2⟩⟩⟩
lemma coe_inf : ((S ⊓ T : convex_cone E) : set E) = ↑S ∩ ↑T := rfl
lemma mem_inf {x} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T := iff.rfl
instance : has_Inf (convex_cone E) :=
⟨λ S, ⟨⋂ s ∈ S, ↑s,
λ c hc x hx, mem_bInter $ λ s hs, s.smul_mem hc $ by apply mem_bInter_iff.1 hx s hs,
λ x hx y hy, mem_bInter $ λ s hs, s.add_mem (by apply mem_bInter_iff.1 hx s hs)
(by apply mem_bInter_iff.1 hy s hs)⟩⟩
lemma mem_Inf {x : E} {S : set (convex_cone E)} : x ∈ Inf S ↔ ∀ s ∈ S, x ∈ s := mem_bInter_iff
instance : has_bot (convex_cone E) := ⟨⟨∅, λ c hc x, false.elim, λ x, false.elim⟩⟩
lemma mem_bot (x : E) : x ∈ (⊥ : convex_cone E) = false := rfl
instance : has_top (convex_cone E) := ⟨⟨univ, λ c hc x hx, mem_univ _, λ x hx y hy, mem_univ _⟩⟩
lemma mem_top (x : E) : x ∈ (⊤ : convex_cone E) := mem_univ x
instance : complete_lattice (convex_cone E) :=
{ le := (≤),
lt := (<),
bot := (⊥),
bot_le := λ S x, false.elim,
top := (⊤),
le_top := λ S x hx, mem_top x,
inf := (⊓),
Inf := has_Inf.Inf,
sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x},
Sup := λ s, Inf {T | ∀ S ∈ s, S ≤ T},
le_sup_left := λ a b, λ x hx, mem_Inf.2 $ λ s hs, hs.1 hx,
le_sup_right := λ a b, λ x hx, mem_Inf.2 $ λ s hs, hs.2 hx,
sup_le := λ a b c ha hb x hx, mem_Inf.1 hx c ⟨ha, hb⟩,
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,
le_Sup := λ s p hs x hx, mem_Inf.2 $ λ t ht, ht p hs hx,
Sup_le := λ s p hs x hx, mem_Inf.1 hx p hs,
le_Inf := λ s a ha x hx, mem_Inf.2 $ λ t ht, ha t ht hx,
Inf_le := λ s a ha x hx, mem_Inf.1 hx _ ha,
.. partial_order.lift (coe : convex_cone E → set E) (λ a b, ext') }
instance : inhabited (convex_cone E) := ⟨⊥⟩
/-- The image of a convex cone under an `ℝ`-linear map is a convex cone. -/
def map (f : E →ₗ[ℝ] F) (S : convex_cone E) : convex_cone F :=
{ carrier := f '' S,
smul_mem' := λ c hc y ⟨x, hx, hy⟩, hy ▸ f.map_smul c x ▸ mem_image_of_mem f (S.smul_mem hc hx),
add_mem' := λ y₁ ⟨x₁, hx₁, hy₁⟩ y₂ ⟨x₂, hx₂, hy₂⟩, hy₁ ▸ hy₂ ▸ f.map_add x₁ x₂ ▸
mem_image_of_mem f (S.add_mem hx₁ hx₂) }
lemma map_map (g : F →ₗ[ℝ] G) (f : E →ₗ[ℝ] F) (S : convex_cone E) :
(S.map f).map g = S.map (g.comp f) :=
ext' $ image_image g f S
@[simp] lemma map_id : S.map linear_map.id = S := ext' $ image_id _
/-- The preimage of a convex cone under an `ℝ`-linear map is a convex cone. -/
def comap (f : E →ₗ[ℝ] F) (S : convex_cone F) : convex_cone E :=
{ carrier := f ⁻¹' S,
smul_mem' := λ c hc x hx, by { rw [mem_preimage, f.map_smul c], exact S.smul_mem hc hx },
add_mem' := λ x hx y hy, by { rw [mem_preimage, f.map_add], exact S.add_mem hx hy } }
@[simp] lemma comap_id : S.comap linear_map.id = S := ext' preimage_id
lemma comap_comap (g : F →ₗ[ℝ] G) (f : E →ₗ[ℝ] F) (S : convex_cone G) :
(S.comap g).comap f = S.comap (g.comp f) :=
ext' $ preimage_comp.symm
@[simp] lemma mem_comap {f : E →ₗ[ℝ] F} {S : convex_cone F} {x : E} :
x ∈ S.comap f ↔ f x ∈ S := iff.rfl
/--
Constructs an ordered module given an `ordered_add_comm_group`, a cone, and a proof that
the order relation is the one defined by the cone.
-/
lemma to_ordered_module {M : Type*} [ordered_add_comm_group M] [module ℝ M]
(S : convex_cone M) (h : ∀ x y : M, x ≤ y ↔ y - x ∈ S) : ordered_module ℝ M :=
ordered_module.mk'
begin
intros x y z xy hz,
rw [h (z • x) (z • y), ←smul_sub z y x],
exact smul_mem S hz ((h x y).mp (le_of_lt xy))
end
/-! ### Convex cones with extra properties -/
/-- A convex cone is pointed if it includes 0. -/
def pointed (S : convex_cone E) : Prop := (0 : E) ∈ S
/-- A convex cone is blunt if it doesn't include 0. -/
def blunt (S : convex_cone E) : Prop := (0 : E) ∉ S
/-- A convex cone is flat if it contains some nonzero vector `x` and its opposite `-x`. -/
def flat (S : convex_cone E) : Prop := ∃ x ∈ S, x ≠ (0 : E) ∧ -x ∈ S
/-- A convex cone is salient if it doesn't include `x` and `-x` for any nonzero `x`. -/
def salient (S : convex_cone E) : Prop := ∀ x ∈ S, x ≠ (0 : E) → -x ∉ S
lemma pointed_iff_not_blunt (S : convex_cone E) : pointed S ↔ ¬blunt S :=
⟨λ h₁ h₂, h₂ h₁, λ h, not_not.mp h⟩
lemma salient_iff_not_flat (S : convex_cone E) : salient S ↔ ¬flat S :=
begin
split,
{ rintros h₁ ⟨x, xs, H₁, H₂⟩,
exact h₁ x xs H₁ H₂ },
{ intro h,
unfold flat at h,
push_neg at h,
exact h }
end
/-- A blunt cone (one not containing 0) is always salient. -/
lemma salient_of_blunt (S : convex_cone E) : blunt S → salient S :=
begin
intro h₁,
rw [salient_iff_not_flat],
intro h₂,
obtain ⟨x, xs, H₁, H₂⟩ := h₂,
have hkey : (0 : E) ∈ S := by rw [(show 0 = x + (-x), by simp)]; exact add_mem S xs H₂,
exact h₁ hkey,
end
/-- A pointed convex cone defines a preorder. -/
def to_preorder (S : convex_cone E) (h₁ : pointed S) : preorder E :=
{ le := λ x y, y - x ∈ S,
le_refl := λ x, by change x - x ∈ S; rw [sub_self x]; exact h₁,
le_trans := λ x y z xy zy, by simp [(show z - x = z - y + (y - x), by abel), add_mem S zy xy] }
/-- A pointed and salient cone defines a partial order. -/
def to_partial_order (S : convex_cone E) (h₁ : pointed S) (h₂ : salient S) : partial_order E :=
{ le_antisymm :=
begin
intros a b ab ba,
by_contradiction h,
have h' : b - a ≠ 0 := λ h'', h (eq_of_sub_eq_zero h'').symm,
have H := h₂ (b-a) ab h',
rw [neg_sub b a] at H,
exact H ba,
end,
..to_preorder S h₁ }
/-- A pointed and salient cone defines an `ordered_add_comm_group`. -/
def to_ordered_add_comm_group (S : convex_cone E) (h₁ : pointed S) (h₂ : salient S) :
ordered_add_comm_group E :=
{ add_le_add_left :=
begin
intros a b hab c,
change c + b - (c + a) ∈ S,
rw [add_sub_add_left_eq_sub],
exact hab,
end,
..to_partial_order S h₁ h₂,
..show add_comm_group E, by apply_instance }
/-! ### Positive cone of an ordered module -/
section positive_cone
variables (M : Type*) [ordered_add_comm_group M] [module ℝ M] [ordered_module ℝ M]
/--
The positive cone is the convex cone formed by the set of nonnegative elements in an ordered
module.
-/
def positive_cone : convex_cone M :=
{ carrier := {x | 0 ≤ x},
smul_mem' :=
begin
intros c hc x hx,
have := smul_le_smul_of_nonneg (show 0 ≤ x, by exact hx) (le_of_lt hc),
have h' : c • (0 : M) = 0,
{ simp only [smul_zero] },
rwa [h'] at this
end,
add_mem' := λ x hx y hy, add_nonneg (show 0 ≤ x, by exact hx) (show 0 ≤ y, by exact hy) }
/-- The positive cone of an ordered module is always salient. -/
lemma salient_of_positive_cone : salient (positive_cone M) :=
begin
intros x xs hx hx',
have := calc
0 < x : lt_of_le_of_ne xs hx.symm
... ≤ x + (-x) : (le_add_iff_nonneg_right x).mpr hx'
... = 0 : by rw [tactic.ring.add_neg_eq_sub x x]; exact sub_self x,
exact lt_irrefl 0 this,
end
/-- The positive cone of an ordered module is always pointed. -/
lemma pointed_of_positive_cone : pointed (positive_cone M) := le_refl 0
end positive_cone
end convex_cone
/-!
### Cone over a convex set
-/
namespace convex
/-- The set of vectors proportional to those in a convex set forms a convex cone. -/
def to_cone (s : set E) (hs : convex s) : convex_cone E :=
begin
apply convex_cone.mk (⋃ c > 0, (c : ℝ) • s);
simp only [mem_Union, mem_smul_set],
{ rintros c c_pos _ ⟨c', c'_pos, x, hx, rfl⟩,
exact ⟨c * c', mul_pos c_pos c'_pos, x, hx, (smul_smul _ _ _).symm⟩ },
{ rintros _ ⟨cx, cx_pos, x, hx, rfl⟩ _ ⟨cy, cy_pos, y, hy, rfl⟩,
have : 0 < cx + cy, from add_pos cx_pos cy_pos,
refine ⟨_, this, _, convex_iff_div.1 hs hx hy (le_of_lt cx_pos) (le_of_lt cy_pos) this, _⟩,
simp only [smul_add, smul_smul, mul_div_assoc', mul_div_cancel_left _ (ne_of_gt this)] }
end
variables {s : set E} (hs : convex s) {x : E}
lemma mem_to_cone : x ∈ hs.to_cone s ↔ ∃ (c > 0) (y ∈ s), (c : ℝ) • y = x :=
by simp only [to_cone, convex_cone.mem_mk, mem_Union, mem_smul_set, eq_comm, exists_prop]
lemma mem_to_cone' : x ∈ hs.to_cone s ↔ ∃ c > 0, (c : ℝ) • x ∈ s :=
begin
refine hs.mem_to_cone.trans ⟨_, _⟩,
{ rintros ⟨c, hc, y, hy, rfl⟩,
exact ⟨c⁻¹, inv_pos.2 hc, by rwa [smul_smul, inv_mul_cancel (ne_of_gt hc), one_smul]⟩ },
{ rintros ⟨c, hc, hcx⟩,
exact ⟨c⁻¹, inv_pos.2 hc, _, hcx, by rw [smul_smul, inv_mul_cancel (ne_of_gt hc), one_smul]⟩ }
end
lemma subset_to_cone : s ⊆ hs.to_cone s :=
λ x hx, hs.mem_to_cone'.2 ⟨1, zero_lt_one, by rwa one_smul⟩
/-- `hs.to_cone s` is the least cone that includes `s`. -/
lemma to_cone_is_least : is_least { t : convex_cone E | s ⊆ t } (hs.to_cone s) :=
begin
refine ⟨hs.subset_to_cone, λ t ht x hx, _⟩,
rcases hs.mem_to_cone.1 hx with ⟨c, hc, y, hy, rfl⟩,
exact t.smul_mem hc (ht hy)
end
lemma to_cone_eq_Inf : hs.to_cone s = Inf { t : convex_cone E | s ⊆ t } :=
hs.to_cone_is_least.is_glb.Inf_eq.symm
end convex
lemma convex_hull_to_cone_is_least (s : set E) :
is_least {t : convex_cone E | s ⊆ t} ((convex_convex_hull s).to_cone _) :=
begin
convert (convex_convex_hull s).to_cone_is_least,
ext t,
exact ⟨λ h, convex_hull_min h t.convex, λ h, subset.trans (subset_convex_hull s) h⟩
end
lemma convex_hull_to_cone_eq_Inf (s : set E) :
(convex_convex_hull s).to_cone _ = Inf {t : convex_cone E | s ⊆ t} :=
(convex_hull_to_cone_is_least s).is_glb.Inf_eq.symm
/-!
### M. Riesz extension theorem
Given a convex cone `s` in a vector space `E`, a submodule `p`, and a linear `f : p → ℝ`, assume
that `f` is nonnegative on `p ∩ s` and `p + s = E`. Then there exists a globally defined linear
function `g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`.
We prove this theorem using Zorn's lemma. `riesz_extension.step` is the main part of the proof.
It says that if the domain `p` of `f` is not the whole space, then `f` can be extended to a larger
subspace `p ⊔ span ℝ {y}` without breaking the non-negativity condition.
In `riesz_extension.exists_top` we use Zorn's lemma to prove that we can extend `f`
to a linear map `g` on `⊤ : submodule E`. Mathematically this is the same as a linear map on `E`
but in Lean `⊤ : submodule E` is isomorphic but is not equal to `E`. In `riesz_extension`
we use this isomorphism to prove the theorem.
-/
namespace riesz_extension
open submodule
variables (s : convex_cone E) (f : linear_pmap ℝ E ℝ)
/-- Induction step in M. Riesz extension theorem. Given a convex cone `s` in a vector space `E`,
a partially defined linear map `f : f.domain → ℝ`, assume that `f` is nonnegative on `f.domain ∩ p`
and `p + s = E`. If `f` is not defined on the whole `E`, then we can extend it to a larger
submodule without breaking the non-negativity condition. -/
lemma step (nonneg : ∀ x : f.domain, (x : E) ∈ s → 0 ≤ f x)
(dense : ∀ y, ∃ x : f.domain, (x : E) + y ∈ s) (hdom : f.domain ≠ ⊤) :
∃ g, f < g ∧ ∀ x : g.domain, (x : E) ∈ s → 0 ≤ g x :=
begin
rcases set_like.exists_of_lt (lt_top_iff_ne_top.2 hdom) with ⟨y, hy', hy⟩, clear hy',
obtain ⟨c, le_c, c_le⟩ :
∃ c, (∀ x : f.domain, -(x:E) - y ∈ s → f x ≤ c) ∧ (∀ x : f.domain, (x:E) + y ∈ s → c ≤ f x),
{ set Sp := f '' {x : f.domain | (x:E) + y ∈ s},
set Sn := f '' {x : f.domain | -(x:E) - y ∈ s},
suffices : (upper_bounds Sn ∩ lower_bounds Sp).nonempty,
by simpa only [set.nonempty, upper_bounds, lower_bounds, ball_image_iff] using this,
refine exists_between_of_forall_le (nonempty.image f _) (nonempty.image f (dense y)) _,
{ rcases (dense (-y)) with ⟨x, hx⟩,
rw [← neg_neg x, coe_neg, ← sub_eq_add_neg] at hx,
exact ⟨_, hx⟩ },
rintros a ⟨xn, hxn, rfl⟩ b ⟨xp, hxp, rfl⟩,
have := s.add_mem hxp hxn,
rw [add_assoc, add_sub_cancel'_right, ← sub_eq_add_neg, ← coe_sub] at this,
replace := nonneg _ this,
rwa [f.map_sub, sub_nonneg] at this },
have hy' : y ≠ 0, from λ hy₀, hy (hy₀.symm ▸ zero_mem _),
refine ⟨f.sup_span_singleton y (-c) hy, _, _⟩,
{ refine lt_iff_le_not_le.2 ⟨f.left_le_sup _ _, λ H, _⟩,
replace H := linear_pmap.domain_mono.monotone H,
rw [linear_pmap.domain_sup_span_singleton, sup_le_iff, span_le, singleton_subset_iff] at H,
exact hy H.2 },
{ rintros ⟨z, hz⟩ hzs,
rcases mem_sup.1 hz with ⟨x, hx, y', hy', rfl⟩,
rcases mem_span_singleton.1 hy' with ⟨r, rfl⟩,
simp only [subtype.coe_mk] at hzs,
erw [linear_pmap.sup_span_singleton_apply_mk _ _ _ _ _ hx, smul_neg,
← sub_eq_add_neg, sub_nonneg],
rcases lt_trichotomy r 0 with hr|hr|hr,
{ have : -(r⁻¹ • x) - y ∈ s,
by rwa [← s.smul_mem_iff (neg_pos.2 hr), smul_sub, smul_neg, neg_smul, neg_neg, smul_smul,
mul_inv_cancel (ne_of_lt hr), one_smul, sub_eq_add_neg, neg_smul, neg_neg],
replace := le_c (r⁻¹ • ⟨x, hx⟩) this,
rwa [← mul_le_mul_left (neg_pos.2 hr), ← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul,
neg_le_neg_iff, f.map_smul, smul_eq_mul, ← mul_assoc, mul_inv_cancel (ne_of_lt hr),
one_mul] at this },
{ subst r,
simp only [zero_smul, add_zero] at hzs ⊢,
apply nonneg,
exact hzs },
{ have : r⁻¹ • x + y ∈ s,
by rwa [← s.smul_mem_iff hr, smul_add, smul_smul, mul_inv_cancel (ne_of_gt hr), one_smul],
replace := c_le (r⁻¹ • ⟨x, hx⟩) this,
rwa [← mul_le_mul_left hr, f.map_smul, smul_eq_mul, ← mul_assoc,
mul_inv_cancel (ne_of_gt hr), one_mul] at this } }
end
theorem exists_top (p : linear_pmap ℝ E ℝ)
(hp_nonneg : ∀ x : p.domain, (x : E) ∈ s → 0 ≤ p x)
(hp_dense : ∀ y, ∃ x : p.domain, (x : E) + y ∈ s) :
∃ q ≥ p, q.domain = ⊤ ∧ ∀ x : q.domain, (x : E) ∈ s → 0 ≤ q x :=
begin
replace hp_nonneg : p ∈ { p | _ }, by { rw mem_set_of_eq, exact hp_nonneg },
obtain ⟨q, hqs, hpq, hq⟩ := zorn.zorn_nonempty_partial_order₀ _ _ _ hp_nonneg,
{ refine ⟨q, hpq, _, hqs⟩,
contrapose! hq,
rcases step s q hqs _ hq with ⟨r, hqr, hr⟩,
{ exact ⟨r, hr, le_of_lt hqr, ne_of_gt hqr⟩ },
{ exact λ y, let ⟨x, hx⟩ := hp_dense y in ⟨of_le hpq.left x, hx⟩ } },
{ intros c hcs c_chain y hy,
clear hp_nonneg hp_dense p,
have cne : c.nonempty := ⟨y, hy⟩,
refine ⟨linear_pmap.Sup c c_chain.directed_on, _, λ _, linear_pmap.le_Sup c_chain.directed_on⟩,
rintros ⟨x, hx⟩ hxs,
have hdir : directed_on (≤) (linear_pmap.domain '' c),
from directed_on_image.2 (c_chain.directed_on.mono linear_pmap.domain_mono.monotone),
rcases (mem_Sup_of_directed (cne.image _) hdir).1 hx with ⟨_, ⟨f, hfc, rfl⟩, hfx⟩,
have : f ≤ linear_pmap.Sup c c_chain.directed_on, from linear_pmap.le_Sup _ hfc,
convert ← hcs hfc ⟨x, hfx⟩ hxs,
apply this.2, refl }
end
end riesz_extension
/-- M. **Riesz extension theorem**: given a convex cone `s` in a vector space `E`, a submodule `p`,
and a linear `f : p → ℝ`, assume that `f` is nonnegative on `p ∩ s` and `p + s = E`. Then
there exists a globally defined linear function `g : E → ℝ` that agrees with `f` on `p`,
and is nonnegative on `s`. -/
theorem riesz_extension (s : convex_cone E) (f : linear_pmap ℝ E ℝ)
(nonneg : ∀ x : f.domain, (x : E) ∈ s → 0 ≤ f x) (dense : ∀ y, ∃ x : f.domain, (x : E) + y ∈ s) :
∃ g : E →ₗ[ℝ] ℝ, (∀ x : f.domain, g x = f x) ∧ (∀ x ∈ s, 0 ≤ g x) :=
begin
rcases riesz_extension.exists_top s f nonneg dense with ⟨⟨g_dom, g⟩, ⟨hpg, hfg⟩, htop, hgs⟩,
clear hpg,
refine ⟨g.comp (linear_equiv.of_top _ htop).symm, _, _⟩;
simp only [comp_apply, linear_equiv.coe_coe, linear_equiv.of_top_symm_apply],
{ exact λ x, (hfg (submodule.coe_mk _ _).symm).symm },
{ exact λ x hx, hgs ⟨x, _⟩ hx }
end
/-- **Hahn-Banach theorem**: if `N : E → ℝ` is a sublinear map, `f` is a linear map
defined on a subspace of `E`, and `f x ≤ N x` for all `x` in the domain of `f`,
then `f` can be extended to the whole space to a linear map `g` such that `g x ≤ N x`
for all `x`. -/
theorem exists_extension_of_le_sublinear (f : linear_pmap ℝ E ℝ) (N : E → ℝ)
(N_hom : ∀ (c : ℝ), 0 < c → ∀ x, N (c • x) = c * N x)
(N_add : ∀ x y, N (x + y) ≤ N x + N y)
(hf : ∀ x : f.domain, f x ≤ N x) :
∃ g : E →ₗ[ℝ] ℝ, (∀ x : f.domain, g x = f x) ∧ (∀ x, g x ≤ N x) :=
begin
let s : convex_cone (E × ℝ) :=
{ carrier := {p : E × ℝ | N p.1 ≤ p.2 },
smul_mem' := λ c hc p hp,
calc N (c • p.1) = c * N p.1 : N_hom c hc p.1
... ≤ c * p.2 : mul_le_mul_of_nonneg_left hp (le_of_lt hc),
add_mem' := λ x hx y hy, le_trans (N_add _ _) (add_le_add hx hy) },
obtain ⟨g, g_eq, g_nonneg⟩ :=
riesz_extension s ((-f).coprod (linear_map.id.to_pmap ⊤)) _ _;
try { simp only [linear_pmap.coprod_apply, to_pmap_apply, id_apply,
linear_pmap.neg_apply, ← sub_eq_neg_add, sub_nonneg, subtype.coe_mk] at * },
replace g_eq : ∀ (x : f.domain) (y : ℝ), g (x, y) = y - f x,
{ intros x y,
simpa only [subtype.coe_mk, subtype.coe_eta] using g_eq ⟨(x, y), ⟨x.2, trivial⟩⟩ },
{ refine ⟨-g.comp (inl ℝ E ℝ), _, _⟩; simp only [neg_apply, inl_apply, comp_apply],
{ intro x, simp [g_eq x 0] },
{ intro x,
have A : (x, N x) = (x, 0) + (0, N x), by simp,
have B := g_nonneg ⟨x, N x⟩ (le_refl (N x)),
rw [A, map_add, ← neg_le_iff_add_nonneg'] at B,
have C := g_eq 0 (N x),
simp only [submodule.coe_zero, f.map_zero, sub_zero] at C,
rwa ← C } },
{ exact λ x hx, le_trans (hf _) hx },
{ rintros ⟨x, y⟩,
refine ⟨⟨(0, N x - y), ⟨f.domain.zero_mem, trivial⟩⟩, _⟩,
simp only [convex_cone.mem_mk, mem_set_of_eq, subtype.coe_mk, prod.fst_add, prod.snd_add,
zero_add, sub_add_cancel] }
end
/-!
### The dual cone
-/
section dual
variables {H : Type*} [inner_product_space ℝ H] (s t : set H)
open_locale real_inner_product_space
/-- The dual cone is the cone consisting of all points `y` such that for
all points `x` in a given set `0 ≤ ⟪ x, y ⟫`. -/
noncomputable def set.inner_dual_cone (s : set H) : convex_cone H :=
{ carrier := { y | ∀ x ∈ s, 0 ≤ ⟪ x, y ⟫ },
smul_mem' := λ c hc y hy x hx,
begin
rw real_inner_smul_right,
exact mul_nonneg (le_of_lt hc) (hy x hx)
end,
add_mem' := λ u hu v hv x hx,
begin
rw inner_add_right,
exact add_nonneg (hu x hx) (hv x hx)
end }
lemma mem_inner_dual_cone (y : H) (s : set H) :
y ∈ s.inner_dual_cone ↔ ∀ x ∈ s, 0 ≤ ⟪ x, y ⟫ := by refl
@[simp] lemma inner_dual_cone_empty : (∅ : set H).inner_dual_cone = ⊤ :=
convex_cone.ext' (eq_univ_of_forall
(λ x y hy, false.elim (set.not_mem_empty _ hy)))
lemma inner_dual_cone_le_inner_dual_cone (h : t ⊆ s) :
s.inner_dual_cone ≤ t.inner_dual_cone :=
λ y hy x hx, hy x (h hx)
lemma pointed_inner_dual_cone : s.inner_dual_cone.pointed :=
λ x hx, by rw inner_zero_right
end dual
|
4964c94df039256ad3d7d19f9b828bce051e8361 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/combinatorics/simple_graph/regularity/uniform.lean | 47a34c7cc18de34011f7a09ac5e8261f40279d27 | [
"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,399 | lean | /-
Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Bhavik Mehta
-/
import combinatorics.simple_graph.density
import set_theory.ordinal.basic
/-!
# Graph uniformity and uniform partitions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define uniformity of a pair of vertices in a graph and uniformity of a partition of
vertices of a graph. Both are also known as ε-regularity.
Finsets of vertices `s` and `t` are `ε`-uniform in a graph `G` if their edge density is at most
`ε`-far from the density of any big enough `s'` and `t'` where `s' ⊆ s`, `t' ⊆ t`.
The definition is pretty technical, but it amounts to the edges between `s` and `t` being "random"
The literature contains several definitions which are equivalent up to scaling `ε` by some constant
when the partition is equitable.
A partition `P` of the vertices is `ε`-uniform if the proportion of non `ε`-uniform pairs of parts
is less than `ε`.
## Main declarations
* `simple_graph.is_uniform`: Graph uniformity of a pair of finsets of vertices.
* `simple_graph.nonuniform_witness`: `G.nonuniform_witness ε s t` and `G.nonuniform_witness ε t s`
together witness the non-uniformity of `s` and `t`.
* `finpartition.non_uniforms`: Non uniform pairs of parts of a partition.
* `finpartition.is_uniform`: Uniformity of a partition.
* `finpartition.nonuniform_witnesses`: For each non-uniform pair of parts of a partition, pick
witnesses of non-uniformity and dump them all together.
-/
open finset
variables {α 𝕜 : Type*} [linear_ordered_field 𝕜]
/-! ### Graph uniformity -/
namespace simple_graph
variables (G : simple_graph α) [decidable_rel G.adj] (ε : 𝕜) {s t : finset α} {a b : α}
/-- A pair of finsets of vertices is `ε`-uniform (aka `ε`-regular) iff their edge density is close
to the density of any big enough pair of subsets. Intuitively, the edges between them are
random-like. -/
def is_uniform (s t : finset α) : Prop :=
∀ ⦃s'⦄, s' ⊆ s → ∀ ⦃t'⦄, t' ⊆ t → (s.card : 𝕜) * ε ≤ s'.card → (t.card : 𝕜) * ε ≤ t'.card →
|(G.edge_density s' t' : 𝕜) - (G.edge_density s t : 𝕜)| < ε
variables {G ε}
lemma is_uniform.mono {ε' : 𝕜} (h : ε ≤ ε') (hε : is_uniform G ε s t) : is_uniform G ε' s t :=
λ s' hs' t' ht' hs ht, by refine (hε hs' ht' (le_trans _ hs) (le_trans _ ht)).trans_le h;
exact mul_le_mul_of_nonneg_left h (nat.cast_nonneg _)
lemma is_uniform.symm : symmetric (is_uniform G ε) :=
λ s t h t' ht' s' hs' ht hs,
by { rw [edge_density_comm _ t', edge_density_comm _ t], exact h hs' ht' hs ht }
variables (G)
lemma is_uniform_comm : is_uniform G ε s t ↔ is_uniform G ε t s := ⟨λ h, h.symm, λ h, h.symm⟩
lemma is_uniform_singleton (hε : 0 < ε) : G.is_uniform ε {a} {b} :=
begin
intros s' hs' t' ht' hs ht,
rw [card_singleton, nat.cast_one, one_mul] at hs ht,
obtain rfl | rfl := finset.subset_singleton_iff.1 hs',
{ replace hs : ε ≤ 0 := by simpa using hs,
exact (hε.not_le hs).elim },
obtain rfl | rfl := finset.subset_singleton_iff.1 ht',
{ replace ht : ε ≤ 0 := by simpa using ht,
exact (hε.not_le ht).elim },
{ rwa [sub_self, abs_zero] }
end
lemma not_is_uniform_zero : ¬ G.is_uniform (0 : 𝕜) s t :=
λ h, (abs_nonneg _).not_lt $ h (empty_subset _) (empty_subset _) (by simp) (by simp)
lemma is_uniform_one : G.is_uniform (1 : 𝕜) s t :=
begin
intros s' hs' t' ht' hs ht,
rw mul_one at hs ht,
rw [eq_of_subset_of_card_le hs' (nat.cast_le.1 hs),
eq_of_subset_of_card_le ht' (nat.cast_le.1 ht), sub_self, abs_zero],
exact zero_lt_one,
end
variables {G}
lemma not_is_uniform_iff :
¬ G.is_uniform ε s t ↔ ∃ s', s' ⊆ s ∧ ∃ t', t' ⊆ t ∧ ↑s.card * ε ≤ s'.card ∧
↑t.card * ε ≤ t'.card ∧ ε ≤ |G.edge_density s' t' - G.edge_density s t| :=
by { unfold is_uniform, simp only [not_forall, not_lt, exists_prop] }
open_locale classical
variables (G)
/-- An arbitrary pair of subsets witnessing the non-uniformity of `(s, t)`. If `(s, t)` is uniform,
returns `(s, t)`. Witnesses for `(s, t)` and `(t, s)` don't necessarily match. See
`simple_graph.nonuniform_witness`. -/
noncomputable def nonuniform_witnesses (ε : 𝕜) (s t : finset α) : finset α × finset α :=
if h : ¬ G.is_uniform ε s t
then ((not_is_uniform_iff.1 h).some, (not_is_uniform_iff.1 h).some_spec.2.some)
else (s, t)
lemma left_nonuniform_witnesses_subset (h : ¬ G.is_uniform ε s t) :
(G.nonuniform_witnesses ε s t).1 ⊆ s :=
by { rw [nonuniform_witnesses, dif_pos h], exact (not_is_uniform_iff.1 h).some_spec.1 }
lemma left_nonuniform_witnesses_card (h : ¬ G.is_uniform ε s t) :
(s.card : 𝕜) * ε ≤ (G.nonuniform_witnesses ε s t).1.card :=
by { rw [nonuniform_witnesses, dif_pos h],
exact (not_is_uniform_iff.1 h).some_spec.2.some_spec.2.1 }
lemma right_nonuniform_witnesses_subset (h : ¬ G.is_uniform ε s t) :
(G.nonuniform_witnesses ε s t).2 ⊆ t :=
by { rw [nonuniform_witnesses, dif_pos h], exact (not_is_uniform_iff.1 h).some_spec.2.some_spec.1 }
lemma right_nonuniform_witnesses_card (h : ¬ G.is_uniform ε s t) :
(t.card : 𝕜) * ε ≤ (G.nonuniform_witnesses ε s t).2.card :=
by { rw [nonuniform_witnesses, dif_pos h],
exact (not_is_uniform_iff.1 h).some_spec.2.some_spec.2.2.1 }
lemma nonuniform_witnesses_spec (h : ¬ G.is_uniform ε s t) :
ε ≤ |G.edge_density (G.nonuniform_witnesses ε s t).1 (G.nonuniform_witnesses ε s t).2
- G.edge_density s t| :=
by { rw [nonuniform_witnesses, dif_pos h],
exact (not_is_uniform_iff.1 h).some_spec.2.some_spec.2.2.2 }
/-- Arbitrary witness of non-uniformity. `G.nonuniform_witness ε s t` and
`G.nonuniform_witness ε t s` form a pair of subsets witnessing the non-uniformity of `(s, t)`. If
`(s, t)` is uniform, returns `s`. -/
noncomputable def nonuniform_witness (ε : 𝕜) (s t : finset α) : finset α :=
if well_ordering_rel s t then (G.nonuniform_witnesses ε s t).1 else (G.nonuniform_witnesses ε t s).2
lemma nonuniform_witness_subset (h : ¬ G.is_uniform ε s t) : G.nonuniform_witness ε s t ⊆ s :=
begin
unfold nonuniform_witness,
split_ifs,
{ exact G.left_nonuniform_witnesses_subset h },
{ exact G.right_nonuniform_witnesses_subset (λ i, h i.symm) }
end
lemma nonuniform_witness_card_le (h : ¬ G.is_uniform ε s t) :
(s.card : 𝕜) * ε ≤ (G.nonuniform_witness ε s t).card :=
begin
unfold nonuniform_witness,
split_ifs,
{ exact G.left_nonuniform_witnesses_card h },
{ exact G.right_nonuniform_witnesses_card (λ i, h i.symm) }
end
lemma nonuniform_witness_spec (h₁ : s ≠ t) (h₂ : ¬ G.is_uniform ε s t) :
ε ≤ |G.edge_density (G.nonuniform_witness ε s t) (G.nonuniform_witness ε t s)
- G.edge_density s t| :=
begin
unfold nonuniform_witness,
rcases trichotomous_of well_ordering_rel s t with lt | rfl | gt,
{ rw [if_pos lt, if_neg (asymm lt)],
exact G.nonuniform_witnesses_spec h₂ },
{ cases h₁ rfl },
{ rw [if_neg (asymm gt), if_pos gt, edge_density_comm, edge_density_comm _ s],
apply G.nonuniform_witnesses_spec (λ i, h₂ i.symm) }
end
end simple_graph
/-! ### Uniform partitions -/
variables [decidable_eq α] {A : finset α} (P : finpartition A) (G : simple_graph α)
[decidable_rel G.adj] {ε : 𝕜}
namespace finpartition
open_locale classical
/-- The pairs of parts of a partition `P` which are not `ε`-uniform in a graph `G`. Note that we
dismiss the diagonal. We do not care whether `s` is `ε`-uniform with itself. -/
noncomputable def non_uniforms (ε : 𝕜) : finset (finset α × finset α) :=
P.parts.off_diag.filter $ λ uv, ¬G.is_uniform ε uv.1 uv.2
lemma mk_mem_non_uniforms_iff (u v : finset α) (ε : 𝕜) :
(u, v) ∈ P.non_uniforms G ε ↔ u ∈ P.parts ∧ v ∈ P.parts ∧ u ≠ v ∧ ¬G.is_uniform ε u v :=
by rw [non_uniforms, mem_filter, mem_off_diag, and_assoc, and_assoc]
lemma non_uniforms_mono {ε ε' : 𝕜} (h : ε ≤ ε') : P.non_uniforms G ε' ⊆ P.non_uniforms G ε :=
monotone_filter_right _ $ λ uv, mt $ simple_graph.is_uniform.mono h
lemma non_uniforms_bot (hε : 0 < ε) : (⊥ : finpartition A).non_uniforms G ε = ∅ :=
begin
rw eq_empty_iff_forall_not_mem,
rintro ⟨u, v⟩,
simp only [finpartition.mk_mem_non_uniforms_iff, finpartition.parts_bot, mem_map, not_and,
not_not, exists_imp_distrib],
rintro x hx rfl y hy rfl h,
exact G.is_uniform_singleton hε,
end
/-- A finpartition of a graph's vertex set is `ε`-uniform (aka `ε`-regular) iff the proportion of
its pairs of parts that are not `ε`-uniform is at most `ε`. -/
def is_uniform (ε : 𝕜) : Prop :=
((P.non_uniforms G ε).card : 𝕜) ≤ (P.parts.card * (P.parts.card - 1) : ℕ) * ε
lemma bot_is_uniform (hε : 0 < ε) : (⊥ : finpartition A).is_uniform G ε :=
begin
rw [finpartition.is_uniform, finpartition.card_bot, non_uniforms_bot _ hε,
finset.card_empty, nat.cast_zero],
exact mul_nonneg (nat.cast_nonneg _) hε.le,
end
lemma is_uniform_one : P.is_uniform G (1 : 𝕜) :=
begin
rw [is_uniform, mul_one, nat.cast_le],
refine (card_filter_le _ _).trans _,
rw [off_diag_card, nat.mul_sub_left_distrib, mul_one],
end
variables {P G}
lemma is_uniform.mono {ε ε' : 𝕜} (hP : P.is_uniform G ε) (h : ε ≤ ε') : P.is_uniform G ε' :=
((nat.cast_le.2 $ card_le_of_subset $ P.non_uniforms_mono G h).trans hP).trans $
mul_le_mul_of_nonneg_left h $ nat.cast_nonneg _
lemma is_uniform_of_empty (hP : P.parts = ∅) : P.is_uniform G ε :=
by simp [is_uniform, hP, non_uniforms]
lemma nonempty_of_not_uniform (h : ¬ P.is_uniform G ε) : P.parts.nonempty :=
nonempty_of_ne_empty $ λ h₁, h $ is_uniform_of_empty h₁
variables (P G ε) (s : finset α)
/-- A choice of witnesses of non-uniformity among the parts of a finpartition. -/
noncomputable def nonuniform_witnesses : finset (finset α) :=
(P.parts.filter $ λ t, s ≠ t ∧ ¬ G.is_uniform ε s t).image (G.nonuniform_witness ε s)
variables {P G ε s} {t : finset α}
lemma nonuniform_witness_mem_nonuniform_witnesses (h : ¬ G.is_uniform ε s t) (ht : t ∈ P.parts)
(hst : s ≠ t) :
G.nonuniform_witness ε s t ∈ P.nonuniform_witnesses G ε s :=
mem_image_of_mem _ $ mem_filter.2 ⟨ht, hst, h⟩
end finpartition
|
ca41e7dea383d45c1b35bd77ae473cfaea883b9d | 626e312b5c1cb2d88fca108f5933076012633192 | /src/measure_theory/function/l1_space.lean | d933dafa74dcc25ab2880c9eb65b33800a240e26 | [
"Apache-2.0"
] | permissive | Bioye97/mathlib | 9db2f9ee54418d29dd06996279ba9dc874fd6beb | 782a20a27ee83b523f801ff34efb1a9557085019 | refs/heads/master | 1,690,305,956,488 | 1,631,067,774,000 | 1,631,067,774,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 38,604 | lean | /-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import measure_theory.function.lp_space
/-!
# Integrable functions and `L¹` space
In the first part of this file, the predicate `integrable` is defined and basic properties of
integrable functions are proved.
Such a predicate is already available under the name `mem_ℒp 1`. We give a direct definition which
is easier to use, and show that it is equivalent to `mem_ℒp 1`
In the second part, we establish an API between `integrable` and the space `L¹` of equivalence
classes of integrable functions, already defined as a special case of `L^p` spaces for `p = 1`.
## Notation
* `α →₁[μ] β` is the type of `L¹` space, where `α` is a `measure_space` and `β` is a `normed_group`
with a `second_countable_topology`. `f : α →ₘ β` is a "function" in `L¹`. In comments, `[f]` is
also used to denote an `L¹` function.
`₁` can be typed as `\1`.
## Main definitions
* Let `f : α → β` be a function, where `α` is a `measure_space` and `β` a `normed_group`.
Then `has_finite_integral f` means `(∫⁻ a, nnnorm (f a)) < ∞`.
* If `β` is moreover a `measurable_space` then `f` is called `integrable` if
`f` is `measurable` and `has_finite_integral f` holds.
## Implementation notes
To prove something for an arbitrary integrable function, a useful theorem is
`integrable.induction` in the file `set_integral`.
## Tags
integrable, function space, l1
-/
noncomputable theory
open_locale classical topological_space big_operators ennreal measure_theory nnreal
open set filter topological_space ennreal emetric measure_theory
variables {α β γ δ : Type*} {m : measurable_space α} {μ ν : measure α}
variables [normed_group β]
variables [normed_group γ]
namespace measure_theory
/-! ### Some results about the Lebesgue integral involving a normed group -/
lemma lintegral_nnnorm_eq_lintegral_edist (f : α → β) :
∫⁻ a, nnnorm (f a) ∂μ = ∫⁻ a, edist (f a) 0 ∂μ :=
by simp only [edist_eq_coe_nnnorm]
lemma lintegral_norm_eq_lintegral_edist (f : α → β) :
∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ = ∫⁻ a, edist (f a) 0 ∂μ :=
by simp only [of_real_norm_eq_coe_nnnorm, edist_eq_coe_nnnorm]
lemma lintegral_edist_triangle [second_countable_topology β] [measurable_space β]
[opens_measurable_space β] {f g h : α → β}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) (hh : ae_measurable h μ) :
∫⁻ a, edist (f a) (g a) ∂μ ≤ ∫⁻ a, edist (f a) (h a) ∂μ + ∫⁻ a, edist (g a) (h a) ∂μ :=
begin
rw ← lintegral_add' (hf.edist hh) (hg.edist hh),
refine lintegral_mono (λ a, _),
apply edist_triangle_right
end
lemma lintegral_nnnorm_zero : ∫⁻ a : α, nnnorm (0 : β) ∂μ = 0 := by simp
lemma lintegral_nnnorm_add [measurable_space β] [opens_measurable_space β]
[measurable_space γ] [opens_measurable_space γ]
{f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) :
∫⁻ a, nnnorm (f a) + nnnorm (g a) ∂μ = ∫⁻ a, nnnorm (f a) ∂μ + ∫⁻ a, nnnorm (g a) ∂μ :=
lintegral_add' hf.ennnorm hg.ennnorm
lemma lintegral_nnnorm_neg {f : α → β} :
∫⁻ a, nnnorm ((-f) a) ∂μ = ∫⁻ a, nnnorm (f a) ∂μ :=
by simp only [pi.neg_apply, nnnorm_neg]
/-! ### The predicate `has_finite_integral` -/
/-- `has_finite_integral f μ` means that the integral `∫⁻ a, ∥f a∥ ∂μ` is finite.
`has_finite_integral f` means `has_finite_integral f volume`. -/
def has_finite_integral {m : measurable_space α} (f : α → β) (μ : measure α . volume_tac) : Prop :=
∫⁻ a, nnnorm (f a) ∂μ < ∞
lemma has_finite_integral_iff_norm (f : α → β) :
has_finite_integral f μ ↔ ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ < ∞ :=
by simp only [has_finite_integral, of_real_norm_eq_coe_nnnorm]
lemma has_finite_integral_iff_edist (f : α → β) :
has_finite_integral f μ ↔ ∫⁻ a, edist (f a) 0 ∂μ < ∞ :=
by simp only [has_finite_integral_iff_norm, edist_dist, dist_zero_right]
lemma has_finite_integral_iff_of_real {f : α → ℝ} (h : 0 ≤ᵐ[μ] f) :
has_finite_integral f μ ↔ ∫⁻ a, ennreal.of_real (f a) ∂μ < ∞ :=
have lintegral_eq : ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ = ∫⁻ a, ennreal.of_real (f a) ∂μ :=
begin
refine lintegral_congr_ae (h.mono $ λ a h, _),
rwa [real.norm_eq_abs, abs_of_nonneg]
end,
by rw [has_finite_integral_iff_norm, lintegral_eq]
lemma has_finite_integral_iff_of_nnreal {f : α → ℝ≥0} :
has_finite_integral (λ x, (f x : ℝ)) μ ↔ ∫⁻ a, f a ∂μ < ∞ :=
by simp [has_finite_integral_iff_norm]
lemma has_finite_integral.mono {f : α → β} {g : α → γ} (hg : has_finite_integral g μ)
(h : ∀ᵐ a ∂μ, ∥f a∥ ≤ ∥g a∥) : has_finite_integral f μ :=
begin
simp only [has_finite_integral_iff_norm] at *,
calc ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ ≤ ∫⁻ (a : α), (ennreal.of_real ∥g a∥) ∂μ :
lintegral_mono_ae (h.mono $ assume a h, of_real_le_of_real h)
... < ∞ : hg
end
lemma has_finite_integral.mono' {f : α → β} {g : α → ℝ} (hg : has_finite_integral g μ)
(h : ∀ᵐ a ∂μ, ∥f a∥ ≤ g a) : has_finite_integral f μ :=
hg.mono $ h.mono $ λ x hx, le_trans hx (le_abs_self _)
lemma has_finite_integral.congr' {f : α → β} {g : α → γ} (hf : has_finite_integral f μ)
(h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) :
has_finite_integral g μ :=
hf.mono $ eventually_eq.le $ eventually_eq.symm h
lemma has_finite_integral_congr' {f : α → β} {g : α → γ} (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) :
has_finite_integral f μ ↔ has_finite_integral g μ :=
⟨λ hf, hf.congr' h, λ hg, hg.congr' $ eventually_eq.symm h⟩
lemma has_finite_integral.congr {f g : α → β} (hf : has_finite_integral f μ) (h : f =ᵐ[μ] g) :
has_finite_integral g μ :=
hf.congr' $ h.fun_comp norm
lemma has_finite_integral_congr {f g : α → β} (h : f =ᵐ[μ] g) :
has_finite_integral f μ ↔ has_finite_integral g μ :=
has_finite_integral_congr' $ h.fun_comp norm
lemma has_finite_integral_const_iff {c : β} :
has_finite_integral (λ x : α, c) μ ↔ c = 0 ∨ μ univ < ∞ :=
begin
simp only [has_finite_integral, lintegral_const],
by_cases hc : c = 0,
{ simp [hc] },
{ simp only [hc, false_or],
refine ⟨λ h, _, λ h, mul_lt_top coe_lt_top h⟩,
replace h := mul_lt_top (@coe_lt_top $ (nnnorm c)⁻¹) h,
rwa [← mul_assoc, ← coe_mul, _root_.inv_mul_cancel, coe_one, one_mul] at h,
rwa [ne.def, nnnorm_eq_zero] }
end
lemma has_finite_integral_const [is_finite_measure μ] (c : β) :
has_finite_integral (λ x : α, c) μ :=
has_finite_integral_const_iff.2 (or.inr $ measure_lt_top _ _)
lemma has_finite_integral_of_bounded [is_finite_measure μ] {f : α → β} {C : ℝ}
(hC : ∀ᵐ a ∂μ, ∥f a∥ ≤ C) : has_finite_integral f μ :=
(has_finite_integral_const C).mono' hC
lemma has_finite_integral.mono_measure {f : α → β} (h : has_finite_integral f ν) (hμ : μ ≤ ν) :
has_finite_integral f μ :=
lt_of_le_of_lt (lintegral_mono' hμ (le_refl _)) h
lemma has_finite_integral.add_measure {f : α → β} (hμ : has_finite_integral f μ)
(hν : has_finite_integral f ν) : has_finite_integral f (μ + ν) :=
begin
simp only [has_finite_integral, lintegral_add_measure] at *,
exact add_lt_top.2 ⟨hμ, hν⟩
end
lemma has_finite_integral.left_of_add_measure {f : α → β} (h : has_finite_integral f (μ + ν)) :
has_finite_integral f μ :=
h.mono_measure $ measure.le_add_right $ le_refl _
lemma has_finite_integral.right_of_add_measure {f : α → β} (h : has_finite_integral f (μ + ν)) :
has_finite_integral f ν :=
h.mono_measure $ measure.le_add_left $ le_refl _
@[simp] lemma has_finite_integral_add_measure {f : α → β} :
has_finite_integral f (μ + ν) ↔ has_finite_integral f μ ∧ has_finite_integral f ν :=
⟨λ h, ⟨h.left_of_add_measure, h.right_of_add_measure⟩, λ h, h.1.add_measure h.2⟩
lemma has_finite_integral.smul_measure {f : α → β} (h : has_finite_integral f μ) {c : ℝ≥0∞}
(hc : c < ∞) : has_finite_integral f (c • μ) :=
begin
simp only [has_finite_integral, lintegral_smul_measure] at *,
exact mul_lt_top hc h
end
@[simp] lemma has_finite_integral_zero_measure {m : measurable_space α} (f : α → β) :
has_finite_integral f (0 : measure α) :=
by simp only [has_finite_integral, lintegral_zero_measure, with_top.zero_lt_top]
variables (α β μ)
@[simp] lemma has_finite_integral_zero : has_finite_integral (λa:α, (0:β)) μ :=
by simp [has_finite_integral]
variables {α β μ}
lemma has_finite_integral.neg {f : α → β} (hfi : has_finite_integral f μ) :
has_finite_integral (-f) μ :=
by simpa [has_finite_integral] using hfi
@[simp] lemma has_finite_integral_neg_iff {f : α → β} :
has_finite_integral (-f) μ ↔ has_finite_integral f μ :=
⟨λ h, neg_neg f ▸ h.neg, has_finite_integral.neg⟩
lemma has_finite_integral.norm {f : α → β} (hfi : has_finite_integral f μ) :
has_finite_integral (λa, ∥f a∥) μ :=
have eq : (λa, (nnnorm ∥f a∥ : ℝ≥0∞)) = λa, (nnnorm (f a) : ℝ≥0∞),
by { funext, rw nnnorm_norm },
by { rwa [has_finite_integral, eq] }
lemma has_finite_integral_norm_iff (f : α → β) :
has_finite_integral (λa, ∥f a∥) μ ↔ has_finite_integral f μ :=
has_finite_integral_congr' $ eventually_of_forall $ λ x, norm_norm (f x)
section dominated_convergence
variables {F : ℕ → α → β} {f : α → β} {bound : α → ℝ}
lemma all_ae_of_real_F_le_bound (h : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) :
∀ n, ∀ᵐ a ∂μ, ennreal.of_real ∥F n a∥ ≤ ennreal.of_real (bound a) :=
λn, (h n).mono $ λ a h, ennreal.of_real_le_of_real h
lemma all_ae_tendsto_of_real_norm (h : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top $ 𝓝 $ f a) :
∀ᵐ a ∂μ, tendsto (λn, ennreal.of_real ∥F n a∥) at_top $ 𝓝 $ ennreal.of_real ∥f a∥ :=
h.mono $
λ a h, tendsto_of_real $ tendsto.comp (continuous.tendsto continuous_norm _) h
lemma all_ae_of_real_f_le_bound (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) :
∀ᵐ a ∂μ, ennreal.of_real ∥f a∥ ≤ ennreal.of_real (bound a) :=
begin
have F_le_bound := all_ae_of_real_F_le_bound h_bound,
rw ← ae_all_iff at F_le_bound,
apply F_le_bound.mp ((all_ae_tendsto_of_real_norm h_lim).mono _),
assume a tendsto_norm F_le_bound,
exact le_of_tendsto' tendsto_norm (F_le_bound)
end
lemma has_finite_integral_of_dominated_convergence {F : ℕ → α → β} {f : α → β} {bound : α → ℝ}
(bound_has_finite_integral : has_finite_integral bound μ)
(h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) :
has_finite_integral f μ :=
/- `∥F n a∥ ≤ bound a` and `∥F n a∥ --> ∥f a∥` implies `∥f a∥ ≤ bound a`,
and so `∫ ∥f∥ ≤ ∫ bound < ∞` since `bound` is has_finite_integral -/
begin
rw has_finite_integral_iff_norm,
calc ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ ≤ ∫⁻ a, ennreal.of_real (bound a) ∂μ :
lintegral_mono_ae $ all_ae_of_real_f_le_bound h_bound h_lim
... < ∞ :
begin
rw ← has_finite_integral_iff_of_real,
{ exact bound_has_finite_integral },
exact (h_bound 0).mono (λ a h, le_trans (norm_nonneg _) h)
end
end
lemma tendsto_lintegral_norm_of_dominated_convergence [measurable_space β]
[borel_space β] [second_countable_topology β]
{F : ℕ → α → β} {f : α → β} {bound : α → ℝ}
(F_measurable : ∀ n, ae_measurable (F n) μ)
(f_measurable : ae_measurable f μ)
(bound_has_finite_integral : has_finite_integral bound μ)
(h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) :
tendsto (λn, ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 0) :=
let b := λa, 2 * ennreal.of_real (bound a) in
/- `∥F n a∥ ≤ bound a` and `F n a --> f a` implies `∥f a∥ ≤ bound a`, and thus by the
triangle inequality, have `∥F n a - f a∥ ≤ 2 * (bound a). -/
have hb : ∀ n, ∀ᵐ a ∂μ, ennreal.of_real ∥F n a - f a∥ ≤ b a,
begin
assume n,
filter_upwards [all_ae_of_real_F_le_bound h_bound n, all_ae_of_real_f_le_bound h_bound h_lim],
assume a h₁ h₂,
calc ennreal.of_real ∥F n a - f a∥ ≤ (ennreal.of_real ∥F n a∥) + (ennreal.of_real ∥f a∥) :
begin
rw [← ennreal.of_real_add],
apply of_real_le_of_real,
{ apply norm_sub_le }, { exact norm_nonneg _ }, { exact norm_nonneg _ }
end
... ≤ (ennreal.of_real (bound a)) + (ennreal.of_real (bound a)) : add_le_add h₁ h₂
... = b a : by rw ← two_mul
end,
/- On the other hand, `F n a --> f a` implies that `∥F n a - f a∥ --> 0` -/
have h : ∀ᵐ a ∂μ, tendsto (λ n, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0),
begin
rw ← ennreal.of_real_zero,
refine h_lim.mono (λ a h, (continuous_of_real.tendsto _).comp _),
rwa ← tendsto_iff_norm_tendsto_zero
end,
/- Therefore, by the dominated convergence theorem for nonnegative integration, have
` ∫ ∥f a - F n a∥ --> 0 ` -/
begin
suffices h : tendsto (λn, ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 (∫⁻ (a:α), 0 ∂μ)),
{ rwa lintegral_zero at h },
-- Using the dominated convergence theorem.
refine tendsto_lintegral_of_dominated_convergence' _ _ hb _ _,
-- Show `λa, ∥f a - F n a∥` is almost everywhere measurable for all `n`
{ exact λn, measurable_of_real.comp_ae_measurable ((F_measurable n).sub f_measurable).norm },
-- Show `2 * bound` is has_finite_integral
{ rw has_finite_integral_iff_of_real at bound_has_finite_integral,
{ calc ∫⁻ a, b a ∂μ = 2 * ∫⁻ a, ennreal.of_real (bound a) ∂μ :
by { rw lintegral_const_mul', exact coe_ne_top }
... < ∞ : mul_lt_top (coe_lt_top) bound_has_finite_integral },
filter_upwards [h_bound 0] λ a h, le_trans (norm_nonneg _) h },
-- Show `∥f a - F n a∥ --> 0`
{ exact h }
end
end dominated_convergence
section pos_part
/-! Lemmas used for defining the positive part of a `L¹` function -/
lemma has_finite_integral.max_zero {f : α → ℝ} (hf : has_finite_integral f μ) :
has_finite_integral (λa, max (f a) 0) μ :=
hf.mono $ eventually_of_forall $ λ x, by simp [real.norm_eq_abs, abs_le, abs_nonneg, le_abs_self]
lemma has_finite_integral.min_zero {f : α → ℝ} (hf : has_finite_integral f μ) :
has_finite_integral (λa, min (f a) 0) μ :=
hf.mono $ eventually_of_forall $ λ x,
by simp [real.norm_eq_abs, abs_le, abs_nonneg, neg_le, neg_le_abs_self]
end pos_part
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β]
lemma has_finite_integral.smul (c : 𝕜) {f : α → β} : has_finite_integral f μ →
has_finite_integral (c • f) μ :=
begin
simp only [has_finite_integral], assume hfi,
calc
∫⁻ (a : α), nnnorm (c • f a) ∂μ = ∫⁻ (a : α), (nnnorm c) * nnnorm (f a) ∂μ :
by simp only [nnnorm_smul, ennreal.coe_mul]
... < ∞ :
begin
rw lintegral_const_mul',
exacts [mul_lt_top coe_lt_top hfi, coe_ne_top]
end
end
lemma has_finite_integral_smul_iff {c : 𝕜} (hc : c ≠ 0) (f : α → β) :
has_finite_integral (c • f) μ ↔ has_finite_integral f μ :=
begin
split,
{ assume h,
simpa only [smul_smul, inv_mul_cancel hc, one_smul] using h.smul c⁻¹ },
exact has_finite_integral.smul _
end
lemma has_finite_integral.const_mul {f : α → ℝ} (h : has_finite_integral f μ) (c : ℝ) :
has_finite_integral (λ x, c * f x) μ :=
(has_finite_integral.smul c h : _)
lemma has_finite_integral.mul_const {f : α → ℝ} (h : has_finite_integral f μ) (c : ℝ) :
has_finite_integral (λ x, f x * c) μ :=
by simp_rw [mul_comm, h.const_mul _]
end normed_space
/-! ### The predicate `integrable` -/
variables [measurable_space β] [measurable_space γ] [measurable_space δ]
/-- `integrable f μ` means that `f` is measurable and that the integral `∫⁻ a, ∥f a∥ ∂μ` is finite.
`integrable f` means `integrable f volume`. -/
def integrable {α} {m : measurable_space α} (f : α → β) (μ : measure α . volume_tac) : Prop :=
ae_measurable f μ ∧ has_finite_integral f μ
lemma integrable.ae_measurable {f : α → β} (hf : integrable f μ) : ae_measurable f μ := hf.1
lemma integrable.has_finite_integral {f : α → β} (hf : integrable f μ) : has_finite_integral f μ :=
hf.2
lemma integrable.mono {f : α → β} {g : α → γ} (hg : integrable g μ) (hf : ae_measurable f μ)
(h : ∀ᵐ a ∂μ, ∥f a∥ ≤ ∥g a∥) : integrable f μ :=
⟨hf, hg.has_finite_integral.mono h⟩
lemma integrable.mono' {f : α → β} {g : α → ℝ} (hg : integrable g μ) (hf : ae_measurable f μ)
(h : ∀ᵐ a ∂μ, ∥f a∥ ≤ g a) : integrable f μ :=
⟨hf, hg.has_finite_integral.mono' h⟩
lemma integrable.congr' {f : α → β} {g : α → γ} (hf : integrable f μ) (hg : ae_measurable g μ)
(h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : integrable g μ :=
⟨hg, hf.has_finite_integral.congr' h⟩
lemma integrable_congr' {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ)
(h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : integrable f μ ↔ integrable g μ :=
⟨λ h2f, h2f.congr' hg h, λ h2g, h2g.congr' hf $ eventually_eq.symm h⟩
lemma integrable.congr {f g : α → β} (hf : integrable f μ) (h : f =ᵐ[μ] g) :
integrable g μ :=
⟨hf.1.congr h, hf.2.congr h⟩
lemma integrable_congr {f g : α → β} (h : f =ᵐ[μ] g) :
integrable f μ ↔ integrable g μ :=
⟨λ hf, hf.congr h, λ hg, hg.congr h.symm⟩
lemma integrable_const_iff {c : β} : integrable (λ x : α, c) μ ↔ c = 0 ∨ μ univ < ∞ :=
begin
have : ae_measurable (λ (x : α), c) μ := measurable_const.ae_measurable,
rw [integrable, and_iff_right this, has_finite_integral_const_iff]
end
lemma integrable_const [is_finite_measure μ] (c : β) : integrable (λ x : α, c) μ :=
integrable_const_iff.2 $ or.inr $ measure_lt_top _ _
lemma integrable.mono_measure {f : α → β} (h : integrable f ν) (hμ : μ ≤ ν) : integrable f μ :=
⟨h.ae_measurable.mono_measure hμ, h.has_finite_integral.mono_measure hμ⟩
lemma integrable.add_measure {f : α → β} (hμ : integrable f μ) (hν : integrable f ν) :
integrable f (μ + ν) :=
⟨hμ.ae_measurable.add_measure hν.ae_measurable,
hμ.has_finite_integral.add_measure hν.has_finite_integral⟩
lemma integrable.left_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f μ :=
h.mono_measure $ measure.le_add_right $ le_refl _
lemma integrable.right_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f ν :=
h.mono_measure $ measure.le_add_left $ le_refl _
@[simp] lemma integrable_add_measure {f : α → β} :
integrable f (μ + ν) ↔ integrable f μ ∧ integrable f ν :=
⟨λ h, ⟨h.left_of_add_measure, h.right_of_add_measure⟩, λ h, h.1.add_measure h.2⟩
lemma integrable.smul_measure {f : α → β} (h : integrable f μ) {c : ℝ≥0∞} (hc : c < ∞) :
integrable f (c • μ) :=
⟨h.ae_measurable.smul_measure c, h.has_finite_integral.smul_measure hc⟩
lemma integrable_map_measure [opens_measurable_space β] {f : α → δ} {g : δ → β}
(hg : ae_measurable g (measure.map f μ)) (hf : measurable f) :
integrable g (measure.map f μ) ↔ integrable (g ∘ f) μ :=
by simp [integrable, hg, hg.comp_measurable hf, has_finite_integral, lintegral_map' hg.ennnorm hf]
lemma lintegral_edist_lt_top [second_countable_topology β] [opens_measurable_space β] {f g : α → β}
(hf : integrable f μ) (hg : integrable g μ) :
∫⁻ a, edist (f a) (g a) ∂μ < ∞ :=
lt_of_le_of_lt
(lintegral_edist_triangle hf.ae_measurable hg.ae_measurable
(measurable_const.ae_measurable : ae_measurable (λa, (0 : β)) μ))
(ennreal.add_lt_top.2 $ by { simp_rw ← has_finite_integral_iff_edist,
exact ⟨hf.has_finite_integral, hg.has_finite_integral⟩ })
variables (α β μ)
@[simp] lemma integrable_zero : integrable (λ _, (0 : β)) μ :=
by simp [integrable, measurable_const.ae_measurable]
variables {α β μ}
lemma integrable.add' [opens_measurable_space β] {f g : α → β} (hf : integrable f μ)
(hg : integrable g μ) :
has_finite_integral (f + g) μ :=
calc ∫⁻ a, nnnorm (f a + g a) ∂μ ≤ ∫⁻ a, nnnorm (f a) + nnnorm (g a) ∂μ :
lintegral_mono (λ a, by exact_mod_cast nnnorm_add_le _ _)
... = _ : lintegral_nnnorm_add hf.ae_measurable hg.ae_measurable
... < ∞ : add_lt_top.2 ⟨hf.has_finite_integral, hg.has_finite_integral⟩
lemma integrable.add [borel_space β] [second_countable_topology β]
{f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : integrable (f + g) μ :=
⟨hf.ae_measurable.add hg.ae_measurable, hf.add' hg⟩
lemma integrable_finset_sum {ι} [borel_space β] [second_countable_topology β] (s : finset ι)
{f : ι → α → β} (hf : ∀ i, integrable (f i) μ) : integrable (λ a, ∑ i in s, f i a) μ :=
begin
refine finset.induction_on s _ _,
{ simp only [finset.sum_empty, integrable_zero] },
{ assume i s his ih, simp only [his, finset.sum_insert, not_false_iff],
exact (hf _).add ih }
end
lemma integrable.neg [borel_space β] {f : α → β} (hf : integrable f μ) : integrable (-f) μ :=
⟨hf.ae_measurable.neg, hf.has_finite_integral.neg⟩
@[simp] lemma integrable_neg_iff [borel_space β] {f : α → β} :
integrable (-f) μ ↔ integrable f μ :=
⟨λ h, neg_neg f ▸ h.neg, integrable.neg⟩
lemma integrable.sub' [opens_measurable_space β] {f g : α → β}
(hf : integrable f μ) (hg : integrable g μ) : has_finite_integral (f - g) μ :=
calc ∫⁻ a, nnnorm (f a - g a) ∂μ ≤ ∫⁻ a, nnnorm (f a) + nnnorm (-g a) ∂μ :
lintegral_mono (assume a, by { simp only [sub_eq_add_neg], exact_mod_cast nnnorm_add_le _ _ } )
... = _ :
by { simp only [nnnorm_neg], exact lintegral_nnnorm_add hf.ae_measurable hg.ae_measurable }
... < ∞ : add_lt_top.2 ⟨hf.has_finite_integral, hg.has_finite_integral⟩
lemma integrable.sub [borel_space β] [second_countable_topology β] {f g : α → β}
(hf : integrable f μ) (hg : integrable g μ) : integrable (f - g) μ :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
lemma integrable.norm [opens_measurable_space β] {f : α → β} (hf : integrable f μ) :
integrable (λa, ∥f a∥) μ :=
⟨hf.ae_measurable.norm, hf.has_finite_integral.norm⟩
lemma integrable_norm_iff [opens_measurable_space β] {f : α → β} (hf : ae_measurable f μ) :
integrable (λa, ∥f a∥) μ ↔ integrable f μ :=
by simp_rw [integrable, and_iff_right hf, and_iff_right hf.norm, has_finite_integral_norm_iff]
lemma integrable_of_norm_sub_le [opens_measurable_space β] {f₀ f₁ : α → β} {g : α → ℝ}
(hf₁_m : ae_measurable f₁ μ)
(hf₀_i : integrable f₀ μ)
(hg_i : integrable g μ)
(h : ∀ᵐ a ∂μ, ∥f₀ a - f₁ a∥ ≤ g a) :
integrable f₁ μ :=
begin
have : ∀ᵐ a ∂μ, ∥f₁ a∥ ≤ ∥f₀ a∥ + g a,
{ apply h.mono,
intros a ha,
calc ∥f₁ a∥ ≤ ∥f₀ a∥ + ∥f₀ a - f₁ a∥ : norm_le_insert _ _
... ≤ ∥f₀ a∥ + g a : add_le_add_left ha _ },
exact integrable.mono' (hf₀_i.norm.add hg_i) hf₁_m this
end
lemma integrable.prod_mk [opens_measurable_space β] [opens_measurable_space γ] {f : α → β}
{g : α → γ} (hf : integrable f μ) (hg : integrable g μ) :
integrable (λ x, (f x, g x)) μ :=
⟨hf.ae_measurable.prod_mk hg.ae_measurable,
(hf.norm.add' hg.norm).mono $ eventually_of_forall $ λ x,
calc max ∥f x∥ ∥g x∥ ≤ ∥f x∥ + ∥g x∥ : max_le_add_of_nonneg (norm_nonneg _) (norm_nonneg _)
... ≤ ∥(∥f x∥ + ∥g x∥)∥ : le_abs_self _⟩
lemma mem_ℒp_one_iff_integrable {f : α → β} : mem_ℒp f 1 μ ↔ integrable f μ :=
by simp_rw [integrable, has_finite_integral, mem_ℒp, snorm_one_eq_lintegral_nnnorm]
lemma mem_ℒp.integrable [borel_space β] {q : ℝ≥0∞} (hq1 : 1 ≤ q) {f : α → β} [is_finite_measure μ]
(hfq : mem_ℒp f q μ) : integrable f μ :=
mem_ℒp_one_iff_integrable.mp (hfq.mem_ℒp_of_exponent_le hq1)
lemma lipschitz_with.integrable_comp_iff_of_antilipschitz [complete_space β] [borel_space β]
[borel_space γ] {K K'} {f : α → β} {g : β → γ} (hg : lipschitz_with K g)
(hg' : antilipschitz_with K' g) (g0 : g 0 = 0) :
integrable (g ∘ f) μ ↔ integrable f μ :=
by simp [← mem_ℒp_one_iff_integrable, hg.mem_ℒp_comp_iff_of_antilipschitz hg' g0]
lemma integrable.real_to_nnreal {f : α → ℝ} (hf : integrable f μ) :
integrable (λ x, ((f x).to_nnreal : ℝ)) μ :=
begin
refine ⟨hf.ae_measurable.real_to_nnreal.coe_nnreal_real, _⟩,
rw has_finite_integral_iff_norm,
refine lt_of_le_of_lt _ ((has_finite_integral_iff_norm _).1 hf.has_finite_integral),
apply lintegral_mono,
assume x,
simp [real.norm_eq_abs, ennreal.of_real_le_of_real, abs_le, abs_nonneg, le_abs_self],
end
section pos_part
/-! ### Lemmas used for defining the positive part of a `L¹` function -/
lemma integrable.max_zero {f : α → ℝ} (hf : integrable f μ) : integrable (λa, max (f a) 0) μ :=
⟨hf.ae_measurable.max measurable_const.ae_measurable, hf.has_finite_integral.max_zero⟩
lemma integrable.min_zero {f : α → ℝ} (hf : integrable f μ) : integrable (λa, min (f a) 0) μ :=
⟨hf.ae_measurable.min measurable_const.ae_measurable, hf.has_finite_integral.min_zero⟩
end pos_part
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] [measurable_space 𝕜]
[opens_measurable_space 𝕜]
lemma integrable.smul [borel_space β] (c : 𝕜) {f : α → β}
(hf : integrable f μ) : integrable (c • f) μ :=
⟨hf.ae_measurable.const_smul c, hf.has_finite_integral.smul c⟩
lemma integrable_smul_iff [borel_space β] {c : 𝕜} (hc : c ≠ 0) (f : α → β) :
integrable (c • f) μ ↔ integrable f μ :=
and_congr (ae_measurable_const_smul_iff' hc) (has_finite_integral_smul_iff hc f)
lemma integrable.const_mul {f : α → ℝ} (h : integrable f μ) (c : ℝ) :
integrable (λ x, c * f x) μ :=
integrable.smul c h
lemma integrable.mul_const {f : α → ℝ} (h : integrable f μ) (c : ℝ) :
integrable (λ x, f x * c) μ :=
by simp_rw [mul_comm, h.const_mul _]
end normed_space
section normed_space_over_complete_field
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [complete_space 𝕜] [measurable_space 𝕜]
variables [borel_space 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E]
lemma integrable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) :
integrable (λ x, f x • c) μ ↔ integrable f μ :=
begin
simp_rw [integrable, ae_measurable_smul_const hc, and.congr_right_iff, has_finite_integral,
nnnorm_smul, ennreal.coe_mul],
intro hf, rw [lintegral_mul_const' _ _ ennreal.coe_ne_top, ennreal.mul_lt_top_iff],
have : ∀ x : ℝ≥0∞, x = 0 → x < ∞ := by simp,
simp [hc, or_iff_left_of_imp (this _)]
end
end normed_space_over_complete_field
section is_R_or_C
variables {𝕜 : Type*} [is_R_or_C 𝕜] [measurable_space 𝕜] [opens_measurable_space 𝕜] {f : α → 𝕜}
lemma integrable.re (hf : integrable f μ) : integrable (λ x, is_R_or_C.re (f x)) μ :=
by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.re, }
lemma integrable.im (hf : integrable f μ) : integrable (λ x, is_R_or_C.im (f x)) μ :=
by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.im, }
end is_R_or_C
section inner_product
variables {𝕜 E : Type*} [is_R_or_C 𝕜] [measurable_space 𝕜] [borel_space 𝕜]
[inner_product_space 𝕜 E]
[measurable_space E] [opens_measurable_space E] [second_countable_topology E]
{f : α → E}
local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y
lemma integrable.const_inner (c : E) (hf : integrable f μ) : integrable (λ x, ⟪c, f x⟫) μ :=
by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.const_inner c, }
lemma integrable.inner_const (hf : integrable f μ) (c : E) : integrable (λ x, ⟪f x, c⟫) μ :=
by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.inner_const c, }
end inner_product
section trim
variables {H : Type*} [normed_group H] [measurable_space H] [opens_measurable_space H]
{m0 : measurable_space α} {μ' : measure α} {f : α → H}
lemma integrable.trim (hm : m ≤ m0) (hf_int : integrable f μ') (hf : @measurable _ _ m _ f) :
integrable f (μ'.trim hm) :=
begin
refine ⟨measurable.ae_measurable hf, _⟩,
rw [has_finite_integral, lintegral_trim hm _],
{ exact hf_int.2, },
{ exact @measurable.coe_nnreal_ennreal α m _ (@measurable.nnnorm _ α _ _ _ m _ hf), },
end
lemma integrable_of_integrable_trim (hm : m ≤ m0) (hf_int : integrable f (μ'.trim hm)) :
integrable f μ' :=
begin
obtain ⟨hf_meas_ae, hf⟩ := hf_int,
refine ⟨ae_measurable_of_ae_measurable_trim hm hf_meas_ae, _⟩,
rw has_finite_integral at hf ⊢,
rwa lintegral_trim_ae hm _ at hf,
exact @ae_measurable.coe_nnreal_ennreal α m _ _
(@ae_measurable.nnnorm H α _ _ _ m _ _ hf_meas_ae),
end
end trim
section sigma_finite
variables {E : Type*} {m0 : measurable_space α} [normed_group E] [measurable_space E]
[opens_measurable_space E]
lemma integrable_of_forall_fin_meas_le' {μ : measure α} (hm : m ≤ m0)
[sigma_finite (μ.trim hm)] (C : ℝ≥0∞) (hC : C < ∞) {f : α → E} (hf_meas : ae_measurable f μ)
(hf : ∀ s, measurable_set[m] s → μ s ≠ ∞ → ∫⁻ x in s, nnnorm (f x) ∂μ ≤ C) :
integrable f μ :=
⟨hf_meas,
(lintegral_le_of_forall_fin_meas_le' hm C hf_meas.nnnorm.coe_nnreal_ennreal hf).trans_lt hC⟩
lemma integrable_of_forall_fin_meas_le [sigma_finite μ]
(C : ℝ≥0∞) (hC : C < ∞) {f : α → E} (hf_meas : ae_measurable f μ)
(hf : ∀ s : set α, measurable_set s → μ s ≠ ∞ → ∫⁻ x in s, nnnorm (f x) ∂μ ≤ C) :
integrable f μ :=
@integrable_of_forall_fin_meas_le' _ _ _ _ _ _ _ _ le_rfl (by rwa trim_eq_self) C hC _ hf_meas hf
end sigma_finite
/-! ### The predicate `integrable` on measurable functions modulo a.e.-equality -/
namespace ae_eq_fun
section
/-- A class of almost everywhere equal functions is `integrable` if its function representative
is integrable. -/
def integrable (f : α →ₘ[μ] β) : Prop := integrable f μ
lemma integrable_mk {f : α → β} (hf : ae_measurable f μ ) :
(integrable (mk f hf : α →ₘ[μ] β)) ↔ measure_theory.integrable f μ :=
begin
simp [integrable],
apply integrable_congr,
exact coe_fn_mk f hf
end
lemma integrable_coe_fn {f : α →ₘ[μ] β} : (measure_theory.integrable f μ) ↔ integrable f :=
by rw [← integrable_mk, mk_coe_fn]
lemma integrable_zero : integrable (0 : α →ₘ[μ] β) :=
(integrable_zero α β μ).congr (coe_fn_mk _ _).symm
end
section
variables [borel_space β]
lemma integrable.neg {f : α →ₘ[μ] β} : integrable f → integrable (-f) :=
induction_on f $ λ f hfm hfi, (integrable_mk _).2 ((integrable_mk hfm).1 hfi).neg
section
variable [second_countable_topology β]
lemma integrable_iff_mem_L1 {f : α →ₘ[μ] β} : integrable f ↔ f ∈ (α →₁[μ] β) :=
by rw [← integrable_coe_fn, ← mem_ℒp_one_iff_integrable, Lp.mem_Lp_iff_mem_ℒp]
lemma integrable.add {f g : α →ₘ[μ] β} : integrable f → integrable g → integrable (f + g) :=
begin
refine induction_on₂ f g (λ f hf g hg hfi hgi, _),
simp only [integrable_mk, mk_add_mk] at hfi hgi ⊢,
exact hfi.add hgi
end
lemma integrable.sub {f g : α →ₘ[μ] β} (hf : integrable f) (hg : integrable g) :
integrable (f - g) :=
(sub_eq_add_neg f g).symm ▸ hf.add hg.neg
end
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] [measurable_space 𝕜]
[opens_measurable_space 𝕜]
lemma integrable.smul {c : 𝕜} {f : α →ₘ[μ] β} : integrable f → integrable (c • f) :=
induction_on f $ λ f hfm hfi, (integrable_mk _).2 $ ((integrable_mk hfm).1 hfi).smul _
end normed_space
end
end ae_eq_fun
namespace L1
variables [second_countable_topology β] [borel_space β]
lemma integrable_coe_fn (f : α →₁[μ] β) :
integrable f μ :=
by { rw ← mem_ℒp_one_iff_integrable, exact Lp.mem_ℒp f }
lemma has_finite_integral_coe_fn (f : α →₁[μ] β) :
has_finite_integral f μ :=
(integrable_coe_fn f).has_finite_integral
lemma measurable_coe_fn (f : α →₁[μ] β) :
measurable f := Lp.measurable f
lemma ae_measurable_coe_fn (f : α →₁[μ] β) :
ae_measurable f μ := Lp.ae_measurable f
lemma edist_def (f g : α →₁[μ] β) :
edist f g = ∫⁻ a, edist (f a) (g a) ∂μ :=
by { simp [Lp.edist_def, snorm, snorm'], simp [edist_eq_coe_nnnorm_sub] }
lemma dist_def (f g : α →₁[μ] β) :
dist f g = (∫⁻ a, edist (f a) (g a) ∂μ).to_real :=
by { simp [Lp.dist_def, snorm, snorm'], simp [edist_eq_coe_nnnorm_sub] }
lemma norm_def (f : α →₁[μ] β) :
∥f∥ = (∫⁻ a, nnnorm (f a) ∂μ).to_real :=
by { simp [Lp.norm_def, snorm, snorm'] }
/-- Computing the norm of a difference between two L¹-functions. Note that this is not a
special case of `norm_def` since `(f - g) x` and `f x - g x` are not equal
(but only a.e.-equal). -/
lemma norm_sub_eq_lintegral (f g : α →₁[μ] β) :
∥f - g∥ = (∫⁻ x, (nnnorm (f x - g x) : ℝ≥0∞) ∂μ).to_real :=
begin
rw [norm_def],
congr' 1,
rw lintegral_congr_ae,
filter_upwards [Lp.coe_fn_sub f g],
assume a ha,
simp only [ha, pi.sub_apply],
end
lemma of_real_norm_eq_lintegral (f : α →₁[μ] β) :
ennreal.of_real ∥f∥ = ∫⁻ x, (nnnorm (f x) : ℝ≥0∞) ∂μ :=
by { rw [norm_def, ennreal.of_real_to_real], rw [← ennreal.lt_top_iff_ne_top],
exact has_finite_integral_coe_fn f }
/-- Computing the norm of a difference between two L¹-functions. Note that this is not a
special case of `of_real_norm_eq_lintegral` since `(f - g) x` and `f x - g x` are not equal
(but only a.e.-equal). -/
lemma of_real_norm_sub_eq_lintegral (f g : α →₁[μ] β) :
ennreal.of_real ∥f - g∥ = ∫⁻ x, (nnnorm (f x - g x) : ℝ≥0∞) ∂μ :=
begin
simp_rw [of_real_norm_eq_lintegral, ← edist_eq_coe_nnnorm],
apply lintegral_congr_ae,
filter_upwards [Lp.coe_fn_sub f g],
assume a ha,
simp only [ha, pi.sub_apply],
end
end L1
namespace integrable
variables [second_countable_topology β] [borel_space β]
/-- Construct the equivalence class `[f]` of an integrable function `f`, as a member of the
space `L1 β 1 μ`. -/
def to_L1 (f : α → β) (hf : integrable f μ) : α →₁[μ] β :=
(mem_ℒp_one_iff_integrable.2 hf).to_Lp f
@[simp] lemma to_L1_coe_fn (f : α →₁[μ] β) (hf : integrable f μ) : hf.to_L1 f = f :=
by simp [integrable.to_L1]
lemma coe_fn_to_L1 {f : α → β} (hf : integrable f μ) : hf.to_L1 f =ᵐ[μ] f :=
ae_eq_fun.coe_fn_mk _ _
@[simp] lemma to_L1_zero (h : integrable (0 : α → β) μ) : h.to_L1 0 = 0 := rfl
@[simp] lemma to_L1_eq_mk (f : α → β) (hf : integrable f μ) :
(hf.to_L1 f : α →ₘ[μ] β) = ae_eq_fun.mk f hf.ae_measurable :=
rfl
@[simp] lemma to_L1_eq_to_L1_iff (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) :
to_L1 f hf = to_L1 g hg ↔ f =ᵐ[μ] g :=
mem_ℒp.to_Lp_eq_to_Lp_iff _ _
lemma to_L1_add (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) :
to_L1 (f + g) (hf.add hg) = to_L1 f hf + to_L1 g hg := rfl
lemma to_L1_neg (f : α → β) (hf : integrable f μ) :
to_L1 (- f) (integrable.neg hf) = - to_L1 f hf := rfl
lemma to_L1_sub (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) :
to_L1 (f - g) (hf.sub hg) = to_L1 f hf - to_L1 g hg := rfl
lemma norm_to_L1 (f : α → β) (hf : integrable f μ) :
∥hf.to_L1 f∥ = ennreal.to_real (∫⁻ a, edist (f a) 0 ∂μ) :=
by { simp [to_L1, snorm, snorm'], simp [edist_eq_coe_nnnorm] }
lemma norm_to_L1_eq_lintegral_norm (f : α → β) (hf : integrable f μ) :
∥hf.to_L1 f∥ = ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) :=
by { rw [norm_to_L1, lintegral_norm_eq_lintegral_edist] }
@[simp] lemma edist_to_L1_to_L1 (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) :
edist (hf.to_L1 f) (hg.to_L1 g) = ∫⁻ a, edist (f a) (g a) ∂μ :=
by { simp [integrable.to_L1, snorm, snorm'], simp [edist_eq_coe_nnnorm_sub] }
@[simp] lemma edist_to_L1_zero (f : α → β) (hf : integrable f μ) :
edist (hf.to_L1 f) 0 = ∫⁻ a, edist (f a) 0 ∂μ :=
by { simp [integrable.to_L1, snorm, snorm'], simp [edist_eq_coe_nnnorm] }
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] [measurable_space 𝕜]
[opens_measurable_space 𝕜]
lemma to_L1_smul (f : α → β) (hf : integrable f μ) (k : 𝕜) :
to_L1 (λa, k • f a) (hf.smul k) = k • to_L1 f hf := rfl
end integrable
end measure_theory
open measure_theory
lemma integrable_zero_measure {m : measurable_space α} [measurable_space β] {f : α → β} :
integrable f (0 : measure α) :=
begin
apply (integrable_zero _ _ _).congr,
change (0 : measure α) {x | 0 ≠ f x} = 0,
refl,
end
variables {E : Type*} [normed_group E] [measurable_space E] [borel_space E] [normed_space ℝ E]
{H : Type*} [normed_group H] [normed_space ℝ H]
lemma measure_theory.integrable.apply_continuous_linear_map {φ : α → H →L[ℝ] E}
(φ_int : integrable φ μ) (v : H) : integrable (λ a, φ a v) μ :=
(φ_int.norm.mul_const ∥v∥).mono' (φ_int.ae_measurable.apply_continuous_linear_map v)
(eventually_of_forall $ λ a, (φ a).le_op_norm v)
variables {𝕜 : Type*} [is_R_or_C 𝕜]
{G : Type*} [normed_group G] [normed_space 𝕜 G] [measurable_space G] [borel_space G]
{F : Type*} [normed_group F] [normed_space 𝕜 F] [measurable_space F] [opens_measurable_space F]
lemma continuous_linear_map.integrable_comp {φ : α → F} (L : F →L[𝕜] G)
(φ_int : integrable φ μ) : integrable (λ (a : α), L (φ a)) μ :=
((integrable.norm φ_int).const_mul ∥L∥).mono' (L.measurable.comp_ae_measurable φ_int.ae_measurable)
(eventually_of_forall $ λ a, L.le_op_norm (φ a))
|
42131bbe5f2137086b97e4b999ebda8d226480ea | bb31430994044506fa42fd667e2d556327e18dfe | /src/linear_algebra/dual.lean | 425bd69a89e60adfbdd38879eb0ddb017513dc3a | [
"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 | 35,477 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Fabian Glöckle
-/
import linear_algebra.finite_dimensional
import linear_algebra.projection
import linear_algebra.sesquilinear_form
import ring_theory.finiteness
import linear_algebra.free_module.finite.basic
/-!
# Dual vector spaces
The dual space of an R-module M is the R-module of linear maps `M → R`.
## Main definitions
* `dual R M` defines the dual space of M over R.
* Given a basis for an `R`-module `M`, `basis.to_dual` produces a map from `M` to `dual R M`.
* Given families of vectors `e` and `ε`, `module.dual_bases e ε` states that these families have the
characteristic properties of a basis and a dual.
* `dual_annihilator W` is the submodule of `dual R M` where every element annihilates `W`.
## Main results
* `to_dual_equiv` : the linear equivalence between the dual module and primal module,
given a finite basis.
* `module.dual_bases.basis` and `module.dual_bases.eq_dual`: if `e` and `ε` form a dual pair, `e`
is a basis and `ε` is its dual basis.
* `quot_equiv_annihilator`: the quotient by a subspace is isomorphic to its dual annihilator.
## Notation
We sometimes use `V'` as local notation for `dual K V`.
## TODO
Erdös-Kaplansky theorem about the dimension of a dual vector space in case of infinite dimension.
-/
noncomputable theory
namespace module
variables (R : Type*) (M : Type*)
variables [comm_semiring R] [add_comm_monoid M] [module R M]
/-- The dual space of an R-module M is the R-module of linear maps `M → R`. -/
@[derive [add_comm_monoid, module R]] def dual := M →ₗ[R] R
instance {S : Type*} [comm_ring S] {N : Type*} [add_comm_group N] [module S N] :
add_comm_group (dual S N) := linear_map.add_comm_group
instance : linear_map_class (dual R M) R M R :=
linear_map.semilinear_map_class
/-- The canonical pairing of a vector space and its algebraic dual. -/
def dual_pairing (R M) [comm_semiring R] [add_comm_monoid M] [module R M] :
module.dual R M →ₗ[R] M →ₗ[R] R := linear_map.id
@[simp] lemma dual_pairing_apply (v x) : dual_pairing R M v x = v x := rfl
namespace dual
instance : inhabited (dual R M) := linear_map.inhabited
instance : has_coe_to_fun (dual R M) (λ _, M → R) := ⟨linear_map.to_fun⟩
/-- Maps a module M to the dual of the dual of M. See `module.erange_coe` and
`module.eval_equiv`. -/
def eval : M →ₗ[R] (dual R (dual R M)) := linear_map.flip linear_map.id
@[simp] lemma eval_apply (v : M) (a : dual R M) : eval R M v a = a v :=
begin
dunfold eval,
rw [linear_map.flip_apply, linear_map.id_apply]
end
variables {R M} {M' : Type*} [add_comm_monoid M'] [module R M']
/-- The transposition of linear maps, as a linear map from `M →ₗ[R] M'` to
`dual R M' →ₗ[R] dual R M`. -/
def transpose : (M →ₗ[R] M') →ₗ[R] (dual R M' →ₗ[R] dual R M) :=
(linear_map.llcomp R M M' R).flip
lemma transpose_apply (u : M →ₗ[R] M') (l : dual R M') : transpose u l = l.comp u := rfl
variables {M'' : Type*} [add_comm_monoid M''] [module R M'']
lemma transpose_comp (u : M' →ₗ[R] M'') (v : M →ₗ[R] M') :
transpose (u.comp v) = (transpose v).comp (transpose u) := rfl
end dual
end module
namespace basis
universes u v w
open module module.dual submodule linear_map cardinal function
open_locale big_operators
variables {R M K V ι : Type*}
section comm_semiring
variables [comm_semiring R] [add_comm_monoid M] [module R M] [decidable_eq ι]
variables (b : basis ι R M)
/-- The linear map from a vector space equipped with basis to its dual vector space,
taking basis elements to corresponding dual basis elements. -/
def to_dual : M →ₗ[R] module.dual R M :=
b.constr ℕ $ λ v, b.constr ℕ $ λ w, if w = v then (1 : R) else 0
lemma to_dual_apply (i j : ι) :
b.to_dual (b i) (b j) = if i = j then 1 else 0 :=
by { erw [constr_basis b, constr_basis b], ac_refl }
@[simp] lemma to_dual_total_left (f : ι →₀ R) (i : ι) :
b.to_dual (finsupp.total ι M R b f) (b i) = f i :=
begin
rw [finsupp.total_apply, finsupp.sum, linear_map.map_sum, linear_map.sum_apply],
simp_rw [linear_map.map_smul, linear_map.smul_apply, to_dual_apply, smul_eq_mul,
mul_boole, finset.sum_ite_eq'],
split_ifs with h,
{ refl },
{ rw finsupp.not_mem_support_iff.mp h }
end
@[simp] lemma to_dual_total_right (f : ι →₀ R) (i : ι) :
b.to_dual (b i) (finsupp.total ι M R b f) = f i :=
begin
rw [finsupp.total_apply, finsupp.sum, linear_map.map_sum],
simp_rw [linear_map.map_smul, to_dual_apply, smul_eq_mul, mul_boole, finset.sum_ite_eq],
split_ifs with h,
{ refl },
{ rw finsupp.not_mem_support_iff.mp h }
end
lemma to_dual_apply_left (m : M) (i : ι) : b.to_dual m (b i) = b.repr m i :=
by rw [← b.to_dual_total_left, b.total_repr]
lemma to_dual_apply_right (i : ι) (m : M) : b.to_dual (b i) m = b.repr m i :=
by rw [← b.to_dual_total_right, b.total_repr]
lemma coe_to_dual_self (i : ι) : b.to_dual (b i) = b.coord i :=
by { ext, apply to_dual_apply_right }
/-- `h.to_dual_flip v` is the linear map sending `w` to `h.to_dual w v`. -/
def to_dual_flip (m : M) : (M →ₗ[R] R) := b.to_dual.flip m
lemma to_dual_flip_apply (m₁ m₂ : M) : b.to_dual_flip m₁ m₂ = b.to_dual m₂ m₁ := rfl
lemma to_dual_eq_repr (m : M) (i : ι) : b.to_dual m (b i) = b.repr m i :=
b.to_dual_apply_left m i
lemma to_dual_eq_equiv_fun [fintype ι] (m : M) (i : ι) : b.to_dual m (b i) = b.equiv_fun m i :=
by rw [b.equiv_fun_apply, to_dual_eq_repr]
lemma to_dual_inj (m : M) (a : b.to_dual m = 0) : m = 0 :=
begin
rw [← mem_bot R, ← b.repr.ker, mem_ker, linear_equiv.coe_coe],
apply finsupp.ext,
intro b,
rw [← to_dual_eq_repr, a],
refl
end
theorem to_dual_ker : b.to_dual.ker = ⊥ :=
ker_eq_bot'.mpr b.to_dual_inj
theorem to_dual_range [_root_.finite ι] : b.to_dual.range = ⊤ :=
begin
casesI nonempty_fintype ι,
refine eq_top_iff'.2 (λ f, _),
rw linear_map.mem_range,
let lin_comb : ι →₀ R := finsupp.equiv_fun_on_finite.symm (λ i, f.to_fun (b i)),
refine ⟨finsupp.total ι M R b lin_comb, b.ext $ λ i, _⟩,
rw [b.to_dual_eq_repr _ i, repr_total b],
refl,
end
end comm_semiring
section
variables [comm_semiring R] [add_comm_monoid M] [module R M] [fintype ι]
variables (b : basis ι R M)
@[simp] lemma sum_dual_apply_smul_coord (f : module.dual R M) : ∑ x, f (b x) • b.coord x = f :=
begin
ext m,
simp_rw [linear_map.sum_apply, linear_map.smul_apply, smul_eq_mul, mul_comm (f _), ←smul_eq_mul,
←f.map_smul, ←f.map_sum, basis.coord_apply, basis.sum_repr],
end
end
section comm_ring
variables [comm_ring R] [add_comm_group M] [module R M] [decidable_eq ι]
variables (b : basis ι R M)
section finite
variables [_root_.finite ι]
/-- A vector space is linearly equivalent to its dual space. -/
@[simps]
def to_dual_equiv : M ≃ₗ[R] dual R M :=
linear_equiv.of_bijective b.to_dual
⟨ker_eq_bot.mp b.to_dual_ker, range_eq_top.mp b.to_dual_range⟩
/-- Maps a basis for `V` to a basis for the dual space. -/
def dual_basis : basis ι R (dual R M) := b.map b.to_dual_equiv
-- We use `j = i` to match `basis.repr_self`
lemma dual_basis_apply_self (i j : ι) : b.dual_basis i (b j) = if j = i then 1 else 0 :=
by { convert b.to_dual_apply i j using 2, rw @eq_comm _ j i }
lemma total_dual_basis (f : ι →₀ R) (i : ι) :
finsupp.total ι (dual R M) R b.dual_basis f (b i) = f i :=
begin
casesI nonempty_fintype ι,
rw [finsupp.total_apply, finsupp.sum_fintype, linear_map.sum_apply],
{ simp_rw [linear_map.smul_apply, smul_eq_mul, dual_basis_apply_self, mul_boole,
finset.sum_ite_eq, if_pos (finset.mem_univ i)] },
{ intro, rw zero_smul },
end
lemma dual_basis_repr (l : dual R M) (i : ι) : b.dual_basis.repr l i = l (b i) :=
by rw [← total_dual_basis b, basis.total_repr b.dual_basis l]
lemma dual_basis_apply (i : ι) (m : M) : b.dual_basis i m = b.repr m i := b.to_dual_apply_right i m
@[simp] lemma coe_dual_basis : ⇑b.dual_basis = b.coord := by { ext i x, apply dual_basis_apply }
@[simp] lemma to_dual_to_dual : b.dual_basis.to_dual.comp b.to_dual = dual.eval R M :=
begin
refine b.ext (λ i, b.dual_basis.ext (λ j, _)),
rw [linear_map.comp_apply, to_dual_apply_left, coe_to_dual_self, ← coe_dual_basis,
dual.eval_apply, basis.repr_self, finsupp.single_apply, dual_basis_apply_self]
end
end finite
lemma dual_basis_equiv_fun [fintype ι] (l : dual R M) (i : ι) :
b.dual_basis.equiv_fun l i = l (b i) :=
by rw [basis.equiv_fun_apply, dual_basis_repr]
theorem eval_ker {ι : Type*} (b : basis ι R M) :
(dual.eval R M).ker = ⊥ :=
begin
rw ker_eq_bot',
intros m hm,
simp_rw [linear_map.ext_iff, dual.eval_apply, zero_apply] at hm,
exact (basis.forall_coord_eq_zero_iff _).mp (λ i, hm (b.coord i))
end
lemma eval_range {ι : Type*} [_root_.finite ι] (b : basis ι R M) : (eval R M).range = ⊤ :=
begin
classical,
casesI nonempty_fintype ι,
rw [← b.to_dual_to_dual, range_comp, b.to_dual_range, map_top, to_dual_range _],
apply_instance
end
/-- A module with a basis is linearly equivalent to the dual of its dual space. -/
def eval_equiv {ι : Type*} [_root_.finite ι] (b : basis ι R M) : M ≃ₗ[R] dual R (dual R M) :=
linear_equiv.of_bijective (eval R M)
⟨ker_eq_bot.mp b.eval_ker, range_eq_top.mp b.eval_range⟩
@[simp] lemma eval_equiv_to_linear_map {ι : Type*} [_root_.finite ι] (b : basis ι R M) :
(b.eval_equiv).to_linear_map = dual.eval R M := rfl
section
open_locale classical
variables [finite R M] [free R M] [nontrivial R]
instance dual_free : free R (dual R M) := free.of_basis (free.choose_basis R M).dual_basis
instance dual_finite : finite R (dual R M) := finite.of_basis (free.choose_basis R M).dual_basis
end
end comm_ring
/-- `simp` normal form version of `total_dual_basis` -/
@[simp] lemma total_coord [comm_ring R] [add_comm_group M] [module R M] [_root_.finite ι]
(b : basis ι R M) (f : ι →₀ R) (i : ι) :
finsupp.total ι (dual R M) R b.coord f (b i) = f i :=
by { haveI := classical.dec_eq ι, rw [← coe_dual_basis, total_dual_basis] }
lemma dual_dim_eq [comm_ring K] [add_comm_group V] [module K V] [_root_.finite ι]
(b : basis ι K V) :
cardinal.lift (module.rank K V) = module.rank K (dual K V) :=
begin
classical,
casesI nonempty_fintype ι,
have := linear_equiv.lift_dim_eq b.to_dual_equiv,
simp only [cardinal.lift_umax] at this,
rw [this, ← cardinal.lift_umax],
apply cardinal.lift_id,
end
end basis
namespace module
variables {K V : Type*}
variables [field K] [add_comm_group V] [module K V]
open module module.dual submodule linear_map cardinal basis finite_dimensional
theorem eval_ker : (eval K V).ker = ⊥ :=
by { classical, exact (basis.of_vector_space K V).eval_ker }
section
variable (K)
theorem eval_apply_eq_zero_iff (v : V) : (eval K V) v = 0 ↔ v = 0 :=
by simpa only using set_like.ext_iff.mp (eval_ker : (eval K V).ker = _) v
theorem eval_apply_injective : function.injective (eval K V) :=
(injective_iff_map_eq_zero' (eval K V)).mpr (eval_apply_eq_zero_iff K)
theorem forall_dual_apply_eq_zero_iff (v : V) : (∀ (φ : module.dual K V), φ v = 0) ↔ v = 0 :=
by { rw [← eval_apply_eq_zero_iff K v, linear_map.ext_iff], refl }
end
-- TODO(jmc): generalize to rings, once `module.rank` is generalized
theorem dual_dim_eq [finite_dimensional K V] :
cardinal.lift (module.rank K V) = module.rank K (dual K V) :=
(basis.of_vector_space K V).dual_dim_eq
lemma erange_coe [finite_dimensional K V] : (eval K V).range = ⊤ :=
begin
letI : is_noetherian K V := is_noetherian.iff_fg.2 infer_instance,
exact (basis.of_vector_space K V).eval_range
end
variables (K V)
/-- A vector space is linearly equivalent to the dual of its dual space. -/
def eval_equiv [finite_dimensional K V] : V ≃ₗ[K] dual K (dual K V) :=
linear_equiv.of_bijective (eval K V)
⟨ker_eq_bot.mp eval_ker, range_eq_top.mp erange_coe⟩
variables {K V}
@[simp] lemma eval_equiv_to_linear_map [finite_dimensional K V] :
(eval_equiv K V).to_linear_map = dual.eval K V := rfl
end module
section dual_bases
open module
variables {R M ι : Type*}
variables [comm_semiring R] [add_comm_monoid M] [module R M] [decidable_eq ι]
/-- `e` and `ε` have characteristic properties of a basis and its dual -/
@[nolint has_nonempty_instance]
structure module.dual_bases (e : ι → M) (ε : ι → (dual R M)) :=
(eval : ∀ i j : ι, ε i (e j) = if i = j then 1 else 0)
(total : ∀ {m : M}, (∀ i, ε i m = 0) → m = 0)
[finite : ∀ m : M, fintype {i | ε i m ≠ 0}]
end dual_bases
namespace module.dual_bases
open module module.dual linear_map function
variables {R M ι : Type*}
variables [comm_ring R] [add_comm_group M] [module R M]
variables {e : ι → M} {ε : ι → dual R M}
/-- The coefficients of `v` on the basis `e` -/
def coeffs [decidable_eq ι] (h : dual_bases e ε) (m : M) : ι →₀ R :=
{ to_fun := λ i, ε i m,
support := by { haveI := h.finite m, exact {i : ι | ε i m ≠ 0}.to_finset },
mem_support_to_fun := by {intro i, rw set.mem_to_finset, exact iff.rfl } }
@[simp] lemma coeffs_apply [decidable_eq ι] (h : dual_bases e ε) (m : M) (i : ι) :
h.coeffs m i = ε i m := rfl
/-- linear combinations of elements of `e`.
This is a convenient abbreviation for `finsupp.total _ M R e l` -/
def lc {ι} (e : ι → M) (l : ι →₀ R) : M := l.sum (λ (i : ι) (a : R), a • (e i))
lemma lc_def (e : ι → M) (l : ι →₀ R) : lc e l = finsupp.total _ _ _ e l := rfl
open module
variables [decidable_eq ι] (h : dual_bases e ε)
include h
lemma dual_lc (l : ι →₀ R) (i : ι) : ε i (dual_bases.lc e l) = l i :=
begin
erw linear_map.map_sum,
simp only [h.eval, map_smul, smul_eq_mul],
rw finset.sum_eq_single i,
{ simp },
{ intros q q_in q_ne,
simp [q_ne.symm] },
{ intro p_not_in,
simp [finsupp.not_mem_support_iff.1 p_not_in] },
end
@[simp]
lemma coeffs_lc (l : ι →₀ R) : h.coeffs (dual_bases.lc e l) = l :=
by { ext i, rw [h.coeffs_apply, h.dual_lc] }
/-- For any m : M n, \sum_{p ∈ Q n} (ε p m) • e p = m -/
@[simp]
lemma lc_coeffs (m : M) : dual_bases.lc e (h.coeffs m) = m :=
begin
refine eq_of_sub_eq_zero (h.total _),
intros i,
simp [-sub_eq_add_neg, linear_map.map_sub, h.dual_lc, sub_eq_zero]
end
/-- `(h : dual_bases e ε).basis` shows the family of vectors `e` forms a basis. -/
@[simps]
def basis : basis ι R M :=
basis.of_repr
{ to_fun := coeffs h,
inv_fun := lc e,
left_inv := lc_coeffs h,
right_inv := coeffs_lc h,
map_add' := λ v w, by { ext i, exact (ε i).map_add v w },
map_smul' := λ c v, by { ext i, exact (ε i).map_smul c v } }
@[simp] lemma coe_basis : ⇑h.basis = e :=
by { ext i, rw basis.apply_eq_iff, ext j,
rw [h.basis_repr_apply, coeffs_apply, h.eval, finsupp.single_apply],
convert if_congr eq_comm rfl rfl } -- `convert` to get rid of a `decidable_eq` mismatch
lemma mem_of_mem_span {H : set ι} {x : M} (hmem : x ∈ submodule.span R (e '' H)) :
∀ i : ι, ε i x ≠ 0 → i ∈ H :=
begin
intros i hi,
rcases (finsupp.mem_span_image_iff_total _).mp hmem with ⟨l, supp_l, rfl⟩,
apply not_imp_comm.mp ((finsupp.mem_supported' _ _).mp supp_l i),
rwa [← lc_def, h.dual_lc] at hi
end
lemma coe_dual_basis [fintype ι] : ⇑h.basis.dual_basis = ε :=
funext (λ i, h.basis.ext (λ j, by rw [h.basis.dual_basis_apply_self, h.coe_basis, h.eval,
if_congr eq_comm rfl rfl]))
end module.dual_bases
namespace submodule
universes u v w
variables {R : Type u} {M : Type v} [comm_semiring R] [add_comm_monoid M] [module R M]
variable {W : submodule R M}
/-- The `dual_restrict` of a submodule `W` of `M` is the linear map from the
dual of `M` to the dual of `W` such that the domain of each linear map is
restricted to `W`. -/
def dual_restrict (W : submodule R M) :
module.dual R M →ₗ[R] module.dual R W :=
linear_map.dom_restrict' W
@[simp] lemma dual_restrict_apply
(W : submodule R M) (φ : module.dual R M) (x : W) :
W.dual_restrict φ x = φ (x : M) := rfl
/-- The `dual_annihilator` of a submodule `W` is the set of linear maps `φ` such
that `φ w = 0` for all `w ∈ W`. -/
def dual_annihilator {R : Type u} {M : Type v} [comm_semiring R] [add_comm_monoid M]
[module R M] (W : submodule R M) : submodule R $ module.dual R M :=
W.dual_restrict.ker
@[simp] lemma mem_dual_annihilator (φ : module.dual R M) :
φ ∈ W.dual_annihilator ↔ ∀ w ∈ W, φ w = 0 :=
begin
refine linear_map.mem_ker.trans _,
simp_rw [linear_map.ext_iff, dual_restrict_apply],
exact ⟨λ h w hw, h ⟨w, hw⟩, λ h w, h w.1 w.2⟩
end
lemma dual_restrict_ker_eq_dual_annihilator (W : submodule R M) :
W.dual_restrict.ker = W.dual_annihilator :=
rfl
/-- The `dual_annihilator` of a submodule of the dual space pulled back along the evaluation map
`module.dual.eval`. -/
def dual_annihilator_comap (Φ : submodule R (module.dual R M)) : submodule R M :=
Φ.dual_annihilator.comap (module.dual.eval R M)
lemma mem_dual_annihilator_comap {Φ : submodule R (module.dual R M)} (x : M) :
x ∈ Φ.dual_annihilator_comap ↔ ∀ φ ∈ Φ, (φ x : R) = 0 :=
by simp_rw [dual_annihilator_comap, mem_comap, mem_dual_annihilator, module.dual.eval_apply]
@[simp] lemma dual_annihilator_top : (⊤ : submodule R M).dual_annihilator = ⊥ :=
begin
rw eq_bot_iff,
intro v,
simp_rw [mem_dual_annihilator, mem_bot, mem_top, forall_true_left],
exact λ h, linear_map.ext h,
end
@[simp] lemma dual_annihilator_bot : (⊥ : submodule R M).dual_annihilator = ⊤ :=
begin
rw eq_top_iff,
intro v,
simp_rw [mem_dual_annihilator, mem_bot, mem_top, forall_true_left],
rintro _ rfl,
exact _root_.map_zero v,
end
@[simp] lemma dual_annihilator_comap_bot :
(⊥ : submodule R (module.dual R M)).dual_annihilator_comap = ⊤ :=
by rw [dual_annihilator_comap, dual_annihilator_bot, comap_top]
@[mono] lemma dual_annihilator_anti {U V : submodule R M} (hUV : U ≤ V) :
V.dual_annihilator ≤ U.dual_annihilator :=
begin
intro φ,
simp_rw [mem_dual_annihilator],
intros h w hw,
exact h w (hUV hw),
end
@[mono] lemma dual_annihilator_comap_anti {U V : submodule R (module.dual R M)} (hUV : U ≤ V) :
V.dual_annihilator_comap ≤ U.dual_annihilator_comap :=
begin
intro φ,
simp_rw [mem_dual_annihilator_comap],
intros h w hw,
exact h w (hUV hw),
end
lemma le_dual_annihilator_dual_annihilator_comap {U : submodule R M} :
U ≤ U.dual_annihilator.dual_annihilator_comap :=
begin
intro v,
simp_rw [mem_dual_annihilator_comap, mem_dual_annihilator],
intros hv φ h,
exact h _ hv,
end
lemma le_dual_annihilator_comap_dual_annihilator {U : submodule R (module.dual R M)} :
U ≤ U.dual_annihilator_comap.dual_annihilator :=
begin
intro v,
simp_rw [mem_dual_annihilator, mem_dual_annihilator_comap],
intros hv φ h,
exact h _ hv,
end
lemma dual_annihilator_sup_eq (U V : submodule R M) :
(U ⊔ V).dual_annihilator = U.dual_annihilator ⊓ V.dual_annihilator :=
begin
ext φ,
rw [mem_inf, mem_dual_annihilator, mem_dual_annihilator, mem_dual_annihilator],
split; intro h,
{ refine ⟨_, _⟩;
intros x hx,
exact h x (mem_sup.2 ⟨x, hx, 0, zero_mem _, add_zero _⟩),
exact h x (mem_sup.2 ⟨0, zero_mem _, x, hx, zero_add _⟩) },
{ simp_rw mem_sup,
rintro _ ⟨x, hx, y, hy, rfl⟩,
rw [linear_map.map_add, h.1 _ hx, h.2 _ hy, add_zero] }
end
lemma dual_annihilator_supr_eq {ι : Type*} (U : ι → submodule R M) :
(⨆ (i : ι), U i).dual_annihilator = ⨅ (i : ι), (U i).dual_annihilator :=
begin
classical,
ext φ,
simp_rw [mem_infi, mem_dual_annihilator],
split,
{ simp_rw [mem_supr],
intros h i w hw,
exact h _ (λ _ hi, hi i hw), },
{ simp_rw [submodule.mem_supr_iff_exists_dfinsupp'],
rintros h w ⟨f, rfl⟩,
simp only [linear_map.map_dfinsupp_sum],
transitivity f.sum (λ (i : ι) (d : U i), (0 : R)),
{ congr,
ext i d,
exact h i d d.property, },
{ exact @dfinsupp.sum_zero ι _ (λ i, U i) _ _ _ _ f, } }
end
-- TODO: when `M` is finite-dimensional this is an equality
lemma sup_dual_annihilator_le_inf (U V : submodule R M) :
U.dual_annihilator ⊔ V.dual_annihilator ≤ (U ⊓ V).dual_annihilator :=
begin
intro φ,
simp_rw [mem_sup, mem_dual_annihilator, mem_inf],
rintro ⟨ψ, hψ, ψ', hψ', rfl⟩ v ⟨hU, hV⟩,
rw [linear_map.add_apply, hψ _ hU, hψ' _ hV, zero_add],
end
-- TODO: when `M` is finite-dimensional this is an equality
lemma supr_dual_annihilator_le_infi {ι : Type*} (U : ι → submodule R M) :
(⨆ (i : ι), (U i).dual_annihilator) ≤ (⨅ (i : ι), U i).dual_annihilator :=
begin
classical,
intro φ,
simp_rw [mem_dual_annihilator, submodule.mem_supr_iff_exists_dfinsupp', mem_infi],
rintros ⟨f, rfl⟩ x hx,
rw [linear_map.dfinsupp_sum_apply],
transitivity f.sum (λ (i : ι) (d : (U i).dual_annihilator), (0 : R)),
{ congr,
ext i ⟨d, hd⟩,
rw [mem_dual_annihilator] at hd,
exact hd x (hx _), },
{ exact @dfinsupp.sum_zero ι _ (λ i, (U i).dual_annihilator) _ _ _ _ f }
end
end submodule
namespace subspace
open submodule linear_map
universes u v w
-- We work in vector spaces because `exists_is_compl` only hold for vector spaces
variables {K : Type u} {V : Type v} [field K] [add_comm_group V] [module K V]
@[simp] lemma dual_annihilator_comap_top (W : subspace K V) :
(⊤ : submodule K (module.dual K W)).dual_annihilator_comap = ⊥ :=
by rw [dual_annihilator_comap, dual_annihilator_top, comap_bot, module.eval_ker]
lemma dual_annihilator_dual_annihilator_comap_eq {W : subspace K V} :
W.dual_annihilator.dual_annihilator_comap = W :=
begin
refine le_antisymm _ le_dual_annihilator_dual_annihilator_comap,
intro v,
simp only [mem_dual_annihilator, mem_dual_annihilator_comap],
contrapose!,
intro hv,
obtain ⟨W', hW⟩ := submodule.exists_is_compl W,
obtain ⟨⟨w, w'⟩, rfl, -⟩ := exists_unique_add_of_is_compl_prod hW v,
have hw'n : (w' : V) ∉ W := by { contrapose! hv, exact submodule.add_mem W w.2 hv },
have hw'nz : w' ≠ 0 := by { rintro rfl, exact hw'n (submodule.zero_mem W) },
rw [ne.def, ← module.forall_dual_apply_eq_zero_iff K w'] at hw'nz,
push_neg at hw'nz,
obtain ⟨φ, hφ⟩ := hw'nz,
existsi ((linear_map.of_is_compl_prod hW).comp (linear_map.inr _ _ _)) φ,
simp only [coe_comp, coe_inr, function.comp_app, of_is_compl_prod_apply, map_add,
of_is_compl_left_apply, zero_apply, of_is_compl_right_apply, zero_add, ne.def],
refine ⟨_, hφ⟩,
intros v hv,
convert linear_map.of_is_compl_left_apply hW ⟨v, hv⟩,
end
/-- Given a subspace `W` of `V` and an element of its dual `φ`, `dual_lift W φ` is
the natural extension of `φ` to an element of the dual of `V`.
That is, `dual_lift W φ` sends `w ∈ W` to `φ x` and `x` in the complement of `W` to `0`. -/
noncomputable def dual_lift (W : subspace K V) :
module.dual K W →ₗ[K] module.dual K V :=
let h := classical.indefinite_description _ W.exists_is_compl in
(linear_map.of_is_compl_prod h.2).comp (linear_map.inl _ _ _)
variable {W : subspace K V}
@[simp] lemma dual_lift_of_subtype {φ : module.dual K W} (w : W) :
W.dual_lift φ (w : V) = φ w :=
by { erw of_is_compl_left_apply _ w, refl }
lemma dual_lift_of_mem {φ : module.dual K W} {w : V} (hw : w ∈ W) :
W.dual_lift φ w = φ ⟨w, hw⟩ :=
by convert dual_lift_of_subtype ⟨w, hw⟩
@[simp] lemma dual_restrict_comp_dual_lift (W : subspace K V) :
W.dual_restrict.comp W.dual_lift = 1 :=
by { ext φ x, simp }
lemma dual_restrict_left_inverse (W : subspace K V) :
function.left_inverse W.dual_restrict W.dual_lift :=
λ x, show W.dual_restrict.comp W.dual_lift x = x,
by { rw [dual_restrict_comp_dual_lift], refl }
lemma dual_lift_right_inverse (W : subspace K V) :
function.right_inverse W.dual_lift W.dual_restrict :=
W.dual_restrict_left_inverse
lemma dual_restrict_surjective :
function.surjective W.dual_restrict :=
W.dual_lift_right_inverse.surjective
lemma dual_lift_injective : function.injective W.dual_lift :=
W.dual_restrict_left_inverse.injective
/-- The quotient by the `dual_annihilator` of a subspace is isomorphic to the
dual of that subspace. -/
noncomputable def quot_annihilator_equiv (W : subspace K V) :
(module.dual K V ⧸ W.dual_annihilator) ≃ₗ[K] module.dual K W :=
(quot_equiv_of_eq _ _ W.dual_restrict_ker_eq_dual_annihilator).symm.trans $
W.dual_restrict.quot_ker_equiv_of_surjective dual_restrict_surjective
/-- The natural isomorphism forom the dual of a subspace `W` to `W.dual_lift.range`. -/
noncomputable def dual_equiv_dual (W : subspace K V) :
module.dual K W ≃ₗ[K] W.dual_lift.range :=
linear_equiv.of_injective _ dual_lift_injective
lemma dual_equiv_dual_def (W : subspace K V) :
W.dual_equiv_dual.to_linear_map = W.dual_lift.range_restrict := rfl
@[simp] lemma dual_equiv_dual_apply (φ : module.dual K W) :
W.dual_equiv_dual φ = ⟨W.dual_lift φ, mem_range.2 ⟨φ, rfl⟩⟩ := rfl
section
open_locale classical
open finite_dimensional
variables {V₁ : Type*} [add_comm_group V₁] [module K V₁]
instance [H : finite_dimensional K V] : finite_dimensional K (module.dual K V) :=
by apply_instance
variables [finite_dimensional K V] [finite_dimensional K V₁]
@[simp] lemma dual_finrank_eq :
finrank K (module.dual K V) = finrank K V :=
linear_equiv.finrank_eq (basis.of_vector_space K V).to_dual_equiv.symm
/-- The quotient by the dual is isomorphic to its dual annihilator. -/
noncomputable def quot_dual_equiv_annihilator (W : subspace K V) :
(module.dual K V ⧸ W.dual_lift.range) ≃ₗ[K] W.dual_annihilator :=
linear_equiv.quot_equiv_of_quot_equiv $
linear_equiv.trans W.quot_annihilator_equiv W.dual_equiv_dual
/-- The quotient by a subspace is isomorphic to its dual annihilator. -/
noncomputable def quot_equiv_annihilator (W : subspace K V) :
(V ⧸ W) ≃ₗ[K] W.dual_annihilator :=
begin
refine _ ≪≫ₗ W.quot_dual_equiv_annihilator,
refine linear_equiv.quot_equiv_of_equiv _ (basis.of_vector_space K V).to_dual_equiv,
exact (basis.of_vector_space K W).to_dual_equiv.trans W.dual_equiv_dual
end
open finite_dimensional
@[simp]
lemma finrank_dual_annihilator_comap_eq {Φ : subspace K (module.dual K V)} :
finrank K Φ.dual_annihilator_comap = finrank K Φ.dual_annihilator :=
begin
rw [submodule.dual_annihilator_comap, ← module.eval_equiv_to_linear_map],
exact linear_equiv.finrank_eq (linear_equiv.of_submodule' _ _),
end
lemma finrank_add_finrank_dual_annihilator_comap_eq
(W : subspace K (module.dual K V)) :
finrank K W + finrank K W.dual_annihilator_comap = finrank K V :=
begin
rw [finrank_dual_annihilator_comap_eq, W.quot_equiv_annihilator.finrank_eq.symm, add_comm,
submodule.finrank_quotient_add_finrank, subspace.dual_finrank_eq],
end
end
end subspace
open module
section dual_map
variables {R : Type*} [comm_semiring R] {M₁ : Type*} {M₂ : Type*}
variables [add_comm_monoid M₁] [module R M₁] [add_comm_monoid M₂] [module R M₂]
/-- Given a linear map `f : M₁ →ₗ[R] M₂`, `f.dual_map` is the linear map between the dual of
`M₂` and `M₁` such that it maps the functional `φ` to `φ ∘ f`. -/
def linear_map.dual_map (f : M₁ →ₗ[R] M₂) : dual R M₂ →ₗ[R] dual R M₁ :=
linear_map.lcomp R R f
@[simp] lemma linear_map.dual_map_apply (f : M₁ →ₗ[R] M₂) (g : dual R M₂) (x : M₁) :
f.dual_map g x = g (f x) := rfl
@[simp] lemma linear_map.dual_map_id :
(linear_map.id : M₁ →ₗ[R] M₁).dual_map = linear_map.id :=
by { ext, refl }
lemma linear_map.dual_map_comp_dual_map {M₃ : Type*} [add_comm_group M₃] [module R M₃]
(f : M₁ →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) :
f.dual_map.comp g.dual_map = (g.comp f).dual_map :=
rfl
/-- The `linear_equiv` version of `linear_map.dual_map`. -/
def linear_equiv.dual_map (f : M₁ ≃ₗ[R] M₂) : dual R M₂ ≃ₗ[R] dual R M₁ :=
{ inv_fun := f.symm.to_linear_map.dual_map,
left_inv :=
begin
intro φ, ext x,
simp only [linear_map.dual_map_apply, linear_equiv.coe_to_linear_map,
linear_map.to_fun_eq_coe, linear_equiv.apply_symm_apply]
end,
right_inv :=
begin
intro φ, ext x,
simp only [linear_map.dual_map_apply, linear_equiv.coe_to_linear_map,
linear_map.to_fun_eq_coe, linear_equiv.symm_apply_apply]
end,
.. f.to_linear_map.dual_map }
@[simp] lemma linear_equiv.dual_map_apply (f : M₁ ≃ₗ[R] M₂) (g : dual R M₂) (x : M₁) :
f.dual_map g x = g (f x) := rfl
@[simp] lemma linear_equiv.dual_map_refl :
(linear_equiv.refl R M₁).dual_map = linear_equiv.refl R (dual R M₁) :=
by { ext, refl }
@[simp] lemma linear_equiv.dual_map_symm {f : M₁ ≃ₗ[R] M₂} :
(linear_equiv.dual_map f).symm = linear_equiv.dual_map f.symm := rfl
lemma linear_equiv.dual_map_trans {M₃ : Type*} [add_comm_group M₃] [module R M₃]
(f : M₁ ≃ₗ[R] M₂) (g : M₂ ≃ₗ[R] M₃) :
g.dual_map.trans f.dual_map = (f.trans g).dual_map :=
rfl
end dual_map
namespace linear_map
variables {R : Type*} [comm_semiring R] {M₁ : Type*} {M₂ : Type*}
variables [add_comm_monoid M₁] [module R M₁] [add_comm_monoid M₂] [module R M₂]
variable (f : M₁ →ₗ[R] M₂)
lemma ker_dual_map_eq_dual_annihilator_range :
f.dual_map.ker = f.range.dual_annihilator :=
begin
ext φ, split; intro hφ,
{ rw mem_ker at hφ,
rw submodule.mem_dual_annihilator,
rintro y ⟨x, rfl⟩,
rw [← dual_map_apply, hφ, zero_apply] },
{ ext x,
rw dual_map_apply,
rw submodule.mem_dual_annihilator at hφ,
exact hφ (f x) ⟨x, rfl⟩ }
end
lemma range_dual_map_le_dual_annihilator_ker :
f.dual_map.range ≤ f.ker.dual_annihilator :=
begin
rintro _ ⟨ψ, rfl⟩,
simp_rw [submodule.mem_dual_annihilator, mem_ker],
rintro x hx,
rw [dual_map_apply, hx, map_zero]
end
section finite_dimensional
variables {K : Type*} [field K] {V₁ : Type*} {V₂ : Type*}
variables [add_comm_group V₁] [module K V₁] [add_comm_group V₂] [module K V₂]
open finite_dimensional
variable [finite_dimensional K V₂]
@[simp] lemma finrank_range_dual_map_eq_finrank_range (f : V₁ →ₗ[K] V₂) :
finrank K f.dual_map.range = finrank K f.range :=
begin
have := submodule.finrank_quotient_add_finrank f.range,
rw [(subspace.quot_equiv_annihilator f.range).finrank_eq,
← ker_dual_map_eq_dual_annihilator_range] at this,
conv_rhs at this { rw ← subspace.dual_finrank_eq },
refine add_left_injective (finrank K f.dual_map.ker) _,
change _ + _ = _ + _,
rw [finrank_range_add_finrank_ker f.dual_map, add_comm, this],
end
lemma range_dual_map_eq_dual_annihilator_ker [finite_dimensional K V₁] (f : V₁ →ₗ[K] V₂) :
f.dual_map.range = f.ker.dual_annihilator :=
begin
refine eq_of_le_of_finrank_eq f.range_dual_map_le_dual_annihilator_ker _,
have := submodule.finrank_quotient_add_finrank f.ker,
rw (subspace.quot_equiv_annihilator f.ker).finrank_eq at this,
refine add_left_injective (finrank K f.ker) _,
simp_rw [this, finrank_range_dual_map_eq_finrank_range],
exact finrank_range_add_finrank_ker f,
end
end finite_dimensional
section field
variables {K V : Type*}
variables [field K] [add_comm_group V] [module K V]
lemma dual_pairing_nondegenerate : (dual_pairing K V).nondegenerate :=
begin
refine ⟨separating_left_iff_ker_eq_bot.mpr ker_id, _⟩,
intros x,
contrapose,
rintros hx : x ≠ 0,
rw [not_forall],
let f : V →ₗ[K] K := classical.some (linear_pmap.mk_span_singleton x 1 hx).to_fun.exists_extend,
use [f],
refine ne_zero_of_eq_one _,
have h : f.comp (K ∙ x).subtype = (linear_pmap.mk_span_singleton x 1 hx).to_fun :=
classical.some_spec (linear_pmap.mk_span_singleton x (1 : K) hx).to_fun.exists_extend,
exact (fun_like.congr_fun h _).trans (linear_pmap.mk_span_singleton_apply _ hx _),
end
end field
end linear_map
namespace tensor_product
variables (R : Type*) (M : Type*) (N : Type*)
variables {ι κ : Type*}
variables [decidable_eq ι] [decidable_eq κ]
variables [fintype ι] [fintype κ]
open_locale big_operators
open_locale tensor_product
local attribute [ext] tensor_product.ext
open tensor_product
open linear_map
section
variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid N]
variables [module R M] [module R N]
/--
The canonical linear map from `dual M ⊗ dual N` to `dual (M ⊗ N)`,
sending `f ⊗ g` to the composition of `tensor_product.map f g` with
the natural isomorphism `R ⊗ R ≃ R`.
-/
def dual_distrib : (dual R M) ⊗[R] (dual R N) →ₗ[R] dual R (M ⊗[R] N) :=
(comp_right ↑(tensor_product.lid R R)) ∘ₗ hom_tensor_hom_map R M N R R
variables {R M N}
@[simp]
lemma dual_distrib_apply (f : dual R M) (g : dual R N) (m : M) (n : N) :
dual_distrib R M N (f ⊗ₜ g) (m ⊗ₜ n) = f m * g n :=
rfl
end
variables {R M N}
variables [comm_ring R] [add_comm_group M] [add_comm_group N]
variables [module R M] [module R N]
/--
An inverse to `dual_tensor_dual_map` given bases.
-/
noncomputable
def dual_distrib_inv_of_basis (b : basis ι R M) (c : basis κ R N) :
dual R (M ⊗[R] N) →ₗ[R] (dual R M) ⊗[R] (dual R N) :=
∑ i j, (ring_lmap_equiv_self R ℕ _).symm (b.dual_basis i ⊗ₜ c.dual_basis j)
∘ₗ applyₗ (c j) ∘ₗ applyₗ (b i) ∘ₗ (lcurry R M N R)
@[simp]
lemma dual_distrib_inv_of_basis_apply (b : basis ι R M) (c : basis κ R N)
(f : dual R (M ⊗[R] N)) : dual_distrib_inv_of_basis b c f =
∑ i j, (f (b i ⊗ₜ c j)) • (b.dual_basis i ⊗ₜ c.dual_basis j) :=
by simp [dual_distrib_inv_of_basis]
/--
A linear equivalence between `dual M ⊗ dual N` and `dual (M ⊗ N)` given bases for `M` and `N`.
It sends `f ⊗ g` to the composition of `tensor_product.map f g` with the natural
isomorphism `R ⊗ R ≃ R`.
-/
@[simps]
noncomputable def dual_distrib_equiv_of_basis (b : basis ι R M) (c : basis κ R N) :
(dual R M) ⊗[R] (dual R N) ≃ₗ[R] dual R (M ⊗[R] N) :=
begin
refine linear_equiv.of_linear
(dual_distrib R M N) (dual_distrib_inv_of_basis b c) _ _,
{ ext f m n,
have h : ∀ (r s : R), r • s = s • r := is_commutative.comm,
simp only [compr₂_apply, mk_apply, comp_apply, id_apply, dual_distrib_inv_of_basis_apply,
linear_map.map_sum, map_smul, sum_apply, smul_apply, dual_distrib_apply, h (f _) _,
← f.map_smul, ←f.map_sum, ←smul_tmul_smul, ←tmul_sum, ←sum_tmul, basis.coe_dual_basis,
basis.coord_apply, basis.sum_repr] },
{ ext f g,
simp only [compr₂_apply, mk_apply, comp_apply, id_apply, dual_distrib_inv_of_basis_apply,
dual_distrib_apply, ←smul_tmul_smul, ←tmul_sum, ←sum_tmul, basis.coe_dual_basis,
basis.sum_dual_apply_smul_coord] }
end
variables (R M N)
variables [module.finite R M] [module.finite R N] [module.free R M] [module.free R N]
variables [nontrivial R]
open_locale classical
/--
A linear equivalence between `dual M ⊗ dual N` and `dual (M ⊗ N)` when `M` and `N` are finite free
modules. It sends `f ⊗ g` to the composition of `tensor_product.map f g` with the natural
isomorphism `R ⊗ R ≃ R`.
-/
@[simp]
noncomputable
def dual_distrib_equiv : (dual R M) ⊗[R] (dual R N) ≃ₗ[R] dual R (M ⊗[R] N) :=
dual_distrib_equiv_of_basis (module.free.choose_basis R M) (module.free.choose_basis R N)
end tensor_product
|
61fd63f62147cb3e6ab9d267165dc4e3d295e64a | e61a235b8468b03aee0120bf26ec615c045005d2 | /tests/lean/run/frontend1.lean | b6ae9f9811e56a699dae8aff7740e527962e43e8 | [
"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 | 7,304 | lean | import Init.Lean.Elab
open Lean
open Lean.Elab
def run (input : String) (failIff : Bool := true) : MetaIO Unit :=
do env ← MetaIO.getEnv;
opts ← MetaIO.getOptions;
(env, messages) ← liftM $ process input env opts;
messages.forM $ fun msg => IO.println msg;
when (failIff && messages.hasErrors) $ throw (IO.userError "errors have been found");
when (!failIff && !messages.hasErrors) $ throw (IO.userError "there are no errors");
pure ()
def fail (input : String) : MetaIO Unit :=
run input false
def M := IO Unit
def zero := 0
def one := 1
def two := 2
def hello : String := "hello"
def act1 : IO String :=
pure "hello"
#eval run "#check @HasAdd.add"
#eval run "#check [zero, one, two]"
#eval run "#check id $ Nat.succ one"
#eval run "#check HasAdd.add one two"
#eval run "#check one + two > one ∧ True"
#eval run "#check act1 >>= IO.println"
#eval run "#check one + two == one"
#eval fail "#check one + one + hello == hello ++ one"
#eval run "#check Nat.add one $ Nat.add one two"
#eval run
"universe u universe v
export HasToString (toString)
section namespace foo.bla end bla end foo
variable (p q : Prop)
variable (_ b : _)
variable {α : Type}
variable {m : Type → Type}
variable [Monad m]
#check m
#check Type
#check Prop
#check toString zero
#check id Nat.zero (α := Nat)
#check id _ (α := Nat)
#check id Nat.zero
#check id (α := Nat)
#check @id Nat
#check p
#check α
#check Nat.succ
#check Nat.add
#check id
#check forall (α : Type), α → α
#check (α : Type) → α → α
#check {α : Type} → {β : Type} → M → (α → β) → α → β
#check ()
#check _root_.run
end"
structure S1 :=
(x y : Nat := 0)
structure S2 extends S1 :=
(z : Nat := 0)
def fD {α} [HasToString α] (a b : α) : String :=
toString a ++ toString b
structure S3 :=
(w : Nat := 0)
(f : forall {α : Type} [HasToString α], α → α → String := @fD)
structure S4 extends S2, S3 :=
(s : Nat := 0)
def s4 : S4 := {}
structure S (α : Type) :=
(field1 : S4 := {})
(field2 : S4 × S4 := ({}, {}))
(field3 : α)
(field4 : List α × Nat := ([], 0))
(vec : Array (α × α) := #[])
(map : HashMap String α := {})
inductive D (α : Type)
| mk (a : α) (s : S4) : D
def s : S Nat := { field3 := 0 }
def d : D Nat := D.mk 10 {}
def i : Nat := 10
def k : String := "hello"
universes u
class Monoid (α : Type u) :=
(one : α)
(mul : α → α → α)
def m : Monoid Nat :=
{ one := 1, mul := Nat.mul }
def f (x y z : Nat) : Nat :=
x + y + z
#eval run "#check s4.x"
#eval run "#check s.field1.x"
#eval run "#check s.field2.fst"
#eval run "#check s.field2.fst.w"
#eval run "#check s.1.x"
#eval run "#check s.2.1.x"
#eval run "#check d.1"
#eval run "#check d.2.x"
#eval run "#check s4.f s4.x"
#eval run "#check m.mul m.one"
#eval run "#check s.field4.1.length.succ"
#eval run "#check s.field4.1.map Nat.succ"
#eval run "#check s.vec[i].1"
#eval run "#check \"hello\""
#eval run "#check 1"
#eval run "#check Nat.succ 1"
#eval run "#check fun _ a (x y : Int) => x + y + a"
#eval run "#check (one)"
#eval run "#check ()"
#eval run "#check (one, two, zero)"
#eval run "#check (one, two, zero)"
#eval run "#check (1 : Int)"
#eval run "#check ((1, 2) : Nat × Int)"
#eval run "#check (· + one)"
#eval run "#check (· + · : Nat → Nat → Nat)"
#eval run "#check (f one · zero)"
#eval run "#check (f · · zero)"
#eval run "#check fun (_ b : Nat) => b + 1"
def foo {α β} (a : α) (b : β) (a' : α) : α :=
a
def bla {α β} (f : α → β) (a : α) : β :=
f a
-- #check fun x => foo x x.w s4 -- fails in old elaborator
-- #check bla (fun x => x.w) s4 -- fails in the old elaborator
-- #check #[1, 2, 3].foldl (fun r a => r.push a) #[] -- fails in the old elaborator
#eval run "#check fun x => foo x x.w s4"
#eval run "#check bla (fun x => x.w) s4"
#eval run "#check #[1, 2, 3].foldl (fun r a => r.push a) #[]"
#eval run "#check #[1, 2, 3].foldl (fun r a => (r.push a).push a) #[]"
#eval run "#check #[1, 2, 3].foldl (fun r a => ((r.push a).push a).push a) #[]"
#eval run "#check #[].push one $.push two $.push zero $.size.succ"
#eval run "#check #[1, 2].foldl (fun r a => r.push a $.push a $.push a) #[]"
#eval run "#check #[1, 2].foldl (init := #[]) $ fun r a => r.push a $.push a"
#eval run "#check let x := one + zero; x + x"
-- set_option trace.Elab true
#eval run "#check (fun x => let v := x.w; v + v) s4"
#eval run "#check fun x => foo x (let v := x.w; v + one) s4"
#eval run "#check fun x => foo x (let v := x.w; let w := x.x; v + w + one) s4"
#eval fail "#check id.{1,1}"
#eval fail "#check @id.{0} Nat"
#eval run "#check @id.{1} Nat"
#eval run "universes u #check id.{u}"
#eval fail "universes u #check id.{v}"
#eval run "universes u #check Type u"
#eval run "universes u #check Sort u"
#eval run "#check Type 1"
#eval run "#check Type 0"
#eval run "universes u v #check Sort (max u v)"
#eval run "universes u v #check Type (max u v)"
#eval run "#check 'a'"
#eval fail "#check #['a', \"hello\"]"
#eval run "#check fun (a : Array Nat) => a.size"
#eval run "#check if 0 = 1 then 'a' else 'b'"
#eval run "#check fun (i : Nat) (a : Array Nat) => if h : i < a.size then a.get (Fin.mk i h) else i"
#eval run "#check { x : Nat // x > 0 }"
#eval run "#check { x // x > 0 }"
#eval run "#check fun (i : Nat) (a : Array Nat) => if h : i < a.size then a.get ⟨i, h⟩ else i"
#eval run "#check Prod.fst ⟨1, 2⟩"
#eval run "#check let x := ⟨1, 2⟩; Prod.fst x"
#eval run "#check show Nat from 1"
#eval run "#check show Int from 1"
#eval run "#check have Nat from one + zero; this + this"
#eval run "#check have x : Nat from one + zero; x + x"
#eval run "#check have Nat := one + zero; this + this"
#eval run "#check have x : Nat := one + zero; x + x"
#eval run "#check x + y where x := 1; where y := x + x"
#eval run "#check let z := 2; x + y where x := z + 1; where y := x + x"
#eval run "variables {α β} axiom x (n : Nat) : α → α #check x 1 0"
#eval run "#check HasToString.toString 0"
#eval run "@[instance] axiom newInst : HasToString Nat #check newInst #check HasToString.toString 0"
#eval run "variables {β σ} universes w1 w2 /-- Testing axiom -/ unsafe axiom Nat.aux.{u, v} (γ : Type w1) (v : Nat) : β → (α : Type _) → v = zero /- Nat.zero -/ → Array α #check @Nat.aux"
#eval run "def x : Nat := Nat.zero #check x"
#eval run "def x := Nat.zero #check x"
#eval run "open Lean.Parser def x := parser! symbol \"foo\" 10 #check x"
#eval run "open Lean.Parser def x := tparser! symbol \"foo\" 0 #check x"
#eval run "def x : Nat := 1 #check x"
def g (x : Nat := zero) (y : Nat := one) (z : Nat := two) : Nat :=
x + y + z
def three := 3
#eval run "#check g"
#eval run "#check g (x := three) (z := zero)"
#eval run "#check g (y := three)"
#eval run "#check g (z := three)"
#eval run "#check g three (z := zero)"
#eval run "open Lean.Parser
@[termParser] def myParser : Lean.Parser.Parser := parser! oldCoe \"hi\"
#check myParser"
#eval run "#check (fun stx => if True then let e := stx; HasPure.pure e else HasPure.pure stx : Nat → Id Nat)"
#eval run "constant n : Nat #check n"
#eval fail "#check Nat.succ 'a'"
#eval run "universes u v #check Type (max u v)"
#eval run "universes u v #check Type (imax u v)"
#eval fail "namespace Boo def f (x : Nat) := x def s := 'a' #check (fun x => f x) s end Boo"
|
bd84acb762cf75e3ba8d35ef95c9ea621d4ca65d | bdd56e6eb0f467437e368d613de75299495d4054 | /src/category_theory/limits/shapes/pullbacks.lean | b8e26a1b9a3dcb7d946d49a5597fd6ee875c22a1 | [] | no_license | truong111000/formalabstracts | 49a04c268ccee136e48e24e9d5dcb6fedea4b53e | 93a89a5c05c6fbc23eb9b914b60dcc353e609cd2 | refs/heads/master | 1,589,551,767,824 | 1,555,708,723,000 | 1,555,708,723,000 | 182,326,292 | 0 | 0 | null | 1,555,708,332,000 | 1,555,708,331,000 | null | UTF-8 | Lean | false | false | 7,138 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import category_theory.eq_to_hom
import category_theory.limits.cones
open category_theory
namespace tactic
meta def case_bash : tactic unit :=
do l ← local_context,
r ← successes (l.reverse.map (λ h, cases h >> skip)),
when (r.empty) failed
end tactic
namespace category_theory.limits
universes u v w
local attribute [tidy] tactic.case_bash
@[derive decidable_eq] inductive walking_cospan : Type v
| left | right | one
@[derive decidable_eq] inductive walking_span : Type v
| zero | left | right
open walking_cospan
open walking_span
inductive walking_cospan_hom : walking_cospan → walking_cospan → Type v
| inl : walking_cospan_hom left one
| inr : walking_cospan_hom right one
| id : Π X : walking_cospan.{v}, walking_cospan_hom X X
inductive walking_span_hom : walking_span → walking_span → Type v
| fst : walking_span_hom zero left
| snd : walking_span_hom zero right
| id : Π X : walking_span.{v}, walking_span_hom X X
open walking_cospan_hom
open walking_span_hom
instance walking_cospan_category : small_category walking_cospan :=
{ hom := walking_cospan_hom,
id := walking_cospan_hom.id,
comp := λ X Y Z f g, match X, Y, Z, f, g with
| _, _ ,_, (id _), h := h
| _, _, _, inl, (id one) := inl
| _, _, _, inr, (id one) := inr
end }
instance walking_span_category : small_category walking_span :=
{ hom := walking_span_hom,
id := walking_span_hom.id,
comp := λ X Y Z f g, match X, Y, Z, f, g with
| _, _ ,_, (id _), h := h
| _, _, _, fst, (id left) := fst
| _, _, _, snd, (id right) := snd
end }
lemma walking_cospan_hom_id (X : walking_cospan.{v}) : walking_cospan_hom.id X = 𝟙 X := rfl
lemma walking_span_hom_id (X : walking_span.{v}) : walking_span_hom.id X = 𝟙 X := rfl
variables {C : Type u} [𝒞 : category.{v} C]
include 𝒞
def cospan {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : walking_cospan.{v} ⥤ C :=
{ obj := λ x, match x with
| left := X
| right := Y
| one := Z
end,
map := λ x y h, match x, y, h with
| _, _, (id _) := 𝟙 _
| _, _, inl := f
| _, _, inr := g
end }
def span {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : walking_span.{v} ⥤ C :=
{ obj := λ x, match x with
| zero := X
| left := Y
| right := Z
end,
map := λ x y h, match x, y, h with
| _, _, (id _) := 𝟙 _
| _, _, fst := f
| _, _, snd := g
end }
@[simp] lemma cospan_left {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) :
(cospan f g).obj walking_cospan.left = X := rfl
@[simp] lemma span_left {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) :
(span f g).obj walking_span.left = Y := rfl
@[simp] lemma cospan_right {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) :
(cospan f g).obj walking_cospan.right = Y := rfl
@[simp] lemma span_right {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) :
(span f g).obj walking_span.right = Z := rfl
@[simp] lemma cospan_one {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) :
(cospan f g).obj walking_cospan.one = Z := rfl
@[simp] lemma span_zero {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) :
(span f g).obj walking_span.zero = X := rfl
@[simp] lemma cospan_map_inl {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) :
(cospan f g).map walking_cospan_hom.inl = f := rfl
@[simp] lemma span_map_fst {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) :
(span f g).map walking_span_hom.fst = f := rfl
@[simp] lemma cospan_map_inr {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) :
(cospan f g).map walking_cospan_hom.inr = g := rfl
@[simp] lemma span_map_snd {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) :
(span f g).map walking_span_hom.snd = g := rfl
@[simp] lemma cospan_map_id {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (w : walking_cospan) :
(cospan f g).map (walking_cospan_hom.id w) = 𝟙 _ := rfl
@[simp] lemma span_map_id {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) (w : walking_span) :
(span f g).map (walking_span_hom.id w) = 𝟙 _ := rfl
variables {X Y Z : C}
attribute [simp] walking_cospan_hom_id walking_span_hom_id
section pullback
def square (f : X ⟶ Z) (g : Y ⟶ Z) := cone (cospan f g)
variables {f : X ⟶ Z} {g : Y ⟶ Z}
def square.π₁ (t : square f g) : t.X ⟶ X := t.π.app left
def square.π₂ (t : square f g) : t.X ⟶ Y := t.π.app right
def square.mk {W : C} (π₁ : W ⟶ X) (π₂ : W ⟶ Y)
(eq : π₁ ≫ f = π₂ ≫ g) :
square f g :=
{ X := W,
π :=
{ app := λ j, walking_cospan.cases_on j π₁ π₂ (π₁ ≫ f),
naturality' := λ j j' f, by cases f; obviously } }
def square.condition (t : square f g) : (square.π₁ t) ≫ f = (square.π₂ t) ≫ g :=
begin
erw [t.w inl, ← t.w inr], refl
end
end pullback
section pushout
def cosquare (f : X ⟶ Y) (g : X ⟶ Z) := cocone (span f g)
variables {f : X ⟶ Y} {g : X ⟶ Z}
def cosquare.ι₁ (t : cosquare f g) : Y ⟶ t.X := t.ι.app left
def cosquare.ι₂ (t : cosquare f g) : Z ⟶ t.X := t.ι.app right
def cosquare.mk {W : C} (ι₁ : Y ⟶ W) (ι₂ : Z ⟶ W)
(eq : f ≫ ι₁ = g ≫ ι₂) :
cosquare f g :=
{ X := W,
ι :=
{ app := λ j, walking_span.cases_on j (f ≫ ι₁) ι₁ ι₂,
naturality' := λ j j' f, by cases f; obviously } }
def cosquare.condition (t : cosquare f g) : f ≫ (cosquare.ι₁ t) = g ≫ (cosquare.ι₂ t) :=
begin
erw [t.w fst, ← t.w snd], refl
end
end pushout
def cone.of_square
{F : walking_cospan.{v} ⥤ C} (t : square (F.map inl) (F.map inr)) : cone F :=
{ X := t.X,
π :=
{ app := λ X, t.π.app X ≫ eq_to_hom (by tidy),
naturality' := λ j j' g,
begin
cases j; cases j'; cases g; dsimp; simp,
erw ← t.w inl, refl,
erw ← t.w inr, refl,
end } }.
@[simp] lemma cone.of_square_π
{F : walking_cospan.{v} ⥤ C} (t : square (F.map inl) (F.map inr)) (j):
(cone.of_square t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl
def cocone.of_cosquare
{F : walking_span.{v} ⥤ C} (t : cosquare (F.map fst) (F.map snd)) : cocone F :=
{ X := t.X,
ι :=
{ app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X,
naturality' := λ j j' g,
begin
cases j; cases j'; cases g; dsimp; simp,
erw ← t.w fst, refl,
erw ← t.w snd, refl,
end } }.
@[simp] lemma cocone.of_cosquare_ι
{F : walking_span.{v} ⥤ C} (t : cosquare (F.map fst) (F.map snd)) (j):
(cocone.of_cosquare t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl
def square.of_cone
{F : walking_cospan.{v} ⥤ C} (t : cone F) : square (F.map inl) (F.map inr) :=
{ X := t.X,
π :=
{ app := λ j, t.π.app j ≫ eq_to_hom (by tidy) } }
@[simp] lemma square.of_cone_π {F : walking_cospan.{v} ⥤ C} (t : cone F) (j) :
(square.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl
def cosquare.of_cocone
{F : walking_span.{v} ⥤ C} (t : cocone F) : cosquare (F.map fst) (F.map snd) :=
{ X := t.X,
ι :=
{ app := λ j, eq_to_hom (by tidy) ≫ t.ι.app j } }
@[simp] lemma cosquare.of_cocone_ι {F : walking_span.{v} ⥤ C} (t : cocone F) (j) :
(cosquare.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl
end category_theory.limits
|
e71811df93dea7bf3ada31ef77c4a3cab63c690a | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/jordan/basic.lean | 4dd058d744d60454bf77a6d8d1cbf6a6278f165e | [
"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 | 11,095 | lean | /-
Copyright (c) 2021 Christopher Hoskin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Christopher Hoskin
-/
import algebra.lie.of_associative
import algebra.ring.basic
/-!
# Jordan rings
Let `A` be a non-unital, non-associative ring. Then `A` is said to be a (commutative, linear) Jordan
ring if the multiplication is commutative and satisfies a weak associativity law known as the
Jordan Identity: for all `a` and `b` in `A`,
```
(a * b) * a^2 = a * (b * a^2)
```
i.e. the operators of multiplication by `a` and `a^2` commute.
A more general concept of a (non-commutative) Jordan ring can also be defined, as a
(non-commutative, non-associative) ring `A` where, for each `a` in `A`, the operators of left and
right multiplication by `a` and `a^2` commute.
A real Jordan algebra `A` can be introduced by
```lean
variables {A : Type*} [non_unital_non_assoc_ring A] [module ℝ A] [smul_comm_class ℝ A A]
[is_scalar_tower ℝ A A] [is_comm_jordan A]
```
## Main results
- `two_nsmul_lie_lmul_lmul_add_add_eq_zero` : Linearisation of the commutative Jordan axiom
## Implementation notes
We shall primarily be interested in linear Jordan algebras (i.e. over rings of characteristic not
two) leaving quadratic algebras to those better versed in that theory.
The conventional way to linearise the Jordan axiom is to equate coefficients (more formally, assume
that the axiom holds in all field extensions). For simplicity we use brute force algebraic expansion
and substitution instead.
## Motivation
Every Jordan algebra `A` has a triple product defined, for `a` `b` and `c` in `A` by
$$
{a\,b\,c} = (a * b) * c - (a * c) * b + a * (b * c).
$$
Via this triple product Jordan algebras are related to a number of other mathematical structures:
Jordan triples, partial Jordan triples, Jordan pairs and quadratic Jordan algebras. In addition to
their considerable algebraic interest ([mccrimmon2004]) these structures have been shown to have
deep connections to mathematical physics, functional analysis and differential geometry. For more
information about these connections the interested reader is referred to [alfsenshultz2003],
[chu2012], [friedmanscarr2005], [iordanescu2003] and [upmeier1987].
Every associative algebra can be equipped with a symmetrized multiplication (characterized by
`sym_alg.sym_mul_sym`) making it into a commutative Jordan algebra. Jordan algebras arising this way
are said to be special.
There are also exceptional Jordan algebras which can be shown not to be the symmetrization of any
associative algebra. The 3x3 matrices of octonions is the canonical example.
Non-commutative Jordan algebras have connections to the Vidav-Palmer theorem
[cabreragarciarodriguezpalacios2014].
## References
* [Cabrera García and Rodríguez Palacios, Non-associative normed algebras. Volume 1]
[cabreragarciarodriguezpalacios2014]
* [Hanche-Olsen and Størmer, Jordan Operator Algebras][hancheolsenstormer1984]
* [McCrimmon, A taste of Jordan algebras][mccrimmon2004]
-/
variables (A : Type*)
/-- A (non-commutative) Jordan multiplication. -/
class is_jordan [has_mul A] :=
(lmul_comm_rmul : ∀ a b : A, (a * b) * a = a * (b * a))
(lmul_lmul_comm_lmul : ∀ a b : A, (a * a) * (a * b) = a * ((a * a) * b))
(lmul_lmul_comm_rmul : ∀ a b : A, (a * a) * (b * a) = ((a * a) * b) * a)
(lmul_comm_rmul_rmul : ∀ a b : A, (a * b) * (a * a) = a * (b * (a * a)))
(rmul_comm_rmul_rmul : ∀ a b : A, (b * a) * (a * a) = (b * (a * a)) * a)
/-- A commutative Jordan multipication -/
class is_comm_jordan [has_mul A] :=
(mul_comm : ∀ a b : A, a * b = b * a)
(lmul_comm_rmul_rmul : ∀ a b : A, (a * b) * (a * a) = a * (b * (a * a)))
/-- A (commutative) Jordan multiplication is also a Jordan multipication -/
@[priority 100] -- see Note [lower instance priority]
instance is_comm_jordan.to_is_jordan [has_mul A] [is_comm_jordan A] : is_jordan A :=
{ lmul_comm_rmul := λ a b, by rw [is_comm_jordan.mul_comm, is_comm_jordan.mul_comm a b],
lmul_lmul_comm_lmul := λ a b, by rw [is_comm_jordan.mul_comm (a * a) (a * b),
is_comm_jordan.lmul_comm_rmul_rmul, is_comm_jordan.mul_comm b (a * a)],
lmul_comm_rmul_rmul := is_comm_jordan.lmul_comm_rmul_rmul,
lmul_lmul_comm_rmul := λ a b, by rw [is_comm_jordan.mul_comm (a * a) (b * a),
is_comm_jordan.mul_comm b a, is_comm_jordan.lmul_comm_rmul_rmul, is_comm_jordan.mul_comm,
is_comm_jordan.mul_comm b (a * a)],
rmul_comm_rmul_rmul := λ a b, by rw [is_comm_jordan.mul_comm b a,
is_comm_jordan.lmul_comm_rmul_rmul, is_comm_jordan.mul_comm], }
/-- Semigroup multiplication satisfies the (non-commutative) Jordan axioms-/
@[priority 100] -- see Note [lower instance priority]
instance semigroup.is_jordan [semigroup A] : is_jordan A :=
{ lmul_comm_rmul := λ a b, by rw mul_assoc,
lmul_lmul_comm_lmul := λ a b, by rw [mul_assoc, mul_assoc],
lmul_comm_rmul_rmul := λ a b, by rw [mul_assoc],
lmul_lmul_comm_rmul := λ a b, by rw [←mul_assoc],
rmul_comm_rmul_rmul := λ a b, by rw [← mul_assoc, ← mul_assoc], }
@[priority 100] -- see Note [lower instance priority]
instance comm_semigroup.is_comm_jordan [comm_semigroup A] : is_comm_jordan A :=
{ mul_comm := mul_comm,
lmul_comm_rmul_rmul := λ a b, mul_assoc _ _ _, }
local notation `L` := add_monoid.End.mul_left
local notation `R` := add_monoid.End.mul_right
/-!
The Jordan axioms can be expressed in terms of commuting multiplication operators.
-/
section commute
variables {A} [non_unital_non_assoc_ring A] [is_jordan A]
@[simp] lemma commute_lmul_rmul (a : A) : commute (L a) (R a) :=
add_monoid_hom.ext $ λ b, (is_jordan.lmul_comm_rmul _ _).symm
@[simp] lemma commute_lmul_lmul_sq (a : A) : commute (L a) (L (a * a)) :=
add_monoid_hom.ext $ λ b, (is_jordan.lmul_lmul_comm_lmul _ _).symm
@[simp] lemma commute_lmul_rmul_sq (a : A) : commute (L a) (R (a * a)) :=
add_monoid_hom.ext $ λ b, (is_jordan.lmul_comm_rmul_rmul _ _).symm
@[simp] lemma commute_lmul_sq_rmul (a : A) : commute (L (a * a)) (R a) :=
add_monoid_hom.ext $ λ b, (is_jordan.lmul_lmul_comm_rmul _ _)
@[simp] lemma commute_rmul_rmul_sq (a : A) : commute (R a) (R (a * a)) :=
add_monoid_hom.ext $ λ b, (is_jordan.rmul_comm_rmul_rmul _ _).symm
end commute
variables {A} [non_unital_non_assoc_ring A] [is_comm_jordan A]
/-!
The endomorphisms on an additive monoid `add_monoid.End` form a `ring`, and this may be equipped
with a Lie Bracket via `ring.has_bracket`.
-/
lemma two_nsmul_lie_lmul_lmul_add_eq_lie_lmul_lmul_add (a b : A) :
2•(⁅L a, L (a * b)⁆ + ⁅L b, L (b * a)⁆) = ⁅L (a * a), L b⁆ + ⁅L (b * b), L a⁆ :=
begin
suffices : 2 • ⁅L a, L (a * b)⁆ + 2 • ⁅L b, L (b * a)⁆ + ⁅L b, L (a * a)⁆ + ⁅L a, L (b * b)⁆ = 0,
{ rwa [← sub_eq_zero, ← sub_sub, sub_eq_add_neg, sub_eq_add_neg, lie_skew, lie_skew, nsmul_add] },
convert (commute_lmul_lmul_sq (a + b)).lie_eq,
simp only [add_mul, mul_add, map_add, lie_add, add_lie, is_comm_jordan.mul_comm b a,
(commute_lmul_lmul_sq a).lie_eq, (commute_lmul_lmul_sq b).lie_eq],
abel,
end
lemma two_nsmul_lie_lmul_lmul_add_add_eq_zero (a b c : A) :
2•(⁅L a, L (b * c)⁆ + ⁅L b, L (c * a)⁆ + ⁅L c, L (a * b)⁆) = 0 :=
begin
symmetry,
calc 0 = ⁅L (a + b + c), L ((a + b + c) * (a + b + c))⁆ :
by rw (commute_lmul_lmul_sq (a + b + c)).lie_eq
... = ⁅L a + L b + L c,
L (a * a) + L (a * b) + L (a * c) + (L (b * a) + L (b * b) + L (b * c))
+ (L (c * a) + L (c * b) + L (c * c))⁆ :
by rw [add_mul, add_mul, mul_add, mul_add, mul_add, mul_add, mul_add, mul_add,
map_add, map_add, map_add, map_add, map_add, map_add, map_add, map_add, map_add, map_add]
... = ⁅L a + L b + L c,
L (a * a) + L (a * b) + L (c * a) + (L (a * b) + L (b * b) + L (b * c))
+ (L (c * a) + L (b * c) + L (c * c))⁆ :
by rw [is_comm_jordan.mul_comm b a, is_comm_jordan.mul_comm c a, is_comm_jordan.mul_comm c b]
... = ⁅L a + L b + L c, L (a * a) + L (b * b) + L (c * c) + 2•L (a * b) + 2•L (c * a)
+ 2•L (b * c) ⁆ :
by {rw [two_smul, two_smul, two_smul],
simp only [lie_add, add_lie, commute_lmul_lmul_sq, zero_add, add_zero], abel}
... = ⁅L a, L (a * a)⁆ + ⁅L a, L (b * b)⁆ + ⁅L a, L (c * c)⁆ + ⁅L a, 2•L (a * b)⁆
+ ⁅L a, 2•L(c * a)⁆ + ⁅L a, 2•L (b * c)⁆
+ (⁅L b, L (a * a)⁆ + ⁅L b, L (b * b)⁆ + ⁅L b, L (c * c)⁆ + ⁅L b, 2•L (a * b)⁆
+ ⁅L b, 2•L (c * a)⁆ + ⁅L b, 2•L (b * c)⁆)
+ (⁅L c, L (a * a)⁆ + ⁅L c, L (b * b)⁆ + ⁅L c, L (c * c)⁆ + ⁅L c, 2•L (a * b)⁆
+ ⁅L c, 2•L (c * a)⁆ + ⁅L c, 2•L (b * c)⁆) :
by rw [add_lie, add_lie, lie_add, lie_add, lie_add, lie_add, lie_add, lie_add, lie_add, lie_add,
lie_add, lie_add, lie_add, lie_add, lie_add, lie_add, lie_add]
... = ⁅L a, L (b * b)⁆ + ⁅L a, L (c * c)⁆ + ⁅L a, 2•L (a * b)⁆ + ⁅L a, 2•L (c * a)⁆
+ ⁅L a, 2•L (b * c)⁆
+ (⁅L b, L (a * a)⁆ + ⁅L b, L (c * c)⁆ + ⁅L b, 2•L (a * b)⁆ + ⁅L b, 2•L (c * a)⁆
+ ⁅L b, 2•L (b * c)⁆)
+ (⁅L c, L (a * a)⁆ + ⁅L c, L (b * b)⁆ + ⁅L c, 2•L (a * b)⁆ + ⁅L c, 2•L (c * a)⁆
+ ⁅L c, 2•L (b * c)⁆) :
by rw [(commute_lmul_lmul_sq a).lie_eq, (commute_lmul_lmul_sq b).lie_eq,
(commute_lmul_lmul_sq c).lie_eq, zero_add, add_zero, add_zero]
... = ⁅L a, L (b * b)⁆ + ⁅L a, L (c * c)⁆ + 2•⁅L a, L (a * b)⁆ + 2•⁅L a, L (c * a)⁆
+ 2•⁅L a, L (b * c)⁆
+ (⁅L b, L (a * a)⁆ + ⁅L b, L (c * c)⁆ + 2•⁅L b, L (a * b)⁆ + 2•⁅L b, L (c * a)⁆
+ 2•⁅L b, L (b * c)⁆)
+ (⁅L c, L (a * a)⁆ + ⁅L c, L (b * b)⁆ + 2•⁅L c, L (a * b)⁆ + 2•⁅L c, L (c * a)⁆
+ 2•⁅L c, L (b * c)⁆) :
by simp only [lie_nsmul]
... = (⁅L a, L (b * b)⁆+ ⁅L b, L (a * a)⁆ + 2•(⁅L a, L (a * b)⁆ + ⁅L b, L (a * b)⁆))
+ (⁅L a, L (c * c)⁆ + ⁅L c, L (a * a)⁆ + 2•(⁅L a, L (c * a)⁆ + ⁅L c, L (c * a)⁆))
+ (⁅L b, L (c * c)⁆ + ⁅L c, L (b * b)⁆ + 2•(⁅L b, L (b * c)⁆ + ⁅L c, L (b * c)⁆))
+ (2•⁅L a, L (b * c)⁆ + 2•⁅L b, L (c * a)⁆ + 2•⁅L c, L (a * b)⁆) : by abel
... = 2•⁅L a, L (b * c)⁆ + 2•⁅L b, L (c * a)⁆ + 2•⁅L c, L (a * b)⁆ :
by begin
rw add_left_eq_self,
nth_rewrite 1 is_comm_jordan.mul_comm a b,
nth_rewrite 0 is_comm_jordan.mul_comm c a,
nth_rewrite 1 is_comm_jordan.mul_comm b c,
rw [two_nsmul_lie_lmul_lmul_add_eq_lie_lmul_lmul_add,
two_nsmul_lie_lmul_lmul_add_eq_lie_lmul_lmul_add,
two_nsmul_lie_lmul_lmul_add_eq_lie_lmul_lmul_add,
← lie_skew (L (a * a)), ← lie_skew (L (b * b)), ← lie_skew (L (c * c)),
← lie_skew (L (a * a)), ← lie_skew (L (b * b)), ← lie_skew (L (c * c))],
abel,
end
... = 2•(⁅L a, L (b * c)⁆ + ⁅L b, L (c * a)⁆ + ⁅L c, L (a * b)⁆) : by rw [nsmul_add, nsmul_add]
end
|
ac9e21d884e0a457de31b4748356a821421848ee | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/preadditive/Mat.lean | c9265e87ecf09e44315fb0d3dbe4ca7e12b75dc9 | [
"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 | 18,771 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.big_operators.basic
import algebra.big_operators.pi
import category_theory.limits.shapes.biproducts
import category_theory.preadditive
import category_theory.preadditive.additive_functor
import data.matrix.dmatrix
import data.matrix.basic
import category_theory.Fintype
import category_theory.preadditive.single_obj
import algebra.opposites
/-!
# Matrices over a category.
When `C` is a preadditive category, `Mat_ C` is the preadditive category
whose objects are finite tuples of objects in `C`, and
whose morphisms are matrices of morphisms from `C`.
There is a functor `Mat_.embedding : C ⥤ Mat_ C` sending morphisms to one-by-one matrices.
`Mat_ C` has finite biproducts.
## The additive envelope
We show that this construction is the "additive envelope" of `C`,
in the sense that any additive functor `F : C ⥤ D` to a category `D` with biproducts
lifts to a functor `Mat_.lift F : Mat_ C ⥤ D`,
Moreover, this functor is unique (up to natural isomorphisms) amongst functors `L : Mat_ C ⥤ D`
such that `embedding C ⋙ L ≅ F`.
(As we don't have 2-category theory, we can't explicitly state that `Mat_ C` is
the initial object in the 2-category of categories under `C` which have biproducts.)
As a consequence, when `C` already has finite biproducts we have `Mat_ C ≌ C`.
## Future work
We should provide a more convenient `Mat R`, when `R` is a ring,
as a category with objects `n : FinType`,
and whose morphisms are matrices with components in `R`.
Ideally this would conveniently interact with both `Mat_` and `matrix`.
-/
open category_theory category_theory.preadditive
open_locale big_operators
noncomputable theory
namespace category_theory
universes w v₁ v₂ u₁ u₂
variables (C : Type u₁) [category.{v₁} C] [preadditive C]
/--
An object in `Mat_ C` is a finite tuple of objects in `C`.
-/
structure Mat_ : Type (max (v₁+1) u₁) :=
(ι : Type v₁)
[F : fintype ι]
[D : decidable_eq ι]
(X : ι → C)
attribute [instance] Mat_.F Mat_.D
namespace Mat_
variables {C}
/-- A morphism in `Mat_ C` is a dependently typed matrix of morphisms. -/
@[nolint has_inhabited_instance]
def hom (M N : Mat_ C) : Type v₁ := dmatrix M.ι N.ι (λ i j, M.X i ⟶ N.X j)
namespace hom
/-- The identity matrix consists of identity morphisms on the diagonal, and zeros elsewhere. -/
def id (M : Mat_ C) : hom M M := λ i j, if h : i = j then eq_to_hom (congr_arg M.X h) else 0
/-- Composition of matrices using matrix multiplication. -/
def comp {M N K : Mat_ C} (f : hom M N) (g : hom N K) : hom M K :=
λ i k, ∑ j : N.ι, f i j ≫ g j k
end hom
section
local attribute [simp] hom.id hom.comp
instance : category.{v₁} (Mat_ C) :=
{ hom := hom,
id := hom.id,
comp := λ M N K f g, f.comp g,
id_comp' := λ M N f, by simp [dite_comp],
comp_id' := λ M N f, by simp [comp_dite],
assoc' := λ M N K L f g h, begin
ext i k,
simp_rw [hom.comp, sum_comp, comp_sum, category.assoc],
rw finset.sum_comm,
end, }.
lemma id_def (M : Mat_ C) :
(𝟙 M : hom M M) = λ i j, if h : i = j then eq_to_hom (congr_arg M.X h) else 0 :=
rfl
lemma id_apply (M : Mat_ C) (i j : M.ι) :
(𝟙 M : hom M M) i j = if h : i = j then eq_to_hom (congr_arg M.X h) else 0 :=
rfl
@[simp] lemma id_apply_self (M : Mat_ C) (i : M.ι) :
(𝟙 M : hom M M) i i = 𝟙 _ :=
by simp [id_apply]
@[simp] lemma id_apply_of_ne (M : Mat_ C) (i j : M.ι) (h : i ≠ j) :
(𝟙 M : hom M M) i j = 0 :=
by simp [id_apply, h]
lemma comp_def {M N K : Mat_ C} (f : M ⟶ N) (g : N ⟶ K) :
(f ≫ g) = λ i k, ∑ j : N.ι, f i j ≫ g j k := rfl
@[simp] lemma comp_apply {M N K : Mat_ C} (f : M ⟶ N) (g : N ⟶ K) (i k) :
(f ≫ g) i k = ∑ j : N.ι, f i j ≫ g j k := rfl
instance (M N : Mat_ C) : inhabited (M ⟶ N) := ⟨λ i j, (0 : M.X i ⟶ N.X j)⟩
end
instance : preadditive (Mat_ C) :=
{ hom_group := λ M N, by { change add_comm_group (dmatrix M.ι N.ι _), apply_instance, },
add_comp' := λ M N K f f' g, by { ext, simp [finset.sum_add_distrib], },
comp_add' := λ M N K f g g', by { ext, simp [finset.sum_add_distrib], }, }
@[simp] lemma add_apply {M N : Mat_ C} (f g : M ⟶ N) (i j) : (f + g) i j = f i j + g i j := rfl
open category_theory.limits
/--
We now prove that `Mat_ C` has finite biproducts.
Be warned, however, that `Mat_ C` is not necessarily Krull-Schmidt,
and so the internal indexing of a biproduct may have nothing to do with the external indexing,
even though the construction we give uses a sigma type.
See however `iso_biproduct_embedding`.
-/
instance has_finite_biproducts : has_finite_biproducts (Mat_ C) :=
{ has_biproducts_of_shape := λ J 𝒟 ℱ, by exactI
{ has_biproduct := λ f,
has_biproduct_of_total
{ X := ⟨Σ j : J, (f j).ι, λ p, (f p.1).X p.2⟩,
π := λ j x y,
begin
dsimp at x ⊢,
refine if h : x.1 = j then _ else 0,
refine if h' : (@eq.rec J x.1 (λ j, (f j).ι) x.2 _ h) = y then _ else 0,
apply eq_to_hom,
substs h h', -- Notice we were careful not to use `subst` until we had a goal in `Prop`.
end,
ι := λ j x y,
begin
dsimp at y ⊢,
refine if h : y.1 = j then _ else 0,
refine if h' : (@eq.rec J y.1 (λ j, (f j).ι) y.2 _ h) = x then _ else 0,
apply eq_to_hom,
substs h h',
end,
ι_π := λ j j',
begin
ext x y,
dsimp,
simp_rw [dite_comp, comp_dite],
simp only [if_t_t, dite_eq_ite, dif_ctx_congr, limits.comp_zero, limits.zero_comp,
eq_to_hom_trans, finset.sum_congr],
erw finset.sum_sigma,
dsimp,
simp only [if_congr, if_true, dif_ctx_congr, finset.sum_dite_irrel, finset.mem_univ,
finset.sum_const_zero, finset.sum_congr, finset.sum_dite_eq'],
split_ifs with h h',
{ substs h h',
simp only [category_theory.eq_to_hom_refl, category_theory.Mat_.id_apply_self], },
{ subst h,
simp only [id_apply_of_ne _ _ _ h', category_theory.eq_to_hom_refl], },
{ refl, },
end, }
begin
dsimp,
funext i₁,
dsimp at i₁ ⊢,
rcases i₁ with ⟨j₁, i₁⟩,
-- I'm not sure why we can't just `simp` by `finset.sum_apply`: something doesn't quite match
convert finset.sum_apply _ _ _ using 1,
{ refl, },
{ apply heq_of_eq,
symmetry,
funext i₂,
rcases i₂ with ⟨j₂, i₂⟩,
simp only [comp_apply, dite_comp, comp_dite,
if_t_t, dite_eq_ite, if_congr, if_true, dif_ctx_congr,
finset.sum_dite_irrel, finset.sum_dite_eq, finset.mem_univ, finset.sum_const_zero,
finset.sum_congr, finset.sum_dite_eq, finset.sum_apply,
limits.comp_zero, limits.zero_comp, eq_to_hom_trans, Mat_.id_apply],
by_cases h : j₁ = j₂,
{ subst h, simp, },
{ simp [h], }, },
end }}.
end Mat_
namespace functor
variables {C} {D : Type*} [category.{v₁} D] [preadditive D]
local attribute [simp] Mat_.id_apply
/--
A functor induces a functor of matrix categories.
-/
@[simps]
def map_Mat_ (F : C ⥤ D) [functor.additive F] : Mat_ C ⥤ Mat_ D :=
{ obj := λ M, ⟨M.ι, λ i, F.obj (M.X i)⟩,
map := λ M N f i j, F.map (f i j),
map_comp' := λ M N K f g, by { ext i k, simp,}, }
/--
The identity functor induces the identity functor on matrix categories.
-/
@[simps]
def map_Mat_id : (𝟭 C).map_Mat_ ≅ 𝟭 (Mat_ C) :=
nat_iso.of_components (λ M, eq_to_iso (by { cases M, refl, }))
(λ M N f, begin
ext i j,
cases M, cases N,
simp [comp_dite, dite_comp],
end)
/--
Composite functors induce composite functors on matrix categories.
-/
@[simps]
def map_Mat_comp {E : Type*} [category.{v₁} E] [preadditive E]
(F : C ⥤ D) [functor.additive F] (G : D ⥤ E) [functor.additive G] :
(F ⋙ G).map_Mat_ ≅ F.map_Mat_ ⋙ G.map_Mat_ :=
nat_iso.of_components (λ M, eq_to_iso (by { cases M, refl, }))
(λ M N f, begin
ext i j,
cases M, cases N,
simp [comp_dite, dite_comp],
end)
end functor
namespace Mat_
variables (C)
/-- The embedding of `C` into `Mat_ C` as one-by-one matrices.
(We index the summands by `punit`.) -/
@[simps]
def embedding : C ⥤ Mat_ C :=
{ obj := λ X, ⟨punit, λ _, X⟩,
map := λ X Y f, λ _ _, f,
map_id' := λ X, by { ext ⟨⟩ ⟨⟩, simp, },
map_comp' := λ X Y Z f g, by { ext ⟨⟩ ⟨⟩, simp, }, }
namespace embedding
instance : faithful (embedding C) :=
{ map_injective' := λ X Y f g h, congr_fun (congr_fun h punit.star) punit.star, }
instance : full (embedding C) :=
{ preimage := λ X Y f, f punit.star punit.star, }
instance : functor.additive (embedding C) := {}
end embedding
instance [inhabited C] : inhabited (Mat_ C) := ⟨(embedding C).obj default⟩
open category_theory.limits
variables {C}
/--
Every object in `Mat_ C` is isomorphic to the biproduct of its summands.
-/
@[simps]
def iso_biproduct_embedding (M : Mat_ C) : M ≅ ⨁ (λ i, (embedding C).obj (M.X i)) :=
{ hom := biproduct.lift (λ i j k, if h : j = i then eq_to_hom (congr_arg M.X h) else 0),
inv := biproduct.desc (λ i j k, if h : i = k then eq_to_hom (congr_arg M.X h) else 0),
hom_inv_id' :=
begin
simp only [biproduct.lift_desc],
funext i,
dsimp,
convert finset.sum_apply _ _ _,
{ dsimp, refl, },
{ apply heq_of_eq,
symmetry,
funext j,
simp only [finset.sum_apply],
dsimp,
simp [dite_comp, comp_dite, Mat_.id_apply], }
end,
inv_hom_id' :=
begin
apply biproduct.hom_ext,
intro i,
apply biproduct.hom_ext',
intro j,
simp only [category.id_comp, category.assoc,
biproduct.lift_π, biproduct.ι_desc_assoc, biproduct.ι_π],
ext ⟨⟩ ⟨⟩,
simp [dite_comp, comp_dite],
split_ifs,
{ subst h, simp, },
{ simp [h], },
end, }.
variables {D : Type u₁} [category.{v₁} D] [preadditive D]
/-- Every `M` is a direct sum of objects from `C`, and `F` preserves biproducts. -/
@[simps]
def additive_obj_iso_biproduct (F : Mat_ C ⥤ D) [functor.additive F] (M : Mat_ C) :
F.obj M ≅ ⨁ (λ i, F.obj ((embedding C).obj (M.X i))) :=
(F.map_iso (iso_biproduct_embedding M)) ≪≫ (F.map_biproduct _)
variables [has_finite_biproducts D]
@[reassoc] lemma additive_obj_iso_biproduct_naturality (F : Mat_ C ⥤ D) [functor.additive F]
{M N : Mat_ C} (f : M ⟶ N) :
F.map f ≫ (additive_obj_iso_biproduct F N).hom =
(additive_obj_iso_biproduct F M).hom ≫
biproduct.matrix (λ i j, F.map ((embedding C).map (f i j))) :=
begin
-- This is disappointingly tedious.
ext,
simp only [additive_obj_iso_biproduct_hom, category.assoc, biproduct.lift_π, functor.map_bicone_π,
biproduct.bicone_π, biproduct.lift_matrix],
dsimp [embedding],
simp only [←F.map_comp, biproduct.lift_π, biproduct.matrix_π, category.assoc],
simp only [←F.map_comp, ←F.map_sum, biproduct.lift_desc, biproduct.lift_π_assoc, comp_sum],
simp only [comp_def, comp_dite, comp_zero, finset.sum_dite_eq', finset.mem_univ, if_true],
dsimp,
simp only [finset.sum_singleton, dite_comp, zero_comp],
congr,
symmetry,
convert finset.sum_fn _ _, -- It's hard to use this as a simp lemma!
simp only [finset.sum_fn, finset.sum_dite_eq],
ext,
simp,
end
@[reassoc] lemma additive_obj_iso_biproduct_naturality' (F : Mat_ C ⥤ D) [functor.additive F]
{M N : Mat_ C} (f : M ⟶ N) :
(additive_obj_iso_biproduct F M).inv ≫ F.map f =
biproduct.matrix (λ i j, F.map ((embedding C).map (f i j)) : _) ≫
(additive_obj_iso_biproduct F N).inv :=
by rw [iso.inv_comp_eq, ←category.assoc, iso.eq_comp_inv, additive_obj_iso_biproduct_naturality]
/-- Any additive functor `C ⥤ D` to a category `D` with finite biproducts extends to
a functor `Mat_ C ⥤ D`. -/
@[simps]
def lift (F : C ⥤ D) [functor.additive F] : Mat_ C ⥤ D :=
{ obj := λ X, ⨁ (λ i, F.obj (X.X i)),
map := λ X Y f, biproduct.matrix (λ i j, F.map (f i j)),
map_id' := λ X, begin
ext i j,
by_cases h : i = j,
{ subst h, simp, },
{ simp [h, Mat_.id_apply], },
end,
map_comp' := λ X Y Z f g, by { ext i j, simp, }, }.
instance lift_additive (F : C ⥤ D) [functor.additive F] : functor.additive (lift F) := {}
/-- An additive functor `C ⥤ D` factors through its lift to `Mat_ C ⥤ D`. -/
@[simps]
def embedding_lift_iso (F : C ⥤ D) [functor.additive F] : embedding C ⋙ lift F ≅ F :=
nat_iso.of_components (λ X,
{ hom := biproduct.desc (λ P, 𝟙 (F.obj X)),
inv := biproduct.lift (λ P, 𝟙 (F.obj X)), })
(λ X Y f, begin
dsimp,
ext,
simp only [category.id_comp, biproduct.ι_desc_assoc],
erw biproduct.ι_matrix_assoc, -- Not sure why this doesn't fire via `simp`.
simp,
end).
/--
`Mat_.lift F` is the unique additive functor `L : Mat_ C ⥤ D` such that `F ≅ embedding C ⋙ L`.
-/
def lift_unique (F : C ⥤ D) [functor.additive F] (L : Mat_ C ⥤ D) [functor.additive L]
(α : embedding C ⋙ L ≅ F) :
L ≅ lift F :=
nat_iso.of_components
(λ M, (additive_obj_iso_biproduct L M) ≪≫
(biproduct.map_iso (λ i, α.app (M.X i))) ≪≫
(biproduct.map_iso (λ i, (embedding_lift_iso F).symm.app (M.X i))) ≪≫
(additive_obj_iso_biproduct (lift F) M).symm)
(λ M N f, begin
dsimp only [iso.trans_hom, iso.symm_hom, biproduct.map_iso_hom],
simp only [additive_obj_iso_biproduct_naturality_assoc],
simp only [biproduct.matrix_map_assoc, category.assoc],
simp only [additive_obj_iso_biproduct_naturality'],
simp only [biproduct.map_matrix_assoc, category.assoc],
congr,
ext j k ⟨⟩,
dsimp, simp,
convert α.hom.naturality (f j k),
erw [biproduct.matrix_π],
simp,
end).
-- TODO is there some uniqueness statement for the natural isomorphism in `lift_unique`?
/-- Two additive functors `Mat_ C ⥤ D` are naturally isomorphic if
their precompositions with `embedding C` are naturally isomorphic as functors `C ⥤ D`. -/
@[ext]
def ext {F G : Mat_ C ⥤ D} [functor.additive F] [functor.additive G]
(α : embedding C ⋙ F ≅ embedding C ⋙ G) : F ≅ G :=
(lift_unique (embedding C ⋙ G) _ α) ≪≫ (lift_unique _ _ (iso.refl _)).symm
/--
Natural isomorphism needed in the construction of `equivalence_self_of_has_finite_biproducts`.
-/
def equivalence_self_of_has_finite_biproducts_aux [has_finite_biproducts C] :
embedding C ⋙ 𝟭 (Mat_ C) ≅ embedding C ⋙ lift (𝟭 C) ⋙ embedding C :=
functor.right_unitor _ ≪≫
(functor.left_unitor _).symm ≪≫
(iso_whisker_right (embedding_lift_iso _).symm _) ≪≫
functor.associator _ _ _
/--
A preadditive category that already has finite biproducts is equivalent to its additive envelope.
Note that we only prove this for a large category;
otherwise there are universe issues that I haven't attempted to sort out.
-/
def equivalence_self_of_has_finite_biproducts
(C : Type (u₁+1)) [large_category C] [preadditive C] [has_finite_biproducts C] :
Mat_ C ≌ C :=
equivalence.mk -- I suspect this is already an adjoint equivalence, but it seems painful to verify.
(lift (𝟭 C))
(embedding C)
(ext equivalence_self_of_has_finite_biproducts_aux)
(embedding_lift_iso (𝟭 C))
@[simp] lemma equivalence_self_of_has_finite_biproducts_functor
{C : Type (u₁+1)} [large_category C] [preadditive C] [has_finite_biproducts C] :
(equivalence_self_of_has_finite_biproducts C).functor = lift (𝟭 C) :=
rfl
@[simp] lemma equivalence_self_of_has_finite_biproducts_inverse
{C : Type (u₁+1)} [large_category C] [preadditive C] [has_finite_biproducts C] :
(equivalence_self_of_has_finite_biproducts C).inverse = embedding C :=
rfl
end Mat_
universe u
/-- A type synonym for `Fintype`, which we will equip with a category structure
where the morphisms are matrices with components in `R`. -/
@[nolint unused_arguments, derive inhabited]
def Mat (R : Type u) := Fintype.{u}
instance (R : Type u) : has_coe_to_sort (Mat R) (Type u) := bundled.has_coe_to_sort
open_locale classical matrix
instance (R : Type u) [semiring R] : category (Mat R) :=
{ hom := λ X Y, matrix X Y R,
id := λ X, 1,
comp := λ X Y Z f g, f ⬝ g,
assoc' := by { intros, simp [matrix.mul_assoc], }, }
namespace Mat
section
variables (R : Type u) [semiring R]
lemma id_def (M : Mat R) :
𝟙 M = λ i j, if h : i = j then 1 else 0 :=
rfl
lemma id_apply (M : Mat R) (i j : M) :
(𝟙 M : matrix M M R) i j = if h : i = j then 1 else 0 :=
rfl
@[simp] lemma id_apply_self (M : Mat R) (i : M) :
(𝟙 M : matrix M M R) i i = 1 :=
by simp [id_apply]
@[simp] lemma id_apply_of_ne (M : Mat R) (i j : M) (h : i ≠ j) :
(𝟙 M : matrix M M R) i j = 0 :=
by simp [id_apply, h]
lemma comp_def {M N K : Mat R} (f : M ⟶ N) (g : N ⟶ K) :
(f ≫ g) = λ i k, ∑ j : N, f i j * g j k := rfl
@[simp] lemma comp_apply {M N K : Mat R} (f : M ⟶ N) (g : N ⟶ K) (i k) :
(f ≫ g) i k = ∑ j : N, f i j * g j k := rfl
instance (M N : Mat R) : inhabited (M ⟶ N) := ⟨λ (i : M) (j : N), (0 : R)⟩
end
variables (R : Type u) [ring R]
open opposite
/-- Auxiliary definition for `category_theory.Mat.equivalence_single_obj`. -/
@[simps]
def equivalence_single_obj_inverse : Mat_ (single_obj Rᵐᵒᵖ) ⥤ Mat R :=
{ obj := λ X, Fintype.of X.ι,
map := λ X Y f i j, mul_opposite.unop (f i j),
map_id' := λ X, by { ext i j, simp [id_def, Mat_.id_def], split_ifs; refl, }, }
instance : faithful (equivalence_single_obj_inverse R) :=
{ map_injective' := λ X Y f g w, begin
ext i j,
apply_fun mul_opposite.unop using mul_opposite.unop_injective,
exact (congr_fun (congr_fun w i) j),
end }
instance : full (equivalence_single_obj_inverse R) :=
{ preimage := λ X Y f i j, mul_opposite.op (f i j), }
instance : ess_surj (equivalence_single_obj_inverse R) :=
{ mem_ess_image := λ X,
⟨{ ι := X, X := λ _, punit.star }, ⟨eq_to_iso (by { dsimp, cases X, congr, })⟩⟩, }
/-- The categorical equivalence between the category of matrices over a ring,
and the category of matrices over that ring considered as a single-object category. -/
def equivalence_single_obj : Mat R ≌ Mat_ (single_obj Rᵐᵒᵖ) :=
begin
haveI := equivalence.of_fully_faithfully_ess_surj (equivalence_single_obj_inverse R),
exact (equivalence_single_obj_inverse R).as_equivalence.symm,
end
instance : preadditive (Mat R) :=
{ add_comp' := by { intros, ext, simp [add_mul, finset.sum_add_distrib], },
comp_add' := by { intros, ext, simp [mul_add, finset.sum_add_distrib], }, }
-- TODO show `Mat R` has biproducts, and that `biprod.map` "is" forming a block diagonal matrix.
end Mat
end category_theory
|
25fe214620c9065941b7ed91ad53ba685f344e8c | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/limits/constructions/over/default_auto.lean | 93ddf759c52e088677f895da01f2c10bf6b7e615 | [] | 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,341 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Reid Barton, Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.limits.constructions.over.products
import Mathlib.category_theory.limits.constructions.over.connected
import Mathlib.category_theory.limits.constructions.limits_of_products_and_equalizers
import Mathlib.category_theory.limits.constructions.equalizers
import Mathlib.PostPort
universes v u
namespace Mathlib
/-!
# Limits in the over category
Declare instances for limits in the over category: If `C` has finite wide pullbacks, `over B` has
finite limits, and if `C` has arbitrary wide pullbacks then `over B` has limits.
-/
namespace category_theory.over
/-- Make sure we can derive pullbacks in `over B`. -/
/-- Make sure we can derive equalizers in `over B`. -/
protected instance has_finite_limits {C : Type u} [category C] {B : C}
[limits.has_finite_wide_pullbacks C] : limits.has_finite_limits (over B) :=
limits.finite_limits_from_equalizers_and_finite_products
protected instance has_limits {C : Type u} [category C] {B : C} [limits.has_wide_pullbacks C] :
limits.has_limits (over B) :=
limits.limits_from_equalizers_and_products
end Mathlib |
88d8d20dd3e2045c687976f9b39cd29920b62015 | 5fbbd711f9bfc21ee168f46a4be146603ece8835 | /lean/natural_number_game/inequality/10.lean | 477d27845428ab74ee65aec098b7c691b1f67632 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | goedel-gang/maths | 22596f71e3fde9c088e59931f128a3b5efb73a2c | a20a6f6a8ce800427afd595c598a5ad43da1408d | refs/heads/master | 1,623,055,941,960 | 1,621,599,441,000 | 1,621,599,441,000 | 169,335,840 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 95 | lean | lemma le_succ_self (a : mynat) : a ≤ succ a :=
begin
use 1,
exact succ_eq_add_one a,
end
|
ff16cf2c7304b33787eed6586efc13df8ea1e400 | 1b8f093752ba748c5ca0083afef2959aaa7dace5 | /src/category_theory/universal/strongly_concrete.lean | 5b96c397b3d6a7c4f51db66b606c4c30c63745d0 | [] | no_license | khoek/lean-category-theory | 7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386 | 63dcb598e9270a3e8b56d1769eb4f825a177cd95 | refs/heads/master | 1,585,251,725,759 | 1,539,344,445,000 | 1,539,344,445,000 | 145,281,070 | 0 | 0 | null | 1,534,662,376,000 | 1,534,662,376,000 | null | UTF-8 | Lean | false | false | 713 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import category_theory.universal.continuous
import category_theory.concrete
import category_theory.functor.isomorphism
open category_theory
namespace category_theory
universes u
variable (C : Type (u+1))
variable [large_category C]
class strongly_concrete [concrete C] :=
(reflects_isos : reflects_isos (concrete.fibre_functor C))
(preserves_limits : continuous (concrete.fibre_functor C))
-- PROJECT
instance type_strongly_concrete : strongly_concrete (Type u) := {
reflects_isos := sorry,
preserves_limits := sorry
}
end category_theory |
18a5dd435f3e404cf8e64262da7671069e0aa8a0 | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/linear_algebra/basis.lean | b575f4afd0907bebded9a6e75e89e77b12cc31b6 | [
"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 | 23,408 | 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, Alexander Bentkamp
-/
import linear_algebra.linear_independent
import linear_algebra.projection
import data.fintype.card
/-!
# Bases
This file defines bases in a module or vector space.
It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light.
## Main definitions
All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or
vector space and `ι : Type*` is an arbitrary indexing type.
* `is_basis R v` states that the vector family `v` is a basis, i.e. it is linearly independent and
spans the entire space.
* `is_basis.repr hv x` is the basis version of `linear_independent.repr hv x`. It returns the
linear combination representing `x : M` on a basis `v` of `M` (using classical choice).
The argument `hv` must be a proof that `is_basis R v`. `is_basis.repr hv` is given as a linear
map as well.
* `is_basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the
basis `v : ι → M₁`, given `hv : is_basis R v`.
## Main statements
* `is_basis.ext` states that two linear maps are equal if they coincide on a basis.
* `exists_is_basis` states that every vector space has a basis.
## Implementation notes
We use families instead of sets because it allows us to say that two identical vectors are linearly
dependent. For bases, this is useful as well because we can easily derive ordered bases by using an
ordered index type `ι`.
## Tags
basis, bases
-/
noncomputable theory
universe u
open function set submodule
open_locale classical big_operators
variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*}
variables {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*}
section module
open linear_map
variables {v : ι → M}
variables [ring R] [add_comm_group M] [add_comm_group M'] [add_comm_group M'']
variables [module R M] [module R M'] [module R M'']
variables {a b : R} {x y : M}
variables (R) (v)
/-- A family of vectors is a basis if it is linearly independent and all vectors are in the span. -/
def is_basis := linear_independent R v ∧ span R (range v) = ⊤
variables {R} {v}
section is_basis
variables {s t : set M} (hv : is_basis R v)
lemma is_basis.mem_span (hv : is_basis R v) : ∀ x, x ∈ span R (range v) := eq_top_iff'.1 hv.2
lemma is_basis.comp (hv : is_basis R v) (f : ι' → ι) (hf : bijective f) :
is_basis R (v ∘ f) :=
begin
split,
{ apply hv.1.comp f hf.1 },
{ rw[set.range_comp, range_iff_surjective.2 hf.2, image_univ, hv.2] }
end
lemma is_basis.injective [nontrivial R] (hv : is_basis R v) : injective v :=
λ x y h, linear_independent.injective hv.1 h
lemma is_basis.range (hv : is_basis R v) : is_basis R (λ x, x : range v → M) :=
⟨hv.1.to_subtype_range, by { convert hv.2, ext i, exact ⟨λ ⟨p, hp⟩, hp ▸ p.2, λ hi, ⟨⟨i, hi⟩, rfl⟩⟩ }⟩
/-- Given a basis, any vector can be written as a linear combination of the basis vectors. They are
given by this linear map. This is one direction of `module_equiv_finsupp`. -/
def is_basis.repr : M →ₗ (ι →₀ R) :=
(hv.1.repr).comp (linear_map.id.cod_restrict _ hv.mem_span)
lemma is_basis.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x :=
hv.1.total_repr ⟨x, _⟩
lemma is_basis.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = linear_map.id :=
linear_map.ext hv.total_repr
lemma is_basis.ext {f g : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, f (v i) = g (v i)) : f = g :=
linear_map.ext_on_range hv.2 h
lemma is_basis.repr_ker : hv.repr.ker = ⊥ :=
linear_map.ker_eq_bot.2 $ left_inverse.injective hv.total_repr
lemma is_basis.repr_range : hv.repr.range = finsupp.supported R R univ :=
by rw [is_basis.repr, linear_map.range, submodule.map_comp,
linear_map.map_cod_restrict, submodule.map_id, comap_top, map_top, hv.1.repr_range,
finsupp.supported_univ]
lemma is_basis.repr_total (x : ι →₀ R) (hx : x ∈ finsupp.supported R R (univ : set ι)) :
hv.repr (finsupp.total ι M R v x) = x :=
begin
rw [← hv.repr_range, linear_map.mem_range] at hx,
cases hx with w hw,
rw [← hw, hv.total_repr],
end
lemma is_basis.repr_eq_single {i} : hv.repr (v i) = finsupp.single i 1 :=
by apply hv.1.repr_eq_single; simp
@[simp]
lemma is_basis.repr_self_apply (i j : ι) : hv.repr (v i) j = if i = j then 1 else 0 :=
by rw [hv.repr_eq_single, finsupp.single_apply]
lemma is_basis.repr_eq_iff {f : M →ₗ[R] (ι →₀ R)} :
hv.repr = f ↔ ∀ i, f (v i) = finsupp.single i 1 :=
begin
split,
{ rintros rfl i,
exact hv.repr_eq_single },
intro h,
refine hv.ext (λ _, _),
rw [h, hv.repr_eq_single]
end
lemma is_basis.repr_apply_eq {f : M → ι → R}
(hadd : ∀ x y, f (x + y) = f x + f y) (hsmul : ∀ (c : R) (x : M), f (c • x) = c • f x)
(f_eq : ∀ i, f (v i) = finsupp.single i 1) (x : M) (i : ι) :
hv.repr x i = f x i :=
begin
let f_i : M →ₗ[R] R :=
{ to_fun := λ x, f x i,
map_add' := λ _ _, by rw [hadd, pi.add_apply],
map_smul' := λ _ _, by rw [hsmul, pi.smul_apply] },
show (finsupp.lapply i).comp hv.repr x = f_i x,
congr' 1,
refine hv.ext (λ j, _),
show hv.repr (v j) i = f (v j) i,
rw [hv.repr_eq_single, f_eq]
end
lemma is_basis.range_repr_self (i : ι) :
hv.range.repr (v i) = finsupp.single ⟨v i, mem_range_self i⟩ 1 :=
hv.1.to_subtype_range.repr_eq_single _ _ rfl
@[simp] lemma is_basis.range_repr (i : ι) :
hv.range.repr x ⟨v i, mem_range_self i⟩ = hv.repr x i :=
begin
by_cases H : (0 : R) = 1,
{ exact eq_of_zero_eq_one H _ _ },
refine (hv.repr_apply_eq _ _ _ x i).symm,
{ intros x y,
ext j,
rw [linear_map.map_add, finsupp.add_apply],
refl },
{ intros c x,
ext j,
rw [linear_map.map_smul, finsupp.smul_apply],
refl },
{ intro i,
ext j,
haveI : nontrivial R := ⟨⟨0, 1, H⟩⟩,
simp [hv.range_repr_self, finsupp.single_apply, hv.injective] }
end
/-- Construct a linear map given the value at the basis. -/
def is_basis.constr (f : ι → M') : M →ₗ[R] M' :=
(finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f).comp hv.repr
theorem is_basis.constr_apply (f : ι → M') (x : M) :
(hv.constr f : M → M') x = (hv.repr x).sum (λb a, a • f b) :=
by dsimp [is_basis.constr] ;
rw [finsupp.total_apply, finsupp.sum_map_domain_index]; simp [add_smul]
@[simp] lemma constr_basis {f : ι → M'} {i : ι} (hv : is_basis R v) :
(hv.constr f : M → M') (v i) = f i :=
by simp [is_basis.constr_apply, hv.repr_eq_single, finsupp.sum_single_index]
lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (hv : is_basis R v)
(h : ∀i, g i = f (v i)) : hv.constr g = f :=
hv.ext $ λ i, (constr_basis hv).trans (h i)
lemma constr_self (f : M →ₗ[R] M') : hv.constr (λ i, f (v i)) = f :=
constr_eq hv $ λ x, rfl
lemma constr_zero (hv : is_basis R v) : hv.constr (λi, (0 : M')) = 0 :=
constr_eq hv $ λ x, rfl
lemma constr_add {g f : ι → M'} (hv : is_basis R v) :
hv.constr (λi, f i + g i) = hv.constr f + hv.constr g :=
constr_eq hv $ λ b, by simp
lemma constr_neg {f : ι → M'} (hv : is_basis R v) : hv.constr (λi, - f i) = - hv.constr f :=
constr_eq hv $ λ b, by simp
lemma constr_sub {g f : ι → M'} (hs : is_basis R v) :
hv.constr (λi, f i - g i) = hs.constr f - hs.constr g :=
by simp [sub_eq_add_neg, constr_add, constr_neg]
-- this only works on functions if `R` is a commutative ring
lemma constr_smul {ι R M} [comm_ring R] [add_comm_group M] [module R M]
{v : ι → R} {f : ι → M} {a : R} (hv : is_basis R v) :
hv.constr (λb, a • f b) = a • hv.constr f :=
constr_eq hv $ by simp [constr_basis hv] {contextual := tt}
lemma constr_range [nonempty ι] (hv : is_basis R v) {f : ι → M'} :
(hv.constr f).range = span R (range f) :=
by rw [is_basis.constr, linear_map.range_comp, linear_map.range_comp, is_basis.repr_range,
finsupp.lmap_domain_supported, ←set.image_univ, ←finsupp.span_eq_map_total, image_id]
/-- Canonical equivalence between a module and the linear combinations of basis vectors. -/
def module_equiv_finsupp (hv : is_basis R v) : M ≃ₗ[R] ι →₀ R :=
(hv.1.total_equiv.trans (linear_equiv.of_top _ hv.2)).symm
@[simp] theorem module_equiv_finsupp_apply_basis (hv : is_basis R v) (i : ι) :
module_equiv_finsupp hv (v i) = finsupp.single i 1 :=
(linear_equiv.symm_apply_eq _).2 $ by simp [linear_independent.total_equiv]
/-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases
`v` and `v'` and a bijection between the indexing sets of the two bases. -/
def linear_equiv_of_is_basis {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v')
(e : ι ≃ ι') : M ≃ₗ[R] M' :=
{ inv_fun := hv'.constr (v ∘ e.symm),
left_inv := have (hv'.constr (v ∘ e.symm)).comp (hv.constr (v' ∘ e)) = linear_map.id,
from hv.ext $ by simp,
λ x, congr_arg (λ h : M →ₗ[R] M, h x) this,
right_inv := have (hv.constr (v' ∘ e)).comp (hv'.constr (v ∘ e.symm)) = linear_map.id,
from hv'.ext $ by simp,
λ y, congr_arg (λ h : M' →ₗ[R] M', h y) this,
..hv.constr (v' ∘ e) }
/-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases
`v` and `v'` and a bijection between the two bases. -/
def linear_equiv_of_is_basis' {v : ι → M} {v' : ι' → M'} (f : M → M') (g : M' → M)
(hv : is_basis R v) (hv' : is_basis R v')
(hf : ∀i, f (v i) ∈ range v') (hg : ∀i, g (v' i) ∈ range v)
(hgf : ∀i, g (f (v i)) = v i) (hfg : ∀i, f (g (v' i)) = v' i) :
M ≃ₗ M' :=
{ inv_fun := hv'.constr (g ∘ v'),
left_inv :=
have (hv'.constr (g ∘ v')).comp (hv.constr (f ∘ v)) = linear_map.id,
from hv.ext $ λ i, exists.elim (hf i)
(λ i' hi', by simp [constr_basis, hi'.symm]; rw [hi', hgf]),
λ x, congr_arg (λ h:M →ₗ[R] M, h x) this,
right_inv :=
have (hv.constr (f ∘ v)).comp (hv'.constr (g ∘ v')) = linear_map.id,
from hv'.ext $ λ i', exists.elim (hg i')
(λ i hi, by simp [constr_basis, hi.symm]; rw [hi, hfg]),
λ y, congr_arg (λ h:M' →ₗ[R] M', h y) this,
..hv.constr (f ∘ v) }
@[simp] lemma linear_equiv_of_is_basis_comp {ι'' : Type*} {v : ι → M} {v' : ι' → M'}
{v'' : ι'' → M''} (hv : is_basis R v) (hv' : is_basis R v') (hv'' : is_basis R v'')
(e : ι ≃ ι') (f : ι' ≃ ι'' ) :
(linear_equiv_of_is_basis hv hv' e).trans (linear_equiv_of_is_basis hv' hv'' f) =
linear_equiv_of_is_basis hv hv'' (e.trans f) :=
begin
apply linear_equiv.injective_to_linear_map,
apply hv.ext,
intros i,
simp [linear_equiv_of_is_basis]
end
@[simp] lemma linear_equiv_of_is_basis_refl :
linear_equiv_of_is_basis hv hv (equiv.refl ι) = linear_equiv.refl R M :=
begin
apply linear_equiv.injective_to_linear_map,
apply hv.ext,
intros i,
simp [linear_equiv_of_is_basis]
end
lemma linear_equiv_of_is_basis_trans_symm (e : ι ≃ ι') {v' : ι' → M'} (hv' : is_basis R v') :
(linear_equiv_of_is_basis hv hv' e).trans (linear_equiv_of_is_basis hv' hv e.symm) = linear_equiv.refl R M :=
by simp
lemma linear_equiv_of_is_basis_symm_trans (e : ι ≃ ι') {v' : ι' → M'} (hv' : is_basis R v') :
(linear_equiv_of_is_basis hv' hv e.symm).trans (linear_equiv_of_is_basis hv hv' e) = linear_equiv.refl R M' :=
by simp
lemma is_basis_inl_union_inr {v : ι → M} {v' : ι' → M'}
(hv : is_basis R v) (hv' : is_basis R v') :
is_basis R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) :=
begin
split,
apply linear_independent_inl_union_inr' hv.1 hv'.1,
rw [sum.elim_range, span_union,
set.range_comp, span_image (inl R M M'), hv.2, map_top,
set.range_comp, span_image (inr R M M'), hv'.2, map_top],
exact linear_map.sup_range_inl_inr
end
end is_basis
lemma is_basis_singleton_one (R : Type*) [unique ι] [ring R] :
is_basis R (λ (_ : ι), (1 : R)) :=
begin
split,
{ refine linear_independent_iff.2 (λ l hl, _),
rw [finsupp.total_unique, smul_eq_mul, mul_one] at hl,
exact finsupp.unique_ext hl },
{ refine top_unique (λ _ _, _),
simp only [mem_span_singleton, range_const, mul_one, exists_eq, smul_eq_mul] }
end
protected lemma linear_equiv.is_basis (hs : is_basis R v)
(f : M ≃ₗ[R] M') : is_basis R (f ∘ v) :=
begin
split,
{ simpa only using hs.1.map' (f : M →ₗ[R] M') f.ker },
{ rw [set.range_comp, ← linear_equiv.coe_coe, span_image, hs.2, map_top, f.range] }
end
lemma is_basis_span (hs : linear_independent R v) :
@is_basis ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self _)⟩) _ _ _ :=
begin
split,
{ apply linear_independent_span hs },
{ rw eq_top_iff',
intro x,
have h₁ : subtype.val '' set.range (λ i, subtype.mk (v i) _) = range v,
by rw ←set.range_comp,
have h₂ : map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _)))
= span R (range v),
by rw [←span_image, submodule.subtype_eq_val, h₁],
have h₃ : (x : M) ∈ map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))),
by rw h₂; apply subtype.mem x,
rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩,
have h_x_eq_y : x = y,
by rw [subtype.ext_iff, ← hy₂]; simp,
rw h_x_eq_y,
exact hy₁ }
end
lemma is_basis_empty (h_empty : ¬ nonempty ι) (h : ∀x:M, x = 0) : is_basis R (λ x : ι, (0 : M)) :=
⟨ linear_independent_empty_type h_empty,
eq_top_iff'.2 $ assume x, (h x).symm ▸ submodule.zero_mem _ ⟩
lemma is_basis_empty_bot (h_empty : ¬ nonempty ι) :
is_basis R (λ _ : ι, (0 : (⊥ : submodule R M))) :=
begin
apply is_basis_empty h_empty,
intro x,
apply subtype.ext_iff_val.2,
exact (submodule.mem_bot R).1 (subtype.mem x),
end
open fintype
variables [fintype ι] (h : is_basis R v)
/-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`.
-/
def is_basis.equiv_fun : M ≃ₗ[R] (ι → R) :=
linear_equiv.trans (module_equiv_finsupp h)
{ to_fun := finsupp.to_fun,
map_add' := λ x y, by ext; exact finsupp.add_apply,
map_smul' := λ x y, by ext; exact finsupp.smul_apply,
..finsupp.equiv_fun_on_fintype }
/-- A module over a finite ring that admits a finite basis is finite. -/
def module.fintype_of_fintype [fintype R] : fintype M :=
fintype.of_equiv _ h.equiv_fun.to_equiv.symm
theorem module.card_fintype [fintype R] [fintype M] :
card M = (card R) ^ (card ι) :=
calc card M = card (ι → R) : card_congr h.equiv_fun.to_equiv
... = card R ^ card ι : card_fun
/-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps
a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/
@[simp] lemma is_basis.equiv_fun_symm_apply (x : ι → R) :
h.equiv_fun.symm x = ∑ i, x i • v i :=
begin
change finsupp.sum
((finsupp.equiv_fun_on_fintype.symm : (ι → R) ≃ (ι →₀ R)) x) (λ (i : ι) (a : R), a • v i)
= ∑ i, x i • v i,
dsimp [finsupp.equiv_fun_on_fintype, finsupp.sum],
rw finset.sum_filter,
refine finset.sum_congr rfl (λi hi, _),
by_cases H : x i = 0; simp [H]
end
lemma is_basis.equiv_fun_apply (u : M) : h.equiv_fun u = h.repr u := rfl
lemma is_basis.equiv_fun_total (u : M) : ∑ i, h.equiv_fun u i • v i = u:=
begin
conv_rhs { rw ← h.total_repr u },
simp [finsupp.total_apply, finsupp.sum_fintype, h.equiv_fun_apply]
end
@[simp]
lemma is_basis.equiv_fun_self (i j : ι) : h.equiv_fun (v i) j = if i = j then 1 else 0 :=
by { rw [h.equiv_fun_apply, h.repr_self_apply] }
@[simp] theorem is_basis.constr_apply_fintype (f : ι → M') (x : M) :
(h.constr f : M → M') x = ∑ i, (h.equiv_fun x i) • f i :=
by simp [h.constr_apply, h.equiv_fun_apply, finsupp.sum_fintype]
end module
section vector_space
variables [field K] [add_comm_group V] [add_comm_group V'] [vector_space K V] [vector_space K V']
variables {v : ι → V} {s t : set V} {x y z : V}
include K
open submodule
lemma exists_subset_is_basis (hs : linear_independent K (λ x, x : s → V)) :
∃b, s ⊆ b ∧ is_basis K (coe : b → V) :=
let ⟨b, hb₀, hx, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in
⟨ b, hx,
@linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ hb₃,
by simp; exact eq_top_iff.2 hb₂⟩
lemma exists_sum_is_basis (hs : linear_independent K v) :
∃ (ι' : Type u) (v' : ι' → V), is_basis K (sum.elim v v') :=
begin
-- This is a hack: we jump through hoops to reuse `exists_subset_is_basis`.
let s := set.range v,
let e : ι ≃ s := equiv.set.range v hs.injective,
have : (λ x, x : s → V) = v ∘ e.symm := by { funext, dsimp, rw [equiv.set.apply_range_symm v], },
have : linear_independent K (λ x, x : s → V),
{ rw this,
exact linear_independent.comp hs _ (e.symm.injective), },
obtain ⟨b, ss, is⟩ := exists_subset_is_basis this,
let e' : ι ⊕ (b \ s : set V) ≃ b :=
calc ι ⊕ (b \ s : set V) ≃ s ⊕ (b \ s : set V) : equiv.sum_congr e (equiv.refl _)
... ≃ b : equiv.set.sum_diff_subset ss,
refine ⟨(b \ s : set V), λ x, x.1, _⟩,
convert is_basis.comp is e' _,
{ funext x,
cases x; simp; refl, },
{ exact e'.bijective, },
end
variables (K V)
lemma exists_is_basis : ∃b : set V, is_basis K (λ i, i : b → V) :=
let ⟨b, _, hb⟩ := exists_subset_is_basis (linear_independent_empty K V : _) in ⟨b, hb⟩
variables {K V}
lemma linear_map.exists_left_inverse_of_injective (f : V →ₗ[K] V')
(hf_inj : f.ker = ⊥) : ∃g:V' →ₗ V, g.comp f = linear_map.id :=
begin
rcases exists_is_basis K V with ⟨B, hB⟩,
have hB₀ : _ := hB.1.to_subtype_range,
have : linear_independent K (λ x, x : f '' B → V'),
{ have h₁ := hB₀.image_subtype
(show disjoint (span K (range (λ i : B, i.val))) (linear_map.ker f), by simp [hf_inj]),
rwa subtype.range_coe at h₁ },
rcases exists_subset_is_basis this with ⟨C, BC, hC⟩,
haveI : inhabited V := ⟨0⟩,
use hC.constr (C.restrict (inv_fun f)),
refine hB.ext (λ b, _),
rw image_subset_iff at BC,
have : f b = (⟨f b, BC b.2⟩ : C) := rfl,
dsimp,
rw [this, constr_basis hC],
exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _
end
lemma submodule.exists_is_compl (p : submodule K V) : ∃ q : submodule K V, is_compl p q :=
let ⟨f, hf⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in
⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩
lemma linear_map.exists_right_inverse_of_surjective (f : V →ₗ[K] V')
(hf_surj : f.range = ⊤) : ∃g:V' →ₗ V, f.comp g = linear_map.id :=
begin
rcases exists_is_basis K V' with ⟨C, hC⟩,
haveI : inhabited V := ⟨0⟩,
use hC.constr (C.restrict (inv_fun f)),
refine hC.ext (λ c, _),
simp [constr_basis hC, right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) c]
end
open submodule linear_map
theorem quotient_prod_linear_equiv (p : submodule K V) :
nonempty ((p.quotient × p) ≃ₗ[K] V) :=
let ⟨q, hq⟩ := p.exists_is_compl in nonempty.intro $
((quotient_equiv_of_is_compl p q hq).prod (linear_equiv.refl _ _)).trans
(prod_equiv_of_is_compl q p hq.symm)
open fintype
variables (K) (V)
theorem vector_space.card_fintype [fintype K] [fintype V] :
∃ n : ℕ, card V = (card K) ^ n :=
exists.elim (exists_is_basis K V) $ λ b hb, ⟨card b, module.card_fintype hb⟩
end vector_space
namespace pi
open set linear_map
section module
variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*}
variables [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)]
lemma linear_independent_std_basis [decidable_eq η]
(v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) :
linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) :=
begin
have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)),
{ intro j,
exact (hs j).map' _ (ker_std_basis _ _ _) },
apply linear_independent_Union_finite hs',
{ assume j J _ hiJ,
simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union],
have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))
≤ range (std_basis R Ms j),
{ intro j,
rw [span_le, linear_map.range_coe],
apply range_comp_subset_range },
have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))
≤ ⨆ i ∈ {j}, range (std_basis R Ms i),
{ rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)),
apply h₀ },
have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤
⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) :=
supr_le_supr (λ i, supr_le_supr (λ H, h₀ i)),
have h₃ : disjoint (λ (i : η), i ∈ {j}) J,
{ convert set.disjoint_singleton_left.2 hiJ,
rw ←@set_of_mem_eq _ {j},
refl },
exact (disjoint_std_basis_std_basis _ _ _ _ h₃).mono h₁ h₂ }
end
variable [fintype η]
lemma is_basis_std_basis [decidable_eq η] (s : Πj, ιs j → (Ms j)) (hs : ∀j, is_basis R (s j)) :
is_basis R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (s ji.1 ji.2)) :=
begin
split,
{ apply linear_independent_std_basis _ (assume i, (hs i).1) },
have h₁ : Union (λ j, set.range (std_basis R Ms j ∘ s j))
⊆ range (λ (ji : Σ (j : η), ιs j), (std_basis R Ms (ji.fst)) (s (ji.fst) (ji.snd))),
{ apply Union_subset, intro i,
apply range_comp_subset_range (λ x : ιs i, (⟨i, x⟩ : Σ (j : η), ιs j))
(λ (ji : Σ (j : η), ιs j), std_basis R Ms (ji.fst) (s (ji.fst) (ji.snd))) },
have h₂ : ∀ i, span R (range (std_basis R Ms i ∘ s i)) = range (std_basis R Ms i),
{ intro i,
rw [set.range_comp, submodule.span_image, (assume i, (hs i).2), submodule.map_top] },
apply eq_top_mono,
apply span_mono h₁,
rw span_Union,
simp only [h₂],
apply supr_range_std_basis
end
section
variables (R η)
lemma is_basis_fun₀ [decidable_eq η] : is_basis R
(λ (ji : Σ (j : η), unit),
(std_basis R (λ (i : η), R) (ji.fst)) 1) :=
@is_basis_std_basis R η (λi:η, unit) (λi:η, R) _ _ _ _ _ (λ _ _, (1 : R))
(assume i, @is_basis_singleton_one _ _ _ _)
lemma is_basis_fun [decidable_eq η] : is_basis R (λ i, std_basis R (λi:η, R) i 1) :=
begin
apply (is_basis_fun₀ R η).comp (λ i, ⟨i, punit.star⟩),
apply bijective_iff_has_inverse.2,
use sigma.fst,
simp [function.left_inverse, function.right_inverse]
end
@[simp] lemma is_basis_fun_repr [decidable_eq η] (x : η → R) (i : η) :
(pi.is_basis_fun R η).repr x i = x i :=
begin
conv_rhs { rw ← (pi.is_basis_fun R η).total_repr x },
rw [finsupp.total_apply, finsupp.sum_fintype],
show (pi.is_basis_fun R η).repr x i =
(∑ j, λ i, (pi.is_basis_fun R η).repr x j • std_basis R (λ _, R) j 1 i) i,
rw [finset.sum_apply, finset.sum_eq_single i],
{ simp only [pi.smul_apply, smul_eq_mul, std_basis_same, mul_one] },
{ rintros b - hb, simp only [std_basis_ne _ _ _ _ hb.symm, smul_zero] },
{ intro,
have := finset.mem_univ i,
contradiction },
{ intros, apply zero_smul },
end
end
end module
end pi
|
7874c89f3d81ec7ba516cfdadcd577901287c367 | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /algebra/euclidean_domain.lean | db1d01e8f05a2da35387a7c2013d3cf2fd8e3e1b | [
"Apache-2.0"
] | permissive | kckennylau/mathlib | 21fb810b701b10d6606d9002a4004f7672262e83 | 47b3477e20ffb5a06588dd3abb01fe0fe3205646 | refs/heads/master | 1,634,976,409,281 | 1,542,042,832,000 | 1,542,319,733,000 | 109,560,458 | 0 | 0 | Apache-2.0 | 1,542,369,208,000 | 1,509,867,494,000 | Lean | UTF-8 | Lean | false | false | 9,094 | 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
Euclidean domains and Euclidean algorithm (extended to come)
A lot is based on pre-existing code in mathlib for natural number gcds
-/
import data.int.basic
universe u
class euclidean_domain (α : Type u) extends nonzero_comm_ring α :=
(quotient : α → α → α)
(remainder : α → α → α)
-- This could be changed to the same order as int.mod_add_div.
-- We normally write qb+r rather than r + qb though.
(quotient_mul_add_remainder_eq : ∀ a b, b * quotient a b + remainder a b = a)
(r : α → α → Prop)
(r_well_founded : well_founded r)
(remainder_lt : ∀ a {b}, b ≠ 0 → r (remainder a b) b)
/- `val_le_mul_left` is often not a required in definitions of a euclidean
domain since given the other properties we can show there is a
(noncomputable) euclidean domain α with the property `val_le_mul_left`.
So potentially this definition could be split into two different ones
(euclidean_domain_weak and euclidean_domain_strong) with a noncomputable
function from weak to strong. I've currently divided the lemmas into
strong and weak depending on whether they require `val_le_mul_left` or not. -/
(mul_left_not_lt : ∀ a {b}, b ≠ 0 → ¬r (a * b) a)
namespace euclidean_domain
variable {α : Type u}
variables [euclidean_domain α]
local infix ` ≺ `:50 := euclidean_domain.r
instance : has_div α := ⟨quotient⟩
instance : has_mod α := ⟨remainder⟩
theorem div_add_mod (a b : α) : b * (a / b) + a % b = a :=
quotient_mul_add_remainder_eq _ _
lemma mod_eq_sub_mul_div {α : Type*} [euclidean_domain α] (a b : α) :
a % b = a - b * (a / b) :=
calc a % b = b * (a / b) + a % b - b * (a / b) : (add_sub_cancel' _ _).symm
... = a - b * (a / b) : by rw div_add_mod
theorem mod_lt : ∀ a {b : α}, b ≠ 0 → (a % b) ≺ b :=
remainder_lt
theorem mul_right_not_lt {a : α} (b) (h : a ≠ 0) : ¬(a * b) ≺ b :=
by rw mul_comm; exact mul_left_not_lt b h
lemma mul_div_cancel_left {a : α} (b) (a0 : a ≠ 0) : a * b / a = b :=
eq.symm $ eq_of_sub_eq_zero $ classical.by_contradiction $ λ h,
begin
have := mul_left_not_lt a h,
rw [mul_sub, sub_eq_iff_eq_add'.2 (div_add_mod (a*b) a).symm] at this,
exact this (mod_lt _ a0)
end
lemma mul_div_cancel (a) {b : α} (b0 : b ≠ 0) : a * b / b = a :=
by rw mul_comm; exact mul_div_cancel_left a b0
@[simp] lemma mod_zero (a : α) : a % 0 = a :=
by simpa only [zero_mul, zero_add] using div_add_mod a 0
@[simp] lemma mod_eq_zero {a b : α} : a % b = 0 ↔ b ∣ a :=
⟨λ h, by rw [← div_add_mod a b, h, add_zero]; exact dvd_mul_right _ _,
λ ⟨c, e⟩, begin
rw [e, ← add_left_cancel_iff, div_add_mod, add_zero],
haveI := classical.dec,
by_cases b0 : b = 0,
{ simp only [b0, zero_mul] },
{ rw [mul_div_cancel_left _ b0] }
end⟩
@[simp] lemma mod_self (a : α) : a % a = 0 :=
mod_eq_zero.2 (dvd_refl _)
lemma dvd_mod_iff {a b c : α} (h : c ∣ b) : c ∣ a % b ↔ c ∣ a :=
by rw [dvd_add_iff_right (dvd_mul_of_dvd_left h _), div_add_mod]
lemma lt_one (a : α) : a ≺ (1:α) → a = 0 :=
by haveI := classical.dec; exact
not_imp_not.1 (λ h, by simpa only [one_mul] using mul_left_not_lt 1 h)
lemma val_dvd_le : ∀ a b : α, b ∣ a → a ≠ 0 → ¬a ≺ b
| _ b ⟨d, rfl⟩ ha := mul_left_not_lt b (mt (by rintro rfl; exact mul_zero _) ha)
@[simp] lemma mod_one (a : α) : a % 1 = 0 :=
mod_eq_zero.2 (one_dvd _)
@[simp] lemma zero_mod (b : α) : 0 % b = 0 :=
mod_eq_zero.2 (dvd_zero _)
@[simp] lemma zero_div {a : α} (a0 : a ≠ 0) : 0 / a = 0 :=
by simpa only [zero_mul] using mul_div_cancel 0 a0
@[simp] lemma div_self {a : α} (a0 : a ≠ 0) : a / a = 1 :=
by simpa only [one_mul] using mul_div_cancel 1 a0
section gcd
variable [decidable_eq α]
def gcd : α → α → α
| a := λ b, if a0 : a = 0 then b else
have h:_ := mod_lt b a0,
gcd (b%a) a
using_well_founded {dec_tac := tactic.assumption,
rel_tac := λ _ _, `[exact ⟨_, r_well_founded α⟩]}
@[simp] theorem gcd_zero_left (a : α) : gcd 0 a = a :=
by rw gcd; exact if_pos rfl
@[simp] theorem gcd_zero_right (a : α) : gcd a 0 = a :=
by rw gcd; split_ifs; simp only [h, zero_mod, gcd_zero_left]
theorem gcd_val (a b : α) : gcd a b = gcd (b % a) a :=
by rw gcd; split_ifs; [simp only [h, mod_zero, gcd_zero_right], refl]
@[elab_as_eliminator]
theorem gcd.induction {P : α → α → Prop} : ∀ a b : α,
(∀ x, P 0 x) →
(∀ a b, a ≠ 0 → P (b % a) a → P a b) →
P a b
| a := λ b H0 H1, if a0 : a = 0 then by rw [a0]; apply H0 else
have h:_ := mod_lt b a0,
H1 _ _ a0 (gcd.induction (b%a) a H0 H1)
using_well_founded {dec_tac := tactic.assumption,
rel_tac := λ _ _, `[exact ⟨_, r_well_founded α⟩]}
theorem gcd_dvd (a b : α) : gcd a b ∣ a ∧ gcd a b ∣ b :=
gcd.induction a b
(λ b, by rw [gcd_zero_left]; exact ⟨dvd_zero _, dvd_refl _⟩)
(λ a b aneq ⟨IH₁, IH₂⟩, by rw gcd_val;
exact ⟨IH₂, (dvd_mod_iff IH₂).1 IH₁⟩)
theorem gcd_dvd_left (a b : α) : gcd a b ∣ a := (gcd_dvd a b).left
theorem gcd_dvd_right (a b : α) : gcd a b ∣ b := (gcd_dvd a b).right
theorem dvd_gcd {a b c : α} : c ∣ a → c ∣ b → c ∣ gcd a b :=
gcd.induction a b
(λ _ _ H, by simpa only [gcd_zero_left] using H)
(λ a b a0 IH ca cb, by rw gcd_val;
exact IH ((dvd_mod_iff ca).2 cb) ca)
theorem gcd_eq_left {a b : α} : gcd a b = a ↔ a ∣ b :=
⟨λ h, by rw ← h; apply gcd_dvd_right,
λ h, by rw [gcd_val, mod_eq_zero.2 h, gcd_zero_left]⟩
@[simp] theorem gcd_one_left (a : α) : gcd 1 a = 1 :=
gcd_eq_left.2 (one_dvd _)
@[simp] theorem gcd_self (a : α) : gcd a a = a :=
gcd_eq_left.2 (dvd_refl _)
def xgcd_aux : α → α → α → α → α → α → α × α × α
| r := λ s t r' s' t',
if hr : r = 0 then (r', s', t')
else
have r' % r ≺ r, from mod_lt _ hr,
let q := r' / r in xgcd_aux (r' % r) (s' - q * s) (t' - q * t) r s t
using_well_founded {dec_tac := tactic.assumption,
rel_tac := λ _ _, `[exact ⟨_, r_well_founded α⟩]}
@[simp] theorem xgcd_zero_left {s t r' s' t' : α} : xgcd_aux 0 s t r' s' t' = (r', s', t') :=
by unfold xgcd_aux; exact if_pos rfl
@[simp] theorem xgcd_aux_rec {r s t r' s' t' : α} (h : r ≠ 0) :
xgcd_aux r s t r' s' t' = xgcd_aux (r' % r) (s' - (r' / r) * s) (t' - (r' / r) * t) r s t :=
by conv {to_lhs, rw [xgcd_aux]}; exact if_neg h
/-- Use the extended GCD algorithm to generate the `a` and `b` values
satisfying `gcd x y = x * a + y * b`. -/
def xgcd (x y : α) : α × α := (xgcd_aux x 1 0 y 0 1).2
/-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/
def gcd_a (x y : α) : α := (xgcd x y).1
/-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/
def gcd_b (x y : α) : α := (xgcd x y).2
@[simp] theorem xgcd_aux_fst (x y : α) : ∀ s t s' t',
(xgcd_aux x s t y s' t').1 = gcd x y :=
gcd.induction x y (by intros; rw [xgcd_zero_left, gcd_zero_left])
(λ x y h IH s t s' t', by simp only [xgcd_aux_rec h, if_neg h, IH]; rw ← gcd_val)
theorem xgcd_aux_val (x y : α) : xgcd_aux x 1 0 y 0 1 = (gcd x y, xgcd x y) :=
by rw [xgcd, ← xgcd_aux_fst x y 1 0 0 1, prod.mk.eta]
theorem xgcd_val (x y : α) : xgcd x y = (gcd_a x y, gcd_b x y) :=
prod.mk.eta.symm
private def P (a b : α) : α × α × α → Prop | (r, s, t) := (r : α) = a * s + b * t
theorem xgcd_aux_P (a b : α) {r r' : α} : ∀ {s t s' t'}, P a b (r, s, t) →
P a b (r', s', t') → P a b (xgcd_aux r s t r' s' t') :=
gcd.induction r r' (by intros; simpa only [xgcd_zero_left]) $ λ x y h IH s t s' t' p p', begin
rw [xgcd_aux_rec h], refine IH _ p, unfold P at p p' ⊢,
rw [mul_sub, mul_sub, add_sub, sub_add_eq_add_sub, ← p', sub_sub,
mul_comm _ s, ← mul_assoc, mul_comm _ t, ← mul_assoc, ← add_mul, ← p,
mod_eq_sub_mul_div]
end
theorem gcd_eq_gcd_ab (a b : α) : (gcd a b : α) = a * gcd_a a b + b * gcd_b a b :=
by have := @xgcd_aux_P _ _ _ a b a b 1 0 0 1
(by rw [P, mul_one, mul_zero, add_zero]) (by rw [P, mul_one, mul_zero, zero_add]);
rwa [xgcd_aux_val, xgcd_val] at this
instance (α : Type*) [e : euclidean_domain α] : integral_domain α :=
by haveI := classical.dec_eq α; exact
{ eq_zero_or_eq_zero_of_mul_eq_zero :=
λ a b (h : a * b = 0), or_iff_not_and_not.2 $ λ h0 : a ≠ 0 ∧ b ≠ 0,
h0.1 $ by rw [← mul_div_cancel a h0.2, h, zero_div h0.2],
..e }
end gcd
instance : euclidean_domain ℤ :=
{ quotient := (/),
remainder := (%),
quotient_mul_add_remainder_eq := λ a b, by rw add_comm; exact int.mod_add_div _ _,
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 _) }
end euclidean_domain
|
023853e99a9282ab4f4b0e751ff8c55c4c34905b | 4727251e0cd73359b15b664c3170e5d754078599 | /src/combinatorics/hall/basic.lean | 9081fb4d8c30d611471cfb36f37ce7bf255248dd | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 10,172 | lean | /-
Copyright (c) 2021 Alena Gusakov, Bhavik Mehta, Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alena Gusakov, Bhavik Mehta, Kyle Miller
-/
import combinatorics.hall.finite
import topology.category.Top.limits
/-!
# Hall's Marriage Theorem
Given a list of finite subsets $X_1, X_2, \dots, X_n$ of some given set
$S$, P. Hall in [Hall1935] gave a necessary and sufficient condition for
there to be a list of distinct elements $x_1, x_2, \dots, x_n$ with
$x_i\in X_i$ for each $i$: it is when for each $k$, the union of every
$k$ of these subsets has at least $k$ elements.
Rather than a list of finite subsets, one may consider indexed families
`t : ι → finset α` of finite subsets with `ι` a `fintype`, and then the list
of distinct representatives is given by an injective function `f : ι → α`
such that `∀ i, f i ∈ t i`, called a *matching*.
This version is formalized as `finset.all_card_le_bUnion_card_iff_exists_injective'`
in a separate module.
The theorem can be generalized to remove the constraint that `ι` be a `fintype`.
As observed in [Halpern1966], one may use the constrained version of the theorem
in a compactness argument to remove this constraint.
The formulation of compactness we use is that inverse limits of nonempty finite sets
are nonempty (`nonempty_sections_of_fintype_inverse_system`), which uses the
Tychonoff theorem.
The core of this module is constructing the inverse system: for every finite subset `ι'` of
`ι`, we can consider the matchings on the restriction of the indexed family `t` to `ι'`.
## Main statements
* `finset.all_card_le_bUnion_card_iff_exists_injective` is in terms of `t : ι → finset α`.
* `fintype.all_card_le_rel_image_card_iff_exists_injective` is in terms of a relation
`r : α → β → Prop` such that `rel.image r {a}` is a finite set for all `a : α`.
* `fintype.all_card_le_filter_rel_iff_exists_injective` is in terms of a relation
`r : α → β → Prop` on finite types, with the Hall condition given in terms of
`finset.univ.filter`.
## Todo
* The statement of the theorem in terms of bipartite graphs is in preparation.
## Tags
Hall's Marriage Theorem, indexed families
-/
open finset
universes u v
/-- The set of matchings for `t` when restricted to a `finset` of `ι`. -/
def hall_matchings_on {ι : Type u} {α : Type v} (t : ι → finset α) (ι' : finset ι) :=
{f : ι' → α | function.injective f ∧ ∀ x, f x ∈ t x}
/-- Given a matching on a finset, construct the restriction of that matching to a subset. -/
def hall_matchings_on.restrict {ι : Type u} {α : Type v}
(t : ι → finset α) {ι' ι'' : finset ι} (h : ι' ⊆ ι'')
(f : hall_matchings_on t ι'') : hall_matchings_on t ι' :=
begin
refine ⟨λ i, f.val ⟨i, h i.property⟩, _⟩,
cases f.property with hinj hc,
refine ⟨_, λ i, hc ⟨i, h i.property⟩⟩,
rintro ⟨i, hi⟩ ⟨j, hj⟩ hh,
simpa only [subtype.mk_eq_mk] using hinj hh,
end
/-- When the Hall condition is satisfied, the set of matchings on a finite set is nonempty.
This is where `finset.all_card_le_bUnion_card_iff_exists_injective'` comes into the argument. -/
lemma hall_matchings_on.nonempty {ι : Type u} {α : Type v} [decidable_eq α]
(t : ι → finset α) (h : (∀ (s : finset ι), s.card ≤ (s.bUnion t).card))
(ι' : finset ι) : nonempty (hall_matchings_on t ι') :=
begin
classical,
refine ⟨classical.indefinite_description _ _⟩,
apply (all_card_le_bUnion_card_iff_exists_injective' (λ (i : ι'), t i)).mp,
intro s',
convert h (s'.image coe) using 1,
simp only [card_image_of_injective s' subtype.coe_injective],
rw image_bUnion,
congr,
end
/--
This is the `hall_matchings_on` sets assembled into a directed system.
-/
-- TODO: This takes a long time to elaborate for an unknown reason.
def hall_matchings_functor {ι : Type u} {α : Type v} (t : ι → finset α) :
(finset ι)ᵒᵖ ⥤ Type (max u v) :=
{ obj := λ ι', hall_matchings_on t ι'.unop,
map := λ ι' ι'' g f, hall_matchings_on.restrict t (category_theory.le_of_hom g.unop) f }
noncomputable instance hall_matchings_on.fintype {ι : Type u} {α : Type v}
(t : ι → finset α) (ι' : finset ι) :
fintype (hall_matchings_on t ι') :=
begin
classical,
rw hall_matchings_on,
let g : hall_matchings_on t ι' → (ι' → ι'.bUnion t),
{ rintro f i,
refine ⟨f.val i, _⟩,
rw mem_bUnion,
exact ⟨i, i.property, f.property.2 i⟩ },
apply fintype.of_injective g,
intros f f' h,
simp only [g, function.funext_iff, subtype.val_eq_coe] at h,
ext a,
exact h a,
end
/--
This is the version of **Hall's Marriage Theorem** in terms of indexed
families of finite sets `t : ι → finset α`. It states that there is a
set of distinct representatives if and only if every union of `k` of the
sets has at least `k` elements.
Recall that `s.bUnion t` is the union of all the sets `t i` for `i ∈ s`.
This theorem is bootstrapped from `finset.all_card_le_bUnion_card_iff_exists_injective'`,
which has the additional constraint that `ι` is a `fintype`.
-/
theorem finset.all_card_le_bUnion_card_iff_exists_injective
{ι : Type u} {α : Type v} [decidable_eq α] (t : ι → finset α) :
(∀ (s : finset ι), s.card ≤ (s.bUnion t).card) ↔
(∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x) :=
begin
split,
{ intro h,
/- Set up the functor -/
haveI : ∀ (ι' : (finset ι)ᵒᵖ), nonempty ((hall_matchings_functor t).obj ι') :=
λ ι', hall_matchings_on.nonempty t h ι'.unop,
classical,
haveI : Π (ι' : (finset ι)ᵒᵖ), fintype ((hall_matchings_functor t).obj ι') := begin
intro ι',
rw [hall_matchings_functor],
apply_instance,
end,
/- Apply the compactness argument -/
obtain ⟨u, hu⟩ := nonempty_sections_of_fintype_inverse_system (hall_matchings_functor t),
/- Interpret the resulting section of the inverse limit -/
refine ⟨_, _, _⟩,
{ /- Build the matching function from the section -/
exact λ i, (u (opposite.op ({i} : finset ι))).val
⟨i, by simp only [opposite.unop_op, mem_singleton]⟩, },
{ /- Show that it is injective -/
intros i i',
have subi : ({i} : finset ι) ⊆ {i,i'} := by simp,
have subi' : ({i'} : finset ι) ⊆ {i,i'} := by simp,
have le : ∀ {s t : finset ι}, s ⊆ t → s ≤ t := λ _ _ h, h,
rw [←hu (category_theory.hom_of_le (le subi)).op,
←hu (category_theory.hom_of_le (le subi')).op],
let uii' := u (opposite.op ({i,i'} : finset ι)),
exact λ h, subtype.mk_eq_mk.mp (uii'.property.1 h), },
{ /- Show that it maps each index to the corresponding finite set -/
intro i,
apply (u (opposite.op ({i} : finset ι))).property.2, }, },
{ /- The reverse direction is a straightforward cardinality argument -/
rintro ⟨f, hf₁, hf₂⟩ s,
rw ←finset.card_image_of_injective s hf₁,
apply finset.card_le_of_subset,
intro _,
rw [finset.mem_image, finset.mem_bUnion],
rintros ⟨x, hx, rfl⟩,
exact ⟨x, hx, hf₂ x⟩, },
end
/-- Given a relation such that the image of every singleton set is finite, then the image of every
finite set is finite. -/
instance {α : Type u} {β : Type v} [decidable_eq β]
(r : α → β → Prop) [∀ (a : α), fintype (rel.image r {a})]
(A : finset α) : fintype (rel.image r A) :=
begin
have h : rel.image r A = (A.bUnion (λ a, (rel.image r {a}).to_finset) : set β),
{ ext, simp [rel.image], },
rw [h],
apply finset_coe.fintype,
end
/--
This is a version of **Hall's Marriage Theorem** in terms of a relation
between types `α` and `β` such that `α` is finite and the image of
each `x : α` is finite (it suffices for `β` to be finite; see
`fintype.all_card_le_filter_rel_iff_exists_injective`). There is
a transversal of the relation (an injective function `α → β` whose graph is
a subrelation of the relation) iff every subset of
`k` terms of `α` is related to at least `k` terms of `β`.
Note: if `[fintype β]`, then there exist instances for `[∀ (a : α), fintype (rel.image r {a})]`.
-/
theorem fintype.all_card_le_rel_image_card_iff_exists_injective
{α : Type u} {β : Type v} [decidable_eq β]
(r : α → β → Prop) [∀ (a : α), fintype (rel.image r {a})] :
(∀ (A : finset α), A.card ≤ fintype.card (rel.image r A)) ↔
(∃ (f : α → β), function.injective f ∧ ∀ x, r x (f x)) :=
begin
let r' := λ a, (rel.image r {a}).to_finset,
have h : ∀ (A : finset α), fintype.card (rel.image r A) = (A.bUnion r').card,
{ intro A,
rw ←set.to_finset_card,
apply congr_arg,
ext b,
simp [rel.image], },
have h' : ∀ (f : α → β) x, r x (f x) ↔ f x ∈ r' x,
{ simp [rel.image], },
simp only [h, h'],
apply finset.all_card_le_bUnion_card_iff_exists_injective,
end
/--
This is a version of **Hall's Marriage Theorem** in terms of a relation to a finite type.
There is a transversal of the relation (an injective function `α → β` whose graph is a subrelation
of the relation) iff every subset of `k` terms of `α` is related to at least `k` terms of `β`.
It is like `fintype.all_card_le_rel_image_card_iff_exists_injective` but uses `finset.filter`
rather than `rel.image`.
-/
/- TODO: decidable_pred makes Yael sad. When an appropriate decidable_rel-like exists, fix it. -/
theorem fintype.all_card_le_filter_rel_iff_exists_injective
{α : Type u} {β : Type v} [fintype β]
(r : α → β → Prop) [∀ a, decidable_pred (r a)] :
(∀ (A : finset α), A.card ≤ (univ.filter (λ (b : β), ∃ a ∈ A, r a b)).card) ↔
(∃ (f : α → β), function.injective f ∧ ∀ x, r x (f x)) :=
begin
haveI := classical.dec_eq β,
let r' := λ a, univ.filter (λ b, r a b),
have h : ∀ (A : finset α), (univ.filter (λ (b : β), ∃ a ∈ A, r a b)) = (A.bUnion r'),
{ intro A,
ext b,
simp, },
have h' : ∀ (f : α → β) x, r x (f x) ↔ f x ∈ r' x,
{ simp, },
simp_rw [h, h'],
apply finset.all_card_le_bUnion_card_iff_exists_injective,
end
|
717f5e10999dae39fdc807657c8c4f04453aaed1 | 649957717d58c43b5d8d200da34bf374293fe739 | /src/topology/metric_space/gromov_hausdorff.lean | 59e8bf0b86afe20e7b8a42bcd0eeb5ec28f49ba4 | [
"Apache-2.0"
] | permissive | Vtec234/mathlib | b50c7b21edea438df7497e5ed6a45f61527f0370 | fb1848bbbfce46152f58e219dc0712f3289d2b20 | refs/heads/master | 1,592,463,095,113 | 1,562,737,749,000 | 1,562,737,749,000 | 196,202,858 | 0 | 0 | Apache-2.0 | 1,562,762,338,000 | 1,562,762,337,000 | null | UTF-8 | Lean | false | false | 56,063 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sébastien Gouëzel
The Gromov-Hausdorff distance on the space of nonempty compact metric spaces up to isometry.
We introduces the space of all nonempty compact metric spaces, up to isometry,
called `GH_space`, and endow it with a metric space structure. The distance,
known as the Gromov-Hausdorff distance, is defined as follows: given two
nonempty compact spaces X and Y, their distance is the minimum Hausdorff distance
between all possible isometric embeddings of X and Y in all metric spaces.
To define properly the Gromov-Hausdorff space, we consider the non-empty
compact subsets of ℓ^∞(ℝ) up to isometry, which is a well-defined type,
and define the distance as the infimum of the Hausdorff distance over all
embeddings in ℓ^∞(ℝ). We prove that this coincides with the previous description,
as all separable metric spaces embed isometrically into ℓ^∞(ℝ), through an
embedding called the Kuratowski embedding.
To prove that we have a distance, we should show that if spaces can be coupled
to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff
distance is realized, i.e., there is a coupling for which the Hausdorff distance
is exactly the Gromov-Hausdorff distance. This follows from a compactness
argument, essentially following from Arzela-Ascoli.
We prove the most important properties of the Gromov-Hausdorff space: it is a polish space,
i.e., it is complete and second countable. We also prove the Gromov compactness criterion.
-/
import topology.metric_space.closeds set_theory.cardinal topology.metric_space.gromov_hausdorff_realized
topology.metric_space.completion
noncomputable theory
local attribute [instance, priority 0] classical.prop_decidable
universes u v w
open classical lattice set function topological_space filter metric quotient
open bounded_continuous_function nat Kuratowski_embedding
open sum (inl inr)
set_option class.instance_max_depth 50
local attribute [instance] metric_space_sum
namespace Gromov_Hausdorff
section GH_space
/- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient
of nonempty compact subsets of ℓ^∞(ℝ) by identifying isometric sets.
Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty
compact type to GH_space. -/
/-- Equivalence relation identifying two nonempty compact sets which are isometric -/
private definition isometry_rel : nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop :=
λx y, nonempty (x.val ≃ᵢ y.val)
/-- This is indeed an equivalence relation -/
private lemma is_equivalence_isometry_rel : equivalence isometry_rel :=
⟨λx, ⟨isometric.refl _⟩, λx y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩
/-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/
instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) :=
setoid.mk isometry_rel is_equivalence_isometry_rel
/-- The Gromov-Hausdorff space -/
definition GH_space : Type := quotient (isometry_rel.setoid)
/-- Map any nonempty compact type to GH_space -/
definition to_GH_space (α : Type u) [metric_space α] [compact_space α] [nonempty α] : GH_space :=
⟦nonempty_compacts.Kuratowski_embedding α⟧
/-- A metric space representative of any abstract point in GH_space -/
definition GH_space.rep (p : GH_space) : Type := (quot.out p).val
lemma eq_to_GH_space_iff {α : Type u} [metric_space α] [compact_space α] [nonempty α] {p : nonempty_compacts ℓ_infty_ℝ} :
⟦p⟧ = to_GH_space α ↔ ∃Ψ : α → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p.val :=
begin
simp only [to_GH_space, quotient.eq],
split,
{ assume h,
rcases setoid.symm h with ⟨e⟩,
have f := (Kuratowski_embedding_isometry α).isometric_on_range.trans e,
use λx, f x,
split,
{ apply isometry_subtype_val.comp f.isometry },
{ rw [range_comp, f.range_coe, set.image_univ, set.range_coe_subtype] } },
{ rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩,
have f := ((Kuratowski_embedding_isometry α).isometric_on_range.symm.trans
isomΨ.isometric_on_range).symm,
have E : (range Ψ) ≃ᵢ (nonempty_compacts.Kuratowski_embedding α).val = (p.val ≃ᵢ range (Kuratowski_embedding α)),
by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl },
have g := cast E f,
exact ⟨g⟩ }
end
lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p.val :=
begin
refine eq_to_GH_space_iff.2 ⟨((λx, x) : p.val → ℓ_infty_ℝ), _, subtype.val_range⟩,
apply isometry_subtype_val
end
section
local attribute [reducible] GH_space.rep
instance rep_GH_space_metric_space {p : GH_space} : metric_space (p.rep) :=
by apply_instance
instance rep_GH_space_compact_space {p : GH_space} : compact_space (p.rep) :=
by apply_instance
instance rep_GH_space_nonempty {p : GH_space} : nonempty (p.rep) :=
by apply_instance
end
lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space (p.rep) = p :=
begin
change to_GH_space (quot.out p).val = p,
rw ← eq_to_GH_space,
exact quot.out_eq p
end
/-- Two nonempty compact spaces have the same image in GH_space if and only if they are isometric -/
lemma to_GH_space_eq_to_GH_space_iff_isometric {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type u} [metric_space β] [compact_space β] [nonempty β] :
to_GH_space α = to_GH_space β ↔ nonempty (α ≃ᵢ β) :=
⟨begin
simp only [to_GH_space, quotient.eq],
assume h,
rcases h with e,
have I : ((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val)
= ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
have e' := cast I e,
have f := (Kuratowski_embedding_isometry α).isometric_on_range,
have g := (Kuratowski_embedding_isometry β).isometric_on_range.symm,
have h := (f.trans e').trans g,
exact ⟨h⟩
end,
begin
rintros ⟨e⟩,
simp only [to_GH_space, quotient.eq],
have f := (Kuratowski_embedding_isometry α).isometric_on_range.symm,
have g := (Kuratowski_embedding_isometry β).isometric_on_range,
have h := (f.trans e).trans g,
have I : ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))) =
((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
have h' := cast I h,
exact ⟨h'⟩
end⟩
/-- Distance on GH_space : the distance between two nonempty compact spaces is the infimum
Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition,
we only consider embeddings in ℓ^∞(ℝ), but we will prove below that it works for all spaces. -/
instance : has_dist (GH_space) :=
{ dist := λx y, Inf ((λp : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ, Hausdorff_dist p.1.val p.2.val) ''
(set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y})) }
def GH_dist (α : Type u) (β : Type v) [metric_space α] [nonempty α] [compact_space α]
[metric_space β] [nonempty β] [compact_space β] : ℝ := dist (to_GH_space α) (to_GH_space β)
lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist (p.rep) (q.rep) :=
by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep]
/-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance
of isometric copies of the spaces, in any metric space. -/
theorem GH_dist_le_Hausdorff_dist {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type v} [metric_space β] [compact_space β] [nonempty β]
{γ : Type w} [metric_space γ] {Φ : α → γ} {Ψ : β → γ} (ha : isometry Φ) (hb : isometry Ψ) :
GH_dist α β ≤ Hausdorff_dist (range Φ) (range Ψ) :=
begin
/- For the proof, we want to embed γ in ℓ^∞(ℝ), to say that the Hausdorff distance is realized
in ℓ^∞(ℝ) and therefore bounded below by the Gromov-Hausdorff-distance. However, γ is not
separable in general. We restrict to the union of the images of α and β in γ, which is
separable and therefore embeddable in ℓ^∞(ℝ). -/
rcases exists_mem_of_nonempty α with ⟨xα, _⟩,
letI : inhabited α := ⟨xα⟩,
letI : inhabited β := classical.inhabited_of_nonempty (by assumption),
let s : set γ := (range Φ) ∪ (range Ψ),
let Φ' : α → subtype s := λy, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩,
let Ψ' : β → subtype s := λy, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩,
have IΦ' : isometry Φ' := λx y, ha x y,
have IΨ' : isometry Ψ' := λx y, hb x y,
have : compact s,
{ apply compact_union_of_compact,
{ rw ← image_univ,
apply compact_image compact_univ ha.continuous },
{ rw ← image_univ,
apply compact_image compact_univ hb.continuous } },
letI : metric_space (subtype s) := by apply_instance,
haveI : compact_space (subtype s) := ⟨compact_iff_compact_univ.1 ‹compact s›⟩,
haveI : nonempty (subtype s) := ⟨Φ' xα⟩,
have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl },
have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl },
have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'),
{ rw [ΦΦ', ΨΨ', range_comp, range_comp],
exact Hausdorff_dist_image (isometry_subtype_val) },
rw this,
-- Embed s in ℓ^∞(ℝ) through its Kuratowski embedding
let F := Kuratowski_embedding (subtype s),
have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) = Hausdorff_dist (range Φ') (range Ψ') :=
Hausdorff_dist_image (Kuratowski_embedding_isometry _),
rw ← this,
-- Let A and B be the images of α and β under this embedding. They are in ℓ^∞(ℝ), and
-- their Hausdorff distance is the same as in the original space.
let A : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Φ'), ⟨by simp, begin
rw [← range_comp, ← image_univ],
exact compact_image compact_univ
((Kuratowski_embedding_isometry _).continuous.comp IΦ'.continuous),
end⟩⟩,
let B : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Ψ'), ⟨by simp, begin
rw [← range_comp, ← image_univ],
exact compact_image compact_univ
((Kuratowski_embedding_isometry _).continuous.comp IΨ'.continuous),
end⟩⟩,
have Aα : ⟦A⟧ = to_GH_space α,
{ rw eq_to_GH_space_iff,
exact ⟨λx, F (Φ' x), ⟨(Kuratowski_embedding_isometry _).comp IΦ', by rw range_comp⟩⟩ },
have Bβ : ⟦B⟧ = to_GH_space β,
{ rw eq_to_GH_space_iff,
exact ⟨λx, F (Ψ' x), ⟨(Kuratowski_embedding_isometry _).comp IΨ', by rw range_comp⟩⟩ },
refine cInf_le ⟨0, begin simp, assume t _ _ _ _ ht, rw ← ht, exact Hausdorff_dist_nonneg end⟩ _,
apply (mem_image _ _ _).2,
existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
simp [Aα, Bβ]
end
local attribute [instance, priority 0] inhabited_of_nonempty'
/-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance,
essentially by design. -/
lemma Hausdorff_dist_optimal {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type v} [metric_space β] [compact_space β] [nonempty β] :
Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) = GH_dist α β :=
begin
/- we only need to check the inequality ≤, as the other one follows from the previous lemma.
As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance
in the optimal coupling is smaller than the Hausdorff distance of any coupling.
First, we check this for couplings which already have small Hausdorff distance: in this
case, the induced "distance" on α ⊕ β belongs to the candidates family introduced in the
definition of the optimal coupling, and the conclusion follows from the optimality
of the optimal coupling within this family.
-/
have A : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β →
Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β) →
Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val),
{ assume p q hp hq bound,
rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩,
rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩,
have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β),
{ rcases exists_mem_of_nonempty α with ⟨xα, _⟩,
have : ∃y ∈ range Ψ, dist (Φ xα) y < diam (univ : set α) + 1 + diam (univ : set β),
{ rw Ψrange,
have : Φ xα ∈ p.val := begin rw ← Φrange, exact mem_range_self _ end,
exact exists_dist_lt_of_Hausdorff_dist_lt this bound
(Hausdorff_edist_ne_top_of_ne_empty_of_bounded p.2.1 q.2.1 (bounded_of_compact p.2.2) (bounded_of_compact q.2.2)) },
rcases this with ⟨y, hy, dy⟩,
rcases mem_range.1 hy with ⟨z, hzy⟩,
rw ← hzy at dy,
have DΦ : diam (range Φ) = diam (univ : set α) :=
begin rw [← image_univ], apply metric.isometry.diam_image Φisom end,
have DΨ : diam (range Ψ) = diam (univ : set β) :=
begin rw [← image_univ], apply metric.isometry.diam_image Ψisom end,
calc
diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xα) (Ψ z) + diam (range Ψ) :
diam_union (mem_range_self _) (mem_range_self _)
... ≤ diam (univ : set α) + (diam (univ : set α) + 1 + diam (univ : set β)) + diam (univ : set β) :
by { rw [DΦ, DΨ], apply add_le_add (add_le_add (le_refl _) (le_of_lt dy)) (le_refl _) }
... = 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by ring },
let f : α ⊕ β → ℓ_infty_ℝ := λx, match x with | inl y := Φ y | inr z := Ψ z end,
let F : (α ⊕ β) × (α ⊕ β) → ℝ := λp, dist (f p.1) (f p.2),
-- check that the induced "distance" is a candidate
have Fgood : F ∈ candidates α β,
{ simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero,
and_self, set.mem_set_of_eq],
repeat {split},
{ exact λx y, calc
F (inl x, inl y) = dist (Φ x) (Φ y) : rfl
... = dist x y : Φisom.dist_eq },
{ exact λx y, calc
F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl
... = dist x y : Ψisom.dist_eq },
{ exact λx y, dist_comm _ _ },
{ exact λx y z, dist_triangle _ _ _ },
{ exact λx y, calc
F (x, y) ≤ diam (range Φ ∪ range Ψ) :
begin
have A : ∀z : α ⊕ β, f z ∈ range Φ ∪ range Ψ,
{ assume z,
cases z,
{ apply mem_union_left, apply mem_range_self },
{ apply mem_union_right, apply mem_range_self } },
refine dist_le_diam_of_mem _ (A _) (A _),
rw [Φrange, Ψrange],
exact bounded_of_compact (compact_union_of_compact p.2.2 q.2.2),
end
... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : I } },
let Fb := candidates_b_of_candidates F Fgood,
have : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD Fb :=
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood),
refine le_trans this (le_of_forall_le_of_dense (λr hr, _)),
have I1 : ∀x : α, infi (λy:β, Fb (inl x, inr y)) ≤ r,
{ assume x,
have : f (inl x) ∈ p.val, by { rw [← Φrange], apply mem_range_self },
rcases exists_dist_lt_of_Hausdorff_dist_lt this hr
(Hausdorff_edist_ne_top_of_ne_empty_of_bounded p.2.1 q.2.1 (bounded_of_compact p.2.2) (bounded_of_compact q.2.2))
with ⟨z, zq, hz⟩,
have : z ∈ range Ψ, by rwa [← Ψrange] at zq,
rcases mem_range.1 this with ⟨y, hy⟩,
calc infi (λy:β, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa using HD_below_aux1 0)
... = dist (Φ x) (Ψ y) : rfl
... = dist (f (inl x)) z : by rw hy
... ≤ r : le_of_lt hz },
have I2 : ∀y : β, infi (λx:α, Fb (inl x, inr y)) ≤ r,
{ assume y,
have : f (inr y) ∈ q.val, by { rw [← Ψrange], apply mem_range_self },
rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr
(Hausdorff_edist_ne_top_of_ne_empty_of_bounded p.2.1 q.2.1 (bounded_of_compact p.2.2) (bounded_of_compact q.2.2))
with ⟨z, zq, hz⟩,
have : z ∈ range Φ, by rwa [← Φrange] at zq,
rcases mem_range.1 this with ⟨x, hx⟩,
calc infi (λx:α, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa using HD_below_aux2 0)
... = dist (Φ x) (Ψ y) : rfl
... = dist z (f (inr y)) : by rw hx
... ≤ r : le_of_lt hz },
simp [HD, csupr_le I1, csupr_le I2] },
/- Get the same inequality for any coupling. If the coupling is quite good, the desired
inequality has been proved above. If it is bad, then the inequality is obvious. -/
have B : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β →
Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val),
{ assume p q hp hq,
by_cases h : Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β),
{ exact A p q hp hq h },
{ calc Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD (candidates_b_dist α β) :
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b)
... ≤ diam (univ : set α) + 1 + diam (univ : set β) : HD_candidates_b_dist_le
... ≤ Hausdorff_dist (p.val) (q.val) : not_lt.1 h } },
refine le_antisymm _ _,
{ apply le_cInf,
{ rw ne_empty_iff_exists_mem,
simp only [set.mem_image, nonempty_of_inhabited, set.mem_set_of_eq, prod.exists],
existsi [Hausdorff_dist (nonempty_compacts.Kuratowski_embedding α).val (nonempty_compacts.Kuratowski_embedding β).val,
nonempty_compacts.Kuratowski_embedding α, nonempty_compacts.Kuratowski_embedding β],
simp [to_GH_space, -quotient.eq] },
{ rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩,
exact B p q hp hq } },
{ exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl α β) (isometry_optimal_GH_injr α β) }
end
/-- The Gromov-Hausdorff distance can also be realized by a coupling in ℓ^∞(ℝ), by embedding
the optimal coupling through its Kuratowski embedding. -/
theorem GH_dist_eq_Hausdorff_dist (α : Type u) [metric_space α] [compact_space α] [nonempty α]
(β : Type v) [metric_space β] [compact_space β] [nonempty β] :
∃Φ : α → ℓ_infty_ℝ, ∃Ψ : β → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧
GH_dist α β = Hausdorff_dist (range Φ) (range Ψ) :=
begin
let F := Kuratowski_embedding (optimal_GH_coupling α β),
let Φ := F ∘ optimal_GH_injl α β,
let Ψ := F ∘ optimal_GH_injr α β,
refine ⟨Φ, Ψ, _, _, _⟩,
{ exact (Kuratowski_embedding_isometry _).comp (isometry_optimal_GH_injl α β) },
{ exact (Kuratowski_embedding_isometry _).comp (isometry_optimal_GH_injr α β) },
{ rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr α β),
image_univ, ← Hausdorff_dist_optimal],
exact (Hausdorff_dist_image (Kuratowski_embedding_isometry _)).symm },
end
-- without the next two lines, { exact closed_of_compact (range Φ) hΦ } in the next
-- proof is very slow, as the t2_space instance is very hard to find
local attribute [instance, priority 0] orderable_topology.t2_space
local attribute [instance, priority 0] ordered_topology.to_t2_space
/-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/
instance GH_space_metric_space : metric_space GH_space :=
{ dist_self := λx, begin
rcases exists_rep x with ⟨y, hy⟩,
refine le_antisymm _ _,
{ apply cInf_le,
{ exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩},
{ simp, existsi [y, y], simpa } },
{ apply le_cInf,
{ simp only [set.image_eq_empty, ne.def],
apply ne_empty_iff_exists_mem.2,
existsi (⟨y, y⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
simpa },
{ rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } },
end,
dist_comm := λx y, begin
have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist ((p.fst).val) ((p.snd).val)) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y})
= ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist ((p.fst).val) ((p.snd).val)) ∘ prod.swap) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) :=
by { congr, funext, simp, rw Hausdorff_dist_comm },
simp only [dist, A, image_comp, prod.swap, image_swap_prod],
end,
eq_of_dist_eq_zero := λx y hxy, begin
/- To show that two spaces at zero distance are isometric, we argue that the distance
is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance,
i.e., they coincide. Therefore, the original spaces are isometric. -/
rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩,
rw [← dist_GH_dist, hxy] at DΦΨ,
have : range Φ = range Ψ,
{ have hΦ : compact (range Φ) :=
by { rw [← image_univ], exact compact_image compact_univ Φisom.continuous },
have hΨ : compact (range Ψ) :=
by { rw [← image_univ], exact compact_image compact_univ Ψisom.continuous },
apply (Hausdorff_dist_zero_iff_eq_of_closed _ _ _).1 (DΦΨ.symm),
{ exact closed_of_compact (range Φ) hΦ },
{ exact closed_of_compact (range Ψ) hΨ },
{ exact Hausdorff_edist_ne_top_of_ne_empty_of_bounded (by simp [-nonempty_subtype])
(by simp [-nonempty_subtype]) (bounded_of_compact hΦ) (bounded_of_compact hΨ) } },
have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this,
have eΨ := cast T Ψisom.isometric_on_range.symm,
have e := Φisom.isometric_on_range.trans eΨ,
rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric],
exact ⟨e⟩
end,
dist_triangle := λx y z, begin
/- To show the triangular inequality between X, Y and Z, realize an optimal coupling
between X and Y in a space γ1, and an optimal coupling between Y and Z in a space γ2. Then,
glue these metric spaces along Y. We get a new space γ in which X and Y are optimally coupled,
as well as Y and Z. Apply the triangle inequality for the Hausdorff distance in γ to conclude. -/
let X := x.rep,
let Y := y.rep,
let Z := z.rep,
let γ1 := optimal_GH_coupling X Y,
let γ2 := optimal_GH_coupling Y Z,
let Φ : Y → γ1 := optimal_GH_injr X Y,
have hΦ : isometry Φ := isometry_optimal_GH_injr X Y,
let Ψ : Y → γ2 := optimal_GH_injl Y Z,
have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z,
let γ := glue_space hΦ hΨ,
letI : metric_space γ := metric.metric_space_glue_space hΦ hΨ,
have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) = (to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) :=
to_glue_commute hΦ hΨ,
calc dist x z = dist (to_GH_space X) (to_GH_space Z) :
by rw [x.to_GH_space_rep, z.to_GH_space_rep]
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
GH_dist_le_Hausdorff_dist
((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y))
((to_glue_r_isometry hΦ hΨ).comp (isometry_optimal_GH_injr Y Z))
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
+ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
begin
refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_ne_empty_of_bounded
(by simp [-nonempty_subtype]) (by simp [-nonempty_subtype]) _ _),
{ rw [← image_univ],
exact bounded_of_compact (compact_image compact_univ (isometry.continuous
((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y)))) },
{ rw [← image_univ],
exact bounded_of_compact (compact_image compact_univ (isometry.continuous
((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injr X Y)))) }
end
... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y)))
((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y)))
+ Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z)))
((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) :
by simp only [eq.symm range_comp, Comm, eq_self_iff_true, add_right_inj]
... = Hausdorff_dist (range (optimal_GH_injl X Y))
(range (optimal_GH_injr X Y))
+ Hausdorff_dist (range (optimal_GH_injl Y Z))
(range (optimal_GH_injr Y Z)) :
by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ),
Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)]
... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) :
by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist]
... = dist x y + dist y z:
by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep]
end }
end GH_space --section
end Gromov_Hausdorff
/-- In particular, nonempty compacts of a metric space map to GH_space. We register this
in the topological_space namespace to take advantage of the notation p.to_GH_space -/
definition topological_space.nonempty_compacts.to_GH_space {α : Type u} [metric_space α]
(p : nonempty_compacts α) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p.val
open topological_space
namespace Gromov_Hausdorff
section nonempty_compacts
variables {α : Type u} [metric_space α]
theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts α) :
dist p.to_GH_space q.to_GH_space ≤ dist p q :=
begin
have ha : isometry (subtype.val : p.val → α) := isometry_subtype_val,
have hb : isometry (subtype.val : q.val → α) := isometry_subtype_val,
have A : dist p q = Hausdorff_dist p.val q.val := rfl,
have I : p.val = range (subtype.val : p.val → α), by simp,
have J : q.val = range (subtype.val : q.val → α), by simp,
rw [I, J] at A,
rw A,
exact GH_dist_le_Hausdorff_dist ha hb
end
lemma to_GH_space_lipschitz :
lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) :=
⟨zero_le_one, by { simp, exact GH_dist_le_nonempty_compacts_dist } ⟩
lemma to_GH_space_continuous :
continuous (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) :=
to_GH_space_lipschitz.to_continuous
end nonempty_compacts
section
/- In this section, we show that if two metric spaces are isometric up to ε2, then their
Gromov-Hausdorff distance is bounded by ε2 / 2. More generally, if there are subsets which are
ε1-dense and ε3-dense in two spaces, and isometric up to ε2, then the Gromov-Hausdorff distance
between the spaces is bounded by ε1 + ε2/2 + ε3. For this, we construct a suitable coupling between
the two spaces, by gluing them (approximately) along the two matching subsets. -/
variables {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type v} [metric_space β] [compact_space β] [nonempty β]
/-- If there are subsets which are ε1-dense and ε3-dense in two spaces, and
isometric up to ε2, then the Gromov-Hausdorff distance between the spaces is bounded by
ε1 + ε2/2 + ε3. -/
theorem GH_dist_le_of_approx_subsets {s : set α} (Φ : s → β) {ε1 ε2 ε3 : ℝ}
(hs : ∀x : α, ∃y ∈ s, dist x y ≤ ε1) (hs' : ∀x : β, ∃y : s, dist x (Φ y) ≤ ε3)
(H : ∀x y : s, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε2) :
GH_dist α β ≤ ε1 + ε2 / 2 + ε3 :=
begin
refine real.le_of_forall_epsilon_le (λδ δ0, _),
rcases exists_mem_of_nonempty α with ⟨xα, _⟩,
rcases hs xα with ⟨xs, hxs, Dxs⟩,
have sne : s ≠ ∅ := ne_empty_of_mem hxs,
letI : nonempty (subtype s) := ⟨⟨xs, hxs⟩⟩,
have : 0 ≤ ε2 := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩),
have : ∀ p q : s, abs (dist p q - dist (Φ p) (Φ q)) ≤ 2 * (ε2/2 + δ) := λp q, calc
abs (dist p q - dist (Φ p) (Φ q)) ≤ ε2 : H p q
... ≤ 2 * (ε2/2 + δ) : by linarith,
-- glue α and β along the almost matching subsets
letI : metric_space (α ⊕ β) := glue_metric_approx (@subtype.val α s) (λx, Φ x) (ε2/2 + δ) (by linarith) this,
let Fl := @sum.inl α β,
let Fr := @sum.inr α β,
have Il : isometry Fl := isometry_emetric_iff_metric.2 (λx y, rfl),
have Ir : isometry Fr := isometry_emetric_iff_metric.2 (λx y, rfl),
/- The proof goes as follows : the GH_dist is bounded by the Hausdorff distance of the images in the
coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff distances
of α and s (in the coupling or, equivalently in the original space), of s and Φ s, and of Φ s and β
(in the coupling or, equivalently, in the original space). The first term is bounded by ε1,
by ε1-density. The third one is bounded by ε3. And the middle one is bounded by ε2/2 as in the
coupling the points x and Φ x are at distance ε2/2 by construction of the coupling (in fact
ε2/2 + δ where δ is an arbitrarily small positive constant where positivity is used to ensure
that the coupling is really a metric space and not a premetric space on α ⊕ β). -/
have : GH_dist α β ≤ Hausdorff_dist (range Fl) (range Fr) :=
GH_dist_le_Hausdorff_dist Il Ir,
have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s)
+ Hausdorff_dist (Fl '' s) (range Fr),
{ have B : bounded (range Fl) := bounded_of_compact (compact_range Il.continuous),
exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_ne_empty_of_bounded (by simpa) (by simpa)
B (bounded.subset (image_subset_range _ _) B)) },
have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ))
+ Hausdorff_dist (Fr '' (range Φ)) (range Fr),
{ have B : bounded (range Fr) := bounded_of_compact (compact_range Ir.continuous),
exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_ne_empty_of_bounded
(by simpa [-nonempty_subtype]) (by simpa) (bounded.subset (image_subset_range _ _) B) B) },
have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε1,
{ rw [← image_univ, Hausdorff_dist_image Il],
have : 0 ≤ ε1 := le_trans dist_nonneg Dxs,
refine Hausdorff_dist_le_of_mem_dist this (λx hx, hs x)
(λx hx, ⟨x, mem_univ _, by simpa⟩) },
have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε2/2 + δ,
{ refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _,
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩,
rw ← xx',
use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)],
exact le_of_eq (glue_dist_glued_points (@subtype.val α s) Φ (ε2/2 + δ) ⟨x, x_in_s⟩) },
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩,
rcases mem_range.1 y_in_s' with ⟨x, xy⟩,
use [Fl x, mem_image_of_mem _ x.2],
rw [← yx', ← xy, dist_comm],
exact le_of_eq (glue_dist_glued_points (@subtype.val α s) Φ (ε2/2 + δ) x) } },
have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε3,
{ rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir],
rcases exists_mem_of_nonempty β with ⟨xβ, _⟩,
rcases hs' xβ with ⟨xs', Dxs'⟩,
have : 0 ≤ ε3 := le_trans dist_nonneg Dxs',
refine Hausdorff_dist_le_of_mem_dist this (λx hx, ⟨x, mem_univ _, by simpa⟩) (λx _, _),
rcases hs' x with ⟨y, Dy⟩,
exact ⟨Φ y, mem_range_self _, Dy⟩ },
linarith
end
end --section
/-- The Gromov-Hausdorff space is second countable. -/
lemma second_countable : second_countable_topology GH_space :=
begin
refine second_countable_of_countable_discretization (λδ δpos, _),
let ε := (2/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
have : ∀p:GH_space, ∃s : set (p.rep), finite s ∧ (univ ⊆ (⋃x∈s, ball x ε)) :=
λp, by simpa using finite_cover_balls_of_compact (@compact_univ (p.rep) _ _ _) εpos,
-- for each p, s p is a finite ε-dense subset of p (or rather the metric space
-- p.rep representing p)
choose s hs using this,
have : ∀p:GH_space, ∀t:set (p.rep), finite t → ∃n:ℕ, ∃e:equiv t (fin n), true,
{ assume p t ht,
letI : fintype t := finite.fintype ht,
rcases fintype.exists_equiv_fin t with ⟨n, hn⟩,
rcases hn with e,
exact ⟨n, e, trivial⟩ },
choose N e hne using this,
-- cardinality of the nice finite subset s p of p.rep, called N p
let N := λp:GH_space, N p (s p) (hs p).1,
-- equiv from s p, a nice finite subset of p.rep, to fin (N p), called E p
let E := λp:GH_space, e p (s p) (hs p).1,
-- A function F associating to p ∈ GH_space the data of all distances of points
-- in the ε-dense set s p.
let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) :=
λp, ⟨N p, λa b, floor (ε⁻¹ * dist ((E p).inv_fun a) ((E p).inv_fun b))⟩,
refine ⟨_, by apply_instance, F, λp q hpq, _⟩,
/- As the target space of F is countable, it suffices to show that two points
p and q with F p = F q are at distance ≤ δ.
For this, we construct a map Φ from s p ⊆ p.rep (representing p)
to q.rep (representing q) which is almost an isometry on s p, and
with image s q. For this, we compose the identification of s p with fin (N p)
and the inverse of the identification of s q with fin (N q). Together with
the fact that N p = N q, this constructs Ψ between s p and s q, and then
composing with the canonical inclusion we get Φ. -/
have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λx, (E q).inv_fun (fin.cast Npq ((E p).to_fun x)),
let Φ : s p → q.rep := λx, Ψ x,
-- Use the almost isometry Φ to show that p.rep and q.rep
-- are within controlled Gromov-Hausdorff distance.
have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε,
{ refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, s p is ε-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ⟨ys, hy⟩⟩,
exact ⟨y, ys, le_of_lt hy⟩ },
show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, s q is ε-dense, and it is the range of Φ
assume x,
have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ⟨ys, hy⟩⟩,
let i := ((E q).to_fun ⟨y, ys⟩).1,
let hi := ((E q).to_fun ⟨y, ys⟩).2,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q).to_fun ⟨y, ys⟩, by rw fin.ext_iff,
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).inv_fun ⟨i, hip⟩,
use z,
have C1 : (E p).to_fun z = ⟨i, hip⟩ := (E p).right_inv ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).inv_fun ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).left_inv ⟨y, ys⟩ },
have : Φ z = y :=
by { simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_of_lt hy },
show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε,
{ /- the distance between x and y is encoded in F p, and the distance between
Φ x and Φ y (two points of s q) is encoded in F q, all this up to ε.
As F p = F q, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce i, that codes both x and Φ x in fin (N p) = fin (N q)
let i := ((E p).to_fun x).1,
have hip : i < N p := ((E p).to_fun x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q).to_fun (Ψ x)).1, by { simp [Ψ, (E q).right_inv _] },
-- introduce j, that codes both y and Φ y in fin (N p) = fin (N q)
let j := ((E p).to_fun y).1,
have hjp : j < N p := ((E p).to_fun y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q).to_fun (Ψ y)).1, by { simp [Ψ, (E q).right_inv _] },
-- Express dist x y in terms of F p
have : (F p).2 ((E p).to_fun x) ((E p).to_fun y) = floor (ε⁻¹ * dist x y),
by simp only [F, (E p).left_inv _],
have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y),
by { rw ← this, congr; apply (fin.ext_iff _ _).2; refl },
-- Express dist (Φ x) (Φ y) in terms of F q
have : (F q).2 ((E q).to_fun (Ψ x)) ((E q).to_fun (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by simp only [F, (E q).left_inv _],
have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by { rw ← this, congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] },
-- use the equality between F p and F q to deduce that the distances have equal
-- integer parts
have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant f
-- then subst
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
rw [Ap, Aq] at this,
-- deduce that the distances coincide up to ε, by a straightforward computation
-- that should be automated
have I := calc
abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) =
abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm
... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) :
by rw [abs_of_nonneg (le_of_lt (inv_pos εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ : by { simp [ε], ring }
end
/-- Compactness criterion : a closed set of compact metric spaces is compact if the spaces have
a uniformly bounded diameter, and for all ε the number of balls of radius ε required
to cover the space is uniformly bounded. This is an equivalence, but we only prove the
interesting direction that these conditions imply compactness. -/
lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ}
(ulim : tendsto u at_top (nhds 0))
(hdiam : ∀p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C)
(hcov : ∀p ∈ t, ∀n:ℕ, ∃s : set (GH_space.rep p), cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) :
totally_bounded t :=
begin
/- Let δ>0, and ε = δ/5. For each p, we construct a finite subset s p of p, which
is ε-dense and has cardinality at most K n. Encoding the mutual distances of points in s p,
up to ε, we will get a map F associating to p finitely many data, and making it possible to
reconstruct p up to ε. This is enough to prove total boundedness. -/
refine metric.totally_bounded_of_finite_discretization (λδ δpos, _),
let ε := (1/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
-- choose n for which ε < u n
rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩,
have u_le_ε : u n ≤ ε,
{ have := hn n (le_refl _),
simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this,
exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) },
-- construct a finite subset s p of p which is ε-dense and has cardinal ≤ K n
have : ∀p:GH_space, ∃s : set (p.rep), ∃N ≤ K n, ∃E : equiv s (fin N),
p ∈ t → univ ⊆ ⋃x∈s, ball x (u n),
{ assume p,
by_cases hp : p ∉ t,
{ have : nonempty (equiv (∅ : set (p.rep)) (fin 0)),
{ rw ← fintype.card_eq, simp },
use [∅, 0, bot_le, choice (this)] },
{ rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩,
rcases cardinal.lt_omega.1 (lt_of_le_of_lt scard (cardinal.nat_lt_omega _)) with ⟨N, hN⟩,
rw [hN, cardinal.nat_cast_le] at scard,
have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin],
cases quotient.exact this with E,
use [s, N, scard, E],
simp [hp, scover] } },
choose s N hN E hs using this,
-- Define a function F taking values in a finite type and associating to p enough data
-- to reconstruct it up to ε, namely the (discretized) distances between elements of s p.
let M := (floor (ε⁻¹ * max C 0)).to_nat,
let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) :=
λp, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩,
λa b, ⟨min M (floor (ε⁻¹ * dist ((E p).inv_fun a) ((E p).inv_fun b))).to_nat,
lt_of_le_of_lt ( min_le_left _ _) (nat.lt_succ_self _) ⟩ ⟩,
refine ⟨_, by apply_instance, (λp, F p), _⟩,
-- It remains to show that if F p = F q, then p and q are ε-close
rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq,
have Npq : N p = N q := (fin.ext_iff _ _).1 (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λx, (E q).inv_fun (fin.cast Npq ((E p).to_fun x)),
let Φ : s p → q.rep := λx, Ψ x,
have main : GH_dist (p.rep) (q.rep) ≤ ε + ε/2 + ε,
{ -- to prove the main inequality, argue that s p is ε-dense in p, and s q is ε-dense in q,
-- and s p and s q are almost isometric. Then closeness follows
-- from GH_dist_le_of_approx_subsets
refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, s p is ε-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ⟨ys, hy⟩⟩,
exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ },
show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, s q is ε-dense, and it is the range of Φ
assume x,
have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ⟨ys, hy⟩⟩,
let i := ((E q).to_fun ⟨y, ys⟩).1,
let hi := ((E q).to_fun ⟨y, ys⟩).2,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q).to_fun ⟨y, ys⟩, by rw fin.ext_iff,
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).inv_fun ⟨i, hip⟩,
use z,
have C1 : (E p).to_fun z = ⟨i, hip⟩ := (E p).right_inv ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).inv_fun ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).left_inv ⟨y, ys⟩ },
have : Φ z = y :=
by { simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_trans (le_of_lt hy) u_le_ε },
show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε,
{ /- the distance between x and y is encoded in F p, and the distance between
Φ x and Φ y (two points of s q) is encoded in F q, all this up to ε.
As F p = F q, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce i, that codes both x and Φ x in fin (N p) = fin (N q)
let i := ((E p).to_fun x).1,
have hip : i < N p := ((E p).to_fun x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q).to_fun (Ψ x)).1, by { simp [Ψ, (E q).right_inv _] },
-- introduce j, that codes both y and Φ y in fin (N p) = fin (N q)
let j := ((E p).to_fun y).1,
have hjp : j < N p := ((E p).to_fun y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q).to_fun (Ψ y)).1, by { simp [Ψ, (E q).right_inv _] },
-- Express dist x y in terms of F p
have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = (floor (ε⁻¹ * dist x y)).to_nat := calc
((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p).to_fun x) ((E p).to_fun y)).1 :
by { congr; apply (fin.ext_iff _ _).2; refl }
... = min M (floor (ε⁻¹ * dist x y)).to_nat :
by simp only [F, (E p).left_inv _]
... = (floor (ε⁻¹ * dist x y)).to_nat :
begin
refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) (le_of_lt (inv_pos εpos)),
change dist (x : p.rep) y ≤ C,
refine le_trans (dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _)) _,
exact hdiam p pt
end,
-- Express dist (Φ x) (Φ y) in terms of F q
have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat := calc
((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q).to_fun (Ψ x)) ((E q).to_fun (Ψ y))).1 :
by { congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] }
... = min M (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat :
by simp only [F, (E q).left_inv _]
... = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat :
begin
refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) (le_of_lt (inv_pos εpos)),
change dist (Ψ x : q.rep) (Ψ y) ≤ C,
refine le_trans (dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _)) _,
exact hdiam q qt
end,
-- use the equality between F p and F q to deduce that the distances have equal
-- integer parts
have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant f
-- then subst
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
have : floor (ε⁻¹ * dist x y) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
{ rw [Ap, Aq] at this,
have D : 0 ≤ floor (ε⁻¹ * dist x y) :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos εpos)) dist_nonneg),
have D' : floor (ε⁻¹ * dist (Ψ x) (Ψ y)) ≥ 0 :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos εpos)) dist_nonneg),
rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', this] },
-- deduce that the distances coincide up to ε, by a straightforward computation
-- that should be automated
have I := calc
abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) =
abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm
... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) :
by rw [abs_of_nonneg (le_of_lt (inv_pos εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ/2 : by { simp [ε], ring }
... < δ : half_lt_self δpos
end
section complete
/- We will show that a sequence `u n` of compact metric spaces satisfying
`dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space.
We need to exhibit the limiting compact metric space. For this, start from
a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)`
for all `n`, in a common metric space. Formally, this is done as follows.
Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space
`Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and
glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an
embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive
limit of the `Y n`, and finally let `Z` be the completion of `Z0`.
The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they
form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its
set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty
compact metric space we are looking for. -/
variables (X : ℕ → Type) [∀n, metric_space (X n)] [∀n, compact_space (X n)] [∀n, nonempty (X n)]
structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 :=
(space : Type)
(metric : metric_space space)
(embed : A → space)
(isom : isometry embed)
def aux_gluing (n : ℕ) : aux_gluing_struct (X n) := nat.rec_on n
{ space := X 0,
metric := by apply_instance,
embed := id,
isom := λx y, rfl }
(λn a, by letI : metric_space a.space := a.metric; exact
{ space := glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)),
metric := metric.metric_space_glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)),
embed := (to_glue_r a.isom (isometry_optimal_GH_injl (X n) (X n.succ)))
∘ (optimal_GH_injr (X n) (X n.succ)),
isom := (to_glue_r_isometry _ _).comp (isometry_optimal_GH_injr (X n) (X n.succ)) })
/-- The Gromov-Hausdorff space is complete. -/
instance : complete_space (GH_space) :=
begin
have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply _root_.pow_pos, norm_num },
-- start from a sequence of nonempty compact metric spaces within distance 1/2^n of each other
refine metric.complete_of_convergent_controlled_sequences (λn, (1/2)^n) this (λu hu, _),
-- X n is a representative of u n
let X := λn, (u n).rep,
-- glue them together successively in an optimal way, getting a sequence of metric spaces Y n
let Y := aux_gluing X,
letI : ∀n, metric_space (Y n).space := λn, (Y n).metric,
have E : ∀n:ℕ, glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)) = (Y n.succ).space :=
λn, by { simp [Y, aux_gluing], refl },
let c := λn, cast (E n),
have ic : ∀n, isometry (c n) := λn x y, rfl,
-- there is a canonical embedding of Y n in Y (n+1), by construction
let f : Πn, (Y n).space → (Y n.succ).space :=
λn, (c n) ∘ (to_glue_l (aux_gluing X n).isom (isometry_optimal_GH_injl (X n) (X n.succ))),
have I : ∀n, isometry (f n),
{ assume n,
apply isometry.comp,
{ assume x y, refl },
{ apply to_glue_l_isometry } },
-- consider the inductive limit Z0 of the Y n, and then its completion Z
let Z0 := metric.inductive_limit I,
let Z := uniform_space.completion Z0,
let Φ := to_inductive_limit I,
let coeZ := (coe : Z0 → Z),
-- let X2 n be the image of X n in the space Z
let X2 := λn, range (coeZ ∘ (Φ n) ∘ (Y n).embed),
have isom : ∀n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed),
{ assume n,
apply isometry.comp completion.coe_isometry _,
apply isometry.comp _ (Y n).isom,
apply to_inductive_limit_isometry },
-- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between
-- `u n` and `u (n+1)`, therefore bounded by 1/2^n
have D2 : ∀n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n,
{ assume n,
have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injl (X n) (X n.succ))),
{ change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))
∘ (optimal_GH_injl (X n) (X n.succ))),
simp only [X2, Φ],
rw [← to_inductive_limit_commute I],
simp only [f],
rw ← to_glue_commute },
rw range_comp at X2n,
have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injr (X n) (X n.succ))), by refl,
rw range_comp at X2nsucc,
rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist],
{ exact hu n n n.succ (le_refl n) (le_succ n) },
{ apply isometry.comp completion.coe_isometry _,
apply isometry.comp _ ((ic n).comp (to_glue_r_isometry _ _)),
apply to_inductive_limit_isometry } },
-- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which
-- is a metric space
let X3 : ℕ → nonempty_compacts Z := λn, ⟨X2 n,
⟨by { simp only [X2, set.range_eq_empty, not_not, ne.def], apply_instance },
compact_range (isom n).continuous ⟩⟩,
-- `X3 n` is a Cauchy sequence by construction, as the successive distances are
-- bounded by (1/2)^n
have : cauchy_seq X3,
{ refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λn, _),
rw one_mul,
exact le_of_lt (D2 n) },
-- therefore, it converges to a limit `L`
rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩,
-- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L`
have M : tendsto (λn, (X3 n).to_GH_space) at_top (nhds L.to_GH_space) :=
tendsto.comp (to_GH_space_continuous.tendsto _) hL,
-- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`.
have : ∀n, (X3 n).to_GH_space = u n,
{ assume n,
rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep,
to_GH_space_eq_to_GH_space_iff_isometric],
constructor,
convert (isom n).isometric_on_range.symm,
},
-- Finally, we have proved the convergence of `u n`
exact ⟨L.to_GH_space, by simpa [this] using M⟩
end
end complete--section
end Gromov_Hausdorff --namespace
|
7e8c7d87d720208abe0bb89a3a6112f43b040a11 | abd85493667895c57a7507870867b28124b3998f | /src/algebra/ordered_field.lean | 730903ed5b09b4342cf077ce30f5c9f669a8c4e0 | [
"Apache-2.0"
] | permissive | pechersky/mathlib | d56eef16bddb0bfc8bc552b05b7270aff5944393 | f1df14c2214ee114c9738e733efd5de174deb95d | refs/heads/master | 1,666,714,392,571 | 1,591,747,567,000 | 1,591,747,567,000 | 270,557,274 | 0 | 0 | Apache-2.0 | 1,591,597,975,000 | 1,591,597,974,000 | null | UTF-8 | Lean | false | false | 25,404 | lean | /-
Copyright (c) 2014 Robert Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Lewis, Leonardo de Moura, Mario Carneiro
-/
import algebra.ordered_ring
import algebra.field
set_option default_priority 100 -- see Note [default priority]
set_option old_structure_cmd true
variable {α : Type*}
@[protect_proj] class linear_ordered_field (α : Type*) extends linear_ordered_ring α, field α
section linear_ordered_field
variables [linear_ordered_field α] {a b c d e : α}
lemma mul_zero_lt_mul_inv_of_pos (h : 0 < a) : a * 0 < a * (1 / a) :=
calc a * 0 = 0 : by rw mul_zero
... < 1 : zero_lt_one
... = a * a⁻¹ : eq.symm (mul_inv_cancel (ne.symm (ne_of_lt h)))
... = a * (1 / a) : by rw inv_eq_one_div
lemma mul_zero_lt_mul_inv_of_neg (h : a < 0) : a * 0 < a * (1 / a) :=
calc a * 0 = 0 : by rw mul_zero
... < 1 : zero_lt_one
... = a * a⁻¹ : eq.symm (mul_inv_cancel (ne_of_lt h))
... = a * (1 / a) : by rw inv_eq_one_div
lemma one_div_pos_of_pos (h : 0 < a) : 0 < 1 / a :=
lt_of_mul_lt_mul_left (mul_zero_lt_mul_inv_of_pos h) (le_of_lt h)
lemma pos_of_one_div_pos (h : 0 < 1 / a) : 0 < a :=
one_div_one_div a ▸ one_div_pos_of_pos h
lemma one_div_neg_of_neg (h : a < 0) : 1 / a < 0 :=
gt_of_mul_lt_mul_neg_left (mul_zero_lt_mul_inv_of_neg h) (le_of_lt h)
lemma neg_of_one_div_neg (h : 1 / a < 0) : a < 0 :=
one_div_one_div a ▸ one_div_neg_of_neg h
lemma le_mul_of_ge_one_right (hb : b ≥ 0) (h : a ≥ 1) : b ≤ b * a :=
suffices b * 1 ≤ b * a, by rwa mul_one at this,
mul_le_mul_of_nonneg_left h hb
lemma le_mul_of_ge_one_left (hb : b ≥ 0) (h : a ≥ 1) : b ≤ a * b :=
by rw mul_comm; exact le_mul_of_ge_one_right hb h
lemma lt_mul_of_gt_one_right (hb : b > 0) (h : a > 1) : b < b * a :=
suffices b * 1 < b * a, by rwa mul_one at this,
mul_lt_mul_of_pos_left h hb
lemma one_le_div_of_le (a : α) {b : α} (hb : b > 0) (h : b ≤ a) : 1 ≤ a / b :=
have hb' : b ≠ 0, from ne.symm (ne_of_lt hb),
have hbinv : 1 / b > 0, from one_div_pos_of_pos hb,
calc
1 = b * (1 / b) : eq.symm (mul_one_div_cancel hb')
... ≤ a * (1 / b) : mul_le_mul_of_nonneg_right h (le_of_lt hbinv)
... = a / b : eq.symm $ div_eq_mul_one_div a b
lemma le_of_one_le_div (a : α) {b : α} (hb : b > 0) (h : 1 ≤ a / b) : b ≤ a :=
have hb' : b ≠ 0, from ne.symm (ne_of_lt hb),
calc
b ≤ b * (a / b) : le_mul_of_ge_one_right (le_of_lt hb) h
... = a : by rw [mul_div_cancel' _ hb']
lemma one_lt_div_of_lt (a : α) {b : α} (hb : b > 0) (h : b < a) : 1 < a / b :=
have hb' : b ≠ 0, from ne.symm (ne_of_lt hb),
have hbinv : 1 / b > 0, from one_div_pos_of_pos hb, calc
1 = b * (1 / b) : eq.symm (mul_one_div_cancel hb')
... < a * (1 / b) : mul_lt_mul_of_pos_right h hbinv
... = a / b : eq.symm $ div_eq_mul_one_div a b
lemma lt_of_one_lt_div (a : α) {b : α} (hb : b > 0) (h : 1 < a / b) : b < a :=
have hb' : b ≠ 0, from ne.symm (ne_of_lt hb),
calc
b < b * (a / b) : lt_mul_of_gt_one_right hb h
... = a : by rw [mul_div_cancel' _ hb']
-- the following lemmas amount to four iffs, for <, ≤, ≥, >.
lemma mul_le_of_le_div (hc : 0 < c) (h : a ≤ b / c) : a * c ≤ b :=
div_mul_cancel b (ne.symm (ne_of_lt hc)) ▸ mul_le_mul_of_nonneg_right h (le_of_lt hc)
lemma le_div_of_mul_le (hc : 0 < c) (h : a * c ≤ b) : a ≤ b / c :=
calc
a = a * c * (1 / c) : mul_mul_div a (ne.symm (ne_of_lt hc))
... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right h (le_of_lt (one_div_pos_of_pos hc))
... = b / c : eq.symm $ div_eq_mul_one_div b c
lemma mul_lt_of_lt_div (hc : 0 < c) (h : a < b / c) : a * c < b :=
div_mul_cancel b (ne.symm (ne_of_lt hc)) ▸ mul_lt_mul_of_pos_right h hc
lemma lt_div_of_mul_lt (hc : 0 < c) (h : a * c < b) : a < b / c :=
calc
a = a * c * (1 / c) : mul_mul_div a (ne.symm (ne_of_lt hc))
... < b * (1 / c) : mul_lt_mul_of_pos_right h (one_div_pos_of_pos hc)
... = b / c : eq.symm $ div_eq_mul_one_div b c
lemma mul_le_of_div_le_of_neg (hc : c < 0) (h : b / c ≤ a) : a * c ≤ b :=
div_mul_cancel b (ne_of_lt hc) ▸ mul_le_mul_of_nonpos_right h (le_of_lt hc)
lemma div_le_of_mul_le_of_neg (hc : c < 0) (h : a * c ≤ b) : b / c ≤ a :=
calc
a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc)
... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right h (le_of_lt (one_div_neg_of_neg hc))
... = b / c : eq.symm $ div_eq_mul_one_div b c
lemma mul_lt_of_gt_div_of_neg (hc : c < 0) (h : a > b / c) : a * c < b :=
div_mul_cancel b (ne_of_lt hc) ▸ mul_lt_mul_of_neg_right h hc
lemma div_lt_of_mul_lt_of_pos (hc : c > 0) (h : b < a * c) : b / c < a :=
calc
a = a * c * (1 / c) : mul_mul_div a (ne_of_gt hc)
... > b * (1 / c) : mul_lt_mul_of_pos_right h (one_div_pos_of_pos hc)
... = b / c : eq.symm $ div_eq_mul_one_div b c
lemma div_lt_of_mul_gt_of_neg (hc : c < 0) (h : a * c < b) : b / c < a :=
calc
a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc)
... > b * (1 / c) : mul_lt_mul_of_neg_right h (one_div_neg_of_neg hc)
... = b / c : eq.symm $ div_eq_mul_one_div b c
lemma div_le_of_le_mul (hb : b > 0) (h : a ≤ b * c) : a / b ≤ c :=
calc
a / b = a * (1 / b) : div_eq_mul_one_div a b
... ≤ (b * c) * (1 / b) : mul_le_mul_of_nonneg_right h (le_of_lt (one_div_pos_of_pos hb))
... = (b * c) / b : eq.symm $ div_eq_mul_one_div (b * c) b
... = c : by rw [mul_div_cancel_left _ (ne.symm (ne_of_lt hb))]
lemma le_mul_of_div_le (hc : c > 0) (h : a / c ≤ b) : a ≤ b * c :=
calc
a = a / c * c : by rw (div_mul_cancel _ (ne.symm (ne_of_lt hc)))
... ≤ b * c : mul_le_mul_of_nonneg_right h (le_of_lt hc)
-- following these in the isabelle file, there are 8 biconditionals for the above with - signs
-- skipping for now
lemma mul_sub_mul_div_mul_neg (hc : c ≠ 0) (hd : d ≠ 0) (h : a / c < b / d) :
(a * d - b * c) / (c * d) < 0 :=
have h1 : a / c - b / d < 0, from calc
a / c - b / d < b / d - b / d : sub_lt_sub_right h _
... = 0 : by rw sub_self,
calc
0 > a / c - b / d : h1
... = (a * d - c * b) / (c * d) : div_sub_div _ _ hc hd
... = (a * d - b * c) / (c * d) : by rw (mul_comm b c)
lemma mul_sub_mul_div_mul_nonpos (hc : c ≠ 0) (hd : d ≠ 0) (h : a / c ≤ b / d) :
(a * d - b * c) / (c * d) ≤ 0 :=
have h1 : a / c - b / d ≤ 0, from calc
a / c - b / d ≤ b / d - b / d : sub_le_sub_right h _
... = 0 : by rw sub_self,
calc
0 ≥ a / c - b / d : h1
... = (a * d - c * b) / (c * d) : div_sub_div _ _ hc hd
... = (a * d - b * c) / (c * d) : by rw (mul_comm b c)
lemma div_lt_div_of_mul_sub_mul_div_neg (hc : c ≠ 0) (hd : d ≠ 0)
(h : (a * d - b * c) / (c * d) < 0) : a / c < b / d :=
have (a * d - c * b) / (c * d) < 0, by rwa [mul_comm c b],
have a / c - b / d < 0, by rwa [div_sub_div _ _ hc hd],
have a / c - b / d + b / d < 0 + b / d, from add_lt_add_right this _,
by rwa [zero_add, sub_eq_add_neg, neg_add_cancel_right] at this
lemma div_le_div_of_mul_sub_mul_div_nonpos (hc : c ≠ 0) (hd : d ≠ 0)
(h : (a * d - b * c) / (c * d) ≤ 0) : a / c ≤ b / d :=
have (a * d - c * b) / (c * d) ≤ 0, by rwa [mul_comm c b],
have a / c - b / d ≤ 0, by rwa [div_sub_div _ _ hc hd],
have a / c - b / d + b / d ≤ 0 + b / d, from add_le_add_right this _,
by rwa [zero_add, sub_eq_add_neg, neg_add_cancel_right] at this
lemma div_pos_of_pos_of_pos : 0 < a → 0 < b → 0 < a / b :=
begin
intros,
rw div_eq_mul_one_div,
apply mul_pos,
assumption,
apply one_div_pos_of_pos,
assumption
end
lemma div_nonneg_of_nonneg_of_pos : 0 ≤ a → 0 < b → 0 ≤ a / b :=
begin
intros, rw div_eq_mul_one_div,
apply mul_nonneg, assumption,
apply le_of_lt,
apply one_div_pos_of_pos,
assumption
end
lemma div_neg_of_neg_of_pos : a < 0 → 0 < b → a / b < 0 :=
begin
intros, rw div_eq_mul_one_div,
apply mul_neg_of_neg_of_pos,
assumption,
apply one_div_pos_of_pos,
assumption
end
lemma div_nonpos_of_nonpos_of_pos : a ≤ 0 → 0 < b → a / b ≤ 0 :=
begin
intros, rw div_eq_mul_one_div,
apply mul_nonpos_of_nonpos_of_nonneg,
assumption,
apply le_of_lt,
apply one_div_pos_of_pos,
assumption
end
lemma div_neg_of_pos_of_neg : 0 < a → b < 0 → a / b < 0 :=
begin
intros, rw div_eq_mul_one_div,
apply mul_neg_of_pos_of_neg,
assumption,
apply one_div_neg_of_neg,
assumption
end
lemma div_nonpos_of_nonneg_of_neg : 0 ≤ a → b < 0 → a / b ≤ 0 :=
begin
intros, rw div_eq_mul_one_div,
apply mul_nonpos_of_nonneg_of_nonpos,
assumption,
apply le_of_lt,
apply one_div_neg_of_neg,
assumption
end
lemma div_pos_of_neg_of_neg : a < 0 → b < 0 → 0 < a / b :=
begin
intros, rw div_eq_mul_one_div,
apply mul_pos_of_neg_of_neg,
assumption,
apply one_div_neg_of_neg,
assumption
end
lemma div_nonneg_of_nonpos_of_neg : a ≤ 0 → b < 0 → 0 ≤ a / b :=
begin
intros, rw div_eq_mul_one_div,
apply mul_nonneg_of_nonpos_of_nonpos,
assumption,
apply le_of_lt,
apply one_div_neg_of_neg,
assumption
end
lemma div_lt_div_of_lt_of_pos (h : a < b) (hc : 0 < c) : a / c < b / c :=
begin
intros,
rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c],
exact mul_lt_mul_of_pos_right h (one_div_pos_of_pos hc)
end
lemma div_le_div_of_le_of_pos (h : a ≤ b) (hc : 0 < c) : a / c ≤ b / c :=
begin
rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c],
exact mul_le_mul_of_nonneg_right h (le_of_lt (one_div_pos_of_pos hc))
end
lemma div_lt_div_of_lt_of_neg (h : b < a) (hc : c < 0) : a / c < b / c :=
begin
rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c],
exact mul_lt_mul_of_neg_right h (one_div_neg_of_neg hc)
end
lemma div_le_div_of_le_of_neg (h : b ≤ a) (hc : c < 0) : a / c ≤ b / c :=
begin
rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c],
exact mul_le_mul_of_nonpos_right h (le_of_lt (one_div_neg_of_neg hc))
end
lemma add_halves (a : α) : a / 2 + a / 2 = a :=
by { rw [div_add_div_same, ← two_mul, mul_div_cancel_left], exact two_ne_zero }
lemma sub_self_div_two (a : α) : a - a / 2 = a / 2 :=
suffices a / 2 + a / 2 - a / 2 = a / 2, by rwa add_halves at this,
by rw [add_sub_cancel]
lemma add_midpoint {a b : α} (h : a < b) : a + (b - a) / 2 < b :=
begin
rw [← div_sub_div_same, sub_eq_add_neg, add_comm (b/2), ← add_assoc, ← sub_eq_add_neg],
apply add_lt_of_lt_sub_right,
rw [sub_self_div_two, sub_self_div_two],
apply div_lt_div_of_lt_of_pos h two_pos
end
lemma div_two_sub_self (a : α) : a / 2 - a = - (a / 2) :=
suffices a / 2 - (a / 2 + a / 2) = - (a / 2), by rwa add_halves at this,
by rw [sub_add_eq_sub_sub, sub_self, zero_sub]
lemma add_self_div_two (a : α) : (a + a) / 2 = a :=
eq.symm
(iff.mpr (eq_div_iff_mul_eq _ _ (ne_of_gt (add_pos (@zero_lt_one α _) zero_lt_one)))
(begin unfold bit0, rw [left_distrib, mul_one] end))
lemma mul_le_mul_of_mul_div_le {a b c d : α} (h : a * (b / c) ≤ d) (hc : c > 0) : b * a ≤ d * c :=
begin
rw [← mul_div_assoc] at h, rw [mul_comm b],
apply le_mul_of_div_le hc h
end
lemma div_two_lt_of_pos {a : α} (h : a > 0) : a / 2 < a :=
suffices a / (1 + 1) < a, begin unfold bit0, assumption end,
have ha : a / 2 > 0, from div_pos_of_pos_of_pos h (add_pos zero_lt_one zero_lt_one),
calc
a / 2 < a / 2 + a / 2 : lt_add_of_pos_left _ ha
... = a : add_halves a
lemma div_mul_le_div_mul_of_div_le_div_pos {a b c d e : α} (h : a / b ≤ c / d)
(he : e > 0) : a / (b * e) ≤ c / (d * e) :=
begin
have h₁ := div_mul_eq_div_mul_one_div a b e,
have h₂ := div_mul_eq_div_mul_one_div c d e,
rw [h₁, h₂],
apply mul_le_mul_of_nonneg_right h,
apply le_of_lt,
apply one_div_pos_of_pos he
end
lemma exists_add_lt_and_pos_of_lt {a b : α} (h : b < a) : ∃ c : α, b + c < a ∧ 0 < c :=
begin
apply exists.intro ((a - b) / (1 + 1)),
split,
{have h2 : a + a > (b + b) + (a - b),
calc
a + a > b + a : add_lt_add_right h _
... = b + a + b - b : by rw add_sub_cancel
... = b + b + a - b : by simp [add_comm, add_left_comm]
... = (b + b) + (a - b) : by rw add_sub,
have h3 : (a + a) / 2 > ((b + b) + (a - b)) / 2,
exact div_lt_div_of_lt_of_pos h2 two_pos,
rw [one_add_one_eq_two, sub_eq_add_neg],
rw [add_self_div_two, ← div_add_div_same, add_self_div_two, sub_eq_add_neg] at h3,
exact h3},
exact div_pos_of_pos_of_pos (sub_pos_of_lt h) two_pos
end
lemma le_of_forall_sub_le {a b : α} (h : ∀ ε > 0, b - ε ≤ a) : b ≤ a :=
begin
apply le_of_not_gt,
intro hb,
cases exists_add_lt_and_pos_of_lt hb with c hc,
have hc' := h c (and.right hc),
apply (not_le_of_gt (and.left hc)) (le_add_of_sub_right_le hc')
end
lemma one_div_lt_one_div_of_lt {a b : α} (ha : 0 < a) (h : a < b) : 1 / b < 1 / a :=
begin
apply lt_div_of_mul_lt ha,
rw [mul_comm, ← div_eq_mul_one_div],
apply div_lt_of_mul_lt_of_pos (lt_trans ha h),
rwa [one_mul]
end
lemma one_div_le_one_div_of_le {a b : α} (ha : 0 < a) (h : a ≤ b) : 1 / b ≤ 1 / a :=
(lt_or_eq_of_le h).elim
(λ h, le_of_lt $ one_div_lt_one_div_of_lt ha h)
(λ h, by rw [h])
lemma one_div_lt_one_div_of_lt_of_neg {a b : α} (hb : b < 0) (h : a < b) : 1 / b < 1 / a :=
begin
apply div_lt_of_mul_gt_of_neg hb,
rw [mul_comm, ← div_eq_mul_one_div],
apply div_lt_of_mul_gt_of_neg (lt_trans h hb),
rwa [one_mul]
end
lemma one_div_le_one_div_of_le_of_neg {a b : α} (hb : b < 0) (h : a ≤ b) : 1 / b ≤ 1 / a :=
(lt_or_eq_of_le h).elim
(λ h, le_of_lt $ one_div_lt_one_div_of_lt_of_neg hb h)
(λ h, by rw [h])
lemma le_of_one_div_le_one_div {a b : α} (h : 0 < a) (hl : 1 / a ≤ 1 / b) : b ≤ a :=
le_of_not_gt $ λ hn, not_lt_of_ge hl $ one_div_lt_one_div_of_lt h hn
lemma le_of_one_div_le_one_div_of_neg {a b : α} (h : b < 0) (hl : 1 / a ≤ 1 / b) : b ≤ a :=
le_of_not_gt $ λ hn, not_lt_of_ge hl $ one_div_lt_one_div_of_lt_of_neg h hn
lemma lt_of_one_div_lt_one_div {a b : α} (h : 0 < a) (hl : 1 / a < 1 / b) : b < a :=
lt_of_not_ge $ λ hn, not_le_of_gt hl $ one_div_le_one_div_of_le h hn
lemma lt_of_one_div_lt_one_div_of_neg {a b : α} (h : b < 0) (hl : 1 / a < 1 / b) : b < a :=
lt_of_not_ge $ λ hn, not_le_of_gt hl $ one_div_le_one_div_of_le_of_neg h hn
lemma one_div_le_of_one_div_le_of_pos {a b : α} (ha : a > 0) (h : 1 / a ≤ b) : 1 / b ≤ a :=
begin
rw [← one_div_one_div a],
apply one_div_le_one_div_of_le _ h,
apply one_div_pos_of_pos ha
end
lemma one_div_le_of_one_div_le_of_neg {a b : α} (hb : b < 0) (h : 1 / a ≤ b) : 1 / b ≤ a :=
le_of_not_gt $ λ hl, begin
have : a < 0, from lt_trans hl (one_div_neg_of_neg hb),
rw ← one_div_one_div a at hl,
exact not_lt_of_ge h (lt_of_one_div_lt_one_div_of_neg hb hl)
end
lemma one_lt_one_div {a : α} (h1 : 0 < a) (h2 : a < 1) : 1 < 1 / a :=
suffices 1 / 1 < 1 / a, by rwa one_div_one at this,
one_div_lt_one_div_of_lt h1 h2
lemma one_le_one_div {a : α} (h1 : 0 < a) (h2 : a ≤ 1) : 1 ≤ 1 / a :=
suffices 1 / 1 ≤ 1 / a, by rwa one_div_one at this,
one_div_le_one_div_of_le h1 h2
lemma one_div_lt_neg_one {a : α} (h1 : a < 0) (h2 : -1 < a) : 1 / a < -1 :=
suffices 1 / a < 1 / -1, by rwa one_div_neg_one_eq_neg_one at this,
one_div_lt_one_div_of_lt_of_neg h1 h2
lemma one_div_le_neg_one {a : α} (h1 : a < 0) (h2 : -1 ≤ a) : 1 / a ≤ -1 :=
suffices 1 / a ≤ 1 / -1, by rwa one_div_neg_one_eq_neg_one at this,
one_div_le_one_div_of_le_of_neg h1 h2
lemma div_lt_div_of_pos_of_lt_of_pos (hb : 0 < b) (h : b < a) (hc : 0 < c) : c / a < c / b :=
begin
apply lt_of_sub_neg,
rw [div_eq_mul_one_div, div_eq_mul_one_div c b, ← mul_sub_left_distrib],
apply mul_neg_of_pos_of_neg,
exact hc,
apply sub_neg_of_lt,
apply one_div_lt_one_div_of_lt; assumption,
end
lemma div_mul_le_div_mul_of_div_le_div_pos' (h : a / b ≤ c / d)
(he : e > 0) : a / (b * e) ≤ c / (d * e) :=
begin
rw [div_mul_eq_div_mul_one_div, div_mul_eq_div_mul_one_div],
apply mul_le_mul_of_nonneg_right h,
apply le_of_lt,
apply one_div_pos_of_pos he
end
lemma div_pos : 0 < a → 0 < b → 0 < a / b := div_pos_of_pos_of_pos
@[simp] lemma inv_pos : ∀ {a : α}, 0 < a⁻¹ ↔ 0 < a :=
suffices ∀ a : α, 0 < a → 0 < a⁻¹,
from λ a, ⟨λ h, inv_inv' a ▸ this _ h, this a⟩,
λ a, one_div_eq_inv a ▸ one_div_pos_of_pos
@[simp] lemma inv_lt_zero : ∀ {a : α}, a⁻¹ < 0 ↔ a < 0 :=
suffices ∀ a : α, a < 0 → a⁻¹ < 0,
from λ a, ⟨λ h, inv_inv' a ▸ this _ h, this a⟩,
λ a, one_div_eq_inv a ▸ one_div_neg_of_neg
@[simp] lemma inv_nonneg : 0 ≤ a⁻¹ ↔ 0 ≤ a :=
le_iff_le_iff_lt_iff_lt.2 inv_lt_zero
@[simp] lemma inv_nonpos : a⁻¹ ≤ 0 ↔ a ≤ 0 :=
le_iff_le_iff_lt_iff_lt.2 inv_pos
lemma one_le_div_iff_le (hb : 0 < b) : 1 ≤ a / b ↔ b ≤ a :=
⟨le_of_one_le_div a hb, one_le_div_of_le a hb⟩
lemma one_lt_div_iff_lt (hb : 0 < b) : 1 < a / b ↔ b < a :=
⟨lt_of_one_lt_div a hb, one_lt_div_of_lt a hb⟩
lemma div_le_one_iff_le (hb : 0 < b) : a / b ≤ 1 ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 (one_lt_div_iff_lt hb)
lemma div_lt_one_iff_lt (hb : 0 < b) : a / b < 1 ↔ a < b :=
lt_iff_lt_of_le_iff_le (one_le_div_iff_le hb)
lemma le_div_iff (hc : 0 < c) : a ≤ b / c ↔ a * c ≤ b :=
⟨mul_le_of_le_div hc, le_div_of_mul_le hc⟩
lemma le_div_iff' (hc : 0 < c) : a ≤ b / c ↔ c * a ≤ b :=
by rw [mul_comm, le_div_iff hc]
lemma div_le_iff (hb : 0 < b) : a / b ≤ c ↔ a ≤ c * b :=
⟨le_mul_of_div_le hb, by rw [mul_comm]; exact div_le_of_le_mul hb⟩
lemma div_le_iff' (hb : 0 < b) : a / b ≤ c ↔ a ≤ b * c :=
by rw [mul_comm, div_le_iff hb]
lemma lt_div_iff (hc : 0 < c) : a < b / c ↔ a * c < b :=
⟨mul_lt_of_lt_div hc, lt_div_of_mul_lt hc⟩
lemma lt_div_iff' (hc : 0 < c) : a < b / c ↔ c * a < b :=
by rw [mul_comm, lt_div_iff hc]
lemma div_le_iff_of_neg (hc : c < 0) : b / c ≤ a ↔ a * c ≤ b :=
⟨mul_le_of_div_le_of_neg hc, div_le_of_mul_le_of_neg hc⟩
lemma le_div_iff_of_neg (hc : c < 0) : a ≤ b / c ↔ b ≤ a * c :=
by rw [← neg_neg c, mul_neg_eq_neg_mul_symm, div_neg, le_neg,
div_le_iff (neg_pos.2 hc), neg_mul_eq_neg_mul_symm]
lemma div_lt_iff (hc : 0 < c) : b / c < a ↔ b < a * c :=
lt_iff_lt_of_le_iff_le (le_div_iff hc)
lemma div_lt_iff' (hc : 0 < c) : b / c < a ↔ b < c * a :=
by rw [mul_comm, div_lt_iff hc]
lemma div_lt_iff_of_neg (hc : c < 0) : b / c < a ↔ a * c < b :=
⟨mul_lt_of_gt_div_of_neg hc, div_lt_of_mul_gt_of_neg hc⟩
lemma inv_le_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a :=
by rw [inv_eq_one_div, div_le_iff ha,
← div_eq_inv_mul, one_le_div_iff_le hb]
lemma inv_le (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a :=
by rw [← inv_le_inv hb (inv_pos.2 ha), inv_inv']
lemma le_inv (ha : 0 < a) (hb : 0 < b) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ :=
by rw [← inv_le_inv (inv_pos.2 hb) ha, inv_inv']
lemma one_div_le_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ 1 / b ↔ b ≤ a :=
by simpa [one_div_eq_inv] using inv_le_inv ha hb
lemma inv_lt_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b⁻¹ ↔ b < a :=
lt_iff_lt_of_le_iff_le (inv_le_inv hb ha)
lemma inv_lt (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b ↔ b⁻¹ < a :=
lt_iff_lt_of_le_iff_le (le_inv hb ha)
lemma one_div_lt (ha : 0 < a) (hb : 0 < b) : 1 / a < b ↔ 1 / b < a :=
(one_div_eq_inv a).symm ▸ (one_div_eq_inv b).symm ▸ inv_lt ha hb
lemma lt_inv (ha : 0 < a) (hb : 0 < b) : a < b⁻¹ ↔ b < a⁻¹ :=
lt_iff_lt_of_le_iff_le (inv_le hb ha)
lemma one_div_lt_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a < 1 / b ↔ b < a :=
lt_iff_lt_of_le_iff_le (one_div_le_one_div hb ha)
lemma div_nonneg : 0 ≤ a → 0 < b → 0 ≤ a / b := div_nonneg_of_nonneg_of_pos
lemma div_lt_div_right (hc : 0 < c) : a / c < b / c ↔ a < b :=
⟨lt_imp_lt_of_le_imp_le (λ h, div_le_div_of_le_of_pos h hc),
λ h, div_lt_div_of_lt_of_pos h hc⟩
lemma div_le_div_right (hc : 0 < c) : a / c ≤ b / c ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right hc)
lemma div_lt_div_right_of_neg (hc : c < 0) : a / c < b / c ↔ b < a :=
⟨lt_imp_lt_of_le_imp_le (λ h, div_le_div_of_le_of_neg h hc),
λ h, div_lt_div_of_lt_of_neg h hc⟩
lemma div_le_div_right_of_neg (hc : c < 0) : a / c ≤ b / c ↔ b ≤ a :=
le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right_of_neg hc)
lemma div_lt_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b < a / c ↔ c < b :=
(mul_lt_mul_left ha).trans (inv_lt_inv hb hc)
lemma div_le_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b ≤ a / c ↔ c ≤ b :=
le_iff_le_iff_lt_iff_lt.2 (div_lt_div_left ha hc hb)
lemma div_lt_div_iff (b0 : 0 < b) (d0 : 0 < d) :
a / b < c / d ↔ a * d < c * b :=
by rw [lt_div_iff d0, div_mul_eq_mul_div, div_lt_iff b0]
lemma div_le_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b ≤ c / d ↔ a * d ≤ c * b :=
by rw [le_div_iff d0, div_mul_eq_mul_div, div_le_iff b0]
lemma div_le_div (hc : 0 ≤ c) (hac : a ≤ c) (hd : 0 < d) (hbd : d ≤ b) : a / b ≤ c / d :=
begin
rw div_le_div_iff (lt_of_lt_of_le hd hbd) hd,
exact mul_le_mul hac hbd (le_of_lt hd) hc
end
lemma div_lt_div (hac : a < c) (hbd : d ≤ b) (c0 : 0 ≤ c) (d0 : 0 < d) :
a / b < c / d :=
(div_lt_div_iff (lt_of_lt_of_le d0 hbd) d0).2 (mul_lt_mul hac hbd d0 c0)
lemma div_lt_div' (hac : a ≤ c) (hbd : d < b) (c0 : 0 < c) (d0 : 0 < d) :
a / b < c / d :=
(div_lt_div_iff (lt_trans d0 hbd) d0).2 (mul_lt_mul' hac hbd (le_of_lt d0) c0)
lemma monotone.div_const {β : Type*} [preorder β] {f : β → α} (hf : monotone f)
{c : α} (hc : 0 ≤ c) :
monotone (λ x, (f x) / c) :=
hf.mul_const (inv_nonneg.2 hc)
lemma strict_mono.div_const {β : Type*} [preorder β] {f : β → α} (hf : strict_mono f)
{c : α} (hc : 0 < c) :
strict_mono (λ x, (f x) / c) :=
hf.mul_const (inv_pos.2 hc)
lemma half_pos {a : α} (h : 0 < a) : 0 < a / 2 := div_pos h two_pos
lemma one_half_pos : (0:α) < 1 / 2 := half_pos zero_lt_one
lemma half_lt_self : 0 < a → a / 2 < a := div_two_lt_of_pos
lemma one_half_lt_one : (1 / 2 : α) < 1 := half_lt_self zero_lt_one
instance linear_ordered_field.to_densely_ordered : densely_ordered α :=
{ dense := assume a₁ a₂ h, ⟨(a₁ + a₂) / 2,
calc a₁ = (a₁ + a₁) / 2 : (add_self_div_two a₁).symm
... < (a₁ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_left h _) two_pos,
calc (a₁ + a₂) / 2 < (a₂ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_right h _) two_pos
... = a₂ : add_self_div_two a₂⟩ }
instance linear_ordered_field.to_no_top_order : no_top_order α :=
{ no_top := assume a, ⟨a + 1, lt_add_of_le_of_pos (le_refl a) zero_lt_one ⟩ }
instance linear_ordered_field.to_no_bot_order : no_bot_order α :=
{ no_bot := assume a, ⟨a + -1,
add_lt_of_le_of_neg (le_refl _) (neg_lt_of_neg_lt $ by simp [zero_lt_one]) ⟩ }
lemma inv_lt_one (ha : 1 < a) : a⁻¹ < 1 :=
by rw [inv_eq_one_div]; exact div_lt_of_mul_lt_of_pos (lt_trans zero_lt_one ha) (by simp *)
lemma one_lt_inv (h₁ : 0 < a) (h₂ : a < 1) : 1 < a⁻¹ :=
by rw [inv_eq_one_div, lt_div_iff h₁]; simp [h₂]
lemma inv_le_one (ha : 1 ≤ a) : a⁻¹ ≤ 1 :=
by rw [inv_eq_one_div]; exact div_le_of_le_mul (lt_of_lt_of_le zero_lt_one ha) (by simp *)
lemma one_le_inv (ha0 : 0 < a) (ha : a ≤ 1) : 1 ≤ a⁻¹ :=
le_of_mul_le_mul_left (by simpa [mul_inv_cancel (ne.symm (ne_of_lt ha0))]) ha0
lemma mul_self_inj_of_nonneg (a0 : 0 ≤ a) (b0 : 0 ≤ b) : a * a = b * b ↔ a = b :=
(mul_self_eq_mul_self_iff a b).trans $ or_iff_left_of_imp $
λ h, by subst a; rw [le_antisymm (neg_nonneg.1 a0) b0, neg_zero]
lemma div_le_div_of_le_left (ha : 0 ≤ a) (hc : 0 < c) (h : c ≤ b) :
a / b ≤ a / c :=
by haveI := classical.dec_eq α; exact
if ha0 : a = 0 then by simp [ha0]
else (div_le_div_left (lt_of_le_of_ne ha (ne.symm ha0)) (lt_of_lt_of_le hc h) hc).2 h
lemma inv_le_inv_of_le (hb : 0 < b) (h : b ≤ a) : a⁻¹ ≤ b⁻¹ :=
begin
rw [inv_eq_one_div, inv_eq_one_div],
exact one_div_le_one_div_of_le hb h
end
lemma div_nonneg' (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a / b :=
(lt_or_eq_of_le hb).elim (div_nonneg ha) (λ h, by simp [h.symm])
lemma div_le_div_of_le_of_nonneg (hab : a ≤ b) (hc : 0 ≤ c) :
a / c ≤ b / c :=
mul_le_mul_of_nonneg_right hab (inv_nonneg.2 hc)
end linear_ordered_field
@[protect_proj] class discrete_linear_ordered_field (α : Type*)
extends linear_ordered_field α, decidable_linear_ordered_comm_ring α
section discrete_linear_ordered_field
variables [discrete_linear_ordered_field α]
lemma abs_div (a b : α) : abs (a / b) = abs a / abs b :=
decidable.by_cases
(assume h : b = 0, by rw [h, abs_zero, div_zero, div_zero, abs_zero])
(assume h : b ≠ 0,
have h₁ : abs b ≠ 0, from
assume h₂, h (eq_zero_of_abs_eq_zero h₂),
eq_div_of_mul_eq _ _ h₁
(show abs (a / b) * abs b = abs a, by rw [← abs_mul, div_mul_cancel _ h]))
lemma abs_one_div (a : α) : abs (1 / a) = 1 / abs a :=
by rw [abs_div, abs_of_nonneg (zero_le_one : 1 ≥ (0 : α))]
lemma abs_inv (a : α) : abs a⁻¹ = (abs a)⁻¹ :=
have h : abs (1 / a) = 1 / abs a,
begin rw [abs_div, abs_of_nonneg], exact zero_le_one end,
by simp [*] at *
end discrete_linear_ordered_field
|
6ebc703bfd49b1cbfeeb25b555e9c03dd64dc08b | 48eee836fdb5c613d9a20741c17db44c8e12e61c | /src/util/signature_inst.lean | ba9f6f7a5d7134147ec5a96dc8bb5627c9ea9959 | [
"Apache-2.0"
] | permissive | fgdorais/lean-universal | 06430443a4abe51e303e602684c2977d1f5c0834 | 9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1 | refs/heads/master | 1,592,479,744,136 | 1,589,473,399,000 | 1,589,473,399,000 | 196,287,552 | 1 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 1,964 | lean | import .default
import .meta.default
definition list.pure {α : Type*} (x : α) : list α := [x]
namespace tactic
meta def mk_list_expr (ty : expr) : list expr → tactic expr
| [] := mk_app `list.nil [ty]
| (e :: es) := mk_list_expr es >>= λ es, mk_app `list.cons [ty, e, es]
meta def get_structure_fields (nm : name) : tactic (list name) :=
do {
nm ← resolve_constant nm,
env ← get_env,
env.structure_fields nm
}
meta def add_structure_field_hints (d : declaration) : tactic unit :=
do {
(ctx, typ) ← mk_local_pis d.type,
val ← pure $ d.value.mk_app_beta ctx,
let tnm := typ.get_app_fn.const_name,
fns ← get_structure_fields tnm,
dobj ← mk_app d.to_name ctx,
gobj ← mk_local' `t binder_info.default typ,
let ctx := ctx ++ [gobj],
hcns ← mk_mapp `unification_constraint.mk [none, some gobj, some dobj],
hcns ← infer_type hcns >>= λ t, mk_list_expr t [hcns],
(fns.reverse.zip val.get_app_args.reverse).mfoldl (λ k ⟨fn, fv⟩,
do {
fe ← mk_mapp (tnm ++ fn) $ (typ.get_app_args ++ [gobj]).map option.some,
hpat ← mk_mapp `unification_constraint.mk [none, some fe, some fv],
hintv ← mk_mapp `unification_hint.mk [some hpat, some hcns],
hintt ← infer_type hintv,
let hintn : name := d.to_name ++ mk_sub_name `_hint (k+1),
let hintt : expr := hintt.pis ctx,
let hintv : expr := hintv.lambdas ctx,
let hdecl := declaration.defn hintn hintt.collect_univ_params hintt hintv reducibility_hints.abbrev tt,
add_decl hdecl,
set_basic_attribute `unify hintn tt,
pure (k+1)
} <|> (pure k)) (0),
skip
}
end tactic
section signature_inst_attr
open tactic
@[user_attribute]
meta def algebra.signature_inst_attr : user_attribute :=
{ name := `signature_instance
, descr := "declare an algebraic signature instance"
, after_set := some $ λ nm _ _, do {
decl ← resolve_constant nm >>= get_decl,
add_structure_field_hints decl
}
}
end signature_inst_attr
|
f82c3f36f2b627e20d9494465edc0fd7ed1461eb | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/simp5.lean | ab7edaa8c44067ccd4ad697fc9f5ad4378ec4ea2 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 271 | lean | def f {α} (a b : α) := a
theorem f_Eq {α} (a b : α) : f a b = a :=
rfl
theorem ex1 (a b c : α) : f (f a b) c = a := by
simp [f_Eq]
#print ex1
theorem ex2 (p : Nat → Bool) (x : Nat) (h : p x = true) : (if p x then 1 else 2) = 1 := by
simp [h]
#print ex2
|
555a4bd483470c3dcb0957fe804245ab18d5e963 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/compiler/arrayMk.lean | 5ca9b254042217524b75eac9d7d89341d0dda1d1 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 98 | lean | def step : Array Nat := Array.mk (List.range 10)
def main : IO Unit := IO.print s!"{step.size}\n"
|
a7fc5599b0e8cf62bd0597e1c01ed04a1db3b768 | ba306bac106b8f27befb2a800f4357237f86c760 | /lean/love04_functional_programming_demo.lean | e09dbd32b707c31afc477f63823891d70aeedf34 | [] | no_license | qyqnl/logical_verification_2020 | 406aa4cc47797501275ea07de5d6f59f01e977d0 | 17dff35b56336acb671ddfb36871f98475bc0b96 | refs/heads/master | 1,672,501,336,112 | 1,603,724,260,000 | 1,603,724,260,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,806 | lean | import .lovelib
/- # LoVe Demo 4: Functional Programming
We take a closer look at the basics of typed functional programming: inductive
types, proofs by induction, recursive functions, pattern matching, structures
(records), and type classes. -/
set_option pp.beta true
set_option pp.generalized_field_notation false
namespace LoVe
/- ## Inductive Types
Recall the definition of type `nat` (= `ℕ`): -/
#print nat
/- Mottos:
* **No junk**: The type contains no values beyond those expressible using the
constructors.
* **No confusion**: Values built in a different ways are different.
For `nat` (= `ℕ`):
* "No junk" means that there are no special values, say, `–1` or `ε`, that
cannot be expressed using a finite combination of `zero` and `succ`.
* "No confusion" is what ensures that `zero` ≠ `succ x`.
In addition, inductive types are always finite. `succ (succ (succ …))` is not a
value.
## Structural Induction
__Structural induction__ is a generalization of mathematical induction to
inductive types. To prove a property `P[n]` for all natural numbers `n`, it
suffices to prove the base case
`P[0]`
and the induction step
`∀k, P[k] → P[k + 1]`
For lists, the base case is
`P[[]]`
and the induction step is
`∀y ys, P[ys] → P[y :: ys]`
In general, there is one subgoal per constructor, and induction hypotheses are
available for all constructor arguments of the type we are doing the induction
on. -/
lemma nat.succ_neq_self (n : ℕ) :
nat.succ n ≠ n :=
begin
induction' n,
{ simp },
{ simp [ih] }
end
/- The `case` tactic can be used to supply custom names, and potentially
reorder the cases. -/
lemma nat.succ_neq_self₂ (n : ℕ) :
nat.succ n ≠ n :=
begin
induction' n,
case nat.succ : m IH {
simp [IH] },
case nat.zero {
simp }
end
/- ## Structural Recursion
__Structural recursion__ is a form of recursion that allows us to peel off
one or more constructors from the value on which we recurse. Such functions are
guaranteed to call themselves only finitely many times before the recursion
stops. This is a prerequisite for establishing that the function terminates. -/
def fact : ℕ → ℕ
| 0 := 1
| (n + 1) := (n + 1) * fact n
def fact₂ : ℕ → ℕ
| 0 := 1
| 1 := 1
| (n + 1) := (n + 1) * fact₂ n
/- For structurally recursive functions, Lean can automatically prove
termination. For more general recursive schemes, the termination check may fail.
Sometimes it does so for a good reason, as in the following example: -/
-- fails
def illegal : ℕ → ℕ
| n := illegal n + 1
constant immoral : ℕ → ℕ
axiom immoral_eq (n : ℕ) :
immoral n = immoral n + 1
lemma proof_of_false :
false :=
have immoral 0 = immoral 0 + 1 :=
immoral_eq 0,
have immoral 0 - immoral 0 = immoral 0 + 1 - immoral 0 :=
by cc,
have 0 = 1 :=
by simp [*] at *,
show false, from
by cc
/- ## Pattern Matching Expressions
`match` _term₁_, …, _termM_ `with`
| _pattern₁₁_, …, _pattern₁M_ := _result₁_
⋮
| _patternN₁_, …, _patternNM_ := _resultN_
`end`
`match` allows nonrecursive pattern matching within terms.
In contrast to pattern matching after `lemma` or `def`, the patterns are
separated by commas, so parentheses are optional. -/
def bcount {α : Type} (p : α → bool) : list α → ℕ
| [] := 0
| (x :: xs) :=
match p x with
| tt := bcount xs + 1
| ff := bcount xs
end
def min (a b : ℕ) : ℕ :=
if a ≤ b then a else b
/- ## Structures
Lean provides a convenient syntax for defining records, or structures. These are
essentially nonrecursive, single-constructor inductive types. -/
structure rgb :=
(red green blue : ℕ)
#check rgb.mk
#check rgb.red
#check rgb.green
#check rgb.blue
namespace rgb_as_inductive
inductive rgb : Type
| mk : ℕ → ℕ → ℕ → rgb
def rgb.red : rgb → ℕ
| (rgb.mk r _ _) := r
def rgb.green : rgb → ℕ
| (rgb.mk _ g _) := g
def rgb.blue : rgb → ℕ
| (rgb.mk _ _ b) := b
end rgb_as_inductive
structure rgba extends rgb :=
(alpha : ℕ)
#print rgba
def pure_red : rgb :=
{ red := 0xff,
green := 0x00,
blue := 0x00 }
def semitransparent_red : rgba :=
{ alpha := 0x7f,
..pure_red }
#print pure_red
#print semitransparent_red
def shuffle (c : rgb) : rgb :=
{ red := rgb.green c,
green := rgb.blue c,
blue := rgb.red c }
/- `cases'` performs a case distinction on the specified term. This gives rise
to as many subgoals as there are constructors in the definition of the term's
type. The tactic behaves the same as `induction` except that it does not produce
induction hypotheses. -/
lemma shuffle_shuffle_shuffle (c : rgb) :
shuffle (shuffle (shuffle c)) = c :=
begin
cases' c,
refl
end
lemma shuffle_shuffle_shuffle₂ (c : rgb) :
shuffle (shuffle (shuffle c)) = c :=
match c with
| rgb.mk r g b := eq.refl _
end
/- ## Type Classes
A __type class__ is a structure type combining abstract constants and their
properties. A type can be declared an instance of a type class by providing
concrete definitions for the constants and proving that the properties hold.
Based on the type, Lean retrieves the relevant instance. -/
#print inhabited
@[instance] def nat.inhabited : inhabited ℕ :=
{ default := 0 }
@[instance] def list.inhabited {α : Type} :
inhabited (list α) :=
{ default := [] }
#eval inhabited.default ℕ -- result: 0
#eval inhabited.default (list ℤ) -- result: []
def head {α : Type} [inhabited α] : list α → α
| [] := inhabited.default α
| (x :: _) := x
lemma head_head {α : Type} [inhabited α] (xs : list α) :
head [head xs] = head xs :=
begin
cases' xs,
{ refl },
{ refl }
end
#eval head ([] : list ℕ) -- result: 0
#check list.head
@[instance] def fun.inhabited {α β : Type} [inhabited β] :
inhabited (α → β) :=
{ default := λa : α, inhabited.default β }
inductive empty : Type
@[instance] def fun_empty.inhabited {β : Type} :
inhabited (empty → β) :=
{ default := λa : empty, match a with end }
@[instance] def prod.inhabited {α β : Type}
[inhabited α] [inhabited β] :
inhabited (α × β) :=
{ default := (inhabited.default α, inhabited.default β) }
/- Here are other type classes without properties: -/
#check has_zero
#check has_neg
#check has_add
#check has_one
#check has_inv
#check has_mul
#check (1 : ℕ)
#check (1 : ℤ)
#check (1 : ℝ)
#check (1 : linear_map _ _ _)
/- We encountered these type classes in lecture 2: -/
#print is_commutative
#print is_associative
/- ## Lists
`list` is an inductive polymorphic type constructed from `nil` and `cons`: -/
#print list
/- `cases'` can also be used on a hypothesis of the form `l = r`. It matches `r`
against `l` and replaces all occurrences of the variables occurring in `r` with
the corresponding terms in `l` everywhere in the goal. -/
lemma injection_example {α : Type} (x y : α) (xs ys : list α)
(h : list.cons x xs = list.cons y ys) :
x = y ∧ xs = ys :=
begin
cases' h,
cc
end
/- If `r` fails to match `l`, no subgoals emerge; the proof is complete. -/
lemma distinctness_example {α : Type} (y : α) (ys : list α)
(h : [] = y :: ys) :
false :=
by cases' h
def map {α β : Type} (f : α → β) : list α → list β
| [] := []
| (x :: xs) := f x :: map xs
def map₂ {α β : Type} : (α → β) → list α → list β
| _ [] := []
| f (x :: xs) := f x :: map₂ f xs
#check list.map
lemma map_ident {α : Type} (xs : list α) :
map (λx, x) xs = xs :=
begin
induction' xs,
case list.nil {
refl },
case list.cons : y ys {
simp [map, ih] }
end
lemma map_comp {α β γ : Type} (f : α → β) (g : β → γ)
(xs : list α) :
map g (map f xs) = map (λx, g (f x)) xs :=
begin
induction' xs,
case list.nil {
refl },
case list.cons : y ys {
simp [map, ih] }
end
lemma map_append {α β : Type} (f : α → β) (xs ys : list α) :
map f (xs ++ ys) = map f xs ++ map f ys :=
begin
induction' xs,
case list.nil {
refl },
case list.cons : y ys {
simp [map, ih] }
end
def tail {α : Type} : list α → list α
| [] := []
| (_ :: xs) := xs
#check list.tail
def head_opt {α : Type} : list α → option α
| [] := option.none
| (x :: _) := option.some x
def head_le {α : Type} : ∀xs : list α, xs ≠ [] → α
| [] hxs := by cc
| (x :: _) _ := x
#eval head_opt [3, 1, 4]
#eval head_le [3, 1, 4] (by simp)
-- fails
#eval head_le ([] : list ℕ) sorry
def zip {α β : Type} : list α → list β → list (α × β)
| (x :: xs) (y :: ys) := (x, y) :: zip xs ys
| [] _ := []
| (_ :: _) [] := []
#check list.zip
def length {α : Type} : list α → ℕ
| [] := 0
| (x :: xs) := length xs + 1
#check list.length
/- `cases'` can also be used to perform a case distinction on a proposition, in
conjunction with `classical.em`. Two cases emerge: one in which the proposition
is true and one in which it is false.
Also notice the `have` tactic below. We will come back to it. -/
#check classical.em
lemma min_add_add (l m n : ℕ) :
min (m + l) (n + l) = min m n + l :=
begin
cases' classical.em (m ≤ n),
case or.inl {
simp [min, h] },
case or.inr {
simp [min, h] }
end
lemma min_add_add₂ (l m n : ℕ) :
min (m + l) (n + l) = min m n + l :=
match classical.em (m ≤ n) with
| or.inl h := by simp [min, h]
| or.inr h := by simp [min, h]
end
lemma min_add_add₃ (l m n : ℕ) :
min (m + l) (n + l) = min m n + l :=
if h : m ≤ n then
by simp [min, h]
else
by simp [min, h]
lemma length_zip {α β : Type} (xs : list α) (ys : list β) :
length (zip xs ys) = min (length xs) (length ys) :=
begin
induction' xs,
case list.nil {
refl },
case list.cons : x xs' {
cases' ys,
case list.nil {
refl },
case list.cons : y ys' {
simp [zip, length, ih ys', min_add_add] } }
end
lemma map_zip {α α' β β' : Type} (f : α → α') (g : β → β') :
∀xs ys,
map (λab : α × β, (f (prod.fst ab), g (prod.snd ab)))
(zip xs ys) =
zip (map f xs) (map g ys)
| (x :: xs) (y :: ys) := by simp [zip, map, map_zip xs ys]
| [] _ := by refl
| (_ :: _) [] := by refl
/- ## Binary Trees
Inductive types with constructors taking several recursive arguments define
tree-like objects. __Binary trees__ have nodes with at most two children. -/
inductive btree (α : Type) : Type
| empty {} : btree
| node : α → btree → btree → btree
/- The type `aexp` of arithmetic expressions was also an example of a tree data
structure.
The nodes of a tree, whether inner nodes or leaf nodes, often carry labels or
other annotations.
Inductive trees contain no infinite branches, not even cycles. This is less
expressive than pointer- or reference-based data structures (in imperative
languages) but easier to reason about.
Recursive definitions (and proofs by induction) work roughly as for lists, but
we may need to recurse (or invoke the induction hypothesis) on several child
nodes. -/
def mirror {α : Type} : btree α → btree α
| btree.empty := btree.empty
| (btree.node a l r) := btree.node a (mirror r) (mirror l)
lemma mirror_mirror {α : Type} (t : btree α) :
mirror (mirror t) = t :=
begin
induction' t,
case btree.empty {
refl },
case btree.node : a l r ih_l ih_r {
simp [mirror, ih_l, ih_r] }
end
lemma mirror_mirror₂ {α : Type} :
∀t : btree α, mirror (mirror t) = t
| btree.empty := by refl
| (btree.node a l r) :=
calc mirror (mirror (btree.node a l r))
= mirror (btree.node a (mirror r) (mirror l)) :
by refl
... = btree.node a (mirror (mirror l)) (mirror (mirror r)) :
by refl
... = btree.node a l (mirror (mirror r)) :
by rw mirror_mirror₂ l
... = btree.node a l r :
by rw mirror_mirror₂ r
lemma mirror_eq_empty_iff {α : Type} :
∀t : btree α, mirror t = btree.empty ↔ t = btree.empty
| btree.empty := by refl
| (btree.node _ _ _) := by simp [mirror]
/- ## Dependent Inductive Types (**optional**) -/
#check vector
inductive vec (α : Type) : ℕ → Type
| nil {} : vec 0
| cons (a : α) {n : ℕ} (v : vec n) : vec (n + 1)
#check vec.nil
#check vec.cons
def list_of_vec {α : Type} : ∀{n : ℕ}, vec α n → list α
| _ vec.nil := []
| _ (vec.cons a v) := a :: list_of_vec v
def vec_of_list {α : Type} :
∀xs : list α, vec α (list.length xs)
| [] := vec.nil
| (x :: xs) := vec.cons x (vec_of_list xs)
lemma length_list_of_vec {α : Type} :
∀{n : ℕ} (v : vec α n), list.length (list_of_vec v) = n
| _ vec.nil := by refl
| _ (vec.cons a v) :=
by simp [list_of_vec, length_list_of_vec v]
end LoVe
|
efefce7b889a2ace4ca89bbd80550dea3015b423 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/category_theory/sites/grothendieck.lean | 18220c9ef720e8bc2164f4765e7611574bc168d9 | [
"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 | 12,740 | lean | /-
Copyright (c) 2020 Bhavik Mehta, E. W. Ayers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, E. W. Ayers
-/
import category_theory.sites.sieves
import category_theory.limits.shapes.pullbacks
import order.copy
/-!
# Grothendieck topologies
Definition and lemmas about Grothendieck topologies.
A Grothendieck topology for a category `C` is a set of sieves on each object `X` satisfying
certain closure conditions.
Alternate versions of the axioms (in arrow form) are also described.
Two explicit examples of Grothendieck topologies are given:
* The dense topology
* The atomic topology
as well as the complete lattice structure on Grothendieck topologies (which gives two additional
explicit topologies: the discrete and trivial topologies.)
A pretopology, or a basis for a topology is defined in `pretopology.lean`. The topology associated
to a topological space is defined in `spaces.lean`.
## Tags
Grothendieck topology, coverage, pretopology, site
## References
* [https://ncatlab.org/nlab/show/Grothendieck+topology][nlab]
* [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM91]
## Implementation notes
We use the definition of [nlab] and [MM91](Chapter III, Section 2), where Grothendieck topologies
are saturated collections of morphisms, rather than the notions of the Stacks project (00VG) and
the Elephant, in which topologies are allowed to be unsaturated, and are then completed.
TODO (BM): Add the definition from Stacks, as a pretopology, and complete to a topology.
This is so that we can produce a bijective correspondence between Grothendieck topologies on a
small category and Lawvere-Tierney topologies on its presheaf topos, as well as the equivalence
between Grothendieck topoi and left exact reflective subcategories of presheaf toposes.
-/
universes v u
namespace category_theory
open category_theory category
variables (C : Type u) [category.{v} C]
/--
The definition of a Grothendieck topology: a set of sieves `J X` on each object `X` satisfying
three axioms:
1. For every object `X`, the maximal sieve is in `J X`.
2. If `S ∈ J X` then its pullback along any `h : Y ⟶ X` is in `J Y`.
3. If `S ∈ J X` and `R` is a sieve on `X`, then provided that the pullback of `R` along any arrow
`f : Y ⟶ X` in `S` is in `J Y`, we have that `R` itself is in `J X`.
A sieve `S` on `X` is referred to as `J`-covering, (or just covering), if `S ∈ J X`.
See https://stacks.math.columbia.edu/tag/00Z4, or [nlab], or [MM92] Chapter III, Section 2,
Definition 1.
-/
structure grothendieck_topology :=
(sieves : Π (X : C), set (sieve X))
(top_mem' : ∀ X, ⊤ ∈ sieves X)
(pullback_stable' : ∀ ⦃X Y : C⦄ ⦃S : sieve X⦄ (f : Y ⟶ X), S ∈ sieves X → S.pullback f ∈ sieves Y)
(transitive' : ∀ ⦃X⦄ ⦃S : sieve X⦄ (hS : S ∈ sieves X) (R : sieve X),
(∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → R.pullback f ∈ sieves Y) → R ∈ sieves X)
namespace grothendieck_topology
instance : has_coe_to_fun (grothendieck_topology C) :=
⟨_, λ J, J.sieves⟩
variables {C} {X Y : C} {S R : sieve X}
variables (J : grothendieck_topology C)
/--
An extensionality lemma in terms of the coercion to a pi-type.
We prove this explicitly rather than deriving it so that it is in terms of the coercion rather than
the projection `.sieves`.
-/
@[ext]
lemma ext {J₁ J₂ : grothendieck_topology C} (h : (J₁ : Π (X : C), set (sieve X)) = J₂) : J₁ = J₂ :=
by { cases J₁, cases J₂, congr, apply h }
@[simp] lemma mem_sieves_iff_coe : S ∈ J.sieves X ↔ S ∈ J X := iff.rfl
-- Also known as the maximality axiom.
@[simp] lemma top_mem (X : C) : ⊤ ∈ J X := J.top_mem' X
-- Also known as the stability axiom.
@[simp] lemma pullback_stable (f : Y ⟶ X) (hS : S ∈ J X) : S.pullback f ∈ J Y :=
J.pullback_stable' f hS
lemma transitive (hS : S ∈ J X) (R : sieve X)
(h : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → R.pullback f ∈ J Y) :
R ∈ J X :=
J.transitive' hS R h
lemma covering_of_eq_top : S = ⊤ → S ∈ J X := λ h, h.symm ▸ J.top_mem X
/--
If `S` is a subset of `R`, and `S` is covering, then `R` is covering as well.
See https://stacks.math.columbia.edu/tag/00Z5 (2), or discussion after [MM92] Chapter III,
Section 2, Definition 1.
-/
lemma superset_covering (Hss : S ≤ R) (sjx : S ∈ J X) : R ∈ J X :=
begin
apply J.transitive sjx R (λ Y f hf, _),
apply covering_of_eq_top,
rw [← top_le_iff, ← S.pullback_eq_top_of_mem hf],
apply sieve.pullback_monotone _ Hss,
end
/--
The intersection of two covering sieves is covering.
See https://stacks.math.columbia.edu/tag/00Z5 (1), or [MM92] Chapter III,
Section 2, Definition 1 (iv).
-/
lemma intersection_covering (rj : R ∈ J X) (sj : S ∈ J X) : R ⊓ S ∈ J X :=
begin
apply J.transitive rj _ (λ Y f Hf, _),
rw [sieve.pullback_inter, R.pullback_eq_top_of_mem Hf],
simp [sj],
end
@[simp]
lemma intersection_covering_iff : R ⊓ S ∈ J X ↔ R ∈ J X ∧ S ∈ J X :=
⟨λ h, ⟨J.superset_covering inf_le_left h, J.superset_covering inf_le_right h⟩,
λ t, intersection_covering _ t.1 t.2⟩
lemma bind_covering {S : sieve X} {R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y} (hS : S ∈ J X)
(hR : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (H : S f), R H ∈ J Y) :
sieve.bind S R ∈ J X :=
J.transitive hS _ (λ Y f hf, superset_covering J (sieve.le_pullback_bind S R f hf) (hR hf))
/--
The sieve `S` on `X` `J`-covers an arrow `f` to `X` if `S.pullback f ∈ J Y`.
This definition is an alternate way of presenting a Grothendieck topology.
-/
def covers (S : sieve X) (f : Y ⟶ X) : Prop := S.pullback f ∈ J Y
lemma covers_iff (S : sieve X) (f : Y ⟶ X) : J.covers S f ↔ S.pullback f ∈ J Y :=
iff.rfl
lemma covering_iff_covers_id (S : sieve X) : S ∈ J X ↔ J.covers S (𝟙 X) :=
by simp [covers_iff]
/-- The maximality axiom in 'arrow' form: Any arrow `f` in `S` is covered by `S`. -/
lemma arrow_max (f : Y ⟶ X) (S : sieve X) (hf : S f) : J.covers S f :=
begin
rw [covers, (sieve.pullback_eq_top_iff_mem f).1 hf],
apply J.top_mem,
end
/-- The stability axiom in 'arrow' form: If `S` covers `f` then `S` covers `g ≫ f` for any `g`. -/
lemma arrow_stable (f : Y ⟶ X) (S : sieve X) (h : J.covers S f) {Z : C} (g : Z ⟶ Y) :
J.covers S (g ≫ f) :=
begin
rw covers_iff at h ⊢,
simp [h, sieve.pullback_comp],
end
/--
The transitivity axiom in 'arrow' form: If `S` covers `f` and every arrow in `S` is covered by
`R`, then `R` covers `f`.
-/
lemma arrow_trans (f : Y ⟶ X) (S R : sieve X) (h : J.covers S f) :
(∀ {Z : C} (g : Z ⟶ X), S g → J.covers R g) → J.covers R f :=
begin
intro k,
apply J.transitive h,
intros Z g hg,
rw ← sieve.pullback_comp,
apply k (g ≫ f) hg,
end
lemma arrow_intersect (f : Y ⟶ X) (S R : sieve X) (hS : J.covers S f) (hR : J.covers R f) :
J.covers (S ⊓ R) f :=
by simpa [covers_iff] using and.intro hS hR
variable (C)
/--
The trivial Grothendieck topology, in which only the maximal sieve is covering. This topology is
also known as the indiscrete, coarse, or chaotic topology.
See [MM92] Chapter III, Section 2, example (a), or
https://en.wikipedia.org/wiki/Grothendieck_topology#The_discrete_and_indiscrete_topologies
-/
def trivial : grothendieck_topology C :=
{ sieves := λ X, {⊤},
top_mem' := λ X, rfl,
pullback_stable' := λ X Y S f hf,
begin
rw set.mem_singleton_iff at ⊢ hf,
simp [hf],
end,
transitive' := λ X S hS R hR,
begin
rw [set.mem_singleton_iff, ← sieve.id_mem_iff_eq_top] at hS,
simpa using hR hS,
end }
/--
The discrete Grothendieck topology, in which every sieve is covering.
See https://en.wikipedia.org/wiki/Grothendieck_topology#The_discrete_and_indiscrete_topologies.
-/
def discrete : grothendieck_topology C :=
{ sieves := λ X, set.univ,
top_mem' := by simp,
pullback_stable' := λ X Y f, by simp,
transitive' := by simp }
variable {C}
lemma trivial_covering : S ∈ trivial C X ↔ S = ⊤ := set.mem_singleton_iff
/-- See https://stacks.math.columbia.edu/tag/00Z6 -/
instance : partial_order (grothendieck_topology C) :=
{ le := λ J₁ J₂, (J₁ : Π (X : C), set (sieve X)) ≤ (J₂ : Π (X : C), set (sieve X)),
le_refl := λ J₁, le_refl _,
le_trans := λ J₁ J₂ J₃ h₁₂ h₂₃, le_trans h₁₂ h₂₃,
le_antisymm := λ J₁ J₂ h₁₂ h₂₁, grothendieck_topology.ext (le_antisymm h₁₂ h₂₁) }
/-- See https://stacks.math.columbia.edu/tag/00Z7 -/
instance : has_Inf (grothendieck_topology C) :=
{ Inf := λ T,
{ sieves := Inf (sieves '' T),
top_mem' :=
begin
rintro X S ⟨⟨_, J, hJ, rfl⟩, rfl⟩,
simp,
end,
pullback_stable' :=
begin
rintro X Y S hS f _ ⟨⟨_, J, hJ, rfl⟩, rfl⟩,
apply J.pullback_stable _ (f _ ⟨⟨_, _, hJ, rfl⟩, rfl⟩),
end,
transitive' :=
begin
rintro X S hS R h _ ⟨⟨_, J, hJ, rfl⟩, rfl⟩,
apply J.transitive (hS _ ⟨⟨_, _, hJ, rfl⟩, rfl⟩) _ (λ Y f hf, h hf _ ⟨⟨_, _, hJ, rfl⟩, rfl⟩),
end } }
/-- See https://stacks.math.columbia.edu/tag/00Z7 -/
lemma is_glb_Inf (s : set (grothendieck_topology C)) : is_glb s (Inf s) :=
begin
refine @is_glb.of_image _ _ _ _ sieves _ _ _ _,
{ intros, refl },
{ exact is_glb_Inf _ },
end
/--
Construct a complete lattice from the `Inf`, but make the trivial and discrete topologies
definitionally equal to the bottom and top respectively.
-/
instance : complete_lattice (grothendieck_topology C) :=
complete_lattice.copy
(complete_lattice_of_Inf _ is_glb_Inf)
_ rfl
(discrete C)
(begin
apply le_antisymm,
{ exact @complete_lattice.le_top _ (complete_lattice_of_Inf _ is_glb_Inf) (discrete C) },
{ intros X S hS,
apply set.mem_univ },
end)
(trivial C)
(begin
apply le_antisymm,
{ intros X S hS,
rw trivial_covering at hS,
apply covering_of_eq_top _ hS },
{ refine @complete_lattice.bot_le _ (complete_lattice_of_Inf _ is_glb_Inf) (trivial C) },
end)
_ rfl
_ rfl
_ rfl
Inf rfl
instance : inhabited (grothendieck_topology C) := ⟨⊤⟩
@[simp] lemma trivial_eq_bot : trivial C = ⊥ := rfl
@[simp] lemma discrete_eq_top : discrete C = ⊤ := rfl
@[simp] lemma bot_covering : S ∈ (⊥ : grothendieck_topology C) X ↔ S = ⊤ := trivial_covering
@[simp] lemma top_covering : S ∈ (⊤ : grothendieck_topology C) X := ⟨⟩
lemma bot_covers (S : sieve X) (f : Y ⟶ X) :
(⊥ : grothendieck_topology C).covers S f ↔ S f :=
by rw [covers_iff, bot_covering, ← sieve.pullback_eq_top_iff_mem]
@[simp] lemma top_covers (S : sieve X) (f : Y ⟶ X) : (⊤ : grothendieck_topology C).covers S f :=
by simp [covers_iff]
/--
The dense Grothendieck topology.
See https://ncatlab.org/nlab/show/dense+topology, or [MM92] Chapter III, Section 2, example (e).
-/
def dense : grothendieck_topology C :=
{ sieves := λ X S, ∀ {Y : C} (f : Y ⟶ X), ∃ Z (g : Z ⟶ Y), S (g ≫ f),
top_mem' := λ X Y f, ⟨Y, 𝟙 Y, ⟨⟩⟩,
pullback_stable' :=
begin
intros X Y S h H Z f,
rcases H (f ≫ h) with ⟨W, g, H'⟩,
exact ⟨W, g, by simpa⟩,
end,
transitive' :=
begin
intros X S H₁ R H₂ Y f,
rcases H₁ f with ⟨Z, g, H₃⟩,
rcases H₂ H₃ (𝟙 Z) with ⟨W, h, H₄⟩,
exact ⟨W, (h ≫ g), by simpa using H₄⟩,
end }
lemma dense_covering : S ∈ dense X ↔ ∀ {Y} (f : Y ⟶ X), ∃ Z (g : Z ⟶ Y), S (g ≫ f) :=
iff.rfl
/--
A category satisfies the right Ore condition if any span can be completed to a commutative square.
NB. Any category with pullbacks obviously satisfies the right Ore condition, see
`right_ore_of_pullbacks`.
-/
def right_ore_condition (C : Type u) [category.{v} C] : Prop :=
∀ {X Y Z : C} (yx : Y ⟶ X) (zx : Z ⟶ X), ∃ W (wy : W ⟶ Y) (wz : W ⟶ Z), wy ≫ yx = wz ≫ zx
lemma right_ore_of_pullbacks [limits.has_pullbacks C] : right_ore_condition C :=
λ X Y Z yx zx, ⟨_, _, _, limits.pullback.condition⟩
/--
The atomic Grothendieck topology: a sieve is covering iff it is nonempty.
For the pullback stability condition, we need the right Ore condition to hold.
See https://ncatlab.org/nlab/show/atomic+site, or [MM92] Chapter III, Section 2, example (f).
-/
def atomic (hro : right_ore_condition C) : grothendieck_topology C :=
{ sieves := λ X S, ∃ Y (f : Y ⟶ X), S f,
top_mem' := λ X, ⟨_, 𝟙 _, ⟨⟩⟩,
pullback_stable' :=
begin
rintros X Y S h ⟨Z, f, hf⟩,
rcases hro h f with ⟨W, g, k, comm⟩,
refine ⟨_, g, _⟩,
simp [comm, hf],
end,
transitive' :=
begin
rintros X S ⟨Y, f, hf⟩ R h,
rcases h hf with ⟨Z, g, hg⟩,
exact ⟨_, _, hg⟩,
end }
end grothendieck_topology
end category_theory
|
4e48cd44f4874c4a2d39ffbdea21d868f56ab1a6 | 3c693e12637d1cf47effc09ab5e21700d1278e73 | /src/equivalence_relations/partitions.lean | 607ca4d02e3ed152d2c498385ef6760dd214b4a1 | [] | no_license | ImperialCollegeLondon/Example-Lean-Projects | e731664ae046980921a69ccfeb2286674080c5bb | 87b27ba616eaf03f3642000829a481a1932dd08e | refs/heads/master | 1,685,399,670,721 | 1,623,092,696,000 | 1,623,092,696,000 | 275,571,570 | 19 | 1 | null | 1,593,361,524,000 | 1,593,344,124,000 | Lean | UTF-8 | Lean | false | false | 2,323 | lean | import data.equiv.basic -- bijections with inverses
import tactic -- we want to use tactics
open set
/-- Definition of a partition as a collection of disjoint nonempty
subsets of X whose union is X-/
@[ext] structure partition (X : Type) :=
(C : set (set X))
(Hnonempty : ∀ c ∈ C, c ≠ ∅)
(Hcover : ∀ x, ∃ c ∈ C, x ∈ c)
(Hunique : ∀ c d ∈ C, c ∩ d ≠ ∅ → c = d)
/-- Equivalence class for a binary relation -/
def equivalence_class {X : Type} (R : X → X → Prop) (x : X) := {y : X | R x y}
/-- x is in the equivalence class of x -/
lemma mem_class {X : Type} {R : X → X → Prop} (HR : equivalence R) (x : X) :
x ∈ equivalence_class R x :=
begin
sorry
end
/-- There is a bijection between equivalence relations on X and partitions of X -/
example (X : Type) : {R : X → X → Prop // equivalence R} ≃ partition X :=
-- The map in one direction: given a relation, use the set of equivalence classes.
{ to_fun := λ R, {
C := { S : set X | ∃ x : X, S = equivalence_class R x},
-- I claim that this is a partition.
Hnonempty := begin -- equiv classes are nonempty
sorry,
end,
Hcover := begin -- they cover
sorry,
end,
Hunique := begin -- and distinct equiv classes are disjoint
sorry
end },
-- The map the other way: given a partition, say two elements are related
-- if there's a set in the partition that they both lie in.
inv_fun := λ P, ⟨λ x y, ∃ c ∈ P.C, x ∈ c ∧ y ∈ c, ⟨
-- Claim this is an equivalence relation.
begin -- reflexive
change ∀ (x : X), ∃ (c : set X) (H : c ∈ P.C), x ∈ c ∧ x ∈ c,
sorry,
end,
begin -- symmetric
change ∀ (x y : X), (∃ (c : set X) (H : c ∈ P.C), x ∈ c ∧ y ∈ c) →
(∃ (d : set X) (H : d ∈ P.C), y ∈ d ∧ x ∈ d),
sorry,
end,
begin -- transitive
change ∀ (x y z : X),
(∃ (c : set X) (H : c ∈ P.C), x ∈ c ∧ y ∈ c) →
(∃ (d : set X) (H : d ∈ P.C), y ∈ d ∧ z ∈ d) →
(∃ (e : set X) (H : e ∈ P.C), x ∈ e ∧ z ∈ e),
sorry,
end
⟩⟩,
-- Furthermore, I claim that these two constructions are inverse to each other.
left_inv := begin
sorry,
end,
-- (in both directions)
right_inv := begin
sorry,
end }
|
2a09eb4c9fe97af5b444eb86044bb49bd963b19e | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/group_with_zero/defs.lean | c7ad5b9e5d179334af0bc0684ae892fddfcdec97 | [
"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 | 11,053 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import algebra.group.defs
import logic.nontrivial
import algebra.ne_zero
/-!
# Typeclasses for groups with an adjoined zero element
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> https://github.com/leanprover-community/mathlib4/pull/563
> Any changes to this file require a corresponding PR to mathlib4.
This file provides just the typeclass definitions, and the projection lemmas that expose their
members.
## Main definitions
* `group_with_zero`
* `comm_group_with_zero`
-/
set_option old_structure_cmd true
universe u
-- We have to fix the universe of `G₀` here, since the default argument to
-- `group_with_zero.div'` cannot contain a universe metavariable.
variables {G₀ : Type u} {M₀ M₀' G₀' : Type*}
/-- Typeclass for expressing that a type `M₀` with multiplication and a zero satisfies
`0 * a = 0` and `a * 0 = 0` for all `a : M₀`. -/
@[protect_proj, ancestor has_mul has_zero]
class mul_zero_class (M₀ : Type*) extends has_mul M₀, has_zero M₀ :=
(zero_mul : ∀ a : M₀, 0 * a = 0)
(mul_zero : ∀ a : M₀, a * 0 = 0)
/-- A mixin for left cancellative multiplication by nonzero elements. -/
@[protect_proj] class is_left_cancel_mul_zero (M₀ : Type u) [has_mul M₀] [has_zero M₀] : Prop :=
(mul_left_cancel_of_ne_zero : ∀ {a b c : M₀}, a ≠ 0 → a * b = a * c → b = c)
/-- A mixin for right cancellative multiplication by nonzero elements. -/
@[protect_proj] class is_right_cancel_mul_zero (M₀ : Type u) [has_mul M₀] [has_zero M₀] : Prop :=
(mul_right_cancel_of_ne_zero : ∀ {a b c : M₀}, b ≠ 0 → a * b = c * b → a = c)
/-- A mixin for cancellative multiplication by nonzero elements. -/
@[protect_proj] class is_cancel_mul_zero (M₀ : Type u) [has_mul M₀] [has_zero M₀]
extends is_left_cancel_mul_zero M₀, is_right_cancel_mul_zero M₀ : Prop
section mul_zero_class
variables [mul_zero_class M₀] {a b : M₀}
@[ematch, simp] lemma zero_mul (a : M₀) : 0 * a = 0 :=
mul_zero_class.zero_mul a
@[ematch, simp] lemma mul_zero (a : M₀) : a * 0 = 0 :=
mul_zero_class.mul_zero a
end mul_zero_class
/-- Predicate typeclass for expressing that `a * b = 0` implies `a = 0` or `b = 0`
for all `a` and `b` of type `G₀`. -/
class no_zero_divisors (M₀ : Type*) [has_mul M₀] [has_zero M₀] : Prop :=
(eq_zero_or_eq_zero_of_mul_eq_zero : ∀ {a b : M₀}, a * b = 0 → a = 0 ∨ b = 0)
export no_zero_divisors (eq_zero_or_eq_zero_of_mul_eq_zero)
/-- A type `S₀` is a "semigroup with zero” if it is a semigroup with zero element, and `0` is left
and right absorbing. -/
@[protect_proj, ancestor semigroup mul_zero_class]
class semigroup_with_zero (S₀ : Type*) extends semigroup S₀, mul_zero_class S₀.
/- By defining this _after_ `semigroup_with_zero`, we ensure that searches for `mul_zero_class` find
this class first. -/
/-- A typeclass for non-associative monoids with zero elements. -/
@[protect_proj, ancestor mul_one_class mul_zero_class]
class mul_zero_one_class (M₀ : Type*) extends mul_one_class M₀, mul_zero_class M₀.
/-- A type `M₀` is a “monoid with zero” if it is a monoid with zero element, and `0` is left
and right absorbing. -/
@[protect_proj, ancestor monoid mul_zero_one_class]
class monoid_with_zero (M₀ : Type*) extends monoid M₀, mul_zero_one_class M₀.
@[priority 100] -- see Note [lower instance priority]
instance monoid_with_zero.to_semigroup_with_zero (M₀ : Type*) [monoid_with_zero M₀] :
semigroup_with_zero M₀ :=
{ ..‹monoid_with_zero M₀› }
/-- A type `M` is a `cancel_monoid_with_zero` if it is a monoid with zero element, `0` is left
and right absorbing, and left/right multiplication by a non-zero element is injective. -/
@[protect_proj, ancestor monoid_with_zero]
class cancel_monoid_with_zero (M₀ : Type*) extends monoid_with_zero M₀ :=
(mul_left_cancel_of_ne_zero : ∀ {a b c : M₀}, a ≠ 0 → a * b = a * c → b = c)
(mul_right_cancel_of_ne_zero : ∀ {a b c : M₀}, b ≠ 0 → a * b = c * b → a = c)
section cancel_monoid_with_zero
variables [cancel_monoid_with_zero M₀] {a b c : M₀}
lemma mul_left_cancel₀ (ha : a ≠ 0) (h : a * b = a * c) : b = c :=
cancel_monoid_with_zero.mul_left_cancel_of_ne_zero ha h
lemma mul_right_cancel₀ (hb : b ≠ 0) (h : a * b = c * b) : a = c :=
cancel_monoid_with_zero.mul_right_cancel_of_ne_zero hb h
lemma mul_right_injective₀ (ha : a ≠ 0) : function.injective ((*) a) :=
λ b c, mul_left_cancel₀ ha
lemma mul_left_injective₀ (hb : b ≠ 0) : function.injective (λ a, a * b) :=
λ a c, mul_right_cancel₀ hb
/-- A `cancel_monoid_with_zero` satisfies `is_cancel_mul_zero`. -/
@[priority 100]
instance cancel_monoid_with_zero.to_is_cancel_mul_zero : is_cancel_mul_zero M₀ :=
{ mul_left_cancel_of_ne_zero := λ a b c ha h,
cancel_monoid_with_zero.mul_left_cancel_of_ne_zero ha h,
mul_right_cancel_of_ne_zero := λ a b c hb h,
cancel_monoid_with_zero.mul_right_cancel_of_ne_zero hb h, }
end cancel_monoid_with_zero
/-- A type `M` is a commutative “monoid with zero” if it is a commutative monoid with zero
element, and `0` is left and right absorbing. -/
@[protect_proj, ancestor comm_monoid monoid_with_zero]
class comm_monoid_with_zero (M₀ : Type*) extends comm_monoid M₀, monoid_with_zero M₀.
/-- A type `M` is a `cancel_comm_monoid_with_zero` if it is a commutative monoid with zero element,
`0` is left and right absorbing,
and left/right multiplication by a non-zero element is injective. -/
@[protect_proj, ancestor comm_monoid_with_zero cancel_monoid_with_zero]
class cancel_comm_monoid_with_zero (M₀ : Type*) extends
comm_monoid_with_zero M₀, cancel_monoid_with_zero M₀.
/-- A type `G₀` is a “group with zero” if it is a monoid with zero element (distinct from `1`)
such that every nonzero element is invertible.
The type is required to come with an “inverse” function, and the inverse of `0` must be `0`.
Examples include division rings and the ordered monoids that are the
target of valuations in general valuation theory.-/
@[protect_proj, ancestor monoid_with_zero div_inv_monoid nontrivial]
class group_with_zero (G₀ : Type u) extends
monoid_with_zero G₀, div_inv_monoid G₀, nontrivial G₀ :=
(inv_zero : (0 : G₀)⁻¹ = 0)
(mul_inv_cancel : ∀ a:G₀, a ≠ 0 → a * a⁻¹ = 1)
namespace comm_monoid_with_zero
variable [comm_monoid_with_zero M₀]
lemma is_left_cancel_mul_zero.to_is_right_cancel_mul_zero [is_left_cancel_mul_zero M₀] :
is_right_cancel_mul_zero M₀ :=
{ mul_right_cancel_of_ne_zero := λ a b c ha h,
begin
rw [mul_comm, mul_comm c] at h,
exact is_left_cancel_mul_zero.mul_left_cancel_of_ne_zero ha h,
end }
lemma is_right_cancel_mul_zero.to_is_left_cancel_mul_zero [is_right_cancel_mul_zero M₀] :
is_left_cancel_mul_zero M₀ :=
{ mul_left_cancel_of_ne_zero := λ a b c ha h,
begin
rw [mul_comm a, mul_comm a c] at h,
exact is_right_cancel_mul_zero.mul_right_cancel_of_ne_zero ha h,
end }
lemma is_left_cancel_mul_zero.to_is_cancel_mul_zero [is_left_cancel_mul_zero M₀] :
is_cancel_mul_zero M₀ :=
{ mul_left_cancel_of_ne_zero := λ _ _ _,
is_left_cancel_mul_zero.mul_left_cancel_of_ne_zero,
mul_right_cancel_of_ne_zero := λ _ _ _,
is_left_cancel_mul_zero.to_is_right_cancel_mul_zero.mul_right_cancel_of_ne_zero }
lemma is_right_cancel_mul_zero.to_is_cancel_mul_zero [is_right_cancel_mul_zero M₀] :
is_cancel_mul_zero M₀ :=
{ mul_left_cancel_of_ne_zero := λ _ _ _,
is_right_cancel_mul_zero.to_is_left_cancel_mul_zero.mul_left_cancel_of_ne_zero,
mul_right_cancel_of_ne_zero := λ _ _ _,
is_right_cancel_mul_zero.mul_right_cancel_of_ne_zero }
end comm_monoid_with_zero
section group_with_zero
variables [group_with_zero G₀]
@[simp] lemma inv_zero : (0 : G₀)⁻¹ = 0 :=
group_with_zero.inv_zero
@[simp] lemma mul_inv_cancel {a : G₀} (h : a ≠ 0) : a * a⁻¹ = 1 :=
group_with_zero.mul_inv_cancel a h
end group_with_zero
/-- A type `G₀` is a commutative “group with zero”
if it is a commutative monoid with zero element (distinct from `1`)
such that every nonzero element is invertible.
The type is required to come with an “inverse” function, and the inverse of `0` must be `0`. -/
@[protect_proj, ancestor comm_monoid_with_zero group_with_zero]
class comm_group_with_zero (G₀ : Type*) extends comm_monoid_with_zero G₀, group_with_zero G₀.
section ne_zero
attribute [field_simps] two_ne_zero three_ne_zero four_ne_zero
variables [mul_zero_one_class M₀] [nontrivial M₀] {a b : M₀}
variable (M₀)
/-- In a nontrivial monoid with zero, zero and one are different. -/
instance ne_zero.one : ne_zero (1 : M₀) :=
⟨begin
assume h,
rcases exists_pair_ne M₀ with ⟨x, y, hx⟩,
apply hx,
calc x = 1 * x : by rw [one_mul]
... = 0 : by rw [h, zero_mul]
... = 1 * y : by rw [h, zero_mul]
... = y : by rw [one_mul]
end⟩
variable {M₀}
/-- Pullback a `nontrivial` instance along a function sending `0` to `0` and `1` to `1`. -/
lemma pullback_nonzero [has_zero M₀'] [has_one M₀']
(f : M₀' → M₀) (zero : f 0 = 0) (one : f 1 = 1) : nontrivial M₀' :=
⟨⟨0, 1, mt (congr_arg f) $ by { rw [zero, one], exact zero_ne_one }⟩⟩
end ne_zero
section mul_zero_class
variables [mul_zero_class M₀]
lemma mul_eq_zero_of_left {a : M₀} (h : a = 0) (b : M₀) : a * b = 0 := h.symm ▸ zero_mul b
lemma mul_eq_zero_of_right (a : M₀) {b : M₀} (h : b = 0) : a * b = 0 := h.symm ▸ mul_zero a
variables [no_zero_divisors M₀] {a b : M₀}
/-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them
equals zero. -/
@[simp] theorem mul_eq_zero : a * b = 0 ↔ a = 0 ∨ b = 0 :=
⟨eq_zero_or_eq_zero_of_mul_eq_zero,
λo, o.elim (λ h, mul_eq_zero_of_left h b) (mul_eq_zero_of_right a)⟩
/-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them
equals zero. -/
@[simp] theorem zero_eq_mul : 0 = a * b ↔ a = 0 ∨ b = 0 :=
by rw [eq_comm, mul_eq_zero]
/-- If `α` has no zero divisors, then the product of two elements is nonzero iff both of them
are nonzero. -/
theorem mul_ne_zero_iff : a * b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 :=
mul_eq_zero.not.trans not_or_distrib
/-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` equals zero iff so is
`b * a`. -/
theorem mul_eq_zero_comm : a * b = 0 ↔ b * a = 0 :=
mul_eq_zero.trans $ (or_comm _ _).trans mul_eq_zero.symm
/-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` is nonzero iff so is
`b * a`. -/
theorem mul_ne_zero_comm : a * b ≠ 0 ↔ b * a ≠ 0 :=
mul_eq_zero_comm.not
lemma mul_self_eq_zero : a * a = 0 ↔ a = 0 := by simp
lemma zero_eq_mul_self : 0 = a * a ↔ a = 0 := by simp
lemma mul_self_ne_zero : a * a ≠ 0 ↔ a ≠ 0 := mul_self_eq_zero.not
lemma zero_ne_mul_self : 0 ≠ a * a ↔ a ≠ 0 := zero_eq_mul_self.not
end mul_zero_class
|
1c012f29ca722587d085eb86a45bbc8fbf641fc2 | 3994e03e14a3cbe3858c1098d0ab9ed1113d6666 | /06-formalizacija-dokazov/vaje.lean | 4ecd61dc87f582eaef478a5cdfb9c5859c59cb70 | [] | no_license | tadejpetric/tpj-coq | 15f2548ba8f012d9a5b5e0bfb78ab0860d048e96 | dda9fb2e635f9a1302739e34d8692a4252066b76 | refs/heads/master | 1,629,182,614,649 | 1,600,449,570,000 | 1,600,449,570,000 | 222,798,649 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,015 | lean | namespace hidden
universe u
-------------------------------------------------------------------------------
inductive list (A:Type) : Type
| Nil {} : list -- Brez {} moramo konstruktorju Nil vedno podati tip A
| Cons : A -> list -> list -- Cons tip A ugotovi iz tipa prvega elementa
namespace list
-- Dopolnite definicije in dokažitve trditve za sezname iz vaj 3. Uporabljate -- lahko notacijo x :: xs, [] in ++ (namesto @), vendar bodite pozorni na
-- oklepaje.
notation x `::` xs := Cons x xs
notation `[]` := Nil
def join {A} : list A -> list A -> list A := sorry
notation xs `++` ys := join xs ys
theorem join_nil {A} (xs: list A) :
xs ++ [] = xs
:=
begin
sorry
end
end list
-------------------------------------------------------------------------------
-- Podobno kot za sezname, napišite tip za drevesa in dokažite trditve iz
-- vaj 3. Če po definiciji tipa `tree` odprete `namespace tree` lahko
-- uporabljate konstruktorje brez predpone, torej `Empty` namesto
-- `tree.Empty`.
end hidden |
fdb2991ff5b616be8d0d8c2eab620086e008eaa6 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/normed_space/compact_operator.lean | a2e78130ad594fd03db1ea91a14daafd7f89de69 | [
"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 | 22,021 | lean | /-
Copyright (c) 2022 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker
-/
import analysis.normed_space.operator_norm
import analysis.locally_convex.bounded
/-!
# Compact operators
In this file we define compact linear operators between two topological vector spaces (TVS).
## Main definitions
* `is_compact_operator` : predicate for compact operators
## Main statements
* `is_compact_operator_iff_is_compact_closure_image_closed_ball` : the usual characterization of
compact operators from a normed space to a T2 TVS.
* `is_compact_operator.comp_clm` : precomposing a compact operator by a continuous linear map gives
a compact operator
* `is_compact_operator.clm_comp` : postcomposing a compact operator by a continuous linear map
gives a compact operator
* `is_compact_operator.continuous` : compact operators are automatically continuous
* `is_closed_set_of_is_compact_operator` : the set of compact operators is closed for the operator
norm
## Implementation details
We define `is_compact_operator` as a predicate, because the space of compact operators inherits all
of its structure from the space of continuous linear maps (e.g we want to have the usual operator
norm on compact operators).
The two natural options then would be to make it a predicate over linear maps or continuous linear
maps. Instead we define it as a predicate over bare functions, although it really only makes sense
for linear functions, because Lean is really good at finding coercions to bare functions (whereas
coercing from continuous linear maps to linear maps often needs type ascriptions).
## TODO
Once we have the strong operator topology on spaces of linear maps between two TVSs,
`is_closed_set_of_is_compact_operator` should be generalized to this setup.
## References
* Bourbaki, *Spectral Theory*, chapters 3 to 5, to be published (2022)
## Tags
Compact operator
-/
open function set filter bornology metric
open_locale pointwise big_operators topological_space
/-- A compact operator between two topological vector spaces. This definition is usually
given as "there exists a neighborhood of zero whose image is contained in a compact set",
but we choose a definition which involves fewer existential quantifiers and replaces images
with preimages.
We prove the equivalence in `is_compact_operator_iff_exists_mem_nhds_image_subset_compact`. -/
def is_compact_operator {M₁ M₂ : Type*} [has_zero M₁] [topological_space M₁]
[topological_space M₂] (f : M₁ → M₂) : Prop :=
∃ K, is_compact K ∧ f ⁻¹' K ∈ (𝓝 0 : filter M₁)
lemma is_compact_operator_zero {M₁ M₂ : Type*} [has_zero M₁] [topological_space M₁]
[topological_space M₂] [has_zero M₂] : is_compact_operator (0 : M₁ → M₂) :=
⟨{0}, is_compact_singleton, mem_of_superset univ_mem (λ x _, rfl)⟩
section characterizations
section
variables {R₁ R₂ : Type*} [semiring R₁] [semiring R₂] {σ₁₂ : R₁ →+* R₂} {M₁ M₂ : Type*}
[topological_space M₁] [add_comm_monoid M₁] [topological_space M₂]
lemma is_compact_operator_iff_exists_mem_nhds_image_subset_compact (f : M₁ → M₂) :
is_compact_operator f ↔ ∃ V ∈ (𝓝 0 : filter M₁), ∃ (K : set M₂), is_compact K ∧ f '' V ⊆ K :=
⟨λ ⟨K, hK, hKf⟩, ⟨f ⁻¹' K, hKf, K, hK, image_preimage_subset _ _⟩,
λ ⟨V, hV, K, hK, hVK⟩, ⟨K, hK, mem_of_superset hV (image_subset_iff.mp hVK)⟩⟩
lemma is_compact_operator_iff_exists_mem_nhds_is_compact_closure_image [t2_space M₂]
(f : M₁ → M₂) :
is_compact_operator f ↔ ∃ V ∈ (𝓝 0 : filter M₁), is_compact (closure $ f '' V) :=
begin
rw is_compact_operator_iff_exists_mem_nhds_image_subset_compact,
exact ⟨λ ⟨V, hV, K, hK, hKV⟩, ⟨V, hV, is_compact_closure_of_subset_compact hK hKV⟩,
λ ⟨V, hV, hVc⟩, ⟨V, hV, closure (f '' V), hVc, subset_closure⟩⟩,
end
end
section bounded
variables {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁] [semi_normed_ring 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂}
{M₁ M₂ : Type*} [topological_space M₁] [add_comm_monoid M₁] [topological_space M₂]
[add_comm_monoid M₂] [module 𝕜₁ M₁] [module 𝕜₂ M₂] [has_continuous_const_smul 𝕜₂ M₂]
lemma is_compact_operator.image_subset_compact_of_vonN_bounded {f : M₁ →ₛₗ[σ₁₂] M₂}
(hf : is_compact_operator f) {S : set M₁} (hS : is_vonN_bounded 𝕜₁ S) :
∃ (K : set M₂), is_compact K ∧ f '' S ⊆ K :=
let ⟨K, hK, hKf⟩ := hf,
⟨r, hr, hrS⟩ := hS hKf,
⟨c, hc⟩ := normed_field.exists_lt_norm 𝕜₁ r,
this := ne_zero_of_norm_ne_zero (hr.trans hc).ne.symm in
⟨σ₁₂ c • K, hK.image $ continuous_id.const_smul (σ₁₂ c),
by rw [image_subset_iff, preimage_smul_setₛₗ _ _ _ f this.is_unit]; exact hrS c hc.le⟩
lemma is_compact_operator.is_compact_closure_image_of_vonN_bounded [t2_space M₂]
{f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) {S : set M₁}
(hS : is_vonN_bounded 𝕜₁ S) : is_compact (closure $ f '' S) :=
let ⟨K, hK, hKf⟩ := hf.image_subset_compact_of_vonN_bounded hS in
is_compact_closure_of_subset_compact hK hKf
end bounded
section normed_space
variables {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁] [semi_normed_ring 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂}
{M₁ M₂ M₃ : Type*} [seminormed_add_comm_group M₁] [topological_space M₂]
[add_comm_monoid M₂] [normed_space 𝕜₁ M₁] [module 𝕜₂ M₂]
lemma is_compact_operator.image_subset_compact_of_bounded [has_continuous_const_smul 𝕜₂ M₂]
{f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) {S : set M₁} (hS : metric.bounded S) :
∃ (K : set M₂), is_compact K ∧ f '' S ⊆ K :=
hf.image_subset_compact_of_vonN_bounded
(by rwa [normed_space.is_vonN_bounded_iff, ← metric.bounded_iff_is_bounded])
lemma is_compact_operator.is_compact_closure_image_of_bounded [has_continuous_const_smul 𝕜₂ M₂]
[t2_space M₂] {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) {S : set M₁}
(hS : metric.bounded S) : is_compact (closure $ f '' S) :=
hf.is_compact_closure_image_of_vonN_bounded
(by rwa [normed_space.is_vonN_bounded_iff, ← metric.bounded_iff_is_bounded])
lemma is_compact_operator.image_ball_subset_compact [has_continuous_const_smul 𝕜₂ M₂]
{f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) (r : ℝ) :
∃ (K : set M₂), is_compact K ∧ f '' metric.ball 0 r ⊆ K :=
hf.image_subset_compact_of_vonN_bounded (normed_space.is_vonN_bounded_ball 𝕜₁ M₁ r)
lemma is_compact_operator.image_closed_ball_subset_compact [has_continuous_const_smul 𝕜₂ M₂]
{f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) (r : ℝ) :
∃ (K : set M₂), is_compact K ∧ f '' metric.closed_ball 0 r ⊆ K :=
hf.image_subset_compact_of_vonN_bounded (normed_space.is_vonN_bounded_closed_ball 𝕜₁ M₁ r)
lemma is_compact_operator.is_compact_closure_image_ball [has_continuous_const_smul 𝕜₂ M₂]
[t2_space M₂] {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) (r : ℝ) :
is_compact (closure $ f '' metric.ball 0 r) :=
hf.is_compact_closure_image_of_vonN_bounded (normed_space.is_vonN_bounded_ball 𝕜₁ M₁ r)
lemma is_compact_operator.is_compact_closure_image_closed_ball [has_continuous_const_smul 𝕜₂ M₂]
[t2_space M₂] {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) (r : ℝ) :
is_compact (closure $ f '' metric.closed_ball 0 r) :=
hf.is_compact_closure_image_of_vonN_bounded (normed_space.is_vonN_bounded_closed_ball 𝕜₁ M₁ r)
lemma is_compact_operator_iff_image_ball_subset_compact [has_continuous_const_smul 𝕜₂ M₂]
(f : M₁ →ₛₗ[σ₁₂] M₂) {r : ℝ} (hr : 0 < r) :
is_compact_operator f ↔ ∃ (K : set M₂), is_compact K ∧ f '' metric.ball 0 r ⊆ K :=
⟨λ hf, hf.image_ball_subset_compact r,
λ ⟨K, hK, hKr⟩, (is_compact_operator_iff_exists_mem_nhds_image_subset_compact f).mpr
⟨metric.ball 0 r, ball_mem_nhds _ hr, K, hK, hKr⟩⟩
lemma is_compact_operator_iff_image_closed_ball_subset_compact [has_continuous_const_smul 𝕜₂ M₂]
(f : M₁ →ₛₗ[σ₁₂] M₂) {r : ℝ} (hr : 0 < r) :
is_compact_operator f ↔ ∃ (K : set M₂), is_compact K ∧ f '' metric.closed_ball 0 r ⊆ K :=
⟨λ hf, hf.image_closed_ball_subset_compact r,
λ ⟨K, hK, hKr⟩, (is_compact_operator_iff_exists_mem_nhds_image_subset_compact f).mpr
⟨metric.closed_ball 0 r, closed_ball_mem_nhds _ hr, K, hK, hKr⟩⟩
lemma is_compact_operator_iff_is_compact_closure_image_ball [has_continuous_const_smul 𝕜₂ M₂]
[t2_space M₂] (f : M₁ →ₛₗ[σ₁₂] M₂) {r : ℝ} (hr : 0 < r) :
is_compact_operator f ↔ is_compact (closure $ f '' metric.ball 0 r) :=
⟨λ hf, hf.is_compact_closure_image_ball r,
λ hf, (is_compact_operator_iff_exists_mem_nhds_is_compact_closure_image f).mpr
⟨metric.ball 0 r, ball_mem_nhds _ hr, hf⟩⟩
lemma is_compact_operator_iff_is_compact_closure_image_closed_ball
[has_continuous_const_smul 𝕜₂ M₂] [t2_space M₂] (f : M₁ →ₛₗ[σ₁₂] M₂) {r : ℝ} (hr : 0 < r) :
is_compact_operator f ↔ is_compact (closure $ f '' metric.closed_ball 0 r) :=
⟨λ hf, hf.is_compact_closure_image_closed_ball r,
λ hf, (is_compact_operator_iff_exists_mem_nhds_is_compact_closure_image f).mpr
⟨metric.closed_ball 0 r, closed_ball_mem_nhds _ hr, hf⟩⟩
end normed_space
end characterizations
section operations
variables {R₁ R₂ R₃ R₄ : Type*} [semiring R₁] [semiring R₂] [comm_semiring R₃] [comm_semiring R₄]
{σ₁₂ : R₁ →+* R₂} {σ₁₄ : R₁ →+* R₄} {σ₃₄ : R₃ →+* R₄} {M₁ M₂ M₃ M₄ : Type*}
[topological_space M₁] [add_comm_monoid M₁] [topological_space M₂] [add_comm_monoid M₂]
[topological_space M₃] [add_comm_group M₃] [topological_space M₄] [add_comm_group M₄]
lemma is_compact_operator.smul {S : Type*} [monoid S] [distrib_mul_action S M₂]
[has_continuous_const_smul S M₂] {f : M₁ → M₂}
(hf : is_compact_operator f) (c : S) :
is_compact_operator (c • f) :=
let ⟨K, hK, hKf⟩ := hf in ⟨c • K, hK.image $ continuous_id.const_smul c,
mem_of_superset hKf (λ x hx, smul_mem_smul_set hx)⟩
lemma is_compact_operator.add [has_continuous_add M₂] {f g : M₁ → M₂}
(hf : is_compact_operator f) (hg : is_compact_operator g) :
is_compact_operator (f + g) :=
let ⟨A, hA, hAf⟩ := hf, ⟨B, hB, hBg⟩ := hg in
⟨A + B, hA.add hB, mem_of_superset (inter_mem hAf hBg) (λ x ⟨hxA, hxB⟩, set.add_mem_add hxA hxB)⟩
lemma is_compact_operator.neg [has_continuous_neg M₄] {f : M₁ → M₄}
(hf : is_compact_operator f) : is_compact_operator (-f) :=
let ⟨K, hK, hKf⟩ := hf in
⟨-K, hK.neg, mem_of_superset hKf $ λ x (hx : f x ∈ K), set.neg_mem_neg.mpr hx⟩
lemma is_compact_operator.sub [topological_add_group M₄] {f g : M₁ → M₄}
(hf : is_compact_operator f) (hg : is_compact_operator g) : is_compact_operator (f - g) :=
by rw sub_eq_add_neg; exact hf.add hg.neg
variables (σ₁₄ M₁ M₄)
/-- The submodule of compact continuous linear maps. -/
def compact_operator [module R₁ M₁] [module R₄ M₄] [has_continuous_const_smul R₄ M₄]
[topological_add_group M₄] :
submodule R₄ (M₁ →SL[σ₁₄] M₄) :=
{ carrier := {f | is_compact_operator f},
add_mem' := λ f g hf hg, hf.add hg,
zero_mem' := is_compact_operator_zero,
smul_mem' := λ c f hf, hf.smul c }
end operations
section comp
variables {R₁ R₂ R₃ : Type*} [semiring R₁] [semiring R₂] [semiring R₃] {σ₁₂ : R₁ →+* R₂}
{σ₂₃ : R₂ →+* R₃} {M₁ M₂ M₃ : Type*} [topological_space M₁] [topological_space M₂]
[topological_space M₃] [add_comm_monoid M₁] [module R₁ M₁]
lemma is_compact_operator.comp_clm [add_comm_monoid M₂] [module R₂ M₂] {f : M₂ → M₃}
(hf : is_compact_operator f) (g : M₁ →SL[σ₁₂] M₂) :
is_compact_operator (f ∘ g) :=
begin
have := g.continuous.tendsto 0,
rw map_zero at this,
rcases hf with ⟨K, hK, hKf⟩,
exact ⟨K, hK, this hKf⟩
end
lemma is_compact_operator.continuous_comp {f : M₁ → M₂} (hf : is_compact_operator f) {g : M₂ → M₃}
(hg : continuous g) :
is_compact_operator (g ∘ f) :=
begin
rcases hf with ⟨K, hK, hKf⟩,
refine ⟨g '' K, hK.image hg, mem_of_superset hKf _⟩,
nth_rewrite 1 preimage_comp,
exact preimage_mono (subset_preimage_image _ _)
end
lemma is_compact_operator.clm_comp [add_comm_monoid M₂] [module R₂ M₂] [add_comm_monoid M₃]
[module R₃ M₃] {f : M₁ → M₂} (hf : is_compact_operator f) (g : M₂ →SL[σ₂₃] M₃) :
is_compact_operator (g ∘ f) :=
hf.continuous_comp g.continuous
end comp
section cod_restrict
variables {R₁ R₂ : Type*} [semiring R₁] [semiring R₂] {σ₁₂ : R₁ →+* R₂}
{M₁ M₂ : Type*} [topological_space M₁] [topological_space M₂]
[add_comm_monoid M₁] [add_comm_monoid M₂] [module R₁ M₁] [module R₂ M₂]
lemma is_compact_operator.cod_restrict {f : M₁ → M₂} (hf : is_compact_operator f)
{V : submodule R₂ M₂} (hV : ∀ x, f x ∈ V) (h_closed : is_closed (V : set M₂)):
is_compact_operator (set.cod_restrict f V hV) :=
let ⟨K, hK, hKf⟩ := hf in
⟨coe ⁻¹' K, (closed_embedding_subtype_coe h_closed).is_compact_preimage hK, hKf⟩
end cod_restrict
section restrict
variables {R₁ R₂ R₃ : Type*} [semiring R₁] [semiring R₂] [semiring R₃] {σ₁₂ : R₁ →+* R₂}
{σ₂₃ : R₂ →+* R₃} {M₁ M₂ M₃ : Type*} [topological_space M₁] [uniform_space M₂]
[topological_space M₃] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃]
[module R₁ M₁] [module R₂ M₂] [module R₃ M₃]
/-- If a compact operator preserves a closed submodule, its restriction to that submodule is
compact.
Note that, following mathlib's convention in linear algebra, `restrict` designates the restriction
of an endomorphism `f : E →ₗ E` to an endomorphism `f' : ↥V →ₗ ↥V`. To prove that the restriction
`f' : ↥U →ₛₗ ↥V` of a compact operator `f : E →ₛₗ F` is compact, apply
`is_compact_operator.cod_restrict` to `f ∘ U.subtypeL`, which is compact by
`is_compact_operator.comp_clm`. -/
lemma is_compact_operator.restrict {f : M₁ →ₗ[R₁] M₁} (hf : is_compact_operator f)
{V : submodule R₁ M₁} (hV : ∀ v ∈ V, f v ∈ V) (h_closed : is_closed (V : set M₁)):
is_compact_operator (f.restrict hV) :=
(hf.comp_clm V.subtypeL).cod_restrict (set_like.forall.2 hV) h_closed
/-- If a compact operator preserves a complete submodule, its restriction to that submodule is
compact.
Note that, following mathlib's convention in linear algebra, `restrict` designates the restriction
of an endomorphism `f : E →ₗ E` to an endomorphism `f' : ↥V →ₗ ↥V`. To prove that the restriction
`f' : ↥U →ₛₗ ↥V` of a compact operator `f : E →ₛₗ F` is compact, apply
`is_compact_operator.cod_restrict` to `f ∘ U.subtypeL`, which is compact by
`is_compact_operator.comp_clm`. -/
lemma is_compact_operator.restrict' [separated_space M₂] {f : M₂ →ₗ[R₂] M₂}
(hf : is_compact_operator f) {V : submodule R₂ M₂} (hV : ∀ v ∈ V, f v ∈ V)
[hcomplete : complete_space V] : is_compact_operator (f.restrict hV) :=
hf.restrict hV (complete_space_coe_iff_is_complete.mp hcomplete).is_closed
end restrict
section continuous
variables {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁] [nontrivially_normed_field 𝕜₂]
{σ₁₂ : 𝕜₁ →+* 𝕜₂} [ring_hom_isometric σ₁₂] {M₁ M₂ : Type*} [topological_space M₁]
[add_comm_group M₁] [topological_space M₂] [add_comm_group M₂] [module 𝕜₁ M₁] [module 𝕜₂ M₂]
[topological_add_group M₁] [has_continuous_const_smul 𝕜₁ M₁]
[topological_add_group M₂] [has_continuous_smul 𝕜₂ M₂]
@[continuity] lemma is_compact_operator.continuous {f : M₁ →ₛₗ[σ₁₂] M₂}
(hf : is_compact_operator f) : continuous f :=
begin
letI : uniform_space M₂ := topological_add_group.to_uniform_space _,
haveI : uniform_add_group M₂ := topological_add_comm_group_is_uniform,
-- Since `f` is linear, we only need to show that it is continuous at zero.
-- Let `U` be a neighborhood of `0` in `M₂`.
refine continuous_of_continuous_at_zero f (λ U hU, _),
rw map_zero at hU,
-- The compactness of `f` gives us a compact set `K : set M₂` such that `f ⁻¹' K` is a
-- neighborhood of `0` in `M₁`.
rcases hf with ⟨K, hK, hKf⟩,
-- But any compact set is totally bounded, hence Von-Neumann bounded. Thus, `K` absorbs `U`.
-- This gives `r > 0` such that `∀ a : 𝕜₂, r ≤ ‖a‖ → K ⊆ a • U`.
rcases hK.totally_bounded.is_vonN_bounded 𝕜₂ hU with ⟨r, hr, hrU⟩,
-- Choose `c : 𝕜₂` with `r < ‖c‖`.
rcases normed_field.exists_lt_norm 𝕜₁ r with ⟨c, hc⟩,
have hcnz : c ≠ 0 := ne_zero_of_norm_ne_zero (hr.trans hc).ne.symm,
-- We have `f ⁻¹' ((σ₁₂ c⁻¹) • K) = c⁻¹ • f ⁻¹' K ∈ 𝓝 0`. Thus, showing that
-- `(σ₁₂ c⁻¹) • K ⊆ U` is enough to deduce that `f ⁻¹' U ∈ 𝓝 0`.
suffices : (σ₁₂ $ c⁻¹) • K ⊆ U,
{ refine mem_of_superset _ this,
have : is_unit c⁻¹ := hcnz.is_unit.inv,
rwa [mem_map, preimage_smul_setₛₗ _ _ _ f this, set_smul_mem_nhds_zero_iff (inv_ne_zero hcnz)],
apply_instance },
-- Since `σ₁₂ c⁻¹` = `(σ₁₂ c)⁻¹`, we have to prove that `K ⊆ σ₁₂ c • U`.
rw [map_inv₀, ← subset_set_smul_iff₀ ((map_ne_zero σ₁₂).mpr hcnz)],
-- But `σ₁₂` is isometric, so `‖σ₁₂ c‖ = ‖c‖ > r`, which concludes the argument since
-- `∀ a : 𝕜₂, r ≤ ‖a‖ → K ⊆ a • U`.
refine hrU (σ₁₂ c) _,
rw ring_hom_isometric.is_iso,
exact hc.le
end
/-- Upgrade a compact `linear_map` to a `continuous_linear_map`. -/
def continuous_linear_map.mk_of_is_compact_operator {f : M₁ →ₛₗ[σ₁₂] M₂}
(hf : is_compact_operator f) : M₁ →SL[σ₁₂] M₂ :=
⟨f, hf.continuous⟩
@[simp] lemma continuous_linear_map.mk_of_is_compact_operator_to_linear_map {f : M₁ →ₛₗ[σ₁₂] M₂}
(hf : is_compact_operator f) :
(continuous_linear_map.mk_of_is_compact_operator hf : M₁ →ₛₗ[σ₁₂] M₂) = f :=
rfl
@[simp] lemma continuous_linear_map.coe_mk_of_is_compact_operator {f : M₁ →ₛₗ[σ₁₂] M₂}
(hf : is_compact_operator f) :
(continuous_linear_map.mk_of_is_compact_operator hf : M₁ → M₂) = f :=
rfl
lemma continuous_linear_map.mk_of_is_compact_operator_mem_compact_operator {f : M₁ →ₛₗ[σ₁₂] M₂}
(hf : is_compact_operator f) :
continuous_linear_map.mk_of_is_compact_operator hf ∈ compact_operator σ₁₂ M₁ M₂ :=
hf
end continuous
lemma is_closed_set_of_is_compact_operator {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁]
[nontrivially_normed_field 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂} [ring_hom_isometric σ₁₂] {M₁ M₂ : Type*}
[seminormed_add_comm_group M₁] [normed_add_comm_group M₂] [normed_space 𝕜₁ M₁]
[normed_space 𝕜₂ M₂] [complete_space M₂] :
is_closed {f : M₁ →SL[σ₁₂] M₂ | is_compact_operator f} :=
begin
refine is_closed_of_closure_subset _,
rintros u hu,
rw metric.mem_closure_iff at hu,
suffices : totally_bounded (u '' metric.closed_ball 0 1),
{ change is_compact_operator (u : M₁ →ₛₗ[σ₁₂] M₂),
rw is_compact_operator_iff_is_compact_closure_image_closed_ball (u : M₁ →ₛₗ[σ₁₂] M₂)
zero_lt_one,
exact is_compact_of_totally_bounded_is_closed this.closure is_closed_closure },
rw metric.totally_bounded_iff,
intros ε hε,
rcases hu (ε/2) (by linarith) with ⟨v, hv, huv⟩,
rcases (hv.is_compact_closure_image_closed_ball 1).finite_cover_balls
(show 0 < ε/2, by linarith) with ⟨T, -, hT, hTv⟩,
have hTv : v '' closed_ball 0 1 ⊆ _ := subset_closure.trans hTv,
refine ⟨T, hT, _⟩,
rw image_subset_iff at ⊢ hTv,
intros x hx,
specialize hTv hx,
rw [mem_preimage, mem_Union₂] at ⊢ hTv,
rcases hTv with ⟨t, ht, htx⟩,
refine ⟨t, ht, _⟩,
suffices : dist (u x) (v x) < ε/2,
{ rw mem_ball at *,
linarith [dist_triangle (u x) (v x) t] },
rw mem_closed_ball_zero_iff at hx,
calc dist (u x) (v x)
= ‖u x - v x‖ : dist_eq_norm _ _
... = ‖(u - v) x‖ : by rw continuous_linear_map.sub_apply; refl
... ≤ ‖u - v‖ : (u - v).unit_le_op_norm x hx
... = dist u v : (dist_eq_norm _ _).symm
... < ε/2 : huv
end
lemma compact_operator_topological_closure {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁]
[nontrivially_normed_field 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂} [ring_hom_isometric σ₁₂] {M₁ M₂ : Type*}
[seminormed_add_comm_group M₁] [normed_add_comm_group M₂] [normed_space 𝕜₁ M₁]
[normed_space 𝕜₂ M₂] [complete_space M₂] :
(compact_operator σ₁₂ M₁ M₂).topological_closure = compact_operator σ₁₂ M₁ M₂ :=
set_like.ext' (is_closed_set_of_is_compact_operator.closure_eq)
lemma is_compact_operator_of_tendsto {ι 𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁]
[nontrivially_normed_field 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂} [ring_hom_isometric σ₁₂] {M₁ M₂ : Type*}
[seminormed_add_comm_group M₁] [normed_add_comm_group M₂] [normed_space 𝕜₁ M₁]
[normed_space 𝕜₂ M₂] [complete_space M₂] {l : filter ι} [l.ne_bot] {F : ι → M₁ →SL[σ₁₂] M₂}
{f : M₁ →SL[σ₁₂] M₂} (hf : tendsto F l (𝓝 f)) (hF : ∀ᶠ i in l, is_compact_operator (F i)) :
is_compact_operator f :=
is_closed_set_of_is_compact_operator.mem_of_tendsto hf hF
|
541542159d421dfe34f134da26b64d6db643bb97 | 43390109ab88557e6090f3245c47479c123ee500 | /src/M1F/problem_bank/0505/S0505.lean | d31d9ef627bab3df088c287453c9ab6ee164299e | [
"Apache-2.0"
] | permissive | Ja1941/xena-UROP-2018 | 41f0956519f94d56b8bf6834a8d39473f4923200 | b111fb87f343cf79eca3b886f99ee15c1dd9884b | refs/heads/master | 1,662,355,955,139 | 1,590,577,325,000 | 1,590,577,325,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,200 | lean | import algebra.group_power tactic.norm_num algebra.big_operators
theorem Q5 : (¬ (∃ a b c : ℕ, 6*a+9*b+20*c = 43))
∧ ∀ m, m ≥ 44 → ∃ a b c : ℕ, 6*a+9*b+20*c = m :=
begin
split,
intro H,
cases H with a H,
cases H with b H,
cases H with c H,
revert H,
cases c with c,tactic.swap,
cases c with c,tactic.swap,
cases c with c,tactic.swap,
show 6*a+9*b+20*(c+3) = 43 → false,
rw [mul_add],
apply ne_of_gt,
exact calc 6 * a + 9 * b + (20 * c + 20 * 3)
= 6*a + (9*b+(20*c+20*3)) : by simp
... ≥ 9 * b + (20 * c + 20 * 3) : nat.le_add_left (9 * b + (20 * c + 20 * 3)) (6*a)
... ≥ 20 * c + 20 * 3 : nat.le_add_left _ _
... ≥ 20*3 : nat.le_add_left _ _
... > 43 : dec_trivial,
cases b with b,tactic.swap,
show (6*a+9*(b+1)+20*2=43 → false),
rw [mul_add],
apply ne_of_gt,
exact calc 6 * a + (9 * b + 9 * 1) + 20 * 2
= (6*a+9*b)+9*1+20*2 : by simp
... ≥ 9*1+20*2 : nat.le_add_left _ _
... > 43 : dec_trivial,
cases a with a,
exact dec_trivial,
show 6*(a+1) + 9 * 0 + 20 * 2 = 43 → false,
rw [mul_add],
apply ne_of_gt,
exact calc 6 * a + 6 * 1 + 9 * 0 + 20 * 2
≥ 6 * 1 + 9 * 0 + 20 * 2 : nat.le_add_left _ _
... > 43 : dec_trivial,
cases b with b,tactic.swap,
cases b with b,tactic.swap,
cases b with b,tactic.swap,
show (6*a+9*(b+3)+20*1=43 → false),
rw [mul_add],
apply ne_of_gt,
exact calc 6 * a + (9 * b + 9 * 3) + 20 * 1
= (6*a+9*b)+9*3+20*1 : by simp
... ≥ 9*3+20*1 : nat.le_add_left _ _
... > 43 : dec_trivial,
cases a with a,
exact dec_trivial,
show 6*(a+1) + 9 * 2 + 20 * 1 = 43 → false,
rw [mul_add],
apply ne_of_gt,
exact calc 6 * a + 6 * 1 + 9 * 2 + 20 * 1
≥ 6 * 1 + 9 * 2 + 20 * 1 : nat.le_add_left _ _
... > 43 : dec_trivial,
cases a with a,
exact dec_trivial,
cases a with a,
exact dec_trivial,
cases a with a,
exact dec_trivial,
show 6*(a+3) + 9 * 1 + 20 * 1 = 43 → false,
rw [mul_add],
apply ne_of_gt,
exact calc 6 * a + 6 * 3 + 9 * 1 + 20 * 1
≥ 6 * 3 + 9 * 1 + 20 * 1 : nat.le_add_left _ _
... > 43 : dec_trivial,
cases a with a,
exact dec_trivial,
cases a with a,
exact dec_trivial,
cases a with a,
exact dec_trivial,
cases a with a,
exact dec_trivial,
show 6*(a+4) + 9 * 0 + 20 * 1 = 43 → false,
rw [mul_add],
apply ne_of_gt,
exact calc 6 * a + 6 * 4 + 9 * 0 + 20 * 1
≥ 6 * 4 + 9 * 0 + 20 * 1 : nat.le_add_left _ _
... > 43 : dec_trivial,
cases b with b,tactic.swap,
cases b with b,tactic.swap,
cases b with b,tactic.swap,
cases b with b,tactic.swap,
cases b with b,tactic.swap,
show (6*a+9*(b+5)+20*0=43 → false),
rw [mul_add],
apply ne_of_gt,
exact calc 6 * a + (9 * b + 9 * 5) + 20 * 0
= (6*a+9*b)+9*5+20*0 : by simp
... ≥ 9*5+20*0 : nat.le_add_left _ _
... > 43 : dec_trivial,
cases a with a,
exact dec_trivial,
cases a with a,
exact dec_trivial,
show 6*(a+2) + 9 * 4 + 20 * 0 = 43 → false,
rw [mul_add],
apply ne_of_gt,
exact calc 6 * a + 6 * 2 + 9 * 4 + 20 * 0
≥ 6 * 2 + 9 * 4 + 20 * 0 : nat.le_add_left _ _
... > 43 : dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
show 6*(a+3) + 9 * 3 + 20 * 0 = 43 → false,
rw [mul_add],
apply ne_of_gt,
exact calc 6 * a + 6 * 3 + 9 * 3 + 20 * 0
≥ 6 * 3 + 9 * 3 + 20 * 0 : nat.le_add_left _ _
... > 43 : dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
show 6*(a+5) + 9 * 2 + 20 * 0 = 43 → false,
rw [mul_add],
apply ne_of_gt,
exact calc 6 * a + 6 * 5 + 9 * 2 + 20 * 0
≥ 6 * 5 + 9 * 2 + 20 * 0 : nat.le_add_left _ _
... > 43 : dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
show 6*(a+6) + 9 * 1 + 20 * 0 = 43 → false,
rw [mul_add],
apply ne_of_gt,
exact calc 6 * a + 6 * 6 + 9 * 1 + 20 * 0
≥ 6 * 6 + 9 * 1 + 20 * 0 : nat.le_add_left _ _
... > 43 : dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
cases a with a,exact dec_trivial,
show 6*(a+8) + 9 * 0 + 20 * 0 = 43 → false,
rw [mul_add],
apply ne_of_gt,
exact calc 6 * a + 6 * 8 + 9 * 0 + 20 * 0
≥ 6 * 8 + 9 * 0 + 20 * 0 : nat.le_add_left _ _
... > 43 : dec_trivial,
-- now the opposite
-- proof that if m>=44 then it's 44+n
-- probably would have been easier to do by induction on 44
intros m Hm,
have H44 : ∃ n : ℕ, m=44+n,
let c:ℤ := m-((44:ℕ):ℤ),
have Hc_nonneg : c ≥ 0 := calc
c = ↑m - ↑44 : rfl
... = ↑m + -↑44 : sub_eq_add_neg _ _
... ≥ ↑44 + -↑44 : add_le_add_right ((int.coe_nat_le_coe_nat_iff _ _).2 Hm) _
... = 0 : add_neg_self _,
have H := int.nat_abs_of_nonneg Hc_nonneg,
let n := int.nat_abs c,
existsi n,
apply (int.of_nat_eq_of_nat_iff _ _).1,
rw [←int.coe_nat_eq,←int.coe_nat_eq,int.coe_nat_add,H,add_comm,sub_add_cancel],
cases H44 with n H,
rw [H],
clear Hm H m,
/- State now
n : ℕ
⊢ ∃ (a b c : ℕ), 6 * a + 9 * b + 20 * c = 44 + n
-/
-- Now need division with remainder
have H6 : ∃ q r : ℕ, n=6*q+r ∧ (r=0 ∨ r=1 ∨ r=2 ∨ r=3 ∨ r=4 ∨ r=5),
induction n with d Hd,
existsi 0,
existsi 0,
split,
simp,
simp,
cases Hd with q Hd',
cases Hd' with r HI,
cases HI.right with H0 H15,
existsi q,
existsi 1,
split,
simp [HI.left,H0,nat.succ_eq_add_one],
simp,
cases H15 with H H25,
existsi q,
existsi 2,
split,
-- simp [nat.succ_eq_add_one,HI.left,H1],
rw [nat.succ_eq_add_one,HI.left,H],
simp,
cases H25 with H H35,
existsi q,
existsi 3,
split,
rw [nat.succ_eq_add_one,HI.left,H],
simp,
cases H35 with H H45,
existsi q,
existsi 4,
split,
rw [nat.succ_eq_add_one,HI.left,H],
simp,
cases H45 with H H5,
existsi q,
existsi 5,
split,
rw [nat.succ_eq_add_one,HI.left,H],
simp,
existsi q+1,
existsi 0,
split,
rw [nat.succ_eq_add_one,HI.left,H5,mul_add,mul_one],
simp,
cases H6 with q H6',
cases H6' with r H,
rw [H.left],
have Hrsmall := H.right,
clear H n,
/-
State now
q r : ℕ
Hrsmall : r = 0 ∨ r = 1 ∨ r = 2 ∨ r = 3 ∨ r = 4 ∨ r = 5
⊢ ∃ (a b c : ℕ), 6 * a + 9 * b + 20 * c = 44 + (6 * q + r)
-/
induction q with d Hd,
cases Hrsmall with H H15,
existsi 4,existsi 0,existsi 1,
rw [H],exact dec_trivial,
cases H15 with H H25,
existsi 0,existsi 5,existsi 0,
rw [H],exact dec_trivial,
cases H25 with H H35,
existsi 1,existsi 0,existsi 2,
rw [H],exact dec_trivial,
cases H35 with H H45,
existsi 0,existsi 3,existsi 1,
rw [H],exact dec_trivial,
cases H45 with H H5,
existsi 8,existsi 0,existsi 0,
rw [H],exact dec_trivial,
existsi 0,existsi 1,existsi 2,
rw [H5],exact dec_trivial,
clear Hrsmall,
cases Hd with a Hd',
cases Hd' with b Hd'',
cases Hd'' with c H,
existsi (a+1),
existsi b,
existsi c,
rw [nat.succ_eq_add_one,mul_add,mul_add,mul_one],
rw [add_comm (6*a) 6,add_assoc,add_assoc],
rw add_assoc at H,
rw H,
simp,
end |
38d72bc1480b3866c9e19b6a4d8990ef33892980 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/algebra/pointwise.lean | 3d82b77c295cda0f89f7ccdecfb19d3a87160544 | [
"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 | 19,533 | 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 addition, multiplication, and scalar multiplication of sets.
This file defines pointwise algebraic operations on sets.
* For a type `α` with multiplication, multiplication is defined on `set α` by taking
`s * t` to be the set of all `x * y` where `x ∈ s` and `y ∈ t`. Similarly for addition.
* For `α` a semigroup, `set α` is a semigroup.
* If `α` is a (commutative) monoid, we define an alias `set_semiring α` for `set α`, which then
becomes a (commutative) semiring with union as addition and pointwise multiplication as
multiplication.
* For a type `β` with scalar multiplication by another type `α`, this
file defines a scalar multiplication of `set β` by `set α` and a separate scalar
multiplication of `set β` by `α`.
* We also define pointwise multiplication on `finset`.
Appropriate definitions and results are also transported to the additive theory via `to_additive`.
## Implementation notes
* The following expressions are considered in simp-normal form in a group:
`(λ h, h * g) ⁻¹' s`, `(λ h, g * h) ⁻¹' s`, `(λ h, h * g⁻¹) ⁻¹' s`, `(λ h, g⁻¹ * h) ⁻¹' s`,
`s * t`, `s⁻¹`, `(1 : set _)` (and similarly for additive variants).
Expressions equal to one of these will be simplified.
## Tags
set multiplication, set addition, pointwise addition, pointwise multiplication
-/
namespace set
open function
variables {α : Type*} {β : Type*} {s s₁ s₂ t t₁ t₂ u : set α} {a b : α} {x y : β}
/-! ### Properties about 1 -/
@[to_additive]
instance [has_one α] : has_one (set α) := ⟨{1}⟩
@[to_additive]
lemma singleton_one [has_one α] : ({1} : set α) = 1 := rfl
@[simp, to_additive]
lemma mem_one [has_one α] : a ∈ (1 : set α) ↔ a = 1 := iff.rfl
@[to_additive]
lemma one_mem_one [has_one α] : (1 : α) ∈ (1 : set α) := eq.refl _
@[simp, to_additive]
theorem one_subset [has_one α] : 1 ⊆ s ↔ (1 : α) ∈ s := singleton_subset_iff
@[to_additive]
theorem one_nonempty [has_one α] : (1 : set α).nonempty := ⟨1, rfl⟩
@[simp, to_additive]
theorem image_one [has_one α] {f : α → β} : f '' 1 = {f 1} := image_singleton
/-! ### Properties about multiplication -/
@[to_additive]
instance [has_mul α] : has_mul (set α) := ⟨image2 has_mul.mul⟩
@[simp, to_additive]
lemma image2_mul [has_mul α] : image2 has_mul.mul s t = s * t := rfl
@[to_additive]
lemma mem_mul [has_mul α] : a ∈ s * t ↔ ∃ x y, x ∈ s ∧ y ∈ t ∧ x * y = a := iff.rfl
@[to_additive]
lemma mul_mem_mul [has_mul α] (ha : a ∈ s) (hb : b ∈ t) : a * b ∈ s * t := mem_image2_of_mem ha hb
@[to_additive add_image_prod]
lemma image_mul_prod [has_mul α] : (λ x : α × α, x.fst * x.snd) '' s.prod t = s * t := image_prod _
@[simp, to_additive]
lemma image_mul_left [group α] : (λ b, a * b) '' t = (λ b, a⁻¹ * b) ⁻¹' t :=
by { rw image_eq_preimage_of_inverse; intro c; simp }
@[simp, to_additive]
lemma image_mul_right [group α] : (λ a, a * b) '' t = (λ a, a * b⁻¹) ⁻¹' t :=
by { rw image_eq_preimage_of_inverse; intro c; simp }
@[to_additive]
lemma image_mul_left' [group α] : (λ b, a⁻¹ * b) '' t = (λ b, a * b) ⁻¹' t := by simp
@[to_additive]
lemma image_mul_right' [group α] : (λ a, a * b⁻¹) '' t = (λ a, a * b) ⁻¹' t := by simp
@[simp, to_additive]
lemma preimage_mul_left_singleton [group α] : ((*) a) ⁻¹' {b} = {a⁻¹ * b} :=
by rw [← image_mul_left', image_singleton]
@[simp, to_additive]
lemma preimage_mul_right_singleton [group α] : (* a) ⁻¹' {b} = {b * a⁻¹} :=
by rw [← image_mul_right', image_singleton]
@[simp, to_additive]
lemma preimage_mul_left_one [group α] : (λ b, a * b) ⁻¹' 1 = {a⁻¹} :=
by rw [← image_mul_left', image_one, mul_one]
@[simp, to_additive]
lemma preimage_mul_right_one [group α] : (λ a, a * b) ⁻¹' 1 = {b⁻¹} :=
by rw [← image_mul_right', image_one, one_mul]
@[to_additive]
lemma preimage_mul_left_one' [group α] : (λ b, a⁻¹ * b) ⁻¹' 1 = {a} := by simp
@[to_additive]
lemma preimage_mul_right_one' [group α] : (λ a, a * b⁻¹) ⁻¹' 1 = {b} := by simp
@[simp, to_additive]
lemma mul_singleton [has_mul α] : s * {b} = (λ a, a * b) '' s := image2_singleton_right
@[simp, to_additive]
lemma singleton_mul [has_mul α] : {a} * t = (λ b, a * b) '' t := image2_singleton_left
@[simp, to_additive]
lemma singleton_mul_singleton [has_mul α] : ({a} : set α) * {b} = {a * b} := image2_singleton
@[to_additive set.add_zero_class]
instance [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 }
@[to_additive set.add_semigroup]
instance [semigroup α] : semigroup (set α) :=
{ mul_assoc := λ _ _ _, image2_assoc mul_assoc,
..set.has_mul }
@[to_additive set.add_monoid]
instance [monoid α] : monoid (set α) :=
{ ..set.semigroup,
..set.mul_one_class }
@[to_additive]
protected lemma mul_comm [comm_semigroup α] : s * t = t * s :=
by simp only [← image2_mul, image2_swap _ s, mul_comm]
@[to_additive set.add_comm_monoid]
instance [comm_monoid α] : comm_monoid (set α) :=
{ mul_comm := λ _ _, set.mul_comm, ..set.monoid }
@[to_additive]
lemma singleton.is_mul_hom [has_mul α] : is_mul_hom (singleton : α → set α) :=
{ map_mul := λ a b, singleton_mul_singleton.symm }
@[simp, to_additive]
lemma empty_mul [has_mul α] : ∅ * s = ∅ := image2_empty_left
@[simp, to_additive]
lemma mul_empty [has_mul α] : s * ∅ = ∅ := image2_empty_right
@[to_additive]
lemma mul_subset_mul [has_mul α] (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ * s₂ ⊆ t₁ * t₂ :=
image2_subset h₁ h₂
@[to_additive]
lemma union_mul [has_mul α] : (s ∪ t) * u = (s * u) ∪ (t * u) := image2_union_left
@[to_additive]
lemma mul_union [has_mul α] : s * (t ∪ u) = (s * t) ∪ (s * u) := image2_union_right
@[to_additive]
lemma Union_mul_left_image [has_mul α] : (⋃ a ∈ s, (λ x, a * x) '' t) = s * t :=
Union_image_left _
@[to_additive]
lemma Union_mul_right_image [has_mul α] : (⋃ a ∈ t, (λ x, x * a) '' s) = s * t :=
Union_image_right _
@[simp, to_additive]
lemma univ_mul_univ [monoid α] : (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
/-- `singleton` is a monoid hom. -/
@[to_additive singleton_add_hom "singleton is an add monoid hom"]
def singleton_hom [monoid α] : α →* set α :=
{ to_fun := singleton, map_one' := rfl, map_mul' := λ a b, singleton_mul_singleton.symm }
@[to_additive]
lemma nonempty.mul [has_mul α] : s.nonempty → t.nonempty → (s * t).nonempty := nonempty.image2
@[to_additive]
lemma finite.mul [has_mul α] (hs : finite s) (ht : finite t) : finite (s * t) :=
hs.image2 _ ht
/-- multiplication preserves finiteness -/
@[to_additive "addition preserves finiteness"]
def fintype_mul [has_mul α] [decidable_eq α] (s t : set α) [hs : fintype s] [ht : fintype t] :
fintype (s * t : set α) :=
set.fintype_image2 _ s t
@[to_additive]
lemma bdd_above_mul [ordered_comm_monoid α] {A B : set α} :
bdd_above A → bdd_above B → bdd_above (A * B) :=
begin
rintros ⟨bA, hbA⟩ ⟨bB, hbB⟩,
use bA * bB,
rintros x ⟨xa, xb, hxa, hxb, rfl⟩,
exact mul_le_mul' (hbA hxa) (hbB hxb),
end
/-! ### Properties about inversion -/
@[to_additive set.has_neg]
instance [has_inv α] : has_inv (set α) :=
⟨preimage has_inv.inv⟩
@[simp, to_additive]
lemma mem_inv [has_inv α] : a ∈ s⁻¹ ↔ a⁻¹ ∈ s := iff.rfl
@[to_additive]
lemma inv_mem_inv [group α] : a⁻¹ ∈ s⁻¹ ↔ a ∈ s :=
by simp only [mem_inv, inv_inv]
@[simp, to_additive]
lemma inv_preimage [has_inv α] : has_inv.inv ⁻¹' s = s⁻¹ := rfl
@[simp, to_additive]
lemma image_inv [group α] : has_inv.inv '' s = s⁻¹ :=
by { simp only [← inv_preimage], rw [image_eq_preimage_of_inverse]; intro; simp only [inv_inv] }
@[simp, to_additive]
lemma inter_inv [has_inv α] : (s ∩ t)⁻¹ = s⁻¹ ∩ t⁻¹ := preimage_inter
@[simp, to_additive]
lemma union_inv [has_inv α] : (s ∪ t)⁻¹ = s⁻¹ ∪ t⁻¹ := preimage_union
@[simp, to_additive]
lemma compl_inv [has_inv α] : (sᶜ)⁻¹ = (s⁻¹)ᶜ := preimage_compl
@[simp, to_additive]
protected lemma inv_inv [group α] : s⁻¹⁻¹ = s :=
by { simp only [← inv_preimage, preimage_preimage, inv_inv, preimage_id'] }
@[simp, to_additive]
protected lemma univ_inv [group α] : (univ : set α)⁻¹ = univ := preimage_univ
@[simp, to_additive]
lemma inv_subset_inv [group α] {s t : set α} : s⁻¹ ⊆ t⁻¹ ↔ s ⊆ t :=
(equiv.inv α).surjective.preimage_subset_preimage_iff
@[to_additive] lemma inv_subset [group α] {s t : set α} : s⁻¹ ⊆ t ↔ s ⊆ t⁻¹ :=
by { rw [← inv_subset_inv, set.inv_inv] }
@[to_additive] lemma finite.inv [group α] {s : set α} (hs : finite s) : finite s⁻¹ :=
hs.preimage $ inv_injective.inj_on _
/-! ### Properties about scalar multiplication -/
/-- Scaling a set: multiplying every element by a scalar. -/
instance has_scalar_set [has_scalar α β] : has_scalar α (set β) :=
⟨λ a, image (has_scalar.smul a)⟩
@[simp]
lemma image_smul [has_scalar α β] {t : set β} : (λ x, a • x) '' t = a • t := rfl
lemma mem_smul_set [has_scalar α β] {t : set β} : x ∈ a • t ↔ ∃ y, y ∈ t ∧ a • y = x := iff.rfl
lemma smul_mem_smul_set [has_scalar α β] {t : set β} (hy : y ∈ t) : a • y ∈ a • t :=
⟨y, hy, rfl⟩
lemma smul_set_union [has_scalar α β] {s t : set β} : a • (s ∪ t) = a • s ∪ a • t :=
by simp only [← image_smul, image_union]
@[simp]
lemma smul_set_empty [has_scalar α β] (a : α) : a • (∅ : set β) = ∅ :=
by rw [← image_smul, image_empty]
lemma smul_set_mono [has_scalar α β] {s t : set β} (h : s ⊆ t) : a • s ⊆ a • t :=
by { simp only [← image_smul, image_subset, h] }
/-- Pointwise scalar multiplication by a set of scalars. -/
instance [has_scalar α β] : has_scalar (set α) (set β) := ⟨image2 has_scalar.smul⟩
@[simp]
lemma image2_smul [has_scalar α β] {t : set β} : image2 has_scalar.smul s t = s • t := rfl
lemma mem_smul [has_scalar α β] {t : set β} : x ∈ s • t ↔ ∃ a y, a ∈ s ∧ y ∈ t ∧ a • y = x :=
iff.rfl
lemma image_smul_prod [has_scalar α β] {t : set β} :
(λ x : α × β, x.fst • x.snd) '' s.prod t = s • t :=
image_prod _
theorem range_smul_range [has_scalar α β] {ι κ : Type*} (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⟩⟩
lemma singleton_smul [has_scalar α β] {t : set β} : ({a} : set α) • t = a • t :=
image2_singleton_left
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] def set_semiring (α : Type*) : Type* := set α
/-- The identitiy function `set α → set_semiring α`. -/
protected def up (s : set α) : set_semiring α := s
/-- The identitiy 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
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.mul_zero_class [has_mul α] : mul_zero_class (set_semiring α) :=
{ zero_mul := λ s, empty_mul,
mul_zero := λ s, mul_empty,
..set.has_mul, ..set_semiring.add_comm_monoid }
instance set_semiring.distrib [has_mul α] : distrib (set_semiring α) :=
{ left_distrib := λ _ _ _, mul_union,
right_distrib := λ _ _ _, union_mul,
..set.has_mul, ..set_semiring.add_comm_monoid }
instance set_semiring.mul_zero_one_class [mul_one_class α] : mul_zero_one_class (set_semiring α) :=
{ ..set_semiring.mul_zero_class, ..set.mul_one_class }
instance set_semiring.semigroup_with_zero [semigroup α] : semigroup_with_zero (set_semiring α) :=
{ ..set_semiring.mul_zero_class, ..set.semigroup }
instance set_semiring.semiring [monoid α] : semiring (set_semiring α) :=
{ ..set_semiring.add_comm_monoid,
..set_semiring.distrib,
..set_semiring.mul_zero_class,
..set.monoid }
instance set_semiring.comm_semiring [comm_monoid α] : comm_semiring (set_semiring α) :=
{ ..set.comm_monoid, ..set_semiring.semiring }
/-- A multiplicative action of a monoid on a type β gives also a
multiplicative action on the subsets of β. -/
instance 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, image_eta, one_smul, image_id'] },
..set.has_scalar_set }
section is_mul_hom
open is_mul_hom
variables [has_mul α] [has_mul β] (m : α → β) [is_mul_hom m]
@[to_additive]
lemma image_mul : m '' (s * t) = m '' s * m '' t :=
by { simp only [← image2_mul, image_image2, image2_image_left, image2_image_right, map_mul m] }
@[to_additive]
lemma preimage_mul_preimage_subset {s t : set β} : m ⁻¹' s * m ⁻¹' t ⊆ m ⁻¹' (s * t) :=
by { rintros _ ⟨_, _, _, _, rfl⟩, exact ⟨_, _, ‹_›, ‹_›, (map_mul _ _ _).symm ⟩ }
end is_mul_hom
/-- The image of a set under function 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, is_monoid_hom.map_one f],
map_add' := image_union _,
map_mul' := λ _ _, image_mul _ }
end monoid
end set
open set
section
variables {α : Type*} {β : Type*}
/-- A nonempty set in a module is scaled by zero to the singleton
containing 0 in the module. -/
lemma zero_smul_set [semiring α] [add_comm_monoid β] [module α β] {s : set β} (h : s.nonempty) :
(0 : α) • s = (0 : set β) :=
by simp only [← image_smul, image_eta, zero_smul, h.image_const, singleton_zero]
lemma mem_inv_smul_set_iff [field α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β) (x : β) :
x ∈ a⁻¹ • A ↔ a • x ∈ A :=
by simp only [← image_smul, mem_image, inv_smul_eq_iff' ha, exists_eq_right]
lemma mem_smul_set_iff_inv_smul_mem [field α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β)
(x : β) : x ∈ a • A ↔ a⁻¹ • x ∈ A :=
by rw [← mem_inv_smul_set_iff $ inv_ne_zero ha, inv_inv']
end
namespace finset
variables {α : Type*} [decidable_eq α]
/-- The pointwise product of two finite sets `s` and `t`:
`st = s ⬝ t = s * t = { x * y | x ∈ s, y ∈ t }`. -/
@[to_additive "The pointwise sum of two finite sets `s` and `t`:
`s + t = { x + y | x ∈ s, y ∈ t }`."]
instance [has_mul α] : has_mul (finset α) :=
⟨λ s t, (s.product t).image (λ p : α × α, p.1 * p.2)⟩
@[to_additive]
lemma mul_def [has_mul α] {s t : finset α} :
s * t = (s.product t).image (λ p : α × α, p.1 * p.2) := rfl
@[to_additive]
lemma mem_mul [has_mul α] {s t : finset α} {x : α} :
x ∈ s * t ↔ ∃ y z, y ∈ s ∧ z ∈ t ∧ y * z = x :=
by { simp only [finset.mul_def, and.assoc, mem_image, exists_prop, prod.exists, mem_product] }
@[simp, norm_cast, to_additive]
lemma coe_mul [has_mul α] {s t : finset α} : (↑(s * t) : set α) = ↑s * ↑t :=
by { ext, simp only [mem_mul, set.mem_mul, mem_coe] }
@[to_additive]
lemma mul_mem_mul [has_mul α] {s t : finset α} {x y : α} (hx : x ∈ s) (hy : y ∈ t) :
x * y ∈ s * t :=
by { simp only [finset.mem_mul], exact ⟨x, y, hx, hy, rfl⟩ }
lemma add_card_le [has_add α] {s t : finset α} : (s + t).card ≤ s.card * t.card :=
by { convert finset.card_image_le, rw [finset.card_product, mul_comm] }
@[to_additive]
lemma mul_card_le [has_mul α] {s t : finset α} : (s * t).card ≤ s.card * t.card :=
by { convert finset.card_image_le, rw [finset.card_product, mul_comm] }
open_locale classical
/-- A finite set `U` contained in the product of two sets `S * S'` is also contained in the product
of two finite sets `T * T' ⊆ S * S'`. -/
@[to_additive]
lemma subset_mul {M : Type*} [monoid M] {S : set M} {S' : set M} {U : finset M} (f : ↑U ⊆ S * S') :
∃ (T T' : finset M), ↑T ⊆ S ∧ ↑T' ⊆ S' ∧ U ⊆ T * T' :=
begin
apply finset.induction_on' U,
{ use [∅, ∅], simp only [finset.empty_subset, finset.coe_empty, set.empty_subset, and_self], },
rintros a s haU hs has ⟨T, T', hS, hS', h⟩,
obtain ⟨x, y, hx, hy, ha⟩ := set.mem_mul.1 (f haU),
use [insert x T, insert y T'],
simp only [finset.coe_insert],
repeat { rw [set.insert_subset], },
use [hx, hS, hy, hS'],
refine finset.insert_subset.mpr ⟨_, _⟩,
{ rw finset.mem_mul,
use [x,y],
simpa only [true_and, true_or, eq_self_iff_true, finset.mem_insert], },
{ suffices g : (s : set M) ⊆ insert x T * insert y T', { norm_cast at g, assumption, },
transitivity ↑(T * T'),
apply h,
rw finset.coe_mul,
apply set.mul_subset_mul (set.subset_insert x T) (set.subset_insert y T'), },
end
end finset
/-! Some lemmas about pointwise multiplication and submonoids. Ideally we put these in
`group_theory.submonoid.basic`, but currently we cannot because that file is imported by this. -/
namespace submonoid
variables {M : Type*} [monoid M]
@[to_additive]
lemma mul_subset {s t : set M} {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 {s t u : set M} (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⟩⟩,
rintros ⟨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)
end submonoid
|
1c73c99641b907f0a2970e24641fad6b3e5d9271 | d1bbf1801b3dcb214451d48214589f511061da63 | /src/ring_theory/roots_of_unity.lean | 7e86f84c4a4558a7d4fe74ef82043fc13d6e1d76 | [
"Apache-2.0"
] | permissive | cheraghchi/mathlib | 5c366f8c4f8e66973b60c37881889da8390cab86 | f29d1c3038422168fbbdb2526abf7c0ff13e86db | refs/heads/master | 1,676,577,831,283 | 1,610,894,638,000 | 1,610,894,638,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 38,371 | 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.nat.parity
import data.polynomial.ring_division
import group_theory.order_of_element
import ring_theory.integral_domain
import number_theory.divisors
import data.zmod.basic
import tactic.zify
import field_theory.separable
import field_theory.finite.basic
/-!
# Roots of unity and primitive roots of unity
We define roots of unity in the context of an arbitrary commutative monoid,
as a subgroup of the group of units. We also define a predicate `is_primitive_root` on commutative
monoids, expressing that an element is a primitive root of unity.
## Main definitions
* `roots_of_unity n M`, for `n : ℕ+` is the subgroup of the units of a commutative monoid `M`
consisting of elements `x` that satisfy `x ^ n = 1`.
* `is_primitive_root ζ k`: an element `ζ` is a primitive `k`-th root of unity if `ζ ^ k = 1`,
and if `l` satisfies `ζ ^ l = 1` then `k ∣ l`.
* `primitive_roots k R`: the finset of primitive `k`-th roots of unity in an integral domain `R`.
## Main results
* `roots_of_unity.is_cyclic`: the roots of unity in an integral domain form a cyclic group.
* `is_primitive_root.zmod_equiv_gpowers`: `zmod k` is equivalent to
the subgroup generated by a primitive `k`-th root of unity.
* `is_primitive_root.gpowers_eq`: in an integral domain, the subgroup generated by
a primitive `k`-th root of unity is equal to the `k`-th roots of unity.
* `is_primitive_root.card_primitive_roots`: if an integral domain
has a primitive `k`-th root of unity, then it has `φ k` of them.
## Implementation details
It is desirable that `roots_of_unity` is a subgroup,
and it will mainly be applied to rings (e.g. the ring of integers in a number field) and fields.
We therefore implement it as a subgroup of the units of a commutative monoid.
We have chosen to define `roots_of_unity n` for `n : ℕ+`, instead of `n : ℕ`,
because almost all lemmas need the positivity assumption,
and in particular the type class instances for `fintype` and `is_cyclic`.
On the other hand, for primitive roots of unity, it is desirable to have a predicate
not just on units, but directly on elements of the ring/field.
For example, we want to say that `exp (2 * pi * I / n)` is a primitive `n`-th root of unity
in the complex numbers, without having to turn that number into a unit first.
This creates a little bit of friction, but lemmas like `is_primitive_root.is_unit` and
`is_primitive_root.coe_units_iff` should provide the necessary glue.
-/
open_locale classical big_operators
noncomputable theory
open polynomial
open finset
variables {M N G G₀ R S : Type*}
variables [comm_monoid M] [comm_monoid N] [comm_group G] [comm_group_with_zero G₀]
variables [integral_domain R] [integral_domain S]
section roots_of_unity
variables {k l : ℕ+}
/-- `roots_of_unity k M` is the subgroup of elements `m : units M` that satisfy `m ^ k = 1` -/
def roots_of_unity (k : ℕ+) (M : Type*) [comm_monoid M] : subgroup (units M) :=
{ carrier := { ζ | ζ ^ (k : ℕ) = 1 },
one_mem' := one_pow _,
mul_mem' := λ ζ ξ hζ hξ, by simp only [*, set.mem_set_of_eq, mul_pow, one_mul] at *,
inv_mem' := λ ζ hζ, by simp only [*, set.mem_set_of_eq, inv_pow, one_inv] at * }
@[simp] lemma mem_roots_of_unity (k : ℕ+) (ζ : units M) :
ζ ∈ roots_of_unity k M ↔ ζ ^ (k : ℕ) = 1 := iff.rfl
lemma roots_of_unity_le_of_dvd (h : k ∣ l) : roots_of_unity k M ≤ roots_of_unity l M :=
begin
obtain ⟨d, rfl⟩ := h,
intros ζ h,
simp only [mem_roots_of_unity, pnat.mul_coe, pow_mul, one_pow, *] at *,
end
lemma map_roots_of_unity (f : units M →* units N) (k : ℕ+) :
(roots_of_unity k M).map f ≤ roots_of_unity k N :=
begin
rintros _ ⟨ζ, h, rfl⟩,
simp only [←monoid_hom.map_pow, *, mem_roots_of_unity, subgroup.mem_coe, monoid_hom.map_one] at *
end
lemma mem_roots_of_unity_iff_mem_nth_roots {ζ : units R} :
ζ ∈ roots_of_unity k R ↔ (ζ : R) ∈ nth_roots k (1 : R) :=
by simp only [mem_roots_of_unity, mem_nth_roots k.pos, units.ext_iff, units.coe_one, units.coe_pow]
variables (k R)
/-- Equivalence between the `k`-th roots of unity in `R` and the `k`-th roots of `1`.
This is implemented as equivalence of subtypes,
because `roots_of_unity` is a subgroup of the group of units,
whereas `nth_roots` is a multiset. -/
def roots_of_unity_equiv_nth_roots :
roots_of_unity k R ≃ {x // x ∈ nth_roots k (1 : R)} :=
begin
refine
{ to_fun := λ x, ⟨x, mem_roots_of_unity_iff_mem_nth_roots.mp x.2⟩,
inv_fun := λ x, ⟨⟨x, x ^ (k - 1 : ℕ), _, _⟩, _⟩,
left_inv := _,
right_inv := _ },
swap 4, { rintro ⟨x, hx⟩, ext, refl },
swap 4, { rintro ⟨x, hx⟩, ext, refl },
all_goals
{ rcases x with ⟨x, hx⟩, rw [mem_nth_roots k.pos] at hx,
simp only [subtype.coe_mk, ← pow_succ, ← pow_succ', hx,
nat.sub_add_cancel (show 1 ≤ (k : ℕ), from k.one_le)] },
{ show (_ : units R) ^ (k : ℕ) = 1,
simp only [units.ext_iff, hx, units.coe_mk, units.coe_one, subtype.coe_mk, units.coe_pow] }
end
variables {k R}
@[simp] lemma roots_of_unity_equiv_nth_roots_apply (x : roots_of_unity k R) :
(roots_of_unity_equiv_nth_roots R k x : R) = x :=
rfl
@[simp] lemma roots_of_unity_equiv_nth_roots_symm_apply (x : {x // x ∈ nth_roots k (1 : R)}) :
((roots_of_unity_equiv_nth_roots R k).symm x : R) = x :=
rfl
variables (k R)
instance roots_of_unity.fintype : fintype (roots_of_unity k R) :=
fintype.of_equiv {x // x ∈ nth_roots k (1 : R)} $ (roots_of_unity_equiv_nth_roots R k).symm
instance roots_of_unity.is_cyclic : is_cyclic (roots_of_unity k R) :=
is_cyclic_of_subgroup_integral_domain ((units.coe_hom R).comp (roots_of_unity k R).subtype)
(units.ext.comp subtype.val_injective)
lemma card_roots_of_unity : fintype.card (roots_of_unity k R) ≤ k :=
calc fintype.card (roots_of_unity k R)
= fintype.card {x // x ∈ nth_roots k (1 : R)} : fintype.card_congr (roots_of_unity_equiv_nth_roots R k)
... ≤ (nth_roots k (1 : R)).attach.card : multiset.card_le_of_le (multiset.erase_dup_le _)
... = (nth_roots k (1 : R)).card : multiset.card_attach
... ≤ k : card_nth_roots k 1
end roots_of_unity
/-- An element `ζ` is a primitive `k`-th root of unity if `ζ ^ k = 1`,
and if `l` satisfies `ζ ^ l = 1` then `k ∣ l`. -/
structure is_primitive_root (ζ : M) (k : ℕ) : Prop :=
(pow_eq_one : ζ ^ (k : ℕ) = 1)
(dvd_of_pow_eq_one : ∀ l : ℕ, ζ ^ l = 1 → k ∣ l)
section primitive_roots
variables {k : ℕ}
/-- `primitive_roots k R` is the finset of primitive `k`-th roots of unity
in the integral domain `R`. -/
def primitive_roots (k : ℕ) (R : Type*) [integral_domain R] : finset R :=
(nth_roots k (1 : R)).to_finset.filter (λ ζ, is_primitive_root ζ k)
@[simp] lemma mem_primitive_roots {ζ : R} (h0 : 0 < k) :
ζ ∈ primitive_roots k R ↔ is_primitive_root ζ k :=
begin
rw [primitive_roots, mem_filter, multiset.mem_to_finset, mem_nth_roots h0, and_iff_right_iff_imp],
exact is_primitive_root.pow_eq_one
end
end primitive_roots
namespace is_primitive_root
variables {k l : ℕ}
lemma iff_def (ζ : M) (k : ℕ) :
is_primitive_root ζ k ↔ (ζ ^ k = 1) ∧ (∀ l : ℕ, ζ ^ l = 1 → k ∣ l) :=
⟨λ ⟨h1, h2⟩, ⟨h1, h2⟩, λ ⟨h1, h2⟩, ⟨h1, h2⟩⟩
lemma mk_of_lt (ζ : M) (hk : 0 < k) (h1 : ζ ^ k = 1) (h : ∀ l : ℕ, 0 < l → l < k → ζ ^ l ≠ 1) :
is_primitive_root ζ k :=
begin
refine ⟨h1, _⟩,
intros l hl,
apply dvd_trans _ (k.gcd_dvd_right l),
suffices : k.gcd l = k, { rw this },
rw eq_iff_le_not_lt,
refine ⟨nat.le_of_dvd hk (k.gcd_dvd_left l), _⟩,
intro h', apply h _ (nat.gcd_pos_of_pos_left _ hk) h',
exact pow_gcd_eq_one _ h1 hl
end
section comm_monoid
variables {ζ : M} (h : is_primitive_root ζ k)
lemma pow_eq_one_iff_dvd (l : ℕ) : ζ ^ l = 1 ↔ k ∣ l :=
⟨h.dvd_of_pow_eq_one l,
by { rintro ⟨i, rfl⟩, simp only [pow_mul, h.pow_eq_one, one_pow, pnat.mul_coe] }⟩
lemma is_unit (h : is_primitive_root ζ k) (h0 : 0 < k) : is_unit ζ :=
begin
apply is_unit_of_mul_eq_one ζ (ζ ^ (k - 1)),
rw [← pow_succ, nat.sub_add_cancel h0, h.pow_eq_one]
end
lemma pow_ne_one_of_pos_of_lt (h0 : 0 < l) (hl : l < k) : ζ ^ l ≠ 1 :=
mt (nat.le_of_dvd h0 ∘ h.dvd_of_pow_eq_one _) $ not_le_of_lt hl
lemma pow_inj (h : is_primitive_root ζ k) ⦃i j : ℕ⦄ (hi : i < k) (hj : j < k) (H : ζ ^ i = ζ ^ j) :
i = j :=
begin
wlog hij : i ≤ j,
apply le_antisymm hij,
rw ← nat.sub_eq_zero_iff_le,
apply nat.eq_zero_of_dvd_of_lt _ (lt_of_le_of_lt (nat.sub_le_self _ _) hj),
apply h.dvd_of_pow_eq_one,
rw [← ((h.is_unit (lt_of_le_of_lt (nat.zero_le _) hi)).pow i).mul_left_inj,
← pow_add, nat.sub_add_cancel hij, H, one_mul]
end
lemma one : is_primitive_root (1 : M) 1 :=
{ pow_eq_one := pow_one _,
dvd_of_pow_eq_one := λ l hl, one_dvd _ }
@[simp] lemma one_right_iff : is_primitive_root ζ 1 ↔ ζ = 1 :=
begin
split,
{ intro h, rw [← pow_one ζ, h.pow_eq_one] },
{ rintro rfl, exact one }
end
@[simp] lemma coe_units_iff {ζ : units M} :
is_primitive_root (ζ : M) k ↔ is_primitive_root ζ k :=
by simp only [iff_def, units.ext_iff, units.coe_pow, units.coe_one]
lemma pow_of_coprime (h : is_primitive_root ζ k) (i : ℕ) (hi : i.coprime k) :
is_primitive_root (ζ ^ i) k :=
begin
by_cases h0 : k = 0,
{ subst k, simp only [*, pow_one, nat.coprime_zero_right] at * },
rcases h.is_unit (nat.pos_of_ne_zero h0) with ⟨ζ, rfl⟩,
rw [← units.coe_pow],
rw coe_units_iff at h ⊢,
refine
{ pow_eq_one := by rw [← pow_mul', pow_mul, h.pow_eq_one, one_pow],
dvd_of_pow_eq_one := _ },
intros l hl,
apply h.dvd_of_pow_eq_one,
rw [← pow_one ζ, ← gpow_coe_nat ζ, ← hi.gcd_eq_one, nat.gcd_eq_gcd_ab, gpow_add,
mul_pow, ← gpow_coe_nat, ← gpow_mul, mul_right_comm],
simp only [gpow_mul, hl, h.pow_eq_one, one_gpow, one_pow, one_mul, gpow_coe_nat]
end
lemma pow_of_prime (h : is_primitive_root ζ k) {p : ℕ} (hprime : nat.prime p) (hdiv : ¬ p ∣ k) :
is_primitive_root (ζ ^ p) k :=
h.pow_of_coprime p (hprime.coprime_iff_not_dvd.2 hdiv)
lemma pow_iff_coprime (h : is_primitive_root ζ k) (h0 : 0 < k) (i : ℕ) :
is_primitive_root (ζ ^ i) k ↔ i.coprime k :=
begin
refine ⟨_, h.pow_of_coprime i⟩,
intro hi,
obtain ⟨a, ha⟩ := i.gcd_dvd_left k,
obtain ⟨b, hb⟩ := i.gcd_dvd_right k,
suffices : b = k,
{ rwa [this, ← one_mul k, nat.mul_left_inj h0, eq_comm] at hb { occs := occurrences.pos [1] } },
rw [ha] at hi,
rw [mul_comm] at hb,
apply nat.dvd_antisymm ⟨i.gcd k, hb⟩ (hi.dvd_of_pow_eq_one b _),
rw [← pow_mul', ← mul_assoc, ← hb, pow_mul, h.pow_eq_one, one_pow]
end
end comm_monoid
section comm_group
variables {ζ : G} (h : is_primitive_root ζ k)
lemma gpow_eq_one : ζ ^ (k : ℤ) = 1 := h.pow_eq_one
lemma gpow_eq_one_iff_dvd (h : is_primitive_root ζ k) (l : ℤ) :
ζ ^ l = 1 ↔ (k : ℤ) ∣ l :=
begin
by_cases h0 : 0 ≤ l,
{ lift l to ℕ using h0, rw [gpow_coe_nat], norm_cast, exact h.pow_eq_one_iff_dvd l },
{ have : 0 ≤ -l, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 },
lift -l to ℕ using this with l' hl',
rw [← dvd_neg, ← hl'],
norm_cast,
rw [← h.pow_eq_one_iff_dvd, ← inv_inj, ← gpow_neg, ← hl', gpow_coe_nat, one_inv] }
end
lemma inv (h : is_primitive_root ζ k) : is_primitive_root ζ⁻¹ k :=
{ pow_eq_one := by simp only [h.pow_eq_one, one_inv, eq_self_iff_true, inv_pow],
dvd_of_pow_eq_one :=
begin
intros l hl,
apply h.dvd_of_pow_eq_one l,
rw [← inv_inj, ← inv_pow, hl, one_inv]
end }
@[simp] lemma inv_iff : is_primitive_root ζ⁻¹ k ↔ is_primitive_root ζ k :=
by { refine ⟨_, λ h, inv h⟩, intro h, rw [← inv_inv ζ], exact inv h }
lemma gpow_of_gcd_eq_one (h : is_primitive_root ζ k) (i : ℤ) (hi : i.gcd k = 1) :
is_primitive_root (ζ ^ i) k :=
begin
by_cases h0 : 0 ≤ i,
{ lift i to ℕ using h0, exact h.pow_of_coprime i hi },
have : 0 ≤ -i, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 },
lift -i to ℕ using this with i' hi',
rw [← inv_iff, ← gpow_neg, ← hi'],
apply h.pow_of_coprime,
rw [int.gcd, ← int.nat_abs_neg, ← hi'] at hi,
exact hi
end
@[simp] lemma coe_subgroup_iff (H : subgroup G) {ζ : H} :
is_primitive_root (ζ : G) k ↔ is_primitive_root ζ k :=
by simp only [iff_def, ← subgroup.coe_pow, ← H.coe_one, ← subtype.ext_iff]
end comm_group
section comm_group_with_zero
variables {ζ : G₀} (h : is_primitive_root ζ k)
lemma fpow_eq_one : ζ ^ (k : ℤ) = 1 := h.pow_eq_one
lemma fpow_eq_one_iff_dvd (h : is_primitive_root ζ k) (l : ℤ) :
ζ ^ l = 1 ↔ (k : ℤ) ∣ l :=
begin
by_cases h0 : 0 ≤ l,
{ lift l to ℕ using h0, rw [fpow_coe_nat], norm_cast, exact h.pow_eq_one_iff_dvd l },
{ have : 0 ≤ -l, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 },
lift -l to ℕ using this with l' hl',
rw [← dvd_neg, ← hl'],
norm_cast,
rw [← h.pow_eq_one_iff_dvd, ← inv_inj', ← fpow_neg, ← hl', fpow_coe_nat, inv_one] }
end
lemma inv' (h : is_primitive_root ζ k) : is_primitive_root ζ⁻¹ k :=
{ pow_eq_one := by simp only [h.pow_eq_one, inv_one, eq_self_iff_true, inv_pow'],
dvd_of_pow_eq_one :=
begin
intros l hl,
apply h.dvd_of_pow_eq_one l,
rw [← inv_inj', ← inv_pow', hl, inv_one]
end }
@[simp] lemma inv_iff' : is_primitive_root ζ⁻¹ k ↔ is_primitive_root ζ k :=
by { refine ⟨_, λ h, inv' h⟩, intro h, rw [← inv_inv' ζ], exact inv' h }
lemma fpow_of_gcd_eq_one (h : is_primitive_root ζ k) (i : ℤ) (hi : i.gcd k = 1) :
is_primitive_root (ζ ^ i) k :=
begin
by_cases h0 : 0 ≤ i,
{ lift i to ℕ using h0, exact h.pow_of_coprime i hi },
have : 0 ≤ -i, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 },
lift -i to ℕ using this with i' hi',
rw [← inv_iff', ← fpow_neg, ← hi'],
apply h.pow_of_coprime,
rw [int.gcd, ← int.nat_abs_neg, ← hi'] at hi,
exact hi
end
end comm_group_with_zero
section integral_domain
variables {ζ : R}
@[simp] lemma primitive_roots_zero : primitive_roots 0 R = ∅ :=
begin
rw [← finset.val_eq_zero, ← multiset.subset_zero, ← nth_roots_zero (1 : R), primitive_roots],
simp only [finset.not_mem_empty, forall_const, forall_prop_of_false, multiset.to_finset_zero,
finset.filter_true_of_mem, finset.empty_val, not_false_iff,
multiset.zero_subset, nth_roots_zero]
end
@[simp] lemma primitive_roots_one : primitive_roots 1 R = {(1 : R)} :=
begin
apply finset.eq_singleton_iff_unique_mem.2,
split,
{ simp only [is_primitive_root.one_right_iff, mem_primitive_roots zero_lt_one] },
{ intros x hx,
rw [mem_primitive_roots zero_lt_one, is_primitive_root.one_right_iff] at hx,
exact hx }
end
lemma neg_one (p : ℕ) [char_p R p] (hp : p ≠ 2) : is_primitive_root (-1 : R) 2 :=
mk_of_lt (-1 : R) dec_trivial (by simp only [one_pow, neg_square]) $
begin
intros l hl0 hl2,
obtain rfl : l = 1,
{ unfreezingI { clear_dependent R p }, dec_trivial! },
simp only [pow_one, ne.def],
intro h,
suffices h2 : p ∣ 2,
{ have := char_p.char_ne_one R p,
unfreezingI { clear_dependent R },
have aux := nat.le_of_dvd dec_trivial h2,
revert this hp h2, revert p, dec_trivial },
simp only [← char_p.cast_eq_zero_iff R p, nat.cast_bit0, nat.cast_one],
rw [bit0, ← h, neg_add_self] { occs := occurrences.pos [1] }
end
lemma eq_neg_one_of_two_right (h : is_primitive_root ζ 2) : ζ = -1 :=
begin
apply (eq_or_eq_neg_of_pow_two_eq_pow_two ζ 1 _).resolve_left,
{ rw [← pow_one ζ], apply h.pow_ne_one_of_pos_of_lt; dec_trivial },
{ simp only [h.pow_eq_one, one_pow] }
end
end integral_domain
section integral_domain
variables {ζ : units R} (h : is_primitive_root ζ k)
protected
lemma mem_roots_of_unity {n : ℕ+} (h : is_primitive_root ζ n) : ζ ∈ roots_of_unity n R :=
h.pow_eq_one
/-- The (additive) monoid equivalence between `zmod k`
and the powers of a primitive root of unity `ζ`. -/
def zmod_equiv_gpowers (h : is_primitive_root ζ k) : zmod k ≃+ additive (subgroup.gpowers ζ) :=
add_equiv.of_bijective
(add_monoid_hom.lift_of_surjective (int.cast_add_hom _)
zmod.int_cast_surjective
{ to_fun := λ i, additive.of_mul (⟨_, i, rfl⟩ : subgroup.gpowers ζ),
map_zero' := by { simp only [gpow_zero], refl },
map_add' := by { intros i j, simp only [gpow_add], refl } }
(λ i hi,
begin
simp only [add_monoid_hom.mem_ker, char_p.int_cast_eq_zero_iff (zmod k) k,
add_monoid_hom.coe_mk, int.coe_cast_add_hom] at hi ⊢,
obtain ⟨i, rfl⟩ := hi,
simp only [gpow_mul, h.pow_eq_one, one_gpow, gpow_coe_nat],
refl
end)) $
begin
split,
{ rw add_monoid_hom.injective_iff,
intros i hi,
rw subtype.ext_iff at hi,
have := (h.gpow_eq_one_iff_dvd _).mp hi,
rw [← (char_p.int_cast_eq_zero_iff (zmod k) k _).mpr this, eq_comm],
exact classical.some_spec (zmod.int_cast_surjective i) },
{ rintro ⟨ξ, i, rfl⟩,
refine ⟨int.cast_add_hom _ i, _⟩,
rw [add_monoid_hom.lift_of_surjective_comp_apply],
refl }
end
@[simp] lemma zmod_equiv_gpowers_apply_coe_int (i : ℤ) :
h.zmod_equiv_gpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ) :=
begin
apply add_monoid_hom.lift_of_surjective_comp_apply,
intros j hj,
simp only [add_monoid_hom.mem_ker, char_p.int_cast_eq_zero_iff (zmod k) k,
add_monoid_hom.coe_mk, int.coe_cast_add_hom] at hj ⊢,
obtain ⟨j, rfl⟩ := hj,
simp only [gpow_mul, h.pow_eq_one, one_gpow, gpow_coe_nat],
refl
end
@[simp] lemma zmod_equiv_gpowers_apply_coe_nat (i : ℕ) :
h.zmod_equiv_gpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ) :=
begin
have : (i : zmod k) = (i : ℤ), by norm_cast,
simp only [this, zmod_equiv_gpowers_apply_coe_int, gpow_coe_nat],
refl
end
@[simp] lemma zmod_equiv_gpowers_symm_apply_gpow (i : ℤ) :
h.zmod_equiv_gpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ)) = i :=
by rw [← h.zmod_equiv_gpowers.symm_apply_apply i, zmod_equiv_gpowers_apply_coe_int]
@[simp] lemma zmod_equiv_gpowers_symm_apply_gpow' (i : ℤ) :
h.zmod_equiv_gpowers.symm ⟨ζ ^ i, i, rfl⟩ = i :=
h.zmod_equiv_gpowers_symm_apply_gpow i
@[simp] lemma zmod_equiv_gpowers_symm_apply_pow (i : ℕ) :
h.zmod_equiv_gpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ)) = i :=
by rw [← h.zmod_equiv_gpowers.symm_apply_apply i, zmod_equiv_gpowers_apply_coe_nat]
@[simp] lemma zmod_equiv_gpowers_symm_apply_pow' (i : ℕ) :
h.zmod_equiv_gpowers.symm ⟨ζ ^ i, i, rfl⟩ = i :=
h.zmod_equiv_gpowers_symm_apply_pow i
lemma gpowers_eq {k : ℕ+} {ζ : units R} (h : is_primitive_root ζ k) :
subgroup.gpowers ζ = roots_of_unity k R :=
begin
apply subgroup.ext',
haveI : fact (0 < (k : ℕ)) := k.pos,
haveI F : fintype (subgroup.gpowers ζ) := fintype.of_equiv _ (h.zmod_equiv_gpowers).to_equiv,
refine @set.eq_of_subset_of_card_le (units R) (subgroup.gpowers ζ) (roots_of_unity k R)
F (roots_of_unity.fintype R k)
(subgroup.gpowers_subset $ show ζ ∈ roots_of_unity k R, from h.pow_eq_one) _,
calc fintype.card (roots_of_unity k R)
≤ k : card_roots_of_unity R k
... = fintype.card (zmod k) : (zmod.card k).symm
... = fintype.card (subgroup.gpowers ζ) : fintype.card_congr (h.zmod_equiv_gpowers).to_equiv
end
lemma eq_pow_of_mem_roots_of_unity {k : ℕ+} {ζ ξ : units R}
(h : is_primitive_root ζ k) (hξ : ξ ∈ roots_of_unity k R) :
∃ (i : ℕ) (hi : i < k), ζ ^ i = ξ :=
begin
obtain ⟨n, rfl⟩ : ∃ n : ℤ, ζ ^ n = ξ, by rwa [← h.gpowers_eq] at hξ,
have hk0 : (0 : ℤ) < k := by exact_mod_cast k.pos,
let i := n % k,
have hi0 : 0 ≤ i := int.mod_nonneg _ (ne_of_gt hk0),
lift i to ℕ using hi0 with i₀ hi₀,
refine ⟨i₀, _, _⟩,
{ zify, rw [hi₀], exact int.mod_lt_of_pos _ hk0 },
{ have aux := h.gpow_eq_one, rw [← coe_coe] at aux,
rw [← gpow_coe_nat, hi₀, ← int.mod_add_div n k, gpow_add, gpow_mul,
aux, one_gpow, mul_one] }
end
lemma eq_pow_of_pow_eq_one {k : ℕ} {ζ ξ : R}
(h : is_primitive_root ζ k) (hξ : ξ ^ k = 1) (h0 : 0 < k) :
∃ i < k, ζ ^ i = ξ :=
begin
obtain ⟨ζ, rfl⟩ := h.is_unit h0,
obtain ⟨ξ, rfl⟩ := is_unit_of_pow_eq_one ξ k hξ h0,
obtain ⟨k, rfl⟩ : ∃ k' : ℕ+, k = k' := ⟨⟨k, h0⟩, rfl⟩,
simp only [← units.coe_pow, ← units.ext_iff],
rw coe_units_iff at h,
apply h.eq_pow_of_mem_roots_of_unity,
rw [mem_roots_of_unity, units.ext_iff, units.coe_pow, hξ, units.coe_one]
end
lemma is_primitive_root_iff' {k : ℕ+} {ζ ξ : units R} (h : is_primitive_root ζ k) :
is_primitive_root ξ k ↔ ∃ (i < (k : ℕ)) (hi : i.coprime k), ζ ^ i = ξ :=
begin
split,
{ intro hξ,
obtain ⟨i, hik, rfl⟩ := h.eq_pow_of_mem_roots_of_unity hξ.pow_eq_one,
rw h.pow_iff_coprime k.pos at hξ,
exact ⟨i, hik, hξ, rfl⟩ },
{ rintro ⟨i, -, hi, rfl⟩, exact h.pow_of_coprime i hi }
end
lemma is_primitive_root_iff {k : ℕ} {ζ ξ : R} (h : is_primitive_root ζ k) (h0 : 0 < k) :
is_primitive_root ξ k ↔ ∃ (i < k) (hi : i.coprime k), ζ ^ i = ξ :=
begin
split,
{ intro hξ,
obtain ⟨i, hik, rfl⟩ := h.eq_pow_of_pow_eq_one hξ.pow_eq_one h0,
rw h.pow_iff_coprime h0 at hξ,
exact ⟨i, hik, hξ, rfl⟩ },
{ rintro ⟨i, -, hi, rfl⟩, exact h.pow_of_coprime i hi }
end
lemma card_roots_of_unity' {n : ℕ+} (h : is_primitive_root ζ n) :
fintype.card (roots_of_unity n R) = n :=
begin
haveI : fact (0 < ↑n) := n.pos,
let e := h.zmod_equiv_gpowers,
haveI F : fintype (subgroup.gpowers ζ) := fintype.of_equiv _ e.to_equiv,
calc fintype.card (roots_of_unity n R)
= fintype.card (subgroup.gpowers ζ) : fintype.card_congr $ by rw h.gpowers_eq
... = fintype.card (zmod n) : fintype.card_congr e.to_equiv.symm
... = n : zmod.card n
end
lemma card_roots_of_unity {ζ : R} {n : ℕ+} (h : is_primitive_root ζ n) :
fintype.card (roots_of_unity n R) = n :=
begin
obtain ⟨ζ, hζ⟩ := h.is_unit n.pos,
rw [← hζ, is_primitive_root.coe_units_iff] at h,
exact h.card_roots_of_unity'
end
/-- The cardinality of the multiset `nth_roots ↑n (1 : R)` is `n`
if there is a primitive root of unity in `R`. -/
lemma card_nth_roots {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) :
(nth_roots n (1 : R)).card = n :=
begin
cases nat.eq_zero_or_pos n with hzero hpos,
{ simp only [hzero, multiset.card_zero, nth_roots_zero] },
rw eq_iff_le_not_lt,
use card_nth_roots n 1,
{ rw [not_lt],
have hcard : fintype.card {x // x ∈ nth_roots n (1 : R)}
≤ (nth_roots n (1 : R)).attach.card := multiset.card_le_of_le (multiset.erase_dup_le _),
rw multiset.card_attach at hcard,
rw ← pnat.to_pnat'_coe hpos at hcard h ⊢,
set m := nat.to_pnat' n,
rw [← fintype.card_congr (roots_of_unity_equiv_nth_roots R m), card_roots_of_unity h] at hcard,
exact hcard }
end
/-- The multiset `nth_roots ↑n (1 : R)` has no repeated elements
if there is a primitive root of unity in `R`. -/
lemma nth_roots_nodup {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots n (1 : R)).nodup :=
begin
cases nat.eq_zero_or_pos n with hzero hpos,
{ simp only [hzero, multiset.nodup_zero, nth_roots_zero] },
apply (@multiset.erase_dup_eq_self R _ _).1,
rw eq_iff_le_not_lt,
split,
{ exact multiset.erase_dup_le (nth_roots n (1 : R)) },
{ by_contra ha,
replace ha := multiset.card_lt_of_lt ha,
rw card_nth_roots h at ha,
have hrw : (nth_roots n (1 : R)).erase_dup.card =
fintype.card {x // x ∈ (nth_roots n (1 : R))},
{ set fs := (⟨(nth_roots n (1 : R)).erase_dup, multiset.nodup_erase_dup _⟩ : finset R),
rw [← finset.card_mk, ← fintype.card_of_subtype fs _],
intro x,
simp only [multiset.mem_erase_dup, finset.mem_mk] },
rw ← pnat.to_pnat'_coe hpos at h hrw ha,
set m := nat.to_pnat' n,
rw [hrw, ← fintype.card_congr (roots_of_unity_equiv_nth_roots R m),
card_roots_of_unity h] at ha,
exact nat.lt_asymm ha ha }
end
@[simp] lemma card_nth_roots_finset {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) :
(nth_roots_finset n R).card = n :=
by rw [nth_roots_finset, ← multiset.to_finset_eq (nth_roots_nodup h), card_mk, h.card_nth_roots]
open_locale nat
/-- If an integral domain has a primitive `k`-th root of unity, then it has `φ k` of them. -/
lemma card_primitive_roots {ζ : R} {k : ℕ} (h : is_primitive_root ζ k) (h0 : 0 < k) :
(primitive_roots k R).card = φ k :=
begin
symmetry,
refine finset.card_congr (λ i _, ζ ^ i) _ _ _,
{ simp only [true_and, and_imp, mem_filter, mem_range, mem_univ],
rintro i - hi,
rw mem_primitive_roots h0,
exact h.pow_of_coprime i hi.symm },
{ simp only [true_and, and_imp, mem_filter, mem_range, mem_univ],
rintro i j hi - hj - H,
exact h.pow_inj hi hj H },
{ simp only [exists_prop, true_and, mem_filter, mem_range, mem_univ],
intros ξ hξ,
rw [mem_primitive_roots h0, h.is_primitive_root_iff h0] at hξ,
rcases hξ with ⟨i, hin, hi, H⟩,
exact ⟨i, ⟨hin, hi.symm⟩, H⟩ }
end
/-- The sets `primitive_roots k R` are pairwise disjoint. -/
lemma disjoint {k l : ℕ} (hk : 0 < k) (hl : 0 < l) (h : k ≠ l) :
disjoint (primitive_roots k R) (primitive_roots l R) :=
begin
intro z,
simp only [finset.inf_eq_inter, finset.mem_inter, mem_primitive_roots, hk, hl, iff_def],
rintro ⟨⟨hzk, Hzk⟩, ⟨hzl, Hzl⟩⟩,
apply_rules [h, nat.dvd_antisymm, Hzk, Hzl, hzk, hzl]
end
/-- If there is a `n`-th primitive root of unity in `R` and `b` divides `n`,
then there is a `b`-th primitive root of unity in `R`. -/
lemma pow {ζ : R} {n : ℕ} {a b : ℕ}
(hn : 0 < n) (h : is_primitive_root ζ n) (hprod : n = a * b) :
is_primitive_root (ζ ^ a) b :=
begin
subst n,
simp only [iff_def, ← pow_mul, h.pow_eq_one, eq_self_iff_true, true_and],
intros l hl,
have ha0 : a ≠ 0, { rintro rfl, simpa only [nat.not_lt_zero, zero_mul] using hn },
rwa ← mul_dvd_mul_iff_left ha0,
exact h.dvd_of_pow_eq_one _ hl
end
/-- `nth_roots n` as a `finset` is equal to the union of `primitive_roots i R` for `i ∣ n`
if there is a primitive root of unity in `R`. -/
lemma nth_roots_one_eq_bind_primitive_roots' {ζ : R} {n : ℕ+} (h : is_primitive_root ζ n) :
nth_roots_finset n R = (nat.divisors ↑n).bind (λ i, (primitive_roots i R)) :=
begin
symmetry,
apply finset.eq_of_subset_of_card_le,
{ intros x,
simp only [nth_roots_finset, ← multiset.to_finset_eq (nth_roots_nodup h),
exists_prop, finset.mem_bind, finset.mem_filter, finset.mem_range, mem_nth_roots,
finset.mem_mk, nat.mem_divisors, and_true, ne.def, pnat.ne_zero, pnat.pos, not_false_iff],
rintro ⟨a, ⟨d, hd⟩, ha⟩,
have hazero : 0 < a,
{ contrapose! hd with ha0,
simp only [nonpos_iff_eq_zero, zero_mul, *] at *,
exact n.ne_zero },
rw mem_primitive_roots hazero at ha,
rw [hd, pow_mul, ha.pow_eq_one, one_pow] },
{ apply le_of_eq,
rw [h.card_nth_roots_finset, finset.card_bind],
{ rw [← nat.sum_totient n, nat.filter_dvd_eq_divisors (pnat.ne_zero n), sum_congr rfl]
{ occs := occurrences.pos [1] },
simp only [finset.mem_filter, finset.mem_range, nat.mem_divisors],
rintro k ⟨H, hk⟩,
have hdvd := H,
rcases H with ⟨d, hd⟩,
rw mul_comm at hd,
rw (h.pow n.pos hd).card_primitive_roots (pnat.pos_of_div_pos hdvd) },
{ intros i hi j hj hdiff,
simp only [nat.mem_divisors, and_true, ne.def, pnat.ne_zero, not_false_iff] at hi hj,
exact disjoint (pnat.pos_of_div_pos hi) (pnat.pos_of_div_pos hj) hdiff } }
end
/-- `nth_roots n` as a `finset` is equal to the union of `primitive_roots i R` for `i ∣ n`
if there is a primitive root of unity in `R`. -/
lemma nth_roots_one_eq_bind_primitive_roots {ζ : R} {n : ℕ} (hpos : 0 < n)
(h : is_primitive_root ζ n) :
nth_roots_finset n R = (nat.divisors n).bind (λ i, (primitive_roots i R)) :=
@nth_roots_one_eq_bind_primitive_roots' _ _ _ ⟨n, hpos⟩ h
end integral_domain
section minpoly
open minpoly
variables {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n)
include n μ h hpos
/--`μ` is integral over `ℤ`. -/
lemma is_integral : is_integral ℤ μ :=
begin
use (X ^ n - 1),
split,
{ exact (monic_X_pow_sub_C 1 (ne_of_lt hpos).symm) },
{ simp only [((is_primitive_root.iff_def μ n).mp h).left, eval₂_one, eval₂_X_pow, eval₂_sub,
sub_self] }
end
variables [char_zero K]
/--The minimal polynomial of a root of unity `μ` divides `X ^ n - 1`. -/
lemma minpoly_dvd_X_pow_sub_one :
minpoly (is_integral h hpos) ∣ X ^ n - 1 :=
begin
apply integer_dvd (is_integral h hpos) (polynomial.monic.is_primitive
(monic_X_pow_sub_C 1 (ne_of_lt hpos).symm)),
simp only [((is_primitive_root.iff_def μ n).mp h).left, aeval_X_pow, ring_hom.eq_int_cast,
int.cast_one, aeval_one, alg_hom.map_sub, sub_self]
end
/-- The reduction modulo `p` of the minimal polynomial of a root of unity `μ` is separable. -/
lemma separable_minpoly_mod {p : ℕ} [fact p.prime] (hdiv : ¬p ∣ n) :
separable (map (int.cast_ring_hom (zmod p)) (minpoly (is_integral h hpos))) :=
begin
have hdvd : (map (int.cast_ring_hom (zmod p))
(minpoly (is_integral h hpos))) ∣ X ^ n - 1,
{ simpa [map_pow, map_X, map_one, ring_hom.coe_of, map_sub] using
ring_hom.map_dvd (ring_hom.of (map (int.cast_ring_hom (zmod p))))
(minpoly_dvd_X_pow_sub_one h hpos) },
refine separable.of_dvd (separable_X_pow_sub_C 1 _ one_ne_zero) hdvd,
by_contra hzero,
exact hdiv ((zmod.nat_coe_zmod_eq_zero_iff_dvd n p).1 (not_not.1 hzero))
end
/-- The reduction modulo `p` of the minimal polynomial of a root of unity `μ` is squarefree. -/
lemma squarefree_minpoly_mod {p : ℕ} [fact p.prime] (hdiv : ¬ p ∣ n) :
squarefree (map (int.cast_ring_hom (zmod p)) (minpoly (is_integral h hpos))) :=
(separable_minpoly_mod h hpos hdiv).squarefree
/- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of
`μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `expand ℤ p Q`. -/
lemma minpoly_dvd_expand {p : ℕ} (hprime : nat.prime p) (hdiv : ¬ p ∣ n) :
minpoly (is_integral h hpos) ∣
expand ℤ p (minpoly (is_integral (pow_of_prime h hprime hdiv) hpos)) :=
begin
apply minpoly.integer_dvd,
{ apply monic.is_primitive,
rw [polynomial.monic, leading_coeff, nat_degree_expand, mul_comm, coeff_expand_mul'
(nat.prime.pos hprime), ← leading_coeff, ← polynomial.monic],
exact minpoly.monic (is_integral (pow_of_prime h hprime hdiv) hpos) },
{ rw [aeval_def, coe_expand, ← comp, eval₂_eq_eval_map, map_comp, map_pow, map_X, eval_comp,
eval_pow, eval_X, ← eval₂_eq_eval_map, ← aeval_def],
exact minpoly.aeval (is_integral (pow_of_prime h hprime hdiv) hpos) }
end
/- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of
`μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `Q ^ p` modulo `p`. -/
lemma minpoly_dvd_pow_mod {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) :
map (int.cast_ring_hom (zmod p)) (minpoly (is_integral h hpos)) ∣
map (int.cast_ring_hom (zmod p)) (minpoly (is_integral
(pow_of_prime h hprime hdiv) hpos)) ^ p :=
begin
set Q := minpoly (is_integral (pow_of_prime h hprime hdiv) hpos),
have hfrob : map (int.cast_ring_hom (zmod p)) Q ^ p =
map (int.cast_ring_hom (zmod p)) (expand ℤ p Q),
by rw [← zmod.expand_card, map_expand (nat.prime.pos hprime)],
rw [hfrob],
apply ring_hom.map_dvd (ring_hom.of (map (int.cast_ring_hom (zmod p)))),
exact minpoly_dvd_expand h hpos hprime hdiv
end
/- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of
`μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `Q` modulo `p`. -/
lemma minpoly_dvd_mod_p {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) :
map (int.cast_ring_hom (zmod p)) (minpoly (is_integral h hpos)) ∣
map (int.cast_ring_hom (zmod p)) (minpoly (is_integral
(pow_of_prime h hprime hdiv) hpos)) :=
(unique_factorization_monoid.dvd_pow_iff_dvd_of_squarefree (squarefree_minpoly_mod h
hpos hdiv) (nat.prime.ne_zero hprime)).1 (minpoly_dvd_pow_mod h hpos hdiv)
/-- If `p` is a prime that does not divide `n`,
then the minimal polynomials of a primitive `n`-th root of unity `μ`
and of `μ ^ p` are the same. -/
lemma minpoly_eq_pow {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) :
minpoly (is_integral h hpos) =
minpoly (is_integral (pow_of_prime h hprime hdiv) hpos) :=
begin
by_contra hdiff,
set P := minpoly (is_integral h hpos),
set Q := minpoly (is_integral (pow_of_prime h hprime hdiv) hpos),
have Pmonic : P.monic := minpoly.monic _,
have Qmonic : Q.monic := minpoly.monic _,
have Pirr : irreducible P := minpoly.irreducible _,
have Qirr : irreducible Q := minpoly.irreducible _,
have PQprim : is_primitive (P * Q) := Pmonic.is_primitive.mul Qmonic.is_primitive,
have prod : P * Q ∣ X ^ n - 1,
{ apply (is_primitive.int.dvd_iff_map_cast_dvd_map_cast (P * Q) (X ^ n - 1) PQprim
((monic_X_pow_sub_C 1 (ne_of_lt hpos).symm).is_primitive)).2,
rw [map_mul],
refine is_coprime.mul_dvd _ _ _,
{ have aux := is_primitive.int.irreducible_iff_irreducible_map_cast Pmonic.is_primitive,
refine (dvd_or_coprime _ _ (aux.1 Pirr)).resolve_left _,
rw map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Pmonic,
intro hdiv,
refine hdiff (eq_of_monic_of_associated Pmonic Qmonic _),
exact associated_of_dvd_dvd hdiv (dvd_symm_of_irreducible Pirr Qirr hdiv) },
{ apply (map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Pmonic).2,
exact minpoly_dvd_X_pow_sub_one h hpos },
{ apply (map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Qmonic).2,
exact minpoly_dvd_X_pow_sub_one (pow_of_prime h hprime hdiv) hpos } },
replace prod := ring_hom.map_dvd (ring_hom.of (map (int.cast_ring_hom (zmod p)))) prod,
rw [ring_hom.coe_of, map_mul, map_sub, map_one, map_pow, map_X] at prod,
obtain ⟨R, hR⟩ := minpoly_dvd_mod_p h hpos hdiv,
rw [hR, ← mul_assoc, ← map_mul, ← pow_two, map_pow] at prod,
have habs : map (int.cast_ring_hom (zmod p)) P ^ 2 ∣ map (int.cast_ring_hom (zmod p)) P ^ 2 * R,
{ use R },
replace habs := lt_of_lt_of_le (enat.coe_lt_coe.2 one_lt_two)
(multiplicity.le_multiplicity_of_pow_dvd (dvd_trans habs prod)),
have hfree : squarefree (X ^ n - 1 : polynomial (zmod p)),
{ refine squarefree_X_pow_sub_C 1 _ one_ne_zero,
by_contra hzero,
exact hdiv ((zmod.nat_coe_zmod_eq_zero_iff_dvd n p).1 (not_not.1 hzero)) },
cases (multiplicity.squarefree_iff_multiplicity_le_one (X ^ n - 1)).1 hfree
(map (int.cast_ring_hom (zmod p)) P) with hle hunit,
{ exact not_lt_of_le hle habs },
{ replace hunit := degree_eq_zero_of_is_unit hunit,
rw degree_map_eq_of_leading_coeff_ne_zero _ _ at hunit,
{ exact (ne_of_lt (minpoly.degree_pos (is_integral h hpos))).symm hunit },
simp only [Pmonic, ring_hom.eq_int_cast, monic.leading_coeff, int.cast_one, ne.def,
not_false_iff, one_ne_zero] }
end
/-- If `m : ℕ` is coprime with `n`,
then the minimal polynomials of a primitive `n`-th root of unity `μ`
and of `μ ^ m` are the same. -/
lemma minpoly_eq_pow_coprime {m : ℕ} (hcop : nat.coprime m n) :
minpoly (is_integral h hpos) = minpoly
(is_integral (h.pow_of_coprime m hcop) hpos) :=
begin
revert n hcop,
refine unique_factorization_monoid.induction_on_prime m _ _ _,
{ intros n hn h hpos,
congr,
simpa [(nat.coprime_zero_left n).mp hn] using h },
{ intros u hunit n hcop h hpos,
congr,
simp [nat.is_unit_iff.mp hunit] },
{ intros a p ha hprime hind n hcop h hpos,
rw hind (nat.coprime.coprime_mul_left hcop) h hpos, clear hind,
replace hprime := nat.prime_iff_prime.2 hprime,
have hdiv := (nat.prime.coprime_iff_not_dvd hprime).1 (nat.coprime.coprime_mul_right hcop),
letI : fact p.prime := hprime,
rw [minpoly_eq_pow
(h.pow_of_coprime a (nat.coprime.coprime_mul_left hcop)) hpos hdiv],
congr' 1,
ring_exp }
end
/-- If `m : ℕ` is coprime with `n`,
then the minimal polynomial of a primitive `n`-th root of unity `μ`
has `μ ^ m` as root. -/
lemma pow_is_root_minpoly {m : ℕ} (hcop : nat.coprime m n) :
is_root (map (int.cast_ring_hom K) (minpoly (is_integral h hpos))) (μ ^ m) :=
by simpa [minpoly_eq_pow_coprime h hpos hcop, eval_map, aeval_def (μ ^ m) _]
using minpoly.aeval (is_integral (h.pow_of_coprime m hcop) hpos)
/-- `primitive_roots n K` is a subset of the roots of the minimal polynomial of a primitive
`n`-th root of unity `μ`. -/
lemma is_roots_of_minpoly : primitive_roots n K ⊆ (map (int.cast_ring_hom K)
(minpoly (is_integral h hpos))).roots.to_finset :=
begin
intros x hx,
obtain ⟨m, hle, hcop, rfl⟩ := (is_primitive_root_iff h hpos).1 ((mem_primitive_roots hpos).1 hx),
simpa [multiset.mem_to_finset,
mem_roots (map_monic_ne_zero $ minpoly.monic $ is_integral h hpos)]
using pow_is_root_minpoly h hpos hcop
end
/-- The degree of the minimal polynomial of `μ` is at least `totient n`. -/
lemma totient_le_degree_minpoly : nat.totient n ≤ (minpoly
(is_integral h hpos)).nat_degree :=
let P : polynomial ℤ := minpoly (is_integral h hpos),-- minimal polynomial of `μ`
P_K : polynomial K := map (int.cast_ring_hom K) P -- minimal polynomial of `μ` sent to `K[X]`
in calc
n.totient = (primitive_roots n K).card : (h.card_primitive_roots hpos).symm
... ≤ P_K.roots.to_finset.card : finset.card_le_of_subset (is_roots_of_minpoly h hpos)
... ≤ P_K.roots.card : multiset.to_finset_card_le _
... ≤ P_K.nat_degree : (card_roots' $ map_monic_ne_zero
(minpoly.monic $ is_integral h hpos))
... ≤ P.nat_degree : nat_degree_map_le _
end minpoly
end is_primitive_root
|
2b5138a826051332a51e1301f07b7a864f929233 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /test/json.lean | b0e2ae251b6eabb9bee83c909b8c1984a5631287 | [
"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 | 2,842 | lean | import data.json
import data.int.basic
run_cmd do
let j := json.of_int 2,
z ← of_json native.float j,
guard (z = 2)
run_cmd do
j ← json.parse "2.0",
tactic.success_if_fail_with_msg (of_json ℤ j) "number must be integral"
run_cmd do
let j := json.of_int (-1),
tactic.success_if_fail_with_msg (of_json ℕ j) "must be non-negative"
run_cmd do
let j := json.of_int 1,
v ← of_json {x // x ≠ some 2} j,
guard (v = ⟨some 1, dec_trivial⟩),
v ← of_json (option {x // x ≠ 2}) j,
guard (v = some ⟨1, dec_trivial⟩)
run_cmd do
let j := json.null,
v ← of_json {x // x ≠ some 2} j,
guard (v = ⟨none, dec_trivial⟩),
v ← of_json (option {x // x ≠ 2}) j,
guard (v = none)
@[derive [decidable_eq, non_null_json_serializable]]
structure my_type (yval : bool) :=
(x : nat)
(f : fin x)
(y : bool)
(h : y = yval)
run_cmd do
let actual := to_json (my_type.mk 37 2 tt rfl),
let expected := json.object [("x", json.of_int 37), ("f", json.of_int 2), ("y", json.of_bool tt)],
guard (actual = expected)
run_cmd do
some j ← pure (json.parse "{\"x\":37,\"f\":2,\"y\":true}"),
x ← of_json (my_type tt) j,
guard (x = ⟨37, 2, tt, rfl⟩)
run_cmd do
some j ← pure (json.parse "{\"x\":37,\"f\":2,\"y\":true,\"z\":true}"),
tactic.success_if_fail_with_msg (of_json (my_type tt) j) "unexpected fields [z]"
run_cmd do
some j ← pure (json.parse "{\"x\":37}"),
tactic.success_if_fail_with_msg (of_json (my_type tt) j) "field f is required"
run_cmd do
let j := json.object [("x", to_json 37), ("x", to_json 37)],
tactic.success_if_fail_with_msg (of_json (my_type tt) j) "duplicate x field"
run_cmd do
let j := json.null,
tactic.success_if_fail_with_msg (of_json (my_type tt) j) "object expected, got null"
run_cmd do
some j ← pure (json.parse "{\"x\":37,\"f\":2,\"y\":false}"),
tactic.success_if_fail_with_msg (of_json (my_type tt) j) "condition does not hold"
@[derive [decidable_eq, non_null_json_serializable]]
structure no_fields (n : ℕ) : Type
run_cmd do
let actual := to_json (@no_fields.mk 37),
let expected := json.object [],
guard (actual = expected)
run_cmd do
some j ← pure (json.parse "{}"),
of_json (@no_fields 37) j
@[derive [decidable_eq, non_null_json_serializable]]
structure has_default : Type :=
(x : ℕ := 2)
(y : fin x.succ := 3 * fin.of_nat x)
(z : ℕ := 3)
run_cmd do
e ← of_json has_default (json.object []),
guard (e = {})
run_cmd do
let actual := to_json (has_default.mk 2 1 3),
let expected := json.object [("x", json.of_int 2), ("y", json.of_int 1), ("z", json.of_int 3)],
guard (actual = expected)
run_cmd do
some j ← pure (json.parse "{\"x\":1,\"z\":3}"),
of_json has_default j
run_cmd do
some j ← pure (json.parse "{\"y\":2}"),
v ← of_json has_default j,
guard (v = {y := 2})
|
16b5f8d2f5e51d95dc616a4dda935711b3c28a53 | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /tests/lean/slow/nat_bug2.lean | 3865ee2e8604eb7d27e9e80f1a4ae8ff840de9fe | [
"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 | 49,310 | 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
----------------------------------------------------------------------------------------------------
import logic algebra.binary
open tactic binary eq.ops eq
open decidable
namespace experiment
definition refl := @eq.refl
definition and_intro := @and.intro
definition or_intro_left := @or.intro_left
definition or_intro_right := @or.intro_right
inductive nat : Type :=
zero : nat,
succ : nat → nat
namespace nat
notation `ℕ`:max := nat
definition plus (x y : ℕ) : ℕ
:= nat.rec x (λ n r, succ r) y
definition to_nat [coercion] (n : num) : ℕ
:= num.rec zero (λ n, pos_num.rec (succ zero) (λ n r, plus r (plus r (succ zero))) (λ n r, plus r r) n) n
namespace helper_tactics
definition apply_refl := apply @refl
tactic_hint apply_refl
end helper_tactics
open helper_tactics
theorem nat_rec_zero {P : ℕ → Type} (x : P 0) (f : ∀m, P m → P (succ m)) : nat.rec x f 0 = x
theorem nat_rec_succ {P : ℕ → Type} (x : P 0) (f : ∀m, P m → P (succ m)) (n : ℕ) : nat.rec x f (succ n) = f n (nat.rec x f n)
-------------------------------------------------- succ pred
theorem succ_ne_zero (n : ℕ) : succ n ≠ 0
:= assume H : succ n = 0,
have H2 : true = false, from
let f := (nat.rec false (fun a b, true)) in
calc true = f (succ n) : _
... = f 0 : {H}
... = false : _,
absurd H2 true_ne_false
definition pred (n : ℕ) := nat.rec 0 (fun m x, m) n
theorem pred_zero : pred 0 = 0
theorem pred_succ (n : ℕ) : pred (succ n) = n
theorem zero_or_succ (n : ℕ) : n = 0 ∨ n = succ (pred n)
:= induction_on n
(or.intro_left _ (refl 0))
(take m IH, or.intro_right _
(show succ m = succ (pred (succ m)), from congr_arg succ ((pred_succ m)⁻¹)))
theorem zero_or_succ2 (n : ℕ) : n = 0 ∨ ∃k, n = succ k
:= or_of_or_of_imp_of_imp (zero_or_succ n) (assume H, H) (assume H : n = succ (pred n), exists.intro (pred n) H)
theorem case {P : ℕ → Prop} (n : ℕ) (H1: P 0) (H2 : ∀m, P (succ m)) : P n
:= induction_on n H1 (take m IH, H2 m)
theorem discriminate {B : Prop} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B
:= or.elim (zero_or_succ n)
(take H3 : n = 0, H1 H3)
(take H3 : n = succ (pred n), H2 (pred n) H3)
theorem succ_inj {n m : ℕ} (H : succ n = succ m) : n = m
:= calc
n = pred (succ n) : (pred_succ n)⁻¹
... = pred (succ m) : {H}
... = m : pred_succ m
theorem succ_ne_self (n : ℕ) : succ n ≠ n
:= induction_on n
(take H : 1 = 0,
have ne : 1 ≠ 0, from succ_ne_zero 0,
absurd H ne)
(take k IH H, IH (succ_inj H))
theorem decidable_eq [instance] (n m : ℕ) : decidable (n = m)
:= have general : ∀n, decidable (n = m), from
rec_on m
(take n,
rec_on n
(inl (refl 0))
(λ m iH, inr (succ_ne_zero m)))
(λ (m' : ℕ) (iH1 : ∀n, decidable (n = m')),
take n, rec_on n
(inr (ne.symm (succ_ne_zero m')))
(λ (n' : ℕ) (iH2 : decidable (n' = succ m')),
have d1 : decidable (n' = m'), from iH1 n',
decidable.rec_on d1
(assume Heq : n' = m', inl (congr_arg succ Heq))
(assume Hne : n' ≠ m',
have H1 : succ n' ≠ succ m', from
assume Heq, absurd (succ_inj Heq) Hne,
inr H1))),
general n
theorem two_step_induction_on {P : ℕ → Prop} (a : ℕ) (H1 : P 0) (H2 : P 1)
(H3 : ∀ (n : ℕ) (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 sub_induction {P : ℕ → ℕ → Prop} (n m : ℕ) (H1 : ∀m, P 0 m)
(H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : P n m
:= have general : ∀m, P n m, from induction_on n
(take m : ℕ, H1 m)
(take k : ℕ,
assume IH : ∀m, P k m,
take m : ℕ,
discriminate
(assume Hm : m = 0,
Hm⁻¹ ▸ (H2 k))
(take l : ℕ,
assume Hm : m = succ l,
Hm⁻¹ ▸ (H3 k l (IH l)))),
general m
-------------------------------------------------- add
definition add (x y : ℕ) : ℕ := plus x y
infixl `+` := add
theorem add_zero (n : ℕ) : n + 0 = n
theorem add_succ (n m : ℕ) : n + succ m = succ (n + m)
---------- comm, assoc
theorem zero_add (n : ℕ) : 0 + n = n
:= induction_on n
(add_zero 0)
(take m IH, show 0 + succ m = succ m, from
calc
0 + succ m = succ (0 + m) : add_succ _ _
... = succ m : {IH})
theorem succ_add (n m : ℕ) : (succ n) + m = succ (n + m)
:= induction_on m
(calc
succ n + 0 = succ n : add_zero (succ n)
... = succ (n + 0) : {symm (add_zero n)})
(take k IH,
calc
succ n + succ k = succ (succ n + k) : add_succ _ _
... = succ (succ (n + k)) : {IH}
... = succ (n + succ k) : {symm (add_succ _ _)})
theorem add_comm (n m : ℕ) : n + m = m + n
:= induction_on m
(trans (add_zero _) (symm (zero_add _)))
(take k IH,
calc
n + succ k = succ (n+k) : add_succ _ _
... = succ (k + n) : {IH}
... = succ k + n : symm (succ_add _ _))
theorem succ_add_eq_add_succ (n m : ℕ) : succ n + m = n + succ m
:= calc
succ n + m = succ (n + m) : succ_add n m
... = n +succ m : symm (add_succ n m)
theorem add_comm_succ (n m : ℕ) : n + succ m = m + succ n
:= calc
n + succ m = succ n + m : symm (succ_add_eq_add_succ n m)
... = m + succ n : add_comm (succ n) m
theorem add_assoc (n m k : ℕ) : (n + m) + k = n + (m + k)
:= induction_on k
(calc
(n + m) + 0 = n + m : add_zero _
... = n + (m + 0) : {symm (add_zero m)})
(take l IH,
calc
(n + m) + succ l = succ ((n + m) + l) : add_succ _ _
... = succ (n + (m + l)) : {IH}
... = n + succ (m + l) : symm (add_succ _ _)
... = n + (m + succ l) : {symm (add_succ _ _)})
theorem add_left_comm (n m k : ℕ) : n + (m + k) = m + (n + k)
:= left_comm add_comm add_assoc n m k
theorem add_right_comm (n m k : ℕ) : n + m + k = n + k + m
:= right_comm add_comm add_assoc n m k
---------- inversion
theorem add_cancel_left {n m k : ℕ} : n + m = n + k → m = k
:=
induction_on n
(take H : 0 + m = 0 + k,
calc
m = 0 + m : symm (zero_add m)
... = 0 + k : H
... = k : zero_add k)
(take (n : ℕ) (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 (succ_add n m)
... = succ n + k : H
... = succ (n + k) : succ_add n k,
have H3 : n + m = n + k, from succ_inj H2,
IH H3)
--rename to and_cancel_right
theorem add_cancel_right {n m k : ℕ} (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_cancel_left H2
theorem eq_zero_of_add_eq_zero_right {n m : ℕ} : n + m = 0 → n = 0
:=
induction_on n
(take (H : 0 + m = 0), refl 0)
(take k IH,
assume (H : succ k + m = 0),
absurd
(show succ (k + m) = 0, from
calc
succ (k + m) = succ k + m : symm (succ_add k m)
... = 0 : H)
(succ_ne_zero (k + m)))
theorem add_eq_zero_right {n m : ℕ} (H : n + m = 0) : m = 0
:= eq_zero_of_add_eq_zero_right (trans (add_comm m n) H)
theorem add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0
:= and_intro (eq_zero_of_add_eq_zero_right H) (add_eq_zero_right H)
-- add_eq_self below
---------- misc
theorem add_one (n:ℕ) : n + 1 = succ n
:=
calc
n + 1 = succ (n + 0) : add_succ _ _
... = succ n : {add_zero _}
theorem add_one_left (n:ℕ) : 1 + n = succ n
:=
calc
1 + n = succ (0 + n) : succ_add _ _
... = succ n : {zero_add _}
--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 : ℕ → Prop} (a : ℕ) (H1 : P 0)
(H2 : ∀ (n : ℕ) (IH : P n), P (n + 1)) : P a
:= nat.rec H1 (take n IH, (add_one n) ▸ (H2 n IH)) a
-------------------------------------------------- mul
definition mul (n m : ℕ) := nat.rec 0 (fun m x, x + n) m
infixl `*` := mul
theorem mul_zero_right (n:ℕ) : n * 0 = 0
theorem mul_succ_right (n m:ℕ) : n * succ m = n * m + n
set_option unifier.max_steps 100000
---------- comm, distr, assoc, identity
theorem mul_zero_left (n:ℕ) : 0 * n = 0
:= induction_on n
(mul_zero_right 0)
(take m IH,
calc
0 * succ m = 0 * m + 0 : mul_succ_right _ _
... = 0 * m : add_zero _
... = 0 : IH)
theorem mul_succ_left (n m:ℕ) : (succ n) * m = (n * m) + m
:= induction_on m
(calc
succ n * 0 = 0 : mul_zero_right _
... = n * 0 : symm (mul_zero_right _)
... = n * 0 + 0 : symm (add_zero _))
(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) + (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:ℕ) : 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 : ℕ) : (n + m) * k = n * k + m * k
:= induction_on k
(calc
(n + m) * 0 = 0 : mul_zero_right _
... = 0 + 0 : symm (add_zero _)
... = n * 0 + 0 : refl _
... = n * 0 + m * 0 : refl _)
(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_right_comm _ _ _}
... = 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 : ℕ) : 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:ℕ) : (n * m) * k = n * (m * k)
:= induction_on k
(calc
(n * m) * 0 = 0 : mul_zero_right _
... = n * 0 : symm (mul_zero_right _)
... = n * (m * 0) : {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 : ℕ) : n * (m * k) = m * (n * k)
:= left_comm mul_comm mul_assoc n m k
theorem mul_comm_right (n m k : ℕ) : n * m * k = n * k * m
:= right_comm mul_comm mul_assoc n m k
theorem mul_one_right (n : ℕ) : n * 1 = n
:= calc
n * 1 = n * 0 + n : mul_succ_right n 0
... = 0 + n : {mul_zero_right n}
... = n : zero_add n
theorem mul_one_left (n : ℕ) : 1 * n = n
:= calc
1 * n = n * 1 : mul_comm _ _
... = n : mul_one_right n
---------- inversion
theorem mul_eq_zero {n m : ℕ} (H : n * m = 0) : n = 0 ∨ m = 0
:=
discriminate
(take Hn : n = 0, or_intro_left _ Hn)
(take (k : ℕ),
assume (Hk : n = succ k),
discriminate
(take (Hm : m = 0), or_intro_right _ Hm)
(take (l : ℕ),
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 _ _),
absurd (trans Heq H) (succ_ne_zero _)))
-- see more under "positivity" below
-------------------------------------------------- le
definition le (n m:ℕ) : Prop := ∃k, n + k = m
infix `<=` := le
infix `≤` := le
theorem le_intro {n m k : ℕ} (H : n + k = m) : n ≤ m
:= exists.intro k H
theorem le_elim {n m : ℕ} (H : n ≤ m) : ∃ k, n + k = m
:= H
---------- partial order (totality is part of lt)
theorem le_intro2 (n m : ℕ) : n ≤ n + m
:= le_intro (refl (n + m))
theorem le_refl (n : ℕ) : n ≤ n
:= le_intro (add_zero n)
theorem zero_le (n : ℕ) : 0 ≤ n
:= le_intro (zero_add n)
theorem le_zero {n : ℕ} (H : n ≤ 0) : n = 0
:=
obtain (k : ℕ) (Hk : n + k = 0), from le_elim H,
eq_zero_of_add_eq_zero_right Hk
theorem not_succ_zero_le (n : ℕ) : ¬ succ n ≤ 0
:= assume H : succ n ≤ 0,
have H2 : succ n = 0, from le_zero H,
absurd H2 (succ_ne_zero n)
theorem le_zero_inv {n : ℕ} (H : n ≤ 0) : n = 0
:= obtain (k : ℕ) (Hk : n + k = 0), from le_elim H,
eq_zero_of_add_eq_zero_right Hk
theorem le_trans {n m k : ℕ} (H1 : n ≤ m) (H2 : m ≤ k) : n ≤ k
:= obtain (l1 : ℕ) (Hl1 : n + l1 = m), from le_elim H1,
obtain (l2 : ℕ) (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 : ℕ} (H1 : n ≤ m) (H2 : m ≤ n) : n = m
:= obtain (k : ℕ) (Hk : n + k = m), from (le_elim H1),
obtain (l : ℕ) (Hl : m + l = n), from (le_elim H2),
have L1 : k + l = 0, from
add_cancel_left
(calc
n + (k + l) = n + k + l : { symm (add_assoc n k l) }
... = m + l : { Hk }
... = n : Hl
... = n + 0 : symm (add_zero n)),
have L2 : k = 0, from eq_zero_of_add_eq_zero_right L1,
calc
n = n + 0 : symm (add_zero n)
... = n + k : { symm L2 }
... = m : Hk
---------- interaction with add
theorem add_le_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k + n ≤ k + m
:= obtain (l : ℕ) (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 : ℕ} (H : n ≤ m) (k : ℕ) : n + k ≤ m + k
:= (add_comm k m) ▸ (add_comm k n) ▸ (add_le_left H k)
theorem add_le {n m k l : ℕ} (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 : ℕ} (H : k + n ≤ k + m) : n ≤ m
:=
obtain (l : ℕ) (Hl : k + n + l = k + m), from (le_elim H),
le_intro (add_cancel_left
(calc
k + (n + l) = k + n + l : symm (add_assoc k n l)
... = k + m : Hl))
theorem add_le_right_inv {n m k : ℕ} (H : n + k ≤ m + k) : n ≤ m
:= add_le_left_inv (add_comm m k ▸ add_comm n k ▸ H)
---------- interaction with succ and pred
theorem succ_le {n m : ℕ} (H : n ≤ m) : succ n ≤ succ m
:= add_one m ▸ add_one n ▸ add_le_right H 1
theorem succ_le_cancel {n m : ℕ} (H : succ n ≤ succ m) : n ≤ m
:= add_le_right_inv ((add_one m)⁻¹ ▸ (add_one n)⁻¹ ▸ H)
theorem self_le_succ (n : ℕ) : n ≤ succ n
:= le_intro (add_one n)
theorem le_imp_le_succ {n m : ℕ} (H : n ≤ m) : n ≤ succ m
:= le_trans H (self_le_succ m)
theorem succ_le_left_or {n m : ℕ} (H : n ≤ m) : succ n ≤ m ∨ n = m
:= obtain (k : ℕ) (Hk : n + k = m), from (le_elim H),
discriminate
(assume H3 : k = 0,
have Heq : n = m,
from calc
n = n + 0 : (add_zero n)⁻¹
... = n + k : {H3⁻¹}
... = m : Hk,
or_intro_right _ Heq)
(take l:ℕ,
assume H3 : k = succ l,
have Hlt : succ n ≤ m, from
(le_intro
(calc
succ n + l = n + succ l : succ_add_eq_add_succ n l
... = n + k : {H3⁻¹}
... = m : Hk)),
or_intro_left _ Hlt)
theorem succ_le_left {n m : ℕ} (H1 : n ≤ m) (H2 : n ≠ m) : succ n ≤ m
:= or_resolve_left (succ_le_left_or H1) H2
theorem succ_le_right_inv {n m : ℕ} (H : n ≤ succ m) : n ≤ m ∨ n = succ m
:= or_of_or_of_imp_of_imp (succ_le_left_or H)
(take H2 : succ n ≤ succ m, show n ≤ m, from succ_le_cancel H2)
(take H2 : n = succ m, H2)
theorem succ_le_left_inv {n m : ℕ} (H : succ n ≤ m) : n ≤ m ∧ n ≠ m
:= obtain (k : ℕ) (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 (succ_add_eq_add_succ n k)
... = m : H2,
show n ≤ m, from le_intro H3)
(assume H3 : n = m,
have H4 : succ n ≤ n, from subst (symm H3) H,
have H5 : succ n = n, from le_antisym H4 (self_le_succ n),
show false, from absurd H5 (succ_ne_self n))
theorem le_pred_self (n : ℕ) : pred n ≤ n
:= case n
(subst (symm pred_zero) (le_refl 0))
(take k : ℕ, subst (symm (pred_succ k)) (self_le_succ k))
theorem pred_le {n m : ℕ} (H : n ≤ m) : pred n ≤ pred m
:= discriminate
(take Hn : n = 0,
have H2 : pred n = 0,
from calc
pred n = pred 0 : {Hn}
... = 0 : pred_zero,
subst (symm H2) (zero_le (pred m)))
(take k : ℕ,
assume Hn : n = succ k,
obtain (l : ℕ) (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 (succ_add k l)}
... = pred (n + l) : {symm Hn}
... = pred m : {Hl},
le_intro H2)
theorem pred_le_left_inv {n m : ℕ} (H : pred n ≤ m) : n ≤ m ∨ n = succ m
:= discriminate
(take Hn : n = 0,
or_intro_left _ (subst (symm Hn) (zero_le m)))
(take k : ℕ,
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 H2 H,
have H4 : succ k ≤ m ∨ k = m, from succ_le_left_or H3,
show n ≤ m ∨ n = succ m, from
or_of_or_of_imp_of_imp H4
(take H5 : succ k ≤ m, show n ≤ m, from subst (symm Hn) H5)
(take H5 : k = m, show n = succ m, from subst H5 Hn))
-- ### interaction with successor and predecessor
theorem le_imp_succ_le_or_eq {n m : ℕ} (H : n ≤ m) : succ n ≤ m ∨ n = m
:=
obtain (k : ℕ) (Hk : n + k = m), from (le_elim H),
discriminate
(assume H3 : k = 0,
have Heq : n = m,
from calc
n = n + 0 : symm (add_zero 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 : succ_add_eq_add_succ n l
... = n + k : {symm H3}
... = m : Hk)),
or_intro_left _ Hlt)
theorem le_ne_imp_succ_le {n m : ℕ} (H1 : n ≤ m) (H2 : n ≠ m) : succ n ≤ m
:= or_resolve_left (le_imp_succ_le_or_eq H1) H2
theorem succ_le_imp_le_and_ne {n m : ℕ} (H : succ n ≤ m) : n ≤ m ∧ n ≠ m
:=
and_intro
(le_trans (self_le_succ n) H)
(assume H2 : n = m,
have H3 : succ n ≤ n, from subst (symm H2) H,
have H4 : succ n = n, from le_antisym H3 (self_le_succ n),
show false, from absurd H4 (succ_ne_self n))
theorem pred_le_self (n : ℕ) : pred n ≤ n
:=
case n
(subst (symm pred_zero) (le_refl 0))
(take k : nat, subst (symm (pred_succ k)) (self_le_succ k))
theorem pred_le_imp_le_or_eq {n m : ℕ} (H : pred n ≤ m) : n ≤ m ∨ n = succ m
:=
discriminate
(take Hn : n = 0,
or_intro_left _ (subst (symm Hn) (zero_le m)))
(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 H2 H,
have H4 : succ k ≤ m ∨ k = m, from le_imp_succ_le_or_eq H3,
show n ≤ m ∨ n = succ m, from
or_of_or_of_imp_of_imp H4
(take H5 : succ k ≤ m, show n ≤ m, from subst (symm Hn) H5)
(take H5 : k = m, show n = succ m, from subst H5 Hn))
---------- interaction with mul
theorem mul_le_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k * n ≤ k * m
:=
obtain (l : ℕ) (Hl : n + l = m), from (le_elim H),
induction_on k
(have H2 : 0 * n = 0 * m,
from calc
0 * n = 0 : mul_zero_left n
... = 0 * m : symm (mul_zero_left m),
show 0 * n ≤ 0 * m, from subst H2 (le_refl (0 * n)))
(take (l : ℕ),
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 (symm (mul_succ_left l n)) H2,
show succ l * n ≤ succ l * m, from subst (symm (mul_succ_left l m)) H3)
theorem mul_le_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n * k ≤ m * k
:= mul_comm k m ▸ mul_comm k n ▸ (mul_le_left H k)
theorem mul_le {n m k l : ℕ} (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 : ℕ) := succ n ≤ m
infix `<` := lt
theorem lt_intro {n m k : ℕ} (H : succ n + k = m) : n < m
:= le_intro H
theorem lt_elim {n m : ℕ} (H : n < m) : ∃ k, succ n + k = m
:= le_elim H
theorem lt_intro2 (n m : ℕ) : n < n + succ m
:= lt_intro (succ_add_eq_add_succ n m)
-------------------------------------------------- ge, gt
definition ge (n m : ℕ) := m ≤ n
infix `>=` := ge
infix `≥` := ge
definition gt (n m : ℕ) := m < n
infix `>` := gt
---------- basic facts
theorem lt_ne {n m : ℕ} (H : n < m) : n ≠ m
:= and.elim_right (succ_le_left_inv H)
theorem lt_irrefl (n : ℕ) : ¬ n < n
:= assume H : n < n, absurd (refl n) (lt_ne H)
theorem lt_zero (n : ℕ) : 0 < succ n
:= succ_le (zero_le n)
theorem lt_zero_inv (n : ℕ) : ¬ n < 0
:= assume H : n < 0,
have H2 : succ n = 0, from le_zero_inv H,
absurd H2 (succ_ne_zero n)
theorem lt_positive {n m : ℕ} (H : n < m) : ∃k, m = succ k
:= discriminate
(take (Hm : m = 0), absurd (subst Hm H) (lt_zero_inv n))
(take (l : ℕ) (Hm : m = succ l), exists.intro l Hm)
---------- interaction with le
theorem lt_imp_le_succ {n m : ℕ} (H : n < m) : succ n ≤ m
:= H
theorem le_succ_imp_lt {n m : ℕ} (H : succ n ≤ m) : n < m
:= H
theorem self_lt_succ (n : ℕ) : n < succ n
:= le_refl (succ n)
theorem lt_imp_le {n m : ℕ} (H : n < m) : n ≤ m
:= and.elim_left (succ_le_imp_le_and_ne H)
theorem le_imp_lt_or_eq {n m : ℕ} (H : n ≤ m) : n < m ∨ n = m
:= le_imp_succ_le_or_eq H
theorem le_ne_imp_lt {n m : ℕ} (H1 : n ≤ m) (H2 : n ≠ m) : n < m
:= le_ne_imp_succ_le H1 H2
theorem le_imp_lt_succ {n m : ℕ} (H : n ≤ m) : n < succ m
:= succ_le H
theorem lt_succ_imp_le {n m : ℕ} (H : n < succ m) : n ≤ m
:= succ_le_cancel H
---------- trans, antisym
theorem lt_le_trans {n m k : ℕ} (H1 : n < m) (H2 : m ≤ k) : n < k
:= le_trans H1 H2
theorem le_lt_trans {n m k : ℕ} (H1 : n ≤ m) (H2 : m < k) : n < k
:= le_trans (succ_le H1) H2
theorem lt_trans {n m k : ℕ} (H1 : n < m) (H2 : m < k) : n < k
:= lt_le_trans H1 (lt_imp_le H2)
theorem le_imp_not_gt {n m : ℕ} (H : n ≤ m) : ¬ n > m
:= assume H2 : m < n, absurd (le_lt_trans H H2) (lt_irrefl n)
theorem lt_imp_not_ge {n m : ℕ} (H : n < m) : ¬ n ≥ m
:= assume H2 : m ≤ n, absurd (lt_le_trans H H2) (lt_irrefl n)
theorem lt_antisym {n m : ℕ} (H : n < m) : ¬ m < n
:= le_imp_not_gt (lt_imp_le H)
---------- interaction with add
theorem add_lt_left {n m : ℕ} (H : n < m) (k : ℕ) : k + n < k + m
:= add_succ k n ▸ add_le_left H k
theorem add_lt_right {n m : ℕ} (H : n < m) (k : ℕ) : n + k < m + k
:= add_comm k m ▸ add_comm k n ▸ add_lt_left H k
theorem add_le_lt {n m k l : ℕ} (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 : ℕ} (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 : ℕ} (H1 : n < k) (H2 : m < l) : n + m < k + l
:= add_lt_le H1 (lt_imp_le H2)
theorem add_lt_left_inv {n m k : ℕ} (H : k + n < k + m) : n < m
:= add_le_left_inv ((add_succ k n)⁻¹ ▸ H)
theorem add_lt_right_inv {n m k : ℕ} (H : n + k < m + k) : n < m
:= add_lt_left_inv (add_comm m k ▸ add_comm n k ▸ H)
---------- interaction with succ (see also the interaction with le)
theorem succ_lt {n m : ℕ} (H : n < m) : succ n < succ m
:= add_one m ▸ add_one n ▸ add_lt_right H 1
theorem succ_lt_inv {n m : ℕ} (H : succ n < succ m) : n < m
:= add_lt_right_inv ((add_one m)⁻¹ ▸ (add_one n)⁻¹ ▸ H)
theorem lt_self_succ (n : ℕ) : n < succ n
:= le_refl (succ n)
theorem succ_lt_right {n m : ℕ} (H : n < m) : n < succ m
:= lt_trans H (lt_self_succ m)
---------- totality of lt and le
theorem le_or_lt (n m : ℕ) : n ≤ m ∨ m < n
:= induction_on n
(or_intro_left _ (zero_le m))
(take (k : ℕ),
assume IH : k ≤ m ∨ m < k,
or.elim IH
(assume H : k ≤ m,
obtain (l : ℕ) (Hl : k + l = m), from le_elim H,
discriminate
(assume H2 : l = 0,
have H3 : m = k,
from calc
m = k + l : symm Hl
... = k + 0 : {H2}
... = k : add_zero k,
have H4 : m < succ k, from subst H3 (lt_self_succ m),
or_intro_right _ H4)
(take l2 : ℕ,
assume H2 : l = succ l2,
have H3 : succ k + l2 = m,
from calc
succ k + l2 = k + succ l2 : succ_add_eq_add_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 : ℕ) : (n < m ∨ n = m) ∨ m < n
:= or_of_or_of_imp_of_imp (le_or_lt n m) (assume H : n ≤ m, le_imp_lt_or_eq H) (assume H : m < n, H)
theorem trichotomy (n m : ℕ) : n < m ∨ n = m ∨ m < n
:= iff.elim_left or.assoc (trichotomy_alt n m)
theorem le_total (n m : ℕ) : n ≤ m ∨ m ≤ n
:= or_of_or_of_imp_of_imp (le_or_lt n m) (assume H : n ≤ m, H) (assume H : m < n, lt_imp_le H)
-- interaction with mul under "positivity"
theorem strong_induction_on {P : ℕ → Prop} (n : ℕ) (IH : ∀n, (∀m, m < n → P m) → P n) : P n
:= have stronger : ∀k, k ≤ n → P k, from
induction_on n
(take (k : ℕ),
assume H : k ≤ 0,
have H2 : k = 0, from le_zero_inv H,
have H3 : ∀m, m < k → P m, from
(take m : ℕ,
assume H4 : m < k,
have H5 : m < 0, from subst H2 H4,
absurd H5 (lt_zero_inv m)),
show P k, from IH k H3)
(take l : ℕ,
assume IHl : ∀k, k ≤ l → P k,
take k : ℕ,
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 : ℕ,
assume H4 : m < k,
have H5 : m ≤ l, from lt_succ_imp_le (subst H2 H4),
show P m, from IHl m H5),
show P k, from IH k H3)),
stronger n (le_refl n)
theorem case_strong_induction_on {P : ℕ → Prop} (a : ℕ) (H0 : P 0) (Hind : ∀(n : ℕ), (∀m, m ≤ n → P m) → P (succ n)) : P a
:= strong_induction_on a
(take n, case n
(assume H : (∀m, m < 0 → P m), H0)
(take n, assume H : (∀m, m < succ n → P m),
Hind n (take m, assume H1 : m ≤ n, H m (le_imp_lt_succ H1))))
theorem add_eq_self {n m : ℕ} (H : n + m = n) : m = 0
:= discriminate
(take Hm : m = 0, Hm)
(take k : ℕ,
assume Hm : m = succ k,
have H2 : succ n + k = n,
from calc
succ n + k = n + succ k : succ_add_eq_add_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 (refl n) H4)
-------------------------------------------------- positivity
-- we use " _ > 0" as canonical way of denoting that a number is positive
---------- basic
theorem zero_or_positive (n : ℕ) : n = 0 ∨ n > 0
:= or_of_or_of_imp_of_imp (or.swap (le_imp_lt_or_eq (zero_le n))) (take H : 0 = n, symm H) (take H : n > 0, H)
theorem succ_positive {n m : ℕ} (H : n = succ m) : n > 0
:= subst (symm H) (lt_zero m)
theorem ne_zero_positive {n : ℕ} (H : n ≠ 0) : n > 0
:= or.elim (zero_or_positive n) (take H2 : n = 0, absurd H2 H) (take H2 : n > 0, H2)
theorem pos_imp_eq_succ {n : ℕ} (H : n > 0) : ∃l, n = succ l
:= discriminate
(take H2, absurd (subst H2 H) (lt_irrefl 0))
(take l Hl, exists.intro l Hl)
theorem add_positive_right (n : ℕ) {k : ℕ} (H : k > 0) : n + k > n
:= obtain (l : ℕ) (Hl : k = succ l), from pos_imp_eq_succ H,
subst (symm Hl) (lt_intro2 n l)
theorem add_positive_left (n : ℕ) {k : ℕ} (H : k > 0) : k + n > n
:= subst (add_comm n k) (add_positive_right n H)
-- Positivity
-- ---------
--
-- Writing "t > 0" is the preferred way to assert that a natural number is positive.
-- ### basic
-- See also succ_pos.
theorem succ_pos (n : ℕ) : 0 < succ n
:= succ_le (zero_le n)
theorem case_zero_pos {P : ℕ → Prop} (y : ℕ) (H0 : P 0) (H1 : ∀y, y > 0 → P y) : P y
:= case y H0 (take y', H1 _ (succ_pos _))
theorem succ_imp_pos {n m : ℕ} (H : n = succ m) : n > 0
:= subst (symm H) (succ_pos m)
theorem add_pos_right (n : ℕ) {k : ℕ} (H : k > 0) : n + k > n
:= subst (add_zero n) (add_lt_left H n)
theorem add_pos_left (n : ℕ) {k : ℕ} (H : k > 0) : k + n > n
:= subst (add_comm n k) (add_pos_right n H)
---------- mul
theorem mul_positive {n m : ℕ} (Hn : n > 0) (Hm : m > 0) : n * m > 0
:= obtain (k : ℕ) (Hk : n = succ k), from pos_imp_eq_succ Hn,
obtain (l : ℕ) (Hl : m = succ l), from pos_imp_eq_succ Hm,
succ_positive (calc
n * m = succ k * m : {Hk}
... = succ k * succ l : {Hl}
... = succ k * l + succ k : mul_succ_right (succ k) l
... = succ (succ k * l + k) : add_succ _ _)
theorem mul_positive_inv_left {n m : ℕ} (H : n * m > 0) : n > 0
:= discriminate
(assume H2 : n = 0,
have H3 : n * m = 0,
from calc
n * m = 0 * m : {H2}
... = 0 : mul_zero_left m,
have H4 : 0 > 0, from subst H3 H,
absurd H4 (lt_irrefl 0))
(take l : ℕ,
assume Hl : n = succ l,
subst (symm Hl) (lt_zero l))
theorem mul_positive_inv_right {n m : ℕ} (H : n * m > 0) : m > 0
:= mul_positive_inv_left (subst (mul_comm n m) H)
theorem mul_left_inj {n m k : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k
:=
have general : ∀m, n * m = n * k → m = k, from
induction_on k
(take m:ℕ,
assume H : n * m = n * 0,
have H2 : n * m = 0,
from calc
n * m = n * 0 : H
... = 0 : mul_zero_right n,
have H3 : n = 0 ∨ m = 0, from mul_eq_zero H2,
or_resolve_right H3 (ne.symm (lt_ne Hn)))
(take (l : ℕ),
assume (IH : ∀ m, n * m = n * l → m = l),
take (m : ℕ),
assume (H : n * m = n * succ l),
have H2 : n * succ l > 0, from mul_positive Hn (lt_zero l),
have H3 : m > 0, from mul_positive_inv_right (subst (symm H) H2),
obtain (l2:ℕ) (Hm : m = succ l2), from pos_imp_eq_succ H3,
have H4 : n * l2 + n = n * l + n,
from calc
n * l2 + n = n * succ l2 : symm (mul_succ_right n l2)
... = n * m : {symm Hm}
... = n * succ l : H
... = n * l + n : mul_succ_right n l,
have H5 : n * l2 = n * l, from add_cancel_right H4,
calc
m = succ l2 : Hm
... = succ l : {IH l2 H5}),
general m H
theorem mul_right_inj {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k
:= mul_left_inj Hm (subst (mul_comm k m) (subst (mul_comm n m) H))
-- mul_eq_one below
---------- interaction of mul with le and lt
theorem mul_lt_left {n m k : ℕ} (Hk : k > 0) (H : n < m) : k * n < k * m
:=
have H2 : k * n < k * n + k, from add_positive_right (k * n) Hk,
have H3 : k * n + k ≤ k * m, from subst (mul_succ_right k n) (mul_le_left H k),
lt_le_trans H2 H3
theorem mul_lt_right {n m k : ℕ} (Hk : k > 0) (H : n < m) : n * k < m * k
:= subst (mul_comm k m) (subst (mul_comm k n) (mul_lt_left Hk H))
theorem mul_le_lt {n m k l : ℕ} (Hk : k > 0) (H1 : n ≤ k) (H2 : m < l) : n * m < k * l
:= le_lt_trans (mul_le_right H1 m) (mul_lt_left Hk H2)
theorem mul_lt_le {n m k l : ℕ} (Hl : l > 0) (H1 : n < k) (H2 : m ≤ l) : n * m < k * l
:= le_lt_trans (mul_le_left H2 n) (mul_lt_right Hl H1)
theorem mul_lt {n m k l : ℕ} (H1 : n < k) (H2 : m < l) : n * m < k * l
:=
have H3 : n * m ≤ k * m, from mul_le_right (lt_imp_le H1) m,
have H4 : k * m < k * l, from mul_lt_left (le_lt_trans (zero_le n) H1) H2,
le_lt_trans H3 H4
theorem mul_lt_left_inv {n m k : ℕ} (H : k * n < k * m) : n < m
:=
have general : ∀ m, k * n < k * m → n < m, from
induction_on n
(take m : ℕ,
assume H2 : k * 0 < k * m,
have H3 : 0 < k * m, from mul_zero_right k ▸ H2,
show 0 < m, from mul_positive_inv_right H3)
(take l : ℕ,
assume IH : ∀ m, k * l < k * m → l < m,
take m : ℕ,
assume H2 : k * succ l < k * m,
have H3 : 0 < k * m, from le_lt_trans (zero_le _) H2,
have H4 : 0 < m, from mul_positive_inv_right H3,
obtain (l2 : ℕ) (Hl2 : m = succ l2), from pos_imp_eq_succ H4,
have H5 : k * l + k < k * m, from mul_succ_right k l ▸ H2,
have H6 : k * l + k < k * succ l2, from Hl2 ▸ H5,
have H7 : k * l + k < k * l2 + k, from mul_succ_right k l2 ▸ H6,
have H8 : k * l < k * l2, from add_lt_right_inv H7,
have H9 : l < l2, from IH l2 H8,
have H10 : succ l < succ l2, from succ_lt H9,
show succ l < m, from Hl2⁻¹ ▸ H10),
general m H
theorem mul_lt_right_inv {n m k : ℕ} (H : n * k < m * k) : n < m
:= mul_lt_left_inv (mul_comm m k ▸ mul_comm n k ▸ H)
theorem mul_le_left_inv {n m k : ℕ} (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 (symm (mul_succ_right (succ k) m)) H2,
have H4 : n < succ m, from mul_lt_left_inv H3,
show n ≤ m, from lt_succ_imp_le H4
theorem mul_le_right_inv {n m k : ℕ} (H : n * succ m ≤ k * succ m) : n ≤ k
:= mul_le_left_inv (subst (mul_comm k (succ m)) (subst (mul_comm n (succ m)) H))
theorem mul_eq_one_left {n m : ℕ} (H : n * m = 1) : n = 1
:=
have H2 : n * m > 0, from subst (symm H) (lt_zero 0),
have H3 : n > 0, from mul_positive_inv_left H2,
have H4 : m > 0, from mul_positive_inv_right H2,
or.elim (le_or_lt n 1)
(assume H5 : n ≤ 1,
show n = 1, from le_antisym H5 H3)
(assume H5 : n > 1,
have H6 : n * m ≥ 2 * 1, from mul_le H5 H4,
have H7 : 1 ≥ 2, from subst (mul_one_right 2) (subst H H6),
absurd (self_lt_succ 1) (le_imp_not_gt H7))
theorem mul_eq_one_right {n m : ℕ} (H : n * m = 1) : m = 1
:= mul_eq_one_left (subst (mul_comm n m) H)
theorem mul_eq_one {n m : ℕ} (H : n * m = 1) : n = 1 ∧ m = 1
:= and_intro (mul_eq_one_left H) (mul_eq_one_right H)
-------------------------------------------------- sub
definition sub (n m : ℕ) : ℕ := nat.rec n (fun m x, pred x) m
infixl `-` := sub
theorem sub_zero_right (n : ℕ) : n - 0 = n
theorem sub_succ_right (n m : ℕ) : n - succ m = pred (n - m)
theorem sub_zero_left (n : ℕ) : 0 - n = 0
:= induction_on n (sub_zero_right 0)
(take k : ℕ,
assume IH : 0 - k = 0,
calc
0 - succ k = pred (0 - k) : sub_succ_right 0 k
... = pred 0 : {IH}
... = 0 : pred_zero)
theorem sub_succ_succ (n m : ℕ) : succ n - succ m = n - m
:= induction_on m
(calc
succ n - 1 = pred (succ n - 0) : sub_succ_right (succ n) 0
... = pred (succ n) : {sub_zero_right (succ n)}
... = n : pred_succ n
... = n - 0 : symm (sub_zero_right n))
(take k : ℕ,
assume IH : succ n - succ k = n - k,
calc
succ n - succ (succ k) = pred (succ n - succ k) : sub_succ_right (succ n) (succ k)
... = pred (n - k) : {IH}
... = n - succ k : symm (sub_succ_right n k))
theorem sub_one (n : ℕ) : n - 1 = pred n
:= calc
n - 1 = pred (n - 0) : sub_succ_right n 0
... = pred n : {sub_zero_right n}
theorem sub_self (n : ℕ) : n - n = 0
:= induction_on n (sub_zero_right 0) (take k IH, trans (sub_succ_succ k k) IH)
theorem sub_add_add_right (n m k : ℕ) : (n + k) - (m + k) = n - m
:= induction_on k
(calc
(n + 0) - (m + 0) = n - (m + 0) : {add_zero _}
... = n - m : {add_zero _})
(take l : ℕ,
assume IH : (n + l) - (m + l) = n - m,
calc
(n + succ l) - (m + succ l) = succ (n + l) - (m + succ l) : {add_succ _ _}
... = succ (n + l) - succ (m + l) : {add_succ _ _}
... = (n + l) - (m + l) : sub_succ_succ _ _
... = n - m : IH)
theorem sub_add_add_left (n m k : ℕ) : (k + n) - (k + m) = n - m
:= subst (add_comm m k) (subst (add_comm n k) (sub_add_add_right n m k))
theorem sub_add_left (n m : ℕ) : n + m - m = n
:= induction_on m
(subst (symm (add_zero n)) (sub_zero_right n))
(take k : ℕ,
assume IH : n + k - k = n,
calc
n + succ k - succ k = succ (n + k) - succ k : {add_succ n k}
... = n + k - k : sub_succ_succ _ _
... = n : IH)
theorem sub_sub (n m k : ℕ) : n - m - k = n - (m + k)
:= induction_on k
(calc
n - m - 0 = n - m : sub_zero_right _
... = n - (m + 0) : {symm (add_zero m)})
(take l : ℕ,
assume IH : n - m - l = n - (m + l),
calc
n - m - succ l = pred (n - m - l) : sub_succ_right (n - m) l
... = pred (n - (m + l)) : {IH}
... = n - succ (m + l) : symm (sub_succ_right n (m + l))
... = n - (m + succ l) : {symm (add_succ m l)})
theorem succ_sub_sub (n m k : ℕ) : succ n - m - succ k = n - m - k
:= calc
succ n - m - succ k = succ n - (m + succ k) : sub_sub _ _ _
... = succ n - succ (m + k) : {add_succ m k}
... = n - (m + k) : sub_succ_succ _ _
... = n - m - k : symm (sub_sub n m k)
theorem sub_add_right_eq_zero (n m : ℕ) : n - (n + m) = 0
:= calc
n - (n + m) = n - n - m : symm (sub_sub n n m)
... = 0 - m : {sub_self n}
... = 0 : sub_zero_left m
theorem sub_comm (m n k : ℕ) : m - n - k = m - k - n
:= calc
m - n - k = m - (n + k) : sub_sub m n k
... = m - (k + n) : {add_comm n k}
... = m - k - n : symm (sub_sub m k n)
theorem succ_sub_one (n : ℕ) : succ n - 1 = n
:= sub_succ_succ n 0 ⬝ sub_zero_right n
---------- mul
theorem mul_pred_left (n m : ℕ) : pred n * m = n * m - m
:= induction_on n
(calc
pred 0 * m = 0 * m : {pred_zero}
... = 0 : mul_zero_left _
... = 0 - m : symm (sub_zero_left m)
... = 0 * m - m : {symm (mul_zero_left m)})
(take k : ℕ,
assume IH : pred k * m = k * m - m,
calc
pred (succ k) * m = k * m : {pred_succ k}
... = k * m + m - m : symm (sub_add_left _ _)
... = succ k * m - m : {symm (mul_succ_left k m)})
theorem mul_pred_right (n m : ℕ) : 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_sub_distr_left (n m k : ℕ) : (n - m) * k = n * k - m * k
:= induction_on m
(calc
(n - 0) * k = n * k : {sub_zero_right n}
... = n * k - 0 : symm (sub_zero_right _)
... = n * k - 0 * k : {symm (mul_zero_left _)})
(take l : ℕ,
assume IH : (n - l) * k = n * k - l * k,
calc
(n - succ l) * k = pred (n - l) * k : {sub_succ_right n l}
... = (n - l) * k - k : mul_pred_left _ _
... = n * k - l * k - k : {IH}
... = n * k - (l * k + k) : sub_sub _ _ _
... = n * k - (succ l * k) : {symm (mul_succ_left l k)})
theorem mul_sub_distr_right (n m k : ℕ) : n * (m - k) = n * m - n * k
:= calc
n * (m - k) = (m - k) * n : mul_comm _ _
... = m * n - k * n : mul_sub_distr_left _ _ _
... = n * m - k * n : {mul_comm _ _}
... = n * m - n * k : {mul_comm _ _}
-------------------------------------------------- max, min, iteration, maybe: sub, div
theorem succ_sub {m n : ℕ} : m ≥ n → succ m - n = succ (m - n)
:= sub_induction n m
(take k,
assume H : 0 ≤ k,
calc
succ k - 0 = succ k : sub_zero_right (succ k)
... = succ (k - 0) : {symm (sub_zero_right k)})
(take k,
assume H : succ k ≤ 0,
absurd H (not_succ_zero_le k))
(take k l,
assume IH : k ≤ l → succ l - k = succ (l - k),
take H : succ k ≤ succ l,
calc
succ (succ l) - succ k = succ l - k : sub_succ_succ (succ l) k
... = succ (l - k) : IH (succ_le_cancel H)
... = succ (succ l - succ k) : {symm (sub_succ_succ l k)})
theorem le_imp_sub_eq_zero {n m : ℕ} (H : n ≤ m) : n - m = 0
:= obtain (k : ℕ) (Hk : n + k = m), from le_elim H, subst Hk (sub_add_right_eq_zero n k)
theorem add_sub_le {n m : ℕ} : n ≤ m → n + (m - n) = m
:= sub_induction n m
(take k,
assume H : 0 ≤ k,
calc
0 + (k - 0) = k - 0 : zero_add (k - 0)
... = k : sub_zero_right k)
(take k, assume H : succ k ≤ 0, absurd H (not_succ_zero_le k))
(take k l,
assume IH : k ≤ l → k + (l - k) = l,
take H : succ k ≤ succ l,
calc
succ k + (succ l - succ k) = succ k + (l - k) : {sub_succ_succ l k}
... = succ (k + (l - k)) : succ_add k (l - k)
... = succ l : {IH (succ_le_cancel H)})
theorem add_sub_ge_left {n m : ℕ} : n ≥ m → n - m + m = n
:= subst (add_comm m (n - m)) add_sub_le
theorem add_sub_ge {n m : ℕ} (H : n ≥ m) : n + (m - n) = n
:= calc
n + (m - n) = n + 0 : {le_imp_sub_eq_zero H}
... = n : add_zero n
theorem add_sub_le_left {n m : ℕ} : n ≤ m → n - m + m = m
:= subst (add_comm m (n - m)) add_sub_ge
theorem le_add_sub_left (n m : ℕ) : n ≤ n + (m - n)
:= or.elim (le_total n m)
(assume H : n ≤ m, subst (symm (add_sub_le H)) H)
(assume H : m ≤ n, subst (symm (add_sub_ge H)) (le_refl n))
theorem le_add_sub_right (n m : ℕ) : m ≤ n + (m - n)
:= or.elim (le_total n m)
(assume H : n ≤ m, subst (symm (add_sub_le H)) (le_refl m))
(assume H : m ≤ n, subst (symm (add_sub_ge H)) H)
theorem sub_split {P : ℕ → Prop} {n m : ℕ} (H1 : n ≤ m → P 0) (H2 : ∀k, m + k = n -> P k)
: P (n - m)
:= or.elim (le_total n m)
(assume H3 : n ≤ m, subst (symm (le_imp_sub_eq_zero H3)) (H1 H3))
(assume H3 : m ≤ n, H2 (n - m) (add_sub_le H3))
theorem sub_le_self (n m : ℕ) : n - m ≤ n
:=
sub_split
(assume H : n ≤ m, zero_le n)
(take k : ℕ, assume H : m + k = n, le_intro (subst (add_comm m k) H))
theorem le_elim_sub (n m : ℕ) (H : n ≤ m) : ∃k, m - k = n
:=
obtain (k : ℕ) (Hk : n + k = m), from le_elim H,
exists.intro k
(calc
m - k = n + k - k : {symm Hk}
... = n : sub_add_left n k)
theorem add_sub_assoc {m k : ℕ} (H : k ≤ m) (n : ℕ) : n + m - k = n + (m - k)
:= have l1 : k ≤ m → n + m - k = n + (m - k), from
sub_induction k m
(take m : ℕ,
assume H : 0 ≤ m,
calc
n + m - 0 = n + m : sub_zero_right (n + m)
... = n + (m - 0) : {symm (sub_zero_right m)})
(take k : ℕ, assume H : succ k ≤ 0, absurd H (not_succ_zero_le k))
(take k m,
assume IH : k ≤ m → n + m - k = n + (m - k),
take H : succ k ≤ succ m,
calc
n + succ m - succ k = succ (n + m) - succ k : {add_succ n m}
... = n + m - k : sub_succ_succ (n + m) k
... = n + (m - k) : IH (succ_le_cancel H)
... = n + (succ m - succ k) : {symm (sub_succ_succ m k)}),
l1 H
theorem sub_eq_zero_imp_le {n m : ℕ} : n - m = 0 → n ≤ m
:= sub_split
(assume H1 : n ≤ m, assume H2 : 0 = 0, H1)
(take k : ℕ,
assume H1 : m + k = n,
assume H2 : k = 0,
have H3 : n = m, from subst (add_zero m) (subst H2 (symm H1)),
subst H3 (le_refl n))
theorem sub_sub_split {P : ℕ → ℕ → Prop} {n m : ℕ} (H1 : ∀k, n = m + k -> P k 0)
(H2 : ∀k, m = n + k → P 0 k) : P (n - m) (m - n)
:= or.elim (le_total n m)
(assume H3 : n ≤ m,
(le_imp_sub_eq_zero H3)⁻¹ ▸ (H2 (m - n) ((add_sub_le H3)⁻¹)))
(assume H3 : m ≤ n,
(le_imp_sub_eq_zero H3)⁻¹ ▸ (H1 (n - m) ((add_sub_le H3)⁻¹)))
theorem sub_intro {n m k : ℕ} (H : n + m = k) : k - n = m
:= have H2 : k - n + n = m + n, from
calc
k - n + n = k : add_sub_ge_left (le_intro H)
... = n + m : symm H
... = m + n : add_comm n m,
add_cancel_right H2
theorem sub_lt {x y : ℕ} (xpos : x > 0) (ypos : y > 0) : x - y < x
:= obtain (x' : ℕ) (xeq : x = succ x'), from pos_imp_eq_succ xpos,
obtain (y' : ℕ) (yeq : y = succ y'), from pos_imp_eq_succ ypos,
have xsuby_eq : x - y = x' - y', from
calc
x - y = succ x' - y : {xeq}
... = succ x' - succ y' : {yeq}
... = x' - y' : sub_succ_succ _ _,
have H1 : x' - y' ≤ x', from sub_le_self _ _,
have H2 : x' < succ x', from self_lt_succ _,
show x - y < x, from xeq⁻¹ ▸ xsuby_eq⁻¹ ▸ le_lt_trans H1 H2
-- Max, min, iteration, and absolute difference
-- --------------------------------------------
definition max (n m : ℕ) : ℕ := n + (m - n)
definition min (n m : ℕ) : ℕ := m - (m - n)
theorem max_le {n m : ℕ} (H : n ≤ m) : n + (m - n) = m := add_sub_le H
theorem max_ge {n m : ℕ} (H : n ≥ m) : n + (m - n) = n := add_sub_ge H
theorem left_le_max (n m : ℕ) : n ≤ n + (m - n) := le_add_sub_left n m
theorem right_le_max (n m : ℕ) : m ≤ max n m := le_add_sub_right n m
-- ### absolute difference
-- This section is still incomplete
definition dist (n m : ℕ) := (n - m) + (m - n)
theorem dist_comm (n m : ℕ) : dist n m = dist m n
:= add_comm (n - m) (m - n)
theorem dist_eq_zero {n m : ℕ} (H : dist n m = 0) : n = m
:=
have H2 : n - m = 0, from eq_zero_of_add_eq_zero_right H,
have H3 : n ≤ m, from sub_eq_zero_imp_le H2,
have H4 : m - n = 0, from add_eq_zero_right H,
have H5 : m ≤ n, from sub_eq_zero_imp_le H4,
le_antisym H3 H5
theorem dist_le {n m : ℕ} (H : n ≤ m) : dist n m = m - n
:= calc
dist n m = (n - m) + (m - n) : refl _
... = 0 + (m - n) : {le_imp_sub_eq_zero H}
... = m - n : zero_add (m - n)
theorem dist_ge {n m : ℕ} (H : n ≥ m) : dist n m = n - m
:= subst (dist_comm m n) (dist_le H)
theorem dist_zero_right (n : ℕ) : dist n 0 = n
:= trans (dist_ge (zero_le n)) (sub_zero_right n)
theorem dist_zero_left (n : ℕ) : dist 0 n = n
:= trans (dist_le (zero_le n)) (sub_zero_right n)
theorem dist_intro {n m k : ℕ} (H : n + m = k) : dist k n = m
:= calc
dist k n = k - n : dist_ge (le_intro H)
... = m : sub_intro H
theorem dist_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m
:=
calc
dist (n + k) (m + k) = ((n+k) - (m+k)) + ((m+k)-(n+k)) : refl _
... = (n - m) + ((m + k) - (n + k)) : {sub_add_add_right _ _ _}
... = (n - m) + (m - n) : {sub_add_add_right _ _ _}
theorem dist_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m
:= subst (add_comm m k) (subst (add_comm n k) (dist_add_right n k m))
theorem dist_ge_add_right {n m : ℕ} (H : n ≥ m) : dist n m + m = n
:= calc
dist n m + m = n - m + m : {dist_ge H}
... = n : add_sub_ge_left H
theorem dist_eq_intro {n m k l : ℕ} (H : n + m = k + l) : dist n k = dist l m
:= calc
dist n k = dist (n + m) (k + m) : symm (dist_add_right n m k)
... = dist (k + l) (k + m) : {H}
... = dist l m : dist_add_left k l m
end nat
end experiment
|
d5e071ecc0b22319042efc5920719e9d516669e8 | a4673261e60b025e2c8c825dfa4ab9108246c32e | /stage0/src/Lean/Data/Lsp/Hover.lean | 87cbf7c32226c1b2fcfe6ce57365a3df3f525d40 | [
"Apache-2.0"
] | permissive | jcommelin/lean4 | c02dec0cc32c4bccab009285475f265f17d73228 | 2909313475588cc20ac0436e55548a4502050d0a | refs/heads/master | 1,674,129,550,893 | 1,606,415,348,000 | 1,606,415,348,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,093 | lean | /-
Copyright (c) 2020 Wojciech Nawrocki. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Wojciech Nawrocki
-/
import Lean.Data.Json
import Lean.Data.Lsp.Basic
/-! Handling of mouse hover requests. -/
namespace Lean
namespace Lsp
open Json
structure Hover :=
/- NOTE we should also accept MarkedString/MarkedString[] here
but they are deprecated, so maybe can get away without. -/
(contents : MarkupContent)
(range? : Option Range := none)
instance : FromJson Hover := ⟨fun j => do
let contents ← j.getObjValAs? MarkupContent "contents"
let range? := j.getObjValAs? Range "range"
pure ⟨contents, range?⟩⟩
instance : ToJson Hover := ⟨fun o => mkObj $
⟨"contents", toJson o.contents⟩ ::
opt "range" o.range?⟩
structure HoverParams extends TextDocumentPositionParams
instance : FromJson HoverParams := ⟨fun j => do
let tdpp ← @fromJson? TextDocumentPositionParams _ j
pure ⟨tdpp⟩⟩
instance : ToJson HoverParams :=
⟨fun o => toJson o.toTextDocumentPositionParams⟩
end Lsp
end Lean
|
62b29b8eefb89bdbdd7081299167754720b0ce62 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/group_theory/specific_groups/cyclic.lean | de1bc886463bccbe91289946734cbaa17283951c | [
"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 | 22,309 | 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
-/
import algebra.big_operators.order
import data.nat.totient
import group_theory.order_of_element
import tactic.group
import group_theory.exponent
/-!
# Cyclic groups
A group `G` is called cyclic if there exists an element `g : G` such that every element of `G` is of
the form `g ^ n` for some `n : ℕ`. This file only deals with the predicate on a group to be cyclic.
For the concrete cyclic group of order `n`, see `data.zmod.basic`.
## Main definitions
* `is_cyclic` is a predicate on a group stating that the group is cyclic.
## Main statements
* `is_cyclic_of_prime_card` proves that a finite group of prime order is cyclic.
* `is_simple_group_of_prime_card`, `is_simple_group.is_cyclic`,
and `is_simple_group.prime_card` classify finite simple abelian groups.
* `is_cyclic.exponent_eq_card`: For a finite cyclic group `G`, the exponent is equal to
the group's cardinality.
* `is_cyclic.exponent_eq_zero_of_infinite`: Infinite cyclic groups have exponent zero.
* `is_cyclic.iff_exponent_eq_card`: A finite commutative group is cyclic iff its exponent
is equal to its cardinality.
## Tags
cyclic group
-/
universe u
variables {α : Type u} {a : α}
section cyclic
open_locale big_operators
local attribute [instance] set_fintype
open subgroup
/-- A group is called *cyclic* if it is generated by a single element. -/
class is_add_cyclic (α : Type u) [add_group α] : Prop :=
(exists_generator [] : ∃ g : α, ∀ x, x ∈ add_subgroup.zmultiples g)
/-- A group is called *cyclic* if it is generated by a single element. -/
@[to_additive is_add_cyclic] class is_cyclic (α : Type u) [group α] : Prop :=
(exists_generator [] : ∃ g : α, ∀ x, x ∈ zpowers g)
@[priority 100, to_additive is_add_cyclic_of_subsingleton]
instance is_cyclic_of_subsingleton [group α] [subsingleton α] : is_cyclic α :=
⟨⟨1, λ x, by { rw subsingleton.elim x 1, exact mem_zpowers 1 }⟩⟩
/-- A cyclic group is always commutative. This is not an `instance` because often we have a better
proof of `comm_group`. -/
@[to_additive "A cyclic group is always commutative. This is not an `instance` because often we have
a better proof of `add_comm_group`."]
def is_cyclic.comm_group [hg : group α] [is_cyclic α] : comm_group α :=
{ mul_comm := λ x y,
let ⟨g, hg⟩ := is_cyclic.exists_generator α,
⟨n, hn⟩ := hg x,
⟨m, hm⟩ := hg y in
hm ▸ hn ▸ zpow_mul_comm _ _ _,
..hg }
variables [group α]
@[to_additive monoid_add_hom.map_add_cyclic]
lemma monoid_hom.map_cyclic {G : Type*} [group G] [h : is_cyclic G] (σ : G →* G) :
∃ m : ℤ, ∀ g : G, σ g = g ^ m :=
begin
obtain ⟨h, hG⟩ := is_cyclic.exists_generator G,
obtain ⟨m, hm⟩ := hG (σ h),
refine ⟨m, λ g, _⟩,
obtain ⟨n, rfl⟩ := hG g,
rw [monoid_hom.map_zpow, ←hm, ←zpow_mul, ←zpow_mul'],
end
@[to_additive is_add_cyclic_of_order_of_eq_card]
lemma is_cyclic_of_order_of_eq_card [fintype α] (x : α)
(hx : order_of x = fintype.card α) : is_cyclic α :=
begin
classical,
use x,
simp_rw [← set_like.mem_coe, ← set.eq_univ_iff_forall],
rw [←fintype.card_congr (equiv.set.univ α), order_eq_card_zpowers] at hx,
exact set.eq_of_subset_of_card_le (set.subset_univ _) (ge_of_eq hx),
end
/-- A finite group of prime order is cyclic. -/
@[to_additive is_add_cyclic_of_prime_card "A finite group of prime order is cyclic."]
lemma is_cyclic_of_prime_card {α : Type u} [group α] [fintype α] {p : ℕ} [hp : fact p.prime]
(h : fintype.card α = p) : is_cyclic α :=
⟨begin
obtain ⟨g, hg⟩ : ∃ g : α, g ≠ 1 := fintype.exists_ne_of_one_lt_card (h.symm ▸ hp.1.one_lt) 1,
classical, -- for fintype (subgroup.zpowers g)
have : fintype.card (subgroup.zpowers g) ∣ p,
{ rw ←h,
apply card_subgroup_dvd_card },
rw nat.dvd_prime hp.1 at this,
cases this,
{ rw fintype.card_eq_one_iff at this,
cases this with t ht,
suffices : g = 1,
{ contradiction },
have hgt := ht ⟨g, by { change g ∈ subgroup.zpowers g, exact subgroup.mem_zpowers g }⟩,
rw [←ht 1] at hgt,
change (⟨_, _⟩ : subgroup.zpowers g) = ⟨_, _⟩ at hgt,
simpa using hgt },
{ use g,
intro x,
rw [←h] at this,
rw subgroup.eq_top_of_card_eq _ this,
exact subgroup.mem_top _ }
end⟩
@[to_additive add_order_of_eq_card_of_forall_mem_zmultiples]
lemma order_of_eq_card_of_forall_mem_zpowers [fintype α]
{g : α} (hx : ∀ x, x ∈ zpowers g) : order_of g = fintype.card α :=
begin
classical,
rw order_eq_card_zpowers,
apply fintype.card_of_finset',
simpa using hx
end
@[to_additive infinite.add_order_of_eq_zero_of_forall_mem_zmultiples]
lemma infinite.order_of_eq_zero_of_forall_mem_zpowers [infinite α] {g : α}
(h : ∀ x, x ∈ zpowers g) : order_of g = 0 :=
begin
classical,
rw order_of_eq_zero_iff',
refine λ n hn hgn, _,
have ho := order_of_pos' ((is_of_fin_order_iff_pow_eq_one g).mpr ⟨n, hn, hgn⟩),
obtain ⟨x, hx⟩ := infinite.exists_not_mem_finset
(finset.image (pow g) $ finset.range $ order_of g),
apply hx,
rw [←mem_powers_iff_mem_range_order_of' g x ho, submonoid.mem_powers_iff],
obtain ⟨k, hk⟩ := h x,
obtain ⟨k, rfl | rfl⟩ := k.eq_coe_or_neg,
{ exact ⟨k, by exact_mod_cast hk⟩ },
let t : ℤ := -k % (order_of g),
rw zpow_eq_mod_order_of at hk,
have : 0 ≤ t := int.mod_nonneg (-k) (by exact_mod_cast ho.ne'),
refine ⟨t.to_nat, _⟩,
rwa [←zpow_coe_nat, int.to_nat_of_nonneg this]
end
@[to_additive bot.is_add_cyclic]
instance bot.is_cyclic {α : Type u} [group α] : is_cyclic (⊥ : subgroup α) :=
⟨⟨1, λ x, ⟨0, subtype.eq $ (zpow_zero (1 : α)).trans $ eq.symm (subgroup.mem_bot.1 x.2)⟩⟩⟩
@[to_additive add_subgroup.is_add_cyclic]
instance subgroup.is_cyclic {α : Type u} [group α] [is_cyclic α] (H : subgroup α) : is_cyclic H :=
by haveI := classical.prop_decidable; exact
let ⟨g, hg⟩ := is_cyclic.exists_generator α in
if hx : ∃ (x : α), x ∈ H ∧ x ≠ (1 : α) then
let ⟨x, hx₁, hx₂⟩ := hx in
let ⟨k, hk⟩ := hg x in
have hex : ∃ n : ℕ, 0 < n ∧ g ^ n ∈ H,
from ⟨k.nat_abs, nat.pos_of_ne_zero
(λ h, hx₂ $ by rw [← hk, int.eq_zero_of_nat_abs_eq_zero h, zpow_zero]),
match k, hk with
| (k : ℕ), hk := by rw [int.nat_abs_of_nat, ← zpow_coe_nat, hk]; exact hx₁
| -[1+ k], hk := by rw [int.nat_abs_of_neg_succ_of_nat,
← subgroup.inv_mem_iff H]; simp * at *
end⟩,
⟨⟨⟨g ^ nat.find hex, (nat.find_spec hex).2⟩,
λ ⟨x, hx⟩, let ⟨k, hk⟩ := hg x in
have hk₁ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ zpowers (g ^ nat.find hex),
from ⟨k / nat.find hex, by rw [← zpow_coe_nat, zpow_mul]⟩,
have hk₂ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ H,
by { rw zpow_mul, apply H.zpow_mem, exact_mod_cast (nat.find_spec hex).2 },
have hk₃ : g ^ (k % nat.find hex) ∈ H,
from (subgroup.mul_mem_cancel_right H hk₂).1 $
by rw [← zpow_add, int.mod_add_div, hk]; exact hx,
have hk₄ : k % nat.find hex = (k % nat.find hex).nat_abs,
by rw int.nat_abs_of_nonneg (int.mod_nonneg _
(int.coe_nat_ne_zero_iff_pos.2 (nat.find_spec hex).1)),
have hk₅ : g ^ (k % nat.find hex ).nat_abs ∈ H,
by rwa [← zpow_coe_nat, ← hk₄],
have hk₆ : (k % (nat.find hex : ℤ)).nat_abs = 0,
from by_contradiction (λ h,
nat.find_min hex (int.coe_nat_lt.1 $ by rw [← hk₄];
exact int.mod_lt_of_pos _ (int.coe_nat_pos.2 (nat.find_spec hex).1))
⟨nat.pos_of_ne_zero h, hk₅⟩),
⟨k / (nat.find hex : ℤ), subtype.ext_iff_val.2 begin
suffices : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) = x,
{ simpa [zpow_mul] },
rw [int.mul_div_cancel' (int.dvd_of_mod_eq_zero (int.eq_zero_of_nat_abs_eq_zero hk₆)), hk]
end⟩⟩⟩
else
have H = (⊥ : subgroup α), from subgroup.ext $ λ x, ⟨λ h, by simp at *; tauto,
λ h, by rw [subgroup.mem_bot.1 h]; exact H.one_mem⟩,
by clear _let_match; substI this; apply_instance
open finset nat
section classical
open_locale classical
@[to_additive is_add_cyclic.card_pow_eq_one_le]
lemma is_cyclic.card_pow_eq_one_le [decidable_eq α] [fintype α] [is_cyclic α] {n : ℕ}
(hn0 : 0 < n) : (univ.filter (λ a : α, a ^ n = 1)).card ≤ n :=
let ⟨g, hg⟩ := is_cyclic.exists_generator α in
calc (univ.filter (λ a : α, a ^ n = 1)).card
≤ ((zpowers (g ^ (fintype.card α / (nat.gcd n (fintype.card α))))) : set α).to_finset.card :
card_le_of_subset (λ x hx, let ⟨m, hm⟩ := show x ∈ submonoid.powers g,
from mem_powers_iff_mem_zpowers.2 $ hg x in
set.mem_to_finset.2 ⟨(m / (fintype.card α / (nat.gcd n (fintype.card α))) : ℕ),
have hgmn : g ^ (m * nat.gcd n (fintype.card α)) = 1,
by rw [pow_mul, hm, ← pow_gcd_card_eq_one_iff]; exact (mem_filter.1 hx).2,
begin
rw [zpow_coe_nat, ← pow_mul, nat.mul_div_cancel_left', hm],
refine dvd_of_mul_dvd_mul_right (gcd_pos_of_pos_left (fintype.card α) hn0) _,
conv_lhs
{ rw [nat.div_mul_cancel (nat.gcd_dvd_right _ _),
←order_of_eq_card_of_forall_mem_zpowers hg] },
exact order_of_dvd_of_pow_eq_one hgmn
end⟩)
... ≤ n :
let ⟨m, hm⟩ := nat.gcd_dvd_right n (fintype.card α) in
have hm0 : 0 < m, from nat.pos_of_ne_zero $
λ hm0, by { rw [hm0, mul_zero, fintype.card_eq_zero_iff] at hm, exact hm.elim' 1 },
begin
simp only [set.to_finset_card, set_like.coe_sort_coe],
rw [←order_eq_card_zpowers, order_of_pow g, order_of_eq_card_of_forall_mem_zpowers hg],
rw [hm] {occs := occurrences.pos [2,3]},
rw [nat.mul_div_cancel_left _ (gcd_pos_of_pos_left _ hn0), gcd_mul_left_left,
hm, nat.mul_div_cancel _ hm0],
exact le_of_dvd hn0 (nat.gcd_dvd_left _ _)
end
end classical
@[to_additive]
lemma is_cyclic.exists_monoid_generator [finite α] [is_cyclic α] :
∃ x : α, ∀ y : α, y ∈ submonoid.powers x :=
by { simp_rw [mem_powers_iff_mem_zpowers], exact is_cyclic.exists_generator α }
section
variables [decidable_eq α] [fintype α]
@[to_additive]
lemma is_cyclic.image_range_order_of (ha : ∀ x : α, x ∈ zpowers a) :
finset.image (λ i, a ^ i) (range (order_of a)) = univ :=
begin
simp_rw [←set_like.mem_coe] at ha,
simp only [image_range_order_of, set.eq_univ_iff_forall.mpr ha, set.to_finset_univ],
end
@[to_additive]
lemma is_cyclic.image_range_card (ha : ∀ x : α, x ∈ zpowers a) :
finset.image (λ i, a ^ i) (range (fintype.card α)) = univ :=
by rw [← order_of_eq_card_of_forall_mem_zpowers ha, is_cyclic.image_range_order_of ha]
end
section totient
variables [decidable_eq α] [fintype α]
(hn : ∀ n : ℕ, 0 < n → (univ.filter (λ a : α, a ^ n = 1)).card ≤ n)
include hn
private lemma card_pow_eq_one_eq_order_of_aux (a : α) :
(finset.univ.filter (λ b : α, b ^ order_of a = 1)).card = order_of a :=
le_antisymm
(hn _ (order_of_pos a))
(calc order_of a = @fintype.card (zpowers a) (id _) : order_eq_card_zpowers
... ≤ @fintype.card (↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α)
(fintype.of_finset _ (λ _, iff.rfl)) :
@fintype.card_le_of_injective (zpowers a)
(↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α)
(id _) (id _) (λ b, ⟨b.1, mem_filter.2 ⟨mem_univ _,
let ⟨i, hi⟩ := b.2 in
by rw [← hi, ← zpow_coe_nat, ← zpow_mul, mul_comm, zpow_mul, zpow_coe_nat,
pow_order_of_eq_one, one_zpow]⟩⟩) (λ _ _ h, subtype.eq (subtype.mk.inj h))
... = (univ.filter (λ b : α, b ^ order_of a = 1)).card : fintype.card_of_finset _ _)
open_locale nat -- use φ for nat.totient
private lemma card_order_of_eq_totient_aux₁ :
∀ {d : ℕ}, d ∣ fintype.card α → 0 < (univ.filter (λ a : α, order_of a = d)).card →
(univ.filter (λ a : α, order_of a = d)).card = φ d :=
begin
intros d hd hd0,
induction d using nat.strong_rec' with d IH,
rcases d.eq_zero_or_pos with rfl | hd_pos,
{ cases fintype.card_ne_zero (eq_zero_of_zero_dvd hd) },
rcases card_pos.1 hd0 with ⟨a, ha'⟩,
have ha : order_of a = d := (mem_filter.1 ha').2,
have h1 : ∑ m in d.proper_divisors, (univ.filter (λ a : α, order_of a = m)).card =
∑ m in d.proper_divisors, φ m,
{ refine finset.sum_congr rfl (λ m hm, _),
simp only [mem_filter, mem_range, mem_proper_divisors] at hm,
refine IH m hm.2 (hm.1.trans hd) (finset.card_pos.2 ⟨a ^ (d / m), _⟩),
simp only [mem_filter, mem_univ, order_of_pow a, ha, true_and,
nat.gcd_eq_right (div_dvd_of_dvd hm.1), nat.div_div_self hm.1 hd_pos.ne'] },
have h2 : ∑ m in d.divisors, (univ.filter (λ a : α, order_of a = m)).card =
∑ m in d.divisors, φ m,
{ rw [←filter_dvd_eq_divisors hd_pos.ne', sum_card_order_of_eq_card_pow_eq_one hd_pos,
filter_dvd_eq_divisors hd_pos.ne', sum_totient, ←ha, card_pow_eq_one_eq_order_of_aux hn a] },
simpa [divisors_eq_proper_divisors_insert_self_of_pos hd_pos, ←h1] using h2,
end
lemma card_order_of_eq_totient_aux₂ {d : ℕ} (hd : d ∣ fintype.card α) :
(univ.filter (λ a : α, order_of a = d)).card = φ d :=
begin
let c := fintype.card α,
have hc0 : 0 < c := fintype.card_pos_iff.2 ⟨1⟩,
apply card_order_of_eq_totient_aux₁ hn hd,
by_contradiction h0,
simp only [not_lt, _root_.le_zero_iff, card_eq_zero] at h0,
apply lt_irrefl c,
calc
c = ∑ m in c.divisors, (univ.filter (λ a : α, order_of a = m)).card : by
{ simp only [←filter_dvd_eq_divisors hc0.ne', sum_card_order_of_eq_card_pow_eq_one hc0],
apply congr_arg card,
simp }
... = ∑ m in c.divisors.erase d, (univ.filter (λ a : α, order_of a = m)).card : by
{ rw eq_comm,
refine (sum_subset (erase_subset _ _) (λ m hm₁ hm₂, _)),
have : m = d, by { contrapose! hm₂, exact mem_erase_of_ne_of_mem hm₂ hm₁ },
simp [this, h0] }
... ≤ ∑ m in c.divisors.erase d, φ m : by
{ refine sum_le_sum (λ m hm, _),
have hmc : m ∣ c, { simp only [mem_erase, mem_divisors] at hm, tauto },
rcases (filter (λ (a : α), order_of a = m) univ).card.eq_zero_or_pos with h1 | h1,
{ simp [h1] }, { simp [card_order_of_eq_totient_aux₁ hn hmc h1] } }
... < ∑ m in c.divisors, φ m :
sum_erase_lt_of_pos (mem_divisors.2 ⟨hd, hc0.ne'⟩) (totient_pos (pos_of_dvd_of_pos hd hc0))
... = c : sum_totient _
end
lemma is_cyclic_of_card_pow_eq_one_le : is_cyclic α :=
have (univ.filter (λ a : α, order_of a = fintype.card α)).nonempty,
from (card_pos.1 $
by rw [card_order_of_eq_totient_aux₂ hn dvd_rfl];
exact totient_pos (fintype.card_pos_iff.2 ⟨1⟩)),
let ⟨x, hx⟩ := this in
is_cyclic_of_order_of_eq_card x (finset.mem_filter.1 hx).2
lemma is_add_cyclic_of_card_pow_eq_one_le {α} [add_group α] [decidable_eq α] [fintype α]
(hn : ∀ n : ℕ, 0 < n → (univ.filter (λ a : α, n • a = 0)).card ≤ n) : is_add_cyclic α :=
begin
obtain ⟨g, hg⟩ := @is_cyclic_of_card_pow_eq_one_le (multiplicative α) _ _ _ hn,
exact ⟨⟨g, hg⟩⟩
end
attribute [to_additive is_cyclic_of_card_pow_eq_one_le] is_add_cyclic_of_card_pow_eq_one_le
end totient
lemma is_cyclic.card_order_of_eq_totient [is_cyclic α] [fintype α]
{d : ℕ} (hd : d ∣ fintype.card α) : (univ.filter (λ a : α, order_of a = d)).card = totient d :=
begin
classical,
apply card_order_of_eq_totient_aux₂ (λ n, is_cyclic.card_pow_eq_one_le) hd
end
lemma is_add_cyclic.card_order_of_eq_totient {α} [add_group α] [is_add_cyclic α] [fintype α] {d : ℕ}
(hd : d ∣ fintype.card α) : (univ.filter (λ a : α, add_order_of a = d)).card = totient d :=
begin
obtain ⟨g, hg⟩ := id ‹is_add_cyclic α›,
exact @is_cyclic.card_order_of_eq_totient (multiplicative α) _ ⟨⟨g, hg⟩⟩ _ _ hd
end
attribute [to_additive is_cyclic.card_order_of_eq_totient] is_add_cyclic.card_order_of_eq_totient
/-- A finite group of prime order is simple. -/
@[to_additive "A finite group of prime order is simple."]
lemma is_simple_group_of_prime_card {α : Type u} [group α] [fintype α] {p : ℕ} [hp : fact p.prime]
(h : fintype.card α = p) : is_simple_group α :=
⟨begin
have h' := nat.prime.one_lt (fact.out p.prime),
rw ← h at h',
haveI := fintype.one_lt_card_iff_nontrivial.1 h',
apply exists_pair_ne α,
end, λ H Hn, begin
classical,
have hcard := card_subgroup_dvd_card H,
rw [h, dvd_prime (fact.out p.prime)] at hcard,
refine hcard.imp (λ h1, _) (λ hp, _),
{ haveI := fintype.card_le_one_iff_subsingleton.1 (le_of_eq h1),
apply eq_bot_of_subsingleton },
{ exact eq_top_of_card_eq _ (hp.trans h.symm) }
end⟩
end cyclic
section quotient_center
open subgroup
variables {G : Type*} {H : Type*} [group G] [group H]
/-- A group is commutative if the quotient by the center is cyclic.
Also see `comm_group_of_cycle_center_quotient` for the `comm_group` instance. -/
@[to_additive commutative_of_add_cyclic_center_quotient "A group is commutative if the quotient by
the center is cyclic. Also see `add_comm_group_of_cycle_center_quotient`
for the `add_comm_group` instance."]
lemma commutative_of_cyclic_center_quotient [is_cyclic H] (f : G →* H)
(hf : f.ker ≤ center G) (a b : G) : a * b = b * a :=
let ⟨⟨x, y, (hxy : f y = x)⟩, (hx : ∀ a : f.range, a ∈ zpowers _)⟩ :=
is_cyclic.exists_generator f.range in
let ⟨m, hm⟩ := hx ⟨f a, a, rfl⟩ in
let ⟨n, hn⟩ := hx ⟨f b, b, rfl⟩ in
have hm : x ^ m = f a, by simpa [subtype.ext_iff] using hm,
have hn : x ^ n = f b, by simpa [subtype.ext_iff] using hn,
have ha : y ^ (-m) * a ∈ center G,
from hf (by rw [f.mem_ker, f.map_mul, f.map_zpow, hxy, zpow_neg, hm, inv_mul_self]),
have hb : y ^ (-n) * b ∈ center G,
from hf (by rw [f.mem_ker, f.map_mul, f.map_zpow, hxy, zpow_neg, hn, inv_mul_self]),
calc a * b = y ^ m * ((y ^ (-m) * a) * y ^ n) * (y ^ (-n) * b) : by simp [mul_assoc]
... = y ^ m * (y ^ n * (y ^ (-m) * a)) * (y ^ (-n) * b) : by rw [mem_center_iff.1 ha]
... = y ^ m * y ^ n * y ^ (-m) * (a * (y ^ (-n) * b)) : by simp [mul_assoc]
... = y ^ m * y ^ n * y ^ (-m) * ((y ^ (-n) * b) * a) : by rw [mem_center_iff.1 hb]
... = b * a : by group
/-- A group is commutative if the quotient by the center is cyclic. -/
@[to_additive commutative_of_add_cycle_center_quotient "A group is commutative if the quotient by
the center is cyclic."]
def comm_group_of_cycle_center_quotient [is_cyclic H] (f : G →* H)
(hf : f.ker ≤ center G) : comm_group G :=
{ mul_comm := commutative_of_cyclic_center_quotient f hf,
..show group G, by apply_instance }
end quotient_center
namespace is_simple_group
section comm_group
variables [comm_group α] [is_simple_group α]
@[priority 100, to_additive is_simple_add_group.is_add_cyclic]
instance : is_cyclic α :=
begin
cases subsingleton_or_nontrivial α with hi hi; haveI := hi,
{ apply is_cyclic_of_subsingleton },
{ obtain ⟨g, hg⟩ := exists_ne (1 : α),
refine ⟨⟨g, λ x, _⟩⟩,
cases is_simple_order.eq_bot_or_eq_top (subgroup.zpowers g) with hb ht,
{ exfalso,
apply hg,
rw [← subgroup.mem_bot, ← hb],
apply subgroup.mem_zpowers },
{ rw ht,
apply subgroup.mem_top } }
end
@[to_additive]
theorem prime_card [fintype α] : (fintype.card α).prime :=
begin
have h0 : 0 < fintype.card α := fintype.card_pos_iff.2 (by apply_instance),
obtain ⟨g, hg⟩ := is_cyclic.exists_generator α,
rw nat.prime_def_lt'',
refine ⟨fintype.one_lt_card_iff_nontrivial.2 infer_instance, λ n hn, _⟩,
refine (is_simple_order.eq_bot_or_eq_top (subgroup.zpowers (g ^ n))).symm.imp _ _,
{ intro h,
have hgo := order_of_pow g,
rw [order_of_eq_card_of_forall_mem_zpowers hg, nat.gcd_eq_right_iff_dvd.1 hn,
order_of_eq_card_of_forall_mem_zpowers, eq_comm,
nat.div_eq_iff_eq_mul_left (nat.pos_of_dvd_of_pos hn h0) hn] at hgo,
{ exact (mul_left_cancel₀ (ne_of_gt h0) ((mul_one (fintype.card α)).trans hgo)).symm },
{ intro x,
rw h,
exact subgroup.mem_top _ } },
{ intro h,
apply le_antisymm (nat.le_of_dvd h0 hn),
rw ← order_of_eq_card_of_forall_mem_zpowers hg,
apply order_of_le_of_pow_eq_one (nat.pos_of_dvd_of_pos hn h0),
rw [← subgroup.mem_bot, ← h],
exact subgroup.mem_zpowers _ }
end
end comm_group
end is_simple_group
@[to_additive add_comm_group.is_simple_iff_is_add_cyclic_and_prime_card]
theorem comm_group.is_simple_iff_is_cyclic_and_prime_card [fintype α] [comm_group α] :
is_simple_group α ↔ is_cyclic α ∧ (fintype.card α).prime :=
begin
split,
{ introI h,
exact ⟨is_simple_group.is_cyclic, is_simple_group.prime_card⟩ },
{ rintro ⟨hc, hp⟩,
haveI : fact (fintype.card α).prime := ⟨hp⟩,
exact is_simple_group_of_prime_card rfl }
end
section exponent
open monoid
@[to_additive] lemma is_cyclic.exponent_eq_card [group α] [is_cyclic α] [fintype α] :
exponent α = fintype.card α :=
begin
obtain ⟨g, hg⟩ := is_cyclic.exists_generator α,
apply nat.dvd_antisymm,
{ rw [←lcm_order_eq_exponent, finset.lcm_dvd_iff],
exact λ b _, order_of_dvd_card_univ },
rw ←order_of_eq_card_of_forall_mem_zpowers hg,
exact order_dvd_exponent _
end
@[to_additive] lemma is_cyclic.of_exponent_eq_card [comm_group α] [fintype α]
(h : exponent α = fintype.card α) : is_cyclic α :=
let ⟨g, _, hg⟩ := finset.mem_image.mp (finset.max'_mem _ _) in
is_cyclic_of_order_of_eq_card g $ hg.trans $ exponent_eq_max'_order_of.symm.trans h
@[to_additive] lemma is_cyclic.iff_exponent_eq_card [comm_group α] [fintype α] :
is_cyclic α ↔ exponent α = fintype.card α :=
⟨λ h, by exactI is_cyclic.exponent_eq_card, is_cyclic.of_exponent_eq_card⟩
@[to_additive] lemma is_cyclic.exponent_eq_zero_of_infinite [group α] [is_cyclic α] [infinite α] :
exponent α = 0 :=
let ⟨g, hg⟩ := is_cyclic.exists_generator α in
exponent_eq_zero_of_order_zero $ infinite.order_of_eq_zero_of_forall_mem_zpowers hg
end exponent
|
d401dc68f0ba5fe34fae1f6bd2db1a4027d88b90 | 367134ba5a65885e863bdc4507601606690974c1 | /src/analysis/convex/extrema.lean | 00a9ca47fd0b8b73fd9ddb3706184e7fa419de65 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 5,432 | lean | /-
Copyright (c) 2020 Frédéric Dupuis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Frédéric Dupuis
-/
import analysis.calculus.local_extr
import topology.algebra.affine
/-!
# Minima and maxima of convex functions
We show that if a function `f : E → β` is convex, then a local minimum is also
a global minimum, and likewise for concave functions.
-/
variables {E β: Type*} [add_comm_group E] [topological_space E]
[module ℝ E] [topological_add_group E] [topological_vector_space ℝ E]
[linear_ordered_add_comm_group β] [semimodule ℝ β] [ordered_semimodule ℝ β]
{s : set E}
open set filter
open_locale classical
/--
Helper lemma for the more general case: `is_min_on.of_is_local_min_on_of_convex_on`.
-/
lemma is_min_on.of_is_local_min_on_of_convex_on_Icc {f : ℝ → β} {a b : ℝ}
(a_lt_b : a < b) (h_local_min : is_local_min_on f (Icc a b) a) (h_conv : convex_on (Icc a b) f) :
∀ x ∈ Icc a b, f a ≤ f x :=
begin
by_contradiction H_cont,
push_neg at H_cont,
rcases H_cont with ⟨x, ⟨h_ax, h_xb⟩, fx_lt_fa⟩,
obtain ⟨z, hz, ge_on_nhd⟩ : ∃ z > a, ∀ y ∈ (Icc a z), f y ≥ f a,
{ rcases eventually_iff_exists_mem.mp h_local_min with ⟨U, U_in_nhds_within, fy_ge_fa⟩,
rw [nhds_within_Icc_eq_nhds_within_Ici a_lt_b, mem_nhds_within_Ici_iff_exists_Icc_subset]
at U_in_nhds_within,
rcases U_in_nhds_within with ⟨ε, ε_in_Ioi, Ioc_in_U⟩,
exact ⟨ε, mem_Ioi.mp ε_in_Ioi, λ y y_in_Ioc, fy_ge_fa y $ Ioc_in_U y_in_Ioc⟩ },
have a_lt_x : a < x := lt_of_le_of_ne h_ax (λ H, by subst H; exact lt_irrefl (f a) fx_lt_fa),
have lt_on_nhd : ∀ y ∈ Ioc a x, f y < f a,
{ intros y y_in_Ioc,
rcases (convex.mem_Ioc a_lt_x).mp y_in_Ioc with ⟨ya, yx, ya_pos, yx_pos, yax, y_combo⟩,
calc
f y = f (ya * a + yx * x) : by rw [y_combo]
... ≤ ya • f a + yx • f x
: h_conv.2 (left_mem_Icc.mpr (le_of_lt a_lt_b)) ⟨h_ax, h_xb⟩ (ya_pos)
(le_of_lt yx_pos) yax
... < ya • f a + yx • f a : add_lt_add_left (smul_lt_smul_of_pos fx_lt_fa yx_pos) _
... = f a : by rw [←add_smul, yax, one_smul] },
by_cases h_xz : x ≤ z,
{ exact not_lt_of_ge (ge_on_nhd x (show x ∈ Icc a z, by exact ⟨h_ax, h_xz⟩)) fx_lt_fa, },
{ have h₁ : z ∈ Ioc a x := ⟨hz, le_of_not_ge h_xz⟩,
have h₂ : z ∈ Icc a z := ⟨le_of_lt hz, le_refl z⟩,
exact not_lt_of_ge (ge_on_nhd z h₂) (lt_on_nhd z h₁) }
end
/--
A local minimum of a convex function is a global minimum, restricted to a set `s`.
-/
lemma is_min_on.of_is_local_min_on_of_convex_on {f : E → β} {a : E}
(a_in_s : a ∈ s) (h_localmin: is_local_min_on f s a) (h_conv : convex_on s f) :
∀ x ∈ s, f a ≤ f x :=
begin
by_contradiction H_cont,
push_neg at H_cont,
rcases H_cont with ⟨x, ⟨x_in_s, fx_lt_fa⟩⟩,
let g : ℝ →ᵃ[ℝ] E := affine_map.line_map a x,
have hg0 : g 0 = a := affine_map.line_map_apply_zero a x,
have hg1 : g 1 = x := affine_map.line_map_apply_one a x,
have fg_local_min_on : is_local_min_on (f ∘ g) (g ⁻¹' s) 0,
{ rw ←hg0 at h_localmin,
refine is_local_min_on.comp_continuous_on h_localmin subset.rfl
(continuous.continuous_on (affine_map.line_map_continuous)) _,
simp [mem_preimage, hg0, a_in_s] },
have fg_min_on : ∀ x ∈ (Icc 0 1 : set ℝ), (f ∘ g) 0 ≤ (f ∘ g) x,
{ have Icc_in_s' : Icc 0 1 ⊆ (g ⁻¹' s),
{ have h0 : (0 : ℝ) ∈ (g ⁻¹' s) := by simp [mem_preimage, a_in_s],
have h1 : (1 : ℝ) ∈ (g ⁻¹' s) := by simp [mem_preimage, hg1, x_in_s],
rw ←segment_eq_Icc (show (0 : ℝ) ≤ 1, by linarith),
exact (convex.affine_preimage g h_conv.1).segment_subset
(by simp [mem_preimage, hg0, a_in_s]) (by simp [mem_preimage, hg1, x_in_s]) },
have fg_local_min_on' : is_local_min_on (f ∘ g) (Icc 0 1) 0 :=
is_local_min_on.on_subset fg_local_min_on Icc_in_s',
refine is_min_on.of_is_local_min_on_of_convex_on_Icc (by linarith) fg_local_min_on' _,
exact (convex_on.comp_affine_map g h_conv).subset Icc_in_s' (convex_Icc 0 1) },
have gx_lt_ga : (f ∘ g) 1 < (f ∘ g) 0 := by simp [hg1, fx_lt_fa, hg0],
exact not_lt_of_ge (fg_min_on 1 (mem_Icc.mpr ⟨zero_le_one, le_refl 1⟩)) gx_lt_ga,
end
/-- A local maximum of a concave function is a global maximum, restricted to a set `s`. -/
lemma is_max_on.of_is_local_max_on_of_concave_on {f : E → β} {a : E}
(a_in_s : a ∈ s) (h_localmax: is_local_max_on f s a) (h_conc : concave_on s f) :
∀ x ∈ s, f x ≤ f a :=
@is_min_on.of_is_local_min_on_of_convex_on
_ (order_dual β) _ _ _ _ _ _ _ _ s f a a_in_s h_localmax h_conc
/-- A local minimum of a convex function is a global minimum. -/
lemma is_min_on.of_is_local_min_of_convex_univ {f : E → β} {a : E}
(h_local_min : is_local_min f a) (h_conv : convex_on univ f) : ∀ x, f a ≤ f x :=
λ x, (is_min_on.of_is_local_min_on_of_convex_on (mem_univ a)
(is_local_min.on h_local_min univ) h_conv) x (mem_univ x)
/-- A local maximum of a concave function is a global maximum. -/
lemma is_max_on.of_is_local_max_of_convex_univ {f : E → β} {a : E}
(h_local_max : is_local_max f a) (h_conc : concave_on univ f) : ∀ x, f x ≤ f a :=
@is_min_on.of_is_local_min_of_convex_univ _ (order_dual β) _ _ _ _ _ _ _ _ f a h_local_max h_conc
|
042047871ca8b4d81c140c7fa16f116454f1ffee | b32d3853770e6eaf06817a1b8c52064baaed0ef1 | /src/super/inferences/factoring.lean | 45cb7ac8851240f78fb5e044adbc728b23addaf9 | [] | no_license | gebner/super2 | 4d58b7477b6f7d945d5d866502982466db33ab0b | 9bc5256c31750021ab97d6b59b7387773e54b384 | refs/heads/master | 1,635,021,682,021 | 1,634,886,326,000 | 1,634,886,326,000 | 225,600,688 | 4 | 2 | null | 1,598,209,306,000 | 1,575,371,550,000 | Lean | UTF-8 | Lean | false | false | 378 | lean | import super.prover_state
namespace super
open tactic
meta def inference.factoring : inference_rule | given :=
retrieve_packed $ do
(l1, i1) ← given.cls.literals.zip_with_index,
(l2, i2) ← given.cls.literals.zip_with_index,
guard $ i1 < i2,
guard $ l1.is_pos = l2.is_pos,
pure $ do
some () ← try_core (unify l1.formula l2.formula) | pure [],
pure [given.cls]
end super
|
fc33c232293f94d70db4eec6e6eee4ff22375c80 | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /src/data/set/lattice.lean | 336903df07e2cd06a660273568aa908f6df4d992 | [
"Apache-2.0"
] | permissive | kmill/mathlib | ea5a007b67ae4e9e18dd50d31d8aa60f650425ee | 1a419a9fea7b959317eddd556e1bb9639f4dcc05 | refs/heads/master | 1,668,578,197,719 | 1,593,629,163,000 | 1,593,629,163,000 | 276,482,939 | 0 | 0 | null | 1,593,637,960,000 | 1,593,637,959,000 | null | UTF-8 | Lean | false | false | 37,322 | 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, Johannes Hölzl, Mario Carneiro
-- QUESTION: can make the first argument in ∀ x ∈ a, ... implicit?
-/
import order.complete_boolean_algebra
import data.sigma.basic
import order.galois_connection
open function tactic set auto
universes u v w x y
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {ι' : Sort y}
namespace set
instance lattice_set : complete_lattice (set α) :=
{ le := (⊆),
lt := (⊂),
sup := (∪),
inf := (∩),
top := univ,
bot := ∅,
Sup := λs, {a | ∃ t ∈ s, a ∈ t },
Inf := λs, {a | ∀ t ∈ s, a ∈ t },
le_Sup := assume s t t_in a a_in, ⟨t, ⟨t_in, a_in⟩⟩,
Sup_le := assume s t h a ⟨t', ⟨t'_in, a_in⟩⟩, h t' t'_in a_in,
le_Inf := assume s t h a a_in t' t'_in, h t' t'_in a_in,
Inf_le := assume s t t_in a h, h _ t_in,
.. (infer_instance : complete_lattice (α → Prop)) }
instance : distrib_lattice (set α) :=
{ le_sup_inf := λ s t u x, or_and_distrib_left.2, ..set.lattice_set }
@[simp] lemma bot_eq_empty : (⊥ : set α) = ∅ := rfl
@[simp] lemma sup_eq_union (s t : set α) : s ⊔ t = s ∪ t := rfl
@[simp] lemma inf_eq_inter (s t : set α) : s ⊓ t = s ∩ t := rfl
@[simp] lemma le_eq_subset (s t : set α) : s ≤ t = (s ⊆ t) := rfl
@[simp] lemma lt_eq_ssubset (s t : set α) : s < t = (s ⊂ t) := rfl
/-- Image is monotone. See `set.image_image` for the statement in terms of `⊆`. -/
lemma monotone_image {f : α → β} : monotone (image f) :=
assume s t, assume h : s ⊆ t, image_subset _ h
theorem monotone_inter [preorder β] {f g : β → set α}
(hf : monotone f) (hg : monotone g) : monotone (λx, f x ∩ g x) :=
assume b₁ b₂ h, inter_subset_inter (hf h) (hg h)
theorem monotone_union [preorder β] {f g : β → set α}
(hf : monotone f) (hg : monotone g) : monotone (λx, f x ∪ g x) :=
assume b₁ b₂ h, union_subset_union (hf h) (hg h)
theorem monotone_set_of [preorder α] {p : α → β → Prop}
(hp : ∀b, monotone (λa, p a b)) : monotone (λa, {b | p a b}) :=
assume a a' h b, hp b h
section galois_connection
variables {f : α → β}
protected lemma image_preimage : galois_connection (image f) (preimage f) :=
assume a b, image_subset_iff
/-- `kern_image f s` is the set of `y` such that `f ⁻¹ y ⊆ s` -/
def kern_image (f : α → β) (s : set α) : set β := {y | ∀ ⦃x⦄, f x = y → x ∈ s}
protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) :=
assume a b,
⟨ assume h x hx y hy, have f y ∈ a, from hy.symm ▸ hx, h this,
assume h x (hx : f x ∈ a), h hx rfl⟩
end galois_connection
/- union and intersection over a family of sets indexed by a type -/
/-- Indexed union of a family of sets -/
@[reducible] def Union (s : ι → set β) : set β := supr s
/-- Indexed intersection of a family of sets -/
@[reducible] def Inter (s : ι → set β) : set β := infi s
notation `⋃` binders `, ` r:(scoped f, Union f) := r
notation `⋂` binders `, ` r:(scoped f, Inter f) := r
@[simp] theorem mem_Union {x : β} {s : ι → set β} : x ∈ Union s ↔ ∃ i, x ∈ s i :=
⟨assume ⟨t, ⟨⟨a, (t_eq : s a = t)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq.symm ▸ h⟩,
assume ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩
/- alternative proof: dsimp [Union, supr, Sup]; simp -/
-- TODO: more rewrite rules wrt forall / existentials and logical connectives
-- TODO: also eliminate ∃i, ... ∧ i = t ∧ ...
theorem set_of_exists (p : ι → β → Prop) : {x | ∃ i, p i x} = ⋃ i, {x | p i x} :=
ext $ λ i, mem_Union.symm
@[simp] theorem mem_Inter {x : β} {s : ι → set β} : x ∈ Inter s ↔ ∀ i, x ∈ s i :=
⟨assume (h : ∀a ∈ {a : set β | ∃i, s i = a}, x ∈ a) a, h (s a) ⟨a, rfl⟩,
assume h t ⟨a, (eq : s a = t)⟩, eq ▸ h a⟩
theorem set_of_forall (p : ι → β → Prop) : {x | ∀ i, p i x} = ⋂ i, {x | p i x} :=
ext $ λ i, mem_Inter.symm
theorem Union_subset {s : ι → set β} {t : set β} (h : ∀ i, s i ⊆ t) : (⋃ i, s i) ⊆ t :=
-- TODO: should be simpler when sets' order is based on lattices
@supr_le (set β) _ set.lattice_set _ _ h
theorem Union_subset_iff {s : ι → set β} {t : set β} : (⋃ i, s i) ⊆ t ↔ (∀ i, s i ⊆ t) :=
⟨assume h i, subset.trans (le_supr s _) h, Union_subset⟩
theorem mem_Inter_of_mem {x : β} {s : ι → set β} : (∀ i, x ∈ s i) → (x ∈ ⋂ i, s i) :=
mem_Inter.2
theorem subset_Inter {t : set β} {s : ι → set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i :=
-- TODO: should be simpler when sets' order is based on lattices
@le_infi (set β) _ set.lattice_set _ _ h
theorem subset_Union : ∀ (s : ι → set β) (i : ι), s i ⊆ (⋃ i, s i) := le_supr
-- This rather trivial consequence is convenient with `apply`,
-- and has `i` explicit for this use case.
theorem subset_subset_Union
{A : set β} {s : ι → set β} (i : ι) (h : A ⊆ s i) : A ⊆ ⋃ (i : ι), s i :=
subset.trans h (subset_Union s i)
theorem Inter_subset : ∀ (s : ι → set β) (i : ι), (⋂ i, s i) ⊆ s i := infi_le
lemma Inter_subset_of_subset {s : ι → set α} {t : set α} (i : ι)
(h : s i ⊆ t) : (⋂ i, s i) ⊆ t :=
set.subset.trans (set.Inter_subset s i) h
lemma Inter_subset_Inter {s t : ι → set α} (h : ∀ i, s i ⊆ t i) :
(⋂ i, s i) ⊆ (⋂ i, t i) :=
set.subset_Inter $ λ i, set.Inter_subset_of_subset i (h i)
lemma Inter_subset_Inter2 {s : ι → set α} {t : ι' → set α} (h : ∀ j, ∃ i, s i ⊆ t j) :
(⋂ i, s i) ⊆ (⋂ j, t j) :=
set.subset_Inter $ λ j, let ⟨i, hi⟩ := h j in Inter_subset_of_subset i hi
theorem Union_const [nonempty ι] (s : set β) : (⋃ i:ι, s) = s :=
ext $ by simp
theorem Inter_const [nonempty ι] (s : set β) : (⋂ i:ι, s) = s :=
ext $ by simp
@[simp] -- complete_boolean_algebra
theorem compl_Union (s : ι → set β) : (⋃ i, s i)ᶜ = (⋂ i, (s i)ᶜ) :=
ext (by simp)
-- classical -- complete_boolean_algebra
theorem compl_Inter (s : ι → set β) : (⋂ i, s i)ᶜ = (⋃ i, (s i)ᶜ) :=
ext (λ x, by simp [classical.not_forall])
-- classical -- complete_boolean_algebra
theorem Union_eq_comp_Inter_comp (s : ι → set β) : (⋃ i, s i) = (⋂ i, (s i)ᶜ)ᶜ :=
by simp [compl_Inter, compl_compl]
-- classical -- complete_boolean_algebra
theorem Inter_eq_comp_Union_comp (s : ι → set β) : (⋂ i, s i) = (⋃ i, (s i)ᶜ)ᶜ :=
by simp [compl_compl]
theorem inter_Union (s : set β) (t : ι → set β) :
s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i :=
ext $ by simp
theorem Union_inter (s : set β) (t : ι → set β) :
(⋃ i, t i) ∩ s = ⋃ i, t i ∩ s :=
ext $ by simp
theorem Union_union_distrib (s : ι → set β) (t : ι → set β) :
(⋃ i, s i ∪ t i) = (⋃ i, s i) ∪ (⋃ i, t i) :=
ext $ by simp [exists_or_distrib]
theorem Inter_inter_distrib (s : ι → set β) (t : ι → set β) :
(⋂ i, s i ∩ t i) = (⋂ i, s i) ∩ (⋂ i, t i) :=
ext $ by simp [forall_and_distrib]
theorem union_Union [nonempty ι] (s : set β) (t : ι → set β) :
s ∪ (⋃ i, t i) = ⋃ i, s ∪ t i :=
by rw [Union_union_distrib, Union_const]
theorem Union_union [nonempty ι] (s : set β) (t : ι → set β) :
(⋃ i, t i) ∪ s = ⋃ i, t i ∪ s :=
by rw [Union_union_distrib, Union_const]
theorem inter_Inter [nonempty ι] (s : set β) (t : ι → set β) :
s ∩ (⋂ i, t i) = ⋂ i, s ∩ t i :=
by rw [Inter_inter_distrib, Inter_const]
theorem Inter_inter [nonempty ι] (s : set β) (t : ι → set β) :
(⋂ i, t i) ∩ s = ⋂ i, t i ∩ s :=
by rw [Inter_inter_distrib, Inter_const]
-- classical
theorem union_Inter (s : set β) (t : ι → set β) :
s ∪ (⋂ i, t i) = ⋂ i, s ∪ t i :=
ext $ assume x, by simp [classical.forall_or_distrib_left]
theorem Union_diff (s : set β) (t : ι → set β) :
(⋃ i, t i) \ s = ⋃ i, t i \ s :=
Union_inter _ _
theorem diff_Union [nonempty ι] (s : set β) (t : ι → set β) :
s \ (⋃ i, t i) = ⋂ i, s \ t i :=
by rw [diff_eq, compl_Union, inter_Inter]; refl
theorem diff_Inter (s : set β) (t : ι → set β) :
s \ (⋂ i, t i) = ⋃ i, s \ t i :=
by rw [diff_eq, compl_Inter, inter_Union]; refl
lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊆) f)
(h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) :=
by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact
assume a₁ b₁ fb₁ a₂ b₂ fb₂,
let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂,
⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in
⟨x, ⟨z, xf⟩, xa₁, xa₂⟩
/- bounded unions and intersections -/
theorem mem_bUnion_iff {s : set α} {t : α → set β} {y : β} :
y ∈ (⋃ x ∈ s, t x) ↔ ∃ x ∈ s, y ∈ t x := by simp
theorem mem_bInter_iff {s : set α} {t : α → set β} {y : β} :
y ∈ (⋂ x ∈ s, t x) ↔ ∀ x ∈ s, y ∈ t x := by simp
theorem mem_bUnion {s : set α} {t : α → set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) :
y ∈ ⋃ x ∈ s, t x :=
by simp; exact ⟨x, ⟨xs, ytx⟩⟩
theorem mem_bInter {s : set α} {t : α → set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) :
y ∈ ⋂ x ∈ s, t x :=
by simp; assumption
theorem bUnion_subset {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, u x ⊆ t) :
(⋃ x ∈ s, u x) ⊆ t :=
show (⨆ x ∈ s, u x) ≤ t, -- TODO: should not be necessary when sets' order is based on lattices
from supr_le $ assume x, supr_le (h x)
theorem subset_bInter {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, t ⊆ u x) :
t ⊆ (⋂ x ∈ s, u x) :=
subset_Inter $ assume x, subset_Inter $ h x
theorem subset_bUnion_of_mem {s : set α} {u : α → set β} {x : α} (xs : x ∈ s) :
u x ⊆ (⋃ x ∈ s, u x) :=
show u x ≤ (⨆ x ∈ s, u x),
from le_supr_of_le x $ le_supr _ xs
theorem bInter_subset_of_mem {s : set α} {t : α → set β} {x : α} (xs : x ∈ s) :
(⋂ x ∈ s, t x) ⊆ t x :=
show (⨅x ∈ s, t x) ≤ t x,
from infi_le_of_le x $ infi_le _ xs
theorem bUnion_subset_bUnion_left {s s' : set α} {t : α → set β}
(h : s ⊆ s') : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s', t x) :=
bUnion_subset (λ x xs, subset_bUnion_of_mem (h xs))
theorem bInter_subset_bInter_left {s s' : set α} {t : α → set β}
(h : s' ⊆ s) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s', t x) :=
subset_bInter (λ x xs, bInter_subset_of_mem (h xs))
theorem bUnion_subset_bUnion_right {s : set α} {t1 t2 : α → set β}
(h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋃ x ∈ s, t1 x) ⊆ (⋃ x ∈ s, t2 x) :=
bUnion_subset (λ x xs, subset.trans (h x xs) (subset_bUnion_of_mem xs))
theorem bInter_subset_bInter_right {s : set α} {t1 t2 : α → set β}
(h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋂ x ∈ s, t1 x) ⊆ (⋂ x ∈ s, t2 x) :=
subset_bInter (λ x xs, subset.trans (bInter_subset_of_mem xs) (h x xs))
theorem bUnion_subset_bUnion {γ : Type*} {s : set α} {t : α → set β} {s' : set γ} {t' : γ → set β}
(h : ∀ x ∈ s, ∃ y ∈ s', t x ⊆ t' y) :
(⋃ x ∈ s, t x) ⊆ (⋃ y ∈ s', t' y) :=
begin
intros x,
simp only [mem_Union],
rintros ⟨a, a_in, ha⟩,
rcases h a a_in with ⟨c, c_in, hc⟩,
exact ⟨c, c_in, hc ha⟩
end
theorem bUnion_mono {s : set α} {t t' : α → set β} (h : ∀ x ∈ s, t x ⊆ t' x) :
(⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s, t' x) :=
bUnion_subset_bUnion (λ x x_in, ⟨x, x_in, h x x_in⟩)
theorem bUnion_eq_Union (s : set α) (t : Π x ∈ s, set β) :
(⋃ x ∈ s, t x ‹_›) = (⋃ x : s, t x x.2) :=
supr_subtype'
theorem bInter_eq_Inter (s : set α) (t : Π x ∈ s, set β) :
(⋂ x ∈ s, t x ‹_›) = (⋂ x : s, t x x.2) :=
infi_subtype'
theorem bInter_empty (u : α → set β) : (⋂ x ∈ (∅ : set α), u x) = univ :=
show (⨅x ∈ (∅ : set α), u x) = ⊤, -- simplifier should be able to rewrite x ∈ ∅ to false.
from infi_emptyset
theorem bInter_univ (u : α → set β) : (⋂ x ∈ @univ α, u x) = ⋂ x, u x :=
infi_univ
-- TODO(Jeremy): here is an artifact of the the encoding of bounded intersection:
-- without dsimp, the next theorem fails to type check, because there is a lambda
-- in a type that needs to be contracted. Using simp [eq_of_mem_singleton xa] also works.
@[simp] theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : set α), s x) = s a :=
show (⨅ x ∈ ({a} : set α), s x) = s a, by simp
theorem bInter_union (s t : set α) (u : α → set β) :
(⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) :=
show (⨅ x ∈ s ∪ t, u x) = (⨅ x ∈ s, u x) ⊓ (⨅ x ∈ t, u x),
from infi_union
-- TODO(Jeremy): simp [insert_eq, bInter_union] doesn't work
@[simp] theorem bInter_insert (a : α) (s : set α) (t : α → set β) :
(⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) :=
begin rw insert_eq, simp [bInter_union] end
-- TODO(Jeremy): another example of where an annotation is needed
theorem bInter_pair (a b : α) (s : α → set β) :
(⋂ x ∈ ({a, b} : set α), s x) = s a ∩ s b :=
by simp [inter_comm]
theorem bUnion_empty (s : α → set β) : (⋃ x ∈ (∅ : set α), s x) = ∅ :=
supr_emptyset
theorem bUnion_univ (s : α → set β) : (⋃ x ∈ @univ α, s x) = ⋃ x, s x :=
supr_univ
@[simp] theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : set α), s x) = s a :=
supr_singleton
@[simp] theorem bUnion_of_singleton (s : set α) : (⋃ x ∈ s, {x}) = s :=
ext $ by simp
theorem bUnion_union (s t : set α) (u : α → set β) :
(⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) :=
supr_union
-- TODO(Jeremy): once again, simp doesn't do it alone.
@[simp] theorem bUnion_insert (a : α) (s : set α) (t : α → set β) :
(⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) :=
begin rw [insert_eq], simp [bUnion_union] end
theorem bUnion_pair (a b : α) (s : α → set β) :
(⋃ x ∈ ({a, b} : set α), s x) = s a ∪ s b :=
by simp [union_comm]
@[simp] -- complete_boolean_algebra
theorem compl_bUnion (s : set α) (t : α → set β) : (⋃ i ∈ s, t i)ᶜ = (⋂ i ∈ s, (t i)ᶜ) :=
ext (λ x, by simp)
-- classical -- complete_boolean_algebra
theorem compl_bInter (s : set α) (t : α → set β) : (⋂ i ∈ s, t i)ᶜ = (⋃ i ∈ s, (t i)ᶜ) :=
ext (λ x, by simp [classical.not_forall])
theorem inter_bUnion (s : set α) (t : α → set β) (u : set β) :
u ∩ (⋃ i ∈ s, t i) = ⋃ i ∈ s, u ∩ t i :=
begin
ext x,
simp only [exists_prop, mem_Union, mem_inter_eq],
exact ⟨λ ⟨hx, ⟨i, is, xi⟩⟩, ⟨i, is, hx, xi⟩, λ ⟨i, is, hx, xi⟩, ⟨hx, ⟨i, is, xi⟩⟩⟩
end
theorem bUnion_inter (s : set α) (t : α → set β) (u : set β) :
(⋃ i ∈ s, t i) ∩ u = (⋃ i ∈ s, t i ∩ u) :=
by simp [@inter_comm _ _ u, inter_bUnion]
/-- Intersection of a set of sets. -/
@[reducible] def sInter (S : set (set α)) : set α := Inf S
prefix `⋂₀`:110 := sInter
theorem mem_sUnion_of_mem {x : α} {t : set α} {S : set (set α)} (hx : x ∈ t) (ht : t ∈ S) :
x ∈ ⋃₀ S :=
⟨t, ⟨ht, hx⟩⟩
theorem mem_sUnion {x : α} {S : set (set α)} : x ∈ ⋃₀ S ↔ ∃t ∈ S, x ∈ t := iff.rfl
-- is this theorem really necessary?
theorem not_mem_of_not_mem_sUnion {x : α} {t : set α} {S : set (set α)}
(hx : x ∉ ⋃₀ S) (ht : t ∈ S) : x ∉ t :=
λ h, hx ⟨t, ht, h⟩
@[simp] theorem mem_sInter {x : α} {S : set (set α)} : x ∈ ⋂₀ S ↔ ∀ t ∈ S, x ∈ t := iff.rfl
theorem sInter_subset_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : ⋂₀ S ⊆ t :=
Inf_le tS
theorem subset_sUnion_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : t ⊆ ⋃₀ S :=
le_Sup tS
lemma subset_sUnion_of_subset {s : set α} (t : set (set α)) (u : set α) (h₁ : s ⊆ u)
(h₂ : u ∈ t) : s ⊆ ⋃₀ t :=
subset.trans h₁ (subset_sUnion_of_mem h₂)
theorem sUnion_subset {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t' ⊆ t) : (⋃₀ S) ⊆ t :=
Sup_le h
theorem sUnion_subset_iff {s : set (set α)} {t : set α} : ⋃₀ s ⊆ t ↔ ∀t' ∈ s, t' ⊆ t :=
⟨assume h t' ht', subset.trans (subset_sUnion_of_mem ht') h, sUnion_subset⟩
theorem subset_sInter {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t ⊆ t') : t ⊆ (⋂₀ S) :=
le_Inf h
theorem sUnion_subset_sUnion {S T : set (set α)} (h : S ⊆ T) : ⋃₀ S ⊆ ⋃₀ T :=
sUnion_subset $ λ s hs, subset_sUnion_of_mem (h hs)
theorem sInter_subset_sInter {S T : set (set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S :=
subset_sInter $ λ s hs, sInter_subset_of_mem (h hs)
@[simp] theorem sUnion_empty : ⋃₀ ∅ = (∅ : set α) := Sup_empty
@[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : set α) := Inf_empty
@[simp] theorem sUnion_singleton (s : set α) : ⋃₀ {s} = s := Sup_singleton
@[simp] theorem sInter_singleton (s : set α) : ⋂₀ {s} = s := Inf_singleton
theorem sUnion_union (S T : set (set α)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := Sup_union
theorem sInter_union (S T : set (set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := Inf_union
theorem sInter_Union (s : ι → set (set α)) : ⋂₀ (⋃ i, s i) = ⋂ i, ⋂₀ s i :=
begin
ext x,
simp only [mem_Union, mem_Inter, mem_sInter, exists_imp_distrib],
split ; tauto
end
@[simp] theorem sUnion_insert (s : set α) (T : set (set α)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T := Sup_insert
@[simp] theorem sInter_insert (s : set α) (T : set (set α)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T := Inf_insert
theorem sUnion_pair (s t : set α) : ⋃₀ {s, t} = s ∪ t :=
Sup_pair
theorem sInter_pair (s t : set α) : ⋂₀ {s, t} = s ∩ t :=
Inf_pair
@[simp] theorem sUnion_image (f : α → set β) (s : set α) : ⋃₀ (f '' s) = ⋃ x ∈ s, f x := Sup_image
@[simp] theorem sInter_image (f : α → set β) (s : set α) : ⋂₀ (f '' s) = ⋂ x ∈ s, f x := Inf_image
@[simp] theorem sUnion_range (f : ι → set β) : ⋃₀ (range f) = ⋃ x, f x := rfl
@[simp] theorem sInter_range (f : ι → set β) : ⋂₀ (range f) = ⋂ x, f x := rfl
lemma sUnion_eq_univ_iff {c : set (set α)} :
⋃₀ c = @set.univ α ↔ ∀ a, ∃ b ∈ c, a ∈ b :=
⟨λ H a, let ⟨b, hm, hb⟩ := mem_sUnion.1 $ by rw H; exact mem_univ a in ⟨b, hm, hb⟩,
λ H, set.univ_subset_iff.1 $ λ x hx, let ⟨b, hm, hb⟩ := H x in set.mem_sUnion_of_mem hb hm⟩
theorem compl_sUnion (S : set (set α)) :
(⋃₀ S)ᶜ = ⋂₀ (compl '' S) :=
set.ext $ assume x,
⟨assume : ¬ (∃s∈S, x ∈ s), assume s h,
match s, h with
._, ⟨t, hs, rfl⟩ := assume h, this ⟨t, hs, h⟩
end,
assume : ∀s, s ∈ compl '' S → x ∈ s,
assume ⟨t, tS, xt⟩, this (compl t) (mem_image_of_mem _ tS) xt⟩
-- classical
theorem sUnion_eq_compl_sInter_compl (S : set (set α)) :
⋃₀ S = (⋂₀ (compl '' S))ᶜ :=
by rw [←compl_compl (⋃₀ S), compl_sUnion]
-- classical
theorem compl_sInter (S : set (set α)) :
(⋂₀ S)ᶜ = ⋃₀ (compl '' S) :=
by rw [sUnion_eq_compl_sInter_compl, compl_compl_image]
-- classical
theorem sInter_eq_comp_sUnion_compl (S : set (set α)) :
⋂₀ S = (⋃₀ (compl '' S))ᶜ :=
by rw [←compl_compl (⋂₀ S), compl_sInter]
theorem inter_empty_of_inter_sUnion_empty {s t : set α} {S : set (set α)} (hs : t ∈ S)
(h : s ∩ ⋃₀ S = ∅) :
s ∩ t = ∅ :=
eq_empty_of_subset_empty $ by rw ← h; exact
inter_subset_inter_right _ (subset_sUnion_of_mem hs)
theorem range_sigma_eq_Union_range {γ : α → Type*} (f : sigma γ → β) :
range f = ⋃ a, range (λ b, f ⟨a, b⟩) :=
set.ext $ by simp
theorem Union_eq_range_sigma (s : α → set β) : (⋃ i, s i) = range (λ a : Σ i, s i, a.2) :=
by simp [set.ext_iff]
theorem Union_image_preimage_sigma_mk_eq_self {ι : Type*} {σ : ι → Type*} (s : set (sigma σ)) :
(⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s)) = s :=
begin
ext x,
simp only [mem_Union, mem_image, mem_preimage],
split,
{ rintros ⟨i, a, h, rfl⟩, exact h },
{ intro h, cases x with i a, exact ⟨i, a, h, rfl⟩ }
end
lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) :=
sUnion_subset $ assume t' ht', subset_sUnion_of_mem $ h ht'
lemma Union_subset_Union {s t : ι → set α} (h : ∀i, s i ⊆ t i) : (⋃i, s i) ⊆ (⋃i, t i) :=
@supr_le_supr (set α) ι _ s t h
lemma Union_subset_Union2 {ι₂ : Sort*} {s : ι → set α} {t : ι₂ → set α} (h : ∀i, ∃j, s i ⊆ t j) :
(⋃i, s i) ⊆ (⋃i, t i) :=
@supr_le_supr2 (set α) ι ι₂ _ s t h
lemma Union_subset_Union_const {ι₂ : Sort x} {s : set α} (h : ι → ι₂) : (⋃ i:ι, s) ⊆ (⋃ j:ι₂, s) :=
@supr_le_supr_const (set α) ι ι₂ _ s h
@[simp] lemma Union_of_singleton (α : Type u) : (⋃(x : α), {x}) = @set.univ α :=
ext $ λ x, ⟨λ h, ⟨⟩, λ h, ⟨{x}, ⟨⟨x, rfl⟩, mem_singleton x⟩⟩⟩
theorem bUnion_subset_Union (s : set α) (t : α → set β) :
(⋃ x ∈ s, t x) ⊆ (⋃ x, t x) :=
Union_subset_Union $ λ i, Union_subset $ λ h, by refl
lemma sUnion_eq_bUnion {s : set (set α)} : (⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) :=
by rw [← sUnion_image, image_id']
lemma sInter_eq_bInter {s : set (set α)} : (⋂₀ s) = (⋂ (i : set α) (h : i ∈ s), i) :=
by rw [← sInter_image, image_id']
lemma sUnion_eq_Union {s : set (set α)} : (⋃₀ s) = (⋃ (i : s), i) :=
by simp only [←sUnion_range, subtype.range_coe, mem_def]
lemma sInter_eq_Inter {s : set (set α)} : (⋂₀ s) = (⋂ (i : s), i) :=
by simp only [←sInter_range, subtype.range_coe, mem_def]
lemma union_eq_Union {s₁ s₂ : set α} : s₁ ∪ s₂ = ⋃ b : bool, cond b s₁ s₂ :=
set.ext $ λ x, by simp [bool.exists_bool, or_comm]
lemma inter_eq_Inter {s₁ s₂ : set α} : s₁ ∩ s₂ = ⋂ b : bool, cond b s₁ s₂ :=
set.ext $ λ x, by simp [bool.forall_bool, and_comm]
instance : complete_boolean_algebra (set α) :=
{ compl := compl,
sdiff := (\),
le_sup_inf := distrib_lattice.le_sup_inf,
inf_compl_eq_bot := assume s, ext $ assume x, ⟨assume ⟨h, nh⟩, nh h, false.elim⟩,
sup_compl_eq_top := assume s, ext $ assume x, ⟨assume h, trivial, assume _, classical.em $ x ∈ s⟩,
sdiff_eq := assume x y, rfl,
infi_sup_le_sup_Inf := assume s t x, show x ∈ (⋂ b ∈ t, s ∪ b) → x ∈ s ∪ (⋂₀ t),
by simp; exact assume h,
or.imp_right
(assume hn : x ∉ s, assume i hi, or.resolve_left (h i hi) hn)
(classical.em $ x ∈ s),
inf_Sup_le_supr_inf := assume s t x, show x ∈ s ∩ (⋃₀ t) → x ∈ (⋃ b ∈ t, s ∩ b),
by simp [-and_imp, and.left_comm],
..set.lattice_set }
lemma sInter_union_sInter {S T : set (set α)} :
(⋂₀S) ∪ (⋂₀T) = (⋂p ∈ set.prod S T, (p : (set α) × (set α)).1 ∪ p.2) :=
Inf_sup_Inf
lemma sUnion_inter_sUnion {s t : set (set α)} :
(⋃₀s) ∩ (⋃₀t) = (⋃p ∈ set.prod s t, (p : (set α) × (set α )).1 ∩ p.2) :=
Sup_inf_Sup
/-- If `S` is a set of sets, and each `s ∈ S` can be represented as an intersection
of sets `T s hs`, then `⋂₀ S` is the intersection of the union of all `T s hs`. -/
lemma sInter_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)} (hT : ∀s∈S, s = ⋂₀ T s ‹s ∈ S›) :
⋂₀ (⋃s∈S, T s ‹_›) = ⋂₀ S :=
begin
ext,
simp only [and_imp, exists_prop, set.mem_sInter, set.mem_Union, exists_imp_distrib],
split,
{ assume H s sS,
rw [hT s sS, mem_sInter],
assume t tTs,
exact H t s sS tTs },
{ assume H t s sS tTs,
suffices : s ⊆ t, exact this (H s sS),
rw [hT s sS, sInter_eq_bInter],
exact bInter_subset_of_mem tTs }
end
/-- If `S` is a set of sets, and each `s ∈ S` can be represented as an union
of sets `T s hs`, then `⋃₀ S` is the union of the union of all `T s hs`. -/
lemma sUnion_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)} (hT : ∀s∈S, s = ⋃₀ T s ‹_›) :
⋃₀ (⋃s∈S, T s ‹_›) = ⋃₀ S :=
begin
ext,
simp only [exists_prop, set.mem_Union, set.mem_set_of_eq],
split,
{ rintros ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩,
refine ⟨s, ⟨sS, _⟩⟩,
rw hT s sS,
exact subset_sUnion_of_mem tTs xt },
{ rintros ⟨s, ⟨sS, xs⟩⟩,
rw hT s sS at xs,
rcases mem_sUnion.1 xs with ⟨t, tTs, xt⟩,
exact ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩ }
end
lemma Union_range_eq_sUnion {α β : Type*} (C : set (set α))
{f : ∀(s : C), β → s} (hf : ∀(s : C), surjective (f s)) :
(⋃(y : β), range (λ(s : C), (f s y).val)) = ⋃₀ C :=
begin
ext x, split,
{ rintro ⟨s, ⟨y, rfl⟩, ⟨⟨s, hs⟩, rfl⟩⟩, refine ⟨_, hs, _⟩, exact (f ⟨s, hs⟩ y).2 },
{ rintro ⟨s, hs, hx⟩, cases hf ⟨s, hs⟩ ⟨x, hx⟩ with y hy, refine ⟨_, ⟨y, rfl⟩, ⟨⟨s, hs⟩, _⟩⟩,
exact congr_arg subtype.val hy }
end
lemma Union_range_eq_Union {ι α β : Type*} (C : ι → set α)
{f : ∀(x : ι), β → C x} (hf : ∀(x : ι), surjective (f x)) :
(⋃(y : β), range (λ(x : ι), (f x y).val)) = ⋃x, C x :=
begin
ext x, rw [mem_Union, mem_Union], split,
{ rintro ⟨y, ⟨i, rfl⟩⟩, exact ⟨i, (f i y).2⟩ },
{ rintro ⟨i, hx⟩, cases hf i ⟨x, hx⟩ with y hy, refine ⟨y, ⟨i, congr_arg subtype.val hy⟩⟩ }
end
section
variables {p : Prop} {μ : p → set α}
@[simp] lemma Inter_pos (hp : p) : (⋂h:p, μ h) = μ hp := infi_pos hp
@[simp] lemma Inter_neg (hp : ¬ p) : (⋂h:p, μ h) = univ := infi_neg hp
@[simp] lemma Union_pos (hp : p) : (⋃h:p, μ h) = μ hp := supr_pos hp
@[simp] lemma Union_neg (hp : ¬ p) : (⋃h:p, μ h) = ∅ := supr_neg hp
@[simp] lemma Union_empty {ι : Sort*} : (⋃i:ι, ∅:set α) = ∅ := supr_bot
@[simp] lemma Inter_univ {ι : Sort*} : (⋂i:ι, univ:set α) = univ := infi_top
end
section image
lemma image_Union {f : α → β} {s : ι → set α} : f '' (⋃ i, s i) = (⋃i, f '' s i) :=
begin
apply set.ext, intro x,
simp [image, exists_and_distrib_right.symm, -exists_and_distrib_right],
exact exists_swap
end
lemma univ_subtype {p : α → Prop} : (univ : set (subtype p)) = (⋃x (h : p x), {⟨x, h⟩}) :=
set.ext $ assume ⟨x, h⟩, by simp [h]
lemma range_eq_Union {ι} (f : ι → α) : range f = (⋃i, {f i}) :=
set.ext $ assume a, by simp [@eq_comm α a]
lemma image_eq_Union (f : α → β) (s : set α) : f '' s = (⋃i∈s, {f i}) :=
set.ext $ assume b, by simp [@eq_comm β b]
@[simp] lemma bUnion_range {f : ι → α} {g : α → set β} : (⋃x ∈ range f, g x) = (⋃y, g (f y)) :=
supr_range
@[simp] lemma bInter_range {f : ι → α} {g : α → set β} : (⋂x ∈ range f, g x) = (⋂y, g (f y)) :=
infi_range
variables {s : set γ} {f : γ → α} {g : α → set β}
@[simp] lemma bUnion_image : (⋃x∈ (f '' s), g x) = (⋃y ∈ s, g (f y)) :=
supr_image
@[simp] lemma bInter_image : (⋂x∈ (f '' s), g x) = (⋂y ∈ s, g (f y)) :=
infi_image
end image
section preimage
theorem monotone_preimage {f : α → β} : monotone (preimage f) := assume a b h, preimage_mono h
@[simp] theorem preimage_Union {ι : Sort w} {f : α → β} {s : ι → set β} :
preimage f (⋃i, s i) = (⋃i, preimage f (s i)) :=
set.ext $ by simp [preimage]
theorem preimage_bUnion {ι} {f : α → β} {s : set ι} {t : ι → set β} :
f ⁻¹' (⋃i ∈ s, t i) = (⋃i ∈ s, f ⁻¹' (t i)) :=
by simp
@[simp] theorem preimage_sUnion {f : α → β} {s : set (set β)} :
f ⁻¹' (⋃₀ s) = (⋃t ∈ s, f ⁻¹' t) :=
set.ext $ by simp [preimage]
lemma preimage_Inter {ι : Sort*} {s : ι → set β} {f : α → β} :
f ⁻¹' (⋂ i, s i) = (⋂ i, f ⁻¹' s i) :=
by ext; simp
lemma preimage_bInter {s : γ → set β} {t : set γ} {f : α → β} :
f ⁻¹' (⋂ i∈t, s i) = (⋂ i∈t, f ⁻¹' s i) :=
by ext; simp
@[simp] lemma bUnion_preimage_singleton (f : α → β) (s : set β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' s :=
by rw [← preimage_bUnion, bUnion_of_singleton]
lemma bUnion_range_preimage_singleton (f : α → β) : (⋃ y ∈ range f, f ⁻¹' {y}) = univ :=
by simp
end preimage
section seq
/-- Given a set `s` of functions `α → β` and `t : set α`, `seq s t` is the union of `f '' t` over
all `f ∈ s`. -/
def seq (s : set (α → β)) (t : set α) : set β := {b | ∃f∈s, ∃a∈t, (f : α → β) a = b}
lemma seq_def {s : set (α → β)} {t : set α} : seq s t = ⋃f∈s, f '' t :=
set.ext $ by simp [seq]
@[simp] lemma mem_seq_iff {s : set (α → β)} {t : set α} {b : β} :
b ∈ seq s t ↔ ∃ (f ∈ s) (a ∈ t), (f : α → β) a = b :=
iff.rfl
lemma seq_subset {s : set (α → β)} {t : set α} {u : set β} :
seq s t ⊆ u ↔ (∀f∈s, ∀a∈t, (f : α → β) a ∈ u) :=
iff.intro
(assume h f hf a ha, h ⟨f, hf, a, ha, rfl⟩)
(assume h b ⟨f, hf, a, ha, eq⟩, eq ▸ h f hf a ha)
lemma seq_mono {s₀ s₁ : set (α → β)} {t₀ t₁ : set α} (hs : s₀ ⊆ s₁) (ht : t₀ ⊆ t₁) :
seq s₀ t₀ ⊆ seq s₁ t₁ :=
assume b ⟨f, hf, a, ha, eq⟩, ⟨f, hs hf, a, ht ha, eq⟩
lemma singleton_seq {f : α → β} {t : set α} : set.seq {f} t = f '' t :=
set.ext $ by simp
lemma seq_singleton {s : set (α → β)} {a : α} : set.seq s {a} = (λf:α→β, f a) '' s :=
set.ext $ by simp
lemma seq_seq {s : set (β → γ)} {t : set (α → β)} {u : set α} :
seq s (seq t u) = seq (seq ((∘) '' s) t) u :=
begin
refine set.ext (assume c, iff.intro _ _),
{ rintros ⟨f, hfs, b, ⟨g, hg, a, hau, rfl⟩, rfl⟩,
exact ⟨f ∘ g, ⟨(∘) f, mem_image_of_mem _ hfs, g, hg, rfl⟩, a, hau, rfl⟩ },
{ rintros ⟨fg, ⟨fc, ⟨f, hfs, rfl⟩, g, hgt, rfl⟩, a, ha, rfl⟩,
exact ⟨f, hfs, g a, ⟨g, hgt, a, ha, rfl⟩, rfl⟩ }
end
lemma image_seq {f : β → γ} {s : set (α → β)} {t : set α} :
f '' seq s t = seq ((∘) f '' s) t :=
by rw [← singleton_seq, ← singleton_seq, seq_seq, image_singleton]
lemma prod_eq_seq {s : set α} {t : set β} : set.prod s t = (prod.mk '' s).seq t :=
begin
ext ⟨a, b⟩,
split,
{ rintros ⟨ha, hb⟩, exact ⟨prod.mk a, ⟨a, ha, rfl⟩, b, hb, rfl⟩ },
{ rintros ⟨f, ⟨x, hx, rfl⟩, y, hy, eq⟩, rw ← eq, exact ⟨hx, hy⟩ }
end
lemma prod_image_seq_comm (s : set α) (t : set β) :
(prod.mk '' s).seq t = seq ((λb a, (a, b)) '' t) s :=
by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp]
end seq
theorem monotone_prod [preorder α] {f : α → set β} {g : α → set γ}
(hf : monotone f) (hg : monotone g) : monotone (λx, set.prod (f x) (g x)) :=
assume a b h, prod_mono (hf h) (hg h)
instance : monad set :=
{ pure := λ(α : Type u) a, {a},
bind := λ(α β : Type u) s f, ⋃i∈s, f i,
seq := λ(α β : Type u), set.seq,
map := λ(α β : Type u), set.image }
section monad
variables {α' β' : Type u} {s : set α'} {f : α' → set β'} {g : set (α' → β')}
@[simp] lemma bind_def : s >>= f = ⋃i∈s, f i := rfl
@[simp] lemma fmap_eq_image (f : α' → β') : f <$> s = f '' s := rfl
@[simp] lemma seq_eq_set_seq {α β : Type*} (s : set (α → β)) (t : set α) : s <*> t = s.seq t := rfl
@[simp] lemma pure_def (a : α) : (pure a : set α) = {a} := rfl
end monad
instance : is_lawful_monad set :=
{ pure_bind := assume α β x f, by simp,
bind_assoc := assume α β γ s f g, set.ext $ assume a,
by simp [exists_and_distrib_right.symm, -exists_and_distrib_right,
exists_and_distrib_left.symm, -exists_and_distrib_left, and_assoc];
exact exists_swap,
id_map := assume α, id_map,
bind_pure_comp_eq_map := assume α β f s, set.ext $ by simp [set.image, eq_comm],
bind_map_eq_seq := assume α β s t, by simp [seq_def] }
instance : is_comm_applicative (set : Type u → Type u) :=
⟨ assume α β s t, prod_image_seq_comm s t ⟩
section pi
lemma pi_def {α : Type*} {π : α → Type*} (i : set α) (s : Πa, set (π a)) :
pi i s = (⋂ a∈i, ((λf:(Πa, π a), f a) ⁻¹' (s a))) :=
by ext; simp [pi]
end pi
end set
/- disjoint sets -/
namespace set
protected theorem disjoint_iff {s t : set α} : disjoint s t ↔ s ∩ t ⊆ ∅ := iff.rfl
theorem disjoint_iff_inter_eq_empty {s t : set α} : disjoint s t ↔ s ∩ t = ∅ :=
disjoint_iff
lemma not_disjoint_iff {s t : set α} : ¬disjoint s t ↔ ∃x, x ∈ s ∧ x ∈ t :=
(not_congr (set.disjoint_iff.trans subset_empty_iff)).trans ne_empty_iff_nonempty
lemma disjoint_left {s t : set α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t :=
show (∀ x, ¬(x ∈ s ∩ t)) ↔ _, from ⟨λ h a, not_and.1 $ h a, λ h a, not_and.2 $ h a⟩
theorem disjoint_right {s t : set α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
by rw [disjoint.comm, disjoint_left]
theorem disjoint_of_subset_left {s t u : set α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t :=
disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁))
theorem disjoint_of_subset_right {s t u : set α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t :=
disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁))
theorem disjoint_of_subset {s t u v : set α} (h1 : s ⊆ u) (h2 : t ⊆ v) (d : disjoint u v) :
disjoint s t :=
disjoint_of_subset_left h1 $ disjoint_of_subset_right h2 d
theorem disjoint_diff {a b : set α} : disjoint a (b \ a) :=
disjoint_iff.2 (inter_diff_self _ _)
theorem disjoint_compl (s : set α) : disjoint s sᶜ := assume a ⟨h₁, h₂⟩, h₂ h₁
theorem disjoint_singleton_left {a : α} {s : set α} : disjoint {a} s ↔ a ∉ s :=
by simp [set.disjoint_iff, subset_def]; exact iff.rfl
theorem disjoint_singleton_right {a : α} {s : set α} : disjoint s {a} ↔ a ∉ s :=
by rw [disjoint.comm]; exact disjoint_singleton_left
theorem disjoint_image_image {f : β → α} {g : γ → α} {s : set β} {t : set γ}
(h : ∀b∈s, ∀c∈t, f b ≠ g c) : disjoint (f '' s) (g '' t) :=
by rintros a ⟨⟨b, hb, eq⟩, ⟨c, hc, rfl⟩⟩; exact h b hb c hc eq
lemma disjoint.preimage {α β} (f : α → β) {s t : set β} (h : disjoint s t) :
disjoint (f ⁻¹' s) (f ⁻¹' t) :=
λ x hx, h hx
theorem pairwise_on_disjoint_fiber (f : α → β) (s : set β) :
pairwise_on s (disjoint on (λ y, f ⁻¹' {y})) :=
λ y₁ _ y₂ _ hy x ⟨hx₁, hx₂⟩, hy (eq.trans (eq.symm hx₁) hx₂)
/-- A collection of sets is `pairwise_disjoint`, if any two different sets in this collection
are disjoint. -/
def pairwise_disjoint (s : set (set α)) : Prop :=
pairwise_on s disjoint
lemma pairwise_disjoint.subset {s t : set (set α)} (h : s ⊆ t)
(ht : pairwise_disjoint t) : pairwise_disjoint s :=
pairwise_on.mono h ht
lemma pairwise_disjoint.range {s : set (set α)} (f : s → set α) (hf : ∀(x : s), f x ⊆ x.1)
(ht : pairwise_disjoint s) : pairwise_disjoint (range f) :=
begin
rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy, refine (ht _ x.2 _ y.2 _).mono (hf x) (hf y),
intro h, apply hxy, apply congr_arg f, exact subtype.eq h
end
/- warning: classical -/
lemma pairwise_disjoint.elim {s : set (set α)} (h : pairwise_disjoint s) {x y : set α}
(hx : x ∈ s) (hy : y ∈ s) (z : α) (hzx : z ∈ x) (hzy : z ∈ y) : x = y :=
classical.not_not.1 $ λ h', h x hx y hy h' ⟨hzx, hzy⟩
end set
namespace set
variables (t : α → set β)
lemma subset_diff {s t u : set α} : s ⊆ t \ u ↔ s ⊆ t ∧ disjoint s u :=
⟨λ h, ⟨λ x hxs, (h hxs).1, λ x ⟨hxs, hxu⟩, (h hxs).2 hxu⟩,
λ ⟨h1, h2⟩ x hxs, ⟨h1 hxs, λ hxu, h2 ⟨hxs, hxu⟩⟩⟩
/-- If `t` is an indexed family of sets, then there is a natural map from `Σ i, t i` to `⋃ i, t i`
sending `⟨i, x⟩` to `x`. -/
def sigma_to_Union (x : Σi, t i) : (⋃i, t i) := ⟨x.2, mem_Union.2 ⟨x.1, x.2.2⟩⟩
lemma sigma_to_Union_surjective : surjective (sigma_to_Union t)
| ⟨b, hb⟩ := have ∃a, b ∈ t a, by simpa using hb, let ⟨a, hb⟩ := this in ⟨⟨a, ⟨b, hb⟩⟩, rfl⟩
lemma sigma_to_Union_injective (h : ∀i j, i ≠ j → disjoint (t i) (t j)) :
injective (sigma_to_Union t)
| ⟨a₁, ⟨b₁, h₁⟩⟩ ⟨a₂, ⟨b₂, h₂⟩⟩ eq :=
have b_eq : b₁ = b₂, from congr_arg subtype.val eq,
have a_eq : a₁ = a₂, from classical.by_contradiction $ assume ne,
have b₁ ∈ t a₁ ∩ t a₂, from ⟨h₁, b_eq.symm ▸ h₂⟩,
h _ _ ne this,
sigma.eq a_eq $ subtype.eq $ by subst b_eq; subst a_eq
lemma sigma_to_Union_bijective (h : ∀i j, i ≠ j → disjoint (t i) (t j)) :
bijective (sigma_to_Union t) :=
⟨sigma_to_Union_injective t h, sigma_to_Union_surjective t⟩
noncomputable def Union_eq_sigma_of_disjoint {t : α → set β}
(h : ∀i j, i ≠ j → disjoint (t i) (t j)) : (⋃i, t i) ≃ (Σi, t i) :=
(equiv.of_bijective _ $ sigma_to_Union_bijective t h).symm
noncomputable def bUnion_eq_sigma_of_disjoint {s : set α} {t : α → set β}
(h : pairwise_on s (disjoint on t)) : (⋃i∈s, t i) ≃ (Σi:s, t i.val) :=
equiv.trans (equiv.set_congr (bUnion_eq_Union _ _)) $ Union_eq_sigma_of_disjoint $
assume ⟨i, hi⟩ ⟨j, hj⟩ ne, h _ hi _ hj $ assume eq, ne $ subtype.eq eq
end set
|
bd0987e855f6c4b5622f3e451fda73ef598ee23d | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/1163.lean | e9279e1b2c8ce05208faca2b60360be0f539adf9 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 448 | lean | import Lean
open Lean Elab Tactic
macro "obviously1" : tactic => `(exact sorryAx _)
theorem result1 : False := by obviously1
elab "obviously2" : tactic =>
liftMetaTactic1 fun mvarId => mvarId.admit *> pure none
theorem result2 : False := by obviously2
def x : Bool := 0
theorem result3 : False := by obviously2
theorem result4 : False := by -- Does not generate a `sorry` warning because there is an error
let x : Bool := 0
obviously2
|
8d2c9e4a154531dfa15ea46b21a97c6cb755b6f1 | b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77 | /src/category_theory/limits/shapes/binary_products.lean | 2832f7be6cb759c804163541833ede1a94c487c8 | [
"Apache-2.0"
] | permissive | molodiuc/mathlib | cae2ba3ef1601c1f42ca0b625c79b061b63fef5b | 98ebe5a6739fbe254f9ee9d401882d4388f91035 | refs/heads/master | 1,674,237,127,059 | 1,606,353,533,000 | 1,606,353,533,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 32,224 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Bhavik Mehta
-/
import category_theory.limits.limits
import category_theory.limits.shapes.terminal
import category_theory.discrete_category
import category_theory.epi_mono
/-!
# Binary (co)products
We define a category `walking_pair`, which is the index category
for a binary (co)product diagram. A convenience method `pair X Y`
constructs the functor from the walking pair, hitting the given objects.
We define `prod X Y` and `coprod X Y` as limits and colimits of such functors.
Typeclasses `has_binary_products` and `has_binary_coproducts` assert the existence
of (co)limits shaped as walking pairs.
We include lemmas for simplifying equations involving projections and coprojections, and define
braiding and associating isomorphisms, and the product comparison morphism.
## References
* [Stacks: Products of pairs](https://stacks.math.columbia.edu/tag/001R)
* [Stacks: coproducts of pairs](https://stacks.math.columbia.edu/tag/04AN)
-/
noncomputable theory
universes v u u₂
open category_theory
namespace category_theory.limits
/-- The type of objects for the diagram indexing a binary (co)product. -/
@[derive decidable_eq, derive inhabited]
inductive walking_pair : Type v
| left | right
open walking_pair
/--
The equivalence swapping left and right.
-/
def walking_pair.swap : walking_pair ≃ walking_pair :=
{ to_fun := λ j, walking_pair.rec_on j right left,
inv_fun := λ j, walking_pair.rec_on j right left,
left_inv := λ j, by { cases j; refl, },
right_inv := λ j, by { cases j; refl, }, }
@[simp] lemma walking_pair.swap_apply_left : walking_pair.swap left = right := rfl
@[simp] lemma walking_pair.swap_apply_right : walking_pair.swap right = left := rfl
@[simp] lemma walking_pair.swap_symm_apply_tt : walking_pair.swap.symm left = right := rfl
@[simp] lemma walking_pair.swap_symm_apply_ff : walking_pair.swap.symm right = left := rfl
/--
An equivalence from `walking_pair` to `bool`, sometimes useful when reindexing limits.
-/
def walking_pair.equiv_bool : walking_pair ≃ bool :=
{ to_fun := λ j, walking_pair.rec_on j tt ff, -- to match equiv.sum_equiv_sigma_bool
inv_fun := λ b, bool.rec_on b right left,
left_inv := λ j, by { cases j; refl, },
right_inv := λ b, by { cases b; refl, }, }
@[simp] lemma walking_pair.equiv_bool_apply_left : walking_pair.equiv_bool left = tt := rfl
@[simp] lemma walking_pair.equiv_bool_apply_right : walking_pair.equiv_bool right = ff := rfl
@[simp] lemma walking_pair.equiv_bool_symm_apply_tt : walking_pair.equiv_bool.symm tt = left := rfl
@[simp] lemma walking_pair.equiv_bool_symm_apply_ff : walking_pair.equiv_bool.symm ff = right := rfl
variables {C : Type u} [category.{v} C]
/-- The diagram on the walking pair, sending the two points to `X` and `Y`. -/
def pair (X Y : C) : discrete walking_pair ⥤ C :=
discrete.functor (λ j, walking_pair.cases_on j X Y)
@[simp] lemma pair_obj_left (X Y : C) : (pair X Y).obj left = X := rfl
@[simp] lemma pair_obj_right (X Y : C) : (pair X Y).obj right = Y := rfl
section
variables {F G : discrete walking_pair.{v} ⥤ C} (f : F.obj left ⟶ G.obj left) (g : F.obj right ⟶ G.obj right)
/-- The natural transformation between two functors out of the walking pair, specified by its components. -/
def map_pair : F ⟶ G :=
{ app := λ j, match j with
| left := f
| right := g
end }
@[simp] lemma map_pair_left : (map_pair f g).app left = f := rfl
@[simp] lemma map_pair_right : (map_pair f g).app right = g := rfl
/-- The natural isomorphism between two functors out of the walking pair, specified by its components. -/
@[simps]
def map_pair_iso (f : F.obj left ≅ G.obj left) (g : F.obj right ≅ G.obj right) : F ≅ G :=
{ hom := map_pair f.hom g.hom,
inv := map_pair f.inv g.inv,
hom_inv_id' := by { ext ⟨⟩; simp, },
inv_hom_id' := by { ext ⟨⟩; simp, } }
end
section
variables {D : Type u} [category.{v} D]
/-- The natural isomorphism between `pair X Y ⋙ F` and `pair (F.obj X) (F.obj Y)`. -/
def pair_comp (X Y : C) (F : C ⥤ D) : pair X Y ⋙ F ≅ pair (F.obj X) (F.obj Y) :=
map_pair_iso (eq_to_iso rfl) (eq_to_iso rfl)
end
/-- Every functor out of the walking pair is naturally isomorphic (actually, equal) to a `pair` -/
def diagram_iso_pair (F : discrete walking_pair ⥤ C) :
F ≅ pair (F.obj walking_pair.left) (F.obj walking_pair.right) :=
map_pair_iso (eq_to_iso rfl) (eq_to_iso rfl)
/-- A binary fan is just a cone on a diagram indexing a product. -/
abbreviation binary_fan (X Y : C) := cone (pair X Y)
/-- The first projection of a binary fan. -/
abbreviation binary_fan.fst {X Y : C} (s : binary_fan X Y) := s.π.app walking_pair.left
/-- The second projection of a binary fan. -/
abbreviation binary_fan.snd {X Y : C} (s : binary_fan X Y) := s.π.app walking_pair.right
@[simp] lemma binary_fan.π_app_left {X Y : C} (s : binary_fan X Y) :
s.π.app walking_pair.left = s.fst := rfl
@[simp] lemma binary_fan.π_app_right {X Y : C} (s : binary_fan X Y) :
s.π.app walking_pair.right = s.snd := rfl
lemma binary_fan.is_limit.hom_ext {W X Y : C} {s : binary_fan X Y} (h : is_limit s)
{f g : W ⟶ s.X} (h₁ : f ≫ s.fst = g ≫ s.fst) (h₂ : f ≫ s.snd = g ≫ s.snd) : f = g :=
h.hom_ext $ λ j, walking_pair.cases_on j h₁ h₂
/-- A binary cofan is just a cocone on a diagram indexing a coproduct. -/
abbreviation binary_cofan (X Y : C) := cocone (pair X Y)
/-- The first inclusion of a binary cofan. -/
abbreviation binary_cofan.inl {X Y : C} (s : binary_cofan X Y) := s.ι.app walking_pair.left
/-- The second inclusion of a binary cofan. -/
abbreviation binary_cofan.inr {X Y : C} (s : binary_cofan X Y) := s.ι.app walking_pair.right
@[simp] lemma binary_cofan.ι_app_left {X Y : C} (s : binary_cofan X Y) :
s.ι.app walking_pair.left = s.inl := rfl
@[simp] lemma binary_cofan.ι_app_right {X Y : C} (s : binary_cofan X Y) :
s.ι.app walking_pair.right = s.inr := rfl
lemma binary_cofan.is_colimit.hom_ext {W X Y : C} {s : binary_cofan X Y} (h : is_colimit s)
{f g : s.X ⟶ W} (h₁ : s.inl ≫ f = s.inl ≫ g) (h₂ : s.inr ≫ f = s.inr ≫ g) : f = g :=
h.hom_ext $ λ j, walking_pair.cases_on j h₁ h₂
variables {X Y : C}
/-- A binary fan with vertex `P` consists of the two projections `π₁ : P ⟶ X` and `π₂ : P ⟶ Y`. -/
@[simps X]
def binary_fan.mk {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : binary_fan X Y :=
{ X := P,
π := { app := λ j, walking_pair.cases_on j π₁ π₂ }}
/-- A binary cofan with vertex `P` consists of the two inclusions `ι₁ : X ⟶ P` and `ι₂ : Y ⟶ P`. -/
@[simps X]
def binary_cofan.mk {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : binary_cofan X Y :=
{ X := P,
ι := { app := λ j, walking_pair.cases_on j ι₁ ι₂ }}
@[simp] lemma binary_fan.mk_π_app_left {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) :
(binary_fan.mk π₁ π₂).π.app walking_pair.left = π₁ := rfl
@[simp] lemma binary_fan.mk_π_app_right {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) :
(binary_fan.mk π₁ π₂).π.app walking_pair.right = π₂ := rfl
@[simp] lemma binary_cofan.mk_ι_app_left {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) :
(binary_cofan.mk ι₁ ι₂).ι.app walking_pair.left = ι₁ := rfl
@[simp] lemma binary_cofan.mk_ι_app_right {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) :
(binary_cofan.mk ι₁ ι₂).ι.app walking_pair.right = ι₂ := rfl
/-- If `s` is a limit binary fan over `X` and `Y`, then every pair of morphisms `f : W ⟶ X` and
`g : W ⟶ Y` induces a morphism `l : W ⟶ s.X` satisfying `l ≫ s.fst = f` and `l ≫ s.snd = g`.
-/
@[simps]
def binary_fan.is_limit.lift' {W X Y : C} {s : binary_fan X Y} (h : is_limit s) (f : W ⟶ X)
(g : W ⟶ Y) : {l : W ⟶ s.X // l ≫ s.fst = f ∧ l ≫ s.snd = g} :=
⟨h.lift $ binary_fan.mk f g, h.fac _ _, h.fac _ _⟩
/-- If `s` is a colimit binary cofan over `X` and `Y`,, then every pair of morphisms `f : X ⟶ W` and
`g : Y ⟶ W` induces a morphism `l : s.X ⟶ W` satisfying `s.inl ≫ l = f` and `s.inr ≫ l = g`.
-/
@[simps]
def binary_cofan.is_colimit.desc' {W X Y : C} {s : binary_cofan X Y} (h : is_colimit s) (f : X ⟶ W)
(g : Y ⟶ W) : {l : s.X ⟶ W // s.inl ≫ l = f ∧ s.inr ≫ l = g} :=
⟨h.desc $ binary_cofan.mk f g, h.fac _ _, h.fac _ _⟩
/-- An abbreviation for `has_limit (pair X Y)`. -/
abbreviation has_binary_product (X Y : C) := has_limit (pair X Y)
/-- An abbreviation for `has_colimit (pair X Y)`. -/
abbreviation has_binary_coproduct (X Y : C) := has_colimit (pair X Y)
/-- If we have a product of `X` and `Y`, we can access it using `prod X Y` or
`X ⨯ Y`. -/
abbreviation prod (X Y : C) [has_binary_product X Y] := limit (pair X Y)
/-- If we have a coproduct of `X` and `Y`, we can access it using `coprod X Y ` or
`X ⨿ Y`. -/
abbreviation coprod (X Y : C) [has_binary_coproduct X Y] := colimit (pair X Y)
notation X ` ⨯ `:20 Y:20 := prod X Y
notation X ` ⨿ `:20 Y:20 := coprod X Y
/-- The projection map to the first component of the product. -/
abbreviation prod.fst {X Y : C} [has_binary_product X Y] : X ⨯ Y ⟶ X :=
limit.π (pair X Y) walking_pair.left
/-- The projecton map to the second component of the product. -/
abbreviation prod.snd {X Y : C} [has_binary_product X Y] : X ⨯ Y ⟶ Y :=
limit.π (pair X Y) walking_pair.right
/-- The inclusion map from the first component of the coproduct. -/
abbreviation coprod.inl {X Y : C} [has_binary_coproduct X Y] : X ⟶ X ⨿ Y :=
colimit.ι (pair X Y) walking_pair.left
/-- The inclusion map from the second component of the coproduct. -/
abbreviation coprod.inr {X Y : C} [has_binary_coproduct X Y] : Y ⟶ X ⨿ Y :=
colimit.ι (pair X Y) walking_pair.right
@[ext] lemma prod.hom_ext {W X Y : C} [has_binary_product X Y] {f g : W ⟶ X ⨯ Y}
(h₁ : f ≫ prod.fst = g ≫ prod.fst) (h₂ : f ≫ prod.snd = g ≫ prod.snd) : f = g :=
binary_fan.is_limit.hom_ext (limit.is_limit _) h₁ h₂
@[ext] lemma coprod.hom_ext {W X Y : C} [has_binary_coproduct X Y] {f g : X ⨿ Y ⟶ W}
(h₁ : coprod.inl ≫ f = coprod.inl ≫ g) (h₂ : coprod.inr ≫ f = coprod.inr ≫ g) : f = g :=
binary_cofan.is_colimit.hom_ext (colimit.is_colimit _) h₁ h₂
/-- If the product of `X` and `Y` exists, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y`
induces a morphism `prod.lift f g : W ⟶ X ⨯ Y`. -/
abbreviation prod.lift {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⨯ Y :=
limit.lift _ (binary_fan.mk f g)
/-- diagonal arrow of the binary product in the category `fam I` -/
abbreviation diag (X : C) [has_binary_product X X] : X ⟶ X ⨯ X :=
prod.lift (𝟙 _) (𝟙 _)
/-- If the coproduct of `X` and `Y` exists, then every pair of morphisms `f : X ⟶ W` and
`g : Y ⟶ W` induces a morphism `coprod.desc f g : X ⨿ Y ⟶ W`. -/
abbreviation coprod.desc {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : X ⨿ Y ⟶ W :=
colimit.desc _ (binary_cofan.mk f g)
/-- codiagonal arrow of the binary coproduct -/
abbreviation codiag (X : C) [has_binary_coproduct X X] : X ⨿ X ⟶ X :=
coprod.desc (𝟙 _) (𝟙 _)
@[simp, reassoc]
lemma prod.lift_fst {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) :
prod.lift f g ≫ prod.fst = f :=
limit.lift_π _ _
@[simp, reassoc]
lemma prod.lift_snd {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) :
prod.lift f g ≫ prod.snd = g :=
limit.lift_π _ _
-- The simp linter says simp can prove the reassoc version of this lemma.
@[reassoc, simp]
lemma coprod.inl_desc {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) :
coprod.inl ≫ coprod.desc f g = f :=
colimit.ι_desc _ _
-- The simp linter says simp can prove the reassoc version of this lemma.
@[reassoc, simp]
lemma coprod.inr_desc {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) :
coprod.inr ≫ coprod.desc f g = g :=
colimit.ι_desc _ _
instance prod.mono_lift_of_mono_left {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y)
[mono f] : mono (prod.lift f g) :=
mono_of_mono_fac $ prod.lift_fst _ _
instance prod.mono_lift_of_mono_right {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y)
[mono g] : mono (prod.lift f g) :=
mono_of_mono_fac $ prod.lift_snd _ _
instance coprod.epi_desc_of_epi_left {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W)
[epi f] : epi (coprod.desc f g) :=
epi_of_epi_fac $ coprod.inl_desc _ _
instance coprod.epi_desc_of_epi_right {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W)
[epi g] : epi (coprod.desc f g) :=
epi_of_epi_fac $ coprod.inr_desc _ _
/-- If the product of `X` and `Y` exists, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y`
induces a morphism `l : W ⟶ X ⨯ Y` satisfying `l ≫ prod.fst = f` and `l ≫ prod.snd = g`. -/
def prod.lift' {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) :
{l : W ⟶ X ⨯ Y // l ≫ prod.fst = f ∧ l ≫ prod.snd = g} :=
⟨prod.lift f g, prod.lift_fst _ _, prod.lift_snd _ _⟩
/-- If the coproduct of `X` and `Y` exists, then every pair of morphisms `f : X ⟶ W` and
`g : Y ⟶ W` induces a morphism `l : X ⨿ Y ⟶ W` satisfying `coprod.inl ≫ l = f` and
`coprod.inr ≫ l = g`. -/
def coprod.desc' {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) :
{l : X ⨿ Y ⟶ W // coprod.inl ≫ l = f ∧ coprod.inr ≫ l = g} :=
⟨coprod.desc f g, coprod.inl_desc _ _, coprod.inr_desc _ _⟩
/-- If the products `W ⨯ X` and `Y ⨯ Z` exist, then every pair of morphisms `f : W ⟶ Y` and
`g : X ⟶ Z` induces a morphism `prod.map f g : W ⨯ X ⟶ Y ⨯ Z`. -/
def prod.map {W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z]
(f : W ⟶ Y) (g : X ⟶ Z) : W ⨯ X ⟶ Y ⨯ Z :=
lim_map (map_pair f g)
/-- If the coproducts `W ⨿ X` and `Y ⨿ Z` exist, then every pair of morphisms `f : W ⟶ Y` and
`g : W ⟶ Z` induces a morphism `coprod.map f g : W ⨿ X ⟶ Y ⨿ Z`. -/
def coprod.map {W X Y Z : C} [has_binary_coproduct W X] [has_binary_coproduct Y Z]
(f : W ⟶ Y) (g : X ⟶ Z) : W ⨿ X ⟶ Y ⨿ Z :=
colim_map (map_pair f g)
section prod_lemmas
-- Making the reassoc version of this a simp lemma seems to be more harmful than helpful.
@[reassoc, simp]
lemma prod.comp_lift {V W X Y : C} [has_binary_product X Y] (f : V ⟶ W) (g : W ⟶ X) (h : W ⟶ Y) :
f ≫ prod.lift g h = prod.lift (f ≫ g) (f ≫ h) :=
by { ext; simp }
lemma prod.comp_diag {X Y : C} [has_binary_product Y Y] (f : X ⟶ Y) :
f ≫ diag Y = prod.lift f f :=
by simp
@[simp, reassoc]
lemma prod.map_fst {W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z]
(f : W ⟶ Y) (g : X ⟶ Z) : prod.map f g ≫ prod.fst = prod.fst ≫ f :=
lim_map_π _ _
@[simp, reassoc]
lemma prod.map_snd {W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z]
(f : W ⟶ Y) (g : X ⟶ Z) : prod.map f g ≫ prod.snd = prod.snd ≫ g :=
lim_map_π _ _
@[simp] lemma prod.map_id_id {X Y : C} [has_binary_product X Y] :
prod.map (𝟙 X) (𝟙 Y) = 𝟙 _ :=
by { ext; simp }
@[simp] lemma prod.lift_fst_snd {X Y : C} [has_binary_product X Y] :
prod.lift prod.fst prod.snd = 𝟙 (X ⨯ Y) :=
by { ext; simp }
@[simp, reassoc] lemma prod.lift_map {V W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z]
(f : V ⟶ W) (g : V ⟶ X) (h : W ⟶ Y) (k : X ⟶ Z) :
prod.lift f g ≫ prod.map h k = prod.lift (f ≫ h) (g ≫ k) :=
by { ext; simp }
@[simp] lemma prod.lift_fst_comp_snd_comp {W X Y Z : C} [has_binary_product W Y] [has_binary_product X Z]
(g : W ⟶ X) (g' : Y ⟶ Z) :
prod.lift (prod.fst ≫ g) (prod.snd ≫ g') = prod.map g g' :=
by { rw ← prod.lift_map, simp }
-- We take the right hand side here to be simp normal form, as this way composition lemmas for
-- `f ≫ h` and `g ≫ k` can fire (eg `id_comp`) , while `map_fst` and `map_snd` can still work just
-- as well.
@[simp, reassoc]
lemma prod.map_map {A₁ A₂ A₃ B₁ B₂ B₃ : C}
[has_binary_product A₁ B₁] [has_binary_product A₂ B₂] [has_binary_product A₃ B₃]
(f : A₁ ⟶ A₂) (g : B₁ ⟶ B₂) (h : A₂ ⟶ A₃) (k : B₂ ⟶ B₃) :
prod.map f g ≫ prod.map h k = prod.map (f ≫ h) (g ≫ k) :=
by { ext; simp }
-- TODO: is it necessary to weaken the assumption here?
@[reassoc]
lemma prod.map_swap {A B X Y : C} (f : A ⟶ B) (g : X ⟶ Y) [has_limits_of_shape (discrete walking_pair) C] :
prod.map (𝟙 X) f ≫ prod.map g (𝟙 B) = prod.map g (𝟙 A) ≫ prod.map (𝟙 Y) f :=
by simp
@[reassoc] lemma prod.map_comp_id {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_binary_product X W] [has_binary_product Z W] [has_binary_product Y W] :
prod.map (f ≫ g) (𝟙 W) = prod.map f (𝟙 W) ≫ prod.map g (𝟙 W) :=
by simp
@[reassoc] lemma prod.map_id_comp {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_binary_product W X] [has_binary_product W Y] [has_binary_product W Z] :
prod.map (𝟙 W) (f ≫ g) = prod.map (𝟙 W) f ≫ prod.map (𝟙 W) g :=
by simp
/-- If the products `W ⨯ X` and `Y ⨯ Z` exist, then every pair of isomorphisms `f : W ≅ Y` and
`g : X ≅ Z` induces an isomorphism `prod.map_iso f g : W ⨯ X ≅ Y ⨯ Z`. -/
@[simps]
def prod.map_iso {W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z]
(f : W ≅ Y) (g : X ≅ Z) : W ⨯ X ≅ Y ⨯ Z :=
{ hom := prod.map f.hom g.hom,
inv := prod.map f.inv g.inv }
@[simp, reassoc]
lemma prod.diag_map {X Y : C} (f : X ⟶ Y) [has_binary_product X X] [has_binary_product Y Y] :
diag X ≫ prod.map f f = f ≫ diag Y :=
by simp
@[simp, reassoc]
lemma prod.diag_map_fst_snd {X Y : C} [has_binary_product X Y] [has_binary_product (X ⨯ Y) (X ⨯ Y)] :
diag (X ⨯ Y) ≫ prod.map prod.fst prod.snd = 𝟙 (X ⨯ Y) :=
by simp
@[simp, reassoc]
lemma prod.diag_map_fst_snd_comp [has_limits_of_shape (discrete walking_pair) C]
{X X' Y Y' : C} (g : X ⟶ Y) (g' : X' ⟶ Y') :
diag (X ⨯ X') ≫ prod.map (prod.fst ≫ g) (prod.snd ≫ g') = prod.map g g' :=
by simp
instance {X : C} [has_binary_product X X] : split_mono (diag X) :=
{ retraction := prod.fst }
end prod_lemmas
section coprod_lemmas
@[simp, reassoc]
lemma coprod.desc_comp {V W X Y : C} [has_binary_coproduct X Y] (f : V ⟶ W) (g : X ⟶ V) (h : Y ⟶ V) :
coprod.desc g h ≫ f = coprod.desc (g ≫ f) (h ≫ f) :=
by { ext; simp }
lemma coprod.diag_comp {X Y : C} [has_binary_coproduct X X] (f : X ⟶ Y) :
codiag X ≫ f = coprod.desc f f :=
by simp
@[simp, reassoc]
lemma coprod.inl_map {W X Y Z : C} [has_binary_coproduct W X] [has_binary_coproduct Y Z]
(f : W ⟶ Y) (g : X ⟶ Z) : coprod.inl ≫ coprod.map f g = f ≫ coprod.inl :=
ι_colim_map _ _
@[simp, reassoc]
lemma coprod.inr_map {W X Y Z : C} [has_binary_coproduct W X] [has_binary_coproduct Y Z]
(f : W ⟶ Y) (g : X ⟶ Z) : coprod.inr ≫ coprod.map f g = g ≫ coprod.inr :=
ι_colim_map _ _
@[simp]
lemma coprod.map_id_id {X Y : C} [has_binary_coproduct X Y] :
coprod.map (𝟙 X) (𝟙 Y) = 𝟙 _ :=
by { ext; simp }
@[simp]
lemma coprod.desc_inl_inr {X Y : C} [has_binary_coproduct X Y] :
coprod.desc coprod.inl coprod.inr = 𝟙 (X ⨿ Y) :=
by { ext; simp }
-- The simp linter says simp can prove the reassoc version of this lemma.
@[reassoc, simp]
lemma coprod.map_desc {S T U V W : C} [has_binary_coproduct U W] [has_binary_coproduct T V]
(f : U ⟶ S) (g : W ⟶ S) (h : T ⟶ U) (k : V ⟶ W) :
coprod.map h k ≫ coprod.desc f g = coprod.desc (h ≫ f) (k ≫ g) :=
by { ext; simp }
@[simp]
lemma coprod.desc_comp_inl_comp_inr {W X Y Z : C}
[has_binary_coproduct W Y] [has_binary_coproduct X Z]
(g : W ⟶ X) (g' : Y ⟶ Z) :
coprod.desc (g ≫ coprod.inl) (g' ≫ coprod.inr) = coprod.map g g' :=
by { rw ← coprod.map_desc, simp }
-- We take the right hand side here to be simp normal form, as this way composition lemmas for
-- `f ≫ h` and `g ≫ k` can fire (eg `id_comp`) , while `inl_map` and `inr_map` can still work just
-- as well.
@[simp, reassoc]
lemma coprod.map_map {A₁ A₂ A₃ B₁ B₂ B₃ : C}
[has_binary_coproduct A₁ B₁] [has_binary_coproduct A₂ B₂] [has_binary_coproduct A₃ B₃]
(f : A₁ ⟶ A₂) (g : B₁ ⟶ B₂) (h : A₂ ⟶ A₃) (k : B₂ ⟶ B₃) :
coprod.map f g ≫ coprod.map h k = coprod.map (f ≫ h) (g ≫ k) :=
by { ext; simp }
-- I don't think it's a good idea to make any of the following three simp lemmas.
@[reassoc]
lemma coprod.map_swap {A B X Y : C} (f : A ⟶ B) (g : X ⟶ Y) [has_colimits_of_shape (discrete walking_pair) C] :
coprod.map (𝟙 X) f ≫ coprod.map g (𝟙 B) = coprod.map g (𝟙 A) ≫ coprod.map (𝟙 Y) f :=
by simp
@[reassoc] lemma coprod.map_comp_id {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_binary_coproduct Z W] [has_binary_coproduct Y W] [has_binary_coproduct X W] :
coprod.map (f ≫ g) (𝟙 W) = coprod.map f (𝟙 W) ≫ coprod.map g (𝟙 W) :=
by simp
@[reassoc] lemma coprod.map_id_comp {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_binary_coproduct W X] [has_binary_coproduct W Y] [has_binary_coproduct W Z] :
coprod.map (𝟙 W) (f ≫ g) = coprod.map (𝟙 W) f ≫ coprod.map (𝟙 W) g :=
by simp
/-- If the coproducts `W ⨿ X` and `Y ⨿ Z` exist, then every pair of isomorphisms `f : W ≅ Y` and
`g : W ≅ Z` induces a isomorphism `coprod.map_iso f g : W ⨿ X ≅ Y ⨿ Z`. -/
@[simps]
def coprod.map_iso {W X Y Z : C} [has_binary_coproduct W X] [has_binary_coproduct Y Z]
(f : W ≅ Y) (g : X ≅ Z) : W ⨿ X ≅ Y ⨿ Z :=
{ hom := coprod.map f.hom g.hom,
inv := coprod.map f.inv g.inv }
-- The simp linter says simp can prove the reassoc version of this lemma.
@[reassoc, simp]
lemma coprod.map_codiag {X Y : C} (f : X ⟶ Y) [has_binary_coproduct X X] [has_binary_coproduct Y Y] :
coprod.map f f ≫ codiag Y = codiag X ≫ f :=
by simp
-- The simp linter says simp can prove the reassoc version of this lemma.
@[reassoc, simp]
lemma coprod.map_inl_inr_codiag {X Y : C} [has_binary_coproduct X Y] [has_binary_coproduct (X ⨿ Y) (X ⨿ Y)] :
coprod.map coprod.inl coprod.inr ≫ codiag (X ⨿ Y) = 𝟙 (X ⨿ Y) :=
by simp
-- The simp linter says simp can prove the reassoc version of this lemma.
@[reassoc, simp]
lemma coprod.map_comp_inl_inr_codiag [has_colimits_of_shape (discrete walking_pair) C]
{X X' Y Y' : C} (g : X ⟶ Y) (g' : X' ⟶ Y') :
coprod.map (g ≫ coprod.inl) (g' ≫ coprod.inr) ≫ codiag (Y ⨿ Y') = coprod.map g g' :=
by simp
end coprod_lemmas
variables (C)
/--
`has_binary_products` represents a choice of product for every pair of objects.
See https://stacks.math.columbia.edu/tag/001T.
-/
abbreviation has_binary_products := has_limits_of_shape (discrete walking_pair) C
/--
`has_binary_coproducts` represents a choice of coproduct for every pair of objects.
See https://stacks.math.columbia.edu/tag/04AP.
-/
abbreviation has_binary_coproducts := has_colimits_of_shape (discrete walking_pair) C
/-- If `C` has all limits of diagrams `pair X Y`, then it has all binary products -/
lemma has_binary_products_of_has_limit_pair [Π {X Y : C}, has_limit (pair X Y)] :
has_binary_products C :=
{ has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm }
/-- If `C` has all colimits of diagrams `pair X Y`, then it has all binary coproducts -/
lemma has_binary_coproducts_of_has_colimit_pair [Π {X Y : C}, has_colimit (pair X Y)] :
has_binary_coproducts C :=
{ has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) }
section
variables {C}
/-- The braiding isomorphism which swaps a binary product. -/
@[simps] def prod.braiding (P Q : C) [has_binary_product P Q] [has_binary_product Q P] :
P ⨯ Q ≅ Q ⨯ P :=
{ hom := prod.lift prod.snd prod.fst,
inv := prod.lift prod.snd prod.fst }
/-- The braiding isomorphism can be passed through a map by swapping the order. -/
@[reassoc] lemma braid_natural [has_binary_products C] {W X Y Z : C} (f : X ⟶ Y) (g : Z ⟶ W) :
prod.map f g ≫ (prod.braiding _ _).hom = (prod.braiding _ _).hom ≫ prod.map g f :=
by simp
@[reassoc] lemma prod.symmetry' (P Q : C) [has_binary_product P Q] [has_binary_product Q P] :
prod.lift prod.snd prod.fst ≫ prod.lift prod.snd prod.fst = 𝟙 (P ⨯ Q) :=
(prod.braiding _ _).hom_inv_id
/-- The braiding isomorphism is symmetric. -/
@[reassoc] lemma prod.symmetry (P Q : C) [has_binary_product P Q] [has_binary_product Q P] :
(prod.braiding P Q).hom ≫ (prod.braiding Q P).hom = 𝟙 _ :=
(prod.braiding _ _).hom_inv_id
/-- The associator isomorphism for binary products. -/
@[simps] def prod.associator [has_binary_products C] (P Q R : C) :
(P ⨯ Q) ⨯ R ≅ P ⨯ (Q ⨯ R) :=
{ hom :=
prod.lift
(prod.fst ≫ prod.fst)
(prod.lift (prod.fst ≫ prod.snd) prod.snd),
inv :=
prod.lift
(prod.lift prod.fst (prod.snd ≫ prod.fst))
(prod.snd ≫ prod.snd) }
@[reassoc]
lemma prod.pentagon [has_binary_products C] (W X Y Z : C) :
prod.map ((prod.associator W X Y).hom) (𝟙 Z) ≫
(prod.associator W (X ⨯ Y) Z).hom ≫ prod.map (𝟙 W) ((prod.associator X Y Z).hom) =
(prod.associator (W ⨯ X) Y Z).hom ≫ (prod.associator W X (Y ⨯ Z)).hom :=
by simp
@[reassoc]
lemma prod.associator_naturality [has_binary_products C] {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C}
(f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) :
prod.map (prod.map f₁ f₂) f₃ ≫ (prod.associator Y₁ Y₂ Y₃).hom =
(prod.associator X₁ X₂ X₃).hom ≫ prod.map f₁ (prod.map f₂ f₃) :=
by simp
variables [has_terminal C]
/-- The left unitor isomorphism for binary products with the terminal object. -/
@[simps] def prod.left_unitor (P : C) [has_binary_product (⊤_ C) P] :
⊤_ C ⨯ P ≅ P :=
{ hom := prod.snd,
inv := prod.lift (terminal.from P) (𝟙 _) }
/-- The right unitor isomorphism for binary products with the terminal object. -/
@[simps] def prod.right_unitor (P : C) [has_binary_product P (⊤_ C)] :
P ⨯ ⊤_ C ≅ P :=
{ hom := prod.fst,
inv := prod.lift (𝟙 _) (terminal.from P) }
@[reassoc]
lemma prod.left_unitor_hom_naturality [has_binary_products C] (f : X ⟶ Y) :
prod.map (𝟙 _) f ≫ (prod.left_unitor Y).hom = (prod.left_unitor X).hom ≫ f :=
prod.map_snd _ _
@[reassoc]
lemma prod.left_unitor_inv_naturality [has_binary_products C] (f : X ⟶ Y) :
(prod.left_unitor X).inv ≫ prod.map (𝟙 _) f = f ≫ (prod.left_unitor Y).inv :=
by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, prod.left_unitor_hom_naturality]
@[reassoc]
lemma prod.right_unitor_hom_naturality [has_binary_products C] (f : X ⟶ Y) :
prod.map f (𝟙 _) ≫ (prod.right_unitor Y).hom = (prod.right_unitor X).hom ≫ f :=
prod.map_fst _ _
@[reassoc]
lemma prod_right_unitor_inv_naturality [has_binary_products C] (f : X ⟶ Y) :
(prod.right_unitor X).inv ≫ prod.map f (𝟙 _) = f ≫ (prod.right_unitor Y).inv :=
by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, prod.right_unitor_hom_naturality]
lemma prod.triangle [has_binary_products C] (X Y : C) :
(prod.associator X (⊤_ C) Y).hom ≫ prod.map (𝟙 X) ((prod.left_unitor Y).hom) =
prod.map ((prod.right_unitor X).hom) (𝟙 Y) :=
by tidy
end
section
variables {C} [has_binary_coproducts C]
/-- The braiding isomorphism which swaps a binary coproduct. -/
@[simps] def coprod.braiding (P Q : C) : P ⨿ Q ≅ Q ⨿ P :=
{ hom := coprod.desc coprod.inr coprod.inl,
inv := coprod.desc coprod.inr coprod.inl }
@[reassoc] lemma coprod.symmetry' (P Q : C) :
coprod.desc coprod.inr coprod.inl ≫ coprod.desc coprod.inr coprod.inl = 𝟙 (P ⨿ Q) :=
(coprod.braiding _ _).hom_inv_id
/-- The braiding isomorphism is symmetric. -/
lemma coprod.symmetry (P Q : C) :
(coprod.braiding P Q).hom ≫ (coprod.braiding Q P).hom = 𝟙 _ :=
coprod.symmetry' _ _
/-- The associator isomorphism for binary coproducts. -/
@[simps] def coprod.associator
(P Q R : C) : (P ⨿ Q) ⨿ R ≅ P ⨿ (Q ⨿ R) :=
{ hom :=
coprod.desc
(coprod.desc coprod.inl (coprod.inl ≫ coprod.inr))
(coprod.inr ≫ coprod.inr),
inv :=
coprod.desc
(coprod.inl ≫ coprod.inl)
(coprod.desc (coprod.inr ≫ coprod.inl) coprod.inr) }
lemma coprod.pentagon (W X Y Z : C) :
coprod.map ((coprod.associator W X Y).hom) (𝟙 Z) ≫
(coprod.associator W (X ⨿ Y) Z).hom ≫ coprod.map (𝟙 W) ((coprod.associator X Y Z).hom) =
(coprod.associator (W ⨿ X) Y Z).hom ≫ (coprod.associator W X (Y ⨿ Z)).hom :=
by simp
lemma coprod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) :
coprod.map (coprod.map f₁ f₂) f₃ ≫ (coprod.associator Y₁ Y₂ Y₃).hom =
(coprod.associator X₁ X₂ X₃).hom ≫ coprod.map f₁ (coprod.map f₂ f₃) :=
by simp
variables [has_initial C]
/-- The left unitor isomorphism for binary coproducts with the initial object. -/
@[simps] def coprod.left_unitor
(P : C) : ⊥_ C ⨿ P ≅ P :=
{ hom := coprod.desc (initial.to P) (𝟙 _),
inv := coprod.inr }
/-- The right unitor isomorphism for binary coproducts with the initial object. -/
@[simps] def coprod.right_unitor
(P : C) : P ⨿ ⊥_ C ≅ P :=
{ hom := coprod.desc (𝟙 _) (initial.to P),
inv := coprod.inl }
lemma coprod.triangle (X Y : C) :
(coprod.associator X (⊥_ C) Y).hom ≫ coprod.map (𝟙 X) ((coprod.left_unitor Y).hom) =
coprod.map ((coprod.right_unitor X).hom) (𝟙 Y) :=
by tidy
end
section prod_functor
variables {C} [has_binary_products C]
-- FIXME deterministic timeout with `-T50000`
/-- The binary product functor. -/
@[simps]
def prod.functor : C ⥤ C ⥤ C :=
{ obj := λ X, { obj := λ Y, X ⨯ Y, map := λ Y Z, prod.map (𝟙 X) },
map := λ Y Z f, { app := λ T, prod.map f (𝟙 T) }}
/-- The product functor can be decomposed. -/
def prod.functor_left_comp (X Y : C) :
prod.functor.obj (X ⨯ Y) ≅ prod.functor.obj Y ⋙ prod.functor.obj X :=
nat_iso.of_components (prod.associator _ _) (by tidy)
end prod_functor
section prod_comparison
variables {C} [has_binary_products C]
variables {D : Type u₂} [category.{v} D]
variables (F : C ⥤ D) {A A' B B' : C}
variables [has_binary_product (F.obj A) (F.obj B)] [has_binary_product (F.obj A') (F.obj B')]
/--
The product comparison morphism.
In `category_theory/limits/preserves` we show this is always an iso iff F preserves binary products.
-/
def prod_comparison (F : C ⥤ D) (A B : C) [has_binary_product (F.obj A) (F.obj B)] :
F.obj (A ⨯ B) ⟶ F.obj A ⨯ F.obj B :=
prod.lift (F.map prod.fst) (F.map prod.snd)
/-- Naturality of the prod_comparison morphism in both arguments. -/
@[reassoc] lemma prod_comparison_natural (f : A ⟶ A') (g : B ⟶ B') :
F.map (prod.map f g) ≫ prod_comparison F A' B' = prod_comparison F A B ≫ prod.map (F.map f) (F.map g) :=
begin
rw [prod_comparison, prod_comparison, prod.lift_map, ← F.map_comp, ← F.map_comp,
prod.comp_lift, ← F.map_comp, prod.map_fst, ← F.map_comp, prod.map_snd]
end
@[reassoc]
lemma inv_prod_comparison_map_fst [is_iso (prod_comparison F A B)] :
inv (prod_comparison F A B) ≫ F.map prod.fst = prod.fst :=
begin
erw (as_iso (prod_comparison F A B)).inv_comp_eq,
dsimp [as_iso_hom, prod_comparison],
rw prod.lift_fst,
end
@[reassoc]
lemma inv_prod_comparison_map_snd [is_iso (prod_comparison F A B)] :
inv (prod_comparison F A B) ≫ F.map prod.snd = prod.snd :=
begin
erw (as_iso (prod_comparison F A B)).inv_comp_eq,
dsimp [as_iso_hom, prod_comparison],
rw prod.lift_snd,
end
/-- If the product comparison morphism is an iso, its inverse is natural. -/
@[reassoc]
lemma prod_comparison_inv_natural (f : A ⟶ A') (g : B ⟶ B')
[is_iso (prod_comparison F A B)] [is_iso (prod_comparison F A' B')] :
inv (prod_comparison F A B) ≫ F.map (prod.map f g) = prod.map (F.map f) (F.map g) ≫ inv (prod_comparison F A' B') :=
by { erw [(as_iso (prod_comparison F A' B')).eq_comp_inv, category.assoc,
(as_iso (prod_comparison F A B)).inv_comp_eq, prod_comparison_natural], refl }
end prod_comparison
end category_theory.limits
|
aa0506b445ab1c208d845740689bae04b27789be | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /library/hott/logic.lean | bd41ed824e3565187c9a3f8a6ee224384865c4b9 | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 231 | lean | import data.empty .path
open path
inductive tdecidable [class] (A : Type) : Type :=
inl : A → tdecidable A,
inr : ~A → tdecidable A
structure decidable_paths [class] (A : Type) :=
(elim : ∀(x y : A), tdecidable (x ≈ y))
|
3447d88e0c4eeec74372a35c4c3da45ef07943e0 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Lean/Elab/AuxDef.lean | f26d391aa28cfdc9c43a6705a4ff3a8f1d0d3103 | [
"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 | 1,381 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import Lean.Elab.Command
namespace Lean.Elab.Command
open Lean.Parser.Command
open Lean.Parser.Term
/--
Declares an auxiliary definition with an automatically generated name.
For example, `aux_def foo : Nat := 42` creates a definition
with an internal, unused name based on the suggestion `foo`.
-/
scoped syntax (name := aux_def) docComment ? attributes ? "aux_def" ident+ ":" term ":=" term : command
@[builtinCommandElab «aux_def»]
def elabAuxDef : CommandElab
| `($[$doc?:docComment]? $[$attrs?:attributes]? aux_def $[$suggestion:ident]* : $ty := $body) => do
let id := suggestion.map (·.getId.eraseMacroScopes) |>.foldl (· ++ ·) Name.anonymous
let id := `_aux ++ (← getMainModule) ++ `_ ++ id
let id := String.intercalate "_" <| id.components.map (·.toString (escape := false))
let ns ← getCurrNamespace
-- make sure we only add a single component so that scoped workes
let id ← mkAuxName (ns.mkStr id) 1
let id := id.replacePrefix ns Name.anonymous -- TODO: replace with def _root_.id
elabCommand <|
← `($[$doc?:docComment]? $[$attrs?:attributes]?
def $(mkIdentFrom (mkNullNode suggestion) id):ident : $ty := $body)
| _ => throwUnsupportedSyntax
|
4cd18209936b0bce8aca81317879fb2f315785a4 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Util/FindMVar.lean | eb49dc376f58b6a86e140294f578b2bef3d6c013 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,030 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Expr
namespace Lean
namespace FindMVar
abbrev Visitor := Option MVarId → Option MVarId
mutual
partial def visit (p : MVarId → Bool) (e : Expr) : Visitor := fun s =>
if s.isSome || !e.hasMVar then s else main p e s
partial def main (p : MVarId → Bool) : Expr → Visitor
| Expr.proj _ _ e => visit p e
| Expr.forallE _ d b _ => visit p b ∘ visit p d
| Expr.lam _ d b _ => visit p b ∘ visit p d
| Expr.letE _ t v b _ => visit p b ∘ visit p v ∘ visit p t
| Expr.app f a => visit p a ∘ visit p f
| Expr.mdata _ b => visit p b
| Expr.mvar mvarId => fun s => if s.isNone && p mvarId then some mvarId else s
| _ => id
end
end FindMVar
@[inline] def Expr.findMVar? (e : Expr) (p : MVarId → Bool) : Option MVarId :=
FindMVar.main p e none
end Lean
|
d80a66a1b6c0606529dd9ea08a668bc1598e2e87 | 5ca7b1b12d14c4742e29366312ba2c2ef8201b21 | /src/game/world6/level1.lean | 2cca7b7a80dbf89d02d06bb83dc023a193159d99 | [
"Apache-2.0"
] | permissive | MatthiasHu/natural_number_game | 2e464482ef3001863430b0336133b6697b275ba3 | 2d764f72669ae30861f6a1057fce0257f3e466c4 | refs/heads/master | 1,609,719,110,419 | 1,576,345,737,000 | 1,576,345,737,000 | 240,296,314 | 0 | 0 | Apache-2.0 | 1,581,608,357,000 | 1,581,608,356,000 | null | UTF-8 | Lean | false | false | 3,071 | lean | -- World name : Proposition world
/-
# Proposition world.
A Proposition is a true/false statement, like `2 + 2 = 4` or `2 + 2 = 5`.
Just like we can have concrete sets in Lean like `mynat`, and abstract
sets called things like `X`, we can also have concrete propositions like
`2 + 2 = 5` and abstract propositions called things like `P`.
Mathematicians are very good at conflating a theorem with its proof.
They might say "now use theorem 12 and we're done". What they really
mean is "now use the proof of theorem 12..." (i.e. the fact that we proved
it already). Particularly problematic is the fact that mathematicians
use the word Proposition to mean "a relatively straightforward statement
which is true" and computer scientists use it to mean "a statement of
arbitrary complexity, which might be true or false". Computer scientists
are far more careful about distinguishing between a proposition and a proof.
For example: `x + 0 = x` is a proposition, and `add_zero x`
is its proof. The convention we'll use is capital letters for propositions
and small letters for proofs.
In this world you will see the local context in the following kind of state:
```
P : Prop
p : P
```
Here `P` is the true/false statement (the statement of proposition), and `p` is its proof.
It's like `P` being the set and `p` being the element. In fact computer scientists
sometimes think about the following analogy: propositions are like sets,
and their proofs are like their elements.
## What's going on in this world?
We're going to learn about manipulating propositions and proofs.
Fortunately, we don't need to learn a bunch of new tactics -- the
ones we just learnt (`exact`, `intro`, `have`, `apply`) will be perfect.
The levels in proposition world are "back to normal", we're proving
theorems, not constructing elements of sets. Or are we?
If you delete the sorry below then your local context will look like this:
```
P Q : Prop,
p : P,
h : P → Q
⊢ Q
```
In this situation, we have true/false statements $P$ and $Q$,
a proof $p$ of $P$, and $h$ is the hypothesis that $P\implies Q$.
Our goal is to construct a proof of $Q$. It's clear what to do
*mathematically* to solve this goal, $P$ is true and $P$ implies $Q$
so $Q$ is true. But how to do it in Lean?
Adopting a point of view wholly unfamiliar to many mathematicians,
Lean interprets the hypothesis $h$ as a function from proofs
of $P$ to proofs of $Q$, so the rather surprising approach
`exact h(p),`
works to close the goal.
Note that `exact h(P),` (with a capital P) won't work;
this is a common error I see from beginners. "We're trying to solve P
so it's exactly P". The goal states the *theorem*, your job is to
construct the *proof*. $P$ is not a proof of $P$, it's $p$ that is a proof of $P$.
In Lean, Propositions are types, like sets, and proofs are terms,
like elements of sets.
## Level 1: the `exact` tactic.
-/
/- Lemma : no-side-bar
If $P$ is true, and $P\implies Q$ is also true, then $Q$ is true.
-/
example (P Q : Prop) (p : P) (h : P → Q) : Q :=
begin
exact h(p),
end
|
9d6e32e85ca4394fa98324eb35cccd2e84084364 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/PrettyPrinter/Basic.lean | 2179877c82fbc13b4100e4bb332398c245307b7a | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,065 | lean | /-
Copyright (c) 2020 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
import Lean.KeyedDeclsAttribute
namespace Lean
namespace PrettyPrinter
/- Auxiliary internal exception for backtracking the pretty printer.
See `orelse.parenthesizer` for example -/
builtin_initialize backtrackExceptionId : InternalExceptionId ← registerInternalExceptionId `backtrackFormatter
unsafe def runForNodeKind {α} (attr : KeyedDeclsAttribute α) (k : SyntaxNodeKind) (interp : ParserDescr → CoreM α) : CoreM α := do
match attr.getValues (← getEnv) k with
| p::_ => pure p
| _ =>
-- assume `k` is from a `ParserDescr`, in which case we assume it's also the declaration name
let info ← getConstInfo k
if info.type.isConstOf ``ParserDescr || info.type.isConstOf ``TrailingParserDescr then
let d ← evalConst ParserDescr k
interp d
else
throwError "no declaration of attribute [{attr.defn.name}] found for '{k}'"
end PrettyPrinter
end Lean
|
2640ebd19bf4e40f347d8024200b3d1381b8de3e | bb31430994044506fa42fd667e2d556327e18dfe | /src/group_theory/submonoid/membership.lean | 355e74a4360d64756212337b7d43cb1b04fb41f3 | [
"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 | 23,201 | 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 group_theory.submonoid.operations
import algebra.big_operators.basic
import algebra.free_monoid.basic
import data.finset.noncomm_prod
/-!
# Submonoids: membership criteria
In this file we prove various facts about membership in a submonoid:
* `list_prod_mem`, `multiset_prod_mem`, `prod_mem`: if each element of a collection belongs
to a multiplicative submonoid, then so does their product;
* `list_sum_mem`, `multiset_sum_mem`, `sum_mem`: if each element of a collection belongs
to an additive submonoid, then so does their sum;
* `pow_mem`, `nsmul_mem`: if `x ∈ S` where `S` is a multiplicative (resp., additive) submonoid and
`n` is a natural number, then `x^n` (resp., `n • x`) belongs to `S`;
* `mem_supr_of_directed`, `coe_supr_of_directed`, `mem_Sup_of_directed_on`,
`coe_Sup_of_directed_on`: the supremum of a directed collection of submonoid is their union.
* `sup_eq_range`, `mem_sup`: supremum of two submonoids `S`, `T` of a commutative monoid is the set
of products;
* `closure_singleton_eq`, `mem_closure_singleton`, `mem_closure_pair`: the multiplicative (resp.,
additive) closure of `{x}` consists of powers (resp., natural multiples) of `x`, and a similar
result holds for the closure of `{x, y}`.
## Tags
submonoid, submonoids
-/
open_locale big_operators
variables {M A B : Type*}
section assoc
variables [monoid M] [set_like B M] [submonoid_class B M] {S : B}
namespace submonoid_class
@[simp, norm_cast, to_additive] theorem coe_list_prod (l : list S) :
(l.prod : M) = (l.map coe).prod :=
(submonoid_class.subtype S : _ →* M).map_list_prod l
@[simp, norm_cast, to_additive] theorem coe_multiset_prod {M} [comm_monoid M] [set_like B M]
[submonoid_class B M] (m : multiset S) : (m.prod : M) = (m.map coe).prod :=
(submonoid_class.subtype S : _ →* M).map_multiset_prod m
@[simp, norm_cast, to_additive] theorem coe_finset_prod {ι M} [comm_monoid M] [set_like B M]
[submonoid_class B M] (f : ι → S) (s : finset ι) :
↑(∏ i in s, f i) = (∏ i in s, f i : M) :=
(submonoid_class.subtype S : _ →* M).map_prod f s
end submonoid_class
open submonoid_class
/-- Product of a list of elements in a submonoid is in the submonoid. -/
@[to_additive "Sum of a list of elements in an `add_submonoid` is in the `add_submonoid`."]
lemma list_prod_mem {l : list M} (hl : ∀ x ∈ l, x ∈ S) : l.prod ∈ S :=
by { lift l to list S using hl, rw ← coe_list_prod, exact l.prod.coe_prop }
/-- Product of a multiset of elements in a submonoid of a `comm_monoid` is in the submonoid. -/
@[to_additive "Sum of a multiset of elements in an `add_submonoid` of an `add_comm_monoid` is
in the `add_submonoid`."]
lemma multiset_prod_mem {M} [comm_monoid M] [set_like B M] [submonoid_class B M] (m : multiset M)
(hm : ∀ a ∈ m, a ∈ S) : m.prod ∈ S :=
by { lift m to multiset S using hm, rw ← coe_multiset_prod, exact m.prod.coe_prop }
/-- Product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is in the
submonoid. -/
@[to_additive "Sum of elements in an `add_submonoid` of an `add_comm_monoid` indexed by a `finset`
is in the `add_submonoid`."]
lemma prod_mem {M : Type*} [comm_monoid M] [set_like B M] [submonoid_class B M]
{ι : Type*} {t : finset ι} {f : ι → M} (h : ∀c ∈ t, f c ∈ S) :
∏ c in t, f c ∈ S :=
multiset_prod_mem (t.1.map f) $ λ x hx, let ⟨i, hi, hix⟩ := multiset.mem_map.1 hx in hix ▸ h i hi
namespace submonoid
variables (s : submonoid M)
@[simp, norm_cast, to_additive] theorem coe_list_prod (l : list s) :
(l.prod : M) = (l.map coe).prod :=
s.subtype.map_list_prod l
@[simp, norm_cast, to_additive] theorem coe_multiset_prod {M} [comm_monoid M] (S : submonoid M)
(m : multiset S) : (m.prod : M) = (m.map coe).prod :=
S.subtype.map_multiset_prod m
@[simp, norm_cast, to_additive] theorem coe_finset_prod {ι M} [comm_monoid M] (S : submonoid M)
(f : ι → S) (s : finset ι) :
↑(∏ i in s, f i) = (∏ i in s, f i : M) :=
S.subtype.map_prod f s
/-- Product of a list of elements in a submonoid is in the submonoid. -/
@[to_additive "Sum of a list of elements in an `add_submonoid` is in the `add_submonoid`."]
lemma list_prod_mem {l : list M} (hl : ∀ x ∈ l, x ∈ s) : l.prod ∈ s :=
by { lift l to list s using hl, rw ← coe_list_prod, exact l.prod.coe_prop }
/-- Product of a multiset of elements in a submonoid of a `comm_monoid` is in the submonoid. -/
@[to_additive "Sum of a multiset of elements in an `add_submonoid` of an `add_comm_monoid` is
in the `add_submonoid`."]
lemma multiset_prod_mem {M} [comm_monoid M] (S : submonoid M) (m : multiset M)
(hm : ∀ a ∈ m, a ∈ S) : m.prod ∈ S :=
by { lift m to multiset S using hm, rw ← coe_multiset_prod, exact m.prod.coe_prop }
@[to_additive]
lemma multiset_noncomm_prod_mem (S : submonoid M) (m : multiset M) (comm) (h : ∀ (x ∈ m), x ∈ S) :
m.noncomm_prod comm ∈ S :=
begin
induction m using quotient.induction_on with l,
simp only [multiset.quot_mk_to_coe, multiset.noncomm_prod_coe],
exact submonoid.list_prod_mem _ h,
end
/-- Product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is in the
submonoid. -/
@[to_additive "Sum of elements in an `add_submonoid` of an `add_comm_monoid` indexed by a `finset`
is in the `add_submonoid`."]
lemma prod_mem {M : Type*} [comm_monoid M] (S : submonoid M)
{ι : Type*} {t : finset ι} {f : ι → M} (h : ∀c ∈ t, f c ∈ S) :
∏ c in t, f c ∈ S :=
S.multiset_prod_mem (t.1.map f) $ λ x hx, let ⟨i, hi, hix⟩ := multiset.mem_map.1 hx in hix ▸ h i hi
@[to_additive]
lemma noncomm_prod_mem (S : submonoid M) {ι : Type*} (t : finset ι) (f : ι → M) (comm)
(h : ∀ c ∈ t, f c ∈ S) :
t.noncomm_prod f comm ∈ S :=
begin
apply multiset_noncomm_prod_mem,
intro y,
rw multiset.mem_map,
rintros ⟨x, ⟨hx, rfl⟩⟩,
exact h x hx,
end
end submonoid
end assoc
section non_assoc
variables [mul_one_class M]
open set
namespace submonoid
-- TODO: this section can be generalized to `[submonoid_class B M] [complete_lattice B]`
-- such that `complete_lattice.le` coincides with `set_like.le`
@[to_additive]
lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → submonoid M} (hS : directed (≤) S)
{x : M} :
x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i :=
begin
refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩,
suffices : x ∈ closure (⋃ i, (S i : set M)) → ∃ i, x ∈ S i,
by simpa only [closure_Union, closure_eq (S _)] using this,
refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _),
{ exact hι.elim (λ i, ⟨i, (S i).one_mem⟩) },
{ rintros x y ⟨i, hi⟩ ⟨j, hj⟩,
rcases hS i j with ⟨k, hki, hkj⟩,
exact ⟨k, (S k).mul_mem (hki hi) (hkj hj)⟩ }
end
@[to_additive]
lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → submonoid M} (hS : directed (≤) S) :
((⨆ i, S i : submonoid M) : set M) = ⋃ i, ↑(S i) :=
set.ext $ λ x, by simp [mem_supr_of_directed hS]
@[to_additive]
lemma mem_Sup_of_directed_on {S : set (submonoid M)} (Sne : S.nonempty)
(hS : directed_on (≤) S) {x : M} :
x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s :=
begin
haveI : nonempty S := Sne.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk]
end
@[to_additive]
lemma coe_Sup_of_directed_on {S : set (submonoid M)} (Sne : S.nonempty) (hS : directed_on (≤) S) :
(↑(Sup S) : set M) = ⋃ s ∈ S, ↑s :=
set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS]
@[to_additive]
lemma mem_sup_left {S T : submonoid M} : ∀ {x : M}, x ∈ S → x ∈ S ⊔ T :=
show S ≤ S ⊔ T, from le_sup_left
@[to_additive]
lemma mem_sup_right {S T : submonoid M} : ∀ {x : M}, x ∈ T → x ∈ S ⊔ T :=
show T ≤ S ⊔ T, from le_sup_right
@[to_additive]
lemma mul_mem_sup {S T : submonoid M} {x y : M} (hx : x ∈ S) (hy : y ∈ T) : x * y ∈ S ⊔ T :=
(S ⊔ T).mul_mem (mem_sup_left hx) (mem_sup_right hy)
@[to_additive]
lemma mem_supr_of_mem {ι : Sort*} {S : ι → submonoid M} (i : ι) :
∀ {x : M}, x ∈ S i → x ∈ supr S :=
show S i ≤ supr S, from le_supr _ _
@[to_additive]
lemma mem_Sup_of_mem {S : set (submonoid M)} {s : submonoid M}
(hs : s ∈ S) : ∀ {x : M}, x ∈ s → x ∈ Sup S :=
show s ≤ Sup S, from le_Sup hs
/-- An induction principle for elements of `⨆ i, S i`.
If `C` holds for `1` and all elements of `S i` for all `i`, and is preserved under multiplication,
then it holds for all elements of the supremum of `S`. -/
@[elab_as_eliminator, to_additive /-" An induction principle for elements of `⨆ i, S i`.
If `C` holds for `0` and all elements of `S i` for all `i`, and is preserved under addition,
then it holds for all elements of the supremum of `S`. "-/]
lemma supr_induction {ι : Sort*} (S : ι → submonoid M) {C : M → Prop} {x : M} (hx : x ∈ ⨆ i, S i)
(hp : ∀ i (x ∈ S i), C x)
(h1 : C 1)
(hmul : ∀ x y, C x → C y → C (x * y)) : C x :=
begin
rw supr_eq_closure at hx,
refine closure_induction hx (λ x hx, _) h1 hmul,
obtain ⟨i, hi⟩ := set.mem_Union.mp hx,
exact hp _ _ hi,
end
/-- A dependent version of `submonoid.supr_induction`. -/
@[elab_as_eliminator, to_additive /-"A dependent version of `add_submonoid.supr_induction`. "-/]
lemma supr_induction' {ι : Sort*} (S : ι → submonoid M) {C : Π x, (x ∈ ⨆ i, S i) → Prop}
(hp : ∀ i (x ∈ S i), C x (mem_supr_of_mem i ‹_›))
(h1 : C 1 (one_mem _))
(hmul : ∀ x y hx hy, C x hx → C y hy → C (x * y) (mul_mem ‹_› ‹_›))
{x : M} (hx : x ∈ ⨆ i, S i) : C x hx :=
begin
refine exists.elim _ (λ (hx : x ∈ ⨆ i, S i) (hc : C x hx), hc),
refine supr_induction S hx (λ i x hx, _) _ (λ x y, _),
{ exact ⟨_, hp _ _ hx⟩ },
{ exact ⟨_, h1⟩ },
{ rintro ⟨_, Cx⟩ ⟨_, Cy⟩,
refine ⟨_, hmul _ _ _ _ Cx Cy⟩ },
end
end submonoid
end non_assoc
namespace free_monoid
variables {α : Type*}
open submonoid
@[to_additive]
theorem closure_range_of : closure (set.range $ @of α) = ⊤ :=
eq_top_iff.2 $ λ x hx, free_monoid.rec_on x (one_mem _) $ λ x xs hxs,
mul_mem (subset_closure $ set.mem_range_self _) hxs
end free_monoid
namespace submonoid
variables [monoid M]
open monoid_hom
lemma closure_singleton_eq (x : M) : closure ({x} : set M) = (powers_hom M x).mrange :=
closure_eq_of_le (set.singleton_subset_iff.2 ⟨multiplicative.of_add 1, pow_one x⟩) $
λ x ⟨n, hn⟩, hn ▸ pow_mem (subset_closure $ set.mem_singleton _) _
/-- The submonoid generated by an element of a monoid equals the set of natural number powers of
the element. -/
lemma mem_closure_singleton {x y : M} : y ∈ closure ({x} : set M) ↔ ∃ n:ℕ, x^n=y :=
by rw [closure_singleton_eq, mem_mrange]; refl
lemma mem_closure_singleton_self {y : M} : y ∈ closure ({y} : set M) :=
mem_closure_singleton.2 ⟨1, pow_one y⟩
lemma closure_singleton_one : closure ({1} : set M) = ⊥ :=
by simp [eq_bot_iff_forall, mem_closure_singleton]
@[to_additive] lemma _root_.free_monoid.mrange_lift {α} (f : α → M) :
(free_monoid.lift f).mrange = closure (set.range f) :=
by rw [mrange_eq_map, ← free_monoid.closure_range_of, map_mclosure, ← set.range_comp,
free_monoid.lift_comp_of]
@[to_additive]
lemma closure_eq_mrange (s : set M) : closure s = (free_monoid.lift (coe : s → M)).mrange :=
by rw [free_monoid.mrange_lift, subtype.range_coe]
@[to_additive] lemma closure_eq_image_prod (s : set M) :
(closure s : set M) = list.prod '' {l : list M | ∀ x ∈ l, x ∈ s} :=
begin
rw [closure_eq_mrange, coe_mrange, ← list.range_map_coe, ← set.range_comp, function.comp],
exact congr_arg _ (funext $ free_monoid.lift_apply _),
end
@[to_additive]
lemma exists_list_of_mem_closure {s : set M} {x : M} (hx : x ∈ closure s) :
∃ (l : list M) (hl : ∀ y ∈ l, y ∈ s), l.prod = x :=
by rwa [← set_like.mem_coe, closure_eq_image_prod, set.mem_image_iff_bex] at hx
@[to_additive]
lemma exists_multiset_of_mem_closure {M : Type*} [comm_monoid M] {s : set M}
{x : M} (hx : x ∈ closure s) : ∃ (l : multiset M) (hl : ∀ y ∈ l, y ∈ s), l.prod = x :=
begin
obtain ⟨l, h1, h2⟩ := exists_list_of_mem_closure hx,
exact ⟨l, h1, (multiset.coe_prod l).trans h2⟩,
end
@[to_additive]
lemma closure_induction_left {s : set M} {p : M → Prop} {x : M} (h : x ∈ closure s) (H1 : p 1)
(Hmul : ∀ (x ∈ s) y, p y → p (x * y)) : p x :=
begin
rw closure_eq_mrange at h,
obtain ⟨l, rfl⟩ := h,
induction l using free_monoid.rec_on with x y ih,
{ exact H1 },
{ simpa only [map_mul, free_monoid.lift_eval_of] using Hmul _ x.prop _ ih }
end
@[elab_as_eliminator, to_additive]
lemma induction_of_closure_eq_top_left {s : set M} {p : M → Prop} (hs : closure s = ⊤) (x : M)
(H1 : p 1) (Hmul : ∀ (x ∈ s) y, p y → p (x * y)) : p x :=
closure_induction_left (by { rw [hs], exact mem_top _ }) H1 Hmul
@[to_additive]
lemma closure_induction_right {s : set M} {p : M → Prop} {x : M} (h : x ∈ closure s) (H1 : p 1)
(Hmul : ∀ x (y ∈ s), p x → p (x * y)) : p x :=
@closure_induction_left _ _ (mul_opposite.unop ⁻¹' s) (p ∘ mul_opposite.unop) (mul_opposite.op x)
(closure_induction h (λ x hx, subset_closure hx) (one_mem _) (λ x y hx hy, mul_mem hy hx))
H1 (λ x hx y, Hmul _ _ hx)
@[elab_as_eliminator, to_additive]
lemma induction_of_closure_eq_top_right {s : set M} {p : M → Prop} (hs : closure s = ⊤) (x : M)
(H1 : p 1) (Hmul : ∀ x (y ∈ s), p x → p (x * y)) : p x :=
closure_induction_right (by { rw [hs], exact mem_top _ }) H1 Hmul
/-- The submonoid generated by an element. -/
def powers (n : M) : submonoid M :=
submonoid.copy (powers_hom M n).mrange (set.range ((^) n : ℕ → M)) $
set.ext (λ n, exists_congr $ λ i, by simp; refl)
@[simp] lemma mem_powers (n : M) : n ∈ powers n := ⟨1, pow_one _⟩
lemma mem_powers_iff (x z : M) : x ∈ powers z ↔ ∃ n : ℕ, z ^ n = x := iff.rfl
lemma powers_eq_closure (n : M) : powers n = closure {n} :=
by { ext, exact mem_closure_singleton.symm }
lemma powers_subset {n : M} {P : submonoid M} (h : n ∈ P) : powers n ≤ P :=
λ x hx, match x, hx with _, ⟨i, rfl⟩ := pow_mem h i end
@[simp] lemma powers_one : powers (1 : M) = ⊥ := bot_unique $ powers_subset (one_mem _)
/-- Exponentiation map from natural numbers to powers. -/
@[simps] def pow (n : M) (m : ℕ) : powers n :=
(powers_hom M n).mrange_restrict (multiplicative.of_add m)
lemma pow_apply (n : M) (m : ℕ) : submonoid.pow n m = ⟨n ^ m, m, rfl⟩ := rfl
/-- Logarithms from powers to natural numbers. -/
def log [decidable_eq M] {n : M} (p : powers n) : ℕ :=
nat.find $ (mem_powers_iff p.val n).mp p.prop
@[simp] theorem pow_log_eq_self [decidable_eq M] {n : M} (p : powers n) : pow n (log p) = p :=
subtype.ext $ nat.find_spec p.prop
lemma pow_right_injective_iff_pow_injective {n : M} :
function.injective (λ m : ℕ, n ^ m) ↔ function.injective (pow n) :=
subtype.coe_injective.of_comp_iff (pow n)
@[simp] theorem log_pow_eq_self [decidable_eq M] {n : M} (h : function.injective (λ m : ℕ, n ^ m))
(m : ℕ) : log (pow n m) = m :=
pow_right_injective_iff_pow_injective.mp h $ pow_log_eq_self _
/-- The exponentiation map is an isomorphism from the additive monoid on natural numbers to powers
when it is injective. The inverse is given by the logarithms. -/
@[simps]
def pow_log_equiv [decidable_eq M] {n : M} (h : function.injective (λ m : ℕ, n ^ m)) :
multiplicative ℕ ≃* powers n :=
{ to_fun := λ m, pow n m.to_add,
inv_fun := λ m, multiplicative.of_add (log m),
left_inv := log_pow_eq_self h,
right_inv := pow_log_eq_self,
map_mul' := λ _ _, by { simp only [pow, map_mul, of_add_add, to_add_mul] } }
lemma log_mul [decidable_eq M] {n : M} (h : function.injective (λ m : ℕ, n ^ m))
(x y : powers (n : M)) : log (x * y) = log x + log y := (pow_log_equiv h).symm.map_mul x y
theorem log_pow_int_eq_self {x : ℤ} (h : 1 < x.nat_abs) (m : ℕ) : log (pow x m) = m :=
(pow_log_equiv (int.pow_right_injective h)).symm_apply_apply _
@[simp] lemma map_powers {N : Type*} {F : Type*} [monoid N] [monoid_hom_class F M N]
(f : F) (m : M) : (powers m).map f = powers (f m) :=
by simp only [powers_eq_closure, map_mclosure f, set.image_singleton]
/-- If all the elements of a set `s` commute, then `closure s` is a commutative monoid. -/
@[to_additive "If all the elements of a set `s` commute, then `closure s` forms an additive
commutative monoid."]
def closure_comm_monoid_of_comm {s : set M} (hcomm : ∀ a b ∈ s, a * b = b * a) :
comm_monoid (closure s) :=
{ mul_comm := λ x y,
begin
ext,
simp only [submonoid.coe_mul],
exact closure_induction₂ x.prop y.prop hcomm commute.one_left commute.one_right
(λ x y z, commute.mul_left) (λ x y z, commute.mul_right),
end,
.. (closure s).to_monoid }
end submonoid
@[to_additive] lemma is_scalar_tower.of_mclosure_eq_top {N α} [monoid M] [mul_action M N]
[has_smul N α] [mul_action M α] {s : set M} (htop : submonoid.closure s = ⊤)
(hs : ∀ (x ∈ s) (y : N) (z : α), (x • y) • z = x • (y • z)) :
is_scalar_tower M N α :=
begin
refine ⟨λ x, submonoid.induction_of_closure_eq_top_left htop x _ _⟩,
{ intros y z, rw [one_smul, one_smul] },
{ clear x, intros x hx x' hx' y z, rw [mul_smul, mul_smul, hs x hx, hx'] }
end
@[to_additive] lemma smul_comm_class.of_mclosure_eq_top {N α} [monoid M]
[has_smul N α] [mul_action M α] {s : set M} (htop : submonoid.closure s = ⊤)
(hs : ∀ (x ∈ s) (y : N) (z : α), x • y • z = y • x • z) :
smul_comm_class M N α :=
begin
refine ⟨λ x, submonoid.induction_of_closure_eq_top_left htop x _ _⟩,
{ intros y z, rw [one_smul, one_smul] },
{ clear x, intros x hx x' hx' y z, rw [mul_smul, mul_smul, hx', hs x hx] }
end
namespace submonoid
variables {N : Type*} [comm_monoid N]
open monoid_hom
@[to_additive]
lemma sup_eq_range (s t : submonoid N) : s ⊔ t = (s.subtype.coprod t.subtype).mrange :=
by rw [mrange_eq_map, ← mrange_inl_sup_mrange_inr, map_sup, map_mrange, coprod_comp_inl,
map_mrange, coprod_comp_inr, range_subtype, range_subtype]
@[to_additive]
lemma mem_sup {s t : submonoid N} {x : N} :
x ∈ s ⊔ t ↔ ∃ (y ∈ s) (z ∈ t), y * z = x :=
by simp only [sup_eq_range, mem_mrange, coprod_apply, prod.exists, set_like.exists,
coe_subtype, subtype.coe_mk]
end submonoid
namespace add_submonoid
variables [add_monoid A]
open set
lemma closure_singleton_eq (x : A) : closure ({x} : set A) = (multiples_hom A x).mrange :=
closure_eq_of_le (set.singleton_subset_iff.2 ⟨1, one_nsmul x⟩) $
λ x ⟨n, hn⟩, hn ▸ nsmul_mem (subset_closure $ set.mem_singleton _) _
/-- The `add_submonoid` generated by an element of an `add_monoid` equals the set of
natural number multiples of the element. -/
lemma mem_closure_singleton {x y : A} :
y ∈ closure ({x} : set A) ↔ ∃ n:ℕ, n • x = y :=
by rw [closure_singleton_eq, add_monoid_hom.mem_mrange]; refl
lemma closure_singleton_zero : closure ({0} : set A) = ⊥ :=
by simp [eq_bot_iff_forall, mem_closure_singleton, nsmul_zero]
/-- The additive submonoid generated by an element. -/
def multiples (x : A) : add_submonoid A :=
add_submonoid.copy (multiples_hom A x).mrange (set.range (λ i, i • x : ℕ → A)) $
set.ext (λ n, exists_congr $ λ i, by simp; refl)
attribute [to_additive multiples] submonoid.powers
attribute [to_additive mem_multiples] submonoid.mem_powers
attribute [to_additive mem_multiples_iff] submonoid.mem_powers_iff
attribute [to_additive multiples_eq_closure] submonoid.powers_eq_closure
attribute [to_additive multiples_subset] submonoid.powers_subset
attribute [to_additive multiples_zero] submonoid.powers_one
end add_submonoid
/-! Lemmas about additive closures of `subsemigroup`. -/
namespace mul_mem_class
variables {R : Type*} [non_unital_non_assoc_semiring R] [set_like M R] [mul_mem_class M R]
{S : M} {a b : R}
/-- The product of an element of the additive closure of a multiplicative subsemigroup `M`
and an element of `M` is contained in the additive closure of `M`. -/
lemma mul_right_mem_add_closure
(ha : a ∈ add_submonoid.closure (S : set R)) (hb : b ∈ S) :
a * b ∈ add_submonoid.closure (S : set R) :=
begin
revert b,
refine add_submonoid.closure_induction ha _ _ _; clear ha a,
{ exact λ r hr b hb, add_submonoid.mem_closure.mpr (λ y hy, hy (mul_mem hr hb)) },
{ exact λ b hb, by simp only [zero_mul, (add_submonoid.closure (S : set R)).zero_mem] },
{ simp_rw add_mul,
exact λ r s hr hs b hb, (add_submonoid.closure (S : set R)).add_mem (hr hb) (hs hb) }
end
/-- The product of two elements of the additive closure of a submonoid `M` is an element of the
additive closure of `M`. -/
lemma mul_mem_add_closure
(ha : a ∈ add_submonoid.closure (S : set R)) (hb : b ∈ add_submonoid.closure (S : set R)) :
a * b ∈ add_submonoid.closure (S : set R) :=
begin
revert a,
refine add_submonoid.closure_induction hb _ _ _; clear hb b,
{ exact λ r hr b hb, mul_mem_class.mul_right_mem_add_closure hb hr },
{ exact λ b hb, by simp only [mul_zero, (add_submonoid.closure (S : set R)).zero_mem] },
{ simp_rw mul_add,
exact λ r s hr hs b hb, (add_submonoid.closure (S : set R)).add_mem (hr hb) (hs hb) }
end
/-- The product of an element of `S` and an element of the additive closure of a multiplicative
submonoid `S` is contained in the additive closure of `S`. -/
lemma mul_left_mem_add_closure (ha : a ∈ S) (hb : b ∈ add_submonoid.closure (S : set R)) :
a * b ∈ add_submonoid.closure (S : set R) :=
mul_mem_add_closure (add_submonoid.mem_closure.mpr (λ sT hT, hT ha)) hb
end mul_mem_class
namespace submonoid
/-- An element is in the closure of a two-element set if it is a linear combination of those two
elements. -/
@[to_additive "An element is in the closure of a two-element set if it is a linear combination of
those two elements."]
lemma mem_closure_pair {A : Type*} [comm_monoid A] (a b c : A) :
c ∈ submonoid.closure ({a, b} : set A) ↔ ∃ m n : ℕ, a ^ m * b ^ n = c :=
begin
rw [←set.singleton_union, submonoid.closure_union, mem_sup],
simp_rw [exists_prop, mem_closure_singleton, exists_exists_eq_and],
end
end submonoid
section mul_add
lemma of_mul_image_powers_eq_multiples_of_mul [monoid M] {x : M} :
additive.of_mul '' ((submonoid.powers x) : set M) = add_submonoid.multiples (additive.of_mul x) :=
begin
ext,
split,
{ rintros ⟨y, ⟨n, hy1⟩, hy2⟩,
use n,
simpa [← of_mul_pow, hy1] },
{ rintros ⟨n, hn⟩,
refine ⟨x ^ n, ⟨n, rfl⟩, _⟩,
rwa of_mul_pow }
end
lemma of_add_image_multiples_eq_powers_of_add [add_monoid A] {x : A} :
multiplicative.of_add '' ((add_submonoid.multiples x) : set A) =
submonoid.powers (multiplicative.of_add x) :=
begin
symmetry,
rw equiv.eq_image_iff_symm_image_eq,
exact of_mul_image_powers_eq_multiples_of_mul,
end
end mul_add
|
54d04b385dae9eb471b12298dce219ff43b2da79 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /07_Induction_and_Recursion.org.2.lean | b8ae41320de165a7794e9ead88a57fcf3d9e6208 | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 245 | lean | /- page 100 -/
import standard
open nat
definition sub2 : nat → nat
| sub2 0 := 0
| sub2 1 := 0
| sub2 (a+2) := a
-- BEGIN
example : sub2 0 = 0 := rfl
example : sub2 1 = 0 := rfl
example (a : nat) : sub2 (a + 2) = a := rfl
-- END
|
0235a3f71add7765d06f38614f48e4e545109dde | 4727251e0cd73359b15b664c3170e5d754078599 | /src/ring_theory/free_comm_ring.lean | 214f602c4430a415fcfe7290eda1a15993eace1e | [
"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 | 14,050 | lean | /-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Johan Commelin
-/
import data.mv_polynomial.equiv
import data.mv_polynomial.comm_ring
import logic.equiv.functor
import ring_theory.free_ring
/-!
# Free commutative rings
The theory of the free commutative ring generated by a type `α`.
It is isomorphic to the polynomial ring over ℤ with variables
in `α`
## Main definitions
* `free_comm_ring α` : the free commutative ring on a type α
* `lift (f : α → R)` : the ring hom `free_comm_ring α →+* R` induced by functoriality from `f`.
* `map (f : α → β)` : the ring hom `free_comm_ring α →*+ free_comm_ring β` induced by
functoriality from f.
## Main results
`free_comm_ring` has functorial properties (it is an adjoint to the forgetful functor).
In this file we have:
* `of : α → free_comm_ring α`
* `lift (f : α → R) : free_comm_ring α →+* R`
* `map (f : α → β) : free_comm_ring α →+* free_comm_ring β`
* `free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ` :
`free_comm_ring α` is isomorphic to a polynomial ring.
## Implementation notes
`free_comm_ring α` is implemented not using `mv_polynomial` but
directly as the free abelian group on `multiset α`, the type
of monomials in this free commutative ring.
## Tags
free commutative ring, free ring
-/
noncomputable theory
open_locale classical polynomial
universes u v
variables (α : Type u)
/-- `free_comm_ring α` is the free commutative ring on the type `α`. -/
@[derive [comm_ring, inhabited]]
def free_comm_ring (α : Type u) : Type u :=
free_abelian_group $ multiplicative $ multiset α
namespace free_comm_ring
variables {α}
/-- The canonical map from `α` to the free commutative ring on `α`. -/
def of (x : α) : free_comm_ring α :=
free_abelian_group.of $ multiplicative.of_add ({x} : multiset α)
lemma of_injective : function.injective (of : α → free_comm_ring α) :=
free_abelian_group.of_injective.comp (λ x y,
(multiset.coe_eq_coe.trans list.singleton_perm_singleton).mp)
@[elab_as_eliminator] protected lemma induction_on
{C : free_comm_ring α → Prop} (z : free_comm_ring α)
(hn1 : C (-1)) (hb : ∀ b, C (of b))
(ha : ∀ x y, C x → C y → C (x + y))
(hm : ∀ x y, C x → C y → C (x * y)) : C z :=
have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih,
have h1 : C 1, from neg_neg (1 : free_comm_ring α) ▸ hn _ hn1,
free_abelian_group.induction_on z
(add_left_neg (1 : free_comm_ring α) ▸ ha _ _ hn1 h1)
(λ m, multiset.induction_on m h1 $ λ a m ih, hm _ _ (hb a) ih)
(λ m ih, hn _ ih)
ha
section lift
variables {R : Type v} [comm_ring R] (f : α → R)
/-- A helper to implement `lift`. This is essentially `free_comm_monoid.lift`, but this does not
currently exist. -/
private def lift_to_multiset : (α → R) ≃ (multiplicative (multiset α) →* R) :=
{ to_fun := λ f,
{ to_fun := λ s, (s.to_add.map f).prod,
map_mul' := λ x y, calc _ = multiset.prod ((multiset.map f x) + (multiset.map f y)) :
by {congr' 1, exact multiset.map_add _ _ _}
... = _ : multiset.prod_add _ _,
map_one' := rfl},
inv_fun := λ F x, F (multiplicative.of_add ({x} : multiset α)),
left_inv := λ f, funext $ λ x, show (multiset.map f {x}).prod = _, by simp,
right_inv := λ F, monoid_hom.ext $ λ x,
let F' := F.to_additive'', x' := x.to_add in show (multiset.map (λ a, F' {a}) x').sum = F' x',
begin
rw [←multiset.map_map, ←add_monoid_hom.map_multiset_sum],
exact F.congr_arg (multiset.sum_map_singleton x'),
end }
/-- Lift a map `α → R` to a additive group homomorphism `free_comm_ring α → R`.
For a version producing a bundled homomorphism, see `lift_hom`. -/
def lift : (α → R) ≃ (free_comm_ring α →+* R) :=
equiv.trans lift_to_multiset free_abelian_group.lift_monoid
@[simp] lemma lift_of (x : α) : lift f (of x) = f x :=
(free_abelian_group.lift.of _ _).trans $ mul_one _
@[simp] lemma lift_comp_of (f : free_comm_ring α →+* R) : lift (f ∘ of) = f :=
ring_hom.ext $ λ x, free_comm_ring.induction_on x
(by rw [ring_hom.map_neg, ring_hom.map_one, f.map_neg, f.map_one])
(lift_of _)
(λ x y ihx ihy, by rw [ring_hom.map_add, f.map_add, ihx, ihy])
(λ x y ihx ihy, by rw [ring_hom.map_mul, f.map_mul, ihx, ihy])
@[ext]
lemma hom_ext ⦃f g : free_comm_ring α →+* R⦄ (h : ∀ x, f (of x) = g (of x)) :
f = g :=
lift.symm.injective (funext h)
end lift
variables {β : Type v} (f : α → β)
/-- A map `f : α → β` produces a ring homomorphism `free_comm_ring α →+* free_comm_ring β`. -/
def map : free_comm_ring α →+* free_comm_ring β :=
lift $ of ∘ f
@[simp]
lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _
/-- `is_supported x s` means that all monomials showing up in `x` have variables in `s`. -/
def is_supported (x : free_comm_ring α) (s : set α) : Prop :=
x ∈ subring.closure (of '' s)
section is_supported
variables {x y : free_comm_ring α} {s t : set α}
theorem is_supported_upwards (hs : is_supported x s) (hst : s ⊆ t) :
is_supported x t :=
subring.closure_mono (set.monotone_image hst) hs
theorem is_supported_add (hxs : is_supported x s) (hys : is_supported y s) :
is_supported (x + y) s :=
subring.add_mem _ hxs hys
theorem is_supported_neg (hxs : is_supported x s) :
is_supported (-x) s :=
subring.neg_mem _ hxs
theorem is_supported_sub (hxs : is_supported x s) (hys : is_supported y s) :
is_supported (x - y) s :=
subring.sub_mem _ hxs hys
theorem is_supported_mul (hxs : is_supported x s) (hys : is_supported y s) :
is_supported (x * y) s :=
subring.mul_mem _ hxs hys
theorem is_supported_zero : is_supported 0 s :=
subring.zero_mem _
theorem is_supported_one : is_supported 1 s :=
subring.one_mem _
theorem is_supported_int {i : ℤ} {s : set α} : is_supported ↑i s :=
int.induction_on i is_supported_zero
(λ i hi, by rw [int.cast_add, int.cast_one]; exact is_supported_add hi is_supported_one)
(λ i hi, by rw [int.cast_sub, int.cast_one]; exact is_supported_sub hi is_supported_one)
end is_supported
/-- The restriction map from `free_comm_ring α` to `free_comm_ring s` where `s : set α`, defined
by sending all variables not in `s` to zero. -/
def restriction (s : set α) [decidable_pred (∈ s)] : free_comm_ring α →+* free_comm_ring s :=
lift (λ p, if H : p ∈ s then of (⟨p, H⟩ : s) else 0)
section restriction
variables (s : set α) [decidable_pred (∈ s)] (x y : free_comm_ring α)
@[simp] lemma restriction_of (p) :
restriction s (of p) = if H : p ∈ s then of ⟨p, H⟩ else 0 := lift_of _ _
end restriction
theorem is_supported_of {p} {s : set α} : is_supported (of p) s ↔ p ∈ s :=
suffices is_supported (of p) s → p ∈ s, from ⟨this, λ hps, subring.subset_closure ⟨p, hps, rfl⟩⟩,
assume hps : is_supported (of p) s, begin
haveI := classical.dec_pred s,
have : ∀ x, is_supported x s →
∃ (n : ℤ), lift (λ a, if a ∈ s then (0 : ℤ[X]) else polynomial.X) x = n,
{ intros x hx, refine subring.in_closure.rec_on hx _ _ _ _,
{ use 1, rw [ring_hom.map_one], norm_cast },
{ use -1, rw [ring_hom.map_neg, ring_hom.map_one], norm_cast },
{ rintros _ ⟨z, hzs, rfl⟩ _ _, use 0, rw [ring_hom.map_mul, lift_of, if_pos hzs, zero_mul],
norm_cast },
{ rintros x y ⟨q, hq⟩ ⟨r, hr⟩, refine ⟨q+r, _⟩, rw [ring_hom.map_add, hq, hr], norm_cast } },
specialize this (of p) hps, rw [lift_of] at this, split_ifs at this, { exact h },
exfalso, apply ne.symm int.zero_ne_one,
rcases this with ⟨w, H⟩, rw ←polynomial.C_eq_int_cast at H,
have : polynomial.X.coeff 1 = (polynomial.C ↑w).coeff 1, by rw H,
rwa [polynomial.coeff_C, if_neg (one_ne_zero : 1 ≠ 0), polynomial.coeff_X, if_pos rfl] at this
end
theorem map_subtype_val_restriction {x} (s : set α) [decidable_pred (∈ s)]
(hxs : is_supported x s) :
map (subtype.val : s → α) (restriction s x) = x :=
begin
refine subring.in_closure.rec_on hxs _ _ _ _,
{ rw ring_hom.map_one, refl },
{ rw [ring_hom.map_neg, ring_hom.map_neg, ring_hom.map_one], refl },
{ rintros _ ⟨p, hps, rfl⟩ n ih,
rw [ring_hom.map_mul, restriction_of, dif_pos hps, ring_hom.map_mul, map_of, ih] },
{ intros x y ihx ihy, rw [ring_hom.map_add, ring_hom.map_add, ihx, ihy] }
end
theorem exists_finite_support (x : free_comm_ring α) :
∃ s : set α, set.finite s ∧ is_supported x s :=
free_comm_ring.induction_on x
⟨∅, set.finite_empty, is_supported_neg is_supported_one⟩
(λ p, ⟨{p}, set.finite_singleton p, is_supported_of.2 $ set.mem_singleton _⟩)
(λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_add
(is_supported_upwards hxs $ set.subset_union_left s t)
(is_supported_upwards hxt $ set.subset_union_right s t)⟩)
(λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_mul
(is_supported_upwards hxs $ set.subset_union_left s t)
(is_supported_upwards hxt $ set.subset_union_right s t)⟩)
theorem exists_finset_support (x : free_comm_ring α) : ∃ s : finset α, is_supported x ↑s :=
let ⟨s, hfs, hxs⟩ := exists_finite_support x in ⟨hfs.to_finset, by rwa set.finite.coe_to_finset⟩
end free_comm_ring
namespace free_ring
open function
variable (α)
/-- The canonical ring homomorphism from the free ring generated by `α` to the free commutative ring
generated by `α`. -/
def to_free_comm_ring {α} : free_ring α →+* free_comm_ring α :=
free_ring.lift free_comm_ring.of
instance : has_coe (free_ring α) (free_comm_ring α) := ⟨to_free_comm_ring⟩
/-- The natural map `free_ring α → free_comm_ring α`, as a `ring_hom`. -/
def coe_ring_hom : free_ring α →+* free_comm_ring α := to_free_comm_ring
@[simp, norm_cast] protected lemma coe_zero : ↑(0 : free_ring α) = (0 : free_comm_ring α) := rfl
@[simp, norm_cast] protected lemma coe_one : ↑(1 : free_ring α) = (1 : free_comm_ring α) := rfl
variable {α}
@[simp] protected lemma coe_of (a : α) : ↑(free_ring.of a) = free_comm_ring.of a :=
free_ring.lift_of _ _
@[simp, norm_cast] protected lemma coe_neg (x : free_ring α) : ↑(-x) = -(x : free_comm_ring α) :=
(free_ring.lift _).map_neg _
@[simp, norm_cast] protected lemma coe_add (x y : free_ring α) :
↑(x + y) = (x : free_comm_ring α) + y :=
(free_ring.lift _).map_add _ _
@[simp, norm_cast] protected lemma coe_sub (x y : free_ring α) :
↑(x - y) = (x : free_comm_ring α) - y :=
(free_ring.lift _).map_sub _ _
@[simp, norm_cast] protected lemma coe_mul (x y : free_ring α) :
↑(x * y) = (x : free_comm_ring α) * y :=
(free_ring.lift _).map_mul _ _
variable (α)
protected lemma coe_surjective : surjective (coe : free_ring α → free_comm_ring α) :=
λ x,
begin
apply free_comm_ring.induction_on x,
{ use -1, refl },
{ intro x, use free_ring.of x, refl },
{ rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x + y, exact (free_ring.lift _).map_add _ _ },
{ rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x * y, exact (free_ring.lift _).map_mul _ _ }
end
lemma coe_eq :
(coe : free_ring α → free_comm_ring α) =
@functor.map free_abelian_group _ _ _ (λ (l : list α), (l : multiset α)) :=
funext $ λ x, free_abelian_group.lift.unique _ _ $ λ L,
by { simp_rw [free_abelian_group.lift.of, (∘)], exact free_monoid.rec_on L rfl
(λ hd tl ih, by { rw [(free_monoid.lift _).map_mul, free_monoid.lift_eval_of, ih], refl }) }
/-- If α has size at most 1 then the natural map from the free ring on `α` to the
free commutative ring on `α` is an isomorphism of rings. -/
def subsingleton_equiv_free_comm_ring [subsingleton α] :
free_ring α ≃+* free_comm_ring α :=
ring_equiv.of_bijective (coe_ring_hom _)
begin
have : (coe_ring_hom _ : free_ring α → free_comm_ring α) =
(functor.map_equiv free_abelian_group (multiset.subsingleton_equiv α)) := coe_eq α,
rw this,
apply equiv.bijective,
end
instance [subsingleton α] : comm_ring (free_ring α) :=
{ mul_comm := λ x y,
by { rw [← (subsingleton_equiv_free_comm_ring α).symm_apply_apply (y * x),
((subsingleton_equiv_free_comm_ring α)).map_mul,
mul_comm,
← ((subsingleton_equiv_free_comm_ring α)).map_mul,
(subsingleton_equiv_free_comm_ring α).symm_apply_apply], },
.. free_ring.ring α }
end free_ring
/-- The free commutative ring on `α` is isomorphic to the polynomial ring over ℤ with
variables in `α` -/
def free_comm_ring_equiv_mv_polynomial_int :
free_comm_ring α ≃+* mv_polynomial α ℤ :=
ring_equiv.of_hom_inv
(free_comm_ring.lift $ (λ a, mv_polynomial.X a : α → mv_polynomial α ℤ))
(mv_polynomial.eval₂_hom (int.cast_ring_hom (free_comm_ring α)) free_comm_ring.of)
(by { ext, simp })
(by ext; simp)
/-- The free commutative ring on the empty type is isomorphic to `ℤ`. -/
def free_comm_ring_pempty_equiv_int : free_comm_ring pempty.{u+1} ≃+* ℤ :=
ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _)
(mv_polynomial.is_empty_ring_equiv _ pempty)
/-- The free commutative ring on a type with one term is isomorphic to `ℤ[X]`. -/
def free_comm_ring_punit_equiv_polynomial_int : free_comm_ring punit.{u+1} ≃+* polynomial ℤ :=
(free_comm_ring_equiv_mv_polynomial_int _).trans (mv_polynomial.punit_alg_equiv ℤ).to_ring_equiv
open free_ring
/-- The free ring on the empty type is isomorphic to `ℤ`. -/
def free_ring_pempty_equiv_int : free_ring pempty.{u+1} ≃+* ℤ :=
ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_pempty_equiv_int
/-- The free ring on a type with one term is isomorphic to `ℤ[X]`. -/
def free_ring_punit_equiv_polynomial_int : free_ring punit.{u+1} ≃+* polynomial ℤ :=
ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_punit_equiv_polynomial_int
|
48841c080651d5e6f5dd9d37dd3c4b951e0e5079 | b328e8ebb2ba923140e5137c83f09fa59516b793 | /stage0/src/Lean/Server/FileWorker.lean | cedbfa9cdbad38a8f09c5209d98d0ed60d618138 | [
"Apache-2.0"
] | permissive | DrMaxis/lean4 | a781bcc095511687c56ab060e816fd948553e162 | 5a02c4facc0658aad627cfdcc3db203eac0cb544 | refs/heads/master | 1,677,051,517,055 | 1,611,876,226,000 | 1,611,876,226,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 29,005 | lean | /-
Copyright (c) 2020 Marc Huisinga. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Marc Huisinga, Wojciech Nawrocki
-/
import Init.System.IO
import Std.Data.RBMap
import Lean.Environment
import Lean.PrettyPrinter
import Lean.DeclarationRange
import Lean.Data.Lsp
import Lean.Data.Json.FromToJson
import Lean.Server.Snapshots
import Lean.Server.Utils
import Lean.Server.AsyncList
import Lean.Server.InfoUtils
/-!
For general server architecture, see `README.md`. For details of IPC communication, see `Watchdog.lean`.
This module implements per-file worker processes.
File processing and requests+notifications against a file should be concurrent for two reasons:
- By the LSP standard, requests should be cancellable.
- Since Lean allows arbitrary user code to be executed during elaboration via the tactic framework,
elaboration can be extremely slow and even not halt in some cases. Users should be able to
work with the file while this is happening, e.g. make new changes to the file or send requests.
To achieve these goals, elaboration is executed in a chain of tasks, where each task corresponds to
the elaboration of one command. When the elaboration of one command is done, the next task is spawned.
On didChange notifications, we search for the task in which the change occured. If we stumble across
a task that has not yet finished before finding the task we're looking for, we terminate it
and start the elaboration there, otherwise we start the elaboration at the task where the change occured.
Requests iterate over tasks until they find the command that they need to answer the request.
In order to not block the main thread, this is done in a request task.
If a task that the request task waits for is terminated, a change occured somewhere before the
command that the request is looking for and the request sends a "content changed" error.
-/
namespace Lean.Server.FileWorker
open Lsp
open IO
open Snapshots
open Lean.Parser.Command
open Std (RBMap RBMap.empty)
open JsonRpc
section Utils
private def logSnapContent (s : Snapshot) (text : FileMap) : IO Unit :=
IO.eprintln s!"[{s.beginPos}, {s.endPos}]: `{text.source.extract s.beginPos (s.endPos-1)}`"
inductive ElabTaskError where
| aborted
| eof
| ioError (e : IO.Error)
instance : Coe IO.Error ElabTaskError := ⟨ElabTaskError.ioError⟩
structure CancelToken where
ref : IO.Ref Bool
deriving Inhabited
namespace CancelToken
def new : IO CancelToken :=
CancelToken.mk <$> IO.mkRef false
def check [MonadExceptOf ElabTaskError m] [MonadLiftT (ST RealWorld) m] [Monad m] (tk : CancelToken) : m Unit := do
let c ← tk.ref.get
if c = true then
throw ElabTaskError.aborted
def set (tk : CancelToken) : IO Unit :=
tk.ref.set true
end CancelToken
/-- A document editable in the sense that we track the environment
and parser state after each command so that edits can be applied
without recompiling code appearing earlier in the file. -/
structure EditableDocument where
meta : DocumentMeta
/- The first snapshot is that after the header. -/
headerSnap : Snapshot
/- Subsequent snapshots occur after each command. -/
cmdSnaps : AsyncList ElabTaskError Snapshot
cancelTk : CancelToken
deriving Inhabited
end Utils
/- Asynchronous snapshot elaboration. -/
section Elab
/-- Elaborates the next command after `parentSnap` and emits diagnostics into `hOut`. -/
private def nextCmdSnap (m : DocumentMeta) (parentSnap : Snapshot) (cancelTk : CancelToken) (hOut : FS.Stream)
: ExceptT ElabTaskError IO Snapshot := do
cancelTk.check
let maybeSnap ← compileNextCmd m.text.source parentSnap
-- TODO(MH): check for interrupt with increased precision
cancelTk.check
let sendDiagnostics (msgLog : MessageLog) : IO Unit := do
let diagnostics ← msgLog.msgs.mapM (msgToDiagnostic m.text)
hOut.writeLspNotification {
method := "textDocument/publishDiagnostics"
param := {
uri := m.uri
version? := m.version
diagnostics := diagnostics.toArray
: PublishDiagnosticsParams
}
}
match maybeSnap with
| Sum.inl snap =>
/- NOTE(MH): This relies on the client discarding old diagnostics upon receiving new ones
while prefering newer versions over old ones. The former is necessary because we do
not explicitly clear older diagnostics, while the latter is necessary because we do
not guarantee that diagnostics are emitted in order. Specifically, it may happen that
we interrupted this elaboration task right at this point and a newer elaboration task
emits diagnostics, after which we emit old diagnostics because we did not yet detect
the interrupt. Explicitly clearing diagnostics is difficult for a similar reason,
because we cannot guarantee that no further diagnostics are emitted after clearing
them. -/
sendDiagnostics <| snap.msgLog.add {
fileName := "<ignored>"
pos := m.text.toPosition snap.endPos
severity := MessageSeverity.information
data := "processing..."
}
snap
| Sum.inr msgLog =>
sendDiagnostics msgLog
throw ElabTaskError.eof
/-- Elaborates all commands after `initSnap`, emitting the diagnostics into `hOut`. -/
def unfoldCmdSnaps (m : DocumentMeta) (initSnap : Snapshot) (cancelTk : CancelToken) (hOut : FS.Stream)
: IO (AsyncList ElabTaskError Snapshot) := do
AsyncList.unfoldAsync (nextCmdSnap m . cancelTk hOut) initSnap
end Elab
-- Pending requests are tracked so they can be cancelled
abbrev PendingRequestMap := RBMap RequestID (Task (Except IO.Error Unit)) (fun a b => Decidable.decide (a < b))
structure ServerContext where
hIn : FS.Stream
hOut : FS.Stream
hLog : FS.Stream
srcSearchPath : SearchPath
docRef : IO.Ref EditableDocument
pendingRequestsRef : IO.Ref PendingRequestMap
abbrev ServerM := ReaderT ServerContext IO
/- Worker initialization sequence. -/
section Initialization
/-- Use `leanpkg print-paths` to compile dependencies on the fly and add them to `LEAN_PATH`.
Compilation progress is reported to `hOut` via LSP notifications. Return the search path for
source files. -/
partial def leanpkgSetupSearchPath (leanpkgPath : String) (m : DocumentMeta) (imports : Array Import) (hOut : FS.Stream) : IO SearchPath := do
let leanpkgProc ← Process.spawn {
stdin := Process.Stdio.null
stdout := Process.Stdio.piped
stderr := Process.Stdio.piped
cmd := leanpkgPath
args := #["print-paths"] ++ imports.map (toString ·.module)
}
-- progress notification: report latest stderr line
let rec processStderr (acc : String) : IO String := do
let line ← leanpkgProc.stderr.getLine
if line == "" then
return acc
else
hOut.writeLspNotification {
method := "textDocument/publishDiagnostics"
param := {
uri := m.uri
version? := m.version
diagnostics := #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.information, message := line }]
: PublishDiagnosticsParams
}
}
processStderr (acc ++ line)
let stderr ← IO.asTask (processStderr "") Task.Priority.dedicated
let stdout := String.trim (← leanpkgProc.stdout.readToEnd)
let stderr ← IO.ofExcept stderr.get
if (← leanpkgProc.wait) == 0 then
match stdout.split (· == '\n') with
| [""] => pure [] -- e.g. no leanpkg.toml
| [leanPath, leanSrcPath] => let sp ← getBuiltinSearchPath
let sp ← addSearchPathFromEnv sp
let sp ← parseSearchPath leanPath sp
searchPathRef.set sp
let srcPath := parseSearchPath leanSrcPath
srcPath.mapM realPathNormalized
| _ => throw <| IO.userError s!"unexpected output from `leanpkg print-paths`:\n{stdout}\nstderr:\n{stderr}"
else
throw <| IO.userError s!"`leanpkg print-paths` failed:\n{stdout}\nstderr:\n{stderr}"
def compileHeader (m : DocumentMeta) (hOut : FS.Stream) : IO (Snapshot × SearchPath) := do
let opts := {} -- TODO
let inputCtx := Parser.mkInputContext m.text.source "<input>"
let (headerStx, headerParserState, msgLog) ← Parser.parseHeader inputCtx
let leanpkgPath ← match ← IO.getEnv "LEAN_SYSROOT" with
| some path => s!"{path}/bin/leanpkg{System.FilePath.exeSuffix}"
| _ => s!"{← appDir}/leanpkg{System.FilePath.exeSuffix}"
let mut srcSearchPath := [s!"{← appDir}/../lib/lean/src"]
if let some p := (← IO.getEnv "LEAN_SRC_PATH") then
srcSearchPath := srcSearchPath ++ parseSearchPath p
-- NOTE: leanpkg does not exist in stage 0 (yet?)
if (← fileExists leanpkgPath) then
let pkgSearchPath ← leanpkgSetupSearchPath leanpkgPath m (Lean.Elab.headerToImports headerStx).toArray hOut
srcSearchPath := srcSearchPath ++ pkgSearchPath
let (headerEnv, msgLog) ← Elab.processHeader headerStx opts msgLog inputCtx
let cmdState := Elab.Command.mkState headerEnv msgLog opts
let opts := opts.setBool `interpreter.prefer_native false
let cmdState := { cmdState with infoState.enabled := true, scopes := [{ header := "", opts := opts }] }
let headerSnap := {
beginPos := 0
stx := headerStx
mpState := headerParserState
data := SnapshotData.headerData cmdState
}
return (headerSnap, srcSearchPath)
def initializeWorker (p : DidOpenTextDocumentParams) (i o e : FS.Stream)
: IO ServerContext := do
let doc := p.textDocument
/- NOTE(WN): `toFileMap` marks line beginnings as immediately following
"\n", which should be enough to handle both LF and CRLF correctly.
This is because LSP always refers to characters by (line, column),
so if we get the line number correct it shouldn't matter that there
is a CR there. -/
let meta : DocumentMeta := ⟨doc.uri, doc.version, doc.text.toFileMap⟩
let (headerSnap, srcSearchPath) ← compileHeader meta o
let cancelTk ← CancelToken.new
let cmdSnaps ← unfoldCmdSnaps meta headerSnap cancelTk o
let doc : EditableDocument := ⟨meta, headerSnap, cmdSnaps, cancelTk⟩
return {
hIn := i
hOut := o
hLog := e
srcSearchPath := srcSearchPath
docRef := ←IO.mkRef doc
pendingRequestsRef := ←IO.mkRef RBMap.empty
}
end Initialization
section Updates
def updatePendingRequests (map : PendingRequestMap → PendingRequestMap) : ServerM Unit := do
(←read).pendingRequestsRef.modify map
/-- Given the new document and `changePos`, the UTF-8 offset of a change into the pre-change source,
updates editable doc state. -/
def updateDocument (newMeta : DocumentMeta) (changePos : String.Pos) : ServerM Unit := do
-- The watchdog only restarts the file worker when the syntax tree of the header changes.
-- If e.g. a newline is deleted, it will not restart this file worker, but we still
-- need to reparse the header so that the offsets are correct.
let st ← read
let oldDoc ← st.docRef.get
let newHeaderSnap ← reparseHeader newMeta.text.source oldDoc.headerSnap
if newHeaderSnap.stx != oldDoc.headerSnap.stx then
throwServerError "Internal server error: header changed but worker wasn't restarted."
let ⟨cmdSnaps, e?⟩ ← oldDoc.cmdSnaps.updateFinishedPrefix
match e? with
-- This case should not be possible. only the main task aborts tasks and ensures that aborted tasks
-- do not show up in `snapshots` of an EditableDocument.
| some ElabTaskError.aborted =>
throwServerError "Internal server error: elab task was aborted while still in use."
| some (ElabTaskError.ioError ioError) => throw ioError
| _ => -- No error or EOF
oldDoc.cancelTk.set
-- NOTE(WN): we invalidate eagerly as `endPos` consumes input greedily. To re-elaborate only
-- when really necessary, we could do a whitespace-aware `Syntax` comparison instead.
let mut validSnaps := cmdSnaps.finishedPrefix.takeWhile (fun s => s.endPos < changePos)
if validSnaps.length = 0 then
let cancelTk ← CancelToken.new
let newCmdSnaps ← unfoldCmdSnaps newMeta newHeaderSnap cancelTk st.hOut
st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩
else
/- When at least one valid non-header snap exists, it may happen that a change does not fall
within the syntactic range of that last snap but still modifies it by appending tokens.
We check for this here. We do not currently handle crazy grammars in which an appended
token can merge two or more previous commands into one. To do so would require reparsing
the entire file. -/
let mut lastSnap := validSnaps.getLast!
let preLastSnap :=
if validSnaps.length ≥ 2
then validSnaps.get! (validSnaps.length - 2)
else newHeaderSnap
let newLastStx ← parseNextCmd newMeta.text.source preLastSnap
if newLastStx != lastSnap.stx then
validSnaps ← validSnaps.dropLast
lastSnap ← preLastSnap
let cancelTk ← CancelToken.new
let newSnaps ← unfoldCmdSnaps newMeta lastSnap cancelTk st.hOut
let newCmdSnaps := AsyncList.ofList validSnaps ++ newSnaps
st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩
end Updates
/- Notifications are handled in the main thread. They may change global worker state
such as the current file contents. -/
section NotificationHandling
def handleDidChange (p : DidChangeTextDocumentParams) : ServerM Unit := do
let docId := p.textDocument
let changes := p.contentChanges
let oldDoc ← (←read).docRef.get
let some newVersion ← pure docId.version?
| throwServerError "Expected version number"
if newVersion ≤ oldDoc.meta.version then
-- TODO(WN): This happens on restart sometimes.
IO.eprintln s!"Got outdated version number: {newVersion} ≤ {oldDoc.meta.version}"
else if ¬ changes.isEmpty then
let (newDocText, minStartOff) := foldDocumentChanges changes oldDoc.meta.text
updateDocument ⟨docId.uri, newVersion, newDocText⟩ minStartOff
def handleCancelRequest (p : CancelParams) : ServerM Unit := do
updatePendingRequests (fun pendingRequests => pendingRequests.erase p.id)
end NotificationHandling
/- Request handlers are given by `Task`s executed asynchronously. They may be cancelled at any time,
so they should check the cancellation token when possible to handle this cooperatively. Any exceptions
thrown in a handler will be reported to the client as LSP error responses. -/
section RequestHandling
structure RequestError where
code : ErrorCode
message : String
namespace RequestError
def fileChanged : RequestError :=
{ code := ErrorCode.contentModified
message := "File changed." }
end RequestError
-- TODO(WN): the type is too complicated
abbrev RequestM α := ServerM $ Task $ Except IO.Error $ Except RequestError α
def mapTask (t : Task α) (f : α → ExceptT RequestError ServerM β) : RequestM β := fun st =>
(IO.mapTask · t) fun a => f a st
/-- Create a task which waits for a snapshot matching `p`, handles various errors,
and if a matching snapshot was found executes `x` with it. If not found, the task
executes `notFoundX`. -/
def withWaitFindSnap (doc : EditableDocument) (p : Snapshot → Bool)
(notFoundX : ExceptT RequestError ServerM β)
(x : Snapshot → ExceptT RequestError ServerM β)
: ServerM (Task (Except IO.Error (Except RequestError β))) := do
let findTask ← doc.cmdSnaps.waitFind? p
mapTask findTask fun
| Except.error ElabTaskError.aborted =>
throwThe RequestError RequestError.fileChanged
| Except.error (ElabTaskError.ioError e) =>
throwThe IO.Error e
| Except.error ElabTaskError.eof => notFoundX
| Except.ok none => notFoundX
| Except.ok (some snap) => x snap
/- Requests that need data from a certain command should traverse the snapshots
by successively getting the next task, meaning that we might need to wait for elaboration.
When that happens, the request should send a "content changed" error to the user
(this way, the server doesn't get bogged down in requests for an old state of the document).
Requests need to manually check for whether their task has been cancelled, so that they
can reply with a RequestCancelled error. -/
open Elab in
partial def handleHover (id : RequestID) (p : HoverParams)
: ServerM (Task (Except IO.Error (Except RequestError (Option Hover)))) := do
let st ← read
let doc ← st.docRef.get
let text := doc.meta.text
let mkHover (s : String) (f : String.Pos) (t : String.Pos) : Hover :=
{ contents := { kind := MarkupKind.markdown
value := s }
range? := some { start := text.utf8PosToLspPos f
«end» := text.utf8PosToLspPos t } }
let hoverPos := text.lspPosToUtf8Pos p.position
withWaitFindSnap doc (fun s => s.endPos > hoverPos)
(notFoundX := pure none) fun snap => do
for t in snap.toCmdState.infoState.trees do
if let some (ci, i) := t.hoverableTermAt? hoverPos then
let tFmt ← ci.runMetaM i.lctx do
return f!"{← Meta.ppExpr i.expr} : {← Meta.ppExpr (← Meta.inferType i.expr)}"
let mut hoverFmt := f!"```lean
{tFmt}
```"
if let some n := i.expr.constName? then
if let some doc ← ci.runMetaM i.lctx <| findDocString? n then
hoverFmt := f!"{hoverFmt}\n***\n{doc}"
return some <| mkHover (toString hoverFmt) i.pos?.get! i.tailPos?.get!
pure ()
return none
open Elab in
partial def handleDefinition (goToType? : Bool) (id : RequestID) (p : TextDocumentPositionParams)
: ServerM (Task (Except IO.Error (Except RequestError (Array LocationLink)))) := do
let st ← read
let doc ← st.docRef.get
let text := doc.meta.text
let hoverPos := text.lspPosToUtf8Pos p.position
withWaitFindSnap doc (fun s => s.endPos > hoverPos)
(notFoundX := pure #[]) fun snap => do
for t in snap.toCmdState.infoState.trees do
if let some (ci, i) := t.hoverableTermAt? hoverPos then
let expr ← if goToType? then ci.runMetaM i.lctx <| Meta.inferType i.expr else i.expr
if let some n := expr.constName? then
let mod? ← ci.runMetaM i.lctx <| findModuleOf? n
let modUri? ← match mod? with
| some modName =>
let modFname? ← st.srcSearchPath.findWithExt ".lean" modName
pure <| modFname?.map ("file://" ++ ·)
| none => pure <| some doc.meta.uri
let ranges? ← ci.runMetaM i.lctx <| findDeclarationRanges? n
if let (some ranges, some modUri) := (ranges?, modUri?) then
let declRangeToLspRange (r : DeclarationRange) : Lsp.Range :=
{ start := ⟨r.pos.line - 1, r.charUtf16⟩
«end» := ⟨r.endPos.line - 1, r.endCharUtf16⟩ }
let ll : LocationLink := {
originSelectionRange? := some ⟨text.utf8PosToLspPos i.pos?.get!, text.utf8PosToLspPos i.tailPos?.get!⟩
targetUri := modUri
targetRange := declRangeToLspRange ranges.range
targetSelectionRange := declRangeToLspRange ranges.selectionRange
}
return #[ll]
return #[]
def rangeOfSyntax (text : FileMap) (stx : Syntax) : Range :=
⟨text.utf8PosToLspPos <| stx.getPos?.get!,
text.utf8PosToLspPos <| stx.getTailPos?.get!⟩
partial def handleDocumentSymbol (id : RequestID) (p : DocumentSymbolParams) :
ServerM (Task (Except IO.Error (Except RequestError DocumentSymbolResult))) := do
let st ← read
asTask do
let doc ← st.docRef.get
let ⟨cmdSnaps, e?⟩ ← doc.cmdSnaps.updateFinishedPrefix
let mut stxs := cmdSnaps.finishedPrefix.map Snapshot.stx
match e? with
| some ElabTaskError.aborted =>
return Except.error RequestError.fileChanged
| some _ => pure () -- TODO(WN): what to do on ioError?
| none =>
let lastSnap := cmdSnaps.finishedPrefix.getLastD doc.headerSnap
stxs := stxs ++ (← parseAhead doc.meta.text.source lastSnap).toList
let (syms, _) := toDocumentSymbols doc.meta.text stxs
return Except.ok { syms := syms.toArray }
where
toDocumentSymbols (text : FileMap)
| [] => ([], [])
| stx::stxs => match stx with
| `(namespace $id) => sectionLikeToDocumentSymbols text stx stxs (id.getId.toString) SymbolKind.namespace id
| `(section $(id)?) => sectionLikeToDocumentSymbols text stx stxs ((·.getId.toString) <$> id |>.getD "<section>") SymbolKind.namespace (id.getD stx)
| `(end $(id)?) => ([], stx::stxs)
| _ =>
let (syms, stxs') := toDocumentSymbols text stxs
if stx.isOfKind ``Lean.Parser.Command.declaration then
let (name, selection) := match stx with
| `($dm:declModifiers $ak:attrKind instance $[$np:namedPrio]? $[$id:ident$[.{$ls,*}]?]? $sig:declSig $val) =>
((·.getId.toString) <$> id |>.getD s!"instance {sig.reprint.getD ""}", id.getD sig)
| _ => match stx[1][1] with
| `(declId|$id:ident$[.{$ls,*}]?) => (id.getId.toString, id)
| _ => (stx[1][0].isIdOrAtom?.getD "<unknown>", stx[1][0])
(DocumentSymbol.mk {
name := name
kind := SymbolKind.method
range := rangeOfSyntax text stx
selectionRange := rangeOfSyntax text selection
} :: syms, stxs')
else
(syms, stxs')
sectionLikeToDocumentSymbols (text : FileMap) (stx : Syntax) (stxs : List Syntax) (name : String) (kind : SymbolKind) (selection : Syntax) :=
let (syms, stxs') := toDocumentSymbols text stxs
-- discard `end`
let (syms', stxs'') := toDocumentSymbols text (stxs'.drop 1)
let endStx := match stxs' with
| endStx::_ => endStx
| [] => (stx::stxs').getLast!
(DocumentSymbol.mk {
name := name
kind := kind
range := ⟨(rangeOfSyntax text stx).start, (rangeOfSyntax text endStx).«end»⟩
selectionRange := rangeOfSyntax text selection
children? := syms.toArray
} :: syms', stxs'')
partial def handleWaitForDiagnostics (id : RequestID) (p : WaitForDiagnosticsParams)
: ServerM (Task (Except IO.Error (Except RequestError WaitForDiagnostics))) := do
let st ← read
let rec waitLoop : IO EditableDocument := do
let doc ← st.docRef.get
if p.version ≤ doc.meta.version then
return doc
else
IO.sleep 50
waitLoop
let t ← IO.asTask waitLoop
let t ← IO.bindTask t fun
| Except.error e => unreachable!
| Except.ok doc => do
let t₁ ← doc.cmdSnaps.waitAll
return t₁.map fun _ => Except.ok WaitForDiagnostics.mk
return t.map fun _ => Except.ok <| Except.ok WaitForDiagnostics.mk
end RequestHandling
section MessageHandling
def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType :=
match fromJson? params with
| some parsed => pure parsed
| none => throwServerError s!"Got param with wrong structure: {params.compress}"
def handleNotification (method : String) (params : Json) : ServerM Unit := do
let handle := fun paramType [FromJson paramType] (handler : paramType → ServerM Unit) =>
parseParams paramType params >>= handler
match method with
| "textDocument/didChange" => handle DidChangeTextDocumentParams handleDidChange
| "$/cancelRequest" => handle CancelParams handleCancelRequest
| _ => throwServerError s!"Got unsupported notification method: {method}"
def queueRequest (id : RequestID) (requestTask : Task (Except IO.Error Unit))
: ServerM Unit := do
updatePendingRequests (fun pendingRequests => pendingRequests.insert id requestTask)
def handleRequest (id : RequestID) (method : String) (params : Json)
: ServerM Unit := do
let handle := fun paramType [FromJson paramType] respType [ToJson respType]
(handler : RequestID → paramType → RequestM respType) => do
let st ← read
let p ← parseParams paramType params
let t ← handler id p
let t₁ ← (IO.mapTask · t) fun
| Except.ok (Except.ok resp) =>
st.hOut.writeLspResponse ⟨id, resp⟩
| Except.ok (Except.error e) =>
st.hOut.writeLspResponseError { id := id, code := e.code, message := e.message }
| Except.error e =>
st.hOut.writeLspResponseError { id := id, code := ErrorCode.internalError, message := toString e }
queueRequest id t₁
match method with
| "textDocument/waitForDiagnostics" => handle WaitForDiagnosticsParams WaitForDiagnostics handleWaitForDiagnostics
| "textDocument/hover" => handle HoverParams (Option Hover) handleHover
| "textDocument/declaration" => handle TextDocumentPositionParams (Array LocationLink) <| handleDefinition (goToType? := false)
| "textDocument/definition" => handle TextDocumentPositionParams (Array LocationLink) <| handleDefinition (goToType? := false)
| "textDocument/typeDefinition" => handle TextDocumentPositionParams (Array LocationLink) <| handleDefinition (goToType? := true)
| "textDocument/documentSymbol" => handle DocumentSymbolParams DocumentSymbolResult handleDocumentSymbol
| _ => throwServerError s!"Got unsupported request: {method}"
end MessageHandling
section MainLoop
partial def mainLoop : ServerM Unit := do
let st ← read
let msg ← st.hIn.readLspMessage
let pendingRequests ← st.pendingRequestsRef.get
let filterFinishedTasks (acc : PendingRequestMap) (id : RequestID) (task : Task (Except IO.Error Unit))
: ServerM PendingRequestMap := do
if (←hasFinished task) then
/- Handler tasks are constructed so that the only possible errors here
are failures of writing a response into the stream. -/
if let Except.error e := task.get then
throwServerError s!"Failed responding to request {id}: {e}"
acc.erase id
else acc
let pendingRequests ← pendingRequests.foldM filterFinishedTasks pendingRequests
st.pendingRequestsRef.set pendingRequests
match msg with
| Message.request id method (some params) =>
handleRequest id method (toJson params)
mainLoop
| Message.notification "exit" none =>
let doc ← st.docRef.get
doc.cancelTk.set
return ()
| Message.notification method (some params) =>
handleNotification method (toJson params)
mainLoop
| _ => throwServerError "Got invalid JSON-RPC message"
end MainLoop
def initAndRunWorker (i o e : FS.Stream) : IO UInt32 := do
let i ← maybeTee "fwIn.txt" false i
let o ← maybeTee "fwOut.txt" true o
-- TODO(WN): act in accordance with InitializeParams
let _ ← i.readLspRequestAs "initialize" InitializeParams
let ⟨_, param⟩ ← i.readLspNotificationAs "textDocument/didOpen" DidOpenTextDocumentParams
let e ← e.withPrefix s!"[{param.textDocument.uri}] "
let _ ← IO.setStderr e
try
let ctx ← initializeWorker param i o e
ReaderT.run (r := ctx) mainLoop
return 0
catch e =>
o.writeLspNotification {
method := "textDocument/publishDiagnostics"
param := {
uri := param.textDocument.uri
version? := param.textDocument.version
diagnostics := #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.error, message := e.toString }]
: PublishDiagnosticsParams
}
}
return 1
@[export lean_server_worker_main]
def workerMain : IO UInt32 := do
let i ← IO.getStdin
let o ← IO.getStdout
let e ← IO.getStderr
try
initAndRunWorker i o e
catch err =>
e.putStrLn s!"worker initialization error: {err}"
return (1 : UInt32)
end Lean.Server.FileWorker
|
ac1111a3e457fff077b7076d19e5d0d7f8d4bbcd | d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6 | /Papyrus/IR/ModuleRef.lean | 3d305a3e5545fd98f3dc4f468674b1be6912e9be | [
"Apache-2.0"
] | permissive | xubaiw/lean4-papyrus | c3fbbf8ba162eb5f210155ae4e20feb2d32c8182 | 02e82973a5badda26fc0f9fd15b3d37e2eb309e0 | refs/heads/master | 1,691,425,756,824 | 1,632,122,825,000 | 1,632,123,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,355 | lean | import Papyrus.FFI
import Papyrus.Context
import Papyrus.MemoryBufferRef
import Papyrus.IR.GlobalVariableRef
import Papyrus.IR.FunctionRef
namespace Papyrus
/--
A opaque type representing an external LLVM
[Module](https://llvm.org/doxygen/classllvm_1_1Module.html).
-/
constant Llvm.Module : Type := Unit
/--
A reference to an external LLVM
[Module](https://llvm.org/doxygen/classllvm_1_1Module.html).
-/
def ModuleRef := LinkedLoosePtr ContextRef Llvm.Module
namespace ModuleRef
/-- Create a new module. -/
@[extern "papyrus_module_new"]
constant new (modID : @& String) : LlvmM ModuleRef
/-- Load module from a bitcode memory buffer. -/
@[extern "papyrus_module_parse_bitcode_from_buffer"]
constant parseBitcodeFromBuffer (self : @& MemoryBufferRef) : LlvmM ModuleRef
/-- Load module from a bitcode file. -/
def parseBitcodeFromFile (file : System.FilePath) : LlvmM ModuleRef := do
parseBitcodeFromBuffer (← MemoryBufferRef.fromFile file)
/--
Write the bitcode of the module to a file.
If `preserveUseListOrder` is set, the use-list order for each
Value in the module will be encoded in the bitcode.
These will then be reconstructed exactly when it is deserialized.
-/
@[extern "papyrus_module_write_bitcode_to_file"]
constant writeBitcodeToFile (file : @& System.FilePath) (self : @& ModuleRef)
(preserveUseListOrder := false) : IO PUnit
/-- Get the module's identifier (which is, essentially, its name). -/
@[extern "papyrus_module_get_id"]
constant getModuleID (self : @& ModuleRef) : IO String
/-- Set the module's identifier. -/
@[extern "papyrus_module_set_id"]
constant setModuleID (self : @& ModuleRef) (modID : @& String) : IO PUnit
/--
Get the function of the given name in this module.
Throws an error if no such function exist.
If `allowInternal` is set to true, this function will return globals
that have internal linkage. By default, they are not returned.
-/
@[extern "papyrus_module_get_global_variable"]
constant getGlobalVariable (name : @& String) (self : @& ModuleRef)
(allowInternal := false) : IO GlobalVariableRef
/--
Get the function of the given name in this module (if it exists).
If `allowInternal` is set to true, this function will return globals
that have internal linkage. By default, they are not returned.
-/
@[extern "papyrus_module_get_global_variable_opt"]
constant getGlobalVariable? (name : @& String) (self : @& ModuleRef)
(allowInternal := false) : IO (Option GlobalVariableRef)
/-- Get an array of references to the global variables of this module. -/
@[extern "papyrus_module_get_global_variables"]
constant getGlobalVariables (self : @& ModuleRef) : IO (Array GlobalVariableRef)
/-- Add a global variable to the end of this module . -/
@[extern "papyrus_module_append_global_variable"]
constant appendGlobalVariable (var : @& GlobalVariableRef) (self : @& ModuleRef) : IO PUnit
/--
Get the function of the given name in this module.
Throws and error if no such function exists.
-/
@[extern "papyrus_module_get_function"]
constant getFunction (name : @& String) (self : @& ModuleRef) : IO FunctionRef
/-- Get the function of the given name in this module (if it exists). -/
@[extern "papyrus_module_get_function_opt"]
constant getFunction? (name : @& String) (self : @& ModuleRef) : IO (Option FunctionRef)
/-- Get an array of references to the functions of this module. -/
@[extern "papyrus_module_get_functions"]
constant getFunctions (self : @& ModuleRef) : IO (Array FunctionRef)
/-- Add a function to the end of this module . -/
@[extern "papyrus_module_append_function"]
constant appendFunction (fn : @& FunctionRef) (self : @& ModuleRef) : IO PUnit
/--
Check the module for errors. Errors are reported inside the `IO` monad.
If `warnBrokenDebugInfo` is `true`, DebugInfo verification failures
won't be considered as an error and instead the function will return `true`.
Otherwise, the function will always return `false`.
-/
@[extern "papyrus_module_verify"]
constant verify (self : @& ModuleRef) (warnBrokenDebugInfo := false) : IO Bool
/--
Print this module to LLVM's standard output (which may not correspond to Lean's).
If`shouldPreserveUseListOrder`, the output will include `uselistorder`
directives so that use-lists can be recreated when reading the assembly.
-/
@[extern "papyrus_module_print"]
constant print (self : @& ModuleRef)
(shouldPreserveUseListOrder := false) (isForDebug := false) : IO PUnit
/--
Print this module to LLVM's standard error (which may not correspond to Lean's).
If`shouldPreserveUseListOrder`, the output will include `uselistorder`
directives so that use-lists can be recreated when reading the assembly.
-/
@[extern "papyrus_module_eprint"]
constant eprint (self : @& ModuleRef)
(shouldPreserveUseListOrder := false) (isForDebug := false) : IO PUnit
/--
Print this module to a String.
If`shouldPreserveUseListOrder`, the output will include `uselistorder`
directives so that use-lists can be recreated when reading the assembly.
-/
@[extern "papyrus_module_sprint"]
constant sprint (self : @& ModuleRef)
(shouldPreserveUseListOrder := false) (isForDebug := false) : IO String
/-- Print this module to Lean's standard output for debugging. -/
def dump (self : @& ModuleRef) : IO PUnit := do
IO.print (← self.sprint (isForDebug := true))
end ModuleRef
|
a16305457ade52d3459469cefc4b128c20898a17 | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/ring_theory/simple_module.lean | f7a3ffbe73735569cb991ca7713b80059f1b66b0 | [
"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 | 3,630 | lean | /-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors : Aaron Anderson
-/
import linear_algebra.basic
import order.atoms
/-!
# Simple Modules
## Main Definitions
* `is_simple_module` indicates that a module has no proper submodules
(the only submodules are `⊥` and `⊤`).
* A `division_ring` structure on the endomorphism ring of a simple module.
## Main Results
* Schur's Lemma: `bijective_or_eq_zero` shows that a linear map between simple modules
is either bijective or 0, leading to a `division_ring` structure on the endomorphism ring.
## TODO
* Semisimple modules, Artin-Wedderburn Theory
* Unify with the work on Schur's Lemma in a category theory context
-/
variables (R : Type*) [comm_ring R] (M : Type*) [add_comm_group M] [module R M]
/-- A module is simple when it has only two submodules, `⊥` and `⊤`. -/
abbreviation is_simple_module := (is_simple_lattice (submodule R M))
-- Making this an instance causes the linter to complain of "dangerous instances"
theorem is_simple_module.nontrivial [is_simple_module R M] : nontrivial M :=
⟨⟨0, begin
have h : (⊥ : submodule R M) ≠ ⊤ := bot_ne_top,
contrapose! h,
ext,
simp [submodule.mem_bot,submodule.mem_top, h x],
end⟩⟩
variables {R} {M} {N : Type*} [add_comm_group N] [module R N]
namespace linear_map
theorem injective_or_eq_zero [is_simple_module R M] (f : M →ₗ[R] N) :
function.injective f ∨ f = 0 :=
begin
rw [← ker_eq_bot, ← ker_eq_top],
apply eq_bot_or_eq_top,
end
theorem injective_of_ne_zero [is_simple_module R M] {f : M →ₗ[R] N} (h : f ≠ 0) :
function.injective f :=
f.injective_or_eq_zero.resolve_right h
theorem surjective_or_eq_zero [is_simple_module R N] (f : M →ₗ[R] N) :
function.surjective f ∨ f = 0 :=
begin
rw [← range_eq_top, ← range_eq_bot, or_comm],
apply eq_bot_or_eq_top,
end
theorem surjective_of_ne_zero [is_simple_module R N] {f : M →ₗ[R] N} (h : f ≠ 0) :
function.surjective f :=
f.surjective_or_eq_zero.resolve_right h
/-- Schur's Lemma for linear maps between (possibly distinct) simple modules -/
theorem bijective_or_eq_zero [is_simple_module R M] [is_simple_module R N]
(f : M →ₗ[R] N) :
function.bijective f ∨ f = 0 :=
begin
by_cases h : f = 0,
{ right,
exact h },
exact or.intro_left _ ⟨injective_of_ne_zero h, surjective_of_ne_zero h⟩,
end
theorem bijective_of_ne_zero [is_simple_module R M] [is_simple_module R N]
{f : M →ₗ[R] N} (h : f ≠ 0):
function.bijective f :=
f.bijective_or_eq_zero.resolve_right h
/-- Schur's Lemma makes the endomorphism ring of a simple module a division ring. -/
noncomputable instance [decidable_eq (module.End R M)] [is_simple_module R M] :
division_ring (module.End R M) :=
{ inv := λ f, if h : f = 0 then 0 else (linear_map.inverse f
(equiv.of_bijective _ (bijective_of_ne_zero h)).inv_fun
(equiv.of_bijective _ (bijective_of_ne_zero h)).left_inv
(equiv.of_bijective _ (bijective_of_ne_zero h)).right_inv),
exists_pair_ne := ⟨0, 1, begin
haveI := is_simple_module.nontrivial R M,
have h := exists_pair_ne M,
contrapose! h,
intros x y,
simp_rw [ext_iff, one_app, zero_apply] at h,
rw [← h x, h y],
end⟩,
mul_inv_cancel := begin
intros a a0,
change (a * (dite _ _ _)) = 1,
ext,
rw [dif_neg a0, mul_eq_comp, one_app, comp_apply],
exact (equiv.of_bijective _ (bijective_of_ne_zero a0)).right_inv x,
end,
inv_zero := dif_pos rfl,
.. (linear_map.endomorphism_ring : ring (module.End R M))}
end linear_map
|
d7223fcc82d398b5805d6e32353943f6c20051da | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/sigma/lex.lean | 9029366b44c15325872fd317a448f3b0c74fe0d5 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 7,064 | lean | /-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.sigma.basic
import order.rel_classes
/-!
# Lexicographic order on a sigma type
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> https://github.com/leanprover-community/mathlib4/pull/646
> Any changes to this file require a corresponding PR to mathlib4.
This defines the lexicographical order of two arbitrary relations on a sigma type and proves some
lemmas about `psigma.lex`, which is defined in core Lean.
Given a relation in the index type and a relation on each summand, the lexicographical order on the
sigma type relates `a` and `b` if their summands are related or they are in the same summand and
related by the summand's relation.
## See also
Related files are:
* `data.finset.colex`: Colexicographic order on finite sets.
* `data.list.lex`: Lexicographic order on lists.
* `data.sigma.order`: Lexicographic order on `Σ i, α i` per say.
* `data.psigma.order`: Lexicographic order on `Σ' i, α i`.
* `data.prod.lex`: Lexicographic order on `α × β`. Can be thought of as the special case of
`sigma.lex` where all summands are the same
-/
namespace sigma
variables {ι : Type*} {α : ι → Type*} {r r₁ r₂ : ι → ι → Prop} {s s₁ s₂ : Π i, α i → α i → Prop}
{a b : Σ i, α i}
/-- The lexicographical order on a sigma type. It takes in a relation on the index type and a
relation for each summand. `a` is related to `b` iff their summands are related or they are in the
same summand and are related through the summand's relation. -/
inductive lex (r : ι → ι → Prop) (s : Π i, α i → α i → Prop) : Π a b : Σ i, α i, Prop
| left {i j : ι} (a : α i) (b : α j) : r i j → lex ⟨i, a⟩ ⟨j, b⟩
| right {i : ι} (a b : α i) : s i a b → lex ⟨i, a⟩ ⟨i, b⟩
lemma lex_iff : lex r s a b ↔ r a.1 b.1 ∨ ∃ h : a.1 = b.1, s _ (h.rec a.2) b.2 :=
begin
split,
{ rintro (⟨a, b, hij⟩ | ⟨a, b, hab⟩),
{ exact or.inl hij },
{ exact or.inr ⟨rfl, hab⟩ } },
{ obtain ⟨i, a⟩ := a,
obtain ⟨j, b⟩ := b,
dsimp only,
rintro (h | ⟨rfl, h⟩),
{ exact lex.left _ _ h },
{ exact lex.right _ _ h } }
end
instance lex.decidable (r : ι → ι → Prop) (s : Π i, α i → α i → Prop) [decidable_eq ι]
[decidable_rel r] [Π i, decidable_rel (s i)] :
decidable_rel (lex r s) :=
λ a b, decidable_of_decidable_of_iff infer_instance lex_iff.symm
lemma lex.mono (hr : ∀ a b, r₁ a b → r₂ a b) (hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ i, α i}
(h : lex r₁ s₁ a b) :
lex r₂ s₂ a b :=
begin
obtain (⟨a, b, hij⟩ | ⟨a, b, hab⟩) := h,
{ exact lex.left _ _ (hr _ _ hij) },
{ exact lex.right _ _ (hs _ _ _ hab) }
end
lemma lex.mono_left (hr : ∀ a b, r₁ a b → r₂ a b) {a b : Σ i, α i} (h : lex r₁ s a b) :
lex r₂ s a b :=
h.mono hr $ λ _ _ _, id
lemma lex.mono_right (hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ i, α i} (h : lex r s₁ a b) :
lex r s₂ a b :=
h.mono (λ _ _, id) hs
lemma lex_swap : lex r.swap s a b ↔ lex r (λ i, (s i).swap) b a :=
by split; { rintro (⟨a, b, h⟩ | ⟨a, b, h⟩), exacts [lex.left _ _ h, lex.right _ _ h] }
instance [Π i, is_refl (α i) (s i)] : is_refl _ (lex r s) := ⟨λ ⟨i, a⟩, lex.right _ _ $ refl _⟩
instance [is_irrefl ι r] [Π i, is_irrefl (α i) (s i)] : is_irrefl _ (lex r s) :=
⟨begin
rintro _ (⟨a, b, hi⟩ | ⟨a, b, ha⟩),
{ exact irrefl _ hi },
{ exact irrefl _ ha }
end⟩
instance [is_trans ι r] [Π i, is_trans (α i) (s i)] : is_trans _ (lex r s) :=
⟨begin
rintro _ _ _ (⟨a, b, hij⟩ | ⟨a, b, hab⟩) (⟨_, c, hk⟩ | ⟨_, c, hc⟩),
{ exact lex.left _ _ (trans hij hk) },
{ exact lex.left _ _ hij },
{ exact lex.left _ _ hk },
{ exact lex.right _ _ (trans hab hc) }
end⟩
instance [is_symm ι r] [Π i, is_symm (α i) (s i)] : is_symm _ (lex r s) :=
⟨begin
rintro _ _ (⟨a, b, hij⟩ | ⟨a, b, hab⟩),
{ exact lex.left _ _ (symm hij) },
{ exact lex.right _ _ (symm hab) }
end⟩
local attribute [instance] is_asymm.is_irrefl
instance [is_asymm ι r] [Π i, is_antisymm (α i) (s i)] : is_antisymm _ (lex r s) :=
⟨begin
rintro _ _ (⟨a, b, hij⟩ | ⟨a, b, hab⟩) (⟨_, _, hji⟩ | ⟨_, _, hba⟩),
{ exact (asymm hij hji).elim },
{ exact (irrefl _ hij).elim },
{ exact (irrefl _ hji).elim },
{ exact ext rfl (heq_of_eq $ antisymm hab hba) }
end⟩
instance [is_trichotomous ι r] [Π i, is_total (α i) (s i)] : is_total _ (lex r s) :=
⟨begin
rintro ⟨i, a⟩ ⟨j, b⟩,
obtain hij | rfl | hji := trichotomous_of r i j,
{ exact or.inl (lex.left _ _ hij) },
{ obtain hab | hba := total_of (s i) a b,
{ exact or.inl (lex.right _ _ hab) },
{ exact or.inr (lex.right _ _ hba) } },
{ exact or.inr (lex.left _ _ hji) }
end⟩
instance [is_trichotomous ι r] [Π i, is_trichotomous (α i) (s i)] : is_trichotomous _ (lex r s) :=
⟨begin
rintro ⟨i, a⟩ ⟨j, b⟩,
obtain hij | rfl | hji := trichotomous_of r i j,
{ exact or.inl (lex.left _ _ hij) },
{ obtain hab | rfl | hba := trichotomous_of (s i) a b,
{ exact or.inl (lex.right _ _ hab) },
{ exact or.inr (or.inl rfl) },
{ exact or.inr (or.inr $ lex.right _ _ hba) } },
{ exact or.inr (or.inr $ lex.left _ _ hji) }
end⟩
end sigma
/-! ### `psigma` -/
namespace psigma
variables {ι : Sort*} {α : ι → Sort*} {r r₁ r₂ : ι → ι → Prop} {s s₁ s₂ : Π i, α i → α i → Prop}
lemma lex_iff {a b : Σ' i, α i} : lex r s a b ↔ r a.1 b.1 ∨ ∃ h : a.1 = b.1, s _ (h.rec a.2) b.2 :=
begin
split,
{ rintro (⟨a, b, hij⟩ | ⟨i, hab⟩),
{ exact or.inl hij },
{ exact or.inr ⟨rfl, hab⟩ } },
{ obtain ⟨i, a⟩ := a,
obtain ⟨j, b⟩ := b,
dsimp only,
rintro (h | ⟨rfl, h⟩),
{ exact lex.left _ _ h },
{ exact lex.right _ h } }
end
instance lex.decidable (r : ι → ι → Prop) (s : Π i, α i → α i → Prop) [decidable_eq ι]
[decidable_rel r] [Π i, decidable_rel (s i)] :
decidable_rel (lex r s) :=
λ a b, decidable_of_decidable_of_iff infer_instance lex_iff.symm
lemma lex.mono {r₁ r₂ : ι → ι → Prop} {s₁ s₂ : Π i, α i → α i → Prop}
(hr : ∀ a b, r₁ a b → r₂ a b) (hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ' i, α i}
(h : lex r₁ s₁ a b) :
lex r₂ s₂ a b :=
begin
obtain (⟨a, b, hij⟩ | ⟨i, hab⟩) := h,
{ exact lex.left _ _ (hr _ _ hij) },
{ exact lex.right _ (hs _ _ _ hab) }
end
lemma lex.mono_left {r₁ r₂ : ι → ι → Prop} {s : Π i, α i → α i → Prop}
(hr : ∀ a b, r₁ a b → r₂ a b) {a b : Σ' i, α i} (h : lex r₁ s a b) :
lex r₂ s a b :=
h.mono hr $ λ _ _ _, id
lemma lex.mono_right {r : ι → ι → Prop} {s₁ s₂ : Π i, α i → α i → Prop}
(hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ' i, α i} (h : lex r s₁ a b) :
lex r s₂ a b :=
h.mono (λ _ _, id) hs
end psigma
|
fd137c0636c66fe25299f289213e6229f4f0ab73 | 367134ba5a65885e863bdc4507601606690974c1 | /src/tactic/omega/nat/neg_elim.lean | a8fc8f4d7b22f5720df8362a31e95155e702337e | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 3,958 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
-/
/-
Negation elimination.
-/
import tactic.omega.nat.form
namespace omega
namespace nat
open_locale omega.nat
/-- push_neg p returns the result of normalizing ¬ p by
pushing the outermost negation all the way down,
until it reaches either a negation or an atom -/
@[simp] def push_neg : preform → preform
| (p ∨* q) := (push_neg p) ∧* (push_neg q)
| (p ∧* q) := (push_neg p) ∨* (push_neg q)
| (¬*p) := p
| p := ¬* p
lemma push_neg_equiv :
∀ {p : preform}, preform.equiv (push_neg p) (¬* p) :=
begin
preform.induce `[intros v; try {refl}],
{ simp only [not_not, preform.holds, push_neg] },
{ simp only [preform.holds, push_neg, not_or_distrib, ihp v, ihq v] },
{ simp only [preform.holds, push_neg, not_and_distrib, ihp v, ihq v] }
end
/-- NNF transformation -/
def nnf : preform → preform
| (¬* p) := push_neg (nnf p)
| (p ∨* q) := (nnf p) ∨* (nnf q)
| (p ∧* q) := (nnf p) ∧* (nnf q)
| a := a
/-- Asserts that the given preform is in NNF -/
def is_nnf : preform → Prop
| (t =* s) := true
| (t ≤* s) := true
| ¬*(t =* s) := true
| ¬*(t ≤* s) := true
| (p ∨* q) := is_nnf p ∧ is_nnf q
| (p ∧* q) := is_nnf p ∧ is_nnf q
| _ := false
lemma is_nnf_push_neg : ∀ p : preform, is_nnf p → is_nnf (push_neg p) :=
begin
preform.induce `[intro h1; try {trivial}],
{ cases p; try {cases h1}; trivial },
{ cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption },
{ cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption }
end
lemma is_nnf_nnf : ∀ p : preform, is_nnf (nnf p) :=
begin
preform.induce `[try {trivial}],
{ apply is_nnf_push_neg _ ih },
{ constructor; assumption },
{ constructor; assumption }
end
lemma nnf_equiv : ∀ {p : preform}, preform.equiv (nnf p) p :=
begin
preform.induce `[intros v; try {refl}; simp only [nnf]],
{ rw push_neg_equiv,
apply not_iff_not_of_iff, apply ih },
{ apply pred_mono_2' (ihp v) (ihq v) },
{ apply pred_mono_2' (ihp v) (ihq v) }
end
@[simp] def neg_elim_core : preform → preform
| (¬* (t =* s)) := (t.add_one ≤* s) ∨* (s.add_one ≤* t)
| (¬* (t ≤* s)) := s.add_one ≤* t
| (p ∨* q) := (neg_elim_core p) ∨* (neg_elim_core q)
| (p ∧* q) := (neg_elim_core p) ∧* (neg_elim_core q)
| p := p
lemma neg_free_neg_elim_core : ∀ p, is_nnf p → (neg_elim_core p).neg_free :=
begin
preform.induce `[intro h1, try {simp only [neg_free, neg_elim_core]}, try {trivial}],
{ cases p; try {cases h1}; try {trivial},
constructor; trivial },
{ cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption },
{ cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption }
end
lemma le_and_le_iff_eq {α : Type} [partial_order α] {a b : α} :
(a ≤ b ∧ b ≤ a) ↔ a = b :=
begin
constructor; intro h1,
{ cases h1, apply le_antisymm; assumption },
{ constructor; apply le_of_eq; rw h1 }
end
lemma implies_neg_elim_core : ∀ {p : preform},
preform.implies p (neg_elim_core p) :=
begin
preform.induce `[intros v h, try {apply h}],
{ cases p with t s t s; try {apply h},
{ apply or.symm,
simpa only [preform.holds, le_and_le_iff_eq.symm,
not_and_distrib, not_le] using h },
simpa only [preform.holds, not_le, int.add_one_le_iff] using h },
{ simp only [neg_elim_core], cases h;
[{left, apply ihp}, {right, apply ihq}];
assumption },
apply and.imp (ihp _) (ihq _) h
end
/-- Eliminate all negations in a preform -/
def neg_elim : preform → preform := neg_elim_core ∘ nnf
lemma neg_free_neg_elim {p : preform} : (neg_elim p).neg_free :=
neg_free_neg_elim_core _ (is_nnf_nnf _)
lemma implies_neg_elim {p : preform} : preform.implies p (neg_elim p) :=
begin
intros v h1, apply implies_neg_elim_core,
apply (nnf_equiv v).elim_right h1
end
end nat
end omega
|
12e7b7e9e4cd86ccb56d3735349ddfec0476487f | 94e33a31faa76775069b071adea97e86e218a8ee | /src/algebra/lie/submodule.lean | 8c156677de16939057a11cdda722ce6fc90059e5 | [
"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 | 36,991 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.subalgebra
import ring_theory.noetherian
/-!
# Lie submodules of a Lie algebra
In this file we define Lie submodules and Lie ideals, we construct the lattice structure on Lie
submodules and we use it to define various important operations, notably the Lie span of a subset
of a Lie module.
## Main definitions
* `lie_submodule`
* `lie_submodule.well_founded_of_noetherian`
* `lie_submodule.lie_span`
* `lie_submodule.map`
* `lie_submodule.comap`
* `lie_ideal`
* `lie_ideal.map`
* `lie_ideal.comap`
## Tags
lie algebra, lie submodule, lie ideal, lattice structure
-/
universes u v w w₁ w₂
section lie_submodule
variables (R : Type u) (L : Type v) (M : Type w)
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
set_option old_structure_cmd true
/-- A Lie submodule of a Lie module is a submodule that is closed under the Lie bracket.
This is a sufficient condition for the subset itself to form a Lie module. -/
structure lie_submodule extends submodule R M :=
(lie_mem : ∀ {x : L} {m : M}, m ∈ carrier → ⁅x, m⁆ ∈ carrier)
attribute [nolint doc_blame] lie_submodule.to_submodule
namespace lie_submodule
variables {R L M} (N N' : lie_submodule R L M)
instance : set_like (lie_submodule R L M) M :=
{ coe := carrier,
coe_injective' := λ N O h, by cases N; cases O; congr' }
instance : add_subgroup_class (lie_submodule R L M) M :=
{ add_mem := λ N, N.add_mem',
zero_mem := λ N, N.zero_mem',
neg_mem := λ N x hx, show -x ∈ N.to_submodule, from neg_mem hx }
/-- The zero module is a Lie submodule of any Lie module. -/
instance : has_zero (lie_submodule R L M) :=
⟨{ lie_mem := λ x m h, by { rw ((submodule.mem_bot R).1 h), apply lie_zero, },
..(0 : submodule R M)}⟩
instance : inhabited (lie_submodule R L M) := ⟨0⟩
instance coe_submodule : has_coe (lie_submodule R L M) (submodule R M) := ⟨to_submodule⟩
@[simp] lemma to_submodule_eq_coe : N.to_submodule = N := rfl
@[norm_cast]
lemma coe_to_submodule : ((N : submodule R M) : set M) = N := rfl
@[simp] lemma mem_carrier {x : M} : x ∈ N.carrier ↔ x ∈ (N : set M) :=
iff.rfl
@[simp] lemma mem_mk_iff (S : set M) (h₁ h₂ h₃ h₄) {x : M} :
x ∈ (⟨S, h₁, h₂, h₃, h₄⟩ : lie_submodule R L M) ↔ x ∈ S :=
iff.rfl
@[simp] lemma mem_coe_submodule {x : M} : x ∈ (N : submodule R M) ↔ x ∈ N := iff.rfl
lemma mem_coe {x : M} : x ∈ (N : set M) ↔ x ∈ N := iff.rfl
@[simp] protected lemma zero_mem : (0 : M) ∈ N := zero_mem N
@[simp] lemma mk_eq_zero {x} (h : x ∈ N) : (⟨x, h⟩ : N) = 0 ↔ x = 0 := subtype.ext_iff_val
@[simp] lemma coe_to_set_mk (S : set M) (h₁ h₂ h₃ h₄) :
((⟨S, h₁, h₂, h₃, h₄⟩ : lie_submodule R L M) : set M) = S := rfl
@[simp] lemma coe_to_submodule_mk (p : submodule R M) (h) :
(({lie_mem := h, ..p} : lie_submodule R L M) : submodule R M) = p :=
by { cases p, refl, }
lemma coe_submodule_injective :
function.injective (to_submodule : lie_submodule R L M → submodule R M) :=
λ x y h, by { cases x, cases y, congr, injection h }
@[ext] lemma ext (h : ∀ m, m ∈ N ↔ m ∈ N') : N = N' := set_like.ext h
@[simp] lemma coe_to_submodule_eq_iff : (N : submodule R M) = (N' : submodule R M) ↔ N = N' :=
coe_submodule_injective.eq_iff
/-- Copy of a lie_submodule with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (s : set M) (hs : s = ↑N) : lie_submodule R L M :=
{ carrier := s,
zero_mem' := hs.symm ▸ N.zero_mem',
add_mem' := hs.symm ▸ N.add_mem',
smul_mem' := hs.symm ▸ N.smul_mem',
lie_mem := hs.symm ▸ N.lie_mem, }
@[simp] lemma coe_copy (S : lie_submodule R L M) (s : set M) (hs : s = ↑S) :
(S.copy s hs : set M) = s := rfl
lemma copy_eq (S : lie_submodule R L M) (s : set M) (hs : s = ↑S) : S.copy s hs = S :=
coe_submodule_injective (set_like.coe_injective hs)
instance : lie_ring_module L N :=
{ bracket := λ (x : L) (m : N), ⟨⁅x, m.val⁆, N.lie_mem m.property⟩,
add_lie := by { intros x y m, apply set_coe.ext, apply add_lie, },
lie_add := by { intros x m n, apply set_coe.ext, apply lie_add, },
leibniz_lie := by { intros x y m, apply set_coe.ext, apply leibniz_lie, }, }
instance module' {S : Type*} [semiring S] [has_smul S R] [module S M] [is_scalar_tower S R M] :
module S N :=
N.to_submodule.module'
instance : module R N := N.to_submodule.module
instance {S : Type*} [semiring S] [has_smul S R] [has_smul Sᵐᵒᵖ R] [module S M] [module Sᵐᵒᵖ M]
[is_scalar_tower S R M] [is_scalar_tower Sᵐᵒᵖ R M] [is_central_scalar S M] :
is_central_scalar S N :=
N.to_submodule.is_central_scalar
instance : lie_module R L N :=
{ lie_smul := by { intros t x y, apply set_coe.ext, apply lie_smul, },
smul_lie := by { intros t x y, apply set_coe.ext, apply smul_lie, }, }
@[simp, norm_cast] lemma coe_zero : ((0 : N) : M) = (0 : M) := rfl
@[simp, norm_cast] lemma coe_add (m m' : N) : (↑(m + m') : M) = (m : M) + (m' : M) := rfl
@[simp, norm_cast] lemma coe_neg (m : N) : (↑(-m) : M) = -(m : M) := rfl
@[simp, norm_cast] lemma coe_sub (m m' : N) : (↑(m - m') : M) = (m : M) - (m' : M) := rfl
@[simp, norm_cast] lemma coe_smul (t : R) (m : N) : (↑(t • m) : M) = t • (m : M) := rfl
@[simp, norm_cast] lemma coe_bracket (x : L) (m : N) : (↑⁅x, m⁆ : M) = ⁅x, ↑m⁆ := rfl
end lie_submodule
section lie_ideal
variables (L)
/-- An ideal of a Lie algebra is a Lie submodule of the Lie algebra as a Lie module over itself. -/
abbreviation lie_ideal := lie_submodule R L L
lemma lie_mem_right (I : lie_ideal R L) (x y : L) (h : y ∈ I) : ⁅x, y⁆ ∈ I := I.lie_mem h
lemma lie_mem_left (I : lie_ideal R L) (x y : L) (h : x ∈ I) : ⁅x, y⁆ ∈ I :=
by { rw [←lie_skew, ←neg_lie], apply lie_mem_right, assumption, }
/-- An ideal of a Lie algebra is a Lie subalgebra. -/
def lie_ideal_subalgebra (I : lie_ideal R L) : lie_subalgebra R L :=
{ lie_mem' := by { intros x y hx hy, apply lie_mem_right, exact hy, },
..I.to_submodule, }
instance : has_coe (lie_ideal R L) (lie_subalgebra R L) := ⟨λ I, lie_ideal_subalgebra R L I⟩
@[norm_cast] lemma lie_ideal.coe_to_subalgebra (I : lie_ideal R L) :
((I : lie_subalgebra R L) : set L) = I := rfl
@[norm_cast] lemma lie_ideal.coe_to_lie_subalgebra_to_submodule (I : lie_ideal R L) :
((I : lie_subalgebra R L) : submodule R L) = I := rfl
end lie_ideal
variables {R M}
lemma submodule.exists_lie_submodule_coe_eq_iff (p : submodule R M) :
(∃ (N : lie_submodule R L M), ↑N = p) ↔ ∀ (x : L) (m : M), m ∈ p → ⁅x, m⁆ ∈ p :=
begin
split,
{ rintros ⟨N, rfl⟩, exact N.lie_mem, },
{ intros h, use { lie_mem := h, ..p }, exact lie_submodule.coe_to_submodule_mk p _, },
end
namespace lie_subalgebra
variables {L} (K : lie_subalgebra R L)
/-- Given a Lie subalgebra `K ⊆ L`, if we view `L` as a `K`-module by restriction, it contains
a distinguished Lie submodule for the action of `K`, namely `K` itself. -/
def to_lie_submodule : lie_submodule R K L :=
{ lie_mem := λ x y hy, K.lie_mem x.property hy,
.. (K : submodule R L) }
@[simp] lemma coe_to_lie_submodule :
(K.to_lie_submodule : submodule R L) = K :=
by { rcases K with ⟨⟨⟩⟩, refl, }
variables {K}
@[simp] lemma mem_to_lie_submodule (x : L) :
x ∈ K.to_lie_submodule ↔ x ∈ K :=
iff.rfl
lemma exists_lie_ideal_coe_eq_iff :
(∃ (I : lie_ideal R L), ↑I = K) ↔ ∀ (x y : L), y ∈ K → ⁅x, y⁆ ∈ K :=
begin
simp only [← coe_to_submodule_eq_iff, lie_ideal.coe_to_lie_subalgebra_to_submodule,
submodule.exists_lie_submodule_coe_eq_iff L],
exact iff.rfl,
end
lemma exists_nested_lie_ideal_coe_eq_iff {K' : lie_subalgebra R L} (h : K ≤ K') :
(∃ (I : lie_ideal R K'), ↑I = of_le h) ↔ ∀ (x y : L), x ∈ K' → y ∈ K → ⁅x, y⁆ ∈ K :=
begin
simp only [exists_lie_ideal_coe_eq_iff, coe_bracket, mem_of_le],
split,
{ intros h' x y hx hy, exact h' ⟨x, hx⟩ ⟨y, h hy⟩ hy, },
{ rintros h' ⟨x, hx⟩ ⟨y, hy⟩ hy', exact h' x y hx hy', },
end
end lie_subalgebra
end lie_submodule
namespace lie_submodule
variables {R : Type u} {L : Type v} {M : Type w}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
variables (N N' : lie_submodule R L M) (I J : lie_ideal R L)
section lattice_structure
open set
lemma coe_injective : function.injective (coe : lie_submodule R L M → set M) :=
set_like.coe_injective
@[simp, norm_cast] lemma coe_submodule_le_coe_submodule : (N : submodule R M) ≤ N' ↔ N ≤ N' :=
iff.rfl
instance : has_bot (lie_submodule R L M) := ⟨0⟩
@[simp] lemma bot_coe : ((⊥ : lie_submodule R L M) : set M) = {0} := rfl
@[simp] lemma bot_coe_submodule : ((⊥ : lie_submodule R L M) : submodule R M) = ⊥ := rfl
@[simp] lemma mem_bot (x : M) : x ∈ (⊥ : lie_submodule R L M) ↔ x = 0 := mem_singleton_iff
instance : has_top (lie_submodule R L M) :=
⟨{ lie_mem := λ x m h, mem_univ ⁅x, m⁆,
..(⊤ : submodule R M) }⟩
@[simp] lemma top_coe : ((⊤ : lie_submodule R L M) : set M) = univ := rfl
@[simp] lemma top_coe_submodule : ((⊤ : lie_submodule R L M) : submodule R M) = ⊤ := rfl
@[simp] lemma mem_top (x : M) : x ∈ (⊤ : lie_submodule R L M) := mem_univ x
instance : has_inf (lie_submodule R L M) :=
⟨λ N N', { lie_mem := λ x m h, mem_inter (N.lie_mem h.1) (N'.lie_mem h.2),
..(N ⊓ N' : submodule R M) }⟩
instance : has_Inf (lie_submodule R L M) :=
⟨λ S, { lie_mem := λ x m h, by
{ simp only [submodule.mem_carrier, mem_Inter, submodule.Inf_coe, mem_set_of_eq,
forall_apply_eq_imp_iff₂, exists_imp_distrib] at *,
intros N hN, apply N.lie_mem (h N hN), },
..Inf {(s : submodule R M) | s ∈ S} }⟩
@[simp] theorem inf_coe : (↑(N ⊓ N') : set M) = N ∩ N' := rfl
@[simp] lemma Inf_coe_to_submodule (S : set (lie_submodule R L M)) :
(↑(Inf S) : submodule R M) = Inf {(s : submodule R M) | s ∈ S} := rfl
@[simp] lemma Inf_coe (S : set (lie_submodule R L M)) : (↑(Inf S) : set M) = ⋂ s ∈ S, (s : set M) :=
begin
rw [← lie_submodule.coe_to_submodule, Inf_coe_to_submodule, submodule.Inf_coe],
ext m,
simpa only [mem_Inter, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib],
end
lemma Inf_glb (S : set (lie_submodule R L M)) : is_glb S (Inf S) :=
begin
have h : ∀ (N N' : lie_submodule R L M), (N : set M) ≤ N' ↔ N ≤ N', { intros, refl },
apply is_glb.of_image h,
simp only [Inf_coe],
exact is_glb_binfi
end
/-- The set of Lie submodules of a Lie module form a complete lattice.
We provide explicit values for the fields `bot`, `top`, `inf` to get more convenient definitions
than we would otherwise obtain from `complete_lattice_of_Inf`. -/
instance : complete_lattice (lie_submodule R L M) :=
{ le := (≤),
lt := (<),
bot := ⊥,
bot_le := λ N _ h, by { rw mem_bot at h, rw h, exact N.zero_mem', },
top := ⊤,
le_top := λ _ _ _, trivial,
inf := (⊓),
le_inf := λ N₁ N₂ N₃ h₁₂ h₁₃ m hm, ⟨h₁₂ hm, h₁₃ hm⟩,
inf_le_left := λ _ _ _, and.left,
inf_le_right := λ _ _ _, and.right,
..set_like.partial_order,
..complete_lattice_of_Inf _ Inf_glb }
instance : add_comm_monoid (lie_submodule R L M) :=
{ add := (⊔),
add_assoc := λ _ _ _, sup_assoc,
zero := ⊥,
zero_add := λ _, bot_sup_eq,
add_zero := λ _, sup_bot_eq,
add_comm := λ _ _, sup_comm, }
@[simp] lemma add_eq_sup : N + N' = N ⊔ N' := rfl
@[norm_cast, simp] lemma sup_coe_to_submodule :
(↑(N ⊔ N') : submodule R M) = (N : submodule R M) ⊔ (N' : submodule R M) :=
begin
have aux : ∀ (x : L) m, m ∈ (N ⊔ N' : submodule R M) → ⁅x,m⁆ ∈ (N ⊔ N' : submodule R M),
{ simp only [submodule.mem_sup],
rintro x m ⟨y, hy, z, hz, rfl⟩,
refine ⟨⁅x, y⁆, N.lie_mem hy, ⁅x, z⁆, N'.lie_mem hz, (lie_add _ _ _).symm⟩ },
refine le_antisymm (Inf_le ⟨{ lie_mem := aux, ..(N ⊔ N' : submodule R M) }, _⟩) _,
{ simp only [exists_prop, and_true, mem_set_of_eq, eq_self_iff_true, coe_to_submodule_mk,
← coe_submodule_le_coe_submodule, and_self, le_sup_left, le_sup_right] },
{ simp, },
end
@[norm_cast, simp] lemma inf_coe_to_submodule :
(↑(N ⊓ N') : submodule R M) = (N : submodule R M) ⊓ (N' : submodule R M) := rfl
@[simp] lemma mem_inf (x : M) : x ∈ N ⊓ N' ↔ x ∈ N ∧ x ∈ N' :=
by rw [← mem_coe_submodule, ← mem_coe_submodule, ← mem_coe_submodule, inf_coe_to_submodule,
submodule.mem_inf]
lemma mem_sup (x : M) : x ∈ N ⊔ N' ↔ ∃ (y ∈ N) (z ∈ N'), y + z = x :=
by { rw [← mem_coe_submodule, sup_coe_to_submodule, submodule.mem_sup], exact iff.rfl, }
lemma eq_bot_iff : N = ⊥ ↔ ∀ (m : M), m ∈ N → m = 0 :=
by { rw eq_bot_iff, exact iff.rfl, }
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_bot : subsingleton (lie_submodule R L ↥(⊥ : lie_submodule R L M)) :=
begin
apply subsingleton_of_bot_eq_top,
ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw submodule.mem_bot at hx, subst hx,
simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, lie_submodule.mem_bot],
end
instance : is_modular_lattice (lie_submodule R L M) :=
{ sup_inf_le_assoc_of_le := λ N₁ N₂ N₃,
by { simp only [← coe_submodule_le_coe_submodule, sup_coe_to_submodule, inf_coe_to_submodule],
exact is_modular_lattice.sup_inf_le_assoc_of_le ↑N₂, }, }
variables (R L M)
lemma well_founded_of_noetherian [is_noetherian R M] :
well_founded ((>) : lie_submodule R L M → lie_submodule R L M → Prop) :=
let f : ((>) : lie_submodule R L M → lie_submodule R L M → Prop) →r
((>) : submodule R M → submodule R M → Prop) :=
{ to_fun := coe,
map_rel' := λ N N' h, h, }
in rel_hom_class.well_founded f (is_noetherian_iff_well_founded.mp infer_instance)
@[simp] lemma subsingleton_iff : subsingleton (lie_submodule R L M) ↔ subsingleton M :=
have h : subsingleton (lie_submodule R L M) ↔ subsingleton (submodule R M),
{ rw [← subsingleton_iff_bot_eq_top, ← subsingleton_iff_bot_eq_top, ← coe_to_submodule_eq_iff,
top_coe_submodule, bot_coe_submodule], },
h.trans $ submodule.subsingleton_iff R
@[simp] lemma nontrivial_iff : nontrivial (lie_submodule R L M) ↔ nontrivial M :=
not_iff_not.mp (
(not_nontrivial_iff_subsingleton.trans $ subsingleton_iff R L M).trans
not_nontrivial_iff_subsingleton.symm)
instance [nontrivial M] : nontrivial (lie_submodule R L M) := (nontrivial_iff R L M).mpr ‹_›
lemma nontrivial_iff_ne_bot {N : lie_submodule R L M} : nontrivial N ↔ N ≠ ⊥ :=
begin
split;
contrapose!,
{ rintros rfl ⟨⟨m₁, h₁ : m₁ ∈ (⊥ : lie_submodule R L M)⟩,
⟨m₂, h₂ : m₂ ∈ (⊥ : lie_submodule R L M)⟩, h₁₂⟩,
simpa [(lie_submodule.mem_bot _).mp h₁, (lie_submodule.mem_bot _).mp h₂] using h₁₂, },
{ rw [not_nontrivial_iff_subsingleton, lie_submodule.eq_bot_iff],
rintros ⟨h⟩ m hm,
simpa using h ⟨m, hm⟩ ⟨_, N.zero_mem⟩, },
end
variables {R L M}
section inclusion_maps
/-- The inclusion of a Lie submodule into its ambient space is a morphism of Lie modules. -/
def incl : N →ₗ⁅R,L⁆ M :=
{ map_lie' := λ x m, rfl,
..submodule.subtype (N : submodule R M) }
@[simp] lemma incl_coe : (N.incl : N →ₗ[R] M) = (N : submodule R M).subtype := rfl
@[simp] lemma incl_apply (m : N) : N.incl m = m := rfl
lemma incl_eq_val : (N.incl : N → M) = subtype.val := rfl
variables {N N'} (h : N ≤ N')
/-- Given two nested Lie submodules `N ⊆ N'`, the inclusion `N ↪ N'` is a morphism of Lie modules.-/
def hom_of_le : N →ₗ⁅R,L⁆ N' :=
{ map_lie' := λ x m, rfl,
..submodule.of_le (show N.to_submodule ≤ N'.to_submodule, from h) }
@[simp] lemma coe_hom_of_le (m : N) : (hom_of_le h m : M) = m := rfl
lemma hom_of_le_apply (m : N) : hom_of_le h m = ⟨m.1, h m.2⟩ := rfl
lemma hom_of_le_injective : function.injective (hom_of_le h) :=
λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe,
subtype.val_eq_coe]
end inclusion_maps
section lie_span
variables (R L) (s : set M)
/-- The `lie_span` of a set `s ⊆ M` is the smallest Lie submodule of `M` that contains `s`. -/
def lie_span : lie_submodule R L M := Inf {N | s ⊆ N}
variables {R L s}
lemma mem_lie_span {x : M} : x ∈ lie_span R L s ↔ ∀ N : lie_submodule R L M, s ⊆ N → x ∈ N :=
by { change x ∈ (lie_span R L s : set M) ↔ _, erw Inf_coe, exact mem_Inter₂, }
lemma subset_lie_span : s ⊆ lie_span R L s :=
by { intros m hm, erw mem_lie_span, intros N hN, exact hN hm, }
lemma submodule_span_le_lie_span : submodule.span R s ≤ lie_span R L s :=
by { rw submodule.span_le, apply subset_lie_span, }
lemma lie_span_le {N} : lie_span R L s ≤ N ↔ s ⊆ N :=
begin
split,
{ exact subset.trans subset_lie_span, },
{ intros hs m hm, rw mem_lie_span at hm, exact hm _ hs, },
end
lemma lie_span_mono {t : set M} (h : s ⊆ t) : lie_span R L s ≤ lie_span R L t :=
by { rw lie_span_le, exact subset.trans h subset_lie_span, }
lemma lie_span_eq : lie_span R L (N : set M) = N :=
le_antisymm (lie_span_le.mpr rfl.subset) subset_lie_span
lemma coe_lie_span_submodule_eq_iff {p : submodule R M} :
(lie_span R L (p : set M) : submodule R M) = p ↔ ∃ (N : lie_submodule R L M), ↑N = p :=
begin
rw p.exists_lie_submodule_coe_eq_iff L, split; intros h,
{ intros x m hm, rw [← h, mem_coe_submodule], exact lie_mem _ (subset_lie_span hm), },
{ rw [← coe_to_submodule_mk p h, coe_to_submodule, coe_to_submodule_eq_iff, lie_span_eq], },
end
variables (R L M)
/-- `lie_span` forms a Galois insertion with the coercion from `lie_submodule` to `set`. -/
protected def gi : galois_insertion (lie_span R L : set M → lie_submodule R L M) coe :=
{ choice := λ s _, lie_span R L s,
gc := λ s t, lie_span_le,
le_l_u := λ s, subset_lie_span,
choice_eq := λ s h, rfl }
@[simp] lemma span_empty : lie_span R L (∅ : set M) = ⊥ :=
(lie_submodule.gi R L M).gc.l_bot
@[simp] lemma span_univ : lie_span R L (set.univ : set M) = ⊤ :=
eq_top_iff.2 $ set_like.le_def.2 $ subset_lie_span
lemma lie_span_eq_bot_iff : lie_span R L s = ⊥ ↔ ∀ (m ∈ s), m = (0 : M) :=
by rw [_root_.eq_bot_iff, lie_span_le, bot_coe, subset_singleton_iff]
variables {M}
lemma span_union (s t : set M) : lie_span R L (s ∪ t) = lie_span R L s ⊔ lie_span R L t :=
(lie_submodule.gi R L M).gc.l_sup
lemma span_Union {ι} (s : ι → set M) : lie_span R L (⋃ i, s i) = ⨆ i, lie_span R L (s i) :=
(lie_submodule.gi R L M).gc.l_supr
end lie_span
end lattice_structure
end lie_submodule
section lie_submodule_map_and_comap
variables {R : Type u} {L : Type v} {L' : Type w₂} {M : Type w} {M' : Type w₁}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L']
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables [add_comm_group M'] [module R M'] [lie_ring_module L M'] [lie_module R L M']
namespace lie_submodule
variables (f : M →ₗ⁅R,L⁆ M') (N N₂ : lie_submodule R L M) (N' : lie_submodule R L M')
/-- A morphism of Lie modules `f : M → M'` pushes forward Lie submodules of `M` to Lie submodules
of `M'`. -/
def map : lie_submodule R L M' :=
{ lie_mem := λ x m' h, by
{ rcases h with ⟨m, hm, hfm⟩, use ⁅x, m⁆, split,
{ apply N.lie_mem hm, },
{ norm_cast at hfm, simp [hfm], }, },
..(N : submodule R M).map (f : M →ₗ[R] M') }
@[simp] lemma coe_submodule_map :
(N.map f : submodule R M') = (N : submodule R M).map (f : M →ₗ[R] M') :=
rfl
/-- A morphism of Lie modules `f : M → M'` pulls back Lie submodules of `M'` to Lie submodules of
`M`. -/
def comap : lie_submodule R L M :=
{ lie_mem := λ x m h, by { suffices : ⁅x, f m⁆ ∈ N', { simp [this], }, apply N'.lie_mem h, },
..(N' : submodule R M').comap (f : M →ₗ[R] M') }
@[simp] lemma coe_submodule_comap :
(N'.comap f : submodule R M) = (N' : submodule R M').comap (f : M →ₗ[R] M') :=
rfl
variables {f N N₂ N'}
lemma map_le_iff_le_comap : map f N ≤ N' ↔ N ≤ comap f N' :=
set.image_subset_iff
variables (f)
lemma gc_map_comap : galois_connection (map f) (comap f) :=
λ N N', map_le_iff_le_comap
variables {f}
@[simp] lemma map_sup : (N ⊔ N₂).map f = N.map f ⊔ N₂.map f :=
(gc_map_comap f).l_sup
lemma mem_map (m' : M') : m' ∈ N.map f ↔ ∃ m, m ∈ N ∧ f m = m' :=
submodule.mem_map
@[simp] lemma mem_comap {m : M} : m ∈ comap f N' ↔ f m ∈ N' := iff.rfl
lemma comap_incl_eq_top : N₂.comap N.incl = ⊤ ↔ N ≤ N₂ :=
by simpa only [← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.coe_submodule_comap,
lie_submodule.incl_coe, lie_submodule.top_coe_submodule, submodule.comap_subtype_eq_top]
end lie_submodule
namespace lie_ideal
variables (f : L →ₗ⁅R⁆ L') (I I₂ : lie_ideal R L) (J : lie_ideal R L')
@[simp] lemma top_coe_lie_subalgebra : ((⊤ : lie_ideal R L) : lie_subalgebra R L) = ⊤ := rfl
/-- A morphism of Lie algebras `f : L → L'` pushes forward Lie ideals of `L` to Lie ideals of `L'`.
Note that unlike `lie_submodule.map`, we must take the `lie_span` of the image. Mathematically
this is because although `f` makes `L'` into a Lie module over `L`, in general the `L` submodules of
`L'` are not the same as the ideals of `L'`. -/
def map : lie_ideal R L' := lie_submodule.lie_span R L' $ (I : submodule R L).map (f : L →ₗ[R] L')
/-- A morphism of Lie algebras `f : L → L'` pulls back Lie ideals of `L'` to Lie ideals of `L`.
Note that `f` makes `L'` into a Lie module over `L` (turning `f` into a morphism of Lie modules)
and so this is a special case of `lie_submodule.comap` but we do not exploit this fact. -/
def comap : lie_ideal R L :=
{ lie_mem := λ x y h, by { suffices : ⁅f x, f y⁆ ∈ J, { simp [this], }, apply J.lie_mem h, },
..(J : submodule R L').comap (f : L →ₗ[R] L') }
@[simp] lemma map_coe_submodule (h : ↑(map f I) = f '' I) :
(map f I : submodule R L') = (I : submodule R L).map (f : L →ₗ[R] L') :=
by { rw [set_like.ext'_iff, lie_submodule.coe_to_submodule, h, submodule.map_coe], refl, }
@[simp] lemma comap_coe_submodule :
(comap f J : submodule R L) = (J : submodule R L').comap (f : L →ₗ[R] L') := rfl
lemma map_le : map f I ≤ J ↔ f '' I ⊆ J := lie_submodule.lie_span_le
variables {f I I₂ J}
lemma mem_map {x : L} (hx : x ∈ I) : f x ∈ map f I :=
by { apply lie_submodule.subset_lie_span, use x, exact ⟨hx, rfl⟩, }
@[simp] lemma mem_comap {x : L} : x ∈ comap f J ↔ f x ∈ J := iff.rfl
lemma map_le_iff_le_comap : map f I ≤ J ↔ I ≤ comap f J :=
by { rw map_le, exact set.image_subset_iff, }
variables (f)
lemma gc_map_comap : galois_connection (map f) (comap f) :=
λ I I', map_le_iff_le_comap
variables {f}
@[simp] lemma map_sup : (I ⊔ I₂).map f = I.map f ⊔ I₂.map f :=
(gc_map_comap f).l_sup
lemma map_comap_le : map f (comap f J) ≤ J :=
by { rw map_le_iff_le_comap, exact le_rfl, }
/-- See also `lie_ideal.map_comap_eq`. -/
lemma comap_map_le : I ≤ comap f (map f I) :=
by { rw ← map_le_iff_le_comap, exact le_rfl, }
@[mono] lemma map_mono : monotone (map f) :=
λ I₁ I₂ h,
by { rw set_like.le_def at h, apply lie_submodule.lie_span_mono (set.image_subset ⇑f h), }
@[mono] lemma comap_mono : monotone (comap f) :=
λ J₁ J₂ h, by { rw ← set_like.coe_subset_coe at h ⊢, exact set.preimage_mono h, }
lemma map_of_image (h : f '' I = J) : I.map f = J :=
begin
apply le_antisymm,
{ erw [lie_submodule.lie_span_le, submodule.map_coe, h], },
{ rw [← set_like.coe_subset_coe, ← h], exact lie_submodule.subset_lie_span, },
end
/-- Note that this is not a special case of `lie_submodule.subsingleton_of_bot`. Indeed, given
`I : lie_ideal R L`, in general the two lattices `lie_ideal R I` and `lie_submodule R L I` are
different (though the latter does naturally inject into the former).
In other words, in general, ideals of `I`, regarded as a Lie algebra in its own right, are not the
same as ideals of `L` contained in `I`. -/
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_bot : subsingleton (lie_ideal R ↥(⊥ : lie_ideal R L)) :=
begin
apply subsingleton_of_bot_eq_top,
ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw submodule.mem_bot at hx, subst hx,
simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, lie_submodule.mem_bot],
end
end lie_ideal
namespace lie_hom
variables (f : L →ₗ⁅R⁆ L') (I : lie_ideal R L) (J : lie_ideal R L')
/-- The kernel of a morphism of Lie algebras, as an ideal in the domain. -/
def ker : lie_ideal R L := lie_ideal.comap f ⊥
/-- The range of a morphism of Lie algebras as an ideal in the codomain. -/
def ideal_range : lie_ideal R L' := lie_submodule.lie_span R L' f.range
lemma ideal_range_eq_lie_span_range :
f.ideal_range = lie_submodule.lie_span R L' f.range := rfl
lemma ideal_range_eq_map :
f.ideal_range = lie_ideal.map f ⊤ :=
by { ext, simp only [ideal_range, range_eq_map], refl }
/-- The condition that the image of a morphism of Lie algebras is an ideal. -/
def is_ideal_morphism : Prop := (f.ideal_range : lie_subalgebra R L') = f.range
@[simp] lemma is_ideal_morphism_def :
f.is_ideal_morphism ↔ (f.ideal_range : lie_subalgebra R L') = f.range := iff.rfl
lemma is_ideal_morphism_iff :
f.is_ideal_morphism ↔ ∀ (x : L') (y : L), ∃ (z : L), ⁅x, f y⁆ = f z :=
begin
simp only [is_ideal_morphism_def, ideal_range_eq_lie_span_range,
← lie_subalgebra.coe_to_submodule_eq_iff, ← f.range.coe_to_submodule,
lie_ideal.coe_to_lie_subalgebra_to_submodule, lie_submodule.coe_lie_span_submodule_eq_iff,
lie_subalgebra.mem_coe_submodule, mem_range, exists_imp_distrib,
submodule.exists_lie_submodule_coe_eq_iff],
split,
{ intros h x y, obtain ⟨z, hz⟩ := h x (f y) y rfl, use z, exact hz.symm, },
{ intros h x y z hz, obtain ⟨w, hw⟩ := h x z, use w, rw [← hw, hz], },
end
lemma range_subset_ideal_range : (f.range : set L') ⊆ f.ideal_range := lie_submodule.subset_lie_span
lemma map_le_ideal_range : I.map f ≤ f.ideal_range :=
begin
rw f.ideal_range_eq_map,
exact lie_ideal.map_mono le_top,
end
lemma ker_le_comap : f.ker ≤ J.comap f := lie_ideal.comap_mono bot_le
@[simp] lemma ker_coe_submodule : (ker f : submodule R L) = (f : L →ₗ[R] L').ker := rfl
@[simp] lemma mem_ker {x : L} : x ∈ ker f ↔ f x = 0 :=
show x ∈ (f.ker : submodule R L) ↔ _,
by simp only [ker_coe_submodule, linear_map.mem_ker, coe_to_linear_map]
lemma mem_ideal_range {x : L} : f x ∈ ideal_range f :=
begin
rw ideal_range_eq_map,
exact lie_ideal.mem_map (lie_submodule.mem_top x)
end
@[simp] lemma mem_ideal_range_iff (h : is_ideal_morphism f) {y : L'} :
y ∈ ideal_range f ↔ ∃ (x : L), f x = y :=
begin
rw f.is_ideal_morphism_def at h,
rw [← lie_submodule.mem_coe, ← lie_ideal.coe_to_subalgebra, h, f.range_coe, set.mem_range],
end
lemma le_ker_iff : I ≤ f.ker ↔ ∀ x, x ∈ I → f x = 0 :=
begin
split; intros h x hx,
{ specialize h hx, rw mem_ker at h, exact h, },
{ rw mem_ker, apply h x hx, },
end
lemma ker_eq_bot : f.ker = ⊥ ↔ function.injective f :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, ker_coe_submodule, lie_submodule.bot_coe_submodule,
linear_map.ker_eq_bot, coe_to_linear_map]
@[simp] lemma range_coe_submodule : (f.range : submodule R L') = (f : L →ₗ[R] L').range := rfl
lemma range_eq_top : f.range = ⊤ ↔ function.surjective f :=
begin
rw [← lie_subalgebra.coe_to_submodule_eq_iff, range_coe_submodule,
lie_subalgebra.top_coe_submodule],
exact linear_map.range_eq_top,
end
@[simp] lemma ideal_range_eq_top_of_surjective (h : function.surjective f) : f.ideal_range = ⊤ :=
begin
rw ← f.range_eq_top at h,
rw [ideal_range_eq_lie_span_range, h, ← lie_subalgebra.coe_to_submodule,
← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.top_coe_submodule,
lie_subalgebra.top_coe_submodule, lie_submodule.coe_lie_span_submodule_eq_iff],
use ⊤,
exact lie_submodule.top_coe_submodule,
end
lemma is_ideal_morphism_of_surjective (h : function.surjective f) : f.is_ideal_morphism :=
by rw [is_ideal_morphism_def, f.ideal_range_eq_top_of_surjective h, f.range_eq_top.mpr h,
lie_ideal.top_coe_lie_subalgebra]
end lie_hom
namespace lie_ideal
variables {f : L →ₗ⁅R⁆ L'} {I : lie_ideal R L} {J : lie_ideal R L'}
@[simp] lemma map_eq_bot_iff : I.map f = ⊥ ↔ I ≤ f.ker :=
by { rw ← le_bot_iff, exact lie_ideal.map_le_iff_le_comap }
lemma coe_map_of_surjective (h : function.surjective f) :
(I.map f : submodule R L') = (I : submodule R L).map (f : L →ₗ[R] L') :=
begin
let J : lie_ideal R L' :=
{ lie_mem := λ x y hy,
begin
have hy' : ∃ (x : L), x ∈ I ∧ f x = y, { simpa [hy], },
obtain ⟨z₂, hz₂, rfl⟩ := hy',
obtain ⟨z₁, rfl⟩ := h x,
simp only [lie_hom.coe_to_linear_map, set_like.mem_coe, set.mem_image,
lie_submodule.mem_coe_submodule, submodule.mem_carrier, submodule.map_coe],
use ⁅z₁, z₂⁆,
exact ⟨I.lie_mem hz₂, f.map_lie z₁ z₂⟩,
end,
..(I : submodule R L).map (f : L →ₗ[R] L'), },
erw lie_submodule.coe_lie_span_submodule_eq_iff,
use J,
apply lie_submodule.coe_to_submodule_mk,
end
lemma mem_map_of_surjective {y : L'} (h₁ : function.surjective f) (h₂ : y ∈ I.map f) :
∃ (x : I), f x = y :=
begin
rw [← lie_submodule.mem_coe_submodule, coe_map_of_surjective h₁, submodule.mem_map] at h₂,
obtain ⟨x, hx, rfl⟩ := h₂,
use ⟨x, hx⟩,
refl,
end
lemma bot_of_map_eq_bot {I : lie_ideal R L} (h₁ : function.injective f) (h₂ : I.map f = ⊥) :
I = ⊥ :=
begin
rw ← f.ker_eq_bot at h₁, change comap f ⊥ = ⊥ at h₁,
rw [eq_bot_iff, map_le_iff_le_comap, h₁] at h₂,
rw eq_bot_iff, exact h₂,
end
/-- Given two nested Lie ideals `I₁ ⊆ I₂`, the inclusion `I₁ ↪ I₂` is a morphism of Lie algebras. -/
def hom_of_le {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) : I₁ →ₗ⁅R⁆ I₂ :=
{ map_lie' := λ x y, rfl,
..submodule.of_le (show I₁.to_submodule ≤ I₂.to_submodule, from h), }
@[simp] lemma coe_hom_of_le {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) (x : I₁) :
(hom_of_le h x : L) = x := rfl
lemma hom_of_le_apply {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) (x : I₁) :
hom_of_le h x = ⟨x.1, h x.2⟩ := rfl
lemma hom_of_le_injective {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) :
function.injective (hom_of_le h) :=
λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe,
subtype.val_eq_coe]
@[simp] lemma map_sup_ker_eq_map : lie_ideal.map f (I ⊔ f.ker) = lie_ideal.map f I :=
begin
suffices : lie_ideal.map f (I ⊔ f.ker) ≤ lie_ideal.map f I,
{ exact le_antisymm this (lie_ideal.map_mono le_sup_left), },
apply lie_submodule.lie_span_mono,
rintros x ⟨y, hy₁, hy₂⟩, rw ← hy₂,
erw lie_submodule.mem_sup at hy₁, obtain ⟨z₁, hz₁, z₂, hz₂, hy⟩ := hy₁, rw ← hy,
rw [f.coe_to_linear_map, f.map_add, f.mem_ker.mp hz₂, add_zero], exact ⟨z₁, hz₁, rfl⟩,
end
@[simp] lemma map_comap_eq (h : f.is_ideal_morphism) : map f (comap f J) = f.ideal_range ⊓ J :=
begin
apply le_antisymm,
{ rw le_inf_iff, exact ⟨f.map_le_ideal_range _, map_comap_le⟩, },
{ rw f.is_ideal_morphism_def at h,
rw [← set_like.coe_subset_coe, lie_submodule.inf_coe, ← coe_to_subalgebra, h],
rintros y ⟨⟨x, h₁⟩, h₂⟩, rw ← h₁ at h₂ ⊢, exact mem_map h₂, },
end
@[simp] lemma comap_map_eq (h : ↑(map f I) = f '' I) : comap f (map f I) = I ⊔ f.ker :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, comap_coe_submodule, I.map_coe_submodule f h,
lie_submodule.sup_coe_to_submodule, f.ker_coe_submodule, submodule.comap_map_eq]
variables (f I J)
/-- Regarding an ideal `I` as a subalgebra, the inclusion map into its ambient space is a morphism
of Lie algebras. -/
def incl : I →ₗ⁅R⁆ L := (I : lie_subalgebra R L).incl
@[simp] lemma incl_range : I.incl.range = I := (I : lie_subalgebra R L).incl_range
@[simp] lemma incl_apply (x : I) : I.incl x = x := rfl
@[simp] lemma incl_coe : (I.incl : I →ₗ[R] L) = (I : submodule R L).subtype := rfl
@[simp] lemma comap_incl_self : comap I.incl I = ⊤ :=
by { rw ← lie_submodule.coe_to_submodule_eq_iff, exact submodule.comap_subtype_self _, }
@[simp] lemma ker_incl : I.incl.ker = ⊥ :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, I.incl.ker_coe_submodule,
lie_submodule.bot_coe_submodule, incl_coe, submodule.ker_subtype]
@[simp] lemma incl_ideal_range : I.incl.ideal_range = I :=
begin
rw [lie_hom.ideal_range_eq_lie_span_range, ← lie_subalgebra.coe_to_submodule,
← lie_submodule.coe_to_submodule_eq_iff, incl_range, coe_to_lie_subalgebra_to_submodule,
lie_submodule.coe_lie_span_submodule_eq_iff],
use I,
end
lemma incl_is_ideal_morphism : I.incl.is_ideal_morphism :=
begin
rw [I.incl.is_ideal_morphism_def, incl_ideal_range],
exact (I : lie_subalgebra R L).incl_range.symm,
end
end lie_ideal
end lie_submodule_map_and_comap
namespace lie_module_hom
variables {R : Type u} {L : Type v} {M : Type w} {N : Type w₁}
variables [comm_ring R] [lie_ring L] [lie_algebra R L]
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N]
variables (f : M →ₗ⁅R,L⁆ N)
/-- The kernel of a morphism of Lie algebras, as an ideal in the domain. -/
def ker : lie_submodule R L M := lie_submodule.comap f ⊥
@[simp] lemma ker_coe_submodule : (f.ker : submodule R M) = (f : M →ₗ[R] N).ker := rfl
lemma ker_eq_bot : f.ker = ⊥ ↔ function.injective f :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, ker_coe_submodule, lie_submodule.bot_coe_submodule,
linear_map.ker_eq_bot, coe_to_linear_map]
variables {f}
@[simp] lemma mem_ker (m : M) : m ∈ f.ker ↔ f m = 0 := iff.rfl
@[simp] lemma ker_id : (lie_module_hom.id : M →ₗ⁅R,L⁆ M).ker = ⊥ := rfl
@[simp] lemma comp_ker_incl : f.comp f.ker.incl = 0 :=
by { ext ⟨m, hm⟩, exact (mem_ker m).mp hm, }
lemma le_ker_iff_map (M' : lie_submodule R L M) :
M' ≤ f.ker ↔ lie_submodule.map f M' = ⊥ :=
by rw [ker, eq_bot_iff, lie_submodule.map_le_iff_le_comap]
variables (f)
/-- The range of a morphism of Lie modules `f : M → N` is a Lie submodule of `N`.
See Note [range copy pattern]. -/
def range : lie_submodule R L N :=
(lie_submodule.map f ⊤).copy (set.range f) set.image_univ.symm
@[simp] lemma coe_range : (f.range : set N) = set.range f := rfl
@[simp] lemma coe_submodule_range : (f.range : submodule R N) = (f : M →ₗ[R] N).range := rfl
@[simp] lemma mem_range (n : N) : n ∈ f.range ↔ ∃ m, f m = n :=
iff.rfl
lemma map_top : lie_submodule.map f ⊤ = f.range :=
by { ext, simp [lie_submodule.mem_map], }
end lie_module_hom
namespace lie_submodule
variables {R : Type u} {L : Type v} {M : Type w}
variables [comm_ring R] [lie_ring L] [lie_algebra R L]
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables (N : lie_submodule R L M)
@[simp] lemma ker_incl : N.incl.ker = ⊥ :=
by simp [← lie_submodule.coe_to_submodule_eq_iff]
@[simp] lemma range_incl : N.incl.range = N :=
by simp [← lie_submodule.coe_to_submodule_eq_iff]
@[simp] lemma comap_incl_self : comap N.incl N = ⊤ :=
by simp [← lie_submodule.coe_to_submodule_eq_iff]
end lie_submodule
section top_equiv
variables {R : Type u} {L : Type v}
variables [comm_ring R] [lie_ring L] [lie_algebra R L]
/-- The natural equivalence between the 'top' Lie subalgebra and the enclosing Lie algebra.
This is the Lie subalgebra version of `submodule.top_equiv`. -/
def lie_subalgebra.top_equiv : (⊤ : lie_subalgebra R L) ≃ₗ⁅R⁆ L :=
{ inv_fun := λ x, ⟨x, set.mem_univ x⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, rfl,
..(⊤ : lie_subalgebra R L).incl, }
@[simp] lemma lie_subalgebra.top_equiv_apply (x : (⊤ : lie_subalgebra R L)) :
lie_subalgebra.top_equiv x = x := rfl
/-- The natural equivalence between the 'top' Lie ideal and the enclosing Lie algebra.
This is the Lie ideal version of `submodule.top_equiv`. -/
def lie_ideal.top_equiv : (⊤ : lie_ideal R L) ≃ₗ⁅R⁆ L :=
lie_subalgebra.top_equiv
@[simp] lemma lie_ideal.top_equiv_apply (x : (⊤ : lie_ideal R L)) :
lie_ideal.top_equiv x = x := rfl
end top_equiv
|
9b984029aa7a69eb0642fad993c7a490a649cf02 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/Compiler/IR/Boxing.lean | fe87373661107bccda71e46e7340ac1f9836de69 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 13,221 | 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.Runtime
import Lean.Compiler.ClosedTermCache
import Lean.Compiler.ExternAttr
import Lean.Compiler.IR.Basic
import Lean.Compiler.IR.CompilerM
import Lean.Compiler.IR.FreeVars
import Lean.Compiler.IR.ElimDeadVars
namespace Lean.IR.ExplicitBoxing
/-!
Add explicit boxing and unboxing instructions.
Recall that the Lean to λ_pure compiler produces code without these instructions.
Assumptions:
- This transformation is applied before explicit RC instructions (`inc`, `dec`) are inserted.
- This transformation is applied before `FnBody.case` has been simplified and `Alt.default` is used.
Reason: if there is no `Alt.default` branch, then we can decide whether `x` at `FnBody.case x alts` is an
enumeration type by simply inspecting the `CtorInfo` values at `alts`.
- This transformation is applied before lower level optimizations are applied which use
`Expr.isShared`, `Expr.isTaggedPtr`, and `FnBody.set`.
- This transformation is applied after `reset` and `reuse` instructions have been added.
Reason: `resetreuse.lean` ignores `box` and `unbox` instructions.
-/
open Std (AssocList)
def mkBoxedName (n : Name) : Name :=
Name.mkStr n "_boxed"
def isBoxedName (name : Name) : Bool :=
name matches .str _ "_boxed"
abbrev N := StateM Nat
private def N.mkFresh : N VarId :=
modifyGet fun n => ({ idx := n }, n + 1)
def requiresBoxedVersion (env : Environment) (decl : Decl) : Bool :=
let ps := decl.params
(ps.size > 0 && (decl.resultType.isScalar || ps.any (fun p => p.ty.isScalar || p.borrow) || isExtern env decl.name))
|| ps.size > closureMaxArgs
def mkBoxedVersionAux (decl : Decl) : N Decl := do
let ps := decl.params
let qs ← ps.mapM fun _ => do let x ← N.mkFresh; pure { x := x, ty := IRType.object, borrow := false : Param }
let (newVDecls, xs) ← qs.size.foldM (init := (#[], #[])) fun i (newVDecls, xs) => do
let p := ps[i]!
let q := qs[i]!
if !p.ty.isScalar then
pure (newVDecls, xs.push (Arg.var q.x))
else
let x ← N.mkFresh
pure (newVDecls.push (FnBody.vdecl x p.ty (Expr.unbox q.x) default), xs.push (Arg.var x))
let r ← N.mkFresh
let newVDecls := newVDecls.push (FnBody.vdecl r decl.resultType (Expr.fap decl.name xs) default)
let body ← if !decl.resultType.isScalar then
pure <| reshape newVDecls (FnBody.ret (Arg.var r))
else
let newR ← N.mkFresh
let newVDecls := newVDecls.push (FnBody.vdecl newR IRType.object (Expr.box decl.resultType r) default)
pure <| reshape newVDecls (FnBody.ret (Arg.var newR))
return Decl.fdecl (mkBoxedName decl.name) qs IRType.object body decl.getInfo
def mkBoxedVersion (decl : Decl) : Decl :=
(mkBoxedVersionAux decl).run' 1
def addBoxedVersions (env : Environment) (decls : Array Decl) : Array Decl :=
let boxedDecls := decls.foldl (init := #[]) fun newDecls decl =>
if requiresBoxedVersion env decl then newDecls.push (mkBoxedVersion decl) else newDecls
decls ++ boxedDecls
/-- Infer scrutinee type using `case` alternatives.
This can be done whenever `alts` does not contain an `Alt.default _` value. -/
def getScrutineeType (alts : Array Alt) : IRType :=
let isScalar :=
alts.size > 1 && -- Recall that we encode Unit and PUnit using `object`.
alts.all fun
| Alt.ctor c _ => c.isScalar
| Alt.default _ => false
match isScalar with
| false => IRType.object
| true =>
let n := alts.size
if n < 256 then IRType.uint8
else if n < 65536 then IRType.uint16
else if n < 4294967296 then IRType.uint32
else IRType.object -- in practice this should be unreachable
def eqvTypes (t₁ t₂ : IRType) : Bool :=
(t₁.isScalar == t₂.isScalar) && (!t₁.isScalar || t₁ == t₂)
structure BoxingContext where
f : FunId := default
localCtx : LocalContext := {}
resultType : IRType := IRType.irrelevant
decls : Array Decl
env : Environment
structure BoxingState where
nextIdx : Index
/-- We create auxiliary declarations when boxing constant and literals.
The idea is to avoid code such as
```
let x1 := Uint64.inhabited;
let x2 := box x1;
...
```
We currently do not cache these declarations in an environment extension, but
we use auxDeclCache to avoid creating equivalent auxiliary declarations more than once when
processing the same IR declaration.
-/
auxDecls : Array Decl := #[]
auxDeclCache : AssocList FnBody Expr := Std.AssocList.empty
nextAuxId : Nat := 1
abbrev M := ReaderT BoxingContext (StateT BoxingState Id)
private def M.mkFresh : M VarId := do
let oldS ← getModify fun s => { s with nextIdx := s.nextIdx + 1 }
pure { idx := oldS.nextIdx }
def getEnv : M Environment := BoxingContext.env <$> read
def getLocalContext : M LocalContext := BoxingContext.localCtx <$> read
def getResultType : M IRType := BoxingContext.resultType <$> read
def getVarType (x : VarId) : M IRType := do
let localCtx ← getLocalContext
match localCtx.getType x with
| some t => pure t
| none => pure IRType.object -- unreachable, we assume the code is well formed
def getJPParams (j : JoinPointId) : M (Array Param) := do
let localCtx ← getLocalContext
match localCtx.getJPParams j with
| some ys => pure ys
| none => pure #[] -- unreachable, we assume the code is well formed
def getDecl (fid : FunId) : M Decl := do
let ctx ← read
match findEnvDecl' ctx.env fid ctx.decls with
| some decl => pure decl
| none => pure default -- unreachable if well-formed
@[inline] def withParams {α : Type} (xs : Array Param) (k : M α) : M α :=
withReader (fun ctx => { ctx with localCtx := ctx.localCtx.addParams xs }) k
@[inline] def withVDecl {α : Type} (x : VarId) (ty : IRType) (v : Expr) (k : M α) : M α :=
withReader (fun ctx => { ctx with localCtx := ctx.localCtx.addLocal x ty v }) k
@[inline] def withJDecl {α : Type} (j : JoinPointId) (xs : Array Param) (v : FnBody) (k : M α) : M α :=
withReader (fun ctx => { ctx with localCtx := ctx.localCtx.addJP j xs v }) k
/-- If `x` declaration is of the form `x := Expr.lit _` or `x := Expr.fap c #[]`,
and `x`'s type is not cheap to box (e.g., it is `UInt64), then return its value. -/
private def isExpensiveConstantValueBoxing (x : VarId) (xType : IRType) : M (Option Expr) :=
if !xType.isScalar then
return none -- We assume unboxing is always cheap
else match xType with
| IRType.uint8 => return none
| IRType.uint16 => return none
| _ => do
let localCtx ← getLocalContext
match localCtx.getValue x with
| some val =>
match val with
| Expr.lit _ => return some val
| Expr.fap _ args => return if args.size == 0 then some val else none
| _ => return none
| _ => return none
/-- Auxiliary function used by castVarIfNeeded.
It is used when the expected type does not match `xType`.
If `xType` is scalar, then we need to "box" it. Otherwise, we need to "unbox" it. -/
def mkCast (x : VarId) (xType : IRType) (expectedType : IRType) : M Expr := do
match (← isExpensiveConstantValueBoxing x xType) with
| some v => do
let ctx ← read
let s ← get
/- Create auxiliary FnBody
```
let x_1 : xType := v;
let x_2 : expectedType := Expr.box xType x_1;
ret x_2
```
-/
let body : FnBody :=
FnBody.vdecl { idx := 1 } xType v $
FnBody.vdecl { idx := 2 } expectedType (Expr.box xType { idx := 1 }) $
FnBody.ret (mkVarArg { idx := 2 })
match s.auxDeclCache.find? body with
| some v => pure v
| none => do
let auxName := ctx.f ++ ((`_boxed_const).appendIndexAfter s.nextAuxId)
let auxConst := Expr.fap auxName #[]
let auxDecl := Decl.fdecl auxName #[] expectedType body {}
modify fun s => { s with
auxDecls := s.auxDecls.push auxDecl
auxDeclCache := s.auxDeclCache.cons body auxConst
nextAuxId := s.nextAuxId + 1
}
pure auxConst
| none => pure $ if xType.isScalar then Expr.box xType x else Expr.unbox x
@[inline] def castVarIfNeeded (x : VarId) (expected : IRType) (k : VarId → M FnBody) : M FnBody := do
let xType ← getVarType x
if eqvTypes xType expected then
k x
else
let y ← M.mkFresh
let v ← mkCast x xType expected
FnBody.vdecl y expected v <$> k y
@[inline] def castArgIfNeeded (x : Arg) (expected : IRType) (k : Arg → M FnBody) : M FnBody :=
match x with
| Arg.var x => castVarIfNeeded x expected (fun x => k (Arg.var x))
| _ => k x
def castArgsIfNeededAux (xs : Array Arg) (typeFromIdx : Nat → IRType) : M (Array Arg × Array FnBody) := do
let mut xs' := #[]
let mut bs := #[]
let mut i := 0
for x in xs do
let expected := typeFromIdx i
match x with
| Arg.irrelevant =>
xs' := xs'.push x
| Arg.var x =>
let xType ← getVarType x
if eqvTypes xType expected then
xs' := xs'.push (Arg.var x)
else
let y ← M.mkFresh
let v ← mkCast x xType expected
let b := FnBody.vdecl y expected v FnBody.nil
xs' := xs'.push (Arg.var y)
bs := bs.push b
i := i + 1
return (xs', bs)
@[inline] def castArgsIfNeeded (xs : Array Arg) (ps : Array Param) (k : Array Arg → M FnBody) : M FnBody := do
let (ys, bs) ← castArgsIfNeededAux xs fun i => ps[i]!.ty
let b ← k ys
pure (reshape bs b)
@[inline] def boxArgsIfNeeded (xs : Array Arg) (k : Array Arg → M FnBody) : M FnBody := do
let (ys, bs) ← castArgsIfNeededAux xs (fun _ => IRType.object)
let b ← k ys
pure (reshape bs b)
def unboxResultIfNeeded (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : M FnBody := do
if ty.isScalar then
let y ← M.mkFresh
return FnBody.vdecl y IRType.object e (FnBody.vdecl x ty (Expr.unbox y) b)
else
return FnBody.vdecl x ty e b
def castResultIfNeeded (x : VarId) (ty : IRType) (e : Expr) (eType : IRType) (b : FnBody) : M FnBody := do
if eqvTypes ty eType then
return FnBody.vdecl x ty e b
else
let y ← M.mkFresh
let v ← mkCast y eType ty
return FnBody.vdecl y eType e (FnBody.vdecl x ty v b)
def visitVDeclExpr (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : M FnBody :=
match e with
| Expr.ctor c ys =>
if c.isScalar && ty.isScalar then
return FnBody.vdecl x ty (Expr.lit (LitVal.num c.cidx)) b
else
boxArgsIfNeeded ys fun ys => return FnBody.vdecl x ty (Expr.ctor c ys) b
| Expr.reuse w c u ys =>
boxArgsIfNeeded ys fun ys => return FnBody.vdecl x ty (Expr.reuse w c u ys) b
| Expr.fap f ys => do
let decl ← getDecl f
castArgsIfNeeded ys decl.params fun ys =>
castResultIfNeeded x ty (Expr.fap f ys) decl.resultType b
| Expr.pap f ys => do
let env ← getEnv
let decl ← getDecl f
let f := if requiresBoxedVersion env decl then mkBoxedName f else f
boxArgsIfNeeded ys fun ys => return FnBody.vdecl x ty (Expr.pap f ys) b
| Expr.ap f ys =>
boxArgsIfNeeded ys fun ys =>
unboxResultIfNeeded x ty (Expr.ap f ys) b
| _ =>
return FnBody.vdecl x ty e b
partial def visitFnBody : FnBody → M FnBody
| FnBody.vdecl x t v b => do
let b ← withVDecl x t v (visitFnBody b)
visitVDeclExpr x t v b
| FnBody.jdecl j xs v b => do
let v ← withParams xs (visitFnBody v)
let b ← withJDecl j xs v (visitFnBody b)
return FnBody.jdecl j xs v b
| FnBody.uset x i y b => do
let b ← visitFnBody b
castVarIfNeeded y IRType.usize fun y =>
return FnBody.uset x i y b
| FnBody.sset x i o y ty b => do
let b ← visitFnBody b
castVarIfNeeded y ty fun y =>
return FnBody.sset x i o y ty b
| FnBody.mdata d b =>
FnBody.mdata d <$> visitFnBody b
| FnBody.case tid x _ alts => do
let expected := getScrutineeType alts
let alts ← alts.mapM fun alt => alt.mmodifyBody visitFnBody
castVarIfNeeded x expected fun x => do
return FnBody.case tid x expected alts
| FnBody.ret x => do
let expected ← getResultType
castArgIfNeeded x expected (fun x => return FnBody.ret x)
| FnBody.jmp j ys => do
let ps ← getJPParams j
castArgsIfNeeded ys ps fun ys => return FnBody.jmp j ys
| other =>
pure other
def run (env : Environment) (decls : Array Decl) : Array Decl :=
let ctx : BoxingContext := { decls := decls, env := env }
let decls := decls.foldl (init := #[]) fun newDecls decl =>
match decl with
| .fdecl (f := f) (xs := xs) (type := t) (body := b) .. =>
let nextIdx := decl.maxIndex + 1
let (b, s) := (withParams xs (visitFnBody b) { ctx with f := f, resultType := t }).run { nextIdx := nextIdx }
let newDecls := newDecls ++ s.auxDecls
let newDecl := decl.updateBody! b
let newDecl := newDecl.elimDead
newDecls.push newDecl
| d => newDecls.push d
addBoxedVersions env decls
end ExplicitBoxing
def explicitBoxing (decls : Array Decl) : CompilerM (Array Decl) := do
let env ← getEnv
return ExplicitBoxing.run env decls
end Lean.IR
|
74bcb64ac4578fd0a3a72905280a1aaf953d07b4 | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /library/init/wf.lean | 6fb26fef5b299af52c096f0ddc0c2b33ab072ae5 | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 7,086 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import init.data.nat.basic init.data.prod
universes u v
inductive acc {α : Sort u} (r : α → α → Prop) : α → Prop
| intro : ∀ x, (∀ y, r y x → acc y) → acc x
namespace acc
variables {α : Sort u} {r : α → α → Prop}
def inv {x y : α} (h₁ : acc r x) (h₂ : r y x) : acc r y :=
acc.rec_on h₁ (λ x₁ ac₁ ih h₂, ac₁ y h₂) h₂
end acc
inductive well_founded {α : Sort u} (r : α → α → Prop) : Prop
| intro : (∀ a, acc r a) → well_founded
class has_well_founded (α : Sort u) : Type u :=
(r : α → α → Prop) (wf : well_founded r)
namespace well_founded
def apply {α : Sort u} {r : α → α → Prop} (wf : well_founded r) : ∀ a, acc r a :=
take a, well_founded.rec_on wf (λ p, p) a
section
parameters {α : Sort u} {r : α → α → Prop}
local infix `≺`:50 := r
parameter hwf : well_founded r
lemma recursion {C : α → Sort v} (a : α) (h : Π x, (Π y, y ≺ x → C y) → C x) : C a :=
acc.rec_on (apply hwf a) (λ x₁ ac₁ ih, h x₁ ih)
lemma induction {C : α → Prop} (a : α) (h : ∀ x, (∀ y, y ≺ x → C y) → C x) : C a :=
recursion a h
variable {C : α → Sort v}
variable F : Π x, (Π y, y ≺ x → C y) → C x
def fix_F (x : α) (a : acc r x) : C x :=
acc.rec_on a (λ x₁ ac₁ ih, F x₁ ih)
lemma fix_F_eq (x : α) (acx : acc r x) :
fix_F F x acx = F x (λ (y : α) (p : y ≺ x), fix_F F y (acc.inv acx p)) :=
acc.drec (λ x r ih, rfl) acx
end
variables {α : Sort u} {C : α → Sort v} {r : α → α → Prop}
-- Well-founded fixpoint
def fix (hwf : well_founded r) (F : Π x, (Π y, r y x → C y) → C x) (x : α) : C x :=
fix_F F x (apply hwf x)
-- Well-founded fixpoint satisfies fixpoint equation
lemma fix_eq (hwf : well_founded r) (F : Π x, (Π y, r y x → C y) → C x) (x : α) :
fix hwf F x = F x (λ y h, fix hwf F y) :=
fix_F_eq F x (apply hwf x)
end well_founded
open well_founded
-- Empty relation is well-founded
def empty_wf {α : Sort u} : well_founded empty_relation :=
well_founded.intro (λ (a : α),
acc.intro a (λ (b : α) (lt : false), false.rec _ lt))
-- Subrelation of a well-founded relation is well-founded
namespace subrelation
section
parameters {α : Sort u} {r Q : α → α → Prop}
parameters (h₁ : subrelation Q r)
parameters (h₂ : well_founded r)
def accessible {a : α} (ac : acc r a) : acc Q a :=
acc.rec_on ac (λ x ax ih,
acc.intro x (λ (y : α) (lt : Q y x), ih y (h₁ lt)))
def wf : well_founded Q :=
⟨λ a, accessible (apply h₂ a)⟩
end
end subrelation
-- The inverse image of a well-founded relation is well-founded
namespace inv_image
section
parameters {α : Sort u} {β : Sort v} {r : β → β → Prop}
parameters (f : α → β)
parameters (h : well_founded r)
private def acc_aux {b : β} (ac : acc r b) : ∀ (x : α), f x = b → acc (inv_image r f) x :=
acc.rec_on ac (λ x acx ih z e,
acc.intro z (λ y lt, eq.rec_on e (λ acx ih, ih (f y) lt y rfl) acx ih))
def accessible {a : α} (ac : acc r (f a)) : acc (inv_image r f) a :=
acc_aux ac a rfl
def wf : well_founded (inv_image r f) :=
⟨λ a, accessible (apply h (f a))⟩
end
end inv_image
-- The transitive closure of a well-founded relation is well-founded
namespace tc
section
parameters {α : Sort u} {r : α → α → Prop}
local notation `r⁺` := tc r
def accessible {z : α} (ac : acc r z) : acc (tc r) z :=
acc.rec_on ac (λ x acx ih,
acc.intro x (λ y rel,
tc.rec_on rel
(λ a b rab acx ih, ih a rab)
(λ a b c rab rbc ih₁ ih₂ acx ih, acc.inv (ih₂ acx ih) rab)
acx ih))
def wf (h : well_founded r) : well_founded r⁺ :=
⟨λ a, accessible (apply h a)⟩
end
end tc
-- less-than is well-founded
def nat.lt_wf : well_founded nat.lt :=
⟨nat.rec
(acc.intro 0 (λ n h, absurd h (nat.not_lt_zero n)))
(λ n ih, acc.intro (nat.succ n) (λ m h,
or.elim (nat.eq_or_lt_of_le (nat.le_of_succ_le_succ h))
(λ e, eq.substr e ih) (acc.inv ih)))⟩
def measure {α : Sort u} : (α → ℕ) → α → α → Prop :=
inv_image (<)
def measure_wf {α : Sort u} (f : α → ℕ) : well_founded (measure f) :=
inv_image.wf f nat.lt_wf
def sizeof_measure (α : Sort u) [has_sizeof α] : α → α → Prop :=
measure sizeof
def sizeof_measure_wf (α : Sort u) [has_sizeof α] : well_founded (sizeof_measure α) :=
measure_wf sizeof
instance has_well_founded_of_has_sizeof (α : Sort u) [has_sizeof α] : has_well_founded α :=
{r := sizeof_measure α, wf := sizeof_measure_wf α}
namespace prod
open well_founded
section
variables {α : Type u} {β : Type v}
variable (ra : α → α → Prop)
variable (rb : β → β → Prop)
-- Lexicographical order based on ra and rb
inductive lex : α × β → α × β → Prop
| left : ∀ {a₁} b₁ {a₂} b₂, ra a₁ a₂ → lex (a₁, b₁) (a₂, b₂)
| right : ∀ a {b₁ b₂}, rb b₁ b₂ → lex (a, b₁) (a, b₂)
-- relational product based on ra and rb
inductive rprod : α × β → α × β → Prop
| intro : ∀ {a₁ b₁ a₂ b₂}, ra a₁ a₂ → rb b₁ b₂ → rprod (a₁, b₁) (a₂, b₂)
end
section
parameters {α : Type u} {β : Type v}
parameters {ra : α → α → Prop} {rb : β → β → Prop}
local infix `≺`:50 := lex ra rb
def lex_accessible {a} (aca : acc ra a) (acb : ∀ b, acc rb b): ∀ b, acc (lex ra rb) (a, b) :=
acc.rec_on aca (λ xa aca iha b,
acc.rec_on (acb b) (λ xb acb ihb,
acc.intro (xa, xb) (λ p lt,
have aux : xa = xa → xb = xb → acc (lex ra rb) p, from
@prod.lex.rec_on α β ra rb (λ p₁ p₂, fst p₂ = xa → snd p₂ = xb → acc (lex ra rb) p₁)
p (xa, xb) lt
(λ a₁ b₁ a₂ b₂ h (eq₂ : a₂ = xa) (eq₃ : b₂ = xb), iha a₁ (eq.rec_on eq₂ h) b₁)
(λ a b₁ b₂ h (eq₂ : a = xa) (eq₃ : b₂ = xb), eq.rec_on eq₂.symm (ihb b₁ (eq.rec_on eq₃ h))),
aux rfl rfl)))
-- The lexicographical order of well founded relations is well-founded
def lex_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (lex ra rb) :=
⟨λ p, cases_on p (λ a b, lex_accessible (apply ha a) (well_founded.apply hb) b)⟩
-- relational product is a subrelation of the lex
def rprod_sub_lex : ∀ a b, rprod ra rb a b → lex ra rb a b :=
λ a b h, prod.rprod.rec_on h (λ a₁ b₁ a₂ b₂ h₁ h₂, lex.left rb b₁ b₂ h₁)
-- The relational product of well founded relations is well-founded
def rprod_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (rprod ra rb) :=
subrelation.wf (rprod_sub_lex) (lex_wf ha hb)
end
instance has_well_founded {α : Type u} {β : Type v} [s₁ : has_well_founded α] [s₂ : has_well_founded β] : has_well_founded (α × β) :=
{r := lex s₁.r s₂.r, wf := lex_wf s₁.wf s₂.wf}
end prod
|
3bd70e6c418730f34fccf6cc480ade07890bc305 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebra/lie/engel.lean | b27b354fdaca867f744833ae689d2df28ad57625 | [
"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,629 | lean | /-
Copyright (c) 2022 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.nilpotent
import algebra.lie.cartan_subalgebra
/-!
# Engel's theorem
This file contains a proof of Engel's theorem providing necessary and sufficient conditions for Lie
algebras and Lie modules to be nilpotent.
The key result `lie_module.is_nilpotent_iff_forall` says that if `M` is a Lie module of a
Noetherian Lie algebra `L`, then `M` is nilpotent iff the image of `L → End(M)` consists of
nilpotent elements. In the special case that we have the adjoint representation `M = L`, this says
that a Lie algebra is nilpotent iff `ad x : End(L)` is nilpotent for all `x : L`.
Engel's theorem is true for any coefficients (i.e., it is really a theorem about Lie rings) and so
we work with coefficients in any commutative ring `R` throughout.
On the other hand, Engel's theorem is not true for infinite-dimensional Lie algebras and so a
finite-dimensionality assumption is required. We prove the theorem subject to the the assumption
that the Lie algebra is Noetherian as an `R`-module, though actually we only need the slightly
weaker property that the relation `>` is well-founded on the complete lattice of Lie subalgebras.
## Remarks about the proof
Engel's theorem is usually proved in the special case that the coefficients are a field, and uses
an inductive argument on the dimension of the Lie algebra. One begins by choosing either a maximal
proper Lie subalgebra (in some proofs) or a maximal nilpotent Lie subalgebra (in other proofs, at
the cost of obtaining a weaker end result).
Since we work with general coefficients, we cannot induct on dimension and an alternate approach
must be taken. The key ingredient is the concept of nilpotency, not just for Lie algebras, but for
Lie modules. Using this concept, we define an _Engelian Lie algebra_ `lie_algebra.is_engelian` to
be one for which a Lie module is nilpotent whenever the action consists of nilpotent endomorphisms.
The argument then proceeds by selecting a maximal Engelian Lie subalgebra and showing that it cannot
be proper.
The first part of the traditional statement of Engel's theorem consists of the statement that if `M`
is a non-trivial `R`-module and `L ⊆ End(M)` is a finite-dimensional Lie subalgebra of nilpotent
elements, then there exists a non-zero element `m : M` that is annihilated by every element of `L`.
This follows trivially from the result established here `lie_module.is_nilpotent_iff_forall`, that
`M` is a nilpotent Lie module over `L`, since the last non-zero term in the lower central series
will consist of such elements `m` (see: `lie_module.nontrivial_max_triv_of_is_nilpotent`). It seems
that this result has not previously been established at this level of generality.
The second part of the traditional statement of Engel's theorem concerns nilpotency of the Lie
algebra and a proof of this for general coefficients appeared in the literature as long ago
[as 1937](zorn1937). This also follows trivially from `lie_module.is_nilpotent_iff_forall` simply by
taking `M = L`.
It is pleasing that the two parts of the traditional statements of Engel's theorem are thus unified
into a single statement about nilpotency of Lie modules. This is not usually emphasised.
## Main definitions
* `lie_algebra.is_engelian`
* `lie_algebra.is_engelian_of_is_noetherian`
* `lie_module.is_nilpotent_iff_forall`
* `lie_algebra.is_nilpotent_iff_forall`
-/
universes u₁ u₂ u₃ u₄
variables {R : Type u₁} {L : Type u₂} {L₂ : Type u₃} {M : Type u₄}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L₂] [lie_algebra R L₂]
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
include R L
namespace lie_submodule
open lie_module
variables {I : lie_ideal R L} {x : L} (hxI : (R ∙ x) ⊔ I = ⊤)
include hxI
lemma exists_smul_add_of_span_sup_eq_top (y : L) : ∃ (t : R) (z ∈ I), y = t • x + z :=
begin
have hy : y ∈ (⊤ : submodule R L) := submodule.mem_top,
simp only [← hxI, submodule.mem_sup, submodule.mem_span_singleton] at hy,
obtain ⟨-, ⟨t, rfl⟩, z, hz, rfl⟩ := hy,
exact ⟨t, z, hz, rfl⟩,
end
lemma lie_top_eq_of_span_sup_eq_top (N : lie_submodule R L M) :
(↑⁅(⊤ : lie_ideal R L), N⁆ : submodule R M) =
(N : submodule R M).map (to_endomorphism R L M x) ⊔ (↑⁅I, N⁆ : submodule R M) :=
begin
simp only [lie_ideal_oper_eq_linear_span', submodule.sup_span, mem_top, exists_prop,
exists_true_left, submodule.map_coe, to_endomorphism_apply_apply],
refine le_antisymm (submodule.span_le.mpr _) (submodule.span_mono (λ z hz, _)),
{ rintros z ⟨y, n, hn : n ∈ N, rfl⟩,
obtain ⟨t, z, hz, rfl⟩ := exists_smul_add_of_span_sup_eq_top hxI y,
simp only [set_like.mem_coe, submodule.span_union, submodule.mem_sup],
exact ⟨t • ⁅x, n⁆, submodule.subset_span ⟨t • n, N.smul_mem' t hn, lie_smul t x n⟩,
⁅z, n⁆, submodule.subset_span ⟨z, hz, n, hn, rfl⟩, by simp⟩, },
{ rcases hz with ⟨m, hm, rfl⟩ | ⟨y, hy, m, hm, rfl⟩,
exacts [⟨x, m, hm, rfl⟩, ⟨y, m, hm, rfl⟩], },
end
lemma lcs_le_lcs_of_is_nilpotent_span_sup_eq_top {n i j : ℕ} (hxn : (to_endomorphism R L M x)^n = 0)
(hIM : lower_central_series R L M i ≤ I.lcs M j) :
lower_central_series R L M (i + n) ≤ I.lcs M (j + 1) :=
begin
suffices : ∀ l, ((⊤ : lie_ideal R L).lcs M (i + l) : submodule R M) ≤
(I.lcs M j : submodule R M).map
((to_endomorphism R L M x)^l) ⊔ (I.lcs M (j + 1) : submodule R M),
{ simpa only [bot_sup_eq, lie_ideal.incl_coe, submodule.map_zero, hxn] using this n, },
intros l,
induction l with l ih,
{ simp only [add_zero, lie_ideal.lcs_succ, pow_zero, linear_map.one_eq_id, submodule.map_id],
exact le_sup_of_le_left hIM, },
{ simp only [lie_ideal.lcs_succ, i.add_succ l, lie_top_eq_of_span_sup_eq_top hxI, sup_le_iff],
refine ⟨(submodule.map_mono ih).trans _, le_sup_of_le_right _⟩,
{ rw [submodule.map_sup, ← submodule.map_comp, ← linear_map.mul_eq_comp, ← pow_succ,
← I.lcs_succ],
exact sup_le_sup_left coe_map_to_endomorphism_le _, },
{ refine le_trans (mono_lie_right _ _ I _) (mono_lie_right _ _ I hIM),
exact antitone_lower_central_series R L M le_self_add, }, },
end
lemma is_nilpotent_of_is_nilpotent_span_sup_eq_top
(hnp : is_nilpotent $ to_endomorphism R L M x) (hIM : is_nilpotent R I M) :
is_nilpotent R L M :=
begin
obtain ⟨n, hn⟩ := hnp,
unfreezingI { obtain ⟨k, hk⟩ := hIM, },
have hk' : I.lcs M k = ⊥,
{ simp only [← coe_to_submodule_eq_iff, I.coe_lcs_eq, hk, bot_coe_submodule], },
suffices : ∀ l, lower_central_series R L M (l * n) ≤ I.lcs M l,
{ use k * n,
simpa [hk'] using this k, },
intros l,
induction l with l ih,
{ simp, },
{ exact (l.succ_mul n).symm ▸ lcs_le_lcs_of_is_nilpotent_span_sup_eq_top hxI hn ih, },
end
end lie_submodule
section lie_algebra
open lie_module (hiding is_nilpotent)
variables (R L)
/-- A Lie algebra `L` is said to be Engelian if a sufficient condition for any `L`-Lie module `M` to
be nilpotent is that the image of the map `L → End(M)` consists of nilpotent elements.
Engel's theorem `lie_algebra.is_engelian_of_is_noetherian` states that any Noetherian Lie algebra is
Engelian. -/
def lie_algebra.is_engelian : Prop :=
∀ (M : Type u₄) [add_comm_group M], by exactI ∀ [module R M] [lie_ring_module L M], by exactI ∀
[lie_module R L M], by exactI ∀ (h : ∀ (x : L), is_nilpotent (to_endomorphism R L M x)),
lie_module.is_nilpotent R L M
variables {R L}
lemma lie_algebra.is_engelian_of_subsingleton [subsingleton L] : lie_algebra.is_engelian R L :=
begin
intros M _i1 _i2 _i3 _i4 h,
use 1,
suffices : (⊤ : lie_ideal R L) = ⊥, { simp [this], },
haveI := (lie_submodule.subsingleton_iff R L L).mpr infer_instance,
apply subsingleton.elim,
end
lemma function.surjective.is_engelian
{f : L →ₗ⁅R⁆ L₂} (hf : function.surjective f) (h : lie_algebra.is_engelian.{u₁ u₂ u₄} R L) :
lie_algebra.is_engelian.{u₁ u₃ u₄} R L₂ :=
begin
introsI M _i1 _i2 _i3 _i4 h',
letI : lie_ring_module L M := lie_ring_module.comp_lie_hom M f,
letI : lie_module R L M := comp_lie_hom M f,
have hnp : ∀ x, is_nilpotent (to_endomorphism R L M x) := λ x, h' (f x),
have surj_id : function.surjective (linear_map.id : M →ₗ[R] M) := function.surjective_id,
haveI : lie_module.is_nilpotent R L M := h M hnp,
apply hf.lie_module_is_nilpotent surj_id,
simp,
end
lemma lie_equiv.is_engelian_iff (e : L ≃ₗ⁅R⁆ L₂) :
lie_algebra.is_engelian.{u₁ u₂ u₄} R L ↔ lie_algebra.is_engelian.{u₁ u₃ u₄} R L₂ :=
⟨e.surjective.is_engelian, e.symm.surjective.is_engelian⟩
lemma lie_algebra.exists_engelian_lie_subalgebra_of_lt_normalizer
{K : lie_subalgebra R L} (hK₁ : lie_algebra.is_engelian.{u₁ u₂ u₄} R K) (hK₂ : K < K.normalizer) :
∃ (K' : lie_subalgebra R L) (hK' : lie_algebra.is_engelian.{u₁ u₂ u₄} R K'), K < K' :=
begin
obtain ⟨x, hx₁, hx₂⟩ := set_like.exists_of_lt hK₂,
let K' : lie_subalgebra R L :=
{ lie_mem' := λ y z, lie_subalgebra.lie_mem_sup_of_mem_normalizer hx₁,
.. (R ∙ x) ⊔ (K : submodule R L) },
have hxK' : x ∈ K' := submodule.mem_sup_left (submodule.subset_span (set.mem_singleton _)),
have hKK' : K ≤ K' := (lie_subalgebra.coe_submodule_le_coe_submodule K K').mp le_sup_right,
have hK' : K' ≤ K.normalizer,
{ rw ← lie_subalgebra.coe_submodule_le_coe_submodule,
exact sup_le ((submodule.span_singleton_le_iff_mem _ _).mpr hx₁) hK₂.le, },
refine ⟨K', _, lt_iff_le_and_ne.mpr ⟨hKK', λ contra, hx₂ (contra.symm ▸ hxK')⟩⟩,
introsI M _i1 _i2 _i3 _i4 h,
obtain ⟨I, hI₁ : (I : lie_subalgebra R K') = lie_subalgebra.of_le hKK'⟩ :=
lie_subalgebra.exists_nested_lie_ideal_of_le_normalizer hKK' hK',
have hI₂ : (R ∙ (⟨x, hxK'⟩ : K')) ⊔ I = ⊤,
{ rw [← lie_ideal.coe_to_lie_subalgebra_to_submodule R K' I, hI₁],
apply submodule.map_injective_of_injective (K' : submodule R L).injective_subtype,
simpa, },
have e : K ≃ₗ⁅R⁆ I := (lie_subalgebra.equiv_of_le hKK').trans
(lie_equiv.of_eq _ _ ((lie_subalgebra.coe_set_eq _ _).mpr hI₁.symm)),
have hI₃ : lie_algebra.is_engelian R I := e.is_engelian_iff.mp hK₁,
exact lie_submodule.is_nilpotent_of_is_nilpotent_span_sup_eq_top hI₂ (h _) (hI₃ _ (λ x, h x)),
end
local attribute [instance] lie_subalgebra.subsingleton_bot
variables [is_noetherian R L]
/-- *Engel's theorem*.
Note that this implies all traditional forms of Engel's theorem via
`lie_module.nontrivial_max_triv_of_is_nilpotent`, `lie_module.is_nilpotent_iff_forall`,
`lie_algebra.is_nilpotent_iff_forall`. -/
lemma lie_algebra.is_engelian_of_is_noetherian : lie_algebra.is_engelian R L :=
begin
introsI M _i1 _i2 _i3 _i4 h,
rw ← is_nilpotent_range_to_endomorphism_iff,
let L' := (to_endomorphism R L M).range,
replace h : ∀ (y : L'), is_nilpotent (y : module.End R M),
{ rintros ⟨-, ⟨y, rfl⟩⟩,
simp [h], },
change lie_module.is_nilpotent R L' M,
let s := { K : lie_subalgebra R L' | lie_algebra.is_engelian R K },
have hs : s.nonempty := ⟨⊥, lie_algebra.is_engelian_of_subsingleton⟩,
suffices : ⊤ ∈ s,
{ rw ← is_nilpotent_of_top_iff,
apply this M,
simp [lie_subalgebra.to_endomorphism_eq, h], },
have : ∀ (K ∈ s), K ≠ ⊤ → ∃ (K' ∈ s), K < K',
{ rintros K (hK₁ : lie_algebra.is_engelian R K) hK₂,
apply lie_algebra.exists_engelian_lie_subalgebra_of_lt_normalizer hK₁,
apply lt_of_le_of_ne K.le_normalizer,
rw [ne.def, eq_comm, K.normalizer_eq_self_iff, ← ne.def,
← lie_submodule.nontrivial_iff_ne_bot R K],
haveI : nontrivial (L' ⧸ K.to_lie_submodule),
{ replace hK₂ : K.to_lie_submodule ≠ ⊤ :=
by rwa [ne.def, ← lie_submodule.coe_to_submodule_eq_iff, K.coe_to_lie_submodule,
lie_submodule.top_coe_submodule, ← lie_subalgebra.top_coe_submodule,
K.coe_to_submodule_eq_iff],
exact submodule.quotient.nontrivial_of_lt_top _ hK₂.lt_top, },
haveI : lie_module.is_nilpotent R K (L' ⧸ K.to_lie_submodule),
{ refine hK₁ _ (λ x, _),
have hx := lie_algebra.is_nilpotent_ad_of_is_nilpotent (h x),
exact module.End.is_nilpotent.mapq _ hx, },
exact nontrivial_max_triv_of_is_nilpotent R K (L' ⧸ K.to_lie_submodule), },
haveI _i5 : is_noetherian R L' :=
is_noetherian_of_surjective L _ (linear_map.range_range_restrict (to_endomorphism R L M)),
obtain ⟨K, hK₁, hK₂⟩ :=
well_founded.well_founded_iff_has_max'.mp (lie_subalgebra.well_founded_of_noetherian R L') s hs,
have hK₃ : K = ⊤,
{ by_contra contra,
obtain ⟨K', hK'₁, hK'₂⟩ := this K hK₁ contra,
specialize hK₂ K' hK'₁ (le_of_lt hK'₂),
replace hK'₂ := (ne_of_lt hK'₂).symm,
contradiction, },
exact hK₃ ▸ hK₁,
end
/-- Engel's theorem. -/
lemma lie_module.is_nilpotent_iff_forall :
lie_module.is_nilpotent R L M ↔ ∀ x, is_nilpotent $ to_endomorphism R L M x :=
⟨begin
introsI h,
obtain ⟨k, hk⟩ := nilpotent_endo_of_nilpotent_module R L M,
exact λ x, ⟨k, hk x⟩,
end,
λ h, lie_algebra.is_engelian_of_is_noetherian M h⟩
/-- Engel's theorem. -/
lemma lie_algebra.is_nilpotent_iff_forall :
lie_algebra.is_nilpotent R L ↔ ∀ x, is_nilpotent $ lie_algebra.ad R L x :=
lie_module.is_nilpotent_iff_forall
end lie_algebra
|
75ca379536aea761a42806a99b3c1c73fcb75061 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebraic_geometry/function_field.lean | 628ccd684a4349468a8d6c4891cf6421fe73bfeb | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 8,270 | 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 algebraic_geometry.properties
/-!
# Function field of integral schemes
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define the function field of an irreducible scheme as the stalk of the generic point.
This is a field when the scheme is integral.
## Main definition
* `algebraic_geometry.Scheme.function_field`: The function field of an integral scheme.
* `algebraic_geometry.germ_to_function_field`: The canonical map from a component into the function
field. This map is injective.
-/
universes u v
open topological_space opposite category_theory category_theory.limits Top
namespace algebraic_geometry
variable (X : Scheme)
/-- The function field of an irreducible scheme is the local ring at its generic point.
Despite the name, this is a field only when the scheme is integral. -/
noncomputable
abbreviation Scheme.function_field [irreducible_space X.carrier] : CommRing :=
X.presheaf.stalk (generic_point X.carrier)
/-- The restriction map from a component to the function field. -/
noncomputable
abbreviation Scheme.germ_to_function_field [irreducible_space X.carrier] (U : opens X.carrier)
[h : nonempty U] : X.presheaf.obj (op U) ⟶ X.function_field :=
X.presheaf.germ ⟨generic_point X.carrier,
((generic_point_spec X.carrier).mem_open_set_iff U.is_open).mpr (by simpa using h)⟩
noncomputable
instance [irreducible_space X.carrier] (U : opens X.carrier) [nonempty U] :
algebra (X.presheaf.obj (op U)) X.function_field :=
(X.germ_to_function_field U).to_algebra
noncomputable
instance [is_integral X] : field X.function_field :=
begin
apply field_of_is_unit_or_eq_zero,
intro a,
obtain ⟨U, m, s, rfl⟩ := Top.presheaf.germ_exist _ _ a,
rw [or_iff_not_imp_right, ← (X.presheaf.germ ⟨_, m⟩).map_zero],
intro ha,
replace ha := ne_of_apply_ne _ ha,
have hs : generic_point X.carrier ∈ RingedSpace.basic_open _ s,
{ rw [← set_like.mem_coe, (generic_point_spec X.carrier).mem_open_set_iff, set.top_eq_univ,
set.univ_inter, set.nonempty_iff_ne_empty, ne.def, ← opens.coe_bot,
← set_like.ext'_iff],
erw basic_open_eq_bot_iff,
exacts [ha, (RingedSpace.basic_open _ _).is_open] },
have := (X.presheaf.germ ⟨_, hs⟩).is_unit_map (RingedSpace.is_unit_res_basic_open _ s),
rwa Top.presheaf.germ_res_apply at this
end
lemma germ_injective_of_is_integral [is_integral X] {U : opens X.carrier} (x : U) :
function.injective (X.presheaf.germ x) :=
begin
rw injective_iff_map_eq_zero,
intros y hy,
rw ← (X.presheaf.germ x).map_zero at hy,
obtain ⟨W, hW, iU, iV, e⟩ := X.presheaf.germ_eq _ x.prop x.prop _ _ hy,
cases (show iU = iV, from subsingleton.elim _ _),
haveI : nonempty W := ⟨⟨_, hW⟩⟩,
exact map_injective_of_is_integral X iU e
end
lemma Scheme.germ_to_function_field_injective [is_integral X] (U : opens X.carrier)
[nonempty U] : function.injective (X.germ_to_function_field U) :=
germ_injective_of_is_integral _ _
lemma generic_point_eq_of_is_open_immersion {X Y : Scheme} (f : X ⟶ Y) [H : is_open_immersion f]
[hX : irreducible_space X.carrier] [irreducible_space Y.carrier] :
f.1.base (generic_point X.carrier : _) = (generic_point Y.carrier : _) :=
begin
apply ((generic_point_spec _).eq _).symm,
show t0_space Y.carrier, by apply_instance,
convert (generic_point_spec X.carrier).image (show continuous f.1.base, by continuity),
symmetry,
rw [eq_top_iff, set.top_eq_univ, set.top_eq_univ],
convert subset_closure_inter_of_is_preirreducible_of_is_open _ H.base_open.open_range _,
rw [set.univ_inter, set.image_univ],
apply_with preirreducible_space.is_preirreducible_univ { instances := ff },
show preirreducible_space Y.carrier, by apply_instance,
exact ⟨_, trivial, set.mem_range_self hX.2.some⟩,
end
noncomputable
instance stalk_function_field_algebra [irreducible_space X.carrier] (x : X.carrier) :
algebra (X.presheaf.stalk x) X.function_field :=
begin
apply ring_hom.to_algebra,
exact X.presheaf.stalk_specializes ((generic_point_spec X.carrier).specializes trivial)
end
instance function_field_is_scalar_tower [irreducible_space X.carrier] (U : opens X.carrier) (x : U)
[nonempty U] :
is_scalar_tower (X.presheaf.obj $ op U) (X.presheaf.stalk x) X.function_field :=
begin
apply is_scalar_tower.of_algebra_map_eq',
simp_rw [ring_hom.algebra_map_to_algebra],
change _ = X.presheaf.germ x ≫ _,
rw X.presheaf.germ_stalk_specializes,
refl
end
noncomputable
instance (R : CommRing) [is_domain R] : algebra R (Scheme.Spec.obj $ op R).function_field :=
ring_hom.to_algebra $ by { change CommRing.of R ⟶ _, apply structure_sheaf.to_stalk }
@[simp] lemma generic_point_eq_bot_of_affine (R : CommRing) [is_domain R] :
generic_point (Scheme.Spec.obj $ op R).carrier = (⟨0, ideal.bot_prime⟩ : prime_spectrum R) :=
begin
apply (generic_point_spec (Scheme.Spec.obj $ op R).carrier).eq,
simp [is_generic_point_def, ← prime_spectrum.zero_locus_vanishing_ideal_eq_closure]
end
instance function_field_is_fraction_ring_of_affine (R : CommRing.{u}) [is_domain R] :
is_fraction_ring R (Scheme.Spec.obj $ op R).function_field :=
begin
convert structure_sheaf.is_localization.to_stalk R _,
delta is_fraction_ring is_localization.at_prime,
congr' 1,
rw generic_point_eq_bot_of_affine,
ext,
exact mem_non_zero_divisors_iff_ne_zero
end
instance {X : Scheme} [is_integral X] {U : opens X.carrier} [hU : nonempty U] :
is_integral (X.restrict U.open_embedding) :=
begin
haveI : nonempty (X.restrict U.open_embedding).carrier := hU,
exact is_integral_of_open_immersion (X.of_restrict U.open_embedding)
end
lemma is_affine_open.prime_ideal_of_generic_point {X : Scheme} [is_integral X]
{U : opens X.carrier} (hU : is_affine_open U) [h : nonempty U] :
hU.prime_ideal_of ⟨generic_point X.carrier,
((generic_point_spec X.carrier).mem_open_set_iff U.is_open).mpr (by simpa using h)⟩ =
generic_point (Scheme.Spec.obj $ op $ X.presheaf.obj $ op U).carrier :=
begin
haveI : is_affine _ := hU,
have e : U.open_embedding.is_open_map.functor.obj ⊤ = U,
{ ext1, exact set.image_univ.trans subtype.range_coe },
delta is_affine_open.prime_ideal_of,
rw ← Scheme.comp_val_base_apply,
convert (generic_point_eq_of_is_open_immersion ((X.restrict U.open_embedding).iso_Spec.hom ≫
Scheme.Spec.map (X.presheaf.map (eq_to_hom e).op).op)),
ext1,
exact (generic_point_eq_of_is_open_immersion (X.of_restrict U.open_embedding)).symm
end
lemma function_field_is_fraction_ring_of_is_affine_open [is_integral X] (U : opens X.carrier)
(hU : is_affine_open U) [hU' : nonempty U] :
is_fraction_ring (X.presheaf.obj $ op U) X.function_field :=
begin
haveI : is_affine _ := hU,
haveI : nonempty (X.restrict U.open_embedding).carrier := hU',
haveI : is_integral (X.restrict U.open_embedding) := @@is_integral_of_is_affine_is_domain _ _ _
(by { dsimp, rw opens.open_embedding_obj_top, apply_instance }),
have e : U.open_embedding.is_open_map.functor.obj ⊤ = U,
{ ext1, exact set.image_univ.trans subtype.range_coe },
delta is_fraction_ring Scheme.function_field,
convert hU.is_localization_stalk ⟨generic_point X.carrier, _⟩ using 1,
rw [hU.prime_ideal_of_generic_point, generic_point_eq_bot_of_affine],
ext, exact mem_non_zero_divisors_iff_ne_zero
end
instance (x : X.carrier) : is_affine (X.affine_cover.obj x) :=
algebraic_geometry.Spec_is_affine _
instance [h : is_integral X] (x : X.carrier) :
is_fraction_ring (X.presheaf.stalk x) X.function_field :=
begin
let U : opens X.carrier := ⟨set.range (X.affine_cover.map x).1.base,
PresheafedSpace.is_open_immersion.base_open.open_range⟩,
haveI : nonempty U := ⟨⟨_, X.affine_cover.covers x⟩⟩,
have hU : is_affine_open U := range_is_affine_open_of_open_immersion (X.affine_cover.map x),
exact @@is_fraction_ring.is_fraction_ring_of_is_domain_of_is_localization _ _ _ _ _ _ _ _ _ _ _
(hU.is_localization_stalk ⟨x, X.affine_cover.covers x⟩)
(function_field_is_fraction_ring_of_is_affine_open X U hU)
end
end algebraic_geometry
|
8a0029840c548d01a794895eb79f6bf00d48166c | f3849be5d845a1cb97680f0bbbe03b85518312f0 | /tests/lean/run/1495.lean | 15a78eba507e67a61d9e244ab54c7d8d3cd0dd5b | [
"Apache-2.0"
] | permissive | bjoeris/lean | 0ed95125d762b17bfcb54dad1f9721f953f92eeb | 4e496b78d5e73545fa4f9a807155113d8e6b0561 | refs/heads/master | 1,611,251,218,281 | 1,495,337,658,000 | 1,495,337,658,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 177 | lean | section
variables (r : ℕ → ℕ → Prop)
local infix `≼` : 50 := r
example {a b : ℕ} : a ≼ b → true :=
begin
show a ≼ b → true,
from λx, trivial
end
end
|
75d25a372044476aaa8a54dabc7d648062d2bae8 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Elab/Tactic/Induction.lean | bbdcdb84fa0d4508f239c64024176aa537dea9b0 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 27,664 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Util.CollectFVars
import Lean.AuxRecursor
import Lean.Parser.Term
import Lean.Meta.RecursorInfo
import Lean.Meta.CollectMVars
import Lean.Meta.Tactic.ElimInfo
import Lean.Meta.Tactic.Induction
import Lean.Meta.Tactic.Cases
import Lean.Meta.GeneralizeVars
import Lean.Elab.App
import Lean.Elab.Tactic.ElabTerm
import Lean.Elab.Tactic.Generalize
namespace Lean.Elab.Tactic
open Meta
/-
Given an `inductionAlt` of the form
```
syntax inductionAltLHS := "| " (group("@"? ident) <|> hole) (ident <|> hole)*
syntax inductionAlt := ppDedent(ppLine) inductionAltLHS+ " => " (hole <|> syntheticHole <|> tacticSeq)
```
-/
private def getFirstAltLhs (alt : Syntax) : Syntax :=
alt[0][0]
/-- Return `inductionAlt` name. It assumes `alt` does not have multiple `inductionAltLHS` -/
private def getAltName (alt : Syntax) : Name :=
let lhs := getFirstAltLhs alt
if !lhs[1].isOfKind ``Parser.Term.hole then lhs[1][1].getId.eraseMacroScopes else `_
/-- Returns the `inductionAlt` `ident <|> hole` -/
private def getAltNameStx (alt : Syntax) : Syntax :=
let lhs := getFirstAltLhs alt
if lhs[1].isOfKind ``Parser.Term.hole then lhs[1] else lhs[1][1]
/-- Return `true` if the first LHS of the given alternative contains `@`. -/
private def altHasExplicitModifier (alt : Syntax) : Bool :=
let lhs := getFirstAltLhs alt
!lhs[1].isOfKind ``Parser.Term.hole && !lhs[1][0].isNone
/-- Return the variables in the first LHS of the given alternative. -/
private def getAltVars (alt : Syntax) : Array Syntax :=
let lhs := getFirstAltLhs alt
lhs[2].getArgs
private def getAltRHS (alt : Syntax) : Syntax :=
alt[2]
private def getAltDArrow (alt : Syntax) : Syntax :=
alt[1]
-- Return true if `stx` is a term occurring in the RHS of the induction/cases tactic
def isHoleRHS (rhs : Syntax) : Bool :=
rhs.isOfKind ``Parser.Term.syntheticHole || rhs.isOfKind ``Parser.Term.hole
def evalAlt (mvarId : MVarId) (alt : Syntax) (addInfo : TermElabM Unit) (remainingGoals : Array MVarId) : TacticM (Array MVarId) :=
let rhs := getAltRHS alt
withCaseRef (getAltDArrow alt) rhs do
if isHoleRHS rhs then
addInfo
let gs' ← mvarId.withContext <| withRef rhs do
let mvarDecl ← mvarId.getDecl
let val ← elabTermEnsuringType rhs mvarDecl.type
mvarId.assign val
let gs' ← getMVarsNoDelayed val
tagUntaggedGoals mvarDecl.userName `induction gs'.toList
pure gs'
return remainingGoals ++ gs'
else
setGoals [mvarId]
closeUsingOrAdmit (withTacticInfoContext alt (addInfo *> evalTactic rhs))
return remainingGoals
/-!
Helper method for creating an user-defined eliminator/recursor application.
-/
namespace ElimApp
structure Alt where
/-- The short name of the alternative, used in `| foo =>` cases -/
name : Name
/-- A declaration corresponding to the inductive constructor.
(For custom recursors, the alternatives correspond to parameter names in the
recursor, so we may not have a declaration to point to.)
This is used for go-to-definition on the alternative name. -/
declName? : Option Name
/-- The subgoal metavariable for the alternative. -/
mvarId : MVarId
deriving Inhabited
structure Context where
elimInfo : ElimInfo
targets : Array Expr -- targets provided by the user
structure State where
argPos : Nat := 0 -- current argument position
targetPos : Nat := 0 -- current target at targetsStx
f : Expr
fType : Expr
alts : Array Alt := #[]
insts : Array MVarId := #[]
abbrev M := ReaderT Context $ StateRefT State TermElabM
private def addNewArg (arg : Expr) : M Unit :=
modify fun s => { s with argPos := s.argPos+1, f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg }
/-- 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!
private def getFType : M Expr := do
let fType ← whnfForall (← get).fType
modify fun s => { s with fType := fType }
pure fType
structure Result where
elimApp : Expr
alts : Array Alt := #[]
others : Array MVarId := #[]
/--
Construct the an eliminator/recursor application. `targets` contains the explicit and implicit targets for
the eliminator. For example, the indices of builtin recursors are considered implicit targets.
Remark: the method `addImplicitTargets` may be used to compute the sequence of implicit and explicit targets
from the explicit ones.
-/
partial def mkElimApp (elimInfo : ElimInfo) (targets : Array Expr) (tag : Name) : TermElabM Result := do
let rec loop : M Unit := do
match (← getFType) with
| .forallE binderName _ _ c =>
let ctx ← read
let argPos := (← get).argPos
if ctx.elimInfo.motivePos == argPos then
let motive ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.syntheticOpaque
addNewArg motive
else if ctx.elimInfo.targetsPos.contains argPos then
let s ← get
let ctx ← read
unless s.targetPos < ctx.targets.size do
throwError "insufficient number of targets for '{elimInfo.name}'"
let target := ctx.targets[s.targetPos]!
let expectedType ← getArgExpectedType
let target ← withAssignableSyntheticOpaque <| Term.ensureHasType expectedType target
modify fun s => { s with targetPos := s.targetPos + 1 }
addNewArg target
else match c with
| .implicit =>
let arg ← mkFreshExprMVar (← getArgExpectedType)
addNewArg arg
| .strictImplicit =>
let arg ← mkFreshExprMVar (← getArgExpectedType)
addNewArg arg
| .instImplicit =>
let arg ← mkFreshExprMVar (← getArgExpectedType) (kind := MetavarKind.synthetic) (userName := appendTag tag binderName)
modify fun s => { s with insts := s.insts.push arg.mvarId! }
addNewArg arg
| _ =>
let arg ← mkFreshExprSyntheticOpaqueMVar (← getArgExpectedType) (tag := appendTag tag binderName)
let x ← getBindingName
modify fun s =>
let declName? := elimInfo.altsInfo[s.alts.size]!.declName?
{ s with alts := s.alts.push ⟨x, declName?, arg.mvarId!⟩ }
addNewArg arg
loop
| _ =>
pure ()
let f ← Term.mkConst elimInfo.name
let fType ← inferType f
let (_, s) ← (loop).run { elimInfo := elimInfo, targets := targets } |>.run { f := f, fType := fType }
let mut others := #[]
for mvarId in s.insts do
try
unless (← Term.synthesizeInstMVarCore mvarId) do
mvarId.setKind .syntheticOpaque
others := others.push mvarId
catch _ =>
mvarId.setKind .syntheticOpaque
others := others.push mvarId
let alts ← s.alts.filterM fun alt => return !(← alt.mvarId.isAssigned)
return { elimApp := (← instantiateMVars s.f), alts, others := others }
/-- Given a goal `... targets ... |- C[targets]` associated with `mvarId`, assign
`motiveArg := fun targets => C[targets]` -/
def setMotiveArg (mvarId : MVarId) (motiveArg : MVarId) (targets : Array FVarId) : MetaM Unit := do
let type ← inferType (mkMVar mvarId)
let motive ← mkLambdaFVars (targets.map mkFVar) type
let motiverInferredType ← inferType motive
let motiveType ← inferType (mkMVar motiveArg)
unless (← isDefEqGuarded motiverInferredType motiveType) do
throwError "type mismatch when assigning motive{indentExpr motive}\n{← mkHasTypeButIsExpectedMsg motiverInferredType motiveType}"
motiveArg.assign motive
private def getAltNumFields (elimInfo : ElimInfo) (altName : Name) : TermElabM Nat := do
for altInfo in elimInfo.altsInfo do
if altInfo.name == altName then
return altInfo.numFields
throwError "unknown alternative name '{altName}'"
private def checkAltNames (alts : Array Alt) (altsSyntax : Array Syntax) : TacticM Unit :=
for i in [:altsSyntax.size] do
let altStx := altsSyntax[i]!
if getAltName altStx == `_ && i != altsSyntax.size - 1 then
withRef altStx <| throwError "invalid occurrence of wildcard alternative, it must be the last alternative"
let altName := getAltName altStx
if altName != `_ then
unless alts.any (·.name == altName) do
throwErrorAt altStx "invalid alternative name '{altName}'"
/-- Given the goal `altMVarId` for a given alternative that introduces `numFields` new variables,
return the number of explicit variables. Recall that when the `@` is not used, only the explicit variables can
be named by the user. -/
private def getNumExplicitFields (altMVarId : MVarId) (numFields : Nat) : MetaM Nat := altMVarId.withContext do
let target ← altMVarId.getType
withoutModifyingState do
let (_, bis, _) ← forallMetaBoundedTelescope target numFields
return bis.foldl (init := 0) fun r bi => if bi.isExplicit then r + 1 else r
private def saveAltVarsInfo (altMVarId : MVarId) (altStx : Syntax) (fvarIds : Array FVarId) : TermElabM Unit :=
withSaveInfoContext <| altMVarId.withContext do
let useNamesForExplicitOnly := !altHasExplicitModifier altStx
let mut i := 0
let altVars := getAltVars altStx
for fvarId in fvarIds do
if !useNamesForExplicitOnly || (← fvarId.getDecl).binderInfo.isExplicit then
if i < altVars.size then
Term.addLocalVarInfo altVars[i]! (mkFVar fvarId)
i := i + 1
/--
If `altsSyntax` is not empty we reorder `alts` using the order the alternatives have been provided
in `altsSyntax`. Motivations:
1- It improves the effectiveness of the `checkpoint` and `save` tactics. Consider the following example:
```lean
example (h₁ : p ∨ q) (h₂ : p → x = 0) (h₃ : q → y = 0) : x * y = 0 := by
cases h₁ with
| inr h =>
sleep 5000 -- sleeps for 5 seconds
save
have : y = 0 := h₃ h
-- We can confortably work here
| inl h => stop ...
```
If we do reorder, the `inl` alternative will be executed first. Moreover, as we type in the `inr` alternative,
type errors will "swallow" the `inl` alternative and affect the tactic state at `save` making it ineffective.
2- The errors are produced in the same order the appear in the code above. This is not super important when using IDEs.
-/
def reorderAlts (alts : Array Alt) (altsSyntax : Array Syntax) : Array Alt := Id.run do
if altsSyntax.isEmpty then
return alts
else
let mut alts := alts
let mut result := #[]
for altStx in altsSyntax do
let altName := getAltName altStx
let some i := alts.findIdx? (·.1 == altName) | return result ++ alts
result := result.push alts[i]!
alts := alts.eraseIdx i
return result ++ alts
def evalAlts (elimInfo : ElimInfo) (alts : Array Alt) (optPreTac : Syntax) (altsSyntax : Array Syntax)
(initialInfo : Info)
(numEqs : Nat := 0) (numGeneralized : Nat := 0) (toClear : Array FVarId := #[]) : TacticM Unit := do
checkAltNames alts altsSyntax
let hasAlts := altsSyntax.size > 0
if hasAlts then
-- default to initial state outside of alts
-- HACK: because this node has the same span as the original tactic,
-- we need to take all the info trees we have produced so far and re-nest them
-- inside this node as well
let treesSaved ← getResetInfoTrees
withInfoContext ((modifyInfoState fun s => { s with trees := treesSaved }) *> go) (pure initialInfo)
else go
where
go := do
let alts := reorderAlts alts altsSyntax
let hasAlts := altsSyntax.size > 0
let mut usedWildcard := false
let mut subgoals := #[] -- when alternatives are not provided, we accumulate subgoals here
let mut altsSyntax := altsSyntax
for { name := altName, declName?, mvarId := altMVarId } in alts do
let numFields ← getAltNumFields elimInfo altName
let mut isWildcard := false
let altStx? ←
match altsSyntax.findIdx? (fun alt => getAltName alt == altName) with
| some idx =>
let altStx := altsSyntax[idx]!
altsSyntax := altsSyntax.eraseIdx idx
pure (some altStx)
| none => match altsSyntax.findIdx? (fun alt => getAltName alt == `_) with
| some idx =>
isWildcard := true
pure (some altsSyntax[idx]!)
| none =>
pure none
match altStx? with
| none =>
let mut (_, altMVarId) ← altMVarId.introN numFields
match (← Cases.unifyEqs? numEqs altMVarId {}) with
| none => pure () -- alternative is not reachable
| some (altMVarId', _) =>
(_, altMVarId) ← altMVarId'.introNP numGeneralized
for fvarId in toClear do
altMVarId ← altMVarId.tryClear fvarId
let altMVarIds ← applyPreTac altMVarId
if !hasAlts then
-- User did not provide alternatives using `|`
subgoals := subgoals ++ altMVarIds.toArray
else if altMVarIds.isEmpty then
pure ()
else
logError m!"alternative '{altName}' has not been provided"
altMVarIds.forM fun mvarId => admitGoal mvarId
| some altStx =>
(subgoals, usedWildcard) ← withRef altStx do
let altVars := getAltVars altStx
let numFieldsToName ← if altHasExplicitModifier altStx then pure numFields else getNumExplicitFields altMVarId numFields
if altVars.size > numFieldsToName then
logError m!"too many variable names provided at alternative '{altName}', #{altVars.size} provided, but #{numFieldsToName} expected"
let mut (fvarIds, altMVarId) ← altMVarId.introN numFields (altVars.toList.map getNameOfIdent') (useNamesForExplicitOnly := !altHasExplicitModifier altStx)
-- Delay adding the infos for the pattern LHS because we want them to nest
-- inside tacticInfo for the current alternative (in `evalAlt`)
let addInfo := do
if (← getInfoState).enabled then
if let some declName := declName? then
addConstInfo (getAltNameStx altStx) declName
saveAltVarsInfo altMVarId altStx fvarIds
let unusedAlt := do
addInfo
if isWildcard then
pure (#[], usedWildcard)
else
throwError "alternative '{altName}' is not needed"
match (← Cases.unifyEqs? numEqs altMVarId {}) with
| none => unusedAlt
| some (altMVarId', _) =>
(_, altMVarId) ← altMVarId'.introNP numGeneralized
for fvarId in toClear do
altMVarId ← altMVarId.tryClear fvarId
let altMVarIds ← applyPreTac altMVarId
if altMVarIds.isEmpty then
unusedAlt
else
let mut subgoals := subgoals
for altMVarId' in altMVarIds do
subgoals ← evalAlt altMVarId' altStx addInfo subgoals
pure (subgoals, usedWildcard || isWildcard)
if usedWildcard then
altsSyntax := altsSyntax.filter fun alt => getAltName alt != `_
unless altsSyntax.isEmpty do
logErrorAt altsSyntax[0]! "unused alternative"
setGoals subgoals.toList
applyPreTac (mvarId : MVarId) : TacticM (List MVarId) :=
if optPreTac.isNone then
return [mvarId]
else
evalTacticAt optPreTac[0] mvarId
end ElimApp
/-
Recall that
```
generalizingVars := optional (" generalizing " >> many1 ident)
«induction» := leading_parser nonReservedSymbol "induction " >> majorPremise >> usingRec >> generalizingVars >> optional inductionAlts
```
`stx` is syntax for `induction`. -/
private def getUserGeneralizingFVarIds (stx : Syntax) : TacticM (Array FVarId) :=
withRef stx do
let generalizingStx := stx[3]
if generalizingStx.isNone then
pure #[]
else
trace[Elab.induction] "{generalizingStx}"
let vars := generalizingStx[1].getArgs
getFVarIds vars
-- process `generalizingVars` subterm of induction Syntax `stx`.
private def generalizeVars (mvarId : MVarId) (stx : Syntax) (targets : Array Expr) : TacticM (Nat × MVarId) :=
mvarId.withContext do
let userFVarIds ← getUserGeneralizingFVarIds stx
let forbidden ← mkGeneralizationForbiddenSet targets
let mut s ← getFVarSetToGeneralize targets forbidden
for userFVarId in userFVarIds do
if forbidden.contains userFVarId then
throwError "variable cannot be generalized because target depends on it{indentExpr (mkFVar userFVarId)}"
if s.contains userFVarId then
throwError "unnecessary 'generalizing' argument, variable '{mkFVar userFVarId}' is generalized automatically"
s := s.insert userFVarId
let fvarIds ← sortFVarIds s.toArray
let (fvarIds, mvarId') ← mvarId.revert fvarIds
return (fvarIds.size, mvarId')
/--
Given `inductionAlts` of the fom
```
syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+)
```
Return an array containing its alternatives.
-/
private def getAltsOfInductionAlts (inductionAlts : Syntax) : Array Syntax :=
inductionAlts[2].getArgs
private def getAltsOfOptInductionAlts (optInductionAlts : Syntax) : Array Syntax :=
if optInductionAlts.isNone then #[] else getAltsOfInductionAlts optInductionAlts[0]
private def getOptPreTacOfOptInductionAlts (optInductionAlts : Syntax) : Syntax :=
if optInductionAlts.isNone then mkNullNode else optInductionAlts[0][1]
private def isMultiAlt (alt : Syntax) : Bool :=
alt[0].getNumArgs > 1
/-- Return `some #[alt_1, ..., alt_n]` if `alt` has multiple LHSs. -/
private def expandMultiAlt? (alt : Syntax) : Option (Array Syntax) := Id.run do
if isMultiAlt alt then
some <| alt[0].getArgs.map fun lhs => alt.setArg 0 (mkNullNode #[lhs])
else
none
/--
Given `inductionAlts` of the form
```
syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+)
```
Return `some inductionAlts'` if one of the alternatives have multiple LHSs, in the new `inductionAlts'`
all alternatives have a single LHS.
Remark: the `RHS` of alternatives with multi LHSs is copied.
-/
private def expandInductionAlts? (inductionAlts : Syntax) : Option Syntax := Id.run do
let alts := getAltsOfInductionAlts inductionAlts
if alts.any isMultiAlt then
let mut altsNew := #[]
for alt in alts do
if let some alt' := expandMultiAlt? alt then
altsNew := altsNew ++ alt'
else
altsNew := altsNew.push alt
some <| inductionAlts.setArg 2 (mkNullNode altsNew)
else
none
/--
Expand
```
syntax "induction " term,+ (" using " ident)? ("generalizing " (colGt term:max)+)? (inductionAlts)? : tactic
```
if `inductionAlts` has an alternative with multiple LHSs.
-/
private def expandInduction? (induction : Syntax) : Option Syntax := do
let optInductionAlts := induction[4]
guard <| !optInductionAlts.isNone
let inductionAlts' ← expandInductionAlts? optInductionAlts[0]
return induction.setArg 4 (mkNullNode #[inductionAlts'])
/--
Expand
```
syntax "cases " casesTarget,+ (" using " ident)? (inductionAlts)? : tactic
```
if `inductionAlts` has an alternative with multiple LHSs.
-/
private def expandCases? (induction : Syntax) : Option Syntax := do
let optInductionAlts := induction[3]
guard <| !optInductionAlts.isNone
let inductionAlts' ← expandInductionAlts? optInductionAlts[0]
return induction.setArg 3 (mkNullNode #[inductionAlts'])
/--
We may have at most one `| _ => ...` (wildcard alternative), and it must not set variable names.
The idea is to make sure users do not write unstructured tactics. -/
private def checkAltsOfOptInductionAlts (optInductionAlts : Syntax) : TacticM Unit :=
unless optInductionAlts.isNone do
let mut found := false
for alt in getAltsOfInductionAlts optInductionAlts[0] do
let n := getAltName alt
if n == `_ then
unless (getAltVars alt).isEmpty do
throwErrorAt alt "wildcard alternative must not specify variable names"
if found then
throwErrorAt alt "more than one wildcard alternative '| _ => ...' used"
found := true
def getInductiveValFromMajor (major : Expr) : TacticM InductiveVal :=
liftMetaMAtMain fun mvarId => do
let majorType ← inferType major
let majorType ← whnf majorType
matchConstInduct majorType.getAppFn
(fun _ => Meta.throwTacticEx `induction mvarId m!"major premise type is not an inductive type {indentExpr majorType}")
(fun val _ => pure val)
-- `optElimId` is of the form `("using" ident)?`
private def getElimNameInfo (optElimId : Syntax) (targets : Array Expr) (induction : Bool): TacticM ElimInfo := do
if optElimId.isNone then
if let some elimInfo ← getCustomEliminator? targets then
return elimInfo
unless targets.size == 1 do
throwError "eliminator must be provided when multiple targets are used (use 'using <eliminator-name>'), and no default eliminator has been registered using attribute `[eliminator]`"
let indVal ← getInductiveValFromMajor targets[0]!
if induction && indVal.all.length != 1 then
throwError "'induction' tactic does not support mutually inductive types, the eliminator '{mkRecName indVal.name}' has multiple motives"
if induction && indVal.isNested then
throwError "'induction' tactic does not support nested inductive types, the eliminator '{mkRecName indVal.name}' has multiple motives"
let elimName := if induction then mkRecName indVal.name else mkCasesOnName indVal.name
getElimInfo elimName indVal.name
else
let elimId := optElimId[1]
let elimName ← withRef elimId do resolveGlobalConstNoOverloadWithInfo elimId
-- not a precise check, but covers the common cases of T.recOn / T.casesOn
-- as well as user defined T.myInductionOn to locate the constructors of T
let baseName? := if ← isInductive elimName.getPrefix then some elimName.getPrefix else none
withRef elimId <| getElimInfo elimName baseName?
private def shouldGeneralizeTarget (e : Expr) : MetaM Bool := do
if let .fvar fvarId .. := e then
return (← fvarId.getDecl).hasValue -- must generalize let-decls
else
return true
private def generalizeTargets (exprs : Array Expr) : TacticM (Array Expr) := do
if (← withMainContext <| exprs.anyM (shouldGeneralizeTarget ·)) then
liftMetaTacticAux fun mvarId => do
let (fvarIds, mvarId) ← mvarId.generalize (exprs.map fun expr => { expr })
return (fvarIds.map mkFVar, [mvarId])
else
return exprs
@[builtin_tactic Lean.Parser.Tactic.induction] def evalInduction : Tactic := fun stx =>
match expandInduction? stx with
| some stxNew => withMacroExpansion stx stxNew <| evalTactic stxNew
| _ => focus do
let optInductionAlts := stx[4]
let alts := getAltsOfOptInductionAlts optInductionAlts
let targets ← withMainContext <| stx[1].getSepArgs.mapM (elabTerm · none)
let targets ← generalizeTargets targets
let elimInfo ← withMainContext <| getElimNameInfo stx[2] targets (induction := true)
let mvarId ← getMainGoal
-- save initial info before main goal is reassigned
let initInfo ← mkTacticInfo (← getMCtx) (← getUnsolvedGoals) (← getRef)
let tag ← mvarId.getTag
mvarId.withContext do
let targets ← addImplicitTargets elimInfo targets
checkTargets targets
let targetFVarIds := targets.map (·.fvarId!)
let (n, mvarId) ← generalizeVars mvarId stx targets
mvarId.withContext do
let result ← withRef stx[1] do -- use target position as reference
ElimApp.mkElimApp elimInfo targets tag
trace[Elab.induction] "elimApp: {result.elimApp}"
let elimArgs := result.elimApp.getAppArgs
ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos]!.mvarId! targetFVarIds
let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts
mvarId.assign result.elimApp
ElimApp.evalAlts elimInfo result.alts optPreTac alts initInfo (numGeneralized := n) (toClear := targetFVarIds)
appendGoals result.others.toList
where
checkTargets (targets : Array Expr) : MetaM Unit := do
let mut foundFVars : FVarIdSet := {}
for target in targets do
unless target.isFVar do
throwError "index in target's type is not a variable (consider using the `cases` tactic instead){indentExpr target}"
if foundFVars.contains target.fvarId! then
throwError "target (or one of its indices) occurs more than once{indentExpr target}"
def elabCasesTargets (targets : Array Syntax) : TacticM (Array Expr) :=
withMainContext do
let args ← targets.mapM fun target => do
let hName? := if target[0].isNone then none else some target[0][0].getId
let expr ← elabTerm target[1] none
return { expr, hName? : GeneralizeArg }
if (← withMainContext <| args.anyM fun arg => shouldGeneralizeTarget arg.expr <||> pure arg.hName?.isSome) then
liftMetaTacticAux fun mvarId => do
let argsToGeneralize ← args.filterM fun arg => shouldGeneralizeTarget arg.expr <||> pure arg.hName?.isSome
let (fvarIdsNew, mvarId) ← mvarId.generalize argsToGeneralize
let mut result := #[]
let mut j := 0
for arg in args do
if (← shouldGeneralizeTarget arg.expr) || arg.hName?.isSome then
result := result.push (mkFVar fvarIdsNew[j]!)
j := j+1
else
result := result.push arg.expr
return (result, [mvarId])
else
return args.map (·.expr)
@[builtin_tactic Lean.Parser.Tactic.cases] def evalCases : Tactic := fun stx =>
match expandCases? stx with
| some stxNew => withMacroExpansion stx stxNew <| evalTactic stxNew
| _ => focus do
-- leading_parser nonReservedSymbol "cases " >> sepBy1 (group majorPremise) ", " >> usingRec >> optInductionAlts
let targets ← elabCasesTargets stx[1].getSepArgs
let optInductionAlts := stx[3]
let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts
let alts := getAltsOfOptInductionAlts optInductionAlts
let targetRef := stx[1]
let elimInfo ← withMainContext <| getElimNameInfo stx[2] targets (induction := false)
let mvarId ← getMainGoal
-- save initial info before main goal is reassigned
let initInfo ← mkTacticInfo (← getMCtx) (← getUnsolvedGoals) (← getRef)
let tag ← mvarId.getTag
mvarId.withContext do
let targets ← addImplicitTargets elimInfo targets
let result ← withRef targetRef <| ElimApp.mkElimApp elimInfo targets tag
let elimArgs := result.elimApp.getAppArgs
let targets ← elimInfo.targetsPos.mapM fun i => instantiateMVars elimArgs[i]!
let motiveType ← inferType elimArgs[elimInfo.motivePos]!
let mvarId ← generalizeTargetsEq mvarId motiveType targets
let (targetsNew, mvarId) ← mvarId.introN targets.size
mvarId.withContext do
ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos]!.mvarId! targetsNew
mvarId.assign result.elimApp
ElimApp.evalAlts elimInfo result.alts optPreTac alts initInfo (numEqs := targets.size) (toClear := targetsNew)
builtin_initialize
registerTraceClass `Elab.cases
registerTraceClass `Elab.induction
end Lean.Elab.Tactic
|
aa0c05f91a827581062a77703e3e6cba5f4d8ae8 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/setoid/basic.lean | f8e8c56b9a906f41196c5caff529f36c1f9c889d | [
"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 | 18,553 | lean | /-
Copyright (c) 2019 Amelia Livingston. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Amelia Livingston, Bryan Gin-ge Chen
-/
import logic.relation
import order.galois_connection
/-!
# Equivalence relations
This file defines the complete lattice of equivalence relations on a type, results about the
inductively defined equivalence closure of a binary relation, and the analogues of some isomorphism
theorems for quotients of arbitrary types.
## Implementation notes
The function `rel` and lemmas ending in ' make it easier to talk about different
equivalence relations on the same type.
The complete lattice instance for equivalence relations could have been defined by lifting
the Galois insertion of equivalence relations on α into binary relations on α, and then using
`complete_lattice.copy` to define a complete lattice instance with more appropriate
definitional equalities (a similar example is `filter.complete_lattice` in
`order/filter/basic.lean`). This does not save space, however, and is less clear.
Partitions are not defined as a separate structure here; users are encouraged to
reason about them using the existing `setoid` and its infrastructure.
## Tags
setoid, equivalence, iseqv, relation, equivalence relation
-/
variables {α : Type*} {β : Type*}
/-- A version of `setoid.r` that takes the equivalence relation as an explicit argument. -/
def setoid.rel (r : setoid α) : α → α → Prop := @setoid.r _ r
instance setoid.decidable_rel (r : setoid α) [h : decidable_rel r.r] : decidable_rel r.rel := h
/-- A version of `quotient.eq'` compatible with `setoid.rel`, to make rewriting possible. -/
lemma quotient.eq_rel {r : setoid α} {x y} :
(quotient.mk' x : quotient r) = quotient.mk' y ↔ r.rel x y := quotient.eq
namespace setoid
@[ext] lemma ext' {r s : setoid α} (H : ∀ a b, r.rel a b ↔ s.rel a b) :
r = s := ext H
lemma ext_iff {r s : setoid α} : r = s ↔ ∀ a b, r.rel a b ↔ s.rel a b :=
⟨λ h a b, h ▸ iff.rfl, ext'⟩
/-- Two equivalence relations are equal iff their underlying binary operations are equal. -/
theorem eq_iff_rel_eq {r₁ r₂ : setoid α} : r₁ = r₂ ↔ r₁.rel = r₂.rel :=
⟨λ h, h ▸ rfl, λ h, setoid.ext' $ λ x y, h ▸ iff.rfl⟩
/-- Defining `≤` for equivalence relations. -/
instance : has_le (setoid α) := ⟨λ r s, ∀ ⦃x y⦄, r.rel x y → s.rel x y⟩
theorem le_def {r s : setoid α} : r ≤ s ↔ ∀ {x y}, r.rel x y → s.rel x y := iff.rfl
@[refl] lemma refl' (r : setoid α) (x) : r.rel x x := r.2.1 x
@[symm] lemma symm' (r : setoid α) : ∀ {x y}, r.rel x y → r.rel y x := λ _ _ h, r.2.2.1 h
@[trans] lemma trans' (r : setoid α) : ∀ {x y z}, r.rel x y → r.rel y z → r.rel x z :=
λ _ _ _ hx, r.2.2.2 hx
lemma comm' (s : setoid α) {x y} : s.rel x y ↔ s.rel y x :=
⟨s.symm', s.symm'⟩
/-- The kernel of a function is an equivalence relation. -/
def ker (f : α → β) : setoid α :=
⟨(=) on f, eq_equivalence.comap f⟩
/-- The kernel of the quotient map induced by an equivalence relation r equals r. -/
@[simp] lemma ker_mk_eq (r : setoid α) : ker (@quotient.mk _ r) = r :=
ext' $ λ x y, quotient.eq
lemma ker_apply_mk_out {f : α → β} (a : α) :
f (by haveI := setoid.ker f; exact ⟦a⟧.out) = f a :=
@quotient.mk_out _ (setoid.ker f) a
lemma ker_apply_mk_out' {f : α → β} (a : α) :
f ((quotient.mk' a : quotient $ setoid.ker f).out') = f a :=
@quotient.mk_out' _ (setoid.ker f) a
lemma ker_def {f : α → β} {x y : α} : (ker f).rel x y ↔ f x = f y := iff.rfl
/-- Given types `α`, `β`, the product of two equivalence relations `r` on `α` and `s` on `β`:
`(x₁, x₂), (y₁, y₂) ∈ α × β` are related by `r.prod s` iff `x₁` is related to `y₁`
by `r` and `x₂` is related to `y₂` by `s`. -/
protected def prod (r : setoid α) (s : setoid β) : setoid (α × β) :=
{ r := λ x y, r.rel x.1 y.1 ∧ s.rel x.2 y.2,
iseqv := ⟨λ x, ⟨r.refl' x.1, s.refl' x.2⟩, λ _ _ h, ⟨r.symm' h.1, s.symm' h.2⟩,
λ _ _ _ h1 h2, ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩ }
/-- The infimum of two equivalence relations. -/
instance : has_inf (setoid α) :=
⟨λ r s, ⟨λ x y, r.rel x y ∧ s.rel x y, ⟨λ x, ⟨r.refl' x, s.refl' x⟩,
λ _ _ h, ⟨r.symm' h.1, s.symm' h.2⟩,
λ _ _ _ h1 h2, ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩⟩⟩
/-- The infimum of 2 equivalence relations r and s is the same relation as the infimum
of the underlying binary operations. -/
lemma inf_def {r s : setoid α} : (r ⊓ s).rel = r.rel ⊓ s.rel := rfl
theorem inf_iff_and {r s : setoid α} {x y} :
(r ⊓ s).rel x y ↔ r.rel x y ∧ s.rel x y := iff.rfl
/-- The infimum of a set of equivalence relations. -/
instance : has_Inf (setoid α) :=
⟨λ S, ⟨λ x y, ∀ r ∈ S, rel r x y,
⟨λ x r hr, r.refl' x, λ _ _ h r hr, r.symm' $ h r hr,
λ _ _ _ h1 h2 r hr, r.trans' (h1 r hr) $ h2 r hr⟩⟩⟩
/-- The underlying binary operation of the infimum of a set of equivalence relations
is the infimum of the set's image under the map to the underlying binary operation. -/
theorem Inf_def {s : set (setoid α)} : (Inf s).rel = Inf (rel '' s) :=
by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl }
instance : partial_order (setoid α) :=
{ le := (≤),
lt := λ r s, r ≤ s ∧ ¬s ≤ r,
le_refl := λ _ _ _, id,
le_trans := λ _ _ _ hr hs _ _ h, hs $ hr h,
lt_iff_le_not_le := λ _ _, iff.rfl,
le_antisymm := λ r s h1 h2, setoid.ext' $ λ x y, ⟨λ h, h1 h, λ h, h2 h⟩ }
/-- The complete lattice of equivalence relations on a type, with bottom element `=`
and top element the trivial equivalence relation. -/
instance complete_lattice : complete_lattice (setoid α) :=
{ inf := has_inf.inf,
inf_le_left := λ _ _ _ _ h, h.1,
inf_le_right := λ _ _ _ _ h, h.2,
le_inf := λ _ _ _ h1 h2 _ _ h, ⟨h1 h, h2 h⟩,
top := ⟨λ _ _, true, ⟨λ _, trivial, λ _ _ h, h, λ _ _ _ h1 h2, h1⟩⟩,
le_top := λ _ _ _ _, trivial,
bot := ⟨(=), ⟨λ _, rfl, λ _ _ h, h.symm, λ _ _ _ h1 h2, h1.trans h2⟩⟩,
bot_le := λ r x y h, h ▸ r.2.1 x,
.. complete_lattice_of_Inf (setoid α) $ assume s,
⟨λ r hr x y h, h _ hr, λ r hr x y h r' hr', hr hr' h⟩ }
@[simp]
lemma top_def : (⊤ : setoid α).rel = ⊤ := rfl
@[simp]
lemma bot_def : (⊥ : setoid α).rel = (=) := rfl
lemma eq_top_iff {s : setoid α} : s = (⊤ : setoid α) ↔ ∀ x y : α, s.rel x y :=
by simp [eq_top_iff, setoid.le_def, setoid.top_def, pi.top_apply]
/-- The inductively defined equivalence closure of a binary relation r is the infimum
of the set of all equivalence relations containing r. -/
theorem eqv_gen_eq (r : α → α → Prop) :
eqv_gen.setoid r = Inf {s : setoid α | ∀ ⦃x y⦄, r x y → s.rel x y} :=
le_antisymm
(λ _ _ H, eqv_gen.rec (λ _ _ h _ hs, hs h) (refl' _)
(λ _ _ _, symm' _) (λ _ _ _ _ _, trans' _) H)
(Inf_le $ λ _ _ h, eqv_gen.rel _ _ h)
/-- The supremum of two equivalence relations r and s is the equivalence closure of the binary
relation `x is related to y by r or s`. -/
lemma sup_eq_eqv_gen (r s : setoid α) :
r ⊔ s = eqv_gen.setoid (λ x y, r.rel x y ∨ s.rel x y) :=
begin
rw eqv_gen_eq,
apply congr_arg Inf,
simp only [le_def, or_imp_distrib, ← forall_and_distrib]
end
/-- The supremum of 2 equivalence relations r and s is the equivalence closure of the
supremum of the underlying binary operations. -/
lemma sup_def {r s : setoid α} : r ⊔ s = eqv_gen.setoid (r.rel ⊔ s.rel) :=
by rw sup_eq_eqv_gen; refl
/-- The supremum of a set S of equivalence relations is the equivalence closure of the binary
relation `there exists r ∈ S relating x and y`. -/
lemma Sup_eq_eqv_gen (S : set (setoid α)) :
Sup S = eqv_gen.setoid (λ x y, ∃ r : setoid α, r ∈ S ∧ r.rel x y) :=
begin
rw eqv_gen_eq,
apply congr_arg Inf,
simp only [upper_bounds, le_def, and_imp, exists_imp_distrib],
ext,
exact ⟨λ H x y r hr, H hr, λ H r hr x y, H r hr⟩
end
/-- The supremum of a set of equivalence relations is the equivalence closure of the
supremum of the set's image under the map to the underlying binary operation. -/
lemma Sup_def {s : set (setoid α)} : Sup s = eqv_gen.setoid (Sup (rel '' s)) :=
begin
rw [Sup_eq_eqv_gen, Sup_image],
congr' with x y,
simp only [supr_apply, supr_Prop_eq, exists_prop]
end
/-- The equivalence closure of an equivalence relation r is r. -/
@[simp] lemma eqv_gen_of_setoid (r : setoid α) : eqv_gen.setoid r.r = r :=
le_antisymm (by rw eqv_gen_eq; exact Inf_le (λ _ _, id)) eqv_gen.rel
/-- Equivalence closure is idempotent. -/
@[simp] lemma eqv_gen_idem (r : α → α → Prop) :
eqv_gen.setoid (eqv_gen.setoid r).rel = eqv_gen.setoid r :=
eqv_gen_of_setoid _
/-- The equivalence closure of a binary relation r is contained in any equivalence
relation containing r. -/
theorem eqv_gen_le {r : α → α → Prop} {s : setoid α} (h : ∀ x y, r x y → s.rel x y) :
eqv_gen.setoid r ≤ s :=
by rw eqv_gen_eq; exact Inf_le h
/-- Equivalence closure of binary relations is monotone. -/
theorem eqv_gen_mono {r s : α → α → Prop} (h : ∀ x y, r x y → s x y) :
eqv_gen.setoid r ≤ eqv_gen.setoid s :=
eqv_gen_le $ λ _ _ hr, eqv_gen.rel _ _ $ h _ _ hr
/-- There is a Galois insertion of equivalence relations on α into binary relations
on α, with equivalence closure the lower adjoint. -/
def gi : @galois_insertion (α → α → Prop) (setoid α) _ _ eqv_gen.setoid rel :=
{ choice := λ r h, eqv_gen.setoid r,
gc := λ r s, ⟨λ H _ _ h, H $ eqv_gen.rel _ _ h, λ H, eqv_gen_of_setoid s ▸ eqv_gen_mono H⟩,
le_l_u := λ x, (eqv_gen_of_setoid x).symm ▸ le_refl x,
choice_eq := λ _ _, rfl }
open function
/-- A function from α to β is injective iff its kernel is the bottom element of the complete lattice
of equivalence relations on α. -/
theorem injective_iff_ker_bot (f : α → β) :
injective f ↔ ker f = ⊥ :=
(@eq_bot_iff (setoid α) _ _ (ker f)).symm
/-- The elements related to x ∈ α by the kernel of f are those in the preimage of f(x) under f. -/
lemma ker_iff_mem_preimage {f : α → β} {x y} : (ker f).rel x y ↔ x ∈ f ⁻¹' {f y} :=
iff.rfl
/-- Equivalence between functions `α → β` such that `r x y → f x = f y` and functions
`quotient r → β`. -/
def lift_equiv (r : setoid α) : {f : α → β // r ≤ ker f} ≃ (quotient r → β) :=
{ to_fun := λ f, quotient.lift (f : α → β) f.2,
inv_fun := λ f, ⟨f ∘ quotient.mk, λ x y h, by simp [ker_def, quotient.sound h]⟩,
left_inv := λ ⟨f, hf⟩, subtype.eq $ funext $ λ x, rfl,
right_inv := λ f, funext $ λ x, quotient.induction_on' x $ λ x, rfl }
/-- The uniqueness part of the universal property for quotients of an arbitrary type. -/
theorem lift_unique {r : setoid α} {f : α → β} (H : r ≤ ker f) (g : quotient r → β)
(Hg : f = g ∘ quotient.mk) : quotient.lift f H = g :=
begin
ext ⟨x⟩,
erw [quotient.lift_mk f H, Hg],
refl
end
/-- Given a map f from α to β, the natural map from the quotient of α by the kernel of f is
injective. -/
lemma ker_lift_injective (f : α → β) : injective (@quotient.lift _ _ (ker f) f (λ _ _ h, h)) :=
λ x y, quotient.induction_on₂' x y $ λ a b h, quotient.sound' h
/-- Given a map f from α to β, the kernel of f is the unique equivalence relation on α whose
induced map from the quotient of α to β is injective. -/
lemma ker_eq_lift_of_injective {r : setoid α} (f : α → β) (H : ∀ x y, r.rel x y → f x = f y)
(h : injective (quotient.lift f H)) : ker f = r :=
le_antisymm
(λ x y hk, quotient.exact $ h $ show quotient.lift f H ⟦x⟧ = quotient.lift f H ⟦y⟧, from hk)
H
variables (r : setoid α) (f : α → β)
/-- The first isomorphism theorem for sets: the quotient of α by the kernel of a function f
bijects with f's image. -/
noncomputable def quotient_ker_equiv_range :
quotient (ker f) ≃ set.range f :=
equiv.of_bijective (@quotient.lift _ (set.range f) (ker f)
(λ x, ⟨f x, set.mem_range_self x⟩) $ λ _ _ h, subtype.ext_val h)
⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections,
λ ⟨w, z, hz⟩, ⟨@quotient.mk _ (ker f) z, by rw quotient.lift_mk; exact subtype.ext_iff_val.2 hz⟩⟩
/-- If `f` has a computable right-inverse, then the quotient by its kernel is equivalent to its
domain. -/
@[simps]
def quotient_ker_equiv_of_right_inverse (g : β → α) (hf : function.right_inverse g f) :
quotient (ker f) ≃ β :=
{ to_fun := λ a, quotient.lift_on' a f $ λ _ _, id,
inv_fun := λ b, quotient.mk' (g b),
left_inv := λ a, quotient.induction_on' a $ λ a, quotient.sound' $ by exact hf (f a),
right_inv := hf }
/-- The quotient of α by the kernel of a surjective function f bijects with f's codomain.
If a specific right-inverse of `f` is known, `setoid.quotient_ker_equiv_of_right_inverse` can be
definitionally more useful. -/
noncomputable def quotient_ker_equiv_of_surjective (hf : surjective f) :
quotient (ker f) ≃ β :=
quotient_ker_equiv_of_right_inverse _ (function.surj_inv hf) (right_inverse_surj_inv hf)
variables {r f}
/-- Given a function `f : α → β` and equivalence relation `r` on `α`, the equivalence
closure of the relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are
related to the elements of `f⁻¹(y)` by `r`.' -/
def map (r : setoid α) (f : α → β) : setoid β :=
eqv_gen.setoid $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ r.rel a b
/-- Given a surjective function f whose kernel is contained in an equivalence relation r, the
equivalence relation on f's codomain defined by x ≈ y ↔ the elements of f⁻¹(x) are related to
the elements of f⁻¹(y) by r. -/
def map_of_surjective (r) (f : α → β) (h : ker f ≤ r) (hf : surjective f) :
setoid β :=
⟨λ x y, ∃ a b, f a = x ∧ f b = y ∧ r.rel a b,
⟨λ x, let ⟨y, hy⟩ := hf x in ⟨y, y, hy, hy, r.refl' y⟩,
λ _ _ ⟨x, y, hx, hy, h⟩, ⟨y, x, hy, hx, r.symm' h⟩,
λ _ _ _ ⟨x, y, hx, hy, h₁⟩ ⟨y', z, hy', hz, h₂⟩,
⟨x, z, hx, hz, r.trans' h₁ $ r.trans' (h $ by rwa ←hy' at hy) h₂⟩⟩⟩
/-- A special case of the equivalence closure of an equivalence relation r equalling r. -/
lemma map_of_surjective_eq_map (h : ker f ≤ r) (hf : surjective f) :
map r f = map_of_surjective r f h hf :=
by rw ←eqv_gen_of_setoid (map_of_surjective r f h hf); refl
/-- Given a function `f : α → β`, an equivalence relation `r` on `β` induces an equivalence
relation on `α` defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `r`'.
See note [reducible non-instances]. -/
@[reducible]
def comap (f : α → β) (r : setoid β) : setoid α :=
⟨r.rel on f, r.iseqv.comap _⟩
lemma comap_rel (f : α → β) (r : setoid β) (x y : α) : (comap f r).rel x y ↔ r.rel (f x) (f y) :=
iff.rfl
/-- Given a map `f : N → M` and an equivalence relation `r` on `β`, the equivalence relation
induced on `α` by `f` equals the kernel of `r`'s quotient map composed with `f`. -/
lemma comap_eq {f : α → β} {r : setoid β} : comap f r = ker (@quotient.mk _ r ∘ f) :=
ext $ λ x y, show _ ↔ ⟦_⟧ = ⟦_⟧, by rw quotient.eq; refl
/-- The second isomorphism theorem for sets. -/
noncomputable def comap_quotient_equiv (f : α → β) (r : setoid β) :
quotient (comap f r) ≃ set.range (@quotient.mk _ r ∘ f) :=
(quotient.congr_right $ ext_iff.1 comap_eq).trans $ quotient_ker_equiv_range $ quotient.mk ∘ f
variables (r f)
/-- The third isomorphism theorem for sets. -/
def quotient_quotient_equiv_quotient (s : setoid α) (h : r ≤ s) :
quotient (ker (quot.map_right h)) ≃ quotient s :=
{ to_fun := λ x, quotient.lift_on' x (λ w, quotient.lift_on' w (@quotient.mk _ s) $
λ x y H, quotient.sound $ h H) $ λ x y, quotient.induction_on₂' x y $ λ w z H,
show @quot.mk _ _ _ = @quot.mk _ _ _, from H,
inv_fun := λ x, quotient.lift_on' x
(λ w, @quotient.mk _ (ker $ quot.map_right h) $ @quotient.mk _ r w) $
λ x y H, quotient.sound' $ show @quot.mk _ _ _ = @quot.mk _ _ _, from quotient.sound H,
left_inv := λ x, quotient.induction_on' x $ λ y, quotient.induction_on' y $
λ w, by show ⟦_⟧ = _; refl,
right_inv := λ x, quotient.induction_on' x $ λ y, by show ⟦_⟧ = _; refl }
variables {r f}
open quotient
/-- Given an equivalence relation `r` on `α`, the order-preserving bijection between the set of
equivalence relations containing `r` and the equivalence relations on the quotient of `α` by `r`. -/
def correspondence (r : setoid α) : {s // r ≤ s} ≃o setoid (quotient r) :=
{ to_fun := λ s, map_of_surjective s.1 quotient.mk ((ker_mk_eq r).symm ▸ s.2) exists_rep,
inv_fun := λ s, ⟨comap quotient.mk' s, λ x y h, by rw [comap_rel, eq_rel.2 h]⟩,
left_inv := λ s, subtype.ext_iff_val.2 $ ext' $ λ _ _,
⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in
s.1.trans' (s.1.symm' $ s.2 $ eq_rel.1 hx) $ s.1.trans' H $ s.2 $ eq_rel.1 hy,
λ h, ⟨_, _, rfl, rfl, h⟩⟩,
right_inv := λ s, let Hm : ker quotient.mk' ≤ comap quotient.mk' s :=
λ x y h, by rw [comap_rel, (@eq_rel _ r x y).2 ((ker_mk_eq r) ▸ h)] in
ext' $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H,
quotient.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩,
map_rel_iff' := λ s t, ⟨λ h x y hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨x, y, rfl, rfl, hs⟩ in
t.1.trans' (t.1.symm' $ t.2 $ eq_rel.1 hx) $ t.1.trans' ht $ t.2 $ eq_rel.1 hy,
λ h x y hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩⟩ }
end setoid
@[simp]
lemma quotient.subsingleton_iff {s : setoid α} :
subsingleton (quotient s) ↔ s = ⊤ :=
begin
simp only [subsingleton_iff, eq_top_iff, setoid.le_def, setoid.top_def,
pi.top_apply, forall_const],
refine (surjective_quotient_mk _).forall.trans (forall_congr $ λ a, _),
refine (surjective_quotient_mk _).forall.trans (forall_congr $ λ b, _),
exact quotient.eq',
end
lemma quot.subsingleton_iff (r : α → α → Prop) : subsingleton (quot r) ↔ eqv_gen r = ⊤ :=
begin
simp only [subsingleton_iff, _root_.eq_top_iff, pi.le_def, pi.top_apply, forall_const],
refine (surjective_quot_mk _).forall.trans (forall_congr $ λ a, _),
refine (surjective_quot_mk _).forall.trans (forall_congr $ λ b, _),
rw quot.eq,
simp only [forall_const, le_Prop_eq],
end
|
952573df40ee3fdfa0dedd8049d2400fb78bc6c4 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/interactive/hole2.lean | 10e26363b4115b4e645b6bd7b836e1d1c72b5b64 | [
"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 | 77 | lean | def x : nat → nat :=
λ a, {! a + a !}
--^ "command": "hole_commands"
|
553530b88970182b4d984f50b8243ae31dabe029 | 96338d06deb5f54f351493a71d6ecf6c546089a2 | /priv/Lean/Initial.lean | d4ebc3b48a5b769316c54a9c4260f1d2da6a8aa1 | [] | no_license | silky/exe | 5f9e4eea772d74852a1a2fac57d8d20588282d2b | e81690d6e16f2a83c105cce446011af6ae905b81 | refs/heads/master | 1,609,385,766,412 | 1,472,164,223,000 | 1,472,164,223,000 | 66,610,224 | 1 | 0 | null | 1,472,178,919,000 | 1,472,178,919,000 | null | UTF-8 | Lean | false | false | 5,754 | lean | /- Initial -/
import Setoid
import Cat
import Mor
import Functor
import Adjunction
set_option pp.universes true
set_option pp.metavar_args false
namespace EXE
record InitialType (C : CatType) (Obj : C) : Type :=
(Cone : Functor.ConeType Obj 𝟙)
(IsCone : Functor.IsConeProp Obj 𝟙 Cone)
(Ok : Cone Obj ≡(Obj ⇒C⇒ Obj)≡ ①)
-- print InitialType
namespace Initial
abbreviation Mk {C : CatType} {Obj : C} :=
@InitialType.mk C Obj
lemma Singleton {C : CatType} {I : C}
(init : InitialType C I) (X : C)
: Setoid.SingletonType (I ⇒C⇒ X) :=
Setoid.MkSingleton
( InitialType.Cone init X)
( λ(f : I ⇒C⇒ X),
(InitialType.IsCone init f) ⊡_⊡
(f ⊙C⊙/ (InitialType.Ok init)) ⊡_⊡
(CatType.UnitR C f) )
definition FromLim.{o1 h1} {C : CatType.{o1 h1}}
(lim : HaveAllLim.{o1 h1 o1 h1} C)
: C :=
Lim.Apply lim 𝟙
print FromLim
definition FromLim.Ok.{o1 h1} {C : CatType.{o1 h1}}
(lim : HaveAllLim.{o1 h1 o1 h1} C)
: InitialType C ((RightAdj.Right (lim C)) $$ 𝟙) := -- (Lim.Apply lim 𝟙)
proof Mk
( λ X, ((AdjType.counit (RightAdj.adj (lim C))) /$$ 𝟙) /$$ X)
( λ A B, λ(m : A ⇒C⇒ B),
(CatType.UnitRInv C ((((AdjType.counit (RightAdj.adj (lim C))) /$$ 𝟙)) /$$ B))
⊡(((RightAdj.Right (lim C)) $$ 𝟙) ⇒C⇒ B)⊡
(((AdjType.counit (RightAdj.adj (lim C))) /$$ 𝟙) /$$/ m) )
begin
have eqNat :
(((AdjType.counit (RightAdj.adj (lim C))) /$$ 𝟙) ⊙(C⟶C)⊙
((Cat.Delta C C) $$/
(((AdjType.counit (RightAdj.adj (lim C))) /$$ 𝟙) /$$ ((RightAdj.Right (lim C)) $$ 𝟙))))
≡((Cat.Delta C C ((RightAdj.Right (lim C)) $$ 𝟙)) ⟹ 𝟙)≡
(((AdjType.counit (RightAdj.adj (lim C))) /$$ 𝟙) ⊙(C⟶C)⊙
①),
from λ(X : C), proof
SetoidType.Sym (((RightAdj.Right (lim C)) $$ 𝟙) ⇒C⇒ X)
(((AdjType.counit (RightAdj.adj (lim C))) /$$ 𝟙) /$$/
(((AdjType.counit (RightAdj.adj (lim C))) /$$ 𝟙) /$$ X))
qed,
have myCong : ∀ {g1 g2 : (Cat.Delta C C ((RightAdj.Right (lim C)) $$ 𝟙)) ⟹ 𝟙},
∀ (eq : g1 ≡((Cat.Delta C C ((RightAdj.Right (lim C)) $$ 𝟙)) ⟹ 𝟙)≡ g2),
( (((RightAdj.Right (lim C)) $$/ g1) ⊙C⊙
((AdjType.unit (RightAdj.adj (lim C))) /$$ ((RightAdj.Right (lim C)) $$ 𝟙)))
≡(((RightAdj.Right (lim C)) $$ 𝟙) ⇒C⇒ ((RightAdj.Right (lim C)) $$ 𝟙))≡
(((RightAdj.Right (lim C)) $$/ g2) ⊙C⊙
((AdjType.unit (RightAdj.adj (lim C))) /$$ ((RightAdj.Right (lim C)) $$ 𝟙))) ),
from
λ (g1 g2 : (Cat.Delta C C ((RightAdj.Right (lim C)) $$ 𝟙)) ⟹ 𝟙),
λ (eq : g1 ≡((Cat.Delta C C ((RightAdj.Right (lim C)) $$ 𝟙)) ⟹ 𝟙)≡ g2),
proof
((RightAdj.Right (lim C)) $$// eq) /⊙C⊙
((AdjType.unit (RightAdj.adj (lim C))) /$$ ((RightAdj.Right (lim C)) $$ 𝟙))
qed,
show (
(((AdjType.counit (RightAdj.adj (lim C))) /$$ 𝟙) /$$ ((RightAdj.Right (lim C)) $$ 𝟙))
≡(((RightAdj.Right (lim C)) $$ 𝟙) ⇒C⇒ ((RightAdj.Right (lim C)) $$ 𝟙))≡
①),
from proof
(SetoidType.Sym (((RightAdj.Right (lim C)) $$ 𝟙) ⇒C⇒ ((RightAdj.Right (lim C)) $$ 𝟙))
((Adj.IsoOnLR.ReqR (RightAdj.adj (lim C))
((RightAdj.Right (lim C)) $$ 𝟙) 𝟙)
(((AdjType.counit (RightAdj.adj (lim C))) /$$ 𝟙) /$$ ((RightAdj.Right (lim C)) $$ 𝟙)))
)
⊡(((RightAdj.Right (lim C)) $$ 𝟙) ⇒C⇒ ((RightAdj.Right (lim C)) $$ 𝟙))⊡
(myCong eqNat)
⊡(((RightAdj.Right (lim C)) $$ 𝟙) ⇒C⇒ ((RightAdj.Right (lim C)) $$ 𝟙))⊡
((Adj.IsoOnLR.ReqR (RightAdj.adj (lim C))
((RightAdj.Right (lim C)) $$ 𝟙) 𝟙)
①)
qed
end
qed
end Initial
record TerminalType (C : CatType) (Obj : C) : Type :=
(Cocone : Functor.CoconeType 𝟙 Obj)
(IsCocone : Functor.IsCoconeProp 𝟙 Obj Cocone)
(Ok : Cocone Obj ≡(Obj ⇒C⇒ Obj)≡ ①)
namespace Terminal
abbreviation Mk {C : CatType} {Obj : C} :=
@TerminalType.mk C Obj
lemma Singleton {C : CatType} {T : C} (term : TerminalType C T) (X : C)
: Setoid.SingletonType (X ⇒C⇒ T) :=
Setoid.MkSingleton
( TerminalType.Cocone term X)
( λ(g : X ⇒C⇒ T),
(SetoidType.Sym _ (TerminalType.IsCocone term g)) ⊡_⊡
((TerminalType.Ok term) /⊙C⊙ g) ⊡_⊡
(CatType.UnitL C g))
definition FromColim.{o1 h1} {C : CatType.{o1 h1}}
(colim : HaveAllColim.{o1 h1 o1 h1} C)
: C
:= Colim.Apply colim 𝟙
/- -- actually, we do not need it now
definition FromColim.Ok {C : CatType.{o1 h1}}
(colim : HaveAllColim.{o1 h1 o1 h1} C)
: TerminalType C (FromColim colim)
:= sorry
-/
-- TODO: limit of empty is terminal (actually need it!)
end Terminal
end EXE
|
e647ece4dd45cf8169909f431226e7f5d5985e0c | a726f88081e44db9edfd14d32cfe9c4393ee56a4 | /src/solutions/world3_le.lean | 2c334ab17be1e22a4673ffbb29aefa604a18cfd8 | [] | no_license | b-mehta/natural_number_game | 80451bf10277adc89a55dbe8581692c36d822462 | 9faf799d0ab48ecbc89b3d70babb65ba64beee3b | refs/heads/master | 1,598,525,389,186 | 1,573,516,674,000 | 1,573,516,674,000 | 217,339,684 | 0 | 0 | null | 1,571,933,100,000 | 1,571,933,099,000 | null | UTF-8 | Lean | false | false | 9,105 | lean | import mynat.le
import solutions.world2_multiplication
import tactic.interactive
-- #check tactic.interactive.rintro
meta def less_leaky.interactive.rintro := tactic.interactive.rintro
namespace mynat
theorem le_refl (a : mynat) : a ≤ a :=
begin
use 0,
rw add_zero,
end
-- ignore this; it's making the "refl" tactic work with goals of the form a ≤ a
attribute [_refl_lemma] le_refl
theorem le_succ {a b : mynat} (h : a ≤ b) : a ≤ (succ b) :=
begin
cases h with c hc,
use (succ c),
rw add_succ,
rw hc,
end
example : one ≤ one := le_refl one
lemma zero_le (a : mynat) : 0 ≤ a :=
begin
use a,
rw' zero_add a,
refl
end
lemma le_zero {a : mynat} : a ≤ 0 → a = 0 :=
begin
intro h,
cases h with c hc,
rw add_comm at hc,
cases a with b,
refl,
exfalso,
rw add_succ at hc,
rw eq_comm at hc,
exact succ_ne_zero hc,
end
theorem le_trans ⦃a b c : mynat⦄ (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c :=
begin
-- again no induction
cases hab with x hx,
cases hbc with y hy,
use (x + y),
rw ←add_assoc,
rw ←hx,
assumption,
end
instance : preorder mynat := by structure_helper
theorem lt_iff_le_not_le {a b : mynat} : a < b ↔ a ≤ b ∧ ¬ b ≤ a := iff.rfl
theorem le_antisymm : ∀ {{a b : mynat}}, a ≤ b → b ≤ a → a = b :=
begin
intros a b hab hba,
cases hab with c hc,
cases hba with d hd,
rw hc at hd,
rw add_assoc at hd,
rw eq_comm at hd,
have H := eq_zero_of_add_right_eq_self hd,
rw eq_comm at hc,
convert hc,
symmetry,
convert add_zero a,
exact add_right_eq_zero H,
end
instance : partial_order mynat := by structure_helper
theorem lt_iff_le_and_ne ⦃a b : mynat⦄ : a < b ↔ a ≤ b ∧ a ≠ b :=
begin
split,
{ intro h,
rw lt_iff_le_not_le at h,
cases h with hab hba,
split, exact hab,
intro h,
apply hba,
rw' h,
apply le_refl,
},
{ intro h,
cases h with hab hne,
rw lt_iff_le_not_le,
split, assumption,
intro hba,
apply hne,
apply le_antisymm hab hba,
}
end
lemma succ_le_succ {a b : mynat} (h : a ≤ b) : succ a ≤ succ b :=
begin
cases h with c hc,
use c,
rw succ_add,
rw hc,
end
theorem le_total (a b : mynat) : a ≤ b ∨ b ≤ a :=
begin
revert a,
induction' b with c hc,
intro a, right, apply zero_le,
intro a,
induction' a with d hd,
left, apply zero_le,
cases hc d with h h,
left, exact succ_le_succ h,
right, exact succ_le_succ h,
end
instance : linear_order mynat := by structure_helper
theorem add_le_add_right (a b : mynat) : a ≤ b → ∀ t, (a + t) ≤ (b + t) :=
begin
intros h t,
induction' t with d hd,
{
rw add_zero, rw add_zero,
assumption
},
{
rw add_succ,
rw add_succ,
exact succ_le_succ hd
}
end
theorem le_succ_self (a : mynat) : a ≤ succ a :=
begin
apply le_succ,
apply le_refl
end
theorem le_of_succ_le_succ {a b : mynat} : succ a ≤ succ b → a ≤ b :=
begin
intro h,
cases h with c hc,
use c,
rw succ_add at hc,
exact succ_inj hc,
end
theorem not_succ_le_self {{d : mynat}} (h : succ d ≤ d) : false :=
begin
cases h with c hc,
rw ←add_one_eq_succ at hc,
rw add_assoc at hc,
rw eq_comm at hc,
have h := eq_zero_of_add_right_eq_self hc,
rw add_comm at h,
rw add_one_eq_succ at h,
apply zero_ne_succ c,
symmetry,
assumption,
end
theorem add_le_add_left :
∀ (a b : mynat), a ≤ b → ∀ (c : mynat), c + a ≤ c + b :=
begin
intros a b hab c,
rw add_comm,
rw add_comm c,
apply add_le_add_right,
assumption
end
def succ_le_succ_iff (a b : mynat) : succ a ≤ succ b ↔ a ≤ b :=
begin
split,
{ intro h,
cases h with c hc,
use c,
apply succ_inj,
convert hc,
rw' succ_add,
refl
},
{ intro h,
cases h with c hc,
use c,
rw succ_add,
rw' hc,
refl,
}
end
def succ_lt_succ_iff (a b : mynat) : succ a < succ b ↔ a < b :=
begin
rw lt_iff_le_not_le,
rw lt_iff_le_not_le,
split,
intro h,
cases h,
split,
rwa succ_le_succ_iff at h_left,
intro h, apply h_right,
rwa succ_le_succ_iff,
intro h,
cases h,
split,
rwa succ_le_succ_iff,
intro h, apply h_right,
rwa succ_le_succ_iff at h,
end
theorem lt_of_add_lt_add_left : ∀ {{a b c : mynat}}, a + b < a + c → b < c :=
begin
intros a b c,
intro h,
rw add_comm at h,
rw add_comm a at h,
revert b c,
induction a with d hd,
intros a b h, exact h,
intros b c h,
rw [add_succ, add_succ] at h,
apply hd,
rwa succ_lt_succ_iff at h,
end
theorem le_iff_exists_add : ∀ (a b : mynat), a ≤ b ↔ ∃ (c : mynat), b = a + c :=
begin
intros a b,
refl,
end
theorem zero_ne_one : (0 : mynat) ≠ 1 :=
begin
symmetry,
rw one_eq_succ_zero,
apply succ_ne_zero,
end
instance : ordered_comm_monoid mynat := by structure_helper
theorem le_of_add_le_add_left ⦃ a b c : mynat⦄ : a + b ≤ a + c → b ≤ c :=
begin
intro h,
cases h with d hd,
use d,
rw add_assoc at hd,
exact add_left_cancel hd
end
instance : ordered_cancel_comm_monoid mynat := by structure_helper
theorem mul_le_mul_of_nonneg_left ⦃a b c : mynat⦄ : a ≤ b → 0 ≤ c → c * a ≤ c * b :=
begin
intro hab,
intro hc,
cases hab with d hd,
rw hd,
use c * d,
rw' mul_add,
refl
end
theorem mul_le_mul_of_nonneg_right ⦃a b c : mynat⦄ : a ≤ b → 0 ≤ c → a * c ≤ b * c :=
begin
rw mul_comm,
rw mul_comm b,
apply mul_le_mul_of_nonneg_left
end
theorem ne_zero_of_pos ⦃a : mynat⦄ : 0 < a → a ≠ 0 :=
begin
intro ha,
intro h,
rw h at ha,
rw lt_iff_le_and_ne at ha,
cases ha with h1 h2,
apply h2,
refl,
end
theorem mul_lt_mul_of_pos_left ⦃a b c : mynat⦄ : a < b → 0 < c → c * a < c * b :=
begin
intros hab hc,
cases' hab with hab hba,
rw lt_iff_le_and_ne,
split,
{ cases hab with d hd,
use c * d,
rw hd,
rw' mul_add,
refl,
},
{ intro h,
apply hba,
have h2 := mul_left_cancel (ne_zero_of_pos hc) h,
rw' h2,
refl
}
end
theorem mul_lt_mul_of_pos_right ⦃a b c : mynat⦄ : a < b → 0 < c → a * c < b * c :=
begin
rw mul_comm,
rw mul_comm b,
apply mul_lt_mul_of_pos_left,
end
instance : ordered_semiring mynat := by structure_helper
theorem not_lt_zero ⦃a : mynat⦄ : ¬(a < 0) :=
begin [less_leaky]
-- rintro ⟨ha, hna⟩, -- *TODO* -- rintro doesn't work??
intro h,
cases h with ha hna,
apply hna, clear hna,
--apply le_zero at ha,
replace ha := le_zero ha,
rw ha,
refl,
end
#check @nat.lt_succ_iff
#check @nat.succ_eq_add_one
/-
nat.lt_succ_iff : ∀ {m n : ℕ}, m < nat.succ n ↔ m ≤ n
-/
theorem lt_succ_self (n : mynat) : n < succ n :=
begin [less_leaky]
rw lt_iff_le_and_ne,
split,
use 1,
apply succ_eq_add_one,
intro h,
exact ne_succ_self n h
end
theorem lt_succ_iff (m n : mynat) : m < succ n ↔ m ≤ n :=
begin [less_leaky]
rw lt_iff_le_and_ne,
split,
{ rintro ⟨h1, h2⟩,
cases h1 with c hc,
cases c with d,
exfalso,
apply h2,
rw hc,
rw add_zero,refl,
use d,
apply succ_inj,
rw hc,
apply add_succ,
},
{ rintro ⟨c, hc⟩,
split,
{ use succ c,
rw hc,
rw add_succ,
refl
},
{ rw hc,
apply ne_of_lt,
rw lt_iff_le_and_ne,
split,
use succ c,
rw add_succ,
refl,
intro h,
rw [succ_eq_add_one, add_assoc] at h,
-- doesn't' work yet
-- symmetry at h,
rw eq_comm at h,
replace h := eq_zero_of_add_right_eq_self h,
apply zero_ne_succ c,
rw ←h,
apply add_one_eq_succ
}
}
end
-- is this right?
@[elab_as_eliminator]
theorem strong_induction (P : mynat → Prop)
(IH : ∀ m : mynat, (∀ d : mynat, d < m → P d) → P m) :
∀ n, P n :=
begin [less_leaky]
let Q : mynat → Prop := λ m, ∀ d < m, P d,
have hQ : ∀ n, Q n,
{ intro n,
induction n with d hd,
{ intros m hm,
exfalso,
exact not_lt_zero hm,
},
{ intro m,
intro hm,
rw lt_succ_iff at hm,
apply IH,
intros e he,
apply hd,
exact lt_of_lt_of_le he hm,
}
},
intro n,
apply hQ (succ n),
apply lt_succ_self
end
lemma lt_irrefl (a : mynat) : ¬ (a < a) :=
begin
intro h,
rw lt_iff_le_and_ne at h,
cases h with h1 h2,
apply h2,
refl,
end
end mynat
/-
instance : canonically_ordered_comm_semiring mynat :=
{ add := (+),
add_assoc := add_assoc,
zero := 0,
zero_add := zero_add,
add_zero := add_zero,
add_comm := add_comm,
le := (≤),
le_refl := le_refl,
le_trans := le_trans,
le_antisymm := le_antisymm,
add_le_add_left := add_le_add_left,
lt_of_add_lt_add_left := lt_of_add_lt_add_left,
bot := 0,
bot_le := zero_le,
le_iff_exists_add := le_iff_exists_add,
mul := (*),
mul_assoc := mul_assoc,
one := 1,
one_mul := one_mul,
mul_one := mul_one,
left_distrib := left_distrib,
right_distrib := right_distrib,
zero_mul := zero_mul,
mul_zero := mul_zero,
mul_comm := mul_comm,
zero_ne_one := zero_ne_one,
mul_eq_zero_iff := mul_eq_zero_iff }
-/
|
463244b758c09f744d871be64ee5fc096fb57aca | 367134ba5a65885e863bdc4507601606690974c1 | /src/analysis/normed_space/mazur_ulam.lean | dc85e0fccea99033fe3384f26b29b059773c6bc3 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 6,369 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury Kudryashov
-/
import topology.instances.real_vector_space
import analysis.normed_space.add_torsor
import linear_algebra.affine_space.midpoint
import analysis.normed_space.linear_isometry
/-!
# Mazur-Ulam Theorem
Mazur-Ulam theorem states that an isometric bijection between two normed affine spaces over `ℝ` is
affine. We formalize it in three definitions:
* `isometric.to_real_linear_isometry_equiv_of_map_zero` : given `E ≃ᵢ F` sending `0` to `0`,
returns `E ≃ₗᵢ[ℝ] F` with the same `to_fun` and `inv_fun`;
* `isometric.to_real_linear_isometry_equiv` : given `f : E ≃ᵢ F`,
returns `g : E ≃ₗᵢ[ℝ] F` with `g x = f x - f 0`.
* `isometric.to_affine_equiv` : given `PE ≃ᵢ PF`, returns `g : PE ≃ᵃ[ℝ] PF` with the same
`to_equiv`.
The formalization is based on [Jussi Väisälä, *A Proof of the Mazur-Ulam Theorem*][Vaisala_2003].
## Tags
isometry, affine map, linear map
-/
variables
{E PE : Type*} [normed_group E] [normed_space ℝ E] [metric_space PE] [normed_add_torsor E PE]
{F PF : Type*} [normed_group F] [normed_space ℝ F] [metric_space PF] [normed_add_torsor F PF]
open set affine_map
noncomputable theory
namespace isometric
include E
/-- If an isometric self-homeomorphism of a normed vector space over `ℝ` fixes `x` and `y`,
then it fixes the midpoint of `[x, y]`. This is a lemma for a more general Mazur-Ulam theorem,
see below. -/
lemma midpoint_fixed {x y : PE} :
∀ e : PE ≃ᵢ PE, e x = x → e y = y → e (midpoint ℝ x y) = midpoint ℝ x y :=
begin
set z := midpoint ℝ x y,
-- Consider the set of `e : E ≃ᵢ E` such that `e x = x` and `e y = y`
set s := { e : PE ≃ᵢ PE | e x = x ∧ e y = y },
haveI : nonempty s := ⟨⟨isometric.refl PE, rfl, rfl⟩⟩,
-- On the one hand, `e` cannot send the midpoint `z` of `[x, y]` too far
have h_bdd : bdd_above (range $ λ e : s, dist (e z) z),
{ refine ⟨dist x z + dist x z, forall_range_iff.2 $ subtype.forall.2 _⟩,
rintro e ⟨hx, hy⟩,
calc dist (e z) z ≤ dist (e z) x + dist x z : dist_triangle (e z) x z
... = dist (e x) (e z) + dist x z : by rw [hx, dist_comm]
... = dist x z + dist x z : by erw [e.dist_eq x z] },
-- On the other hand, consider the map `f : (E ≃ᵢ E) → (E ≃ᵢ E)`
-- sending each `e` to `R ∘ e⁻¹ ∘ R ∘ e`, where `R` is the point reflection in the
-- midpoint `z` of `[x, y]`.
set R : PE ≃ᵢ PE := point_reflection z,
set f : (PE ≃ᵢ PE) → (PE ≃ᵢ PE) := λ e, ((e.trans R).trans e.symm).trans R,
-- Note that `f` doubles the value of ``dist (e z) z`
have hf_dist : ∀ e, dist (f e z) z = 2 * dist (e z) z,
{ intro e,
dsimp [f],
rw [dist_point_reflection_fixed, ← e.dist_eq, e.apply_symm_apply,
dist_point_reflection_self_real, dist_comm] },
-- Also note that `f` maps `s` to itself
have hf_maps_to : maps_to f s s,
{ rintros e ⟨hx, hy⟩,
split; simp [hx, hy, e.symm_apply_eq.2 hx.symm, e.symm_apply_eq.2 hy.symm], },
-- Therefore, `dist (e z) z = 0` for all `e ∈ s`.
set c := ⨆ e : s, dist (e z) z,
have : c ≤ c / 2,
{ apply csupr_le,
rintros ⟨e, he⟩,
simp only [coe_fn_coe_base, subtype.coe_mk, le_div_iff' (@zero_lt_two ℝ _ _), ← hf_dist],
exact le_csupr h_bdd ⟨f e, hf_maps_to he⟩ },
replace : c ≤ 0, { linarith },
refine λ e hx hy, dist_le_zero.1 (le_trans _ this),
exact le_csupr h_bdd ⟨e, hx, hy⟩
end
include F
/-- A bijective isometry sends midpoints to midpoints. -/
lemma map_midpoint (f : PE ≃ᵢ PF) (x y : PE) : f (midpoint ℝ x y) = midpoint ℝ (f x) (f y) :=
begin
set e : PE ≃ᵢ PE := ((f.trans $ point_reflection $ midpoint ℝ (f x) (f y)).trans f.symm).trans
(point_reflection $ midpoint ℝ x y),
have hx : e x = x, by simp,
have hy : e y = y, by simp,
have hm := e.midpoint_fixed hx hy,
simp only [e, trans_apply] at hm,
rwa [← eq_symm_apply, point_reflection_symm, point_reflection_self, symm_apply_eq,
point_reflection_fixed_iff ℝ] at hm,
apply_instance
end
/-!
Since `f : PE ≃ᵢ PF` sends midpoints to midpoints, it is an affine map.
We define a conversion to a `continuous_linear_equiv` first, then a conversion to an `affine_map`.
-/
/-- Mazur-Ulam Theorem: if `f` is an isometric bijection between two normed vector spaces
over `ℝ` and `f 0 = 0`, then `f` is a linear equivalence. -/
def to_real_linear_isometry_equiv_of_map_zero (f : E ≃ᵢ F) (h0 : f 0 = 0) :
E ≃ₗᵢ[ℝ] F :=
{ norm_map' := λ x, show ∥f x∥ = ∥x∥, by simp only [← dist_zero_right, ← h0, f.dist_eq],
.. ((add_monoid_hom.of_map_midpoint ℝ ℝ f h0 f.map_midpoint).to_real_linear_map f.continuous),
.. f }
@[simp] lemma coe_to_real_linear_equiv_of_map_zero (f : E ≃ᵢ F) (h0 : f 0 = 0) :
⇑(f.to_real_linear_isometry_equiv_of_map_zero h0) = f := rfl
@[simp] lemma coe_to_real_linear_equiv_of_map_zero_symm (f : E ≃ᵢ F) (h0 : f 0 = 0) :
⇑(f.to_real_linear_isometry_equiv_of_map_zero h0).symm = f.symm := rfl
/-- Mazur-Ulam Theorem: if `f` is an isometric bijection between two normed vector spaces
over `ℝ`, then `x ↦ f x - f 0` is a linear equivalence. -/
def to_real_linear_isometry_equiv (f : E ≃ᵢ F) : E ≃ₗᵢ[ℝ] F :=
(f.trans (isometric.add_right (f 0)).symm).to_real_linear_isometry_equiv_of_map_zero
(by simpa only [sub_eq_add_neg] using sub_self (f 0))
@[simp] lemma to_real_linear_equiv_apply (f : E ≃ᵢ F) (x : E) :
(f.to_real_linear_isometry_equiv : E → F) x = f x - f 0 :=
(sub_eq_add_neg (f x) (f 0)).symm
@[simp] lemma to_real_linear_isometry_equiv_symm_apply (f : E ≃ᵢ F) (y : F) :
(f.to_real_linear_isometry_equiv.symm : F → E) y = f.symm (y + f 0) := rfl
/-- Convert an isometric equivalence between two affine spaces to an `affine_map`. -/
def to_affine_equiv (f : PE ≃ᵢ PF) : PE ≃ᵃ[ℝ] PF :=
affine_equiv.mk' f.to_equiv
(((vadd_const (classical.arbitrary PE)).trans $ f.trans
(vadd_const (f $ classical.arbitrary PE)).symm).to_real_linear_isometry_equiv.to_linear_equiv)
(classical.arbitrary PE) (λ p, by simp)
@[simp] lemma coe_to_affine_equiv (f : PE ≃ᵢ PF) : ⇑f.to_affine_equiv = f := rfl
end isometric
|
ad1d12492c0ba3e77e5599ee1f23f0612c46bcd5 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/data/list/perm.lean | b17a98ba25f3a97171c38b4f69982f81e8e6b779 | [
"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 | 41,267 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro
List permutations.
-/
import data.list.bag_inter
import data.list.erase_dup
import data.list.zip
import logic.relation
namespace list
universe variables uu vv
variables {α : Type uu} {β : Type vv}
/-- `perm l₁ l₂` or `l₁ ~ l₂` asserts that `l₁` and `l₂` are permutations
of each other. This is defined by induction using pairwise swaps. -/
inductive perm : list α → list α → Prop
| nil : perm [] []
| skip : Π (x : α) {l₁ l₂ : list α}, perm l₁ l₂ → perm (x::l₁) (x::l₂)
| swap : Π (x y : α) (l : list α), perm (y::x::l) (x::y::l)
| trans : Π {l₁ l₂ l₃ : list α}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃
open perm
infix ~ := perm
@[refl] protected theorem perm.refl : ∀ (l : list α), l ~ l
| [] := perm.nil
| (x::xs) := skip x (perm.refl xs)
@[symm] protected theorem perm.symm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₂ ~ l₁ :=
perm.rec_on p
perm.nil
(λ x l₁ l₂ p₁ r₁, skip x r₁)
(λ x y l, swap y x l)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₂ r₁)
theorem perm.swap'
(x y : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : y::x::l₁ ~ x::y::l₂ :=
trans (swap _ _ _) (skip _ $ skip _ p)
attribute [trans] perm.trans
theorem perm.eqv (α) : equivalence (@perm α) :=
mk_equivalence (@perm α) (@perm.refl α) (@perm.symm α) (@perm.trans α)
instance is_setoid (α) : setoid (list α) :=
setoid.mk (@perm α) (perm.eqv α)
theorem perm_subset {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ ⊆ l₂ :=
λ a, perm.rec_on p
(λ h, h)
(λ x l₁ l₂ p₁ r₁ i, or.elim i
(λ ax, by simp [ax])
(λ al₁, or.inr (r₁ al₁)))
(λ x y l ayxl, or.elim ayxl
(λ ay, by simp [ay])
(λ axl, or.elim axl
(λ ax, by simp [ax])
(λ al, or.inr (or.inr al))))
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁))
theorem mem_of_perm {a : α} {l₁ l₂ : list α} (h : l₁ ~ l₂) : a ∈ l₁ ↔ a ∈ l₂ :=
iff.intro (λ m, perm_subset h m) (λ m, perm_subset h.symm m)
theorem perm_app_left {l₁ l₂ : list α} (t₁ : list α) (p : l₁ ~ l₂) : l₁++t₁ ~ l₂++t₁ :=
perm.rec_on p
(perm.refl ([] ++ t₁))
(λ x l₁ l₂ p₁ r₁, skip x r₁)
(λ x y l, swap x y _)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂)
theorem perm_app_right {t₁ t₂ : list α} : ∀ (l : list α), t₁ ~ t₂ → l++t₁ ~ l++t₂
| [] p := p
| (x::xs) p := skip x (perm_app_right xs p)
theorem perm_app {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁++t₁ ~ l₂++t₂ :=
trans (perm_app_left t₁ p₁) (perm_app_right l₂ p₂)
theorem perm_app_cons (a : α) {h₁ h₂ t₁ t₂ : list α}
(p₁ : h₁ ~ h₂) (p₂ : t₁ ~ t₂) : h₁ ++ a::t₁ ~ h₂ ++ a::t₂ :=
perm_app p₁ (skip a p₂)
@[simp] theorem perm_middle {a : α} : ∀ {l₁ l₂ : list α}, l₁++a::l₂ ~ a::(l₁++l₂)
| [] l₂ := perm.refl _
| (b::l₁) l₂ := (skip b (@perm_middle l₁ l₂)).trans (swap a b _)
@[simp] theorem perm_cons_app (a : α) (l : list α) : l ++ [a] ~ a::l :=
by simpa using @perm_middle _ a l []
@[simp] theorem perm_app_comm : ∀ {l₁ l₂ : list α}, (l₁++l₂) ~ (l₂++l₁)
| [] l₂ := by simp
| (a::t) l₂ := (skip a perm_app_comm).trans perm_middle.symm
theorem concat_perm (l : list α) (a : α) : concat l a ~ a :: l :=
by simp
theorem perm_length {l₁ l₂ : list α} (p : l₁ ~ l₂) : length l₁ = length l₂ :=
perm.rec_on p
rfl
(λ x l₁ l₂ p r, by simp[r])
(λ x y l, by simp)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂)
theorem eq_nil_of_perm_nil {l₁ : list α} (p : [] ~ l₁) : l₁ = [] :=
eq_nil_of_length_eq_zero (perm_length p).symm
theorem perm_nil {l₁ : list α} : l₁ ~ [] ↔ l₁ = [] :=
⟨λ p, eq_nil_of_perm_nil p.symm, λ e, e ▸ perm.refl _⟩
theorem not_perm_nil_cons (x : α) (l : list α) : ¬ [] ~ x::l
| p := by injection eq_nil_of_perm_nil p
theorem eq_singleton_of_perm {a b : α} (p : [a] ~ [b]) : a = b :=
by simpa using perm_subset p (by simp)
theorem eq_singleton_of_perm_inv {a : α} {l : list α} (p : [a] ~ l) : l = [a] :=
match l, show 1 = _, from perm_length p, p with
| [a'], rfl, p := by rw [eq_singleton_of_perm p]
end
@[simp] theorem reverse_perm : ∀ (l : list α), reverse l ~ l
| [] := perm.nil
| (a::l) := by rw reverse_cons; exact
(perm_cons_app _ _).trans (skip a $ reverse_perm l)
theorem perm_cons_app_cons {l l₁ l₂ : list α} (a : α) (p : l ~ l₁++l₂) : a::l ~ l₁++(a::l₂) :=
trans (skip a p) perm_middle.symm
@[simp] theorem perm_repeat {a : α} {n : ℕ} {l : list α} : repeat a n ~ l ↔ repeat a n = l :=
⟨λ p, (eq_repeat.2 $ by exact
⟨by simpa using (perm_length p).symm,
λ b m, eq_of_mem_repeat $ perm_subset p.symm m⟩).symm,
λ h, h ▸ perm.refl _⟩
theorem perm_erase [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : l ~ a :: l.erase a :=
let ⟨l₁, l₂, _, e₁, e₂⟩ := exists_erase_eq h in
e₂.symm ▸ e₁.symm ▸ perm_middle
@[elab_as_eliminator] theorem perm_induction_on
{P : list α → list α → Prop} {l₁ l₂ : list α} (p : l₁ ~ l₂)
(h₁ : P [] [])
(h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂))
(h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂))
(h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) :
P l₁ l₂ :=
have P_refl : ∀ l, P l l, from
assume l,
list.rec_on l h₁ (λ x xs ih, h₂ x xs xs (perm.refl xs) ih),
perm.rec_on p h₁ h₂ (λ x y l, h₃ x y l l (perm.refl l) (P_refl l)) h₄
@[congr] theorem perm_filter_map (f : α → option β) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
filter_map f l₁ ~ filter_map f l₂ :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂,
{ simp },
{ simp [filter_map], cases f x with a; simp [filter_map, IH, skip] },
{ simp [filter_map], cases f x with a; cases f y with b; simp [filter_map, swap] },
{ exact IH₁.trans IH₂ }
end
@[congr] theorem perm_map (f : α → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
map f l₁ ~ map f l₂ :=
by rw ← filter_map_eq_map; apply perm_filter_map _ p
theorem perm_pmap {p : α → Prop} (f : Π a, p a → β)
{l₁ l₂ : list α} (p : l₁ ~ l₂) {H₁ H₂} : pmap f l₁ H₁ ~ pmap f l₂ H₂ :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂,
{ simp },
{ simp [IH, skip] },
{ simp [swap] },
{ refine IH₁.trans IH₂,
exact λ a m, H₂ a (perm_subset p₂ m) }
end
theorem perm_filter (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} (s : l₁ ~ l₂) : filter p l₁ ~ filter p l₂ :=
by rw ← filter_map_eq_filter; apply perm_filter_map _ s
theorem exists_perm_sublist {l₁ l₂ l₂' : list α}
(s : l₁ <+ l₂) (p : l₂ ~ l₂') : ∃ l₁' ~ l₁, l₁' <+ l₂' :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂ generalizing l₁ s,
{ exact ⟨[], eq_nil_of_sublist_nil s ▸ perm.refl _, nil_sublist _⟩ },
{ cases s with _ _ _ s l₁ _ _ s,
{ exact let ⟨l₁', p', s'⟩ := IH s in ⟨l₁', p', s'.cons _ _ _⟩ },
{ exact let ⟨l₁', p', s'⟩ := IH s in ⟨x::l₁', skip x p', s'.cons2 _ _ _⟩ } },
{ cases s with _ _ _ s l₁ _ _ s; cases s with _ _ _ s l₁ _ _ s,
{ exact ⟨l₁, perm.refl _, (s.cons _ _ _).cons _ _ _⟩ },
{ exact ⟨x::l₁, perm.refl _, (s.cons _ _ _).cons2 _ _ _⟩ },
{ exact ⟨y::l₁, perm.refl _, (s.cons2 _ _ _).cons _ _ _⟩ },
{ exact ⟨x::y::l₁, perm.swap _ _ _, (s.cons2 _ _ _).cons2 _ _ _⟩ } },
{ exact let ⟨m₁, pm, sm⟩ := IH₁ s, ⟨r₁, pr, sr⟩ := IH₂ sm in
⟨r₁, pr.trans pm, sr⟩ }
end
section rel
open relator
variables {γ : Type*} {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
local infixr ` ∘r ` : 80 := relation.comp
lemma perm_comp_perm : (perm ∘r perm : list α → list α → Prop) = perm :=
begin
funext a c, apply propext,
split,
{ exact assume ⟨b, hab, hba⟩, perm.trans hab hba },
{ exact assume h, ⟨a, perm.refl a, h⟩ }
end
lemma perm_comp_forall₂ {l u v} (hlu : perm l u) (huv : forall₂ r u v) : (forall₂ r ∘r perm) l v :=
begin
induction hlu generalizing v,
case perm.nil { cases huv, exact ⟨[], forall₂.nil, perm.nil⟩ },
case perm.skip : a l u hlu ih {
cases huv with _ b _ v hab huv',
rcases ih huv' with ⟨l₂, h₁₂, h₂₃⟩,
exact ⟨b::l₂, forall₂.cons hab h₁₂, perm.skip _ h₂₃⟩
},
case perm.swap : a₁ a₂ l₁ l₂ h₂₃ {
cases h₂₃ with _ b₁ _ l₂ h₁ hr_₂₃,
cases hr_₂₃ with _ b₂ _ l₂ h₂ h₁₂,
exact ⟨b₂::b₁::l₂, forall₂.cons h₂ (forall₂.cons h₁ h₁₂), perm.swap _ _ _⟩
},
case perm.trans : la₁ la₂ la₃ _ _ ih₁ ih₂ {
rcases ih₂ huv with ⟨lb₂, hab₂, h₂₃⟩,
rcases ih₁ hab₂ with ⟨lb₁, hab₁, h₁₂⟩,
exact ⟨lb₁, hab₁, perm.trans h₁₂ h₂₃⟩
}
end
lemma forall₂_comp_perm_eq_perm_comp_forall₂ : forall₂ r ∘r perm = perm ∘r forall₂ r :=
begin
funext l₁ l₃, apply propext,
split,
{ assume h, rcases h with ⟨l₂, h₁₂, h₂₃⟩,
have : forall₂ (flip r) l₂ l₁, from h₁₂.flip ,
rcases perm_comp_forall₂ h₂₃.symm this with ⟨l', h₁, h₂⟩,
exact ⟨l', h₂.symm, h₁.flip⟩ },
{ exact assume ⟨l₂, h₁₂, h₂₃⟩, perm_comp_forall₂ h₁₂ h₂₃ }
end
lemma rel_perm_imp (hr : right_unique r) : (forall₂ r ⇒ forall₂ r ⇒ implies) perm perm :=
assume a b h₁ c d h₂ h,
have (flip (forall₂ r) ∘r (perm ∘r forall₂ r)) b d, from ⟨a, h₁, c, h, h₂⟩,
have ((flip (forall₂ r) ∘r forall₂ r) ∘r perm) b d,
by rwa [← forall₂_comp_perm_eq_perm_comp_forall₂, ← relation.comp_assoc] at this,
let ⟨b', ⟨c', hbc, hcb⟩, hbd⟩ := this in
have b' = b, from right_unique_forall₂ @hr hcb hbc,
this ▸ hbd
lemma rel_perm (hr : bi_unique r) : (forall₂ r ⇒ forall₂ r ⇒ (↔)) perm perm :=
assume a b hab c d hcd, iff.intro
(rel_perm_imp hr.2 hab hcd)
(rel_perm_imp (assume a b c, left_unique_flip hr.1) hab.flip hcd.flip)
end rel
section subperm
/-- `subperm l₁ l₂`, denoted `l₁ <+~ l₂`, means that `l₁` is a sublist of
a permutation of `l₂`. This is an analogue of `l₁ ⊆ l₂` which respects
multiplicities of elements, and is used for the `≤` relation on multisets. -/
def subperm (l₁ l₂ : list α) : Prop := ∃ l ~ l₁, l <+ l₂
infix ` <+~ `:50 := subperm
theorem nil_subperm {l : list α} : [] <+~ l :=
⟨[], perm.nil, by simp⟩
theorem perm.subperm_left {l l₁ l₂ : list α} (p : l₁ ~ l₂) : l <+~ l₁ ↔ l <+~ l₂ :=
suffices ∀ {l₁ l₂ : list α}, l₁ ~ l₂ → l <+~ l₁ → l <+~ l₂,
from ⟨this p, this p.symm⟩,
λ l₁ l₂ p ⟨u, pu, su⟩,
let ⟨v, pv, sv⟩ := exists_perm_sublist su p in
⟨v, pv.trans pu, sv⟩
theorem perm.subperm_right {l₁ l₂ l : list α} (p : l₁ ~ l₂) : l₁ <+~ l ↔ l₂ <+~ l :=
⟨λ ⟨u, pu, su⟩, ⟨u, pu.trans p, su⟩,
λ ⟨u, pu, su⟩, ⟨u, pu.trans p.symm, su⟩⟩
theorem subperm_of_sublist {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁ <+~ l₂ :=
⟨l₁, perm.refl _, s⟩
theorem subperm_of_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ <+~ l₂ :=
⟨l₂, p.symm, sublist.refl _⟩
theorem subperm.refl (l : list α) : l <+~ l := subperm_of_perm (perm.refl _)
theorem subperm.trans {l₁ l₂ l₃ : list α} : l₁ <+~ l₂ → l₂ <+~ l₃ → l₁ <+~ l₃
| s ⟨l₂', p₂, s₂⟩ :=
let ⟨l₁', p₁, s₁⟩ := p₂.subperm_left.2 s in ⟨l₁', p₁, s₁.trans s₂⟩
theorem length_le_of_subperm {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ ≤ length l₂
| ⟨l, p, s⟩ := perm_length p ▸ length_le_of_sublist s
theorem subperm.perm_of_length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₂ ≤ length l₁ → l₁ ~ l₂
| ⟨l, p, s⟩ h :=
suffices l = l₂, from this ▸ p.symm,
eq_of_sublist_of_length_le s $ perm_length p.symm ▸ h
theorem subperm.antisymm {l₁ l₂ : list α} (h₁ : l₁ <+~ l₂) (h₂ : l₂ <+~ l₁) : l₁ ~ l₂ :=
h₁.perm_of_length_le (length_le_of_subperm h₂)
theorem subset_of_subperm {l₁ l₂ : list α} : l₁ <+~ l₂ → l₁ ⊆ l₂
| ⟨l, p, s⟩ := subset.trans (perm_subset p.symm) (subset_of_sublist s)
end subperm
theorem exists_perm_append_of_sublist : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → ∃ l, l₂ ~ l₁ ++ l
| ._ ._ sublist.slnil := ⟨nil, perm.refl _⟩
| ._ ._ (sublist.cons l₁ l₂ a s) :=
let ⟨l, p⟩ := exists_perm_append_of_sublist s in
⟨a::l, (skip a p).trans perm_middle.symm⟩
| ._ ._ (sublist.cons2 l₁ l₂ a s) :=
let ⟨l, p⟩ := exists_perm_append_of_sublist s in
⟨l, skip a p⟩
theorem perm_countp (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} (s : l₁ ~ l₂) : countp p l₁ = countp p l₂ :=
by rw [countp_eq_length_filter, countp_eq_length_filter];
exact perm_length (perm_filter _ s)
theorem countp_le_of_subperm (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} : l₁ <+~ l₂ → countp p l₁ ≤ countp p l₂
| ⟨l, p', s⟩ := perm_countp p p' ▸ countp_le_of_sublist s
theorem perm_count [decidable_eq α] {l₁ l₂ : list α}
(p : l₁ ~ l₂) (a) : count a l₁ = count a l₂ :=
perm_countp _ p
theorem count_le_of_subperm [decidable_eq α] {l₁ l₂ : list α}
(s : l₁ <+~ l₂) (a) : count a l₁ ≤ count a l₂ :=
countp_le_of_subperm _ s
theorem foldl_eq_of_perm {f : β → α → β} {l₁ l₂ : list α} (rcomm : right_commutative f) (p : l₁ ~ l₂) :
∀ b, foldl f b l₁ = foldl f b l₂ :=
perm_induction_on p
(λ b, rfl)
(λ x t₁ t₂ p r b, r (f b x))
(λ x y t₁ t₂ p r b, by simp; rw rcomm; exact r (f (f b x) y))
(λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ b, eq.trans (r₁ b) (r₂ b))
theorem foldr_eq_of_perm {f : α → β → β} {l₁ l₂ : list α} (lcomm : left_commutative f) (p : l₁ ~ l₂) :
∀ b, foldr f b l₁ = foldr f b l₂ :=
perm_induction_on p
(λ b, rfl)
(λ x t₁ t₂ p r b, by simp; rw [r b])
(λ x y t₁ t₂ p r b, by simp; rw [lcomm, r b])
(λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a))
lemma rec_heq_of_perm {β : list α → Sort*} {f : Πa l, β l → β (a::l)} {b : β []} {l l' : list α}
(hl : perm l l')
(f_congr : ∀{a l l' b b'}, perm l l' → b == b' → f a l b == f a l' b')
(f_swap : ∀{a a' l b}, f a (a'::l) (f a' l b) == f a' (a::l) (f a l b)) :
@list.rec α β b f l == @list.rec α β b f l' :=
begin
induction hl,
case list.perm.nil { refl },
case list.perm.skip : a l l' h ih { exact f_congr h ih },
case list.perm.swap : a a' l { exact f_swap },
case list.perm.trans : l₁ l₂ l₃ h₁ h₂ ih₁ ih₂ { exact heq.trans ih₁ ih₂ }
end
section
variables {op : α → α → α} [is_associative α op] [is_commutative α op]
local notation a * b := op a b
local notation l <*> a := foldl op a l
lemma fold_op_eq_of_perm {l₁ l₂ : list α} {a : α} (h : l₁ ~ l₂) : l₁ <*> a = l₂ <*> a :=
foldl_eq_of_perm (right_comm _ is_commutative.comm is_associative.assoc) h _
end
section comm_monoid
open list
variable [comm_monoid α]
@[to_additive]
lemma prod_eq_of_perm {l₁ l₂ : list α} (h : perm l₁ l₂) : prod l₁ = prod l₂ :=
by induction h; simp [*, mul_left_comm]
@[to_additive]
lemma prod_reverse (l : list α) : prod l.reverse = prod l :=
prod_eq_of_perm $ reverse_perm l
end comm_monoid
theorem perm_inv_core {a : α} {l₁ l₂ r₁ r₂ : list α} : l₁++a::r₁ ~ l₂++a::r₂ → l₁++r₁ ~ l₂++r₂ :=
begin
generalize e₁ : l₁++a::r₁ = s₁, generalize e₂ : l₂++a::r₂ = s₂,
intro p, revert l₁ l₂ r₁ r₂ e₁ e₂,
refine perm_induction_on p _ (λ x t₁ t₂ p IH, _) (λ x y t₁ t₂ p IH, _) (λ t₁ t₂ t₃ p₁ p₂ IH₁ IH₂, _);
intros l₁ l₂ r₁ r₂ e₁ e₂,
{ apply (not_mem_nil a).elim, rw ← e₁, simp },
{ cases l₁ with y l₁; cases l₂ with z l₂;
dsimp at e₁ e₂; injections; subst x,
{ substs t₁ t₂, exact p },
{ substs z t₁ t₂, exact p.trans perm_middle },
{ substs y t₁ t₂, exact perm_middle.symm.trans p },
{ substs z t₁ t₂, exact skip y (IH rfl rfl) } },
{ rcases l₁ with _|⟨y, _|⟨z, l₁⟩⟩; rcases l₂ with _|⟨u, _|⟨v, l₂⟩⟩;
dsimp at e₁ e₂; injections; substs x y,
{ substs r₁ r₂, exact skip a p },
{ substs r₁ r₂, exact skip u p },
{ substs r₁ v t₂, exact skip u (p.trans perm_middle) },
{ substs r₁ r₂, exact skip y p },
{ substs r₁ r₂ y u, exact skip a p },
{ substs r₁ u v t₂, exact (skip y $ p.trans perm_middle).trans (swap _ _ _) },
{ substs r₂ z t₁, exact skip y (perm_middle.symm.trans p) },
{ substs r₂ y z t₁, exact (swap _ _ _).trans (skip u $ perm_middle.symm.trans p) },
{ substs u v t₁ t₂, exact (IH rfl rfl).swap' _ _ } },
{ substs t₁ t₃,
have : a ∈ t₂ := perm_subset p₁ (by simp),
rcases mem_split this with ⟨l₂, r₂, e₂⟩,
subst t₂, exact (IH₁ rfl rfl).trans (IH₂ rfl rfl) }
end
theorem perm_cons_inv {a : α} {l₁ l₂ : list α} : a::l₁ ~ a::l₂ → l₁ ~ l₂ :=
@perm_inv_core _ _ [] [] _ _
theorem perm_cons (a : α) {l₁ l₂ : list α} : a::l₁ ~ a::l₂ ↔ l₁ ~ l₂ :=
⟨perm_cons_inv, skip a⟩
theorem perm_app_left_iff {l₁ l₂ : list α} : ∀ l, l++l₁ ~ l++l₂ ↔ l₁ ~ l₂
| [] := iff.rfl
| (a::l) := (perm_cons a).trans (perm_app_left_iff l)
theorem perm_app_right_iff {l₁ l₂ : list α} (l) : l₁++l ~ l₂++l ↔ l₁ ~ l₂ :=
⟨λ p, (perm_app_left_iff _).1 $ trans perm_app_comm $ trans p perm_app_comm,
perm_app_left _⟩
theorem perm_option_to_list {o₁ o₂ : option α} : o₁.to_list ~ o₂.to_list ↔ o₁ = o₂ :=
begin
refine ⟨λ p, _, λ e, e ▸ perm.refl _⟩,
cases o₁ with a; cases o₂ with b, {refl},
{ cases (perm_length p) },
{ cases (perm_length p) },
{ exact option.mem_to_list.1 ((mem_of_perm p).2 $ by simp) }
end
theorem subperm_cons (a : α) {l₁ l₂ : list α} : a::l₁ <+~ a::l₂ ↔ l₁ <+~ l₂ :=
⟨λ ⟨l, p, s⟩, begin
cases s with _ _ _ s' u _ _ s',
{ exact (p.subperm_left.2 $ subperm_of_sublist $ sublist_cons _ _).trans
(subperm_of_sublist s') },
{ exact ⟨u, perm_cons_inv p, s'⟩ }
end, λ ⟨l, p, s⟩, ⟨a::l, skip a p, s.cons2 _ _ _⟩⟩
theorem cons_subperm_of_mem {a : α} {l₁ l₂ : list α} (d₁ : nodup l₁) (h₁ : a ∉ l₁) (h₂ : a ∈ l₂)
(s : l₁ <+~ l₂) : a :: l₁ <+~ l₂ :=
begin
rcases s with ⟨l, p, s⟩,
induction s generalizing l₁,
case list.sublist.slnil { cases h₂ },
case list.sublist.cons : r₁ r₂ b s' ih {
simp at h₂,
cases h₂ with e m,
{ subst b, exact ⟨a::r₁, skip a p, s'.cons2 _ _ _⟩ },
{ rcases ih m d₁ h₁ p with ⟨t, p', s'⟩, exact ⟨t, p', s'.cons _ _ _⟩ } },
case list.sublist.cons2 : r₁ r₂ b s' ih {
have bm : b ∈ l₁ := (perm_subset p $ mem_cons_self _ _),
have am : a ∈ r₂ := h₂.resolve_left (λ e, h₁ $ e.symm ▸ bm),
rcases mem_split bm with ⟨t₁, t₂, rfl⟩,
have st : t₁ ++ t₂ <+ t₁ ++ b :: t₂ := by simp,
rcases ih am (nodup_of_sublist st d₁)
(mt (λ x, subset_of_sublist st x) h₁)
(perm_cons_inv $ p.trans perm_middle) with ⟨t, p', s'⟩,
exact ⟨b::t, (skip b p').trans $ (swap _ _ _).trans (skip a perm_middle.symm), s'.cons2 _ _ _⟩ }
end
theorem subperm_app_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+~ l++l₂ ↔ l₁ <+~ l₂
| [] := iff.rfl
| (a::l) := (subperm_cons a).trans (subperm_app_left l)
theorem subperm_app_right {l₁ l₂ : list α} (l) : l₁++l <+~ l₂++l ↔ l₁ <+~ l₂ :=
(perm_app_comm.subperm_left.trans perm_app_comm.subperm_right).trans (subperm_app_left l)
theorem subperm.exists_of_length_lt {l₁ l₂ : list α} :
l₁ <+~ l₂ → length l₁ < length l₂ → ∃ a, a :: l₁ <+~ l₂
| ⟨l, p, s⟩ h :=
suffices length l < length l₂ → ∃ (a : α), a :: l <+~ l₂, from
(this $ perm_length p.symm ▸ h).imp (λ a, (skip a p).subperm_right.1),
begin
clear subperm.exists_of_length_lt p h l₁, rename l₂ u,
induction s with l₁ l₂ a s IH _ _ b s IH; intro h,
{ cases h },
{ cases lt_or_eq_of_le (nat.le_of_lt_succ h : length l₁ ≤ length l₂) with h h,
{ exact (IH h).imp (λ a s, s.trans (subperm_of_sublist $ sublist_cons _ _)) },
{ exact ⟨a, eq_of_sublist_of_length_eq s h ▸ subperm.refl _⟩ } },
{ exact (IH $ nat.lt_of_succ_lt_succ h).imp
(λ a s, (swap _ _ _).subperm_right.1 $ (subperm_cons _).2 s) }
end
theorem subperm_of_subset_nodup
{l₁ l₂ : list α} (d : nodup l₁) (H : l₁ ⊆ l₂) : l₁ <+~ l₂ :=
begin
induction d with a l₁' h d IH,
{ exact ⟨nil, perm.nil, nil_sublist _⟩ },
{ cases forall_mem_cons.1 H with H₁ H₂,
simp at h,
exact cons_subperm_of_mem d h H₁ (IH H₂) }
end
theorem perm_ext {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) : l₁ ~ l₂ ↔ ∀a, a ∈ l₁ ↔ a ∈ l₂ :=
⟨λ p a, mem_of_perm p, λ H, subperm.antisymm
(subperm_of_subset_nodup d₁ (λ a, (H a).1))
(subperm_of_subset_nodup d₂ (λ a, (H a).2))⟩
theorem perm_ext_sublist_nodup {l₁ l₂ l : list α} (d : nodup l)
(s₁ : l₁ <+ l) (s₂ : l₂ <+ l) : l₁ ~ l₂ ↔ l₁ = l₂ :=
⟨λ h, begin
induction s₂ with l₂ l a s₂ IH l₂ l a s₂ IH generalizing l₁,
{ exact eq_nil_of_perm_nil h.symm },
{ simp at d,
cases s₁ with _ _ _ s₁ l₁ _ _ s₁,
{ exact IH d.2 s₁ h },
{ apply d.1.elim,
exact subset_of_subperm ⟨_, h.symm, s₂⟩ (mem_cons_self _ _) } },
{ simp at d,
cases s₁ with _ _ _ s₁ l₁ _ _ s₁,
{ apply d.1.elim,
exact subset_of_subperm ⟨_, h, s₁⟩ (mem_cons_self _ _) },
{ rw IH d.2 s₁ (perm_cons_inv h) } }
end, λ h, by rw h⟩
section
variable [decidable_eq α]
-- attribute [congr]
theorem erase_perm_erase (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
l₁.erase a ~ l₂.erase a :=
if h₁ : a ∈ l₁ then
have h₂ : a ∈ l₂, from perm_subset p h₁,
perm_cons_inv $ trans (perm_erase h₁).symm $ trans p (perm_erase h₂)
else
have h₂ : a ∉ l₂, from mt (mem_of_perm p).2 h₁,
by rw [erase_of_not_mem h₁, erase_of_not_mem h₂]; exact p
theorem erase_subperm (a : α) (l : list α) : l.erase a <+~ l :=
⟨l.erase a, perm.refl _, erase_sublist _ _⟩
theorem erase_subperm_erase {l₁ l₂ : list α} (a : α) (h : l₁ <+~ l₂) : l₁.erase a <+~ l₂.erase a :=
let ⟨l, hp, hs⟩ := h in ⟨l.erase a, erase_perm_erase _ hp, erase_sublist_erase _ hs⟩
theorem perm_diff_left {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.diff t ~ l₂.diff t :=
by induction t generalizing l₁ l₂ h; simp [*, erase_perm_erase]
theorem perm_diff_right (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l.diff t₁ = l.diff t₂ :=
by induction h generalizing l; simp [*, erase_perm_erase, erase_comm]
<|> exact (ih_1 _).trans (ih_2 _)
theorem subperm_cons_diff {a : α} : ∀ {l₁ l₂ : list α}, (a :: l₁).diff l₂ <+~ a :: l₁.diff l₂
| l₁ [] := ⟨a::l₁, by simp⟩
| l₁ (b::l₂) :=
begin
repeat {rw diff_cons},
by_cases heq : a = b,
{ by_cases b ∈ l₁,
{ rw perm.subperm_right, apply subperm_cons_diff,
simp [perm_diff_left, heq, perm_erase h] },
{ simp [subperm_of_sublist, sublist.cons, h, heq] } },
{ simp [heq, subperm_cons_diff] }
end
theorem subset_cons_diff {a : α} {l₁ l₂ : list α} : (a :: l₁).diff l₂ ⊆ a :: l₁.diff l₂ :=
subset_of_subperm subperm_cons_diff
theorem perm_bag_inter_left {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.bag_inter t ~ l₂.bag_inter t :=
begin
induction h with x _ _ _ _ x y _ _ _ _ _ _ ih_1 ih_2 generalizing t, {simp},
{ by_cases x ∈ t; simp [*, skip] },
{ by_cases x = y, {simp [h]},
by_cases xt : x ∈ t; by_cases yt : y ∈ t,
{ simp [xt, yt, mem_erase_of_ne h, mem_erase_of_ne (ne.symm h), erase_comm, swap] },
{ simp [xt, yt, mt mem_of_mem_erase, skip] },
{ simp [xt, yt, mt mem_of_mem_erase, skip] },
{ simp [xt, yt] } },
{ exact (ih_1 _).trans (ih_2 _) }
end
theorem perm_bag_inter_right (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l.bag_inter t₁ = l.bag_inter t₂ :=
begin
induction l with a l IH generalizing t₁ t₂ p, {simp},
by_cases a ∈ t₁,
{ simp [h, (mem_of_perm p).1 h, IH (erase_perm_erase _ p)] },
{ simp [h, mt (mem_of_perm p).2 h, IH p] }
end
theorem cons_perm_iff_perm_erase {a : α} {l₁ l₂ : list α} : a::l₁ ~ l₂ ↔ a ∈ l₂ ∧ l₁ ~ l₂.erase a :=
⟨λ h, have a ∈ l₂, from perm_subset h (mem_cons_self a l₁),
⟨this, perm_cons_inv $ h.trans $ perm_erase this⟩,
λ ⟨m, h⟩, trans (skip a h) (perm_erase m).symm⟩
theorem perm_iff_count {l₁ l₂ : list α} : l₁ ~ l₂ ↔ ∀ a, count a l₁ = count a l₂ :=
⟨perm_count, λ H, begin
induction l₁ with a l₁ IH generalizing l₂,
{ cases l₂ with b l₂, {refl},
specialize H b, simp at H, contradiction },
{ have : a ∈ l₂ := count_pos.1 (by rw ← H; simp; apply nat.succ_pos),
refine trans (skip a $ IH $ λ b, _) (perm_erase this).symm,
specialize H b,
rw perm_count (perm_erase this) at H,
by_cases b = a; simp [h] at H ⊢; assumption }
end⟩
instance decidable_perm : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂)
| [] [] := is_true $ perm.refl _
| [] (b::l₂) := is_false $ λ h, by have := eq_nil_of_perm_nil h; contradiction
| (a::l₁) l₂ := by haveI := decidable_perm l₁ (l₂.erase a);
exact decidable_of_iff' _ cons_perm_iff_perm_erase
-- @[congr]
theorem perm_erase_dup_of_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
erase_dup l₁ ~ erase_dup l₂ :=
perm_iff_count.2 $ λ a,
if h : a ∈ l₁
then by simp [nodup_erase_dup, h, perm_subset p h]
else by simp [h, mt (mem_of_perm p).2 h]
-- attribute [congr]
theorem perm_insert (a : α)
{l₁ l₂ : list α} (p : l₁ ~ l₂) : insert a l₁ ~ insert a l₂ :=
if h : a ∈ l₁
then by simpa [h, perm_subset p h] using p
else by simpa [h, mt (mem_of_perm p).2 h] using skip a p
theorem perm_insert_swap (x y : α) (l : list α) :
insert x (insert y l) ~ insert y (insert x l) :=
begin
by_cases xl : x ∈ l; by_cases yl : y ∈ l; simp [xl, yl],
by_cases xy : x = y, { simp [xy] },
simp [not_mem_cons_of_ne_of_not_mem xy xl,
not_mem_cons_of_ne_of_not_mem (ne.symm xy) yl],
constructor
end
theorem perm_union_left {l₁ l₂ : list α} (t₁ : list α) (h : l₁ ~ l₂) : l₁ ∪ t₁ ~ l₂ ∪ t₁ :=
begin
induction h with a _ _ _ ih _ _ _ _ _ _ _ _ ih_1 ih_2; try {simp},
{ exact perm_insert a ih },
{ apply perm_insert_swap },
{ exact ih_1.trans ih_2 }
end
theorem perm_union_right (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l ∪ t₁ ~ l ∪ t₂ :=
by induction l; simp [*, perm_insert]
-- @[congr]
theorem perm_union {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∪ t₁ ~ l₂ ∪ t₂ :=
trans (perm_union_left t₁ p₁) (perm_union_right l₂ p₂)
theorem perm_inter_left {l₁ l₂ : list α} (t₁ : list α) : l₁ ~ l₂ → l₁ ∩ t₁ ~ l₂ ∩ t₁ :=
perm_filter _
theorem perm_inter_right (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l ∩ t₁ = l ∩ t₂ :=
by dsimp [(∩), list.inter]; congr; funext a; rw [mem_of_perm p]
-- @[congr]
theorem perm_inter {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∩ t₁ ~ l₂ ∩ t₂ :=
perm_inter_right l₂ p₂ ▸ perm_inter_left t₁ p₁
end
theorem perm_pairwise {R : α → α → Prop} (S : symmetric R) :
∀ {l₁ l₂ : list α} (p : l₁ ~ l₂), pairwise R l₁ ↔ pairwise R l₂ :=
suffices ∀ {l₁ l₂}, l₁ ~ l₂ → pairwise R l₁ → pairwise R l₂, from λ l₁ l₂ p, ⟨this p, this p.symm⟩,
λ l₁ l₂ p d, begin
induction d with a l₁ h d IH generalizing l₂,
{ rw eq_nil_of_perm_nil p, constructor },
{ have : a ∈ l₂ := perm_subset p (mem_cons_self _ _),
rcases mem_split this with ⟨s₂, t₂, rfl⟩,
have p' := perm_cons_inv (p.trans perm_middle),
refine (pairwise_middle S).2 (pairwise_cons.2 ⟨λ b m, _, IH _ p'⟩),
exact h _ (perm_subset p'.symm m) }
end
theorem perm_nodup {l₁ l₂ : list α} : l₁ ~ l₂ → (nodup l₁ ↔ nodup l₂) :=
perm_pairwise $ @ne.symm α
theorem perm_bind_left {l₁ l₂ : list α} (f : α → list β) (p : l₁ ~ l₂) :
l₁.bind f ~ l₂.bind f :=
begin
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ simp, exact perm_app_right _ IH },
{ simp, rw [← append_assoc, ← append_assoc], exact perm_app_left _ perm_app_comm },
{ exact trans IH₁ IH₂ }
end
theorem perm_bind_right (l : list α) {f g : α → list β} (h : ∀ a, f a ~ g a) :
l.bind f ~ l.bind g :=
by induction l with a l IH; simp; exact perm_app (h a) IH
theorem perm_product_left {l₁ l₂ : list α} (t₁ : list β) (p : l₁ ~ l₂) : product l₁ t₁ ~ product l₂ t₁ :=
perm_bind_left _ p
theorem perm_product_right (l : list α) {t₁ t₂ : list β} (p : t₁ ~ t₂) : product l t₁ ~ product l t₂ :=
perm_bind_right _ $ λ a, perm_map _ p
@[congr] theorem perm_product {l₁ l₂ : list α} {t₁ t₂ : list β}
(p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : product l₁ t₁ ~ product l₂ t₂ :=
trans (perm_product_left t₁ p₁) (perm_product_right l₂ p₂)
theorem sublists_cons_perm_append (a : α) (l : list α) :
sublists (a :: l) ~ sublists l ++ map (cons a) (sublists l) :=
begin
simp [sublists, sublists_aux_cons_cons],
refine skip _ ((skip _ _).trans perm_middle.symm),
induction sublists_aux l cons with b l IH; simp,
exact skip b ((skip _ IH).trans perm_middle.symm)
end
theorem sublists_perm_sublists' : ∀ l : list α, sublists l ~ sublists' l
| [] := perm.refl _
| (a::l) := let IH := sublists_perm_sublists' l in
by rw sublists'_cons; exact
(sublists_cons_perm_append _ _).trans (perm_app IH (perm_map _ IH))
theorem revzip_sublists (l : list α) :
∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists → l₁ ++ l₂ ~ l :=
begin
rw revzip,
apply list.reverse_rec_on l,
{ intros l₁ l₂ h, simp at h, simp [h] },
{ intros l a IH l₁ l₂ h,
rw [sublists_concat, reverse_append, zip_append, ← map_reverse,
zip_map_right, zip_map_left] at h; [skip, {simp}],
simp only [prod.mk.inj_iff, mem_map, mem_append, prod.map_mk, prod.exists] at h,
rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩,
{ rw ← append_assoc,
exact perm_app_left _ (IH _ _ h) },
{ rw append_assoc,
apply (perm_app_right _ perm_app_comm).trans,
rw ← append_assoc,
exact perm_app_left _ (IH _ _ h) } }
end
theorem revzip_sublists' (l : list α) :
∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists' → l₁ ++ l₂ ~ l :=
begin
rw revzip,
induction l with a l IH; intros l₁ l₂ h,
{ simp at h, simp [h] },
{ rw [sublists'_cons, reverse_append, zip_append, ← map_reverse,
zip_map_right, zip_map_left] at h; [simp at h, simp],
rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩,
{ exact perm_middle.trans (skip _ (IH _ _ h)) },
{ exact skip _ (IH _ _ h) } }
end
theorem perm_lookmap (f : α → option α) {l₁ l₂ : list α}
(H : pairwise (λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d) l₁)
(p : l₁ ~ l₂) : lookmap f l₁ ~ lookmap f l₂ :=
begin
let F := λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d,
change pairwise F l₁ at H,
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ cases h : f a,
{ simp [h], exact (IH (pairwise_cons.1 H).2).skip _ },
{ simp [lookmap_cons_some _ _ h], exact p.skip _ } },
{ cases h₁ : f a with c; cases h₂ : f b with d,
{ simp [h₁, h₂], apply swap },
{ simp [h₁, lookmap_cons_some _ _ h₂], apply swap },
{ simp [lookmap_cons_some _ _ h₁, h₂], apply swap },
{ simp [lookmap_cons_some _ _ h₁, lookmap_cons_some _ _ h₂],
rcases (pairwise_cons.1 H).1 _ (or.inl rfl) _ h₂ _ h₁ with ⟨rfl, rfl⟩,
refl } },
{ refine (IH₁ H).trans (IH₂ ((perm_pairwise _ p₁).1 H)),
exact λ a b h c h₁ d h₂, (h d h₂ c h₁).imp eq.symm eq.symm }
end
theorem perm_erasep (f : α → Prop) [decidable_pred f] {l₁ l₂ : list α}
(H : pairwise (λ a b, f a → f b → false) l₁)
(p : l₁ ~ l₂) : erasep f l₁ ~ erasep f l₂ :=
begin
let F := λ a b, f a → f b → false,
change pairwise F l₁ at H,
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ by_cases h : f a,
{ simp [h, p] },
{ simp [h], exact (IH (pairwise_cons.1 H).2).skip _ } },
{ by_cases h₁ : f a; by_cases h₂ : f b; simp [h₁, h₂],
{ cases (pairwise_cons.1 H).1 _ (or.inl rfl) h₂ h₁ },
{ apply swap } },
{ refine (IH₁ H).trans (IH₂ ((perm_pairwise _ p₁).1 H)),
exact λ a b h h₁ h₂, h h₂ h₁ }
end
/- enumerating permutations -/
section permutations
theorem permutations_aux2_fst (t : α) (ts : list α) (r : list β) : ∀ (ys : list α) (f : list α → β),
(permutations_aux2 t ts r ys f).1 = ys ++ ts
| [] f := rfl
| (y::ys) f := match _, permutations_aux2_fst ys _ : ∀ o : list α × list β, o.1 = ys ++ ts →
(permutations_aux2._match_1 t y f o).1 = y :: ys ++ ts with
| ⟨_, zs⟩, rfl := rfl
end
@[simp] theorem permutations_aux2_snd_nil (t : α) (ts : list α) (r : list β) (f : list α → β) :
(permutations_aux2 t ts r [] f).2 = r := rfl
@[simp] theorem permutations_aux2_snd_cons (t : α) (ts : list α) (r : list β) (y : α) (ys : list α) (f : list α → β) :
(permutations_aux2 t ts r (y::ys) f).2 = f (t :: y :: ys ++ ts) ::
(permutations_aux2 t ts r ys (λx : list α, f (y::x))).2 :=
match _, permutations_aux2_fst t ts r _ _ : ∀ o : list α × list β, o.1 = ys ++ ts →
(permutations_aux2._match_1 t y f o).2 = f (t :: y :: ys ++ ts) :: o.2 with
| ⟨_, zs⟩, rfl := rfl
end
theorem permutations_aux2_append (t : α) (ts : list α) (r : list β) (ys : list α) (f : list α → β) :
(permutations_aux2 t ts nil ys f).2 ++ r = (permutations_aux2 t ts r ys f).2 :=
by induction ys generalizing f; simp *
theorem mem_permutations_aux2 {t : α} {ts : list α} {ys : list α} {l l' : list α} :
l' ∈ (permutations_aux2 t ts [] ys (append l)).2 ↔
∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l' = l ++ l₁ ++ t :: l₂ ++ ts :=
begin
induction ys with y ys ih generalizing l,
{ simp {contextual := tt} },
{ rw [permutations_aux2_snd_cons, show (λ (x : list α), l ++ y :: x) = append (l ++ [y]),
by funext; simp, mem_cons_iff, ih], split; intro h,
{ rcases h with e | ⟨l₁, l₂, l0, ye, _⟩,
{ subst l', exact ⟨[], y::ys, by simp⟩ },
{ substs l' ys, exact ⟨y::l₁, l₂, l0, by simp⟩ } },
{ rcases h with ⟨_ | ⟨y', l₁⟩, l₂, l0, ye, rfl⟩,
{ simp [ye] },
{ simp at ye, rcases ye with ⟨rfl, rfl⟩,
exact or.inr ⟨l₁, l₂, l0, by simp⟩ } } }
end
theorem mem_permutations_aux2' {t : α} {ts : list α} {ys : list α} {l : list α} :
l ∈ (permutations_aux2 t ts [] ys id).2 ↔
∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l = l₁ ++ t :: l₂ ++ ts :=
by rw [show @id (list α) = append nil, by funext; refl]; apply mem_permutations_aux2
theorem length_permutations_aux2 (t : α) (ts : list α) (ys : list α) (f : list α → β) :
length (permutations_aux2 t ts [] ys f).2 = length ys :=
by induction ys generalizing f; simp *
theorem foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) :
foldr (λy r, (permutations_aux2 t ts r y id).2) r L = L.bind (λ y, (permutations_aux2 t ts [] y id).2) ++ r :=
by induction L with l L ih; [refl, {simp [ih], rw ← permutations_aux2_append}]
theorem mem_foldr_permutations_aux2 {t : α} {ts : list α} {r L : list (list α)} {l' : list α} :
l' ∈ foldr (λy r, (permutations_aux2 t ts r y id).2) r L ↔ l' ∈ r ∨
∃ l₁ l₂, l₁ ++ l₂ ∈ L ∧ l₂ ≠ [] ∧ l' = l₁ ++ t :: l₂ ++ ts :=
have (∃ (a : list α), a ∈ L ∧
∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ a = l₁ ++ l₂ ∧ l' = l₁ ++ t :: (l₂ ++ ts)) ↔
∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ l₁ ++ l₂ ∈ L ∧ l' = l₁ ++ t :: (l₂ ++ ts),
from ⟨λ ⟨a, aL, l₁, l₂, l0, e, h⟩, ⟨l₁, l₂, l0, e ▸ aL, h⟩,
λ ⟨l₁, l₂, l0, aL, h⟩, ⟨_, aL, l₁, l₂, l0, rfl, h⟩⟩,
by rw foldr_permutations_aux2; simp [mem_permutations_aux2', this,
or.comm, or.left_comm, or.assoc, and.comm, and.left_comm, and.assoc]
theorem length_foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) :
length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = sum (map length L) + length r :=
by simp [foldr_permutations_aux2, (∘), length_permutations_aux2]
theorem length_foldr_permutations_aux2' (t : α) (ts : list α) (r L : list (list α))
(n) (H : ∀ l ∈ L, length l = n) :
length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = n * length L + length r :=
begin
rw [length_foldr_permutations_aux2, (_ : sum (map length L) = n * length L)],
induction L with l L ih, {simp},
have sum_map : sum (map length L) = n * length L :=
ih (λ l m, H l (mem_cons_of_mem _ m)),
have length_l : length l = n := H _ (mem_cons_self _ _),
simp [sum_map, length_l, mul_add, add_comm]
end
theorem perm_of_mem_permutations_aux :
∀ {ts is l : list α}, l ∈ permutations_aux ts is → l ~ ts ++ is :=
begin
refine permutations_aux.rec (by simp) _,
introv IH1 IH2 m,
rw [permutations_aux_cons, permutations, mem_foldr_permutations_aux2] at m,
rcases m with m | ⟨l₁, l₂, m, _, e⟩,
{ exact (IH1 m).trans perm_middle },
{ subst e,
have p : l₁ ++ l₂ ~ is,
{ simp [permutations] at m,
cases m with e m, {simp [e]},
exact is.append_nil ▸ IH2 m },
exact (perm_app_left _ (perm_middle.trans (skip _ p))).trans (skip _ perm_app_comm) }
end
theorem perm_of_mem_permutations {l₁ l₂ : list α}
(h : l₁ ∈ permutations l₂) : l₁ ~ l₂ :=
(eq_or_mem_of_mem_cons h).elim (λ e, e ▸ perm.refl _)
(λ m, append_nil l₂ ▸ perm_of_mem_permutations_aux m)
theorem length_permutations_aux :
∀ ts is : list α, length (permutations_aux ts is) + is.length.fact = (length ts + length is).fact :=
begin
refine permutations_aux.rec (by simp) _,
intros t ts is IH1 IH2,
have IH2 : length (permutations_aux is nil) + 1 = is.length.fact,
{ simpa using IH2 },
simp [-add_comm, nat.fact, nat.add_succ, mul_comm] at IH1,
rw [permutations_aux_cons,
length_foldr_permutations_aux2' _ _ _ _ _
(λ l m, perm_length (perm_of_mem_permutations m)),
permutations, length, length, IH2,
nat.succ_add, nat.fact_succ, mul_comm (nat.succ _), ← IH1,
add_comm (_*_), add_assoc, nat.mul_succ, mul_comm]
end
theorem length_permutations (l : list α) : length (permutations l) = (length l).fact :=
length_permutations_aux l []
theorem mem_permutations_of_perm_lemma {is l : list α}
(H : l ~ [] ++ is → (∃ ts' ~ [], l = ts' ++ is) ∨ l ∈ permutations_aux is [])
: l ~ is → l ∈ permutations is :=
by simpa [permutations, perm_nil] using H
theorem mem_permutations_aux_of_perm :
∀ {ts is l : list α}, l ~ is ++ ts → (∃ is' ~ is, l = is' ++ ts) ∨ l ∈ permutations_aux ts is :=
begin
refine permutations_aux.rec (by simp) _,
intros t ts is IH1 IH2 l p,
rw [permutations_aux_cons, mem_foldr_permutations_aux2],
rcases IH1 (p.trans perm_middle) with ⟨is', p', e⟩ | m,
{ clear p, subst e,
rcases mem_split (perm_subset p'.symm (mem_cons_self _ _)) with ⟨l₁, l₂, e⟩,
subst is',
have p := perm_cons_inv (perm_middle.symm.trans p'),
cases l₂ with a l₂',
{ exact or.inl ⟨l₁, by simpa using p⟩ },
{ exact or.inr (or.inr ⟨l₁, a::l₂',
mem_permutations_of_perm_lemma IH2 p, by simp⟩) } },
{ exact or.inr (or.inl m) }
end
@[simp] theorem mem_permutations (s t : list α) : s ∈ permutations t ↔ s ~ t :=
⟨perm_of_mem_permutations, mem_permutations_of_perm_lemma mem_permutations_aux_of_perm⟩
end permutations
end list
|
55151652877f854199adc12c4761b9dfe2e32c7e | fe84e287c662151bb313504482b218a503b972f3 | /src/group_theory/action_instances.lean | 15a3d9100503742f3c79e0e043e9f9b31041c5ec | [] | no_license | NeilStrickland/lean_lib | 91e163f514b829c42fe75636407138b5c75cba83 | 6a9563de93748ace509d9db4302db6cd77d8f92c | refs/heads/master | 1,653,408,198,261 | 1,652,996,419,000 | 1,652,996,419,000 | 181,006,067 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 10,055 | lean | /-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Neil Strickland
If we have types `X` and `Y` with a left action of a monoid `M`,
then there are also natural actions of `M` on various other types
defined in terms of `X` and/or `Y`, such as `X × Y` and
`finset X` and `X / E` (for an equivalence relation `E` with
appropriate properties). This file defines typeclass instances
that encode these natural actions.
-/
import group_theory.group_action
import tactic.interactive
universes uM uG uX uY uZ
variables {M : Type uM} [monoid M]
variables {G : Type uG} [group G ]
variables {X : Type uX} {Y : Type uY} {Z : Type uZ}
variables [mul_action M X] [mul_action M Y] [mul_action M Z]
variables [mul_action G X] [mul_action G Y] [mul_action G Z]
namespace mul_action
lemma smul_cancel_left {g : G} {x : X} : g⁻¹ • g • x = x :=
by { rw [← mul_smul, mul_left_inv, one_smul] }
lemma smul_cancel_right {g : G} {x : X} : g • g⁻¹ • x = x :=
by { rw [← mul_smul, mul_right_inv, one_smul] }
lemma smul_eq_iff_eq_smul_inv {g : G} {x y : X} :
g • x = y ↔ x = g⁻¹ • y :=
begin
split; intro h,
{ rw [← h, smul_cancel_left ] },
{ rw [ h, smul_cancel_right] }
end
lemma one_act : ((•) (1 : M)) = @id X :=
by { funext x, rw[one_smul,id] }
lemma mul_act (m n : M) : (((•) (m * n)) : X → X) = ((•) m) ∘ ((•) n) :=
by { funext x, rw[mul_smul] }
variable (M)
def trivial_action (Z : Type*) : mul_action M Z := {
smul := λ a z, z,
one_smul := λ z, rfl,
mul_smul := λ a b z, rfl
}
variable {M}
instance empty_action : mul_action M empty := trivial_action _ _
instance unit_action : mul_action M unit := trivial_action _ _
instance sum_action : mul_action M (X ⊕ Y) := {
smul := λ m z,sum.cases_on z (λ x, sum.inl (m • x)) (λ y, sum.inr (m • y)),
one_smul := λ z,begin
rcases z with x | y,
{ change sum.inl ((1 : M) • x) = sum.inl x, rw[one_smul], },
{ change sum.inr ((1 : M) • y) = sum.inr y, rw[one_smul], }
end,
mul_smul := λ m n z,begin
rcases z with x | y,
{ change sum.inl ((m * n) • x) = sum.inl (m • n • x), rw[mul_smul] },
{ change sum.inr ((m * n) • y) = sum.inr (m • n • y), rw[mul_smul] }
end
}
instance prod_action : mul_action M (X × Y) := {
smul := λ m xy, ⟨m • xy.1,m • xy.2⟩,
one_smul := λ ⟨x,y⟩,
by {change (prod.mk ((1 : M) • x) ((1 : M) • y)) = prod.mk x y,
rw[one_smul,one_smul] },
mul_smul := λ m n ⟨x,y⟩,
by {change (prod.mk ((m * n) • x) ((m * n) • y)) =
(prod.mk (m • n • x) (m • n • y)),
rw[mul_smul,mul_smul] }
}
lemma smul_prod (m : M) (xy : X × Y) : m • xy = ⟨m • xy.1, m • xy.2⟩ := rfl
variables (M G)
def is_equivariant (f : X → Y) := ∀ (m : M) (x : X), f (m • x) = m • (f x)
def equivariantizer (f : X → Y) : submonoid M := {
carrier := { m : M | ∀ (x : X), f (m • x) = m • (f x) },
one_mem' := λ x, by { rw [one_smul, one_smul] },
mul_mem' := λ a b ha hb x,
by { rw[mul_smul, mul_smul, ha, hb] }
}
def equivariantizer_subgroup (f : X → Y) : subgroup G := {
inv_mem' := λ g hg x, by {
rw [← smul_eq_iff_eq_smul_inv, ← hg, ← mul_smul,
mul_right_inv, one_smul] },
.. mul_action.equivariantizer G f
}
variables {M G}
lemma is_equivariant_id : is_equivariant M (id : X → X) := λ m x, rfl
lemma is_equivariant_comp {g : Y → Z} {f : X → Y}
(hg : is_equivariant M g) (hf : is_equivariant M f) :
(is_equivariant M (g ∘ f)) :=
λ m x, by { rw [function.comp_app, hf, hg] }
instance map_action : mul_action G (X → Y) := {
smul := λ g u x, g • (u (g⁻¹ • x)),
one_smul := λ u, funext $ λ x,
by { change _ • (u _) = u x, rw [inv_one, one_smul, one_smul] },
mul_smul := λ a b u, funext $ λ x,
by { change _ • (u _) = _ • (_ • _),
rw [mul_inv_rev, mul_smul, mul_smul] }
}
lemma smul_map (g : G) (u : X → Y) (x : X) :
(g • u) x = g • (u (g⁻¹ • x)) := rfl
instance list_scalar : has_scalar M (list X) := ⟨λ m xs,xs.map ((•) m)⟩
instance list_action : mul_action M (list X) := {
one_smul := λ xs,
begin
change xs.map ((•) (1 : M)) = xs,
rw[one_act,list.map_id],
end,
mul_smul := λ m n xs,calc
(m * n) • xs = xs.map ((•) (m * n)) : rfl
... = xs.map (((•) m) ∘ ((•) n)) : by rw[mul_act]
... = m • n • xs : by { rw[← list.map_map], refl },
.. mul_action.list_scalar
}
lemma smul_list (m : M) (xs : list X) : m • xs = xs.map ((•) m) := rfl
instance finset_scalar [decidable_eq X] : has_scalar M (finset X) :=
⟨λ m xs,xs.image ((•) m)⟩
instance finset_action [decidable_eq X] : mul_action M (finset X) := {
one_smul := λ xs,
begin
change xs.image ((•) (1 : M)) = xs,
rw [one_act, finset.image_id],
end,
mul_smul := λ m n xs, calc
(m * n) • xs = xs.image ((•) (m * n)) : rfl
... = xs.image (((•) m) ∘ ((•) n)) : by rw [mul_act]
... = m • n • xs : by { rw [← finset.image_image], refl },
.. mul_action.finset_scalar
}
lemma smul_finset [decidable_eq X] (m : M) (xs : finset X) :
m • xs = xs.image ((•) m) := rfl
lemma mem_smul_finset [decidable_eq X] {x : X} {m : M} {xs : finset X} :
x ∈ m • xs ↔ ∃ (x' : X), x' ∈ xs ∧ m • x' = x :=
by { rw [smul_finset, finset.mem_image]; simp only [exists_prop] }
lemma mem_smul_finset_of_mem [decidable_eq X] (m : M) {xs : finset X}
{x : X} (hx : x ∈ xs) : m • x ∈ m • xs :=
finset.mem_image_of_mem ((•) m) hx
lemma mem_smul_finset' [decidable_eq X]
{x : X} {g : G} {xs : finset X} :
x ∈ g • xs ↔ (g⁻¹ • x) ∈ xs :=
begin
rw [mem_smul_finset], split,
{ rintro ⟨x',⟨hm,he⟩⟩,
have := calc g⁻¹ • x = g⁻¹ • (g • x') : by { rw [← he] }
... = x' : by { rw [smul_cancel_left] },
rw [← this] at hm, exact hm },
{ intro h, use g⁻¹ • x, split,
{ exact h },
{ rw [smul_cancel_right] } }
end
lemma smul_finset_eq_iff [decidable_eq X]
{g : G} {xs ys : finset X} :
g • xs = ys ↔ (∀ {x : X}, x ∈ xs → g • x ∈ ys) ∧
(∀ {y : X}, y ∈ ys → g⁻¹ • y ∈ xs) :=
begin
split,
{ intro h, split,
{ intros x hx, rw [← h, mem_smul_finset', smul_cancel_left], exact hx },
{ let h' : xs = g⁻¹ • ys := smul_eq_iff_eq_smul_inv.mp h,
intros y hy, rw [h'],
exact mem_smul_finset_of_mem g⁻¹ hy
} },
{ rintro ⟨h₀,h₁⟩, ext y, split; intro hy,
{ replace hy := h₀ (mem_smul_finset'.mp hy),
rw [smul_cancel_right] at hy, exact hy },
{ rw [mem_smul_finset'], exact h₁ hy } }
end
variables (M X)
structure equivariant_set : Type uX :=
(carrier : set X)
(smul : ∀ (m : M) {x : X}, x ∈ carrier → m • x ∈ carrier)
variables {M X}
namespace equivariant_set
instance : has_coe (equivariant_set M X) (set X) := ⟨equivariant_set.carrier⟩
instance : has_mem X (equivariant_set M X) := ⟨λ x Y, x ∈ (Y : set X)⟩
@[simp] theorem mem_coe {Y : equivariant_set M X} (x : X) :
x ∈ (Y : set X) ↔ x ∈ Y := iff.rfl
theorem ext' {Y₀ Y₁ : equivariant_set M X}
(h : (Y₀ : set X) = (Y₁ : set X)) : Y₀ = Y₁ :=
by cases Y₀; cases Y₁; congr'
protected theorem ext'_iff {Y₀ Y₁ : equivariant_set M X} :
(Y₀ : set X) = (Y₁ : set X) ↔ Y₀ = Y₁ := ⟨ext', λ h, h ▸ rfl⟩
@[ext] theorem ext {Y₀ Y₁ : equivariant_set M X}
(h : ∀ x, x ∈ Y₀ ↔ x ∈ Y₁) : Y₀ = Y₁ := ext' $ set.ext h
instance restricted_action (Y : equivariant_set M X) : mul_action M Y.carrier := {
smul := λ m ⟨y,y_in_Y⟩, ⟨m • y,Y.smul m y_in_Y⟩,
one_smul := λ ⟨y,y_in_Y⟩,
by { apply subtype.eq, change (1 : M) • y = y, apply one_smul },
mul_smul := λ m n ⟨y,y_in_Y⟩,
by { apply subtype.eq, change (m * n) • y = m • n • y, apply mul_smul }
}
lemma coe_smul {Y : equivariant_set M X} (m : M) (y : Y) :
((m • y) : X) = m • (y : X) := rfl
end equivariant_set
variables (M X)
structure equivariant_setoid extends (setoid X) :=
(smul : ∀ (m : M) {x y : X}, r x y → r (m • x) (m • y))
variables {M X}
namespace equivariant_setoid
instance : has_coe (equivariant_setoid M X) (setoid X) := ⟨λ E, ⟨E.r,E.iseqv⟩⟩
def quotient (E : equivariant_setoid M X) := quotient (E : setoid X)
def quotient.mk (E : equivariant_setoid M X) (x : X) : quotient E :=
@_root_.quotient.mk X E x
instance induced_action (E : equivariant_setoid M X) :
mul_action M (quotient E) :=
begin
exact {
smul := λ m, @quotient.lift X _ E
(λ x, (@_root_.quotient.mk X E (m • x)))
(λ x₀ x₁ e, begin
let h := @quotient.sound X E,
exact h (equivariant_setoid.smul _ m e),
end),
one_smul :=
begin
rintro ⟨x⟩, change @_root_.quotient.mk X E _ = _,
rw [one_smul], refl
end,
mul_smul :=
begin
rintro a b ⟨x⟩,
change @_root_.quotient.mk X E _ = @_root_.quotient.mk X E _,
rw [mul_smul]
end
}
end
lemma smul_mk (E : equivariant_setoid M X) (m : M) (x : X) :
m • (quotient.mk E x) = quotient.mk E (m • x) := rfl
end equivariant_setoid
end mul_action
namespace mul_action
variables [decidable_eq X]
variable (X)
def smul_equiv (g : G) : X ≃ X := {
to_fun := λ x, g • x,
inv_fun := λ x, g⁻¹ • x,
left_inv := λ x, by { change g⁻¹ • (g • x) = x, rw [← mul_smul, inv_mul_self, one_smul] },
right_inv := λ x, by { change g • (g⁻¹ • x) = x, rw [← mul_smul, mul_inv_self, one_smul] }
}
variable {X}
lemma finset_action_eq_map (g : G) (s : finset X) :
g • s = s.map (smul_equiv X g).to_embedding :=
begin
change s.image _ = s.map _,
rw [finset.map_eq_image], refl
end
lemma finset_action.card (g : G) (s : finset X) : (g • s).card = s.card :=
begin
rw [finset_action_eq_map, finset.card_map]
end
end mul_action |
e6ac0299315bea52b2c1248d4c3d3859e7fce4a9 | 453dcd7c0d1ef170b0843a81d7d8caedc9741dce | /data/rat.lean | aef140994b336c4ce19df3c9762c132aa9db962b | [
"Apache-2.0"
] | permissive | amswerdlow/mathlib | 9af77a1f08486d8fa059448ae2d97795bd12ec0c | 27f96e30b9c9bf518341705c99d641c38638dfd0 | refs/heads/master | 1,585,200,953,598 | 1,534,275,532,000 | 1,534,275,532,000 | 144,564,700 | 0 | 0 | null | 1,534,156,197,000 | 1,534,156,197,000 | null | UTF-8 | Lean | false | false | 36,454 | 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
Introduces the rational numbers as discrete, linear ordered field.
-/
import
data.nat.gcd data.pnat data.int.basic data.equiv.encodable order.basic
algebra.ordered_field
/- rational numbers -/
/-- `rat`, or `ℚ`, is the type of rational numbers. It is defined
as the set of pairs ⟨n, d⟩ of integers such that `d` is positive and `n` and
`d` are coprime. This representation is preferred to the quotient
because without periodic reduction, the numerator and denominator can grow
exponentially (for example, adding 1/2 to itself repeatedly). -/
structure rat := mk' ::
(num : ℤ)
(denom : ℕ)
(pos : denom > 0)
(cop : num.nat_abs.coprime denom)
notation `ℚ` := rat
namespace rat
protected def repr : ℚ → string
| ⟨n, d, _, _⟩ := if d = 1 then _root_.repr n else
_root_.repr n ++ "/" ++ _root_.repr d
instance : has_repr ℚ := ⟨rat.repr⟩
instance : has_to_string ℚ := ⟨rat.repr⟩
meta instance : has_to_format ℚ := ⟨coe ∘ rat.repr⟩
instance : encodable ℚ := encodable.of_equiv (Σ n : ℤ, {d : ℕ // d > 0 ∧ n.nat_abs.coprime d})
⟨λ ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ⟨a, b, c, d⟩, ⟨a, b, c, d⟩,
λ ⟨a, b, c, d⟩, rfl, λ⟨a, b, c, d⟩, rfl⟩
/-- Embed an integer as a rational number -/
def of_int (n : ℤ) : ℚ :=
⟨n, 1, nat.one_pos, nat.coprime_one_right _⟩
instance : has_zero ℚ := ⟨of_int 0⟩
instance : has_one ℚ := ⟨of_int 1⟩
/-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ+` (not necessarily coprime) -/
def mk_pnat (n : ℤ) : ℕ+ → ℚ | ⟨d, dpos⟩ :=
let n' := n.nat_abs, g := n'.gcd d in
⟨n / g, d / g, begin
apply (nat.le_div_iff_mul_le _ _ (nat.gcd_pos_of_pos_right _ dpos)).2,
simp, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _)
end, begin
have : int.nat_abs (n / ↑g) = n' / g,
{ cases int.nat_abs_eq n with e e; rw e, { refl },
rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl },
exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) },
rw this,
exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos)
end⟩
/-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ`. In the case `d = 0`, we
define `n / 0 = 0` by convention. -/
def mk_nat (n : ℤ) (d : ℕ) : ℚ :=
if d0 : d = 0 then 0 else mk_pnat n ⟨d, nat.pos_of_ne_zero d0⟩
/-- Form the quotient `n / d` where `n d : ℤ`. -/
def mk : ℤ → ℤ → ℚ
| n (int.of_nat d) := mk_nat n d
| n -[1+ d] := mk_pnat (-n) d.succ_pnat
local infix ` /. `:70 := mk
theorem mk_pnat_eq (n d h) : mk_pnat n ⟨d, h⟩ = n /. d :=
by change n /. d with dite _ _ _; simp [ne_of_gt h]
theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl
@[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl
@[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 :=
by cases n; simp [mk_pnat]; change int.nat_abs 0 with 0; simp *; refl
@[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 :=
by by_cases n = 0; simp [*, mk_nat]
@[simp] theorem zero_mk (n) : 0 /. n = 0 :=
by cases n; simp [mk]
private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : ℤ) ∣ a :=
int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left (int.nat_abs a) b
@[simp] theorem mk_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 :=
begin
constructor; intro h; [skip, {subst a, simp}],
have : ∀ {a b}, mk_pnat a b = 0 → a = 0,
{ intros a b e, cases b with b h,
injection e with e,
apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e },
cases b with b; simp [mk, mk_nat] at h,
{ simp [mt (congr_arg int.of_nat) b0] at h,
exact this h },
{ apply neg_inj, simp [this h] }
end
theorem mk_eq : ∀ {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0),
a /. b = c /. d ↔ a * d = c * b :=
suffices ∀ a b c d hb hd, mk_pnat a ⟨b, hb⟩ = mk_pnat c ⟨d, hd⟩ ↔ a * d = c * b,
begin
intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hb],
all_goals {
cases d with d d; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hd],
all_goals { rw this, try {refl} } },
{ change a * ↑(d.succ) = -c * ↑b ↔ a * -(d.succ) = c * b,
constructor; intro h; apply neg_inj; simpa [left_distrib, neg_add_eq_iff_eq_add,
eq_neg_iff_add_eq_zero, neg_eq_iff_add_eq_zero] using h },
{ change -a * ↑d = c * b.succ ↔ a * d = c * -b.succ,
constructor; intro h; apply neg_inj; simpa [left_distrib, eq_comm] using h },
{ change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ,
simp [left_distrib] }
end,
begin
intros, simp [mk_pnat], constructor; intro h,
{ cases h with ha hb,
have ha, {
have dv := @gcd_abs_dvd_left,
have := int.eq_mul_of_div_eq_right dv ha,
rw ← int.mul_div_assoc _ dv at this,
exact int.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm },
have hb, {
have dv := λ {a b}, nat.gcd_dvd_right (int.nat_abs a) b,
have := nat.eq_mul_of_div_eq_right dv hb,
rw ← nat.mul_div_assoc _ dv at this,
exact nat.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm },
have m0 : (a.nat_abs.gcd b * c.nat_abs.gcd d : ℤ) ≠ 0, {
refine int.coe_nat_ne_zero.2 (ne_of_gt _),
apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption },
apply eq_of_mul_eq_mul_right m0,
simpa [mul_comm, mul_left_comm] using
congr (congr_arg (*) ha.symm) (congr_arg coe hb) },
{ suffices : ∀ a c, a * d = c * b →
a / a.gcd b = c / c.gcd d ∧ b / a.gcd b = d / c.gcd d,
{ cases this a.nat_abs c.nat_abs
(by simpa [int.nat_abs_mul] using congr_arg int.nat_abs h) with h₁ h₂,
have hs := congr_arg int.sign h,
simp [int.sign_eq_one_of_pos (int.coe_nat_lt.2 hb),
int.sign_eq_one_of_pos (int.coe_nat_lt.2 hd)] at hs,
conv in a { rw ← int.sign_mul_nat_abs a },
conv in c { rw ← int.sign_mul_nat_abs c },
rw [int.mul_div_assoc, int.mul_div_assoc],
exact ⟨congr (congr_arg (*) hs) (congr_arg coe h₁), h₂⟩,
all_goals { exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) } },
intros a c h,
suffices bd : b / a.gcd b = d / c.gcd d,
{ refine ⟨_, bd⟩,
apply nat.eq_of_mul_eq_mul_left hb,
rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd,
← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] },
suffices : ∀ {a c : ℕ} (b>0) (d>0),
a * d = c * b → b / a.gcd b ≤ d / c.gcd d,
{ exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) },
intros a c b hb d hd h,
have gb0 := nat.gcd_pos_of_pos_right a hb,
have gd0 := nat.gcd_pos_of_pos_right c hd,
apply nat.le_of_dvd,
apply (nat.le_div_iff_mul_le _ _ gd0).2,
simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _),
apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left,
refine ⟨c / c.gcd d, _⟩,
rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)],
apply congr_arg (/ c.gcd d),
rw [mul_comm, ← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] }
end
@[simp] theorem div_mk_div_cancel_left {a b c : ℤ} (c0 : c ≠ 0) :
(a * c) /. (b * c) = a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp },
apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp [mul_comm, mul_assoc]
end
theorem num_denom : ∀ a : ℚ, a = a.num /. a.denom
| ⟨n, d, h, (c:_=1)⟩ := show _ = mk_nat n d,
by simp [mk_nat, ne_of_gt h, mk_pnat, c]
theorem num_denom' (n d h c) : (⟨n, d, h, c⟩ : ℚ) = n /. d := num_denom _
@[elab_as_eliminator] theorem {u} num_denom_cases_on {C : ℚ → Sort u}
: ∀ (a : ℚ) (H : ∀ n d, d > 0 → (int.nat_abs n).coprime d → C (n /. d)), C a
| ⟨n, d, h, c⟩ H := by rw num_denom'; exact H n d h c
@[elab_as_eliminator] theorem {u} num_denom_cases_on' {C : ℚ → Sort u}
(a : ℚ) (H : ∀ (n:ℤ) (d:ℕ), d ≠ 0 → C (n /. d)) : C a :=
num_denom_cases_on a $ λ n d h c,
H n d $ ne_of_gt h
theorem num_dvd (a) {b} (b0 : b ≠ 0) : (a /. b).num ∣ a :=
begin
cases e : a /. b with n d h c,
rw [num_denom', mk_eq (int.coe_nat_ne_zero.2 b0)
(ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $
c.dvd_of_dvd_mul_right _),
have := congr_arg int.nat_abs e,
simp [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this]
end
theorem denom_dvd (a b : ℤ) : ((a /. b).denom : ℤ) ∣ b :=
begin
by_cases b0 : b = 0, {simp [b0]},
cases e : a /. b with n d h c,
rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _),
rw [← int.nat_abs_mul, ← int.coe_nat_dvd, int.dvd_nat_abs, ← e], simp
end
protected def add : ℚ → ℚ → ℚ
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * d₂ + n₂ * d₁) ⟨d₁ * d₂, mul_pos h₁ h₂⟩
instance : has_add ℚ := ⟨rat.add⟩
theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ)
(fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂},
f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂)
(f0 : ∀ {n₁ d₁ n₂ d₂} (d₁0 : d₁ ≠ 0) (d₂0 : d₂ ≠ 0), f₂ n₁ d₁ n₂ d₂ ≠ 0)
(a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0)
(H : ∀ {n₁ d₁ n₂ d₂} (h₁ : a * d₁ = n₁ * b) (h₂ : c * d₂ = n₂ * d),
f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) :
f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d :=
begin
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
generalize hc : c /. d = x, cases x with n₂ d₂ h₂ c₂, rw num_denom' at hc,
rw fv,
have d₁0 := ne_of_gt (int.coe_nat_lt.2 h₁),
have d₂0 := ne_of_gt (int.coe_nat_lt.2 h₂),
exact (mk_eq (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((mk_eq b0 d₁0).1 ha) ((mk_eq d0 d₂0).1 hc))
end
@[simp] theorem add_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
a /. b + c /. d = (a * d + c * b) /. (b * d) :=
begin
apply lift_binop_eq rat.add; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero d₁0 d₂0 },
calc (n₁ * d₂ + n₂ * d₁) * (b * d) =
(n₁ * b) * d₂ * d + (n₂ * d) * (d₁ * b) : by simp [mul_add, mul_comm, mul_left_comm]
... = (a * d₁) * d₂ * d + (c * d₂) * (d₁ * b) : by rw [h₁, h₂]
... = (a * d + c * b) * (d₁ * d₂) : by simp [mul_add, mul_comm, mul_left_comm]
end
protected def neg : ℚ → ℚ
| ⟨n, d, h, c⟩ := ⟨-n, d, h, by simp [c]⟩
instance : has_neg ℚ := ⟨rat.neg⟩
@[simp] theorem neg_def {a b : ℤ} : -(a /. b) = -a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
show rat.mk' _ _ _ _ = _, rw num_denom',
have d0 := ne_of_gt (int.coe_nat_lt.2 h₁),
apply (mk_eq d0 b0).2, have h₁ := (mk_eq b0 d0).1 ha,
simp only [neg_mul_eq_neg_mul_symm, congr_arg has_neg.neg h₁]
end
protected def mul : ℚ → ℚ → ℚ
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * n₂) ⟨d₁ * d₂, mul_pos h₁ h₂⟩
instance : has_mul ℚ := ⟨rat.mul⟩
@[simp] theorem mul_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
(a /. b) * (c /. d) = (a * c) /. (b * d) :=
begin
apply lift_binop_eq rat.mul; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero d₁0 d₂0 },
cc
end
protected def inv : ℚ → ℚ
| ⟨(n+1:ℕ), d, h, c⟩ := ⟨d, n+1, n.succ_pos, c.symm⟩
| ⟨0, d, h, c⟩ := 0
| ⟨-[1+ n], d, h, c⟩ := ⟨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact c⟩
instance : has_inv ℚ := ⟨rat.inv⟩
@[simp] theorem inv_def {a b : ℤ} : (a /. b)⁻¹ = b /. a :=
begin
by_cases a0 : a = 0, { subst a0, simp, refl },
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha,
refine eq.trans (_ : rat.inv ⟨n, d, h, c⟩ = d /. n) _,
{ cases n with n; [cases n with n, skip],
{ refl },
{ change int.of_nat n.succ with (n+1:ℕ),
unfold rat.inv, rw num_denom' },
{ unfold rat.inv, rw num_denom', refl } },
have n0 : n ≠ 0,
{ refine mt (λ (n0 : n = 0), _) a0,
subst n0, simp at ha,
exact (mk_eq_zero b0).1 ha },
have d0 := ne_of_gt (int.coe_nat_lt.2 h),
have ha := (mk_eq b0 d0).1 ha,
apply (mk_eq n0 a0).2,
cc
end
variables (a b c : ℚ)
protected theorem add_zero : a + 0 = a :=
num_denom_cases_on' a $ λ n d h,
by rw [← zero_mk d]; simp [h, -zero_mk]
protected theorem zero_add : 0 + a = a :=
num_denom_cases_on' a $ λ n d h,
by rw [← zero_mk d]; simp [h, -zero_mk]
protected theorem add_comm : a + b = b + a :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
by simp [h₁, h₂, mul_comm]
protected theorem add_assoc : a + b + c = a + (b + c) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero, mul_add, mul_comm, mul_left_comm, add_left_comm]
protected theorem add_left_neg : -a + a = 0 :=
num_denom_cases_on' a $ λ n d h,
by simp [h]
protected theorem mul_one : a * 1 = a :=
num_denom_cases_on' a $ λ n d h,
by change (1:ℚ) with 1 /. 1; simp [h]
protected theorem one_mul : 1 * a = a :=
num_denom_cases_on' a $ λ n d h,
by change (1:ℚ) with 1 /. 1; simp [h]
protected theorem mul_comm : a * b = b * a :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
by simp [h₁, h₂, mul_comm]
protected theorem mul_assoc : a * b * c = a * (b * c) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero, mul_comm, mul_left_comm]
protected theorem add_mul : (a + b) * c = a * c + b * c :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero];
refine (div_mk_div_cancel_left (int.coe_nat_ne_zero.2 h₃)).symm.trans _;
simp [mul_add, mul_comm, mul_assoc, mul_left_comm]
protected theorem mul_add : a * (b + c) = a * b + a * c :=
by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a]
protected theorem zero_ne_one : 0 ≠ (1:ℚ) :=
mt (λ (h : 0 = 1 /. 1), (mk_eq_zero one_ne_zero).1 h.symm) one_ne_zero
protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 :=
num_denom_cases_on' a $ λ n d h a0,
have n0 : n ≠ 0, from mt (by intro e; subst e; simp) a0,
by simp [h, n0, mul_comm]; exact
eq.trans (by simp) (@div_mk_div_cancel_left 1 1 _ n0)
protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 :=
eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h)
instance : decidable_eq ℚ := by tactic.mk_dec_eq_instance
instance field_rat : discrete_field ℚ :=
{ zero := 0,
add := rat.add,
neg := rat.neg,
one := 1,
mul := rat.mul,
inv := rat.inv,
zero_add := rat.zero_add,
add_zero := rat.add_zero,
add_comm := rat.add_comm,
add_assoc := rat.add_assoc,
add_left_neg := rat.add_left_neg,
mul_one := rat.mul_one,
one_mul := rat.one_mul,
mul_comm := rat.mul_comm,
mul_assoc := rat.mul_assoc,
left_distrib := rat.mul_add,
right_distrib := rat.add_mul,
zero_ne_one := rat.zero_ne_one,
mul_inv_cancel := rat.mul_inv_cancel,
inv_mul_cancel := rat.inv_mul_cancel,
has_decidable_eq := rat.decidable_eq,
inv_zero := rfl }
theorem sub_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
a /. b - c /. d = (a * d - c * b) /. (b * d) :=
by simp [b0, d0]
protected def nonneg : ℚ → Prop
| ⟨n, d, h, c⟩ := n ≥ 0
@[simp] theorem mk_nonneg (a : ℤ) {b : ℤ} (h : b > 0) : (a /. b).nonneg ↔ a ≥ 0 :=
begin
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
simp [rat.nonneg],
have d0 := int.coe_nat_lt.2 h₁,
have := (mk_eq (ne_of_gt h) (ne_of_gt d0)).1 ha,
constructor; intro h₂,
{ apply nonneg_of_mul_nonneg_right _ d0,
rw this, exact mul_nonneg h₂ (le_of_lt h) },
{ apply nonneg_of_mul_nonneg_right _ h,
rw ← this, exact mul_nonneg h₂ (int.coe_zero_le _) },
end
protected def nonneg_add {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a + b) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
begin
have d₁0 : (d₁:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁),
have d₂0 : (d₂:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂),
simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0],
intros n₁0 n₂0,
apply add_nonneg; apply mul_nonneg; {assumption <|> apply int.coe_zero_le}
end
protected def nonneg_mul {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a * b) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
begin
have d₁0 : (d₁:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁),
have d₂0 : (d₂:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂),
simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0],
exact mul_nonneg
end
protected def nonneg_antisymm {a} : rat.nonneg a → rat.nonneg (-a) → a = 0 :=
num_denom_cases_on' a $ λ n d h,
begin
have d0 : (d:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h),
simp [d0, h],
exact λ h₁ h₂, le_antisymm (nonpos_of_neg_nonneg h₂) h₁
end
protected def nonneg_total : rat.nonneg a ∨ rat.nonneg (-a) :=
by cases a with n; exact
or.imp_right neg_nonneg_of_nonpos (le_total 0 n)
instance decidable_nonneg : decidable (rat.nonneg a) :=
by cases a; unfold rat.nonneg; apply_instance
protected def le (a b : ℚ) := rat.nonneg (b - a)
instance : has_le ℚ := ⟨rat.le⟩
instance decidable_le : decidable_rel ((≤) : ℚ → ℚ → Prop)
| a b := show decidable (rat.nonneg (b - a)), by apply_instance
protected theorem le_def {a b c d : ℤ} (b0 : b > 0) (d0 : d > 0) :
a /. b ≤ c /. d ↔ a * d ≤ c * b :=
show rat.nonneg _ ↔ _,
by simpa [ne_of_gt b0, ne_of_gt d0, mul_pos b0 d0, mul_comm]
using @sub_nonneg _ _ (b * c) (a * d)
protected theorem le_refl : a ≤ a :=
show rat.nonneg (a - a), by rw sub_self; exact le_refl (0 : ℤ)
protected theorem le_total : a ≤ b ∨ b ≤ a :=
by have := rat.nonneg_total (b - a); rwa neg_sub at this
protected theorem le_antisymm {a b : ℚ} (hab : a ≤ b) (hba : b ≤ a) : a = b :=
by have := eq_neg_of_add_eq_zero (rat.nonneg_antisymm hba $ by simpa);
rwa neg_neg at this
protected theorem le_trans {a b c : ℚ} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c :=
have rat.nonneg (b - a + (c - b)), from rat.nonneg_add hab hbc,
have rat.nonneg (c - a + (b - b)), by simpa [-add_right_neg, add_left_comm],
by simpa
instance : decidable_linear_order ℚ :=
{ le := rat.le,
le_refl := rat.le_refl,
le_trans := @rat.le_trans,
le_antisymm := @rat.le_antisymm,
le_total := rat.le_total,
decidable_eq := by apply_instance,
decidable_le := assume a b, rat.decidable_nonneg (b - a) }
theorem nonneg_iff_zero_le {a} : rat.nonneg a ↔ 0 ≤ a :=
show rat.nonneg a ↔ rat.nonneg (a - 0), by simp
theorem num_nonneg_iff_zero_le : ∀ {a : ℚ}, 0 ≤ a.num ↔ 0 ≤ a
| ⟨n, d, h, c⟩ := @nonneg_iff_zero_le ⟨n, d, h, c⟩
theorem mk_le {a b c d : ℤ} (h₁ : b > 0) (h₂ : d > 0) :
a /. b ≤ c /. d ↔ a * d ≤ c * b :=
by conv in (_ ≤ _) {
simp only [(≤), rat.le],
rw [sub_def (ne_of_gt h₂) (ne_of_gt h₁),
mk_nonneg _ (mul_pos h₂ h₁), ge, sub_nonneg] }
protected theorem add_le_add_left {a b c : ℚ} : c + a ≤ c + b ↔ a ≤ b :=
by unfold has_le.le rat.le; rw add_sub_add_left_eq_sub
protected theorem mul_nonneg {a b : ℚ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b :=
by rw ← nonneg_iff_zero_le at ha hb ⊢; exact rat.nonneg_mul ha hb
instance : discrete_linear_ordered_field ℚ :=
{ zero_lt_one := dec_trivial,
add_le_add_left := assume a b ab c, rat.add_le_add_left.2 ab,
add_lt_add_left := assume a b ab c, lt_of_not_ge $ λ ba,
not_le_of_lt ab $ rat.add_le_add_left.1 ba,
mul_nonneg := @rat.mul_nonneg,
mul_pos := assume a b ha hb, lt_of_le_of_ne
(rat.mul_nonneg (le_of_lt ha) (le_of_lt hb))
(mul_ne_zero (ne_of_lt ha).symm (ne_of_lt hb).symm).symm,
..rat.field_rat, ..rat.decidable_linear_order }
theorem num_pos_iff_pos {a : ℚ} : 0 < a.num ↔ 0 < a :=
le_iff_le_iff_lt_iff_lt.1 $
by simpa [(by cases a; refl : (-a).num = -a.num)]
using @num_nonneg_iff_zero_le (-a)
theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom' _ _ _ _
theorem coe_int_eq_mk : ∀ z : ℤ, ↑z = z /. 1
| (n : ℕ) := show (n:ℚ) = n /. 1,
by induction n with n IH n; simp [*, show (1:ℚ) = 1 /. 1, from rfl]
| -[1+ n] := show (-(n + 1) : ℚ) = -[1+ n] /. 1, begin
induction n with n IH, {refl},
show -(n + 1 + 1 : ℚ) = -[1+ n.succ] /. 1,
rw [neg_add, IH],
simpa [show -1 = (-1) /. 1, from rfl]
end
theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z :=
(coe_int_eq_mk z).trans (of_int_eq_mk z).symm
theorem mk_eq_div (n d : ℤ) : n /. d = (n / d : ℚ) :=
begin
by_cases d0 : d = 0, {simp [d0, div_zero]},
rw [division_def, coe_int_eq_mk, coe_int_eq_mk, inv_def,
mul_def one_ne_zero d0, one_mul, mul_one]
end
/-- `floor q` is the largest integer `z` such that `z ≤ q` -/
def floor : ℚ → ℤ
| ⟨n, d, h, c⟩ := n / d
theorem le_floor {z : ℤ} : ∀ {r : ℚ}, z ≤ floor r ↔ (z : ℚ) ≤ r
| ⟨n, d, h, c⟩ := begin
simp [floor],
rw [num_denom'],
have h' := int.coe_nat_lt.2 h,
conv { to_rhs,
rw [coe_int_eq_mk, mk_le zero_lt_one h', mul_one] },
exact int.le_div_iff_mul_le h'
end
theorem floor_lt {r : ℚ} {z : ℤ} : floor r < z ↔ r < z :=
le_iff_le_iff_lt_iff_lt.1 le_floor
theorem floor_le (r : ℚ) : (floor r : ℚ) ≤ r :=
le_floor.1 (le_refl _)
theorem lt_succ_floor (r : ℚ) : r < (floor r).succ :=
floor_lt.1 $ int.lt_succ_self _
@[simp] theorem floor_coe (z : ℤ) : floor z = z :=
eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le]
theorem floor_mono {a b : ℚ} (h : a ≤ b) : floor a ≤ floor b :=
le_floor.2 (le_trans (floor_le _) h)
@[simp] theorem floor_add_int (r : ℚ) (z : ℤ) : floor (r + z) = floor r + z :=
eq_of_forall_le_iff $ λ a, by rw [le_floor,
← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub]
theorem floor_sub_int (r : ℚ) (z : ℤ) : floor (r - z) = floor r - z :=
eq.trans (by rw [int.cast_neg]; refl) (floor_add_int _ _)
/-- `ceil q` is the smallest integer `z` such that `q ≤ z` -/
def ceil (r : ℚ) : ℤ :=
-(floor (-r))
theorem ceil_le {z : ℤ} {r : ℚ} : ceil r ≤ z ↔ r ≤ z :=
by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff]
theorem le_ceil (r : ℚ) : r ≤ ceil r :=
ceil_le.1 (le_refl _)
@[simp] theorem ceil_coe (z : ℤ) : ceil z = z :=
by rw [ceil, ← int.cast_neg, floor_coe, neg_neg]
theorem ceil_mono {a b : ℚ} (h : a ≤ b) : ceil a ≤ ceil b :=
ceil_le.2 (le_trans h (le_ceil _))
@[simp] theorem ceil_add_int (r : ℚ) (z : ℤ) : ceil (r + z) = ceil r + z :=
by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl
theorem ceil_sub_int (r : ℚ) (z : ℤ) : ceil (r - z) = ceil r - z :=
eq.trans (by rw [int.cast_neg]; refl) (ceil_add_int _ _)
/- cast (injection into fields) -/
section cast
variables {α : Type*}
section
variables [division_ring α]
/-- Construct the canonical injection from `ℚ` into an arbitrary
division ring. If the field has positive characteristic `p`,
we define `1 / p = 1 / 0 = 0` for consistency with our
division by zero convention. -/
protected def cast : ℚ → α
| ⟨n, d, h, c⟩ := n / d
@[priority 0] instance cast_coe : has_coe ℚ α := ⟨rat.cast⟩
@[simp] theorem cast_of_int (n : ℤ) : (of_int n : α) = n :=
show (n / (1:ℕ) : α) = n, by rw [nat.cast_one, div_one]
@[simp] theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n :=
by rw [coe_int_eq_of_int, cast_of_int]
@[simp] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n :=
by rw coe_int_eq_of_int; refl
@[simp] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 :=
by rw coe_int_eq_of_int; refl
@[simp] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n :=
by rw [← int.cast_coe_nat, coe_int_num]
@[simp] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 :=
by rw [← int.cast_coe_nat, coe_int_denom]
@[simp] theorem cast_coe_nat (n : ℕ) : ((n : ℚ) : α) = n := cast_coe_int n
@[simp] theorem cast_zero : ((0 : ℚ) : α) = 0 :=
(cast_of_int _).trans int.cast_zero
@[simp] theorem cast_one : ((1 : ℚ) : α) = 1 :=
(cast_of_int _).trans int.cast_one
theorem mul_cast_comm (a : α) :
∀ (n : ℚ), (n.denom : α) ≠ 0 → a * n = n * a
| ⟨n, d, h, c⟩ h₂ := show a * (n * d⁻¹) = n * d⁻¹ * a,
by rw [← mul_assoc, int.mul_cast_comm, mul_assoc, mul_assoc,
← show (d:α)⁻¹ * a = a * d⁻¹, from
division_ring.inv_comm_of_comm h₂ (int.mul_cast_comm a d).symm]
theorem cast_mk_of_ne_zero (a b : ℤ)
(b0 : (b:α) ≠ 0) : (a /. b : α) = a / b :=
begin
have b0' : b ≠ 0, { refine mt _ b0, simp {contextual := tt} },
cases e : a /. b with n d h c,
have d0 : (d:α) ≠ 0,
{ intro d0,
have dd := denom_dvd a b,
cases (show (d:ℤ) ∣ b, by rwa e at dd) with k ke,
have : (b:α) = (d:α) * (k:α), {rw [ke, int.cast_mul], refl},
rw [d0, zero_mul] at this, contradiction },
rw [num_denom'] at e,
have := congr_arg (coe : ℤ → α) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e),
rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this,
symmetry, change (a * b⁻¹ : α) = n / d,
rw [eq_div_iff_mul_eq _ _ d0, mul_assoc, nat.mul_cast_comm,
← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one]
end
theorem cast_add_of_ne_zero : ∀ {m n : ℚ},
(m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m + n : ℚ) : α) = m + n
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin
have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl),
have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl),
rw [num_denom', num_denom', add_def d₁0' d₂0'],
suffices : (n₁ * (d₂ * (d₂⁻¹ * d₁⁻¹)) +
n₂ * (d₁ * d₂⁻¹) * d₁⁻¹ : α) = n₁ * d₁⁻¹ + n₂ * d₂⁻¹,
{ rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero],
{ simpa [division_def, left_distrib, right_distrib, mul_inv_eq,
d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] },
all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} },
rw [← mul_assoc (d₂:α), mul_inv_cancel d₂0, one_mul,
← nat.mul_cast_comm], simp [d₁0, mul_assoc]
end
@[simp] theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n
| ⟨n, d, h, c⟩ := show (↑-n * d⁻¹ : α) = -(n * d⁻¹),
by rw [int.cast_neg, neg_mul_eq_neg_mul]
theorem cast_sub_of_ne_zero {m n : ℚ}
(m0 : (m.denom : α) ≠ 0) (n0 : (n.denom : α) ≠ 0) : ((m - n : ℚ) : α) = m - n :=
have ((-n).denom : α) ≠ 0, by cases n; exact n0,
by simp [m0, this, cast_add_of_ne_zero]
theorem cast_mul_of_ne_zero : ∀ {m n : ℚ},
(m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m * n : ℚ) : α) = m * n
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin
have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl),
have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl),
rw [num_denom', num_denom', mul_def d₁0' d₂0'],
suffices : (n₁ * ((n₂ * d₂⁻¹) * d₁⁻¹) : α) = n₁ * (d₁⁻¹ * (n₂ * d₂⁻¹)),
{ rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero],
{ simpa [division_def, mul_inv_eq, d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] },
all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} },
rw [division_ring.inv_comm_of_comm d₁0 (nat.mul_cast_comm _ _).symm]
end
theorem cast_inv_of_ne_zero : ∀ {n : ℚ},
(n.num : α) ≠ 0 → (n.denom : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = n⁻¹
| ⟨n, d, h, c⟩ := λ (n0 : (n:α) ≠ 0) (d0 : (d:α) ≠ 0), begin
have n0' : (n:ℤ) ≠ 0 := λ e, by rw e at n0; exact n0 rfl,
have d0' : (d:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d0; exact d0 rfl),
rw [num_denom', inv_def],
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div];
simp [n0, d0]
end
theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.denom : α) ≠ 0)
(nn : (n.num : α) ≠ 0) (nd : (n.denom : α) ≠ 0) : ((m / n : ℚ) : α) = m / n :=
have (n⁻¹.denom : ℤ) ∣ n.num,
by conv in n⁻¹.denom { rw [num_denom n, inv_def] };
apply denom_dvd,
have (n⁻¹.denom : α) = 0 → (n.num : α) = 0, from
λ h, let ⟨k, e⟩ := this in
by have := congr_arg (coe : ℤ → α) e;
rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this,
by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def]
@[simp] theorem cast_inj [char_zero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := begin
refine ⟨λ h, _, congr_arg _⟩,
have d₁0 : d₁ ≠ 0 := ne_of_gt h₁,
have d₂0 : d₂ ≠ 0 := ne_of_gt h₂,
have d₁a : (d₁:α) ≠ 0 := nat.cast_ne_zero.2 d₁0,
have d₂a : (d₂:α) ≠ 0 := nat.cast_ne_zero.2 d₂0,
rw [num_denom', num_denom'] at h ⊢,
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [d₁0, d₂0] at h ⊢,
rwa [eq_div_iff_mul_eq _ _ d₂a, division_def, mul_assoc,
division_ring.inv_comm_of_comm d₁a (nat.mul_cast_comm _ _),
← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq _ _ d₁a, eq_comm,
← int.cast_coe_nat, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul,
int.cast_inj, ← mk_eq (int.coe_nat_ne_zero.2 d₁0) (int.coe_nat_ne_zero.2 d₂0)] at h
end
theorem cast_injective [char_zero α] : function.injective (coe : ℚ → α)
| m n := cast_inj.1
@[simp] theorem cast_eq_zero [char_zero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 :=
by rw [← cast_zero, cast_inj]
@[simp] theorem cast_ne_zero [char_zero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 :=
not_congr cast_eq_zero
theorem eq_cast_of_ne_zero (f : ℚ → α) (H1 : f 1 = 1)
(Hadd : ∀ x y, f (x + y) = f x + f y)
(Hmul : ∀ x y, f (x * y) = f x * f y) :
∀ n : ℚ, (n.denom : α) ≠ 0 → f n = n
| ⟨n, d, h, c⟩ := λ (h₂ : ((d:ℤ):α) ≠ 0), show _ = (n / (d:ℤ) : α), begin
rw [num_denom', mk_eq_div, eq_div_iff_mul_eq _ _ h₂],
have : ∀ n : ℤ, f n = n, { apply int.eq_cast; simp [H1, Hadd] },
rw [← this, ← this, ← Hmul, div_mul_cancel],
exact int.cast_ne_zero.2 (int.coe_nat_ne_zero.2 $ ne_of_gt h),
end
theorem eq_cast [char_zero α] (f : ℚ → α) (H1 : f 1 = 1)
(Hadd : ∀ x y, f (x + y) = f x + f y)
(Hmul : ∀ x y, f (x * y) = f x * f y) (n : ℚ) : f n = n :=
eq_cast_of_ne_zero _ H1 Hadd Hmul _ $
nat.cast_ne_zero.2 $ ne_of_gt n.pos
end
theorem cast_mk [discrete_field α] [char_zero α] (a b : ℤ) : ((a /. b) : α) = a / b :=
if b0 : b = 0 then by simp [b0, div_zero]
else cast_mk_of_ne_zero a b (int.cast_ne_zero.2 b0)
@[simp] theorem cast_add [division_ring α] [char_zero α] (m n) : ((m + n : ℚ) : α) = m + n :=
cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_sub [division_ring α] [char_zero α] (m n) : ((m - n : ℚ) : α) = m - n :=
cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_mul [division_ring α] [char_zero α] (m n) : ((m * n : ℚ) : α) = m * n :=
cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_inv [discrete_field α] [char_zero α] (n) : ((n⁻¹ : ℚ) : α) = n⁻¹ :=
if n0 : n.num = 0 then
by simp [show n = 0, by rw [num_denom n, n0]; simp, inv_zero] else
cast_inv_of_ne_zero (int.cast_ne_zero.2 n0) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_div [discrete_field α] [char_zero α] (m n) : ((m / n : ℚ) : α) = m / n :=
by rw [division_def, cast_mul, cast_inv, division_def]
@[simp] theorem cast_bit0 [division_ring α] [char_zero α] (n : ℚ) : ((bit0 n : ℚ) : α) = bit0 n := cast_add _ _
@[simp] theorem cast_bit1 [division_ring α] [char_zero α] (n : ℚ) : ((bit1 n : ℚ) : α) = bit1 n :=
by rw [bit1, cast_add, cast_one, cast_bit0]; refl
@[simp] theorem cast_nonneg [linear_ordered_field α] : ∀ {n : ℚ}, 0 ≤ (n : α) ↔ 0 ≤ n
| ⟨n, d, h, c⟩ := show 0 ≤ (n * d⁻¹ : α) ↔ 0 ≤ (⟨n, d, h, c⟩ : ℚ),
by rw [num_denom', ← nonneg_iff_zero_le, mk_nonneg _ (int.coe_nat_pos.2 h),
mul_nonneg_iff_right_nonneg_of_pos (@inv_pos α _ _ (nat.cast_pos.2 h)),
int.cast_nonneg]
@[simp] theorem cast_le [linear_ordered_field α] {m n : ℚ} : (m : α) ≤ n ↔ m ≤ n :=
by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg]
@[simp] theorem cast_lt [linear_ordered_field α] {m n : ℚ} : (m : α) < n ↔ m < n :=
by simpa [-cast_le] using not_congr (@cast_le α _ n m)
@[simp] theorem cast_nonpos [linear_ordered_field α] {n : ℚ} : (n : α) ≤ 0 ↔ n ≤ 0 :=
by rw [← cast_zero, cast_le]
@[simp] theorem cast_pos [linear_ordered_field α] {n : ℚ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_lt_zero [linear_ordered_field α] {n : ℚ} : (n : α) < 0 ↔ n < 0 :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_id : ∀ n : ℚ, ↑n = n
| ⟨n, d, h, c⟩ := show (n / (d : ℤ) : ℚ) = _, by rw [num_denom', mk_eq_div]
@[simp] theorem cast_min [discrete_linear_ordered_field α] {a b : ℚ} : (↑(min a b) : α) = min a b :=
by by_cases a ≤ b; simp [h, min]
@[simp] theorem cast_max [discrete_linear_ordered_field α] {a b : ℚ} : (↑(max a b) : α) = max a b :=
by by_cases a ≤ b; simp [h, max]
@[simp] theorem cast_abs [discrete_linear_ordered_field α] {q : ℚ} : ((abs q : ℚ) : α) = abs q :=
by simp [abs]
end cast
/- nat ceiling -/
/-- `nat_ceil q` is the smallest nonnegative integer `n` with `q ≤ n`.
It is the same as `ceil q` when `q ≥ 0`, otherwise it is `0`. -/
def nat_ceil (q : ℚ) : ℕ := int.to_nat (ceil q)
theorem nat_ceil_le {q : ℚ} {n : ℕ} : nat_ceil q ≤ n ↔ q ≤ n :=
by rw [nat_ceil, int.to_nat_le, ceil_le]; refl
theorem lt_nat_ceil {q : ℚ} {n : ℕ} : n < nat_ceil q ↔ (n : ℚ) < q :=
not_iff_not.1 $ by rw [not_lt, not_lt, nat_ceil_le]
theorem le_nat_ceil (q : ℚ) : q ≤ nat_ceil q :=
nat_ceil_le.1 (le_refl _)
theorem nat_ceil_mono {q₁ q₂ : ℚ} (h : q₁ ≤ q₂) : nat_ceil q₁ ≤ nat_ceil q₂ :=
nat_ceil_le.2 (le_trans h (le_nat_ceil _))
@[simp] theorem nat_ceil_coe (n : ℕ) : nat_ceil n = n :=
show (ceil (n:ℤ)).to_nat = n, by rw [ceil_coe]; refl
@[simp] theorem nat_ceil_zero : nat_ceil 0 = 0 := nat_ceil_coe 0
theorem nat_ceil_add_nat {q : ℚ} (hq : 0 ≤ q) (n : ℕ) : nat_ceil (q + n) = nat_ceil q + n :=
show int.to_nat (ceil (q + (n:ℤ))) = int.to_nat (ceil q) + n,
by rw [ceil_add_int]; exact
match ceil q, int.eq_coe_of_zero_le (ceil_mono hq) with
| _, ⟨m, rfl⟩ := rfl
end
theorem nat_ceil_lt_add_one {q : ℚ} (hq : q ≥ 0) : ↑(nat_ceil q) < q + 1 :=
lt_nat_ceil.1 $ by rw [
show nat_ceil (q+1) = nat_ceil q+1, from nat_ceil_add_nat hq 1]; apply nat.lt_succ_self
end rat
|
23f11a2b0d260edb4dfeacf54958bbcb73e8b2cd | f57749ca63d6416f807b770f67559503fdb21001 | /library/data/set/default.lean | b10e1aead6c5673057947a28cbc63a0245ddc691 | [
"Apache-2.0"
] | permissive | aliassaf/lean | bd54e85bed07b1ff6f01396551867b2677cbc6ac | f9b069b6a50756588b309b3d716c447004203152 | refs/heads/master | 1,610,982,152,948 | 1,438,916,029,000 | 1,438,916,029,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 180 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
-/
import .basic .function .map
|
afae55c1a529cfbbf8be5441f1f4235dd4c9946f | b561a44b48979a98df50ade0789a21c79ee31288 | /stage0/src/Lean/Elab/PreDefinition/WF/Fix.lean | 0526170688063eca2c5c38482b3e19688610d8d8 | [
"Apache-2.0"
] | permissive | 3401ijk/lean4 | 97659c475ebd33a034fed515cb83a85f75ccfb06 | a5b1b8de4f4b038ff752b9e607b721f15a9a4351 | refs/heads/master | 1,693,933,007,651 | 1,636,424,845,000 | 1,636,424,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,921 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Match.Match
import Lean.Meta.Tactic.Simp.Main
import Lean.Meta.Tactic.Cleanup
import Lean.Elab.PreDefinition.Basic
import Lean.Elab.PreDefinition.Structural.Basic
namespace Lean.Elab.WF
open Meta
private def toUnfold : Std.PHashSet Name :=
[``measure, ``id, ``Prod.lex, ``invImage, ``InvImage, ``Nat.lt_wfRel].foldl (init := {}) fun s a => s.insert a
private def applyDefaultDecrTactic (mvarId : MVarId) : TermElabM Unit := do
let ctx ← Simp.Context.mkDefault
let ctx := { ctx with simpLemmas.toUnfold := toUnfold }
if let some mvarId ← simpTarget mvarId ctx then
-- TODO: invoke tactic to close the goal
trace[Elab.definition.wf] "{MessageData.ofGoal mvarId}"
admit mvarId
private def mkDecreasingProof (decreasingProp : Expr) (decrTactic? : Option Syntax) : TermElabM Expr := do
let mvar ← mkFreshExprSyntheticOpaqueMVar decreasingProp
let mvarId := mvar.mvarId!
let mvarId ← cleanup mvarId
match decrTactic? with
| none => applyDefaultDecrTactic mvarId
| some decrTactic => Term.runTactic mvarId decrTactic
instantiateMVars mvar
private partial def replaceRecApps (recFnName : Name) (decrTactic? : Option Syntax) (F : Expr) (e : Expr) : TermElabM Expr :=
let rec loop (F : Expr) (e : Expr) : TermElabM Expr := do
match e with
| Expr.lam n d b c =>
withLocalDecl n c.binderInfo (← loop F d) fun x => do
mkLambdaFVars #[x] (← loop F (b.instantiate1 x))
| Expr.forallE n d b c =>
withLocalDecl n c.binderInfo (← loop F d) fun x => do
mkForallFVars #[x] (← loop F (b.instantiate1 x))
| Expr.letE n type val body _ =>
withLetDecl n (← loop F type) (← loop F val) fun x => do
mkLetFVars #[x] (← loop F (body.instantiate1 x)) (usedLetOnly := false)
| Expr.mdata d e _ => return mkMData d (← loop F e)
| Expr.proj n i e _ => return mkProj n i (← loop F e)
| Expr.app _ _ _ =>
let processApp (e : Expr) : TermElabM Expr :=
e.withApp fun f args => do
if f.isConstOf recFnName && args.size == 1 then
let r := mkApp F args[0]
let decreasingProp := (← whnf (← inferType r)).bindingDomain!
return mkApp r (← mkDecreasingProof decreasingProp decrTactic?)
else
return mkAppN (← loop F f) (← args.mapM (loop F))
let matcherApp? ← matchMatcherApp? e
match matcherApp? with
| some matcherApp =>
if !Structural.recArgHasLooseBVarsAt recFnName 0 e then
processApp e
else
let matcherApp ← mapError (matcherApp.addArg F) (fun msg => "failed to add functional argument to 'matcher' application" ++ indentD msg)
let altsNew ← (Array.zip matcherApp.alts matcherApp.altNumParams).mapM fun (alt, numParams) =>
lambdaTelescope alt fun xs altBody => do
unless xs.size >= numParams do
throwError "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}"
let FAlt := xs[numParams - 1]
mkLambdaFVars xs (← loop FAlt altBody)
pure { matcherApp with alts := altsNew }.toExpr
| none => processApp e
| e => Structural.ensureNoRecFn recFnName e
loop F e
/-- Refine `F` over `Sum.casesOn` -/
private partial def processSumCasesOn (x F val : Expr) (k : (x : Expr) → (F : Expr) → (val : Expr) → TermElabM Expr) : TermElabM Expr := do
if x.isFVar && val.isAppOfArity ``Sum.casesOn 6 && val.getArg! 3 == x && (val.getArg! 4).isLambda && (val.getArg! 5).isLambda then
let args := val.getAppArgs
let α := args[0]
let β := args[1]
let FDecl ← getLocalDecl F.fvarId!
let (motiveNew, u) ← lambdaTelescope args[2] fun xs type => do
let type ← mkArrow (FDecl.type.replaceFVar x xs[0]) type
return (← mkLambdaFVars xs type, ← getLevel type)
let mkMinorNew (ctorName : Name) (minor : Expr) : TermElabM Expr :=
lambdaTelescope minor fun xs body => do
let xNew ← xs[0]
let valNew ← mkLambdaFVars xs[1:] body
let FTypeNew := FDecl.type.replaceFVar x (← mkAppOptM ctorName #[α, β, xNew])
withLocalDeclD FDecl.userName FTypeNew fun FNew => do
mkLambdaFVars #[xNew, FNew] (← processSumCasesOn xNew FNew valNew k)
let minorLeft ← mkMinorNew ``Sum.inl args[4]
let minorRight ← mkMinorNew ``Sum.inr args[5]
let result := mkAppN (mkConst ``Sum.casesOn [u, (← getDecLevel α), (← getDecLevel β)]) #[α, β, motiveNew, x, minorLeft, minorRight, F]
return result
else
k x F val
/-- Refine `F` over `PSigma.casesOn` -/
private partial def processPSigmaCasesOn (x F val : Expr) (k : (F : Expr) → (val : Expr) → TermElabM Expr) : TermElabM Expr := do
if x.isFVar && val.isAppOfArity ``PSigma.casesOn 5 && val.getArg! 3 == x && (val.getArg! 4).isLambda && (val.getArg! 4).bindingBody!.isLambda then
let args := val.getAppArgs
let [_, u, v] ← val.getAppFn.constLevels! | unreachable!
let α := args[0]
let β := args[1]
let FDecl ← getLocalDecl F.fvarId!
let (motiveNew, w) ← lambdaTelescope args[2] fun xs type => do
let type ← mkArrow (FDecl.type.replaceFVar x xs[0]) type
return (← mkLambdaFVars xs type, ← getLevel type)
let minor ← lambdaTelescope args[4] fun xs body => do
let a ← xs[0]
let xNew ← xs[1]
let valNew ← mkLambdaFVars xs[2:] body
let FTypeNew := FDecl.type.replaceFVar x (← mkAppOptM `PSigma.mk #[α, β, a, xNew])
withLocalDeclD FDecl.userName FTypeNew fun FNew => do
mkLambdaFVars #[a, xNew, FNew] (← processPSigmaCasesOn xNew FNew valNew k)
let result := mkAppN (mkConst ``PSigma.casesOn [w, u, v]) #[α, β, motiveNew, x, minor, F]
return result
else
k F val
def mkFix (preDef : PreDefinition) (wfRel : Expr) (decrTactic? : Option Syntax) : TermElabM PreDefinition := do
let wfFix ← forallBoundedTelescope preDef.type (some 1) fun x type => do
let x := x[0]
let α ← inferType x
let u ← getLevel α
let v ← getLevel type
let motive ← mkLambdaFVars #[x] type
let rel := mkProj ``WellFoundedRelation 0 wfRel
let wf := mkProj ``WellFoundedRelation 1 wfRel
return mkApp4 (mkConst ``WellFounded.fix [u, v]) α motive rel wf
forallBoundedTelescope (← whnf (← inferType wfFix)).bindingDomain! (some 2) fun xs _ => do
let x := xs[0]
let F := xs[1]
let val := preDef.value.betaRev #[x]
let val ← processSumCasesOn x F val fun x F val => processPSigmaCasesOn x F val (replaceRecApps preDef.declName decrTactic?)
return { preDef with value := mkApp wfFix (← mkLambdaFVars #[x, F] val) }
end Lean.Elab.WF
|
dd447de85b6da766226f961dba1336710361265b | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/category_theory/limits/shapes/regular_mono.lean | 4710a7a309cb8e4bf76d8519ed2241204f0bc4f0 | [
"Apache-2.0"
] | permissive | vaibhavkarve/mathlib | a574aaf68c0a431a47fa82ce0637f0f769826bfe | 17f8340912468f49bdc30acdb9a9fa02eeb0473a | refs/heads/master | 1,621,263,802,637 | 1,585,399,588,000 | 1,585,399,588,000 | 250,833,447 | 0 | 0 | Apache-2.0 | 1,585,410,341,000 | 1,585,410,341,000 | null | UTF-8 | Lean | false | false | 3,190 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.epi_mono
import category_theory.limits.shapes.kernels
/-!
# Definitions and basic properties of regular and normal monomorphisms and epimorphisms.
A regular monomorphism is a morphism that is the equalizer of some parallel pair.
A normal monomorphism is a morphism that is the kernel of some other morphism.
We give the constructions
* `split_mono → regular_mono`
* `normal_mono → regular_mono`, and
* `regular_mono → mono`.
-/
namespace category_theory
open category_theory.limits
universes v₁ u₁
variables {C : Type u₁} [𝒞 : category.{v₁} C]
include 𝒞
variables {X Y : C}
/-- A regular monomorphism is a morphism which is the equalizer of some parallel pair. -/
class regular_mono (f : X ⟶ Y) :=
(Z : C)
(left right : Y ⟶ Z)
(w : f ≫ left = f ≫ right)
(is_limit : is_limit (fork.of_ι f w))
/-- Every regular monomorphism is a monomorphism. -/
@[priority 100]
instance regular_mono.mono (f : X ⟶ Y) [regular_mono f] : mono f :=
mono_of_is_limit_parallel_pair (regular_mono.is_limit f)
/-- Every split monomorphism is a regular monomorphism. -/
@[priority 100]
instance regular_mono.of_split_mono (f : X ⟶ Y) [split_mono f] : regular_mono f :=
{ Z := Y,
left := 𝟙 Y,
right := retraction f ≫ f,
w := by tidy,
is_limit := split_mono_equalizes f }
section
variables [has_zero_morphisms.{v₁} C]
/-- A normal monomorphism is a morphism which is the kernel of some morphism. -/
class normal_mono (f : X ⟶ Y) :=
(Z : C)
(g : Y ⟶ Z)
(w : f ≫ g = 0)
(is_limit : is_limit (kernel_fork.of_ι f w))
/-- Every normal monomorphism is a regular monomorphism. -/
@[priority 100]
instance normal_mono.regular_mono (f : X ⟶ Y) [I : normal_mono f] : regular_mono f :=
{ left := I.g,
right := 0,
w := (by simpa using I.w),
..I }
end
/-- A regular epimorphism is a morphism which is the coequalizer of some parallel pair. -/
class regular_epi (f : X ⟶ Y) :=
(W : C)
(left right : W ⟶ X)
(w : left ≫ f = right ≫ f)
(is_colimit : is_colimit (cofork.of_π f w))
/-- Every regular epimorphism is an epimorphism. -/
@[priority 100]
instance regular_epi.epi (f : X ⟶ Y) [regular_epi f] : epi f :=
epi_of_is_colimit_parallel_pair (regular_epi.is_colimit f)
/-- Every split epimorphism is a regular epimorphism. -/
@[priority 100]
instance regular_epi.of_split_epi (f : X ⟶ Y) [split_epi f] : regular_epi f :=
{ W := X,
left := 𝟙 X,
right := f ≫ section_ f,
w := by tidy,
is_colimit := split_epi_coequalizes f }
section
variables [has_zero_morphisms.{v₁} C]
/-- A normal epimorphism is a morphism which is the cokernel of some morphism. -/
class normal_epi (f : X ⟶ Y) :=
(W : C)
(g : W ⟶ X)
(w : g ≫ f = 0)
(is_colimit : is_colimit (cokernel_cofork.of_π f w))
/-- Every normal epimorphism is a regular epimorphism. -/
@[priority 100]
instance normal_epi.regular_epi (f : X ⟶ Y) [I : normal_epi f] : regular_epi f :=
{ left := I.g,
right := 0,
w := (by simpa using I.w),
..I }
end
end category_theory
|
3baba47261a098482d0e3dab671c0366e5fb39f4 | 618003631150032a5676f229d13a079ac875ff77 | /src/logic/basic.lean | ba1a5ce2bc45fa9530b8e73966b7c3bdc816ff27 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 37,644 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
-/
import tactic.doc_commands
/-!
# Basic logic properties
This file is one of the earliest imports in mathlib.
## Implementation notes
Theorems that require decidability hypotheses are in the namespace "decidable".
Classical versions are in the namespace "classical".
In the presence of automation, this whole file may be unnecessary. On the other hand,
maybe it is useful for writing automation.
-/
section miscellany
/- We add the `inline` attribute to optimize VM computation using these declarations. For example,
`if p ∧ q then ... else ...` will not evaluate the decidability of `q` if `p` is false. -/
attribute [inline] and.decidable or.decidable decidable.false xor.decidable iff.decidable
decidable.true implies.decidable not.decidable ne.decidable
bool.decidable_eq decidable.to_bool
variables {α : Type*} {β : Type*}
@[reducible] def hidden {α : Sort*} {a : α} := a
def empty.elim {C : Sort*} : empty → C.
instance : subsingleton empty := ⟨λa, a.elim⟩
instance : decidable_eq empty := λa, a.elim
instance sort.inhabited : inhabited (Sort*) := ⟨punit⟩
instance sort.inhabited' : inhabited (default (Sort*)) := ⟨punit.star⟩
instance psum.inhabited_left {α β} [inhabited α] : inhabited (psum α β) := ⟨psum.inl (default _)⟩
instance psum.inhabited_right {α β} [inhabited β] : inhabited (psum α β) := ⟨psum.inr (default _)⟩
@[priority 10] instance decidable_eq_of_subsingleton
{α} [subsingleton α] : decidable_eq α
| a b := is_true (subsingleton.elim a b)
/-- Add an instance to "undo" coercion transitivity into a chain of coercions, because
most simp lemmas are stated with respect to simple coercions and will not match when
part of a chain. -/
@[simp] theorem coe_coe {α β γ} [has_coe α β] [has_coe_t β γ]
(a : α) : (a : γ) = (a : β) := rfl
theorem coe_fn_coe_trans
{α β γ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_fun γ]
(x : α) : @coe_fn α _ x = @coe_fn β _ x := rfl
@[simp] theorem coe_fn_coe_base
{α β} [has_coe α β] [has_coe_to_fun β]
(x : α) : @coe_fn α _ x = @coe_fn β _ x := rfl
theorem coe_sort_coe_trans
{α β γ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_sort γ]
(x : α) : @coe_sort α _ x = @coe_sort β _ x := rfl
/--
Many structures such as bundled morphisms coerce to functions so that you can
transparently apply them to arguments. For example, if `e : α ≃ β` and `a : α`
then you can write `e a` and this is elaborated as `⇑e a`. This type of
coercion is implemented using the `has_coe_to_fun`type class. There is one
important consideration:
If a type coerces to another type which in turn coerces to a function,
then it **must** implement `has_coe_to_fun` directly:
```lean
structure sparkling_equiv (α β) extends α ≃ β
-- if we add a `has_coe` instance,
instance {α β} : has_coe (sparkling_equiv α β) (α ≃ β) :=
⟨sparkling_equiv.to_equiv⟩
-- then a `has_coe_to_fun` instance **must** be added as well:
instance {α β} : has_coe_to_fun (sparkling_equiv α β) :=
⟨λ _, α → β, λ f, f.to_equiv.to_fun⟩
```
(Rationale: if we do not declare the direct coercion, then `⇑e a` is not in
simp-normal form. The lemma `coe_fn_coe_base` will unfold it to `⇑↑e a`. This
often causes loops in the simplifier.)
-/
library_note "function coercion"
@[simp] theorem coe_sort_coe_base
{α β} [has_coe α β] [has_coe_to_sort β]
(x : α) : @coe_sort α _ x = @coe_sort β _ x := rfl
/-- `pempty` is the universe-polymorphic analogue of `empty`. -/
@[derive decidable_eq]
inductive {u} pempty : Sort u
def pempty.elim {C : Sort*} : pempty → C.
instance subsingleton_pempty : subsingleton pempty := ⟨λa, a.elim⟩
@[simp] lemma not_nonempty_pempty : ¬ nonempty pempty :=
assume ⟨h⟩, h.elim
@[simp] theorem forall_pempty {P : pempty → Prop} : (∀ x : pempty, P x) ↔ true :=
⟨λ h, trivial, λ h x, by cases x⟩
@[simp] theorem exists_pempty {P : pempty → Prop} : (∃ x : pempty, P x) ↔ false :=
⟨λ h, by { cases h with w, cases w }, false.elim⟩
lemma congr_arg_heq {α} {β : α → Sort*} (f : ∀ a, β a) : ∀ {a₁ a₂ : α}, a₁ = a₂ → f a₁ == f a₂
| a _ rfl := heq.rfl
lemma plift.down_inj {α : Sort*} : ∀ (a b : plift α), a.down = b.down → a = b
| ⟨a⟩ ⟨b⟩ rfl := rfl
-- missing [symm] attribute for ne in core.
attribute [symm] ne.symm
lemma ne_comm {α} {a b : α} : a ≠ b ↔ b ≠ a := ⟨ne.symm, ne.symm⟩
@[simp] lemma eq_iff_eq_cancel_left {b c : α} :
(∀ {a}, a = b ↔ a = c) ↔ (b = c) :=
⟨λ h, by rw [← h], λ h a, by rw h⟩
@[simp] lemma eq_iff_eq_cancel_right {a b : α} :
(∀ {c}, a = c ↔ b = c) ↔ (a = b) :=
⟨λ h, by rw h, λ h a, by rw h⟩
/-- Wrapper for adding elementary propositions to the type class systems.
Warning: this can easily be abused. See the rest of this docstring for details.
Certain propositions should not be treated as a class globally,
but sometimes it is very convenient to be able to use the type class system
in specific circumstances.
For example, `zmod p` is a field if and only if `p` is a prime number.
In order to be able to find this field instance automatically by type class search,
we have to turn `p.prime` into an instance implicit assumption.
On the other hand, making `nat.prime` a class would require a major refactoring of the library,
and it is questionable whether making `nat.prime` a class is desirable at all.
The compromise is to add the assumption `[fact p.prime]` to `zmod.field`.
In particular, this class is not intended for turning the type class system
into an automated theorem prover for first order logic. -/
@[class]
def fact (p : Prop) := p
end miscellany
/-!
### Declarations about propositional connectives
-/
theorem false_ne_true : false ≠ true
| h := h.symm ▸ trivial
section propositional
variables {a b c d : Prop}
/-! ### Declarations about `implies` -/
theorem iff_of_eq (e : a = b) : a ↔ b := e ▸ iff.rfl
theorem iff_iff_eq : (a ↔ b) ↔ a = b := ⟨propext, iff_of_eq⟩
@[simp] lemma eq_iff_iff {p q : Prop} : (p = q) ↔ (p ↔ q) := iff_iff_eq.symm
@[simp] theorem imp_self : (a → a) ↔ true := iff_true_intro id
theorem imp_intro {α β : Prop} (h : α) : β → α := λ _, h
theorem imp_false : (a → false) ↔ ¬ a := iff.rfl
theorem imp_and_distrib {α} : (α → b ∧ c) ↔ (α → b) ∧ (α → c) :=
⟨λ h, ⟨λ ha, (h ha).left, λ ha, (h ha).right⟩,
λ h ha, ⟨h.left ha, h.right ha⟩⟩
@[simp] theorem and_imp : (a ∧ b → c) ↔ (a → b → c) :=
iff.intro (λ h ha hb, h ⟨ha, hb⟩) (λ h ⟨ha, hb⟩, h ha hb)
theorem iff_def : (a ↔ b) ↔ (a → b) ∧ (b → a) :=
iff_iff_implies_and_implies _ _
theorem iff_def' : (a ↔ b) ↔ (b → a) ∧ (a → b) :=
iff_def.trans and.comm
theorem imp_true_iff {α : Sort*} : (α → true) ↔ true :=
iff_true_intro $ λ_, trivial
@[simp] theorem imp_iff_right (ha : a) : (a → b) ↔ b :=
⟨λf, f ha, imp_intro⟩
/-! ### Declarations about `not` -/
def not.elim {α : Sort*} (H1 : ¬a) (H2 : a) : α := absurd H2 H1
@[reducible] theorem not.imp {a b : Prop} (H2 : ¬b) (H1 : a → b) : ¬a := mt H1 H2
theorem not_not_of_not_imp : ¬(a → b) → ¬¬a :=
mt not.elim
theorem not_of_not_imp {a : Prop} : ¬(a → b) → ¬b :=
mt imp_intro
theorem dec_em (p : Prop) [decidable p] : p ∨ ¬p := decidable.em p
theorem by_contradiction {p} [decidable p] : (¬p → false) → p :=
decidable.by_contradiction
theorem not_not [decidable a] : ¬¬a ↔ a :=
iff.intro by_contradiction not_not_intro
theorem of_not_not [decidable a] : ¬¬a → a :=
by_contradiction
theorem of_not_imp [decidable a] (h : ¬ (a → b)) : a :=
by_contradiction (not_not_of_not_imp h)
theorem not.imp_symm [decidable a] (h : ¬a → b) (hb : ¬b) : a :=
by_contradiction $ hb ∘ h
theorem not_imp_comm [decidable a] [decidable b] : (¬a → b) ↔ (¬b → a) :=
⟨not.imp_symm, not.imp_symm⟩
theorem imp.swap : (a → b → c) ↔ (b → a → c) :=
⟨function.swap, function.swap⟩
theorem imp_not_comm : (a → ¬b) ↔ (b → ¬a) :=
imp.swap
/-! ### Declarations about `and` -/
theorem not_and_of_not_left (b : Prop) : ¬a → ¬(a ∧ b) :=
mt and.left
theorem not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) :=
mt and.right
theorem and.imp_left (h : a → b) : a ∧ c → b ∧ c :=
and.imp h id
theorem and.imp_right (h : a → b) : c ∧ a → c ∧ b :=
and.imp id h
lemma and.right_comm : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ b :=
by simp [and.left_comm, and.comm]
lemma and.rotate : a ∧ b ∧ c ↔ b ∧ c ∧ a :=
by simp [and.left_comm, and.comm]
theorem and_not_self_iff (a : Prop) : a ∧ ¬ a ↔ false :=
iff.intro (assume h, (h.right) (h.left)) (assume h, h.elim)
theorem not_and_self_iff (a : Prop) : ¬ a ∧ a ↔ false :=
iff.intro (assume ⟨hna, ha⟩, hna ha) false.elim
theorem and_iff_left_of_imp {a b : Prop} (h : a → b) : (a ∧ b) ↔ a :=
iff.intro and.left (λ ha, ⟨ha, h ha⟩)
theorem and_iff_right_of_imp {a b : Prop} (h : b → a) : (a ∧ b) ↔ b :=
iff.intro and.right (λ hb, ⟨h hb, hb⟩)
lemma and.congr_right_iff : (a ∧ b ↔ a ∧ c) ↔ (a → (b ↔ c)) :=
⟨λ h ha, by simp [ha] at h; exact h, and_congr_right⟩
@[simp] lemma and_self_left : a ∧ a ∧ b ↔ a ∧ b :=
⟨λ h, ⟨h.1, h.2.2⟩, λ h, ⟨h.1, h.1, h.2⟩⟩
@[simp] lemma and_self_right : (a ∧ b) ∧ b ↔ a ∧ b :=
⟨λ h, ⟨h.1.1, h.2⟩, λ h, ⟨⟨h.1, h.2⟩, h.2⟩⟩
/-! ### Declarations about `or` -/
theorem or_of_or_of_imp_of_imp (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → d) : c ∨ d :=
or.imp h₂ h₃ h₁
theorem or_of_or_of_imp_left (h₁ : a ∨ c) (h : a → b) : b ∨ c :=
or.imp_left h h₁
theorem or_of_or_of_imp_right (h₁ : c ∨ a) (h : a → b) : c ∨ b :=
or.imp_right h h₁
theorem or.elim3 (h : a ∨ b ∨ c) (ha : a → d) (hb : b → d) (hc : c → d) : d :=
or.elim h ha (assume h₂, or.elim h₂ hb hc)
theorem or_imp_distrib : (a ∨ b → c) ↔ (a → c) ∧ (b → c) :=
⟨assume h, ⟨assume ha, h (or.inl ha), assume hb, h (or.inr hb)⟩,
assume ⟨ha, hb⟩, or.rec ha hb⟩
theorem or_iff_not_imp_left [decidable a] : a ∨ b ↔ (¬ a → b) :=
⟨or.resolve_left, λ h, dite _ or.inl (or.inr ∘ h)⟩
theorem or_iff_not_imp_right [decidable b] : a ∨ b ↔ (¬ b → a) :=
or.comm.trans or_iff_not_imp_left
theorem not_imp_not [decidable a] : (¬ a → ¬ b) ↔ (b → a) :=
⟨assume h hb, by_contradiction $ assume na, h na hb, mt⟩
/-! ### Declarations about distributivity -/
theorem and_or_distrib_left : a ∧ (b ∨ c) ↔ (a ∧ b) ∨ (a ∧ c) :=
⟨λ ⟨ha, hbc⟩, hbc.imp (and.intro ha) (and.intro ha),
or.rec (and.imp_right or.inl) (and.imp_right or.inr)⟩
theorem or_and_distrib_right : (a ∨ b) ∧ c ↔ (a ∧ c) ∨ (b ∧ c) :=
(and.comm.trans and_or_distrib_left).trans (or_congr and.comm and.comm)
theorem or_and_distrib_left : a ∨ (b ∧ c) ↔ (a ∨ b) ∧ (a ∨ c) :=
⟨or.rec (λha, and.intro (or.inl ha) (or.inl ha)) (and.imp or.inr or.inr),
and.rec $ or.rec (imp_intro ∘ or.inl) (or.imp_right ∘ and.intro)⟩
theorem and_or_distrib_right : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) :=
(or.comm.trans or_and_distrib_left).trans (and_congr or.comm or.comm)
@[simp] lemma or_self_left : a ∨ a ∨ b ↔ a ∨ b :=
⟨λ h, h.elim or.inl id, λ h, h.elim or.inl (or.inr ∘ or.inr)⟩
@[simp] lemma or_self_right : (a ∨ b) ∨ b ↔ a ∨ b :=
⟨λ h, h.elim id or.inr, λ h, h.elim (or.inl ∘ or.inl) or.inr⟩
/-! Declarations about `iff` -/
theorem iff_of_true (ha : a) (hb : b) : a ↔ b :=
⟨λ_, hb, λ _, ha⟩
theorem iff_of_false (ha : ¬a) (hb : ¬b) : a ↔ b :=
⟨ha.elim, hb.elim⟩
theorem iff_true_left (ha : a) : (a ↔ b) ↔ b :=
⟨λ h, h.1 ha, iff_of_true ha⟩
theorem iff_true_right (ha : a) : (b ↔ a) ↔ b :=
iff.comm.trans (iff_true_left ha)
theorem iff_false_left (ha : ¬a) : (a ↔ b) ↔ ¬b :=
⟨λ h, mt h.2 ha, iff_of_false ha⟩
theorem iff_false_right (ha : ¬a) : (b ↔ a) ↔ ¬b :=
iff.comm.trans (iff_false_left ha)
theorem not_or_of_imp [decidable a] (h : a → b) : ¬ a ∨ b :=
if ha : a then or.inr (h ha) else or.inl ha
theorem imp_iff_not_or [decidable a] : (a → b) ↔ (¬ a ∨ b) :=
⟨not_or_of_imp, or.neg_resolve_left⟩
theorem imp_or_distrib [decidable a] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) :=
by simp [imp_iff_not_or, or.comm, or.left_comm]
theorem imp_or_distrib' [decidable b] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) :=
by by_cases b; simp [h, or_iff_right_of_imp ((∘) false.elim)]
theorem not_imp_of_and_not : a ∧ ¬ b → ¬ (a → b)
| ⟨ha, hb⟩ h := hb $ h ha
theorem not_imp [decidable a] : ¬(a → b) ↔ a ∧ ¬b :=
⟨λ h, ⟨of_not_imp h, not_of_not_imp h⟩, not_imp_of_and_not⟩
-- for monotonicity
lemma imp_imp_imp
(h₀ : c → a) (h₁ : b → d) :
(a → b) → (c → d) :=
assume (h₂ : a → b),
h₁ ∘ h₂ ∘ h₀
theorem peirce (a b : Prop) [decidable a] : ((a → b) → a) → a :=
if ha : a then λ h, ha else λ h, h ha.elim
theorem peirce' {a : Prop} (H : ∀ b : Prop, (a → b) → a) : a := H _ id
theorem not_iff_not [decidable a] [decidable b] : (¬ a ↔ ¬ b) ↔ (a ↔ b) :=
by rw [@iff_def (¬ a), @iff_def' a]; exact and_congr not_imp_not not_imp_not
theorem not_iff_comm [decidable a] [decidable b] : (¬ a ↔ b) ↔ (¬ b ↔ a) :=
by rw [@iff_def (¬ a), @iff_def (¬ b)]; exact and_congr not_imp_comm imp_not_comm
theorem not_iff [decidable b] : ¬ (a ↔ b) ↔ (¬ a ↔ b) :=
by split; intro h; [split, skip]; intro h'; [by_contradiction,intro,skip];
try { refine h _; simp [*] }; rw [h',not_iff_self] at h; exact h
theorem iff_not_comm [decidable a] [decidable b] : (a ↔ ¬ b) ↔ (b ↔ ¬ a) :=
by rw [@iff_def a, @iff_def b]; exact and_congr imp_not_comm not_imp_comm
theorem iff_iff_and_or_not_and_not [decidable b] : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) :=
by { split; intro h,
{ rw h; by_cases b; [left,right]; split; assumption },
{ cases h with h h; cases h; split; intro; { contradiction <|> assumption } } }
theorem not_and_not_right [decidable b] : ¬(a ∧ ¬b) ↔ (a → b) :=
⟨λ h ha, h.imp_symm $ and.intro ha, λ h ⟨ha, hb⟩, hb $ h ha⟩
@[inline] def decidable_of_iff (a : Prop) (h : a ↔ b) [D : decidable a] : decidable b :=
decidable_of_decidable_of_iff D h
@[inline] def decidable_of_iff' (b : Prop) (h : a ↔ b) [D : decidable b] : decidable a :=
decidable_of_decidable_of_iff D h.symm
def decidable_of_bool : ∀ (b : bool) (h : b ↔ a), decidable a
| tt h := is_true (h.1 rfl)
| ff h := is_false (mt h.2 bool.ff_ne_tt)
/-! ### De Morgan's laws -/
theorem not_and_of_not_or_not (h : ¬ a ∨ ¬ b) : ¬ (a ∧ b)
| ⟨ha, hb⟩ := or.elim h (absurd ha) (absurd hb)
theorem not_and_distrib [decidable a] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b :=
⟨λ h, if ha : a then or.inr (λ hb, h ⟨ha, hb⟩) else or.inl ha, not_and_of_not_or_not⟩
theorem not_and_distrib' [decidable b] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b :=
⟨λ h, if hb : b then or.inl (λ ha, h ⟨ha, hb⟩) else or.inr hb, not_and_of_not_or_not⟩
@[simp] theorem not_and : ¬ (a ∧ b) ↔ (a → ¬ b) := and_imp
theorem not_and' : ¬ (a ∧ b) ↔ b → ¬a :=
not_and.trans imp_not_comm
theorem not_or_distrib : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b :=
⟨λ h, ⟨λ ha, h (or.inl ha), λ hb, h (or.inr hb)⟩,
λ ⟨h₁, h₂⟩ h, or.elim h h₁ h₂⟩
theorem or_iff_not_and_not [decidable a] [decidable b] : a ∨ b ↔ ¬ (¬a ∧ ¬b) :=
by rw [← not_or_distrib, not_not]
theorem and_iff_not_or_not [decidable a] [decidable b] : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) :=
by rw [← not_and_distrib, not_not]
end propositional
/-! ### Declarations about equality -/
section equality
variables {α : Sort*} {a b : α}
@[simp] theorem heq_iff_eq : a == b ↔ a = b :=
⟨eq_of_heq, heq_of_eq⟩
theorem proof_irrel_heq {p q : Prop} (hp : p) (hq : q) : hp == hq :=
have p = q, from propext ⟨λ _, hq, λ _, hp⟩,
by subst q; refl
theorem ne_of_mem_of_not_mem {α β} [has_mem α β] {s : β} {a b : α}
(h : a ∈ s) : b ∉ s → a ≠ b :=
mt $ λ e, e ▸ h
theorem eq_equivalence : equivalence (@eq α) :=
⟨eq.refl, @eq.symm _, @eq.trans _⟩
/-- Transport through trivial families is the identity. -/
@[simp]
lemma eq_rec_constant {α : Sort*} {a a' : α} {β : Sort*} (y : β) (h : a = a') :
(@eq.rec α a (λ a, β) y a' h) = y :=
by { cases h, refl, }
@[simp]
lemma eq_mp_rfl {α : Sort*} {a : α} : eq.mp (eq.refl α) a = a := rfl
@[simp]
lemma eq_mpr_rfl {α : Sort*} {a : α} : eq.mpr (eq.refl α) a = a := rfl
lemma heq_of_eq_mp :
∀ {α β : Sort*} {a : α} {a' : β} (e : α = β) (h₂ : (eq.mp e a) = a'), a == a'
| α ._ a a' rfl h := eq.rec_on h (heq.refl _)
lemma rec_heq_of_heq {β} {C : α → Sort*} {x : C a} {y : β} (eq : a = b) (h : x == y) :
@eq.rec α a C x b eq == y :=
by subst eq; exact h
@[simp] lemma {u} eq_mpr_heq {α β : Sort u} (h : β = α) (x : α) : eq.mpr h x == x :=
by subst h; refl
protected lemma eq.congr {x₁ x₂ y₁ y₂ : α} (h₁ : x₁ = y₁) (h₂ : x₂ = y₂) :
(x₁ = x₂) ↔ (y₁ = y₂) :=
by { subst h₁, subst h₂ }
lemma eq.congr_left {x y z : α} (h : x = y) : x = z ↔ y = z := by rw [h]
lemma eq.congr_right {x y z : α} (h : x = y) : z = x ↔ z = y := by rw [h]
lemma congr_arg2 {α β γ : Type*} (f : α → β → γ) {x x' : α} {y y' : β}
(hx : x = x') (hy : y = y') : f x y = f x' y' :=
by { subst hx, subst hy }
end equality
/-! ### Declarations about quantifiers -/
section quantifiers
variables {α : Sort*} {β : Sort*} {p q : α → Prop} {b : Prop}
lemma Exists.imp (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := exists_imp_exists h p
lemma exists_imp_exists' {p : α → Prop} {q : β → Prop} (f : α → β) (hpq : ∀ a, p a → q (f a))
(hp : ∃ a, p a) : ∃ b, q b :=
exists.elim hp (λ a hp', ⟨_, hpq _ hp'⟩)
theorem forall_swap {p : α → β → Prop} : (∀ x y, p x y) ↔ ∀ y x, p x y :=
⟨function.swap, function.swap⟩
theorem exists_swap {p : α → β → Prop} : (∃ x y, p x y) ↔ ∃ y x, p x y :=
⟨λ ⟨x, y, h⟩, ⟨y, x, h⟩, λ ⟨y, x, h⟩, ⟨x, y, h⟩⟩
@[simp] theorem exists_imp_distrib : ((∃ x, p x) → b) ↔ ∀ x, p x → b :=
⟨λ h x hpx, h ⟨x, hpx⟩, λ h ⟨x, hpx⟩, h x hpx⟩
--theorem forall_not_of_not_exists (h : ¬ ∃ x, p x) : ∀ x, ¬ p x :=
--forall_imp_of_exists_imp h
theorem not_exists_of_forall_not (h : ∀ x, ¬ p x) : ¬ ∃ x, p x :=
exists_imp_distrib.2 h
@[simp] theorem not_exists : (¬ ∃ x, p x) ↔ ∀ x, ¬ p x :=
exists_imp_distrib
theorem not_forall_of_exists_not : (∃ x, ¬ p x) → ¬ ∀ x, p x
| ⟨x, hn⟩ h := hn (h x)
theorem not_forall {p : α → Prop}
[decidable (∃ x, ¬ p x)] [∀ x, decidable (p x)] :
(¬ ∀ x, p x) ↔ ∃ x, ¬ p x :=
⟨not.imp_symm $ λ nx x, nx.imp_symm $ λ h, ⟨x, h⟩,
not_forall_of_exists_not⟩
theorem not_forall_not [decidable (∃ x, p x)] :
(¬ ∀ x, ¬ p x) ↔ ∃ x, p x :=
(@not_iff_comm _ _ _ (decidable_of_iff (¬ ∃ x, p x) not_exists)).1 not_exists
theorem not_exists_not [∀ x, decidable (p x)] :
(¬ ∃ x, ¬ p x) ↔ ∀ x, p x :=
by simp [not_not]
@[simp] theorem forall_true_iff : (α → true) ↔ true :=
iff_true_intro (λ _, trivial)
-- Unfortunately this causes simp to loop sometimes, so we
-- add the 2 and 3 cases as simp lemmas instead
theorem forall_true_iff' (h : ∀ a, p a ↔ true) : (∀ a, p a) ↔ true :=
iff_true_intro (λ _, of_iff_true (h _))
@[simp] theorem forall_2_true_iff {β : α → Sort*} : (∀ a, β a → true) ↔ true :=
forall_true_iff' $ λ _, forall_true_iff
@[simp] theorem forall_3_true_iff {β : α → Sort*} {γ : Π a, β a → Sort*} :
(∀ a (b : β a), γ a b → true) ↔ true :=
forall_true_iff' $ λ _, forall_2_true_iff
@[simp] theorem forall_const (α : Sort*) [i : nonempty α] : (α → b) ↔ b :=
⟨i.elim, λ hb x, hb⟩
@[simp] theorem exists_const (α : Sort*) [i : nonempty α] : (∃ x : α, b) ↔ b :=
⟨λ ⟨x, h⟩, h, i.elim exists.intro⟩
theorem forall_and_distrib : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) :=
⟨λ h, ⟨λ x, (h x).left, λ x, (h x).right⟩, λ ⟨h₁, h₂⟩ x, ⟨h₁ x, h₂ x⟩⟩
theorem exists_or_distrib : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) :=
⟨λ ⟨x, hpq⟩, hpq.elim (λ hpx, or.inl ⟨x, hpx⟩) (λ hqx, or.inr ⟨x, hqx⟩),
λ hepq, hepq.elim (λ ⟨x, hpx⟩, ⟨x, or.inl hpx⟩) (λ ⟨x, hqx⟩, ⟨x, or.inr hqx⟩)⟩
@[simp] theorem exists_and_distrib_left {q : Prop} {p : α → Prop} :
(∃x, q ∧ p x) ↔ q ∧ (∃x, p x) :=
⟨λ ⟨x, hq, hp⟩, ⟨hq, x, hp⟩, λ ⟨hq, x, hp⟩, ⟨x, hq, hp⟩⟩
@[simp] theorem exists_and_distrib_right {q : Prop} {p : α → Prop} :
(∃x, p x ∧ q) ↔ (∃x, p x) ∧ q :=
by simp [and_comm]
@[simp] theorem forall_eq {a' : α} : (∀a, a = a' → p a) ↔ p a' :=
⟨λ h, h a' rfl, λ h a e, e.symm ▸ h⟩
@[simp] theorem exists_eq {a' : α} : ∃ a, a = a' := ⟨_, rfl⟩
@[simp] theorem exists_eq' {a' : α} : Exists (eq a') := ⟨_, rfl⟩
@[simp] theorem exists_eq_left {a' : α} : (∃ a, a = a' ∧ p a) ↔ p a' :=
⟨λ ⟨a, e, h⟩, e ▸ h, λ h, ⟨_, rfl, h⟩⟩
@[simp] theorem exists_eq_right {a' : α} : (∃ a, p a ∧ a = a') ↔ p a' :=
(exists_congr $ by exact λ a, and.comm).trans exists_eq_left
@[simp] theorem exists_exists_and_eq_and {f : α → β} {p : α → Prop} {q : β → Prop} :
(∃ b, (∃ a, p a ∧ f a = b) ∧ q b) ↔ ∃ a, p a ∧ q (f a) :=
⟨λ ⟨b, ⟨a, ha, hab⟩, hb⟩, ⟨a, ha, hab.symm ▸ hb⟩, λ ⟨a, hp, hq⟩, ⟨f a, ⟨a, hp, rfl⟩, hq⟩⟩
@[simp] theorem exists_exists_eq_and {f : α → β} {p : β → Prop} :
(∃ b, (∃ a, f a = b) ∧ p b) ↔ ∃ a, p (f a) :=
⟨λ ⟨b, ⟨a, ha⟩, hb⟩, ⟨a, ha.symm ▸ hb⟩, λ ⟨a, ha⟩, ⟨f a, ⟨a, rfl⟩, ha⟩⟩
@[simp] theorem forall_eq' {a' : α} : (∀a, a' = a → p a) ↔ p a' :=
by simp [@eq_comm _ a']
@[simp] theorem exists_eq_left' {a' : α} : (∃ a, a' = a ∧ p a) ↔ p a' :=
by simp [@eq_comm _ a']
@[simp] theorem exists_eq_right' {a' : α} : (∃ a, p a ∧ a' = a) ↔ p a' :=
by simp [@eq_comm _ a']
theorem exists_comm {p : α → β → Prop} : (∃ a b, p a b) ↔ ∃ b a, p a b :=
⟨λ ⟨a, b, h⟩, ⟨b, a, h⟩, λ ⟨b, a, h⟩, ⟨a, b, h⟩⟩
theorem forall_or_of_or_forall (h : b ∨ ∀x, p x) (x) : b ∨ p x :=
h.imp_right $ λ h₂, h₂ x
theorem forall_or_distrib_left {q : Prop} {p : α → Prop} [decidable q] :
(∀x, q ∨ p x) ↔ q ∨ (∀x, p x) :=
⟨λ h, if hq : q then or.inl hq else or.inr $ λ x, (h x).resolve_left hq,
forall_or_of_or_forall⟩
theorem forall_or_distrib_right {q : Prop} {p : α → Prop} [decidable q] :
(∀x, p x ∨ q) ↔ (∀x, p x) ∨ q :=
by simp [or_comm, forall_or_distrib_left]
/-- A predicate holds everywhere on the image of a surjective functions iff
it holds everywhere. -/
theorem forall_iff_forall_surj
{α β : Type*} {f : α → β} (h : function.surjective f) {P : β → Prop} :
(∀ a, P (f a)) ↔ ∀ b, P b :=
⟨λ ha b, by cases h b with a hab; rw ←hab; exact ha a, λ hb a, hb $ f a⟩
@[simp] theorem exists_prop {p q : Prop} : (∃ h : p, q) ↔ p ∧ q :=
⟨λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩⟩
@[simp] theorem exists_false : ¬ (∃a:α, false) := assume ⟨a, h⟩, h
theorem Exists.fst {p : b → Prop} : Exists p → b
| ⟨h, _⟩ := h
theorem Exists.snd {p : b → Prop} : ∀ h : Exists p, p h.fst
| ⟨_, h⟩ := h
@[simp] theorem forall_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∀ h' : p, q h') ↔ q h :=
@forall_const (q h) p ⟨h⟩
@[simp] theorem exists_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃ h' : p, q h') ↔ q h :=
@exists_const (q h) p ⟨h⟩
@[simp] theorem forall_prop_of_false {p : Prop} {q : p → Prop} (hn : ¬ p) : (∀ h' : p, q h') ↔ true :=
iff_true_intro $ λ h, hn.elim h
@[simp] theorem exists_prop_of_false {p : Prop} {q : p → Prop} : ¬ p → ¬ (∃ h' : p, q h') :=
mt Exists.fst
lemma exists_unique.exists {α : Sort*} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x :=
exists.elim h (λ x hx, ⟨x, and.left hx⟩)
lemma exists_unique.unique {α : Sort*} {p : α → Prop} (h : ∃! x, p x)
{y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ :=
unique_of_exists_unique h py₁ py₂
@[simp] lemma exists_unique_iff_exists {α : Sort*} [subsingleton α] {p : α → Prop} :
(∃! x, p x) ↔ ∃ x, p x :=
⟨λ h, h.exists, Exists.imp $ λ x hx, ⟨hx, λ y _, subsingleton.elim y x⟩⟩
lemma exists_unique.elim2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)]
{q : Π x (h : p x), Prop} {b : Prop} (h₂ : ∃! x (h : p x), q x h)
(h₁ : ∀ x (h : p x), q x h → (∀ y (hy : p y), q y hy → y = x) → b) : b :=
begin
simp only [exists_unique_iff_exists] at h₂,
apply h₂.elim,
exact λ x ⟨hxp, hxq⟩ H, h₁ x hxp hxq (λ y hyp hyq, H y ⟨hyp, hyq⟩)
end
lemma exists_unique.intro2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)]
{q : Π (x : α) (h : p x), Prop} (w : α) (hp : p w) (hq : q w hp)
(H : ∀ y (hy : p y), q y hy → y = w) :
∃! x (hx : p x), q x hx :=
begin
simp only [exists_unique_iff_exists],
exact exists_unique.intro w ⟨hp, hq⟩ (λ y ⟨hyp, hyq⟩, H y hyp hyq)
end
lemma exists_unique.exists2 {α : Sort*} {p : α → Sort*} {q : Π (x : α) (h : p x), Prop}
(h : ∃! x (hx : p x), q x hx) :
∃ x (hx : p x), q x hx :=
h.exists.imp (λ x hx, hx.exists)
lemma exists_unique.unique2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)]
{q : Π (x : α) (hx : p x), Prop} (h : ∃! x (hx : p x), q x hx)
{y₁ y₂ : α} (hpy₁ : p y₁) (hqy₁ : q y₁ hpy₁)
(hpy₂ : p y₂) (hqy₂ : q y₂ hpy₂) : y₁ = y₂ :=
begin
simp only [exists_unique_iff_exists] at h,
exact h.unique ⟨hpy₁, hqy₁⟩ ⟨hpy₂, hqy₂⟩
end
end quantifiers
/-! ### Classical versions of earlier lemmas -/
namespace classical
variables {α : Sort*} {p : α → Prop}
local attribute [instance] prop_decidable
@[simp] protected theorem not_forall : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := not_forall
@[simp] protected theorem not_exists_not : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x := not_exists_not
protected theorem forall_or_distrib_left {q : Prop} {p : α → Prop} :
(∀x, q ∨ p x) ↔ q ∨ (∀x, p x) :=
forall_or_distrib_left
protected theorem forall_or_distrib_right {q : Prop} {p : α → Prop} :
(∀x, p x ∨ q) ↔ (∀x, p x) ∨ q :=
forall_or_distrib_right
protected theorem forall_or_distrib {β} {p : α → Prop} {q : β → Prop} :
(∀x y, p x ∨ q y) ↔ (∀ x, p x) ∨ (∀ y, q y) :=
by rw ← forall_or_distrib_right; simp [forall_or_distrib_left.symm]
theorem cases {p : Prop → Prop} (h1 : p true) (h2 : p false) : ∀a, p a :=
assume a, cases_on a h1 h2
theorem or_not {p : Prop} : p ∨ ¬ p :=
by_cases or.inl or.inr
protected theorem or_iff_not_imp_left {p q : Prop} : p ∨ q ↔ (¬ p → q) :=
or_iff_not_imp_left
protected theorem or_iff_not_imp_right {p q : Prop} : q ∨ p ↔ (¬ p → q) :=
or_iff_not_imp_right
@[simp] protected lemma not_not {p : Prop} : ¬¬p ↔ p := not_not
@[simp] protected lemma not_imp {p q : Prop} : ¬(p → q) ↔ p ∧ ¬q :=
not_imp
protected theorem not_imp_not {p q : Prop} : (¬ p → ¬ q) ↔ (q → p) := not_imp_not
protected lemma not_and_distrib {p q : Prop}: ¬(p ∧ q) ↔ ¬p ∨ ¬q := not_and_distrib
protected lemma imp_iff_not_or {a b : Prop} : a → b ↔ ¬a ∨ b := imp_iff_not_or
lemma iff_iff_not_or_and_or_not {a b : Prop} : (a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) :=
begin
rw [iff_iff_implies_and_implies a b],
simp only [imp_iff_not_or, or.comm]
end
/- use shortened names to avoid conflict when classical namespace is open. -/
noncomputable lemma dec (p : Prop) : decidable p := -- see Note [classical lemma]
by apply_instance
noncomputable lemma dec_pred (p : α → Prop) : decidable_pred p := -- see Note [classical lemma]
by apply_instance
noncomputable lemma dec_rel (p : α → α → Prop) : decidable_rel p := -- see Note [classical lemma]
by apply_instance
noncomputable lemma dec_eq (α : Sort*) : decidable_eq α := -- see Note [classical lemma]
by apply_instance
/--
We make decidability results that depends on `classical.choice` noncomputable lemmas.
* We have to mark them as noncomputable, because otherwise Lean will try to generate bytecode
for them, and fail because it depends on `classical.choice`.
* We make them lemmas, and not definitions, because otherwise later definitions will raise
\"failed to generate bytecode\" errors when writing something like
`letI := classical.dec_eq _`.
Cf. <https://leanprover-community.github.io/archive/113488general/08268noncomputabletheorem.html>
-/
library_note "classical lemma"
@[elab_as_eliminator]
noncomputable def {u} exists_cases {C : Sort u} (H0 : C) (H : ∀ a, p a → C) : C :=
if h : ∃ a, p a then H (classical.some h) (classical.some_spec h) else H0
lemma some_spec2 {α : Sort*} {p : α → Prop} {h : ∃a, p a}
(q : α → Prop) (hpq : ∀a, p a → q a) : q (some h) :=
hpq _ $ some_spec _
/-- A version of classical.indefinite_description which is definitionally equal to a pair -/
noncomputable def subtype_of_exists {α : Type*} {P : α → Prop} (h : ∃ x, P x) : {x // P x} :=
⟨classical.some h, classical.some_spec h⟩
end classical
@[elab_as_eliminator]
noncomputable def {u} exists.classical_rec_on
{α} {p : α → Prop} (h : ∃ a, p a) {C : Sort u} (H : ∀ a, p a → C) : C :=
H (classical.some h) (classical.some_spec h)
/-! ### Declarations about bounded quantifiers -/
section bounded_quantifiers
variables {α : Sort*} {r p q : α → Prop} {P Q : ∀ x, p x → Prop} {b : Prop}
theorem bex_def : (∃ x (h : p x), q x) ↔ ∃ x, p x ∧ q x :=
⟨λ ⟨x, px, qx⟩, ⟨x, px, qx⟩, λ ⟨x, px, qx⟩, ⟨x, px, qx⟩⟩
theorem bex.elim {b : Prop} : (∃ x h, P x h) → (∀ a h, P a h → b) → b
| ⟨a, h₁, h₂⟩ h' := h' a h₁ h₂
theorem bex.intro (a : α) (h₁ : p a) (h₂ : P a h₁) : ∃ x (h : p x), P x h :=
⟨a, h₁, h₂⟩
theorem ball_congr (H : ∀ x h, P x h ↔ Q x h) :
(∀ x h, P x h) ↔ (∀ x h, Q x h) :=
forall_congr $ λ x, forall_congr (H x)
theorem bex_congr (H : ∀ x h, P x h ↔ Q x h) :
(∃ x h, P x h) ↔ (∃ x h, Q x h) :=
exists_congr $ λ x, exists_congr (H x)
theorem ball.imp_right (H : ∀ x h, (P x h → Q x h))
(h₁ : ∀ x h, P x h) (x h) : Q x h :=
H _ _ $ h₁ _ _
theorem bex.imp_right (H : ∀ x h, (P x h → Q x h)) :
(∃ x h, P x h) → ∃ x h, Q x h
| ⟨x, h, h'⟩ := ⟨_, _, H _ _ h'⟩
theorem ball.imp_left (H : ∀ x, p x → q x)
(h₁ : ∀ x, q x → r x) (x) (h : p x) : r x :=
h₁ _ $ H _ h
theorem bex.imp_left (H : ∀ x, p x → q x) :
(∃ x (_ : p x), r x) → ∃ x (_ : q x), r x
| ⟨x, hp, hr⟩ := ⟨x, H _ hp, hr⟩
theorem ball_of_forall (h : ∀ x, p x) (x) : p x :=
h x
theorem forall_of_ball (H : ∀ x, p x) (h : ∀ x, p x → q x) (x) : q x :=
h x $ H x
theorem bex_of_exists (H : ∀ x, p x) : (∃ x, q x) → ∃ x (_ : p x), q x
| ⟨x, hq⟩ := ⟨x, H x, hq⟩
theorem exists_of_bex : (∃ x (_ : p x), q x) → ∃ x, q x
| ⟨x, _, hq⟩ := ⟨x, hq⟩
@[simp] theorem bex_imp_distrib : ((∃ x h, P x h) → b) ↔ (∀ x h, P x h → b) :=
by simp
theorem not_bex : (¬ ∃ x h, P x h) ↔ ∀ x h, ¬ P x h :=
bex_imp_distrib
theorem not_ball_of_bex_not : (∃ x h, ¬ P x h) → ¬ ∀ x h, P x h
| ⟨x, h, hp⟩ al := hp $ al x h
theorem not_ball [decidable (∃ x h, ¬ P x h)] [∀ x h, decidable (P x h)] :
(¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) :=
⟨not.imp_symm $ λ nx x h, nx.imp_symm $ λ h', ⟨x, h, h'⟩,
not_ball_of_bex_not⟩
theorem ball_true_iff (p : α → Prop) : (∀ x, p x → true) ↔ true :=
iff_true_intro (λ h hrx, trivial)
theorem ball_and_distrib : (∀ x h, P x h ∧ Q x h) ↔ (∀ x h, P x h) ∧ (∀ x h, Q x h) :=
iff.trans (forall_congr $ λ x, forall_and_distrib) forall_and_distrib
theorem bex_or_distrib : (∃ x h, P x h ∨ Q x h) ↔ (∃ x h, P x h) ∨ (∃ x h, Q x h) :=
iff.trans (exists_congr $ λ x, exists_or_distrib) exists_or_distrib
end bounded_quantifiers
namespace classical
local attribute [instance] prop_decidable
theorem not_ball {α : Sort*} {p : α → Prop} {P : Π (x : α), p x → Prop} :
(¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := _root_.not_ball
end classical
/-! ### Declarations about `nonempty` -/
section nonempty
universe variables u v w
variables {α : Type u} {β : Type v} {γ : α → Type w}
attribute [simp] nonempty_of_inhabited
@[priority 20]
instance has_zero.nonempty [has_zero α] : nonempty α := ⟨0⟩
@[priority 20]
instance has_one.nonempty [has_one α] : nonempty α := ⟨1⟩
lemma exists_true_iff_nonempty {α : Sort*} : (∃a:α, true) ↔ nonempty α :=
iff.intro (λ⟨a, _⟩, ⟨a⟩) (λ⟨a⟩, ⟨a, trivial⟩)
@[simp] lemma nonempty_Prop {p : Prop} : nonempty p ↔ p :=
iff.intro (assume ⟨h⟩, h) (assume h, ⟨h⟩)
lemma not_nonempty_iff_imp_false : ¬ nonempty α ↔ α → false :=
⟨λ h a, h ⟨a⟩, λ h ⟨a⟩, h a⟩
@[simp] lemma nonempty_sigma : nonempty (Σa:α, γ a) ↔ (∃a:α, nonempty (γ a)) :=
iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩)
@[simp] lemma nonempty_subtype {α : Sort u} {p : α → Prop} : nonempty (subtype p) ↔ (∃a:α, p a) :=
iff.intro (assume ⟨⟨a, h⟩⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a, h⟩⟩)
@[simp] lemma nonempty_prod : nonempty (α × β) ↔ (nonempty α ∧ nonempty β) :=
iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩)
@[simp] lemma nonempty_pprod {α : Sort u} {β : Sort v} :
nonempty (pprod α β) ↔ (nonempty α ∧ nonempty β) :=
iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩)
@[simp] lemma nonempty_sum : nonempty (α ⊕ β) ↔ (nonempty α ∨ nonempty β) :=
iff.intro
(assume ⟨h⟩, match h with sum.inl a := or.inl ⟨a⟩ | sum.inr b := or.inr ⟨b⟩ end)
(assume h, match h with or.inl ⟨a⟩ := ⟨sum.inl a⟩ | or.inr ⟨b⟩ := ⟨sum.inr b⟩ end)
@[simp] lemma nonempty_psum {α : Sort u} {β : Sort v} :
nonempty (psum α β) ↔ (nonempty α ∨ nonempty β) :=
iff.intro
(assume ⟨h⟩, match h with psum.inl a := or.inl ⟨a⟩ | psum.inr b := or.inr ⟨b⟩ end)
(assume h, match h with or.inl ⟨a⟩ := ⟨psum.inl a⟩ | or.inr ⟨b⟩ := ⟨psum.inr b⟩ end)
@[simp] lemma nonempty_psigma {α : Sort u} {β : α → Sort v} :
nonempty (psigma β) ↔ (∃a:α, nonempty (β a)) :=
iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩)
@[simp] lemma nonempty_empty : ¬ nonempty empty :=
assume ⟨h⟩, h.elim
@[simp] lemma nonempty_ulift : nonempty (ulift α) ↔ nonempty α :=
iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩)
@[simp] lemma nonempty_plift {α : Sort u} : nonempty (plift α) ↔ nonempty α :=
iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩)
@[simp] lemma nonempty.forall {α : Sort u} {p : nonempty α → Prop} :
(∀h:nonempty α, p h) ↔ (∀a, p ⟨a⟩) :=
iff.intro (assume h a, h _) (assume h ⟨a⟩, h _)
@[simp] lemma nonempty.exists {α : Sort u} {p : nonempty α → Prop} :
(∃h:nonempty α, p h) ↔ (∃a, p ⟨a⟩) :=
iff.intro (assume ⟨⟨a⟩, h⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a⟩, h⟩)
lemma classical.nonempty_pi {α : Sort u} {β : α → Sort v} :
nonempty (Πa:α, β a) ↔ (∀a:α, nonempty (β a)) :=
iff.intro (assume ⟨f⟩ a, ⟨f a⟩) (assume f, ⟨assume a, classical.choice $ f a⟩)
/-- Using `classical.choice`, lifts a (`Prop`-valued) `nonempty` instance to a (`Type`-valued)
`inhabited` instance. `classical.inhabited_of_nonempty` already exists, in
`core/init/classical.lean`, but the assumption is not a type class argument,
which makes it unsuitable for some applications. -/
noncomputable def classical.inhabited_of_nonempty' {α : Sort u} [h : nonempty α] : inhabited α :=
⟨classical.choice h⟩
/-- Given `f : α → β`, if `α` is nonempty then `β` is also nonempty.
`nonempty` cannot be a `functor`, because `functor` is restricted to `Type`. -/
lemma nonempty.map {α : Sort u} {β : Sort v} (f : α → β) : nonempty α → nonempty β
| ⟨h⟩ := ⟨f h⟩
protected lemma nonempty.map2 {α β γ : Sort*} (f : α → β → γ) : nonempty α → nonempty β → nonempty γ
| ⟨x⟩ ⟨y⟩ := ⟨f x y⟩
protected lemma nonempty.congr {α : Sort u} {β : Sort v} (f : α → β) (g : β → α) :
nonempty α ↔ nonempty β :=
⟨nonempty.map f, nonempty.map g⟩
lemma nonempty.elim_to_inhabited {α : Sort*} [h : nonempty α] {p : Prop}
(f : inhabited α → p) : p :=
h.elim $ f ∘ inhabited.mk
instance {α β} [h : nonempty α] [h2 : nonempty β] : nonempty (α × β) :=
h.elim $ λ g, h2.elim $ λ g2, ⟨⟨g, g2⟩⟩
end nonempty
|
ac984910cee78fa6da2c29c3d94380fbdd6e8f76 | 00c000939652bc85fffcfe8ba5dd194580a13c4b | /src/mvfunctor.lean | 5f631f5772e4820df93636660fb5280c56d28a62 | [
"Apache-2.0"
] | permissive | johoelzl/qpf | a795220c4e872014a62126800313b74ba3b06680 | d93ab1fb41d085e49ae476fa364535f40388f44d | refs/heads/master | 1,587,372,400,745 | 1,548,633,467,000 | 1,548,633,467,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,335 | lean | /-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
Tuples of types, and their categorical structure.
Features:
`typevec n` : n-tuples of types
`α ⟹ β` : n-tuples of maps
`f ⊚ g` : composition
`mvfunctor n` : the type class of multivariate functors
`f <$$> x` : notation for map
Also, support functions for operating with n-tuples of types, such as:
`append1 α β` : append type `β` to n-tuple `α` to obtain an (n+1)-tuple
`drop α` : drops the last element of an (n+1)-tuple
`last α` : returns the last element of an (n+1)-tuple
`append_fun f g` : appends a function g to an n-tuple of functions
`drop_fun f` : drops the last function from an n+1-tuple
`last_fun f` : returns the last function of a tuple.
Since e.g. `append1 α.drop α.last` is propositionally equal to `α` but not definitionally equal
to it, we need lots of support functions and lemmas to mediate between constructions.
-/
import .pfunctor
/-
n-tuples of types, as a category
-/
def typevec (n : ℕ) := fin n → Type*
namespace typevec
variable {n : ℕ}
def arrow (α β : typevec n) := Π i : fin n, α i → β i
infixl ` ⟹ `:40 := arrow
def id {α : typevec n} : α ⟹ α := λ i x, x
def comp {α β γ : typevec n} (g : β ⟹ γ) (f : α ⟹ β) : α ⟹ γ :=
λ i x, g i (f i x)
infixr ` ⊚ `:80 := typevec.comp -- type as \oo
@[simp] theorem id_comp {α β : typevec n} (f : α ⟹ β) : id ⊚ f = f :=
rfl
@[simp] theorem comp_id {α β : typevec n} (f : α ⟹ β) : f ⊚ id = f :=
rfl
theorem comp_assoc {α β γ δ : typevec n} (h : γ ⟹ δ) (g : β ⟹ γ) (f : α ⟹ β) :
(h ⊚ g) ⊚ f = h ⊚ g ⊚ f := rfl
end typevec
class mvfunctor {n : ℕ} (F : typevec n → Type*) :=
(map : Π {α β : typevec n}, (α ⟹ β) → (F α → F β))
infixr ` <$$> `:100 := mvfunctor.map
class is_lawful_mvfunctor {n : ℕ} (F : typevec n → Type*) [mvfunctor F] : Prop :=
(mv_id_map : Π {α : typevec n} (x : F α), typevec.id <$$> x = x)
(mv_comp_map : Π {α β γ : typevec n} (g : α ⟹ β) (h : β ⟹ γ) (x : F α),
(h ⊚ g) <$$> x = h <$$> g <$$> x)
export is_lawful_mvfunctor (mv_id_map mv_comp_map)
attribute [simp] mv_id_map
/-
Support for extending a typevec by one element.
-/
namespace eq
theorem mp_mpr {α β : Type*} (h : α = β) (x : β) :
eq.mp h (eq.mpr h x) = x :=
by induction h; reflexivity
theorem mpr_mp {α β : Type*} (h : α = β) (x : α) :
eq.mpr h (eq.mp h x) = x :=
by induction h; reflexivity
end eq
namespace fin
def succ_cases {n : ℕ} (i : fin (n + 1)) : psum {j : fin n // i = j.cast_succ} (i = fin.last n) :=
begin
cases i with i h,
by_cases h' : i < n,
{ left, refine ⟨⟨i, h'⟩, _⟩, apply eq_of_veq, reflexivity },
right, apply eq_of_veq,
show i = n, from le_antisymm (nat.le_of_lt_succ h) (le_of_not_lt h')
end
def succ_rec' {n : ℕ} {β : fin (n + 1) → Type*}
(f : Π i : fin n, β i.cast_succ) (a : β (fin.last n)) : Π i : fin (n + 1), β i
| ⟨i, h⟩ := if h' : i < n then
have cast_succ ⟨i, h'⟩ = ⟨i, h⟩, from fin.eq_of_veq rfl,
by rw ←this; exact f ⟨i, h'⟩
else
have fin.last n = ⟨i, h⟩,
from fin.eq_of_veq (le_antisymm (le_of_not_lt h') (nat.le_of_lt_succ h)),
by rw ←this; exact a
@[simp] theorem succ_rec'_cast_succ {n : ℕ} {β : fin (n + 1) → Type*}
(f : Π i : fin n, β i.cast_succ) (a : β (fin.last n)) (i : fin n) :
succ_rec' f a i.cast_succ = f i :=
begin
cases i with i h,
change succ_rec' f a ⟨i, _⟩ = _,
dsimp [succ_rec'], rw dif_pos h,
reflexivity
end
@[simp] theorem succ_rec'_last {n : ℕ} {β : fin (n + 1) → Type*}
(f : Π i : fin n, β i.cast_succ) (a : β (fin.last n)) :
succ_rec' f a (fin.last n) = a :=
begin
change succ_rec' f a ⟨n, _⟩ = _,
dsimp [succ_rec'], rw dif_neg (lt_irrefl n),
reflexivity
end
end fin
namespace typevec
variable {n : ℕ}
def append1 (α : typevec n) (β : Type*) : typevec (n+1) :=
fin.succ_rec' α β
def drop (α : typevec (n+1)) : typevec n := λ i, α i.cast_succ
def last (α : typevec (n+1)) : Type* := α (fin.last n)
theorem drop_append1 {α : typevec n} {β : Type*} {i : fin n} : drop (append1 α β) i = α i :=
fin.succ_rec'_cast_succ _ _ _
theorem last_append1 {α : typevec n} {β : Type*} : last (append1 α β) = β :=
fin.succ_rec'_last _ _
def to_drop_append {α : typevec n} {β : Type*} : α ⟹ drop (append1 α β) :=
λ i, eq.mpr drop_append1
def from_drop_append {α : typevec n} {β : Type*} : drop (append1 α β) ⟹ α :=
λ i, eq.mp drop_append1
@[simp] theorem to_drop_append_from_drop_append {α : typevec n} {β : Type*} {i : fin n}
(x : drop (append1 α β) i) :
to_drop_append i (from_drop_append i x) = x := eq.mpr_mp _ _
@[simp] theorem from_drop_append_to_drop_append {α : typevec n} {β : Type*} {i : fin n} (x : α i) :
from_drop_append i (@to_drop_append n α β i x) = x := eq.mp_mpr _ _
def to_last_append {α : typevec n} {β : Type*} : β → last (append1 α β) :=
eq.mpr last_append1
def from_last_append {α : typevec n} {β : Type*} : last (append1 α β) → β :=
eq.mp last_append1
@[simp] theorem to_last_append_from_last_append {α : typevec n} {β : Type*} (x : last (append1 α β)) :
to_last_append (from_last_append x) = x := eq.mpr_mp _ _
@[simp] theorem from_last_append_to_last_append {α : typevec n} {β : Type*} (x : β) :
from_last_append (@to_last_append n α β x) = x := eq.mpr_mp _ _
theorem append1_drop_last {α : typevec (n+1)} {i : fin (n+1)} : append1 (drop α) (last α) i = α i :=
by rw [append1, drop, last]; rcases i.succ_cases with ⟨j, ieq⟩ | ieq; rw ieq; simp
def to_append1_drop_last {α : typevec (n+1)} : α ⟹ append1 (drop α) (last α) :=
λ i, eq.mpr append1_drop_last
def from_append1_drop_last {α : typevec (n+1)} : append1 (drop α) (last α) ⟹ α :=
λ i, eq.mp append1_drop_last
@[simp] theorem to_append1_drop_last_from_append1_drop_last {α : typevec (n+1)} {i : fin (n+1)}
(x : append1 (drop α) (last α) i) :
to_append1_drop_last i (from_append1_drop_last i x) = x := eq.mp_mpr _ _
@[simp] theorem from_append1_drop_last_to_append1_drop_last {α : typevec (n+1)} {i : fin (n+1)}
(x : α i) :
from_append1_drop_last i (to_append1_drop_last i x) = x := eq.mpr_mp _ _
def append_fun {α α' : typevec n} {β β' : Type*}
(f : α ⟹ α') (g : β → β') : append1 α β ⟹ append1 α' β' :=
fin.succ_rec' (to_drop_append ⊚ f ⊚ from_drop_append) (to_last_append ∘ g ∘ from_last_append)
def drop_fun {α β : typevec (n+1)} (f : α ⟹ β) : drop α ⟹ drop β :=
λ i, f i.cast_succ
def last_fun {α β : typevec (n+1)} (f : α ⟹ β) : last α → last β :=
f (fin.last n)
theorem eq_of_drop_last_eq {α β : typevec (n+1)} (f g : α ⟹ β)
(h₀ : ∀ j, drop_fun f j = drop_fun g j) (h₁ : last_fun f = last_fun g) : f = g :=
begin
ext1 i; rcases i.succ_cases with ⟨j, ieq⟩ | ieq; rw ieq,
{ exact h₀ j },
exact h₁
end
theorem drop_fun_append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') :
drop_fun (append_fun f g) = to_drop_append ⊚ f ⊚ from_drop_append :=
by ext1 i; dsimp only [drop_fun, append_fun]; rw [fin.succ_rec'_cast_succ]
theorem last_fun_append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') :
last_fun (append_fun f g) = to_last_append ∘ g ∘ from_last_append :=
by ext1 i; dsimp only [last_fun, append_fun]; rw [fin.succ_rec'_last]
def append_fun_comp {α₀ α₁ α₂ : typevec n} {β₀ β₁ β₂ : Type*}
(f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) :
append_fun (f₁ ⊚ f₀) (g₁ ∘ g₀) = append_fun f₁ g₁ ⊚ append_fun f₀ g₀ :=
by ext1 i; rcases i.succ_cases with ⟨j, ieq⟩ | ieq; rw ieq;
simp [append_fun, function.comp, typevec.comp]
theorem drop_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) :
drop_fun (f₁ ⊚ f₀) = drop_fun f₁ ⊚ drop_fun f₀ := rfl
theorem last_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) :
last_fun (f₁ ⊚ f₀) = last_fun f₁ ∘ last_fun f₀ := rfl
theorem drop_fun_to_append1_drop_last {α : typevec (n+1)} :
drop_fun (@to_append1_drop_last n α) = to_drop_append := rfl
theorem last_fun_to_append1_drop_last {α : typevec (n+1)} :
last_fun (@to_append1_drop_last n α) = to_last_append := rfl
theorem append_fun_aux {γ : typevec (n+1)} {α : typevec n} {β : Type*} (f : γ ⟹ append1 α β) :
append_fun (from_drop_append ⊚ drop_fun f)
(from_last_append ∘ last_fun f) ⊚ to_append1_drop_last = f :=
begin
ext1 i, rcases i.succ_cases with ⟨j, ieq⟩ | ieq; rw ieq;
simp [append_fun, function.comp, typevec.comp]; ext x; congr; apply eq.mp_mpr
end
theorem append_fun_id_id {α : typevec n} {β : Type*} :
append_fun (@id n α) (@_root_.id β) = id :=
by ext1 i; rcases i.succ_cases with ⟨j, ieq⟩ | ieq; rw ieq; ext x;
simp [append_fun, typevec.comp, id]
end typevec
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.