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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d3f4b7f7494b05ef4abf0b9084cffc38bbac1ab3 | 0c9c1ff8e5013c525bf1d72338b62db639374733 | /library/data/stream.lean | ec2b300caf08d2a8c7bf2524bfb5fccef8b9b8c4 | [
"Apache-2.0"
] | permissive | semorrison/lean | 1f2bb450c3400098666ff6e43aa29b8e1e3cdc3a | 85dcb385d5219f2fca8c73b2ebca270fe81337e0 | refs/heads/master | 1,638,526,143,586 | 1,634,825,588,000 | 1,634,825,588,000 | 258,650,844 | 0 | 0 | Apache-2.0 | 1,587,772,955,000 | 1,587,772,954,000 | null | UTF-8 | Lean | false | false | 21,712 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
open nat function option
universes u v w
def stream (α : Type u) := nat → α
namespace stream
variables {α : Type u} {β : Type v} {δ : Type w}
def cons (a : α) (s : stream α) : stream α :=
λ i,
match i with
| 0 := a
| succ n := s n
end
notation h :: t := cons h t
@[reducible] def head (s : stream α) : α :=
s 0
def tail (s : stream α) : stream α :=
λ i, s (i+1)
def drop (n : nat) (s : stream α) : stream α :=
λ i, s (i+n)
@[reducible] def nth (n : nat) (s : stream α) : α :=
s n
protected theorem eta (s : stream α) : head s :: tail s = s :=
funext (λ i, begin cases i; refl end)
theorem nth_zero_cons (a : α) (s : stream α) : nth 0 (a :: s) = a := rfl
theorem head_cons (a : α) (s : stream α) : head (a :: s) = a := rfl
theorem tail_cons (a : α) (s : stream α) : tail (a :: s) = s := rfl
theorem tail_drop (n : nat) (s : stream α) : tail (drop n s) = drop n (tail s) :=
funext (λ i, begin unfold tail drop, simp [nat.add_comm, nat.add_left_comm] end)
theorem nth_drop (n m : nat) (s : stream α) : nth n (drop m s) = nth (n+m) s := rfl
theorem tail_eq_drop (s : stream α) : tail s = drop 1 s := rfl
theorem drop_drop (n m : nat) (s : stream α) : drop n (drop m s) = drop (n+m) s :=
funext (λ i, begin unfold drop, rw nat.add_assoc end)
theorem nth_succ (n : nat) (s : stream α) : nth (succ n) s = nth n (tail s) := rfl
theorem drop_succ (n : nat) (s : stream α) : drop (succ n) s = drop n (tail s) := rfl
protected theorem ext {s₁ s₂ : stream α} : (∀ n, nth n s₁ = nth n s₂) → s₁ = s₂ :=
assume h, funext h
def all (p : α → Prop) (s : stream α) := ∀ n, p (nth n s)
def any (p : α → Prop) (s : stream α) := ∃ n, p (nth n s)
theorem all_def (p : α → Prop) (s : stream α) : all p s = ∀ n, p (nth n s) := rfl
theorem any_def (p : α → Prop) (s : stream α) : any p s = ∃ n, p (nth n s) := rfl
protected def mem (a : α) (s : stream α) := any (λ b, a = b) s
instance : has_mem α (stream α) :=
⟨stream.mem⟩
theorem mem_cons (a : α) (s : stream α) : a ∈ (a::s) :=
exists.intro 0 rfl
theorem mem_cons_of_mem {a : α} {s : stream α} (b : α) : a ∈ s → a ∈ b :: s :=
assume ⟨n, h⟩,
exists.intro (succ n) (by rw [nth_succ, tail_cons, h])
theorem eq_or_mem_of_mem_cons {a b : α} {s : stream α} : a ∈ b::s → a = b ∨ a ∈ s :=
assume ⟨n, h⟩,
begin
cases n with n',
{left, exact h},
{right, rw [nth_succ, tail_cons] at h, exact ⟨n', h⟩}
end
theorem mem_of_nth_eq {n : nat} {s : stream α} {a : α} : a = nth n s → a ∈ s :=
assume h, exists.intro n h
section map
variable (f : α → β)
def map (s : stream α) : stream β :=
λ n, f (nth n s)
theorem drop_map (n : nat) (s : stream α) : drop n (map f s) = map f (drop n s) :=
stream.ext (λ i, rfl)
theorem nth_map (n : nat) (s : stream α) : nth n (map f s) = f (nth n s) := rfl
theorem tail_map (s : stream α) : tail (map f s) = map f (tail s) :=
begin rw tail_eq_drop, refl end
theorem head_map (s : stream α) : head (map f s) = f (head s) := rfl
theorem map_eq (s : stream α) : map f s = f (head s) :: map f (tail s) :=
by rw [← stream.eta (map f s), tail_map, head_map]
theorem map_cons (a : α) (s : stream α) : map f (a :: s) = f a :: map f s :=
begin rw [← stream.eta (map f (a :: s)), map_eq], refl end
theorem map_id (s : stream α) : map id s = s := rfl
theorem map_map (g : β → δ) (f : α → β) (s : stream α) : map g (map f s) = map (g ∘ f) s := rfl
theorem map_tail (s : stream α) : map f (tail s) = tail (map f s) := rfl
theorem mem_map {a : α} {s : stream α} : a ∈ s → f a ∈ map f s :=
assume ⟨n, h⟩,
exists.intro n (by rw [nth_map, h])
theorem exists_of_mem_map {f} {b : β} {s : stream α} : b ∈ map f s → ∃ a, a ∈ s ∧ f a = b :=
assume ⟨n, h⟩, ⟨nth n s, ⟨n, rfl⟩, h.symm⟩
end map
section zip
variable (f : α → β → δ)
def zip (s₁ : stream α) (s₂ : stream β) : stream δ :=
λ n, f (nth n s₁) (nth n s₂)
theorem drop_zip (n : nat) (s₁ : stream α) (s₂ : stream β) : drop n (zip f s₁ s₂) = zip f (drop n s₁) (drop n s₂) :=
stream.ext (λ i, rfl)
theorem nth_zip (n : nat) (s₁ : stream α) (s₂ : stream β) : nth n (zip f s₁ s₂) = f (nth n s₁) (nth n s₂) := rfl
theorem head_zip (s₁ : stream α) (s₂ : stream β) : head (zip f s₁ s₂) = f (head s₁) (head s₂) := rfl
theorem tail_zip (s₁ : stream α) (s₂ : stream β) : tail (zip f s₁ s₂) = zip f (tail s₁) (tail s₂) := rfl
theorem zip_eq (s₁ : stream α) (s₂ : stream β) : zip f s₁ s₂ = f (head s₁) (head s₂) :: zip f (tail s₁) (tail s₂) :=
begin rw [← stream.eta (zip f s₁ s₂)], refl end
end zip
def const (a : α) : stream α :=
λ n, a
theorem mem_const (a : α) : a ∈ const a :=
exists.intro 0 rfl
theorem const_eq (a : α) : const a = a :: const a :=
begin
apply stream.ext, intro n,
cases n; refl
end
theorem tail_const (a : α) : tail (const a) = const a :=
suffices tail (a :: const a) = const a, by rwa [← const_eq] at this, rfl
theorem map_const (f : α → β) (a : α) : map f (const a) = const (f a) := rfl
theorem nth_const (n : nat) (a : α) : nth n (const a) = a := rfl
theorem drop_const (n : nat) (a : α) : drop n (const a) = const a :=
stream.ext (λ i, rfl)
def iterate (f : α → α) (a : α) : stream α :=
λ n, nat.rec_on n a (λ n r, f r)
theorem head_iterate (f : α → α) (a : α) : head (iterate f a) = a := rfl
theorem tail_iterate (f : α → α) (a : α) : tail (iterate f a) = iterate f (f a) :=
begin
funext n,
induction n with n' ih,
{refl},
{unfold tail iterate,
unfold tail iterate at ih,
rw add_one at ih, dsimp at ih,
rw add_one, dsimp, rw ih}
end
theorem iterate_eq (f : α → α) (a : α) : iterate f a = a :: iterate f (f a) :=
begin
rw [← stream.eta (iterate f a)],
rw tail_iterate, refl
end
theorem nth_zero_iterate (f : α → α) (a : α) : nth 0 (iterate f a) = a := rfl
theorem nth_succ_iterate (n : nat) (f : α → α) (a : α) : nth (succ n) (iterate f a) = nth n (iterate f (f a)) :=
by rw [nth_succ, tail_iterate]
section bisim
variable (R : stream α → stream α → Prop)
local infix ` ~ `:50 := R
def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → head s₁ = head s₂ ∧ tail s₁ ~ tail s₂
theorem nth_of_bisim (bisim : is_bisimulation R) : ∀ {s₁ s₂} n, s₁ ~ s₂ → nth n s₁ = nth n s₂ ∧ drop (n+1) s₁ ~ drop (n+1) s₂
| s₁ s₂ 0 h := bisim h
| s₁ s₂ (n+1) h :=
match bisim h with
| ⟨h₁, trel⟩ := nth_of_bisim n trel
end
-- If two streams are bisimilar, then they are equal
theorem eq_of_bisim (bisim : is_bisimulation R) : ∀ {s₁ s₂}, s₁ ~ s₂ → s₁ = s₂ :=
λ s₁ s₂ r, stream.ext (λ n, and.elim_left (nth_of_bisim R bisim n r))
end bisim
theorem bisim_simple (s₁ s₂ : stream α) : head s₁ = head s₂ → s₁ = tail s₁ → s₂ = tail s₂ → s₁ = s₂ :=
assume hh ht₁ ht₂, eq_of_bisim
(λ s₁ s₂, head s₁ = head s₂ ∧ s₁ = tail s₁ ∧ s₂ = tail s₂)
(λ s₁ s₂ ⟨h₁, h₂, h₃⟩,
begin
constructor, exact h₁, rw [← h₂, ← h₃], repeat { constructor }; assumption
end)
(and.intro hh (and.intro ht₁ ht₂))
theorem coinduction {s₁ s₂ : stream α} :
head s₁ = head s₂ → (∀ (β : Type u) (fr : stream α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂ :=
assume hh ht,
eq_of_bisim
(λ s₁ s₂, head s₁ = head s₂ ∧ ∀ (β : Type u) (fr : stream α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂))
(λ s₁ s₂ h,
have h₁ : head s₁ = head s₂, from and.elim_left h,
have h₂ : head (tail s₁) = head (tail s₂), from and.elim_right h α (@head α) h₁,
have h₃ : ∀ (β : Type u) (fr : stream α → β), fr (tail s₁) = fr (tail s₂) → fr (tail (tail s₁)) = fr (tail (tail s₂)), from
λ β fr, and.elim_right h β (λ s, fr (tail s)),
and.intro h₁ (and.intro h₂ h₃))
(and.intro hh ht)
theorem iterate_id (a : α) : iterate id a = const a :=
coinduction
rfl
(λ β fr ch, begin rw [tail_iterate, tail_const], exact ch end)
local attribute [reducible] stream
theorem map_iterate (f : α → α) (a : α) : iterate f (f a) = map f (iterate f a) :=
begin
funext n,
induction n with n' ih,
{refl},
{ unfold map iterate nth, dsimp,
unfold map iterate nth at ih, dsimp at ih,
rw ih }
end
section corec
def corec (f : α → β) (g : α → α) : α → stream β :=
λ a, map f (iterate g a)
def corec_on (a : α) (f : α → β) (g : α → α) : stream β :=
corec f g a
theorem corec_def (f : α → β) (g : α → α) (a : α) : corec f g a = map f (iterate g a) := rfl
theorem corec_eq (f : α → β) (g : α → α) (a : α) : corec f g a = f a :: corec f g (g a) :=
begin rw [corec_def, map_eq, head_iterate, tail_iterate], refl end
theorem corec_id_id_eq_const (a : α) : corec id id a = const a :=
by rw [corec_def, map_id, iterate_id]
theorem corec_id_f_eq_iterate (f : α → α) (a : α) : corec id f a = iterate f a := rfl
end corec
section corec'
def corec' (f : α → β × α) : α → stream β := corec (prod.fst ∘ f) (prod.snd ∘ f)
theorem corec'_eq (f : α → β × α) (a : α) : corec' f a = (f a).1 :: corec' f (f a).2 :=
corec_eq _ _ _
end corec'
-- corec is also known as unfold
def unfolds (g : α → β) (f : α → α) (a : α) : stream β :=
corec g f a
theorem unfolds_eq (g : α → β) (f : α → α) (a : α) : unfolds g f a = g a :: unfolds g f (f a) :=
begin unfold unfolds, rw [corec_eq] end
theorem nth_unfolds_head_tail : ∀ (n : nat) (s : stream α), nth n (unfolds head tail s) = nth n s :=
begin
intro n, induction n with n' ih,
{intro s, refl},
{intro s, rw [nth_succ, nth_succ, unfolds_eq, tail_cons, ih]}
end
theorem unfolds_head_eq : ∀ (s : stream α), unfolds head tail s = s :=
λ s, stream.ext (λ n, nth_unfolds_head_tail n s)
def interleave (s₁ s₂ : stream α) : stream α :=
corec_on (s₁, s₂)
(λ ⟨s₁, s₂⟩, head s₁)
(λ ⟨s₁, s₂⟩, (s₂, tail s₁))
infix `⋈`:65 := interleave
theorem interleave_eq (s₁ s₂ : stream α) : s₁ ⋈ s₂ = head s₁ :: head s₂ :: (tail s₁ ⋈ tail s₂) :=
begin
unfold interleave corec_on, rw corec_eq, dsimp, rw corec_eq, refl
end
theorem tail_interleave (s₁ s₂ : stream α) : tail (s₁ ⋈ s₂) = s₂ ⋈ (tail s₁) :=
begin unfold interleave corec_on, rw corec_eq, refl end
theorem interleave_tail_tail (s₁ s₂ : stream α) : tail s₁ ⋈ tail s₂ = tail (tail (s₁ ⋈ s₂)) :=
begin rw [interleave_eq s₁ s₂], refl end
theorem nth_interleave_left : ∀ (n : nat) (s₁ s₂ : stream α), nth (2*n) (s₁ ⋈ s₂) = nth n s₁
| 0 s₁ s₂ := rfl
| (succ n) s₁ s₂ :=
begin
change nth (succ (succ (2*n))) (s₁ ⋈ s₂) = nth (succ n) s₁,
rw [nth_succ, nth_succ, interleave_eq, tail_cons, tail_cons, nth_interleave_left],
refl
end
theorem nth_interleave_right : ∀ (n : nat) (s₁ s₂ : stream α), nth (2*n+1) (s₁ ⋈ s₂) = nth n s₂
| 0 s₁ s₂ := rfl
| (succ n) s₁ s₂ :=
begin
change nth (succ (succ (2*n+1))) (s₁ ⋈ s₂) = nth (succ n) s₂,
rw [nth_succ, nth_succ, interleave_eq, tail_cons, tail_cons, nth_interleave_right],
refl
end
theorem mem_interleave_left {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₁ → a ∈ s₁ ⋈ s₂ :=
assume ⟨n, h⟩,
exists.intro (2*n) (by rw [h, nth_interleave_left])
theorem mem_interleave_right {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₂ → a ∈ s₁ ⋈ s₂ :=
assume ⟨n, h⟩,
exists.intro (2*n+1) (by rw [h, nth_interleave_right])
def even (s : stream α) : stream α :=
corec
(λ s, head s)
(λ s, tail (tail s))
s
def odd (s : stream α) : stream α :=
even (tail s)
theorem odd_eq (s : stream α) : odd s = even (tail s) := rfl
theorem head_even (s : stream α) : head (even s) = head s := rfl
theorem tail_even (s : stream α) : tail (even s) = even (tail (tail s)) :=
begin unfold even, rw corec_eq, refl end
theorem even_cons_cons (a₁ a₂ : α) (s : stream α) : even (a₁ :: a₂ :: s) = a₁ :: even s :=
begin unfold even, rw corec_eq, refl end
theorem even_tail (s : stream α) : even (tail s) = odd s := rfl
theorem even_interleave (s₁ s₂ : stream α) : even (s₁ ⋈ s₂) = s₁ :=
eq_of_bisim
(λ s₁' s₁, ∃ s₂, s₁' = even (s₁ ⋈ s₂))
(λ s₁' s₁ ⟨s₂, h₁⟩,
begin
rw h₁,
constructor,
{refl},
{exact ⟨tail s₂, by rw [interleave_eq, even_cons_cons, tail_cons]⟩}
end)
(exists.intro s₂ rfl)
theorem interleave_even_odd (s₁ : stream α) : even s₁ ⋈ odd s₁ = s₁ :=
eq_of_bisim
(λ s' s, s' = even s ⋈ odd s)
(λ s' s (h : s' = even s ⋈ odd s),
begin
rw h, constructor,
{refl},
{simp [odd_eq, odd_eq, tail_interleave, tail_even]}
end)
rfl
theorem nth_even : ∀ (n : nat) (s : stream α), nth n (even s) = nth (2*n) s
| 0 s := rfl
| (succ n) s :=
begin
change nth (succ n) (even s) = nth (succ (succ (2 * n))) s,
rw [nth_succ, nth_succ, tail_even, nth_even], refl
end
theorem nth_odd : ∀ (n : nat) (s : stream α), nth n (odd s) = nth (2*n + 1) s :=
λ n s, begin rw [odd_eq, nth_even], refl end
theorem mem_of_mem_even (a : α) (s : stream α) : a ∈ even s → a ∈ s :=
assume ⟨n, h⟩,
exists.intro (2*n) (by rw [h, nth_even])
theorem mem_of_mem_odd (a : α) (s : stream α) : a ∈ odd s → a ∈ s :=
assume ⟨n, h⟩,
exists.intro (2*n+1) (by rw [h, nth_odd])
def append_stream : list α → stream α → stream α
| [] s := s
| (list.cons a l) s := a :: append_stream l s
theorem nil_append_stream (s : stream α) : append_stream [] s = s := rfl
theorem cons_append_stream (a : α) (l : list α) (s : stream α) : append_stream (a::l) s = a :: append_stream l s := rfl
infix `++ₛ`:65 := append_stream
theorem append_append_stream : ∀ (l₁ l₂ : list α) (s : stream α), (l₁ ++ l₂) ++ₛ s = l₁ ++ₛ (l₂ ++ₛ s)
| [] l₂ s := rfl
| (list.cons a l₁) l₂ s := by rw [list.cons_append, cons_append_stream, cons_append_stream, append_append_stream]
theorem map_append_stream (f : α → β) : ∀ (l : list α) (s : stream α), map f (l ++ₛ s) = list.map f l ++ₛ map f s
| [] s := rfl
| (list.cons a l) s := by rw [cons_append_stream, list.map_cons, map_cons, cons_append_stream, map_append_stream]
theorem drop_append_stream : ∀ (l : list α) (s : stream α), drop l.length (l ++ₛ s) = s
| [] s := by refl
| (list.cons a l) s := by rw [list.length_cons, add_one, drop_succ, cons_append_stream, tail_cons, drop_append_stream]
theorem append_stream_head_tail (s : stream α) : [head s] ++ₛ tail s = s :=
by rw [cons_append_stream, nil_append_stream, stream.eta]
theorem mem_append_stream_right : ∀ {a : α} (l : list α) {s : stream α}, a ∈ s → a ∈ l ++ₛ s
| a [] s h := h
| a (list.cons b l) s h :=
have ih : a ∈ l ++ₛ s, from mem_append_stream_right l h,
mem_cons_of_mem _ ih
theorem mem_append_stream_left : ∀ {a : α} {l : list α} (s : stream α), a ∈ l → a ∈ l ++ₛ s
| a [] s h := absurd h (list.not_mem_nil _)
| a (list.cons b l) s h :=
or.elim (list.eq_or_mem_of_mem_cons h)
(λ (aeqb : a = b), exists.intro 0 aeqb)
(λ (ainl : a ∈ l), mem_cons_of_mem b (mem_append_stream_left s ainl))
def approx : nat → stream α → list α
| 0 s := []
| (n+1) s := list.cons (head s) (approx n (tail s))
theorem approx_zero (s : stream α) : approx 0 s = [] := rfl
theorem approx_succ (n : nat) (s : stream α) : approx (succ n) s = head s :: approx n (tail s) := rfl
theorem nth_approx : ∀ (n : nat) (s : stream α), list.nth (approx (succ n) s) n = some (nth n s)
| 0 s := rfl
| (n+1) s := begin rw [approx_succ, add_one, list.nth, nth_approx], refl end
theorem append_approx_drop : ∀ (n : nat) (s : stream α), append_stream (approx n s) (drop n s) = s :=
begin
intro n,
induction n with n' ih,
{intro s, refl},
{intro s, rw [approx_succ, drop_succ, cons_append_stream, ih (tail s), stream.eta]}
end
-- Take theorem reduces a proof of equality of infinite streams to an
-- induction over all their finite approximations.
theorem take_theorem (s₁ s₂ : stream α) : (∀ (n : nat), approx n s₁ = approx n s₂) → s₁ = s₂ :=
begin
intro h, apply stream.ext, intro n,
induction n with n ih,
{ have aux := h 1, simp [approx] at aux, exact aux },
{ have h₁ : some (nth (succ n) s₁) = some (nth (succ n) s₂),
{ rw [← nth_approx, ← nth_approx, h (succ (succ n))] },
injection h₁ }
end
-- auxiliary def for cycle corecursive def
private def cycle_f : α × list α × α × list α → α
| (v, _, _, _) := v
-- auxiliary def for cycle corecursive def
private def cycle_g : α × list α × α × list α → α × list α × α × list α
| (v₁, [], v₀, l₀) := (v₀, l₀, v₀, l₀)
| (v₁, list.cons v₂ l₂, v₀, l₀) := (v₂, l₂, v₀, l₀)
private lemma cycle_g_cons (a : α) (a₁ : α) (l₁ : list α) (a₀ : α) (l₀ : list α) :
cycle_g (a, a₁::l₁, a₀, l₀) = (a₁, l₁, a₀, l₀) := rfl
def cycle : Π (l : list α), l ≠ [] → stream α
| [] h := absurd rfl h
| (list.cons a l) h := corec cycle_f cycle_g (a, l, a, l)
theorem cycle_eq : ∀ (l : list α) (h : l ≠ []), cycle l h = l ++ₛ cycle l h
| [] h := absurd rfl h
| (list.cons a l) h :=
have gen : ∀ l' a', corec cycle_f cycle_g (a', l', a, l) = (a' :: l') ++ₛ corec cycle_f cycle_g (a, l, a, l),
begin
intro l',
induction l' with a₁ l₁ ih,
{intros, rw [corec_eq], refl},
{intros, rw [corec_eq, cycle_g_cons, ih a₁], refl}
end,
gen l a
theorem mem_cycle {a : α} {l : list α} : ∀ (h : l ≠ []), a ∈ l → a ∈ cycle l h :=
assume h ainl, begin rw [cycle_eq], exact mem_append_stream_left _ ainl end
theorem cycle_singleton (a : α) (h : [a] ≠ []) : cycle [a] h = const a :=
coinduction
rfl
(λ β fr ch, by rwa [cycle_eq, const_eq])
def tails (s : stream α) : stream (stream α) :=
corec id tail (tail s)
theorem tails_eq (s : stream α) : tails s = tail s :: tails (tail s) :=
by unfold tails; rw [corec_eq]; refl
theorem nth_tails : ∀ (n : nat) (s : stream α), nth n (tails s) = drop n (tail s) :=
begin
intro n, induction n with n' ih,
{intros, refl},
{intro s, rw [nth_succ, drop_succ, tails_eq, tail_cons, ih]}
end
theorem tails_eq_iterate (s : stream α) : tails s = iterate tail (tail s) := rfl
def inits_core (l : list α) (s : stream α) : stream (list α) :=
corec_on (l, s)
(λ ⟨a, b⟩, a)
(λ p, match p with (l', s') := (l' ++ [head s'], tail s') end)
def inits (s : stream α) : stream (list α) :=
inits_core [head s] (tail s)
theorem inits_core_eq (l : list α) (s : stream α) : inits_core l s = l :: inits_core (l ++ [head s]) (tail s) :=
begin unfold inits_core corec_on, rw [corec_eq], refl end
theorem tail_inits (s : stream α) : tail (inits s) = inits_core [head s, head (tail s)] (tail (tail s)) :=
begin unfold inits, rw inits_core_eq, refl end
theorem inits_tail (s : stream α) : inits (tail s) = inits_core [head (tail s)] (tail (tail s)) := rfl
theorem cons_nth_inits_core : ∀ (a : α) (n : nat) (l : list α) (s : stream α),
a :: nth n (inits_core l s) = nth n (inits_core (a::l) s) :=
begin
intros a n,
induction n with n' ih,
{intros, refl},
{intros l s, rw [nth_succ, inits_core_eq, tail_cons, ih, inits_core_eq (a::l) s], refl }
end
theorem nth_inits : ∀ (n : nat) (s : stream α), nth n (inits s) = approx (succ n) s :=
begin
intro n, induction n with n' ih,
{intros, refl},
{intros, rw [nth_succ, approx_succ, ← ih, tail_inits, inits_tail, cons_nth_inits_core]}
end
theorem inits_eq (s : stream α) : inits s = [head s] :: map (list.cons (head s)) (inits (tail s)) :=
begin
apply stream.ext, intro n,
cases n,
{refl},
{rw [nth_inits, nth_succ, tail_cons, nth_map, nth_inits], refl}
end
theorem zip_inits_tails (s : stream α) : zip append_stream (inits s) (tails s) = const s :=
begin
apply stream.ext, intro n,
rw [nth_zip, nth_inits, nth_tails, nth_const, approx_succ,
cons_append_stream, append_approx_drop, stream.eta]
end
def pure (a : α) : stream α :=
const a
def apply (f : stream (α → β)) (s : stream α) : stream β :=
λ n, (nth n f) (nth n s)
infix `⊛`:75 := apply -- input as \o*
theorem identity (s : stream α) : pure id ⊛ s = s := rfl
theorem composition (g : stream (β → δ)) (f : stream (α → β)) (s : stream α) : pure comp ⊛ g ⊛ f ⊛ s = g ⊛ (f ⊛ s) := rfl
theorem homomorphism (f : α → β) (a : α) : pure f ⊛ pure a = pure (f a) := rfl
theorem interchange (fs : stream (α → β)) (a : α) : fs ⊛ pure a = pure (λ f : α → β, f a) ⊛ fs := rfl
theorem map_eq_apply (f : α → β) (s : stream α) : map f s = pure f ⊛ s := rfl
def nats : stream nat :=
λ n, n
theorem nth_nats (n : nat) : nth n nats = n := rfl
theorem nats_eq : nats = 0 :: map succ nats :=
begin
apply stream.ext, intro n,
cases n, refl, rw [nth_succ], refl
end
end stream
|
a0e169a74258897086b1196ffd877d76e1e2adb7 | 4950bf76e5ae40ba9f8491647d0b6f228ddce173 | /src/measure_theory/integration.lean | a6f6d3a1da32a91b886f08f1ec65db1d17c461f2 | [
"Apache-2.0"
] | permissive | ntzwq/mathlib | ca50b21079b0a7c6781c34b62199a396dd00cee2 | 36eec1a98f22df82eaccd354a758ef8576af2a7f | refs/heads/master | 1,675,193,391,478 | 1,607,822,996,000 | 1,607,822,996,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 71,948 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johannes Hölzl
-/
import measure_theory.measure_space
import measure_theory.borel_space
import data.indicator_function
import data.support
/-!
# Lebesgue integral for `ennreal`-valued functions
We define simple functions and show that each Borel measurable function on `ennreal` can be
approximated by a sequence of simple functions.
To prove something for an arbitrary measurable function into `ennreal`, the theorem
`measurable.ennreal_induction` shows that is it sufficient to show that the property holds for
(multiples of) characteristic functions and is closed under addition and supremum of increasing
sequences of functions.
## Notation
We introduce the following notation for the lower Lebesgue integral of a function `f : α → ennreal`.
* `∫⁻ x, f x ∂μ`: integral of a function `f : α → ennreal` with respect to a measure `μ`;
* `∫⁻ x, f x`: integral of a function `f : α → ennreal` with respect to the canonical measure
`volume` on `α`;
* `∫⁻ x in s, f x ∂μ`: integral of a function `f : α → ennreal` over a set `s` with respect
to a measure `μ`, defined as `∫⁻ x, f x ∂(μ.restrict s)`;
* `∫⁻ x in s, f x`: integral of a function `f : α → ennreal` over a set `s` with respect
to the canonical measure `volume`, defined as `∫⁻ x, f x ∂(volume.restrict s)`.
-/
noncomputable theory
open set (hiding restrict restrict_apply) filter ennreal
open_locale classical topological_space big_operators nnreal
namespace measure_theory
variables {α β γ δ : Type*}
/-- A function `f` from a measurable space to any type is called *simple*,
if every preimage `f ⁻¹' {x}` is measurable, and the range is finite. This structure bundles
a function with these properties. -/
structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) :=
(to_fun : α → β)
(is_measurable_fiber' : ∀ x, is_measurable (to_fun ⁻¹' {x}))
(finite_range' : (set.range to_fun).finite)
local infixr ` →ₛ `:25 := simple_func
namespace simple_func
section measurable
variables [measurable_space α]
instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) := ⟨_, to_fun⟩
lemma coe_injective ⦃f g : α →ₛ β⦄ (H : ⇑f = g) : f = g :=
by cases f; cases g; congr; exact H
@[ext] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g :=
coe_injective $ funext H
lemma finite_range (f : α →ₛ β) : (set.range f).finite := f.finite_range'
lemma is_measurable_fiber (f : α →ₛ β) (x : β) : is_measurable (f ⁻¹' {x}) :=
f.is_measurable_fiber' x
/-- Range of a simple function `α →ₛ β` as a `finset β`. -/
protected def range (f : α →ₛ β) : finset β := f.finite_range.to_finset
@[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ b ∈ range f :=
finite.mem_to_finset
theorem mem_range_self (f : α →ₛ β) (x : α) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩
@[simp] lemma coe_range (f : α →ₛ β) : (↑f.range : set β) = set.range f :=
f.finite_range.coe_to_finset
theorem mem_range_of_measure_ne_zero {f : α →ₛ β} {x : β} {μ : measure α} (H : μ (f ⁻¹' {x}) ≠ 0) :
x ∈ f.range :=
let ⟨a, ha⟩ := nonempty_of_measure_ne_zero H in
mem_range.2 ⟨a, ha⟩
lemma forall_range_iff {f : α →ₛ β} {p : β → Prop} :
(∀ y ∈ f.range, p y) ↔ ∀ x, p (f x) :=
by simp only [mem_range, set.forall_range_iff]
lemma exists_range_iff {f : α →ₛ β} {p : β → Prop} :
(∃ y ∈ f.range, p y) ↔ ∃ x, p (f x) :=
by simpa only [mem_range, exists_prop] using set.exists_range_iff
lemma preimage_eq_empty_iff (f : α →ₛ β) (b : β) : f ⁻¹' {b} = ∅ ↔ b ∉ f.range :=
preimage_singleton_eq_empty.trans $ not_congr mem_range.symm
/-- Constant function as a `simple_func`. -/
def const (α) {β} [measurable_space α] (b : β) : α →ₛ β :=
⟨λ a, b, λ x, is_measurable.const _, finite_range_const⟩
instance [inhabited β] : inhabited (α →ₛ β) := ⟨const _ (default _)⟩
theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl
@[simp] theorem coe_const (b : β) : ⇑(const α b) = function.const α b := rfl
@[simp] lemma range_const (α) [measurable_space α] [nonempty α] (b : β) :
(const α b).range = {b} :=
finset.coe_injective $ by simp
lemma is_measurable_cut (r : α → β → Prop) (f : α →ₛ β)
(h : ∀b, is_measurable {a | r a b}) : is_measurable {a | r a (f a)} :=
begin
have : {a | r a (f a)} = ⋃ b ∈ range f, {a | r a b} ∩ f ⁻¹' {b},
{ ext a,
suffices : r a (f a) ↔ ∃ i, r a (f i) ∧ f a = f i, by simpa,
exact ⟨λ h, ⟨a, ⟨h, rfl⟩⟩, λ ⟨a', ⟨h', e⟩⟩, e.symm ▸ h'⟩ },
rw this,
exact is_measurable.bUnion f.finite_range.countable
(λ b _, is_measurable.inter (h b) (f.is_measurable_fiber _))
end
theorem is_measurable_preimage (f : α →ₛ β) (s) : is_measurable (f ⁻¹' s) :=
is_measurable_cut (λ _ b, b ∈ s) f (λ b, is_measurable.const (b ∈ s))
/-- A simple function is measurable -/
protected theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f :=
λ s _, is_measurable_preimage f s
protected lemma sum_measure_preimage_singleton (f : α →ₛ β) {μ : measure α} (s : finset β) :
∑ y in s, μ (f ⁻¹' {y}) = μ (f ⁻¹' ↑s) :=
sum_measure_preimage_singleton _ (λ _ _, f.is_measurable_fiber _)
lemma sum_range_measure_preimage_singleton (f : α →ₛ β) (μ : measure α) :
∑ y in f.range, μ (f ⁻¹' {y}) = μ univ :=
by rw [f.sum_measure_preimage_singleton, coe_range, preimage_range]
/-- If-then-else as a `simple_func`. -/
def piecewise (s : set α) (hs : is_measurable s) (f g : α →ₛ β) : α →ₛ β :=
⟨s.piecewise f g,
λ x, by letI : measurable_space β := ⊤; exact
f.measurable.piecewise hs g.measurable trivial,
(f.finite_range.union g.finite_range).subset range_ite_subset⟩
@[simp] theorem coe_piecewise {s : set α} (hs : is_measurable s) (f g : α →ₛ β) :
⇑(piecewise s hs f g) = s.piecewise f g :=
rfl
theorem piecewise_apply {s : set α} (hs : is_measurable s) (f g : α →ₛ β) (a) :
piecewise s hs f g a = if a ∈ s then f a else g a :=
rfl
@[simp] lemma piecewise_compl {s : set α} (hs : is_measurable sᶜ) (f g : α →ₛ β) :
piecewise sᶜ hs f g = piecewise s hs.of_compl g f :=
coe_injective $ by simp [hs]
@[simp] lemma piecewise_univ (f g : α →ₛ β) : piecewise univ is_measurable.univ f g = f :=
coe_injective $ by simp
@[simp] lemma piecewise_empty (f g : α →ₛ β) : piecewise ∅ is_measurable.empty f g = g :=
coe_injective $ by simp
lemma measurable_bind [measurable_space γ] (f : α →ₛ β) (g : β → α → γ)
(hg : ∀ b, measurable (g b)) : measurable (λ a, g (f a) a) :=
λ s hs, f.is_measurable_cut (λ a b, g b a ∈ s) $ λ b, hg b hs
/-- If `f : α →ₛ β` is a simple function and `g : β → α →ₛ γ` is a family of simple functions,
then `f.bind g` binds the first argument of `g` to `f`. In other words, `f.bind g a = g (f a) a`. -/
def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ :=
⟨λa, g (f a) a,
λ c, f.is_measurable_cut (λ a b, g b a = c) $ λ b, (g b).is_measurable_preimage {c},
(f.finite_range.bUnion (λ b _, (g b).finite_range)).subset $
by rintro _ ⟨a, rfl⟩; simp; exact ⟨a, a, rfl⟩⟩
@[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) :
f.bind g a = g (f a) a := rfl
/-- Given a function `g : β → γ` and a simple function `f : α →ₛ β`, `f.map g` return the simple
function `g ∘ f : α →ₛ γ` -/
def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g)
theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl
theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl
@[simp] theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl
@[simp] theorem range_map [decidable_eq γ] (g : β → γ) (f : α →ₛ β) :
(f.map g).range = f.range.image g :=
finset.coe_injective $ by simp [range_comp]
@[simp] theorem map_const (g : β → γ) (b : β) : (const α b).map g = const α (g b) := rfl
lemma map_preimage (f : α →ₛ β) (g : β → γ) (s : set γ) :
(f.map g) ⁻¹' s = f ⁻¹' ↑(f.range.filter (λb, g b ∈ s)) :=
by { simp only [coe_range, sep_mem_eq, set.mem_range, function.comp_app, coe_map, finset.coe_filter,
← mem_preimage, inter_comm, preimage_inter_range], apply preimage_comp }
lemma map_preimage_singleton (f : α →ₛ β) (g : β → γ) (c : γ) :
(f.map g) ⁻¹' {c} = f ⁻¹' ↑(f.range.filter (λ b, g b = c)) :=
map_preimage _ _ _
/-- Composition of a `simple_fun` and a measurable function is a `simple_func`. -/
def comp [measurable_space β] (f : β →ₛ γ) (g : α → β) (hgm : measurable g) : α →ₛ γ :=
{ to_fun := f ∘ g,
finite_range' := f.finite_range.subset $ set.range_comp_subset_range _ _,
is_measurable_fiber' := λ z, hgm (f.is_measurable_fiber z) }
@[simp] lemma coe_comp [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) :
⇑(f.comp g hgm) = f ∘ g :=
rfl
lemma range_comp_subset_range [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) :
(f.comp g hgm).range ⊆ f.range :=
finset.coe_subset.1 $ by simp only [coe_range, coe_comp, set.range_comp_subset_range]
/-- If `f` is a simple function taking values in `β → γ` and `g` is another simple function
with the same domain and codomain `β`, then `f.seq g = f a (g a)`. -/
def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f)
@[simp] lemma seq_apply (f : α →ₛ (β → γ)) (g : α →ₛ β) (a : α) : f.seq g a = f a (g a) := rfl
/-- Combine two simple functions `f : α →ₛ β` and `g : α →ₛ β`
into `λ a, (f a, g a)`. -/
def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g
@[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl
lemma pair_preimage (f : α →ₛ β) (g : α →ₛ γ) (s : set β) (t : set γ) :
(pair f g) ⁻¹' (set.prod s t) = (f ⁻¹' s) ∩ (g ⁻¹' t) := rfl
/- A special form of `pair_preimage` -/
lemma pair_preimage_singleton (f : α →ₛ β) (g : α →ₛ γ) (b : β) (c : γ) :
(pair f g) ⁻¹' {(b, c)} = (f ⁻¹' {b}) ∩ (g ⁻¹' {c}) :=
by { rw ← singleton_prod_singleton, exact pair_preimage _ _ _ _ }
theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp
instance [has_zero β] : has_zero (α →ₛ β) := ⟨const α 0⟩
instance [has_add β] : has_add (α →ₛ β) := ⟨λf g, (f.map (+)).seq g⟩
instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩
instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩
instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩
instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩
@[simp, norm_cast] lemma coe_zero [has_zero β] : ⇑(0 : α →ₛ β) = 0 := rfl
@[simp] lemma const_zero [has_zero β] : const α (0:β) = 0 := rfl
@[simp, norm_cast] lemma coe_add [has_add β] (f g : α →ₛ β) : ⇑(f + g) = f + g := rfl
@[simp, norm_cast] lemma coe_mul [has_mul β] (f g : α →ₛ β) : ⇑(f * g) = f * g := rfl
@[simp, norm_cast] lemma coe_le [preorder β] {f g : α →ₛ β} : (f : α → β) ≤ g ↔ f ≤ g := iff.rfl
@[simp] lemma range_zero [nonempty α] [has_zero β] : (0 : α →ₛ β).range = {0} :=
finset.ext $ λ x, by simp [eq_comm]
lemma eq_zero_of_mem_range_zero [has_zero β] : ∀ {y : β}, y ∈ (0 : α →ₛ β).range → y = 0 :=
forall_range_iff.2 $ λ x, rfl
lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl
lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl
lemma add_apply [has_add β] (f g : α →ₛ β) (a : α) : (f + g) a = f a + g a := rfl
lemma add_eq_map₂ [has_add β] (f g : α →ₛ β) : f + g = (pair f g).map (λp:β×β, p.1 + p.2) :=
rfl
lemma mul_eq_map₂ [has_mul β] (f g : α →ₛ β) : f * g = (pair f g).map (λp:β×β, p.1 * p.2) :=
rfl
lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) :=
rfl
lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl
instance [add_monoid β] : add_monoid (α →ₛ β) :=
function.injective.add_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add
instance add_comm_monoid [add_comm_monoid β] : add_comm_monoid (α →ₛ β) :=
function.injective.add_comm_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add
instance [has_neg β] : has_neg (α →ₛ β) := ⟨λf, f.map (has_neg.neg)⟩
@[simp, norm_cast] lemma coe_neg [has_neg β] (f : α →ₛ β) : ⇑(-f) = -f := rfl
instance [add_group β] : add_group (α →ₛ β) :=
function.injective.add_group (λ f, show α → β, from f) coe_injective coe_zero coe_add coe_neg
@[simp, norm_cast] lemma coe_sub [add_group β] (f g : α →ₛ β) : ⇑(f - g) = f - g := rfl
instance [add_comm_group β] : add_comm_group (α →ₛ β) :=
function.injective.add_comm_group (λ f, show α → β, from f) coe_injective
coe_zero coe_add coe_neg
variables {K : Type*}
instance [has_scalar K β] : has_scalar K (α →ₛ β) := ⟨λk f, f.map ((•) k)⟩
@[simp] lemma coe_smul [has_scalar K β] (c : K) (f : α →ₛ β) : ⇑(c • f) = c • f := rfl
lemma smul_apply [has_scalar K β] (k : K) (f : α →ₛ β) (a : α) : (k • f) a = k • f a := rfl
instance [semiring K] [add_comm_monoid β] [semimodule K β] : semimodule K (α →ₛ β) :=
function.injective.semimodule K ⟨λ f, show α → β, from f, coe_zero, coe_add⟩
coe_injective coe_smul
lemma smul_eq_map [has_scalar K β] (k : K) (f : α →ₛ β) : k • f = f.map ((•) k) := rfl
instance [preorder β] : preorder (α →ₛ β) :=
{ le_refl := λf a, le_refl _,
le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a),
.. simple_func.has_le }
instance [partial_order β] : partial_order (α →ₛ β) :=
{ le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a),
.. simple_func.preorder }
instance [order_bot β] : order_bot (α →ₛ β) :=
{ bot := const α ⊥, bot_le := λf a, bot_le, .. simple_func.partial_order }
instance [order_top β] : order_top (α →ₛ β) :=
{ top := const α ⊤, le_top := λf a, le_top, .. simple_func.partial_order }
instance [semilattice_inf β] : semilattice_inf (α →ₛ β) :=
{ inf := (⊓),
inf_le_left := assume f g a, inf_le_left,
inf_le_right := assume f g a, inf_le_right,
le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a),
.. simple_func.partial_order }
instance [semilattice_sup β] : semilattice_sup (α →ₛ β) :=
{ sup := (⊔),
le_sup_left := assume f g a, le_sup_left,
le_sup_right := assume f g a, le_sup_right,
sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a),
.. simple_func.partial_order }
instance [semilattice_sup_bot β] : semilattice_sup_bot (α →ₛ β) :=
{ .. simple_func.semilattice_sup,.. simple_func.order_bot }
instance [lattice β] : lattice (α →ₛ β) :=
{ .. simple_func.semilattice_sup,.. simple_func.semilattice_inf }
instance [bounded_lattice β] : bounded_lattice (α →ₛ β) :=
{ .. simple_func.lattice, .. simple_func.order_bot, .. simple_func.order_top }
lemma finset_sup_apply [semilattice_sup_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) :
s.sup f a = s.sup (λc, f c a) :=
begin
refine finset.induction_on s rfl _,
assume a s hs ih,
rw [finset.sup_insert, finset.sup_insert, sup_apply, ih]
end
section restrict
variables [has_zero β]
/-- Restrict a simple function `f : α →ₛ β` to a set `s`. If `s` is measurable,
then `f.restrict s a = if a ∈ s then f a else 0`, otherwise `f.restrict s = const α 0`. -/
def restrict (f : α →ₛ β) (s : set α) : α →ₛ β :=
if hs : is_measurable s then piecewise s hs f 0 else 0
theorem restrict_of_not_measurable {f : α →ₛ β} {s : set α}
(hs : ¬is_measurable s) :
restrict f s = 0 :=
dif_neg hs
@[simp] theorem coe_restrict (f : α →ₛ β) {s : set α} (hs : is_measurable s) :
⇑(restrict f s) = indicator s f :=
by { rw [restrict, dif_pos hs], refl }
@[simp] theorem restrict_univ (f : α →ₛ β) : restrict f univ = f :=
by simp [restrict]
@[simp] theorem restrict_empty (f : α →ₛ β) : restrict f ∅ = 0 :=
by simp [restrict]
theorem map_restrict_of_zero [has_zero γ] {g : β → γ} (hg : g 0 = 0) (f : α →ₛ β) (s : set α) :
(f.restrict s).map g = (f.map g).restrict s :=
ext $ λ x,
if hs : is_measurable s then by simp [hs, set.indicator_comp_of_zero hg]
else by simp [restrict_of_not_measurable hs, hg]
theorem map_coe_ennreal_restrict (f : α →ₛ nnreal) (s : set α) :
(f.restrict s).map (coe : nnreal → ennreal) = (f.map coe).restrict s :=
map_restrict_of_zero ennreal.coe_zero _ _
theorem map_coe_nnreal_restrict (f : α →ₛ nnreal) (s : set α) :
(f.restrict s).map (coe : nnreal → ℝ) = (f.map coe).restrict s :=
map_restrict_of_zero nnreal.coe_zero _ _
theorem restrict_apply (f : α →ₛ β) {s : set α} (hs : is_measurable s) (a) :
restrict f s a = if a ∈ s then f a else 0 :=
by simp only [hs, coe_restrict]
theorem restrict_preimage (f : α →ₛ β) {s : set α} (hs : is_measurable s)
{t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t :=
by simp [hs, indicator_preimage_of_not_mem _ _ ht]
theorem restrict_preimage_singleton (f : α →ₛ β) {s : set α} (hs : is_measurable s)
{r : β} (hr : r ≠ 0) : restrict f s ⁻¹' {r} = s ∩ f ⁻¹' {r} :=
f.restrict_preimage hs hr.symm
lemma mem_restrict_range {r : β} {s : set α} {f : α →ₛ β} (hs : is_measurable s) :
r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (r ∈ f '' s) :=
by rw [← finset.mem_coe, coe_range, coe_restrict _ hs, mem_range_indicator]
lemma mem_image_of_mem_range_restrict {r : β} {s : set α} {f : α →ₛ β}
(hr : r ∈ (restrict f s).range) (h0 : r ≠ 0) :
r ∈ f '' s :=
if hs : is_measurable s then by simpa [mem_restrict_range hs, h0] using hr
else by { rw [restrict_of_not_measurable hs] at hr,
exact (h0 $ eq_zero_of_mem_range_zero hr).elim }
@[mono] lemma restrict_mono [preorder β] (s : set α) {f g : α →ₛ β} (H : f ≤ g) :
f.restrict s ≤ g.restrict s :=
if hs : is_measurable s then λ x, by simp only [coe_restrict _ hs, indicator_le_indicator (H x)]
else by simp only [restrict_of_not_measurable hs, le_refl]
end restrict
section approx
section
variables [semilattice_sup_bot β] [has_zero β]
/-- Fix a sequence `i : ℕ → β`. Given a function `α → β`, its `n`-th approximation
by simple functions is defined so that in case `β = ennreal` it sends each `a` to the supremum
of the set `{i k | k ≤ n ∧ i k ≤ f a}`, see `approx_apply` and `supr_approx_apply` for details. -/
def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β :=
(finset.range n).sup (λk, restrict (const α (i k)) {a:α | i k ≤ f a})
lemma approx_apply [topological_space β] [order_closed_topology β] [measurable_space β]
[opens_measurable_space β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : measurable f) :
(approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) :=
begin
dsimp only [approx],
rw [finset_sup_apply],
congr,
funext k,
rw [restrict_apply],
refl,
exact (hf is_measurable_Ici)
end
lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) :=
assume n m h, finset.sup_mono $ finset.range_subset.2 h
lemma approx_comp [topological_space β] [order_closed_topology β] [measurable_space β]
[opens_measurable_space β] [measurable_space γ]
{i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α)
(hf : measurable f) (hg : measurable g) :
(approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) :=
by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)]
end
lemma supr_approx_apply [topological_space β] [complete_lattice β] [order_closed_topology β]
[has_zero β] [measurable_space β] [opens_measurable_space β]
(i : ℕ → β) (f : α → β) (a : α) (hf : measurable f) (h_zero : (0 : β) = ⊥) :
(⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) :=
begin
refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _),
{ rw [approx_apply a hf, h_zero],
refine finset.sup_le (assume k hk, _),
split_ifs,
exact le_supr_of_le k (le_supr _ h),
exact bot_le },
{ refine le_supr_of_le (k+1) _,
rw [approx_apply a hf],
have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _),
refine le_trans (le_of_eq _) (finset.le_sup this),
rw [if_pos hk] }
end
end approx
section eapprox
/-- A sequence of `ennreal`s such that its range is the set of non-negative rational numbers. -/
def ennreal_rat_embed (n : ℕ) : ennreal :=
ennreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ))
lemma ennreal_rat_embed_encode (q : ℚ) :
ennreal_rat_embed (encodable.encode q) = nnreal.of_real q :=
by rw [ennreal_rat_embed, encodable.encodek]; refl
/-- Approximate a function `α → ennreal` by a sequence of simple functions. -/
def eapprox : (α → ennreal) → ℕ → α →ₛ ennreal :=
approx ennreal_rat_embed
lemma monotone_eapprox (f : α → ennreal) : monotone (eapprox f) :=
monotone_approx _ f
lemma supr_eapprox_apply (f : α → ennreal) (hf : measurable f) (a : α) :
(⨆n, (eapprox f n : α →ₛ ennreal) a) = f a :=
begin
rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl],
refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _),
assume h,
rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩,
have : (nnreal.of_real q : ennreal) ≤
(⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k),
{ refine le_supr_of_le (encodable.encode q) _,
rw [ennreal_rat_embed_encode q],
refine le_supr_of_le (le_of_lt q_lt) _,
exact le_refl _ },
exact lt_irrefl _ (lt_of_le_of_lt this lt_q)
end
lemma eapprox_comp [measurable_space γ] {f : γ → ennreal} {g : α → γ} {n : ℕ}
(hf : measurable f) (hg : measurable g) :
(eapprox (f ∘ g) n : α → ennreal) = (eapprox f n : γ →ₛ ennreal) ∘ g :=
funext $ assume a, approx_comp a hf hg
end eapprox
end measurable
section measure
variables [measurable_space α] {μ : measure α}
/-- Integral of a simple function whose codomain is `ennreal`. -/
def lintegral (f : α →ₛ ennreal) (μ : measure α) : ennreal :=
∑ x in f.range, x * μ (f ⁻¹' {x})
lemma lintegral_eq_of_subset (f : α →ₛ ennreal) {s : finset ennreal}
(hs : ∀ x, f x ≠ 0 → μ (f ⁻¹' {f x}) ≠ 0 → f x ∈ s) :
f.lintegral μ = ∑ x in s, x * μ (f ⁻¹' {x}) :=
begin
refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _,
{ simpa only [forall_range_iff, mul_ne_zero_iff, and_imp] },
{ intros, assumption },
{ intros b _ hb,
refine ⟨b, _, hb, rfl⟩,
rw [mem_range, ← preimage_singleton_nonempty],
exact nonempty_of_measure_ne_zero (mul_ne_zero_iff.1 hb).2 },
{ intros, refl }
end
/-- Calculate the integral of `(g ∘ f)`, where `g : β → ennreal` and `f : α →ₛ β`. -/
lemma map_lintegral (g : β → ennreal) (f : α →ₛ β) :
(f.map g).lintegral μ = ∑ x in f.range, g x * μ (f ⁻¹' {x}) :=
begin
simp only [lintegral, range_map],
refine finset.sum_image' _ (assume b hb, _),
rcases mem_range.1 hb with ⟨a, rfl⟩,
rw [map_preimage_singleton, ← f.sum_measure_preimage_singleton, finset.mul_sum],
refine finset.sum_congr _ _,
{ congr },
{ assume x, simp only [finset.mem_filter], rintro ⟨_, h⟩, rw h },
end
lemma add_lintegral (f g : α →ₛ ennreal) : (f + g).lintegral μ = f.lintegral μ + g.lintegral μ :=
calc (f + g).lintegral μ =
∑ x in (pair f g).range, (x.1 * μ (pair f g ⁻¹' {x}) + x.2 * μ (pair f g ⁻¹' {x})) :
by rw [add_eq_map₂, map_lintegral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _)
... = ∑ x in (pair f g).range, x.1 * μ (pair f g ⁻¹' {x}) +
∑ x in (pair f g).range, x.2 * μ (pair f g ⁻¹' {x}) : by rw [finset.sum_add_distrib]
... = ((pair f g).map prod.fst).lintegral μ + ((pair f g).map prod.snd).lintegral μ :
by rw [map_lintegral, map_lintegral]
... = lintegral f μ + lintegral g μ : rfl
lemma const_mul_lintegral (f : α →ₛ ennreal) (x : ennreal) :
(const α x * f).lintegral μ = x * f.lintegral μ :=
calc (f.map (λa, x * a)).lintegral μ = ∑ r in f.range, x * r * μ (f ⁻¹' {r}) :
map_lintegral _ _
... = ∑ r in f.range, x * (r * μ (f ⁻¹' {r})) :
finset.sum_congr rfl (assume a ha, mul_assoc _ _ _)
... = x * f.lintegral μ :
finset.mul_sum.symm
/-- Integral of a simple function `α →ₛ ennreal` as a bilinear map. -/
def lintegralₗ : (α →ₛ ennreal) →ₗ[ennreal] measure α →ₗ[ennreal] ennreal :=
{ to_fun := λ f,
{ to_fun := lintegral f,
map_add' := by simp [lintegral, mul_add, finset.sum_add_distrib],
map_smul' := λ c μ, by simp [lintegral, mul_left_comm _ c, finset.mul_sum] },
map_add' := λ f g, linear_map.ext (λ μ, add_lintegral f g),
map_smul' := λ c f, linear_map.ext (λ μ, const_mul_lintegral f c) }
@[simp] lemma zero_lintegral : (0 : α →ₛ ennreal).lintegral μ = 0 :=
linear_map.ext_iff.1 lintegralₗ.map_zero μ
lemma lintegral_add {ν} (f : α →ₛ ennreal) : f.lintegral (μ + ν) = f.lintegral μ + f.lintegral ν :=
(lintegralₗ f).map_add μ ν
lemma lintegral_smul (f : α →ₛ ennreal) (c : ennreal) :
f.lintegral (c • μ) = c • f.lintegral μ :=
(lintegralₗ f).map_smul c μ
@[simp] lemma lintegral_zero (f : α →ₛ ennreal) :
f.lintegral 0 = 0 :=
(lintegralₗ f).map_zero
lemma lintegral_sum {ι} (f : α →ₛ ennreal) (μ : ι → measure α) :
f.lintegral (measure.sum μ) = ∑' i, f.lintegral (μ i) :=
begin
simp only [lintegral, measure.sum_apply, f.is_measurable_preimage, ← finset.tsum_subtype,
← ennreal.tsum_mul_left],
apply ennreal.tsum_comm
end
lemma restrict_lintegral (f : α →ₛ ennreal) {s : set α} (hs : is_measurable s) :
(restrict f s).lintegral μ = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) :=
calc (restrict f s).lintegral μ = ∑ r in f.range, r * μ (restrict f s ⁻¹' {r}) :
lintegral_eq_of_subset _ $ λ x hx, if hxs : x ∈ s
then by simp [f.restrict_apply hs, if_pos hxs, mem_range_self]
else false.elim $ hx $ by simp [*]
... = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) :
finset.sum_congr rfl $ forall_range_iff.2 $ λ b, if hb : f b = 0 then by simp only [hb, zero_mul]
else by rw [restrict_preimage_singleton _ hs hb, inter_comm]
lemma lintegral_restrict (f : α →ₛ ennreal) (s : set α) (μ : measure α) :
f.lintegral (μ.restrict s) = ∑ y in f.range, y * μ (f ⁻¹' {y} ∩ s) :=
by simp only [lintegral, measure.restrict_apply, f.is_measurable_preimage]
lemma restrict_lintegral_eq_lintegral_restrict (f : α →ₛ ennreal) {s : set α}
(hs : is_measurable s) :
(restrict f s).lintegral μ = f.lintegral (μ.restrict s) :=
by rw [f.restrict_lintegral hs, lintegral_restrict]
lemma const_lintegral (c : ennreal) : (const α c).lintegral μ = c * μ univ :=
begin
rw [lintegral],
by_cases ha : nonempty α,
{ resetI, simp [preimage_const_of_mem] },
{ simp [μ.eq_zero_of_not_nonempty ha] }
end
lemma const_lintegral_restrict (c : ennreal) (s : set α) :
(const α c).lintegral (μ.restrict s) = c * μ s :=
by rw [const_lintegral, measure.restrict_apply is_measurable.univ, univ_inter]
lemma restrict_const_lintegral (c : ennreal) {s : set α} (hs : is_measurable s) :
((const α c).restrict s).lintegral μ = c * μ s :=
by rw [restrict_lintegral_eq_lintegral_restrict _ hs, const_lintegral_restrict]
lemma le_sup_lintegral (f g : α →ₛ ennreal) : f.lintegral μ ⊔ g.lintegral μ ≤ (f ⊔ g).lintegral μ :=
calc f.lintegral μ ⊔ g.lintegral μ =
((pair f g).map prod.fst).lintegral μ ⊔ ((pair f g).map prod.snd).lintegral μ : rfl
... ≤ ∑ x in (pair f g).range, (x.1 ⊔ x.2) * μ (pair f g ⁻¹' {x}) :
begin
rw [map_lintegral, map_lintegral],
refine sup_le _ _;
refine finset.sum_le_sum (λ a _, canonically_ordered_semiring.mul_le_mul _ (le_refl _)),
exact le_sup_left,
exact le_sup_right
end
... = (f ⊔ g).lintegral μ : by rw [sup_eq_map₂, map_lintegral]
/-- `simple_func.lintegral` is monotone both in function and in measure. -/
@[mono] lemma lintegral_mono {f g : α →ₛ ennreal} (hfg : f ≤ g) {μ ν : measure α} (hμν : μ ≤ ν) :
f.lintegral μ ≤ g.lintegral ν :=
calc f.lintegral μ ≤ f.lintegral μ ⊔ g.lintegral μ : le_sup_left
... ≤ (f ⊔ g).lintegral μ : le_sup_lintegral _ _
... = g.lintegral μ : by rw [sup_of_le_right hfg]
... ≤ g.lintegral ν : finset.sum_le_sum $ λ y hy, ennreal.mul_left_mono $
hμν _ (g.is_measurable_preimage _)
/-- `simple_func.lintegral` depends only on the measures of `f ⁻¹' {y}`. -/
lemma lintegral_eq_of_measure_preimage [measurable_space β] {f : α →ₛ ennreal} {g : β →ₛ ennreal}
{ν : measure β} (H : ∀ y, μ (f ⁻¹' {y}) = ν (g ⁻¹' {y})) :
f.lintegral μ = g.lintegral ν :=
begin
simp only [lintegral, ← H],
apply lintegral_eq_of_subset,
simp only [H],
intros,
exact mem_range_of_measure_ne_zero ‹_›
end
/-- If two simple functions are equal a.e., then their `lintegral`s are equal. -/
lemma lintegral_congr {f g : α →ₛ ennreal} (h : f =ᵐ[μ] g) :
f.lintegral μ = g.lintegral μ :=
lintegral_eq_of_measure_preimage $ λ y, measure_congr $
eventually.set_eq $ h.mono $ λ x hx, by simp [hx]
lemma lintegral_map {β} [measurable_space β] {μ' : measure β} (f : α →ₛ ennreal) (g : β →ₛ ennreal)
(m : α → β) (eq : ∀a:α, f a = g (m a)) (h : ∀s:set β, is_measurable s → μ' s = μ (m ⁻¹' s)) :
f.lintegral μ = g.lintegral μ' :=
lintegral_eq_of_measure_preimage $ λ y,
by { simp only [preimage, eq], exact (h (g ⁻¹' {y}) (g.is_measurable_preimage _)).symm }
end measure
section fin_meas_supp
variables [measurable_space α] [has_zero β] [has_zero γ] {μ : measure α}
open finset ennreal function
lemma support_eq (f : α →ₛ β) : support f = ⋃ y ∈ f.range.filter (λ y, y ≠ 0), f ⁻¹' {y} :=
set.ext $ λ x, by simp only [finset.bUnion_preimage_singleton, mem_support, set.mem_preimage,
finset.mem_coe, mem_filter, mem_range_self, true_and]
/-- A `simple_func` has finite measure support if it is equal to `0` outside of a set of finite
measure. -/
protected def fin_meas_supp (f : α →ₛ β) (μ : measure α) : Prop :=
f =ᶠ[μ.cofinite] 0
lemma fin_meas_supp_iff_support {f : α →ₛ β} {μ : measure α} :
f.fin_meas_supp μ ↔ μ (support f) < ⊤ :=
iff.rfl
lemma fin_meas_supp_iff {f : α →ₛ β} {μ : measure α} :
f.fin_meas_supp μ ↔ ∀ y ≠ 0, μ (f ⁻¹' {y}) < ⊤ :=
begin
split,
{ refine λ h y hy, lt_of_le_of_lt (measure_mono _) h,
exact λ x hx (H : f x = 0), hy $ H ▸ eq.symm hx },
{ intro H,
rw [fin_meas_supp_iff_support, support_eq],
refine lt_of_le_of_lt (measure_bUnion_finset_le _ _) (sum_lt_top _),
exact λ y hy, H y (finset.mem_filter.1 hy).2 }
end
namespace fin_meas_supp
lemma meas_preimage_singleton_ne_zero {f : α →ₛ β} (h : f.fin_meas_supp μ) {y : β} (hy : y ≠ 0) :
μ (f ⁻¹' {y}) < ⊤ :=
fin_meas_supp_iff.1 h y hy
protected lemma map {f : α →ₛ β} {g : β → γ} (hf : f.fin_meas_supp μ) (hg : g 0 = 0) :
(f.map g).fin_meas_supp μ :=
flip lt_of_le_of_lt hf (measure_mono $ support_comp_subset hg f)
lemma of_map {f : α →ₛ β} {g : β → γ} (h : (f.map g).fin_meas_supp μ) (hg : ∀b, g b = 0 → b = 0) :
f.fin_meas_supp μ :=
flip lt_of_le_of_lt h $ measure_mono $ support_subset_comp hg _
lemma map_iff {f : α →ₛ β} {g : β → γ} (hg : ∀ {b}, g b = 0 ↔ b = 0) :
(f.map g).fin_meas_supp μ ↔ f.fin_meas_supp μ :=
⟨λ h, h.of_map $ λ b, hg.1, λ h, h.map $ hg.2 rfl⟩
protected lemma pair {f : α →ₛ β} {g : α →ₛ γ} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) :
(pair f g).fin_meas_supp μ :=
calc μ (support $ pair f g) = μ (support f ∪ support g) : congr_arg μ $ support_prod_mk f g
... ≤ μ (support f) + μ (support g) : measure_union_le _ _
... < _ : add_lt_top.2 ⟨hf, hg⟩
protected lemma map₂ [has_zero δ] {μ : measure α} {f : α →ₛ β} (hf : f.fin_meas_supp μ)
{g : α →ₛ γ} (hg : g.fin_meas_supp μ) {op : β → γ → δ} (H : op 0 0 = 0) :
((pair f g).map (function.uncurry op)).fin_meas_supp μ :=
(hf.pair hg).map H
protected lemma add {β} [add_monoid β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ)
(hg : g.fin_meas_supp μ) :
(f + g).fin_meas_supp μ :=
by { rw [add_eq_map₂], exact hf.map₂ hg (zero_add 0) }
protected lemma mul {β} [monoid_with_zero β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ)
(hg : g.fin_meas_supp μ) :
(f * g).fin_meas_supp μ :=
by { rw [mul_eq_map₂], exact hf.map₂ hg (zero_mul 0) }
lemma lintegral_lt_top {f : α →ₛ ennreal} (hm : f.fin_meas_supp μ) (hf : ∀ᵐ a ∂μ, f a < ⊤) :
f.lintegral μ < ⊤ :=
begin
refine sum_lt_top (λ a ha, _),
rcases eq_or_lt_of_le (le_top : a ≤ ⊤) with rfl|ha,
{ simp only [ae_iff, lt_top_iff_ne_top, ne.def, not_not] at hf,
simp [set.preimage, hf] },
{ by_cases ha0 : a = 0,
{ subst a, rwa [zero_mul] },
{ exact mul_lt_top ha (fin_meas_supp_iff.1 hm _ ha0) } }
end
lemma of_lintegral_lt_top {f : α →ₛ ennreal} (h : f.lintegral μ < ⊤) : f.fin_meas_supp μ :=
begin
refine fin_meas_supp_iff.2 (λ b hb, _),
rw [lintegral, sum_lt_top_iff] at h,
by_cases b_mem : b ∈ f.range,
{ rw ennreal.lt_top_iff_ne_top,
have h : ¬ _ = ⊤ := ennreal.lt_top_iff_ne_top.1 (h b b_mem),
simp only [mul_eq_top, not_or_distrib, not_and_distrib] at h,
rcases h with ⟨h, h'⟩,
refine or.elim h (λh, by contradiction) (λh, h) },
{ rw ← preimage_eq_empty_iff at b_mem,
rw [b_mem, measure_empty],
exact with_top.zero_lt_top }
end
lemma iff_lintegral_lt_top {f : α →ₛ ennreal} (hf : ∀ᵐ a ∂μ, f a < ⊤) :
f.fin_meas_supp μ ↔ f.lintegral μ < ⊤ :=
⟨λ h, h.lintegral_lt_top hf, λ h, of_lintegral_lt_top h⟩
end fin_meas_supp
end fin_meas_supp
/-- To prove something for an arbitrary simple function, it suffices to show
that the property holds for (multiples of) characteristic functions and is closed under
addition (of functions with disjoint support).
It is possible to make the hypotheses in `h_sum` a bit stronger, and such conditions can be added
once we need them (for example it is only necessary to consider the case where `g` is a multiple
of a characteristic function, and that this multiple doesn't appear in the image of `f`) -/
@[elab_as_eliminator]
protected lemma induction {α γ} [measurable_space α] [add_monoid γ] {P : simple_func α γ → Prop}
(h_ind : ∀ c {s} (hs : is_measurable s),
P (simple_func.piecewise s hs (simple_func.const _ c) (simple_func.const _ 0)))
(h_sum : ∀ ⦃f g : simple_func α γ⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → P f → P g → P (f + g))
(f : simple_func α γ) : P f :=
begin
generalize' h : f.range \ {0} = s,
rw [← finset.coe_inj, finset.coe_sdiff, finset.coe_singleton, simple_func.coe_range] at h,
revert s f h, refine finset.induction _ _,
{ intros f hf, rw [finset.coe_empty, diff_eq_empty, range_subset_singleton] at hf,
convert h_ind 0 is_measurable.univ, ext x, simp [hf] },
{ intros x s hxs ih f hf,
have mx := f.is_measurable_preimage {x},
let g := simple_func.piecewise (f ⁻¹' {x}) mx 0 f,
have Pg : P g,
{ apply ih, simp only [g, simple_func.coe_piecewise, range_piecewise],
rw [image_compl_preimage, union_diff_distrib, diff_diff_comm, hf, finset.coe_insert,
insert_diff_self_of_not_mem, diff_eq_empty.mpr, set.empty_union],
{ rw [set.image_subset_iff], convert set.subset_univ _,
exact preimage_const_of_mem (mem_singleton _) },
{ rwa [finset.mem_coe] }},
convert h_sum _ Pg (h_ind x mx),
{ ext1 y, by_cases hy : y ∈ f ⁻¹' {x}; [simpa [hy], simp [hy]] },
{ rintro y -, by_cases hy : y ∈ f ⁻¹' {x}; simp [hy] } }
end
end simple_func
section lintegral
open simple_func
variables [measurable_space α] {μ : measure α}
/-- The lower Lebesgue integral of a function `f` with respect to a measure `μ`. -/
def lintegral (μ : measure α) (f : α → ennreal) : ennreal :=
⨆ (g : α →ₛ ennreal) (hf : ⇑g ≤ f), g.lintegral μ
/-! In the notation for integrals, an expression like `∫⁻ x, g ∥x∥ ∂μ` will not be parsed correctly,
and needs parentheses. We do not set the binding power of `r` to `0`, because then
`∫⁻ x, f x = 0` will be parsed incorrectly. -/
notation `∫⁻` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral μ r
notation `∫⁻` binders `, ` r:(scoped:60 f, lintegral volume f) := r
notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 :=
lintegral (measure.restrict μ s) r
notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, lintegral (measure.restrict volume s) f) := r
theorem simple_func.lintegral_eq_lintegral (f : α →ₛ ennreal) (μ : measure α) :
∫⁻ a, f a ∂ μ = f.lintegral μ :=
le_antisymm
(bsupr_le $ λ g hg, lintegral_mono hg $ le_refl _)
(le_supr_of_le f $ le_supr_of_le (le_refl _) (le_refl _))
@[mono] lemma lintegral_mono' ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) ⦃f g : α → ennreal⦄ (hfg : f ≤ g) :
∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂ν :=
supr_le_supr $ λ φ, supr_le_supr2 $ λ hφ, ⟨le_trans hφ hfg, lintegral_mono (le_refl φ) hμν⟩
lemma lintegral_mono ⦃f g : α → ennreal⦄ (hfg : f ≤ g) :
∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ :=
lintegral_mono' (le_refl μ) hfg
lemma lintegral_mono_nnreal {f g : α → nnreal} (h : f ≤ g) :
∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ :=
begin
refine lintegral_mono _,
intro a,
rw ennreal.coe_le_coe,
exact h a,
end
lemma monotone_lintegral (μ : measure α) : monotone (lintegral μ) :=
lintegral_mono
@[simp] lemma lintegral_const (c : ennreal) : ∫⁻ a, c ∂μ = c * μ univ :=
by rw [← simple_func.const_lintegral, ← simple_func.lintegral_eq_lintegral, simple_func.coe_const]
lemma set_lintegral_one (s) : ∫⁻ a in s, 1 ∂μ = μ s :=
by rw [lintegral_const, one_mul, measure.restrict_apply_univ]
/-- `∫⁻ a in s, f a ∂μ` is defined as the supremum of integrals of simple functions
`φ : α →ₛ ennreal` such that `φ ≤ f`. This lemma says that it suffices to take
functions `φ : α →ₛ ℝ≥0`. -/
lemma lintegral_eq_nnreal (f : α → ennreal) (μ : measure α) :
(∫⁻ a, f a ∂μ) = (⨆ (φ : α →ₛ ℝ≥0) (hf : ∀ x, ↑(φ x) ≤ f x),
(φ.map (coe : nnreal → ennreal)).lintegral μ) :=
begin
refine le_antisymm
(bsupr_le $ assume φ hφ, _)
(supr_le_supr2 $ λ φ, ⟨φ.map (coe : ℝ≥0 → ennreal), le_refl _⟩),
by_cases h : ∀ᵐ a ∂μ, φ a ≠ ⊤,
{ let ψ := φ.map ennreal.to_nnreal,
replace h : ψ.map (coe : ℝ≥0 → ennreal) =ᵐ[μ] φ :=
h.mono (λ a, ennreal.coe_to_nnreal),
have : ∀ x, ↑(ψ x) ≤ f x := λ x, le_trans ennreal.coe_to_nnreal_le_self (hφ x),
exact le_supr_of_le (φ.map ennreal.to_nnreal)
(le_supr_of_le this (ge_of_eq $ lintegral_congr h)) },
{ have h_meas : μ (φ ⁻¹' {⊤}) ≠ 0, from mt measure_zero_iff_ae_nmem.1 h,
refine le_trans le_top (ge_of_eq $ (supr_eq_top _).2 $ λ b hb, _),
obtain ⟨n, hn⟩ : ∃ n : ℕ, b < n * μ (φ ⁻¹' {⊤}), from exists_nat_mul_gt h_meas (ne_of_lt hb),
use (const α (n : ℝ≥0)).restrict (φ ⁻¹' {⊤}),
simp only [lt_supr_iff, exists_prop, coe_restrict, φ.is_measurable_preimage, coe_const,
ennreal.coe_indicator, map_coe_ennreal_restrict, map_const, ennreal.coe_nat,
restrict_const_lintegral],
refine ⟨indicator_le (λ x hx, le_trans _ (hφ _)), hn⟩,
simp only [mem_preimage, mem_singleton_iff] at hx,
simp only [hx, le_top] }
end
theorem supr_lintegral_le {ι : Sort*} (f : ι → α → ennreal) :
(⨆i, ∫⁻ a, f i a ∂μ) ≤ (∫⁻ a, ⨆i, f i a ∂μ) :=
begin
simp only [← supr_apply],
exact (monotone_lintegral μ).le_map_supr
end
theorem supr2_lintegral_le {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) :
(⨆i (h : ι' i), ∫⁻ a, f i h a ∂μ) ≤ (∫⁻ a, ⨆i (h : ι' i), f i h a ∂μ) :=
by { convert (monotone_lintegral μ).le_map_supr2 f, ext1 a, simp only [supr_apply] }
theorem le_infi_lintegral {ι : Sort*} (f : ι → α → ennreal) :
(∫⁻ a, ⨅i, f i a ∂μ) ≤ (⨅i, ∫⁻ a, f i a ∂μ) :=
by { simp only [← infi_apply], exact (monotone_lintegral μ).map_infi_le }
theorem le_infi2_lintegral {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) :
(∫⁻ a, ⨅ i (h : ι' i), f i h a ∂μ) ≤ (⨅ i (h : ι' i), ∫⁻ a, f i h a ∂μ) :=
by { convert (monotone_lintegral μ).map_infi2_le f, ext1 a, simp only [infi_apply] }
/-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence.
See `lintegral_supr_directed` for a more general form. -/
theorem lintegral_supr
{f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : monotone f) :
(∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) :=
begin
set c : nnreal → ennreal := coe,
set F := λ a:α, ⨆n, f n a,
have hF : measurable F := measurable_supr hf,
refine le_antisymm _ (supr_lintegral_le _),
rw [lintegral_eq_nnreal],
refine supr_le (assume s, supr_le (assume hsf, _)),
refine ennreal.le_of_forall_lt_one_mul_lt (assume a ha, _),
rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩,
have ha : r < 1 := ennreal.coe_lt_coe.1 ha,
let rs := s.map (λa, r * a),
have eq_rs : (const α r : α →ₛ ennreal) * map c s = rs.map c,
{ ext1 a, exact ennreal.coe_mul.symm },
have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}),
{ assume p,
rw [← inter_Union, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]},
refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _),
by_cases p_eq : p = 0, { simp [p_eq] },
simp at hx, subst hx,
have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] },
have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] },
have : (rs.map c) x < ⨆ (n : ℕ), f n x,
{ refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x),
suffices : r * s x < 1 * s x, simpa [rs],
exact mul_lt_mul_of_pos_right ha (zero_lt_iff_ne_zero.2 this) },
rcases lt_supr_iff.1 this with ⟨i, hi⟩,
exact mem_Union.2 ⟨i, le_of_lt hi⟩ },
have mono : ∀r:ennreal, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}),
{ assume r i j h,
refine inter_subset_inter (subset.refl _) _,
assume x hx, exact le_trans hx (h_mono h x) },
have h_meas : ∀n, is_measurable {a : α | ⇑(map c rs) a ≤ f n a} :=
assume n, is_measurable_le (simple_func.measurable _) (hf n),
calc (r:ennreal) * (s.map c).lintegral μ = ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r}) :
by rw [← const_mul_lintegral, eq_rs, simple_func.lintegral]
... ≤ ∑ r in (rs.map c).range, r * μ (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) :
le_of_eq (finset.sum_congr rfl $ assume x hx, by rw ← eq)
... ≤ ∑ r in (rs.map c).range, (⨆n, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) :
le_of_eq (finset.sum_congr rfl $ assume x hx,
begin
rw [measure_Union_eq_supr _ (directed_of_sup $ mono x), ennreal.mul_supr],
{ assume i,
refine ((rs.map c).is_measurable_preimage _).inter _,
exact hf i is_measurable_Ici }
end)
... ≤ ⨆n, ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) :
begin
refine le_of_eq _,
rw [ennreal.finset_sum_supr_nat],
assume p i j h,
exact canonically_ordered_semiring.mul_le_mul (le_refl _) (measure_mono $ mono p h)
end
... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).lintegral μ) :
begin
refine supr_le_supr (assume n, _),
rw [restrict_lintegral _ (h_meas n)],
{ refine le_of_eq (finset.sum_congr rfl $ assume r hr, _),
congr' 2 with a,
refine and_congr_right _,
simp {contextual := tt} }
end
... ≤ (⨆n, ∫⁻ a, f n a ∂μ) :
begin
refine supr_le_supr (assume n, _),
rw [← simple_func.lintegral_eq_lintegral],
refine lintegral_mono (assume a, _),
dsimp,
rw [restrict_apply],
split_ifs; simp, simpa using h,
exact h_meas n
end
end
lemma lintegral_eq_supr_eapprox_lintegral {f : α → ennreal} (hf : measurable f) :
(∫⁻ a, f a ∂μ) = (⨆n, (eapprox f n).lintegral μ) :=
calc (∫⁻ a, f a ∂μ) = (∫⁻ a, ⨆n, (eapprox f n : α → ennreal) a ∂μ) :
by congr; ext a; rw [supr_eapprox_apply f hf]
... = (⨆n, ∫⁻ a, (eapprox f n : α → ennreal) a ∂μ) :
begin
rw [lintegral_supr],
{ assume n, exact (eapprox f n).measurable },
{ assume i j h, exact (monotone_eapprox f h) }
end
... = (⨆n, (eapprox f n).lintegral μ) : by congr; ext n; rw [(eapprox f n).lintegral_eq_lintegral]
@[simp] lemma lintegral_add {f g : α → ennreal} (hf : measurable f) (hg : measurable g) :
(∫⁻ a, f a + g a ∂μ) = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) :=
calc (∫⁻ a, f a + g a ∂μ) =
(∫⁻ a, (⨆n, (eapprox f n : α → ennreal) a) + (⨆n, (eapprox g n : α → ennreal) a) ∂μ) :
by congr; funext a; rw [supr_eapprox_apply f hf, supr_eapprox_apply g hg]
... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ennreal) a) ∂μ) :
begin
congr, funext a,
rw [ennreal.supr_add_supr_of_monotone], { refl },
{ assume i j h, exact monotone_eapprox _ h a },
{ assume i j h, exact monotone_eapprox _ h a },
end
... = (⨆n, (eapprox f n).lintegral μ + (eapprox g n).lintegral μ) :
begin
rw [lintegral_supr],
{ congr,
funext n, rw [← simple_func.add_lintegral, ← simple_func.lintegral_eq_lintegral],
refl },
{ assume n, exact measurable.add (eapprox f n).measurable (eapprox g n).measurable },
{ assume i j h a, exact add_le_add (monotone_eapprox _ h _) (monotone_eapprox _ h _) }
end
... = (⨆n, (eapprox f n).lintegral μ) + (⨆n, (eapprox g n).lintegral μ) :
by refine (ennreal.supr_add_supr_of_monotone _ _).symm;
{ assume i j h, exact simple_func.lintegral_mono (monotone_eapprox _ h) (le_refl μ) }
... = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) :
by rw [lintegral_eq_supr_eapprox_lintegral hf, lintegral_eq_supr_eapprox_lintegral hg]
lemma lintegral_zero : (∫⁻ a:α, 0 ∂μ) = 0 := by simp
lemma lintegral_zero_fun : (∫⁻ a:α, (0 : α → ennreal) a ∂μ) = 0 := by simp
@[simp] lemma lintegral_smul_measure (c : ennreal) (f : α → ennreal) :
∫⁻ a, f a ∂ (c • μ) = c * ∫⁻ a, f a ∂μ :=
by simp only [lintegral, supr_subtype', simple_func.lintegral_smul, ennreal.mul_supr, smul_eq_mul]
@[simp] lemma lintegral_sum_measure {ι} (f : α → ennreal) (μ : ι → measure α) :
∫⁻ a, f a ∂(measure.sum μ) = ∑' i, ∫⁻ a, f a ∂(μ i) :=
begin
simp only [lintegral, supr_subtype', simple_func.lintegral_sum, ennreal.tsum_eq_supr_sum],
rw [supr_comm],
congr, funext s,
induction s using finset.induction_on with i s hi hs, { apply bot_unique, simp },
simp only [finset.sum_insert hi, ← hs],
refine (ennreal.supr_add_supr _).symm,
intros φ ψ,
exact ⟨⟨φ ⊔ ψ, λ x, sup_le (φ.2 x) (ψ.2 x)⟩,
add_le_add (simple_func.lintegral_mono le_sup_left (le_refl _))
(finset.sum_le_sum $ λ j hj, simple_func.lintegral_mono le_sup_right (le_refl _))⟩
end
@[simp] lemma lintegral_add_measure (f : α → ennreal) (μ ν : measure α) :
∫⁻ a, f a ∂ (μ + ν) = ∫⁻ a, f a ∂μ + ∫⁻ a, f a ∂ν :=
by simpa [tsum_fintype] using lintegral_sum_measure f (λ b, cond b μ ν)
@[simp] lemma lintegral_zero_measure (f : α → ennreal) : ∫⁻ a, f a ∂0 = 0 :=
bot_unique $ by simp [lintegral]
lemma lintegral_finset_sum (s : finset β) {f : β → α → ennreal} (hf : ∀b, measurable (f b)) :
(∫⁻ a, ∑ b in s, f b a ∂μ) = ∑ b in s, ∫⁻ a, f b a ∂μ :=
begin
refine finset.induction_on s _ _,
{ simp },
{ assume a s has ih,
simp only [finset.sum_insert has],
rw [lintegral_add (hf _) (s.measurable_sum hf), ih] }
end
@[simp] lemma lintegral_const_mul (r : ennreal) {f : α → ennreal} (hf : measurable f) :
(∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) :=
calc (∫⁻ a, r * f a ∂μ) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a) ∂μ) :
by { congr, funext a, rw [← supr_eapprox_apply f hf, ennreal.mul_supr], refl }
... = (⨆n, r * (eapprox f n).lintegral μ) :
begin
rw [lintegral_supr],
{ congr, funext n,
rw [← simple_func.const_mul_lintegral, ← simple_func.lintegral_eq_lintegral] },
{ assume n, exact simple_func.measurable _ },
{ assume i j h a, exact canonically_ordered_semiring.mul_le_mul (le_refl _)
(monotone_eapprox _ h _) }
end
... = r * (∫⁻ a, f a ∂μ) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_lintegral hf]
lemma lintegral_const_mul_le (r : ennreal) (f : α → ennreal) :
r * (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, r * f a ∂μ) :=
begin
rw [lintegral, ennreal.mul_supr],
refine supr_le (λs, _),
rw [ennreal.mul_supr],
simp only [supr_le_iff, ge_iff_le],
assume hs,
rw ← simple_func.const_mul_lintegral,
refine le_supr_of_le (const α r * s) (le_supr_of_le (λx, _) (le_refl _)),
exact canonically_ordered_semiring.mul_le_mul (le_refl _) (hs x)
end
lemma lintegral_const_mul' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤) :
(∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) :=
begin
by_cases h : r = 0,
{ simp [h] },
apply le_antisymm _ (lintegral_const_mul_le r f),
have rinv : r * r⁻¹ = 1 := ennreal.mul_inv_cancel h hr,
have rinv' : r ⁻¹ * r = 1, by { rw mul_comm, exact rinv },
have := lintegral_const_mul_le (r⁻¹) (λx, r * f x),
simp [(mul_assoc _ _ _).symm, rinv'] at this,
simpa [(mul_assoc _ _ _).symm, rinv]
using canonically_ordered_semiring.mul_le_mul (le_refl r) this
end
lemma lintegral_mul_const (r : ennreal) {f : α → ennreal} (hf : measurable f) :
∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r :=
by simp_rw [mul_comm, lintegral_const_mul r hf]
lemma lintegral_mul_const_le (r : ennreal) (f : α → ennreal) :
∫⁻ a, f a ∂μ * r ≤ ∫⁻ a, f a * r ∂μ :=
by simp_rw [mul_comm, lintegral_const_mul_le r f]
lemma lintegral_mul_const' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤):
∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r :=
by simp_rw [mul_comm, lintegral_const_mul' r f hr]
lemma lintegral_mono_ae {f g : α → ennreal} (h : ∀ᵐ a ∂μ, f a ≤ g a) :
(∫⁻ a, f a ∂μ) ≤ (∫⁻ a, g a ∂μ) :=
begin
rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t, hts, ht, ht0⟩,
have : ∀ᵐ x ∂μ, x ∉ t := measure_zero_iff_ae_nmem.1 ht0,
refine (supr_le $ assume s, supr_le $ assume hfs,
le_supr_of_le (s.restrict tᶜ) $ le_supr_of_le _ _),
{ assume a,
by_cases a ∈ t;
simp [h, restrict_apply, ht.compl],
exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) },
{ refine le_of_eq (simple_func.lintegral_congr $ this.mono $ λ a hnt, _),
by_cases hat : a ∈ t; simp [hat, ht.compl],
exact (hnt hat).elim }
end
lemma lintegral_congr_ae {f g : α → ennreal} (h : f =ᵐ[μ] g) :
(∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) :=
le_antisymm (lintegral_mono_ae $ h.le) (lintegral_mono_ae $ h.symm.le)
lemma lintegral_congr {f g : α → ennreal} (h : ∀ a, f a = g a) :
(∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) :=
by simp only [h]
lemma set_lintegral_congr {f : α → ennreal} {s t : set α} (h : s =ᵐ[μ] t) :
∫⁻ x in s, f x ∂μ = ∫⁻ x in t, f x ∂μ :=
by rw [restrict_congr_set h]
-- TODO: Need a better way of rewriting inside of a integral
lemma lintegral_rw₁ {f f' : α → β} (h : f =ᵐ[μ] f') (g : β → ennreal) :
(∫⁻ a, g (f a) ∂μ) = (∫⁻ a, g (f' a) ∂μ) :=
lintegral_congr_ae $ h.mono $ λ a h, by rw h
-- TODO: Need a better way of rewriting inside of a integral
lemma lintegral_rw₂ {f₁ f₁' : α → β} {f₂ f₂' : α → γ} (h₁ : f₁ =ᵐ[μ] f₁')
(h₂ : f₂ =ᵐ[μ] f₂') (g : β → γ → ennreal) :
(∫⁻ a, g (f₁ a) (f₂ a) ∂μ) = (∫⁻ a, g (f₁' a) (f₂' a) ∂μ) :=
lintegral_congr_ae $ h₁.mp $ h₂.mono $ λ _ h₂ h₁, by rw [h₁, h₂]
@[simp] lemma lintegral_indicator (f : α → ennreal) {s : set α} (hs : is_measurable s) :
∫⁻ a, s.indicator f a ∂μ = ∫⁻ a in s, f a ∂μ :=
begin
simp only [lintegral, ← restrict_lintegral_eq_lintegral_restrict _ hs, supr_subtype'],
apply le_antisymm; refine supr_le_supr2 (subtype.forall.2 $ λ φ hφ, _),
{ refine ⟨⟨φ, le_trans hφ (indicator_le_self _ _)⟩, _⟩,
refine simple_func.lintegral_mono (λ x, _) (le_refl _),
by_cases hx : x ∈ s,
{ simp [hx, hs, le_refl] },
{ apply le_trans (hφ x),
simp [hx, hs, le_refl] } },
{ refine ⟨⟨φ.restrict s, λ x, _⟩, le_refl _⟩,
simp [hφ x, hs, indicator_le_indicator] }
end
/-- Chebyshev's inequality -/
lemma mul_meas_ge_le_lintegral {f : α → ennreal} (hf : measurable f) (ε : ennreal) :
ε * μ {x | ε ≤ f x} ≤ ∫⁻ a, f a ∂μ :=
begin
have : is_measurable {a : α | ε ≤ f a }, from hf is_measurable_Ici,
rw [← simple_func.restrict_const_lintegral _ this, ← simple_func.lintegral_eq_lintegral],
refine lintegral_mono (λ a, _),
simp only [restrict_apply _ this],
split_ifs; [assumption, exact zero_le _]
end
lemma meas_ge_le_lintegral_div {f : α → ennreal} (hf : measurable f) {ε : ennreal}
(hε : ε ≠ 0) (hε' : ε ≠ ⊤) :
μ {x | ε ≤ f x} ≤ (∫⁻ a, f a ∂μ) / ε :=
(ennreal.le_div_iff_mul_le (or.inl hε) (or.inl hε')).2 $
by { rw [mul_comm], exact mul_meas_ge_le_lintegral hf ε }
@[simp] lemma lintegral_eq_zero_iff {f : α → ennreal} (hf : measurable f) :
∫⁻ a, f a ∂μ = 0 ↔ (f =ᵐ[μ] 0) :=
begin
refine iff.intro (assume h, _) (assume h, _),
{ have : ∀n:ℕ, ∀ᵐ a ∂μ, f a < n⁻¹,
{ assume n,
rw [ae_iff, ← le_zero_iff_eq, ← @ennreal.zero_div n⁻¹,
ennreal.le_div_iff_mul_le, mul_comm],
simp only [not_lt],
-- TODO: why `rw ← h` fails with "not an equality or an iff"?
exacts [h ▸ mul_meas_ge_le_lintegral hf n⁻¹,
or.inl (ennreal.inv_ne_zero.2 ennreal.coe_nat_ne_top),
or.inr ennreal.zero_ne_top] },
refine (ae_all_iff.2 this).mono (λ a ha, _),
by_contradiction h,
rcases ennreal.exists_inv_nat_lt h with ⟨n, hn⟩,
exact (lt_irrefl _ $ lt_trans hn $ ha n).elim },
{ calc ∫⁻ a, f a ∂μ = ∫⁻ a, 0 ∂μ : lintegral_congr_ae h
... = 0 : lintegral_zero }
end
lemma lintegral_pos_iff_support {f : α → ennreal} (hf : measurable f) :
0 < ∫⁻ a, f a ∂μ ↔ 0 < μ (function.support f) :=
by simp [zero_lt_iff_ne_zero, hf, filter.eventually_eq, ae_iff, function.support]
/-- Weaker version of the monotone convergence theorem-/
lemma lintegral_supr_ae {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n))
(h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f n.succ a) :
(∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) :=
let ⟨s, hs⟩ := exists_is_measurable_superset_of_measure_eq_zero
(ae_iff.1 (ae_all_iff.2 h_mono)) in
let g := λ n a, if a ∈ s then 0 else f n a in
have g_eq_f : ∀ᵐ a ∂μ, ∀n, g n a = f n a,
from (measure_zero_iff_ae_nmem.1 hs.2.2).mono (assume a ha n, if_neg ha),
calc
∫⁻ a, ⨆n, f n a ∂μ = ∫⁻ a, ⨆n, g n a ∂μ :
lintegral_congr_ae $ g_eq_f.mono $ λ a ha, by simp only [ha]
... = ⨆n, (∫⁻ a, g n a ∂μ) :
lintegral_supr
(assume n, measurable_const.piecewise hs.2.1 (hf n))
(monotone_of_monotone_nat $ assume n a, classical.by_cases
(assume h : a ∈ s, by simp [g, if_pos h])
(assume h : a ∉ s,
begin
simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h,
simp only [not_not, mem_set_of_eq] at this, exact this n
end))
... = ⨆n, (∫⁻ a, f n a ∂μ) :
by simp only [lintegral_congr_ae (g_eq_f.mono $ λ a ha, ha _)]
lemma lintegral_sub {f g : α → ennreal} (hf : measurable f) (hg : measurable g)
(hg_fin : ∫⁻ a, g a ∂μ < ⊤) (h_le : g ≤ᵐ[μ] f) :
∫⁻ a, f a - g a ∂μ = ∫⁻ a, f a ∂μ - ∫⁻ a, g a ∂μ :=
begin
rw [← ennreal.add_left_inj hg_fin,
ennreal.sub_add_cancel_of_le (lintegral_mono_ae h_le),
← lintegral_add (hf.ennreal_sub hg) hg],
refine lintegral_congr_ae (h_le.mono $ λ x hx, _),
exact ennreal.sub_add_cancel_of_le hx
end
/-- Monotone convergence theorem for nonincreasing sequences of functions -/
lemma lintegral_infi_ae
{f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n))
(h_mono : ∀n:ℕ, f n.succ ≤ᵐ[μ] f n) (h_fin : ∫⁻ a, f 0 a ∂μ < ⊤) :
∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ :=
have fn_le_f0 : ∫⁻ a, ⨅n, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ, from
lintegral_mono (assume a, infi_le_of_le 0 (le_refl _)),
have fn_le_f0' : (⨅n, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ, from infi_le_of_le 0 (le_refl _),
(ennreal.sub_right_inj h_fin fn_le_f0 fn_le_f0').1 $
show ∫⁻ a, f 0 a ∂μ - ∫⁻ a, ⨅n, f n a ∂μ = ∫⁻ a, f 0 a ∂μ - (⨅n, ∫⁻ a, f n a ∂μ), from
calc
∫⁻ a, f 0 a ∂μ - (∫⁻ a, ⨅n, f n a ∂μ) = ∫⁻ a, f 0 a - ⨅n, f n a ∂μ:
(lintegral_sub (h_meas 0) (measurable_infi h_meas)
(calc
(∫⁻ a, ⨅n, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ : lintegral_mono (assume a, infi_le _ _)
... < ⊤ : h_fin )
(ae_of_all _ $ assume a, infi_le _ _)).symm
... = ∫⁻ a, ⨆n, f 0 a - f n a ∂μ : congr rfl (funext (assume a, ennreal.sub_infi))
... = ⨆n, ∫⁻ a, f 0 a - f n a ∂μ :
lintegral_supr_ae
(assume n, (h_meas 0).ennreal_sub (h_meas n))
(assume n, (h_mono n).mono $ assume a ha, ennreal.sub_le_sub (le_refl _) ha)
... = ⨆n, ∫⁻ a, f 0 a ∂μ - ∫⁻ a, f n a ∂μ :
have h_mono : ∀ᵐ a ∂μ, ∀n:ℕ, f n.succ a ≤ f n a := ae_all_iff.2 h_mono,
have h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f 0 a := assume n, h_mono.mono $ assume a h,
begin
induction n with n ih,
{exact le_refl _}, {exact le_trans (h n) ih}
end,
congr rfl (funext $ assume n, lintegral_sub (h_meas _) (h_meas _)
(calc
∫⁻ a, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ : lintegral_mono_ae $ h_mono n
... < ⊤ : h_fin)
(h_mono n))
... = ∫⁻ a, f 0 a ∂μ - ⨅n, ∫⁻ a, f n a ∂μ : ennreal.sub_infi.symm
/-- Monotone convergence theorem for nonincreasing sequences of functions -/
lemma lintegral_infi
{f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n))
(h_mono : ∀ ⦃m n⦄, m ≤ n → f n ≤ f m) (h_fin : ∫⁻ a, f 0 a ∂μ < ⊤) :
∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ :=
lintegral_infi_ae h_meas (λ n, ae_of_all _ $ h_mono $ le_of_lt n.lt_succ_self) h_fin
/-- Known as Fatou's lemma -/
lemma lintegral_liminf_le {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) :
∫⁻ a, liminf at_top (λ n, f n a) ∂μ ≤ liminf at_top (λ n, ∫⁻ a, f n a ∂μ) :=
calc
∫⁻ a, liminf at_top (λ n, f n a) ∂μ = ∫⁻ a, ⨆n:ℕ, ⨅i≥n, f i a ∂μ :
by simp only [liminf_eq_supr_infi_of_nat]
... = ⨆n:ℕ, ∫⁻ a, ⨅i≥n, f i a ∂μ :
lintegral_supr
(assume n, measurable_binfi _ (countable_encodable _) h_meas)
(assume n m hnm a, infi_le_infi_of_subset $ λ i hi, le_trans hnm hi)
... ≤ ⨆n:ℕ, ⨅i≥n, ∫⁻ a, f i a ∂μ :
supr_le_supr $ λ n, le_infi2_lintegral _
... = liminf at_top (λ n, ∫⁻ a, f n a ∂μ) : liminf_eq_supr_infi_of_nat.symm
lemma limsup_lintegral_le {f : ℕ → α → ennreal} {g : α → ennreal}
(hf_meas : ∀ n, measurable (f n)) (h_bound : ∀n, f n ≤ᵐ[μ] g) (h_fin : ∫⁻ a, g a ∂μ < ⊤) :
limsup at_top (λn, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, f n a) ∂μ :=
calc
limsup at_top (λn, ∫⁻ a, f n a ∂μ) = ⨅n:ℕ, ⨆i≥n, ∫⁻ a, f i a ∂μ :
limsup_eq_infi_supr_of_nat
... ≤ ⨅n:ℕ, ∫⁻ a, ⨆i≥n, f i a ∂μ :
infi_le_infi $ assume n, supr2_lintegral_le _
... = ∫⁻ a, ⨅n:ℕ, ⨆i≥n, f i a ∂μ :
begin
refine (lintegral_infi _ _ _).symm,
{ assume n, exact measurable_bsupr _ (countable_encodable _) hf_meas },
{ assume n m hnm a, exact (supr_le_supr_of_subset $ λ i hi, le_trans hnm hi) },
{ refine lt_of_le_of_lt (lintegral_mono_ae _) h_fin,
refine (ae_all_iff.2 h_bound).mono (λ n hn, _),
exact supr_le (λ i, supr_le $ λ hi, hn i) }
end
... = ∫⁻ a, limsup at_top (λn, f n a) ∂μ :
by simp only [limsup_eq_infi_supr_of_nat]
/-- Dominated convergence theorem for nonnegative functions -/
lemma tendsto_lintegral_of_dominated_convergence
{F : ℕ → α → ennreal} {f : α → ennreal} (bound : α → ennreal)
(hF_meas : ∀n, measurable (F n)) (h_bound : ∀n, F n ≤ᵐ[μ] bound)
(h_fin : ∫⁻ a, bound a ∂μ < ⊤)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) :
tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) :=
tendsto_of_le_liminf_of_limsup_le
(calc ∫⁻ a, f a ∂μ = ∫⁻ a, liminf at_top (λ (n : ℕ), F n a) ∂μ :
lintegral_congr_ae $ h_lim.mono $ assume a h, h.liminf_eq.symm
... ≤ liminf at_top (λ n, ∫⁻ a, F n a ∂μ) : lintegral_liminf_le hF_meas)
(calc limsup at_top (λ (n : ℕ), ∫⁻ a, F n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, F n a) ∂μ :
limsup_lintegral_le hF_meas h_bound h_fin
... = ∫⁻ a, f a ∂μ : lintegral_congr_ae $ h_lim.mono $ λ a h, h.limsup_eq)
/-- Dominated convergence theorem for filters with a countable basis -/
lemma tendsto_lintegral_filter_of_dominated_convergence {ι} {l : filter ι}
{F : ι → α → ennreal} {f : α → ennreal} (bound : α → ennreal)
(hl_cb : l.is_countably_generated)
(hF_meas : ∀ᶠ n in l, measurable (F n))
(h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, F n a ≤ bound a)
(h_fin : ∫⁻ a, bound a ∂μ < ⊤)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) :
tendsto (λn, ∫⁻ a, F n a ∂μ) l (𝓝 $ ∫⁻ a, f a ∂μ) :=
begin
rw hl_cb.tendsto_iff_seq_tendsto,
{ intros x xl,
have hxl, { rw tendsto_at_top' at xl, exact xl },
have h := inter_mem_sets hF_meas h_bound,
replace h := hxl _ h,
rcases h with ⟨k, h⟩,
rw ← tendsto_add_at_top_iff_nat k,
refine tendsto_lintegral_of_dominated_convergence _ _ _ _ _,
{ exact bound },
{ intro, refine (h _ _).1, exact nat.le_add_left _ _ },
{ intro, refine (h _ _).2, exact nat.le_add_left _ _ },
{ assumption },
{ refine h_lim.mono (λ a h_lim, _),
apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a),
{ assumption },
rw tendsto_add_at_top_iff_nat,
assumption } },
end
section
open encodable
/-- Monotone convergence for a suprema over a directed family and indexed by an encodable type -/
theorem lintegral_supr_directed [encodable β] {f : β → α → ennreal}
(hf : ∀b, measurable (f b)) (h_directed : directed (≤) f) :
∫⁻ a, ⨆b, f b a ∂μ = ⨆b, ∫⁻ a, f b a ∂μ :=
begin
by_cases hβ : nonempty β, swap,
{ simp [supr_of_empty hβ] },
resetI, inhabit β,
have : ∀a, (⨆ b, f b a) = (⨆ n, f (h_directed.sequence f n) a),
{ assume a,
refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (λn, f n a) _),
exact le_supr_of_le (encode b + 1) (h_directed.le_sequence b a) },
calc ∫⁻ a, ⨆ b, f b a ∂μ = ∫⁻ a, ⨆ n, f (h_directed.sequence f n) a ∂μ :
by simp only [this]
... = ⨆ n, ∫⁻ a, f (h_directed.sequence f n) a ∂μ :
lintegral_supr (assume n, hf _) h_directed.sequence_mono
... = ⨆ b, ∫⁻ a, f b a ∂μ :
begin
refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _),
{ exact le_supr (λb, ∫⁻ a, f b a ∂μ) _ },
{ exact le_supr_of_le (encode b + 1)
(lintegral_mono $ h_directed.le_sequence b) }
end
end
end
lemma lintegral_tsum [encodable β] {f : β → α → ennreal} (hf : ∀i, measurable (f i)) :
∫⁻ a, ∑' i, f i a ∂μ = ∑' i, ∫⁻ a, f i a ∂μ :=
begin
simp only [ennreal.tsum_eq_supr_sum],
rw [lintegral_supr_directed],
{ simp [lintegral_finset_sum _ hf] },
{ assume b, exact finset.measurable_sum _ hf },
{ assume s t,
use [s ∪ t],
split,
exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _),
exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) }
end
open measure
lemma lintegral_Union [encodable β] {s : β → set α} (hm : ∀ i, is_measurable (s i))
(hd : pairwise (disjoint on s)) (f : α → ennreal) :
∫⁻ a in ⋃ i, s i, f a ∂μ = ∑' i, ∫⁻ a in s i, f a ∂μ :=
by simp only [measure.restrict_Union hd hm, lintegral_sum_measure]
lemma lintegral_Union_le [encodable β] (s : β → set α) (f : α → ennreal) :
∫⁻ a in ⋃ i, s i, f a ∂μ ≤ ∑' i, ∫⁻ a in s i, f a ∂μ :=
begin
rw [← lintegral_sum_measure],
exact lintegral_mono' restrict_Union_le (le_refl _)
end
lemma lintegral_map [measurable_space β] {f : β → ennreal} {g : α → β}
(hf : measurable f) (hg : measurable g) : ∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ :=
begin
simp only [lintegral_eq_supr_eapprox_lintegral, hf, hf.comp hg],
{ congr, funext n, symmetry,
apply simple_func.lintegral_map,
{ assume a, exact congr_fun (simple_func.eapprox_comp hf hg) a },
{ assume s hs, exact map_apply hg hs } },
end
lemma lintegral_comp [measurable_space β] {f : β → ennreal} {g : α → β}
(hf : measurable f) (hg : measurable g) : lintegral μ (f ∘ g) = ∫⁻ a, f a ∂(map g μ) :=
(lintegral_map hf hg).symm
lemma set_lintegral_map [measurable_space β] {f : β → ennreal} {g : α → β}
{s : set β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) :
∫⁻ y in s, f y ∂(map g μ) = ∫⁻ x in g ⁻¹' s, f (g x) ∂μ :=
by rw [restrict_map hg hs, lintegral_map hf hg]
lemma lintegral_dirac (a : α) {f : α → ennreal} (hf : measurable f) :
∫⁻ a, f a ∂(dirac a) = f a :=
by simp [lintegral_congr_ae (eventually_eq_dirac hf)]
lemma ae_lt_top {f : α → ennreal} (hf : measurable f) (h2f : ∫⁻ x, f x ∂μ < ⊤) :
∀ᵐ x ∂μ, f x < ⊤ :=
begin
simp_rw [ae_iff, ennreal.not_lt_top], by_contra h, rw [← not_le] at h2f, apply h2f,
have : (f ⁻¹' {⊤}).indicator ⊤ ≤ f,
{ intro x, by_cases hx : x ∈ f ⁻¹' {⊤}; [simpa [hx], simp [hx]] },
convert lintegral_mono this,
rw [lintegral_indicator _ (hf (is_measurable_singleton ⊤))], simp [ennreal.top_mul, preimage, h]
end
/-- Given a measure `μ : measure α` and a function `f : α → ennreal`, `μ.with_density f` is the
measure such that for a measurable set `s` we have `μ.with_density f s = ∫⁻ a in s, f a ∂μ`. -/
def measure.with_density (μ : measure α) (f : α → ennreal) : measure α :=
measure.of_measurable (λs hs, ∫⁻ a in s, f a ∂μ) (by simp) (λ s hs hd, lintegral_Union hs hd _)
@[simp] lemma with_density_apply (f : α → ennreal) {s : set α} (hs : is_measurable s) :
μ.with_density f s = ∫⁻ a in s, f a ∂μ :=
measure.of_measurable_apply s hs
end lintegral
end measure_theory
open measure_theory measure_theory.simple_func
/-- To prove something for an arbitrary measurable function into `ennreal`, it suffices to show
that the property holds for (multiples of) characteristic functions and is closed under addition
and supremum of increasing sequences of functions.
It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions
can be added once we need them (for example in `h_sum` it is only necessary to consider the sum of
a simple function with a multiple of a characteristic function and that the intersection
of their images is a subset of `{0}`. -/
@[elab_as_eliminator]
theorem measurable.ennreal_induction {α} [measurable_space α] {P : (α → ennreal) → Prop}
(h_ind : ∀ (c : ennreal) ⦃s⦄, is_measurable s → P (indicator s (λ _, c)))
(h_sum : ∀ ⦃f g : α → ennreal⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → measurable f → measurable g →
P f → P g → P (f + g))
(h_supr : ∀ ⦃f : ℕ → α → ennreal⦄ (hf : ∀n, measurable (f n)) (h_mono : monotone f)
(hP : ∀ n, P (f n)), P (λ x, ⨆ n, f n x))
⦃f : α → ennreal⦄ (hf : measurable f) : P f :=
begin
convert h_supr (λ n, (eapprox f n).measurable) (monotone_eapprox f) _,
{ ext1 x, rw [supr_eapprox_apply f hf] },
{ exact λ n, simple_func.induction (λ c s hs, h_ind c hs)
(λ f g hfg hf hg, h_sum hfg f.measurable g.measurable hf hg) (eapprox f n) }
end
namespace measure_theory
/-- This is Exercise 1.2.1 from [tao2010]. It allows you to express integration of a measurable
function with respect to `(μ.with_density f)` as an integral with respect to `μ`, called the base
measure. `μ` is often the Lebesgue measure, and in this circumstance `f` is the probability density
function, and `(μ.with_density f)` represents any continuous random variable as a
probability measure, such as the uniform distribution between 0 and 1, the Gaussian distribution,
the exponential distribution, the Beta distribution, or the Cauchy distribution (see Section 2.4
of [wasserman2004]). Thus, this method shows how to one can calculate expectations, variances,
and other moments as a function of the probability density function.
-/
lemma lintegral_with_density_eq_lintegral_mul {α} [measurable_space α] (μ : measure α)
{f : α → ennreal} (h_mf : measurable f) : ∀ {g : α → ennreal}, measurable g →
∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ :=
begin
apply measurable.ennreal_induction,
{ intros c s h_ms,
simp [*, mul_comm _ c] },
{ intros g h h_univ h_mea_g h_mea_h h_ind_g h_ind_h,
simp [mul_add, *, measurable.ennreal_mul] },
{ intros g h_mea_g h_mono_g h_ind,
have : monotone (λ n a, f a * g n a) := λ m n hmn x, ennreal.mul_le_mul le_rfl (h_mono_g hmn x),
simp [lintegral_supr, ennreal.mul_supr, h_mf.ennreal_mul (h_mea_g _), *] }
end
end measure_theory
|
4c8096960112dfefe390c71ea65d91ed2acb400b | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/number_theory/pythagorean_triples.lean | a06c507916d19b67620f55427c38e784291c31f7 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 26,046 | lean | /-
Copyright (c) 2020 Paul van Wamelen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Paul van Wamelen
-/
import algebra.field
import ring_theory.int.basic
import algebra.group_with_zero.power
import tactic.ring
import tactic.ring_exp
import tactic.field_simp
/-!
# Pythagorean Triples
The main result is the classification of Pythagorean triples. The final result is for general
Pythagorean triples. It follows from the more interesting relatively prime case. We use the
"rational parametrization of the circle" method for the proof. The parametrization maps the point
`(x / z, y / z)` to the slope of the line through `(-1 , 0)` and `(x / z, y / z)`. This quickly
shows that `(x / z, y / z) = (2 * m * n / (m ^ 2 + n ^ 2), (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2))` where
`m / n` is the slope. In order to identify numerators and denominators we now need results showing
that these are coprime. This is easy except for the prime 2. In order to deal with that we have to
analyze the parity of `x`, `y`, `m` and `n` and eliminate all the impossible cases. This takes up
the bulk of the proof below.
-/
noncomputable theory
open_locale classical
/-- Three integers `x`, `y`, and `z` form a Pythagorean triple if `x * x + y * y = z * z`. -/
def pythagorean_triple (x y z : ℤ) : Prop := x * x + y * y = z * z
/-- Pythagorean triples are interchangable, i.e `x * x + y * y = y * y + x * x = z * z`.
This comes from additive commutativity. -/
lemma pythagorean_triple_comm {x y z : ℤ} :
(pythagorean_triple x y z) ↔ (pythagorean_triple y x z) :=
by { delta pythagorean_triple, rw add_comm }
/-- The zeroth Pythagorean triple is all zeros. -/
lemma pythagorean_triple.zero : pythagorean_triple 0 0 0 :=
by simp only [pythagorean_triple, zero_mul, zero_add]
namespace pythagorean_triple
variables {x y z : ℤ} (h : pythagorean_triple x y z)
include h
lemma eq : x * x + y * y = z * z := h
@[symm]
lemma symm :
pythagorean_triple y x z :=
by rwa [pythagorean_triple_comm]
/-- A triple is still a triple if you multiply `x`, `y` and `z`
by a constant `k`. -/
lemma mul (k : ℤ) : pythagorean_triple (k * x) (k * y) (k * z) :=
begin
by_cases hk : k = 0,
{ simp only [pythagorean_triple, hk, zero_mul, zero_add], },
{ calc (k * x) * (k * x) + (k * y) * (k * y)
= k ^ 2 * (x * x + y * y) : by ring
... = k ^ 2 * (z * z) : by rw h.eq
... = (k * z) * (k * z) : by ring }
end
omit h
/-- `(k*x, k*y, k*z)` is a Pythagorean triple if and only if
`(x, y, z)` is also a triple. -/
lemma mul_iff (k : ℤ) (hk : k ≠ 0) :
pythagorean_triple (k * x) (k * y) (k * z) ↔ pythagorean_triple x y z :=
begin
refine ⟨_, λ h, h.mul k⟩,
simp only [pythagorean_triple],
intro h,
rw ← mul_left_inj' (mul_ne_zero hk hk),
convert h using 1; ring,
end
include h
/-- A Pythagorean triple `x, y, z` is “classified” if there exist integers `k, m, n` such that
either
* `x = k * (m ^ 2 - n ^ 2)` and `y = k * (2 * m * n)`, or
* `x = k * (2 * m * n)` and `y = k * (m ^ 2 - n ^ 2)`. -/
@[nolint unused_arguments] def is_classified := ∃ (k m n : ℤ),
((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n))
∨ (x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2)))
∧ int.gcd m n = 1
/-- A primitive pythogorean triple `x, y, z` is a pythagorean triple with `x` and `y` coprime.
Such a triple is “primitively classified” if there exist coprime integers `m, n` such that either
* `x = m ^ 2 - n ^ 2` and `y = 2 * m * n`, or
* `x = 2 * m * n` and `y = m ^ 2 - n ^ 2`.
-/
@[nolint unused_arguments] def is_primitive_classified := ∃ (m n : ℤ),
((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n)
∨ (x = 2 * m * n ∧ y = m ^ 2 - n ^ 2))
∧ int.gcd m n = 1
∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0))
lemma mul_is_classified (k : ℤ) (hc : h.is_classified) : (h.mul k).is_classified :=
begin
obtain ⟨l, m, n, ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co⟩⟩ := hc,
{ use [k * l, m, n], apply and.intro _ co, left, split; ring },
{ use [k * l, m, n], apply and.intro _ co, right, split; ring },
end
lemma even_odd_of_coprime (hc : int.gcd x y = 1) :
(x % 2 = 0 ∧ y % 2 = 1) ∨ (x % 2 = 1 ∧ y % 2 = 0) :=
begin
cases int.mod_two_eq_zero_or_one x with hx hx;
cases int.mod_two_eq_zero_or_one y with hy hy,
{ -- x even, y even
exfalso,
apply nat.not_coprime_of_dvd_of_dvd (dec_trivial : 1 < 2) _ _ hc,
{ apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hx },
{ apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hy } },
{ left, exact ⟨hx, hy⟩ }, -- x even, y odd
{ right, exact ⟨hx, hy⟩ }, -- x odd, y even
{ -- x odd, y odd
exfalso,
obtain ⟨x0, y0, rfl, rfl⟩ : ∃ x0 y0, x = x0* 2 + 1 ∧ y = y0 * 2 + 1,
{ cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hx) with x0 hx2,
cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hy) with y0 hy2,
rw sub_eq_iff_eq_add at hx2 hy2, exact ⟨x0, y0, hx2, hy2⟩ },
have hz : (z * z) % 4 = 2,
{ rw show z * z = 4 * (x0 * x0 + x0 + y0 * y0 + y0) + 2, by { rw ← h.eq, ring },
simp only [int.add_mod, int.mul_mod_right, int.mod_mod, zero_add], refl },
have : ∀ (k : ℤ), 0 ≤ k → k < 4 → k * k % 4 ≠ 2 := dec_trivial,
have h4 : (4 : ℤ) ≠ 0 := dec_trivial,
apply this (z % 4) (int.mod_nonneg z h4) (int.mod_lt z h4),
rwa [← int.mul_mod] },
end
lemma gcd_dvd : (int.gcd x y : ℤ) ∣ z :=
begin
by_cases h0 : int.gcd x y = 0,
{ have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 },
have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 },
have hz : z = 0,
{ simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h },
simp only [hz, dvd_zero], },
obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ :
∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k :=
int.exists_gcd_one' (nat.pos_of_ne_zero h0),
rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul],
rw [← int.pow_dvd_pow_iff (dec_trivial : 0 < 2), pow_two z, ← h.eq],
rw (by ring : x0 * k * (x0 * k) + y0 * k * (y0 * k) = k ^ 2 * (x0 * x0 + y0 * y0)),
exact dvd_mul_right _ _
end
lemma normalize : pythagorean_triple (x / int.gcd x y) (y / int.gcd x y) (z / int.gcd x y) :=
begin
by_cases h0 : int.gcd x y = 0,
{ have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 },
have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 },
have hz : z = 0,
{ simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h },
simp only [hx, hy, hz, int.zero_div], exact zero },
rcases h.gcd_dvd with ⟨z0, rfl⟩,
obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ :
∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k :=
int.exists_gcd_one' (nat.pos_of_ne_zero h0),
have hk : (k : ℤ) ≠ 0, { norm_cast, rwa pos_iff_ne_zero at k0 },
rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul] at h ⊢,
rw [mul_comm x0, mul_comm y0, mul_iff k hk] at h,
rwa [int.mul_div_cancel _ hk, int.mul_div_cancel _ hk, int.mul_div_cancel_left _ hk],
end
lemma is_classified_of_is_primitive_classified (hp : h.is_primitive_classified) :
h.is_classified :=
begin
obtain ⟨m, n, H⟩ := hp,
use [1, m, n],
rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩;
{ apply and.intro _ co, rw one_mul, rw one_mul, tauto }
end
lemma is_classified_of_normalize_is_primitive_classified
(hc : h.normalize.is_primitive_classified) : h.is_classified :=
begin
convert h.normalize.mul_is_classified (int.gcd x y)
(is_classified_of_is_primitive_classified h.normalize hc);
rw int.mul_div_cancel',
{ exact int.gcd_dvd_left x y },
{ exact int.gcd_dvd_right x y },
{ exact h.gcd_dvd }
end
lemma ne_zero_of_coprime (hc : int.gcd x y = 1) : z ≠ 0 :=
begin
suffices : 0 < z * z, { rintro rfl, norm_num at this },
rw [← h.eq, ← pow_two, ← pow_two],
have hc' : int.gcd x y ≠ 0, { rw hc, exact one_ne_zero },
cases int.ne_zero_of_gcd hc' with hxz hyz,
{ apply lt_add_of_pos_of_le (pow_two_pos_of_ne_zero x hxz) (pow_two_nonneg y) },
{ apply lt_add_of_le_of_pos (pow_two_nonneg x) (pow_two_pos_of_ne_zero y hyz) }
end
lemma is_primitive_classified_of_coprime_of_zero_left (hc : int.gcd x y = 1) (hx : x = 0) :
h.is_primitive_classified :=
begin
subst x,
change nat.gcd 0 (int.nat_abs y) = 1 at hc,
rw [nat.gcd_zero_left (int.nat_abs y)] at hc,
cases int.nat_abs_eq y with hy hy,
{ use [1, 0], rw [hy, hc, int.gcd_zero_right], norm_num },
{ use [0, 1], rw [hy, hc, int.gcd_zero_left], norm_num }
end
lemma coprime_of_coprime (hc : int.gcd x y = 1) : int.gcd y z = 1 :=
begin
by_contradiction H,
obtain ⟨p, hp, hpy, hpz⟩ := nat.prime.not_coprime_iff_dvd.mp H,
apply hp.not_dvd_one,
rw [← hc],
apply nat.dvd_gcd (int.prime.dvd_nat_abs_of_coe_dvd_pow_two hp _ _) hpy,
rw [pow_two, eq_sub_of_add_eq h],
rw [← int.coe_nat_dvd_left] at hpy hpz,
exact dvd_sub (dvd_mul_of_dvd_left (hpz) _) (dvd_mul_of_dvd_left (hpy) _),
end
end pythagorean_triple
section circle_equiv_gen
/-!
### A parametrization of the unit circle
For the classification of pythogorean triples, we will use a parametrization of the unit circle.
-/
variables {K : Type*} [field K]
/-- A parameterization of the unit circle that is useful for classifying Pythagorean triples.
(To be applied in the case where `K = ℚ`.) -/
def circle_equiv_gen (hk : ∀ x : K, 1 + x^2 ≠ 0) :
K ≃ {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} :=
{ to_fun := λ x, ⟨⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩,
by { field_simp [hk x, div_pow], ring },
begin
simp only [ne.def, div_eq_iff (hk x), ←neg_mul_eq_neg_mul, one_mul, neg_add,
sub_eq_add_neg, add_left_inj],
simpa only [eq_neg_iff_add_eq_zero, one_pow] using hk 1,
end⟩,
inv_fun := λ p, (p : K × K).1 / ((p : K × K).2 + 1),
left_inv := λ x,
begin
have h2 : (1 + 1 : K) = 2 := rfl,
have h3 : (2 : K) ≠ 0, { convert hk 1, rw [one_pow 2, h2] },
field_simp [hk x, h2, add_assoc, add_comm, add_sub_cancel'_right, mul_comm],
end,
right_inv := λ ⟨⟨x, y⟩, hxy, hy⟩,
begin
change x ^ 2 + y ^ 2 = 1 at hxy,
have h2 : y + 1 ≠ 0, { apply mt eq_neg_of_add_eq_zero, exact hy },
have h3 : (y + 1) ^ 2 + x ^ 2 = 2 * (y + 1),
{ rw [(add_neg_eq_iff_eq_add.mpr hxy.symm).symm], ring },
have h4 : (2 : K) ≠ 0, { convert hk 1, rw one_pow 2, refl },
simp only [prod.mk.inj_iff, subtype.mk_eq_mk],
split,
{ field_simp [h3], ring },
{ field_simp [h3], rw [← add_neg_eq_iff_eq_add.mpr hxy.symm], ring }
end }
@[simp] lemma circle_equiv_apply (hk : ∀ x : K, 1 + x^2 ≠ 0) (x : K) :
(circle_equiv_gen hk x : K × K) = ⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩ := rfl
@[simp] lemma circle_equiv_symm_apply (hk : ∀ x : K, 1 + x^2 ≠ 0)
(v : {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1}) :
(circle_equiv_gen hk).symm v = (v : K × K).1 / ((v : K × K).2 + 1) := rfl
end circle_equiv_gen
private lemma coprime_pow_two_sub_pow_two_add_of_even_odd {m n : ℤ} (h : int.gcd m n = 1)
(hm : m % 2 = 0) (hn : n % 2 = 1) :
int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 :=
begin
by_contradiction H,
obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H,
rw ← int.coe_nat_dvd_left at hp1 hp2,
have h2m : (p : ℤ) ∣ 2 * m ^ 2, { convert dvd_add hp2 hp1, ring },
have h2n : (p : ℤ) ∣ 2 * n ^ 2, { convert dvd_sub hp2 hp1, ring },
have hmc : p = 2 ∨ p ∣ int.nat_abs m :=
prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2m,
have hnc : p = 2 ∨ p ∣ int.nat_abs n :=
prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2n,
by_cases h2 : p = 2,
{ have h3 : (m ^ 2 + n ^ 2) % 2 = 1, { norm_num [pow_two, int.add_mod, int.mul_mod, hm, hn] },
have h4 : (m ^ 2 + n ^ 2) % 2 = 0, { apply int.mod_eq_zero_of_dvd, rwa h2 at hp2 },
rw h4 at h3, exact zero_ne_one h3 },
{ apply hp.not_dvd_one,
rw ← h,
exact nat.dvd_gcd (or.resolve_left hmc h2) (or.resolve_left hnc h2), }
end
private lemma coprime_pow_two_sub_pow_two_add_of_odd_even {m n : ℤ} (h : int.gcd m n = 1)
(hm : m % 2 = 1) (hn : n % 2 = 0):
int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 :=
begin
rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)],
rw [(by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2), add_comm],
apply coprime_pow_two_sub_pow_two_add_of_even_odd _ hn hm, rwa [int.gcd_comm],
end
private lemma coprime_pow_two_sub_mul_of_even_odd {m n : ℤ} (h : int.gcd m n = 1)
(hm : m % 2 = 0) (hn : n % 2 = 1) :
int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 :=
begin
by_contradiction H,
obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H,
rw ← int.coe_nat_dvd_left at hp1 hp2,
have hnp : ¬ (p : ℤ) ∣ int.gcd m n,
{ rw h, norm_cast, exact mt nat.dvd_one.mp (nat.prime.ne_one hp) },
cases int.prime.dvd_mul hp hp2 with hp2m hpn,
{ rw int.nat_abs_mul at hp2m,
cases (nat.prime.dvd_mul hp).mp hp2m with hp2 hpm,
{ have hp2' : p = 2 := (nat.le_of_dvd zero_lt_two hp2).antisymm hp.two_le,
revert hp1, rw hp2',
apply mt int.mod_eq_zero_of_dvd,
norm_num [pow_two, int.sub_mod, int.mul_mod, hm, hn],
},
apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpm)) hnp,
apply (or_self _).mp, apply int.prime.dvd_mul' hp,
rw (by ring : n * n = - (m ^ 2 - n ^ 2) + m * m),
apply dvd_add (dvd_neg_of_dvd hp1),
exact dvd_mul_of_dvd_left (int.coe_nat_dvd_left.mpr hpm) m
},
rw int.gcd_comm at hnp,
apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpn)) hnp,
apply (or_self _).mp, apply int.prime.dvd_mul' hp,
rw (by ring : m * m = (m ^ 2 - n ^ 2) + n * n),
apply dvd_add hp1,
exact dvd_mul_of_dvd_left (int.coe_nat_dvd_left.mpr hpn) n
end
private lemma coprime_pow_two_sub_mul_of_odd_even {m n : ℤ} (h : int.gcd m n = 1)
(hm : m % 2 = 1) (hn : n % 2 = 0) :
int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 :=
begin
rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)],
rw [(by ring : 2 * m * n = 2 * n * m), (by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2)],
apply coprime_pow_two_sub_mul_of_even_odd _ hn hm, rwa [int.gcd_comm]
end
private lemma coprime_pow_two_sub_mul {m n : ℤ} (h : int.gcd m n = 1)
(hmn : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) :
int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 :=
begin
cases hmn with h1 h2,
{ exact coprime_pow_two_sub_mul_of_even_odd h h1.left h1.right },
{ exact coprime_pow_two_sub_mul_of_odd_even h h2.left h2.right }
end
private lemma coprime_pow_two_sub_pow_two_sum_of_odd_odd {m n : ℤ} (h : int.gcd m n = 1)
(hm : m % 2 = 1) (hn : n % 2 = 1) :
2 ∣ m ^ 2 + n ^ 2
∧ 2 ∣ m ^ 2 - n ^ 2
∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0
∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1 :=
begin
cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hm) with m0 hm2,
cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hn) with n0 hn2,
rw sub_eq_iff_eq_add at hm2 hn2, subst m, subst n,
have h1 : (m0 * 2 + 1) ^ 2 + (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 + n0 ^ 2 + m0 + n0) + 1),
by ring_exp,
have h2 : (m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 - n0 ^ 2 + m0 - n0)),
by ring_exp,
have h3 : ((m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2) / 2 % 2 = 0,
{ rw [h2, int.mul_div_cancel_left, int.mul_mod_right], exact dec_trivial },
refine ⟨⟨_, h1⟩, ⟨_, h2⟩, h3, _⟩,
have h20 : (2:ℤ) ≠ 0 := dec_trivial,
rw [h1, h2, int.mul_div_cancel_left _ h20, int.mul_div_cancel_left _ h20],
by_contra h4,
obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp h4,
apply hp.not_dvd_one,
rw ← h,
rw ← int.coe_nat_dvd_left at hp1 hp2,
apply nat.dvd_gcd,
{ apply int.prime.dvd_nat_abs_of_coe_dvd_pow_two hp,
convert dvd_add hp1 hp2, ring_exp },
{ apply int.prime.dvd_nat_abs_of_coe_dvd_pow_two hp,
convert dvd_sub hp2 hp1, ring_exp },
end
namespace pythagorean_triple
variables {x y z : ℤ} (h : pythagorean_triple x y z)
include h
lemma is_primitive_classified_aux (hc : x.gcd y = 1) (hzpos : 0 < z)
{m n : ℤ} (hm2n2 : 0 < m ^ 2 + n ^ 2)
(hv2 : (x : ℚ) / z = 2 * m * n / (m ^ 2 + n ^ 2))
(hw2 : (y : ℚ) / z = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2))
(H : int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1)
(co : int.gcd m n = 1)
(pp : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)):
h.is_primitive_classified :=
begin
have hz : z ≠ 0, apply ne_of_gt hzpos,
have h2 : y = m ^ 2 - n ^ 2 ∧ z = m ^ 2 + n ^ 2,
{ apply rat.div_int_inj hzpos hm2n2 (h.coprime_of_coprime hc) H, rw [hw2], norm_cast },
use [m, n], apply and.intro _ (and.intro co pp), right,
refine ⟨_, h2.left⟩,
rw [← rat.coe_int_inj _ _, ← div_left_inj' ((mt (rat.coe_int_inj z 0).mp) hz), hv2, h2.right],
norm_cast
end
theorem is_primitive_classified_of_coprime_of_odd_of_pos
(hc : int.gcd x y = 1) (hyo : y % 2 = 1) (hzpos : 0 < z) :
h.is_primitive_classified :=
begin
by_cases h0 : x = 0, { exact h.is_primitive_classified_of_coprime_of_zero_left hc h0 },
let v := (x : ℚ) / z,
let w := (y : ℚ) / z,
have hz : z ≠ 0, apply ne_of_gt hzpos,
have hq : v ^ 2 + w ^ 2 = 1,
{ field_simp [hz, pow_two], norm_cast, exact h },
have hvz : v ≠ 0, { field_simp [hz], exact h0 },
have hw1 : w ≠ -1,
{ contrapose! hvz with hw1,
rw [hw1, neg_square, one_pow, add_left_eq_self] at hq,
exact pow_eq_zero hq, },
have hQ : ∀ x : ℚ, 1 + x^2 ≠ 0,
{ intro q, apply ne_of_gt, exact lt_add_of_pos_of_le zero_lt_one (pow_two_nonneg q) },
have hp : (⟨v, w⟩ : ℚ × ℚ) ∈ {p : ℚ × ℚ | p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} := ⟨hq, hw1⟩,
let q := (circle_equiv_gen hQ).symm ⟨⟨v, w⟩, hp⟩,
have ht4 : v = 2 * q / (1 + q ^ 2) ∧ w = (1 - q ^ 2) / (1 + q ^ 2),
{ apply prod.mk.inj,
have := ((circle_equiv_gen hQ).apply_symm_apply ⟨⟨v, w⟩, hp⟩).symm,
exact congr_arg subtype.val this, },
let m := (q.denom : ℤ),
let n := q.num,
have hm0 : m ≠ 0, { norm_cast, apply rat.denom_ne_zero q },
have hq2 : q = n / m, { rw [int.cast_coe_nat], exact (rat.cast_id q).symm },
have hm2n2 : 0 < m ^ 2 + n ^ 2,
{ apply lt_add_of_pos_of_le _ (pow_two_nonneg n),
exact lt_of_le_of_ne (pow_two_nonneg m) (ne.symm (pow_ne_zero 2 hm0)) },
have hw2 : w = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2),
{ rw [ht4.2, hq2], field_simp [hm2n2, (rat.denom_ne_zero q)] },
have hm2n20 : (m : ℚ) ^ 2 + (n : ℚ) ^ 2 ≠ 0,
{ norm_cast, simpa only [int.coe_nat_pow] using ne_of_gt hm2n2 },
have hv2 : v = 2 * m * n / (m ^ 2 + n ^ 2),
{ apply eq.symm, apply (div_eq_iff hm2n20).mpr, rw [ht4.1], field_simp [hQ q],
rw [hq2] {occs := occurrences.pos [2, 3]}, field_simp [rat.denom_ne_zero q], ring },
have hnmcp : int.gcd n m = 1 := q.cop,
have hmncp : int.gcd m n = 1, { rw int.gcd_comm, exact hnmcp },
cases int.mod_two_eq_zero_or_one m with hm2 hm2;
cases int.mod_two_eq_zero_or_one n with hn2 hn2,
{ -- m even, n even
exfalso,
have h1 : 2 ∣ (int.gcd n m : ℤ),
{ exact int.dvd_gcd (int.dvd_of_mod_eq_zero hn2) (int.dvd_of_mod_eq_zero hm2) },
rw hnmcp at h1, revert h1, norm_num },
{ -- m even, n odd
apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp,
{ apply or.intro_left, exact and.intro hm2 hn2 },
{ apply coprime_pow_two_sub_pow_two_add_of_even_odd hmncp hm2 hn2 } },
{ -- m odd, n even
apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp,
{ apply or.intro_right, exact and.intro hm2 hn2 },
apply coprime_pow_two_sub_pow_two_add_of_odd_even hmncp hm2 hn2 },
{ -- m odd, n odd
exfalso,
have h1 : 2 ∣ m ^ 2 + n ^ 2 ∧ 2 ∣ m ^ 2 - n ^ 2
∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0 ∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1,
{ exact coprime_pow_two_sub_pow_two_sum_of_odd_odd hmncp hm2 hn2 },
have h2 : y = (m ^ 2 - n ^ 2) / 2 ∧ z = (m ^ 2 + n ^ 2) / 2,
{ apply rat.div_int_inj hzpos _ (h.coprime_of_coprime hc) h1.2.2.2,
{ show w = _, rw [←rat.mk_eq_div, ←(rat.div_mk_div_cancel_left (by norm_num : (2 : ℤ) ≠ 0))],
rw [int.div_mul_cancel h1.1, int.div_mul_cancel h1.2.1, hw2], norm_cast },
{ apply (mul_lt_mul_right (by norm_num : 0 < (2 : ℤ))).mp,
rw [int.div_mul_cancel h1.1, zero_mul], exact hm2n2 } },
rw [h2.1, h1.2.2.1] at hyo,
revert hyo,
norm_num }
end
theorem is_primitive_classified_of_coprime_of_pos (hc : int.gcd x y = 1) (hzpos : 0 < z):
h.is_primitive_classified :=
begin
cases h.even_odd_of_coprime hc with h1 h2,
{ exact (h.is_primitive_classified_of_coprime_of_odd_of_pos hc h1.right hzpos) },
rw int.gcd_comm at hc,
obtain ⟨m, n, H⟩ := (h.symm.is_primitive_classified_of_coprime_of_odd_of_pos hc h2.left hzpos),
use [m, n], tauto
end
theorem is_primitive_classified_of_coprime (hc : int.gcd x y = 1) : h.is_primitive_classified :=
begin
by_cases hz : 0 < z,
{ exact h.is_primitive_classified_of_coprime_of_pos hc hz },
have h' : pythagorean_triple x y (-z),
{ simpa [pythagorean_triple, neg_mul_neg] using h.eq, },
apply h'.is_primitive_classified_of_coprime_of_pos hc,
apply lt_of_le_of_ne _ (h'.ne_zero_of_coprime hc).symm,
exact le_neg.mp (not_lt.mp hz)
end
theorem classified : h.is_classified :=
begin
by_cases h0 : int.gcd x y = 0,
{ have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 },
have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 },
use [0, 1, 0], norm_num [hx, hy], },
apply h.is_classified_of_normalize_is_primitive_classified,
apply h.normalize.is_primitive_classified_of_coprime,
apply int.gcd_div_gcd_div_gcd (nat.pos_of_ne_zero h0),
end
omit h
theorem coprime_classification :
pythagorean_triple x y z ∧ int.gcd x y = 1 ↔
∃ m n, ((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n) ∨
(x = 2 * m * n ∧ y = m ^ 2 - n ^ 2))
∧ (z = m ^ 2 + n ^ 2 ∨ z = - (m ^ 2 + n ^ 2))
∧ int.gcd m n = 1
∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) :=
begin
split,
{ intro h,
obtain ⟨m, n, H⟩ := h.left.is_primitive_classified_of_coprime h.right,
use [m, n],
rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩,
{ refine ⟨or.inl ⟨rfl, rfl⟩, _, co, pp⟩,
have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2,
{ rw [pow_two, ← h.left.eq], ring },
simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this },
{ refine ⟨or.inr ⟨rfl, rfl⟩, _, co, pp⟩,
have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2,
{ rw [pow_two, ← h.left.eq], ring },
simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this } },
{ delta pythagorean_triple,
rintro ⟨m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl, co, pp⟩;
{ split, { ring }, exact coprime_pow_two_sub_mul co pp }
<|>
{ split, { ring }, rw int.gcd_comm, exact coprime_pow_two_sub_mul co pp } }
end
/-- by assuming `x` is odd and `z` is positive we get a slightly more precise classification of
the pythagorean triple `x ^ 2 + y ^ 2 = z ^ 2`-/
theorem coprime_classification' {x y z : ℤ} (h : pythagorean_triple x y z)
(h_coprime : int.gcd x y = 1) (h_parity : x % 2 = 1) (h_pos : 0 < z) :
∃ m n, x = m ^ 2 - n ^ 2
∧ y = 2 * m * n
∧ z = m ^ 2 + n ^ 2
∧ int.gcd m n = 1
∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0))
∧ 0 ≤ m :=
begin
obtain ⟨m, n, ht1, ht2, ht3, ht4⟩ :=
pythagorean_triple.coprime_classification.mp (and.intro h h_coprime),
cases le_or_lt 0 m with hm hm,
{ use [m, n],
cases ht1 with h_odd h_even,
{ apply and.intro h_odd.1,
apply and.intro h_odd.2,
cases ht2 with h_pos h_neg,
{ apply and.intro h_pos (and.intro ht3 (and.intro ht4 hm)) },
{ exfalso, revert h_pos, rw h_neg,
exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (pow_two_nonneg m)
(pow_two_nonneg n)))) } },
exfalso,
rcases h_even with ⟨rfl, -⟩,
rw [mul_assoc, int.mul_mod_right] at h_parity,
exact zero_ne_one h_parity },
{ use [-m, -n],
cases ht1 with h_odd h_even,
{ rw [neg_square m],
rw [neg_square n],
apply and.intro h_odd.1,
split, { rw h_odd.2, ring },
cases ht2 with h_pos h_neg,
{ apply and.intro h_pos,
split,
{ delta int.gcd, rw [int.nat_abs_neg, int.nat_abs_neg], exact ht3 },
{ rw [int.neg_mod_two, int.neg_mod_two],
apply and.intro ht4, linarith } },
{ exfalso, revert h_pos, rw h_neg,
exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (pow_two_nonneg m)
(pow_two_nonneg n)))) } },
exfalso,
rcases h_even with ⟨rfl, -⟩,
rw [mul_assoc, int.mul_mod_right] at h_parity,
exact zero_ne_one h_parity }
end
theorem classification :
pythagorean_triple x y z ↔
∃ k m n, ((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n)) ∨
(x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2)))
∧ (z = k * (m ^ 2 + n ^ 2) ∨ z = - k * (m ^ 2 + n ^ 2)) :=
begin
split,
{ intro h,
obtain ⟨k, m, n, H⟩ := h.classified,
use [k, m, n],
rcases H with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩,
{ refine ⟨or.inl ⟨rfl, rfl⟩, _⟩,
have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2,
{ rw [pow_two, ← h.eq], ring },
simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this },
{ refine ⟨or.inr ⟨rfl, rfl⟩, _⟩,
have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2,
{ rw [pow_two, ← h.eq], ring },
simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this } },
{ rintro ⟨k, m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl⟩;
delta pythagorean_triple; ring }
end
end pythagorean_triple
|
d64ef4417b7ee2da482140a91ccbedc8f66de322 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/analysis/calculus/uniform_limits_deriv.lean | 4416629d8836d7a767a1cb30bb96aa03d41f07fa | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 25,929 | lean | /-
Copyright (c) 2022 Kevin H. Wilson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin H. Wilson
-/
import analysis.calculus.mean_value
import analysis.normed_space.is_R_or_C
import order.filter.curry
/-!
# Swapping limits and derivatives via uniform convergence
The purpose of this file is to prove that the derivative of the pointwise limit of a sequence of
functions is the pointwise limit of the functions' derivatives when the derivatives converge
_uniformly_. The formal statement appears as `has_fderiv_at_of_tendsto_locally_uniformly_at`.
## Main statements
* `uniform_cauchy_seq_on_filter_of_tendsto_uniformly_on_filter_fderiv`: If
1. `f : ℕ → E → G` is a sequence of functions which have derivatives
`f' : ℕ → E → (E →L[𝕜] G)` on a neighborhood of `x`,
2. the functions `f` converge at `x`, and
3. the derivatives `f'` converge uniformly on a neighborhood of `x`,
then the `f` converge _uniformly_ on a neighborhood of `x`
* `has_fderiv_at_of_tendsto_uniformly_on_filter` : Suppose (1), (2), and (3) above are true. Let
`g` (resp. `g'`) be the limiting function of the `f` (resp. `g'`). Then `f'` is the derivative of
`g` on a neighborhood of `x`
* `has_fderiv_at_of_tendsto_uniformly_on`: An often-easier-to-use version of the above theorem when
*all* the derivatives exist and functions converge on a common open set and the derivatives
converge uniformly there.
Each of the above statements also has variations that support `deriv` instead of `fderiv`.
## Implementation notes
Our technique for proving the main result is the famous "`ε / 3` proof." In words, you can find it
explained, for instance, at [this StackExchange post](https://math.stackexchange.com/questions/214218/uniform-convergence-of-derivatives-tao-14-2-7).
The subtlety is that we want to prove that the difference quotients of the `g` converge to the `g'`.
That is, we want to prove something like:
```
∀ ε > 0, ∃ δ > 0, ∀ y ∈ B_δ(x), |y - x|⁻¹ * |(g y - g x) - g' x (y - x)| < ε.
```
To do so, we will need to introduce a pair of quantifers
```lean
∀ ε > 0, ∃ N, ∀ n ≥ N, ∃ δ > 0, ∀ y ∈ B_δ(x), |y - x|⁻¹ * |(g y - g x) - g' x (y - x)| < ε.
```
So how do we write this in terms of filters? Well, the initial definition of the derivative is
```lean
tendsto (|y - x|⁻¹ * |(g y - g x) - g' x (y - x)|) (𝓝 x) (𝓝 0)
```
There are two ways we might introduce `n`. We could do:
```lean
∀ᶠ (n : ℕ) in at_top, tendsto (|y - x|⁻¹ * |(g y - g x) - g' x (y - x)|) (𝓝 x) (𝓝 0)
```
but this is equivalent to the quantifier order `∃ N, ∀ n ≥ N, ∀ ε > 0, ∃ δ > 0, ∀ y ∈ B_δ(x)`,
which _implies_ our desired `∀ ∃ ∀ ∃ ∀` but is _not_ equivalent to it. On the other hand, we might
try
```lean
tendsto (|y - x|⁻¹ * |(g y - g x) - g' x (y - x)|) (at_top ×ᶠ 𝓝 x) (𝓝 0)
```
but this is equivalent to the quantifer order `∀ ε > 0, ∃ N, ∃ δ > 0, ∀ n ≥ N, ∀ y ∈ B_δ(x)`, which
again _implies_ our desired `∀ ∃ ∀ ∃ ∀` but is not equivalent to it.
So to get the quantifier order we want, we need to introduce a new filter construction, which we
call a "curried filter"
```lean
tendsto (|y - x|⁻¹ * |(g y - g x) - g' x (y - x)|) (at_top.curry (𝓝 x)) (𝓝 0)
```
Then the above implications are `filter.tendsto.curry` and
`filter.tendsto.mono_left filter.curry_le_prod`. We will use both of these deductions as part of
our proof.
We note that if you loosen the assumptions of the main theorem then the proof becomes quite a bit
easier. In particular, if you assume there is a common neighborhood `s` where all of the three
assumptions of `has_fderiv_at_of_tendsto_uniformly_on_filter` hold and that the `f'` are
continuous, then you can avoid the mean value theorem and much of the work around curried filters.
## Tags
uniform convergence, limits of derivatives
-/
open filter
open_locale uniformity filter topological_space
section limits_of_derivatives
variables {ι : Type*} {l : filter ι} [ne_bot l]
{E : Type*} [normed_add_comm_group E] [normed_space ℝ E]
{𝕜 : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E]
{G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G]
{f : ι → E → G} {g : E → G} {f' : ι → (E → (E →L[𝕜] G))} {g' : E → (E →L[𝕜] G)}
{x : E}
/-- If a sequence of functions real or complex functions are eventually differentiable on a
neighborhood of `x`, they converge pointwise _at_ `x`, and their derivatives
converge uniformly in a neighborhood of `x`, then the functions form a uniform Cauchy sequence
in a neighborhood of `x`. -/
lemma uniform_cauchy_seq_on_filter_of_tendsto_uniformly_on_filter_fderiv
(hf' : uniform_cauchy_seq_on_filter f' l (𝓝 x))
(hf : ∀ᶠ (n : ι × E) in (l ×ᶠ 𝓝 x), has_fderiv_at (f n.1) (f' n.1 n.2) n.2)
(hfg : tendsto (λ n, f n x) l (𝓝 (g x))) :
uniform_cauchy_seq_on_filter f l (𝓝 x) :=
begin
rw normed_add_comm_group.uniform_cauchy_seq_on_filter_iff_tendsto_uniformly_on_filter_zero at
hf' ⊢,
suffices : tendsto_uniformly_on_filter
(λ (n : ι × ι) (z : E), f n.1 z - f n.2 z - (f n.1 x - f n.2 x)) 0 (l ×ᶠ l) (𝓝 x) ∧
tendsto_uniformly_on_filter (λ (n : ι × ι) (z : E), f n.1 x - f n.2 x) 0 (l ×ᶠ l) (𝓝 x),
{ have := this.1.add this.2,
rw add_zero at this,
exact this.congr (by simp), },
split,
{ -- This inequality follows from the mean value theorem. To apply it, we will need to shrink our
-- neighborhood to small enough ball
rw metric.tendsto_uniformly_on_filter_iff at hf' ⊢,
intros ε hε,
have := (tendsto_swap4_prod.eventually (hf.prod_mk hf)).diag_of_prod_right,
obtain ⟨a, b, c, d, e⟩ := eventually_prod_iff.1 ((hf' ε hε).and this),
obtain ⟨R, hR, hR'⟩ := metric.nhds_basis_ball.eventually_iff.mp d,
let r := min 1 R,
have hr : 0 < r, { simp [hR], },
have hr' : ∀ ⦃y : E⦄, y ∈ metric.ball x r → c y,
{ exact (λ y hy, hR' (lt_of_lt_of_le (metric.mem_ball.mp hy) (min_le_right _ _))), },
have hxy : ∀ (y : E), y ∈ metric.ball x r → ∥y - x∥ < 1,
{ intros y hy,
rw [metric.mem_ball, dist_eq_norm] at hy,
exact lt_of_lt_of_le hy (min_le_left _ _), },
have hxyε : ∀ (y : E), y ∈ metric.ball x r → ε * ∥y - x∥ < ε,
{ intros y hy,
exact (mul_lt_iff_lt_one_right hε.lt).mpr (hxy y hy), },
-- With a small ball in hand, apply the mean value theorem
refine eventually_prod_iff.mpr ⟨_, b, (λ e : E, metric.ball x r e),
eventually_mem_set.mpr (metric.nhds_basis_ball.mem_of_mem hr), (λ n hn y hy, _)⟩,
simp only [pi.zero_apply, dist_zero_left] at e ⊢,
refine lt_of_le_of_lt _ (hxyε y hy),
exact convex.norm_image_sub_le_of_norm_has_fderiv_within_le
(λ y hy, ((e hn (hr' hy)).2.1.sub (e hn (hr' hy)).2.2).has_fderiv_within_at)
(λ y hy, (e hn (hr' hy)).1.le)
(convex_ball x r) (metric.mem_ball_self hr) hy, },
{ -- This is just `hfg` run through `eventually_prod_iff`
refine metric.tendsto_uniformly_on_filter_iff.mpr (λ ε hε, _),
obtain ⟨t, ht, ht'⟩ := (metric.cauchy_iff.mp hfg.cauchy_map).2 ε hε,
exact eventually_prod_iff.mpr
⟨ (λ (n : ι × ι), (f n.1 x ∈ t) ∧ (f n.2 x ∈ t)),
eventually_prod_iff.mpr ⟨_, ht, _, ht, (λ n hn n' hn', ⟨hn, hn'⟩)⟩,
(λ y, true),
(by simp),
(λ n hn y hy, by simpa [norm_sub_rev, dist_eq_norm] using ht' _ hn.1 _ hn.2)⟩, },
end
/-- A variant of the second fundamental theorem of calculus (FTC-2): If a sequence of functions
between real or complex normed spaces are differentiable on a ball centered at `x`, they
converge pointwise _at_ `x`, and their derivatives converge uniformly on the ball, then the
functions form a uniform Cauchy sequence on the ball.
NOTE: The fact that we work on a ball is typically all that is necessary to work with power series
and Dirichlet series (our primary use case). However, this can be generalized by replacing the ball
with any connected, bounded, open set and replacing uniform convergence with local uniform
convergence.
-/
lemma uniform_cauchy_seq_on_ball_of_tendsto_uniformly_on_ball_fderiv
{r : ℝ} (hr : 0 < r)
(hf' : uniform_cauchy_seq_on f' l (metric.ball x r))
(hf : ∀ n : ι, ∀ y : E, y ∈ metric.ball x r → has_fderiv_at (f n) (f' n y) y)
(hfg : tendsto (λ n, f n x) l (𝓝 (g x))) :
uniform_cauchy_seq_on f l (metric.ball x r) :=
begin
rw normed_add_comm_group.uniform_cauchy_seq_on_iff_tendsto_uniformly_on_zero at hf' ⊢,
suffices : tendsto_uniformly_on
(λ (n : ι × ι) (z : E), f n.1 z - f n.2 z - (f n.1 x - f n.2 x)) 0
(l ×ᶠ l) (metric.ball x r) ∧
tendsto_uniformly_on (λ (n : ι × ι) (z : E), f n.1 x - f n.2 x) 0
(l ×ᶠ l) (metric.ball x r),
{ have := this.1.add this.2,
rw add_zero at this,
refine this.congr _,
apply eventually_of_forall,
intros n z hz,
simp, },
split,
{ -- This inequality follows from the mean value theorem
rw metric.tendsto_uniformly_on_iff at hf' ⊢,
intros ε hε,
obtain ⟨q, hqpos, hq⟩ : ∃ q : ℝ, 0 < q ∧ q * r < ε,
{ simp_rw mul_comm,
exact exists_pos_mul_lt hε.lt r, },
apply (hf' q hqpos.gt).mono,
intros n hn y hy,
simp_rw [dist_eq_norm, pi.zero_apply, zero_sub, norm_neg] at hn ⊢,
have mvt := convex.norm_image_sub_le_of_norm_has_fderiv_within_le
(λ z hz, ((hf n.1 z hz).sub (hf n.2 z hz)).has_fderiv_within_at)
(λ z hz, (hn z hz).le) (convex_ball x r) (metric.mem_ball_self hr) hy,
refine lt_of_le_of_lt mvt _,
have : q * ∥y - x∥ < q * r,
{ exact mul_lt_mul' rfl.le (by simpa only [dist_eq_norm] using metric.mem_ball.mp hy)
(norm_nonneg _) hqpos, },
exact this.trans hq, },
{ -- This is just `hfg` run through `eventually_prod_iff`
refine metric.tendsto_uniformly_on_iff.mpr (λ ε hε, _),
obtain ⟨t, ht, ht'⟩ := (metric.cauchy_iff.mp hfg.cauchy_map).2 ε hε,
rw eventually_prod_iff,
refine ⟨(λ n, f n x ∈ t), ht, (λ n, f n x ∈ t), ht, _⟩,
intros n hn n' hn' z hz,
rw [dist_eq_norm, pi.zero_apply, zero_sub, norm_neg, ←dist_eq_norm],
exact (ht' _ hn _ hn'), },
end
/-- If `f_n → g` pointwise and the derivatives `(f_n)' → h` _uniformly_ converge, then
in fact for a fixed `y`, the difference quotients `∥z - y∥⁻¹ • (f_n z - f_n y)` converge
_uniformly_ to `∥z - y∥⁻¹ • (g z - g y)` -/
lemma difference_quotients_converge_uniformly
(hf' : tendsto_uniformly_on_filter f' g' l (𝓝 x))
(hf : ∀ᶠ (n : ι × E) in (l ×ᶠ 𝓝 x), has_fderiv_at (f n.1) (f' n.1 n.2) n.2)
(hfg : ∀ᶠ (y : E) in 𝓝 x, tendsto (λ n, f n y) l (𝓝 (g y))) :
tendsto_uniformly_on_filter
(λ n : ι, λ y : E, (∥y - x∥⁻¹ : 𝕜) • (f n y - f n x))
(λ y : E, (∥y - x∥⁻¹ : 𝕜) • (g y - g x))
l (𝓝 x) :=
begin
refine uniform_cauchy_seq_on_filter.tendsto_uniformly_on_filter_of_tendsto _
((hfg.and (eventually_const.mpr hfg.self_of_nhds)).mono (λ y hy, (hy.1.sub hy.2).const_smul _)),
rw normed_add_comm_group.uniform_cauchy_seq_on_filter_iff_tendsto_uniformly_on_filter_zero,
rw metric.tendsto_uniformly_on_filter_iff,
have hfg' := hf'.uniform_cauchy_seq_on_filter,
rw normed_add_comm_group.uniform_cauchy_seq_on_filter_iff_tendsto_uniformly_on_filter_zero at
hfg',
rw metric.tendsto_uniformly_on_filter_iff at hfg',
intros ε hε,
obtain ⟨q, hqpos, hqε⟩ := exists_pos_rat_lt hε,
specialize hfg' (q : ℝ) (by simp [hqpos]),
have := (tendsto_swap4_prod.eventually (hf.prod_mk hf)).diag_of_prod_right,
obtain ⟨a, b, c, d, e⟩ := eventually_prod_iff.1 (hfg'.and this),
obtain ⟨r, hr, hr'⟩ := metric.nhds_basis_ball.eventually_iff.mp d,
rw eventually_prod_iff,
refine ⟨_, b, (λ e : E, metric.ball x r e),
eventually_mem_set.mpr (metric.nhds_basis_ball.mem_of_mem hr), (λ n hn y hy, _)⟩,
simp only [pi.zero_apply, dist_zero_left],
rw [← smul_sub, norm_smul, norm_inv, is_R_or_C.norm_coe_norm],
refine lt_of_le_of_lt _ hqε,
by_cases hyz' : x = y, { simp [hyz', hqpos.le], },
have hyz : 0 < ∥y - x∥,
{rw norm_pos_iff, intros hy', exact hyz' (eq_of_sub_eq_zero hy').symm, },
rw [inv_mul_le_iff hyz, mul_comm, sub_sub_sub_comm],
simp only [pi.zero_apply, dist_zero_left] at e,
refine convex.norm_image_sub_le_of_norm_has_fderiv_within_le
(λ y hy, ((e hn (hr' hy)).2.1.sub (e hn (hr' hy)).2.2).has_fderiv_within_at)
(λ y hy, (e hn (hr' hy)).1.le)
(convex_ball x r) (metric.mem_ball_self hr) hy,
end
/-- `(d/dx) lim_{n → ∞} f n x = lim_{n → ∞} f' n x` when the `f' n` converge
_uniformly_ to their limit at `x`.
In words the assumptions mean the following:
* `hf'`: The `f'` converge "uniformly at" `x` to `g'`. This does not mean that the `f' n` even
converge away from `x`!
* `hf`: For all `(y, n)` with `y` sufficiently close to `x` and `n` sufficiently large, `f' n` is
the derivative of `f n`
* `hfg`: The `f n` converge pointwise to `g` on a neighborhood of `x` -/
lemma has_fderiv_at_of_tendsto_uniformly_on_filter
(hf' : tendsto_uniformly_on_filter f' g' l (𝓝 x))
(hf : ∀ᶠ (n : ι × E) in (l ×ᶠ 𝓝 x), has_fderiv_at (f n.1) (f' n.1 n.2) n.2)
(hfg : ∀ᶠ y in 𝓝 x, tendsto (λ n, f n y) l (𝓝 (g y))) :
has_fderiv_at g (g' x) x :=
begin
-- The proof strategy follows several steps:
-- 1. The quantifiers in the definition of the derivative are
-- `∀ ε > 0, ∃δ > 0, ∀y ∈ B_δ(x)`. We will introduce a quantifier in the middle:
-- `∀ ε > 0, ∃N, ∀n ≥ N, ∃δ > 0, ∀y ∈ B_δ(x)` which will allow us to introduce the `f(') n`
-- 2. The order of the quantifiers `hfg` are opposite to what we need. We will be able to swap
-- the quantifiers using the uniform convergence assumption
rw has_fderiv_at_iff_tendsto,
-- Introduce extra quantifier via curried filters
suffices : tendsto
(λ (y : ι × E), ∥y.2 - x∥⁻¹ * ∥g y.2 - g x - (g' x) (y.2 - x)∥) (l.curry (𝓝 x)) (𝓝 0),
{ rw metric.tendsto_nhds at this ⊢,
intros ε hε,
specialize this ε hε,
rw eventually_curry_iff at this,
simp only at this,
exact (eventually_const.mp this).mono (by simp only [imp_self, forall_const]), },
-- With the new quantifier in hand, we can perform the famous `ε/3` proof. Specifically,
-- we will break up the limit (the difference functions minus the derivative go to 0) into 3:
-- * The difference functions of the `f n` converge *uniformly* to the difference functions
-- of the `g n`
-- * The `f' n` are the derivatives of the `f n`
-- * The `f' n` converge to `g'` at `x`
conv
{ congr, funext,
rw [←norm_norm, ←norm_inv,←@is_R_or_C.norm_of_real 𝕜 _ _,
is_R_or_C.of_real_inv, ←norm_smul], },
rw ←tendsto_zero_iff_norm_tendsto_zero,
have : (λ a : ι × E, (∥a.2 - x∥⁻¹ : 𝕜) • (g a.2 - g x - (g' x) (a.2 - x))) =
(λ a : ι × E, (∥a.2 - x∥⁻¹ : 𝕜) • (g a.2 - g x - (f a.1 a.2 - f a.1 x))) +
(λ a : ι × E, (∥a.2 - x∥⁻¹ : 𝕜) • ((f a.1 a.2 - f a.1 x) -
((f' a.1 x) a.2 - (f' a.1 x) x))) +
(λ a : ι × E, (∥a.2 - x∥⁻¹ : 𝕜) • ((f' a.1 x - g' x) (a.2 - x))),
{ ext, simp only [pi.add_apply], rw [←smul_add, ←smul_add], congr,
simp only [map_sub, sub_add_sub_cancel, continuous_linear_map.coe_sub', pi.sub_apply], },
simp_rw this,
have : 𝓝 (0 : G) = 𝓝 (0 + 0 + 0), simp only [add_zero],
rw this,
refine tendsto.add (tendsto.add _ _) _,
simp only,
{ have := difference_quotients_converge_uniformly hf' hf hfg,
rw metric.tendsto_uniformly_on_filter_iff at this,
rw metric.tendsto_nhds,
intros ε hε,
apply ((this ε hε).filter_mono curry_le_prod).mono,
intros n hn,
rw dist_eq_norm at hn ⊢,
rw ← smul_sub at hn,
rwa sub_zero, },
{ -- (Almost) the definition of the derivatives
rw metric.tendsto_nhds,
intros ε hε,
rw eventually_curry_iff,
refine hf.curry.mono (λ n hn, _),
have := hn.self_of_nhds,
rw [has_fderiv_at_iff_tendsto, metric.tendsto_nhds] at this,
refine (this ε hε).mono (λ y hy, _),
rw dist_eq_norm at hy ⊢,
simp only [sub_zero, map_sub, norm_mul, norm_inv, norm_norm] at hy ⊢,
rw [norm_smul, norm_inv, is_R_or_C.norm_coe_norm],
exact hy, },
{ -- hfg' after specializing to `x` and applying the definition of the operator norm
refine tendsto.mono_left _ curry_le_prod,
have h1: tendsto (λ n : ι × E, g' n.2 - f' n.1 n.2) (l ×ᶠ 𝓝 x) (𝓝 0),
{ rw metric.tendsto_uniformly_on_filter_iff at hf',
exact metric.tendsto_nhds.mpr (λ ε hε, by simpa using hf' ε hε), },
have h2: tendsto (λ n : ι, g' x - f' n x) l (𝓝 0),
{ rw metric.tendsto_nhds at h1 ⊢,
exact (λ ε hε, (h1 ε hε).curry.mono (λ n hn, hn.self_of_nhds)), },
have := (tendsto_fst.comp (h2.prod_map tendsto_id)),
refine squeeze_zero_norm _ (tendsto_zero_iff_norm_tendsto_zero.mp this),
intros n,
simp_rw [norm_smul, norm_inv, is_R_or_C.norm_coe_norm],
by_cases hx : x = n.2, { simp [hx], },
have hnx : 0 < ∥n.2 - x∥,
{ rw norm_pos_iff, intros hx', exact hx (eq_of_sub_eq_zero hx').symm, },
rw [inv_mul_le_iff hnx, mul_comm],
simp only [function.comp_app, prod_map],
rw norm_sub_rev,
exact (f' n.1 x - g' x).le_op_norm (n.2 - x), },
end
/-- `(d/dx) lim_{n → ∞} f n x = lim_{n → ∞} f' n x` when the `f' n` converge
_uniformly_ to their limit on an open set containing `x`. -/
lemma has_fderiv_at_of_tendsto_uniformly_on
{s : set E} (hs : is_open s)
(hf' : tendsto_uniformly_on f' g' l s)
(hf : ∀ (n : ι), ∀ (x : E), x ∈ s → has_fderiv_at (f n) (f' n x) x)
(hfg : ∀ (x : E), x ∈ s → tendsto (λ n, f n x) l (𝓝 (g x))) :
∀ (x : E), x ∈ s → has_fderiv_at g (g' x) x :=
begin
intros x hx,
have hf : ∀ᶠ (n : ι × E) in (l ×ᶠ 𝓝 x), has_fderiv_at (f n.1) (f' n.1 n.2) n.2,
{ exact eventually_prod_iff.mpr ⟨(λ y, true), (by simp), (λ y, y ∈ s),
eventually_mem_set.mpr (mem_nhds_iff.mpr ⟨s, rfl.subset, hs, hx⟩),
(λ n hn y hy, hf n y hy)⟩, },
have hfg : ∀ᶠ y in 𝓝 x, tendsto (λ n, f n y) l (𝓝 (g y)),
{ exact eventually_iff.mpr (mem_nhds_iff.mpr ⟨s, set.subset_def.mpr hfg, hs, hx⟩), },
have hfg' := hf'.tendsto_uniformly_on_filter.mono_right (calc
𝓝 x = 𝓝[s] x : ((hs.nhds_within_eq hx).symm)
... ≤ 𝓟 s : (by simp only [nhds_within, inf_le_right])),
exact has_fderiv_at_of_tendsto_uniformly_on_filter hfg' hf hfg,
end
/-- `(d/dx) lim_{n → ∞} f n x = lim_{n → ∞} f' n x` when the `f' n` converge
_uniformly_ to their limit. -/
lemma has_fderiv_at_of_tendsto_uniformly
(hf' : tendsto_uniformly f' g' l)
(hf : ∀ (n : ι), ∀ (x : E), has_fderiv_at (f n) (f' n x) x)
(hfg : ∀ (x : E), tendsto (λ n, f n x) l (𝓝 (g x))) :
∀ (x : E), has_fderiv_at g (g' x) x :=
begin
intros x,
have hf : ∀ (n : ι), ∀ (x : E), x ∈ set.univ → has_fderiv_at (f n) (f' n x) x, { simp [hf], },
have hfg : ∀ (x : E), x ∈ set.univ → tendsto (λ n, f n x) l (𝓝 (g x)), { simp [hfg], },
have hf' : tendsto_uniformly_on f' g' l set.univ, { rwa tendsto_uniformly_on_univ, },
refine has_fderiv_at_of_tendsto_uniformly_on is_open_univ hf' hf hfg x (set.mem_univ x),
end
end limits_of_derivatives
section deriv
/-! ### `deriv` versions of above theorems
In this section, we provide `deriv` equivalents of the `fderiv` lemmas in the previous section.
The protected function `promote_deriv` provides the translation between derivatives and Fréchet
derivatives
-/
variables {ι : Type*} {l : filter ι}
{𝕜 : Type*} [is_R_or_C 𝕜]
{G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G]
{f : ι → 𝕜 → G} {g : 𝕜 → G} {f' : ι → 𝕜 → G} {g' : 𝕜 → G}
{x : 𝕜}
/-- If our derivatives converge uniformly, then the Fréchet derivatives converge uniformly -/
lemma uniform_cauchy_seq_on_filter.one_smul_right {l' : filter 𝕜}
(hf' : uniform_cauchy_seq_on_filter f' l l') :
uniform_cauchy_seq_on_filter (λ n, λ z, (1 : 𝕜 →L[𝕜] 𝕜).smul_right (f' n z)) l l' :=
begin
-- The tricky part of this proof is that operator norms are written in terms of `≤` whereas
-- metrics are written in terms of `<`. So we need to shrink `ε` utilizing the archimedean
-- property of `ℝ`
rw [normed_add_comm_group.uniform_cauchy_seq_on_filter_iff_tendsto_uniformly_on_filter_zero,
metric.tendsto_uniformly_on_filter_iff] at hf' ⊢,
intros ε hε,
obtain ⟨q, hq, hq'⟩ := exists_between hε.lt,
apply (hf' q hq).mono,
intros n hn,
refine lt_of_le_of_lt _ hq',
simp only [dist_eq_norm, pi.zero_apply, zero_sub, norm_neg] at hn ⊢,
refine continuous_linear_map.op_norm_le_bound _ hq.le _,
intros z,
simp only [continuous_linear_map.coe_sub', pi.sub_apply, continuous_linear_map.smul_right_apply,
continuous_linear_map.one_apply],
rw [←smul_sub, norm_smul, mul_comm],
exact mul_le_mul hn.le rfl.le (norm_nonneg _) hq.le,
end
variables [ne_bot l]
lemma uniform_cauchy_seq_on_filter_of_tendsto_uniformly_on_filter_deriv
(hf' : uniform_cauchy_seq_on_filter f' l (𝓝 x))
(hf : ∀ᶠ (n : ι × 𝕜) in (l ×ᶠ 𝓝 x), has_deriv_at (f n.1) (f' n.1 n.2) n.2)
(hfg : tendsto (λ n, f n x) l (𝓝 (g x))) :
uniform_cauchy_seq_on_filter f l (𝓝 x) :=
begin
simp_rw has_deriv_at_iff_has_fderiv_at at hf,
exact uniform_cauchy_seq_on_filter_of_tendsto_uniformly_on_filter_fderiv
hf'.one_smul_right hf hfg,
end
lemma uniform_cauchy_seq_on_ball_of_tendsto_uniformly_on_ball_deriv
{r : ℝ} (hr : 0 < r)
(hf' : uniform_cauchy_seq_on f' l (metric.ball x r))
(hf : ∀ n : ι, ∀ y : 𝕜, y ∈ metric.ball x r → has_deriv_at (f n) (f' n y) y)
(hfg : tendsto (λ n, f n x) l (𝓝 (g x))) :
uniform_cauchy_seq_on f l (metric.ball x r) :=
begin
simp_rw has_deriv_at_iff_has_fderiv_at at hf,
rw uniform_cauchy_seq_on_iff_uniform_cauchy_seq_on_filter at hf',
have hf' : uniform_cauchy_seq_on (λ n, λ z, (1 : 𝕜 →L[𝕜] 𝕜).smul_right (f' n z)) l
(metric.ball x r),
{ rw uniform_cauchy_seq_on_iff_uniform_cauchy_seq_on_filter,
exact hf'.one_smul_right, },
exact uniform_cauchy_seq_on_ball_of_tendsto_uniformly_on_ball_fderiv hr hf' hf hfg,
end
lemma has_deriv_at_of_tendsto_uniformly_on_filter
(hf' : tendsto_uniformly_on_filter f' g' l (𝓝 x))
(hf : ∀ᶠ (n : ι × 𝕜) in (l ×ᶠ 𝓝 x), has_deriv_at (f n.1) (f' n.1 n.2) n.2)
(hfg : ∀ᶠ y in 𝓝 x, tendsto (λ n, f n y) l (𝓝 (g y))) :
has_deriv_at g (g' x) x :=
begin
-- The first part of the proof rewrites `hf` and the goal to be functions so that Lean
-- can recognize them when we apply `has_fderiv_at_of_tendsto_uniformly_on_filter`
let F' := (λ n, λ z, (1 : 𝕜 →L[𝕜] 𝕜).smul_right (f' n z)),
let G' := λ z, (1 : 𝕜 →L[𝕜] 𝕜).smul_right (g' z),
simp_rw has_deriv_at_iff_has_fderiv_at at hf ⊢,
-- Now we need to rewrite hf' in terms of continuous_linear_maps. The tricky part is that
-- operator norms are written in terms of `≤` whereas metrics are written in terms of `<`. So we
-- need to shrink `ε` utilizing the archimedean property of `ℝ`
have hf' : tendsto_uniformly_on_filter F' G' l (𝓝 x),
{ rw metric.tendsto_uniformly_on_filter_iff at hf' ⊢,
intros ε hε,
obtain ⟨q, hq, hq'⟩ := exists_between hε.lt,
apply (hf' q hq).mono,
intros n hn,
refine lt_of_le_of_lt _ hq',
simp only [F', G', dist_eq_norm] at hn ⊢,
refine continuous_linear_map.op_norm_le_bound _ hq.le _,
intros z,
simp only [continuous_linear_map.coe_sub', pi.sub_apply, continuous_linear_map.smul_right_apply,
continuous_linear_map.one_apply],
rw [←smul_sub, norm_smul, mul_comm],
exact mul_le_mul hn.le rfl.le (norm_nonneg _) hq.le, },
exact has_fderiv_at_of_tendsto_uniformly_on_filter hf' hf hfg,
end
lemma has_deriv_at_of_tendsto_uniformly_on
{s : set 𝕜} (hs : is_open s)
(hf' : tendsto_uniformly_on f' g' l s)
(hf : ∀ (n : ι), ∀ (x : 𝕜), x ∈ s → has_deriv_at (f n) (f' n x) x)
(hfg : ∀ (x : 𝕜), x ∈ s → tendsto (λ n, f n x) l (𝓝 (g x))) :
∀ (x : 𝕜), x ∈ s → has_deriv_at g (g' x) x :=
begin
intros x hx,
have hsx : s ∈ 𝓝 x, { exact mem_nhds_iff.mpr ⟨s, rfl.subset, hs, hx⟩, },
rw tendsto_uniformly_on_iff_tendsto_uniformly_on_filter at hf',
have hf' := hf'.mono_right (le_principal_iff.mpr hsx),
have hfg : ∀ᶠ y in 𝓝 x, tendsto (λ n, f n y) l (𝓝 (g y)),
{ exact eventually_iff_exists_mem.mpr ⟨s, hsx, hfg⟩, },
have hf : ∀ᶠ (n : ι × 𝕜) in (l ×ᶠ 𝓝 x), has_deriv_at (f n.1) (f' n.1 n.2) n.2,
{ rw eventually_prod_iff,
refine ⟨(λ y, true), by simp, (λ y, y ∈ s), _, (λ n hn y hy, hf n y hy)⟩,
exact eventually_mem_set.mpr hsx, },
exact has_deriv_at_of_tendsto_uniformly_on_filter hf' hf hfg,
end
lemma has_deriv_at_of_tendsto_uniformly
(hf' : tendsto_uniformly f' g' l)
(hf : ∀ (n : ι), ∀ (x : 𝕜), has_deriv_at (f n) (f' n x) x)
(hfg : ∀ (x : 𝕜), tendsto (λ n, f n x) l (𝓝 (g x))) :
∀ (x : 𝕜), has_deriv_at g (g' x) x :=
begin
intros x,
have hf : ∀ (n : ι), ∀ (x : 𝕜), x ∈ set.univ → has_deriv_at (f n) (f' n x) x, { simp [hf], },
have hfg : ∀ (x : 𝕜), x ∈ set.univ → tendsto (λ n, f n x) l (𝓝 (g x)), { simp [hfg], },
have hf' : tendsto_uniformly_on f' g' l set.univ, { rwa tendsto_uniformly_on_univ, },
exact has_deriv_at_of_tendsto_uniformly_on is_open_univ hf' hf hfg x (set.mem_univ x),
end
end deriv
|
d92fec7f0e478522890047d06597e31f84637d87 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/int/succ_pred.lean | 1d65823913dbf9ef602e28018f42ea9d2aace2e8 | [
"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,480 | 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.int.order.basic
import data.nat.succ_pred
/-!
# Successors and predecessors of integers
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file, we show that `ℤ` is both an archimedean `succ_order` and an archimedean `pred_order`.
-/
open function order
namespace int
@[reducible] -- so that Lean reads `int.succ` through `succ_order.succ`
instance : succ_order ℤ :=
{ succ := succ,
..succ_order.of_succ_le_iff succ (λ a b, iff.rfl) }
@[reducible] -- so that Lean reads `int.pred` through `pred_order.pred`
instance : pred_order ℤ :=
{ pred := pred,
pred_le := λ a, (sub_one_lt_of_le le_rfl).le,
min_of_le_pred := λ a ha, ((sub_one_lt_of_le le_rfl).not_le ha).elim,
le_pred_of_lt := λ a b, le_sub_one_of_lt,
le_of_pred_lt := λ a b, le_of_sub_one_lt }
@[simp] lemma succ_eq_succ : order.succ = succ := rfl
@[simp] lemma pred_eq_pred : order.pred = pred := rfl
lemma pos_iff_one_le {a : ℤ} : 0 < a ↔ 1 ≤ a := order.succ_le_iff.symm
lemma succ_iterate (a : ℤ) : ∀ n, succ^[n] a = a + n
| 0 := (add_zero a).symm
| (n + 1) := by { rw [function.iterate_succ', int.coe_nat_succ, ←add_assoc],
exact congr_arg _ (succ_iterate n) }
lemma pred_iterate (a : ℤ) : ∀ n, pred^[n] a = a - n
| 0 := (sub_zero a).symm
| (n + 1) := by { rw [function.iterate_succ', int.coe_nat_succ, ←sub_sub],
exact congr_arg _ (pred_iterate n) }
instance : is_succ_archimedean ℤ :=
⟨λ a b h, ⟨(b - a).to_nat,
by rw [succ_eq_succ, succ_iterate, to_nat_sub_of_le h, ←add_sub_assoc, add_sub_cancel']⟩⟩
instance : is_pred_archimedean ℤ :=
⟨λ a b h, ⟨(b - a).to_nat, by rw [pred_eq_pred, pred_iterate, to_nat_sub_of_le h, sub_sub_cancel]⟩⟩
/-! ### Covering relation -/
protected lemma covby_iff_succ_eq {m n : ℤ} : m ⋖ n ↔ m + 1 = n := succ_eq_iff_covby.symm
@[simp] lemma sub_one_covby (z : ℤ) : z - 1 ⋖ z :=
by rw [int.covby_iff_succ_eq, sub_add_cancel]
@[simp] lemma covby_add_one (z : ℤ) : z ⋖ z + 1 :=
int.covby_iff_succ_eq.mpr rfl
end int
@[simp, norm_cast] lemma nat.cast_int_covby_iff {a b : ℕ} : (a : ℤ) ⋖ b ↔ a ⋖ b :=
by { rw [nat.covby_iff_succ_eq, int.covby_iff_succ_eq], exact int.coe_nat_inj' }
alias nat.cast_int_covby_iff ↔ _ covby.cast_int
|
fa475062d281ff164a47fed51403efbc36cb0339 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/order/monotone/basic.lean | 84433c7deff175d4ccb7fa45826a3539bc90c3c0 | [
"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 | 38,445 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Mario Carneiro, Yaël Dillies
-/
import order.compare
import order.max
import order.rel_classes
/-!
# Monotonicity
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines (strictly) monotone/antitone functions. Contrary to standard mathematical usage,
"monotone"/"mono" here means "increasing", not "increasing or decreasing". We use "antitone"/"anti"
to mean "decreasing".
## Definitions
* `monotone f`: A function `f` between two preorders is monotone if `a ≤ b` implies `f a ≤ f b`.
* `antitone f`: A function `f` between two preorders is antitone if `a ≤ b` implies `f b ≤ f a`.
* `monotone_on f s`: Same as `monotone f`, but for all `a, b ∈ s`.
* `antitone_on f s`: Same as `antitone f`, but for all `a, b ∈ s`.
* `strict_mono f` : A function `f` between two preorders is strictly monotone if `a < b` implies
`f a < f b`.
* `strict_anti f` : A function `f` between two preorders is strictly antitone if `a < b` implies
`f b < f a`.
* `strict_mono_on f s`: Same as `strict_mono f`, but for all `a, b ∈ s`.
* `strict_anti_on f s`: Same as `strict_anti f`, but for all `a, b ∈ s`.
## Main theorems
* `monotone_nat_of_le_succ`, `monotone_int_of_le_succ`: If `f : ℕ → α` or `f : ℤ → α` and
`f n ≤ f (n + 1)` for all `n`, then `f` is monotone.
* `antitone_nat_of_succ_le`, `antitone_int_of_succ_le`: If `f : ℕ → α` or `f : ℤ → α` and
`f (n + 1) ≤ f n` for all `n`, then `f` is antitone.
* `strict_mono_nat_of_lt_succ`, `strict_mono_int_of_lt_succ`: If `f : ℕ → α` or `f : ℤ → α` and
`f n < f (n + 1)` for all `n`, then `f` is strictly monotone.
* `strict_anti_nat_of_succ_lt`, `strict_anti_int_of_succ_lt`: If `f : ℕ → α` or `f : ℤ → α` and
`f (n + 1) < f n` for all `n`, then `f` is strictly antitone.
## Implementation notes
Some of these definitions used to only require `has_le α` or `has_lt α`. The advantage of this is
unclear and it led to slight elaboration issues. Now, everything requires `preorder α` and seems to
work fine. Related Zulip discussion:
https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/Order.20diamond/near/254353352.
## TODO
The above theorems are also true in `ℕ+`, `fin n`... To make that work, we need `succ_order α`
and `succ_archimedean α`.
## Tags
monotone, strictly monotone, antitone, strictly antitone, increasing, strictly increasing,
decreasing, strictly decreasing
-/
open function order_dual
universes u v w
variables {ι : Type*} {α : Type u} {β : Type v} {γ : Type w} {δ : Type*} {π : ι → Type*}
{r : α → α → Prop}
section monotone_def
variables [preorder α] [preorder β]
/-- A function `f` is monotone if `a ≤ b` implies `f a ≤ f b`. -/
def monotone (f : α → β) : Prop := ∀ ⦃a b⦄, a ≤ b → f a ≤ f b
/-- A function `f` is antitone if `a ≤ b` implies `f b ≤ f a`. -/
def antitone (f : α → β) : Prop := ∀ ⦃a b⦄, a ≤ b → f b ≤ f a
/-- A function `f` is monotone on `s` if, for all `a, b ∈ s`, `a ≤ b` implies `f a ≤ f b`. -/
def monotone_on (f : α → β) (s : set α) : Prop :=
∀ ⦃a⦄ (ha : a ∈ s) ⦃b⦄ (hb : b ∈ s), a ≤ b → f a ≤ f b
/-- A function `f` is antitone on `s` if, for all `a, b ∈ s`, `a ≤ b` implies `f b ≤ f a`. -/
def antitone_on (f : α → β) (s : set α) : Prop :=
∀ ⦃a⦄ (ha : a ∈ s) ⦃b⦄ (hb : b ∈ s), a ≤ b → f b ≤ f a
/-- A function `f` is strictly monotone if `a < b` implies `f a < f b`. -/
def strict_mono (f : α → β) : Prop :=
∀ ⦃a b⦄, a < b → f a < f b
/-- A function `f` is strictly antitone if `a < b` implies `f b < f a`. -/
def strict_anti (f : α → β) : Prop :=
∀ ⦃a b⦄, a < b → f b < f a
/-- A function `f` is strictly monotone on `s` if, for all `a, b ∈ s`, `a < b` implies
`f a < f b`. -/
def strict_mono_on (f : α → β) (s : set α) : Prop :=
∀ ⦃a⦄ (ha : a ∈ s) ⦃b⦄ (hb : b ∈ s), a < b → f a < f b
/-- A function `f` is strictly antitone on `s` if, for all `a, b ∈ s`, `a < b` implies
`f b < f a`. -/
def strict_anti_on (f : α → β) (s : set α) : Prop :=
∀ ⦃a⦄ (ha : a ∈ s) ⦃b⦄ (hb : b ∈ s), a < b → f b < f a
end monotone_def
/-! ### Monotonicity on the dual order
Strictly, many of the `*_on.dual` lemmas in this section should use `of_dual ⁻¹' s` instead of `s`,
but right now this is not possible as `set.preimage` is not defined yet, and importing it creates
an import cycle.
Often, you should not need the rewriting lemmas. Instead, you probably want to add `.dual`,
`.dual_left` or `.dual_right` to your `monotone`/`antitone` hypothesis.
-/
section order_dual
variables [preorder α] [preorder β] {f : α → β} {s : set α}
@[simp] lemma monotone_comp_of_dual_iff : monotone (f ∘ of_dual) ↔ antitone f := forall_swap
@[simp] lemma antitone_comp_of_dual_iff : antitone (f ∘ of_dual) ↔ monotone f := forall_swap
@[simp] lemma monotone_to_dual_comp_iff : monotone (to_dual ∘ f) ↔ antitone f := iff.rfl
@[simp] lemma antitone_to_dual_comp_iff : antitone (to_dual ∘ f) ↔ monotone f := iff.rfl
@[simp] lemma monotone_on_comp_of_dual_iff : monotone_on (f ∘ of_dual) s ↔ antitone_on f s :=
forall₂_swap
@[simp] lemma antitone_on_comp_of_dual_iff : antitone_on (f ∘ of_dual) s ↔ monotone_on f s :=
forall₂_swap
@[simp] lemma monotone_on_to_dual_comp_iff : monotone_on (to_dual ∘ f) s ↔ antitone_on f s :=
iff.rfl
@[simp] lemma antitone_on_to_dual_comp_iff : antitone_on (to_dual ∘ f) s ↔ monotone_on f s :=
iff.rfl
@[simp] lemma strict_mono_comp_of_dual_iff : strict_mono (f ∘ of_dual) ↔ strict_anti f :=
forall_swap
@[simp] lemma strict_anti_comp_of_dual_iff : strict_anti (f ∘ of_dual) ↔ strict_mono f :=
forall_swap
@[simp] lemma strict_mono_to_dual_comp_iff : strict_mono (to_dual ∘ f) ↔ strict_anti f := iff.rfl
@[simp] lemma strict_anti_to_dual_comp_iff : strict_anti (to_dual ∘ f) ↔ strict_mono f := iff.rfl
@[simp] lemma strict_mono_on_comp_of_dual_iff :
strict_mono_on (f ∘ of_dual) s ↔ strict_anti_on f s := forall₂_swap
@[simp] lemma strict_anti_on_comp_of_dual_iff :
strict_anti_on (f ∘ of_dual) s ↔ strict_mono_on f s := forall₂_swap
@[simp] lemma strict_mono_on_to_dual_comp_iff :
strict_mono_on (to_dual ∘ f) s ↔ strict_anti_on f s := iff.rfl
@[simp] lemma strict_anti_on_to_dual_comp_iff :
strict_anti_on (to_dual ∘ f) s ↔ strict_mono_on f s := iff.rfl
protected lemma monotone.dual (hf : monotone f) : monotone (to_dual ∘ f ∘ of_dual) := swap hf
protected lemma antitone.dual (hf : antitone f) : antitone (to_dual ∘ f ∘ of_dual) := swap hf
protected lemma monotone_on.dual (hf : monotone_on f s) : monotone_on (to_dual ∘ f ∘ of_dual) s :=
swap₂ hf
protected lemma antitone_on.dual (hf : antitone_on f s) : antitone_on (to_dual ∘ f ∘ of_dual) s :=
swap₂ hf
protected lemma strict_mono.dual (hf : strict_mono f) : strict_mono (to_dual ∘ f ∘ of_dual) :=
swap hf
protected lemma strict_anti.dual (hf : strict_anti f) : strict_anti (to_dual ∘ f ∘ of_dual) :=
swap hf
protected lemma strict_mono_on.dual (hf : strict_mono_on f s) :
strict_mono_on (to_dual ∘ f ∘ of_dual) s := swap₂ hf
protected lemma strict_anti_on.dual (hf : strict_anti_on f s) :
strict_anti_on (to_dual ∘ f ∘ of_dual) s := swap₂ hf
alias antitone_comp_of_dual_iff ↔ _ monotone.dual_left
alias monotone_comp_of_dual_iff ↔ _ antitone.dual_left
alias antitone_to_dual_comp_iff ↔ _ monotone.dual_right
alias monotone_to_dual_comp_iff ↔ _ antitone.dual_right
alias antitone_on_comp_of_dual_iff ↔ _ monotone_on.dual_left
alias monotone_on_comp_of_dual_iff ↔ _ antitone_on.dual_left
alias antitone_on_to_dual_comp_iff ↔ _ monotone_on.dual_right
alias monotone_on_to_dual_comp_iff ↔ _ antitone_on.dual_right
alias strict_anti_comp_of_dual_iff ↔ _ strict_mono.dual_left
alias strict_mono_comp_of_dual_iff ↔ _ strict_anti.dual_left
alias strict_anti_to_dual_comp_iff ↔ _ strict_mono.dual_right
alias strict_mono_to_dual_comp_iff ↔ _ strict_anti.dual_right
alias strict_anti_on_comp_of_dual_iff ↔ _ strict_mono_on.dual_left
alias strict_mono_on_comp_of_dual_iff ↔ _ strict_anti_on.dual_left
alias strict_anti_on_to_dual_comp_iff ↔ _ strict_mono_on.dual_right
alias strict_mono_on_to_dual_comp_iff ↔ _ strict_anti_on.dual_right
end order_dual
/-! ### Monotonicity in function spaces -/
section preorder
variables [preorder α]
theorem monotone.comp_le_comp_left [preorder β]
{f : β → α} {g h : γ → β} (hf : monotone f) (le_gh : g ≤ h) :
has_le.le.{max w u} (f ∘ g) (f ∘ h) :=
λ x, hf (le_gh x)
variables [preorder γ]
theorem monotone_lam {f : α → β → γ} (hf : ∀ b, monotone (λ a, f a b)) : monotone f :=
λ a a' h b, hf b h
theorem monotone_app (f : β → α → γ) (b : β) (hf : monotone (λ a b, f b a)) : monotone (f b) :=
λ a a' h, hf h b
theorem antitone_lam {f : α → β → γ} (hf : ∀ b, antitone (λ a, f a b)) : antitone f :=
λ a a' h b, hf b h
theorem antitone_app (f : β → α → γ) (b : β) (hf : antitone (λ a b, f b a)) : antitone (f b) :=
λ a a' h, hf h b
end preorder
lemma function.monotone_eval {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] (i : ι) :
monotone (function.eval i : (Π i, α i) → α i) :=
λ f g H, H i
/-! ### Monotonicity hierarchy -/
section preorder
variables [preorder α]
section preorder
variables [preorder β] {f : α → β} {s : set α} {a b : α}
/-!
These four lemmas are there to strip off the semi-implicit arguments `⦃a b : α⦄`. This is useful
when you do not want to apply a `monotone` assumption (i.e. your goal is `a ≤ b → f a ≤ f b`).
However if you find yourself writing `hf.imp h`, then you should have written `hf h` instead.
-/
lemma monotone.imp (hf : monotone f) (h : a ≤ b) : f a ≤ f b := hf h
lemma antitone.imp (hf : antitone f) (h : a ≤ b) : f b ≤ f a := hf h
lemma strict_mono.imp (hf : strict_mono f) (h : a < b) : f a < f b := hf h
lemma strict_anti.imp (hf : strict_anti f) (h : a < b) : f b < f a := hf h
protected lemma monotone.monotone_on (hf : monotone f) (s : set α) : monotone_on f s :=
λ a _ b _, hf.imp
protected lemma antitone.antitone_on (hf : antitone f) (s : set α) : antitone_on f s :=
λ a _ b _, hf.imp
@[simp] lemma monotone_on_univ : monotone_on f set.univ ↔ monotone f :=
⟨λ h a b, h trivial trivial, λ h, h.monotone_on _⟩
@[simp] lemma antitone_on_univ : antitone_on f set.univ ↔ antitone f :=
⟨λ h a b, h trivial trivial, λ h, h.antitone_on _⟩
protected lemma strict_mono.strict_mono_on (hf : strict_mono f) (s : set α) : strict_mono_on f s :=
λ a _ b _, hf.imp
protected lemma strict_anti.strict_anti_on (hf : strict_anti f) (s : set α) : strict_anti_on f s :=
λ a _ b _, hf.imp
@[simp] lemma strict_mono_on_univ : strict_mono_on f set.univ ↔ strict_mono f :=
⟨λ h a b, h trivial trivial, λ h, h.strict_mono_on _⟩
@[simp] lemma strict_anti_on_univ : strict_anti_on f set.univ ↔ strict_anti f :=
⟨λ h a b, h trivial trivial, λ h, h.strict_anti_on _⟩
end preorder
section partial_order
variables [partial_order β] {f : α → β}
lemma monotone.strict_mono_of_injective (h₁ : monotone f) (h₂ : injective f) : strict_mono f :=
λ a b h, (h₁ h.le).lt_of_ne (λ H, h.ne $ h₂ H)
lemma antitone.strict_anti_of_injective (h₁ : antitone f) (h₂ : injective f) : strict_anti f :=
λ a b h, (h₁ h.le).lt_of_ne (λ H, h.ne $ h₂ H.symm)
end partial_order
end preorder
section partial_order
variables [partial_order α] [preorder β] {f : α → β} {s : set α}
lemma monotone_iff_forall_lt : monotone f ↔ ∀ ⦃a b⦄, a < b → f a ≤ f b :=
forall₂_congr $ λ a b, ⟨λ hf h, hf h.le, λ hf h, h.eq_or_lt.elim (λ H, (congr_arg _ H).le) hf⟩
lemma antitone_iff_forall_lt : antitone f ↔ ∀ ⦃a b⦄, a < b → f b ≤ f a :=
forall₂_congr $ λ a b, ⟨λ hf h, hf h.le, λ hf h, h.eq_or_lt.elim (λ H, (congr_arg _ H).ge) hf⟩
lemma monotone_on_iff_forall_lt :
monotone_on f s ↔ ∀ ⦃a⦄ (ha : a ∈ s) ⦃b⦄ (hb : b ∈ s), a < b → f a ≤ f b :=
⟨λ hf a ha b hb h, hf ha hb h.le,
λ hf a ha b hb h, h.eq_or_lt.elim (λ H, (congr_arg _ H).le) (hf ha hb)⟩
lemma antitone_on_iff_forall_lt :
antitone_on f s ↔ ∀ ⦃a⦄ (ha : a ∈ s) ⦃b⦄ (hb : b ∈ s), a < b → f b ≤ f a :=
⟨λ hf a ha b hb h, hf ha hb h.le,
λ hf a ha b hb h, h.eq_or_lt.elim (λ H, (congr_arg _ H).ge) (hf ha hb)⟩
-- `preorder α` isn't strong enough: if the preorder on `α` is an equivalence relation,
-- then `strict_mono f` is vacuously true.
protected lemma strict_mono_on.monotone_on (hf : strict_mono_on f s) : monotone_on f s :=
monotone_on_iff_forall_lt.2 $ λ a ha b hb h, (hf ha hb h).le
protected lemma strict_anti_on.antitone_on (hf : strict_anti_on f s) : antitone_on f s :=
antitone_on_iff_forall_lt.2 $ λ a ha b hb h, (hf ha hb h).le
protected lemma strict_mono.monotone (hf : strict_mono f) : monotone f :=
monotone_iff_forall_lt.2 $ λ a b h, (hf h).le
protected lemma strict_anti.antitone (hf : strict_anti f) : antitone f :=
antitone_iff_forall_lt.2 $ λ a b h, (hf h).le
end partial_order
/-! ### Monotonicity from and to subsingletons -/
namespace subsingleton
variables [preorder α] [preorder β]
protected lemma monotone [subsingleton α] (f : α → β) : monotone f :=
λ a b _, (congr_arg _ $ subsingleton.elim _ _).le
protected lemma antitone [subsingleton α] (f : α → β) : antitone f :=
λ a b _, (congr_arg _ $ subsingleton.elim _ _).le
lemma monotone' [subsingleton β] (f : α → β) : monotone f := λ a b _, (subsingleton.elim _ _).le
lemma antitone' [subsingleton β] (f : α → β) : antitone f := λ a b _, (subsingleton.elim _ _).le
protected lemma strict_mono [subsingleton α] (f : α → β) : strict_mono f :=
λ a b h, (h.ne $ subsingleton.elim _ _).elim
protected lemma strict_anti [subsingleton α] (f : α → β) : strict_anti f :=
λ a b h, (h.ne $ subsingleton.elim _ _).elim
end subsingleton
/-! ### Miscellaneous monotonicity results -/
lemma monotone_id [preorder α] : monotone (id : α → α) := λ a b, id
lemma monotone_on_id [preorder α] {s : set α} : monotone_on id s := λ a ha b hb, id
lemma strict_mono_id [preorder α] : strict_mono (id : α → α) := λ a b, id
lemma strict_mono_on_id [preorder α] {s : set α} : strict_mono_on id s := λ a ha b hb, id
theorem monotone_const [preorder α] [preorder β] {c : β} : monotone (λ (a : α), c) :=
λ a b _, le_rfl
theorem monotone_on_const [preorder α] [preorder β] {c : β} {s : set α} :
monotone_on (λ (a : α), c) s :=
λ a _ b _ _, le_rfl
theorem antitone_const [preorder α] [preorder β] {c : β} : antitone (λ (a : α), c) :=
λ a b _, le_refl c
theorem antitone_on_const [preorder α] [preorder β] {c : β} {s : set α} :
antitone_on (λ (a : α), c) s :=
λ a _ b _ _, le_rfl
lemma strict_mono_of_le_iff_le [preorder α] [preorder β] {f : α → β}
(h : ∀ x y, x ≤ y ↔ f x ≤ f y) : strict_mono f :=
λ a b, (lt_iff_lt_of_le_iff_le' (h _ _) (h _ _)).1
lemma strict_anti_of_le_iff_le [preorder α] [preorder β] {f : α → β}
(h : ∀ x y, x ≤ y ↔ f y ≤ f x) : strict_anti f :=
λ a b, (lt_iff_lt_of_le_iff_le' (h _ _) (h _ _)).1
lemma injective_of_lt_imp_ne [linear_order α] {f : α → β} (h : ∀ x y, x < y → f x ≠ f y) :
injective f :=
begin
intros x y hxy,
contrapose hxy,
cases ne.lt_or_lt hxy with hxy hxy,
exacts [h _ _ hxy, (h _ _ hxy).symm]
end
lemma injective_of_le_imp_le [partial_order α] [preorder β] (f : α → β)
(h : ∀ {x y}, f x ≤ f y → x ≤ y) : injective f :=
λ x y hxy, (h hxy.le).antisymm (h hxy.ge)
section preorder
variables [preorder α] [preorder β] {f g : α → β} {a : α}
lemma strict_mono.is_max_of_apply (hf : strict_mono f) (ha : is_max (f a)) : is_max a :=
of_not_not $ λ h, let ⟨b, hb⟩ := not_is_max_iff.1 h in (hf hb).not_is_max ha
lemma strict_mono.is_min_of_apply (hf : strict_mono f) (ha : is_min (f a)) : is_min a :=
of_not_not $ λ h, let ⟨b, hb⟩ := not_is_min_iff.1 h in (hf hb).not_is_min ha
lemma strict_anti.is_max_of_apply (hf : strict_anti f) (ha : is_min (f a)) : is_max a :=
of_not_not $ λ h, let ⟨b, hb⟩ := not_is_max_iff.1 h in (hf hb).not_is_min ha
lemma strict_anti.is_min_of_apply (hf : strict_anti f) (ha : is_max (f a)) : is_min a :=
of_not_not $ λ h, let ⟨b, hb⟩ := not_is_min_iff.1 h in (hf hb).not_is_max ha
protected lemma strict_mono.ite' (hf : strict_mono f) (hg : strict_mono g) {p : α → Prop}
[decidable_pred p] (hp : ∀ ⦃x y⦄, x < y → p y → p x)
(hfg : ∀ ⦃x y⦄, p x → ¬p y → x < y → f x < g y) :
strict_mono (λ x, if p x then f x else g x) :=
begin
intros x y h,
by_cases hy : p y,
{ have hx : p x := hp h hy,
simpa [hx, hy] using hf h },
by_cases hx : p x,
{ simpa [hx, hy] using hfg hx hy h },
{ simpa [hx, hy] using hg h}
end
protected lemma strict_mono.ite (hf : strict_mono f) (hg : strict_mono g) {p : α → Prop}
[decidable_pred p] (hp : ∀ ⦃x y⦄, x < y → p y → p x) (hfg : ∀ x, f x ≤ g x) :
strict_mono (λ x, if p x then f x else g x) :=
hf.ite' hg hp $ λ x y hx hy h, (hf h).trans_le (hfg y)
protected lemma strict_anti.ite' (hf : strict_anti f) (hg : strict_anti g) {p : α → Prop}
[decidable_pred p] (hp : ∀ ⦃x y⦄, x < y → p y → p x)
(hfg : ∀ ⦃x y⦄, p x → ¬p y → x < y → g y < f x) :
strict_anti (λ x, if p x then f x else g x) :=
(strict_mono.ite' hf.dual_right hg.dual_right hp hfg).dual_right
protected lemma strict_anti.ite (hf : strict_anti f) (hg : strict_anti g) {p : α → Prop}
[decidable_pred p] (hp : ∀ ⦃x y⦄, x < y → p y → p x) (hfg : ∀ x, g x ≤ f x) :
strict_anti (λ x, if p x then f x else g x) :=
hf.ite' hg hp $ λ x y hx hy h, (hfg y).trans_lt (hf h)
end preorder
/-! ### Monotonicity under composition -/
section composition
variables [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} {s : set α}
protected lemma monotone.comp (hg : monotone g) (hf : monotone f) :
monotone (g ∘ f) :=
λ a b h, hg (hf h)
lemma monotone.comp_antitone (hg : monotone g) (hf : antitone f) :
antitone (g ∘ f) :=
λ a b h, hg (hf h)
protected lemma antitone.comp (hg : antitone g) (hf : antitone f) :
monotone (g ∘ f) :=
λ a b h, hg (hf h)
lemma antitone.comp_monotone (hg : antitone g) (hf : monotone f) :
antitone (g ∘ f) :=
λ a b h, hg (hf h)
protected lemma monotone.iterate {f : α → α} (hf : monotone f) (n : ℕ) : monotone (f^[n]) :=
nat.rec_on n monotone_id (λ n h, h.comp hf)
protected lemma monotone.comp_monotone_on (hg : monotone g) (hf : monotone_on f s) :
monotone_on (g ∘ f) s :=
λ a ha b hb h, hg (hf ha hb h)
lemma monotone.comp_antitone_on (hg : monotone g) (hf : antitone_on f s) :
antitone_on (g ∘ f) s :=
λ a ha b hb h, hg (hf ha hb h)
protected lemma antitone.comp_antitone_on (hg : antitone g) (hf : antitone_on f s) :
monotone_on (g ∘ f) s :=
λ a ha b hb h, hg (hf ha hb h)
lemma antitone.comp_monotone_on (hg : antitone g) (hf : monotone_on f s) :
antitone_on (g ∘ f) s :=
λ a ha b hb h, hg (hf ha hb h)
protected lemma strict_mono.comp (hg : strict_mono g) (hf : strict_mono f) :
strict_mono (g ∘ f) :=
λ a b h, hg (hf h)
lemma strict_mono.comp_strict_anti (hg : strict_mono g) (hf : strict_anti f) :
strict_anti (g ∘ f) :=
λ a b h, hg (hf h)
protected lemma strict_anti.comp (hg : strict_anti g) (hf : strict_anti f) :
strict_mono (g ∘ f) :=
λ a b h, hg (hf h)
lemma strict_anti.comp_strict_mono (hg : strict_anti g) (hf : strict_mono f) :
strict_anti (g ∘ f) :=
λ a b h, hg (hf h)
protected lemma strict_mono.iterate {f : α → α} (hf : strict_mono f) (n : ℕ) :
strict_mono (f^[n]) :=
nat.rec_on n strict_mono_id (λ n h, h.comp hf)
protected lemma strict_mono.comp_strict_mono_on (hg : strict_mono g) (hf : strict_mono_on f s) :
strict_mono_on (g ∘ f) s :=
λ a ha b hb h, hg (hf ha hb h)
lemma strict_mono.comp_strict_anti_on (hg : strict_mono g) (hf : strict_anti_on f s) :
strict_anti_on (g ∘ f) s :=
λ a ha b hb h, hg (hf ha hb h)
protected lemma strict_anti.comp_strict_anti_on (hg : strict_anti g) (hf : strict_anti_on f s) :
strict_mono_on (g ∘ f) s :=
λ a ha b hb h, hg (hf ha hb h)
lemma strict_anti.comp_strict_mono_on (hg : strict_anti g) (hf : strict_mono_on f s) :
strict_anti_on (g ∘ f) s :=
λ a ha b hb h, hg (hf ha hb h)
end composition
namespace list
section fold
theorem foldl_monotone [preorder α] {f : α → β → α} (H : ∀ b, monotone (λ a, f a b)) (l : list β) :
monotone (λ a, l.foldl f a) :=
list.rec_on l (λ _ _, id) (λ i l hl _ _ h, hl (H _ h))
theorem foldr_monotone [preorder β] {f : α → β → β} (H : ∀ a, monotone (f a)) (l : list α) :
monotone (λ b, l.foldr f b) :=
λ _ _ h, list.rec_on l h (λ i l hl, H i hl)
theorem foldl_strict_mono [preorder α] {f : α → β → α} (H : ∀ b, strict_mono (λ a, f a b))
(l : list β) : strict_mono (λ a, l.foldl f a) :=
list.rec_on l (λ _ _, id) (λ i l hl _ _ h, hl (H _ h))
theorem foldr_strict_mono [preorder β] {f : α → β → β} (H : ∀ a, strict_mono (f a)) (l : list α) :
strict_mono (λ b, l.foldr f b) :=
λ _ _ h, list.rec_on l h (λ i l hl, H i hl)
end fold
end list
/-! ### Monotonicity in linear orders -/
section linear_order
variables [linear_order α]
section preorder
variables [preorder β] {f : α → β} {s : set α}
open ordering
lemma monotone.reflect_lt (hf : monotone f) {a b : α} (h : f a < f b) : a < b :=
lt_of_not_ge (λ h', h.not_le (hf h'))
lemma antitone.reflect_lt (hf : antitone f) {a b : α} (h : f a < f b) : b < a :=
lt_of_not_ge (λ h', h.not_le (hf h'))
lemma monotone_on.reflect_lt (hf : monotone_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s)
(h : f a < f b) :
a < b :=
lt_of_not_ge $ λ h', h.not_le $ hf hb ha h'
lemma antitone_on.reflect_lt (hf : antitone_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s)
(h : f a < f b) :
b < a :=
lt_of_not_ge $ λ h', h.not_le $ hf ha hb h'
lemma strict_mono_on.le_iff_le (hf : strict_mono_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) :
f a ≤ f b ↔ a ≤ b :=
⟨λ h, le_of_not_gt $ λ h', (hf hb ha h').not_le h,
λ h, h.lt_or_eq_dec.elim (λ h', (hf ha hb h').le) (λ h', h' ▸ le_rfl)⟩
lemma strict_anti_on.le_iff_le (hf : strict_anti_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) :
f a ≤ f b ↔ b ≤ a :=
hf.dual_right.le_iff_le hb ha
lemma strict_mono_on.eq_iff_eq (hf : strict_mono_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) :
f a = f b ↔ a = b :=
⟨λ h, le_antisymm ((hf.le_iff_le ha hb).mp h.le) ((hf.le_iff_le hb ha).mp h.ge),
by { rintro rfl, refl, }⟩
lemma strict_anti_on.eq_iff_eq (hf : strict_anti_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) :
f a = f b ↔ b = a :=
(hf.dual_right.eq_iff_eq ha hb).trans eq_comm
lemma strict_mono_on.lt_iff_lt (hf : strict_mono_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) :
f a < f b ↔ a < b :=
by rw [lt_iff_le_not_le, lt_iff_le_not_le, hf.le_iff_le ha hb, hf.le_iff_le hb ha]
lemma strict_anti_on.lt_iff_lt (hf : strict_anti_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) :
f a < f b ↔ b < a :=
hf.dual_right.lt_iff_lt hb ha
lemma strict_mono.le_iff_le (hf : strict_mono f) {a b : α} :
f a ≤ f b ↔ a ≤ b :=
(hf.strict_mono_on set.univ).le_iff_le trivial trivial
lemma strict_anti.le_iff_le (hf : strict_anti f) {a b : α} :
f a ≤ f b ↔ b ≤ a :=
(hf.strict_anti_on set.univ).le_iff_le trivial trivial
lemma strict_mono.lt_iff_lt (hf : strict_mono f) {a b : α} :
f a < f b ↔ a < b :=
(hf.strict_mono_on set.univ).lt_iff_lt trivial trivial
lemma strict_anti.lt_iff_lt (hf : strict_anti f) {a b : α} :
f a < f b ↔ b < a :=
(hf.strict_anti_on set.univ).lt_iff_lt trivial trivial
protected theorem strict_mono_on.compares (hf : strict_mono_on f s) {a b : α} (ha : a ∈ s)
(hb : b ∈ s) :
∀ {o : ordering}, o.compares (f a) (f b) ↔ o.compares a b
| ordering.lt := hf.lt_iff_lt ha hb
| ordering.eq := ⟨λ h, ((hf.le_iff_le ha hb).1 h.le).antisymm ((hf.le_iff_le hb ha).1 h.symm.le),
congr_arg _⟩
| ordering.gt := hf.lt_iff_lt hb ha
protected theorem strict_anti_on.compares (hf : strict_anti_on f s) {a b : α} (ha : a ∈ s)
(hb : b ∈ s) {o : ordering} :
o.compares (f a) (f b) ↔ o.compares b a :=
to_dual_compares_to_dual.trans $ hf.dual_right.compares hb ha
protected theorem strict_mono.compares (hf : strict_mono f) {a b : α} {o : ordering} :
o.compares (f a) (f b) ↔ o.compares a b :=
(hf.strict_mono_on set.univ).compares trivial trivial
protected theorem strict_anti.compares (hf : strict_anti f) {a b : α} {o : ordering} :
o.compares (f a) (f b) ↔ o.compares b a :=
(hf.strict_anti_on set.univ).compares trivial trivial
lemma strict_mono.injective (hf : strict_mono f) : injective f :=
λ x y h, show compares eq x y, from hf.compares.1 h
lemma strict_anti.injective (hf : strict_anti f) : injective f :=
λ x y h, show compares eq x y, from hf.compares.1 h.symm
lemma strict_mono.maximal_of_maximal_image (hf : strict_mono f) {a} (hmax : ∀ p, p ≤ f a) (x : α) :
x ≤ a :=
hf.le_iff_le.mp (hmax (f x))
lemma strict_mono.minimal_of_minimal_image (hf : strict_mono f) {a} (hmin : ∀ p, f a ≤ p) (x : α) :
a ≤ x :=
hf.le_iff_le.mp (hmin (f x))
lemma strict_anti.minimal_of_maximal_image (hf : strict_anti f) {a} (hmax : ∀ p, p ≤ f a) (x : α) :
a ≤ x :=
hf.le_iff_le.mp (hmax (f x))
lemma strict_anti.maximal_of_minimal_image (hf : strict_anti f) {a} (hmin : ∀ p, f a ≤ p) (x : α) :
x ≤ a :=
hf.le_iff_le.mp (hmin (f x))
end preorder
section partial_order
variables [partial_order β] {f : α → β}
lemma monotone.strict_mono_iff_injective (hf : monotone f) :
strict_mono f ↔ injective f :=
⟨λ h, h.injective, hf.strict_mono_of_injective⟩
lemma antitone.strict_anti_iff_injective (hf : antitone f) :
strict_anti f ↔ injective f :=
⟨λ h, h.injective, hf.strict_anti_of_injective⟩
end partial_order
variables [linear_order β] {f : α → β} {s : set α} {x y : α}
/-- A function between linear orders which is neither monotone nor antitone makes a dent upright or
downright. -/
lemma not_monotone_not_antitone_iff_exists_le_le :
¬ monotone f ∧ ¬ antitone f ↔ ∃ a b c, a ≤ b ∧ b ≤ c ∧
(f a < f b ∧ f c < f b ∨ f b < f a ∧ f b < f c) :=
begin
simp_rw [monotone, antitone, not_forall, not_le],
refine iff.symm ⟨_, _⟩,
{ rintro ⟨a, b, c, hab, hbc, ⟨hfab, hfcb⟩ | ⟨hfba, hfbc⟩⟩,
exacts [⟨⟨_, _, hbc, hfcb⟩, _, _, hab, hfab⟩, ⟨⟨_, _, hab, hfba⟩, _, _, hbc, hfbc⟩] },
rintro ⟨⟨a, b, hab, hfba⟩, c, d, hcd, hfcd⟩,
obtain hda | had := le_total d a,
{ obtain hfad | hfda := le_total (f a) (f d),
{ exact ⟨c, d, b, hcd, hda.trans hab, or.inl ⟨hfcd, hfba.trans_le hfad⟩⟩ },
{ exact ⟨c, a, b, hcd.trans hda, hab, or.inl ⟨hfcd.trans_le hfda, hfba⟩⟩ } },
obtain hac | hca := le_total a c,
{ obtain hfdb | hfbd := le_or_lt (f d) (f b),
{ exact ⟨a, c, d, hac, hcd, or.inr ⟨hfcd.trans $ hfdb.trans_lt hfba, hfcd⟩⟩ },
obtain hfca | hfac := lt_or_le (f c) (f a),
{ exact ⟨a, c, d, hac, hcd, or.inr ⟨hfca, hfcd⟩⟩ },
obtain hbd | hdb := le_total b d,
{ exact ⟨a, b, d, hab, hbd, or.inr ⟨hfba, hfbd⟩⟩ },
{ exact ⟨a, d, b, had, hdb, or.inl ⟨hfac.trans_lt hfcd, hfbd⟩⟩ } },
{ obtain hfdb | hfbd := le_or_lt (f d) (f b),
{ exact ⟨c, a, b, hca, hab, or.inl ⟨hfcd.trans $ hfdb.trans_lt hfba, hfba⟩⟩ },
obtain hfca | hfac := lt_or_le (f c) (f a),
{ exact ⟨c, a, b, hca, hab, or.inl ⟨hfca, hfba⟩⟩ },
obtain hbd | hdb := le_total b d,
{ exact ⟨a, b, d, hab, hbd, or.inr ⟨hfba, hfbd⟩⟩ },
{ exact ⟨a, d, b, had, hdb, or.inl ⟨hfac.trans_lt hfcd, hfbd⟩⟩ } }
end
/-- A function between linear orders which is neither monotone nor antitone makes a dent upright or
downright. -/
lemma not_monotone_not_antitone_iff_exists_lt_lt :
¬ monotone f ∧ ¬ antitone f ↔ ∃ a b c, a < b ∧ b < c ∧
(f a < f b ∧ f c < f b ∨ f b < f a ∧ f b < f c) :=
begin
simp_rw [not_monotone_not_antitone_iff_exists_le_le, ←and_assoc],
refine exists₃_congr (λ a b c, and_congr_left $ λ h, (ne.le_iff_lt _).and $ ne.le_iff_lt _);
rintro rfl; simpa using h,
end
/-!
### Strictly monotone functions and `cmp`
-/
lemma strict_mono_on.cmp_map_eq (hf : strict_mono_on f s) (hx : x ∈ s) (hy : y ∈ s) :
cmp (f x) (f y) = cmp x y :=
((hf.compares hx hy).2 (cmp_compares x y)).cmp_eq
lemma strict_mono.cmp_map_eq (hf : strict_mono f) (x y : α) : cmp (f x) (f y) = cmp x y :=
(hf.strict_mono_on set.univ).cmp_map_eq trivial trivial
lemma strict_anti_on.cmp_map_eq (hf : strict_anti_on f s) (hx : x ∈ s) (hy : y ∈ s) :
cmp (f x) (f y) = cmp y x :=
hf.dual_right.cmp_map_eq hy hx
lemma strict_anti.cmp_map_eq (hf : strict_anti f) (x y : α) : cmp (f x) (f y) = cmp y x :=
(hf.strict_anti_on set.univ).cmp_map_eq trivial trivial
end linear_order
/-! ### Monotonicity in `ℕ` and `ℤ` -/
section preorder
variables [preorder α]
lemma nat.rel_of_forall_rel_succ_of_le_of_lt (r : β → β → Prop) [is_trans β r]
{f : ℕ → β} {a : ℕ} (h : ∀ n, a ≤ n → r (f n) (f (n + 1))) ⦃b c : ℕ⦄
(hab : a ≤ b) (hbc : b < c) :
r (f b) (f c) :=
begin
induction hbc with k b_lt_k r_b_k,
exacts [h _ hab, trans r_b_k (h _ (hab.trans_lt b_lt_k).le)]
end
lemma nat.rel_of_forall_rel_succ_of_le_of_le (r : β → β → Prop) [is_refl β r] [is_trans β r]
{f : ℕ → β} {a : ℕ} (h : ∀ n, a ≤ n → r (f n) (f (n + 1))) ⦃b c : ℕ⦄
(hab : a ≤ b) (hbc : b ≤ c) :
r (f b) (f c) :=
hbc.eq_or_lt.elim (λ h, h ▸ refl _) (nat.rel_of_forall_rel_succ_of_le_of_lt r h hab)
lemma nat.rel_of_forall_rel_succ_of_lt (r : β → β → Prop) [is_trans β r]
{f : ℕ → β} (h : ∀ n, r (f n) (f (n + 1))) ⦃a b : ℕ⦄ (hab : a < b) : r (f a) (f b) :=
nat.rel_of_forall_rel_succ_of_le_of_lt r (λ n _, h n) le_rfl hab
lemma nat.rel_of_forall_rel_succ_of_le (r : β → β → Prop) [is_refl β r] [is_trans β r]
{f : ℕ → β} (h : ∀ n, r (f n) (f (n + 1))) ⦃a b : ℕ⦄ (hab : a ≤ b) : r (f a) (f b) :=
nat.rel_of_forall_rel_succ_of_le_of_le r (λ n _, h n) le_rfl hab
lemma monotone_nat_of_le_succ {f : ℕ → α} (hf : ∀ n, f n ≤ f (n + 1)) :
monotone f :=
nat.rel_of_forall_rel_succ_of_le (≤) hf
lemma antitone_nat_of_succ_le {f : ℕ → α} (hf : ∀ n, f (n + 1) ≤ f n) : antitone f :=
@monotone_nat_of_le_succ αᵒᵈ _ _ hf
lemma strict_mono_nat_of_lt_succ {f : ℕ → α} (hf : ∀ n, f n < f (n + 1)) : strict_mono f :=
nat.rel_of_forall_rel_succ_of_lt (<) hf
lemma strict_anti_nat_of_succ_lt {f : ℕ → α} (hf : ∀ n, f (n + 1) < f n) : strict_anti f :=
@strict_mono_nat_of_lt_succ αᵒᵈ _ f hf
namespace nat
/-- If `α` is a preorder with no maximal elements, then there exists a strictly monotone function
`ℕ → α` with any prescribed value of `f 0`. -/
lemma exists_strict_mono' [no_max_order α] (a : α) : ∃ f : ℕ → α, strict_mono f ∧ f 0 = a :=
begin
have := (λ x : α, exists_gt x),
choose g hg,
exact ⟨λ n, nat.rec_on n a (λ _, g), strict_mono_nat_of_lt_succ $ λ n, hg _, rfl⟩
end
/-- If `α` is a preorder with no maximal elements, then there exists a strictly antitone function
`ℕ → α` with any prescribed value of `f 0`. -/
lemma exists_strict_anti' [no_min_order α] (a : α) : ∃ f : ℕ → α, strict_anti f ∧ f 0 = a :=
exists_strict_mono' (order_dual.to_dual a)
variable (α)
/-- If `α` is a nonempty preorder with no maximal elements, then there exists a strictly monotone
function `ℕ → α`. -/
lemma exists_strict_mono [nonempty α] [no_max_order α] : ∃ f : ℕ → α, strict_mono f :=
let ⟨a⟩ := ‹nonempty α›, ⟨f, hf, hfa⟩ := exists_strict_mono' a in ⟨f, hf⟩
/-- If `α` is a nonempty preorder with no minimal elements, then there exists a strictly antitone
function `ℕ → α`. -/
lemma exists_strict_anti [nonempty α] [no_min_order α] : ∃ f : ℕ → α, strict_anti f :=
exists_strict_mono αᵒᵈ
end nat
lemma int.rel_of_forall_rel_succ_of_lt (r : β → β → Prop) [is_trans β r]
{f : ℤ → β} (h : ∀ n, r (f n) (f (n + 1))) ⦃a b : ℤ⦄ (hab : a < b) : r (f a) (f b) :=
begin
rcases hab.dest with ⟨n, rfl⟩, clear hab,
induction n with n ihn,
{ rw int.coe_nat_one, apply h },
{ rw [int.coe_nat_succ, ← int.add_assoc],
exact trans ihn (h _) }
end
lemma int.rel_of_forall_rel_succ_of_le (r : β → β → Prop) [is_refl β r] [is_trans β r]
{f : ℤ → β} (h : ∀ n, r (f n) (f (n + 1))) ⦃a b : ℤ⦄ (hab : a ≤ b) : r (f a) (f b) :=
hab.eq_or_lt.elim (λ h, h ▸ refl _) (λ h', int.rel_of_forall_rel_succ_of_lt r h h')
lemma monotone_int_of_le_succ {f : ℤ → α} (hf : ∀ n, f n ≤ f (n + 1)) : monotone f :=
int.rel_of_forall_rel_succ_of_le (≤) hf
lemma antitone_int_of_succ_le {f : ℤ → α} (hf : ∀ n, f (n + 1) ≤ f n) : antitone f :=
int.rel_of_forall_rel_succ_of_le (≥) hf
lemma strict_mono_int_of_lt_succ {f : ℤ → α} (hf : ∀ n, f n < f (n + 1)) : strict_mono f :=
int.rel_of_forall_rel_succ_of_lt (<) hf
lemma strict_anti_int_of_succ_lt {f : ℤ → α} (hf : ∀ n, f (n + 1) < f n) : strict_anti f :=
int.rel_of_forall_rel_succ_of_lt (>) hf
namespace int
variables (α) [nonempty α] [no_min_order α] [no_max_order α]
/-- If `α` is a nonempty preorder with no minimal or maximal elements, then there exists a strictly
monotone function `f : ℤ → α`. -/
lemma exists_strict_mono : ∃ f : ℤ → α, strict_mono f :=
begin
inhabit α,
rcases nat.exists_strict_mono' (default : α) with ⟨f, hf, hf₀⟩,
rcases nat.exists_strict_anti' (default : α) with ⟨g, hg, hg₀⟩,
refine ⟨λ n, int.cases_on n f (λ n, g (n + 1)), strict_mono_int_of_lt_succ _⟩,
rintro (n|_|n),
{ exact hf n.lt_succ_self },
{ show g 1 < f 0,
rw [hf₀, ← hg₀],
exact hg nat.zero_lt_one },
{ exact hg (nat.lt_succ_self _) }
end
/-- If `α` is a nonempty preorder with no minimal or maximal elements, then there exists a strictly
antitone function `f : ℤ → α`. -/
lemma exists_strict_anti : ∃ f : ℤ → α, strict_anti f := exists_strict_mono αᵒᵈ
end int
-- TODO@Yael: Generalize the following four to succ orders
/-- If `f` is a monotone function from `ℕ` to a preorder such that `x` lies between `f n` and
`f (n + 1)`, then `x` doesn't lie in the range of `f`. -/
lemma monotone.ne_of_lt_of_lt_nat {f : ℕ → α} (hf : monotone f) (n : ℕ) {x : α}
(h1 : f n < x) (h2 : x < f (n + 1)) (a : ℕ) :
f a ≠ x :=
by { rintro rfl, exact (hf.reflect_lt h1).not_le (nat.le_of_lt_succ $ hf.reflect_lt h2) }
/-- If `f` is an antitone function from `ℕ` to a preorder such that `x` lies between `f (n + 1)` and
`f n`, then `x` doesn't lie in the range of `f`. -/
lemma antitone.ne_of_lt_of_lt_nat {f : ℕ → α} (hf : antitone f)
(n : ℕ) {x : α} (h1 : f (n + 1) < x) (h2 : x < f n) (a : ℕ) : f a ≠ x :=
by { rintro rfl, exact (hf.reflect_lt h2).not_le (nat.le_of_lt_succ $ hf.reflect_lt h1) }
/-- If `f` is a monotone function from `ℤ` to a preorder and `x` lies between `f n` and
`f (n + 1)`, then `x` doesn't lie in the range of `f`. -/
lemma monotone.ne_of_lt_of_lt_int {f : ℤ → α} (hf : monotone f) (n : ℤ) {x : α}
(h1 : f n < x) (h2 : x < f (n + 1)) (a : ℤ) :
f a ≠ x :=
by { rintro rfl, exact (hf.reflect_lt h1).not_le (int.le_of_lt_add_one $ hf.reflect_lt h2) }
/-- If `f` is an antitone function from `ℤ` to a preorder and `x` lies between `f (n + 1)` and
`f n`, then `x` doesn't lie in the range of `f`. -/
lemma antitone.ne_of_lt_of_lt_int {f : ℤ → α} (hf : antitone f)
(n : ℤ) {x : α} (h1 : f (n + 1) < x) (h2 : x < f n) (a : ℤ) : f a ≠ x :=
by { rintro rfl, exact (hf.reflect_lt h2).not_le (int.le_of_lt_add_one $ hf.reflect_lt h1) }
lemma strict_mono.id_le {φ : ℕ → ℕ} (h : strict_mono φ) : ∀ n, n ≤ φ n :=
λ n, nat.rec_on n (nat.zero_le _)
(λ n hn, nat.succ_le_of_lt (hn.trans_lt $ h $ nat.lt_succ_self n))
end preorder
lemma subtype.mono_coe [preorder α] (t : set α) : monotone (coe : (subtype t) → α) :=
λ x y, id
lemma subtype.strict_mono_coe [preorder α] (t : set α) : strict_mono (coe : (subtype t) → α) :=
λ x y, id
section preorder
variables [preorder α] [preorder β] [preorder γ] [preorder δ] {f : α → γ} {g : β → δ} {a b : α}
lemma monotone_fst : monotone (@prod.fst α β) := λ a b, and.left
lemma monotone_snd : monotone (@prod.snd α β) := λ a b, and.right
lemma monotone.prod_map (hf : monotone f) (hg : monotone g) : monotone (prod.map f g) :=
λ a b h, ⟨hf h.1, hg h.2⟩
lemma antitone.prod_map (hf : antitone f) (hg : antitone g) : antitone (prod.map f g) :=
λ a b h, ⟨hf h.1, hg h.2⟩
end preorder
section partial_order
variables [partial_order α] [partial_order β] [preorder γ] [preorder δ]
{f : α → γ} {g : β → δ}
lemma strict_mono.prod_map (hf : strict_mono f) (hg : strict_mono g) : strict_mono (prod.map f g) :=
λ a b, by { simp_rw prod.lt_iff,
exact or.imp (and.imp hf.imp hg.monotone.imp) (and.imp hf.monotone.imp hg.imp) }
lemma strict_anti.prod_map (hf : strict_anti f) (hg : strict_anti g) : strict_anti (prod.map f g) :=
λ a b, by { simp_rw prod.lt_iff,
exact or.imp (and.imp hf.imp hg.antitone.imp) (and.imp hf.antitone.imp hg.imp) }
end partial_order
/-! ### Pi types -/
namespace function
variables [preorder α] [decidable_eq ι] [Π i, preorder (π i)] {f : Π i, π i} {i : ι}
lemma update_mono : monotone (f.update i) := λ a b, update_le_update_iff'.2
lemma update_strict_mono : strict_mono (f.update i) := λ a b, update_lt_update_iff.2
lemma const_mono : monotone (const β : α → β → α) := λ a b h i, h
lemma const_strict_mono [nonempty β] : strict_mono (const β : α → β → α) := λ a b, const_lt_const.2
end function
|
6f2f97d3e0c41ce7157c01496572dc2f56391b60 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/blast_recursor1.lean | dd5ea801763184f528fb536db1692c84b4853faa | [
"Apache-2.0"
] | permissive | soonhokong/lean | cb8aa01055ffe2af0fb99a16b4cda8463b882cd1 | 38607e3eb57f57f77c0ac114ad169e9e4262e24f | refs/heads/master | 1,611,187,284,081 | 1,450,766,737,000 | 1,476,122,547,000 | 11,513,992 | 2 | 0 | null | 1,401,763,102,000 | 1,374,182,235,000 | C++ | UTF-8 | Lean | false | false | 389 | lean | constants P Q : nat → Prop
inductive foo : nat → Prop :=
| intro1 : ∀ n, P n → foo n
| intro2 : ∀ n, P n → foo n
definition bar (n : nat) : foo n → P n :=
by blast
print bar
/-
definition bar : ∀ (n : ℕ), foo n → P n :=
foo.rec (λ (n : ℕ) (H.3 : P n), H.3) (λ (n : ℕ) (H.3 : P n), H.3)
-/
definition baz (n : nat) : foo n → foo n ∧ P n :=
by blast --loops
|
cb473feb46ee02749d0fea3528cd1bc6b6bb4539 | 4fa161becb8ce7378a709f5992a594764699e268 | /src/algebra/category/Algebra/basic.lean | 99fa04d32dcf9ab3c7eeb638a6c0c745af3f1add | [
"Apache-2.0"
] | permissive | laughinggas/mathlib | e4aa4565ae34e46e834434284cb26bd9d67bc373 | 86dcd5cda7a5017c8b3c8876c89a510a19d49aad | refs/heads/master | 1,669,496,232,688 | 1,592,831,995,000 | 1,592,831,995,000 | 274,155,979 | 0 | 0 | Apache-2.0 | 1,592,835,190,000 | 1,592,835,189,000 | null | UTF-8 | Lean | false | false | 3,407 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.category.CommRing.basic
import algebra.category.Module.basic
import ring_theory.algebra
open category_theory
open category_theory.limits
universe u
variables (R : Type u) [comm_ring R]
/-- The category of R-modules and their morphisms. -/
structure Algebra :=
(carrier : Type u)
[is_ring : ring carrier]
[is_algebra : algebra R carrier]
attribute [instance] Algebra.is_ring Algebra.is_algebra
namespace Algebra
instance : has_coe_to_sort (Algebra R) :=
{ S := Type u, coe := Algebra.carrier }
instance : category (Algebra.{u} R) :=
{ hom := λ A B, A →ₐ[R] B,
id := λ A, alg_hom.id R A,
comp := λ A B C f g, g.comp f }
instance : concrete_category (Algebra.{u} R) :=
{ forget := { obj := λ R, R, map := λ R S f, (f : R → S) },
forget_faithful := { } }
instance has_forget_to_Ring : has_forget₂ (Algebra R) Ring :=
{ forget₂ :=
{ obj := λ A, Ring.of A,
map := λ A₁ A₂ f, alg_hom.to_ring_hom f, } }
instance has_forget_to_Module : has_forget₂ (Algebra R) (Module R) :=
{ forget₂ :=
{ obj := λ M, Module.of R M,
map := λ M₁ M₂ f, alg_hom.to_linear_map f, } }
/-- The object in the category of R-algebras associated to a type equipped with the appropriate typeclasses. -/
def of (X : Type u) [ring X] [algebra R X] : Algebra R := ⟨X⟩
instance : inhabited (Algebra R) := ⟨of R R⟩
@[simp]
lemma of_apply (X : Type u) [ring X] [algebra R X] :
(of R X : Type u) = X := rfl
variables {R}
/-- Forgetting to the underlying type and then building the bundled object returns the original algebra. -/
@[simps]
def of_self_iso (M : Algebra R) : Algebra.of R M ≅ M :=
{ hom := 𝟙 M, inv := 𝟙 M }
variables {R} {M N U : Module R}
@[simp] lemma id_apply (m : M) : (𝟙 M : M → M) m = m := rfl
@[simp] lemma coe_comp (f : M ⟶ N) (g : N ⟶ U) :
((f ≫ g) : M → U) = g ∘ f := rfl
end Algebra
variables {R}
variables {X₁ X₂ : Type u}
/-- Build an isomorphism in the category `Algebra R` from a `alg_equiv` between `algebra`s. -/
@[simps]
def alg_equiv.to_Algebra_iso
{g₁ : ring X₁} {g₂ : ring X₂} {m₁ : algebra R X₁} {m₂ : algebra R X₂} (e : X₁ ≃ₐ[R] X₂) :
Algebra.of R X₁ ≅ Algebra.of R X₂ :=
{ hom := (e : X₁ →ₐ[R] X₂),
inv := (e.symm : X₂ →ₐ[R] X₁),
hom_inv_id' := begin ext, exact e.left_inv x, end,
inv_hom_id' := begin ext, exact e.right_inv x, end, }
namespace category_theory.iso
/-- Build a `alg_equiv` from an isomorphism in the category `Algebra R`. -/
@[simps]
def to_alg_equiv {X Y : Algebra.{u} R} (i : X ≅ Y) : X ≃ₐ[R] Y :=
{ to_fun := i.hom,
inv_fun := i.inv,
left_inv := by tidy,
right_inv := by tidy,
map_add' := by tidy,
map_mul' := by tidy,
commutes' := by tidy, }.
end category_theory.iso
/-- algebra equivalences between `algebras`s are the same as (isomorphic to) isomorphisms in `Algebra` -/
@[simps]
def alg_equiv_iso_Algebra_iso {X Y : Type u}
[ring X] [ring Y] [algebra R X] [algebra R Y] :
(X ≃ₐ[R] Y) ≅ (Algebra.of R X ≅ Algebra.of R Y) :=
{ hom := λ e, e.to_Algebra_iso,
inv := λ i, i.to_alg_equiv, }
instance (X : Type u) [ring X] [algebra R X] : has_coe (subalgebra R X) (Algebra R) :=
⟨ λ N, Algebra.of R N ⟩
|
cdc633309b04901c64718e1fd1f3d5e6ce7ca145 | 4f065978c49388d188224610d9984673079f7d91 | /perfect_closure.lean | f0aaa8067b4a23b5c3af891d16a7ea020ed0db5c | [] | no_license | kckennylau/Lean | b323103f52706304907adcfaee6f5cb8095d4a33 | 907d0a4d2bd8f23785abd6142ad53d308c54fdcb | refs/heads/master | 1,624,623,720,653 | 1,563,901,820,000 | 1,563,901,820,000 | 109,506,702 | 3 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 23,605 | lean | import data.padics.padic_norm data.nat.binomial
universes u v
theorem inv_pow' {α : Type u} [discrete_field α] {x : α} {n : ℕ} : (x⁻¹)^n = (x^n)⁻¹ :=
decidable.by_cases
(assume H : x = 0, or.cases_on (nat.eq_zero_or_pos n)
(λ hn, by rw [H, hn, pow_zero, pow_zero, inv_one])
(λ hn, by rw [H, zero_pow hn, inv_zero, zero_pow hn]))
(λ H, division_ring.inv_pow H n)
theorem pow_eq_zero {α : Type u} [domain α] {x : α} {n : ℕ} (H : x^n = 0) : x = 0 :=
begin
induction n with n ih,
{ rw pow_zero at H,
rw [← mul_one x, H, mul_zero] },
exact or.cases_on (mul_eq_zero.1 H) id ih
end
class char_p (α : Type u) [semiring α] (p : ℕ) : Prop :=
(cast_eq_zero_iff : ∀ x:ℕ, (x:α) = 0 ↔ p ∣ x)
theorem char_p.cast_eq_zero (α : Type u) [semiring α] (p : ℕ) [char_p α p] : (p:α) = 0 :=
(char_p.cast_eq_zero_iff α p p).2 (dvd_refl p)
theorem char_p.eq (α : Type u) [semiring α] {p q : ℕ} (c1 : char_p α p) (c2 : char_p α q) : p = q :=
nat.dvd_antisymm
((char_p.cast_eq_zero_iff α p q).1 (char_p.cast_eq_zero _ _))
((char_p.cast_eq_zero_iff α q p).1 (char_p.cast_eq_zero _ _))
instance char_p.of_char_zero (α : Type u) [semiring α] [char_zero α] : char_p α 0 :=
⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩
theorem char_p.exists (α : Type u) [semiring α] : ∃ p, char_p α p :=
by letI := classical.dec_eq α; exact
classical.by_cases
(assume H : ∀ p:ℕ, (p:α) = 0 → p = 0, ⟨0,
⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩)
(λ H, ⟨nat.find (classical.not_forall.1 H), ⟨λ x,
⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2,
nat.find_min (classical.not_forall.1 H)
(nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $
nat.find_spec (classical.not_forall.1 H))
(not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (classical.not_forall.1 H)),
nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)),
zero_mul, add_zero] at H1, H2⟩)),
λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul,
of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul]⟩⟩⟩)
theorem char_p.exists_unique (α : Type u) [semiring α] : ∃! p, char_p α p :=
let ⟨c, H⟩ := char_p.exists α in ⟨c, H, λ y H2, char_p.eq α H2 H⟩
noncomputable def ring_char (α : Type u) [semiring α] : ℕ :=
classical.some (char_p.exists_unique α)
theorem ring_char.spec (α : Type u) [semiring α] : ∀ x:ℕ, (x:α) = 0 ↔ ring_char α ∣ x :=
by letI := (classical.some_spec (char_p.exists_unique α)).1;
unfold ring_char; exact char_p.cast_eq_zero_iff α (ring_char α)
theorem ring_char.eq (α : Type u) [semiring α] {p : ℕ} (C : char_p α p) : p = ring_char α :=
(classical.some_spec (char_p.exists_unique α)).2 p C
theorem add_pow_char (α : Type u) [comm_ring α] {p : ℕ} (hp : nat.prime p)
[char_p α p] (x y : α) : (x + y)^p = x^p + y^p :=
begin
rw [add_pow, finset.sum_range_succ, nat.sub_self, pow_zero, choose_self],
rw [nat.cast_one, mul_one, mul_one, add_left_inj],
transitivity,
{ refine finset.sum_eq_single 0 _ _,
{ intros b h1 h2,
have := nat.prime.dvd_choose (nat.pos_of_ne_zero h2) (finset.mem_range.1 h1) hp,
rw [← nat.div_mul_cancel this, nat.cast_mul, char_p.cast_eq_zero α p],
simp only [mul_zero] },
{ intro H, exfalso, apply H, exact finset.mem_range.2 hp.pos } },
rw [pow_zero, nat.sub_zero, one_mul, choose_zero_right, nat.cast_one, mul_one]
end
theorem nat.iterate₀ {α : Type u} {op : α → α} {x : α} (H : op x = x) {n : ℕ} :
op^[n] x = x :=
by induction n; [simp only [nat.iterate_zero], simp only [nat.iterate_succ', H, *]]
theorem nat.iterate₁ {α : Type u} {β : Type v} {op : α → α} {op' : β → β} {op'' : α → β}
(H : ∀ x, op' (op'' x) = op'' (op x)) {n : ℕ} {x : α} :
op'^[n] (op'' x) = op'' (op^[n] x) :=
by induction n; [simp only [nat.iterate_zero], simp only [nat.iterate_succ', H, *]]
theorem nat.iterate₂ {α : Type u} {op : α → α} {op' : α → α → α} (H : ∀ x y, op (op' x y) = op' (op x) (op y)) {n : ℕ} {x y : α} :
op^[n] (op' x y) = op' (op^[n] x) (op^[n] y) :=
by induction n; [simp only [nat.iterate_zero], simp only [nat.iterate_succ', H, *]]
theorem nat.iterate_cancel {α : Type u} {op op' : α → α} (H : ∀ x, op (op' x) = x) {n : ℕ} {x : α} : op^[n] (op'^[n] x) = x :=
by induction n; [refl, rwa [nat.iterate_succ, nat.iterate_succ', H]]
theorem nat.iterate_inj {α : Type u} {op : α → α} (Hinj : function.injective op) (n : ℕ) (x y : α)
(H : (op^[n] x) = (op^[n] y)) : x = y :=
by induction n with n ih; simp only [nat.iterate_zero, nat.iterate_succ'] at H;
[exact H, exact ih (Hinj H)]
def frobenius (α : Type u) [monoid α] (p : ℕ) (x : α) : α := x^p
theorem frobenius_def (α : Type u) [monoid α] (p : ℕ) (x : α) : frobenius α p x = x ^ p := rfl
theorem frobenius_mul (α : Type u) [comm_monoid α] (p : ℕ) (x y : α) :
frobenius α p (x * y) = frobenius α p x * frobenius α p y := mul_pow x y p
theorem frobenius_one (α : Type u) [monoid α] (p : ℕ) :
frobenius α p 1 = 1 := one_pow _
theorem is_monoid_hom.map_frobenius {α : Type u} {β : Type v} [monoid α] [monoid β] (f : α → β) [is_monoid_hom f]
(p : ℕ) (x : α) : f (frobenius α p x) = frobenius β p (f x) :=
by unfold frobenius; induction p; simp only [pow_zero, pow_succ,
is_monoid_hom.map_one f, is_monoid_hom.map_mul f, *]
instance {α : Type u} [comm_ring α] (p : ℕ) [hp : nat.prime p] [char_p α p] : is_ring_hom (frobenius α p) :=
{ map_one := frobenius_one α p,
map_mul := frobenius_mul α p,
map_add := add_pow_char α hp }
section
variables (α : Type u) [comm_ring α] (p : ℕ) [hp : nat.prime p]
theorem frobenius_zero : frobenius α p 0 = 0 := zero_pow hp.pos
variables [char_p α p] (x y : α)
include hp
theorem frobenius_add : frobenius α p (x + y) = frobenius α p x + frobenius α p y := is_ring_hom.map_add _
theorem frobenius_neg : frobenius α p (-x) = -frobenius α p x := is_ring_hom.map_neg _
theorem frobenius_sub : frobenius α p (x - y) = frobenius α p x - frobenius α p y := is_ring_hom.map_sub _
end
theorem frobenius_inj (α : Type u) [integral_domain α] (p : ℕ) [nat.prime p] [char_p α p] (x y : α)
(H : frobenius α p x = frobenius α p y) : x = y :=
by rw ← sub_eq_zero at H ⊢; rw ← frobenius_sub at H; exact pow_eq_zero H
theorem frobenius_nat_cast (α : Type u) [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x : ℕ) :
frobenius α p x = x :=
by induction x; simp only [nat.cast_zero, nat.cast_succ, frobenius_zero, frobenius_one, frobenius_add, *]
class perfect_field (α : Type u) [field α] (p : ℕ) [char_p α p] : Type u :=
(pth_root : α → α)
(frobenius_pth_root : ∀ x, frobenius α p (pth_root x) = x)
theorem frobenius_pth_root (α : Type u) [field α] (p : ℕ) [char_p α p] [perfect_field α p] (x : α) :
frobenius α p (perfect_field.pth_root p x) = x :=
perfect_field.frobenius_pth_root p x
theorem pth_root_frobenius (α : Type u) [field α] (p : ℕ) [nat.prime p] [char_p α p] [perfect_field α p] (x : α) :
perfect_field.pth_root p (frobenius α p x) = x :=
frobenius_inj α p _ _ (by rw frobenius_pth_root)
instance pth_root.is_ring_hom (α : Type u) [field α] (p : ℕ) [nat.prime p] [char_p α p] [perfect_field α p] :
is_ring_hom (@perfect_field.pth_root α _ p _ _) :=
{ map_one := frobenius_inj α p _ _ (by rw [frobenius_pth_root, frobenius_one]),
map_mul := λ x y, frobenius_inj α p _ _ (by simp only [frobenius_pth_root, frobenius_mul]),
map_add := λ x y, frobenius_inj α p _ _ (by simp only [frobenius_pth_root, frobenius_add]) }
theorem is_ring_hom.pth_root {α : Type u} [field α] (p : ℕ) [nat.prime p] [char_p α p] [perfect_field α p]
{β : Type v} [field β] [char_p β p] [perfect_field β p] (f : α → β) [is_ring_hom f] {x : α} :
f (perfect_field.pth_root p x) = perfect_field.pth_root p (f x) :=
frobenius_inj β p _ _ (by rw [← is_monoid_hom.map_frobenius f, frobenius_pth_root, frobenius_pth_root])
inductive perfect_closure.r (α : Type u) [monoid α] (p : ℕ) : (ℕ × α) → (ℕ × α) → Prop
| intro : ∀ n x, perfect_closure.r (n, x) (n+1, frobenius α p x)
run_cmd tactic.mk_iff_of_inductive_prop `perfect_closure.r `perfect_closure.r_iff
def perfect_closure (α : Type u) [monoid α] (p : ℕ) : Type u :=
quot (perfect_closure.r α p)
namespace perfect_closure
variables (α : Type u)
private lemma mul_aux_left [comm_monoid α] (p : ℕ) (x1 x2 y : ℕ × α) (H : r α p x1 x2) :
quot.mk (r α p) (x1.1 + y.1, ((frobenius α p)^[y.1] x1.2) * ((frobenius α p)^[x1.1] y.2)) =
quot.mk (r α p) (x2.1 + y.1, ((frobenius α p)^[y.1] x2.2) * ((frobenius α p)^[x2.1] y.2)) :=
match x1, x2, H with
| _, _, r.intro _ n x := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ',
nat.iterate_succ', ← frobenius_mul, nat.succ_add]; apply r.intro
end
private lemma mul_aux_right [comm_monoid α] (p : ℕ) (x y1 y2 : ℕ × α) (H : r α p y1 y2) :
quot.mk (r α p) (x.1 + y1.1, ((frobenius α p)^[y1.1] x.2) * ((frobenius α p)^[x.1] y1.2)) =
quot.mk (r α p) (x.1 + y2.1, ((frobenius α p)^[y2.1] x.2) * ((frobenius α p)^[x.1] y2.2)) :=
match y1, y2, H with
| _, _, r.intro _ n y := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ',
nat.iterate_succ', ← frobenius_mul]; apply r.intro
end
instance [comm_monoid α] (p : ℕ) : has_mul (perfect_closure α p) :=
⟨quot.lift (λ x:ℕ×α, quot.lift (λ y:ℕ×α, quot.mk (r α p)
(x.1 + y.1, ((frobenius α p)^[y.1] x.2) * ((frobenius α p)^[x.1] y.2))) (mul_aux_right α p x))
(λ x1 x2 (H : r α p x1 x2), funext $ λ e, quot.induction_on e $ λ y,
mul_aux_left α p x1 x2 y H)⟩
instance [comm_monoid α] (p : ℕ) : comm_monoid (perfect_closure α p) :=
{ mul_assoc := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩,
quot.induction_on g $ λ ⟨s, z⟩, congr_arg (quot.mk _) $
by simp only [add_assoc, mul_assoc, nat.iterate₂ (frobenius_mul _ _),
(nat.iterate_add _ _ _ _).symm, add_comm, add_left_comm],
one := quot.mk _ (0, 1),
one_mul := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $
by simp only [nat.iterate₀ (frobenius_one _ _), nat.iterate_zero, one_mul, zero_add]),
mul_one := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $
by simp only [nat.iterate₀ (frobenius_one _ _), nat.iterate_zero, mul_one, add_zero]),
mul_comm := λ e f, quot.induction_on e (λ ⟨m, x⟩, quot.induction_on f (λ ⟨n, y⟩,
congr_arg (quot.mk _) $ by simp only [add_comm, mul_comm])),
.. (infer_instance : has_mul (perfect_closure α p)) }
private lemma add_aux_left [comm_ring α] (p : ℕ) (hp : nat.prime p) [char_p α p]
(x1 x2 y : ℕ × α) (H : r α p x1 x2) :
quot.mk (r α p) (x1.1 + y.1, ((frobenius α p)^[y.1] x1.2) + ((frobenius α p)^[x1.1] y.2)) =
quot.mk (r α p) (x2.1 + y.1, ((frobenius α p)^[y.1] x2.2) + ((frobenius α p)^[x2.1] y.2)) :=
match x1, x2, H with
| _, _, r.intro _ n x := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ',
nat.iterate_succ', ← frobenius_add, nat.succ_add]; apply r.intro
end
private lemma add_aux_right [comm_ring α] (p : ℕ) (hp : nat.prime p) [char_p α p]
(x y1 y2 : ℕ × α) (H : r α p y1 y2) :
quot.mk (r α p) (x.1 + y1.1, ((frobenius α p)^[y1.1] x.2) + ((frobenius α p)^[x.1] y1.2)) =
quot.mk (r α p) (x.1 + y2.1, ((frobenius α p)^[y2.1] x.2) + ((frobenius α p)^[x.1] y2.2)) :=
match y1, y2, H with
| _, _, r.intro _ n y := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ',
nat.iterate_succ', ← frobenius_add]; apply r.intro
end
instance [comm_ring α] (p : ℕ) [hp : nat.prime p] [char_p α p] : has_add (perfect_closure α p) :=
⟨quot.lift (λ x:ℕ×α, quot.lift (λ y:ℕ×α, quot.mk (r α p)
(x.1 + y.1, ((frobenius α p)^[y.1] x.2) + ((frobenius α p)^[x.1] y.2))) (add_aux_right α p hp x))
(λ x1 x2 (H : r α p x1 x2), funext $ λ e, quot.induction_on e $ λ y,
add_aux_left α p hp x1 x2 y H)⟩
instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : has_neg (perfect_closure α p) :=
⟨quot.lift (λ x:ℕ×α, quot.mk (r α p) (x.1, -x.2)) (λ x y (H : r α p x y), match x, y, H with
| _, _, r.intro _ n x := quot.sound $ by rw ← frobenius_neg; apply r.intro
end)⟩
theorem mk_zero [comm_ring α] (p : ℕ) [nat.prime p] (n : ℕ) : quot.mk (r α p) (n, 0) = quot.mk (r α p) (0, 0) :=
by induction n with n ih; [refl, rw ← ih]; symmetry; apply quot.sound;
have := r.intro p n (0:α); rwa [frobenius_zero α p] at this
theorem r.sound [monoid α] (p m n : ℕ) (x y : α) (H : frobenius α p^[m] x = y) :
quot.mk (r α p) (n, x) = quot.mk (r α p) (m + n, y) :=
by subst H; induction m with m ih; [simp only [zero_add, nat.iterate_zero],
rw [ih, nat.succ_add, nat.iterate_succ']]; apply quot.sound; apply r.intro
instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : comm_ring (perfect_closure α p) :=
{ add_assoc := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩,
quot.induction_on g $ λ ⟨s, z⟩, congr_arg (quot.mk _) $
by simp only [add_assoc, nat.iterate₂ (frobenius_add α p),
(nat.iterate_add _ _ _ _).symm, add_comm, add_left_comm],
zero := quot.mk _ (0, 0),
zero_add := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $
by simp only [nat.iterate₀ (frobenius_zero α p), nat.iterate_zero, zero_add]),
add_zero := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $
by simp only [nat.iterate₀ (frobenius_zero α p), nat.iterate_zero, add_zero]),
add_left_neg := λ e, quot.induction_on e (λ ⟨n, x⟩, show quot.mk _ _ = _,
by simp only [nat.iterate₁ (frobenius_neg α p), add_left_neg, mk_zero]; refl),
add_comm := λ e f, quot.induction_on e (λ ⟨m, x⟩, quot.induction_on f (λ ⟨n, y⟩,
congr_arg (quot.mk _) $ by simp only [add_comm])),
left_distrib := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩,
quot.induction_on g $ λ ⟨s, z⟩, show quot.mk _ _ = quot.mk _ _,
by simp only [add_assoc, add_comm, add_left_comm]; apply r.sound;
simp only [nat.iterate₂ (frobenius_mul α p), nat.iterate₂ (frobenius_add α p),
(nat.iterate_add _ _ _ _).symm, mul_add, add_comm, add_left_comm],
right_distrib := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩,
quot.induction_on g $ λ ⟨s, z⟩, show quot.mk _ _ = quot.mk _ _,
by simp only [add_assoc, add_comm _ s, add_left_comm _ s]; apply r.sound;
simp only [nat.iterate₂ (frobenius_mul α p), nat.iterate₂ (frobenius_add α p),
(nat.iterate_add _ _ _ _).symm, add_mul, add_comm, add_left_comm],
.. (infer_instance : has_add (perfect_closure α p)),
.. (infer_instance : has_neg (perfect_closure α p)),
.. (infer_instance : comm_monoid (perfect_closure α p)) }
instance [discrete_field α] (p : ℕ) [nat.prime p] [char_p α p] : has_inv (perfect_closure α p) :=
⟨quot.lift (λ x:ℕ×α, quot.mk (r α p) (x.1, x.2⁻¹)) (λ x y (H : r α p x y), match x, y, H with
| _, _, r.intro _ n x := quot.sound $ by simp only [frobenius]; rw [← inv_pow']; apply r.intro
end)⟩
theorem eq_iff' [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p]
(x y : ℕ × α) : quot.mk (r α p) x = quot.mk (r α p) y ↔
∃ z, (frobenius α p^[y.1 + z] x.2) = (frobenius α p^[x.1 + z] y.2) :=
begin
split,
{ intro H,
replace H := quot.exact _ H,
induction H,
case eqv_gen.rel : x y H
{ cases H with n x, exact ⟨0, rfl⟩ },
case eqv_gen.refl : H
{ exact ⟨0, rfl⟩ },
case eqv_gen.symm : x y H ih
{ cases ih with w ih, exact ⟨w, ih.symm⟩ },
case eqv_gen.trans : x y z H1 H2 ih1 ih2
{ cases ih1 with z1 ih1,
cases ih2 with z2 ih2,
existsi z2+(y.1+z1),
rw [← add_assoc, nat.iterate_add, ih1],
rw [← nat.iterate_add, add_comm, nat.iterate_add, ih2],
rw [← nat.iterate_add],
simp only [add_comm, add_left_comm] } },
intro H,
cases x with m x,
cases y with n y,
cases H with z H, dsimp only at H,
rw [r.sound α p (n+z) m x _ rfl, r.sound α p (m+z) n y _ rfl, H],
rw [add_assoc, add_comm, add_comm z]
end
theorem eq_iff [integral_domain α] (p : ℕ) [nat.prime p] [char_p α p]
(x y : ℕ × α) : quot.mk (r α p) x = quot.mk (r α p) y ↔
(frobenius α p^[y.1] x.2) = (frobenius α p^[x.1] y.2) :=
(eq_iff' α p x y).trans ⟨λ ⟨z, H⟩, nat.iterate_inj (frobenius_inj α p) z _ _ $
by simpa only [add_comm, nat.iterate_add] using H,
λ H, ⟨0, H⟩⟩
instance [discrete_field α] (p : ℕ) [nat.prime p] [char_p α p] : discrete_field (perfect_closure α p) :=
{ zero_ne_one := λ H, zero_ne_one ((eq_iff _ _ _ _).1 H),
mul_inv_cancel := λ e, quot.induction_on e $ λ ⟨m, x⟩ H,
have _ := mt (eq_iff _ _ _ _).2 H, (eq_iff _ _ _ _).2
(by simp only [nat.iterate₀ (frobenius_one _ _), nat.iterate₀ (frobenius_zero α p),
nat.iterate_zero, (nat.iterate₂ (frobenius_mul α p)).symm] at this ⊢;
rw [mul_inv_cancel this, nat.iterate₀ (frobenius_one _ _)]),
inv_mul_cancel := λ e, quot.induction_on e $ λ ⟨m, x⟩ H,
have _ := mt (eq_iff _ _ _ _).2 H, (eq_iff _ _ _ _).2
(by simp only [nat.iterate₀ (frobenius_one _ _), nat.iterate₀ (frobenius_zero α p),
nat.iterate_zero, (nat.iterate₂ (frobenius_mul α p)).symm] at this ⊢;
rw [inv_mul_cancel this, nat.iterate₀ (frobenius_one _ _)]),
has_decidable_eq := λ e f, quot.rec_on_subsingleton e $ λ ⟨m, x⟩,
quot.rec_on_subsingleton f $ λ ⟨n, y⟩,
decidable_of_iff' _ (eq_iff α p _ _),
inv_zero := congr_arg (quot.mk (r α p)) (by rw [inv_zero]),
.. (infer_instance : has_inv (perfect_closure α p)),
.. (infer_instance : comm_ring (perfect_closure α p)) }
theorem frobenius_mk [comm_monoid α] (p : ℕ) (x : ℕ × α) :
frobenius (perfect_closure α p) p (quot.mk (r α p) x) = quot.mk _ (x.1, x.2^p) :=
begin
unfold frobenius, cases x with n x, dsimp only,
suffices : ∀ p':ℕ, (quot.mk (r α p) (n, x) ^ p' : perfect_closure α p) = quot.mk (r α p) (n, x ^ p'),
{ apply this },
intro p, induction p with p ih,
case nat.zero { apply r.sound, rw [nat.iterate₀ (frobenius_one _ _), pow_zero] },
case nat.succ {
rw [pow_succ, ih],
symmetry,
apply r.sound,
simp only [pow_succ, nat.iterate₂ (frobenius_mul _ _)]
}
end
def frobenius_equiv [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] :
perfect_closure α p ≃ perfect_closure α p :=
{ to_fun := frobenius (perfect_closure α p) p,
inv_fun := λ e, quot.lift_on e (λ x, quot.mk (r α p) (x.1 + 1, x.2)) (λ x y H,
match x, y, H with
| _, _, r.intro _ n x := quot.sound (r.intro _ _ _)
end),
left_inv := λ e, quot.induction_on e (λ ⟨m, x⟩, by rw frobenius_mk;
symmetry; apply quot.sound; apply r.intro),
right_inv := λ e, quot.induction_on e (λ ⟨m, x⟩, by rw frobenius_mk;
symmetry; apply quot.sound; apply r.intro) }
theorem frobenius_equiv_apply [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] {x : perfect_closure α p} :
frobenius_equiv α p x = frobenius _ p x :=
rfl
theorem nat_cast [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (n x : ℕ) :
(x : perfect_closure α p) = quot.mk (r α p) (n, x) :=
begin
induction n with n ih,
{ induction x with x ih, {refl},
rw [nat.cast_succ, nat.cast_succ, ih], refl },
rw ih, apply quot.sound,
conv {congr, skip, skip, rw ← frobenius_nat_cast α p x},
apply r.intro
end
theorem int_cast [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x : ℤ) :
(x : perfect_closure α p) = quot.mk (r α p) (0, x) :=
by induction x; simp only [int.cast_of_nat, int.cast_neg_succ_of_nat, nat_cast α p 0]; refl
theorem nat_cast_eq_iff [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x y : ℕ) :
(x : perfect_closure α p) = y ↔ (x : α) = y :=
begin
split; intro H,
{ rw [nat_cast α p 0, nat_cast α p 0, eq_iff'] at H,
cases H with z H,
simpa only [zero_add, nat.iterate₀ (frobenius_nat_cast α p _)] using H },
rw [nat_cast α p 0, nat_cast α p 0, H]
end
instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : char_p (perfect_closure α p) p :=
begin
constructor, intro x, rw ← char_p.cast_eq_zero_iff α,
rw [← nat.cast_zero, nat_cast_eq_iff, nat.cast_zero]
end
instance [discrete_field α] (p : ℕ) [nat.prime p] [char_p α p] : perfect_field (perfect_closure α p) p :=
{ pth_root := (frobenius_equiv α p).symm,
frobenius_pth_root := (frobenius_equiv α p).apply_inverse_apply }
def of [monoid α] (p : ℕ) (x : α) : perfect_closure α p :=
quot.mk _ (0, x)
instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : is_ring_hom (of α p) :=
{ map_one := rfl,
map_mul := λ x y, rfl,
map_add := λ x y, rfl }
theorem eq_pth_root [discrete_field α] (p : ℕ) [nat.prime p] [char_p α p] (m : ℕ) (x : α) :
quot.mk (r α p) (m, x) = (perfect_field.pth_root p^[m] (of α p x) : perfect_closure α p) :=
begin
unfold of,
induction m with m ih, {refl},
rw [nat.iterate_succ', ← ih]; refl
end
def UMP [discrete_field α] (p : ℕ) [nat.prime p] [char_p α p]
(β : Type v) [discrete_field β] [char_p β p] [perfect_field β p] :
{ f : α → β // is_ring_hom f } ≃ { f : perfect_closure α p → β // is_ring_hom f } :=
{ to_fun := λ f, ⟨λ e, quot.lift_on e (λ x, perfect_field.pth_root p^[x.1] (f.1 x.2))
(λ x y H, match x, y, H with | _, _, r.intro _ n x := by letI := f.2;
simp only [is_monoid_hom.map_frobenius f.1, nat.iterate_succ, pth_root_frobenius]
end),
show f.1 1 = 1, from f.2.1,
λ j k, quot.induction_on j $ λ ⟨m, x⟩, quot.induction_on k $ λ ⟨n, y⟩,
show (perfect_field.pth_root p^[_] _) = (perfect_field.pth_root p^[_] _) * (perfect_field.pth_root p^[_] _),
by letI := f.2; simp only [is_ring_hom.map_mul f.1, (nat.iterate₁ (λ x, (is_monoid_hom.map_frobenius f.1 p x).symm)).symm,
@nat.iterate₂ β _ (*) (λ x y, is_ring_hom.map_mul (perfect_field.pth_root p))];
rw [nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p),
add_comm, nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p)],
λ j k, quot.induction_on j $ λ ⟨m, x⟩, quot.induction_on k $ λ ⟨n, y⟩,
show (perfect_field.pth_root p^[_] _) = (perfect_field.pth_root p^[_] _) + (perfect_field.pth_root p^[_] _),
by letI := f.2; simp only [is_ring_hom.map_add f.1, (nat.iterate₁ (λ x, (is_monoid_hom.map_frobenius f.1 p x).symm)).symm,
@nat.iterate₂ β _ (+) (λ x y, is_ring_hom.map_add (perfect_field.pth_root p))];
rw [nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p),
add_comm m, nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p)]⟩,
inv_fun := λ f, ⟨f.1 ∘ of α p, @@is_ring_hom.comp _ _ _ _ _ _ f.2⟩,
left_inv := λ ⟨f, hf⟩, subtype.eq rfl,
right_inv := λ ⟨f, hf⟩, subtype.eq $ funext $ λ i, quot.induction_on i $ λ ⟨m, x⟩,
show perfect_field.pth_root p^[m] (f _) = f _,
by resetI; rw [eq_pth_root, @nat.iterate₁ _ _ _ _ f (λ x:perfect_closure α p, (is_ring_hom.pth_root p f).symm)] }
end perfect_closure
|
e648eea165484d93082d4fa39417efc5b9fa892e | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /archive/imo/imo2008_q4.lean | b3446ebb9856659d6052e0e4fe7cd16542c24bd6 | [
"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 | 5,645 | lean | /-
Copyright (c) 2021 Manuel Candales. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Manuel Candales
-/
import data.real.basic
import data.real.sqrt
import data.real.nnreal
/-!
# IMO 2008 Q4
Find all functions `f : (0,∞) → (0,∞)` (so, `f` is a function from the positive real
numbers to the positive real numbers) such that
```
(f(w)^2 + f(x)^2)/(f(y^2) + f(z^2)) = (w^2 + x^2)/(y^2 + z^2)
```
for all positive real numbers `w`, `x`, `y`, `z`, satisfying `wx = yz`.
# Solution
The desired theorem is that either `f = λ x, x` or `f = λ x, 1/x`
-/
open real
lemma abs_eq_one_of_pow_eq_one (x : ℝ) (n : ℕ) (hn : n ≠ 0) (h : x ^ n = 1) : abs x = 1 :=
begin
let x₀ := nnreal.of_real (abs x),
have h' : (abs x) ^ n = 1, { rwa [pow_abs, h, abs_one] },
have : (x₀ : ℝ) ^ n = 1, rw (nnreal.coe_of_real (abs x) (abs_nonneg x)), exact h',
have : x₀ = 1 := eq_one_of_pow_eq_one hn (show x₀ ^ n = 1, by assumption_mod_cast),
rwa ← nnreal.coe_of_real (abs x) (abs_nonneg x), assumption_mod_cast,
end
theorem imo2008_q4
(f : ℝ → ℝ)
(H₁ : ∀ x > 0, f(x) > 0) :
(∀ w x y z : ℝ, 0 < w → 0 < x → 0 < y → 0 < z → w * x = y * z →
(f(w) ^ 2 + f(x) ^ 2) / (f(y ^ 2) + f(z ^ 2)) = (w ^ 2 + x ^ 2) / (y ^ 2 + z ^ 2)) ↔
((∀ x > 0, f(x) = x) ∨ (∀ x > 0, f(x) = 1 / x)) :=
begin
split, swap,
-- proof that f(x) = x and f(x) = 1/x satisfy the condition
{ rintros (h | h),
{ intros w x y z hw hx hy hz hprod,
rw [h w hw, h x hx, h (y ^ 2) (pow_pos hy 2), h (z ^ 2) (pow_pos hz 2)] },
{ intros w x y z hw hx hy hz hprod,
rw [h w hw, h x hx, h (y ^ 2) (pow_pos hy 2), h (z ^ 2) (pow_pos hz 2)],
have hy2z2 : y ^ 2 + z ^ 2 ≠ 0 := ne_of_gt (add_pos (pow_pos hy 2) (pow_pos hz 2)),
have hz2y2 : z ^ 2 + y ^ 2 ≠ 0 := ne_of_gt (add_pos (pow_pos hz 2) (pow_pos hy 2)),
have hp2 : w ^ 2 * x ^ 2 = y ^ 2 * z ^ 2,
{ rw [← mul_pow w x 2, ← mul_pow y z 2, hprod] },
field_simp [ne_of_gt hw, ne_of_gt hx, ne_of_gt hy, ne_of_gt hz, hy2z2, hz2y2, hp2],
ring } },
-- proof that the only solutions are f(x) = x or f(x) = 1/x
intro H₂,
have h₀ : f(1) ≠ 0, { specialize H₁ 1 zero_lt_one, exact ne_of_gt H₁ },
have h₁ : f(1) = 1,
{ specialize H₂ 1 1 1 1 zero_lt_one zero_lt_one zero_lt_one zero_lt_one rfl,
norm_num at H₂,
simp only [← two_mul] at H₂,
rw mul_div_mul_left (f(1) ^ 2) (f 1) two_ne_zero at H₂,
rwa ← (div_eq_iff h₀).mpr (sq (f 1)) },
have h₂ : ∀ x > 0, (f(x) - x) * (f(x) - 1 / x) = 0,
{ intros x hx,
have h1xss : 1 * x = (sqrt x) * (sqrt x), { rw [one_mul, mul_self_sqrt (le_of_lt hx)] },
specialize H₂ 1 x (sqrt x) (sqrt x) zero_lt_one hx (sqrt_pos.mpr hx) (sqrt_pos.mpr hx) h1xss,
rw [h₁, one_pow 2, sq_sqrt (le_of_lt hx), ← two_mul (f(x)), ← two_mul x] at H₂,
have hx_ne_0 : x ≠ 0 := ne_of_gt hx,
have hfx_ne_0 : f(x) ≠ 0, { specialize H₁ x hx, exact ne_of_gt H₁ },
field_simp at H₂,
have h1 : (2 * x) * ((f(x) - x) * (f(x) - 1 / x)) = 0,
{ calc (2 * x) * ((f(x) - x) * (f(x) - 1 / x))
= 2 * (f(x) - x) * (x * f(x) - x * 1 / x) : by ring
... = 2 * (f(x) - x) * (x * f(x) - 1) : by rw (mul_div_cancel_left 1 hx_ne_0)
... = ((1 + f(x) ^ 2) * (2 * x) - (1 + x ^ 2) * (2 * f(x))) : by ring
... = 0 : sub_eq_zero.mpr H₂ },
have h2x_ne_0 : 2 * x ≠ 0 := mul_ne_zero two_ne_zero hx_ne_0,
calc ((f(x) - x) * (f(x) - 1 / x))
= (2 * x) * ((f(x) - x) * (f(x) - 1 / x)) / (2 * x) : (mul_div_cancel_left _ h2x_ne_0).symm
... = 0 : by { rw h1, exact zero_div (2 * x) } },
have h₃ : ∀ x > 0, f(x) = x ∨ f(x) = 1 / x, { simpa [sub_eq_zero] using h₂ },
by_contradiction,
push_neg at h,
rcases h with ⟨⟨b, hb, hfb₁⟩, ⟨a, ha, hfa₁⟩⟩,
obtain hfa₂ := or.resolve_right (h₃ a ha) hfa₁, -- f(a) ≠ 1/a, f(a) = a
obtain hfb₂ := or.resolve_left (h₃ b hb) hfb₁, -- f(b) ≠ b, f(b) = 1/b
have hab : a * b > 0 := mul_pos ha hb,
have habss : a * b = sqrt(a * b) * sqrt(a * b) := (mul_self_sqrt (le_of_lt hab)).symm,
specialize H₂ a b (sqrt (a * b)) (sqrt (a * b)) ha hb (sqrt_pos.mpr hab) (sqrt_pos.mpr hab) habss,
rw [sq_sqrt (le_of_lt hab), ← two_mul (f(a * b)), ← two_mul (a * b)] at H₂,
rw [hfa₂, hfb₂] at H₂,
have h2ab_ne_0 : 2 * (a * b) ≠ 0 := mul_ne_zero two_ne_zero (ne_of_gt hab),
specialize h₃ (a * b) hab,
cases h₃ with hab₁ hab₂,
-- f(ab) = ab → b^4 = 1 → b = 1 → f(b) = b → false
{ rw hab₁ at H₂, field_simp at H₂,
obtain hb₁ := or.resolve_right H₂ h2ab_ne_0,
field_simp [ne_of_gt hb] at hb₁,
rw (show b ^ 2 * b ^ 2 = b ^ 4, by ring) at hb₁,
obtain hb₂ := abs_eq_one_of_pow_eq_one b 4 (show 4 ≠ 0, by norm_num) hb₁.symm,
rw abs_of_pos hb at hb₂, rw hb₂ at hfb₁, exact hfb₁ h₁ },
-- f(ab) = 1/ab → a^4 = 1 → a = 1 → f(a) = 1/a → false
{ have hb_ne_0 : b ≠ 0 := ne_of_gt hb,
rw hab₂ at H₂, field_simp at H₂,
rw ← sub_eq_zero at H₂,
rw (show (a ^ 2 * b ^ 2 + 1) * (a * b) * (2 * (a * b)) - (a ^ 2 + b ^ 2) * (b ^ 2 * 2)
= 2 * (b ^ 4) * (a ^ 4 - 1), by ring) at H₂,
have h2b4_ne_0 : 2 * (b ^ 4) ≠ 0 := mul_ne_zero two_ne_zero (pow_ne_zero 4 hb_ne_0),
have ha₁ : a ^ 4 = 1, { simpa [sub_eq_zero, h2b4_ne_0] using H₂ },
obtain ha₂ := abs_eq_one_of_pow_eq_one a 4 (show 4 ≠ 0, by norm_num) ha₁,
rw abs_of_pos ha at ha₂, rw ha₂ at hfa₁, norm_num at hfa₁ },
end
|
d1708261c6484ac00cc291a552975852c486ec52 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/testing/slim_check/gen.lean | b7c4cd5ab50d82ffdb7aae5074e2d7f6fa0d24cd | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 5,665 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import control.random
import control.uliftable
/-!
# `gen` Monad
This monad is used to formulate randomized computations with a parameter
to specify the desired size of the result.
This is a port of the Haskell QuickCheck library.
## Main definitions
* `gen` monad
## Local notation
* `i .. j` : `Icc i j`, the set of values between `i` and `j` inclusively;
## Tags
random testing
## References
* https://hackage.haskell.org/package/QuickCheck
-/
universes u v
namespace slim_check
/-- Monad to generate random examples to test properties with.
It has a `nat` parameter so that the caller can decide on the
size of the examples. -/
@[reducible, derive [monad, is_lawful_monad]]
def gen (α : Type u) := reader_t (ulift ℕ) rand α
variable (α : Type u)
local infix ` .. `:41 := set.Icc
/-- Execute a `gen` inside the `io` monad using `i` as the example
size and with a fresh random number generator. -/
def io.run_gen {α} (x : gen α) (i : ℕ) : io α :=
io.run_rand (x.run ⟨i⟩)
namespace gen
section rand
/-- Lift `random.random` to the `gen` monad. -/
def choose_any [random α] : gen α :=
⟨ λ _, rand.random α ⟩
variables {α} [preorder α]
/-- Lift `random.random_r` to the `gen` monad. -/
def choose [bounded_random α] (x y : α) (p : x ≤ y) : gen (x .. y) :=
⟨ λ _, rand.random_r x y p ⟩
end rand
open nat (hiding choose)
/-- Generate a `nat` example between `x` and `y`. -/
def choose_nat (x y : ℕ) (p : x ≤ y) : gen (x .. y) :=
choose x y p
/-- Generate a `nat` example between `x` and `y`. -/
def choose_nat' (x y : ℕ) (p : x < y) : gen (set.Ico x y) :=
have ∀ i, x < i → i ≤ y → i.pred < y,
from λ i h₀ h₁,
show i.pred.succ ≤ y,
by rwa succ_pred_eq_of_pos; apply lt_of_le_of_lt (nat.zero_le _) h₀,
subtype.map pred (λ i (h : x+1 ≤ i ∧ i ≤ y), ⟨le_pred_of_lt h.1, this _ h.1 h.2⟩) <$>
choose (x+1) y p
open nat
instance : uliftable gen.{u} gen.{v} :=
reader_t.uliftable' (equiv.ulift.trans equiv.ulift.symm)
instance : has_orelse gen.{u} :=
⟨ λ α x y, do
b ← uliftable.up $ choose_any bool,
if b.down then x else y ⟩
variable {α}
/-- Get access to the size parameter of the `gen` monad. For
reasons of universe polymorphism, it is specified in
continuation passing style. -/
def sized (cmd : ℕ → gen α) : gen α :=
⟨ λ ⟨sz⟩, reader_t.run (cmd sz) ⟨sz⟩ ⟩
/-- Apply a function to the size parameter. -/
def resize (f : ℕ → ℕ) (cmd : gen α) : gen α :=
⟨ λ ⟨sz⟩, reader_t.run cmd ⟨f sz⟩ ⟩
/-- Create `n` examples using `cmd`. -/
def vector_of : ∀ (n : ℕ) (cmd : gen α), gen (vector α n)
| 0 _ := return vector.nil
| (succ n) cmd := vector.cons <$> cmd <*> vector_of n cmd
/-- Create a list of examples using `cmd`. The size is controlled
by the size parameter of `gen`. -/
def list_of (cmd : gen α) : gen (list α) :=
sized $ λ sz, do
do ⟨ n ⟩ ← uliftable.up $ choose_nat 0 (sz + 1) dec_trivial,
v ← vector_of n.val cmd,
return v.to_list
open ulift
/-- Given a list of example generators, choose one to create an example. -/
def one_of (xs : list (gen α)) (pos : 0 < xs.length) : gen α := do
⟨⟨n, h, h'⟩⟩ ← uliftable.up $ choose_nat' 0 xs.length pos,
list.nth_le xs n h'
/-- Given a list of example generators, choose one to create an example. -/
def elements (xs : list α) (pos : 0 < xs.length) : gen α := do
⟨⟨n,h₀,h₁⟩⟩ ← uliftable.up $ choose_nat' 0 xs.length pos,
pure $ list.nth_le xs n h₁
/--
`freq_aux xs i _` takes a weighted list of generator and a number meant to select one of the
generators.
If we consider `freq_aux [(1, gena), (3, genb), (5, genc)] 4 _`, we choose a generator by splitting
the interval 1-9 into 1-1, 2-4, 5-9 so that the width of each interval corresponds to one of the
number in the list of generators. Then, we check which interval 4 falls into: it selects `genb`.
-/
def freq_aux : Π (xs : list (ℕ+ × gen α)) i, i < (xs.map (subtype.val ∘ prod.fst)).sum → gen α
| [] i h := false.elim (nat.not_lt_zero _ h)
| ((i, x) :: xs) j h :=
if h' : j < i then x
else freq_aux xs (j - i)
(by { rw tsub_lt_iff_right (le_of_not_gt h'),
simpa [list.sum_cons, add_comm] using h })
/--
`freq [(1, gena), (3, genb), (5, genc)] _` will choose one of `gena`, `genb`, `genc` with
probabilities proportional to the number accompanying them. In this example, the sum of
those numbers is 9, `gena` will be chosen with probability ~1/9, `genb` with ~3/9 (i.e. 1/3)
and `genc` with probability 5/9.
-/
def freq (xs : list (ℕ+ × gen α)) (pos : 0 < xs.length) : gen α :=
let s := (xs.map (subtype.val ∘ prod.fst)).sum in
have ha : 1 ≤ s, from
(le_trans pos $
list.length_map (subtype.val ∘ prod.fst) xs ▸
(list.length_le_sum_of_one_le _ (λ i, by { simp, intros, assumption }))),
have 0 ≤ s - 1, from le_tsub_of_add_le_right ha,
uliftable.adapt_up gen.{0} gen.{u} (choose_nat 0 (s-1) this) $ λ i,
freq_aux xs i.1 (by rcases i with ⟨i,h₀,h₁⟩; rwa le_tsub_iff_right at h₁; exact ha)
/-- Generate a random permutation of a given list. -/
def permutation_of {α : Type u} : Π xs : list α, gen (subtype $ list.perm xs)
| [] := pure ⟨[], list.perm.nil ⟩
| (x :: xs) := do
⟨xs',h⟩ ← permutation_of xs,
⟨⟨n,_,h'⟩⟩ ← uliftable.up $ choose_nat 0 xs'.length dec_trivial,
pure ⟨list.insert_nth n x xs',
list.perm.trans (list.perm.cons _ h)
(list.perm_insert_nth _ _ h').symm ⟩
end gen
end slim_check
|
70b2f742790e7c27ef478ec5b7acf0ee9faf049d | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /tests/lean/hott/crash1.hlean | b77a52e86c93bd4aae06f5a46c830346fc04ca41 | [
"Apache-2.0"
] | permissive | jroesch/lean | 30ef0860fa905d35b9ad6f76de1a4f65c9af6871 | 3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2 | refs/heads/master | 1,586,090,835,348 | 1,455,142,203,000 | 1,455,142,277,000 | 51,536,958 | 1 | 0 | null | 1,455,215,811,000 | 1,455,215,811,000 | null | UTF-8 | Lean | false | false | 730 | hlean | import types.sigma types.prod
import algebra.binary algebra.group
open eq eq.ops
namespace algebra
variable {A : Type}
structure distrib [class] (A : Type) extends has_mul A, has_add A :=
(left_distrib : ∀a b c, mul a (add b c) = add (mul a b) (mul a c))
(right_distrib : ∀a b c, mul (add a b) c = add (mul a c) (mul b c))
structure mul_zero_class [class] (A : Type) extends has_mul A, has_zero A :=
(zero_mul : Πa, mul zero a = zero)
(mul_zero : Πa, mul a zero = zero)
structure zero_ne_one_class [class] (A : Type) extends has_zero A, has_one A :=
(zero_ne_one : zero ≠ one)
structure semiring [class] (A : Type) extends add_comm_monoid A, monoid A,
distrib A, mul_zero_class A, zero_ne_one_class A
end algebra
|
bb32d5940efa49a83137f6e16f9c4aa8e078dc2b | 12dabd587ce2621d9a4eff9f16e354d02e206c8e | /world02/level05.lean | 07c351e35d58fe301e731b92b1bf14d4bf84d1aa | [] | no_license | abdelq/natural-number-game | a1b5b8f1d52625a7addcefc97c966d3f06a48263 | bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2 | refs/heads/master | 1,668,606,478,691 | 1,594,175,058,000 | 1,594,175,058,000 | 278,673,209 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 119 | lean | theorem succ_eq_add_one (n : mynat) : succ n = n + 1 :=
begin
rw one_eq_succ_zero,
rw add_succ,
rw add_zero,
refl,
end
|
1d54971657ee2612072fed9304318948bf14a645 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/pfunctor/univariate/basic.lean | 479b4bab22d4337ab46526ca2e424d3242e1622c | [] | 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 | 6,811 | lean | /-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.W
import Mathlib.PostPort
universes u l u_1 u_2 u_3
namespace Mathlib
/-!
# Polynomial functors
This file defines polynomial functors and the W-type construction as a
polynomial functor. (For the M-type construction, see
pfunctor/M.lean.)
-/
/--
A polynomial functor `P` is given by a type `A` and a family `B` of types over `A`. `P` maps
any type `α` to a new type `P.obj α`, which is defined as the sigma type `Σ x, P.B x → α`.
An element of `P.obj α` is a pair `⟨a, f⟩`, where `a` is an element of a type `A` and
`f : B a → α`. Think of `a` as the shape of the object and `f` as an index to the relevant
elements of `α`.
-/
structure pfunctor
where
A : Type u
B : A → Type u
namespace pfunctor
protected instance inhabited : Inhabited pfunctor :=
{ default := mk Inhabited.default Inhabited.default }
/-- Applying `P` to an object of `Type` -/
def obj (P : pfunctor) (α : Type u_2) :=
sigma fun (x : A P) => B P x → α
/-- Applying `P` to a morphism of `Type` -/
def map (P : pfunctor) {α : Type u_2} {β : Type u_3} (f : α → β) : obj P α → obj P β :=
fun (_x : obj P α) => sorry
protected instance obj.inhabited (P : pfunctor) {α : Type u} [Inhabited (A P)] [Inhabited α] : Inhabited (obj P α) :=
{ default := sigma.mk Inhabited.default fun (_x : B P Inhabited.default) => Inhabited.default }
protected instance obj.functor (P : pfunctor) : Functor (obj P) :=
{ map := map P, mapConst := fun (α β : Type u_2) => map P ∘ function.const β }
protected theorem map_eq (P : pfunctor) {α : Type u_2} {β : Type u_2} (f : α → β) (a : A P) (g : B P a → α) : f <$> sigma.mk a g = sigma.mk a (f ∘ g) :=
rfl
protected theorem id_map (P : pfunctor) {α : Type u_2} (x : obj P α) : id <$> x = id x := sorry
protected theorem comp_map (P : pfunctor) {α : Type u_2} {β : Type u_2} {γ : Type u_2} (f : α → β) (g : β → γ) (x : obj P α) : (g ∘ f) <$> x = g <$> f <$> x := sorry
protected instance obj.is_lawful_functor (P : pfunctor) : is_lawful_functor (obj P) :=
is_lawful_functor.mk (pfunctor.id_map P) (pfunctor.comp_map P)
/-- re-export existing definition of W-types and
adapt it to a packaged definition of polynomial functor -/
def W (P : pfunctor) :=
W_type (B P)
/- inhabitants of W types is awkward to encode as an instance
assumption because there needs to be a value `a : P.A`
such that `P.B a` is empty to yield a finite tree -/
/-- root element of a W tree -/
def W.head {P : pfunctor} : W P → A P :=
sorry
/-- children of the root of a W tree -/
def W.children {P : pfunctor} (x : W P) : B P (W.head x) → W P :=
sorry
/-- destructor for W-types -/
def W.dest {P : pfunctor} : W P → obj P (W P) :=
sorry
/-- constructor for W-types -/
def W.mk {P : pfunctor} : obj P (W P) → W P :=
sorry
@[simp] theorem W.dest_mk {P : pfunctor} (p : obj P (W P)) : W.dest (W.mk p) = p :=
sigma.cases_on p fun (p_fst : A P) (p_snd : B P p_fst → W P) => Eq.refl (W.dest (W.mk (sigma.mk p_fst p_snd)))
@[simp] theorem W.mk_dest {P : pfunctor} (p : W P) : W.mk (W.dest p) = p :=
W_type.cases_on p fun (p_a : A P) (p_f : B P p_a → W_type (B P)) => Eq.refl (W.mk (W.dest (W_type.mk p_a p_f)))
/-- `Idx` identifies a location inside the application of a pfunctor.
For `F : pfunctor`, `x : F.obj α` and `i : F.Idx`, `i` can designate
one part of `x` or is invalid, if `i.1 ≠ x.1` -/
def Idx (P : pfunctor) :=
sigma fun (x : A P) => B P x
protected instance Idx.inhabited (P : pfunctor) [Inhabited (A P)] [Inhabited (B P Inhabited.default)] : Inhabited (Idx P) :=
{ default := sigma.mk Inhabited.default Inhabited.default }
/-- `x.iget i` takes the component of `x` designated by `i` if any is or returns
a default value -/
def obj.iget {P : pfunctor} [DecidableEq (A P)] {α : Type u_2} [Inhabited α] (x : obj P α) (i : Idx P) : α :=
dite (sigma.fst i = sigma.fst x) (fun (h : sigma.fst i = sigma.fst x) => sigma.snd x (cast sorry (sigma.snd i)))
fun (h : ¬sigma.fst i = sigma.fst x) => Inhabited.default
@[simp] theorem fst_map {P : pfunctor} {α : Type u} {β : Type u} (x : obj P α) (f : α → β) : sigma.fst (f <$> x) = sigma.fst x :=
sigma.cases_on x fun (x_fst : A P) (x_snd : B P x_fst → α) => Eq.refl (sigma.fst (f <$> sigma.mk x_fst x_snd))
@[simp] theorem iget_map {P : pfunctor} [DecidableEq (A P)] {α : Type u} {β : Type u} [Inhabited α] [Inhabited β] (x : obj P α) (f : α → β) (i : Idx P) (h : sigma.fst i = sigma.fst x) : obj.iget (f <$> x) i = f (obj.iget x i) := sorry
end pfunctor
/-
Composition of polynomial functors.
-/
namespace pfunctor
/-- functor composition for polynomial functors -/
def comp (P₂ : pfunctor) (P₁ : pfunctor) : pfunctor :=
mk (sigma fun (a₂ : A P₂) => B P₂ a₂ → A P₁)
fun (a₂a₁ : sigma fun (a₂ : A P₂) => B P₂ a₂ → A P₁) =>
sigma fun (u : B P₂ (sigma.fst a₂a₁)) => B P₁ (sigma.snd a₂a₁ u)
/-- constructor for composition -/
def comp.mk (P₂ : pfunctor) (P₁ : pfunctor) {α : Type} (x : obj P₂ (obj P₁ α)) : obj (comp P₂ P₁) α :=
sigma.mk (sigma.mk (sigma.fst x) (sigma.fst ∘ sigma.snd x))
fun (a₂a₁ : B (comp P₂ P₁) (sigma.mk (sigma.fst x) (sigma.fst ∘ sigma.snd x))) =>
sigma.snd (sigma.snd x (sigma.fst a₂a₁)) (sigma.snd a₂a₁)
/-- destructor for composition -/
def comp.get (P₂ : pfunctor) (P₁ : pfunctor) {α : Type} (x : obj (comp P₂ P₁) α) : obj P₂ (obj P₁ α) :=
sigma.mk (sigma.fst (sigma.fst x))
fun (a₂ : B P₂ (sigma.fst (sigma.fst x))) =>
sigma.mk (sigma.snd (sigma.fst x) a₂) fun (a₁ : B P₁ (sigma.snd (sigma.fst x) a₂)) => sigma.snd x (sigma.mk a₂ a₁)
end pfunctor
/-
Lifting predicates and relations.
-/
namespace pfunctor
theorem liftp_iff {P : pfunctor} {α : Type u} (p : α → Prop) (x : obj P α) : functor.liftp p x ↔ ∃ (a : A P), ∃ (f : B P a → α), x = sigma.mk a f ∧ ∀ (i : B P a), p (f i) := sorry
theorem liftp_iff' {P : pfunctor} {α : Type u} (p : α → Prop) (a : A P) (f : B P a → α) : functor.liftp p (sigma.mk a f) ↔ ∀ (i : B P a), p (f i) := sorry
theorem liftr_iff {P : pfunctor} {α : Type u} (r : α → α → Prop) (x : obj P α) (y : obj P α) : functor.liftr r x y ↔
∃ (a : A P),
∃ (f₀ : B P a → α), ∃ (f₁ : B P a → α), x = sigma.mk a f₀ ∧ y = sigma.mk a f₁ ∧ ∀ (i : B P a), r (f₀ i) (f₁ i) := sorry
theorem supp_eq {P : pfunctor} {α : Type u} (a : A P) (f : B P a → α) : functor.supp (sigma.mk a f) = f '' set.univ := sorry
|
d5c20157465eadce5c2e46e1aeba8b707c8271e1 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /hott/hit/coeq.hlean | 4efce25d76b36e76f1fad1b233eae5fd8647b6aa | [
"Apache-2.0"
] | permissive | soonhokong/lean | cb8aa01055ffe2af0fb99a16b4cda8463b882cd1 | 38607e3eb57f57f77c0ac114ad169e9e4262e24f | refs/heads/master | 1,611,187,284,081 | 1,450,766,737,000 | 1,476,122,547,000 | 11,513,992 | 2 | 0 | null | 1,401,763,102,000 | 1,374,182,235,000 | C++ | UTF-8 | Lean | false | false | 5,160 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
Declaration of the coequalizer
-/
import .quotient_functor types.equiv
open quotient eq equiv is_trunc sigma sigma.ops
namespace coeq
section
universe u
parameters {A B : Type.{u}} (f g : A → B)
inductive coeq_rel : B → B → Type :=
| Rmk : Π(x : A), coeq_rel (f x) (g x)
open coeq_rel
local abbreviation R := coeq_rel
definition coeq : Type := quotient coeq_rel -- TODO: define this in root namespace
definition coeq_i (x : B) : coeq :=
class_of R x
/- cp is the name Coq uses. I don't know what it abbreviates, but at least it's short :-) -/
definition cp (x : A) : coeq_i (f x) = coeq_i (g x) :=
eq_of_rel coeq_rel (Rmk f g x)
protected definition rec {P : coeq → Type} (P_i : Π(x : B), P (coeq_i x))
(Pcp : Π(x : A), P_i (f x) =[cp x] P_i (g x)) (y : coeq) : P y :=
begin
induction y,
{ apply P_i},
{ cases H, apply Pcp}
end
protected definition rec_on [reducible] {P : coeq → Type} (y : coeq)
(P_i : Π(x : B), P (coeq_i x)) (Pcp : Π(x : A), P_i (f x) =[cp x] P_i (g x)) : P y :=
rec P_i Pcp y
theorem rec_cp {P : coeq → Type} (P_i : Π(x : B), P (coeq_i x))
(Pcp : Π(x : A), P_i (f x) =[cp x] P_i (g x))
(x : A) : apd (rec P_i Pcp) (cp x) = Pcp x :=
!rec_eq_of_rel
protected definition elim {P : Type} (P_i : B → P)
(Pcp : Π(x : A), P_i (f x) = P_i (g x)) (y : coeq) : P :=
rec P_i (λx, pathover_of_eq _ (Pcp x)) y
protected definition elim_on [reducible] {P : Type} (y : coeq) (P_i : B → P)
(Pcp : Π(x : A), P_i (f x) = P_i (g x)) : P :=
elim P_i Pcp y
theorem elim_cp {P : Type} (P_i : B → P) (Pcp : Π(x : A), P_i (f x) = P_i (g x))
(x : A) : ap (elim P_i Pcp) (cp x) = Pcp x :=
begin
apply eq_of_fn_eq_fn_inv !(pathover_constant (cp x)),
rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim,rec_cp],
end
protected definition elim_type (P_i : B → Type)
(Pcp : Π(x : A), P_i (f x) ≃ P_i (g x)) (y : coeq) : Type :=
elim P_i (λx, ua (Pcp x)) y
protected definition elim_type_on [reducible] (y : coeq) (P_i : B → Type)
(Pcp : Π(x : A), P_i (f x) ≃ P_i (g x)) : Type :=
elim_type P_i Pcp y
theorem elim_type_cp (P_i : B → Type) (Pcp : Π(x : A), P_i (f x) ≃ P_i (g x))
(x : A) : transport (elim_type P_i Pcp) (cp x) = Pcp x :=
by rewrite [tr_eq_cast_ap_fn,↑elim_type,elim_cp];apply cast_ua_fn
protected definition rec_prop {P : coeq → Type} [H : Πx, is_prop (P x)]
(P_i : Π(x : B), P (coeq_i x)) (y : coeq) : P y :=
rec P_i (λa, !is_prop.elimo) y
protected definition elim_prop {P : Type} [H : is_prop P] (P_i : B → P) (y : coeq) : P :=
elim P_i (λa, !is_prop.elim) y
end
end coeq
attribute coeq.coeq_i [constructor]
attribute coeq.rec coeq.elim [unfold 8] [recursor 8]
attribute coeq.elim_type [unfold 7]
attribute coeq.rec_on coeq.elim_on [unfold 6]
attribute coeq.elim_type_on [unfold 5]
/- Flattening -/
namespace coeq
section
open function
universe u
parameters {A B : Type.{u}} (f g : A → B) (P_i : B → Type)
(Pcp : Πx : A, P_i (f x) ≃ P_i (g x))
local abbreviation P := coeq.elim_type f g P_i Pcp
local abbreviation F : sigma (P_i ∘ f) → sigma P_i :=
λz, ⟨f z.1, z.2⟩
local abbreviation G : sigma (P_i ∘ f) → sigma P_i :=
λz, ⟨g z.1, Pcp z.1 z.2⟩
local abbreviation Pr : Π⦃b b' : B⦄,
coeq_rel f g b b' → P_i b ≃ P_i b' :=
@coeq_rel.rec A B f g _ Pcp
local abbreviation P' := quotient.elim_type P_i Pr
protected definition flattening : sigma P ≃ coeq F G :=
begin
have H : Πz, P z ≃ P' z,
begin
intro z, apply equiv_of_eq,
have H1 : coeq.elim_type f g P_i Pcp = quotient.elim_type P_i Pr,
begin
change
quotient.rec P_i
(λb b' r, coeq_rel.cases_on r (λx, pathover_of_eq _ (ua (Pcp x))))
= quotient.rec P_i
(λb b' r, pathover_of_eq _ (ua (coeq_rel.cases_on r Pcp))),
have H2 : Π⦃b b' : B⦄ (r : coeq_rel f g b b'),
coeq_rel.cases_on r (λx, pathover_of_eq _ (ua (Pcp x)))
= pathover_of_eq _ (ua (coeq_rel.cases_on r Pcp))
:> P_i b =[eq_of_rel (coeq_rel f g) r] P_i b',
begin intros b b' r, cases r, reflexivity end,
rewrite (eq_of_homotopy3 H2)
end,
apply ap10 H1
end,
apply equiv.trans (sigma_equiv_sigma_right H),
apply equiv.trans !quotient.flattening.flattening_lemma,
fapply quotient.equiv,
{ reflexivity },
{ intros bp bp',
fapply equiv.MK,
{ intro r, induction r with b b' r p,
induction r with x, exact coeq_rel.Rmk F G ⟨x, p⟩ },
{ esimp, intro r, induction r with xp,
induction xp with x p,
exact quotient.flattening.flattening_rel.mk Pr
(coeq_rel.Rmk f g x) p },
{ esimp, intro r, induction r with xp,
induction xp with x p, reflexivity },
{ intro r, induction r with b b' r p,
induction r with x, reflexivity } }
end
end
end coeq
|
6274a49b14ea9114a73e3112b1eaa8998cc79a12 | 46125763b4dbf50619e8846a1371029346f4c3db | /src/order/conditionally_complete_lattice.lean | 509c563ee8890e0ed703845432d999b5902f7abf | [
"Apache-2.0"
] | permissive | thjread/mathlib | a9d97612cedc2c3101060737233df15abcdb9eb1 | 7cffe2520a5518bba19227a107078d83fa725ddc | refs/heads/master | 1,615,637,696,376 | 1,583,953,063,000 | 1,583,953,063,000 | 246,680,271 | 0 | 0 | Apache-2.0 | 1,583,960,875,000 | 1,583,960,875,000 | null | UTF-8 | Lean | false | false | 28,109 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
Adapted from the corresponding theory for complete lattices.
-/
import
order.lattice order.complete_lattice order.bounds
tactic.finish data.set.finite
/-!
# Theory of conditionally complete lattices.
A conditionally complete lattice is a lattice in which every non-empty bounded subset s
has a least upper bound and a greatest lower bound, denoted below by Sup s and Inf s.
Typical examples are real, nat, int with their usual orders.
The theory is very comparable to the theory of complete lattices, except that suitable
boundedness and nonemptiness assumptions have to be added to most statements.
We introduce two predicates bdd_above and bdd_below to express this boundedness, prove
their basic properties, and then go on to prove most useful properties of Sup and Inf
in conditionally complete lattices.
To differentiate the statements between complete lattices and conditionally complete
lattices, we prefix Inf and Sup in the statements by c, giving cInf and cSup. For instance,
Inf_le is a statement in complete lattices ensuring Inf s ≤ x, while cInf_le is the same
statement in conditionally complete lattices with an additional assumption that s is
bounded below.
-/
set_option old_structure_cmd true
open set lattice
universes u v w
variables {α : Type u} {β : Type v} {ι : Sort w}
section
/-!
Extension of Sup and Inf from a preorder `α` to `with_top α` and `with_bot α`
-/
open_locale classical
noncomputable instance {α : Type*} [preorder α] [has_Sup α] : has_Sup (with_top α) :=
⟨λ S, if ⊤ ∈ S then ⊤ else
if bdd_above (coe ⁻¹' S : set α) then ↑(Sup (coe ⁻¹' S : set α)) else ⊤⟩
noncomputable instance {α : Type*} [has_Inf α] : has_Inf (with_top α) :=
⟨λ S, if S ⊆ {⊤} then ⊤ else ↑(Inf (coe ⁻¹' S : set α))⟩
noncomputable instance {α : Type*} [has_Sup α] : has_Sup (with_bot α) :=
⟨(@with_top.lattice.has_Inf (order_dual α) _).Inf⟩
noncomputable instance {α : Type*} [preorder α] [has_Inf α] : has_Inf (with_bot α) :=
⟨(@with_top.lattice.has_Sup (order_dual α) _ _).Sup⟩
end -- section
namespace lattice
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A conditionally complete lattice is a lattice in which
every nonempty subset which is bounded above has a supremum, and
every nonempty subset which is bounded below has an infimum.
Typical examples are real numbers or natural numbers.
To differentiate the statements from the corresponding statements in (unconditional)
complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should
hold in both worlds, sometimes with additional assumptions of nonemptiness or
boundedness.-/
class conditionally_complete_lattice (α : Type u) extends lattice α, has_Sup α, has_Inf α :=
(le_cSup : ∀s a, bdd_above s → a ∈ s → a ≤ Sup s)
(cSup_le : ∀ s a, set.nonempty s → a ∈ upper_bounds s → Sup s ≤ a)
(cInf_le : ∀s a, bdd_below s → a ∈ s → Inf s ≤ a)
(le_cInf : ∀s a, set.nonempty s → a ∈ lower_bounds s → a ≤ Inf s)
class conditionally_complete_linear_order (α : Type u)
extends conditionally_complete_lattice α, decidable_linear_order α
class conditionally_complete_linear_order_bot (α : Type u)
extends conditionally_complete_lattice α, decidable_linear_order α, order_bot α :=
(cSup_empty : Sup ∅ = ⊥)
end prio
/- A complete lattice is a conditionally complete lattice, as there are no restrictions
on the properties of Inf and Sup in a complete lattice.-/
@[priority 100] -- see Note [lower instance priority]
instance conditionally_complete_lattice_of_complete_lattice [complete_lattice α]:
conditionally_complete_lattice α :=
{ le_cSup := by intros; apply le_Sup; assumption,
cSup_le := by intros; apply Sup_le; assumption,
cInf_le := by intros; apply Inf_le; assumption,
le_cInf := by intros; apply le_Inf; assumption,
..‹complete_lattice α› }
@[priority 100] -- see Note [lower instance priority]
instance conditionally_complete_linear_order_of_complete_linear_order [complete_linear_order α]:
conditionally_complete_linear_order α :=
{ ..lattice.conditionally_complete_lattice_of_complete_lattice, .. ‹complete_linear_order α› }
section conditionally_complete_lattice
variables [conditionally_complete_lattice α] {s t : set α} {a b : α}
theorem le_cSup (h₁ : bdd_above s) (h₂ : a ∈ s) : a ≤ Sup s :=
conditionally_complete_lattice.le_cSup s a h₁ h₂
theorem cSup_le (h₁ : s.nonempty) (h₂ : ∀b∈s, b ≤ a) : Sup s ≤ a :=
conditionally_complete_lattice.cSup_le s a h₁ h₂
theorem cInf_le (h₁ : bdd_below s) (h₂ : a ∈ s) : Inf s ≤ a :=
conditionally_complete_lattice.cInf_le s a h₁ h₂
theorem le_cInf (h₁ : s.nonempty) (h₂ : ∀b∈s, a ≤ b) : a ≤ Inf s :=
conditionally_complete_lattice.le_cInf s a h₁ h₂
theorem le_cSup_of_le (_ : bdd_above s) (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s :=
le_trans h (le_cSup ‹bdd_above s› hb)
theorem cInf_le_of_le (_ : bdd_below s) (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a :=
le_trans (cInf_le ‹bdd_below s› hb) h
theorem cSup_le_cSup (_ : bdd_above t) (_ : s.nonempty) (h : s ⊆ t) : Sup s ≤ Sup t :=
cSup_le ‹_› (assume (a) (ha : a ∈ s), le_cSup ‹bdd_above t› (h ha))
theorem cInf_le_cInf (_ : bdd_below t) (_ : s.nonempty) (h : s ⊆ t) : Inf t ≤ Inf s :=
le_cInf ‹_› (assume (a) (ha : a ∈ s), cInf_le ‹bdd_below t› (h ha))
lemma is_lub_cSup (ne : s.nonempty) (H : bdd_above s) : is_lub s (Sup s) :=
⟨assume x, le_cSup H, assume x, cSup_le ne⟩
lemma is_glb_cInf (ne : s.nonempty) (H : bdd_below s) : is_glb s (Inf s) :=
⟨assume x, cInf_le H, assume x, le_cInf ne⟩
-- Use `private lemma` + `alias` to escape `namespace lattice` without closing it
private lemma is_lub.cSup_eq (H : is_lub s a) (ne : s.nonempty) : Sup s = a :=
(is_lub_cSup ne ⟨a, H.1⟩).unique H
alias is_lub.cSup_eq ← is_lub.cSup_eq
private lemma is_greatest.cSup_eq (H : is_greatest s a) : Sup s = a :=
H.is_lub.cSup_eq H.nonempty
/-- A greatest element of a set is the supremum of this set. -/
alias is_greatest.cSup_eq ← is_greatest.cSup_eq
private lemma is_glb.cInf_eq (H : is_glb s a) (ne : s.nonempty) : Inf s = a :=
(is_glb_cInf ne ⟨a, H.1⟩).unique H
alias is_glb.cInf_eq ← is_glb.cInf_eq
private lemma is_least.cInf_eq (H : is_least s a) : Inf s = a :=
H.is_glb.cInf_eq H.nonempty
/-- A least element of a set is the infimum of this set. -/
alias is_least.cInf_eq ← is_least.cInf_eq
theorem cSup_le_iff (hb : bdd_above s) (ne : s.nonempty) : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) :=
is_lub_le_iff (is_lub_cSup ne hb)
theorem le_cInf_iff (hb : bdd_below s) (ne : s.nonempty) : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) :=
le_is_glb_iff (is_glb_cInf ne hb)
lemma cSup_lower_bounds_eq_cInf {s : set α} (h : bdd_below s) (hs : s.nonempty) :
Sup (lower_bounds s) = Inf s :=
(is_lub_cSup h $ hs.mono $ λ x hx y hy, hy hx).unique (is_glb_cInf hs h).is_lub
lemma cInf_upper_bounds_eq_cSup {s : set α} (h : bdd_above s) (hs : s.nonempty) :
Inf (upper_bounds s) = Sup s :=
(is_glb_cInf h $ hs.mono $ λ x hx y hy, hy hx).unique (is_lub_cSup hs h).is_glb
/--Introduction rule to prove that b is the supremum of s: it suffices to check that b
is larger than all elements of s, and that this is not the case of any `w<b`.-/
theorem cSup_intro (_ : s.nonempty) (_ : ∀a∈s, a ≤ b) (H : ∀w, w < b → (∃a∈s, w < a)) : Sup s = b :=
have bdd_above s := ⟨b, by assumption⟩,
have (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (cSup_le ‹_› ‹∀a∈s, a ≤ b›),
have ¬(Sup s < b) :=
assume: Sup s < b,
let ⟨a, _, _⟩ := (H (Sup s) ‹Sup s < b›) in /- a ∈ s, Sup s < a-/
have Sup s < Sup s := lt_of_lt_of_le ‹Sup s < a› (le_cSup ‹bdd_above s› ‹a ∈ s›),
show false, by finish [lt_irrefl (Sup s)],
show Sup s = b, by finish
/--Introduction rule to prove that b is the infimum of s: it suffices to check that b
is smaller than all elements of s, and that this is not the case of any `w>b`.-/
theorem cInf_intro (_ : s.nonempty) (_ : ∀a∈s, b ≤ a) (H : ∀w, b < w → (∃a∈s, a < w)) : Inf s = b :=
have bdd_below s := ⟨b, by assumption⟩,
have (b < Inf s) ∨ (b = Inf s) := lt_or_eq_of_le (le_cInf ‹_› ‹∀a∈s, b ≤ a›),
have ¬(b < Inf s) :=
assume: b < Inf s,
let ⟨a, _, _⟩ := (H (Inf s) ‹b < Inf s›) in /- a ∈ s, a < Inf s-/
have Inf s < Inf s := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < Inf s› ,
show false, by finish [lt_irrefl (Inf s)],
show Inf s = b, by finish
/--b < Sup s when there is an element a in s with b < a, when s is bounded above.
This is essentially an iff, except that the assumptions for the two implications are
slightly different (one needs boundedness above for one direction, nonemptiness and linear
order for the other one), so we formulate separately the two implications, contrary to
the complete_lattice case.-/
lemma lt_cSup_of_lt (_ : bdd_above s) (_ : a ∈ s) (_ : b < a) : b < Sup s :=
lt_of_lt_of_le ‹b < a› (le_cSup ‹bdd_above s› ‹a ∈ s›)
/--Inf s < b when there is an element a in s with a < b, when s is bounded below.
This is essentially an iff, except that the assumptions for the two implications are
slightly different (one needs boundedness below for one direction, nonemptiness and linear
order for the other one), so we formulate separately the two implications, contrary to
the complete_lattice case.-/
lemma cInf_lt_of_lt (_ : bdd_below s) (_ : a ∈ s) (_ : a < b) : Inf s < b :=
lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < b›
/--The supremum of a singleton is the element of the singleton-/
@[simp] theorem cSup_singleton (a : α) : Sup {a} = a :=
is_greatest_singleton.cSup_eq
/--The infimum of a singleton is the element of the singleton-/
@[simp] theorem cInf_singleton (a : α) : Inf {a} = a :=
is_least_singleton.cInf_eq
/--If a set is bounded below and above, and nonempty, its infimum is less than or equal to
its supremum.-/
theorem cInf_le_cSup (hb : bdd_below s) (ha : bdd_above s) (ne : s.nonempty) : Inf s ≤ Sup s :=
is_glb_le_is_lub (is_glb_cInf ne hb) (is_lub_cSup ne ha) ne
/--The sup of a union of two sets is the max of the suprema of each subset, under the assumptions
that all sets are bounded above and nonempty.-/
theorem cSup_union (hs : bdd_above s) (sne : s.nonempty) (ht : bdd_above t) (tne : t.nonempty) :
Sup (s ∪ t) = Sup s ⊔ Sup t :=
((is_lub_cSup sne hs).union (is_lub_cSup tne ht)).cSup_eq sne.inl
/--The inf of a union of two sets is the min of the infima of each subset, under the assumptions
that all sets are bounded below and nonempty.-/
theorem cInf_union (hs : bdd_below s) (sne : s.nonempty) (ht : bdd_below t) (tne : t.nonempty) :
Inf (s ∪ t) = Inf s ⊓ Inf t :=
((is_glb_cInf sne hs).union (is_glb_cInf tne ht)).cInf_eq sne.inl
/--The supremum of an intersection of two sets is bounded by the minimum of the suprema of each
set, if all sets are bounded above and nonempty.-/
theorem cSup_inter_le (_ : bdd_above s) (_ : bdd_above t) (hst : (s ∩ t).nonempty) :
Sup (s ∩ t) ≤ Sup s ⊓ Sup t :=
begin
apply cSup_le hst, simp only [lattice.le_inf_iff, and_imp, set.mem_inter_eq], intros b _ _, split,
apply le_cSup ‹bdd_above s› ‹b ∈ s›,
apply le_cSup ‹bdd_above t› ‹b ∈ t›
end
/--The infimum of an intersection of two sets is bounded below by the maximum of the
infima of each set, if all sets are bounded below and nonempty.-/
theorem le_cInf_inter (_ : bdd_below s) (_ : bdd_below t) (hst : (s ∩ t).nonempty) :
Inf s ⊔ Inf t ≤ Inf (s ∩ t) :=
begin
apply le_cInf hst, simp only [and_imp, set.mem_inter_eq, lattice.sup_le_iff], intros b _ _, split,
apply cInf_le ‹bdd_below s› ‹b ∈ s›,
apply cInf_le ‹bdd_below t› ‹b ∈ t›
end
/-- The supremum of insert a s is the maximum of a and the supremum of s, if s is
nonempty and bounded above.-/
theorem cSup_insert (hs : bdd_above s) (sne : s.nonempty) : Sup (insert a s) = a ⊔ Sup s :=
((is_lub_cSup sne hs).insert a).cSup_eq (insert_nonempty a s)
/-- The infimum of insert a s is the minimum of a and the infimum of s, if s is
nonempty and bounded below.-/
theorem cInf_insert (hs : bdd_below s) (sne : s.nonempty) : Inf (insert a s) = a ⊓ Inf s :=
((is_glb_cInf sne hs).insert a).cInf_eq (insert_nonempty a s)
@[simp] lemma cInf_Ici : Inf (Ici a) = a := is_least_Ici.cInf_eq
@[simp] lemma cSup_Iic : Sup (Iic a) = a := is_greatest_Iic.cSup_eq
/--The indexed supremum of two functions are comparable if the functions are pointwise comparable-/
lemma csupr_le_csupr {f g : ι → α} (B : bdd_above (range g)) (H : ∀x, f x ≤ g x) :
supr f ≤ supr g :=
begin
classical, by_cases hι : nonempty ι,
{ have Rf : (range f).nonempty := range_nonempty _,
apply cSup_le Rf,
rintros y ⟨x, rfl⟩,
have : g x ∈ range g := ⟨x, rfl⟩,
exact le_cSup_of_le B this (H x) },
{ have Rf : range f = ∅, from range_eq_empty.2 hι,
have Rg : range g = ∅, from range_eq_empty.2 hι,
unfold supr, rw [Rf, Rg] }
end
/--The indexed supremum of a function is bounded above by a uniform bound-/
lemma csupr_le [nonempty ι] {f : ι → α} {c : α} (H : ∀x, f x ≤ c) : supr f ≤ c :=
cSup_le (range_nonempty f) (by rwa forall_range_iff)
/--The indexed supremum of a function is bounded below by the value taken at one point-/
lemma le_csupr {f : ι → α} (H : bdd_above (range f)) {c : ι} : f c ≤ supr f :=
le_cSup H (mem_range_self _)
/--The indexed infimum of two functions are comparable if the functions are pointwise comparable-/
lemma cinfi_le_cinfi {f g : ι → α} (B : bdd_below (range f)) (H : ∀x, f x ≤ g x) :
infi f ≤ infi g :=
begin
classical, by_cases hι : nonempty ι,
{ have Rg : (range g).nonempty, from range_nonempty _,
apply le_cInf Rg,
rintros y ⟨x, rfl⟩,
have : f x ∈ range f := ⟨x, rfl⟩,
exact cInf_le_of_le B this (H x) },
{ have Rf : range f = ∅, from range_eq_empty.2 hι,
have Rg : range g = ∅, from range_eq_empty.2 hι,
unfold infi, rw [Rf, Rg] }
end
/--The indexed minimum of a function is bounded below by a uniform lower bound-/
lemma le_cinfi [nonempty ι] {f : ι → α} {c : α} (H : ∀x, c ≤ f x) : c ≤ infi f :=
le_cInf (range_nonempty f) (by rwa forall_range_iff)
/--The indexed infimum of a function is bounded above by the value taken at one point-/
lemma cinfi_le {f : ι → α} (H : bdd_below (range f)) {c : ι} : infi f ≤ f c :=
cInf_le H (mem_range_self _)
@[simp] theorem cinfi_const [hι : nonempty ι] {a : α} : (⨅ b:ι, a) = a :=
by rw [infi, range_const, cInf_singleton]
@[simp] theorem csupr_const [hι : nonempty ι] {a : α} : (⨆ b:ι, a) = a :=
by rw [supr, range_const, cSup_singleton]
end conditionally_complete_lattice
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order α] {s t : set α} {a b : α}
/-- When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is
a linear order. -/
lemma exists_lt_of_lt_cSup (hs : s.nonempty) (hb : b < Sup s) : ∃a∈s, b < a :=
begin
classical, contrapose! hb,
exact cSup_le hs hb
end
/--
Indexed version of the above lemma `exists_lt_of_lt_cSup`.
When `b < supr f`, there is an element `i` such that `b < f i`.
-/
lemma exists_lt_of_lt_csupr [nonempty ι] {f : ι → α} (h : b < supr f) :
∃i, b < f i :=
let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_lt_cSup (range_nonempty f) h in ⟨i, h⟩
/--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is
a linear order.-/
lemma exists_lt_of_cInf_lt (hs : s.nonempty) (hb : Inf s < b) : ∃a∈s, a < b :=
begin
classical, contrapose! hb,
exact le_cInf hs hb
end
/--
Indexed version of the above lemma `exists_lt_of_cInf_lt`
When `infi f < a`, there is an element `i` such that `f i < a`.
-/
lemma exists_lt_of_cinfi_lt [nonempty ι] {f : ι → α} (h : infi f < a) :
(∃i, f i < a) :=
let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_cInf_lt (range_nonempty f) h in ⟨i, h⟩
/--Introduction rule to prove that b is the supremum of s: it suffices to check that
1) b is an upper bound
2) every other upper bound b' satisfies b ≤ b'.-/
theorem cSup_intro' (_ : s.nonempty)
(h_is_ub : ∀ a ∈ s, a ≤ b) (h_b_le_ub : ∀ub, (∀ a ∈ s, a ≤ ub) → (b ≤ ub)) : Sup s = b :=
le_antisymm
(show Sup s ≤ b, from cSup_le ‹s.nonempty› h_is_ub)
(show b ≤ Sup s, from h_b_le_ub _ $ assume a, le_cSup ⟨b, h_is_ub⟩)
end conditionally_complete_linear_order
section conditionally_complete_linear_order_bot
lemma cSup_empty [conditionally_complete_linear_order_bot α] : (Sup ∅ : α) = ⊥ :=
conditionally_complete_linear_order_bot.cSup_empty α
end conditionally_complete_linear_order_bot
section
open_locale classical
noncomputable instance : has_Inf ℕ :=
⟨λs, if h : ∃n, n ∈ s then @nat.find (λn, n ∈ s) _ h else 0⟩
noncomputable instance : has_Sup ℕ :=
⟨λs, if h : ∃n, ∀a∈s, a ≤ n then @nat.find (λn, ∀a∈s, a ≤ n) _ h else 0⟩
lemma Inf_nat_def {s : set ℕ} (h : ∃n, n ∈ s) : Inf s = @nat.find (λn, n ∈ s) _ h :=
dif_pos _
lemma Sup_nat_def {s : set ℕ} (h : ∃n, ∀a∈s, a ≤ n) :
Sup s = @nat.find (λn, ∀a∈s, a ≤ n) _ h :=
dif_pos _
/-- This instance is necessary, otherwise the lattice operations would be derived via
conditionally_complete_linear_order_bot and marked as noncomputable. -/
instance : lattice ℕ := infer_instance
noncomputable instance : conditionally_complete_linear_order_bot ℕ :=
{ Sup := Sup, Inf := Inf,
le_cSup := assume s a hb ha, by rw [Sup_nat_def hb]; revert a ha; exact @nat.find_spec _ _ hb,
cSup_le := assume s a hs ha, by rw [Sup_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha,
le_cInf := assume s a hs hb,
by rw [Inf_nat_def hs]; exact hb (@nat.find_spec (λn, n ∈ s) _ _),
cInf_le := assume s a hb ha, by rw [Inf_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha,
cSup_empty :=
begin
simp only [Sup_nat_def, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff, exists_const],
apply bot_unique (nat.find_min' _ _),
trivial
end,
.. (infer_instance : order_bot ℕ), .. (infer_instance : lattice ℕ),
.. (infer_instance : decidable_linear_order ℕ) }
end
end lattice /-end of namespace lattice-/
namespace with_top
open lattice
open_locale classical
variables [conditionally_complete_linear_order_bot α]
/-- The Sup of a non-empty set is its least upper bound for a conditionally
complete lattice with a top. -/
lemma is_lub_Sup' {β : Type*} [conditionally_complete_lattice β]
{s : set (with_top β)} (hs : s.nonempty) : is_lub s (Sup s) :=
begin
split,
{ show ite _ _ _ ∈ _,
split_ifs,
{ intros _ _, exact le_top },
{ rintro (⟨⟩|a) ha,
{ contradiction },
apply some_le_some.2,
exact le_cSup h_1 ha },
{ intros _ _, exact le_top } },
{ show ite _ _ _ ∈ _,
split_ifs,
{ rintro (⟨⟩|a) ha,
{ exact _root_.le_refl _ },
{ exact false.elim (not_top_le_coe a (ha h)) } },
{ rintro (⟨⟩|b) hb,
{ exact le_top },
refine some_le_some.2 (cSup_le _ _),
{ rcases hs with ⟨⟨⟩|b, hb⟩,
{ exact absurd hb h },
{ exact ⟨b, hb⟩ } },
{ intros a ha, exact some_le_some.1 (hb ha) } },
{ rintro (⟨⟩|b) hb,
{ exact _root_.le_refl _ },
{ exfalso, apply h_1, use b, intros a ha, exact some_le_some.1 (hb ha) } } }
end
lemma is_lub_Sup (s : set (with_top α)) : is_lub s (Sup s) :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ rw hs,
show is_lub ∅ (ite _ _ _),
split_ifs,
{ cases h },
{ rw [preimage_empty, cSup_empty], exact is_lub_empty },
{ exfalso, apply h_1, use ⊥, rintro a ⟨⟩ } },
exact is_lub_Sup' hs,
end
/-- The Inf of a bounded-below set is its greatest lower bound for a conditionally
complete lattice with a top. -/
lemma is_glb_Inf' {β : Type*} [conditionally_complete_lattice β]
{s : set (with_top β)} (hs : bdd_below s) : is_glb s (Inf s) :=
begin
split,
{ show ite _ _ _ ∈ _,
split_ifs,
{ intros a ha, exact top_le_iff.2 (set.mem_singleton_iff.1 (h ha)) },
{ rintro (⟨⟩|a) ha,
{ exact le_top },
refine some_le_some.2 (cInf_le _ ha),
rcases hs with ⟨⟨⟩|b, hb⟩,
{ exfalso,
apply h,
intros c hc,
rw [mem_singleton_iff, ←top_le_iff],
exact hb hc },
use b,
intros c hc,
exact some_le_some.1 (hb hc) } },
{ show ite _ _ _ ∈ _,
split_ifs,
{ intros _ _, exact le_top },
{ rintro (⟨⟩|a) ha,
{ exfalso, apply h, intros b hb, exact set.mem_singleton_iff.2 (top_le_iff.1 (ha hb)) },
{ refine some_le_some.2 (le_cInf _ _),
{ classical, contrapose! h,
rintros (⟨⟩|a) ha,
{ exact mem_singleton ⊤ },
{ exact (h ⟨a, ha⟩).elim }},
{ intros b hb,
rw ←some_le_some,
exact ha hb } } } }
end
lemma is_glb_Inf (s : set (with_top α)) : is_glb s (Inf s) :=
begin
by_cases hs : bdd_below s,
{ exact is_glb_Inf' hs },
{ exfalso, apply hs, use ⊥, intros _ _, exact bot_le },
end
noncomputable instance : complete_linear_order (with_top α) :=
{ Sup := Sup, le_Sup := assume s, (is_lub_Sup s).1, Sup_le := assume s, (is_lub_Sup s).2,
Inf := Inf, le_Inf := assume s, (is_glb_Inf s).2, Inf_le := assume s, (is_glb_Inf s).1,
decidable_le := classical.dec_rel _,
.. with_top.linear_order, ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot }
lemma coe_Sup {s : set α} (hb : bdd_above s) : (↑(Sup s) : with_top α) = (⨆a∈s, ↑a) :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ rw [hs, cSup_empty], simp only [set.mem_empty_eq, lattice.supr_bot, lattice.supr_false], refl },
apply le_antisymm,
{ refine ((coe_le_iff _ _).2 $ assume b hb, cSup_le hs $ assume a has, coe_le_coe.1 $ hb ▸ _),
exact (le_supr_of_le a $ le_supr_of_le has $ _root_.le_refl _) },
{ exact (supr_le $ assume a, supr_le $ assume ha, coe_le_coe.2 $ le_cSup hb ha) }
end
lemma coe_Inf {s : set α} (hs : s.nonempty) : (↑(Inf s) : with_top α) = (⨅a∈s, ↑a) :=
let ⟨x, hx⟩ := hs in
have (⨅a∈s, ↑a : with_top α) ≤ x, from infi_le_of_le x $ infi_le_of_le hx $ _root_.le_refl _,
let ⟨r, r_eq, hr⟩ := (le_coe_iff _ _).1 this in
le_antisymm
(le_infi $ assume a, le_infi $ assume ha, coe_le_coe.2 $ cInf_le (order_bot.bdd_below s) ha)
begin
refine (r_eq.symm ▸ coe_le_coe.2 $ le_cInf hs $ assume a has, coe_le_coe.1 $ _),
refine (r_eq ▸ infi_le_of_le a _),
exact (infi_le_of_le has $ _root_.le_refl _),
end
end with_top
namespace enat
open_locale classical
open lattice
noncomputable instance : complete_linear_order enat :=
{ Sup := λ s, with_top_equiv.symm $ Sup (with_top_equiv '' s),
Inf := λ s, with_top_equiv.symm $ Inf (with_top_equiv '' s),
le_Sup := by intros; rw ← with_top_equiv_le; simp; apply le_Sup _; simpa,
Inf_le := by intros; rw ← with_top_equiv_le; simp; apply Inf_le _; simpa,
Sup_le := begin
intros s a h1,
rw [← with_top_equiv_le, with_top_equiv.right_inverse_symm],
apply Sup_le _,
rintros b ⟨x, h2, rfl⟩,
rw with_top_equiv_le,
apply h1,
assumption
end,
le_Inf := begin
intros s a h1,
rw [← with_top_equiv_le, with_top_equiv.right_inverse_symm],
apply le_Inf _,
rintros b ⟨x, h2, rfl⟩,
rw with_top_equiv_le,
apply h1,
assumption
end,
..enat.decidable_linear_order,
..enat.lattice.bounded_lattice }
end enat
section order_dual
open lattice
instance (α : Type*) [conditionally_complete_lattice α] :
conditionally_complete_lattice (order_dual α) :=
{ le_cSup := @cInf_le α _,
cSup_le := @le_cInf α _,
le_cInf := @cSup_le α _,
cInf_le := @le_cSup α _,
..order_dual.lattice.has_Inf α,
..order_dual.lattice.has_Sup α,
..order_dual.lattice.lattice α }
instance (α : Type*) [conditionally_complete_linear_order α] :
conditionally_complete_linear_order (order_dual α) :=
{ ..order_dual.lattice.conditionally_complete_lattice α,
..order_dual.decidable_linear_order α }
end order_dual
section with_top_bot
/-! ### Complete lattice structure on `with_top (with_bot α)`
If `α` is a `conditionally_complete_lattice`, then we show that `with_top α` and `with_bot α`
also inherit the structure of conditionally complete lattices. Furthermore, we show
that `with_top (with_bot α)` naturally inherits the structure of a complete lattice. Note that
for α a conditionally complete lattice, `Sup` and `Inf` both return junk values
for sets which are empty or unbounded. The extension of `Sup` to `with_top α` fixes
the unboundedness problem and the extension to `with_bot α` fixes the problem with
the empty set.
This result can be used to show that the extended reals [-∞, ∞] are a complete lattice.
-/
open lattice
open_locale classical
/-- Adding a top element to a conditionally complete lattice gives a conditionally complete lattice -/
noncomputable instance with_top.conditionally_complete_lattice
{α : Type*} [conditionally_complete_lattice α] :
conditionally_complete_lattice (with_top α) :=
{ le_cSup := λ S a hS haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS,
cSup_le := λ S a hS haS, (with_top.is_lub_Sup' hS).2 haS,
cInf_le := λ S a hS haS, (with_top.is_glb_Inf' hS).1 haS,
le_cInf := λ S a hS haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS,
..with_top.lattice,
..with_top.lattice.has_Sup,
..with_top.lattice.has_Inf }
/-- Adding a bottom element to a conditionally complete lattice gives a conditionally complete lattice -/
noncomputable instance with_bot.conditionally_complete_lattice
{α : Type*} [conditionally_complete_lattice α] :
conditionally_complete_lattice (with_bot α) :=
{ le_cSup := (@with_top.conditionally_complete_lattice (order_dual α) _).cInf_le,
cSup_le := (@with_top.conditionally_complete_lattice (order_dual α) _).le_cInf,
cInf_le := (@with_top.conditionally_complete_lattice (order_dual α) _).le_cSup,
le_cInf := (@with_top.conditionally_complete_lattice (order_dual α) _).cSup_le,
..with_bot.lattice,
..with_bot.lattice.has_Sup,
..with_bot.lattice.has_Inf }
/-- Adding a bottom and a top to a conditionally complete lattice gives a bounded lattice-/
noncomputable instance {α : Type*} [conditionally_complete_lattice α] : bounded_lattice (with_top (with_bot α)) :=
{ ..with_top.order_bot,
..with_top.order_top,
..conditionally_complete_lattice.to_lattice _ }
theorem with_bot.cSup_empty {α : Type*} [conditionally_complete_lattice α] :
Sup (∅ : set (with_bot α)) = ⊥ :=
begin
show ite _ _ _ = ⊥,
split_ifs; finish,
end
noncomputable instance {α : Type*} [conditionally_complete_lattice α] :
complete_lattice (with_top (with_bot α)) :=
{ le_Sup := λ S a haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS,
Sup_le := λ S a ha,
begin
cases S.eq_empty_or_nonempty with h,
{ show ite _ _ _ ≤ a,
split_ifs,
{ rw h at h_1, cases h_1 },
{ convert bot_le, convert with_bot.cSup_empty, rw h, refl },
{ exfalso, apply h_2, use ⊥, rw h, rintro b ⟨⟩ } },
{ refine (with_top.is_lub_Sup' h).2 ha }
end,
Inf_le := λ S a haS,
show ite _ _ _ ≤ a,
begin
split_ifs,
{ cases a with a, exact _root_.le_refl _,
cases (h haS); tauto },
{ cases a,
{ exact le_top },
{ apply with_top.some_le_some.2, refine cInf_le _ haS, use ⊥, intros b hb, exact bot_le } }
end,
le_Inf := λ S a haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS,
..with_top.lattice.has_Inf,
..with_top.lattice.has_Sup,
..with_top.lattice.bounded_lattice }
end with_top_bot
|
418820205155b312a68e9f7ab9f4ae2bb1c1a033 | d29d82a0af640c937e499f6be79fc552eae0aa13 | /src/measure_theory/vector_measure.lean | 19bf9c8a3db61d1628d2b6efc8c611d6f1c398e8 | [
"Apache-2.0"
] | permissive | AbdulMajeedkhurasani/mathlib | 835f8a5c5cf3075b250b3737172043ab4fa1edf6 | 79bc7323b164aebd000524ebafd198eb0e17f956 | refs/heads/master | 1,688,003,895,660 | 1,627,788,521,000 | 1,627,788,521,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,346 | lean | /-
Copyright (c) 2021 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying
-/
import measure_theory.integration
/-!
# Vector valued measures
This file defines vector valued measures, which are σ-additive functions from a set to a add monoid
`M` such that it maps the empty set and non-measurable sets to zero. In the case
that `M = ℝ`, we called the vector measure a signed measure and write `signed_measure α`.
Similarly, when `M = ℂ`, we call the measure a complex measure and write `complex_measure α`.
## Main definitions
* `vector_measure` is a vector valued, σ-additive function that maps the empty
and non-measurable set to zero.
## Implementation notes
We require all non-measurable sets to be mapped to zero in order for the extensionality lemma
to only compare the underlying functions for measurable sets.
We use `has_sum` instead of `tsum` in the definition of vector measures in comparison to `measure`
since this provides summablity.
## Tags
vector measure, signed measure, complex measure
-/
noncomputable theory
open_locale classical big_operators nnreal ennreal
namespace measure_theory
variables {α β : Type*} [measurable_space α]
/-- A vector measure on a measurable space `α` is a σ-additive `M`-valued function (for some `M`
an add monoid) such that the empty set and non-measurable sets are mapped to zero. -/
structure vector_measure (α : Type*) [measurable_space α]
(M : Type*) [add_comm_monoid M] [topological_space M] :=
(measure_of' : set α → M)
(empty' : measure_of' ∅ = 0)
(not_measurable' ⦃i : set α⦄ : ¬ measurable_set i → measure_of' i = 0)
(m_Union' ⦃f : ℕ → set α⦄ :
(∀ i, measurable_set (f i)) → pairwise (disjoint on f) →
has_sum (λ i, measure_of' (f i)) (measure_of' (⋃ i, f i)))
/-- A `signed_measure` is a `ℝ`-vector measure. -/
abbreviation signed_measure (α : Type*) [measurable_space α] := vector_measure α ℝ
/-- A `complex_measure` is a `ℂ`-vector_measure. -/
abbreviation complex_measure (α : Type*) [measurable_space α] := vector_measure α ℂ
open set measure_theory
namespace vector_measure
section
variables {M : Type*} [add_comm_monoid M] [topological_space M]
instance : has_coe_to_fun (vector_measure α M) :=
⟨λ _, set α → M, vector_measure.measure_of'⟩
initialize_simps_projections vector_measure (measure_of' → apply)
@[simp]
lemma measure_of_eq_coe (v : vector_measure α M) : v.measure_of' = v := rfl
@[simp]
lemma empty (v : vector_measure α M) : v ∅ = 0 := v.empty'
lemma not_measurable (v : vector_measure α M)
{i : set α} (hi : ¬ measurable_set i) : v i = 0 := v.not_measurable' hi
lemma m_Union (v : vector_measure α M) {f : ℕ → set α}
(hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) :
has_sum (λ i, v (f i)) (v (⋃ i, f i)) :=
v.m_Union' hf₁ hf₂
lemma of_disjoint_Union_nat [t2_space M] (v : vector_measure α M) {f : ℕ → set α}
(hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) :
v (⋃ i, f i) = ∑' i, v (f i) :=
(v.m_Union hf₁ hf₂).tsum_eq.symm
lemma coe_injective : @function.injective (vector_measure α M) (set α → M) coe_fn :=
λ v w h, by { cases v, cases w, congr' }
lemma ext_iff' (v w : vector_measure α M) :
v = w ↔ ∀ i : set α, v i = w i :=
by rw [← coe_injective.eq_iff, function.funext_iff]
lemma ext_iff (v w : vector_measure α M) :
v = w ↔ ∀ i : set α, measurable_set i → v i = w i :=
begin
split,
{ rintro rfl _ _, refl },
{ rw ext_iff',
intros h i,
by_cases hi : measurable_set i,
{ exact h i hi },
{ simp_rw [not_measurable _ hi] } }
end
@[ext] lemma ext {s t : vector_measure α M}
(h : ∀ i : set α, measurable_set i → s i = t i) : s = t :=
(ext_iff s t).2 h
variables [t2_space M] {v : vector_measure α M} {f : ℕ → set α}
lemma has_sum_of_disjoint_Union [encodable β] {f : β → set α}
(hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) :
has_sum (λ i, v (f i)) (v (⋃ i, f i)) :=
begin
set g := λ i : ℕ, ⋃ (b : β) (H : b ∈ encodable.decode₂ β i), f b with hg,
have hg₁ : ∀ i, measurable_set (g i),
{ exact λ _, measurable_set.Union (λ b, measurable_set.Union_Prop $ λ _, hf₁ b) },
have hg₂ : pairwise (disjoint on g),
{ exact encodable.Union_decode₂_disjoint_on hf₂ },
have := v.of_disjoint_Union_nat hg₁ hg₂,
rw [hg, encodable.Union_decode₂] at this,
have hg₃ : (λ (i : β), v (f i)) = (λ i, v (g (encodable.encode i))),
{ ext, rw hg, simp only,
congr, ext y, simp only [exists_prop, mem_Union, option.mem_def],
split,
{ intro hy,
refine ⟨x, (encodable.decode₂_is_partial_inv _ _).2 rfl, hy⟩ },
{ rintro ⟨b, hb₁, hb₂⟩,
rw (encodable.decode₂_is_partial_inv _ _) at hb₁,
rwa ← encodable.encode_injective hb₁ } },
rw [summable.has_sum_iff, this, ← tsum_Union_decode₂],
{ exact v.empty },
{ rw hg₃, change summable ((λ i, v (g i)) ∘ encodable.encode),
rw function.injective.summable_iff encodable.encode_injective,
{ exact (v.m_Union hg₁ hg₂).summable },
{ intros x hx,
convert v.empty,
simp only [Union_eq_empty, option.mem_def, not_exists, mem_range] at ⊢ hx,
intros i hi,
exact false.elim ((hx i) ((encodable.decode₂_is_partial_inv _ _).1 hi)) } }
end
lemma of_disjoint_Union [encodable β] {f : β → set α}
(hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) :
v (⋃ i, f i) = ∑' i, v (f i) :=
(has_sum_of_disjoint_Union hf₁ hf₂).tsum_eq.symm
lemma of_union {A B : set α}
(h : disjoint A B) (hA : measurable_set A) (hB : measurable_set B) :
v (A ∪ B) = v A + v B :=
begin
rw [union_eq_Union, of_disjoint_Union, tsum_fintype, fintype.sum_bool, cond, cond],
exacts [λ b, bool.cases_on b hB hA, pairwise_disjoint_on_bool.2 h]
end
lemma of_add_of_diff {A B : set α} (hA : measurable_set A) (hB : measurable_set B)
(h : A ⊆ B) : v A + v (B \ A) = v B :=
begin
rw [← of_union disjoint_diff hA (hB.diff hA), union_diff_cancel h],
apply_instance,
end
lemma of_diff {M : Type*} [add_comm_group M]
[topological_space M] [t2_space M] {v : vector_measure α M}
{A B : set α} (hA : measurable_set A) (hB : measurable_set B)
(h : A ⊆ B) : v (B \ A) = v B - (v A) :=
begin
rw [← of_add_of_diff hA hB h, add_sub_cancel'],
apply_instance,
end
lemma of_Union_nonneg {M : Type*} [topological_space M]
[ordered_add_comm_monoid M] [order_closed_topology M]
{v : vector_measure α M} (hf₁ : ∀ i, measurable_set (f i))
(hf₂ : pairwise (disjoint on f)) (hf₃ : ∀ i, 0 ≤ v (f i)) :
0 ≤ v (⋃ i, f i) :=
(v.of_disjoint_Union_nat hf₁ hf₂).symm ▸ tsum_nonneg hf₃
lemma of_Union_nonpos {M : Type*} [topological_space M]
[ordered_add_comm_monoid M] [order_closed_topology M]
{v : vector_measure α M} (hf₁ : ∀ i, measurable_set (f i))
(hf₂ : pairwise (disjoint on f)) (hf₃ : ∀ i, v (f i) ≤ 0) :
v (⋃ i, f i) ≤ 0 :=
(v.of_disjoint_Union_nat hf₁ hf₂).symm ▸ tsum_nonpos hf₃
lemma of_nonneg_disjoint_union_eq_zero {s : signed_measure α} {A B : set α}
(h : disjoint A B) (hA₁ : measurable_set A) (hB₁ : measurable_set B)
(hA₂ : 0 ≤ s A) (hB₂ : 0 ≤ s B)
(hAB : s (A ∪ B) = 0) : s A = 0 :=
begin
rw of_union h hA₁ hB₁ at hAB,
linarith,
apply_instance,
end
lemma of_nonpos_disjoint_union_eq_zero {s : signed_measure α} {A B : set α}
(h : disjoint A B) (hA₁ : measurable_set A) (hB₁ : measurable_set B)
(hA₂ : s A ≤ 0) (hB₂ : s B ≤ 0)
(hAB : s (A ∪ B) = 0) : s A = 0 :=
begin
rw of_union h hA₁ hB₁ at hAB,
linarith,
apply_instance,
end
end
section add_comm_monoid
variables {M : Type*} [add_comm_monoid M] [topological_space M]
instance : has_zero (vector_measure α M) :=
⟨⟨0, rfl, λ _ _, rfl, λ _ _ _, has_sum_zero⟩⟩
instance : inhabited (vector_measure α M) := ⟨0⟩
@[simp] lemma coe_zero : ⇑(0 : vector_measure α M) = 0 := rfl
lemma zero_apply (i : set α) : (0 : vector_measure α M) i = 0 := rfl
variables [has_continuous_add M]
/-- The sum of two vector measure is a vector measure. -/
def add (v w : vector_measure α M) : vector_measure α M :=
{ measure_of' := v + w,
empty' := by simp,
not_measurable' := λ _ hi,
by simp [v.not_measurable hi, w.not_measurable hi],
m_Union' := λ f hf₁ hf₂,
has_sum.add (v.m_Union hf₁ hf₂) (w.m_Union hf₁ hf₂) }
instance : has_add (vector_measure α M) := ⟨add⟩
@[simp] lemma coe_add (v w : vector_measure α M) : ⇑(v + w) = v + w := rfl
lemma add_apply (v w : vector_measure α M) (i : set α) :(v + w) i = v i + w i := rfl
instance : add_comm_monoid (vector_measure α M) :=
function.injective.add_comm_monoid _ coe_injective coe_zero coe_add
/-- `coe_fn` is an `add_monoid_hom`. -/
@[simps]
def coe_fn_add_monoid_hom : vector_measure α M →+ (set α → M) :=
{ to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add }
end add_comm_monoid
section add_comm_group
variables {M : Type*} [add_comm_group M] [topological_space M]
variables [topological_add_group M]
/-- The negative of a vector measure is a vector measure. -/
def neg (v : vector_measure α M) : vector_measure α M :=
{ measure_of' := -v,
empty' := by simp,
not_measurable' := λ _ hi, by simp [v.not_measurable hi],
m_Union' := λ f hf₁ hf₂, has_sum.neg $ v.m_Union hf₁ hf₂ }
instance : has_neg (vector_measure α M) := ⟨neg⟩
@[simp] lemma coe_neg (v : vector_measure α M) : ⇑(-v) = - v := rfl
lemma neg_apply (v : vector_measure α M) (i : set α) :(-v) i = - v i := rfl
/-- The difference of two vector measure is a vector measure. -/
def sub (v w : vector_measure α M) : vector_measure α M :=
{ measure_of' := v - w,
empty' := by simp,
not_measurable' := λ _ hi,
by simp [v.not_measurable hi, w.not_measurable hi],
m_Union' := λ f hf₁ hf₂,
has_sum.sub (v.m_Union hf₁ hf₂)
(w.m_Union hf₁ hf₂) }
instance : has_sub (vector_measure α M) := ⟨sub⟩
@[simp] lemma coe_sub (v w : vector_measure α M) : ⇑(v - w) = v - w := rfl
lemma sub_apply (v w : vector_measure α M) (i : set α) : (v - w) i = v i - w i := rfl
instance : add_comm_group (vector_measure α M) :=
function.injective.add_comm_group _ coe_injective coe_zero coe_add coe_neg coe_sub
end add_comm_group
section distrib_mul_action
variables {M : Type*} [add_comm_monoid M] [topological_space M]
variables {R : Type*} [semiring R] [distrib_mul_action R M]
variables [topological_space R] [has_continuous_smul R M]
/-- Given a real number `r` and a signed measure `s`, `smul r s` is the signed
measure corresponding to the function `r • s`. -/
def smul (r : R) (v : vector_measure α M) : vector_measure α M :=
{ measure_of' := r • v,
empty' := by rw [pi.smul_apply, empty, smul_zero],
not_measurable' := λ _ hi, by rw [pi.smul_apply, v.not_measurable hi, smul_zero],
m_Union' := λ _ hf₁ hf₂, has_sum.smul (v.m_Union hf₁ hf₂) }
instance : has_scalar R (vector_measure α M) := ⟨smul⟩
@[simp] lemma coe_smul (r : R) (v : vector_measure α M) : ⇑(r • v) = r • v := rfl
lemma smul_apply (r : R) (v : vector_measure α M) (i : set α) :
(r • v) i = r • v i := rfl
instance [has_continuous_add M] : distrib_mul_action R (vector_measure α M) :=
function.injective.distrib_mul_action coe_fn_add_monoid_hom coe_injective coe_smul
end distrib_mul_action
section module
variables {M : Type*} [add_comm_monoid M] [topological_space M]
variables {R : Type*} [semiring R] [module R M]
variables [topological_space R] [has_continuous_smul R M]
instance [has_continuous_add M] : module R (vector_measure α M) :=
function.injective.module R coe_fn_add_monoid_hom coe_injective coe_smul
end module
end vector_measure
namespace measure
/-- A finite measure coerced into a real function is a signed measure. -/
@[simps]
def to_signed_measure (μ : measure α) [hμ : finite_measure μ] : signed_measure α :=
{ measure_of' := λ i : set α, if measurable_set i then (μ.measure_of i).to_real else 0,
empty' := by simp [μ.empty],
not_measurable' := λ _ hi, if_neg hi,
m_Union' :=
begin
intros _ hf₁ hf₂,
rw [μ.m_Union hf₁ hf₂, ennreal.tsum_to_real_eq, if_pos (measurable_set.Union hf₁),
summable.has_sum_iff],
{ congr, ext n, rw if_pos (hf₁ n) },
{ refine @summable_of_nonneg_of_le _ (ennreal.to_real ∘ μ ∘ f) _ _ _ _,
{ intro, split_ifs,
exacts [ennreal.to_real_nonneg, le_refl _] },
{ intro, split_ifs,
exacts [le_refl _, ennreal.to_real_nonneg] },
exact summable_measure_to_real hf₁ hf₂ },
{ intros a ha,
apply ne_of_lt hμ.measure_univ_lt_top,
rw [eq_top_iff, ← ha, outer_measure.measure_of_eq_coe, coe_to_outer_measure],
exact measure_mono (set.subset_univ _) }
end }
lemma to_signed_measure_apply_measurable {μ : measure α} [finite_measure μ]
{i : set α} (hi : measurable_set i) :
μ.to_signed_measure i = (μ i).to_real :=
if_pos hi
@[simp] lemma to_signed_measure_zero :
(0 : measure α).to_signed_measure = 0 :=
by { ext i hi, simp }
@[simp] lemma to_signed_measure_add (μ ν : measure α) [finite_measure μ] [finite_measure ν] :
(μ + ν).to_signed_measure = μ.to_signed_measure + ν.to_signed_measure :=
begin
ext i hi,
rw [to_signed_measure_apply_measurable hi, add_apply,
ennreal.to_real_add (ne_of_lt (measure_lt_top _ _ )) (ne_of_lt (measure_lt_top _ _)),
vector_measure.add_apply, to_signed_measure_apply_measurable hi,
to_signed_measure_apply_measurable hi],
all_goals { apply_instance }
end
@[simp] lemma to_signed_measure_smul (μ : measure α) [finite_measure μ] (r : ℝ≥0) :
(r • μ).to_signed_measure = r • μ.to_signed_measure :=
begin
ext i hi,
rw [to_signed_measure_apply_measurable hi, vector_measure.smul_apply,
to_signed_measure_apply_measurable hi, coe_nnreal_smul, pi.smul_apply,
ennreal.to_real_smul],
end
/-- A measure is a vector measure over `ℝ≥0∞`. -/
@[simps]
def to_ennreal_vector_measure (μ : measure α) : vector_measure α ℝ≥0∞ :=
{ measure_of' := λ i : set α, if measurable_set i then μ i else 0,
empty' := by simp [μ.empty],
not_measurable' := λ _ hi, if_neg hi,
m_Union' := λ _ hf₁ hf₂,
begin
rw summable.has_sum_iff ennreal.summable,
{ rw [if_pos (measurable_set.Union hf₁), measure_theory.measure_Union hf₂ hf₁],
exact tsum_congr (λ n, if_pos (hf₁ n)) },
end }
lemma to_ennreal_vector_measure_apply_measurable
{μ : measure α} {i : set α} (hi : measurable_set i) :
μ.to_ennreal_vector_measure i = μ i :=
if_pos hi
@[simp] lemma to_ennreal_vector_measure_zero :
(0 : measure α).to_ennreal_vector_measure = 0 :=
by { ext i hi, simp }
@[simp] lemma to_ennreal_vector_measure_add (μ ν : measure α) :
(μ + ν).to_ennreal_vector_measure = μ.to_ennreal_vector_measure + ν.to_ennreal_vector_measure :=
begin
refine measure_theory.vector_measure.ext (λ i hi, _),
rw [to_ennreal_vector_measure_apply_measurable hi, add_apply, vector_measure.add_apply,
to_ennreal_vector_measure_apply_measurable hi, to_ennreal_vector_measure_apply_measurable hi]
end
/-- Given two finite measures `μ, ν`, `sub_to_signed_measure μ ν` is the signed measure
corresponding to the function `μ - ν`. -/
def sub_to_signed_measure (μ ν : measure α) [hμ : finite_measure μ] [hν : finite_measure ν] :
signed_measure α :=
μ.to_signed_measure - ν.to_signed_measure
lemma sub_to_signed_measure_apply {μ ν : measure α} [finite_measure μ] [finite_measure ν]
{i : set α} (hi : measurable_set i) :
μ.sub_to_signed_measure ν i = (μ i).to_real - (ν i).to_real :=
begin
rw [sub_to_signed_measure, vector_measure.sub_apply, to_signed_measure_apply_measurable hi,
measure.to_signed_measure_apply_measurable hi, sub_eq_add_neg]
end
end measure
namespace vector_measure
section
variables {M : Type*} [topological_space M] [add_comm_monoid M] [partial_order M]
/-- Vector measures over a partially ordered monoid is partially ordered.
This definition is consistent with `measure.partial_order`. -/
instance : partial_order (vector_measure α M) :=
{ le := λ v w, ∀ i, measurable_set i → v i ≤ w i,
le_refl := λ v i hi, le_refl _,
le_trans := λ u v w h₁ h₂ i hi, le_trans (h₁ i hi) (h₂ i hi),
le_antisymm := λ v w h₁ h₂, ext (λ i hi, le_antisymm (h₁ i hi) (h₂ i hi)) }
variables {u v w : vector_measure α M}
lemma le_iff : v ≤ w ↔ ∀ i, measurable_set i → v i ≤ w i :=
iff.rfl
lemma le_iff' : v ≤ w ↔ ∀ i, v i ≤ w i :=
begin
refine ⟨λ h i, _, λ h i hi, h i⟩,
by_cases hi : measurable_set i,
{ exact h i hi },
{ rw [v.not_measurable hi, w.not_measurable hi] }
end
end
section
variables {M : Type*} [topological_space M] [add_comm_monoid M] [partial_order M]
[covariant_class M M (+) (≤)] [has_continuous_add M]
instance covariant_add_le :
covariant_class (vector_measure α M) (vector_measure α M) (+) (≤) :=
⟨λ u v w h i hi, add_le_add_left (h i hi) _⟩
end
end vector_measure
end measure_theory
|
c558e54c902d840952f0dbe4b00c153f4de8550a | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/homology/homotopy.lean | b733ad12c7c10daf23598b3c28292df5ae4f31f6 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 30,527 | 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.homology.additive
import tactic.abel
/-!
# Chain homotopies
We define chain homotopies, and prove that homotopic chain maps induce the same map on homology.
-/
universes v u
open_locale classical
noncomputable theory
open category_theory category_theory.limits homological_complex
variables {ι : Type*}
variables {V : Type u} [category.{v} V] [preadditive V]
variables {c : complex_shape ι} {C D E : homological_complex V c}
variables (f g : C ⟶ D) (h k : D ⟶ E) (i : ι)
section
/-- The composition of `C.d i i' ≫ f i' i` if there is some `i'` coming after `i`,
and `0` otherwise. -/
def d_next (i : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X i ⟶ D.X i) :=
add_monoid_hom.mk' (λ f, C.d i (c.next i) ≫ f (c.next i) i) $
λ f g, preadditive.comp_add _ _ _ _ _ _
/-- `f i' i` if `i'` comes after `i`, and 0 if there's no such `i'`.
Hopefully there won't be much need for this, except in `d_next_eq_d_from_from_next`
to see that `d_next` factors through `C.d_from i`. -/
def from_next (i : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X_next i ⟶ D.X i) :=
add_monoid_hom.mk' (λ f, f (c.next i) i) $ λ f g, rfl
@[simp]
lemma d_next_eq_d_from_from_next (f : Π i j, C.X i ⟶ D.X j) (i : ι) :
d_next i f = C.d_from i ≫ from_next i f := rfl
lemma d_next_eq (f : Π i j, C.X i ⟶ D.X j) {i i' : ι} (w : c.rel i i') :
d_next i f = C.d i i' ≫ f i' i :=
by { obtain rfl := c.next_eq' w, refl }
@[simp] lemma d_next_comp_left (f : C ⟶ D) (g : Π i j, D.X i ⟶ E.X j) (i : ι) :
d_next i (λ i j, f.f i ≫ g i j) = f.f i ≫ d_next i g :=
(f.comm_assoc _ _ _).symm
@[simp] lemma d_next_comp_right (f : Π i j, C.X i ⟶ D.X j) (g : D ⟶ E) (i : ι) :
d_next i (λ i j, f i j ≫ g.f j) = d_next i f ≫ g.f i :=
(category.assoc _ _ _).symm
/-- The composition of `f j j' ≫ D.d j' j` if there is some `j'` coming before `j`,
and `0` otherwise. -/
def prev_d (j : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X j ⟶ D.X j) :=
add_monoid_hom.mk' (λ f, f j (c.prev j) ≫ D.d (c.prev j) j) $
λ f g, preadditive.add_comp _ _ _ _ _ _
/-- `f j j'` if `j'` comes after `j`, and 0 if there's no such `j'`.
Hopefully there won't be much need for this, except in `d_next_eq_d_from_from_next`
to see that `d_next` factors through `C.d_from i`. -/
def to_prev (j : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X j ⟶ D.X_prev j) :=
add_monoid_hom.mk' (λ f, f j (c.prev j)) $ λ f g, rfl
@[simp]
lemma prev_d_eq_to_prev_d_to (f : Π i j, C.X i ⟶ D.X j) (j : ι) :
prev_d j f = to_prev j f ≫ D.d_to j := rfl
lemma prev_d_eq (f : Π i j, C.X i ⟶ D.X j) {j j' : ι} (w : c.rel j' j) :
prev_d j f = f j j' ≫ D.d j' j :=
by { obtain rfl := c.prev_eq' w, refl }
@[simp] lemma prev_d_comp_left (f : C ⟶ D) (g : Π i j, D.X i ⟶ E.X j) (j : ι) :
prev_d j (λ i j, f.f i ≫ g i j) = f.f j ≫ prev_d j g :=
category.assoc _ _ _
@[simp] lemma prev_d_comp_right (f : Π i j, C.X i ⟶ D.X j) (g : D ⟶ E) (j : ι) :
prev_d j (λ i j, f i j ≫ g.f j) = prev_d j f ≫ g.f j :=
by { dsimp [prev_d], simp only [category.assoc, g.comm] }
lemma d_next_nat (C D : chain_complex V ℕ) (i : ℕ) (f : Π i j, C.X i ⟶ D.X j) :
d_next i f = C.d i (i-1) ≫ f (i-1) i :=
begin
dsimp [d_next],
cases i,
{ simp only [shape, chain_complex.next_nat_zero, complex_shape.down_rel,
nat.one_ne_zero, not_false_iff, zero_comp], },
{ dsimp only [nat.succ_eq_add_one],
have : (complex_shape.down ℕ).next (i + 1) = i + 1 - 1,
{ rw chain_complex.next_nat_succ, refl },
congr' 2, }
end
lemma prev_d_nat (C D : cochain_complex V ℕ) (i : ℕ) (f : Π i j, C.X i ⟶ D.X j) :
prev_d i f = f i (i-1) ≫ D.d (i-1) i :=
begin
dsimp [prev_d],
cases i,
{ simp only [shape, cochain_complex.prev_nat_zero, complex_shape.up_rel,
nat.one_ne_zero, not_false_iff, comp_zero]},
{ dsimp only [nat.succ_eq_add_one],
have : (complex_shape.up ℕ).prev (i + 1) = i + 1 - 1,
{ rw cochain_complex.prev_nat_succ, refl },
congr' 2, },
end
/--
A homotopy `h` between chain maps `f` and `g` consists of components `h i j : C.X i ⟶ D.X j`
which are zero unless `c.rel j i`, satisfying the homotopy condition.
-/
@[ext, nolint has_nonempty_instance]
structure homotopy (f g : C ⟶ D) :=
(hom : Π i j, C.X i ⟶ D.X j)
(zero' : ∀ i j, ¬ c.rel j i → hom i j = 0 . obviously)
(comm : ∀ i, f.f i = d_next i hom + prev_d i hom + g.f i . obviously')
variables {f g}
namespace homotopy
restate_axiom homotopy.zero'
/--
`f` is homotopic to `g` iff `f - g` is homotopic to `0`.
-/
def equiv_sub_zero : homotopy f g ≃ homotopy (f - g) 0 :=
{ to_fun := λ h,
{ hom := λ i j, h.hom i j,
zero' := λ i j w, h.zero _ _ w,
comm := λ i, by simp [h.comm] },
inv_fun := λ h,
{ hom := λ i j, h.hom i j,
zero' := λ i j w, h.zero _ _ w,
comm := λ i, by simpa [sub_eq_iff_eq_add] using h.comm i },
left_inv := by tidy,
right_inv := by tidy, }
/-- Equal chain maps are homotopic. -/
@[simps]
def of_eq (h : f = g) : homotopy f g :=
{ hom := 0,
zero' := λ _ _ _, rfl,
comm := λ _, by simp only [add_monoid_hom.map_zero, zero_add, h] }
/-- Every chain map is homotopic to itself. -/
@[simps, refl]
def refl (f : C ⟶ D) : homotopy f f :=
of_eq (rfl : f = f)
/-- `f` is homotopic to `g` iff `g` is homotopic to `f`. -/
@[simps, symm]
def symm {f g : C ⟶ D} (h : homotopy f g) : homotopy g f :=
{ hom := -h.hom,
zero' := λ i j w, by rw [pi.neg_apply, pi.neg_apply, h.zero i j w, neg_zero],
comm := λ i, by rw [add_monoid_hom.map_neg, add_monoid_hom.map_neg, h.comm, ← neg_add,
← add_assoc, neg_add_self, zero_add] }
/-- homotopy is a transitive relation. -/
@[simps, trans]
def trans {e f g : C ⟶ D} (h : homotopy e f) (k : homotopy f g) : homotopy e g :=
{ hom := h.hom + k.hom,
zero' := λ i j w, by rw [pi.add_apply, pi.add_apply, h.zero i j w, k.zero i j w, zero_add],
comm := λ i, by { rw [add_monoid_hom.map_add, add_monoid_hom.map_add, h.comm, k.comm], abel }, }
/-- the sum of two homotopies is a homotopy between the sum of the respective morphisms. -/
@[simps]
def add {f₁ g₁ f₂ g₂ : C ⟶ D}
(h₁ : homotopy f₁ g₁) (h₂ : homotopy f₂ g₂) : homotopy (f₁+f₂) (g₁+g₂) :=
{ hom := h₁.hom + h₂.hom,
zero' := λ i j hij, by
rw [pi.add_apply, pi.add_apply, h₁.zero' i j hij, h₂.zero' i j hij, add_zero],
comm := λ i, by
{ simp only [homological_complex.add_f_apply, h₁.comm, h₂.comm,
add_monoid_hom.map_add],
abel, }, }
/-- homotopy is closed under composition (on the right) -/
@[simps]
def comp_right {e f : C ⟶ D} (h : homotopy e f) (g : D ⟶ E) : homotopy (e ≫ g) (f ≫ g) :=
{ hom := λ i j, h.hom i j ≫ g.f j,
zero' := λ i j w, by rw [h.zero i j w, zero_comp],
comm := λ i, by simp only [h.comm i, d_next_comp_right, preadditive.add_comp,
prev_d_comp_right, comp_f], }
/-- homotopy is closed under composition (on the left) -/
@[simps]
def comp_left {f g : D ⟶ E} (h : homotopy f g) (e : C ⟶ D) : homotopy (e ≫ f) (e ≫ g) :=
{ hom := λ i j, e.f i ≫ h.hom i j,
zero' := λ i j w, by rw [h.zero i j w, comp_zero],
comm := λ i, by simp only [h.comm i, d_next_comp_left, preadditive.comp_add,
prev_d_comp_left, comp_f], }
/-- homotopy is closed under composition -/
@[simps]
def comp {C₁ C₂ C₃ : homological_complex V c} {f₁ g₁ : C₁ ⟶ C₂} {f₂ g₂ : C₂ ⟶ C₃}
(h₁ : homotopy f₁ g₁) (h₂ : homotopy f₂ g₂) : homotopy (f₁ ≫ f₂) (g₁ ≫ g₂) :=
(h₁.comp_right _).trans (h₂.comp_left _)
/-- a variant of `homotopy.comp_right` useful for dealing with homotopy equivalences. -/
@[simps]
def comp_right_id {f : C ⟶ C} (h : homotopy f (𝟙 C)) (g : C ⟶ D) : homotopy (f ≫ g) g :=
(h.comp_right g).trans (of_eq $ category.id_comp _)
/-- a variant of `homotopy.comp_left` useful for dealing with homotopy equivalences. -/
@[simps]
def comp_left_id {f : D ⟶ D} (h : homotopy f (𝟙 D)) (g : C ⟶ D) : homotopy (g ≫ f) g :=
(h.comp_left g).trans (of_eq $ category.comp_id _)
/-!
Null homotopic maps can be constructed using the formula `hd+dh`. We show that
these morphisms are homotopic to `0` and provide some convenient simplification
lemmas that give a degreewise description of `hd+dh`, depending on whether we have
two differentials going to and from a certain degree, only one, or none.
-/
/-- The null homotopic map associated to a family `hom` of morphisms `C_i ⟶ D_j`.
This is the same datum as for the field `hom` in the structure `homotopy`. For
this definition, we do not need the field `zero` of that structure
as this definition uses only the maps `C_i ⟶ C_j` when `c.rel j i`. -/
def null_homotopic_map (hom : Π i j, C.X i ⟶ D.X j) : C ⟶ D :=
{ f := λ i, d_next i hom + prev_d i hom,
comm' := λ i j hij,
begin
have eq1 : prev_d i hom ≫ D.d i j = 0,
{ simp only [prev_d, add_monoid_hom.mk'_apply, category.assoc, d_comp_d, comp_zero], },
have eq2 : C.d i j ≫ d_next j hom = 0,
{ simp only [d_next, add_monoid_hom.mk'_apply, d_comp_d_assoc, zero_comp], },
rw [d_next_eq hom hij, prev_d_eq hom hij, preadditive.comp_add, preadditive.add_comp,
eq1, eq2, add_zero, zero_add, category.assoc],
end }
/-- Variant of `null_homotopic_map` where the input consists only of the
relevant maps `C_i ⟶ D_j` such that `c.rel j i`. -/
def null_homotopic_map' (h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) : C ⟶ D :=
null_homotopic_map (λ i j, dite (c.rel j i) (h i j) (λ _, 0))
/-- Compatibility of `null_homotopic_map` with the postcomposition by a morphism
of complexes. -/
lemma null_homotopic_map_comp (hom : Π i j, C.X i ⟶ D.X j) (g : D ⟶ E) :
null_homotopic_map hom ≫ g = null_homotopic_map (λ i j, hom i j ≫ g.f j) :=
begin
ext n,
dsimp [null_homotopic_map, from_next, to_prev, add_monoid_hom.mk'_apply],
simp only [preadditive.add_comp, category.assoc, g.comm],
end
/-- Compatibility of `null_homotopic_map'` with the postcomposition by a morphism
of complexes. -/
lemma null_homotopic_map'_comp (hom : Π i j, c.rel j i → (C.X i ⟶ D.X j)) (g : D ⟶ E) :
null_homotopic_map' hom ≫ g = null_homotopic_map' (λ i j hij, hom i j hij ≫ g.f j) :=
begin
ext n,
erw null_homotopic_map_comp,
congr',
ext i j,
split_ifs,
{ refl, },
{ rw zero_comp, },
end
/-- Compatibility of `null_homotopic_map` with the precomposition by a morphism
of complexes. -/
lemma comp_null_homotopic_map (f : C ⟶ D) (hom : Π i j, D.X i ⟶ E.X j) :
f ≫ null_homotopic_map hom = null_homotopic_map (λ i j, f.f i ≫ hom i j) :=
begin
ext n,
dsimp [null_homotopic_map, from_next, to_prev, add_monoid_hom.mk'_apply],
simp only [preadditive.comp_add, category.assoc, f.comm_assoc],
end
/-- Compatibility of `null_homotopic_map'` with the precomposition by a morphism
of complexes. -/
lemma comp_null_homotopic_map' (f : C ⟶ D) (hom : Π i j, c.rel j i → (D.X i ⟶ E.X j)) :
f ≫ null_homotopic_map' hom = null_homotopic_map' (λ i j hij, f.f i ≫ hom i j hij) :=
begin
ext n,
erw comp_null_homotopic_map,
congr',
ext i j,
split_ifs,
{ refl, },
{ rw comp_zero, },
end
/-- Compatibility of `null_homotopic_map` with the application of additive functors -/
lemma map_null_homotopic_map {W : Type*} [category W] [preadditive W]
(G : V ⥤ W) [G.additive] (hom : Π i j, C.X i ⟶ D.X j) :
(G.map_homological_complex c).map (null_homotopic_map hom) =
null_homotopic_map (λ i j, G.map (hom i j)) :=
begin
ext i,
dsimp [null_homotopic_map, d_next, prev_d],
simp only [G.map_comp, functor.map_add],
end
/-- Compatibility of `null_homotopic_map'` with the application of additive functors -/
lemma map_null_homotopic_map' {W : Type*} [category W] [preadditive W]
(G : V ⥤ W) [G.additive] (hom : Π i j, c.rel j i → (C.X i ⟶ D.X j)) :
(G.map_homological_complex c).map (null_homotopic_map' hom) =
null_homotopic_map' (λ i j hij, G.map (hom i j hij)) :=
begin
ext n,
erw map_null_homotopic_map,
congr',
ext i j,
split_ifs,
{ refl, },
{ rw G.map_zero, }
end
/-- Tautological construction of the `homotopy` to zero for maps constructed by
`null_homotopic_map`, at least when we have the `zero'` condition. -/
@[simps]
def null_homotopy (hom : Π i j, C.X i ⟶ D.X j) (zero' : ∀ i j, ¬ c.rel j i → hom i j = 0) :
homotopy (null_homotopic_map hom) 0 :=
{ hom := hom,
zero' := zero',
comm := by { intro i, rw [homological_complex.zero_f_apply, add_zero], refl, }, }
/-- Homotopy to zero for maps constructed with `null_homotopic_map'` -/
@[simps]
def null_homotopy' (h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) :
homotopy (null_homotopic_map' h) 0 :=
begin
apply null_homotopy (λ i j, dite (c.rel j i) (h i j) (λ _, 0)),
intros i j hij,
dsimp,
rw [dite_eq_right_iff],
intro hij',
exfalso,
exact hij hij',
end
/-! This lemma and the following ones can be used in order to compute
the degreewise morphisms induced by the null homotopic maps constructed
with `null_homotopic_map` or `null_homotopic_map'` -/
@[simp]
lemma null_homotopic_map_f {k₂ k₁ k₀ : ι} (r₂₁ : c.rel k₂ k₁) (r₁₀ : c.rel k₁ k₀)
(hom : Π i j, C.X i ⟶ D.X j) :
(null_homotopic_map hom).f k₁ = C.d k₁ k₀ ≫ hom k₀ k₁ + hom k₁ k₂ ≫ D.d k₂ k₁ :=
by { dsimp only [null_homotopic_map], rw [d_next_eq hom r₁₀, prev_d_eq hom r₂₁], }
@[simp]
lemma null_homotopic_map'_f {k₂ k₁ k₀ : ι} (r₂₁ : c.rel k₂ k₁) (r₁₀ : c.rel k₁ k₀)
(h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) :
(null_homotopic_map' h).f k₁ = C.d k₁ k₀ ≫ h k₀ k₁ r₁₀ + h k₁ k₂ r₂₁ ≫ D.d k₂ k₁ :=
begin
simp only [← null_homotopic_map'],
rw null_homotopic_map_f r₂₁ r₁₀ (λ i j, dite (c.rel j i) (h i j) (λ _, 0)),
dsimp,
split_ifs,
refl,
end
@[simp]
lemma null_homotopic_map_f_of_not_rel_left {k₁ k₀ : ι} (r₁₀ : c.rel k₁ k₀)
(hk₀ : ∀ l : ι, ¬c.rel k₀ l)
(hom : Π i j, C.X i ⟶ D.X j) :
(null_homotopic_map hom).f k₀ = hom k₀ k₁ ≫ D.d k₁ k₀ :=
begin
dsimp only [null_homotopic_map],
rw [prev_d_eq hom r₁₀, d_next, add_monoid_hom.mk'_apply, C.shape, zero_comp, zero_add],
exact hk₀ _
end
@[simp]
lemma null_homotopic_map'_f_of_not_rel_left {k₁ k₀ : ι} (r₁₀ : c.rel k₁ k₀)
(hk₀ : ∀ l : ι, ¬c.rel k₀ l)
(h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) :
(null_homotopic_map' h).f k₀ = h k₀ k₁ r₁₀ ≫ D.d k₁ k₀ :=
begin
simp only [← null_homotopic_map'],
rw null_homotopic_map_f_of_not_rel_left r₁₀ hk₀ (λ i j, dite (c.rel j i) (h i j) (λ _, 0)),
dsimp,
split_ifs,
refl,
end
@[simp]
lemma null_homotopic_map_f_of_not_rel_right {k₁ k₀ : ι} (r₁₀ : c.rel k₁ k₀)
(hk₁ : ∀ l : ι, ¬c.rel l k₁)
(hom : Π i j, C.X i ⟶ D.X j) :
(null_homotopic_map hom).f k₁ = C.d k₁ k₀ ≫ hom k₀ k₁ :=
begin
dsimp only [null_homotopic_map],
rw [d_next_eq hom r₁₀, prev_d, add_monoid_hom.mk'_apply, D.shape, comp_zero, add_zero],
exact hk₁ _,
end
@[simp]
lemma null_homotopic_map'_f_of_not_rel_right {k₁ k₀ : ι} (r₁₀ : c.rel k₁ k₀)
(hk₁ : ∀ l : ι, ¬c.rel l k₁)
(h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) :
(null_homotopic_map' h).f k₁ = C.d k₁ k₀ ≫ h k₀ k₁ r₁₀ :=
begin
simp only [← null_homotopic_map'],
rw null_homotopic_map_f_of_not_rel_right r₁₀ hk₁ (λ i j, dite (c.rel j i) (h i j) (λ _, 0)),
dsimp,
split_ifs,
refl,
end
@[simp]
lemma null_homotopic_map_f_eq_zero {k₀ : ι}
(hk₀ : ∀ l : ι, ¬c.rel k₀ l) (hk₀' : ∀ l : ι, ¬c.rel l k₀)
(hom : Π i j, C.X i ⟶ D.X j) :
(null_homotopic_map hom).f k₀ = 0 :=
begin
dsimp [null_homotopic_map, d_next, prev_d],
rw [C.shape, D.shape, zero_comp, comp_zero, add_zero]; apply_assumption,
end
@[simp]
lemma null_homotopic_map'_f_eq_zero {k₀ : ι}
(hk₀ : ∀ l : ι, ¬c.rel k₀ l) (hk₀' : ∀ l : ι, ¬c.rel l k₀)
(h : Π i j, c.rel j i → (C.X i ⟶ D.X j)) :
(null_homotopic_map' h).f k₀ = 0 :=
begin
simp only [← null_homotopic_map'],
exact null_homotopic_map_f_eq_zero hk₀ hk₀'
(λ i j, dite (c.rel j i) (h i j) (λ _, 0)),
end
/-!
`homotopy.mk_inductive` allows us to build a homotopy of chain complexes inductively,
so that as we construct each component, we have available the previous two components,
and the fact that they satisfy the homotopy condition.
To simplify the situation, we only construct homotopies of the form `homotopy e 0`.
`homotopy.equiv_sub_zero` can provide the general case.
Notice however, that this construction does not have particularly good definitional properties:
we have to insert `eq_to_hom` in several places.
Hopefully this is okay in most applications, where we only need to have the existence of some
homotopy.
-/
section mk_inductive
variables {P Q : chain_complex V ℕ}
@[simp] lemma prev_d_chain_complex (f : Π i j, P.X i ⟶ Q.X j) (j : ℕ) :
prev_d j f = f j (j+1) ≫ Q.d _ _ :=
begin
dsimp [prev_d],
have : (complex_shape.down ℕ).prev j = j + 1 := chain_complex.prev ℕ j,
congr' 2,
end
@[simp] lemma d_next_succ_chain_complex (f : Π i j, P.X i ⟶ Q.X j) (i : ℕ) :
d_next (i+1) f = P.d _ _ ≫ f i (i+1) :=
begin
dsimp [d_next],
have : (complex_shape.down ℕ).next (i + 1) = i := chain_complex.next_nat_succ _,
congr' 2,
end
@[simp] lemma d_next_zero_chain_complex (f : Π i j, P.X i ⟶ Q.X j) :
d_next 0 f = 0 :=
begin
dsimp [d_next],
rw [P.shape, zero_comp],
rw chain_complex.next_nat_zero, dsimp, dec_trivial,
end
variables (e : P ⟶ Q)
(zero : P.X 0 ⟶ Q.X 1)
(comm_zero : e.f 0 = zero ≫ Q.d 1 0)
(one : P.X 1 ⟶ Q.X 2)
(comm_one : e.f 1 = P.d 1 0 ≫ zero + one ≫ Q.d 2 1)
(succ : ∀ (n : ℕ)
(p : Σ' (f : P.X n ⟶ Q.X (n+1)) (f' : P.X (n+1) ⟶ Q.X (n+2)),
e.f (n+1) = P.d (n+1) n ≫ f + f' ≫ Q.d (n+2) (n+1)),
Σ' f'' : P.X (n+2) ⟶ Q.X (n+3), e.f (n+2) = P.d (n+2) (n+1) ≫ p.2.1 + f'' ≫ Q.d (n+3) (n+2))
include comm_one comm_zero
/--
An auxiliary construction for `mk_inductive`.
Here we build by induction a family of diagrams,
but don't require at the type level that these successive diagrams actually agree.
They do in fact agree, and we then capture that at the type level (i.e. by constructing a homotopy)
in `mk_inductive`.
At this stage, we don't check the homotopy condition in degree 0,
because it "falls off the end", and is easier to treat using `X_next` and `X_prev`,
which we do in `mk_inductive_aux₂`.
-/
@[simp, nolint unused_arguments]
def mk_inductive_aux₁ :
Π n, Σ' (f : P.X n ⟶ Q.X (n+1)) (f' : P.X (n+1) ⟶ Q.X (n+2)),
e.f (n+1) = P.d (n+1) n ≫ f + f' ≫ Q.d (n+2) (n+1)
| 0 := ⟨zero, one, comm_one⟩
| 1 := ⟨one, (succ 0 ⟨zero, one, comm_one⟩).1, (succ 0 ⟨zero, one, comm_one⟩).2⟩
| (n+2) :=
⟨(mk_inductive_aux₁ (n+1)).2.1,
(succ (n+1) (mk_inductive_aux₁ (n+1))).1,
(succ (n+1) (mk_inductive_aux₁ (n+1))).2⟩
section
/--
An auxiliary construction for `mk_inductive`.
-/
@[simp]
def mk_inductive_aux₂ :
Π n, Σ' (f : P.X_next n ⟶ Q.X n) (f' : P.X n ⟶ Q.X_prev n), e.f n = P.d_from n ≫ f + f' ≫ Q.d_to n
| 0 := ⟨0, zero ≫ (Q.X_prev_iso rfl).inv, by simpa using comm_zero⟩
| (n+1) := let I := mk_inductive_aux₁ e zero comm_zero one comm_one succ n in
⟨(P.X_next_iso rfl).hom ≫ I.1, I.2.1 ≫ (Q.X_prev_iso rfl).inv, by simpa using I.2.2⟩
lemma mk_inductive_aux₃ (i j : ℕ) (h : i+1 = j) :
(mk_inductive_aux₂ e zero comm_zero one comm_one succ i).2.1 ≫ (Q.X_prev_iso h).hom
= (P.X_next_iso h).inv ≫ (mk_inductive_aux₂ e zero comm_zero one comm_one succ j).1 :=
by subst j; rcases i with (_|_|i); { dsimp, simp, }
/--
A constructor for a `homotopy e 0`, for `e` a chain map between `ℕ`-indexed chain complexes,
working by induction.
You need to provide the components of the homotopy in degrees 0 and 1,
show that these satisfy the homotopy condition,
and then give a construction of each component,
and the fact that it satisfies the homotopy condition,
using as an inductive hypothesis the data and homotopy condition for the previous two components.
-/
def mk_inductive : homotopy e 0 :=
{ hom := λ i j, if h : i + 1 = j then
(mk_inductive_aux₂ e zero comm_zero one comm_one succ i).2.1 ≫ (Q.X_prev_iso h).hom
else
0,
zero' := λ i j w, by rwa dif_neg,
comm := λ i, begin
dsimp, simp only [add_zero],
convert (mk_inductive_aux₂ e zero comm_zero one comm_one succ i).2.2,
{ cases i,
{ dsimp [from_next], rw dif_neg,
simp only [chain_complex.next_nat_zero, nat.one_ne_zero, not_false_iff], },
{ dsimp [from_next], rw dif_pos, swap, { simp only [chain_complex.next_nat_succ] },
have aux : (complex_shape.down ℕ).next i.succ = i := chain_complex.next_nat_succ i,
rw mk_inductive_aux₃ e zero comm_zero one comm_one succ
((complex_shape.down ℕ).next i.succ) (i+1) (by rw aux),
dsimp [X_next_iso], erw category.id_comp, } },
{ dsimp [to_prev], rw dif_pos, swap, { simp only [chain_complex.prev] },
dsimp [X_prev_iso], erw category.comp_id, },
end, }
end
end mk_inductive
/-!
`homotopy.mk_coinductive` allows us to build a homotopy of cochain complexes inductively,
so that as we construct each component, we have available the previous two components,
and the fact that they satisfy the homotopy condition.
-/
section mk_coinductive
variables {P Q : cochain_complex V ℕ}
@[simp] lemma d_next_cochain_complex (f : Π i j, P.X i ⟶ Q.X j) (j : ℕ) :
d_next j f = P.d _ _ ≫ f (j+1) j :=
begin
dsimp [d_next],
have : (complex_shape.up ℕ).next j = j + 1 := cochain_complex.next ℕ j,
congr' 2,
end
@[simp] lemma prev_d_succ_cochain_complex (f : Π i j, P.X i ⟶ Q.X j) (i : ℕ) :
prev_d (i+1) f = f (i+1) _ ≫ Q.d i (i+1) :=
begin
dsimp [prev_d],
have : (complex_shape.up ℕ).prev (i+1) = i := cochain_complex.prev_nat_succ i,
congr' 2,
end
@[simp] lemma prev_d_zero_cochain_complex (f : Π i j, P.X i ⟶ Q.X j) :
prev_d 0 f = 0 :=
begin
dsimp [prev_d],
rw [Q.shape, comp_zero],
rw [cochain_complex.prev_nat_zero], dsimp, dec_trivial,
end
variables (e : P ⟶ Q)
(zero : P.X 1 ⟶ Q.X 0)
(comm_zero : e.f 0 = P.d 0 1 ≫ zero)
(one : P.X 2 ⟶ Q.X 1)
(comm_one : e.f 1 = zero ≫ Q.d 0 1 + P.d 1 2 ≫ one)
(succ : ∀ (n : ℕ)
(p : Σ' (f : P.X (n+1) ⟶ Q.X n) (f' : P.X (n+2) ⟶ Q.X (n+1)),
e.f (n+1) = f ≫ Q.d n (n+1) + P.d (n+1) (n+2) ≫ f'),
Σ' f'' : P.X (n+3) ⟶ Q.X (n+2), e.f (n+2) = p.2.1 ≫ Q.d (n+1) (n+2) + P.d (n+2) (n+3) ≫ f'')
include comm_one comm_zero succ
/--
An auxiliary construction for `mk_coinductive`.
Here we build by induction a family of diagrams,
but don't require at the type level that these successive diagrams actually agree.
They do in fact agree, and we then capture that at the type level (i.e. by constructing a homotopy)
in `mk_coinductive`.
At this stage, we don't check the homotopy condition in degree 0,
because it "falls off the end", and is easier to treat using `X_next` and `X_prev`,
which we do in `mk_inductive_aux₂`.
-/
@[simp, nolint unused_arguments]
def mk_coinductive_aux₁ :
Π n, Σ' (f : P.X (n+1) ⟶ Q.X n) (f' : P.X (n+2) ⟶ Q.X (n+1)),
e.f (n+1) = f ≫ Q.d n (n+1) + P.d (n+1) (n+2) ≫ f'
| 0 := ⟨zero, one, comm_one⟩
| 1 := ⟨one, (succ 0 ⟨zero, one, comm_one⟩).1, (succ 0 ⟨zero, one, comm_one⟩).2⟩
| (n+2) :=
⟨(mk_coinductive_aux₁ (n+1)).2.1,
(succ (n+1) (mk_coinductive_aux₁ (n+1))).1,
(succ (n+1) (mk_coinductive_aux₁ (n+1))).2⟩
section
/--
An auxiliary construction for `mk_inductive`.
-/
@[simp]
def mk_coinductive_aux₂ :
Π n, Σ' (f : P.X n ⟶ Q.X_prev n) (f' : P.X_next n ⟶ Q.X n),
e.f n = f ≫ Q.d_to n + P.d_from n ≫ f'
| 0 := ⟨0, (P.X_next_iso rfl).hom ≫ zero, by simpa using comm_zero⟩
| (n+1) := let I := mk_coinductive_aux₁ e zero comm_zero one comm_one succ n in
⟨I.1 ≫ (Q.X_prev_iso rfl).inv, (P.X_next_iso rfl).hom ≫ I.2.1, by simpa using I.2.2⟩
lemma mk_coinductive_aux₃ (i j : ℕ) (h : i + 1 = j) :
(P.X_next_iso h).inv ≫ (mk_coinductive_aux₂ e zero comm_zero one comm_one succ i).2.1
= (mk_coinductive_aux₂ e zero comm_zero one comm_one succ j).1 ≫ (Q.X_prev_iso h).hom :=
by subst j; rcases i with (_|_|i); { dsimp, simp, }
/--
A constructor for a `homotopy e 0`, for `e` a chain map between `ℕ`-indexed cochain complexes,
working by induction.
You need to provide the components of the homotopy in degrees 0 and 1,
show that these satisfy the homotopy condition,
and then give a construction of each component,
and the fact that it satisfies the homotopy condition,
using as an inductive hypothesis the data and homotopy condition for the previous two components.
-/
def mk_coinductive : homotopy e 0 :=
{ hom := λ i j, if h : j + 1 = i then
(P.X_next_iso h).inv ≫ (mk_coinductive_aux₂ e zero comm_zero one comm_one succ j).2.1
else
0,
zero' := λ i j w, by rwa dif_neg,
comm := λ i, begin
dsimp,
rw [add_zero, add_comm],
convert (mk_coinductive_aux₂ e zero comm_zero one comm_one succ i).2.2 using 2,
{ cases i,
{ dsimp [to_prev], rw dif_neg,
simp only [cochain_complex.prev_nat_zero, nat.one_ne_zero, not_false_iff], },
{ dsimp [to_prev], rw dif_pos, swap, { simp only [cochain_complex.prev_nat_succ] },
have aux : (complex_shape.up ℕ).prev i.succ = i := cochain_complex.prev_nat_succ i,
rw mk_coinductive_aux₃ e zero comm_zero one comm_one succ
((complex_shape.up ℕ).prev i.succ) (i+1) (by rw aux),
dsimp [X_prev_iso], erw category.comp_id, } },
{ dsimp [from_next], rw dif_pos, swap, { simp only [cochain_complex.next] },
dsimp [X_next_iso], erw category.id_comp, },
end }
end
end mk_coinductive
end homotopy
/--
A homotopy equivalence between two chain complexes consists of a chain map each way,
and homotopies from the compositions to the identity chain maps.
Note that this contains data;
arguably it might be more useful for many applications if we truncated it to a Prop.
-/
structure homotopy_equiv (C D : homological_complex V c) :=
(hom : C ⟶ D)
(inv : D ⟶ C)
(homotopy_hom_inv_id : homotopy (hom ≫ inv) (𝟙 C))
(homotopy_inv_hom_id : homotopy (inv ≫ hom) (𝟙 D))
namespace homotopy_equiv
/-- Any complex is homotopy equivalent to itself. -/
@[refl] def refl (C : homological_complex V c) : homotopy_equiv C C :=
{ hom := 𝟙 C,
inv := 𝟙 C,
homotopy_hom_inv_id := by simp,
homotopy_inv_hom_id := by simp, }
instance : inhabited (homotopy_equiv C C) := ⟨refl C⟩
/-- Being homotopy equivalent is a symmetric relation. -/
@[symm] def symm
{C D : homological_complex V c} (f : homotopy_equiv C D) :
homotopy_equiv D C :=
{ hom := f.inv,
inv := f.hom,
homotopy_hom_inv_id := f.homotopy_inv_hom_id,
homotopy_inv_hom_id := f.homotopy_hom_inv_id, }
/-- Homotopy equivalence is a transitive relation. -/
@[trans] def trans
{C D E : homological_complex V c} (f : homotopy_equiv C D) (g : homotopy_equiv D E) :
homotopy_equiv C E :=
{ hom := f.hom ≫ g.hom,
inv := g.inv ≫ f.inv,
homotopy_hom_inv_id := by simpa using
((g.homotopy_hom_inv_id.comp_right_id f.inv).comp_left f.hom).trans f.homotopy_hom_inv_id,
homotopy_inv_hom_id := by simpa using
((f.homotopy_inv_hom_id.comp_right_id g.hom).comp_left g.inv).trans g.homotopy_inv_hom_id, }
end homotopy_equiv
variables [has_equalizers V] [has_cokernels V] [has_images V] [has_image_maps V]
/--
Homotopic maps induce the same map on homology.
-/
theorem homology_map_eq_of_homotopy (h : homotopy f g) (i : ι) :
(homology_functor V c i).map f = (homology_functor V c i).map g :=
begin
dsimp [homology_functor],
apply eq_of_sub_eq_zero,
ext,
simp only [homology.π_map, comp_zero, preadditive.comp_sub],
dsimp [kernel_subobject_map],
simp_rw [h.comm i],
simp only [zero_add, zero_comp, d_next_eq_d_from_from_next, kernel_subobject_arrow_comp_assoc,
preadditive.comp_add],
rw [←preadditive.sub_comp],
simp only [category_theory.subobject.factor_thru_add_sub_factor_thru_right],
erw [subobject.factor_thru_of_le (D.boundaries_le_cycles i)],
{ simp, },
{ rw [prev_d_eq_to_prev_d_to, ←category.assoc],
apply image_subobject_factors_comp_self, },
end
/-- Homotopy equivalent complexes have isomorphic homologies. -/
def homology_obj_iso_of_homotopy_equiv (f : homotopy_equiv C D) (i : ι) :
(homology_functor V c i).obj C ≅ (homology_functor V c i).obj D :=
{ hom := (homology_functor V c i).map f.hom,
inv := (homology_functor V c i).map f.inv,
hom_inv_id' := begin
rw [←functor.map_comp, homology_map_eq_of_homotopy f.homotopy_hom_inv_id,
category_theory.functor.map_id],
end,
inv_hom_id' := begin
rw [←functor.map_comp, homology_map_eq_of_homotopy f.homotopy_inv_hom_id,
category_theory.functor.map_id],
end, }
end
namespace category_theory
variables {W : Type*} [category W] [preadditive W]
/-- An additive functor takes homotopies to homotopies. -/
@[simps]
def functor.map_homotopy (F : V ⥤ W) [F.additive] {f g : C ⟶ D} (h : homotopy f g) :
homotopy ((F.map_homological_complex c).map f) ((F.map_homological_complex c).map g) :=
{ hom := λ i j, F.map (h.hom i j),
zero' := λ i j w, by { rw [h.zero i j w, F.map_zero], },
comm := λ i, begin
dsimp [d_next, prev_d] at *,
rw h.comm i,
simp only [F.map_add, ← F.map_comp],
refl
end, }
/-- An additive functor preserves homotopy equivalences. -/
@[simps]
def functor.map_homotopy_equiv (F : V ⥤ W) [F.additive] (h : homotopy_equiv C D) :
homotopy_equiv ((F.map_homological_complex c).obj C) ((F.map_homological_complex c).obj D) :=
{ hom := (F.map_homological_complex c).map h.hom,
inv := (F.map_homological_complex c).map h.inv,
homotopy_hom_inv_id := begin
rw [←(F.map_homological_complex c).map_comp, ←(F.map_homological_complex c).map_id],
exact F.map_homotopy h.homotopy_hom_inv_id,
end,
homotopy_inv_hom_id := begin
rw [←(F.map_homological_complex c).map_comp, ←(F.map_homological_complex c).map_id],
exact F.map_homotopy h.homotopy_inv_hom_id,
end }
end category_theory
|
5224b55cbb014756ad14d3c6f84c2d53b0ec323e | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /library/tools/super/prover_state.lean | 57dd7c07c75ca0dd03b5b088f1004f6df7283c32 | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,688 | lean | /-
Copyright (c) 2016 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import .clause .lpo .cdcl_solver
open tactic monad expr
namespace super
structure score :=
(priority : ℕ)
(in_sos : bool)
(cost : ℕ)
(age : ℕ)
namespace score
def prio.immediate : ℕ := 0
def prio.default : ℕ := 1
def prio.never : ℕ := 2
def sched_default (sc : score) : score := { sc with priority := prio.default }
def sched_now (sc : score) : score := { sc with priority := prio.immediate }
def inc_cost (sc : score) (n : ℕ) : score := { sc with cost := sc^.cost + n }
def min (a b : score) : score :=
{ priority := nat.min a^.priority b^.priority,
in_sos := a^.in_sos && b^.in_sos,
cost := nat.min a^.cost b^.cost,
age := nat.min a^.age b^.age }
def combine (a b : score) : score :=
{ priority := nat.max a^.priority b^.priority,
in_sos := a^.in_sos && b^.in_sos,
cost := a^.cost + b^.cost,
age := nat.max a^.age b^.age }
end score
namespace score
meta instance : has_to_string score :=
⟨λe, "[" ++ to_string e^.priority ++
"," ++ to_string e^.cost ++
"," ++ to_string e^.age ++
",sos=" ++ to_string e^.in_sos ++ "]"⟩
end score
def clause_id := ℕ
namespace clause_id
def to_nat (id : clause_id) : ℕ := id
instance : decidable_eq clause_id := nat.decidable_eq
instance : has_ordering clause_id := nat.has_ordering
end clause_id
meta structure derived_clause :=
(id : clause_id)
(c : clause)
(selected : list ℕ)
(assertions : list expr)
(sc : score)
namespace derived_clause
meta instance : has_to_tactic_format derived_clause :=
⟨λc, do
prf_fmt ← pp c^.c^.proof,
c_fmt ← pp c^.c,
ass_fmt ← pp (c^.assertions^.for (λa, a^.local_type)),
return $
to_string c^.sc ++ " " ++
prf_fmt ++ " " ++
c_fmt ++ " <- " ++ ass_fmt ++
" (selected: " ++ to_fmt c^.selected ++
")"
⟩
meta def clause_with_assertions (ac : derived_clause) : clause :=
ac^.c^.close_constn ac^.assertions
meta def update_proof (dc : derived_clause) (p : expr) : derived_clause :=
{ dc with c := { (dc^.c) with proof := p } }
end derived_clause
meta structure locked_clause :=
(dc : derived_clause)
(reasons : list (list expr))
namespace locked_clause
meta instance : has_to_tactic_format locked_clause :=
⟨λc, do
c_fmt ← pp c^.dc,
reasons_fmt ← pp (c^.reasons^.for (λr, r^.for (λa, a^.local_type))),
return $ c_fmt ++ " (locked in case of: " ++ reasons_fmt ++ ")"
⟩
end locked_clause
meta structure prover_state :=
(active : rb_map clause_id derived_clause)
(passive : rb_map clause_id derived_clause)
(newly_derived : list derived_clause)
(prec : list expr)
(locked : list locked_clause)
(local_false : expr)
(sat_solver : cdcl.state)
(current_model : rb_map expr bool)
(sat_hyps : rb_map expr (expr × expr))
(needs_sat_run : bool)
(clause_counter : nat)
open prover_state
private meta def join_with_nl : list format → format :=
list.foldl (λx y, x ++ format.line ++ y) format.nil
private meta def prover_state_tactic_fmt (s : prover_state) : tactic format := do
active_fmts ← mapm pp $ rb_map.values s^.active,
passive_fmts ← mapm pp $ rb_map.values s^.passive,
new_fmts ← mapm pp s^.newly_derived,
locked_fmts ← mapm pp s^.locked,
sat_fmts ← mapm pp s^.sat_solver^.clauses,
sat_model_fmts ← for s^.current_model^.to_list (λx, if x.2 = tt then pp x.1 else pp (not_ x.1)),
prec_fmts ← mapm pp s^.prec,
return (join_with_nl
([to_fmt "active:"] ++ map (append (to_fmt " ")) active_fmts ++
[to_fmt "passive:"] ++ map (append (to_fmt " ")) passive_fmts ++
[to_fmt "new:"] ++ map (append (to_fmt " ")) new_fmts ++
[to_fmt "locked:"] ++ map (append (to_fmt " ")) locked_fmts ++
[to_fmt "sat formulas:"] ++ map (append (to_fmt " ")) sat_fmts ++
[to_fmt "sat model:"] ++ map (append (to_fmt " ")) sat_model_fmts ++
[to_fmt "precedence order: " ++ to_fmt prec_fmts]))
meta instance : has_to_tactic_format prover_state :=
⟨prover_state_tactic_fmt⟩
meta def prover := state_t prover_state tactic
namespace prover
meta instance : monad prover := state_t.monad _ _
meta instance : has_monad_lift tactic prover :=
monad.monad_transformer_lift (state_t prover_state) tactic
meta instance (α : Type) : has_coe (tactic α) (prover α) :=
⟨monad.monad_lift⟩
meta def fail {α β : Type} [has_to_format β] (msg : β) : prover α :=
tactic.fail msg
meta def orelse (A : Type) (p1 p2 : prover A) : prover A :=
take state, p1 state <|> p2 state
meta instance : alternative prover :=
{ monad_is_applicative prover with
failure := λα, fail "failed",
orelse := orelse }
end prover
meta def selection_strategy := derived_clause → prover derived_clause
meta def get_active : prover (rb_map clause_id derived_clause) :=
do state ← state_t.read, return state^.active
meta def add_active (a : derived_clause) : prover unit :=
do state ← state_t.read,
state_t.write { state with active := state^.active^.insert a^.id a }
meta def get_passive : prover (rb_map clause_id derived_clause) :=
lift passive state_t.read
meta def get_precedence : prover (list expr) :=
do state ← state_t.read, return state^.prec
meta def get_term_order : prover (expr → expr → bool) := do
state ← state_t.read,
return $ mk_lpo (map name_of_funsym state^.prec)
private meta def set_precedence (new_prec : list expr) : prover unit :=
do state ← state_t.read, state_t.write { state with prec := new_prec }
meta def register_consts_in_precedence (consts : list expr) := do
p ← get_precedence,
p_set ← return (rb_map.set_of_list (map name_of_funsym p)),
new_syms ← return $ list.filter (λc, ¬p_set^.contains (name_of_funsym c)) consts,
set_precedence (new_syms ++ p)
meta def in_sat_solver {A} (cmd : cdcl.solver A) : prover A := do
state ← state_t.read,
result ← cmd state^.sat_solver,
state_t.write { state with sat_solver := result.2 },
return result.1
meta def collect_ass_hyps (c : clause) : prover (list expr) :=
let lcs := contained_lconsts c^.proof in
do st ← state_t.read,
return (do
hs ← st^.sat_hyps^.values,
h ← [hs.1, hs.2],
guard $ lcs^.contains h^.local_uniq_name,
[h])
meta def get_clause_count : prover ℕ :=
do s ← state_t.read, return s^.clause_counter
meta def get_new_cls_id : prover clause_id := do
state ← state_t.read,
state_t.write { state with clause_counter := state^.clause_counter + 1 },
return state^.clause_counter
meta def mk_derived (c : clause) (sc : score) : prover derived_clause := do
ass ← collect_ass_hyps c,
id ← get_new_cls_id,
return { id := id, c := c, selected := [], assertions := ass, sc := sc }
meta def add_inferred (c : derived_clause) : prover unit := do
c' ← c^.c^.normalize, c' ← return { c with c := c' },
register_consts_in_precedence (contained_funsyms c'^.c^.type)^.values,
state ← state_t.read,
state_t.write { state with newly_derived := c' :: state^.newly_derived }
-- FIXME: what if we've seen the variable before, but with a weaker score?
meta def mk_sat_var (v : expr) (suggested_ph : bool) (suggested_ev : score) : prover unit :=
do st ← state_t.read, if st^.sat_hyps^.contains v then return () else do
hpv ← mk_local_def `h v,
hnv ← mk_local_def `hn $ imp v st^.local_false,
state_t.modify $ λst, { st with sat_hyps := st^.sat_hyps^.insert v (hpv, hnv) },
in_sat_solver $ cdcl.mk_var_core v suggested_ph,
match v with
| (pi _ _ _ _) := do
c ← clause.of_proof st^.local_false hpv,
mk_derived c suggested_ev >>= add_inferred
| _ := do cp ← clause.of_proof st^.local_false hpv, mk_derived cp suggested_ev >>= add_inferred,
cn ← clause.of_proof st^.local_false hnv, mk_derived cn suggested_ev >>= add_inferred
end
meta def get_sat_hyp_core (v : expr) (ph : bool) : prover (option expr) :=
flip monad.lift state_t.read $ λst,
match st^.sat_hyps^.find v with
| some (hp, hn) := some $ if ph then hp else hn
| none := none
end
meta def get_sat_hyp (v : expr) (ph : bool) : prover expr :=
do hyp_opt ← get_sat_hyp_core v ph,
match hyp_opt with
| some hyp := return hyp
| none := fail $ "unknown sat variable: " ++ v^.to_string
end
meta def add_sat_clause (c : clause) (suggested_ev : score) : prover unit := do
c ← c^.distinct,
already_added ← flip monad.lift state_t.read $ λst, decidable.to_bool $
c^.type ∈ st^.sat_solver^.clauses^.for (λd, d^.type),
if already_added then return () else do
for c^.get_lits $ λl, mk_sat_var l^.formula l^.is_neg suggested_ev,
in_sat_solver $ cdcl.mk_clause c,
state_t.modify $ λst, { st with needs_sat_run := tt }
meta def sat_eval_lit (v : expr) (pol : bool) : prover bool :=
do v_st ← flip monad.lift state_t.read $ λst, st^.current_model^.find v,
match v_st with
| some ph := return $ if pol then ph else bnot ph
| none := return tt
end
meta def sat_eval_assertion (assertion : expr) : prover bool :=
do lf ← flip monad.lift state_t.read $ λst, st^.local_false,
match is_local_not lf assertion^.local_type with
| some v := sat_eval_lit v ff
| none := sat_eval_lit assertion^.local_type tt
end
meta def sat_eval_assertions : list expr → prover bool
| (a::ass) := do v_a ← sat_eval_assertion a,
if v_a then
sat_eval_assertions ass
else
return ff
| [] := return tt
private meta def intern_clause (c : derived_clause) : prover derived_clause := do
hyp_name ← get_unused_name (mk_simple_name $ "clause_" ++ to_string c^.id^.to_nat) none,
c' ← return $ c^.c^.close_constn c^.assertions,
assertv hyp_name c'^.type c'^.proof,
proof' ← get_local hyp_name,
type ← infer_type proof', -- FIXME: otherwise ""
return $ c^.update_proof $ app_of_list proof' c^.assertions
meta def register_as_passive (c : derived_clause) : prover unit := do
c ← intern_clause c,
ass_v ← sat_eval_assertions c^.assertions,
if c^.c^.num_quants = 0 ∧ c^.c^.num_lits = 0 then
add_sat_clause c^.clause_with_assertions c^.sc
else if ¬ass_v then do
state_t.modify $ λst, { st with locked := ⟨c, []⟩ :: st^.locked }
else do
state_t.modify $ λst, { st with passive := st^.passive^.insert c^.id c }
meta def remove_passive (id : clause_id) : prover unit :=
do state ← state_t.read, state_t.write { state with passive := state^.passive^.erase id }
meta def move_locked_to_passive : prover unit := do
locked ← flip monad.lift state_t.read (λst, st^.locked),
new_locked ← flip filter locked (λlc, do
reason_vals ← mapm sat_eval_assertions lc^.reasons,
c_val ← sat_eval_assertions lc^.dc^.assertions,
if reason_vals^.for_all (λr, r = ff) ∧ c_val then do
state_t.modify $ λst, { st with passive := st^.passive^.insert lc^.dc^.id lc^.dc },
return ff
else
return tt
),
state_t.modify $ λst, { st with locked := new_locked }
meta def move_active_to_locked : prover unit :=
do active ← get_active, for' active^.values $ λac, do
c_val ← sat_eval_assertions ac^.assertions,
if ¬c_val then do
state_t.modify $ λst, { st with
active := st^.active^.erase ac^.id,
locked := ⟨ac, []⟩ :: st^.locked
}
else
return ()
meta def move_passive_to_locked : prover unit :=
do passive ← flip monad.lift state_t.read $ λst, st^.passive, for' passive^.to_list $ λpc, do
c_val ← sat_eval_assertions pc.2^.assertions,
if ¬c_val then do
state_t.modify $ λst, { st with
passive := st^.passive^.erase pc.1,
locked := ⟨pc.2, []⟩ :: st^.locked
}
else
return ()
def super_cc_config : cc_config :=
{ em := ff }
meta def do_sat_run : prover (option expr) :=
do sat_result ← in_sat_solver $ cdcl.run (cdcl.theory_solver_of_tactic $ using_smt $ return ()),
state_t.modify $ λst, { st with needs_sat_run := ff },
old_model ← lift prover_state.current_model state_t.read,
match sat_result with
| (cdcl.result.unsat proof) := return (some proof)
| (cdcl.result.sat new_model) := do
state_t.modify $ λst, { st with current_model := new_model },
move_locked_to_passive,
move_active_to_locked,
move_passive_to_locked,
return none
end
meta def take_newly_derived : prover (list derived_clause) := do
state ← state_t.read,
state_t.write { state with newly_derived := [] },
return state^.newly_derived
meta def remove_redundant (id : clause_id) (parents : list derived_clause) : prover unit := do
when (not $ parents^.for_all $ λp, p^.id ≠ id) (fail "clause is redundant because of itself"),
red ← flip monad.lift state_t.read (λst, st^.active^.find id),
match red with
| none := return ()
| some red := do
let reasons := parents^.for (λp, p^.assertions),
let assertion := red^.assertions,
if reasons^.for_all $ λr, r^.subset_of assertion then do
state_t.modify $ λst, { st with active := st^.active^.erase id }
else do
state_t.modify $ λst, { st with active := st^.active^.erase id,
locked := ⟨red, reasons⟩ :: st^.locked }
end
meta def inference := derived_clause → prover unit
meta structure inf_decl := (prio : ℕ) (inf : inference)
meta def inf_attr : user_attribute :=
⟨ `super.inf, "inference for the super prover" ⟩
run_command attribute.register `super.inf_attr
meta def seq_inferences : list inference → inference
| [] := λgiven, return ()
| (inf::infs) := λgiven, do
inf given,
now_active ← get_active,
if rb_map.contains now_active given^.id then
seq_inferences infs given
else
return ()
meta def simp_inference (simpl : derived_clause → prover (option clause)) : inference :=
λgiven, do maybe_simpld ← simpl given,
match maybe_simpld with
| some simpld := do
derived_simpld ← mk_derived simpld given^.sc^.sched_now,
add_inferred derived_simpld,
remove_redundant given^.id []
| none := return ()
end
meta def preprocessing_rule (f : list derived_clause → prover (list derived_clause)) : prover unit := do
state ← state_t.read,
newly_derived' ← f state^.newly_derived,
state' ← state_t.read,
state_t.write { state' with newly_derived := newly_derived' }
meta def clause_selection_strategy := ℕ → prover clause_id
namespace prover_state
meta def empty (local_false : expr) : prover_state :=
{ active := rb_map.mk _ _, passive := rb_map.mk _ _,
newly_derived := [], prec := [], clause_counter := 0,
local_false := local_false,
locked := [], sat_solver := cdcl.state.initial local_false,
current_model := rb_map.mk _ _, sat_hyps := rb_map.mk _ _, needs_sat_run := ff }
meta def initial (local_false : expr) (clauses : list clause) : tactic prover_state := do
after_setup ← for' clauses (λc,
let in_sos := ((contained_lconsts c^.proof)^.erase local_false^.local_uniq_name)^.size = 0 in
do mk_derived c { priority := score.prio.immediate, in_sos := in_sos,
age := 0, cost := 0 } >>= add_inferred
) $ empty local_false,
return after_setup.2
end prover_state
meta def inf_score (add_cost : ℕ) (scores : list score) : prover score := do
age ← get_clause_count,
return $ list.foldl score.combine { priority := score.prio.default,
in_sos := tt,
age := age,
cost := add_cost
} scores
meta def inf_if_successful (add_cost : ℕ) (parent : derived_clause) (tac : tactic (list clause)) : prover unit :=
(do inferred ← tac,
for' inferred $ λc,
inf_score add_cost [parent^.sc] >>= mk_derived c >>= add_inferred)
<|> return ()
meta def simp_if_successful (parent : derived_clause) (tac : tactic (list clause)) : prover unit :=
(do inferred ← tac,
for' inferred $ λc,
mk_derived c parent^.sc^.sched_now >>= add_inferred,
remove_redundant parent^.id [])
<|> return ()
end super
|
a990606719e2f10918c427429f5113ec5c60e791 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/logic/nontrivial.lean | 2ab8166a5ee1b4541c5b929add5a7ddbd0254532 | [
"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 | 10,393 | 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 data.pi
import data.prod
import data.subtype
import logic.unique
import logic.function.basic
/-!
# Nontrivial types
A type is *nontrivial* if it contains at least two elements. This is useful in particular for rings
(where it is equivalent to the fact that zero is different from one) and for vector spaces
(where it is equivalent to the fact that the dimension is positive).
We introduce a typeclass `nontrivial` formalizing this property.
-/
variables {α : Type*} {β : Type*}
open_locale classical
/-- Predicate typeclass for expressing that a type is not reduced to a single element. In rings,
this is equivalent to `0 ≠ 1`. In vector spaces, this is equivalent to positive dimension. -/
class nontrivial (α : Type*) : Prop :=
(exists_pair_ne : ∃ (x y : α), x ≠ y)
lemma nontrivial_iff : nontrivial α ↔ ∃ (x y : α), x ≠ y :=
⟨λ h, h.exists_pair_ne, λ h, ⟨h⟩⟩
lemma exists_pair_ne (α : Type*) [nontrivial α] : ∃ (x y : α), x ≠ y :=
nontrivial.exists_pair_ne
-- See Note [decidable namespace]
protected lemma decidable.exists_ne [nontrivial α] [decidable_eq α] (x : α) : ∃ y, y ≠ x :=
begin
rcases exists_pair_ne α with ⟨y, y', h⟩,
by_cases hx : x = y,
{ rw ← hx at h,
exact ⟨y', h.symm⟩ },
{ exact ⟨y, ne.symm hx⟩ }
end
lemma exists_ne [nontrivial α] (x : α) : ∃ y, y ≠ x :=
by classical; exact decidable.exists_ne x
-- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`.
lemma nontrivial_of_ne (x y : α) (h : x ≠ y) : nontrivial α :=
⟨⟨x, y, h⟩⟩
-- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`.
lemma nontrivial_of_lt [preorder α] (x y : α) (h : x < y) : nontrivial α :=
⟨⟨x, y, ne_of_lt h⟩⟩
lemma nontrivial_iff_exists_ne (x : α) : nontrivial α ↔ ∃ y, y ≠ x :=
⟨λ h, @exists_ne α h x, λ ⟨y, hy⟩, nontrivial_of_ne _ _ hy⟩
lemma subtype.nontrivial_iff_exists_ne (p : α → Prop) (x : subtype p) :
nontrivial (subtype p) ↔ ∃ (y : α) (hy : p y), y ≠ x :=
by simp only [nontrivial_iff_exists_ne x, subtype.exists, ne.def, subtype.ext_iff, subtype.coe_mk]
/--
See Note [lower instance priority]
Note that since this and `nonempty_of_inhabited` are the most "obvious" way to find a nonempty
instance if no direct instance can be found, we give this a higher priority than the usual `100`.
-/
@[priority 500]
instance nontrivial.to_nonempty [nontrivial α] : nonempty α :=
let ⟨x, _⟩ := exists_pair_ne α in ⟨x⟩
attribute [instance, priority 500] nonempty_of_inhabited
/-- An inhabited type is either nontrivial, or has a unique element. -/
noncomputable def nontrivial_psum_unique (α : Type*) [inhabited α] :
psum (nontrivial α) (unique α) :=
if h : nontrivial α then psum.inl h else psum.inr
{ default := default α,
uniq := λ (x : α),
begin
change x = default α,
contrapose! h,
use [x, default α]
end }
lemma subsingleton_iff : subsingleton α ↔ ∀ (x y : α), x = y :=
⟨by { introsI h, exact subsingleton.elim }, λ h, ⟨h⟩⟩
lemma not_nontrivial_iff_subsingleton : ¬(nontrivial α) ↔ subsingleton α :=
by { rw [nontrivial_iff, subsingleton_iff], push_neg, refl }
lemma not_subsingleton (α) [h : nontrivial α] : ¬subsingleton α :=
let ⟨⟨x, y, hxy⟩⟩ := h in λ ⟨h'⟩, hxy $ h' x y
/-- A type is either a subsingleton or nontrivial. -/
lemma subsingleton_or_nontrivial (α : Type*) : subsingleton α ∨ nontrivial α :=
by { rw [← not_nontrivial_iff_subsingleton, or_comm], exact classical.em _ }
lemma false_of_nontrivial_of_subsingleton (α : Type*) [nontrivial α] [subsingleton α] : false :=
let ⟨x, y, h⟩ := exists_pair_ne α in h $ subsingleton.elim x y
instance option.nontrivial [nonempty α] : nontrivial (option α) :=
by { inhabit α, use [none, some (default α)] }
/-- Pushforward a `nontrivial` instance along an injective function. -/
protected lemma function.injective.nontrivial [nontrivial α]
{f : α → β} (hf : function.injective f) : nontrivial β :=
let ⟨x, y, h⟩ := exists_pair_ne α in ⟨⟨f x, f y, hf.ne h⟩⟩
/-- Pullback a `nontrivial` instance along a surjective function. -/
protected lemma function.surjective.nontrivial [nontrivial β]
{f : α → β} (hf : function.surjective f) : nontrivial α :=
begin
rcases exists_pair_ne β with ⟨x, y, h⟩,
rcases hf x with ⟨x', hx'⟩,
rcases hf y with ⟨y', hy'⟩,
have : x' ≠ y', by { contrapose! h, rw [← hx', ← hy', h] },
exact ⟨⟨x', y', this⟩⟩
end
/-- An injective function from a nontrivial type has an argument at
which it does not take a given value. -/
protected lemma function.injective.exists_ne [nontrivial α] {f : α → β}
(hf : function.injective f) (y : β) : ∃ x, f x ≠ y :=
begin
rcases exists_pair_ne α with ⟨x₁, x₂, hx⟩,
by_cases h : f x₂ = y,
{ exact ⟨x₁, (hf.ne_iff' h).2 hx⟩ },
{ exact ⟨x₂, h⟩ }
end
instance nontrivial_prod_right [nonempty α] [nontrivial β] : nontrivial (α × β) :=
prod.snd_surjective.nontrivial
instance nontrivial_prod_left [nontrivial α] [nonempty β] : nontrivial (α × β) :=
prod.fst_surjective.nontrivial
namespace pi
variables {I : Type*} {f : I → Type*}
/-- A pi type is nontrivial if it's nonempty everywhere and nontrivial somewhere. -/
lemma nontrivial_at (i' : I) [inst : Π i, nonempty (f i)] [nontrivial (f i')] :
nontrivial (Π i : I, f i) :=
by classical; exact
(function.update_injective (λ i, classical.choice (inst i)) i').nontrivial
/--
As a convenience, provide an instance automatically if `(f (default I))` is nontrivial.
If a different index has the non-trivial type, then use `haveI := nontrivial_at that_index`.
-/
instance nontrivial [inhabited I] [inst : Π i, nonempty (f i)] [nontrivial (f (default I))] :
nontrivial (Π i : I, f i) :=
nontrivial_at (default I)
end pi
instance function.nontrivial [h : nonempty α] [nontrivial β] : nontrivial (α → β) :=
h.elim $ λ a, pi.nontrivial_at a
mk_simp_attribute nontriviality "Simp lemmas for `nontriviality` tactic"
protected lemma subsingleton.le [preorder α] [subsingleton α] (x y : α) : x ≤ y :=
le_of_eq (subsingleton.elim x y)
attribute [nontriviality] eq_iff_true_of_subsingleton subsingleton.le
namespace tactic
/--
Tries to generate a `nontrivial α` instance by performing case analysis on
`subsingleton_or_nontrivial α`,
attempting to discharge the subsingleton branch using lemmas with `@[nontriviality]` attribute,
including `subsingleton.le` and `eq_iff_true_of_subsingleton`.
-/
meta def nontriviality_by_elim (α : expr) (lems : interactive.parse simp_arg_list) : tactic unit :=
do
alternative ← to_expr ``(subsingleton_or_nontrivial %%α),
n ← get_unused_name "_inst",
tactic.cases alternative [n, n],
(solve1 $ do
reset_instance_cache,
apply_instance <|>
interactive.simp none none ff lems [`nontriviality] (interactive.loc.ns [none])) <|>
fail format!"Could not prove goal assuming `subsingleton {α}`",
reset_instance_cache
/--
Tries to generate a `nontrivial α` instance using `nontrivial_of_ne` or `nontrivial_of_lt`
and local hypotheses.
-/
meta def nontriviality_by_assumption (α : expr) : tactic unit :=
do
n ← get_unused_name "_inst",
to_expr ``(nontrivial %%α) >>= assert n,
apply_instance <|> `[solve_by_elim [nontrivial_of_ne, nontrivial_of_lt]],
reset_instance_cache
end tactic
namespace tactic.interactive
open tactic
setup_tactic_parser
/--
Attempts to generate a `nontrivial α` hypothesis.
The tactic first looks for an instance using `apply_instance`.
If the goal is an (in)equality, the type `α` is inferred from the goal.
Otherwise, the type needs to be specified in the tactic invocation, as `nontriviality α`.
The `nontriviality` tactic will first look for strict inequalities amongst the hypotheses,
and use these to derive the `nontrivial` instance directly.
Otherwise, it will perform a case split on `subsingleton α ∨ nontrivial α`, and attempt to discharge
the `subsingleton` goal using `simp [lemmas] with nontriviality`, where `[lemmas]` is a list of
additional `simp` lemmas that can be passed to `nontriviality` using the syntax
`nontriviality α using [lemmas]`.
```
example {R : Type} [ordered_ring R] {a : R} (h : 0 < a) : 0 < a :=
begin
nontriviality, -- There is now a `nontrivial R` hypothesis available.
assumption,
end
```
```
example {R : Type} [comm_ring R] {r s : R} : r * s = s * r :=
begin
nontriviality, -- There is now a `nontrivial R` hypothesis available.
apply mul_comm,
end
```
```
example {R : Type} [ordered_ring R] {a : R} (h : 0 < a) : (2 : ℕ) ∣ 4 :=
begin
nontriviality R, -- there is now a `nontrivial R` hypothesis available.
dec_trivial
end
```
```
def myeq {α : Type} (a b : α) : Prop := a = b
example {α : Type} (a b : α) (h : a = b) : myeq a b :=
begin
success_if_fail { nontriviality α }, -- Fails
nontriviality α using [myeq], -- There is now a `nontrivial α` hypothesis available
assumption
end
```
-/
meta def nontriviality (t : parse texpr?)
(lems : parse (tk "using" *> simp_arg_list <|> pure [])) :
tactic unit :=
do
α ← match t with
| some α := to_expr α
| none :=
(do t ← mk_mvar, e ← to_expr ``(@eq %%t _ _), target >>= unify e, return t) <|>
(do t ← mk_mvar, e ← to_expr ``(@has_le.le %%t _ _ _), target >>= unify e, return t) <|>
(do t ← mk_mvar, e ← to_expr ``(@ne %%t _ _), target >>= unify e, return t) <|>
(do t ← mk_mvar, e ← to_expr ``(@has_lt.lt %%t _ _ _), target >>= unify e, return t) <|>
fail "The goal is not an (in)equality, so you'll need to specify the desired `nontrivial α`
instance by invoking `nontriviality α`."
end,
nontriviality_by_assumption α <|> nontriviality_by_elim α lems
add_tactic_doc
{ name := "nontriviality",
category := doc_category.tactic,
decl_names := [`tactic.interactive.nontriviality],
tags := ["logic", "type class"] }
end tactic.interactive
namespace bool
instance : nontrivial bool := ⟨⟨tt,ff, tt_eq_ff_eq_false⟩⟩
end bool
|
1dc3cd79ed72b3a444b5b5f553e1b5f035b644f6 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/topology/metric_space/holder.lean | ea4a06f7cc792ccefe909a84101e38c60540b885 | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,700 | lean | /-
Copyright (c) 2021 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import topology.metric_space.lipschitz
import analysis.special_functions.pow
/-!
# Hölder continuous functions
In this file we define Hölder continuity on a set and on the whole space. We also prove some basic
properties of Hölder continuous functions.
## Main definitions
* `holder_on_with`: `f : X → Y` is said to be *Hölder continuous* with constant `C : ℝ≥0` and
exponent `r : ℝ≥0` on a set `s`, if `edist (f x) (f y) ≤ C * edist x y ^ r` for all `x y ∈ s`;
* `holder_with`: `f : X → Y` is said to be *Hölder continuous* with constant `C : ℝ≥0` and exponent
`r : ℝ≥0`, if `edist (f x) (f y) ≤ C * edist x y ^ r` for all `x y : X`.
## Implementation notes
We use the type `ℝ≥0` (a.k.a. `nnreal`) for `C` because this type has coercion both to `ℝ` and
`ℝ≥0∞`, so it can be easily used both in inequalities about `dist` and `edist`. We also use `ℝ≥0`
for `r` to ensure that `d ^ r` is monotonically increasing in `d`. It might be a good idea to use
`ℝ>0` for `r` but we don't have this type in `mathlib` (yet).
## Tags
Hölder continuity, Lipschitz continuity
-/
variables {X Y Z : Type*}
open filter set
open_locale nnreal ennreal topological_space
section emetric
variables [pseudo_emetric_space X] [pseudo_emetric_space Y] [pseudo_emetric_space Z]
/-- A function `f : X → Y` between two `pseudo_emetric_space`s is Hölder continuous with constant
`C : ℝ≥0` and exponent `r : ℝ≥0`, if `edist (f x) (f y) ≤ C * edist x y ^ r` for all `x y : X`. -/
def holder_with (C r : ℝ≥0) (f : X → Y) : Prop :=
∀ x y, edist (f x) (f y) ≤ C * edist x y ^ (r : ℝ)
/-- A function `f : X → Y` between two `pseudo_emeteric_space`s is Hölder continuous with constant
`C : ℝ≥0` and exponent `r : ℝ≥0` on a set `s : set X`, if `edist (f x) (f y) ≤ C * edist x y ^ r`
for all `x y ∈ s`. -/
def holder_on_with (C r : ℝ≥0) (f : X → Y) (s : set X) : Prop :=
∀ (x ∈ s) (y ∈ s), edist (f x) (f y) ≤ C * edist x y ^ (r : ℝ)
@[simp] lemma holder_on_with_empty (C r : ℝ≥0) (f : X → Y) : holder_on_with C r f ∅ :=
λ x hx, hx.elim
@[simp] lemma holder_on_with_singleton (C r : ℝ≥0) (f : X → Y) (x : X) : holder_on_with C r f {x} :=
by { rintro a (rfl : a = x) b (rfl : b = a), rw edist_self, exact zero_le _ }
lemma set.subsingleton.holder_on_with {s : set X} (hs : s.subsingleton) (C r : ℝ≥0) (f : X → Y) :
holder_on_with C r f s :=
hs.induction_on (holder_on_with_empty C r f) (holder_on_with_singleton C r f)
lemma holder_on_with_univ {C r : ℝ≥0} {f : X → Y} :
holder_on_with C r f univ ↔ holder_with C r f :=
by simp only [holder_on_with, holder_with, mem_univ, true_implies_iff]
@[simp] lemma holder_on_with_one {C : ℝ≥0} {f : X → Y} {s : set X} :
holder_on_with C 1 f s ↔ lipschitz_on_with C f s :=
by simp only [holder_on_with, lipschitz_on_with, nnreal.coe_one, ennreal.rpow_one]
alias holder_on_with_one ↔ _ lipschitz_on_with.holder_on_with
@[simp] lemma holder_with_one {C : ℝ≥0} {f : X → Y} :
holder_with C 1 f ↔ lipschitz_with C f :=
holder_on_with_univ.symm.trans $ holder_on_with_one.trans lipschitz_on_univ
alias holder_with_one ↔ _ lipschitz_with.holder_with
lemma holder_with_id : holder_with 1 1 (id : X → X) :=
lipschitz_with.id.holder_with
protected lemma holder_with.holder_on_with {C r : ℝ≥0} {f : X → Y} (h : holder_with C r f)
(s : set X) :
holder_on_with C r f s :=
λ x _ y _, h x y
namespace holder_on_with
variables {C r : ℝ≥0} {f : X → Y} {s t : set X}
lemma edist_le (h : holder_on_with C r f s) {x y : X} (hx : x ∈ s) (hy : y ∈ s) :
edist (f x) (f y) ≤ C * edist x y ^ (r : ℝ) :=
h x hx y hy
lemma edist_le_of_le (h : holder_on_with C r f s) {x y : X} (hx : x ∈ s) (hy : y ∈ s)
{d : ℝ≥0∞} (hd : edist x y ≤ d) :
edist (f x) (f y) ≤ C * d ^ (r : ℝ) :=
(h.edist_le hx hy).trans (mul_le_mul_left' (ennreal.rpow_le_rpow hd r.coe_nonneg) _)
lemma comp {Cg rg : ℝ≥0} {g : Y → Z} {t : set Y} (hg : holder_on_with Cg rg g t)
{Cf rf : ℝ≥0} {f : X → Y} (hf : holder_on_with Cf rf f s) (hst : maps_to f s t) :
holder_on_with (Cg * Cf ^ (rg : ℝ)) (rg * rf) (g ∘ f) s :=
begin
intros x hx y hy,
rw [ennreal.coe_mul, mul_comm rg, nnreal.coe_mul, ennreal.rpow_mul, mul_assoc,
← ennreal.coe_rpow_of_nonneg _ rg.coe_nonneg, ← ennreal.mul_rpow_of_nonneg _ _ rg.coe_nonneg],
exact hg.edist_le_of_le (hst hx) (hst hy) (hf.edist_le hx hy)
end
lemma comp_holder_with {Cg rg : ℝ≥0} {g : Y → Z} {t : set Y} (hg : holder_on_with Cg rg g t)
{Cf rf : ℝ≥0} {f : X → Y} (hf : holder_with Cf rf f) (ht : ∀ x, f x ∈ t) :
holder_with (Cg * Cf ^ (rg : ℝ)) (rg * rf) (g ∘ f) :=
holder_on_with_univ.mp $ hg.comp (hf.holder_on_with univ) (λ x _, ht x)
/-- A Hölder continuous function is uniformly continuous -/
protected lemma uniform_continuous_on (hf : holder_on_with C r f s) (h0 : 0 < r) :
uniform_continuous_on f s :=
begin
refine emetric.uniform_continuous_on_iff.2 (λε εpos, _),
have : tendsto (λ d : ℝ≥0∞, (C : ℝ≥0∞) * d ^ (r : ℝ)) (𝓝 0) (𝓝 0),
from ennreal.tendsto_const_mul_rpow_nhds_zero_of_pos ennreal.coe_ne_top h0,
rcases ennreal.nhds_zero_basis.mem_iff.1 (this (gt_mem_nhds εpos)) with ⟨δ, δ0, H⟩,
exact ⟨δ, δ0, λ x y hx hy h, (hf.edist_le hx hy).trans_lt (H h)⟩,
end
protected lemma continuous_on (hf : holder_on_with C r f s) (h0 : 0 < r) : continuous_on f s :=
(hf.uniform_continuous_on h0).continuous_on
protected lemma mono (hf : holder_on_with C r f s) (ht : t ⊆ s) : holder_on_with C r f t :=
λ x hx y hy, hf.edist_le (ht hx) (ht hy)
lemma ediam_image_le_of_le (hf : holder_on_with C r f s) {d : ℝ≥0∞} (hd : emetric.diam s ≤ d) :
emetric.diam (f '' s) ≤ C * d ^ (r : ℝ) :=
emetric.diam_image_le_iff.2 $ λ x hx y hy, hf.edist_le_of_le hx hy $
(emetric.edist_le_diam_of_mem hx hy).trans hd
lemma ediam_image_le (hf : holder_on_with C r f s) :
emetric.diam (f '' s) ≤ C * emetric.diam s ^ (r : ℝ) :=
hf.ediam_image_le_of_le le_rfl
lemma ediam_image_le_of_subset (hf : holder_on_with C r f s) (ht : t ⊆ s) :
emetric.diam (f '' t) ≤ C * emetric.diam t ^ (r : ℝ) :=
(hf.mono ht).ediam_image_le
lemma ediam_image_le_of_subset_of_le (hf : holder_on_with C r f s) (ht : t ⊆ s) {d : ℝ≥0∞}
(hd : emetric.diam t ≤ d) :
emetric.diam (f '' t) ≤ C * d ^ (r : ℝ) :=
(hf.mono ht).ediam_image_le_of_le hd
lemma ediam_image_inter_le_of_le (hf : holder_on_with C r f s) {d : ℝ≥0∞}
(hd : emetric.diam t ≤ d) :
emetric.diam (f '' (t ∩ s)) ≤ C * d ^ (r : ℝ) :=
hf.ediam_image_le_of_subset_of_le (inter_subset_right _ _) $
(emetric.diam_mono $ inter_subset_left _ _).trans hd
lemma ediam_image_inter_le (hf : holder_on_with C r f s) (t : set X) :
emetric.diam (f '' (t ∩ s)) ≤ C * emetric.diam t ^ (r : ℝ) :=
hf.ediam_image_inter_le_of_le le_rfl
end holder_on_with
namespace holder_with
variables {C r : ℝ≥0} {f : X → Y}
lemma edist_le (h : holder_with C r f) (x y : X) :
edist (f x) (f y) ≤ C * edist x y ^ (r : ℝ) :=
h x y
lemma edist_le_of_le (h : holder_with C r f) {x y : X} {d : ℝ≥0∞} (hd : edist x y ≤ d) :
edist (f x) (f y) ≤ C * d ^ (r : ℝ) :=
(h.holder_on_with univ).edist_le_of_le trivial trivial hd
lemma comp {Cg rg : ℝ≥0} {g : Y → Z} (hg : holder_with Cg rg g)
{Cf rf : ℝ≥0} {f : X → Y} (hf : holder_with Cf rf f) :
holder_with (Cg * Cf ^ (rg : ℝ)) (rg * rf) (g ∘ f) :=
(hg.holder_on_with univ).comp_holder_with hf (λ _, trivial)
lemma comp_holder_on_with {Cg rg : ℝ≥0} {g : Y → Z} (hg : holder_with Cg rg g)
{Cf rf : ℝ≥0} {f : X → Y} {s : set X} (hf : holder_on_with Cf rf f s) :
holder_on_with (Cg * Cf ^ (rg : ℝ)) (rg * rf) (g ∘ f) s :=
(hg.holder_on_with univ).comp hf (λ _ _, trivial)
/-- A Hölder continuous function is uniformly continuous -/
protected lemma uniform_continuous (hf : holder_with C r f) (h0 : 0 < r) : uniform_continuous f :=
uniform_continuous_on_univ.mp $ (hf.holder_on_with univ).uniform_continuous_on h0
protected lemma continuous (hf : holder_with C r f) (h0 : 0 < r) : continuous f :=
(hf.uniform_continuous h0).continuous
lemma ediam_image_le (hf : holder_with C r f) (s : set X) :
emetric.diam (f '' s) ≤ C * emetric.diam s ^ (r : ℝ) :=
emetric.diam_image_le_iff.2 $ λ x hx y hy, hf.edist_le_of_le $ emetric.edist_le_diam_of_mem hx hy
end holder_with
end emetric
section metric
variables [pseudo_metric_space X] [pseudo_metric_space Y] {C r : ℝ≥0} {f : X → Y}
namespace holder_with
lemma nndist_le_of_le (hf : holder_with C r f) {x y : X} {d : ℝ≥0} (hd : nndist x y ≤ d) :
nndist (f x) (f y) ≤ C * d ^ (r : ℝ) :=
begin
rw [← ennreal.coe_le_coe, ← edist_nndist, ennreal.coe_mul,
← ennreal.coe_rpow_of_nonneg _ r.coe_nonneg],
apply hf.edist_le_of_le,
rwa [edist_nndist, ennreal.coe_le_coe],
end
lemma nndist_le (hf : holder_with C r f) (x y : X) :
nndist (f x) (f y) ≤ C * nndist x y ^ (r : ℝ) :=
hf.nndist_le_of_le le_rfl
lemma dist_le_of_le (hf : holder_with C r f) {x y : X} {d : ℝ} (hd : dist x y ≤ d) :
dist (f x) (f y) ≤ C * d ^ (r : ℝ) :=
begin
lift d to ℝ≥0 using dist_nonneg.trans hd,
rw dist_nndist at hd ⊢,
norm_cast at hd ⊢,
exact hf.nndist_le_of_le hd
end
lemma dist_le (hf : holder_with C r f) (x y : X) :
dist (f x) (f y) ≤ C * dist x y ^ (r : ℝ) :=
hf.dist_le_of_le le_rfl
end holder_with
end metric
|
73723426fce7dd743b1de668b75cbe2d10b705d4 | d48477f6d2a5f434203448f53a910b09488d752b | /src/main.lean | ede3561e7cebfe2ef234a9c03cd1295eb3bf7d7b | [] | no_license | ADedecker/gauss | 2576868db8bf338155c8742f17cd06ba72091ee9 | d44d482d49d4755b1d238f3e8a67d22a605970a9 | refs/heads/master | 1,685,610,013,938 | 1,625,525,246,000 | 1,625,525,246,000 | 338,175,066 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,514 | lean | import measure_theory.integral_eq_improper
import analysis.special_functions.exp_log
import analysis.special_functions.trigonometric
import analysis.calculus.parametric_integral
import topology.uniform_space.compact_separated
noncomputable theory
open interval_integral set filter measure_theory
open_locale topological_space
def f : ℝ → ℝ := λ x, ∫ t in 0..x, real.exp (-t^2)
def g : ℝ → ℝ := λ x, ∫ t in 0..1, (real.exp (-(1+t^2)*x^2))/(1+t^2)
def h : ℝ → ℝ := λ x, g x + (f^2) x
lemma is_const_of_deriv_eq_zero {F : Type*}
[normed_group F] [normed_space ℝ F] {f : ℝ → F} (hf : differentiable ℝ f)
(hz : ∀ x, deriv f x = 0) : ∀ x y, f x = f y :=
begin
apply is_const_of_fderiv_eq_zero hf (λ x, _),
rw [← deriv_fderiv, hz x],
ext u,
simp
end
lemma exists_has_deriv_at_eq_slope_interval (f f' : ℝ → ℝ) {a b : ℝ}
(hab : a ≠ b) (hf : continuous_on f (interval a b))
(hff' : ∀ (x : ℝ), x ∈ Ioo (min a b) (max a b) → has_deriv_at f (f' x) x) :
(∃ (c : ℝ) (H : c ∈ Ioo (min a b) (max a b)), f' c = (f b - f a) / (b - a)) :=
begin
by_cases hlt : a < b;
[skip, have hlt : b < a := lt_of_le_of_ne (le_of_not_lt hlt) hab.symm];
rw interval at *;
[rw min_eq_left_of_lt hlt at *, rw min_eq_right_of_lt hlt at *];
[rw max_eq_right_of_lt hlt at *, rw max_eq_left_of_lt hlt at *];
convert exists_has_deriv_at_eq_slope f f' hlt hf hff',
conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] }
end
lemma has_deriv_at_parametric {a b : ℝ} (hab : a < b) (f f' : ℝ → ℝ → ℝ)
(hff' : ∀ x t, has_deriv_at (λ u, f u t) (f' x t) x)
(hf : continuous ↿f) (hf' : continuous ↿f') (x₀ : ℝ) :
has_deriv_at (λ x, ∫ t in a..b, f x t) (∫ t in a..b, f' x₀ t) x₀ :=
begin
refine has_deriv_within_at.has_deriv_at _ (Icc_mem_nhds (sub_one_lt x₀) (lt_add_one x₀)),
have compact_ab : is_compact (interval a b) := is_compact_Icc,
have compact_cd : is_compact (Icc (x₀-1) (x₀+1)) := is_compact_Icc,
have := (compact_cd.prod compact_ab).uniform_continuous_on_of_continuous hf'.continuous_on,
rw [has_deriv_within_at_iff_tendsto_slope, metric.tendsto_nhds_within_nhds],
intros ε hε,
rw metric.uniform_continuous_on_iff at this,
specialize this ((ε/2)/(b-a)) (div_pos (by linarith) (by linarith)),
rcases this with ⟨δ, hδ, this⟩,
use [δ, hδ],
rintros y₀ ⟨⟨hy₁, hy₂⟩, hy₃ : y₀ ≠ x₀⟩ hy₀x₀,
have key₁ := λ (t : ℝ), exists_has_deriv_at_eq_slope_interval (λ x, f x t) (λ x, f' x t) hy₃.symm
(@continuous_uncurry_right _ _ _ _ _ _ f t hf).continuous_on (λ x hx, hff' x t),
choose u hu using key₁,
have key₂ : ∀ t, dist (u t) x₀ < δ,
{ intro t,
rw [real.dist_eq, abs, max_lt_iff] at ⊢ hy₀x₀,
rcases hu t with ⟨⟨ht₁, ht₂⟩, _⟩,
by_cases hl : x₀ < y₀;
[skip, push_neg at hl];
[rw min_eq_left_of_lt hl at ht₁, rw min_eq_right hl at ht₁];
[rw max_eq_right_of_lt hl at ht₂, rw max_eq_left hl at ht₂];
split;
linarith },
have key₃ : Ioo (min x₀ y₀) (max x₀ y₀) ⊆ Icc (x₀-1) (x₀+1),
{ by_cases hl : x₀ < y₀;
[skip, push_neg at hl];
[rw min_eq_left_of_lt hl, rw min_eq_right hl];
[rw max_eq_right_of_lt hl, rw max_eq_left hl];
rintros a ⟨ha₁, ha₂⟩;
split;
linarith },
have key₄ : ∀ x, continuous (f x) := λ x, @continuous_uncurry_left _ _ _ _ _ _ f x hf,
have key₅ : continuous (λ (t : ℝ), (y₀ - x₀)⁻¹ * (f y₀ t - f x₀ t)) :=
continuous_const.mul ((key₄ y₀).sub (key₄ x₀)),
have key₅' : continuous (λ (t : ℝ), (y₀ - x₀)⁻¹ • (f y₀ t - f x₀ t)) := key₅,
have key₆ : continuous (λ (t : ℝ), f' (u t) t),
{ convert key₅,
ext t,
rw [(hu t).2, div_eq_mul_inv, mul_comm] },
rw [← integral_sub ((key₄ y₀).interval_integrable _ _) ((key₄ x₀).interval_integrable _ _),
← interval_integral.integral_smul, real.dist_eq,
← integral_sub (key₅'.interval_integrable _ _)
((@continuous_uncurry_left _ _ _ _ _ _ f' x₀ hf').interval_integrable _ _)],
conv in (_ • _)
{ dsimp, rw ← div_eq_inv_mul, rw ← (hu _).2 },
calc abs (∫ (t : ℝ) in a..b, f' (u t) t - f' x₀ t)
≤ abs (∫ (t : ℝ) in a..b, abs (f' (u t) t - f' x₀ t)) :
by rw ← real.norm_eq_abs; exact norm_integral_le_abs_integral_norm
... = abs (∫ (t : ℝ) in Ioc a b, abs (f' (u t) t - f' x₀ t)) :
by repeat {conv in (interval_integral _ _ _ _) { rw integral_of_le hab.le }}
... = (∫ (t : ℝ) in Ioc a b, abs (f' (u t) t - f' x₀ t)) :
by rw abs_eq_self; exact integral_nonneg (λ x, abs_nonneg _)
... ≤ (∫ (t : ℝ) in Ioc a b, (ε/2)/(b-a)) :
begin
have meas_ab : measurable_set (Ioc a b) := measurable_set_Ioc,
rw ← integral_indicator meas_ab,
rw ← integral_indicator meas_ab,
refine integral_mono _ _ (λ t, _),
{ rw integrable_indicator_iff meas_ab,
refine ((continuous_abs.comp _).integrable_on_compact is_compact_Icc).mono_set Ioc_subset_Icc_self,
refine key₆.sub (@continuous_uncurry_left _ _ _ _ _ _ f' x₀ hf') },
{ rw integrable_indicator_iff meas_ab,
refine (continuous.integrable_on_compact compact_Icc _).mono_set Ioc_subset_Icc_self,
simp only [continuous_const]},
by_cases ht : t ∈ Ioc a b,
{ have := le_of_lt (this (u t, t) (x₀, t) _ _ _),
{ simpa only [ht, indicator_of_mem] using this},
{ refine ⟨key₃ (hu t).1, Icc_subset_interval $ Ioc_subset_Icc_self ht⟩, },
{ exact ⟨⟨(sub_one_lt x₀).le, (lt_add_one x₀).le⟩,
Icc_subset_interval $ Ioc_subset_Icc_self ht⟩ },
{ rw [prod.dist_eq, max_lt_iff],
refine ⟨key₂ t, (dist_self t).symm ▸ hδ⟩ } },
{ simp only [ht, indicator_of_not_mem, not_false_iff]},
end
... = (b-a) * (ε/2/(b-a)) :
by rw [set_integral_const, real.volume_Ioc,
ennreal.to_real_of_real (show 0 ≤ b - a, by linarith),
smul_eq_mul]
... = ε/2 : mul_div_cancel' (ε/2) (show b - a ≠ 0, by linarith)
... < ε : by linarith [hε],
all_goals {apply_instance}
end
lemma continuous_gauss : continuous (λ x, real.exp (-x^2)) := by continuity; exact complex.continuous_exp
lemma has_deriv_at_f (x : ℝ) : has_deriv_at f (real.exp (-x^2)) x :=
integral_has_deriv_at_right (continuous_gauss.interval_integrable _ _)
continuous_gauss.measurable.measurable_at_filter continuous_gauss.continuous_at
lemma has_deriv_at_f_square (x : ℝ) : has_deriv_at (f^2) (2 * real.exp (-x^2) * ∫ t in 0..x, real.exp (-t^2)) x :=
begin
convert has_deriv_at.comp x (has_deriv_at_pow 2 _) (has_deriv_at_f x) using 1,
norm_cast,
ring
end
lemma has_deriv_at_g (x₀ : ℝ) : has_deriv_at g (∫ t in 0..1, -2 * x₀ * real.exp (-(1+t^2)*x₀^2)) x₀ :=
begin
have key₁ : continuous (λ (t : ℝ), 1 + t^2) := by continuity,
have key₂ : continuous ↿(λ x t, real.exp (-(1+t^2) * x^2)) :=
real.continuous_exp.comp ((key₁.comp continuous_snd).neg.mul
((continuous_pow 2).comp continuous_fst)),
apply has_deriv_at_parametric (zero_lt_one),
{ intros x t,
have step₁ : has_deriv_at (λ u, -(1 + t^2) * u^2) (-(1 + t^2) * 2 * x) x,
{ convert (has_deriv_at_pow 2 x).const_mul (-(1 + t ^ 2)) using 1,
norm_cast,
ring },
have step₂ : has_deriv_at (λ u, real.exp (-(1 + t^2) * u^2))
(-(1 + t^2) * 2 * x * real.exp (-(1 + t^2) * x^2)) x,
{ rw mul_comm,
exact has_deriv_at.comp x (real.has_deriv_at_exp _) step₁ },
conv in (_ / _) { rw div_eq_mul_inv },
convert step₂.mul_const _ using 1,
conv_rhs {rw mul_comm, rw ← mul_assoc, rw ← mul_assoc, rw ← mul_assoc,
rw mul_neg_eq_neg_mul_symm,
rw inv_mul_cancel (show 1 + t^2 ≠ 0, by linarith [pow_two_nonneg t]) },
ring },
{ exact key₂.div (key₁.comp continuous_snd) (λ ⟨x, t⟩, by linarith [pow_two_nonneg t]) },
{ exact (continuous_const.mul continuous_fst).mul key₂, },
end
lemma key1 : ∀ x : ℝ, ∀ t ∈ (set.interval 0 1 : set ℝ),
has_deriv_at ((λ (u : ℝ), ∫ (t : ℝ) in 0..u, real.exp (-t ^ 2)) ∘ λ (u : ℝ), u * x) (real.exp (-(t * x) ^ 2) * x) t :=
begin
intros x t ht,
apply has_deriv_at.comp _ (has_deriv_at_f _),
convert (has_deriv_at_id t).mul_const x,
ring
end
lemma has_deriv_at_h : ∀ x, has_deriv_at h 0 x :=
begin
intros x,
rw h,
convert ← (has_deriv_at_g x).add (has_deriv_at_f_square x),
rw add_eq_zero_iff_eq_neg,
calc ∫ (t : ℝ) in 0..1, (-2) * x * real.exp (-(1 + t ^ 2) * x ^ 2)
= ∫ (t : ℝ) in 0..1, (-2) * x * real.exp (-(t * x) ^ 2 + -x ^ 2) :
by conv in (-(1+_^2)*x^2) { ring_nf, rw [← mul_pow, mul_comm, sub_eq_add_neg] }
... = ∫ t in 0..1, (-2) * x * (real.exp (-x ^ 2) * real.exp (-(t * x) ^ 2)) :
by conv in (real.exp _) { rw real.exp_add, rw mul_comm }
... = ∫ t in 0..1, (-2 * real.exp (-x ^ 2)) * (real.exp (-(t * x) ^ 2) * x) :
by congr; ext t; ring
... = ∫ t in 0..1, (-2 * real.exp (-x ^ 2)) • (real.exp (-(t * x) ^ 2) * x) :
by congr; ext t; rw smul_eq_mul
... = (-2 * real.exp (-x ^ 2)) • ∫ t in 0..1, (real.exp (-(t * x) ^ 2) * x) :
integral_smul _
... = (-2 * real.exp (-x ^ 2)) * ∫ t in 0..1, (real.exp (-(t * x) ^ 2) * x) :
by rw smul_eq_mul
... = (-2 * real.exp (-x ^ 2)) *
( ((λ u, ∫ t in 0..u, real.exp (-t ^ 2)) ∘ (λ u, u * x)) 1
- ((λ u, ∫ t in 0..u, real.exp (-t ^ 2)) ∘ (λ u, u * x)) 0 ) :
begin
congr,
refine integral_eq_sub_of_has_deriv_at (key1 x) (continuous.continuous_on _),
continuity
end
... = (-2 * real.exp (-x ^ 2)) * ∫ t in 0..x, real.exp (-t ^ 2) : by simp
... = -(2 * real.exp (-x ^ 2) * ∫ t in 0..x, real.exp (-t ^ 2)) : by ring
end
lemma h_zero : h 0 = real.pi / 4 :=
begin
change (∫ t in 0..1, real.exp (-(1 + t^2) * 0^2) / (1 + t^2)) +
(∫ (t : ℝ) in 0..0, real.exp (-t^2))^2 = real.pi / 4,
rw [integral_same, zero_pow zero_lt_two, add_zero],
conv_lhs {congr, funext, rw mul_zero, rw real.exp_zero},
convert integral_eq_sub_of_has_deriv_at (λ t _, t.has_deriv_at_arctan)
(continuous_const.div _ _).continuous_on,
{ rw [real.arctan_one, real.arctan_zero, sub_zero] },
{ continuity },
{ intro t,
linarith [pow_two_nonneg t] }
end
lemma h_eq : h = (λ x, real.pi / 4) :=
funext $ λ x, h_zero ▸ (is_const_of_deriv_eq_zero (λ t, (has_deriv_at_h t).differentiable_at)
(λ t, (has_deriv_at_h t).deriv) x 0)
lemma g_le_key (x : ℝ) (hx : 1 ≤ x) :
(λ t, (real.exp (-(1+t^2)*x^2))/(1+t^2)) ≤ (λ t, real.exp (-x)) :=
assume t,
have key₁ : 1 ≤ 1 + t^2,
from (le_add_iff_nonneg_right 1).mpr (pow_two_nonneg t),
calc (real.exp (-(1+t^2)*x^2))/(1+t^2)
≤ (real.exp (-(1+t^2)*x^2))/1 : div_le_div_of_le_left
(real.exp_pos _).le zero_lt_one key₁
... = real.exp (-(1+t^2)*x^2) : div_one _
... = real.exp ((1+t^2)*(-x^2)) : congr_arg real.exp (by ring)
... ≤ real.exp (1*(-x^2)) : real.exp_monotone
(mul_mono_nonpos (neg_nonpos.mpr $ pow_two_nonneg x) key₁)
... = real.exp (-x^2) : by rw one_mul
... = real.exp (x*(-x)) : by ring_nf
... ≤ real.exp (1*(-x)) : real.exp_monotone
(mul_mono_nonpos (neg_nonpos.mpr $ zero_le_one.trans hx) hx)
... = real.exp (-x) : by rw one_mul
lemma g_le : g ≤ᶠ[at_top] (λ x, real.exp (-x)) :=
begin
dsimp [g],
refine ((eventually_ge_at_top 1).mono $ λ x hx, _),
convert interval_integral.integral_mono (zero_le_one : (0 : ℝ) ≤ 1) _ _ (g_le_key x hx),
{ rw interval_integral.integral_const,
simp },
{ refine (continuous.div _ _ _).interval_integrable 0 1,
{ continuity },
{ continuity },
{ intro x, linarith [pow_two_nonneg x] } },
{ exact continuous.interval_integrable (by continuity) 0 1 },
end
lemma g_tendsto : tendsto g at_top (𝓝 0) :=
begin
refine tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds
(real.tendsto_exp_at_bot.comp tendsto_neg_at_top_at_bot)
(eventually_of_forall $ λ x, _) g_le,
dsimp [g],
rw integral_of_le,
{ refine integral_nonneg (λ t, _),
exact div_nonneg (real.exp_pos _).le
(zero_le_one.trans $ (le_add_iff_nonneg_right 1).mpr (pow_two_nonneg t)) },
{ exact zero_le_one }
end
lemma f_square_tendsto : tendsto (f^2) at_top (𝓝 $ real.pi/4) :=
begin
have : f^2 = h - g,
{ ext, simp [h] },
rw [this, ← sub_zero (real.pi/4), h_eq],
exact tendsto_const_nhds.sub g_tendsto
end
lemma f_tendsto : tendsto f at_top (𝓝 $ real.pi.sqrt / 2) :=
begin
rw [← real.sqrt_sq zero_le_two, ← real.sqrt_div real.pi_pos.le],
norm_num,
refine f_square_tendsto.sqrt.congr' _,
refine (eventually_ge_at_top 0).mono (λ x hx, real.sqrt_sq _),
dsimp [f],
rw integral_of_le hx,
refine integral_nonneg (λ t, (real.exp_pos _).le),
end
lemma tendsto_gauss_integral_symm_interval :
tendsto (λ x, ∫ t in (-x)..x, real.exp (-t^2)) at_top (𝓝 real.pi.sqrt) :=
begin
convert ← tendsto.const_mul 2 f_tendsto,
{ ext x,
rw [two_mul, ← integral_add_adjacent_intervals
(continuous_gauss.interval_integrable (-x) 0)
(continuous_gauss.interval_integrable 0 x)],
refine congr_arg2 (+) _ rfl,
conv in (real.exp _) {rw ← neg_sq, change (λ t, real.exp (-t^2)) (-t)},
rw [integral_comp_neg (λ t, real.exp (-t^2)), neg_zero],
all_goals {apply_instance} },
{ linarith }
end
lemma gauss_integrable : integrable (λ x, real.exp (-x^2)) :=
begin
refine integrable_of_interval_integral_norm_tendsto at_top_countably_generated_of_archimedean
(continuous_gauss.ae_measurable _) real.pi.sqrt
(λ i, continuous_gauss.integrable_on_Icc.mono_set Ioc_subset_Icc_self)
tendsto_neg_at_top_at_bot tendsto_id _,
conv in (norm _) {rw real.norm_of_nonneg (-x^2).exp_pos.le},
exact tendsto_gauss_integral_symm_interval
end
lemma gauss_integral : ∫ x : ℝ, real.exp (-x^2) = real.pi.sqrt :=
begin
have := interval_integral_tendsto_integral at_top_countably_generated_of_archimedean
(continuous_gauss.ae_measurable _) gauss_integrable tendsto_neg_at_top_at_bot tendsto_id,
exact tendsto_nhds_unique this tendsto_gauss_integral_symm_interval,
end |
092781e577bc1ac6397069fa0e504b8289bc8ce7 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/fin_cases.lean | 1c08c6aa61db02e16959f8c078378a7060ae6891 | [
"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 | 5,845 | 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 data.fintype.basic
import tactic.norm_num
/-!
# Case bash
This file provides the tactic `fin_cases`. `fin_cases x` performs case analysis on `x`, that is
creates one goal for each possible value of `x`, where either:
* `x : α`, where `[fintype α]`
* `x ∈ A`, where `A : finset α`, `A : multiset α` or `A : list α`.
-/
namespace tactic
open expr
open conv.interactive
/-- Checks that the expression looks like `x ∈ A` for `A : finset α`, `multiset α` or `A : list α`,
and returns the type α. -/
meta def guard_mem_fin (e : expr) : tactic expr :=
do t ← infer_type e,
α ← mk_mvar,
to_expr ``(_ ∈ (_ : finset %%α)) tt ff >>= unify t <|>
to_expr ``(_ ∈ (_ : multiset %%α)) tt ff >>= unify t <|>
to_expr ``(_ ∈ (_ : list %%α)) tt ff >>= unify t,
instantiate_mvars α
/--
`expr_list_to_list_expr` converts an `expr` of type `list α`
to a list of `expr`s each with type `α`.
TODO: this should be moved, and possibly duplicates an existing definition.
-/
meta def expr_list_to_list_expr : Π (e : expr), tactic (list expr)
| `(list.cons %%h %%t) := list.cons h <$> expr_list_to_list_expr t
| `([]) := return []
| _ := failed
private meta def fin_cases_at_aux : Π (with_list : list expr) (e : expr), tactic unit
| with_list e :=
(do
result ← cases_core e,
match result with
-- We have a goal with an equation `s`, and a second goal with a smaller `e : x ∈ _`.
| [(_, [s], _), (_, [e], _)] :=
do let sn := local_pp_name s,
ng ← num_goals,
-- tidy up the new value
match with_list.nth 0 with
-- If an explicit value was specified via the `with` keyword, use that.
| (some h) := tactic.interactive.conv (some sn) none
(to_rhs >> conv.interactive.change (to_pexpr h))
-- Otherwise, call `norm_num`. We let `norm_num` unfold `max` and `min`
-- because it's helpful for the `interval_cases` tactic.
| _ := try $ tactic.interactive.conv (some sn) none $
to_rhs >> conv.interactive.norm_num
[simp_arg_type.expr ``(max_def'), simp_arg_type.expr ``(min_def)]
end,
s ← get_local sn,
try `[subst %%s],
ng' ← num_goals,
when (ng = ng') (rotate_left 1),
fin_cases_at_aux with_list.tail e
-- No cases; we're done.
| [] := skip
| _ := failed
end)
/--
`fin_cases_at with_list e` performs case analysis on `e : α`, where `α` is a fintype.
The optional list of expressions `with_list` provides descriptions for the cases of `e`,
for example, to display nats as `n.succ` instead of `n+1`.
These should be defeq to and in the same order as the terms in the enumeration of `α`.
-/
meta def fin_cases_at (nm : option name) : Π (with_list : option pexpr) (e : expr), tactic unit
| with_list e := focus1 $
do ty ← try_core $ guard_mem_fin e,
match ty with
| none := -- Deal with `x : A`, where `[fintype A]` is available:
(do
ty ← infer_type e,
i ← to_expr ``(fintype %%ty) >>= mk_instance <|> fail "Failed to find `fintype` instance.",
t ← to_expr ``(%%e ∈ @fintype.elems %%ty %%i),
v ← to_expr ``(@fintype.complete %%ty %%i %%e),
h ← assertv (nm.get_or_else `this) t v,
fin_cases_at with_list h)
| (some ty) := -- Deal with `x ∈ A` hypotheses:
(do
with_list ← match with_list with
| (some e) := do e ← to_expr ``(%%e : list %%ty), expr_list_to_list_expr e
| none := return []
end,
fin_cases_at_aux with_list e)
end
namespace interactive
setup_tactic_parser
private meta def hyp := tk "*" *> return none <|> some <$> ident
/--
`fin_cases h` performs case analysis on a hypothesis of the form
`h : A`, where `[fintype A]` is available, or
`h : a ∈ A`, where `A : finset X`, `A : multiset X` or `A : list X`.
`fin_cases *` performs case analysis on all suitable hypotheses.
As an example, in
```
example (f : ℕ → Prop) (p : fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val :=
begin
fin_cases *; simp,
all_goals { assumption }
end
```
after `fin_cases p; simp`, there are three goals, `f 0`, `f 1`, and `f 2`.
`fin_cases h with l` takes a list of descriptions for the cases of `h`.
These should be definitionally equal to and in the same order as the
default enumeration of the cases.
For example,
```
example (x y : ℕ) (h : x ∈ [1, 2]) : x = y :=
begin
fin_cases h with [1, 1+1],
end
```
produces two cases: `1 = y` and `1 + 1 = y`.
When using `fin_cases a` on data `a` defined with `let`,
the tactic will not be able to clear the variable `a`,
and will instead produce hypotheses `this : a = ...`.
These hypotheses can be given a name using `fin_cases a using ha`.
For example,
```
example (f : ℕ → fin 3) : true :=
begin
let a := f 3,
fin_cases a using ha,
end
```
produces three goals with hypotheses
`ha : a = 0`, `ha : a = 1`, and `ha : a = 2`.
-/
meta def fin_cases :
parse hyp → parse (tk "with" *> texpr)? → parse (tk "using" *> ident)? → tactic unit
| none none nm := do
ctx ← local_context,
ctx.mfirst (fin_cases_at nm none) <|>
fail ("No hypothesis of the forms `x ∈ A`, where " ++
"`A : finset X`, `A : list X`, or `A : multiset X`, or `x : A`, with `[fintype A]`.")
| none (some _) _ := fail "Specify a single hypothesis when using a `with` argument."
| (some n) with_list nm :=
do
h ← get_local n,
fin_cases_at nm with_list h
end interactive
add_tactic_doc
{ name := "fin_cases",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fin_cases],
tags := ["case bashing"] }
end tactic
|
cf72e181dcb851a80fa6e8486401cbe099448985 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/qexpr1.lean | 047e1033c04569737b9893c2f2cb37f7c1959031 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 318 | lean | open tactic
set_option pp.all true
example (a b c : nat) : true :=
by do
x ← to_expr `(a + b),
trace x, infer_type x >>= trace,
constructor
example (a b c : nat) : true :=
by do
x ← get_local `a,
x ← mk_app `nat.succ [x],
r ← to_expr `(%%x + b),
trace r, infer_type r >>= trace,
constructor
|
bef2ac5c7b6a41308bdd956942ef27b6f1f1fe7a | 9b9a16fa2cb737daee6b2785474678b6fa91d6d4 | /src/data/set/intervals.lean | 2767598a0eaf155d83db1c12f5e0b715c3042d85 | [
"Apache-2.0"
] | permissive | johoelzl/mathlib | 253f46daa30b644d011e8e119025b01ad69735c4 | 592e3c7a2dfbd5826919b4605559d35d4d75938f | refs/heads/master | 1,625,657,216,488 | 1,551,374,946,000 | 1,551,374,946,000 | 98,915,829 | 0 | 0 | Apache-2.0 | 1,522,917,267,000 | 1,501,524,499,000 | Lean | UTF-8 | Lean | false | false | 7,050 | 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
Intervals
Naming conventions:
`i`: infinite
`o`: open
`c`: closed
Each interval has the name `I` + letter for left side + letter for right side
TODO: This is just the beginning; a lot of intervals and rules are missing
-/
import data.set.lattice algebra.order algebra.order_functions
namespace set
open set
section intervals
variables {α : Type*} [preorder α] {a a₁ a₂ b b₁ b₂ x : α}
/-- Left-open right-open interval -/
def Ioo (a b : α) := {x | a < x ∧ x < b}
/-- Left-closed right-open interval -/
def Ico (a b : α) := {x | a ≤ x ∧ x < b}
/-- Left-closed right-closed interval -/
def Icc (a b : α) := {x | a ≤ x ∧ x ≤ b}
/-- Left-infinite right-open interval -/
def Iio (a : α) := {x | x < a}
@[simp] lemma mem_Ioo : x ∈ Ioo a b ↔ a < x ∧ x < b := iff.rfl
@[simp] lemma mem_Ico : x ∈ Ico a b ↔ a ≤ x ∧ x < b := iff.rfl
@[simp] lemma mem_Icc : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := iff.rfl
@[simp] lemma mem_Iio : x ∈ Iio b ↔ x < b := iff.rfl
@[simp] lemma Ioo_eq_empty (h : b ≤ a) : Ioo a b = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_trans h₁ h₂) h
@[simp] lemma Ico_eq_empty (h : b ≤ a) : Ico a b = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_of_le_of_lt h₁ h₂) h
@[simp] lemma Icc_eq_empty (h : b < a) : Icc a b = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₁ h₂) h
@[simp] lemma Ioo_self (a : α) : Ioo a a = ∅ := Ioo_eq_empty $ le_refl _
@[simp] lemma Ico_self (a : α) : Ico a a = ∅ := Ico_eq_empty $ le_refl _
lemma Iio_ne_empty [no_bot_order α] (a : α) : Iio a ≠ ∅ :=
ne_empty_iff_exists_mem.2 (no_bot a)
lemma Ioo_subset_Ioo (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) :
Ioo a₁ b₁ ⊆ Ioo a₂ b₂ :=
λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩
lemma Ioo_subset_Ioo_left (h : a₁ ≤ a₂) : Ioo a₂ b ⊆ Ioo a₁ b :=
Ioo_subset_Ioo h (le_refl _)
lemma Ioo_subset_Ioo_right (h : b₁ ≤ b₂) : Ioo a b₁ ⊆ Ioo a b₂ :=
Ioo_subset_Ioo (le_refl _) h
lemma Ico_subset_Ico (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) :
Ico a₁ b₁ ⊆ Ico a₂ b₂ :=
λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩
lemma Ico_subset_Ico_left (h : a₁ ≤ a₂) : Ico a₂ b ⊆ Ico a₁ b :=
Ico_subset_Ico h (le_refl _)
lemma Ico_subset_Ico_right (h : b₁ ≤ b₂) : Ico a b₁ ⊆ Ico a b₂ :=
Ico_subset_Ico (le_refl _) h
lemma Icc_subset_Icc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) :
Icc a₁ b₁ ⊆ Icc a₂ b₂ :=
λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, le_trans hx₂ h₂⟩
lemma Icc_subset_Icc_left (h : a₁ ≤ a₂) : Icc a₂ b ⊆ Icc a₁ b :=
Icc_subset_Icc h (le_refl _)
lemma Icc_subset_Icc_right (h : b₁ ≤ b₂) : Icc a b₁ ⊆ Icc a b₂ :=
Icc_subset_Icc (le_refl _) h
lemma Ico_subset_Ioo_left (h₁ : a₁ < a₂) : Ico a₂ b ⊆ Ioo a₁ b :=
λ x, and.imp_left $ lt_of_lt_of_le h₁
lemma Icc_subset_Ico_right (h₁ : b₁ < b₂) : Icc a b₁ ⊆ Ico a b₂ :=
λ x, and.imp_right $ λ h₂, lt_of_le_of_lt h₂ h₁
lemma Ioo_subset_Ico_self : Ioo a b ⊆ Ico a b := λ x, and.imp_left le_of_lt
lemma Ico_subset_Icc_self : Ico a b ⊆ Icc a b := λ x, and.imp_right le_of_lt
lemma Ioo_subset_Icc_self : Ioo a b ⊆ Icc a b :=
subset.trans Ioo_subset_Ico_self Ico_subset_Icc_self
lemma Ico_subset_Iio_self : Ioo a b ⊆ Iio b := λ x, and.right
end intervals
section partial_order
variables {α : Type*} [partial_order α] {a b : α}
@[simp] lemma Icc_self (a : α) : Icc a a = {a} :=
set.ext $ by simp [Icc, le_antisymm_iff, and_comm]
lemma Ico_diff_Ioo_eq_singleton (h : a < b) : Ico a b \ Ioo a b = {a} :=
set.ext $ λ x, begin
simp, split,
{ rintro ⟨⟨ax, xb⟩, h⟩,
exact eq.symm (classical.by_contradiction
(λ ne, h (lt_of_le_of_ne ax ne) xb)) },
{ rintro rfl, exact ⟨⟨le_refl _, h⟩, (lt_irrefl x).elim⟩ }
end
lemma Icc_diff_Ico_eq_singleton (h : a ≤ b) : Icc a b \ Ico a b = {b} :=
set.ext $ λ x, begin
simp, split,
{ rintro ⟨⟨ax, xb⟩, h⟩,
exact classical.by_contradiction
(λ ne, h ax (lt_of_le_of_ne xb ne)) },
{ rintro rfl, exact ⟨⟨h, le_refl _⟩, λ _, lt_irrefl x⟩ }
end
end partial_order
section linear_order
variables {α : Type*} [linear_order α] {a a₁ a₂ b b₁ b₂ : α}
lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ b ≤ a :=
⟨λ eq, le_of_not_lt $ λ h,
let ⟨x, h₁, h₂⟩ := dense h in
eq_empty_iff_forall_not_mem.1 eq x ⟨h₁, h₂⟩,
Ioo_eq_empty⟩
lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ b ≤ a :=
⟨λ eq, le_of_not_lt $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩,
Ico_eq_empty⟩
lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ b < a :=
⟨λ eq, lt_of_not_ge $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩,
Icc_eq_empty⟩
lemma Ico_subset_Ico_iff (h₁ : a₁ < b₁) :
Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ :=
⟨λ h,
have a₂ ≤ a₁ ∧ a₁ < b₂ := h ⟨le_refl _, h₁⟩,
⟨this.1, le_of_not_lt $ λ h', lt_irrefl b₂ (h ⟨le_of_lt this.2, h'⟩).2⟩,
λ ⟨h₁, h₂⟩, Ico_subset_Ico h₁ h₂⟩
lemma Ioo_subset_Ioo_iff [densely_ordered α] (h₁ : a₁ < b₁) :
Ioo a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ :=
⟨λ h, begin
rcases dense h₁ with ⟨x, xa, xb⟩,
split; refine le_of_not_lt (λ h', _),
{ have ab := lt_trans (h ⟨xa, xb⟩).1 xb,
exact lt_irrefl _ (h ⟨h', ab⟩).1 },
{ have ab := lt_trans xa (h ⟨xa, xb⟩).2,
exact lt_irrefl _ (h ⟨ab, h'⟩).2 }
end, λ ⟨h₁, h₂⟩, Ioo_subset_Ioo h₁ h₂⟩
lemma Ico_eq_Ico_iff (h : a₁ < b₁ ∨ a₂ < b₂) : Ico a₁ b₁ = Ico a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ :=
⟨λ e, begin
simp [subset.antisymm_iff] at e, simp [le_antisymm_iff],
cases h; simp [Ico_subset_Ico_iff h] at e;
[ rcases e with ⟨⟨h₁, h₂⟩, e'⟩, rcases e with ⟨e', ⟨h₁, h₂⟩⟩ ];
have := (Ico_subset_Ico_iff (lt_of_le_of_lt h₁ $ lt_of_lt_of_le h h₂)).1 e';
tauto
end, λ ⟨h₁, h₂⟩, by rw [h₁, h₂]⟩
end linear_order
section decidable_linear_order
variables {α : Type*} [decidable_linear_order α] {a a₁ a₂ b b₁ b₂ : α}
@[simp] lemma Ico_diff_Iio {a b c : α} : Ico a b \ Iio c = Ico (max a c) b :=
set.ext $ by simp [Ico, Iio, iff_def, max_le_iff] {contextual:=tt}
@[simp] lemma Ico_inter_Iio {a b c : α} : Ico a b ∩ Iio c = Ico a (min b c) :=
set.ext $ by simp [Ico, Iio, iff_def, lt_min_iff] {contextual:=tt}
lemma Ioo_inter_Ioo {a b c d : α} : Ioo a b ∩ Ioo c d = Ioo (max a c) (min b d) :=
set.ext $ by simp [iff_def, Ioo, lt_min_iff, max_lt_iff] {contextual := tt}
end decidable_linear_order
end set |
b81c87258c4b9cfef0a36011efbac98e4ebda04e | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebra/is_prime_pow.lean | 73a651a3d1a766e8f6e19a88d54c790e30fe1ffb | [
"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 | 9,838 | lean | /-
Copyright (c) 2022 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import algebra.associated
import data.nat.factorization
import number_theory.divisors
/-!
# Prime powers
This file deals with prime powers: numbers which are positive integer powers of a single prime.
-/
variables {R : Type*} [comm_monoid_with_zero R] (n p : R) (k : ℕ)
/-- `n` is a prime power if there is a prime `p` and a positive natural `k` such that `n` can be
written as `p^k`. -/
def is_prime_pow : Prop :=
∃ (p : R) (k : ℕ), prime p ∧ 0 < k ∧ p ^ k = n
lemma is_prime_pow_def :
is_prime_pow n ↔ ∃ (p : R) (k : ℕ), prime p ∧ 0 < k ∧ p ^ k = n := iff.rfl
/-- An equivalent definition for prime powers: `n` is a prime power iff there is a prime `p` and a
natural `k` such that `n` can be written as `p^(k+1)`. -/
lemma is_prime_pow_iff_pow_succ :
is_prime_pow n ↔ ∃ (p : R) (k : ℕ), prime p ∧ p ^ (k + 1) = n :=
(is_prime_pow_def _).trans
⟨λ ⟨p, k, hp, hk, hn⟩, ⟨_, _, hp, by rwa [nat.sub_add_cancel hk]⟩,
λ ⟨p, k, hp, hn⟩, ⟨_, _, hp, nat.succ_pos', hn⟩⟩
lemma not_is_prime_pow_zero [no_zero_divisors R] :
¬ is_prime_pow (0 : R) :=
begin
simp only [is_prime_pow_def, not_exists, not_and', and_imp],
intros x n hn hx,
rw pow_eq_zero hx,
simp,
end
lemma not_is_prime_pow_one : ¬ is_prime_pow (1 : R) :=
begin
simp only [is_prime_pow_def, not_exists, not_and', and_imp],
intros x n hn hx ht,
exact ht.not_unit (is_unit_of_pow_eq_one x n hx hn),
end
lemma prime.is_prime_pow {p : R} (hp : prime p) : is_prime_pow p :=
⟨p, 1, hp, zero_lt_one, by simp⟩
lemma is_prime_pow.pow {n : R} (hn : is_prime_pow n)
{k : ℕ} (hk : k ≠ 0) : is_prime_pow (n ^ k) :=
let ⟨p, k', hp, hk', hn⟩ := hn in ⟨p, k * k', hp, mul_pos hk.bot_lt hk', by rw [pow_mul', hn]⟩
theorem is_prime_pow.ne_zero [no_zero_divisors R] {n : R} (h : is_prime_pow n) : n ≠ 0 :=
λ t, eq.rec not_is_prime_pow_zero t.symm h
lemma is_prime_pow.ne_one {n : R} (h : is_prime_pow n) : n ≠ 1 :=
λ t, eq.rec not_is_prime_pow_one t.symm h
section unique_units
lemma eq_of_prime_pow_eq {R : Type*} [cancel_comm_monoid_with_zero R] [unique Rˣ] {p₁ p₂ : R}
{k₁ k₂ : ℕ} (hp₁ : prime p₁) (hp₂ : prime p₂) (hk₁ : 0 < k₁) (h : p₁ ^ k₁ = p₂ ^ k₂) :
p₁ = p₂ :=
by { rw [←associated_iff_eq] at h ⊢, apply h.of_pow_associated_of_prime hp₁ hp₂ hk₁ }
lemma eq_of_prime_pow_eq' {R : Type*} [cancel_comm_monoid_with_zero R] [unique Rˣ] {p₁ p₂ : R}
{k₁ k₂ : ℕ} (hp₁ : prime p₁) (hp₂ : prime p₂) (hk₁ : 0 < k₂) (h : p₁ ^ k₁ = p₂ ^ k₂) :
p₁ = p₂ :=
by { rw [←associated_iff_eq] at h ⊢, apply h.of_pow_associated_of_prime' hp₁ hp₂ hk₁ }
end unique_units
section nat
lemma is_prime_pow_nat_iff (n : ℕ) :
is_prime_pow n ↔ ∃ (p k : ℕ), nat.prime p ∧ 0 < k ∧ p ^ k = n :=
by simp only [is_prime_pow_def, nat.prime_iff]
lemma nat.prime.is_prime_pow {p : ℕ} (hp : p.prime) : is_prime_pow p :=
(nat.prime_iff.mp hp).is_prime_pow
lemma is_prime_pow_nat_iff_bounded (n : ℕ) :
is_prime_pow n ↔ ∃ (p : ℕ), p ≤ n ∧ ∃ (k : ℕ), k ≤ n ∧ p.prime ∧ 0 < k ∧ p ^ k = n :=
begin
rw is_prime_pow_nat_iff,
refine iff.symm ⟨λ ⟨p, _, k, _, hp, hk, hn⟩, ⟨p, k, hp, hk, hn⟩, _⟩,
rintro ⟨p, k, hp, hk, rfl⟩,
refine ⟨p, _, k, (nat.lt_pow_self hp.one_lt _).le, hp, hk, rfl⟩,
simpa using nat.pow_le_pow_of_le_right hp.pos hk,
end
instance {n : ℕ} : decidable (is_prime_pow n) :=
decidable_of_iff' _ (is_prime_pow_nat_iff_bounded n)
lemma is_prime_pow.min_fac_pow_factorization_eq {n : ℕ} (hn : is_prime_pow n) :
n.min_fac ^ n.factorization n.min_fac = n :=
begin
obtain ⟨p, k, hp, hk, rfl⟩ := hn,
rw ←nat.prime_iff at hp,
rw [hp.pow_min_fac hk.ne', hp.factorization_pow, finsupp.single_eq_same],
end
lemma is_prime_pow_of_min_fac_pow_factorization_eq {n : ℕ}
(h : n.min_fac ^ n.factorization n.min_fac = n) (hn : n ≠ 1) :
is_prime_pow n :=
begin
rcases eq_or_ne n 0 with rfl | hn',
{ simpa using h },
refine ⟨_, _, nat.prime_iff.1 (nat.min_fac_prime hn), _, h⟩,
rw [pos_iff_ne_zero, ←finsupp.mem_support_iff, nat.factor_iff_mem_factorization,
nat.mem_factors_iff_dvd hn' (nat.min_fac_prime hn)],
apply nat.min_fac_dvd
end
lemma is_prime_pow_iff_min_fac_pow_factorization_eq {n : ℕ} (hn : n ≠ 1) :
is_prime_pow n ↔ n.min_fac ^ n.factorization n.min_fac = n :=
⟨λ h, h.min_fac_pow_factorization_eq, λ h, is_prime_pow_of_min_fac_pow_factorization_eq h hn⟩
lemma is_prime_pow.dvd {n m : ℕ} (hn : is_prime_pow n) (hm : m ∣ n) (hm₁ : m ≠ 1) :
is_prime_pow m :=
begin
rw is_prime_pow_nat_iff at hn ⊢,
rcases hn with ⟨p, k, hp, hk, rfl⟩,
obtain ⟨i, hik, rfl⟩ := (nat.dvd_prime_pow hp).1 hm,
refine ⟨p, i, hp, _, rfl⟩,
apply nat.pos_of_ne_zero,
rintro rfl,
simpa using hm₁,
end
lemma is_prime_pow_iff_factorization_eq_single {n : ℕ} :
is_prime_pow n ↔ ∃ p k : ℕ, 0 < k ∧ n.factorization = finsupp.single p k :=
begin
rw is_prime_pow_nat_iff,
refine exists₂_congr (λ p k, _),
split,
{ rintros ⟨hp, hk, hn⟩,
exact ⟨hk, by rw [←hn, nat.prime.factorization_pow hp]⟩ },
{ rintros ⟨hk, hn⟩,
have hn0 : n ≠ 0,
{ rintro rfl,
simpa only [finsupp.single_eq_zero, eq_comm, nat.factorization_zero, hk.ne'] using hn },
rw nat.eq_pow_of_factorization_eq_single hn0 hn,
exact ⟨nat.prime_of_mem_factorization
(by simp [hn, hk.ne'] : p ∈ n.factorization.support), hk, rfl⟩ }
end
lemma is_prime_pow_iff_card_support_factorization_eq_one {n : ℕ} :
is_prime_pow n ↔ n.factorization.support.card = 1 :=
by simp_rw [is_prime_pow_iff_factorization_eq_single, finsupp.card_support_eq_one', exists_prop,
pos_iff_ne_zero]
/-- An equivalent definition for prime powers: `n` is a prime power iff there is a unique prime
dividing it. -/
lemma is_prime_pow_iff_unique_prime_dvd {n : ℕ} :
is_prime_pow n ↔ ∃! p : ℕ, p.prime ∧ p ∣ n :=
begin
rw is_prime_pow_nat_iff,
split,
{ rintro ⟨p, k, hp, hk, rfl⟩,
refine ⟨p, ⟨hp, dvd_pow_self _ hk.ne'⟩, _⟩,
rintro q ⟨hq, hq'⟩,
exact (nat.prime_dvd_prime_iff_eq hq hp).1 (hq.dvd_of_dvd_pow hq') },
rintro ⟨p, ⟨hp, hn⟩, hq⟩,
-- Take care of the n = 0 case
rcases eq_or_ne n 0 with rfl | hn₀,
{ obtain ⟨q, hq', hq''⟩ := nat.exists_infinite_primes (p + 1),
cases hq q ⟨hq'', by simp⟩,
simpa using hq' },
-- So assume 0 < n
refine ⟨p, n.factorization p, hp, hp.factorization_pos_of_dvd hn₀ hn, _⟩,
simp only [and_imp] at hq,
apply nat.dvd_antisymm (nat.pow_factorization_dvd _ _),
-- We need to show n ∣ p ^ n.factorization p
apply nat.dvd_of_factors_subperm hn₀,
rw [hp.factors_pow, list.subperm_ext_iff],
intros q hq',
rw nat.mem_factors hn₀ at hq',
cases hq _ hq'.1 hq'.2,
simp,
end
lemma is_prime_pow_pow_iff {n k : ℕ} (hk : k ≠ 0) :
is_prime_pow (n ^ k) ↔ is_prime_pow n :=
begin
simp only [is_prime_pow_iff_unique_prime_dvd],
apply exists_unique_congr,
simp only [and.congr_right_iff],
intros p hp,
exact ⟨hp.dvd_of_dvd_pow, λ t, t.trans (dvd_pow_self _ hk)⟩,
end
lemma nat.coprime.is_prime_pow_dvd_mul {n a b : ℕ} (hab : nat.coprime a b) (hn : is_prime_pow n) :
n ∣ a * b ↔ n ∣ a ∨ n ∣ b :=
begin
rcases eq_or_ne a 0 with rfl | ha,
{ simp only [nat.coprime_zero_left] at hab,
simp [hab, finset.filter_singleton, not_is_prime_pow_one] },
rcases eq_or_ne b 0 with rfl | hb,
{ simp only [nat.coprime_zero_right] at hab,
simp [hab, finset.filter_singleton, not_is_prime_pow_one] },
refine ⟨_, λ h, or.elim h (λ i, i.trans (dvd_mul_right _ _)) (λ i, i.trans (dvd_mul_left _ _))⟩,
obtain ⟨p, k, hp, hk, rfl⟩ := (is_prime_pow_nat_iff _).1 hn,
simp only [hp.pow_dvd_iff_le_factorization (mul_ne_zero ha hb),
nat.factorization_mul ha hb, hp.pow_dvd_iff_le_factorization ha,
hp.pow_dvd_iff_le_factorization hb, pi.add_apply, finsupp.coe_add],
have : a.factorization p = 0 ∨ b.factorization p = 0,
{ rw [←finsupp.not_mem_support_iff, ←finsupp.not_mem_support_iff, ←not_and_distrib,
←finset.mem_inter],
exact λ t, nat.factorization_disjoint_of_coprime hab t },
cases this;
simp [this, imp_or_distrib],
end
lemma nat.disjoint_divisors_filter_prime_pow {a b : ℕ} (hab : a.coprime b) :
disjoint (a.divisors.filter is_prime_pow) (b.divisors.filter is_prime_pow) :=
begin
simp only [finset.disjoint_left, finset.mem_filter, and_imp, nat.mem_divisors, not_and],
rintro n han ha hn hbn hb -,
exact hn.ne_one (nat.eq_one_of_dvd_coprimes hab han hbn),
end
lemma nat.mul_divisors_filter_prime_pow {a b : ℕ} (hab : a.coprime b) :
(a * b).divisors.filter is_prime_pow = (a.divisors ∪ b.divisors).filter is_prime_pow :=
begin
rcases eq_or_ne a 0 with rfl | ha,
{ simp only [nat.coprime_zero_left] at hab,
simp [hab, finset.filter_singleton, not_is_prime_pow_one] },
rcases eq_or_ne b 0 with rfl | hb,
{ simp only [nat.coprime_zero_right] at hab,
simp [hab, finset.filter_singleton, not_is_prime_pow_one] },
ext n,
simp only [ha, hb, finset.mem_union, finset.mem_filter, nat.mul_eq_zero, and_true, ne.def,
and.congr_left_iff, not_false_iff, nat.mem_divisors, or_self],
apply hab.is_prime_pow_dvd_mul,
end
lemma is_prime_pow.two_le : ∀ {n : ℕ}, is_prime_pow n → 2 ≤ n
| 0 h := (not_is_prime_pow_zero h).elim
| 1 h := (not_is_prime_pow_one h).elim
| (n+2) _ := le_add_self
theorem is_prime_pow.pos {n : ℕ} (hn : is_prime_pow n) : 0 < n := pos_of_gt hn.two_le
theorem is_prime_pow.one_lt {n : ℕ} (h : is_prime_pow n) : 1 < n := h.two_le
end nat
|
29406719c829391e8762d21768987af0a67a9612 | c31182a012eec69da0a1f6c05f42b0f0717d212d | /src/pseudo_normed_group/breen_deligne.lean | 6eb12f8ab6d480fc43a98ed1e1bfd3d19957a640 | [] | no_license | Ja1941/lean-liquid | fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc | 8e80ed0cbdf5145d6814e833a674eaf05a1495c1 | refs/heads/master | 1,689,437,983,362 | 1,628,362,719,000 | 1,628,362,719,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,142 | lean | import pseudo_normed_group.basic
import pseudo_normed_group.category
import breen_deligne.suitable
/-!
# Universal maps and pseudo-normed groups
This file contains the definition of the action of a basic universal map
on powers of a pseudo-normed group and related types.
## Main definitions
- `f.eval_png : (M^m) →+ (M^n)` : the group homomorphism induced by a basic universal map.
- `f.eval_png₀ : M_{c₁}^m → M_{c₂}^n` : the induced map if `f` is (c₁, c₂)-suitable.
-/
noncomputable theory
local attribute [instance] type_pow
open_locale nnreal big_operators matrix
namespace breen_deligne
namespace basic_universal_map
variables {m n : ℕ} (f : basic_universal_map m n)
variables (M : Type*)
section pseudo_normed_group
variables [pseudo_normed_group M]
open add_monoid_hom pseudo_normed_group
end pseudo_normed_group
section profinitely_filtered_pseudo_normed_group
open pseudo_normed_group profinitely_filtered_pseudo_normed_group add_monoid_hom
open profinitely_filtered_pseudo_normed_group_hom
variables [profinitely_filtered_pseudo_normed_group M]
/-- `eval_png M f` is the homomorphism `M^m → M^n` of profinitely filtered pseudo-normed groups
obtained by matrix multiplication with the matrix `f`. -/
def eval_png : basic_universal_map m n →+
profinitely_filtered_pseudo_normed_group_hom (M ^ m) (M ^ n) :=
add_monoid_hom.mk' (λ f, pi_lift (λ j, ∑ i, f j i • pi_proj i)
begin
let C : ℝ≥0 := finset.univ.sup (λ j, ∑ i, (f j i).nat_abs),
refine ⟨C, λ j, _⟩,
intros c x hx,
have : ∑ i, (↑(f j i).nat_abs * (1 * c)) ≤ C * c,
{ rw ← finset.sum_mul, exact mul_le_mul' (finset.le_sup (finset.mem_univ j)) (one_mul c).le },
refine filtration_mono this _,
simp only [← coe_to_add_monoid_hom, ← to_add_monoid_hom_hom_apply,
add_monoid_hom.map_sum, add_monoid_hom.map_gsmul, add_monoid_hom.finset_sum_apply],
refine sum_mem_filtration _ _ _ _,
rintro i -,
refine int_smul_mem_filtration _ _ _ _,
exact @pi_proj_bound_by _ (λ _, M) _ i _ _ hx,
end)
begin
intros f g,
ext x j,
simp only [← coe_to_add_monoid_hom, ← to_add_monoid_hom_hom_apply,
add_monoid_hom.map_add, add_monoid_hom.add_apply, pi.add_apply],
simp only [coe_to_add_monoid_hom, to_add_monoid_hom_hom_apply],
simp only [pi_lift_to_fun, mk_to_pi_apply, ← to_add_monoid_hom_hom_apply,
add_monoid_hom.map_sum, add_monoid_hom.map_gsmul, add_monoid_hom.finset_sum_apply],
rw ← finset.sum_add_distrib,
simp only [pi_proj_to_fun, to_add_monoid_hom_hom_apply, coe_smul,
coe_to_add_monoid_hom, pi.smul_apply, add_smul],
refl
end
lemma eval_png_apply (x : M^m) : eval_png M f x = λ j, ∑ i, f j i • (x i) :=
begin
ext j,
simp only [eval_png, mk'_apply, pi_lift_to_fun, mk_to_pi_apply, ← to_add_monoid_hom_hom_apply],
simp only [add_monoid_hom.map_sum, add_monoid_hom.map_gsmul,
add_monoid_hom.finset_sum_apply],
refl
end
lemma eval_png_mem_filtration :
(eval_png M f).to_add_monoid_hom ∈
filtration ((M^m) →+ (M^n)) (finset.univ.sup $ λ i, ∑ j, (f i j).nat_abs) :=
begin
apply mk_to_pi_mem_filtration,
intro j,
let C : ℝ≥0 := finset.univ.sup (λ j, ∑ i, (f j i).nat_abs),
intros c x hx,
have : ∑ i, (↑(f j i).nat_abs * (1 * c)) ≤ C * c,
{ rw ← finset.sum_mul, exact mul_le_mul' (finset.le_sup (finset.mem_univ j)) (one_mul c).le },
refine filtration_mono this _,
simp only [← coe_to_add_monoid_hom, ← to_add_monoid_hom_hom_apply,
add_monoid_hom.map_sum, add_monoid_hom.map_gsmul, add_monoid_hom.finset_sum_apply],
refine sum_mem_filtration _ _ _ _,
rintro i -,
refine int_smul_mem_filtration _ _ _ _,
exact @pi_proj_bound_by _ (λ _, M) _ i _ _ hx,
end
lemma eval_png_mem_filtration' (c₁ c₂ : ℝ≥0) [h : f.suitable c₁ c₂]
(x : M^m) (hx : x ∈ filtration (M^m) c₁) :
(eval_png M f x) ∈ filtration (M^n) c₂ :=
filtration_mono (f.sup_mul_le c₁ c₂) (f.eval_png_mem_filtration M hx)
/-- `f.eval_png₀ M` is the group homomorphism `(M^m) →+ (M^n)`
obtained by matrix multiplication with the matrix `f`,
but restricted to `(filtration M c₁)^m → (filtration M c₂)^n`. -/
@[simps {fully_applied := ff}]
def eval_png₀ (c₁ c₂ : ℝ≥0) [h : f.suitable c₁ c₂] (x : filtration (M^m) c₁) :
filtration (M^n) c₂ :=
⟨eval_png M f x, eval_png_mem_filtration' f M c₁ c₂ x x.2⟩
lemma eval_png_comp {l m n} (g : basic_universal_map m n) (f : basic_universal_map l m) :
eval_png M (basic_universal_map.comp g f) = (eval_png M g).comp (eval_png M f) :=
begin
ext x j,
simp only [eval_png_apply, function.comp_app, coe_comp, basic_universal_map.comp, comp_to_fun,
matrix.mul_apply, finset.smul_sum, finset.sum_smul, mul_smul, add_monoid_hom.mk'_apply],
rw finset.sum_comm
end
lemma eval_png₀_continuous (c₁ c₂ : ℝ≥0) [f.suitable c₁ c₂] : continuous (f.eval_png₀ M c₁ c₂) :=
(eval_png M f).continuous _ (λ x, rfl)
end profinitely_filtered_pseudo_normed_group
end basic_universal_map
end breen_deligne
#lint- only unused_arguments def_lemma doc_blame
|
363c51c44f36987a94d57cc709260e1f7d34727e | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/hinst_lemmas1.lean | 5752516707995a31eb2b1a5008dba878ff687e4f | [
"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 | 475 | lean | axiom foo1 : ∀ (a b c : nat), b > a → b < c → a < c
axiom foo2 : ∀ (a b c : nat), b > a → b < c → a < c
axiom foo3 : ∀ (a b c : nat), b > a → b < c + c → a < c + c
run_cmd
do
hs ← return $ hinst_lemmas.mk,
h₁ ← hinst_lemma.mk_from_decl `foo1,
h₂ ← hinst_lemma.mk_from_decl_core tactic.transparency.none `foo2 ff,
h₃ ← hinst_lemma.mk_from_decl `foo3,
hs ← return $ ((hs^.add h₁)^.add h₂)^.add h₃,
hs^.pp >>= tactic.trace
|
8c25e33b26c8979448fe678caa81f993add31482 | 367134ba5a65885e863bdc4507601606690974c1 | /src/algebra/algebra/operations.lean | 7f57387fade3923f0e33a7aaa5d59655ee7cb30e | [
"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 | 13,025 | lean | /-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.algebra.basic
/-!
# Multiplication and division of submodules of an algebra.
An interface for multiplication and division of sub-R-modules of an R-algebra A is developed.
## Main definitions
Let `R` be a commutative ring (or semiring) and aet `A` be an `R`-algebra.
* `1 : submodule R A` : the R-submodule R of the R-algebra A
* `has_mul (submodule R A)` : multiplication of two sub-R-modules M and N of A is defined to be
the smallest submodule containing all the products `m * n`.
* `has_div (submodule R A)` : `I / J` is defined to be the submodule consisting of all `a : A` such
that `a • J ⊆ I`
It is proved that `submodule R A` is a semiring, and also an algebra over `set A`.
## Tags
multiplication of submodules, division of subodules, submodule semiring
-/
universes u v
open algebra set
namespace submodule
variables {R : Type u} [comm_semiring R]
section ring
variables {A : Type v} [semiring A] [algebra R A]
variables (S T : set A) {M N P Q : submodule R A} {m n : A}
/-- `1 : submodule R A` is the submodule R of A. -/
instance : has_one (submodule R A) :=
⟨submodule.map (of_id R A).to_linear_map (⊤ : submodule R R)⟩
theorem one_eq_map_top :
(1 : submodule R A) = submodule.map (of_id R A).to_linear_map (⊤ : submodule R R) := rfl
theorem one_eq_span : (1 : submodule R A) = R ∙ 1 :=
begin
apply submodule.ext,
intro a,
erw [mem_map, mem_span_singleton],
apply exists_congr,
intro r,
simpa [smul_def],
end
theorem one_le : (1 : submodule R A) ≤ P ↔ (1 : A) ∈ P :=
by simpa only [one_eq_span, span_le, set.singleton_subset_iff]
/-- Multiplication of sub-R-modules of an R-algebra A. The submodule `M * N` is the
smallest R-submodule of `A` containing the elements `m * n` for `m ∈ M` and `n ∈ N`. -/
instance : has_mul (submodule R A) :=
⟨λ M N, ⨆ s : M, N.map $ algebra.lmul R A s.1⟩
theorem mul_mem_mul (hm : m ∈ M) (hn : n ∈ N) : m * n ∈ M * N :=
(le_supr _ ⟨m, hm⟩ : _ ≤ M * N) ⟨n, hn, rfl⟩
theorem mul_le : M * N ≤ P ↔ ∀ (m ∈ M) (n ∈ N), m * n ∈ P :=
⟨λ H m hm n hn, H $ mul_mem_mul hm hn,
λ H, supr_le $ λ ⟨m, hm⟩, map_le_iff_le_comap.2 $ λ n hn, H m hm n hn⟩
@[elab_as_eliminator] protected theorem mul_induction_on
{C : A → Prop} {r : A} (hr : r ∈ M * N)
(hm : ∀ (m ∈ M) (n ∈ N), C (m * n))
(h0 : C 0) (ha : ∀ x y, C x → C y → C (x + y))
(hs : ∀ (r : R) x, C x → C (r • x)) : C r :=
(@mul_le _ _ _ _ _ _ _ ⟨C, h0, ha, hs⟩).2 hm hr
variables R
theorem span_mul_span : span R S * span R T = span R (S * T) :=
begin
apply le_antisymm,
{ rw mul_le, intros a ha b hb,
apply span_induction ha,
work_on_goal 0 { intros, apply span_induction hb,
work_on_goal 0 { intros, exact subset_span ⟨_, _, ‹_›, ‹_›, rfl⟩ } },
all_goals { intros, simp only [mul_zero, zero_mul, zero_mem,
left_distrib, right_distrib, mul_smul_comm, smul_mul_assoc],
try {apply add_mem _ _ _}, try {apply smul_mem _ _ _} }, assumption' },
{ rw span_le, rintros _ ⟨a, b, ha, hb, rfl⟩,
exact mul_mem_mul (subset_span ha) (subset_span hb) }
end
variables {R}
variables (M N P Q)
protected theorem mul_assoc : (M * N) * P = M * (N * P) :=
le_antisymm (mul_le.2 $ λ mn hmn p hp,
suffices M * N ≤ (M * (N * P)).comap (algebra.lmul_right R p), from this hmn,
mul_le.2 $ λ m hm n hn, show m * n * p ∈ M * (N * P), from
(mul_assoc m n p).symm ▸ mul_mem_mul hm (mul_mem_mul hn hp))
(mul_le.2 $ λ m hm np hnp,
suffices N * P ≤ (M * N * P).comap (algebra.lmul_left R m), from this hnp,
mul_le.2 $ λ n hn p hp, show m * (n * p) ∈ M * N * P, from
mul_assoc m n p ▸ mul_mem_mul (mul_mem_mul hm hn) hp)
@[simp] theorem mul_bot : M * ⊥ = ⊥ :=
eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hn ⊢; rw [hn, mul_zero]
@[simp] theorem bot_mul : ⊥ * M = ⊥ :=
eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hm ⊢; rw [hm, zero_mul]
@[simp] protected theorem one_mul : (1 : submodule R A) * M = M :=
by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, one_mul, span_eq] }
@[simp] protected theorem mul_one : M * 1 = M :=
by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, mul_one, span_eq] }
variables {M N P Q}
@[mono] theorem mul_le_mul (hmp : M ≤ P) (hnq : N ≤ Q) : M * N ≤ P * Q :=
mul_le.2 $ λ m hm n hn, mul_mem_mul (hmp hm) (hnq hn)
theorem mul_le_mul_left (h : M ≤ N) : M * P ≤ N * P :=
mul_le_mul h (le_refl P)
theorem mul_le_mul_right (h : N ≤ P) : M * N ≤ M * P :=
mul_le_mul (le_refl M) h
variables (M N P)
theorem mul_sup : M * (N ⊔ P) = M * N ⊔ M * P :=
le_antisymm (mul_le.2 $ λ m hm np hnp, let ⟨n, hn, p, hp, hnp⟩ := mem_sup.1 hnp in
mem_sup.2 ⟨_, mul_mem_mul hm hn, _, mul_mem_mul hm hp, hnp ▸ (mul_add m n p).symm⟩)
(sup_le (mul_le_mul_right le_sup_left) (mul_le_mul_right le_sup_right))
theorem sup_mul : (M ⊔ N) * P = M * P ⊔ N * P :=
le_antisymm (mul_le.2 $ λ mn hmn p hp, let ⟨m, hm, n, hn, hmn⟩ := mem_sup.1 hmn in
mem_sup.2 ⟨_, mul_mem_mul hm hp, _, mul_mem_mul hn hp, hmn ▸ (add_mul m n p).symm⟩)
(sup_le (mul_le_mul_left le_sup_left) (mul_le_mul_left le_sup_right))
lemma mul_subset_mul : (↑M : set A) * (↑N : set A) ⊆ (↑(M * N) : set A) :=
by { rintros _ ⟨i, j, hi, hj, rfl⟩, exact mul_mem_mul hi hj }
lemma map_mul {A'} [semiring A'] [algebra R A'] (f : A →ₐ[R] A') :
map f.to_linear_map (M * N) = map f.to_linear_map M * map f.to_linear_map N :=
calc map f.to_linear_map (M * N)
= ⨆ (i : M), (N.map (lmul R A i)).map f.to_linear_map : map_supr _ _
... = map f.to_linear_map M * map f.to_linear_map N :
begin
apply congr_arg Sup,
ext S,
split; rintros ⟨y, hy⟩,
{ use [f y, mem_map.mpr ⟨y.1, y.2, rfl⟩],
refine trans _ hy,
ext,
simp },
{ obtain ⟨y', hy', fy_eq⟩ := mem_map.mp y.2,
use [y', hy'],
refine trans _ hy,
rw f.to_linear_map_apply at fy_eq,
ext,
simp [fy_eq] }
end
section decidable_eq
open_locale classical
lemma mem_span_mul_finite_of_mem_span_mul {S : set A} {S' : set A} {x : A}
(hx : x ∈ span R (S * S')) :
∃ (T T' : finset A), ↑T ⊆ S ∧ ↑T' ⊆ S' ∧ x ∈ span R (T * T' : set A) :=
begin
obtain ⟨U, h, hU⟩ := mem_span_finite_of_mem_span hx,
obtain ⟨T, T', hS, hS', h⟩ := finset.subset_mul h,
use [T, T', hS, hS'],
have h' : (U : set A) ⊆ T * T', { assumption_mod_cast, },
have h'' := span_mono h' hU,
assumption,
end
end decidable_eq
lemma mem_span_mul_finite_of_mem_mul {P Q : submodule R A} {x : A} (hx : x ∈ P * Q) :
∃ (T T' : finset A), (T : set A) ⊆ P ∧ (T' : set A) ⊆ Q ∧ x ∈ span R (T * T' : set A) :=
submodule.mem_span_mul_finite_of_mem_span_mul
(by rwa [← submodule.span_eq P, ← submodule.span_eq Q, submodule.span_mul_span] at hx)
variables {M N P}
/-- Sub-R-modules of an R-algebra form a semiring. -/
instance : semiring (submodule R A) :=
{ one_mul := submodule.one_mul,
mul_one := submodule.mul_one,
mul_assoc := submodule.mul_assoc,
zero_mul := bot_mul,
mul_zero := mul_bot,
left_distrib := mul_sup,
right_distrib := sup_mul,
..submodule.add_comm_monoid_submodule,
..submodule.has_one,
..submodule.has_mul }
variables (M)
lemma pow_subset_pow {n : ℕ} : (↑M : set A)^n ⊆ ↑(M^n : submodule R A) :=
begin
induction n with n ih,
{ erw [pow_zero, pow_zero, set.singleton_subset_iff], rw [mem_coe, ← one_le], exact le_refl _ },
{ rw [pow_succ, pow_succ],
refine set.subset.trans (set.mul_subset_mul (subset.refl _) ih) _,
apply mul_subset_mul }
end
/-- `span` is a semiring homomorphism (recall multiplication is pointwise multiplication of subsets
on either side). -/
def span.ring_hom : set_semiring A →+* submodule R A :=
{ to_fun := submodule.span R,
map_zero' := span_empty,
map_one' := le_antisymm (span_le.2 $ singleton_subset_iff.2 ⟨1, ⟨⟩, (algebra_map R A).map_one⟩)
(map_le_iff_le_comap.2 $ λ r _, mem_span_singleton.2 ⟨r, (algebra_map_eq_smul_one r).symm⟩),
map_add' := span_union,
map_mul' := λ s t, by erw [span_mul_span, ← image_mul_prod] }
end ring
section comm_ring
variables {A : Type v} [comm_semiring A] [algebra R A]
variables {M N : submodule R A} {m n : A}
theorem mul_mem_mul_rev (hm : m ∈ M) (hn : n ∈ N) : n * m ∈ M * N :=
mul_comm m n ▸ mul_mem_mul hm hn
variables (M N)
protected theorem mul_comm : M * N = N * M :=
le_antisymm (mul_le.2 $ λ r hrm s hsn, mul_mem_mul_rev hsn hrm)
(mul_le.2 $ λ r hrn s hsm, mul_mem_mul_rev hsm hrn)
/-- Sub-R-modules of an R-algebra A form a semiring. -/
instance : comm_semiring (submodule R A) :=
{ mul_comm := submodule.mul_comm,
.. submodule.semiring }
variables (R A)
/-- R-submodules of the R-algebra A are a module over `set A`. -/
instance semimodule_set : semimodule (set_semiring A) (submodule R A) :=
{ smul := λ s P, span R s * P,
smul_add := λ _ _ _, mul_add _ _ _,
add_smul := λ s t P, show span R (s ⊔ t) * P = _, by { erw [span_union, right_distrib] },
mul_smul := λ s t P, show _ = _ * (_ * _),
by { rw [← mul_assoc, span_mul_span, ← image_mul_prod] },
one_smul := λ P, show span R {(1 : A)} * P = _,
by { conv_lhs {erw ← span_eq P}, erw [span_mul_span, one_mul, span_eq] },
zero_smul := λ P, show span R ∅ * P = ⊥, by erw [span_empty, bot_mul],
smul_zero := λ _, mul_bot _ }
variables {R A}
lemma smul_def {s : set_semiring A} {P : submodule R A} : s • P = span R s * P := rfl
lemma smul_le_smul {s t : set_semiring A} {M N : submodule R A} (h₁ : s.down ≤ t.down)
(h₂ : M ≤ N) : s • M ≤ t • N :=
mul_le_mul (span_mono h₁) h₂
lemma smul_singleton (a : A) (M : submodule R A) :
({a} : set A).up • M = M.map (lmul_left _ a) :=
begin
conv_lhs {rw ← span_eq M},
change span _ _ * span _ _ = _,
rw [span_mul_span],
apply le_antisymm,
{ rw span_le,
rintros _ ⟨b, m, hb, hm, rfl⟩,
rw [mem_coe, mem_map, set.mem_singleton_iff.mp hb],
exact ⟨m, hm, rfl⟩ },
{ rintros _ ⟨m, hm, rfl⟩, exact subset_span ⟨a, m, set.mem_singleton a, hm, rfl⟩ }
end
section quotient
/-- The elements of `I / J` are the `x` such that `x • J ⊆ I`.
In fact, we define `x ∈ I / J` to be `∀ y ∈ J, x * y ∈ I` (see `mem_div_iff_forall_mul_mem`),
which is equivalent to `x • J ⊆ I` (see `mem_div_iff_smul_subset`), but nicer to use in proofs.
This is the general form of the ideal quotient, traditionally written $I : J$.
-/
instance : has_div (submodule R A) :=
⟨ λ I J, {
carrier := { x | ∀ y ∈ J, x * y ∈ I },
zero_mem' := λ y hy, by { rw zero_mul, apply submodule.zero_mem },
add_mem' := λ a b ha hb y hy, by { rw add_mul, exact submodule.add_mem _ (ha _ hy) (hb _ hy) },
smul_mem' := λ r x hx y hy, by { rw algebra.smul_mul_assoc,
exact submodule.smul_mem _ _ (hx _ hy) } } ⟩
lemma mem_div_iff_forall_mul_mem {x : A} {I J : submodule R A} :
x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I :=
iff.refl _
lemma mem_div_iff_smul_subset {x : A} {I J : submodule R A} : x ∈ I / J ↔ x • (J : set A) ⊆ I :=
⟨ λ h y ⟨y', hy', xy'_eq_y⟩, by { rw ← xy'_eq_y, apply h, assumption },
λ h y hy, h (set.smul_mem_smul_set hy) ⟩
lemma le_div_iff {I J K : submodule R A} : I ≤ J / K ↔ ∀ (x ∈ I) (z ∈ K), x * z ∈ J := iff.refl _
lemma le_div_iff_mul_le {I J K : submodule R A} : I ≤ J / K ↔ I * K ≤ J :=
by rw [le_div_iff, mul_le]
@[simp] lemma one_le_one_div {I : submodule R A} :
1 ≤ 1 / I ↔ I ≤ 1 :=
begin
split, all_goals {intro hI},
{rwa [le_div_iff_mul_le, one_mul] at hI},
{rwa [le_div_iff_mul_le, one_mul]},
end
lemma le_self_mul_one_div {I : submodule R A} (hI : I ≤ 1) :
I ≤ I * (1 / I) :=
begin
rw [← mul_one I] {occs := occurrences.pos [1]},
apply mul_le_mul_right (one_le_one_div.mpr hI),
end
lemma mul_one_div_le_one {I : submodule R A} : I * (1 / I) ≤ 1 :=
begin
rw submodule.mul_le,
intros m hm n hn,
rw [submodule.mem_div_iff_forall_mul_mem] at hn,
rw mul_comm,
exact hn m hm,
end
@[simp] lemma map_div {B : Type*} [comm_ring B] [algebra R B]
(I J : submodule R A) (h : A ≃ₐ[R] B) :
(I / J).map h.to_linear_map = I.map h.to_linear_map / J.map h.to_linear_map :=
begin
ext x,
simp only [mem_map, mem_div_iff_forall_mul_mem],
split,
{ rintro ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩,
exact ⟨x * y, hx _ hy, h.map_mul x y⟩ },
{ rintro hx,
refine ⟨h.symm x, λ z hz, _, h.apply_symm_apply x⟩,
obtain ⟨xz, xz_mem, hxz⟩ := hx (h z) ⟨z, hz, rfl⟩,
convert xz_mem,
apply h.injective,
erw [h.map_mul, h.apply_symm_apply, hxz] }
end
end quotient
end comm_ring
end submodule
|
dc6430fc66dae76c3856eebad3d625d7a4d1be3c | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/category_theory/limits/preserves/shapes/equalizers.lean | 7f5eb58367cd5f27d5beb9d025938868230e2b86 | [
"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 | 7,226 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.limits.shapes.split_coequalizer
import category_theory.limits.preserves.basic
/-!
# Preserving (co)equalizers
Constructions to relate the notions of preserving (co)equalizers and reflecting (co)equalizers
to concrete (co)forks.
In particular, we show that `equalizer_comparison G f` is an isomorphism iff `G` preserves
the limit of `f` as well as the dual.
-/
noncomputable theory
universes v u₁ u₂
open category_theory category_theory.category category_theory.limits
variables {C : Type u₁} [category.{v} C]
variables {D : Type u₂} [category.{v} D]
variables (G : C ⥤ D)
namespace category_theory.limits
section equalizers
variables {X Y Z : C} {f g : X ⟶ Y} {h : Z ⟶ X} (w : h ≫ f = h ≫ g)
/--
The map of a fork is a limit iff the fork consisting of the mapped morphisms is a limit. This
essentially lets us commute `fork.of_ι` with `functor.map_cone`.
-/
def is_limit_map_cone_fork_equiv :
is_limit (G.map_cone (fork.of_ι h w)) ≃
is_limit (fork.of_ι (G.map h) (by simp only [←G.map_comp, w]) : fork (G.map f) (G.map g)) :=
(is_limit.postcompose_hom_equiv (diagram_iso_parallel_pair.{v} _) _).symm.trans
(is_limit.equiv_iso_limit (fork.ext (iso.refl _) (by simp)))
/-- The property of preserving equalizers expressed in terms of forks. -/
def is_limit_fork_map_of_is_limit [preserves_limit (parallel_pair f g) G]
(l : is_limit (fork.of_ι h w)) :
is_limit (fork.of_ι (G.map h) (by simp only [←G.map_comp, w]) : fork (G.map f) (G.map g)) :=
is_limit_map_cone_fork_equiv G w (preserves_limit.preserves l)
/-- The property of reflecting equalizers expressed in terms of forks. -/
def is_limit_of_is_limit_fork_map [reflects_limit (parallel_pair f g) G]
(l : is_limit (fork.of_ι (G.map h) (by simp only [←G.map_comp, w]) : fork (G.map f) (G.map g))) :
is_limit (fork.of_ι h w) :=
reflects_limit.reflects ((is_limit_map_cone_fork_equiv G w).symm l)
variables (f g) [has_equalizer f g]
/--
If `G` preserves equalizers and `C` has them, then the fork constructed of the mapped morphisms of
a fork is a limit.
-/
def is_limit_of_has_equalizer_of_preserves_limit
[preserves_limit (parallel_pair f g) G] :
is_limit (fork.of_ι (G.map (equalizer.ι f g))
(by simp only [←G.map_comp, equalizer.condition])) :=
is_limit_fork_map_of_is_limit G _ (equalizer_is_equalizer f g)
variables [has_equalizer (G.map f) (G.map g)]
/--
If the equalizer comparison map for `G` at `(f,g)` is an isomorphism, then `G` preserves the
equalizer of `(f,g)`.
-/
def preserves_equalizer.of_iso_comparison [i : is_iso (equalizer_comparison f g G)] :
preserves_limit (parallel_pair f g) G :=
begin
apply preserves_limit_of_preserves_limit_cone (equalizer_is_equalizer f g),
apply (is_limit_map_cone_fork_equiv _ _).symm _,
apply is_limit.of_point_iso (limit.is_limit (parallel_pair (G.map f) (G.map g))),
apply i,
end
variables [preserves_limit (parallel_pair f g) G]
/--
If `G` preserves the equalizer of `(f,g)`, then the equalizer comparison map for `G` at `(f,g)` is
an isomorphism.
-/
def preserves_equalizer.iso :
G.obj (equalizer f g) ≅ equalizer (G.map f) (G.map g) :=
is_limit.cone_point_unique_up_to_iso
(is_limit_of_has_equalizer_of_preserves_limit G f g)
(limit.is_limit _)
@[simp]
lemma preserves_equalizer.iso_hom :
(preserves_equalizer.iso G f g).hom = equalizer_comparison f g G :=
rfl
instance : is_iso (equalizer_comparison f g G) :=
begin
rw ← preserves_equalizer.iso_hom,
apply_instance
end
end equalizers
section coequalizers
variables {X Y Z : C} {f g : X ⟶ Y} {h : Y ⟶ Z} (w : f ≫ h = g ≫ h)
/--
The map of a cofork is a colimit iff the cofork consisting of the mapped morphisms is a colimit.
This essentially lets us commute `cofork.of_π` with `functor.map_cocone`.
-/
def is_colimit_map_cocone_cofork_equiv :
is_colimit (G.map_cocone (cofork.of_π h w)) ≃
is_colimit (cofork.of_π (G.map h) (by simp only [←G.map_comp, w]) : cofork (G.map f) (G.map g)) :=
(is_colimit.precompose_inv_equiv (diagram_iso_parallel_pair.{v} _) _).symm.trans
(is_colimit.equiv_iso_colimit (cofork.ext (iso.refl _) (by { dsimp, simp })))
/-- The property of preserving coequalizers expressed in terms of coforks. -/
def is_colimit_cofork_map_of_is_colimit [preserves_colimit (parallel_pair f g) G]
(l : is_colimit (cofork.of_π h w)) :
is_colimit (cofork.of_π (G.map h) (by simp only [←G.map_comp, w]) : cofork (G.map f) (G.map g)) :=
is_colimit_map_cocone_cofork_equiv G w (preserves_colimit.preserves l)
/-- The property of reflecting coequalizers expressed in terms of coforks. -/
def is_colimit_of_is_colimit_cofork_map [reflects_colimit (parallel_pair f g) G]
(l : is_colimit (cofork.of_π (G.map h) (by simp only [←G.map_comp, w])
: cofork (G.map f) (G.map g))) :
is_colimit (cofork.of_π h w) :=
reflects_colimit.reflects ((is_colimit_map_cocone_cofork_equiv G w).symm l)
variables (f g) [has_coequalizer f g]
/--
If `G` preserves coequalizers and `C` has them, then the cofork constructed of the mapped morphisms
of a cofork is a colimit.
-/
def is_colimit_of_has_coequalizer_of_preserves_colimit
[preserves_colimit (parallel_pair f g) G] :
is_colimit (cofork.of_π (G.map (coequalizer.π f g)) _) :=
is_colimit_cofork_map_of_is_colimit G _ (coequalizer_is_coequalizer f g)
variables [has_coequalizer (G.map f) (G.map g)]
/--
If the coequalizer comparison map for `G` at `(f,g)` is an isomorphism, then `G` preserves the
coequalizer of `(f,g)`.
-/
def of_iso_comparison [i : is_iso (coequalizer_comparison f g G)] :
preserves_colimit (parallel_pair f g) G :=
begin
apply preserves_colimit_of_preserves_colimit_cocone (coequalizer_is_coequalizer f g),
apply (is_colimit_map_cocone_cofork_equiv _ _).symm _,
apply is_colimit.of_point_iso (colimit.is_colimit (parallel_pair (G.map f) (G.map g))),
apply i,
end
variables [preserves_colimit (parallel_pair f g) G]
/--
If `G` preserves the coequalizer of `(f,g)`, then the coequalizer comparison map for `G` at `(f,g)`
is an isomorphism.
-/
def preserves_coequalizer.iso :
coequalizer (G.map f) (G.map g) ≅ G.obj (coequalizer f g) :=
is_colimit.cocone_point_unique_up_to_iso
(colimit.is_colimit _)
(is_colimit_of_has_coequalizer_of_preserves_colimit G f g)
@[simp]
lemma preserves_coequalizer.iso_hom :
(preserves_coequalizer.iso G f g).hom = coequalizer_comparison f g G :=
rfl
instance : is_iso (coequalizer_comparison f g G) :=
begin
rw ← preserves_coequalizer.iso_hom,
apply_instance
end
/-- Any functor preserves coequalizers of split pairs. -/
@[priority 1]
instance preserves_split_coequalizers (f g : X ⟶ Y) [has_split_coequalizer f g] :
preserves_colimit (parallel_pair f g) G :=
begin
apply preserves_colimit_of_preserves_colimit_cocone
((has_split_coequalizer.is_split_coequalizer f g).is_coequalizer),
apply (is_colimit_map_cocone_cofork_equiv G _).symm
((has_split_coequalizer.is_split_coequalizer f g).map G).is_coequalizer,
end
end coequalizers
end category_theory.limits
|
4fb2aba17fcb089bd0abd6364a41d38a17bf3bfb | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/nat/prime.lean | ea7845c9b5f43f4ff9bfd8ca0b64a6610ea09d32 | [
"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 | 46,211 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro
-/
import data.list.prime
import data.list.sort
import data.nat.gcd
import data.nat.sqrt_norm_num
import data.set.finite
import tactic.wlog
import algebra.parity
/-!
# Prime numbers
This file deals with prime numbers: natural numbers `p ≥ 2` whose only divisors are `p` and `1`.
## Important declarations
- `nat.prime`: the predicate that expresses that a natural number `p` is prime
- `nat.primes`: the subtype of natural numbers that are prime
- `nat.min_fac n`: the minimal prime factor of a natural number `n ≠ 1`
- `nat.exists_infinite_primes`: Euclid's theorem that there exist infinitely many prime numbers.
This also appears as `nat.not_bdd_above_set_of_prime` and `nat.infinite_set_of_prime`.
- `nat.factors n`: the prime factorization of `n`
- `nat.factors_unique`: uniqueness of the prime factorisation
* `nat.prime_iff`: `nat.prime` coincides with the general definition of `prime`
* `nat.irreducible_iff_prime`: a non-unit natural number is only divisible by `1` iff it is prime
-/
open bool subtype
open_locale nat
namespace nat
/-- `prime p` means that `p` is a prime number, that is, a natural number
at least 2 whose only divisors are `p` and `1`. -/
@[pp_nodot]
def prime (p : ℕ) := _root_.irreducible p
theorem _root_.irreducible_iff_nat_prime (a : ℕ) : irreducible a ↔ nat.prime a := iff.rfl
theorem not_prime_zero : ¬ prime 0
| h := h.ne_zero rfl
theorem not_prime_one : ¬ prime 1
| h := h.ne_one rfl
theorem prime.ne_zero {n : ℕ} (h : prime n) : n ≠ 0 := irreducible.ne_zero h
theorem prime.pos {p : ℕ} (pp : prime p) : 0 < p := nat.pos_of_ne_zero pp.ne_zero
theorem prime.two_le : ∀ {p : ℕ}, prime p → 2 ≤ p
| 0 h := (not_prime_zero h).elim
| 1 h := (not_prime_one h).elim
| (n+2) _ := le_add_self
theorem prime.one_lt {p : ℕ} : prime p → 1 < p := prime.two_le
instance prime.one_lt' (p : ℕ) [hp : _root_.fact p.prime] : _root_.fact (1 < p) := ⟨hp.1.one_lt⟩
lemma prime.ne_one {p : ℕ} (hp : p.prime) : p ≠ 1 :=
hp.one_lt.ne'
lemma prime.eq_one_or_self_of_dvd {p : ℕ} (pp : p.prime) (m : ℕ) (hm : m ∣ p) : m = 1 ∨ m = p :=
begin
obtain ⟨n, hn⟩ := hm,
have := pp.is_unit_or_is_unit hn,
rw [nat.is_unit_iff, nat.is_unit_iff] at this,
apply or.imp_right _ this,
rintro rfl,
rw [hn, mul_one]
end
theorem prime_def_lt'' {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m ∣ p, m = 1 ∨ m = p :=
begin
refine ⟨λ h, ⟨h.two_le, h.eq_one_or_self_of_dvd⟩, λ h, _⟩,
have h1 := one_lt_two.trans_le h.1,
refine ⟨mt nat.is_unit_iff.mp h1.ne', λ a b hab, _⟩,
simp only [nat.is_unit_iff],
apply or.imp_right _ (h.2 a _),
{ rintro rfl,
rw [←nat.mul_right_inj (pos_of_gt h1), ←hab, mul_one] },
{ rw hab,
exact dvd_mul_right _ _ }
end
theorem prime_def_lt {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m < p, m ∣ p → m = 1 :=
prime_def_lt''.trans $
and_congr_right $ λ p2, forall_congr $ λ m,
⟨λ h l d, (h d).resolve_right (ne_of_lt l),
λ h d, (le_of_dvd (le_of_succ_le p2) d).lt_or_eq_dec.imp_left (λ l, h l d)⟩
theorem prime_def_lt' {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m, 2 ≤ m → m < p → ¬ m ∣ p :=
prime_def_lt.trans $ and_congr_right $ λ p2, forall_congr $ λ m,
⟨λ h m2 l d, not_lt_of_ge m2 ((h l d).symm ▸ dec_trivial),
λ h l d, begin
rcases m with _|_|m,
{ rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial },
{ refl },
{ exact (h dec_trivial l).elim d }
end⟩
theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ 2 ≤ p ∧
∀ m, 2 ≤ m → m ≤ sqrt p → ¬ m ∣ p :=
prime_def_lt'.trans $ and_congr_right $ λ p2,
⟨λ a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2,
λ a, have ∀ {m k}, m ≤ k → 1 < m → p ≠ m * k, from
λ m k mk m1 e, a m m1
(le_sqrt.2 (e.symm ▸ nat.mul_le_mul_left m mk)) ⟨k, e⟩,
λ m m2 l ⟨k, e⟩, begin
cases (le_total m k) with mk km,
{ exact this mk m2 e },
{ rw [mul_comm] at e,
refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e,
rwa [one_mul, ← e] }
end⟩
theorem prime_of_coprime (n : ℕ) (h1 : 1 < n) (h : ∀ m < n, m ≠ 0 → n.coprime m) : prime n :=
begin
refine prime_def_lt.mpr ⟨h1, λ m mlt mdvd, _⟩,
have hm : m ≠ 0,
{ rintro rfl,
rw zero_dvd_iff at mdvd,
exact mlt.ne' mdvd },
exact (h m mlt hm).symm.eq_one_of_dvd mdvd,
end
section
/--
This instance is slower than the instance `decidable_prime` defined below,
but has the advantage that it works in the kernel for small values.
If you need to prove that a particular number is prime, in any case
you should not use `dec_trivial`, but rather `by norm_num`, which is
much faster.
-/
local attribute [instance]
def decidable_prime_1 (p : ℕ) : decidable (prime p) :=
decidable_of_iff' _ prime_def_lt'
theorem prime_two : prime 2 := dec_trivial
end
theorem prime.pred_pos {p : ℕ} (pp : prime p) : 0 < pred p :=
lt_pred_iff.2 pp.one_lt
theorem succ_pred_prime {p : ℕ} (pp : prime p) : succ (pred p) = p :=
succ_pred_eq_of_pos pp.pos
theorem dvd_prime {p m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p :=
⟨λ d, pp.eq_one_or_self_of_dvd m d, λ h, h.elim (λ e, e.symm ▸ one_dvd _) (λ e, e.symm ▸ dvd_rfl)⟩
theorem dvd_prime_two_le {p m : ℕ} (pp : prime p) (H : 2 ≤ m) : m ∣ p ↔ m = p :=
(dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H
theorem prime_dvd_prime_iff_eq {p q : ℕ} (pp : p.prime) (qp : q.prime) : p ∣ q ↔ p = q :=
dvd_prime_two_le qp (prime.two_le pp)
theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬ p ∣ 1 :=
pp.not_dvd_one
theorem not_prime_mul {a b : ℕ} (a1 : 1 < a) (b1 : 1 < b) : ¬ prime (a * b) :=
λ h, ne_of_lt (nat.mul_lt_mul_of_pos_left b1 (lt_of_succ_lt a1)) $
by simpa using (dvd_prime_two_le h a1).1 (dvd_mul_right _ _)
lemma not_prime_mul' {a b n : ℕ} (h : a * b = n) (h₁ : 1 < a) (h₂ : 1 < b) : ¬ prime n :=
by { rw ← h, exact not_prime_mul h₁ h₂ }
lemma prime_mul_iff {a b : ℕ} :
nat.prime (a * b) ↔ (a.prime ∧ b = 1) ∨ (b.prime ∧ a = 1) :=
by simp only [iff_self, irreducible_mul_iff, ←irreducible_iff_nat_prime, nat.is_unit_iff]
lemma prime.dvd_iff_eq {p a : ℕ} (hp : p.prime) (a1 : a ≠ 1) : a ∣ p ↔ p = a :=
begin
refine ⟨_, by { rintro rfl, refl }⟩,
-- rintro ⟨j, rfl⟩ does not work, due to `nat.prime` depending on the class `irreducible`
rintro ⟨j, hj⟩,
rw hj at hp ⊢,
rcases prime_mul_iff.mp hp with ⟨h, rfl⟩ | ⟨h, rfl⟩,
{ exact mul_one _ },
{ exact (a1 rfl).elim }
end
section min_fac
lemma min_fac_lemma (n k : ℕ) (h : ¬ n < k * k) :
sqrt n - k < sqrt n + 2 - k :=
(tsub_lt_tsub_iff_right $ le_sqrt.2 $ le_of_not_gt h).2 $
nat.lt_add_of_pos_right dec_trivial
/-- If `n < k * k`, then `min_fac_aux n k = n`, if `k | n`, then `min_fac_aux n k = k`.
Otherwise, `min_fac_aux n k = min_fac_aux n (k+2)` using well-founded recursion.
If `n` is odd and `1 < n`, then then `min_fac_aux n 3` is the smallest prime factor of `n`. -/
def min_fac_aux (n : ℕ) : ℕ → ℕ
| k :=
if h : n < k * k then n else
if k ∣ n then k else
have _, from min_fac_lemma n k h,
min_fac_aux (k + 2)
using_well_founded {rel_tac :=
λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]}
/-- Returns the smallest prime factor of `n ≠ 1`. -/
def min_fac : ℕ → ℕ
| 0 := 2
| 1 := 1
| (n+2) := if 2 ∣ n then 2 else min_fac_aux (n + 2) 3
@[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl
@[simp] theorem min_fac_one : min_fac 1 = 1 := rfl
theorem min_fac_eq : ∀ n, min_fac n = if 2 ∣ n then 2 else min_fac_aux n 3
| 0 := by simp
| 1 := by simp [show 2≠1, from dec_trivial]; rw min_fac_aux; refl
| (n+2) :=
have 2 ∣ n + 2 ↔ 2 ∣ n, from
(nat.dvd_add_iff_left (by refl)).symm,
by simp [min_fac, this]; congr
private def min_fac_prop (n k : ℕ) :=
2 ≤ k ∧ k ∣ n ∧ ∀ m, 2 ≤ m → m ∣ n → k ≤ m
theorem min_fac_aux_has_prop {n : ℕ} (n2 : 2 ≤ n) :
∀ k i, k = 2*i+3 → (∀ m, 2 ≤ m → m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k)
| k := λ i e a, begin
rw min_fac_aux,
by_cases h : n < k*k; simp [h],
{ have pp : prime n :=
prime_def_le_sqrt.2 ⟨n2, λ m m2 l d,
not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩,
from ⟨n2, dvd_rfl, λ m m2 d, le_of_eq
((dvd_prime_two_le pp m2).1 d).symm⟩ },
have k2 : 2 ≤ k, { subst e, exact dec_trivial },
by_cases dk : k ∣ n; simp [dk],
{ exact ⟨k2, dk, a⟩ },
{ refine have _, from min_fac_lemma n k h,
min_fac_aux_has_prop (k+2) (i+1)
(by simp [e, left_distrib]) (λ m m2 d, _),
cases nat.eq_or_lt_of_le (a m m2 d) with me ml,
{ subst me, contradiction },
apply (nat.eq_or_lt_of_le ml).resolve_left, intro me,
rw [← me, e] at d, change 2 * (i + 2) ∣ n at d,
have := a _ le_rfl (dvd_of_mul_right_dvd d),
rw e at this, exact absurd this dec_trivial }
end
using_well_founded {rel_tac :=
λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]}
theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) :
min_fac_prop n (min_fac n) :=
begin
by_cases n0 : n = 0, {simp [n0, min_fac_prop, ge]},
have n2 : 2 ≤ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial },
simp [min_fac_eq],
by_cases d2 : 2 ∣ n; simp [d2],
{ exact ⟨le_rfl, d2, λ k k2 d, k2⟩ },
{ refine min_fac_aux_has_prop n2 3 0 rfl
(λ m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)),
exact λ e, e.symm ▸ d }
end
theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n :=
if n1 : n = 1 then by simp [n1] else (min_fac_has_prop n1).2.1
theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) :=
let ⟨f2, fd, a⟩ := min_fac_has_prop n1 in
prime_def_lt'.2 ⟨f2, λ m m2 l d, not_le_of_gt l (a m m2 (d.trans fd))⟩
theorem min_fac_le_of_dvd {n : ℕ} : ∀ {m : ℕ}, 2 ≤ m → m ∣ n → min_fac n ≤ m :=
by by_cases n1 : n = 1;
[exact λ m m2 d, n1.symm ▸ le_trans dec_trivial m2,
exact (min_fac_has_prop n1).2.2]
theorem min_fac_pos (n : ℕ) : 0 < min_fac n :=
by by_cases n1 : n = 1;
[exact n1.symm ▸ dec_trivial, exact (min_fac_prime n1).pos]
theorem min_fac_le {n : ℕ} (H : 0 < n) : min_fac n ≤ n :=
le_of_dvd H (min_fac_dvd n)
theorem le_min_fac {m n : ℕ} : n = 1 ∨ m ≤ min_fac n ↔ ∀ p, prime p → p ∣ n → m ≤ p :=
⟨λ h p pp d, h.elim
(by rintro rfl; cases pp.not_dvd_one d)
(λ h, le_trans h $ min_fac_le_of_dvd pp.two_le d),
λ H, or_iff_not_imp_left.2 $ λ n1, H _ (min_fac_prime n1) (min_fac_dvd _)⟩
theorem le_min_fac' {m n : ℕ} : n = 1 ∨ m ≤ min_fac n ↔ ∀ p, 2 ≤ p → p ∣ n → m ≤ p :=
⟨λ h p (pp:1<p) d, h.elim
(by rintro rfl; cases not_le_of_lt pp (le_of_dvd dec_trivial d))
(λ h, le_trans h $ min_fac_le_of_dvd pp d),
λ H, le_min_fac.2 (λ p pp d, H p pp.two_le d)⟩
theorem prime_def_min_fac {p : ℕ} : prime p ↔ 2 ≤ p ∧ min_fac p = p :=
⟨λ pp, ⟨pp.two_le,
let ⟨f2, fd, a⟩ := min_fac_has_prop $ ne_of_gt pp.one_lt in
((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩,
λ ⟨p2, e⟩, e ▸ min_fac_prime (ne_of_gt p2)⟩
@[simp] lemma prime.min_fac_eq {p : ℕ} (hp : prime p) : min_fac p = p :=
(prime_def_min_fac.1 hp).2
/--
This instance is faster in the virtual machine than `decidable_prime_1`,
but slower in the kernel.
If you need to prove that a particular number is prime, in any case
you should not use `dec_trivial`, but rather `by norm_num`, which is
much faster.
-/
instance decidable_prime (p : ℕ) : decidable (prime p) :=
decidable_of_iff' _ prime_def_min_fac
theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : 2 ≤ n) : ¬ prime n ↔ min_fac n < n :=
(not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $
(lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm
lemma min_fac_le_div {n : ℕ} (pos : 0 < n) (np : ¬ prime n) : min_fac n ≤ n / min_fac n :=
match min_fac_dvd n with
| ⟨0, h0⟩ := absurd pos $ by rw [h0, mul_zero]; exact dec_trivial
| ⟨1, h1⟩ :=
begin
rw mul_one at h1,
rw [prime_def_min_fac, not_and_distrib, ← h1, eq_self_iff_true, not_true, or_false,
not_le] at np,
rw [le_antisymm (le_of_lt_succ np) (succ_le_of_lt pos), min_fac_one, nat.div_one]
end
| ⟨(x+2), hx⟩ :=
begin
conv_rhs { congr, rw hx },
rw [nat.mul_div_cancel_left _ (min_fac_pos _)],
exact min_fac_le_of_dvd dec_trivial ⟨min_fac n, by rwa mul_comm⟩
end
end
/--
The square of the smallest prime factor of a composite number `n` is at most `n`.
-/
lemma min_fac_sq_le_self {n : ℕ} (w : 0 < n) (h : ¬ prime n) : (min_fac n)^2 ≤ n :=
have t : (min_fac n) ≤ (n/min_fac n) := min_fac_le_div w h,
calc
(min_fac n)^2 = (min_fac n) * (min_fac n) : sq (min_fac n)
... ≤ (n/min_fac n) * (min_fac n) : nat.mul_le_mul_right (min_fac n) t
... ≤ n : div_mul_le_self n (min_fac n)
@[simp]
lemma min_fac_eq_one_iff {n : ℕ} : min_fac n = 1 ↔ n = 1 :=
begin
split,
{ intro h,
by_contradiction hn,
have := min_fac_prime hn,
rw h at this,
exact not_prime_one this, },
{ rintro rfl, refl, }
end
@[simp]
lemma min_fac_eq_two_iff (n : ℕ) : min_fac n = 2 ↔ 2 ∣ n :=
begin
split,
{ intro h,
convert min_fac_dvd _,
rw h, },
{ intro h,
have ub := min_fac_le_of_dvd (le_refl 2) h,
have lb := min_fac_pos n,
apply ub.eq_or_lt.resolve_right (λ h', _),
have := le_antisymm (nat.succ_le_of_lt lb) (lt_succ_iff.mp h'),
rw [eq_comm, nat.min_fac_eq_one_iff] at this,
subst this,
exact not_lt_of_le (le_of_dvd zero_lt_one h) one_lt_two }
end
end min_fac
theorem exists_dvd_of_not_prime {n : ℕ} (n2 : 2 ≤ n) (np : ¬ prime n) :
∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n :=
⟨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).one_lt,
ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 np⟩
theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : 2 ≤ n) (np : ¬ prime n) :
∃ m, m ∣ n ∧ 2 ≤ m ∧ m < n :=
⟨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).two_le,
(not_prime_iff_min_fac_lt n2).1 np⟩
theorem exists_prime_and_dvd {n : ℕ} (hn : n ≠ 1) : ∃ p, prime p ∧ p ∣ n :=
⟨min_fac n, min_fac_prime hn, min_fac_dvd _⟩
/-- Euclid's theorem on the **infinitude of primes**.
Here given in the form: for every `n`, there exists a prime number `p ≥ n`. -/
theorem exists_infinite_primes (n : ℕ) : ∃ p, n ≤ p ∧ prime p :=
let p := min_fac (n! + 1) in
have f1 : n! + 1 ≠ 1, from ne_of_gt $ succ_lt_succ $ factorial_pos _,
have pp : prime p, from min_fac_prime f1,
have np : n ≤ p, from le_of_not_ge $ λ h,
have h₁ : p ∣ n!, from dvd_factorial (min_fac_pos _) h,
have h₂ : p ∣ 1, from (nat.dvd_add_iff_right h₁).2 (min_fac_dvd _),
pp.not_dvd_one h₂,
⟨p, np, pp⟩
/-- A version of `nat.exists_infinite_primes` using the `bdd_above` predicate. -/
lemma not_bdd_above_set_of_prime : ¬ bdd_above {p | prime p} :=
begin
rw not_bdd_above_iff,
intro n,
obtain ⟨p, hi, hp⟩ := exists_infinite_primes n.succ,
exact ⟨p, hp, hi⟩,
end
/-- A version of `nat.exists_infinite_primes` using the `set.infinite` predicate. -/
lemma infinite_set_of_prime : {p | prime p}.infinite :=
set.infinite_of_not_bdd_above not_bdd_above_set_of_prime
lemma prime.eq_two_or_odd {p : ℕ} (hp : prime p) : p = 2 ∨ p % 2 = 1 :=
p.mod_two_eq_zero_or_one.imp_left
(λ h, ((hp.eq_one_or_self_of_dvd 2 (dvd_of_mod_eq_zero h)).resolve_left dec_trivial).symm)
lemma prime.eq_two_or_odd' {p : ℕ} (hp : prime p) : p = 2 ∨ odd p :=
or.imp_right (λ h, ⟨p / 2, (div_add_mod p 2).symm.trans (congr_arg _ h)⟩) hp.eq_two_or_odd
/-- A prime `p` satisfies `p % 2 = 1` if and only if `p ≠ 2`. -/
lemma prime.mod_two_eq_one_iff_ne_two {p : ℕ} [fact p.prime] : p % 2 = 1 ↔ p ≠ 2 :=
begin
refine ⟨λ h hf, _, (nat.prime.eq_two_or_odd $ fact.out p.prime).resolve_left⟩,
rw hf at h,
simpa using h,
end
theorem coprime_of_dvd {m n : ℕ} (H : ∀ k, prime k → k ∣ m → ¬ k ∣ n) : coprime m n :=
begin
rw [coprime_iff_gcd_eq_one],
by_contra g2,
obtain ⟨p, hp, hpdvd⟩ := exists_prime_and_dvd g2,
apply H p hp; apply dvd_trans hpdvd,
{ exact gcd_dvd_left _ _ },
{ exact gcd_dvd_right _ _ }
end
theorem coprime_of_dvd' {m n : ℕ} (H : ∀ k, prime k → k ∣ m → k ∣ n → k ∣ 1) : coprime m n :=
coprime_of_dvd $ λk kp km kn, not_le_of_gt kp.one_lt $ le_of_dvd zero_lt_one $ H k kp km kn
theorem factors_lemma {k} : (k+2) / min_fac (k+2) < k+2 :=
div_lt_self dec_trivial (min_fac_prime dec_trivial).one_lt
/-- `factors n` is the prime factorization of `n`, listed in increasing order. -/
def factors : ℕ → list ℕ
| 0 := []
| 1 := []
| n@(k+2) :=
let m := min_fac n in have n / m < n := factors_lemma,
m :: factors (n / m)
@[simp] lemma factors_zero : factors 0 = [] := by rw factors
@[simp] lemma factors_one : factors 1 = [] := by rw factors
lemma prime_of_mem_factors : ∀ {n p}, p ∈ factors n → prime p
| 0 := by simp
| 1 := by simp
| n@(k+2) := λ p h,
let m := min_fac n in have n / m < n := factors_lemma,
have h₁ : p = m ∨ p ∈ (factors (n / m)) :=
(list.mem_cons_iff _ _ _).1 (by rwa [factors] at h),
or.cases_on h₁ (λ h₂, h₂.symm ▸ min_fac_prime dec_trivial)
prime_of_mem_factors
lemma pos_of_mem_factors {n p : ℕ} (h : p ∈ factors n) : 0 < p :=
prime.pos (prime_of_mem_factors h)
lemma prod_factors : ∀ {n}, n ≠ 0 → list.prod (factors n) = n
| 0 := by simp
| 1 := by simp
| n@(k+2) := λ h,
let m := min_fac n in have n / m < n := factors_lemma,
show (factors n).prod = n, from
have h₁ : n / m ≠ 0 := λ h,
have n = 0 * m := (nat.div_eq_iff_eq_mul_left (min_fac_pos _) (min_fac_dvd _)).1 h,
by rw zero_mul at this; exact (show k + 2 ≠ 0, from dec_trivial) this,
by rw [factors, list.prod_cons, prod_factors h₁, nat.mul_div_cancel' (min_fac_dvd _)]
lemma factors_prime {p : ℕ} (hp : nat.prime p) : p.factors = [p] :=
begin
have : p = (p - 2) + 2 := (tsub_eq_iff_eq_add_of_le hp.two_le).mp rfl,
rw [this, nat.factors],
simp only [eq.symm this],
have : nat.min_fac p = p := (nat.prime_def_min_fac.mp hp).2,
split,
{ exact this, },
{ simp only [this, nat.factors, nat.div_self (nat.prime.pos hp)], },
end
lemma factors_chain : ∀ {n a}, (∀ p, prime p → p ∣ n → a ≤ p) → list.chain (≤) a (factors n)
| 0 := λ a h, by simp
| 1 := λ a h, by simp
| n@(k+2) := λ a h,
let m := min_fac n in have n / m < n := factors_lemma,
begin
rw factors,
refine list.chain.cons ((le_min_fac.2 h).resolve_left dec_trivial) (factors_chain _),
exact λ p pp d, min_fac_le_of_dvd pp.two_le (d.trans $ div_dvd_of_dvd $ min_fac_dvd _),
end
lemma factors_chain_2 (n) : list.chain (≤) 2 (factors n) := factors_chain $ λ p pp _, pp.two_le
lemma factors_chain' (n) : list.chain' (≤) (factors n) :=
@list.chain'.tail _ _ (_::_) (factors_chain_2 _)
lemma factors_sorted (n : ℕ) : list.sorted (≤) (factors n) :=
(list.chain'_iff_pairwise (@le_trans _ _)).1 (factors_chain' _)
/-- `factors` can be constructed inductively by extracting `min_fac`, for sufficiently large `n`. -/
lemma factors_add_two (n : ℕ) :
factors (n+2) = min_fac (n+2) :: factors ((n+2) / min_fac (n+2)) :=
by rw factors
@[simp]
lemma factors_eq_nil (n : ℕ) : n.factors = [] ↔ n = 0 ∨ n = 1 :=
begin
split; intro h,
{ rcases n with (_ | _ | n),
{ exact or.inl rfl },
{ exact or.inr rfl },
{ rw factors at h, injection h }, },
{ rcases h with (rfl | rfl),
{ exact factors_zero },
{ exact factors_one }, }
end
lemma eq_of_perm_factors {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) (h : a.factors ~ b.factors) : a = b :=
by simpa [prod_factors ha, prod_factors hb] using list.perm.prod_eq h
theorem prime.coprime_iff_not_dvd {p n : ℕ} (pp : prime p) : coprime p n ↔ ¬ p ∣ n :=
⟨λ co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]),
λ nd, coprime_of_dvd $ λ m m2 mp, ((prime_dvd_prime_iff_eq m2 pp).1 mp).symm ▸ nd⟩
theorem prime.dvd_iff_not_coprime {p n : ℕ} (pp : prime p) : p ∣ n ↔ ¬ coprime p n :=
iff_not_comm.2 pp.coprime_iff_not_dvd
theorem prime.not_coprime_iff_dvd {m n : ℕ} :
¬ coprime m n ↔ ∃p, prime p ∧ p ∣ m ∧ p ∣ n :=
begin
apply iff.intro,
{ intro h,
exact ⟨min_fac (gcd m n), min_fac_prime h,
((min_fac_dvd (gcd m n)).trans (gcd_dvd_left m n)),
((min_fac_dvd (gcd m n)).trans (gcd_dvd_right m n))⟩ },
{ intro h,
cases h with p hp,
apply nat.not_coprime_of_dvd_of_dvd (prime.one_lt hp.1) hp.2.1 hp.2.2 }
end
theorem prime.dvd_mul {p m n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n :=
⟨λ H, or_iff_not_imp_left.2 $ λ h,
(pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H,
or.rec (λ h : p ∣ m, h.mul_right _) (λ h : p ∣ n, h.mul_left _)⟩
theorem prime.not_dvd_mul {p m n : ℕ} (pp : prime p)
(Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) : ¬ p ∣ m * n :=
mt pp.dvd_mul.1 $ by simp [Hm, Hn]
theorem prime_iff {p : ℕ} : p.prime ↔ _root_.prime p :=
⟨λ h, ⟨h.ne_zero, h.not_unit, λ a b, h.dvd_mul.mp⟩, prime.irreducible⟩
theorem irreducible_iff_prime {p : ℕ} : irreducible p ↔ _root_.prime p :=
by rw [←prime_iff, prime]
theorem prime.dvd_of_dvd_pow {p m n : ℕ} (pp : prime p) (h : p ∣ m^n) : p ∣ m :=
begin
induction n with n IH,
{ exact pp.not_dvd_one.elim h },
{ rw pow_succ at h, exact (pp.dvd_mul.1 h).elim id IH }
end
lemma prime.pow_not_prime {x n : ℕ} (hn : 2 ≤ n) : ¬ (x ^ n).prime :=
λ hp, (hp.eq_one_or_self_of_dvd x $ dvd_trans ⟨x, sq _⟩ (pow_dvd_pow _ hn)).elim
(λ hx1, hp.ne_one $ hx1.symm ▸ one_pow _)
(λ hxn, lt_irrefl x $ calc x = x ^ 1 : (pow_one _).symm
... < x ^ n : nat.pow_right_strict_mono (hxn.symm ▸ hp.two_le) hn
... = x : hxn.symm)
lemma prime.pow_not_prime' {x : ℕ} : ∀ {n : ℕ}, n ≠ 1 → ¬ (x ^ n).prime
| 0 := λ _, not_prime_one
| 1 := λ h, (h rfl).elim
| (n+2) := λ _, prime.pow_not_prime le_add_self
lemma prime.eq_one_of_pow {x n : ℕ} (h : (x ^ n).prime) : n = 1 :=
not_imp_not.mp prime.pow_not_prime' h
lemma prime.pow_eq_iff {p a k : ℕ} (hp : p.prime) : a ^ k = p ↔ a = p ∧ k = 1 :=
begin
refine ⟨λ h, _, λ h, by rw [h.1, h.2, pow_one]⟩,
rw ←h at hp,
rw [←h, hp.eq_one_of_pow, eq_self_iff_true, and_true, pow_one],
end
lemma pow_min_fac {n k : ℕ} (hk : k ≠ 0) : (n^k).min_fac = n.min_fac :=
begin
rcases eq_or_ne n 1 with rfl | hn,
{ simp },
have hnk : n ^ k ≠ 1 := λ hk', hn ((pow_eq_one_iff hk).1 hk'),
apply (min_fac_le_of_dvd (min_fac_prime hn).two_le ((min_fac_dvd n).pow hk)).antisymm,
apply min_fac_le_of_dvd (min_fac_prime hnk).two_le
((min_fac_prime hnk).dvd_of_dvd_pow (min_fac_dvd _)),
end
lemma prime.pow_min_fac {p k : ℕ} (hp : p.prime) (hk : k ≠ 0) : (p^k).min_fac = p :=
by rw [pow_min_fac hk, hp.min_fac_eq]
lemma prime.mul_eq_prime_sq_iff {x y p : ℕ} (hp : p.prime) (hx : x ≠ 1) (hy : y ≠ 1) :
x * y = p ^ 2 ↔ x = p ∧ y = p :=
⟨λ h, have pdvdxy : p ∣ x * y, by rw h; simp [sq],
begin
wlog := hp.dvd_mul.1 pdvdxy using x y,
cases case with a ha,
have hap : a ∣ p, from ⟨y, by rwa [ha, sq,
mul_assoc, nat.mul_right_inj hp.pos, eq_comm] at h⟩,
exact ((nat.dvd_prime hp).1 hap).elim
(λ _, by clear_aux_decl; simp [*, sq, nat.mul_right_inj hp.pos] at *
{contextual := tt})
(λ _, by clear_aux_decl; simp [*, sq, mul_comm, mul_assoc,
nat.mul_right_inj hp.pos, nat.mul_right_eq_self_iff hp.pos] at *
{contextual := tt})
end,
λ ⟨h₁, h₂⟩, h₁.symm ▸ h₂.symm ▸ (sq _).symm⟩
lemma prime.dvd_factorial : ∀ {n p : ℕ} (hp : prime p), p ∣ n! ↔ p ≤ n
| 0 p hp := iff_of_false hp.not_dvd_one (not_le_of_lt hp.pos)
| (n+1) p hp := begin
rw [factorial_succ, hp.dvd_mul, prime.dvd_factorial hp],
exact ⟨λ h, h.elim (le_of_dvd (succ_pos _)) le_succ_of_le,
λ h, (_root_.lt_or_eq_of_le h).elim (or.inr ∘ le_of_lt_succ)
(λ h, or.inl $ by rw h)⟩
end
theorem prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : prime p) (h : ¬ p ∣ a) : coprime a (p^m) :=
(pp.coprime_iff_not_dvd.2 h).symm.pow_right _
theorem coprime_primes {p q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q :=
pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_two_le pq pp.two_le
theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) :
coprime (p^n) (q^m) :=
((coprime_primes pp pq).2 h).pow _ _
theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i :=
by rw [pp.dvd_iff_not_coprime]; apply em
lemma coprime_of_lt_prime {n p} (n_pos : 0 < n) (hlt : n < p) (pp : prime p) :
coprime p n :=
(coprime_or_dvd_of_prime pp n).resolve_right $ λ h, lt_le_antisymm hlt (le_of_dvd n_pos h)
lemma eq_or_coprime_of_le_prime {n p} (n_pos : 0 < n) (hle : n ≤ p) (pp : prime p) :
p = n ∨ coprime p n :=
hle.eq_or_lt.imp eq.symm (λ h, coprime_of_lt_prime n_pos h pp)
theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m i : ℕ} : i ∣ (p^m) ↔ ∃ k ≤ m, i = p^k :=
by simp_rw [dvd_prime_pow (prime_iff.mp pp) m, associated_eq_eq]
lemma prime.dvd_mul_of_dvd_ne {p1 p2 n : ℕ} (h_neq : p1 ≠ p2) (pp1 : prime p1) (pp2 : prime p2)
(h1 : p1 ∣ n) (h2 : p2 ∣ n) : (p1 * p2 ∣ n) :=
coprime.mul_dvd_of_dvd_of_dvd ((coprime_primes pp1 pp2).mpr h_neq) h1 h2
/--
If `p` is prime,
and `a` doesn't divide `p^k`, but `a` does divide `p^(k+1)`
then `a = p^(k+1)`.
-/
lemma eq_prime_pow_of_dvd_least_prime_pow
{a p k : ℕ} (pp : prime p) (h₁ : ¬(a ∣ p^k)) (h₂ : a ∣ p^(k+1)) :
a = p^(k+1) :=
begin
obtain ⟨l, ⟨h, rfl⟩⟩ := (dvd_prime_pow pp).1 h₂,
congr,
exact le_antisymm h (not_le.1 ((not_congr (pow_dvd_pow_iff_le_right (prime.one_lt pp))).1 h₁)),
end
lemma ne_one_iff_exists_prime_dvd : ∀ {n}, n ≠ 1 ↔ ∃ p : ℕ, p.prime ∧ p ∣ n
| 0 := by simpa using (Exists.intro 2 nat.prime_two)
| 1 := by simp [nat.not_prime_one]
| (n+2) :=
let a := n+2 in
let ha : a ≠ 1 := nat.succ_succ_ne_one n in
begin
simp only [true_iff, ne.def, not_false_iff, ha],
exact ⟨a.min_fac, nat.min_fac_prime ha, a.min_fac_dvd⟩,
end
lemma eq_one_iff_not_exists_prime_dvd {n : ℕ} : n = 1 ↔ ∀ p : ℕ, p.prime → ¬p ∣ n :=
by simpa using not_iff_not.mpr ne_one_iff_exists_prime_dvd
section
open list
lemma mem_factors_iff_dvd {n p : ℕ} (hn : n ≠ 0) (hp : prime p) : p ∈ factors n ↔ p ∣ n :=
⟨λ h, prod_factors hn ▸ list.dvd_prod h,
λ h, mem_list_primes_of_dvd_prod
(prime_iff.mp hp)
(λ p h, prime_iff.mp (prime_of_mem_factors h))
((prod_factors hn).symm ▸ h)⟩
lemma dvd_of_mem_factors {n p : ℕ} (h : p ∈ n.factors) : p ∣ n :=
begin
rcases n.eq_zero_or_pos with rfl | hn,
{ exact dvd_zero p },
{ rwa ←mem_factors_iff_dvd hn.ne' (prime_of_mem_factors h) }
end
lemma mem_factors {n p} (hn : n ≠ 0) : p ∈ factors n ↔ prime p ∧ p ∣ n :=
⟨λ h, ⟨prime_of_mem_factors h, dvd_of_mem_factors h⟩,
λ ⟨hprime, hdvd⟩, (mem_factors_iff_dvd hn hprime).mpr hdvd⟩
lemma le_of_mem_factors {n p : ℕ} (h : p ∈ n.factors) : p ≤ n :=
begin
rcases n.eq_zero_or_pos with rfl | hn,
{ rw factors_zero at h, cases h },
{ exact le_of_dvd hn (dvd_of_mem_factors h) },
end
/-- **Fundamental theorem of arithmetic**-/
lemma factors_unique {n : ℕ} {l : list ℕ} (h₁ : prod l = n) (h₂ : ∀ p ∈ l, prime p) :
l ~ factors n :=
begin
refine perm_of_prod_eq_prod _ _ _,
{ rw h₁,
refine (prod_factors _).symm,
rintro rfl,
rw prod_eq_zero_iff at h₁,
exact prime.ne_zero (h₂ 0 h₁) rfl },
{ simp_rw ←prime_iff, exact h₂ },
{ simp_rw ←prime_iff, exact (λ p, prime_of_mem_factors) },
end
lemma prime.factors_pow {p : ℕ} (hp : p.prime) (n : ℕ) :
(p ^ n).factors = list.repeat p n :=
begin
symmetry,
rw ← list.repeat_perm,
apply nat.factors_unique (list.prod_repeat p n),
intros q hq,
rwa eq_of_mem_repeat hq,
end
lemma eq_prime_pow_of_unique_prime_dvd {n p : ℕ} (hpos : n ≠ 0)
(h : ∀ {d}, nat.prime d → d ∣ n → d = p) :
n = p ^ n.factors.length :=
begin
set k := n.factors.length,
rw [←prod_factors hpos, ←prod_repeat p k,
eq_repeat_of_mem (λ d hd, h (prime_of_mem_factors hd) (dvd_of_mem_factors hd))],
end
/-- For positive `a` and `b`, the prime factors of `a * b` are the union of those of `a` and `b` -/
lemma perm_factors_mul {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) :
(a * b).factors ~ a.factors ++ b.factors :=
begin
refine (factors_unique _ _).symm,
{ rw [list.prod_append, prod_factors ha, prod_factors hb] },
{ intros p hp,
rw list.mem_append at hp,
cases hp;
exact prime_of_mem_factors hp },
end
/-- For coprime `a` and `b`, the prime factors of `a * b` are the union of those of `a` and `b` -/
lemma perm_factors_mul_of_coprime {a b : ℕ} (hab : coprime a b) :
(a * b).factors ~ a.factors ++ b.factors :=
begin
rcases a.eq_zero_or_pos with rfl | ha,
{ simp [(coprime_zero_left _).mp hab] },
rcases b.eq_zero_or_pos with rfl | hb,
{ simp [(coprime_zero_right _).mp hab] },
exact perm_factors_mul ha.ne' hb.ne',
end
lemma factors_sublist_right {n k : ℕ} (h : k ≠ 0) : n.factors <+ (n * k).factors :=
begin
cases n,
{ rw zero_mul },
apply sublist_of_subperm_of_sorted _ (factors_sorted _) (factors_sorted _),
rw (perm_factors_mul n.succ_ne_zero h).subperm_left,
exact (sublist_append_left _ _).subperm,
end
lemma factors_sublist_of_dvd {n k : ℕ} (h : n ∣ k) (h' : k ≠ 0) : n.factors <+ k.factors :=
begin
obtain ⟨a, rfl⟩ := h,
exact factors_sublist_right (right_ne_zero_of_mul h'),
end
lemma factors_subset_right {n k : ℕ} (h : k ≠ 0) : n.factors ⊆ (n * k).factors :=
(factors_sublist_right h).subset
lemma factors_subset_of_dvd {n k : ℕ} (h : n ∣ k) (h' : k ≠ 0) : n.factors ⊆ k.factors :=
(factors_sublist_of_dvd h h').subset
lemma dvd_of_factors_subperm {a b : ℕ} (ha : a ≠ 0) (h : a.factors <+~ b.factors) : a ∣ b :=
begin
rcases b.eq_zero_or_pos with rfl | hb,
{ exact dvd_zero _ },
rcases a with (_|_|a),
{ exact (ha rfl).elim },
{ exact one_dvd _ },
use (b.factors.diff a.succ.succ.factors).prod,
nth_rewrite 0 ←nat.prod_factors ha,
rw [←list.prod_append,
list.perm.prod_eq $ list.subperm_append_diff_self_of_count_le $ list.subperm_ext_iff.mp h,
nat.prod_factors hb.ne']
end
end
lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : prime p) {m n k l : ℕ}
(hpm : p ^ k ∣ m) (hpn : p ^ l ∣ n) (hpmn : p ^ (k+l+1) ∣ m*n) :
p ^ (k+1) ∣ m ∨ p ^ (l+1) ∣ n :=
have hpd : p^(k+l)*p ∣ m*n, by rwa pow_succ' at hpmn,
have hpd2 : p ∣ (m*n) / p ^ (k+l), from dvd_div_of_mul_dvd hpd,
have hpd3 : p ∣ (m*n) / (p^k * p^l), by simpa [pow_add] using hpd2,
have hpd4 : p ∣ (m / p^k) * (n / p^l), by simpa [nat.div_mul_div_comm hpm hpn] using hpd3,
have hpd5 : p ∣ (m / p^k) ∨ p ∣ (n / p^l), from (prime.dvd_mul p_prime).1 hpd4,
suffices p^k*p ∣ m ∨ p^l*p ∣ n, by rwa [pow_succ', pow_succ'],
hpd5.elim
(assume : p ∣ m / p ^ k, or.inl $ mul_dvd_of_dvd_div hpm this)
(assume : p ∣ n / p ^ l, or.inr $ mul_dvd_of_dvd_div hpn this)
lemma prime_iff_prime_int {p : ℕ} : p.prime ↔ _root_.prime (p : ℤ) :=
⟨λ hp, ⟨int.coe_nat_ne_zero_iff_pos.2 hp.pos, mt int.is_unit_iff_nat_abs_eq.1 hp.ne_one,
λ a b h, by rw [← int.dvd_nat_abs, int.coe_nat_dvd, int.nat_abs_mul, hp.dvd_mul] at h;
rwa [← int.dvd_nat_abs, int.coe_nat_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd]⟩,
λ hp, nat.prime_iff.2 ⟨int.coe_nat_ne_zero.1 hp.1,
mt nat.is_unit_iff.1 $ λ h, by simpa [h, not_prime_one] using hp,
λ a b, by simpa only [int.coe_nat_dvd, (int.coe_nat_mul _ _).symm] using hp.2.2 a b⟩⟩
/-- The type of prime numbers -/
def primes := {p : ℕ // p.prime}
namespace primes
instance : has_repr nat.primes := ⟨λ p, repr p.val⟩
instance inhabited_primes : inhabited primes := ⟨⟨2, prime_two⟩⟩
instance coe_nat : has_coe nat.primes ℕ := ⟨subtype.val⟩
theorem coe_nat_inj (p q : nat.primes) : (p : ℕ) = (q : ℕ) → p = q :=
λ h, subtype.eq h
end primes
instance monoid.prime_pow {α : Type*} [monoid α] : has_pow α primes := ⟨λ x p, x^p.val⟩
end nat
/-! ### Primality prover -/
open norm_num
namespace tactic
namespace norm_num
lemma is_prime_helper (n : ℕ)
(h₁ : 1 < n) (h₂ : nat.min_fac n = n) : nat.prime n :=
nat.prime_def_min_fac.2 ⟨h₁, h₂⟩
lemma min_fac_bit0 (n : ℕ) : nat.min_fac (bit0 n) = 2 :=
by simp [nat.min_fac_eq, show 2 ∣ bit0 n, by simp [bit0_eq_two_mul n]]
/-- A predicate representing partial progress in a proof of `min_fac`. -/
def min_fac_helper (n k : ℕ) : Prop :=
0 < k ∧ bit1 k ≤ nat.min_fac (bit1 n)
theorem min_fac_helper.n_pos {n k : ℕ} (h : min_fac_helper n k) : 0 < n :=
pos_iff_ne_zero.2 $ λ e,
by rw e at h; exact not_le_of_lt (nat.bit1_lt h.1) h.2
lemma min_fac_ne_bit0 {n k : ℕ} : nat.min_fac (bit1 n) ≠ bit0 k :=
begin
rw bit0_eq_two_mul,
refine (λ e, absurd ((nat.dvd_add_iff_right _).2
(dvd_trans ⟨_, e⟩ (nat.min_fac_dvd _))) _); simp
end
lemma min_fac_helper_0 (n : ℕ) (h : 0 < n) : min_fac_helper n 1 :=
begin
refine ⟨zero_lt_one, lt_of_le_of_ne _ min_fac_ne_bit0.symm⟩,
rw nat.succ_le_iff,
refine lt_of_le_of_ne (nat.min_fac_pos _) (λ e, nat.not_prime_one _),
rw e,
exact nat.min_fac_prime (nat.bit1_lt h).ne',
end
lemma min_fac_helper_1 {n k k' : ℕ} (e : k + 1 = k')
(np : nat.min_fac (bit1 n) ≠ bit1 k)
(h : min_fac_helper n k) : min_fac_helper n k' :=
begin
rw ← e,
refine ⟨nat.succ_pos _,
(lt_of_le_of_ne (lt_of_le_of_ne _ _ : k+1+k < _)
min_fac_ne_bit0.symm : bit0 (k+1) < _)⟩,
{ rw add_right_comm, exact h.2 },
{ rw add_right_comm, exact np.symm }
end
lemma min_fac_helper_2 (n k k' : ℕ) (e : k + 1 = k')
(np : ¬ nat.prime (bit1 k)) (h : min_fac_helper n k) : min_fac_helper n k' :=
begin
refine min_fac_helper_1 e _ h,
intro e₁, rw ← e₁ at np,
exact np (nat.min_fac_prime $ ne_of_gt $ nat.bit1_lt h.n_pos)
end
lemma min_fac_helper_3 (n k k' c : ℕ) (e : k + 1 = k')
(nc : bit1 n % bit1 k = c) (c0 : 0 < c)
(h : min_fac_helper n k) : min_fac_helper n k' :=
begin
refine min_fac_helper_1 e _ h,
refine mt _ (ne_of_gt c0), intro e₁,
rw [← nc, ← nat.dvd_iff_mod_eq_zero, ← e₁],
apply nat.min_fac_dvd
end
lemma min_fac_helper_4 (n k : ℕ) (hd : bit1 n % bit1 k = 0)
(h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 k :=
by { rw ← nat.dvd_iff_mod_eq_zero at hd,
exact le_antisymm (nat.min_fac_le_of_dvd (nat.bit1_lt h.1) hd) h.2 }
lemma min_fac_helper_5 (n k k' : ℕ) (e : bit1 k * bit1 k = k')
(hd : bit1 n < k') (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 n :=
begin
refine (nat.prime_def_min_fac.1 (nat.prime_def_le_sqrt.2
⟨nat.bit1_lt h.n_pos, _⟩)).2,
rw ← e at hd,
intros m m2 hm md,
have := le_trans h.2 (le_trans (nat.min_fac_le_of_dvd m2 md) hm),
rw nat.le_sqrt at this,
exact not_le_of_lt hd this
end
/-- Given `e` a natural numeral and `d : nat` a factor of it, return `⊢ ¬ prime e`. -/
meta def prove_non_prime (e : expr) (n d₁ : ℕ) : tactic expr :=
do let e₁ := reflect d₁,
c ← mk_instance_cache `(nat),
(c, p₁) ← prove_lt_nat c `(1) e₁,
let d₂ := n / d₁, let e₂ := reflect d₂,
(c, e', p) ← prove_mul_nat c e₁ e₂,
guard (e' =ₐ e),
(c, p₂) ← prove_lt_nat c `(1) e₂,
return $ `(@nat.not_prime_mul').mk_app [e₁, e₂, e, p, p₁, p₂]
/-- Given `a`,`a1 := bit1 a`, `n1` the value of `a1`, `b` and `p : min_fac_helper a b`,
returns `(c, ⊢ min_fac a1 = c)`. -/
meta def prove_min_fac_aux (a a1 : expr) (n1 : ℕ) :
instance_cache → expr → expr → tactic (instance_cache × expr × expr)
| ic b p := do
k ← b.to_nat,
let k1 := bit1 k,
let b1 := `(bit1:ℕ→ℕ).mk_app [b],
if n1 < k1*k1 then do
(ic, e', p₁) ← prove_mul_nat ic b1 b1,
(ic, p₂) ← prove_lt_nat ic a1 e',
return (ic, a1, `(min_fac_helper_5).mk_app [a, b, e', p₁, p₂, p])
else let d := k1.min_fac in
if to_bool (d < k1) then do
let k' := k+1, let e' := reflect k',
(ic, p₁) ← prove_succ ic b e',
p₂ ← prove_non_prime b1 k1 d,
prove_min_fac_aux ic e' $ `(min_fac_helper_2).mk_app [a, b, e', p₁, p₂, p]
else do
let nc := n1 % k1,
(ic, c, pc) ← prove_div_mod ic a1 b1 tt,
if nc = 0 then
return (ic, b1, `(min_fac_helper_4).mk_app [a, b, pc, p])
else do
(ic, p₀) ← prove_pos ic c,
let k' := k+1, let e' := reflect k',
(ic, p₁) ← prove_succ ic b e',
prove_min_fac_aux ic e' $ `(min_fac_helper_3).mk_app [a, b, e', c, p₁, pc, p₀, p]
/-- Given `a` a natural numeral, returns `(b, ⊢ min_fac a = b)`. -/
meta def prove_min_fac (ic : instance_cache) (e : expr) : tactic (instance_cache × expr × expr) :=
match match_numeral e with
| match_numeral_result.zero := return (ic, `(2:ℕ), `(nat.min_fac_zero))
| match_numeral_result.one := return (ic, `(1:ℕ), `(nat.min_fac_one))
| match_numeral_result.bit0 e := return (ic, `(2), `(min_fac_bit0).mk_app [e])
| match_numeral_result.bit1 e := do
n ← e.to_nat,
c ← mk_instance_cache `(nat),
(c, p) ← prove_pos c e,
let a1 := `(bit1:ℕ→ℕ).mk_app [e],
prove_min_fac_aux e a1 (bit1 n) c `(1) (`(min_fac_helper_0).mk_app [e, p])
| _ := failed
end
/-- A partial proof of `factors`. Asserts that `l` is a sorted list of primes, lower bounded by a
prime `p`, which multiplies to `n`. -/
def factors_helper (n p : ℕ) (l : list ℕ) : Prop :=
p.prime → list.chain (≤) p l ∧ (∀ a ∈ l, nat.prime a) ∧ list.prod l = n
lemma factors_helper_nil (a : ℕ) : factors_helper 1 a [] :=
λ pa, ⟨list.chain.nil, by rintro _ ⟨⟩, list.prod_nil⟩
lemma factors_helper_cons' (n m a b : ℕ) (l : list ℕ)
(h₁ : b * m = n) (h₂ : a ≤ b) (h₃ : nat.min_fac b = b)
(H : factors_helper m b l) : factors_helper n a (b :: l) :=
λ pa,
have pb : b.prime, from nat.prime_def_min_fac.2 ⟨le_trans pa.two_le h₂, h₃⟩,
let ⟨f₁, f₂, f₃⟩ := H pb in
⟨list.chain.cons h₂ f₁, λ c h, h.elim (λ e, e.symm ▸ pb) (f₂ _),
by rw [list.prod_cons, f₃, h₁]⟩
lemma factors_helper_cons (n m a b : ℕ) (l : list ℕ)
(h₁ : b * m = n) (h₂ : a < b) (h₃ : nat.min_fac b = b)
(H : factors_helper m b l) : factors_helper n a (b :: l) :=
factors_helper_cons' _ _ _ _ _ h₁ h₂.le h₃ H
lemma factors_helper_sn (n a : ℕ) (h₁ : a < n) (h₂ : nat.min_fac n = n) : factors_helper n a [n] :=
factors_helper_cons _ _ _ _ _ (mul_one _) h₁ h₂ (factors_helper_nil _)
lemma factors_helper_same (n m a : ℕ) (l : list ℕ) (h : a * m = n)
(H : factors_helper m a l) : factors_helper n a (a :: l) :=
λ pa, factors_helper_cons' _ _ _ _ _ h le_rfl (nat.prime_def_min_fac.1 pa).2 H pa
lemma factors_helper_same_sn (a : ℕ) : factors_helper a a [a] :=
factors_helper_same _ _ _ _ (mul_one _) (factors_helper_nil _)
lemma factors_helper_end (n : ℕ) (l : list ℕ) (H : factors_helper n 2 l) : nat.factors n = l :=
let ⟨h₁, h₂, h₃⟩ := H nat.prime_two in
have _, from (list.chain'_iff_pairwise (@le_trans _ _)).1 (@list.chain'.tail _ _ (_::_) h₁),
(list.eq_of_perm_of_sorted (nat.factors_unique h₃ h₂) this (nat.factors_sorted _)).symm
/-- Given `n` and `a` natural numerals, returns `(l, ⊢ factors_helper n a l)`. -/
meta def prove_factors_aux :
instance_cache → expr → expr → ℕ → ℕ → tactic (instance_cache × expr × expr)
| c en ea n a :=
let b := n.min_fac in
if b < n then do
let m := n / b,
(c, em) ← c.of_nat m,
if b = a then do
(c, _, p₁) ← prove_mul_nat c ea em,
(c, l, p₂) ← prove_factors_aux c em ea m a,
pure (c, `(%%ea::%%l:list ℕ), `(factors_helper_same).mk_app [en, em, ea, l, p₁, p₂])
else do
(c, eb) ← c.of_nat b,
(c, _, p₁) ← prove_mul_nat c eb em,
(c, p₂) ← prove_lt_nat c ea eb,
(c, _, p₃) ← prove_min_fac c eb,
(c, l, p₄) ← prove_factors_aux c em eb m b,
pure (c, `(%%eb::%%l : list ℕ),
`(factors_helper_cons).mk_app [en, em, ea, eb, l, p₁, p₂, p₃, p₄])
else if b = a then
pure (c, `([%%ea] : list ℕ), `(factors_helper_same_sn).mk_app [ea])
else do
(c, p₁) ← prove_lt_nat c ea en,
(c, _, p₂) ← prove_min_fac c en,
pure (c, `([%%en] : list ℕ), `(factors_helper_sn).mk_app [en, ea, p₁, p₂])
/-- Evaluates the `prime` and `min_fac` functions. -/
@[norm_num] meta def eval_prime : expr → tactic (expr × expr)
| `(nat.prime %%e) := do
n ← e.to_nat,
match n with
| 0 := false_intro `(nat.not_prime_zero)
| 1 := false_intro `(nat.not_prime_one)
| _ := let d₁ := n.min_fac in
if d₁ < n then prove_non_prime e n d₁ >>= false_intro
else do
let e₁ := reflect d₁,
c ← mk_instance_cache `(ℕ),
(c, p₁) ← prove_lt_nat c `(1) e₁,
(c, e₁, p) ← prove_min_fac c e,
true_intro $ `(is_prime_helper).mk_app [e, p₁, p]
end
| `(nat.min_fac %%e) := do
ic ← mk_instance_cache `(ℕ),
prod.snd <$> prove_min_fac ic e
| `(nat.factors %%e) := do
n ← e.to_nat,
match n with
| 0 := pure (`(@list.nil ℕ), `(nat.factors_zero))
| 1 := pure (`(@list.nil ℕ), `(nat.factors_one))
| _ := do
c ← mk_instance_cache `(ℕ),
(c, l, p) ← prove_factors_aux c e `(2) n 2,
pure (l, `(factors_helper_end).mk_app [e, l, p])
end
| _ := failed
end norm_num
end tactic
namespace nat
theorem prime_three : prime 3 := by norm_num
instance fact_prime_two : fact (prime 2) := ⟨prime_two⟩
instance fact_prime_three : fact (prime 3) := ⟨prime_three⟩
end nat
namespace nat
lemma mem_factors_mul {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) {p : ℕ} :
p ∈ (a * b).factors ↔ p ∈ a.factors ∨ p ∈ b.factors :=
begin
rw [mem_factors (mul_ne_zero ha hb), mem_factors ha, mem_factors hb, ←and_or_distrib_left],
simpa only [and.congr_right_iff] using prime.dvd_mul
end
/-- If `a`, `b` are positive, the prime divisors of `a * b` are the union of those of `a` and `b` -/
lemma factors_mul_to_finset {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) :
(a * b).factors.to_finset = a.factors.to_finset ∪ b.factors.to_finset :=
(list.to_finset.ext $ λ x, (mem_factors_mul ha hb).trans list.mem_union.symm).trans $
list.to_finset_union _ _
lemma pow_succ_factors_to_finset (n k : ℕ) :
(n^(k+1)).factors.to_finset = n.factors.to_finset :=
begin
rcases eq_or_ne n 0 with rfl | hn,
{ simp },
induction k with k ih,
{ simp },
rw [pow_succ, factors_mul_to_finset hn (pow_ne_zero _ hn), ih, finset.union_idempotent]
end
lemma pow_factors_to_finset (n : ℕ) {k : ℕ} (hk : k ≠ 0) :
(n^k).factors.to_finset = n.factors.to_finset :=
begin
cases k,
{ simpa using hk },
rw pow_succ_factors_to_finset
end
/-- The only prime divisor of positive prime power `p^k` is `p` itself -/
lemma prime_pow_prime_divisor {p k : ℕ} (hk : k ≠ 0) (hp : prime p) :
(p^k).factors.to_finset = {p} :=
by simp [pow_factors_to_finset p hk, factors_prime hp]
/-- The sets of factors of coprime `a` and `b` are disjoint -/
lemma coprime_factors_disjoint {a b : ℕ} (hab : a.coprime b) : list.disjoint a.factors b.factors :=
begin
intros q hqa hqb,
apply not_prime_one,
rw ←(eq_one_of_dvd_coprimes hab (dvd_of_mem_factors hqa) (dvd_of_mem_factors hqb)),
exact prime_of_mem_factors hqa
end
lemma mem_factors_mul_of_coprime {a b : ℕ} (hab : coprime a b) (p : ℕ):
p ∈ (a * b).factors ↔ p ∈ a.factors ∪ b.factors :=
begin
rcases a.eq_zero_or_pos with rfl | ha,
{ simp [(coprime_zero_left _).mp hab] },
rcases b.eq_zero_or_pos with rfl | hb,
{ simp [(coprime_zero_right _).mp hab] },
rw [mem_factors_mul ha.ne' hb.ne', list.mem_union]
end
lemma factors_mul_to_finset_of_coprime {a b : ℕ} (hab : coprime a b) :
(a * b).factors.to_finset = a.factors.to_finset ∪ b.factors.to_finset :=
(list.to_finset.ext $ mem_factors_mul_of_coprime hab).trans $ list.to_finset_union _ _
open list
/-- If `p` is a prime factor of `a` then `p` is also a prime factor of `a * b` for any `b > 0` -/
lemma mem_factors_mul_left {p a b : ℕ} (hpa : p ∈ a.factors) (hb : b ≠ 0) : p ∈ (a*b).factors :=
begin
rcases eq_or_ne a 0 with rfl | ha,
{ simpa using hpa },
apply (mem_factors_mul ha hb).2 (or.inl hpa),
end
/-- If `p` is a prime factor of `b` then `p` is also a prime factor of `a * b` for any `a > 0` -/
lemma mem_factors_mul_right {p a b : ℕ} (hpb : p ∈ b.factors) (ha : a ≠ 0) : p ∈ (a*b).factors :=
by { rw mul_comm, exact mem_factors_mul_left hpb ha }
lemma eq_two_pow_or_exists_odd_prime_and_dvd (n : ℕ) :
(∃ k : ℕ, n = 2 ^ k) ∨ ∃ p, nat.prime p ∧ p ∣ n ∧ odd p :=
(eq_or_ne n 0).elim
(λ hn, (or.inr ⟨3, prime_three, hn.symm ▸ dvd_zero 3, ⟨1, rfl⟩⟩))
(λ hn, or_iff_not_imp_right.mpr
(λ H, ⟨n.factors.length, eq_prime_pow_of_unique_prime_dvd hn
(λ p hprime hdvd, hprime.eq_two_or_odd'.resolve_right
(λ hodd, H ⟨p, hprime, hdvd, hodd⟩))⟩))
end nat
namespace int
lemma prime_two : prime (2 : ℤ) := nat.prime_iff_prime_int.mp nat.prime_two
lemma prime_three : prime (3 : ℤ) := nat.prime_iff_prime_int.mp nat.prime_three
end int
section
open finset
/-- Exactly `n / p` naturals in `[1, n]` are multiples of `p`. -/
lemma card_multiples (n p : ℕ) : card ((range n).filter (λ e, p ∣ e + 1)) = n / p :=
begin
induction n with n hn,
{ rw [nat.zero_div, range_zero, filter_empty, card_empty] },
{ rw [nat.succ_div, add_ite, add_zero, range_succ, filter_insert, apply_ite card,
card_insert_of_not_mem (mem_filter.not.mpr (not_and_of_not_left _ not_mem_range_self)), hn] }
end
end
|
e6a04bfbc1f8b53509562c028675b97c92a65799 | 4fa118f6209450d4e8d058790e2967337811b2b5 | /src/valuation/field.lean | f7b42157320988212657fd3c12bc31734de8dd4c | [
"Apache-2.0"
] | permissive | leanprover-community/lean-perfectoid-spaces | 16ab697a220ed3669bf76311daa8c466382207f7 | 95a6520ce578b30a80b4c36e36ab2d559a842690 | refs/heads/master | 1,639,557,829,139 | 1,638,797,866,000 | 1,638,797,866,000 | 135,769,296 | 96 | 10 | Apache-2.0 | 1,638,797,866,000 | 1,527,892,754,000 | Lean | UTF-8 | Lean | false | false | 14,662 | lean | import for_mathlib.topological_field
import for_mathlib.topology
import for_mathlib.uniform_space.uniform_field
import valuation.topology
import valuation.with_zero_topology
import topology.algebra.ordered
/-!
In this file we study the topology of a field `K` endowed with a valuation (in our application
to adic spaces, `K` will be the valuation field associated to some valuation on a ring, defined in
valuation.basic).
We already know from valuation.topology that one can build a topology on `K` which
makes it a topological ring.
The first goal is to show `K` is a topological *field*, ie inversion is continuous
at every non-zero element.
The next goal is to prove `K` is a *completable* topological field. This gives us
a completion `hat K` which is a topological field. We also prove that `K` is automatically
separated, so the map from `K` to `hat K` is injective.
Then we extend the valuation given on `K` to a valuation on `hat K`.
-/
open filter set linear_ordered_structure
local attribute [instance, priority 0] classical.DLO
local notation `𝓝` x: 70 := nhds x
section division_ring
variables {K : Type*} [division_ring K]
section valuation_topological_division_ring
section inversion_estimate
variables {Γ₀ : Type*} [linear_ordered_comm_group_with_zero Γ₀] (v : valuation K Γ₀)
-- The following is the main technical lemma ensuring that inversion is continuous
-- in the topology induced by a valuation on a division ring (ie the next instance)
-- and the fact that a valued field is completable
-- [BouAC, VI.5.1 Lemme 1]
lemma valuation.inversion_estimate {x y : K} {γ : units Γ₀} (y_ne : y ≠ 0)
(h : v (x - y) < min (γ * ((v y) * (v y))) (v y)) :
v (x⁻¹ - y⁻¹) < γ :=
begin
have hyp1 : v (x - y) < γ * ((v y) * (v y)),
from lt_of_lt_of_le h (min_le_left _ _),
have hyp1' : v (x - y) * ((v y) * (v y))⁻¹ < γ,
from mul_inv_lt_of_lt_mul' hyp1,
have hyp2 : v (x - y) < v y,
from lt_of_lt_of_le h (min_le_right _ _),
have key : v x = v y, from valuation.map_eq_of_sub_lt v hyp2,
have x_ne : x ≠ 0,
{ intro h,
apply y_ne,
rw [h, v.map_zero] at key,
exact v.zero_iff.1 key.symm },
have decomp : x⁻¹ - y⁻¹ = x⁻¹ * (y - x) * y⁻¹,
by rw [mul_sub_left_distrib, sub_mul, mul_assoc,
show y * y⁻¹ = 1, from mul_inv_cancel y_ne,
show x⁻¹ * x = 1, from inv_mul_cancel x_ne, mul_one, one_mul],
calc
v (x⁻¹ - y⁻¹) = v (x⁻¹ * (y - x) * y⁻¹) : by rw decomp
... = (v x⁻¹) * (v $ y - x) * (v y⁻¹) : by repeat { rw valuation.map_mul }
... = (v x)⁻¹ * (v $ y - x) * (v y)⁻¹ : by rw [v.map_inv' x_ne, v.map_inv' y_ne]
... = (v $ y - x) * ((v y) * (v y))⁻¹ : by
rw [mul_assoc, mul_comm, key, mul_assoc, ← group_with_zero.mul_inv_rev]
... = (v $ y - x) * ((v y) * (v y))⁻¹ : rfl
... = (v $ x - y) * ((v y) * (v y))⁻¹ : by rw valuation.map_sub_swap
... < γ : hyp1',
end
end inversion_estimate
local attribute [instance] valued.subgroups_basis subgroups_basis.topology
ring_filter_basis.topological_ring
local notation `v` := valued.value
/-- The topology coming from a valuation on a division rings make it a topological division ring
[BouAC, VI.5.1 middle of Proposition 1] -/
instance valued.topological_division_ring [valued K] : topological_division_ring K :=
{ continuous_inv :=
begin
intros x x_ne s s_in,
cases valued.mem_nhds.mp s_in with γ hs, clear s_in,
rw [mem_map, valued.mem_nhds],
change ∃ (γ : units (valued.Γ₀ K)), {y : K | v (y - x) < γ} ⊆ {x : K | x⁻¹ ∈ s},
have vx_ne := (valuation.ne_zero_iff $ valued.v K).mpr x_ne,
let γ' := group_with_zero.mk₀ _ vx_ne,
use min (γ * (γ'*γ')) γ',
intros y y_in,
apply hs,
change v (y⁻¹ - x⁻¹) < γ,
simp only [mem_set_of_eq] at y_in,
rw [coe_min, units.coe_mul, units.coe_mul] at y_in,
exact valuation.inversion_estimate _ x_ne y_in
end,
..(by apply_instance : topological_ring K) }
section
local attribute [instance]
linear_ordered_comm_group_with_zero.topological_space
linear_ordered_comm_group_with_zero.regular_space
linear_ordered_comm_group_with_zero.nhds_basis
lemma valued.continuous_valuation [valued K] : continuous (v : K → valued.Γ₀ K) :=
begin
rw continuous_iff_continuous_at,
intro x,
classical,
by_cases h : x = 0,
{ rw h,
change tendsto _ _ (𝓝 (valued.v K 0)),
erw valuation.map_zero,
rw linear_ordered_comm_group_with_zero.tendsto_zero,
intro γ,
rw valued.mem_nhds_zero,
use [γ, set.subset.refl _] },
{ change tendsto _ _ _,
have v_ne : v x ≠ 0, from (valuation.ne_zero_iff _).mpr h,
rw linear_ordered_comm_group_with_zero.tendsto_nonzero v_ne,
apply valued.loc_const v_ne },
end
end
section
-- until the end of this section, all linearly ordered commutative groups will be endowed with
-- the discrete topology
-- In the next lemma, K will be endowed with its left uniformity coming from the valuation topology
local attribute [instance] valued.uniform_space
/-- A valued division ring is separated. -/
instance valued_ring.separated [valued K] : separated K :=
begin
apply topological_add_group.separated_of_zero_sep,
intros x x_ne,
refine ⟨{k | v k < v x}, _, λ h, lt_irrefl _ h⟩,
rw valued.mem_nhds,
have vx_ne := (valuation.ne_zero_iff $ valued.v K).mpr x_ne,
let γ' := group_with_zero.mk₀ _ vx_ne,
exact ⟨γ', λ y hy, by simpa using hy⟩,
end
end
end valuation_topological_division_ring
end division_ring
section valuation_on_valued_field_completion
open uniform_space
-- In this section K is commutative (hence a field), and equipped with a valuation
variables {K : Type*} [discrete_field K] [vK : valued K]
include vK
open valued
local notation `v` := valued.value
local attribute [instance, priority 0] valued.uniform_space valued.uniform_add_group
local notation `hat` K := completion K
set_option class.instance_max_depth 300
-- The following instances helps going over the uniform_add_group/topological_add_group loop
lemma hatK_top_group : topological_add_group (hat K) := uniform_add_group.to_topological_add_group
local attribute [instance] hatK_top_group
lemma hatK_top_monoid : topological_add_monoid (hat K) :=
topological_add_group.to_topological_add_monoid _
local attribute [instance] hatK_top_monoid
/-- A valued field is completable. -/
instance valued.completable : completable_top_field K :=
{ separated := by apply_instance,
nice := begin
rintros F hF h0,
have : ∃ (γ₀ : units (Γ₀ K)) (M ∈ F), ∀ x ∈ M, (γ₀ : Γ₀ K) ≤ v x,
{ rcases (filter.inf_eq_bot_iff _ _).1 h0 with ⟨U, U_in, M, M_in, H⟩,
rcases valued.mem_nhds_zero.mp U_in with ⟨γ₀, hU⟩,
existsi [γ₀, M, M_in],
intros x xM,
apply le_of_not_lt _,
intro hyp,
have : x ∈ U ∩ M := ⟨hU hyp, xM⟩,
rwa H at this },
rcases this with ⟨γ₀, M₀, M₀_in, H₀⟩,
rw valued.cauchy_iff at hF ⊢,
refine ⟨map_ne_bot hF.1, _⟩,
replace hF := hF.2,
intros γ,
rcases hF (min (γ * γ₀ * γ₀) γ₀) with ⟨M₁, M₁_in, H₁⟩, clear hF,
use (λ x : K, x⁻¹) '' (M₀ ∩ M₁),
split,
{ rw mem_map,
apply mem_sets_of_superset (filter.inter_mem_sets M₀_in M₁_in),
exact subset_preimage_image _ _ },
{ rintros _ _ ⟨x, ⟨x_in₀, x_in₁⟩, rfl⟩ ⟨y, ⟨y_in₀, y_in₁⟩, rfl⟩,
simp only [mem_set_of_eq],
specialize H₁ x y x_in₁ y_in₁,
replace x_in₀ := H₀ x x_in₀,
replace y_in₀ := H₀ y y_in₀, clear H₀,
apply valuation.inversion_estimate,
{ have : v x ≠ 0,
{ intro h, rw h at x_in₀, simpa using x_in₀, },
exact (valuation.ne_zero_iff _).mp this },
{ refine lt_of_lt_of_le H₁ _,
rw coe_min,
apply min_le_min _ x_in₀,
rw mul_assoc,
have : ((γ₀ * γ₀ : units (Γ₀ K)) : Γ₀ K) ≤ v x * v x,
from calc ↑γ₀ * ↑γ₀ ≤ ↑γ₀ * v x : actual_ordered_comm_monoid.mul_le_mul_left' x_in₀
... ≤ _ : actual_ordered_comm_monoid.mul_le_mul_right' x_in₀,
exact actual_ordered_comm_monoid.mul_le_mul_left' this } }
end }
local attribute [instance]
linear_ordered_comm_group_with_zero.topological_space
linear_ordered_comm_group_with_zero.regular_space
linear_ordered_comm_group_with_zero.nhds_basis
linear_ordered_comm_group_with_zero.t2_space
linear_ordered_comm_group_with_zero.ordered_topology
/-- The extension of the valuation of a valued field to the completion of the field. -/
noncomputable def valued.extension : (hat K) → Γ₀ K :=
completion.dense_inducing_coe.extend (v : K → Γ₀ K)
lemma valued.continuous_extension : continuous (valued.extension : (hat K) → Γ₀ K) :=
begin
refine completion.dense_inducing_coe.continuous_extend _,
intro x₀,
by_cases h : x₀ = coe 0,
{ refine ⟨0, _⟩,
erw [h, ← completion.dense_inducing_coe.to_inducing.nhds_eq_comap]; try { apply_instance },
rw linear_ordered_comm_group_with_zero.tendsto_zero,
intro γ₀,
rw valued.mem_nhds,
exact ⟨γ₀, by simp⟩ },
{ have preimage_one : v ⁻¹' {(1 : Γ₀ K)} ∈ 𝓝 (1 : K),
{ have : v (1 : K) ≠ 0, { rw valued.map_one, exact zero_ne_one.symm },
convert valued.loc_const this,
ext x,
rw [valued.map_one, mem_preimage, mem_singleton_iff, mem_set_of_eq] },
obtain ⟨V, V_in, hV⟩ : ∃ V ∈ 𝓝 (1 : hat K), ∀ x : K, (x : hat K) ∈ V → v x = 1,
{ rwa [completion.dense_inducing_coe.nhds_eq_comap, mem_comap_sets] at preimage_one,
rcases preimage_one with ⟨V, V_in, hV⟩,
use [V, V_in],
intros x x_in,
specialize hV x_in,
rwa [mem_preimage, mem_singleton_iff] at hV },
have : ∃ V' ∈ (𝓝 (1 : hat K)), (0 : hat K) ∉ V' ∧ ∀ x y ∈ V', x*y⁻¹ ∈ V,
{ have : tendsto (λ p : (hat K) × hat K, p.1*p.2⁻¹) ((𝓝 1).prod 𝓝 1) 𝓝 1,
{ rw ← nhds_prod_eq,
conv {congr, skip, skip, rw ← (one_mul (1 : hat K))},
refine tendsto.mul continuous_fst.continuous_at (tendsto.comp _ continuous_snd.continuous_at),
convert topological_division_ring.continuous_inv (1 : hat K) zero_ne_one.symm,
exact inv_one.symm },
rcases tendsto_prod_self_iff.mp this V V_in with ⟨U, U_in, hU⟩,
let hatKstar := (-{0} : set $ hat K),
have : hatKstar ∈ 𝓝 (1 : hat K),
{ haveI : t1_space (hat K) := @t2_space.t1_space (hat K) _ (@separated_t2 (hat K) _ _),
exact compl_singleton_mem_nhds zero_ne_one.symm },
use [U ∩ hatKstar, filter.inter_mem_sets U_in this],
split,
{ rintro ⟨h, h'⟩,
rw mem_compl_singleton_iff at h',
exact h' rfl },
{ rintros x y ⟨hx, _⟩ ⟨hy, _⟩,
apply hU ; assumption } },
rcases this with ⟨V', V'_in, zeroV', hV'⟩,
have nhds_right : (λ x, x*x₀) '' V' ∈ 𝓝 x₀,
{ have l : function.left_inverse (λ (x : hat K), x * x₀⁻¹) (λ (x : hat K), x * x₀),
{ intro x,
simp only [mul_assoc, mul_inv_cancel h, mul_one] },
have r: function.right_inverse (λ (x : hat K), x * x₀⁻¹) (λ (x : hat K), x * x₀),
{ intro x,
simp only [mul_assoc, inv_mul_cancel h, mul_one] },
have c : continuous (λ (x : hat K), x * x₀⁻¹),
from continuous_id.mul continuous_const,
rw image_eq_preimage_of_inverse l r,
rw ← mul_inv_cancel h at V'_in,
exact c.continuous_at V'_in },
have : ∃ (z₀ : K) (y₀ ∈ V'), coe z₀ = y₀*x₀ ∧ z₀ ≠ 0,
{ rcases dense_range.mem_nhds completion.dense nhds_right with ⟨z₀, y₀, y₀_in, h⟩,
refine ⟨z₀, y₀, y₀_in, ⟨h.symm, _⟩⟩,
intro hz,
rw hz at h,
cases discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero _ _ h ; finish },
rcases this with ⟨z₀, y₀, y₀_in, hz₀, z₀_ne⟩,
have vz₀_ne: valued.v K z₀ ≠ 0 := by rwa valuation.ne_zero_iff,
refine ⟨valued.v K z₀, _⟩,
rw [linear_ordered_comm_group_with_zero.tendsto_nonzero vz₀_ne, mem_comap_sets],
use [(λ x, x*x₀) '' V', nhds_right],
intros x x_in,
rcases mem_preimage.1 x_in with ⟨y, y_in, hy⟩, clear x_in,
change y*x₀ = coe x at hy,
have : valued.v K (x*z₀⁻¹) = 1,
{ apply hV,
rw [completion.coe_mul, is_ring_hom.map_inv' (coe : K → hat K) z₀_ne, ← hy, hz₀, mul_inv'],
assoc_rw mul_inv_cancel h,
rw mul_one,
solve_by_elim },
calc valued.v K x = valued.v K (x*z₀⁻¹*z₀) : by rw [mul_assoc, inv_mul_cancel z₀_ne, mul_one]
... = valued.v K (x*z₀⁻¹)*valued.v K z₀ : valuation.map_mul _ _ _
... = valued.v K z₀ : by rw [this, one_mul] },
end
@[elim_cast]
lemma valued.extension_extends (x : K) : valued.extension (x : hat K) = v x :=
begin
haveI : t2_space (valued.Γ₀ K) := regular_space.t2_space _,
exact completion.dense_inducing_coe.extend_eq_of_cont valued.continuous_valuation x
end
/-- the extension of a valuation on a division ring to its completion. -/
noncomputable def valued.extension_valuation :
valuation (hat K) (Γ₀ K) :=
{ to_fun := valued.extension,
map_zero' := by exact_mod_cast valuation.map_zero _,
map_one' := by { rw [← completion.coe_one, valued.extension_extends (1 : K)], exact valuation.map_one _ },
map_mul' := λ x y, begin
apply completion.induction_on₂ x y,
{ have c1 : continuous (λ (x : (hat K) × hat K), valued.extension (x.1 * x.2)),
from valued.continuous_extension.comp (continuous_fst.mul continuous_snd),
have c2 : continuous (λ (x : (hat K) × hat K), valued.extension x.1 * valued.extension x.2),
from (valued.continuous_extension.comp continuous_fst).mul
(valued.continuous_extension.comp continuous_snd),
exact is_closed_eq c1 c2 },
{ intros x y,
norm_cast,
exact valuation.map_mul _ _ _ },
end,
map_add' := λ x y, begin
rw le_max_iff,
apply completion.induction_on₂ x y,
{ exact is_closed_union
(is_closed_le ((valued.continuous_extension).comp continuous_add)
((valued.continuous_extension).comp continuous_fst))
(is_closed_le ((valued.continuous_extension).comp continuous_add)
((valued.continuous_extension).comp continuous_snd)) },
{ intros x y,
norm_cast,
rw ← le_max_iff,
exact valuation.map_add _ _ _ },
end }
end valuation_on_valued_field_completion
|
79745010ea7a5b77983b0461225cb86614e47bad | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/data/set/finite.lean | ae9059fe0a52eced0ad9ff0ea101c4b728c8a358 | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 21,054 | 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
Finite sets.
-/
import logic.function
import data.nat.basic data.fintype data.set.lattice data.set.function
open set lattice function
universes u v w x
variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x}
namespace set
/-- A set is finite if the subtype is a fintype, i.e. there is a
list that enumerates its members. -/
def finite (s : set α) : Prop := nonempty (fintype s)
/-- A set is infinite if it is not finite. -/
def infinite (s : set α) : Prop := ¬ finite s
/-- Construct a fintype from a finset with the same elements. -/
def fintype_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p :=
fintype.subtype s H
@[simp] theorem card_fintype_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) :
@fintype.card p (fintype_of_finset s H) = s.card :=
fintype.subtype_card s H
theorem card_fintype_of_finset' {p : set α} (s : finset α)
(H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card :=
by rw ← card_fintype_of_finset s H; congr
/-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/
def to_finset (s : set α) [fintype s] : finset α :=
⟨(@finset.univ s _).1.map subtype.val,
multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩
@[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s :=
by simp [to_finset]
@[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s :=
mem_to_finset
noncomputable instance finite.fintype {s : set α} (h : finite s) : fintype s :=
classical.choice h
/-- Get a finset from a finite set -/
noncomputable def finite.to_finset {s : set α} (h : finite s) : finset α :=
@set.to_finset _ _ (finite.fintype h)
@[simp] theorem finite.mem_to_finset {s : set α} {h : finite s} {a : α} : a ∈ h.to_finset ↔ a ∈ s :=
@mem_to_finset _ _ (finite.fintype h) _
lemma finite.coe_to_finset {α} {s : set α} (h : finite s) : ↑h.to_finset = s :=
by { ext, apply mem_to_finset }
lemma exists_finset_of_finite {s : set α} (h : finite s) : ∃(s' : finset α), ↑s' = s :=
⟨h.to_finset, h.coe_to_finset⟩
theorem finite.exists_finset {s : set α} : finite s →
∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s
| ⟨h⟩ := by exactI ⟨to_finset s, λ _, mem_to_finset⟩
theorem finite.exists_finset_coe {s : set α} (hs : finite s) :
∃ s' : finset α, ↑s' = s :=
let ⟨s', h⟩ := hs.exists_finset in ⟨s', set.ext h⟩
theorem finite_mem_finset (s : finset α) : finite {a | a ∈ s} :=
⟨fintype_of_finset s (λ _, iff.rfl)⟩
theorem finite.of_fintype [fintype α] (s : set α) : finite s :=
by classical; exact ⟨set_fintype s⟩
instance decidable_mem_of_fintype [decidable_eq α] (s : set α) [fintype s] (a) : decidable (a ∈ s) :=
decidable_of_iff _ mem_to_finset
instance fintype_empty : fintype (∅ : set α) :=
fintype_of_finset ∅ $ by simp
theorem empty_card : fintype.card (∅ : set α) = 0 := rfl
@[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} :
@fintype.card (∅ : set α) h = 0 :=
eq.trans (by congr) empty_card
@[simp] theorem finite_empty : @finite α ∅ := ⟨set.fintype_empty⟩
def fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) :=
fintype_of_finset ⟨a :: s.to_finset.1,
multiset.nodup_cons_of_nodup (by simp [h]) s.to_finset.2⟩ $ by simp
theorem card_fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) :
@fintype.card _ (fintype_insert' s h) = fintype.card s + 1 :=
by rw [fintype_insert', card_fintype_of_finset];
simp [finset.card, to_finset]; refl
@[simp] theorem card_insert {a : α} (s : set α)
[fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} :
@fintype.card _ d = fintype.card s + 1 :=
by rw ← card_fintype_insert' s h; congr
lemma card_image_of_inj_on {s : set α} [fintype s]
{f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) :
fintype.card (f '' s) = fintype.card s :=
by haveI := classical.prop_decidable; exact
calc fintype.card (f '' s) = (s.to_finset.image f).card : card_fintype_of_finset' _ (by simp)
... = s.to_finset.card : finset.card_image_of_inj_on
(λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy)
... = fintype.card s : (card_fintype_of_finset' _ (λ a, mem_to_finset)).symm
lemma card_image_of_injective (s : set α) [fintype s]
{f : α → β} [fintype (f '' s)] (H : function.injective f) :
fintype.card (f '' s) = fintype.card s :=
card_image_of_inj_on $ λ _ _ _ _ h, H h
instance fintype_insert [decidable_eq α] (a : α) (s : set α) [fintype s] : fintype (insert a s : set α) :=
if h : a ∈ s then by rwa [insert_eq, union_eq_self_of_subset_left (singleton_subset_iff.2 h)]
else fintype_insert' _ h
@[simp] theorem finite_insert (a : α) {s : set α} : finite s → finite (insert a s)
| ⟨h⟩ := ⟨@set.fintype_insert _ (classical.dec_eq α) _ _ h⟩
lemma to_finset_insert [decidable_eq α] {a : α} {s : set α} (hs : finite s) :
(finite_insert a hs).to_finset = insert a hs.to_finset :=
finset.ext.mpr $ by simp
@[elab_as_eliminator]
theorem finite.induction_on {C : set α → Prop} {s : set α} (h : finite s)
(H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → finite s → C s → C (insert a s)) : C s :=
let ⟨t⟩ := h in by exactI
match s.to_finset, @mem_to_finset _ s _ with
| ⟨l, nd⟩, al := begin
change ∀ a, a ∈ l ↔ a ∈ s at al,
clear _let_match _match t h, revert s nd al,
refine multiset.induction_on l _ (λ a l IH, _); intros s nd al,
{ rw show s = ∅, from eq_empty_iff_forall_not_mem.2 (by simpa using al),
exact H0 },
{ rw ← show insert a {x | x ∈ l} = s, from set.ext (by simpa using al),
cases multiset.nodup_cons.1 nd with m nd',
refine H1 _ ⟨finset.subtype.fintype ⟨l, nd'⟩⟩ (IH nd' (λ _, iff.rfl)),
exact m }
end
end
@[elab_as_eliminator]
theorem finite.dinduction_on {C : ∀s:set α, finite s → Prop} {s : set α} (h : finite s)
(H0 : C ∅ finite_empty)
(H1 : ∀ {a s}, a ∉ s → ∀h:finite s, C s h → C (insert a s) (finite_insert a h)) :
C s h :=
have ∀h:finite s, C s h,
from finite.induction_on h (assume h, H0) (assume a s has hs ih h, H1 has hs (ih _)),
this h
instance fintype_singleton (a : α) : fintype ({a} : set α) :=
fintype_insert' _ (not_mem_empty _)
@[simp] theorem card_singleton (a : α) :
fintype.card ({a} : set α) = 1 :=
by rw [show fintype.card ({a} : set α) = _, from
card_fintype_insert' ∅ (not_mem_empty a)]; refl
@[simp] theorem finite_singleton (a : α) : finite ({a} : set α) :=
⟨set.fintype_singleton _⟩
instance fintype_pure : ∀ a : α, fintype (pure a : set α) :=
set.fintype_singleton
theorem finite_pure (a : α) : finite (pure a : set α) :=
⟨set.fintype_pure a⟩
instance fintype_univ [fintype α] : fintype (@univ α) :=
fintype_of_finset finset.univ $ λ _, iff_true_intro (finset.mem_univ _)
theorem finite_univ [fintype α] : finite (@univ α) := ⟨set.fintype_univ⟩
instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s ∪ t : set α) :=
fintype_of_finset (s.to_finset ∪ t.to_finset) $ by simp
theorem finite_union {s t : set α} : finite s → finite t → finite (s ∪ t)
| ⟨hs⟩ ⟨ht⟩ := ⟨@set.fintype_union _ (classical.dec_eq α) _ _ hs ht⟩
instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] : fintype ({a ∈ s | p a} : set α) :=
fintype_of_finset (s.to_finset.filter p) $ by simp
instance fintype_inter (s t : set α) [fintype s] [decidable_pred t] : fintype (s ∩ t : set α) :=
set.fintype_sep s t
def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred t] (h : t ⊆ s) : fintype t :=
by rw ← inter_eq_self_of_subset_right h; apply_instance
theorem finite_subset {s : set α} : finite s → ∀ {t : set α}, t ⊆ s → finite t
| ⟨hs⟩ t h := ⟨@set.fintype_subset _ _ _ hs (classical.dec_pred t) h⟩
instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) :=
fintype_of_finset (s.to_finset.image f) $ by simp
instance fintype_range [decidable_eq β] (f : α → β) [fintype α] : fintype (range f) :=
fintype_of_finset (finset.univ.image f) $ by simp [range]
theorem finite_range (f : α → β) [fintype α] : finite (range f) :=
by haveI := classical.dec_eq β; exact ⟨by apply_instance⟩
theorem finite_image {s : set α} (f : α → β) : finite s → finite (f '' s)
| ⟨h⟩ := ⟨@set.fintype_image _ _ (classical.dec_eq β) _ _ h⟩
instance fintype_map {α β} [decidable_eq β] :
∀ (s : set α) (f : α → β) [fintype s], fintype (f <$> s) := set.fintype_image
theorem finite_map {α β} {s : set α} :
∀ (f : α → β), finite s → finite (f <$> s) := finite_image
def fintype_of_fintype_image [decidable_eq β] (s : set α)
{f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s :=
fintype_of_finset ⟨_, @multiset.nodup_filter_map β α g _
(@injective_of_partial_inv_right _ _ f g I) (f '' s).to_finset.2⟩ $ λ a,
begin
suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s,
by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc],
rw exists_swap,
suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]},
simp [I _, (injective_of_partial_inv I).eq_iff]
end
theorem finite_of_finite_image_on {s : set α} {f : α → β} (hi : set.inj_on f s) :
finite (f '' s) → finite s | ⟨h⟩ :=
⟨@fintype.of_injective _ _ h (λa:s, ⟨f a.1, mem_image_of_mem f a.2⟩) $
assume a b eq, subtype.eq $ hi a.2 b.2 $ subtype.ext.1 eq⟩
theorem finite_image_iff_on {s : set α} {f : α → β} (hi : inj_on f s) :
finite (f '' s) ↔ finite s :=
⟨finite_of_finite_image_on hi, finite_image _⟩
theorem finite_of_finite_image {s : set α} {f : α → β} (I : set.inj_on f s) :
finite (f '' s) → finite s :=
finite_of_finite_image_on I
theorem finite_preimage {s : set β} {f : α → β}
(I : set.inj_on f (f⁻¹' s)) (h : finite s) : finite (f ⁻¹' s) :=
finite_of_finite_image I (finite_subset h (image_preimage_subset f s))
instance fintype_Union [decidable_eq α] {ι : Type*} [fintype ι]
(f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) :=
fintype_of_finset (finset.univ.bind (λ i, (f i).to_finset)) $ by simp
theorem finite_Union {ι : Type*} [fintype ι] {f : ι → set α} (H : ∀i, finite (f i)) : finite (⋃ i, f i) :=
⟨@set.fintype_Union _ (classical.dec_eq α) _ _ _ (λ i, finite.fintype (H i))⟩
def fintype_bUnion [decidable_eq α] {ι : Type*} {s : set ι} [fintype s]
(f : ι → set α) (H : ∀ i ∈ s, fintype (f i)) : fintype (⋃ i ∈ s, f i) :=
by rw bUnion_eq_Union; exact
@set.fintype_Union _ _ _ _ _ (by rintro ⟨i, hi⟩; exact H i hi)
instance fintype_bUnion' [decidable_eq α] {ι : Type*} {s : set ι} [fintype s]
(f : ι → set α) [H : ∀ i, fintype (f i)] : fintype (⋃ i ∈ s, f i) :=
fintype_bUnion _ (λ i _, H i)
theorem finite_sUnion {s : set (set α)} (h : finite s) (H : ∀t∈s, finite t) : finite (⋃₀ s) :=
by rw sUnion_eq_Union; haveI := finite.fintype h;
apply finite_Union; simpa using H
theorem finite_bUnion {α} {ι : Type*} {s : set ι} {f : ι → set α} :
finite s → (∀i, finite (f i)) → finite (⋃ i∈s, f i)
| ⟨hs⟩ h := by rw [bUnion_eq_Union]; exactI finite_Union (λ i, h _)
theorem finite_bUnion' {α} {ι : Type*} {s : set ι} (f : ι → set α) :
finite s → (∀i ∈ s, finite (f i)) → finite (⋃ i∈s, f i)
| ⟨hs⟩ h := by { rw [bUnion_eq_Union], exactI finite_Union (λ i, h i.1 i.2) }
instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} :=
fintype_of_finset (finset.range n) $ by simp
instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} :=
by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1)
lemma finite_le_nat (n : ℕ) : finite {i | i ≤ n} := ⟨set.fintype_le_nat _⟩
lemma finite_lt_nat (n : ℕ) : finite {i | i < n} := ⟨set.fintype_lt_nat _⟩
instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (set.prod s t) :=
fintype_of_finset (s.to_finset.product t.to_finset) $ by simp
lemma finite_prod {s : set α} {t : set β} : finite s → finite t → finite (set.prod s t)
| ⟨hs⟩ ⟨ht⟩ := by exactI ⟨set.fintype_prod s t⟩
def fintype_bind {α β} [decidable_eq β] (s : set α) [fintype s]
(f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) :=
set.fintype_bUnion _ H
instance fintype_bind' {α β} [decidable_eq β] (s : set α) [fintype s]
(f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) :=
fintype_bind _ _ (λ i _, H i)
theorem finite_bind {α β} {s : set α} {f : α → set β} :
finite s → (∀ a ∈ s, finite (f a)) → finite (s >>= f)
| ⟨hs⟩ H := ⟨@fintype_bind _ _ (classical.dec_eq β) _ hs _ (λ a ha, (H a ha).fintype)⟩
instance fintype_seq {α β : Type u} [decidable_eq β]
(f : set (α → β)) (s : set α) [fintype f] [fintype s] :
fintype (f <*> s) :=
by rw seq_eq_bind_map; apply set.fintype_bind'
theorem finite_seq {α β : Type u} {f : set (α → β)} {s : set α} :
finite f → finite s → finite (f <*> s)
| ⟨hf⟩ ⟨hs⟩ := by { haveI := classical.dec_eq β, exactI ⟨set.fintype_seq _ _⟩ }
/-- There are finitely many subsets of a given finite set -/
lemma finite_subsets_of_finite {α : Type u} {a : set α} (h : finite a) : finite {b | b ⊆ a} :=
begin
-- we just need to translate the result, already known for finsets,
-- to the language of finite sets
let s := coe '' ((finset.powerset (finite.to_finset h)).to_set),
have : finite s := finite_image _ (finite_mem_finset _),
have : {b | b ⊆ a} ⊆ s :=
begin
assume b hb,
rw [set.mem_image],
rw [set.mem_set_of_eq] at hb,
let b' : finset α := finite.to_finset (finite_subset h hb),
have : b' ∈ (finset.powerset (finite.to_finset h)).to_set :=
show b' ∈ (finset.powerset (finite.to_finset h)),
by simp [b', finset.subset_iff]; exact hb,
have : coe b' = b := by ext; simp,
exact ⟨b', by assumption, by assumption⟩
end,
exact finite_subset ‹finite s› this
end
end set
namespace finset
variables [decidable_eq β]
variables {s t u : finset α} {f : α → β} {a : α}
lemma finite_to_set (s : finset α) : set.finite (↑s : set α) :=
set.finite_mem_finset s
@[simp] lemma coe_bind {f : α → finset β} : ↑(s.bind f) = (⋃x ∈ (↑s : set α), ↑(f x) : set β) :=
by simp [set.ext_iff]
@[simp] lemma coe_to_finset {s : set α} {hs : set.finite s} : ↑(hs.to_finset) = s :=
by simp [set.ext_iff]
@[simp] lemma coe_to_finset' [decidable_eq α] (s : set α) [fintype s] : (↑s.to_finset : set α) = s :=
by ext; simp
end finset
namespace set
lemma finite_subset_Union {s : set α} (hs : finite s)
{ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, finite I ∧ s ⊆ ⋃ i ∈ I, t i :=
begin
unfreezeI, cases hs,
choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h},
refine ⟨range f, finite_range f, _⟩,
rintro x hx,
simp,
exact ⟨_, ⟨_, hx, rfl⟩, hf ⟨x, hx⟩⟩
end
lemma finite_range_ite {p : α → Prop} [decidable_pred p] {f g : α → β} (hf : finite (range f))
(hg : finite (range g)) : finite (range (λ x, if p x then f x else g x)) :=
finite_subset (finite_union hf hg) range_ite_subset
lemma finite_range_const {c : β} : finite (range (λ x : α, c)) :=
finite_subset (finite_singleton c) range_const_subset
lemma range_find_greatest_subset {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ}:
range (λ x, nat.find_greatest (P x) b) ⊆ ↑(finset.range (b + 1)) :=
by { rw range_subset_iff, assume x, simp [nat.lt_succ_iff, nat.find_greatest_le] }
lemma finite_range_find_greatest {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ} :
finite (range (λ x, nat.find_greatest (P x) b)) :=
finite_subset (finset.finite_to_set $ finset.range (b + 1)) range_find_greatest_subset
lemma infinite_univ_nat : infinite (univ : set ℕ) :=
assume (h : finite (univ : set ℕ)),
let ⟨n, hn⟩ := finset.exists_nat_subset_range h.to_finset in
have n ∈ finset.range n, from finset.subset_iff.mpr hn $ by simp,
by simp * at *
lemma not_injective_nat_fintype [fintype α] [decidable_eq α] {f : ℕ → α} : ¬ injective f :=
assume (h : injective f),
have finite (f '' univ),
from finite_subset (finset.finite_to_set $ fintype.elems α) (assume a h, fintype.complete a),
have finite (univ : set ℕ), from finite_of_finite_image (set.inj_on_of_injective _ h) this,
infinite_univ_nat this
lemma not_injective_int_fintype [fintype α] [decidable_eq α] {f : ℤ → α} : ¬ injective f :=
assume hf,
have injective (f ∘ (coe : ℕ → ℤ)), from injective_comp hf $ assume i j, int.of_nat_inj,
not_injective_nat_fintype this
lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) :
fintype.card s < fintype.card t :=
begin
haveI := classical.prop_decidable,
rw [← finset.coe_to_finset' s, ← finset.coe_to_finset' t, finset.coe_ssubset] at h,
rw [card_fintype_of_finset' _ (λ x, mem_to_finset),
card_fintype_of_finset' _ (λ x, mem_to_finset)],
exact finset.card_lt_card h,
end
lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) :
fintype.card s ≤ fintype.card t :=
calc fintype.card s = s.to_finset.card : set.card_fintype_of_finset' _ (by simp)
... ≤ t.to_finset.card : finset.card_le_of_subset (λ x hx, by simp [set.subset_def, *] at *)
... = fintype.card t : eq.symm (set.card_fintype_of_finset' _ (by simp))
lemma eq_of_subset_of_card_le {s t : set α} [fintype s] [fintype t]
(hsub : s ⊆ t) (hcard : fintype.card t ≤ fintype.card s) : s = t :=
classical.by_contradiction (λ h, lt_irrefl (fintype.card t)
(have fintype.card s < fintype.card t := set.card_lt_card ⟨hsub, h⟩,
by rwa [le_antisymm (card_le_of_subset hsub) hcard] at this))
lemma card_range_of_injective [fintype α] {f : α → β} (hf : injective f)
[fintype (range f)] : fintype.card (range f) = fintype.card α :=
eq.symm $ fintype.card_congr (@equiv.of_bijective _ _ (λ a : α, show range f, from ⟨f a, a, rfl⟩)
⟨λ x y h, hf $ subtype.mk.inj h, λ b, let ⟨a, ha⟩ := b.2 in ⟨a, by simp *⟩⟩)
lemma finite.exists_maximal_wrt [partial_order β]
(f : α → β) (s : set α) (h : set.finite s) : s ≠ ∅ → ∃a∈s, ∀a'∈s, f a ≤ f a' → f a = f a' :=
begin
classical,
refine h.induction_on _ _,
{ assume h, contradiction },
assume a s his _ ih _,
by_cases s = ∅,
{ use a, simp [h] },
rcases ih h with ⟨b, hb, ih⟩,
by_cases f b ≤ f a,
{ refine ⟨a, set.mem_insert _ _, assume c hc hac, le_antisymm hac _⟩,
rcases set.mem_insert_iff.1 hc with rfl | hcs,
{ refl },
{ rwa [← ih c hcs (le_trans h hac)] } },
{ refine ⟨b, set.mem_insert_of_mem _ hb, assume c hc hbc, _⟩,
rcases set.mem_insert_iff.1 hc with rfl | hcs,
{ exact (h hbc).elim },
{ exact ih c hcs hbc } }
end
end set
namespace finset
section preimage
noncomputable def preimage {f : α → β} (s : finset β)
(hf : set.inj_on f (f ⁻¹' ↑s)) : finset α :=
set.finite.to_finset (set.finite_preimage hf (set.finite_mem_finset s))
@[simp] lemma mem_preimage {f : α → β} {s : finset β} {hf : set.inj_on f (f ⁻¹' ↑s)} {x : α} :
x ∈ preimage s hf ↔ f x ∈ s :=
by simp [preimage]
@[simp] lemma coe_preimage {f : α → β} (s : finset β)
(hf : set.inj_on f (f ⁻¹' ↑s)) : (↑(preimage s hf) : set α) = f ⁻¹' ↑s :=
by simp [set.ext_iff]
lemma image_preimage [decidable_eq β] (f : α → β) (s : finset β)
(hf : set.bij_on f (f ⁻¹' s.to_set) s.to_set) :
image f (preimage s (set.inj_on_of_bij_on hf)) = s :=
finset.coe_inj.1 $
suffices f '' (f ⁻¹' ↑s) = ↑s, by simpa,
(set.subset.antisymm (image_preimage_subset _ _) hf.2.2)
end preimage
@[to_additive finset.sum_preimage]
lemma prod_preimage [comm_monoid β] (f : α → γ) (s : finset γ)
(hf : set.bij_on f (f ⁻¹' ↑s) ↑s) (g : γ → β) :
(preimage s (set.inj_on_of_bij_on hf)).prod (g ∘ f) = s.prod g :=
by classical;
calc
(preimage s (set.inj_on_of_bij_on hf)).prod (g ∘ f)
= (image f (preimage s (set.inj_on_of_bij_on hf))).prod g :
begin
rw prod_image,
intros x hx y hy hxy,
apply set.inj_on_of_bij_on hf,
repeat { try { rw mem_preimage at hx hy,
rw [set.mem_preimage, mem_coe] },
assumption },
end
... = s.prod g : by rw image_preimage
end finset
|
f6071ffeab95007199eedf65331773c6e74b386a | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/CoreM.lean | 8765bc4a2ca2baab86aceb2b5e67948ad9fbcc61 | [
"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 | 10,974 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.RecDepth
import Lean.Util.Trace
import Lean.Log
import Lean.Data.Options
import Lean.Environment
import Lean.Exception
import Lean.InternalExceptionId
import Lean.Eval
import Lean.MonadEnv
import Lean.ResolveName
import Lean.Elab.InfoTree.Types
namespace Lean
namespace Core
register_builtin_option maxHeartbeats : Nat := {
defValue := 200000
descr := "maximum amount of heartbeats per command. A heartbeat is number of (small) memory allocations (in thousands), 0 means no limit"
}
def getMaxHeartbeats (opts : Options) : Nat :=
maxHeartbeats.get opts * 1000
abbrev InstantiateLevelCache := Std.PersistentHashMap Name (List Level × Expr)
/-- Cache for the `CoreM` monad -/
structure Cache where
instLevelType : InstantiateLevelCache := {}
instLevelValue : InstantiateLevelCache := {}
deriving Inhabited
/-- State for the CoreM monad. -/
structure State where
/-- Current environment. -/
env : Environment
/-- Next macro scope. We use macro scopes to avoid accidental name capture. -/
nextMacroScope : MacroScope := firstFrontendMacroScope + 1
/-- Name generator for producing unique `FVarId`s, `MVarId`s, and `LMVarId`s -/
ngen : NameGenerator := {}
/-- Trace messages -/
traceState : TraceState := {}
/-- Cache for instantiating universe polymorphic declarations. -/
cache : Cache := {}
/-- Message log. -/
messages : MessageLog := {}
/-- Info tree. We have the info tree here because we want to update it while adding attributes. -/
infoState : Elab.InfoState := {}
deriving Inhabited
/-- Context for the CoreM monad. -/
structure Context where
/-- Name of the file being compiled. -/
fileName : String
/-- Auxiliary datastructure for converting `String.Pos` into Line/Column number. -/
fileMap : FileMap
options : Options := {}
currRecDepth : Nat := 0
maxRecDepth : Nat := 1000
ref : Syntax := Syntax.missing
currNamespace : Name := Name.anonymous
openDecls : List OpenDecl := []
initHeartbeats : Nat := 0
maxHeartbeats : Nat := getMaxHeartbeats options
currMacroScope : MacroScope := firstFrontendMacroScope
/-- CoreM is a monad for manipulating the Lean environment.
It is the base monad for `MetaM`.
The main features it provides are:
- name generator state
- environment state
- Lean options context
- the current open namespace
-/
abbrev CoreM := ReaderT Context <| StateRefT State (EIO Exception)
-- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the
-- whole monad stack at every use site. May eventually be covered by `deriving`.
instance : Monad CoreM := let i := inferInstanceAs (Monad CoreM); { pure := i.pure, bind := i.bind }
instance : Inhabited (CoreM α) where
default := fun _ _ => throw default
instance : MonadRef CoreM where
getRef := return (← read).ref
withRef ref x := withReader (fun ctx => { ctx with ref := ref }) x
instance : MonadEnv CoreM where
getEnv := return (← get).env
modifyEnv f := modify fun s => { s with env := f s.env, cache := {} }
instance : MonadOptions CoreM where
getOptions := return (← read).options
instance : MonadWithOptions CoreM where
withOptions f x := withReader (fun ctx => { ctx with options := f ctx.options }) x
instance : AddMessageContext CoreM where
addMessageContext := addMessageContextPartial
instance : MonadNameGenerator CoreM where
getNGen := return (← get).ngen
setNGen ngen := modify fun s => { s with ngen := ngen }
instance : MonadRecDepth CoreM where
withRecDepth d x := withReader (fun ctx => { ctx with currRecDepth := d }) x
getRecDepth := return (← read).currRecDepth
getMaxRecDepth := return (← read).maxRecDepth
instance : MonadResolveName CoreM where
getCurrNamespace := return (← read).currNamespace
getOpenDecls := return (← read).openDecls
protected def withFreshMacroScope (x : CoreM α) : CoreM α := do
let fresh ← modifyGetThe Core.State (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 }))
withReader (fun ctx => { ctx with currMacroScope := fresh }) x
instance : MonadQuotation CoreM where
getCurrMacroScope := return (← read).currMacroScope
getMainModule := return (← get).env.mainModule
withFreshMacroScope := Core.withFreshMacroScope
instance : Elab.MonadInfoTree CoreM where
getInfoState := return (← get).infoState
modifyInfoState f := modify fun s => { s with infoState := f s.infoState }
@[inline] def modifyCache (f : Cache → Cache) : CoreM Unit :=
modify fun ⟨env, next, ngen, trace, cache, messages, infoState⟩ => ⟨env, next, ngen, trace, f cache, messages, infoState⟩
@[inline] def modifyInstLevelTypeCache (f : InstantiateLevelCache → InstantiateLevelCache) : CoreM Unit :=
modifyCache fun ⟨c₁, c₂⟩ => ⟨f c₁, c₂⟩
@[inline] def modifyInstLevelValueCache (f : InstantiateLevelCache → InstantiateLevelCache) : CoreM Unit :=
modifyCache fun ⟨c₁, c₂⟩ => ⟨c₁, f c₂⟩
def instantiateTypeLevelParams (c : ConstantInfo) (us : List Level) : CoreM Expr := do
if let some (us', r) := (← get).cache.instLevelType.find? c.name then
if us == us' then
return r
let r := c.instantiateTypeLevelParams us
modifyInstLevelTypeCache fun s => s.insert c.name (us, r)
return r
def instantiateValueLevelParams (c : ConstantInfo) (us : List Level) : CoreM Expr := do
if let some (us', r) := (← get).cache.instLevelValue.find? c.name then
if us == us' then
return r
let r := c.instantiateValueLevelParams us
modifyInstLevelValueCache fun s => s.insert c.name (us, r)
return r
@[inline] def liftIOCore (x : IO α) : CoreM α := do
let ref ← getRef
IO.toEIO (fun (err : IO.Error) => Exception.error ref (toString err)) x
instance : MonadLift IO CoreM where
monadLift := liftIOCore
instance : MonadTrace CoreM where
getTraceState := return (← get).traceState
modifyTraceState f := modify fun s => { s with traceState := f s.traceState }
/-- Restore backtrackable parts of the state. -/
def restore (b : State) : CoreM Unit :=
modify fun s => { s with env := b.env, messages := b.messages, infoState := b.infoState }
private def mkFreshNameImp (n : Name) : CoreM Name := do
let fresh ← modifyGet fun s => (s.nextMacroScope, { s with nextMacroScope := s.nextMacroScope + 1 })
return addMacroScope (← getEnv).mainModule n fresh
def mkFreshUserName (n : Name) : CoreM Name :=
mkFreshNameImp n
@[inline] def CoreM.run (x : CoreM α) (ctx : Context) (s : State) : EIO Exception (α × State) :=
(x ctx).run s
@[inline] def CoreM.run' (x : CoreM α) (ctx : Context) (s : State) : EIO Exception α :=
Prod.fst <$> x.run ctx s
@[inline] def CoreM.toIO (x : CoreM α) (ctx : Context) (s : State) : IO (α × State) := do
match (← (x.run { ctx with initHeartbeats := (← IO.getNumHeartbeats) } s).toIO') with
| Except.error (Exception.error _ msg) => throw <| IO.userError (← msg.toString)
| Except.error (Exception.internal id _) => throw <| IO.userError <| "internal exception #" ++ toString id.idx
| Except.ok a => return a
instance [MetaEval α] : MetaEval (CoreM α) where
eval env opts x _ := do
let x : CoreM α := do try x finally printTraces
let (a, s) ← x.toIO { maxRecDepth := maxRecDepth.get opts, options := opts, fileName := "<CoreM>", fileMap := default } { env := env }
MetaEval.eval s.env opts a (hideUnit := true)
-- withIncRecDepth for a monad `m` such that `[MonadControlT CoreM n]`
protected def withIncRecDepth [Monad m] [MonadControlT CoreM m] (x : m α) : m α :=
controlAt CoreM fun runInBase => withIncRecDepth (runInBase x)
def throwMaxHeartbeat (moduleName : Name) (optionName : Name) (max : Nat) : CoreM Unit := do
let msg := s!"(deterministic) timeout at '{moduleName}', maximum number of heartbeats ({max/1000}) has been reached (use 'set_option {optionName} <num>' to set the limit)"
throw <| Exception.error (← getRef) (MessageData.ofFormat (Std.Format.text msg))
def checkMaxHeartbeatsCore (moduleName : String) (optionName : Name) (max : Nat) : CoreM Unit := do
unless max == 0 do
let numHeartbeats ← IO.getNumHeartbeats
if numHeartbeats - (← read).initHeartbeats > max then
throwMaxHeartbeat moduleName optionName max
def checkMaxHeartbeats (moduleName : String) : CoreM Unit := do
checkMaxHeartbeatsCore moduleName `maxHeartbeats (← read).maxHeartbeats
private def withCurrHeartbeatsImp (x : CoreM α) : CoreM α := do
let heartbeats ← IO.getNumHeartbeats
withReader (fun ctx => { ctx with initHeartbeats := heartbeats }) x
def withCurrHeartbeats [Monad m] [MonadControlT CoreM m] (x : m α) : m α :=
controlAt CoreM fun runInBase => withCurrHeartbeatsImp (runInBase x)
def setMessageLog (messages : MessageLog) : CoreM Unit :=
modify fun s => { s with messages := messages }
def resetMessageLog : CoreM Unit :=
setMessageLog {}
def getMessageLog : CoreM MessageLog :=
return (← get).messages
instance : MonadLog CoreM where
getRef := getRef
getFileMap := return (← read).fileMap
getFileName := return (← read).fileName
hasErrors := return (← get).messages.hasErrors
logMessage msg := do
let ctx ← read
let msg := { msg with data := MessageData.withNamingContext { currNamespace := ctx.currNamespace, openDecls := ctx.openDecls } msg.data };
modify fun s => { s with messages := s.messages.add msg }
end Core
export Core (CoreM mkFreshUserName checkMaxHeartbeats withCurrHeartbeats)
@[inline] def catchInternalId [Monad m] [MonadExcept Exception m] (id : InternalExceptionId) (x : m α) (h : Exception → m α) : m α := do
try
x
catch ex => match ex with
| .error .. => throw ex
| .internal id' _ => if id == id' then h ex else throw ex
@[inline] def catchInternalIds [Monad m] [MonadExcept Exception m] (ids : List InternalExceptionId) (x : m α) (h : Exception → m α) : m α := do
try
x
catch ex => match ex with
| .error .. => throw ex
| .internal id _ => if ids.contains id then h ex else throw ex
/--
Return true if `ex` was generated by `throwMaxHeartbeat`.
This function is a bit hackish. The heartbeat exception should probably be an internal exception.
We used a similar hack at `Exception.isMaxRecDepth` -/
def Exception.isMaxHeartbeat (ex : Exception) : Bool :=
match ex with
| Exception.error _ (MessageData.ofFormat (Std.Format.text msg)) => "(deterministic) timeout".isPrefixOf msg
| _ => false
/-- Creates the expression `d → b` -/
def mkArrow (d b : Expr) : CoreM Expr :=
return Lean.mkForall (← mkFreshUserName `x) BinderInfo.default d b
end Lean
|
4680125b9f398a8361fd48e16c6b24dafa78fd23 | 84c325c9a58de83324b777adc78ac188ecdbceae | /src/util/tactic.lean | f6df3372faf059aa48100d0d5a5ae05dcd6e5c7f | [
"Apache-2.0"
] | permissive | brando90/lean-gym | 0c3b433dac9c1a1079623721cdb3307a0981d86b | f4a94fcf54f8729be416ebdca82097d95a6f1c39 | refs/heads/main | 1,683,583,589,195 | 1,622,558,076,000 | 1,622,558,076,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,160 | lean | /-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author(s): Stanislas Polu
Helper functions to work with the tactic monad.
-/
import tactic
import tactic.core
import util.io
import system.io
import basic.control
open tactic
namespace tactic
meta def set_goal_to (goal : expr) : tactic unit :=
mk_meta_var goal >>= set_goals ∘ pure
end tactic
section add_open_namespace
meta def add_open_namespace : name → tactic unit := λ nm, do
env ← tactic.get_env, tactic.set_env (env.execute_open nm)
meta def add_open_namespaces (nms : list name) : tactic unit :=
nms.mmap' add_open_namespace
end add_open_namespace
section hashing
meta def tactic_hash : tactic ℕ := do {
gs ← tactic.get_goals,
hs ← gs.mmap $ λ g, do {
tactic.set_goals [g],
es ← (::) <$> tactic.target <*> tactic.local_context,
es.mfoldl (λ acc e, (+) acc <$> expr.hash <$> tactic.head_zeta e) 0
},
pure $ hs.sum
}
end hashing
section misc
meta def tactic.is_theorem (nm : name) : tactic bool := do {
env ← tactic.get_env,
declaration.is_theorem <$> env.get nm
}
end misc
|
98989ab1d92ca3ecc2e6bcc05219fa3153392080 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/category_theory/functor/currying.lean | b62d53fbcbad9bde64dafa2a287e501aff30c428 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 3,582 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.products.bifunctor
/-!
# Curry and uncurry, as functors.
We define `curry : ((C × D) ⥤ E) ⥤ (C ⥤ (D ⥤ E))` and `uncurry : (C ⥤ (D ⥤ E)) ⥤ ((C × D) ⥤ E)`,
and verify that they provide an equivalence of categories
`currying : (C ⥤ (D ⥤ E)) ≌ ((C × D) ⥤ E)`.
-/
namespace category_theory
universes v₁ v₂ v₃ u₁ u₂ u₃
variables {C : Type u₁} [category.{v₁} C]
{D : Type u₂} [category.{v₂} D]
{E : Type u₃} [category.{v₃} E]
/--
The uncurrying functor, taking a functor `C ⥤ (D ⥤ E)` and producing a functor `(C × D) ⥤ E`.
-/
@[simps]
def uncurry : (C ⥤ (D ⥤ E)) ⥤ ((C × D) ⥤ E) :=
{ obj := λ F,
{ obj := λ X, (F.obj X.1).obj X.2,
map := λ X Y f, (F.map f.1).app X.2 ≫ (F.obj Y.1).map f.2,
map_comp' := λ X Y Z f g,
begin
simp only [prod_comp_fst, prod_comp_snd, functor.map_comp,
nat_trans.comp_app, category.assoc],
slice_lhs 2 3 { rw ← nat_trans.naturality },
rw category.assoc,
end },
map := λ F G T,
{ app := λ X, (T.app X.1).app X.2,
naturality' := λ X Y f,
begin
simp only [prod_comp_fst, prod_comp_snd, category.comp_id, category.assoc,
functor.map_id, functor.map_comp, nat_trans.id_app, nat_trans.comp_app],
slice_lhs 2 3 { rw nat_trans.naturality },
slice_lhs 1 2 { rw [←nat_trans.comp_app, nat_trans.naturality, nat_trans.comp_app] },
rw category.assoc,
end } }.
/--
The object level part of the currying functor. (See `curry` for the functorial version.)
-/
def curry_obj (F : (C × D) ⥤ E) : C ⥤ (D ⥤ E) :=
{ obj := λ X,
{ obj := λ Y, F.obj (X, Y),
map := λ Y Y' g, F.map (𝟙 X, g) },
map := λ X X' f, { app := λ Y, F.map (f, 𝟙 Y) } }
/--
The currying functor, taking a functor `(C × D) ⥤ E` and producing a functor `C ⥤ (D ⥤ E)`.
-/
@[simps obj_obj_obj obj_obj_map obj_map_app map_app_app]
def curry : ((C × D) ⥤ E) ⥤ (C ⥤ (D ⥤ E)) :=
{ obj := λ F, curry_obj F,
map := λ F G T,
{ app := λ X,
{ app := λ Y, T.app (X, Y),
naturality' := λ Y Y' g,
begin
dsimp [curry_obj],
rw nat_trans.naturality,
end },
naturality' := λ X X' f,
begin
ext, dsimp [curry_obj],
rw nat_trans.naturality,
end } }.
/--
The equivalence of functor categories given by currying/uncurrying.
-/
@[simps] -- create projection simp lemmas even though this isn't a `{ .. }`.
def currying : (C ⥤ (D ⥤ E)) ≌ ((C × D) ⥤ E) :=
equivalence.mk uncurry curry
(nat_iso.of_components (λ F, nat_iso.of_components
(λ X, nat_iso.of_components (λ Y, iso.refl _) (by tidy)) (by tidy)) (by tidy))
(nat_iso.of_components (λ F, nat_iso.of_components
(λ X, eq_to_iso (by simp)) (by tidy)) (by tidy))
/-- `F.flip` is isomorphic to uncurrying `F`, swapping the variables, and currying. -/
@[simps]
def flip_iso_curry_swap_uncurry (F : C ⥤ D ⥤ E) :
F.flip ≅ curry.obj (prod.swap _ _ ⋙ uncurry.obj F) :=
nat_iso.of_components (λ d, nat_iso.of_components (λ c, iso.refl _) (by tidy)) (by tidy)
/-- The uncurrying of `F.flip` is isomorphic to
swapping the factors followed by the uncurrying of `F`. -/
@[simps]
def uncurry_obj_flip (F : C ⥤ D ⥤ E) : uncurry.obj F.flip ≅ prod.swap _ _ ⋙ uncurry.obj F :=
nat_iso.of_components (λ p, iso.refl _) (by tidy)
end category_theory
|
6596c841ab44378e1b5ae092c8689cff54ee04fe | a4673261e60b025e2c8c825dfa4ab9108246c32e | /tests/lean/run/doNotation2.lean | 3892a6e87d0b8f448454f344674b0d9f55a8c6f9 | [
"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 | 4,050 | lean | def f (x : Nat) : IO Nat := do
IO.println "hello world"
let aux (y : Nat) (z : Nat) : IO Nat := do
IO.println "aux started"
IO.println s!"y: {y}, z: {z}"
pure (x+y)
aux x
(x + 1) -- It is part of the application since it is indented
aux x (x -- parentheses use `withoutPosition`
-1)
aux x x;
aux x
x
#eval f 10
def g (xs : List Nat) : StateT Nat Id Nat := do
let mut xs := xs
if xs.isEmpty then
xs := [← get]
dbgTrace! ">>> xs: {xs}"
return xs.length
#eval g [1, 2, 3] |>.run' 10
#eval g [] |>.run' 10
theorem ex1 : (g [1, 2, 4, 5] |>.run' 0) = 4 :=
rfl
theorem ex2 : (g [] |>.run' 0) = 1 :=
rfl
def h (x : Nat) (y : Nat) : Nat := do
let mut x := x
let mut y := y
if x > 0 then
let y := x + 1 -- this is a new `y` that shadows the one above
x := y
else
y := y + 1
return x + y
theorem ex3 (y : Nat) : h 0 y = 0 + (y + 1) :=
rfl
theorem ex4 (y : Nat) : h 1 y = (1 + 1) + y :=
rfl
def sumOdd (xs : List Nat) (threshold : Nat) : Nat := do
let mut sum := 0
for x in xs do
if x % 2 == 1 then
sum := sum + x
if sum > threshold then
break
unless x % 2 == 1 do
continue
dbgTrace! ">> x: {x}"
return sum
#eval sumOdd [1, 2, 3, 4, 5, 6, 7, 9, 11, 101] 10
theorem ex5 : sumOdd [1, 2, 3, 4, 5, 6, 7, 9, 11, 101] 10 = 16 :=
rfl
-- We need `Id.run` because we still have `Monad Option`
def find? (xs : List Nat) (p : Nat → Bool) : Option Nat := Id.run do
let mut result := none
for x in xs do
if p x then
result := x
break
return result
def sumDiff (ps : List (Nat × Nat)) : Nat := do
let mut sum := 0
for (x, y) in ps do
sum := sum + x - y
return sum
theorem ex7 : sumDiff [(2, 1), (10, 5)] = 6 :=
rfl
def f1 (x : Nat) : IO Unit := do
let rec loop : Nat → IO Unit
| 0 => pure ()
| x+1 => do IO.println x; loop x
loop x
#eval f1 10
partial def f2 (x : Nat) : IO Unit := do
let rec
isEven : Nat → Bool
| 0 => true
| x+1 => isOdd x,
isOdd : Nat → Bool
| 0 => false
| x+1 => isEven x
IO.println ("isOdd(" ++ toString x ++ "): " ++ toString (isOdd x))
#eval f2 11
#eval f2 10
def split (xs : List Nat) : List Nat × List Nat := do
let mut evens := []
let mut odds := []
for x in xs.reverse do
if x % 2 == 0 then
evens := x :: evens
else
odds := x :: odds
return (evens, odds)
theorem ex8 : split [1, 2, 3, 4] = ([2, 4], [1, 3]) :=
rfl
def f3 (x : Nat) : IO Bool := do
let y ← cond (x == 0) (do IO.println "hello"; true) false;
!y
def f4 (x y : Nat) : Nat × Nat := do
let mut (x, y) := (x, y)
match x with
| 0 => y := y + 1
| _ => x := x + y
return (x, y)
#eval f4 0 10
#eval f4 5 10
theorem ex9 (y : Nat) : f4 0 y = (0, y+1) :=
rfl
theorem ex10 (x y : Nat) : f4 (x+1) y = ((x+1)+y, y) :=
rfl
def f5 (x y : Nat) : Nat × Nat := do
let mut (x, y) := (x, y)
match x with
| 0 => y := y + 1
| z+1 => dbgTrace! "z: {z}"; x := x + y
return (x, y)
#eval f5 5 6
theorem ex11 (x y : Nat) : f5 (x+1) y = ((x+1)+y, y) :=
rfl
def f6 (x : Nat) : Nat := do
let mut x := x
if x > 10 then
return 0
x := x + 1
return x
theorem ex12 : f6 11 = 0 :=
rfl
theorem ex13 : f6 5 = 6 :=
rfl
def findOdd (xs : List Nat) : Nat := do
for x in xs do
if x % 2 == 1 then
return x
return 0
theorem ex14 : findOdd [2, 4, 5, 8, 7] = 5 :=
rfl
theorem ex15 : findOdd [2, 4, 8, 10] = 0 :=
rfl
def f7 (ref : IO.Ref (Option (Nat × Nat))) : IO Nat := do
let some (x, y) ← ref.get | pure 100
IO.println (toString x ++ ", " ++ toString y)
return x+y
def f7Test : IO Unit := do
unless (← f7 (← IO.mkRef (some (10, 20)))) == 30 do throw $ IO.userError "unexpected"
unless (← f7 (← IO.mkRef none)) == 100 do throw $ IO.userError "unexpected"
#eval f7Test
def f8 (x : Nat) : IO Nat := do
let y ←
if x == 0 then
IO.println "x is zero"
return 100 -- returns from the `do`-block
else
pure (x + 1)
IO.println ("y: " ++ toString y)
return y
def f8Test : IO Unit := do
unless (← f8 0) == 100 do throw $ IO.userError "unexpected"
unless (← f8 1) == 2 do throw $ IO.userError "unexpected"
#eval f8Test
|
d19cac7309b38beb3253ca60917a0d976da4c1b0 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/set/intervals/image_preimage.lean | b5149ed2e2baed58130c5e9853a904032552dfec | [
"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 | 20,648 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov, Patrick Massot
-/
import data.set.intervals.basic
import data.equiv.mul_add
import algebra.pointwise
/-!
# (Pre)images of intervals
In this file we prove a bunch of trivial lemmas like “if we add `a` to all points of `[b, c]`,
then we get `[a + b, a + c]`”. For the functions `x ↦ x ± a`, `x ↦ a ± x`, and `x ↦ -x` we prove
lemmas about preimages and images of all intervals. We also prove a few lemmas about images under
`x ↦ a * x`, `x ↦ x * a` and `x ↦ x⁻¹`.
-/
universe u
open_locale pointwise
namespace set
section has_exists_add_of_le
/-!
The lemmas in this section state that addition maps intervals bijectively. The typeclass
`has_exists_add_of_le` is defined specifically to make them work when combined with
`ordered_cancel_add_comm_monoid`; the lemmas below therefore apply to all
`ordered_add_comm_group`, but also to `ℕ` and `ℝ≥0`, which are not groups.
TODO : move as much as possible in this file to the setting of this weaker typeclass.
-/
variables {α : Type u} [ordered_cancel_add_comm_monoid α] [has_exists_add_of_le α] (a b d : α)
lemma Icc_add_bij : bij_on (+d) (Icc a b) (Icc (a + d) (b + d)) :=
begin
refine ⟨λ _ h, ⟨add_le_add_right h.1 _, add_le_add_right h.2 _⟩,
λ _ _ _ _ h, add_right_cancel h,
λ _ h, _⟩,
obtain ⟨c, rfl⟩ := exists_add_of_le h.1,
rw [mem_Icc, add_right_comm, add_le_add_iff_right, add_le_add_iff_right] at h,
exact ⟨a + c, h, by rw add_right_comm⟩,
end
lemma Ioo_add_bij : bij_on (+d) (Ioo a b) (Ioo (a + d) (b + d)) :=
begin
refine ⟨λ _ h, ⟨add_lt_add_right h.1 _, add_lt_add_right h.2 _⟩,
λ _ _ _ _ h, add_right_cancel h,
λ _ h, _⟩,
obtain ⟨c, rfl⟩ := exists_add_of_le h.1.le,
rw [mem_Ioo, add_right_comm, add_lt_add_iff_right, add_lt_add_iff_right] at h,
exact ⟨a + c, h, by rw add_right_comm⟩,
end
lemma Ioc_add_bij : bij_on (+d) (Ioc a b) (Ioc (a + d) (b + d)) :=
begin
refine ⟨λ _ h, ⟨add_lt_add_right h.1 _, add_le_add_right h.2 _⟩,
λ _ _ _ _ h, add_right_cancel h,
λ _ h, _⟩,
obtain ⟨c, rfl⟩ := exists_add_of_le h.1.le,
rw [mem_Ioc, add_right_comm, add_lt_add_iff_right, add_le_add_iff_right] at h,
exact ⟨a + c, h, by rw add_right_comm⟩,
end
lemma Ico_add_bij : bij_on (+d) (Ico a b) (Ico (a + d) (b + d)) :=
begin
refine ⟨λ _ h, ⟨add_le_add_right h.1 _, add_lt_add_right h.2 _⟩,
λ _ _ _ _ h, add_right_cancel h,
λ _ h, _⟩,
obtain ⟨c, rfl⟩ := exists_add_of_le h.1,
rw [mem_Ico, add_right_comm, add_le_add_iff_right, add_lt_add_iff_right] at h,
exact ⟨a + c, h, by rw add_right_comm⟩,
end
lemma Ici_add_bij : bij_on (+d) (Ici a) (Ici (a + d)) :=
begin
refine ⟨λ x h, add_le_add_right (mem_Ici.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩,
obtain ⟨c, rfl⟩ := exists_add_of_le (mem_Ici.mp h),
rw [mem_Ici, add_right_comm, add_le_add_iff_right] at h,
exact ⟨a + c, h, by rw add_right_comm⟩,
end
lemma Ioi_add_bij : bij_on (+d) (Ioi a) (Ioi (a + d)) :=
begin
refine ⟨λ x h, add_lt_add_right (mem_Ioi.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩,
obtain ⟨c, rfl⟩ := exists_add_of_le (mem_Ioi.mp h).le,
rw [mem_Ioi, add_right_comm, add_lt_add_iff_right] at h,
exact ⟨a + c, h, by rw add_right_comm⟩,
end
end has_exists_add_of_le
section ordered_add_comm_group
variables {G : Type u} [ordered_add_comm_group G] (a b c : G)
/-!
### Preimages under `x ↦ a + x`
-/
@[simp] lemma preimage_const_add_Ici : (λ x, a + x) ⁻¹' (Ici b) = Ici (b - a) :=
ext $ λ x, sub_le_iff_le_add'.symm
@[simp] lemma preimage_const_add_Ioi : (λ x, a + x) ⁻¹' (Ioi b) = Ioi (b - a) :=
ext $ λ x, sub_lt_iff_lt_add'.symm
@[simp] lemma preimage_const_add_Iic : (λ x, a + x) ⁻¹' (Iic b) = Iic (b - a) :=
ext $ λ x, le_sub_iff_add_le'.symm
@[simp] lemma preimage_const_add_Iio : (λ x, a + x) ⁻¹' (Iio b) = Iio (b - a) :=
ext $ λ x, lt_sub_iff_add_lt'.symm
@[simp] lemma preimage_const_add_Icc : (λ x, a + x) ⁻¹' (Icc b c) = Icc (b - a) (c - a) :=
by simp [← Ici_inter_Iic]
@[simp] lemma preimage_const_add_Ico : (λ x, a + x) ⁻¹' (Ico b c) = Ico (b - a) (c - a) :=
by simp [← Ici_inter_Iio]
@[simp] lemma preimage_const_add_Ioc : (λ x, a + x) ⁻¹' (Ioc b c) = Ioc (b - a) (c - a) :=
by simp [← Ioi_inter_Iic]
@[simp] lemma preimage_const_add_Ioo : (λ x, a + x) ⁻¹' (Ioo b c) = Ioo (b - a) (c - a) :=
by simp [← Ioi_inter_Iio]
/-!
### Preimages under `x ↦ x + a`
-/
@[simp] lemma preimage_add_const_Ici : (λ x, x + a) ⁻¹' (Ici b) = Ici (b - a) :=
ext $ λ x, sub_le_iff_le_add.symm
@[simp] lemma preimage_add_const_Ioi : (λ x, x + a) ⁻¹' (Ioi b) = Ioi (b - a) :=
ext $ λ x, sub_lt_iff_lt_add.symm
@[simp] lemma preimage_add_const_Iic : (λ x, x + a) ⁻¹' (Iic b) = Iic (b - a) :=
ext $ λ x, le_sub_iff_add_le.symm
@[simp] lemma preimage_add_const_Iio : (λ x, x + a) ⁻¹' (Iio b) = Iio (b - a) :=
ext $ λ x, lt_sub_iff_add_lt.symm
@[simp] lemma preimage_add_const_Icc : (λ x, x + a) ⁻¹' (Icc b c) = Icc (b - a) (c - a) :=
by simp [← Ici_inter_Iic]
@[simp] lemma preimage_add_const_Ico : (λ x, x + a) ⁻¹' (Ico b c) = Ico (b - a) (c - a) :=
by simp [← Ici_inter_Iio]
@[simp] lemma preimage_add_const_Ioc : (λ x, x + a) ⁻¹' (Ioc b c) = Ioc (b - a) (c - a) :=
by simp [← Ioi_inter_Iic]
@[simp] lemma preimage_add_const_Ioo : (λ x, x + a) ⁻¹' (Ioo b c) = Ioo (b - a) (c - a) :=
by simp [← Ioi_inter_Iio]
/-!
### Preimages under `x ↦ -x`
-/
@[simp] lemma preimage_neg_Ici : - Ici a = Iic (-a) := ext $ λ x, le_neg
@[simp] lemma preimage_neg_Iic : - Iic a = Ici (-a) := ext $ λ x, neg_le
@[simp] lemma preimage_neg_Ioi : - Ioi a = Iio (-a) := ext $ λ x, lt_neg
@[simp] lemma preimage_neg_Iio : - Iio a = Ioi (-a) := ext $ λ x, neg_lt
@[simp] lemma preimage_neg_Icc : - Icc a b = Icc (-b) (-a) :=
by simp [← Ici_inter_Iic, inter_comm]
@[simp] lemma preimage_neg_Ico : - Ico a b = Ioc (-b) (-a) :=
by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, inter_comm]
@[simp] lemma preimage_neg_Ioc : - Ioc a b = Ico (-b) (-a) :=
by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm]
@[simp] lemma preimage_neg_Ioo : - Ioo a b = Ioo (-b) (-a) :=
by simp [← Ioi_inter_Iio, inter_comm]
/-!
### Preimages under `x ↦ x - a`
-/
@[simp] lemma preimage_sub_const_Ici : (λ x, x - a) ⁻¹' (Ici b) = Ici (b + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Ioi : (λ x, x - a) ⁻¹' (Ioi b) = Ioi (b + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Iic : (λ x, x - a) ⁻¹' (Iic b) = Iic (b + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Iio : (λ x, x - a) ⁻¹' (Iio b) = Iio (b + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Icc : (λ x, x - a) ⁻¹' (Icc b c) = Icc (b + a) (c + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Ico : (λ x, x - a) ⁻¹' (Ico b c) = Ico (b + a) (c + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Ioc : (λ x, x - a) ⁻¹' (Ioc b c) = Ioc (b + a) (c + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Ioo : (λ x, x - a) ⁻¹' (Ioo b c) = Ioo (b + a) (c + a) :=
by simp [sub_eq_add_neg]
/-!
### Preimages under `x ↦ a - x`
-/
@[simp] lemma preimage_const_sub_Ici : (λ x, a - x) ⁻¹' (Ici b) = Iic (a - b) :=
ext $ λ x, le_sub
@[simp] lemma preimage_const_sub_Iic : (λ x, a - x) ⁻¹' (Iic b) = Ici (a - b) :=
ext $ λ x, sub_le
@[simp] lemma preimage_const_sub_Ioi : (λ x, a - x) ⁻¹' (Ioi b) = Iio (a - b) :=
ext $ λ x, lt_sub
@[simp] lemma preimage_const_sub_Iio : (λ x, a - x) ⁻¹' (Iio b) = Ioi (a - b) :=
ext $ λ x, sub_lt
@[simp] lemma preimage_const_sub_Icc : (λ x, a - x) ⁻¹' (Icc b c) = Icc (a - c) (a - b) :=
by simp [← Ici_inter_Iic, inter_comm]
@[simp] lemma preimage_const_sub_Ico : (λ x, a - x) ⁻¹' (Ico b c) = Ioc (a - c) (a - b) :=
by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm]
@[simp] lemma preimage_const_sub_Ioc : (λ x, a - x) ⁻¹' (Ioc b c) = Ico (a - c) (a - b) :=
by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm]
@[simp] lemma preimage_const_sub_Ioo : (λ x, a - x) ⁻¹' (Ioo b c) = Ioo (a - c) (a - b) :=
by simp [← Ioi_inter_Iio, inter_comm]
/-!
### Images under `x ↦ a + x`
-/
@[simp] lemma image_const_add_Ici : (λ x, a + x) '' Ici b = Ici (a + b) :=
by simp [add_comm]
@[simp] lemma image_const_add_Iic : (λ x, a + x) '' Iic b = Iic (a + b) :=
by simp [add_comm]
@[simp] lemma image_const_add_Iio : (λ x, a + x) '' Iio b = Iio (a + b) :=
by simp [add_comm]
@[simp] lemma image_const_add_Ioi : (λ x, a + x) '' Ioi b = Ioi (a + b) :=
by simp [add_comm]
@[simp] lemma image_const_add_Icc : (λ x, a + x) '' Icc b c = Icc (a + b) (a + c) :=
by simp [add_comm]
@[simp] lemma image_const_add_Ico : (λ x, a + x) '' Ico b c = Ico (a + b) (a + c) :=
by simp [add_comm]
@[simp] lemma image_const_add_Ioc : (λ x, a + x) '' Ioc b c = Ioc (a + b) (a + c) :=
by simp [add_comm]
@[simp] lemma image_const_add_Ioo : (λ x, a + x) '' Ioo b c = Ioo (a + b) (a + c) :=
by simp [add_comm]
/-!
### Images under `x ↦ x + a`
-/
@[simp] lemma image_add_const_Ici : (λ x, x + a) '' Ici b = Ici (b + a) := by simp
@[simp] lemma image_add_const_Iic : (λ x, x + a) '' Iic b = Iic (b + a) := by simp
@[simp] lemma image_add_const_Iio : (λ x, x + a) '' Iio b = Iio (b + a) := by simp
@[simp] lemma image_add_const_Ioi : (λ x, x + a) '' Ioi b = Ioi (b + a) := by simp
@[simp] lemma image_add_const_Icc : (λ x, x + a) '' Icc b c = Icc (b + a) (c + a) :=
by simp
@[simp] lemma image_add_const_Ico : (λ x, x + a) '' Ico b c = Ico (b + a) (c + a) :=
by simp
@[simp] lemma image_add_const_Ioc : (λ x, x + a) '' Ioc b c = Ioc (b + a) (c + a) :=
by simp
@[simp] lemma image_add_const_Ioo : (λ x, x + a) '' Ioo b c = Ioo (b + a) (c + a) :=
by simp
/-!
### Images under `x ↦ -x`
-/
lemma image_neg_Ici : has_neg.neg '' (Ici a) = Iic (-a) := by simp
lemma image_neg_Iic : has_neg.neg '' (Iic a) = Ici (-a) := by simp
lemma image_neg_Ioi : has_neg.neg '' (Ioi a) = Iio (-a) := by simp
lemma image_neg_Iio : has_neg.neg '' (Iio a) = Ioi (-a) := by simp
lemma image_neg_Icc : has_neg.neg '' (Icc a b) = Icc (-b) (-a) := by simp
lemma image_neg_Ico : has_neg.neg '' (Ico a b) = Ioc (-b) (-a) := by simp
lemma image_neg_Ioc : has_neg.neg '' (Ioc a b) = Ico (-b) (-a) := by simp
lemma image_neg_Ioo : has_neg.neg '' (Ioo a b) = Ioo (-b) (-a) := by simp
/-!
### Images under `x ↦ a - x`
-/
@[simp] lemma image_const_sub_Ici : (λ x, a - x) '' Ici b = Iic (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_const_sub_Iic : (λ x, a - x) '' Iic b = Ici (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_const_sub_Ioi : (λ x, a - x) '' Ioi b = Iio (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_const_sub_Iio : (λ x, a - x) '' Iio b = Ioi (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_const_sub_Icc : (λ x, a - x) '' Icc b c = Icc (a - c) (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_const_sub_Ico : (λ x, a - x) '' Ico b c = Ioc (a - c) (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_const_sub_Ioc : (λ x, a - x) '' Ioc b c = Ico (a - c) (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_const_sub_Ioo : (λ x, a - x) '' Ioo b c = Ioo (a - c) (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
/-!
### Images under `x ↦ x - a`
-/
@[simp] lemma image_sub_const_Ici : (λ x, x - a) '' Ici b = Ici (b - a) := by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Iic : (λ x, x - a) '' Iic b = Iic (b - a) := by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Ioi : (λ x, x - a) '' Ioi b = Ioi (b - a) := by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Iio : (λ x, x - a) '' Iio b = Iio (b - a) := by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Icc : (λ x, x - a) '' Icc b c = Icc (b - a) (c - a) :=
by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Ico : (λ x, x - a) '' Ico b c = Ico (b - a) (c - a) :=
by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Ioc : (λ x, x - a) '' Ioc b c = Ioc (b - a) (c - a) :=
by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Ioo : (λ x, x - a) '' Ioo b c = Ioo (b - a) (c - a) :=
by simp [sub_eq_neg_add]
/-!
### Bijections
-/
lemma Iic_add_bij : bij_on (+a) (Iic b) (Iic (b + a)) :=
begin
refine ⟨λ x h, add_le_add_right (mem_Iic.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩,
simpa [add_comm a] using h,
end
lemma Iio_add_bij : bij_on (+a) (Iio b) (Iio (b + a)) :=
begin
refine ⟨λ x h, add_lt_add_right (mem_Iio.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩,
simpa [add_comm a] using h,
end
end ordered_add_comm_group
/-!
### Multiplication and inverse in a field
-/
section linear_ordered_field
variables {k : Type u} [linear_ordered_field k]
@[simp] lemma preimage_mul_const_Iio (a : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Iio a) = Iio (a / c) :=
ext $ λ x, (lt_div_iff h).symm
@[simp] lemma preimage_mul_const_Ioi (a : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Ioi a) = Ioi (a / c) :=
ext $ λ x, (div_lt_iff h).symm
@[simp] lemma preimage_mul_const_Iic (a : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Iic a) = Iic (a / c) :=
ext $ λ x, (le_div_iff h).symm
@[simp] lemma preimage_mul_const_Ici (a : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Ici a) = Ici (a / c) :=
ext $ λ x, (div_le_iff h).symm
@[simp] lemma preimage_mul_const_Ioo (a b : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Ioo a b) = Ioo (a / c) (b / c) :=
by simp [← Ioi_inter_Iio, h]
@[simp] lemma preimage_mul_const_Ioc (a b : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Ioc a b) = Ioc (a / c) (b / c) :=
by simp [← Ioi_inter_Iic, h]
@[simp] lemma preimage_mul_const_Ico (a b : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Ico a b) = Ico (a / c) (b / c) :=
by simp [← Ici_inter_Iio, h]
@[simp] lemma preimage_mul_const_Icc (a b : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Icc a b) = Icc (a / c) (b / c) :=
by simp [← Ici_inter_Iic, h]
@[simp] lemma preimage_mul_const_Iio_of_neg (a : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Iio a) = Ioi (a / c) :=
ext $ λ x, (div_lt_iff_of_neg h).symm
@[simp] lemma preimage_mul_const_Ioi_of_neg (a : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Ioi a) = Iio (a / c) :=
ext $ λ x, (lt_div_iff_of_neg h).symm
@[simp] lemma preimage_mul_const_Iic_of_neg (a : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Iic a) = Ici (a / c) :=
ext $ λ x, (div_le_iff_of_neg h).symm
@[simp] lemma preimage_mul_const_Ici_of_neg (a : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Ici a) = Iic (a / c) :=
ext $ λ x, (le_div_iff_of_neg h).symm
@[simp] lemma preimage_mul_const_Ioo_of_neg (a b : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Ioo a b) = Ioo (b / c) (a / c) :=
by simp [← Ioi_inter_Iio, h, inter_comm]
@[simp] lemma preimage_mul_const_Ioc_of_neg (a b : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Ioc a b) = Ico (b / c) (a / c) :=
by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, h, inter_comm]
@[simp] lemma preimage_mul_const_Ico_of_neg (a b : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Ico a b) = Ioc (b / c) (a / c) :=
by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, h, inter_comm]
@[simp] lemma preimage_mul_const_Icc_of_neg (a b : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Icc a b) = Icc (b / c) (a / c) :=
by simp [← Ici_inter_Iic, h, inter_comm]
@[simp] lemma preimage_const_mul_Iio (a : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Iio a) = Iio (a / c) :=
ext $ λ x, (lt_div_iff' h).symm
@[simp] lemma preimage_const_mul_Ioi (a : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Ioi a) = Ioi (a / c) :=
ext $ λ x, (div_lt_iff' h).symm
@[simp] lemma preimage_const_mul_Iic (a : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Iic a) = Iic (a / c) :=
ext $ λ x, (le_div_iff' h).symm
@[simp] lemma preimage_const_mul_Ici (a : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Ici a) = Ici (a / c) :=
ext $ λ x, (div_le_iff' h).symm
@[simp] lemma preimage_const_mul_Ioo (a b : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Ioo a b) = Ioo (a / c) (b / c) :=
by simp [← Ioi_inter_Iio, h]
@[simp] lemma preimage_const_mul_Ioc (a b : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Ioc a b) = Ioc (a / c) (b / c) :=
by simp [← Ioi_inter_Iic, h]
@[simp] lemma preimage_const_mul_Ico (a b : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Ico a b) = Ico (a / c) (b / c) :=
by simp [← Ici_inter_Iio, h]
@[simp] lemma preimage_const_mul_Icc (a b : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Icc a b) = Icc (a / c) (b / c) :=
by simp [← Ici_inter_Iic, h]
@[simp] lemma preimage_const_mul_Iio_of_neg (a : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Iio a) = Ioi (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Iio_of_neg a h
@[simp] lemma preimage_const_mul_Ioi_of_neg (a : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Ioi a) = Iio (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Ioi_of_neg a h
@[simp] lemma preimage_const_mul_Iic_of_neg (a : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Iic a) = Ici (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Iic_of_neg a h
@[simp] lemma preimage_const_mul_Ici_of_neg (a : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Ici a) = Iic (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Ici_of_neg a h
@[simp] lemma preimage_const_mul_Ioo_of_neg (a b : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Ioo a b) = Ioo (b / c) (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Ioo_of_neg a b h
@[simp] lemma preimage_const_mul_Ioc_of_neg (a b : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Ioc a b) = Ico (b / c) (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Ioc_of_neg a b h
@[simp] lemma preimage_const_mul_Ico_of_neg (a b : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Ico a b) = Ioc (b / c) (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Ico_of_neg a b h
@[simp] lemma preimage_const_mul_Icc_of_neg (a b : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Icc a b) = Icc (b / c) (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Icc_of_neg a b h
lemma image_mul_right_Icc' (a b : k) {c : k} (h : 0 < c) :
(λ x, x * c) '' Icc a b = Icc (a * c) (b * c) :=
((units.mk0 c h.ne').mul_right.image_eq_preimage _).trans (by simp [h, division_def])
lemma image_mul_right_Icc {a b c : k} (hab : a ≤ b) (hc : 0 ≤ c) :
(λ x, x * c) '' Icc a b = Icc (a * c) (b * c) :=
begin
cases eq_or_lt_of_le hc,
{ subst c,
simp [(nonempty_Icc.2 hab).image_const] },
exact image_mul_right_Icc' a b ‹0 < c›
end
lemma image_mul_left_Icc' {a : k} (h : 0 < a) (b c : k) :
((*) a) '' Icc b c = Icc (a * b) (a * c) :=
by { convert image_mul_right_Icc' b c h using 1; simp only [mul_comm _ a] }
lemma image_mul_left_Icc {a b c : k} (ha : 0 ≤ a) (hbc : b ≤ c) :
((*) a) '' Icc b c = Icc (a * b) (a * c) :=
by { convert image_mul_right_Icc hbc ha using 1; simp only [mul_comm _ a] }
lemma image_mul_right_Ioo (a b : k) {c : k} (h : 0 < c) :
(λ x, x * c) '' Ioo a b = Ioo (a * c) (b * c) :=
((units.mk0 c h.ne').mul_right.image_eq_preimage _).trans (by simp [h, division_def])
lemma image_mul_left_Ioo {a : k} (h : 0 < a) (b c : k) :
((*) a) '' Ioo b c = Ioo (a * b) (a * c) :=
by { convert image_mul_right_Ioo b c h using 1; simp only [mul_comm _ a] }
/-- The image under `inv` of `Ioo 0 a` is `Ioi a⁻¹`. -/
lemma image_inv_Ioo_0_left {a : k} (ha : 0 < a) : has_inv.inv '' Ioo 0 a = Ioi a⁻¹ :=
begin
ext x,
exact ⟨λ ⟨y, ⟨hy0, hya⟩, hyx⟩, hyx ▸ (inv_lt_inv ha hy0).2 hya, λ h, ⟨x⁻¹, ⟨inv_pos.2 (lt_trans
(inv_pos.2 ha) h), (inv_lt ha (lt_trans (inv_pos.2 ha) h)).1 h⟩, inv_inv₀ x⟩⟩,
end
/-!
### Images under `x ↦ a * x + b`
-/
@[simp] lemma image_affine_Icc' {a : k} (h : 0 < a) (b c d : k) :
(λ x, a * x + b) '' Icc c d = Icc (a * c + b) (a * d + b) :=
begin
suffices : (λ x, x + b) '' ((λ x, a * x) '' Icc c d) = Icc (a * c + b) (a * d + b),
{ rwa set.image_image at this, },
rw [image_mul_left_Icc' h, image_add_const_Icc],
end
end linear_ordered_field
end set
|
1c80e22cfdc86b60438eccd0fee9d59a04aaa1ef | cf39355caa609c0f33405126beee2739aa3cb77e | /library/init/data/to_string.lean | da331460474c091aae5c7d0f4df896d47f3bb5de | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 2,842 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import init.data.string.basic init.data.bool.basic init.data.subtype.basic
import init.data.unsigned.basic init.data.prod init.data.sum.basic init.data.nat.div
import init.data.repr
open sum subtype nat
universes u v
/-- Convert the object into a string for tracing/display purposes.
Similar to Haskell's `show`.
See also `has_repr`, which is used to output a string which is a valid lean code.
See also `has_to_format` and `has_to_tactic_format`, `format` has additional support for colours and pretty printing multilines.
-/
class has_to_string (α : Type u) :=
(to_string : α → string)
def to_string {α : Type u} [has_to_string α] : α → string :=
has_to_string.to_string
instance : has_to_string string :=
⟨λ s, s⟩
instance : has_to_string bool :=
⟨λ b, cond b "tt" "ff"⟩
instance {p : Prop} : has_to_string (decidable p) :=
-- Remark: type class inference will not consider local instance `b` in the new elaborator
⟨λ b : decidable p, @ite _ p b "tt" "ff"⟩
protected def list.to_string_aux {α : Type u} [has_to_string α] : bool → list α → string
| b [] := ""
| tt (x::xs) := to_string x ++ list.to_string_aux ff xs
| ff (x::xs) := ", " ++ to_string x ++ list.to_string_aux ff xs
protected def list.to_string {α : Type u} [has_to_string α] : list α → string
| [] := "[]"
| (x::xs) := "[" ++ list.to_string_aux tt (x::xs) ++ "]"
instance {α : Type u} [has_to_string α] : has_to_string (list α) :=
⟨list.to_string⟩
instance : has_to_string unit :=
⟨λ u, "star"⟩
instance : has_to_string nat :=
⟨λ n, repr n⟩
instance : has_to_string char :=
⟨λ c, c.to_string⟩
instance (n : nat) : has_to_string (fin n) :=
⟨λ f, to_string f.val⟩
instance : has_to_string unsigned :=
⟨λ n, to_string n.val⟩
instance {α : Type u} [has_to_string α] : has_to_string (option α) :=
⟨λ o, match o with | none := "none" | (some a) := "(some " ++ to_string a ++ ")" end⟩
instance {α : Type u} {β : Type v} [has_to_string α] [has_to_string β] : has_to_string (α ⊕ β) :=
⟨λ s, match s with | (inl a) := "(inl " ++ to_string a ++ ")" | (inr b) := "(inr " ++ to_string b ++ ")" end⟩
instance {α : Type u} {β : Type v} [has_to_string α] [has_to_string β] : has_to_string (α × β) :=
⟨λ ⟨a, b⟩, "(" ++ to_string a ++ ", " ++ to_string b ++ ")"⟩
instance {α : Type u} {β : α → Type v} [has_to_string α] [s : ∀ x, has_to_string (β x)] : has_to_string (sigma β) :=
⟨λ ⟨a, b⟩, "⟨" ++ to_string a ++ ", " ++ to_string b ++ "⟩"⟩
instance {α : Type u} {p : α → Prop} [has_to_string α] : has_to_string (subtype p) :=
⟨λ s, to_string (val s)⟩
|
3fff95dd83641a22ce3bd4c1038d81fba86cf762 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/measure_theory/giry_monad.lean | b37bcea79f01187a4a313fa2ae3dc45029e646e6 | [
"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 | 8,555 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import measure_theory.integration
/-!
# The Giry monad
Let X be a measurable space. The collection of all measures on X again
forms a measurable space. This construction forms a monad on
measurable spaces and measurable functions, called the Giry monad.
Note that most sources use the term "Giry monad" for the restriction
to *probability* measures. Here we include all measures on X.
See also `measure_theory/category/Meas.lean`, containing an upgrade of the type-level
monad to an honest monad of the functor `Measure : Meas ⥤ Meas`.
## References
* <https://ncatlab.org/nlab/show/Giry+monad>
## Tags
giry monad
-/
noncomputable theory
open_locale classical
open classical set lattice filter
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ε : Type*}
namespace measure_theory
namespace measure
variables [measurable_space α] [measurable_space β]
/-- Measurability structure on `measure`: Measures are measurable w.r.t. all projections -/
instance : measurable_space (measure α) :=
⨆ (s : set α) (hs : is_measurable s), (borel ennreal).comap (λμ, μ s)
lemma measurable_coe {s : set α} (hs : is_measurable s) : measurable (λμ : measure α, μ s) :=
measurable_space.comap_le_iff_le_map.1 $ le_supr_of_le s $ le_supr_of_le hs $ le_refl _
lemma measurable_of_measurable_coe (f : β → measure α)
(h : ∀(s : set α) (hs : is_measurable s), measurable (λb, f b s)) :
measurable f :=
supr_le $ assume s, supr_le $ assume hs, measurable_space.comap_le_iff_le_map.2 $
by rw [measurable_space.map_comp]; exact h s hs
lemma measurable_map (f : α → β) (hf : measurable f) :
measurable (λμ : measure α, μ.map f) :=
measurable_of_measurable_coe _ $ assume s hs,
suffices measurable (λ (μ : measure α), μ (f ⁻¹' s)),
by simpa [map_apply, hs, hf],
measurable_coe (hf.preimage hs)
lemma measurable_dirac :
measurable (measure.dirac : α → measure α) :=
measurable_of_measurable_coe _ $ assume s hs,
begin
simp [hs, lattice.supr_eq_if],
exact measurable_const.if hs measurable_const
end
lemma measurable_integral (f : α → ennreal) (hf : measurable f) :
measurable (λμ : measure α, μ.integral f) :=
suffices measurable (λμ : measure α,
(⨆n:ℕ, @simple_func.integral α { μ := μ } (simple_func.eapprox f n)) : _ → ennreal),
begin
convert this,
funext μ,
exact @lintegral_eq_supr_eapprox_integral α {μ := μ} f hf
end,
measurable.supr $ assume n,
begin
dunfold simple_func.integral,
refine measurable_finset_sum (simple_func.eapprox f n).range _,
assume i,
refine ennreal.measurable.mul measurable_const _,
exact measurable_coe ((simple_func.eapprox f n).preimage_measurable _)
end
/-- Monadic join on `measure` in the category of measurable spaces and measurable
functions. -/
def join (m : measure (measure α)) : measure α :=
measure.of_measurable
(λs hs, m.integral (λμ, μ s))
(by simp [integral])
begin
assume f hf h,
simp [measure_Union h hf],
apply lintegral_tsum,
assume i, exact measurable_coe (hf i)
end
@[simp] lemma join_apply {m : measure (measure α)} :
∀{s : set α}, is_measurable s → join m s = m.integral (λμ, μ s) :=
measure.of_measurable_apply
lemma measurable_join : measurable (join : measure (measure α) → measure α) :=
measurable_of_measurable_coe _ $ assume s hs,
by simp [hs]; exact measurable_integral _ (measurable_coe hs)
lemma integral_join {m : measure (measure α)} {f : α → ennreal} (hf : measurable f) :
integral (join m) f = integral m (λμ, integral μ f) :=
begin
transitivity,
apply lintegral_eq_supr_eapprox_integral,
{ exact hf },
have : ∀n x,
@volume α { μ := join m} (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x}) =
m.integral (λμ, @volume α { μ := μ } ((⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x}))) :=
assume n x, join_apply (simple_func.measurable_sn _ _),
conv {
to_lhs,
congr,
funext,
rw [simple_func.integral] },
simp [this],
transitivity,
have : ∀(s : ℕ → finset ennreal) (f : ℕ → ennreal → measure α → ennreal)
(hf : ∀n r, measurable (f n r)) (hm : monotone (λn μ, (s n).sum (λ r, r * f n r μ))),
(⨆n:ℕ, (s n).sum (λr, r * integral m (f n r))) =
integral m (λμ, ⨆n:ℕ, (s n).sum (λr, r * f n r μ)),
{ assume s f hf hm,
symmetry,
transitivity,
apply lintegral_supr,
{ exact assume n,
measurable_finset_sum _ (assume r, ennreal.measurable.mul measurable_const (hf _ _)) },
{ exact hm },
congr, funext n,
transitivity,
apply lintegral_finset_sum,
{ exact assume r, ennreal.measurable.mul measurable_const (hf _ _) },
congr, funext r,
apply lintegral_const_mul,
exact hf _ _ },
specialize this (λn, simple_func.range (simple_func.eapprox f n)),
specialize this
(λn r μ, @volume α { μ := μ } (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {r})),
refine this _ _; clear this,
{ assume n r,
apply measurable_coe,
exact simple_func.measurable_sn _ _ },
{ change monotone (λn μ, @simple_func.integral α {μ := μ} (simple_func.eapprox f n)),
assume n m h μ,
apply simple_func.integral_le_integral,
apply simple_func.monotone_eapprox,
assumption },
congr, funext μ,
symmetry,
apply lintegral_eq_supr_eapprox_integral,
exact hf
end
/-- Monadic bind on `measure`, only works in the category of measurable spaces and measurable
functions. When the function `f` is not measurable the result is not well defined. -/
def bind (m : measure α) (f : α → measure β) : measure β := join (map f m)
@[simp] lemma bind_apply {m : measure α} {f : α → measure β} {s : set β}
(hs : is_measurable s) (hf : measurable f) : bind m f s = m.integral (λa, f a s) :=
by rw [bind, join_apply hs, integral_map (measurable_coe hs) hf]
lemma measurable_bind' {g : α → measure β} (hg : measurable g) : measurable (λm, bind m g) :=
measurable_join.comp (measurable_map _ hg)
lemma integral_bind {m : measure α} {g : α → measure β} {f : β → ennreal}
(hg : measurable g) (hf : measurable f) :
integral (bind m g) f = integral m (λa, integral (g a) f) :=
begin
transitivity,
exact integral_join hf,
exact integral_map (measurable_integral _ hf) hg
end
lemma bind_bind {γ} [measurable_space γ] {m : measure α} {f : α → measure β} {g : β → measure γ}
(hf : measurable f) (hg : measurable g) :
bind (bind m f) g = bind m (λa, bind (f a) g) :=
measure.ext $ assume s hs,
begin
rw [bind_apply hs hg, bind_apply hs ((measurable_bind' hg).comp hf), integral_bind hf],
{ congr, funext a,
exact (bind_apply hs hg).symm },
exact (measurable_coe hs).comp hg
end
lemma bind_dirac {f : α → measure β} (hf : measurable f) (a : α) : bind (dirac a) f = f a :=
measure.ext $ assume s hs, by rw [bind_apply hs hf, integral_dirac a ((measurable_coe hs).comp hf)]
lemma dirac_bind {m : measure α} : bind m dirac = m :=
measure.ext $ assume s hs,
begin
rw [bind_apply hs measurable_dirac],
simp [dirac_apply _ hs],
transitivity,
apply lintegral_supr_const,
assumption,
exact one_mul _
end
lemma map_dirac {f : α → β} (hf : measurable f) (a : α) :
map f (dirac a) = dirac (f a) :=
measure.ext $ assume s hs,
by rw [dirac_apply (f a) hs, map_apply hf hs, dirac_apply a (hf s hs), set.mem_preimage]
lemma join_eq_bind (μ : measure (measure α)) : join μ = bind μ id :=
by rw [bind, map_id]
lemma join_map_map {f : α → β} (hf : measurable f) (μ : measure (measure α)) :
join (map (map f) μ) = map f (join μ) :=
measure.ext $ assume s hs,
begin
rw [join_apply hs, map_apply hf hs, join_apply,
integral_map (measurable_coe hs) (measurable_map f hf)],
{ congr, funext ν, exact map_apply hf hs },
exact hf s hs
end
lemma join_map_join (μ : measure (measure (measure α))) :
join (map join μ) = join (join μ) :=
begin
show bind μ join = join (join μ),
rw [join_eq_bind, join_eq_bind, bind_bind measurable_id measurable_id],
apply congr_arg (bind μ),
funext ν,
exact join_eq_bind ν
end
lemma join_map_dirac (μ : measure α) : join (map dirac μ) = μ :=
dirac_bind
lemma join_dirac (μ : measure α) : join (dirac μ) = μ :=
eq.trans (join_eq_bind (dirac μ)) (bind_dirac measurable_id _)
end measure
end measure_theory
|
e73214e547871dfae6a9cf08f917ce02b1e71c6e | 1e561612e7479c100cd9302e3fe08cbd2914aa25 | /mathlib4_experiments/Tactic/Split.lean | 9624dae8d80c1068575b302412bc37aca6592179 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib4_experiments | 8de8ed7193f70748a7529e05d831203a7c64eedb | 87cb879b4d602c8ecfd9283b7c0b06015abdbab1 | refs/heads/master | 1,687,971,389,316 | 1,620,336,942,000 | 1,620,336,942,000 | 353,994,588 | 7 | 4 | Apache-2.0 | 1,622,410,748,000 | 1,617,361,732,000 | Lean | UTF-8 | Lean | false | false | 205 | lean | /-
## `split`
Currently works for iff and and
-/
syntax "split" : tactic
macro_rules
| `(tactic| split) => `(tactic| apply Iff.intro)
macro_rules
| `(tactic| split) => `(tactic| apply And.intro)
|
c8de20643191ffdaf8b479771ad4e266b46398c4 | 80746c6dba6a866de5431094bf9f8f841b043d77 | /src/topology/continuity.lean | 3ca78b1a5f11351f9a346a820bc2d513d1950e25 | [
"Apache-2.0"
] | permissive | leanprover-fork/mathlib-backup | 8b5c95c535b148fca858f7e8db75a76252e32987 | 0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0 | refs/heads/master | 1,585,156,056,139 | 1,548,864,430,000 | 1,548,864,438,000 | 143,964,213 | 0 | 0 | Apache-2.0 | 1,550,795,966,000 | 1,533,705,322,000 | Lean | UTF-8 | Lean | false | false | 71,493 | 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, Patrick Massot
Continuous functions.
Parts of the formalization is based on the books:
N. Bourbaki: General Topology
I. M. James: Topologies and Uniformities
A major difference is that this formalization is heavily based on the filter library.
-/
import topology.basic
noncomputable theory
open set filter lattice
local attribute [instance] classical.prop_decidable
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
section
variables [topological_space α] [topological_space β] [topological_space γ]
/-- A function between topological spaces is continuous if the preimage
of every open set is open. -/
def continuous (f : α → β) := ∀s, is_open s → is_open (f ⁻¹' s)
lemma continuous_id : continuous (id : α → α) :=
assume s h, h
lemma continuous.comp {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g):
continuous (g ∘ f) :=
assume s h, hf _ (hg s h)
lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) :
tendsto f (nhds x) (nhds (f x)) | s :=
show s ∈ (nhds (f x)).sets → s ∈ (map f (nhds x)).sets,
by simp [nhds_sets]; exact
assume t t_subset t_open fx_in_t,
⟨f ⁻¹' t, preimage_mono t_subset, hf t t_open, fx_in_t⟩
lemma continuous_iff_tendsto {f : α → β} :
continuous f ↔ (∀x, tendsto f (nhds x) (nhds (f x))) :=
⟨continuous.tendsto,
assume hf : ∀x, tendsto f (nhds x) (nhds (f x)),
assume s, assume hs : is_open s,
have ∀a, f a ∈ s → s ∈ (nhds (f a)).sets,
by simp [nhds_sets]; exact assume a ha, ⟨s, subset.refl s, hs, ha⟩,
show is_open (f ⁻¹' s),
by simp [is_open_iff_nhds]; exact assume a ha, hf a (this a ha)⟩
lemma continuous_const {b : β} : continuous (λa:α, b) :=
continuous_iff_tendsto.mpr $ assume a, tendsto_const_nhds
lemma continuous_of_discrete_topology [discrete_topology α] {f : α → β} : continuous f :=
λs hs, is_open_discrete _
lemma continuous_iff_is_closed {f : α → β} :
continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) :=
⟨assume hf s hs, hf (-s) hs,
assume hf s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩
lemma continuous_at_iff_ultrafilter {f : α → β} (x) : tendsto f (nhds x) (nhds (f x)) ↔
∀ g, is_ultrafilter g → g ≤ nhds x → g.map f ≤ nhds (f x) :=
tendsto_iff_ultrafilter f (nhds x) (nhds (f x))
lemma continuous_iff_ultrafilter {f : α → β} :
continuous f ↔ ∀ x g, is_ultrafilter g → g ≤ nhds x → g.map f ≤ nhds (f x) :=
by simp only [continuous_iff_tendsto, continuous_at_iff_ultrafilter]
lemma continuous_if {p : α → Prop} {f g : α → β} {h : ∀a, decidable (p a)}
(hp : ∀a∈frontier {a | p a}, f a = g a) (hf : continuous f) (hg : continuous g) :
continuous (λa, @ite (p a) (h a) β (f a) (g a)) :=
continuous_iff_is_closed.mpr $
assume s hs,
have (λa, ite (p a) (f a) (g a)) ⁻¹' s =
(closure {a | p a} ∩ f ⁻¹' s) ∪ (closure {a | ¬ p a} ∩ g ⁻¹' s),
from set.ext $ assume a,
classical.by_cases
(assume : a ∈ frontier {a | p a},
have hac : a ∈ closure {a | p a}, from this.left,
have hai : a ∈ closure {a | ¬ p a},
from have a ∈ - interior {a | p a}, from this.right, by rwa [←closure_compl] at this,
by by_cases p a; simp [h, hp a this, hac, hai, iff_def] {contextual := tt})
(assume hf : a ∈ - frontier {a | p a},
classical.by_cases
(assume : p a,
have hc : a ∈ closure {a | p a}, from subset_closure this,
have hnc : a ∉ closure {a | ¬ p a},
by show a ∉ closure (- {a | p a}); rw [closure_compl]; simpa [frontier, hc] using hf,
by simp [this, hc, hnc])
(assume : ¬ p a,
have hc : a ∈ closure {a | ¬ p a}, from subset_closure this,
have hnc : a ∉ closure {a | p a},
begin
have hc : a ∈ closure (- {a | p a}), from hc,
simp [closure_compl] at hc,
simpa [frontier, hc] using hf
end,
by simp [this, hc, hnc])),
by rw [this]; exact is_closed_union
(is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hf s hs)
(is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hg s hs)
lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) :
f '' closure s ⊆ closure (f '' s) :=
have ∀ (a : α), nhds a ⊓ principal s ≠ ⊥ → nhds (f a) ⊓ principal (f '' s) ≠ ⊥,
from assume a ha,
have h₁ : ¬ map f (nhds a ⊓ principal s) = ⊥,
by rwa[map_eq_bot_iff],
have h₂ : map f (nhds a ⊓ principal s) ≤ nhds (f a) ⊓ principal (f '' s),
from le_inf
(le_trans (map_mono inf_le_left) $ by rw [continuous_iff_tendsto] at h; exact h a)
(le_trans (map_mono inf_le_right) $ by simp; exact subset.refl _),
neq_bot_of_le_neq_bot h₁ h₂,
by simp [image_subset_iff, closure_eq_nhds]; assumption
lemma mem_closure [topological_space α] [topological_space β]
{s : set α} {t : set β} {f : α → β} {a : α}
(hf : continuous f) (ha : a ∈ closure s) (ht : ∀a∈s, f a ∈ t) : f a ∈ closure t :=
subset.trans (image_closure_subset_closure_image hf) (closure_mono $ image_subset_iff.2 ht) $
(mem_image_of_mem f ha)
lemma compact_image {s : set α} {f : α → β} (hs : compact s) (hf : continuous f) : compact (f '' s) :=
compact_of_finite_subcover $ assume c hco hcs,
have hdo : ∀t∈c, is_open (f ⁻¹' t), from assume t' ht, hf _ $ hco _ ht,
have hds : s ⊆ ⋃i∈c, f ⁻¹' i,
by simpa [subset_def, -mem_image] using hcs,
let ⟨d', hcd', hfd', hd'⟩ := compact_elim_finite_subcover_image hs hdo hds in
⟨d', hcd', hfd', by simpa [subset_def, -mem_image, image_subset_iff] using hd'⟩
lemma compact_range [compact_space α] {f : α → β} (hf : continuous f) : compact (range f) :=
by rw ← image_univ; exact compact_image compact_univ hf
end
section constructions
local notation `cont` := @continuous _ _
local notation `tspace` := topological_space
open topological_space
variables {f : α → β} {ι : Sort*}
lemma continuous_iff_le_coinduced {t₁ : tspace α} {t₂ : tspace β} :
cont t₁ t₂ f ↔ t₂ ≤ coinduced f t₁ := iff.rfl
lemma continuous_iff_induced_le {t₁ : tspace α} {t₂ : tspace β} :
cont t₁ t₂ f ↔ induced f t₂ ≤ t₁ :=
iff.trans continuous_iff_le_coinduced (gc_induced_coinduced f _ _).symm
theorem continuous_generated_from {t : tspace α} {b : set (set β)}
(h : ∀s∈b, is_open (f ⁻¹' s)) : cont t (generate_from b) f :=
continuous_iff_le_coinduced.2 $ generate_from_le h
lemma continuous_induced_dom {t : tspace β} : cont (induced f t) t f :=
assume s h, ⟨_, h, rfl⟩
lemma continuous_induced_rng {g : γ → α} {t₂ : tspace β} {t₁ : tspace γ}
(h : cont t₁ t₂ (f ∘ g)) : cont t₁ (induced f t₂) g :=
assume s ⟨t, ht, s_eq⟩, s_eq ▸ h t ht
lemma continuous_coinduced_rng {t : tspace α} : cont t (coinduced f t) f :=
assume s h, h
lemma continuous_coinduced_dom {g : β → γ} {t₁ : tspace α} {t₂ : tspace γ}
(h : cont t₁ t₂ (g ∘ f)) : cont (coinduced f t₁) t₂ g :=
assume s hs, h s hs
lemma continuous_le_dom {t₁ t₂ : tspace α} {t₃ : tspace β}
(h₁ : t₁ ≤ t₂) (h₂ : cont t₁ t₃ f) : cont t₂ t₃ f :=
assume s h, h₁ _ (h₂ s h)
lemma continuous_le_rng {t₁ : tspace α} {t₂ t₃ : tspace β}
(h₁ : t₃ ≤ t₂) (h₂ : cont t₁ t₂ f) : cont t₁ t₃ f :=
assume s h, h₂ s (h₁ s h)
lemma continuous_inf_dom {t₁ t₂ : tspace α} {t₃ : tspace β}
(h₁ : cont t₁ t₃ f) (h₂ : cont t₂ t₃ f) : cont (t₁ ⊓ t₂) t₃ f :=
assume s h, ⟨h₁ s h, h₂ s h⟩
lemma continuous_inf_rng_left {t₁ : tspace α} {t₃ t₂ : tspace β} :
cont t₁ t₂ f → cont t₁ (t₂ ⊓ t₃) f :=
continuous_le_rng inf_le_left
lemma continuous_inf_rng_right {t₁ : tspace α} {t₃ t₂ : tspace β} :
cont t₁ t₃ f → cont t₁ (t₂ ⊓ t₃) f :=
continuous_le_rng inf_le_right
lemma continuous_Inf_dom {t₁ : set (tspace α)} {t₂ : tspace β}
(h : ∀t∈t₁, cont t t₂ f) : cont (Inf t₁) t₂ f :=
continuous_iff_induced_le.2 $ le_Inf $ assume t ht, continuous_iff_induced_le.1 $ h t ht
lemma continuous_Inf_rng {t₁ : tspace α} {t₂ : set (tspace β)} {t : tspace β}
(h₁ : t ∈ t₂) (hf : cont t₁ t f) : cont t₁ (Inf t₂) f :=
continuous_iff_le_coinduced.2 $ Inf_le_of_le h₁ $ continuous_iff_le_coinduced.1 hf
lemma continuous_infi_dom {t₁ : ι → tspace α} {t₂ : tspace β}
(h : ∀i, cont (t₁ i) t₂ f) : cont (infi t₁) t₂ f :=
continuous_Inf_dom $ assume t ⟨i, (t_eq : t₁ i = t)⟩, t_eq ▸ h i
lemma continuous_infi_rng {t₁ : tspace α} {t₂ : ι → tspace β} {i : ι}
(h : cont t₁ (t₂ i) f) : cont t₁ (infi t₂) f :=
continuous_Inf_rng ⟨i, rfl⟩ h
lemma continuous_sup_rng {t₁ : tspace α} {t₂ t₃ : tspace β}
(h₁ : cont t₁ t₂ f) (h₂ : cont t₁ t₃ f) : cont t₁ (t₂ ⊔ t₃) f :=
continuous_iff_le_coinduced.2 $ sup_le
(continuous_iff_le_coinduced.1 h₁)
(continuous_iff_le_coinduced.1 h₂)
lemma continuous_sup_dom_left {t₁ t₂ : tspace α} {t₃ : tspace β} :
cont t₁ t₃ f → cont (t₁ ⊔ t₂) t₃ f :=
continuous_le_dom le_sup_left
lemma continuous_sup_dom_right {t₁ t₂ : tspace α} {t₃ : tspace β} :
cont t₂ t₃ f → cont (t₁ ⊔ t₂) t₃ f :=
continuous_le_dom le_sup_right
lemma continuous_Sup_dom {t₁ : set (tspace α)} {t₂ : tspace β} {t : tspace α} (h₁ : t ∈ t₁) :
cont t t₂ f → cont (Sup t₁) t₂ f :=
continuous_le_dom $ le_Sup h₁
lemma continuous_Sup_rng {t₁ : tspace α} {t₂ : set (tspace β)}
(h : ∀t∈t₂, cont t₁ t f) : cont t₁ (Sup t₂) f :=
continuous_iff_le_coinduced.2 $ Sup_le $ assume b hb, continuous_iff_le_coinduced.1 $ h b hb
lemma continuous_supr_dom {t₁ : ι → tspace α} {t₂ : tspace β} {i : ι} :
cont (t₁ i) t₂ f → cont (supr t₁) t₂ f :=
continuous_le_dom $ le_supr _ _
lemma continuous_supr_rng {t₁ : tspace α} {t₂ : ι → tspace β}
(h : ∀i, cont t₁ (t₂ i) f) : cont t₁ (supr t₂) f :=
continuous_iff_le_coinduced.2 $ supr_le $ assume i, continuous_iff_le_coinduced.1 $ h i
lemma continuous_top {t : tspace β} : cont ⊤ t f :=
continuous_iff_induced_le.2 $ le_top
lemma continuous_bot {t : tspace α} : cont t ⊥ f :=
continuous_iff_le_coinduced.2 $ bot_le
end constructions
section induced
open topological_space
variables [t : topological_space β] {f : α → β}
theorem is_open_induced_eq {s : set α} :
@_root_.is_open _ (induced f t) s ↔ s ∈ preimage f '' {s | is_open s} :=
iff.refl _
theorem is_open_induced {s : set β} (h : is_open s) : (induced f t).is_open (f ⁻¹' s) :=
⟨s, h, rfl⟩
lemma nhds_induced_eq_comap {a : α} : @nhds α (induced f t) a = comap f (nhds (f a)) :=
calc @nhds α (induced f t) a = (⨅ s (x : s ∈ preimage f '' set_of is_open ∧ a ∈ s), principal s) :
by simp [nhds, is_open_induced_eq, -mem_image, and_comm]
... = (⨅ s (x : is_open s ∧ f a ∈ s), principal (f ⁻¹' s)) :
by simp only [infi_and, infi_image]; refl
... = _ : by simp [nhds, comap_infi, and_comm]
lemma map_nhds_induced_eq {a : α} (h : range f ∈ (nhds (f a)).sets) :
map f (@nhds α (induced f t) a) = nhds (f a) :=
by rw [nhds_induced_eq_comap, filter.map_comap h]
lemma closure_induced [t : topological_space β] {f : α → β} {a : α} {s : set α}
(hf : ∀x y, f x = f y → x = y) :
a ∈ @closure α (topological_space.induced f t) s ↔ f a ∈ closure (f '' s) :=
have comap f (nhds (f a) ⊓ principal (f '' s)) ≠ ⊥ ↔ nhds (f a) ⊓ principal (f '' s) ≠ ⊥,
from ⟨assume h₁ h₂, h₁ $ h₂.symm ▸ comap_bot,
assume h,
forall_sets_neq_empty_iff_neq_bot.mp $
assume s₁ ⟨s₂, hs₂, (hs : f ⁻¹' s₂ ⊆ s₁)⟩,
have f '' s ∈ (nhds (f a) ⊓ principal (f '' s)).sets,
from mem_inf_sets_of_right $ by simp [subset.refl],
have s₂ ∩ f '' s ∈ (nhds (f a) ⊓ principal (f '' s)).sets,
from inter_mem_sets hs₂ this,
let ⟨b, hb₁, ⟨a, ha, ha₂⟩⟩ := inhabited_of_mem_sets h this in
ne_empty_of_mem $ hs $ by rwa [←ha₂] at hb₁⟩,
calc a ∈ @closure α (topological_space.induced f t) s
↔ (@nhds α (topological_space.induced f t) a) ⊓ principal s ≠ ⊥ : by rw [closure_eq_nhds]; refl
... ↔ comap f (nhds (f a)) ⊓ principal (f ⁻¹' (f '' s)) ≠ ⊥ : by rw [nhds_induced_eq_comap, preimage_image_eq _ hf]
... ↔ comap f (nhds (f a) ⊓ principal (f '' s)) ≠ ⊥ : by rw [comap_inf, ←comap_principal]
... ↔ _ : by rwa [closure_eq_nhds]
end induced
section embedding
/-- A function between topological spaces is an embedding if it is injective,
and for all `s : set α`, `s` is open iff it is the preimage of an open set. -/
def embedding [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop :=
function.injective f ∧ tα = tβ.induced f
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
lemma embedding_id : embedding (@id α) :=
⟨assume a₁ a₂ h, h, induced_id.symm⟩
lemma embedding_compose {f : α → β} {g : β → γ} (hf : embedding f) (hg : embedding g) :
embedding (g ∘ f) :=
⟨assume a₁ a₂ h, hf.left $ hg.left h, by rw [hf.right, hg.right, induced_compose]⟩
lemma embedding_prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) :
embedding (λx:α×γ, (f x.1, g x.2)) :=
⟨assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.left h₁, hg.left h₂⟩,
by rw [prod.topological_space, prod.topological_space, hf.right, hg.right,
induced_compose, induced_compose, induced_sup, induced_compose, induced_compose]⟩
lemma embedding_of_embedding_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g)
(hgf : embedding (g ∘ f)) : embedding f :=
⟨assume a₁ a₂ h, hgf.left $ by simp [h, (∘)],
le_antisymm
(by rw [hgf.right, ← continuous_iff_induced_le];
apply continuous_induced_dom.comp hg)
(by rwa ← continuous_iff_induced_le)⟩
lemma embedding_open {f : α → β} {s : set α}
(hf : embedding f) (h : is_open (range f)) (hs : is_open s) : is_open (f '' s) :=
let ⟨t, ht, h_eq⟩ := by rw [hf.right] at hs; exact hs in
have is_open (t ∩ range f), from is_open_inter ht h,
h_eq ▸ by rwa [image_preimage_eq_inter_range]
lemma embedding_is_closed {f : α → β} {s : set α}
(hf : embedding f) (h : is_closed (range f)) (hs : is_closed s) : is_closed (f '' s) :=
let ⟨t, ht, h_eq⟩ := by rw [hf.right, is_closed_induced_iff] at hs; exact hs in
have is_closed (t ∩ range f), from is_closed_inter ht h,
h_eq.symm ▸ by rwa [image_preimage_eq_inter_range]
lemma embedding.map_nhds_eq [topological_space α] [topological_space β] {f : α → β}
(hf : embedding f) (a : α) (h : range f ∈ (nhds (f a)).sets) : (nhds a).map f = nhds (f a) :=
by rw [hf.2]; exact map_nhds_induced_eq h
lemma embedding.tendsto_nhds_iff {ι : Type*}
{f : ι → β} {g : β → γ} {a : filter ι} {b : β} (hg : embedding g) :
tendsto f a (nhds b) ↔ tendsto (g ∘ f) a (nhds (g b)) :=
by rw [tendsto, tendsto, hg.right, nhds_induced_eq_comap, ← map_le_iff_le_comap, filter.map_map]
lemma embedding.continuous_iff {f : α → β} {g : β → γ} (hg : embedding g) :
continuous f ↔ continuous (g ∘ f) :=
by simp [continuous_iff_tendsto, embedding.tendsto_nhds_iff hg]
lemma embedding.continuous {f : α → β} (hf : embedding f) : continuous f :=
hf.continuous_iff.mp continuous_id
lemma compact_iff_compact_image_of_embedding {s : set α} {f : α → β} (hf : embedding f) :
compact s ↔ compact (f '' s) :=
iff.intro (assume h, compact_image h hf.continuous) $ assume h, begin
rw compact_iff_ultrafilter_le_nhds at ⊢ h,
intros u hu us',
let u' : filter β := map f u,
have : u' ≤ principal (f '' s), begin
rw [map_le_iff_le_comap, comap_principal], convert us',
exact preimage_image_eq _ hf.1
end,
rcases h u' (ultrafilter_map hu) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩,
refine ⟨a, ha, _⟩,
rwa [hf.2, nhds_induced_eq_comap, ←map_le_iff_le_comap]
end
lemma embedding.closure_eq_preimage_closure_image {e : α → β} (he : embedding e) (s : set α) :
closure s = e ⁻¹' closure (e '' s) :=
by ext x; rw [set.mem_preimage_eq, ← closure_induced he.1, he.2]
end embedding
/-- A function between topological spaces is a quotient map if it is surjective,
and for all `s : set β`, `s` is open iff its preimage is an open set. -/
def quotient_map [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop :=
function.surjective f ∧ tβ = tα.coinduced f
namespace quotient_map
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
protected lemma id : quotient_map (@id α) :=
⟨assume a, ⟨a, rfl⟩, coinduced_id.symm⟩
protected lemma comp {f : α → β} {g : β → γ} (hf : quotient_map f) (hg : quotient_map g) :
quotient_map (g ∘ f) :=
⟨function.surjective_comp hg.left hf.left, by rw [hg.right, hf.right, coinduced_compose]⟩
protected lemma of_quotient_map_compose {f : α → β} {g : β → γ}
(hf : continuous f) (hg : continuous g)
(hgf : quotient_map (g ∘ f)) : quotient_map g :=
⟨assume b, let ⟨a, h⟩ := hgf.left b in ⟨f a, h⟩,
le_antisymm
(by rwa ← continuous_iff_le_coinduced)
(by rw [hgf.right, ← continuous_iff_le_coinduced];
apply hf.comp continuous_coinduced_rng)⟩
protected lemma continuous_iff {f : α → β} {g : β → γ} (hf : quotient_map f) :
continuous g ↔ continuous (g ∘ f) :=
by rw [continuous_iff_le_coinduced, continuous_iff_le_coinduced, hf.right, coinduced_compose]
protected lemma continuous {f : α → β} (hf : quotient_map f) : continuous f :=
hf.continuous_iff.mp continuous_id
end quotient_map
section is_open_map
variables [topological_space α] [topological_space β]
def is_open_map (f : α → β) := ∀ U : set α, is_open U → is_open (f '' U)
lemma is_open_map_iff_nhds_le (f : α → β) : is_open_map f ↔ ∀(a:α), nhds (f a) ≤ (nhds a).map f :=
begin
split,
{ assume h a s hs,
rcases mem_nhds_sets_iff.1 hs with ⟨t, hts, ht, hat⟩,
exact filter.mem_sets_of_superset
(mem_nhds_sets (h t ht) (mem_image_of_mem _ hat))
(image_subset_iff.2 hts) },
{ refine assume h s hs, is_open_iff_mem_nhds.2 _,
rintros b ⟨a, ha, rfl⟩,
exact h _ (filter.image_mem_map $ mem_nhds_sets hs ha) }
end
end is_open_map
namespace is_open_map
variables [topological_space α] [topological_space β] [topological_space γ]
open function
protected lemma id : is_open_map (@id α) := assume s hs, by rwa [image_id]
protected lemma comp
{f : α → β} {g : β → γ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (g ∘ f) :=
by intros s hs; rw [image_comp]; exact hg _ (hf _ hs)
lemma of_inverse {f : α → β} {f' : β → α}
(h : continuous f') (l_inv : left_inverse f f') (r_inv : right_inverse f f') :
is_open_map f :=
assume s hs,
have f' ⁻¹' s = f '' s, by ext x; simp [mem_image_iff_of_inverse r_inv l_inv],
this ▸ h s hs
lemma to_quotient_map {f : α → β}
(open_map : is_open_map f) (cont : continuous f) (surj : function.surjective f) :
quotient_map f :=
⟨ surj,
begin
ext s,
show is_open s ↔ is_open (f ⁻¹' s),
split,
{ exact cont s },
{ assume h,
rw ← @image_preimage_eq _ _ _ s surj,
exact open_map _ h }
end⟩
end is_open_map
section sierpinski
variables [topological_space α]
@[simp] lemma is_open_singleton_true : is_open ({true} : set Prop) :=
topological_space.generate_open.basic _ (by simp)
lemma continuous_Prop {p : α → Prop} : continuous p ↔ is_open {x | p x} :=
⟨assume h : continuous p,
have is_open (p ⁻¹' {true}),
from h _ is_open_singleton_true,
by simp [preimage, eq_true] at this; assumption,
assume h : is_open {x | p x},
continuous_generated_from $ assume s (hs : s ∈ {{true}}),
by simp at hs; simp [hs, preimage, eq_true, h]⟩
end sierpinski
section prod
open topological_space
variables [topological_space α] [topological_space β] [topological_space γ]
lemma continuous_fst : continuous (@prod.fst α β) :=
continuous_sup_dom_left continuous_induced_dom
lemma continuous_snd : continuous (@prod.snd α β) :=
continuous_sup_dom_right continuous_induced_dom
lemma continuous.prod_mk {f : γ → α} {g : γ → β}
(hf : continuous f) (hg : continuous g) : continuous (λx, prod.mk (f x) (g x)) :=
continuous_sup_rng (continuous_induced_rng hf) (continuous_induced_rng hg)
lemma continuous_swap : continuous (prod.swap : α × β → β × α) :=
continuous.prod_mk continuous_snd continuous_fst
lemma is_open_prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) :
is_open (set.prod s t) :=
is_open_inter (continuous_fst s hs) (continuous_snd t ht)
lemma nhds_prod_eq {a : α} {b : β} : nhds (a, b) = filter.prod (nhds a) (nhds b) :=
by rw [filter.prod, prod.topological_space, nhds_sup, nhds_induced_eq_comap, nhds_induced_eq_comap]
instance [topological_space α] [discrete_topology α] [topological_space β] [discrete_topology β] :
discrete_topology (α × β) :=
⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩,
by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_top, filter.prod_pure_pure]⟩
lemma prod_mem_nhds_sets {s : set α} {t : set β} {a : α} {b : β}
(ha : s ∈ (nhds a).sets) (hb : t ∈ (nhds b).sets) : set.prod s t ∈ (nhds (a, b)).sets :=
by rw [nhds_prod_eq]; exact prod_mem_prod ha hb
lemma nhds_swap (a : α) (b : β) : nhds (a, b) = (nhds (b, a)).map prod.swap :=
by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl
lemma tendsto_prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β}
(ha : tendsto ma f (nhds a)) (hb : tendsto mb f (nhds b)) :
tendsto (λc, (ma c, mb c)) f (nhds (a, b)) :=
by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb
lemma prod_generate_from_generate_from_eq {s : set (set α)} {t : set (set β)}
(hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) :
@prod.topological_space α β (generate_from s) (generate_from t) =
generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} :=
let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in
le_antisymm
(sup_le
(induced_le_iff_le_coinduced.mpr $ generate_from_le $ assume u hu,
have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u,
from calc (⋃v∈t, set.prod u v) = set.prod u univ :
set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt}
... = prod.fst ⁻¹' u : by simp [set.prod, preimage],
show G.is_open (prod.fst ⁻¹' u),
from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv,
generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)
(induced_le_iff_le_coinduced.mpr $ generate_from_le $ assume v hv,
have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v,
from calc (⋃u∈s, set.prod u v) = set.prod univ v:
set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt}
... = prod.snd ⁻¹' v : by simp [set.prod, preimage],
show G.is_open (prod.snd ⁻¹' v),
from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu,
generate_open.basic _ ⟨_, hu, _, hv, rfl⟩))
(generate_from_le $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸
@is_open_prod _ _ (generate_from s) (generate_from t) _ _
(generate_open.basic _ hu) (generate_open.basic _ hv))
lemma prod_eq_generate_from [tα : topological_space α] [tβ : topological_space β] :
prod.topological_space =
generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} :=
le_antisymm
(sup_le
(ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩)
(ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩))
(generate_from_le $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ is_open_prod hs ht)
lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔
(∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) :=
begin
rw [is_open_iff_nhds],
simp [nhds_prod_eq, mem_prod_iff],
simp [mem_nhds_sets_iff],
exact forall_congr (assume a, ball_congr $ assume b h,
⟨assume ⟨u', ⟨u, us, uo, au⟩, v', ⟨v, vs, vo, bv⟩, h⟩,
⟨u, uo, v, vo, au, bv, subset.trans (set.prod_mono us vs) h⟩,
assume ⟨u, uo, v, vo, au, bv, h⟩,
⟨u, ⟨u, subset.refl u, uo, au⟩, v, ⟨v, subset.refl v, vo, bv⟩, h⟩⟩)
end
lemma closure_prod_eq {s : set α} {t : set β} :
closure (set.prod s t) = set.prod (closure s) (closure t) :=
set.ext $ assume ⟨a, b⟩,
have filter.prod (nhds a) (nhds b) ⊓ principal (set.prod s t) =
filter.prod (nhds a ⊓ principal s) (nhds b ⊓ principal t),
by rw [←prod_inf_prod, prod_principal_principal],
by simp [closure_eq_nhds, nhds_prod_eq, this]; exact prod_neq_bot
lemma mem_closure2 [topological_space α] [topological_space β] [topological_space γ]
{s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β}
(hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t)
(hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) :
f a b ∈ closure u :=
have (a, b) ∈ closure (set.prod s t), by rw [closure_prod_eq]; from ⟨ha, hb⟩,
show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from
mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb
lemma is_closed_prod [topological_space α] [topological_space β] {s₁ : set α} {s₂ : set β}
(h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (set.prod s₁ s₂) :=
closure_eq_iff_is_closed.mp $ by simp [h₁, h₂, closure_prod_eq, closure_eq_of_is_closed]
protected lemma is_open_map.prod
[topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
{f : α → β} {g : γ → δ}
(hf : is_open_map f) (hg : is_open_map g) : is_open_map (λ p : α × γ, (f p.1, g p.2)) :=
begin
rw [is_open_map_iff_nhds_le],
rintros ⟨a, b⟩,
rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq],
exact filter.prod_mono ((is_open_map_iff_nhds_le f).1 hf a) ((is_open_map_iff_nhds_le g).1 hg b)
end
section tube_lemma
def nhds_contain_boxes (s : set α) (t : set β) : Prop :=
∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n),
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n
lemma nhds_contain_boxes.symm {s : set α} {t : set β} :
nhds_contain_boxes s t → nhds_contain_boxes t s :=
assume H n hn hp,
let ⟨u, v, uo, vo, su, tv, p⟩ :=
H (prod.swap ⁻¹' n)
(continuous_swap n hn)
(by rwa [←image_subset_iff, prod.swap, image_swap_prod]) in
⟨v, u, vo, uo, tv, su,
by rwa [←image_subset_iff, prod.swap, image_swap_prod] at p⟩
lemma nhds_contain_boxes.comm {s : set α} {t : set β} :
nhds_contain_boxes s t ↔ nhds_contain_boxes t s :=
iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm
lemma nhds_contain_boxes_of_singleton {x : α} {y : β} :
nhds_contain_boxes ({x} : set α) ({y} : set β) :=
assume n hn hp,
let ⟨u, v, uo, vo, xu, yv, hp'⟩ :=
is_open_prod_iff.mp hn x y (hp $ by simp) in
⟨u, v, uo, vo, by simpa, by simpa, hp'⟩
lemma nhds_contain_boxes_of_compact {s : set α} (hs : compact s) (t : set β)
(H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t :=
assume n hn hp,
have ∀x : subtype s, ∃uv : set α × set β,
is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n,
from assume ⟨x, hx⟩,
have set.prod {x} t ⊆ n, from
subset.trans (prod_mono (by simpa) (subset.refl _)) hp,
let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩,
let ⟨uvs, h⟩ := classical.axiom_of_choice this in
have us_cover : s ⊆ ⋃i, (uvs i).1, from
assume x hx, set.subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1),
let ⟨s0, _, s0_fin, s0_cover⟩ :=
compact_elim_finite_subcover_image hs (λi _, (h i).1) $
by rw bUnion_univ; exact us_cover in
let u := ⋃(i ∈ s0), (uvs i).1 in
let v := ⋂(i ∈ s0), (uvs i).2 in
have is_open u, from is_open_bUnion (λi _, (h i).1),
have is_open v, from is_open_bInter s0_fin (λi _, (h i).2.1),
have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1),
have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩,
have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx',
let ⟨i,is0,hi⟩ := this in
(h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩,
⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩
lemma generalized_tube_lemma {s : set α} (hs : compact s) {t : set β} (ht : compact t)
{n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) :
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n :=
have _, from
nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $
nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton,
this n hn hp
end tube_lemma
lemma is_closed_diagonal [topological_space α] [t2_space α] : is_closed {p:α×α | p.1 = p.2} :=
is_closed_iff_nhds.mpr $ assume ⟨a₁, a₂⟩ h, eq_of_nhds_neq_bot $ assume : nhds a₁ ⊓ nhds a₂ = ⊥, h $
let ⟨t₁, ht₁, t₂, ht₂, (h' : t₁ ∩ t₂ ⊆ ∅)⟩ :=
by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this in
begin
rw [nhds_prod_eq, ←empty_in_sets_eq_bot],
apply filter.sets_of_superset,
apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)),
exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩,
show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩
end
lemma is_closed_eq [topological_space α] [t2_space α] [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} :=
continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal
lemma diagonal_eq_range_diagonal_map : {p:α×α | p.1 = p.2} = range (λx, (x,x)) :=
ext $ assume p, iff.intro
(assume h, ⟨p.1, prod.ext_iff.2 ⟨rfl, h⟩⟩)
(assume ⟨x, hx⟩, show p.1 = p.2, by rw ←hx)
lemma prod_subset_compl_diagonal_iff_disjoint {s t : set α} :
set.prod s t ⊆ - {p:α×α | p.1 = p.2} ↔ s ∩ t = ∅ :=
by rw [eq_empty_iff_forall_not_mem, subset_compl_comm,
diagonal_eq_range_diagonal_map, range_subset_iff]; simp
lemma compact_compact_separated [t2_space α] {s t : set α}
(hs : compact s) (ht : compact t) (hst : s ∩ t = ∅) :
∃u v : set α, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ∩ v = ∅ :=
by simp only [prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst;
exact generalized_tube_lemma hs ht is_closed_diagonal hst
lemma closed_of_compact [t2_space α] (s : set α) (hs : compact s) : is_closed s :=
is_open_compl_iff.mpr $ is_open_iff_forall_mem_open.mpr $ assume x hx,
let ⟨u, v, uo, vo, su, xv, uv⟩ :=
compact_compact_separated hs (compact_singleton : compact {x})
(by rwa [inter_comm, ←subset_compl_iff_disjoint, singleton_subset_iff]) in
have v ⊆ -s, from
subset_compl_comm.mp (subset.trans su (subset_compl_iff_disjoint.mpr uv)),
⟨v, this, vo, by simpa using xv⟩
lemma locally_compact_of_compact_nhds [topological_space α] [t2_space α]
(h : ∀ x : α, ∃ s, s ∈ (nhds x).sets ∧ compact s) :
locally_compact_space α :=
⟨assume x n hn,
let ⟨u, un, uo, xu⟩ := mem_nhds_sets_iff.mp hn in
let ⟨k, kx, kc⟩ := h x in
-- K is compact but not necessarily contained in N.
-- K \ U is again compact and doesn't contain x, so
-- we may find open sets V, W separating x from K \ U.
-- Then K \ W is a compact neighborhood of x contained in U.
let ⟨v, w, vo, wo, xv, kuw, vw⟩ :=
compact_compact_separated compact_singleton (compact_diff kc uo)
(by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in
have wn : -w ∈ (nhds x).sets, from
mem_nhds_sets_iff.mpr
⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩,
⟨k - w,
filter.inter_mem_sets kx wn,
subset.trans (diff_subset_comm.mp kuw) un,
compact_diff kc wo⟩⟩
instance locally_compact_of_compact [topological_space α] [t2_space α] [compact_space α] :
locally_compact_space α :=
locally_compact_of_compact_nhds (assume x, ⟨univ, mem_nhds_sets is_open_univ trivial, compact_univ⟩)
-- We can't make this an instance because it could cause an instance loop.
lemma normal_of_compact_t2 [topological_space α] [compact_space α] [t2_space α] : normal_space α :=
begin
refine ⟨assume s t hs ht st, _⟩,
simp only [disjoint_iff],
exact compact_compact_separated (compact_of_closed hs) (compact_of_closed ht) st.eq_bot
end
/- TODO: more fine grained instances for first_countable_topology, separable_space, t2_space, ... -/
instance [second_countable_topology α] [second_countable_topology β] :
second_countable_topology (α × β) :=
⟨let ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩ := is_open_generated_countable_inter α in
let ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩ := is_open_generated_countable_inter β in
⟨{g | ∃u∈a, ∃v∈b, g = set.prod u v},
have {g | ∃u∈a, ∃v∈b, g = set.prod u v} = (⋃u∈a, ⋃v∈b, {set.prod u v}),
by apply set.ext; simp,
by rw [this]; exact (countable_bUnion ha₁ $ assume u hu, countable_bUnion hb₁ $ by simp),
by rw [ha₅, hb₅, prod_generate_from_generate_from_eq ha₄ hb₄]⟩⟩
lemma compact_prod (s : set α) (t : set β) (ha : compact s) (hb : compact t) : compact (set.prod s t) :=
begin
rw compact_iff_ultrafilter_le_nhds at ha hb ⊢,
intros f hf hfs,
rw le_principal_iff at hfs,
rcases ha (map prod.fst f) (ultrafilter_map hf)
(le_principal_iff.2 (mem_map_sets_iff.2
⟨_, hfs, image_subset_iff.2 (λ s h, h.1)⟩)) with ⟨a, sa, ha⟩,
rcases hb (map prod.snd f) (ultrafilter_map hf)
(le_principal_iff.2 (mem_map_sets_iff.2
⟨_, hfs, image_subset_iff.2 (λ s h, h.2)⟩)) with ⟨b, tb, hb⟩,
rw map_le_iff_le_comap at ha hb,
refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩,
rw nhds_prod_eq, exact le_inf ha hb
end
instance [compact_space α] [compact_space β] : compact_space (α × β) :=
⟨begin
have A : compact (set.prod (univ : set α) (univ : set β)) :=
compact_prod univ univ compact_univ compact_univ,
have : set.prod (univ : set α) (univ : set β) = (univ : set (α × β)) := by simp,
rwa this at A,
end⟩
end prod
section sum
variables [topological_space α] [topological_space β] [topological_space γ]
lemma continuous_inl : continuous (@sum.inl α β) :=
continuous_inf_rng_left continuous_coinduced_rng
lemma continuous_inr : continuous (@sum.inr α β) :=
continuous_inf_rng_right continuous_coinduced_rng
lemma continuous_sum_rec {f : α → γ} {g : β → γ}
(hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) :=
continuous_inf_dom hf hg
lemma embedding_inl : embedding (@sum.inl α β) :=
⟨λ _ _, sum.inl.inj_iff.mp,
begin
unfold sum.topological_space,
apply le_antisymm,
{ intros u hu, existsi (sum.inl '' u),
change
(is_open (sum.inl ⁻¹' (@sum.inl α β '' u)) ∧
is_open (sum.inr ⁻¹' (@sum.inl α β '' u))) ∧
sum.inl ⁻¹' (sum.inl '' u) = u,
have : sum.inl ⁻¹' (@sum.inl α β '' u) = u :=
preimage_image_eq u (λ _ _, sum.inl.inj_iff.mp), rw this,
have : sum.inr ⁻¹' (@sum.inl α β '' u) = ∅ :=
eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, sum.inl_ne_inr h), rw this,
exact ⟨⟨hu, is_open_empty⟩, rfl⟩ },
{ rw induced_le_iff_le_coinduced, exact lattice.inf_le_left }
end⟩
lemma embedding_inr : embedding (@sum.inr α β) :=
⟨λ _ _, sum.inr.inj_iff.mp,
begin
unfold sum.topological_space,
apply le_antisymm,
{ intros u hu, existsi (sum.inr '' u),
change
(is_open (sum.inl ⁻¹' (@sum.inr α β '' u)) ∧
is_open (sum.inr ⁻¹' (@sum.inr α β '' u))) ∧
sum.inr ⁻¹' (sum.inr '' u) = u,
have : sum.inl ⁻¹' (@sum.inr α β '' u) = ∅ :=
eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, sum.inr_ne_inl h), rw this,
have : sum.inr ⁻¹' (@sum.inr α β '' u) = u :=
preimage_image_eq u (λ _ _, sum.inr.inj_iff.mp), rw this,
exact ⟨⟨is_open_empty, hu⟩, rfl⟩ },
{ rw induced_le_iff_le_coinduced, exact lattice.inf_le_right }
end⟩
instance [topological_space α] [topological_space β] [compact_space α] [compact_space β] :
compact_space (α ⊕ β) :=
⟨begin
have A : compact (@sum.inl α β '' univ) := compact_image compact_univ continuous_inl,
have B : compact (@sum.inr α β '' univ) := compact_image compact_univ continuous_inr,
have C := compact_union_of_compact A B,
have : (@sum.inl α β '' univ) ∪ (@sum.inr α β '' univ) = univ := by ext; cases x; simp,
rwa this at C,
end⟩
end sum
section subtype
variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop}
lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) :=
embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id
lemma embedding_subtype_val : embedding (@subtype.val α p) :=
⟨subtype.val_injective, rfl⟩
lemma continuous_subtype_val : continuous (@subtype.val α p) :=
continuous_induced_dom
lemma continuous_subtype_mk {f : β → α}
(hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) :=
continuous_induced_rng h
lemma tendsto_subtype_val [topological_space α] {p : α → Prop} {a : subtype p} :
tendsto subtype.val (nhds a) (nhds a.val) :=
continuous_iff_tendsto.1 continuous_subtype_val _
lemma map_nhds_subtype_val_eq {a : α} (ha : p a) (h : {a | p a} ∈ (nhds a).sets) :
map (@subtype.val α p) (nhds ⟨a, ha⟩) = nhds a :=
map_nhds_induced_eq (by simp [subtype_val_image, h])
lemma nhds_subtype_eq_comap {a : α} {h : p a} :
nhds (⟨a, h⟩ : subtype p) = comap subtype.val (nhds a) :=
nhds_induced_eq_comap
lemma tendsto_subtype_rng [topological_space α] {p : α → Prop} {b : filter β} {f : β → subtype p} :
∀{a:subtype p}, tendsto f b (nhds a) ↔ tendsto (λx, subtype.val (f x)) b (nhds a.val)
| ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff]
lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop}
(c_cover : ∀x:α, ∃i, {x | c i x} ∈ (nhds x).sets)
(f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) :
continuous f :=
continuous_iff_tendsto.mpr $ assume x,
let ⟨i, (c_sets : {x | c i x} ∈ (nhds x).sets)⟩ := c_cover x in
let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in
calc map f (nhds x) = map f (map subtype.val (nhds x')) :
congr_arg (map f) (map_nhds_subtype_val_eq _ $ c_sets).symm
... = map (λx:subtype (c i), f x.val) (nhds x') : rfl
... ≤ nhds (f x) : continuous_iff_tendsto.mp (f_cont i) x'
lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop)
(h_lf : locally_finite (λi, {x | c i x}))
(h_is_closed : ∀i, is_closed {x | c i x})
(h_cover : ∀x, ∃i, c i x)
(f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) :
continuous f :=
continuous_iff_is_closed.mpr $
assume s hs,
have ∀i, is_closed (@subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)),
from assume i,
embedding_is_closed embedding_subtype_val
(by simp [subtype_val_range]; exact h_is_closed i)
(continuous_iff_is_closed.mp (f_cont i) _ hs),
have is_closed (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)),
from is_closed_Union_of_locally_finite
(locally_finite_subset h_lf $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx')
this,
have f ⁻¹' s = (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)),
begin
apply set.ext,
have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s :=
λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩,
λ ⟨i, hi, hx⟩, hx⟩,
simp [and.comm, and.left_comm], simpa [(∘)],
end,
by rwa [this]
lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}:
x ∈ closure s ↔ x.val ∈ closure (subtype.val '' s) :=
closure_induced $ assume x y, subtype.eq
lemma compact_iff_compact_in_subtype {s : set {a // p a}} :
compact s ↔ compact (subtype.val '' s) :=
compact_iff_compact_image_of_embedding embedding_subtype_val
lemma compact_iff_compact_univ {s : set α} : compact s ↔ compact (univ : set (subtype s)) :=
by rw [compact_iff_compact_in_subtype, image_univ, subtype_val_range]; refl
lemma compact_iff_compact_space {s : set α} : compact s ↔ compact_space s :=
compact_iff_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩
end subtype
section quotient
variables [topological_space α] [topological_space β] [topological_space γ]
variables {r : α → α → Prop} {s : setoid α}
lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) :=
⟨quot.exists_rep, rfl⟩
lemma continuous_quot_mk : continuous (@quot.mk α r) :=
continuous_coinduced_rng
lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b)
(h : continuous f) : continuous (quot.lift f hr : quot r → β) :=
continuous_coinduced_dom h
lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) :=
quotient_map_quot_mk
lemma continuous_quotient_mk : continuous (@quotient.mk α s) :=
continuous_coinduced_rng
lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b)
(h : continuous f) : continuous (quotient.lift f hs : quotient s → β) :=
continuous_coinduced_dom h
instance quot.compact_space {r : α → α → Prop} [topological_space α] [compact_space α] :
compact_space (quot r) :=
⟨begin
have : quot.mk r '' univ = univ,
by rw [image_univ, range_iff_surjective]; exact quot.exists_rep,
rw ←this,
exact compact_image compact_univ continuous_quot_mk
end⟩
instance quotient.compact_space {s : setoid α} [topological_space α] [compact_space α] :
compact_space (quotient s) :=
quot.compact_space
end quotient
section pi
variables {ι : Type*} {π : ι → Type*}
open topological_space
lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i}
(h : ∀i, continuous (λa, f a i)) : continuous f :=
continuous_supr_rng $ assume i, continuous_induced_rng $ h i
lemma continuous_apply [∀i, topological_space (π i)] (i : ι) :
continuous (λp:Πi, π i, p i) :=
continuous_supr_dom continuous_induced_dom
lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} :
nhds a = (⨅i, comap (λx, x i) (nhds (a i))) :=
calc nhds a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_supr
... = (⨅i, comap (λx, x i) (nhds (a i))) : by simp [nhds_induced_eq_comap]
/-- Tychonoff's theorem -/
lemma compact_pi_infinite [∀i, topological_space (π i)] {s : Πi:ι, set (π i)} :
(∀i, compact (s i)) → compact {x : Πi:ι, π i | ∀i, x i ∈ s i} :=
begin
simp [compact_iff_ultrafilter_le_nhds, nhds_pi],
exact assume h f hf hfs,
let p : Πi:ι, filter (π i) := λi, map (λx:Πi:ι, π i, x i) f in
have ∀i:ι, ∃a, a∈s i ∧ p i ≤ nhds a,
from assume i, h i (p i) (ultrafilter_map hf) $
show (λx:Πi:ι, π i, x i) ⁻¹' s i ∈ f.sets,
from mem_sets_of_superset hfs $ assume x (hx : ∀i, x i ∈ s i), hx i,
let ⟨a, ha⟩ := classical.axiom_of_choice this in
⟨a, assume i, (ha i).left, assume i, map_le_iff_le_comap.mp $ (ha i).right⟩
end
lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)}
(hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) :=
by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, continuous_apply a _ $ hs a ha)
lemma pi_eq_generate_from [∀a, topological_space (π a)] :
Pi.topological_space =
generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} :=
le_antisymm
(supr_le $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $
⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]⟩)
(generate_from_le $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi)
lemma pi_generate_from_eq {g : Πa, set (set (π a))} :
@Pi.topological_space ι π (λa, generate_from (g a)) =
generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} :=
let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in
begin
rw [pi_eq_generate_from],
refine le_antisymm (generate_from_le _) (generate_from_mono _),
{ rintros s ⟨t, i, hi, rfl⟩,
rw [pi_def],
apply is_open_bInter (finset.finite_to_set _),
assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a),
refine generate_from_le _ _ (hi a ha),
exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ },
exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩
end
lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) :
@Pi.topological_space ι π (λa, generate_from (g a)) =
generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} :=
let G := {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} in
begin
rw [pi_generate_from_eq],
refine le_antisymm (generate_from_le _) (generate_from_mono _),
{ rintros s ⟨t, i, ht, rfl⟩,
apply is_open_iff_forall_mem_open.2 _,
assume f hf,
choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s,
{ assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa },
refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩,
{ simp [pi_if] },
{ refine generate_open.basic _ ⟨_, assume a, _, rfl⟩,
by_cases a ∈ i; simp [*, pi] at * },
{ have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * },
simpa [pi_if, hf] } },
exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩
end
instance second_countable_topology_fintype
[fintype ι] [t : ∀a, topological_space (π a)] [sc : ∀a, second_countable_topology (π a)] :
second_countable_topology (∀a, π a) :=
have ∀i, ∃b : set (set (π i)), countable b ∧ ∅ ∉ b ∧ is_topological_basis b, from
assume a, @is_open_generated_countable_inter (π a) _ (sc a),
let ⟨g, hg⟩ := classical.axiom_of_choice this in
have t = (λa, generate_from (g a)), from funext $ assume a, (hg a).2.2.2.2,
begin
constructor,
refine ⟨pi univ '' pi univ g, countable_image _ _, _⟩,
{ suffices : countable {f : Πa, set (π a) | ∀a, f a ∈ g a}, { simpa [pi] },
exact countable_pi (assume i, (hg i).1), },
rw [this, pi_generate_from_eq_fintype],
{ congr' 1, ext f, simp [pi, eq_comm] },
exact assume a, (hg a).2.2.2.1
end
instance pi.compact [∀i:ι, topological_space (π i)] [∀i:ι, compact_space (π i)] : compact_space (Πi, π i) :=
⟨begin
have A : compact {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} :=
compact_pi_infinite (λi, compact_univ),
have : {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} = univ := by ext; simp,
rwa this at A,
end⟩
end pi
namespace list
variables [topological_space α] [topological_space β]
lemma tendsto_cons' {a : α} {l : list α} :
tendsto (λp:α×list α, list.cons p.1 p.2) ((nhds a).prod (nhds l)) (nhds (a :: l)) :=
by rw [nhds_cons, tendsto, map_prod]; exact le_refl _
lemma tendsto_cons {f : α → β} {g : α → list β}
{a : _root_.filter α} {b : β} {l : list β} (hf : tendsto f a (nhds b)) (hg : tendsto g a (nhds l)):
tendsto (λa, list.cons (f a) (g a)) a (nhds (b :: l)) :=
(tendsto.prod_mk hf hg).comp tendsto_cons'
lemma tendsto_cons_iff [topological_space β]
{f : list α → β} {b : _root_.filter β} {a : α} {l : list α} :
tendsto f (nhds (a :: l)) b ↔ tendsto (λp:α×list α, f (p.1 :: p.2)) ((nhds a).prod (nhds l)) b :=
have nhds (a :: l) = ((nhds a).prod (nhds l)).map (λp:α×list α, (p.1 :: p.2)),
begin
simp only
[nhds_cons, filter.prod_eq, (filter.map_def _ _).symm, (filter.seq_eq_filter_seq _ _).symm],
simp [-filter.seq_eq_filter_seq, -filter.map_def, (∘)] with functor_norm,
end,
by rw [this, filter.tendsto_map'_iff]
lemma tendsto_nhds [topological_space β]
{f : list α → β} {r : list α → _root_.filter β}
(h_nil : tendsto f (pure []) (r []))
(h_cons : ∀l a, tendsto f (nhds l) (r l) → tendsto (λp:α×list α, f (p.1 :: p.2)) ((nhds a).prod (nhds l)) (r (a::l))) :
∀l, tendsto f (nhds l) (r l)
| [] := by rwa [nhds_nil]
| (a::l) := by rw [tendsto_cons_iff]; exact h_cons l a (tendsto_nhds l)
lemma tendsto_length [topological_space α] :
∀(l : list α), tendsto list.length (nhds l) (nhds l.length) :=
begin
simp only [nhds_discrete],
refine tendsto_nhds _ _,
{ exact tendsto_pure_pure _ _ },
{ assume l a ih,
dsimp only [list.length],
refine tendsto.comp _ (tendsto_pure_pure (λx, x + 1) _),
refine tendsto.comp tendsto_snd ih }
end
lemma tendsto_insert_nth' {a : α} : ∀{n : ℕ} {l : list α},
tendsto (λp:α×list α, insert_nth n p.1 p.2) ((nhds a).prod (nhds l)) (nhds (insert_nth n a l))
| 0 l := tendsto_cons'
| (n+1) [] :=
suffices tendsto (λa, []) (nhds a) (nhds ([] : list α)),
by simpa [nhds_nil, tendsto, map_prod, -filter.pure_def, (∘), insert_nth],
tendsto_const_nhds
| (n+1) (a'::l) :=
have (nhds a).prod (nhds (a' :: l)) =
((nhds a).prod ((nhds a').prod (nhds l))).map (λp:α×α×list α, (p.1, p.2.1 :: p.2.2)),
begin
simp only
[nhds_cons, filter.prod_eq, (filter.map_def _ _).symm, (filter.seq_eq_filter_seq _ _).symm],
simp [-filter.seq_eq_filter_seq, -filter.map_def, (∘)] with functor_norm
end,
begin
rw [this, tendsto_map'_iff],
exact tendsto_cons
(tendsto_snd.comp tendsto_fst)
((tendsto.prod_mk tendsto_fst (tendsto_snd.comp tendsto_snd)).comp (@tendsto_insert_nth' n l))
end
lemma tendsto_insert_nth {n : ℕ} {a : α} {l : list α} {f : β → α} {g : β → list α}
{b : _root_.filter β} (hf : tendsto f b (nhds a)) (hg : tendsto g b (nhds l)) :
tendsto (λb:β, insert_nth n (f b) (g b)) b (nhds (insert_nth n a l)) :=
(tendsto.prod_mk hf hg).comp tendsto_insert_nth'
lemma continuous_insert_nth {n : ℕ} : continuous (λp:α×list α, insert_nth n p.1 p.2) :=
continuous_iff_tendsto.2 $ assume ⟨a, l⟩, by rw [nhds_prod_eq]; exact tendsto_insert_nth'
lemma tendsto_remove_nth : ∀{n : ℕ} {l : list α},
tendsto (λl, remove_nth l n) (nhds l) (nhds (remove_nth l n))
| _ [] := by rw [nhds_nil]; exact tendsto_pure_nhds _ _
| 0 (a::l) := by rw [tendsto_cons_iff]; exact tendsto_snd
| (n+1) (a::l) :=
begin
rw [tendsto_cons_iff],
dsimp [remove_nth],
exact tendsto_cons tendsto_fst (tendsto_snd.comp (@tendsto_remove_nth n l))
end
lemma continuous_remove_nth {n : ℕ} : continuous (λl : list α, remove_nth l n) :=
continuous_iff_tendsto.2 $ assume a, tendsto_remove_nth
end list
namespace vector
open list filter
instance (n : ℕ) [topological_space α] : topological_space (vector α n) :=
by unfold vector; apply_instance
lemma cons_val {n : ℕ} {a : α} : ∀{v : vector α n}, (a :: v).val = a :: v.val
| ⟨l, hl⟩ := rfl
lemma tendsto_cons [topological_space α] {n : ℕ} {a : α} {l : vector α n}:
tendsto (λp:α×vector α n, vector.cons p.1 p.2) ((nhds a).prod (nhds l)) (nhds (a :: l)) :=
by
simp [tendsto_subtype_rng, cons_val];
exact tendsto_cons tendsto_fst (tendsto.comp tendsto_snd tendsto_subtype_val)
lemma tendsto_insert_nth
[topological_space α] {n : ℕ} {i : fin (n+1)} {a:α} :
∀{l:vector α n}, tendsto (λp:α×vector α n, insert_nth p.1 i p.2)
((nhds a).prod (nhds l)) (nhds (insert_nth a i l))
| ⟨l, hl⟩ :=
begin
rw [insert_nth, tendsto_subtype_rng],
simp [insert_nth_val],
exact list.tendsto_insert_nth tendsto_fst (tendsto.comp tendsto_snd tendsto_subtype_val)
end
lemma continuous_insert_nth' [topological_space α] {n : ℕ} {i : fin (n+1)} :
continuous (λp:α×vector α n, insert_nth p.1 i p.2) :=
continuous_iff_tendsto.2 $ assume ⟨a, l⟩, by rw [nhds_prod_eq]; exact tendsto_insert_nth
lemma continuous_insert_nth [topological_space α] [topological_space β] {n : ℕ} {i : fin (n+1)}
{f : β → α} {g : β → vector α n} (hf : continuous f) (hg : continuous g) :
continuous (λb, insert_nth (f b) i (g b)) :=
continuous.comp (continuous.prod_mk hf hg) continuous_insert_nth'
lemma tendsto_remove_nth [topological_space α] {n : ℕ} {i : fin (n+1)} :
∀{l:vector α (n+1)}, tendsto (remove_nth i) (nhds l) (nhds (remove_nth i l))
| ⟨l, hl⟩ :=
begin
rw [remove_nth, tendsto_subtype_rng],
simp [remove_nth_val],
exact tendsto_subtype_val.comp list.tendsto_remove_nth
end
lemma continuous_remove_nth [topological_space α] {n : ℕ} {i : fin (n+1)} :
continuous (remove_nth i : vector α (n+1) → vector α n) :=
continuous_iff_tendsto.2 $ assume ⟨a, l⟩, tendsto_remove_nth
end vector
-- TODO: use embeddings from above!
structure dense_embedding [topological_space α] [topological_space β] (e : α → β) : Prop :=
(dense : ∀x, x ∈ closure (range e))
(inj : function.injective e)
(induced : ∀a, comap e (nhds (e a)) = nhds a)
theorem dense_embedding.mk'
[topological_space α] [topological_space β] (e : α → β)
(c : continuous e)
(dense : ∀x, x ∈ closure (range e))
(inj : function.injective e)
(H : ∀ (a:α) s ∈ (nhds a).sets,
∃t ∈ (nhds (e a)).sets, ∀ b, e b ∈ t → b ∈ s) :
dense_embedding e :=
⟨dense, inj, λ a, le_antisymm
(by simpa [le_def] using H a)
(tendsto_iff_comap.1 $ c.tendsto _)⟩
namespace dense_embedding
variables [topological_space α] [topological_space β]
variables {e : α → β} (de : dense_embedding e)
protected lemma embedding (de : dense_embedding e) : embedding e :=
⟨de.inj, eq_of_nhds_eq_nhds begin intro a, rw [← de.induced a, nhds_induced_eq_comap] end⟩
protected lemma tendsto (de : dense_embedding e) {a : α} : tendsto e (nhds a) (nhds (e a)) :=
by rw [←de.induced a]; exact tendsto_comap
protected lemma continuous (de : dense_embedding e) {a : α} : continuous e :=
continuous_iff_tendsto.2 $ λ a, de.tendsto
lemma inj_iff (de : dense_embedding e) {x y} : e x = e y ↔ x = y := de.inj.eq_iff
lemma closure_range : closure (range e) = univ :=
let h := de.dense in
set.ext $ assume x, ⟨assume _, trivial, assume _, @h x⟩
lemma self_sub_closure_image_preimage_of_open {s : set β} (de : dense_embedding e) :
is_open s → s ⊆ closure (e '' (e ⁻¹' s)) :=
begin
intros s_op b b_in_s,
rw [image_preimage_eq_inter_range, mem_closure_iff],
intros U U_op b_in,
rw ←inter_assoc,
have ne_e : U ∩ s ≠ ∅ := ne_empty_of_mem ⟨b_in, b_in_s⟩,
exact (dense_iff_inter_open.1 de.closure_range) _ (is_open_inter U_op s_op) ne_e
end
lemma closure_image_nhds_of_nhds {s : set α} {a : α} (de : dense_embedding e) :
s ∈ (nhds a).sets → closure (e '' s) ∈ (nhds (e a)).sets :=
begin
rw [← de.induced a, mem_comap_sets],
intro h,
rcases h with ⟨t, t_nhd, sub⟩,
rw mem_nhds_sets_iff at t_nhd,
rcases t_nhd with ⟨U, U_sub, ⟨U_op, e_a_in_U⟩⟩,
have := calc e ⁻¹' U ⊆ e⁻¹' t : preimage_mono U_sub
... ⊆ s : sub,
have := calc U ⊆ closure (e '' (e ⁻¹' U)) : self_sub_closure_image_preimage_of_open de U_op
... ⊆ closure (e '' s) : closure_mono (image_subset e this),
have U_nhd : U ∈ (nhds (e a)).sets := mem_nhds_sets U_op e_a_in_U,
exact (nhds (e a)).sets_of_superset U_nhd this
end
variables [topological_space δ] {f : γ → α} {g : γ → δ} {h : δ → β}
/--
γ -f→ α
g↓ ↓e
δ -h→ β
-/
lemma tendsto_comap_nhds_nhds {d : δ} {a : α} (de : dense_embedding e) (H : tendsto h (nhds d) (nhds (e a)))
(comm : h ∘ g = e ∘ f) : tendsto f (comap g (nhds d)) (nhds a) :=
begin
have lim1 : map g (comap g (nhds d)) ≤ nhds d := map_comap_le,
replace lim1 : map h (map g (comap g (nhds d))) ≤ map h (nhds d) := map_mono lim1,
rw [filter.map_map, comm, ← filter.map_map, map_le_iff_le_comap] at lim1,
have lim2 : comap e (map h (nhds d)) ≤ comap e (nhds (e a)) := comap_mono H,
rw de.induced at lim2,
exact le_trans lim1 lim2,
end
protected lemma nhds_inf_neq_bot (de : dense_embedding e) {b : β} : nhds b ⊓ principal (range e) ≠ ⊥ :=
begin
have h := de.dense,
simp [closure_eq_nhds] at h,
exact h _
end
lemma comap_nhds_neq_bot (de : dense_embedding e) {b : β} : comap e (nhds b) ≠ ⊥ :=
forall_sets_neq_empty_iff_neq_bot.mp $
assume s ⟨t, ht, (hs : e ⁻¹' t ⊆ s)⟩,
have t ∩ range e ∈ (nhds b ⊓ principal (range e)).sets,
from inter_mem_inf_sets ht (subset.refl _),
let ⟨_, ⟨hx₁, y, rfl⟩⟩ := inhabited_of_mem_sets de.nhds_inf_neq_bot this in
subset_ne_empty hs $ ne_empty_of_mem hx₁
variables [topological_space γ]
/-- If `e : α → β` is a dense embedding, then any function `α → γ` extends to a function `β → γ`.
It only extends the parts of `β` which are not mapped by `e`, everything else equal to `f (e a)`.
This allows us to gain equality even if `γ` is not T2. -/
def extend (de : dense_embedding e) (f : α → γ) (b : β) : γ :=
have nonempty γ, from
let ⟨_, ⟨_, a, _⟩⟩ := exists_mem_of_ne_empty (mem_closure_iff.1 (de.dense b) _ is_open_univ trivial) in
⟨f a⟩,
if hb : b ∈ range e
then f (classical.some hb)
else @lim _ (classical.inhabited_of_nonempty this) _ (map f (comap e (nhds b)))
lemma extend_e_eq {f : α → γ} (a : α) : de.extend f (e a) = f a :=
have e a ∈ range e := ⟨a, rfl⟩,
begin
simp [extend, this],
congr,
refine classical.some_spec2 (λx, x = a) _,
exact assume a h, de.inj h
end
lemma extend_eq [t2_space γ] {b : β} {c : γ} {f : α → γ} (hf : map f (comap e (nhds b)) ≤ nhds c) :
de.extend f b = c :=
begin
by_cases hb : b ∈ range e,
{ rcases hb with ⟨a, rfl⟩,
rw [extend_e_eq],
have f_a_c : tendsto f (pure a) (nhds c),
{ rw [de.induced] at hf,
refine le_trans (map_mono _) hf,
exact pure_le_nhds a },
have f_a_fa : tendsto f (pure a) (nhds (f a)),
{ rw [tendsto, filter.map_pure], exact pure_le_nhds _ },
exact tendsto_nhds_unique pure_neq_bot f_a_fa f_a_c },
{ simp [extend, hb],
exact @lim_eq _ (id _) _ _ _ _ (by simp; exact comap_nhds_neq_bot de) hf }
end
lemma tendsto_extend [regular_space γ] {b : β} {f : α → γ} (de : dense_embedding e)
(hf : {b | ∃c, tendsto f (comap e $ nhds b) (nhds c)} ∈ (nhds b).sets) :
tendsto (de.extend f) (nhds b) (nhds (de.extend f b)) :=
let φ := {b | tendsto f (comap e $ nhds b) (nhds $ de.extend f b)} in
have hφ : φ ∈ (nhds b).sets,
from (nhds b).sets_of_superset hf $ assume b ⟨c, hc⟩,
show tendsto f (comap e (nhds b)) (nhds (de.extend f b)), from (de.extend_eq hc).symm ▸ hc,
assume s hs,
let ⟨s'', hs''₁, hs''₂, hs''₃⟩ := nhds_is_closed hs in
let ⟨s', hs'₁, (hs'₂ : e ⁻¹' s' ⊆ f ⁻¹' s'')⟩ := mem_of_nhds hφ hs''₁ in
let ⟨t, (ht₁ : t ⊆ φ ∩ s'), ht₂, ht₃⟩ := mem_nhds_sets_iff.mp $ inter_mem_sets hφ hs'₁ in
have h₁ : closure (f '' (e ⁻¹' s')) ⊆ s'',
by rw [closure_subset_iff_subset_of_is_closed hs''₃, image_subset_iff]; exact hs'₂,
have h₂ : t ⊆ de.extend f ⁻¹' closure (f '' (e ⁻¹' t)), from
assume b' hb',
have nhds b' ≤ principal t, by simp; exact mem_nhds_sets ht₂ hb',
have map f (comap e (nhds b')) ≤ nhds (de.extend f b') ⊓ principal (f '' (e ⁻¹' t)),
from calc _ ≤ map f (comap e (nhds b' ⊓ principal t)) : map_mono $ comap_mono $ le_inf (le_refl _) this
... ≤ map f (comap e (nhds b')) ⊓ map f (comap e (principal t)) :
le_inf (map_mono $ comap_mono $ inf_le_left) (map_mono $ comap_mono $ inf_le_right)
... ≤ map f (comap e (nhds b')) ⊓ principal (f '' (e ⁻¹' t)) : by simp [le_refl]
... ≤ _ : inf_le_inf ((ht₁ hb').left) (le_refl _),
show de.extend f b' ∈ closure (f '' (e ⁻¹' t)),
begin
rw [closure_eq_nhds],
apply neq_bot_of_le_neq_bot _ this,
simp,
exact de.comap_nhds_neq_bot
end,
(nhds b).sets_of_superset
(show t ∈ (nhds b).sets, from mem_nhds_sets ht₂ ht₃)
(calc t ⊆ de.extend f ⁻¹' closure (f '' (e ⁻¹' t)) : h₂
... ⊆ de.extend f ⁻¹' closure (f '' (e ⁻¹' s')) :
preimage_mono $ closure_mono $ image_subset f $ preimage_mono $ subset.trans ht₁ $ inter_subset_right _ _
... ⊆ de.extend f ⁻¹' s'' : preimage_mono h₁
... ⊆ de.extend f ⁻¹' s : preimage_mono hs''₂)
lemma continuous_extend [regular_space γ] {f : α → γ} (de : dense_embedding e)
(hf : ∀b, ∃c, tendsto f (comap e (nhds b)) (nhds c)) : continuous (de.extend f) :=
continuous_iff_tendsto.mpr $ assume b, de.tendsto_extend $ univ_mem_sets' hf
end dense_embedding
namespace dense_embedding
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
/-- The product of two dense embeddings is a dense embedding -/
protected def prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_embedding e₁) (de₂ : dense_embedding e₂) :
dense_embedding (λ(p : α × γ), (e₁ p.1, e₂ p.2)) :=
{ dense_embedding .
dense :=
have closure (range (λ(p : α × γ), (e₁ p.1, e₂ p.2))) =
set.prod (closure (range e₁)) (closure (range e₂)),
by rw [←closure_prod_eq, prod_range_range_eq],
assume ⟨b, d⟩, begin rw [this], simp, constructor, apply de₁.dense, apply de₂.dense end,
inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩,
by simp; exact assume h₁ h₂, ⟨de₁.inj h₁, de₂.inj h₂⟩,
induced := assume ⟨a, b⟩,
by rw [nhds_prod_eq, nhds_prod_eq, ←prod_comap_comap_eq, de₁.induced, de₂.induced] }
def subtype_emb (p : α → Prop) {e : α → β} (de : dense_embedding e) (x : {x // p x}) :
{x // x ∈ closure (e '' {x | p x})} :=
⟨e x.1, subset_closure $ mem_image_of_mem e x.2⟩
protected def subtype (p : α → Prop) {e : α → β} (de : dense_embedding e) :
dense_embedding (de.subtype_emb p) :=
{ dense_embedding .
dense := assume ⟨x, hx⟩, closure_subtype.mpr $
have (λ (x : {x // p x}), e (x.val)) = e ∘ subtype.val, from rfl,
begin
rw ← image_univ,
simp [(image_comp _ _ _).symm, (∘), subtype_emb, -image_univ],
rw [this, image_comp, subtype_val_image],
simp,
assumption
end,
inj := assume ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq $ de.inj $ @@congr_arg subtype.val h,
induced := assume ⟨x, hx⟩,
by simp [subtype_emb, nhds_subtype_eq_comap, comap_comap_comp, (∘), (de.induced x).symm] }
end dense_embedding
lemma is_closed_property [topological_space α] [topological_space β] {e : α → β} {p : β → Prop}
(he : closure (range e) = univ) (hp : is_closed {x | p x}) (h : ∀a, p (e a)) :
∀b, p b :=
have univ ⊆ {b | p b},
from calc univ = closure (range e) : he.symm
... ⊆ closure {b | p b} : closure_mono $ range_subset_iff.mpr h
... = _ : closure_eq_of_is_closed hp,
assume b, this trivial
lemma is_closed_property2 [topological_space α] [topological_space β] {e : α → β} {p : β → β → Prop}
(he : dense_embedding e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) :
∀b₁ b₂, p b₁ b₂ :=
have ∀q:β×β, p q.1 q.2,
from is_closed_property (he.prod he).closure_range hp $ assume a, h _ _,
assume b₁ b₂, this ⟨b₁, b₂⟩
lemma is_closed_property3 [topological_space α] [topological_space β] {e : α → β} {p : β → β → β → Prop}
(he : dense_embedding e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) :
∀b₁ b₂ b₃, p b₁ b₂ b₃ :=
have ∀q:β×β×β, p q.1 q.2.1 q.2.2,
from is_closed_property (he.prod $ he.prod he).closure_range hp $ assume ⟨a₁, a₂, a₃⟩, h _ _ _,
assume b₁ b₂ b₃, this ⟨b₁, b₂, b₃⟩
lemma mem_closure_of_continuous [topological_space α] [topological_space β]
{f : α → β} {a : α} {s : set α} {t : set β}
(hf : continuous f) (ha : a ∈ closure s) (h : ∀a∈s, f a ∈ closure t) :
f a ∈ closure t :=
calc f a ∈ f '' closure s : mem_image_of_mem _ ha
... ⊆ closure (f '' s) : image_closure_subset_closure_image hf
... ⊆ closure (closure t) : closure_mono $ image_subset_iff.mpr $ h
... ⊆ closure t : begin rw [closure_eq_of_is_closed], exact subset.refl _, exact is_closed_closure end
lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ]
{f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ}
(hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t)
(h : ∀a∈s, ∀b∈t, f a b ∈ closure u) :
f a b ∈ closure u :=
have (a,b) ∈ closure (set.prod s t),
by simp [closure_prod_eq, ha, hb],
show f (a, b).1 (a, b).2 ∈ closure u,
from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $
assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
/-- α and β are homeomorph, also called topological isomoph -/
structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β]
extends α ≃ β :=
(continuous_to_fun : continuous to_fun)
(continuous_inv_fun : continuous inv_fun)
infix ` ≃ₜ `:50 := homeomorph
namespace homeomorph
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
instance : has_coe_to_fun (α ≃ₜ β) := ⟨λ_, α → β, λe, e.to_equiv⟩
lemma coe_eq_to_equiv (h : α ≃ₜ β) (a : α) : h a = h.to_equiv a := rfl
protected def refl (α : Type*) [topological_space α] : α ≃ₜ α :=
{ continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, .. equiv.refl α }
protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ :=
{ continuous_to_fun := h₁.continuous_to_fun.comp h₂.continuous_to_fun,
continuous_inv_fun := h₂.continuous_inv_fun.comp h₁.continuous_inv_fun,
.. equiv.trans h₁.to_equiv h₂.to_equiv }
protected def symm (h : α ≃ₜ β) : β ≃ₜ α :=
{ continuous_to_fun := h.continuous_inv_fun,
continuous_inv_fun := h.continuous_to_fun,
.. h.to_equiv.symm }
protected def continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun
lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id :=
funext $ assume a, h.to_equiv.left_inv a
lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id :=
funext $ assume a, h.to_equiv.right_inv a
lemma range_coe (h : α ≃ₜ β) : range h = univ :=
eq_univ_of_forall $ assume b, ⟨h.symm b, congr_fun h.self_comp_symm b⟩
lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h :=
image_eq_preimage_of_inverse h.symm.to_equiv.left_inv h.symm.to_equiv.right_inv
lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h :=
(image_eq_preimage_of_inverse h.to_equiv.left_inv h.to_equiv.right_inv).symm
lemma induced_eq
{α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (h : α ≃ₜ β) :
tβ.induced h = tα :=
le_antisymm
(induced_le_iff_le_coinduced.2 h.continuous)
(calc tα = (tα.induced h.symm).induced h : by rw [induced_compose, symm_comp_self, induced_id]
... ≤ tβ.induced h : induced_mono $ (induced_le_iff_le_coinduced.2 h.symm.continuous))
lemma coinduced_eq
{α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (h : α ≃ₜ β) :
tα.coinduced h = tβ :=
le_antisymm
(calc tα.coinduced h ≤ (tβ.coinduced h.symm).coinduced h : coinduced_mono h.symm.continuous
... = tβ : by rw [coinduced_compose, self_comp_symm, coinduced_id])
h.continuous
lemma compact_image {s : set α} (h : α ≃ₜ β) : compact (h '' s) ↔ compact s :=
⟨λ hs, by have := compact_image hs h.symm.continuous;
rwa [← image_comp, symm_comp_self, image_id] at this,
λ hs, compact_image hs h.continuous⟩
lemma compact_preimage {s : set β} (h : α ≃ₜ β) : compact (h ⁻¹' s) ↔ compact s :=
by rw ← image_symm; exact h.symm.compact_image
protected lemma embedding (h : α ≃ₜ β) : embedding h :=
⟨h.to_equiv.bijective.1, h.induced_eq.symm⟩
protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h :=
{ dense := assume a, by rw [h.range_coe, closure_univ]; trivial,
inj := h.to_equiv.bijective.1,
induced := assume a, by rw [← nhds_induced_eq_comap, h.induced_eq] }
protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h :=
begin
assume s,
rw ← h.preimage_symm,
exact h.symm.continuous s
end
protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h :=
⟨h.to_equiv.bijective.2, h.coinduced_eq.symm⟩
def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : (α × γ) ≃ₜ (β × δ) :=
{ continuous_to_fun :=
continuous.prod_mk (continuous_fst.comp h₁.continuous) (continuous_snd.comp h₂.continuous),
continuous_inv_fun :=
continuous.prod_mk (continuous_fst.comp h₁.symm.continuous) (continuous_snd.comp h₂.symm.continuous),
.. h₁.to_equiv.prod_congr h₂.to_equiv }
section
variables (α β γ)
def prod_comm : (α × β) ≃ₜ (β × α) :=
{ continuous_to_fun := continuous.prod_mk continuous_snd continuous_fst,
continuous_inv_fun := continuous.prod_mk continuous_snd continuous_fst,
.. equiv.prod_comm α β }
def prod_assoc : ((α × β) × γ) ≃ₜ (α × (β × γ)) :=
{ continuous_to_fun :=
continuous.prod_mk (continuous_fst.comp continuous_fst)
(continuous.prod_mk (continuous_fst.comp continuous_snd) continuous_snd),
continuous_inv_fun := continuous.prod_mk
(continuous.prod_mk continuous_fst (continuous_snd.comp continuous_fst))
(continuous_snd.comp continuous_snd),
.. equiv.prod_assoc α β γ }
end
end homeomorph
|
8b3eea1b365e40700d86caf051989e8413164ae5 | 367134ba5a65885e863bdc4507601606690974c1 | /src/tactic/omega/nat/sub_elim.lean | dd0aaf75059c22d1c1a522b9a3f08461d18c6788 | [
"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,709 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
-/
/-
Subtraction elimination for linear natural number arithmetic.
Works by repeatedly rewriting goals of the preform `P[t-s]` into
`P[x] ∧ (t = s + x ∨ (t ≤ s ∧ x = 0))`, where `x` is fresh.
-/
import tactic.omega.nat.form
namespace omega
namespace nat
open_locale omega.nat
namespace preterm
/-- Find subtraction inside preterm and return its operands -/
def sub_terms : preterm → option (preterm × preterm)
| (& i) := none
| (i ** n) := none
| (t +* s) := t.sub_terms <|> s.sub_terms
| (t -* s) := t.sub_terms <|> s.sub_terms <|> some (t,s)
/-- Find (t - s) inside a preterm and replace it with variable k -/
def sub_subst (t s : preterm) (k : nat) : preterm → preterm
| t@(& m) := t
| t@(m ** n) := t
| (x +* y) := x.sub_subst +* y.sub_subst
| (x -* y) :=
if x = t ∧ y = s then (1 ** k)
else x.sub_subst -* y.sub_subst
lemma val_sub_subst {k : nat} {x y : preterm} {v : nat → nat} :
∀ {t : preterm}, t.fresh_index ≤ k →
(sub_subst x y k t).val (update k (x.val v - y.val v) v) = t.val v
| (& m) h1 := rfl
| (m ** n) h1 :=
begin
have h2 : n ≠ k := ne_of_lt h1,
simp only [sub_subst, preterm.val],
rw update_eq_of_ne _ h2,
end
| (t +* s) h1 :=
begin
simp only [sub_subst, val_add], apply fun_mono_2;
apply val_sub_subst (le_trans _ h1),
apply le_max_left, apply le_max_right
end
| (t -* s) h1 :=
begin
simp only [sub_subst, val_sub],
by_cases h2 : t = x ∧ s = y,
{ rw if_pos h2, simp only [val_var, one_mul],
rw [update_eq, h2.left, h2.right] },
{ rw if_neg h2,
simp only [val_sub, sub_subst],
apply fun_mono_2;
apply val_sub_subst (le_trans _ h1),
apply le_max_left, apply le_max_right, }
end
end preterm
namespace preform
/-- Find subtraction inside preform and return its operands -/
def sub_terms : preform → option (preterm × preterm)
| (t =* s) := t.sub_terms <|> s.sub_terms
| (t ≤* s) := t.sub_terms <|> s.sub_terms
| (¬* p) := p.sub_terms
| (p ∨* q) := p.sub_terms <|> q.sub_terms
| (p ∧* q) := p.sub_terms <|> q.sub_terms
/-- Find (t - s) inside a preform and replace it with variable k -/
@[simp] def sub_subst (x y : preterm) (k : nat) : preform → preform
| (t =* s) := preterm.sub_subst x y k t =* preterm.sub_subst x y k s
| (t ≤* s) := preterm.sub_subst x y k t ≤* preterm.sub_subst x y k s
| (¬* p) := ¬* p.sub_subst
| (p ∨* q) := p.sub_subst ∨* q.sub_subst
| (p ∧* q) := p.sub_subst ∧* q.sub_subst
end preform
/-- Preform which asserts that the value of variable k is
the truncated difference between preterms t and s -/
def is_diff (t s : preterm) (k : nat) : preform :=
((t =* (s +* (1 ** k))) ∨* (t ≤* s ∧* ((1 ** k) =* &0)))
lemma holds_is_diff {t s : preterm} {k : nat} {v : nat → nat} :
v k = t.val v - s.val v → (is_diff t s k).holds v :=
begin
intro h1,
simp only [preform.holds, is_diff, if_pos (eq.refl 1),
preterm.val_add, preterm.val_var, preterm.val_const],
by_cases h2 : t.val v ≤ s.val v,
{ right, refine ⟨h2,_⟩,
rw [h1, one_mul, nat.sub_eq_zero_iff_le], exact h2 },
{ left, rw [h1, one_mul, add_comm, nat.sub_add_cancel _],
rw not_le at h2, apply le_of_lt h2 }
end
/-- Helper function for sub_elim -/
def sub_elim_core (t s : preterm) (k : nat) (p : preform) : preform :=
(preform.sub_subst t s k p) ∧* (is_diff t s k)
/-- Return de Brujin index of fresh variable that does not occur
in any of the arguments -/
def sub_fresh_index (t s : preterm) (p : preform) : nat :=
max p.fresh_index (max t.fresh_index s.fresh_index)
/-- Return a new preform with all subtractions eliminated -/
def sub_elim (t s : preterm) (p : preform) : preform :=
sub_elim_core t s (sub_fresh_index t s p) p
lemma sub_subst_equiv {k : nat} {x y : preterm} {v : nat → nat} :
∀ p : preform, p.fresh_index ≤ k → ((preform.sub_subst x y k p).holds
(update k (x.val v - y.val v) v) ↔ (p.holds v))
| (t =* s) h1 :=
begin
simp only [preform.holds, preform.sub_subst],
apply pred_mono_2;
apply preterm.val_sub_subst (le_trans _ h1),
apply le_max_left, apply le_max_right
end
| (t ≤* s) h1 :=
begin
simp only [preform.holds, preform.sub_subst],
apply pred_mono_2;
apply preterm.val_sub_subst (le_trans _ h1),
apply le_max_left, apply le_max_right
end
| (¬* p) h1 :=
by { apply not_iff_not_of_iff, apply sub_subst_equiv p h1 }
| (p ∨* q) h1 :=
begin
simp only [preform.holds, preform.sub_subst],
apply pred_mono_2; apply propext;
apply sub_subst_equiv _ (le_trans _ h1),
apply le_max_left, apply le_max_right
end
| (p ∧* q) h1 :=
begin
simp only [preform.holds, preform.sub_subst],
apply pred_mono_2; apply propext;
apply sub_subst_equiv _ (le_trans _ h1),
apply le_max_left, apply le_max_right
end
lemma sat_sub_elim {t s : preterm} {p : preform} :
p.sat → (sub_elim t s p).sat :=
begin
intro h1, simp only [sub_elim, sub_elim_core],
cases h1 with v h1,
refine ⟨update (sub_fresh_index t s p) (t.val v - s.val v) v, _⟩,
constructor,
{ apply (sub_subst_equiv p _).elim_right h1,
apply le_max_left },
{ apply holds_is_diff, rw update_eq,
apply fun_mono_2;
apply preterm.val_constant; intros x h2;
rw update_eq_of_ne _ (ne.symm (ne_of_gt _));
apply lt_of_lt_of_le h2;
apply le_trans _ (le_max_right _ _),
apply le_max_left, apply le_max_right }
end
lemma unsat_of_unsat_sub_elim (t s : preterm) (p : preform) :
(sub_elim t s p).unsat → p.unsat := mt sat_sub_elim
end nat
end omega
|
008a422ad19c056c67513d000718433284ce8e26 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/topology/uniform_space/equiv.lean | 9ebf5a9481b64e291e5bf20acaf67c2c92399ca8 | [
"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 | 11,967 | lean | /-
Copyright (c) 2022 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton,
Anatole Dedecker
-/
import topology.homeomorph
import topology.uniform_space.uniform_embedding
import topology.uniform_space.pi
/-!
# Uniform isomorphisms
This file defines uniform isomorphisms between two uniform spaces. They are bijections with both
directions uniformly continuous. We denote uniform isomorphisms with the notation `≃ᵤ`.
# Main definitions
* `uniform_equiv α β`: The type of uniform isomorphisms from `α` to `β`.
This type can be denoted using the following notation: `α ≃ᵤ β`.
-/
open set filter
open_locale
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-- Uniform isomorphism between `α` and `β` -/
@[nolint has_inhabited_instance] -- not all spaces are homeomorphic to each other
structure uniform_equiv (α : Type*) (β : Type*) [uniform_space α] [uniform_space β]
extends α ≃ β :=
(uniform_continuous_to_fun : uniform_continuous to_fun)
(uniform_continuous_inv_fun : uniform_continuous inv_fun)
infix ` ≃ᵤ `:25 := uniform_equiv
namespace uniform_equiv
variables [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ]
instance : has_coe_to_fun (α ≃ᵤ β) (λ _, α → β) := ⟨λe, e.to_equiv⟩
@[simp] lemma uniform_equiv_mk_coe (a : equiv α β) (b c) :
((uniform_equiv.mk a b c) : α → β) = a :=
rfl
/-- Inverse of a uniform isomorphism. -/
protected def symm (h : α ≃ᵤ β) : β ≃ᵤ α :=
{ uniform_continuous_to_fun := h.uniform_continuous_inv_fun,
uniform_continuous_inv_fun := h.uniform_continuous_to_fun,
to_equiv := h.to_equiv.symm }
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.apply (h : α ≃ᵤ β) : α → β := h
/-- See Note [custom simps projection] -/
def simps.symm_apply (h : α ≃ᵤ β) : β → α := h.symm
initialize_simps_projections uniform_equiv
(to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, -to_equiv)
@[simp] lemma coe_to_equiv (h : α ≃ᵤ β) : ⇑h.to_equiv = h := rfl
@[simp] lemma coe_symm_to_equiv (h : α ≃ᵤ β) : ⇑h.to_equiv.symm = h.symm := rfl
lemma to_equiv_injective : function.injective (to_equiv : α ≃ᵤ β → α ≃ β)
| ⟨e, h₁, h₂⟩ ⟨e', h₁', h₂'⟩ rfl := rfl
@[ext] lemma ext {h h' : α ≃ᵤ β} (H : ∀ x, h x = h' x) : h = h' :=
to_equiv_injective $ equiv.ext H
/-- Identity map as a uniform isomorphism. -/
@[simps apply {fully_applied := ff}]
protected def refl (α : Type*) [uniform_space α] : α ≃ᵤ α :=
{ uniform_continuous_to_fun := uniform_continuous_id,
uniform_continuous_inv_fun := uniform_continuous_id,
to_equiv := equiv.refl α }
/-- Composition of two uniform isomorphisms. -/
protected def trans (h₁ : α ≃ᵤ β) (h₂ : β ≃ᵤ γ) : α ≃ᵤ γ :=
{ uniform_continuous_to_fun := h₂.uniform_continuous_to_fun.comp h₁.uniform_continuous_to_fun,
uniform_continuous_inv_fun := h₁.uniform_continuous_inv_fun.comp h₂.uniform_continuous_inv_fun,
to_equiv := equiv.trans h₁.to_equiv h₂.to_equiv }
@[simp] lemma trans_apply (h₁ : α ≃ᵤ β) (h₂ : β ≃ᵤ γ) (a : α) : h₁.trans h₂ a = h₂ (h₁ a) := rfl
@[simp] lemma uniform_equiv_mk_coe_symm (a : equiv α β) (b c) :
((uniform_equiv.mk a b c).symm : β → α) = a.symm :=
rfl
@[simp] lemma refl_symm : (uniform_equiv.refl α).symm = uniform_equiv.refl α := rfl
protected lemma uniform_continuous (h : α ≃ᵤ β) : uniform_continuous h :=
h.uniform_continuous_to_fun
@[continuity]
protected lemma continuous (h : α ≃ᵤ β) : continuous h :=
h.uniform_continuous.continuous
protected lemma uniform_continuous_symm (h : α ≃ᵤ β) : uniform_continuous (h.symm) :=
h.uniform_continuous_inv_fun
@[continuity] -- otherwise `by continuity` can't prove continuity of `h.to_equiv.symm`
protected lemma continuous_symm (h : α ≃ᵤ β) : continuous (h.symm) :=
h.uniform_continuous_symm.continuous
/-- A uniform isomorphism as a homeomorphism. -/
@[simps]
protected def to_homeomorph (e : α ≃ᵤ β) : α ≃ₜ β :=
{ continuous_to_fun := e.continuous,
continuous_inv_fun := e.continuous_symm,
.. e.to_equiv }
@[simp] lemma apply_symm_apply (h : α ≃ᵤ β) (x : β) : h (h.symm x) = x :=
h.to_equiv.apply_symm_apply x
@[simp] lemma symm_apply_apply (h : α ≃ᵤ β) (x : α) : h.symm (h x) = x :=
h.to_equiv.symm_apply_apply x
protected lemma bijective (h : α ≃ᵤ β) : function.bijective h := h.to_equiv.bijective
protected lemma injective (h : α ≃ᵤ β) : function.injective h := h.to_equiv.injective
protected lemma surjective (h : α ≃ᵤ β) : function.surjective h := h.to_equiv.surjective
/-- Change the uniform equiv `f` to make the inverse function definitionally equal to `g`. -/
def change_inv (f : α ≃ᵤ β) (g : β → α) (hg : function.right_inverse g f) : α ≃ᵤ β :=
have g = f.symm, from funext (λ x, calc g x = f.symm (f (g x)) : (f.left_inv (g x)).symm
... = f.symm x : by rw hg x),
{ to_fun := f,
inv_fun := g,
left_inv := by convert f.left_inv,
right_inv := by convert f.right_inv,
uniform_continuous_to_fun := f.uniform_continuous,
uniform_continuous_inv_fun := by convert f.symm.uniform_continuous }
@[simp] lemma symm_comp_self (h : α ≃ᵤ β) : ⇑h.symm ∘ ⇑h = id :=
funext h.symm_apply_apply
@[simp] lemma self_comp_symm (h : α ≃ᵤ β) : ⇑h ∘ ⇑h.symm = id :=
funext h.apply_symm_apply
@[simp] lemma range_coe (h : α ≃ᵤ β) : range h = univ :=
h.surjective.range_eq
lemma image_symm (h : α ≃ᵤ β) : image h.symm = preimage h :=
funext h.symm.to_equiv.image_eq_preimage
lemma preimage_symm (h : α ≃ᵤ β) : preimage h.symm = image h :=
(funext h.to_equiv.image_eq_preimage).symm
@[simp] lemma image_preimage (h : α ≃ᵤ β) (s : set β) : h '' (h ⁻¹' s) = s :=
h.to_equiv.image_preimage s
@[simp] lemma preimage_image (h : α ≃ᵤ β) (s : set α) : h ⁻¹' (h '' s) = s :=
h.to_equiv.preimage_image s
protected lemma uniform_inducing (h : α ≃ᵤ β) : uniform_inducing h :=
uniform_inducing_of_compose h.uniform_continuous h.symm.uniform_continuous $
by simp only [symm_comp_self, uniform_inducing_id]
lemma comap_eq (h : α ≃ᵤ β) : uniform_space.comap h ‹_› = ‹_› :=
by ext : 1; exact h.uniform_inducing.comap_uniformity
protected lemma uniform_embedding (h : α ≃ᵤ β) : uniform_embedding h :=
⟨h.uniform_inducing, h.injective⟩
/-- Uniform equiv given a uniform embedding. -/
noncomputable def of_uniform_embedding (f : α → β) (hf : uniform_embedding f) :
α ≃ᵤ (set.range f) :=
{ uniform_continuous_to_fun := uniform_continuous_subtype_mk
hf.to_uniform_inducing.uniform_continuous _,
uniform_continuous_inv_fun :=
by simp [hf.to_uniform_inducing.uniform_continuous_iff, uniform_continuous_subtype_coe],
to_equiv := equiv.of_injective f hf.inj }
/-- If two sets are equal, then they are uniformly equivalent. -/
def set_congr {s t : set α} (h : s = t) : s ≃ᵤ t :=
{ uniform_continuous_to_fun := uniform_continuous_subtype_mk uniform_continuous_subtype_val _,
uniform_continuous_inv_fun := uniform_continuous_subtype_mk uniform_continuous_subtype_val _,
to_equiv := equiv.set_congr h }
/-- Product of two uniform isomorphisms. -/
def prod_congr (h₁ : α ≃ᵤ β) (h₂ : γ ≃ᵤ δ) : α × γ ≃ᵤ β × δ :=
{ uniform_continuous_to_fun := (h₁.uniform_continuous.comp uniform_continuous_fst).prod_mk
(h₂.uniform_continuous.comp uniform_continuous_snd),
uniform_continuous_inv_fun := (h₁.symm.uniform_continuous.comp uniform_continuous_fst).prod_mk
(h₂.symm.uniform_continuous.comp uniform_continuous_snd),
to_equiv := h₁.to_equiv.prod_congr h₂.to_equiv }
@[simp] lemma prod_congr_symm (h₁ : α ≃ᵤ β) (h₂ : γ ≃ᵤ δ) :
(h₁.prod_congr h₂).symm = h₁.symm.prod_congr h₂.symm := rfl
@[simp] lemma coe_prod_congr (h₁ : α ≃ᵤ β) (h₂ : γ ≃ᵤ δ) :
⇑(h₁.prod_congr h₂) = prod.map h₁ h₂ := rfl
section
variables (α β γ)
/-- `α × β` is uniformly isomorphic to `β × α`. -/
def prod_comm : α × β ≃ᵤ β × α :=
{ uniform_continuous_to_fun := uniform_continuous_snd.prod_mk uniform_continuous_fst,
uniform_continuous_inv_fun := uniform_continuous_snd.prod_mk uniform_continuous_fst,
to_equiv := equiv.prod_comm α β }
@[simp] lemma prod_comm_symm : (prod_comm α β).symm = prod_comm β α := rfl
@[simp] lemma coe_prod_comm : ⇑(prod_comm α β) = prod.swap := rfl
/-- `(α × β) × γ` is uniformly isomorphic to `α × (β × γ)`. -/
def prod_assoc : (α × β) × γ ≃ᵤ α × (β × γ) :=
{ uniform_continuous_to_fun := (uniform_continuous_fst.comp uniform_continuous_fst).prod_mk
((uniform_continuous_snd.comp uniform_continuous_fst).prod_mk uniform_continuous_snd),
uniform_continuous_inv_fun := (uniform_continuous_fst.prod_mk
(uniform_continuous_fst.comp uniform_continuous_snd)).prod_mk
(uniform_continuous_snd.comp uniform_continuous_snd),
to_equiv := equiv.prod_assoc α β γ }
/-- `α × {*}` is uniformly isomorphic to `α`. -/
@[simps apply {fully_applied := ff}]
def prod_punit : α × punit ≃ᵤ α :=
{ to_equiv := equiv.prod_punit α,
uniform_continuous_to_fun := uniform_continuous_fst,
uniform_continuous_inv_fun := uniform_continuous_id.prod_mk uniform_continuous_const }
/-- `{*} × α` is uniformly isomorphic to `α`. -/
def punit_prod : punit × α ≃ᵤ α :=
(prod_comm _ _).trans (prod_punit _)
@[simp] lemma coe_punit_prod : ⇑(punit_prod α) = prod.snd := rfl
end
/-- If `ι` has a unique element, then `ι → α` is homeomorphic to `α`. -/
@[simps { fully_applied := ff }]
def fun_unique (ι α : Type*) [unique ι] [uniform_space α] : (ι → α) ≃ᵤ α :=
{ to_equiv := equiv.fun_unique ι α,
uniform_continuous_to_fun := Pi.uniform_continuous_proj _ _,
uniform_continuous_inv_fun := uniform_continuous_pi.mpr (λ _, uniform_continuous_id) }
/-- Uniform isomorphism between dependent functions `Π i : fin 2, α i` and `α 0 × α 1`. -/
@[simps { fully_applied := ff }]
def {u} pi_fin_two (α : fin 2 → Type u) [Π i, uniform_space (α i)] : (Π i, α i) ≃ᵤ α 0 × α 1 :=
{ to_equiv := pi_fin_two_equiv α,
uniform_continuous_to_fun :=
(Pi.uniform_continuous_proj _ 0).prod_mk (Pi.uniform_continuous_proj _ 1),
uniform_continuous_inv_fun := uniform_continuous_pi.mpr $
fin.forall_fin_two.2 ⟨uniform_continuous_fst, uniform_continuous_snd⟩ }
/-- Uniform isomorphism between `α² = fin 2 → α` and `α × α`. -/
@[simps { fully_applied := ff }] def fin_two_arrow : (fin 2 → α) ≃ᵤ α × α :=
{ to_equiv := fin_two_arrow_equiv α, .. pi_fin_two (λ _, α) }
/--
A subset of a uniform space is uniformly isomorphic to its image under a uniform isomorphism.
-/
def image (e : α ≃ᵤ β) (s : set α) : s ≃ᵤ e '' s :=
{ uniform_continuous_to_fun := uniform_continuous_subtype_mk
(e.uniform_continuous.comp uniform_continuous_subtype_val) (λ x, mem_image_of_mem _ x.2),
uniform_continuous_inv_fun := uniform_continuous_subtype_mk
(e.symm.uniform_continuous.comp uniform_continuous_subtype_val)
(λ x, by simpa using mem_image_of_mem e.symm x.2),
to_equiv := e.to_equiv.image s }
end uniform_equiv
/-- A uniform inducing equiv between uniform spaces is a uniform isomorphism. -/
@[simps] def equiv.to_uniform_equiv_of_uniform_inducing [uniform_space α] [uniform_space β]
(f : α ≃ β) (hf : uniform_inducing f) :
α ≃ᵤ β :=
{ uniform_continuous_to_fun := hf.uniform_continuous,
uniform_continuous_inv_fun := hf.uniform_continuous_iff.2 $ by simpa using uniform_continuous_id,
.. f }
|
8195ba69bc29032c3542e84a99e086ed2d1959c0 | 90bd8c2a52dbaaba588bdab57b155a7ec1532de0 | /src/path/lift.lean | 939e3264908f8fdd9e242229c7204560c2fc6de9 | [
"Apache-2.0"
] | permissive | shingtaklam1324/alg-top | fd434f1478925a232af45f18f370ee3a22811c54 | 4c88e28df6f0a329f26eab32bae023789193990e | refs/heads/master | 1,689,447,024,947 | 1,630,073,400,000 | 1,630,073,400,000 | 381,528,689 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 579 | lean | import covering_space.lift
import locally_path_connected
import path.defs
variables {X X' Y : Type _} [topological_space X] [topological_space X'] [topological_space Y]
variables {x₀ x₁ : X}
example (p : C(X', X)) (hp : is_covering_map p) (γ : path' x₀ x₁) (x₀' : X') (hx₀' : p x₀' = x₀) :
is_open {t ∈ set.Icc (0 : ℝ) 1 | ∃ γ' : C(ℝ, X'), (∀ w ∈ set.Icc (0 : ℝ) t, γ w = (p.comp γ') w) ∧ γ' 0 = x₀'} :=
begin
rw is_open_iff_forall_mem_open,
rintros t₀ ⟨ht₀, γ', hγ'₀, hγ'₁⟩,
let U := hp.U (γ t₀),
dsimp,
end
|
41e3ba76ea0257445b6b06786258bbfb464ad4e7 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/direct_sum/ring.lean | 8da08a69f5213d7c25bb22a2bf036667634df29a | [
"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,806 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import algebra.graded_monoid
import algebra.direct_sum.basic
/-!
# Additively-graded multiplicative structures on `⨁ i, A i`
This module provides a set of heterogeneous typeclasses for defining a multiplicative structure
over `⨁ i, A i` such that `(*) : A i → A j → A (i + j)`; that is to say, `A` forms an
additively-graded ring. The typeclasses are:
* `direct_sum.gnon_unital_non_assoc_semiring A`
* `direct_sum.gsemiring A`
* `direct_sum.gring A`
* `direct_sum.gcomm_semiring A`
* `direct_sum.gcomm_ring A`
Respectively, these imbue the external direct sum `⨁ i, A i` with:
* `direct_sum.non_unital_non_assoc_semiring`, `direct_sum.non_unital_non_assoc_ring`
* `direct_sum.semiring`
* `direct_sum.ring`
* `direct_sum.comm_semiring`
* `direct_sum.comm_ring`
the base ring `A 0` with:
* `direct_sum.grade_zero.non_unital_non_assoc_semiring`,
`direct_sum.grade_zero.non_unital_non_assoc_ring`
* `direct_sum.grade_zero.semiring`
* `direct_sum.grade_zero.ring`
* `direct_sum.grade_zero.comm_semiring`
* `direct_sum.grade_zero.comm_ring`
and the `i`th grade `A i` with `A 0`-actions (`•`) defined as left-multiplication:
* `direct_sum.grade_zero.has_smul (A 0)`, `direct_sum.grade_zero.smul_with_zero (A 0)`
* `direct_sum.grade_zero.module (A 0)`
* (nothing)
* (nothing)
* (nothing)
Note that in the presence of these instances, `⨁ i, A i` itself inherits an `A 0`-action.
`direct_sum.of_zero_ring_hom : A 0 →+* ⨁ i, A i` provides `direct_sum.of A 0` as a ring
homomorphism.
`direct_sum.to_semiring` extends `direct_sum.to_add_monoid` to produce a `ring_hom`.
## Direct sums of subobjects
Additionally, this module provides helper functions to construct `gsemiring` and `gcomm_semiring`
instances for:
* `A : ι → submonoid S`:
`direct_sum.gsemiring.of_add_submonoids`, `direct_sum.gcomm_semiring.of_add_submonoids`.
* `A : ι → subgroup S`:
`direct_sum.gsemiring.of_add_subgroups`, `direct_sum.gcomm_semiring.of_add_subgroups`.
* `A : ι → submodule S`:
`direct_sum.gsemiring.of_submodules`, `direct_sum.gcomm_semiring.of_submodules`.
If `complete_lattice.independent (set.range A)`, these provide a gradation of `⨆ i, A i`, and the
mapping `⨁ i, A i →+ ⨆ i, A i` can be obtained as
`direct_sum.to_monoid (λ i, add_submonoid.inclusion $ le_supr A i)`.
## tags
graded ring, filtered ring, direct sum, add_submonoid
-/
set_option old_structure_cmd true
variables {ι : Type*} [decidable_eq ι]
namespace direct_sum
open_locale direct_sum
/-! ### Typeclasses -/
section defs
variables (A : ι → Type*)
/-- A graded version of `non_unital_non_assoc_semiring`. -/
class gnon_unital_non_assoc_semiring [has_add ι] [Π i, add_comm_monoid (A i)] extends
graded_monoid.ghas_mul A :=
(mul_zero : ∀ {i j} (a : A i), mul a (0 : A j) = 0)
(zero_mul : ∀ {i j} (b : A j), mul (0 : A i) b = 0)
(mul_add : ∀ {i j} (a : A i) (b c : A j), mul a (b + c) = mul a b + mul a c)
(add_mul : ∀ {i j} (a b : A i) (c : A j), mul (a + b) c = mul a c + mul b c)
end defs
section defs
variables (A : ι → Type*)
/-- A graded version of `semiring`. -/
class gsemiring [add_monoid ι] [Π i, add_comm_monoid (A i)] extends
gnon_unital_non_assoc_semiring A, graded_monoid.gmonoid A :=
(nat_cast : ℕ → A 0)
(nat_cast_zero : nat_cast 0 = 0)
(nat_cast_succ : ∀ n : ℕ, nat_cast (n + 1) = nat_cast n + graded_monoid.ghas_one.one)
/-- A graded version of `comm_semiring`. -/
class gcomm_semiring [add_comm_monoid ι] [Π i, add_comm_monoid (A i)] extends
gsemiring A, graded_monoid.gcomm_monoid A
/-- A graded version of `ring`. -/
class gring [add_monoid ι] [Π i, add_comm_group (A i)] extends gsemiring A :=
(int_cast : ℤ → A 0)
(int_cast_of_nat : ∀ n : ℕ, int_cast n = nat_cast n)
(int_cast_neg_succ_of_nat : ∀ n : ℕ, int_cast (-(n+1 : ℕ)) = -nat_cast (n+1 : ℕ))
/-- A graded version of `comm_ring`. -/
class gcomm_ring [add_comm_monoid ι] [Π i, add_comm_group (A i)] extends
gring A, gcomm_semiring A
end defs
lemma of_eq_of_graded_monoid_eq {A : ι → Type*} [Π (i : ι), add_comm_monoid (A i)]
{i j : ι} {a : A i} {b : A j} (h : graded_monoid.mk i a = graded_monoid.mk j b) :
direct_sum.of A i a = direct_sum.of A j b :=
dfinsupp.single_eq_of_sigma_eq h
variables (A : ι → Type*)
/-! ### Instances for `⨁ i, A i` -/
section one
variables [has_zero ι] [graded_monoid.ghas_one A] [Π i, add_comm_monoid (A i)]
instance : has_one (⨁ i, A i) :=
{ one := direct_sum.of (λ i, A i) 0 graded_monoid.ghas_one.one }
end one
section mul
variables [has_add ι] [Π i, add_comm_monoid (A i)] [gnon_unital_non_assoc_semiring A]
open add_monoid_hom (flip_apply coe_comp comp_hom_apply_apply)
/-- The piecewise multiplication from the `has_mul` instance, as a bundled homomorphism. -/
@[simps]
def gmul_hom {i j} : A i →+ A j →+ A (i + j) :=
{ to_fun := λ a,
{ to_fun := λ b, graded_monoid.ghas_mul.mul a b,
map_zero' := gnon_unital_non_assoc_semiring.mul_zero _,
map_add' := gnon_unital_non_assoc_semiring.mul_add _ },
map_zero' := add_monoid_hom.ext $ λ a, gnon_unital_non_assoc_semiring.zero_mul a,
map_add' := λ a₁ a₂, add_monoid_hom.ext $ λ b, gnon_unital_non_assoc_semiring.add_mul _ _ _}
/-- The multiplication from the `has_mul` instance, as a bundled homomorphism. -/
def mul_hom : (⨁ i, A i) →+ (⨁ i, A i) →+ ⨁ i, A i :=
direct_sum.to_add_monoid $ λ i,
add_monoid_hom.flip $ direct_sum.to_add_monoid $ λ j, add_monoid_hom.flip $
(direct_sum.of A _).comp_hom.comp $ gmul_hom A
instance : non_unital_non_assoc_semiring (⨁ i, A i) :=
{ mul := λ a b, mul_hom A a b,
zero := 0,
add := (+),
zero_mul := λ a, by simp only [add_monoid_hom.map_zero, add_monoid_hom.zero_apply],
mul_zero := λ a, by simp only [add_monoid_hom.map_zero],
left_distrib := λ a b c, by simp only [add_monoid_hom.map_add],
right_distrib := λ a b c, by simp only [add_monoid_hom.map_add, add_monoid_hom.add_apply],
.. direct_sum.add_comm_monoid _ _}
variables {A}
lemma mul_hom_of_of {i j} (a : A i) (b : A j) :
mul_hom A (of _ i a) (of _ j b) = of _ (i + j) (graded_monoid.ghas_mul.mul a b) :=
begin
unfold mul_hom,
rw [to_add_monoid_of, flip_apply, to_add_monoid_of, flip_apply, coe_comp, function.comp_app,
comp_hom_apply_apply, coe_comp, function.comp_app, gmul_hom_apply_apply],
end
lemma of_mul_of {i j} (a : A i) (b : A j) :
of _ i a * of _ j b = of _ (i + j) (graded_monoid.ghas_mul.mul a b) :=
mul_hom_of_of a b
end mul
section semiring
variables [Π i, add_comm_monoid (A i)] [add_monoid ι] [gsemiring A]
open add_monoid_hom (flip_hom coe_comp comp_hom_apply_apply flip_apply flip_hom_apply)
private lemma one_mul (x : ⨁ i, A i) : 1 * x = x :=
suffices mul_hom A 1 = add_monoid_hom.id (⨁ i, A i),
from add_monoid_hom.congr_fun this x,
begin
apply add_hom_ext, intros i xi,
unfold has_one.one,
rw mul_hom_of_of,
exact of_eq_of_graded_monoid_eq (one_mul $ graded_monoid.mk i xi),
end
private lemma mul_one (x : ⨁ i, A i) : x * 1 = x :=
suffices (mul_hom A).flip 1 = add_monoid_hom.id (⨁ i, A i),
from add_monoid_hom.congr_fun this x,
begin
apply add_hom_ext, intros i xi,
unfold has_one.one,
rw [flip_apply, mul_hom_of_of],
exact of_eq_of_graded_monoid_eq (mul_one $ graded_monoid.mk i xi),
end
private lemma mul_assoc (a b c : ⨁ i, A i) : a * b * c = a * (b * c) :=
suffices (mul_hom A).comp_hom.comp (mul_hom A) -- `λ a b c, a * b * c` as a bundled hom
= (add_monoid_hom.comp_hom flip_hom $ -- `λ a b c, a * (b * c)` as a bundled hom
(mul_hom A).flip.comp_hom.comp (mul_hom A)).flip,
from add_monoid_hom.congr_fun (add_monoid_hom.congr_fun (add_monoid_hom.congr_fun this a) b) c,
begin
ext ai ax bi bx ci cx : 6,
dsimp only [coe_comp, function.comp_app, comp_hom_apply_apply, flip_apply, flip_hom_apply],
rw [mul_hom_of_of, mul_hom_of_of, mul_hom_of_of, mul_hom_of_of],
exact of_eq_of_graded_monoid_eq (mul_assoc (graded_monoid.mk ai ax) ⟨bi, bx⟩ ⟨ci, cx⟩),
end
/-- The `semiring` structure derived from `gsemiring A`. -/
instance semiring : semiring (⨁ i, A i) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
one_mul := one_mul A,
mul_one := mul_one A,
mul_assoc := mul_assoc A,
nat_cast := λ n, of _ _ (gsemiring.nat_cast n),
nat_cast_zero := by rw [gsemiring.nat_cast_zero, map_zero],
nat_cast_succ := λ n, by { rw [gsemiring.nat_cast_succ, map_add], refl },
..direct_sum.non_unital_non_assoc_semiring _, }
lemma of_pow {i} (a : A i) (n : ℕ) :
of _ i a ^ n = of _ (n • i) (graded_monoid.gmonoid.gnpow _ a) :=
begin
induction n with n,
{ exact of_eq_of_graded_monoid_eq (pow_zero $ graded_monoid.mk _ a).symm, },
{ rw [pow_succ, n_ih, of_mul_of],
exact of_eq_of_graded_monoid_eq (pow_succ (graded_monoid.mk _ a) n).symm, },
end
lemma of_list_dprod {α} (l : list α) (fι : α → ι) (fA : Π a, A (fι a)) :
of A _ (l.dprod fι fA) = (l.map $ λ a, of A (fι a) (fA a)).prod :=
begin
induction l,
{ simp only [list.map_nil, list.prod_nil, list.dprod_nil],
refl },
{ simp only [list.map_cons, list.prod_cons, list.dprod_cons, ←l_ih, direct_sum.of_mul_of],
refl },
end
lemma list_prod_of_fn_of_eq_dprod (n : ℕ) (fι : fin n → ι) (fA : Π a, A (fι a)) :
(list.of_fn $ λ a, of A (fι a) (fA a)).prod = of A _ ((list.fin_range n).dprod fι fA) :=
by rw [list.of_fn_eq_map, of_list_dprod]
open_locale big_operators
lemma mul_eq_dfinsupp_sum [Π (i : ι) (x : A i), decidable (x ≠ 0)] (a a' : ⨁ i, A i) :
a * a' = a.sum (λ i ai, a'.sum $ λ j aj, direct_sum.of _ _ $ graded_monoid.ghas_mul.mul ai aj) :=
begin
change mul_hom _ a a' = _,
simpa only [mul_hom, to_add_monoid, dfinsupp.lift_add_hom_apply, dfinsupp.sum_add_hom_apply,
add_monoid_hom.dfinsupp_sum_apply, flip_apply, add_monoid_hom.dfinsupp_sum_add_hom_apply],
end
/-- A heavily unfolded version of the definition of multiplication -/
lemma mul_eq_sum_support_ghas_mul
[Π (i : ι) (x : A i), decidable (x ≠ 0)] (a a' : ⨁ i, A i) :
a * a' =
∑ ij in dfinsupp.support a ×ˢ dfinsupp.support a',
direct_sum.of _ _ (graded_monoid.ghas_mul.mul (a ij.fst) (a' ij.snd)) :=
by simp only [mul_eq_dfinsupp_sum, dfinsupp.sum, finset.sum_product]
end semiring
section comm_semiring
variables [Π i, add_comm_monoid (A i)] [add_comm_monoid ι] [gcomm_semiring A]
private lemma mul_comm (a b : ⨁ i, A i) : a * b = b * a :=
suffices mul_hom A = (mul_hom A).flip,
from add_monoid_hom.congr_fun (add_monoid_hom.congr_fun this a) b,
begin
apply add_hom_ext, intros ai ax, apply add_hom_ext, intros bi bx,
rw [add_monoid_hom.flip_apply, mul_hom_of_of, mul_hom_of_of],
exact of_eq_of_graded_monoid_eq (gcomm_semiring.mul_comm ⟨ai, ax⟩ ⟨bi, bx⟩),
end
/-- The `comm_semiring` structure derived from `gcomm_semiring A`. -/
instance comm_semiring : comm_semiring (⨁ i, A i) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
mul_comm := mul_comm A,
..direct_sum.semiring _, }
end comm_semiring
section non_unital_non_assoc_ring
variables [Π i, add_comm_group (A i)] [has_add ι] [gnon_unital_non_assoc_semiring A]
/-- The `ring` derived from `gsemiring A`. -/
instance non_assoc_ring : non_unital_non_assoc_ring (⨁ i, A i) :=
{ mul := (*),
zero := 0,
add := (+),
neg := has_neg.neg,
..(direct_sum.non_unital_non_assoc_semiring _),
..(direct_sum.add_comm_group _), }
end non_unital_non_assoc_ring
section ring
variables [Π i, add_comm_group (A i)] [add_monoid ι] [gring A]
/-- The `ring` derived from `gsemiring A`. -/
instance ring : ring (⨁ i, A i) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
neg := has_neg.neg,
int_cast := λ z, of _ _ (gring.int_cast z),
int_cast_of_nat := λ z, congr_arg _ $ gring.int_cast_of_nat _,
int_cast_neg_succ_of_nat := λ z,
(congr_arg _ $ gring.int_cast_neg_succ_of_nat _).trans (map_neg _ _),
..(direct_sum.semiring _),
..(direct_sum.add_comm_group _), }
end ring
section comm_ring
variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gcomm_ring A]
/-- The `comm_ring` derived from `gcomm_semiring A`. -/
instance comm_ring : comm_ring (⨁ i, A i) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
neg := has_neg.neg,
..(direct_sum.ring _),
..(direct_sum.comm_semiring _), }
end comm_ring
/-! ### Instances for `A 0`
The various `g*` instances are enough to promote the `add_comm_monoid (A 0)` structure to various
types of multiplicative structure.
-/
section grade_zero
section one
variables [has_zero ι] [graded_monoid.ghas_one A] [Π i, add_comm_monoid (A i)]
@[simp] lemma of_zero_one : of _ 0 (1 : A 0) = 1 := rfl
end one
section mul
variables [add_zero_class ι] [Π i, add_comm_monoid (A i)] [gnon_unital_non_assoc_semiring A]
@[simp] lemma of_zero_smul {i} (a : A 0) (b : A i) : of _ _ (a • b) = of _ _ a * of _ _ b :=
(of_eq_of_graded_monoid_eq (graded_monoid.mk_zero_smul a b)).trans (of_mul_of _ _).symm
@[simp] lemma of_zero_mul (a b : A 0) : of _ 0 (a * b) = of _ 0 a * of _ 0 b:=
of_zero_smul A a b
instance grade_zero.non_unital_non_assoc_semiring : non_unital_non_assoc_semiring (A 0) :=
function.injective.non_unital_non_assoc_semiring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of A 0).map_add (of_zero_mul A) (λ x n, dfinsupp.single_smul n x)
instance grade_zero.smul_with_zero (i : ι) : smul_with_zero (A 0) (A i) :=
begin
letI := smul_with_zero.comp_hom (⨁ i, A i) (of A 0).to_zero_hom,
refine dfinsupp.single_injective.smul_with_zero (of A i).to_zero_hom (of_zero_smul A),
end
end mul
section semiring
variables [Π i, add_comm_monoid (A i)] [add_monoid ι] [gsemiring A]
@[simp] lemma of_zero_pow (a : A 0) : ∀ n : ℕ, of _ 0 (a ^ n) = of _ 0 a ^ n
| 0 := by rw [pow_zero, pow_zero, direct_sum.of_zero_one]
| (n + 1) := by rw [pow_succ, pow_succ, of_zero_mul, of_zero_pow]
instance : has_nat_cast (A 0) := ⟨gsemiring.nat_cast⟩
@[simp] lemma of_nat_cast (n : ℕ) : of A 0 n = n :=
rfl
/-- The `semiring` structure derived from `gsemiring A`. -/
instance grade_zero.semiring : semiring (A 0) :=
function.injective.semiring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A)
(of A 0).map_nsmul (λ x n, of_zero_pow _ _ _) (of_nat_cast A)
/-- `of A 0` is a `ring_hom`, using the `direct_sum.grade_zero.semiring` structure. -/
def of_zero_ring_hom : A 0 →+* (⨁ i, A i) :=
{ map_one' := of_zero_one A, map_mul' := of_zero_mul A, ..(of _ 0) }
/-- Each grade `A i` derives a `A 0`-module structure from `gsemiring A`. Note that this results
in an overall `module (A 0) (⨁ i, A i)` structure via `direct_sum.module`.
-/
instance grade_zero.module {i} : module (A 0) (A i) :=
begin
letI := module.comp_hom (⨁ i, A i) (of_zero_ring_hom A),
exact dfinsupp.single_injective.module (A 0) (of A i) (λ a, of_zero_smul A a),
end
end semiring
section comm_semiring
variables [Π i, add_comm_monoid (A i)] [add_comm_monoid ι] [gcomm_semiring A]
/-- The `comm_semiring` structure derived from `gcomm_semiring A`. -/
instance grade_zero.comm_semiring : comm_semiring (A 0) :=
function.injective.comm_semiring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A)
(λ x n, dfinsupp.single_smul n x) (λ x n, of_zero_pow _ _ _) (of_nat_cast A)
end comm_semiring
section ring
variables [Π i, add_comm_group (A i)] [add_zero_class ι] [gnon_unital_non_assoc_semiring A]
/-- The `non_unital_non_assoc_ring` derived from `gnon_unital_non_assoc_semiring A`. -/
instance grade_zero.non_unital_non_assoc_ring : non_unital_non_assoc_ring (A 0) :=
function.injective.non_unital_non_assoc_ring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of A 0).map_add (of_zero_mul A)
(of A 0).map_neg (of A 0).map_sub
(λ x n, begin
letI : Π i, distrib_mul_action ℕ (A i) := λ i, infer_instance,
exact dfinsupp.single_smul n x
end)
(λ x n, begin
letI : Π i, distrib_mul_action ℤ (A i) := λ i, infer_instance,
exact dfinsupp.single_smul n x
end)
end ring
section ring
variables [Π i, add_comm_group (A i)] [add_monoid ι] [gring A]
instance : has_int_cast (A 0) := ⟨gring.int_cast⟩
@[simp] lemma of_int_cast (n : ℤ) : of A 0 n = n :=
rfl
/-- The `ring` derived from `gsemiring A`. -/
instance grade_zero.ring : ring (A 0) :=
function.injective.ring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A)
(of A 0).map_neg (of A 0).map_sub
(λ x n, begin
letI : Π i, distrib_mul_action ℕ (A i) := λ i, infer_instance,
exact dfinsupp.single_smul n x
end)
(λ x n, begin
letI : Π i, distrib_mul_action ℤ (A i) := λ i, infer_instance,
exact dfinsupp.single_smul n x
end) (λ x n, of_zero_pow _ _ _)
(of_nat_cast A) (of_int_cast A)
end ring
section comm_ring
variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gcomm_ring A]
/-- The `comm_ring` derived from `gcomm_semiring A`. -/
instance grade_zero.comm_ring : comm_ring (A 0) :=
function.injective.comm_ring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A)
(of A 0).map_neg (of A 0).map_sub
(λ x n, begin
letI : Π i, distrib_mul_action ℕ (A i) := λ i, infer_instance,
exact dfinsupp.single_smul n x
end)
(λ x n, begin
letI : Π i, distrib_mul_action ℤ (A i) := λ i, infer_instance,
exact dfinsupp.single_smul n x
end) (λ x n, of_zero_pow _ _ _)
(of_nat_cast A) (of_int_cast A)
end comm_ring
end grade_zero
section to_semiring
variables {R : Type*} [Π i, add_comm_monoid (A i)] [add_monoid ι] [gsemiring A] [semiring R]
variables {A}
/-- If two ring homomorphisms from `⨁ i, A i` are equal on each `of A i y`,
then they are equal.
See note [partially-applied ext lemmas]. -/
@[ext]
lemma ring_hom_ext' ⦃F G : (⨁ i, A i) →+* R⦄
(h : ∀ i, (↑F : _ →+ R).comp (of A i) = (↑G : _ →+ R).comp (of A i)) : F = G :=
ring_hom.coe_add_monoid_hom_injective $ direct_sum.add_hom_ext' h
/-- Two `ring_hom`s out of a direct sum are equal if they agree on the generators. -/
lemma ring_hom_ext ⦃f g : (⨁ i, A i) →+* R⦄ (h : ∀ i x, f (of A i x) = g (of A i x)) :
f = g :=
ring_hom_ext' $ λ i, add_monoid_hom.ext $ h i
/-- A family of `add_monoid_hom`s preserving `direct_sum.ghas_one.one` and `direct_sum.ghas_mul.mul`
describes a `ring_hom`s on `⨁ i, A i`. This is a stronger version of `direct_sum.to_monoid`.
Of particular interest is the case when `A i` are bundled subojects, `f` is the family of
coercions such as `add_submonoid.subtype (A i)`, and the `[gsemiring A]` structure originates from
`direct_sum.gsemiring.of_add_submonoids`, in which case the proofs about `ghas_one` and `ghas_mul`
can be discharged by `rfl`. -/
@[simps]
def to_semiring
(f : Π i, A i →+ R) (hone : f _ (graded_monoid.ghas_one.one) = 1)
(hmul : ∀ {i j} (ai : A i) (aj : A j), f _ (graded_monoid.ghas_mul.mul ai aj) = f _ ai * f _ aj) :
(⨁ i, A i) →+* R :=
{ to_fun := to_add_monoid f,
map_one' := begin
change (to_add_monoid f) (of _ 0 _) = 1,
rw to_add_monoid_of,
exact hone
end,
map_mul' := begin
rw (to_add_monoid f).map_mul_iff,
ext xi xv yi yv : 4,
show to_add_monoid f (of A xi xv * of A yi yv) =
to_add_monoid f (of A xi xv) * to_add_monoid f (of A yi yv),
rw [of_mul_of, to_add_monoid_of, to_add_monoid_of, to_add_monoid_of],
exact hmul _ _,
end,
.. to_add_monoid f}
@[simp] lemma to_semiring_of (f : Π i, A i →+ R) (hone hmul) (i : ι) (x : A i) :
to_semiring f hone hmul (of _ i x) = f _ x :=
to_add_monoid_of f i x
@[simp] lemma to_semiring_coe_add_monoid_hom (f : Π i, A i →+ R) (hone hmul):
(to_semiring f hone hmul : (⨁ i, A i) →+ R) = to_add_monoid f := rfl
/-- Families of `add_monoid_hom`s preserving `direct_sum.ghas_one.one` and `direct_sum.ghas_mul.mul`
are isomorphic to `ring_hom`s on `⨁ i, A i`. This is a stronger version of `dfinsupp.lift_add_hom`.
-/
@[simps]
def lift_ring_hom :
{f : Π {i}, A i →+ R //
f (graded_monoid.ghas_one.one) = 1 ∧
∀ {i j} (ai : A i) (aj : A j), f (graded_monoid.ghas_mul.mul ai aj) = f ai * f aj} ≃
((⨁ i, A i) →+* R) :=
{ to_fun := λ f, to_semiring (λ _, f.1) f.2.1 (λ _ _, f.2.2),
inv_fun := λ F,
⟨λ i, (F : (⨁ i, A i) →+ R).comp (of _ i), begin
simp only [add_monoid_hom.comp_apply, ring_hom.coe_add_monoid_hom],
rw ←F.map_one,
refl
end, λ i j ai aj, begin
simp only [add_monoid_hom.comp_apply, ring_hom.coe_add_monoid_hom],
rw [←F.map_mul, of_mul_of],
end⟩,
left_inv := λ f, begin
ext xi xv,
exact to_add_monoid_of (λ _, f.1) xi xv,
end,
right_inv := λ F, begin
apply ring_hom.coe_add_monoid_hom_injective,
ext xi xv,
simp only [ring_hom.coe_add_monoid_hom_mk,
direct_sum.to_add_monoid_of,
add_monoid_hom.mk_coe,
add_monoid_hom.comp_apply, to_semiring_coe_add_monoid_hom],
end}
end to_semiring
end direct_sum
/-! ### Concrete instances -/
section uniform
variables (ι)
/-- A direct sum of copies of a `semiring` inherits the multiplication structure. -/
instance non_unital_non_assoc_semiring.direct_sum_gnon_unital_non_assoc_semiring
{R : Type*} [add_monoid ι] [non_unital_non_assoc_semiring R] :
direct_sum.gnon_unital_non_assoc_semiring (λ i : ι, R) :=
{ mul_zero := λ i j, mul_zero,
zero_mul := λ i j, zero_mul,
mul_add := λ i j, mul_add,
add_mul := λ i j, add_mul,
..has_mul.ghas_mul ι }
/-- A direct sum of copies of a `semiring` inherits the multiplication structure. -/
instance semiring.direct_sum_gsemiring {R : Type*} [add_monoid ι] [semiring R] :
direct_sum.gsemiring (λ i : ι, R) :=
{ nat_cast := λ n, n,
nat_cast_zero := nat.cast_zero,
nat_cast_succ := nat.cast_succ,
..non_unital_non_assoc_semiring.direct_sum_gnon_unital_non_assoc_semiring ι,
..monoid.gmonoid ι }
open_locale direct_sum
-- To check `has_mul.ghas_mul_mul` matches
example {R : Type*} [add_monoid ι] [semiring R] (i j : ι) (a b : R) :
(direct_sum.of _ i a * direct_sum.of _ j b : ⨁ i, R) = direct_sum.of _ (i + j) (by exact a * b) :=
by rw [direct_sum.of_mul_of, has_mul.ghas_mul_mul]
/-- A direct sum of copies of a `comm_semiring` inherits the commutative multiplication structure.
-/
instance comm_semiring.direct_sum_gcomm_semiring {R : Type*} [add_comm_monoid ι] [comm_semiring R] :
direct_sum.gcomm_semiring (λ i : ι, R) :=
{ ..comm_monoid.gcomm_monoid ι, ..semiring.direct_sum_gsemiring ι }
end uniform
|
81cfe84c1b43e8050472b832269da6b3cd79ffbd | 02fbe05a45fda5abde7583464416db4366eedfbf | /library/init/core.lean | 6722205484867232ad29b2d6ae61225c8f166c57 | [
"Apache-2.0"
] | permissive | jasonrute/lean | cc12807e11f9ac6b01b8951a8bfb9c2eb35a0154 | 4be962c167ca442a0ec5e84472d7ff9f5302788f | refs/heads/master | 1,672,036,664,637 | 1,601,642,826,000 | 1,601,642,826,000 | 260,777,966 | 0 | 0 | Apache-2.0 | 1,588,454,819,000 | 1,588,454,818,000 | null | UTF-8 | Lean | false | false | 19,154 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
notation, basic datatypes and type classes
-/
prelude
notation `Prop` := Sort 0
notation f ` $ `:1 a:0 := f a
/- Reserving notation. We do this so that the precedence of all of the operators
can be seen in one place and to prevent core notation being accidentally overloaded later. -/
/- Notation for logical operations and relations -/
reserve prefix `¬`:40
reserve prefix `~`:40 -- not used
reserve infixr ` ∧ `:35
reserve infixr ` /\ `:35
reserve infixr ` \/ `:30
reserve infixr ` ∨ `:30
reserve infix ` <-> `:20
reserve infix ` ↔ `:20
reserve infix ` = `:50 -- eq
reserve infix ` == `:50 -- heq
reserve infix ` ≠ `:50
reserve infix ` ≈ `:50 -- has_equiv.equiv
reserve infix ` ~ `:50 -- used as local notation for relations
reserve infix ` ≡ `:50 -- not used
reserve infixl ` ⬝ `:75 -- not used
reserve infixr ` ▸ `:75 -- eq.subst
reserve infixr ` ▹ `:75 -- not used
/- types and type constructors -/
reserve infixr ` ⊕ `:30 -- sum (defined in init/data/sum/basic.lean)
reserve infixr ` × `:35
/- arithmetic operations -/
reserve infixl ` + `:65
reserve infixl ` - `:65
reserve infixl ` * `:70
reserve infixl ` / `:70
reserve infixl ` % `:70
reserve prefix `-`:75
reserve infixr ` ^ `:80
reserve infixr ` ∘ `:90 -- function composition
reserve infix ` <= `:50
reserve infix ` ≤ `:50
reserve infix ` < `:50
reserve infix ` >= `:50
reserve infix ` ≥ `:50
reserve infix ` > `:50
/- boolean operations -/
reserve infixl ` && `:70
reserve infixl ` || `:65
/- set operations -/
reserve infix ` ∈ `:50
reserve infix ` ∉ `:50
reserve infixl ` ∩ `:70
reserve infixl ` ∪ `:65
reserve infix ` ⊆ `:50
reserve infix ` ⊇ `:50
reserve infix ` ⊂ `:50
reserve infix ` ⊃ `:50
reserve infix ` \ `:70 -- symmetric difference
/- other symbols -/
reserve infix ` ∣ `:50 -- has_dvd.dvd. Note this is different to `|`.
reserve infixl ` ++ `:65 -- has_append.append
reserve infixr ` :: `:67 -- list.cons
reserve infixl `; `:1 -- has_andthen.andthen
universes u v w
/--
The kernel definitional equality test (t =?= s) has special support for id_delta applications.
It implements the following rules
1) (id_delta t) =?= t
2) t =?= (id_delta t)
3) (id_delta t) =?= s IF (unfold_of t) =?= s
4) t =?= id_delta s IF t =?= (unfold_of s)
This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel.
We use id_delta applications to address performance problems when type checking
lemmas generated by the equation compiler.
-/
@[inline] def id_delta {α : Sort u} (a : α) : α :=
a
/-- Gadget for optional parameter support. -/
@[reducible] def opt_param (α : Sort u) (default : α) : Sort u :=
α
/-- Gadget for marking output parameters in type classes. -/
@[reducible] def out_param (α : Sort u) : Sort u := α
/-
id_rhs is an auxiliary declaration used in the equation compiler to address performance
issues when proving equational lemmas. The equation compiler uses it as a marker.
-/
abbreviation id_rhs (α : Sort u) (a : α) : α := a
inductive punit : Sort u
| star : punit
/-- An abbreviation for `punit.{0}`, its most common instantiation.
This type should be preferred over `punit` where possible to avoid
unnecessary universe parameters. -/
abbreviation unit : Type := punit
@[pattern] abbreviation unit.star : unit := punit.star
/--
Gadget for defining thunks, thunk parameters have special treatment.
Example: given
def f (s : string) (t : thunk nat) : nat
an application
f "hello" 10
is converted into
f "hello" (λ _, 10)
-/
@[reducible] def thunk (α : Type u) : Type u :=
unit → α
inductive true : Prop
| intro : true
inductive false : Prop
inductive empty : Type
/-- `not P`, with notation `¬ P`, is the `Prop` which is true if and only if `P` is false. It is
internally represented as `P → false`. -/
def not (a : Prop) := a → false
prefix `¬` := not
inductive eq {α : Sort u} (a : α) : α → Prop
| refl [] : eq a
/-
Initialize the quotient module, which effectively adds the following definitions:
constant quot {α : Sort u} (r : α → α → Prop) : Sort u
constant quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : quot r
constant quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) :
(∀ a b : α, r a b → eq (f a) (f b)) → quot r → β
constant quot.ind {α : Sort u} {r : α → α → Prop} {β : quot r → Prop} :
(∀ a : α, β (quot.mk r a)) → ∀ q : quot r, β q
Also the reduction rule:
quot.lift f _ (quot.mk a) ~~> f a
-/
init_quotient
/-- Heterogeneous equality.
It's purpose is to write down equalities between terms whose types are not definitionally equal.
For example, given `x : vector α n` and `y : vector α (0+n)`, `x = y` doesn't typecheck but `x == y` does.
-/
inductive heq {α : Sort u} (a : α) : Π {β : Sort u}, β → Prop
| refl [] : heq a
structure prod (α : Type u) (β : Type v) :=
(fst : α) (snd : β)
/-- Similar to `prod`, but α and β can be propositions.
We use this type internally to automatically generate the brec_on recursor. -/
structure pprod (α : Sort u) (β : Sort v) :=
(fst : α) (snd : β)
/-- `and P Q`, with notation `P ∧ Q`, is the `Prop` which is true precisely when `P` and `Q` are
both true. -/
structure and (a b : Prop) : Prop :=
intro :: (left : a) (right : b)
def and.elim_left {a b : Prop} (h : and a b) : a := h.1
def and.elim_right {a b : Prop} (h : and a b) : b := h.2
/- eq basic support -/
infix = := eq
attribute [refl] eq.refl
@[pattern] def rfl {α : Sort u} {a : α} : a = a := eq.refl a
@[elab_as_eliminator, subst]
lemma eq.subst {α : Sort u} {P : α → Prop} {a b : α} (h₁ : a = b) (h₂ : P a) : P b :=
eq.rec h₂ h₁
notation h1 ▸ h2 := eq.subst h1 h2
@[trans] lemma eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c :=
h₂ ▸ h₁
@[symm] lemma eq.symm {α : Sort u} {a b : α} (h : a = b) : b = a :=
h ▸ rfl
infix == := heq
@[pattern] def heq.rfl {α : Sort u} {a : α} : a == a := heq.refl a
lemma eq_of_heq {α : Sort u} {a a' : α} (h : a == a') : a = a' :=
have ∀ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a') (h₂ : α = α'), (eq.rec_on h₂ a : α') = a', from
λ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a'), heq.rec_on h₁ (λ h₂ : α = α, rfl),
show (eq.rec_on (eq.refl α) a : α) = a', from
this α a' h (eq.refl α)
/- The following four lemmas could not be automatically generated when the
structures were declared, so we prove them manually here. -/
lemma prod.mk.inj {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: (x₁, y₁) = (x₂, y₂) → and (x₁ = x₂) (y₁ = y₂) :=
λ h, prod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩)
lemma prod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P :=
λ h₁ _ h₂, prod.no_confusion h₁ h₂
lemma pprod.mk.inj {α : Sort u} {β : Sort v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: pprod.mk x₁ y₁ = pprod.mk x₂ y₂ → and (x₁ = x₂) (y₁ = y₂) :=
λ h, pprod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩)
lemma pprod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P :=
λ h₁ _ h₂, prod.no_confusion h₁ h₂
inductive sum (α : Type u) (β : Type v)
| inl (val : α) : sum
| inr (val : β) : sum
inductive psum (α : Sort u) (β : Sort v)
| inl (val : α) : psum
| inr (val : β) : psum
/-- `or P Q`, with notation `P ∨ Q`, is the proposition which is true if and only if `P` or `Q` is
true. -/
inductive or (a b : Prop) : Prop
| inl (h : a) : or
| inr (h : b) : or
def or.intro_left {a : Prop} (b : Prop) (ha : a) : or a b :=
or.inl ha
def or.intro_right (a : Prop) {b : Prop} (hb : b) : or a b :=
or.inr hb
structure sigma {α : Type u} (β : α → Type v) :=
mk :: (fst : α) (snd : β fst)
structure psigma {α : Sort u} (β : α → Sort v) :=
mk :: (fst : α) (snd : β fst)
inductive bool : Type
| ff : bool
| tt : bool
/- Remark: subtype must take a Sort instead of Type because of the axiom strong_indefinite_description. -/
structure subtype {α : Sort u} (p : α → Prop) :=
(val : α) (property : p val)
attribute [pp_using_anonymous_constructor] sigma psigma subtype pprod and
class inductive decidable (p : Prop)
| is_false (h : ¬p) : decidable
| is_true (h : p) : decidable
@[reducible]
def decidable_pred {α : Sort u} (r : α → Prop) :=
Π (a : α), decidable (r a)
@[reducible]
def decidable_rel {α : Sort u} (r : α → α → Prop) :=
Π (a b : α), decidable (r a b)
@[reducible]
def decidable_eq (α : Sort u) :=
decidable_rel (@eq α)
inductive option (α : Type u)
| none : option
| some (val : α) : option
export option (none some)
export bool (ff tt)
inductive list (T : Type u)
| nil : list
| cons (hd : T) (tl : list) : list
notation h :: t := list.cons h t
notation `[` l:(foldr `, ` (h t, list.cons h t) list.nil `]`) := l
inductive nat
| zero : nat
| succ (n : nat) : nat
structure unification_constraint :=
{α : Type u} (lhs : α) (rhs : α)
infix ` ≟ `:50 := unification_constraint.mk
infix ` =?= `:50 := unification_constraint.mk
structure unification_hint :=
(pattern : unification_constraint)
(constraints : list unification_constraint)
/- Declare builtin and reserved notation -/
class has_zero (α : Type u) := (zero : α)
class has_one (α : Type u) := (one : α)
class has_add (α : Type u) := (add : α → α → α)
class has_mul (α : Type u) := (mul : α → α → α)
class has_inv (α : Type u) := (inv : α → α)
class has_neg (α : Type u) := (neg : α → α)
class has_sub (α : Type u) := (sub : α → α → α)
class has_div (α : Type u) := (div : α → α → α)
class has_dvd (α : Type u) := (dvd : α → α → Prop)
class has_mod (α : Type u) := (mod : α → α → α)
class has_le (α : Type u) := (le : α → α → Prop)
class has_lt (α : Type u) := (lt : α → α → Prop)
class has_append (α : Type u) := (append : α → α → α)
class has_andthen (α : Type u) (β : Type v) (σ : out_param $ Type w) := (andthen : α → β → σ)
class has_union (α : Type u) := (union : α → α → α)
class has_inter (α : Type u) := (inter : α → α → α)
class has_sdiff (α : Type u) := (sdiff : α → α → α)
class has_equiv (α : Sort u) := (equiv : α → α → Prop)
class has_subset (α : Type u) := (subset : α → α → Prop)
class has_ssubset (α : Type u) := (ssubset : α → α → Prop)
/- Type classes has_emptyc and has_insert are
used to implement polymorphic notation for collections.
Example: {a, b, c}. -/
class has_emptyc (α : Type u) := (emptyc : α)
class has_insert (α : out_param $ Type u) (γ : Type v) := (insert : α → γ → γ)
class has_singleton (α : out_param $ Type u) (β : Type v) := (singleton : α → β)
/- Type class used to implement the notation { a ∈ c | p a } -/
class has_sep (α : out_param $ Type u) (γ : Type v) :=
(sep : (α → Prop) → γ → γ)
/- Type class for set-like membership -/
class has_mem (α : out_param $ Type u) (γ : Type v) := (mem : α → γ → Prop)
class has_pow (α : Type u) (β : Type v) :=
(pow : α → β → α)
export has_andthen (andthen)
export has_pow (pow)
infix ∈ := has_mem.mem
notation a ∉ s := ¬ has_mem.mem a s
infix + := has_add.add
infix * := has_mul.mul
infix - := has_sub.sub
infix / := has_div.div
infix ∣ := has_dvd.dvd
infix % := has_mod.mod
prefix - := has_neg.neg
infix <= := has_le.le
infix ≤ := has_le.le
infix < := has_lt.lt
infix ++ := has_append.append
infix ; := andthen
notation `∅` := has_emptyc.emptyc
infix ∪ := has_union.union
infix ∩ := has_inter.inter
infix ⊆ := has_subset.subset
infix ⊂ := has_ssubset.ssubset
infix \ := has_sdiff.sdiff
infix ≈ := has_equiv.equiv
infixr ^ := has_pow.pow
export has_append (append)
@[reducible] def ge {α : Type u} [has_le α] (a b : α) : Prop := has_le.le b a
@[reducible] def gt {α : Type u} [has_lt α] (a b : α) : Prop := has_lt.lt b a
infix >= := ge
infix ≥ := ge
infix > := gt
@[reducible] def superset {α : Type u} [has_subset α] (a b : α) : Prop := has_subset.subset b a
@[reducible] def ssuperset {α : Type u} [has_ssubset α] (a b : α) : Prop := has_ssubset.ssubset b a
infix ⊇ := superset
infix ⊃ := ssuperset
def bit0 {α : Type u} [s : has_add α] (a : α) : α := a + a
def bit1 {α : Type u} [s₁ : has_one α] [s₂ : has_add α] (a : α) : α := (bit0 a) + 1
attribute [pattern] has_zero.zero has_one.one bit0 bit1 has_add.add has_neg.neg
export has_insert (insert)
class is_lawful_singleton (α : Type u) (β : Type v) [has_emptyc β] [has_insert α β]
[has_singleton α β] :=
(insert_emptyc_eq : ∀ (x : α), (insert x ∅ : β) = {x})
export has_singleton (singleton)
export is_lawful_singleton (insert_emptyc_eq)
attribute [simp] insert_emptyc_eq
/- nat basic instances -/
namespace nat
protected def add : nat → nat → nat
| a zero := a
| a (succ b) := succ (add a b)
/- We mark the following definitions as pattern to make sure they can be used in recursive equations,
and reduced by the equation compiler. -/
attribute [pattern] nat.add nat.add._main
end nat
instance : has_zero nat := ⟨nat.zero⟩
instance : has_one nat := ⟨nat.succ (nat.zero)⟩
instance : has_add nat := ⟨nat.add⟩
def std.priority.default : nat := 1000
def std.priority.max : nat := 0xFFFFFFFF
namespace nat
protected def prio := std.priority.default + 100
end nat
/-
Global declarations of right binding strength
If a module reassigns these, it will be incompatible with other modules that adhere to these
conventions.
When hovering over a symbol, use "C-c C-k" to see how to input it.
-/
def std.prec.max : nat := 1024 -- the strength of application, identifiers, (, [, etc.
def std.prec.arrow : nat := 25
/-
The next def is "max + 10". It can be used e.g. for postfix operations that should
be stronger than application.
-/
def std.prec.max_plus : nat := std.prec.max + 10
reserve postfix `⁻¹`:std.prec.max_plus -- input with \sy or \-1 or \inv
postfix ⁻¹ := has_inv.inv
notation α × β := prod α β
-- notation for n-ary tuples
/- sizeof -/
class has_sizeof (α : Sort u) :=
(sizeof : α → nat)
def sizeof {α : Sort u} [s : has_sizeof α] : α → nat :=
has_sizeof.sizeof
/-
Declare sizeof instances and lemmas for types declared before has_sizeof.
From now on, the inductive compiler will automatically generate sizeof instances and lemmas.
-/
/- Every type `α` has a default has_sizeof instance that just returns 0 for every element of `α` -/
protected def default.sizeof (α : Sort u) : α → nat
| a := 0
instance default_has_sizeof (α : Sort u) : has_sizeof α :=
⟨default.sizeof α⟩
protected def nat.sizeof : nat → nat
| n := n
instance : has_sizeof nat :=
⟨nat.sizeof⟩
protected def prod.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (prod α β) → nat
| ⟨a, b⟩ := 1 + sizeof a + sizeof b
instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (prod α β) :=
⟨prod.sizeof⟩
protected def sum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (sum α β) → nat
| (sum.inl a) := 1 + sizeof a
| (sum.inr b) := 1 + sizeof b
instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (sum α β) :=
⟨sum.sizeof⟩
protected def psum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (psum α β) → nat
| (psum.inl a) := 1 + sizeof a
| (psum.inr b) := 1 + sizeof b
instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (psum α β) :=
⟨psum.sizeof⟩
protected def sigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : sigma β → nat
| ⟨a, b⟩ := 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (sigma β) :=
⟨sigma.sizeof⟩
protected def psigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : psigma β → nat
| ⟨a, b⟩ := 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (psigma β) :=
⟨psigma.sizeof⟩
protected def punit.sizeof : punit → nat
| u := 1
instance : has_sizeof punit := ⟨punit.sizeof⟩
protected def bool.sizeof : bool → nat
| b := 1
instance : has_sizeof bool := ⟨bool.sizeof⟩
protected def option.sizeof {α : Type u} [has_sizeof α] : option α → nat
| none := 1
| (some a) := 1 + sizeof a
instance (α : Type u) [has_sizeof α] : has_sizeof (option α) :=
⟨option.sizeof⟩
protected def list.sizeof {α : Type u} [has_sizeof α] : list α → nat
| list.nil := 1
| (list.cons a l) := 1 + sizeof a + list.sizeof l
instance (α : Type u) [has_sizeof α] : has_sizeof (list α) :=
⟨list.sizeof⟩
protected def subtype.sizeof {α : Type u} [has_sizeof α] {p : α → Prop} : subtype p → nat
| ⟨a, _⟩ := sizeof a
instance {α : Type u} [has_sizeof α] (p : α → Prop) : has_sizeof (subtype p) :=
⟨subtype.sizeof⟩
lemma nat_add_zero (n : nat) : n + 0 = n := rfl
/- Combinator calculus -/
namespace combinator
universes u₁ u₂ u₃
def I {α : Type u₁} (a : α) := a
def K {α : Type u₁} {β : Type u₂} (a : α) (b : β) := a
def S {α : Type u₁} {β : Type u₂} {γ : Type u₃} (x : α → β → γ) (y : α → β) (z : α) := x z (y z)
end combinator
/-- Auxiliary datatype for #[ ... ] notation.
#[1, 2, 3, 4] is notation for
bin_tree.node
(bin_tree.node (bin_tree.leaf 1) (bin_tree.leaf 2))
(bin_tree.node (bin_tree.leaf 3) (bin_tree.leaf 4))
We use this notation to input long sequences without exhausting the system stack space.
Later, we define a coercion from `bin_tree` into `list`.
-/
inductive bin_tree (α : Type u)
| empty : bin_tree
| leaf (val : α) : bin_tree
| node (left right : bin_tree) : bin_tree
attribute [elab_simple] bin_tree.node bin_tree.leaf
/- Basic unification hints -/
@[unify] def add_succ_defeq_succ_add_hint (x y z : nat) : unification_hint :=
{ pattern := x + nat.succ y ≟ nat.succ z,
constraints := [z ≟ x + y] }
/-- Like `by apply_instance`, but not dependent on the tactic framework. -/
@[reducible] def infer_instance {α : Type u} [i : α] : α := i
|
b28da2851f0b0121ec34c74e4642839e8441b85f | 4727251e0cd73359b15b664c3170e5d754078599 | /src/linear_algebra/std_basis.lean | 152612e47dd6d988b1bb3d257ff98498b18fd8fa | [
"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,744 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import data.matrix.basis
import linear_algebra.basis
import linear_algebra.pi
/-!
# The standard basis
This file defines the standard basis `pi.basis (s : ∀ j, basis (ι j) R (M j))`,
which is the `Σ j, ι j`-indexed basis of Π j, M j`. The basis vectors are given by
`pi.basis s ⟨j, i⟩ j' = linear_map.std_basis R M j' (s j) i = if j = j' then s i else 0`.
The standard basis on `R^η`, i.e. `η → R` is called `pi.basis_fun`.
To give a concrete example, `linear_map.std_basis R (λ (i : fin 3), R) i 1`
gives the `i`th unit basis vector in `R³`, and `pi.basis_fun R (fin 3)` proves
this is a basis over `fin 3 → R`.
## Main definitions
- `linear_map.std_basis R M`: if `x` is a basis vector of `M i`, then
`linear_map.std_basis R M i x` is the `i`th standard basis vector of `Π i, M i`.
- `pi.basis s`: given a basis `s i` for each `M i`, the standard basis on `Π i, M i`
- `pi.basis_fun R η`: the standard basis on `R^η`, i.e. `η → R`, given by
`pi.basis_fun R η i j = if i = j then 1 else 0`.
- `matrix.std_basis R n m`: the standard basis on `matrix n m R`, given by
`matrix.std_basis R n m (i, j) i' j' = if (i, j) = (i', j') then 1 else 0`.
-/
open function submodule
open_locale big_operators
open_locale big_operators
namespace linear_map
variables (R : Type*) {ι : Type*} [semiring R] (φ : ι → Type*)
[Π i, add_comm_monoid (φ i)] [Π i, module R (φ i)] [decidable_eq ι]
/-- The standard basis of the product of `φ`. -/
def std_basis : Π (i : ι), φ i →ₗ[R] (Πi, φ i) := single
lemma std_basis_apply (i : ι) (b : φ i) : std_basis R φ i b = update 0 i b :=
rfl
lemma coe_std_basis (i : ι) : ⇑(std_basis R φ i) = pi.single i :=
funext $ std_basis_apply R φ i
@[simp] lemma std_basis_same (i : ι) (b : φ i) : std_basis R φ i b i = b :=
by rw [std_basis_apply, update_same]
lemma std_basis_ne (i j : ι) (h : j ≠ i) (b : φ i) : std_basis R φ i b j = 0 :=
by rw [std_basis_apply, update_noteq h]; refl
lemma std_basis_eq_pi_diag (i : ι) : std_basis R φ i = pi (diag i) :=
begin
ext x j,
convert (update_apply 0 x i j _).symm,
refl,
end
lemma ker_std_basis (i : ι) : ker (std_basis R φ i) = ⊥ :=
ker_eq_bot_of_injective $ assume f g hfg,
have std_basis R φ i f i = std_basis R φ i g i := hfg ▸ rfl,
by simpa only [std_basis_same]
lemma proj_comp_std_basis (i j : ι) : (proj i).comp (std_basis R φ j) = diag j i :=
by rw [std_basis_eq_pi_diag, proj_pi]
lemma proj_std_basis_same (i : ι) : (proj i).comp (std_basis R φ i) = id :=
by ext b; simp
lemma proj_std_basis_ne (i j : ι) (h : i ≠ j) : (proj i).comp (std_basis R φ j) = 0 :=
by ext b; simp [std_basis_ne R φ _ _ h]
lemma supr_range_std_basis_le_infi_ker_proj (I J : set ι) (h : disjoint I J) :
(⨆i∈I, range (std_basis R φ i)) ≤ (⨅i∈J, ker (proj i)) :=
begin
refine (supr_le $ λ i, supr_le $ λ hi, range_le_iff_comap.2 _),
simp only [(ker_comp _ _).symm, eq_top_iff, set_like.le_def, mem_ker, comap_infi, mem_infi],
rintro b - j hj,
rw [proj_std_basis_ne R φ j i, zero_apply],
rintro rfl,
exact h ⟨hi, hj⟩
end
lemma infi_ker_proj_le_supr_range_std_basis {I : finset ι} {J : set ι} (hu : set.univ ⊆ ↑I ∪ J) :
(⨅ i∈J, ker (proj i)) ≤ (⨆i∈I, range (std_basis R φ i)) :=
set_like.le_def.2
begin
assume b hb,
simp only [mem_infi, mem_ker, proj_apply] at hb,
rw ← show ∑ i in I, std_basis R φ i (b i) = b,
{ ext i,
rw [finset.sum_apply, ← std_basis_same R φ i (b i)],
refine finset.sum_eq_single i (assume j hjI ne, std_basis_ne _ _ _ _ ne.symm _) _,
assume hiI,
rw [std_basis_same],
exact hb _ ((hu trivial).resolve_left hiI) },
exact sum_mem (assume i hiI, mem_supr_of_mem i $ mem_supr_of_mem hiI $
(std_basis R φ i).mem_range_self (b i))
end
lemma supr_range_std_basis_eq_infi_ker_proj {I J : set ι}
(hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) (hI : set.finite I) :
(⨆i∈I, range (std_basis R φ i)) = (⨅i∈J, ker (proj i)) :=
begin
refine le_antisymm (supr_range_std_basis_le_infi_ker_proj _ _ _ _ hd) _,
have : set.univ ⊆ ↑hI.to_finset ∪ J, { rwa [hI.coe_to_finset] },
refine le_trans (infi_ker_proj_le_supr_range_std_basis R φ this) (supr_mono $ assume i, _),
rw [set.finite.mem_to_finset],
exact le_rfl
end
lemma supr_range_std_basis [fintype ι] : (⨆i:ι, range (std_basis R φ i)) = ⊤ :=
have (set.univ : set ι) ⊆ ↑(finset.univ : finset ι) ∪ ∅ := by rw [finset.coe_univ, set.union_empty],
begin
apply top_unique,
convert (infi_ker_proj_le_supr_range_std_basis R φ this),
exact infi_emptyset.symm,
exact (funext $ λi, (@supr_pos _ _ _ (λh, range (std_basis R φ i)) $ finset.mem_univ i).symm)
end
lemma disjoint_std_basis_std_basis (I J : set ι) (h : disjoint I J) :
disjoint (⨆i∈I, range (std_basis R φ i)) (⨆i∈J, range (std_basis R φ i)) :=
begin
refine disjoint.mono
(supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ disjoint_compl_right)
(supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ disjoint_compl_right) _,
simp only [disjoint, set_like.le_def, mem_infi, mem_inf, mem_ker, mem_bot, proj_apply,
funext_iff],
rintros b ⟨hI, hJ⟩ i,
classical,
by_cases hiI : i ∈ I,
{ by_cases hiJ : i ∈ J,
{ exact (h ⟨hiI, hiJ⟩).elim },
{ exact hJ i hiJ } },
{ exact hI i hiI }
end
lemma std_basis_eq_single {a : R} :
(λ (i : ι), (std_basis R (λ _ : ι, R) i) a) = λ (i : ι), (finsupp.single i a) :=
begin
ext i j,
rw [std_basis_apply, finsupp.single_apply],
split_ifs,
{ rw [h, function.update_same] },
{ rw [function.update_noteq (ne.symm h)], refl },
end
end linear_map
namespace pi
open linear_map
open set
variables {R : Type*}
section module
variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*}
lemma linear_independent_std_basis [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)]
[decidable_eq η] (v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) :
linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) :=
begin
have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)),
{ intro j,
exact (hs j).map' _ (ker_std_basis _ _ _) },
apply linear_independent_Union_finite hs',
{ assume j J _ hiJ,
simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union],
have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))
≤ range (std_basis R Ms j),
{ intro j,
rw [span_le, linear_map.range_coe],
apply range_comp_subset_range },
have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))
≤ ⨆ i ∈ {j}, range (std_basis R Ms i),
{ rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)),
apply h₀ },
have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤
⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) :=
supr₂_mono (λ i _, h₀ i),
have h₃ : disjoint (λ (i : η), i ∈ {j}) J,
{ convert set.disjoint_singleton_left.2 hiJ using 0 },
exact (disjoint_std_basis_std_basis _ _ _ _ h₃).mono h₁ h₂ }
end
variables [semiring R] [∀i, add_comm_monoid (Ms i)] [∀i, module R (Ms i)]
variable [fintype η]
section
open linear_equiv
/-- `pi.basis (s : ∀ j, basis (ιs j) R (Ms j))` is the `Σ j, ιs j`-indexed basis on `Π j, Ms j`
given by `s j` on each component. -/
protected noncomputable def basis (s : ∀ j, basis (ιs j) R (Ms j)) :
basis (Σ j, ιs j) R (Π j, Ms j) :=
-- The `add_comm_monoid (Π j, Ms j)` instance was hard to find.
-- Defining this in tactic mode seems to shake up instance search enough that it works by itself.
by { refine basis.of_repr (_ ≪≫ₗ (finsupp.sigma_finsupp_lequiv_pi_finsupp R).symm),
exact linear_equiv.Pi_congr_right (λ j, (s j).repr) }
@[simp] lemma basis_repr_std_basis [decidable_eq η] (s : ∀ j, basis (ιs j) R (Ms j)) (j i) :
(pi.basis s).repr (std_basis R _ j (s j i)) = finsupp.single ⟨j, i⟩ 1 :=
begin
ext ⟨j', i'⟩,
by_cases hj : j = j',
{ subst hj,
simp only [pi.basis, linear_equiv.trans_apply, basis.repr_self, std_basis_same,
linear_equiv.Pi_congr_right_apply, finsupp.sigma_finsupp_lequiv_pi_finsupp_symm_apply],
symmetry,
exact basis.finsupp.single_apply_left
(λ i i' (h : (⟨j, i⟩ : Σ j, ιs j) = ⟨j, i'⟩), eq_of_heq (sigma.mk.inj h).2) _ _ _ },
simp only [pi.basis, linear_equiv.trans_apply, finsupp.sigma_finsupp_lequiv_pi_finsupp_symm_apply,
linear_equiv.Pi_congr_right_apply],
dsimp,
rw [std_basis_ne _ _ _ _ (ne.symm hj), linear_equiv.map_zero, finsupp.zero_apply,
finsupp.single_eq_of_ne],
rintros ⟨⟩,
contradiction
end
@[simp] lemma basis_apply [decidable_eq η] (s : ∀ j, basis (ιs j) R (Ms j)) (ji) :
pi.basis s ji = std_basis R _ ji.1 (s ji.1 ji.2) :=
basis.apply_eq_iff.mpr (by simp)
@[simp] lemma basis_repr (s : ∀ j, basis (ιs j) R (Ms j)) (x) (ji) :
(pi.basis s).repr x ji = (s ji.1).repr (x ji.1) ji.2 :=
rfl
end
section
variables (R η)
/-- The basis on `η → R` where the `i`th basis vector is `function.update 0 i 1`. -/
noncomputable def basis_fun : basis η R (Π (j : η), R) :=
basis.of_equiv_fun (linear_equiv.refl _ _)
@[simp] lemma basis_fun_apply [decidable_eq η] (i) :
basis_fun R η i = std_basis R (λ (i : η), R) i 1 :=
by { simp only [basis_fun, basis.coe_of_equiv_fun, linear_equiv.refl_symm,
linear_equiv.refl_apply, std_basis_apply],
congr /- Get rid of a `decidable_eq` mismatch. -/ }
@[simp] lemma basis_fun_repr (x : η → R) (i : η) :
(pi.basis_fun R η).repr x i = x i :=
by simp [basis_fun]
end
end module
end pi
namespace matrix
variables (R : Type*) (m n : Type*) [fintype m] [fintype n] [semiring R]
/-- The standard basis of `matrix m n R`. -/
noncomputable def std_basis : basis (m × n) R (matrix m n R) :=
basis.reindex (pi.basis (λ (i : m), pi.basis_fun R n)) (equiv.sigma_equiv_prod _ _)
variables {n m}
lemma std_basis_eq_std_basis_matrix (i : n) (j : m) [decidable_eq n] [decidable_eq m] :
std_basis R n m (i, j) = std_basis_matrix i j (1 : R) :=
begin
ext a b,
by_cases hi : i = a; by_cases hj : j = b,
{ simp [std_basis, hi, hj] },
{ simp [std_basis, hi, hj, ne.symm hj, linear_map.std_basis_ne] },
{ simp [std_basis, hi, hj, ne.symm hi, linear_map.std_basis_ne] },
{ simp [std_basis, hi, hj, ne.symm hj, ne.symm hi, linear_map.std_basis_ne] }
end
end matrix
|
d1b453ea87492546e40e240ece0553bf951be7eb | a19a4fce1e5677f4d20cbfdf60c04b6386ab8210 | /hott/init/nat.hlean | 497a179798bafb988cce8695f13a14129ca956fb | [
"Apache-2.0"
] | permissive | nthomas103/lean | 9c341a316e7d9faa00546462f90a8aa402e17eac | 04eaf184a92606a56e54d0d6c8d59437557263fc | refs/heads/master | 1,586,061,106,806 | 1,454,640,115,000 | 1,454,641,279,000 | 51,127,143 | 0 | 0 | null | 1,454,648,683,000 | 1,454,648,683,000 | null | UTF-8 | Lean | false | false | 10,588 | hlean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Leonardo de Moura
-/
prelude
import init.wf init.tactic init.num init.types init.path
open eq eq.ops decidable
open algebra sum
set_option class.force_new true
notation `ℕ` := nat
namespace nat
protected definition rec_on [reducible] [recursor] [unfold 2]
{C : ℕ → Type} (n : ℕ) (H₁ : C 0) (H₂ : Π (a : ℕ), C a → C (succ a)) : C n :=
nat.rec H₁ H₂ n
protected definition cases_on [reducible] [recursor] [unfold 2]
{C : ℕ → Type} (n : ℕ) (H₁ : C 0) (H₂ : Π (a : ℕ), C (succ a)) : C n :=
nat.rec H₁ (λ a ih, H₂ a) n
protected definition no_confusion_type.{u} [reducible] (P : Type.{u}) (v₁ v₂ : ℕ) : Type.{u} :=
nat.rec
(nat.rec
(P → lift P)
(λ a₂ ih, lift P)
v₂)
(λ a₁ ih, nat.rec
(lift P)
(λ a₂ ih, (a₁ = a₂ → P) → lift P)
v₂)
v₁
protected definition no_confusion [reducible] [unfold 4]
{P : Type} {v₁ v₂ : ℕ} (H : v₁ = v₂) : nat.no_confusion_type P v₁ v₂ :=
eq.rec (λ H₁ : v₁ = v₁, nat.rec (λ h, lift.up h) (λ a ih h, lift.up (h (eq.refl a))) v₁) H H
/- basic definitions on natural numbers -/
inductive le (a : ℕ) : ℕ → Type :=
| nat_refl : le a a -- use nat_refl to avoid overloading le.refl
| step : Π {b}, le a b → le a (succ b)
definition nat_has_le [instance] [reducible] [priority nat.prio]: has_le nat := has_le.mk nat.le
protected definition le_refl [refl] : Π a : nat, a ≤ a :=
le.nat_refl
protected definition lt [reducible] (n m : ℕ) := succ n ≤ m
definition nat_has_lt [instance] [reducible] [priority nat.prio] : has_lt nat := has_lt.mk nat.lt
definition pred [unfold 1] (a : nat) : nat :=
nat.cases_on a zero (λ a₁, a₁)
-- add is defined in init.reserved_notation
protected definition sub (a b : nat) : nat :=
nat.rec_on b a (λ b₁, pred)
protected definition mul (a b : nat) : nat :=
nat.rec_on b zero (λ b₁ r, r + a)
definition nat_has_sub [instance] [reducible] [priority nat.prio] : has_sub nat :=
has_sub.mk nat.sub
definition nat_has_mul [instance] [reducible] [priority nat.prio] : has_mul nat :=
has_mul.mk nat.mul
/- properties of ℕ -/
protected definition is_inhabited [instance] : inhabited nat :=
inhabited.mk zero
protected definition has_decidable_eq [instance] [priority nat.prio] : Π x y : nat, decidable (x = y)
| has_decidable_eq zero zero := inl rfl
| has_decidable_eq (succ x) zero := inr (by contradiction)
| has_decidable_eq zero (succ y) := inr (by contradiction)
| has_decidable_eq (succ x) (succ y) :=
match has_decidable_eq x y with
| inl xeqy := inl (by rewrite xeqy)
| inr xney := inr (λ h : succ x = succ y, by injection h with xeqy; exact absurd xeqy xney)
end
/- properties of inequality -/
protected definition le_of_eq {n m : ℕ} (p : n = m) : n ≤ m := p ▸ !nat.le_refl
definition le_succ (n : ℕ) : n ≤ succ n := le.step !nat.le_refl
definition pred_le (n : ℕ) : pred n ≤ n := by cases n;repeat constructor
definition le_succ_iff_unit [simp] (n : ℕ) : n ≤ succ n ↔ unit :=
iff_unit_intro (le_succ n)
definition pred_le_iff_unit [simp] (n : ℕ) : pred n ≤ n ↔ unit :=
iff_unit_intro (pred_le n)
protected definition le_trans {n m k : ℕ} (H1 : n ≤ m) : m ≤ k → n ≤ k :=
le.rec H1 (λp H2, le.step)
definition le_succ_of_le {n m : ℕ} (H : n ≤ m) : n ≤ succ m := nat.le_trans H !le_succ
definition le_of_succ_le {n m : ℕ} (H : succ n ≤ m) : n ≤ m := nat.le_trans !le_succ H
protected definition le_of_lt {n m : ℕ} (H : n < m) : n ≤ m := le_of_succ_le H
definition succ_le_succ {n m : ℕ} : n ≤ m → succ n ≤ succ m :=
le.rec !nat.le_refl (λa b, le.step)
theorem pred_le_pred {n m : ℕ} : n ≤ m → pred n ≤ pred m :=
le.rec !nat.le_refl (nat.rec (λa b, b) (λa b c, le.step))
theorem le_of_succ_le_succ {n m : ℕ} : succ n ≤ succ m → n ≤ m :=
pred_le_pred
theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m :=
nat.cases_on n le.step (λa, succ_le_succ)
theorem not_succ_le_zero (n : ℕ) : ¬succ n ≤ 0 :=
by intro H; cases H
theorem succ_le_zero_iff_empty (n : ℕ) : succ n ≤ 0 ↔ empty :=
iff_empty_intro !not_succ_le_zero
theorem not_succ_le_self : Π {n : ℕ}, ¬succ n ≤ n :=
nat.rec !not_succ_le_zero (λa b c, b (le_of_succ_le_succ c))
theorem succ_le_self_iff_empty [simp] (n : ℕ) : succ n ≤ n ↔ empty :=
iff_empty_intro not_succ_le_self
definition zero_le : Π (n : ℕ), 0 ≤ n :=
nat.rec !nat.le_refl (λa, le.step)
theorem zero_le_iff_unit [simp] (n : ℕ) : 0 ≤ n ↔ unit :=
iff_unit_intro !zero_le
theorem lt.step {n m : ℕ} : n < m → n < succ m := le.step
theorem zero_lt_succ (n : ℕ) : 0 < succ n :=
succ_le_succ !zero_le
theorem zero_lt_succ_iff_unit [simp] (n : ℕ) : 0 < succ n ↔ unit :=
iff_unit_intro (zero_lt_succ n)
protected theorem lt_trans {n m k : ℕ} (H1 : n < m) : m < k → n < k :=
nat.le_trans (le.step H1)
protected theorem lt_of_le_of_lt {n m k : ℕ} (H1 : n ≤ m) : m < k → n < k :=
nat.le_trans (succ_le_succ H1)
protected theorem lt_of_lt_of_le {n m k : ℕ} : n < m → m ≤ k → n < k := nat.le_trans
protected theorem lt_irrefl (n : ℕ) : ¬n < n := not_succ_le_self
theorem lt_self_iff_empty (n : ℕ) : n < n ↔ empty :=
iff_empty_intro (λ H, absurd H (nat.lt_irrefl n))
theorem self_lt_succ (n : ℕ) : n < succ n := !nat.le_refl
theorem self_lt_succ_iff_unit [simp] (n : ℕ) : n < succ n ↔ unit :=
iff_unit_intro (self_lt_succ n)
theorem lt.base (n : ℕ) : n < succ n := !nat.le_refl
theorem le_lt_antisymm {n m : ℕ} (H1 : n ≤ m) (H2 : m < n) : empty :=
!nat.lt_irrefl (nat.lt_of_le_of_lt H1 H2)
protected theorem le_antisymm {n m : ℕ} (H1 : n ≤ m) : m ≤ n → n = m :=
le.cases_on H1 (λa, rfl) (λa b c, absurd (nat.lt_of_le_of_lt b c) !nat.lt_irrefl)
theorem lt_le_antisymm {n m : ℕ} (H1 : n < m) (H2 : m ≤ n) : empty :=
le_lt_antisymm H2 H1
protected theorem nat.lt_asymm {n m : ℕ} (H1 : n < m) : ¬ m < n :=
le_lt_antisymm (nat.le_of_lt H1)
theorem not_lt_zero (a : ℕ) : ¬ a < 0 := !not_succ_le_zero
theorem lt_zero_iff_empty [simp] (a : ℕ) : a < 0 ↔ empty :=
iff_empty_intro (not_lt_zero a)
protected theorem eq_sum_lt_of_le {a b : ℕ} (H : a ≤ b) : a = b ⊎ a < b :=
le.cases_on H (inl rfl) (λn h, inr (succ_le_succ h))
protected theorem le_of_eq_sum_lt {a b : ℕ} (H : a = b ⊎ a < b) : a ≤ b :=
sum.rec_on H !nat.le_of_eq !nat.le_of_lt
-- less-than is well-founded
definition lt.wf [instance] : well_founded (lt : ℕ → ℕ → Type₀) :=
begin
constructor, intro n, induction n with n IH,
{ constructor, intros n H, exfalso, exact !not_lt_zero H},
{ constructor, intros m H,
assert aux : ∀ {n₁} (hlt : m < n₁), succ n = n₁ → acc lt m,
{ intros n₁ hlt, induction hlt,
{ intro p, injection p with q, exact q ▸ IH},
{ intro p, injection p with q, exact (acc.inv (q ▸ IH) a)}},
apply aux H rfl},
end
definition measure {A : Type} : (A → ℕ) → A → A → Type₀ :=
inv_image lt
definition measure.wf {A : Type} (f : A → ℕ) : well_founded (measure f) :=
inv_image.wf f lt.wf
theorem succ_lt_succ {a b : ℕ} : a < b → succ a < succ b :=
succ_le_succ
theorem lt_of_succ_lt {a b : ℕ} : succ a < b → a < b :=
le_of_succ_le
theorem lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b :=
le_of_succ_le_succ
definition decidable_le [instance] [priority nat.prio] : Π a b : nat, decidable (a ≤ b) :=
nat.rec (λm, (decidable.inl !zero_le))
(λn IH m, !nat.cases_on (decidable.inr (not_succ_le_zero n))
(λm, decidable.rec (λH, inl (succ_le_succ H))
(λH, inr (λa, H (le_of_succ_le_succ a))) (IH m)))
definition decidable_lt [instance] [priority nat.prio] : Π a b : nat, decidable (a < b) :=
λ a b, decidable_le (succ a) b
protected theorem lt_sum_ge (a b : ℕ) : a < b ⊎ a ≥ b :=
nat.rec (inr !zero_le) (λn, sum.rec
(λh, inl (le_succ_of_le h))
(λh, sum.rec_on (nat.eq_sum_lt_of_le h) (λe, inl (eq.subst e !nat.le_refl)) inr)) b
protected definition lt_ge_by_cases {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a ≥ b → P) : P :=
by_cases H1 (λh, H2 (sum.rec_on !nat.lt_sum_ge (λa, absurd a h) (λa, a)))
protected definition lt_by_cases {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P)
(H3 : b < a → P) : P :=
nat.lt_ge_by_cases H1 (λh₁,
nat.lt_ge_by_cases H3 (λh₂, H2 (nat.le_antisymm h₂ h₁)))
protected theorem lt_trichotomy (a b : ℕ) : a < b ⊎ a = b ⊎ b < a :=
nat.lt_by_cases (λH, inl H) (λH, inr (inl H)) (λH, inr (inr H))
protected theorem eq_sum_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ⊎ b < a :=
sum.rec_on (nat.lt_trichotomy a b)
(λ hlt, absurd hlt hnlt)
(λ h, h)
theorem lt_succ_of_le {a b : ℕ} : a ≤ b → a < succ b :=
succ_le_succ
theorem lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h
theorem succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h
theorem succ_sub_succ_eq_sub [simp] (a b : ℕ) : succ a - succ b = a - b :=
nat.rec (by esimp) (λ b, ap pred) b
theorem sub_eq_succ_sub_succ (a b : ℕ) : a - b = succ a - succ b :=
inverse !succ_sub_succ_eq_sub
theorem zero_sub_eq_zero [simp] (a : ℕ) : 0 - a = 0 :=
nat.rec rfl (λ a, ap pred) a
theorem zero_eq_zero_sub (a : ℕ) : 0 = 0 - a :=
inverse !zero_sub_eq_zero
theorem sub_le (a b : ℕ) : a - b ≤ a :=
nat.rec_on b !nat.le_refl (λ b₁, nat.le_trans !pred_le)
theorem sub_le_iff_unit [simp] (a b : ℕ) : a - b ≤ a ↔ unit :=
iff_unit_intro (sub_le a b)
theorem sub_lt {a b : ℕ} (H1 : 0 < a) (H2 : 0 < b) : a - b < a :=
!nat.cases_on (λh, absurd h !nat.lt_irrefl)
(λa h, succ_le_succ (!nat.cases_on (λh, absurd h !nat.lt_irrefl)
(λb c, tr_rev _ !succ_sub_succ_eq_sub !sub_le) H2)) H1
theorem sub_lt_succ (a b : ℕ) : a - b < succ a :=
lt_succ_of_le !sub_le
theorem sub_lt_succ_iff_unit [simp] (a b : ℕ) : a - b < succ a ↔ unit :=
iff_unit_intro !sub_lt_succ
end nat
|
c910f5937807d2be7265b928f1852a7b74f2b63b | bdb33f8b7ea65f7705fc342a178508e2722eb851 | /data/set/function.lean | d2a9ceda30f1b501dcdc1ff8c8d73b999ba6490b | [
"Apache-2.0"
] | permissive | rwbarton/mathlib | 939ae09bf8d6eb1331fc2f7e067d39567e10e33d | c13c5ea701bb1eec057e0a242d9f480a079105e9 | refs/heads/master | 1,584,015,335,862 | 1,524,142,167,000 | 1,524,142,167,000 | 130,614,171 | 0 | 0 | Apache-2.0 | 1,548,902,667,000 | 1,524,437,371,000 | Lean | UTF-8 | Lean | false | false | 9,627 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad, Andrew Zipperer, Haitao Zhang, Minchao Wu
Functions over sets.
-/
import data.set.basic
open function
namespace set
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
/- maps to -/
/-- `maps_to f a b` means that the image of `a` is contained in `b`. -/
@[reducible] def maps_to (f : α → β) (a : set α) (b : set β) : Prop := a ⊆ f ⁻¹' b
theorem maps_to_of_eq_on {f1 f2 : α → β} {a : set α} {b : set β} (h₁ : eq_on f1 f2 a)
(h₂ : maps_to f1 a b) :
maps_to f2 a b :=
λ x h, by rw [mem_preimage_eq, ← h₁ _ h]; exact h₂ h
theorem maps_to_comp {g : β → γ} {f : α → β} {a : set α} {b : set β} {c : set γ}
(h₁ : maps_to g b c) (h₂ : maps_to f a b) : maps_to (g ∘ f) a c :=
λ x h, h₁ (h₂ h)
theorem maps_to_univ (f : α → β) (a) : maps_to f a univ :=
λ x h, trivial
theorem image_subset_of_maps_to_of_subset {f : α → β} {a c : set α} {b : set β} (h₁ : maps_to f a b)
(h₂ : c ⊆ a) :
f '' c ⊆ b :=
λ y hy, let ⟨x, hx, heq⟩ := hy in
by rw [←heq]; apply h₁; apply h₂; assumption
theorem image_subset_of_maps_to {f : α → β} {a : set α} {b : set β} (h : maps_to f a b) :
f '' a ⊆ b :=
image_subset_of_maps_to_of_subset h (subset.refl _)
/- injectivity -/
/-- `f` is injective on `a` if the restriction of `f` to `a` is injective. -/
@[reducible] def inj_on (f : α → β) (a : set α) : Prop :=
∀⦃x1 x2 : α⦄, x1 ∈ a → x2 ∈ a → f x1 = f x2 → x1 = x2
theorem inj_on_empty (f : α → β) : inj_on f ∅ :=
λ _ _ h₁ _ _, false.elim h₁
theorem inj_on_of_eq_on {f1 f2 : α → β} {a : set α} (h₁ : eq_on f1 f2 a)
(h₂ : inj_on f1 a) :
inj_on f2 a :=
λ _ _ h₁' h₂' heq, by apply h₂ h₁' h₂'; rw [h₁, heq, ←h₁]; repeat {assumption}
theorem inj_on_comp {g : β → γ} {f : α → β} {a : set α} {b : set β}
(h₁ : maps_to f a b) (h₂ : inj_on g b) (h₃: inj_on f a) :
inj_on (g ∘ f) a :=
λ _ _ h₁' h₂' heq,
by apply h₃ h₁' h₂'; apply h₂; repeat {apply h₁, assumption}; assumption
theorem inj_on_of_inj_on_of_subset {f : α → β} {a b : set α} (h₁ : inj_on f b) (h₂ : a ⊆ b) :
inj_on f a :=
λ _ _ h₁' h₂' heq, h₁ (h₂ h₁') (h₂ h₂') heq
lemma injective_iff_inj_on_univ {f : α → β} : injective f ↔ inj_on f univ :=
iff.intro (λ h _ _ _ _ heq, h heq) (λ h _ _ heq, h trivial trivial heq)
/- surjectivity -/
/-- `f` is surjective from `a` to `b` if `b` is contained in the image of `a`. -/
@[reducible] def surj_on (f : α → β) (a : set α) (b : set β) : Prop := b ⊆ f '' a
theorem surj_on_of_eq_on {f1 f2 : α → β} {a : set α} {b : set β} (h₁ : eq_on f1 f2 a)
(h₂ : surj_on f1 a b) :
surj_on f2 a b :=
λ _ h, let ⟨x, hx⟩ := h₂ h in
⟨x, hx.left, by rw [←h₁ _ hx.left]; exact hx.right⟩
theorem surj_on_comp {g : β → γ} {f : α → β} {a : set α} {b : set β} {c : set γ}
(h₁ : surj_on g b c) (h₂ : surj_on f a b) :
surj_on (g ∘ f) a c :=
λ z h, let ⟨y, hy⟩ := h₁ h, ⟨x, hx⟩ := h₂ hy.left in
⟨x, hx.left, calc g (f x) = g y : by rw [hx.right]
... = z : hy.right⟩
lemma surjective_iff_surj_on_univ {f : α → β} : surjective f ↔ surj_on f univ univ :=
by simp [surjective, surj_on, subset_def]
lemma image_eq_of_maps_to_of_surj_on {f : α → β} {a : set α} {b : set β}
(h₁ : maps_to f a b) (h₂ : surj_on f a b) :
f '' a = b :=
eq_of_subset_of_subset (image_subset_of_maps_to h₁) h₂
/- bijectivity -/
/-- `f` is bijective from `a` to `b` if `f` is injective on `a` and `f '' a = b`. -/
@[reducible] def bij_on (f : α → β) (a : set α) (b : set β) : Prop :=
maps_to f a b ∧ inj_on f a ∧ surj_on f a b
lemma maps_to_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) :
maps_to f a b :=
h.left
lemma inj_on_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) :
inj_on f a :=
h.right.left
lemma surj_on_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) :
surj_on f a b :=
h.right.right
lemma bij_on.mk {f : α → β} {a : set α} {b : set β}
(h₁ : maps_to f a b) (h₂ : inj_on f a) (h₃ : surj_on f a b) :
bij_on f a b :=
⟨h₁, h₂, h₃⟩
theorem bij_on_of_eq_on {f1 f2 : α → β} {a : set α} {b : set β} (h₁ : eq_on f1 f2 a)
(h₂ : bij_on f1 a b) : bij_on f2 a b :=
let ⟨map, inj, surj⟩ := h₂ in
⟨maps_to_of_eq_on h₁ map, inj_on_of_eq_on h₁ inj, surj_on_of_eq_on h₁ surj⟩
lemma image_eq_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) :
f '' a = b :=
image_eq_of_maps_to_of_surj_on h.left h.right.right
theorem bij_on_comp {g : β → γ} {f : α → β} {a : set α} {b : set β} {c : set γ}
(h₁ : bij_on g b c) (h₂: bij_on f a b) :
bij_on (g ∘ f) a c :=
let ⟨gmap, ginj, gsurj⟩ := h₁, ⟨fmap, finj, fsurj⟩ := h₂ in
⟨maps_to_comp gmap fmap, inj_on_comp fmap ginj finj, surj_on_comp gsurj fsurj⟩
lemma bijective_iff_bij_on_univ {f : α → β} : bijective f ↔ bij_on f univ univ :=
iff.intro
(λ h, let ⟨inj, surj⟩ := h in
⟨maps_to_univ f _, iff.mp injective_iff_inj_on_univ inj, iff.mp surjective_iff_surj_on_univ surj⟩)
(λ h, let ⟨map, inj, surj⟩ := h in
⟨iff.mpr injective_iff_inj_on_univ inj, iff.mpr surjective_iff_surj_on_univ surj⟩)
/- left inverse -/
/-- `g` is a left inverse to `f` on `a` means that `g (f x) = x` for all `x ∈ a`. -/
@[reducible] def left_inv_on (g : β → α) (f : α → β) (a : set α) : Prop :=
∀ x ∈ a, g (f x) = x
theorem left_inv_on_of_eq_on_left {g1 g2 : β → α} {f : α → β} {a : set α} {b : set β}
(h₁ : maps_to f a b) (h₂ : eq_on g1 g2 b) (h₃ : left_inv_on g1 f a) : left_inv_on g2 f a :=
λ x h,
calc
g2 (f x) = g1 (f x) : eq.symm $ h₂ _ (h₁ h)
... = x : h₃ _ h
theorem left_inv_on_of_eq_on_right {g : β → α} {f1 f2 : α → β} {a : set α}
(h₁ : eq_on f1 f2 a) (h₂ : left_inv_on g f1 a) : left_inv_on g f2 a :=
λ x h,
calc
g (f2 x) = g (f1 x) : congr_arg g (h₁ _ h).symm
... = x : h₂ _ h
theorem inj_on_of_left_inv_on {g : β → α} {f : α → β} {a : set α} (h : left_inv_on g f a) :
inj_on f a :=
λ x₁ x₂ h₁ h₂ heq,
calc
x₁ = g (f x₁) : eq.symm $ h _ h₁
... = g (f x₂) : congr_arg g heq
... = x₂ : h _ h₂
theorem left_inv_on_comp {f' : β → α} {g' : γ → β} {g : β → γ} {f : α → β}
{a : set α} {b : set β} (h₁ : maps_to f a b)
(h₂ : left_inv_on f' f a) (h₃ : left_inv_on g' g b) : left_inv_on (f' ∘ g') (g ∘ f) a :=
λ x h,
calc
(f' ∘ g') ((g ∘ f) x) = f' (f x) : congr_arg f' (h₃ _ (h₁ h))
... = x : h₂ _ h
/- right inverse -/
/-- `g` is a right inverse to `f` on `b` if `f (g x) = x` for all `x ∈ b`. -/
@[reducible] def right_inv_on (g : β → α) (f : α → β) (b : set β) : Prop :=
left_inv_on f g b
theorem right_inv_on_of_eq_on_left {g1 g2 : β → α} {f : α → β} {a : set α} {b : set β}
(h₁ : eq_on g1 g2 b) (h₂ : right_inv_on g1 f b) : right_inv_on g2 f b :=
left_inv_on_of_eq_on_right h₁ h₂
theorem right_inv_on_of_eq_on_right {g : β → α} {f1 f2 : α → β} {a : set α} {b : set β}
(h₁ : maps_to g b a) (h₂ : eq_on f1 f2 a) (h₃ : right_inv_on g f1 b) : right_inv_on g f2 b :=
left_inv_on_of_eq_on_left h₁ h₂ h₃
theorem surj_on_of_right_inv_on {g : β → α} {f : α → β} {a : set α} {b : set β}
(h₁ : maps_to g b a) (h₂ : right_inv_on g f b) :
surj_on f a b :=
λ y h, ⟨g y, h₁ h, h₂ _ h⟩
theorem right_inv_on_comp {f' : β → α} {g' : γ → β} {g : β → γ} {f : α → β}
{c : set γ} {b : set β} (g'cb : maps_to g' c b)
(h₁ : right_inv_on f' f b) (h₂ : right_inv_on g' g c) : right_inv_on (f' ∘ g') (g ∘ f) c :=
left_inv_on_comp g'cb h₂ h₁
theorem right_inv_on_of_inj_on_of_left_inv_on {f : α → β} {g : β → α} {a : set α} {b : set β}
(h₁ : maps_to f a b) (h₂ : maps_to g b a) (h₃ : inj_on f a) (h₄ : left_inv_on f g b) :
right_inv_on f g a :=
λ x h, h₃ (h₂ $ h₁ h) h (h₄ _ (h₁ h))
theorem eq_on_of_left_inv_of_right_inv {g₁ g₂ : β → α} {f : α → β} {a : set α} {b : set β}
(h₁ : maps_to g₂ b a) (h₂ : left_inv_on g₁ f a) (h₃ : right_inv_on g₂ f b) : eq_on g₁ g₂ b :=
λ y h,
calc
g₁ y = (g₁ ∘ f ∘ g₂) y : congr_arg g₁ (h₃ _ h).symm
... = g₂ y : h₂ _ (h₁ h)
theorem left_inv_on_of_surj_on_right_inv_on {f : α → β} {g : β → α} {a : set α} {b : set β}
(h₁ : surj_on f a b) (h₂ : right_inv_on f g a) :
left_inv_on f g b :=
λ y h, let ⟨x, hx, heq⟩ := h₁ h in
calc
(f ∘ g) y = (f ∘ g ∘ f) x : congr_arg (f ∘ g) heq.symm
... = f x : congr_arg f (h₂ _ hx)
... = y : heq
/- inverses -/
/-- `g` is an inverse to `f` viewed as a map from `a` to `b` -/
@[reducible] def inv_on (g : β → α) (f : α → β) (a : set α) (b : set β) : Prop :=
left_inv_on g f a ∧ right_inv_on g f b
theorem bij_on_of_inv_on {g : β → α} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b)
(h₂ : maps_to g b a) (h₃ : inv_on g f a b) : bij_on f a b :=
⟨h₁, inj_on_of_left_inv_on h₃.left, surj_on_of_right_inv_on h₂ h₃.right⟩
end set
|
baafdeccc4fd32ed955236bff181029c2f59c276 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/analysis/complex/roots_of_unity_auto.lean | 8d18c875c2eaddc873a4c03e565600a5fab72c29 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,197 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.ring_theory.roots_of_unity
import Mathlib.analysis.special_functions.trigonometric
import Mathlib.analysis.special_functions.pow
import Mathlib.PostPort
namespace Mathlib
/-!
# Complex roots of unity
In this file we show that the `n`-th complex roots of unity
are exactly the complex numbers `e ^ (2 * real.pi * complex.I * (i / n))` for `i ∈ finset.range n`.
## Main declarations
* `complex.mem_roots_of_unity`: the complex `n`-th roots of unity are exactly the
complex numbers of the form `e ^ (2 * real.pi * complex.I * (i / n))` for some `i < n`.
* `complex.card_roots_of_unity`: the number of `n`-th roots of unity is exactly `n`.
-/
namespace complex
theorem is_primitive_root_exp_of_coprime (i : ℕ) (n : ℕ) (h0 : n ≠ 0) (hi : nat.coprime i n) :
is_primitive_root (exp (bit0 1 * ↑real.pi * I * (↑i / ↑n))) n :=
sorry
theorem is_primitive_root_exp (n : ℕ) (h0 : n ≠ 0) :
is_primitive_root (exp (bit0 1 * ↑real.pi * I / ↑n)) n :=
sorry
theorem is_primitive_root_iff (ζ : ℂ) (n : ℕ) (hn : n ≠ 0) :
is_primitive_root ζ n ↔
∃ (i : ℕ),
∃ (H : i < n), ∃ (hi : nat.coprime i n), exp (bit0 1 * ↑real.pi * I * (↑i / ↑n)) = ζ :=
sorry
/-- The complex `n`-th roots of unity are exactly the
complex numbers of the form `e ^ (2 * real.pi * complex.I * (i / n))` for some `i < n`. -/
theorem mem_roots_of_unity (n : ℕ+) (x : units ℂ) :
x ∈ roots_of_unity n ℂ ↔
∃ (i : ℕ), ∃ (H : i < ↑n), exp (bit0 1 * ↑real.pi * I * (↑i / ↑n)) = ↑x :=
sorry
theorem card_roots_of_unity (n : ℕ+) : fintype.card ↥(roots_of_unity n ℂ) = ↑n :=
is_primitive_root.card_roots_of_unity (is_primitive_root_exp (↑n) (pnat.ne_zero n))
theorem card_primitive_roots (k : ℕ) (h : k ≠ 0) :
finset.card (primitive_roots k ℂ) = nat.totient k :=
is_primitive_root.card_primitive_roots (is_primitive_root_exp k h) (nat.pos_of_ne_zero h)
end Mathlib |
959ccec1df3c9080edaf6b419590ef35df877b81 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebra/module/prod.lean | 640e0b4d736937b55dd4cbed9ae490cb40b01747 | [
"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 | 1,774 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot, Eric Wieser
-/
import algebra.module.basic
import group_theory.group_action.prod
/-!
# Prod instances for module and multiplicative actions
This file defines instances for binary product of modules
-/
variables {R : Type*} {S : Type*} {M : Type*} {N : Type*}
namespace prod
instance smul_with_zero [has_zero R] [has_zero M] [has_zero N]
[smul_with_zero R M] [smul_with_zero R N] : smul_with_zero R (M × N) :=
{ smul_zero := λ r, prod.ext (smul_zero' _ _) (smul_zero' _ _),
zero_smul := λ ⟨m, n⟩, prod.ext (zero_smul _ _) (zero_smul _ _),
..prod.has_scalar }
instance mul_action_with_zero [monoid_with_zero R] [has_zero M] [has_zero N]
[mul_action_with_zero R M] [mul_action_with_zero R N] : mul_action_with_zero R (M × N) :=
{ smul_zero := λ r, prod.ext (smul_zero' _ _) (smul_zero' _ _),
zero_smul := λ ⟨m, n⟩, prod.ext (zero_smul _ _) (zero_smul _ _),
..prod.mul_action }
instance {r : semiring R} [add_comm_monoid M] [add_comm_monoid N]
[module R M] [module R N] : module R (M × N) :=
{ add_smul := λ a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩,
zero_smul := λ ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩,
.. prod.distrib_mul_action }
instance {r : semiring R} [add_comm_monoid M] [add_comm_monoid N]
[module R M] [module R N]
[no_zero_smul_divisors R M] [no_zero_smul_divisors R N] :
no_zero_smul_divisors R (M × N) :=
⟨λ c ⟨x, y⟩ h, or_iff_not_imp_left.mpr (λ hc, mk.inj_iff.mpr
⟨(smul_eq_zero.mp (congr_arg fst h)).resolve_left hc,
(smul_eq_zero.mp (congr_arg snd h)).resolve_left hc⟩)⟩
end prod
|
d88ab7c336b134ea47b62c733187a6d276b0b8d3 | b00eb947a9c4141624aa8919e94ce6dcd249ed70 | /stage0/src/Lean/PrettyPrinter/Delaborator/Builtins.lean | 0ef3d7c117fa1efe5febdb21a5aa6f71b5c38639 | [
"Apache-2.0"
] | permissive | gebner/lean4-old | a4129a041af2d4d12afb3a8d4deedabde727719b | ee51cdfaf63ee313c914d83264f91f414a0e3b6e | refs/heads/master | 1,683,628,606,745 | 1,622,651,300,000 | 1,622,654,405,000 | 142,608,821 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 25,650 | 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.PrettyPrinter.Delaborator.Basic
import Lean.Parser
namespace Lean.PrettyPrinter.Delaborator
open Lean.Meta
open Lean.Parser.Term
@[builtinDelab fvar]
def delabFVar : Delab := do
let Expr.fvar id _ ← getExpr | unreachable!
try
let l ← getLocalDecl id
pure $ mkIdent l.userName
catch _ =>
-- loose free variable, use internal name
pure $ mkIdent id
-- loose bound variable, use pseudo syntax
@[builtinDelab bvar]
def delabBVar : Delab := do
let Expr.bvar idx _ ← getExpr | unreachable!
pure $ mkIdent $ Name.mkSimple $ "#" ++ toString idx
@[builtinDelab mvar]
def delabMVar : Delab := do
let Expr.mvar n _ ← getExpr | unreachable!
let mvarDecl ← getMVarDecl n
let n :=
match mvarDecl.userName with
| Name.anonymous => n.replacePrefix `_uniq `m
| n => n
`(?$(mkIdent n))
@[builtinDelab sort]
def delabSort : Delab := do
let Expr.sort l _ ← getExpr | unreachable!
match l with
| Level.zero _ => `(Prop)
| Level.succ (Level.zero _) _ => `(Type)
| _ => match l.dec with
| some l' => `(Type $(Level.quote l' max_prec))
| none => `(Sort $(Level.quote l max_prec))
-- find shorter names for constants, in reverse to Lean.Elab.ResolveName
private def unresolveQualifiedName (ns : Name) (c : Name) : DelabM Name := do
let c' := c.replacePrefix ns Name.anonymous;
let env ← getEnv
guard $ c' != c && !c'.isAnonymous && (!c'.isAtomic || !isProtected env c)
pure c'
private def unresolveUsingNamespace (c : Name) : Name → DelabM Name
| ns@(Name.str p _ _) => unresolveQualifiedName ns c <|> unresolveUsingNamespace c p
| _ => failure
private def unresolveOpenDecls (c : Name) : List OpenDecl → DelabM Name
| [] => failure
| OpenDecl.simple ns exs :: openDecls =>
let c' := c.replacePrefix ns Name.anonymous
if c' != c && exs.elem c' then unresolveOpenDecls c openDecls
else
unresolveQualifiedName ns c <|> unresolveOpenDecls c openDecls
| OpenDecl.explicit openedId resolvedId :: openDecls =>
guard (c == resolvedId) *> pure openedId <|> unresolveOpenDecls c openDecls
-- NOTE: not a registered delaborator, as `const` is never called (see [delab] description)
def delabConst : Delab := do
let Expr.const c ls _ ← getExpr | unreachable!
let c₀ := c
let mut c ← if (← getPPOption getPPFullNames) then pure c else
let ctx ← read
let env ← getEnv
let as := getRevAliases env c
-- might want to use a more clever heuristic such as selecting the shortest alias...
let c := as.headD c
unresolveUsingNamespace c ctx.currNamespace <|> unresolveOpenDecls c ctx.openDecls <|> pure c
unless (← getPPOption getPPPrivateNames) do
c := (privateToUserName? c).getD c
let ppUnivs ← getPPOption getPPUniverses
if ls.isEmpty || !ppUnivs then
if (← getLCtx).usesUserName c then
-- `c` is also a local declaration
if c == c₀ then
-- `c` is the fully qualified named. So, we append the `_root_` prefix
c := `_root_ ++ c
else
c := c₀
return mkIdent c
else
`($(mkIdent c).{$[$(ls.toArray.map quote)],*})
inductive ParamKind where
| explicit
-- combines implicit params, optParams, and autoParams
| implicit (defVal : Option Expr)
/-- Return array with n-th element set to kind of n-th parameter of `e`. -/
def getParamKinds (e : Expr) : MetaM (Array ParamKind) := do
let t ← inferType e
forallTelescopeReducing t fun params _ =>
params.mapM fun param => do
let l ← getLocalDecl param.fvarId!
match l.type.getOptParamDefault? with
| some val => pure $ ParamKind.implicit val
| _ =>
if l.type.isAutoParam || !l.binderInfo.isExplicit then
pure $ ParamKind.implicit none
else
pure ParamKind.explicit
@[builtinDelab app]
def delabAppExplicit : Delab := do
let (fnStx, argStxs) ← withAppFnArgs
(do
let fn ← getExpr
let stx ← if fn.isConst then delabConst else delab
let paramKinds ← liftM <| getParamKinds fn <|> pure #[]
let stx ← if paramKinds.any (fun | ParamKind.explicit => false | _ => true) then `(@$stx) else pure stx
pure (stx, #[]))
(fun ⟨fnStx, argStxs⟩ => do
let argStx ← delab
pure (fnStx, argStxs.push argStx))
Syntax.mkApp fnStx argStxs
@[builtinDelab app]
def delabAppImplicit : Delab := whenNotPPOption getPPExplicit do
let (fnStx, _, argStxs) ← withAppFnArgs
(do
let fn ← getExpr
let stx ← if fn.isConst then delabConst else delab
let paramKinds ← liftM (getParamKinds fn <|> pure #[])
pure (stx, paramKinds.toList, #[]))
(fun (fnStx, paramKinds, argStxs) => do
let arg ← getExpr;
let implicit : Bool := match paramKinds with -- TODO: check why we need `: Bool` here
| [ParamKind.implicit (some v)] => !v.hasLooseBVars && v == arg
| ParamKind.implicit none :: _ => true
| _ => false
if implicit then
pure (fnStx, paramKinds.tailD [], argStxs)
else do
let argStx ← delab
pure (fnStx, paramKinds.tailD [], argStxs.push argStx))
Syntax.mkApp fnStx argStxs
@[builtinDelab app]
def delabAppWithUnexpander : Delab := whenPPOption getPPNotation do
let Expr.const c _ _ ← pure (← getExpr).getAppFn | failure
let stx ← delabAppImplicit
match stx with
| `($cPP:ident $args*) => do go c stx
| `($cPP:ident) => do go c stx
| _ => pure stx
where
go c stx := do
let some (f::_) ← pure <| (appUnexpanderAttribute.ext.getState (← getEnv)).table.find? c
| pure stx
let EStateM.Result.ok stx _ ← f stx |>.run ()
| pure stx
pure stx
/-- State for `delabAppMatch` and helpers. -/
structure AppMatchState where
info : MatcherInfo
matcherTy : Expr
params : Array Expr := #[]
hasMotive : Bool := false
discrs : Array Syntax := #[]
varNames : Array (Array Name) := #[]
rhss : Array Syntax := #[]
-- additional arguments applied to the result of the `match` expression
moreArgs : Array Syntax := #[]
/--
Extract arguments of motive applications from the matcher type.
For the example below: `#[#[`([])], #[`(a::as)]]` -/
private partial def delabPatterns (st : AppMatchState) : DelabM (Array (Array Syntax)) :=
withReader (fun ctx => { ctx with inPattern := true }) do
let ty ← instantiateForall st.matcherTy st.params
forallTelescope ty fun params _ => do
-- skip motive and discriminators
let alts := Array.ofSubarray $ params[1 + st.discrs.size:]
alts.mapIdxM fun idx alt => do
let ty ← inferType alt
withReader ({ · with expr := ty }) $
usingNames st.varNames[idx] do
withAppFnArgs (pure #[]) (fun pats => do pure $ pats.push (← delab))
where
usingNames {α} (varNames : Array Name) (x : DelabM α) : DelabM α :=
usingNamesAux 0 varNames x
usingNamesAux {α} (i : Nat) (varNames : Array Name) (x : DelabM α) : DelabM α :=
if i < varNames.size then
withBindingBody varNames[i] <| usingNamesAux (i+1) varNames x
else
x
/-- Skip `numParams` binders, and execute `x varNames` where `varNames` contains the new binder names. -/
private def skippingBinders {α} (numParams : Nat) (x : Array Name → DelabM α) : DelabM α :=
loop numParams #[]
where
loop : Nat → Array Name → DelabM α
| 0, varNames => x varNames
| n+1, varNames => do
let varName ← (← getExpr).bindingName!.eraseMacroScopes
-- Pattern variables cannot shadow each other
if varNames.contains varName then
let varName := (← getLCtx).getUnusedName varName
withBindingBody varName do
loop n (varNames.push varName)
else
withBindingBodyUnusedName fun id => do
loop n (varNames.push id.getId)
/--
Delaborate applications of "matchers" such as
```
List.map.match_1 : {α : Type _} →
(motive : List α → Sort _) →
(x : List α) → (Unit → motive List.nil) → ((a : α) → (as : List α) → motive (a :: as)) → motive x
```
-/
@[builtinDelab app]
def delabAppMatch : Delab := whenPPOption getPPNotation do
-- incrementally fill `AppMatchState` from arguments
let st ← withAppFnArgs
(do
let (Expr.const c us _) ← getExpr | failure
let (some info) ← getMatcherInfo? c | failure
{ matcherTy := (← getConstInfo c).instantiateTypeLevelParams us, info := info : AppMatchState })
(fun st => do
if st.params.size < st.info.numParams then
pure { st with params := st.params.push (← getExpr) }
else if !st.hasMotive then
-- discard motive argument
pure { st with hasMotive := true }
else if st.discrs.size < st.info.numDiscrs then
pure { st with discrs := st.discrs.push (← delab) }
else if st.rhss.size < st.info.altNumParams.size then
/- We save the variables names here to be able to implement safe_shadowing.
The pattern delaboration must use the names saved here. -/
let (varNames, rhs) ← skippingBinders st.info.altNumParams[st.rhss.size] fun varNames => do
let rhs ← delab
return (varNames, rhs)
pure { st with rhss := st.rhss.push rhs, varNames := st.varNames.push varNames }
else
pure { st with moreArgs := st.moreArgs.push (← delab) })
if st.discrs.size < st.info.numDiscrs || st.rhss.size < st.info.altNumParams.size then
-- underapplied
failure
match st.discrs, st.rhss with
| #[discr], #[] =>
let stx ← `(nomatch $discr)
Syntax.mkApp stx st.moreArgs
| _, #[] => failure
| _, _ =>
let pats ← delabPatterns st
let stx ← `(match $[$st.discrs:term],* with $[| $pats,* => $st.rhss]*)
Syntax.mkApp stx st.moreArgs
@[builtinDelab mdata]
def delabMData : Delab := do
if let some _ := Lean.Meta.Match.inaccessible? (← getExpr) then
let s ← withMDataExpr delab
if (← read).inPattern then
`(.($s)) -- We only include the inaccessible annotation when we are delaborating patterns
else
return s
else
-- only interpret `pp.` values by default
let Expr.mdata m _ _ ← getExpr | unreachable!
let mut posOpts := (← read).optionsPerPos
let pos := (← read).pos
for (k, v) in m do
if (`pp).isPrefixOf k then
let opts := posOpts.find? pos |>.getD {}
posOpts := posOpts.insert pos (opts.insert k v)
withReader ({ · with optionsPerPos := posOpts }) do
withMDataExpr delab
/--
Check for a `Syntax.ident` of the given name anywhere in the tree.
This is usually a bad idea since it does not check for shadowing bindings,
but in the delaborator we assume that bindings are never shadowed.
-/
partial def hasIdent (id : Name) : Syntax → Bool
| Syntax.ident _ _ id' _ => id == id'
| Syntax.node _ args => args.any (hasIdent id)
| _ => false
/--
Return `true` iff current binder should be merged with the nested
binder, if any, into a single binder group:
* both binders must have same binder info and domain
* they cannot be inst-implicit (`[a b : A]` is not valid syntax)
* `pp.binder_types` must be the same value for both terms
* prefer `fun a b` over `fun (a b)`
-/
private def shouldGroupWithNext : DelabM Bool := do
let e ← getExpr
let ppEType ← getPPOption getPPBinderTypes;
let go (e' : Expr) := do
let ppE'Type ← withBindingBody `_ $ getPPOption getPPBinderTypes
pure $ e.binderInfo == e'.binderInfo &&
e.bindingDomain! == e'.bindingDomain! &&
e'.binderInfo != BinderInfo.instImplicit &&
ppEType == ppE'Type &&
(e'.binderInfo != BinderInfo.default || ppE'Type)
match e with
| Expr.lam _ _ e'@(Expr.lam _ _ _ _) _ => go e'
| Expr.forallE _ _ e'@(Expr.forallE _ _ _ _) _ => go e'
| _ => pure false
private partial def delabBinders (delabGroup : Array Syntax → Syntax → Delab) : optParam (Array Syntax) #[] → Delab
-- Accumulate names (`Syntax.ident`s with position information) of the current, unfinished
-- binder group `(d e ...)` as determined by `shouldGroupWithNext`. We cannot do grouping
-- inside-out, on the Syntax level, because it depends on comparing the Expr binder types.
| curNames => do
if (← shouldGroupWithNext) then
-- group with nested binder => recurse immediately
withBindingBodyUnusedName fun stxN => delabBinders delabGroup (curNames.push stxN)
else
-- don't group => delab body and prepend current binder group
let (stx, stxN) ← withBindingBodyUnusedName fun stxN => do (← delab, stxN)
delabGroup (curNames.push stxN) stx
@[builtinDelab lam]
def delabLam : Delab :=
delabBinders fun curNames stxBody => do
let e ← getExpr
let stxT ← withBindingDomain delab
let ppTypes ← getPPOption getPPBinderTypes
let expl ← getPPOption getPPExplicit
-- leave lambda implicit if possible
let blockImplicitLambda := expl ||
e.binderInfo == BinderInfo.default ||
Elab.Term.blockImplicitLambda stxBody ||
curNames.any (fun n => hasIdent n.getId stxBody);
if !blockImplicitLambda then
pure stxBody
else
let group ← match e.binderInfo, ppTypes with
| BinderInfo.default, true =>
-- "default" binder group is the only one that expects binder names
-- as a term, i.e. a single `Syntax.ident` or an application thereof
let stxCurNames ←
if curNames.size > 1 then
`($(curNames.get! 0) $(curNames.eraseIdx 0)*)
else
pure $ curNames.get! 0;
`(funBinder| ($stxCurNames : $stxT))
| BinderInfo.default, false => pure curNames.back -- here `curNames.size == 1`
| BinderInfo.implicit, true => `(funBinder| {$curNames* : $stxT})
| BinderInfo.implicit, false => `(funBinder| {$curNames*})
| BinderInfo.instImplicit, _ => `(funBinder| [$curNames.back : $stxT]) -- here `curNames.size == 1`
| _ , _ => unreachable!;
match stxBody with
| `(fun $binderGroups* => $stxBody) => `(fun $group $binderGroups* => $stxBody)
| _ => `(fun $group => $stxBody)
@[builtinDelab forallE]
def delabForall : Delab :=
delabBinders fun curNames stxBody => do
let e ← getExpr
let prop ← try isProp e catch _ => false
let stxT ← withBindingDomain delab
let group ← match e.binderInfo with
| BinderInfo.implicit => `(bracketedBinderF|{$curNames* : $stxT})
-- here `curNames.size == 1`
| BinderInfo.instImplicit => `(bracketedBinderF|[$curNames.back : $stxT])
| _ =>
-- heuristic: use non-dependent arrows only if possible for whole group to avoid
-- noisy mix like `(α : Type) → Type → (γ : Type) → ...`.
let dependent := curNames.any $ fun n => hasIdent n.getId stxBody
-- NOTE: non-dependent arrows are available only for the default binder info
if dependent then
if prop && !(← getPPOption getPPBinderTypes) then
return ← `(∀ $curNames:ident*, $stxBody)
else
`(bracketedBinderF|($curNames* : $stxT))
else
return ← curNames.foldrM (fun _ stxBody => `($stxT → $stxBody)) stxBody
if prop then
match stxBody with
| `(∀ $groups*, $stxBody) => `(∀ $group $groups*, $stxBody)
| _ => `(∀ $group, $stxBody)
else
`($group:bracketedBinder → $stxBody)
@[builtinDelab letE]
def delabLetE : Delab := do
let Expr.letE n t v b _ ← getExpr | unreachable!
let n ← getUnusedName n b
let stxT ← descend t 0 delab
let stxV ← descend v 1 delab
let stxB ← withLetDecl n t v fun fvar =>
let b := b.instantiate1 fvar
descend b 2 delab
`(let $(mkIdent n) : $stxT := $stxV; $stxB)
@[builtinDelab lit]
def delabLit : Delab := do
let Expr.lit l _ ← getExpr | unreachable!
match l with
| Literal.natVal n => pure $ quote n
| Literal.strVal s => pure $ quote s
-- `@OfNat.ofNat _ n _` ~> `n`
@[builtinDelab app.OfNat.ofNat]
def delabOfNat : Delab := whenPPOption getPPCoercions do
let (Expr.app (Expr.app _ (Expr.lit (Literal.natVal n) _) _) _ _) ← getExpr | failure
return quote n
-- `@OfDecimal.ofDecimal _ _ m s e` ~> `m*10^(sign * e)` where `sign == 1` if `s = false` and `sign = -1` if `s = true`
@[builtinDelab app.OfScientific.ofScientific]
def delabOfScientific : Delab := whenPPOption getPPCoercions do
let expr ← getExpr
guard <| expr.getAppNumArgs == 5
let Expr.lit (Literal.natVal m) _ ← pure (expr.getArg! 2) | failure
let Expr.lit (Literal.natVal e) _ ← pure (expr.getArg! 4) | failure
let s ← match expr.getArg! 3 with
| Expr.const `Bool.true _ _ => pure true
| Expr.const `Bool.false _ _ => pure false
| _ => failure
let str := toString m
if s && e == str.length then
return Syntax.mkScientificLit ("0." ++ str)
else if s && e < str.length then
let mStr := str.extract 0 (str.length - e)
let eStr := str.extract (str.length - e) str.length
return Syntax.mkScientificLit (mStr ++ "." ++ eStr)
else
return Syntax.mkScientificLit (str ++ "e" ++ (if s then "-" else "") ++ toString e)
/--
Delaborate a projection primitive. These do not usually occur in
user code, but are pretty-printed when e.g. `#print`ing a projection
function.
-/
@[builtinDelab proj]
def delabProj : Delab := do
let Expr.proj _ idx _ _ ← getExpr | unreachable!
let e ← withProj delab
-- not perfectly authentic: elaborates to the `idx`-th named projection
-- function (e.g. `e.1` is `Prod.fst e`), which unfolds to the actual
-- `proj`.
let idx := Syntax.mkLit fieldIdxKind (toString (idx + 1));
`($(e).$idx:fieldIdx)
/-- Delaborate a call to a projection function such as `Prod.fst`. -/
@[builtinDelab app]
def delabProjectionApp : Delab := whenPPOption getPPStructureProjections $ do
let e@(Expr.app fn _ _) ← getExpr | failure
let Expr.const c@(Name.str _ f _) _ _ ← pure fn.getAppFn | failure
let env ← getEnv
let some info ← pure $ env.getProjectionFnInfo? c | failure
-- can't use with classes since the instance parameter is implicit
guard $ !info.fromClass
-- projection function should be fully applied (#struct params + 1 instance parameter)
-- TODO: support over-application
guard $ e.getAppNumArgs == info.nparams + 1
-- If pp.explicit is true, and the structure has parameters, we should not
-- use field notation because we will not be able to see the parameters.
let expl ← getPPOption getPPExplicit
guard $ !expl || info.nparams == 0
let appStx ← withAppArg delab
`($(appStx).$(mkIdent f):ident)
@[builtinDelab app]
def delabStructureInstance : Delab := whenPPOption getPPStructureInstances do
let env ← getEnv
let e ← getExpr
let some s ← pure $ e.isConstructorApp? env | failure
guard $ isStructure env s.induct;
/- If implicit arguments should be shown, and the structure has parameters, we should not
pretty print using { ... }, because we will not be able to see the parameters. -/
let explicit ← getPPOption getPPExplicit
guard !(explicit && s.numParams > 0)
let fieldNames := getStructureFields env s.induct
let (_, fields) ← withAppFnArgs (pure (0, #[])) fun ⟨idx, fields⟩ => do
if idx < s.numParams then
pure (idx + 1, fields)
else
let val ← delab
let field ← `(structInstField|$(mkIdent <| fieldNames.get! (idx - s.numParams)):ident := $val)
pure (idx + 1, fields.push field)
let lastField := fields[fields.size - 1]
let fields := fields.pop
let ty ←
if (← getPPOption getPPStructureInstanceType) then
let ty ← inferType e
-- `ty` is not actually part of `e`, but since `e` must be an application or constant, we know that
-- index 2 is unused.
pure <| some (← descend ty 2 delab)
else pure <| none
`({ $[$fields, ]* $lastField $[: $ty]? })
@[builtinDelab app.Prod.mk]
def delabTuple : Delab := whenPPOption getPPNotation do
let e ← getExpr
guard $ e.getAppNumArgs == 4
let a ← withAppFn $ withAppArg delab
let b ← withAppArg delab
match b with
| `(($b, $bs,*)) => `(($a, $b, $bs,*))
| _ => `(($a, $b))
-- abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β
@[builtinDelab app.coe]
def delabCoe : Delab := whenPPOption getPPCoercions do
let e ← getExpr
guard $ e.getAppNumArgs >= 4
-- delab as application, then discard function
let stx ← delabAppImplicit
match stx with
| `($fn $arg) => arg
| `($fn $args*) => `($(args.get! 0) $(args.eraseIdx 0)*)
| _ => failure
-- abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a
@[builtinDelab app.coeFun]
def delabCoeFun : Delab := delabCoe
@[builtinDelab app.List.nil]
def delabNil : Delab := whenPPOption getPPNotation do
guard $ (← getExpr).getAppNumArgs == 1
`([])
@[builtinDelab app.List.cons]
def delabConsList : Delab := whenPPOption getPPNotation do
guard $ (← getExpr).getAppNumArgs == 3
let x ← withAppFn (withAppArg delab)
match (← withAppArg delab) with
| `([]) => `([$x])
| `([$xs,*]) => `([$x, $xs,*])
| _ => failure
@[builtinDelab app.List.toArray]
def delabListToArray : Delab := whenPPOption getPPNotation do
guard $ (← getExpr).getAppNumArgs == 2
match (← withAppArg delab) with
| `([$xs,*]) => `(#[$xs,*])
| _ => failure
@[builtinDelab app.ite]
def delabIte : Delab := whenPPOption getPPNotation do
guard $ (← getExpr).getAppNumArgs == 5
let c ← withAppFn $ withAppFn $ withAppFn $ withAppArg delab
let t ← withAppFn $ withAppArg delab
let e ← withAppArg delab
`(if $c then $t else $e)
@[builtinDelab app.dite]
def delabDIte : Delab := whenPPOption getPPNotation do
guard $ (← getExpr).getAppNumArgs == 5
let c ← withAppFn $ withAppFn $ withAppFn $ withAppArg delab
let (t, h) ← withAppFn $ withAppArg $ delabBranch none
let (e, _) ← withAppArg $ delabBranch h
`(if $(mkIdent h):ident : $c then $t else $e)
where
delabBranch (h? : Option Name) : DelabM (Syntax × Name) := do
let e ← getExpr
guard e.isLambda
let h ← match h? with
| some h => return (← withBindingBody h delab, h)
| none => withBindingBodyUnusedName fun h => do
return (← delab, h.getId)
@[builtinDelab app.namedPattern]
def delabNamedPattern : Delab := do
guard $ (← getExpr).getAppNumArgs == 3
let x ← withAppFn $ withAppArg delab
let p ← withAppArg delab
guard x.isIdent
`($x:ident@$p:term)
partial def delabDoElems : DelabM (List Syntax) := do
let e ← getExpr
if e.isAppOfArity `Bind.bind 6 then
-- Bind.bind.{u, v} : {m : Type u → Type v} → [self : Bind m] → {α β : Type u} → m α → (α → m β) → m β
let ma ← withAppFn $ withAppArg delab
withAppArg do
match (← getExpr) with
| Expr.lam _ _ body _ =>
withBindingBodyUnusedName fun n => do
if body.hasLooseBVars then
prependAndRec `(doElem|let $n:term ← $ma)
else
prependAndRec `(doElem|$ma:term)
| _ => failure
else if e.isLet then
let Expr.letE n t v b _ ← getExpr | unreachable!
let n ← getUnusedName n b
let stxT ← descend t 0 delab
let stxV ← descend v 1 delab
withLetDecl n t v fun fvar =>
let b := b.instantiate1 fvar
descend b 2 $
prependAndRec `(doElem|let $(mkIdent n) : $stxT := $stxV)
else
let stx ← delab
[←`(doElem|$stx:term)]
where
prependAndRec x : DelabM _ := List.cons <$> x <*> delabDoElems
@[builtinDelab app.Bind.bind]
def delabDo : Delab := whenPPOption getPPNotation do
guard <| (← getExpr).isAppOfArity `Bind.bind 6
let elems ← delabDoElems
let items ← elems.toArray.mapM (`(doSeqItem|$(·):doElem))
`(do $items:doSeqItem*)
@[builtinDelab app.sorryAx]
def delabSorryAx : Delab := whenPPOption getPPNotation do
guard <| (← getExpr).isAppOfArity ``sorryAx 2
`(sorry)
@[builtinDelab app.Eq.ndrec]
def delabEqNDRec : Delab := whenPPOption getPPNotation do
guard <| (← getExpr).getAppNumArgs == 6
-- Eq.ndrec.{u1, u2} : {α : Sort u2} → {a : α} → {motive : α → Sort u1} → (m : motive a) → {b : α} → (h : a = b) → motive b
let m ← withAppFn <| withAppFn <| withAppArg delab
let h ← withAppArg delab
`($h ▸ $m)
@[builtinDelab app.Eq.rec]
def delabEqRec : Delab :=
-- relevant signature parts as in `Eq.ndrec`
delabEqNDRec
def reifyName : Expr → DelabM Name
| Expr.const ``Lean.Name.anonymous .. => Name.anonymous
| Expr.app (Expr.app (Expr.const ``Lean.Name.mkStr ..) n _) (Expr.lit (Literal.strVal s) _) _ => do
(← reifyName n).mkStr s
| Expr.app (Expr.app (Expr.const ``Lean.Name.mkNum ..) n _) (Expr.lit (Literal.natVal i) _) _ => do
(← reifyName n).mkNum i
| _ => failure
@[builtinDelab app.Lean.Name.mkStr]
def delabNameMkStr : Delab := whenPPOption getPPNotation do
let n ← reifyName (← getExpr)
-- not guaranteed to be a syntactically valid name, but usually more helpful than the explicit version
mkNode ``Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!"`{n}"]
@[builtinDelab app.Lean.Name.mkNum]
def delabNameMkNum : Delab := delabNameMkStr
end Lean.PrettyPrinter.Delaborator
|
fc8b214829247b4656f3329b00562948f5cfd9bf | b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77 | /src/representation_theory/maschke.lean | 4f5d5c29723265417b501389884f33b9f558ca65 | [
"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 | 5,875 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Scott Morrison
-/
import algebra.monoid_algebra
import algebra.invertible
import algebra.char_p
import linear_algebra.basis
/-!
# Maschke's theorem
We prove Maschke's theorem for finite groups,
in the formulation that every submodule of a `k[G]` module has a complement,
when `k` is a field with `¬(ring_char k ∣ fintype.card G)`.
We do the core computation in greater generality.
For any `[comm_ring k]` in which `[invertible (fintype.card G : k)]`,
and a `k[G]`-linear map `i : V → W` which admits a `k`-linear retraction `π`,
we produce a `k[G]`-linear retraction by
taking the average over `G` of the conjugates of `π`.
## Future work
It's not so far to give the usual statement, that every finite dimensional representation
of a finite group is semisimple (i.e. a direct sum of irreducibles).
-/
universes u
noncomputable theory
open semimodule
open monoid_algebra
open_locale big_operators
section
-- At first we work with any `[comm_ring k]`, and add the assumption that
-- `[invertible (fintype.card G : k)]` when it is required.
variables {k : Type u} [comm_ring k] {G : Type u} [group G]
variables {V : Type u} [add_comm_group V] [module k V] [module (monoid_algebra k G) V]
variables [is_scalar_tower k (monoid_algebra k G) V]
variables {W : Type u} [add_comm_group W] [module k W] [module (monoid_algebra k G) W]
variables [is_scalar_tower k (monoid_algebra k G) W]
/-!
We now do the key calculation in Maschke's theorem.
Given `V → W`, an inclusion of `k[G]` modules,,
assume we have some retraction `π` (i.e. `∀ v, π (i v) = v`),
just as a `k`-linear map.
(When `k` is a field, this will be available cheaply, by choosing a basis.)
We now construct a retraction of the inclusion as a `k[G]`-linear map,
by the formula
$$ \frac{1}{|G|} \sum_{g \in G} g⁻¹ • π(g • -). $$
-/
namespace linear_map
variables (π : W →ₗ[k] V)
include π
/--
We define the conjugate of `π` by `g`, as a `k`-linear map.
-/
def conjugate (g : G) : W →ₗ[k] V :=
((group_smul.linear_map k V g⁻¹).comp π).comp (group_smul.linear_map k W g)
variables (i : V →ₗ[monoid_algebra k G] W) (h : ∀ v : V, π (i v) = v)
section
include h
lemma conjugate_i (g : G) (v : V) : (conjugate π g) (i v) = v :=
begin
dsimp [conjugate],
simp only [←i.map_smul, h, ←mul_smul, single_mul_single, mul_one, mul_left_inv],
change (1 : monoid_algebra k G) • v = v,
simp,
end
end
variables (G) [fintype G]
/--
The sum of the conjugates of `π` by each element `g : G`, as a `k`-linear map.
(We postpone dividing by the size of the group as long as possible.)
-/
def sum_of_conjugates : W →ₗ[k] V :=
∑ g : G, π.conjugate g
/--
In fact, the sum over `g : G` of the conjugate of `π` by `g` is a `k[G]`-linear map.
-/
def sum_of_conjugates_equivariant : W →ₗ[monoid_algebra k G] V :=
monoid_algebra.equivariant_of_linear_of_comm (π.sum_of_conjugates G) (λ g v,
begin
dsimp [sum_of_conjugates],
simp only [linear_map.sum_apply, finset.smul_sum],
dsimp [conjugate],
conv_lhs {
rw [←finset.univ_map_embedding (mul_right_embedding g⁻¹)],
simp only [mul_right_embedding],
},
simp only [←mul_smul, single_mul_single, mul_inv_rev, mul_one, function.embedding.coe_fn_mk,
finset.sum_map, inv_inv, inv_mul_cancel_right],
recover,
end)
section
variables [inv : invertible (fintype.card G : k)]
include inv
/--
We construct our `k[G]`-linear retraction of `i` as
$$ \frac{1}{|G|} \sum_{g \in G} g⁻¹ • π(g • -). $$
-/
def equivariant_projection : W →ₗ[monoid_algebra k G] V :=
⅟(fintype.card G : k) • (π.sum_of_conjugates_equivariant G)
include h
lemma equivariant_projection_condition (v : V) : (π.equivariant_projection G) (i v) = v :=
begin
rw [equivariant_projection, smul_apply, sum_of_conjugates_equivariant,
equivariant_of_linear_of_comm_apply, sum_of_conjugates],
rw [linear_map.sum_apply],
simp only [conjugate_i π i h],
rw [finset.sum_const, finset.card_univ,
@semimodule.nsmul_eq_smul k _
V _ _ (fintype.card G) v,
←mul_smul, invertible.inv_of_mul_self, one_smul],
end
end
end linear_map
end
-- Now we work over a `[field k]`, and replace the assumption `[invertible (fintype.card G : k)]`
-- with `¬(ring_char k ∣ fintype.card G)`.
variables {k : Type u} [field k] {G : Type u} [fintype G] [group G]
variables {V : Type u} [add_comm_group V] [module k V] [module (monoid_algebra k G) V]
variables [is_scalar_tower k (monoid_algebra k G) V]
variables {W : Type u} [add_comm_group W] [module k W] [module (monoid_algebra k G) W]
variables [is_scalar_tower k (monoid_algebra k G) W]
lemma monoid_algebra.exists_left_inverse_of_injective
(not_dvd : ¬(ring_char k ∣ fintype.card G)) (f : V →ₗ[monoid_algebra k G] W) (hf : f.ker = ⊥) :
∃ (g : W →ₗ[monoid_algebra k G] V), g.comp f = linear_map.id :=
begin
haveI : invertible (fintype.card G : k) :=
invertible_of_ring_char_not_dvd not_dvd,
obtain ⟨φ, hφ⟩ := (f.restrict_scalars k).exists_left_inverse_of_injective
(by simp only [hf, submodule.restrict_scalars_bot, linear_map.ker_restrict_scalars]),
refine ⟨φ.equivariant_projection G, _⟩,
ext v,
simp only [linear_map.id_coe, id.def, linear_map.comp_apply],
apply linear_map.equivariant_projection_condition,
intro v,
have := congr_arg linear_map.to_fun hφ,
exact congr_fun this v
end
lemma monoid_algebra.submodule.exists_is_compl
(not_dvd : ¬(ring_char k ∣ fintype.card G)) (p : submodule (monoid_algebra k G) V) :
∃ q : submodule (monoid_algebra k G) V, is_compl p q :=
let ⟨f, hf⟩ := monoid_algebra.exists_left_inverse_of_injective not_dvd p.subtype p.ker_subtype in
⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩
|
d39381f0d317ec4e7cec43e7edbf99539b64b016 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/data/set/intervals/proj_Icc.lean | 3195a580737f4dc4dae0276e73610619b983c2bf | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,731 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov, Patrick Massot
-/
import data.set.intervals.basic
/-!
# Projection of a line onto a closed interval
Given a linearly ordered type `α`, in this file we define
* `set.proj_Icc (a b : α) (h : a ≤ b)` to be the map `α → [a, b]` sending `(-∞, a]` to `a`, `[b, ∞)`
to `b`, and each point `x ∈ [a, b]` to itself;
* `set.Icc_extend {a b : α} (h : a ≤ b) (f : Icc a b → β)` to be the extension of `f` to `α` defined
as `f ∘ proj_Icc a b h`.
We also prove some trivial properties of these maps.
-/
variables {α β : Type*} [linear_order α]
open function
namespace set
/-- Projection of `α` to the closed interval `[a, b]`. -/
def proj_Icc (a b : α) (h : a ≤ b) (x : α) : Icc a b :=
⟨max a (min b x), le_max_left _ _, max_le h (min_le_left _ _)⟩
variables {a b : α} (h : a ≤ b) {x : α}
lemma proj_Icc_of_le_left (hx : x ≤ a) : proj_Icc a b h x = ⟨a, left_mem_Icc.2 h⟩ :=
by simp [proj_Icc, hx, hx.trans h]
@[simp] lemma proj_Icc_left : proj_Icc a b h a = ⟨a, left_mem_Icc.2 h⟩ :=
proj_Icc_of_le_left h le_rfl
lemma proj_Icc_of_right_le (hx : b ≤ x) : proj_Icc a b h x = ⟨b, right_mem_Icc.2 h⟩ :=
by simp [proj_Icc, hx, h]
@[simp] lemma proj_Icc_right : proj_Icc a b h b = ⟨b, right_mem_Icc.2 h⟩ :=
proj_Icc_of_right_le h le_rfl
lemma proj_Icc_of_mem (hx : x ∈ Icc a b) : proj_Icc a b h x = ⟨x, hx⟩ :=
by simp [proj_Icc, hx.1, hx.2]
@[simp] lemma proj_Icc_coe (x : Icc a b) : proj_Icc a b h x = x :=
by { cases x, apply proj_Icc_of_mem }
lemma proj_Icc_surj_on : surj_on (proj_Icc a b h) (Icc a b) univ :=
λ x _, ⟨x, x.2, proj_Icc_coe h x⟩
lemma proj_Icc_surjective : surjective (proj_Icc a b h) :=
λ x, ⟨x, proj_Icc_coe h x⟩
@[simp] lemma range_proj_Icc : range (proj_Icc a b h) = univ :=
(proj_Icc_surjective h).range_eq
lemma monotone_proj_Icc : monotone (proj_Icc a b h) :=
λ x y hxy, max_le_max le_rfl $ min_le_min le_rfl hxy
lemma strict_mono_on_proj_Icc : strict_mono_on (proj_Icc a b h) (Icc a b) :=
λ x hx y hy hxy, by simpa only [proj_Icc_of_mem, hx, hy]
/-- Extend a function `[a, b] → β` to a map `α → β`. -/
def Icc_extend {a b : α} (h : a ≤ b) (f : Icc a b → β) : α → β :=
f ∘ proj_Icc a b h
@[simp] lemma Icc_extend_range (f : Icc a b → β) :
range (Icc_extend h f) = range f :=
by simp [Icc_extend, range_comp f]
lemma Icc_extend_of_le_left (f : Icc a b → β) (hx : x ≤ a) :
Icc_extend h f x = f ⟨a, left_mem_Icc.2 h⟩ :=
congr_arg f $ proj_Icc_of_le_left h hx
@[simp] lemma Icc_extend_left (f : Icc a b → β) :
Icc_extend h f a = f ⟨a, left_mem_Icc.2 h⟩ :=
Icc_extend_of_le_left h f le_rfl
lemma Icc_extend_of_right_le (f : Icc a b → β) (hx : b ≤ x) :
Icc_extend h f x = f ⟨b, right_mem_Icc.2 h⟩ :=
congr_arg f $ proj_Icc_of_right_le h hx
@[simp] lemma Icc_extend_right (f : Icc a b → β) :
Icc_extend h f b = f ⟨b, right_mem_Icc.2 h⟩ :=
Icc_extend_of_right_le h f le_rfl
lemma Icc_extend_of_mem (f : Icc a b → β) (hx : x ∈ Icc a b) :
Icc_extend h f x = f ⟨x, hx⟩ :=
congr_arg f $ proj_Icc_of_mem h hx
@[simp] lemma Icc_extend_coe (f : Icc a b → β) (x : Icc a b) :
Icc_extend h f x = f x :=
congr_arg f $ proj_Icc_coe h x
end set
open set
variables [preorder β] {a b : α} (h : a ≤ b) {f : Icc a b → β}
lemma monotone.Icc_extend (hf : monotone f) : monotone (Icc_extend h f) :=
hf.comp $ monotone_proj_Icc h
lemma strict_mono.strict_mono_on_Icc_extend (hf : strict_mono f) :
strict_mono_on (Icc_extend h f) (Icc a b) :=
hf.comp_strict_mono_on (strict_mono_on_proj_Icc h)
|
6f43563f157051c1b271812596bc602f3e1df936 | 037dba89703a79cd4a4aec5e959818147f97635d | /src/2020/relations/partition_challenge_xena.lean | 70319332c63ee0536c203a9557eb4a7bf518a0c2 | [] | no_license | ImperialCollegeLondon/M40001_lean | 3a6a09298da395ab51bc220a535035d45bbe919b | 62a76fa92654c855af2b2fc2bef8e60acd16ccec | refs/heads/master | 1,666,750,403,259 | 1,665,771,117,000 | 1,665,771,117,000 | 209,141,835 | 115 | 12 | null | 1,640,270,596,000 | 1,568,749,174,000 | Lean | UTF-8 | Lean | false | false | 8,027 | lean | import tactic
/-!
# The partition challenge!
Prove that equivalence relations on α are the same as partitions of α.
Three sections:
1) partitions
2) equivalence classes
3) the challenge
## Overview
Say `α` is a type, and `R` is a binary relation on `α`.
The following things are already in Lean:
reflexive R := ∀ (x : α), R x x
symmetric R := ∀ ⦃x y : α⦄, R x y → R y x
transitive R := ∀ ⦃x y z : α⦄, R x y → R y z → R x z
equivalence R := reflexive R ∧ symmetric R ∧ transitive R
In the file below, we will define partitions of `α` and "build some
interface" (i.e. prove some propositions). We will define
equivalence classes and do the same thing.
Finally, we will prove that there's a bijection between
equivalence relations on `α` and partitions of `α`.
-/
/-
# 1) Partitions
We define a partition, and prove some easy lemmas.
-/
/-
## Definition of a partition
Let `α` be a type. A *partition* on `α` is defined to be
the following data:
1) A set C of subsets of α, called "blocks".
2) A hypothesis (i.e. a proof!) that all the blocks are non-empty.
3) A hypothesis that every term of type α is in one of the blocks.
4) A hypothesis that two blocks with non-empty intersection are equal.
-/
/-- The structure of a partition on a Type α. -/
@[ext] structure partition (α : Type) :=
(C : set (set α))
(Hnonempty : ∀ X ∈ C, (X : set α).nonempty)
(Hcover : ∀ (a : α), ∃ X ∈ C, a ∈ X)
(Hdisjoint : ∀ X Y ∈ C, (X ∩ Y : set α).nonempty → X = Y)
/-
## Basic interface for partitions
-/
namespace partition
-- let α be a type, and fix a partition P on α. Let X and Y be subsets of α.
variables {α : Type} {P : partition α} {X Y : set α}
/-- If X and Y are blocks, and a is in X and Y, then X = Y. -/
theorem eq_of_mem (hX : X ∈ P.C) (hY : Y ∈ P.C) {a : α}
(haX : a ∈ X)
(haY : a ∈ Y) : X = Y :=
begin
have h := P.Hdisjoint X hX Y hY,
apply h,
use a,
split;
assumption,
end
/-- If a is in two blocks X and Y, and if b is in X,
then b is in Y (as X=Y) -/
theorem mem_of_mem (hX : X ∈ P.C) (hY : Y ∈ P.C) {a b : α}
(haX : a ∈ X) (haY : a ∈ Y) (hbX : b ∈ X) : b ∈ Y :=
begin
convert hbX,
exact (eq_of_mem hX hY haX haY).symm,
end
/-- Every term of type `α` is in one of the blocks for a partition `P`. -/
theorem mem_block (a : α) : ∃ X : set α, X ∈ P.C ∧ a ∈ X :=
begin
rcases P.Hcover a with ⟨X, hXC, haX⟩,
use X,
split; assumption,
end
end partition
/-
# 2) Equivalence classes.
We define equivalence classes and prove a few basic results about them.
-/
section equivalence_classes
/-!
## Definition of equivalence classes
-/
-- Notation and variables for the equivalence class section:
-- let α be a type, and let R be a binary relation on R.
variables {α : Type} (R : α → α → Prop)
/-- The equivalence class of `a` is the set of `b` related to `a`. -/
def cl (a : α) :=
{b : α | R b a}
/-!
## Basic lemmas about equivalence classes
-/
/-- Useful for rewriting -- `b` is in the equivalence class of `a` iff
`b` is related to `a`. True by definition. -/
theorem cl_def {a b : α} : b ∈ cl R a ↔ R b a := iff.rfl
-- Assume now that R is an equivalence relation.
variables {R} (hR : equivalence R)
include hR
/-- x is in cl_R(x) -/
lemma mem_cl_self (a : α) :
a ∈ cl R a :=
begin
rw cl_def,
rcases hR with ⟨hrefl, hsymm, htrans⟩,
unfold reflexive at hrefl,
apply hrefl,
end
/-- if a is in cl(b) then cl(a) ⊆ cl(b) -/
lemma cl_sub_cl_of_mem_cl {a b : α} :
a ∈ cl R b →
cl R a ⊆ cl R b :=
begin
intro hab,
rw set.subset_def,
intro x,
intro hxa,
rw cl_def at *,
rcases hR with ⟨hrefl, hsymm, htrans⟩,
exact htrans hxa hab,
end
lemma cl_eq_cl_of_mem_cl {a b : α} :
a ∈ cl R b →
cl R a = cl R b :=
begin
intro hab,
apply set.subset.antisymm,
{ apply cl_sub_cl_of_mem_cl hR hab },
{ apply cl_sub_cl_of_mem_cl hR,
rw cl_def at *,
rcases hR with ⟨hrefl, hsymm, htrans⟩,
apply hsymm,
exact hab }
end
end equivalence_classes -- section
/-!
# 3) The challenge!
Let `α` be a type (i.e. a collection of stucff).
There is a bijection between equivalence relations on `α` and
partitions of `α`.
We prove this by writing down constructions in each direction
and proving that the constructions are two-sided inverses of one another.
-/
open partition
example (α : Type) : {R : α → α → Prop // equivalence R} ≃ partition α :=
-- We define constructions (functions!) in both directions and prove that
-- one is a two-sided inverse of the other
{ -- Here is the first construction, from equivalence
-- relations to partitions.
-- Let R be an equivalence relation.
to_fun := λ R, {
-- Let C be the set of equivalence classes for R.
C := { B : set α | ∃ x : α, B = cl R.1 x},
-- I claim that C is a partition. We need to check the three
-- hypotheses for a partition (`Hnonempty`, `Hcover` and `Hdisjoint`),
-- so we need to supply three proofs.
Hnonempty := begin
cases R with R hR,
-- If X is an equivalence class then X is nonempty.
show ∀ (X : set α), (∃ (a : α), X = cl R a) → X.nonempty,
sorry,
end,
Hcover := begin
cases R with R hR,
-- The equivalence classes cover α
show ∀ (a : α), ∃ (X : set α) (H : ∃ (b : α), X = cl R b), a ∈ X,
sorry,
end,
Hdisjoint := begin
cases R with R hR,
-- If two equivalence classes overlap, they are equal.
show ∀ (X : set α), (∃ (a : α), X = cl R a) →
∀ (Y : set α), (∃ (b : α), Y = cl R b) → (X ∩ Y).nonempty → X = Y,
sorry,
end },
-- Conversely, say P is an partition.
inv_fun := λ P,
-- Let's define a binary relation `R` thus:
-- `R a b` iff *every* block containing `a` also contains `b`.
-- Because only one block contains a, this will work,
-- and it turns out to be a nice way of thinking about it.
⟨λ a b, ∀ X ∈ P.C, a ∈ X → b ∈ X, begin
-- I claim this is an equivalence relation.
split,
{ -- It's reflexive
show ∀ (a : α)
(X : set α), X ∈ P.C → a ∈ X → a ∈ X,
sorry,
},
split,
{ -- it's symmetric
show ∀ (a b : α),
(∀ (X : set α), X ∈ P.C → a ∈ X → b ∈ X) →
∀ (X : set α), X ∈ P.C → b ∈ X → a ∈ X,
sorry,
},
{ -- it's transitive
unfold transitive,
show ∀ (a b c : α),
(∀ (X : set α), X ∈ P.C → a ∈ X → b ∈ X) →
(∀ (X : set α), X ∈ P.C → b ∈ X → c ∈ X) →
∀ (X : set α), X ∈ P.C → a ∈ X → c ∈ X,
sorry,
}
end⟩,
-- If you start with the equivalence relation, and then make the partition
-- and a new equivalence relation, you get back to where you started.
left_inv := begin
rintro ⟨R, hR⟩,
-- Tidying up the mess...
suffices : (λ (a b : α), ∀ (c : α), a ∈ cl R c → b ∈ cl R c) = R,
simpa,
-- ... you have to prove two binary relations are equal.
ext a b,
-- so you have to prove an if and only if.
show (∀ (c : α), a ∈ cl R c → b ∈ cl R c) ↔ R a b,
sorry,
end,
-- Similarly, if you start with the partition, and then make the
-- equivalence relation, and then construct the corresponding partition
-- into equivalence classes, you have the same partition you started with.
right_inv := begin
-- Let P be a partition
intro P,
-- It suffices to prove that a subset X is in the original partition
-- if and only if it's in the one made from the equivalence relation.
ext X,
show (∃ (a : α), X = cl _ a) ↔ X ∈ P.C,
dsimp only,
sorry,
end }
/-
-- get these files with
leanproject get ImperialCollegeLondon/M40001_lean
leave this channel and go to a workgroup channel and try
folling in the sorrys.
I will come around to help.
-/ |
284b90703b91fb69df5aafe1c0392e89c3060f42 | 97c8e5d8aca4afeebb5b335f26a492c53680efc8 | /ground_zero/HITs/pushout.lean | a9d08cb8aea4b892804a2f9f445790a45d2f6779 | [] | no_license | jfrancese/lean | cf32f0d8d5520b6f0e9d3987deb95841c553c53c | 06e7efaecce4093d97fb5ecc75479df2ef1dbbdb | refs/heads/master | 1,587,915,151,351 | 1,551,012,140,000 | 1,551,012,140,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,548 | lean | import ground_zero.types.heq
/-
Pushout.
* HoTT 6.8
-/
namespace ground_zero
namespace HITs
universes u v w k
section
parameters {α : Type u} {β : Type v} {σ : Type k} (f : σ → α) (g : σ → β)
inductive pushout_rel : (α ⊕ β) → (α ⊕ β) → Prop
| mk {} : Π (x : σ), pushout_rel (sum.inl (f x)) (sum.inr (g x))
def pushout := quot pushout_rel
end
namespace pushout
-- https://github.com/leanprover/lean2/blob/master/hott/hit/pushout.hlean
variables {α : Type u} {β : Type v} {σ : Type k} {f : σ → α} {g : σ → β}
def inl (x : α) : pushout f g :=
quot.mk (pushout_rel f g) (sum.inl x)
def inr (x : β) : pushout f g :=
quot.mk (pushout_rel f g) (sum.inr x)
def glue (x : σ) : inl (f x) = inr (g x) :> pushout f g :=
support.inclusion (quot.sound $ pushout_rel.mk x)
def ind {δ : pushout f g → Type w}
(inl₁ : Π (x : α), δ (inl x)) (inr₁ : Π (x : β), δ (inr x))
(glue₁ : Π (x : σ), inl₁ (f x) =[glue x] inr₁ (g x)) :
Π (x : pushout f g), δ x := begin
intro h, refine quot.hrec_on h _ _,
{ intro x, induction x, exact inl₁ x, exact inr₁ x },
{ intros u v H, cases H with x, simp,
apply types.heq.from_pathover (glue x),
exact glue₁ x }
end
def rec {δ : Type w} (inl₁ : α → δ) (inr₁ : β → δ)
(glue₁ : Π (x : σ), inl₁ (f x) = inr₁ (g x) :> δ) :
pushout f g → δ :=
ind inl₁ inr₁ (λ x, types.dep_path.pathover_of_eq (glue x) (glue₁ x))
end pushout
end HITs
end ground_zero |
35ecf8a80c8d4d48fc6b6ac4030739590bd50eec | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /library/init/native/pass.lean | 5b521e7af38004ff34f81246dce2ae1da255a116 | [
"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 | 1,850 | lean | /-
Copyright (c) 2016 Jared Roesch. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jared Roesch
-/
prelude
import init.meta.expr
import init.meta.format
import init.native.internal
import init.native.procedure
import init.native.config
namespace native
meta structure pass :=
(name : string)
(transform : config → procedure → procedure)
meta def file_name_for_dump (p : pass) :=
(pass.name p)
-- Unit functions get optimized away, need to talk to Leo about this one.
meta def run_pass (conf : config) (p : pass) (proc : procedure) : (format × procedure × format) :=
let result := pass.transform p conf proc in
(to_string proc, result, to_string result)
meta def collect_dumps {A : Type} : list (format × A × format) → format × list A × format
| [] := (format.nil, [], format.nil)
| ((pre, body, post) :: fs) :=
let (pre', bodies, post') := collect_dumps fs
in (pre ++ format.line ++ format.line ++ pre',
body :: bodies,
post ++ format.line ++ format.line ++ post')
meta def inner_loop_debug (conf : config) (p : pass) (es : list procedure) : list procedure :=
let (pre, bodies, post) := collect_dumps (list.map (fun e, run_pass conf p e) es) in
match native.dump_format (file_name_for_dump p ++ ".pre") pre with
| n := match native.dump_format (file_name_for_dump p ++ ".post") post with
| m := if n = m then bodies else bodies
end
end
meta def inner_loop (conf : config) (p : pass) (es : list procedure) : list procedure :=
if config.debug conf
then inner_loop_debug conf p es
else list.map (fun proc, pass.transform p conf proc) es
meta def run_passes (conf : config) (passes : list pass) (procs : list procedure) : list procedure :=
list.foldl (fun pass procs, inner_loop conf procs pass) procs passes
end native
|
bd9366b5d75e50de3b78a47f02ffd8995bc815cd | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/reflected_coercion_with_mvars.lean | b9e96c6f5fcf6a58c8b343f526403501c361cfc0 | [
"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 | 38 | lean | meta example : expr :=
`(1 + 1 : nat)
|
a539df7cc8472c811772f20dd76ada7a7dac2e6a | 49ffcd4736fa3bdcc1cdbb546d4c855d67c0f28a | /library/init/algebra/group.lean | 435d1a7da96cc936357bc04b319f7377399ed91a | [
"Apache-2.0"
] | permissive | black13/lean | 979e24d09e17b2fdf8ec74aac160583000086bc8 | 1a80ea9c8e28902cadbfb612896bcd45ba4ce697 | refs/heads/master | 1,626,839,620,164 | 1,509,113,016,000 | 1,509,122,889,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,242 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
-/
prelude
import init.logic init.algebra.classes init.meta init.meta.decl_cmds init.meta.smt.rsimp
/- Make sure instances defined in this file have lower priority than the ones
defined for concrete structures -/
set_option default_priority 100
set_option old_structure_cmd true
universe u
variables {α : Type u}
class semigroup (α : Type u) extends has_mul α :=
(mul_assoc : ∀ a b c : α, a * b * c = a * (b * c))
class comm_semigroup (α : Type u) extends semigroup α :=
(mul_comm : ∀ a b : α, a * b = b * a)
class left_cancel_semigroup (α : Type u) extends semigroup α :=
(mul_left_cancel : ∀ a b c : α, a * b = a * c → b = c)
class right_cancel_semigroup (α : Type u) extends semigroup α :=
(mul_right_cancel : ∀ a b c : α, a * b = c * b → a = c)
class monoid (α : Type u) extends semigroup α, has_one α :=
(one_mul : ∀ a : α, 1 * a = a) (mul_one : ∀ a : α, a * 1 = a)
class comm_monoid (α : Type u) extends monoid α, comm_semigroup α
class group (α : Type u) extends monoid α, has_inv α :=
(mul_left_inv : ∀ a : α, a⁻¹ * a = 1)
class comm_group (α : Type u) extends group α, comm_monoid α
@[simp] lemma mul_assoc [semigroup α] : ∀ a b c : α, a * b * c = a * (b * c) :=
semigroup.mul_assoc
instance semigroup_to_is_associative [semigroup α] : is_associative α (*) :=
⟨mul_assoc⟩
@[simp] lemma mul_comm [comm_semigroup α] : ∀ a b : α, a * b = b * a :=
comm_semigroup.mul_comm
instance comm_semigroup_to_is_commutative [comm_semigroup α] : is_commutative α (*) :=
⟨mul_comm⟩
@[simp] lemma mul_left_comm [comm_semigroup α] : ∀ a b c : α, a * (b * c) = b * (a * c) :=
left_comm has_mul.mul mul_comm mul_assoc
lemma mul_right_comm [comm_semigroup α] : ∀ a b c : α, a * b * c = a * c * b :=
right_comm has_mul.mul mul_comm mul_assoc
lemma mul_left_cancel [left_cancel_semigroup α] {a b c : α} : a * b = a * c → b = c :=
left_cancel_semigroup.mul_left_cancel a b c
lemma mul_right_cancel [right_cancel_semigroup α] {a b c : α} : a * b = c * b → a = c :=
right_cancel_semigroup.mul_right_cancel a b c
lemma mul_left_cancel_iff [left_cancel_semigroup α] {a b c : α} : a * b = a * c ↔ b = c :=
⟨mul_left_cancel, congr_arg _⟩
lemma mul_right_cancel_iff [right_cancel_semigroup α] {a b c : α} : b * a = c * a ↔ b = c :=
⟨mul_right_cancel, congr_arg _⟩
@[simp] lemma one_mul [monoid α] : ∀ a : α, 1 * a = a :=
monoid.one_mul
@[simp] lemma mul_one [monoid α] : ∀ a : α, a * 1 = a :=
monoid.mul_one
@[simp] lemma mul_left_inv [group α] : ∀ a : α, a⁻¹ * a = 1 :=
group.mul_left_inv
def inv_mul_self := @mul_left_inv
@[simp] lemma inv_mul_cancel_left [group α] (a b : α) : a⁻¹ * (a * b) = b :=
by rw [← mul_assoc, mul_left_inv, one_mul]
@[simp] lemma inv_mul_cancel_right [group α] (a b : α) : a * b⁻¹ * b = a :=
by simp
@[simp] lemma inv_eq_of_mul_eq_one [group α] {a b : α} (h : a * b = 1) : a⁻¹ = b :=
by rw [← mul_one a⁻¹, ←h, ←mul_assoc, mul_left_inv, one_mul]
@[simp] lemma one_inv [group α] : 1⁻¹ = (1 : α) :=
inv_eq_of_mul_eq_one (one_mul 1)
@[simp] lemma inv_inv [group α] (a : α) : (a⁻¹)⁻¹ = a :=
inv_eq_of_mul_eq_one (mul_left_inv a)
@[simp] lemma mul_right_inv [group α] (a : α) : a * a⁻¹ = 1 :=
have a⁻¹⁻¹ * a⁻¹ = 1, by rw mul_left_inv,
by rwa [inv_inv] at this
def mul_inv_self := @mul_right_inv
lemma inv_inj [group α] {a b : α} (h : a⁻¹ = b⁻¹) : a = b :=
have a = a⁻¹⁻¹, by simp,
begin rw this, simp [h] end
lemma group.mul_left_cancel [group α] {a b c : α} (h : a * b = a * c) : b = c :=
have a⁻¹ * (a * b) = b, by simp,
begin simp [h] at this, rw this end
lemma group.mul_right_cancel [group α] {a b c : α} (h : a * b = c * b) : a = c :=
have a * b * b⁻¹ = a, by simp,
begin simp [h] at this, rw this end
instance group.to_left_cancel_semigroup [s : group α] : left_cancel_semigroup α :=
{ s with mul_left_cancel := @group.mul_left_cancel α s }
instance group.to_right_cancel_semigroup [s : group α] : right_cancel_semigroup α :=
{ s with mul_right_cancel := @group.mul_right_cancel α s }
lemma mul_inv_cancel_left [group α] (a b : α) : a * (a⁻¹ * b) = b :=
by rw [← mul_assoc, mul_right_inv, one_mul]
lemma mul_inv_cancel_right [group α] (a b : α) : a * b * b⁻¹ = a :=
by rw [mul_assoc, mul_right_inv, mul_one]
@[simp] lemma mul_inv_rev [group α] (a b : α) : (a * b)⁻¹ = b⁻¹ * a⁻¹ :=
inv_eq_of_mul_eq_one begin rw [mul_assoc, ← mul_assoc b, mul_right_inv, one_mul, mul_right_inv] end
lemma eq_inv_of_eq_inv [group α] {a b : α} (h : a = b⁻¹) : b = a⁻¹ :=
by simp [h]
lemma eq_inv_of_mul_eq_one [group α] {a b : α} (h : a * b = 1) : a = b⁻¹ :=
have a⁻¹ = b, from inv_eq_of_mul_eq_one h,
by simp [this.symm]
lemma eq_mul_inv_of_mul_eq [group α] {a b c : α} (h : a * c = b) : a = b * c⁻¹ :=
by simp [h.symm]
lemma eq_inv_mul_of_mul_eq [group α] {a b c : α} (h : b * a = c) : a = b⁻¹ * c :=
by simp [h.symm]
lemma inv_mul_eq_of_eq_mul [group α] {a b c : α} (h : b = a * c) : a⁻¹ * b = c :=
by simp [h]
lemma mul_inv_eq_of_eq_mul [group α] {a b c : α} (h : a = c * b) : a * b⁻¹ = c :=
by simp [h]
lemma eq_mul_of_mul_inv_eq [group α] {a b c : α} (h : a * c⁻¹ = b) : a = b * c :=
by simp [h.symm]
lemma eq_mul_of_inv_mul_eq [group α] {a b c : α} (h : b⁻¹ * a = c) : a = b * c :=
by simp [h.symm, mul_inv_cancel_left]
lemma mul_eq_of_eq_inv_mul [group α] {a b c : α} (h : b = a⁻¹ * c) : a * b = c :=
by rw [h, mul_inv_cancel_left]
lemma mul_eq_of_eq_mul_inv [group α] {a b c : α} (h : a = c * b⁻¹) : a * b = c :=
by simp [h]
lemma mul_inv [comm_group α] (a b : α) : (a * b)⁻¹ = a⁻¹ * b⁻¹ :=
by rw [mul_inv_rev, mul_comm]
/- αdditive "sister" structures.
Example, add_semigroup mirrors semigroup.
These structures exist just to help automation.
In an alternative design, we could have the binary operation as an
extra argument for semigroup, monoid, group, etc. However, the lemmas
would be hard to index since they would not contain any constant.
For example, mul_assoc would be
lemma mul_assoc {α : Type u} {op : α → α → α} [semigroup α op] :
∀ a b c : α, op (op a b) c = op a (op b c) :=
semigroup.mul_assoc
The simplifier cannot effectively use this lemma since the pattern for
the left-hand-side would be
?op (?op ?a ?b) ?c
Remark: we use a tactic for transporting theorems from the multiplicative fragment
to the additive one.
-/
class add_semigroup (α : Type u) extends has_add α :=
(add_assoc : ∀ a b c : α, a + b + c = a + (b + c))
class add_comm_semigroup (α : Type u) extends add_semigroup α :=
(add_comm : ∀ a b : α, a + b = b + a)
class add_left_cancel_semigroup (α : Type u) extends add_semigroup α :=
(add_left_cancel : ∀ a b c : α, a + b = a + c → b = c)
class add_right_cancel_semigroup (α : Type u) extends add_semigroup α :=
(add_right_cancel : ∀ a b c : α, a + b = c + b → a = c)
class add_monoid (α : Type u) extends add_semigroup α, has_zero α :=
(zero_add : ∀ a : α, 0 + a = a) (add_zero : ∀ a : α, a + 0 = a)
class add_comm_monoid (α : Type u) extends add_monoid α, add_comm_semigroup α
class add_group (α : Type u) extends add_monoid α, has_neg α :=
(add_left_neg : ∀ a : α, -a + a = 0)
class add_comm_group (α : Type u) extends add_group α, add_comm_monoid α
open tactic
meta def transport_with_dict (dict : name_map name) (src : name) (tgt : name) : command :=
copy_decl_using dict src tgt
>> copy_attribute `reducible src tt tgt
>> copy_attribute `simp src tt tgt
>> copy_attribute `instance src tt tgt
/- Transport multiplicative to additive -/
meta def transport_multiplicative_to_additive (ls : list (name × name)) : command :=
let dict := rb_map.of_list ls in
ls.foldl (λ t ⟨src, tgt⟩, do
env ← get_env,
if (env.get tgt).to_bool = ff
then t >> transport_with_dict dict src tgt
else t)
skip
run_cmd transport_multiplicative_to_additive
[/- map operations -/
(`has_mul.mul, `has_add.add), (`has_one.one, `has_zero.zero), (`has_inv.inv, `has_neg.neg),
(`has_mul, `has_add), (`has_one, `has_zero), (`has_inv, `has_neg),
/- map constructors -/
(`has_mul.mk, `has_add.mk), (`has_one, `has_zero.mk), (`has_inv, `has_neg.mk),
/- map structures -/
(`semigroup, `add_semigroup),
(`monoid, `add_monoid),
(`group, `add_group),
(`comm_semigroup, `add_comm_semigroup),
(`comm_monoid, `add_comm_monoid),
(`comm_group, `add_comm_group),
(`left_cancel_semigroup, `add_left_cancel_semigroup),
(`right_cancel_semigroup, `add_right_cancel_semigroup),
(`left_cancel_semigroup.mk, `add_left_cancel_semigroup.mk),
(`right_cancel_semigroup.mk, `add_right_cancel_semigroup.mk),
/- map instances -/
(`semigroup.to_has_mul, `add_semigroup.to_has_add),
(`monoid.to_has_one, `add_monoid.to_has_zero),
(`group.to_has_inv, `add_group.to_has_neg),
(`comm_semigroup.to_semigroup, `add_comm_semigroup.to_add_semigroup),
(`monoid.to_semigroup, `add_monoid.to_add_semigroup),
(`comm_monoid.to_monoid, `add_comm_monoid.to_add_monoid),
(`comm_monoid.to_comm_semigroup, `add_comm_monoid.to_add_comm_semigroup),
(`group.to_monoid, `add_group.to_add_monoid),
(`comm_group.to_group, `add_comm_group.to_add_group),
(`comm_group.to_comm_monoid, `add_comm_group.to_add_comm_monoid),
(`left_cancel_semigroup.to_semigroup, `add_left_cancel_semigroup.to_add_semigroup),
(`right_cancel_semigroup.to_semigroup, `add_right_cancel_semigroup.to_add_semigroup),
/- map projections -/
(`semigroup.mul_assoc, `add_semigroup.add_assoc),
(`comm_semigroup.mul_comm, `add_comm_semigroup.add_comm),
(`left_cancel_semigroup.mul_left_cancel, `add_left_cancel_semigroup.add_left_cancel),
(`right_cancel_semigroup.mul_right_cancel, `add_right_cancel_semigroup.add_right_cancel),
(`monoid.one_mul, `add_monoid.zero_add),
(`monoid.mul_one, `add_monoid.add_zero),
(`group.mul_left_inv, `add_group.add_left_neg),
(`group.mul, `add_group.add),
(`group.mul_assoc, `add_group.add_assoc),
/- map lemmas -/
(`mul_assoc, `add_assoc),
(`mul_comm, `add_comm),
(`mul_left_comm, `add_left_comm),
(`mul_right_comm, `add_right_comm),
(`one_mul, `zero_add),
(`mul_one, `add_zero),
(`mul_left_inv, `add_left_neg),
(`mul_left_cancel, `add_left_cancel),
(`mul_right_cancel, `add_right_cancel),
(`mul_left_cancel_iff, `add_left_cancel_iff),
(`mul_right_cancel_iff, `add_right_cancel_iff),
(`inv_mul_cancel_left, `neg_add_cancel_left),
(`inv_mul_cancel_right, `neg_add_cancel_right),
(`eq_inv_mul_of_mul_eq, `eq_neg_add_of_add_eq),
(`inv_eq_of_mul_eq_one, `neg_eq_of_add_eq_zero),
(`inv_inv, `neg_neg),
(`mul_right_inv, `add_right_neg),
(`mul_inv_cancel_left, `add_neg_cancel_left),
(`mul_inv_cancel_right, `add_neg_cancel_right),
(`mul_inv_rev, `neg_add_rev),
(`mul_inv, `neg_add),
(`inv_inj, `neg_inj),
(`group.mul_left_cancel, `add_group.add_left_cancel),
(`group.mul_right_cancel, `add_group.add_right_cancel),
(`group.to_left_cancel_semigroup, `add_group.to_left_cancel_add_semigroup),
(`group.to_right_cancel_semigroup, `add_group.to_right_cancel_add_semigroup),
(`eq_inv_of_eq_inv, `eq_neg_of_eq_neg),
(`eq_inv_of_mul_eq_one, `eq_neg_of_add_eq_zero),
(`eq_mul_inv_of_mul_eq, `eq_add_neg_of_add_eq),
(`inv_mul_eq_of_eq_mul, `neg_add_eq_of_eq_add),
(`mul_inv_eq_of_eq_mul, `add_neg_eq_of_eq_add),
(`eq_mul_of_mul_inv_eq, `eq_add_of_add_neg_eq),
(`eq_mul_of_inv_mul_eq, `eq_add_of_neg_add_eq),
(`mul_eq_of_eq_inv_mul, `add_eq_of_eq_neg_add),
(`mul_eq_of_eq_mul_inv, `add_eq_of_eq_add_neg),
(`one_inv, `neg_zero)
]
instance add_semigroup_to_is_eq_associative [add_semigroup α] : is_associative α (+) :=
⟨add_assoc⟩
instance add_comm_semigroup_to_is_eq_commutative [add_comm_semigroup α] : is_commutative α (+) :=
⟨add_comm⟩
def neg_add_self := @add_left_neg
def add_neg_self := @add_right_neg
def eq_of_add_eq_add_left := @add_left_cancel
def eq_of_add_eq_add_right := @add_right_cancel
@[reducible] protected def algebra.sub [add_group α] (a b : α) : α :=
a + -b
instance add_group_has_sub [add_group α] : has_sub α :=
⟨algebra.sub⟩
@[simp] lemma sub_eq_add_neg [add_group α] (a b : α) : a - b = a + -b :=
rfl
lemma sub_self [add_group α] (a : α) : a - a = 0 :=
add_right_neg a
lemma sub_add_cancel [add_group α] (a b : α) : a - b + b = a :=
neg_add_cancel_right a b
lemma add_sub_cancel [add_group α] (a b : α) : a + b - b = a :=
add_neg_cancel_right a b
lemma add_sub_assoc [add_group α] (a b c : α) : a + b - c = a + (b - c) :=
by rw [sub_eq_add_neg, add_assoc, ←sub_eq_add_neg]
lemma eq_of_sub_eq_zero [add_group α] {a b : α} (h : a - b = 0) : a = b :=
have 0 + b = b, by rw zero_add,
have (a - b) + b = b, by rwa h,
by rwa [sub_eq_add_neg, neg_add_cancel_right] at this
lemma sub_eq_zero_of_eq [add_group α] {a b : α} (h : a = b) : a - b = 0 :=
by rw [h, sub_self]
lemma sub_eq_zero_iff_eq [add_group α] {a b : α} : a - b = 0 ↔ a = b :=
⟨eq_of_sub_eq_zero, sub_eq_zero_of_eq⟩
lemma zero_sub [add_group α] (a : α) : 0 - a = -a :=
zero_add (-a)
lemma sub_zero [add_group α] (a : α) : a - 0 = a :=
by rw [sub_eq_add_neg, neg_zero, add_zero]
lemma sub_ne_zero_of_ne [add_group α] {a b : α} (h : a ≠ b) : a - b ≠ 0 :=
begin
intro hab,
apply h,
apply eq_of_sub_eq_zero hab
end
lemma sub_neg_eq_add [add_group α] (a b : α) : a - (-b) = a + b :=
by rw [sub_eq_add_neg, neg_neg]
lemma neg_sub [add_group α] (a b : α) : -(a - b) = b - a :=
neg_eq_of_add_eq_zero (by rw [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left, add_right_neg])
lemma add_sub [add_group α] (a b c : α) : a + (b - c) = a + b - c :=
by simp
lemma sub_add_eq_sub_sub_swap [add_group α] (a b c : α) : a - (b + c) = a - c - b :=
by simp
lemma add_sub_add_right_eq_sub [add_group α] (a b c : α) : (a + c) - (b + c) = a - b :=
by rw [sub_add_eq_sub_sub_swap]; simp
lemma eq_sub_of_add_eq [add_group α] {a b c : α} (h : a + c = b) : a = b - c :=
by simp [h.symm]
lemma sub_eq_of_eq_add [add_group α] {a b c : α} (h : a = c + b) : a - b = c :=
by simp [h]
lemma eq_add_of_sub_eq [add_group α] {a b c : α} (h : a - c = b) : a = b + c :=
by simp [h.symm]
lemma add_eq_of_eq_sub [add_group α] {a b c : α} (h : a = c - b) : a + b = c :=
by simp [h]
lemma sub_add_eq_sub_sub [add_comm_group α] (a b c : α) : a - (b + c) = a - b - c :=
by simp
lemma neg_add_eq_sub [add_comm_group α] (a b : α) : -a + b = b - a :=
by simp
lemma sub_add_eq_add_sub [add_comm_group α] (a b c : α) : a - b + c = a + c - b :=
by simp
lemma sub_sub [add_comm_group α] (a b c : α) : a - b - c = a - (b + c) :=
by simp
lemma sub_add [add_comm_group α] (a b c : α) : a - b + c = a - (b - c) :=
by simp
lemma add_sub_add_left_eq_sub [add_comm_group α] (a b c : α) : (c + a) - (c + b) = a - b :=
by simp
lemma eq_sub_of_add_eq' [add_comm_group α] {a b c : α} (h : c + a = b) : a = b - c :=
by simp [h.symm]
lemma sub_eq_of_eq_add' [add_comm_group α] {a b c : α} (h : a = b + c) : a - b = c :=
by simp [h]
lemma eq_add_of_sub_eq' [add_comm_group α] {a b c : α} (h : a - b = c) : a = b + c :=
by simp [h.symm]
lemma add_eq_of_eq_sub' [add_comm_group α] {a b c : α} (h : b = c - a) : a + b = c :=
begin simp [h], rw [add_comm c, add_neg_cancel_left] end
lemma sub_sub_self [add_comm_group α] (a b : α) : a - (a - b) = b :=
begin simp, rw [add_comm b, add_neg_cancel_left] end
lemma add_sub_comm [add_comm_group α] (a b c d : α) : a + b - (c + d) = (a - c) + (b - d) :=
by simp
lemma sub_eq_sub_add_sub [add_comm_group α] (a b c : α) : a - b = c - b + (a - c) :=
by simp
lemma neg_neg_sub_neg [add_comm_group α] (a b : α) : - (-a - -b) = a - b :=
by simp
/- The following lemmas generate too many instances for rsimp -/
attribute [no_rsimp]
mul_assoc mul_comm mul_left_comm
add_assoc add_comm add_left_comm
|
d5ff485b06ebc587f92ccd0bbff994c6abb163bb | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/bench/rbmap4.lean | 3e06b39220a73377a5386ec50fc0e92616868ee4 | [
"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 | 2,843 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.coe init.data.option.basic init.system.io
universe u v w w'
inductive color
| Red | Black
inductive Tree
| Leaf {} : Tree
| Node (color : color) (lchild : Tree) (key : Nat) (val : Bool) (rchild : Tree) : Tree
variable {σ : Type w}
open color Nat Tree
def fold (f : Nat → Bool → σ → σ) : Tree → σ → σ
| Leaf, b => b
| Node _ l k v r, b => fold r (f k v (fold l b))
@[inline]
def balance1 : Nat → Bool → Tree → Tree → Tree
| kv, vv, t, Node _ (Node Red l kx vx r₁) ky vy r₂ => Node Red (Node Black l kx vx r₁) ky vy (Node Black r₂ kv vv t)
| kv, vv, t, Node _ l₁ ky vy (Node Red l₂ kx vx r) => Node Red (Node Black l₁ ky vy l₂) kx vx (Node Black r kv vv t)
| kv, vv, t, Node _ l ky vy r => Node Black (Node Red l ky vy r) kv vv t
| _, _, _, _ => Leaf
@[inline]
def balance2 : Tree → Nat → Bool → Tree → Tree
| t, kv, vv, Node _ (Node Red l kx₁ vx₁ r₁) ky vy r₂ => Node Red (Node Black t kv vv l) kx₁ vx₁ (Node Black r₁ ky vy r₂)
| t, kv, vv, Node _ l₁ ky vy (Node Red l₂ kx₂ vx₂ r₂) => Node Red (Node Black t kv vv l₁) ky vy (Node Black l₂ kx₂ vx₂ r₂)
| t, kv, vv, Node _ l ky vy r => Node Black t kv vv (Node Red l ky vy r)
| _, _, _, _ => Leaf
def isRed : Tree → Bool
| Node Red _ _ _ _ => true
| _ => false
def ins : Tree → Nat → Bool → Tree
| Leaf, kx, vx => Node Red Leaf kx vx Leaf
| Node Red a ky vy b, kx, vx =>
(if kx < ky then Node Red (ins a kx vx) ky vy b
else if kx = ky then Node Red a kx vx b
else Node Red a ky vy (ins b kx vx))
| Node Black a ky vy b, kx, vx =>
if kx < ky then
(if isRed a then balance1 ky vy b (ins a kx vx)
else Node Black (ins a kx vx) ky vy b)
else if kx = ky then Node Black a kx vx b
else if isRed b then balance2 a ky vy (ins b kx vx)
else Node Black a ky vy (ins b kx vx)
def setBlack : Tree → Tree
| Node _ l k v r => Node Black l k v r
| e => e
def insert (t : Tree) (k : Nat) (v : Bool) : Tree :=
if isRed t then setBlack (ins t k v)
else ins t k v
def mkMapAux : Nat → Tree → Tree
| 0, m => m
| n+1, m => mkMapAux n (insert m n (n % 10 = 0))
def mkMap (n : Nat) :=
mkMapAux n Leaf
def main (xs : List String) : IO UInt32 :=
let m := mkMap xs.head.toNat;
let v := fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) m 0;
IO.println (toString v) *>
pure 0
|
a7289112afe0a2f5e47ca7270a9403ea6e6b9aea | 83c8119e3298c0bfc53fc195c41a6afb63d01513 | /library/init/category/reader.lean | a7a00462591084e82353887ea0db18098892e175 | [
"Apache-2.0"
] | permissive | anfelor/lean | 584b91c4e87a6d95f7630c2a93fb082a87319ed0 | 31cfc2b6bf7d674f3d0f73848b842c9c9869c9f1 | refs/heads/master | 1,610,067,141,310 | 1,585,992,232,000 | 1,585,992,232,000 | 251,683,543 | 0 | 0 | Apache-2.0 | 1,585,676,570,000 | 1,585,676,569,000 | null | UTF-8 | Lean | false | false | 4,990 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
The reader monad transformer for passing immutable state.
-/
prelude
import init.category.lift init.category.id init.category.alternative init.category.except
universes u v w
/-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/
structure reader_t (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) :=
(run : ρ → m α)
@[reducible] def reader (ρ : Type u) := reader_t ρ id
attribute [pp_using_anonymous_constructor] reader_t
namespace reader_t
section
variable {ρ : Type u}
variable {m : Type u → Type v}
variable [monad m]
variables {α β : Type u}
@[inline] protected def read : reader_t ρ m ρ :=
⟨pure⟩
@[inline] protected def pure (a : α) : reader_t ρ m α :=
⟨λ r, pure a⟩
@[inline] protected def bind (x : reader_t ρ m α) (f : α → reader_t ρ m β) : reader_t ρ m β :=
⟨λ r, do a ← x.run r,
(f a).run r⟩
instance : monad (reader_t ρ m) :=
{ pure := @reader_t.pure _ _ _, bind := @reader_t.bind _ _ _ }
@[inline] protected def lift (a : m α) : reader_t ρ m α :=
⟨λ r, a⟩
instance (m) [monad m] : has_monad_lift m (reader_t ρ m) :=
⟨@reader_t.lift ρ m _⟩
@[inline] protected def monad_map {ρ m m'} [monad m] [monad m'] {α} (f : Π {α}, m α → m' α) : reader_t ρ m α → reader_t ρ m' α :=
λ x, ⟨λ r, f (x.run r)⟩
instance (ρ m m') [monad m] [monad m'] : monad_functor m m' (reader_t ρ m) (reader_t ρ m') :=
⟨@reader_t.monad_map ρ m m' _ _⟩
@[inline] protected def adapt {ρ' : Type u} [monad m] {α : Type u} (f : ρ' → ρ) : reader_t ρ m α → reader_t ρ' m α :=
λ x, ⟨λ r, x.run (f r)⟩
protected def orelse [alternative m] {α : Type u} (x₁ x₂ : reader_t ρ m α) : reader_t ρ m α :=
⟨λ s, x₁.run s <|> x₂.run s⟩
protected def failure [alternative m] {α : Type u} : reader_t ρ m α :=
⟨λ s, failure⟩
instance [alternative m] : alternative (reader_t ρ m) :=
{ failure := @reader_t.failure _ _ _ _,
orelse := @reader_t.orelse _ _ _ _ }
instance (ε) [monad m] [monad_except ε m] : monad_except ε (reader_t ρ m) :=
{ throw := λ α, reader_t.lift ∘ throw,
catch := λ α x c, ⟨λ r, catch (x.run r) (λ e, (c e).run r)⟩ }
end
end reader_t
/-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader).
It does not contain `local` because this function cannot be lifted using `monad_lift`.
Instead, the `monad_reader_adapter` class provides the more general `adapt_reader` function.
Note: This class can be seen as a simplification of the more "principled" definition
```
class monad_reader (ρ : out_param (Type u)) (n : Type u → Type u) :=
(lift {} {α : Type u} : (∀ {m : Type u → Type u} [monad m], reader_t ρ m α) → n α)
```
-/
class monad_reader (ρ : out_param (Type u)) (m : Type u → Type v) :=
(read {} : m ρ)
export monad_reader (read)
instance monad_reader_trans {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w}
[monad_reader ρ m] [has_monad_lift m n] : monad_reader ρ n :=
⟨monad_lift (monad_reader.read : m ρ)⟩
instance {ρ : Type u} {m : Type u → Type v} [monad m] : monad_reader ρ (reader_t ρ m) :=
⟨reader_t.read⟩
/-- Adapt a monad stack, changing the type of its top-most environment.
This class is comparable to [Control.Lens.Magnify](https://hackage.haskell.org/package/lens-4.15.4/docs/Control-Lens-Zoom.html#t:Magnify), but does not use lenses (why would it), and is derived automatically for any transformer implementing `monad_functor`.
Note: This class can be seen as a simplification of the more "principled" definition
```
class monad_reader_functor (ρ ρ' : out_param (Type u)) (n n' : Type u → Type u) :=
(map {} {α : Type u} : (∀ {m : Type u → Type u} [monad m], reader_t ρ m α → reader_t ρ' m α) → n α → n' α)
```
-/
class monad_reader_adapter (ρ ρ' : out_param (Type u)) (m m' : Type u → Type v) :=
(adapt_reader {} {α : Type u} : (ρ' → ρ) → m α → m' α)
export monad_reader_adapter (adapt_reader)
section
variables {ρ ρ' : Type u} {m m' : Type u → Type v}
instance monad_reader_adapter_trans {n n' : Type u → Type v} [monad_functor m m' n n'] [monad_reader_adapter ρ ρ' m m'] : monad_reader_adapter ρ ρ' n n' :=
⟨λ α f, monad_map (λ α, (adapt_reader f : m α → m' α))⟩
instance [monad m] : monad_reader_adapter ρ ρ' (reader_t ρ m) (reader_t ρ' m) :=
⟨λ α, reader_t.adapt⟩
end
instance (ρ : Type u) (m out) [monad_run out m] : monad_run (λ α, ρ → out α) (reader_t ρ m) :=
⟨λ α x, run ∘ x.run⟩
|
25b189655ab3e9418d6ba72b0cbb652c62b886f8 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/data/fintype/card.lean | ab469b3a148e7ef4c9de3fa729abe81b5ea05832 | [
"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 | 9,573 | 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.fintype.basic
import algebra.big_operators.ring
import algebra.big_operators.option
/-!
Results about "big operations" over a `fintype`, and consequent
results about cardinalities of certain types.
## Implementation note
This content had previously been in `data.fintype.basic`, but was moved here to avoid
requiring `algebra.big_operators` (and hence many other imports) as a
dependency of `fintype`.
However many of the results here really belong in `algebra.big_operators.basic`
and should be moved at some point.
-/
universes u v
variables {α : Type*} {β : Type*} {γ : Type*}
open_locale big_operators
namespace fintype
@[to_additive]
lemma prod_bool [comm_monoid α] (f : bool → α) : ∏ b, f b = f tt * f ff := by simp
lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = ∑ a : α, 1 :=
finset.card_eq_sum_ones _
section
open finset
variables {ι : Type*} [decidable_eq ι] [fintype ι]
@[to_additive]
lemma prod_extend_by_one [comm_monoid α] (s : finset ι) (f : ι → α) :
∏ i, (if i ∈ s then f i else 1) = ∏ i in s, f i :=
by rw [← prod_filter, filter_mem_eq_inter, univ_inter]
end
section
variables {M : Type*} [fintype α] [comm_monoid M]
@[to_additive]
lemma prod_eq_one (f : α → M) (h : ∀ a, f a = 1) :
(∏ a, f a) = 1 :=
finset.prod_eq_one $ λ a ha, h a
@[to_additive]
lemma prod_congr (f g : α → M) (h : ∀ a, f a = g a) :
(∏ a, f a) = ∏ a, g a :=
finset.prod_congr rfl $ λ a ha, h a
@[to_additive]
lemma prod_eq_single {f : α → M} (a : α) (h : ∀ x ≠ a, f x = 1) :
(∏ x, f x) = f a :=
finset.prod_eq_single a (λ x _ hx, h x hx) $ λ ha, (ha (finset.mem_univ a)).elim
@[to_additive]
lemma prod_eq_mul {f : α → M} (a b : α) (h₁ : a ≠ b) (h₂ : ∀ x, x ≠ a ∧ x ≠ b → f x = 1) :
(∏ x, f x) = (f a) * (f b) :=
begin
apply finset.prod_eq_mul a b h₁ (λ x _ hx, h₂ x hx);
exact λ hc, (hc (finset.mem_univ _)).elim
end
/-- If a product of a `finset` of a subsingleton type has a given
value, so do the terms in that product. -/
@[to_additive "If a sum of a `finset` of a subsingleton type has a given
value, so do the terms in that sum."]
lemma eq_of_subsingleton_of_prod_eq {ι : Type*} [subsingleton ι] {s : finset ι}
{f : ι → M} {b : M} (h : ∏ i in s, f i = b) : ∀ i ∈ s, f i = b :=
finset.eq_of_card_le_one_of_prod_eq (finset.card_le_one_of_subsingleton s) h
end
end fintype
open finset
section
variables {M : Type*} [fintype α] [comm_monoid M]
@[simp, to_additive]
lemma fintype.prod_option (f : option α → M) : ∏ i, f i = f none * ∏ i, f (some i) :=
finset.prod_insert_none f univ
end
open finset
@[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*)
[fintype α] [∀ a, fintype (β a)] :
fintype.card (sigma β) = ∑ a, fintype.card (β a) :=
card_sigma _ _
@[simp] lemma finset.card_pi [decidable_eq α] {δ : α → Type*}
(s : finset α) (t : Π a, finset (δ a)) :
(s.pi t).card = ∏ a in s, card (t a) :=
multiset.card_pi _ _
@[simp] lemma fintype.card_pi_finset [decidable_eq α] [fintype α]
{δ : α → Type*} (t : Π a, finset (δ a)) :
(fintype.pi_finset t).card = ∏ a, card (t a) :=
by simp [fintype.pi_finset, card_map]
@[simp] lemma fintype.card_pi {β : α → Type*} [decidable_eq α] [fintype α]
[f : Π a, fintype (β a)] : fintype.card (Π a, β a) = ∏ a, fintype.card (β a) :=
fintype.card_pi_finset _
-- FIXME ouch, this should be in the main file.
@[simp] lemma fintype.card_fun [decidable_eq α] [fintype α] [fintype β] :
fintype.card (α → β) = fintype.card β ^ fintype.card α :=
by rw [fintype.card_pi, finset.prod_const]; refl
@[simp] lemma card_vector [fintype α] (n : ℕ) :
fintype.card (vector α n) = fintype.card α ^ n :=
by rw fintype.of_equiv_card; simp
@[simp, to_additive]
lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) :
∏ x in univ.attach, f x = ∏ x, f ⟨x, (mem_univ _)⟩ :=
fintype.prod_equiv (equiv.subtype_univ_equiv (λ x, mem_univ _)) _ _ (λ x, by simp)
/-- Taking a product over `univ.pi t` is the same as taking the product over `fintype.pi_finset t`.
`univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ
in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and
`fintype.pi_finset t` is a `finset (Π a, t a)`. -/
@[to_additive "Taking a sum over `univ.pi t` is the same as taking the sum over
`fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`,
but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and
`fintype.pi_finset t` is a `finset (Π a, t a)`."]
lemma finset.prod_univ_pi [decidable_eq α] [fintype α] [comm_monoid β]
{δ : α → Type*} {t : Π (a : α), finset (δ a)}
(f : (Π (a : α), a ∈ (univ : finset α) → δ a) → β) :
∏ x in univ.pi t, f x = ∏ x in fintype.pi_finset t, f (λ a _, x a) :=
prod_bij (λ x _ a, x a (mem_univ _))
(by simp)
(by simp)
(by simp [function.funext_iff] {contextual := tt})
(λ x hx, ⟨λ a _, x a, by simp * at *⟩)
/-- The product over `univ` of a sum can be written as a sum over the product of sets,
`fintype.pi_finset`. `finset.prod_sum` is an alternative statement when the product is not
over `univ` -/
lemma finset.prod_univ_sum [decidable_eq α] [fintype α] [comm_semiring β] {δ : α → Type u_1}
[Π (a : α), decidable_eq (δ a)] {t : Π (a : α), finset (δ a)}
{f : Π (a : α), δ a → β} :
∏ a, ∑ b in t a, f a b = ∑ p in fintype.pi_finset t, ∏ x, f x (p x) :=
by simp only [finset.prod_attach_univ, prod_sum, finset.sum_univ_pi]
/-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a fintype of cardinality `n`
gives `(a + b)^n`. The "good" proof involves expanding along all coordinates using the fact that
`x^n` is multilinear, but multilinear maps are only available now over rings, so we give instead
a proof reducing to the usual binomial theorem to have a result over semirings. -/
lemma fintype.sum_pow_mul_eq_add_pow
(α : Type*) [fintype α] {R : Type*} [comm_semiring R] (a b : R) :
∑ s : finset α, a ^ s.card * b ^ (fintype.card α - s.card) =
(a + b) ^ (fintype.card α) :=
finset.sum_pow_mul_eq_add_pow _ _ _
@[to_additive]
lemma function.bijective.prod_comp [fintype α] [fintype β] [comm_monoid γ] {f : α → β}
(hf : function.bijective f) (g : β → γ) :
∏ i, g (f i) = ∏ i, g i :=
fintype.prod_bijective f hf _ _ (λ x, rfl)
@[to_additive]
lemma equiv.prod_comp [fintype α] [fintype β] [comm_monoid γ] (e : α ≃ β) (f : β → γ) :
∏ i, f (e i) = ∏ i, f i :=
e.bijective.prod_comp f
/-- It is equivalent to sum a function over `fin n` or `finset.range n`. -/
@[to_additive]
lemma fin.prod_univ_eq_prod_range [comm_monoid α] (f : ℕ → α) (n : ℕ) :
∏ i : fin n, f i = ∏ i in range n, f i :=
calc (∏ i : fin n, f i) = ∏ i : {x // x ∈ range n}, f i :
(equiv.subtype_equiv_right $ λ m, (@mem_range n m).symm).prod_comp (f ∘ coe)
... = ∏ i in range n, f i : by rw [← attach_eq_univ, prod_attach]
@[to_additive]
lemma finset.prod_fin_eq_prod_range [comm_monoid β] {n : ℕ} (c : fin n → β) :
∏ i, c i = ∏ i in finset.range n, if h : i < n then c ⟨i, h⟩ else 1 :=
begin
rw [← fin.prod_univ_eq_prod_range, finset.prod_congr rfl],
rintros ⟨i, hi⟩ _,
simp only [fin.coe_eq_val, hi, dif_pos]
end
@[to_additive]
lemma finset.prod_to_finset_eq_subtype {M : Type*} [comm_monoid M] [fintype α]
(p : α → Prop) [decidable_pred p] (f : α → M) :
∏ a in {x | p x}.to_finset, f a = ∏ a : subtype p, f a :=
by { rw ← finset.prod_subtype, simp }
@[to_additive] lemma finset.prod_fiberwise [decidable_eq β] [fintype β] [comm_monoid γ]
(s : finset α) (f : α → β) (g : α → γ) :
∏ b : β, ∏ a in s.filter (λ a, f a = b), g a = ∏ a in s, g a :=
finset.prod_fiberwise_of_maps_to (λ x _, mem_univ _) _
@[to_additive]
lemma fintype.prod_fiberwise [fintype α] [decidable_eq β] [fintype β] [comm_monoid γ]
(f : α → β) (g : α → γ) :
(∏ b : β, ∏ a : {a // f a = b}, g (a : α)) = ∏ a, g a :=
begin
rw [← (equiv.sigma_fiber_equiv f).prod_comp, ← univ_sigma_univ, prod_sigma],
refl
end
lemma fintype.prod_dite [fintype α] {p : α → Prop} [decidable_pred p]
[comm_monoid β] (f : Π (a : α) (ha : p a), β) (g : Π (a : α) (ha : ¬p a), β) :
(∏ a, dite (p a) (f a) (g a)) = (∏ a : {a // p a}, f a a.2) * (∏ a : {a // ¬p a}, g a a.2) :=
begin
simp only [prod_dite, attach_eq_univ],
congr' 1,
{ convert (equiv.subtype_equiv_right _).prod_comp (λ x : {x // p x}, f x x.2),
simp },
{ convert (equiv.subtype_equiv_right _).prod_comp (λ x : {x // ¬p x}, g x x.2),
simp }
end
section
open finset
variables {α₁ : Type*} {α₂ : Type*} {M : Type*} [fintype α₁] [fintype α₂] [comm_monoid M]
@[to_additive]
lemma fintype.prod_sum_elim (f : α₁ → M) (g : α₂ → M) :
(∏ x, sum.elim f g x) = (∏ a₁, f a₁) * (∏ a₂, g a₂) :=
by { classical, rw [univ_sum_type, prod_sum_elim] }
@[to_additive]
lemma fintype.prod_sum_type (f : α₁ ⊕ α₂ → M) :
(∏ x, f x) = (∏ a₁, f (sum.inl a₁)) * (∏ a₂, f (sum.inr a₂)) :=
by simp only [← fintype.prod_sum_elim, sum.elim_comp_inl_inr]
end
|
9d8af6c811b587f6b8eae4b9925010392b9639b6 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/data/fin/basic_auto.lean | 1e83f6608ba6d9bccff14e336a91975b8301689d | [] | 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,977 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.data.nat.basic
universes u
namespace Mathlib
/-- `fin n` is the subtype of `ℕ` consisting of natural numbers strictly smaller than `n`. -/
def fin (n : ℕ) := Subtype fun (i : ℕ) => i < n
namespace fin
/-- Backwards-compatible constructor for `fin n`. -/
def mk {n : ℕ} (i : ℕ) (h : i < n) : fin n := { val := i, property := h }
protected def lt {n : ℕ} (a : fin n) (b : fin n) := subtype.val a < subtype.val b
protected def le {n : ℕ} (a : fin n) (b : fin n) := subtype.val a ≤ subtype.val b
protected instance has_lt {n : ℕ} : HasLess (fin n) := { Less := fin.lt }
protected instance has_le {n : ℕ} : HasLessEq (fin n) := { LessEq := fin.le }
protected instance decidable_lt {n : ℕ} (a : fin n) (b : fin n) : Decidable (a < b) :=
nat.decidable_lt (subtype.val a) (subtype.val b)
protected instance decidable_le {n : ℕ} (a : fin n) (b : fin n) : Decidable (a ≤ b) :=
nat.decidable_le (subtype.val a) (subtype.val b)
def elim0 {α : fin 0 → Sort u} (x : fin 0) : α x := sorry
theorem eq_of_veq {n : ℕ} {i : fin n} {j : fin n} : subtype.val i = subtype.val j → i = j := sorry
theorem veq_of_eq {n : ℕ} {i : fin n} {j : fin n} : i = j → subtype.val i = subtype.val j := sorry
theorem ne_of_vne {n : ℕ} {i : fin n} {j : fin n} (h : subtype.val i ≠ subtype.val j) : i ≠ j :=
fun (h' : i = j) => absurd (veq_of_eq h') h
theorem vne_of_ne {n : ℕ} {i : fin n} {j : fin n} (h : i ≠ j) : subtype.val i ≠ subtype.val j :=
fun (h' : subtype.val i = subtype.val j) => absurd (eq_of_veq h') h
end fin
protected instance fin.decidable_eq (n : ℕ) : DecidableEq (fin n) :=
fun (i j : fin n) =>
decidable_of_decidable_of_iff (nat.decidable_eq (subtype.val i) (subtype.val j)) sorry
end Mathlib |
48afb3dfa4ae0397ea5e251e18b98d8ac8bfc937 | d450724ba99f5b50b57d244eb41fef9f6789db81 | /src/mywork/lectures/lecture_10.lean | e26f9889a1081458ff24f535f3e542fafdd6c816 | [] | no_license | jakekauff/CS2120F21 | 4f009adeb4ce4a148442b562196d66cc6c04530c | e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad | refs/heads/main | 1,693,841,880,030 | 1,637,604,848,000 | 1,637,604,848,000 | 399,946,698 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,109 | lean | /-
In today's class, we'll continue with our
exploration of the proposition, "false",
its elimination rule, and their vital uses
in logical reasoning: especially in
- proof of ¬P by negation
- proof of P by false elimination
Here are the inference rules in display
notation:
NEGATION INTRODUCTION
The first, proof by negation, says that
from a proof of P → false you can derive
a proof of ¬P. Indeed! It's definitional.
Recall: def not (P : Prop) := P → false.
(P : Prop) (np : P → false)
--------------------------- [by defn'n]
(pf : ¬P)
This rule is the foundation for "proof by
negation." To prove ¬P you first assume P,
is true, then you show that in this context
you can derive a contradiction. What you
have then shown, of course, is P → false.
So, to prove ¬P, assume P and show that in
this context there is a contradiction.
This is proof by negation. It is not to be
confused with proof by contradition, which
is a different thing entirely.
(Proof by contradiction. You can use this
approach to a proposition, P, by assuming
¬P and showing that this assumption leads
to a contradiction. That proves ¬¬P. Then
you use the *indepedent* axiom of negation
elimination to infer P from ¬¬P.)
FALSE ELIMINATION
The second rule says that if you have a
proof of false and any other proposition,
P, the logic is useless and so you might
as well just admit that P is true. Why is
the logic useless? Well, if false is true
then there's no longer a difference! In
this situation, tHere's sense in reasoning
any further, and you can just dismiss it.
A contradiction makes a logic inconsistent.
(P : Prop) (f : false)
---------------------- (false_elim f)
(pf : P)
-/
/-
We covered the relatively simpler notion of
negation introduction last time, so today we
will start by focusing on false elimination.
Understanding why it's not magic and in fact
makes perfect sense takes a bit of thought.
-/
/-
To make sense of false elimination, think in
terms of case analysis. Proof by case analysis
says that if the truth of some proposition, Y,
follows from *any possible form of proof* of X,
then you've proved X → Y.
If X is a disjunction, P ∨ Q (so now you want
to prove P ∨ Q → Y) you must consider two cases:
one where P is assumed true and one where Q is
assumed true.
If X is a proposition with just one form of
proof (e.g., the proposition, true), there's
just one case to consider.
-/
-- two cases
example : true ∨ false → true :=
begin
assume h,
cases h,
assumption, -- context has exact proof
contradiction, -- context has contradiction
end
-- one case
example : true → true :=
begin
assume t,
cases t, -- just one case
exact true.intro,
end
/-
How many cases must you consider if you putatively
have a putative proof of false? ZERO! To consider
*all* cases you need consider exactly zero cases.
Proving all cases when the number of cases is zero
is trivial, so the conclusion *follows*.
-/
example : false → false :=
begin
assume f,
cases f, -- case analysis: there are no cases!
end
/-
In fact, it doesn't matter what your conclusion
is: it will always be true in a context in which
you have a proof of false. And this makes sense,
because if you have a proof of false, then false
is true, so whether a given proposition is true
or false, it's true, because even if it's false,
well, false is true, so it's also true!
-/
theorem false_elim : ∀ (P : Prop), false → P :=
begin
assume P,
assume f,
cases f,
end
/-
This, then, is the general principle for false
elimination: ANYTHING FOLLOWS FROM FALSE. This
principle gives you a powerful way to prove any
proposition is true (conditional on your having
a proof that can't exist).
The theorem states that if you're given any
proposition, P, and a proof, f, of false, then
in that context, you can return a proof of P by
using false elimination. The only problem with
this super-power is that in reality, there is no
proof of false, so there's no real danger of any
old proposition being automatically true! The
rule of false elimination tells you that if
you're in a situation that can't happen, then
no worries, be happy, you're done (just use
false elimination).
-/
/-
The elimination principle for false is called
false.elim in Lean. If you are given or can
derive a proof, f, of false, then all you have
to do to finish your proof is to say, "this is
situation can't happen, so we need not consider
it any further." Or, formally, (false.elim f).
-/
-- Suppose P is *any* (an arbitrary) proposition
axiom P : Prop
example : false → P :=
begin
assume f,
exact false.elim f, -- Using Lean's version
-- P is implicit argument
end
/-
SOME THEOREMS INVOLVING FALSE AND NEGATION
-/
theorem no_contradiction : ∀ (P : Prop), ¬(P ∧ ¬P) :=
begin
assume p,
assume h,
have p := h.left,
have np := h.right,
have f := np p, -- IMPORTANT TO KNOW
exact f,
end
/-
The so-called "law" (it's really an axiom) of the
excluded middle says that any proposition is either
true or false. There's no middle ground. But in the
constructive logic of Lean, this isn't true.
To prove P ∨ ¬P, as you recall, we need to have
either a proof of P (in this case use or.intro_left)
or a proof of ¬P, in which case we use or.intro_right
to prove P ∨ ¬P. But what if we don't have a proof
either way?
There are many important questions in computer science
and mathematics where we don't know either way. If you
call one of those propositions, P, and try to prove P
∨ ¬P in Lean, you just get stuck.
-/
theorem excluded_middle' : ∀ (P : Prop), (P ∨ ¬P) :=
begin
assume P,
apply or.intro_right,
assume p,
-- we don't have a proof of either P or of ¬P!
end
/-
Let P be the conjecture, "every even whole number
greater than 2 is the sum of two prime numbers."
This conjecture, dating (in a slightly different
form) to a letter from Goldback to Euler in 1742
is still neither proved nor disproved! Below you
will find a placeholder for a proof. Just fill it
in (correctly) and you will win $1M and probably
a Fields Medal (the "Nobel Prize" in mathematics).
-/
axioms (ev : ℕ → Prop) (prime : ℕ → Prop)
def goldbach_conjecture :=
∀ (n : ℕ),
n > 2 →
(∃ h k : ℕ, n = h + k ∧ prime h ∧ prime k)
theorem goldbach_conjecture_true : goldbach_conjecture := _
theorem goldbach_conjecture_false : ¬goldbach_conjecture := _
example : goldbach_conjecture ∨ ¬goldbach_conjecture := _
/-
Our only options are or.intro_left or or.intro_right, but
we don't have a required argument (proof) to use either of
them!
-/
/-
The axioms of the constructive logic of Lean are not
strong enough to prove the "law of the excluded middle."
Rather, if we want to use it, we have to accept it as
an additional axiom. We thus have two different logics:
one without and one with the law of the excluded middle!
-/
axiom excluded_middle : ∀ (P : Prop), (P ∨ ¬P)
/-
Now, for any proposition whatsoever, P, we can always
prove P ∨ ¬P by applying excluded middle to P (using
the elimination rule for ∀). What we get in return is
a proof of P ∨ ¬P for whatever proposition P is. Here
is an example where the proposition is ItsRaining.
-/
axiom ItsRaining : Prop
theorem example_em : ItsRaining ∨ ¬ItsRaining :=
begin
apply excluded_middle ItsRaining,
end
/-
PROOF BY NEGATION, EXAMPLE
-/
/-
Next we return to the negation connective, which
in logic is pronounced "not." Given any proposition,
P, ¬P is also a proposition; and what it means is,
exactly, P → false. If P is true, then false is true,
and false cannot possibly be true, so P must not be.
Thus, to prove ¬P you prove P → false. Another way
to read P → false is that, if we assume that P is
true, we can derive a proof of false, which cannot
exist, so P must not be true. MEMORIZE THIS REASONING.
Again, to prove ¬P, *assume P and show that in that
context, you can derive a contradiction in the form
of a proof of false. This is the strategy call proof
by contradiction.
-/
/-
How about we prove ¬(0 = 1) in English.
Proof. By negation. Assume 0 = 1 and show
that this leads to a contradiction. That
is, show 0 = 1 → false.
The rest of the proof is by case analysis on
the assumed proof of 0 = 1. The only way to
have a proof of equality is by the reflexive
property of =. But the reflexive property
doesn't imply that there's a proof of 0 = 1.
So there can be no proof of 0 = 1, and the
assumption that 0 = 1 is a contradiction.
We finish the proof by case analysis on the
possible proofs of 0 = 1, of which there are
zero. So in all (zero!) cases, the conclusion
(false) follows. Therefore 0 = 1 → false, which
is to say, ¬(0 = 1) is proved and thus true.
QED.
-/
example : ¬0 = 1 :=
begin
show 0 = 1 → false, -- rewrite goal to a definitionally equal goal
assume h,
cases h, -- there are *zero* ways to build a proof of 0 = 1
-- case analysis discharges our "proof obligation"
end
|
59cc397379d853edd15957039f0aa007bdb528dc | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/attributes.lean | a221f0e52a2f8e414de551f2b23d6e6b93d90f9c | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 196 | lean | universe variables u
definition foo (A : Type u) := A
local attribute [reducible] foo
local attribute [-reducible] foo -- use [semireducible] instead
--
local attribute [-instance] nat_has_one
|
d445bbc0603cfef71b2ea466e278afb5e095e20b | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/topology/metric_space/gromov_hausdorff.lean | 5f8a9c66185cb3615a240e0958f54cd719344eb8 | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 55,733 | 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
-/
import topology.metric_space.closeds
import set_theory.cardinal
import topology.metric_space.gromov_hausdorff_realized
import topology.metric_space.completion
/-!
# Gromov-Hausdorff distance
This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces
up to isometry.
We introduce 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.
## Main results
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.
-/
noncomputable theory
open_locale classical topological_space
universes u v w
open classical set function topological_space filter metric quotient
open bounded_continuous_function nat Kuratowski_embedding
open sum (inl inr)
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 α⟧
instance : inhabited GH_space := ⟨quot.mk _ ⟨{0}, by simp [-singleton_zero]⟩⟩
/-- 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_coe.comp f.isometry },
{ rw [range_comp, f.range_coe, set.image_univ, subtype.range_coe] } },
{ 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.range_coe⟩,
apply isometry_subtype_coe
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})) }
/-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to
the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/
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 : is_compact s, from (compact_range ha.continuous).union (compact_range hb.continuous),
letI : metric_space (subtype s) := by apply_instance,
haveI : compact_space (subtype s) := ⟨compact_iff_compact_univ.1 ‹is_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_coe) },
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 Φ'), ⟨(range_nonempty _).image _,
(compact_range IΦ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩,
let B : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Ψ'), ⟨(range_nonempty _).image _,
(compact_range IΨ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩,
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 [lower_bounds], 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
/-- 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
inhabit α, inhabit β,
/- 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 := Φrange ▸ mem_range_self _,
exact exists_dist_lt_of_Hausdorff_dist_lt this bound
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) },
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 α) := Φisom.diam_range,
have DΨ : diam (range Ψ) = diam (univ : set β) := Ψisom.diam_range,
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 x y },
{ exact λx y, calc
F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl
... = dist x y : Ψisom.dist_eq x y },
{ 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 (p.2.2.union q.2.2).bounded,
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_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded)
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) y
... = 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_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded)
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) x
... = 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,
{ refine (set.nonempty.prod _ _).image _; exact ⟨_, rfl⟩ },
{ 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 hΦ.is_closed }` in the next
-- proof is very slow, as the `t2_space` instance is very hard to find
local attribute [instance, priority 10] order_topology.t2_space
local attribute [instance, priority 10] order_closed_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,
{ exact (nonempty.prod ⟨y, hy⟩ ⟨y, hy⟩).image _ },
{ 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, 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Φ : is_compact (range Φ) := compact_range Φisom.continuous,
have hΨ : is_compact (range Ψ) := compact_range Ψisom.continuous,
apply (Hausdorff_dist_zero_iff_eq_of_closed _ _ _).1 (DΦΨ.symm),
{ exact hΦ.is_closed },
{ exact hΨ.is_closed },
{ exact Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _)
(range_nonempty _) hΦ.bounded hΨ.bounded } },
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_nonempty_of_bounded
(range_nonempty _) (range_nonempty _) _ _),
{ exact (compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injl X Y)))).bounded },
{ exact (compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injr X Y)))).bounded }
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 (coe : p.val → α) := isometry_subtype_coe,
have hb : isometry (coe : q.val → α) := isometry_subtype_coe,
have A : dist p q = Hausdorff_dist p.val q.val := rfl,
have I : p.val = range (coe : p.val → α), by simp,
have J : q.val = range (coe : 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) :=
lipschitz_with.mk_one 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.continuous
end nonempty_compacts
section
/- In this section, we show that if two metric spaces are isometric up to `ε₂`, then their
Gromov-Hausdorff distance is bounded by `ε₂ / 2`. More generally, if there are subsets which are
`ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff distance
between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. 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 β]
-- we want to ignore these instances in the following theorem
local attribute [instance, priority 10] sum.topological_space sum.uniform_space
/-- If there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and
isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by
`ε₁ + ε₂/2 + ε₃`. -/
theorem GH_dist_le_of_approx_subsets {s : set α} (Φ : s → β) {ε₁ ε₂ ε₃ : ℝ}
(hs : ∀x : α, ∃y ∈ s, dist x y ≤ ε₁) (hs' : ∀x : β, ∃y : s, dist x (Φ y) ≤ ε₃)
(H : ∀x y : s, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε₂) :
GH_dist α β ≤ ε₁ + ε₂ / 2 + ε₃ :=
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.nonempty := ⟨xs, hxs⟩,
letI : nonempty s := sne.to_subtype,
have : 0 ≤ ε₂ := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩),
have : ∀ p q : s, abs (dist p q - dist (Φ p) (Φ q)) ≤ 2 * (ε₂/2 + δ) := λp q, calc
abs (dist p q - dist (Φ p) (Φ q)) ≤ ε₂ : H p q
... ≤ 2 * (ε₂/2 + δ) : by linarith,
-- glue `α` and `β` along the almost matching subsets
letI : metric_space (α ⊕ β) := glue_metric_approx (λ x:s, (x:α)) (λx, Φ x) (ε₂/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 `ε₁`, by `ε₁`-density. The third one is bounded by `ε₃`. And the middle one is bounded by `ε₂/2`
as in the coupling the points `x` and `Φ x` are at distance `ε₂/2` by construction of the coupling
(in fact `ε₂/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) := (compact_range Il.continuous).bounded,
exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded
(range_nonempty _) (sne.image _) B (B.subset (image_subset_range _ _))) },
have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ))
+ Hausdorff_dist (Fr '' (range Φ)) (range Fr),
{ have B : bounded (range Fr) := (compact_range Ir.continuous).bounded,
exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_nonempty_of_bounded
((range_nonempty _).image _) (range_nonempty _)
(bounded.subset (image_subset_range _ _) B) B) },
have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε₁,
{ rw [← image_univ, Hausdorff_dist_image Il],
have : 0 ≤ ε₁ := 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 + δ,
{ 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 (λ x:s, (x:α)) Φ (ε₂/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 + δ) x) } },
have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε₃,
{ rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir],
rcases exists_mem_of_nonempty β with ⟨xβ, _⟩,
rcases hs' xβ with ⟨xs', Dxs'⟩,
have : 0 ≤ ε₃ := 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. -/
instance 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 between 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).symm a) ((E p).symm 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).symm (fin.cast Npq ((E p) 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 ⟨y, ys⟩,
let hi := ((E q) ⟨y, ys⟩).is_lt,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk],
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨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 x,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)), by { simp [Ψ] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j : ℕ := E p y,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)).1, by { simp [Ψ] },
-- Express `dist x y` in terms of `F p`
have : (F p).2 ((E p) x) ((E p) y) = floor (ε⁻¹ * dist x y),
by simp only [F, (E p).symm_apply_apply],
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) (Ψ x)) ((E q) (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by simp only [F, (E q).symm_apply_apply],
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.2 ε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 spaces 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 (𝓝 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).symm a) ((E p).symm 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).symm (fin.cast Npq ((E p) 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 ⟨y, ys⟩,
let hi := ((E q) ⟨y, ys⟩).2,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk],
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨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 x,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)), by { simp [Ψ] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j : ℕ := E p y,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)), by { simp [Ψ] },
-- 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) x) ((E p) y)).1 :
by { congr; apply (fin.ext_iff _ _).2; refl }
... = min M (floor (ε⁻¹ * dist x y)).to_nat :
by simp only [F, (E p).symm_apply_apply]
... = (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.2 εpos)),
change dist (x : p.rep) y ≤ C,
refine le_trans (dist_le_diam_of_mem compact_univ.bounded (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) (Ψ x)) ((E q) (Ψ 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).symm_apply_apply]
... = (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.2 εpos)),
change dist (Ψ x : q.rep) (Ψ y) ≤ C,
refine le_trans (dist_le_diam_of_mem compact_univ.bounded (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.2 εpos)) dist_nonneg),
have D' : floor (ε⁻¹ * dist (Ψ x) (Ψ y)) ≥ 0 :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 ε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.2 ε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)]
/-- Auxiliary structure used to glue metric spaces below, recording an isometric embedding
of a type `A` in another metric space. -/
structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 :=
(space : Type)
(metric : metric_space space)
(embed : A → space)
(isom : isometry embed)
/-- Auxiliary sequence of metric spaces, containing copies of `X 0`, ..., `X n`, where each
`X i` is glued to `X (i+1)` in an optimal way. The space at step `n+1` is obtained from the space
at step `n` by adding `X (n+1)`, glued in an optimal way to the `X n` already sitting there. -/
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,
⟨range_nonempty _, 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 (𝓝 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
|
893ff50bd8ba7b44a7dc67354032d3732f1f666f | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /library/data/quotient/classical.lean | 88447d6b90ec21eb2a411e93fb8cc44c21928e84 | [
"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 | 2,094 | 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 algebra.relation data.subtype logic.axioms.classical logic.axioms.hilbert logic.axioms.funext
import .basic
namespace quotient
open relation nonempty subtype
-- abstract quotient
-- -----------------
definition prelim_map {A : Type} (R : A → A → Prop) (a : A) :=
-- TODO: it is interesting how the elaborator fails here
-- epsilon (fun b, R a b)
@epsilon _ (nonempty.intro a) (fun b, R a b)
-- TODO: only needed R reflexive (or weaker: R a a)
theorem prelim_map_rel {A : Type} {R : A → A → Prop} (H : is_equivalence R) (a : A)
: R a (prelim_map R a) :=
have reflR : reflexive R, from is_equivalence.refl R,
epsilon_spec (exists.intro a (reflR a))
-- TODO: only needed: R PER
theorem prelim_map_congr {A : Type} {R : A → A → Prop} (H1 : is_equivalence R) {a b : A}
(H2 : R a b) : prelim_map R a = prelim_map R b :=
have symmR : relation.symmetric R, from is_equivalence.symm R,
have transR : relation.transitive R, from is_equivalence.trans R,
have H3 : ∀c, R a c ↔ R b c, from
take c,
iff.intro
(assume H4 : R a c, transR (symmR H2) H4)
(assume H4 : R b c, transR H2 H4),
have H4 : (fun c, R a c) = (fun c, R b c), from
funext (take c, eq.of_iff (H3 c)),
have H5 [visible] : nonempty A, from
nonempty.intro a,
show epsilon (λc, R a c) = epsilon (λc, R b c), from
congr_arg _ H4
definition quotient {A : Type} (R : A → A → Prop) : Type := image (prelim_map R)
definition quotient_abs {A : Type} (R : A → A → Prop) : A → quotient R :=
fun_image (prelim_map R)
definition quotient_elt_of {A : Type} (R : A → A → Prop) : quotient R → A := elt_of
-- TODO: I had to make is_quotient transparent -- change this?
theorem quotient_is_quotient {A : Type} (R : A → A → Prop) (H : is_equivalence R)
: is_quotient R (quotient_abs R) (quotient_elt_of R) :=
representative_map_to_quotient_equiv
H
(prelim_map_rel H)
(@prelim_map_congr _ _ H)
end quotient
|
5515f31430e62bd73029c3d85eb48ac26d4ebc22 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/sites/cover_preserving.lean | c0d61ab09942777925274d0948a174fd218a609d | [
"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,474 | lean | /-
Copyright (c) 2021 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import category_theory.sites.limits
import category_theory.functor.flat
import category_theory.limits.preserves.filtered
import category_theory.sites.left_exact
/-!
# Cover-preserving functors between sites.
We define cover-preserving functors between sites as functors that push covering sieves to
covering sieves. A cover-preserving and compatible-preserving functor `G : C ⥤ D` then pulls
sheaves on `D` back to sheaves on `C` via `G.op ⋙ -`.
## Main definitions
* `category_theory.cover_preserving`: a functor between sites is cover-preserving if it
pushes covering sieves to covering sieves
* `category_theory.compatible_preserving`: a functor between sites is compatible-preserving
if it pushes compatible families of elements to compatible families.
* `category_theory.pullback_sheaf`: the pullback of a sheaf along a cover-preserving and
compatible-preserving functor.
* `category_theory.sites.pullback`: the induced functor `Sheaf K A ⥤ Sheaf J A` for a
cover-preserving and compatible-preserving functor `G : (C, J) ⥤ (D, K)`.
* `category_theory.sites.pushforward`: the induced functor `Sheaf J A ⥤ Sheaf K A` for a
cover-preserving and compatible-preserving functor `G : (C, J) ⥤ (D, K)`.
* `category_theory.sites.pushforward`: the induced functor `Sheaf J A ⥤ Sheaf K A` for a
cover-preserving and compatible-preserving functor `G : (C, J) ⥤ (D, K)`.
## Main results
- `category_theory.sites.whiskering_left_is_sheaf_of_cover_preserving`: If `G : C ⥤ D` is
cover-preserving and compatible-preserving, then `G ⋙ -` (`uᵖ`) as a functor
`(Dᵒᵖ ⥤ A) ⥤ (Cᵒᵖ ⥤ A)` of presheaves maps sheaves to sheaves.
## References
* [Elephant]: *Sketches of an Elephant*, P. T. Johnstone: C2.3.
* https://stacks.math.columbia.edu/tag/00WW
-/
universes w v₁ v₂ v₃ u₁ u₂ u₃
noncomputable theory
open category_theory
open opposite
open category_theory.presieve.family_of_elements
open category_theory.presieve
open category_theory.limits
namespace category_theory
variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]
variables {A : Type u₃} [category.{v₃} A]
variables (J : grothendieck_topology C) (K : grothendieck_topology D)
variables {L : grothendieck_topology A}
/--
A functor `G : (C, J) ⥤ (D, K)` between sites is *cover-preserving*
if for all covering sieves `R` in `C`, `R.pushforward_functor G` is a covering sieve in `D`.
-/
@[nolint has_nonempty_instance]
structure cover_preserving (G : C ⥤ D) : Prop :=
(cover_preserve : ∀ {U : C} {S : sieve U} (hS : S ∈ J U), S.functor_pushforward G ∈ K (G.obj U))
/-- The identity functor on a site is cover-preserving. -/
lemma id_cover_preserving : cover_preserving J J (𝟭 _) := ⟨λ U S hS, by simpa using hS⟩
variables (J) (K)
/-- The composition of two cover-preserving functors is cover-preserving. -/
lemma cover_preserving.comp {F} (hF : cover_preserving J K F) {G} (hG : cover_preserving K L G) :
cover_preserving J L (F ⋙ G) := ⟨λ U S hS,
begin
rw sieve.functor_pushforward_comp,
exact hG.cover_preserve (hF.cover_preserve hS)
end⟩
/--
A functor `G : (C, J) ⥤ (D, K)` between sites is called compatible preserving if for each
compatible family of elements at `C` and valued in `G.op ⋙ ℱ`, and each commuting diagram
`f₁ ≫ G.map g₁ = f₂ ≫ G.map g₂`, `x g₁` and `x g₂` coincide when restricted via `fᵢ`.
This is actually stronger than merely preserving compatible families because of the definition of
`functor_pushforward` used.
-/
@[nolint has_nonempty_instance]
structure compatible_preserving (K : grothendieck_topology D) (G : C ⥤ D) : Prop :=
(compatible :
∀ (ℱ : SheafOfTypes.{w} K) {Z} {T : presieve Z}
{x : family_of_elements (G.op ⋙ ℱ.val) T} (h : x.compatible)
{Y₁ Y₂} {X} (f₁ : X ⟶ G.obj Y₁) (f₂ : X ⟶ G.obj Y₂) {g₁ : Y₁ ⟶ Z} {g₂ : Y₂ ⟶ Z}
(hg₁ : T g₁) (hg₂ : T g₂) (eq : f₁ ≫ G.map g₁ = f₂ ≫ G.map g₂),
ℱ.val.map f₁.op (x g₁ hg₁) = ℱ.val.map f₂.op (x g₂ hg₂))
variables {J K} {G : C ⥤ D} (hG : compatible_preserving.{w} K G) (ℱ : SheafOfTypes.{w} K) {Z : C}
variables {T : presieve Z} {x : family_of_elements (G.op ⋙ ℱ.val) T} (h : x.compatible)
include h hG
/-- `compatible_preserving` functors indeed preserve compatible families. -/
lemma presieve.family_of_elements.compatible.functor_pushforward :
(x.functor_pushforward G).compatible :=
begin
rintros Z₁ Z₂ W g₁ g₂ f₁' f₂' H₁ H₂ eq,
unfold family_of_elements.functor_pushforward,
rcases get_functor_pushforward_structure H₁ with ⟨X₁, f₁, h₁, hf₁, rfl⟩,
rcases get_functor_pushforward_structure H₂ with ⟨X₂, f₂, h₂, hf₂, rfl⟩,
suffices : ℱ.val.map (g₁ ≫ h₁).op (x f₁ hf₁) = ℱ.val.map (g₂ ≫ h₂).op (x f₂ hf₂),
simpa using this,
apply hG.compatible ℱ h _ _ hf₁ hf₂,
simpa using eq
end
@[simp] lemma compatible_preserving.apply_map {Y : C} {f : Y ⟶ Z} (hf : T f) :
x.functor_pushforward G (G.map f) (image_mem_functor_pushforward G T hf) = x f hf :=
begin
unfold family_of_elements.functor_pushforward,
rcases e₁ : get_functor_pushforward_structure (image_mem_functor_pushforward G T hf) with
⟨X, g, f', hg, eq⟩,
simpa using hG.compatible ℱ h f' (𝟙 _) hg hf (by simp[eq])
end
omit h hG
open limits.walking_cospan
lemma compatible_preserving_of_flat {C : Type u₁} [category.{v₁} C] {D : Type u₁} [category.{v₁} D]
(K : grothendieck_topology D) (G : C ⥤ D) [representably_flat G] : compatible_preserving K G :=
begin
constructor,
intros ℱ Z T x hx Y₁ Y₂ X f₁ f₂ g₁ g₂ hg₁ hg₂ e,
/- First, `f₁` and `f₂` form a cone over `cospan g₁ g₂ ⋙ u`. -/
let c : cone (cospan g₁ g₂ ⋙ G) :=
(cones.postcompose (diagram_iso_cospan (cospan g₁ g₂ ⋙ G)).inv).obj
(pullback_cone.mk f₁ f₂ e),
/-
This can then be viewed as a cospan of structured arrows, and we may obtain an arbitrary cone
over it since `structured_arrow W u` is cofiltered.
Then, it suffices to prove that it is compatible when restricted onto `u(c'.X.right)`.
-/
let c' := is_cofiltered.cone (structured_arrow_cone.to_diagram c ⋙ structured_arrow.pre _ _ _),
have eq₁ : f₁ = (c'.X.hom ≫ G.map (c'.π.app left).right) ≫ eq_to_hom (by simp),
{ erw ← (c'.π.app left).w, dsimp, simp },
have eq₂ : f₂ = (c'.X.hom ≫ G.map (c'.π.app right).right) ≫ eq_to_hom (by simp),
{ erw ← (c'.π.app right).w, dsimp, simp },
conv_lhs { rw eq₁ },
conv_rhs { rw eq₂ },
simp only [op_comp, functor.map_comp, types_comp_apply, eq_to_hom_op, eq_to_hom_map],
congr' 1,
/-
Since everything now falls in the image of `u`,
the result follows from the compatibility of `x` in the image of `u`.
-/
injection c'.π.naturality walking_cospan.hom.inl with _ e₁,
injection c'.π.naturality walking_cospan.hom.inr with _ e₂,
exact hx (c'.π.app left).right (c'.π.app right).right hg₁ hg₂ (e₁.symm.trans e₂)
end
/--
If `G` is cover-preserving and compatible-preserving,
then `G.op ⋙ _` pulls sheaves back to sheaves.
This result is basically <https://stacks.math.columbia.edu/tag/00WW>.
-/
theorem pullback_is_sheaf_of_cover_preserving {G : C ⥤ D} (hG₁ : compatible_preserving.{v₃} K G)
(hG₂ : cover_preserving J K G) (ℱ : Sheaf K A) :
presheaf.is_sheaf J (G.op ⋙ ℱ.val) :=
begin
intros X U S hS x hx,
change family_of_elements (G.op ⋙ ℱ.val ⋙ coyoneda.obj (op X)) _ at x,
let H := ℱ.2 X _ (hG₂.cover_preserve hS),
let hx' := hx.functor_pushforward hG₁ (sheaf_over ℱ X),
split, swap,
{ apply H.amalgamate (x.functor_pushforward G),
exact hx' },
split,
{ intros V f hf,
convert H.is_amalgamation hx' (G.map f) (image_mem_functor_pushforward G S hf),
rw hG₁.apply_map (sheaf_over ℱ X) hx },
{ intros y hy,
refine H.is_separated_for _ y _ _
(H.is_amalgamation (hx.functor_pushforward hG₁ (sheaf_over ℱ X))),
rintros V f ⟨Z, f', g', h, rfl⟩,
erw family_of_elements.comp_of_compatible (S.functor_pushforward G)
hx' (image_mem_functor_pushforward G S h) g',
dsimp,
simp [hG₁.apply_map (sheaf_over ℱ X) hx h, ←hy f' h] }
end
/-- The pullback of a sheaf along a cover-preserving and compatible-preserving functor. -/
def pullback_sheaf {G : C ⥤ D} (hG₁ : compatible_preserving K G)
(hG₂ : cover_preserving J K G) (ℱ : Sheaf K A) : Sheaf J A :=
⟨G.op ⋙ ℱ.val, pullback_is_sheaf_of_cover_preserving hG₁ hG₂ ℱ⟩
variable (A)
/--
The induced functor from `Sheaf K A ⥤ Sheaf J A` given by `G.op ⋙ _`
if `G` is cover-preserving and compatible-preserving.
-/
@[simps] def sites.pullback {G : C ⥤ D} (hG₁ : compatible_preserving K G)
(hG₂ : cover_preserving J K G) : Sheaf K A ⥤ Sheaf J A :=
{ obj := λ ℱ, pullback_sheaf hG₁ hG₂ ℱ,
map := λ _ _ f, ⟨(((whiskering_left _ _ _).obj G.op)).map f.val⟩,
map_id' := λ ℱ, by { ext1, apply (((whiskering_left _ _ _).obj G.op)).map_id },
map_comp' := λ _ _ _ f g, by { ext1, apply (((whiskering_left _ _ _).obj G.op)).map_comp } }
end category_theory
namespace category_theory
variables {C : Type v₁} [small_category C] {D : Type v₁} [small_category D]
variables (A : Type u₂) [category.{v₁} A]
variables (J : grothendieck_topology C) (K : grothendieck_topology D)
instance [has_limits A] : creates_limits (Sheaf_to_presheaf J A) :=
category_theory.Sheaf.category_theory.Sheaf_to_presheaf.category_theory.creates_limits.{u₂ v₁ v₁}
-- The assumptions so that we have sheafification
variables [concrete_category.{v₁} A] [preserves_limits (forget A)] [has_colimits A] [has_limits A]
variables [preserves_filtered_colimits (forget A)] [reflects_isomorphisms (forget A)]
local attribute [instance] reflects_limits_of_reflects_isomorphisms
instance {X : C} : is_cofiltered (J.cover X) := infer_instance
/-- The pushforward functor `Sheaf J A ⥤ Sheaf K A` associated to a functor `G : C ⥤ D` in the
same direction as `G`. -/
@[simps] def sites.pushforward (G : C ⥤ D) : Sheaf J A ⥤ Sheaf K A :=
Sheaf_to_presheaf J A ⋙ Lan G.op ⋙ presheaf_to_Sheaf K A
instance (G : C ⥤ D) [representably_flat G] :
preserves_finite_limits (sites.pushforward A J K G) :=
begin
apply_with comp_preserves_finite_limits { instances := ff },
{ apply_instance },
apply_with comp_preserves_finite_limits { instances := ff },
{ apply category_theory.Lan_preserves_finite_limits_of_flat },
{ apply category_theory.presheaf_to_Sheaf.limits.preserves_finite_limits.{u₂ v₁ v₁},
apply_instance }
end
/-- The pushforward functor is left adjoint to the pullback functor. -/
def sites.pullback_pushforward_adjunction {G : C ⥤ D} (hG₁ : compatible_preserving K G)
(hG₂ : cover_preserving J K G) : sites.pushforward A J K G ⊣ sites.pullback A hG₁ hG₂ :=
((Lan.adjunction A G.op).comp (sheafification_adjunction K A)).restrict_fully_faithful
(Sheaf_to_presheaf J A) (𝟭 _)
(nat_iso.of_components (λ _, iso.refl _)
(λ _ _ _,(category.comp_id _).trans (category.id_comp _).symm))
(nat_iso.of_components (λ _, iso.refl _)
(λ _ _ _,(category.comp_id _).trans (category.id_comp _).symm))
end category_theory
|
cc3c009e33281adca467e49cd0dcb45a3db0d49a | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/print_reducible.lean | f8fcad7c99b1077fa3ebe21af47fb0e5d7d3f761 | [
"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 | 448 | lean | prelude
attribute [reducible]
definition id₁ {A : Type} (a : A) := a
attribute [reducible]
definition id₂ {A : Type} (a : A) := a
attribute [irreducible]
definition id₅ {A : Type} (a : A) := a
attribute [irreducible]
definition id₆ {A : Type} (a : A) := a
attribute [reducible]
definition pr {A B : Type} (a : A) (b : B) := a
definition pr2 {A B : Type} (a : A) (b : B) := a
#print [reducible]
#print "-----------"
#print [irreducible]
|
2a4e77faf09470c58860dda3c455fba03849e39b | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/measure_theory/lebesgue_measure.lean | 90bedca0bbf4ae9f0e45601996caf54f72830981 | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 23,780 | 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, Yury Kudryashov
-/
import measure_theory.pi
/-!
# Lebesgue measure on the real line and on `ℝⁿ`
-/
noncomputable theory
open classical set filter
open ennreal (of_real)
open_locale big_operators ennreal nnreal
namespace measure_theory
/-!
### Preliminary definitions
-/
/-- Length of an interval. This is the largest monotonic function which correctly
measures all intervals. -/
def lebesgue_length (s : set ℝ) : ℝ≥0∞ := ⨅a b (h : s ⊆ Ico a b), of_real (b - a)
@[simp] lemma lebesgue_length_empty : lebesgue_length ∅ = 0 :=
nonpos_iff_eq_zero.1 $ infi_le_of_le 0 $ infi_le_of_le 0 $ by simp
@[simp] lemma lebesgue_length_Ico (a b : ℝ) :
lebesgue_length (Ico a b) = of_real (b - a) :=
begin
refine le_antisymm (infi_le_of_le a $ binfi_le b (subset.refl _))
(le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, ennreal.coe_le_coe.2 _),
cases le_or_lt b a with ab ab,
{ rw real.to_nnreal_of_nonpos (sub_nonpos.2 ab), apply zero_le },
cases (Ico_subset_Ico_iff ab).1 h with h₁ h₂,
exact real.to_nnreal_le_to_nnreal (sub_le_sub h₂ h₁)
end
lemma lebesgue_length_mono {s₁ s₂ : set ℝ} (h : s₁ ⊆ s₂) :
lebesgue_length s₁ ≤ lebesgue_length s₂ :=
infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h', ⟨subset.trans h h', le_refl _⟩
lemma lebesgue_length_eq_infi_Ioo (s) :
lebesgue_length s = ⨅a b (h : s ⊆ Ioo a b), of_real (b - a) :=
begin
refine le_antisymm
(infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h,
⟨subset.trans h Ioo_subset_Ico_self, le_refl _⟩) _,
refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _),
refine ennreal.le_of_forall_pos_le_add (λ ε ε0 _, _),
refine infi_le_of_le (a - ε) (infi_le_of_le b $ infi_le_of_le
(subset.trans h $ Ico_subset_Ioo_left $ (sub_lt_self_iff _).2 ε0) _),
rw ← sub_add,
refine le_trans ennreal.of_real_add_le (add_le_add_left _ _),
simp only [ennreal.of_real_coe_nnreal, le_refl]
end
@[simp] lemma lebesgue_length_Ioo (a b : ℝ) :
lebesgue_length (Ioo a b) = of_real (b - a) :=
begin
rw ← lebesgue_length_Ico,
refine le_antisymm (lebesgue_length_mono Ioo_subset_Ico_self) _,
rw lebesgue_length_eq_infi_Ioo (Ioo a b),
refine (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, _),
cases le_or_lt b a with ab ab, {simp [ab]},
cases (Ioo_subset_Ioo_iff ab).1 h with h₁ h₂,
rw [lebesgue_length_Ico],
exact ennreal.of_real_le_of_real (sub_le_sub h₂ h₁)
end
lemma lebesgue_length_eq_infi_Icc (s) :
lebesgue_length s = ⨅a b (h : s ⊆ Icc a b), of_real (b - a) :=
begin
refine le_antisymm _
(infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h,
⟨subset.trans h Ico_subset_Icc_self, le_refl _⟩),
refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _),
refine ennreal.le_of_forall_pos_le_add (λ ε ε0 _, _),
refine infi_le_of_le a (infi_le_of_le (b + ε) $ infi_le_of_le
(subset.trans h $ Icc_subset_Ico_right $ (lt_add_iff_pos_right _).2 ε0) _),
rw [← sub_add_eq_add_sub],
refine le_trans ennreal.of_real_add_le (add_le_add_left _ _),
simp only [ennreal.of_real_coe_nnreal, le_refl]
end
@[simp] lemma lebesgue_length_Icc (a b : ℝ) :
lebesgue_length (Icc a b) = of_real (b - a) :=
begin
rw ← lebesgue_length_Ico,
refine le_antisymm _ (lebesgue_length_mono Ico_subset_Icc_self),
rw lebesgue_length_eq_infi_Icc (Icc a b),
exact infi_le_of_le a (infi_le_of_le b $ infi_le_of_le (by refl) (by simp [le_refl]))
end
/-- The Lebesgue outer measure, as an outer measure of ℝ. -/
def lebesgue_outer : outer_measure ℝ :=
outer_measure.of_function lebesgue_length lebesgue_length_empty
lemma lebesgue_outer_le_length (s : set ℝ) : lebesgue_outer s ≤ lebesgue_length s :=
outer_measure.of_function_le _
lemma lebesgue_length_subadditive {a b : ℝ} {c d : ℕ → ℝ}
(ss : Icc a b ⊆ ⋃i, Ioo (c i) (d i)) :
(of_real (b - a) : ℝ≥0∞) ≤ ∑' i, of_real (d i - c i) :=
begin
suffices : ∀ (s:finset ℕ) b
(cv : Icc a b ⊆ ⋃ i ∈ (↑s:set ℕ), Ioo (c i) (d i)),
(of_real (b - a) : ℝ≥0∞) ≤ ∑ i in s, of_real (d i - c i),
{ rcases is_compact_Icc.elim_finite_subcover_image (λ (i : ℕ) (_ : i ∈ univ),
@is_open_Ioo _ _ _ _ (c i) (d i)) (by simpa using ss) with ⟨s, su, hf, hs⟩,
have e : (⋃ i ∈ (↑hf.to_finset:set ℕ),
Ioo (c i) (d i)) = (⋃ i ∈ s, Ioo (c i) (d i)), {simp [set.ext_iff]},
rw ennreal.tsum_eq_supr_sum,
refine le_trans _ (le_supr _ hf.to_finset),
exact this hf.to_finset _ (by simpa [e]) },
clear ss b,
refine λ s, finset.strong_induction_on s (λ s IH b cv, _),
cases le_total b a with ab ab,
{ rw ennreal.of_real_eq_zero.2 (sub_nonpos.2 ab), exact zero_le _ },
have := cv ⟨ab, le_refl _⟩, simp at this,
rcases this with ⟨i, is, cb, bd⟩,
rw [← finset.insert_erase is] at cv ⊢,
rw [finset.coe_insert, bUnion_insert] at cv,
rw [finset.sum_insert (finset.not_mem_erase _ _)],
refine le_trans _ (add_le_add_left (IH _ (finset.erase_ssubset is) (c i) _) _),
{ refine le_trans (ennreal.of_real_le_of_real _) ennreal.of_real_add_le,
rw sub_add_sub_cancel,
exact sub_le_sub_right (le_of_lt bd) _ },
{ rintro x ⟨h₁, h₂⟩,
refine (cv ⟨h₁, le_trans h₂ (le_of_lt cb)⟩).resolve_left
(mt and.left (not_lt_of_le h₂)) }
end
@[simp] lemma lebesgue_outer_Icc (a b : ℝ) :
lebesgue_outer (Icc a b) = of_real (b - a) :=
begin
refine le_antisymm (by rw ← lebesgue_length_Icc; apply lebesgue_outer_le_length)
(le_binfi $ λ f hf, ennreal.le_of_forall_pos_le_add $ λ ε ε0 h, _),
rcases ennreal.exists_pos_sum_of_encodable
(ennreal.zero_lt_coe_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩,
refine le_trans _ (add_le_add_left (le_of_lt hε) _),
rw ← ennreal.tsum_add,
choose g hg using show
∀ i, ∃ p:ℝ×ℝ, f i ⊆ Ioo p.1 p.2 ∧ (of_real (p.2 - p.1) : ℝ≥0∞) <
lebesgue_length (f i) + ε' i,
{ intro i,
have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h)
(ennreal.zero_lt_coe_iff.2 (ε'0 i))),
conv at this {to_lhs, rw lebesgue_length_eq_infi_Ioo},
simpa [infi_lt_iff] },
refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hg i).2),
exact lebesgue_length_subadditive (subset.trans hf $
Union_subset_Union $ λ i, (hg i).1)
end
@[simp] lemma lebesgue_outer_singleton (a : ℝ) : lebesgue_outer {a} = 0 :=
by simpa using lebesgue_outer_Icc a a
@[simp] lemma lebesgue_outer_Ico (a b : ℝ) :
lebesgue_outer (Ico a b) = of_real (b - a) :=
by rw [← Icc_diff_right, lebesgue_outer.diff_null _ (lebesgue_outer_singleton _),
lebesgue_outer_Icc]
@[simp] lemma lebesgue_outer_Ioo (a b : ℝ) :
lebesgue_outer (Ioo a b) = of_real (b - a) :=
by rw [← Ico_diff_left, lebesgue_outer.diff_null _ (lebesgue_outer_singleton _), lebesgue_outer_Ico]
@[simp] lemma lebesgue_outer_Ioc (a b : ℝ) :
lebesgue_outer (Ioc a b) = of_real (b - a) :=
by rw [← Icc_diff_left, lebesgue_outer.diff_null _ (lebesgue_outer_singleton _), lebesgue_outer_Icc]
lemma is_lebesgue_measurable_Iio {c : ℝ} :
lebesgue_outer.caratheodory.measurable_set' (Iio c) :=
outer_measure.of_function_caratheodory $ λ t,
le_infi $ λ a, le_infi $ λ b, le_infi $ λ h, begin
refine le_trans (add_le_add
(lebesgue_length_mono $ inter_subset_inter_left _ h)
(lebesgue_length_mono $ diff_subset_diff_left h)) _,
cases le_total a c with hac hca; cases le_total b c with hbc hcb;
simp [*, -sub_eq_add_neg, sub_add_sub_cancel', le_refl],
{ simp [*, ← ennreal.of_real_add, -sub_eq_add_neg, sub_add_sub_cancel', le_refl] },
{ simp only [ennreal.of_real_eq_zero.2 (sub_nonpos.2 (le_trans hbc hca)), zero_add, le_refl] }
end
theorem lebesgue_outer_trim : lebesgue_outer.trim = lebesgue_outer :=
begin
refine le_antisymm (λ s, _) (outer_measure.le_trim _),
rw outer_measure.trim_eq_infi,
refine le_infi (λ f, le_infi $ λ hf,
ennreal.le_of_forall_pos_le_add $ λ ε ε0 h, _),
rcases ennreal.exists_pos_sum_of_encodable
(ennreal.zero_lt_coe_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩,
refine le_trans _ (add_le_add_left (le_of_lt hε) _),
rw ← ennreal.tsum_add,
choose g hg using show
∀ i, ∃ s, f i ⊆ s ∧ measurable_set s ∧
lebesgue_outer s ≤ lebesgue_length (f i) + of_real (ε' i),
{ intro i,
have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h)
(ennreal.zero_lt_coe_iff.2 (ε'0 i))),
conv at this {to_lhs, rw lebesgue_length},
simp only [infi_lt_iff] at this,
rcases this with ⟨a, b, h₁, h₂⟩,
rw ← lebesgue_outer_Ico at h₂,
exact ⟨_, h₁, measurable_set_Ico, le_of_lt $ by simpa using h₂⟩ },
simp at hg,
apply infi_le_of_le (Union g) _,
apply infi_le_of_le (subset.trans hf $ Union_subset_Union (λ i, (hg i).1)) _,
apply infi_le_of_le (measurable_set.Union (λ i, (hg i).2.1)) _,
exact le_trans (lebesgue_outer.Union _) (ennreal.tsum_le_tsum $ λ i, (hg i).2.2)
end
lemma borel_le_lebesgue_measurable : borel ℝ ≤ lebesgue_outer.caratheodory :=
begin
rw real.borel_eq_generate_from_Iio_rat,
refine measurable_space.generate_from_le _,
simp [is_lebesgue_measurable_Iio] { contextual := tt }
end
/-!
### Definition of the Lebesgue measure and lengths of intervals
-/
/-- Lebesgue measure on the Borel sets
The outer Lebesgue measure is the completion of this measure. (TODO: proof this)
-/
instance real.measure_space : measure_space ℝ :=
⟨{to_outer_measure := lebesgue_outer,
m_Union := λ f hf, lebesgue_outer.Union_eq_of_caratheodory $
λ i, borel_le_lebesgue_measurable _ (hf i),
trimmed := lebesgue_outer_trim }⟩
@[simp] theorem lebesgue_to_outer_measure :
(volume : measure ℝ).to_outer_measure = lebesgue_outer := rfl
end measure_theory
open measure_theory
namespace real
variables {ι : Type*} [fintype ι]
open_locale topological_space
theorem volume_val (s) : volume s = lebesgue_outer s := rfl
instance has_no_atoms_volume : has_no_atoms (volume : measure ℝ) :=
⟨lebesgue_outer_singleton⟩
@[simp] lemma volume_Ico {a b : ℝ} : volume (Ico a b) = of_real (b - a) := lebesgue_outer_Ico a b
@[simp] lemma volume_Icc {a b : ℝ} : volume (Icc a b) = of_real (b - a) := lebesgue_outer_Icc a b
@[simp] lemma volume_Ioo {a b : ℝ} : volume (Ioo a b) = of_real (b - a) := lebesgue_outer_Ioo a b
@[simp] lemma volume_Ioc {a b : ℝ} : volume (Ioc a b) = of_real (b - a) := lebesgue_outer_Ioc a b
@[simp] lemma volume_singleton {a : ℝ} : volume ({a} : set ℝ) = 0 := lebesgue_outer_singleton a
@[simp] lemma volume_interval {a b : ℝ} : volume (interval a b) = of_real (abs (b - a)) :=
by rw [interval, volume_Icc, max_sub_min_eq_abs]
@[simp] lemma volume_Ioi {a : ℝ} : volume (Ioi a) = ∞ :=
top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n,
calc (n : ℝ≥0∞) = volume (Ioo a (a + n)) : by simp
... ≤ volume (Ioi a) : measure_mono Ioo_subset_Ioi_self
@[simp] lemma volume_Ici {a : ℝ} : volume (Ici a) = ∞ :=
by simp [← measure_congr Ioi_ae_eq_Ici]
@[simp] lemma volume_Iio {a : ℝ} : volume (Iio a) = ∞ :=
top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n,
calc (n : ℝ≥0∞) = volume (Ioo (a - n) a) : by simp
... ≤ volume (Iio a) : measure_mono Ioo_subset_Iio_self
@[simp] lemma volume_Iic {a : ℝ} : volume (Iic a) = ∞ :=
by simp [← measure_congr Iio_ae_eq_Iic]
instance locally_finite_volume : locally_finite_measure (volume : measure ℝ) :=
⟨λ x, ⟨Ioo (x - 1) (x + 1),
is_open.mem_nhds is_open_Ioo ⟨sub_lt_self _ zero_lt_one, lt_add_of_pos_right _ zero_lt_one⟩,
by simp only [real.volume_Ioo, ennreal.of_real_lt_top]⟩⟩
instance finite_measure_restrict_Icc (x y : ℝ) : finite_measure (volume.restrict (Icc x y)) :=
⟨by simp⟩
instance finite_measure_restrict_Ico (x y : ℝ) : finite_measure (volume.restrict (Ico x y)) :=
⟨by simp⟩
instance finite_measure_restrict_Ioc (x y : ℝ) : finite_measure (volume.restrict (Ioc x y)) :=
⟨by simp⟩
instance finite_measure_restrict_Ioo (x y : ℝ) : finite_measure (volume.restrict (Ioo x y)) :=
⟨by simp⟩
/-!
### Volume of a box in `ℝⁿ`
-/
lemma volume_Icc_pi {a b : ι → ℝ} : volume (Icc a b) = ∏ i, ennreal.of_real (b i - a i) :=
begin
rw [← pi_univ_Icc, volume_pi_pi],
{ simp only [real.volume_Icc] },
{ exact λ i, measurable_set_Icc }
end
@[simp] lemma volume_Icc_pi_to_real {a b : ι → ℝ} (h : a ≤ b) :
(volume (Icc a b)).to_real = ∏ i, (b i - a i) :=
by simp only [volume_Icc_pi, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))]
lemma volume_pi_Ioo {a b : ι → ℝ} :
volume (pi univ (λ i, Ioo (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) :=
(measure_congr measure.univ_pi_Ioo_ae_eq_Icc).trans volume_Icc_pi
@[simp] lemma volume_pi_Ioo_to_real {a b : ι → ℝ} (h : a ≤ b) :
(volume (pi univ (λ i, Ioo (a i) (b i)))).to_real = ∏ i, (b i - a i) :=
by simp only [volume_pi_Ioo, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))]
lemma volume_pi_Ioc {a b : ι → ℝ} :
volume (pi univ (λ i, Ioc (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) :=
(measure_congr measure.univ_pi_Ioc_ae_eq_Icc).trans volume_Icc_pi
@[simp] lemma volume_pi_Ioc_to_real {a b : ι → ℝ} (h : a ≤ b) :
(volume (pi univ (λ i, Ioc (a i) (b i)))).to_real = ∏ i, (b i - a i) :=
by simp only [volume_pi_Ioc, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))]
lemma volume_pi_Ico {a b : ι → ℝ} :
volume (pi univ (λ i, Ico (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) :=
(measure_congr measure.univ_pi_Ico_ae_eq_Icc).trans volume_Icc_pi
@[simp] lemma volume_pi_Ico_to_real {a b : ι → ℝ} (h : a ≤ b) :
(volume (pi univ (λ i, Ico (a i) (b i)))).to_real = ∏ i, (b i - a i) :=
by simp only [volume_pi_Ico, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))]
lemma volume_le_diam (s : set ℝ) : volume s ≤ emetric.diam s :=
begin
by_cases hs : metric.bounded s,
{ rw [real.ediam_eq hs, ← volume_Icc],
exact volume.mono (real.subset_Icc_Inf_Sup_of_bounded hs) },
{ rw metric.ediam_of_unbounded hs, exact le_top }
end
lemma volume_pi_le_prod_diam (s : set (ι → ℝ)) :
volume s ≤ ∏ i : ι, emetric.diam (function.eval i '' s) :=
calc volume s ≤ volume (pi univ (λ i, closure (function.eval i '' s))) :
volume.mono $ subset.trans (subset_pi_eval_image univ s) $ pi_mono $ λ i hi, subset_closure
... = ∏ i, volume (closure $ function.eval i '' s) :
volume_pi_pi _ $ λ i, measurable_set_closure
... ≤ ∏ i : ι, emetric.diam (function.eval i '' s) :
finset.prod_le_prod' $ λ i hi, (volume_le_diam _).trans_eq (emetric.diam_closure _)
lemma volume_pi_le_diam_pow (s : set (ι → ℝ)) :
volume s ≤ emetric.diam s ^ fintype.card ι :=
calc volume s ≤ ∏ i : ι, emetric.diam (function.eval i '' s) : volume_pi_le_prod_diam s
... ≤ ∏ i : ι, (1 : ℝ≥0) * emetric.diam s :
finset.prod_le_prod' $ λ i hi, (lipschitz_with.eval i).ediam_image_le s
... = emetric.diam s ^ fintype.card ι :
by simp only [ennreal.coe_one, one_mul, finset.prod_const, fintype.card]
/-!
### Images of the Lebesgue measure under translation/multiplication/...
-/
lemma map_volume_add_left (a : ℝ) : measure.map ((+) a) volume = volume :=
eq.symm $ real.measure_ext_Ioo_rat $ λ p q,
by simp [measure.map_apply (measurable_const_add a) measurable_set_Ioo, sub_sub_sub_cancel_right]
lemma map_volume_add_right (a : ℝ) : measure.map (+ a) volume = volume :=
by simpa only [add_comm] using real.map_volume_add_left a
lemma smul_map_volume_mul_left {a : ℝ} (h : a ≠ 0) :
ennreal.of_real (abs a) • measure.map ((*) a) volume = volume :=
begin
refine (real.measure_ext_Ioo_rat $ λ p q, _).symm,
cases lt_or_gt_of_ne h with h h,
{ simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt $ neg_pos.2 h),
measure.map_apply (measurable_const_mul a) measurable_set_Ioo, neg_sub_neg,
← neg_mul_eq_neg_mul, preimage_const_mul_Ioo_of_neg _ _ h, abs_of_neg h, mul_sub,
mul_div_cancel' _ (ne_of_lt h)] },
{ simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt h),
measure.map_apply (measurable_const_mul a) measurable_set_Ioo, preimage_const_mul_Ioo _ _ h,
abs_of_pos h, mul_sub, mul_div_cancel' _ (ne_of_gt h)] }
end
lemma map_volume_mul_left {a : ℝ} (h : a ≠ 0) :
measure.map ((*) a) volume = ennreal.of_real (abs a⁻¹) • volume :=
by conv_rhs { rw [← real.smul_map_volume_mul_left h, smul_smul,
← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, inv_mul_cancel h, abs_one, ennreal.of_real_one,
one_smul] }
lemma smul_map_volume_mul_right {a : ℝ} (h : a ≠ 0) :
ennreal.of_real (abs a) • measure.map (* a) volume = volume :=
by simpa only [mul_comm] using real.smul_map_volume_mul_left h
lemma map_volume_mul_right {a : ℝ} (h : a ≠ 0) :
measure.map (* a) volume = ennreal.of_real (abs a⁻¹) • volume :=
by simpa only [mul_comm] using real.map_volume_mul_left h
@[simp] lemma map_volume_neg : measure.map has_neg.neg (volume : measure ℝ) = volume :=
eq.symm $ real.measure_ext_Ioo_rat $ λ p q,
by simp [show measure.map has_neg.neg volume (Ioo (p : ℝ) q) = _,
from measure.map_apply measurable_neg measurable_set_Ioo]
end real
open_locale topological_space
lemma filter.eventually.volume_pos_of_nhds_real {p : ℝ → Prop} {a : ℝ} (h : ∀ᶠ x in 𝓝 a, p x) :
(0 : ℝ≥0∞) < volume {x | p x} :=
begin
rcases h.exists_Ioo_subset with ⟨l, u, hx, hs⟩,
refine lt_of_lt_of_le _ (measure_mono hs),
simpa [-mem_Ioo] using hx.1.trans hx.2
end
section region_between
open_locale classical
variable {α : Type*}
/-- The region between two real-valued functions on an arbitrary set. -/
def region_between (f g : α → ℝ) (s : set α) : set (α × ℝ) :=
{p : α × ℝ | p.1 ∈ s ∧ p.2 ∈ Ioo (f p.1) (g p.1)}
lemma region_between_subset (f g : α → ℝ) (s : set α) : region_between f g s ⊆ s.prod univ :=
by simpa only [prod_univ, region_between, set.preimage, set_of_subset_set_of] using λ a, and.left
variables [measurable_space α] {μ : measure α} {f g : α → ℝ} {s : set α}
/-- The region between two measurable functions on a measurable set is measurable. -/
lemma measurable_set_region_between
(hf : measurable f) (hg : measurable g) (hs : measurable_set s) :
measurable_set (region_between f g s) :=
begin
dsimp only [region_between, Ioo, mem_set_of_eq, set_of_and],
refine measurable_set.inter _ ((measurable_set_lt (hf.comp measurable_fst) measurable_snd).inter
(measurable_set_lt measurable_snd (hg.comp measurable_fst))),
convert hs.prod measurable_set.univ,
simp only [and_true, mem_univ],
end
theorem volume_region_between_eq_lintegral'
(hf : measurable f) (hg : measurable g) (hs : measurable_set s) :
μ.prod volume (region_between f g s) = ∫⁻ y in s, ennreal.of_real ((g - f) y) ∂μ :=
begin
rw measure.prod_apply,
{ have h : (λ x, volume {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)})
= s.indicator (λ x, ennreal.of_real (g x - f x)),
{ funext x,
rw indicator_apply,
split_ifs,
{ have hx : {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)} = Ioo (f x) (g x) := by simp [h, Ioo],
simp only [hx, real.volume_Ioo, sub_zero] },
{ have hx : {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)} = ∅ := by simp [h],
simp only [hx, measure_empty] } },
dsimp only [region_between, preimage_set_of_eq],
rw [h, lintegral_indicator];
simp only [hs, pi.sub_apply] },
{ exact measurable_set_region_between hf hg hs },
end
/-- The volume of the region between two almost everywhere measurable functions on a measurable set
can be represented as a Lebesgue integral. -/
theorem volume_region_between_eq_lintegral [sigma_finite μ]
(hf : ae_measurable f (μ.restrict s)) (hg : ae_measurable g (μ.restrict s))
(hs : measurable_set s) :
μ.prod volume (region_between f g s) = ∫⁻ y in s, ennreal.of_real ((g - f) y) ∂μ :=
begin
have h₁ : (λ y, ennreal.of_real ((g - f) y))
=ᵐ[μ.restrict s]
λ y, ennreal.of_real ((ae_measurable.mk g hg - ae_measurable.mk f hf) y) :=
eventually_eq.fun_comp (eventually_eq.sub hg.ae_eq_mk hf.ae_eq_mk) _,
have h₂ : (μ.restrict s).prod volume (region_between f g s) =
(μ.restrict s).prod volume (region_between (ae_measurable.mk f hf) (ae_measurable.mk g hg) s),
{ apply measure_congr,
apply eventually_eq.inter, { refl },
exact eventually_eq.inter
(eventually_eq.comp₂ (ae_eq_comp' measurable_fst hf.ae_eq_mk
measure.prod_fst_absolutely_continuous) _ eventually_eq.rfl)
(eventually_eq.comp₂ eventually_eq.rfl _
(ae_eq_comp' measurable_fst hg.ae_eq_mk measure.prod_fst_absolutely_continuous)) },
rw [lintegral_congr_ae h₁,
← volume_region_between_eq_lintegral' hf.measurable_mk hg.measurable_mk hs],
convert h₂ using 1,
{ rw measure.restrict_prod_eq_prod_univ,
exacts [ (measure.restrict_eq_self_of_subset_of_measurable (hs.prod measurable_set.univ)
(region_between_subset f g s)).symm, hs], },
{ rw measure.restrict_prod_eq_prod_univ,
exacts [(measure.restrict_eq_self_of_subset_of_measurable (hs.prod measurable_set.univ)
(region_between_subset (ae_measurable.mk f hf) (ae_measurable.mk g hg) s)).symm, hs] },
end
theorem volume_region_between_eq_integral' [sigma_finite μ]
(f_int : integrable_on f s μ) (g_int : integrable_on g s μ)
(hs : measurable_set s) (hfg : f ≤ᵐ[μ.restrict s] g ) :
μ.prod volume (region_between f g s) = ennreal.of_real (∫ y in s, (g - f) y ∂μ) :=
begin
have h : g - f =ᵐ[μ.restrict s] (λ x, real.to_nnreal (g x - f x)),
{ apply hfg.mono,
simp only [real.to_nnreal, max, sub_nonneg, pi.sub_apply],
intros x hx,
split_ifs,
refl },
rw [volume_region_between_eq_lintegral f_int.ae_measurable g_int.ae_measurable hs,
integral_congr_ae h, lintegral_congr_ae,
lintegral_coe_eq_integral _ ((integrable_congr h).mp (g_int.sub f_int))],
simpa only,
end
/-- If two functions are integrable on a measurable set, and one function is less than
or equal to the other on that set, then the volume of the region
between the two functions can be represented as an integral. -/
theorem volume_region_between_eq_integral [sigma_finite μ]
(f_int : integrable_on f s μ) (g_int : integrable_on g s μ)
(hs : measurable_set s) (hfg : ∀ x ∈ s, f x ≤ g x) :
μ.prod volume (region_between f g s) = ennreal.of_real (∫ y in s, (g - f) y ∂μ) :=
volume_region_between_eq_integral' f_int g_int hs
((ae_restrict_iff' hs).mpr (eventually_of_forall hfg))
end region_between
/-
section vitali
def vitali_aux_h (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) :
∃ y ∈ Icc (0:ℝ) 1, ∃ q:ℚ, ↑q = x - y :=
⟨x, h, 0, by simp⟩
def vitali_aux (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : ℝ :=
classical.some (vitali_aux_h x h)
theorem vitali_aux_mem (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : vitali_aux x h ∈ Icc (0:ℝ) 1 :=
Exists.fst (classical.some_spec (vitali_aux_h x h):_)
theorem vitali_aux_rel (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) :
∃ q:ℚ, ↑q = x - vitali_aux x h :=
Exists.snd (classical.some_spec (vitali_aux_h x h):_)
def vitali : set ℝ := {x | ∃ h, x = vitali_aux x h}
theorem vitali_nonmeasurable : ¬ null_measurable_set measure_space.μ vitali :=
sorry
end vitali
-/
|
25c78e33d31f4ff0e2d7e62d6c0ec6e10c42180a | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/category/monad/writer.lean | 6289fd4d8834480ce3dbc96a27e5235518d09718 | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 7,037 | lean |
/-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
The writer monad transformer for passing immutable state.
-/
import tactic.basic category.monad.basic
universes u v w
structure writer_t (ω : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) :=
(run : m (α × ω))
@[reducible] def writer (ω : Type u) := writer_t ω id
attribute [pp_using_anonymous_constructor] writer_t
namespace writer_t
section
variable {ω : Type u}
variable {m : Type u → Type v}
variable [monad m]
variables {α β : Type u}
open function
@[extensionality]
protected lemma ext (x x' : writer_t ω m α)
(h : x.run = x'.run) :
x = x' := by cases x; cases x'; congr; apply h
@[inline] protected def tell (w : ω) : writer_t ω m punit :=
⟨pure (punit.star, w)⟩
@[inline] protected def listen : writer_t ω m α → writer_t ω m (α × ω)
| ⟨ cmd ⟩ := ⟨ (λ x : α × ω, ((x.1,x.2),x.2)) <$> cmd ⟩
@[inline] protected def pass : writer_t ω m (α × (ω → ω)) → writer_t ω m α
| ⟨ cmd ⟩ := ⟨ uncurry (uncurry $ λ x (f : ω → ω) w, (x,f w)) <$> cmd ⟩
@[inline] protected def pure [has_one ω] (a : α) : writer_t ω m α :=
⟨ pure (a,1) ⟩
@[inline] protected def bind [has_mul ω] (x : writer_t ω m α) (f : α → writer_t ω m β) : writer_t ω m β :=
⟨ do x ← x.run,
x' ← (f x.1).run,
pure (x'.1,x.2 * x'.2) ⟩
instance [has_one ω] [has_mul ω] : monad (writer_t ω m) :=
{ pure := λ α, writer_t.pure, bind := λ α β, writer_t.bind }
instance [monoid ω] [is_lawful_monad m] : is_lawful_monad (writer_t ω m) :=
{ id_map := by { intros, cases x, simp [(<$>),writer_t.bind,writer_t.pure] },
pure_bind := by { intros, simp [has_pure.pure,writer_t.pure,(>>=),writer_t.bind], ext; refl },
bind_assoc := by { intros, simp [(>>=),writer_t.bind,mul_assoc] with functor_norm } }
@[inline] protected def lift [has_one ω] (a : m α) : writer_t ω m α :=
⟨ flip prod.mk 1 <$> a ⟩
instance (m) [monad m] [has_one ω] : has_monad_lift m (writer_t ω m) :=
⟨ λ α, writer_t.lift ⟩
@[inline] protected def monad_map {m m'} [monad m] [monad m'] {α} (f : Π {α}, m α → m' α) : writer_t ω m α → writer_t ω m' α :=
λ x, ⟨ f x.run ⟩
instance (m m') [monad m] [monad m'] : monad_functor m m' (writer_t ω m) (writer_t ω m') :=
⟨@writer_t.monad_map ω m m' _ _⟩
@[inline] protected def adapt {ω' : Type u} [monad m] {α : Type u} (f : ω → ω') : writer_t ω m α → writer_t ω' m α :=
λ x, ⟨prod.map id f <$> x.run⟩
instance (ε) [has_one ω] [monad m] [monad_except ε m] : monad_except ε (writer_t ω m) :=
{ throw := λ α, writer_t.lift ∘ throw,
catch := λ α x c, ⟨catch x.run (λ e, (c e).run)⟩ }
end
end writer_t
/-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader).
It does not contain `local` because this function cannot be lifted using `monad_lift`.
Instead, the `monad_reader_adapter` class provides the more general `adapt_reader` function.
Note: This class can be seen as a simplification of the more "principled" definition
```
class monad_reader (ρ : out_param (Type u)) (n : Type u → Type u) :=
(lift {} {α : Type u} : (∀ {m : Type u → Type u} [monad m], reader_t ρ m α) → n α)
```
-/
class monad_writer (ω : out_param (Type u)) (m : Type u → Type v) :=
(tell {} (w : ω) : m punit)
(listen {α} : m α → m (α × ω))
(pass {α : Type u} : m (α × (ω → ω)) → m α)
export monad_writer
instance {ω : Type u} {m : Type u → Type v} [monad m] : monad_writer ω (writer_t ω m) :=
{ tell := writer_t.tell,
listen := λ α, writer_t.listen,
pass := λ α, writer_t.pass }
instance {ω ρ : Type u} {m : Type u → Type v} [monad m] [monad_writer ω m] : monad_writer ω (reader_t ρ m) :=
{ tell := λ x, monad_lift (tell x : m punit),
listen := λ α ⟨ cmd ⟩, ⟨ λ r, listen (cmd r) ⟩,
pass := λ α ⟨ cmd ⟩, ⟨ λ r, pass (cmd r) ⟩ }
def swap_right {α β γ} : (α × β) × γ → (α × γ) × β
| ⟨⟨x,y⟩,z⟩ := ((x,z),y)
instance {ω σ : Type u} {m : Type u → Type v} [monad m] [monad_writer ω m] : monad_writer ω (state_t σ m) :=
{ tell := λ x, monad_lift (tell x : m punit),
listen := λ α ⟨ cmd ⟩, ⟨ λ r, swap_right <$> listen (cmd r) ⟩,
pass := λ α ⟨ cmd ⟩, ⟨ λ r, pass (swap_right <$> cmd r) ⟩ }
open function
def except_t.pass_aux {ε α ω} : except ε (α × (ω → ω)) → except ε α × (ω → ω)
| (except.error a) := (except.error a,id)
| (except.ok (x,y)) := (except.ok x,y)
instance {ω ε : Type u} {m : Type u → Type v} [monad m] [monad_writer ω m] : monad_writer ω (except_t ε m) :=
{ tell := λ x, monad_lift (tell x : m punit),
listen := λ α ⟨ cmd ⟩, ⟨ uncurry (λ x y, flip prod.mk y <$> x) <$> listen cmd ⟩,
pass := λ α ⟨ cmd ⟩, ⟨ pass (except_t.pass_aux <$> cmd) ⟩ }
def option_t.pass_aux {α ω} : option (α × (ω → ω)) → option α × (ω → ω)
| none := (none ,id)
| (some (x,y)) := (some x,y)
instance {ω : Type u} {m : Type u → Type v} [monad m] [monad_writer ω m] : monad_writer ω (option_t m) :=
{ tell := λ x, monad_lift (tell x : m punit),
listen := λ α ⟨ cmd ⟩, ⟨ uncurry (λ x y, flip prod.mk y <$> x) <$> listen cmd ⟩,
pass := λ α ⟨ cmd ⟩, ⟨ pass (option_t.pass_aux <$> cmd) ⟩ }
/-- Adapt a monad stack, changing the type of its top-most environment.
This class is comparable to [Control.Lens.Magnify](https://hackage.haskell.org/package/lens-4.15.4/docs/Control-Lens-Zoom.html#t:Magnify), but does not use lenses (why would it), and is derived automatically for any transformer implementing `monad_functor`.
Note: This class can be seen as a simplification of the more "principled" definition
```
class monad_reader_functor (ρ ρ' : out_param (Type u)) (n n' : Type u → Type u) :=
(map {} {α : Type u} : (∀ {m : Type u → Type u} [monad m], reader_t ρ m α → reader_t ρ' m α) → n α → n' α)
```
-/
class monad_writer_adapter (ω ω' : out_param (Type u)) (m m' : Type u → Type v) :=
(adapt_writer {} {α : Type u} : (ω → ω') → m α → m' α)
export monad_writer_adapter (adapt_writer)
section
variables {ω ω' : Type u} {m m' : Type u → Type v}
instance monad_writer_adapter_trans {n n' : Type u → Type v} [monad_functor m m' n n'] [monad_writer_adapter ω ω' m m'] : monad_writer_adapter ω ω' n n' :=
⟨λ α f, monad_map (λ α, (adapt_writer f : m α → m' α))⟩
instance [monad m] : monad_writer_adapter ω ω' (writer_t ω m) (writer_t ω' m) :=
⟨λ α, writer_t.adapt⟩
end
instance (ω : Type u) (m out) [monad_run out m] : monad_run (λ α, out (α × ω)) (writer_t ω m) :=
⟨λ α x, run $ x.run ⟩
|
c5d6157620ab803c796172150a3f7da5daa3e1bd | 6094e25ea0b7699e642463b48e51b2ead6ddc23f | /tests/lean/congr_error_msg.lean | 0436d186e00835eac7164b6c5726dd3c66678e83 | [
"Apache-2.0"
] | permissive | gbaz/lean | a7835c4e3006fbbb079e8f8ffe18aacc45adebfb | a501c308be3acaa50a2c0610ce2e0d71becf8032 | refs/heads/master | 1,611,198,791,433 | 1,451,339,111,000 | 1,451,339,111,000 | 48,713,797 | 0 | 0 | null | 1,451,338,939,000 | 1,451,338,939,000 | null | UTF-8 | Lean | false | false | 803 | lean | open nat
definition g : nat → nat → nat :=
sorry
definition R : nat → nat → Prop :=
sorry
lemma C₁ [congr] : g 0 1 = g 1 0 := -- ERROR
sorry
lemma C₂ [congr] (a b : nat) : g a b = 0 := -- ERROR
sorry
lemma C₃ [congr] (a b : nat) : R (g a b) (g 0 0) := -- ERROR
sorry
lemma C₄ [congr] (A B : Type) : (A → B) = (λ a : nat, B → A) 0 := -- ERROR
sorry
lemma C₅ [congr] (A B : Type₁) : (A → nat) = (B → nat) := -- ERROR
sorry
lemma C₆ [congr] (A B : Type₁) : A = B := -- ERROR
sorry
lemma C₇ [congr] (a b c d : nat) : (∀ (x : nat), x > c → a = c) → g a b = g c d := -- ERROR
sorry
lemma C₈ [congr] (a b c d : nat) : (c = a) → g a b = g c d := -- ERROR
sorry
lemma C₉ [congr] (a b c d : nat) : (a = c) → (b = c) → g a b = g c d := -- ERROR
sorry
|
9edd52785f90b6333d70ad85077ae1e9ac2c992f | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/topology/category/TopCommRing.lean | edbb40fd35db53db86b8ac5584f93712b69863a5 | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,530 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.category.CommRing.basic
import topology.category.Top.basic
import topology.algebra.ring
/-!
# Category of topological commutative rings
We introduce the category `TopCommRing` of topological commutative rings together with the relevant
forgetful functors to topological spaces and commutative rings.
-/
universes u
open category_theory
/-- A bundled topological commutative ring. -/
structure TopCommRing :=
(α : Type u)
[is_comm_ring : comm_ring α]
[is_topological_space : topological_space α]
[is_topological_ring : topological_ring α]
namespace TopCommRing
instance : has_coe_to_sort TopCommRing (Type u) := ⟨TopCommRing.α⟩
attribute [instance] is_comm_ring is_topological_space is_topological_ring
instance : category TopCommRing.{u} :=
{ hom := λ R S, {f : R →+* S // continuous f },
id := λ R, ⟨ring_hom.id R, by obviously⟩, -- TODO remove obviously?
comp := λ R S T f g, ⟨g.val.comp f.val,
begin -- TODO automate
cases f, cases g,
dsimp, apply continuous.comp ; assumption
end⟩ }
instance : concrete_category TopCommRing.{u} :=
{ forget := { obj := λ R, R, map := λ R S f, f.val },
forget_faithful := { } }
/-- Construct a bundled `TopCommRing` from the underlying type and the appropriate typeclasses. -/
def of (X : Type u) [comm_ring X] [topological_space X] [topological_ring X] : TopCommRing := ⟨X⟩
@[simp] lemma coe_of (X : Type u) [comm_ring X] [topological_space X] [topological_ring X] :
(of X : Type u) = X := rfl
instance forget_topological_space (R : TopCommRing) :
topological_space ((forget TopCommRing).obj R) :=
R.is_topological_space
instance forget_comm_ring (R : TopCommRing) :
comm_ring ((forget TopCommRing).obj R) :=
R.is_comm_ring
instance forget_topological_ring (R : TopCommRing) :
topological_ring ((forget TopCommRing).obj R) :=
R.is_topological_ring
instance has_forget_to_CommRing : has_forget₂ TopCommRing CommRing :=
has_forget₂.mk'
(λ R, CommRing.of R)
(λ x, rfl)
(λ R S f, f.val)
(λ R S f, heq.rfl)
instance forget_to_CommRing_topological_space (R : TopCommRing) :
topological_space ((forget₂ TopCommRing CommRing).obj R) :=
R.is_topological_space
/-- The forgetful functor to Top. -/
instance has_forget_to_Top : has_forget₂ TopCommRing Top :=
has_forget₂.mk'
(λ R, Top.of R)
(λ x, rfl)
(λ R S f, ⟨⇑f.1, f.2⟩)
(λ R S f, heq.rfl)
instance forget_to_Top_comm_ring (R : TopCommRing) :
comm_ring ((forget₂ TopCommRing Top).obj R) :=
R.is_comm_ring
instance forget_to_Top_topological_ring (R : TopCommRing) :
topological_ring ((forget₂ TopCommRing Top).obj R) :=
R.is_topological_ring
/--
The forgetful functors to `Type` do not reflect isomorphisms,
but the forgetful functor from `TopCommRing` to `Top` does.
-/
instance : reflects_isomorphisms (forget₂ TopCommRing.{u} Top.{u}) :=
{ reflects := λ X Y f _,
begin
resetI,
-- We have an isomorphism in `Top`,
let i_Top := as_iso ((forget₂ TopCommRing Top).map f),
-- and a `ring_equiv`.
let e_Ring : X ≃+* Y := { ..f.1, ..((forget Top).map_iso i_Top).to_equiv },
-- Putting these together we obtain the isomorphism we're after:
exact
⟨⟨⟨e_Ring.symm, i_Top.inv.2⟩,
⟨by { ext x, exact e_Ring.left_inv x, }, by { ext x, exact e_Ring.right_inv x, }⟩⟩⟩
end }
end TopCommRing
|
bfc98fd5ae10a2d281670418bddf6d861d8754c4 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/computability/primrec.lean | 9212f83bd428cf39d2e041275665a9c186f93e9e | [
"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 | 50,158 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
The primitive recursive functions are the least collection of functions
nat → nat which are closed under projections (using the mkpair
pairing function), composition, zero, successor, and primitive recursion
(i.e. nat.rec where the motive is C n := nat).
We can extend this definition to a large class of basic types by
using canonical encodings of types as natural numbers (Gödel numbering),
which we implement through the type class `encodable`. (More precisely,
we need that the composition of encode with decode yields a
primitive recursive function, so we have the `primcodable` type class
for this.)
-/
import data.equiv.list
open denumerable encodable
namespace nat
def elim {C : Sort*} : C → (ℕ → C → C) → ℕ → C := @nat.rec (λ _, C)
@[simp] theorem elim_zero {C} (a f) : @nat.elim C a f 0 = a := rfl
@[simp] theorem elim_succ {C} (a f n) :
@nat.elim C a f (succ n) = f n (nat.elim a f n) := rfl
def cases {C : Sort*} (a : C) (f : ℕ → C) : ℕ → C := nat.elim a (λ n _, f n)
@[simp] theorem cases_zero {C} (a f) : @nat.cases C a f 0 = a := rfl
@[simp] theorem cases_succ {C} (a f n) : @nat.cases C a f (succ n) = f n := rfl
@[simp, reducible] def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α :=
f n.unpair.1 n.unpair.2
/-- The primitive recursive functions `ℕ → ℕ`. -/
inductive primrec : (ℕ → ℕ) → Prop
| zero : primrec (λ n, 0)
| succ : primrec succ
| left : primrec (λ n, n.unpair.1)
| right : primrec (λ n, n.unpair.2)
| pair {f g} : primrec f → primrec g → primrec (λ n, mkpair (f n) (g n))
| comp {f g} : primrec f → primrec g → primrec (λ n, f (g n))
| prec {f g} : primrec f → primrec g → primrec (unpaired (λ z n,
n.elim (f z) (λ y IH, g $ mkpair z $ mkpair y IH)))
namespace primrec
theorem of_eq {f g : ℕ → ℕ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g :=
(funext H : f = g) ▸ hf
theorem const : ∀ (n : ℕ), primrec (λ _, n)
| 0 := zero
| (n+1) := succ.comp (const n)
protected theorem id : primrec id :=
(left.pair right).of_eq $ λ n, by simp
theorem prec1 {f} (m : ℕ) (hf : primrec f) : primrec (λ n,
n.elim m (λ y IH, f $ mkpair y IH)) :=
((prec (const m) (hf.comp right)).comp
(zero.pair primrec.id)).of_eq $
λ n, by simp; dsimp; rw [unpair_mkpair]
theorem cases1 {f} (m : ℕ) (hf : primrec f) : primrec (nat.cases m f) :=
(prec1 m (hf.comp left)).of_eq $ by simp [cases]
theorem cases {f g} (hf : primrec f) (hg : primrec g) :
primrec (unpaired (λ z n, n.cases (f z) (λ y, g $ mkpair z y))) :=
(prec hf (hg.comp (pair left (left.comp right)))).of_eq $ by simp [cases]
protected theorem swap : primrec (unpaired (function.swap mkpair)) :=
(pair right left).of_eq $ λ n, by simp
theorem swap' {f} (hf : primrec (unpaired f)) : primrec (unpaired (function.swap f)) :=
(hf.comp primrec.swap).of_eq $ λ n, by simp
theorem pred : primrec pred :=
(cases1 0 primrec.id).of_eq $ λ n, by cases n; simp *
theorem add : primrec (unpaired (+)) :=
(prec primrec.id ((succ.comp right).comp right)).of_eq $
λ p, by simp; induction p.unpair.2; simp [*, -add_comm, add_succ]
theorem sub : primrec (unpaired has_sub.sub) :=
(prec primrec.id ((pred.comp right).comp right)).of_eq $
λ p, by simp; induction p.unpair.2; simp [*, -add_comm, sub_succ]
theorem mul : primrec (unpaired (*)) :=
(prec zero (add.comp (pair left (right.comp right)))).of_eq $
λ p, by simp; induction p.unpair.2; simp [*, mul_succ, add_comm]
theorem pow : primrec (unpaired (^)) :=
(prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq $
λ p, by simp; induction p.unpair.2; simp [*, pow_succ]
end primrec
end nat
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A `primcodable` type is an `encodable` type for which
the encode/decode functions are primitive recursive. -/
class primcodable (α : Type*) extends encodable α :=
(prim [] : nat.primrec (λ n, encodable.encode (decode n)))
end prio
namespace primcodable
open nat.primrec
@[priority 10] instance of_denumerable (α) [denumerable α] : primcodable α :=
⟨succ.of_eq $ by simp⟩
def of_equiv (α) {β} [primcodable α] (e : β ≃ α) : primcodable β :=
{ prim := (primcodable.prim α).of_eq $ λ n,
show encode (decode α n) =
(option.cases_on (option.map e.symm (decode α n))
0 (λ a, nat.succ (encode (e a))) : ℕ),
by cases decode α n; dsimp; simp,
..encodable.of_equiv α e }
instance empty : primcodable empty :=
⟨zero⟩
instance unit : primcodable punit :=
⟨(cases1 1 zero).of_eq $ λ n, by cases n; simp⟩
instance option {α : Type*} [h : primcodable α] : primcodable (option α) :=
⟨(cases1 1 ((cases1 0 (succ.comp succ)).comp (primcodable.prim α))).of_eq $
λ n, by cases n; simp; cases decode α n; refl⟩
instance bool : primcodable bool :=
⟨(cases1 1 (cases1 2 zero)).of_eq $
λ n, begin
cases n, {refl}, cases n, {refl},
rw decode_ge_two, {refl},
exact dec_trivial
end⟩
end primcodable
/-- `primrec f` means `f` is primitive recursive (after
encoding its input and output as natural numbers). -/
def primrec {α β} [primcodable α] [primcodable β] (f : α → β) : Prop :=
nat.primrec (λ n, encode ((decode α n).map f))
namespace primrec
variables {α : Type*} {β : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable σ]
open nat.primrec
protected theorem encode : primrec (@encode α _) :=
(primcodable.prim α).of_eq $ λ n, by cases decode α n; refl
protected theorem decode : primrec (decode α) :=
succ.comp (primcodable.prim α)
theorem dom_denumerable {α β} [denumerable α] [primcodable β]
{f : α → β} : primrec f ↔ nat.primrec (λ n, encode (f (of_nat α n))) :=
⟨λ h, (pred.comp h).of_eq $ λ n, by simp; refl,
λ h, (succ.comp h).of_eq $ λ n, by simp; refl⟩
theorem nat_iff {f : ℕ → ℕ} : primrec f ↔ nat.primrec f :=
dom_denumerable
theorem encdec : primrec (λ n, encode (decode α n)) :=
nat_iff.2 (primcodable.prim α)
theorem option_some : primrec (@some α) :=
((cases1 0 (succ.comp succ)).comp (primcodable.prim α)).of_eq $
λ n, by cases decode α n; simp
theorem of_eq {f g : α → σ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g :=
(funext H : f = g) ▸ hf
theorem const (x : σ) : primrec (λ a : α, x) :=
((cases1 0 (const (encode x).succ)).comp (primcodable.prim α)).of_eq $
λ n, by cases decode α n; refl
protected theorem id : primrec (@id α) :=
(primcodable.prim α).of_eq $ by simp
theorem comp {f : β → σ} {g : α → β}
(hf : primrec f) (hg : primrec g) : primrec (λ a, f (g a)) :=
((cases1 0 (hf.comp $ pred.comp hg)).comp (primcodable.prim α)).of_eq $
λ n, begin
cases decode α n, {refl},
simp [encodek]
end
theorem succ : primrec nat.succ := nat_iff.2 nat.primrec.succ
theorem pred : primrec nat.pred := nat_iff.2 nat.primrec.pred
theorem encode_iff {f : α → σ} : primrec (λ a, encode (f a)) ↔ primrec f :=
⟨λ h, nat.primrec.of_eq h $ λ n, by cases decode α n; refl,
primrec.encode.comp⟩
theorem of_nat_iff {α β} [denumerable α] [primcodable β]
{f : α → β} : primrec f ↔ primrec (λ n, f (of_nat α n)) :=
dom_denumerable.trans $ nat_iff.symm.trans encode_iff
protected theorem of_nat (α) [denumerable α] : primrec (of_nat α) :=
of_nat_iff.1 primrec.id
theorem option_some_iff {f : α → σ} : primrec (λ a, some (f a)) ↔ primrec f :=
⟨λ h, encode_iff.1 $ pred.comp $ encode_iff.2 h, option_some.comp⟩
theorem of_equiv {β} {e : β ≃ α} :
by haveI := primcodable.of_equiv α e; exact
primrec e :=
(primcodable.prim α).of_eq $ λ n,
show _ = encode (option.map e (option.map _ _)),
by cases decode α n; simp
theorem of_equiv_symm {β} {e : β ≃ α} :
by haveI := primcodable.of_equiv α e; exact
primrec e.symm :=
by letI := primcodable.of_equiv α e; exact
encode_iff.1
(show primrec (λ a, encode (e (e.symm a))), by simp [primrec.encode])
theorem of_equiv_iff {β} (e : β ≃ α)
{f : σ → β} :
by haveI := primcodable.of_equiv α e; exact
primrec (λ a, e (f a)) ↔ primrec f :=
by letI := primcodable.of_equiv α e; exact
⟨λ h, (of_equiv_symm.comp h).of_eq (λ a, by simp), of_equiv.comp⟩
theorem of_equiv_symm_iff {β} (e : β ≃ α)
{f : σ → α} :
by haveI := primcodable.of_equiv α e; exact
primrec (λ a, e.symm (f a)) ↔ primrec f :=
by letI := primcodable.of_equiv α e; exact
⟨λ h, (of_equiv.comp h).of_eq (λ a, by simp), of_equiv_symm.comp⟩
end primrec
namespace primcodable
open nat.primrec
instance prod {α β} [primcodable α] [primcodable β] : primcodable (α × β) :=
⟨((cases zero ((cases zero succ).comp
(pair right ((primcodable.prim β).comp left)))).comp
(pair right ((primcodable.prim α).comp left))).of_eq $
λ n, begin
simp [nat.unpaired],
cases decode α n.unpair.1, { simp },
cases decode β n.unpair.2; simp
end⟩
end primcodable
namespace primrec
variables {α : Type*} {σ : Type*} [primcodable α] [primcodable σ]
open nat.primrec
theorem fst {α β} [primcodable α] [primcodable β] :
primrec (@prod.fst α β) :=
((cases zero ((cases zero (nat.primrec.succ.comp left)).comp
(pair right ((primcodable.prim β).comp left)))).comp
(pair right ((primcodable.prim α).comp left))).of_eq $
λ n, begin
simp,
cases decode α n.unpair.1; simp,
cases decode β n.unpair.2; simp
end
theorem snd {α β} [primcodable α] [primcodable β] :
primrec (@prod.snd α β) :=
((cases zero ((cases zero (nat.primrec.succ.comp right)).comp
(pair right ((primcodable.prim β).comp left)))).comp
(pair right ((primcodable.prim α).comp left))).of_eq $
λ n, begin
simp,
cases decode α n.unpair.1; simp,
cases decode β n.unpair.2; simp
end
theorem pair {α β γ} [primcodable α] [primcodable β] [primcodable γ]
{f : α → β} {g : α → γ} (hf : primrec f) (hg : primrec g) :
primrec (λ a, (f a, g a)) :=
((cases1 0 (nat.primrec.succ.comp $
pair (nat.primrec.pred.comp hf) (nat.primrec.pred.comp hg))).comp
(primcodable.prim α)).of_eq $
λ n, by cases decode α n; simp [encodek]; refl
theorem unpair : primrec nat.unpair :=
(pair (nat_iff.2 nat.primrec.left) (nat_iff.2 nat.primrec.right)).of_eq $
λ n, by simp
theorem list_nth₁ : ∀ (l : list α), primrec l.nth
| [] := dom_denumerable.2 zero
| (a::l) := dom_denumerable.2 $
(cases1 (encode a).succ $ dom_denumerable.1 $ list_nth₁ l).of_eq $
λ n, by cases n; simp
end primrec
/-- `primrec₂ f` means `f` is a binary primitive recursive function.
This is technically unnecessary since we can always curry all
the arguments together, but there are enough natural two-arg
functions that it is convenient to express this directly. -/
def primrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) :=
primrec (λ p : α × β, f p.1 p.2)
/-- `primrec_pred p` means `p : α → Prop` is a (decidable)
primitive recursive predicate, which is to say that
`to_bool ∘ p : α → bool` is primitive recursive. -/
def primrec_pred {α} [primcodable α] (p : α → Prop)
[decidable_pred p] := primrec (λ a, to_bool (p a))
/-- `primrec_rel p` means `p : α → β → Prop` is a (decidable)
primitive recursive relation, which is to say that
`to_bool ∘ p : α → β → bool` is primitive recursive. -/
def primrec_rel {α β} [primcodable α] [primcodable β]
(s : α → β → Prop) [∀ a b, decidable (s a b)] :=
primrec₂ (λ a b, to_bool (s a b))
namespace primrec₂
variables {α : Type*} {β : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable σ]
theorem of_eq {f g : α → β → σ} (hg : primrec₂ f) (H : ∀ a b, f a b = g a b) : primrec₂ g :=
(by funext a b; apply H : f = g) ▸ hg
theorem const (x : σ) : primrec₂ (λ (a : α) (b : β), x) := primrec.const _
protected theorem pair : primrec₂ (@prod.mk α β) :=
primrec.pair primrec.fst primrec.snd
theorem left : primrec₂ (λ (a : α) (b : β), a) := primrec.fst
theorem right : primrec₂ (λ (a : α) (b : β), b) := primrec.snd
theorem mkpair : primrec₂ nat.mkpair :=
by simp [primrec₂, primrec]; constructor
theorem unpaired {f : ℕ → ℕ → α} : primrec (nat.unpaired f) ↔ primrec₂ f :=
⟨λ h, by simpa using h.comp mkpair,
λ h, h.comp primrec.unpair⟩
theorem unpaired' {f : ℕ → ℕ → ℕ} : nat.primrec (nat.unpaired f) ↔ primrec₂ f :=
primrec.nat_iff.symm.trans unpaired
theorem encode_iff {f : α → β → σ} : primrec₂ (λ a b, encode (f a b)) ↔ primrec₂ f :=
primrec.encode_iff
theorem option_some_iff {f : α → β → σ} : primrec₂ (λ a b, some (f a b)) ↔ primrec₂ f :=
primrec.option_some_iff
theorem of_nat_iff {α β σ}
[denumerable α] [denumerable β] [primcodable σ]
{f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ,
f (of_nat α m) (of_nat β n)) :=
(primrec.of_nat_iff.trans $ by simp).trans unpaired
theorem uncurry {f : α → β → σ} : primrec (function.uncurry f) ↔ primrec₂ f :=
by rw [show function.uncurry f = λ (p : α × β), f p.1 p.2,
from funext $ λ ⟨a, b⟩, rfl]; refl
theorem curry {f : α × β → σ} : primrec₂ (function.curry f) ↔ primrec f :=
by rw [← uncurry, function.uncurry_curry]
end primrec₂
section comp
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ]
theorem primrec.comp₂ {f : γ → σ} {g : α → β → γ}
(hf : primrec f) (hg : primrec₂ g) :
primrec₂ (λ a b, f (g a b)) := hf.comp hg
theorem primrec₂.comp
{f : β → γ → σ} {g : α → β} {h : α → γ}
(hf : primrec₂ f) (hg : primrec g) (hh : primrec h) :
primrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh)
theorem primrec₂.comp₂
{f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ}
(hf : primrec₂ f) (hg : primrec₂ g) (hh : primrec₂ h) :
primrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh
theorem primrec_pred.comp
{p : β → Prop} [decidable_pred p] {f : α → β} :
primrec_pred p → primrec f →
primrec_pred (λ a, p (f a)) := primrec.comp
theorem primrec_rel.comp
{R : β → γ → Prop} [∀ a b, decidable (R a b)] {f : α → β} {g : α → γ} :
primrec_rel R → primrec f → primrec g →
primrec_pred (λ a, R (f a) (g a)) := primrec₂.comp
theorem primrec_rel.comp₂
{R : γ → δ → Prop} [∀ a b, decidable (R a b)] {f : α → β → γ} {g : α → β → δ} :
primrec_rel R → primrec₂ f → primrec₂ g →
primrec_rel (λ a b, R (f a b) (g a b)) := primrec_rel.comp
end comp
theorem primrec_pred.of_eq {α} [primcodable α]
{p q : α → Prop} [decidable_pred p] [decidable_pred q]
(hp : primrec_pred p) (H : ∀ a, p a ↔ q a) : primrec_pred q :=
primrec.of_eq hp (λ a, to_bool_congr (H a))
theorem primrec_rel.of_eq {α β} [primcodable α] [primcodable β]
{r s : α → β → Prop} [∀ a b, decidable (r a b)] [∀ a b, decidable (s a b)]
(hr : primrec_rel r) (H : ∀ a b, r a b ↔ s a b) : primrec_rel s :=
primrec₂.of_eq hr (λ a b, to_bool_congr (H a b))
namespace primrec₂
variables {α : Type*} {β : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable σ]
open nat.primrec
theorem swap {f : α → β → σ} (h : primrec₂ f) : primrec₂ (function.swap f) :=
h.comp₂ primrec₂.right primrec₂.left
theorem nat_iff {f : α → β → σ} : primrec₂ f ↔
nat.primrec (nat.unpaired $ λ m n : ℕ,
encode $ (decode α m).bind $ λ a, (decode β n).map (f a)) :=
have ∀ (a : option α) (b : option β),
option.map (λ (p : α × β), f p.1 p.2)
(option.bind a (λ (a : α), option.map (prod.mk a) b)) =
option.bind a (λ a, option.map (f a) b),
by intros; cases a; [refl, {cases b; refl}],
by simp [primrec₂, primrec, this]
theorem nat_iff' {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ,
option.bind (decode α m) (λ a, option.map (f a) (decode β n))) :=
nat_iff.trans $ unpaired'.trans encode_iff
end primrec₂
namespace primrec
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ]
theorem to₂ {f : α × β → σ} (hf : primrec f) : primrec₂ (λ a b, f (a, b)) :=
hf.of_eq $ λ ⟨a, b⟩, rfl
theorem nat_elim {f : α → β} {g : α → ℕ × β → β}
(hf : primrec f) (hg : primrec₂ g) :
primrec₂ (λ a (n : ℕ), n.elim (f a) (λ n IH, g a (n, IH))) :=
primrec₂.nat_iff.2 $ ((nat.primrec.cases nat.primrec.zero $
(nat.primrec.prec hf $ nat.primrec.comp hg $ nat.primrec.left.pair $
(nat.primrec.left.comp nat.primrec.right).pair $
nat.primrec.pred.comp $ nat.primrec.right.comp nat.primrec.right).comp $
nat.primrec.right.pair $
nat.primrec.right.comp nat.primrec.left).comp $
nat.primrec.id.pair $ (primcodable.prim α).comp nat.primrec.left).of_eq $
λ n, begin
simp,
cases decode α n.unpair.1 with a, {refl},
simp [encodek],
induction n.unpair.2 with m; simp [encodek],
simp [ih, encodek]
end
theorem nat_elim' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β}
(hf : primrec f) (hg : primrec g) (hh : primrec₂ h) :
primrec (λ a, (f a).elim (g a) (λ n IH, h a (n, IH))) :=
(nat_elim hg hh).comp primrec.id hf
theorem nat_elim₁ {f : ℕ → α → α} (a : α) (hf : primrec₂ f) :
primrec (nat.elim a f) :=
nat_elim' primrec.id (const a) $ comp₂ hf primrec₂.right
theorem nat_cases' {f : α → β} {g : α → ℕ → β}
(hf : primrec f) (hg : primrec₂ g) :
primrec₂ (λ a, nat.cases (f a) (g a)) :=
nat_elim hf $ hg.comp₂ primrec₂.left $
comp₂ fst primrec₂.right
theorem nat_cases {f : α → ℕ} {g : α → β} {h : α → ℕ → β}
(hf : primrec f) (hg : primrec g) (hh : primrec₂ h) :
primrec (λ a, (f a).cases (g a) (h a)) :=
(nat_cases' hg hh).comp primrec.id hf
theorem nat_cases₁ {f : ℕ → α} (a : α) (hf : primrec f) :
primrec (nat.cases a f) :=
nat_cases primrec.id (const a) (comp₂ hf primrec₂.right)
theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β}
(hf : primrec f) (hg : primrec g) (hh : primrec₂ h) :
primrec (λ a, (h a)^[f a] (g a)) :=
(nat_elim' hf hg (hh.comp₂ primrec₂.left $ snd.comp₂ primrec₂.right)).of_eq $
λ a, by induction f a; simp [*, -nat.iterate_succ, nat.iterate_succ']
theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ}
(ho : primrec o) (hf : primrec f) (hg : primrec₂ g) :
@primrec _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) :=
encode_iff.1 $
(nat_cases (encode_iff.2 ho) (encode_iff.2 hf) $
pred.comp₂ $ primrec₂.encode_iff.2 $
(primrec₂.nat_iff'.1 hg).comp₂
((@primrec.encode α _).comp fst).to₂
primrec₂.right).of_eq $
λ a, by cases o a with b; simp [encodek]; refl
theorem option_bind {f : α → option β} {g : α → β → option σ}
(hf : primrec f) (hg : primrec₂ g) :
primrec (λ a, (f a).bind (g a)) :=
(option_cases hf (const none) hg).of_eq $
λ a, by cases f a; refl
theorem option_bind₁ {f : α → option σ} (hf : primrec f) :
primrec (λ o, option.bind o f) :=
option_bind primrec.id (hf.comp snd).to₂
theorem option_map {f : α → option β} {g : α → β → σ}
(hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) :=
option_bind hf (option_some.comp₂ hg)
theorem option_map₁ {f : α → σ} (hf : primrec f) : primrec (option.map f) :=
option_map primrec.id (hf.comp snd).to₂
theorem option_iget [inhabited α] : primrec (@option.iget α _) :=
(option_cases primrec.id (const $ default α) primrec₂.right).of_eq $
λ o, by cases o; refl
theorem option_is_some : primrec (@option.is_some α) :=
(option_cases primrec.id (const ff) (const tt).to₂).of_eq $
λ o, by cases o; refl
theorem bind_decode_iff {f : α → β → option σ} : primrec₂ (λ a n,
(decode β n).bind (f a)) ↔ primrec₂ f :=
⟨λ h, by simpa [encodek] using
h.comp fst ((@primrec.encode β _).comp snd),
λ h, option_bind (primrec.decode.comp snd) $
h.comp (fst.comp fst) snd⟩
theorem map_decode_iff {f : α → β → σ} : primrec₂ (λ a n,
(decode β n).map (f a)) ↔ primrec₂ f :=
bind_decode_iff.trans primrec₂.option_some_iff
theorem nat_add : primrec₂ ((+) : ℕ → ℕ → ℕ) :=
primrec₂.unpaired'.1 nat.primrec.add
theorem nat_sub : primrec₂ (has_sub.sub : ℕ → ℕ → ℕ) :=
primrec₂.unpaired'.1 nat.primrec.sub
theorem nat_mul : primrec₂ ((*) : ℕ → ℕ → ℕ) :=
primrec₂.unpaired'.1 nat.primrec.mul
theorem cond {c : α → bool} {f : α → σ} {g : α → σ}
(hc : primrec c) (hf : primrec f) (hg : primrec g) :
primrec (λ a, cond (c a) (f a) (g a)) :=
(nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $
λ a, by cases c a; refl
theorem ite {c : α → Prop} [decidable_pred c] {f : α → σ} {g : α → σ}
(hc : primrec_pred c) (hf : primrec f) (hg : primrec g) :
primrec (λ a, if c a then f a else g a) :=
by simpa using cond hc hf hg
theorem nat_le : primrec_rel ((≤) : ℕ → ℕ → Prop) :=
(nat_cases nat_sub (const tt) (const ff).to₂).of_eq $
λ p, begin
dsimp [function.swap],
cases e : p.1 - p.2 with n,
{ simp [nat.sub_eq_zero_iff_le.1 e] },
{ simp [not_le.2 (nat.lt_of_sub_eq_succ e)] }
end
theorem nat_min : primrec₂ (@min ℕ _) := ite nat_le fst snd
theorem nat_max : primrec₂ (@max ℕ _) := ite nat_le snd fst
theorem dom_bool (f : bool → α) : primrec f :=
(cond primrec.id (const (f tt)) (const (f ff))).of_eq $
λ b, by cases b; refl
theorem dom_bool₂ (f : bool → bool → α) : primrec₂ f :=
(cond fst
((dom_bool (f tt)).comp snd)
((dom_bool (f ff)).comp snd)).of_eq $
λ ⟨a, b⟩, by cases a; refl
protected theorem bnot : primrec bnot := dom_bool _
protected theorem band : primrec₂ band := dom_bool₂ _
protected theorem bor : primrec₂ bor := dom_bool₂ _
protected theorem not {p : α → Prop} [decidable_pred p]
(hp : primrec_pred p) : primrec_pred (λ a, ¬ p a) :=
(primrec.bnot.comp hp).of_eq $ λ n, by simp
protected theorem and {p q : α → Prop}
[decidable_pred p] [decidable_pred q]
(hp : primrec_pred p) (hq : primrec_pred q) :
primrec_pred (λ a, p a ∧ q a) :=
(primrec.band.comp hp hq).of_eq $ λ n, by simp
protected theorem or {p q : α → Prop}
[decidable_pred p] [decidable_pred q]
(hp : primrec_pred p) (hq : primrec_pred q) :
primrec_pred (λ a, p a ∨ q a) :=
(primrec.bor.comp hp hq).of_eq $ λ n, by simp
protected theorem eq [decidable_eq α] : primrec_rel (@eq α) :=
have primrec_rel (λ a b : ℕ, a = b), from
(primrec.and nat_le nat_le.swap).of_eq $
λ a, by simp [le_antisymm_iff],
(this.comp₂
(primrec.encode.comp₂ primrec₂.left)
(primrec.encode.comp₂ primrec₂.right)).of_eq $
λ a b, encode_injective.eq_iff
theorem nat_lt : primrec_rel ((<) : ℕ → ℕ → Prop) :=
(nat_le.comp snd fst).not.of_eq $ λ p, by simp
theorem option_guard {p : α → β → Prop}
[∀ a b, decidable (p a b)] (hp : primrec_rel p)
{f : α → β} (hf : primrec f) :
primrec (λ a, option.guard (p a) (f a)) :=
ite (hp.comp primrec.id hf) (option_some_iff.2 hf) (const none)
theorem option_orelse :
primrec₂ ((<|>) : option α → option α → option α) :=
(option_cases fst snd (fst.comp fst).to₂).of_eq $
λ ⟨o₁, o₂⟩, by cases o₁; cases o₂; refl
protected theorem decode2 : primrec (decode2 α) :=
option_bind primrec.decode $
option_guard ((@primrec.eq _ _ nat.decidable_eq).comp
(encode_iff.2 snd) (fst.comp fst)) snd
theorem list_find_index₁ {p : α → β → Prop}
[∀ a b, decidable (p a b)] (hp : primrec_rel p) :
∀ (l : list β), primrec (λ a, l.find_index (p a))
| [] := const 0
| (a::l) := ite (hp.comp primrec.id (const a)) (const 0)
(succ.comp (list_find_index₁ l))
theorem list_index_of₁ [decidable_eq α] (l : list α) :
primrec (λ a, l.index_of a) := list_find_index₁ primrec.eq l
theorem dom_fintype [fintype α] (f : α → σ) : primrec f :=
let ⟨l, nd, m⟩ := fintype.exists_univ_list α in
option_some_iff.1 $ begin
haveI := decidable_eq_of_encodable α,
refine ((list_nth₁ (l.map f)).comp (list_index_of₁ l)).of_eq (λ a, _),
rw [list.nth_map, list.nth_le_nth (list.index_of_lt_length.2 (m _)),
list.index_of_nth_le]; refl
end
theorem nat_bodd_div2 : primrec nat.bodd_div2 :=
(nat_elim' primrec.id (const (ff, 0))
(((cond fst
(pair (const ff) (succ.comp snd))
(pair (const tt) snd)).comp snd).comp snd).to₂).of_eq $
λ n, begin
simp [-nat.bodd_div2_eq],
induction n with n IH, {refl},
simp [-nat.bodd_div2_eq, nat.bodd_div2, *],
rcases nat.bodd_div2 n with ⟨_|_, m⟩; simp [nat.bodd_div2]
end
theorem nat_bodd : primrec nat.bodd := fst.comp nat_bodd_div2
theorem nat_div2 : primrec nat.div2 := snd.comp nat_bodd_div2
theorem nat_bit0 : primrec (@bit0 ℕ _) :=
nat_add.comp primrec.id primrec.id
theorem nat_bit1 : primrec (@bit1 ℕ _ _) :=
nat_add.comp nat_bit0 (const 1)
theorem nat_bit : primrec₂ nat.bit :=
(cond primrec.fst
(nat_bit1.comp primrec.snd)
(nat_bit0.comp primrec.snd)).of_eq $
λ n, by cases n.1; refl
theorem nat_div_mod : primrec₂ (λ n k : ℕ, (n / k, n % k)) :=
let f (a : ℕ × ℕ) : ℕ × ℕ := a.1.elim (0, 0) (λ _ IH,
if nat.succ IH.2 = a.2
then (nat.succ IH.1, 0)
else (IH.1, nat.succ IH.2)) in
have hf : primrec f, from
nat_elim' fst (const (0, 0)) $
((ite ((@primrec.eq ℕ _ _).comp (succ.comp $ snd.comp snd) fst)
(pair (succ.comp $ fst.comp snd) (const 0))
(pair (fst.comp snd) (succ.comp $ snd.comp snd)))
.comp (pair (snd.comp fst) (snd.comp snd))).to₂,
suffices ∀ k n, (n / k, n % k) = f (n, k),
from hf.of_eq $ λ ⟨m, n⟩, by simp [this],
λ k n, begin
have : (f (n, k)).2 + k * (f (n, k)).1 = n
∧ (0 < k → (f (n, k)).2 < k)
∧ (k = 0 → (f (n, k)).1 = 0),
{ induction n with n IH, {exact ⟨rfl, id, λ _, rfl⟩},
rw [λ n:ℕ, show f (n.succ, k) =
_root_.ite ((f (n, k)).2.succ = k)
(nat.succ (f (n, k)).1, 0)
((f (n, k)).1, (f (n, k)).2.succ), from rfl],
by_cases h : (f (n, k)).2.succ = k; simp [h],
{ have := congr_arg nat.succ IH.1,
refine ⟨_, λ k0, nat.no_confusion (h.trans k0)⟩,
rwa [← nat.succ_add, h, add_comm, ← nat.mul_succ] at this },
{ exact ⟨by rw [nat.succ_add, IH.1],
λ k0, lt_of_le_of_ne (IH.2.1 k0) h, IH.2.2⟩ } },
revert this, cases f (n, k) with D M,
simp, intros h₁ h₂ h₃,
cases nat.eq_zero_or_pos k,
{ simp [h, h₃ h] at h₁ ⊢, simp [h₁] },
{ exact (nat.div_mod_unique h).2 ⟨h₁, h₂ h⟩ }
end
theorem nat_div : primrec₂ ((/) : ℕ → ℕ → ℕ) := fst.comp₂ nat_div_mod
theorem nat_mod : primrec₂ ((%) : ℕ → ℕ → ℕ) := snd.comp₂ nat_div_mod
end primrec
section
variables {α : Type*} {β : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable σ]
variable (H : nat.primrec (λ n, encodable.encode (decode (list β) n)))
include H
open primrec
private def prim : primcodable (list β) := ⟨H⟩
private lemma list_cases'
{f : α → list β} {g : α → σ} {h : α → β × list β → σ}
(hf : by haveI := prim H; exact primrec f) (hg : primrec g)
(hh : by haveI := prim H; exact primrec₂ h) :
@primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) :=
by letI := prim H; exact
have @primrec _ (option σ) _ _ (λ a,
(decode (option (β × list β)) (encode (f a))).map
(λ o, option.cases_on o (g a) (h a))), from
((@map_decode_iff _ (option (β × list β)) _ _ _ _ _).2 $
to₂ $ option_cases snd (hg.comp fst)
(hh.comp₂ (fst.comp₂ primrec₂.left) primrec₂.right))
.comp primrec.id (encode_iff.2 hf),
option_some_iff.1 $ this.of_eq $
λ a, by cases f a with b l; simp [encodek]; refl
private lemma list_foldl'
{f : α → list β} {g : α → σ} {h : α → σ × β → σ}
(hf : by haveI := prim H; exact primrec f) (hg : primrec g)
(hh : by haveI := prim H; exact primrec₂ h) :
primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) :=
by letI := prim H; exact
let G (a : α) (IH : σ × list β) : σ × list β :=
list.cases_on IH.2 IH (λ b l, (h a (IH.1, b), l)) in
let F (a : α) (n : ℕ) := nat.iterate (G a) n (g a, f a) in
have primrec (λ a, (F a (encode (f a))).1), from
fst.comp $ nat_iterate (encode_iff.2 hf) (pair hg hf) $
list_cases' H (snd.comp snd) snd $ to₂ $ pair
(hh.comp (fst.comp fst) $
pair ((fst.comp snd).comp fst) (fst.comp snd))
(snd.comp snd),
this.of_eq $ λ a, begin
have : ∀ n, F a n =
((list.take n (f a)).foldl (λ s b, h a (s, b)) (g a),
list.drop n (f a)),
{ intro, simp [F],
generalize : f a = l, generalize : g a = x,
induction n with n IH generalizing l x, {refl},
simp, cases l with b l; simp [IH] },
rw [this, list.take_all_of_le (length_le_encode _)]
end
private lemma list_cons' : by haveI := prim H; exact primrec₂ (@list.cons β) :=
by letI := prim H; exact
encode_iff.1 (succ.comp $
primrec₂.mkpair.comp (encode_iff.2 fst) (encode_iff.2 snd))
private lemma list_reverse' : by haveI := prim H; exact
primrec (@list.reverse β) :=
by letI := prim H; exact
(list_foldl' H primrec.id (const []) $ to₂ $
((list_cons' H).comp snd fst).comp snd).of_eq
(suffices ∀ l r, list.foldl (λ (s : list β) (b : β), b :: s) r l = list.reverse_core l r,
from λ l, this l [],
λ l, by induction l; simp [*, list.reverse_core])
end
namespace primcodable
variables {α : Type*} {β : Type*}
variables [primcodable α] [primcodable β]
open primrec
instance sum : primcodable (α ⊕ β) :=
⟨primrec.nat_iff.1 $
(encode_iff.2 (cond nat_bodd
(((@primrec.decode β _).comp nat_div2).option_map $ to₂ $
nat_bit.comp (const tt) (primrec.encode.comp snd))
(((@primrec.decode α _).comp nat_div2).option_map $ to₂ $
nat_bit.comp (const ff) (primrec.encode.comp snd)))).of_eq $
λ n, show _ = encode (decode_sum n), begin
simp [decode_sum],
cases nat.bodd n; simp [decode_sum],
{ cases decode α n.div2; refl },
{ cases decode β n.div2; refl }
end⟩
instance list : primcodable (list α) := ⟨
by letI H := primcodable.prim (list ℕ); exact
have primrec₂ (λ (a : α) (o : option (list ℕ)),
o.map (list.cons (encode a))), from
option_map snd $
(list_cons' H).comp ((@primrec.encode α _).comp (fst.comp fst)) snd,
have primrec (λ n, (of_nat (list ℕ) n).reverse.foldl
(λ o m, (decode α m).bind (λ a, o.map (list.cons (encode a))))
(some [])), from
list_foldl' H
((list_reverse' H).comp (primrec.of_nat (list ℕ)))
(const (some []))
(primrec.comp₂ (bind_decode_iff.2 $ primrec₂.swap this) primrec₂.right),
nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, begin
rw list.foldl_reverse,
apply nat.case_strong_induction_on n, {refl},
intros n IH, simp,
cases decode α n.unpair.1 with a, {refl},
simp,
suffices : ∀ (o : option (list ℕ)) p (_ : encode o = encode p),
encode (option.map (list.cons (encode a)) o) =
encode (option.map (list.cons a) p),
from this _ _ (IH _ (nat.unpair_le_right n)),
intros o p IH,
cases o; cases p; injection IH with h,
exact congr_arg (λ k, (nat.mkpair (encode a) k).succ.succ) h
end⟩
end primcodable
namespace primrec
variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ]
theorem sum_inl : primrec (@sum.inl α β) :=
encode_iff.1 $ nat_bit0.comp primrec.encode
theorem sum_inr : primrec (@sum.inr α β) :=
encode_iff.1 $ nat_bit1.comp primrec.encode
theorem sum_cases
{f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ}
(hf : primrec f) (hg : primrec₂ g) (hh : primrec₂ h) :
@primrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) :=
option_some_iff.1 $
(cond (nat_bodd.comp $ encode_iff.2 hf)
(option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh)
(option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $
λ a, by cases f a with b c;
simp [nat.div2_bit, nat.bodd_bit, encodek]; refl
theorem list_cons : primrec₂ (@list.cons α) :=
list_cons' (primcodable.prim _)
theorem list_cases
{f : α → list β} {g : α → σ} {h : α → β × list β → σ} :
primrec f → primrec g → primrec₂ h →
@primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) :=
list_cases' (primcodable.prim _)
theorem list_foldl
{f : α → list β} {g : α → σ} {h : α → σ × β → σ} :
primrec f → primrec g → primrec₂ h →
primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) :=
list_foldl' (primcodable.prim _)
theorem list_reverse : primrec (@list.reverse α) :=
list_reverse' (primcodable.prim _)
theorem list_foldr
{f : α → list β} {g : α → σ} {h : α → β × σ → σ}
(hf : primrec f) (hg : primrec g) (hh : primrec₂ h) :
primrec (λ a, (f a).foldr (λ b s, h a (b, s)) (g a)) :=
(list_foldl (list_reverse.comp hf) hg $ to₂ $
hh.comp fst $ (pair snd fst).comp snd).of_eq $
λ a, by simp [list.foldl_reverse]
theorem list_head' : primrec (@list.head' α) :=
(list_cases primrec.id (const none)
(option_some_iff.2 $ (fst.comp snd)).to₂).of_eq $
λ l, by cases l; refl
theorem list_head [inhabited α] : primrec (@list.head α _) :=
(option_iget.comp list_head').of_eq $
λ l, l.head_eq_head'.symm
theorem list_tail : primrec (@list.tail α) :=
(list_cases primrec.id (const []) (snd.comp snd).to₂).of_eq $
λ l, by cases l; refl
theorem list_rec
{f : α → list β} {g : α → σ} {h : α → β × list β × σ → σ}
(hf : primrec f) (hg : primrec g) (hh : primrec₂ h) :
@primrec _ σ _ _ (λ a,
list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))) :=
let F (a : α) := (f a).foldr
(λ (b : β) (s : list β × σ), (b :: s.1, h a (b, s))) ([], g a) in
have primrec F, from
list_foldr hf (pair (const []) hg) $ to₂ $
pair ((list_cons.comp fst (fst.comp snd)).comp snd) hh,
(snd.comp this).of_eq $ λ a, begin
suffices : F a = (f a,
list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))), {rw this},
simp [F], induction f a with b l IH; simp *
end
theorem list_nth : primrec₂ (@list.nth α) :=
let F (l : list α) (n : ℕ) :=
l.foldl (λ (s : ℕ ⊕ α) (a : α),
sum.cases_on s
(@nat.cases (ℕ ⊕ α) (sum.inr a) sum.inl) sum.inr)
(sum.inl n) in
have hF : primrec₂ F, from
list_foldl fst (sum_inl.comp snd) ((sum_cases fst
(nat_cases snd
(sum_inr.comp $ snd.comp fst)
(sum_inl.comp snd).to₂).to₂
(sum_inr.comp snd).to₂).comp snd).to₂,
have @primrec _ (option α) _ _ (λ p : list α × ℕ,
sum.cases_on (F p.1 p.2) (λ _, none) some), from
sum_cases hF (const none).to₂ (option_some.comp snd).to₂,
this.to₂.of_eq $ λ l n, begin
dsimp, symmetry,
induction l with a l IH generalizing n, {refl},
cases n with n,
{ rw [(_ : F (a :: l) 0 = sum.inr a)], {refl},
clear IH, dsimp [F],
induction l with b l IH; simp * },
{ apply IH }
end
theorem list_inth [inhabited α] : primrec₂ (@list.inth α _) :=
option_iget.comp₂ list_nth
theorem list_append : primrec₂ ((++) : list α → list α → list α) :=
(list_foldr fst snd $ to₂ $ comp (@list_cons α _) snd).to₂.of_eq $
λ l₁ l₂, by induction l₁; simp *
theorem list_concat : primrec₂ (λ l (a:α), l ++ [a]) :=
list_append.comp fst (list_cons.comp snd (const []))
theorem list_map
{f : α → list β} {g : α → β → σ}
(hf : primrec f) (hg : primrec₂ g) :
primrec (λ a, (f a).map (g a)) :=
(list_foldr hf (const []) $ to₂ $ list_cons.comp
(hg.comp fst (fst.comp snd)) (snd.comp snd)).of_eq $
λ a, by induction f a; simp *
theorem list_range : primrec list.range :=
(nat_elim' primrec.id (const [])
((list_concat.comp snd fst).comp snd).to₂).of_eq $
λ n, by simp; induction n; simp [*, list.range_concat]; refl
theorem list_join : primrec (@list.join α) :=
(list_foldr primrec.id (const []) $ to₂ $
comp (@list_append α _) snd).of_eq $
λ l, by dsimp; induction l; simp *
theorem list_length : primrec (@list.length α) :=
(list_foldr (@primrec.id (list α) _) (const 0) $ to₂ $
(succ.comp $ snd.comp snd).to₂).of_eq $
λ l, by dsimp; induction l; simp [*, -add_comm]
theorem list_find_index {f : α → list β} {p : α → β → Prop}
[∀ a b, decidable (p a b)]
(hf : primrec f) (hp : primrec_rel p) :
primrec (λ a, (f a).find_index (p a)) :=
(list_foldr hf (const 0) $ to₂ $
ite (hp.comp fst $ fst.comp snd) (const 0)
(succ.comp $ snd.comp snd)).of_eq $
λ a, eq.symm $ by dsimp; induction f a with b l;
[refl, simp [*, list.find_index]]
theorem list_index_of [decidable_eq α] : primrec₂ (@list.index_of α _) :=
to₂ $ list_find_index snd $ primrec.eq.comp₂ (fst.comp fst).to₂ snd.to₂
theorem nat_strong_rec
(f : α → ℕ → σ) {g : α → list σ → option σ} (hg : primrec₂ g)
(H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : primrec₂ f :=
suffices primrec₂ (λ a n, (list.range n).map (f a)), from
primrec₂.option_some_iff.1 $
(list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $
λ a n, by simp [list.nth_range (nat.lt_succ_self n)]; refl,
primrec₂.option_some_iff.1 $
(nat_elim (const (some [])) (to₂ $
option_bind (snd.comp snd) $ to₂ $
option_map
(hg.comp (fst.comp fst) snd)
(to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $
λ a n, begin
simp, induction n with n IH, {refl},
simp [IH, H, list.range_concat]
end
end primrec
namespace primcodable
variables {α : Type*} {β : Type*}
variables [primcodable α] [primcodable β]
open primrec
def subtype {p : α → Prop} [decidable_pred p]
(hp : primrec_pred p) : primcodable (subtype p) :=
⟨have primrec (λ n, (decode α n).bind (λ a, option.guard p a)),
from option_bind primrec.decode (option_guard (hp.comp snd) snd),
nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n,
show _ = encode ((decode α n).bind (λ a, _)), begin
cases decode α n with a, {refl},
dsimp [option.guard],
by_cases h : p a; simp [h]; refl
end⟩
instance fin {n} : primcodable (fin n) :=
@of_equiv _ _
(subtype $ nat_lt.comp primrec.id (const n))
(equiv.fin_equiv_subtype _)
instance vector {n} : primcodable (vector α n) :=
subtype ((@primrec.eq _ _ nat.decidable_eq).comp list_length (const _))
instance fin_arrow {n} : primcodable (fin n → α) :=
of_equiv _ (equiv.vector_equiv_fin _ _).symm
instance array {n} : primcodable (array n α) :=
of_equiv _ (equiv.array_equiv_fin _ _)
end primcodable
namespace primrec
variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ]
theorem subtype_val {p : α → Prop} [decidable_pred p]
{hp : primrec_pred p} :
by haveI := primcodable.subtype hp; exact
primrec (@subtype.val α p) :=
begin
letI := primcodable.subtype hp,
refine (primcodable.prim (subtype p)).of_eq (λ n, _),
rcases decode (subtype p) n with _|⟨a,h⟩; refl
end
theorem subtype_val_iff {p : β → Prop} [decidable_pred p]
{hp : primrec_pred p} {f : α → subtype p} :
by haveI := primcodable.subtype hp; exact
primrec (λ a, (f a).1) ↔ primrec f :=
begin
letI := primcodable.subtype hp,
refine ⟨λ h, _, λ hf, subtype_val.comp hf⟩,
refine nat.primrec.of_eq h (λ n, _),
cases decode α n with a, {refl},
simp, cases f a; refl
end
theorem fin_val_iff {n} {f : α → fin n} :
primrec (λ a, (f a).1) ↔ primrec f :=
begin
let : primcodable {a//id a<n}, swap,
exactI (iff.trans (by refl) subtype_val_iff).trans (of_equiv_iff _)
end
theorem fin_val {n} : primrec (@fin.val n) := fin_val_iff.2 primrec.id
theorem fin_succ {n} : primrec (@fin.succ n) :=
fin_val_iff.1 $ by simp [succ.comp fin_val]
theorem vector_to_list {n} : primrec (@vector.to_list α n) := subtype_val
theorem vector_to_list_iff {n} {f : α → vector β n} :
primrec (λ a, (f a).to_list) ↔ primrec f := subtype_val_iff
theorem vector_cons {n} : primrec₂ (@vector.cons α n) :=
vector_to_list_iff.1 $ by simp; exact
list_cons.comp fst (vector_to_list_iff.2 snd)
theorem vector_length {n} : primrec (@vector.length α n) := const _
theorem vector_head {n} : primrec (@vector.head α n) :=
option_some_iff.1 $
(list_head'.comp vector_to_list).of_eq $ λ ⟨a::l, h⟩, rfl
theorem vector_tail {n} : primrec (@vector.tail α n) :=
vector_to_list_iff.1 $ (list_tail.comp vector_to_list).of_eq $
λ ⟨l, h⟩, by cases l; refl
theorem vector_nth {n} : primrec₂ (@vector.nth α n) :=
option_some_iff.1 $
(list_nth.comp (vector_to_list.comp fst) (fin_val.comp snd)).of_eq $
λ a, by simp [vector.nth_eq_nth_le]; rw [← list.nth_le_nth]
theorem list_of_fn : ∀ {n} {f : fin n → α → σ},
(∀ i, primrec (f i)) → primrec (λ a, list.of_fn (λ i, f i a))
| 0 f hf := const []
| (n+1) f hf := by simp [list.of_fn_succ]; exact
list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ))
theorem vector_of_fn {n} {f : fin n → α → σ}
(hf : ∀ i, primrec (f i)) : primrec (λ a, vector.of_fn (λ i, f i a)) :=
vector_to_list_iff.1 $ by simp [list_of_fn hf]
theorem vector_nth' {n} : primrec (@vector.nth α n) := of_equiv_symm
theorem vector_of_fn' {n} : primrec (@vector.of_fn α n) := of_equiv
theorem fin_app {n} : primrec₂ (@id (fin n → σ)) :=
(vector_nth.comp (vector_of_fn'.comp fst) snd).of_eq $
λ ⟨v, i⟩, by simp
theorem fin_curry₁ {n} {f : fin n → α → σ} : primrec₂ f ↔ ∀ i, primrec (f i) :=
⟨λ h i, h.comp (const i) primrec.id,
λ h, (vector_nth.comp ((vector_of_fn h).comp snd) fst).of_eq $ λ a, by simp⟩
theorem fin_curry {n} {f : α → fin n → σ} : primrec f ↔ primrec₂ f :=
⟨λ h, fin_app.comp (h.comp fst) snd,
λ h, (vector_nth'.comp (vector_of_fn (λ i,
show primrec (λ a, f a i), from
h.comp primrec.id (const i)))).of_eq $
λ a, by funext i; simp⟩
end primrec
namespace nat
open vector
/-- An alternative inductive definition of `primrec` which
does not use the pairing function on ℕ, and so has to
work with n-ary functions on ℕ instead of unary functions.
We prove that this is equivalent to the regular notion
in `to_prim` and `of_prim`. -/
inductive primrec' : ∀ {n}, (vector ℕ n → ℕ) → Prop
| zero : @primrec' 0 (λ _, 0)
| succ : @primrec' 1 (λ v, succ v.head)
| nth {n} (i : fin n) : primrec' (λ v, v.nth i)
| comp {m n f} (g : fin n → vector ℕ m → ℕ) :
primrec' f → (∀ i, primrec' (g i)) →
primrec' (λ a, f (of_fn (λ i, g i a)))
| prec {n f g} : @primrec' n f → @primrec' (n+2) g →
primrec' (λ v : vector ℕ (n+1),
v.head.elim (f v.tail) (λ y IH, g (y :: IH :: v.tail)))
end nat
namespace nat.primrec'
open vector primrec nat (primrec') nat.primrec'
hide ite
theorem to_prim {n f} (pf : @primrec' n f) : primrec f :=
begin
induction pf,
case nat.primrec'.zero { exact const 0 },
case nat.primrec'.succ { exact primrec.succ.comp vector_head },
case nat.primrec'.nth : n i {
exact vector_nth.comp primrec.id (const i) },
case nat.primrec'.comp : m n f g _ _ hf hg {
exact hf.comp (vector_of_fn (λ i, hg i)) },
case nat.primrec'.prec : n f g _ _ hf hg {
exact nat_elim' vector_head (hf.comp vector_tail) (hg.comp $
vector_cons.comp (fst.comp snd) $
vector_cons.comp (snd.comp snd) $
(@vector_tail _ _ (n+1)).comp fst).to₂ },
end
theorem of_eq {n} {f g : vector ℕ n → ℕ}
(hf : primrec' f) (H : ∀ i, f i = g i) : primrec' g :=
(funext H : f = g) ▸ hf
theorem const {n} : ∀ m, @primrec' n (λ v, m)
| 0 := zero.comp fin.elim0 (λ i, i.elim0)
| (m+1) := succ.comp _ (λ i, const m)
theorem head {n : ℕ} : @primrec' n.succ head :=
(nth 0).of_eq $ λ v, by simp [nth_zero]
theorem tail {n f} (hf : @primrec' n f) : @primrec' n.succ (λ v, f v.tail) :=
(hf.comp _ (λ i, @nth _ i.succ)).of_eq $
λ v, by rw [← of_fn_nth v.tail]; congr; funext i; simp
def vec {n m} (f : vector ℕ n → vector ℕ m) :=
∀ i, primrec' (λ v, (f v).nth i)
protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0
protected theorem cons {n m f g}
(hf : @primrec' n f) (hg : @vec n m g) :
vec (λ v, f v :: g v) :=
λ i, fin.cases (by simp *) (λ i, by simp [hg i]) i
theorem idv {n} : @vec n n id := nth
theorem comp' {n m f g}
(hf : @primrec' m f) (hg : @vec n m g) :
primrec' (λ v, f (g v)) :=
(hf.comp _ hg).of_eq $ λ v, by simp
theorem comp₁ (f : ℕ → ℕ) (hf : @primrec' 1 (λ v, f v.head))
{n g} (hg : @primrec' n g) : primrec' (λ v, f (g v)) :=
hf.comp _ (λ i, hg)
theorem comp₂ (f : ℕ → ℕ → ℕ)
(hf : @primrec' 2 (λ v, f v.head v.tail.head))
{n g h} (hg : @primrec' n g) (hh : @primrec' n h) :
primrec' (λ v, f (g v) (h v)) :=
by simpa using hf.comp' (hg.cons $ hh.cons primrec'.nil)
theorem prec' {n f g h}
(hf : @primrec' n f) (hg : @primrec' n g) (hh : @primrec' (n+2) h) :
@primrec' n (λ v, (f v).elim (g v)
(λ (y IH : ℕ), h (y :: IH :: v))) :=
by simpa using comp' (prec hg hh) (hf.cons idv)
theorem pred : @primrec' 1 (λ v, v.head.pred) :=
(prec' head (const 0) head).of_eq $
λ v, by simp; cases v.head; refl
theorem add : @primrec' 2 (λ v, v.head + v.tail.head) :=
(prec head (succ.comp₁ _ (tail head))).of_eq $
λ v, by simp; induction v.head; simp [*, nat.succ_add]
theorem sub : @primrec' 2 (λ v, v.head - v.tail.head) :=
begin
suffices, simpa using comp₂ (λ a b, b - a) this (tail head) head,
refine (prec head (pred.comp₁ _ (tail head))).of_eq (λ v, _),
simp, induction v.head; simp [*, nat.sub_succ]
end
theorem mul : @primrec' 2 (λ v, v.head * v.tail.head) :=
(prec (const 0) (tail (add.comp₂ _ (tail head) (head)))).of_eq $
λ v, by simp; induction v.head; simp [*, nat.succ_mul]; rw add_comm
theorem if_lt {n a b f g}
(ha : @primrec' n a) (hb : @primrec' n b)
(hf : @primrec' n f) (hg : @primrec' n g) :
@primrec' n (λ v, if a v < b v then f v else g v) :=
(prec' (sub.comp₂ _ hb ha) hg (tail $ tail hf)).of_eq $
λ v, begin
cases e : b v - a v,
{ simp [not_lt.2 (nat.le_of_sub_eq_zero e)] },
{ simp [nat.lt_of_sub_eq_succ e] }
end
theorem mkpair : @primrec' 2 (λ v, v.head.mkpair v.tail.head) :=
if_lt head (tail head)
(add.comp₂ _ (tail $ mul.comp₂ _ head head) head)
(add.comp₂ _ (add.comp₂ _
(mul.comp₂ _ head head) head) (tail head))
protected theorem encode : ∀ {n}, @primrec' n encode
| 0 := (const 0).of_eq (λ v, by rw v.eq_nil; refl)
| (n+1) := (succ.comp₁ _ (mkpair.comp₂ _ head (tail encode)))
.of_eq $ λ ⟨a::l, e⟩, rfl
theorem sqrt : @primrec' 1 (λ v, v.head.sqrt) :=
begin
suffices H : ∀ n : ℕ, n.sqrt = n.elim 0 (λ x y,
if x.succ < y.succ*y.succ then y else y.succ),
{ simp [H],
have := @prec' 1 _ _ (λ v,
by have x := v.head; have y := v.tail.head; from
if x.succ < y.succ*y.succ then y else y.succ) head (const 0) _,
{ convert this, funext, congr, funext x y, congr; simp },
have x1 := succ.comp₁ _ head,
have y1 := succ.comp₁ _ (tail head),
exact if_lt x1 (mul.comp₂ _ y1 y1) (tail head) y1 },
intro, symmetry,
induction n with n IH, {refl},
dsimp, rw IH, split_ifs,
{ exact le_antisymm (nat.sqrt_le_sqrt (nat.le_succ _))
(nat.lt_succ_iff.1 $ nat.sqrt_lt.2 h) },
{ exact nat.eq_sqrt.2 ⟨not_lt.1 h, nat.sqrt_lt.1 $
nat.lt_succ_iff.2 $ nat.sqrt_succ_le_succ_sqrt _⟩ },
end
theorem unpair₁ {n f} (hf : @primrec' n f) :
@primrec' n (λ v, (f v).unpair.1) :=
begin
have s := sqrt.comp₁ _ hf,
have fss := sub.comp₂ _ hf (mul.comp₂ _ s s),
refine (if_lt fss s fss s).of_eq (λ v, _),
simp [nat.unpair], split_ifs; refl
end
theorem unpair₂ {n f} (hf : @primrec' n f) :
@primrec' n (λ v, (f v).unpair.2) :=
begin
have s := sqrt.comp₁ _ hf,
have fss := sub.comp₂ _ hf (mul.comp₂ _ s s),
refine (if_lt fss s s (sub.comp₂ _ fss s)).of_eq (λ v, _),
simp [nat.unpair], split_ifs; refl
end
theorem of_prim : ∀ {n f}, primrec f → @primrec' n f :=
suffices ∀ f, nat.primrec f → @primrec' 1 (λ v, f v.head), from
λ n f hf, (pred.comp₁ _ $ (this _ hf).comp₁
(λ m, encodable.encode $ (decode (vector ℕ n) m).map f)
primrec'.encode).of_eq (λ i, by simp [encodek]),
λ f hf, begin
induction hf,
case nat.primrec.zero { exact const 0 },
case nat.primrec.succ { exact succ },
case nat.primrec.left { exact unpair₁ head },
case nat.primrec.right { exact unpair₂ head },
case nat.primrec.pair : f g _ _ hf hg {
exact mkpair.comp₂ _ hf hg },
case nat.primrec.comp : f g _ _ hf hg {
exact hf.comp₁ _ hg },
case nat.primrec.prec : f g _ _ hf hg {
simpa using prec' (unpair₂ head)
(hf.comp₁ _ (unpair₁ head))
(hg.comp₁ _ $ mkpair.comp₂ _ (unpair₁ $ tail $ tail head)
(mkpair.comp₂ _ head (tail head))) },
end
theorem prim_iff {n f} : @primrec' n f ↔ primrec f := ⟨to_prim, of_prim⟩
theorem prim_iff₁ {f : ℕ → ℕ} :
@primrec' 1 (λ v, f v.head) ↔ primrec f :=
prim_iff.trans ⟨
λ h, (h.comp $ vector_of_fn $ λ i, primrec.id).of_eq (λ v, by simp),
λ h, h.comp vector_head⟩
theorem prim_iff₂ {f : ℕ → ℕ → ℕ} :
@primrec' 2 (λ v, f v.head v.tail.head) ↔ primrec₂ f :=
prim_iff.trans ⟨
λ h, (h.comp $ vector_cons.comp fst $
vector_cons.comp snd (primrec.const nil)).of_eq (λ v, by simp),
λ h, h.comp vector_head (vector_head.comp vector_tail)⟩
theorem vec_iff {m n f} :
@vec m n f ↔ primrec f :=
⟨λ h, by simpa using vector_of_fn (λ i, to_prim (h i)),
λ h i, of_prim $ vector_nth.comp h (primrec.const i)⟩
end nat.primrec'
theorem primrec.nat_sqrt : primrec nat.sqrt :=
nat.primrec'.prim_iff₁.1 nat.primrec'.sqrt
|
94b1e1b733c33606cab9124f819cf9428393e6b3 | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /tests/lean/exp/nat.lean | 98acf60eb24ffad283c9df55b11e2fe288e2b660 | [
"Apache-2.0"
] | permissive | codyroux/lean0.1 | 1ce92751d664aacff0529e139083304a7bbc8a71 | 0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef | refs/heads/master | 1,610,830,535,062 | 1,402,150,480,000 | 1,402,150,480,000 | 19,588,851 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,363 | lean | import macros
definition injective {A B : (Type U)} (f : A → B) := ∀ x1 x2, f x1 = f x2 → x1 = x2
definition non_surjective {A B : (Type U)} (f : A → B) := ∃ y, ∀ x, ¬ f x = y
-- The set of individuals
variable ind : Type
-- ind is infinite, i.e., there is a function f s.t. f is injective, and not surjective
axiom infinity : ∃ f : ind → ind, injective f ∧ non_surjective f
theorem nonempty_ind : nonempty ind
-- We use as the witness for non-emptiness, the value w in ind that is not convered by f.
:= obtain f His, from infinity,
obtain w Hw, from and_elimr His,
nonempty_intro w
definition S := ε (nonempty_ex_intro infinity) (λ f, injective f ∧ non_surjective f)
definition Z := ε nonempty_ind (λ y, ∀ x, ¬ S x = y)
theorem injective_S : injective S
:= and_eliml (exists_to_eps infinity)
theorem non_surjective_S : non_surjective S
:= and_elimr (exists_to_eps infinity)
theorem S_ne_Z (i : ind) : S i ≠ Z
:= obtain w Hw, from non_surjective_S,
eps_ax nonempty_ind w Hw i
definition N (i : ind) : Bool
:= ∀ P, P Z → (∀ x, P x → P (S x)) → P i
theorem N_Z : N Z
:= λ P Hz Hi, Hz
theorem N_S (i : ind) (H : N i) : N (S i)
:= λ P Hz Hi, Hi i (H P Hz Hi)
theorem N_smallest : ∀ P : ind → Bool, P Z → (∀ x, P x → P (S x)) → (∀ i, N i → P i)
:= λ P Hz Hi i Hni, Hni P Hz Hi
|
725d3c6970f4dca77b379a86b36bf252196cc646 | bf532e3e865883a676110e756f800e0ddeb465be | /logic/basic.lean | ab515696d875fb460c30cdd67bc58c241a98c236 | [
"Apache-2.0"
] | permissive | aqjune/mathlib | da42a97d9e6670d2efaa7d2aa53ed3585dafc289 | f7977ff5a6bcf7e5c54eec908364ceb40dafc795 | refs/heads/master | 1,631,213,225,595 | 1,521,089,840,000 | 1,521,089,840,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 21,214 | 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
Theorems that require decidability hypotheses are in the namespace "decidable".
Classical versions are in the namespace "classical".
Note: in the presence of automation, this whole file may be unnecessary. On the other hand,
maybe it is useful for writing automation.
-/
import data.prod tactic.interactive
/-
miscellany
TODO: move elsewhere
-/
section miscellany
variables {α : Type*} {β : Type*}
def empty.elim {C : Sort*} : empty → C.
instance : subsingleton empty := ⟨λa, a.elim⟩
instance : decidable_eq empty := λa, a.elim
@[priority 0] 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
end miscellany
/-
propositional connectives
-/
@[simp] theorem false_ne_true : false ≠ true
| h := h.symm ▸ trivial
section propositional
variables {a b c d : Prop}
/- 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] theorem imp_self : (a → a) ↔ true := iff_true_intro id
theorem imp_intro {α β} (h : α) (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
@[simp] 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⟩
/- not -/
theorem 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 {α} : ¬(α → 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
@[simp] 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
/- 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
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⟩)
/- 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⟩
/- 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)
/- 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 (h : a ∧ ¬ b) : ¬ (a → b) :=
assume h₁, and.right h (h₁ (and.left h))
@[simp] theorem not_imp [decidable a] : ¬(a → b) ↔ a ∧ ¬b :=
⟨λ h, ⟨of_not_imp h, not_of_not_imp h⟩, not_imp_of_and_not⟩
theorem peirce (a b : Prop) [decidable a] : ((a → b) → a) → a :=
if ha : a then λ h, ha else λ h, h (λ h', absurd h' ha)
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 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
@[simp] theorem not_and_not_right [decidable a] [decidable b] : ¬(a ∧ ¬b) ↔ (a → b) :=
not_iff_comm.1 not_imp
def decidable_of_iff (a : Prop) (h : a ↔ b) [D : decidable a] : decidable b :=
decidable_of_decidable_of_iff D h
def decidable_of_iff' (b : Prop) (h : a ↔ b) [D : decidable b] : decidable a :=
decidable_of_decidable_of_iff D h.symm
/- 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
/- equality -/
section equality
variables {α : Sort*} {a b : α}
@[simp] theorem heq_iff_eq : a == b ↔ a = b :=
⟨eq_of_heq, heq_of_eq⟩
theorem ne_of_mem_of_not_mem {α β} [has_mem α β] {s : β} {a b : α}
(h : a ∈ s) : b ∉ s → a ≠ b :=
mt $ λ e, e ▸ h
end equality
/-
quantifiers
-/
section quantifiers
variables {α : Sort*} {p q : α → Prop} {b : Prop}
def Exists.imp := @exists_imp_exists
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⟩
@[simp] theorem not_forall_not [decidable (∃ x, p x)] :
(¬ ∀ x, ¬ p x) ↔ ∃ x, p x :=
by haveI := decidable_of_iff (¬ ∃ x, p x) not_exists;
exact not_iff_comm.1 not_exists
@[simp] theorem not_exists_not [∀ x, decidable (p x)] :
(¬ ∃ x, ¬ p x) ↔ ∀ x, p x :=
by simp
@[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*) [inhabited α] : (α → b) ↔ b :=
⟨λ h, h (arbitrary α), λ hb x, hb⟩
@[simp] theorem exists_const (α : Sort*) [inhabited α] : (∃ x : α, b) ↔ b :=
⟨λ ⟨x, h⟩, h, λ h, ⟨arbitrary α, h⟩⟩
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' ∧ 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
@[simp] theorem forall_eq' {a' : α} : (∀a, a' = a → p a) ↔ p a' :=
by simp [@eq_comm _ a']
@[simp] theorem exists_eq' {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 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⟩
@[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
end quantifiers
/- classical versions -/
namespace classical
variables {α : Sort*} {p : α → Prop}
local attribute [instance] prop_decidable
theorem not_forall : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := not_forall
theorem forall_or_distrib_left {q : Prop} {p : α → Prop} :
(∀x, q ∨ p x) ↔ q ∨ (∀x, p x) :=
forall_or_distrib_left
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
theorem or_iff_not_imp_left {p q : Prop} : p ∨ q ↔ (¬ p → q) :=
or_iff_not_imp_left
theorem or_iff_not_imp_right {p q : Prop} : q ∨ p ↔ (¬ p → q) :=
or_iff_not_imp_right
/- use shortened names to avoid conflict when classical namespace is open -/
noncomputable theorem dec (p : Prop) : decidable p := by apply_instance
noncomputable theorem dec_pred (p : α → Prop) : decidable_pred p := by apply_instance
noncomputable theorem dec_rel (p : α → α → Prop) : decidable_rel p := by apply_instance
noncomputable theorem dec_eq (α : Sort*) : decidable_eq α := by apply_instance
end classical
/-
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) (_ : q 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
section nonempty
universes u v w
variables {α : Type u} {β : Type v} {γ : α → Type w}
attribute [simp] nonempty_of_inhabited
@[simp] lemma nonempty_Prop {p : Prop} : nonempty p ↔ p :=
iff.intro (assume ⟨h⟩, h) (assume h, ⟨h⟩)
@[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⟩)
end nonempty
|
c3138ade481aa36d2728d12725dfccae300d62f6 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /stage0/src/Lean/Meta/Match/Match.lean | b91a7939b68d7bbf9ea4aed8b740ab2b0203e32c | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 45,299 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.CollectLevelParams
import Lean.Util.Recognizers
import Lean.Compiler.ExternAttr
import Lean.Meta.Check
import Lean.Meta.Closure
import Lean.Meta.Tactic.Cases
import Lean.Meta.GeneralizeTelescope
import Lean.Meta.Match.MVarRenaming
import Lean.Meta.Match.CaseValues
import Lean.Meta.Match.CaseArraySizes
namespace Lean.Meta.Match
inductive Pattern : Type
| inaccessible (e : Expr) : Pattern
| var (fvarId : FVarId) : Pattern
| ctor (ctorName : Name) (us : List Level) (params : List Expr) (fields : List Pattern) : Pattern
| val (e : Expr) : Pattern
| arrayLit (type : Expr) (xs : List Pattern) : Pattern
| as (varId : FVarId) (p : Pattern) : Pattern
namespace Pattern
instance : Inhabited Pattern := ⟨Pattern.inaccessible (arbitrary _)⟩
partial def toMessageData : Pattern → MessageData
| inaccessible e => msg!".({e})"
| var varId => mkFVar varId
| ctor ctorName _ _ [] => ctorName
| ctor ctorName _ _ pats => msg!"({ctorName}{pats.foldl (fun (msg : MessageData) pat => msg ++ " " ++ toMessageData pat) Format.nil})"
| val e => e
| arrayLit _ pats => msg!"#[{MessageData.joinSep (pats.map toMessageData) ", "}]"
| as varId p => msg!"{mkFVar varId}@{toMessageData p}"
partial def toExpr : Pattern → MetaM Expr
| inaccessible e => pure e
| var fvarId => pure $ mkFVar fvarId
| val e => pure e
| as _ p => toExpr p
| arrayLit type xs => do
let xs ← xs.mapM toExpr;
mkArrayLit type xs
| ctor ctorName us params fields => do
let fields ← fields.mapM toExpr;
pure $ mkAppN (mkConst ctorName us) (params ++ fields).toArray
/- Apply the free variable substitution `s` to the given pattern -/
partial def applyFVarSubst (s : FVarSubst) : Pattern → Pattern
| inaccessible e => inaccessible $ s.apply e
| ctor n us ps fs => ctor n us (ps.map s.apply) $ fs.map (applyFVarSubst s)
| val e => val $ s.apply e
| arrayLit t xs => arrayLit (s.apply t) $ xs.map (applyFVarSubst s)
| var fvarId => match s.find? fvarId with
| some e => inaccessible e
| none => var fvarId
| as fvarId p => match s.find? fvarId with
| none => as fvarId $ applyFVarSubst s p
| some _ => applyFVarSubst s p
def replaceFVarId (fvarId : FVarId) (v : Expr) (p : Pattern) : Pattern :=
let s : FVarSubst := {}
p.applyFVarSubst (s.insert fvarId v)
partial def hasExprMVar : Pattern → Bool
| inaccessible e => e.hasExprMVar
| ctor _ _ ps fs => ps.any (·.hasExprMVar) || fs.any hasExprMVar
| val e => e.hasExprMVar
| as _ p => hasExprMVar p
| arrayLit t xs => t.hasExprMVar || xs.any hasExprMVar
| _ => false
end Pattern
partial def instantiatePatternMVars : Pattern → MetaM Pattern
| Pattern.inaccessible e => return Pattern.inaccessible (← instantiateMVars e)
| Pattern.val e => return Pattern.val (← instantiateMVars e)
| Pattern.ctor n us ps fields => return Pattern.ctor n us (← ps.mapM instantiateMVars) (← fields.mapM instantiatePatternMVars)
| Pattern.as x p => return Pattern.as x (← instantiatePatternMVars p)
| Pattern.arrayLit t xs => return Pattern.arrayLit (← instantiateMVars t) (← xs.mapM instantiatePatternMVars)
| p => return p
structure AltLHS :=
(ref : Syntax)
(fvarDecls : List LocalDecl) -- Free variables used in the patterns.
(patterns : List Pattern) -- We use `List Pattern` since we have nary match-expressions.
def instantiateAltLHSMVars (altLHS : AltLHS) : MetaM AltLHS :=
return { altLHS with
fvarDecls := (← altLHS.fvarDecls.mapM instantiateLocalDeclMVars),
patterns := (← altLHS.patterns.mapM instantiatePatternMVars)
}
structure Alt :=
(ref : Syntax)
(idx : Nat) -- for generating error messages
(rhs : Expr)
(fvarDecls : List LocalDecl)
(patterns : List Pattern)
namespace Alt
instance : Inhabited Alt := ⟨⟨arbitrary _, 0, arbitrary _, [], []⟩⟩
partial def toMessageData (alt : Alt) : MetaM MessageData := do
withExistingLocalDecls alt.fvarDecls do
let msg : List MessageData := alt.fvarDecls.map fun d => d.toExpr ++ ":(" ++ d.type ++ ")"
let msg : MessageData := msg ++ " |- " ++ (alt.patterns.map Pattern.toMessageData) ++ " => " ++ alt.rhs
addMessageContext msg
def applyFVarSubst (s : FVarSubst) (alt : Alt) : Alt :=
{ alt with
patterns := alt.patterns.map fun p => p.applyFVarSubst s,
fvarDecls := alt.fvarDecls.map fun d => d.applyFVarSubst s,
rhs := alt.rhs.applyFVarSubst s }
def replaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : Alt :=
{ alt with
patterns := alt.patterns.map fun p => p.replaceFVarId fvarId v,
fvarDecls :=
let decls := alt.fvarDecls.filter fun d => d.fvarId != fvarId
decls.map $ replaceFVarIdAtLocalDecl fvarId v,
rhs := alt.rhs.replaceFVarId fvarId v }
/-
Similar to `checkAndReplaceFVarId`, but ensures type of `v` is definitionally equal to type of `fvarId`.
This extra check is necessary when performing dependent elimination and inaccessible terms have been used.
For example, consider the following code fragment:
```
inductive Vec (α : Type u) : Nat → Type u
| nil : Vec α 0
| cons {n} (head : α) (tail : Vec α n) : Vec α (n+1)
inductive VecPred {α : Type u} (P : α → Prop) : {n : Nat} → Vec α n → Prop
| nil : VecPred P Vec.nil
| cons {n : Nat} {head : α} {tail : Vec α n} : P head → VecPred P tail → VecPred P (Vec.cons head tail)
theorem ex {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P
| _, Vec.cons head _, VecPred.cons h (w : VecPred P Vec.nil) => ⟨head, h⟩
```
Recall that `_` in a pattern can be elaborated into pattern variable or an inaccessible term.
The elaborator uses an inaccessible term when typing constraints restrict its value.
Thus, in the example above, the `_` at `Vec.cons head _` becomes the inaccessible pattern `.(Vec.nil)`
because the type ascription `(w : VecPred P Vec.nil)` propagates typing constraints that restrict its value to be `Vec.nil`.
After elaboration the alternative becomes:
```
| .(0), @Vec.cons .(α) .(0) head .(Vec.nil), @VecPred.cons .(α) .(P) .(0) .(head) .(Vec.nil) h w => ⟨head, h⟩
```
where
```
(head : α), (h: P head), (w : VecPred P Vec.nil)
```
Then, when we process this alternative in this module, the following check will detect that
`w` has type `VecPred P Vec.nil`, when it is supposed to have type `VecPred P tail`.
Note that if we had written
```
theorem ex {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P
| _, Vec.cons head Vec.nil, VecPred.cons h (w : VecPred P Vec.nil) => ⟨head, h⟩
```
we would get the easier to digest error message
```
missing cases:
_, (Vec.cons _ _ (Vec.cons _ _ _)), _
```
-/
def checkAndReplaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : MetaM Alt := do
match alt.fvarDecls.find? fun (fvarDecl : LocalDecl) => fvarDecl.fvarId == fvarId with
| none => throwErrorAt alt.ref "unknown free pattern variable"
| some fvarDecl => do
let vType ← inferType v
unless (← isDefEqGuarded fvarDecl.type vType) do
withExistingLocalDecls alt.fvarDecls do
throwErrorAt alt.ref $
msg!"type mismatch during dependent match-elimination at pattern variable '{mkFVar fvarDecl.fvarId}' with type{indentExpr fvarDecl.type}\nexpected type{indentExpr vType}"
pure $ replaceFVarId fvarId v alt
end Alt
inductive Example
| var : FVarId → Example
| underscore : Example
| ctor : Name → List Example → Example
| val : Expr → Example
| arrayLit : List Example → Example
namespace Example
partial def replaceFVarId (fvarId : FVarId) (ex : Example) : Example → Example
| var x => if x == fvarId then ex else var x
| ctor n exs => ctor n $ exs.map (replaceFVarId fvarId ex)
| arrayLit exs => arrayLit $ exs.map (replaceFVarId fvarId ex)
| ex => ex
partial def applyFVarSubst (s : FVarSubst) : Example → Example
| var fvarId =>
match s.get fvarId with
| Expr.fvar fvarId' _ => var fvarId'
| _ => underscore
| ctor n exs => ctor n $ exs.map (applyFVarSubst s)
| arrayLit exs => arrayLit $ exs.map (applyFVarSubst s)
| ex => ex
partial def varsToUnderscore : Example → Example
| var x => underscore
| ctor n exs => ctor n $ exs.map varsToUnderscore
| arrayLit exs => arrayLit $ exs.map varsToUnderscore
| ex => ex
partial def toMessageData : Example → MessageData
| var fvarId => mkFVar fvarId
| ctor ctorName [] => mkConst ctorName
| ctor ctorName exs => "(" ++ mkConst ctorName ++ exs.foldl (fun (msg : MessageData) pat => msg ++ " " ++ toMessageData pat) Format.nil ++ ")"
| arrayLit exs => "#" ++ MessageData.ofList (exs.map toMessageData)
| val e => e
| underscore => "_"
end Example
def examplesToMessageData (cex : List Example) : MessageData :=
MessageData.joinSep (cex.map (Example.toMessageData ∘ Example.varsToUnderscore)) ", "
structure Problem :=
(mvarId : MVarId)
(vars : List Expr)
(alts : List Alt)
(examples : List Example)
def withGoalOf {α} (p : Problem) (x : MetaM α) : MetaM α :=
withMVarContext p.mvarId x
instance : Inhabited Problem := ⟨{ mvarId := arbitrary _, vars := [], alts := [], examples := []}⟩
def Problem.toMessageData (p : Problem) : MetaM MessageData :=
withGoalOf p do
let alts ← p.alts.mapM Alt.toMessageData
let vars ← p.vars.mapM fun x => do let xType ← inferType x; pure (x ++ ":(" ++ xType ++ ")" : MessageData)
return "remaining variables: " ++ vars
++ Format.line ++ "alternatives:" ++ indentD (MessageData.joinSep alts Format.line)
++ Format.line ++ "examples: " ++ examplesToMessageData p.examples
++ Format.line
abbrev CounterExample := List Example
def counterExampleToMessageData (cex : CounterExample) : MessageData :=
examplesToMessageData cex
def counterExamplesToMessageData (cexs : List CounterExample) : MessageData :=
MessageData.joinSep (cexs.map counterExampleToMessageData) Format.line
structure MatcherResult :=
(matcher : Expr) -- The matcher. It is not just `Expr.const matcherName` because the type of the major premises may contain free variables.
(counterExamples : List CounterExample)
(unusedAltIdxs : List Nat)
/- The number of patterns in each AltLHS must be equal to majors.length -/
private def checkNumPatterns (majors : Array Expr) (lhss : List AltLHS) : MetaM Unit := do
let num := majors.size
if lhss.any fun lhs => lhs.patterns.length != num then
throwError "incorrect number of patterns"
private partial def withAltsAux {α} (motive : Expr) : List AltLHS → List Alt → Array (Expr × Nat) → (List Alt → Array (Expr × Nat) → MetaM α) → MetaM α
| [], alts, minors, k => k alts.reverse minors
| lhs::lhss, alts, minors, k => do
let xs := lhs.fvarDecls.toArray.map LocalDecl.toExpr
let minorType ← withExistingLocalDecls lhs.fvarDecls do
let args ← lhs.patterns.toArray.mapM Pattern.toExpr
let minorType := mkAppN motive args
mkForallFVars xs minorType
let (minorType, minorNumParams) := if !xs.isEmpty then (minorType, xs.size) else (mkSimpleThunkType minorType, 1)
let idx := alts.length
let minorName := (`h).appendIndexAfter (idx+1)
trace[Meta.Match.debug]! "minor premise {minorName} : {minorType}"
withLocalDeclD minorName minorType fun minor => do
let rhs := if xs.isEmpty then mkApp minor (mkConst `Unit.unit) else mkAppN minor xs
let minors := minors.push (minor, minorNumParams)
let fvarDecls ← lhs.fvarDecls.mapM instantiateLocalDeclMVars
let alts := { ref := lhs.ref, idx := idx, rhs := rhs, fvarDecls := fvarDecls, patterns := lhs.patterns : Alt } :: alts
withAltsAux motive lhss alts minors k
/- Given a list of `AltLHS`, create a minor premise for each one, convert them into `Alt`, and then execute `k` -/
private partial def withAlts {α} (motive : Expr) (lhss : List AltLHS) (k : List Alt → Array (Expr × Nat) → MetaM α) : MetaM α :=
withAltsAux motive lhss [] #[] k
def assignGoalOf (p : Problem) (e : Expr) : MetaM Unit :=
withGoalOf p (assignExprMVar p.mvarId e)
structure State :=
(used : Std.HashSet Nat := {}) -- used alternatives
(counterExamples : List (List Example) := [])
/-- Return true if the given (sub-)problem has been solved. -/
private def isDone (p : Problem) : Bool :=
p.vars.isEmpty
/-- Return true if the next element on the `p.vars` list is a variable. -/
private def isNextVar (p : Problem) : Bool :=
match p.vars with
| Expr.fvar _ _ :: _ => true
| _ => false
private def hasAsPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| Pattern.as _ _ :: _ => true
| _ => false
private def hasCtorPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| Pattern.ctor _ _ _ _ :: _ => true
| _ => false
private def hasValPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| Pattern.val _ :: _ => true
| _ => false
private def hasNatValPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| Pattern.val v :: _ => v.isNatLit
| _ => false
private def hasVarPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| Pattern.var _ :: _ => true
| _ => false
private def hasArrayLitPattern (p : Problem) : Bool :=
p.alts.any fun alt => match alt.patterns with
| Pattern.arrayLit _ _ :: _ => true
| _ => false
private def isVariableTransition (p : Problem) : Bool :=
p.alts.all fun alt => match alt.patterns with
| Pattern.inaccessible _ :: _ => true
| Pattern.var _ :: _ => true
| _ => false
private def isConstructorTransition (p : Problem) : Bool :=
(hasCtorPattern p || p.alts.isEmpty)
&& p.alts.all fun alt => match alt.patterns with
| Pattern.ctor _ _ _ _ :: _ => true
| Pattern.var _ :: _ => true
| Pattern.inaccessible _ :: _ => true
| _ => false
private def isValueTransition (p : Problem) : Bool :=
hasVarPattern p && hasValPattern p
&& p.alts.all fun alt => match alt.patterns with
| Pattern.val _ :: _ => true
| Pattern.var _ :: _ => true
| _ => false
private def isArrayLitTransition (p : Problem) : Bool :=
hasArrayLitPattern p && hasVarPattern p
&& p.alts.all fun alt => match alt.patterns with
| Pattern.arrayLit _ _ :: _ => true
| Pattern.var _ :: _ => true
| _ => false
private def isNatValueTransition (p : Problem) : Bool :=
hasNatValPattern p
&& (!isNextVar p ||
p.alts.any fun alt => match alt.patterns with
| Pattern.ctor _ _ _ _ :: _ => true
| Pattern.inaccessible _ :: _ => true
| _ => false)
private def processSkipInaccessible (p : Problem) : Problem :=
match p.vars with
| [] => unreachable!
| x :: xs => do
let alts := p.alts.map fun alt => match alt.patterns with
| Pattern.inaccessible _ :: ps => { alt with patterns := ps }
| _ => unreachable!
{ p with alts := alts, vars := xs }
private def processLeaf (p : Problem) : StateRefT State MetaM Unit :=
match p.alts with
| [] => do
liftM $ admit p.mvarId
modify fun s => { s with counterExamples := p.examples :: s.counterExamples }
| alt :: _ => do
-- TODO: check whether we have unassigned metavars in rhs
liftM $ assignGoalOf p alt.rhs
modify fun s => { s with used := s.used.insert alt.idx }
private def processAsPattern (p : Problem) : MetaM Problem :=
match p.vars with
| [] => unreachable!
| x :: xs => withGoalOf p do
let alts ← p.alts.mapM fun alt => match alt.patterns with
| Pattern.as fvarId p :: ps => { alt with patterns := p :: ps }.checkAndReplaceFVarId fvarId x
| _ => pure alt
pure { p with alts := alts }
private def processVariable (p : Problem) : MetaM Problem :=
match p.vars with
| [] => unreachable!
| x :: xs => withGoalOf p do
let alts ← p.alts.mapM fun alt => match alt.patterns with
| Pattern.inaccessible _ :: ps => pure { alt with patterns := ps }
| Pattern.var fvarId :: ps => { alt with patterns := ps }.checkAndReplaceFVarId fvarId x
| _ => unreachable!
pure { p with alts := alts, vars := xs }
private def throwInductiveTypeExpected {α} (e : Expr) : MetaM α := do
let t ← inferType e
throwError! "failed to compile pattern matching, inductive type expected{indentExpr e}\nhas type{indentExpr t}"
private def inLocalDecls (localDecls : List LocalDecl) (fvarId : FVarId) : Bool :=
localDecls.any fun d => d.fvarId == fvarId
namespace Unify
structure Context :=
(altFVarDecls : List LocalDecl)
structure State :=
(fvarSubst : FVarSubst := {})
abbrev M := ReaderT Context $ StateRefT State MetaM
def isAltVar (fvarId : FVarId) : M Bool := do
return inLocalDecls (← read).altFVarDecls fvarId
def expandIfVar (e : Expr) : M Expr := do
match e with
| Expr.fvar _ _ => return (← get).fvarSubst.apply e
| _ => return e
def occurs (fvarId : FVarId) (v : Expr) : Bool :=
Option.isSome $ v.find? fun e => match e with
| Expr.fvar fvarId' _ => fvarId == fvarId'
| _=> false
def assign (fvarId : FVarId) (v : Expr) : M Bool := do
if occurs fvarId v then
trace[Meta.Match.unify]! "assign occurs check failed, {mkFVar fvarId} := {v}"
pure false
else
let ctx ← read
if (← isAltVar fvarId) then
trace[Meta.Match.unify]! "{mkFVar fvarId} := {v}"
modify fun s => { s with fvarSubst := s.fvarSubst.insert fvarId v }
pure true
else
trace[Meta.Match.unify]! "assign failed variable is not local, {mkFVar fvarId} := {v}"
pure false
partial def unify (a : Expr) (b : Expr) : M Bool := do
trace[Meta.Match.unify]! "{a} =?= {b}"
if (← isDefEq a b) then
pure true
else
let a' ← expandIfVar a
let b' ← expandIfVar b
if a != a' || b != b' then unify a' b'
else match a, b with
| Expr.mdata _ a _, b => unify a b
| a, Expr.mdata _ b _ => unify a b
| Expr.fvar aFvarId _, Expr.fvar bFVarId _ => assign aFvarId b <||> assign bFVarId a
| Expr.fvar aFvarId _, b => assign aFvarId b
| a, Expr.fvar bFVarId _ => assign bFVarId a
| Expr.app aFn aArg _, Expr.app bFn bArg _ => unify aFn bFn <&&> unify aArg bArg
| _, _ =>
trace[Meta.Match.unify]! "unify failed @ {a} =?= {b}"
pure false
end Unify
private def unify? (altFVarDecls : List LocalDecl) (a b : Expr) : MetaM (Option FVarSubst) := do
let a ← instantiateMVars a
let b ← instantiateMVars b
let (b, s) ← Unify.unify a b { altFVarDecls := altFVarDecls} $.run {}
if b then pure s.fvarSubst else pure none
private def expandVarIntoCtor? (alt : Alt) (fvarId : FVarId) (ctorName : Name) : MetaM (Option Alt) :=
withExistingLocalDecls alt.fvarDecls do
let env ← getEnv
let ldecl ← getLocalDecl fvarId
let expectedType ← inferType (mkFVar fvarId)
let expectedType ← whnfD expectedType
let (ctorLevels, ctorParams) ← getInductiveUniverseAndParams expectedType
let ctor := mkAppN (mkConst ctorName ctorLevels) ctorParams
let ctorType ← inferType ctor
forallTelescopeReducing ctorType fun ctorFields resultType => do
let ctor := mkAppN ctor ctorFields
let alt := alt.replaceFVarId fvarId ctor
let ctorFieldDecls ← ctorFields.mapM fun ctorField => getLocalDecl ctorField.fvarId!
let newAltDecls := ctorFieldDecls.toList ++ alt.fvarDecls
let subst? ← unify? newAltDecls resultType expectedType
match subst? with
| none => pure none
| some subst =>
let newAltDecls := newAltDecls.filter fun d => !subst.contains d.fvarId -- remove declarations that were assigned
let newAltDecls := newAltDecls.map fun d => d.applyFVarSubst subst -- apply substitution to remaining declaration types
let patterns := alt.patterns.map fun p => p.applyFVarSubst subst
let rhs := subst.apply alt.rhs
let ctorFieldPatterns := ctorFields.toList.map fun ctorField => match subst.get ctorField.fvarId! with
| e@(Expr.fvar fvarId _) => if inLocalDecls newAltDecls fvarId then Pattern.var fvarId else Pattern.inaccessible e
| e => Pattern.inaccessible e
pure $ some { alt with fvarDecls := newAltDecls, rhs := rhs, patterns := ctorFieldPatterns ++ patterns }
private def getInductiveVal? (x : Expr) : MetaM (Option InductiveVal) := do
let xType ← inferType x
let xType ← whnfD xType
match xType.getAppFn with
| Expr.const constName _ _ =>
let cinfo ← getConstInfo constName
match cinfo with
| ConstantInfo.inductInfo val => pure (some val)
| _ => pure none
| _ => pure none
private def hasRecursiveType (x : Expr) : MetaM Bool := do
match (← getInductiveVal? x) with
| some val => pure val.isRec
| _ => pure false
/- Given `alt` s.t. the next pattern is an inaccessible pattern `e`,
try to normalize `e` into a constructor application.
If it is not a constructor, throw an error.
Otherwise, if it is a constructor application of `ctorName`,
update the next patterns with the fields of the constructor.
Otherwise, return none. -/
def processInaccessibleAsCtor (alt : Alt) (ctorName : Name) : MetaM (Option Alt) := do
let env ← getEnv
match alt.patterns with
| p@(Pattern.inaccessible e) :: ps =>
trace[Meta.Match.match]! "inaccessible in ctor step {e}"
withExistingLocalDecls alt.fvarDecls do
-- Try to push inaccessible annotations.
let e ← whnfD e
match e.constructorApp? env with
| some (ctorVal, ctorArgs) =>
if ctorVal.name == ctorName then
let fields := ctorArgs.extract ctorVal.nparams ctorArgs.size
let fields := fields.toList.map Pattern.inaccessible
pure $ some { alt with patterns := fields ++ ps }
else
pure none
| _ => throwErrorAt! alt.ref "dependent match elimination failed, inaccessible pattern found{indentD p.toMessageData}\nconstructor expected"
| _ => unreachable!
private def processConstructor (p : Problem) : MetaM (Array Problem) := do
trace[Meta.Match.match]! "constructor step"
let env ← getEnv
match p.vars with
| [] => unreachable!
| x :: xs => do
let subgoals? ← commitWhenSome? do
let subgoals ← cases p.mvarId x.fvarId!
if subgoals.isEmpty then
/- Easy case: we have solved problem `p` since there are no subgoals -/
pure (some #[])
else if !p.alts.isEmpty then
pure (some subgoals)
else do
let isRec ← withGoalOf p $ hasRecursiveType x
/- If there are no alternatives and the type of the current variable is recursive, we do NOT consider
a constructor-transition to avoid nontermination.
TODO: implement a more general approach if this is not sufficient in practice -/
if isRec then pure none
else pure (some subgoals)
match subgoals? with
| none => pure #[{ p with vars := xs }]
| some subgoals =>
subgoals.mapM fun subgoal => withMVarContext subgoal.mvarId do
let subst := subgoal.subst
let fields := subgoal.fields.toList
let newVars := fields ++ xs
let newVars := newVars.map fun x => x.applyFVarSubst subst
let subex := Example.ctor subgoal.ctorName $ fields.map fun field => match field with
| Expr.fvar fvarId _ => Example.var fvarId
| _ => Example.underscore -- This case can happen due to dependent elimination
let examples := p.examples.map $ Example.replaceFVarId x.fvarId! subex
let examples := examples.map $ Example.applyFVarSubst subst
let newAlts := p.alts.filter fun alt => match alt.patterns with
| Pattern.ctor n _ _ _ :: _ => n == subgoal.ctorName
| Pattern.var _ :: _ => true
| Pattern.inaccessible _ :: _ => true
| _ => false
let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst
let newAlts ← newAlts.filterMapM fun alt => match alt.patterns with
| Pattern.ctor _ _ _ fields :: ps => pure $ some { alt with patterns := fields ++ ps }
| Pattern.var fvarId :: ps => expandVarIntoCtor? { alt with patterns := ps } fvarId subgoal.ctorName
| Pattern.inaccessible _ :: _ => processInaccessibleAsCtor alt subgoal.ctorName
| _ => unreachable!
pure { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples }
private def processNonVariable (p : Problem) : MetaM Problem :=
match p.vars with
| [] => unreachable!
| x :: xs => withGoalOf p do
let x ← whnfD x
let env ← getEnv
match x.constructorApp? env with
| some (ctorVal, xArgs) =>
let alts ← p.alts.filterMapM fun alt => match alt.patterns with
| Pattern.ctor n _ _ fields :: ps =>
if n != ctorVal.name then
pure none
else
pure $ some { alt with patterns := fields ++ ps }
| Pattern.inaccessible _ :: _ => processInaccessibleAsCtor alt ctorVal.name
| p :: _ => throwError! "failed to compile pattern matching, inaccessible pattern or constructor expected{indentD p.toMessageData}"
| _ => unreachable!
let xFields := xArgs.extract ctorVal.nparams xArgs.size
pure { p with alts := alts, vars := xFields.toList ++ xs }
| none => throwError! "failed to compile pattern matching, constructor expected{indentExpr x}"
private def collectValues (p : Problem) : Array Expr :=
p.alts.foldl (init := #[]) fun values alt =>
match alt.patterns with
| Pattern.val v :: _ => if values.contains v then values else values.push v
| _ => values
private def isFirstPatternVar (alt : Alt) : Bool :=
match alt.patterns with
| Pattern.var _ :: _ => true
| _ => false
private def processValue (p : Problem) : MetaM (Array Problem) := do
trace[Meta.Match.match]! "value step"
match p.vars with
| [] => unreachable!
| x :: xs => do
let values := collectValues p
let subgoals ← caseValues p.mvarId x.fvarId! values
subgoals.mapIdxM fun i subgoal => do
if h : i.val < values.size then
let value := values.get ⟨i, h⟩
-- (x = value) branch
let subst := subgoal.subst
let examples := p.examples.map $ Example.replaceFVarId x.fvarId! (Example.val value)
let examples := examples.map $ Example.applyFVarSubst subst
let newAlts := p.alts.filter fun alt => match alt.patterns with
| Pattern.val v :: _ => v == value
| Pattern.var _ :: _ => true
| _ => false
let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst
let newAlts := newAlts.map fun alt => match alt.patterns with
| Pattern.val _ :: ps => { alt with patterns := ps }
| Pattern.var fvarId :: ps =>
let alt := { alt with patterns := ps }
alt.replaceFVarId fvarId value
| _ => unreachable!
let newVars := xs.map fun x => x.applyFVarSubst subst
pure { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples }
else
-- else branch for value
let newAlts := p.alts.filter isFirstPatternVar
pure { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs }
private def collectArraySizes (p : Problem) : Array Nat :=
p.alts.foldl (init := #[]) fun sizes alt =>
match alt.patterns with
| Pattern.arrayLit _ ps :: _ => let sz := ps.length; if sizes.contains sz then sizes else sizes.push sz
| _ => sizes
private def expandVarIntoArrayLit (alt : Alt) (fvarId : FVarId) (arrayElemType : Expr) (arraySize : Nat) : MetaM Alt :=
withExistingLocalDecls alt.fvarDecls do
let fvarDecl ← getLocalDecl fvarId
let varNamePrefix := fvarDecl.userName
let rec loop
| n+1, newVars =>
withLocalDeclD (varNamePrefix.appendIndexAfter (n+1)) arrayElemType fun x =>
loop n (newVars.push x)
| 0, newVars => do
let arrayLit ← mkArrayLit arrayElemType newVars.toList
let alt := alt.replaceFVarId fvarId arrayLit
let newDecls ← newVars.toList.mapM fun newVar => getLocalDecl newVar.fvarId!
let newPatterns := newVars.toList.map fun newVar => Pattern.var newVar.fvarId!
pure { alt with fvarDecls := newDecls ++ alt.fvarDecls, patterns := newPatterns ++ alt.patterns }
loop arraySize #[]
private def processArrayLit (p : Problem) : MetaM (Array Problem) := do
trace[Meta.Match.match]! "array literal step"
match p.vars with
| [] => unreachable!
| x :: xs => do
let sizes := collectArraySizes p
let subgoals ← caseArraySizes p.mvarId x.fvarId! sizes
subgoals.mapIdxM fun i subgoal => do
if h : i.val < sizes.size then
let size := sizes.get! i
let subst := subgoal.subst
let elems := subgoal.elems.toList
let newVars := elems.map mkFVar ++ xs
let newVars := newVars.map fun x => x.applyFVarSubst subst
let subex := Example.arrayLit $ elems.map Example.var
let examples := p.examples.map $ Example.replaceFVarId x.fvarId! subex
let examples := examples.map $ Example.applyFVarSubst subst
let newAlts := p.alts.filter fun alt => match alt.patterns with
| Pattern.arrayLit _ ps :: _ => ps.length == size
| Pattern.var _ :: _ => true
| _ => false
let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst
let newAlts ← newAlts.mapM fun alt => match alt.patterns with
| Pattern.arrayLit _ pats :: ps => pure { alt with patterns := pats ++ ps }
| Pattern.var fvarId :: ps => do let α ← getArrayArgType x; expandVarIntoArrayLit { alt with patterns := ps } fvarId α size
| _ => unreachable!
pure { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples }
else do
-- else branch
let newAlts := p.alts.filter isFirstPatternVar
pure { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs }
private def expandNatValuePattern (p : Problem) : Problem := do
let alts := p.alts.map fun alt => match alt.patterns with
| Pattern.val (Expr.lit (Literal.natVal 0) _) :: ps => { alt with patterns := Pattern.ctor `Nat.zero [] [] [] :: ps }
| Pattern.val (Expr.lit (Literal.natVal (n+1)) _) :: ps => { alt with patterns := Pattern.ctor `Nat.succ [] [] [Pattern.val (mkNatLit n)] :: ps }
| _ => alt
{ p with alts := alts }
private def traceStep (msg : String) : StateRefT State MetaM Unit :=
trace[Meta.Match.match]! "{msg} step"
private def traceState (p : Problem) : MetaM Unit :=
withGoalOf p (traceM `Meta.Match.match p.toMessageData)
private def throwNonSupported (p : Problem) : MetaM Unit :=
withGoalOf p do
let msg ← p.toMessageData
throwError! "failed to compile pattern matching, stuck at{indentD msg}"
def isCurrVarInductive (p : Problem) : MetaM Bool := do
match p.vars with
| [] => pure false
| x::_ => withGoalOf p do
let val? ← getInductiveVal? x
pure val?.isSome
private partial def process (p : Problem) : StateRefT State MetaM Unit := withIncRecDepth do
traceState p
let isInductive ← liftM $ isCurrVarInductive p
if isDone p then
processLeaf p
else if hasAsPattern p then
traceStep ("as-pattern")
let p ← processAsPattern p
process p
else if isNatValueTransition p then
traceStep ("nat value to constructor")
process (expandNatValuePattern p)
else if !isNextVar p then
traceStep ("non variable")
let p ← processNonVariable p
process p
else if isInductive && isConstructorTransition p then
let ps ← processConstructor p
ps.forM process
else if isVariableTransition p then
traceStep ("variable")
let p ← processVariable p
process p
else if isValueTransition p then
let ps ← processValue p
ps.forM process
else if isArrayLitTransition p then
let ps ← processArrayLit p
ps.forM process
else
liftM $ throwNonSupported p
/--
A "matcher" auxiliary declaration has the following structure:
- `numParams` parameters
- motive
- `numDiscrs` discriminators (aka major premises)
- `altNumParams.size` alternatives (aka minor premises) where alternative `i` has `altNumParams[i]` parameters
- `uElimPos?` is `some pos` when the matcher can eliminate in different universe levels, and
`pos` is the position of the universe level parameter that specifies the elimination universe.
It is `none` if the matcher only eliminates into `Prop`. -/
structure MatcherInfo :=
(numParams : Nat)
(numDiscrs : Nat)
(altNumParams : Array Nat)
(uElimPos? : Option Nat)
def MatcherInfo.numAlts (matcherInfo : MatcherInfo) : Nat :=
matcherInfo.altNumParams.size
namespace Extension
structure Entry :=
(name : Name)
(info : MatcherInfo)
structure State :=
(map : SMap Name MatcherInfo := {})
instance : Inhabited State := ⟨{}⟩
def State.addEntry (s : State) (e : Entry) : State := { s with map := s.map.insert e.name e.info }
def State.switch (s : State) : State := { s with map := s.map.switch }
builtin_initialize extension : SimplePersistentEnvExtension Entry State ←
registerSimplePersistentEnvExtension {
name := `matcher,
addEntryFn := State.addEntry,
addImportedFn := fun es => (mkStateFromImportedEntries State.addEntry {} es).switch
}
def addMatcherInfo (env : Environment) (matcherName : Name) (info : MatcherInfo) : Environment :=
extension.addEntry env { name := matcherName, info := info }
def getMatcherInfo? (env : Environment) (declName : Name) : Option MatcherInfo :=
(extension.getState env).map.find? declName
end Extension
def addMatcherInfo (matcherName : Name) (info : MatcherInfo) : MetaM Unit :=
modifyEnv fun env => Extension.addMatcherInfo env matcherName info
private def getUElimPos? (matcherLevels : List Level) (uElim : Level) : MetaM (Option Nat) :=
if uElim == levelZero then
pure none
else match matcherLevels.toArray.indexOf? uElim with
| none => throwError "dependent match elimination failed, universe level not found"
| some pos => pure $ some pos.val
/- See comment at `mkMatcher` before `mkAuxDefinition` -/
builtin_initialize
registerOption `bootstrap.gen_matcher_code { defValue := true, group := "bootstrap", descr := "disable code generation for auxiliary matcher function" }
def generateMatcherCode (opts : Options) : Bool :=
opts.get `bootstrap.gen_matcher_code true
/-
Create a dependent matcher for `matchType` where `matchType` is of the form
`(a_1 : A_1) -> (a_2 : A_2[a_1]) -> ... -> (a_n : A_n[a_1, a_2, ... a_{n-1}]) -> B[a_1, ..., a_n]`
where `n = numDiscrs`, and the `lhss` are the left-hand-sides of the `match`-expression alternatives.
Each `AltLHS` has a list of local declarations and a list of patterns.
The number of patterns must be the same in each `AltLHS`.
The generated matcher has the structure described at `MatcherInfo`. The motive argument is of the form
`(motive : (a_1 : A_1) -> (a_2 : A_2[a_1]) -> ... -> (a_n : A_n[a_1, a_2, ... a_{n-1}]) -> Sort v)`
where `v` is a universe parameter or 0 if `B[a_1, ..., a_n]` is a proposition. -/
def mkMatcher (matcherName : Name) (matchType : Expr) (numDiscrs : Nat) (lhss : List AltLHS) : MetaM MatcherResult :=
forallBoundedTelescope matchType numDiscrs fun majors matchTypeBody => do
checkNumPatterns majors lhss
/- We generate an matcher that can eliminate using different motives with different universe levels.
`uElim` is the universe level the caller wants to eliminate to.
If it is not levelZero, we create a matcher that can eliminate in any universe level.
This is useful for implementing `MatcherApp.addArg` because it may have to change the universe level. -/
let uElim ← getLevel matchTypeBody
let uElimGen ← if uElim == levelZero then pure levelZero else mkFreshLevelMVar
let motiveType ← mkForallFVars majors (mkSort uElimGen)
withLocalDeclD `motive motiveType fun motive => do
trace! `Meta.Match.debug ("motiveType: " ++ motiveType)
let mvarType := mkAppN motive majors
trace! `Meta.Match.debug ("target: " ++ mvarType)
withAlts motive lhss fun alts minors => do
let mvar ← mkFreshExprMVar mvarType
let examples := majors.toList.map fun major => Example.var major.fvarId!
let (_, s) ← (process { mvarId := mvar.mvarId!, vars := majors.toList, alts := alts, examples := examples }).run {}
let args := #[motive] ++ majors ++ minors.map Prod.fst
let type ← mkForallFVars args mvarType
let val ← mkLambdaFVars args mvar
trace! `Meta.Match.debug ("matcher value: " ++ val ++ "\ntype: " ++ type)
/- The option `bootstrap.gen_matcher_code` is a helper hack. It is useful, for example,
for compiling `src/Init/Data/Int`. It is needed because the compiler uses `Int.decLt`
for generating code for `Int.casesOn` applications, but `Int.casesOn` is used to
give the reference implementation for
```
@[extern "lean_int_neg"] def neg (n : @& Int) : Int :=
match n with
| ofNat n => negOfNat n
| negSucc n => succ n
```
which is defined **before** `Int.decLt` -/
let matcher ← mkAuxDefinition matcherName type val (compile := generateMatcherCode (← getOptions))
trace! `Meta.Match.debug ("matcher levels: " ++ toString matcher.getAppFn.constLevels! ++ ", uElim: " ++ toString uElimGen)
let uElimPos? ← getUElimPos? matcher.getAppFn.constLevels! uElimGen
isLevelDefEq uElimGen uElim
addMatcherInfo matcherName { numParams := matcher.getAppNumArgs, numDiscrs := numDiscrs, altNumParams := minors.map Prod.snd, uElimPos? := uElimPos? }
setInlineAttribute matcherName
trace[Meta.Match.debug]! "matcher: {matcher}"
let unusedAltIdxs : List Nat := lhss.length.fold
(fun i r => if s.used.contains i then r else i::r)
[]
pure { matcher := matcher, counterExamples := s.counterExamples, unusedAltIdxs := unusedAltIdxs.reverse }
end Match
export Match (MatcherInfo)
def getMatcherInfo? (declName : Name) : MetaM (Option MatcherInfo) := do
let env ← getEnv
pure $ Match.Extension.getMatcherInfo? env declName
def isMatcher (declName : Name) : MetaM Bool := do
let info? ← getMatcherInfo? declName
pure info?.isSome
structure MatcherApp :=
(matcherName : Name)
(matcherLevels : Array Level)
(uElimPos? : Option Nat)
(params : Array Expr)
(motive : Expr)
(discrs : Array Expr)
(altNumParams : Array Nat)
(alts : Array Expr)
(remaining : Array Expr)
def matchMatcherApp? (e : Expr) : MetaM (Option MatcherApp) :=
match e.getAppFn with
| Expr.const declName declLevels _ => do
let some info ← getMatcherInfo? declName | pure none
let args := e.getAppArgs
if args.size < info.numParams + 1 + info.numDiscrs + info.numAlts then pure none
else
pure $ some {
matcherName := declName,
matcherLevels := declLevels.toArray,
uElimPos? := info.uElimPos?,
params := args.extract 0 info.numParams,
motive := args.get! info.numParams,
discrs := args.extract (info.numParams + 1) (info.numParams + 1 + info.numDiscrs),
altNumParams := info.altNumParams,
alts := args.extract (info.numParams + 1 + info.numDiscrs) (info.numParams + 1 + info.numDiscrs + info.numAlts),
remaining := args.extract (info.numParams + 1 + info.numDiscrs + info.numAlts) args.size
}
| _ => pure none
def MatcherApp.toExpr (matcherApp : MatcherApp) : Expr :=
let result := mkAppN (mkConst matcherApp.matcherName matcherApp.matcherLevels.toList) matcherApp.params
let result := mkApp result matcherApp.motive
let result := mkAppN result matcherApp.discrs
let result := mkAppN result matcherApp.alts
mkAppN result matcherApp.remaining
/- Auxiliary function for MatcherApp.addArg -/
private partial def updateAlts (typeNew : Expr) (altNumParams : Array Nat) (alts : Array Expr) (i : Nat) : MetaM (Array Nat × Array Expr) := do
if h : i < alts.size then
let alt := alts.get ⟨i, h⟩
let numParams := altNumParams[i]
let typeNew ← whnfD typeNew
match typeNew with
| Expr.forallE n d b _ =>
let alt ← forallBoundedTelescope d (some numParams) fun xs d => do
let alt ← try instantiateLambda alt xs catch _ => throwError "unexpected matcher application, insufficient number of parameters in alternative"
forallBoundedTelescope d (some 1) fun x d => do
let alt ← mkLambdaFVars x alt -- x is the new argument we are adding to the alternative
let alt ← mkLambdaFVars xs alt
pure alt
updateAlts (b.instantiate1 alt) (altNumParams.set! i (numParams+1)) (alts.set ⟨i, h⟩ alt) (i+1)
| _ => throwError "unexpected type at MatcherApp.addArg"
else
pure (altNumParams, alts)
/- Given
- matcherApp `match_i As (fun xs => motive[xs]) discrs (fun ys_1 => (alt_1 : motive (C_1[ys_1])) ... (fun ys_n => (alt_n : motive (C_n[ys_n]) remaining`, and
- expression `e : B[discrs]`,
Construct the term
`match_i As (fun xs => B[xs] -> motive[xs]) discrs (fun ys_1 (y : B[C_1[ys_1]]) => alt_1) ... (fun ys_n (y : B[C_n[ys_n]]) => alt_n) e remaining`, and
We use `kabstract` to abstract the discriminants from `B[discrs]`.
This method assumes
- the `matcherApp.motive` is a lambda abstraction where `xs.size == discrs.size`
- each alternative is a lambda abstraction where `ys_i.size == matcherApp.altNumParams[i]`
-/
def MatcherApp.addArg (matcherApp : MatcherApp) (e : Expr) : MetaM MatcherApp :=
lambdaTelescope matcherApp.motive fun motiveArgs motiveBody => do
unless motiveArgs.size == matcherApp.discrs.size do
-- This error can only happen if someone implemented a transformation that rewrites the motive created by `mkMatcher`.
throwError! "unexpected matcher application, motive must be lambda expression with #{matcherApp.discrs.size} arguments"
let eType ← inferType e
let eTypeAbst ← matcherApp.discrs.size.foldRevM (init := eType) fun i eTypeAbst => do
let motiveArg := motiveArgs[i]
let discr := matcherApp.discrs[i]
let eTypeAbst ← kabstract eTypeAbst discr
pure $ eTypeAbst.instantiate1 motiveArg
let motiveBody ← mkArrow eTypeAbst motiveBody
let matcherLevels ← match matcherApp.uElimPos? with
| none => pure matcherApp.matcherLevels
| some pos =>
let uElim ← getLevel motiveBody
pure $ matcherApp.matcherLevels.set! pos uElim
let motive ← mkLambdaFVars motiveArgs motiveBody
-- Construct `aux` `match_i As (fun xs => B[xs] → motive[xs]) discrs`, and infer its type `auxType`.
-- We use `auxType` to infer the type `B[C_i[ys_i]]` of the new argument in each alternative.
let aux := mkAppN (mkConst matcherApp.matcherName matcherLevels.toList) matcherApp.params
let aux := mkApp aux motive
let aux := mkAppN aux matcherApp.discrs
trace! `Meta.debug aux
check aux
unless (← isTypeCorrect aux) do
throwError "failed to add argument to matcher application, type error when constructing the new motive"
let auxType ← inferType aux
let (altNumParams, alts) ← updateAlts auxType matcherApp.altNumParams matcherApp.alts 0
pure { matcherApp with
matcherLevels := matcherLevels,
motive := motive,
alts := alts,
altNumParams := altNumParams,
remaining := #[e] ++ matcherApp.remaining
}
builtin_initialize
registerTraceClass `Meta.Match.match
registerTraceClass `Meta.Match.debug
registerTraceClass `Meta.Match.unify
end Lean.Meta
|
0fd89c4c1c481602e16e3f5c76f3991646f06036 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/analysis/inner_product_space/orthogonal.lean | e97459a37a1640126ab0b4bff15c6d9ec9dfcfee | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 13,741 | lean | /-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Sébastien Gouëzel, Frédéric Dupuis
-/
import linear_algebra.bilinear_form
import analysis.inner_product_space.basic
/-!
# Orthogonal complements of submodules
In this file, the `orthogonal` complement of a submodule `K` is defined, and basic API established.
Some of the more subtle results about the orthogonal complement are delayed to
`analysis.inner_product_space.projection`.
See also `bilin_form.orthogonal` for orthogonality with respect to a general bilinear form.
## Notation
The orthogonal complement of a submodule `K` is denoted by `Kᗮ`.
The proposition that two submodules are orthogonal, `submodule.is_ortho`, is denoted by `U ⟂ V`.
Note this is not the same unicode symbol as `⊥` (`has_bot`).
-/
variables {𝕜 E F : Type*} [is_R_or_C 𝕜]
variables [normed_add_comm_group E] [inner_product_space 𝕜 E]
variables [normed_add_comm_group F] [inner_product_space 𝕜 F]
local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y
namespace submodule
variables (K : submodule 𝕜 E)
/-- The subspace of vectors orthogonal to a given subspace. -/
def orthogonal : submodule 𝕜 E :=
{ carrier := {v | ∀ u ∈ K, ⟪u, v⟫ = 0},
zero_mem' := λ _ _, inner_zero_right _,
add_mem' := λ x y hx hy u hu, by rw [inner_add_right, hx u hu, hy u hu, add_zero],
smul_mem' := λ c x hx u hu, by rw [inner_smul_right, hx u hu, mul_zero] }
notation K`ᗮ`:1200 := orthogonal K
/-- When a vector is in `Kᗮ`. -/
lemma mem_orthogonal (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪u, v⟫ = 0 := iff.rfl
/-- When a vector is in `Kᗮ`, with the inner product the
other way round. -/
lemma mem_orthogonal' (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪v, u⟫ = 0 :=
by simp_rw [mem_orthogonal, inner_eq_zero_symm]
variables {K}
/-- A vector in `K` is orthogonal to one in `Kᗮ`. -/
lemma inner_right_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪u, v⟫ = 0 :=
(K.mem_orthogonal v).1 hv u hu
/-- A vector in `Kᗮ` is orthogonal to one in `K`. -/
lemma inner_left_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪v, u⟫ = 0 :=
by rw [inner_eq_zero_symm]; exact inner_right_of_mem_orthogonal hu hv
/-- A vector is in `(𝕜 ∙ u)ᗮ` iff it is orthogonal to `u`. -/
lemma mem_orthogonal_singleton_iff_inner_right {u v : E} : v ∈ (𝕜 ∙ u)ᗮ ↔ ⟪u, v⟫ = 0 :=
begin
refine ⟨inner_right_of_mem_orthogonal (mem_span_singleton_self u), _⟩,
intros hv w hw,
rw mem_span_singleton at hw,
obtain ⟨c, rfl⟩ := hw,
simp [inner_smul_left, hv],
end
/-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/
lemma mem_orthogonal_singleton_iff_inner_left {u v : E} : v ∈ (𝕜 ∙ u)ᗮ ↔ ⟪v, u⟫ = 0 :=
by rw [mem_orthogonal_singleton_iff_inner_right, inner_eq_zero_symm]
lemma sub_mem_orthogonal_of_inner_left {x y : E}
(h : ∀ (v : K), ⟪x, v⟫ = ⟪y, v⟫) : x - y ∈ Kᗮ :=
begin
rw mem_orthogonal',
intros u hu,
rw [inner_sub_left, sub_eq_zero],
exact h ⟨u, hu⟩,
end
lemma sub_mem_orthogonal_of_inner_right {x y : E}
(h : ∀ (v : K), ⟪(v : E), x⟫ = ⟪(v : E), y⟫) : x - y ∈ Kᗮ :=
begin
intros u hu,
rw [inner_sub_right, sub_eq_zero],
exact h ⟨u, hu⟩,
end
variables (K)
/-- `K` and `Kᗮ` have trivial intersection. -/
lemma inf_orthogonal_eq_bot : K ⊓ Kᗮ = ⊥ :=
begin
rw eq_bot_iff,
intros x,
rw mem_inf,
exact λ ⟨hx, ho⟩, inner_self_eq_zero.1 (ho x hx)
end
/-- `K` and `Kᗮ` have trivial intersection. -/
lemma orthogonal_disjoint : disjoint K Kᗮ :=
by simp [disjoint_iff, K.inf_orthogonal_eq_bot]
/-- `Kᗮ` can be characterized as the intersection of the kernels of the operations of
inner product with each of the elements of `K`. -/
lemma orthogonal_eq_inter : Kᗮ = ⨅ v : K, linear_map.ker (innerSL 𝕜 (v : E)) :=
begin
apply le_antisymm,
{ rw le_infi_iff,
rintros ⟨v, hv⟩ w hw,
simpa using hw _ hv },
{ intros v hv w hw,
simp only [mem_infi] at hv,
exact hv ⟨w, hw⟩ }
end
/-- The orthogonal complement of any submodule `K` is closed. -/
lemma is_closed_orthogonal : is_closed (Kᗮ : set E) :=
begin
rw orthogonal_eq_inter K,
have := λ v : K, continuous_linear_map.is_closed_ker (innerSL 𝕜 (v : E)),
convert is_closed_Inter this,
simp only [infi_coe],
end
/-- In a complete space, the orthogonal complement of any submodule `K` is complete. -/
instance [complete_space E] : complete_space Kᗮ := K.is_closed_orthogonal.complete_space_coe
variables (𝕜 E)
/-- `orthogonal` gives a `galois_connection` between
`submodule 𝕜 E` and its `order_dual`. -/
lemma orthogonal_gc :
@galois_connection (submodule 𝕜 E) (submodule 𝕜 E)ᵒᵈ _ _
orthogonal orthogonal :=
λ K₁ K₂, ⟨λ h v hv u hu, inner_left_of_mem_orthogonal hv (h hu),
λ h v hv u hu, inner_left_of_mem_orthogonal hv (h hu)⟩
variables {𝕜 E}
/-- `orthogonal` reverses the `≤` ordering of two
subspaces. -/
lemma orthogonal_le {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₂ᗮ ≤ K₁ᗮ :=
(orthogonal_gc 𝕜 E).monotone_l h
/-- `orthogonal.orthogonal` preserves the `≤` ordering of two
subspaces. -/
lemma orthogonal_orthogonal_monotone {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) :
K₁ᗮᗮ ≤ K₂ᗮᗮ :=
orthogonal_le (orthogonal_le h)
/-- `K` is contained in `Kᗮᗮ`. -/
lemma le_orthogonal_orthogonal : K ≤ Kᗮᗮ := (orthogonal_gc 𝕜 E).le_u_l _
/-- The inf of two orthogonal subspaces equals the subspace orthogonal
to the sup. -/
lemma inf_orthogonal (K₁ K₂ : submodule 𝕜 E) : K₁ᗮ ⊓ K₂ᗮ = (K₁ ⊔ K₂)ᗮ :=
(orthogonal_gc 𝕜 E).l_sup.symm
/-- The inf of an indexed family of orthogonal subspaces equals the
subspace orthogonal to the sup. -/
lemma infi_orthogonal {ι : Type*} (K : ι → submodule 𝕜 E) : (⨅ i, (K i)ᗮ) = (supr K)ᗮ :=
(orthogonal_gc 𝕜 E).l_supr.symm
/-- The inf of a set of orthogonal subspaces equals the subspace orthogonal to the sup. -/
lemma Inf_orthogonal (s : set $ submodule 𝕜 E) : (⨅ K ∈ s, Kᗮ) = (Sup s)ᗮ :=
(orthogonal_gc 𝕜 E).l_Sup.symm
@[simp] lemma top_orthogonal_eq_bot : (⊤ : submodule 𝕜 E)ᗮ = ⊥ :=
begin
ext,
rw [mem_bot, mem_orthogonal],
exact ⟨λ h, inner_self_eq_zero.mp (h x mem_top), by { rintro rfl, simp }⟩
end
@[simp] lemma bot_orthogonal_eq_top : (⊥ : submodule 𝕜 E)ᗮ = ⊤ :=
begin
rw [← top_orthogonal_eq_bot, eq_top_iff],
exact le_orthogonal_orthogonal ⊤
end
@[simp] lemma orthogonal_eq_top_iff : Kᗮ = ⊤ ↔ K = ⊥ :=
begin
refine ⟨_, by { rintro rfl, exact bot_orthogonal_eq_top }⟩,
intro h,
have : K ⊓ Kᗮ = ⊥ := K.orthogonal_disjoint.eq_bot,
rwa [h, inf_comm, top_inf_eq] at this
end
lemma orthogonal_family_self :
orthogonal_family 𝕜 (λ b, ↥(cond b K Kᗮ)) (λ b, (cond b K Kᗮ).subtypeₗᵢ)
| tt tt := absurd rfl
| tt ff := λ _ x y, inner_right_of_mem_orthogonal x.prop y.prop
| ff tt := λ _ x y, inner_left_of_mem_orthogonal y.prop x.prop
| ff ff := absurd rfl
end submodule
@[simp]
lemma bilin_form_of_real_inner_orthogonal {E} [normed_add_comm_group E] [inner_product_space ℝ E]
(K : submodule ℝ E) :
bilin_form_of_real_inner.orthogonal K = Kᗮ := rfl
/-!
### Orthogonality of submodules
In this section we define `submodule.is_ortho U V`, with notation `U ⟂ V`.
The API roughly matches that of `disjoint`.
-/
namespace submodule
/-- The proposition that two submodules are orthogonal. Has notation `U ⟂ V`. -/
def is_ortho (U V : submodule 𝕜 E) : Prop :=
U ≤ Vᗮ
infix ` ⟂ `:50 := submodule.is_ortho
lemma is_ortho_iff_le {U V : submodule 𝕜 E} : U ⟂ V ↔ U ≤ Vᗮ := iff.rfl
@[symm]
lemma is_ortho.symm {U V : submodule 𝕜 E} (h : U ⟂ V) : V ⟂ U :=
(le_orthogonal_orthogonal _).trans (orthogonal_le h)
lemma is_ortho_comm {U V : submodule 𝕜 E} : U ⟂ V ↔ V ⟂ U := ⟨is_ortho.symm, is_ortho.symm⟩
lemma symmetric_is_ortho : symmetric (is_ortho : submodule 𝕜 E → submodule 𝕜 E → Prop) :=
λ _ _, is_ortho.symm
lemma is_ortho.inner_eq {U V : submodule 𝕜 E} (h : U ⟂ V) {u v : E} (hu : u ∈ U) (hv : v ∈ V) :
⟪u, v⟫ = 0 :=
h.symm hv _ hu
lemma is_ortho_iff_inner_eq {U V : submodule 𝕜 E} : U ⟂ V ↔ ∀ (u ∈ U) (v ∈ V), ⟪u, v⟫ = 0 :=
forall₄_congr $ λ u hu v hv, inner_eq_zero_symm
/- TODO: generalize `submodule.map₂` to semilinear maps, so that we can state
`U ⟂ V ↔ submodule.map₂ (innerₛₗ 𝕜) U V ≤ ⊥`. -/
@[simp] lemma is_ortho_bot_left {V : submodule 𝕜 E} : ⊥ ⟂ V := bot_le
@[simp] lemma is_ortho_bot_right {U : submodule 𝕜 E} : U ⟂ ⊥ := is_ortho_bot_left.symm
lemma is_ortho.mono_left {U₁ U₂ V : submodule 𝕜 E} (hU : U₂ ≤ U₁) (h : U₁ ⟂ V) : U₂ ⟂ V :=
hU.trans h
lemma is_ortho.mono_right {U V₁ V₂ : submodule 𝕜 E} (hV : V₂ ≤ V₁) (h : U ⟂ V₁) : U ⟂ V₂ :=
(h.symm.mono_left hV).symm
lemma is_ortho.mono {U₁ V₁ U₂ V₂ : submodule 𝕜 E} (hU : U₂ ≤ U₁) (hV : V₂ ≤ V₁) (h : U₁ ⟂ V₁) :
U₂ ⟂ V₂ :=
(h.mono_right hV).mono_left hU
@[simp]
lemma is_ortho_self {U : submodule 𝕜 E} : U ⟂ U ↔ U = ⊥ :=
⟨λ h, eq_bot_iff.mpr $ λ x hx, inner_self_eq_zero.mp (h hx x hx), λ h, h.symm ▸ is_ortho_bot_left⟩
@[simp] lemma is_ortho_orthogonal_right (U : submodule 𝕜 E) : U ⟂ Uᗮ :=
le_orthogonal_orthogonal _
@[simp] lemma is_ortho_orthogonal_left (U : submodule 𝕜 E) : Uᗮ ⟂ U :=
(is_ortho_orthogonal_right U).symm
lemma is_ortho.le {U V : submodule 𝕜 E} (h : U ⟂ V) : U ≤ Vᗮ := h
lemma is_ortho.ge {U V : submodule 𝕜 E} (h : U ⟂ V) : V ≤ Uᗮ := h.symm
@[simp]
lemma is_ortho_top_right {U : submodule 𝕜 E} : U ⟂ ⊤ ↔ U = ⊥ :=
⟨λ h, eq_bot_iff.mpr $ λ x hx, inner_self_eq_zero.mp (h hx _ mem_top),
λ h, h.symm ▸ is_ortho_bot_left⟩
@[simp]
lemma is_ortho_top_left {V : submodule 𝕜 E} : ⊤ ⟂ V ↔ V = ⊥ :=
is_ortho_comm.trans is_ortho_top_right
/-- Orthogonal submodules are disjoint. -/
lemma is_ortho.disjoint {U V : submodule 𝕜 E} (h : U ⟂ V) : disjoint U V :=
(submodule.orthogonal_disjoint _).mono_right h.symm
@[simp] lemma is_ortho_sup_left {U₁ U₂ V : submodule 𝕜 E} : U₁ ⊔ U₂ ⟂ V ↔ U₁ ⟂ V ∧ U₂ ⟂ V :=
sup_le_iff
@[simp] lemma is_ortho_sup_right {U V₁ V₂ : submodule 𝕜 E} : U ⟂ V₁ ⊔ V₂ ↔ U ⟂ V₁ ∧ U ⟂ V₂ :=
is_ortho_comm.trans $ is_ortho_sup_left.trans $ is_ortho_comm.and is_ortho_comm
@[simp] lemma is_ortho_Sup_left {U : set (submodule 𝕜 E)} {V : submodule 𝕜 E} :
Sup U ⟂ V ↔ ∀ Uᵢ ∈ U, Uᵢ ⟂ V :=
Sup_le_iff
@[simp] lemma is_ortho_Sup_right {U : submodule 𝕜 E} {V : set (submodule 𝕜 E)} :
U ⟂ Sup V ↔ ∀ Vᵢ ∈ V, U ⟂ Vᵢ :=
is_ortho_comm.trans $ is_ortho_Sup_left.trans $ by simp_rw is_ortho_comm
@[simp] lemma is_ortho_supr_left {ι : Sort*} {U : ι → submodule 𝕜 E} {V : submodule 𝕜 E} :
supr U ⟂ V ↔ ∀ i, U i ⟂ V :=
supr_le_iff
@[simp] lemma is_ortho_supr_right {ι : Sort*} {U : submodule 𝕜 E} {V : ι → submodule 𝕜 E} :
U ⟂ supr V ↔ ∀ i, U ⟂ V i :=
is_ortho_comm.trans $ is_ortho_supr_left.trans $ by simp_rw is_ortho_comm
@[simp] lemma is_ortho_span {s t : set E} :
span 𝕜 s ⟂ span 𝕜 t ↔ ∀ ⦃u⦄, u ∈ s → ∀ ⦃v⦄, v ∈ t → ⟪u, v⟫ = 0 :=
begin
simp_rw [span_eq_supr_of_singleton_spans s, span_eq_supr_of_singleton_spans t,
is_ortho_supr_left, is_ortho_supr_right, is_ortho_iff_le, span_le, set.subset_def,
set_like.mem_coe, mem_orthogonal_singleton_iff_inner_left, set.mem_singleton_iff, forall_eq],
end
lemma is_ortho.map (f : E →ₗᵢ[𝕜] F) {U V : submodule 𝕜 E} (h : U ⟂ V) : U.map f ⟂ V.map f :=
begin
rw is_ortho_iff_inner_eq at *,
simp_rw [mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂,
linear_isometry.inner_map_map],
exact h,
end
lemma is_ortho.comap (f : E →ₗᵢ[𝕜] F) {U V : submodule 𝕜 F} (h : U ⟂ V) : U.comap f ⟂ V.comap f :=
begin
rw is_ortho_iff_inner_eq at *,
simp_rw [mem_comap, ←f.inner_map_map],
intros u hu v hv,
exact h _ hu _ hv,
end
@[simp] lemma is_ortho.map_iff (f : E ≃ₗᵢ[𝕜] F) {U V : submodule 𝕜 E} : U.map f ⟂ V.map f ↔ U ⟂ V :=
⟨λ h, begin
have hf : ∀ p : submodule 𝕜 E, (p.map f).comap f.to_linear_isometry = p :=
comap_map_eq_of_injective f.injective,
simpa only [hf] using h.comap f.to_linear_isometry,
end, is_ortho.map f.to_linear_isometry⟩
@[simp] lemma is_ortho.comap_iff (f : E ≃ₗᵢ[𝕜] F) {U V : submodule 𝕜 F} :
U.comap f ⟂ V.comap f ↔ U ⟂ V :=
⟨λ h, begin
have hf : ∀ p : submodule 𝕜 F, (p.comap f).map f.to_linear_isometry = p :=
map_comap_eq_of_surjective f.surjective,
simpa only [hf] using h.map f.to_linear_isometry,
end, is_ortho.comap f.to_linear_isometry⟩
end submodule
lemma orthogonal_family_iff_pairwise {ι} {V : ι → submodule 𝕜 E} :
orthogonal_family 𝕜 (λ i, V i) (λ i, (V i).subtypeₗᵢ) ↔ pairwise ((⟂) on V) :=
forall₃_congr $ λ i j hij,
subtype.forall.trans $ forall₂_congr $ λ x hx, subtype.forall.trans $ forall₂_congr $ λ y hy,
inner_eq_zero_symm
alias orthogonal_family_iff_pairwise ↔ orthogonal_family.pairwise orthogonal_family.of_pairwise
/-- Two submodules in an orthogonal family with different indices are orthogonal. -/
lemma orthogonal_family.is_ortho {ι} {V : ι → submodule 𝕜 E}
(hV : orthogonal_family 𝕜 (λ i, V i) (λ i, (V i).subtypeₗᵢ)) {i j : ι} (hij : i ≠ j) :
V i ⟂ V j :=
hV.pairwise hij
|
11ddc96fa85961de46fd0c44a876caa3e2276b3c | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/basic_monitor3.lean | 88fbb4d04b99bf6d523037a5f131c3cdc584abaa | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 1,589 | lean | meta def get_file (fn : name) : vm format :=
do {
d ← vm.get_decl fn,
some n ← return (vm_decl.olean d) | failure,
return (to_fmt n)
}
<|>
return (to_fmt "<curr file>")
meta def pos_info (fn : name) : vm format :=
do {
d ← vm.get_decl fn,
some pos ← return (vm_decl.pos d) | failure,
file ← get_file fn,
return (file ++ ":" ++ pos.1 ++ ":" ++ pos.2)
}
<|>
return (to_fmt "<position not available>")
meta def obj_fmt (o : vm_obj) : vm format :=
match o^.kind with
| vm_obj_kind.tactic_state :=
return (to_fmt "state:" ++ format.nest 8 (format.line ++ o^.to_tactic_state^.to_format))
| _ := do s ← vm.obj_to_string o, return $ to_fmt s
end
meta def display_args_aux : nat → vm unit
| i := do
sz ← vm.stack_size,
if i = sz then return ()
else do
o ← vm.stack_obj i,
(n, t) ← vm.stack_obj_info i,
fmt ← obj_fmt o,
vm.trace (to_fmt " " ++ to_fmt n ++ " := " ++ fmt),
display_args_aux (i+1)
meta def display_args : vm unit :=
do bp ← vm.bp,
display_args_aux bp
@[vm_monitor]
meta def basic_monitor : vm_monitor nat :=
{ init := 1000,
step := λ sz, do
csz ← vm.call_stack_size,
if sz = csz then return sz
else
do {
fn ← vm.curr_fn,
pos ← pos_info fn,
vm.trace (to_fmt "[" ++ csz ++ "]: " ++ to_fmt fn ++ " @ " ++ pos),
display_args,
return csz
}
<|>
return csz -- curr_fn failed
}
set_option debugger true
open tactic
example (a b : Prop) : a → b → a ∧ b :=
by (intros >> constructor >> repeat assumption)
|
982dc342f46673fc2e2c92c9e57a0b67d43cf0a8 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/analysis/calculus/lhopital.lean | 8ac20d899aa2419cd8c2646cff9d06b586893ef5 | [
"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 | 24,976 | lean | /-
Copyright (c) 2020 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker
-/
import analysis.calculus.mean_value
/-!
# L'Hôpital's rule for 0/0 indeterminate forms
In this file, we prove several forms of "L'Hopital's rule" for computing 0/0
indeterminate forms. The proof of `has_deriv_at.lhopital_zero_right_on_Ioo`
is based on the one given in the corresponding
[Wikibooks](https://en.wikibooks.org/wiki/Calculus/L%27H%C3%B4pital%27s_Rule)
chapter, and all other statements are derived from this one by composing by
carefully chosen functions.
Note that the filter `f'/g'` tends to isn't required to be one of `𝓝 a`,
`at_top` or `at_bot`. In fact, we give a slightly stronger statement by
allowing it to be any filter on `ℝ`.
Each statement is available in a `has_deriv_at` form and a `deriv` form, which
is denoted by each statement being in either the `has_deriv_at` or the `deriv`
namespace.
-/
open filter set
open_locale filter topological_space
variables {a b : ℝ} (hab : a < b) {l : filter ℝ} {f f' g g' : ℝ → ℝ}
/-!
## Interval-based versions
We start by proving statements where all conditions (derivability, `g' ≠ 0`) have
to be satisfied on an explicitely-provided interval.
-/
namespace has_deriv_at
include hab
theorem lhopital_zero_right_on_Ioo
(hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x)
(hg' : ∀ x ∈ Ioo a b, g' x ≠ 0)
(hfa : tendsto f (𝓝[Ioi a] a) (𝓝 0)) (hga : tendsto g (𝓝[Ioi a] a) (𝓝 0))
(hdiv : tendsto (λ x, (f' x) / (g' x)) (𝓝[Ioi a] a) l) :
tendsto (λ x, (f x) / (g x)) (𝓝[Ioi a] a) l :=
begin
have sub : ∀ x ∈ Ioo a b, Ioo a x ⊆ Ioo a b := λ x hx, Ioo_subset_Ioo (le_refl a) (le_of_lt hx.2),
have hg : ∀ x ∈ (Ioo a b), g x ≠ 0,
{ intros x hx h,
have : tendsto g (𝓝[Iio x] x) (𝓝 0),
{ rw [← h, ← nhds_within_Ioo_eq_nhds_within_Iio hx.1],
exact ((hgg' x hx).continuous_at.continuous_within_at.mono $ sub x hx).tendsto },
obtain ⟨y, hyx, hy⟩ : ∃ c ∈ Ioo a x, g' c = 0,
from exists_has_deriv_at_eq_zero' hx.1 hga this (λ y hy, hgg' y $ sub x hx hy),
exact hg' y (sub x hx hyx) hy },
have : ∀ x ∈ Ioo a b, ∃ c ∈ Ioo a x, (f x) * (g' c) = (g x) * (f' c),
{ intros x hx,
rw [← sub_zero (f x), ← sub_zero (g x)],
exact exists_ratio_has_deriv_at_eq_ratio_slope' g g' hx.1 f f'
(λ y hy, hgg' y $ sub x hx hy) (λ y hy, hff' y $ sub x hx hy) hga hfa
(tendsto_nhds_within_of_tendsto_nhds (hgg' x hx).continuous_at.tendsto)
(tendsto_nhds_within_of_tendsto_nhds (hff' x hx).continuous_at.tendsto) },
choose! c hc using this,
have : ∀ x ∈ Ioo a b, ((λ x', (f' x') / (g' x')) ∘ c) x = f x / g x,
{ intros x hx,
rcases hc x hx with ⟨h₁, h₂⟩,
field_simp [hg x hx, hg' (c x) ((sub x hx) h₁)],
simp only [h₂],
rwa mul_comm },
have cmp : ∀ x ∈ Ioo a b, a < c x ∧ c x < x,
from λ x hx, (hc x hx).1,
rw ← nhds_within_Ioo_eq_nhds_within_Ioi hab,
apply tendsto_nhds_within_congr this,
simp only,
apply hdiv.comp,
refine tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _
(tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds
(tendsto_nhds_within_of_tendsto_nhds tendsto_id) _ _) _,
all_goals
{ apply eventually_nhds_with_of_forall,
intros x hx,
have := cmp x hx,
try {simp},
linarith [this] }
end
theorem lhopital_zero_right_on_Ico
(hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x)
(hcf : continuous_on f (Ico a b)) (hcg : continuous_on g (Ico a b))
(hg' : ∀ x ∈ Ioo a b, g' x ≠ 0)
(hfa : f a = 0) (hga : g a = 0)
(hdiv : tendsto (λ x, (f' x) / (g' x)) (nhds_within a (Ioi a)) l) :
tendsto (λ x, (f x) / (g x)) (nhds_within a (Ioi a)) l :=
begin
refine lhopital_zero_right_on_Ioo hab hff' hgg' hg' _ _ hdiv,
{ rw [← hfa, ← nhds_within_Ioo_eq_nhds_within_Ioi hab],
exact ((hcf a $ left_mem_Ico.mpr hab).mono Ioo_subset_Ico_self).tendsto },
{ rw [← hga, ← nhds_within_Ioo_eq_nhds_within_Ioi hab],
exact ((hcg a $ left_mem_Ico.mpr hab).mono Ioo_subset_Ico_self).tendsto },
end
theorem lhopital_zero_left_on_Ioo
(hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x)
(hg' : ∀ x ∈ Ioo a b, g' x ≠ 0)
(hfb : tendsto f (nhds_within b (Iio b)) (𝓝 0)) (hgb : tendsto g (nhds_within b (Iio b)) (𝓝 0))
(hdiv : tendsto (λ x, (f' x) / (g' x)) (nhds_within b (Iio b)) l) :
tendsto (λ x, (f x) / (g x)) (nhds_within b (Iio b)) l :=
begin
-- Here, we essentially compose by `has_neg.neg`. The following is mostly technical details.
have hdnf : ∀ x ∈ -Ioo a b, has_deriv_at (f ∘ has_neg.neg) (f' (-x) * (-1)) x,
from λ x hx, comp x (hff' (-x) hx) (has_deriv_at_neg x),
have hdng : ∀ x ∈ -Ioo a b, has_deriv_at (g ∘ has_neg.neg) (g' (-x) * (-1)) x,
from λ x hx, comp x (hgg' (-x) hx) (has_deriv_at_neg x),
rw preimage_neg_Ioo at hdnf,
rw preimage_neg_Ioo at hdng,
have := lhopital_zero_right_on_Ioo (neg_lt_neg hab) hdnf hdng
(by { intros x hx h,
apply hg' _ (by {rw ← preimage_neg_Ioo at hx, exact hx}),
rwa [mul_comm, ← neg_eq_neg_one_mul, neg_eq_zero] at h })
(hfb.comp tendsto_neg_nhds_within_Ioi_neg)
(hgb.comp tendsto_neg_nhds_within_Ioi_neg)
(by { simp only [neg_div_neg_eq, mul_one, mul_neg_eq_neg_mul_symm],
exact (tendsto_congr $ λ x, rfl).mp (hdiv.comp tendsto_neg_nhds_within_Ioi_neg) }),
have := this.comp tendsto_neg_nhds_within_Iio,
unfold function.comp at this,
simpa only [neg_neg]
end
theorem lhopital_zero_left_on_Ioc
(hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x)
(hcf : continuous_on f (Ioc a b)) (hcg : continuous_on g (Ioc a b))
(hg' : ∀ x ∈ Ioo a b, g' x ≠ 0)
(hfb : f b = 0) (hgb : g b = 0)
(hdiv : tendsto (λ x, (f' x) / (g' x)) (nhds_within b (Iio b)) l) :
tendsto (λ x, (f x) / (g x)) (nhds_within b (Iio b)) l :=
begin
refine lhopital_zero_left_on_Ioo hab hff' hgg' hg' _ _ hdiv,
{ rw [← hfb, ← nhds_within_Ioo_eq_nhds_within_Iio hab],
exact ((hcf b $ right_mem_Ioc.mpr hab).mono Ioo_subset_Ioc_self).tendsto },
{ rw [← hgb, ← nhds_within_Ioo_eq_nhds_within_Iio hab],
exact ((hcg b $ right_mem_Ioc.mpr hab).mono Ioo_subset_Ioc_self).tendsto },
end
omit hab
theorem lhopital_zero_at_top_on_Ioi
(hff' : ∀ x ∈ Ioi a, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioi a, has_deriv_at g (g' x) x)
(hg' : ∀ x ∈ Ioi a, g' x ≠ 0)
(hftop : tendsto f at_top (𝓝 0)) (hgtop : tendsto g at_top (𝓝 0))
(hdiv : tendsto (λ x, (f' x) / (g' x)) at_top l) :
tendsto (λ x, (f x) / (g x)) at_top l :=
begin
obtain ⟨ a', haa', ha'⟩ : ∃ a', a < a' ∧ 0 < a' :=
⟨1 + max a 0, ⟨lt_of_le_of_lt (le_max_left a 0) (lt_one_add _),
lt_of_le_of_lt (le_max_right a 0) (lt_one_add _)⟩⟩,
have fact1 : ∀ (x:ℝ), x ∈ Ioo 0 a'⁻¹ → x ≠ 0 := λ _ hx, (ne_of_lt hx.1).symm,
have fact2 : ∀ x ∈ Ioo 0 a'⁻¹, a < x⁻¹,
from λ _ hx, lt_trans haa' ((lt_inv ha' hx.1).mpr hx.2),
have hdnf : ∀ x ∈ Ioo 0 a'⁻¹, has_deriv_at (f ∘ has_inv.inv) (f' (x⁻¹) * (-(x^2)⁻¹)) x,
from λ x hx, comp x (hff' (x⁻¹) $ fact2 x hx) (has_deriv_at_inv $ fact1 x hx),
have hdng : ∀ x ∈ Ioo 0 a'⁻¹, has_deriv_at (g ∘ has_inv.inv) (g' (x⁻¹) * (-(x^2)⁻¹)) x,
from λ x hx, comp x (hgg' (x⁻¹) $ fact2 x hx) (has_deriv_at_inv $ fact1 x hx),
have := lhopital_zero_right_on_Ioo (inv_pos.mpr ha') hdnf hdng
(by { intros x hx,
refine mul_ne_zero _ (neg_ne_zero.mpr $ inv_ne_zero $ pow_ne_zero _ $ fact1 x hx),
exact hg' _ (fact2 x hx) })
(hftop.comp tendsto_inv_zero_at_top)
(hgtop.comp tendsto_inv_zero_at_top)
(by { refine (tendsto_congr' _).mp (hdiv.comp tendsto_inv_zero_at_top),
rw eventually_eq_iff_exists_mem,
use [Ioi 0, self_mem_nhds_within],
intros x hx,
unfold function.comp,
erw mul_div_mul_right,
refine neg_ne_zero.mpr (inv_ne_zero $ pow_ne_zero _ $ ne_of_gt hx) }),
have := this.comp tendsto_inv_at_top_zero',
unfold function.comp at this,
simpa only [inv_inv'],
end
theorem lhopital_zero_at_bot_on_Iio
(hff' : ∀ x ∈ Iio a, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Iio a, has_deriv_at g (g' x) x)
(hg' : ∀ x ∈ Iio a, g' x ≠ 0)
(hfbot : tendsto f at_bot (𝓝 0)) (hgbot : tendsto g at_bot (𝓝 0))
(hdiv : tendsto (λ x, (f' x) / (g' x)) at_bot l) :
tendsto (λ x, (f x) / (g x)) at_bot l :=
begin
-- Here, we essentially compose by `has_neg.neg`. The following is mostly technical details.
have hdnf : ∀ x ∈ -Iio a, has_deriv_at (f ∘ has_neg.neg) (f' (-x) * (-1)) x,
from λ x hx, comp x (hff' (-x) hx) (has_deriv_at_neg x),
have hdng : ∀ x ∈ -Iio a, has_deriv_at (g ∘ has_neg.neg) (g' (-x) * (-1)) x,
from λ x hx, comp x (hgg' (-x) hx) (has_deriv_at_neg x),
rw preimage_neg_Iio at hdnf,
rw preimage_neg_Iio at hdng,
have := lhopital_zero_at_top_on_Ioi hdnf hdng
(by { intros x hx h,
apply hg' _ (by {rw ← preimage_neg_Iio at hx, exact hx}),
rwa [mul_comm, ← neg_eq_neg_one_mul, neg_eq_zero] at h })
(hfbot.comp tendsto_neg_at_top_at_bot)
(hgbot.comp tendsto_neg_at_top_at_bot)
(by { simp only [mul_one, mul_neg_eq_neg_mul_symm, neg_div_neg_eq],
exact (tendsto_congr $ λ x, rfl).mp (hdiv.comp tendsto_neg_at_top_at_bot) }),
have := this.comp tendsto_neg_at_bot_at_top,
unfold function.comp at this,
simpa only [neg_neg],
end
end has_deriv_at
namespace deriv
include hab
theorem lhopital_zero_right_on_Ioo
(hdf : differentiable_on ℝ f (Ioo a b)) (hg' : ∀ x ∈ Ioo a b, deriv g x ≠ 0)
(hfa : tendsto f (𝓝[Ioi a] a) (𝓝 0)) (hga : tendsto g (𝓝[Ioi a] a) (𝓝 0))
(hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) (𝓝[Ioi a] a) l) :
tendsto (λ x, (f x) / (g x)) (𝓝[Ioi a] a) l :=
begin
have hdf : ∀ x ∈ Ioo a b, differentiable_at ℝ f x,
from λ x hx, (hdf x hx).differentiable_at (Ioo_mem_nhds hx.1 hx.2),
have hdg : ∀ x ∈ Ioo a b, differentiable_at ℝ g x,
from λ x hx, classical.by_contradiction (λ h, hg' x hx (deriv_zero_of_not_differentiable_at h)),
exact has_deriv_at.lhopital_zero_right_on_Ioo hab (λ x hx, (hdf x hx).has_deriv_at)
(λ x hx, (hdg x hx).has_deriv_at) hg' hfa hga hdiv
end
theorem lhopital_zero_right_on_Ico
(hdf : differentiable_on ℝ f (Ioo a b))
(hcf : continuous_on f (Ico a b)) (hcg : continuous_on g (Ico a b))
(hg' : ∀ x ∈ (Ioo a b), (deriv g) x ≠ 0)
(hfa : f a = 0) (hga : g a = 0)
(hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) (nhds_within a (Ioi a)) l) :
tendsto (λ x, (f x) / (g x)) (nhds_within a (Ioi a)) l :=
begin
refine lhopital_zero_right_on_Ioo hab hdf hg' _ _ hdiv,
{ rw [← hfa, ← nhds_within_Ioo_eq_nhds_within_Ioi hab],
exact ((hcf a $ left_mem_Ico.mpr hab).mono Ioo_subset_Ico_self).tendsto },
{ rw [← hga, ← nhds_within_Ioo_eq_nhds_within_Ioi hab],
exact ((hcg a $ left_mem_Ico.mpr hab).mono Ioo_subset_Ico_self).tendsto },
end
theorem lhopital_zero_left_on_Ioo
(hdf : differentiable_on ℝ f (Ioo a b))
(hg' : ∀ x ∈ (Ioo a b), (deriv g) x ≠ 0)
(hfb : tendsto f (nhds_within b (Iio b)) (𝓝 0)) (hgb : tendsto g (nhds_within b (Iio b)) (𝓝 0))
(hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) (nhds_within b (Iio b)) l) :
tendsto (λ x, (f x) / (g x)) (nhds_within b (Iio b)) l :=
begin
have hdf : ∀ x ∈ Ioo a b, differentiable_at ℝ f x,
from λ x hx, (hdf x hx).differentiable_at (Ioo_mem_nhds hx.1 hx.2),
have hdg : ∀ x ∈ Ioo a b, differentiable_at ℝ g x,
from λ x hx, classical.by_contradiction (λ h, hg' x hx (deriv_zero_of_not_differentiable_at h)),
exact has_deriv_at.lhopital_zero_left_on_Ioo hab (λ x hx, (hdf x hx).has_deriv_at)
(λ x hx, (hdg x hx).has_deriv_at) hg' hfb hgb hdiv
end
omit hab
theorem lhopital_zero_at_top_on_Ioi
(hdf : differentiable_on ℝ f (Ioi a))
(hg' : ∀ x ∈ (Ioi a), (deriv g) x ≠ 0)
(hftop : tendsto f at_top (𝓝 0)) (hgtop : tendsto g at_top (𝓝 0))
(hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) at_top l) :
tendsto (λ x, (f x) / (g x)) at_top l :=
begin
have hdf : ∀ x ∈ Ioi a, differentiable_at ℝ f x,
from λ x hx, (hdf x hx).differentiable_at (Ioi_mem_nhds hx),
have hdg : ∀ x ∈ Ioi a, differentiable_at ℝ g x,
from λ x hx, classical.by_contradiction (λ h, hg' x hx (deriv_zero_of_not_differentiable_at h)),
exact has_deriv_at.lhopital_zero_at_top_on_Ioi (λ x hx, (hdf x hx).has_deriv_at)
(λ x hx, (hdg x hx).has_deriv_at) hg' hftop hgtop hdiv,
end
theorem lhopital_zero_at_bot_on_Iio
(hdf : differentiable_on ℝ f (Iio a))
(hg' : ∀ x ∈ (Iio a), (deriv g) x ≠ 0)
(hfbot : tendsto f at_bot (𝓝 0)) (hgbot : tendsto g at_bot (𝓝 0))
(hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) at_bot l) :
tendsto (λ x, (f x) / (g x)) at_bot l :=
begin
have hdf : ∀ x ∈ Iio a, differentiable_at ℝ f x,
from λ x hx, (hdf x hx).differentiable_at (Iio_mem_nhds hx),
have hdg : ∀ x ∈ Iio a, differentiable_at ℝ g x,
from λ x hx, classical.by_contradiction (λ h, hg' x hx (deriv_zero_of_not_differentiable_at h)),
exact has_deriv_at.lhopital_zero_at_bot_on_Iio (λ x hx, (hdf x hx).has_deriv_at)
(λ x hx, (hdg x hx).has_deriv_at) hg' hfbot hgbot hdiv,
end
end deriv
/-!
## Generic versions
The following statements no longer any explicit interval, as they only require
conditions holding eventually.
-/
namespace has_deriv_at
/-- L'Hôpital's rule for approaching a real from the right, `has_deriv_at` version -/
theorem lhopital_zero_nhds_right
(hff' : ∀ᶠ x in 𝓝[Ioi a] a, has_deriv_at f (f' x) x)
(hgg' : ∀ᶠ x in 𝓝[Ioi a] a, has_deriv_at g (g' x) x)
(hg' : ∀ᶠ x in 𝓝[Ioi a] a, g' x ≠ 0)
(hfa : tendsto f (𝓝[Ioi a] a) (𝓝 0)) (hga : tendsto g (𝓝[Ioi a] a) (𝓝 0))
(hdiv : tendsto (λ x, (f' x) / (g' x)) (𝓝[Ioi a] a) l) :
tendsto (λ x, (f x) / (g x)) (𝓝[Ioi a] a) l :=
begin
rw eventually_iff_exists_mem at *,
rcases hff' with ⟨s₁, hs₁, hff'⟩,
rcases hgg' with ⟨s₂, hs₂, hgg'⟩,
rcases hg' with ⟨s₃, hs₃, hg'⟩,
let s := s₁ ∩ s₂ ∩ s₃,
have hs : s ∈ 𝓝[Ioi a] a := inter_mem_sets (inter_mem_sets hs₁ hs₂) hs₃,
rw mem_nhds_within_Ioi_iff_exists_Ioo_subset at hs,
rcases hs with ⟨u, hau, hu⟩,
refine lhopital_zero_right_on_Ioo hau _ _ _ hfa hga hdiv;
intros x hx;
apply_assumption;
exact (hu hx).1.1 <|> exact (hu hx).1.2 <|> exact (hu hx).2
end
/-- L'Hôpital's rule for approaching a real from the left, `has_deriv_at` version -/
theorem lhopital_zero_nhds_left
(hff' : ∀ᶠ x in 𝓝[Iio a] a, has_deriv_at f (f' x) x)
(hgg' : ∀ᶠ x in 𝓝[Iio a] a, has_deriv_at g (g' x) x)
(hg' : ∀ᶠ x in 𝓝[Iio a] a, g' x ≠ 0)
(hfa : tendsto f (𝓝[Iio a] a) (𝓝 0)) (hga : tendsto g (𝓝[Iio a] a) (𝓝 0))
(hdiv : tendsto (λ x, (f' x) / (g' x)) (𝓝[Iio a] a) l) :
tendsto (λ x, (f x) / (g x)) (𝓝[Iio a] a) l :=
begin
rw eventually_iff_exists_mem at *,
rcases hff' with ⟨s₁, hs₁, hff'⟩,
rcases hgg' with ⟨s₂, hs₂, hgg'⟩,
rcases hg' with ⟨s₃, hs₃, hg'⟩,
let s := s₁ ∩ s₂ ∩ s₃,
have hs : s ∈ 𝓝[Iio a] a := inter_mem_sets (inter_mem_sets hs₁ hs₂) hs₃,
rw mem_nhds_within_Iio_iff_exists_Ioo_subset at hs,
rcases hs with ⟨l, hal, hl⟩,
refine lhopital_zero_left_on_Ioo hal _ _ _ hfa hga hdiv;
intros x hx;
apply_assumption;
exact (hl hx).1.1 <|> exact (hl hx).1.2 <|> exact (hl hx).2
end
/-- L'Hôpital's rule for approaching a real, `has_deriv_at` version. This
does not require anything about the situation at `a` -/
theorem lhopital_zero_nhds'
(hff' : ∀ᶠ x in 𝓝[univ \ {a}] a, has_deriv_at f (f' x) x)
(hgg' : ∀ᶠ x in 𝓝[univ \ {a}] a, has_deriv_at g (g' x) x)
(hg' : ∀ᶠ x in 𝓝[univ \ {a}] a, g' x ≠ 0)
(hfa : tendsto f (𝓝[univ \ {a}] a) (𝓝 0)) (hga : tendsto g (𝓝[univ \ {a}] a) (𝓝 0))
(hdiv : tendsto (λ x, (f' x) / (g' x)) (𝓝[univ \ {a}] a) l) :
tendsto (λ x, (f x) / (g x)) (𝓝[univ \ {a}] a) l :=
begin
have : univ \ {a} = Iio a ∪ Ioi a,
{ ext, rw [mem_diff_singleton, eq_true_intro $ mem_univ x, true_and, ne_iff_lt_or_gt], refl },
simp only [this, nhds_within_union, tendsto_sup, eventually_sup] at *,
exact ⟨lhopital_zero_nhds_left hff'.1 hgg'.1 hg'.1 hfa.1 hga.1 hdiv.1,
lhopital_zero_nhds_right hff'.2 hgg'.2 hg'.2 hfa.2 hga.2 hdiv.2⟩
end
/-- L'Hôpital's rule for approaching a real, `has_deriv_at` version -/
theorem lhopital_zero_nhds
(hff' : ∀ᶠ x in 𝓝 a, has_deriv_at f (f' x) x)
(hgg' : ∀ᶠ x in 𝓝 a, has_deriv_at g (g' x) x)
(hg' : ∀ᶠ x in 𝓝 a, g' x ≠ 0)
(hfa : tendsto f (𝓝 a) (𝓝 0)) (hga : tendsto g (𝓝 a) (𝓝 0))
(hdiv : tendsto (λ x, f' x / g' x) (𝓝 a) l) :
tendsto (λ x, f x / g x) (𝓝[univ \ {a}] a) l :=
begin
apply @lhopital_zero_nhds' _ _ _ f' _ g';
apply eventually_nhds_within_of_eventually_nhds <|> apply tendsto_nhds_within_of_tendsto_nhds;
assumption
end
/-- L'Hôpital's rule for approaching +∞, `has_deriv_at` version -/
theorem lhopital_zero_at_top
(hff' : ∀ᶠ x in at_top, has_deriv_at f (f' x) x)
(hgg' : ∀ᶠ x in at_top, has_deriv_at g (g' x) x)
(hg' : ∀ᶠ x in at_top, g' x ≠ 0)
(hftop : tendsto f at_top (𝓝 0)) (hgtop : tendsto g at_top (𝓝 0))
(hdiv : tendsto (λ x, (f' x) / (g' x)) at_top l) :
tendsto (λ x, (f x) / (g x)) at_top l :=
begin
rw eventually_iff_exists_mem at *,
rcases hff' with ⟨s₁, hs₁, hff'⟩,
rcases hgg' with ⟨s₂, hs₂, hgg'⟩,
rcases hg' with ⟨s₃, hs₃, hg'⟩,
let s := s₁ ∩ s₂ ∩ s₃,
have hs : s ∈ at_top := inter_mem_sets (inter_mem_sets hs₁ hs₂) hs₃,
rw mem_at_top_sets at hs,
rcases hs with ⟨l, hl⟩,
have hl' : Ioi l ⊆ s := λ x hx, hl x (le_of_lt hx),
refine lhopital_zero_at_top_on_Ioi _ _ (λ x hx, hg' x $ (hl' hx).2) hftop hgtop hdiv;
intros x hx;
apply_assumption;
exact (hl' hx).1.1 <|> exact (hl' hx).1.2
end
/-- L'Hôpital's rule for approaching -∞, `has_deriv_at` version -/
theorem lhopital_zero_at_bot
(hff' : ∀ᶠ x in at_bot, has_deriv_at f (f' x) x)
(hgg' : ∀ᶠ x in at_bot, has_deriv_at g (g' x) x)
(hg' : ∀ᶠ x in at_bot, g' x ≠ 0)
(hfbot : tendsto f at_bot (𝓝 0)) (hgbot : tendsto g at_bot (𝓝 0))
(hdiv : tendsto (λ x, (f' x) / (g' x)) at_bot l) :
tendsto (λ x, (f x) / (g x)) at_bot l :=
begin
rw eventually_iff_exists_mem at *,
rcases hff' with ⟨s₁, hs₁, hff'⟩,
rcases hgg' with ⟨s₂, hs₂, hgg'⟩,
rcases hg' with ⟨s₃, hs₃, hg'⟩,
let s := s₁ ∩ s₂ ∩ s₃,
have hs : s ∈ at_bot := inter_mem_sets (inter_mem_sets hs₁ hs₂) hs₃,
rw mem_at_bot_sets at hs,
rcases hs with ⟨l, hl⟩,
have hl' : Iio l ⊆ s := λ x hx, hl x (le_of_lt hx),
refine lhopital_zero_at_bot_on_Iio _ _ (λ x hx, hg' x $ (hl' hx).2) hfbot hgbot hdiv;
intros x hx;
apply_assumption;
exact (hl' hx).1.1 <|> exact (hl' hx).1.2
end
end has_deriv_at
namespace deriv
/-- L'Hôpital's rule for approaching a real from the right, `deriv` version -/
theorem lhopital_zero_nhds_right
(hdf : ∀ᶠ x in 𝓝[Ioi a] a, differentiable_at ℝ f x)
(hg' : ∀ᶠ x in 𝓝[Ioi a] a, deriv g x ≠ 0)
(hfa : tendsto f (𝓝[Ioi a] a) (𝓝 0)) (hga : tendsto g (𝓝[Ioi a] a) (𝓝 0))
(hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) (𝓝[Ioi a] a) l) :
tendsto (λ x, (f x) / (g x)) (𝓝[Ioi a] a) l :=
begin
have hdg : ∀ᶠ x in 𝓝[Ioi a] a, differentiable_at ℝ g x,
from hg'.mp (eventually_of_forall $
λ _ hg', classical.by_contradiction (λ h, hg' (deriv_zero_of_not_differentiable_at h))),
have hdf' : ∀ᶠ x in 𝓝[Ioi a] a, has_deriv_at f (deriv f x) x,
from hdf.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at),
have hdg' : ∀ᶠ x in 𝓝[Ioi a] a, has_deriv_at g (deriv g x) x,
from hdg.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at),
exact has_deriv_at.lhopital_zero_nhds_right hdf' hdg' hg' hfa hga hdiv
end
/-- L'Hôpital's rule for approaching a real from the left, `deriv` version -/
theorem lhopital_zero_nhds_left
(hdf : ∀ᶠ x in 𝓝[Iio a] a, differentiable_at ℝ f x)
(hg' : ∀ᶠ x in 𝓝[Iio a] a, deriv g x ≠ 0)
(hfa : tendsto f (𝓝[Iio a] a) (𝓝 0)) (hga : tendsto g (𝓝[Iio a] a) (𝓝 0))
(hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) (𝓝[Iio a] a) l) :
tendsto (λ x, (f x) / (g x)) (𝓝[Iio a] a) l :=
begin
have hdg : ∀ᶠ x in 𝓝[Iio a] a, differentiable_at ℝ g x,
from hg'.mp (eventually_of_forall $
λ _ hg', classical.by_contradiction (λ h, hg' (deriv_zero_of_not_differentiable_at h))),
have hdf' : ∀ᶠ x in 𝓝[Iio a] a, has_deriv_at f (deriv f x) x,
from hdf.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at),
have hdg' : ∀ᶠ x in 𝓝[Iio a] a, has_deriv_at g (deriv g x) x,
from hdg.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at),
exact has_deriv_at.lhopital_zero_nhds_left hdf' hdg' hg' hfa hga hdiv
end
/-- L'Hôpital's rule for approaching a real, `deriv` version. This
does not require anything about the situation at `a` -/
theorem lhopital_zero_nhds'
(hdf : ∀ᶠ x in 𝓝[univ \ {a}] a, differentiable_at ℝ f x)
(hg' : ∀ᶠ x in 𝓝[univ \ {a}] a, deriv g x ≠ 0)
(hfa : tendsto f (𝓝[univ \ {a}] a) (𝓝 0)) (hga : tendsto g (𝓝[univ \ {a}] a) (𝓝 0))
(hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) (𝓝[univ \ {a}] a) l) :
tendsto (λ x, (f x) / (g x)) (𝓝[univ \ {a}] a) l :=
begin
have : univ \ {a} = Iio a ∪ Ioi a,
{ ext, rw [mem_diff_singleton, eq_true_intro $ mem_univ x, true_and, ne_iff_lt_or_gt], refl },
simp only [this, nhds_within_union, tendsto_sup, eventually_sup] at *,
exact ⟨lhopital_zero_nhds_left hdf.1 hg'.1 hfa.1 hga.1 hdiv.1,
lhopital_zero_nhds_right hdf.2 hg'.2 hfa.2 hga.2 hdiv.2⟩,
end
/-- L'Hôpital's rule for approaching a real, `deriv` version -/
theorem lhopital_zero_nhds
(hdf : ∀ᶠ x in 𝓝 a, differentiable_at ℝ f x)
(hg' : ∀ᶠ x in 𝓝 a, deriv g x ≠ 0)
(hfa : tendsto f (𝓝 a) (𝓝 0)) (hga : tendsto g (𝓝 a) (𝓝 0))
(hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) (𝓝 a) l) :
tendsto (λ x, (f x) / (g x)) (𝓝[univ \ {a}] a) l :=
begin
apply lhopital_zero_nhds';
apply eventually_nhds_within_of_eventually_nhds <|> apply tendsto_nhds_within_of_tendsto_nhds;
assumption
end
/-- L'Hôpital's rule for approaching +∞, `deriv` version -/
theorem lhopital_zero_at_top
(hdf : ∀ᶠ (x : ℝ) in at_top, differentiable_at ℝ f x)
(hg' : ∀ᶠ (x : ℝ) in at_top, deriv g x ≠ 0)
(hftop : tendsto f at_top (𝓝 0)) (hgtop : tendsto g at_top (𝓝 0))
(hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) at_top l) :
tendsto (λ x, (f x) / (g x)) at_top l :=
begin
have hdg : ∀ᶠ x in at_top, differentiable_at ℝ g x,
from hg'.mp (eventually_of_forall $
λ _ hg', classical.by_contradiction (λ h, hg' (deriv_zero_of_not_differentiable_at h))),
have hdf' : ∀ᶠ x in at_top, has_deriv_at f (deriv f x) x,
from hdf.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at),
have hdg' : ∀ᶠ x in at_top, has_deriv_at g (deriv g x) x,
from hdg.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at),
exact has_deriv_at.lhopital_zero_at_top hdf' hdg' hg' hftop hgtop hdiv
end
/-- L'Hôpital's rule for approaching -∞, `deriv` version -/
theorem lhopital_zero_at_bot
(hdf : ∀ᶠ (x : ℝ) in at_bot, differentiable_at ℝ f x)
(hg' : ∀ᶠ (x : ℝ) in at_bot, deriv g x ≠ 0)
(hfbot : tendsto f at_bot (𝓝 0)) (hgbot : tendsto g at_bot (𝓝 0))
(hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) at_bot l) :
tendsto (λ x, (f x) / (g x)) at_bot l :=
begin
have hdg : ∀ᶠ x in at_bot, differentiable_at ℝ g x,
from hg'.mp (eventually_of_forall $
λ _ hg', classical.by_contradiction (λ h, hg' (deriv_zero_of_not_differentiable_at h))),
have hdf' : ∀ᶠ x in at_bot, has_deriv_at f (deriv f x) x,
from hdf.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at),
have hdg' : ∀ᶠ x in at_bot, has_deriv_at g (deriv g x) x,
from hdg.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at),
exact has_deriv_at.lhopital_zero_at_bot hdf' hdg' hg' hfbot hgbot hdiv
end
end deriv
|
df0d3fac4b3ae41162444a7aac4d413ec3a863f1 | 02fbe05a45fda5abde7583464416db4366eedfbf | /library/init/control/lift.lean | 013dfd9a135198ff617b0322205d034309086971 | [
"Apache-2.0"
] | permissive | jasonrute/lean | cc12807e11f9ac6b01b8951a8bfb9c2eb35a0154 | 4be962c167ca442a0ec5e84472d7ff9f5302788f | refs/heads/master | 1,672,036,664,637 | 1,601,642,826,000 | 1,601,642,826,000 | 260,777,966 | 0 | 0 | Apache-2.0 | 1,588,454,819,000 | 1,588,454,818,000 | null | UTF-8 | Lean | false | false | 4,481 | lean | /-
Copyright (c) 2016 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Sebastian Ullrich
Classy functions for lifting monadic actions of different shapes.
This theory is roughly modeled after the Haskell 'layers' package https://hackage.haskell.org/package/layers-0.1.
Please see https://hackage.haskell.org/package/layers-0.1/docs/Documentation-Layers-Overview.html for an exhaustive discussion of the different approaches to lift functions.
-/
prelude
import init.function init.coe
import init.control.monad
universes u v w
/-- A function for lifting a computation from an inner monad to an outer monad.
Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html),
but `n` does not have to be a monad transformer.
Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/
class has_monad_lift (m : Type u → Type v) (n : Type u → Type w) :=
(monad_lift : ∀ {α}, m α → n α)
/-- The reflexive-transitive closure of `has_monad_lift`.
`monad_lift` is used to transitively lift monadic computations such as `state_t.get` or `state_t.put s`.
Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/
class has_monad_lift_t (m : Type u → Type v) (n : Type u → Type w) :=
(monad_lift : ∀ {α}, m α → n α)
export has_monad_lift_t (monad_lift)
/-- A coercion that may reduce the need for explicit lifting.
Because of [limitations of the current coercion resolution](https://github.com/leanprover/lean/issues/1402), this definition is not marked as a global instance and should be marked locally instead. -/
@[reducible] def has_monad_lift_to_has_coe {m n} [has_monad_lift_t m n] {α} : has_coe (m α) (n α) :=
⟨monad_lift⟩
instance has_monad_lift_t_trans (m n o) [has_monad_lift_t m n] [has_monad_lift n o] : has_monad_lift_t m o :=
⟨λ α ma, has_monad_lift.monad_lift (monad_lift ma : n α)⟩
instance has_monad_lift_t_refl (m) : has_monad_lift_t m m :=
⟨λ α, id⟩
@[simp] lemma monad_lift_refl {m : Type u → Type v} {α} : (monad_lift : m α → m α) = id := rfl
/-- A functor in the category of monads. Can be used to lift monad-transforming functions.
Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html),
but not restricted to monad transformers.
Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/
class monad_functor (m m' : Type u → Type v) (n n' : Type u → Type w) :=
(monad_map {α : Type u} : (∀ {α}, m α → m' α) → n α → n' α)
/-- The reflexive-transitive closure of `monad_functor`.
`monad_map` is used to transitively lift monad morphisms such as `state_t.zoom`.
A generalization of [MonadLiftFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadLiftFunctor), which can only lift endomorphisms (i.e. m = m', n = n'). -/
class monad_functor_t (m m' : Type u → Type v) (n n' : Type u → Type w) :=
(monad_map {α : Type u} : (∀ {α}, m α → m' α) → n α → n' α)
export monad_functor_t (monad_map)
instance monad_functor_t_trans (m m' n n' o o') [monad_functor_t m m' n n'] [monad_functor n n' o o'] :
monad_functor_t m m' o o' :=
⟨λ α f, monad_functor.monad_map (λ α, (monad_map @f : n α → n' α))⟩
instance monad_functor_t_refl (m m') : monad_functor_t m m' m m' :=
⟨λ α f, f⟩
@[simp] lemma monad_map_refl {m m' : Type u → Type v} (f : ∀ {α}, m α → m' α) {α} : (monad_map @f : m α → m' α) = f := rfl
/-- Run a monad stack to completion.
`run` should be the composition of the transformers' individual `run` functions.
This class mostly saves some typing when using highly nested monad stacks:
```
@[reducible] def my_monad := reader_t my_cfg $ state_t my_state $ except_t my_err id
-- def my_monad.run {α : Type} (x : my_monad α) (cfg : my_cfg) (st : my_state) := ((x.run cfg).run st).run
def my_monad.run {α : Type} (x : my_monad α) := monad_run.run x
```
-/
class monad_run (out : out_param $ Type u → Type v) (m : Type u → Type v) :=
(run {α : Type u} : m α → out α)
export monad_run (run)
|
c4cec8172b3d7342890eedf62ab537713e26e822 | 958488bc7f3c2044206e0358e56d7690b6ae696c | /lean/hhg/diff.lean | 28488ef2d6e733106b54a5a1453f97fc60d9b2c3 | [] | no_license | possientis/Prog | a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4 | d4b3debc37610a88e0dac3ac5914903604fd1d1f | refs/heads/master | 1,692,263,717,723 | 1,691,757,179,000 | 1,691,757,179,000 | 40,361,602 | 3 | 0 | null | 1,679,896,438,000 | 1,438,953,859,000 | Coq | UTF-8 | Lean | false | false | 112 | lean | lemma L0 : "x" ≠ "y" :=
begin
from dec_trivial -- remember this, do not use 'cases' tactic on string
end
|
5679fce0a1032bf5ba520687b830ff02d0d7f84f | 03bd658c402412f41d3026d1040ee8ca8c0fc579 | /src/list/lemmas/long_lemmas.lean | 0c051489544efb2aacd88f21fefa3107e36b2607 | [] | no_license | ImperialCollegeLondon/dots_and_boxes | c205f6dbad8af9625f56715e4d1bed96b0ac1022 | f7bd0b1603674a657170c5395adb717c4f670220 | refs/heads/master | 1,663,752,058,476 | 1,591,438,614,000 | 1,591,438,614,000 | 139,707,103 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 35,982 | lean | import data.list.basic tactic.linarith
import tactic.omega tactic.apply
import list.lemmas.simple
open list
/- head -/
/--If you take the head of the first n+1 elements in reverse order you get the nth element-/
lemma head_reverse_take {A : list ℤ} {n : ℕ } (h : n < length A):
head (reverse (take (n + 1) A)) = nth_le A n h :=
begin
/- we want to change the LHS to something involving nth_le (to
nth_le (reverse (take (n + 1) A)) 0 (H1 : 0 < length (reverse (take (n + 1) A))
using nth_le_zero)
For that we need the corresponding argument H1 for nth_le-/
have H1 : 0 < length (reverse (take (n + 1) A)),
{ rw length_reverse, -- length (reverse (take (n + 1) A)) = length (take (n + 1) A)
rw length_take, -- length (take (n + 1) A) = min (n + 1) (length A)
apply lt_min, -- lemma says, for all a,b,c, a < b → a < c → a < min b c
-- focused goal: 0 < n + 1
exact nat.succ_pos n, -- lemma says any successor of a natural number is positive
-- focused goal: 0 < length A
refine lt_of_le_of_lt _ h, -- using that 0 ≤ n and n < length A imply 0 < length A
exact zero_le n, -- 0 ≤ n
},
-- now we have H1 and nth_le_zero gives the following
have H : head (reverse (take (n + 1) A)) = nth_le (reverse (take (n + 1) A)) 0 H1,
rw nth_le_zero,
rw H,
rw nth_le_reverse' _ _ _ _, -- see list.lemmas.simple
swap, /- first prove necessary hypothesis for nth_le_reverse' that
length (take (n + 1) A) - 1 - 0 < length (take (n + 1) A)-/
{ rw length_take, -- length (take (n + 1) A) = min (n + 1) (length A)
rw nat.sub_zero,
apply buffer.lt_aux_2, --min (n + 1) (length A) > 0 → min (n + 1) (length A) - 1 < min (n + 1) (length A)
/- to show min (n + 1) (length A) > 0, we can show that 0 < (n + 1) and n + 1 ≤ length A
the second one is h-/
have H : 0 < (n + 1) := by norm_num, -- the first one is true for any n in ℕ
apply lt_of_lt_of_le H, -- n + 1 ≤ min (n + 1) (length A) → min (n + 1) (length A) > 0
apply le_min (le_refl _), -- n + 1 ≤ length A → n + 1 ≤ min (n + 1) (length A)
exact h },
-- other goal : nth_le (take (n + 1) A) (min (n + 1) (length A) - 1 - 0) _ = nth_le A n h
simp only [length_take], -- simp only because of nth_le
rw nth_le_take, -- see list.lemmas.simple
swap, /- solve necessary hypothesis for nth_le_take first, which is
min (n + 1) (length A) - 1 - 0 < length A-/
{ rw nat.sub_zero, -- get rid of (- 0)
rw nat.sub_lt_right_iff_lt_add, /- if 1 ≤ min (n + 1) (length A), then min (n + 1) (length A) - 1 < length A ↔ min (n + 1) (length A) < length A + 1
(hyothesis 1 ≤ min (n + 1) (length A) necessary beause 0 - 1 = 0) -/
{ apply lt_of_le_of_lt _ (nat.lt_succ_self _), -- min (n + 1) (length A) ≤ length A → min (n + 1) (length A) < length A + 1
apply min_le_right}, -- lemma says : min a b ≤ b for all a,b of the same type
-- now need to prove 1 ≤ min (n + 1) (length A) because of nat.sub_lt_right_iff_lt_add
apply le_min, -- 1 ≤ n + 1 → 1 ≤ length A → 1 ≤ min (n + 1) (length A)
-- prove 1 ≤ n + 1
{exact nat.le_add_left 1 n},
-- prove 1 ≤ length A
{show 0 < length A,
refine lt_of_le_of_lt _ h, -- just like line 26
exact nat.zero_le n,}
},
-- back to main goal : nth_le A (min (n + 1) (length A) - 1 - 0) ?m_1 = nth_le A n h
congr', -- suffices to show : min (n + 1) (length A) - 1 - 0 = n
rw nat.sub_zero, -- get rid of (- 0)
have H3 : n + 1 ≤ length A,
{exact h},
rw min_eq_left H3, -- by H3 min (n + 1) (length A) = n + 1
exact nat.add_sub_cancel n 1,
end
/- remove_nth -/
/--The list with element n removed is the same as the list ccreated by
appending the list containing all its elements after element n to the
list containing its elements up to and excluding element n-/
lemma remove_nth_eq_take_append_drop (n : ℕ) (L : list ℤ) :
remove_nth L n = take n L ++ drop (n + 1) L :=
begin
rw remove_nth_eq_nth_tail, -- remove_nth L n = modify_nth_tail tail n L
rw modify_nth_tail_eq_take_drop, -- modify_nth_tail tail n = take n L ++ tail (drop n L)
rw tail_drop, /- tail (drop n L) = drop (nat.succ n) L,
which is definitionally equal to drop (n + 1) L
by def of nat.succ-/
-- other goal : tail nil = nil (hypothesis necessary for modify_nth_tail_eq_take_drop)
refl, -- true by definition of tail
end
/--changing the order of element removal of a list of integers-/
lemma remove_nth_remove_nth {a b : ℕ } (L : list ℤ)(Ha : a ≤ length L)(Hb : b + 1 ≤ length L):
remove_nth (remove_nth L a) b = if a < (b + 1) then remove_nth (remove_nth L (b+1)) a
else remove_nth (remove_nth L b) (a-1):=
begin
/- my proof will at some point require a to be psitive, so we prove the case where
a is 0 separately-/
cases a,
-- a = 0
{ rw if_pos (nat.zero_lt_succ _), -- 0 < (b + 1), because any successor in ℕ is greater than 0
-- so we need to prove remove_nth (remove_nth L a) b = remove_nth (remove_nth L (b+1)) 0
rw remove_nth_zero, -- lemma says : for any list A, remove_nth A 0 = tail A
rw remove_nth_zero,
cases L with c Lc,
-- L = nil
{intros,
refl}, -- both sides are nil by def of remove_nth and tail
-- L = (c :: Lc)
{intros,
refl}, /- both sides are remove_nth (tail (c :: Lc)) b
by def of remove_nth and tail-/
},
-- nat.succ a
split_ifs with ite1, -- now we have to prove each case of the if-then-else-condition
-- if-case (named ite1) : nat.succ a < b + 1
{ repeat {rw remove_nth_eq_take_append_drop}, -- see lemma above
/- get goal : take b (take (nat.succ a) L ++ drop (nat.succ a + 1) L) ++
drop (b + 1) (take (nat.succ a) L ++ drop (nat.succ a + 1) L) =
take (nat.succ a) (take (b + 1) L ++ drop (b + 1 + 1) L) ++
drop (nat.succ a + 1) (take (b + 1) L ++ drop (b + 1 + 1) L)
we need to simplify this
We will start by getting rid of appends within drop or take-/
rw drop_append, /- drop (b + 1) (take (nat.succ a) L ++ drop (nat.succ a + 1) L) =
ite (b + 1 ≤ length (take (nat.succ a) L)) (drop (b + 1) (take (nat.succ a) L) ++ drop (nat.succ a + 1) L)
(drop (b + 1 - length (take (nat.succ a) L)) (drop (nat.succ a + 1) L))-/
split_ifs with ite2,
-- if-case (named ite2) : b < length (take (nat.succ a) L)
{rw [length_take, lt_min_iff] at ite2, --b < length (take (nat.succ a) L) ↔ b < nat.succ a ∧ b < length L
cases ite2,
linarith}, -- gives contradiction between ite1 and b < nat.succ a which Lean can find itself with linarith
-- else-case (named ite2) : ¬ (b < length (take (nat.succ a) L))
clear ite2,-- will not need negation of ite2 for this
rw @take_append _ _ _ (a + 1), /- take (nat.succ a) (take (b + 1) L ++ drop (b + 1 + 1) L)
= ite (a + 1 ≤ length (take (b + 1) L)) (take (a + 1) (take (b + 1) L))
(take (b + 1) L ++ take (a + 1 - length (take (b + 1) L))
(drop (b + 1 + 1) L))-/
split_ifs with ite3,
swap,
-- else-case (named ite3) : ¬ (a < length (take (b + 1) L))
{ push_neg at ite3, -- ite3 is length (take (b + 1) L) ≤ a
rw [length_take] at ite3, -- ite3 ↔ min (b + 1) (length L) ≤ a
exfalso, -- gives contradiction between ite3 and ite1
rw min_eq_left Hb at ite3, -- know (by Hb) that the minimum is b+1
change a + 1 < _ at ite1,
linarith, -- after simplifying ite1 Lean can find the contradiction
},
-- if-case (named ite3) : a < length (take (b + 1) L)
rw take_append,-- get rid of the other append within take
rw drop_append,-- get rid of the other append within drop
/- simplifying the if-conditions that came up in the last two lines :
b ≤ length (take (nat.succ a) L) and nat.succ a + 1 ≤ length (take (b + 1) L)-/
rw length_take,
rw length_take,
rw min_eq_left Hb,
rw min_eq_left Ha,
rw nat.succ_eq_add_one at *, -- nat.succ a = a + 1 (rewritten in all hypotheses as well)
-- now they are b ≤ a + 1 and a + 1 + 1 ≤ b + 1 (the second one is true by ite1 : a + 1 < b + 1)
clear ite3,
rw if_pos (show a+1+1≤b+1, from ite1), -- second if-condition is true by ite1
split_ifs with ite4, -- the other we solve by cases
--if-case (named ite4) : b ≤ a + 1
{ rw le_iff_eq_or_lt at ite4, -- ite4 is b = a + 1 ∨ b < a + 1
cases ite4,
swap,
-- b < a + 1
{exfalso, -- contradicts ite1
linarith},
-- b = a + 1
{rw ←ite4, -- express everything in terms of b and L
/- goal is :
take b (take b L) ++ drop (b + 1 - b) (drop (b + 1) L) =
take b (take (b + 1) L) ++ (drop (b + 1) (take (b + 1) L) ++ drop (b + 1 + 1) L)-/
rw take_take, -- take b (take b L) = take (min b b) L
rw min_self, -- min b b = b
rw take_take, -- take b (take (b + 1) L) = take (min b (b + 1)) L
rw min_eq_left, -- min b (b + 1) = b, need to prove b ≤ b + 1 for that
swap,
{simp only [zero_le, le_add_iff_nonneg_right]}, -- proves b ≤ b + 1
congr', /- changes goal to drop (b + 1 - b) (drop (b + 1) L) =
drop (b + 1) (take (b + 1) L) ++ drop (b + 1 + 1) L -/
rw drop_drop, -- drop (b + 1 - b) (drop (b + 1) L) = drop (b + 1 - b + (b + 1)) L
rw drop_take (b+1) 0 L, -- drop (b + 1) (take (b + 1) L) = take 0 (drop (b + 1) L)
rw take_zero, -- take 0 (drop (b + 1) L) = nil
rw nil_append,
-- goal is now drop (b + 1 - b + (b + 1)) L = drop (b + 1 + 1) L
simp,}, -- Lean can do this by itself with simp
},
--else-case (named ite4) : ¬ (b ≤ a + 1)
{ /- goal is again :
take (a + 1) L ++ take (b - (a + 1)) (drop (a + 1 + 1) L)
++ drop (b + 1 - (a + 1)) (drop (a + 1 + 1) L) =
take (a + 1) (take (b + 1) L) ++ (drop (a + 1 + 1) (take (b + 1) L)
++ drop (b + 1 + 1) L)-/
rw drop_drop, /- drop (b + 1 - (a + 1)) (drop (a + 1 + 1) L) =
drop (b + 1 - (a + 1) + (a + 1 + 1)) L -/
rw take_take, /- take (a + 1) (take (b + 1) L) =
take (min (a + 1) (b + 1)) L-/
rw min_eq_left (le_of_lt ite1), -- min (a + 1) (b + 1) = a + 1 , because of ite1
rw ←drop_take, /- take (b - (a + 1)) (drop (a + 1 + 1) L) =
drop (a + 1 + 1) (take (a + 1 + 1 + (b - (a + 1))) L) -/
/- hence have goal :
take (a + 1) L ++ drop (a + 1 + 1) (take (a + 1 + 1 + (b - (a + 1))) L)
++ drop (b + 1 - (a + 1) + (a + 1 + 1)) L =
take (a + 1) L ++ (drop (a + 1 + 1) (take (b + 1) L) ++ drop (b + 1 + 1) L)
Just need to show the terms in brackets are the same on both sides-/
have p1 : b + 1 - (a + 1) + (a + 1 + 1) = b + 1 + 1,
{clear Hb Ha, -- because omega peculiarly does not work otherwise
omega}, -- Lean can solve this by itself
rw p1,
clear p1,
have p2 : a + 1 + 1 + (b - (a + 1)) = b + 1,
{clear Hb Ha, -- because omega peculiarly does not work otherwise
omega}, -- Lean can solve this by itself
rw p2,
clear p2,
simp,
},
},
-- else-case (named ite1) : ¬ (nat.succ a < b + 1)
{ rw nat.succ_eq_add_one at *,
repeat {rw remove_nth_eq_take_append_drop},
/- goal is now in form :
take b (take (a + 1) L ++ drop (a + 1 + 1) L)
++ drop (b + 1) (take (a + 1) L ++ drop (a + 1 + 1) L) =
take (a + 1 - 1) (take b L ++ drop (b + 1) L)
++ drop (a + 1 - 1 + 1) (take b L ++ drop (b + 1) L)
Again, we need to simplify this-/
rw take_append, /- take b (take (a + 1) L ++ drop (a + 1 + 1) L) =
if (b ≤ length (take (a + 1) L)) then (take b (take (a + 1) L))
else (take (a + 1) L ++ take (b - length (take (a + 1) L)) (drop (a + 1 + 1) L))-/
split_ifs with ite5,
swap,
-- else-case (named ite5) : ¬ (b ≤ length (take (a + 1) L))
{exfalso, -- contradicts ite1 (rewrite ite5 until Lean finds the contradiction with linarith)
push_neg at ite5,
rw length_take at ite5,
rw min_eq_left Ha at ite5,
linarith},
-- if-case (named ite5) : b ≤ length (take (a + 1) L)
{rw drop_append, /- drop (b + 1) (take (a + 1) L ++ drop (a + 1 + 1) L) =
if (b + 1 ≤ length (take (a + 1) L)) then (drop (b + 1) (take (a + 1) L) ++ drop (a + 1 + 1) L)
else (drop (b + 1 - length (take (a + 1) L)) (drop (a + 1 + 1) L)-/
push_neg at ite1, -- put ite5 in form b + 1 ≤ a + 1
-- simplify if-condition
rw length_take, -- length (take (a + 1) L) = min (a + 1) (length L)
rw min_eq_left Ha, -- min (a + 1) (length L) = a + 1 because of Ha
rw if_pos ite1, -- if-condition is exactly ite1, so is true
rw drop_append, /- drop (a + 1 - 1 + 1) (take b L ++ drop (b + 1) L) =
if (a + 1 - 1 + 1 ≤ length (take b L))
then (drop (a + 1 - 1 + 1) (take b L) ++ drop (b + 1) L)
else (drop (a + 1 - 1 + 1 - length (take b L)) (drop (b + 1) L))-/
split_ifs with ite6,
-- if-case (named ite6) : a + 1 - 1 + 1 ≤ length (take b L)
rw length_take at ite6, -- length (take b L) = min b (length L)
rw min_eq_left (le_trans (nat.le_succ b) Hb) at ite6, -- min b (length L) = b (because of Hb and transitivity of ≤)
{exfalso, -- ite6 contradicts ite1
clear Ha Hb ite5,
omega},
-- else-case (named ite6) : ¬ (a + 1 - 1 + 1 ≤ length (take b L))
rw take_append, /- take (a + 1 - 1) (take b L ++ drop (b + 1) L) =
if (a + 1 - 1 ≤ length (take b L))
then (take (a + 1 - 1) (take b L))
else (take b L ++ take (a + 1 - 1 - length (take b L))
(drop (b + 1) L))-/
-- simplify if-condition to a + 1 - 1 ≤ b
rw length_take,
rw min_eq_left (le_trans (nat.le_succ b) Hb),
split_ifs with ite7,
-- if-case (named ite7) : a + 1 - 1 ≤ b
{push_neg at ite6, -- put ite6 in form length (take b L) ≤ a + 1 - 1
have eq: a + 1 - 1 = b,
{rw length_take at ite6,
rw min_eq_left (le_trans (nat.le_succ b) Hb) at ite6,
exact le_antisymm ite7 ite6}, -- ite6 is now b ≤ a + 1 - 1, so with ite7 we have equality
rw nat.add_sub_cancel at eq, -- get rid of 1 - 1 in eq
rw eq, -- express everything in terms of b and L
rw nat.add_sub_cancel, -- get rid of 1 - 1
/- goal is now :
take b (take (b + 1) L) ++ (drop (b + 1) (take (b + 1) L)
++ drop (b + 1 + 1) L) =
take b (take b L) ++ drop (b + 1 - b) (drop (b + 1) L)-/
rw take_take, --take b (take (b + 1) L) = take (min b (b + 1) L)
rw min_eq_left (nat.le_succ b), -- min b (b + 1) = b (as b ≤ b + 1)
rw drop_drop, -- drop (b + 1 - b) (drop (b + 1) L) = drop (b + 1 - b + (b + 1)) L
rw take_take, -- take b (take b L) = take (min b b) L
clear eq,
rw min_eq_left (nat.le_refl b), -- min b b, because of reflexivity of ≤
simp only [add_zero, nat.add_sub_cancel_left, add_comm, le_add_iff_nonneg_right],
rw append_left_inj (take b L), /- take b L ++ (drop (b + 1) (take (b + 1) L) ++ drop (1 + (b + 1)) L) =
take b L ++ drop (1 + (b + 1)) L
↔
(drop (b + 1) (take (b + 1) L) ++ drop (1 + (b + 1)) L) =
drop (1 + (b + 1)) L-/
rw drop_take (b + 1) 0 L, -- drop (b + 1) (take (b + 1) L) = take 0 (drop (b + 1) L)
rw take_zero, --take 0 (drop (b + 1) L) = nil
rw nil_append,},
-- else-case (named ite7) : ¬ (a + 1 - 1 ≤ b)
/- goal is :
take b (take (a + 1) L) ++ (drop (b + 1) (take (a + 1) L)
++ drop (a + 1 + 1) L) =
take b L ++ take (a + 1 - 1 - b) (drop (b + 1) L)
++ drop (a + 1 - 1 + 1 - b) (drop (b + 1) L)-/
{clear ite6,
rw take_take, -- take b (take (a + 1) L) = take (min b (a + 1)) L
rw drop_drop, -- drop (a + 1 - 1 + 1 - b) (drop (b + 1) L) = drop (a + 1 - 1 + 1 - b + (b + 1)) L
rw length_take at ite5, -- so ite 5 is : b ≤ min (a + 1) (length L)
rw min_eq_left Ha at *, -- min (a + 1) (length L) = a + 1 , because of Ha (everywhere)
rw min_eq_left ite5 at *, -- min b (a + 1) = b , because of ite5 (everywhere)
rw ← drop_take, -- take (a + 1 - 1 - b) (drop (b + 1) L) = drop (b + 1) (take (b + 1 + (a + 1 - 1 - b)) L)
/- so goal is :
take b L ++ (drop (b + 1) (take (a + 1) L) ++ drop (a + 1 + 1) L) =
take b L ++ drop (b + 1) (take (b + 1 + (a + 1 - 1 - b)) L)
++ drop (a + 1 - 1 + 1 - b + (b + 1)) L
and both sides are the same after simpifying the arithmetic-/
have p1 : b + 1 + (a + 1 - 1 - b) = a + 1,
clear Hb Ha,
omega,
rw p1,
clear p1,
have p2 : a + 1 - 1 + 1 - b + (b + 1) = a + 1 + 1,
clear Hb Ha,
omega,
rw p2,
clear p2,
simp}, -- basically would just need associativity of append
},
},
end
/-- If two lists each with their nth element removed are the same,
then their lengths are the same-/
lemma remove_nth_eq_remove_nth_to_length_eq {α : Type*} {A B : list α}:
∀ (n : ℕ) (hA : n < length A)(hB : n < length B), remove_nth A n = remove_nth B n
→ length A = length B:=
begin
intros n hA hB h,
-- show the length of the shortened lists are the same
have p : length (remove_nth A n) = length (remove_nth B n),
{rw h},
-- show from that length A - 1 = length B - 1
rw length_remove_nth A n hA at p,
rw length_remove_nth B n hB at p,
/- as length A is a natural number, length A - 1 = 0 if length A = 0 in Lean,
so we need the following, which follow from hA and hB
(the leangths are strictly greater than some natural number, so at least 1)-/
have pa : 1 ≤ length A := by exact nat.one_le_of_lt hA,
have pb : 1 ≤ length B := by exact nat.one_le_of_lt hB,
exact nat.pred_inj pa pb p, -- now through pa and pb and p the result follows
end
/- drop -/
/-- If the index of the removed element is less than the amount b one wants to drop from the start,
it is the same as dropping b + 1-/
lemma drop_remove_nth_le {a b : ℕ } {L : list ℤ} (h1 : a ≤ b) (h2 : b ≤ length L):
drop b (remove_nth L a) = drop (b + 1) L :=
begin
rw remove_nth_eq_take_append_drop,-- remove_nth L a = take a L ++ drop (a + 1) L
rw drop_append, /- drop b (take a L ++ drop (a + 1) L) =
if (b ≤ length (take a L)),
then (drop b (take a L) ++ drop (a + 1) L),
else (drop (b - length (take a L)) (drop (a + 1) L))-/
rw length_take, -- length (take a L) = min a (length L)
rw min_eq_left (le_trans h1 h2), -- min a (length L) = a, because of h1 and h2
split_ifs with ite,
-- if-case (named ite) : b ≤ a (in this case because of h1, a = b)
{
{have p1: a=b:= by exact le_antisymm h1 ite,
rw p1,
-- the statement then holds because drop b (take b L) = nil (we drop all we take)
have p2 : drop b (take b L) = nil,
{convert drop_all _,
rw length_take,
rw min_eq_left h2,},
rw p2,
rw nil_append}, -- nil ++ drop (b + 1) L = drop (b + 1) L
},
-- else-case (named ite) : ¬ (b ≤ a)
{rw drop_drop, -- drop (b - a) (drop (a + 1) L) = drop (b - a + (a + 1)) L
congr' 1, /- instead of drop (b - a + (a + 1)) L = drop (b + 1) L
we can prove b - a + (a + 1) = b + 1 -/
show b - a + a + 1 = b + 1,
rw nat.sub_add_cancel h1,
},
end
/--If dropping the first x elements of two lists gives the same list,
so does dropping the first x + 1-/
lemma drop_aux_1 {A B : list ℤ} {x: ℕ } :
drop x A = drop x B → drop (nat.succ x) A = drop (nat.succ x) B :=
begin
intro H,
rw nat.succ_eq_add_one,
rw add_comm,
rw drop_add, -- lemma says : for all a, b in ℕ, lists L, drop (a + b) L = drop a (drop b L)
rw H,
rw drop_drop, -- drop_add backwards
end
/--If dropping the first x elements of two lists gives the same list,
so does dropping the first y if y ≥ x-/
lemma drop_aux_2 {A B : list ℤ} {x y : ℕ } (h : x ≤ y):
drop x A = drop x B → drop y A = drop y B :=
begin
/- The plan is to use induction on the difference n between x and y,
then if n = 0 this is trivial and the inductive step is done using drop_aux_1-/
have P : ∃ (n:ℕ), y = x + n,
{exact le_iff_exists_add.mp h},
cases P with n Pn, -- let n be s.t. (Pn : y = x + n) holds
have Py : x = y - n,
{rw Pn,
rw nat.add_sub_cancel}, -- n and -n cancel
rw Py,
revert A B x y, -- do not want inductive hypothesis to depend on A,B,x,y
induction n with d hd,
-- base case : n = 0
{repeat {rw nat.add_zero}, -- x + 0 = x
simp}, -- Lean can do this much by itself
-- inductive step : n = nat.succ d
{intros A B x y P Py Px H, -- A B x y P Py Px as before
rw nat.succ_eq_add_one at Py,
rw Py,
rw ← add_assoc, -- associativity of +
-- goal is now : drop (x + d + 1) A = drop (x + d + 1) B
rw drop_add, -- lemma says : for all a, b in ℕ, lists L, drop (a + b) L = drop a (drop b L)
rw drop_add (x+d) 1 B,
/- now the goal is drop (x + d) (drop 1 A) = drop (x + d) (drop 1 B)
that is why we had to revert A and B
this is the correct form for the inductive hypothesis
with x = x , y = x + d, A = drop 1 A, B = drop 1 B
but before we can use it we need a few trivial necessary hypotheses for
hd-/
rw ← Px at H,
have triv1 : x ≤ x + d, simp,
have triv2 : x + d = x + d, refl,
have triv3 : x = x + d - d, simp,
have H_new : drop (nat.succ x) A = drop (nat.succ x) B,
{exact drop_aux_1 H},
-- need H_new in the form : drop (x + d - d) (drop 1 A) = drop (x + d - d) (drop 1 B)
rw nat.succ_eq_add_one at H_new,
rw drop_add at H_new,
rw drop_add x 1 B at H_new,
rw triv3 at H_new,
exact hd triv1 triv2 triv3 H_new}, -- use inductive hypothesis
end
/- take -/
/--If the first x+1 elements of two lists are the same, so are the first x-/
lemma take_aux_1 {A B : list ℤ} {x: ℕ } :
take (nat.succ x) A = take (nat.succ x) B → take x A = take x B :=
begin
revert B x, -- so inductive hypothesis does not depend on x or B
induction A with a An IH,
-- base case : A = nil
{intros B x,
cases B with b Bn, -- because we get a contradiction when B is non-empty
-- B = nil
{ intro H,
refl}, -- clearly take x nil = take x nil
-- B = (b :: Bn)
{intro H,
exfalso, /- contradicts H : take (nat.succ x) nil = take (nat.succ x) (b :: Bn)
as RHS is not nil -/
rw take_nil at H, -- take (nat.succ x) nil
rw take_cons at H, -- take (nat.succ x) (b :: Bn) = b :: take x Bn
simp at H, -- Lean sees that H is false by itself
exact H}},
-- inductive step : A = (a :: An)
{intros B x,
cases B with b Bn, -- because we get a contradiction when B is empty
-- B = nil (similar to A = nil and B = (b :: Bn))
{intro H,
exfalso,
rw take_nil at H,
rw take_cons at H,
simp at H,
exact H},
-- B = (b :: Bn)
/- goal is now : take (nat.succ x) (a :: An) = take (nat.succ x) (b :: Bn)
→ take x (a :: An) = take x (b :: Bn)-/
cases x with y, /- we want to have some successor nat.succ y in place of x
because we want to use the inductive hypothesis with Bn and y
So we need to do the trivial x=0-case separately-/
-- x = 0
{intro H,
rw take_zero, -- lemma says : take 0 L = nil , for any list L
rw take_zero},
-- x = nat.succ y
{intro H,
rw take_cons, /- Lemma says : for any list l, m of the correct type, n in ℕ, \
take (nat.succ n) (m :: l) = m :: take n l-/
rw take_cons,
rw take_cons at H,
rw take_cons at H,
/- now from H we need to extract the information that a = b (or
equivalently [a] = [b]), and that
take (nat.succ y) An = take (nat.succ y) Bn. The second one we
need for the inductive hypothesis-/
rw cons_eq_sing_append at H, -- see list.lemmas.simple
rw cons_eq_sing_append b at H,
have H_left : [a] = [b] ,
{rw append_inj_right H _, /- if length [a] = length [b] then [a] = [b]
(because by H, [a] ++ take (nat.succ y) An = [b] ++ take (nat.succ y) Bn-/
simp},
have H_right : take (nat.succ y) An = take (nat.succ y) Bn,
{rw append_inj_left H _, -- same as above, but equality of the right side of the append
rw H_left},
rw cons_eq_sing_append,
rw cons_eq_sing_append b,
rw H_left,
rw append_left_inj [b], -- [b] ++ take y An = [b] ++ take y Bn ↔ take y An = take y Bn
exact IH H_right},}, -- use inductive hypothesis
end
/--If the first x elements of two lists are the same, so are the first y if y ≤ x-/
lemma take_aux_2 {A B : list ℤ} {x y : ℕ } (h : y ≤ x):
take x A = take x B → take y A = take y B :=
begin
/- The plan is to use induction on the difference n between x and y,
then if n = 0 this is trivial and the inductive step is done using take_aux_1-/
have P : ∃ (n:ℕ), x = y + n,
{exact le_iff_exists_add.mp h},
cases P with n Pn, -- let n be s.t. (Pn : y = x + n) holds
have Py : y = x - n,
{rw Pn,
rw nat.add_sub_cancel},
rw Py,
revert A B x y, -- so inductive hypothesis does not depend on A B x y
induction n with d hd,
-- base case : n = 0
{repeat {rw nat.sub_zero},
simp}, -- Lean can solve take x A = take x B → take x A = take x B
-- inductive step : n = nat.succ d
{intros A B x y P Px Py H,
rw ← Py,
/- H is take x A = take x B, so if one of the lists is nil while the
other is not, and x is non-zero, we get a contradiction,
because only one side will be the empty list -/
cases A with a An,
-- A = nil
{cases B with b Bn,
-- B = nil
{refl}, -- if both lists are nil, the result follows from def of take
-- B = (b :: Bn)
{cases y with y',
-- y = 0
/-(in this case x - nat.succ d = 0, so right side is take 0 (b :: Bn)
which is also nil)-/
{rw take_nil,
rw take_zero},
-- y = nat.succ y'
{exfalso, -- y ≤ x, so x is positive
rw take_nil at H,
rw Px at H,
rw take_cons at H,
simp at H,
exact H},},
},
-- A = (a :: An)
{cases B with b Bn,
-- B = nil (similar to case where A = nil and B = (b :: Bn))
{cases y with y',
-- y = 0
{rw take_nil,
rw take_zero},
-- y = nat.succ y'
{exfalso,
rw take_nil at H,
rw Px at H,
rw take_cons at H,
simp at H,
exact H},},
-- B = (b :: Bn) (main case, where we will need hd)
/- now the goal is take (x - nat.succ d) (a :: An) = take (x - nat.succ d) (b :: Bn)
this is the correct form for the inductive hypothesis
with x = nat.succ y' + d , y = nat.succ y', A = An, B = Bn, for some y'
so we want y in the form nat.succ y' and hence need to do the (y = 0)-case
separately again-/
{cases y with y',
-- y = 0 (here both sides are nil again)
{rw take_zero,
rw take_zero},
-- y = nat.succ y'
{rw take_cons,
rw take_cons,
/- now from H we need to extract the information that a = b (or
equivalently [a] = [b]), and that
take (nat.succ y' + d) An = take (nat.succ y' + d) Bn. The second one we
need to get a necessary hypothesis for the inductive hypothesis
through take_aux_1-/
rw Px at H,
rw take_cons at H,
rw take_cons at H,
rw cons_eq_sing_append at H,
rw cons_eq_sing_append b at H,
have H_left : [a] = [b] ,
{rw append_inj_right H,
simp},
have H_right : take (nat.succ y' + d) An = take (nat.succ y' + d) Bn,
{rw append_inj_left H,
simp},
-- similarly to the proof of take_aux_1, we get rid of a and b in the goal
rw cons_eq_sing_append,
rw cons_eq_sing_append b,
rw H_left,
rw append_left_inj [b],
-- now we create all the trivial hypotheses needed for the induction
have triv1 : y' ≤ y' + d, simp,
have triv2 : y' + d = y' + d, refl,
have triv3 : y' = y' + d - d, simp,
have H_new : take (y' + d) An = take (y' + d) Bn, -- H_new can be derived from H
{rw nat.succ_add at H_right,
exact take_aux_1 H_right},
rw triv3, -- put the goal in the exact form of the result of the inductive hypothesis
exact hd triv1 triv2 triv3 H_new},},}, -- use inductive hypotheses
}
end
/--If you take the first m+1 elements of a list, revert the order and take the head
of the resulting list, you get the same element as when you drop the first m-1 elements,
and take the head and then the tail. (You get the m-th element counting from 0)-/
lemma take_drop_head_eq {A:list ℤ} {m : ℕ} (h1: 1 ≤ m) (h2: m + 1 ≤ length A):
head (reverse (take (m+1) A)) = head (tail (drop (m-1) A)):=
-- proof in term mode
by rw [
tail_drop, head_reverse_take h2, nat.succ_eq_add_one,
nat.sub_add_cancel h1, head_drop
]
/-
begin
rw tail_drop,
-- tail (drop (m - 1) A) = drop (nat.succ (m - 1)) A
rw head_reverse_take h2,
-- head (reverse (take (m + 1) A)) = nth_le A m h2
rw [nat.succ_eq_add_one, nat.sub_add_cancel h1],
-- nat.succ (m - 1) = m , because 1 ≤ m
rw head_drop,
-- head (drop m A) = nth_le A m _
end
-/
/--If you take the first d+2 elements of a list, revert the order and take the head
of the resulting list, you get the same element as when you drop the first d elements,
and take the head and then the tail. (You get the (d+1)th element element counting from 0)-/
lemma take_drop_head_eq' {A:list ℤ} {d : ℕ} (h2: d + 2 ≤ length A):
head (reverse (take (d+2) A)) = head (tail (drop d A)):=
-- proof in term mode (proof similar to lemma above)
by rw [tail_drop, head_reverse_take h2, head_drop]
/- nth_le -/
/--the nth element of a list with an element removed is the bth or (b+1)th
element of the full list, depending on which element was removed-/
lemma nth_le_remove_nth {a b : ℕ } (L : list ℤ) (h:b < length (remove_nth L a)) (h1 h2):
nth_le (remove_nth L a) b h =
if a ≤ b then nth_le L (b+1) h1
else nth_le L b h2:=
begin
split_ifs with ite1,
-- if-case (named ite1) : a ≤ b
{rw ← head_drop, -- nth_le (remove_nth L a) b h = head (drop b (remove_nth L a))
rw ← head_drop, -- nth_le L (b + 1) h1 = head (drop (b + 1) L)
apply head_eq_of_list_eq, -- if the lists are equal, their heads are equal
rw drop_remove_nth_le ite1 (le_of_lt h2), -- now the goal is just the result this lemma (see line 396)
},
-- else-case (named ite1) : ¬ (a ≤ b)
{{repeat {rw ← head_drop},-- goal becomes : head (drop b (remove_nth L a)) = head (drop b L)
push_neg at ite1, -- puts ite1 in form b < a
/- this time the lists we are taking the head of are not equal, as drop b (remove_nth L a)
has one element less than drop b L-/
rw remove_nth_eq_take_append_drop, -- remove_nth L a = drop b (take a L ++ drop (a + 1) L)
rw drop_append, /- drop b (take a L ++ drop (a + 1) L) =
if (b ≤ length (take a L)),
then (drop b (take a L) ++ drop (a + 1) L),
else (drop (b - length (take a L)) (drop (a + 1) L))-/
rw length_take,
rw if_pos (le_min (le_of_lt ite1) (le_of_lt h2)), -- we have b ≤ length (take a L), because b < a by ite1 and b < length L by h2
/- we want to use that head (drop b (take a L) ++ drop (a + 1) L)
= head (drop b (take a L), because drop b (take a L) is not nil, as b < a and b < length L
so we need to prove the following as well:-/
have P : drop b (take a L) ≠ nil,
{apply ne_nil_of_length_eq_succ , /- we prove this by proving length (drop b (take a L))
is the successor of some natural number (so greater than 0),
that natural number is (min a (length L) - b - 1)-/
swap,
{exact min a (length L) - b - 1},
rw length_drop, -- length (drop b (take a L)) = length (take a L) - b
rw length_take, -- length (take a L) = min a (length L)
rw nat.succ_eq_add_one, --nat.succ (min a (length L) - b - 1) = min a (length L) - b - 1 + 1
rw nat.sub_add_cancel, /- min a (length L) - b - 1 + 1 = min a (length L) - b, as reqired,
if min a (length L) - b ≥ 1 (because 0 - 1 = 0 in ℕ )-/
show 1 ≤ (min a (length L)) - b, -- use ≤ , because ≥ is defined via ≤
apply nat.le_sub_right_of_add_le, -- 1 + b ≤ min a (length L) → 1 ≤ min a (length L) - b
apply le_min, -- suffices to prove 1 + b ≤ a and 1 + b ≤ length L
rw add_comm,
exact ite1, -- first one is true by ite1 (b < a)
rw add_comm,
exact (le_of_lt h1),}, -- second one by h1 (b < length L)
rw head_append _ P, -- now we can use that
/- The goal is now : head (drop b (take a L)) = head (drop b L)
we will put head (drop b L) in the form head (drop b (take a L) ++ something)
and then use head_append again-/
rw ← take_append_drop a L, -- drop b L = drop b (take a L ++ drop a L)
rw drop_append, /- drop b (take a L ++ drop a L) =
if (b ≤ length (take a L)),
then (drop b (take a L) ++ drop a L),
else (drop (b - length (take a L)) (drop a L)))-/
rw length_take,
rw if_pos (le_min (le_of_lt ite1) (le_of_lt h2)), -- we have b ≤ length (take a L), because b < a by ite1 and b < length L by h2
rw take_append_drop a L, -- revert the change of the LHS from line 797
rw head_append _ P, -- head (drop b (take a L) ++ drop a L) = head (drop b (take a L)) by P
},},
end
|
8d69efbf1483782ebb7cfe0205221c8f523c1c30 | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/set/finite.lean | fb8128f395487bfefffea4c46d278588078eabf3 | [
"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 | 28,388 | 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.fintype.basic
/-!
# Finite sets
This file defines predicates `finite : set α → Prop` and `infinite : set α → Prop` and proves some
basic facts about finite sets.
-/
open set function
universes u v w x
variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x}
namespace set
/-- A set is finite if the subtype is a fintype, i.e. there is a
list that enumerates its members. -/
def finite (s : set α) : Prop := nonempty (fintype s)
/-- A set is infinite if it is not finite. -/
def infinite (s : set α) : Prop := ¬ finite s
/-- The subtype corresponding to a finite set is a finite type. Note
that because `finite` isn't a typeclass, this will not fire if it
is made into an instance -/
noncomputable def finite.fintype {s : set α} (h : finite s) : fintype s :=
classical.choice h
/-- Get a finset from a finite set -/
noncomputable def finite.to_finset {s : set α} (h : finite s) : finset α :=
@set.to_finset _ _ h.fintype
@[simp] theorem finite.mem_to_finset {s : set α} (h : finite s) {a : α} : a ∈ h.to_finset ↔ a ∈ s :=
@mem_to_finset _ _ h.fintype _
@[simp] theorem finite.to_finset.nonempty {s : set α} (h : finite s) :
h.to_finset.nonempty ↔ s.nonempty :=
show (∃ x, x ∈ h.to_finset) ↔ (∃ x, x ∈ s),
from exists_congr (λ _, h.mem_to_finset)
@[simp] lemma finite.coe_to_finset {α} {s : set α} (h : finite s) : ↑h.to_finset = s :=
@set.coe_to_finset _ s h.fintype
theorem finite.exists_finset {s : set α} : finite s →
∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s
| ⟨h⟩ := by exactI ⟨to_finset s, λ _, mem_to_finset⟩
theorem finite.exists_finset_coe {s : set α} (hs : finite s) :
∃ s' : finset α, ↑s' = s :=
⟨hs.to_finset, hs.coe_to_finset⟩
/-- Finite sets can be lifted to finsets. -/
instance : can_lift (set α) (finset α) :=
{ coe := coe,
cond := finite,
prf := λ s hs, hs.exists_finset_coe }
theorem finite_mem_finset (s : finset α) : finite {a | a ∈ s} :=
⟨fintype.of_finset s (λ _, iff.rfl)⟩
theorem finite.of_fintype [fintype α] (s : set α) : finite s :=
by classical; exact ⟨set_fintype s⟩
theorem exists_finite_iff_finset {p : set α → Prop} :
(∃ s, finite s ∧ p s) ↔ ∃ s : finset α, p ↑s :=
⟨λ ⟨s, hs, hps⟩, ⟨hs.to_finset, hs.coe_to_finset.symm ▸ hps⟩,
λ ⟨s, hs⟩, ⟨↑s, finite_mem_finset s, hs⟩⟩
/-- Membership of a subset of a finite type is decidable.
Using this as an instance leads to potential loops with `subtype.fintype` under certain decidability
assumptions, so it should only be declared a local instance. -/
def decidable_mem_of_fintype [decidable_eq α] (s : set α) [fintype s] (a) : decidable (a ∈ s) :=
decidable_of_iff _ mem_to_finset
instance fintype_empty : fintype (∅ : set α) :=
fintype.of_finset ∅ $ by simp
theorem empty_card : fintype.card (∅ : set α) = 0 := rfl
@[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} :
@fintype.card (∅ : set α) h = 0 :=
eq.trans (by congr) empty_card
@[simp] theorem finite_empty : @finite α ∅ := ⟨set.fintype_empty⟩
instance finite.inhabited : inhabited {s : set α // finite s} := ⟨⟨∅, finite_empty⟩⟩
/-- A `fintype` structure on `insert a s`. -/
def fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) :=
fintype.of_finset ⟨a ::ₘ s.to_finset.1,
multiset.nodup_cons_of_nodup (by simp [h]) s.to_finset.2⟩ $ by simp
theorem card_fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) :
@fintype.card _ (fintype_insert' s h) = fintype.card s + 1 :=
by rw [fintype_insert', fintype.card_of_finset];
simp [finset.card, to_finset]; refl
@[simp] theorem card_insert {a : α} (s : set α)
[fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} :
@fintype.card _ d = fintype.card s + 1 :=
by rw ← card_fintype_insert' s h; congr
lemma card_image_of_inj_on {s : set α} [fintype s]
{f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) :
fintype.card (f '' s) = fintype.card s :=
by haveI := classical.prop_decidable; exact
calc fintype.card (f '' s) = (s.to_finset.image f).card : fintype.card_of_finset' _ (by simp)
... = s.to_finset.card : finset.card_image_of_inj_on
(λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy)
... = fintype.card s : (fintype.card_of_finset' _ (λ a, mem_to_finset)).symm
lemma card_image_of_injective (s : set α) [fintype s]
{f : α → β} [fintype (f '' s)] (H : function.injective f) :
fintype.card (f '' s) = fintype.card s :=
card_image_of_inj_on $ λ _ _ _ _ h, H h
section
local attribute [instance] decidable_mem_of_fintype
instance fintype_insert [decidable_eq α] (a : α) (s : set α) [fintype s] :
fintype (insert a s : set α) :=
if h : a ∈ s then by rwa [insert_eq, union_eq_self_of_subset_left (singleton_subset_iff.2 h)]
else fintype_insert' _ h
end
@[simp] theorem finite.insert (a : α) {s : set α} : finite s → finite (insert a s)
| ⟨h⟩ := ⟨@set.fintype_insert _ (classical.dec_eq α) _ _ h⟩
lemma to_finset_insert [decidable_eq α] {a : α} {s : set α} (hs : finite s) :
(hs.insert a).to_finset = insert a hs.to_finset :=
finset.ext $ by simp
@[elab_as_eliminator]
theorem finite.induction_on {C : set α → Prop} {s : set α} (h : finite s)
(H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → finite s → C s → C (insert a s)) : C s :=
let ⟨t⟩ := h in by exactI
match s.to_finset, @mem_to_finset _ s _ with
| ⟨l, nd⟩, al := begin
change ∀ a, a ∈ l ↔ a ∈ s at al,
clear _let_match _match t h, revert s nd al,
refine multiset.induction_on l _ (λ a l IH, _); intros s nd al,
{ rw show s = ∅, from eq_empty_iff_forall_not_mem.2 (by simpa using al),
exact H0 },
{ rw ← show insert a {x | x ∈ l} = s, from set.ext (by simpa using al),
cases multiset.nodup_cons.1 nd with m nd',
refine H1 _ ⟨finset.subtype.fintype ⟨l, nd'⟩⟩ (IH nd' (λ _, iff.rfl)),
exact m }
end
end
@[elab_as_eliminator]
theorem finite.dinduction_on {C : ∀s:set α, finite s → Prop} {s : set α} (h : finite s)
(H0 : C ∅ finite_empty)
(H1 : ∀ {a s}, a ∉ s → ∀h:finite s, C s h → C (insert a s) (h.insert a)) :
C s h :=
have ∀h:finite s, C s h,
from finite.induction_on h (assume h, H0) (assume a s has hs ih h, H1 has hs (ih _)),
this h
instance fintype_singleton (a : α) : fintype ({a} : set α) :=
unique.fintype
@[simp] theorem card_singleton (a : α) :
fintype.card ({a} : set α) = 1 :=
fintype.card_of_subsingleton _
@[simp] theorem finite_singleton (a : α) : finite ({a} : set α) :=
⟨set.fintype_singleton _⟩
lemma subsingleton.finite {s : set α} (h : s.subsingleton) : finite s :=
h.induction_on finite_empty finite_singleton
instance fintype_pure : ∀ a : α, fintype (pure a : set α) :=
set.fintype_singleton
theorem finite_pure (a : α) : finite (pure a : set α) :=
⟨set.fintype_pure a⟩
instance fintype_univ [fintype α] : fintype (@univ α) :=
fintype.of_equiv α $ (equiv.set.univ α).symm
theorem finite_univ [fintype α] : finite (@univ α) := ⟨set.fintype_univ⟩
/-- If `(set.univ : set α)` is finite then `α` is a finite type. -/
noncomputable def fintype_of_univ_finite (H : (univ : set α).finite ) :
fintype α :=
@fintype.of_equiv _ (univ : set α) H.fintype (equiv.set.univ _)
lemma univ_finite_iff_nonempty_fintype :
(univ : set α).finite ↔ nonempty (fintype α) :=
begin
split,
{ intro h, exact ⟨fintype_of_univ_finite h⟩ },
{ rintro ⟨_i⟩, exactI finite_univ }
end
theorem infinite_univ_iff : (@univ α).infinite ↔ _root_.infinite α :=
⟨λ h₁, ⟨λ h₂, h₁ $ @finite_univ α h₂⟩, λ ⟨h₁⟩ h₂, h₁ (fintype_of_univ_finite h₂)⟩
theorem infinite_univ [h : _root_.infinite α] : infinite (@univ α) :=
infinite_univ_iff.2 h
theorem infinite_coe_iff {s : set α} : _root_.infinite s ↔ infinite s :=
⟨λ ⟨h₁⟩ h₂, h₁ h₂.some, λ h₁, ⟨λ h₂, h₁ ⟨h₂⟩⟩⟩
theorem infinite.to_subtype {s : set α} (h : infinite s) : _root_.infinite s :=
infinite_coe_iff.2 h
/-- Embedding of `ℕ` into an infinite set. -/
noncomputable def infinite.nat_embedding (s : set α) (h : infinite s) : ℕ ↪ s :=
by { haveI := h.to_subtype, exact infinite.nat_embedding s }
lemma infinite.exists_subset_card_eq {s : set α} (hs : infinite s) (n : ℕ) :
∃ t : finset α, ↑t ⊆ s ∧ t.card = n :=
⟨((finset.range n).map (hs.nat_embedding _)).map (embedding.subtype _), by simp⟩
lemma infinite.nonempty {s : set α} (h : s.infinite) : s.nonempty :=
let a := infinite.nat_embedding s h 37 in ⟨a.1, a.2⟩
instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] :
fintype (s ∪ t : set α) :=
fintype.of_finset (s.to_finset ∪ t.to_finset) $ by simp
theorem finite.union {s t : set α} : finite s → finite t → finite (s ∪ t)
| ⟨hs⟩ ⟨ht⟩ := ⟨@set.fintype_union _ (classical.dec_eq α) _ _ hs ht⟩
lemma infinite_of_finite_compl {α : Type} [_root_.infinite α] {s : set α}
(hs : sᶜ.finite) : s.infinite :=
λ h, set.infinite_univ (by simpa using hs.union h)
lemma finite.infinite_compl {α : Type} [_root_.infinite α] {s : set α}
(hs : s.finite) : sᶜ.infinite :=
λ h, set.infinite_univ (by simpa using hs.union h)
instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] :
fintype ({a ∈ s | p a} : set α) :=
fintype.of_finset (s.to_finset.filter p) $ by simp
instance fintype_inter (s t : set α) [fintype s] [decidable_pred t] : fintype (s ∩ t : set α) :=
set.fintype_sep s t
/-- A `fintype` structure on a set defines a `fintype` structure on its subset. -/
def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred t] (h : t ⊆ s) : fintype t :=
by rw ← inter_eq_self_of_subset_right h; apply_instance
theorem finite.subset {s : set α} : finite s → ∀ {t : set α}, t ⊆ s → finite t
| ⟨hs⟩ t h := ⟨@set.fintype_subset _ _ _ hs (classical.dec_pred t) h⟩
theorem infinite_mono {s t : set α} (h : s ⊆ t) : infinite s → infinite t :=
mt (λ ht, ht.subset h)
instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) :=
fintype.of_finset (s.to_finset.image f) $ by simp
instance fintype_range [decidable_eq β] (f : α → β) [fintype α] : fintype (range f) :=
fintype.of_finset (finset.univ.image f) $ by simp [range]
theorem finite_range (f : α → β) [fintype α] : finite (range f) :=
by haveI := classical.dec_eq β; exact ⟨by apply_instance⟩
theorem finite.image {s : set α} (f : α → β) : finite s → finite (f '' s)
| ⟨h⟩ := ⟨@set.fintype_image _ _ (classical.dec_eq β) _ _ h⟩
theorem infinite_of_infinite_image (f : α → β) {s : set α} (hs : (f '' s).infinite) :
s.infinite :=
mt (finite.image f) hs
lemma finite.dependent_image {s : set α} (hs : finite s) (F : Π i ∈ s, β) :
finite {y : β | ∃ x (hx : x ∈ s), y = F x hx} :=
begin
letI : fintype s := hs.fintype,
convert finite_range (λ x : s, F x x.2),
simp only [set_coe.exists, subtype.coe_mk, eq_comm],
end
instance fintype_map {α β} [decidable_eq β] :
∀ (s : set α) (f : α → β) [fintype s], fintype (f <$> s) := set.fintype_image
theorem finite.map {α β} {s : set α} :
∀ (f : α → β), finite s → finite (f <$> s) := finite.image
/-- If a function `f` has a partial inverse and sends a set `s` to a set with `[fintype]` instance,
then `s` has a `fintype` structure as well. -/
def fintype_of_fintype_image (s : set α)
{f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s :=
fintype.of_finset ⟨_, @multiset.nodup_filter_map β α g _
(@injective_of_partial_inv_right _ _ f g I) (f '' s).to_finset.2⟩ $ λ a,
begin
suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s,
by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc],
rw exists_swap,
suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]},
simp [I _, (injective_of_partial_inv I).eq_iff]
end
theorem finite_of_finite_image {s : set α} {f : α → β} (hi : set.inj_on f s) :
finite (f '' s) → finite s | ⟨h⟩ :=
⟨@fintype.of_injective _ _ h (λa:s, ⟨f a.1, mem_image_of_mem f a.2⟩) $
assume a b eq, subtype.eq $ hi a.2 b.2 $ subtype.ext_iff_val.1 eq⟩
theorem finite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) :
finite (f '' s) ↔ finite s :=
⟨finite_of_finite_image hi, finite.image _⟩
theorem infinite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) :
infinite (f '' s) ↔ infinite s :=
not_congr $ finite_image_iff hi
theorem infinite_of_inj_on_maps_to {s : set α} {t : set β} {f : α → β}
(hi : inj_on f s) (hm : maps_to f s t) (hs : infinite s) : infinite t :=
infinite_mono (maps_to'.mp hm) $ (infinite_image_iff hi).2 hs
theorem infinite_range_of_injective [_root_.infinite α] {f : α → β} (hi : injective f) :
infinite (range f) :=
by { rw [←image_univ, infinite_image_iff (inj_on_of_injective hi _)], exact infinite_univ }
theorem infinite_of_injective_forall_mem [_root_.infinite α] {s : set β} {f : α → β}
(hi : injective f) (hf : ∀ x : α, f x ∈ s) : infinite s :=
by { rw ←range_subset_iff at hf, exact infinite_mono hf (infinite_range_of_injective hi) }
theorem finite.preimage {s : set β} {f : α → β}
(I : set.inj_on f (f⁻¹' s)) (h : finite s) : finite (f ⁻¹' s) :=
finite_of_finite_image I (h.subset (image_preimage_subset f s))
theorem finite.preimage_embedding {s : set β} (f : α ↪ β) (h : s.finite) : (f ⁻¹' s).finite :=
finite.preimage (λ _ _ _ _ h', f.injective h') h
lemma finite_option {s : set (option α)} : finite s ↔ finite {x : α | some x ∈ s} :=
⟨λ h, h.preimage_embedding embedding.some,
λ h, ((h.image some).union (finite_singleton none)).subset $
λ x, option.cases_on x (λ _, or.inr rfl) (λ x hx, or.inl $ mem_image_of_mem _ hx)⟩
instance fintype_Union [decidable_eq α] {ι : Type*} [fintype ι]
(f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) :=
fintype.of_finset (finset.univ.bUnion (λ i, (f i).to_finset)) $ by simp
theorem finite_Union {ι : Type*} [fintype ι] {f : ι → set α} (H : ∀i, finite (f i)) :
finite (⋃ i, f i) :=
⟨@set.fintype_Union _ (classical.dec_eq α) _ _ _ (λ i, finite.fintype (H i))⟩
/-- A union of sets with `fintype` structure over a set with `fintype` structure has a `fintype`
structure. -/
def fintype_set_bUnion [decidable_eq α] {ι : Type*} {s : set ι} [fintype s]
(f : ι → set α) (H : ∀ i ∈ s, fintype (f i)) : fintype (⋃ i ∈ s, f i) :=
by rw bUnion_eq_Union; exact
@set.fintype_Union _ _ _ _ _ (by rintro ⟨i, hi⟩; exact H i hi)
instance fintype_set_bUnion' [decidable_eq α] {ι : Type*} {s : set ι} [fintype s]
(f : ι → set α) [H : ∀ i, fintype (f i)] : fintype (⋃ i ∈ s, f i) :=
fintype_set_bUnion _ (λ i _, H i)
theorem finite.sUnion {s : set (set α)} (h : finite s) (H : ∀t∈s, finite t) : finite (⋃₀ s) :=
by rw sUnion_eq_Union; haveI := finite.fintype h;
apply finite_Union; simpa using H
theorem finite.bUnion {α} {ι : Type*} {s : set ι} {f : Π i ∈ s, set α} :
finite s → (∀ i ∈ s, finite (f i ‹_›)) → finite (⋃ i∈s, f i ‹_›)
| ⟨hs⟩ h := by rw [bUnion_eq_Union]; exactI finite_Union (λ i, h _ _)
instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} :=
fintype.of_finset (finset.range n) $ by simp
instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} :=
by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1)
lemma finite_le_nat (n : ℕ) : finite {i | i ≤ n} := ⟨set.fintype_le_nat _⟩
lemma finite_lt_nat (n : ℕ) : finite {i | i < n} := ⟨set.fintype_lt_nat _⟩
instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (set.prod s t) :=
fintype.of_finset (s.to_finset.product t.to_finset) $ by simp
lemma finite.prod {s : set α} {t : set β} : finite s → finite t → finite (set.prod s t)
| ⟨hs⟩ ⟨ht⟩ := by exactI ⟨set.fintype_prod s t⟩
/-- `image2 f s t` is finitype if `s` and `t` are. -/
instance fintype_image2 [decidable_eq γ] (f : α → β → γ) (s : set α) (t : set β)
[hs : fintype s] [ht : fintype t] : fintype (image2 f s t : set γ) :=
by { rw ← image_prod, apply set.fintype_image }
lemma finite.image2 (f : α → β → γ) {s : set α} {t : set β} (hs : finite s) (ht : finite t) :
finite (image2 f s t) :=
by { rw ← image_prod, exact (hs.prod ht).image _ }
/-- If `s : set α` is a set with `fintype` instance and `f : α → set β` is a function such that
each `f a`, `a ∈ s`, has a `fintype` structure, then `s >>= f` has a `fintype` structure. -/
def fintype_bUnion {α β} [decidable_eq β] (s : set α) [fintype s]
(f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) :=
set.fintype_set_bUnion _ H
instance fintype_bUnion' {α β} [decidable_eq β] (s : set α) [fintype s]
(f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) :=
fintype_bUnion _ _ (λ i _, H i)
theorem finite_bUnion {α β} {s : set α} {f : α → set β} :
finite s → (∀ a ∈ s, finite (f a)) → finite (s >>= f)
| ⟨hs⟩ H := ⟨@fintype_bUnion _ _ (classical.dec_eq β) _ hs _ (λ a ha, (H a ha).fintype)⟩
instance fintype_seq {α β : Type u} [decidable_eq β]
(f : set (α → β)) (s : set α) [fintype f] [fintype s] :
fintype (f <*> s) :=
by rw seq_eq_bind_map; apply set.fintype_bUnion'
theorem finite.seq {α β : Type u} {f : set (α → β)} {s : set α} :
finite f → finite s → finite (f <*> s)
| ⟨hf⟩ ⟨hs⟩ := by { haveI := classical.dec_eq β, exactI ⟨set.fintype_seq _ _⟩ }
/-- There are finitely many subsets of a given finite set -/
lemma finite.finite_subsets {α : Type u} {a : set α} (h : finite a) : finite {b | b ⊆ a} :=
begin
-- we just need to translate the result, already known for finsets,
-- to the language of finite sets
let s : set (set α) := coe '' (↑(finset.powerset (finite.to_finset h)) : set (finset α)),
have : finite s := (finite_mem_finset _).image _,
apply this.subset,
refine λ b hb, ⟨(h.subset hb).to_finset, _, finite.coe_to_finset _⟩,
simpa [finset.subset_iff]
end
lemma exists_min_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) :
s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f a ≤ f b
| ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset]
using h1.to_finset.exists_min_image f ⟨x, h1.mem_to_finset.2 hx⟩
lemma exists_max_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) :
s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f b ≤ f a
| ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset]
using h1.to_finset.exists_max_image f ⟨x, h1.mem_to_finset.2 hx⟩
end set
namespace finset
variables [decidable_eq β]
variables {s : finset α}
lemma finite_to_set (s : finset α) : set.finite (↑s : set α) :=
set.finite_mem_finset s
@[simp] lemma coe_bUnion {f : α → finset β} : ↑(s.bUnion f) = (⋃x ∈ (↑s : set α), ↑(f x) : set β) :=
by simp [set.ext_iff]
@[simp] lemma finite_to_set_to_finset {α : Type*} (s : finset α) :
(finite_to_set s).to_finset = s :=
by { ext, rw [set.finite.mem_to_finset, mem_coe] }
end finset
namespace set
lemma finite_subset_Union {s : set α} (hs : finite s)
{ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, finite I ∧ s ⊆ ⋃ i ∈ I, t i :=
begin
casesI hs,
choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h},
refine ⟨range f, finite_range f, _⟩,
rintro x hx,
simp,
exact ⟨x, ⟨hx, hf _⟩⟩,
end
lemma eq_finite_Union_of_finite_subset_Union {ι} {s : ι → set α} {t : set α} (tfin : finite t)
(h : t ⊆ ⋃ i, s i) :
∃ I : set ι, (finite I) ∧ ∃ σ : {i | i ∈ I} → set α,
(∀ i, finite (σ i)) ∧ (∀ i, σ i ⊆ s i) ∧ t = ⋃ i, σ i :=
let ⟨I, Ifin, hI⟩ := finite_subset_Union tfin h in
⟨I, Ifin, λ x, s x ∩ t,
λ i, tfin.subset (inter_subset_right _ _),
λ i, inter_subset_left _ _,
begin
ext x,
rw mem_Union,
split,
{ intro x_in,
rcases mem_Union.mp (hI x_in) with ⟨i, _, ⟨hi, rfl⟩, H⟩,
use [i, hi, H, x_in] },
{ rintros ⟨i, hi, H⟩,
exact H }
end⟩
/-- An increasing union distributes over finite intersection. -/
lemma Union_Inter_of_monotone {ι ι' α : Type*} [fintype ι] [linear_order ι']
[nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, monotone (s i)) :
(⋃ j : ι', ⋂ i : ι, s i j) = ⋂ i : ι, ⋃ j : ι', s i j :=
begin
ext x, refine ⟨λ hx, Union_Inter_subset hx, λ hx, _⟩,
simp only [mem_Inter, mem_Union, mem_Inter] at hx ⊢, choose j hj using hx,
obtain ⟨j₀⟩ := show nonempty ι', by apply_instance,
refine ⟨finset.univ.fold max j₀ j, λ i, hs i _ (hj i)⟩,
rw [finset.fold_op_rel_iff_or (@le_max_iff _ _)],
exact or.inr ⟨i, finset.mem_univ i, le_rfl⟩
end
instance nat.fintype_Iio (n : ℕ) : fintype (Iio n) :=
fintype.of_finset (finset.range n) $ by simp
/--
If `P` is some relation between terms of `γ` and sets in `γ`,
such that every finite set `t : set γ` has some `c : γ` related to it,
then there is a recursively defined sequence `u` in `γ`
so `u n` is related to the image of `{0, 1, ..., n-1}` under `u`.
(We use this later to show sequentially compact sets
are totally bounded.)
-/
lemma seq_of_forall_finite_exists {γ : Type*}
{P : γ → set γ → Prop} (h : ∀ t, finite t → ∃ c, P c t) :
∃ u : ℕ → γ, ∀ n, P (u n) (u '' Iio n) :=
⟨λ n, @nat.strong_rec_on' (λ _, γ) n $ λ n ih, classical.some $ h
(range $ λ m : Iio n, ih m.1 m.2)
(finite_range _),
λ n, begin
classical,
refine nat.strong_rec_on' n (λ n ih, _),
rw nat.strong_rec_on_beta', convert classical.some_spec (h _ _),
ext x, split,
{ rintros ⟨m, hmn, rfl⟩, exact ⟨⟨m, hmn⟩, rfl⟩ },
{ rintros ⟨⟨m, hmn⟩, rfl⟩, exact ⟨m, hmn, rfl⟩ }
end⟩
lemma finite_range_ite {p : α → Prop} [decidable_pred p] {f g : α → β} (hf : finite (range f))
(hg : finite (range g)) : finite (range (λ x, if p x then f x else g x)) :=
(hf.union hg).subset range_ite_subset
lemma finite_range_const {c : β} : finite (range (λ x : α, c)) :=
(finite_singleton c).subset range_const_subset
lemma range_find_greatest_subset {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ}:
range (λ x, nat.find_greatest (P x) b) ⊆ ↑(finset.range (b + 1)) :=
by { rw range_subset_iff, assume x, simp [nat.lt_succ_iff, nat.find_greatest_le] }
lemma finite_range_find_greatest {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ} :
finite (range (λ x, nat.find_greatest (P x) b)) :=
(finset.range (b + 1)).finite_to_set.subset range_find_greatest_subset
lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) :
fintype.card s < fintype.card t :=
fintype.card_lt_of_injective_not_surjective (set.inclusion h.1) (set.inclusion_injective h.1) $
λ hst, (ssubset_iff_subset_ne.1 h).2 (eq_of_inclusion_surjective hst)
lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) :
fintype.card s ≤ fintype.card t :=
fintype.card_le_of_injective (set.inclusion hsub) (set.inclusion_injective hsub)
lemma eq_of_subset_of_card_le {s t : set α} [fintype s] [fintype t]
(hsub : s ⊆ t) (hcard : fintype.card t ≤ fintype.card s) : s = t :=
(eq_or_ssubset_of_subset hsub).elim id
(λ h, absurd hcard $ not_le_of_lt $ card_lt_card h)
lemma subset_iff_to_finset_subset (s t : set α) [fintype s] [fintype t] :
s ⊆ t ↔ s.to_finset ⊆ t.to_finset :=
⟨λ h x hx, set.mem_to_finset.mpr $ h $ set.mem_to_finset.mp hx,
λ h x hx, set.mem_to_finset.mp $ h $ set.mem_to_finset.mpr hx⟩
lemma card_range_of_injective [fintype α] {f : α → β} (hf : injective f)
[fintype (range f)] : fintype.card (range f) = fintype.card α :=
eq.symm $ fintype.card_congr $ equiv.set.range f hf
lemma finite.exists_maximal_wrt [partial_order β] (f : α → β) (s : set α) (h : set.finite s) :
s.nonempty → ∃a∈s, ∀a'∈s, f a ≤ f a' → f a = f a' :=
begin
classical,
refine h.induction_on _ _,
{ assume h, exact absurd h empty_not_nonempty },
assume a s his _ ih _,
cases s.eq_empty_or_nonempty with h h,
{ use a, simp [h] },
rcases ih h with ⟨b, hb, ih⟩,
by_cases f b ≤ f a,
{ refine ⟨a, set.mem_insert _ _, assume c hc hac, le_antisymm hac _⟩,
rcases set.mem_insert_iff.1 hc with rfl | hcs,
{ refl },
{ rwa [← ih c hcs (le_trans h hac)] } },
{ refine ⟨b, set.mem_insert_of_mem _ hb, assume c hc hbc, _⟩,
rcases set.mem_insert_iff.1 hc with rfl | hcs,
{ exact (h hbc).elim },
{ exact ih c hcs hbc } }
end
lemma finite.card_to_finset {s : set α} [fintype s] (h : s.finite) :
h.to_finset.card = fintype.card s :=
by { rw [← finset.card_attach, finset.attach_eq_univ, ← fintype.card], congr' 2, funext,
rw set.finite.mem_to_finset }
section decidable_eq
lemma to_finset_compl {α : Type*} [fintype α] [decidable_eq α]
(s : set α) [fintype (sᶜ : set α)] [fintype s] : sᶜ.to_finset = (s.to_finset)ᶜ :=
by ext; simp
lemma to_finset_inter {α : Type*} [decidable_eq α] (s t : set α) [fintype (s ∩ t : set α)]
[fintype s] [fintype t] : (s ∩ t).to_finset = s.to_finset ∩ t.to_finset :=
by ext; simp
lemma to_finset_union {α : Type*} [decidable_eq α] (s t : set α) [fintype (s ∪ t : set α)]
[fintype s] [fintype t] : (s ∪ t).to_finset = s.to_finset ∪ t.to_finset :=
by ext; simp
lemma to_finset_ne_eq_erase {α : Type*} [decidable_eq α] [fintype α] (a : α)
[fintype {x : α | x ≠ a}] : {x : α | x ≠ a}.to_finset = finset.univ.erase a :=
by ext; simp
lemma card_ne_eq [fintype α] (a : α) [fintype {x : α | x ≠ a}] :
fintype.card {x : α | x ≠ a} = fintype.card α - 1 :=
begin
haveI := classical.dec_eq α,
rw [←to_finset_card, to_finset_ne_eq_erase, finset.card_erase_of_mem (finset.mem_univ _),
finset.card_univ, nat.pred_eq_sub_one],
end
end decidable_eq
section
variables [semilattice_sup α] [nonempty α] {s : set α}
/--A finite set is bounded above.-/
protected lemma finite.bdd_above (hs : finite s) : bdd_above s :=
finite.induction_on hs bdd_above_empty $ λ a s _ _ h, h.insert a
/--A finite union of sets which are all bounded above is still bounded above.-/
lemma finite.bdd_above_bUnion {I : set β} {S : β → set α} (H : finite I) :
(bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) :=
finite.induction_on H
(by simp only [bUnion_empty, bdd_above_empty, ball_empty_iff])
(λ a s ha _ hs, by simp only [bUnion_insert, ball_insert_iff, bdd_above_union, hs])
end
section
variables [semilattice_inf α] [nonempty α] {s : set α}
/--A finite set is bounded below.-/
protected lemma finite.bdd_below (hs : finite s) : bdd_below s :=
@finite.bdd_above (order_dual α) _ _ _ hs
/--A finite union of sets which are all bounded below is still bounded below.-/
lemma finite.bdd_below_bUnion {I : set β} {S : β → set α} (H : finite I) :
(bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) :=
@finite.bdd_above_bUnion (order_dual α) _ _ _ _ _ H
end
end set
namespace finset
/-- A finset is bounded above. -/
protected lemma bdd_above [semilattice_sup α] [nonempty α] (s : finset α) :
bdd_above (↑s : set α) :=
s.finite_to_set.bdd_above
/-- A finset is bounded below. -/
protected lemma bdd_below [semilattice_inf α] [nonempty α] (s : finset α) :
bdd_below (↑s : set α) :=
s.finite_to_set.bdd_below
end finset
lemma fintype.exists_max [fintype α] [nonempty α]
{β : Type*} [linear_order β] (f : α → β) :
∃ x₀ : α, ∀ x, f x ≤ f x₀ :=
begin
rcases set.finite_univ.exists_maximal_wrt f _ univ_nonempty with ⟨x, _, hx⟩,
exact ⟨x, λ y, (le_total (f x) (f y)).elim (λ h, ge_of_eq $ hx _ trivial h) id⟩
end
|
538aa1cc55311e7e58abd4b72d693e2b3fe513cb | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/ring_theory/noetherian.lean | 0570f41bdc4a7212ad946ec4e9a93fc1424aae14 | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 38,150 | lean | /-
Copyright (c) 2018 Mario Carneiro, Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kevin Buzzard
-/
import algebraic_geometry.prime_spectrum
import data.multiset.finset_ops
import group_theory.finiteness
import linear_algebra.linear_independent
import order.compactly_generated
import order.order_iso_nat
import ring_theory.ideal.quotient
/-!
# Noetherian rings and modules
The following are equivalent for a module M over a ring R:
1. Every increasing chain of submodules M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises.
2. Every submodule is finitely generated.
A module satisfying these equivalent conditions is said to be a *Noetherian* R-module.
A ring is a *Noetherian ring* if it is Noetherian as a module over itself.
(Note that we do not assume yet that our rings are commutative,
so perhaps this should be called "left Noetherian".
To avoid cumbersome names once we specialize to the commutative case,
we don't make this explicit in the declaration names.)
## Main definitions
Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`.
* `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module.
* `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class,
implemented as the predicate that all `R`-submodules of `M` are finitely generated.
## Main statements
* `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form:
if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R
such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0.
* `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff
`>` is well-founded on `submodule R M`.
Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X],
is proved in `ring_theory.polynomial`.
## References
* [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald]
* [samuel]
## Tags
Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module
-/
open set
open_locale big_operators pointwise
namespace submodule
variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M]
/-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/
def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N
theorem fg_def {N : submodule R M} :
N.fg ↔ ∃ S : set M, finite S ∧ span R S = N :=
⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin
rintro ⟨t', h, rfl⟩,
rcases finite.exists_finset_coe h with ⟨t, rfl⟩,
exact ⟨t, rfl⟩
end⟩
lemma fg_iff_add_submonoid_fg (P : submodule ℕ M) :
P.fg ↔ P.to_add_submonoid.fg :=
⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩,
λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩⟩
lemma fg_iff_add_subgroup_fg {G : Type*} [add_comm_group G] (P : submodule ℤ G) :
P.fg ↔ P.to_add_subgroup.fg :=
⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩,
λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩⟩
lemma fg_iff_exists_fin_generating_family {N : submodule R M} :
N.fg ↔ ∃ (n : ℕ) (s : fin n → M), span R (range s) = N :=
begin
rw fg_def,
split,
{ rintros ⟨S, Sfin, hS⟩,
obtain ⟨n, f, rfl⟩ := Sfin.fin_embedding,
exact ⟨n, f, hS⟩, },
{ rintros ⟨n, s, hs⟩,
refine ⟨range s, finite_range s, hs⟩ },
end
/-- **Nakayama's Lemma**. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2,
[Stacks 00DV](https://stacks.math.columbia.edu/tag/00DV) -/
theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R]
{M : Type*} [add_comm_group M] [module R M]
(I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) :
∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) :=
begin
rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩,
have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N,
{ refine ⟨1, _, _, _⟩,
{ rw sub_self, exact I.zero_mem },
{ rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn },
{ rw [← span_le, hs], exact le_refl N } },
clear hin hs, revert this,
refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _),
{ rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn,
rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn },
apply ih, rcases H with ⟨r, hr1, hrn, hs⟩,
rw [← set.singleton_union, span_union, smul_sup] at hrn,
rw [set.insert_subset] at hs,
have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s,
{ specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn,
rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz,
rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩,
use r-c, split,
{ rw [sub_right_comm], exact I.sub_mem hr1 hci },
{ rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } },
rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩,
{ rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢,
rw [ring_hom.map_mul, hc1, hr1, mul_one] },
{ intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn,
rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz,
rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩,
change _ • _ ∈ I • span R s,
rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul],
exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) }
end
theorem fg_bot : (⊥ : submodule R M).fg :=
⟨∅, by rw [finset.coe_empty, span_empty]⟩
theorem fg_span {s : set M} (hs : finite s) : fg (span R s) :=
⟨hs.to_finset, by rw [hs.coe_to_finset]⟩
theorem fg_span_singleton (x : M) : fg (R ∙ x) :=
fg_span (finite_singleton x)
theorem fg_sup {N₁ N₂ : submodule R M}
(hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg :=
let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in
fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩
variables {P : Type*} [add_comm_monoid P] [module R P]
variables {f : M →ₗ[R] P}
theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg :=
let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩
lemma fg_of_fg_map_injective (f : M →ₗ[R] P) (hf : function.injective f) {N : submodule R M}
(hfn : (N.map f).fg) : N.fg :=
let ⟨t, ht⟩ := hfn in ⟨t.preimage f $ λ x _ y _ h, hf h,
submodule.map_injective_of_injective hf $ by { rw [f.map_span, finset.coe_preimage,
set.image_preimage_eq_inter_range, set.inter_eq_self_of_subset_left, ht],
rw [← linear_map.range_coe, ← span_le, ht, ← map_top], exact map_mono le_top }⟩
lemma fg_of_fg_map {R M P : Type*} [ring R] [add_comm_group M] [module R M]
[add_comm_group P] [module R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) {N : submodule R M}
(hfn : (N.map f).fg) : N.fg :=
fg_of_fg_map_injective f (linear_map.ker_eq_bot.1 hf) hfn
lemma fg_top (N : submodule R M) : (⊤ : submodule R N).fg ↔ N.fg :=
⟨λ h, N.range_subtype ▸ map_top N.subtype ▸ fg_map h,
λ h, fg_of_fg_map_injective N.subtype subtype.val_injective $ by rwa [map_top, range_subtype]⟩
lemma fg_of_linear_equiv (e : M ≃ₗ[R] P) (h : (⊤ : submodule R P).fg) :
(⊤ : submodule R M).fg :=
e.symm.range ▸ map_top (e.symm : P →ₗ[R] M) ▸ fg_map h
theorem fg_prod {sb : submodule R M} {sc : submodule R P}
(hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg :=
let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in
fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc,
(htb.1.image _).union (htc.1.image _),
by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩
/-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are
finitely generated then so is M. -/
theorem fg_of_fg_map_of_fg_inf_ker {R M P : Type*} [ring R] [add_comm_group M] [module R M]
[add_comm_group P] [module R P] (f : M →ₗ[R] P)
{s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg :=
begin
haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P,
cases hs1 with t1 ht1, cases hs2 with t2 ht2,
have : ∀ y ∈ t1, ∃ x ∈ s, f x = y,
{ intros y hy,
have : y ∈ map f s, { rw ← ht1, exact subset_span hy },
rcases mem_map.1 this with ⟨x, hx1, hx2⟩,
exact ⟨x, hx1, hx2⟩ },
have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y,
{ choose g hg1 hg2,
existsi λ y, if H : y ∈ t1 then g y H else 0,
intros y H, split,
{ simp only [dif_pos H], apply hg1 },
{ simp only [dif_pos H], apply hg2 } },
cases this with g hg, clear this,
existsi t1.image g ∪ t2,
rw [finset.coe_union, span_union, finset.coe_image],
apply le_antisymm,
{ refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _),
{ intros y hy, exact (hg y hy).1 },
{ intros x hx, have := subset_span hx,
rw ht2 at this,
exact this.1 } },
intros x hx,
have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ },
rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_image_iff_total] at this,
rcases this with ⟨l, hl1, hl2⟩,
refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun
((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _,
x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l),
_, add_sub_cancel'_right _ _⟩,
{ rw [← set.image_id (g '' ↑t1), finsupp.mem_span_image_iff_total], refine ⟨_, _, rfl⟩,
haveI : inhabited P := ⟨0⟩,
rw [← finsupp.lmap_domain_supported _ _ g, mem_map],
refine ⟨l, hl1, _⟩,
refl, },
rw [ht2, mem_inf], split,
{ apply s.sub_mem hx,
rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index],
refine s.sum_mem _,
{ intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 },
{ exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } },
{ rw [linear_map.mem_ker, f.map_sub, ← hl2],
rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply],
rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum],
rw sub_eq_zero,
refine finset.sum_congr rfl (λ y hy, _),
unfold id,
rw [f.map_smul, (hg y (hl1 hy)).2],
{ exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }
end
/-- The image of a finitely generated ideal is finitely generated. -/
lemma map_fg_of_fg {R S : Type*} [comm_ring R] [comm_ring S] (I : ideal R) (h : I.fg) (f : R →+* S)
: (I.map f).fg :=
begin
obtain ⟨X, hXfin, hXgen⟩ := fg_def.1 h,
apply fg_def.2,
refine ⟨set.image f X, finite.image ⇑f hXfin, _⟩,
rw [ideal.map, ideal.span, ← hXgen],
refine le_antisymm (submodule.span_mono (image_subset _ ideal.subset_span)) _,
rw [submodule.span_le, image_subset_iff],
intros i hi,
refine submodule.span_induction hi (λ x hx, _) _ (λ x y hx hy, _) (λ r x hx, _),
{ simp only [set_like.mem_coe, mem_preimage],
suffices : f x ∈ f '' X, { exact ideal.subset_span this },
exact mem_image_of_mem ⇑f hx },
{ simp only [set_like.mem_coe, ring_hom.map_zero, mem_preimage, zero_mem] },
{ simp only [set_like.mem_coe, mem_preimage] at hx hy,
simp only [ring_hom.map_add, set_like.mem_coe, mem_preimage],
exact submodule.add_mem _ hx hy },
{ simp only [set_like.mem_coe, mem_preimage] at hx,
simp only [algebra.id.smul_eq_mul, set_like.mem_coe, mem_preimage, ring_hom.map_mul],
exact submodule.smul_mem _ _ hx }
end
/-- The kernel of the composition of two linear maps is finitely generated if both kernels are and
the first morphism is surjective. -/
lemma fg_ker_comp {R M N P : Type*} [ring R] [add_comm_group M] [module R M]
[add_comm_group N] [module R N] [add_comm_group P] [module R P] (f : M →ₗ[R] N)
(g : N →ₗ[R] P) (hf1 : f.ker.fg) (hf2 : g.ker.fg) (hsur : function.surjective f) :
(g.comp f).ker.fg :=
begin
rw linear_map.ker_comp,
apply fg_of_fg_map_of_fg_inf_ker f,
{ rwa [submodule.map_comap_eq, linear_map.range_eq_top.2 hsur, top_inf_eq] },
{ rwa [inf_of_le_right (show f.ker ≤ (comap f g.ker), from comap_mono (@bot_le _ _ g.ker))] }
end
lemma fg_restrict_scalars {R S M : Type*} [comm_ring R] [comm_ring S] [algebra R S]
[add_comm_group M] [module S M] [module R M] [is_scalar_tower R S M] (N : submodule S M)
(hfin : N.fg) (h : function.surjective (algebra_map R S)) : (submodule.restrict_scalars R N).fg :=
begin
obtain ⟨X, rfl⟩ := hfin,
use X,
exact submodule.span_eq_restrict_scalars R S M X h
end
lemma fg_ker_ring_hom_comp {R S A : Type*} [comm_ring R] [comm_ring S] [comm_ring A]
(f : R →+* S) (g : S →+* A) (hf : f.ker.fg) (hg : g.ker.fg) (hsur : function.surjective f) :
(g.comp f).ker.fg :=
begin
letI : algebra R S := ring_hom.to_algebra f,
letI : algebra R A := ring_hom.to_algebra (g.comp f),
letI : algebra S A := ring_hom.to_algebra g,
letI : is_scalar_tower R S A := is_scalar_tower.of_algebra_map_eq (λ _, rfl),
let f₁ := algebra.linear_map R S,
let g₁ := (is_scalar_tower.to_alg_hom R S A).to_linear_map,
exact fg_ker_comp f₁ g₁ hf (fg_restrict_scalars g.ker hg hsur) hsur
end
/-- Finitely generated submodules are precisely compact elements in the submodule lattice. -/
theorem fg_iff_compact (s : submodule R M) : s.fg ↔ complete_lattice.is_compact_element s :=
begin
classical,
-- Introduce shorthand for span of an element
let sp : M → submodule R M := λ a, span R {a},
-- Trivial rewrite lemma; a small hack since simp (only) & rw can't accomplish this smoothly.
have supr_rw : ∀ t : finset M, (⨆ x ∈ t, sp x) = (⨆ x ∈ (↑t : set M), sp x), from λ t, by refl,
split,
{ rintro ⟨t, rfl⟩,
rw [span_eq_supr_of_singleton_spans, ←supr_rw, ←(finset.sup_eq_supr t sp)],
apply complete_lattice.finset_sup_compact_of_compact,
exact λ n _, singleton_span_is_compact_element n, },
{ intro h,
-- s is the Sup of the spans of its elements.
have sSup : s = Sup (sp '' ↑s),
by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, eq_comm, span_eq],
-- by h, s is then below (and equal to) the sup of the spans of finitely many elements.
obtain ⟨u, ⟨huspan, husup⟩⟩ := h (sp '' ↑s) (le_of_eq sSup),
have ssup : s = u.sup id,
{ suffices : u.sup id ≤ s, from le_antisymm husup this,
rw [sSup, finset.sup_id_eq_Sup], exact Sup_le_Sup huspan, },
obtain ⟨t, ⟨hts, rfl⟩⟩ := finset.subset_image_iff.mp huspan,
rw [finset.sup_finset_image, function.comp.left_id, finset.sup_eq_supr, supr_rw,
←span_eq_supr_of_singleton_spans, eq_comm] at ssup,
exact ⟨t, ssup⟩, },
end
end submodule
/--
`is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module,
implemented as the predicate that all `R`-submodules of `M` are finitely generated.
-/
class is_noetherian (R M) [semiring R] [add_comm_monoid M] [module R M] : Prop :=
(noetherian : ∀ (s : submodule R M), s.fg)
section
variables {R : Type*} {M : Type*} {P : Type*}
variables [semiring R] [add_comm_monoid M] [add_comm_monoid P]
variables [module R M] [module R P]
open is_noetherian
include R
/-- An R-module is Noetherian iff all its submodules are finitely-generated. -/
lemma is_noetherian_def : is_noetherian R M ↔ ∀ (s : submodule R M), s.fg :=
⟨λ h, h.noetherian, is_noetherian.mk⟩
theorem is_noetherian_submodule {N : submodule R M} :
is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg :=
begin
refine ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs,
submodule.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, _⟩⟩,
have f := (submodule.equiv_map_of_injective N.subtype subtype.val_injective s).symm,
have h₁ := h (s.map N.subtype) (submodule.map_subtype_le N s),
have h₂ : (⊤ : submodule R (s.map N.subtype)).map (↑f : _ →ₗ[R] s) = ⊤ := by simp,
have h₃ := @submodule.fg_map _ _ _ _ _ _ _ _ (↑f : _ →ₗ[R] s) _ ((submodule.fg_top _).2 h₁),
exact (submodule.fg_top _).1 (h₂ ▸ h₃),
end
theorem is_noetherian_submodule_left {N : submodule R M} :
is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg :=
is_noetherian_submodule.trans
⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩
theorem is_noetherian_submodule_right {N : submodule R M} :
is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg :=
is_noetherian_submodule.trans
⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩
instance is_noetherian_submodule' [is_noetherian R M] (N : submodule R M) : is_noetherian R N :=
is_noetherian_submodule.2 $ λ _ _, is_noetherian.noetherian _
lemma is_noetherian_of_le {s t : submodule R M} [ht : is_noetherian R t]
(h : s ≤ t) : is_noetherian R s :=
is_noetherian_submodule.mpr (λ s' hs', is_noetherian_submodule.mp ht _ (le_trans hs' h))
variable (M)
theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤)
[is_noetherian R M] : is_noetherian R P :=
⟨λ s, have (s.comap f).map f = s, from submodule.map_comap_eq_self $ hf.symm ▸ le_top,
this ▸ submodule.fg_map $ noetherian _⟩
variable {M}
theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P)
[is_noetherian R M] : is_noetherian R P :=
is_noetherian_of_surjective _ f.to_linear_map f.range
lemma is_noetherian_top_iff :
is_noetherian R (⊤ : submodule R M) ↔ is_noetherian R M :=
begin
unfreezingI { split; assume h },
{ exact is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) },
{ exact is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl).symm },
end
lemma is_noetherian_of_injective [is_noetherian R P] (f : M →ₗ[R] P) (hf : function.injective f) :
is_noetherian R M :=
is_noetherian_of_linear_equiv (linear_equiv.of_injective f hf).symm
lemma fg_of_injective [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P)
(hf : function.injective f) : N.fg :=
@@is_noetherian.noetherian _ _ _ (is_noetherian_of_injective f hf) N
end
section
variables {R : Type*} {M : Type*} {P : Type*}
variables [ring R] [add_comm_group M] [add_comm_group P]
variables [module R M] [module R P]
open is_noetherian
include R
lemma is_noetherian_of_ker_bot [is_noetherian R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) :
is_noetherian R M :=
is_noetherian_of_linear_equiv (linear_equiv.of_injective f $ linear_map.ker_eq_bot.mp hf).symm
lemma fg_of_ker_bot [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P) (hf : f.ker = ⊥) :
N.fg :=
@@is_noetherian.noetherian _ _ _ (is_noetherian_of_ker_bot f hf) N
instance is_noetherian_prod [is_noetherian R M]
[is_noetherian R P] : is_noetherian R (M × P) :=
⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $
have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P),
from λ x ⟨hx1, hx2⟩, ⟨x.1, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩,
submodule.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩
instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R]
[Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι]
[∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) :=
begin
haveI := classical.dec_eq ι,
suffices on_finset : ∀ s : finset ι, is_noetherian R (Π i : s, M i),
{ let coe_e := equiv.subtype_univ_equiv finset.mem_univ,
letI : is_noetherian R (Π i : finset.univ, M (coe_e i)) := on_finset finset.univ,
exact is_noetherian_of_linear_equiv (linear_equiv.Pi_congr_left R M coe_e), },
intro s,
induction s using finset.induction with a s has ih,
{ split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2,
intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 },
refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _
_ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih),
fconstructor,
{ exact λ f i, or.by_cases (finset.mem_insert.1 i.2)
(λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1))
(λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) },
{ intros f g, ext i, unfold or.by_cases, cases i with i hi,
rcases finset.mem_insert.1 hi with rfl | h,
{ change _ = _ + _, simp only [dif_pos], refl },
{ change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h },
simp only [dif_neg this, dif_pos h], refl } },
{ intros c f, ext i, unfold or.by_cases, cases i with i hi,
rcases finset.mem_insert.1 hi with rfl | h,
{ change _ = c • _, simp only [dif_pos], refl },
{ change _ = c • _, have : ¬i = a, { rintro rfl, exact has h },
simp only [dif_neg this, dif_pos h], refl } },
{ exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) },
{ intro f, apply prod.ext,
{ simp only [or.by_cases, dif_pos] },
{ ext ⟨i, his⟩,
have : ¬i = a, { rintro rfl, exact has his },
dsimp only [or.by_cases], change i ∈ s at his,
rw [dif_neg this, dif_pos his] } },
{ intro f, ext ⟨i, hi⟩,
rcases finset.mem_insert.1 hi with rfl | h,
{ simp only [or.by_cases, dif_pos], },
{ have : ¬i = a, { rintro rfl, exact has h },
simp only [or.by_cases, dif_neg this, dif_pos h], } }
end
/-- A version of `is_noetherian_pi` for non-dependent functions. We need this instance because
sometimes Lean fails to apply the dependent version in non-dependent settings (e.g., it fails to
prove that `ι → ℝ` is finite dimensional over `ℝ`). -/
instance is_noetherian_pi' {R ι M : Type*} [ring R] [add_comm_group M] [module R M] [fintype ι]
[is_noetherian R M] : is_noetherian R (ι → M) :=
is_noetherian_pi
end
open is_noetherian submodule function
section
universe w
variables {R M P : Type*} {N : Type w} [ring R] [add_comm_group M] [module R M]
[add_comm_group N] [module R N] [add_comm_group P] [module R P]
theorem is_noetherian_iff_well_founded :
is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) :=
begin
rw (complete_lattice.well_founded_characterisations $ submodule R M).out 0 3,
exact ⟨λ ⟨h⟩, λ k, (fg_iff_compact k).mp (h k), λ h, ⟨λ k, (fg_iff_compact k).mpr (h k)⟩⟩,
end
variables (R M)
lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] :
∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) :=
is_noetherian_iff_well_founded.mp
variables {R M}
lemma finite_of_linear_independent [nontrivial R] [is_noetherian R M]
{s : set M} (hs : linear_independent R (coe : s → M)) : s.finite :=
begin
refine classical.by_contradiction (λ hf, (rel_embedding.well_founded_iff_no_descending_seq.1
(well_founded_submodule_gt R M)).elim' _),
have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩,
have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s,
{ rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 },
have : ∀ a b : ℕ, a ≤ b ↔
span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}),
{ assume a b,
rw [span_le_span_iff hs (this a) (this b),
set.image_subset_image_iff (subtype.coe_injective.comp f.injective),
set.subset_def],
exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ },
exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}),
λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩,
by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩
end
/-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them.
-/
theorem set_has_maximal_iff_noetherian :
(∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔
is_noetherian R M :=
by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max']
/-- A module is Noetherian iff every increasing chain of submodules stabilizes. -/
theorem monotone_stabilizes_iff_noetherian :
(∀ (f : ℕ →ₘ submodule R M), ∃ n, ∀ m, n ≤ m → f n = f m)
↔ is_noetherian R M :=
by rw [is_noetherian_iff_well_founded, well_founded.monotone_chain_condition]
/-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/
lemma is_noetherian.induction [is_noetherian R M] {P : submodule R M → Prop}
(hgt : ∀ I, (∀ J > I, P J) → P I) (I : submodule R M) : P I :=
well_founded.recursion (well_founded_submodule_gt R M) I hgt
/-- If the first and final modules in a short exact sequence are noetherian,
then the middle module is also noetherian. -/
theorem is_noetherian_of_range_eq_ker
[is_noetherian R M] [is_noetherian R P]
(f : M →ₗ[R] N) (g : N →ₗ[R] P)
(hf : function.injective f)
(hg : function.surjective g)
(h : f.range = g.ker) :
is_noetherian R N :=
is_noetherian_iff_well_founded.2 $
well_founded_gt_exact_sequence
(well_founded_submodule_gt R M)
(well_founded_submodule_gt R P)
f.range
(submodule.map f)
(submodule.comap f)
(submodule.comap g)
(submodule.map g)
(submodule.gci_map_comap hf)
(submodule.gi_map_comap hg)
(by simp [submodule.map_comap_eq, inf_comm])
(by simp [submodule.comap_map_eq, h])
/--
For any endomorphism of a Noetherian module, there is some nontrivial iterate
with disjoint kernel and range.
-/
theorem is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot
[I : is_noetherian R M] (f : M →ₗ[R] M) : ∃ n : ℕ, n ≠ 0 ∧ (f ^ n).ker ⊓ (f ^ n).range = ⊥ :=
begin
obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I
(f.iterate_ker.comp ⟨λ n, n+1, λ n m w, by linarith⟩),
specialize w (2 * n + 1) (by linarith),
dsimp at w,
refine ⟨n+1, nat.succ_ne_zero _, _⟩,
rw eq_bot_iff,
rintros - ⟨h, ⟨y, rfl⟩⟩,
rw [mem_bot, ←linear_map.mem_ker, w],
erw linear_map.mem_ker at h ⊢,
change ((f ^ (n + 1)) * (f ^ (n + 1))) y = 0 at h,
rw ←pow_add at h,
convert h using 3,
linarith,
end
/-- Any surjective endomorphism of a Noetherian module is injective. -/
theorem is_noetherian.injective_of_surjective_endomorphism [is_noetherian R M]
(f : M →ₗ[R] M) (s : surjective f) : injective f :=
begin
obtain ⟨n, ne, w⟩ := is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot f,
rw [linear_map.range_eq_top.mpr (linear_map.iterate_surjective s n), inf_top_eq,
linear_map.ker_eq_bot] at w,
exact linear_map.injective_of_iterate_injective ne w,
end
/-- Any surjective endomorphism of a Noetherian module is bijective. -/
theorem is_noetherian.bijective_of_surjective_endomorphism [is_noetherian R M]
(f : M →ₗ[R] M) (s : surjective f) : bijective f :=
⟨is_noetherian.injective_of_surjective_endomorphism f s, s⟩
/--
A sequence `f` of submodules of a noetherian module,
with `f (n+1)` disjoint from the supremum of `f 0`, ..., `f n`,
is eventually zero.
-/
lemma is_noetherian.disjoint_partial_sups_eventually_bot [I : is_noetherian R M]
(f : ℕ → submodule R M) (h : ∀ n, disjoint (partial_sups f n) (f (n+1))) :
∃ n : ℕ, ∀ m, n ≤ m → f m = ⊥ :=
begin
-- A little off-by-one cleanup first:
suffices t : ∃ n : ℕ, ∀ m, n ≤ m → f (m+1) = ⊥,
{ obtain ⟨n, w⟩ := t,
use n+1,
rintros (_|m) p,
{ cases p, },
{ apply w,
exact nat.succ_le_succ_iff.mp p }, },
obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I (partial_sups f),
exact ⟨n, (λ m p,
eq_bot_of_disjoint_absorbs (h m) ((eq.symm (w (m + 1) (le_add_right p))).trans (w m p)))⟩
end
/--
If `M ⊕ N` embeds into `M`, for `M` noetherian over `R`, then `N` is trivial.
-/
noncomputable def is_noetherian.equiv_punit_of_prod_injective [is_noetherian R M]
(f : M × N →ₗ[R] M) (i : injective f) : N ≃ₗ[R] punit.{w+1} :=
begin
apply nonempty.some,
obtain ⟨n, w⟩ := is_noetherian.disjoint_partial_sups_eventually_bot (f.tailing i)
(f.tailings_disjoint_tailing i),
specialize w n (le_refl n),
apply nonempty.intro,
refine (f.tailing_linear_equiv i n).symm ≪≫ₗ _,
rw w,
exact submodule.bot_equiv_punit,
end
end
/--
A ring is Noetherian if it is Noetherian as a module over itself,
i.e. all its ideals are finitely generated.
-/
class is_noetherian_ring (R) [ring R] extends is_noetherian R R : Prop
theorem is_noetherian_ring_iff {R} [ring R] : is_noetherian_ring R ↔ is_noetherian R R :=
⟨λ h, h.1, @is_noetherian_ring.mk _ _⟩
/-- A commutative ring is Noetherian if and only if all its ideals are finitely-generated. -/
lemma is_noetherian_ring_iff_ideal_fg (R : Type*) [comm_ring R] :
is_noetherian_ring R ↔ ∀ I : ideal R, I.fg :=
is_noetherian_ring_iff.trans is_noetherian_def
@[priority 80] -- see Note [lower instance priority]
instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] :
is_noetherian R M :=
by letI := classical.dec; exact
⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩
theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R :=
by haveI := subsingleton_of_zero_eq_one h01;
haveI := fintype.of_subsingleton (0:R);
exact is_noetherian_ring_iff.2 (ring.is_noetherian_of_fintype R R)
theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M]
(N : submodule R M) (h : is_noetherian R M) : is_noetherian R N :=
begin
rw is_noetherian_iff_well_founded at h ⊢,
exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual h,
end
instance submodule.quotient.is_noetherian {R} [ring R] {M} [add_comm_group M] [module R M]
(N : submodule R M) [h : is_noetherian R M] : is_noetherian R N.quotient :=
begin
rw is_noetherian_iff_well_founded at h ⊢,
exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h,
end
/-- If `M / S / R` is a scalar tower, and `M / R` is Noetherian, then `M / S` is
also noetherian. -/
theorem is_noetherian_of_tower (R) {S M} [comm_ring R] [ring S]
[add_comm_group M] [algebra R S] [module S M] [module R M] [is_scalar_tower R S M]
(h : is_noetherian R M) : is_noetherian S M :=
begin
rw is_noetherian_iff_well_founded at h ⊢,
refine (submodule.restrict_scalars_embedding R S M).dual.well_founded h
end
instance ideal.quotient.is_noetherian_ring {R : Type*} [comm_ring R] [h : is_noetherian_ring R]
(I : ideal R) : is_noetherian_ring I.quotient :=
is_noetherian_ring_iff.mpr $ is_noetherian_of_tower R $ submodule.quotient.is_noetherian _
theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M]
(N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N :=
let ⟨s, hs⟩ := hN in
begin
haveI := classical.dec_eq M,
haveI := classical.dec_eq R,
letI : is_noetherian R R := by apply_instance,
have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx,
refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _ _ _)
_ _ _ is_noetherian_pi,
{ fapply linear_map.mk,
{ exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ },
{ intros f g, apply subtype.eq,
change ∑ i in s.attach, (f i + g i) • _ = _,
simp only [add_smul, finset.sum_add_distrib], refl },
{ intros c f, apply subtype.eq,
change ∑ i in s.attach, (c • f i) • _ = _,
simp only [smul_eq_mul, mul_smul],
exact finset.smul_sum.symm } },
rw linear_map.range_eq_top,
rintro ⟨n, hn⟩, change n ∈ N at hn,
rw [← hs, ← set.image_id ↑s, finsupp.mem_span_image_iff_total] at hn,
rcases hn with ⟨l, hl1, hl2⟩,
refine ⟨λ x, l x, subtype.ext _⟩,
change ∑ i in s.attach, l i • (i : M) = n,
rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2,
finsupp.total_apply, finsupp.sum, eq_comm],
refine finset.sum_subset hl1 (λ x _ hx, _),
rw [finsupp.not_mem_support_iff.1 hx, zero_smul]
end
lemma is_noetherian_of_fg_of_noetherian' {R M} [ring R] [add_comm_group M] [module R M]
[is_noetherian_ring R] (h : (⊤ : submodule R M).fg) : is_noetherian R M :=
have is_noetherian R (⊤ : submodule R M), from is_noetherian_of_fg_of_noetherian _ h,
by exactI is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl)
/-- In a module over a noetherian ring, the submodule generated by finitely many vectors is
noetherian. -/
theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M]
[is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) :=
is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩)
theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S]
(f : R →+* S) (hf : function.surjective f)
[H : is_noetherian_ring R] : is_noetherian_ring S :=
begin
rw [is_noetherian_ring_iff, is_noetherian_iff_well_founded] at H ⊢,
exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H,
end
instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S)
[is_noetherian_ring R] : is_noetherian_ring f.range :=
is_noetherian_ring_of_surjective R f.range f.range_restrict
f.range_restrict_surjective
theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S]
(f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S :=
is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective
namespace submodule
variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A]
variables (M N : submodule R A)
theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg :=
let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in
fg_def.2 ⟨m * n, hfm.mul hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩
lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg :=
nat.rec_on n
(⟨{1}, by simp [one_eq_span]⟩)
(λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih)
end submodule
section primes
variables {R : Type*} [comm_ring R] [is_noetherian_ring R]
/--In a noetherian ring, every ideal contains a product of prime ideals
([samuel, § 3.3, Lemma 3])-/
lemma exists_prime_spectrum_prod_le (I : ideal R) :
∃ (Z : multiset (prime_spectrum R)), multiset.prod (Z.map (coe : subtype _ → ideal R)) ≤ I :=
begin
refine is_noetherian.induction (λ (M : ideal R) hgt, _) I,
by_cases h_prM : M.is_prime,
{ use {⟨M, h_prM⟩},
rw [multiset.map_singleton, multiset.prod_singleton, subtype.coe_mk],
exact le_rfl },
by_cases htop : M = ⊤,
{ rw htop,
exact ⟨0, le_top⟩ },
have lt_add : ∀ z ∉ M, M < M + span R {z},
{ intros z hz,
refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _),
rw m_eq,
exact mem_sup_right (mem_span_singleton_self z) },
obtain ⟨x, hx, y, hy, hxy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left htop,
obtain ⟨Wx, h_Wx⟩ := hgt (M + span R {x}) (lt_add _ hx),
obtain ⟨Wy, h_Wy⟩ := hgt (M + span R {y}) (lt_add _ hy),
use Wx + Wy,
rw [multiset.map_add, multiset.prod_add],
apply le_trans (submodule.mul_le_mul h_Wx h_Wy),
rw add_mul,
apply sup_le (show M * (M + span R {y}) ≤ M, from ideal.mul_le_right),
rw mul_add,
apply sup_le (show span R {x} * M ≤ M, from ideal.mul_le_left),
rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem],
end
variables {A : Type*} [comm_ring A] [is_domain A] [is_noetherian_ring A]
/--In a noetherian integral domain which is not a field, every non-zero ideal contains a non-zero
product of prime ideals; in a field, the whole ring is a non-zero ideal containing only 0 as
product or prime ideals ([samuel, § 3.3, Lemma 3])
-/
lemma exists_prime_spectrum_prod_le_and_ne_bot_of_domain (h_fA : ¬ is_field A) {I : ideal A}
(h_nzI: I ≠ ⊥) :
∃ (Z : multiset (prime_spectrum A)), multiset.prod (Z.map (coe : subtype _ → ideal A)) ≤ I ∧
multiset.prod (Z.map (coe : subtype _ → ideal A)) ≠ ⊥ :=
begin
revert h_nzI,
refine is_noetherian.induction (λ (M : ideal A) hgt, _) I,
intro h_nzM,
have hA_nont : nontrivial A,
apply is_domain.to_nontrivial,
by_cases h_topM : M = ⊤,
{ rcases h_topM with rfl,
obtain ⟨p_id, h_nzp, h_pp⟩ : ∃ (p : ideal A), p ≠ ⊥ ∧ p.is_prime,
{ apply ring.not_is_field_iff_exists_prime.mp h_fA },
use [({⟨p_id, h_pp⟩} : multiset (prime_spectrum A)), le_top],
rwa [multiset.map_singleton, multiset.prod_singleton, subtype.coe_mk] },
by_cases h_prM : M.is_prime,
{ use ({⟨M, h_prM⟩} : multiset (prime_spectrum A)),
rw [multiset.map_singleton, multiset.prod_singleton, subtype.coe_mk],
exact ⟨le_rfl, h_nzM⟩ },
obtain ⟨x, hx, y, hy, h_xy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left h_topM,
have lt_add : ∀ z ∉ M, M < M + span A {z},
{ intros z hz,
refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _),
rw m_eq,
exact mem_sup_right (mem_span_singleton_self z) },
obtain ⟨Wx, h_Wx_le, h_Wx_ne⟩ := hgt (M + span A {x}) (lt_add _ hx) (ne_bot_of_gt (lt_add _ hx)),
obtain ⟨Wy, h_Wy_le, h_Wx_ne⟩ := hgt (M + span A {y}) (lt_add _ hy) (ne_bot_of_gt (lt_add _ hy)),
use Wx + Wy,
rw [multiset.map_add, multiset.prod_add],
refine ⟨le_trans (submodule.mul_le_mul h_Wx_le h_Wy_le) _, mt ideal.mul_eq_bot.mp _⟩,
{ rw add_mul,
apply sup_le (show M * (M + span A {y}) ≤ M, from ideal.mul_le_right),
rw mul_add,
apply sup_le (show span A {x} * M ≤ M, from ideal.mul_le_left),
rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem] },
{ rintro (hx | hy); contradiction },
end
end primes
|
e3389be7adcbc712ed7b2f6857c0b3c2c3439364 | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/set/intervals/image_preimage.lean | ea50eea8bbaf9e47c867b251fdfe743f5d76d939 | [
"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 | 16,812 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov, Patrick Massot
-/
import data.set.intervals.basic
import data.equiv.mul_add
import algebra.pointwise
/-!
# (Pre)images of intervals
In this file we prove a bunch of trivial lemmas like “if we add `a` to all points of `[b, c]`,
then we get `[a + b, a + c]`”. For the functions `x ↦ x ± a`, `x ↦ a ± x`, and `x ↦ -x` we prove
lemmas about preimages and images of all intervals. We also prove a few lemmas about images under
`x ↦ a * x`, `x ↦ x * a` and `x ↦ x⁻¹`.
-/
universe u
namespace set
section ordered_add_comm_group
variables {G : Type u} [ordered_add_comm_group G] (a b c : G)
/-!
### Preimages under `x ↦ a + x`
-/
@[simp] lemma preimage_const_add_Ici : (λ x, a + x) ⁻¹' (Ici b) = Ici (b - a) :=
ext $ λ x, sub_le_iff_le_add'.symm
@[simp] lemma preimage_const_add_Ioi : (λ x, a + x) ⁻¹' (Ioi b) = Ioi (b - a) :=
ext $ λ x, sub_lt_iff_lt_add'.symm
@[simp] lemma preimage_const_add_Iic : (λ x, a + x) ⁻¹' (Iic b) = Iic (b - a) :=
ext $ λ x, le_sub_iff_add_le'.symm
@[simp] lemma preimage_const_add_Iio : (λ x, a + x) ⁻¹' (Iio b) = Iio (b - a) :=
ext $ λ x, lt_sub_iff_add_lt'.symm
@[simp] lemma preimage_const_add_Icc : (λ x, a + x) ⁻¹' (Icc b c) = Icc (b - a) (c - a) :=
by simp [← Ici_inter_Iic]
@[simp] lemma preimage_const_add_Ico : (λ x, a + x) ⁻¹' (Ico b c) = Ico (b - a) (c - a) :=
by simp [← Ici_inter_Iio]
@[simp] lemma preimage_const_add_Ioc : (λ x, a + x) ⁻¹' (Ioc b c) = Ioc (b - a) (c - a) :=
by simp [← Ioi_inter_Iic]
@[simp] lemma preimage_const_add_Ioo : (λ x, a + x) ⁻¹' (Ioo b c) = Ioo (b - a) (c - a) :=
by simp [← Ioi_inter_Iio]
/-!
### Preimages under `x ↦ x + a`
-/
@[simp] lemma preimage_add_const_Ici : (λ x, x + a) ⁻¹' (Ici b) = Ici (b - a) :=
ext $ λ x, sub_le_iff_le_add.symm
@[simp] lemma preimage_add_const_Ioi : (λ x, x + a) ⁻¹' (Ioi b) = Ioi (b - a) :=
ext $ λ x, sub_lt_iff_lt_add.symm
@[simp] lemma preimage_add_const_Iic : (λ x, x + a) ⁻¹' (Iic b) = Iic (b - a) :=
ext $ λ x, le_sub_iff_add_le.symm
@[simp] lemma preimage_add_const_Iio : (λ x, x + a) ⁻¹' (Iio b) = Iio (b - a) :=
ext $ λ x, lt_sub_iff_add_lt.symm
@[simp] lemma preimage_add_const_Icc : (λ x, x + a) ⁻¹' (Icc b c) = Icc (b - a) (c - a) :=
by simp [← Ici_inter_Iic]
@[simp] lemma preimage_add_const_Ico : (λ x, x + a) ⁻¹' (Ico b c) = Ico (b - a) (c - a) :=
by simp [← Ici_inter_Iio]
@[simp] lemma preimage_add_const_Ioc : (λ x, x + a) ⁻¹' (Ioc b c) = Ioc (b - a) (c - a) :=
by simp [← Ioi_inter_Iic]
@[simp] lemma preimage_add_const_Ioo : (λ x, x + a) ⁻¹' (Ioo b c) = Ioo (b - a) (c - a) :=
by simp [← Ioi_inter_Iio]
/-!
### Preimages under `x ↦ -x`
-/
@[simp] lemma preimage_neg_Ici : - Ici a = Iic (-a) := ext $ λ x, le_neg
@[simp] lemma preimage_neg_Iic : - Iic a = Ici (-a) := ext $ λ x, neg_le
@[simp] lemma preimage_neg_Ioi : - Ioi a = Iio (-a) := ext $ λ x, lt_neg
@[simp] lemma preimage_neg_Iio : - Iio a = Ioi (-a) := ext $ λ x, neg_lt
@[simp] lemma preimage_neg_Icc : - Icc a b = Icc (-b) (-a) :=
by simp [← Ici_inter_Iic, inter_comm]
@[simp] lemma preimage_neg_Ico : - Ico a b = Ioc (-b) (-a) :=
by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, inter_comm]
@[simp] lemma preimage_neg_Ioc : - Ioc a b = Ico (-b) (-a) :=
by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm]
@[simp] lemma preimage_neg_Ioo : - Ioo a b = Ioo (-b) (-a) :=
by simp [← Ioi_inter_Iio, inter_comm]
/-!
### Preimages under `x ↦ x - a`
-/
@[simp] lemma preimage_sub_const_Ici : (λ x, x - a) ⁻¹' (Ici b) = Ici (b + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Ioi : (λ x, x - a) ⁻¹' (Ioi b) = Ioi (b + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Iic : (λ x, x - a) ⁻¹' (Iic b) = Iic (b + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Iio : (λ x, x - a) ⁻¹' (Iio b) = Iio (b + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Icc : (λ x, x - a) ⁻¹' (Icc b c) = Icc (b + a) (c + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Ico : (λ x, x - a) ⁻¹' (Ico b c) = Ico (b + a) (c + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Ioc : (λ x, x - a) ⁻¹' (Ioc b c) = Ioc (b + a) (c + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Ioo : (λ x, x - a) ⁻¹' (Ioo b c) = Ioo (b + a) (c + a) :=
by simp [sub_eq_add_neg]
/-!
### Preimages under `x ↦ a - x`
-/
@[simp] lemma preimage_const_sub_Ici : (λ x, a - x) ⁻¹' (Ici b) = Iic (a - b) :=
ext $ λ x, le_sub
@[simp] lemma preimage_const_sub_Iic : (λ x, a - x) ⁻¹' (Iic b) = Ici (a - b) :=
ext $ λ x, sub_le
@[simp] lemma preimage_const_sub_Ioi : (λ x, a - x) ⁻¹' (Ioi b) = Iio (a - b) :=
ext $ λ x, lt_sub
@[simp] lemma preimage_const_sub_Iio : (λ x, a - x) ⁻¹' (Iio b) = Ioi (a - b) :=
ext $ λ x, sub_lt
@[simp] lemma preimage_const_sub_Icc : (λ x, a - x) ⁻¹' (Icc b c) = Icc (a - c) (a - b) :=
by simp [← Ici_inter_Iic, inter_comm]
@[simp] lemma preimage_const_sub_Ico : (λ x, a - x) ⁻¹' (Ico b c) = Ioc (a - c) (a - b) :=
by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm]
@[simp] lemma preimage_const_sub_Ioc : (λ x, a - x) ⁻¹' (Ioc b c) = Ico (a - c) (a - b) :=
by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm]
@[simp] lemma preimage_const_sub_Ioo : (λ x, a - x) ⁻¹' (Ioo b c) = Ioo (a - c) (a - b) :=
by simp [← Ioi_inter_Iio, inter_comm]
/-!
### Images under `x ↦ a + x`
-/
@[simp] lemma image_const_add_Ici : (λ x, a + x) '' Ici b = Ici (a + b) :=
by simp [add_comm]
@[simp] lemma image_const_add_Iic : (λ x, a + x) '' Iic b = Iic (a + b) :=
by simp [add_comm]
@[simp] lemma image_const_add_Iio : (λ x, a + x) '' Iio b = Iio (a + b) :=
by simp [add_comm]
@[simp] lemma image_const_add_Ioi : (λ x, a + x) '' Ioi b = Ioi (a + b) :=
by simp [add_comm]
@[simp] lemma image_const_add_Icc : (λ x, a + x) '' Icc b c = Icc (a + b) (a + c) :=
by simp [add_comm]
@[simp] lemma image_const_add_Ico : (λ x, a + x) '' Ico b c = Ico (a + b) (a + c) :=
by simp [add_comm]
@[simp] lemma image_const_add_Ioc : (λ x, a + x) '' Ioc b c = Ioc (a + b) (a + c) :=
by simp [add_comm]
@[simp] lemma image_const_add_Ioo : (λ x, a + x) '' Ioo b c = Ioo (a + b) (a + c) :=
by simp [add_comm]
/-!
### Images under `x ↦ x + a`
-/
@[simp] lemma image_add_const_Ici : (λ x, x + a) '' Ici b = Ici (a + b) := by simp [add_comm]
@[simp] lemma image_add_const_Iic : (λ x, x + a) '' Iic b = Iic (a + b) := by simp [add_comm]
@[simp] lemma image_add_const_Iio : (λ x, x + a) '' Iio b = Iio (a + b) := by simp [add_comm]
@[simp] lemma image_add_const_Ioi : (λ x, x + a) '' Ioi b = Ioi (a + b) := by simp [add_comm]
@[simp] lemma image_add_const_Icc : (λ x, x + a) '' Icc b c = Icc (a + b) (a + c) :=
by simp [add_comm]
@[simp] lemma image_add_const_Ico : (λ x, x + a) '' Ico b c = Ico (a + b) (a + c) :=
by simp [add_comm]
@[simp] lemma image_add_const_Ioc : (λ x, x + a) '' Ioc b c = Ioc (a + b) (a + c) :=
by simp [add_comm]
@[simp] lemma image_add_const_Ioo : (λ x, x + a) '' Ioo b c = Ioo (a + b) (a + c) :=
by simp [add_comm]
/-!
### Images under `x ↦ -x`
-/
lemma image_neg_Ici : has_neg.neg '' (Ici a) = Iic (-a) := by simp
lemma image_neg_Iic : has_neg.neg '' (Iic a) = Ici (-a) := by simp
lemma image_neg_Ioi : has_neg.neg '' (Ioi a) = Iio (-a) := by simp
lemma image_neg_Iio : has_neg.neg '' (Iio a) = Ioi (-a) := by simp
lemma image_neg_Icc : has_neg.neg '' (Icc a b) = Icc (-b) (-a) := by simp
lemma image_neg_Ico : has_neg.neg '' (Ico a b) = Ioc (-b) (-a) := by simp
lemma image_neg_Ioc : has_neg.neg '' (Ioc a b) = Ico (-b) (-a) := by simp
lemma image_neg_Ioo : has_neg.neg '' (Ioo a b) = Ioo (-b) (-a) := by simp
/-!
### Images under `x ↦ a - x`
-/
@[simp] lemma image_const_sub_Ici : (λ x, a - x) '' Ici b = Iic (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_const_sub_Iic : (λ x, a - x) '' Iic b = Ici (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_const_sub_Ioi : (λ x, a - x) '' Ioi b = Iio (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_const_sub_Iio : (λ x, a - x) '' Iio b = Ioi (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_const_sub_Icc : (λ x, a - x) '' Icc b c = Icc (a - c) (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_const_sub_Ico : (λ x, a - x) '' Ico b c = Ioc (a - c) (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_const_sub_Ioc : (λ x, a - x) '' Ioc b c = Ico (a - c) (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_const_sub_Ioo : (λ x, a - x) '' Ioo b c = Ioo (a - c) (a - b) :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
/-!
### Images under `x ↦ x - a`
-/
@[simp] lemma image_sub_const_Ici : (λ x, x - a) '' Ici b = Ici (b - a) := by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Iic : (λ x, x - a) '' Iic b = Iic (b - a) := by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Ioi : (λ x, x - a) '' Ioi b = Ioi (b - a) := by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Iio : (λ x, x - a) '' Iio b = Iio (b - a) := by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Icc : (λ x, x - a) '' Icc b c = Icc (b - a) (c - a) :=
by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Ico : (λ x, x - a) '' Ico b c = Ico (b - a) (c - a) :=
by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Ioc : (λ x, x - a) '' Ioc b c = Ioc (b - a) (c - a) :=
by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Ioo : (λ x, x - a) '' Ioo b c = Ioo (b - a) (c - a) :=
by simp [sub_eq_neg_add]
end ordered_add_comm_group
/-!
### Multiplication and inverse in a field
-/
section linear_ordered_field
variables {k : Type u} [linear_ordered_field k]
@[simp] lemma preimage_mul_const_Iio (a : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Iio a) = Iio (a / c) :=
ext $ λ x, (lt_div_iff h).symm
@[simp] lemma preimage_mul_const_Ioi (a : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Ioi a) = Ioi (a / c) :=
ext $ λ x, (div_lt_iff h).symm
@[simp] lemma preimage_mul_const_Iic (a : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Iic a) = Iic (a / c) :=
ext $ λ x, (le_div_iff h).symm
@[simp] lemma preimage_mul_const_Ici (a : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Ici a) = Ici (a / c) :=
ext $ λ x, (div_le_iff h).symm
@[simp] lemma preimage_mul_const_Ioo (a b : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Ioo a b) = Ioo (a / c) (b / c) :=
by simp [← Ioi_inter_Iio, h]
@[simp] lemma preimage_mul_const_Ioc (a b : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Ioc a b) = Ioc (a / c) (b / c) :=
by simp [← Ioi_inter_Iic, h]
@[simp] lemma preimage_mul_const_Ico (a b : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Ico a b) = Ico (a / c) (b / c) :=
by simp [← Ici_inter_Iio, h]
@[simp] lemma preimage_mul_const_Icc (a b : k) {c : k} (h : 0 < c) :
(λ x, x * c) ⁻¹' (Icc a b) = Icc (a / c) (b / c) :=
by simp [← Ici_inter_Iic, h]
@[simp] lemma preimage_mul_const_Iio_of_neg (a : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Iio a) = Ioi (a / c) :=
ext $ λ x, (div_lt_iff_of_neg h).symm
@[simp] lemma preimage_mul_const_Ioi_of_neg (a : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Ioi a) = Iio (a / c) :=
ext $ λ x, (lt_div_iff_of_neg h).symm
@[simp] lemma preimage_mul_const_Iic_of_neg (a : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Iic a) = Ici (a / c) :=
ext $ λ x, (div_le_iff_of_neg h).symm
@[simp] lemma preimage_mul_const_Ici_of_neg (a : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Ici a) = Iic (a / c) :=
ext $ λ x, (le_div_iff_of_neg h).symm
@[simp] lemma preimage_mul_const_Ioo_of_neg (a b : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Ioo a b) = Ioo (b / c) (a / c) :=
by simp [← Ioi_inter_Iio, h, inter_comm]
@[simp] lemma preimage_mul_const_Ioc_of_neg (a b : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Ioc a b) = Ico (b / c) (a / c) :=
by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, h, inter_comm]
@[simp] lemma preimage_mul_const_Ico_of_neg (a b : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Ico a b) = Ioc (b / c) (a / c) :=
by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, h, inter_comm]
@[simp] lemma preimage_mul_const_Icc_of_neg (a b : k) {c : k} (h : c < 0) :
(λ x, x * c) ⁻¹' (Icc a b) = Icc (b / c) (a / c) :=
by simp [← Ici_inter_Iic, h, inter_comm]
@[simp] lemma preimage_const_mul_Iio (a : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Iio a) = Iio (a / c) :=
ext $ λ x, (lt_div_iff' h).symm
@[simp] lemma preimage_const_mul_Ioi (a : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Ioi a) = Ioi (a / c) :=
ext $ λ x, (div_lt_iff' h).symm
@[simp] lemma preimage_const_mul_Iic (a : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Iic a) = Iic (a / c) :=
ext $ λ x, (le_div_iff' h).symm
@[simp] lemma preimage_const_mul_Ici (a : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Ici a) = Ici (a / c) :=
ext $ λ x, (div_le_iff' h).symm
@[simp] lemma preimage_const_mul_Ioo (a b : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Ioo a b) = Ioo (a / c) (b / c) :=
by simp [← Ioi_inter_Iio, h]
@[simp] lemma preimage_const_mul_Ioc (a b : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Ioc a b) = Ioc (a / c) (b / c) :=
by simp [← Ioi_inter_Iic, h]
@[simp] lemma preimage_const_mul_Ico (a b : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Ico a b) = Ico (a / c) (b / c) :=
by simp [← Ici_inter_Iio, h]
@[simp] lemma preimage_const_mul_Icc (a b : k) {c : k} (h : 0 < c) :
((*) c) ⁻¹' (Icc a b) = Icc (a / c) (b / c) :=
by simp [← Ici_inter_Iic, h]
@[simp] lemma preimage_const_mul_Iio_of_neg (a : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Iio a) = Ioi (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Iio_of_neg a h
@[simp] lemma preimage_const_mul_Ioi_of_neg (a : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Ioi a) = Iio (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Ioi_of_neg a h
@[simp] lemma preimage_const_mul_Iic_of_neg (a : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Iic a) = Ici (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Iic_of_neg a h
@[simp] lemma preimage_const_mul_Ici_of_neg (a : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Ici a) = Iic (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Ici_of_neg a h
@[simp] lemma preimage_const_mul_Ioo_of_neg (a b : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Ioo a b) = Ioo (b / c) (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Ioo_of_neg a b h
@[simp] lemma preimage_const_mul_Ioc_of_neg (a b : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Ioc a b) = Ico (b / c) (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Ioc_of_neg a b h
@[simp] lemma preimage_const_mul_Ico_of_neg (a b : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Ico a b) = Ioc (b / c) (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Ico_of_neg a b h
@[simp] lemma preimage_const_mul_Icc_of_neg (a b : k) {c : k} (h : c < 0) :
((*) c) ⁻¹' (Icc a b) = Icc (b / c) (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Icc_of_neg a b h
lemma image_mul_right_Icc' (a b : k) {c : k} (h : 0 < c) :
(λ x, x * c) '' Icc a b = Icc (a * c) (b * c) :=
begin
refine ((units.mk0 c (ne_of_gt h)).mul_right.image_eq_preimage _).trans _,
simp [h, division_def]
end
lemma image_mul_right_Icc {a b c : k} (hab : a ≤ b) (hc : 0 ≤ c) :
(λ x, x * c) '' Icc a b = Icc (a * c) (b * c) :=
begin
cases eq_or_lt_of_le hc,
{ subst c,
simp [(nonempty_Icc.2 hab).image_const] },
exact image_mul_right_Icc' a b ‹0 < c›
end
lemma image_mul_left_Icc' {a : k} (h : 0 < a) (b c : k) :
((*) a) '' Icc b c = Icc (a * b) (a * c) :=
by { convert image_mul_right_Icc' b c h using 1; simp only [mul_comm _ a] }
lemma image_mul_left_Icc {a b c : k} (ha : 0 ≤ a) (hbc : b ≤ c) :
((*) a) '' Icc b c = Icc (a * b) (a * c) :=
by { convert image_mul_right_Icc hbc ha using 1; simp only [mul_comm _ a] }
/-- The image under `inv` of `Ioo 0 a` is `Ioi a⁻¹`. -/
lemma image_inv_Ioo_0_left {a : k} (ha : 0 < a) : has_inv.inv '' Ioo 0 a = Ioi a⁻¹ :=
begin
ext x,
split,
{ rintros ⟨y, ⟨hy0, hya⟩, hyx⟩,
exact hyx ▸ (inv_lt_inv ha hy0).2 hya },
{ exact λ h, ⟨x⁻¹, ⟨inv_pos.2 (lt_trans (inv_pos.2 ha) h),
(inv_lt ha (lt_trans (inv_pos.2 ha) h)).1 h⟩,
inv_inv' x⟩ }
end
end linear_ordered_field
end set
|
25259b87dc415055ec642b15f59949b7f97878c1 | 0c1546a496eccfb56620165cad015f88d56190c5 | /library/init/cc_lemmas.lean | 36aefa1d31592ccb34f0355e05273a6d559867a8 | [
"Apache-2.0"
] | permissive | Solertis/lean | 491e0939957486f664498fbfb02546e042699958 | 84188c5aa1673fdf37a082b2de8562dddf53df3f | refs/heads/master | 1,610,174,257,606 | 1,486,263,620,000 | 1,486,263,620,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,684 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.propext init.classical
/- Lemmas use by the congruence closure module -/
lemma iff_eq_of_eq_true_left {a b : Prop} (h : a = true) : (a ↔ b) = b :=
h^.symm ▸ propext (true_iff _)
lemma iff_eq_of_eq_true_right {a b : Prop} (h : b = true) : (a ↔ b) = a :=
h^.symm ▸ propext (iff_true _)
lemma iff_eq_true_of_eq {a b : Prop} (h : a = b) : (a ↔ b) = true :=
h ▸ propext (iff_self _)
lemma and_eq_of_eq_true_left {a b : Prop} (h : a = true) : (a ∧ b) = b :=
h^.symm ▸ propext (true_and _)
lemma and_eq_of_eq_true_right {a b : Prop} (h : b = true) : (a ∧ b) = a :=
h^.symm ▸ propext (and_true _)
lemma and_eq_of_eq_false_left {a b : Prop} (h : a = false) : (a ∧ b) = false :=
h^.symm ▸ propext (false_and _)
lemma and_eq_of_eq_false_right {a b : Prop} (h : b = false) : (a ∧ b) = false :=
h^.symm ▸ propext (and_false _)
lemma and_eq_of_eq {a b : Prop} (h : a = b) : (a ∧ b) = a :=
h ▸ propext (and_self _)
lemma or_eq_of_eq_true_left {a b : Prop} (h : a = true) : (a ∨ b) = true :=
h^.symm ▸ propext (true_or _)
lemma or_eq_of_eq_true_right {a b : Prop} (h : b = true) : (a ∨ b) = true :=
h^.symm ▸ propext (or_true _)
lemma or_eq_of_eq_false_left {a b : Prop} (h : a = false) : (a ∨ b) = b :=
h^.symm ▸ propext (false_or _)
lemma or_eq_of_eq_false_right {a b : Prop} (h : b = false) : (a ∨ b) = a :=
h^.symm ▸ propext (or_false _)
lemma or_eq_of_eq {a b : Prop} (h : a = b) : (a ∨ b) = a :=
h ▸ propext (or_self _)
lemma imp_eq_of_eq_true_left {a b : Prop} (h : a = true) : (a → b) = b :=
h^.symm ▸ propext (iff.intro (λ h, h trivial) (λ h₁ h₂, h₁))
lemma imp_eq_of_eq_true_right {a b : Prop} (h : b = true) : (a → b) = true :=
h^.symm ▸ propext (iff.intro (λ h, trivial) (λ h₁ h₂, h₁))
lemma imp_eq_of_eq_false_left {a b : Prop} (h : a = false) : (a → b) = true :=
h^.symm ▸ propext (iff.intro (λ h, trivial) (λ h₁ h₂, false.elim h₂))
lemma imp_eq_of_eq_false_right {a b : Prop} (h : b = false) : (a → b) = not a :=
h^.symm ▸ propext (iff.intro (λ h, h) (λ hna ha, hna ha))
/- Remark: the congruence closure module will only use the following lemma is
cc_config.em is tt. -/
lemma not_imp_eq_of_eq_false_right {a b : Prop} (h : b = false) : (not a → b) = a :=
h^.symm ▸ propext (iff.intro (λ h', classical.by_contradiction (λ hna, h' hna)) (λ ha hna, hna ha))
lemma imp_eq_true_of_eq {a b : Prop} (h : a = b) : (a → b) = true :=
h ▸ propext (iff.intro (λ h, trivial) (λ h ha, ha))
lemma not_eq_of_eq_true {a : Prop} (h : a = true) : (not a) = false :=
h^.symm ▸ propext not_true_iff
lemma not_eq_of_eq_false {a : Prop} (h : a = false) : (not a) = true :=
h^.symm ▸ propext not_false_iff
lemma false_of_a_eq_not_a {a : Prop} (h : a = not a) : false :=
have not a, from λ ha, absurd ha (eq.mp h ha),
absurd (eq.mpr h this) this
universe variables u
lemma if_eq_of_eq_true {c : Prop} [d : decidable c] {α : Sort u} (t e : α) (h : c = true) : (@ite c d α t e) = t :=
if_pos (of_eq_true h)
lemma if_eq_of_eq_false {c : Prop} [d : decidable c] {α : Sort u} (t e : α) (h : c = false) : (@ite c d α t e) = e :=
if_neg (not_of_eq_false h)
lemma if_eq_of_eq (c : Prop) [d : decidable c] {α : Sort u} {t e : α} (h : t = e) : (@ite c d α t e) = t :=
match d with
| (is_true hc) := rfl
| (is_false hnc) := eq.symm h
end
lemma eq_true_of_and_eq_true_left {a b : Prop} (h : (a ∧ b) = true) : a = true :=
eq_true_intro (and.left (of_eq_true h))
lemma eq_true_of_and_eq_true_right {a b : Prop} (h : (a ∧ b) = true) : b = true :=
eq_true_intro (and.right (of_eq_true h))
lemma eq_false_of_or_eq_false_left {a b : Prop} (h : (a ∨ b) = false) : a = false :=
eq_false_intro (λ ha, false.elim (eq.mp h (or.inl ha)))
lemma eq_false_of_or_eq_false_right {a b : Prop} (h : (a ∨ b) = false) : b = false :=
eq_false_intro (λ hb, false.elim (eq.mp h (or.inr hb)))
lemma eq_false_of_not_eq_true {a : Prop} (h : (not a) = true) : a = false :=
eq_false_intro (λ ha, absurd ha (eq.mpr h trivial))
/- Remark: the congruence closure module will only use the following lemma is
cc_config.em is tt. -/
lemma eq_true_of_not_eq_false {a : Prop} (h : (not a) = false) : a = true :=
eq_true_intro (classical.by_contradiction (λ hna, eq.mp h hna))
lemma ne_of_eq_of_ne {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b ≠ c) : a ≠ c :=
h₁^.symm ▸ h₂
lemma ne_of_ne_of_eq {α : Sort u} {a b c : α} (h₁ : a ≠ b) (h₂ : b = c) : a ≠ c :=
h₂ ▸ h₁
|
3dfc54d159aead411a3476d929dbf701e29394db | b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77 | /src/topology/metric_space/basic.lean | 5935739dfbbb589ac2021f0dbdf1ff3f186ac4da | [
"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 | 76,239 | lean | /-
Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Metric spaces.
Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel
Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and
topological spaces. For example:
open and closed sets, compactness, completeness, continuity and uniform continuity
-/
import topology.metric_space.emetric_space
import topology.algebra.ordered
open set filter classical topological_space
noncomputable theory
open_locale uniformity topological_space big_operators filter
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-- Construct a uniform structure from a distance function and metric space axioms -/
def uniform_space_of_dist
(dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α :=
uniform_space.of_core {
uniformity := (⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε}),
refl := le_infi $ assume ε, le_infi $
by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt},
comp := le_infi $ assume ε, le_infi $ assume h, lift'_le
(mem_infi_sets (ε / 2) $ mem_infi_sets (div_pos h zero_lt_two) (subset.refl _)) $
have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε,
from assume a b c hac hcb,
calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _
... < ε / 2 + ε / 2 : add_lt_add hac hcb
... = ε : by rw [div_add_div_same, add_self_div_two],
by simpa [comp_rel],
symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h,
tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] }
/-- The distance function (given an ambient metric space on `α`), which returns
a nonnegative real number `dist x y` given `x y : α`. -/
class has_dist (α : Type*) := (dist : α → α → ℝ)
export has_dist (dist)
-- the uniform structure and the emetric space structure are embedded in the metric space structure
-- to avoid instance diamond issues. See Note [forgetful inheritance].
/-- Metric space
Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`.
This is enforced in the type class definition, by extending the `uniform_space` structure. When
instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be
filled in by default. In the same way, each metric space induces an emetric space structure.
It is included in the structure, but filled in by default.
-/
class metric_space (α : Type u) extends has_dist α : Type u :=
(dist_self : ∀ x : α, dist x x = 0)
(eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(edist : α → α → ennreal := λx y, ennreal.of_real (dist x y))
(edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . control_laws_tac)
(to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle)
(uniformity_dist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε} . control_laws_tac)
variables [metric_space α]
@[priority 100] -- see Note [lower instance priority]
instance metric_space.to_uniform_space' : uniform_space α :=
metric_space.to_uniform_space
@[priority 200] -- see Note [lower instance priority]
instance metric_space.to_has_edist : has_edist α := ⟨metric_space.edist⟩
@[simp] theorem dist_self (x : α) : dist x x = 0 := metric_space.dist_self x
theorem eq_of_dist_eq_zero {x y : α} : dist x y = 0 → x = y :=
metric_space.eq_of_dist_eq_zero
theorem dist_comm (x y : α) : dist x y = dist y x := metric_space.dist_comm x y
theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) :=
metric_space.edist_dist x y
@[simp] theorem dist_eq_zero {x y : α} : dist x y = 0 ↔ x = y :=
iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _)
@[simp] theorem zero_eq_dist {x y : α} : 0 = dist x y ↔ x = y :=
by rw [eq_comm, dist_eq_zero]
theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z :=
metric_space.dist_triangle x y z
theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y :=
by rw dist_comm z; apply dist_triangle
theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z :=
by rw dist_comm y; apply dist_triangle
lemma dist_triangle4 (x y z w : α) :
dist x w ≤ dist x y + dist y z + dist z w :=
calc
dist x w ≤ dist x z + dist z w : dist_triangle x z w
... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (metric_space.dist_triangle x y z) _
lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) :
dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) :=
by rw [add_left_comm, dist_comm x₁, ← add_assoc]; apply dist_triangle4
lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) :
dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ :=
by rw [add_right_comm, dist_comm y₁]; apply dist_triangle4
/-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/
lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) :
dist (f m) (f n) ≤ ∑ i in finset.Ico m n, dist (f i) (f (i + 1)) :=
begin
revert n,
apply nat.le_induction,
{ simp only [finset.sum_empty, finset.Ico.self_eq_empty, dist_self] },
{ assume n hn hrec,
calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _
... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec (le_refl _)
... = ∑ i in finset.Ico m (n+1), _ :
by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp }
end
/-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/
lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) :
dist (f 0) (f n) ≤ ∑ i in finset.range n, dist (f i) (f (i + 1)) :=
finset.Ico.zero_bot n ▸ dist_le_Ico_sum_dist f (nat.zero_le n)
/-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n)
{d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i :=
le_trans (dist_le_Ico_sum_dist f hmn) $
finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2
/-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ)
{d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f 0) (f n) ≤ ∑ i in finset.range n, d i :=
finset.Ico.zero_bot n ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd)
theorem swap_dist : function.swap (@dist α _) = dist :=
by funext x y; exact dist_comm _ _
theorem abs_dist_sub_le (x y z : α) : abs (dist x z - dist y z) ≤ dist x y :=
abs_sub_le_iff.2
⟨sub_le_iff_le_add.2 (dist_triangle _ _ _),
sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩
theorem dist_nonneg {x y : α} : 0 ≤ dist x y :=
have 2 * dist x y ≥ 0,
from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul]
... ≥ 0 : by rw ← dist_self x; apply dist_triangle,
nonneg_of_mul_nonneg_left this zero_lt_two
@[simp] theorem dist_le_zero {x y : α} : dist x y ≤ 0 ↔ x = y :=
by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y
@[simp] theorem dist_pos {x y : α} : 0 < dist x y ↔ x ≠ y :=
by simpa only [not_le] using not_congr dist_le_zero
@[simp] theorem abs_dist {a b : α} : abs (dist a b) = dist a b :=
abs_of_nonneg dist_nonneg
theorem eq_of_forall_dist_le {x y : α} (h : ∀ ε > 0, dist x y ≤ ε) : x = y :=
eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h)
/-- Distance as a nonnegative real number. -/
def nndist (a b : α) : nnreal := ⟨dist a b, dist_nonneg⟩
/--Express `nndist` in terms of `edist`-/
lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal :=
by simp [nndist, edist_dist, nnreal.of_real, max_eq_left dist_nonneg, ennreal.of_real]
/--Express `edist` in terms of `nndist`-/
lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) :=
by { rw [edist_dist, nndist, ennreal.of_real_eq_coe_nnreal] }
@[simp, norm_cast] lemma ennreal_coe_nndist (x y : α) : ↑(nndist x y) = edist x y :=
(edist_nndist x y).symm
@[simp, norm_cast] lemma edist_lt_coe {x y : α} {c : nnreal} :
edist x y < c ↔ nndist x y < c :=
by rw [edist_nndist, ennreal.coe_lt_coe]
@[simp, norm_cast] lemma edist_le_coe {x y : α} {c : nnreal} :
edist x y ≤ c ↔ nndist x y ≤ c :=
by rw [edist_nndist, ennreal.coe_le_coe]
/--In a metric space, the extended distance is always finite-/
lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ :=
by rw [edist_dist x y]; apply ennreal.coe_ne_top
/--In a metric space, the extended distance is always finite-/
lemma edist_lt_top {α : Type*} [metric_space α] (x y : α) : edist x y < ⊤ :=
ennreal.lt_top_iff_ne_top.2 (edist_ne_top x y)
/--`nndist x x` vanishes-/
@[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a)
/--Express `dist` in terms of `nndist`-/
lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl
@[simp, norm_cast] lemma coe_nndist (x y : α) : ↑(nndist x y) = dist x y :=
(dist_nndist x y).symm
@[simp, norm_cast] lemma dist_lt_coe {x y : α} {c : nnreal} :
dist x y < c ↔ nndist x y < c :=
iff.rfl
@[simp, norm_cast] lemma dist_le_coe {x y : α} {c : nnreal} :
dist x y ≤ c ↔ nndist x y ≤ c :=
iff.rfl
/--Express `nndist` in terms of `dist`-/
lemma nndist_dist (x y : α) : nndist x y = nnreal.of_real (dist x y) :=
by rw [dist_nndist, nnreal.of_real_coe]
/--Deduce the equality of points with the vanishing of the nonnegative distance-/
theorem eq_of_nndist_eq_zero {x y : α} : nndist x y = 0 → x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero]
theorem nndist_comm (x y : α) : nndist x y = nndist y x :=
by simpa only [dist_nndist, nnreal.coe_eq] using dist_comm x y
/--Characterize the equality of points with the vanishing of the nonnegative distance-/
@[simp] theorem nndist_eq_zero {x y : α} : nndist x y = 0 ↔ x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero]
@[simp] theorem zero_eq_nndist {x y : α} : 0 = nndist x y ↔ x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, zero_eq_dist]
/--Triangle inequality for the nonnegative distance-/
theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z :=
by simpa [nnreal.coe_le_coe] using dist_triangle x y z
theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y :=
by simpa [nnreal.coe_le_coe] using dist_triangle_left x y z
theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z :=
by simpa [nnreal.coe_le_coe] using dist_triangle_right x y z
/--Express `dist` in terms of `edist`-/
lemma dist_edist (x y : α) : dist x y = (edist x y).to_real :=
by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)]
namespace metric
/- instantiate metric space as a topology -/
variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α}
/-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/
def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε}
@[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl
theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl
@[simp] lemma nonempty_ball (h : 0 < ε) : (ball x ε).nonempty :=
⟨x, by simp [h]⟩
lemma ball_eq_ball (ε : ℝ) (x : α) :
uniform_space.ball x {p | dist p.2 p.1 < ε} = metric.ball x ε := rfl
lemma ball_eq_ball' (ε : ℝ) (x : α) :
uniform_space.ball x {p | dist p.1 p.2 < ε} = metric.ball x ε :=
by { ext, simp [dist_comm, uniform_space.ball] }
/-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/
def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε}
/-- `sphere x ε` is the set of all points `y` with `dist y x = ε` -/
def sphere (x : α) (ε : ℝ) := {y | dist y x = ε}
@[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl
theorem mem_closed_ball' : y ∈ closed_ball x ε ↔ dist x y ≤ ε :=
by { rw dist_comm, refl }
lemma nonempty_closed_ball (h : 0 ≤ ε) : (closed_ball x ε).nonempty :=
⟨x, by simp [h]⟩
theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε :=
assume y (hy : _ < _), le_of_lt hy
theorem sphere_subset_closed_ball : sphere x ε ⊆ closed_ball x ε :=
λ y, le_of_eq
theorem sphere_disjoint_ball : disjoint (sphere x ε) (ball x ε) :=
λ y ⟨hy₁, hy₂⟩, absurd hy₁ $ ne_of_lt hy₂
@[simp] theorem ball_union_sphere : ball x ε ∪ sphere x ε = closed_ball x ε :=
set.ext $ λ y, (@le_iff_lt_or_eq ℝ _ _ _).symm
@[simp] theorem sphere_union_ball : sphere x ε ∪ ball x ε = closed_ball x ε :=
by rw [union_comm, ball_union_sphere]
@[simp] theorem closed_ball_diff_sphere : closed_ball x ε \ sphere x ε = ball x ε :=
by rw [← ball_union_sphere, set.union_diff_cancel_right sphere_disjoint_ball.symm]
@[simp] theorem closed_ball_diff_ball : closed_ball x ε \ ball x ε = sphere x ε :=
by rw [← ball_union_sphere, set.union_diff_cancel_left sphere_disjoint_ball.symm]
theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε :=
lt_of_le_of_lt dist_nonneg hy
theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε :=
show dist x x < ε, by rw dist_self; assumption
theorem mem_closed_ball_self (h : 0 ≤ ε) : x ∈ closed_ball x ε :=
show dist x x ≤ ε, by rw dist_self; assumption
theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε :=
by simp [dist_comm]
theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ :=
λ y (yx : _ < ε₁), lt_of_lt_of_le yx h
theorem closed_ball_subset_closed_ball {α : Type u} [metric_space α] {ε₁ ε₂ : ℝ} {x : α} (h : ε₁ ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball x ε₂ :=
λ y (yx : _ ≤ ε₁), le_trans yx h
theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩,
not_lt_of_le (dist_triangle_left x y z)
(lt_of_lt_of_le (add_lt_add h₁ h₂) h)
theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ :=
ball_disjoint $ by rwa [← two_mul, ← le_div_iff' (@zero_lt_two ℝ _ _)]
theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ :=
λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact
lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h)
theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε :=
ball_subset $ by rw sub_self_div_two; exact le_of_lt h
theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε :=
⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩
@[simp] theorem ball_eq_empty_iff_nonpos : ball x ε = ∅ ↔ ε ≤ 0 :=
eq_empty_iff_forall_not_mem.trans
⟨λ h, le_of_not_gt $ λ ε0, h _ $ mem_ball_self ε0,
λ ε0 y h, not_lt_of_le ε0 $ pos_of_mem_ball h⟩
@[simp] theorem closed_ball_eq_empty_iff_neg : closed_ball x ε = ∅ ↔ ε < 0 :=
eq_empty_iff_forall_not_mem.trans
⟨λ h, not_le.1 $ λ ε0, h x $ mem_closed_ball_self ε0,
λ ε0 y h, not_lt_of_le (mem_closed_ball.1 h) (lt_of_lt_of_le ε0 dist_nonneg)⟩
@[simp] lemma ball_zero : ball x 0 = ∅ :=
by rw [ball_eq_empty_iff_nonpos]
@[simp] lemma closed_ball_zero : closed_ball x 0 = {x} :=
set.ext $ λ y, dist_le_zero
theorem uniformity_basis_dist :
(𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 < ε}) :=
begin
rw ← metric_space.uniformity_dist.symm,
refine has_basis_binfi_principal _ nonempty_Ioi,
exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp,
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p),
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩
end
/-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`.
For specific bases see `uniformity_basis_dist`, `uniformity_basis_dist_inv_nat_succ`,
and `uniformity_basis_dist_inv_nat_pos`. -/
protected theorem mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ}
(hf₀ : ∀ i, p i → 0 < f i) (hf : ∀ ⦃ε⦄, 0 < ε → ∃ i (hi : p i), f i ≤ ε) :
(𝓤 α).has_basis p (λ i, {p:α×α | dist p.1 p.2 < f i}) :=
begin
refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
obtain ⟨i, hi, H⟩ : ∃ i (hi : p i), f i ≤ ε, from hf ε₀,
exact ⟨i, hi, λ x (hx : _ < _), hε $ lt_of_lt_of_le hx H⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ }
end
theorem uniformity_basis_dist_inv_nat_succ :
(𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / (↑n+1) }) :=
metric.mk_uniformity_basis (λ n _, div_pos zero_lt_one $ nat.cast_add_one_pos n)
(λ ε ε0, (exists_nat_one_div_lt ε0).imp $ λ n hn, ⟨trivial, le_of_lt hn⟩)
theorem uniformity_basis_dist_inv_nat_pos :
(𝓤 α).has_basis (λ n:ℕ, 0<n) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / ↑n }) :=
metric.mk_uniformity_basis (λ n hn, div_pos zero_lt_one $ nat.cast_pos.2 hn)
(λ ε ε0, let ⟨n, hn⟩ := exists_nat_one_div_lt ε0 in ⟨n+1, nat.succ_pos n, le_of_lt hn⟩)
/-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then closed neighborhoods of the diagonal of sizes `{f i | p i}`
form a basis of `𝓤 α`.
Currently we have only one specific basis `uniformity_basis_dist_le` based on this constructor.
More can be easily added if needed in the future. -/
protected theorem mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ}
(hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) :
(𝓤 α).has_basis p (λ x, {p:α×α | dist p.1 p.2 ≤ f x}) :=
begin
refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
rcases exists_between ε₀ with ⟨ε', hε'⟩,
rcases hf ε' hε'.1 with ⟨i, hi, H⟩,
exact ⟨i, hi, λ x (hx : _ ≤ _), hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x (hx : _ < _), H (le_of_lt hx)⟩ }
end
/-- Contant size closed neighborhoods of the diagonal form a basis
of the uniformity filter. -/
theorem uniformity_basis_dist_le :
(𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 ≤ ε}) :=
metric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩)
theorem mem_uniformity_dist {s : set (α×α)} :
s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) :=
uniformity_basis_dist.mem_uniformity_iff
/-- A constant size neighborhood of the diagonal is an entourage. -/
theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) :
{p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α :=
mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩
theorem uniform_continuous_iff [metric_space β] {f : α → β} :
uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0,
∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε :=
uniformity_basis_dist.uniform_continuous_iff uniformity_basis_dist
lemma uniform_continuous_on_iff [metric_space β] {f : α → β} {s : set α} :
uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y < δ → dist (f x) (f y) < ε :=
begin
dsimp [uniform_continuous_on],
rw (metric.uniformity_basis_dist.inf_principal (s.prod s)).tendsto_iff metric.uniformity_basis_dist,
simp only [and_imp, exists_prop, prod.forall, mem_inter_eq, gt_iff_lt, mem_set_of_eq, mem_prod],
finish,
end
theorem uniform_embedding_iff [metric_space β] {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ :=
uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl
⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0),
⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in
⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩,
λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in
⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩
/-- A map between metric spaces is a uniform embedding if and only if the distance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/
theorem uniform_embedding_iff' [metric_space β] {f : α → β} :
uniform_embedding f ↔
(∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) :=
begin
split,
{ assume h,
exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1,
(uniform_embedding_iff.1 h).2.2⟩ },
{ rintros ⟨h₁, h₂⟩,
refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩,
assume x y hxy,
have : dist x y ≤ 0,
{ refine le_of_forall_lt' (λδ δpos, _),
rcases h₂ δ δpos with ⟨ε, εpos, hε⟩,
have : dist (f x) (f y) < ε, by simpa [hxy],
exact hε this },
simpa using this }
end
theorem totally_bounded_iff {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, H _ (dist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru,
⟨t, ft, h⟩ := H ε ε0 in
⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩
/-- A metric space space is totally bounded if one can reconstruct up to any ε>0 any element of the
space from finitely many data. -/
lemma totally_bounded_of_finite_discretization {s : set α}
(H : ∀ε > (0 : ℝ), ∃ (β : Type u) [fintype β] (F : s → β),
∀x y, F x = F y → dist (x:α) y < ε) :
totally_bounded s :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ rw hs, exact totally_bounded_empty },
rcases hs with ⟨x0, hx0⟩,
haveI : inhabited s := ⟨⟨x0, hx0⟩⟩,
refine totally_bounded_iff.2 (λ ε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
resetI,
let Finv := function.inv_fun F,
refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩,
let x' := Finv (F ⟨x, xs⟩),
have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩,
simp only [set.mem_Union, set.mem_range],
exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩
end
theorem finite_approx_of_totally_bounded {s : set α} (hs : totally_bounded s) :
∀ ε > 0, ∃ t ⊆ s, finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
begin
intros ε ε_pos,
rw totally_bounded_iff_subset at hs,
exact hs _ (dist_mem_uniformity ε_pos),
end
/-- Expressing locally uniform convergence on a set using `dist`. -/
lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_locally_uniformly_on F f p s ↔
∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu x hx, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
rcases H ε εpos x hx with ⟨t, ht, Ht⟩,
exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩
end
/-- Expressing uniform convergence on a set using `dist`. -/
lemma tendsto_uniformly_on_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, dist (f x) (F n x) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx))
end
/-- Expressing locally uniform convergence using `dist`. -/
lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_locally_uniformly F f p ↔
∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε :=
by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff,
nhds_within_univ, mem_univ, forall_const, exists_prop]
/-- Expressing uniform convergence using `dist`. -/
lemma tendsto_uniformly_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, dist (f x) (F n x) < ε :=
by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp }
protected lemma cauchy_iff {f : filter α} :
cauchy f ↔ ne_bot f ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε :=
uniformity_basis_dist.cauchy_iff
theorem nhds_basis_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (ball x) :=
nhds_basis_uniformity uniformity_basis_dist
theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s :=
nhds_basis_ball.mem_iff
theorem eventually_nhds_iff {p : α → Prop} :
(∀ᶠ y in 𝓝 x, p y) ↔ ∃ε>0, ∀ ⦃y⦄, dist y x < ε → p y :=
mem_nhds_iff
lemma eventually_nhds_iff_ball {p : α → Prop} :
(∀ᶠ y in 𝓝 x, p y) ↔ ∃ ε>0, ∀ y ∈ ball x ε, p y :=
mem_nhds_iff
theorem nhds_basis_closed_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (closed_ball x) :=
nhds_basis_uniformity uniformity_basis_dist_le
theorem nhds_basis_ball_inv_nat_succ :
(𝓝 x).has_basis (λ _, true) (λ n:ℕ, ball x (1 / (↑n+1))) :=
nhds_basis_uniformity uniformity_basis_dist_inv_nat_succ
theorem nhds_basis_ball_inv_nat_pos :
(𝓝 x).has_basis (λ n, 0<n) (λ n:ℕ, ball x (1 / ↑n)) :=
nhds_basis_uniformity uniformity_basis_dist_inv_nat_pos
theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s :=
by simp only [is_open_iff_mem_nhds, mem_nhds_iff]
theorem is_open_ball : is_open (ball x ε) :=
is_open_iff.2 $ λ y, exists_ball_subset_ball
theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x :=
mem_nhds_sets is_open_ball (mem_ball_self ε0)
theorem closed_ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x :=
mem_sets_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball
theorem nhds_within_basis_ball {s : set α} :
(𝓝[s] x).has_basis (λ ε:ℝ, 0 < ε) (λ ε, ball x ε ∩ s) :=
nhds_within_has_basis nhds_basis_ball s
theorem mem_nhds_within_iff {t : set α} : s ∈ 𝓝[t] x ↔ ∃ε>0, ball x ε ∩ t ⊆ s :=
nhds_within_basis_ball.mem_iff
theorem tendsto_nhds_within_nhds_within [metric_space β] {t : set β} {f : α → β} {a b} :
tendsto f (𝓝[s] a) (𝓝[t] b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε :=
(nhds_within_basis_ball.tendsto_iff nhds_within_basis_ball).trans $
by simp only [inter_comm, mem_inter_iff, and_imp, mem_ball]
theorem tendsto_nhds_within_nhds [metric_space β] {f : α → β} {a b} :
tendsto f (𝓝[s] a) (𝓝 b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε :=
by { rw [← nhds_within_univ b, tendsto_nhds_within_nhds_within],
simp only [mem_univ, true_and] }
theorem tendsto_nhds_nhds [metric_space β] {f : α → β} {a b} :
tendsto f (𝓝 a) (𝓝 b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε :=
nhds_basis_ball.tendsto_iff nhds_basis_ball
theorem continuous_at_iff [metric_space β] {f : α → β} {a : α} :
continuous_at f a ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) (f a) < ε :=
by rw [continuous_at, tendsto_nhds_nhds]
theorem continuous_within_at_iff [metric_space β] {f : α → β} {a : α} {s : set α} :
continuous_within_at f s a ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) (f a) < ε :=
by rw [continuous_within_at, tendsto_nhds_within_nhds]
theorem continuous_on_iff [metric_space β] {f : α → β} {s : set α} :
continuous_on f s ↔
∀ (b ∈ s) (ε > 0), ∃ δ > 0, ∀a ∈ s, dist a b < δ → dist (f a) (f b) < ε :=
by simp [continuous_on, continuous_within_at_iff]
theorem continuous_iff [metric_space β] {f : α → β} :
continuous f ↔
∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds
theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, dist (u x) a < ε :=
nhds_basis_ball.tendsto_right_iff
theorem continuous_at_iff' [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔
∀ ε > 0, ∀ᶠ x in 𝓝 b, dist (f x) (f b) < ε :=
by rw [continuous_at, tendsto_nhds]
theorem continuous_within_at_iff' [topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔
∀ ε > 0, ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε :=
by rw [continuous_within_at, tendsto_nhds]
theorem continuous_on_iff' [topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔
∀ (b ∈ s) (ε > 0), ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε :=
by simp [continuous_on, continuous_within_at_iff']
theorem continuous_iff' [topological_space β] {f : β → α} :
continuous f ↔ ∀a (ε > 0), ∀ᶠ x in 𝓝 a, dist (f x) (f a) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds
theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} :
tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε :=
(at_top_basis.tendsto_iff nhds_basis_ball).trans $
by { simp only [exists_prop, true_and], refl }
end metric
open metric
@[priority 100] -- see Note [lower instance priority]
instance metric_space.to_separated : separated_space α :=
separated_def.2 $ λ x y h, eq_of_forall_dist_le $
λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0))
/-Instantiate a metric space as an emetric space. Before we can state the instance,
we need to show that the uniform structure coming from the edistance and the
distance coincide. -/
/-- Expressing the uniformity in terms of `edist` -/
protected lemma metric.uniformity_basis_edist :
(𝓤 α).has_basis (λ ε:ennreal, 0 < ε) (λ ε, {p | edist p.1 p.2 < ε}) :=
⟨begin
intro t,
refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩,
{ use [ennreal.of_real ε, ennreal.of_real_pos.2 ε0],
rintros ⟨a, b⟩,
simp only [edist_dist, ennreal.of_real_lt_of_real_iff ε0],
exact Hε },
{ rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩,
rw [ennreal.of_real_pos] at ε0',
refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩,
rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] }
end⟩
theorem metric.uniformity_edist : 𝓤 α = (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}) :=
metric.uniformity_basis_edist.eq_binfi
/-- A metric space induces an emetric space -/
@[priority 100] -- see Note [lower instance priority]
instance metric_space.to_emetric_space : emetric_space α :=
{ edist := edist,
edist_self := by simp [edist_dist],
eq_of_edist_eq_zero := assume x y h, by simpa [edist_dist] using h,
edist_comm := by simp only [edist_dist, dist_comm]; simp,
edist_triangle := assume x y z, begin
simp only [edist_dist, ← ennreal.of_real_add, dist_nonneg],
rw ennreal.of_real_le_of_real_iff _,
{ exact dist_triangle _ _ _ },
{ simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg }
end,
uniformity_edist := metric.uniformity_edist,
..‹metric_space α› }
/-- Balls defined using the distance or the edistance coincide -/
lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε :=
begin
ext y,
simp only [emetric.mem_ball, mem_ball, edist_dist],
exact ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg
end
/-- Balls defined using the distance or the edistance coincide -/
lemma metric.emetric_ball_nnreal {x : α} {ε : nnreal} : emetric.ball x ε = ball x ε :=
by { convert metric.emetric_ball, simp }
/-- Closed balls defined using the distance or the edistance coincide -/
lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) :
emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε :=
by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h
/-- Closed balls defined using the distance or the edistance coincide -/
lemma metric.emetric_closed_ball_nnreal {x : α} {ε : nnreal} :
emetric.closed_ball x ε = closed_ball x ε :=
by { convert metric.emetric_closed_ball ε.2, simp }
/-- Build a new metric space from an old one where the bundled uniform structure is provably
(but typically non-definitionaly) equal to some given uniform structure.
See Note [forgetful inheritance].
-/
def metric_space.replace_uniformity {α} [U : uniform_space α] (m : metric_space α)
(H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space') :
metric_space α :=
{ dist := @dist _ m.to_has_dist,
dist_self := dist_self,
eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _,
dist_comm := dist_comm,
dist_triangle := dist_triangle,
edist := edist,
edist_dist := edist_dist,
to_uniform_space := U,
uniformity_dist := H.trans metric_space.uniformity_dist }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the metric space and the emetric space. In this definition, the distance
is given separately, to be able to prescribe some expression which is not defeq to the push-forward
of the edistance to reals. -/
def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α]
(dist : α → α → ℝ)
(edist_ne_top : ∀x y: α, edist x y ≠ ⊤)
(h : ∀x y, dist x y = ennreal.to_real (edist x y)) :
metric_space α :=
let m : metric_space α :=
{ dist := dist,
eq_of_dist_eq_zero := λx y hxy, by simpa [h, ennreal.to_real_eq_zero_iff, edist_ne_top x y] using hxy,
dist_self := λx, by simp [h],
dist_comm := λx y, by simp [h, emetric_space.edist_comm],
dist_triangle := λx y z, begin
simp only [h],
rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _),
ennreal.to_real_le_to_real (edist_ne_top _ _)],
{ exact edist_triangle _ _ _ },
{ simp [ennreal.add_eq_top, edist_ne_top] }
end,
edist := λx y, edist x y,
edist_dist := λx y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in
m.replace_uniformity $ by { rw [uniformity_edist, metric.uniformity_edist], refl }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the metric space and the emetric space. -/
def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) :
metric_space α :=
emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl)
/-- A very useful criterion to show that a space is complete is to show that all sequences
which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are
converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to
`0`, which makes it possible to use arguments of converging series, while this is impossible
to do in general for arbitrary Cauchy sequences. -/
theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n)
(H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) :
complete_space α :=
begin
-- this follows from the same criterion in emetric spaces. We just need to translate
-- the convergence assumption from `dist` to `edist`
apply emetric.complete_of_convergent_controlled_sequences (λn, ennreal.of_real (B n)),
{ simp [hB] },
{ assume u Hu,
apply H,
assume N n m hn hm,
rw [← ennreal.of_real_lt_of_real_iff (hB N), ← edist_dist],
exact Hu N n m hn hm }
end
theorem metric.complete_of_cauchy_seq_tendsto :
(∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α :=
emetric.complete_of_cauchy_seq_tendsto
section real
/-- Instantiate the reals as a metric space. -/
instance real.metric_space : metric_space ℝ :=
{ dist := λx y, abs (x - y),
dist_self := by simp [abs_zero],
eq_of_dist_eq_zero := by simp [sub_eq_zero],
dist_comm := assume x y, abs_sub _ _,
dist_triangle := assume x y z, abs_sub_le _ _ _ }
theorem real.dist_eq (x y : ℝ) : dist x y = abs (x - y) := rfl
theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = abs x :=
by simp [real.dist_eq]
instance : order_topology ℝ :=
order_topology_of_nhds_abs $ λ x, begin
simp only [show ∀ r, {b : ℝ | abs (x - b) < r} = ball x r,
by simp [abs_sub, ball, real.dist_eq]],
apply le_antisymm,
{ simp [le_infi_iff],
exact λ ε ε0, mem_nhds_sets (is_open_ball) (mem_ball_self ε0) },
{ intros s h,
rcases mem_nhds_iff.1 h with ⟨ε, ε0, ss⟩,
exact mem_infi_sets _ (mem_infi_sets ε0 (mem_principal_sets.2 ss)) },
end
lemma closed_ball_Icc {x r : ℝ} : closed_ball x r = Icc (x-r) (x+r) :=
by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq,
abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le]
/-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the
general case. -/
lemma squeeze_zero' {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀ᶠ t in t₀, 0 ≤ f t)
(hft : ∀ᶠ t in t₀, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (𝓝 0) :=
tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds g0 hf hft
/-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le`
and `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/
lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t)
(g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) :=
squeeze_zero' (eventually_of_forall hf) (eventually_of_forall hft) g0
theorem metric.uniformity_eq_comap_nhds_zero :
𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) :=
by { ext s,
simp [mem_uniformity_dist, (nhds_basis_ball.comap _).mem_iff, subset_def, real.dist_0_eq_abs] }
lemma cauchy_seq_iff_tendsto_dist_at_top_0 [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) :=
by rw [cauchy_seq_iff_tendsto, metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff,
prod.map_def]
lemma tendsto_uniformity_iff_dist_tendsto_zero {ι : Type*} {f : ι → α × α} {p : filter ι} :
tendsto f p (𝓤 α) ↔ tendsto (λ x, dist (f x).1 (f x).2) p (𝓝 0) :=
by rw [metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff]
lemma filter.tendsto.congr_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α}
(h₁ : tendsto f₁ p (𝓝 a)) (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) :
tendsto f₂ p (𝓝 a) :=
h₁.congr_uniformity $ tendsto_uniformity_iff_dist_tendsto_zero.2 h
alias filter.tendsto.congr_dist ← tendsto_of_tendsto_of_dist
lemma tendsto_iff_of_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α}
(h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) :
tendsto f₁ p (𝓝 a) ↔ tendsto f₂ p (𝓝 a) :=
uniform.tendsto_congr $ tendsto_uniformity_iff_dist_tendsto_zero.2 h
end real
section cauchy_seq
variables [nonempty β] [semilattice_sup β]
/-- In a metric space, Cauchy sequences are characterized by the fact that, eventually,
the distance between its elements is arbitrarily small -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem metric.cauchy_seq_iff {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε :=
uniformity_basis_dist.cauchy_seq_iff
/-- A variation around the metric characterization of Cauchy sequences -/
theorem metric.cauchy_seq_iff' {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε :=
uniformity_basis_dist.cauchy_seq_iff'
/-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N`
and `b` converges to zero, then `s` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ)
(h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (nhds 0)) :
cauchy_seq s :=
metric.cauchy_seq_iff.2 $ λ ε ε0,
(metric.tendsto_at_top.1 h₀ ε ε0).imp $ λ N hN m n hm hn,
calc dist (s m) (s n) ≤ b N : h m n N hm hn
... ≤ abs (b N) : le_abs_self _
... = dist (b N) 0 : by rw real.dist_0_eq_abs; refl
... < ε : (hN _ (le_refl N))
/-- A Cauchy sequence on the natural numbers is bounded. -/
theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) :
∃ R > 0, ∀ m n, dist (u m) (u n) < R :=
begin
rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩,
suffices : ∃ R > 0, ∀ n, dist (u n) (u N) < R,
{ rcases this with ⟨R, R0, H⟩,
exact ⟨_, add_pos R0 R0, λ m n,
lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ },
let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)),
refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩,
cases le_or_lt N n,
{ exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) },
{ have : _ ≤ R := finset.le_sup (finset.mem_range.2 h),
exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) }
end
/-- Yet another metric characterization of Cauchy sequences on integers. This one is often the
most efficient. -/
lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ,
(∀ n, 0 ≤ b n) ∧
(∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧
tendsto b at_top (𝓝 0) :=
⟨λ hs, begin
/- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking
the supremum of the distances between `s n` and `s m` for `n m ≥ N`.
First, we prove that all these distances are bounded, as otherwise the Sup
would not make sense. -/
let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N},
have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x,
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩,
exact le_of_lt (hR m n) },
have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))),
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) },
-- Prove that it bounds the distances of points in the Cauchy sequence
have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ Sup (S N) :=
λ m n N hm hn, real.le_Sup _ (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩,
have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_refl _, le_refl _⟩, dist_self _⟩,
have S0 := λ n, real.le_Sup _ (hS n) (S0m n),
-- Prove that it tends to `0`, by using the Cauchy property of `s`
refine ⟨λ N, Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩,
refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _),
rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)],
refine lt_of_le_of_lt (real.Sup_le_ub _ ⟨_, S0m _⟩ _) (half_lt_self ε0),
rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩,
exact le_of_lt (hN _ _ (le_trans hn hm') (le_trans hn hn'))
end,
λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩
end cauchy_seq
/-- Metric space structure pulled back by an injective function. Injectivity is necessary to
ensure that `dist x y = 0` only if `x = y`. -/
def metric_space.induced {α β} (f : α → β) (hf : function.injective f)
(m : metric_space β) : metric_space α :=
{ dist := λ x y, dist (f x) (f y),
dist_self := λ x, dist_self _,
eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h),
dist_comm := λ x y, dist_comm _ _,
dist_triangle := λ x y z, dist_triangle _ _ _,
edist := λ x y, edist (f x) (f y),
edist_dist := λ x y, edist_dist _ _,
to_uniform_space := uniform_space.comap f m.to_uniform_space,
uniformity_dist := begin
apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)),
refine λ s, mem_comap_sets.trans _,
split; intro H,
{ rcases H with ⟨r, ru, rs⟩,
rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩,
refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h },
{ rcases H with ⟨ε, ε0, hε⟩,
exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ }
end }
instance subtype.metric_space {α : Type*} {p : α → Prop} [t : metric_space α] :
metric_space (subtype p) :=
metric_space.induced coe (λ x y, subtype.ext) t
theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl
section nnreal
instance : metric_space nnreal := by unfold nnreal; apply_instance
lemma nnreal.dist_eq (a b : nnreal) : dist a b = abs ((a:ℝ) - b) := rfl
lemma nnreal.nndist_eq (a b : nnreal) :
nndist a b = max (a - b) (b - a) :=
begin
wlog h : a ≤ b,
{ apply nnreal.coe_eq.1,
rw [nnreal.sub_eq_zero h, max_eq_right (zero_le $ b - a), ← dist_nndist, nnreal.dist_eq,
nnreal.coe_sub h, abs, neg_sub],
apply max_eq_right,
linarith [nnreal.coe_le_coe.2 h] },
rwa [nndist_comm, max_comm]
end
end nnreal
section prod
instance prod.metric_space_max [metric_space β] : metric_space (α × β) :=
{ dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2),
dist_self := λ x, by simp,
eq_of_dist_eq_zero := λ x y h, begin
cases max_le_iff.1 (le_of_eq h) with h₁ h₂,
exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩
end,
dist_comm := λ x y, by simp [dist_comm],
dist_triangle := λ x y z, max_le
(le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _)))
(le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))),
edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2),
edist_dist := assume x y, begin
have : monotone ennreal.of_real := assume x y h, ennreal.of_real_le_of_real h,
rw [edist_dist, edist_dist, ← this.map_max]
end,
uniformity_dist := begin
refine uniformity_prod.trans _,
simp only [uniformity_basis_dist.eq_binfi, comap_infi],
rw ← infi_inf_eq, congr, funext,
rw ← infi_inf_eq, congr, funext,
simp [inf_principal, ext_iff, max_lt_iff]
end,
to_uniform_space := prod.uniform_space }
lemma prod.dist_eq [metric_space β] {x y : α × β} :
dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl
end prod
theorem uniform_continuous_dist : uniform_continuous (λp:α×α, dist p.1 p.2) :=
metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0,
begin
suffices,
{ intros p q h, cases p with p₁ p₂, cases q with q₁ q₂,
cases max_lt_iff.1 h with h₁ h₂, clear h,
dsimp at h₁ h₂ ⊢,
rw real.dist_eq,
refine abs_sub_lt_iff.2 ⟨_, _⟩,
{ revert p₁ p₂ q₁ q₂ h₁ h₂, exact this },
{ apply this; rwa dist_comm } },
intros p₁ p₂ q₁ q₂ h₁ h₂,
have := add_lt_add
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1,
rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this
end⟩)
theorem uniform_continuous.dist [uniform_space β] {f g : β → α}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
uniform_continuous (λb, dist (f b) (g b)) :=
uniform_continuous_dist.comp (hf.prod_mk hg)
theorem continuous_dist : continuous (λp:α×α, dist p.1 p.2) :=
uniform_continuous_dist.continuous
theorem continuous.dist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) :=
continuous_dist.comp (hf.prod_mk hg : _)
theorem filter.tendsto.dist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) :=
(continuous_dist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a :=
by simp only [@nhds_eq_comap_uniformity α, metric.uniformity_eq_comap_nhds_zero,
comap_comap, (∘), dist_comm]
lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} :
(tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) :=
by rw [← nhds_comap_dist a, tendsto_comap_iff]
lemma uniform_continuous_nndist : uniform_continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_subtype_mk uniform_continuous_dist _
lemma uniform_continuous.nndist [uniform_space β] {f g : β → α} (hf : uniform_continuous f)
(hg : uniform_continuous g) :
uniform_continuous (λ b, nndist (f b) (g b)) :=
uniform_continuous_nndist.comp (hf.prod_mk hg)
lemma continuous_nndist : continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_nndist.continuous
lemma continuous.nndist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) :=
continuous_nndist.comp (hf.prod_mk hg : _)
theorem filter.tendsto.nndist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, nndist (f x) (g x)) x (𝓝 (nndist a b)) :=
(continuous_nndist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
namespace metric
variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α}
theorem is_closed_ball : is_closed (closed_ball x ε) :=
is_closed_le (continuous_id.dist continuous_const) continuous_const
lemma is_closed_sphere : is_closed (sphere x ε) :=
is_closed_eq (continuous_id.dist continuous_const) continuous_const
@[simp] theorem closure_closed_ball : closure (closed_ball x ε) = closed_ball x ε :=
is_closed_ball.closure_eq
theorem closure_ball_subset_closed_ball : closure (ball x ε) ⊆ closed_ball x ε :=
closure_minimal ball_subset_closed_ball is_closed_ball
theorem frontier_ball_subset_sphere : frontier (ball x ε) ⊆ sphere x ε :=
frontier_lt_subset_eq (continuous_id.dist continuous_const) continuous_const
theorem frontier_closed_ball_subset_sphere : frontier (closed_ball x ε) ⊆ sphere x ε :=
frontier_le_subset_eq (continuous_id.dist continuous_const) continuous_const
theorem ball_subset_interior_closed_ball : ball x ε ⊆ interior (closed_ball x ε) :=
interior_maximal ball_subset_closed_ball is_open_ball
/-- ε-characterization of the closure in metric spaces-/
theorem mem_closure_iff {α : Type u} [metric_space α] {s : set α} {a : α} :
a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
(mem_closure_iff_nhds_basis nhds_basis_ball).trans $
by simp only [mem_ball, dist_comm]
lemma mem_closure_range_iff {α : Type u} [metric_space α] {e : β → α} {a : α} :
a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε :=
by simp only [mem_closure_iff, exists_range_iff]
lemma mem_closure_range_iff_nat {α : Type u} [metric_space α] {e : β → α} {a : α} :
a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) :=
(mem_closure_iff_nhds_basis nhds_basis_ball_inv_nat_succ).trans $
by simp only [mem_ball, dist_comm, exists_range_iff, forall_const]
theorem mem_of_closed' {α : Type u} [metric_space α] {s : set α} (hs : is_closed s)
{a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
by simpa only [hs.closure_eq] using @mem_closure_iff _ _ s a
end metric
section pi
open finset
variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)]
/-- A finite product of metric spaces is a metric space, with the sup distance. -/
instance metric_space_pi : metric_space (Πb, π b) :=
begin
/- we construct the instance from the emetric space instance to avoid checking again that the
uniformity is the same as the product uniformity, but we register nevertheless a nice formula
for the distance -/
refine emetric_space.to_metric_space_of_dist
(λf g, ((sup univ (λb, nndist (f b) (g b)) : nnreal) : ℝ)) _ _,
show ∀ (x y : Π (b : β), π b), edist x y ≠ ⊤,
{ assume x y,
rw ← lt_top_iff_ne_top,
have : (⊥ : ennreal) < ⊤ := ennreal.coe_lt_top,
simp [edist_pi_def, finset.sup_lt_iff this, edist_lt_top] },
show ∀ (x y : Π (b : β), π b), ↑(sup univ (λ (b : β), nndist (x b) (y b))) =
ennreal.to_real (sup univ (λ (b : β), edist (x b) (y b))),
{ assume x y,
simp only [edist_nndist],
norm_cast }
end
lemma nndist_pi_def (f g : Πb, π b) : nndist f g = sup univ (λb, nndist (f b) (g b)) :=
subtype.eta _ _
lemma dist_pi_def (f g : Πb, π b) :
dist f g = (sup univ (λb, nndist (f b) (g b)) : nnreal) := rfl
lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) :
dist f g < r ↔ ∀b, dist (f b) (g b) < r :=
begin
lift r to nnreal using hr.le,
simp [dist_pi_def, finset.sup_lt_iff (show ⊥ < r, from hr)],
end
lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) :
dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r :=
begin
lift r to nnreal using hr,
simp [nndist_pi_def]
end
lemma nndist_le_pi_nndist (f g : Πb, π b) (b : β) : nndist (f b) (g b) ≤ nndist f g :=
by { rw [nndist_pi_def], exact finset.le_sup (finset.mem_univ b) }
lemma dist_le_pi_dist (f g : Πb, π b) (b : β) : dist (f b) (g b) ≤ dist f g :=
by simp only [dist_nndist, nnreal.coe_le_coe, nndist_le_pi_nndist f g b]
/-- An open ball in a product space is a product of open balls. The assumption `0 < r`
is necessary for the case of the empty product. -/
lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) :
ball x r = { y | ∀b, y b ∈ ball (x b) r } :=
by { ext p, simp [dist_pi_lt_iff hr] }
/-- A closed ball in a product space is a product of closed balls. The assumption `0 ≤ r`
is necessary for the case of the empty product. -/
lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) :
closed_ball x r = { y | ∀b, y b ∈ closed_ball (x b) r } :=
by { ext p, simp [dist_pi_le_iff hr] }
end pi
section compact
/-- Any compact set in a metric space can be covered by finitely many balls of a given positive
radius -/
lemma finite_cover_balls_of_compact {α : Type u} [metric_space α] {s : set α}
(hs : is_compact s) {e : ℝ} (he : 0 < e) :
∃t ⊆ s, finite t ∧ s ⊆ ⋃x∈t, ball x e :=
begin
apply hs.elim_finite_subcover_image,
{ simp [is_open_ball] },
{ intros x xs,
simp,
exact ⟨x, ⟨xs, by simpa⟩⟩ }
end
alias finite_cover_balls_of_compact ← is_compact.finite_cover_balls
end compact
section proper_space
open metric
/-- A metric space is proper if all closed balls are compact. -/
class proper_space (α : Type u) [metric_space α] : Prop :=
(compact_ball : ∀x:α, ∀r, is_compact (closed_ball x r))
lemma tendsto_dist_right_cocompact_at_top [proper_space α] (x : α) :
tendsto (λ y, dist y x) (cocompact α) at_top :=
(has_basis_cocompact.tendsto_iff at_top_basis).2 $ λ r hr,
⟨closed_ball x r, proper_space.compact_ball x r, λ y hy, (not_le.1 $ mt mem_closed_ball.2 hy).le⟩
lemma tendsto_dist_left_cocompact_at_top [proper_space α] (x : α) :
tendsto (dist x) (cocompact α) at_top :=
by simpa only [dist_comm] using tendsto_dist_right_cocompact_at_top x
/-- If all closed balls of large enough radius are compact, then the space is proper. Especially
useful when the lower bound for the radius is 0. -/
lemma proper_space_of_compact_closed_ball_of_le
(R : ℝ) (h : ∀x:α, ∀r, R ≤ r → is_compact (closed_ball x r)) :
proper_space α :=
⟨begin
assume x r,
by_cases hr : R ≤ r,
{ exact h x r hr },
{ have : closed_ball x r = closed_ball x R ∩ closed_ball x r,
{ symmetry,
apply inter_eq_self_of_subset_right,
exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) },
rw this,
exact (h x R (le_refl _)).inter_right is_closed_ball }
end⟩
/- A compact metric space is proper -/
@[priority 100] -- see Note [lower instance priority]
instance proper_of_compact [compact_space α] : proper_space α :=
⟨assume x r, is_closed_ball.compact⟩
/-- A proper space is locally compact -/
@[priority 100] -- see Note [lower instance priority]
instance locally_compact_of_proper [proper_space α] :
locally_compact_space α :=
begin
apply locally_compact_of_compact_nhds,
intros x,
existsi closed_ball x 1,
split,
{ apply mem_nhds_iff.2,
existsi (1 : ℝ),
simp,
exact ⟨zero_lt_one, ball_subset_closed_ball⟩ },
{ apply proper_space.compact_ball }
end
/-- A proper space is complete -/
@[priority 100] -- see Note [lower instance priority]
instance complete_of_proper [proper_space α] : complete_space α :=
⟨begin
intros f hf,
/- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed
ball (therefore compact by properness) where it is nontrivial. -/
have A : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 := (metric.cauchy_iff.1 hf).2 1 zero_lt_one,
rcases A with ⟨t, ⟨t_fset, ht⟩⟩,
rcases hf.1.nonempty_of_mem t_fset with ⟨x, xt⟩,
have : t ⊆ closed_ball x 1 := by intros y yt; simp [dist_comm]; apply le_of_lt (ht x y xt yt),
have : closed_ball x 1 ∈ f := f.sets_of_superset t_fset this,
rcases (compact_iff_totally_bounded_complete.1 (proper_space.compact_ball x 1)).2 f hf (le_principal_iff.2 this)
with ⟨y, _, hy⟩,
exact ⟨y, hy⟩
end⟩
/-- A proper metric space is separable, and therefore second countable. Indeed, any ball is
compact, and therefore admits a countable dense subset. Taking a countable union over the balls
centered at a fixed point and with integer radius, one obtains a countable set which is
dense in the whole space. -/
@[priority 100] -- see Note [lower instance priority]
instance second_countable_of_proper [proper_space α] :
second_countable_topology α :=
begin
/- It suffices to show that `α` admits a countable dense subset. -/
suffices : separable_space α,
{ resetI, apply emetric.second_countable_of_separable },
constructor,
/- We show that the space admits a countable dense subset. The case where the space is empty
is special, and trivial. -/
rcases _root_.em (nonempty α) with (⟨⟨x⟩⟩|hα), swap,
{ exact ⟨∅, countable_empty, λ x, (hα ⟨x⟩).elim⟩ },
/- When the space is not empty, we take a point `x` in the space, and then a countable set
`T r` which is dense in the closed ball `closed_ball x r` for each `r`. Then the set
`t = ⋃ T n` (where the union is over all integers `n`) is countable, as a countable union
of countable sets, and dense in the space by construction. -/
choose T T_sub T_count T_closure using
show ∀ (r:ℝ), ∃ t ⊆ closed_ball x r, (countable (t : set α) ∧ closed_ball x r = closure t),
from assume r, emetric.countable_closure_of_compact (proper_space.compact_ball _ _),
use [⋃n:ℕ, T (n : ℝ), countable_Union (λ n, T_count n)],
intro y,
rcases exists_nat_gt (dist y x) with ⟨n, n_large⟩,
have h : y ∈ closed_ball x (n : ℝ) := n_large.le,
rw [T_closure] at h,
exact closure_mono (subset_Union _ _) h
end
/-- A finite product of proper spaces is proper. -/
instance pi_proper_space {π : β → Type*} [fintype β] [∀b, metric_space (π b)]
[h : ∀b, proper_space (π b)] : proper_space (Πb, π b) :=
begin
refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _),
rw closed_ball_pi _ hr,
apply compact_pi_infinite (λb, _),
apply (h b).compact_ball
end
end proper_space
namespace metric
section second_countable
open topological_space
/-- A metric space is second countable if, for every `ε > 0`, there is a countable set which is
`ε`-dense. -/
lemma second_countable_of_almost_dense_set
(H : ∀ε > (0 : ℝ), ∃ s : set α, countable s ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) :
second_countable_topology α :=
begin
choose T T_dense using H,
have I1 : ∀n:ℕ, (n:ℝ) + 1 > 0 :=
λn, lt_of_lt_of_le zero_lt_one (le_add_of_nonneg_left (nat.cast_nonneg _)),
have I : ∀n:ℕ, (n+1 : ℝ)⁻¹ > 0 := λn, inv_pos.2 (I1 n),
let t := ⋃n:ℕ, T (n+1)⁻¹ (I n),
have count_t : countable t := by finish [countable_Union],
have dense_t : dense t,
{ refine (λx, mem_closure_iff.2 (λε εpos, _)),
rcases exists_nat_gt ε⁻¹ with ⟨n, hn⟩,
have : ε⁻¹ < n + 1 := lt_of_lt_of_le hn (le_add_of_nonneg_right zero_le_one),
have nε : ((n:ℝ)+1)⁻¹ < ε := (inv_lt (I1 n) εpos).2 this,
rcases (T_dense (n+1)⁻¹ (I n)).2 x with ⟨y, yT, Dxy⟩,
have : y ∈ t := mem_of_mem_of_subset yT (by apply subset_Union (λ (n:ℕ), T (n+1)⁻¹ (I n))),
exact ⟨y, this, lt_of_le_of_lt Dxy nε⟩ },
haveI : separable_space α := ⟨⟨t, ⟨count_t, dense_t⟩⟩⟩,
exact emetric.second_countable_of_separable α
end
/-- A metric space space is second countable if one can reconstruct up to any `ε>0` any element of
the space from countably many data. -/
lemma second_countable_of_countable_discretization {α : Type u} [metric_space α]
(H : ∀ε > (0 : ℝ), ∃ (β : Type*) [encodable β] (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) :
second_countable_topology α :=
begin
cases (univ : set α).eq_empty_or_nonempty with hs hs,
{ haveI : compact_space α := ⟨by rw hs; exact compact_empty⟩, by apply_instance },
rcases hs with ⟨x0, hx0⟩,
letI : inhabited α := ⟨x0⟩,
refine second_countable_of_almost_dense_set (λε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
resetI,
let Finv := function.inv_fun F,
refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩,
let x' := Finv (F x),
have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩,
exact ⟨x', mem_range_self _, hF _ _ this.symm⟩
end
end second_countable
end metric
lemma lebesgue_number_lemma_of_metric
{s : set α} {ι} {c : ι → set α} (hs : is_compact s)
(hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) :
∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i :=
let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂,
⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in
⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in
⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩
lemma lebesgue_number_lemma_of_metric_sUnion
{s : set α} {c : set (set α)} (hs : is_compact s)
(hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) :
∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t :=
by rw sUnion_eq_Union at hc₂;
simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂
namespace metric
/-- Boundedness of a subset of a metric space. We formulate the definition to work
even in the empty space. -/
def bounded (s : set α) : Prop :=
∃C, ∀x y ∈ s, dist x y ≤ C
section bounded
variables {x : α} {s t : set α} {r : ℝ}
@[simp] lemma bounded_empty : bounded (∅ : set α) :=
⟨0, by simp⟩
lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s :=
⟨λ h _ _, h, λ H,
s.eq_empty_or_nonempty.elim
(λ hs, hs.symm ▸ bounded_empty)
(λ ⟨x, hx⟩, H x hx)⟩
/-- Subsets of a bounded set are also bounded -/
lemma bounded.subset (incl : s ⊆ t) : bounded t → bounded s :=
Exists.imp $ λ C hC x y hx hy, hC x y (incl hx) (incl hy)
/-- Closed balls are bounded -/
lemma bounded_closed_ball : bounded (closed_ball x r) :=
⟨r + r, λ y z hy hz, begin
simp only [mem_closed_ball] at *,
calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add hy hz
end⟩
/-- Open balls are bounded -/
lemma bounded_ball : bounded (ball x r) :=
bounded_closed_ball.subset ball_subset_closed_ball
/-- Given a point, a bounded subset is included in some ball around this point -/
lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r :=
begin
split; rintro ⟨C, hC⟩,
{ cases s.eq_empty_or_nonempty with h h,
{ subst s, exact ⟨0, by simp⟩ },
{ rcases h with ⟨x, hx⟩,
exact ⟨C + dist x c, λ y hy, calc
dist y c ≤ dist y x + dist x c : dist_triangle _ _ _
... ≤ C + dist x c : add_le_add_right (hC y x hy hx) _⟩ } },
{ exact bounded_closed_ball.subset hC }
end
lemma bounded_closure_of_bounded (h : bounded s) : bounded (closure s) :=
begin
cases h with C h,
replace h : ∀ p : α × α, p ∈ set.prod s s → dist p.1 p.2 ∈ { d | d ≤ C },
{ rintros ⟨x, y⟩ ⟨x_in, y_in⟩,
exact h x y x_in y_in },
use C,
suffices : ∀ p : α × α, p ∈ closure (set.prod s s) → dist p.1 p.2 ∈ { d | d ≤ C },
{ rw closure_prod_eq at this,
intros x y x_in y_in,
exact this (x, y) (mk_mem_prod x_in y_in) },
intros p p_in,
have := map_mem_closure continuous_dist p_in h,
rwa (is_closed_le' C).closure_eq at this
end
alias bounded_closure_of_bounded ← bounded.closure
/-- The union of two bounded sets is bounded iff each of the sets is bounded -/
@[simp] lemma bounded_union :
bounded (s ∪ t) ↔ bounded s ∧ bounded t :=
⟨λh, ⟨h.subset (by simp), h.subset (by simp)⟩,
begin
rintro ⟨hs, ht⟩,
refine bounded_iff_mem_bounded.2 (λ x _, _),
rw bounded_iff_subset_ball x at hs ht ⊢,
rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩,
exact ⟨max Cs Ct, union_subset
(subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _)
(subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩,
end⟩
/-- A finite union of bounded sets is bounded -/
lemma bounded_bUnion {I : set β} {s : β → set α} (H : finite I) :
bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) :=
finite.induction_on H (by simp) $ λ x I _ _ IH,
by simp [or_imp_distrib, forall_and_distrib, IH]
/-- A compact set is bounded -/
lemma bounded_of_compact {s : set α} (h : is_compact s) : bounded s :=
-- We cover the compact set by finitely many balls of radius 1,
-- and then argue that a finite union of bounded sets is bounded
let ⟨t, ht, fint, subs⟩ := finite_cover_balls_of_compact h zero_lt_one in
bounded.subset subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball
alias bounded_of_compact ← is_compact.bounded
/-- A finite set is bounded -/
lemma bounded_of_finite {s : set α} (h : finite s) : bounded s :=
h.is_compact.bounded
/-- A singleton is bounded -/
lemma bounded_singleton {x : α} : bounded ({x} : set α) :=
bounded_of_finite $ finite_singleton _
/-- Characterization of the boundedness of the range of a function -/
lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C :=
exists_congr $ λ C, ⟨
λ H x y, H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩,
by rintro H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩; exact H x y⟩
/-- In a compact space, all sets are bounded -/
lemma bounded_of_compact_space [compact_space α] : bounded s :=
compact_univ.bounded.subset (subset_univ _)
/-- The Heine–Borel theorem:
In a proper space, a set is compact if and only if it is closed and bounded -/
lemma compact_iff_closed_bounded [proper_space α] :
is_compact s ↔ is_closed s ∧ bounded s :=
⟨λ h, ⟨h.is_closed, h.bounded⟩, begin
rintro ⟨hc, hb⟩,
cases s.eq_empty_or_nonempty with h h, {simp [h, compact_empty]},
rcases h with ⟨x, hx⟩,
rcases (bounded_iff_subset_ball x).1 hb with ⟨r, hr⟩,
exact compact_of_is_closed_subset (proper_space.compact_ball x r) hc hr
end⟩
/-- The image of a proper space under an expanding onto map is proper. -/
lemma proper_image_of_proper [proper_space α] [metric_space β] (f : α → β)
(f_cont : continuous f) (hf : range f = univ) (C : ℝ)
(hC : ∀x y, dist x y ≤ C * dist (f x) (f y)) : proper_space β :=
begin
apply proper_space_of_compact_closed_ball_of_le 0 (λx₀ r hr, _),
let K := f ⁻¹' (closed_ball x₀ r),
have A : is_closed K :=
continuous_iff_is_closed.1 f_cont (closed_ball x₀ r) is_closed_ball,
have B : bounded K := ⟨max C 0 * (r + r), λx y hx hy, calc
dist x y ≤ C * dist (f x) (f y) : hC x y
... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left _ _) (dist_nonneg)
... ≤ max C 0 * (dist (f x) x₀ + dist (f y) x₀) :
mul_le_mul_of_nonneg_left (dist_triangle_right (f x) (f y) x₀) (le_max_right _ _)
... ≤ max C 0 * (r + r) : begin
simp only [mem_closed_ball, mem_preimage] at hx hy,
exact mul_le_mul_of_nonneg_left (add_le_add hx hy) (le_max_right _ _)
end⟩,
have : is_compact K := compact_iff_closed_bounded.2 ⟨A, B⟩,
have C : is_compact (f '' K) := this.image f_cont,
have : f '' K = closed_ball x₀ r,
by { rw image_preimage_eq_of_subset, rw hf, exact subset_univ _ },
rwa this at C
end
end bounded
section diam
variables {s : set α} {x y z : α}
/-- The diameter of a set in a metric space. To get controllable behavior even when the diameter
should be infinite, we express it in terms of the emetric.diameter -/
def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s)
/-- The diameter of a set is always nonnegative -/
lemma diam_nonneg : 0 ≤ diam s := ennreal.to_real_nonneg
lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 :=
by simp only [diam, emetric.diam_subsingleton hs, ennreal.zero_to_real]
/-- The empty set has zero diameter -/
@[simp] lemma diam_empty : diam (∅ : set α) = 0 :=
diam_subsingleton subsingleton_empty
/-- A singleton has zero diameter -/
@[simp] lemma diam_singleton : diam ({x} : set α) = 0 :=
diam_subsingleton subsingleton_singleton
-- Does not work as a simp-lemma, since {x, y} reduces to (insert y {x})
lemma diam_pair : diam ({x, y} : set α) = dist x y :=
by simp only [diam, emetric.diam_pair, dist_edist]
-- Does not work as a simp-lemma, since {x, y, z} reduces to (insert z (insert y {x}))
lemma diam_triple :
metric.diam ({x, y, z} : set α) = max (max (dist x y) (dist x z)) (dist y z) :=
begin
simp only [metric.diam, emetric.diam_triple, dist_edist],
rw [ennreal.to_real_max, ennreal.to_real_max];
apply_rules [ne_of_lt, edist_lt_top, max_lt]
end
/-- If the distance between any two points in a set is bounded by some constant `C`,
then `ennreal.of_real C` bounds the emetric diameter of this set. -/
lemma ediam_le_of_forall_dist_le {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) :
emetric.diam s ≤ ennreal.of_real C :=
emetric.diam_le_of_forall_edist_le $
λ x hx y hy, (edist_dist x y).symm ▸ ennreal.of_real_le_of_real (h x hx y hy)
/-- If the distance between any two points in a set is bounded by some non-negative constant,
this constant bounds the diameter. -/
lemma diam_le_of_forall_dist_le {C : ℝ} (h₀ : 0 ≤ C) (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) :
diam s ≤ C :=
ennreal.to_real_le_of_le_of_real h₀ (ediam_le_of_forall_dist_le h)
/-- If the distance between any two points in a nonempty set is bounded by some constant,
this constant bounds the diameter. -/
lemma diam_le_of_forall_dist_le_of_nonempty (hs : s.nonempty) {C : ℝ}
(h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C :=
have h₀ : 0 ≤ C, from let ⟨x, hx⟩ := hs in le_trans dist_nonneg (h x hx x hx),
diam_le_of_forall_dist_le h₀ h
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem' (h : emetric.diam s ≠ ⊤) (hx : x ∈ s) (hy : y ∈ s) :
dist x y ≤ diam s :=
begin
rw [diam, dist_edist],
rw ennreal.to_real_le_to_real (edist_ne_top _ _) h,
exact emetric.edist_le_diam_of_mem hx hy
end
/-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/
lemma bounded_iff_ediam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ :=
iff.intro
(λ ⟨C, hC⟩, ne_top_of_le_ne_top ennreal.of_real_ne_top
(ediam_le_of_forall_dist_le $ λ x hx y hy, hC x y hx hy))
(λ h, ⟨diam s, λ x y hx hy, dist_le_diam_of_mem' h hx hy⟩)
lemma bounded.ediam_ne_top (h : bounded s) : emetric.diam s ≠ ⊤ :=
bounded_iff_ediam_ne_top.1 h
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s :=
dist_le_diam_of_mem' h.ediam_ne_top hx hy
/-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`.
This lemma makes it possible to avoid side conditions in some situations -/
lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 :=
begin
simp only [bounded_iff_ediam_ne_top, not_not, ne.def] at h,
simp [diam, h]
end
/-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/
lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t :=
begin
unfold diam,
rw ennreal.to_real_le_to_real (bounded.subset h ht).ediam_ne_top ht.ediam_ne_top,
exact emetric.diam_mono h
end
/-- The diameter of a union is controlled by the sum of the diameters, and the distance between
any two points in each of the sets. This lemma is true without any side condition, since it is
obviously true if `s ∪ t` is unbounded. -/
lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + dist x y + diam t :=
begin
classical, by_cases H : bounded (s ∪ t),
{ have hs : bounded s, from H.subset (subset_union_left _ _),
have ht : bounded t, from H.subset (subset_union_right _ _),
rw [bounded_iff_ediam_ne_top] at H hs ht,
rw [dist_edist, diam, diam, diam, ← ennreal.to_real_add, ← ennreal.to_real_add,
ennreal.to_real_le_to_real];
repeat { apply ennreal.add_ne_top.2; split }; try { assumption };
try { apply edist_ne_top },
exact emetric.diam_union xs yt },
{ rw [diam_eq_zero_of_unbounded H],
apply_rules [add_nonneg, diam_nonneg, dist_nonneg] }
end
/-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/
lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t :=
begin
rcases h with ⟨x, ⟨xs, xt⟩⟩,
simpa using diam_union xs xt
end
/-- The diameter of a closed ball of radius `r` is at most `2 r`. -/
lemma diam_closed_ball {r : ℝ} (h : 0 ≤ r) : diam (closed_ball x r) ≤ 2 * r :=
diam_le_of_forall_dist_le (mul_nonneg (le_of_lt zero_lt_two) h) $ λa ha b hb, calc
dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add ha hb
... = 2 * r : by simp [mul_two, mul_comm]
/-- The diameter of a ball of radius `r` is at most `2 r`. -/
lemma diam_ball {r : ℝ} (h : 0 ≤ r) : diam (ball x r) ≤ 2 * r :=
le_trans (diam_mono ball_subset_closed_ball bounded_closed_ball) (diam_closed_ball h)
end diam
end metric
|
08e48cb15eb52d28c743b08b9ef81d58b5c3090d | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/order/closure.lean | dcd680373f266c8f50518b8081fa2f692638abb4 | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,821 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import order.basic
import order.preorder_hom
import order.galois_connection
import tactic.monotonicity
/-!
# Closure operators on a partial order
We define (bundled) closure operators on a partial order as an monotone (increasing), extensive
(inflationary) and idempotent function.
We define closed elements for the operator as elements which are fixed by it.
Note that there is close connection to Galois connections and Galois insertions: every closure
operator induces a Galois insertion (from the set of closed elements to the underlying type), and
every Galois connection induces a closure operator (namely the composition). In particular,
a Galois insertion can be seen as a general case of a closure operator, where the inclusion is given
by coercion, see `closure_operator.gi`.
## References
* https://en.wikipedia.org/wiki/Closure_operator#Closure_operators_on_partially_ordered_sets
-/
universe u
variables (α : Type u) [partial_order α]
/--
A closure operator on the partial order `α` is a monotone function which is extensive (every `x`
is less than its closure) and idempotent.
-/
structure closure_operator extends α →ₘ α :=
(le_closure' : ∀ x, x ≤ to_fun x)
(idempotent' : ∀ x, to_fun (to_fun x) = to_fun x)
instance : has_coe_to_fun (closure_operator α) :=
{ F := _, coe := λ c, c.to_fun }
/-- See Note [custom simps projection] -/
def closure_operator.simps.apply (f : closure_operator α) : α → α := f
initialize_simps_projections closure_operator (to_preorder_hom_to_fun → apply, -to_preorder_hom)
namespace closure_operator
/-- The identity function as a closure operator. -/
@[simps]
def id : closure_operator α :=
{ to_fun := λ x, x,
monotone' := λ _ _ h, h,
le_closure' := λ _, le_refl _,
idempotent' := λ _, rfl }
instance : inhabited (closure_operator α) := ⟨id α⟩
variables {α} (c : closure_operator α)
@[ext] lemma ext :
∀ (c₁ c₂ : closure_operator α), (c₁ : α → α) = (c₂ : α → α) → c₁ = c₂
| ⟨⟨c₁, _⟩, _, _⟩ ⟨⟨c₂, _⟩, _, _⟩ h := by { congr, exact h }
/-- Constructor for a closure operator using the weaker idempotency axiom: `f (f x) ≤ f x`. -/
@[simps]
def mk' (f : α → α) (hf₁ : monotone f) (hf₂ : ∀ x, x ≤ f x) (hf₃ : ∀ x, f (f x) ≤ f x) :
closure_operator α :=
{ to_fun := f,
monotone' := hf₁,
le_closure' := hf₂,
idempotent' := λ x, le_antisymm (hf₃ x) (hf₁ (hf₂ x)) }
@[mono] lemma monotone : monotone c := c.monotone'
/--
Every element is less than its closure. This property is sometimes referred to as extensivity or
inflationary.
-/
lemma le_closure (x : α) : x ≤ c x := c.le_closure' x
@[simp] lemma idempotent (x : α) : c (c x) = c x := c.idempotent' x
lemma le_closure_iff (x y : α) : x ≤ c y ↔ c x ≤ c y :=
⟨λ h, c.idempotent y ▸ c.monotone h, λ h, le_trans (c.le_closure x) h⟩
lemma closure_top {α : Type u} [order_top α] (c : closure_operator α) : c ⊤ = ⊤ :=
le_antisymm le_top (c.le_closure _)
lemma closure_inter_le {α : Type u} [semilattice_inf α] (c : closure_operator α) (x y : α) :
c (x ⊓ y) ≤ c x ⊓ c y :=
c.monotone.map_inf_le _ _
lemma closure_union_closure_le {α : Type u} [semilattice_sup α] (c : closure_operator α) (x y : α) :
c x ⊔ c y ≤ c (x ⊔ y) :=
c.monotone.le_map_sup _ _
/-- An element `x` is closed for the closure operator `c` if it is a fixed point for it. -/
def closed : set α := λ x, c x = x
lemma mem_closed_iff (x : α) : x ∈ c.closed ↔ c x = x := iff.rfl
lemma mem_closed_iff_closure_le (x : α) : x ∈ c.closed ↔ c x ≤ x :=
⟨le_of_eq, λ h, le_antisymm h (c.le_closure x)⟩
lemma closure_eq_self_of_mem_closed {x : α} (h : x ∈ c.closed) : c x = x := h
@[simp] lemma closure_is_closed (x : α) : c x ∈ c.closed := c.idempotent x
/-- The set of closed elements for `c` is exactly its range. -/
lemma closed_eq_range_close : c.closed = set.range c :=
set.ext $ λ x, ⟨λ h, ⟨x, h⟩, by { rintro ⟨y, rfl⟩, apply c.idempotent }⟩
/-- Send an `x` to an element of the set of closed elements (by taking the closure). -/
def to_closed (x : α) : c.closed := ⟨c x, c.closure_is_closed x⟩
lemma top_mem_closed {α : Type u} [order_top α] (c : closure_operator α) : ⊤ ∈ c.closed :=
c.closure_top
lemma closure_le_closed_iff_le {x y : α} (hy : c.closed y) : x ≤ y ↔ c x ≤ y :=
by rw [← c.closure_eq_self_of_mem_closed hy, le_closure_iff]
/-- The set of closed elements has a Galois insertion to the underlying type. -/
def gi : galois_insertion c.to_closed coe :=
{ choice := λ x hx, ⟨x, le_antisymm hx (c.le_closure x)⟩,
gc := λ x y, (c.closure_le_closed_iff_le y.2).symm,
le_l_u := λ x, c.le_closure _,
choice_eq := λ x hx, le_antisymm (c.le_closure x) hx }
end closure_operator
variables {α} (c : closure_operator α)
/--
Every Galois connection induces a closure operator given by the composition. This is the partial
order version of the statement that every adjunction induces a monad.
-/
@[simps]
def galois_connection.closure_operator {β : Type u} [preorder β]
{l : α → β} {u : β → α} (gc : galois_connection l u) :
closure_operator α :=
{ to_fun := λ x, u (l x),
monotone' := λ x y h, gc.monotone_u (gc.monotone_l h),
le_closure' := gc.le_u_l,
idempotent' := λ x, le_antisymm (gc.monotone_u (gc.l_u_le _)) (gc.le_u_l _) }
/--
The Galois insertion associated to a closure operator can be used to reconstruct the closure
operator.
Note that the inverse in the opposite direction does not hold in general.
-/
@[simp]
lemma closure_operator_gi_self : c.gi.gc.closure_operator = c :=
by { ext x, refl }
|
9e1bbf953baa6ba34a41faec48a4a9f63ce7f7b2 | ee8cdbabf07f77e7be63a449b8483ce308d37218 | /lean/src/test/imo-1959-q1.lean | 5647c3c9906f240b63e918d0d0af864548a1ef71 | [
"MIT",
"Apache-2.0"
] | permissive | zeta1999/miniF2F | 6d66c75d1c18152e224d07d5eed57624f731d4b7 | c1ba9629559c5273c92ec226894baa0c1ce27861 | refs/heads/main | 1,681,897,460,642 | 1,620,646,361,000 | 1,620,646,361,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 244 | lean | /-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kunhao Zheng
-/
import data.real.basic
example (n : ℕ+) : nat.gcd (21*n + 4) (14*n + 3) = 1 :=
begin
sorry
end
|
0d626d9a98568ce6c49127811f62ac852ff7b570 | fd3506535396cef3d1bdcf4ae5b87c8ed9ff2c2e | /migrated/fin.lean | d8cc40e21506e3fed640f9bb5a4263976c1a6e85 | [] | no_license | williamdemeo/leanproved | 77933dbcb8bfbae61a753ae31fa669b3ed8cda9d | d8c2e2ca0002b252fce049c4ff9be0e9e83a6374 | refs/heads/master | 1,598,674,802,432 | 1,437,528,488,000 | 1,437,528,488,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,468 | lean | /-
Copyright (c) 2015 Haitao Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : Haitao Zhang
-/
import data algebra.group
open fin nat function eq.ops
namespace migration
section
variable {n : nat}
lemma eq_of_veq : ∀ {i j : fin n}, (val i) = j → i = j
| (mk iv ilt) (mk jv jlt) := assume (veq : iv = jv), begin congruence, assumption end
lemma veq_of_eq : ∀ {i j : fin n}, i = j → (val i) = j
| (mk iv ilt) (mk jv jlt) := assume Peq,
have veq : iv = jv, from fin.no_confusion Peq (λ Pe Pqe, Pe), veq
lemma eq_iff_veq : ∀ {i j : fin n}, (val i) = j ↔ i = j :=
take i j, iff.intro eq_of_veq veq_of_eq
definition val_inj := @eq_of_veq n
definition lift_succ (i : fin n) : fin (nat.succ n) :=
lift i 1
definition maxi [reducible] : fin (succ n) :=
mk n !lt_succ_self
lemma ne_max_of_lt_max {i : fin (succ n)} : i < n → i ≠ maxi :=
by intro hlt he; substvars; exact absurd hlt (lt.irrefl n)
lemma lt_max_of_ne_max {i : fin (succ n)} : i ≠ maxi → i < n :=
assume hne : i ≠ maxi,
assert visn : val i < nat.succ n, from val_lt i,
assert aux : val (@maxi n) = n, from rfl,
assert vne : val i ≠ n, from
assume he,
have vivm : val i = val (@maxi n), from he ⬝ aux⁻¹,
absurd (eq_of_veq vivm) hne,
lt_of_le_of_ne (le_of_lt_succ visn) vne
lemma lift_succ_ne_max {i : fin n} : lift_succ i ≠ maxi :=
begin
cases i with v hlt, esimp [lift_succ, lift, max], intro he,
injection he, substvars,
exact absurd hlt (lt.irrefl v)
end
lemma lift_succ_inj : injective (@lift_succ n) :=
take i j, destruct i (destruct j (take iv ilt jv jlt Pmkeq,
begin congruence, apply fin.no_confusion Pmkeq, intros, assumption end))
lemma lt_of_inj_of_max (f : fin (succ n) → fin (succ n)) :
injective f → (f maxi = maxi) → ∀ i, i < n → f i < n :=
assume Pinj Peq, take i, assume Pilt,
assert P1 : f i = f maxi → i = maxi, from assume Peq, Pinj i maxi Peq,
have P : f i ≠ maxi, from
begin rewrite -Peq, intro P2, apply absurd (P1 P2) (ne_max_of_lt_max Pilt) end,
lt_max_of_ne_max P
definition lift_fun : (fin n → fin n) → (fin (succ n) → fin (succ n)) :=
λ f i, dite (i = maxi) (λ Pe, maxi) (λ Pne, lift_succ (f (mk i (lt_max_of_ne_max Pne))))
definition lower_inj (f : fin (succ n) → fin (succ n)) (inj : injective f) :
f maxi = maxi → fin n → fin n :=
assume Peq, take i, mk (f (lift_succ i)) (lt_of_inj_of_max f inj Peq (lift_succ i) (lt_max_of_ne_max lift_succ_ne_max))
lemma lift_fun_max {f : fin n → fin n} : lift_fun f maxi = maxi :=
begin rewrite [↑lift_fun, dif_pos rfl] end
lemma lift_fun_of_ne_max {f : fin n → fin n} {i} (Pne : i ≠ maxi) :
lift_fun f i = lift_succ (f (mk i (lt_max_of_ne_max Pne))) :=
begin rewrite [↑lift_fun, dif_neg Pne] end
lemma lift_fun_eq {f : fin n → fin n} {i : fin n} :
lift_fun f (lift_succ i) = lift_succ (f i) :=
begin
rewrite [lift_fun_of_ne_max lift_succ_ne_max], congruence, congruence,
rewrite [-eq_iff_veq, ↑lift_succ, -val_lift]
end
lemma lift_fun_of_inj {f : fin n → fin n} : injective f → injective (lift_fun f) :=
assume Pinj, take i j,
assert Pdi : decidable (i = maxi), from _, assert Pdj : decidable (j = maxi), from _,
begin
cases Pdi with Pimax Pinmax,
cases Pdj with Pjmax Pjnmax,
substvars, intros, exact rfl,
substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pjnmax],
intro Plmax, apply absurd Plmax⁻¹ lift_succ_ne_max,
cases Pdj with Pjmax Pjnmax,
substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pinmax],
intro Plmax, apply absurd Plmax lift_succ_ne_max,
rewrite [lift_fun_of_ne_max Pinmax, lift_fun_of_ne_max Pjnmax],
intro Peq, rewrite [-eq_iff_veq],
exact veq_of_eq (Pinj (lift_succ_inj Peq))
end
lemma lift_fun_inj : injective (@lift_fun n) :=
take f₁ f₂ Peq, funext (λ i,
assert Peqi : lift_fun f₁ (lift_succ i) = lift_fun f₂ (lift_succ i), from congr_fun Peq _,
begin revert Peqi, rewrite [*lift_fun_eq], apply lift_succ_inj end)
lemma lower_inj_apply {f Pinj Pmax} (i : fin n) :
val (lower_inj f Pinj Pmax i) = val (f (lift_succ i)) :=
by rewrite [↑lower_inj]
definition madd (i j : fin (succ n)) : fin (succ n) :=
mk ((i + j) mod (succ n)) (mod_lt _ !zero_lt_succ)
lemma val_madd : ∀ i j : fin (succ n), val (madd i j) = (i + j) mod (succ n)
| (mk iv ilt) (mk jv jlt) := rfl
lemma madd_inj : ∀ {i : fin (succ n)}, injective (madd i)
| (mk iv ilt) :=
take j₁ j₂, fin.destruct j₁ (fin.destruct j₂ (λ jv₁ jlt₁ jv₂ jlt₂, begin
rewrite [↑madd, -eq_iff_veq],
intro Peq, congruence,
rewrite [-(mod_eq_of_lt jlt₁), -(mod_eq_of_lt jlt₂)],
apply mod_eq_mod_of_add_mod_eq_add_mod_left Peq
end))
variable (n)
definition mk_mod [reducible] (n i : nat) : fin (succ n) :=
mk (i mod (succ n)) (mod_lt _ !zero_lt_succ)
variable {n}
lemma mk_mod_eq {n : nat} {i : fin (succ n)} : i = mk_mod n i :=
eq_of_veq begin rewrite [↑mk_mod, mod_eq_of_lt !is_lt] end
lemma mk_mod_of_lt {n i : nat} (Plt : i < succ n) : mk_mod n i = mk i Plt :=
begin esimp [mk_mod], congruence, exact mod_eq_of_lt Plt end
lemma mk_succ_ne_zero {n i : nat} : ∀ {P}, mk (succ i) P ≠ zero n :=
assume P Pe, absurd (veq_of_eq Pe) !succ_ne_zero
lemma madd_mk_mod {n i j : nat} : madd (mk_mod n i) (mk_mod n j) = mk_mod n (i+j) :=
eq_of_veq begin esimp [madd, mk_mod], rewrite [ mod_add_mod, add_mod_mod ] end
lemma succ_max {n : nat} : fin.succ maxi = (@maxi (succ n)) := rfl
lemma lift_zero {n : nat} : lift_succ (zero n) = zero (succ n) := rfl
lemma lift_succ.comm {n : nat} : lift_succ ∘ (@succ n) = succ ∘ lift_succ :=
funext take i, eq_of_veq (begin rewrite [↑lift_succ, -val_lift, *val_succ, -val_lift] end)
lemma max_lt (i j : fin n) : max i j < n :=
max_lt (is_lt i) (is_lt j)
end
section upto
open list
lemma dmap_map_lift {n : nat} : ∀ l : list nat, (∀ i, i ∈ l → i < n) → dmap (λ i, i < succ n) mk l = map lift_succ (dmap (λ i, i < n) mk l)
| [] := assume Plt, rfl
| (i::l) := assume Plt, begin
rewrite [@dmap_cons_of_pos _ _ (λ i, i < succ n) _ _ _ (lt_succ_of_lt (Plt i !mem_cons)), @dmap_cons_of_pos _ _ (λ i, i < n) _ _ _ (Plt i !mem_cons), map_cons],
congruence,
apply dmap_map_lift,
intro j Pjinl, apply Plt, apply mem_cons_of_mem, assumption end
lemma upto_succ (n : nat) : upto (succ n) = maxi :: map lift_succ (upto n) :=
begin
rewrite [↑fin.upto, list.upto_succ, @dmap_cons_of_pos _ _ (λ i, i < succ n) _ _ _ (nat.self_lt_succ n)],
congruence,
apply dmap_map_lift, apply @list.lt_of_mem_upto
end
definition upto_step : ∀ {n : nat}, fin.upto (succ n) = (map succ (upto n))++[zero n]
| 0 := rfl
| (succ n) := begin rewrite [upto_succ n, map_cons, append_cons, succ_max, upto_succ, -lift_zero],
congruence, rewrite [map_map, -lift_succ.comm, -map_map, -(map_singleton _ (zero n)), -map_append, -upto_step] end
end upto
section zn
open nat fin eq.ops algebra
variable {n : nat}
lemma val_mod : ∀ i : fin (succ n), (val i) mod (succ n) = val i
| (mk iv ilt) := by esimp; rewrite [ mod_eq_of_lt ilt]
definition minv : ∀ i : fin (succ n), fin (succ n)
| (mk iv ilt) := mk ((succ n - iv) mod succ n) (mod_lt _ !zero_lt_succ)
lemma madd_comm (i j : fin (succ n)) : madd i j = madd j i :=
by apply eq_of_veq; rewrite [*val_madd, add.comm (val i)]
lemma zero_madd (i : fin (succ n)) : madd (zero n) i = i :=
by apply eq_of_veq; rewrite [val_madd, ↑zero, nat.zero_add, mod_eq_of_lt (is_lt i)]
lemma madd_zero (i : fin (succ n)) : madd i (zero n) = i :=
!madd_comm ▸ zero_madd i
lemma madd_assoc (i j k : fin (succ n)) : madd (madd i j) k = madd i (madd j k) :=
by apply eq_of_veq; rewrite [*val_madd, mod_add_mod, add_mod_mod, add.assoc (val i)]
lemma madd_left_inv : ∀ i : fin (succ n), madd (minv i) i = zero n
| (mk iv ilt) := eq_of_veq (by
rewrite [val_madd, ↑minv, ↑zero, mod_add_mod, sub_add_cancel (nat.le_of_lt ilt), mod_self])
definition madd_is_comm_group [instance] : add_comm_group (fin (succ n)) :=
add_comm_group.mk madd madd_assoc (zero n) zero_madd madd_zero minv madd_left_inv madd_comm
example (i j : fin (succ n)) : i + j = j + i := add.comm i j
end zn
section unused
definition madd₁ : ∀ {n : nat} (i j : fin n), fin n
| 0 (mk iv ilt) _ := absurd ilt !not_lt_zero
| (succ n) (mk iv ilt) (mk jv jlt) := mk ((iv + jv) mod (succ n)) (mod_lt _ !zero_lt_succ)
variable {n : nat}
-- these become trivial once the group operation of madd is established
definition max_sub : fin (succ n) → fin (succ n)
| (mk iv ilt) := mk (n - iv) (sub_lt_succ n _)
definition sub_max : fin (succ n) → fin (succ n)
| (mk iv ilt) := mk (succ iv mod (succ n)) (mod_lt _ !zero_lt_succ)
lemma madd_max_sub_eq_max : ∀ i : fin (succ n), madd (max_sub i) i = maxi
| (mk iv ilt) := begin
esimp [madd, max_sub, maxi],
congruence,
rewrite [@sub_add_cancel n iv (le_of_lt_succ ilt), mod_eq_of_lt !lt_succ_self]
end
lemma madd_sub_max_eq : ∀ i : fin (succ n), madd (sub_max i) maxi = i
| (mk iv ilt) :=
assert Pd : decidable (iv = n), from _, begin
esimp [madd, sub_max, maxi],
congruence,
cases Pd with Pe Pne,
rewrite [Pe, mod_self, zero_add n, mod_eq_of_lt !lt_succ_self],
assert Plt : succ iv < succ n,
apply succ_lt_succ, exact lt_of_le_and_ne (le_of_lt_succ ilt) Pne,
check_expr mod_eq_of_lt Plt,
rewrite [(mod_eq_of_lt Plt), succ_add, -add_succ, add_mod_self, mod_eq_of_lt ilt]
end
end unused
end migration
|
7cc5016f5364427c12060a3b5d5b2af7a6756e7c | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/run/not_bug1.lean | b1c1b21f6faa5d2b4bb8339951aff917010ba713 | [
"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 | 372 | lean | import standard
using bool
constant list : Type.{1}
constant nil : list
constant cons : bool → list → list
infixr `::` := cons
notation `[` l:(foldr `,` (h t, cons h t) nil `]`) := l
check []
check [tt]
check [tt, ff]
check [tt, ff, ff]
check tt :: ff :: [tt, ff, ff]
check tt :: []
constants a b c : bool
check a :: b :: nil
check [a, b]
check [a, b, c]
check []
|
2768a7a9fce666c114eaaca846e643076e44ac34 | 037dba89703a79cd4a4aec5e959818147f97635d | /src/2020/functions/two_sided_inverse.lean | 649aa7f77894c1768fbd8e6bb5d61b1fb3c41075 | [] | no_license | ImperialCollegeLondon/M40001_lean | 3a6a09298da395ab51bc220a535035d45bbe919b | 62a76fa92654c855af2b2fc2bef8e60acd16ccec | refs/heads/master | 1,666,750,403,259 | 1,665,771,117,000 | 1,665,771,117,000 | 209,141,835 | 115 | 12 | null | 1,640,270,596,000 | 1,568,749,174,000 | Lean | UTF-8 | Lean | false | false | 955 | lean | import tactic
/-! # Two-sided inverses
We define two-sided inverses, and prove that a function
is a bijection if and only if it has a two-sided inverse.
-/
-- let X and Y be types, and let f be a function.
variables {X Y : Type} (f : X → Y)
-- two-sided inverse
structure two_sided_inverse (f : X → Y) :=
(g : Y → X)
(hX : ∀ x : X, g (f x) = x)
(hY : ∀ y : Y, f (g y) = y)
open function
example : bijective f ↔ nonempty (two_sided_inverse f) :=
begin
split,
{ intro hf,
cases hf with hi hs,
choose g hg using hs,
let G : two_sided_inverse f :=
{ g := g,
hX := begin
intro x,
apply hi,
rw hg,
end,
hY := begin
exact hg,
end
},
use G,
},
{ rintro ⟨g, hX, hY⟩,
split,
{ intros a b hab,
apply_fun g at hab,
rw hX at hab,
rw hX at hab,
assumption
},
{ intro y,
use (g(y)),
apply hY,
}
}
end
|
bf13c7c9940f48febd2c349dcfce6d2da7c2bee0 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/number_theory/dioph.lean | e6e2bea2e78a0768c5ed09beeef30b7471fd034d | [
"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 | 26,058 | 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.fin.fin2
import data.pfun
import data.vector3
import number_theory.pell
/-!
# Diophantine functions and Matiyasevic's theorem
Hilbert's tenth problem asked whether there exists an algorithm which for a given integer polynomial
determines whether this polynomial has integer solutions. It was answered in the negative in 1970,
the final step being completed by Matiyasevic who showed that the power function is Diophantine.
Here a function is called Diophantine if its graph is Diophantine as a set. A subset `S ⊆ ℕ ^ α` in
turn is called Diophantine if there exists an integer polynomial on `α ⊕ β` such that `v ∈ S` iff
there exists `t : ℕ^β` with `p (v, t) = 0`.
## Main definitions
* `is_poly`: a predicate stating that a function is a multivariate integer polynomial.
* `poly`: the type of multivariate integer polynomial functions.
* `dioph`: a predicate stating that a set is Diophantine, i.e. a set `S ⊆ ℕ^α` is
Diophantine if there exists a polynomial on `α ⊕ β` such that `v ∈ S` iff there
exists `t : ℕ^β` with `p (v, t) = 0`.
* `dioph_fn`: a predicate on a function stating that it is Diophantine in the sense that its graph
is Diophantine as a set.
## Main statements
* `pell_dioph` states that solutions to Pell's equation form a Diophantine set.
* `pow_dioph` states that the power function is Diophantine, a version of Matiyasevic's theorem.
## References
* [M. Carneiro, _A Lean formalization of Matiyasevic's theorem_][carneiro2018matiyasevic]
* [M. Davis, _Hilbert's tenth problem is unsolvable_][MR317916]
## Tags
Matiyasevic's theorem, Hilbert's tenth problem
## TODO
* Finish the solution of Hilbert's tenth problem.
* Connect `poly` to `mv_polynomial`
-/
open fin2 function nat sum
local infixr ` ::ₒ `:67 := option.elim
local infixr ` ⊗ `:65 := sum.elim
universe u
/-!
### Multivariate integer polynomials
Note that this duplicates `mv_polynomial`.
-/
section polynomials
variables {α β γ : Type*}
/-- A predicate asserting that a function is a multivariate integer polynomial.
(We are being a bit lazy here by allowing many representations for multiplication,
rather than only allowing monomials and addition, but the definition is equivalent
and this is easier to use.) -/
inductive is_poly : ((α → ℕ) → ℤ) → Prop
| proj : ∀ i, is_poly (λ x : α → ℕ, x i)
| const : Π (n : ℤ), is_poly (λ x : α → ℕ, n)
| sub : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λ x, f x - g x)
| mul : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λ x, f x * g x)
lemma is_poly.neg {f : (α → ℕ) → ℤ} : is_poly f → is_poly (-f) :=
by { rw ←zero_sub, exact (is_poly.const 0).sub }
lemma is_poly.add {f g : (α → ℕ) → ℤ} (hf : is_poly f) (hg : is_poly g) : is_poly (f + g) :=
by { rw ←sub_neg_eq_add, exact hf.sub hg.neg }
/-- The type of multivariate integer polynomials -/
def poly (α : Type u) := {f : (α → ℕ) → ℤ // is_poly f}
namespace poly
section
instance fun_like : fun_like (poly α) (α → ℕ) (λ _, ℤ) := ⟨subtype.val, subtype.val_injective⟩
/-- Helper instance for when there are too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (poly α) (λ _, (α → ℕ) → ℤ) := fun_like.has_coe_to_fun
/-- The underlying function of a `poly` is a polynomial -/
protected lemma is_poly (f : poly α) : is_poly f := f.2
/-- Extensionality for `poly α` -/
@[ext] lemma ext {f g : poly α} : (∀ x, f x = g x) → f = g := fun_like.ext _ _
/-- The `i`th projection function, `x_i`. -/
def proj (i) : poly α := ⟨_, is_poly.proj i⟩
@[simp] lemma proj_apply (i : α) (x) : proj i x = x i := rfl
/-- The constant function with value `n : ℤ`. -/
def const (n) : poly α := ⟨_, is_poly.const n⟩
@[simp] lemma const_apply (n) (x : α → ℕ) : const n x = n := rfl
instance : has_zero (poly α) := ⟨const 0⟩
instance : has_one (poly α) := ⟨const 1⟩
instance : has_neg (poly α) := ⟨λ f, ⟨-f, f.2.neg⟩⟩
instance : has_add (poly α) := ⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩
instance : has_sub (poly α) := ⟨λ f g, ⟨f - g, f.2.sub g.2⟩⟩
instance : has_mul (poly α) := ⟨λ f g, ⟨f * g, f.2.mul g.2⟩⟩
@[simp] lemma coe_zero : ⇑(0 : poly α) = const 0 := rfl
@[simp] lemma coe_one : ⇑(1 : poly α) = const 1 := rfl
@[simp] lemma coe_neg (f : poly α) : ⇑(-f) = -f := rfl
@[simp] lemma coe_add (f g : poly α) : ⇑(f + g) = f + g := rfl
@[simp] lemma coe_sub (f g : poly α) : ⇑(f - g) = f - g := rfl
@[simp] lemma coe_mul (f g : poly α) : ⇑(f * g) = f * g := rfl
@[simp] lemma zero_apply (x) : (0 : poly α) x = 0 := rfl
@[simp] lemma one_apply (x) : (1 : poly α) x = 1 := rfl
@[simp] lemma neg_apply (f : poly α) (x) : (-f) x = -f x := rfl
@[simp] lemma add_apply (f g : poly α) (x : α → ℕ) : (f + g) x = f x + g x := rfl
@[simp] lemma sub_apply (f g : poly α) (x : α → ℕ) : (f - g) x = f x - g x := rfl
@[simp] lemma mul_apply (f g : poly α) (x : α → ℕ) : (f * g) x = f x * g x := rfl
instance (α : Type*) : inhabited (poly α) := ⟨0⟩
instance : add_comm_group (poly α) := by refine_struct
{ add := ((+) : poly α → poly α → poly α),
neg := (has_neg.neg : poly α → poly α),
sub := (has_sub.sub),
zero := 0,
zsmul := @zsmul_rec _ ⟨(0 : poly α)⟩ ⟨(+)⟩ ⟨has_neg.neg⟩,
nsmul := @nsmul_rec _ ⟨(0 : poly α)⟩ ⟨(+)⟩ };
intros; try { refl }; refine ext (λ _, _);
simp [sub_eq_add_neg, add_comm, add_assoc]
instance : add_group_with_one (poly α) :=
{ one := 1,
nat_cast := λ n, poly.const n,
int_cast := poly.const,
.. poly.add_comm_group }
instance : comm_ring (poly α) := by refine_struct
{ add := ((+) : poly α → poly α → poly α),
zero := 0,
mul := (*),
one := 1,
npow := @npow_rec _ ⟨(1 : poly α)⟩ ⟨(*)⟩,
.. poly.add_group_with_one, .. poly.add_comm_group };
intros; try { refl }; refine ext (λ _, _);
simp [sub_eq_add_neg, mul_add, mul_left_comm, mul_comm, add_comm, add_assoc]
lemma induction {C : poly α → Prop}
(H1 : ∀i, C (proj i)) (H2 : ∀n, C (const n))
(H3 : ∀f g, C f → C g → C (f - g))
(H4 : ∀f g, C f → C g → C (f * g)) (f : poly α) : C f :=
begin
cases f with f pf,
induction pf with i n f g pf pg ihf ihg f g pf pg ihf ihg,
apply H1, apply H2, apply H3 _ _ ihf ihg, apply H4 _ _ ihf ihg
end
/-- The sum of squares of a list of polynomials. This is relevant for
Diophantine equations, because it means that a list of equations
can be encoded as a single equation: `x = 0 ∧ y = 0 ∧ z = 0` is
equivalent to `x^2 + y^2 + z^2 = 0`. -/
def sumsq : list (poly α) → poly α
| [] := 0
| (p::ps) := p*p + sumsq ps
lemma sumsq_nonneg (x : α → ℕ) : ∀ l, 0 ≤ sumsq l x
| [] := le_refl 0
| (p::ps) := by rw sumsq; simp [-add_comm];
exact add_nonneg (mul_self_nonneg _) (sumsq_nonneg ps)
lemma sumsq_eq_zero (x) : ∀ l, sumsq l x = 0 ↔ l.all₂ (λ a : poly α, a x = 0)
| [] := eq_self_iff_true _
| (p::ps) := by rw [list.all₂_cons, ← sumsq_eq_zero ps]; rw sumsq; simp [-add_comm]; exact
⟨λ (h : p x * p x + sumsq ps x = 0),
have p x = 0, from eq_zero_of_mul_self_eq_zero $ le_antisymm
(by rw ← h; have t := add_le_add_left (sumsq_nonneg x ps) (p x * p x); rwa [add_zero] at t)
(mul_self_nonneg _),
⟨this, by simp [this] at h; exact h⟩,
λ ⟨h1, h2⟩, by rw [h1, h2]; refl⟩
end
/-- Map the index set of variables, replacing `x_i` with `x_(f i)`. -/
def map {α β} (f : α → β) (g : poly α) : poly β :=
⟨λ v, g $ v ∘ f, g.induction
(λ i, by simp; apply is_poly.proj)
(λ n, by simp; apply is_poly.const)
(λ f g pf pg, by simp; apply is_poly.sub pf pg)
(λ f g pf pg, by simp; apply is_poly.mul pf pg)⟩
@[simp] lemma map_apply {α β} (f : α → β) (g : poly α) (v) : map f g v = g (v ∘ f) := rfl
end poly
end polynomials
/-! ### Diophantine sets -/
/-- A set `S ⊆ ℕ^α` is Diophantine if there exists a polynomial on
`α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. -/
def dioph {α : Type u} (S : set (α → ℕ)) : Prop :=
∃ {β : Type u} (p : poly (α ⊕ β)), ∀ v, S v ↔ ∃ t, p (v ⊗ t) = 0
namespace dioph
section
variables {α β γ : Type u} {S S' : set (α → ℕ)}
lemma ext (d : dioph S) (H : ∀ v, v ∈ S ↔ v ∈ S') : dioph S' := by rwa ←set.ext H
lemma of_no_dummies (S : set (α → ℕ)) (p : poly α) (h : ∀ v, S v ↔ p v = 0) : dioph S :=
⟨pempty, p.map inl, λ v, (h v).trans ⟨λ h, ⟨pempty.rec _, h⟩, λ ⟨t, ht⟩, ht⟩⟩
lemma inject_dummies_lem (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x)
(p : poly (α ⊕ β)) (v : α → ℕ) :
(∃ t, p (v ⊗ t) = 0) ↔ ∃ t, p.map (inl ⊗ inr ∘ f) (v ⊗ t) = 0 :=
begin
dsimp, refine ⟨λ t, _, λ t, _⟩; cases t with t ht,
{ have : (v ⊗ (0 ::ₒ t) ∘ g) ∘ (inl ⊗ inr ∘ f) = v ⊗ t :=
funext (λ s, by cases s with a b; dsimp [(∘)]; try {rw inv}; refl),
exact ⟨(0 ::ₒ t) ∘ g, by rwa this⟩ },
{ have : v ⊗ t ∘ f = (v ⊗ t) ∘ (inl ⊗ inr ∘ f) :=
funext (λ s, by cases s with a b; refl),
exact ⟨t ∘ f, by rwa this⟩ }
end
lemma inject_dummies (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β))
(h : ∀ v, S v ↔ ∃ t, p (v ⊗ t) = 0) :
∃ q : poly (α ⊕ γ), ∀ v, S v ↔ ∃ t, q (v ⊗ t) = 0 :=
⟨p.map (inl ⊗ (inr ∘ f)), λ v, (h v).trans $ inject_dummies_lem f g inv _ _⟩
variables (β)
lemma reindex_dioph (f : α → β) : Π (d : dioph S), dioph {v | v ∘ f ∈ S}
| ⟨γ, p, pe⟩ := ⟨γ, p.map ((inl ∘ f) ⊗ inr), λ v, (pe _).trans $ exists_congr $ λ t,
suffices v ∘ f ⊗ t = (v ⊗ t) ∘ (inl ∘ f ⊗ inr), by simp [this],
funext $ λ s, by cases s with a b; refl⟩
variables {β}
lemma dioph_list.all₂ (l : list (set $ α → ℕ)) (d : l.all₂ dioph) :
dioph {v | l.all₂ (λ S : set (α → ℕ), v ∈ S)} :=
suffices ∃ β (pl : list (poly (α ⊕ β))), ∀ v,
list.all₂ (λ S : set _, S v) l ↔ ∃ t, list.all₂ (λ p : poly (α ⊕ β), p (v ⊗ t) = 0) pl,
from let ⟨β, pl, h⟩ := this
in ⟨β, poly.sumsq pl, λ v, (h v).trans $ exists_congr $ λ t, (poly.sumsq_eq_zero _ _).symm⟩,
begin
induction l with S l IH,
exact ⟨ulift empty, [], λ v, by simp; exact ⟨λ ⟨t⟩, empty.rec _ t, trivial⟩⟩,
simp at d,
exact let ⟨⟨β, p, pe⟩, dl⟩ := d, ⟨γ, pl, ple⟩ := IH dl in
⟨β ⊕ γ, p.map (inl ⊗ inr ∘ inl) :: pl.map (λ q, q.map (inl ⊗ (inr ∘ inr))), λ v,
by simp; exact iff.trans (and_congr (pe v) (ple v))
⟨λ ⟨⟨m, hm⟩, ⟨n, hn⟩⟩,
⟨m ⊗ n, by rw [
show (v ⊗ m ⊗ n) ∘ (inl ⊗ inr ∘ inl) = v ⊗ m,
from funext $ λ s, by cases s with a b; refl]; exact hm,
by { refine list.all₂.imp (λ q hq, _) hn, dsimp [(∘)],
rw [show (λ (x : α ⊕ γ), (v ⊗ m ⊗ n) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ n,
from funext $ λ s, by cases s with a b; refl]; exact hq }⟩,
λ ⟨t, hl, hr⟩,
⟨⟨t ∘ inl, by rwa [
show (v ⊗ t) ∘ (inl ⊗ inr ∘ inl) = v ⊗ t ∘ inl,
from funext $ λ s, by cases s with a b; refl] at hl⟩,
⟨t ∘ inr, by
{ refine list.all₂.imp (λ q hq, _) hr, dsimp [(∘)] at hq,
rwa [show (λ (x : α ⊕ γ), (v ⊗ t) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ t ∘ inr,
from funext $ λ s, by cases s with a b; refl] at hq }⟩⟩⟩⟩
end
lemma inter (d : dioph S) (d' : dioph S') : dioph (S ∩ S') := dioph_list.all₂ [S, S'] ⟨d, d'⟩
lemma union : ∀ (d : dioph S) (d' : dioph S'), dioph (S ∪ S')
| ⟨β, p, pe⟩ ⟨γ, q, qe⟩ := ⟨β ⊕ γ, p.map (inl ⊗ inr ∘ inl) * q.map (inl ⊗ inr ∘ inr), λ v,
begin
refine iff.trans (or_congr ((pe v).trans _) ((qe v).trans _))
(exists_or_distrib.symm.trans (exists_congr $ λ t,
(@mul_eq_zero _ _ _ (p ((v ⊗ t) ∘ (inl ⊗ inr ∘ inl)))
(q ((v ⊗ t) ∘ (inl ⊗ inr ∘ inr)))).symm)),
exact inject_dummies_lem _ (some ⊗ (λ _, none)) (λ x, rfl) _ _,
exact inject_dummies_lem _ ((λ _, none) ⊗ some) (λ x, rfl) _ _,
end⟩
/-- A partial function is Diophantine if its graph is Diophantine. -/
def dioph_pfun (f : (α → ℕ) →. ℕ) : Prop := dioph {v : option α → ℕ | f.graph (v ∘ some, v none)}
/-- A function is Diophantine if its graph is Diophantine. -/
def dioph_fn (f : (α → ℕ) → ℕ) : Prop := dioph {v : option α → ℕ | f (v ∘ some) = v none}
lemma reindex_dioph_fn {f : (α → ℕ) → ℕ} (g : α → β) (d : dioph_fn f) : dioph_fn (λ v, f (v ∘ g)) :=
by convert reindex_dioph (option β) (option.map g) d
lemma ex_dioph {S : set (α ⊕ β → ℕ)} : dioph S → dioph {v | ∃ x, v ⊗ x ∈ S}
| ⟨γ, p, pe⟩ := ⟨β ⊕ γ, p.map ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr), λ v,
⟨λ ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x ⊗ t, by simp; rw [
show (v ⊗ x ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ x) ⊗ t,
from funext $ λ s, by cases s with a b; try {cases a}; refl]; exact ht⟩,
λ ⟨t, ht⟩, ⟨t ∘ inl, (pe _).2 ⟨t ∘ inr, by simp at ht; rwa [
show (v ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ t ∘ inl) ⊗ t ∘ inr,
from funext $ λ s, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩
lemma ex1_dioph {S : set (option α → ℕ)} : dioph S → dioph {v | ∃ x, x ::ₒ v ∈ S}
| ⟨β, p, pe⟩ := ⟨option β, p.map (inr none ::ₒ inl ⊗ inr ∘ some), λ v,
⟨λ ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x ::ₒ t, by simp; rw [
show (v ⊗ x ::ₒ t) ∘ (inr none ::ₒ inl ⊗ inr ∘ some) = x ::ₒ v ⊗ t,
from funext $ λ s, by cases s with a b; try {cases a}; refl]; exact ht⟩,
λ ⟨t, ht⟩, ⟨t none, (pe _).2 ⟨t ∘ some, by simp at ht; rwa [
show (v ⊗ t) ∘ (inr none ::ₒ inl ⊗ inr ∘ some) = t none ::ₒ v ⊗ t ∘ some,
from funext $ λ s, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩
theorem dom_dioph {f : (α → ℕ) →. ℕ} (d : dioph_pfun f) : dioph f.dom :=
cast (congr_arg dioph $ set.ext $ λ v, (pfun.dom_iff_graph _ _).symm) (ex1_dioph d)
theorem dioph_fn_iff_pfun (f : (α → ℕ) → ℕ) : dioph_fn f = @dioph_pfun α f :=
by refine congr_arg dioph (set.ext $ λ v, _); exact pfun.lift_graph.symm
lemma abs_poly_dioph (p : poly α) : dioph_fn (λ v, (p v).nat_abs) :=
of_no_dummies _ ((p.map some - poly.proj none) * (p.map some + poly.proj none)) $ λ v,
by { dsimp, exact int.eq_nat_abs_iff_mul_eq_zero }
theorem proj_dioph (i : α) : dioph_fn (λ v, v i) :=
abs_poly_dioph (poly.proj i)
theorem dioph_pfun_comp1 {S : set (option α → ℕ)} (d : dioph S) {f} (df : dioph_pfun f) :
dioph {v : α → ℕ | ∃ h : f.dom v, f.fn v h ::ₒ v ∈ S} :=
ext (ex1_dioph (d.inter df)) $ λ v,
⟨λ ⟨x, hS, (h: Exists _)⟩, by
rw [show (x ::ₒ v) ∘ some = v, from funext $ λ s, rfl] at h;
cases h with hf h; refine ⟨hf, _⟩; rw [pfun.fn, h]; exact hS,
λ ⟨x, hS⟩, ⟨f.fn v x, hS, show Exists _,
by rw [show (f.fn v x ::ₒ v) ∘ some = v, from funext $ λ s, rfl]; exact ⟨x, rfl⟩⟩⟩
theorem dioph_fn_comp1 {S : set (option α → ℕ)} (d : dioph S) {f : (α → ℕ) → ℕ} (df : dioph_fn f) :
dioph {v | f v ::ₒ v ∈ S} :=
ext (dioph_pfun_comp1 d $ cast (dioph_fn_iff_pfun f) df) $ λ v,
⟨λ ⟨_, h⟩, h, λ h, ⟨trivial, h⟩⟩
end
section
variables {α β : Type} {n : ℕ}
open vector3
open_locale vector3
local attribute [reducible] vector3
lemma dioph_fn_vec_comp1 {S : set (vector3 ℕ (succ n))} (d : dioph S) {f : vector3 ℕ n → ℕ}
(df : dioph_fn f) :
dioph {v : vector3 ℕ n | f v :: v ∈ S} :=
ext (dioph_fn_comp1 (reindex_dioph _ (none :: some) d) df) $ λ v,
by { dsimp, congr', ext x, cases x; refl }
theorem vec_ex1_dioph (n) {S : set (vector3 ℕ (succ n))} (d : dioph S) :
dioph {v : fin2 n → ℕ | ∃ x, x :: v ∈ S} :=
ext (ex1_dioph $ reindex_dioph _ (none :: some) d) $ λ v, exists_congr $ λ x, by { dsimp,
rw [show option.elim x v ∘ cons none some = x :: v,
from funext $ λ s, by cases s with a b; refl] }
lemma dioph_fn_vec (f : vector3 ℕ n → ℕ) : dioph_fn f ↔ dioph {v | f (v ∘ fs) = v fz} :=
⟨reindex_dioph _ (fz ::ₒ fs), reindex_dioph _ (none :: some)⟩
lemma dioph_pfun_vec (f : vector3 ℕ n →. ℕ) : dioph_pfun f ↔ dioph {v | f.graph (v ∘ fs, v fz)} :=
⟨reindex_dioph _ (fz ::ₒ fs), reindex_dioph _ (none :: some)⟩
lemma dioph_fn_compn : ∀ {n} {S : set (α ⊕ fin2 n → ℕ)} (d : dioph S)
{f : vector3 ((α → ℕ) → ℕ) n} (df : vector_allp dioph_fn f),
dioph {v : α → ℕ | v ⊗ (λ i, f i v) ∈ S}
| 0 S d f := λ df, ext (reindex_dioph _ (id ⊗ fin2.elim0) d) $ λ v,
by { dsimp, congr', ext x, obtain (_ | _ | _) := x, refl }
| (succ n) S d f := f.cons_elim $ λ f fl, by simp; exact λ df dfl,
have dioph {v |v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr ∈ S},
from ext (dioph_fn_comp1 (reindex_dioph _ (some ∘ inl ⊗ none :: some ∘ inr) d) $
reindex_dioph_fn inl df) $ λ v,
by { dsimp, congr', ext x, obtain (_ | _ | _) := x; refl },
have dioph {v | v ⊗ f v :: (λ (i : fin2 n), fl i v) ∈ S},
from @dioph_fn_compn n (λ v, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)) this _ dfl,
ext this $ λ v, by { dsimp, congr', ext x, obtain (_ | _ | _) := x; refl }
lemma dioph_comp {S : set (vector3 ℕ n)} (d : dioph S) (f : vector3 ((α → ℕ) → ℕ) n)
(df : vector_allp dioph_fn f) : dioph {v | (λ i, f i v) ∈ S} :=
dioph_fn_compn (reindex_dioph _ inr d) df
lemma dioph_fn_comp {f : vector3 ℕ n → ℕ} (df : dioph_fn f) (g : vector3 ((α → ℕ) → ℕ) n)
(dg : vector_allp dioph_fn g) : dioph_fn (λ v, f (λ i, g i v)) :=
dioph_comp ((dioph_fn_vec _).1 df) ((λ v, v none) :: λ i v, g i (v ∘ some)) $
by simp; exact ⟨proj_dioph none, (vector_allp_iff_forall _ _).2 $ λ i,
reindex_dioph_fn _ $ (vector_allp_iff_forall _ _).1 dg _⟩
localized "notation x ` D∧ `:35 y := dioph.inter x y" in dioph
localized "notation x ` D∨ `:35 y := dioph.union x y" in dioph
localized "notation `D∃`:30 := dioph.vec_ex1_dioph" in dioph
localized "prefix `&`:max := fin2.of_nat'" in dioph
theorem proj_dioph_of_nat {n : ℕ} (m : ℕ) [is_lt m n] : dioph_fn (λ v : vector3 ℕ n, v &m) :=
proj_dioph &m
localized "prefix `D&`:100 := dioph.proj_dioph_of_nat" in dioph
theorem const_dioph (n : ℕ) : dioph_fn (const (α → ℕ) n) :=
abs_poly_dioph (poly.const n)
localized "prefix `D.`:100 := dioph.const_dioph" in dioph
variables {f g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g)
include df dg
lemma dioph_comp2 {S : ℕ → ℕ → Prop} (d : dioph (λ v:vector3 ℕ 2, S (v &0) (v &1))) :
dioph (λ v, S (f v) (g v)) :=
dioph_comp d [f, g] (by exact ⟨df, dg⟩)
lemma dioph_fn_comp2 {h : ℕ → ℕ → ℕ} (d : dioph_fn (λ v:vector3 ℕ 2, h (v &0) (v &1))) :
dioph_fn (λ v, h (f v) (g v)) :=
dioph_fn_comp d [f, g] (by exact ⟨df, dg⟩)
lemma eq_dioph : dioph (λ v, f v = g v) :=
dioph_comp2 df dg $ of_no_dummies _ (poly.proj &0 - poly.proj &1)
(λ v, (int.coe_nat_eq_coe_nat_iff _ _).symm.trans
⟨@sub_eq_zero_of_eq ℤ _ (v &0) (v &1), eq_of_sub_eq_zero⟩)
localized "infix ` D= `:50 := dioph.eq_dioph" in dioph
lemma add_dioph : dioph_fn (λ v, f v + g v) :=
dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 + poly.proj &1)
localized "infix ` D+ `:80 := dioph.add_dioph" in dioph
lemma mul_dioph : dioph_fn (λ v, f v * g v) :=
dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 * poly.proj &1)
localized "infix ` D* `:90 := dioph.mul_dioph" in dioph
lemma le_dioph : dioph {v | f v ≤ g v} :=
dioph_comp2 df dg $ ext (D∃2 $ D&1 D+ D&0 D= D&2) (λ v, ⟨λ ⟨x, hx⟩, le.intro hx, le.dest⟩)
localized "infix ` D≤ `:50 := dioph.le_dioph" in dioph
lemma lt_dioph : dioph {v | f v < g v} := df D+ (D. 1) D≤ dg
localized "infix ` D< `:50 := dioph.lt_dioph" in dioph
lemma ne_dioph : dioph {v | f v ≠ g v} :=
ext (df D< dg D∨ dg D< df) $ λ v, by { dsimp, exact lt_or_lt_iff_ne }
localized "infix ` D≠ `:50 := dioph.ne_dioph" in dioph
lemma sub_dioph : dioph_fn (λ v, f v - g v) :=
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $
ext (D&1 D= D&0 D+ D&2 D∨ D&1 D≤ D&2 D∧ D&0 D= D.0) $ (vector_all_iff_forall _).1 $ λ x y z,
show (y = x + z ∨ y ≤ z ∧ x = 0) ↔ y - z = x, from
⟨λ o, begin
rcases o with ae | ⟨yz, x0⟩,
{ rw [ae, add_tsub_cancel_right] },
{ rw [x0, tsub_eq_zero_iff_le.mpr yz] }
end, begin
rintro rfl,
cases le_total y z with yz zy,
{ exact or.inr ⟨yz, tsub_eq_zero_iff_le.mpr yz⟩ },
{ exact or.inl (tsub_add_cancel_of_le zy).symm },
end⟩
localized "infix ` D- `:80 := dioph.sub_dioph" in dioph
lemma dvd_dioph : dioph (λ v, f v ∣ g v) :=
dioph_comp (D∃2 $ D&2 D= D&1 D* D&0) [f, g] (by exact ⟨df, dg⟩)
localized "infix ` D∣ `:50 := dioph.dvd_dioph" in dioph
lemma mod_dioph : dioph_fn (λ v, f v % g v) :=
have dioph (λ v : vector3 ℕ 3, (v &2 = 0 ∨ v &0 < v &2) ∧ ∃ (x : ℕ), v &0 + v &2 * x = v &1),
from (D&2 D= D.0 D∨ D&0 D< D&2) D∧ (D∃3 $ D&1 D+ D&3 D* D&0 D= D&2),
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λ z x y,
show ((y = 0 ∨ z < y) ∧ ∃ c, z + y * c = x) ↔ x % y = z, from
⟨λ ⟨h, c, hc⟩, begin rw ← hc; simp; cases h with x0 hl, rw [x0, mod_zero],
exact mod_eq_of_lt hl end,
λ e, by rw ← e; exact ⟨or_iff_not_imp_left.2 $ λ h, mod_lt _ (nat.pos_of_ne_zero h), x / y,
mod_add_div _ _⟩⟩
localized "infix ` D% `:80 := dioph.mod_dioph" in dioph
lemma modeq_dioph {h : (α → ℕ) → ℕ} (dh : dioph_fn h) : dioph (λ v, f v ≡ g v [MOD h v]) :=
df D% dh D= dg D% dh
localized "notation `D≡` := dioph.modeq_dioph" in dioph
lemma div_dioph : dioph_fn (λ v, f v / g v) :=
have dioph (λ v : vector3 ℕ 3, v &2 = 0 ∧ v &0 = 0 ∨ v &0 * v &2 ≤ v &1 ∧ v &1 < (v &0 + 1) * v &2),
from (D&2 D= D.0 D∧ D&0 D= D.0) D∨ D&0 D* D&2 D≤ D&1 D∧ D&1 D< (D&0 D+ D.1) D* D&2,
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λ z x y,
show y = 0 ∧ z = 0 ∨ z * y ≤ x ∧ x < (z + 1) * y ↔ x / y = z,
by refine iff.trans _ eq_comm; exact y.eq_zero_or_pos.elim
(λ y0, by rw [y0, nat.div_zero]; exact
⟨λ o, (o.resolve_right $ λ ⟨_, h2⟩, nat.not_lt_zero _ h2).right, λ z0, or.inl ⟨rfl, z0⟩⟩)
(λ ypos, iff.trans ⟨λ o, o.resolve_left $ λ ⟨h1, _⟩, ne_of_gt ypos h1, or.inr⟩
(le_antisymm_iff.trans $ and_congr (nat.le_div_iff_mul_le ypos) $
iff.trans ⟨lt_succ_of_le, le_of_lt_succ⟩ (div_lt_iff_lt_mul ypos)).symm)
localized "infix ` D/ `:80 := dioph.div_dioph" in dioph
omit df dg
open pell
lemma pell_dioph : dioph (λ v:vector3 ℕ 4, ∃ h : 1 < v &0,
xn h (v &1) = v &2 ∧ yn h (v &1) = v &3) :=
have dioph {v : vector3 ℕ 4 |
1 < v &0 ∧ v &1 ≤ v &3 ∧
(v &2 = 1 ∧ v &3 = 0 ∨
∃ (u w s t b : ℕ),
v &2 * v &2 - (v &0 * v &0 - 1) * v &3 * v &3 = 1 ∧
u * u - (v &0 * v &0 - 1) * w * w = 1 ∧
s * s - (b * b - 1) * t * t = 1 ∧
1 < b ∧ (b ≡ 1 [MOD 4 * v &3]) ∧ (b ≡ v &0 [MOD u]) ∧
0 < w ∧ v &3 * v &3 ∣ w ∧
(s ≡ v &2 [MOD u]) ∧
(t ≡ v &1 [MOD 4 * v &3]))}, from
D.1 D< D&0 D∧ D&1 D≤ D&3 D∧
((D&2 D= D.1 D∧ D&3 D= D.0) D∨
(D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $
D&7 D* D&7 D- (D&5 D* D&5 D- D.1) D* D&8 D* D&8 D= D.1 D∧
D&4 D* D&4 D- (D&5 D* D&5 D- D.1) D* D&3 D* D&3 D= D.1 D∧
D&2 D* D&2 D- (D&0 D* D&0 D- D.1) D* D&1 D* D&1 D= D.1 D∧
D.1 D< D&0 D∧ (D≡ (D&0) (D.1) (D.4 D* D&8)) D∧ (D≡ (D&0) (D&5) D&4) D∧
D.0 D< D&3 D∧ D&8 D* D&8 D∣ D&3 D∧
(D≡ (D&2) (D&7) D&4) D∧
(D≡ (D&1) (D&6) (D.4 D* D&8)))),
dioph.ext this $ λ v, matiyasevic.symm
lemma xn_dioph : dioph_pfun (λ v:vector3 ℕ 2, ⟨1 < v &0, λ h, xn h (v &1)⟩) :=
have dioph (λ v:vector3 ℕ 3, ∃ y, ∃ h : 1 < v &1, xn h (v &2) = v &0 ∧ yn h (v &2) = y), from
let D_pell := pell_dioph.reindex_dioph (fin2 4) [&2, &3, &1, &0] in D∃3 D_pell,
(dioph_pfun_vec _).2 $ dioph.ext this $ λ v, ⟨λ ⟨y, h, xe, ye⟩, ⟨h, xe⟩, λ ⟨h, xe⟩, ⟨_, h, xe, rfl⟩⟩
include df dg
/-- A version of **Matiyasevic's theorem** -/
theorem pow_dioph : dioph_fn (λ v, f v ^ g v) :=
have dioph {v : vector3 ℕ 3 |
v &2 = 0 ∧ v &0 = 1 ∨ 0 < v &2 ∧
(v &1 = 0 ∧ v &0 = 0 ∨ 0 < v &1 ∧
∃ (w a t z x y : ℕ),
(∃ (a1 : 1 < a), xn a1 (v &2) = x ∧ yn a1 (v &2) = y) ∧
(x ≡ y * (a - v &1) + v &0 [MOD t]) ∧
2 * a * v &1 = t + (v &1 * v &1 + 1) ∧
v &0 < t ∧ v &1 ≤ w ∧ v &2 ≤ w ∧
a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)}, from
let D_pell := pell_dioph.reindex_dioph (fin2 9) [&4, &8, &1, &0] in
(D&2 D= D.0 D∧ D&0 D= D.1) D∨ (D.0 D< D&2 D∧
((D&1 D= D.0 D∧ D&0 D= D.0) D∨ (D.0 D< D&1 D∧
(D∃3 $ D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D_pell D∧
(D≡ (D&1) (D&0 D* (D&4 D- D&7) D+ D&6) (D&3)) D∧
D.2 D* D&4 D* D&7 D= D&3 D+ (D&7 D* D&7 D+ D.1) D∧
D&6 D< D&3 D∧ D&7 D≤ D&5 D∧ D&8 D≤ D&5 D∧
D&4 D* D&4 D- ((D&5 D+ D.1) D* (D&5 D+ D.1) D- D.1) D* (D&5 D* D&2) D* (D&5 D* D&2) D= D.1)))),
dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ dioph.ext this $ λ v, iff.symm $
eq_pow_of_pell.trans $ or_congr iff.rfl $ and_congr iff.rfl $ or_congr iff.rfl $ and_congr iff.rfl $
⟨λ ⟨w, a, t, z, a1, h⟩, ⟨w, a, t, z, _, _, ⟨a1, rfl, rfl⟩, h⟩,
λ ⟨w, a, t, z, ._, ._, ⟨a1, rfl, rfl⟩, h⟩, ⟨w, a, t, z, a1, h⟩⟩
end
end dioph
|
12741483c9714ebbc2dd6d03ed665aa0e78a0361 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/linear_algebra/matrix/determinant.lean | 17d6d99482556158a32b63cc686f44702c109560 | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 28,364 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Chris Hughes, Tim Baanen
-/
import data.matrix.pequiv
import data.matrix.block
import data.fintype.card
import group_theory.perm.fin
import group_theory.perm.sign
import algebra.algebra.basic
import tactic.ring
import linear_algebra.alternating
import linear_algebra.pi
/-!
# Determinant of a matrix
This file defines the determinant of a matrix, `matrix.det`, and its essential properties.
## Main definitions
- `matrix.det`: the determinant of a square matrix, as a sum over permutations
- `matrix.det_row_multilinear`: the determinant, as an `alternating_map` in the rows of the matrix
## Main results
- `det_mul`: the determinant of `A ⬝ B` is the product of determinants
- `det_zero_of_row_eq`: the determinant is zero if there is a repeated row
- `det_block_diagonal`: the determinant of a block diagonal matrix is a product
of the blocks' determinants
## Implementation notes
It is possible to configure `simp` to compute determinants. See the file
`test/matrix.lean` for some examples.
-/
universes u v w z
open equiv equiv.perm finset function
namespace matrix
open_locale matrix big_operators
variables {m n : Type*} [decidable_eq n] [fintype n] [decidable_eq m] [fintype m]
variables {R : Type v} [comm_ring R]
local notation `ε` σ:max := ((sign σ : ℤ ) : R)
/-- `det` is an `alternating_map` in the rows of the matrix. -/
def det_row_multilinear : alternating_map R (n → R) R n :=
((multilinear_map.mk_pi_algebra R n R).comp_linear_map (linear_map.proj)).alternatization
/-- The determinant of a matrix given by the Leibniz formula. -/
abbreviation det (M : matrix n n R) : R :=
det_row_multilinear M
lemma det_apply (M : matrix n n R) :
M.det = ∑ σ : perm n, σ.sign • ∏ i, M (σ i) i :=
multilinear_map.alternatization_apply _ M
-- This is what the old definition was. We use it to avoid having to change the old proofs below
lemma det_apply' (M : matrix n n R) :
M.det = ∑ σ : perm n, ε σ * ∏ i, M (σ i) i :=
by simp [det_apply, units.smul_def]
@[simp] lemma det_diagonal {d : n → R} : det (diagonal d) = ∏ i, d i :=
begin
rw det_apply',
refine (finset.sum_eq_single 1 _ _).trans _,
{ intros σ h1 h2,
cases not_forall.1 (mt equiv.ext h2) with x h3,
convert mul_zero _,
apply finset.prod_eq_zero,
{ change x ∈ _, simp },
exact if_neg h3 },
{ simp },
{ simp }
end
@[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 :=
(det_row_multilinear : alternating_map R (n → R) R n).map_zero
@[simp] lemma det_one : det (1 : matrix n n R) = 1 :=
by rw [← diagonal_one]; simp [-diagonal_one]
@[simp]
lemma det_is_empty [is_empty n] {A : matrix n n R} : det A = 1 :=
by simp [det_apply]
lemma det_eq_one_of_card_eq_zero {A : matrix n n R} (h : fintype.card n = 0) : det A = 1 :=
begin
haveI : is_empty n := fintype.card_eq_zero_iff.mp h,
exact det_is_empty,
end
/-- If `n` has only one element, the determinant of an `n` by `n` matrix is just that element.
Although `unique` implies `decidable_eq` and `fintype`, the instances might
not be syntactically equal. Thus, we need to fill in the args explicitly. -/
@[simp]
lemma det_unique {n : Type*} [unique n] [decidable_eq n] [fintype n] (A : matrix n n R) :
det A = A (default n) (default n) :=
by simp [det_apply, univ_unique]
lemma det_eq_elem_of_card_eq_one {A : matrix n n R} (h : fintype.card n = 1) (k : n) :
det A = A k k :=
begin
casesI fintype.card_eq_one_iff_nonempty_unique.mp h,
convert det_unique A,
end
lemma det_mul_aux {M N : matrix n n R} {p : n → n} (H : ¬bijective p) :
∑ σ : perm n, (ε σ) * ∏ x, (M (σ x) (p x) * N (p x) x) = 0 :=
begin
obtain ⟨i, j, hpij, hij⟩ : ∃ i j, p i = p j ∧ i ≠ j,
{ rw [← fintype.injective_iff_bijective, injective] at H,
push_neg at H,
exact H },
exact sum_involution
(λ σ _, σ * swap i j)
(λ σ _,
have ∏ x, M (σ x) (p x) = ∏ x, M ((σ * swap i j) x) (p x),
from fintype.prod_equiv (swap i j) _ _ (by simp [apply_swap_eq_self hpij]),
by simp [this, sign_swap hij, prod_mul_distrib])
(λ σ _ _, (not_congr mul_swap_eq_iff).mpr hij)
(λ _ _, mem_univ _)
(λ σ _, mul_swap_involutive i j σ)
end
@[simp] lemma det_mul (M N : matrix n n R) : det (M ⬝ N) = det M * det N :=
calc det (M ⬝ N) = ∑ p : n → n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) :
by simp only [det_apply', mul_apply, prod_univ_sum, mul_sum,
fintype.pi_finset_univ]; rw [finset.sum_comm]
... = ∑ p in (@univ (n → n) _).filter bijective, ∑ σ : perm n,
ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) :
eq.symm $ sum_subset (filter_subset _ _)
(λ f _ hbij, det_mul_aux $ by simpa only [true_and, mem_filter, mem_univ] using hbij)
... = ∑ τ : perm n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (τ i) * N (τ i) i) :
sum_bij (λ p h, equiv.of_bijective p (mem_filter.1 h).2) (λ _ _, mem_univ _)
(λ _ _, rfl) (λ _ _ _ _ h, by injection h)
(λ b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, coe_fn_injective rfl⟩)
... = ∑ σ : perm n, ∑ τ : perm n, (∏ i, N (σ i) i) * ε τ * (∏ j, M (τ j) (σ j)) :
by simp only [mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc]
... = ∑ σ : perm n, ∑ τ : perm n, (((∏ i, N (σ i) i) * (ε σ * ε τ)) * ∏ i, M (τ i) i) :
sum_congr rfl (λ σ _, fintype.sum_equiv (equiv.mul_right σ⁻¹) _ _
(λ τ,
have ∏ j, M (τ j) (σ j) = ∏ j, M ((τ * σ⁻¹) j) j,
by { rw ← σ⁻¹.prod_comp, simp only [equiv.perm.coe_mul, apply_inv_self] },
have h : ε σ * ε (τ * σ⁻¹) = ε τ :=
calc ε σ * ε (τ * σ⁻¹) = ε ((τ * σ⁻¹) * σ) :
by { rw [mul_comm, sign_mul (τ * σ⁻¹)], simp only [int.cast_mul, units.coe_mul] }
... = ε τ : by simp only [inv_mul_cancel_right],
by { simp_rw [equiv.coe_mul_right, h], simp only [this] }))
... = det M * det N : by simp only [det_apply', finset.mul_sum, mul_comm, mul_left_comm]
/-- The determinant of a matrix, as a monoid homomorphism. -/
def det_monoid_hom : matrix n n R →* R :=
{ to_fun := det,
map_one' := det_one,
map_mul' := det_mul }
@[simp] lemma coe_det_monoid_hom : (det_monoid_hom : matrix n n R → R) = det := rfl
/-- On square matrices, `mul_comm` applies under `det`. -/
lemma det_mul_comm (M N : matrix m m R) : det (M ⬝ N) = det (N ⬝ M) :=
by rw [det_mul, det_mul, mul_comm]
/-- On square matrices, `mul_left_comm` applies under `det`. -/
lemma det_mul_left_comm (M N P : matrix m m R) : det (M ⬝ (N ⬝ P)) = det (N ⬝ (M ⬝ P)) :=
by rw [←matrix.mul_assoc, ←matrix.mul_assoc, det_mul, det_mul_comm M N, ←det_mul]
/-- On square matrices, `mul_right_comm` applies under `det`. -/
lemma det_mul_right_comm (M N P : matrix m m R) :
det (M ⬝ N ⬝ P) = det (M ⬝ P ⬝ N) :=
by rw [matrix.mul_assoc, matrix.mul_assoc, det_mul, det_mul_comm N P, ←det_mul]
lemma det_units_conj (M : units (matrix m m R)) (N : matrix m m R) :
det (↑M ⬝ N ⬝ ↑M⁻¹ : matrix m m R) = det N :=
by rw [det_mul_right_comm, ←mul_eq_mul, ←mul_eq_mul, units.mul_inv, one_mul]
lemma det_units_conj' (M : units (matrix m m R)) (N : matrix m m R) :
det (↑M⁻¹ ⬝ N ⬝ ↑M : matrix m m R) = det N := det_units_conj M⁻¹ N
/-- Transposing a matrix preserves the determinant. -/
@[simp] lemma det_transpose (M : matrix n n R) : Mᵀ.det = M.det :=
begin
rw [det_apply', det_apply'],
refine fintype.sum_bijective _ inv_involutive.bijective _ _ _,
intros σ,
rw sign_inv,
congr' 1,
apply fintype.prod_equiv σ,
intros,
simp
end
/-- Permuting the columns changes the sign of the determinant. -/
lemma det_permute (σ : perm n) (M : matrix n n R) : matrix.det (λ i, M (σ i)) = σ.sign * M.det :=
((det_row_multilinear : alternating_map R (n → R) R n).map_perm M σ).trans
(by simp [units.smul_def])
/-- Permuting rows and columns with the same equivalence has no effect. -/
@[simp]
lemma det_minor_equiv_self (e : n ≃ m) (A : matrix m m R) :
det (A.minor e e) = det A :=
begin
rw [det_apply', det_apply'],
apply fintype.sum_equiv (equiv.perm_congr e),
intro σ,
rw equiv.perm.sign_perm_congr e σ,
congr' 1,
apply fintype.prod_equiv e,
intro i,
rw [equiv.perm_congr_apply, equiv.symm_apply_apply, minor_apply],
end
/-- Reindexing both indices along the same equivalence preserves the determinant.
For the `simp` version of this lemma, see `det_minor_equiv_self`; this one is unsuitable because
`matrix.reindex_apply` unfolds `reindex` first.
-/
lemma det_reindex_self (e : m ≃ n) (A : matrix m m R) : det (reindex e e A) = det A :=
det_minor_equiv_self e.symm A
/-- The determinant of a permutation matrix equals its sign. -/
@[simp] lemma det_permutation (σ : perm n) :
matrix.det (σ.to_pequiv.to_matrix : matrix n n R) = σ.sign :=
by rw [←matrix.mul_one (σ.to_pequiv.to_matrix : matrix n n R), pequiv.to_pequiv_mul_matrix,
det_permute, det_one, mul_one]
@[simp] lemma det_smul {A : matrix n n R} {c : R} : det (c • A) = c ^ fintype.card n * det A :=
calc det (c • A) = det (matrix.mul (diagonal (λ _, c)) A) : by rw [smul_eq_diagonal_mul]
... = det (diagonal (λ _, c)) * det A : det_mul _ _
... = c ^ fintype.card n * det A : by simp [card_univ]
/-- Multiplying each row by a fixed `v i` multiplies the determinant by
the product of the `v`s. -/
lemma det_mul_row (v : n → R) (A : matrix n n R) :
det (λ i j, v j * A i j) = (∏ i, v i) * det A :=
calc det (λ i j, v j * A i j) = det (A ⬝ diagonal v) : congr_arg det $ by { ext, simp [mul_comm] }
... = (∏ i, v i) * det A : by rw [det_mul, det_diagonal, mul_comm]
/-- Multiplying each column by a fixed `v j` multiplies the determinant by
the product of the `v`s. -/
lemma det_mul_column (v : n → R) (A : matrix n n R) :
det (λ i j, v i * A i j) = (∏ i, v i) * det A :=
multilinear_map.map_smul_univ _ v A
@[simp] lemma det_pow (M : matrix m m R) (n : ℕ) : det (M ^ n) = (det M) ^ n :=
(det_monoid_hom : matrix m m R →* R).map_pow M n
section hom_map
variables {S : Type w} [comm_ring S]
lemma ring_hom.map_det {M : matrix n n R} {f : R →+* S} :
f M.det = matrix.det (f.map_matrix M) :=
by simp [matrix.det_apply', f.map_sum, f.map_prod]
lemma alg_hom.map_det [algebra R S] {T : Type z} [comm_ring T] [algebra R T]
{M : matrix n n S} {f : S →ₐ[R] T} :
f M.det = matrix.det ((f : S →+* T).map_matrix M) :=
by rw [← alg_hom.coe_to_ring_hom, ring_hom.map_det]
end hom_map
section det_zero
/-!
### `det_zero` section
Prove that a matrix with a repeated column has determinant equal to zero.
-/
lemma det_eq_zero_of_row_eq_zero {A : matrix n n R} (i : n) (h : ∀ j, A i j = 0) : det A = 0 :=
(det_row_multilinear : alternating_map R (n → R) R n).map_coord_zero i (funext h)
lemma det_eq_zero_of_column_eq_zero {A : matrix n n R} (j : n) (h : ∀ i, A i j = 0) : det A = 0 :=
by { rw ← det_transpose, exact det_eq_zero_of_row_eq_zero j h, }
variables {M : matrix n n R} {i j : n}
/-- If a matrix has a repeated row, the determinant will be zero. -/
theorem det_zero_of_row_eq (i_ne_j : i ≠ j) (hij : M i = M j) : M.det = 0 :=
(det_row_multilinear : alternating_map R (n → R) R n).map_eq_zero_of_eq M hij i_ne_j
/-- If a matrix has a repeated column, the determinant will be zero. -/
theorem det_zero_of_column_eq (i_ne_j : i ≠ j) (hij : ∀ k, M k i = M k j) : M.det = 0 :=
by { rw [← det_transpose, det_zero_of_row_eq i_ne_j], exact funext hij }
end det_zero
lemma det_update_row_add (M : matrix n n R) (j : n) (u v : n → R) :
det (update_row M j $ u + v) = det (update_row M j u) + det (update_row M j v) :=
(det_row_multilinear : alternating_map R (n → R) R n).map_add M j u v
lemma det_update_column_add (M : matrix n n R) (j : n) (u v : n → R) :
det (update_column M j $ u + v) = det (update_column M j u) + det (update_column M j v) :=
begin
rw [← det_transpose, ← update_row_transpose, det_update_row_add],
simp [update_row_transpose, det_transpose]
end
lemma det_update_row_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) :
det (update_row M j $ s • u) = s * det (update_row M j u) :=
(det_row_multilinear : alternating_map R (n → R) R n).map_smul M j s u
lemma det_update_column_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) :
det (update_column M j $ s • u) = s * det (update_column M j u) :=
begin
rw [← det_transpose, ← update_row_transpose, det_update_row_smul],
simp [update_row_transpose, det_transpose]
end
section det_eq
/-! ### `det_eq` section
Lemmas showing the determinant is invariant under a variety of operations.
-/
lemma det_eq_of_eq_mul_det_one {A B : matrix n n R}
(C : matrix n n R) (hC : det C = 1) (hA : A = B ⬝ C) : det A = det B :=
calc det A = det (B ⬝ C) : congr_arg _ hA
... = det B * det C : det_mul _ _
... = det B : by rw [hC, mul_one]
lemma det_eq_of_eq_det_one_mul {A B : matrix n n R}
(C : matrix n n R) (hC : det C = 1) (hA : A = C ⬝ B) : det A = det B :=
calc det A = det (C ⬝ B) : congr_arg _ hA
... = det C * det B : det_mul _ _
... = det B : by rw [hC, one_mul]
lemma det_update_row_add_self (A : matrix n n R) {i j : n} (hij : i ≠ j) :
det (update_row A i (A i + A j)) = det A :=
by simp [det_update_row_add,
det_zero_of_row_eq hij ((update_row_self).trans (update_row_ne hij.symm).symm)]
lemma det_update_column_add_self (A : matrix n n R) {i j : n} (hij : i ≠ j) :
det (update_column A i (λ k, A k i + A k j)) = det A :=
by { rw [← det_transpose, ← update_row_transpose, ← det_transpose A],
exact det_update_row_add_self Aᵀ hij }
lemma det_update_row_add_smul_self (A : matrix n n R) {i j : n} (hij : i ≠ j) (c : R) :
det (update_row A i (A i + c • A j)) = det A :=
by simp [det_update_row_add, det_update_row_smul,
det_zero_of_row_eq hij ((update_row_self).trans (update_row_ne hij.symm).symm)]
lemma det_update_column_add_smul_self (A : matrix n n R) {i j : n} (hij : i ≠ j) (c : R) :
det (update_column A i (λ k, A k i + c • A k j)) = det A :=
by { rw [← det_transpose, ← update_row_transpose, ← det_transpose A],
exact det_update_row_add_smul_self Aᵀ hij c }
lemma det_eq_of_forall_row_eq_smul_add_const_aux
{A B : matrix n n R} {s : finset n} : ∀ (c : n → R) (hs : ∀ i, i ∉ s → c i = 0)
(k : n) (hk : k ∉ s) (A_eq : ∀ i j, A i j = B i j + c i * B k j),
det A = det B :=
begin
revert B,
refine s.induction_on _ _,
{ intros A c hs k hk A_eq,
have : ∀ i, c i = 0,
{ intros i,
specialize hs i,
contrapose! hs,
simp [hs] },
congr,
ext i j,
rw [A_eq, this, zero_mul, add_zero], },
{ intros i s hi ih B c hs k hk A_eq,
have hAi : A i = B i + c i • B k := funext (A_eq i),
rw [@ih (update_row B i (A i)) (function.update c i 0), hAi,
det_update_row_add_smul_self],
{ exact mt (λ h, show k ∈ insert i s, from h ▸ finset.mem_insert_self _ _) hk },
{ intros i' hi',
rw function.update_apply,
split_ifs with hi'i, { refl },
{ exact hs i' (λ h, hi' ((finset.mem_insert.mp h).resolve_left hi'i)) } },
{ exact λ h, hk (finset.mem_insert_of_mem h) },
{ intros i' j',
rw [update_row_apply, function.update_apply],
split_ifs with hi'i,
{ simp [hi'i] },
rw [A_eq, update_row_ne (λ (h : k = i), hk $ h ▸ finset.mem_insert_self k s)] } }
end
/-- If you add multiples of row `B k` to other rows, the determinant doesn't change. -/
lemma det_eq_of_forall_row_eq_smul_add_const
{A B : matrix n n R} (c : n → R) (k : n) (hk : c k = 0)
(A_eq : ∀ i j, A i j = B i j + c i * B k j) :
det A = det B :=
det_eq_of_forall_row_eq_smul_add_const_aux c
(λ i, not_imp_comm.mp $ λ hi, finset.mem_erase.mpr
⟨mt (λ (h : i = k), show c i = 0, from h.symm ▸ hk) hi, finset.mem_univ i⟩)
k (finset.not_mem_erase k finset.univ) A_eq
lemma det_eq_of_forall_row_eq_smul_add_pred_aux {n : ℕ} (k : fin (n + 1)) :
∀ (c : fin n → R) (hc : ∀ (i : fin n), k < i.succ → c i = 0)
{M N : matrix (fin n.succ) (fin n.succ) R}
(h0 : ∀ j, M 0 j = N 0 j)
(hsucc : ∀ (i : fin n) j, M i.succ j = N i.succ j + c i * M i.cast_succ j),
det M = det N :=
begin
refine fin.induction _ (λ k ih, _) k;
intros c hc M N h0 hsucc,
{ congr,
ext i j,
refine fin.cases (h0 j) (λ i, _) i,
rw [hsucc, hc i (fin.succ_pos _), zero_mul, add_zero] },
set M' := update_row M k.succ (N k.succ) with hM',
have hM : M = update_row M' k.succ (M' k.succ + c k • M k.cast_succ),
{ ext i j,
by_cases hi : i = k.succ,
{ simp [hi, hM', hsucc, update_row_self] },
rw [update_row_ne hi, hM', update_row_ne hi] },
have k_ne_succ : k.cast_succ ≠ k.succ := (fin.cast_succ_lt_succ k).ne,
have M_k : M k.cast_succ = M' k.cast_succ := (update_row_ne k_ne_succ).symm,
rw [hM, M_k, det_update_row_add_smul_self M' k_ne_succ.symm, ih (function.update c k 0)],
{ intros i hi,
rw [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ, fin.coe_succ, nat.lt_succ_iff] at hi,
rw function.update_apply,
split_ifs with hik, { refl },
exact hc _ (fin.succ_lt_succ_iff.mpr (lt_of_le_of_ne hi (ne.symm hik))) },
{ rwa [hM', update_row_ne (fin.succ_ne_zero _).symm] },
intros i j,
rw function.update_apply,
split_ifs with hik,
{ rw [zero_mul, add_zero, hM', hik, update_row_self] },
rw [hM', update_row_ne ((fin.succ_injective _).ne hik), hsucc],
by_cases hik2 : k < i,
{ simp [hc i (fin.succ_lt_succ_iff.mpr hik2)] },
rw update_row_ne,
apply ne_of_lt,
rwa [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ, fin.coe_succ, nat.lt_succ_iff, ← not_lt]
end
/-- If you add multiples of previous rows to the next row, the determinant doesn't change. -/
lemma det_eq_of_forall_row_eq_smul_add_pred {n : ℕ}
{A B : matrix (fin (n + 1)) (fin (n + 1)) R} (c : fin n → R)
(A_zero : ∀ j, A 0 j = B 0 j)
(A_succ : ∀ (i : fin n) j, A i.succ j = B i.succ j + c i * A i.cast_succ j) :
det A = det B :=
det_eq_of_forall_row_eq_smul_add_pred_aux (fin.last _) c
(λ i hi, absurd hi (not_lt_of_ge (fin.le_last _)))
A_zero A_succ
/-- If you add multiples of previous columns to the next columns, the determinant doesn't change. -/
lemma det_eq_of_forall_col_eq_smul_add_pred {n : ℕ}
{A B : matrix (fin (n + 1)) (fin (n + 1)) R} (c : fin n → R)
(A_zero : ∀ i, A i 0 = B i 0)
(A_succ : ∀ i (j : fin n), A i j.succ = B i j.succ + c j * A i j.cast_succ) :
det A = det B :=
by { rw [← det_transpose A, ← det_transpose B],
exact det_eq_of_forall_row_eq_smul_add_pred c A_zero (λ i j, A_succ j i) }
end det_eq
@[simp] lemma det_block_diagonal {o : Type*} [fintype o] [decidable_eq o] (M : o → matrix n n R) :
(block_diagonal M).det = ∏ k, (M k).det :=
begin
-- Rewrite the determinants as a sum over permutations.
simp_rw [det_apply'],
-- The right hand side is a product of sums, rewrite it as a sum of products.
rw finset.prod_sum,
simp_rw [finset.mem_univ, finset.prod_attach_univ, finset.univ_pi_univ],
-- We claim that the only permutations contributing to the sum are those that
-- preserve their second component.
let preserving_snd : finset (equiv.perm (n × o)) :=
finset.univ.filter (λ σ, ∀ x, (σ x).snd = x.snd),
have mem_preserving_snd : ∀ {σ : equiv.perm (n × o)},
σ ∈ preserving_snd ↔ ∀ x, (σ x).snd = x.snd :=
λ σ, finset.mem_filter.trans ⟨λ h, h.2, λ h, ⟨finset.mem_univ _, h⟩⟩,
rw ← finset.sum_subset (finset.subset_univ preserving_snd) _,
-- And that these are in bijection with `o → equiv.perm m`.
rw (finset.sum_bij (λ (σ : ∀ (k : o), k ∈ finset.univ → equiv.perm n) _,
prod_congr_left (λ k, σ k (finset.mem_univ k))) _ _ _ _).symm,
{ intros σ _,
rw mem_preserving_snd,
rintros ⟨k, x⟩,
simp only [prod_congr_left_apply] },
{ intros σ _,
rw [finset.prod_mul_distrib, ←finset.univ_product_univ, finset.prod_product, finset.prod_comm],
simp only [sign_prod_congr_left, units.coe_prod, int.cast_prod, block_diagonal_apply_eq,
prod_congr_left_apply] },
{ intros σ σ' _ _ eq,
ext x hx k,
simp only at eq,
have : ∀ k x, prod_congr_left (λ k, σ k (finset.mem_univ _)) (k, x) =
prod_congr_left (λ k, σ' k (finset.mem_univ _)) (k, x) :=
λ k x, by rw eq,
simp only [prod_congr_left_apply, prod.mk.inj_iff] at this,
exact (this k x).1 },
{ intros σ hσ,
rw mem_preserving_snd at hσ,
have hσ' : ∀ x, (σ⁻¹ x).snd = x.snd,
{ intro x, conv_rhs { rw [← perm.apply_inv_self σ x, hσ] } },
have mk_apply_eq : ∀ k x, ((σ (x, k)).fst, k) = σ (x, k),
{ intros k x,
ext,
{ simp only},
{ simp only [hσ] } },
have mk_inv_apply_eq : ∀ k x, ((σ⁻¹ (x, k)).fst, k) = σ⁻¹ (x, k),
{ intros k x,
conv_lhs { rw ← perm.apply_inv_self σ (x, k) },
ext,
{ simp only [apply_inv_self] },
{ simp only [hσ'] } },
refine ⟨λ k _, ⟨λ x, (σ (x, k)).fst, λ x, (σ⁻¹ (x, k)).fst, _, _⟩, _, _⟩,
{ intro x,
simp only [mk_apply_eq, inv_apply_self] },
{ intro x,
simp only [mk_inv_apply_eq, apply_inv_self] },
{ apply finset.mem_univ },
{ ext ⟨k, x⟩,
{ simp only [coe_fn_mk, prod_congr_left_apply] },
{ simp only [prod_congr_left_apply, hσ] } } },
{ intros σ _ hσ,
rw mem_preserving_snd at hσ,
obtain ⟨⟨k, x⟩, hkx⟩ := not_forall.mp hσ,
rw [finset.prod_eq_zero (finset.mem_univ (k, x)), mul_zero],
rw [← @prod.mk.eta _ _ (σ (k, x)), block_diagonal_apply_ne],
exact hkx }
end
/-- The determinant of a 2x2 block matrix with the lower-left block equal to zero is the product of
the determinants of the diagonal blocks. For the generalization to any number of blocks, see
`matrix.upper_block_triangular_det`. -/
lemma upper_two_block_triangular_det
(A : matrix m m R) (B : matrix m n R) (D : matrix n n R) :
(matrix.from_blocks A B 0 D).det = A.det * D.det :=
begin
classical,
simp_rw det_apply',
convert
(sum_subset (subset_univ ((sum_congr_hom m n).range : set (perm (m ⊕ n))).to_finset) _).symm,
rw sum_mul_sum,
simp_rw univ_product_univ,
rw (sum_bij (λ (σ : perm m × perm n) _, equiv.sum_congr σ.fst σ.snd) _ _ _ _).symm,
{ intros σ₁₂ h,
simp only [],
erw [set.mem_to_finset, monoid_hom.mem_range],
use σ₁₂,
simp only [sum_congr_hom_apply] },
{ simp only [forall_prop_of_true, prod.forall, mem_univ],
intros σ₁ σ₂,
rw fintype.prod_sum_type,
simp_rw [equiv.sum_congr_apply, sum.map_inr, sum.map_inl, from_blocks_apply₁₁,
from_blocks_apply₂₂],
have hr : ∀ (a b c d : R), (a * b) * (c * d) = a * c * (b * d), { intros, ac_refl },
rw hr,
congr,
rw [sign_sum_congr, units.coe_mul, int.cast_mul] },
{ intros σ₁ σ₂ h₁ h₂,
dsimp only [],
intro h,
have h2 : ∀ x, perm.sum_congr σ₁.fst σ₁.snd x = perm.sum_congr σ₂.fst σ₂.snd x,
{ intro x, exact congr_fun (congr_arg to_fun h) x },
simp only [sum.map_inr, sum.map_inl, perm.sum_congr_apply, sum.forall] at h2,
ext,
{ exact h2.left x },
{ exact h2.right x }},
{ intros σ hσ,
erw [set.mem_to_finset, monoid_hom.mem_range] at hσ,
obtain ⟨σ₁₂, hσ₁₂⟩ := hσ,
use σ₁₂,
rw ←hσ₁₂,
simp },
{ intros σ hσ hσn,
have h1 : ¬ (∀ x, ∃ y, sum.inl y = σ (sum.inl x)),
{ by_contradiction,
rw set.mem_to_finset at hσn,
apply absurd (mem_sum_congr_hom_range_of_perm_maps_to_inl _) hσn,
rintros x ⟨a, ha⟩,
rw [←ha], exact h a },
obtain ⟨a, ha⟩ := not_forall.mp h1,
cases hx : σ (sum.inl a) with a2 b,
{ have hn := (not_exists.mp ha) a2,
exact absurd hx.symm hn },
{ rw [finset.prod_eq_zero (finset.mem_univ (sum.inl a)), mul_zero],
rw [hx, from_blocks_apply₂₁], refl }}
end
/-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along column 0. -/
lemma det_succ_column_zero {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) :
det A = ∑ i : fin n.succ, (-1) ^ (i : ℕ) * A i 0 *
det (A.minor i.succ_above fin.succ) :=
begin
rw [matrix.det_apply, finset.univ_perm_fin_succ, ← finset.univ_product_univ],
simp only [finset.sum_map, equiv.to_embedding_apply, finset.sum_product, matrix.minor],
refine finset.sum_congr rfl (λ i _, fin.cases _ (λ i, _) i),
{ simp only [fin.prod_univ_succ, matrix.det_apply, finset.mul_sum,
equiv.perm.decompose_fin_symm_apply_zero, fin.coe_zero, one_mul,
equiv.perm.decompose_fin.symm_sign, equiv.swap_self, if_true, id.def, eq_self_iff_true,
equiv.perm.decompose_fin_symm_apply_succ, fin.succ_above_zero, equiv.coe_refl, pow_zero,
mul_smul_comm] },
-- `univ_perm_fin_succ` gives a different embedding of `perm (fin n)` into
-- `perm (fin n.succ)` than the determinant of the submatrix we want,
-- permute `A` so that we get the correct one.
have : (-1 : R) ^ (i : ℕ) = i.cycle_range.sign,
{ simp [fin.sign_cycle_range] },
rw [fin.coe_succ, pow_succ, this, mul_assoc, mul_assoc, mul_left_comm ↑(equiv.perm.sign _),
← det_permute, matrix.det_apply, finset.mul_sum, finset.mul_sum],
-- now we just need to move the corresponding parts to the same place
refine finset.sum_congr rfl (λ σ _, _),
rw [equiv.perm.decompose_fin.symm_sign, if_neg (fin.succ_ne_zero i)],
calc ((-1) * σ.sign : ℤ) • ∏ i', A (equiv.perm.decompose_fin.symm (fin.succ i, σ) i') i'
= ((-1) * σ.sign : ℤ) • (A (fin.succ i) 0 *
∏ i', A (((fin.succ i).succ_above) (fin.cycle_range i (σ i'))) i'.succ) :
by simp only [fin.prod_univ_succ, fin.succ_above_cycle_range,
equiv.perm.decompose_fin_symm_apply_zero, equiv.perm.decompose_fin_symm_apply_succ]
... = (-1) * (A (fin.succ i) 0 * (σ.sign : ℤ) •
∏ i', A (((fin.succ i).succ_above) (fin.cycle_range i (σ i'))) i'.succ) :
by simp only [mul_assoc, mul_comm, neg_mul_eq_neg_mul_symm, one_mul, gsmul_eq_mul, neg_inj,
neg_smul, fin.succ_above_cycle_range],
end
/-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along row 0. -/
lemma det_succ_row_zero {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) :
det A = ∑ j : fin n.succ, (-1) ^ (j : ℕ) * A 0 j *
det (A.minor fin.succ j.succ_above) :=
by { rw [← det_transpose A, det_succ_column_zero],
refine finset.sum_congr rfl (λ i _, _),
rw [← det_transpose],
simp only [transpose_apply, transpose_minor, transpose_transpose] }
/-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along row `i`. -/
lemma det_succ_row {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) (i : fin n.succ) :
det A = ∑ j : fin n.succ, (-1) ^ (i + j : ℕ) * A i j *
det (A.minor i.succ_above j.succ_above) :=
begin
simp_rw [pow_add, mul_assoc, ← mul_sum],
have : det A = (-1 : R) ^ (i : ℕ) * (i.cycle_range⁻¹).sign * det A,
{ calc det A = ↑((-1 : units ℤ) ^ (i : ℕ) * (-1 : units ℤ) ^ (i : ℕ) : units ℤ) * det A :
by simp
... = (-1 : R) ^ (i : ℕ) * (i.cycle_range⁻¹).sign * det A :
by simp [-int.units_mul_self] },
rw [this, mul_assoc],
congr,
rw [← det_permute, det_succ_row_zero],
refine finset.sum_congr rfl (λ j _, _),
rw [mul_assoc, matrix.minor, matrix.minor],
congr,
{ rw [equiv.perm.inv_def, fin.cycle_range_symm_zero] },
{ ext i' j',
rw [equiv.perm.inv_def, fin.cycle_range_symm_succ] },
end
/-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along column `j`. -/
lemma det_succ_column {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) (j : fin n.succ) :
det A = ∑ i : fin n.succ, (-1) ^ (i + j : ℕ) * A i j *
det (A.minor i.succ_above j.succ_above) :=
by { rw [← det_transpose, det_succ_row _ j],
refine finset.sum_congr rfl (λ i _, _),
rw [add_comm, ← det_transpose, transpose_apply, transpose_minor, transpose_transpose] }
end matrix
|
866fe88fd00f952ff2c8f3672ac6a0c9e6cc3ace | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/algebra/group_ring_action.lean | 60b929ad6e23837bda8ff46b70315bd5caf8b491 | [
"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 | 5,899 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import group_theory.group_action.group
import data.equiv.ring
import ring_theory.subring
/-!
# Group action on rings
This file defines the typeclass of monoid acting on semirings `mul_semiring_action M R`,
and the corresponding typeclass of invariant subrings.
Note that `algebra` does not satisfy the axioms of `mul_semiring_action`.
## Implementation notes
There is no separate typeclass for group acting on rings, group acting on fields, etc.
They are all grouped under `mul_semiring_action`.
## Tags
group action, invariant subring
-/
universes u v
open_locale big_operators
/-- Typeclass for multiplicative actions by monoids on semirings. -/
class mul_semiring_action (M : Type u) [monoid M] (R : Type v) [semiring R]
extends distrib_mul_action M R :=
(smul_one : ∀ (g : M), (g • 1 : R) = 1)
(smul_mul : ∀ (g : M) (x y : R), g • (x * y) = (g • x) * (g • y))
export mul_semiring_action (smul_one)
section semiring
variables (M G : Type u) [monoid M] [group G]
variables (A R S F : Type v) [add_monoid A] [semiring R] [comm_semiring S] [field F]
variables {M R}
lemma smul_mul' [mul_semiring_action M R] (g : M) (x y : R) :
g • (x * y) = (g • x) * (g • y) :=
mul_semiring_action.smul_mul g x y
variables (M R)
/-- Each element of the monoid defines a additive monoid homomorphism. -/
def distrib_mul_action.to_add_monoid_hom [distrib_mul_action M A] (x : M) : A →+ A :=
{ to_fun := (•) x,
map_zero' := smul_zero x,
map_add' := smul_add x }
/-- Each element of the group defines an additive monoid isomorphism. -/
def distrib_mul_action.to_add_equiv [distrib_mul_action G A] (x : G) : A ≃+ A :=
{ .. distrib_mul_action.to_add_monoid_hom G A x,
.. mul_action.to_perm_hom G A x }
/-- Each element of the group defines an additive monoid homomorphism. -/
def distrib_mul_action.hom_add_monoid_hom [distrib_mul_action M A] : M →* add_monoid.End A :=
{ to_fun := distrib_mul_action.to_add_monoid_hom M A,
map_one' := add_monoid_hom.ext $ λ x, one_smul M x,
map_mul' := λ x y, add_monoid_hom.ext $ λ z, mul_smul x y z }
/-- Each element of the monoid defines a semiring homomorphism. -/
def mul_semiring_action.to_ring_hom [mul_semiring_action M R] (x : M) : R →+* R :=
{ map_one' := smul_one x,
map_mul' := smul_mul' x,
.. distrib_mul_action.to_add_monoid_hom M R x }
theorem to_ring_hom_injective [mul_semiring_action M R] [has_faithful_scalar M R] :
function.injective (mul_semiring_action.to_ring_hom M R) :=
λ m₁ m₂ h, eq_of_smul_eq_smul $ λ r, ring_hom.ext_iff.1 h r
/-- Each element of the group defines a semiring isomorphism. -/
def mul_semiring_action.to_semiring_equiv [mul_semiring_action G R] (x : G) : R ≃+* R :=
{ .. distrib_mul_action.to_add_equiv G R x,
.. mul_semiring_action.to_ring_hom G R x }
section
variables {M G R}
/-- A stronger version of `submonoid.distrib_mul_action`. -/
instance submonoid.mul_semiring_action [mul_semiring_action M R] (H : submonoid M) :
mul_semiring_action H R :=
{ smul := (•),
smul_one := λ h, smul_one (h : M),
smul_mul := λ h, smul_mul' (h : M),
.. H.distrib_mul_action }
/-- A stronger version of `subgroup.distrib_mul_action`. -/
instance subgroup.mul_semiring_action [mul_semiring_action G R] (H : subgroup G) :
mul_semiring_action H R :=
H.to_submonoid.mul_semiring_action
/-- A stronger version of `subsemiring.distrib_mul_action`. -/
instance subsemiring.mul_semiring_action {R'} [semiring R'] [mul_semiring_action R' R]
(H : subsemiring R') :
mul_semiring_action H R :=
H.to_submonoid.mul_semiring_action
/-- A stronger version of `subring.distrib_mul_action`. -/
instance subring.mul_semiring_action {R'} [ring R'] [mul_semiring_action R' R]
(H : subring R') :
mul_semiring_action H R :=
H.to_subsemiring.mul_semiring_action
end
section prod
variables [mul_semiring_action M R] [mul_semiring_action M S]
lemma list.smul_prod (g : M) (L : list R) : g • L.prod = (L.map $ (•) g).prod :=
(mul_semiring_action.to_ring_hom M R g).map_list_prod L
lemma multiset.smul_prod (g : M) (m : multiset S) : g • m.prod = (m.map $ (•) g).prod :=
(mul_semiring_action.to_ring_hom M S g).map_multiset_prod m
lemma smul_prod (g : M) {ι : Type*} (f : ι → S) (s : finset ι) :
g • ∏ i in s, f i = ∏ i in s, g • f i :=
(mul_semiring_action.to_ring_hom M S g).map_prod f s
end prod
section simp_lemmas
variables {M G A R}
attribute [simp] smul_one smul_mul' smul_zero smul_add
@[simp] lemma smul_inv' [mul_semiring_action M F] (x : M) (m : F) : x • m⁻¹ = (x • m)⁻¹ :=
(mul_semiring_action.to_ring_hom M F x).map_inv _
@[simp] lemma smul_pow [mul_semiring_action M R] (x : M) (m : R) (n : ℕ) :
x • m ^ n = (x • m) ^ n :=
begin
induction n with n ih,
{ rw [pow_zero, pow_zero], exact smul_one x },
{ rw [pow_succ, pow_succ], exact (smul_mul' x m (m ^ n)).trans (congr_arg _ ih) }
end
end simp_lemmas
end semiring
section ring
variables (M : Type u) [monoid M] {R : Type v} [ring R] [mul_semiring_action M R]
variables (S : subring R)
open mul_action
/-- A typeclass for subrings invariant under a `mul_semiring_action`. -/
class is_invariant_subring : Prop :=
(smul_mem : ∀ (m : M) {x : R}, x ∈ S → m • x ∈ S)
instance is_invariant_subring.to_mul_semiring_action [is_invariant_subring M S] :
mul_semiring_action M S :=
{ smul := λ m x, ⟨m • x, is_invariant_subring.smul_mem m x.2⟩,
one_smul := λ s, subtype.eq $ one_smul M s,
mul_smul := λ m₁ m₂ s, subtype.eq $ mul_smul m₁ m₂ s,
smul_add := λ m s₁ s₂, subtype.eq $ smul_add m s₁ s₂,
smul_zero := λ m, subtype.eq $ smul_zero m,
smul_one := λ m, subtype.eq $ smul_one m,
smul_mul := λ m s₁ s₂, subtype.eq $ smul_mul' m s₁ s₂ }
end ring
|
220b48e4a2eb5ddb3577bf16c440c74b47636b45 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/tactic/replacer.lean | 1569d876bd0865f906f008cebdc6d175477d6c62 | [
"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 | 5,821 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import tactic.core
/-!
# `def_replacer`
A mechanism for defining tactics for use in auto params, whose
meaning is defined incrementally through attributes.
-/
namespace tactic
meta def replacer_core {α : Type} [reflected α]
(ntac : name) (eval : ∀ β [reflected β], expr → tactic β) :
list name → tactic α
| [] := fail ("no implementation defined for " ++ to_string ntac)
| (n::ns) := do d ← get_decl n, let t := d.type,
tac ← do { mk_const n >>= eval (tactic α) } <|>
do { tac ← mk_const n >>= eval (tactic α → tactic α),
return (tac (replacer_core ns)) } <|>
do { tac ← mk_const n >>= eval (option (tactic α) → tactic α),
return (tac (guard (ns ≠ []) >> some (replacer_core ns))) },
tac
meta def replacer (ntac : name) {α : Type} [reflected α]
(F : Type → Type) (eF : ∀ β, reflected β → reflected (F β))
(R : ∀ β, F β → β) : tactic α :=
attribute.get_instances ntac >>= replacer_core ntac
(λ β eβ e, R β <$> @eval_expr' (F β) (eF β eβ) e)
meta def mk_replacer₁ : expr → nat → expr × expr
| (expr.pi n bi d b) i :=
let (e₁, e₂) := mk_replacer₁ b (i+1) in
(expr.pi n bi d e₁, (`(expr.pi n bi d) : expr) e₂)
| _ i := (expr.var i, expr.var 0)
meta def mk_replacer₂ (ntac : name) (v : expr × expr) : expr → nat → option expr
| (expr.pi n bi d b) i := do
b' ← mk_replacer₂ b (i+1),
some (expr.lam n bi d b')
| `(tactic %%β) i := some $
(expr.const ``replacer []).mk_app [
reflect ntac, β, reflect β,
expr.lam `γ binder_info.default `(Type) v.1,
expr.lam `γ binder_info.default `(Type) $
expr.lam `eγ binder_info.inst_implicit ((`(@reflected Type) : expr) β) v.2,
expr.lam `γ binder_info.default `(Type) $
expr.lam `f binder_info.default v.1 $
(list.range i).foldr (λ i e', e' (expr.var (i+2))) (expr.var 0)
]
| _ i := none
meta def mk_replacer (ntac : name) (e : expr) : tactic expr :=
mk_replacer₂ ntac (mk_replacer₁ e 0) e 0
meta def valid_types : expr → list expr
| (expr.pi n bi d b) := expr.pi n bi d <$> valid_types b
| `(tactic %%β) := [`(tactic.{0} %%β),
`(tactic.{0} %%β → tactic.{0} %%β),
`(option (tactic.{0} %%β) → tactic.{0} %%β)]
| _ := []
meta def replacer_attr (ntac : name) : user_attribute :=
{ name := ntac,
descr :=
"Replaces the definition of `" ++ to_string ntac ++ "`. This should be " ++
"applied to a definition with the type `tactic unit`, which will be " ++
"called whenever `" ++ to_string ntac ++ "` is called. The definition " ++
"can optionally have an argument of type `tactic unit` or " ++
"`option (tactic unit)` which refers to the previous definition, if any.",
after_set := some $ λ n _ _, do
d ← get_decl n,
base ← get_decl ntac,
guardb ((valid_types base.type).any (=ₐ d.type))
<|> fail format!"incorrect type for @[{ntac}]" }
/-- Define a new replaceable tactic. -/
meta def def_replacer (ntac : name) (ty : expr) : tactic unit :=
let nattr := ntac <.> "attr" in do
add_meta_definition nattr []
`(user_attribute) `(replacer_attr %%(reflect ntac)),
set_basic_attribute `user_attribute nattr tt,
v ← mk_replacer ntac ty,
add_meta_definition ntac [] ty v,
add_doc_string ntac $
"The `" ++ to_string ntac ++ "` tactic is a \"replaceable\" " ++
"tactic, which means that its meaning is defined by tactics that " ++
"are defined later with the `@[" ++ to_string ntac ++ "]` attribute. " ++
"It is intended for use with `auto_param`s for structure fields."
open interactive lean.parser
/--
`def_replacer foo` sets up a stub definition `foo : tactic unit`, which can
effectively be defined and re-defined later, by tagging definitions with `@[foo]`.
- `@[foo] meta def foo_1 : tactic unit := ...` replaces the current definition of `foo`.
- `@[foo] meta def foo_2 (old : tactic unit) : tactic unit := ...` replaces the current
definition of `foo`, and provides access to the previous definition via `old`.
(The argument can also be an `option (tactic unit)`, which is provided as `none` if
this is the first definition tagged with `@[foo]` since `def_replacer` was invoked.)
`def_replacer foo : α → β → tactic γ` allows the specification of a replacer with
custom input and output types. In this case all subsequent redefinitions must have the
same type, or the type `α → β → tactic γ → tactic γ` or
`α → β → option (tactic γ) → tactic γ` analogously to the previous cases.
-/
@[user_command] meta def def_replacer_cmd (_ : parse $ tk "def_replacer") : lean.parser unit :=
do ntac ← ident,
ty ← optional (tk ":" *> types.texpr),
match ty with
| (some p) := do t ← to_expr p, def_replacer ntac t
| none := def_replacer ntac `(tactic unit)
end
add_tactic_doc
{ name := "def_replacer",
category := doc_category.cmd,
decl_names := [`tactic.def_replacer_cmd],
tags := ["environment", "renaming"] }
meta def unprime : name → tactic name
| nn@(name.mk_string s n) :=
let s' := (s.split_on ''').head in
if s'.length < s.length then pure (name.mk_string s' n)
else fail format!"expecting primed name: {nn}"
| n := fail format!"invalid name: {n}"
@[user_attribute] meta def replaceable_attr : user_attribute :=
{ name := `replaceable,
descr := "make definition replaceable in dependent modules",
after_set := some $ λ n' _ _,
do { n ← unprime n',
d ← get_decl n',
«def_replacer» n d.type,
(replacer_attr n).set n' () tt } }
end tactic
|
adcbed7153802c501795fafedc2d09dfd782736f | 0845ae2ca02071debcfd4ac24be871236c01784f | /library/init/lean/compiler/initattr.lean | 5d5243def0cda12c902e32d4ea4fb6504a70c5c1 | [
"Apache-2.0"
] | permissive | GaloisInc/lean4 | 74c267eb0e900bfaa23df8de86039483ecbd60b7 | 228ddd5fdcd98dd4e9c009f425284e86917938aa | refs/heads/master | 1,643,131,356,301 | 1,562,715,572,000 | 1,562,715,572,000 | 192,390,898 | 0 | 0 | null | 1,560,792,750,000 | 1,560,792,749,000 | null | UTF-8 | Lean | false | false | 2,356 | 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
-/
prelude
import init.lean.environment
import init.lean.attributes
namespace Lean
private def getIOTypeArg : Expr → Option Expr
| (Expr.app (Expr.const `IO _) arg) := some arg
| _ := none
private def isUnitType : Expr → Bool
| (Expr.const `Unit _) := true
| _ := false
private def isIOUnit (type : Expr) : Bool :=
match getIOTypeArg type with
| some type => isUnitType type
| _ => false
def mkInitAttr : IO (ParametricAttribute Name) :=
registerParametricAttribute `init "initialization procedure for global references" $ fun env declName stx =>
match env.find declName with
| none => Except.error "unknown declaration"
| some decl =>
match attrParamSyntaxToIdentifier stx with
| some initFnName =>
match env.find initFnName with
| none => Except.error ("unknown initialization function '" ++ toString initFnName ++ "'")
| some initDecl =>
match getIOTypeArg initDecl.type with
| none => Except.error ("initialization function '" ++ toString initFnName ++ "' must have type of the form `IO <type>`")
| some initTypeArg =>
if decl.type == initTypeArg then Except.ok initFnName
else Except.error ("initialization function '" ++ toString initFnName ++ "' type mismatch")
| _ => match stx with
| Syntax.missing =>
if isIOUnit decl.type then Except.ok Name.anonymous
else Except.error "initialization function must have type `IO Unit`"
| _ => Except.error "unexpected kind of argument"
@[init mkInitAttr]
constant initAttr : ParametricAttribute Name := default _
def isIOUnitInitFn (env : Environment) (fn : Name) : Bool :=
match initAttr.getParam env fn with
| some Name.anonymous => true
| _ => false
@[export lean.get_init_fn_name_for_core]
def getInitFnNameFor (env : Environment) (fn : Name) : Option Name :=
match initAttr.getParam env fn with
| some Name.anonymous => none
| some n => some n
| _ => none
def hasInitAttr (env : Environment) (fn : Name) : Bool :=
(getInitFnNameFor env fn).isSome
def setInitAttr (env : Environment) (declName : Name) (initFnName : Name := Name.anonymous) : Except String Environment :=
initAttr.setParam env declName initFnName
end Lean
|
9e28ea7750d98e02f078f33102e64e4cdf1a34ac | 4e3bf8e2b29061457a887ac8889e88fa5aa0e34c | /lean/love08_operational_semantics_demo.lean | c712167b2d6c480cd7cb26e1fbaebfc1f6b48237 | [] | no_license | mukeshtiwari/logical_verification_2019 | 9f964c067a71f65eb8884743273fbeef99e6503d | 16f62717f55ed5b7b87e03ae0134791a9bef9b9a | refs/heads/master | 1,619,158,844,208 | 1,585,139,500,000 | 1,585,139,500,000 | 249,906,380 | 0 | 0 | null | 1,585,118,728,000 | 1,585,118,727,000 | null | UTF-8 | Lean | false | false | 8,807 | lean | /- LoVe Demo 8: Operational Semantics -/
import .lovelib
namespace LoVe
/- A Minimalistic Imperative Language -/
inductive program : Type
| skip {} : program
| assign : string → (state → ℕ) → program
| seq : program → program → program
| ite : (state → Prop) → program → program → program
| while : (state → Prop) → program → program
infixr ` ;; `:90 := program.seq
export program (skip assign seq ite while)
/- Big-Step Semantics -/
inductive big_step : (program × state) → state → Prop
| skip {s} :
big_step (skip, s) s
| assign {x a s} :
big_step (assign x a, s) (s{x ↦ a s})
| seq {S T s t u} (h₁ : big_step (S, s) t)
(h₂ : big_step (T, t) u) :
big_step (S ;; T, s) u
| ite_true {b : state → Prop} {S₁ S₂ s t} (hcond : b s)
(hbody : big_step (S₁, s) t) :
big_step (ite b S₁ S₂, s) t
| ite_false {b : state → Prop} {S₁ S₂ s t} (hcond : ¬ b s)
(hbody : big_step (S₂, s) t) :
big_step (ite b S₁ S₂, s) t
| while_true {b : state → Prop} {S s t u} (hcond : b s)
(hbody : big_step (S, s) t)
(hrest : big_step (while b S, t) u) :
big_step (while b S, s) u
| while_false {b : state → Prop} {S s} (hcond : ¬ b s) :
big_step (while b S, s) s
infix ` ⟹ `:110 := big_step
/- Lemmas about the Big-Step Semantics -/
lemma big_step_unique {S s l r} (hl : (S, s) ⟹ l)
(hr : (S, s) ⟹ r) :
l = r :=
begin
induction hl generalizing r,
{ cases hr,
refl },
{ cases hr,
refl },
{ cases hr,
rename hl_S S, rename hl_T T, rename hl_s s, rename hl_t t,
rename hl_u l, rename hr_t t', rename hl_h₁ hSst,
rename hl_h₂ hTtl, rename hr_h₂ hTt'r, rename hr_h₁ hSst',
rename hl_ih_h₁ ihS, rename hl_ih_h₂ ihT,
specialize ihS hSst',
rw ihS at *,
specialize ihT hTt'r,
rw ihT at *},
{ cases hr,
{ apply hl_ih,
cc },
{ apply hl_ih,
cc } },
{ cases hr,
{ apply hl_ih,
cc },
{ apply hl_ih,
assumption } },
{ cases hr,
{ specialize hl_ih_hbody hr_hbody,
rw hl_ih_hbody at *,
specialize hl_ih_hrest hr_hrest,
rw hl_ih_hrest at *},
{ cc } },
{ cases hr,
{ cc },
{ refl } }
end
@[simp] lemma big_step_skip_iff {s t} :
(skip, s) ⟹ t ↔ t = s :=
begin
apply iff.intro,
{ intro h,
cases h,
refl },
{ intro h,
rw h,
exact big_step.skip }
end
@[simp] lemma big_step_assign_iff {x a s t} :
(assign x a, s) ⟹ t ↔ t = s{x ↦ a s} :=
begin
apply iff.intro,
{ intro h,
cases h,
refl },
{ intro h,
rw h,
exact big_step.assign }
end
@[simp] lemma big_step_seq_iff {S₁ S₂ s t} :
(S₁ ;; S₂, s) ⟹ t ↔ (∃u, (S₁, s) ⟹ u ∧ (S₂, u) ⟹ t) :=
begin
apply iff.intro,
{ intro h,
cases h,
apply exists.intro,
apply and.intro,
repeat { assumption } },
{ intro h,
cases h,
cases h_h,
apply big_step.seq,
repeat { assumption } }
end
@[simp] lemma big_step_ite_iff {b S₁ S₂ s t} :
(ite b S₁ S₂, s) ⟹ t ↔
(b s ∧ (S₁, s) ⟹ t) ∨ (¬ b s ∧ (S₂, s) ⟹ t) :=
begin
apply iff.intro,
{ intro h,
cases h,
{ apply or.intro_left,
cc },
{ apply or.intro_right,
cc } },
{ intro h,
cases h;
cases h,
{ apply big_step.ite_true,
repeat { assumption }},
{ apply big_step.ite_false,
repeat { assumption }}
}
end
lemma big_step_while_iff {b S s u} :
(while b S, s) ⟹ u ↔
(∃t, b s ∧ (S, s) ⟹ t ∧ (while b S, t) ⟹ u)
∨ (¬ b s ∧ u = s) :=
begin
apply iff.intro,
{ intro h,
cases h,
{ apply or.intro_left,
apply exists.intro h_t,
cc },
{ apply or.intro_right,
cc } },
{ intro h,
cases h,
{ cases h,
cases h_h,
cases h_h_right,
apply big_step.while_true,
repeat { assumption } },
{ cases h,
rw h_right,
apply big_step.while_false,
assumption } }
end
@[simp] lemma big_step_while_true_iff {b : state → Prop} {S s u}
(hcond : b s) :
(while b S, s) ⟹ u ↔
(∃t, (S, s) ⟹ t ∧ (while b S, t) ⟹ u) :=
by rw [big_step_while_iff]; simp [hcond]
@[simp] lemma big_step_while_false_iff {b : state → Prop}
{S s t} (hcond : ¬ b s) :
(while b S, s) ⟹ t ↔ t = s :=
by rw [big_step_while_iff]; simp [hcond]
/- Small-Step Semantics -/
inductive small_step : program × state → program × state → Prop
| assign {x a s} :
small_step (assign x a, s) (skip, s{x ↦ a s})
| seq_step {S T s s'} (S') :
small_step (S, s) (S', s') →
small_step (S ;; T, s) (S' ;; T, s')
| seq_skip {T s} :
small_step (skip ;; T, s) (T, s)
| ite_true {b : state → Prop} {S₁ S₂ s} :
b s → small_step (ite b S₁ S₂, s) (S₁, s)
| ite_false {b : state → Prop} {S₁ S₂ s} :
¬ b s → small_step (ite b S₁ S₂, s) (S₂, s)
| while {b : state → Prop} {S s} :
small_step (while b S, s) (ite b (S ;; while b S) skip, s)
infixr ` ⇒ ` := small_step
infixr ` ⇒* ` : 100 := refl_trans small_step
/- Lemmas about the Small-Step Semantics -/
@[simp] lemma small_step_skip {S s t} :
¬ ((skip, s) ⇒ (S, t)) :=
by intro h; cases h
lemma small_step_seq_iff {S T s Ut} :
(S ;; T, s) ⇒ Ut ↔
(∃S' t, (S, s) ⇒ (S', t) ∧ Ut = (S' ;; T, t))
∨ (S = skip ∧ Ut = (T, s)) :=
begin
apply iff.intro,
{ intro h,
cases h,
{ apply or.intro_left,
apply exists.intro h_S',
apply exists.intro h_s',
cc },
{ apply or.intro_right,
cc } },
{ intro h,
cases h,
{ cases h,
cases h_h,
cases h_h_h,
rw h_h_h_right,
apply small_step.seq_step,
assumption },
{ cases h,
rw [h_left, h_right],
apply small_step.seq_skip } }
end
@[simp] lemma small_step_ite_iff {b S T s Us} :
(ite b S T, s) ⇒ Us ↔
(b s ∧ Us = (S, s)) ∨ (¬ b s ∧ Us = (T, s)) :=
begin
apply iff.intro,
{ intro h,
cases h,
{ apply or.intro_left,
cc },
{ apply or.intro_right,
cc } },
{ intro h,
cases h,
{ cases h,
rw h_right,
apply small_step.ite_true,
assumption },
{ cases h,
rw h_right,
apply small_step.ite_false,
assumption } }
end
/- **optional** Correspondence between the Big-Step and the
Small-Step Semantics -/
lemma refl_trans_small_step_seq {S₁ S₂ s u}
(h : (S₁, s) ⇒* (skip, u)) :
(S₁ ;; S₂, s) ⇒* (skip ;; S₂, u) :=
begin
apply refl_trans.lift
(λSs : program × state, (Ss.1 ;; S₂, Ss.2)) _ h,
intros Ss Ss' h,
cases Ss,
cases Ss',
dsimp,
apply small_step.seq_step,
assumption
end
lemma big_step_imp_refl_trans_small_step {S s t}
(h : (S, s) ⟹ t) :
(S, s) ⇒* (skip, t) :=
begin
induction h,
case big_step.skip { refl },
case big_step.assign {
exact refl_trans.single small_step.assign },
case big_step.seq : S₁ S₂ s t u h₁ h₂ ih₁ ih₂ {
transitivity,
exact refl_trans_small_step_seq ih₁,
exact ih₂.head small_step.seq_skip },
case big_step.ite_true : B S₁ S₂ s t hs hst ih {
exact ih.head (small_step.ite_true hs) },
case big_step.ite_false : B S₁ S₂ s t hs hst ih {
exact ih.head (small_step.ite_false hs) },
case big_step.while_true : B S s t u hs h₁ h₂ ih₁ ih₂ {
exact (refl_trans.head (small_step.while)
(refl_trans.head (small_step.ite_true hs)
(refl_trans.trans (refl_trans_small_step_seq ih₁)
(refl_trans.head small_step.seq_skip ih₂)))) },
case big_step.while_false : c p s hs {
exact (refl_trans.single small_step.while).tail
(small_step.ite_false hs) }
end
lemma big_step_of_small_step_of_big_step {S₀ S₁ s₀ s₁ s₂} :
(S₀, s₀) ⇒ (S₁, s₁) → (S₁, s₁) ⟹ s₂ → (S₀, s₀) ⟹ s₂ :=
begin
generalize hv₀ : (S₀, s₀) = v₀,
generalize hv₁ : (S₁, s₁) = v₀,
intro h,
induction h
generalizing S₀ s₀ S₁ s₁ s₂;
cases hv₁;
clear hv₁;
cases hv₀;
clear hv₀;
simp [*, big_step_while_true_iff] { contextual := tt },
{ intros u h₁ h₂,
use u,
exact and.intro (h_ih rfl rfl h₁) h₂ }
end
lemma refl_trans_small_step_imp_big_step {S s t} :
(S, s) ⇒* (skip, t) → (S, s) ⟹ t :=
begin
generalize hv₀ : (S, s) = v₀,
intro h,
induction h
using LoVe.refl_trans.head_induction_on
with v₀ v₁ h h' ih
generalizing S s;
cases hv₀;
clear hv₀,
{ exact big_step.skip },
{ cases v₁ with S' s',
specialize ih rfl,
exact big_step_of_small_step_of_big_step h ih }
end
lemma big_step_iff_refl_trans_small_step {S s t} :
(S, s) ⟹ t ↔ (S, s) ⇒* (skip, t) :=
iff.intro
big_step_imp_refl_trans_small_step
refl_trans_small_step_imp_big_step
end LoVe
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.