source stringlengths 17 118 | lean4 stringlengths 0 335k |
|---|---|
.lake/packages/mathlib/Mathlib/Data/Vector/Mem.lean | import Mathlib.Data.Vector.Basic
/-!
# Theorems about membership of elements in vectors
This file contains theorems for membership in a `v.toList` for a vector `v`.
Having the length available in the type allows some of the lemmas to be
simpler and more general than the original version for lists.
In particular we can avoid some assumptions about types being `Inhabited`,
and make more general statements about `head` and `tail`.
-/
namespace List
namespace Vector
variable {α β : Type*} {n : ℕ} (a a' : α)
@[simp]
theorem get_mem (i : Fin n) (v : Vector α n) : v.get i ∈ v.toList := List.get_mem _ _
theorem mem_iff_get (v : Vector α n) : a ∈ v.toList ↔ ∃ i, v.get i = a := by
simp only [List.mem_iff_get, Fin.exists_iff, Vector.get_eq_get_toList]
exact
⟨fun ⟨i, hi, h⟩ => ⟨i, by rwa [toList_length] at hi, h⟩, fun ⟨i, hi, h⟩ =>
⟨i, by rwa [toList_length], h⟩⟩
theorem notMem_nil : a ∉ (Vector.nil : Vector α 0).toList := by
simp
@[deprecated (since := "2025-05-23")] alias not_mem_nil := notMem_nil
theorem notMem_zero (v : Vector α 0) : a ∉ v.toList :=
(Vector.eq_nil v).symm ▸ notMem_nil a
@[deprecated (since := "2025-05-23")] alias not_mem_zero := notMem_zero
theorem mem_cons_iff (v : Vector α n) : a' ∈ (a ::ᵥ v).toList ↔ a' = a ∨ a' ∈ v.toList := by
rw [Vector.toList_cons, List.mem_cons]
theorem mem_succ_iff (v : Vector α (n + 1)) : a ∈ v.toList ↔ a = v.head ∨ a ∈ v.tail.toList := by
obtain ⟨a', v', h⟩ := exists_eq_cons v
simp_rw [h, Vector.mem_cons_iff, Vector.head_cons, Vector.tail_cons]
theorem mem_cons_self (v : Vector α n) : a ∈ (a ::ᵥ v).toList :=
(Vector.mem_iff_get a (a ::ᵥ v)).2 ⟨0, Vector.get_cons_zero a v⟩
@[simp]
theorem head_mem (v : Vector α (n + 1)) : v.head ∈ v.toList :=
(Vector.mem_iff_get v.head v).2 ⟨0, Vector.get_zero v⟩
theorem mem_cons_of_mem (v : Vector α n) (ha' : a' ∈ v.toList) : a' ∈ (a ::ᵥ v).toList :=
(Vector.mem_cons_iff a a' v).2 (Or.inr ha')
theorem mem_of_mem_tail (v : Vector α n) (ha : a ∈ v.tail.toList) : a ∈ v.toList := by
induction n with
| zero => exact False.elim (Vector.notMem_zero a v.tail ha)
| succ n _ => exact (mem_succ_iff a v).2 (Or.inr ha)
theorem mem_map_iff (b : β) (v : Vector α n) (f : α → β) :
b ∈ (v.map f).toList ↔ ∃ a : α, a ∈ v.toList ∧ f a = b := by
rw [Vector.toList_map, List.mem_map]
theorem notMem_map_zero (b : β) (v : Vector α 0) (f : α → β) : b ∉ (v.map f).toList := by
simpa only [Vector.eq_nil v, Vector.map_nil, Vector.toList_nil] using List.not_mem_nil
@[deprecated (since := "2025-05-23")] alias not_mem_map_zero := notMem_map_zero
theorem mem_map_succ_iff (b : β) (v : Vector α (n + 1)) (f : α → β) :
b ∈ (v.map f).toList ↔ f v.head = b ∨ ∃ a : α, a ∈ v.tail.toList ∧ f a = b := by
rw [mem_succ_iff, head_map, tail_map, mem_map_iff, @eq_comm _ b]
end Vector
end List |
.lake/packages/mathlib/Mathlib/Data/Vector/MapLemmas.lean | import Mathlib.Data.Vector.Basic
import Mathlib.Data.Vector.Snoc
/-!
This file establishes a set of normalization lemmas for `map`/`mapAccumr` operations on vectors
-/
variable {α β γ ζ σ σ₁ σ₂ φ : Type*} {n : ℕ} {s : σ} {s₁ : σ₁} {s₂ : σ₂}
namespace List
namespace Vector
/-!
## Fold nested `mapAccumr`s into one
-/
section Fold
section Unary
variable (xs : Vector α n) (f₁ : β → σ₁ → σ₁ × γ) (f₂ : α → σ₂ → σ₂ × β)
@[simp]
theorem mapAccumr_mapAccumr :
mapAccumr f₁ (mapAccumr f₂ xs s₂).snd s₁
= let m := (mapAccumr (fun x s =>
let r₂ := f₂ x s.snd
let r₁ := f₁ r₂.snd s.fst
((r₁.fst, r₂.fst), r₁.snd)
) xs (s₁, s₂))
(m.fst.fst, m.snd) := by
induction xs using Vector.revInductionOn generalizing s₁ s₂ <;> simp_all
@[simp]
theorem mapAccumr_map {s : σ₁} (f₂ : α → β) :
(mapAccumr f₁ (map f₂ xs) s) = (mapAccumr (fun x s => f₁ (f₂ x) s) xs s) := by
induction xs using Vector.revInductionOn generalizing s <;> simp_all
@[simp]
theorem map_mapAccumr {s : σ₂} (f₁ : β → γ) :
(map f₁ (mapAccumr f₂ xs s).snd) = (mapAccumr (fun x s =>
let r := (f₂ x s); (r.fst, f₁ r.snd)
) xs s).snd := by
induction xs using Vector.revInductionOn generalizing s <;> simp_all
@[simp]
theorem map_map (f₁ : β → γ) (f₂ : α → β) :
map f₁ (map f₂ xs) = map (fun x => f₁ <| f₂ x) xs := by
induction xs <;> simp_all
theorem map_pmap {p : α → Prop} (f₁ : β → γ) (f₂ : (a : α) → p a → β) (H : ∀ x ∈ xs.toList, p x) :
map f₁ (pmap f₂ xs H) = pmap (fun x hx => f₁ <| f₂ x hx) xs H := by
induction xs <;> simp_all
theorem pmap_map {p : β → Prop} (f₁ : (b : β) → p b → γ) (f₂ : α → β)
(H : ∀ x ∈ (xs.map f₂).toList, p x) :
pmap f₁ (map f₂ xs) H = pmap (fun x hx => f₁ (f₂ x) hx) xs (by simpa using H) := by
induction xs <;> simp_all
end Unary
section Binary
variable (xs : Vector α n) (ys : Vector β n)
@[simp]
theorem mapAccumr₂_mapAccumr_left (f₁ : γ → β → σ₁ → σ₁ × ζ) (f₂ : α → σ₂ → σ₂ × γ) :
(mapAccumr₂ f₁ (mapAccumr f₂ xs s₂).snd ys s₁)
= let m := (mapAccumr₂ (fun x y s =>
let r₂ := f₂ x s.snd
let r₁ := f₁ r₂.snd y s.fst
((r₁.fst, r₂.fst), r₁.snd)
) xs ys (s₁, s₂))
(m.fst.fst, m.snd) := by
induction xs, ys using Vector.revInductionOn₂ generalizing s₁ s₂ <;> simp_all
@[simp]
theorem map₂_map_left (f₁ : γ → β → ζ) (f₂ : α → γ) :
map₂ f₁ (map f₂ xs) ys = map₂ (fun x y => f₁ (f₂ x) y) xs ys := by
induction xs, ys using Vector.revInductionOn₂ <;> simp_all
@[simp]
theorem mapAccumr₂_mapAccumr_right (f₁ : α → γ → σ₁ → σ₁ × ζ) (f₂ : β → σ₂ → σ₂ × γ) :
(mapAccumr₂ f₁ xs (mapAccumr f₂ ys s₂).snd s₁)
= let m := (mapAccumr₂ (fun x y s =>
let r₂ := f₂ y s.snd
let r₁ := f₁ x r₂.snd s.fst
((r₁.fst, r₂.fst), r₁.snd)
) xs ys (s₁, s₂))
(m.fst.fst, m.snd) := by
induction xs, ys using Vector.revInductionOn₂ generalizing s₁ s₂ <;> simp_all
@[simp]
theorem map₂_map_right (f₁ : α → γ → ζ) (f₂ : β → γ) :
map₂ f₁ xs (map f₂ ys) = map₂ (fun x y => f₁ x (f₂ y)) xs ys := by
induction xs, ys using Vector.revInductionOn₂ <;> simp_all
@[simp]
theorem mapAccumr_mapAccumr₂ (f₁ : γ → σ₁ → σ₁ × ζ) (f₂ : α → β → σ₂ → σ₂ × γ) :
(mapAccumr f₁ (mapAccumr₂ f₂ xs ys s₂).snd s₁)
= let m := mapAccumr₂ (fun x y s =>
let r₂ := f₂ x y s.snd
let r₁ := f₁ r₂.snd s.fst
((r₁.fst, r₂.fst), r₁.snd)
) xs ys (s₁, s₂)
(m.fst.fst, m.snd) := by
induction xs, ys using Vector.revInductionOn₂ generalizing s₁ s₂ <;> simp_all
@[simp]
theorem map_map₂ (f₁ : γ → ζ) (f₂ : α → β → γ) :
map f₁ (map₂ f₂ xs ys) = map₂ (fun x y => f₁ <| f₂ x y) xs ys := by
induction xs, ys using Vector.revInductionOn₂ <;> simp_all
@[simp]
theorem mapAccumr₂_mapAccumr₂_left_left (f₁ : γ → α → σ₁ → σ₁ × φ) (f₂ : α → β → σ₂ → σ₂ × γ) :
(mapAccumr₂ f₁ (mapAccumr₂ f₂ xs ys s₂).snd xs s₁)
= let m := mapAccumr₂ (fun x y (s₁, s₂) =>
let r₂ := f₂ x y s₂
let r₁ := f₁ r₂.snd x s₁
((r₁.fst, r₂.fst), r₁.snd)
)
xs ys (s₁, s₂)
(m.fst.fst, m.snd) := by
induction xs, ys using Vector.revInductionOn₂ generalizing s₁ s₂ <;> simp_all
@[simp]
theorem mapAccumr₂_mapAccumr₂_left_right
(f₁ : γ → β → σ₁ → σ₁ × φ) (f₂ : α → β → σ₂ → σ₂ × γ) :
(mapAccumr₂ f₁ (mapAccumr₂ f₂ xs ys s₂).snd ys s₁)
= let m := mapAccumr₂ (fun x y (s₁, s₂) =>
let r₂ := f₂ x y s₂
let r₁ := f₁ r₂.snd y s₁
((r₁.fst, r₂.fst), r₁.snd)
)
xs ys (s₁, s₂)
(m.fst.fst, m.snd) := by
induction xs, ys using Vector.revInductionOn₂ generalizing s₁ s₂ <;> simp_all
@[simp]
theorem mapAccumr₂_mapAccumr₂_right_left (f₁ : α → γ → σ₁ → σ₁ × φ) (f₂ : α → β → σ₂ → σ₂ × γ) :
(mapAccumr₂ f₁ xs (mapAccumr₂ f₂ xs ys s₂).snd s₁)
= let m := mapAccumr₂ (fun x y (s₁, s₂) =>
let r₂ := f₂ x y s₂
let r₁ := f₁ x r₂.snd s₁
((r₁.fst, r₂.fst), r₁.snd)
)
xs ys (s₁, s₂)
(m.fst.fst, m.snd) := by
induction xs, ys using Vector.revInductionOn₂ generalizing s₁ s₂ <;> simp_all
@[simp]
theorem mapAccumr₂_mapAccumr₂_right_right (f₁ : β → γ → σ₁ → σ₁ × φ) (f₂ : α → β → σ₂ → σ₂ × γ) :
(mapAccumr₂ f₁ ys (mapAccumr₂ f₂ xs ys s₂).snd s₁)
= let m := mapAccumr₂ (fun x y (s₁, s₂) =>
let r₂ := f₂ x y s₂
let r₁ := f₁ y r₂.snd s₁
((r₁.fst, r₂.fst), r₁.snd)
)
xs ys (s₁, s₂)
(m.fst.fst, m.snd) := by
induction xs, ys using Vector.revInductionOn₂ generalizing s₁ s₂ <;> simp_all
end Binary
end Fold
/-!
## Bisimulations
We can prove two applications of `mapAccumr` equal by providing a bisimulation relation that relates
the initial states.
That is, by providing a relation `R : σ₁ → σ₁ → Prop` such that `R s₁ s₂` implies that `R` also
relates any pair of states reachable by applying `f₁` to `s₁` and `f₂` to `s₂`, with any possible
input values.
-/
section Bisim
variable {xs : Vector α n}
theorem mapAccumr_bisim {f₁ : α → σ₁ → σ₁ × β} {f₂ : α → σ₂ → σ₂ × β} {s₁ : σ₁} {s₂ : σ₂}
(R : σ₁ → σ₂ → Prop) (h₀ : R s₁ s₂)
(hR : ∀ {s q} a, R s q → R (f₁ a s).1 (f₂ a q).1 ∧ (f₁ a s).2 = (f₂ a q).2) :
R (mapAccumr f₁ xs s₁).fst (mapAccumr f₂ xs s₂).fst
∧ (mapAccumr f₁ xs s₁).snd = (mapAccumr f₂ xs s₂).snd := by
induction xs using Vector.revInductionOn generalizing s₁ s₂
next => exact ⟨h₀, rfl⟩
next xs x ih =>
rcases (hR x h₀) with ⟨hR, _⟩
simp only [mapAccumr_snoc, ih hR, true_and]
congr 1
theorem mapAccumr_bisim_tail {f₁ : α → σ₁ → σ₁ × β} {f₂ : α → σ₂ → σ₂ × β} {s₁ : σ₁} {s₂ : σ₂}
(h : ∃ R : σ₁ → σ₂ → Prop, R s₁ s₂ ∧
∀ {s q} a, R s q → R (f₁ a s).1 (f₂ a q).1 ∧ (f₁ a s).2 = (f₂ a q).2) :
(mapAccumr f₁ xs s₁).snd = (mapAccumr f₂ xs s₂).snd := by
rcases h with ⟨R, h₀, hR⟩
exact (mapAccumr_bisim R h₀ hR).2
theorem mapAccumr₂_bisim {ys : Vector β n} {f₁ : α → β → σ₁ → σ₁ × γ}
{f₂ : α → β → σ₂ → σ₂ × γ} {s₁ : σ₁} {s₂ : σ₂}
(R : σ₁ → σ₂ → Prop) (h₀ : R s₁ s₂)
(hR : ∀ {s q} a b, R s q → R (f₁ a b s).1 (f₂ a b q).1 ∧ (f₁ a b s).2 = (f₂ a b q).2) :
R (mapAccumr₂ f₁ xs ys s₁).1 (mapAccumr₂ f₂ xs ys s₂).1
∧ (mapAccumr₂ f₁ xs ys s₁).2 = (mapAccumr₂ f₂ xs ys s₂).2 := by
induction xs, ys using Vector.revInductionOn₂ generalizing s₁ s₂
next => exact ⟨h₀, rfl⟩
next xs ys x y ih =>
rcases (hR x y h₀) with ⟨hR, _⟩
simp only [mapAccumr₂_snoc, ih hR, true_and]
congr 1
theorem mapAccumr₂_bisim_tail {ys : Vector β n} {f₁ : α → β → σ₁ → σ₁ × γ}
{f₂ : α → β → σ₂ → σ₂ × γ} {s₁ : σ₁} {s₂ : σ₂}
(h : ∃ R : σ₁ → σ₂ → Prop, R s₁ s₂ ∧
∀ {s q} a b, R s q → R (f₁ a b s).1 (f₂ a b q).1 ∧ (f₁ a b s).2 = (f₂ a b q).2) :
(mapAccumr₂ f₁ xs ys s₁).2 = (mapAccumr₂ f₂ xs ys s₂).2 := by
rcases h with ⟨R, h₀, hR⟩
exact (mapAccumr₂_bisim R h₀ hR).2
end Bisim
/-!
## Redundant state optimization
The following section are collection of rewrites to simplify, or even get rid, redundant
accumulation state
-/
section RedundantState
variable {xs : Vector α n} {ys : Vector β n}
protected theorem map_eq_mapAccumr {f : α → β} :
map f xs = (mapAccumr (fun x (_ : Unit) ↦ ((), f x)) xs ()).snd := by
induction xs using Vector.revInductionOn <;> simp_all
/--
If there is a set of states that is closed under `f`, and such that `f` produces that same output
for all states in this set, then the state is not actually needed.
Hence, then we can rewrite `mapAccumr` into just `map`.
-/
theorem mapAccumr_eq_map {f : α → σ → σ × β} {s₀ : σ} (S : Set σ) (h₀ : s₀ ∈ S)
(closure : ∀ a s, s ∈ S → (f a s).1 ∈ S)
(out : ∀ a s s', s ∈ S → s' ∈ S → (f a s).2 = (f a s').2) :
(mapAccumr f xs s₀).snd = map (f · s₀ |>.snd) xs := by
rw [Vector.map_eq_mapAccumr]
apply mapAccumr_bisim_tail
use fun s _ => s ∈ S, h₀
exact @fun s _q a h => ⟨closure a s h, out a s s₀ h h₀⟩
protected theorem map₂_eq_mapAccumr₂ {f : α → β → γ} :
map₂ f xs ys = (mapAccumr₂ (fun x y (_ : Unit) ↦ ((), f x y)) xs ys ()).snd := by
induction xs, ys using Vector.revInductionOn₂ <;> simp_all
/--
If there is a set of states that is closed under `f`, and such that `f` produces that same output
for all states in this set, then the state is not actually needed.
Hence, then we can rewrite `mapAccumr₂` into just `map₂`.
-/
theorem mapAccumr₂_eq_map₂ {f : α → β → σ → σ × γ} {s₀ : σ} (S : Set σ) (h₀ : s₀ ∈ S)
(closure : ∀ a b s, s ∈ S → (f a b s).1 ∈ S)
(out : ∀ a b s s', s ∈ S → s' ∈ S → (f a b s).2 = (f a b s').2) :
(mapAccumr₂ f xs ys s₀).snd = map₂ (f · · s₀ |>.snd) xs ys := by
rw [Vector.map₂_eq_mapAccumr₂]
apply mapAccumr₂_bisim_tail
use fun s _ => s ∈ S, h₀
exact @fun s _q a b h => ⟨closure a b s h, out a b s s₀ h h₀⟩
/--
If an accumulation function `f`, given an initial state `s`, produces `s` as its output state
for all possible input bits, then the state is redundant and can be optimized out.
-/
@[simp]
theorem mapAccumr_eq_map_of_constant_state (f : α → σ → σ × β) (s : σ) (h : ∀ a, (f a s).fst = s) :
mapAccumr f xs s = (s, (map (fun x => (f x s).snd) xs)) := by
induction xs using revInductionOn <;> simp_all
/--
If an accumulation function `f`, given an initial state `s`, produces `s` as its output state
for all possible input bits, then the state is redundant and can be optimized out.
-/
@[simp]
theorem mapAccumr₂_eq_map₂_of_constant_state (f : α → β → σ → σ × γ) (s : σ)
(h : ∀ a b, (f a b s).fst = s) :
mapAccumr₂ f xs ys s = (s, (map₂ (fun x y => (f x y s).snd) xs ys)) := by
induction xs, ys using revInductionOn₂ <;> simp_all
/--
If an accumulation function `f`, produces the same output bits regardless of accumulation state,
then the state is redundant and can be optimized out.
-/
@[simp]
theorem mapAccumr_eq_map_of_unused_state (f : α → σ → σ × β) (f' : α → β) (s : σ)
(h : ∀ a s, (f a s).snd = f' a) :
(mapAccumr f xs s).snd = (map f' xs) := by
rw [mapAccumr_eq_map (fun _ => true) rfl (fun _ _ _ => rfl) (fun a s s' _ _ => by rw [h, h])]
simp_all
/--
If an accumulation function `f`, produces the same output bits regardless of accumulation state,
then the state is redundant and can be optimized out.
-/
@[simp]
theorem mapAccumr₂_eq_map₂_of_unused_state (f : α → β → σ → σ × γ) (f' : α → β → γ) (s : σ)
(h : ∀ a b s, (f a b s).snd = f' a b) :
(mapAccumr₂ f xs ys s).snd = (map₂ (fun x y => (f x y s).snd) xs ys) :=
mapAccumr₂_eq_map₂ (fun _ => true) rfl (fun _ _ _ _ => rfl) (fun a b s s' _ _ => by rw [h, h])
/-- If `f` takes a pair of states, but always returns the same value for both elements of the
pair, then we can simplify to just a single element of state.
-/
@[simp]
theorem mapAccumr_redundant_pair (f : α → (σ × σ) → (σ × σ) × β)
(h : ∀ x s, (f x (s, s)).fst.fst = (f x (s, s)).fst.snd) :
(mapAccumr f xs (s, s)).snd = (mapAccumr (fun x (s : σ) =>
(f x (s, s) |>.fst.fst, f x (s, s) |>.snd)
) xs s).snd :=
mapAccumr_bisim_tail <| by
use fun (s₁, s₂) s => s₂ = s ∧ s₁ = s
simp_all
/-- If `f` takes a pair of states, but always returns the same value for both elements of the
pair, then we can simplify to just a single element of state.
-/
@[simp]
theorem mapAccumr₂_redundant_pair (f : α → β → (σ × σ) → (σ × σ) × γ)
(h : ∀ x y s, let s' := (f x y (s, s)).fst; s'.fst = s'.snd) :
(mapAccumr₂ f xs ys (s, s)).snd = (mapAccumr₂ (fun x y (s : σ) =>
(f x y (s, s) |>.fst.fst, f x y (s, s) |>.snd)
) xs ys s).snd :=
mapAccumr₂_bisim_tail <| by
use fun (s₁, s₂) s => s₂ = s ∧ s₁ = s
simp_all
end RedundantState
/-!
## Unused input optimizations
-/
section UnusedInput
variable {xs : Vector α n} {ys : Vector β n}
/--
If `f` returns the same output and next state for every value of it's first argument, then
`xs : Vector` is ignored, and we can rewrite `mapAccumr₂` into `map`.
-/
@[simp]
theorem mapAccumr₂_unused_input_left (f : α → β → σ → σ × γ) (f' : β → σ → σ × γ)
(h : ∀ a b s, f a b s = f' b s) :
mapAccumr₂ f xs ys s = mapAccumr f' ys s := by
induction xs, ys using Vector.revInductionOn₂ generalizing s with
| nil => rfl
| snoc xs ys x y ih => simp [h x y s, ih]
/--
If `f` returns the same output and next state for every value of it's second argument, then
`ys : Vector` is ignored, and we can rewrite `mapAccumr₂` into `map`.
-/
@[simp]
theorem mapAccumr₂_unused_input_right (f : α → β → σ → σ × γ) (f' : α → σ → σ × γ)
(h : ∀ a b s, f a b s = f' a s) :
mapAccumr₂ f xs ys s = mapAccumr f' xs s := by
induction xs, ys using Vector.revInductionOn₂ generalizing s with
| nil => rfl
| snoc xs ys x y ih => simp [h x y s, ih]
end UnusedInput
/-!
## Commutativity
-/
section Comm
variable (xs ys : Vector α n)
theorem map₂_comm (f : α → α → β) (comm : ∀ a₁ a₂, f a₁ a₂ = f a₂ a₁) :
map₂ f xs ys = map₂ f ys xs := by
induction xs, ys using Vector.inductionOn₂ <;> simp_all
theorem mapAccumr₂_comm (f : α → α → σ → σ × γ) (comm : ∀ a₁ a₂ s, f a₁ a₂ s = f a₂ a₁ s) :
mapAccumr₂ f xs ys s = mapAccumr₂ f ys xs s := by
induction xs, ys using Vector.inductionOn₂ generalizing s <;> simp_all
end Comm
/-!
## Argument Flipping
-/
section Flip
variable (xs : Vector α n) (ys : Vector β n)
theorem map₂_flip (f : α → β → γ) :
map₂ f xs ys = map₂ (flip f) ys xs := by
induction xs, ys using Vector.inductionOn₂ <;> simp_all [flip]
theorem mapAccumr₂_flip (f : α → β → σ → σ × γ) :
mapAccumr₂ f xs ys s = mapAccumr₂ (flip f) ys xs s := by
induction xs, ys using Vector.inductionOn₂ <;> simp_all [flip]
end Flip
end Vector
end List |
.lake/packages/mathlib/Mathlib/Data/Sign/Basic.lean | import Mathlib.Algebra.GroupWithZero.Units.Lemmas
import Mathlib.Algebra.Order.BigOperators.Group.Finset
import Mathlib.Algebra.Order.Ring.Cast
import Mathlib.Data.Fintype.BigOperators
import Mathlib.Data.Sign.Defs
/-!
# Sign function
This file defines the sign function for types with zero and a decidable less-than relation, and
proves some basic theorems about it.
-/
universe u
variable {α : Type u}
namespace SignType
/-- Casting `SignType → ℤ → α` is the same as casting directly `SignType → α`. -/
@[simp, norm_cast]
lemma intCast_cast {α : Type*} [AddGroupWithOne α] (s : SignType) : ((s : ℤ) : α) = s :=
map_cast' _ Int.cast_one Int.cast_zero (@Int.cast_one α _ ▸ Int.cast_neg 1) _
theorem pow_odd (s : SignType) {n : ℕ} (hn : Odd n) : s ^ n = s := by
obtain ⟨k, rfl⟩ := hn
rw [pow_add, pow_one, pow_mul, sq]
cases s <;> simp
theorem zpow_odd (s : SignType) {z : ℤ} (hz : Odd z) : s ^ z = s := by
obtain rfl | hs := eq_or_ne s 0
· rw [zero_zpow]
rintro rfl
simp at hz
obtain ⟨k, rfl⟩ := hz
rw [zpow_add₀ hs, zpow_one, zpow_mul, zpow_two]
cases s <;> simp
lemma pow_even (s : SignType) {n : ℕ} (hn : Even n) (hs : s ≠ 0) :
s ^ n = 1 := by
cases s <;> simp_all
lemma zpow_even (s : SignType) {z : ℤ} (hz : Even z) (hs : s ≠ 0) :
s ^ z = 1 := by
cases s <;> simp_all [Even.neg_one_zpow]
/-- `SignType.cast` as a `MulWithZeroHom`. -/
@[simps]
def castHom {α} [MulZeroOneClass α] [HasDistribNeg α] : SignType →*₀ α where
toFun := cast
map_zero' := rfl
map_one' := rfl
map_mul' x y := by cases x <;> cases y <;> simp [zero_eq_zero, pos_eq_one, neg_eq_neg_one]
theorem univ_eq : (Finset.univ : Finset SignType) = {0, -1, 1} := by
decide
theorem range_eq {α} (f : SignType → α) : Set.range f = {f zero, f neg, f pos} := by
classical rw [← Fintype.coe_image_univ, univ_eq]
classical simp [Finset.coe_insert]
@[simp, norm_cast] lemma coe_mul {α} [MulZeroOneClass α] [HasDistribNeg α] (a b : SignType) :
↑(a * b) = (a : α) * b :=
map_mul SignType.castHom _ _
@[simp, norm_cast] lemma coe_pow {α} [MonoidWithZero α] [HasDistribNeg α] (a : SignType) (k : ℕ) :
↑(a ^ k) = (a : α) ^ k :=
map_pow SignType.castHom _ _
@[simp, norm_cast] lemma coe_zpow {α} [GroupWithZero α] [HasDistribNeg α] (a : SignType) (k : ℤ) :
↑(a ^ k) = (a : α) ^ k :=
map_zpow₀ SignType.castHom _ _
end SignType
open SignType
section OrderedRing
@[simp]
lemma sign_intCast {α : Type*} [Ring α] [PartialOrder α] [IsOrderedRing α]
[Nontrivial α] [DecidableLT α] (n : ℤ) :
sign (n : α) = sign n := by
simp only [sign_apply, Int.cast_pos, Int.cast_lt_zero]
end OrderedRing
section LinearOrderedRing
variable [Ring α] [LinearOrder α] [IsStrictOrderedRing α]
theorem sign_mul (x y : α) : sign (x * y) = sign x * sign y := by
rcases lt_trichotomy x 0 with (hx | hx | hx) <;> rcases lt_trichotomy y 0 with (hy | hy | hy) <;>
simp [hx, hy, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg]
@[simp] theorem sign_mul_abs (x : α) : (sign x * |x| : α) = x := by
rcases lt_trichotomy x 0 with hx | rfl | hx <;> simp [*, abs_of_pos, abs_of_neg]
@[simp] theorem abs_mul_sign (x : α) : (|x| * sign x : α) = x := by
rcases lt_trichotomy x 0 with hx | rfl | hx <;> simp [*, abs_of_pos, abs_of_neg]
@[simp]
theorem sign_mul_self (x : α) : sign x * x = |x| := by
rcases lt_trichotomy x 0 with hx | rfl | hx <;> simp [*, abs_of_pos, abs_of_neg]
@[simp]
theorem self_mul_sign (x : α) : x * sign x = |x| := by
rcases lt_trichotomy x 0 with hx | rfl | hx <;> simp [*, abs_of_pos, abs_of_neg]
/-- `SignType.sign` as a `MonoidWithZeroHom` for a nontrivial ordered semiring. Note that linearity
is required; consider ℂ with the order `z ≤ w` iff they have the same imaginary part and
`z - w ≤ 0` in the reals; then `1 + I` and `1 - I` are incomparable to zero, and thus we have:
`0 * 0 = SignType.sign (1 + I) * SignType.sign (1 - I) ≠ SignType.sign 2 = 1`.
(`Complex.orderedCommRing`) -/
def signHom : α →*₀ SignType where
toFun := sign
map_zero' := sign_zero
map_one' := sign_one
map_mul' := sign_mul
theorem sign_pow (x : α) (n : ℕ) : sign (x ^ n) = sign x ^ n := map_pow signHom x n
end LinearOrderedRing
section LinearOrderedAddCommGroup
variable [AddCommGroup α] [LinearOrder α] [IsOrderedAddMonoid α]
theorem sign_sum {ι : Type*} {s : Finset ι} {f : ι → α} (hs : s.Nonempty) (t : SignType)
(h : ∀ i ∈ s, sign (f i) = t) : sign (∑ i ∈ s, f i) = t := by
cases t
· simp_rw [zero_eq_zero, sign_eq_zero_iff] at h ⊢
exact Finset.sum_eq_zero h
· simp_rw [neg_eq_neg_one, sign_eq_neg_one_iff] at h ⊢
exact Finset.sum_neg h hs
· simp_rw [pos_eq_one, sign_eq_one_iff] at h ⊢
exact Finset.sum_pos h hs
end LinearOrderedAddCommGroup
open Finset Nat
section exists_signed_sum
/-!
In this section we explicitly handle universe variables,
because Lean creates a fresh universe variable for the type whose existence is asserted.
But we want the type to live in the same universe as the input type.
-/
private theorem exists_signed_sum_aux [DecidableEq α] (s : Finset α) (f : α → ℤ) :
∃ (β : Type u) (t : Finset β) (sgn : β → SignType) (g : β → α),
(∀ b, g b ∈ s) ∧
(#t = ∑ a ∈ s, (f a).natAbs) ∧
∀ a ∈ s, (∑ b ∈ t, if g b = a then (sgn b : ℤ) else 0) = f a := by
refine
⟨(Σ _ : { x // x ∈ s }, ℕ), Finset.univ.sigma fun a => range (f a).natAbs,
fun a => sign (f a.1), fun a => a.1, fun a => a.1.2, ?_, ?_⟩
· simp [sum_attach (f := fun a => (f a).natAbs)]
· intro x hx
simp [sum_sigma, hx, ← Int.sign_eq_sign, Int.sign_mul_abs, mul_comm |f _|,
sum_attach (s := s) (f := fun y => if y = x then f y else 0)]
/-- We can decompose a sum of absolute value `n` into a sum of `n` signs. -/
theorem exists_signed_sum [DecidableEq α] (s : Finset α) (f : α → ℤ) :
∃ (β : Type u) (_ : Fintype β) (sgn : β → SignType) (g : β → α),
(∀ b, g b ∈ s) ∧
(Fintype.card β = ∑ a ∈ s, (f a).natAbs) ∧
∀ a ∈ s, (∑ b, if g b = a then (sgn b : ℤ) else 0) = f a :=
let ⟨β, t, sgn, g, hg, ht, hf⟩ := exists_signed_sum_aux s f
⟨t, inferInstance, fun b => sgn b, fun b => g b, fun b => hg b, by simp [ht], fun a ha =>
(sum_attach t fun b ↦ ite (g b = a) (sgn b : ℤ) 0).trans <| hf _ ha⟩
/-- We can decompose a sum of absolute value less than `n` into a sum of at most `n` signs. -/
theorem exists_signed_sum' [Nonempty α] [DecidableEq α] (s : Finset α) (f : α → ℤ)
(n : ℕ) (h : (∑ i ∈ s, (f i).natAbs) ≤ n) :
∃ (β : Type u) (_ : Fintype β) (sgn : β → SignType) (g : β → α),
(∀ b, g b ∉ s → sgn b = 0) ∧
Fintype.card β = n ∧ ∀ a ∈ s, (∑ i, if g i = a then (sgn i : ℤ) else 0) = f a := by
obtain ⟨β, _, sgn, g, hg, hβ, hf⟩ := exists_signed_sum s f
refine
⟨β ⊕ (Fin (n - ∑ i ∈ s, (f i).natAbs)), inferInstance, Sum.elim sgn 0,
Sum.elim g (Classical.arbitrary (Fin (n - Finset.sum s fun i => Int.natAbs (f i)) → α)),
?_, by simp [hβ, h], fun a ha => by simp [hf _ ha]⟩
rintro (b | b) hb
· cases hb (hg _)
· rfl
end exists_signed_sum |
.lake/packages/mathlib/Mathlib/Data/Sign/Defs.lean | import Mathlib.Algebra.GroupWithZero.Defs
import Mathlib.Algebra.Ring.Defs
import Mathlib.Algebra.Order.Ring.Defs
import Mathlib.Tactic.DeriveFintype
/-!
# Sign type
This file defines the type of signs $\{-1, 0, 1\}$ and its basic arithmetic instances.
-/
-- Don't generate unnecessary `sizeOf_spec` lemmas which the `simpNF` linter will complain about.
set_option genSizeOfSpec false in
/-- The type of signs. -/
inductive SignType
| zero
| neg
| pos
deriving DecidableEq, Inhabited, Fintype
namespace SignType
instance : Zero SignType :=
⟨zero⟩
instance : One SignType :=
⟨pos⟩
instance : Neg SignType :=
⟨fun s =>
match s with
| neg => pos
| zero => zero
| pos => neg⟩
@[simp]
theorem zero_eq_zero : zero = 0 :=
rfl
@[simp]
theorem neg_eq_neg_one : neg = -1 :=
rfl
@[simp]
theorem pos_eq_one : pos = 1 :=
rfl
theorem trichotomy (a : SignType) : a = -1 ∨ a = 0 ∨ a = 1 := by
cases a <;> simp
instance : Mul SignType :=
⟨fun x y =>
match x with
| neg => -y
| zero => zero
| pos => y⟩
/-- The less-than-or-equal relation on signs. -/
protected inductive LE : SignType → SignType → Prop
| of_neg (a) : SignType.LE neg a
| zero : SignType.LE zero zero
| of_pos (a) : SignType.LE a pos
instance : LE SignType :=
⟨SignType.LE⟩
instance LE.decidableRel : DecidableRel SignType.LE := fun a b => by
cases a <;> cases b <;> first | exact isTrue (by constructor) | exact isFalse (by rintro ⟨_⟩)
private lemma mul_comm : ∀ (a b : SignType), a * b = b * a := by rintro ⟨⟩ ⟨⟩ <;> rfl
private lemma mul_assoc : ∀ (a b c : SignType), (a * b) * c = a * (b * c) := by
rintro ⟨⟩ ⟨⟩ ⟨⟩ <;> rfl
/- We can define a `Field` instance on `SignType`, but it's not mathematically sensible,
so we only define the `CommGroupWithZero`. -/
instance : CommGroupWithZero SignType where
inv := id
mul_zero a := by cases a <;> rfl
zero_mul a := by cases a <;> rfl
mul_one a := by cases a <;> rfl
one_mul a := by cases a <;> rfl
mul_inv_cancel a ha := by cases a <;> trivial
mul_comm := mul_comm
mul_assoc := mul_assoc
exists_pair_ne := ⟨0, 1, by rintro ⟨_⟩⟩
inv_zero := rfl
private lemma le_antisymm (a b : SignType) (_ : a ≤ b) (_ : b ≤ a) : a = b := by
cases a <;> cases b <;> trivial
private lemma le_trans (a b c : SignType) (_ : a ≤ b) (_ : b ≤ c) : a ≤ c := by
cases a <;> cases b <;> cases c <;> tauto
instance : LinearOrder SignType where
le_refl a := by cases a <;> constructor
le_total a b := by cases a <;> cases b <;> first | left; constructor | right; constructor
le_antisymm := le_antisymm
le_trans := le_trans
toDecidableLE := LE.decidableRel
instance : BoundedOrder SignType where
top := 1
le_top := LE.of_pos
bot := -1
bot_le :=
#adaptation_note /-- https://github.com/leanprover/lean4/pull/6053
Added `by exact`, but don't understand why it was needed. -/
by exact LE.of_neg
instance : HasDistribNeg SignType where
neg_neg := by rintro ⟨_⟩ <;> rfl
neg_mul := by rintro ⟨_⟩ ⟨_⟩ <;> rfl
mul_neg := by rintro ⟨_⟩ ⟨_⟩ <;> rfl
/-- `SignType` is equivalent to `Fin 3`. -/
def fin3Equiv : SignType ≃* Fin 3 where
toFun a :=
match a with
| 0 => ⟨0, by simp⟩
| 1 => ⟨1, by simp⟩
| -1 => ⟨2, by simp⟩
invFun a :=
match a with
| ⟨0, _⟩ => 0
| ⟨1, _⟩ => 1
| ⟨2, _⟩ => -1
left_inv a := by cases a <;> rfl
right_inv a :=
match a with
| ⟨0, _⟩ => by simp
| ⟨1, _⟩ => by simp
| ⟨2, _⟩ => by simp
map_mul' a b := by
cases a <;> cases b <;> rfl
section CaseBashing
theorem nonneg_iff {a : SignType} : 0 ≤ a ↔ a = 0 ∨ a = 1 := by decide +revert
theorem nonneg_iff_ne_neg_one {a : SignType} : 0 ≤ a ↔ a ≠ -1 := by decide +revert
theorem neg_one_lt_iff {a : SignType} : -1 < a ↔ 0 ≤ a := by decide +revert
theorem nonpos_iff {a : SignType} : a ≤ 0 ↔ a = -1 ∨ a = 0 := by decide +revert
theorem nonpos_iff_ne_one {a : SignType} : a ≤ 0 ↔ a ≠ 1 := by decide +revert
theorem lt_one_iff {a : SignType} : a < 1 ↔ a ≤ 0 := by decide +revert
@[simp]
theorem neg_iff {a : SignType} : a < 0 ↔ a = -1 := by decide +revert
@[simp]
theorem le_neg_one_iff {a : SignType} : a ≤ -1 ↔ a = -1 :=
le_bot_iff
@[simp]
theorem pos_iff {a : SignType} : 0 < a ↔ a = 1 := by decide +revert
@[simp]
theorem one_le_iff {a : SignType} : 1 ≤ a ↔ a = 1 :=
top_le_iff
@[simp]
theorem neg_one_le (a : SignType) : -1 ≤ a :=
bot_le
@[simp]
theorem le_one (a : SignType) : a ≤ 1 :=
le_top
@[simp]
theorem not_lt_neg_one (a : SignType) : ¬a < -1 :=
not_lt_bot
@[simp]
theorem not_one_lt (a : SignType) : ¬1 < a :=
not_top_lt
@[simp]
theorem self_eq_neg_iff {a : SignType} : a = -a ↔ a = 0 := by decide +revert
@[simp]
theorem neg_eq_self_iff {a : SignType} : -a = a ↔ a = 0 := by decide +revert
@[simp]
theorem neg_eq_zero_iff {a : SignType} : -a = 0 ↔ a = 0 := by decide +revert
@[simp]
theorem neg_one_lt_one : (-1 : SignType) < 1 :=
bot_lt_top
end CaseBashing
section cast
variable {α : Type*} [Zero α] [One α] [Neg α]
/-- Turn a `SignType` into zero, one, or minus one. This is a coercion instance. -/
@[coe]
def cast : SignType → α
| zero => 0
| pos => 1
| neg => -1
/-- This is a `CoeTail` since the type on the right (trivially) determines the type on the left.
`outParam`-wise it could be a `Coe`, but we don't want to try applying this instance for a
coercion to any `α`.
-/
instance : CoeTail SignType α :=
⟨cast⟩
/-- Casting out of `SignType` respects composition with functions preserving `0, 1, -1`. -/
lemma map_cast' {β : Type*} [One β] [Neg β] [Zero β]
(f : α → β) (h₁ : f 1 = 1) (h₂ : f 0 = 0) (h₃ : f (-1) = -1) (s : SignType) :
f s = s := by
cases s <;> simp only [SignType.cast, h₁, h₂, h₃]
/-- Casting out of `SignType` respects composition with suitable bundled homomorphism types. -/
lemma map_cast {α β F : Type*} [AddGroupWithOne α] [One β] [SubtractionMonoid β]
[FunLike F α β] [AddMonoidHomClass F α β] [OneHomClass F α β] (f : F) (s : SignType) :
f s = s := by
apply map_cast' <;> simp
@[simp]
theorem coe_zero : ↑(0 : SignType) = (0 : α) :=
rfl
@[simp]
theorem coe_one : ↑(1 : SignType) = (1 : α) :=
rfl
@[simp]
theorem coe_neg_one : ↑(-1 : SignType) = (-1 : α) :=
rfl
@[simp, norm_cast]
lemma coe_neg {α : Type*} [One α] [SubtractionMonoid α] (s : SignType) :
(↑(-s) : α) = -↑s := by
cases s <;> simp
end cast
end SignType
variable {α : Type*}
open SignType
section Preorder
variable [Zero α] [Preorder α] [DecidableLT α] {a : α}
/-- The sign of an element is 1 if it's positive, -1 if negative, 0 otherwise. -/
def SignType.sign : α →o SignType :=
⟨fun a => if 0 < a then 1 else if a < 0 then -1 else 0, fun a b h => by
dsimp
split_ifs with h₁ h₂ h₃ h₄ _ _ h₂ h₃ <;> try constructor
· cases lt_irrefl 0 (h₁.trans <| h.trans_lt h₃)
· cases h₂ (h₁.trans_le h)
· cases h₄ (h.trans_lt h₃)⟩
theorem sign_apply : sign a = ite (0 < a) 1 (ite (a < 0) (-1) 0) :=
rfl
@[simp]
theorem sign_zero : sign (0 : α) = 0 := by simp [sign_apply]
@[simp]
theorem sign_pos (ha : 0 < a) : sign a = 1 := by rwa [sign_apply, if_pos]
@[simp]
theorem sign_neg (ha : a < 0) : sign a = -1 := by rwa [sign_apply, if_neg <| asymm ha, if_pos]
theorem sign_eq_one_iff : sign a = 1 ↔ 0 < a := by
refine ⟨fun h => ?_, fun h => sign_pos h⟩
by_contra hn
rw [sign_apply, if_neg hn] at h
split_ifs at h
theorem sign_eq_neg_one_iff : sign a = -1 ↔ a < 0 := by
refine ⟨fun h => ?_, fun h => sign_neg h⟩
rw [sign_apply] at h
split_ifs at h
assumption
end Preorder
section LinearOrder
variable [Zero α] [LinearOrder α] {a : α}
/-- `SignType.sign` respects strictly monotone zero-preserving maps. -/
lemma StrictMono.sign_comp {β F : Type*} [Zero β] [Preorder β] [DecidableLT β]
[FunLike F α β] [ZeroHomClass F α β] {f : F} (hf : StrictMono f) (a : α) :
sign (f a) = sign a := by
simp only [sign_apply, ← map_zero f, hf.lt_iff_lt]
@[simp]
theorem sign_eq_zero_iff : sign a = 0 ↔ a = 0 := by
refine ⟨fun h => ?_, fun h => h.symm ▸ sign_zero⟩
rw [sign_apply] at h
split_ifs at h with h_1 h_2
cases h
exact (le_of_not_gt h_1).eq_of_not_lt h_2
theorem sign_ne_zero : sign a ≠ 0 ↔ a ≠ 0 :=
sign_eq_zero_iff.not
@[simp]
theorem sign_nonneg_iff : 0 ≤ sign a ↔ 0 ≤ a := by
rcases lt_trichotomy 0 a with (h | h | h)
· simp [h, h.le]
· simp [← h]
· simp [h, h.not_ge]
@[simp]
theorem sign_nonpos_iff : sign a ≤ 0 ↔ a ≤ 0 := by
rcases lt_trichotomy 0 a with (h | h | h)
· simp [h, h.not_ge]
· simp [← h]
· simp [h, h.le]
lemma sign_eq_sign_or_eq_neg {b : α} (ha : a ≠ 0) (hb : b ≠ 0) :
sign a = sign b ∨ sign a = -sign b := by
rcases trichotomy (sign a) with hsa | hsa | hsa <;>
rcases trichotomy (sign b) with hsb | hsb | hsb <;>
simp_all
end LinearOrder
section OrderedSemiring
variable [Semiring α] [PartialOrder α] [IsOrderedRing α] [DecidableLT α] [Nontrivial α]
theorem sign_one : sign (1 : α) = 1 :=
sign_pos zero_lt_one
end OrderedSemiring
section AddGroup
variable [AddGroup α] [Preorder α] [DecidableLT α]
theorem Left.sign_neg [AddLeftStrictMono α] (a : α) : sign (-a) = -sign a := by
simp_rw [sign_apply, Left.neg_pos_iff, Left.neg_neg_iff]
split_ifs with h h'
· exact False.elim (lt_asymm h h')
· simp
· simp
· simp
theorem Right.sign_neg [AddRightStrictMono α] (a : α) :
sign (-a) = -sign a := by
simp_rw [sign_apply, Right.neg_pos_iff, Right.neg_neg_iff]
split_ifs with h h'
· exact False.elim (lt_asymm h h')
· simp
· simp
· simp
end AddGroup
theorem Int.sign_eq_sign (n : ℤ) : Int.sign n = SignType.sign n := by
obtain (n | _) | _ := n <;> simp [sign, negSucc_lt_zero] |
.lake/packages/mathlib/Mathlib/Data/Matrix/Auto.lean | import Mathlib.Algebra.Expr
import Mathlib.Data.Matrix.Reflection
/-! # Automatically generated lemmas for working with concrete matrices
In Mathlib3, this file contained "magic" lemmas which autogenerate to the correct size of matrix.
For instance, `Matrix.of_mul_of_fin` could be used as:
```lean
example {α} [AddCommMonoid α] [Mul α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁₁ b₁₂ b₂₁ b₂₂ : α) :
!![a₁₁, a₁₂;
a₂₁, a₂₂] * !![b₁₁, b₁₂;
b₂₁, b₂₂] = !![a₁₁ * b₁₁ + a₁₂ * b₂₁, a₁₁ * b₁₂ + a₁₂ * b₂₂;
a₂₁ * b₁₁ + a₂₂ * b₂₁, a₂₁ * b₁₂ + a₂₂ * b₂₂] := by
rw [of_mul_of_fin]
```
TODO: These magic lemmas have been skipped for now, though the plumbing lemmas in
`Mathlib/Data/Matrix/Reflection.lean` are still available.
They should probably be implemented as simprocs.
-/ |
.lake/packages/mathlib/Mathlib/Data/Matrix/Bilinear.lean | import Mathlib.Algebra.Module.LinearMap.End
import Mathlib.Data.Matrix.Mul
import Mathlib.Data.Matrix.Basis
import Mathlib.Algebra.Algebra.Bilinear
/-!
# Bundled versions of multiplication for matrices
This file provides versions of `LinearMap.mulLeft` and `LinearMap.mulRight` which work for the
heterogeneous multiplication of matrices.
-/
variable {l m n o : Type*} {R A : Type*}
section NonUnitalNonAssocSemiring
variable (R) [Fintype m]
section one_side
variable [Semiring R] [NonUnitalNonAssocSemiring A] [Module R A]
section left
variable (n) [SMulCommClass R A A]
/-- A version of `LinearMap.mulLeft` for matrix multiplication. -/
@[simps]
def mulLeftLinearMap (X : Matrix l m A) :
Matrix m n A →ₗ[R] Matrix l n A where
toFun := (X * ·)
map_smul' := Matrix.mul_smul _
map_add' := Matrix.mul_add _
/-- On square matrices, `Matrix.mulLeftLinearMap` and `LinearMap.mulLeft` coincide. -/
theorem mulLeftLinearMap_eq_mulLeft :
mulLeftLinearMap m R = LinearMap.mulLeft R (A := Matrix m m A) := rfl
/-- A version of `LinearMap.mulLeft_zero_eq_zero` for matrix multiplication. -/
@[simp]
theorem mulLeftLinearMap_zero_eq_zero : mulLeftLinearMap n R (0 : Matrix l m A) = 0 :=
LinearMap.ext fun _ => Matrix.zero_mul _
end left
section right
variable (l) [IsScalarTower R A A]
/-- A version of `LinearMap.mulRight` for matrix multiplication. -/
@[simps]
def mulRightLinearMap (Y : Matrix m n A) :
Matrix l m A →ₗ[R] Matrix l n A where
toFun := (· * Y)
map_smul' _ _ := Matrix.smul_mul _ _ _
map_add' _ _ := Matrix.add_mul _ _ _
/-- On square matrices, `Matrix.mulRightLinearMap` and `LinearMap.mulRight` coincide. -/
theorem mulRightLinearMap_eq_mulRight :
mulRightLinearMap m R = LinearMap.mulRight R (A := Matrix m m A) := rfl
/-- A version of `LinearMap.mulLeft_zero_eq_zero` for matrix multiplication. -/
@[simp]
theorem mulRightLinearMap_zero_eq_zero : mulRightLinearMap l R (0 : Matrix m n A) = 0 :=
LinearMap.ext fun _ => Matrix.mul_zero _
end right
end one_side
variable [CommSemiring R] [NonUnitalNonAssocSemiring A] [Module R A]
variable [SMulCommClass R A A] [IsScalarTower R A A]
/-- A version of `LinearMap.mul` for matrix multiplication. -/
@[simps!]
def mulLinearMap : Matrix l m A →ₗ[R] Matrix m n A →ₗ[R] Matrix l n A where
toFun := mulLeftLinearMap n R
map_add' _ _ := LinearMap.ext fun _ => Matrix.add_mul _ _ _
map_smul' _ _ := LinearMap.ext fun _ => Matrix.smul_mul _ _ _
/-- On square matrices, `Matrix.mulLinearMap` and `LinearMap.mul` coincide. -/
theorem mulLinearMap_eq_mul :
mulLinearMap R = LinearMap.mul R (A := Matrix m m A) := rfl
end NonUnitalNonAssocSemiring
section NonUnital
section one_side
variable [Fintype m] [Fintype n] [Semiring R] [NonUnitalSemiring A] [Module R A]
/-- A version of `LinearMap.mulLeft_mul` for matrix multiplication. -/
@[simp]
theorem mulLeftLinearMap_mul [SMulCommClass R A A] (a : Matrix l m A) (b : Matrix m n A) :
mulLeftLinearMap o R (a * b) = (mulLeftLinearMap o R a).comp (mulLeftLinearMap o R b) := by
ext
simp only [mulLeftLinearMap_apply, LinearMap.comp_apply, Matrix.mul_assoc]
/-- A version of `LinearMap.mulRight_mul` for matrix multiplication. -/
@[simp]
theorem mulRightLinearMap_mul [IsScalarTower R A A] (a : Matrix m n A) (b : Matrix n o A) :
mulRightLinearMap l R (a * b) = (mulRightLinearMap l R b).comp (mulRightLinearMap l R a) := by
ext
simp only [mulRightLinearMap_apply, LinearMap.comp_apply, Matrix.mul_assoc]
end one_side
variable [Fintype m] [Fintype n] [CommSemiring R] [NonUnitalSemiring A] [Module R A]
variable [SMulCommClass R A A] [IsScalarTower R A A]
/-- A version of `LinearMap.commute_mulLeft_right` for matrix multiplication. -/
theorem commute_mulLeftLinearMap_mulRightLinearMap (a : Matrix l m A) (b : Matrix n o A) :
mulLeftLinearMap o R a ∘ₗ mulRightLinearMap m R b =
mulRightLinearMap l R b ∘ₗ mulLeftLinearMap n R a := by
ext c : 1
exact (Matrix.mul_assoc a c b).symm
end NonUnital
section Semiring
section one_side
variable [Fintype m] [DecidableEq m] [Semiring R] [Semiring A]
section left
variable [Module R A] [SMulCommClass R A A]
/-- A version of `LinearMap.mulLeft_one` for matrix multiplication. -/
@[simp]
theorem mulLeftLinearMap_one : mulLeftLinearMap n R (1 : Matrix m m A) = LinearMap.id :=
LinearMap.ext fun _ => Matrix.one_mul _
omit [DecidableEq m] in
/-- A version of `LinearMap.mulLeft_eq_zero_iff` for matrix multiplication. -/
@[simp]
theorem mulLeftLinearMap_eq_zero_iff [Nonempty n] (a : Matrix l m A) :
mulLeftLinearMap n R a = 0 ↔ a = 0 := by
constructor <;> intro h
· inhabit n
ext i j
classical
replace h := DFunLike.congr_fun h (Matrix.single j (default : n) 1)
simpa using Matrix.ext_iff.2 h i default
· rw [h]
exact mulLeftLinearMap_zero_eq_zero _ _
/-- A version of `LinearMap.pow_mulLeft` for matrix multiplication. -/
@[simp]
theorem pow_mulLeftLinearMap (a : Matrix m m A) (k : ℕ) :
mulLeftLinearMap n R a ^ k = mulLeftLinearMap n R (a ^ k) :=
match k with
| 0 => by rw [pow_zero, pow_zero, mulLeftLinearMap_one, Module.End.one_eq_id]
| (n + 1) => by
rw [pow_succ, pow_succ, mulLeftLinearMap_mul, Module.End.mul_eq_comp, pow_mulLeftLinearMap]
end left
section right
variable [Module R A] [IsScalarTower R A A]
/-- A version of `LinearMap.mulRight_one` for matrix multiplication. -/
@[simp]
theorem mulRightLinearMap_one : mulRightLinearMap l R (1 : Matrix m m A) = LinearMap.id :=
LinearMap.ext fun _ => Matrix.mul_one _
omit [DecidableEq m] in
/-- A version of `LinearMap.mulRight_eq_zero_iff` for matrix multiplication. -/
@[simp]
theorem mulRightLinearMap_eq_zero_iff (a : Matrix m n A) [Nonempty l] :
mulRightLinearMap l R a = 0 ↔ a = 0 := by
constructor <;> intro h
· inhabit l
ext i j
classical
replace h := DFunLike.congr_fun h (Matrix.single (default : l) i 1)
simpa using Matrix.ext_iff.2 h default j
· rw [h]
exact mulRightLinearMap_zero_eq_zero _ _
/-- A version of `LinearMap.pow_mulRight` for matrix multiplication. -/
@[simp]
theorem pow_mulRightLinearMap (a : Matrix m m A) (k : ℕ) :
mulRightLinearMap l R a ^ k = mulRightLinearMap l R (a ^ k) :=
match k with
| 0 => by rw [pow_zero, pow_zero, mulRightLinearMap_one, Module.End.one_eq_id]
| (n + 1) => by
rw [pow_succ, pow_succ', mulRightLinearMap_mul, Module.End.mul_eq_comp, pow_mulRightLinearMap]
end right
end one_side
end Semiring |
.lake/packages/mathlib/Mathlib/Data/Matrix/ColumnRowPartitioned.lean | import Mathlib.Data.Matrix.Block
import Mathlib.LinearAlgebra.Matrix.SemiringInverse
/-! # Block Matrices from Rows and Columns
This file provides the basic definitions of matrices composed from columns and rows.
The concatenation of two matrices with the same row indices can be expressed as
`A = fromCols A₁ A₂` the concatenation of two matrices with the same column indices
can be expressed as `B = fromRows B₁ B₂`.
We then provide a few lemmas that deal with the products of these with each other and
with block matrices
## Tags
column matrices, row matrices, column row block matrices
-/
namespace Matrix
variable {R : Type*}
variable {m m₁ m₂ n n₁ n₂ : Type*}
/-- Concatenate together two matrices A₁[m₁ × N] and A₂[m₂ × N] with the same columns (N) to get a
bigger matrix indexed by [(m₁ ⊕ m₂) × N] -/
def fromRows (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) : Matrix (m₁ ⊕ m₂) n R :=
of (Sum.elim A₁ A₂)
/-- Concatenate together two matrices B₁[m × n₁] and B₂[m × n₂] with the same rows (M) to get a
bigger matrix indexed by [m × (n₁ ⊕ n₂)] -/
def fromCols (B₁ : Matrix m n₁ R) (B₂ : Matrix m n₂ R) : Matrix m (n₁ ⊕ n₂) R :=
of fun i => Sum.elim (B₁ i) (B₂ i)
/-- Given a column partitioned matrix extract the first column -/
def toCols₁ (A : Matrix m (n₁ ⊕ n₂) R) : Matrix m n₁ R := of fun i j => (A i (Sum.inl j))
/-- Given a column partitioned matrix extract the second column -/
def toCols₂ (A : Matrix m (n₁ ⊕ n₂) R) : Matrix m n₂ R := of fun i j => (A i (Sum.inr j))
/-- Given a row partitioned matrix extract the first row -/
def toRows₁ (A : Matrix (m₁ ⊕ m₂) n R) : Matrix m₁ n R := of fun i j => (A (Sum.inl i) j)
/-- Given a row partitioned matrix extract the second row -/
def toRows₂ (A : Matrix (m₁ ⊕ m₂) n R) : Matrix m₂ n R := of fun i j => (A (Sum.inr i) j)
@[simp]
lemma fromRows_apply_inl (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) (i : m₁) (j : n) :
(fromRows A₁ A₂) (Sum.inl i) j = A₁ i j := rfl
@[simp]
lemma fromRows_apply_inr (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) (i : m₂) (j : n) :
(fromRows A₁ A₂) (Sum.inr i) j = A₂ i j := rfl
@[simp]
lemma fromCols_apply_inl (A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) (i : m) (j : n₁) :
(fromCols A₁ A₂) i (Sum.inl j) = A₁ i j := rfl
@[simp]
lemma fromCols_apply_inr (A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) (i : m) (j : n₂) :
(fromCols A₁ A₂) i (Sum.inr j) = A₂ i j := rfl
@[simp]
lemma toRows₁_apply (A : Matrix (m₁ ⊕ m₂) n R) (i : m₁) (j : n) :
(toRows₁ A) i j = A (Sum.inl i) j := rfl
@[simp]
lemma toRows₂_apply (A : Matrix (m₁ ⊕ m₂) n R) (i : m₂) (j : n) :
(toRows₂ A) i j = A (Sum.inr i) j := rfl
@[simp]
lemma toRows₁_fromRows (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) :
toRows₁ (fromRows A₁ A₂) = A₁ := rfl
@[simp]
lemma toRows₂_fromRows (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) :
toRows₂ (fromRows A₁ A₂) = A₂ := rfl
@[simp]
lemma toCols₁_apply (A : Matrix m (n₁ ⊕ n₂) R) (i : m) (j : n₁) :
(toCols₁ A) i j = A i (Sum.inl j) := rfl
@[simp]
lemma toCols₂_apply (A : Matrix m (n₁ ⊕ n₂) R) (i : m) (j : n₂) :
(toCols₂ A) i j = A i (Sum.inr j) := rfl
@[simp]
lemma toCols₁_fromCols (A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) :
toCols₁ (fromCols A₁ A₂) = A₁ := rfl
@[simp]
lemma toCols₂_fromCols (A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) :
toCols₂ (fromCols A₁ A₂) = A₂ := rfl
@[simp]
lemma fromCols_toCols (A : Matrix m (n₁ ⊕ n₂) R) :
fromCols A.toCols₁ A.toCols₂ = A := by
ext i (j | j) <;> simp
@[simp]
lemma fromRows_toRows (A : Matrix (m₁ ⊕ m₂) n R) : fromRows A.toRows₁ A.toRows₂ = A := by
ext (i | i) j <;> simp
lemma fromRows_inj : Function.Injective2 (@fromRows R m₁ m₂ n) := by
intro x1 x2 y1 y2
simp [← Matrix.ext_iff]
lemma fromCols_inj : Function.Injective2 (@fromCols R m n₁ n₂) := by
intro x1 x2 y1 y2
simp only [← Matrix.ext_iff]
simp_all
lemma fromCols_ext_iff (A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) (B₁ : Matrix m n₁ R)
(B₂ : Matrix m n₂ R) :
fromCols A₁ A₂ = fromCols B₁ B₂ ↔ A₁ = B₁ ∧ A₂ = B₂ := fromCols_inj.eq_iff
lemma fromRows_ext_iff (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) (B₁ : Matrix m₁ n R)
(B₂ : Matrix m₂ n R) :
fromRows A₁ A₂ = fromRows B₁ B₂ ↔ A₁ = B₁ ∧ A₂ = B₂ := fromRows_inj.eq_iff
/-- A column partitioned matrix when transposed gives a row partitioned matrix with columns of the
initial matrix transposed to become rows. -/
lemma transpose_fromCols (A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) :
transpose (fromCols A₁ A₂) = fromRows (transpose A₁) (transpose A₂) := by
ext (i | i) j <;> simp
/-- A row partitioned matrix when transposed gives a column partitioned matrix with rows of the
initial matrix transposed to become columns. -/
lemma transpose_fromRows (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) :
transpose (fromRows A₁ A₂) = fromCols (transpose A₁) (transpose A₂) := by
ext i (j | j) <;> simp
lemma fromRows_map (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) {R' : Type*} (f : R → R') :
(fromRows A₁ A₂).map f = fromRows (A₁.map f) (A₂.map f) := by
ext (_ | _) <;> rfl
lemma fromCols_map (A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) {R' : Type*} (f : R → R') :
(fromCols A₁ A₂).map f = fromCols (A₁.map f) (A₂.map f) := by
ext _ (_ | _) <;> rfl
section Neg
variable [Neg R]
/-- Negating a matrix partitioned by rows is equivalent to negating each of the rows. -/
@[simp]
lemma fromRows_neg (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) :
-fromRows A₁ A₂ = fromRows (-A₁) (-A₂) := by
ext (i | i) j <;> simp
/-- Negating a matrix partitioned by columns is equivalent to negating each of the columns. -/
@[simp]
lemma fromCols_neg (A₁ : Matrix n m₁ R) (A₂ : Matrix n m₂ R) :
-fromCols A₁ A₂ = fromCols (-A₁) (-A₂) := by
ext i (j | j) <;> simp
end Neg
@[simp]
lemma fromCols_fromRows_eq_fromBlocks (B₁₁ : Matrix m₁ n₁ R) (B₁₂ : Matrix m₁ n₂ R)
(B₂₁ : Matrix m₂ n₁ R) (B₂₂ : Matrix m₂ n₂ R) :
fromCols (fromRows B₁₁ B₂₁) (fromRows B₁₂ B₂₂) = fromBlocks B₁₁ B₁₂ B₂₁ B₂₂ := by
ext (_ | _) (_ | _) <;> simp
@[simp]
lemma fromRows_fromCols_eq_fromBlocks (B₁₁ : Matrix m₁ n₁ R) (B₁₂ : Matrix m₁ n₂ R)
(B₂₁ : Matrix m₂ n₁ R) (B₂₂ : Matrix m₂ n₂ R) :
fromRows (fromCols B₁₁ B₁₂) (fromCols B₂₁ B₂₂) = fromBlocks B₁₁ B₁₂ B₂₁ B₂₂ := by
ext (_ | _) (_ | _) <;> simp
section Semiring
variable [Semiring R]
@[simp]
lemma fromRows_mulVec [Fintype n] (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) (v : n → R) :
fromRows A₁ A₂ *ᵥ v = Sum.elim (A₁ *ᵥ v) (A₂ *ᵥ v) := by
ext (_ | _) <;> rfl
@[simp]
lemma vecMul_fromCols [Fintype m] (B₁ : Matrix m n₁ R) (B₂ : Matrix m n₂ R) (v : m → R) :
v ᵥ* fromCols B₁ B₂ = Sum.elim (v ᵥ* B₁) (v ᵥ* B₂) := by
ext (_ | _) <;> rfl
lemma sumElim_vecMul_fromRows [Fintype m₁] [Fintype m₂] (B₁ : Matrix m₁ n R) (B₂ : Matrix m₂ n R)
(v₁ : m₁ → R) (v₂ : m₂ → R) :
Sum.elim v₁ v₂ ᵥ* fromRows B₁ B₂ = v₁ ᵥ* B₁ + v₂ ᵥ* B₂ := by
ext
simp [Matrix.vecMul, fromRows, dotProduct]
@[simp]
lemma vecMul_fromRows [Fintype m₁] [Fintype m₂]
(B₁ : Matrix m₁ n R) (B₂ : Matrix m₂ n R) (v : m₁ ⊕ m₂ → R) :
v ᵥ* fromRows B₁ B₂ = v ∘ Sum.inl ᵥ* B₁ + v ∘ Sum.inr ᵥ* B₂ := by
simp [← sumElim_vecMul_fromRows]
lemma fromCols_mulVec_sumElim [Fintype n₁] [Fintype n₂]
(A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) (v₁ : n₁ → R) (v₂ : n₂ → R) :
fromCols A₁ A₂ *ᵥ Sum.elim v₁ v₂ = A₁ *ᵥ v₁ + A₂ *ᵥ v₂ := by
ext
simp [Matrix.mulVec, fromCols]
@[simp]
lemma fromCols_mulVec [Fintype n₁] [Fintype n₂]
(A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) (v : n₁ ⊕ n₂ → R) :
fromCols A₁ A₂ *ᵥ v = A₁ *ᵥ v ∘ Sum.inl + A₂ *ᵥ v ∘ Sum.inr := by
simp [← fromCols_mulVec_sumElim]
@[simp]
lemma fromRows_mul [Fintype n] (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) (B : Matrix n m R) :
fromRows A₁ A₂ * B = fromRows (A₁ * B) (A₂ * B) := by
ext (_ | _) _ <;> simp [mul_apply]
@[simp]
lemma mul_fromCols [Fintype n] (A : Matrix m n R) (B₁ : Matrix n n₁ R) (B₂ : Matrix n n₂ R) :
A * fromCols B₁ B₂ = fromCols (A * B₁) (A * B₂) := by
ext _ (_ | _) <;> simp [mul_apply]
@[simp]
lemma fromRows_zero : fromRows (0 : Matrix m₁ n R) (0 : Matrix m₂ n R) = 0 := by
ext (_ | _) _ <;> simp
@[simp]
lemma fromCols_zero : fromCols (0 : Matrix m n₁ R) (0 : Matrix m n₂ R) = 0 := by
ext _ (_ | _) <;> simp
/-- A row partitioned matrix multiplied by a column partitioned matrix gives a 2 by 2 block
matrix. -/
lemma fromRows_mul_fromCols [Fintype n] (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R)
(B₁ : Matrix n n₁ R) (B₂ : Matrix n n₂ R) :
(fromRows A₁ A₂) * (fromCols B₁ B₂) =
fromBlocks (A₁ * B₁) (A₁ * B₂) (A₂ * B₁) (A₂ * B₂) := by
ext (_ | _) (_ | _) <;> simp
/-- A column partitioned matrix multiplied by a row partitioned matrix gives the sum of the "outer"
products of the block matrices. -/
lemma fromCols_mul_fromRows [Fintype n₁] [Fintype n₂] (A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R)
(B₁ : Matrix n₁ n R) (B₂ : Matrix n₂ n R) :
fromCols A₁ A₂ * fromRows B₁ B₂ = (A₁ * B₁ + A₂ * B₂) := by
ext
simp [mul_apply]
/-- A column partitioned matrix multipiled by a block matrix results in a column partitioned
matrix. -/
lemma fromCols_mul_fromBlocks [Fintype m₁] [Fintype m₂] (A₁ : Matrix m m₁ R) (A₂ : Matrix m m₂ R)
(B₁₁ : Matrix m₁ n₁ R) (B₁₂ : Matrix m₁ n₂ R) (B₂₁ : Matrix m₂ n₁ R) (B₂₂ : Matrix m₂ n₂ R) :
(fromCols A₁ A₂) * fromBlocks B₁₁ B₁₂ B₂₁ B₂₂ =
fromCols (A₁ * B₁₁ + A₂ * B₂₁) (A₁ * B₁₂ + A₂ * B₂₂) := by
ext _ (_ | _) <;> simp [mul_apply]
/-- A block matrix multiplied by a row partitioned matrix gives a row partitioned matrix. -/
lemma fromBlocks_mul_fromRows [Fintype n₁] [Fintype n₂] (A₁ : Matrix n₁ n R) (A₂ : Matrix n₂ n R)
(B₁₁ : Matrix m₁ n₁ R) (B₁₂ : Matrix m₁ n₂ R) (B₂₁ : Matrix m₂ n₁ R) (B₂₂ : Matrix m₂ n₂ R) :
fromBlocks B₁₁ B₁₂ B₂₁ B₂₂ * (fromRows A₁ A₂) =
fromRows (B₁₁ * A₁ + B₁₂ * A₂) (B₂₁ * A₁ + B₂₂ * A₂) := by
ext (_ | _) _ <;> simp [mul_apply]
end Semiring
section CommRing
variable [CommRing R]
/-- Multiplication of a matrix by its inverse is commutative.
This is the column and row partitioned matrix form of `Matrix.mul_eq_one_comm`.
The condition `e : n ≃ n₁ ⊕ n₂` states that `fromCols A₁ A₂` and `fromRows B₁ B₂` are "square".
-/
lemma fromCols_mul_fromRows_eq_one_comm
[Fintype n₁] [Fintype n₂] [Fintype n] [DecidableEq n] [DecidableEq n₁] [DecidableEq n₂]
(e : n ≃ n₁ ⊕ n₂)
(A₁ : Matrix n n₁ R) (A₂ : Matrix n n₂ R) (B₁ : Matrix n₁ n R) (B₂ : Matrix n₂ n R) :
fromCols A₁ A₂ * fromRows B₁ B₂ = 1 ↔ fromRows B₁ B₂ * fromCols A₁ A₂ = 1 :=
mul_eq_one_comm_of_equiv e
/-- The lemma `fromCols_mul_fromRows_eq_one_comm` specialized to the case where the index sets
`n₁` and `n₂`, are the result of subtyping by a predicate and its complement. -/
lemma equiv_compl_fromCols_mul_fromRows_eq_one_comm
[Fintype n] [DecidableEq n] (p : n → Prop) [DecidablePred p]
(A₁ : Matrix n {i // p i} R) (A₂ : Matrix n {i // ¬p i} R)
(B₁ : Matrix {i // p i} n R) (B₂ : Matrix {i // ¬p i} n R) :
fromCols A₁ A₂ * fromRows B₁ B₂ = 1 ↔ fromRows B₁ B₂ * fromCols A₁ A₂ = 1 :=
fromCols_mul_fromRows_eq_one_comm (Equiv.sumCompl p).symm A₁ A₂ B₁ B₂
end CommRing
section Star
variable [Star R]
/-- A column partitioned matrix in a Star ring when conjugate transposed gives a row partitioned
matrix with the columns of the initial matrix conjugate transposed to become rows. -/
lemma conjTranspose_fromCols_eq_fromRows_conjTranspose (A₁ : Matrix m n₁ R)
(A₂ : Matrix m n₂ R) :
conjTranspose (fromCols A₁ A₂) = fromRows (conjTranspose A₁) (conjTranspose A₂) := by
ext (_ | _) _ <;> simp
/-- A row partitioned matrix in a Star ring when conjugate transposed gives a column partitioned
matrix with the rows of the initial matrix conjugate transposed to become columns. -/
lemma conjTranspose_fromRows_eq_fromCols_conjTranspose (A₁ : Matrix m₁ n R)
(A₂ : Matrix m₂ n R) : conjTranspose (fromRows A₁ A₂) =
fromCols (conjTranspose A₁) (conjTranspose A₂) := by
ext _ (_ | _) <;> simp
end Star
end Matrix |
.lake/packages/mathlib/Mathlib/Data/Matrix/Diagonal.lean | import Mathlib.Data.Int.Cast.Basic
import Mathlib.Data.Int.Cast.Pi
import Mathlib.Data.Nat.Cast.Basic
import Mathlib.LinearAlgebra.Matrix.Defs
import Mathlib.Logic.Embedding.Basic
/-!
# Diagonal matrices
This file defines diagonal matrices and the `AddCommMonoidWithOne` structure on matrices.
## Main definitions
* `Matrix.diagonal d`: matrix with the vector `d` along the diagonal
* `Matrix.diag M`: the diagonal of a square matrix
* `Matrix.instAddCommMonoidWithOne`: matrices are an additive commutative monoid with one
-/
assert_not_exists Algebra TrivialStar
universe u u' v w
variable {l m n o : Type*} {m' : o → Type*} {n' : o → Type*}
variable {R : Type*} {S : Type*} {α : Type v} {β : Type w} {γ : Type*}
namespace Matrix
section Diagonal
variable [DecidableEq n]
/-- `diagonal d` is the square matrix such that `(diagonal d) i i = d i` and `(diagonal d) i j = 0`
if `i ≠ j`.
Note that bundled versions exist as:
* `Matrix.diagonalAddMonoidHom`
* `Matrix.diagonalLinearMap`
* `Matrix.diagonalRingHom`
* `Matrix.diagonalAlgHom`
-/
def diagonal [Zero α] (d : n → α) : Matrix n n α :=
of fun i j => if i = j then d i else 0
-- TODO: set as an equation lemma for `diagonal`, see https://github.com/leanprover-community/mathlib4/pull/3024
theorem diagonal_apply [Zero α] (d : n → α) (i j) : diagonal d i j = if i = j then d i else 0 :=
rfl
@[simp]
theorem diagonal_apply_eq [Zero α] (d : n → α) (i : n) : (diagonal d) i i = d i := by
simp [diagonal]
@[simp]
theorem diagonal_apply_ne [Zero α] (d : n → α) {i j : n} (h : i ≠ j) : (diagonal d) i j = 0 := by
simp [diagonal, h]
theorem diagonal_apply_ne' [Zero α] (d : n → α) {i j : n} (h : j ≠ i) : (diagonal d) i j = 0 :=
diagonal_apply_ne d h.symm
@[simp]
theorem diagonal_eq_diagonal_iff [Zero α] {d₁ d₂ : n → α} :
diagonal d₁ = diagonal d₂ ↔ ∀ i, d₁ i = d₂ i :=
⟨fun h i => by simpa using congr_arg (fun m : Matrix n n α => m i i) h, fun h => by
rw [show d₁ = d₂ from funext h]⟩
theorem diagonal_injective [Zero α] : Function.Injective (diagonal : (n → α) → Matrix n n α) :=
fun d₁ d₂ h => funext fun i => by simpa using Matrix.ext_iff.mpr h i i
@[simp]
theorem diagonal_zero [Zero α] : (diagonal fun _ => 0 : Matrix n n α) = 0 := by
ext
simp [diagonal]
@[simp]
theorem diagonal_transpose [Zero α] (v : n → α) : (diagonal v)ᵀ = diagonal v := by
ext i j
by_cases h : i = j
· simp [h, transpose]
· simp [h, transpose, diagonal_apply_ne' _ h]
@[simp]
theorem diagonal_add [AddZeroClass α] (d₁ d₂ : n → α) :
diagonal d₁ + diagonal d₂ = diagonal fun i => d₁ i + d₂ i := by
ext i j
by_cases h : i = j <;>
simp [h]
@[simp]
theorem diagonal_smul [Zero α] [SMulZeroClass R α] (r : R) (d : n → α) :
diagonal (r • d) = r • diagonal d := by
ext i j
by_cases h : i = j <;> simp [h]
@[simp]
theorem diagonal_neg [NegZeroClass α] (d : n → α) :
-diagonal d = diagonal fun i => -d i := by
ext i j
by_cases h : i = j <;>
simp [h]
@[simp]
theorem diagonal_sub [SubNegZeroMonoid α] (d₁ d₂ : n → α) :
diagonal d₁ - diagonal d₂ = diagonal fun i => d₁ i - d₂ i := by
ext i j
by_cases h : i = j <;>
simp [h]
theorem diagonal_mem_matrix_iff [Zero α] {S : Set α} (hS : 0 ∈ S) {d : n → α} :
Matrix.diagonal d ∈ S.matrix ↔ ∀ i, d i ∈ S := by
simp only [Set.mem_matrix, diagonal, of_apply]
conv_lhs => intro _ _; rw [ite_mem]
simp [hS]
instance [Zero α] [NatCast α] : NatCast (Matrix n n α) where
natCast m := diagonal fun _ => m
@[norm_cast]
theorem diagonal_natCast [Zero α] [NatCast α] (m : ℕ) : diagonal (fun _ : n => (m : α)) = m := rfl
@[norm_cast]
theorem diagonal_natCast' [Zero α] [NatCast α] (m : ℕ) : diagonal ((m : n → α)) = m := rfl
theorem diagonal_ofNat [Zero α] [NatCast α] (m : ℕ) [m.AtLeastTwo] :
diagonal (fun _ : n => (ofNat(m) : α)) = OfNat.ofNat m := rfl
theorem diagonal_ofNat' [Zero α] [NatCast α] (m : ℕ) [m.AtLeastTwo] :
diagonal (ofNat(m) : n → α) = OfNat.ofNat m := rfl
instance [Zero α] [IntCast α] : IntCast (Matrix n n α) where
intCast m := diagonal fun _ => m
@[norm_cast]
theorem diagonal_intCast [Zero α] [IntCast α] (m : ℤ) : diagonal (fun _ : n => (m : α)) = m := rfl
@[norm_cast]
theorem diagonal_intCast' [Zero α] [IntCast α] (m : ℤ) : diagonal ((m : n → α)) = m := rfl
@[simp]
theorem diagonal_map [Zero α] [Zero β] {f : α → β} (h : f 0 = 0) {d : n → α} :
(diagonal d).map f = diagonal fun m => f (d m) := by
ext
simp only [diagonal_apply, map_apply]
split_ifs <;> simp [h]
protected theorem map_natCast [AddMonoidWithOne α] [Zero β]
{f : α → β} (h : f 0 = 0) (d : ℕ) :
(d : Matrix n n α).map f = diagonal (fun _ => f d) :=
diagonal_map h
protected theorem map_ofNat [AddMonoidWithOne α] [Zero β]
{f : α → β} (h : f 0 = 0) (d : ℕ) [d.AtLeastTwo] :
(ofNat(d) : Matrix n n α).map f = diagonal (fun _ => f (OfNat.ofNat d)) :=
diagonal_map h
theorem natCast_apply [AddMonoidWithOne α] {i j} {d : ℕ} :
(d : Matrix n n α) i j = if i = j then d else 0 := by
rw [Nat.cast_ite, Nat.cast_zero, ← diagonal_natCast, diagonal_apply]
theorem ofNat_apply [AddMonoidWithOne α] {i j} {d : ℕ} [d.AtLeastTwo] :
(ofNat(d) : Matrix n n α) i j = if i = j then d else 0 :=
natCast_apply
protected theorem map_intCast [AddGroupWithOne α] [Zero β]
{f : α → β} (h : f 0 = 0) (d : ℤ) :
(d : Matrix n n α).map f = diagonal (fun _ => f d) :=
diagonal_map h
theorem diagonal_unique [Unique m] [DecidableEq m] [Zero α] (d : m → α) :
diagonal d = of fun _ _ => d default := by
ext i j
rw [Subsingleton.elim i default, Subsingleton.elim j default, diagonal_apply_eq _ _, of_apply]
@[simp]
theorem col_diagonal [Zero α] (d : n → α) (i) : (diagonal d).col i = Pi.single i (d i) := by
ext
simp +contextual [diagonal, Pi.single_apply]
@[simp]
theorem row_diagonal [Zero α] (d : n → α) (j) : (diagonal d).row j = Pi.single j (d j) := by
ext
simp +contextual [diagonal, eq_comm, Pi.single_apply]
section One
variable [Zero α] [One α]
instance one : One (Matrix n n α) :=
⟨diagonal fun _ => 1⟩
@[simp]
theorem diagonal_one : (diagonal fun _ => 1 : Matrix n n α) = 1 :=
rfl
@[simp]
theorem diagonal_one' : (diagonal 1 : Matrix n n α) = 1 :=
rfl
theorem one_apply {i j} : (1 : Matrix n n α) i j = if i = j then 1 else 0 :=
rfl
@[simp]
theorem one_apply_eq (i) : (1 : Matrix n n α) i i = 1 :=
diagonal_apply_eq _ i
@[simp]
theorem one_apply_ne {i j} : i ≠ j → (1 : Matrix n n α) i j = 0 :=
diagonal_apply_ne _
theorem one_apply_ne' {i j} : j ≠ i → (1 : Matrix n n α) i j = 0 :=
diagonal_apply_ne' _
@[simp]
protected theorem map_one [Zero β] [One β] (f : α → β) (h₀ : f 0 = 0) (h₁ : f 1 = 1) :
(1 : Matrix n n α).map f = (1 : Matrix n n β) := by
ext
simp only [one_apply, map_apply]
split_ifs <;> simp [h₀, h₁]
theorem one_eq_pi_single {i j} : (1 : Matrix n n α) i j = Pi.single (M := fun _ => α) i 1 j := by
simp only [one_apply, Pi.single_apply, eq_comm]
end One
instance instAddMonoidWithOne [AddMonoidWithOne α] : AddMonoidWithOne (Matrix n n α) where
natCast_zero := show diagonal _ = _ by
rw [Nat.cast_zero, diagonal_zero]
natCast_succ n := show diagonal _ = diagonal _ + _ by
rw [Nat.cast_succ, ← diagonal_add, diagonal_one]
instance instAddGroupWithOne [AddGroupWithOne α] : AddGroupWithOne (Matrix n n α) where
intCast_ofNat n := show diagonal _ = diagonal _ by
rw [Int.cast_natCast]
intCast_negSucc n := show diagonal _ = -(diagonal _) by
rw [Int.cast_negSucc, diagonal_neg]
__ := addGroup
__ := instAddMonoidWithOne
instance instAddCommMonoidWithOne [AddCommMonoidWithOne α] :
AddCommMonoidWithOne (Matrix n n α) where
__ := addCommMonoid
__ := instAddMonoidWithOne
instance instAddCommGroupWithOne [AddCommGroupWithOne α] :
AddCommGroupWithOne (Matrix n n α) where
__ := addCommGroup
__ := instAddGroupWithOne
end Diagonal
section Diag
/-- The diagonal of a square matrix. -/
def diag (A : Matrix n n α) (i : n) : α :=
A i i
@[simp]
theorem diag_apply (A : Matrix n n α) (i) : diag A i = A i i :=
rfl
@[simp]
theorem diag_diagonal [DecidableEq n] [Zero α] (a : n → α) : diag (diagonal a) = a :=
funext <| @diagonal_apply_eq _ _ _ _ a
@[simp]
theorem diag_transpose (A : Matrix n n α) : diag Aᵀ = diag A :=
rfl
@[simp]
theorem diag_zero [Zero α] : diag (0 : Matrix n n α) = 0 :=
rfl
@[simp]
theorem diag_add [Add α] (A B : Matrix n n α) : diag (A + B) = diag A + diag B :=
rfl
@[simp]
theorem diag_sub [Sub α] (A B : Matrix n n α) : diag (A - B) = diag A - diag B :=
rfl
@[simp]
theorem diag_neg [Neg α] (A : Matrix n n α) : diag (-A) = -diag A :=
rfl
@[simp]
theorem diag_smul [SMul R α] (r : R) (A : Matrix n n α) : diag (r • A) = r • diag A :=
rfl
@[simp]
theorem diag_one [DecidableEq n] [Zero α] [One α] : diag (1 : Matrix n n α) = 1 :=
diag_diagonal _
theorem diag_map {f : α → β} {A : Matrix n n α} : diag (A.map f) = f ∘ diag A :=
rfl
end Diag
end Matrix
open Matrix
namespace Matrix
section Transpose
@[simp]
theorem transpose_eq_diagonal [DecidableEq n] [Zero α] {M : Matrix n n α} {v : n → α} :
Mᵀ = diagonal v ↔ M = diagonal v :=
(Function.Involutive.eq_iff transpose_transpose).trans <|
by rw [diagonal_transpose]
@[simp]
theorem transpose_one [DecidableEq n] [Zero α] [One α] : (1 : Matrix n n α)ᵀ = 1 :=
diagonal_transpose _
@[simp]
theorem transpose_eq_one [DecidableEq n] [Zero α] [One α] {M : Matrix n n α} : Mᵀ = 1 ↔ M = 1 :=
transpose_eq_diagonal
@[simp]
theorem transpose_natCast [DecidableEq n] [AddMonoidWithOne α] (d : ℕ) :
(d : Matrix n n α)ᵀ = d :=
diagonal_transpose _
@[simp]
theorem transpose_eq_natCast [DecidableEq n] [AddMonoidWithOne α] {M : Matrix n n α} {d : ℕ} :
Mᵀ = d ↔ M = d :=
transpose_eq_diagonal
@[simp]
theorem transpose_ofNat [DecidableEq n] [AddMonoidWithOne α] (d : ℕ) [d.AtLeastTwo] :
(ofNat(d) : Matrix n n α)ᵀ = OfNat.ofNat d :=
transpose_natCast _
@[simp]
theorem transpose_eq_ofNat [DecidableEq n] [AddMonoidWithOne α]
{M : Matrix n n α} {d : ℕ} [d.AtLeastTwo] :
Mᵀ = ofNat(d) ↔ M = OfNat.ofNat d :=
transpose_eq_diagonal
@[simp]
theorem transpose_intCast [DecidableEq n] [AddGroupWithOne α] (d : ℤ) :
(d : Matrix n n α)ᵀ = d :=
diagonal_transpose _
@[simp]
theorem transpose_eq_intCast [DecidableEq n] [AddGroupWithOne α]
{M : Matrix n n α} {d : ℤ} :
Mᵀ = d ↔ M = d :=
transpose_eq_diagonal
end Transpose
/-- Given a `(m × m)` diagonal matrix defined by a map `d : m → α`, if the reindexing map `e` is
injective, then the resulting matrix is again diagonal. -/
theorem submatrix_diagonal [Zero α] [DecidableEq m] [DecidableEq l] (d : m → α) (e : l → m)
(he : Function.Injective e) : (diagonal d).submatrix e e = diagonal (d ∘ e) :=
ext fun i j => by
rw [submatrix_apply]
by_cases h : i = j
· rw [h, diagonal_apply_eq, diagonal_apply_eq, Function.comp_apply]
· rw [diagonal_apply_ne _ h, diagonal_apply_ne _ (he.ne h)]
theorem submatrix_one [Zero α] [One α] [DecidableEq m] [DecidableEq l] (e : l → m)
(he : Function.Injective e) : (1 : Matrix m m α).submatrix e e = 1 :=
submatrix_diagonal _ e he
theorem diag_submatrix (A : Matrix m m α) (e : l → m) : diag (A.submatrix e e) = A.diag ∘ e :=
rfl
/-! `simp` lemmas for `Matrix.submatrix`s interaction with `Matrix.diagonal`, `1`, and `Matrix.mul`
for when the mappings are bundled. -/
@[simp]
theorem submatrix_diagonal_embedding [Zero α] [DecidableEq m] [DecidableEq l] (d : m → α)
(e : l ↪ m) : (diagonal d).submatrix e e = diagonal (d ∘ e) :=
submatrix_diagonal d e e.injective
@[simp]
theorem submatrix_diagonal_equiv [Zero α] [DecidableEq m] [DecidableEq l] (d : m → α) (e : l ≃ m) :
(diagonal d).submatrix e e = diagonal (d ∘ e) :=
submatrix_diagonal d e e.injective
@[simp]
theorem submatrix_one_embedding [Zero α] [One α] [DecidableEq m] [DecidableEq l] (e : l ↪ m) :
(1 : Matrix m m α).submatrix e e = 1 :=
submatrix_one e e.injective
@[simp]
theorem submatrix_one_equiv [Zero α] [One α] [DecidableEq m] [DecidableEq l] (e : l ≃ m) :
(1 : Matrix m m α).submatrix e e = 1 :=
submatrix_one e e.injective
end Matrix |
.lake/packages/mathlib/Mathlib/Data/Matrix/Reflection.lean | import Mathlib.Data.Fin.Tuple.Reflection
import Mathlib.LinearAlgebra.Matrix.Notation
/-!
# Lemmas for concrete matrices `Matrix (Fin m) (Fin n) α`
This file contains alternative definitions of common operators on matrices that expand
definitionally to the expected expression when evaluated on `!![]` notation.
This allows "proof by reflection", where we prove `A = !![A 0 0, A 0 1; A 1 0, A 1 1]` by defining
`Matrix.etaExpand A` to be equal to the RHS definitionally, and then prove that
`A = eta_expand A`.
The definitions in this file should normally not be used directly; the intent is for the
corresponding `*_eq` lemmas to be used in a place where they are definitionally unfolded.
## Main definitions
* `Matrix.transposeᵣ`
* `dotProductᵣ`
* `Matrix.mulᵣ`
* `Matrix.mulVecᵣ`
* `Matrix.vecMulᵣ`
* `Matrix.etaExpand`
-/
open Matrix
namespace Matrix
variable {l m n : ℕ} {α : Type*}
/-- `∀` with better defeq for `∀ x : Matrix (Fin m) (Fin n) α, P x`. -/
def Forall : ∀ {m n} (_ : Matrix (Fin m) (Fin n) α → Prop), Prop
| 0, _, P => P (of ![])
| _ + 1, _, P => FinVec.Forall fun r => Forall fun A => P (of (Matrix.vecCons r A))
/-- This can be used to prove
```lean
example (P : Matrix (Fin 2) (Fin 3) α → Prop) :
(∀ x, P x) ↔ ∀ a b c d e f, P !![a, b, c; d, e, f] :=
(forall_iff _).symm
```
-/
theorem forall_iff : ∀ {m n} (P : Matrix (Fin m) (Fin n) α → Prop), Forall P ↔ ∀ x, P x
| 0, _, _ => Iff.symm Fin.forall_fin_zero_pi
| m + 1, n, P => by
simp only [Forall, FinVec.forall_iff, forall_iff]
exact Iff.symm Fin.forall_fin_succ_pi
example (P : Matrix (Fin 2) (Fin 3) α → Prop) :
(∀ x, P x) ↔ ∀ a b c d e f, P !![a, b, c; d, e, f] :=
(forall_iff _).symm
/-- `∃` with better defeq for `∃ x : Matrix (Fin m) (Fin n) α, P x`. -/
def Exists : ∀ {m n} (_ : Matrix (Fin m) (Fin n) α → Prop), Prop
| 0, _, P => P (of ![])
| _ + 1, _, P => FinVec.Exists fun r => Exists fun A => P (of (Matrix.vecCons r A))
/-- This can be used to prove
```lean
example (P : Matrix (Fin 2) (Fin 3) α → Prop) :
(∃ x, P x) ↔ ∃ a b c d e f, P !![a, b, c; d, e, f] :=
(exists_iff _).symm
```
-/
theorem exists_iff : ∀ {m n} (P : Matrix (Fin m) (Fin n) α → Prop), Exists P ↔ ∃ x, P x
| 0, _, _ => Iff.symm Fin.exists_fin_zero_pi
| m + 1, n, P => by
simp only [Exists, FinVec.exists_iff, exists_iff]
exact Iff.symm Fin.exists_fin_succ_pi
example (P : Matrix (Fin 2) (Fin 3) α → Prop) :
(∃ x, P x) ↔ ∃ a b c d e f, P !![a, b, c; d, e, f] :=
(exists_iff _).symm
/-- `Matrix.transpose` with better defeq for `Fin` -/
def transposeᵣ : ∀ {m n}, Matrix (Fin m) (Fin n) α → Matrix (Fin n) (Fin m) α
| _, 0, _ => of ![]
| _, _ + 1, A =>
of <| vecCons (FinVec.map (fun v : Fin _ → α => v 0) A) (transposeᵣ (A.submatrix id Fin.succ))
/-- This can be used to prove
```lean
example (a b c d : α) : transpose !![a, b; c, d] = !![a, c; b, d] := (transposeᵣ_eq _).symm
```
-/
@[simp]
theorem transposeᵣ_eq : ∀ {m n} (A : Matrix (Fin m) (Fin n) α), transposeᵣ A = transpose A
| _, 0, _ => Subsingleton.elim _ _
| m, n + 1, A =>
Matrix.ext fun i j => by
simp_rw [transposeᵣ, transposeᵣ_eq]
refine i.cases ?_ fun i => ?_
· dsimp
rw [FinVec.map_eq, Function.comp_apply]
· simp only [of_apply, Matrix.cons_val_succ]
rfl
example (a b c d : α) : transpose !![a, b; c, d] = !![a, c; b, d] :=
(transposeᵣ_eq _).symm
/-- `dotProduct` with better defeq for `Fin` -/
def dotProductᵣ [Mul α] [Add α] [Zero α] {m} (a b : Fin m → α) : α :=
FinVec.sum <| FinVec.seq (FinVec.map (· * ·) a) b
/-- This can be used to prove
```lean
example (a b c d : α) [Mul α] [AddCommMonoid α] :
dot_product ![a, b] ![c, d] = a * c + b * d :=
(dot_productᵣ_eq _ _).symm
```
-/
@[simp]
theorem dotProductᵣ_eq [Mul α] [AddCommMonoid α] {m} (a b : Fin m → α) :
dotProductᵣ a b = a ⬝ᵥ b := by
simp_rw [dotProductᵣ, dotProduct, FinVec.sum_eq, FinVec.seq_eq, FinVec.map_eq,
Function.comp_apply]
example (a b c d : α) [Mul α] [AddCommMonoid α] : ![a, b] ⬝ᵥ ![c, d] = a * c + b * d :=
(dotProductᵣ_eq _ _).symm
/-- `Matrix.mul` with better defeq for `Fin` -/
def mulᵣ [Mul α] [Add α] [Zero α] (A : Matrix (Fin l) (Fin m) α) (B : Matrix (Fin m) (Fin n) α) :
Matrix (Fin l) (Fin n) α :=
of <| FinVec.map (fun v₁ => FinVec.map (fun v₂ => dotProductᵣ v₁ v₂) Bᵀ) A
/-- This can be used to prove
```lean
example [AddCommMonoid α] [Mul α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁₁ b₁₂ b₂₁ b₂₂ : α) :
!![a₁₁, a₁₂;
a₂₁, a₂₂] * !![b₁₁, b₁₂;
b₂₁, b₂₂] =
!![a₁₁*b₁₁ + a₁₂*b₂₁, a₁₁*b₁₂ + a₁₂*b₂₂;
a₂₁*b₁₁ + a₂₂*b₂₁, a₂₁*b₁₂ + a₂₂*b₂₂] :=
(mulᵣ_eq _ _).symm
```
-/
@[simp]
theorem mulᵣ_eq [Mul α] [AddCommMonoid α] (A : Matrix (Fin l) (Fin m) α)
(B : Matrix (Fin m) (Fin n) α) : mulᵣ A B = A * B := by
simp [mulᵣ, Matrix.transpose]
rfl
example [AddCommMonoid α] [Mul α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁₁ b₁₂ b₂₁ b₂₂ : α) :
!![a₁₁, a₁₂; a₂₁, a₂₂] * !![b₁₁, b₁₂; b₂₁, b₂₂] =
!![a₁₁ * b₁₁ + a₁₂ * b₂₁, a₁₁ * b₁₂ + a₁₂ * b₂₂;
a₂₁ * b₁₁ + a₂₂ * b₂₁, a₂₁ * b₁₂ + a₂₂ * b₂₂] :=
(mulᵣ_eq _ _).symm
/-- `Matrix.mulVec` with better defeq for `Fin` -/
def mulVecᵣ [Mul α] [Add α] [Zero α] (A : Matrix (Fin l) (Fin m) α) (v : Fin m → α) : Fin l → α :=
FinVec.map (fun a => dotProductᵣ a v) A
/-- This can be used to prove
```lean
example [NonUnitalNonAssocSemiring α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁ b₂ : α) :
!![a₁₁, a₁₂;
a₂₁, a₂₂] *ᵥ ![b₁, b₂] = ![a₁₁*b₁ + a₁₂*b₂, a₂₁*b₁ + a₂₂*b₂] :=
(mulVecᵣ_eq _ _).symm
```
-/
@[simp]
theorem mulVecᵣ_eq [NonUnitalNonAssocSemiring α] (A : Matrix (Fin l) (Fin m) α) (v : Fin m → α) :
mulVecᵣ A v = A *ᵥ v := by
simp [mulVecᵣ]
rfl
example [NonUnitalNonAssocSemiring α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁ b₂ : α) :
!![a₁₁, a₁₂; a₂₁, a₂₂] *ᵥ ![b₁, b₂] = ![a₁₁ * b₁ + a₁₂ * b₂, a₂₁ * b₁ + a₂₂ * b₂] :=
(mulVecᵣ_eq _ _).symm
/-- `Matrix.vecMul` with better defeq for `Fin` -/
def vecMulᵣ [Mul α] [Add α] [Zero α] (v : Fin l → α) (A : Matrix (Fin l) (Fin m) α) : Fin m → α :=
FinVec.map (fun a => dotProductᵣ v a) Aᵀ
/-- This can be used to prove
```lean
example [NonUnitalNonAssocSemiring α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁ b₂ : α) :
![b₁, b₂] ᵥ* !![a₁₁, a₁₂;
a₂₁, a₂₂] = ![b₁*a₁₁ + b₂*a₂₁, b₁*a₁₂ + b₂*a₂₂] :=
(vecMulᵣ_eq _ _).symm
```
-/
@[simp]
theorem vecMulᵣ_eq [NonUnitalNonAssocSemiring α] (v : Fin l → α) (A : Matrix (Fin l) (Fin m) α) :
vecMulᵣ v A = v ᵥ* A := by
simp [vecMulᵣ]
rfl
example [NonUnitalNonAssocSemiring α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁ b₂ : α) :
![b₁, b₂] ᵥ* !![a₁₁, a₁₂; a₂₁, a₂₂] = ![b₁ * a₁₁ + b₂ * a₂₁, b₁ * a₁₂ + b₂ * a₂₂] :=
(vecMulᵣ_eq _ _).symm
/-- Expand `A` to `!![A 0 0, ...; ..., A m n]` -/
def etaExpand {m n} (A : Matrix (Fin m) (Fin n) α) : Matrix (Fin m) (Fin n) α :=
Matrix.of (FinVec.etaExpand fun i => FinVec.etaExpand fun j => A i j)
/-- This can be used to prove
```lean
example (A : Matrix (Fin 2) (Fin 2) α) :
A = !![A 0 0, A 0 1;
A 1 0, A 1 1] :=
(etaExpand_eq _).symm
```
-/
theorem etaExpand_eq {m n} (A : Matrix (Fin m) (Fin n) α) : etaExpand A = A := by
simp_rw [etaExpand, FinVec.etaExpand_eq, Matrix.of]
grind
example (A : Matrix (Fin 2) (Fin 2) α) : A = !![A 0 0, A 0 1; A 1 0, A 1 1] :=
(etaExpand_eq _).symm
end Matrix |
.lake/packages/mathlib/Mathlib/Data/Matrix/Composition.lean | import Mathlib.Data.Matrix.Basic
import Mathlib.Data.Matrix.Basis
/-!
# Composition of matrices
This file shows that Mₙ(Mₘ(R)) ≃ Mₙₘ(R), Mₙ(Rᵒᵖ) ≃ₐ[K] Mₙ(R)ᵒᵖ
and also different levels of equivalence when R is an AddCommMonoid,
Semiring, and Algebra over a CommSemiring K.
## Main results
* `Matrix.comp` is an equivalence between `Matrix I J (Matrix K L R)` and
`I × K` by `J × L` matrices.
* `Matrix.swap` is an equivalence between `(I × J)` by `(K × L)` matrices and
`J × I` by `L × K` matrices.
-/
namespace Matrix
variable (I J K L R R' : Type*)
/-- I by J matrix where each entry is a K by L matrix is equivalent to
I × K by J × L matrix -/
@[simps]
def comp : Matrix I J (Matrix K L R) ≃ Matrix (I × K) (J × L) R where
toFun m ik jl := m ik.1 jl.1 ik.2 jl.2
invFun n i j k l := n (i, k) (j, l)
section Basic
variable {R I J K L}
theorem comp_map_map (M : Matrix I J (Matrix K L R)) (f : R → R') :
comp I J K L _ (M.map (fun M' => M'.map f)) = (comp I J K L _ M).map f := rfl
@[simp]
theorem comp_single_single
[DecidableEq I] [DecidableEq J] [DecidableEq K] [DecidableEq L] [Zero R] (i j k l r) :
comp I J K L R (single i j (single k l r))
= single (i, k) (j, l) r := by
ext ⟨i', k'⟩ ⟨j', l'⟩
dsimp [comp_apply]
obtain hi | rfl := ne_or_eq i i'
· rw [single_apply_of_row_ne hi,
single_apply_of_row_ne (ne_of_apply_ne Prod.fst hi), Matrix.zero_apply]
obtain hj | rfl := ne_or_eq j j'
· rw [single_apply_of_col_ne _ _ hj,
single_apply_of_col_ne _ _ (ne_of_apply_ne Prod.fst hj), Matrix.zero_apply]
rw [single_apply_same]
obtain hk | rfl := ne_or_eq k k'
· rw [single_apply_of_row_ne hk,
single_apply_of_row_ne (ne_of_apply_ne Prod.snd hk)]
obtain hj | rfl := ne_or_eq l l'
· rw [single_apply_of_col_ne _ _ hj,
single_apply_of_col_ne _ _ (ne_of_apply_ne Prod.snd hj)]
rw [single_apply_same, single_apply_same]
@[deprecated (since := "2025-05-05")] alias comp_stdBasisMatrix_stdBasisMatrix := comp_single_single
@[simp]
theorem comp_symm_single
[DecidableEq I] [DecidableEq J] [DecidableEq K] [DecidableEq L] [Zero R] (ii jj r) :
(comp I J K L R).symm (single ii jj r) =
(single ii.1 jj.1 (single ii.2 jj.2 r)) :=
(comp I J K L R).symm_apply_eq.2 <| comp_single_single _ _ _ _ _ |>.symm
@[deprecated (since := "2025-05-05")] alias comp_symm_stdBasisMatrix := comp_symm_single
@[simp]
theorem comp_diagonal_diagonal [DecidableEq I] [DecidableEq J] [Zero R] (d : I → J → R) :
comp I I J J R (diagonal fun i => diagonal fun j => d i j)
= diagonal fun ij => d ij.1 ij.2 := by
ext ⟨i₁, j₁⟩ ⟨i₂, j₂⟩
dsimp [comp_apply]
obtain hi | rfl := ne_or_eq i₁ i₂
· rw [diagonal_apply_ne _ hi, diagonal_apply_ne _ (ne_of_apply_ne Prod.fst hi),
Matrix.zero_apply]
rw [diagonal_apply_eq]
obtain hj | rfl := ne_or_eq j₁ j₂
· rw [diagonal_apply_ne _ hj, diagonal_apply_ne _ (ne_of_apply_ne Prod.snd hj)]
rw [diagonal_apply_eq, diagonal_apply_eq]
@[simp]
theorem comp_symm_diagonal [DecidableEq I] [DecidableEq J] [Zero R] (d : I × J → R) :
(comp I I J J R).symm (diagonal d) = diagonal fun i => diagonal fun j => d (i, j) :=
(comp I I J J R).symm_apply_eq.2 <| (comp_diagonal_diagonal fun i j => d (i, j)).symm
theorem comp_transpose (M : Matrix I J (Matrix K L R)) :
comp J I K L R Mᵀ = (comp _ _ _ _ R <| M.map (·ᵀ))ᵀ := rfl
theorem comp_map_transpose (M : Matrix I J (Matrix K L R)) :
comp I J L K R (M.map (·ᵀ)) = (comp _ _ _ _ R Mᵀ)ᵀ := rfl
theorem comp_symm_transpose (M : Matrix (I × K) (J × L) R) :
(comp J I L K R).symm Mᵀ = (((comp I J K L R).symm M).map (·ᵀ))ᵀ := rfl
end Basic
section AddCommMonoid
variable [AddCommMonoid R]
/-- `Matrix.comp` as `AddEquiv` -/
def compAddEquiv : Matrix I J (Matrix K L R) ≃+ Matrix (I × K) (J × L) R where
__ := Matrix.comp I J K L R
map_add' _ _ := rfl
@[simp]
theorem compAddEquiv_apply (M : Matrix I J (Matrix K L R)) :
compAddEquiv I J K L R M = comp I J K L R M := rfl
@[simp]
theorem compAddEquiv_symm_apply (M : Matrix (I × K) (J × L) R) :
(compAddEquiv I J K L R).symm M = (comp I J K L R).symm M := rfl
end AddCommMonoid
section Semiring
variable [Semiring R] [Fintype I] [Fintype J]
/-- `Matrix.comp` as `RingEquiv` -/
def compRingEquiv : Matrix I I (Matrix J J R) ≃+* Matrix (I × J) (I × J) R where
__ := Matrix.compAddEquiv I I J J R
map_mul' _ _ := by ext; exact (Matrix.sum_apply ..).trans <| .symm <| Fintype.sum_prod_type ..
@[simp]
theorem compRingEquiv_apply (M : Matrix I I (Matrix J J R)) :
compRingEquiv I J R M = comp I I J J R M := rfl
@[simp]
theorem compRingEquiv_symm_apply (M : Matrix (I × J) (I × J) R) :
(compRingEquiv I J R).symm M = (comp I I J J R).symm M := rfl
end Semiring
section LinearMap
variable (K : Type*) [CommSemiring K] [AddCommMonoid R] [Module K R]
/-- `Matrix.comp` as `LinearEquiv` -/
@[simps!]
def compLinearEquiv : Matrix I J (Matrix K L R) ≃ₗ[K] Matrix (I × K) (J × L) R where
__ := Matrix.compAddEquiv I J K L R
map_smul' _ _ := rfl
end LinearMap
section Algebra
variable (K : Type*) [CommSemiring K] [Semiring R] [Fintype I] [Fintype J] [Algebra K R]
variable [DecidableEq I] [DecidableEq J]
/-- `Matrix.comp` as `AlgEquiv` -/
def compAlgEquiv : Matrix I I (Matrix J J R) ≃ₐ[K] Matrix (I × J) (I × J) R where
__ := Matrix.compRingEquiv I J R
commutes' _ := comp_diagonal_diagonal _
@[simp]
theorem compAlgEquiv_apply (M : Matrix I I (Matrix J J R)) :
compAlgEquiv I J R K M = comp I I J J R M := rfl
@[simp]
theorem compAlgEquiv_symm_apply (M : Matrix (I × J) (I × J) R) :
(compAlgEquiv I J R K).symm M = (comp I I J J R).symm M := rfl
@[simp]
theorem isUnit_comp_iff {M : Matrix I I (Matrix J J R)} : IsUnit (comp _ _ _ _ _ M) ↔ IsUnit M :=
isUnit_map_iff (compAlgEquiv _ _ _ ℕ) M
@[simp]
theorem isUnit_comp_symm_iff {M : Matrix (I × J) (I × J) R} :
IsUnit (comp _ _ _ _ _ |>.symm M) ↔ IsUnit M :=
isUnit_map_iff (compAlgEquiv _ _ _ ℕ).symm M
end Algebra
end Matrix |
.lake/packages/mathlib/Mathlib/Data/Matrix/Invertible.lean | import Mathlib.LinearAlgebra.Matrix.ConjTranspose
import Mathlib.Tactic.Abel
/-! # Extra lemmas about invertible matrices
A few of the `Invertible` lemmas generalize to multiplication of rectangular matrices.
For lemmas about the matrix inverse in terms of the determinant and adjugate, see `Matrix.inv`
in `LinearAlgebra/Matrix/NonsingularInverse.lean`.
## Main results
* `Matrix.invertibleConjTranspose`
* `Matrix.invertibleTranspose`
* `Matrix.isUnit_conjTranspose`
* `Matrix.isUnit_transpose`
-/
open scoped Matrix
variable {m n : Type*} {α : Type*}
variable [Fintype n] [DecidableEq n]
namespace Matrix
section Semiring
variable [Semiring α]
/-- A copy of `invOf_mul_cancel_left` for rectangular matrices. -/
protected theorem invOf_mul_cancel_left (A : Matrix n n α) (B : Matrix n m α) [Invertible A] :
⅟A * (A * B) = B := by rw [← Matrix.mul_assoc, invOf_mul_self, Matrix.one_mul]
/-- A copy of `mul_invOf_cancel_left` for rectangular matrices. -/
protected theorem mul_invOf_cancel_left (A : Matrix n n α) (B : Matrix n m α) [Invertible A] :
A * (⅟A * B) = B := by rw [← Matrix.mul_assoc, mul_invOf_self, Matrix.one_mul]
/-- A copy of `invOf_mul_cancel_right` for rectangular matrices. -/
protected theorem invOf_mul_cancel_right (A : Matrix m n α) (B : Matrix n n α) [Invertible B] :
A * ⅟B * B = A := by rw [Matrix.mul_assoc, invOf_mul_self, Matrix.mul_one]
/-- A copy of `mul_invOf_cancel_right` for rectangular matrices. -/
protected theorem mul_invOf_cancel_right (A : Matrix m n α) (B : Matrix n n α) [Invertible B] :
A * B * ⅟B = A := by rw [Matrix.mul_assoc, mul_invOf_self, Matrix.mul_one]
/-- A copy oy of `invOf_mul_eq_iff_eq_mul_left` for rectangular matrices. -/
protected theorem invOf_mul_eq_iff_eq_mul_left
{A B : Matrix n m α} {C : Matrix n n α} [Invertible C] :
⅟C * A = B ↔ A = C * B := by
refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩
· rw [← h, Matrix.mul_invOf_cancel_left]
· rw [h, Matrix.invOf_mul_cancel_left]
/-- A copy oy of `mul_left_eq_iff_eq_invOf_mul` for rectangular matrices. -/
protected theorem mul_left_eq_iff_eq_invOf_mul
{A B : Matrix n m α} {C : Matrix n n α} [Invertible C] :
C * A = B ↔ A = ⅟C * B := by
rw [eq_comm, ← Matrix.invOf_mul_eq_iff_eq_mul_left, eq_comm]
/-- A copy oy of `mul_invOf_eq_iff_eq_mul_right` for rectangular matrices. -/
protected theorem mul_invOf_eq_iff_eq_mul_right
{A B : Matrix m n α} {C : Matrix n n α} [Invertible C] :
A * ⅟C = B ↔ A = B * C := by
refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩
· rw [← h, Matrix.invOf_mul_cancel_right]
· rw [h, Matrix.mul_invOf_cancel_right]
/-- A copy oy of `mul_right_eq_iff_eq_mul_invOf` for rectangular matrices. -/
protected theorem mul_right_eq_iff_eq_mul_invOf
{A B : Matrix m n α} {C : Matrix n n α} [Invertible C] :
A * C = B ↔ A = B * ⅟C := by
rw [eq_comm, ← Matrix.mul_invOf_eq_iff_eq_mul_right, eq_comm]
section ConjTranspose
variable [StarRing α] (A : Matrix n n α)
/-- The conjugate transpose of an invertible matrix is invertible. -/
instance invertibleConjTranspose [Invertible A] : Invertible Aᴴ := Invertible.star _
lemma conjTranspose_invOf [Invertible A] [Invertible Aᴴ] : (⅟A)ᴴ = ⅟(Aᴴ) := star_invOf _
/-- A matrix is invertible if the conjugate transpose is invertible. -/
def invertibleOfInvertibleConjTranspose [Invertible Aᴴ] : Invertible A := by
rw [← conjTranspose_conjTranspose A, ← star_eq_conjTranspose]
infer_instance
@[simp] lemma isUnit_conjTranspose : IsUnit Aᴴ ↔ IsUnit A := isUnit_star
end ConjTranspose
end Semiring
section CommSemiring
variable [CommSemiring α] (A : Matrix n n α)
/-- The transpose of an invertible matrix is invertible. -/
instance invertibleTranspose [Invertible A] : Invertible Aᵀ where
invOf := (⅟A)ᵀ
invOf_mul_self := by rw [← transpose_mul, mul_invOf_self, transpose_one]
mul_invOf_self := by rw [← transpose_mul, invOf_mul_self, transpose_one]
lemma transpose_invOf [Invertible A] [Invertible Aᵀ] : (⅟A)ᵀ = ⅟(Aᵀ) := by
letI := invertibleTranspose A
convert (rfl : _ = ⅟(Aᵀ))
/-- `Aᵀ` is invertible when `A` is. -/
def invertibleOfInvertibleTranspose [Invertible Aᵀ] : Invertible A where
invOf := (⅟(Aᵀ))ᵀ
invOf_mul_self := by rw [← transpose_one, ← mul_invOf_self Aᵀ, transpose_mul, transpose_transpose]
mul_invOf_self := by rw [← transpose_one, ← invOf_mul_self Aᵀ, transpose_mul, transpose_transpose]
/-- Together `Matrix.invertibleTranspose` and `Matrix.invertibleOfInvertibleTranspose` form an
equivalence, although both sides of the equiv are subsingleton anyway. -/
@[simps]
def transposeInvertibleEquivInvertible : Invertible Aᵀ ≃ Invertible A where
toFun := @invertibleOfInvertibleTranspose _ _ _ _ _ _
invFun := @invertibleTranspose _ _ _ _ _ _
left_inv _ := Subsingleton.elim _ _
right_inv _ := Subsingleton.elim _ _
@[simp] lemma isUnit_transpose : IsUnit Aᵀ ↔ IsUnit A := by
simp only [← nonempty_invertible_iff_isUnit,
(transposeInvertibleEquivInvertible A).nonempty_congr]
end CommSemiring
section Ring
section Woodbury
variable [Fintype m] [DecidableEq m] [Ring α]
(A : Matrix n n α) (U : Matrix n m α) (C : Matrix m m α) (V : Matrix m n α)
[Invertible A] [Invertible C] [Invertible (⅟C + V * ⅟A * U)]
-- No spaces around multiplication signs for better clarity
set_option linter.style.commandStart false in
lemma add_mul_mul_invOf_mul_eq_one :
(A + U*C*V)*(⅟A - ⅟A*U*⅟(⅟C + V*⅟A*U)*V*⅟A) = 1 := by
calc
(A + U*C*V)*(⅟A - ⅟A*U*⅟(⅟C + V*⅟A*U)*V*⅟A)
_ = A*⅟A - A*⅟A*U*⅟(⅟C + V*⅟A*U)*V*⅟A + U*C*V*⅟A - U*C*V*⅟A*U*⅟(⅟C + V*⅟A*U)*V*⅟A := by
simp_rw [add_sub_assoc, add_mul, mul_sub, Matrix.mul_assoc]
_ = (1 + U*C*V*⅟A) - (U*⅟(⅟C + V*⅟A*U)*V*⅟A + U*C*V*⅟A*U*⅟(⅟C + V*⅟A*U)*V*⅟A) := by
rw [mul_invOf_self, Matrix.one_mul]
abel
_ = 1 + U*C*V*⅟A - (U + U*C*V*⅟A*U)*⅟(⅟C + V*⅟A*U)*V*⅟A := by
rw [sub_right_inj, Matrix.add_mul, Matrix.add_mul, Matrix.add_mul]
_ = 1 + U*C*V*⅟A - U*C*(⅟C + V*⅟A*U)*⅟(⅟C + V*⅟A*U)*V*⅟A := by
congr
simp only [Matrix.mul_add, Matrix.mul_invOf_cancel_right, ← Matrix.mul_assoc]
_ = 1 := by
rw [Matrix.mul_invOf_cancel_right]
abel
-- No spaces around multiplication signs for better clarity
set_option linter.style.commandStart false in
/-- Like `add_mul_mul_invOf_mul_eq_one`, but with multiplication reversed. -/
lemma add_mul_mul_invOf_mul_eq_one' :
(⅟A - ⅟A*U*⅟(⅟C + V*⅟A*U)*V*⅟A)*(A + U*C*V) = 1 := by
calc
(⅟A - ⅟A*U*⅟(⅟C + V*⅟A*U)*V*⅟A)*(A + U*C*V)
_ = ⅟A*A - ⅟A*U*⅟(⅟C + V*⅟A*U)*V*⅟A*A + ⅟A*U*C*V - ⅟A*U*⅟(⅟C + V*⅟A*U)*V*⅟A*U*C*V := by
simp_rw [add_sub_assoc, _root_.mul_add, _root_.sub_mul, Matrix.mul_assoc]
_ = (1 + ⅟A*U*C*V) - (⅟A*U*⅟(⅟C + V*⅟A*U)*V + ⅟A*U*⅟(⅟C + V*⅟A*U)*V*⅟A*U*C*V) := by
rw [invOf_mul_self, Matrix.invOf_mul_cancel_right]
abel
_ = 1 + ⅟A*U*C*V - ⅟A*U*⅟(⅟C + V*⅟A*U)*(V + V*⅟A*U*C*V) := by
rw [sub_right_inj, Matrix.mul_add]
simp_rw [Matrix.mul_assoc]
_ = 1 + ⅟A*U*C*V - ⅟A*U*⅟(⅟C + V*⅟A*U)*(⅟C + V*⅟A*U)*C*V := by
congr 1
simp only [Matrix.mul_add, Matrix.add_mul, ← Matrix.mul_assoc,
Matrix.invOf_mul_cancel_right]
_ = 1 := by
rw [Matrix.invOf_mul_cancel_right]
abel
/-- If matrices `A`, `C`, and `C⁻¹ + V * A⁻¹ * U` are invertible, then so is `A + U * C * V`. -/
def invertibleAddMulMul : Invertible (A + U * C * V) where
invOf := ⅟A - ⅟A * U * ⅟(⅟C + V * ⅟A * U) * V * ⅟A
invOf_mul_self := add_mul_mul_invOf_mul_eq_one' _ _ _ _
mul_invOf_self := add_mul_mul_invOf_mul_eq_one _ _ _ _
/-- The **Woodbury Identity** (`⅟` version).
See `Matrix.invOf_add_mul_mul'` for the Binomial Inverse Theorem. -/
theorem invOf_add_mul_mul [Invertible (A + U * C * V)] :
⅟(A + U * C * V) = ⅟A - ⅟A * U * ⅟(⅟C + V * ⅟A * U) * V * ⅟A := by
letI := invertibleAddMulMul A U C V
convert (rfl : ⅟(A + U * C * V) = _)
end Woodbury
section BinomialInverseTheorem
variable [Fintype m] [DecidableEq m] [Ring α]
(A : Matrix n n α) (U : Matrix n m α) (C : Matrix m m α) (V : Matrix m n α)
[Invertible A] [Invertible (C + C * V * ⅟A * U * C)]
lemma add_mul_mul_mul_invOf_eq_one :
(A + U * C * V) * (⅟A - ⅟A * U * C * ⅟(C + C * V * ⅟A * U * C) * C * V * ⅟A) = 1 := by
simp only [Matrix.mul_sub, Matrix.add_mul, mul_invOf_self']
rw [add_sub_assoc, add_eq_left, sub_eq_zero]
simp only [← Matrix.mul_assoc, mul_invOf_self', Matrix.one_mul]
simp only [← Matrix.add_mul]
congr
rw [← Matrix.mul_right_eq_iff_eq_mul_invOf]
simp only [Matrix.add_mul, Matrix.mul_add, Matrix.mul_assoc]
lemma add_mul_mul_mul_invOf_eq_one' :
(⅟A - ⅟A * U * C * ⅟(C + C * V * ⅟A * U * C) * C * V * ⅟A) * (A + U * C * V) = 1 := by
simp only [Matrix.mul_add, Matrix.sub_mul, invOf_mul_self']
rw [sub_add, sub_eq_self, sub_eq_zero]
simp only [Matrix.mul_assoc, ← Matrix.mul_sub]
congr
rw [eq_sub_iff_add_eq, ← Matrix.mul_add]
rw [Matrix.invOf_mul_eq_iff_eq_mul_left]
simp only [Matrix.add_mul, invOf_mul_self', Matrix.mul_one, add_right_inj]
simp only [Matrix.mul_assoc]
/-- If matrices `A` and `C + C * V * A⁻¹ * U * C` are invertible, then so is `A + U * C * V`. -/
def invertibleAddMulMul' : Invertible (A + U * C * V) where
invOf := ⅟A - ⅟A * U * C * ⅟(C + C * V * ⅟A * U * C) * C * V * ⅟A
invOf_mul_self := add_mul_mul_mul_invOf_eq_one' A U C V
mul_invOf_self := add_mul_mul_mul_invOf_eq_one A U C V
/-- The **Binomial Inverse Theorem** (`⅟` version).
See `Matrix.invOf_add_mul_mul` for the Woodbury identity. -/
theorem invOf_add_mul_mul' [Invertible (A + U * C * V)] :
⅟(A + U * C * V) = ⅟A - ⅟A * U * C * ⅟(C + C * V * ⅟A * U * C) * C * V * ⅟A := by
letI := invertibleAddMulMul' A U C V
convert (rfl : ⅟(A + U * C * V) = _)
end BinomialInverseTheorem
end Ring
end Matrix |
.lake/packages/mathlib/Mathlib/Data/Matrix/Mul.lean | import Mathlib.Algebra.BigOperators.GroupWithZero.Action
import Mathlib.Algebra.BigOperators.Ring.Finset
import Mathlib.Algebra.Regular.Basic
import Mathlib.Data.Fintype.BigOperators
import Mathlib.Data.Matrix.Diagonal
/-!
# Matrix multiplication
This file defines vector and matrix multiplication
## Main definitions
* `dotProduct`: the dot product between two vectors
* `Matrix.mul`: multiplication of two matrices
* `Matrix.mulVec`: multiplication of a matrix with a vector
* `Matrix.vecMul`: multiplication of a vector with a matrix
* `Matrix.vecMulVec`: multiplication of a vector with a vector to get a matrix
* `Matrix.instRing`: square matrices form a ring
## Notation
The scope `Matrix` gives the following notation:
* `⬝ᵥ` for `dotProduct`
* `*ᵥ` for `Matrix.mulVec`
* `ᵥ*` for `Matrix.vecMul`
See `Mathlib/Data/Matrix/ConjTranspose.lean` for
* `ᴴ` for `Matrix.conjTranspose`
## Implementation notes
For convenience, `Matrix m n α` is defined as `m → n → α`, as this allows elements of the matrix
to be accessed with `A i j`. However, it is not advisable to _construct_ matrices using terms of the
form `fun i j ↦ _` or even `(fun i j ↦ _ : Matrix m n α)`, as these are not recognized by Lean
as having the right type. Instead, `Matrix.of` should be used.
## TODO
Under various conditions, multiplication of infinite matrices makes sense.
These have not yet been implemented.
-/
assert_not_exists Algebra Field TrivialStar
universe u u' v w
variable {l m n o : Type*} {m' : o → Type*} {n' : o → Type*}
variable {R : Type*} {S : Type*} {α : Type v} {β : Type w} {γ : Type*}
open Matrix
section DotProduct
variable [Fintype m] [Fintype n]
/-- `dotProduct v w` is the sum of the entrywise products `v i * w i`.
See also `dotProductEquiv`. -/
def dotProduct [Mul α] [AddCommMonoid α] (v w : m → α) : α :=
∑ i, v i * w i
/- The precedence of 72 comes immediately after ` • ` for `SMul.smul`,
so that `r₁ • a ⬝ᵥ r₂ • b` is parsed as `(r₁ • a) ⬝ᵥ (r₂ • b)` here. -/
@[inherit_doc]
infixl:72 " ⬝ᵥ " => dotProduct
theorem dotProduct_assoc [NonUnitalSemiring α] (u : m → α) (w : n → α) (v : Matrix m n α) :
(fun j => u ⬝ᵥ fun i => v i j) ⬝ᵥ w = u ⬝ᵥ fun i => v i ⬝ᵥ w := by
simpa [dotProduct, Finset.mul_sum, Finset.sum_mul, mul_assoc] using Finset.sum_comm
theorem dotProduct_comm [AddCommMonoid α] [CommMagma α] (v w : m → α) : v ⬝ᵥ w = w ⬝ᵥ v := by
simp_rw [dotProduct, mul_comm]
@[simp]
theorem dotProduct_pUnit [AddCommMonoid α] [Mul α] (v w : PUnit → α) : v ⬝ᵥ w = v ⟨⟩ * w ⟨⟩ := by
simp [dotProduct]
section MulOneClass
variable [MulOneClass α] [AddCommMonoid α]
theorem dotProduct_one (v : n → α) : v ⬝ᵥ 1 = ∑ i, v i := by simp [(· ⬝ᵥ ·)]
theorem one_dotProduct (v : n → α) : 1 ⬝ᵥ v = ∑ i, v i := by simp [(· ⬝ᵥ ·)]
end MulOneClass
section NonUnitalNonAssocSemiring
variable [NonUnitalNonAssocSemiring α] (u v w : m → α) (x y : n → α)
@[simp]
theorem dotProduct_zero : v ⬝ᵥ 0 = 0 := by simp [dotProduct]
@[simp]
theorem dotProduct_zero' : (v ⬝ᵥ fun _ => 0) = 0 :=
dotProduct_zero v
@[simp]
theorem zero_dotProduct : 0 ⬝ᵥ v = 0 := by simp [dotProduct]
@[simp]
theorem zero_dotProduct' : (fun _ => (0 : α)) ⬝ᵥ v = 0 :=
zero_dotProduct v
@[simp]
theorem add_dotProduct : (u + v) ⬝ᵥ w = u ⬝ᵥ w + v ⬝ᵥ w := by
simp [dotProduct, add_mul, Finset.sum_add_distrib]
@[simp]
theorem dotProduct_add : u ⬝ᵥ (v + w) = u ⬝ᵥ v + u ⬝ᵥ w := by
simp [dotProduct, mul_add, Finset.sum_add_distrib]
@[simp]
theorem sumElim_dotProduct_sumElim : Sum.elim u x ⬝ᵥ Sum.elim v y = u ⬝ᵥ v + x ⬝ᵥ y := by
simp [dotProduct]
/-- Permuting a vector on the left of a dot product can be transferred to the right. -/
@[simp]
theorem comp_equiv_symm_dotProduct (e : m ≃ n) : u ∘ e.symm ⬝ᵥ x = u ⬝ᵥ x ∘ e :=
(e.sum_comp _).symm.trans <|
Finset.sum_congr rfl fun _ _ => by simp only [Function.comp, Equiv.symm_apply_apply]
/-- Permuting a vector on the right of a dot product can be transferred to the left. -/
@[simp]
theorem dotProduct_comp_equiv_symm (e : n ≃ m) : u ⬝ᵥ x ∘ e.symm = u ∘ e ⬝ᵥ x := by
simpa only [Equiv.symm_symm] using (comp_equiv_symm_dotProduct u x e.symm).symm
/-- Permuting vectors on both sides of a dot product is a no-op. -/
@[simp]
theorem comp_equiv_dotProduct_comp_equiv (e : m ≃ n) : x ∘ e ⬝ᵥ y ∘ e = x ⬝ᵥ y := by
simp [← dotProduct_comp_equiv_symm, Function.comp_def _ e.symm]
theorem dotProduct_sum {ι : Type*} (u : m → α) (s : Finset ι) (v : ι → (m → α)) :
u ⬝ᵥ ∑ i ∈ s, v i = ∑ i ∈ s, u ⬝ᵥ v i := by
simp only [dotProduct, Finset.sum_apply, Finset.mul_sum]
rw [Finset.sum_comm]
theorem sum_dotProduct {ι : Type*} (s : Finset ι) (u : ι → (m → α)) (v : m → α) :
(∑ i ∈ s, u i) ⬝ᵥ v = ∑ i ∈ s, u i ⬝ᵥ v := by
simp only [dotProduct, Finset.sum_apply, Finset.sum_mul]
rw [Finset.sum_comm]
end NonUnitalNonAssocSemiring
section NonUnitalNonAssocSemiringDecidable
variable [DecidableEq m] [NonUnitalNonAssocSemiring α] (u v w : m → α)
@[simp]
theorem diagonal_dotProduct (i : m) : diagonal v i ⬝ᵥ w = v i * w i := by
have : ∀ j ≠ i, diagonal v i j * w j = 0 := fun j hij => by
simp [diagonal_apply_ne' _ hij]
convert Finset.sum_eq_single i (fun j _ => this j) _ using 1 <;> simp
@[simp]
theorem dotProduct_diagonal (i : m) : v ⬝ᵥ diagonal w i = v i * w i := by
have : ∀ j ≠ i, v j * diagonal w i j = 0 := fun j hij => by
simp [diagonal_apply_ne' _ hij]
convert Finset.sum_eq_single i (fun j _ => this j) _ using 1 <;> simp
@[simp]
theorem dotProduct_diagonal' (i : m) : (v ⬝ᵥ fun j => diagonal w j i) = v i * w i := by
have : ∀ j ≠ i, v j * diagonal w j i = 0 := fun j hij => by
simp [diagonal_apply_ne _ hij]
convert Finset.sum_eq_single i (fun j _ => this j) _ using 1 <;> simp
@[simp]
theorem single_dotProduct (x : α) (i : m) : Pi.single i x ⬝ᵥ v = x * v i := by
-- Porting note: added `(_ : m → α)`
have : ∀ j ≠ i, (Pi.single i x : m → α) j * v j = 0 := fun j hij => by
simp [Pi.single_eq_of_ne hij]
convert Finset.sum_eq_single i (fun j _ => this j) _ using 1 <;> simp
@[simp]
theorem dotProduct_single (x : α) (i : m) : v ⬝ᵥ Pi.single i x = v i * x := by
-- Porting note: added `(_ : m → α)`
have : ∀ j ≠ i, v j * (Pi.single i x : m → α) j = 0 := fun j hij => by
simp [Pi.single_eq_of_ne hij]
convert Finset.sum_eq_single i (fun j _ => this j) _ using 1 <;> simp
end NonUnitalNonAssocSemiringDecidable
section NonAssocSemiring
variable [NonAssocSemiring α]
@[simp]
theorem one_dotProduct_one : (1 : n → α) ⬝ᵥ 1 = Fintype.card n := by
simp [dotProduct]
theorem dotProduct_single_one [DecidableEq n] (v : n → α) (i : n) :
v ⬝ᵥ Pi.single i 1 = v i := by
rw [dotProduct_single, mul_one]
theorem single_one_dotProduct [DecidableEq n] (i : n) (v : n → α) :
Pi.single i 1 ⬝ᵥ v = v i := by
rw [single_dotProduct, one_mul]
end NonAssocSemiring
section NonUnitalNonAssocRing
variable [NonUnitalNonAssocRing α] (u v w : m → α)
@[simp]
theorem neg_dotProduct : -v ⬝ᵥ w = -(v ⬝ᵥ w) := by simp [dotProduct]
@[simp]
theorem dotProduct_neg : v ⬝ᵥ -w = -(v ⬝ᵥ w) := by simp [dotProduct]
lemma neg_dotProduct_neg : -v ⬝ᵥ -w = v ⬝ᵥ w := by
rw [neg_dotProduct, dotProduct_neg, neg_neg]
@[simp]
theorem sub_dotProduct : (u - v) ⬝ᵥ w = u ⬝ᵥ w - v ⬝ᵥ w := by simp [sub_eq_add_neg]
@[simp]
theorem dotProduct_sub : u ⬝ᵥ (v - w) = u ⬝ᵥ v - u ⬝ᵥ w := by simp [sub_eq_add_neg]
end NonUnitalNonAssocRing
section DistribMulAction
variable [Mul α] [AddCommMonoid α] [DistribSMul R α]
@[simp]
theorem smul_dotProduct [IsScalarTower R α α] (x : R) (v w : m → α) :
x • v ⬝ᵥ w = x • (v ⬝ᵥ w) := by simp [dotProduct, Finset.smul_sum, smul_mul_assoc]
@[simp]
theorem dotProduct_smul [SMulCommClass R α α] (x : R) (v w : m → α) :
v ⬝ᵥ x • w = x • (v ⬝ᵥ w) := by simp [dotProduct, Finset.smul_sum, mul_smul_comm]
end DistribMulAction
section CommRing
variable [CommRing α] [Nontrivial m] [Nontrivial α]
/-- For any vector `a` in a nontrivial commutative ring with nontrivial index,
there exists a non-zero vector `b` such that `b ⬝ᵥ a = 0`. In other words,
there exists a non-zero orthogonal vector. -/
theorem exists_ne_zero_dotProduct_eq_zero (a : m → α) : ∃ b ≠ 0, b ⬝ᵥ a = 0 := by
obtain ⟨i, j, hij⟩ : ∃ i j : m, i ≠ j := nontrivial_iff.mp ‹_›
classical
use if a i = 0 then Pi.single i 1 else if a j = 0 then Pi.single j 1 else
fun k => if k = i then a j else if k = j then - a i else 0
split_ifs with h h2
· simp [h]
· simp [h2]
· refine ⟨Function.ne_iff.mpr ⟨i, by simp [h2]⟩, ?_⟩
simp [dotProduct, Finset.sum_ite, Finset.sum_eq_ite i, hij.symm, mul_comm (a i)]
lemma not_injective_dotProduct_left (a : m → α) :
¬ Function.Injective (dotProduct a) := by
intro h
obtain ⟨b, hb, hba⟩ := exists_ne_zero_dotProduct_eq_zero a
simpa [dotProduct_comm a b, hba, hb] using @h b 0
lemma not_injective_dotProduct_right (a : m → α) :
¬ Function.Injective (dotProduct · a) := by
intro h
obtain ⟨b, hb, hba⟩ := exists_ne_zero_dotProduct_eq_zero a
simpa [hba, hb] using @h b 0
end CommRing
end DotProduct
open Matrix
namespace Matrix
/-- `M * N` is the usual product of matrices `M` and `N`, i.e. we have that
`(M * N) i k` is the dot product of the `i`-th row of `M` by the `k`-th column of `N`.
This is currently only defined when `m` is finite. -/
-- We want to be lower priority than `instHMul`, but without this we can't have operands with
-- implicit dimensions.
@[default_instance 100]
instance [Fintype m] [Mul α] [AddCommMonoid α] :
HMul (Matrix l m α) (Matrix m n α) (Matrix l n α) where
hMul M N := fun i k => (fun j => M i j) ⬝ᵥ fun j => N j k
theorem mul_apply [Fintype m] [Mul α] [AddCommMonoid α] {M : Matrix l m α} {N : Matrix m n α}
{i k} : (M * N) i k = ∑ j, M i j * N j k :=
rfl
instance [Fintype n] [Mul α] [AddCommMonoid α] : Mul (Matrix n n α) where mul M N := M * N
theorem mul_apply' [Fintype m] [Mul α] [AddCommMonoid α] {M : Matrix l m α} {N : Matrix m n α}
{i k} : (M * N) i k = (M i) ⬝ᵥ fun j => N j k :=
rfl
theorem two_mul_expl {R : Type*} [NonUnitalNonAssocSemiring R] (A B : Matrix (Fin 2) (Fin 2) R) :
(A * B) 0 0 = A 0 0 * B 0 0 + A 0 1 * B 1 0 ∧
(A * B) 0 1 = A 0 0 * B 0 1 + A 0 1 * B 1 1 ∧
(A * B) 1 0 = A 1 0 * B 0 0 + A 1 1 * B 1 0 ∧
(A * B) 1 1 = A 1 0 * B 0 1 + A 1 1 * B 1 1 := by
refine ⟨?_, ?_, ?_, ?_⟩ <;>
· rw [Matrix.mul_apply, Finset.sum_fin_eq_sum_range, Finset.sum_range_succ, Finset.sum_range_succ]
simp
section AddCommMonoid
variable [AddCommMonoid α] [Mul α]
@[simp]
theorem smul_mul [Fintype n] [Monoid R] [DistribMulAction R α] [IsScalarTower R α α] (a : R)
(M : Matrix m n α) (N : Matrix n l α) : (a • M) * N = a • (M * N) := by
ext
apply smul_dotProduct a
@[simp]
theorem mul_smul [Fintype n] [Monoid R] [DistribMulAction R α] [SMulCommClass R α α]
(M : Matrix m n α) (a : R) (N : Matrix n l α) : M * (a • N) = a • (M * N) := by
ext
apply dotProduct_smul
end AddCommMonoid
section NonUnitalNonAssocSemiring
variable [NonUnitalNonAssocSemiring α]
@[simp]
protected theorem mul_zero [Fintype n] (M : Matrix m n α) : M * (0 : Matrix n o α) = 0 := by
ext
apply dotProduct_zero
@[simp]
protected theorem zero_mul [Fintype m] (M : Matrix m n α) : (0 : Matrix l m α) * M = 0 := by
ext
apply zero_dotProduct
protected theorem mul_add [Fintype n] (L : Matrix m n α) (M N : Matrix n o α) :
L * (M + N) = L * M + L * N := by
ext
apply dotProduct_add
protected theorem add_mul [Fintype m] (L M : Matrix l m α) (N : Matrix m n α) :
(L + M) * N = L * N + M * N := by
ext
apply add_dotProduct
instance nonUnitalNonAssocSemiring [Fintype n] : NonUnitalNonAssocSemiring (Matrix n n α) :=
{ Matrix.addCommMonoid with
mul_zero := Matrix.mul_zero
zero_mul := Matrix.zero_mul
left_distrib := Matrix.mul_add
right_distrib := Matrix.add_mul }
@[simp]
theorem diagonal_mul [Fintype m] [DecidableEq m] (d : m → α) (M : Matrix m n α) (i j) :
(diagonal d * M) i j = d i * M i j :=
diagonal_dotProduct _ _ _
@[simp]
theorem mul_diagonal [Fintype n] [DecidableEq n] (d : n → α) (M : Matrix m n α) (i j) :
(M * diagonal d) i j = M i j * d j := by
rw [← diagonal_transpose]
apply dotProduct_diagonal
@[simp]
theorem diagonal_mul_diagonal [Fintype n] [DecidableEq n] (d₁ d₂ : n → α) :
diagonal d₁ * diagonal d₂ = diagonal fun i => d₁ i * d₂ i := by
ext i j
by_cases h : i = j <;>
simp [h]
theorem diagonal_mul_diagonal' [Fintype n] [DecidableEq n] (d₁ d₂ : n → α) :
diagonal d₁ * diagonal d₂ = diagonal fun i => d₁ i * d₂ i :=
diagonal_mul_diagonal _ _
theorem commute_diagonal {α : Type*} [NonUnitalNonAssocCommSemiring α]
[Fintype n] [DecidableEq n] (d₁ d₂ : n → α) :
Commute (diagonal d₁) (diagonal d₂) := by
simp_rw [commute_iff_eq, diagonal_mul_diagonal, mul_comm]
theorem smul_eq_diagonal_mul [Fintype m] [DecidableEq m] (M : Matrix m n α) (a : α) :
a • M = (diagonal fun _ => a) * M := by
ext
simp
theorem op_smul_eq_mul_diagonal [Fintype n] [DecidableEq n] (M : Matrix m n α) (a : α) :
MulOpposite.op a • M = M * (diagonal fun _ : n => a) := by
ext
simp
/-- Left multiplication by a matrix, as an `AddMonoidHom` from matrices to matrices. -/
@[simps]
def addMonoidHomMulLeft [Fintype m] (M : Matrix l m α) : Matrix m n α →+ Matrix l n α where
toFun x := M * x
map_zero' := Matrix.mul_zero _
map_add' := Matrix.mul_add _
/-- Right multiplication by a matrix, as an `AddMonoidHom` from matrices to matrices. -/
@[simps]
def addMonoidHomMulRight [Fintype m] (M : Matrix m n α) : Matrix l m α →+ Matrix l n α where
toFun x := x * M
map_zero' := Matrix.zero_mul _
map_add' _ _ := Matrix.add_mul _ _ _
protected theorem sum_mul [Fintype m] (s : Finset β) (f : β → Matrix l m α) (M : Matrix m n α) :
(∑ a ∈ s, f a) * M = ∑ a ∈ s, f a * M :=
map_sum (addMonoidHomMulRight M) f s
protected theorem mul_sum [Fintype m] (s : Finset β) (f : β → Matrix m n α) (M : Matrix l m α) :
(M * ∑ a ∈ s, f a) = ∑ a ∈ s, M * f a :=
map_sum (addMonoidHomMulLeft M) f s
/-- This instance enables use with `smul_mul_assoc`. -/
instance Semiring.isScalarTower [Fintype n] [Monoid R] [DistribMulAction R α]
[IsScalarTower R α α] : IsScalarTower R (Matrix n n α) (Matrix n n α) :=
⟨fun r m n => Matrix.smul_mul r m n⟩
/-- This instance enables use with `mul_smul_comm`. -/
instance Semiring.smulCommClass [Fintype n] [Monoid R] [DistribMulAction R α]
[SMulCommClass R α α] : SMulCommClass R (Matrix n n α) (Matrix n n α) :=
⟨fun r m n => (Matrix.mul_smul m r n).symm⟩
end NonUnitalNonAssocSemiring
section NonAssocSemiring
variable [NonAssocSemiring α]
@[simp]
protected theorem one_mul [Fintype m] [DecidableEq m] (M : Matrix m n α) :
(1 : Matrix m m α) * M = M := by
ext
rw [← diagonal_one, diagonal_mul, one_mul]
@[simp]
protected theorem mul_one [Fintype n] [DecidableEq n] (M : Matrix m n α) :
M * (1 : Matrix n n α) = M := by
ext
rw [← diagonal_one, mul_diagonal, mul_one]
instance nonAssocSemiring [Fintype n] [DecidableEq n] : NonAssocSemiring (Matrix n n α) :=
{ Matrix.nonUnitalNonAssocSemiring, Matrix.instAddCommMonoidWithOne with
one_mul := Matrix.one_mul
mul_one := Matrix.mul_one }
@[simp]
protected theorem map_mul [Fintype n] {L : Matrix m n α} {M : Matrix n o α} [NonAssocSemiring β]
{f : α →+* β} : (L * M).map f = L.map f * M.map f := by
ext
simp [mul_apply, map_sum]
theorem smul_one_eq_diagonal [DecidableEq m] (a : α) :
a • (1 : Matrix m m α) = diagonal fun _ => a := by
simp_rw [← diagonal_one, ← diagonal_smul, Pi.smul_def, smul_eq_mul, mul_one]
theorem op_smul_one_eq_diagonal [DecidableEq m] (a : α) :
MulOpposite.op a • (1 : Matrix m m α) = diagonal fun _ => a := by
simp_rw [← diagonal_one, ← diagonal_smul, Pi.smul_def, op_smul_eq_mul, one_mul]
variable (α n)
end NonAssocSemiring
section NonUnitalSemiring
variable [NonUnitalSemiring α] [Fintype m] [Fintype n]
protected theorem mul_assoc (L : Matrix l m α) (M : Matrix m n α) (N : Matrix n o α) :
L * M * N = L * (M * N) := by
ext
apply dotProduct_assoc
instance nonUnitalSemiring : NonUnitalSemiring (Matrix n n α) :=
{ Matrix.nonUnitalNonAssocSemiring with mul_assoc := Matrix.mul_assoc }
end NonUnitalSemiring
section Semiring
variable [Semiring α]
instance semiring [Fintype n] [DecidableEq n] : Semiring (Matrix n n α) :=
{ Matrix.nonUnitalSemiring, Matrix.nonAssocSemiring with }
end Semiring
section NonUnitalNonAssocRing
variable [NonUnitalNonAssocRing α] [Fintype n]
@[simp]
protected theorem neg_mul (M : Matrix m n α) (N : Matrix n o α) : (-M) * N = -(M * N) := by
ext
apply neg_dotProduct
@[simp]
protected theorem mul_neg (M : Matrix m n α) (N : Matrix n o α) : M * (-N) = -(M * N) := by
ext
apply dotProduct_neg
protected theorem sub_mul (M M' : Matrix m n α) (N : Matrix n o α) :
(M - M') * N = M * N - M' * N := by
rw [sub_eq_add_neg, Matrix.add_mul, Matrix.neg_mul, sub_eq_add_neg]
protected theorem mul_sub (M : Matrix m n α) (N N' : Matrix n o α) :
M * (N - N') = M * N - M * N' := by
rw [sub_eq_add_neg, Matrix.mul_add, Matrix.mul_neg, sub_eq_add_neg]
instance nonUnitalNonAssocRing : NonUnitalNonAssocRing (Matrix n n α) :=
{ Matrix.nonUnitalNonAssocSemiring, Matrix.addCommGroup with }
end NonUnitalNonAssocRing
instance instNonUnitalRing [Fintype n] [NonUnitalRing α] : NonUnitalRing (Matrix n n α) :=
{ Matrix.nonUnitalSemiring, Matrix.addCommGroup with }
instance instNonAssocRing [Fintype n] [DecidableEq n] [NonAssocRing α] :
NonAssocRing (Matrix n n α) :=
{ Matrix.nonAssocSemiring, Matrix.instAddCommGroupWithOne with }
instance instRing [Fintype n] [DecidableEq n] [Ring α] : Ring (Matrix n n α) :=
{ Matrix.semiring, Matrix.instAddCommGroupWithOne with }
section Semiring
variable [Semiring α]
@[simp]
theorem mul_mul_left [Fintype n] (M : Matrix m n α) (N : Matrix n o α) (a : α) :
(of fun i j => a * M i j) * N = a • (M * N) :=
smul_mul a M N
lemma pow_apply_nonneg [Fintype n] [DecidableEq n] [PartialOrder α] [IsOrderedRing α]
{A : Matrix n n α} (hA : ∀ i j, 0 ≤ A i j) (k : ℕ) : ∀ i j, 0 ≤ (A ^ k) i j := by
induction k with
| zero => aesop (add simp one_apply)
| succ m ih =>
intro i j; rw [pow_succ, mul_apply]
exact Finset.sum_nonneg fun l _ => mul_nonneg (ih i l) (hA l j)
end Semiring
section CommSemiring
variable [CommSemiring α]
theorem smul_eq_mul_diagonal [Fintype n] [DecidableEq n] (M : Matrix m n α) (a : α) :
a • M = M * diagonal fun _ => a := by
ext
simp [mul_comm]
@[simp]
theorem mul_mul_right [Fintype n] (M : Matrix m n α) (N : Matrix n o α) (a : α) :
(M * of fun i j => a * N i j) = a • (M * N) :=
mul_smul M a N
end CommSemiring
end Matrix
open Matrix
namespace Matrix
/-- For two vectors `w` and `v`, `vecMulVec w v i j` is defined to be `w i * v j`.
Put another way, `vecMulVec w v` is exactly `replicateCol ι w * replicateRow ι v` for
`Unique ι`; see `vecMulVec_eq`. -/
def vecMulVec [Mul α] (w : m → α) (v : n → α) : Matrix m n α :=
of fun x y => w x * v y
-- TODO: set as an equation lemma for `vecMulVec`, see https://github.com/leanprover-community/mathlib4/pull/3024
theorem vecMulVec_apply [Mul α] (w : m → α) (v : n → α) (i j) : vecMulVec w v i j = w i * v j :=
rfl
lemma row_vecMulVec [Mul α] (w : m → α) (v : n → α) (i : m) :
(vecMulVec w v).row i = w i • v := rfl
lemma col_vecMulVec [Mul α] (w : m → α) (v : n → α) (j : n) :
(vecMulVec w v).col j = MulOpposite.op (v j) • w := rfl
@[simp] theorem zero_vecMulVec [MulZeroClass α] (v : n → α) : vecMulVec (0 : m → α) v = 0 :=
ext fun _ _ => zero_mul _
@[simp] theorem vecMulVec_zero [MulZeroClass α] (w : m → α) : vecMulVec w (0 : m → α) = 0 :=
ext fun _ _ => mul_zero _
theorem vecMulVec_ne_zero [Mul α] [Zero α] [NoZeroDivisors α] {a b : n → α}
(ha : a ≠ 0) (hb : b ≠ 0) : vecMulVec a b ≠ 0 := by
intro h
obtain ⟨i, ha⟩ := Function.ne_iff.mp ha
obtain ⟨j, hb⟩ := Function.ne_iff.mp hb
exact mul_ne_zero ha hb congr($h i j)
@[simp] theorem vecMulVec_eq_zero [MulZeroClass α] [NoZeroDivisors α] {a b : n → α} :
vecMulVec a b = 0 ↔ a = 0 ∨ b = 0 := by
simp only [← ext_iff, vecMulVec_apply, zero_apply, mul_eq_zero, funext_iff, Pi.zero_apply,
forall_or_left, forall_or_right]
theorem add_vecMulVec [Mul α] [Add α] [RightDistribClass α] (w₁ w₂ : m → α) (v : n → α) :
vecMulVec (w₁ + w₂) v = vecMulVec w₁ v + vecMulVec w₂ v :=
ext fun _ _ => add_mul _ _ _
theorem vecMulVec_add [Mul α] [Add α] [LeftDistribClass α] (w : m → α) (v₁ v₂ : n → α) :
vecMulVec w (v₁ + v₂) = vecMulVec w v₁ + vecMulVec w v₂ :=
ext fun _ _ => mul_add _ _ _
@[simp]
theorem neg_vecMulVec [Mul α] [HasDistribNeg α] (w : m → α) (v : n → α) :
vecMulVec (-w) v = -vecMulVec w v :=
ext fun _ _ => neg_mul _ _
@[simp]
theorem vecMulVec_neg [Mul α] [HasDistribNeg α] (w : m → α) (v : n → α) :
vecMulVec w (-v) = -vecMulVec w v :=
ext fun _ _ => mul_neg _ _
@[simp]
theorem smul_vecMulVec [Mul α] [SMul R α] [IsScalarTower R α α] (r : R) (w : m → α) (v : n → α) :
vecMulVec (r • w) v = r • vecMulVec w v :=
ext fun _ _ => smul_mul_assoc _ _ _
@[simp]
theorem vecMulVec_smul [Mul α] [SMul R α] [SMulCommClass R α α] (r : R) (w : m → α) (v : n → α) :
vecMulVec w (r • v) = r • vecMulVec w v :=
ext fun _ _ => mul_smul_comm _ _ _
theorem vecMulVec_smul' [Semigroup α] (w : m → α) (r : α) (v : n → α) :
vecMulVec w (r • v) = vecMulVec (MulOpposite.op r • w) v :=
ext fun _ _ => mul_assoc _ _ _ |>.symm
@[simp]
theorem transpose_vecMulVec [CommMagma α] (w : m → α) (v : n → α) :
(vecMulVec w v)ᵀ = vecMulVec v w :=
ext fun _ _ => mul_comm _ _
@[simp]
theorem diag_vecMulVec [Mul α] (u v : n → α) : diag (vecMulVec u v) = u * v := rfl
section NonUnitalNonAssocSemiring
variable [NonUnitalNonAssocSemiring α]
/--
`M *ᵥ v` (notation for `mulVec M v`) is the matrix-vector product of matrix `M` and vector `v`,
where `v` is seen as a column vector.
Put another way, `M *ᵥ v` is the vector whose entries are those of `M * col v` (see `col_mulVec`).
The notation has precedence 73, which comes immediately before ` ⬝ᵥ ` for `dotProduct`,
so that `A *ᵥ v ⬝ᵥ B *ᵥ w` is parsed as `(A *ᵥ v) ⬝ᵥ (B *ᵥ w)`.
-/
def mulVec [Fintype n] (M : Matrix m n α) (v : n → α) : m → α
| i => (fun j => M i j) ⬝ᵥ v
@[inherit_doc]
scoped infixr:73 " *ᵥ " => Matrix.mulVec
/--
`v ᵥ* M` (notation for `vecMul v M`) is the vector-matrix product of vector `v` and matrix `M`,
where `v` is seen as a row vector.
Put another way, `v ᵥ* M` is the vector whose entries are those of `row v * M` (see `row_vecMul`).
The notation has precedence 73, which comes immediately before ` ⬝ᵥ ` for `dotProduct`,
so that `v ᵥ* A ⬝ᵥ w ᵥ* B` is parsed as `(v ᵥ* A) ⬝ᵥ (w ᵥ* B)`.
-/
def vecMul [Fintype m] (v : m → α) (M : Matrix m n α) : n → α
| j => v ⬝ᵥ fun i => M i j
@[inherit_doc]
scoped infixl:73 " ᵥ* " => Matrix.vecMul
/-- Left multiplication by a matrix, as an `AddMonoidHom` from vectors to vectors. -/
@[simps]
def mulVec.addMonoidHomLeft [Fintype n] (v : n → α) : Matrix m n α →+ m → α where
toFun M := M *ᵥ v
map_zero' := by
ext
simp [mulVec]
map_add' x y := by
ext m
apply add_dotProduct
/-- The `i`th row of the multiplication is the same as the `vecMul` with the `i`th row of `A`. -/
theorem mul_apply_eq_vecMul [Fintype n] (A : Matrix m n α) (B : Matrix n o α) (i : m) :
(A * B) i = A i ᵥ* B :=
rfl
theorem vecMul_eq_sum [Fintype m] (v : m → α) (M : Matrix m n α) : v ᵥ* M = ∑ i, v i • M i :=
(Finset.sum_fn ..).symm
theorem mulVec_eq_sum [Fintype n] (v : n → α) (M : Matrix m n α) :
M *ᵥ v = ∑ i, MulOpposite.op (v i) • Mᵀ i :=
(Finset.sum_fn ..).symm
theorem mulVec_diagonal [Fintype m] [DecidableEq m] (v w : m → α) (x : m) :
(diagonal v *ᵥ w) x = v x * w x :=
diagonal_dotProduct v w x
theorem vecMul_diagonal [Fintype m] [DecidableEq m] (v w : m → α) (x : m) :
(v ᵥ* diagonal w) x = v x * w x :=
dotProduct_diagonal' v w x
/-- Associate the dot product of `mulVec` to the left. -/
theorem dotProduct_mulVec [Fintype n] [Fintype m] [NonUnitalSemiring R] (v : m → R)
(A : Matrix m n R) (w : n → R) : v ⬝ᵥ A *ᵥ w = v ᵥ* A ⬝ᵥ w := by
simp only [dotProduct, vecMul, mulVec, Finset.mul_sum, Finset.sum_mul, mul_assoc]
exact Finset.sum_comm
@[simp]
theorem mulVec_zero [Fintype n] (A : Matrix m n α) : A *ᵥ 0 = 0 := by
ext
simp [mulVec]
@[simp]
theorem zero_vecMul [Fintype m] (A : Matrix m n α) : 0 ᵥ* A = 0 := by
ext
simp [vecMul]
@[simp]
theorem zero_mulVec [Fintype n] (v : n → α) : (0 : Matrix m n α) *ᵥ v = 0 := by
ext
simp [mulVec]
@[simp]
theorem vecMul_zero [Fintype m] (v : m → α) : v ᵥ* (0 : Matrix m n α) = 0 := by
ext
simp [vecMul]
theorem mulVec_add [Fintype n] (A : Matrix m n α) (x y : n → α) :
A *ᵥ (x + y) = A *ᵥ x + A *ᵥ y := by
ext
apply dotProduct_add
theorem add_mulVec [Fintype n] (A B : Matrix m n α) (x : n → α) :
(A + B) *ᵥ x = A *ᵥ x + B *ᵥ x := by
ext
apply add_dotProduct
theorem vecMul_add [Fintype m] (A B : Matrix m n α) (x : m → α) :
x ᵥ* (A + B) = x ᵥ* A + x ᵥ* B := by
ext
apply dotProduct_add
theorem add_vecMul [Fintype m] (A : Matrix m n α) (x y : m → α) :
(x + y) ᵥ* A = x ᵥ* A + y ᵥ* A := by
ext
apply add_dotProduct
theorem mulVec_smul [Fintype n] [DistribSMul R α] [SMulCommClass R α α]
(M : Matrix m n α) (b : R) (v : n → α) :
M *ᵥ (b • v) = b • M *ᵥ v := by
ext
exact dotProduct_smul _ _ _
theorem smul_mulVec [Fintype n] [DistribSMul R α] [IsScalarTower R α α]
(b : R) (M : Matrix m n α) (v : n → α) :
(b • M) *ᵥ v = b • M *ᵥ v := by
ext
exact smul_dotProduct _ _ _
theorem smul_vecMul [Fintype m] [DistribSMul R α] [IsScalarTower R α α]
(b : R) (v : m → α) (M : Matrix m n α) :
(b • v) ᵥ* M = b • v ᵥ* M := by
ext
exact smul_dotProduct _ _ _
theorem vecMul_smul [Fintype m] [DistribSMul R α] [SMulCommClass R α α]
(v : m → α) (b : R) (M : Matrix m n α) :
v ᵥ* (b • M) = b • v ᵥ* M := by
ext
exact dotProduct_smul _ _ _
@[deprecated (since := "2025-08-14")] alias smul_mulVec_assoc := smul_mulVec
@[simp]
theorem mulVec_single [Fintype n] [DecidableEq n] [NonUnitalNonAssocSemiring R] (M : Matrix m n R)
(j : n) (x : R) : M *ᵥ Pi.single j x = MulOpposite.op x • M.col j :=
funext fun _ => dotProduct_single _ _ _
@[simp]
theorem single_vecMul [Fintype m] [DecidableEq m] [NonUnitalNonAssocSemiring R] (M : Matrix m n R)
(i : m) (x : R) : Pi.single i x ᵥ* M = x • M.row i :=
funext fun _ => single_dotProduct _ _ _
theorem mulVec_single_one [Fintype n] [DecidableEq n] [NonAssocSemiring R]
(M : Matrix m n R) (j : n) :
M *ᵥ Pi.single j 1 = M.col j := by ext; simp
theorem single_one_vecMul [Fintype m] [DecidableEq m] [NonAssocSemiring R]
(i : m) (M : Matrix m n R) :
Pi.single i 1 ᵥ* M = M.row i := by ext; simp
theorem diagonal_mulVec_single [Fintype n] [DecidableEq n] [NonUnitalNonAssocSemiring R] (v : n → R)
(j : n) (x : R) : diagonal v *ᵥ Pi.single j x = Pi.single j (v j * x) := by
ext i
rw [mulVec_diagonal]
exact Pi.apply_single (fun i x => v i * x) (fun i => mul_zero _) j x i
theorem single_vecMul_diagonal [Fintype n] [DecidableEq n] [NonUnitalNonAssocSemiring R] (v : n → R)
(j : n) (x : R) : (Pi.single j x) ᵥ* (diagonal v) = Pi.single j (x * v j) := by
ext i
rw [vecMul_diagonal]
exact Pi.apply_single (fun i x => x * v i) (fun i => zero_mul _) j x i
end NonUnitalNonAssocSemiring
section NonUnitalSemiring
variable [NonUnitalSemiring α]
@[simp]
theorem vecMul_vecMul [Fintype n] [Fintype m] (v : m → α) (M : Matrix m n α) (N : Matrix n o α) :
v ᵥ* M ᵥ* N = v ᵥ* (M * N) := by
ext
apply dotProduct_assoc
@[simp]
theorem mulVec_mulVec [Fintype n] [Fintype o] (v : o → α) (M : Matrix m n α) (N : Matrix n o α) :
M *ᵥ N *ᵥ v = (M * N) *ᵥ v := by
ext
symm
apply dotProduct_assoc
theorem mul_mul_apply [Fintype n] (A B C : Matrix n n α) (i j : n) :
(A * B * C) i j = A i ⬝ᵥ B *ᵥ (Cᵀ j) := by
rw [Matrix.mul_assoc]
simp [mul_apply, dotProduct, mulVec]
theorem vecMul_vecMulVec [Fintype m] (u v : m → α) (w : n → α) :
u ᵥ* vecMulVec v w = (u ⬝ᵥ v) • w := by
ext i
simp [vecMul, dotProduct, vecMulVec, Finset.sum_mul, mul_assoc]
theorem vecMulVec_mulVec [Fintype n] (u : m → α) (v w : n → α) :
vecMulVec u v *ᵥ w = MulOpposite.op (v ⬝ᵥ w) • u := by
ext i
simp [mulVec, dotProduct, vecMulVec, Finset.mul_sum, mul_assoc]
theorem mul_vecMulVec [Fintype m] (M : Matrix l m α) (x : m → α) (y : n → α) :
M * vecMulVec x y = vecMulVec (M *ᵥ x) y := by
ext
simp_rw [mul_apply, vecMulVec_apply, mulVec, dotProduct, Finset.sum_mul, mul_assoc]
theorem vecMulVec_mul [Fintype m] (x : l → α) (y : m → α) (M : Matrix m n α) :
vecMulVec x y * M = vecMulVec x (y ᵥ* M) := by
ext
simp_rw [mul_apply, vecMulVec_apply, vecMul, dotProduct, Finset.mul_sum, mul_assoc]
theorem vecMulVec_mul_vecMulVec [Fintype m] (u : l → α) (v w : m → α) (x : n → α) :
vecMulVec u v * vecMulVec w x = vecMulVec u ((v ⬝ᵥ w) • x) := by
rw [vecMulVec_mul, vecMul_vecMulVec]
lemma mul_right_injective_iff_mulVec_injective [Fintype m] [Nonempty n] {A : Matrix l m α} :
Function.Injective (fun B : Matrix m n α => A * B) ↔ Function.Injective A.mulVec := by
refine ⟨fun ha v w hvw => ?_, fun ha B C hBC => ext_col fun j => ha congr(($hBC).col j)⟩
inhabit n
-- `replicateRow` is not available yet
suffices (of fun i j => v i) = (of fun i j => w i) from
funext fun i => congrFun₂ this i (default : n)
exact ha <| ext fun _ _ => congrFun hvw _
lemma mul_left_injective_iff_vecMul_injective [Nonempty l] [Fintype m] {A : Matrix m n α} :
Function.Injective (fun B : Matrix l m α => B * A) ↔ Function.Injective A.vecMul := by
refine ⟨fun ha v w hvw => ?_, fun ha B C hBC => ext_row fun i => ha congr(($hBC).row i)⟩
inhabit l
-- `replicateCol` is not available yet
suffices (of fun i j => v j) = (of fun i j => w j) from
funext fun j => congrFun₂ this (default : l) j
exact ha <| ext fun _ _ => congrFun hvw _
lemma isLeftRegular_iff_mulVec_injective [Fintype m] {A : Matrix m m α} :
IsLeftRegular A ↔ Function.Injective A.mulVec := by
cases isEmpty_or_nonempty m
· simp [IsLeftRegular, Function.injective_of_subsingleton]
exact mul_right_injective_iff_mulVec_injective
lemma isRightRegular_iff_vecMul_injective [Fintype m] {A : Matrix m m α} :
IsRightRegular A ↔ Function.Injective A.vecMul := by
cases isEmpty_or_nonempty m
· simp [IsRightRegular, Function.injective_of_subsingleton]
exact mul_left_injective_iff_vecMul_injective
end NonUnitalSemiring
section NonAssocSemiring
variable [NonAssocSemiring α]
theorem mulVec_one [Fintype n] (A : Matrix m n α) : A *ᵥ 1 = ∑ j, Aᵀ j := by
ext; simp [mulVec, dotProduct]
theorem one_vecMul [Fintype m] (A : Matrix m n α) : 1 ᵥ* A = ∑ i, A i := by
ext; simp [vecMul, dotProduct]
lemma ext_of_mulVec_single [DecidableEq n] [Fintype n] {M N : Matrix m n α}
(h : ∀ i, M *ᵥ Pi.single i 1 = N *ᵥ Pi.single i 1) :
M = N := by
ext i j
simp_rw [mulVec_single_one] at h
exact congrFun (h j) i
lemma ext_of_single_vecMul [DecidableEq m] [Fintype m] {M N : Matrix m n α}
(h : ∀ i, Pi.single i 1 ᵥ* M = Pi.single i 1 ᵥ* N) :
M = N := by
ext i j
simp_rw [single_one_vecMul] at h
exact congrFun (h i) j
theorem mulVec_injective [Fintype n] : (mulVec : Matrix m n α → _).Injective := by
intro A B h
ext i j
classical
simpa using congrFun₂ h (Pi.single j 1) i
theorem ext_iff_mulVec [Fintype n] {A B : Matrix m n α} : A = B ↔ ∀ v, A *ᵥ v = B *ᵥ v :=
mulVec_injective.eq_iff.symm.trans funext_iff
theorem vecMul_injective [Fintype m] : (·.vecMul : Matrix m n α → _).Injective := by
intro A B h
ext i j
classical
simpa using congrFun₂ h (Pi.single i 1) j
theorem ext_iff_vecMul [Fintype m] {A B : Matrix m n α} : A = B ↔ ∀ v, v ᵥ* A = v ᵥ* B :=
vecMul_injective.eq_iff.symm.trans funext_iff
variable [Fintype m] [DecidableEq m]
@[simp]
theorem one_mulVec (v : m → α) : 1 *ᵥ v = v := by
ext
rw [← diagonal_one, mulVec_diagonal, one_mul]
@[simp]
theorem vecMul_one (v : m → α) : v ᵥ* 1 = v := by
ext
rw [← diagonal_one, vecMul_diagonal, mul_one]
@[simp]
theorem diagonal_const_mulVec (x : α) (v : m → α) :
(diagonal fun _ => x) *ᵥ v = x • v := by
ext; simp [mulVec_diagonal]
@[simp]
theorem vecMul_diagonal_const (x : α) (v : m → α) :
v ᵥ* (diagonal fun _ => x) = MulOpposite.op x • v := by
ext; simp [vecMul_diagonal]
@[simp]
theorem natCast_mulVec (x : ℕ) (v : m → α) : x *ᵥ v = (x : α) • v :=
diagonal_const_mulVec _ _
@[simp]
theorem vecMul_natCast (x : ℕ) (v : m → α) : v ᵥ* x = MulOpposite.op (x : α) • v :=
vecMul_diagonal_const _ _
@[simp]
theorem ofNat_mulVec (x : ℕ) [x.AtLeastTwo] (v : m → α) :
ofNat(x) *ᵥ v = (OfNat.ofNat x : α) • v :=
natCast_mulVec _ _
@[simp]
theorem vecMul_ofNat (x : ℕ) [x.AtLeastTwo] (v : m → α) :
v ᵥ* ofNat(x) = MulOpposite.op (OfNat.ofNat x : α) • v :=
vecMul_natCast _ _
end NonAssocSemiring
section NonUnitalNonAssocRing
variable [NonUnitalNonAssocRing α]
theorem neg_vecMul [Fintype m] (v : m → α) (A : Matrix m n α) : (-v) ᵥ* A = -(v ᵥ* A) := by
ext
apply neg_dotProduct
theorem vecMul_neg [Fintype m] (v : m → α) (A : Matrix m n α) : v ᵥ* (-A) = -(v ᵥ* A) := by
ext
apply dotProduct_neg
lemma neg_vecMul_neg [Fintype m] (v : m → α) (A : Matrix m n α) : (-v) ᵥ* (-A) = v ᵥ* A := by
rw [vecMul_neg, neg_vecMul, neg_neg]
theorem neg_mulVec [Fintype n] (v : n → α) (A : Matrix m n α) : (-A) *ᵥ v = -(A *ᵥ v) := by
ext
apply neg_dotProduct
theorem mulVec_neg [Fintype n] (v : n → α) (A : Matrix m n α) : A *ᵥ (-v) = -(A *ᵥ v) := by
ext
apply dotProduct_neg
lemma neg_mulVec_neg [Fintype n] (v : n → α) (A : Matrix m n α) : (-A) *ᵥ (-v) = A *ᵥ v := by
rw [mulVec_neg, neg_mulVec, neg_neg]
theorem mulVec_sub [Fintype n] (A : Matrix m n α) (x y : n → α) :
A *ᵥ (x - y) = A *ᵥ x - A *ᵥ y := by
ext
apply dotProduct_sub
theorem sub_mulVec [Fintype n] (A B : Matrix m n α) (x : n → α) :
(A - B) *ᵥ x = A *ᵥ x - B *ᵥ x := by simp [sub_eq_add_neg, add_mulVec, neg_mulVec]
theorem vecMul_sub [Fintype m] (A B : Matrix m n α) (x : m → α) :
x ᵥ* (A - B) = x ᵥ* A - x ᵥ* B := by simp [sub_eq_add_neg, vecMul_add, vecMul_neg]
theorem sub_vecMul [Fintype m] (A : Matrix m n α) (x y : m → α) :
(x - y) ᵥ* A = x ᵥ* A - y ᵥ* A := by
ext
apply sub_dotProduct
theorem sub_vecMulVec (w₁ w₂ : m → α) (v : n → α) :
vecMulVec (w₁ - w₂) v = vecMulVec w₁ v - vecMulVec w₂ v :=
ext fun _ _ => sub_mul _ _ _
theorem vecMulVec_sub (w : m → α) (v₁ v₂ : n → α) :
vecMulVec w (v₁ - v₂) = vecMulVec w v₁ - vecMulVec w v₂ :=
ext fun _ _ => mul_sub _ _ _
end NonUnitalNonAssocRing
section NonUnitalCommSemiring
variable [NonUnitalCommSemiring α]
theorem mulVec_transpose [Fintype m] (A : Matrix m n α) (x : m → α) : Aᵀ *ᵥ x = x ᵥ* A := by
ext
apply dotProduct_comm
theorem vecMul_transpose [Fintype n] (A : Matrix m n α) (x : n → α) : x ᵥ* Aᵀ = A *ᵥ x := by
ext
apply dotProduct_comm
theorem mulVec_vecMul [Fintype n] [Fintype o] (A : Matrix m n α) (B : Matrix o n α) (x : o → α) :
A *ᵥ (x ᵥ* B) = (A * Bᵀ) *ᵥ x := by rw [← mulVec_mulVec, mulVec_transpose]
theorem vecMul_mulVec [Fintype m] [Fintype n] (A : Matrix m n α) (B : Matrix m o α) (x : n → α) :
(A *ᵥ x) ᵥ* B = x ᵥ* (Aᵀ * B) := by rw [← vecMul_vecMul, vecMul_transpose]
end NonUnitalCommSemiring
section Semiring
variable [Semiring R]
lemma mulVec_injective_of_isUnit [Fintype m] [DecidableEq m] {A : Matrix m m R}
(ha : IsUnit A) : Function.Injective A.mulVec :=
isLeftRegular_iff_mulVec_injective.1 ha.isRegular.left
lemma vecMul_injective_of_isUnit [Fintype m] [DecidableEq m] {A : Matrix m m R}
(ha : IsUnit A) : Function.Injective A.vecMul :=
isRightRegular_iff_vecMul_injective.1 ha.isRegular.right
lemma pow_row_eq_zero_of_le [Fintype n] [DecidableEq n] {M : Matrix n n R} {k l : ℕ} {i : n}
(h : (M ^ k).row i = 0) (h' : k ≤ l) :
(M ^ l).row i = 0 := by
replace h' : l = k + (l - k) := by omega
rw [← single_one_vecMul] at h ⊢
rw [h', pow_add, ← vecMul_vecMul, h, zero_vecMul]
lemma pow_col_eq_zero_of_le [Fintype n] [DecidableEq n] {M : Matrix n n R} {k l : ℕ} {i : n}
(h : (M ^ k).col i = 0) (h' : k ≤ l) :
(M ^ l).col i = 0 := by
replace h' : l = (l - k) + k := by omega
rw [← mulVec_single_one] at h ⊢
rw [h', pow_add, ← mulVec_mulVec, h, mulVec_zero]
end Semiring
section CommSemiring
variable [CommSemiring α]
@[deprecated mulVec_smul (since := "2025-08-14")]
theorem mulVec_smul_assoc [Fintype n] (A : Matrix m n α) (b : n → α) (a : α) :
A *ᵥ (a • b) = a • A *ᵥ b :=
mulVec_smul _ _ _
end CommSemiring
section NonAssocRing
variable [NonAssocRing α]
variable [Fintype m] [DecidableEq m]
@[simp]
theorem intCast_mulVec (x : ℤ) (v : m → α) : x *ᵥ v = (x : α) • v :=
diagonal_const_mulVec _ _
@[simp]
theorem vecMul_intCast (x : ℤ) (v : m → α) : v ᵥ* x = MulOpposite.op (x : α) • v :=
vecMul_diagonal_const _ _
end NonAssocRing
section Transpose
open Matrix
@[simp]
theorem transpose_mul [AddCommMonoid α] [CommMagma α] [Fintype n] (M : Matrix m n α)
(N : Matrix n l α) : (M * N)ᵀ = Nᵀ * Mᵀ := by
ext
apply dotProduct_comm
variable (m n α)
end Transpose
theorem submatrix_mul [Fintype n] [Fintype o] [Mul α] [AddCommMonoid α] {p q : Type*}
(M : Matrix m n α) (N : Matrix n p α) (e₁ : l → m) (e₂ : o → n) (e₃ : q → p)
(he₂ : Function.Bijective e₂) :
(M * N).submatrix e₁ e₃ = M.submatrix e₁ e₂ * N.submatrix e₂ e₃ :=
ext fun _ _ => (he₂.sum_comp _).symm
/-! `simp` lemmas for `Matrix.submatrix`s interaction with `Matrix.diagonal`, `1`, and `Matrix.mul`
for when the mappings are bundled. -/
@[simp]
theorem submatrix_mul_equiv [Fintype n] [Fintype o] [AddCommMonoid α] [Mul α] {p q : Type*}
(M : Matrix m n α) (N : Matrix n p α) (e₁ : l → m) (e₂ : o ≃ n) (e₃ : q → p) :
M.submatrix e₁ e₂ * N.submatrix e₂ e₃ = (M * N).submatrix e₁ e₃ :=
(submatrix_mul M N e₁ e₂ e₃ e₂.bijective).symm
theorem submatrix_mulVec_equiv [Fintype n] [Fintype o] [NonUnitalNonAssocSemiring α]
(M : Matrix m n α) (v : o → α) (e₁ : l → m) (e₂ : o ≃ n) :
M.submatrix e₁ e₂ *ᵥ v = (M *ᵥ (v ∘ e₂.symm)) ∘ e₁ :=
funext fun _ => Eq.symm (dotProduct_comp_equiv_symm _ _ _)
@[simp]
theorem submatrix_id_mul_left [Fintype n] [Fintype o] [Mul α] [AddCommMonoid α] {p : Type*}
(M : Matrix m n α) (N : Matrix o p α) (e₁ : l → m) (e₂ : n ≃ o) :
M.submatrix e₁ id * N.submatrix e₂ id = M.submatrix e₁ e₂.symm * N := by
ext; simp [mul_apply, ← e₂.bijective.sum_comp]
@[simp]
theorem submatrix_id_mul_right [Fintype n] [Fintype o] [Mul α] [AddCommMonoid α] {p : Type*}
(M : Matrix m n α) (N : Matrix o p α) (e₁ : l → p) (e₂ : o ≃ n) :
M.submatrix id e₂ * N.submatrix id e₁ = M * N.submatrix e₂.symm e₁ := by
ext; simp [mul_apply, ← e₂.bijective.sum_comp]
theorem submatrix_vecMul_equiv [Fintype l] [Fintype m] [NonUnitalNonAssocSemiring α]
(M : Matrix m n α) (v : l → α) (e₁ : l ≃ m) (e₂ : o → n) :
v ᵥ* M.submatrix e₁ e₂ = ((v ∘ e₁.symm) ᵥ* M) ∘ e₂ :=
funext fun _ => Eq.symm (comp_equiv_symm_dotProduct _ _ _)
theorem mul_submatrix_one [Fintype n] [Finite o] [NonAssocSemiring α] [DecidableEq o] (e₁ : n ≃ o)
(e₂ : l → o) (M : Matrix m n α) :
M * (1 : Matrix o o α).submatrix e₁ e₂ = submatrix M id (e₁.symm ∘ e₂) := by
cases nonempty_fintype o
let A := M.submatrix id e₁.symm
have : M = A.submatrix id e₁ := by
simp only [A, submatrix_submatrix, Function.comp_id, submatrix_id_id, Equiv.symm_comp_self]
rw [this, submatrix_mul_equiv]
simp only [A, Matrix.mul_one, submatrix_submatrix, Function.comp_id, submatrix_id_id,
Equiv.symm_comp_self]
theorem one_submatrix_mul [Fintype m] [Finite o] [NonAssocSemiring α] [DecidableEq o] (e₁ : l → o)
(e₂ : m ≃ o) (M : Matrix m n α) :
((1 : Matrix o o α).submatrix e₁ e₂) * M = submatrix M (e₂.symm ∘ e₁) id := by
cases nonempty_fintype o
let A := M.submatrix e₂.symm id
have : M = A.submatrix e₂ id := by
simp only [A, submatrix_submatrix, Function.comp_id, submatrix_id_id, Equiv.symm_comp_self]
rw [this, submatrix_mul_equiv]
simp only [A, Matrix.one_mul, submatrix_submatrix, Function.comp_id, submatrix_id_id,
Equiv.symm_comp_self]
theorem submatrix_mul_transpose_submatrix [Fintype m] [Fintype n] [AddCommMonoid α] [Mul α]
(e : m ≃ n) (M : Matrix m n α) : M.submatrix id e * Mᵀ.submatrix e id = M * Mᵀ := by
rw [submatrix_mul_equiv, submatrix_id_id]
end Matrix
namespace RingHom
variable [Fintype n] [NonAssocSemiring α] [NonAssocSemiring β]
theorem map_matrix_mul (M : Matrix m n α) (N : Matrix n o α) (i : m) (j : o) (f : α →+* β) :
f ((M * N) i j) = (M.map f * N.map f) i j := by
simp [Matrix.mul_apply, map_sum]
theorem map_dotProduct [NonAssocSemiring R] [NonAssocSemiring S] (f : R →+* S) (v w : n → R) :
f (v ⬝ᵥ w) = f ∘ v ⬝ᵥ f ∘ w := by
simp only [dotProduct, map_sum f, f.map_mul, Function.comp]
theorem map_vecMul [NonAssocSemiring R] [NonAssocSemiring S] (f : R →+* S) (M : Matrix n m R)
(v : n → R) (i : m) : f ((v ᵥ* M) i) = ((f ∘ v) ᵥ* M.map f) i := by
simp only [Matrix.vecMul, Matrix.map_apply, RingHom.map_dotProduct, Function.comp_def]
theorem map_mulVec [NonAssocSemiring R] [NonAssocSemiring S] (f : R →+* S) (M : Matrix m n R)
(v : n → R) (i : m) : f ((M *ᵥ v) i) = (M.map f *ᵥ (f ∘ v)) i := by
simp only [Matrix.mulVec, Matrix.map_apply, RingHom.map_dotProduct, Function.comp_def]
end RingHom |
.lake/packages/mathlib/Mathlib/Data/Matrix/Basic.lean | import Mathlib.Algebra.Algebra.Opposite
import Mathlib.Algebra.Algebra.Pi
import Mathlib.Algebra.BigOperators.RingEquiv
import Mathlib.Data.Finite.Prod
import Mathlib.Data.Matrix.Mul
import Mathlib.LinearAlgebra.Pi
/-!
# Matrices
This file contains basic results on matrices including bundled versions of matrix operators.
## Implementation notes
For convenience, `Matrix m n α` is defined as `m → n → α`, as this allows elements of the matrix
to be accessed with `A i j`. However, it is not advisable to _construct_ matrices using terms of the
form `fun i j ↦ _` or even `(fun i j ↦ _ : Matrix m n α)`, as these are not recognized by Lean
as having the right type. Instead, `Matrix.of` should be used.
## TODO
Under various conditions, multiplication of infinite matrices makes sense.
These have not yet been implemented.
-/
assert_not_exists TrivialStar
universe u u' v w
variable {l m n o : Type*} {m' : o → Type*} {n' : o → Type*}
variable {R S T A α β γ : Type*}
namespace Matrix
instance decidableEq [DecidableEq α] [Fintype m] [Fintype n] : DecidableEq (Matrix m n α) :=
Fintype.decidablePiFintype
instance {n m} [Fintype m] [DecidableEq m] [Fintype n] [DecidableEq n] (α) [Fintype α] :
Fintype (Matrix m n α) := inferInstanceAs (Fintype (m → n → α))
instance {n m} [Finite m] [Finite n] (α) [Finite α] :
Finite (Matrix m n α) := inferInstanceAs (Finite (m → n → α))
section
variable (R)
/-- This is `Matrix.of` bundled as a linear equivalence. -/
def ofLinearEquiv [Semiring R] [AddCommMonoid α] [Module R α] : (m → n → α) ≃ₗ[R] Matrix m n α where
__ := ofAddEquiv
map_smul' _ _ := rfl
@[simp] lemma coe_ofLinearEquiv [Semiring R] [AddCommMonoid α] [Module R α] :
⇑(ofLinearEquiv _ : (m → n → α) ≃ₗ[R] Matrix m n α) = of := rfl
@[simp] lemma coe_ofLinearEquiv_symm [Semiring R] [AddCommMonoid α] [Module R α] :
⇑((ofLinearEquiv _).symm : Matrix m n α ≃ₗ[R] (m → n → α)) = of.symm := rfl
end
theorem sum_apply [AddCommMonoid α] (i : m) (j : n) (s : Finset β) (g : β → Matrix m n α) :
(∑ c ∈ s, g c) i j = ∑ c ∈ s, g c i j :=
(congr_fun (s.sum_apply i g) j).trans (s.sum_apply j _)
end Matrix
open Matrix
namespace Matrix
section Diagonal
variable [DecidableEq n]
variable (n α)
/-- `Matrix.diagonal` as an `AddMonoidHom`. -/
@[simps]
def diagonalAddMonoidHom [AddZeroClass α] : (n → α) →+ Matrix n n α where
toFun := diagonal
map_zero' := diagonal_zero
map_add' x y := (diagonal_add x y).symm
variable (R)
/-- `Matrix.diagonal` as a `LinearMap`. -/
@[simps]
def diagonalLinearMap [Semiring R] [AddCommMonoid α] [Module R α] : (n → α) →ₗ[R] Matrix n n α :=
{ diagonalAddMonoidHom n α with map_smul' := diagonal_smul }
variable {n α R}
section One
variable [Zero α] [One α]
lemma zero_le_one_elem [Preorder α] [ZeroLEOneClass α] (i j : n) :
0 ≤ (1 : Matrix n n α) i j := by
by_cases hi : i = j
· subst hi
simp
· simp [hi]
lemma zero_le_one_row [Preorder α] [ZeroLEOneClass α] (i : n) :
0 ≤ (1 : Matrix n n α) i :=
zero_le_one_elem i
end One
end Diagonal
section Diag
variable (n α)
/-- `Matrix.diag` as an `AddMonoidHom`. -/
@[simps]
def diagAddMonoidHom [AddZeroClass α] : Matrix n n α →+ n → α where
toFun := diag
map_zero' := diag_zero
map_add' := diag_add
variable (R)
/-- `Matrix.diag` as a `LinearMap`. -/
@[simps]
def diagLinearMap [Semiring R] [AddCommMonoid α] [Module R α] : Matrix n n α →ₗ[R] n → α :=
{ diagAddMonoidHom n α with map_smul' := diag_smul }
variable {n α R}
@[simp]
theorem diag_list_sum [AddMonoid α] (l : List (Matrix n n α)) : diag l.sum = (l.map diag).sum :=
map_list_sum (diagAddMonoidHom n α) l
@[simp]
theorem diag_multiset_sum [AddCommMonoid α] (s : Multiset (Matrix n n α)) :
diag s.sum = (s.map diag).sum :=
map_multiset_sum (diagAddMonoidHom n α) s
@[simp]
theorem diag_sum {ι} [AddCommMonoid α] (s : Finset ι) (f : ι → Matrix n n α) :
diag (∑ i ∈ s, f i) = ∑ i ∈ s, diag (f i) :=
map_sum (diagAddMonoidHom n α) f s
end Diag
open Matrix
section AddCommMonoid
variable [AddCommMonoid α] [Mul α]
end AddCommMonoid
section NonAssocSemiring
variable [NonAssocSemiring α]
variable (α n)
/-- `Matrix.diagonal` as a `RingHom`. -/
@[simps]
def diagonalRingHom [Fintype n] [DecidableEq n] : (n → α) →+* Matrix n n α :=
{ diagonalAddMonoidHom n α with
toFun := diagonal
map_one' := diagonal_one
map_mul' := fun _ _ => (diagonal_mul_diagonal' _ _).symm }
end NonAssocSemiring
section Semiring
variable [Semiring α]
theorem diagonal_pow [Fintype n] [DecidableEq n] (v : n → α) (k : ℕ) :
diagonal v ^ k = diagonal (v ^ k) :=
(map_pow (diagonalRingHom n α) v k).symm
/-- The ring homomorphism `α →+* Matrix n n α`
sending `a` to the diagonal matrix with `a` on the diagonal.
-/
def scalar (n : Type u) [DecidableEq n] [Fintype n] : α →+* Matrix n n α :=
(diagonalRingHom n α).comp <| Pi.constRingHom n α
section Scalar
variable [DecidableEq n] [Fintype n] [DecidableEq m] [Fintype m]
@[simp]
theorem scalar_apply (a : α) : scalar n a = diagonal fun _ => a :=
rfl
theorem scalar_inj [Nonempty n] {r s : α} : scalar n r = scalar n s ↔ r = s :=
(diagonal_injective.comp Function.const_injective).eq_iff
/-- A version of `Matrix.scalar_commute_iff` for rectangular matrices. -/
theorem scalar_comm_iff {r : α} {M : Matrix m n α} :
scalar m r * M = M * scalar n r ↔ r • M = MulOpposite.op r • M := by
simp_rw [scalar_apply, ← smul_eq_diagonal_mul, ← op_smul_eq_mul_diagonal]
theorem scalar_commute_iff {r : α} {M : Matrix n n α} :
Commute (scalar n r) M ↔ r • M = MulOpposite.op r • M :=
scalar_comm_iff
/-- A version of `Matrix.scalar_commute` for rectangular matrices. -/
theorem scalar_comm (r : α) (hr : ∀ r', Commute r r') (M : Matrix m n α) :
scalar m r * M = M * scalar n r :=
scalar_comm_iff.2 <| ext fun _ _ => hr _
theorem scalar_commute (r : α) (hr : ∀ r', Commute r r') (M : Matrix n n α) :
Commute (scalar n r) M := scalar_comm r hr M
end Scalar
end Semiring
section Algebra
variable [Fintype n] [DecidableEq n]
variable [CommSemiring R] [Semiring α] [Semiring β] [Algebra R α] [Algebra R β]
instance instAlgebra : Algebra R (Matrix n n α) where
algebraMap := (Matrix.scalar n).comp (algebraMap R α)
commutes' _ _ := scalar_commute _ (fun _ => Algebra.commutes _ _) _
smul_def' r x := by ext; simp [Matrix.scalar, Algebra.smul_def r]
theorem algebraMap_matrix_apply {r : R} {i j : n} :
algebraMap R (Matrix n n α) r i j = if i = j then algebraMap R α r else 0 := rfl
theorem algebraMap_eq_diagonal (r : R) :
algebraMap R (Matrix n n α) r = diagonal (algebraMap R (n → α) r) := rfl
theorem algebraMap_eq_diagonalRingHom :
algebraMap R (Matrix n n α) = (diagonalRingHom n α).comp (algebraMap R _) := rfl
@[simp]
theorem map_algebraMap (r : R) (f : α → β) (hf : f 0 = 0)
(hf₂ : f (algebraMap R α r) = algebraMap R β r) :
(algebraMap R (Matrix n n α) r).map f = algebraMap R (Matrix n n β) r := by
rw [algebraMap_eq_diagonal, algebraMap_eq_diagonal, diagonal_map hf]
simp [hf₂]
variable (R)
/-- `Matrix.diagonal` as an `AlgHom`. -/
@[simps]
def diagonalAlgHom : (n → α) →ₐ[R] Matrix n n α :=
{ diagonalRingHom n α with
toFun := diagonal
commutes' := fun r => (algebraMap_eq_diagonal r).symm }
variable (n)
/-- `Matrix.scalar` as an `AlgHom`. -/
def scalarAlgHom : α →ₐ[R] Matrix n n α where
toRingHom := scalar n
commutes' _ := rfl
@[simp] theorem scalarAlgHom_apply (a : α) : scalarAlgHom n R a = scalar n a := rfl
end Algebra
section AddHom
variable [Add α]
variable (R α) in
/-- Extracting entries from a matrix as an additive homomorphism. -/
@[simps]
def entryAddHom (i : m) (j : n) : AddHom (Matrix m n α) α where
toFun M := M i j
map_add' _ _ := rfl
-- It is necessary to spell out the name of the coercion explicitly on the RHS
-- for unification to succeed
lemma entryAddHom_eq_comp {i : m} {j : n} :
entryAddHom α i j =
((Pi.evalAddHom (fun _ => α) j).comp (Pi.evalAddHom _ i)).comp
(AddHomClass.toAddHom ofAddEquiv.symm) :=
rfl
end AddHom
section AddMonoidHom
variable [AddZeroClass α]
variable (R α) in
/--
Extracting entries from a matrix as an additive monoid homomorphism. Note this cannot be upgraded to
a ring homomorphism, as it does not respect multiplication.
-/
@[simps]
def entryAddMonoidHom (i : m) (j : n) : Matrix m n α →+ α where
toFun M := M i j
map_add' _ _ := rfl
map_zero' := rfl
-- It is necessary to spell out the name of the coercion explicitly on the RHS
-- for unification to succeed
lemma entryAddMonoidHom_eq_comp {i : m} {j : n} :
entryAddMonoidHom α i j =
((Pi.evalAddMonoidHom (fun _ => α) j).comp (Pi.evalAddMonoidHom _ i)).comp
(AddMonoidHomClass.toAddMonoidHom ofAddEquiv.symm) := by
rfl
@[simp] lemma evalAddMonoidHom_comp_diagAddMonoidHom (i : m) :
(Pi.evalAddMonoidHom _ i).comp (diagAddMonoidHom m α) = entryAddMonoidHom α i i := by
simp [AddMonoidHom.ext_iff]
@[simp] lemma entryAddMonoidHom_toAddHom {i : m} {j : n} :
(entryAddMonoidHom α i j : AddHom _ _) = entryAddHom α i j := rfl
end AddMonoidHom
section LinearMap
variable [Semiring R] [AddCommMonoid α] [Module R α]
variable (R α) in
/--
Extracting entries from a matrix as a linear map. Note this cannot be upgraded to an algebra
homomorphism, as it does not respect multiplication.
-/
@[simps]
def entryLinearMap (i : m) (j : n) :
Matrix m n α →ₗ[R] α where
toFun M := M i j
map_add' _ _ := rfl
map_smul' _ _ := rfl
-- It is necessary to spell out the name of the coercion explicitly on the RHS
-- for unification to succeed
lemma entryLinearMap_eq_comp {i : m} {j : n} :
entryLinearMap R α i j =
LinearMap.proj j ∘ₗ LinearMap.proj i ∘ₗ (ofLinearEquiv R).symm.toLinearMap := by
rfl
@[simp] lemma proj_comp_diagLinearMap (i : m) :
LinearMap.proj i ∘ₗ diagLinearMap m R α = entryLinearMap R α i i := by
simp [LinearMap.ext_iff]
@[simp] lemma entryLinearMap_toAddMonoidHom {i : m} {j : n} :
(entryLinearMap R α i j : _ →+ _) = entryAddMonoidHom α i j := rfl
@[simp] lemma entryLinearMap_toAddHom {i : m} {j : n} :
(entryLinearMap R α i j : AddHom _ _) = entryAddHom α i j := rfl
end LinearMap
end Matrix
/-!
### Bundled versions of `Matrix.map`
-/
namespace Equiv
/-- The `Equiv` between spaces of matrices induced by an `Equiv` between their
coefficients. This is `Matrix.map` as an `Equiv`. -/
@[simps apply]
def mapMatrix (f : α ≃ β) : Matrix m n α ≃ Matrix m n β where
toFun M := M.map f
invFun M := M.map f.symm
left_inv _ := Matrix.ext fun _ _ => f.symm_apply_apply _
right_inv _ := Matrix.ext fun _ _ => f.apply_symm_apply _
@[simp]
theorem mapMatrix_refl : (Equiv.refl α).mapMatrix = Equiv.refl (Matrix m n α) :=
rfl
@[simp]
theorem mapMatrix_symm (f : α ≃ β) : f.mapMatrix.symm = (f.symm.mapMatrix : Matrix m n β ≃ _) :=
rfl
@[simp]
theorem mapMatrix_trans (f : α ≃ β) (g : β ≃ γ) :
f.mapMatrix.trans g.mapMatrix = ((f.trans g).mapMatrix : Matrix m n α ≃ _) :=
rfl
end Equiv
namespace AddMonoidHom
section AddZeroClass
variable [AddZeroClass α] [AddZeroClass β] [AddZeroClass γ]
/-- The `AddMonoidHom` between spaces of matrices induced by an `AddMonoidHom` between their
coefficients. This is `Matrix.map` as an `AddMonoidHom`. -/
@[simps]
def mapMatrix (f : α →+ β) : Matrix m n α →+ Matrix m n β where
toFun M := M.map f
map_zero' := Matrix.map_zero f f.map_zero
map_add' := Matrix.map_add f f.map_add
@[simp]
theorem mapMatrix_id : (AddMonoidHom.id α).mapMatrix = AddMonoidHom.id (Matrix m n α) :=
rfl
@[simp]
theorem mapMatrix_comp (f : β →+ γ) (g : α →+ β) :
f.mapMatrix.comp g.mapMatrix = ((f.comp g).mapMatrix : Matrix m n α →+ _) :=
rfl
@[simp] lemma entryAddMonoidHom_comp_mapMatrix (f : α →+ β) (i : m) (j : n) :
(entryAddMonoidHom β i j).comp f.mapMatrix = f.comp (entryAddMonoidHom α i j) := rfl
@[simp]
theorem mapMatrix_zero : (0 : α →+ β).mapMatrix = (0 : Matrix m n α →+ _) := rfl
end AddZeroClass
@[simp]
theorem mapMatrix_add [AddZeroClass α] [AddCommMonoid β] (f g : α →+ β) :
(f + g).mapMatrix = (f.mapMatrix + g.mapMatrix : Matrix m n α →+ _) := rfl
@[simp]
theorem mapMatrix_sub [AddZeroClass α] [AddCommGroup β] (f g : α →+ β) :
(f - g).mapMatrix = (f.mapMatrix - g.mapMatrix : Matrix m n α →+ _) := rfl
@[simp]
theorem mapMatrix_neg [AddZeroClass α] [AddCommGroup β] (f : α →+ β) :
(-f).mapMatrix = (-f.mapMatrix : Matrix m n α →+ _) := rfl
@[simp]
theorem mapMatrix_smul [Monoid A] [AddZeroClass α] [AddMonoid β] [DistribMulAction A β]
(a : A) (f : α →+ β) :
(a • f).mapMatrix = (a • f.mapMatrix : Matrix m n α →+ _) := rfl
end AddMonoidHom
namespace AddEquiv
variable [Add α] [Add β] [Add γ]
/-- The `AddEquiv` between spaces of matrices induced by an `AddEquiv` between their
coefficients. This is `Matrix.map` as an `AddEquiv`. -/
@[simps apply]
def mapMatrix (f : α ≃+ β) : Matrix m n α ≃+ Matrix m n β :=
{ f.toEquiv.mapMatrix with
toFun := fun M => M.map f
invFun := fun M => M.map f.symm
map_add' := Matrix.map_add f (map_add f) }
@[simp]
theorem mapMatrix_refl : (AddEquiv.refl α).mapMatrix = AddEquiv.refl (Matrix m n α) :=
rfl
@[simp]
theorem mapMatrix_symm (f : α ≃+ β) : f.mapMatrix.symm = (f.symm.mapMatrix : Matrix m n β ≃+ _) :=
rfl
@[simp]
theorem mapMatrix_trans (f : α ≃+ β) (g : β ≃+ γ) :
f.mapMatrix.trans g.mapMatrix = ((f.trans g).mapMatrix : Matrix m n α ≃+ _) :=
rfl
@[simp] lemma entryAddHom_comp_mapMatrix (f : α ≃+ β) (i : m) (j : n) :
(entryAddHom β i j).comp (AddHomClass.toAddHom f.mapMatrix) =
(f : AddHom α β).comp (entryAddHom _ i j) := rfl
end AddEquiv
namespace LinearMap
variable [Semiring R] [Semiring S] [Semiring T]
variable {σᵣₛ : R →+* S} {σₛₜ : S →+* T} {σᵣₜ : R →+* T} [RingHomCompTriple σᵣₛ σₛₜ σᵣₜ]
section AddCommMonoid
variable [AddCommMonoid α] [AddCommMonoid β] [AddCommMonoid γ]
variable [Module R α] [Module S β] [Module T γ]
/-- The `LinearMap` between spaces of matrices induced by a `LinearMap` between their
coefficients. This is `Matrix.map` as a `LinearMap`. -/
@[simps]
def mapMatrix (f : α →ₛₗ[σᵣₛ] β) : Matrix m n α →ₛₗ[σᵣₛ] Matrix m n β where
toFun M := M.map f
map_add' := Matrix.map_add f f.map_add
map_smul' r := Matrix.map_smulₛₗ f _ r (f.map_smulₛₗ r)
@[simp]
theorem mapMatrix_id : LinearMap.id.mapMatrix = (LinearMap.id : Matrix m n α →ₗ[R] _) :=
rfl
@[simp]
theorem mapMatrix_comp (f : β →ₛₗ[σₛₜ] γ) (g : α →ₛₗ[σᵣₛ] β) :
f.mapMatrix.comp g.mapMatrix = ((f.comp g).mapMatrix : Matrix m n α →ₛₗ[_] _) :=
rfl
@[simp] lemma entryLinearMap_comp_mapMatrix (f : α →ₛₗ[σᵣₛ] β) (i : m) (j : n) :
(entryLinearMap S _ i j).comp f.mapMatrix = f.comp (entryLinearMap R _ i j) := rfl
@[simp]
theorem mapMatrix_zero : (0 : α →ₛₗ[σᵣₛ] β).mapMatrix = (0 : Matrix m n α →ₛₗ[_] _) := rfl
@[simp]
theorem mapMatrix_add (f g : α →ₛₗ[σᵣₛ] β) :
(f + g).mapMatrix = (f.mapMatrix + g.mapMatrix : Matrix m n α →ₛₗ[_] _) := rfl
@[simp]
theorem mapMatrix_smul [Monoid A] [DistribMulAction A β] [SMulCommClass S A β]
(a : A) (f : α →ₛₗ[σᵣₛ] β) :
(a • f).mapMatrix = (a • f.mapMatrix : Matrix m n α →ₛₗ[_] _) := rfl
variable (A) in
/-- `LinearMap.mapMatrix` is itself linear in the map being applied.
Alternative, this is `Matrix.map` as a bilinear map. -/
@[simps]
def mapMatrixLinear [Semiring A] [Module A β] [SMulCommClass S A β] :
(α →ₛₗ[σᵣₛ] β) →ₗ[A] (Matrix m n α →ₛₗ[σᵣₛ] Matrix m n β) where
toFun := mapMatrix
map_add' := mapMatrix_add
map_smul' := mapMatrix_smul
end AddCommMonoid
section
variable [AddCommMonoid α] [AddCommGroup β]
variable [Module R α] [Module S β]
@[simp]
theorem mapMatrix_sub (f g : α →ₛₗ[σᵣₛ] β) :
(f - g).mapMatrix = (f.mapMatrix - g.mapMatrix : Matrix m n α →ₛₗ[σᵣₛ] _) := rfl
@[simp]
theorem mapMatrix_neg (f : α →ₛₗ[σᵣₛ] β) :
(-f).mapMatrix = (-f.mapMatrix : Matrix m n α →ₛₗ[σᵣₛ] _) := rfl
end
end LinearMap
namespace LinearEquiv
variable [Semiring R] [Semiring S] [Semiring T]
variable [AddCommMonoid α] [AddCommMonoid β] [AddCommMonoid γ]
variable [Module R α] [Module S β] [Module T γ]
variable {σᵣₛ : R →+* S} {σₛₜ : S →+* T} {σᵣₜ : R →+* T} [RingHomCompTriple σᵣₛ σₛₜ σᵣₜ]
variable {σₛᵣ : S →+* R} {σₜₛ : T →+* S} {σₜᵣ : T →+* R} [RingHomCompTriple σₜₛ σₛᵣ σₜᵣ]
variable [RingHomInvPair σᵣₛ σₛᵣ] [RingHomInvPair σₛᵣ σᵣₛ]
variable [RingHomInvPair σₛₜ σₜₛ] [RingHomInvPair σₜₛ σₛₜ]
variable [RingHomInvPair σᵣₜ σₜᵣ] [RingHomInvPair σₜᵣ σᵣₜ]
/-- The `LinearEquiv` between spaces of matrices induced by a `LinearEquiv` between their
coefficients. This is `Matrix.map` as a `LinearEquiv`. -/
@[simps apply]
def mapMatrix (f : α ≃ₛₗ[σᵣₛ] β) : Matrix m n α ≃ₛₗ[σᵣₛ] Matrix m n β :=
{ f.toEquiv.mapMatrix,
f.toLinearMap.mapMatrix with
toFun := fun M => M.map f
invFun := fun M => M.map f.symm }
@[simp]
theorem mapMatrix_refl : (LinearEquiv.refl R α).mapMatrix = LinearEquiv.refl R (Matrix m n α) :=
rfl
@[simp]
theorem mapMatrix_symm (f : α ≃ₛₗ[σᵣₛ] β) :
f.mapMatrix.symm = (f.symm.mapMatrix : Matrix m n β ≃ₛₗ[_] _) :=
rfl
@[simp]
theorem mapMatrix_trans (f : α ≃ₛₗ[σᵣₛ] β) (g : β ≃ₛₗ[σₛₜ] γ) :
f.mapMatrix.trans g.mapMatrix = ((f.trans g).mapMatrix : Matrix m n α ≃ₛₗ[_] _) :=
rfl
@[simp] lemma mapMatrix_toLinearMap (f : α ≃ₛₗ[σᵣₛ] β) :
(f.mapMatrix : _ ≃ₛₗ[_] Matrix m n β).toLinearMap = f.toLinearMap.mapMatrix := by
rfl
lemma entryLinearMap_comp_mapMatrix (f : α ≃ₛₗ[σᵣₛ] β) (i : m) (j : n) :
(entryLinearMap S _ i j).comp f.mapMatrix.toLinearMap =
f.toLinearMap.comp (entryLinearMap R _ i j) := by
simp only [mapMatrix_toLinearMap, LinearMap.entryLinearMap_comp_mapMatrix]
end LinearEquiv
namespace RingHom
variable [Fintype m] [DecidableEq m]
variable [NonAssocSemiring α] [NonAssocSemiring β] [NonAssocSemiring γ]
/-- The `RingHom` between spaces of square matrices induced by a `RingHom` between their
coefficients. This is `Matrix.map` as a `RingHom`. -/
@[simps]
def mapMatrix (f : α →+* β) : Matrix m m α →+* Matrix m m β :=
{ f.toAddMonoidHom.mapMatrix with
toFun := fun M => M.map f
map_one' := by simp
map_mul' := fun _ _ => Matrix.map_mul }
@[simp]
theorem mapMatrix_id : (RingHom.id α).mapMatrix = RingHom.id (Matrix m m α) :=
rfl
@[simp]
theorem mapMatrix_comp (f : β →+* γ) (g : α →+* β) :
f.mapMatrix.comp g.mapMatrix = ((f.comp g).mapMatrix : Matrix m m α →+* _) :=
rfl
end RingHom
namespace RingEquiv
variable [Fintype m] [DecidableEq m]
variable [NonAssocSemiring α] [NonAssocSemiring β] [NonAssocSemiring γ]
/-- The `RingEquiv` between spaces of square matrices induced by a `RingEquiv` between their
coefficients. This is `Matrix.map` as a `RingEquiv`. -/
@[simps apply]
def mapMatrix (f : α ≃+* β) : Matrix m m α ≃+* Matrix m m β :=
{ f.toRingHom.mapMatrix,
f.toAddEquiv.mapMatrix with
toFun := fun M => M.map f
invFun := fun M => M.map f.symm }
@[simp]
theorem mapMatrix_refl : (RingEquiv.refl α).mapMatrix = RingEquiv.refl (Matrix m m α) :=
rfl
@[simp]
theorem mapMatrix_symm (f : α ≃+* β) : f.mapMatrix.symm = (f.symm.mapMatrix : Matrix m m β ≃+* _) :=
rfl
@[simp]
theorem mapMatrix_trans (f : α ≃+* β) (g : β ≃+* γ) :
f.mapMatrix.trans g.mapMatrix = ((f.trans g).mapMatrix : Matrix m m α ≃+* _) :=
rfl
open MulOpposite in
/--
For any ring `R`, we have ring isomorphism `Matₙₓₙ(Rᵒᵖ) ≅ (Matₙₓₙ(R))ᵒᵖ` given by transpose.
-/
@[simps apply symm_apply]
def mopMatrix : Matrix m m αᵐᵒᵖ ≃+* (Matrix m m α)ᵐᵒᵖ where
toFun M := op (M.transpose.map unop)
invFun M := M.unop.transpose.map op
left_inv _ := by aesop
right_inv _ := by aesop
map_mul' _ _ := unop_injective <| by ext; simp [transpose, mul_apply]
map_add' _ _ := by aesop
end RingEquiv
namespace AlgHom
variable [Fintype m] [DecidableEq m]
variable [CommSemiring R] [Semiring α] [Semiring β] [Semiring γ]
variable [Algebra R α] [Algebra R β] [Algebra R γ]
/-- The `AlgHom` between spaces of square matrices induced by an `AlgHom` between their
coefficients. This is `Matrix.map` as an `AlgHom`. -/
@[simps]
def mapMatrix (f : α →ₐ[R] β) : Matrix m m α →ₐ[R] Matrix m m β :=
{ f.toRingHom.mapMatrix with
toFun := fun M => M.map f
commutes' := fun r => Matrix.map_algebraMap r f (map_zero _) (f.commutes r) }
@[simp]
theorem mapMatrix_id : (AlgHom.id R α).mapMatrix = AlgHom.id R (Matrix m m α) :=
rfl
@[simp]
theorem mapMatrix_comp (f : β →ₐ[R] γ) (g : α →ₐ[R] β) :
f.mapMatrix.comp g.mapMatrix = ((f.comp g).mapMatrix : Matrix m m α →ₐ[R] _) :=
rfl
end AlgHom
namespace AlgEquiv
variable [Fintype m] [DecidableEq m]
variable [CommSemiring R] [Semiring α] [Semiring β] [Semiring γ]
variable [Algebra R α] [Algebra R β] [Algebra R γ]
/-- The `AlgEquiv` between spaces of square matrices induced by an `AlgEquiv` between their
coefficients. This is `Matrix.map` as an `AlgEquiv`. -/
@[simps apply]
def mapMatrix (f : α ≃ₐ[R] β) : Matrix m m α ≃ₐ[R] Matrix m m β :=
{ f.toAlgHom.mapMatrix,
f.toRingEquiv.mapMatrix with
toFun := fun M => M.map f
invFun := fun M => M.map f.symm }
@[simp]
theorem mapMatrix_refl : AlgEquiv.refl.mapMatrix = (AlgEquiv.refl : Matrix m m α ≃ₐ[R] _) :=
rfl
@[simp]
theorem mapMatrix_symm (f : α ≃ₐ[R] β) :
f.mapMatrix.symm = (f.symm.mapMatrix : Matrix m m β ≃ₐ[R] _) :=
rfl
@[simp]
theorem mapMatrix_trans (f : α ≃ₐ[R] β) (g : β ≃ₐ[R] γ) :
f.mapMatrix.trans g.mapMatrix = ((f.trans g).mapMatrix : Matrix m m α ≃ₐ[R] _) :=
rfl
/-- For any algebra `α` over a ring `R`, we have an `R`-algebra isomorphism
`Matₙₓₙ(αᵒᵖ) ≅ (Matₙₓₙ(R))ᵒᵖ` given by transpose. If `α` is commutative,
we can get rid of the `ᵒᵖ` in the left-hand side, see `Matrix.transposeAlgEquiv`. -/
@[simps!] def mopMatrix : Matrix m m αᵐᵒᵖ ≃ₐ[R] (Matrix m m α)ᵐᵒᵖ where
__ := RingEquiv.mopMatrix
commutes' _ := MulOpposite.unop_injective <| by
ext; simp [algebraMap_matrix_apply, eq_comm, apply_ite MulOpposite.unop]
end AlgEquiv
namespace AddSubmonoid
variable {A : Type*} [AddMonoid A]
/-- A version of `Set.matrix` for `AddSubmonoid`s.
Given an `AddSubmonoid` `S`, `S.matrix` is the `AddSubmonoid` of matrices `m`
all of whose entries `m i j` belong to `S`. -/
@[simps]
def matrix (S : AddSubmonoid A) : AddSubmonoid (Matrix m n A) where
carrier := Set.matrix S
add_mem' hm hn i j := add_mem (hm i j) (hn i j)
zero_mem' _ _ := zero_mem _
end AddSubmonoid
namespace AddSubgroup
variable {A : Type*} [AddGroup A]
/-- A version of `Set.matrix` for `AddSubgroup`s.
Given an `AddSubgroup` `S`, `S.matrix` is the `AddSubgroup` of matrices `m`
all of whose entries `m i j` belong to `S`. -/
@[simps!]
def matrix (S : AddSubgroup A) : AddSubgroup (Matrix m n A) where
__ := S.toAddSubmonoid.matrix
neg_mem' hm i j := AddSubgroup.neg_mem _ (hm i j)
end AddSubgroup
namespace Subsemiring
variable {R : Type*} [NonAssocSemiring R]
variable [Fintype n] [DecidableEq n]
/-- A version of `Set.matrix` for `Subsemiring`s.
Given a `Subsemiring` `S`, `S.matrix` is the `Subsemiring` of square matrices `m`
all of whose entries `m i j` belong to `S`. -/
@[simps!]
def matrix (S : Subsemiring R) : Subsemiring (Matrix n n R) where
__ := S.toAddSubmonoid.matrix
mul_mem' ha hb i j := Subsemiring.sum_mem _ (fun k _ => Subsemiring.mul_mem _ (ha i k) (hb k j))
one_mem' := (diagonal_mem_matrix_iff (Subsemiring.zero_mem _)).mpr fun _ => Subsemiring.one_mem _
end Subsemiring
namespace Subring
variable {R : Type*} [Ring R]
variable [Fintype n] [DecidableEq n]
/-- A version of `Set.matrix` for `Subring`s.
Given a `Subring` `S`, `S.matrix` is the `Subring` of square matrices `m`
all of whose entries `m i j` belong to `S`. -/
@[simps!]
def matrix (S : Subring R) : Subring (Matrix n n R) where
__ := S.toSubsemiring.matrix
neg_mem' hm i j := Subring.neg_mem _ (hm i j)
end Subring
namespace Submodule
variable {R M : Type*} [Semiring R] [AddCommMonoid M] [Module R M]
/-- A version of `Set.matrix` for `Submodule`s.
Given a `Submodule` `S`, `S.matrix` is the `Submodule` of matrices `m`
all of whose entries `m i j` belong to `S`. -/
@[simps!]
def matrix (S : Submodule R M) : Submodule R (Matrix m n M) where
__ := S.toAddSubmonoid.matrix
smul_mem' _ _ hm i j := Submodule.smul_mem _ _ (hm i j)
end Submodule
open Matrix
namespace Matrix
section Pi
variable {ι : Type*} {β : ι → Type*}
/-- Matrices over a Pi type are in canonical bijection with tuples of matrices. -/
@[simps] def piEquiv : Matrix m n (Π i, β i) ≃ Π i, Matrix m n (β i) where
toFun f i := f.map (· i)
invFun f := .of fun j k i ↦ f i j k
left_inv _ := rfl
right_inv _ := rfl
/-- `piEquiv` as an `AddEquiv`. -/
@[simps!] def piAddEquiv [∀ i, Add (β i)] : Matrix m n (Π i, β i) ≃+ Π i, Matrix m n (β i) where
__ := piEquiv
map_add' _ _ := rfl
/-- `piEquiv` as a `LinearEquiv`. -/
@[simps] def piLinearEquiv (R) [Semiring R] [∀ i, AddCommMonoid (β i)] [∀ i, Module R (β i)] :
Matrix m n (Π i, β i) ≃ₗ[R] Π i, Matrix m n (β i) where
__ := piAddEquiv
map_smul' _ _ := rfl
/-- `piEquiv` as a `RingEquiv`. -/
@[simps!] def piRingEquiv [∀ i, AddCommMonoid (β i)] [∀ i, Mul (β i)] [Fintype n] :
Matrix n n (Π i, β i) ≃+* Π i, Matrix n n (β i) where
__ := piAddEquiv
map_mul' _ _ := by ext; simp [Matrix.mul_apply]
/-- `piEquiv` as an `AlgEquiv`. -/
@[simps!] def piAlgEquiv (R) [CommSemiring R] [∀ i, Semiring (β i)] [∀ i, Algebra R (β i)]
[Fintype n] [DecidableEq n] : Matrix n n (Π i, β i) ≃ₐ[R] Π i, Matrix n n (β i) where
__ := piRingEquiv
commutes' := (AlgHom.mk' (piRingEquiv (β := β) (n := n)).toRingHom fun _ _ ↦ rfl).commutes
end Pi
section Transpose
open Matrix
variable (m n α)
/-- `Matrix.transpose` as an `AddEquiv` -/
@[simps apply]
def transposeAddEquiv [Add α] : Matrix m n α ≃+ Matrix n m α where
toFun := transpose
invFun := transpose
left_inv := transpose_transpose
right_inv := transpose_transpose
map_add' := transpose_add
@[simp]
theorem transposeAddEquiv_symm [Add α] : (transposeAddEquiv m n α).symm = transposeAddEquiv n m α :=
rfl
variable {m n α}
theorem transpose_list_sum [AddMonoid α] (l : List (Matrix m n α)) :
l.sumᵀ = (l.map transpose).sum :=
map_list_sum (transposeAddEquiv m n α) l
theorem transpose_multiset_sum [AddCommMonoid α] (s : Multiset (Matrix m n α)) :
s.sumᵀ = (s.map transpose).sum :=
(transposeAddEquiv m n α).toAddMonoidHom.map_multiset_sum s
theorem transpose_sum [AddCommMonoid α] {ι : Type*} (s : Finset ι) (M : ι → Matrix m n α) :
(∑ i ∈ s, M i)ᵀ = ∑ i ∈ s, (M i)ᵀ :=
map_sum (transposeAddEquiv m n α) _ s
variable (m n R α)
/-- `Matrix.transpose` as a `LinearMap` -/
@[simps apply]
def transposeLinearEquiv [Semiring R] [AddCommMonoid α] [Module R α] :
Matrix m n α ≃ₗ[R] Matrix n m α :=
{ transposeAddEquiv m n α with map_smul' := transpose_smul }
@[simp]
theorem transposeLinearEquiv_symm [Semiring R] [AddCommMonoid α] [Module R α] :
(transposeLinearEquiv m n R α).symm = transposeLinearEquiv n m R α :=
rfl
variable {m n R α}
variable (m α)
/-- `Matrix.transpose` as a `RingEquiv` to the opposite ring -/
@[simps]
def transposeRingEquiv [AddCommMonoid α] [CommSemigroup α] [Fintype m] :
Matrix m m α ≃+* (Matrix m m α)ᵐᵒᵖ :=
{ (transposeAddEquiv m m α).trans MulOpposite.opAddEquiv with
toFun := fun M => MulOpposite.op Mᵀ
invFun := fun M => M.unopᵀ
map_mul' := fun M N =>
(congr_arg MulOpposite.op (transpose_mul M N)).trans (MulOpposite.op_mul _ _)
left_inv := fun M => transpose_transpose M
right_inv := fun M => MulOpposite.unop_injective <| transpose_transpose M.unop }
variable {m α}
@[simp]
theorem transpose_pow [CommSemiring α] [Fintype m] [DecidableEq m] (M : Matrix m m α) (k : ℕ) :
(M ^ k)ᵀ = Mᵀ ^ k :=
MulOpposite.op_injective <| map_pow (transposeRingEquiv m α) M k
theorem transpose_list_prod [CommSemiring α] [Fintype m] [DecidableEq m] (l : List (Matrix m m α)) :
l.prodᵀ = (l.map transpose).reverse.prod :=
(transposeRingEquiv m α).unop_map_list_prod l
variable (R m α)
/-- `Matrix.transpose` as an `AlgEquiv` to the opposite ring -/
@[simps]
def transposeAlgEquiv [CommSemiring R] [CommSemiring α] [Fintype m] [DecidableEq m] [Algebra R α] :
Matrix m m α ≃ₐ[R] (Matrix m m α)ᵐᵒᵖ :=
{ (transposeAddEquiv m m α).trans MulOpposite.opAddEquiv,
transposeRingEquiv m α with
toFun := fun M => MulOpposite.op Mᵀ
commutes' := fun r => by
simp only [algebraMap_eq_diagonal, diagonal_transpose, MulOpposite.algebraMap_apply] }
variable {R m α}
end Transpose
section NonUnitalNonAssocSemiring
variable {ι : Type*} [NonUnitalNonAssocSemiring α] [Fintype n]
theorem sum_mulVec (s : Finset ι) (x : ι → Matrix m n α) (y : n → α) :
(∑ i ∈ s, x i) *ᵥ y = ∑ i ∈ s, x i *ᵥ y := by
ext
simp only [mulVec, dotProduct, sum_apply, Finset.sum_mul, Finset.sum_apply]
rw [Finset.sum_comm]
theorem mulVec_sum (x : Matrix m n α) (s : Finset ι) (y : ι → (n → α)) :
x *ᵥ ∑ i ∈ s, y i = ∑ i ∈ s, x *ᵥ y i := by
ext
simp only [mulVec, dotProduct_sum, Finset.sum_apply]
theorem sum_vecMul (s : Finset ι) (x : ι → (n → α)) (y : Matrix n m α) :
(∑ i ∈ s, x i) ᵥ* y = ∑ i ∈ s, x i ᵥ* y := by
ext
simp only [vecMul, sum_dotProduct, Finset.sum_apply]
theorem vecMul_sum (x : n → α) (s : Finset ι) (y : ι → Matrix n m α) :
x ᵥ* (∑ i ∈ s, y i) = ∑ i ∈ s, x ᵥ* y i := by
ext
simp only [vecMul, dotProduct, sum_apply, Finset.mul_sum, Finset.sum_apply]
rw [Finset.sum_comm]
end NonUnitalNonAssocSemiring
end Matrix |
.lake/packages/mathlib/Mathlib/Data/Matrix/DMatrix.lean | import Mathlib.Algebra.Group.Hom.Defs
import Mathlib.Algebra.Group.Pi.Basic
/-!
# Dependent-typed matrices
-/
universe u u' v w z
/-- `DMatrix m n` is the type of dependently typed matrices
whose rows are indexed by the type `m` and
whose columns are indexed by the type `n`.
In most applications `m` and `n` are finite types. -/
def DMatrix (m : Type u) (n : Type u') (α : m → n → Type v) : Type max u u' v :=
∀ i j, α i j
variable {m n : Type*}
variable {α : m → n → Type v}
namespace DMatrix
section Ext
variable {M N : DMatrix m n α}
theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N :=
⟨fun h => funext fun i => funext <| h i, fun h => by simp [h]⟩
@[ext]
theorem ext : (∀ i j, M i j = N i j) → M = N :=
ext_iff.mp
end Ext
/-- `M.map f` is the DMatrix obtained by applying `f` to each entry of the matrix `M`. -/
def map (M : DMatrix m n α) {β : m → n → Type w} (f : ∀ ⦃i j⦄, α i j → β i j) : DMatrix m n β :=
fun i j => f (M i j)
@[simp]
theorem map_apply {M : DMatrix m n α} {β : m → n → Type w} {f : ∀ ⦃i j⦄, α i j → β i j} {i : m}
{j : n} : M.map f i j = f (M i j) := rfl
@[simp]
theorem map_map {M : DMatrix m n α} {β : m → n → Type w} {γ : m → n → Type z}
{f : ∀ ⦃i j⦄, α i j → β i j} {g : ∀ ⦃i j⦄, β i j → γ i j} :
(M.map f).map g = M.map fun _ _ x => g (f x) := by ext; simp
/-- The transpose of a dmatrix. -/
def transpose (M : DMatrix m n α) : DMatrix n m fun j i => α i j
| x, y => M y x
@[inherit_doc]
scoped postfix:1024 "ᵀ" => DMatrix.transpose
/-- `DMatrix.col u` is the column matrix whose entries are given by `u`. -/
def col {α : m → Type v} (w : ∀ i, α i) : DMatrix m Unit fun i _j => α i
| x, _y => w x
/-- `DMatrix.row u` is the row matrix whose entries are given by `u`. -/
def row {α : n → Type v} (v : ∀ j, α j) : DMatrix Unit n fun _i j => α j
| _x, y => v y
instance [∀ i j, Inhabited (α i j)] : Inhabited (DMatrix m n α) :=
inferInstanceAs <| Inhabited <| ∀ i j, α i j
instance [∀ i j, Add (α i j)] : Add (DMatrix m n α) :=
inferInstanceAs <| Add <| ∀ i j, α i j
instance [∀ i j, AddSemigroup (α i j)] : AddSemigroup (DMatrix m n α) :=
inferInstanceAs <| AddSemigroup <| ∀ i j, α i j
instance [∀ i j, AddCommSemigroup (α i j)] : AddCommSemigroup (DMatrix m n α) :=
inferInstanceAs <| AddCommSemigroup <| ∀ i j, α i j
instance [∀ i j, Zero (α i j)] : Zero (DMatrix m n α) :=
inferInstanceAs <| Zero <| ∀ i j, α i j
instance [∀ i j, AddMonoid (α i j)] : AddMonoid (DMatrix m n α) :=
inferInstanceAs <| AddMonoid <| ∀ i j, α i j
instance [∀ i j, AddCommMonoid (α i j)] : AddCommMonoid (DMatrix m n α) :=
inferInstanceAs <| AddCommMonoid <| ∀ i j, α i j
instance [∀ i j, Neg (α i j)] : Neg (DMatrix m n α) :=
inferInstanceAs <| Neg <| ∀ i j, α i j
instance [∀ i j, Sub (α i j)] : Sub (DMatrix m n α) :=
inferInstanceAs <| Sub <| ∀ i j, α i j
instance [∀ i j, AddGroup (α i j)] : AddGroup (DMatrix m n α) :=
inferInstanceAs <| AddGroup <| ∀ i j, α i j
instance [∀ i j, AddCommGroup (α i j)] : AddCommGroup (DMatrix m n α) :=
inferInstanceAs <| AddCommGroup <| ∀ i j, α i j
instance [∀ i j, Unique (α i j)] : Unique (DMatrix m n α) :=
inferInstanceAs <| Unique <| ∀ i j, α i j
instance [∀ i j, Subsingleton (α i j)] : Subsingleton (DMatrix m n α) :=
inferInstanceAs <| Subsingleton <| ∀ i j, α i j
@[simp]
theorem zero_apply [∀ i j, Zero (α i j)] (i j) : (0 : DMatrix m n α) i j = 0 := rfl
@[simp]
theorem neg_apply [∀ i j, Neg (α i j)] (M : DMatrix m n α) (i j) : (-M) i j = -M i j := rfl
@[simp]
theorem add_apply [∀ i j, Add (α i j)] (M N : DMatrix m n α) (i j) : (M + N) i j = M i j + N i j :=
rfl
@[simp]
theorem sub_apply [∀ i j, Sub (α i j)] (M N : DMatrix m n α) (i j) : (M - N) i j = M i j - N i j :=
rfl
@[simp]
theorem map_zero [∀ i j, Zero (α i j)] {β : m → n → Type w} [∀ i j, Zero (β i j)]
{f : ∀ ⦃i j⦄, α i j → β i j} (h : ∀ i j, f (0 : α i j) = 0) :
(0 : DMatrix m n α).map f = 0 := by ext; simp [h]
theorem map_add [∀ i j, AddMonoid (α i j)] {β : m → n → Type w} [∀ i j, AddMonoid (β i j)]
(f : ∀ ⦃i j⦄, α i j →+ β i j) (M N : DMatrix m n α) :
((M + N).map fun i j => @f i j) = (M.map fun i j => @f i j) + N.map fun i j => @f i j := by
ext; simp
theorem map_sub [∀ i j, AddGroup (α i j)] {β : m → n → Type w} [∀ i j, AddGroup (β i j)]
(f : ∀ ⦃i j⦄, α i j →+ β i j) (M N : DMatrix m n α) :
((M - N).map fun i j => @f i j) = (M.map fun i j => @f i j) - N.map fun i j => @f i j := by
ext; simp
instance subsingleton_of_empty_left [IsEmpty m] : Subsingleton (DMatrix m n α) :=
⟨fun M N => by
ext i
exact isEmptyElim i⟩
instance subsingleton_of_empty_right [IsEmpty n] : Subsingleton (DMatrix m n α) :=
⟨fun M N => by ext i j; exact isEmptyElim j⟩
end DMatrix
/-- The `AddMonoidHom` between spaces of dependently typed matrices
induced by an `AddMonoidHom` between their coefficients. -/
def AddMonoidHom.mapDMatrix [∀ i j, AddMonoid (α i j)] {β : m → n → Type w}
[∀ i j, AddMonoid (β i j)] (f : ∀ ⦃i j⦄, α i j →+ β i j) : DMatrix m n α →+ DMatrix m n β where
toFun M := M.map fun i j => @f i j
map_zero' := by simp
map_add' := DMatrix.map_add f
@[simp]
theorem AddMonoidHom.mapDMatrix_apply [∀ i j, AddMonoid (α i j)] {β : m → n → Type w}
[∀ i j, AddMonoid (β i j)] (f : ∀ ⦃i j⦄, α i j →+ β i j) (M : DMatrix m n α) :
AddMonoidHom.mapDMatrix f M = M.map fun i j => @f i j := rfl |
.lake/packages/mathlib/Mathlib/Data/Matrix/Block.lean | import Mathlib.Data.Matrix.Basic
import Mathlib.Data.Matrix.Composition
import Mathlib.LinearAlgebra.Matrix.ConjTranspose
/-!
# Block Matrices
## Main definitions
* `Matrix.fromBlocks`: build a block matrix out of 4 blocks
* `Matrix.toBlocks₁₁`, `Matrix.toBlocks₁₂`, `Matrix.toBlocks₂₁`, `Matrix.toBlocks₂₂`:
extract each of the four blocks from `Matrix.fromBlocks`.
* `Matrix.blockDiagonal`: block diagonal of equally sized blocks. On square blocks, this is a
ring homomorphisms, `Matrix.blockDiagonalRingHom`.
* `Matrix.blockDiag`: extract the blocks from the diagonal of a block diagonal matrix.
* `Matrix.blockDiagonal'`: block diagonal of unequally sized blocks. On square blocks, this is a
ring homomorphisms, `Matrix.blockDiagonal'RingHom`.
* `Matrix.blockDiag'`: extract the blocks from the diagonal of a block diagonal matrix.
-/
variable {l m n o p q : Type*} {m' n' p' : o → Type*}
variable {R : Type*} {S : Type*} {α : Type*} {β : Type*}
open Matrix
namespace Matrix
theorem dotProduct_block [Fintype m] [Fintype n] [Mul α] [AddCommMonoid α] (v w : m ⊕ n → α) :
v ⬝ᵥ w = v ∘ Sum.inl ⬝ᵥ w ∘ Sum.inl + v ∘ Sum.inr ⬝ᵥ w ∘ Sum.inr :=
Fintype.sum_sum_type _
section BlockMatrices
/-- We can form a single large matrix by flattening smaller 'block' matrices of compatible
dimensions. -/
@[pp_nodot]
def fromBlocks (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α) (D : Matrix o m α) :
Matrix (n ⊕ o) (l ⊕ m) α :=
of <| Sum.elim (fun i => Sum.elim (A i) (B i)) (fun j => Sum.elim (C j) (D j))
@[simp]
theorem fromBlocks_apply₁₁ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) (i : n) (j : l) : fromBlocks A B C D (Sum.inl i) (Sum.inl j) = A i j :=
rfl
@[simp]
theorem fromBlocks_apply₁₂ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) (i : n) (j : m) : fromBlocks A B C D (Sum.inl i) (Sum.inr j) = B i j :=
rfl
@[simp]
theorem fromBlocks_apply₂₁ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) (i : o) (j : l) : fromBlocks A B C D (Sum.inr i) (Sum.inl j) = C i j :=
rfl
@[simp]
theorem fromBlocks_apply₂₂ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) (i : o) (j : m) : fromBlocks A B C D (Sum.inr i) (Sum.inr j) = D i j :=
rfl
/-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding
"top left" submatrix. -/
def toBlocks₁₁ (M : Matrix (n ⊕ o) (l ⊕ m) α) : Matrix n l α :=
of fun i j => M (Sum.inl i) (Sum.inl j)
/-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding
"top right" submatrix. -/
def toBlocks₁₂ (M : Matrix (n ⊕ o) (l ⊕ m) α) : Matrix n m α :=
of fun i j => M (Sum.inl i) (Sum.inr j)
/-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding
"bottom left" submatrix. -/
def toBlocks₂₁ (M : Matrix (n ⊕ o) (l ⊕ m) α) : Matrix o l α :=
of fun i j => M (Sum.inr i) (Sum.inl j)
/-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding
"bottom right" submatrix. -/
def toBlocks₂₂ (M : Matrix (n ⊕ o) (l ⊕ m) α) : Matrix o m α :=
of fun i j => M (Sum.inr i) (Sum.inr j)
theorem fromBlocks_toBlocks (M : Matrix (n ⊕ o) (l ⊕ m) α) :
fromBlocks M.toBlocks₁₁ M.toBlocks₁₂ M.toBlocks₂₁ M.toBlocks₂₂ = M := by
ext i j
rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> rfl
@[simp]
theorem toBlocks_fromBlocks₁₁ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) : (fromBlocks A B C D).toBlocks₁₁ = A :=
rfl
@[simp]
theorem toBlocks_fromBlocks₁₂ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) : (fromBlocks A B C D).toBlocks₁₂ = B :=
rfl
@[simp]
theorem toBlocks_fromBlocks₂₁ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) : (fromBlocks A B C D).toBlocks₂₁ = C :=
rfl
@[simp]
theorem toBlocks_fromBlocks₂₂ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) : (fromBlocks A B C D).toBlocks₂₂ = D :=
rfl
/-- Two block matrices are equal if their blocks are equal. -/
theorem ext_iff_blocks {A B : Matrix (n ⊕ o) (l ⊕ m) α} :
A = B ↔
A.toBlocks₁₁ = B.toBlocks₁₁ ∧
A.toBlocks₁₂ = B.toBlocks₁₂ ∧ A.toBlocks₂₁ = B.toBlocks₂₁ ∧ A.toBlocks₂₂ = B.toBlocks₂₂ :=
⟨fun h => h ▸ ⟨rfl, rfl, rfl, rfl⟩, fun ⟨h₁₁, h₁₂, h₂₁, h₂₂⟩ => by
rw [← fromBlocks_toBlocks A, ← fromBlocks_toBlocks B, h₁₁, h₁₂, h₂₁, h₂₂]⟩
@[simp]
theorem fromBlocks_inj {A : Matrix n l α} {B : Matrix n m α} {C : Matrix o l α} {D : Matrix o m α}
{A' : Matrix n l α} {B' : Matrix n m α} {C' : Matrix o l α} {D' : Matrix o m α} :
fromBlocks A B C D = fromBlocks A' B' C' D' ↔ A = A' ∧ B = B' ∧ C = C' ∧ D = D' :=
ext_iff_blocks
theorem fromBlocks_map (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α) (D : Matrix o m α)
(f : α → β) : (fromBlocks A B C D).map f =
fromBlocks (A.map f) (B.map f) (C.map f) (D.map f) := by
ext i j; rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> simp [fromBlocks]
theorem fromBlocks_transpose (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) : (fromBlocks A B C D)ᵀ = fromBlocks Aᵀ Cᵀ Bᵀ Dᵀ := by
ext i j
rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> simp [fromBlocks]
theorem fromBlocks_conjTranspose [Star α] (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) : (fromBlocks A B C D)ᴴ = fromBlocks Aᴴ Cᴴ Bᴴ Dᴴ := by
simp only [conjTranspose, fromBlocks_transpose, fromBlocks_map]
@[simp]
theorem fromBlocks_submatrix_sum_swap_left (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) (f : p → l ⊕ m) :
(fromBlocks A B C D).submatrix Sum.swap f = (fromBlocks C D A B).submatrix id f := by
ext i j
cases i <;> dsimp <;> cases f j <;> rfl
@[simp]
theorem fromBlocks_submatrix_sum_swap_right (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) (f : p → n ⊕ o) :
(fromBlocks A B C D).submatrix f Sum.swap = (fromBlocks B A D C).submatrix f id := by
ext i j
cases j <;> dsimp <;> cases f i <;> rfl
theorem fromBlocks_submatrix_sum_swap_sum_swap {l m n o α : Type*} (A : Matrix n l α)
(B : Matrix n m α) (C : Matrix o l α) (D : Matrix o m α) :
(fromBlocks A B C D).submatrix Sum.swap Sum.swap = fromBlocks D C B A := by simp
/-- A 2x2 block matrix is block diagonal if the blocks outside of the diagonal vanish -/
def IsTwoBlockDiagonal [Zero α] (A : Matrix (n ⊕ o) (l ⊕ m) α) : Prop :=
toBlocks₁₂ A = 0 ∧ toBlocks₂₁ A = 0
/-- Let `p` pick out certain rows and `q` pick out certain columns of a matrix `M`. Then
`toBlock M p q` is the corresponding block matrix. -/
def toBlock (M : Matrix m n α) (p : m → Prop) (q : n → Prop) : Matrix { a // p a } { a // q a } α :=
M.submatrix (↑) (↑)
@[simp]
theorem toBlock_apply (M : Matrix m n α) (p : m → Prop) (q : n → Prop) (i : { a // p a })
(j : { a // q a }) : toBlock M p q i j = M ↑i ↑j :=
rfl
/-- Let `p` pick out certain rows and columns of a square matrix `M`. Then
`toSquareBlockProp M p` is the corresponding block matrix. -/
def toSquareBlockProp (M : Matrix m m α) (p : m → Prop) : Matrix { a // p a } { a // p a } α :=
toBlock M _ _
theorem toSquareBlockProp_def (M : Matrix m m α) (p : m → Prop) :
toSquareBlockProp M p = of (fun i j : { a // p a } => M ↑i ↑j) :=
rfl
/-- Let `b` map rows and columns of a square matrix `M` to blocks. Then
`toSquareBlock M b k` is the block `k` matrix. -/
def toSquareBlock (M : Matrix m m α) (b : m → β) (k : β) :
Matrix { a // b a = k } { a // b a = k } α :=
toSquareBlockProp M _
theorem toSquareBlock_def (M : Matrix m m α) (b : m → β) (k : β) :
toSquareBlock M b k = of (fun i j : { a // b a = k } => M ↑i ↑j) :=
rfl
theorem fromBlocks_smul [SMul R α] (x : R) (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) : x • fromBlocks A B C D = fromBlocks (x • A) (x • B) (x • C) (x • D) := by
ext i j; rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> simp [fromBlocks]
theorem fromBlocks_neg [Neg R] (A : Matrix n l R) (B : Matrix n m R) (C : Matrix o l R)
(D : Matrix o m R) : -fromBlocks A B C D = fromBlocks (-A) (-B) (-C) (-D) := by
ext i j
cases i <;> cases j <;> simp [fromBlocks]
@[simp]
theorem fromBlocks_zero [Zero α] : fromBlocks (0 : Matrix n l α) 0 0 (0 : Matrix o m α) = 0 := by
ext i j
rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> rfl
theorem fromBlocks_add [Add α] (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) (A' : Matrix n l α) (B' : Matrix n m α) (C' : Matrix o l α)
(D' : Matrix o m α) : fromBlocks A B C D + fromBlocks A' B' C' D' =
fromBlocks (A + A') (B + B') (C + C') (D + D') := by
ext i j; rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> rfl
theorem fromBlocks_multiply [Fintype l] [Fintype m] [NonUnitalNonAssocSemiring α] (A : Matrix n l α)
(B : Matrix n m α) (C : Matrix o l α) (D : Matrix o m α) (A' : Matrix l p α) (B' : Matrix l q α)
(C' : Matrix m p α) (D' : Matrix m q α) :
fromBlocks A B C D * fromBlocks A' B' C' D' =
fromBlocks (A * A' + B * C') (A * B' + B * D') (C * A' + D * C') (C * B' + D * D') := by
ext i j
rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> simp only [fromBlocks, mul_apply, of_apply,
Sum.elim_inr, Fintype.sum_sum_type, Sum.elim_inl, add_apply]
theorem fromBlocks_diagonal_pow [Semiring α] [Fintype n] [Fintype m] [DecidableEq n] [DecidableEq m]
(A : Matrix n n α) (D : Matrix m m α) (k : ℕ) :
(fromBlocks A 0 0 D) ^ k = fromBlocks (A ^ k) 0 0 (D ^ k) := by
induction k with
| zero => ext (i | i) (j | j) <;> simp [one_apply]
| succ n ih =>
simp [ih, pow_succ, fromBlocks_multiply]
theorem fromBlocks_mulVec [Fintype l] [Fintype m] [NonUnitalNonAssocSemiring α] (A : Matrix n l α)
(B : Matrix n m α) (C : Matrix o l α) (D : Matrix o m α) (x : l ⊕ m → α) :
(fromBlocks A B C D) *ᵥ x =
Sum.elim (A *ᵥ (x ∘ Sum.inl) + B *ᵥ (x ∘ Sum.inr))
(C *ᵥ (x ∘ Sum.inl) + D *ᵥ (x ∘ Sum.inr)) := by
ext i
cases i <;> simp [mulVec, dotProduct]
theorem vecMul_fromBlocks [Fintype n] [Fintype o] [NonUnitalNonAssocSemiring α] (A : Matrix n l α)
(B : Matrix n m α) (C : Matrix o l α) (D : Matrix o m α) (x : n ⊕ o → α) :
x ᵥ* fromBlocks A B C D =
Sum.elim ((x ∘ Sum.inl) ᵥ* A + (x ∘ Sum.inr) ᵥ* C)
((x ∘ Sum.inl) ᵥ* B + (x ∘ Sum.inr) ᵥ* D) := by
ext i
cases i <;> simp [vecMul, dotProduct]
variable [DecidableEq l] [DecidableEq m]
section Zero
variable [Zero α]
theorem toBlock_diagonal_self (d : m → α) (p : m → Prop) :
Matrix.toBlock (diagonal d) p p = diagonal fun i : Subtype p => d ↑i := by
ext i j
by_cases h : i = j
· simp [h]
· simp [h, Subtype.val_injective.ne h]
theorem toBlock_diagonal_disjoint (d : m → α) {p q : m → Prop} (hpq : Disjoint p q) :
Matrix.toBlock (diagonal d) p q = 0 := by
ext ⟨i, hi⟩ ⟨j, hj⟩
have : i ≠ j := fun heq => hpq.le_bot i ⟨hi, heq.symm ▸ hj⟩
simp [diagonal_apply_ne d this]
@[simp]
theorem fromBlocks_diagonal (d₁ : l → α) (d₂ : m → α) :
fromBlocks (diagonal d₁) 0 0 (diagonal d₂) = diagonal (Sum.elim d₁ d₂) := by
ext i j
rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> simp [diagonal]
@[simp]
lemma toBlocks₁₁_diagonal (v : l ⊕ m → α) :
toBlocks₁₁ (diagonal v) = diagonal (fun i => v (Sum.inl i)) := by
unfold toBlocks₁₁
funext i j
simp only [Sum.inl.injEq, of_apply, diagonal_apply]
@[simp]
lemma toBlocks₂₂_diagonal (v : l ⊕ m → α) :
toBlocks₂₂ (diagonal v) = diagonal (fun i => v (Sum.inr i)) := by
unfold toBlocks₂₂
funext i j
simp only [Sum.inr.injEq, of_apply, diagonal_apply]
@[simp]
lemma toBlocks₁₂_diagonal (v : l ⊕ m → α) : toBlocks₁₂ (diagonal v) = 0 := rfl
@[simp]
lemma toBlocks₂₁_diagonal (v : l ⊕ m → α) : toBlocks₂₁ (diagonal v) = 0 := rfl
end Zero
section HasZeroHasOne
variable [Zero α] [One α]
@[simp]
theorem fromBlocks_one : fromBlocks (1 : Matrix l l α) 0 0 (1 : Matrix m m α) = 1 := by
ext i j
rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> simp [one_apply]
@[simp]
theorem toBlock_one_self (p : m → Prop) : Matrix.toBlock (1 : Matrix m m α) p p = 1 :=
toBlock_diagonal_self _ p
theorem toBlock_one_disjoint {p q : m → Prop} (hpq : Disjoint p q) :
Matrix.toBlock (1 : Matrix m m α) p q = 0 :=
toBlock_diagonal_disjoint _ hpq
end HasZeroHasOne
end BlockMatrices
section BlockDiagonal
variable [DecidableEq o]
section Zero
variable [Zero α] [Zero β]
/-- `Matrix.blockDiagonal M` turns a homogeneously-indexed collection of matrices
`M : o → Matrix m n α'` into an `m × o`-by-`n × o` block matrix which has the entries of `M` along
the diagonal and zero elsewhere.
See also `Matrix.blockDiagonal'` if the matrices may not have the same size everywhere.
-/
def blockDiagonal (M : o → Matrix m n α) : Matrix (m × o) (n × o) α :=
of <| (fun ⟨i, k⟩ ⟨j, k'⟩ => if k = k' then M k i j else 0 : m × o → n × o → α)
-- TODO: set as an equation lemma for `blockDiagonal`, see https://github.com/leanprover-community/mathlib4/pull/3024
theorem blockDiagonal_apply' (M : o → Matrix m n α) (i k j k') :
blockDiagonal M ⟨i, k⟩ ⟨j, k'⟩ = if k = k' then M k i j else 0 :=
rfl
theorem blockDiagonal_apply (M : o → Matrix m n α) (ik jk) :
blockDiagonal M ik jk = if ik.2 = jk.2 then M ik.2 ik.1 jk.1 else 0 := rfl
@[simp]
theorem blockDiagonal_apply_eq (M : o → Matrix m n α) (i j k) :
blockDiagonal M (i, k) (j, k) = M k i j :=
if_pos rfl
theorem blockDiagonal_apply_ne (M : o → Matrix m n α) (i j) {k k'} (h : k ≠ k') :
blockDiagonal M (i, k) (j, k') = 0 :=
if_neg h
theorem blockDiagonal_map (M : o → Matrix m n α) (f : α → β) (hf : f 0 = 0) :
(blockDiagonal M).map f = blockDiagonal fun k => (M k).map f := by
ext
simp only [map_apply, blockDiagonal_apply]
rw [apply_ite f, hf]
@[simp]
theorem blockDiagonal_transpose (M : o → Matrix m n α) :
(blockDiagonal M)ᵀ = blockDiagonal fun k => (M k)ᵀ := by
ext
simp only [transpose_apply, blockDiagonal_apply, eq_comm]
split_ifs with h
· rw [h]
· rfl
@[simp]
theorem blockDiagonal_conjTranspose {α : Type*} [AddMonoid α] [StarAddMonoid α]
(M : o → Matrix m n α) : (blockDiagonal M)ᴴ = blockDiagonal fun k => (M k)ᴴ := by
simp only [conjTranspose, blockDiagonal_transpose]
rw [blockDiagonal_map _ star (star_zero α)]
@[simp]
theorem blockDiagonal_zero : blockDiagonal (0 : o → Matrix m n α) = 0 := by
ext
simp [blockDiagonal_apply]
@[simp]
theorem blockDiagonal_diagonal [DecidableEq m] (d : o → m → α) :
(blockDiagonal fun k => diagonal (d k)) = diagonal fun ik => d ik.2 ik.1 := by
ext ⟨i, k⟩ ⟨j, k'⟩
simp only [blockDiagonal_apply, diagonal_apply, Prod.mk_inj, ← ite_and]
congr 1
rw [and_comm]
@[simp]
theorem blockDiagonal_one [DecidableEq m] [One α] : blockDiagonal (1 : o → Matrix m m α) = 1 :=
show (blockDiagonal fun _ : o => diagonal fun _ : m => (1 : α)) = diagonal fun _ => 1 by
rw [blockDiagonal_diagonal]
end Zero
@[simp]
theorem blockDiagonal_add [AddZeroClass α] (M N : o → Matrix m n α) :
blockDiagonal (M + N) = blockDiagonal M + blockDiagonal N := by
ext
simp only [blockDiagonal_apply, Pi.add_apply, add_apply]
split_ifs <;> simp
section
variable (o m n α)
/-- `Matrix.blockDiagonal` as an `AddMonoidHom`. -/
@[simps]
def blockDiagonalAddMonoidHom [AddZeroClass α] :
(o → Matrix m n α) →+ Matrix (m × o) (n × o) α where
toFun := blockDiagonal
map_zero' := blockDiagonal_zero
map_add' := blockDiagonal_add
end
@[simp]
theorem blockDiagonal_neg [AddGroup α] (M : o → Matrix m n α) :
blockDiagonal (-M) = -blockDiagonal M :=
map_neg (blockDiagonalAddMonoidHom m n o α) M
@[simp]
theorem blockDiagonal_sub [AddGroup α] (M N : o → Matrix m n α) :
blockDiagonal (M - N) = blockDiagonal M - blockDiagonal N :=
map_sub (blockDiagonalAddMonoidHom m n o α) M N
@[simp]
theorem blockDiagonal_mul [Fintype n] [Fintype o] [NonUnitalNonAssocSemiring α]
(M : o → Matrix m n α) (N : o → Matrix n p α) :
(blockDiagonal fun k => M k * N k) = blockDiagonal M * blockDiagonal N := by
ext ⟨i, k⟩ ⟨j, k'⟩
simp only [blockDiagonal_apply, mul_apply, ← Finset.univ_product_univ, Finset.sum_product]
split_ifs with h <;> simp [h]
section
variable (α m o)
/-- `Matrix.blockDiagonal` as a `RingHom`. -/
@[simps]
def blockDiagonalRingHom [DecidableEq m] [Fintype o] [Fintype m] [NonAssocSemiring α] :
(o → Matrix m m α) →+* Matrix (m × o) (m × o) α :=
{ blockDiagonalAddMonoidHom m m o α with
toFun := blockDiagonal
map_one' := blockDiagonal_one
map_mul' := blockDiagonal_mul }
end
@[simp]
theorem blockDiagonal_pow [DecidableEq m] [Fintype o] [Fintype m] [Semiring α]
(M : o → Matrix m m α) (n : ℕ) : blockDiagonal (M ^ n) = blockDiagonal M ^ n :=
map_pow (blockDiagonalRingHom m o α) M n
@[simp]
theorem blockDiagonal_smul {R : Type*} [Zero α] [SMulZeroClass R α] (x : R)
(M : o → Matrix m n α) : blockDiagonal (x • M) = x • blockDiagonal M := by
ext
simp only [blockDiagonal_apply, Pi.smul_apply, smul_apply]
split_ifs <;> simp
end BlockDiagonal
section BlockDiag
/-- Extract a block from the diagonal of a block diagonal matrix.
This is the block form of `Matrix.diag`, and the left-inverse of `Matrix.blockDiagonal`. -/
def blockDiag (M : Matrix (m × o) (n × o) α) (k : o) : Matrix m n α :=
of fun i j => M (i, k) (j, k)
-- TODO: set as an equation lemma for `blockDiag`, see https://github.com/leanprover-community/mathlib4/pull/3024
theorem blockDiag_apply (M : Matrix (m × o) (n × o) α) (k : o) (i j) :
blockDiag M k i j = M (i, k) (j, k) :=
rfl
theorem blockDiag_map (M : Matrix (m × o) (n × o) α) (f : α → β) :
blockDiag (M.map f) = fun k => (blockDiag M k).map f :=
rfl
@[simp]
theorem blockDiag_transpose (M : Matrix (m × o) (n × o) α) (k : o) :
blockDiag Mᵀ k = (blockDiag M k)ᵀ :=
ext fun _ _ => rfl
@[simp]
theorem blockDiag_conjTranspose {α : Type*} [Star α]
(M : Matrix (m × o) (n × o) α) (k : o) : blockDiag Mᴴ k = (blockDiag M k)ᴴ :=
ext fun _ _ => rfl
section Zero
variable [Zero α] [Zero β]
@[simp]
theorem blockDiag_zero : blockDiag (0 : Matrix (m × o) (n × o) α) = 0 :=
rfl
@[simp]
theorem blockDiag_diagonal [DecidableEq o] [DecidableEq m] (d : m × o → α) (k : o) :
blockDiag (diagonal d) k = diagonal fun i => d (i, k) :=
ext fun i j => by
obtain rfl | hij := Decidable.eq_or_ne i j
· rw [blockDiag_apply, diagonal_apply_eq, diagonal_apply_eq]
· rw [blockDiag_apply, diagonal_apply_ne _ hij, diagonal_apply_ne _ (mt _ hij)]
exact Prod.fst_eq_iff.mpr
@[simp]
theorem blockDiag_blockDiagonal [DecidableEq o] (M : o → Matrix m n α) :
blockDiag (blockDiagonal M) = M :=
funext fun _ => ext fun i j => blockDiagonal_apply_eq M i j _
theorem blockDiagonal_injective [DecidableEq o] :
Function.Injective (blockDiagonal : (o → Matrix m n α) → Matrix _ _ α) :=
Function.LeftInverse.injective blockDiag_blockDiagonal
@[simp]
theorem blockDiagonal_inj [DecidableEq o] {M N : o → Matrix m n α} :
blockDiagonal M = blockDiagonal N ↔ M = N :=
blockDiagonal_injective.eq_iff
@[simp]
theorem blockDiag_one [DecidableEq o] [DecidableEq m] [One α] :
blockDiag (1 : Matrix (m × o) (m × o) α) = 1 :=
funext <| blockDiag_diagonal _
end Zero
@[simp]
theorem blockDiag_add [Add α] (M N : Matrix (m × o) (n × o) α) :
blockDiag (M + N) = blockDiag M + blockDiag N :=
rfl
section
variable (o m n α)
/-- `Matrix.blockDiag` as an `AddMonoidHom`. -/
@[simps]
def blockDiagAddMonoidHom [AddZeroClass α] : Matrix (m × o) (n × o) α →+ o → Matrix m n α where
toFun := blockDiag
map_zero' := blockDiag_zero
map_add' := blockDiag_add
end
@[simp]
theorem blockDiag_neg [AddGroup α] (M : Matrix (m × o) (n × o) α) : blockDiag (-M) = -blockDiag M :=
map_neg (blockDiagAddMonoidHom m n o α) M
@[simp]
theorem blockDiag_sub [AddGroup α] (M N : Matrix (m × o) (n × o) α) :
blockDiag (M - N) = blockDiag M - blockDiag N :=
map_sub (blockDiagAddMonoidHom m n o α) M N
@[simp]
theorem blockDiag_smul {R : Type*} [SMul R α] (x : R)
(M : Matrix (m × o) (n × o) α) : blockDiag (x • M) = x • blockDiag M :=
rfl
end BlockDiag
section BlockDiagonal'
variable [DecidableEq o]
section Zero
variable [Zero α] [Zero β]
/-- `Matrix.blockDiagonal' M` turns `M : Π i, Matrix (m i) (n i) α` into a
`Σ i, m i`-by-`Σ i, n i` block matrix which has the entries of `M` along the diagonal
and zero elsewhere.
This is the dependently-typed version of `Matrix.blockDiagonal`. -/
def blockDiagonal' (M : ∀ i, Matrix (m' i) (n' i) α) : Matrix (Σ i, m' i) (Σ i, n' i) α :=
of <|
(fun ⟨k, i⟩ ⟨k', j⟩ => if h : k = k' then M k i (cast (congr_arg n' h.symm) j) else 0 :
(Σ i, m' i) → (Σ i, n' i) → α)
-- TODO: set as an equation lemma for `blockDiagonal'`, see https://github.com/leanprover-community/mathlib4/pull/3024
theorem blockDiagonal'_apply' (M : ∀ i, Matrix (m' i) (n' i) α) (k i k' j) :
blockDiagonal' M ⟨k, i⟩ ⟨k', j⟩ =
if h : k = k' then M k i (cast (congr_arg n' h.symm) j) else 0 :=
rfl
theorem blockDiagonal'_eq_blockDiagonal (M : o → Matrix m n α) {k k'} (i j) :
blockDiagonal M (i, k) (j, k') = blockDiagonal' M ⟨k, i⟩ ⟨k', j⟩ :=
rfl
theorem blockDiagonal'_submatrix_eq_blockDiagonal (M : o → Matrix m n α) :
(blockDiagonal' M).submatrix (Prod.toSigma ∘ Prod.swap) (Prod.toSigma ∘ Prod.swap) =
blockDiagonal M :=
Matrix.ext fun ⟨_, _⟩ ⟨_, _⟩ => rfl
theorem blockDiagonal'_apply (M : ∀ i, Matrix (m' i) (n' i) α) (ik jk) :
blockDiagonal' M ik jk =
if h : ik.1 = jk.1 then M ik.1 ik.2 (cast (congr_arg n' h.symm) jk.2) else 0 := rfl
@[simp]
theorem blockDiagonal'_apply_eq (M : ∀ i, Matrix (m' i) (n' i) α) (k i j) :
blockDiagonal' M ⟨k, i⟩ ⟨k, j⟩ = M k i j :=
dif_pos rfl
theorem blockDiagonal'_apply_ne (M : ∀ i, Matrix (m' i) (n' i) α) {k k'} (i j) (h : k ≠ k') :
blockDiagonal' M ⟨k, i⟩ ⟨k', j⟩ = 0 :=
dif_neg h
theorem blockDiagonal'_map (M : ∀ i, Matrix (m' i) (n' i) α) (f : α → β) (hf : f 0 = 0) :
(blockDiagonal' M).map f = blockDiagonal' fun k => (M k).map f := by
ext
simp only [map_apply, blockDiagonal'_apply]
rw [apply_dite f, hf]
@[simp]
theorem blockDiagonal'_transpose (M : ∀ i, Matrix (m' i) (n' i) α) :
(blockDiagonal' M)ᵀ = blockDiagonal' fun k => (M k)ᵀ := by
ext ⟨ii, ix⟩ ⟨ji, jx⟩
simp only [transpose_apply, blockDiagonal'_apply]
split_ifs <;> grind
@[simp]
theorem blockDiagonal'_conjTranspose {α} [AddMonoid α] [StarAddMonoid α]
(M : ∀ i, Matrix (m' i) (n' i) α) : (blockDiagonal' M)ᴴ = blockDiagonal' fun k => (M k)ᴴ := by
simp only [conjTranspose, blockDiagonal'_transpose]
exact blockDiagonal'_map _ star (star_zero α)
@[simp]
theorem blockDiagonal'_zero : blockDiagonal' (0 : ∀ i, Matrix (m' i) (n' i) α) = 0 := by
ext
simp [blockDiagonal'_apply]
@[simp]
theorem blockDiagonal'_diagonal [∀ i, DecidableEq (m' i)] (d : ∀ i, m' i → α) :
(blockDiagonal' fun k => diagonal (d k)) = diagonal fun ik => d ik.1 ik.2 := by
ext ⟨i, k⟩ ⟨j, k'⟩
simp only [blockDiagonal'_apply, diagonal]
obtain rfl | hij := Decidable.eq_or_ne i j
· simp
· simp [hij]
@[simp]
theorem blockDiagonal'_one [∀ i, DecidableEq (m' i)] [One α] :
blockDiagonal' (1 : ∀ i, Matrix (m' i) (m' i) α) = 1 :=
show (blockDiagonal' fun i : o => diagonal fun _ : m' i => (1 : α)) = diagonal fun _ => 1 by
rw [blockDiagonal'_diagonal]
end Zero
@[simp]
theorem blockDiagonal'_add [AddZeroClass α] (M N : ∀ i, Matrix (m' i) (n' i) α) :
blockDiagonal' (M + N) = blockDiagonal' M + blockDiagonal' N := by
ext
simp only [blockDiagonal'_apply, Pi.add_apply, add_apply]
split_ifs <;> simp
section
variable (m' n' α)
/-- `Matrix.blockDiagonal'` as an `AddMonoidHom`. -/
@[simps]
def blockDiagonal'AddMonoidHom [AddZeroClass α] :
(∀ i, Matrix (m' i) (n' i) α) →+ Matrix (Σ i, m' i) (Σ i, n' i) α where
toFun := blockDiagonal'
map_zero' := blockDiagonal'_zero
map_add' := blockDiagonal'_add
end
@[simp]
theorem blockDiagonal'_neg [AddGroup α] (M : ∀ i, Matrix (m' i) (n' i) α) :
blockDiagonal' (-M) = -blockDiagonal' M :=
map_neg (blockDiagonal'AddMonoidHom m' n' α) M
@[simp]
theorem blockDiagonal'_sub [AddGroup α] (M N : ∀ i, Matrix (m' i) (n' i) α) :
blockDiagonal' (M - N) = blockDiagonal' M - blockDiagonal' N :=
map_sub (blockDiagonal'AddMonoidHom m' n' α) M N
@[simp]
theorem blockDiagonal'_mul [NonUnitalNonAssocSemiring α] [∀ i, Fintype (n' i)] [Fintype o]
(M : ∀ i, Matrix (m' i) (n' i) α) (N : ∀ i, Matrix (n' i) (p' i) α) :
(blockDiagonal' fun k => M k * N k) = blockDiagonal' M * blockDiagonal' N := by
ext ⟨k, i⟩ ⟨k', j⟩
simp only [blockDiagonal'_apply, mul_apply, ← Finset.univ_sigma_univ, Finset.sum_sigma]
rw [Fintype.sum_eq_single k]
· simp only [dif_pos]
split_ifs <;> simp
· intro j' hj'
exact Finset.sum_eq_zero fun _ _ => by rw [dif_neg hj'.symm, zero_mul]
section
variable (α m')
/-- `Matrix.blockDiagonal'` as a `RingHom`. -/
@[simps]
def blockDiagonal'RingHom [∀ i, DecidableEq (m' i)] [Fintype o] [∀ i, Fintype (m' i)]
[NonAssocSemiring α] : (∀ i, Matrix (m' i) (m' i) α) →+* Matrix (Σ i, m' i) (Σ i, m' i) α :=
{ blockDiagonal'AddMonoidHom m' m' α with
toFun := blockDiagonal'
map_one' := blockDiagonal'_one
map_mul' := blockDiagonal'_mul }
end
@[simp]
theorem blockDiagonal'_pow [∀ i, DecidableEq (m' i)] [Fintype o] [∀ i, Fintype (m' i)] [Semiring α]
(M : ∀ i, Matrix (m' i) (m' i) α) (n : ℕ) : blockDiagonal' (M ^ n) = blockDiagonal' M ^ n :=
map_pow (blockDiagonal'RingHom m' α) M n
@[simp]
theorem blockDiagonal'_smul {R : Type*} [Zero α] [SMulZeroClass R α] (x : R)
(M : ∀ i, Matrix (m' i) (n' i) α) : blockDiagonal' (x • M) = x • blockDiagonal' M := by
ext
simp only [blockDiagonal'_apply, Pi.smul_apply, smul_apply]
split_ifs <;> simp
end BlockDiagonal'
section BlockDiag'
/-- Extract a block from the diagonal of a block diagonal matrix.
This is the block form of `Matrix.diag`, and the left-inverse of `Matrix.blockDiagonal'`. -/
def blockDiag' (M : Matrix (Σ i, m' i) (Σ i, n' i) α) (k : o) : Matrix (m' k) (n' k) α :=
of fun i j => M ⟨k, i⟩ ⟨k, j⟩
-- TODO: set as an equation lemma for `blockDiag'`, see https://github.com/leanprover-community/mathlib4/pull/3024
theorem blockDiag'_apply (M : Matrix (Σ i, m' i) (Σ i, n' i) α) (k : o) (i j) :
blockDiag' M k i j = M ⟨k, i⟩ ⟨k, j⟩ :=
rfl
theorem blockDiag'_map (M : Matrix (Σ i, m' i) (Σ i, n' i) α) (f : α → β) :
blockDiag' (M.map f) = fun k => (blockDiag' M k).map f :=
rfl
@[simp]
theorem blockDiag'_transpose (M : Matrix (Σ i, m' i) (Σ i, n' i) α) (k : o) :
blockDiag' Mᵀ k = (blockDiag' M k)ᵀ :=
ext fun _ _ => rfl
@[simp]
theorem blockDiag'_conjTranspose {α : Type*} [Star α]
(M : Matrix (Σ i, m' i) (Σ i, n' i) α) (k : o) : blockDiag' Mᴴ k = (blockDiag' M k)ᴴ :=
ext fun _ _ => rfl
section Zero
variable [Zero α] [Zero β]
@[simp]
theorem blockDiag'_zero : blockDiag' (0 : Matrix (Σ i, m' i) (Σ i, n' i) α) = 0 :=
rfl
@[simp]
theorem blockDiag'_diagonal
[DecidableEq o] [∀ i, DecidableEq (m' i)] (d : (Σ i, m' i) → α) (k : o) :
blockDiag' (diagonal d) k = diagonal fun i => d ⟨k, i⟩ :=
ext fun i j => by
obtain rfl | hij := Decidable.eq_or_ne i j
· rw [blockDiag'_apply, diagonal_apply_eq, diagonal_apply_eq]
· rw [blockDiag'_apply, diagonal_apply_ne _ hij, diagonal_apply_ne _ (mt (fun h => ?_) hij)]
cases h
rfl
@[simp]
theorem blockDiag'_blockDiagonal' [DecidableEq o] (M : ∀ i, Matrix (m' i) (n' i) α) :
blockDiag' (blockDiagonal' M) = M :=
funext fun _ => ext fun _ _ => blockDiagonal'_apply_eq M _ _ _
theorem blockDiagonal'_injective [DecidableEq o] :
Function.Injective (blockDiagonal' : (∀ i, Matrix (m' i) (n' i) α) → Matrix _ _ α) :=
Function.LeftInverse.injective blockDiag'_blockDiagonal'
@[simp]
theorem blockDiagonal'_inj [DecidableEq o] {M N : ∀ i, Matrix (m' i) (n' i) α} :
blockDiagonal' M = blockDiagonal' N ↔ M = N :=
blockDiagonal'_injective.eq_iff
@[simp]
theorem blockDiag'_one [DecidableEq o] [∀ i, DecidableEq (m' i)] [One α] :
blockDiag' (1 : Matrix (Σ i, m' i) (Σ i, m' i) α) = 1 :=
funext <| blockDiag'_diagonal _
end Zero
@[simp]
theorem blockDiag'_add [Add α] (M N : Matrix (Σ i, m' i) (Σ i, n' i) α) :
blockDiag' (M + N) = blockDiag' M + blockDiag' N :=
rfl
section
variable (m' n' α)
/-- `Matrix.blockDiag'` as an `AddMonoidHom`. -/
@[simps]
def blockDiag'AddMonoidHom [AddZeroClass α] :
Matrix (Σ i, m' i) (Σ i, n' i) α →+ ∀ i, Matrix (m' i) (n' i) α where
toFun := blockDiag'
map_zero' := blockDiag'_zero
map_add' := blockDiag'_add
end
@[simp]
theorem blockDiag'_neg [AddGroup α] (M : Matrix (Σ i, m' i) (Σ i, n' i) α) :
blockDiag' (-M) = -blockDiag' M :=
map_neg (blockDiag'AddMonoidHom m' n' α) M
@[simp]
theorem blockDiag'_sub [AddGroup α] (M N : Matrix (Σ i, m' i) (Σ i, n' i) α) :
blockDiag' (M - N) = blockDiag' M - blockDiag' N :=
map_sub (blockDiag'AddMonoidHom m' n' α) M N
@[simp]
theorem blockDiag'_smul {R : Type*} [SMul R α] (x : R)
(M : Matrix (Σ i, m' i) (Σ i, n' i) α) : blockDiag' (x • M) = x • blockDiag' M :=
rfl
end BlockDiag'
section
variable [CommRing R]
theorem toBlock_mul_eq_mul {m n k : Type*} [Fintype n] (p : m → Prop) (q : k → Prop)
(A : Matrix m n R) (B : Matrix n k R) :
(A * B).toBlock p q = A.toBlock p ⊤ * B.toBlock ⊤ q := by
ext i k
simp only [toBlock_apply, mul_apply]
rw [Finset.sum_subtype]
simp [Pi.top_apply, Prop.top_eq_true]
theorem toBlock_mul_eq_add {m n k : Type*} [Fintype n] (p : m → Prop) (q : n → Prop)
[DecidablePred q] (r : k → Prop) (A : Matrix m n R) (B : Matrix n k R) : (A * B).toBlock p r =
A.toBlock p q * B.toBlock q r + (A.toBlock p fun i => ¬q i) * B.toBlock (fun i => ¬q i) r := by
classical
ext i k
simp only [toBlock_apply, mul_apply]
exact (Fintype.sum_subtype_add_sum_subtype q fun x => A (↑i) x * B x ↑k).symm
end
end Matrix
section Maps
variable {R α β ι : Type*}
lemma Matrix.map_toSquareBlock
(f : α → β) {M : Matrix m m α} {ι} {b : m → ι} {i : ι} :
(M.map f).toSquareBlock b i = (M.toSquareBlock b i).map f :=
submatrix_map _ _ _ _
lemma Matrix.comp_toSquareBlock {b : m → α}
(M : Matrix m m (Matrix n n R)) (a : α) :
letI equiv := Equiv.prodSubtypeFstEquivSubtypeProd.symm
(M.comp m m n n R).toSquareBlock (fun i ↦ b i.1) a =
((M.toSquareBlock b a).comp _ _ n n R).reindex equiv equiv :=
rfl
variable [Zero R] [DecidableEq m]
lemma Matrix.comp_diagonal (d) :
comp m m n n R (diagonal d) =
(blockDiagonal d).reindex (.prodComm ..) (.prodComm ..) := by
ext
simp [diagonal, blockDiagonal, Matrix.ite_apply]
end Maps |
.lake/packages/mathlib/Mathlib/Data/Matrix/Action.lean | import Mathlib.Data.Matrix.Mul
import Mathlib.Algebra.Ring.Opposite
/-!
# Actions by matrices on vectors through `*ᵥ` and `ᵥ*`, cast as `Module`s
This file provides the left- and right- module structures of square matrices on vectors, via
`Matrix.mulVec` and `Matrix.vecMul`.
-/
variable {n R S : Type*}
namespace Matrix
variable [Fintype n] [DecidableEq n] [Semiring R]
/-! ## `*ᵥ` as a left-module -/
section mulVec
instance : Module (Matrix n n R) (n → R) where
smul := mulVec
one_smul := one_mulVec
mul_smul _ _ _ := (mulVec_mulVec _ _ _).symm
zero_smul := zero_mulVec
add_smul := add_mulVec
smul_zero := mulVec_zero
smul_add := mulVec_add
@[simp] lemma smul_eq_mulVec (A : Matrix n n R) (v : n → R) : A • v = A *ᵥ v := rfl
instance [DistribSMul S R] [SMulCommClass R S R] : SMulCommClass (Matrix n n R) S (n → R) where
smul_comm := letI := SMulCommClass.symm; mulVec_smul
instance [DistribSMul S R] [SMulCommClass S R R] : SMulCommClass S (Matrix n n R) (n → R) where
smul_comm s A v := (mulVec_smul A s v).symm
instance [DistribSMul S R] [IsScalarTower S R R] : IsScalarTower S (Matrix n n R) (n → R) where
smul_assoc := smul_mulVec
end mulVec
/-! ## `*ᵥ` as a right-module -/
section vecMul
instance : Module (Matrix n n R)ᵐᵒᵖ (n → R) where
smul A v := v ᵥ* A.unop
one_smul := Matrix.vecMul_one
mul_smul _ _ _ := (vecMul_vecMul _ _ _).symm
zero_smul := vecMul_zero
add_smul _ _ := vecMul_add _ _
smul_zero _ := zero_vecMul _
smul_add _ := add_vecMul _
@[simp] lemma op_smul_eq_vecMul (A : (Matrix n n R)ᵐᵒᵖ) (v : n → R) : A • v = v ᵥ* A.unop := rfl
instance [DistribSMul S R] [IsScalarTower S R R] : SMulCommClass (Matrix n n R)ᵐᵒᵖ S (n → R) where
smul_comm A s v := smul_vecMul s v A.unop
instance [DistribSMul S R] [IsScalarTower S R R] : SMulCommClass S (Matrix n n R)ᵐᵒᵖ (n → R) where
smul_comm s A v := (smul_vecMul s v A.unop).symm
instance [DistribSMul S R] [SMulCommClass S R R] : IsScalarTower S (Matrix n n R)ᵐᵒᵖ (n → R) where
smul_assoc s A v := vecMul_smul v s A.unop
end vecMul
end Matrix |
.lake/packages/mathlib/Mathlib/Data/Matrix/Basis.lean | import Mathlib.Data.Matrix.Basic
/-!
# Matrices with a single non-zero element.
This file provides `Matrix.single`. The matrix `Matrix.single i j c` has `c`
at position `(i, j)`, and zeroes elsewhere.
-/
assert_not_exists Matrix.trace
variable {l m n o : Type*}
variable {R S α β γ : Type*}
namespace Matrix
variable [DecidableEq l] [DecidableEq m] [DecidableEq n] [DecidableEq o]
section Zero
variable [Zero α]
/-- `single i j a` is the matrix with `a` in the `i`-th row, `j`-th column,
and zeroes elsewhere.
-/
def single (i : m) (j : n) (a : α) : Matrix m n α :=
of <| fun i' j' => if i = i' ∧ j = j' then a else 0
@[deprecated (since := "2025-05-05")] alias stdBasisMatrix := single
/-- See also `single_eq_updateRow_zero` and `single_eq_updateCol_zero`. -/
theorem single_eq_of_single_single (i : m) (j : n) (a : α) :
single i j a = Matrix.of (Pi.single i (Pi.single j a)) := by
ext a b
unfold single
by_cases hi : i = a <;> by_cases hj : j = b <;> simp [*]
@[deprecated (since := "2025-05-05")]
alias stdBasisMatrix_eq_of_single_single := single_eq_of_single_single
@[simp]
theorem of_symm_single (i : m) (j : n) (a : α) :
of.symm (single i j a) = Pi.single i (Pi.single j a) :=
congr_arg of.symm <| single_eq_of_single_single i j a
@[deprecated (since := "2025-05-05")] alias of_symm_stdBasisMatrix := of_symm_single
@[simp]
theorem smul_single [SMulZeroClass R α] (r : R) (i : m) (j : n) (a : α) :
r • single i j a = single i j (r • a) := by
unfold single
ext
simp [smul_ite]
@[deprecated (since := "2025-05-05")] alias smul_stdBasisMatrix := smul_single
@[simp]
theorem single_zero (i : m) (j : n) : single i j (0 : α) = 0 := by
unfold single
ext
simp
@[deprecated (since := "2025-05-05")] alias stdBasisMatrix_zero := single_zero
@[simp]
lemma transpose_single (i : m) (j : n) (a : α) :
(single i j a)ᵀ = single j i a := by
aesop (add unsafe unfold single)
@[deprecated (since := "2025-05-05")] alias transpose_stdBasisMatrix := transpose_single
@[simp]
lemma map_single (i : m) (j : n) (a : α) {β : Type*} [Zero β]
{F : Type*} [FunLike F α β] [ZeroHomClass F α β] (f : F) :
(single i j a).map f = single i j (f a) := by
aesop (add unsafe unfold single)
@[deprecated (since := "2025-05-05")] alias map_stdBasisMatrix := map_single
theorem single_mem_matrix {S : Set α} (hS : 0 ∈ S) {i : m} {j : n} {a : α} :
Matrix.single i j a ∈ S.matrix ↔ a ∈ S := by
simp only [Set.mem_matrix, single, of_apply]
conv_lhs => intro _ _; rw [ite_mem]
simp [hS]
end Zero
theorem single_add [AddZeroClass α] (i : m) (j : n) (a b : α) :
single i j (a + b) = single i j a + single i j b := by
ext
simp only [single, of_apply]
split_ifs with h <;> simp [h]
@[deprecated (since := "2025-05-05")] alias stdBasisMatrix_add := single_add
theorem single_mulVec [NonUnitalNonAssocSemiring α] [Fintype m]
(i : n) (j : m) (c : α) (x : m → α) :
mulVec (single i j c) x = Function.update (0 : n → α) i (c * x j) := by
ext i'
simp [single, mulVec, dotProduct]
rcases eq_or_ne i i' with rfl | h
· simp
simp [h, h.symm]
@[deprecated (since := "2025-05-05")] alias mulVec_stdBasisMatrix := single_mulVec
theorem matrix_eq_sum_single [AddCommMonoid α] [Fintype m] [Fintype n] (x : Matrix m n α) :
x = ∑ i : m, ∑ j : n, single i j (x i j) := by
ext i j
rw [← Fintype.sum_prod_type']
simp [single, Matrix.sum_apply, Matrix.of_apply, ← Prod.mk_inj]
@[deprecated (since := "2025-05-05")] alias matrix_eq_sum_stdBasisMatrix := matrix_eq_sum_single
theorem single_eq_single_vecMulVec_single [MulZeroOneClass α] (i : m) (j : n) :
single i j (1 : α) = vecMulVec (Pi.single i 1) (Pi.single j 1) := by
simp [-mul_ite, single, vecMulVec, ite_and, Pi.single_apply, eq_comm]
@[deprecated (since := "2025-05-05")]
alias stdBasisMatrix_eq_single_vecMulVec_single := single_eq_single_vecMulVec_single
-- todo: the old proof used fintypes, I don't know `Finsupp` but this feels generalizable
@[elab_as_elim]
protected theorem induction_on'
[AddCommMonoid α] [Finite m] [Finite n] {P : Matrix m n α → Prop} (M : Matrix m n α)
(h_zero : P 0) (h_add : ∀ p q, P p → P q → P (p + q))
(h_std_basis : ∀ (i : m) (j : n) (x : α), P (single i j x)) : P M := by
cases nonempty_fintype m; cases nonempty_fintype n
rw [matrix_eq_sum_single M, ← Finset.sum_product']
apply Finset.sum_induction _ _ h_add h_zero
· intros
apply h_std_basis
@[elab_as_elim]
protected theorem induction_on
[AddCommMonoid α] [Finite m] [Finite n] [Nonempty m] [Nonempty n]
{P : Matrix m n α → Prop} (M : Matrix m n α) (h_add : ∀ p q, P p → P q → P (p + q))
(h_std_basis : ∀ i j x, P (single i j x)) : P M :=
Matrix.induction_on' M
(by
inhabit m
inhabit n
simpa using h_std_basis default default 0)
h_add h_std_basis
/-- `Matrix.single` as a bundled additive map. -/
@[simps]
def singleAddMonoidHom [AddCommMonoid α] (i : m) (j : n) : α →+ Matrix m n α where
toFun := single i j
map_zero' := single_zero _ _
map_add' _ _ := single_add _ _ _ _
@[deprecated (since := "2025-05-05")] alias stdBasisMatrixAddMonoidHom := singleAddMonoidHom
variable (R)
/-- `Matrix.single` as a bundled linear map. -/
@[simps!]
def singleLinearMap [Semiring R] [AddCommMonoid α] [Module R α] (i : m) (j : n) :
α →ₗ[R] Matrix m n α where
__ := singleAddMonoidHom i j
map_smul' _ _:= smul_single _ _ _ _ |>.symm
@[deprecated (since := "2025-05-05")] alias stdBasisMatrixLinearMap := singleLinearMap
section ext
/-- Additive maps from finite matrices are equal if they agree on the standard basis.
See note [partially-applied ext lemmas]. -/
@[local ext]
theorem ext_addMonoidHom
[Finite m] [Finite n] [AddCommMonoid α] [AddCommMonoid β] ⦃f g : Matrix m n α →+ β⦄
(h : ∀ i j, f.comp (singleAddMonoidHom i j) = g.comp (singleAddMonoidHom i j)) :
f = g := by
cases nonempty_fintype m
cases nonempty_fintype n
ext x
rw [matrix_eq_sum_single x]
simp_rw [map_sum]
congr! 2
exact DFunLike.congr_fun (h _ _) _
/-- Linear maps from finite matrices are equal if they agree on the standard basis.
See note [partially-applied ext lemmas]. -/
@[local ext]
theorem ext_linearMap
[Finite m] [Finite n] [Semiring R] [AddCommMonoid α] [AddCommMonoid β] [Module R α] [Module R β]
⦃f g : Matrix m n α →ₗ[R] β⦄
(h : ∀ i j, f ∘ₗ singleLinearMap R i j = g ∘ₗ singleLinearMap R i j) :
f = g :=
LinearMap.toAddMonoidHom_injective <| ext_addMonoidHom fun i j =>
congrArg LinearMap.toAddMonoidHom <| h i j
section liftLinear
variable {R} (S)
variable [Fintype m] [Fintype n] [Semiring R] [Semiring S] [AddCommMonoid α] [AddCommMonoid β]
variable [Module R α] [Module R β] [Module S β] [SMulCommClass R S β]
/-- Families of linear maps acting on each element are equivalent to linear maps from a matrix.
This can be thought of as the matrix version of `LinearMap.lsum`. -/
def liftLinear : (m → n → α →ₗ[R] β) ≃ₗ[S] (Matrix m n α →ₗ[R] β) :=
LinearEquiv.piCongrRight (fun _ => LinearMap.lsum R _ S) ≪≫ₗ LinearMap.lsum R _ S ≪≫ₗ
LinearEquiv.congrLeft _ _ (ofLinearEquiv _)
-- not `simp` to let `liftLinear_single` fire instead
theorem liftLinear_apply (f : m → n → α →ₗ[R] β) (M : Matrix m n α) :
liftLinear S f M = ∑ i, ∑ j, f i j (M i j) := by
simp [liftLinear, map_sum, LinearEquiv.congrLeft]
@[simp]
theorem liftLinear_single (f : m → n → α →ₗ[R] β) (i : m) (j : n) (a : α) :
liftLinear S f (Matrix.single i j a) = f i j a := by
dsimp [liftLinear, -LinearMap.lsum_apply, LinearEquiv.congrLeft, LinearEquiv.piCongrRight]
simp_rw [of_symm_single, LinearMap.lsum_piSingle]
@[deprecated (since := "2025-08-13")] alias liftLinear_piSingle := liftLinear_single
@[simp]
theorem liftLinear_comp_singleLinearMap (f : m → n → α →ₗ[R] β) (i : m) (j : n) :
liftLinear S f ∘ₗ Matrix.singleLinearMap _ i j = f i j :=
LinearMap.ext <| liftLinear_single S f i j
@[simp]
theorem liftLinear_singleLinearMap [Module S α] [SMulCommClass R S α] :
liftLinear S (Matrix.singleLinearMap R) = .id (M := Matrix m n α) :=
ext_linearMap _ <| liftLinear_comp_singleLinearMap _ _
end liftLinear
end ext
section
variable [Zero α] (i : m) (j : n) (c : α) (i' : m) (j' : n)
@[simp]
theorem single_apply_same : single i j c i j = c :=
if_pos (And.intro rfl rfl)
@[deprecated (since := "2025-05-05")] alias StdBasisMatrix.apply_same := single_apply_same
@[simp]
theorem single_apply_of_ne (h : ¬(i = i' ∧ j = j')) : single i j c i' j' = 0 := by
simp only [single, and_imp, ite_eq_right_iff, of_apply]
tauto
@[deprecated (since := "2025-05-05")] alias StdBasisMatrix.apply_of_ne := single_apply_of_ne
theorem single_apply_of_row_ne {i i' : m} (hi : i ≠ i') (j j' : n) (a : α) :
single i j a i' j' = 0 := by simp [hi]
@[deprecated (since := "2025-05-05")] alias StdBasisMatrix.apply_of_row_ne := single_apply_of_row_ne
theorem single_apply_of_col_ne (i i' : m) {j j' : n} (hj : j ≠ j') (a : α) :
single i j a i' j' = 0 := by simp [hj]
@[deprecated (since := "2025-05-05")] alias StdBasisMatrix.apply_of_col_ne := single_apply_of_col_ne
end
section
variable [Zero α] (i j : n) (c : α)
-- This simp lemma should take priority over `diag_apply`
@[simp 1050]
theorem diag_single_of_ne (h : i ≠ j) : diag (single i j c) = 0 :=
funext fun _ => if_neg fun ⟨e₁, e₂⟩ => h (e₁.trans e₂.symm)
@[deprecated (since := "2025-05-05")] alias StdBasisMatrix.diag_zero := diag_single_of_ne
-- This simp lemma should take priority over `diag_apply`
@[simp 1050]
theorem diag_single_same : diag (single i i c) = Pi.single i c := by
ext j
by_cases hij : i = j <;> (try rw [hij]) <;> simp [hij]
@[deprecated (since := "2025-05-05")] alias StdBasisMatrix.diag_same := diag_single_same
end
section mul
variable [Fintype m] [NonUnitalNonAssocSemiring α] (c : α)
omit [DecidableEq n] in
@[simp]
theorem single_mul_apply_same (i : l) (j : m) (b : n) (M : Matrix m n α) :
(single i j c * M) i b = c * M j b := by simp [mul_apply, single]
@[deprecated (since := "2025-05-05")]
alias StdBasisMatrix.mul_left_apply_same := single_mul_apply_same
omit [DecidableEq l] in
@[simp]
theorem mul_single_apply_same (i : m) (j : n) (a : l) (M : Matrix l m α) :
(M * single i j c) a j = M a i * c := by simp [mul_apply, single]
@[deprecated (since := "2025-05-05")]
alias StdBasisMatrix.mul_right_apply_same := mul_single_apply_same
omit [DecidableEq n] in
@[simp]
theorem single_mul_apply_of_ne (i : l) (j : m) (a : l) (b : n) (h : a ≠ i) (M : Matrix m n α) :
(single i j c * M) a b = 0 := by simp [mul_apply, h.symm]
@[deprecated (since := "2025-05-05")]
alias StdBasisMatrix.mul_left_apply_of_ne := single_mul_apply_of_ne
omit [DecidableEq l] in
@[simp]
theorem mul_single_apply_of_ne (i : m) (j : n) (a : l) (b : n) (hbj : b ≠ j) (M : Matrix l m α) :
(M * single i j c) a b = 0 := by simp [mul_apply, hbj.symm]
@[deprecated (since := "2025-05-05")]
alias StdBasisMatrix.mul_right_apply_of_ne := mul_single_apply_of_ne
@[simp]
theorem single_mul_single_same (i : l) (j : m) (k : n) (d : α) :
single i j c * single j k d = single i k (c * d) := by
ext a b
simp only [mul_apply, single]
by_cases h₁ : i = a <;> by_cases h₂ : k = b <;> simp [h₁, h₂]
@[deprecated (since := "2025-05-05")] alias StdBasisMatrix.mul_same := single_mul_single_same
@[simp]
theorem single_mul_mul_single [Fintype n]
(i : l) (i' : m) (j' : n) (j : o) (a : α) (x : Matrix m n α) (b : α) :
single i i' a * x * single j' j b = single i j (a * x i' j' * b) := by
ext i'' j''
simp only [mul_apply, single]
by_cases h₁ : i = i'' <;> by_cases h₂ : j = j'' <;> simp [h₁, h₂]
@[deprecated (since := "2025-05-05")]
alias StdBasisMatrix.stdBasisMatrix_mul_mul_stdBasisMatrix := single_mul_mul_single
@[simp]
theorem single_mul_single_of_ne (i : l) (j k : m) {l : n} (h : j ≠ k) (d : α) :
single i j c * single k l d = 0 := by
ext a b
simp only [mul_apply, single, of_apply]
by_cases h₁ : i = a
· simp [h₁, h, Finset.sum_eq_zero]
· simp [h₁]
@[deprecated (since := "2025-05-05")] alias StdBasisMatrix.mul_of_ne := single_mul_single_of_ne
end mul
section Commute
variable [Fintype n] [Semiring α]
theorem row_eq_zero_of_commute_single {i j k : n} {M : Matrix n n α}
(hM : Commute (single i j 1) M) (hkj : k ≠ j) : M j k = 0 := by
have := ext_iff.mpr hM i k
simp_all
@[deprecated (since := "2025-05-05")]
alias row_eq_zero_of_commute_stdBasisMatrix := row_eq_zero_of_commute_single
theorem col_eq_zero_of_commute_single {i j k : n} {M : Matrix n n α}
(hM : Commute (single i j 1) M) (hki : k ≠ i) : M k i = 0 := by
have := ext_iff.mpr hM k j
simp_all
@[deprecated (since := "2025-05-05")]
alias col_eq_zero_of_commute_stdBasisMatrix := col_eq_zero_of_commute_single
theorem diag_eq_of_commute_single {i j : n} {M : Matrix n n α}
(hM : Commute (single i j 1) M) : M i i = M j j := by
have := ext_iff.mpr hM i j
simp_all
@[deprecated (since := "2025-05-05")]
alias diag_eq_of_commute_stdBasisMatrix := diag_eq_of_commute_single
/-- `M` is a scalar matrix if it commutes with every non-diagonal `single`. -/
theorem mem_range_scalar_of_commute_single {M : Matrix n n α}
(hM : Pairwise fun i j => Commute (single i j 1) M) :
M ∈ Set.range (Matrix.scalar n) := by
cases isEmpty_or_nonempty n
· exact ⟨0, Subsingleton.elim _ _⟩
obtain ⟨i⟩ := ‹Nonempty n›
refine ⟨M i i, Matrix.ext fun j k => ?_⟩
simp only [scalar_apply]
obtain rfl | hkl := Decidable.eq_or_ne j k
· rw [diagonal_apply_eq]
obtain rfl | hij := Decidable.eq_or_ne i j
· rfl
· exact diag_eq_of_commute_single (hM hij)
· rw [diagonal_apply_ne _ hkl]
obtain rfl | hij := Decidable.eq_or_ne i j
· rw [col_eq_zero_of_commute_single (hM hkl.symm) hkl]
· rw [row_eq_zero_of_commute_single (hM hij) hkl.symm]
@[deprecated (since := "2025-05-05")]
alias mem_range_scalar_of_commute_stdBasisMatrix := mem_range_scalar_of_commute_single
theorem mem_range_scalar_iff_commute_single {M : Matrix n n α} :
M ∈ Set.range (Matrix.scalar n) ↔ ∀ (i j : n), i ≠ j → Commute (single i j 1) M := by
refine ⟨fun ⟨r, hr⟩ i j _ => hr ▸ Commute.symm ?_, mem_range_scalar_of_commute_single⟩
rw [scalar_commute_iff]
simp
@[deprecated (since := "2025-05-05")]
alias mem_range_scalar_iff_commute_stdBasisMatrix := mem_range_scalar_iff_commute_single
/-- `M` is a scalar matrix if and only if it commutes with every `single`. -/
theorem mem_range_scalar_iff_commute_single' {M : Matrix n n α} :
M ∈ Set.range (Matrix.scalar n) ↔ ∀ (i j : n), Commute (single i j 1) M := by
refine ⟨fun ⟨r, hr⟩ i j => hr ▸ Commute.symm ?_,
fun hM => mem_range_scalar_iff_commute_single.mpr <| fun i j _ => hM i j⟩
rw [scalar_commute_iff]
simp
@[deprecated (since := "2025-05-05")]
alias mem_range_scalar_iff_commute_stdBasisMatrix' := mem_range_scalar_iff_commute_single'
/-- The center of `Matrix n n α` is equal to the image of the center of `α` under `scalar n`. -/
theorem center_eq_scalar_image :
Set.center (Matrix n n α) = scalar n '' Set.center α := Set.ext fun x ↦ by
simp_rw [Set.mem_image, Semigroup.mem_center_iff]
refine ⟨fun hx ↦ ?_, fun ⟨x, hx, eq⟩ y ↦ eq ▸ scalar_commute x (hx · |>.symm) y |>.symm⟩
refine (isEmpty_or_nonempty n).elim (fun _ ↦ ⟨0, by simp [nontriviality]⟩) fun ⟨i⟩ ↦ ?_
obtain ⟨x, rfl⟩ := mem_range_scalar_iff_commute_single'.mpr fun _ _ ↦ hx _
exact ⟨x, by simpa using fun r ↦ congr($(hx (single i i r)) i i)⟩
theorem submonoidCenter_eq_scalar_map :
Submonoid.center (Matrix n n α) = (Submonoid.center α).map (scalar n) :=
SetLike.coe_injective center_eq_scalar_image
theorem subsemigroupCenter_eq_scalar_map :
Subsemigroup.center (Matrix n n α) = (Subsemigroup.center α).map (scalar n).toMulHom :=
SetLike.coe_injective center_eq_scalar_image
theorem subsemiringCenter_eq_scalar_map :
Subsemiring.center (Matrix n n α) = (Subsemiring.center α).map (scalar n) :=
SetLike.coe_injective center_eq_scalar_image
theorem subringCenter_eq_scalar_map [Ring R] :
Subring.center (Matrix n n R) = (Subring.center R).map (scalar n) :=
SetLike.coe_injective center_eq_scalar_image
/-- For a commutative semiring `R`, the center of `Matrix n n R` is the range of `scalar n`
(i.e., the span of `{1}`). -/
@[simp] theorem center_eq_range [CommSemiring R] :
Set.center (Matrix n n R) = Set.range (scalar n) := by
rw [center_eq_scalar_image, Set.center_eq_univ, Set.image_univ]
end Commute
end Matrix |
.lake/packages/mathlib/Mathlib/Data/Matrix/PEquiv.lean | import Mathlib.Data.Matrix.Mul
import Mathlib.Data.PEquiv
/-!
# partial equivalences for matrices
Using partial equivalences to represent matrices.
This file introduces the function `PEquiv.toMatrix`, which returns a matrix containing ones and
zeros. For any partial equivalence `f`, `f.toMatrix i j = 1 ↔ f i = some j`.
The following important properties of this function are proved
`toMatrix_trans : (f.trans g).toMatrix = f.toMatrix * g.toMatrix`
`toMatrix_symm : f.symm.toMatrix = f.toMatrixᵀ`
`toMatrix_refl : (PEquiv.refl n).toMatrix = 1`
`toMatrix_bot : ⊥.toMatrix = 0`
This theory gives the matrix representation of projection linear maps, and their right inverses.
For example, the matrix `(single (0 : Fin 1) (i : Fin n)).toMatrix` corresponds to the ith
projection map from R^n to R.
Any injective function `Fin m → Fin n` gives rise to a `PEquiv`, whose matrix is the projection
map from R^m → R^n represented by the same function. The transpose of this matrix is the right
inverse of this map, sending anything not in the image to zero.
## Notation
This file uses `ᵀ` for `Matrix.transpose`.
-/
assert_not_exists Field
namespace PEquiv
open Matrix
universe u v
variable {k l m n : Type*}
variable {α β : Type*}
open Matrix
/-- `toMatrix` returns a matrix containing ones and zeros. `f.toMatrix i j` is `1` if
`f i = some j` and `0` otherwise -/
def toMatrix [DecidableEq n] [Zero α] [One α] (f : m ≃. n) : Matrix m n α :=
of fun i j => if j ∈ f i then (1 : α) else 0
-- TODO: set as an equation lemma for `toMatrix`, see https://github.com/leanprover-community/mathlib4/pull/3024
@[simp]
theorem toMatrix_apply [DecidableEq n] [Zero α] [One α] (f : m ≃. n) (i j) :
toMatrix f i j = if j ∈ f i then (1 : α) else 0 :=
rfl
theorem toMatrix_mul_apply [Fintype m] [DecidableEq m] [NonAssocSemiring α] (f : l ≃. m) (i j)
(M : Matrix m n α) : (f.toMatrix * M :) i j = Option.casesOn (f i) 0 fun fi => M fi j := by
dsimp [toMatrix, Matrix.mul_apply]
rcases h : f i with - | fi
· simp
· rw [Finset.sum_eq_single fi] <;> simp +contextual [eq_comm]
theorem mul_toMatrix_apply [Fintype m] [NonAssocSemiring α] [DecidableEq n] (M : Matrix l m α)
(f : m ≃. n) (i j) : (M * f.toMatrix :) i j = Option.casesOn (f.symm j) 0 (M i) := by
dsimp [Matrix.mul_apply, toMatrix_apply]
rcases h : f.symm j with - | fj
· simp [h, ← f.eq_some_iff]
· rw [Finset.sum_eq_single fj]
· simp [h, ← f.eq_some_iff]
· rintro b - n
simp [h, ← f.eq_some_iff, n.symm]
· simp
theorem toMatrix_symm [DecidableEq m] [DecidableEq n] [Zero α] [One α] (f : m ≃. n) :
(f.symm.toMatrix : Matrix n m α) = f.toMatrixᵀ := by
ext
simp only [transpose, mem_iff_mem f, toMatrix_apply]
congr
@[simp]
theorem toMatrix_refl [DecidableEq n] [Zero α] [One α] :
((PEquiv.refl n).toMatrix : Matrix n n α) = 1 := by
ext
simp [toMatrix_apply, one_apply]
@[simp]
theorem toMatrix_toPEquiv_apply [DecidableEq n] [Zero α] [One α] (f : m ≃ n) (i) :
f.toPEquiv.toMatrix i = Pi.single (f i) (1 : α) := by
ext
simp [toMatrix_apply, Pi.single_apply, eq_comm]
@[simp]
theorem transpose_toMatrix_toPEquiv_apply
[DecidableEq m] [DecidableEq n] [Zero α] [One α] (f : m ≃ n) (j) :
f.toPEquiv.toMatrixᵀ j = Pi.single (f.symm j) (1 : α) := by
ext
simp [toMatrix_apply, Pi.single_apply, eq_comm, ← Equiv.apply_eq_iff_eq_symm_apply]
theorem toMatrix_toPEquiv_mul [Fintype m] [DecidableEq m]
[NonAssocSemiring α] (f : l ≃ m) (M : Matrix m n α) :
f.toPEquiv.toMatrix * M = M.submatrix f id := by
ext i j
rw [toMatrix_mul_apply, Equiv.toPEquiv_apply, submatrix_apply, id]
theorem mul_toMatrix_toPEquiv [Fintype m] [DecidableEq n]
[NonAssocSemiring α] (M : Matrix l m α) (f : m ≃ n) :
(M * f.toPEquiv.toMatrix) = M.submatrix id f.symm :=
Matrix.ext fun i j => by
rw [PEquiv.mul_toMatrix_apply, ← Equiv.toPEquiv_symm, Equiv.toPEquiv_apply,
Matrix.submatrix_apply, id]
lemma toMatrix_toPEquiv_mulVec [DecidableEq n] [Fintype n]
[NonAssocSemiring α] (σ : m ≃ n) (a : n → α) :
σ.toPEquiv.toMatrix *ᵥ a = a ∘ σ := by
ext j
simp [toMatrix, mulVec, dotProduct]
lemma vecMul_toMatrix_toPEquiv [DecidableEq n] [Fintype m]
[NonAssocSemiring α] (σ : m ≃ n) (a : m → α) :
a ᵥ* σ.toPEquiv.toMatrix = a ∘ σ.symm := by
classical
ext j
simp [toMatrix, σ.apply_eq_iff_eq_symm_apply, vecMul, dotProduct]
theorem toMatrix_trans [Fintype m] [DecidableEq m] [DecidableEq n] [NonAssocSemiring α] (f : l ≃. m)
(g : m ≃. n) : ((f.trans g).toMatrix : Matrix l n α) = f.toMatrix * g.toMatrix := by
ext i j
rw [toMatrix_mul_apply]
dsimp [toMatrix, PEquiv.trans]
cases f i <;> simp
@[simp]
theorem toMatrix_bot [DecidableEq n] [Zero α] [One α] :
((⊥ : PEquiv m n).toMatrix : Matrix m n α) = 0 :=
rfl
theorem toMatrix_injective [DecidableEq n] [MulZeroOneClass α] [Nontrivial α] :
Function.Injective (@toMatrix m n α _ _ _) := by
intro f g
refine not_imp_not.1 ?_
simp only [Matrix.ext_iff.symm, toMatrix_apply, PEquiv.ext_iff, not_forall, exists_imp]
intro i hi
use i
rcases hf : f i with - | fi
· rcases hg : g i with - | gi
· rw [hf, hg] at hi; exact (hi rfl).elim
· use gi
simp
· use fi
simp [hf.symm, Ne.symm hi]
theorem toMatrix_swap [DecidableEq n] [AddGroupWithOne α] (i j : n) :
(Equiv.swap i j).toPEquiv.toMatrix =
(1 : Matrix n n α) - (single i i).toMatrix - (single j j).toMatrix + (single i j).toMatrix +
(single j i).toMatrix := by
ext
dsimp [toMatrix, single, Equiv.swap_apply_def, Equiv.toPEquiv, one_apply]
split_ifs <;> simp_all
@[simp]
theorem single_mul_single [Fintype n] [DecidableEq k] [DecidableEq m] [DecidableEq n]
[NonAssocSemiring α] (a : m) (b : n) (c : k) :
((single a b).toMatrix : Matrix _ _ α) * (single b c).toMatrix = (single a c).toMatrix := by
rw [← toMatrix_trans, single_trans_single]
theorem single_mul_single_of_ne [Fintype n] [DecidableEq n] [DecidableEq k] [DecidableEq m]
[NonAssocSemiring α] {b₁ b₂ : n} (hb : b₁ ≠ b₂) (a : m) (c : k) :
(single a b₁).toMatrix * (single b₂ c).toMatrix = (0 : Matrix _ _ α) := by
rw [← toMatrix_trans, single_trans_single_of_ne hb, toMatrix_bot]
/-- Restatement of `single_mul_single`, which will simplify expressions in `simp` normal form,
when associativity may otherwise need to be carefully applied. -/
@[simp]
theorem single_mul_single_right [Fintype n] [Fintype k] [DecidableEq n] [DecidableEq k]
[DecidableEq m] [Semiring α] (a : m) (b : n) (c : k) (M : Matrix k l α) :
(single a b).toMatrix * ((single b c).toMatrix * M) = (single a c).toMatrix * M := by
rw [← Matrix.mul_assoc, single_mul_single]
/-- We can also define permutation matrices by permuting the rows of the identity matrix. -/
theorem toMatrix_toPEquiv_eq [DecidableEq n] [Zero α] [One α] (σ : Equiv.Perm n) :
σ.toPEquiv.toMatrix = (1 : Matrix n n α).submatrix σ id :=
Matrix.ext fun _ _ => if_congr Option.some_inj rfl rfl
@[simp]
lemma map_toMatrix [DecidableEq n] [NonAssocSemiring α] [NonAssocSemiring β]
(f : α →+* β) (σ : m ≃. n) : σ.toMatrix.map f = σ.toMatrix := by
ext i j
simp
end PEquiv |
.lake/packages/mathlib/Mathlib/Data/Matrix/DualNumber.lean | import Mathlib.Algebra.DualNumber
import Mathlib.Data.Matrix.Basic
/-!
# Matrices of dual numbers are isomorphic to dual numbers over matrices
Showing this for the more general case of `TrivSqZeroExt R M` would require an action between
`Matrix n n R` and `Matrix n n M`, which would risk causing diamonds.
-/
variable {R n : Type} [CommSemiring R] [Fintype n] [DecidableEq n]
open Matrix TrivSqZeroExt
/-- Matrices over dual numbers and dual numbers over matrices are isomorphic. -/
@[simps]
def Matrix.dualNumberEquiv : Matrix n n (DualNumber R) ≃ₐ[R] DualNumber (Matrix n n R) where
toFun A := ⟨of fun i j => (A i j).fst, of fun i j => (A i j).snd⟩
invFun d := of fun i j => (d.fst i j, d.snd i j)
map_mul' A B := by
ext
· dsimp [mul_apply]
simp_rw [fst_sum]
rfl
· simp_rw [snd_mul, smul_eq_mul, op_smul_eq_mul]
simp only [mul_apply, snd_sum, DualNumber.snd_mul, snd_mk, of_apply, fst_mk, add_apply]
rw [← Finset.sum_add_distrib]
map_add' _ _ := TrivSqZeroExt.ext rfl rfl
commutes' r := by
simp_rw [algebraMap_eq_inl', algebraMap_eq_diagonal, Pi.algebraMap_def,
Algebra.algebraMap_self_apply, algebraMap_eq_inl, ← diagonal_map (inl_zero R), map_apply,
fst_inl, snd_inl]
rfl |
.lake/packages/mathlib/Mathlib/Data/PSigma/Order.lean | import Mathlib.Data.Sigma.Lex
import Mathlib.Util.Notation3
import Init.NotationExtra
import Mathlib.Data.Sigma.Basic
import Mathlib.Order.Lattice
import Mathlib.Order.BoundedOrder.Basic
/-!
# Lexicographic order on a sigma type
This file defines the lexicographic order on `Σₗ' i, α i`. `a` is less than `b` if its summand is
strictly less than the summand of `b` or they are in the same summand and `a` is less than `b`
there.
## Notation
* `Σₗ' i, α i`: Sigma type equipped with the lexicographic order. A type synonym of `Σ' i, α i`.
## See also
Related files are:
* `Data.Finset.Colex`: Colexicographic order on finite sets.
* `Data.List.Lex`: Lexicographic order on lists.
* `Data.Pi.Lex`: Lexicographic order on `Πₗ i, α i`.
* `Data.Sigma.Order`: Lexicographic order on `Σₗ i, α i`. Basically a twin of this file.
* `Data.Prod.Lex`: Lexicographic order on `α × β`.
## TODO
Define the disjoint order on `Σ' i, α i`, where `x ≤ y` only if `x.fst = y.fst`.
Prove that a sigma type is a `NoMaxOrder`, `NoMinOrder`, `DenselyOrdered` when its summands
are.
-/
variable {ι : Type*} {α : ι → Type*}
namespace PSigma
/-- The notation `Σₗ' i, α i` refers to a sigma type which is locally equipped with the
lexicographic order. -/
-- TODO: make `Lex` be `Sort u -> Sort u` so we can remove `.{_+1, _+1}`
notation3 "Σₗ' " (...) ", " r:(scoped p => _root_.Lex (PSigma.{_ + 1, _ + 1} p)) => r
namespace Lex
/-- The lexicographical `≤` on a sigma type. -/
instance le [LT ι] [∀ i, LE (α i)] : LE (Σₗ' i, α i) :=
⟨Lex (· < ·) fun _ => (· ≤ ·)⟩
/-- The lexicographical `<` on a sigma type. -/
instance lt [LT ι] [∀ i, LT (α i)] : LT (Σₗ' i, α i) :=
⟨Lex (· < ·) fun _ => (· < ·)⟩
instance preorder [Preorder ι] [∀ i, Preorder (α i)] : Preorder (Σₗ' i, α i) :=
{ Lex.le, Lex.lt with
le_refl := fun ⟨_, _⟩ => Lex.right _ le_rfl,
le_trans := by
rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ ⟨a₃, b₃⟩ ⟨h₁r⟩ ⟨h₂r⟩
· left
apply lt_trans
repeat' assumption
· left
assumption
· left
assumption
· right
apply le_trans
repeat' assumption,
lt_iff_le_not_ge := by
refine fun a b => ⟨fun hab => ⟨hab.mono_right fun i a b => le_of_lt, ?_⟩, ?_⟩
· rintro (⟨i, a, hji⟩ | ⟨i, hba⟩) <;> obtain ⟨_, _, hij⟩ | ⟨_, hab⟩ := hab
· exact hij.not_gt hji
· exact lt_irrefl _ hji
· exact lt_irrefl _ hij
· exact hab.not_ge hba
· rintro ⟨⟨j, b, hij⟩ | ⟨i, hab⟩, hba⟩
· exact Lex.left _ _ hij
· exact Lex.right _ (hab.lt_of_not_ge fun h => hba <| Lex.right _ h) }
/-- Dictionary / lexicographic partial_order for dependent pairs. -/
instance partialOrder [PartialOrder ι] [∀ i, PartialOrder (α i)] : PartialOrder (Σₗ' i, α i) :=
{ Lex.preorder with
le_antisymm := by
rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ (⟨_, _, hlt₁⟩ | ⟨_, hlt₁⟩) (⟨_, _, hlt₂⟩ | ⟨_, hlt₂⟩)
· exact (lt_irrefl a₁ <| hlt₁.trans hlt₂).elim
· exact (lt_irrefl a₁ hlt₁).elim
· exact (lt_irrefl a₁ hlt₂).elim
· rw [hlt₁.antisymm hlt₂] }
/-- Dictionary / lexicographic linear_order for pairs. -/
instance linearOrder [LinearOrder ι] [∀ i, LinearOrder (α i)] : LinearOrder (Σₗ' i, α i) :=
{ Lex.partialOrder with
le_total := by
rintro ⟨i, a⟩ ⟨j, b⟩
obtain hij | rfl | hji := lt_trichotomy i j
· exact Or.inl (Lex.left _ _ hij)
· obtain hab | hba := le_total a b
· exact Or.inl (Lex.right _ hab)
· exact Or.inr (Lex.right _ hba)
· exact Or.inr (Lex.left _ _ hji),
toDecidableEq := PSigma.decidableEq, toDecidableLE := Lex.decidable _ _,
toDecidableLT := Lex.decidable _ _ }
/-- The lexicographical linear order on a sigma type. -/
instance orderBot [PartialOrder ι] [OrderBot ι] [∀ i, Preorder (α i)] [OrderBot (α ⊥)] :
OrderBot (Σₗ' i, α i) where
bot := ⟨⊥, ⊥⟩
bot_le := fun ⟨a, b⟩ => by
obtain rfl | ha := eq_bot_or_bot_lt a
· exact Lex.right _ bot_le
· exact Lex.left _ _ ha
/-- The lexicographical linear order on a sigma type. -/
instance orderTop [PartialOrder ι] [OrderTop ι] [∀ i, Preorder (α i)] [OrderTop (α ⊤)] :
OrderTop (Σₗ' i, α i) where
top := ⟨⊤, ⊤⟩
le_top := fun ⟨a, b⟩ => by
obtain rfl | ha := eq_top_or_lt_top a
· exact Lex.right _ le_top
· exact Lex.left _ _ ha
/-- The lexicographical linear order on a sigma type. -/
instance boundedOrder [PartialOrder ι] [BoundedOrder ι] [∀ i, Preorder (α i)] [OrderBot (α ⊥)]
[OrderTop (α ⊤)] : BoundedOrder (Σₗ' i, α i) :=
{ Lex.orderBot, Lex.orderTop with }
instance denselyOrdered [Preorder ι] [DenselyOrdered ι] [∀ i, Nonempty (α i)] [∀ i, Preorder (α i)]
[∀ i, DenselyOrdered (α i)] : DenselyOrdered (Σₗ' i, α i) :=
⟨by
rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | @⟨_, _, b, h⟩)
· obtain ⟨k, hi, hj⟩ := exists_between h
obtain ⟨c⟩ : Nonempty (α k) := inferInstance
exact ⟨⟨k, c⟩, left _ _ hi, left _ _ hj⟩
· obtain ⟨c, ha, hb⟩ := exists_between h
exact ⟨⟨i, c⟩, right _ ha, right _ hb⟩⟩
instance denselyOrdered_of_noMaxOrder [Preorder ι] [∀ i, Preorder (α i)]
[∀ i, DenselyOrdered (α i)] [∀ i, NoMaxOrder (α i)] : DenselyOrdered (Σₗ' i, α i) :=
⟨by
rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | @⟨_, _, b, h⟩)
· obtain ⟨c, ha⟩ := exists_gt a
exact ⟨⟨i, c⟩, right _ ha, left _ _ h⟩
· obtain ⟨c, ha, hb⟩ := exists_between h
exact ⟨⟨i, c⟩, right _ ha, right _ hb⟩⟩
instance denselyOrdered_of_noMinOrder [Preorder ι] [∀ i, Preorder (α i)]
[∀ i, DenselyOrdered (α i)] [∀ i, NoMinOrder (α i)] : DenselyOrdered (Σₗ' i, α i) :=
⟨by
rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | @⟨_, _, b, h⟩)
· obtain ⟨c, hb⟩ := exists_lt b
exact ⟨⟨j, c⟩, left _ _ h, right _ hb⟩
· obtain ⟨c, ha, hb⟩ := exists_between h
exact ⟨⟨i, c⟩, right _ ha, right _ hb⟩⟩
instance noMaxOrder_of_nonempty [Preorder ι] [∀ i, Preorder (α i)] [NoMaxOrder ι]
[∀ i, Nonempty (α i)] : NoMaxOrder (Σₗ' i, α i) :=
⟨by
rintro ⟨i, a⟩
obtain ⟨j, h⟩ := exists_gt i
obtain ⟨b⟩ : Nonempty (α j) := inferInstance
exact ⟨⟨j, b⟩, left _ _ h⟩⟩
instance noMinOrder_of_nonempty [Preorder ι] [∀ i, Preorder (α i)] [NoMinOrder ι]
[∀ i, Nonempty (α i)] : NoMinOrder (Σₗ' i, α i) :=
⟨by
rintro ⟨i, a⟩
obtain ⟨j, h⟩ := exists_lt i
obtain ⟨b⟩ : Nonempty (α j) := inferInstance
exact ⟨⟨j, b⟩, left _ _ h⟩⟩
instance noMaxOrder [Preorder ι] [∀ i, Preorder (α i)] [∀ i, NoMaxOrder (α i)] :
NoMaxOrder (Σₗ' i, α i) :=
⟨by
rintro ⟨i, a⟩
obtain ⟨b, h⟩ := exists_gt a
exact ⟨⟨i, b⟩, right _ h⟩⟩
instance noMinOrder [Preorder ι] [∀ i, Preorder (α i)] [∀ i, NoMinOrder (α i)] :
NoMinOrder (Σₗ' i, α i) :=
⟨by
rintro ⟨i, a⟩
obtain ⟨b, h⟩ := exists_lt a
exact ⟨⟨i, b⟩, right _ h⟩⟩
end Lex
end PSigma |
.lake/packages/mathlib/Mathlib/Data/Countable/Basic.lean | import Mathlib.Data.Countable.Defs
import Mathlib.Data.Fin.Tuple.Basic
import Mathlib.Data.ENat.Defs
import Mathlib.Logic.Equiv.Nat
/-!
# Countable types
In this file we provide basic instances of the `Countable` typeclass defined elsewhere.
-/
assert_not_exists Monoid
universe u v w
open Function
instance : Countable ℤ :=
Countable.of_equiv ℕ Equiv.intEquivNat.symm
/-!
### Definition in terms of `Function.Embedding`
-/
section Embedding
variable {α : Sort u} {β : Sort v}
theorem countable_iff_nonempty_embedding : Countable α ↔ Nonempty (α ↪ ℕ) :=
⟨fun ⟨⟨f, hf⟩⟩ => ⟨⟨f, hf⟩⟩, fun ⟨f⟩ => ⟨⟨f, f.2⟩⟩⟩
theorem uncountable_iff_isEmpty_embedding : Uncountable α ↔ IsEmpty (α ↪ ℕ) := by
rw [← not_countable_iff, countable_iff_nonempty_embedding, not_nonempty_iff]
theorem nonempty_embedding_nat (α) [Countable α] : Nonempty (α ↪ ℕ) :=
countable_iff_nonempty_embedding.1 ‹_›
protected theorem Function.Embedding.countable [Countable β] (f : α ↪ β) : Countable α :=
f.injective.countable
protected lemma Function.Embedding.uncountable [Uncountable α] (f : α ↪ β) : Uncountable β :=
f.injective.uncountable
end Embedding
/-!
### Operations on `Type*`s
-/
section type
variable {α : Type u} {β : Type v} {π : α → Type w}
instance [Countable α] [Countable β] : Countable (α ⊕ β) := by
rcases exists_injective_nat α with ⟨f, hf⟩
rcases exists_injective_nat β with ⟨g, hg⟩
exact (Equiv.natSumNatEquivNat.injective.comp <| hf.sumMap hg).countable
instance Sum.uncountable_inl [Uncountable α] : Uncountable (α ⊕ β) :=
inl_injective.uncountable
instance Sum.uncountable_inr [Uncountable β] : Uncountable (α ⊕ β) :=
inr_injective.uncountable
instance Option.instCountable [Countable α] : Countable (Option α) :=
Countable.of_equiv _ (Equiv.optionEquivSumPUnit.{0, _} α).symm
instance WithTop.instCountable [Countable α] : Countable (WithTop α) := Option.instCountable
instance WithBot.instCountable [Countable α] : Countable (WithBot α) := Option.instCountable
instance ENat.instCountable : Countable ℕ∞ := Option.instCountable
instance Option.instUncountable [Uncountable α] : Uncountable (Option α) :=
Injective.uncountable fun _ _ ↦ Option.some_inj.1
instance WithTop.instUncountable [Uncountable α] : Uncountable (WithTop α) := Option.instUncountable
instance WithBot.instUncountable [Uncountable α] : Uncountable (WithBot α) := Option.instUncountable
@[simp] lemma untopD_coe_enat (d n : ℕ) : WithTop.untopD d (n : ℕ∞) = n := rfl
instance [Countable α] [Countable β] : Countable (α × β) := by
rcases exists_injective_nat α with ⟨f, hf⟩
rcases exists_injective_nat β with ⟨g, hg⟩
exact (Nat.pairEquiv.injective.comp <| hf.prodMap hg).countable
instance [Uncountable α] [Nonempty β] : Uncountable (α × β) := by
inhabit β
exact (Prod.mk_left_injective default).uncountable
instance [Nonempty α] [Uncountable β] : Uncountable (α × β) := by
inhabit α
exact (Prod.mk_right_injective default).uncountable
lemma countable_left_of_prod_of_nonempty [Nonempty β] (h : Countable (α × β)) : Countable α := by
contrapose! h
infer_instance
lemma countable_right_of_prod_of_nonempty [Nonempty α] (h : Countable (α × β)) : Countable β := by
contrapose! h
infer_instance
lemma countable_prod_swap [Countable (α × β)] : Countable (β × α) :=
Countable.of_equiv _ (Equiv.prodComm α β)
instance [Countable α] [∀ a, Countable (π a)] : Countable (Sigma π) := by
rcases exists_injective_nat α with ⟨f, hf⟩
choose g hg using fun a => exists_injective_nat (π a)
exact ((Equiv.sigmaEquivProd ℕ ℕ).injective.comp <| hf.sigma_map hg).countable
lemma Sigma.uncountable (a : α) [Uncountable (π a)] : Uncountable (Sigma π) :=
(sigma_mk_injective (i := a)).uncountable
instance [Nonempty α] [∀ a, Uncountable (π a)] : Uncountable (Sigma π) := by
inhabit α; exact Sigma.uncountable default
instance (priority := 500) SetCoe.countable [Countable α] (s : Set α) : Countable s :=
Subtype.countable
end type
section sort
variable {α : Sort u} {β : Sort v} {π : α → Sort w}
/-!
### Operations on `Sort*`s
-/
instance [Countable α] [Countable β] : Countable (α ⊕' β) :=
Countable.of_equiv (PLift α ⊕ PLift β) (Equiv.plift.sumPSum Equiv.plift)
instance [Countable α] [Countable β] : Countable (PProd α β) :=
Countable.of_equiv (PLift α × PLift β) (Equiv.plift.prodPProd Equiv.plift)
instance [Countable α] [∀ a, Countable (π a)] : Countable (PSigma π) :=
Countable.of_equiv (Σ a : PLift α, PLift (π a.down)) (Equiv.psigmaEquivSigmaPLift π).symm
instance [Finite α] [∀ a, Countable (π a)] : Countable (∀ a, π a) := by
have (n : ℕ) : Countable (Fin n → ℕ) := by
induction n with
| zero => infer_instance
| succ n ihn => exact Countable.of_equiv (ℕ × (Fin n → ℕ)) (Fin.consEquiv fun _ ↦ ℕ)
rcases Finite.exists_equiv_fin α with ⟨n, ⟨e⟩⟩
have f := fun a => (nonempty_embedding_nat (π a)).some
exact ((Embedding.piCongrRight f).trans (Equiv.piCongrLeft' _ e).toEmbedding).countable
end sort |
.lake/packages/mathlib/Mathlib/Data/Countable/Defs.lean | import Mathlib.Data.Finite.Defs
import Mathlib.Data.Bool.Basic
import Mathlib.Data.Subtype
import Mathlib.Tactic.MkIffOfInductiveProp
/-!
# Countable and uncountable types
In this file we define a typeclass `Countable` saying that a given `Sort*` is countable
and a typeclass `Uncountable` saying that a given `Type*` is uncountable.
See also `Encodable` for a version that singles out
a specific encoding of elements of `α` by natural numbers.
This file also provides a few instances of these typeclasses.
More instances can be found in other files.
-/
open Function
universe u v
variable {α : Sort u} {β : Sort v}
/-!
### Definition and basic properties
-/
/-- A type `α` is countable if there exists an injective map `α → ℕ`. -/
@[mk_iff countable_iff_exists_injective]
class Countable (α : Sort u) : Prop where
/-- A type `α` is countable if there exists an injective map `α → ℕ`. -/
exists_injective_nat' : ∃ f : α → ℕ, Injective f
lemma Countable.exists_injective_nat (α : Sort u) [Countable α] : ∃ f : α → ℕ, Injective f :=
Countable.exists_injective_nat'
instance : Countable ℕ :=
⟨⟨id, injective_id⟩⟩
export Countable (exists_injective_nat)
protected theorem Function.Injective.countable [Countable β] {f : α → β} (hf : Injective f) :
Countable α :=
let ⟨g, hg⟩ := exists_injective_nat β
⟨⟨g ∘ f, hg.comp hf⟩⟩
protected theorem Function.Surjective.countable [Countable α] {f : α → β} (hf : Surjective f) :
Countable β :=
(injective_surjInv hf).countable
theorem exists_surjective_nat (α : Sort u) [Nonempty α] [Countable α] : ∃ f : ℕ → α, Surjective f :=
let ⟨f, hf⟩ := exists_injective_nat α
⟨invFun f, invFun_surjective hf⟩
theorem countable_iff_exists_surjective [Nonempty α] : Countable α ↔ ∃ f : ℕ → α, Surjective f :=
⟨@exists_surjective_nat _ _, fun ⟨_, hf⟩ ↦ hf.countable⟩
theorem Countable.of_equiv (α : Sort*) [Countable α] (e : α ≃ β) : Countable β :=
e.symm.injective.countable
theorem Equiv.countable_iff (e : α ≃ β) : Countable α ↔ Countable β :=
⟨fun h => @Countable.of_equiv _ _ h e, fun h => @Countable.of_equiv _ _ h e.symm⟩
instance {β : Type v} [Countable β] : Countable (ULift.{u} β) :=
Countable.of_equiv _ Equiv.ulift.symm
/-!
### Operations on `Sort*`s
-/
instance [Countable α] : Countable (PLift α) :=
Equiv.plift.injective.countable
instance (priority := 100) Subsingleton.to_countable [Subsingleton α] : Countable α :=
⟨⟨fun _ => 0, fun x y _ => Subsingleton.elim x y⟩⟩
instance (priority := 500) Subtype.countable [Countable α] {p : α → Prop} :
Countable { x // p x } :=
Subtype.val_injective.countable
instance {n : ℕ} : Countable (Fin n) :=
Function.Injective.countable (@Fin.eq_of_val_eq n)
instance (priority := 100) Finite.to_countable [Finite α] : Countable α :=
let ⟨_, ⟨e⟩⟩ := Finite.exists_equiv_fin α
Countable.of_equiv _ e.symm
instance : Countable PUnit.{u} :=
Subsingleton.to_countable
instance (priority := 100) Prop.countable (p : Prop) : Countable p :=
Subsingleton.to_countable
instance Bool.countable : Countable Bool :=
⟨⟨fun b => cond b 0 1, Bool.injective_iff.2 Nat.one_ne_zero⟩⟩
instance Prop.countable' : Countable Prop :=
Countable.of_equiv Bool Equiv.propEquivBool.symm
instance (priority := 500) Quotient.countable [Countable α] {r : α → α → Prop} :
Countable (Quot r) :=
Quot.mk_surjective.countable
instance (priority := 500) [Countable α] {s : Setoid α} : Countable (Quotient s) :=
(inferInstance : Countable (@Quot α _))
/-!
### Uncountable types
-/
/-- A type `α` is uncountable if it is not countable. -/
@[mk_iff uncountable_iff_not_countable]
class Uncountable (α : Sort*) : Prop where
/-- A type `α` is uncountable if it is not countable. -/
not_countable : ¬Countable α
@[push]
lemma not_uncountable_iff : ¬Uncountable α ↔ Countable α := by
rw [uncountable_iff_not_countable, not_not]
@[push]
lemma not_countable_iff : ¬Countable α ↔ Uncountable α := (uncountable_iff_not_countable α).symm
@[simp]
lemma not_uncountable [Countable α] : ¬Uncountable α := not_uncountable_iff.2 ‹_›
@[simp]
lemma not_countable [Uncountable α] : ¬Countable α := Uncountable.not_countable
protected theorem Function.Injective.uncountable [Uncountable α] {f : α → β} (hf : Injective f) :
Uncountable β :=
⟨fun _ ↦ not_countable hf.countable⟩
protected theorem Function.Surjective.uncountable [Uncountable β] {f : α → β} (hf : Surjective f) :
Uncountable α := (injective_surjInv hf).uncountable
lemma not_injective_uncountable_countable [Uncountable α] [Countable β] (f : α → β) :
¬Injective f := fun hf ↦ not_countable hf.countable
lemma not_surjective_countable_uncountable [Countable α] [Uncountable β] (f : α → β) :
¬Surjective f := fun hf ↦
not_countable hf.countable
theorem uncountable_iff_forall_not_surjective [Nonempty α] :
Uncountable α ↔ ∀ f : ℕ → α, ¬Surjective f := by
rw [← not_countable_iff, countable_iff_exists_surjective, not_exists]
theorem Uncountable.of_equiv (α : Sort*) [Uncountable α] (e : α ≃ β) : Uncountable β :=
e.injective.uncountable
theorem Equiv.uncountable_iff (e : α ≃ β) : Uncountable α ↔ Uncountable β :=
⟨fun h => @Uncountable.of_equiv _ _ h e, fun h => @Uncountable.of_equiv _ _ h e.symm⟩
instance {β : Type v} [Uncountable β] : Uncountable (ULift.{u} β) :=
.of_equiv _ Equiv.ulift.symm
instance [Uncountable α] : Uncountable (PLift α) :=
.of_equiv _ Equiv.plift.symm
instance (priority := 100) [Uncountable α] : Infinite α :=
⟨fun _ ↦ not_countable (α := α) inferInstance⟩ |
.lake/packages/mathlib/Mathlib/Data/Countable/Small.lean | import Mathlib.Logic.Small.Basic
import Mathlib.Data.Countable.Defs
/-!
# All countable types are small.
That is, any countable type is equivalent to a type in any universe.
-/
universe w v
instance (priority := 100) Countable.toSmall (α : Type v) [Countable α] : Small.{w} α :=
let ⟨_, hf⟩ := exists_injective_nat α
small_of_injective hf
theorem Uncountable.of_not_small {α : Type v} (h : ¬ Small.{w} α) : Uncountable α := by
rw [uncountable_iff_not_countable]
exact mt (@Countable.toSmall α) h |
.lake/packages/mathlib/Mathlib/Data/EReal/Basic.lean | import Mathlib.Data.ENNReal.Operations
/-!
# The extended real numbers
This file defines `EReal`, `ℝ` with a top element `⊤` and a bottom element `⊥`, implemented as
`WithBot (WithTop ℝ)`.
`EReal` is a `CompleteLinearOrder`, deduced by typeclass inference from the fact that
`WithBot (WithTop L)` completes a conditionally complete linear order `L`.
Coercions from `ℝ` (called `coe` in lemmas) and from `ℝ≥0∞` (`coe_ennreal`) are registered
and their basic properties proved. The latter takes up most of the rest of this file.
## Tags
real, ereal, complete lattice
-/
open Function ENNReal NNReal Set
noncomputable section
/-- The type of extended real numbers `[-∞, ∞]`, constructed as `WithBot (WithTop ℝ)`. -/
def EReal := WithBot (WithTop ℝ)
deriving Bot, Zero, One, Nontrivial, AddMonoid, PartialOrder, AddCommMonoid
instance : ZeroLEOneClass EReal := inferInstanceAs (ZeroLEOneClass (WithBot (WithTop ℝ)))
instance : SupSet EReal := inferInstanceAs (SupSet (WithBot (WithTop ℝ)))
instance : InfSet EReal := inferInstanceAs (InfSet (WithBot (WithTop ℝ)))
instance : CompleteLinearOrder EReal :=
inferInstanceAs (CompleteLinearOrder (WithBot (WithTop ℝ)))
instance : LinearOrder EReal :=
inferInstanceAs (LinearOrder (WithBot (WithTop ℝ)))
instance : IsOrderedAddMonoid EReal :=
inferInstanceAs (IsOrderedAddMonoid (WithBot (WithTop ℝ)))
instance : AddCommMonoidWithOne EReal :=
inferInstanceAs (AddCommMonoidWithOne (WithBot (WithTop ℝ)))
instance : DenselyOrdered EReal :=
inferInstanceAs (DenselyOrdered (WithBot (WithTop ℝ)))
instance : CharZero EReal := inferInstanceAs (CharZero (WithBot (WithTop ℝ)))
/-- The canonical inclusion from reals to ereals. Registered as a coercion. -/
@[coe] def Real.toEReal : ℝ → EReal := WithBot.some ∘ WithTop.some
namespace EReal
-- things unify with `WithBot.decidableLT` later if we don't provide this explicitly.
instance decidableLT : DecidableLT EReal :=
WithBot.decidableLT
-- TODO: Provide explicitly, otherwise it is inferred noncomputably from `CompleteLinearOrder`
instance : Top EReal := ⟨WithBot.some ⊤⟩
instance : Coe ℝ EReal := ⟨Real.toEReal⟩
theorem coe_strictMono : StrictMono Real.toEReal :=
WithBot.coe_strictMono.comp WithTop.coe_strictMono
theorem coe_injective : Injective Real.toEReal :=
coe_strictMono.injective
@[simp, norm_cast]
protected theorem coe_le_coe_iff {x y : ℝ} : (x : EReal) ≤ (y : EReal) ↔ x ≤ y :=
coe_strictMono.le_iff_le
@[gcongr] protected alias ⟨_, coe_le_coe⟩ := EReal.coe_le_coe_iff
@[simp, norm_cast]
protected theorem coe_lt_coe_iff {x y : ℝ} : (x : EReal) < (y : EReal) ↔ x < y :=
coe_strictMono.lt_iff_lt
@[gcongr] protected alias ⟨_, coe_lt_coe⟩ := EReal.coe_lt_coe_iff
@[simp, norm_cast]
protected theorem coe_eq_coe_iff {x y : ℝ} : (x : EReal) = (y : EReal) ↔ x = y :=
coe_injective.eq_iff
protected theorem coe_ne_coe_iff {x y : ℝ} : (x : EReal) ≠ (y : EReal) ↔ x ≠ y :=
coe_injective.ne_iff
@[simp, norm_cast]
protected theorem coe_natCast {n : ℕ} : ((n : ℝ) : EReal) = n := rfl
/-- The canonical map from nonnegative extended reals to extended reals. -/
@[coe] def _root_.ENNReal.toEReal : ℝ≥0∞ → EReal
| ⊤ => ⊤
| .some x => x.1
instance hasCoeENNReal : Coe ℝ≥0∞ EReal :=
⟨ENNReal.toEReal⟩
instance : Inhabited EReal := ⟨0⟩
@[simp, norm_cast]
theorem coe_zero : ((0 : ℝ) : EReal) = 0 := rfl
@[simp, norm_cast]
theorem coe_one : ((1 : ℝ) : EReal) = 1 := rfl
/-- A recursor for `EReal` in terms of the coercion.
When working in term mode, note that pattern matching can be used directly. -/
@[elab_as_elim, induction_eliminator, cases_eliminator]
protected def rec {motive : EReal → Sort*}
(bot : motive ⊥) (coe : ∀ a : ℝ, motive a) (top : motive ⊤) : ∀ a : EReal, motive a
| ⊥ => bot
| (a : ℝ) => coe a
| ⊤ => top
protected lemma «forall» {p : EReal → Prop} : (∀ r, p r) ↔ p ⊥ ∧ p ⊤ ∧ ∀ r : ℝ, p r where
mp h := ⟨h _, h _, fun _ ↦ h _⟩
mpr h := EReal.rec h.1 h.2.2 h.2.1
protected lemma «exists» {p : EReal → Prop} : (∃ r, p r) ↔ p ⊥ ∨ p ⊤ ∨ ∃ r : ℝ, p r where
mp := by rintro ⟨r, hr⟩; cases r <;> aesop
mpr := by rintro (h | h | ⟨r, hr⟩) <;> exact ⟨_, ‹_›⟩
/-- The multiplication on `EReal`. Our definition satisfies `0 * x = x * 0 = 0` for any `x`, and
picks the only sensible value elsewhere. -/
protected def mul : EReal → EReal → EReal
| ⊥, ⊥ => ⊤
| ⊥, ⊤ => ⊥
| ⊥, (y : ℝ) => if 0 < y then ⊥ else if y = 0 then 0 else ⊤
| ⊤, ⊥ => ⊥
| ⊤, ⊤ => ⊤
| ⊤, (y : ℝ) => if 0 < y then ⊤ else if y = 0 then 0 else ⊥
| (x : ℝ), ⊤ => if 0 < x then ⊤ else if x = 0 then 0 else ⊥
| (x : ℝ), ⊥ => if 0 < x then ⊥ else if x = 0 then 0 else ⊤
| (x : ℝ), (y : ℝ) => (x * y : ℝ)
instance : Mul EReal := ⟨EReal.mul⟩
@[simp, norm_cast]
theorem coe_mul (x y : ℝ) : (↑(x * y) : EReal) = x * y :=
rfl
/-- Induct on two `EReal`s by performing case splits on the sign of one whenever the other is
infinite. -/
@[elab_as_elim]
theorem induction₂ {P : EReal → EReal → Prop} (top_top : P ⊤ ⊤) (top_pos : ∀ x : ℝ, 0 < x → P ⊤ x)
(top_zero : P ⊤ 0) (top_neg : ∀ x : ℝ, x < 0 → P ⊤ x) (top_bot : P ⊤ ⊥)
(pos_top : ∀ x : ℝ, 0 < x → P x ⊤) (pos_bot : ∀ x : ℝ, 0 < x → P x ⊥) (zero_top : P 0 ⊤)
(coe_coe : ∀ x y : ℝ, P x y) (zero_bot : P 0 ⊥) (neg_top : ∀ x : ℝ, x < 0 → P x ⊤)
(neg_bot : ∀ x : ℝ, x < 0 → P x ⊥) (bot_top : P ⊥ ⊤) (bot_pos : ∀ x : ℝ, 0 < x → P ⊥ x)
(bot_zero : P ⊥ 0) (bot_neg : ∀ x : ℝ, x < 0 → P ⊥ x) (bot_bot : P ⊥ ⊥) : ∀ x y, P x y
| ⊥, ⊥ => bot_bot
| ⊥, (y : ℝ) => by
rcases lt_trichotomy y 0 with (hy | rfl | hy)
exacts [bot_neg y hy, bot_zero, bot_pos y hy]
| ⊥, ⊤ => bot_top
| (x : ℝ), ⊥ => by
rcases lt_trichotomy x 0 with (hx | rfl | hx)
exacts [neg_bot x hx, zero_bot, pos_bot x hx]
| (x : ℝ), (y : ℝ) => coe_coe _ _
| (x : ℝ), ⊤ => by
rcases lt_trichotomy x 0 with (hx | rfl | hx)
exacts [neg_top x hx, zero_top, pos_top x hx]
| ⊤, ⊥ => top_bot
| ⊤, (y : ℝ) => by
rcases lt_trichotomy y 0 with (hy | rfl | hy)
exacts [top_neg y hy, top_zero, top_pos y hy]
| ⊤, ⊤ => top_top
/-- Induct on two `EReal`s by performing case splits on the sign of one whenever the other is
infinite. This version eliminates some cases by assuming that the relation is symmetric. -/
@[elab_as_elim]
theorem induction₂_symm {P : EReal → EReal → Prop} (symm : ∀ {x y}, P x y → P y x)
(top_top : P ⊤ ⊤) (top_pos : ∀ x : ℝ, 0 < x → P ⊤ x) (top_zero : P ⊤ 0)
(top_neg : ∀ x : ℝ, x < 0 → P ⊤ x) (top_bot : P ⊤ ⊥) (pos_bot : ∀ x : ℝ, 0 < x → P x ⊥)
(coe_coe : ∀ x y : ℝ, P x y) (zero_bot : P 0 ⊥) (neg_bot : ∀ x : ℝ, x < 0 → P x ⊥)
(bot_bot : P ⊥ ⊥) : ∀ x y, P x y :=
@induction₂ P top_top top_pos top_zero top_neg top_bot (fun _ h => symm <| top_pos _ h)
pos_bot (symm top_zero) coe_coe zero_bot (fun _ h => symm <| top_neg _ h) neg_bot (symm top_bot)
(fun _ h => symm <| pos_bot _ h) (symm zero_bot) (fun _ h => symm <| neg_bot _ h) bot_bot
protected theorem mul_comm (x y : EReal) : x * y = y * x := by
induction x <;> induction y <;>
try { rfl }
rw [← coe_mul, ← coe_mul, mul_comm]
protected theorem one_mul : ∀ x : EReal, 1 * x = x
| ⊤ => if_pos one_pos
| ⊥ => if_pos one_pos
| (x : ℝ) => congr_arg Real.toEReal (one_mul x)
protected theorem zero_mul : ∀ x : EReal, 0 * x = 0
| ⊤ => (if_neg (lt_irrefl _)).trans (if_pos rfl)
| ⊥ => (if_neg (lt_irrefl _)).trans (if_pos rfl)
| (x : ℝ) => congr_arg Real.toEReal (zero_mul x)
instance : MulZeroOneClass EReal where
one_mul := EReal.one_mul
mul_one := fun x => by rw [EReal.mul_comm, EReal.one_mul]
zero_mul := EReal.zero_mul
mul_zero := fun x => by rw [EReal.mul_comm, EReal.zero_mul]
/-! ### Real coercion -/
instance canLift : CanLift EReal ℝ (↑) fun r => r ≠ ⊤ ∧ r ≠ ⊥ where
prf x hx := by
induction x
· simp at hx
· simp
· simp at hx
/-- The map from extended reals to reals sending infinities to zero. -/
def toReal : EReal → ℝ
| ⊥ => 0
| ⊤ => 0
| (x : ℝ) => x
@[simp]
theorem toReal_top : toReal ⊤ = 0 :=
rfl
@[simp]
theorem toReal_bot : toReal ⊥ = 0 :=
rfl
@[simp]
theorem toReal_zero : toReal 0 = 0 :=
rfl
@[simp]
theorem toReal_one : toReal 1 = 1 :=
rfl
@[simp]
theorem toReal_coe (x : ℝ) : toReal (x : EReal) = x :=
rfl
@[simp]
theorem bot_lt_coe (x : ℝ) : (⊥ : EReal) < x :=
WithBot.bot_lt_coe _
@[simp]
theorem coe_ne_bot (x : ℝ) : (x : EReal) ≠ ⊥ :=
(bot_lt_coe x).ne'
@[simp]
theorem bot_ne_coe (x : ℝ) : (⊥ : EReal) ≠ x :=
(bot_lt_coe x).ne
@[simp]
theorem coe_lt_top (x : ℝ) : (x : EReal) < ⊤ :=
WithBot.coe_lt_coe.2 <| WithTop.coe_lt_top _
@[simp]
theorem coe_ne_top (x : ℝ) : (x : EReal) ≠ ⊤ :=
(coe_lt_top x).ne
@[simp]
theorem top_ne_coe (x : ℝ) : (⊤ : EReal) ≠ x :=
(coe_lt_top x).ne'
@[simp]
theorem bot_lt_zero : (⊥ : EReal) < 0 :=
bot_lt_coe 0
@[simp]
theorem bot_ne_zero : (⊥ : EReal) ≠ 0 :=
(coe_ne_bot 0).symm
@[simp]
theorem zero_ne_bot : (0 : EReal) ≠ ⊥ :=
coe_ne_bot 0
@[simp]
theorem zero_lt_top : (0 : EReal) < ⊤ :=
coe_lt_top 0
@[simp]
theorem zero_ne_top : (0 : EReal) ≠ ⊤ :=
coe_ne_top 0
@[simp]
theorem top_ne_zero : (⊤ : EReal) ≠ 0 :=
(coe_ne_top 0).symm
theorem range_coe : range Real.toEReal = {⊥, ⊤}ᶜ := by
ext x
induction x <;> simp
theorem range_coe_eq_Ioo : range Real.toEReal = Ioo ⊥ ⊤ := by
ext x
induction x <;> simp
@[simp, norm_cast]
theorem coe_add (x y : ℝ) : (↑(x + y) : EReal) = x + y :=
rfl
-- `coe_mul` moved up
@[norm_cast]
theorem coe_nsmul (n : ℕ) (x : ℝ) : (↑(n • x) : EReal) = n • (x : EReal) :=
map_nsmul (⟨⟨Real.toEReal, coe_zero⟩, coe_add⟩ : ℝ →+ EReal) _ _
@[simp, norm_cast]
theorem coe_eq_zero {x : ℝ} : (x : EReal) = 0 ↔ x = 0 :=
EReal.coe_eq_coe_iff
@[simp, norm_cast]
theorem coe_eq_one {x : ℝ} : (x : EReal) = 1 ↔ x = 1 :=
EReal.coe_eq_coe_iff
theorem coe_ne_zero {x : ℝ} : (x : EReal) ≠ 0 ↔ x ≠ 0 :=
EReal.coe_ne_coe_iff
theorem coe_ne_one {x : ℝ} : (x : EReal) ≠ 1 ↔ x ≠ 1 :=
EReal.coe_ne_coe_iff
@[simp, norm_cast]
protected theorem coe_nonneg {x : ℝ} : (0 : EReal) ≤ x ↔ 0 ≤ x :=
EReal.coe_le_coe_iff
@[simp, norm_cast]
protected theorem coe_nonpos {x : ℝ} : (x : EReal) ≤ 0 ↔ x ≤ 0 :=
EReal.coe_le_coe_iff
@[simp, norm_cast]
protected theorem coe_pos {x : ℝ} : (0 : EReal) < x ↔ 0 < x :=
EReal.coe_lt_coe_iff
@[simp, norm_cast]
protected theorem coe_neg' {x : ℝ} : (x : EReal) < 0 ↔ x < 0 :=
EReal.coe_lt_coe_iff
lemma toReal_eq_zero_iff {x : EReal} : x.toReal = 0 ↔ x = 0 ∨ x = ⊤ ∨ x = ⊥ := by
cases x <;> norm_num
lemma toReal_ne_zero_iff {x : EReal} : x.toReal ≠ 0 ↔ x ≠ 0 ∧ x ≠ ⊤ ∧ x ≠ ⊥ := by
simp only [ne_eq, toReal_eq_zero_iff, not_or]
lemma toReal_eq_toReal {x y : EReal} (hx_top : x ≠ ⊤) (hx_bot : x ≠ ⊥)
(hy_top : y ≠ ⊤) (hy_bot : y ≠ ⊥) :
x.toReal = y.toReal ↔ x = y := by
lift x to ℝ using ⟨hx_top, hx_bot⟩
lift y to ℝ using ⟨hy_top, hy_bot⟩
simp
lemma toReal_nonneg {x : EReal} (hx : 0 ≤ x) : 0 ≤ x.toReal := by
cases x
· simp
· exact toReal_coe _ ▸ EReal.coe_nonneg.mp hx
· simp
lemma toReal_nonpos {x : EReal} (hx : x ≤ 0) : x.toReal ≤ 0 := by
cases x
· simp
· exact toReal_coe _ ▸ EReal.coe_nonpos.mp hx
· simp
theorem toReal_le_toReal {x y : EReal} (h : x ≤ y) (hx : x ≠ ⊥) (hy : y ≠ ⊤) :
x.toReal ≤ y.toReal := by
lift x to ℝ using ⟨ne_top_of_le_ne_top hy h, hx⟩
lift y to ℝ using ⟨hy, ne_bot_of_le_ne_bot hx h⟩
simpa using h
theorem coe_toReal {x : EReal} (hx : x ≠ ⊤) (h'x : x ≠ ⊥) : (x.toReal : EReal) = x := by
lift x to ℝ using ⟨hx, h'x⟩
rfl
theorem le_coe_toReal {x : EReal} (h : x ≠ ⊤) : x ≤ x.toReal := by
by_cases h' : x = ⊥
· simp only [h', bot_le]
· simp only [le_refl, coe_toReal h h']
theorem coe_toReal_le {x : EReal} (h : x ≠ ⊥) : ↑x.toReal ≤ x := by
by_cases h' : x = ⊤
· simp only [h', le_top]
· simp only [le_refl, coe_toReal h' h]
theorem eq_top_iff_forall_lt (x : EReal) : x = ⊤ ↔ ∀ y : ℝ, (y : EReal) < x := by
constructor
· rintro rfl
exact EReal.coe_lt_top
· contrapose!
intro h
exact ⟨x.toReal, le_coe_toReal h⟩
theorem eq_bot_iff_forall_lt (x : EReal) : x = ⊥ ↔ ∀ y : ℝ, x < (y : EReal) := by
constructor
· rintro rfl
exact bot_lt_coe
· contrapose!
intro h
exact ⟨x.toReal, coe_toReal_le h⟩
/-! ### Intervals and coercion from reals -/
lemma exists_between_coe_real {x z : EReal} (h : x < z) : ∃ y : ℝ, x < y ∧ y < z := by
obtain ⟨a, ha₁, ha₂⟩ := exists_between h
induction a with
| bot => exact (not_lt_bot ha₁).elim
| coe a₀ => exact ⟨a₀, ha₁, ha₂⟩
| top => exact (not_top_lt ha₂).elim
@[simp]
lemma image_coe_Icc (x y : ℝ) : Real.toEReal '' Icc x y = Icc ↑x ↑y := by
refine (image_comp WithBot.some WithTop.some _).trans ?_
rw [WithTop.image_coe_Icc, WithBot.image_coe_Icc]
rfl
@[simp]
lemma image_coe_Ico (x y : ℝ) : Real.toEReal '' Ico x y = Ico ↑x ↑y := by
refine (image_comp WithBot.some WithTop.some _).trans ?_
rw [WithTop.image_coe_Ico, WithBot.image_coe_Ico]
rfl
@[simp]
lemma image_coe_Ici (x : ℝ) : Real.toEReal '' Ici x = Ico ↑x ⊤ := by
refine (image_comp WithBot.some WithTop.some _).trans ?_
rw [WithTop.image_coe_Ici, WithBot.image_coe_Ico]
rfl
@[simp]
lemma image_coe_Ioc (x y : ℝ) : Real.toEReal '' Ioc x y = Ioc ↑x ↑y := by
refine (image_comp WithBot.some WithTop.some _).trans ?_
rw [WithTop.image_coe_Ioc, WithBot.image_coe_Ioc]
rfl
@[simp]
lemma image_coe_Ioo (x y : ℝ) : Real.toEReal '' Ioo x y = Ioo ↑x ↑y := by
refine (image_comp WithBot.some WithTop.some _).trans ?_
rw [WithTop.image_coe_Ioo, WithBot.image_coe_Ioo]
rfl
@[simp]
lemma image_coe_Ioi (x : ℝ) : Real.toEReal '' Ioi x = Ioo ↑x ⊤ := by
refine (image_comp WithBot.some WithTop.some _).trans ?_
rw [WithTop.image_coe_Ioi, WithBot.image_coe_Ioo]
rfl
@[simp]
lemma image_coe_Iic (x : ℝ) : Real.toEReal '' Iic x = Ioc ⊥ ↑x := by
refine (image_comp WithBot.some WithTop.some _).trans ?_
rw [WithTop.image_coe_Iic, WithBot.image_coe_Iic]
rfl
@[simp]
lemma image_coe_Iio (x : ℝ) : Real.toEReal '' Iio x = Ioo ⊥ ↑x := by
refine (image_comp WithBot.some WithTop.some _).trans ?_
rw [WithTop.image_coe_Iio, WithBot.image_coe_Iio]
rfl
@[simp]
lemma preimage_coe_Ici (x : ℝ) : Real.toEReal ⁻¹' Ici x = Ici x := by
change (WithBot.some ∘ WithTop.some) ⁻¹' (Ici (WithBot.some (WithTop.some x))) = _
refine preimage_comp.trans ?_
simp only [WithBot.preimage_coe_Ici, WithTop.preimage_coe_Ici]
@[simp]
lemma preimage_coe_Ioi (x : ℝ) : Real.toEReal ⁻¹' Ioi x = Ioi x := by
change (WithBot.some ∘ WithTop.some) ⁻¹' (Ioi (WithBot.some (WithTop.some x))) = _
refine preimage_comp.trans ?_
simp only [WithBot.preimage_coe_Ioi, WithTop.preimage_coe_Ioi]
@[simp]
lemma preimage_coe_Ioi_bot : Real.toEReal ⁻¹' Ioi ⊥ = univ := by
change (WithBot.some ∘ WithTop.some) ⁻¹' (Ioi ⊥) = _
refine preimage_comp.trans ?_
simp only [WithBot.preimage_coe_Ioi_bot, preimage_univ]
@[simp]
lemma preimage_coe_Iic (y : ℝ) : Real.toEReal ⁻¹' Iic y = Iic y := by
change (WithBot.some ∘ WithTop.some) ⁻¹' (Iic (WithBot.some (WithTop.some y))) = _
refine preimage_comp.trans ?_
simp only [WithBot.preimage_coe_Iic, WithTop.preimage_coe_Iic]
@[simp]
lemma preimage_coe_Iio (y : ℝ) : Real.toEReal ⁻¹' Iio y = Iio y := by
change (WithBot.some ∘ WithTop.some) ⁻¹' (Iio (WithBot.some (WithTop.some y))) = _
refine preimage_comp.trans ?_
simp only [WithBot.preimage_coe_Iio, WithTop.preimage_coe_Iio]
@[simp]
lemma preimage_coe_Iio_top : Real.toEReal ⁻¹' Iio ⊤ = univ := by
change (WithBot.some ∘ WithTop.some) ⁻¹' (Iio (WithBot.some ⊤)) = _
refine preimage_comp.trans ?_
simp only [WithBot.preimage_coe_Iio, WithTop.preimage_coe_Iio_top]
@[simp]
lemma preimage_coe_Icc (x y : ℝ) : Real.toEReal ⁻¹' Icc x y = Icc x y := by
simp_rw [← Ici_inter_Iic]
simp
@[simp]
lemma preimage_coe_Ico (x y : ℝ) : Real.toEReal ⁻¹' Ico x y = Ico x y := by
simp_rw [← Ici_inter_Iio]
simp
@[simp]
lemma preimage_coe_Ioc (x y : ℝ) : Real.toEReal ⁻¹' Ioc x y = Ioc x y := by
simp_rw [← Ioi_inter_Iic]
simp
@[simp]
lemma preimage_coe_Ioo (x y : ℝ) : Real.toEReal ⁻¹' Ioo x y = Ioo x y := by
simp_rw [← Ioi_inter_Iio]
simp
@[simp]
lemma preimage_coe_Ico_top (x : ℝ) : Real.toEReal ⁻¹' Ico x ⊤ = Ici x := by
rw [← Ici_inter_Iio]
simp
@[simp]
lemma preimage_coe_Ioo_top (x : ℝ) : Real.toEReal ⁻¹' Ioo x ⊤ = Ioi x := by
rw [← Ioi_inter_Iio]
simp
@[simp]
lemma preimage_coe_Ioc_bot (y : ℝ) : Real.toEReal ⁻¹' Ioc ⊥ y = Iic y := by
rw [← Ioi_inter_Iic]
simp
@[simp]
lemma preimage_coe_Ioo_bot (y : ℝ) : Real.toEReal ⁻¹' Ioo ⊥ y = Iio y := by
rw [← Ioi_inter_Iio]
simp
@[simp]
lemma preimage_coe_Ioo_bot_top : Real.toEReal ⁻¹' Ioo ⊥ ⊤ = univ := by
rw [← Ioi_inter_Iio]
simp
/-! ### ennreal coercion -/
@[simp]
theorem toReal_coe_ennreal : ∀ {x : ℝ≥0∞}, toReal (x : EReal) = ENNReal.toReal x
| ⊤ => rfl
| .some _ => rfl
@[simp]
theorem coe_ennreal_ofReal {x : ℝ} : (ENNReal.ofReal x : EReal) = max x 0 :=
rfl
lemma coe_ennreal_toReal {x : ℝ≥0∞} (hx : x ≠ ∞) : (x.toReal : EReal) = x := by
lift x to ℝ≥0 using hx
rfl
theorem coe_nnreal_eq_coe_real (x : ℝ≥0) : ((x : ℝ≥0∞) : EReal) = (x : ℝ) :=
rfl
@[simp, norm_cast]
theorem coe_ennreal_zero : ((0 : ℝ≥0∞) : EReal) = 0 :=
rfl
@[simp, norm_cast]
theorem coe_ennreal_one : ((1 : ℝ≥0∞) : EReal) = 1 :=
rfl
@[simp, norm_cast]
theorem coe_ennreal_top : ((⊤ : ℝ≥0∞) : EReal) = ⊤ :=
rfl
theorem coe_ennreal_strictMono : StrictMono ((↑) : ℝ≥0∞ → EReal) :=
WithTop.strictMono_iff.2 ⟨fun _ _ => EReal.coe_lt_coe_iff.2, fun _ => coe_lt_top _⟩
theorem coe_ennreal_injective : Injective ((↑) : ℝ≥0∞ → EReal) :=
coe_ennreal_strictMono.injective
@[simp]
theorem coe_ennreal_eq_top_iff {x : ℝ≥0∞} : (x : EReal) = ⊤ ↔ x = ⊤ :=
coe_ennreal_injective.eq_iff' rfl
theorem coe_nnreal_ne_top (x : ℝ≥0) : ((x : ℝ≥0∞) : EReal) ≠ ⊤ := coe_ne_top x
@[simp]
theorem coe_nnreal_lt_top (x : ℝ≥0) : ((x : ℝ≥0∞) : EReal) < ⊤ := coe_lt_top x
@[simp, norm_cast]
theorem coe_ennreal_le_coe_ennreal_iff {x y : ℝ≥0∞} : (x : EReal) ≤ (y : EReal) ↔ x ≤ y :=
coe_ennreal_strictMono.le_iff_le
@[simp, norm_cast]
theorem coe_ennreal_lt_coe_ennreal_iff {x y : ℝ≥0∞} : (x : EReal) < (y : EReal) ↔ x < y :=
coe_ennreal_strictMono.lt_iff_lt
@[simp, norm_cast]
theorem coe_ennreal_eq_coe_ennreal_iff {x y : ℝ≥0∞} : (x : EReal) = (y : EReal) ↔ x = y :=
coe_ennreal_injective.eq_iff
theorem coe_ennreal_ne_coe_ennreal_iff {x y : ℝ≥0∞} : (x : EReal) ≠ (y : EReal) ↔ x ≠ y :=
coe_ennreal_injective.ne_iff
@[simp, norm_cast]
theorem coe_ennreal_eq_zero {x : ℝ≥0∞} : (x : EReal) = 0 ↔ x = 0 := by
rw [← coe_ennreal_eq_coe_ennreal_iff, coe_ennreal_zero]
@[simp, norm_cast]
theorem coe_ennreal_eq_one {x : ℝ≥0∞} : (x : EReal) = 1 ↔ x = 1 := by
rw [← coe_ennreal_eq_coe_ennreal_iff, coe_ennreal_one]
@[norm_cast]
theorem coe_ennreal_ne_zero {x : ℝ≥0∞} : (x : EReal) ≠ 0 ↔ x ≠ 0 :=
coe_ennreal_eq_zero.not
@[norm_cast]
theorem coe_ennreal_ne_one {x : ℝ≥0∞} : (x : EReal) ≠ 1 ↔ x ≠ 1 :=
coe_ennreal_eq_one.not
theorem coe_ennreal_nonneg (x : ℝ≥0∞) : (0 : EReal) ≤ x :=
coe_ennreal_le_coe_ennreal_iff.2 (zero_le x)
@[simp] theorem range_coe_ennreal : range ((↑) : ℝ≥0∞ → EReal) = Set.Ici 0 :=
Subset.antisymm (range_subset_iff.2 coe_ennreal_nonneg) fun x => match x with
| ⊥ => fun h => absurd h bot_lt_zero.not_ge
| ⊤ => fun _ => ⟨⊤, rfl⟩
| (x : ℝ) => fun h => ⟨.some ⟨x, EReal.coe_nonneg.1 h⟩, rfl⟩
instance : CanLift EReal ℝ≥0∞ (↑) (0 ≤ ·) := ⟨range_coe_ennreal.ge⟩
@[simp, norm_cast]
theorem coe_ennreal_pos {x : ℝ≥0∞} : (0 : EReal) < x ↔ 0 < x := by
rw [← coe_ennreal_zero, coe_ennreal_lt_coe_ennreal_iff]
theorem coe_ennreal_pos_iff_ne_zero {x : ℝ≥0∞} : (0 : EReal) < x ↔ x ≠ 0 := by
rw [coe_ennreal_pos, pos_iff_ne_zero]
@[simp]
theorem bot_lt_coe_ennreal (x : ℝ≥0∞) : (⊥ : EReal) < x :=
(bot_lt_coe 0).trans_le (coe_ennreal_nonneg _)
@[simp]
theorem coe_ennreal_ne_bot (x : ℝ≥0∞) : (x : EReal) ≠ ⊥ :=
(bot_lt_coe_ennreal x).ne'
@[simp, norm_cast]
theorem coe_ennreal_add (x y : ENNReal) : ((x + y : ℝ≥0∞) : EReal) = x + y := by
cases x <;> cases y <;> rfl
private theorem coe_ennreal_top_mul (x : ℝ≥0) : ((⊤ * x : ℝ≥0∞) : EReal) = ⊤ * x := by
rcases eq_or_ne x 0 with (rfl | h0)
· simp
· rw [ENNReal.top_mul (ENNReal.coe_ne_zero.2 h0)]
exact Eq.symm <| if_pos <| NNReal.coe_pos.2 h0.bot_lt
@[simp, norm_cast]
theorem coe_ennreal_mul : ∀ x y : ℝ≥0∞, ((x * y : ℝ≥0∞) : EReal) = (x : EReal) * y
| ⊤, ⊤ => rfl
| ⊤, (y : ℝ≥0) => coe_ennreal_top_mul y
| (x : ℝ≥0), ⊤ => by
rw [mul_comm, coe_ennreal_top_mul, EReal.mul_comm, coe_ennreal_top]
| (x : ℝ≥0), (y : ℝ≥0) => by
simp only [← ENNReal.coe_mul, coe_nnreal_eq_coe_real, NNReal.coe_mul, EReal.coe_mul]
@[norm_cast]
theorem coe_ennreal_nsmul (n : ℕ) (x : ℝ≥0∞) : (↑(n • x) : EReal) = n • (x : EReal) :=
map_nsmul (⟨⟨(↑), coe_ennreal_zero⟩, coe_ennreal_add⟩ : ℝ≥0∞ →+ EReal) _ _
/-! ### toENNReal -/
/-- `x.toENNReal` returns `x` if it is nonnegative, `0` otherwise. -/
noncomputable def toENNReal (x : EReal) : ℝ≥0∞ :=
if x = ⊤ then ⊤
else ENNReal.ofReal x.toReal
@[simp] lemma toENNReal_top : (⊤ : EReal).toENNReal = ⊤ := rfl
@[simp]
lemma toENNReal_of_ne_top {x : EReal} (hx : x ≠ ⊤) : x.toENNReal = ENNReal.ofReal x.toReal :=
if_neg hx
@[simp]
lemma toENNReal_eq_top_iff {x : EReal} : x.toENNReal = ⊤ ↔ x = ⊤ := by
by_cases h : x = ⊤
· simp [h]
· simp [h, toENNReal]
lemma toENNReal_ne_top_iff {x : EReal} : x.toENNReal ≠ ⊤ ↔ x ≠ ⊤ := toENNReal_eq_top_iff.not
@[simp]
lemma toENNReal_of_nonpos {x : EReal} (hx : x ≤ 0) : x.toENNReal = 0 := by
rw [toENNReal, if_neg (fun h ↦ ?_)]
· exact ENNReal.ofReal_of_nonpos (toReal_nonpos hx)
· exact zero_ne_top <| top_le_iff.mp <| h ▸ hx
lemma toENNReal_bot : (⊥ : EReal).toENNReal = 0 := toENNReal_of_nonpos bot_le
lemma toENNReal_zero : (0 : EReal).toENNReal = 0 := toENNReal_of_nonpos le_rfl
lemma toENNReal_eq_zero_iff {x : EReal} : x.toENNReal = 0 ↔ x ≤ 0 := by
induction x <;> simp [toENNReal]
lemma toENNReal_ne_zero_iff {x : EReal} : x.toENNReal ≠ 0 ↔ 0 < x := by
simp [toENNReal_eq_zero_iff.not]
@[simp]
lemma toENNReal_pos_iff {x : EReal} : 0 < x.toENNReal ↔ 0 < x := by
rw [pos_iff_ne_zero, toENNReal_ne_zero_iff]
@[simp]
lemma coe_toENNReal {x : EReal} (hx : 0 ≤ x) : (x.toENNReal : EReal) = x := by
rw [toENNReal]
by_cases h_top : x = ⊤
· rw [if_pos h_top, h_top]
rfl
rw [if_neg h_top]
simp only [coe_ennreal_ofReal, hx, toReal_nonneg, max_eq_left]
exact coe_toReal h_top fun _ ↦ by simp_all only [le_bot_iff, zero_ne_bot]
lemma coe_toENNReal_eq_max {x : EReal} : x.toENNReal = max 0 x := by
rcases le_total 0 x with (hx | hx)
· rw [coe_toENNReal hx, max_eq_right hx]
· rw [toENNReal_of_nonpos hx, max_eq_left hx, coe_ennreal_zero]
@[simp]
lemma toENNReal_coe {x : ℝ≥0∞} : (x : EReal).toENNReal = x := by
by_cases h_top : x = ⊤
· rw [h_top, coe_ennreal_top, toENNReal_top]
rwa [toENNReal, if_neg _, toReal_coe_ennreal, ENNReal.ofReal_toReal_eq_iff]
simp [h_top]
@[simp] lemma real_coe_toENNReal (x : ℝ) : (x : EReal).toENNReal = ENNReal.ofReal x := rfl
@[simp]
lemma toReal_toENNReal {x : EReal} (hx : 0 ≤ x) : x.toENNReal.toReal = x.toReal := by
by_cases h : x = ⊤
· simp [h]
· simp [h, toReal_nonneg hx]
lemma toENNReal_eq_toENNReal {x y : EReal} (hx : 0 ≤ x) (hy : 0 ≤ y) :
x.toENNReal = y.toENNReal ↔ x = y := by
induction x <;> induction y <;> simp_all
lemma toENNReal_le_toENNReal {x y : EReal} (h : x ≤ y) : x.toENNReal ≤ y.toENNReal := by
induction x
· simp
· by_cases hy_top : y = ⊤
· simp [hy_top]
simp only [toENNReal, coe_ne_top, ↓reduceIte, toReal_coe, hy_top]
exact ENNReal.ofReal_le_ofReal <| EReal.toReal_le_toReal h (coe_ne_bot _) hy_top
· simp_all
lemma toENNReal_lt_toENNReal {x y : EReal} (hx : 0 ≤ x) (hxy : x < y) :
x.toENNReal < y.toENNReal :=
lt_of_le_of_ne (toENNReal_le_toENNReal hxy.le)
fun h ↦ hxy.ne <| (toENNReal_eq_toENNReal hx (hx.trans_lt hxy).le).mp h
/-! ### nat coercion -/
theorem coe_coe_eq_natCast (n : ℕ) : (n : ℝ) = (n : EReal) := rfl
theorem natCast_ne_bot (n : ℕ) : (n : EReal) ≠ ⊥ := Ne.symm (ne_of_beq_false rfl)
theorem natCast_ne_top (n : ℕ) : (n : EReal) ≠ ⊤ := Ne.symm (ne_of_beq_false rfl)
@[norm_cast]
theorem natCast_eq_iff {m n : ℕ} : (m : EReal) = (n : EReal) ↔ m = n := by
rw [← coe_coe_eq_natCast n, ← coe_coe_eq_natCast m, EReal.coe_eq_coe_iff, Nat.cast_inj]
theorem natCast_ne_iff {m n : ℕ} : (m : EReal) ≠ (n : EReal) ↔ m ≠ n :=
not_iff_not.2 natCast_eq_iff
@[norm_cast]
theorem natCast_le_iff {m n : ℕ} : (m : EReal) ≤ (n : EReal) ↔ m ≤ n := by
rw [← coe_coe_eq_natCast n, ← coe_coe_eq_natCast m, EReal.coe_le_coe_iff, Nat.cast_le]
@[norm_cast]
theorem natCast_lt_iff {m n : ℕ} : (m : EReal) < (n : EReal) ↔ m < n := by
rw [← coe_coe_eq_natCast n, ← coe_coe_eq_natCast m, EReal.coe_lt_coe_iff, Nat.cast_lt]
@[simp, norm_cast]
theorem natCast_mul (m n : ℕ) :
(m * n : ℕ) = (m : EReal) * (n : EReal) := by
rw [← coe_coe_eq_natCast, ← coe_coe_eq_natCast, ← coe_coe_eq_natCast, Nat.cast_mul, EReal.coe_mul]
/-! ### Miscellaneous lemmas -/
theorem exists_rat_btwn_of_lt :
∀ {a b : EReal}, a < b → ∃ x : ℚ, a < (x : ℝ) ∧ ((x : ℝ) : EReal) < b
| ⊤, _, h => (not_top_lt h).elim
| (a : ℝ), ⊥, h => (lt_irrefl _ ((bot_lt_coe a).trans h)).elim
| (a : ℝ), (b : ℝ), h => by simp [exists_rat_btwn (EReal.coe_lt_coe_iff.1 h)]
| (a : ℝ), ⊤, _ =>
let ⟨b, hab⟩ := exists_rat_gt a
⟨b, by simpa using hab, coe_lt_top _⟩
| ⊥, ⊥, h => (lt_irrefl _ h).elim
| ⊥, (a : ℝ), _ =>
let ⟨b, hab⟩ := exists_rat_lt a
⟨b, bot_lt_coe _, by simpa using hab⟩
| ⊥, ⊤, _ => ⟨0, bot_lt_coe _, coe_lt_top _⟩
theorem lt_iff_exists_rat_btwn {a b : EReal} :
a < b ↔ ∃ x : ℚ, a < (x : ℝ) ∧ ((x : ℝ) : EReal) < b :=
⟨fun hab => exists_rat_btwn_of_lt hab, fun ⟨_x, ax, xb⟩ => ax.trans xb⟩
theorem lt_iff_exists_real_btwn {a b : EReal} : a < b ↔ ∃ x : ℝ, a < x ∧ (x : EReal) < b :=
⟨fun hab =>
let ⟨x, ax, xb⟩ := exists_rat_btwn_of_lt hab
⟨(x : ℝ), ax, xb⟩,
fun ⟨_x, ax, xb⟩ => ax.trans xb⟩
/-- The set of numbers in `EReal` that are not equal to `±∞` is equivalent to `ℝ`. -/
def neTopBotEquivReal : ({⊥, ⊤}ᶜ : Set EReal) ≃ ℝ where
toFun x := EReal.toReal x
invFun x := ⟨x, by simp⟩
left_inv := fun ⟨x, hx⟩ => by
lift x to ℝ
· simpa [not_or, and_comm] using hx
· simp
right_inv x := by simp
end EReal
namespace Mathlib.Meta.Positivity
open Lean Meta Qq Function
/-- Extension for the `positivity` tactic: cast from `ℝ` to `EReal`. -/
@[positivity Real.toEReal _]
def evalRealToEReal : PositivityExt where eval {u α} _zα _pα e := do
match u, α, e with
| 0, ~q(EReal), ~q(Real.toEReal $a) =>
let ra ← core q(inferInstance) q(inferInstance) a
assertInstancesCommute
match ra with
| .positive pa => pure (.positive q(EReal.coe_pos.2 $pa))
| .nonnegative pa => pure (.nonnegative q(EReal.coe_nonneg.2 $pa))
| .nonzero pa => pure (.nonzero q(EReal.coe_ne_zero.2 $pa))
| _ => pure .none
| _, _, _ => throwError "not Real.toEReal"
/-- Extension for the `positivity` tactic: cast from `ℝ≥0∞` to `EReal`. -/
@[positivity ENNReal.toEReal _]
def evalENNRealToEReal : PositivityExt where eval {u α} _zα _pα e := do
match u, α, e with
| 0, ~q(EReal), ~q(ENNReal.toEReal $a) =>
let ra ← core q(inferInstance) q(inferInstance) a
assertInstancesCommute
match ra with
| .positive pa => pure (.positive q(EReal.coe_ennreal_pos.2 $pa))
| .nonzero pa => pure (.positive q(EReal.coe_ennreal_pos_iff_ne_zero.2 $pa))
| _ => pure (.nonnegative q(EReal.coe_ennreal_nonneg $a))
| _, _, _ => throwError "not ENNReal.toEReal"
/-- Extension for the `positivity` tactic: projection from `EReal` to `ℝ`.
We prove that `EReal.toReal x` is nonnegative whenever `x` is nonnegative.
Since `EReal.toReal ⊤ = 0`, we cannot prove a stronger statement,
at least without relying on a tactic like `finiteness`. -/
@[positivity EReal.toReal _]
def evalERealToReal : PositivityExt where eval {u α} _zα _pα e := do
match u, α, e with
| 0, ~q(Real), ~q(EReal.toReal $a) =>
assertInstancesCommute
match (← core q(inferInstance) q(inferInstance) a).toNonneg with
| .some pa => pure (.nonnegative q(EReal.toReal_nonneg $pa))
| _ => pure .none
| _, _, _ => throwError "not EReal.toReal"
/-- Extension for the `positivity` tactic: projection from `EReal` to `ℝ≥0∞`.
We show that `EReal.toENNReal x` is positive whenever `x` is positive,
and it is nonnegative otherwise.
We cannot deduce any corollaries from `x ≠ 0`, since `EReal.toENNReal x = 0` for `x < 0`.
-/
@[positivity EReal.toENNReal _]
def evalERealToENNReal : PositivityExt where eval {u α} _zα _pα e := do
match u, α, e with
| 0, ~q(ENNReal), ~q(EReal.toENNReal $a) =>
assertInstancesCommute
match ← core q(inferInstance) q(inferInstance) a with
| .positive pa => pure (.positive q(EReal.toENNReal_pos_iff.2 $pa))
| _ => pure (.nonnegative q(zero_le $e))
| _, _, _ => throwError "not EReal.toENNReal"
end Mathlib.Meta.Positivity |
.lake/packages/mathlib/Mathlib/Data/EReal/Operations.lean | import Mathlib.Data.EReal.Basic
/-!
# Addition, negation, subtraction and multiplication on extended real numbers
Addition and multiplication in `EReal` are problematic in the presence of `±∞`, but negation has
a natural definition and satisfies the usual properties. In particular, it is an order-reversing
isomorphism.
The construction of `EReal` as `WithBot (WithTop ℝ)` endows a `LinearOrderedAddCommMonoid` structure
on it. However, addition is badly behaved at `(⊥, ⊤)` and `(⊤, ⊥)`, so this cannot be upgraded to a
group structure. Our choice is that `⊥ + ⊤ = ⊤ + ⊥ = ⊥`, to make sure that the exponential and
logarithm between `EReal` and `ℝ≥0∞` respect the operations. Note that the convention `0 * ∞ = 0`
on `ℝ≥0∞` is enforced by measure theory. Subtraction, defined as `x - y = x + (-y)`, does not have
nice properties but is sometimes convenient to have.
There is also a `CommMonoidWithZero` structure on `EReal`, but `Mathlib/Data/EReal/Basic.lean` only
provides `MulZeroOneClass` because a proof of associativity by hand would have 125 cases.
The `CommMonoidWithZero` instance is instead delivered in `Mathlib/Data/EReal/Inv.lean`.
We define `0 * x = x * 0 = 0` for any `x`, with the other cases defined non-ambiguously.
This does not distribute with addition, as `⊥ = ⊥ + ⊤ = 1 * ⊥ + (-1) * ⊥ ≠ (1 - 1) * ⊥ = 0 * ⊥ = 0`.
Distributivity `x * (y + z) = x * y + x * z` is recovered in the case where either `0 ≤ x < ⊤`,
see `EReal.left_distrib_of_nonneg_of_ne_top`, or `0 ≤ y, z`. See `EReal.left_distrib_of_nonneg`
(similarly for right distributivity).
-/
open ENNReal NNReal
noncomputable section
namespace EReal
/-! ### Addition -/
@[simp]
theorem add_bot (x : EReal) : x + ⊥ = ⊥ :=
WithBot.add_bot _
@[simp]
theorem bot_add (x : EReal) : ⊥ + x = ⊥ :=
WithBot.bot_add _
@[simp]
theorem add_eq_bot_iff {x y : EReal} : x + y = ⊥ ↔ x = ⊥ ∨ y = ⊥ :=
WithBot.add_eq_bot
lemma add_ne_bot_iff {x y : EReal} : x + y ≠ ⊥ ↔ x ≠ ⊥ ∧ y ≠ ⊥ := WithBot.add_ne_bot
@[simp]
theorem bot_lt_add_iff {x y : EReal} : ⊥ < x + y ↔ ⊥ < x ∧ ⊥ < y := by
simp [bot_lt_iff_ne_bot]
@[simp]
theorem top_add_top : (⊤ : EReal) + ⊤ = ⊤ :=
rfl
@[simp]
theorem top_add_coe (x : ℝ) : (⊤ : EReal) + x = ⊤ :=
rfl
/-- For any extended real number `x` which is not `⊥`, the sum of `⊤` and `x` is equal to `⊤`. -/
@[simp]
theorem top_add_of_ne_bot {x : EReal} (h : x ≠ ⊥) : ⊤ + x = ⊤ := by
induction x
· exfalso; exact h (Eq.refl ⊥)
· exact top_add_coe _
· exact top_add_top
/-- For any extended real number `x`, the sum of `⊤` and `x` is equal to `⊤`
if and only if `x` is not `⊥`. -/
theorem top_add_iff_ne_bot {x : EReal} : ⊤ + x = ⊤ ↔ x ≠ ⊥ := by
constructor <;> intro h
· rintro rfl
rw [add_bot] at h
exact bot_ne_top h
· cases x with
| bot => contradiction
| top => rfl
| coe r => exact top_add_of_ne_bot h
/-- For any extended real number `x` which is not `⊥`, the sum of `x` and `⊤` is equal to `⊤`. -/
@[simp]
theorem add_top_of_ne_bot {x : EReal} (h : x ≠ ⊥) : x + ⊤ = ⊤ := by
rw [add_comm, top_add_of_ne_bot h]
/-- For any extended real number `x`, the sum of `x` and `⊤` is equal to `⊤`
if and only if `x` is not `⊥`. -/
theorem add_top_iff_ne_bot {x : EReal} : x + ⊤ = ⊤ ↔ x ≠ ⊥ := by rw [add_comm, top_add_iff_ne_bot]
@[deprecated (since := "2025-08-14")] alias add_pos_of_nonneg_of_pos :=
Right.add_pos_of_nonneg_of_pos
protected theorem add_pos_of_pos_of_nonneg {a b : EReal} (ha : 0 < a) (hb : 0 ≤ b) : 0 < a + b :=
add_comm a b ▸ Right.add_pos_of_nonneg_of_pos hb ha
/-- For any two extended real numbers `a` and `b`, if both `a` and `b` are greater than `0`,
then their sum is also greater than `0`. -/
protected theorem add_pos {a b : EReal} (ha : 0 < a) (hb : 0 < b) : 0 < a + b :=
Right.add_pos_of_nonneg_of_pos ha.le hb
@[simp]
theorem coe_add_top (x : ℝ) : (x : EReal) + ⊤ = ⊤ :=
rfl
theorem toReal_add {x y : EReal} (hx : x ≠ ⊤) (h'x : x ≠ ⊥) (hy : y ≠ ⊤) (h'y : y ≠ ⊥) :
toReal (x + y) = toReal x + toReal y := by
lift x to ℝ using ⟨hx, h'x⟩
lift y to ℝ using ⟨hy, h'y⟩
rfl
lemma toENNReal_add {x y : EReal} (hx : 0 ≤ x) (hy : 0 ≤ y) :
(x + y).toENNReal = x.toENNReal + y.toENNReal := by
induction x <;> induction y <;> try {· simp_all}
norm_cast
simp_rw [real_coe_toENNReal]
simp_all [ENNReal.ofReal_add]
lemma toENNReal_add_le {x y : EReal} : (x + y).toENNReal ≤ x.toENNReal + y.toENNReal := by
induction x <;> induction y <;> try {· simp}
exact ENNReal.ofReal_add_le
theorem addLECancellable_coe (x : ℝ) : AddLECancellable (x : EReal)
| _, ⊤, _ => le_top
| ⊥, _, _ => bot_le
| ⊤, (z : ℝ), h => by simp only [coe_add_top, ← coe_add, top_le_iff, coe_ne_top] at h
| _, ⊥, h => by simpa using h
| (y : ℝ), (z : ℝ), h => by
simpa only [← coe_add, EReal.coe_le_coe_iff, add_le_add_iff_left] using h
-- TODO: add `MulLECancellable.strictMono*` etc
theorem add_lt_add_right_coe {x y : EReal} (h : x < y) (z : ℝ) : x + z < y + z :=
not_le.1 <| mt (addLECancellable_coe z).add_le_add_iff_right.1 h.not_ge
theorem add_lt_add_left_coe {x y : EReal} (h : x < y) (z : ℝ) : (z : EReal) + x < z + y := by
simpa [add_comm] using add_lt_add_right_coe h z
theorem add_lt_add {x y z t : EReal} (h1 : x < y) (h2 : z < t) : x + z < y + t := by
rcases eq_or_ne x ⊥ with (rfl | hx)
· simp [h1, bot_le.trans_lt h2]
· lift x to ℝ using ⟨h1.ne_top, hx⟩
calc (x : EReal) + z < x + t := add_lt_add_left_coe h2 _
_ ≤ y + t := by gcongr
theorem add_lt_add_of_lt_of_le' {x y z t : EReal} (h : x < y) (h' : z ≤ t) (hbot : t ≠ ⊥)
(htop : t = ⊤ → z = ⊤ → x = ⊥) : x + z < y + t := by
rcases h'.eq_or_lt with (rfl | hlt)
· rcases eq_or_ne z ⊤ with (rfl | hz)
· obtain rfl := htop rfl rfl
simpa
lift z to ℝ using ⟨hz, hbot⟩
exact add_lt_add_right_coe h z
· exact add_lt_add h hlt
/-- See also `EReal.add_lt_add_of_lt_of_le'` for a version with weaker but less convenient
assumptions. -/
theorem add_lt_add_of_lt_of_le {x y z t : EReal} (h : x < y) (h' : z ≤ t) (hz : z ≠ ⊥)
(ht : t ≠ ⊤) : x + z < y + t :=
add_lt_add_of_lt_of_le' h h' (ne_bot_of_le_ne_bot hz h') fun ht' => (ht ht').elim
theorem add_lt_top {x y : EReal} (hx : x ≠ ⊤) (hy : y ≠ ⊤) : x + y < ⊤ :=
add_lt_add hx.lt_top hy.lt_top
lemma add_ne_top {x y : EReal} (hx : x ≠ ⊤) (hy : y ≠ ⊤) : x + y ≠ ⊤ :=
lt_top_iff_ne_top.mp <| add_lt_top hx hy
lemma add_ne_top_iff_ne_top₂ {x y : EReal} (hx : x ≠ ⊥) (hy : y ≠ ⊥) :
x + y ≠ ⊤ ↔ x ≠ ⊤ ∧ y ≠ ⊤ := by
refine ⟨?_, fun h ↦ add_ne_top h.1 h.2⟩
cases x <;> simp_all only [ne_eq, not_false_eq_true, top_add_of_ne_bot, not_true_eq_false,
IsEmpty.forall_iff]
cases y <;> simp_all only [not_false_eq_true, ne_eq, add_top_of_ne_bot, not_true_eq_false,
coe_ne_top, and_self, implies_true]
lemma add_ne_top_iff_ne_top_left {x y : EReal} (hy : y ≠ ⊥) (hy' : y ≠ ⊤) :
x + y ≠ ⊤ ↔ x ≠ ⊤ := by
cases x <;> simp [add_ne_top_iff_ne_top₂, hy, hy']
lemma add_ne_top_iff_ne_top_right {x y : EReal} (hx : x ≠ ⊥) (hx' : x ≠ ⊤) :
x + y ≠ ⊤ ↔ y ≠ ⊤ := add_comm x y ▸ add_ne_top_iff_ne_top_left hx hx'
@[deprecated (since := "2025-08-14")] alias add_ne_top_iff_of_ne_bot := add_ne_top_iff_ne_top₂
lemma add_ne_top_iff_of_ne_bot_of_ne_top {x y : EReal} (hy : y ≠ ⊥) (hy' : y ≠ ⊤) :
x + y ≠ ⊤ ↔ x ≠ ⊤ := by
induction x <;> simp [EReal.add_ne_top_iff_ne_top₂, hy, hy']
/-- We do not have a notion of `LinearOrderedAddCommMonoidWithBot` but we can at least make
the order dual of the extended reals into a `LinearOrderedAddCommMonoidWithTop`. -/
instance : LinearOrderedAddCommMonoidWithTop ERealᵒᵈ where
le_top := by simp
top_add' := by
rw [OrderDual.forall]
intro x
rw [← OrderDual.toDual_bot, ← toDual_add, bot_add, OrderDual.toDual_bot]
/-! ### Negation -/
/-- negation on `EReal` -/
protected def neg : EReal → EReal
| ⊥ => ⊤
| ⊤ => ⊥
| (x : ℝ) => (-x : ℝ)
instance : Neg EReal := ⟨EReal.neg⟩
instance : SubNegZeroMonoid EReal where
neg_zero := congr_arg Real.toEReal neg_zero
zsmul := zsmulRec
@[simp]
theorem neg_top : -(⊤ : EReal) = ⊥ :=
rfl
@[simp]
theorem neg_bot : -(⊥ : EReal) = ⊤ :=
rfl
@[simp, norm_cast] theorem coe_neg (x : ℝ) : (↑(-x) : EReal) = -↑x := rfl
@[simp, norm_cast] theorem coe_sub (x y : ℝ) : (↑(x - y) : EReal) = x - y := rfl
@[norm_cast]
theorem coe_zsmul (n : ℤ) (x : ℝ) : (↑(n • x) : EReal) = n • (x : EReal) :=
map_zsmul' (⟨⟨(↑), coe_zero⟩, coe_add⟩ : ℝ →+ EReal) coe_neg _ _
instance : InvolutiveNeg EReal where
neg_neg a :=
match a with
| ⊥ => rfl
| ⊤ => rfl
| (a : ℝ) => congr_arg Real.toEReal (neg_neg a)
@[simp]
theorem toReal_neg : ∀ {a : EReal}, toReal (-a) = -toReal a
| ⊤ => by simp
| ⊥ => by simp
| (x : ℝ) => rfl
@[simp]
theorem neg_eq_top_iff {x : EReal} : -x = ⊤ ↔ x = ⊥ :=
neg_injective.eq_iff' rfl
@[simp]
theorem neg_eq_bot_iff {x : EReal} : -x = ⊥ ↔ x = ⊤ :=
neg_injective.eq_iff' rfl
@[simp]
theorem neg_eq_zero_iff {x : EReal} : -x = 0 ↔ x = 0 :=
neg_injective.eq_iff' neg_zero
theorem neg_strictAnti : StrictAnti (- · : EReal → EReal) :=
WithBot.strictAnti_iff.2 ⟨WithTop.strictAnti_iff.2
⟨coe_strictMono.comp_strictAnti fun _ _ => neg_lt_neg, fun _ => bot_lt_coe _⟩,
WithTop.forall.2 ⟨bot_lt_top, fun _ => coe_lt_top _⟩⟩
@[simp] theorem neg_le_neg_iff {a b : EReal} : -a ≤ -b ↔ b ≤ a := neg_strictAnti.le_iff_ge
@[simp] theorem neg_lt_neg_iff {a b : EReal} : -a < -b ↔ b < a := neg_strictAnti.lt_iff_gt
/-- `-a ≤ b` if and only if `-b ≤ a` on `EReal`. -/
protected theorem neg_le {a b : EReal} : -a ≤ b ↔ -b ≤ a := by
rw [← neg_le_neg_iff, neg_neg]
/-- If `-a ≤ b` then `-b ≤ a` on `EReal`. -/
protected theorem neg_le_of_neg_le {a b : EReal} (h : -a ≤ b) : -b ≤ a := EReal.neg_le.mp h
/-- `a ≤ -b` if and only if `b ≤ -a` on `EReal`. -/
protected theorem le_neg {a b : EReal} : a ≤ -b ↔ b ≤ -a := by
rw [← neg_le_neg_iff, neg_neg]
/-- If `a ≤ -b` then `b ≤ -a` on `EReal`. -/
protected theorem le_neg_of_le_neg {a b : EReal} (h : a ≤ -b) : b ≤ -a := EReal.le_neg.mp h
/-- `-a < b` if and only if `-b < a` on `EReal`. -/
theorem neg_lt_comm {a b : EReal} : -a < b ↔ -b < a := by rw [← neg_lt_neg_iff, neg_neg]
/-- If `-a < b` then `-b < a` on `EReal`. -/
protected theorem neg_lt_of_neg_lt {a b : EReal} (h : -a < b) : -b < a := neg_lt_comm.mp h
/-- `-a < b` if and only if `-b < a` on `EReal`. -/
theorem lt_neg_comm {a b : EReal} : a < -b ↔ b < -a := by
rw [← neg_lt_neg_iff, neg_neg]
@[simp] protected theorem neg_lt_zero {a : EReal} : -a < 0 ↔ 0 < a := by rw [neg_lt_comm, neg_zero]
@[simp] protected theorem neg_le_zero {a : EReal} : -a ≤ 0 ↔ 0 ≤ a := by rw [EReal.neg_le, neg_zero]
@[simp] protected theorem neg_pos {a : EReal} : 0 < -a ↔ a < 0 := by rw [lt_neg_comm, neg_zero]
@[simp] protected theorem neg_nonneg {a : EReal} : 0 ≤ -a ↔ a ≤ 0 := by rw [EReal.le_neg, neg_zero]
/-- If `a < -b` then `b < -a` on `EReal`. -/
protected theorem lt_neg_of_lt_neg {a b : EReal} (h : a < -b) : b < -a := lt_neg_comm.mp h
/-- Negation as an order reversing isomorphism on `EReal`. -/
def negOrderIso : EReal ≃o ERealᵒᵈ :=
{ Equiv.neg EReal with
toFun := fun x => OrderDual.toDual (-x)
invFun := fun x => -OrderDual.ofDual x
map_rel_iff' := neg_le_neg_iff }
lemma neg_add {x y : EReal} (h1 : x ≠ ⊥ ∨ y ≠ ⊤) (h2 : x ≠ ⊤ ∨ y ≠ ⊥) :
-(x + y) = -x - y := by
induction x <;> induction y <;> try tauto
rw [← coe_add, ← coe_neg, ← coe_neg, ← coe_sub, neg_add']
lemma neg_sub {x y : EReal} (h1 : x ≠ ⊥ ∨ y ≠ ⊥) (h2 : x ≠ ⊤ ∨ y ≠ ⊤) :
-(x - y) = -x + y := by
rw [sub_eq_add_neg, neg_add _ _, sub_eq_add_neg, neg_neg] <;> simp_all
/-- Induction principle for `EReal`s splitting into cases `↑(x : ℝ≥0∞)` and `-↑(x : ℝ≥0∞)`.
In the latter case, we additionally assume `0 < x`. -/
@[elab_as_elim]
def recENNReal {motive : EReal → Sort*} (coe : ∀ x : ℝ≥0∞, motive x)
(neg_coe : ∀ x : ℝ≥0∞, 0 < x → motive (-x)) (x : EReal) : motive x :=
if hx : 0 ≤ x then coe_toENNReal hx ▸ coe _
else
haveI H₁ : 0 < -x := by simpa using hx
haveI H₂ : x = -(-x).toENNReal := by rw [coe_toENNReal H₁.le, neg_neg]
H₂ ▸ neg_coe _ <| by positivity
@[simp]
theorem recENNReal_coe_ennreal {motive : EReal → Sort*} (coe : ∀ x : ℝ≥0∞, motive x)
(neg_coe : ∀ x : ℝ≥0∞, 0 < x → motive (-x)) (x : ℝ≥0∞) : recENNReal coe neg_coe x = coe x := by
suffices ∀ y : EReal, x = y → (recENNReal coe neg_coe y : motive y) ≍ coe x from
heq_iff_eq.mp (this x rfl)
intro y hy
have H₁ : 0 ≤ y := hy ▸ coe_ennreal_nonneg x
obtain rfl : y.toENNReal = x := by simp [← hy]
simp [recENNReal, H₁]
proof_wanted recENNReal_neg_coe_ennreal {motive : EReal → Sort*} (coe : ∀ x : ℝ≥0∞, motive x)
(neg_coe : ∀ x : ℝ≥0∞, 0 < x → motive (-x)) {x : ℝ≥0∞} (hx : 0 < x) :
recENNReal coe neg_coe (-x) = neg_coe x hx
/-!
### Subtraction
Subtraction on `EReal` is defined by `x - y = x + (-y)`. Since addition is badly behaved at some
points, so is subtraction. There is no standard algebraic typeclass involving subtraction that is
registered on `EReal`, beyond `SubNegZeroMonoid`, because of this bad behavior.
-/
@[simp]
theorem bot_sub (x : EReal) : ⊥ - x = ⊥ :=
bot_add x
@[simp]
theorem sub_top (x : EReal) : x - ⊤ = ⊥ :=
add_bot x
@[simp]
theorem top_sub_bot : (⊤ : EReal) - ⊥ = ⊤ :=
rfl
@[simp]
theorem top_sub_coe (x : ℝ) : (⊤ : EReal) - x = ⊤ :=
rfl
@[simp]
theorem coe_sub_bot (x : ℝ) : (x : EReal) - ⊥ = ⊤ :=
rfl
@[simp]
lemma sub_bot {x : EReal} (h : x ≠ ⊥) : x - ⊥ = ⊤ := by
cases x <;> tauto
@[simp]
lemma top_sub {x : EReal} (hx : x ≠ ⊤) : ⊤ - x = ⊤ := by
cases x <;> tauto
@[simp]
lemma sub_self {x : EReal} (h_top : x ≠ ⊤) (h_bot : x ≠ ⊥) : x - x = 0 := by
cases x <;> simp_all [← coe_sub]
lemma sub_self_le_zero {x : EReal} : x - x ≤ 0 := by
cases x <;> simp
lemma sub_nonneg {x y : EReal} (h_top : x ≠ ⊤ ∨ y ≠ ⊤) (h_bot : x ≠ ⊥ ∨ y ≠ ⊥) :
0 ≤ x - y ↔ y ≤ x := by
cases x <;> cases y <;> simp_all [← EReal.coe_sub]
lemma sub_nonpos {x y : EReal} : x - y ≤ 0 ↔ x ≤ y := by
cases x <;> cases y <;> simp [← EReal.coe_sub]
lemma sub_pos {x y : EReal} : 0 < x - y ↔ y < x := by
cases x <;> cases y <;> simp [← EReal.coe_sub]
lemma sub_neg {x y : EReal} (h_top : x ≠ ⊤ ∨ y ≠ ⊤) (h_bot : x ≠ ⊥ ∨ y ≠ ⊥) :
x - y < 0 ↔ x < y := by
cases x <;> cases y <;> simp_all [← EReal.coe_sub]
theorem sub_le_sub {x y z t : EReal} (h : x ≤ y) (h' : t ≤ z) : x - z ≤ y - t :=
add_le_add h (neg_le_neg_iff.2 h')
theorem sub_lt_sub_of_lt_of_le {x y z t : EReal} (h : x < y) (h' : z ≤ t) (hz : z ≠ ⊥)
(ht : t ≠ ⊤) : x - t < y - z :=
add_lt_add_of_lt_of_le h (neg_le_neg_iff.2 h') (by simp [ht]) (by simp [hz])
theorem coe_real_ereal_eq_coe_toNNReal_sub_coe_toNNReal (x : ℝ) :
(x : EReal) = Real.toNNReal x - Real.toNNReal (-x) := by
rcases le_total 0 x with (h | h)
· lift x to ℝ≥0 using h
rw [Real.toNNReal_of_nonpos (neg_nonpos.mpr x.coe_nonneg), Real.toNNReal_coe, ENNReal.coe_zero,
coe_ennreal_zero, sub_zero]
rfl
· rw [Real.toNNReal_of_nonpos h, ENNReal.coe_zero, coe_ennreal_zero, coe_nnreal_eq_coe_real,
Real.coe_toNNReal, zero_sub, coe_neg, neg_neg]
exact neg_nonneg.2 h
theorem toReal_sub {x y : EReal} (hx : x ≠ ⊤) (h'x : x ≠ ⊥) (hy : y ≠ ⊤) (h'y : y ≠ ⊥) :
toReal (x - y) = toReal x - toReal y := by
lift x to ℝ using ⟨hx, h'x⟩
lift y to ℝ using ⟨hy, h'y⟩
rfl
lemma toENNReal_sub {x y : EReal} (hy : 0 ≤ y) :
(x - y).toENNReal = x.toENNReal - y.toENNReal := by
induction x <;> induction y <;> try {· simp_all [zero_tsub, ENNReal.sub_top]}
rename_i x y
by_cases hxy : x ≤ y
· rw [toENNReal_of_nonpos <| sub_nonpos.mpr <| EReal.coe_le_coe_iff.mpr hxy]
exact (tsub_eq_zero_of_le <| toENNReal_le_toENNReal <| EReal.coe_le_coe_iff.mpr hxy).symm
· rw [toENNReal_of_ne_top (ne_of_beq_false rfl).symm, ← coe_sub, toReal_coe,
ofReal_sub x (EReal.coe_nonneg.mp hy)]
simp
lemma add_sub_cancel_right {a : EReal} {b : Real} : a + b - b = a := by
cases a <;> norm_cast
exact _root_.add_sub_cancel_right _ _
lemma add_sub_cancel_left {a : EReal} {b : Real} : b + a - b = a := by
rw [add_comm, EReal.add_sub_cancel_right]
lemma sub_add_cancel {a : EReal} {b : Real} : a - b + b = a := by
rw [add_comm, ← add_sub_assoc, add_sub_cancel_left]
lemma sub_add_cancel_right {a : EReal} {b : Real} : b - (a + b) = -a := by
cases a <;> norm_cast
exact _root_.sub_add_cancel_right _ _
lemma sub_add_cancel_left {a : EReal} {b : Real} : b - (b + a) = -a := by
rw [add_comm, sub_add_cancel_right]
lemma le_sub_iff_add_le {a b c : EReal} (hb : b ≠ ⊥ ∨ c ≠ ⊥) (ht : b ≠ ⊤ ∨ c ≠ ⊤) :
a ≤ c - b ↔ a + b ≤ c := by
induction b with
| bot =>
simp only [ne_eq, not_true_eq_false, false_or] at hb
simp only [sub_bot hb, le_top, add_bot, bot_le]
| coe b =>
rw [← (addLECancellable_coe b).add_le_add_iff_right, sub_add_cancel]
| top =>
simp only [ne_eq, not_true_eq_false, false_or, sub_top, le_bot_iff] at ht ⊢
refine ⟨fun h ↦ h ▸ (bot_add ⊤).symm ▸ bot_le, fun h ↦ ?_⟩
by_contra ha
exact (h.trans_lt (Ne.lt_top ht)).ne (add_top_iff_ne_bot.2 ha)
lemma sub_le_iff_le_add {a b c : EReal} (h₁ : b ≠ ⊥ ∨ c ≠ ⊤) (h₂ : b ≠ ⊤ ∨ c ≠ ⊥) :
a - b ≤ c ↔ a ≤ c + b := by
suffices a + (-b) ≤ c ↔ a ≤ c - (-b) by simpa [sub_eq_add_neg]
refine (le_sub_iff_add_le ?_ ?_).symm <;> simpa
protected theorem lt_sub_iff_add_lt {a b c : EReal} (h₁ : b ≠ ⊥ ∨ c ≠ ⊤) (h₂ : b ≠ ⊤ ∨ c ≠ ⊥) :
c < a - b ↔ c + b < a :=
lt_iff_lt_of_le_iff_le (sub_le_iff_le_add h₁ h₂)
theorem sub_le_of_le_add {a b c : EReal} (h : a ≤ b + c) : a - c ≤ b := by
induction c with
| bot => rw [add_bot, le_bot_iff] at h; simp only [h, bot_sub, bot_le]
| coe c => exact (sub_le_iff_le_add (.inl (coe_ne_bot c)) (.inl (coe_ne_top c))).2 h
| top => simp only [sub_top, bot_le]
/-- See also `EReal.sub_le_of_le_add`. -/
theorem sub_le_of_le_add' {a b c : EReal} (h : a ≤ b + c) : a - b ≤ c :=
sub_le_of_le_add (add_comm b c ▸ h)
lemma add_le_of_le_sub {a b c : EReal} (h : a ≤ b - c) : a + c ≤ b := by
rw [← neg_neg c]
exact sub_le_of_le_add h
lemma sub_lt_iff {a b c : EReal} (h₁ : b ≠ ⊥ ∨ c ≠ ⊥) (h₂ : b ≠ ⊤ ∨ c ≠ ⊤) :
c - b < a ↔ c < a + b :=
lt_iff_lt_of_le_iff_le (le_sub_iff_add_le h₁ h₂)
lemma add_lt_of_lt_sub {a b c : EReal} (h : a < b - c) : a + c < b := by
contrapose! h
exact sub_le_of_le_add h
lemma sub_lt_of_lt_add {a b c : EReal} (h : a < b + c) : a - c < b :=
add_lt_of_lt_sub <| by rwa [sub_eq_add_neg, neg_neg]
/-- See also `EReal.sub_lt_of_lt_add`. -/
lemma sub_lt_of_lt_add' {a b c : EReal} (h : a < b + c) : a - b < c :=
sub_lt_of_lt_add <| by rwa [add_comm]
/-! ### Addition and order -/
lemma le_of_forall_lt_iff_le {x y : EReal} : (∀ z : ℝ, x < z → y ≤ z) ↔ y ≤ x := by
refine ⟨fun h ↦ WithBot.le_of_forall_lt_iff_le.1 ?_, fun h _ x_z ↦ h.trans x_z.le⟩
rw [WithTop.forall]
aesop
lemma ge_of_forall_gt_iff_ge {x y : EReal} : (∀ z : ℝ, z < y → z ≤ x) ↔ y ≤ x := by
refine ⟨fun h ↦ WithBot.ge_of_forall_gt_iff_ge.1 ?_, fun h _ x_z ↦ x_z.le.trans h⟩
rw [WithTop.forall]
aesop
private lemma exists_lt_add_left {a b c : EReal} (hc : c < a + b) : ∃ a' < a, c < a' + b := by
obtain ⟨a', hc', ha'⟩ := exists_between (sub_lt_of_lt_add hc)
refine ⟨a', ha', (sub_lt_iff (.inl ?_) (.inr hc.ne_top)).1 hc'⟩
contrapose! hc
exact hc ▸ (add_bot a).symm ▸ bot_le
private lemma exists_lt_add_right {a b c : EReal} (hc : c < a + b) : ∃ b' < b, c < a + b' := by
simp_rw [add_comm a] at hc ⊢; exact exists_lt_add_left hc
lemma add_le_of_forall_lt {a b c : EReal} (h : ∀ a' < a, ∀ b' < b, a' + b' ≤ c) : a + b ≤ c := by
refine le_of_forall_lt_imp_le_of_dense fun d hd ↦ ?_
obtain ⟨a', ha', hd⟩ := exists_lt_add_left hd
obtain ⟨b', hb', hd⟩ := exists_lt_add_right hd
exact hd.le.trans (h _ ha' _ hb')
lemma le_add_of_forall_gt {a b c : EReal} (h₁ : a ≠ ⊥ ∨ b ≠ ⊤) (h₂ : a ≠ ⊤ ∨ b ≠ ⊥)
(h : ∀ a' > a, ∀ b' > b, c ≤ a' + b') : c ≤ a + b := by
rw [← neg_le_neg_iff, neg_add h₁ h₂]
refine add_le_of_forall_lt fun a' ha' b' hb' ↦ EReal.le_neg_of_le_neg ?_
rw [neg_add (.inr hb'.ne_top) (.inl ha'.ne_top)]
exact h _ (EReal.lt_neg_of_lt_neg ha') _ (EReal.lt_neg_of_lt_neg hb')
lemma _root_.ENNReal.toEReal_sub {x y : ℝ≥0∞} (hy_top : y ≠ ∞) (h_le : y ≤ x) :
(x - y).toEReal = x.toEReal - y.toEReal := by
lift y to ℝ≥0 using hy_top
cases x with
| top => simp [coe_nnreal_eq_coe_real]
| coe x =>
simp only [coe_nnreal_eq_coe_real, ← ENNReal.coe_sub, NNReal.coe_sub (mod_cast h_le), coe_sub]
/-! ### Multiplication -/
@[simp] lemma top_mul_top : (⊤ : EReal) * ⊤ = ⊤ := rfl
@[simp] lemma top_mul_bot : (⊤ : EReal) * ⊥ = ⊥ := rfl
@[simp] lemma bot_mul_top : (⊥ : EReal) * ⊤ = ⊥ := rfl
@[simp] lemma bot_mul_bot : (⊥ : EReal) * ⊥ = ⊤ := rfl
lemma coe_mul_top_of_pos {x : ℝ} (h : 0 < x) : (x : EReal) * ⊤ = ⊤ :=
if_pos h
lemma coe_mul_top_of_neg {x : ℝ} (h : x < 0) : (x : EReal) * ⊤ = ⊥ :=
(if_neg h.not_gt).trans (if_neg h.ne)
lemma top_mul_coe_of_pos {x : ℝ} (h : 0 < x) : (⊤ : EReal) * x = ⊤ :=
if_pos h
lemma top_mul_coe_of_neg {x : ℝ} (h : x < 0) : (⊤ : EReal) * x = ⊥ :=
(if_neg h.not_gt).trans (if_neg h.ne)
lemma mul_top_of_pos : ∀ {x : EReal}, 0 < x → x * ⊤ = ⊤
| ⊥, h => absurd h not_lt_bot
| (x : ℝ), h => coe_mul_top_of_pos (EReal.coe_pos.1 h)
| ⊤, _ => rfl
lemma mul_top_of_neg : ∀ {x : EReal}, x < 0 → x * ⊤ = ⊥
| ⊥, _ => rfl
| (x : ℝ), h => coe_mul_top_of_neg (EReal.coe_neg'.1 h)
| ⊤, h => absurd h not_top_lt
lemma top_mul_of_pos {x : EReal} (h : 0 < x) : ⊤ * x = ⊤ := by
rw [EReal.mul_comm]
exact mul_top_of_pos h
lemma top_mul_of_neg {x : EReal} (h : x < 0) : ⊤ * x = ⊥ := by
rw [EReal.mul_comm]
exact mul_top_of_neg h
lemma top_mul_coe_ennreal {x : ℝ≥0∞} (hx : x ≠ 0) : ⊤ * (x : EReal) = ⊤ :=
top_mul_of_pos <| coe_ennreal_pos.mpr <| pos_iff_ne_zero.mpr hx
lemma coe_ennreal_mul_top {x : ℝ≥0∞} (hx : x ≠ 0) : (x : EReal) * ⊤ = ⊤ := by
rw [EReal.mul_comm, top_mul_coe_ennreal hx]
lemma coe_mul_bot_of_pos {x : ℝ} (h : 0 < x) : (x : EReal) * ⊥ = ⊥ :=
if_pos h
lemma coe_mul_bot_of_neg {x : ℝ} (h : x < 0) : (x : EReal) * ⊥ = ⊤ :=
(if_neg h.not_gt).trans (if_neg h.ne)
lemma bot_mul_coe_of_pos {x : ℝ} (h : 0 < x) : (⊥ : EReal) * x = ⊥ :=
if_pos h
lemma bot_mul_coe_of_neg {x : ℝ} (h : x < 0) : (⊥ : EReal) * x = ⊤ :=
(if_neg h.not_gt).trans (if_neg h.ne)
lemma mul_bot_of_pos : ∀ {x : EReal}, 0 < x → x * ⊥ = ⊥
| ⊥, h => absurd h not_lt_bot
| (x : ℝ), h => coe_mul_bot_of_pos (EReal.coe_pos.1 h)
| ⊤, _ => rfl
lemma mul_bot_of_neg : ∀ {x : EReal}, x < 0 → x * ⊥ = ⊤
| ⊥, _ => rfl
| (x : ℝ), h => coe_mul_bot_of_neg (EReal.coe_neg'.1 h)
| ⊤, h => absurd h not_top_lt
lemma bot_mul_of_pos {x : EReal} (h : 0 < x) : ⊥ * x = ⊥ := by
rw [EReal.mul_comm]
exact mul_bot_of_pos h
lemma bot_mul_of_neg {x : EReal} (h : x < 0) : ⊥ * x = ⊤ := by
rw [EReal.mul_comm]
exact mul_bot_of_neg h
lemma toReal_mul {x y : EReal} : toReal (x * y) = toReal x * toReal y := by
induction x, y using induction₂_symm with
| top_zero | zero_bot | top_top | top_bot | bot_bot => simp
| symm h => rwa [mul_comm, EReal.mul_comm]
| coe_coe => norm_cast
| top_pos _ h => simp [top_mul_coe_of_pos h]
| top_neg _ h => simp [top_mul_coe_of_neg h]
| pos_bot _ h => simp [coe_mul_bot_of_pos h]
| neg_bot _ h => simp [coe_mul_bot_of_neg h]
instance : NoZeroDivisors EReal where
eq_zero_or_eq_zero_of_mul_eq_zero := by
intro a b h
contrapose! h
cases a <;> cases b <;> try {· simp_all [← EReal.coe_mul]}
· rcases lt_or_gt_of_ne h.2 with (h | h)
<;> simp [EReal.bot_mul_of_neg, EReal.bot_mul_of_pos, h]
· rcases lt_or_gt_of_ne h.1 with (h | h)
<;> simp [EReal.mul_bot_of_pos, EReal.mul_bot_of_neg, h]
· rcases lt_or_gt_of_ne h.1 with (h | h)
<;> simp [EReal.mul_top_of_neg, EReal.mul_top_of_pos, h]
· rcases lt_or_gt_of_ne h.2 with (h | h)
<;> simp [EReal.top_mul_of_pos, EReal.top_mul_of_neg, h]
lemma mul_pos_iff {a b : EReal} : 0 < a * b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := by
induction a, b using EReal.induction₂_symm with
| symm h => simp [EReal.mul_comm, h, and_comm]
| top_top => simp
| top_pos _ hx => simp [EReal.top_mul_coe_of_pos hx, hx]
| top_zero => simp
| top_neg _ hx => simp [hx, EReal.top_mul_coe_of_neg hx, le_of_lt]
| top_bot => simp
| pos_bot _ hx => simp [hx, EReal.coe_mul_bot_of_pos hx, le_of_lt]
| coe_coe x y => simp [← coe_mul, _root_.mul_pos_iff]
| zero_bot => simp
| neg_bot _ hx => simp [hx, EReal.coe_mul_bot_of_neg hx]
| bot_bot => simp
lemma mul_nonneg_iff {a b : EReal} : 0 ≤ a * b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 := by
simp_rw [le_iff_lt_or_eq, mul_pos_iff, zero_eq_mul (a := a)]
rcases lt_trichotomy a 0 with (h | h | h) <;> rcases lt_trichotomy b 0 with (h' | h' | h')
<;> simp only [h, h', true_or, true_and, or_true, and_true] <;> tauto
protected lemma mul_nonneg {a b : EReal} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b :=
mul_nonneg_iff.mpr <| .inl ⟨ha, hb⟩
/-- The product of two positive extended real numbers is positive. -/
protected lemma mul_pos {a b : EReal} (ha : 0 < a) (hb : 0 < b) : 0 < a * b :=
mul_pos_iff.mpr (Or.inl ⟨ha, hb⟩)
/-- Induct on two ereals by performing case splits on the sign of one whenever the other is
infinite. This version eliminates some cases by assuming that `P x y` implies `P (-x) y` for all
`x`, `y`. -/
@[elab_as_elim]
lemma induction₂_neg_left {P : EReal → EReal → Prop} (neg_left : ∀ {x y}, P x y → P (-x) y)
(top_top : P ⊤ ⊤) (top_pos : ∀ x : ℝ, 0 < x → P ⊤ x)
(top_zero : P ⊤ 0) (top_neg : ∀ x : ℝ, x < 0 → P ⊤ x) (top_bot : P ⊤ ⊥)
(zero_top : P 0 ⊤) (zero_bot : P 0 ⊥)
(pos_top : ∀ x : ℝ, 0 < x → P x ⊤) (pos_bot : ∀ x : ℝ, 0 < x → P x ⊥)
(coe_coe : ∀ x y : ℝ, P x y) : ∀ x y, P x y :=
have : ∀ y, (∀ x : ℝ, 0 < x → P x y) → ∀ x : ℝ, x < 0 → P x y := fun _ h x hx =>
neg_neg (x : EReal) ▸ neg_left <| h _ (neg_pos_of_neg hx)
@induction₂ P top_top top_pos top_zero top_neg top_bot pos_top pos_bot zero_top
coe_coe zero_bot (this _ pos_top) (this _ pos_bot) (neg_left top_top)
(fun x hx => neg_left <| top_pos x hx) (neg_left top_zero)
(fun x hx => neg_left <| top_neg x hx) (neg_left top_bot)
/-- Induct on two ereals by performing case splits on the sign of one whenever the other is
infinite. This version eliminates some cases by assuming that `P` is symmetric and `P x y` implies
`P (-x) y` for all `x`, `y`. -/
@[elab_as_elim]
lemma induction₂_symm_neg {P : EReal → EReal → Prop}
(symm : ∀ {x y}, P x y → P y x)
(neg_left : ∀ {x y}, P x y → P (-x) y) (top_top : P ⊤ ⊤)
(top_pos : ∀ x : ℝ, 0 < x → P ⊤ x) (top_zero : P ⊤ 0) (coe_coe : ∀ x y : ℝ, P x y) :
∀ x y, P x y :=
have neg_right : ∀ {x y}, P x y → P x (-y) := fun h => symm <| neg_left <| symm h
have : ∀ x, (∀ y : ℝ, 0 < y → P x y) → ∀ y : ℝ, y < 0 → P x y := fun _ h y hy =>
neg_neg (y : EReal) ▸ neg_right (h _ (neg_pos_of_neg hy))
@induction₂_neg_left P neg_left top_top top_pos top_zero (this _ top_pos) (neg_right top_top)
(symm top_zero) (symm <| neg_left top_zero) (fun x hx => symm <| top_pos x hx)
(fun x hx => symm <| neg_left <| top_pos x hx) coe_coe
protected lemma neg_mul (x y : EReal) : -x * y = -(x * y) := by
induction x, y using induction₂_neg_left with
| top_zero | zero_top | zero_bot => simp only [zero_mul, mul_zero, neg_zero]
| top_top | top_bot => rfl
| neg_left h => rw [h, neg_neg, neg_neg]
| coe_coe => norm_cast; exact neg_mul _ _
| top_pos _ h => rw [top_mul_coe_of_pos h, neg_top, bot_mul_coe_of_pos h]
| pos_top _ h => rw [coe_mul_top_of_pos h, neg_top, ← coe_neg,
coe_mul_top_of_neg (neg_neg_of_pos h)]
| top_neg _ h => rw [top_mul_coe_of_neg h, neg_top, bot_mul_coe_of_neg h, neg_bot]
| pos_bot _ h => rw [coe_mul_bot_of_pos h, neg_bot, ← coe_neg,
coe_mul_bot_of_neg (neg_neg_of_pos h)]
instance : HasDistribNeg EReal where
neg_mul := EReal.neg_mul
mul_neg := fun x y => by
rw [x.mul_comm, x.mul_comm]
exact y.neg_mul x
lemma mul_neg_iff {a b : EReal} : a * b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by
nth_rw 1 [← neg_zero]
rw [lt_neg_comm, ← mul_neg a, mul_pos_iff, neg_lt_comm, lt_neg_comm, neg_zero]
lemma mul_nonpos_iff {a b : EReal} : a * b ≤ 0 ↔ 0 ≤ a ∧ b ≤ 0 ∨ a ≤ 0 ∧ 0 ≤ b := by
nth_rw 1 [← neg_zero]
rw [EReal.le_neg, ← mul_neg, mul_nonneg_iff, EReal.neg_le, EReal.le_neg, neg_zero]
lemma mul_eq_top (a b : EReal) :
a * b = ⊤ ↔ (a = ⊥ ∧ b < 0) ∨ (a < 0 ∧ b = ⊥) ∨ (a = ⊤ ∧ 0 < b) ∨ (0 < a ∧ b = ⊤) := by
induction a, b using EReal.induction₂_symm with
| symm h => grind [EReal.mul_comm]
| top_top => simp
| top_pos _ hx => simp [EReal.top_mul_coe_of_pos hx, hx]
| top_zero => simp
| top_neg _ hx => simp [hx.le, EReal.top_mul_coe_of_neg hx]
| top_bot => simp
| pos_bot _ hx => simp [hx.le, EReal.coe_mul_bot_of_pos hx]
| coe_coe x y =>
simpa only [EReal.coe_ne_bot, EReal.coe_neg', false_and, and_false, EReal.coe_ne_top,
EReal.coe_pos, or_self, iff_false, EReal.coe_mul] using EReal.coe_ne_top _
| zero_bot => simp
| neg_bot _ hx => simp [hx, EReal.coe_mul_bot_of_neg hx]
| bot_bot => simp
lemma mul_ne_top (a b : EReal) :
a * b ≠ ⊤ ↔ (a ≠ ⊥ ∨ 0 ≤ b) ∧ (0 ≤ a ∨ b ≠ ⊥) ∧ (a ≠ ⊤ ∨ b ≤ 0) ∧ (a ≤ 0 ∨ b ≠ ⊤) := by
rw [ne_eq, mul_eq_top]
-- push the negation while keeping the disjunctions, that is converting `¬(p ∧ q)` into `¬p ∨ ¬q`
-- rather than `p → ¬q`, since we already have disjunctions in the rhs
set_option push_neg.use_distrib true in push_neg
rfl
lemma mul_eq_bot (a b : EReal) :
a * b = ⊥ ↔ (a = ⊥ ∧ 0 < b) ∨ (0 < a ∧ b = ⊥) ∨ (a = ⊤ ∧ b < 0) ∨ (a < 0 ∧ b = ⊤) := by
rw [← neg_eq_top_iff, ← EReal.neg_mul, mul_eq_top, neg_eq_bot_iff, neg_eq_top_iff,
neg_lt_comm, lt_neg_comm, neg_zero]
tauto
lemma mul_ne_bot (a b : EReal) :
a * b ≠ ⊥ ↔ (a ≠ ⊥ ∨ b ≤ 0) ∧ (a ≤ 0 ∨ b ≠ ⊥) ∧ (a ≠ ⊤ ∨ 0 ≤ b) ∧ (0 ≤ a ∨ b ≠ ⊤) := by
rw [ne_eq, mul_eq_bot]
set_option push_neg.use_distrib true in push_neg
rfl
/-- `EReal.toENNReal` is multiplicative. For the version with the nonnegativity
hypothesis on the second variable, see `EReal.toENNReal_mul'`. -/
lemma toENNReal_mul {x y : EReal} (hx : 0 ≤ x) :
(x * y).toENNReal = x.toENNReal * y.toENNReal := by
induction x <;> induction y
<;> try {· simp_all [mul_nonpos_iff, ofReal_mul, ← coe_mul]}
· rcases eq_or_lt_of_le hx with (hx | hx)
· simp [← hx]
· simp_all [mul_top_of_pos hx]
· rename_i a
rcases lt_trichotomy a 0 with (ha | ha | ha)
· simp_all [le_of_lt, top_mul_of_neg (EReal.coe_neg'.mpr ha)]
· simp [ha]
· simp_all [top_mul_of_pos (EReal.coe_pos.mpr ha)]
/-- `EReal.toENNReal` is multiplicative. For the version with the nonnegativity
hypothesis on the first variable, see `EReal.toENNReal_mul`. -/
lemma toENNReal_mul' {x y : EReal} (hy : 0 ≤ y) :
(x * y).toENNReal = x.toENNReal * y.toENNReal := by
rw [EReal.mul_comm, toENNReal_mul hy, mul_comm]
lemma right_distrib_of_nonneg {a b c : EReal} (ha : 0 ≤ a) (hb : 0 ≤ b) :
(a + b) * c = a * c + b * c := by
lift a to ℝ≥0∞ using ha
lift b to ℝ≥0∞ using hb
cases c using recENNReal with
| coe c => exact_mod_cast add_mul a b c
| neg_coe c hc =>
simp only [mul_neg, ← coe_ennreal_add, ← coe_ennreal_mul, add_mul]
rw [coe_ennreal_add, EReal.neg_add (.inl (coe_ennreal_ne_bot _)) (.inr (coe_ennreal_ne_bot _)),
sub_eq_add_neg]
lemma left_distrib_of_nonneg {a b c : EReal} (ha : 0 ≤ a) (hb : 0 ≤ b) :
c * (a + b) = c * a + c * b := by
nth_rewrite 1 [EReal.mul_comm]; nth_rewrite 2 [EReal.mul_comm]; nth_rewrite 3 [EReal.mul_comm]
exact right_distrib_of_nonneg ha hb
lemma left_distrib_of_nonneg_of_ne_top {x : EReal} (hx_nonneg : 0 ≤ x)
(hx_ne_top : x ≠ ⊤) (y z : EReal) :
x * (y + z) = x * y + x * z := by
cases hx_nonneg.eq_or_lt' with
| inl hx0 => simp [hx0]
| inr hx0 =>
lift x to ℝ using ⟨hx_ne_top, hx0.ne_bot⟩
cases y <;> cases z <;>
simp [mul_bot_of_pos hx0, mul_top_of_pos hx0, ← coe_mul];
rw_mod_cast [mul_add]
lemma right_distrib_of_nonneg_of_ne_top {x : EReal} (hx_nonneg : 0 ≤ x)
(hx_ne_top : x ≠ ⊤) (y z : EReal) :
(y + z) * x = y * x + z * x := by
simpa only [EReal.mul_comm] using left_distrib_of_nonneg_of_ne_top hx_nonneg hx_ne_top y z
@[simp]
lemma nsmul_eq_mul (n : ℕ) (x : EReal) : n • x = n * x := by
induction n with
| zero => rw [zero_smul, Nat.cast_zero, zero_mul]
| succ n ih =>
rw [succ_nsmul, ih, Nat.cast_succ]
convert (EReal.right_distrib_of_nonneg _ _).symm <;> simp
end EReal
namespace Mathlib.Meta.Positivity
open Lean Meta Qq Function
/-- Extension for the `positivity` tactic: sum of two `EReal`s. -/
@[positivity (_ + _ : EReal)]
def evalERealAdd : PositivityExt where eval {u α} zα pα e := do
match u, α, e with
| 0, ~q(EReal), ~q($a + $b) =>
assertInstancesCommute
match ← core zα pα a with
| .positive pa =>
match (← core zα pα b).toNonneg with
| some pb => pure (.positive q(EReal.add_pos_of_pos_of_nonneg $pa $pb))
| _ => pure .none
| .nonnegative pa =>
match ← core zα pα b with
| .positive pb => pure (.positive q(Right.add_pos_of_nonneg_of_pos $pa $pb))
| .nonnegative pb => pure (.nonnegative q(add_nonneg $pa $pb))
| _ => pure .none
| _ => pure .none
| _, _, _ => throwError "not a sum of 2 `EReal`s"
/-- Extension for the `positivity` tactic: product of two `EReal`s. -/
@[positivity (_ * _ : EReal)]
def evalERealMul : PositivityExt where eval {u α} zα pα e := do
match u, α, e with
| 0, ~q(EReal), ~q($a * $b) =>
assertInstancesCommute
match ← core zα pα a with
| .positive pa =>
match ← core zα pα b with
| .positive pb => pure <| .positive q(EReal.mul_pos $pa $pb)
| .nonnegative pb => pure <| .nonnegative q(EReal.mul_nonneg (le_of_lt $pa) $pb)
| .nonzero pb => pure <| .nonzero q(mul_ne_zero (ne_of_gt $pa) $pb)
| _ => pure .none
| .nonnegative pa =>
match (← core zα pα b).toNonneg with
| some pb => pure (.nonnegative q(EReal.mul_nonneg $pa $pb))
| none => pure .none
| .nonzero pa =>
match (← core zα pα b).toNonzero with
| some pb => pure (.nonzero q(mul_ne_zero $pa $pb))
| none => pure .none
| _ => pure .none
| _, _, _ => throwError "not a product of 2 `EReal`s"
end Mathlib.Meta.Positivity |
.lake/packages/mathlib/Mathlib/Data/EReal/Inv.lean | import Mathlib.Data.ENNReal.Inv
import Mathlib.Data.EReal.Operations
import Mathlib.Data.Sign.Basic
import Mathlib.Data.Nat.Cast.Order.Field
/-!
# Absolute value, sign, inversion and division on extended real numbers
This file defines an absolute value and sign function on `EReal` and uses them to provide a
`CommMonoidWithZero` instance, based on the absolute value and sign characterising all `EReal`s.
Then it defines the inverse of an `EReal` as `⊤⁻¹ = ⊥⁻¹ = 0`, which leads to a
`DivInvMonoid` instance and division.
-/
open ENNReal Set SignType
noncomputable section
namespace EReal
/-! ### Absolute value -/
-- TODO: use `Real.nnabs` for the case `(x : ℝ)`
/-- The absolute value from `EReal` to `ℝ≥0∞`, mapping `⊥` and `⊤` to `⊤` and
a real `x` to `|x|`. -/
protected def abs : EReal → ℝ≥0∞
| ⊥ => ⊤
| ⊤ => ⊤
| (x : ℝ) => ENNReal.ofReal |x|
@[simp] theorem abs_top : (⊤ : EReal).abs = ⊤ := rfl
@[simp] theorem abs_bot : (⊥ : EReal).abs = ⊤ := rfl
theorem abs_def (x : ℝ) : (x : EReal).abs = ENNReal.ofReal |x| := rfl
theorem abs_coe_lt_top (x : ℝ) : (x : EReal).abs < ⊤ :=
ENNReal.ofReal_lt_top
@[simp]
theorem abs_eq_zero_iff {x : EReal} : x.abs = 0 ↔ x = 0 := by
induction x
· simp only [abs_bot, ENNReal.top_ne_zero, bot_ne_zero]
· simp only [abs_def, coe_eq_zero, ENNReal.ofReal_eq_zero, abs_nonpos_iff]
· simp only [abs_top, ENNReal.top_ne_zero, top_ne_zero]
@[simp]
theorem abs_zero : (0 : EReal).abs = 0 := by rw [abs_eq_zero_iff]
@[simp]
theorem coe_abs (x : ℝ) : ((x : EReal).abs : EReal) = (|x| : ℝ) := by
rw [abs_def, ← Real.coe_nnabs, ENNReal.ofReal_coe_nnreal]; rfl
@[simp]
protected theorem abs_neg : ∀ x : EReal, (-x).abs = x.abs
| ⊤ => rfl
| ⊥ => rfl
| (x : ℝ) => by rw [abs_def, ← coe_neg, abs_def, abs_neg]
@[simp]
theorem abs_mul (x y : EReal) : (x * y).abs = x.abs * y.abs := by
induction x, y using induction₂_symm_neg with
| top_zero => simp only [mul_zero, abs_zero]
| top_top => rfl
| symm h => rwa [mul_comm, EReal.mul_comm]
| coe_coe => simp only [← coe_mul, abs_def, _root_.abs_mul, ENNReal.ofReal_mul (abs_nonneg _)]
| top_pos _ h =>
rw [top_mul_coe_of_pos h, abs_top, ENNReal.top_mul]
rw [Ne, abs_eq_zero_iff, coe_eq_zero]
exact h.ne'
| neg_left h => rwa [neg_mul, EReal.abs_neg, EReal.abs_neg]
/-! ### Sign -/
open SignType (sign)
theorem sign_top : sign (⊤ : EReal) = 1 := rfl
theorem sign_bot : sign (⊥ : EReal) = -1 := rfl
@[simp]
theorem sign_coe (x : ℝ) : sign (x : EReal) = sign x := by
simp only [sign, OrderHom.coe_mk, EReal.coe_pos, EReal.coe_neg']
@[simp, norm_cast]
theorem coe_coe_sign (x : SignType) : ((x : ℝ) : EReal) = x := by cases x <;> rfl
@[simp] theorem sign_neg : ∀ x : EReal, sign (-x) = -sign x
| ⊤ => rfl
| ⊥ => rfl
| (x : ℝ) => by rw [← coe_neg, sign_coe, sign_coe, Left.sign_neg]
@[simp]
theorem sign_mul (x y : EReal) : sign (x * y) = sign x * sign y := by
induction x, y using induction₂_symm_neg with
| top_zero => simp only [mul_zero, sign_zero]
| top_top => rfl
| symm h => rwa [mul_comm, EReal.mul_comm]
| coe_coe => simp only [← coe_mul, sign_coe, _root_.sign_mul]
| top_pos _ h =>
rw [top_mul_coe_of_pos h, sign_top, one_mul, sign_pos (EReal.coe_pos.2 h)]
| neg_left h => rw [neg_mul, sign_neg, sign_neg, h, neg_mul]
@[simp] protected theorem sign_mul_abs : ∀ x : EReal, (sign x * x.abs : EReal) = x
| ⊥ => by simp
| ⊤ => by simp
| (x : ℝ) => by rw [sign_coe, coe_abs, ← coe_coe_sign, ← coe_mul, sign_mul_abs]
@[simp] protected theorem abs_mul_sign (x : EReal) : (x.abs * sign x : EReal) = x := by
rw [EReal.mul_comm, EReal.sign_mul_abs]
theorem sign_eq_and_abs_eq_iff_eq {x y : EReal} :
x.abs = y.abs ∧ sign x = sign y ↔ x = y := by
constructor
· rintro ⟨habs, hsign⟩
rw [← x.sign_mul_abs, ← y.sign_mul_abs, habs, hsign]
· rintro rfl
exact ⟨rfl, rfl⟩
theorem le_iff_sign {x y : EReal} :
x ≤ y ↔ sign x < sign y ∨
sign x = SignType.neg ∧ sign y = SignType.neg ∧ y.abs ≤ x.abs ∨
sign x = SignType.zero ∧ sign y = SignType.zero ∨
sign x = SignType.pos ∧ sign y = SignType.pos ∧ x.abs ≤ y.abs := by
constructor
· intro h
refine (sign.monotone h).lt_or_eq.imp_right (fun hs => ?_)
rw [← x.sign_mul_abs, ← y.sign_mul_abs] at h
cases hy : sign y <;> rw [hs, hy] at h ⊢
· simp
· left; simpa using h
· right; right; simpa using h
· rintro (h | h | h | h)
· exact (sign.monotone.reflect_lt h).le
all_goals rw [← x.sign_mul_abs, ← y.sign_mul_abs]; simp [h]
instance : CommMonoidWithZero EReal :=
{ inferInstanceAs (MulZeroOneClass EReal) with
mul_assoc := fun x y z => by
rw [← sign_eq_and_abs_eq_iff_eq]
simp only [mul_assoc, abs_mul, sign_mul, and_self_iff]
mul_comm := EReal.mul_comm }
instance : PosMulMono EReal := posMulMono_iff_covariant_pos.2 <| .mk <| by
rintro ⟨x, x0⟩ a b h
simp only [le_iff_sign, EReal.sign_mul, sign_pos x0, one_mul, EReal.abs_mul] at h ⊢
exact h.imp_right <| Or.imp (And.imp_right <| And.imp_right (mul_le_mul_left' · _)) <|
Or.imp_right <| And.imp_right <| And.imp_right (mul_le_mul_left' · _)
instance : MulPosMono EReal := posMulMono_iff_mulPosMono.1 inferInstance
instance : PosMulReflectLT EReal := PosMulMono.toPosMulReflectLT
instance : MulPosReflectLT EReal := MulPosMono.toMulPosReflectLT
lemma mul_le_mul_of_nonpos_right {a b c : EReal} (h : b ≤ a) (hc : c ≤ 0) : a * c ≤ b * c := by
rw [mul_comm a c, mul_comm b c, ← neg_le_neg_iff, ← neg_mul c b, ← neg_mul c a]
rw [← neg_zero, EReal.le_neg] at hc
gcongr
@[simp, norm_cast]
theorem coe_pow (x : ℝ) (n : ℕ) : (↑(x ^ n) : EReal) = (x : EReal) ^ n :=
map_pow (⟨⟨(↑), coe_one⟩, coe_mul⟩ : ℝ →* EReal) _ _
@[simp, norm_cast]
theorem coe_ennreal_pow (x : ℝ≥0∞) (n : ℕ) : (↑(x ^ n) : EReal) = (x : EReal) ^ n :=
map_pow (⟨⟨(↑), coe_ennreal_one⟩, coe_ennreal_mul⟩ : ℝ≥0∞ →* EReal) _ _
lemma exists_nat_ge_mul {a : EReal} (ha : a ≠ ⊤) (n : ℕ) :
∃ m : ℕ, a * n ≤ m :=
match a with
| ⊤ => ha.irrefl.rec
| ⊥ => ⟨0, Nat.cast_zero (R := EReal) ▸ mul_nonpos_iff.2 (.inr ⟨bot_le, n.cast_nonneg'⟩)⟩
| (a : ℝ) => by
obtain ⟨m, an_m⟩ := exists_nat_ge (a * n)
use m
rwa [← coe_coe_eq_natCast n, ← coe_coe_eq_natCast m, ← EReal.coe_mul, EReal.coe_le_coe_iff]
/-! ### Min and Max -/
lemma min_neg_neg (x y : EReal) : min (-x) (-y) = -max x y := by
rcases le_total x y with (h | h) <;> simp_all
lemma max_neg_neg (x y : EReal) : max (-x) (-y) = -min x y := by
rcases le_total x y with (h | h) <;> simp_all
/-! ### Inverse -/
/-- Multiplicative inverse of an `EReal`. We choose `0⁻¹ = 0` to guarantee several good properties,
for instance `(a * b)⁻¹ = a⁻¹ * b⁻¹`. -/
protected def inv : EReal → EReal
| ⊥ => 0
| ⊤ => 0
| (x : ℝ) => (x⁻¹ : ℝ)
instance : Inv (EReal) := ⟨EReal.inv⟩
noncomputable instance : DivInvMonoid EReal where inv := EReal.inv
@[simp]
lemma inv_bot : (⊥ : EReal)⁻¹ = 0 := rfl
@[simp]
lemma inv_top : (⊤ : EReal)⁻¹ = 0 := rfl
lemma coe_inv (x : ℝ) : (x⁻¹ : ℝ) = (x : EReal)⁻¹ := rfl
@[simp]
lemma inv_zero : (0 : EReal)⁻¹ = 0 := by
change (0 : ℝ)⁻¹ = (0 : EReal)
rw [GroupWithZero.inv_zero, coe_zero]
noncomputable instance : DivInvOneMonoid EReal where
inv_one := by nth_rw 1 [← coe_one, ← coe_inv 1, _root_.inv_one, coe_one]
lemma inv_neg (a : EReal) : (-a)⁻¹ = -a⁻¹ := by
induction a
· rw [neg_bot, inv_top, inv_bot, neg_zero]
· rw [← coe_inv _, ← coe_neg _⁻¹, ← coe_neg _, ← coe_inv (-_)]
exact EReal.coe_eq_coe_iff.2 _root_.inv_neg
· rw [neg_top, inv_bot, inv_top, neg_zero]
lemma inv_inv {a : EReal} (h : a ≠ ⊥) (h' : a ≠ ⊤) : (a⁻¹)⁻¹ = a := by
rw [← coe_toReal h' h, ← coe_inv a.toReal, ← coe_inv a.toReal⁻¹, _root_.inv_inv a.toReal]
lemma mul_inv (a b : EReal) : (a * b)⁻¹ = a⁻¹ * b⁻¹ := by
induction a, b using EReal.induction₂_symm with
| top_top | top_zero | top_bot | zero_bot | bot_bot => simp
| @symm a b h => rw [mul_comm b a, mul_comm b⁻¹ a⁻¹]; exact h
| top_pos x x_pos => rw [top_mul_of_pos (EReal.coe_pos.2 x_pos), inv_top, zero_mul]
| top_neg x x_neg => rw [top_mul_of_neg (EReal.coe_neg'.2 x_neg), inv_bot, inv_top, zero_mul]
| pos_bot x x_pos => rw [mul_bot_of_pos (EReal.coe_pos.2 x_pos), inv_bot, mul_zero]
| coe_coe x y => rw [← coe_mul, ← coe_inv, _root_.mul_inv, coe_mul, coe_inv, coe_inv]
| neg_bot x x_neg => rw [mul_bot_of_neg (EReal.coe_neg'.2 x_neg), inv_top, inv_bot, mul_zero]
/-! #### Inversion and Absolute Value -/
lemma sign_mul_inv_abs (a : EReal) : (sign a) * (a.abs : EReal)⁻¹ = a⁻¹ := by
induction a with
| bot | top => simp
| coe a =>
rcases lt_trichotomy a 0 with (a_neg | rfl | a_pos)
· rw [sign_coe, _root_.sign_neg a_neg, coe_neg_one, neg_one_mul, ← inv_neg, abs_def a,
coe_ennreal_ofReal, max_eq_left (abs_nonneg a), ← coe_neg |a|, abs_of_neg a_neg, neg_neg]
· rw [coe_zero, sign_zero, SignType.coe_zero, abs_zero, coe_ennreal_zero, inv_zero, mul_zero]
· rw [sign_coe, _root_.sign_pos a_pos, SignType.coe_one, one_mul]
simp only [abs_def a, coe_ennreal_ofReal, abs_nonneg, max_eq_left]
congr
exact abs_of_pos a_pos
lemma sign_mul_inv_abs' (a : EReal) : (sign a) * ((a.abs⁻¹ : ℝ≥0∞) : EReal) = a⁻¹ := by
induction a with
| bot | top => simp
| coe a =>
rcases lt_trichotomy a 0 with (a_neg | rfl | a_pos)
· rw [sign_coe, _root_.sign_neg a_neg, coe_neg_one, neg_one_mul, abs_def a,
← ofReal_inv_of_pos (abs_pos_of_neg a_neg), coe_ennreal_ofReal,
max_eq_left (inv_nonneg.2 (abs_nonneg a)), ← coe_neg |a|⁻¹, ← coe_inv a, abs_of_neg a_neg,
← _root_.inv_neg, neg_neg]
· simp
· rw [sign_coe, _root_.sign_pos a_pos, SignType.coe_one, one_mul, abs_def a,
← ofReal_inv_of_pos (abs_pos_of_pos a_pos), coe_ennreal_ofReal,
max_eq_left (inv_nonneg.2 (abs_nonneg a)), ← coe_inv a]
congr
exact abs_of_pos a_pos
/-! #### Inversion and Positivity -/
lemma bot_lt_inv (x : EReal) : ⊥ < x⁻¹ := by
cases x with
| bot => exact inv_bot ▸ bot_lt_zero
| top => exact EReal.inv_top ▸ bot_lt_zero
| coe x => exact (coe_inv x).symm ▸ bot_lt_coe (x⁻¹)
lemma inv_lt_top (x : EReal) : x⁻¹ < ⊤ := by
cases x with
| bot => exact inv_bot ▸ zero_lt_top
| top => exact EReal.inv_top ▸ zero_lt_top
| coe x => exact (coe_inv x).symm ▸ coe_lt_top (x⁻¹)
lemma inv_nonneg_of_nonneg {a : EReal} (h : 0 ≤ a) : 0 ≤ a⁻¹ := by
cases a with
| bot | top => simp
| coe a => rw [← coe_inv a, EReal.coe_nonneg, inv_nonneg]; exact EReal.coe_nonneg.1 h
lemma inv_nonpos_of_nonpos {a : EReal} (h : a ≤ 0) : a⁻¹ ≤ 0 := by
cases a with
| bot | top => simp
| coe a => rw [← coe_inv a, EReal.coe_nonpos, inv_nonpos]; exact EReal.coe_nonpos.1 h
lemma inv_pos_of_pos_ne_top {a : EReal} (h : 0 < a) (h' : a ≠ ⊤) : 0 < a⁻¹ := by
lift a to ℝ using ⟨h', ne_bot_of_gt h⟩
rw [← coe_inv a]; norm_cast at *; exact inv_pos_of_pos h
lemma inv_neg_of_neg_ne_bot {a : EReal} (h : a < 0) (h' : a ≠ ⊥) : a⁻¹ < 0 := by
lift a to ℝ using ⟨ne_top_of_lt h, h'⟩
rw [← coe_inv a]; norm_cast at *; exact inv_lt_zero.2 h
lemma inv_strictAntiOn : StrictAntiOn (fun (x : EReal) => x⁻¹) (Ioi 0) := by
intro a a_0 b b_0 a_b
simp only [mem_Ioi] at *
lift a to ℝ using ⟨ne_top_of_lt a_b, ne_bot_of_gt a_0⟩
match b with
| ⊤ => exact inv_top ▸ inv_pos_of_pos_ne_top a_0 (coe_ne_top a)
| ⊥ => exact (not_lt_bot b_0).rec
| (b : ℝ) =>
rw [← coe_inv a, ← coe_inv b, EReal.coe_lt_coe_iff]
exact _root_.inv_strictAntiOn (EReal.coe_pos.1 a_0) (EReal.coe_pos.1 b_0)
(EReal.coe_lt_coe_iff.1 a_b)
/-! ### Division -/
protected lemma div_eq_inv_mul (a b : EReal) : a / b = b⁻¹ * a := EReal.mul_comm a b⁻¹
lemma coe_div (a b : ℝ) : (a / b : ℝ) = (a : EReal) / (b : EReal) := rfl
theorem natCast_div_le (m n : ℕ) :
(m / n : ℕ) ≤ (m : EReal) / (n : EReal) := by
rw [← coe_coe_eq_natCast, ← coe_coe_eq_natCast, ← coe_coe_eq_natCast, ← coe_div,
EReal.coe_le_coe_iff]
exact Nat.cast_div_le
@[simp]
lemma div_bot {a : EReal} : a / ⊥ = 0 := inv_bot ▸ mul_zero a
@[simp]
lemma div_top {a : EReal} : a / ⊤ = 0 := inv_top ▸ mul_zero a
@[simp]
lemma div_zero {a : EReal} : a / 0 = 0 := by
change a * 0⁻¹ = 0
rw [inv_zero, mul_zero a]
@[simp]
lemma zero_div {a : EReal} : 0 / a = 0 := zero_mul a⁻¹
lemma top_div_of_pos_ne_top {a : EReal} (h : 0 < a) (h' : a ≠ ⊤) : ⊤ / a = ⊤ :=
top_mul_of_pos (inv_pos_of_pos_ne_top h h')
lemma top_div_of_neg_ne_bot {a : EReal} (h : a < 0) (h' : a ≠ ⊥) : ⊤ / a = ⊥ :=
top_mul_of_neg (inv_neg_of_neg_ne_bot h h')
lemma bot_div_of_pos_ne_top {a : EReal} (h : 0 < a) (h' : a ≠ ⊤) : ⊥ / a = ⊥ :=
bot_mul_of_pos (inv_pos_of_pos_ne_top h h')
lemma bot_div_of_neg_ne_bot {a : EReal} (h : a < 0) (h' : a ≠ ⊥) : ⊥ / a = ⊤ :=
bot_mul_of_neg (inv_neg_of_neg_ne_bot h h')
/-! #### Division and Multiplication -/
lemma div_self {a : EReal} (h₁ : a ≠ ⊥) (h₂ : a ≠ ⊤) (h₃ : a ≠ 0) : a / a = 1 := by
rw [← coe_toReal h₂ h₁] at h₃ ⊢
rw [← coe_div, _root_.div_self (coe_ne_zero.1 h₃), coe_one]
lemma mul_div (a b c : EReal) : a * (b / c) = (a * b) / c := by
change a * (b * c⁻¹) = (a * b) * c⁻¹
rw [mul_assoc]
lemma mul_div_right (a b c : EReal) : a / b * c = a * c / b := by
rw [mul_comm, EReal.mul_div, mul_comm]
lemma mul_div_left_comm (a b c : EReal) : a * (b / c) = b * (a / c) := by
rw [mul_div a b c, mul_comm a b, ← mul_div b a c]
lemma div_div (a b c : EReal) : a / b / c = a / (b * c) := by
change (a * b⁻¹) * c⁻¹ = a * (b * c)⁻¹
rw [mul_assoc a b⁻¹, mul_inv]
lemma div_mul_div_comm (a b c d : EReal) : a / b * (c / d) = a * c / (b * d) := by
rw [← mul_div a, mul_comm b d, ← div_div c, ← mul_div_left_comm (c / d), mul_comm (a / b)]
variable {a b c : EReal}
lemma div_mul_cancel (h₁ : b ≠ ⊥) (h₂ : b ≠ ⊤) (h₃ : b ≠ 0) : a / b * b = a := by
rw [mul_comm (a / b) b, ← mul_div_left_comm a b b, div_self h₁ h₂ h₃, mul_one]
lemma mul_div_cancel (h₁ : b ≠ ⊥) (h₂ : b ≠ ⊤) (h₃ : b ≠ 0) : b * (a / b) = a := by
rw [mul_comm, div_mul_cancel h₁ h₂ h₃]
lemma mul_div_mul_cancel (h₁ : c ≠ ⊥) (h₂ : c ≠ ⊤) (h₃ : c ≠ 0) : a * c / (b * c) = a / b := by
rw [← mul_div_right a (b * c) c, ← div_div a b c, div_mul_cancel h₁ h₂ h₃]
lemma div_eq_iff (hbot : b ≠ ⊥) (htop : b ≠ ⊤) (hzero : b ≠ 0) : c / b = a ↔ c = a * b := by
refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩
· rw [← @mul_div_cancel c b hbot htop hzero, h, mul_comm a b]
· rw [h, mul_comm a b, ← mul_div b a b, @mul_div_cancel a b hbot htop hzero]
/-! #### Division and Order -/
lemma monotone_div_right_of_nonneg (h : 0 ≤ b) : Monotone fun a ↦ a / b :=
fun _ _ h' ↦ mul_le_mul_of_nonneg_right h' (inv_nonneg_of_nonneg h)
@[gcongr]
lemma div_le_div_right_of_nonneg (h : 0 ≤ c) (h' : a ≤ b) : a / c ≤ b / c :=
monotone_div_right_of_nonneg h h'
lemma strictMono_div_right_of_pos (h : 0 < b) (h' : b ≠ ⊤) : StrictMono fun a ↦ a / b := by
intro a a' a_lt_a'
apply lt_of_le_of_ne <| div_le_div_right_of_nonneg (le_of_lt h) (le_of_lt a_lt_a')
intro hyp
apply ne_of_lt a_lt_a'
rw [← @EReal.mul_div_cancel a b (ne_bot_of_gt h) h' (ne_of_gt h), hyp,
@EReal.mul_div_cancel a' b (ne_bot_of_gt h) h' (ne_of_gt h)]
@[gcongr]
lemma div_lt_div_right_of_pos (h₁ : 0 < c) (h₂ : c ≠ ⊤) (h₃ : a < b) : a / c < b / c :=
strictMono_div_right_of_pos h₁ h₂ h₃
lemma antitone_div_right_of_nonpos (h : b ≤ 0) : Antitone fun a ↦ a / b := by
intro a a' h'
change a' * b⁻¹ ≤ a * b⁻¹
rw [← neg_neg (a * b⁻¹), ← neg_neg (a' * b⁻¹), neg_le_neg_iff, mul_comm a b⁻¹, mul_comm a' b⁻¹,
← neg_mul b⁻¹ a, ← neg_mul b⁻¹ a', mul_comm (-b⁻¹) a, mul_comm (-b⁻¹) a', ← inv_neg b]
have : 0 ≤ -b := by apply EReal.le_neg_of_le_neg; simp [h]
exact div_le_div_right_of_nonneg this h'
lemma div_le_div_right_of_nonpos (h : c ≤ 0) (h' : a ≤ b) : b / c ≤ a / c :=
antitone_div_right_of_nonpos h h'
lemma strictAnti_div_right_of_neg (h : b < 0) (h' : b ≠ ⊥) : StrictAnti fun a ↦ a / b := by
intro a a' a_lt_a'
simp only
apply lt_of_le_of_ne <| div_le_div_right_of_nonpos (le_of_lt h) (le_of_lt a_lt_a')
intro hyp
apply ne_of_lt a_lt_a'
rw [← @EReal.mul_div_cancel a b h' (ne_top_of_lt h) (ne_of_lt h), ← hyp,
@EReal.mul_div_cancel a' b h' (ne_top_of_lt h) (ne_of_lt h)]
lemma div_lt_div_right_of_neg (h₁ : c < 0) (h₂ : c ≠ ⊥) (h₃ : a < b) : b / c < a / c :=
strictAnti_div_right_of_neg h₁ h₂ h₃
lemma le_div_iff_mul_le (h : b > 0) (h' : b ≠ ⊤) : a ≤ c / b ↔ a * b ≤ c := by
nth_rw 1 [← @mul_div_cancel a b (ne_bot_of_gt h) h' (ne_of_gt h)]
rw [mul_div b a b, mul_comm a b]
exact StrictMono.le_iff_le (strictMono_div_right_of_pos h h')
lemma div_le_iff_le_mul (h : 0 < b) (h' : b ≠ ⊤) : a / b ≤ c ↔ a ≤ b * c := by
nth_rw 1 [← @mul_div_cancel c b (ne_bot_of_gt h) h' (ne_of_gt h)]
rw [mul_div b c b, mul_comm b]
exact StrictMono.le_iff_le (strictMono_div_right_of_pos h h')
lemma lt_div_iff (h : 0 < b) (h' : b ≠ ⊤) : a < c / b ↔ a * b < c := by
nth_rw 1 [← @mul_div_cancel a b (ne_bot_of_gt h) h' (ne_of_gt h)]
rw [EReal.mul_div b a b, mul_comm a b]
exact (strictMono_div_right_of_pos h h').lt_iff_lt
lemma div_lt_iff (h : 0 < c) (h' : c ≠ ⊤) : b / c < a ↔ b < a * c := by
nth_rw 1 [← @mul_div_cancel a c (ne_bot_of_gt h) h' (ne_of_gt h)]
rw [EReal.mul_div c a c, mul_comm a c]
exact (strictMono_div_right_of_pos h h').lt_iff_lt
lemma div_nonneg (h : 0 ≤ a) (h' : 0 ≤ b) : 0 ≤ a / b :=
mul_nonneg h (inv_nonneg_of_nonneg h')
lemma div_pos (ha : 0 < a) (hb : 0 < b) (hb' : b ≠ ⊤) : 0 < a / b :=
EReal.mul_pos ha (inv_pos_of_pos_ne_top hb hb')
lemma div_nonpos_of_nonpos_of_nonneg (h : a ≤ 0) (h' : 0 ≤ b) : a / b ≤ 0 :=
mul_nonpos_of_nonpos_of_nonneg h (inv_nonneg_of_nonneg h')
lemma div_nonpos_of_nonneg_of_nonpos (h : 0 ≤ a) (h' : b ≤ 0) : a / b ≤ 0 :=
mul_nonpos_of_nonneg_of_nonpos h (inv_nonpos_of_nonpos h')
lemma div_nonneg_of_nonpos_of_nonpos (h : a ≤ 0) (h' : b ≤ 0) : 0 ≤ a / b :=
le_of_eq_of_le zero_div.symm (div_le_div_right_of_nonpos h' h)
private lemma exists_lt_mul_left_of_nonneg (ha : 0 ≤ a) (hc : 0 ≤ c) (h : c < a * b) :
∃ a' ∈ Ioo 0 a, c < a' * b := by
rcases eq_or_ne b ⊤ with rfl | b_top
· rcases eq_or_lt_of_le ha with rfl | ha
· rw [zero_mul] at h
exact (not_le_of_gt h hc).rec
· obtain ⟨a', a0', aa'⟩ := exists_between ha
use a', mem_Ioo.2 ⟨a0', aa'⟩
rw [mul_top_of_pos ha] at h
rwa [mul_top_of_pos a0']
· have b0 : 0 < b := pos_of_mul_pos_right (hc.trans_lt h) ha
obtain ⟨a', ha', aa'⟩ := exists_between ((div_lt_iff b0 b_top).2 h)
exact ⟨a', ⟨(div_nonneg hc b0.le).trans_lt ha', aa'⟩, (div_lt_iff b0 b_top).1 ha'⟩
private lemma exists_lt_mul_right_of_nonneg (ha : 0 ≤ a) (hc : 0 ≤ c) (h : c < a * b) :
∃ b' ∈ Ioo 0 b, c < a * b' := by
have hb : 0 < b := pos_of_mul_pos_right (hc.trans_lt h) ha
simp_rw [mul_comm a] at h ⊢
exact exists_lt_mul_left_of_nonneg hb.le hc h
private lemma exists_mul_left_lt (h₁ : a ≠ 0 ∨ b ≠ ⊤) (h₂ : a ≠ ⊤ ∨ 0 < b) (hc : a * b < c) :
∃ a' ∈ Ioo a ⊤, a' * b < c := by
rcases eq_top_or_lt_top a with rfl | a_top
· rw [ne_self_iff_false, false_or] at h₂; rw [top_mul_of_pos h₂] at hc; exact (not_top_lt hc).rec
rcases le_or_gt b 0 with b0 | b0
· obtain ⟨a', aa', a_top'⟩ := exists_between a_top
exact ⟨a', mem_Ioo.2 ⟨aa', a_top'⟩, lt_of_le_of_lt (mul_le_mul_of_nonpos_right aa'.le b0) hc⟩
rcases eq_top_or_lt_top b with rfl | b_top
· rcases lt_trichotomy a 0 with a0 | rfl | a0
· obtain ⟨a', aa', a0'⟩ := exists_between a0
rw [mul_top_of_neg a0] at hc
refine ⟨a', mem_Ioo.2 ⟨aa', lt_top_of_lt a0'⟩, mul_top_of_neg a0' ▸ hc⟩
· rw [ne_self_iff_false, ne_self_iff_false, false_or] at h₁; exact h₁.rec
· rw [mul_top_of_pos a0] at hc; exact (not_top_lt hc).rec
· obtain ⟨a', aa', hc'⟩ := exists_between ((lt_div_iff b0 b_top.ne).2 hc)
exact ⟨a', mem_Ioo.2 ⟨aa', lt_top_of_lt hc'⟩, (lt_div_iff b0 b_top.ne).1 hc'⟩
private lemma exists_mul_right_lt (h₁ : 0 < a ∨ b ≠ ⊤) (h₂ : a ≠ ⊤ ∨ b ≠ 0) (hc : a * b < c) :
∃ b' ∈ Ioo b ⊤, a * b' < c := by
simp_rw [mul_comm a] at hc ⊢
exact exists_mul_left_lt h₂.symm h₁.symm hc
lemma le_mul_of_forall_lt (h₁ : 0 < a ∨ b ≠ ⊤) (h₂ : a ≠ ⊤ ∨ 0 < b)
(h : ∀ a' > a, ∀ b' > b, c ≤ a' * b') : c ≤ a * b := by
refine le_of_forall_gt_imp_ge_of_dense fun d hd ↦ ?_
obtain ⟨a', aa', hd⟩ := exists_mul_left_lt (h₁.imp_left ne_of_gt) h₂ hd
replace h₁ : 0 < a' ∨ b ≠ ⊤ := h₁.imp_left fun a0 ↦ a0.trans (mem_Ioo.1 aa').1
replace h₂ : a' ≠ ⊤ ∨ b ≠ 0 := Or.inl (mem_Ioo.1 aa').2.ne
obtain ⟨b', bb', hd⟩ := exists_mul_right_lt h₁ h₂ hd
exact (h a' (mem_Ioo.1 aa').1 b' (mem_Ioo.1 bb').1).trans hd.le
lemma mul_le_of_forall_lt_of_nonneg (ha : 0 ≤ a) (hc : 0 ≤ c)
(h : ∀ a' ∈ Ioo 0 a, ∀ b' ∈ Ioo 0 b, a' * b' ≤ c) : a * b ≤ c := by
refine le_of_forall_lt_imp_le_of_dense fun d dab ↦ ?_
rcases lt_or_ge d 0 with d0 | d0
· exact d0.le.trans hc
obtain ⟨a', aa', dab⟩ := exists_lt_mul_left_of_nonneg ha d0 dab
obtain ⟨b', bb', dab⟩ := exists_lt_mul_right_of_nonneg aa'.1.le d0 dab
exact dab.le.trans (h a' aa' b' bb')
/-! #### Division Distributivity -/
lemma div_right_distrib_of_nonneg (h : 0 ≤ a) (h' : 0 ≤ b) :
(a + b) / c = a / c + b / c :=
EReal.right_distrib_of_nonneg h h'
lemma add_div_of_nonneg_right (h : 0 ≤ c) :
(a + b) / c = a / c + b / c := by
apply right_distrib_of_nonneg_of_ne_top (inv_nonneg_of_nonneg h) (inv_lt_top c).ne
end EReal
namespace Mathlib.Meta.Positivity
open Lean Meta Qq Function
/-- Extension for the `positivity` tactic: inverse of an `EReal`. -/
@[positivity (_⁻¹ : EReal)]
def evalERealInv : PositivityExt where eval {u α} zα pα e := do
match u, α, e with
| 0, ~q(EReal), ~q($a⁻¹) =>
assertInstancesCommute
match (← core zα pα a).toNonneg with
| some pa => pure (.nonnegative q(EReal.inv_nonneg_of_nonneg <| $pa))
| none => pure .none
| _, _, _ => throwError "not an inverse of an `EReal`"
/-- Extension for the `positivity` tactic: ratio of two `EReal`s. -/
@[positivity (_ / _ : EReal)]
def evalERealDiv : PositivityExt where eval {u α} zα pα e := do
match u, α, e with
| 0, ~q(EReal), ~q($a / $b) =>
assertInstancesCommute
match (← core zα pα a).toNonneg with
| some pa =>
match (← core zα pα b).toNonneg with
| some pb => pure (.nonnegative q(EReal.div_nonneg $pa $pb))
| none => pure .none
| _ => pure .none
| _, _, _ => throwError "not a ratio of 2 `EReal`s"
end Mathlib.Meta.Positivity |
.lake/packages/mathlib/Mathlib/Data/W/Basic.lean | import Mathlib.Data.Finset.Lattice.Fold
import Mathlib.Logic.Encodable.Pi
/-!
# W types
Given `α : Type` and `β : α → Type`, the W type determined by this data, `WType β`, is the
inductively defined type of trees where the nodes are labeled by elements of `α` and the children of
a node labeled `a` are indexed by elements of `β a`.
This file is currently a stub, awaiting a full development of the theory. Currently, the main result
is that if `α` is an encodable fintype and `β a` is encodable for every `a : α`, then `WType β` is
encodable. This can be used to show the encodability of other inductive types, such as those that
are commonly used to formalize syntax, e.g. terms and expressions in a given language. The strategy
is illustrated in the example found in the file `prop_encodable` in the `archive/examples` folder of
mathlib.
## Implementation details
While the name `WType` is somewhat verbose, it is preferable to putting a single character
identifier `W` in the root namespace.
-/
-- For "W_type"
/--
Given `β : α → Type*`, `WType β` is the type of finitely branching trees where nodes are labeled by
elements of `α` and the children of a node labeled `a` are indexed by elements of `β a`.
-/
inductive WType {α : Type*} (β : α → Type*)
| mk (a : α) (f : β a → WType β) : WType β
instance : Inhabited (WType fun _ : Unit => Empty) :=
⟨WType.mk Unit.unit Empty.elim⟩
namespace WType
variable {α : Type*} {β : α → Type*}
/-- The canonical map to the corresponding sigma type, returning the label of a node as an
element `a` of `α`, and the children of the node as a function `β a → WType β`. -/
def toSigma : WType β → Σ a : α, β a → WType β
| ⟨a, f⟩ => ⟨a, f⟩
/-- The canonical map from the sigma type into a `WType`. Given a node `a : α`, and
its children as a function `β a → WType β`, return the corresponding tree. -/
def ofSigma : (Σ a : α, β a → WType β) → WType β
| ⟨a, f⟩ => WType.mk a f
@[simp]
theorem ofSigma_toSigma : ∀ w : WType β, ofSigma (toSigma w) = w
| ⟨_, _⟩ => rfl
@[simp]
theorem toSigma_ofSigma : ∀ s : Σ a : α, β a → WType β, toSigma (ofSigma s) = s
| ⟨_, _⟩ => rfl
variable (β) in
/-- The canonical bijection with the sigma type, showing that `WType` is a fixed point of
the polynomial functor `X ↦ Σ a : α, β a → X`. -/
@[simps]
def equivSigma : WType β ≃ Σ a : α, β a → WType β where
toFun := toSigma
invFun := ofSigma
left_inv := ofSigma_toSigma
right_inv := toSigma_ofSigma
/-- The canonical map from `WType β` into any type `γ` given a map `(Σ a : α, β a → γ) → γ`. -/
def elim (γ : Type*) (fγ : (Σ a : α, β a → γ) → γ) : WType β → γ
| ⟨a, f⟩ => fγ ⟨a, fun b => elim γ fγ (f b)⟩
theorem elim_injective (γ : Type*) (fγ : (Σ a : α, β a → γ) → γ)
(fγ_injective : Function.Injective fγ) : Function.Injective (elim γ fγ)
| ⟨a₁, f₁⟩, ⟨a₂, f₂⟩, h => by
obtain ⟨rfl, h⟩ := Sigma.mk.inj_iff.mp (fγ_injective h)
congr with x
exact elim_injective γ fγ fγ_injective (congr_fun (eq_of_heq h) x :)
instance [hα : IsEmpty α] : IsEmpty (WType β) :=
⟨fun w => WType.recOn w (IsEmpty.elim hα)⟩
theorem infinite_of_nonempty_of_isEmpty (a b : α) [ha : Nonempty (β a)] [he : IsEmpty (β b)] :
Infinite (WType β) :=
⟨by
intro hf
have hba : b ≠ a := fun h => ha.elim (IsEmpty.elim' (show IsEmpty (β a) from h ▸ he))
refine
not_injective_infinite_finite
(fun n : ℕ =>
show WType β from Nat.recOn n ⟨b, IsEmpty.elim' he⟩ fun _ ih => ⟨a, fun _ => ih⟩)
?_
intro n m h
induction n generalizing m with
| zero => rcases m with - | m <;> simp_all
| succ n ih =>
rcases m with - | m
· simp_all
· refine congr_arg Nat.succ (ih ?_)
simp_all [funext_iff]⟩
variable [∀ a : α, Fintype (β a)]
/-- The depth of a finitely branching tree. -/
def depth : WType β → ℕ
| ⟨_, f⟩ => (Finset.sup Finset.univ fun n => depth (f n)) + 1
theorem depth_pos (t : WType β) : 0 < t.depth := by
cases t
apply Nat.succ_pos
theorem depth_lt_depth_mk (a : α) (f : β a → WType β) (i : β a) : depth (f i) < depth ⟨a, f⟩ :=
Nat.lt_succ_of_le (Finset.le_sup (f := (depth <| f ·)) (Finset.mem_univ i))
/-
Show that W types are encodable when `α` is an encodable fintype and for every `a : α`, `β a` is
encodable.
We define an auxiliary type `WType' β n` of trees of depth at most `n`, and then we show by
induction on `n` that these are all encodable. These auxiliary constructions are not interesting in
and of themselves, so we mark them as `private`.
-/
private abbrev WType' {α : Type*} (β : α → Type*) [∀ a : α, Fintype (β a)]
[∀ a : α, Encodable (β a)] (n : ℕ) :=
{ t : WType β // t.depth ≤ n }
variable [∀ a : α, Encodable (β a)]
private def encodable_zero : Encodable (WType' β 0) :=
let f : WType' β 0 → Empty := fun ⟨_, h⟩ => False.elim <| not_lt_of_ge h (WType.depth_pos _)
let finv : Empty → WType' β 0 := by
intro x
cases x
have : ∀ x, finv (f x) = x := fun ⟨_, h⟩ => False.elim <| not_lt_of_ge h (WType.depth_pos _)
Encodable.ofLeftInverse f finv this
private def f (n : ℕ) : WType' β (n + 1) → Σ a : α, β a → WType' β n
| ⟨t, h⟩ => by
obtain ⟨a, f⟩ := t
have h₀ : ∀ i : β a, WType.depth (f i) ≤ n := fun i =>
Nat.le_of_lt_succ (lt_of_lt_of_le (WType.depth_lt_depth_mk a f i) h)
exact ⟨a, fun i : β a => ⟨f i, h₀ i⟩⟩
private def finv (n : ℕ) : (Σ a : α, β a → WType' β n) → WType' β (n + 1)
| ⟨a, f⟩ =>
let f' := fun i : β a => (f i).val
have : WType.depth ⟨a, f'⟩ ≤ n + 1 := Nat.add_le_add_right (Finset.sup_le fun b _ => (f b).2) 1
⟨⟨a, f'⟩, this⟩
variable [Encodable α]
private def encodable_succ (n : Nat) (_ : Encodable (WType' β n)) : Encodable (WType' β (n + 1)) :=
Encodable.ofLeftInverse (f n) (finv n)
(by
rintro ⟨⟨_, _⟩, _⟩
rfl)
/-- `WType` is encodable when `α` is an encodable fintype and for every `a : α`, `β a` is
encodable. -/
instance : Encodable (WType β) := by
haveI h' : ∀ n, Encodable (WType' β n) := fun n => Nat.rec encodable_zero encodable_succ n
let f : WType β → Σ n, WType' β n := fun t => ⟨t.depth, ⟨t, le_rfl⟩⟩
let finv : (Σ n, WType' β n) → WType β := fun p => p.2.1
have : ∀ t, finv (f t) = t := fun t => rfl
exact Encodable.ofLeftInverse f finv this
end WType |
.lake/packages/mathlib/Mathlib/Data/W/Constructions.lean | import Mathlib.Data.W.Basic
/-!
# Examples of W-types
We take the view of W types as inductive types.
Given `α : Type` and `β : α → Type`, the W type determined by this data, `WType β`, is the
inductively with constructors from `α` and arities of each constructor `a : α` given by `β a`.
This file contains `Nat` and `List` as examples of W types.
## Main results
* `WType.equivNat`: the construction of the naturals as a W-type is equivalent to `Nat`
* `WType.equivList`: the construction of lists on a type `γ` as a W-type is equivalent to `List γ`
-/
universe u v
namespace WType
-- For "W_type"
section Nat
/-- The constructors for the naturals -/
inductive Natα : Type
| zero : Natα
| succ : Natα
instance : Inhabited Natα :=
⟨Natα.zero⟩
/-- The arity of the constructors for the naturals, `zero` takes no arguments, `succ` takes one -/
def Natβ : Natα → Type
| Natα.zero => Empty
| Natα.succ => Unit
instance : Inhabited (Natβ Natα.succ) :=
⟨()⟩
/-- The isomorphism from the naturals to its corresponding `WType` -/
@[simp]
def ofNat : ℕ → WType Natβ
| Nat.zero => ⟨Natα.zero, Empty.elim⟩
| Nat.succ n => ⟨Natα.succ, fun _ ↦ ofNat n⟩
/-- The isomorphism from the `WType` of the naturals to the naturals -/
@[simp]
def toNat : WType Natβ → ℕ
| WType.mk Natα.zero _ => 0
| WType.mk Natα.succ f => (f ()).toNat.succ
theorem leftInverse_nat : Function.LeftInverse ofNat toNat
| WType.mk Natα.zero f => by
rw [toNat, ofNat]
congr
ext x
cases x
| WType.mk Natα.succ f => by
simp only [toNat, ofNat, leftInverse_nat (f ()), mk.injEq, heq_eq_eq, true_and]
rfl
theorem rightInverse_nat : Function.RightInverse ofNat toNat
| Nat.zero => rfl
| Nat.succ n => by rw [ofNat, toNat, rightInverse_nat n]
/-- The naturals are equivalent to their associated `WType` -/
def equivNat : WType Natβ ≃ ℕ where
toFun := toNat
invFun := ofNat
left_inv := leftInverse_nat
right_inv := rightInverse_nat
open Sum PUnit
/-- `WType.Natα` is equivalent to `PUnit ⊕ PUnit`.
This is useful when considering the associated polynomial endofunctor.
-/
@[simps]
def NatαEquivPUnitSumPUnit : Natα ≃ PUnit.{u + 1} ⊕ PUnit where
toFun c :=
match c with
| Natα.zero => inl unit
| Natα.succ => inr unit
invFun b :=
match b with
| inl _ => Natα.zero
| inr _ => Natα.succ
left_inv c :=
match c with
| Natα.zero => rfl
| Natα.succ => rfl
right_inv b :=
match b with
| inl _ => rfl
| inr _ => rfl
end Nat
section List
variable (γ : Type u)
/-- The constructors for lists.
There is "one constructor `cons x` for each `x : γ`",
since we view `List γ` as
```
| nil : List γ
| cons x₀ : List γ → List γ
| cons x₁ : List γ → List γ
| ⋮ γ many times
```
-/
inductive Listα : Type u
| nil : Listα
| cons : γ → Listα
instance : Inhabited (Listα γ) :=
⟨Listα.nil⟩
/-- The arities of each constructor for lists, `nil` takes no arguments, `cons hd` takes one -/
def Listβ : Listα γ → Type u
| Listα.nil => PEmpty
| Listα.cons _ => PUnit
instance (hd : γ) : Inhabited (Listβ γ (Listα.cons hd)) :=
⟨PUnit.unit⟩
/-- The isomorphism from lists to the `WType` construction of lists -/
@[simp]
def ofList : List γ → WType (Listβ γ)
| List.nil => ⟨Listα.nil, PEmpty.elim⟩
| List.cons hd tl => ⟨Listα.cons hd, fun _ ↦ ofList tl⟩
/-- The isomorphism from the `WType` construction of lists to lists -/
@[simp]
def toList : WType (Listβ γ) → List γ
| WType.mk Listα.nil _ => []
| WType.mk (Listα.cons hd) f => hd :: (f PUnit.unit).toList
theorem leftInverse_list : Function.LeftInverse (ofList γ) (toList _)
| WType.mk Listα.nil f => by
simp only [toList, ofList, mk.injEq, heq_eq_eq, true_and]
ext x
cases x
| WType.mk (Listα.cons x) f => by
simp only [toList, ofList, leftInverse_list (f PUnit.unit), mk.injEq, heq_eq_eq, true_and]
rfl
theorem rightInverse_list : Function.RightInverse (ofList γ) (toList _)
| List.nil => rfl
| List.cons hd tl => by simp [rightInverse_list tl]
/-- Lists are equivalent to their associated `WType` -/
def equivList : WType (Listβ γ) ≃ List γ where
toFun := toList _
invFun := ofList _
left_inv := leftInverse_list _
right_inv := rightInverse_list _
/-- `WType.Listα` is equivalent to `γ` with an extra point.
This is useful when considering the associated polynomial endofunctor
-/
def ListαEquivPUnitSum : Listα γ ≃ PUnit.{v + 1} ⊕ γ where
toFun c :=
match c with
| Listα.nil => Sum.inl PUnit.unit
| Listα.cons x => Sum.inr x
invFun := Sum.elim (fun _ ↦ Listα.nil) Listα.cons
left_inv c :=
match c with
| Listα.nil => rfl
| Listα.cons _ => rfl
right_inv x :=
match x with
| Sum.inl PUnit.unit => rfl
| Sum.inr _ => rfl
end List
end WType |
.lake/packages/mathlib/Mathlib/Data/W/Cardinal.lean | import Mathlib.Data.W.Basic
import Mathlib.SetTheory.Cardinal.Arithmetic
/-!
# Cardinality of W-types
This file proves some theorems about the cardinality of W-types. The main result is
`cardinalMk_le_max_aleph0_of_finite` which says that if for any `a : α`,
`β a` is finite, then the cardinality of `WType β` is at most the maximum of the
cardinality of `α` and `ℵ₀`.
This can be used to prove theorems about the cardinality of algebraic constructions such as
polynomials. There is a surjection from a `WType` to `MvPolynomial` for example, and
this surjection can be used to put an upper bound on the cardinality of `MvPolynomial`.
## Tags
W, W type, cardinal, first order
-/
universe u v
variable {α : Type u} {β : α → Type v}
noncomputable section
namespace WType
open Cardinal
theorem cardinalMk_eq_sum_lift : #(WType β) = sum fun a ↦ #(WType β) ^ lift.{u} #(β a) :=
(mk_congr <| equivSigma β).trans <| by
simp_rw [mk_sigma, mk_arrow]; rw [lift_id'.{v, u}, lift_umax.{v, u}]
/-- `#(WType β)` is the least cardinal `κ` such that `sum (fun a : α ↦ κ ^ #(β a)) ≤ κ` -/
theorem cardinalMk_le_of_le' {κ : Cardinal.{max u v}}
(hκ : (sum fun a : α => κ ^ lift.{u} #(β a)) ≤ κ) :
#(WType β) ≤ κ := by
induction κ using Cardinal.inductionOn with | _ γ
simp_rw [← lift_umax.{v, u}] at hκ
nth_rewrite 1 [← lift_id'.{v, u} #γ] at hκ
simp_rw [← mk_arrow, ← mk_sigma, le_def] at hκ
obtain ⟨hκ⟩ := hκ
exact Cardinal.mk_le_of_injective (elim_injective _ hκ.1 hκ.2)
/-- If, for any `a : α`, `β a` is finite, then the cardinality of `WType β`
is at most the maximum of the cardinality of `α` and `ℵ₀` -/
theorem cardinalMk_le_max_aleph0_of_finite' [∀ a, Finite (β a)] :
#(WType β) ≤ max (lift.{v} #α) ℵ₀ :=
(isEmpty_or_nonempty α).elim
(by
intro h
rw [Cardinal.mk_eq_zero (WType β)]
exact zero_le _)
fun hn =>
let m := max (lift.{v} #α) ℵ₀
cardinalMk_le_of_le' <|
calc
(Cardinal.sum fun a => m ^ lift.{u} #(β a)) ≤ lift.{v} #α * ⨆ a, m ^ lift.{u} #(β a) :=
Cardinal.sum_le_lift_mk_mul_iSup _
_ ≤ m * ⨆ a, m ^ lift.{u} #(β a) := mul_le_mul' (le_max_left _ _) le_rfl
_ = m :=
mul_eq_left (le_max_right _ _)
(ciSup_le' fun _ => pow_le (le_max_right _ _) (lt_aleph0_of_finite _)) <|
pos_iff_ne_zero.1 <|
Order.succ_le_iff.1
(by
rw [succ_zero]
obtain ⟨a⟩ : Nonempty α := hn
refine le_trans ?_ (le_ciSup (bddAbove_range _) a)
rw [← power_zero]
exact
power_le_power_left
(pos_iff_ne_zero.1 (aleph0_pos.trans_le (le_max_right _ _))) (zero_le _))
variable {β : α → Type u}
theorem cardinalMk_eq_sum : #(WType β) = sum (fun a : α => #(WType β) ^ #(β a)) :=
cardinalMk_eq_sum_lift.trans <| by simp_rw [lift_id]
/-- `#(WType β)` is the least cardinal `κ` such that `sum (fun a : α ↦ κ ^ #(β a)) ≤ κ` -/
theorem cardinalMk_le_of_le {κ : Cardinal.{u}} (hκ : (sum fun a : α => κ ^ #(β a)) ≤ κ) :
#(WType β) ≤ κ := cardinalMk_le_of_le' <| by simp_rw [lift_id]; exact hκ
/-- If, for any `a : α`, `β a` is finite, then the cardinality of `WType β`
is at most the maximum of the cardinality of `α` and `ℵ₀` -/
theorem cardinalMk_le_max_aleph0_of_finite [∀ a, Finite (β a)] : #(WType β) ≤ max #α ℵ₀ :=
cardinalMk_le_max_aleph0_of_finite'.trans_eq <| by rw [lift_id]
end WType |
.lake/packages/mathlib/Mathlib/Control/Applicative.lean | import Mathlib.Algebra.Group.Defs
import Mathlib.Control.Functor
import Mathlib.Control.Basic
/-!
# `applicative` instances
This file provides `Applicative` instances for concrete functors:
* `id`
* `Functor.comp`
* `Functor.const`
* `Functor.add_const`
-/
universe u v w
section Lemmas
open Function
variable {F : Type u → Type v}
variable [Applicative F] [LawfulApplicative F]
variable {α β γ σ : Type u}
theorem Applicative.map_seq_map (f : α → β → γ) (g : σ → β) (x : F α) (y : F σ) :
f <$> x <*> g <$> y = ((· ∘ g) ∘ f) <$> x <*> y := by
simp [functor_norm, Function.comp_def]
theorem Applicative.pure_seq_eq_map' (f : α → β) : ((pure f : F (α → β)) <*> ·) = (f <$> ·) := by
simp [functor_norm]
theorem Applicative.ext {F} :
∀ {A1 : Applicative F} {A2 : Applicative F} [@LawfulApplicative F A1] [@LawfulApplicative F A2],
(∀ {α : Type u} (x : α), @Pure.pure _ A1.toPure _ x = @Pure.pure _ A2.toPure _ x) →
(∀ {α β : Type u} (f : F (α → β)) (x : F α),
@Seq.seq _ A1.toSeq _ _ f (fun _ => x) = @Seq.seq _ A2.toSeq _ _ f (fun _ => x)) →
A1 = A2
| { toFunctor := F1, seq := s1, pure := p1, seqLeft := sl1, seqRight := sr1 },
{ toFunctor := F2, seq := s2, pure := p2, seqLeft := sl2, seqRight := sr2 },
L1, L2, H1, H2 => by
obtain rfl : @p1 = @p2 := by
funext α x
apply H1
obtain rfl : @s1 = @s2 := by
funext α β f x
exact H2 f (x Unit.unit)
obtain ⟨seqLeft_eq1, seqRight_eq1, pure_seq1, -⟩ := L1
obtain ⟨seqLeft_eq2, seqRight_eq2, pure_seq2, -⟩ := L2
obtain rfl : F1 = F2 := by
apply Functor.ext
intros
exact (pure_seq1 _ _).symm.trans (pure_seq2 _ _)
congr <;> funext α β x y
· exact (seqLeft_eq1 _ (y Unit.unit)).trans (seqLeft_eq2 _ _).symm
· exact (seqRight_eq1 _ (y Unit.unit)).trans (seqRight_eq2 _ (y Unit.unit)).symm
end Lemmas
-- Porting note: we have a monad instance for `Id` but not `id`, mathport can't tell
-- which one is intended
instance : CommApplicative Id where commutative_prod _ _ := rfl
namespace Functor
namespace Comp
open Function hiding comp
open Functor
variable {F : Type u → Type w} {G : Type v → Type u}
variable [Applicative F] [Applicative G]
variable [LawfulApplicative F] [LawfulApplicative G]
variable {α β γ : Type v}
theorem map_pure (f : α → β) (x : α) : (f <$> pure x : Comp F G β) = pure (f x) :=
Comp.ext <| by simp
theorem seq_pure (f : Comp F G (α → β)) (x : α) : f <*> pure x = (fun g : α → β => g x) <$> f :=
Comp.ext <| by simp [functor_norm]
theorem seq_assoc (x : Comp F G α) (f : Comp F G (α → β)) (g : Comp F G (β → γ)) :
g <*> (f <*> x) = @Function.comp α β γ <$> g <*> f <*> x :=
Comp.ext <| by simp [comp_def, functor_norm]
theorem pure_seq_eq_map (f : α → β) (x : Comp F G α) : pure f <*> x = f <$> x :=
Comp.ext <| by simp [functor_norm]
-- TODO: the first two results were handled by `control_laws_tac` in mathlib3
instance instLawfulApplicativeComp : LawfulApplicative (Comp F G) where
seqLeft_eq := by intros; rfl
seqRight_eq := by intros; rfl
pure_seq := Comp.pure_seq_eq_map
map_pure := Comp.map_pure
seq_pure := Comp.seq_pure
seq_assoc := Comp.seq_assoc
theorem applicative_id_comp {F} [AF : Applicative F] [LawfulApplicative F] :
@instApplicativeComp Id F _ _ = AF :=
@Applicative.ext F _ _ (instLawfulApplicativeComp (F := Id)) _
(fun _ => rfl) (fun _ _ => rfl)
theorem applicative_comp_id {F} [AF : Applicative F] [LawfulApplicative F] :
@Comp.instApplicativeComp F Id _ _ = AF :=
@Applicative.ext F _ _ (instLawfulApplicativeComp (G := Id)) _
(fun _ => rfl) (fun f x => show id <$> f <*> x = f <*> x by rw [id_map])
open CommApplicative
instance {f : Type u → Type w} {g : Type v → Type u} [Applicative f] [Applicative g]
[CommApplicative f] [CommApplicative g] : CommApplicative (Comp f g) where
commutative_prod _ _ := by
simp! [map, Seq.seq]
rw [commutative_map]
simp only [mk, flip, seq_map_assoc, Function.comp_def, map_map]
congr
funext x y
rw [commutative_map]
congr
end Comp
end Functor
open Functor
@[functor_norm]
theorem Comp.seq_mk {α β : Type w} {f : Type u → Type v} {g : Type w → Type u} [Applicative f]
[Applicative g] (h : f (g (α → β))) (x : f (g α)) :
Comp.mk h <*> Comp.mk x = Comp.mk ((· <*> ·) <$> h <*> x) :=
rfl
-- Porting note: There is some awkwardness in the following definition now that we have `HMul`.
instance {α} [One α] [Mul α] : Applicative (Const α) where
pure _ := (1 : α)
seq f x := (show α from f) * (show α from x Unit.unit)
-- Porting note: `(· <*> ·)` needed to change to `Seq.seq` in the `simp`.
-- Also, `simp` didn't close `refl` goals.
instance {α} [Monoid α] : LawfulApplicative (Const α) where
map_pure _ _ := rfl
seq_pure _ _ := by simp [Const.map, map, Seq.seq, pure, mul_one]
pure_seq _ _ := by simp [Const.map, map, Seq.seq, pure, one_mul]
seqLeft_eq _ _ := by simp [Seq.seq, SeqLeft.seqLeft]
seqRight_eq _ _ := by simp [Seq.seq, SeqRight.seqRight]
seq_assoc _ _ _ := by simp [Const.map, map, Seq.seq, mul_assoc]
instance {α} [Zero α] [Add α] : Applicative (AddConst α) where
pure _ := (0 : α)
seq f x := (show α from f) + (show α from x Unit.unit)
instance {α} [AddMonoid α] : LawfulApplicative (AddConst α) where
map_pure _ _ := rfl
seq_pure _ _ := by simp [Const.map, map, Seq.seq, pure, add_zero]
pure_seq _ _ := by simp [Const.map, map, Seq.seq, pure, zero_add]
seqLeft_eq _ _ := by simp [Seq.seq, SeqLeft.seqLeft]
seqRight_eq _ _ := by simp [Seq.seq, SeqRight.seqRight]
seq_assoc _ _ _ := by simp [Const.map, map, Seq.seq, add_assoc] |
.lake/packages/mathlib/Mathlib/Control/LawfulFix.lean | import Mathlib.Data.Stream.Init
import Mathlib.Tactic.ApplyFun
import Mathlib.Control.Fix
import Mathlib.Order.OmegaCompletePartialOrder
/-!
# Lawful fixed point operators
This module defines the laws required of a `Fix` instance, using the theory of
omega complete partial orders (ωCPO). Proofs of the lawfulness of all `Fix` instances in
`Control.Fix` are provided.
## Main definition
* class `LawfulFix`
-/
universe u v
variable {α : Type*} {β : α → Type*}
open OmegaCompletePartialOrder
/-- Intuitively, a fixed point operator `fix` is lawful if it satisfies `fix f = f (fix f)` for all
`f`, but this is inconsistent / uninteresting in most cases due to the existence of "exotic"
functions `f`, such as the function that is defined iff its argument is not, familiar from the
halting problem. Instead, this requirement is limited to only functions that are `Continuous` in the
sense of `ω`-complete partial orders, which excludes the example because it is not monotone
(making the input argument less defined can make `f` more defined). -/
class LawfulFix (α : Type*) [OmegaCompletePartialOrder α] extends Fix α where
fix_eq : ∀ {f : α → α}, ωScottContinuous f → Fix.fix f = f (Fix.fix f)
namespace Part
open Nat Nat.Upto
namespace Fix
variable (f : ((a : _) → Part <| β a) →o (a : _) → Part <| β a)
theorem approx_mono' {i : ℕ} : Fix.approx f i ≤ Fix.approx f (succ i) := by
induction i with
| zero => dsimp [approx]; apply @bot_le _ _ _ (f ⊥)
| succ _ i_ih => intro; apply f.monotone; apply i_ih
theorem approx_mono ⦃i j : ℕ⦄ (hij : i ≤ j) : approx f i ≤ approx f j := by
induction j with
| zero => cases hij; exact le_rfl
| succ j ih =>
cases hij; · exact le_rfl
exact le_trans (ih ‹_›) (approx_mono' f)
theorem mem_iff (a : α) (b : β a) : b ∈ Part.fix f a ↔ ∃ i, b ∈ approx f i a := by
classical
by_cases h₀ : ∃ i : ℕ, (approx f i a).Dom
· simp only [Part.fix_def f h₀]
constructor <;> intro hh
· exact ⟨_, hh⟩
have h₁ := Nat.find_spec h₀
rw [dom_iff_mem] at h₁
obtain ⟨y, h₁⟩ := h₁
replace h₁ := approx_mono' f _ _ h₁
suffices y = b by
subst this
exact h₁
obtain ⟨i, hh⟩ := hh
revert h₁; generalize succ (Nat.find h₀) = j; intro h₁
wlog case : i ≤ j
· rcases le_total i j with H | H <;> [skip; symm] <;> apply_assumption <;> assumption
replace hh := approx_mono f case _ _ hh
apply Part.mem_unique h₁ hh
· simp only [fix_def' (⇑f) h₀, not_exists, false_iff, notMem_none]
simp only [dom_iff_mem, not_exists] at h₀
intro; apply h₀
theorem approx_le_fix (i : ℕ) : approx f i ≤ Part.fix f := fun a b hh ↦ by
rw [mem_iff f]
exact ⟨_, hh⟩
theorem exists_fix_le_approx (x : α) : ∃ i, Part.fix f x ≤ approx f i x := by
by_cases! hh : ∃ i b, b ∈ approx f i x
· rcases hh with ⟨i, b, hb⟩
exists i
intro b' h'
have hb' := approx_le_fix f i _ _ hb
obtain rfl := Part.mem_unique h' hb'
exact hb
· exists 0
intro b' h'
simp only [mem_iff f] at h'
obtain ⟨i, h'⟩ := h'
cases hh _ _ h'
/-- The series of approximations of `fix f` (see `approx`) as a `Chain` -/
def approxChain : Chain ((a : _) → Part <| β a) :=
⟨approx f, approx_mono f⟩
theorem le_f_of_mem_approx {x} : x ∈ approxChain f → x ≤ f x := by
simp only [Membership.mem, forall_exists_index]
rintro i rfl
apply approx_mono'
theorem approx_mem_approxChain {i} : approx f i ∈ approxChain f :=
Stream'.mem_of_get_eq rfl
end Fix
open Fix
variable {α : Type*}
variable (f : ((a : _) → Part <| β a) →o (a : _) → Part <| β a)
theorem fix_eq_ωSup : Part.fix f = ωSup (approxChain f) := by
apply le_antisymm
· intro x
obtain ⟨i, hx⟩ := exists_fix_le_approx f x
trans approx f i.succ x
· trans
· apply hx
· apply approx_mono' f
apply le_ωSup_of_le i.succ
dsimp [approx]
rfl
· apply ωSup_le _ _ _
simp only [Fix.approxChain]
intro y x
apply approx_le_fix f
theorem fix_le {X : (a : _) → Part <| β a} (hX : f X ≤ X) : Part.fix f ≤ X := by
rw [fix_eq_ωSup f]
apply ωSup_le _ _ _
simp only [Fix.approxChain]
intro i
induction i with
| zero => dsimp [Fix.approx]; apply bot_le
| succ _ i_ih =>
trans f X
· apply f.monotone i_ih
· apply hX
variable {g : ((a : _) → Part <| β a) → (a : _) → Part <| β a}
theorem fix_eq_ωSup_of_ωScottContinuous (hc : ωScottContinuous g) : Part.fix g =
ωSup (approxChain (⟨g,hc.monotone⟩ : ((a : _) → Part <| β a) →o (a : _) → Part <| β a)) := by
rw [← fix_eq_ωSup]
rfl
theorem fix_eq_of_ωScottContinuous (hc : ωScottContinuous g) :
Part.fix g = g (Part.fix g) := by
rw [fix_eq_ωSup_of_ωScottContinuous hc, hc.map_ωSup]
apply le_antisymm
· apply ωSup_le_ωSup_of_le _
intro i
exists i
intro x
apply le_f_of_mem_approx _ ⟨i, rfl⟩
· apply ωSup_le_ωSup_of_le _
intro i
exists i.succ
variable {f}
end Part
namespace Part
/-- `toUnit` as a monotone function -/
@[simps]
def toUnitMono (f : Part α →o Part α) : (Unit → Part α) →o Unit → Part α where
toFun x u := f (x u)
monotone' x y (h : x ≤ y) u := f.monotone <| h u
theorem ωScottContinuous_toUnitMono (f : Part α → Part α) (hc : ωScottContinuous f) :
ωScottContinuous (toUnitMono ⟨f,hc.monotone⟩) := .of_map_ωSup_of_orderHom fun _ => by
ext ⟨⟩ : 1
dsimp [OmegaCompletePartialOrder.ωSup]
erw [hc.map_ωSup]
rw [Chain.map_comp]
rfl
noncomputable instance lawfulFix : LawfulFix (Part α) :=
⟨fun {f : Part α → Part α} hc ↦ show Part.fix (toUnitMono ⟨f,hc.monotone⟩) () = _ by
rw [Part.fix_eq_of_ωScottContinuous (ωScottContinuous_toUnitMono f hc)]; rfl⟩
end Part
open Sigma
namespace Pi
noncomputable instance lawfulFix {β} : LawfulFix (α → Part β) :=
⟨fun {_f} ↦ Part.fix_eq_of_ωScottContinuous⟩
variable {γ : ∀ a : α, β a → Type*}
section Monotone
variable (α β γ)
/-- `Sigma.curry` as a monotone function. -/
@[simps]
def monotoneCurry [(x y : _) → Preorder <| γ x y] :
(∀ x : Σ a, β a, γ x.1 x.2) →o ∀ (a) (b : β a), γ a b where
toFun := curry
monotone' _x _y h a b := h ⟨a, b⟩
/-- `Sigma.uncurry` as a monotone function. -/
@[simps]
def monotoneUncurry [(x y : _) → Preorder <| γ x y] :
(∀ (a) (b : β a), γ a b) →o ∀ x : Σ a, β a, γ x.1 x.2 where
toFun := uncurry
monotone' _x _y h a := h a.1 a.2
variable [(x y : _) → OmegaCompletePartialOrder <| γ x y]
open OmegaCompletePartialOrder.Chain
theorem ωScottContinuous_curry :
ωScottContinuous (monotoneCurry α β γ) :=
ωScottContinuous.of_map_ωSup_of_orderHom fun c ↦ by
ext x y
dsimp [curry, ωSup]
rw [map_comp, map_comp]
rfl
theorem ωScottContinuous_uncurry :
ωScottContinuous (monotoneUncurry α β γ) :=
.of_map_ωSup_of_orderHom fun c ↦ by
ext ⟨x, y⟩
dsimp [uncurry, ωSup]
rw [map_comp, map_comp]
rfl
end Monotone
open Fix
instance hasFix [Fix <| (x : Sigma β) → γ x.1 x.2] : Fix ((x : _) → (y : β x) → γ x y) :=
⟨fun f ↦ curry (fix <| uncurry ∘ f ∘ curry)⟩
variable [∀ x y, OmegaCompletePartialOrder <| γ x y]
section Curry
variable {f : (∀ a b, γ a b) → ∀ a b, γ a b}
theorem uncurry_curry_ωScottContinuous (hc : ωScottContinuous f) :
ωScottContinuous <| (monotoneUncurry α β γ).comp <|
(⟨f,hc.monotone⟩ : ((x : _) → (y : β x) → γ x y) →o (x : _) → (y : β x) → γ x y).comp <|
monotoneCurry α β γ :=
(ωScottContinuous_uncurry _ _ _).comp (hc.comp (ωScottContinuous_curry _ _ _))
end Curry
instance lawfulFix' [LawfulFix <| (x : Sigma β) → γ x.1 x.2] :
LawfulFix ((x y : _) → γ x y) where
fix_eq {_f} hc := by
dsimp [fix]
conv_lhs => erw [LawfulFix.fix_eq (uncurry_curry_ωScottContinuous hc)]
rfl
end Pi |
.lake/packages/mathlib/Mathlib/Control/Bifunctor.lean | import Mathlib.Control.Functor
import Mathlib.Tactic.Common
/-!
# Functors with two arguments
This file defines bifunctors.
A bifunctor is a function `F : Type* → Type* → Type*` along with a bimap which turns `F α β` into
`F α' β'` given two functions `α → α'` and `β → β'`. It further
* respects the identity: `bimap id id = id`
* composes in the obvious way: `(bimap f' g') ∘ (bimap f g) = bimap (f' ∘ f) (g' ∘ g)`
## Main declarations
* `Bifunctor`: A typeclass for the bare bimap of a bifunctor.
* `LawfulBifunctor`: A typeclass asserting this bimap respects the bifunctor laws.
-/
universe u₀ u₁ u₂ v₀ v₁ v₂
open Function
/-- Lawless bifunctor. This typeclass only holds the data for the bimap. -/
class Bifunctor (F : Type u₀ → Type u₁ → Type u₂) where
bimap : ∀ {α α' β β'}, (α → α') → (β → β') → F α β → F α' β'
export Bifunctor (bimap)
/-- Bifunctor. This typeclass asserts that a lawless `Bifunctor` is lawful. -/
class LawfulBifunctor (F : Type u₀ → Type u₁ → Type u₂) [Bifunctor F] : Prop where
id_bimap : ∀ {α β} (x : F α β), bimap id id x = x
bimap_bimap :
∀ {α₀ α₁ α₂ β₀ β₁ β₂} (f : α₀ → α₁) (f' : α₁ → α₂) (g : β₀ → β₁) (g' : β₁ → β₂) (x : F α₀ β₀),
bimap f' g' (bimap f g x) = bimap (f' ∘ f) (g' ∘ g) x
export LawfulBifunctor (id_bimap bimap_bimap)
attribute [higher_order bimap_id_id] id_bimap
attribute [higher_order bimap_comp_bimap] bimap_bimap
export LawfulBifunctor (bimap_id_id bimap_comp_bimap)
variable {F : Type u₀ → Type u₁ → Type u₂} [Bifunctor F]
namespace Bifunctor
/-- Left map of a bifunctor. -/
abbrev fst {α α' β} (f : α → α') : F α β → F α' β :=
bimap f id
/-- Right map of a bifunctor. -/
abbrev snd {α β β'} (f : β → β') : F α β → F α β' :=
bimap id f
variable [LawfulBifunctor F]
@[higher_order fst_id]
theorem id_fst : ∀ {α β} (x : F α β), fst id x = x :=
@id_bimap _ _ _
@[higher_order snd_id]
theorem id_snd : ∀ {α β} (x : F α β), snd id x = x :=
@id_bimap _ _ _
@[higher_order fst_comp_fst]
theorem comp_fst {α₀ α₁ α₂ β} (f : α₀ → α₁) (f' : α₁ → α₂) (x : F α₀ β) :
fst f' (fst f x) = fst (f' ∘ f) x := by simp [fst, bimap_bimap]
@[higher_order fst_comp_snd]
theorem fst_snd {α₀ α₁ β₀ β₁} (f : α₀ → α₁) (f' : β₀ → β₁) (x : F α₀ β₀) :
fst f (snd f' x) = bimap f f' x := by simp [fst, bimap_bimap]
@[higher_order snd_comp_fst]
theorem snd_fst {α₀ α₁ β₀ β₁} (f : α₀ → α₁) (f' : β₀ → β₁) (x : F α₀ β₀) :
snd f' (fst f x) = bimap f f' x := by simp [snd, bimap_bimap]
@[higher_order snd_comp_snd]
theorem comp_snd {α β₀ β₁ β₂} (g : β₀ → β₁) (g' : β₁ → β₂) (x : F α β₀) :
snd g' (snd g x) = snd (g' ∘ g) x := by simp [snd, bimap_bimap]
attribute [functor_norm]
bimap_bimap comp_snd comp_fst snd_comp_snd snd_comp_fst fst_comp_snd fst_comp_fst
bimap_comp_bimap bimap_id_id fst_id snd_id
end Bifunctor
open Functor
instance Prod.bifunctor : Bifunctor Prod where bimap := @Prod.map
instance Prod.lawfulBifunctor : LawfulBifunctor Prod where
id_bimap _ := rfl
bimap_bimap _ _ _ _ _ := rfl
instance Bifunctor.const : Bifunctor Const where bimap f _ := f
instance LawfulBifunctor.const : LawfulBifunctor Const where
id_bimap _ := rfl
bimap_bimap _ _ _ _ _ := rfl
instance Bifunctor.flip : Bifunctor (flip F) where
bimap {_α α' _β β'} f f' x := (bimap f' f x : F β' α')
instance LawfulBifunctor.flip [LawfulBifunctor F] : LawfulBifunctor (flip F) where
id_bimap := by simp [bimap, functor_norm]
bimap_bimap := by simp [bimap, functor_norm]
instance Sum.bifunctor : Bifunctor Sum where bimap := @Sum.map
instance Sum.lawfulBifunctor : LawfulBifunctor Sum where
id_bimap := by aesop
bimap_bimap := by aesop
open Bifunctor
instance (priority := 10) Bifunctor.functor {α} : Functor (F α) where map f x := snd f x
instance (priority := 10) Bifunctor.lawfulFunctor [LawfulBifunctor F] {α} :
LawfulFunctor (F α) where
id_map := by simp [Functor.map, functor_norm]
comp_map := by simp [Functor.map, functor_norm]
map_const := by simp [mapConst, Functor.map]
section Bicompl
variable (G : Type* → Type u₀) (H : Type* → Type u₁) [Functor G] [Functor H]
instance Function.bicompl.bifunctor : Bifunctor (bicompl F G H) where
bimap {_α α' _β β'} f f' x := (bimap (map f) (map f') x : F (G α') (H β'))
instance Function.bicompl.lawfulBifunctor [LawfulFunctor G] [LawfulFunctor H] [LawfulBifunctor F] :
LawfulBifunctor (bicompl F G H) := by
constructor <;> intros <;> simp [bimap, map_id, map_comp_map, functor_norm]
end Bicompl
section Bicompr
variable (G : Type u₂ → Type*) [Functor G]
instance Function.bicompr.bifunctor : Bifunctor (bicompr G F) where
bimap {_α α' _β β'} f f' x := (map (bimap f f') x : G (F α' β'))
instance Function.bicompr.lawfulBifunctor [LawfulFunctor G] [LawfulBifunctor F] :
LawfulBifunctor (bicompr G F) := by
constructor <;> intros <;> simp [bimap, functor_norm]
end Bicompr |
.lake/packages/mathlib/Mathlib/Control/Basic.lean | import Mathlib.Control.Combinators
import Mathlib.Tactic.CasesM
import Mathlib.Tactic.Attr.Core
/-!
Extends the theory on functors, applicatives and monads.
-/
universe u v w
variable {α β γ : Type u}
section Functor
attribute [functor_norm] Functor.map_map
end Functor
section Applicative
variable {F : Type u → Type v} [Applicative F]
/-- A generalization of `List.zipWith` which combines list elements with an `Applicative`. -/
def zipWithM {α₁ α₂ φ : Type u} (f : α₁ → α₂ → F φ) : ∀ (_ : List α₁) (_ : List α₂), F (List φ)
| x :: xs, y :: ys => (· :: ·) <$> f x y <*> zipWithM f xs ys
| _, _ => pure []
/-- Like `zipWithM` but evaluates the result as it traverses the lists using `*>`. -/
def zipWithM' (f : α → β → F γ) : List α → List β → F PUnit
| x :: xs, y :: ys => f x y *> zipWithM' f xs ys
| [], _ => pure PUnit.unit
| _, [] => pure PUnit.unit
variable [LawfulApplicative F]
@[simp]
theorem pure_id'_seq (x : F α) : (pure fun x => x) <*> x = x :=
pure_id_seq x
@[functor_norm]
theorem seq_map_assoc (x : F (α → β)) (f : γ → α) (y : F γ) :
x <*> f <$> y = (· ∘ f) <$> x <*> y := by
simp only [← pure_seq]
simp only [seq_assoc, seq_pure, ← comp_map]
simp [pure_seq]
rfl
@[functor_norm]
theorem map_seq (f : β → γ) (x : F (α → β)) (y : F α) :
f <$> (x <*> y) = (f ∘ ·) <$> x <*> y := by
simp only [← pure_seq]; simp [seq_assoc]
end Applicative
section Monad
variable {m : Type u → Type v} [Monad m] [LawfulMonad m]
theorem seq_bind_eq (x : m α) {g : β → m γ} {f : α → β} :
f <$> x >>= g = x >>= g ∘ f :=
show bind (f <$> x) g = bind x (g ∘ f) by
simp [Function.comp_def]
-- order of implicits and `Seq.seq` has a lazily evaluated second argument using `Unit`
@[functor_norm]
theorem fish_pure {α β} (f : α → m β) : f >=> pure = f := by
simp +unfoldPartialApp only [(· >=> ·), functor_norm]
@[functor_norm]
theorem fish_pipe {α β} (f : α → m β) : pure >=> f = f := by
simp +unfoldPartialApp only [(· >=> ·), functor_norm]
-- note: in Lean 3 `>=>` is left-associative, but in Lean 4 it is right-associative.
@[functor_norm]
theorem fish_assoc {α β γ φ} (f : α → m β) (g : β → m γ) (h : γ → m φ) :
(f >=> g) >=> h = f >=> g >=> h := by
simp +unfoldPartialApp only [(· >=> ·), functor_norm]
variable {β' γ' : Type v}
variable {m' : Type v → Type w} [Monad m']
/-- Takes a value `β` and `List α` and accumulates pairs according to a monadic function `f`.
Accumulation occurs from the right (i.e., starting from the tail of the list). -/
def List.mapAccumRM (f : α → β' → m' (β' × γ')) : β' → List α → m' (β' × List γ')
| a, [] => pure (a, [])
| a, x :: xs => do
let (a', ys) ← List.mapAccumRM f a xs
let (a'', y) ← f x a'
pure (a'', y :: ys)
/-- Takes a value `β` and `List α` and accumulates pairs according to a monadic function `f`.
Accumulation occurs from the left (i.e., starting from the head of the list). -/
def List.mapAccumLM (f : β' → α → m' (β' × γ')) : β' → List α → m' (β' × List γ')
| a, [] => pure (a, [])
| a, x :: xs => do
let (a', y) ← f a x
let (a'', ys) ← List.mapAccumLM f a' xs
pure (a'', y :: ys)
end Monad
section
variable {m : Type u → Type u} [Monad m] [LawfulMonad m]
theorem joinM_map_map {α β : Type u} (f : α → β) (a : m (m α)) :
joinM (Functor.map f <$> a) = f <$> joinM a := by
simp only [joinM, id, ← bind_pure_comp, bind_assoc, pure_bind]
theorem joinM_map_joinM {α : Type u} (a : m (m (m α))) : joinM (joinM <$> a) = joinM (joinM a) := by
simp only [joinM, id, ← bind_pure_comp, bind_assoc, pure_bind]
@[simp]
theorem joinM_map_pure {α : Type u} (a : m α) : joinM (pure <$> a) = a := by
simp only [joinM, id, ← bind_pure_comp, bind_assoc, pure_bind, bind_pure]
@[simp]
theorem joinM_pure {α : Type u} (a : m α) : joinM (pure a) = a :=
LawfulMonad.pure_bind a id
end
section Alternative
variable {F : Type → Type v} [Alternative F]
-- [todo] add notation for `Functor.mapConst` and port `Functor.mapConstRev`
/-- Returns `pure true` if the computation succeeds and `pure false` otherwise. -/
def succeeds {α} (x : F α) : F Bool :=
Functor.mapConst true x <|> pure false
/-- Attempts to perform the computation, but fails silently if it doesn't succeed. -/
def tryM {α} (x : F α) : F Unit :=
Functor.mapConst () x <|> pure ()
/-- Attempts to perform the computation, and returns `none` if it doesn't succeed. -/
def try? {α} (x : F α) : F (Option α) :=
some <$> x <|> pure none
@[simp]
theorem guard_true {h : Decidable True} : @guard F _ True h = pure () := by simp [guard]
@[simp]
theorem guard_false {h : Decidable False} : @guard F _ False h = failure := by
simp [guard]
end Alternative
namespace Sum
variable {e : Type v}
/-- The monadic `bind` operation for `Sum`. -/
protected def bind {α β} : e ⊕ α → (α → e ⊕ β) → e ⊕ β
| inl x, _ => inl x
| inr x, f => f x
-- incorrectly marked as a bad translation by mathport, so we do not mark with `ₓ`.
instance : Monad (Sum.{v, u} e) where
pure := @Sum.inr e
bind := @Sum.bind e
instance : LawfulFunctor (Sum.{v, u} e) := by
constructor <;> intros <;> (try casesm Sum _ _) <;> rfl
instance : LawfulMonad (Sum.{v, u} e) where
seqRight_eq := by
intros
casesm Sum _ _ <;> casesm Sum _ _ <;> rfl
seqLeft_eq := by
intros
casesm Sum _ _ <;> rfl
pure_seq := by
intros
rfl
bind_assoc := by
intros
casesm Sum _ _ <;> rfl
pure_bind := by
intros
rfl
bind_pure_comp := by
intros
casesm Sum _ _ <;> rfl
bind_map := by
intros
casesm Sum _ _ <;> rfl
end Sum
/-- A `CommApplicative` functor `m` is a (lawful) applicative functor which behaves identically on
`α × β` and `β × α`, so computations can occur in either order. -/
class CommApplicative (m : Type u → Type v) [Applicative m] : Prop extends LawfulApplicative m where
/-- Computations performed first on `a : α` and then on `b : β` are equal to those performed in
the reverse order. -/
commutative_prod : ∀ {α β} (a : m α) (b : m β),
Prod.mk <$> a <*> b = (fun (b : β) a => (a, b)) <$> b <*> a
open Functor
theorem CommApplicative.commutative_map {m : Type u → Type v} [h : Applicative m]
[CommApplicative m] {α β γ} (a : m α) (b : m β) {f : α → β → γ} :
f <$> a <*> b = flip f <$> b <*> a :=
calc
f <$> a <*> b = (fun p : α × β => f p.1 p.2) <$> (Prod.mk <$> a <*> b) := by
simp only [map_seq, map_map, Function.comp_def]
_ = (fun b a => f a b) <$> b <*> a := by
rw [@CommApplicative.commutative_prod m h]
simp [map_seq, map_map]
rfl |
.lake/packages/mathlib/Mathlib/Control/ULift.lean | import Mathlib.Init
/-!
# Monadic instances for `ULift` and `PLift`
In this file we define `Monad` and `IsLawfulMonad` instances on `PLift` and `ULift`. -/
universe u v u' v'
namespace PLift
variable {α : Sort u} {β : Sort v}
/-- Functorial action. -/
protected def map (f : α → β) (a : PLift α) : PLift β :=
PLift.up (f a.down)
@[simp]
theorem map_up (f : α → β) (a : α) : (PLift.up a).map f = PLift.up (f a) :=
rfl
/-- Embedding of pure values. -/
@[simp]
protected def pure : α → PLift α :=
up
/-- Applicative sequencing. -/
protected def seq (f : PLift (α → β)) (x : Unit → PLift α) : PLift β :=
PLift.up (f.down (x ()).down)
@[simp]
theorem seq_up (f : α → β) (x : α) : (PLift.up f).seq (fun _ => PLift.up x) = PLift.up (f x) :=
rfl
/-- Monadic bind. -/
protected def bind (a : PLift α) (f : α → PLift β) : PLift β :=
f a.down
@[simp]
theorem bind_up (a : α) (f : α → PLift β) : (PLift.up a).bind f = f a :=
rfl
instance : Monad PLift where
map := @PLift.map
pure := @PLift.pure
seq := @PLift.seq
bind := @PLift.bind
instance : LawfulFunctor PLift where
id_map := @fun _ ⟨_⟩ => rfl
comp_map := @fun _ _ _ _ _ ⟨_⟩ => rfl
map_const := @fun _ _ => rfl
instance : LawfulApplicative PLift where
seqLeft_eq := @fun _ _ _ _ => rfl
seqRight_eq := @fun _ _ _ _ => rfl
pure_seq := @fun _ _ _ ⟨_⟩ => rfl
map_pure := @fun _ _ _ _ => rfl
seq_pure := @fun _ _ ⟨_⟩ _ => rfl
seq_assoc := @fun _ _ _ ⟨_⟩ ⟨_⟩ ⟨_⟩ => rfl
instance : LawfulMonad PLift where
bind_pure_comp := @fun _ _ _ ⟨_⟩ => rfl
bind_map := @fun _ _ ⟨_⟩ ⟨_⟩ => rfl
pure_bind := @fun _ _ _ _ => rfl
bind_assoc := @fun _ _ _ ⟨_⟩ _ _ => rfl
@[simp]
theorem rec.constant {α : Sort u} {β : Type v} (b : β) :
(@PLift.rec α (fun _ => β) fun _ => b) = fun _ => b := rfl
end PLift
namespace ULift
variable {α : Type u} {β : Type v}
/-- Functorial action. -/
protected def map (f : α → β) (a : ULift.{u'} α) : ULift.{v'} β := ULift.up.{v'} (f a.down)
@[simp]
theorem map_up (f : α → β) (a : α) : (ULift.up.{u'} a).map f = ULift.up.{v'} (f a) := rfl
/-- Embedding of pure values. -/
@[simp]
protected def pure : α → ULift α :=
up
/-- Applicative sequencing. -/
protected def seq {α β} (f : ULift (α → β)) (x : Unit → ULift α) : ULift β :=
ULift.up.{u} (f.down (x ()).down)
@[simp]
theorem seq_up (f : α → β) (x : α) : (ULift.up f).seq (fun _ => ULift.up x) = ULift.up (f x) :=
rfl
/-- Monadic bind. -/
protected def bind (a : ULift α) (f : α → ULift β) : ULift β :=
f a.down
@[simp]
theorem bind_up (a : α) (f : α → ULift β) : (ULift.up a).bind f = f a :=
rfl
instance : Monad ULift where
map := @ULift.map
pure := @ULift.pure
seq := @ULift.seq
bind := @ULift.bind
instance : LawfulFunctor ULift where
id_map := @fun _ ⟨_⟩ => rfl
comp_map := @fun _ _ _ _ _ ⟨_⟩ => rfl
map_const := @fun _ _ => rfl
instance : LawfulApplicative ULift where
seqLeft_eq := @fun _ _ _ _ => rfl
seqRight_eq := @fun _ _ _ _ => rfl
pure_seq := @fun _ _ _ ⟨_⟩ => rfl
map_pure := @fun _ _ _ _ => rfl
seq_pure := @fun _ _ ⟨_⟩ _ => rfl
seq_assoc := @fun _ _ _ ⟨_⟩ ⟨_⟩ ⟨_⟩ => rfl
instance : LawfulMonad ULift where
bind_pure_comp := @fun _ _ _ ⟨_⟩ => rfl
bind_map := @fun _ _ ⟨_⟩ ⟨_⟩ => rfl
pure_bind := @fun _ _ _ _ => rfl
bind_assoc := @fun _ _ _ ⟨_⟩ _ _ => rfl
@[simp]
theorem rec.constant {α : Type u} {β : Sort v} (b : β) :
(@ULift.rec α (fun _ => β) fun _ => b) = fun _ => b := rfl
end ULift |
.lake/packages/mathlib/Mathlib/Control/Lawful.lean | import Mathlib.Tactic.Basic
/-!
# Functor Laws, applicative laws, and monad Laws
-/
universe u v
namespace StateT
section
variable {σ : Type u} {m : Type u → Type v} {α β : Type u}
/--
`StateT` doesn't require a constructor, but it appears confusing to declare the
following theorem as a simp theorem.
```lean
@[simp]
theorem run_fun (f : σ → m (α × σ)) (st : σ) : StateT.run (fun s => f s) st = f st :=
rfl
```
If we declare this theorem as a simp theorem, `StateT.run f st` is simplified to `f st` by eta
reduction. This breaks the structure of `StateT`.
So, we declare a constructor-like definition `StateT.mk` and a simp theorem for it.
-/
protected def mk (f : σ → m (α × σ)) : StateT σ m α := f
@[simp]
theorem run_mk (f : σ → m (α × σ)) (st : σ) : StateT.run (StateT.mk f) st = f st :=
rfl
/-- A copy of `LawfulFunctor.map_const` for `StateT` that holds even if `m` is not lawful. -/
protected lemma map_const [Monad m] :
(Functor.mapConst : α → StateT σ m β → StateT σ m α) = Functor.map ∘ Function.const β :=
rfl
@[simp] lemma run_mapConst [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : β) (st : σ) :
(Functor.mapConst y x).run st = Prod.map (Function.const α y) id <$> x.run st := run_map _ _ _
end
end StateT
namespace ExceptT
variable {α ε : Type u} {m : Type u → Type v} (x : ExceptT ε m α)
attribute [simp] run_bind
@[simp]
theorem run_monadLift {n} [Monad m] [MonadLiftT n m] (x : n α) :
(monadLift x : ExceptT ε m α).run = Except.ok <$> (monadLift x : m α) :=
rfl
@[simp]
theorem run_monadMap {n} [MonadFunctorT n m] (f : ∀ {α}, n α → n α) :
(monadMap (@f) x : ExceptT ε m α).run = monadMap (@f) x.run :=
rfl
end ExceptT
namespace ReaderT
section
variable {m : Type u → Type v}
variable {α σ : Type u}
/--
`ReaderT` doesn't require a constructor, but it appears confusing to declare the
following theorem as a simp theorem.
```lean
@[simp]
theorem run_fun (f : σ → m α) (r : σ) : ReaderT.run (fun r' => f r') r = f r :=
rfl
```
If we declare this theorem as a simp theorem, `ReaderT.run f st` is simplified to `f st` by eta
reduction. This breaks the structure of `ReaderT`.
So, we declare a constructor-like definition `ReaderT.mk` and a simp theorem for it.
-/
protected def mk (f : σ → m α) : ReaderT σ m α := f
@[simp]
theorem run_mk (f : σ → m α) (r : σ) : ReaderT.run (ReaderT.mk f) r = f r :=
rfl
end
end ReaderT |
.lake/packages/mathlib/Mathlib/Control/ULiftable.lean | import Mathlib.Control.Monad.Basic
import Mathlib.Control.Monad.Cont
import Mathlib.Control.Monad.Writer
import Mathlib.Logic.Equiv.Basic
import Mathlib.Logic.Equiv.Functor
import Mathlib.Control.Lawful
/-!
# Universe lifting for type families
Some functors such as `Option` and `List` are universe polymorphic. Unlike
type polymorphism where `Option α` is a function application and reasoning and
generalizations that apply to functions can be used, `Option.{u}` and `Option.{v}`
are not one function applied to two universe names but one polymorphic definition
instantiated twice. This means that whatever works on `Option.{u}` is hard
to transport over to `Option.{v}`. `ULiftable` is an attempt at improving the situation.
`ULiftable Option.{u} Option.{v}` gives us a generic and composable way to use
`Option.{u}` in a context that requires `Option.{v}`. It is often used in tandem with
`ULift` but the two are purposefully decoupled.
## Main definitions
* `ULiftable` class
## Tags
universe polymorphism functor
-/
universe v u₀ u₁ v₀ v₁ v₂ w w₀ w₁
variable {s : Type u₀} {s' : Type u₁} {r r' w w' : Type*}
/-- Given a universe polymorphic type family `M.{u} : Type u₁ → Type
u₂`, this class convert between instantiations, from
`M.{u} : Type u₁ → Type u₂` to `M.{v} : Type v₁ → Type v₂` and back.
`f` is an outParam, because `g` can almost always be inferred from the current monad.
At any rate, the lift should be unique, as the intent is to only lift the same constants with
different universe parameters. -/
class ULiftable (f : outParam (Type u₀ → Type u₁)) (g : Type v₀ → Type v₁) where
congr {α β} : α ≃ β → f α ≃ g β
namespace ULiftable
/-- Not an instance as it is incompatible with `outParam`. In practice it seems not to be needed
anyway. -/
abbrev symm (f : Type u₀ → Type u₁) (g : Type v₀ → Type v₁) [ULiftable f g] : ULiftable g f where
congr e := (ULiftable.congr e.symm).symm
instance refl (f : Type u₀ → Type u₁) [Functor f] [LawfulFunctor f] : ULiftable f f where
congr e := Functor.mapEquiv _ e
/-- The most common practical use `ULiftable` (together with `down`), the function `up.{v}` takes
`x : M.{u} α` and lifts it to `M.{max u v} (ULift.{v} α)` -/
abbrev up {f : Type u₀ → Type u₁} {g : Type max u₀ v → Type v₁} [ULiftable f g] {α} :
f α → g (ULift.{v} α) :=
(ULiftable.congr Equiv.ulift.symm).toFun
/-- The most common practical use of `ULiftable` (together with `up`), the function `down.{v}` takes
`x : M.{max u v} (ULift.{v} α)` and lowers it to `M.{u} α` -/
abbrev down {f : Type u₀ → Type u₁} {g : Type max u₀ v → Type v₁} [ULiftable f g] {α} :
g (ULift.{v} α) → f α :=
(ULiftable.congr Equiv.ulift.symm).invFun
/-- convenient shortcut to avoid manipulating `ULift` -/
def adaptUp (F : Type v₀ → Type v₁) (G : Type max v₀ u₀ → Type u₁) [ULiftable F G] [Monad G] {α β}
(x : F α) (f : α → G β) : G β :=
up x >>= f ∘ ULift.down.{u₀}
/-- convenient shortcut to avoid manipulating `ULift` -/
def adaptDown {F : Type max u₀ v₀ → Type u₁} {G : Type v₀ → Type v₁} [L : ULiftable G F] [Monad F]
{α β} (x : F α) (f : α → G β) : G β :=
@down.{max u₀ v₀} G F L β <| x >>= @up.{max u₀ v₀} G F L β ∘ f
/-- map function that moves up universes -/
def upMap {F : Type u₀ → Type u₁} {G : Type max u₀ v₀ → Type v₁} [ULiftable F G] [Functor G]
{α β} (f : α → β) (x : F α) : G β :=
Functor.map (f ∘ ULift.down.{v₀}) (up x)
/-- map function that moves down universes -/
def downMap {F : Type max u₀ v₀ → Type u₁} {G : Type u₀ → Type v₁} [ULiftable G F]
[Functor F] {α β} (f : α → β) (x : F α) : G β :=
down (Functor.map (ULift.up.{v₀} ∘ f) x : F (ULift β))
/-- A version of `up` for a `PUnit` return type. -/
abbrev up' {f : Type u₀ → Type u₁} {g : Type v₀ → Type v₁} [ULiftable f g] :
f PUnit → g PUnit :=
ULiftable.congr Equiv.punitEquivPUnit
/-- A version of `down` for a `PUnit` return type. -/
abbrev down' {f : Type u₀ → Type u₁} {g : Type v₀ → Type v₁} [ULiftable f g] :
g PUnit → f PUnit :=
(ULiftable.congr Equiv.punitEquivPUnit).symm
theorem up_down {f : Type u₀ → Type u₁} {g : Type max u₀ v₀ → Type v₁} [ULiftable f g] {α}
(x : g (ULift.{v₀} α)) : up (down x : f α) = x :=
(ULiftable.congr Equiv.ulift.symm).right_inv _
theorem down_up {f : Type u₀ → Type u₁} {g : Type max u₀ v₀ → Type v₁} [ULiftable f g] {α}
(x : f α) : down (up x : g (ULift.{v₀} α)) = x :=
(ULiftable.congr Equiv.ulift.symm).left_inv _
end ULiftable
open ULift
instance instULiftableId : ULiftable Id Id where
congr F := F
/-- for specific state types, this function helps to create a uliftable instance -/
def StateT.uliftable' {m : Type u₀ → Type v₀} {m' : Type u₁ → Type v₁} [ULiftable m m']
(F : s ≃ s') : ULiftable (StateT s m) (StateT s' m') where
congr G :=
StateT.equiv <| Equiv.piCongr F fun _ => ULiftable.congr <| Equiv.prodCongr G F
instance {m m'} [ULiftable m m'] : ULiftable (StateT s m) (StateT (ULift s) m') :=
StateT.uliftable' Equiv.ulift.symm
instance StateT.instULiftableULiftULift {m m'} [ULiftable m m'] :
ULiftable (StateT (ULift.{max v₀ u₀} s) m) (StateT (ULift.{max v₁ u₀} s) m') :=
StateT.uliftable' <| Equiv.ulift.trans Equiv.ulift.symm
/-- for specific reader monads, this function helps to create a uliftable instance -/
def ReaderT.uliftable' {m m'} [ULiftable m m'] (F : s ≃ s') :
ULiftable (ReaderT s m) (ReaderT s' m') where
congr G := ReaderT.equiv <| Equiv.piCongr F fun _ => ULiftable.congr G
instance {m m'} [ULiftable m m'] : ULiftable (ReaderT s m) (ReaderT (ULift s) m') :=
ReaderT.uliftable' Equiv.ulift.symm
instance ReaderT.instULiftableULiftULift {m m'} [ULiftable m m'] :
ULiftable (ReaderT (ULift.{max v₀ u₀} s) m) (ReaderT (ULift.{max v₁ u₀} s) m') :=
ReaderT.uliftable' <| Equiv.ulift.trans Equiv.ulift.symm
/-- for specific continuation passing monads, this function helps to create a uliftable instance -/
def ContT.uliftable' {m m'} [ULiftable m m'] (F : r ≃ r') :
ULiftable (ContT r m) (ContT r' m') where
congr := ContT.equiv (ULiftable.congr F)
instance {s m m'} [ULiftable m m'] : ULiftable (ContT s m) (ContT (ULift s) m') :=
ContT.uliftable' Equiv.ulift.symm
instance ContT.instULiftableULiftULift {m m'} [ULiftable m m'] :
ULiftable (ContT (ULift.{max v₀ u₀} s) m) (ContT (ULift.{max v₁ u₀} s) m') :=
ContT.uliftable' <| Equiv.ulift.trans Equiv.ulift.symm
/-- for specific writer monads, this function helps to create a uliftable instance -/
def WriterT.uliftable' {m m'} [ULiftable m m'] (F : w ≃ w') :
ULiftable (WriterT w m) (WriterT w' m') where
congr G := WriterT.equiv <| ULiftable.congr <| Equiv.prodCongr G F
instance {m m'} [ULiftable m m'] : ULiftable (WriterT s m) (WriterT (ULift s) m') :=
WriterT.uliftable' Equiv.ulift.symm
instance WriterT.instULiftableULiftULift {m m'} [ULiftable m m'] :
ULiftable (WriterT (ULift.{max v₀ u₀} s) m) (WriterT (ULift.{max v₁ u₀} s) m') :=
WriterT.uliftable' <| Equiv.ulift.trans Equiv.ulift.symm
instance Except.instULiftable {ε : Type u₀} :
ULiftable (Except.{u₀, v₁} ε) (Except.{u₀, v₂} ε) where
congr e :=
{ toFun := Except.map e
invFun := Except.map e.symm
left_inv := fun f => by cases f <;> simp [Except.map]
right_inv := fun f => by cases f <;> simp [Except.map] }
instance Option.instULiftable : ULiftable Option.{u₀} Option.{u₁} where
congr e :=
{ toFun := Option.map e
invFun := Option.map e.symm
left_inv := fun f => by cases f <;> simp
right_inv := fun f => by cases f <;> simp } |
.lake/packages/mathlib/Mathlib/Control/Fold.lean | import Mathlib.Algebra.Group.Opposite
import Mathlib.Algebra.FreeMonoid.Basic
import Mathlib.CategoryTheory.Category.KleisliCat
import Mathlib.CategoryTheory.Endomorphism
import Mathlib.CategoryTheory.Types.Basic
import Mathlib.Control.Traversable.Instances
import Mathlib.Control.Traversable.Lemmas
import Mathlib.Tactic.AdaptationNote
/-!
# List folds generalized to `Traversable`
Informally, we can think of `foldl` as a special case of `traverse` where we do not care about the
reconstructed data structure and, in a state monad, we care about the final state.
The obvious way to define `foldl` would be to use the state monad but it
is nicer to reason about a more abstract interface with `foldMap` as a
primitive and `foldMap_hom` as a defining property.
```
def foldMap {α ω} [One ω] [Mul ω] (f : α → ω) : t α → ω := ...
lemma foldMap_hom (α β) [Monoid α] [Monoid β] (f : α →* β) (g : γ → α) (x : t γ) :
f (foldMap g x) = foldMap (f ∘ g) x :=
...
```
`foldMap` uses a monoid ω to accumulate a value for every element of
a data structure and `foldMap_hom` uses a monoid homomorphism to
substitute the monoid used by `foldMap`. The two are sufficient to
define `foldl`, `foldr` and `toList`. `toList` permits the
formulation of specifications in terms of operations on lists.
Each fold function can be defined using a specialized
monoid. `toList` uses a free monoid represented as a list with
concatenation while `foldl` uses endofunctions together with function
composition.
The definition through monoids uses `traverse` together with the
applicative functor `const m` (where `m` is the monoid). As an
implementation, `const` guarantees that no resource is spent on
reconstructing the structure during traversal.
A special class could be defined for `foldable`, similarly to Haskell,
but the author cannot think of instances of `foldable` that are not also
`Traversable`.
-/
universe u v
open ULift CategoryTheory MulOpposite
namespace Monoid
variable {m : Type u → Type u} [Monad m]
variable {α β : Type u}
/-- For a list, foldl f x [y₀,y₁] reduces as follows:
```
calc foldl f x [y₀,y₁]
= foldl f (f x y₀) [y₁] : rfl
... = foldl f (f (f x y₀) y₁) [] : rfl
... = f (f x y₀) y₁ : rfl
```
with
```
f : α → β → α
x : α
[y₀,y₁] : List β
```
We can view the above as a composition of functions:
```
... = f (f x y₀) y₁ : rfl
... = flip f y₁ (flip f y₀ x) : rfl
... = (flip f y₁ ∘ flip f y₀) x : rfl
```
We can use traverse and const to construct this composition:
```
calc const.run (traverse (fun y ↦ const.mk' (flip f y)) [y₀,y₁]) x
= const.run ((::) <$> const.mk' (flip f y₀) <*>
traverse (fun y ↦ const.mk' (flip f y)) [y₁]) x
... = const.run ((::) <$> const.mk' (flip f y₀) <*>
( (::) <$> const.mk' (flip f y₁) <*> traverse (fun y ↦ const.mk' (flip f y)) [] )) x
... = const.run ((::) <$> const.mk' (flip f y₀) <*>
( (::) <$> const.mk' (flip f y₁) <*> pure [] )) x
... = const.run ( ((::) <$> const.mk' (flip f y₁) <*> pure []) ∘
((::) <$> const.mk' (flip f y₀)) ) x
... = const.run ( const.mk' (flip f y₁) ∘ const.mk' (flip f y₀) ) x
... = const.run ( flip f y₁ ∘ flip f y₀ ) x
... = f (f x y₀) y₁
```
And this is how `const` turns a monoid into an applicative functor and
how the monoid of endofunctions define `Foldl`.
-/
abbrev Foldl (α : Type u) : Type u :=
(End α)ᵐᵒᵖ
def Foldl.mk (f : α → α) : Foldl α :=
op f
def Foldl.get (x : Foldl α) : α → α :=
unop x
@[simps]
def Foldl.ofFreeMonoid (f : β → α → β) : FreeMonoid α →* Monoid.Foldl β where
toFun xs := op <| flip (List.foldl f) (FreeMonoid.toList xs)
map_one' := rfl
map_mul' := by
intros
simp only [FreeMonoid.toList_mul, List.foldl_append, Function.flip_def]
rfl
abbrev Foldr (α : Type u) : Type u :=
End α
def Foldr.mk (f : α → α) : Foldr α :=
f
def Foldr.get (x : Foldr α) : α → α :=
x
@[simps]
def Foldr.ofFreeMonoid (f : α → β → β) : FreeMonoid α →* Monoid.Foldr β where
toFun xs := flip (List.foldr f) (FreeMonoid.toList xs)
map_one' := rfl
map_mul' _ _ := funext fun _ => List.foldr_append
abbrev foldlM (m : Type u → Type u) [Monad m] (α : Type u) : Type u :=
MulOpposite <| End <| KleisliCat.mk m α
def foldlM.mk (f : α → m α) : foldlM m α :=
op f
def foldlM.get (x : foldlM m α) : α → m α :=
unop x
@[simps]
def foldlM.ofFreeMonoid [LawfulMonad m] (f : β → α → m β) : FreeMonoid α →* Monoid.foldlM m β where
toFun xs := op <| flip (List.foldlM f) (FreeMonoid.toList xs)
map_one' := rfl
map_mul' := by intros; apply unop_injective; funext; apply List.foldlM_append
abbrev foldrM (m : Type u → Type u) [Monad m] (α : Type u) : Type u :=
End <| KleisliCat.mk m α
def foldrM.mk (f : α → m α) : foldrM m α :=
f
def foldrM.get (x : foldrM m α) : α → m α :=
x
@[simps]
def foldrM.ofFreeMonoid [LawfulMonad m] (f : α → β → m β) : FreeMonoid α →* Monoid.foldrM m β where
toFun xs := flip (List.foldrM f) (FreeMonoid.toList xs)
map_one' := rfl
map_mul' := by intros; funext; apply List.foldrM_append
end Monoid
namespace Traversable
open Monoid Functor
section Defs
variable {α β : Type u} {t : Type u → Type u} [Traversable t]
def foldMap {α ω} [One ω] [Mul ω] (f : α → ω) : t α → ω :=
traverse (Const.mk' ∘ f)
def foldl (f : α → β → α) (x : α) (xs : t β) : α :=
(foldMap (Foldl.mk ∘ flip f) xs).get x
def foldr (f : α → β → β) (x : β) (xs : t α) : β :=
(foldMap (Foldr.mk ∘ f) xs).get x
/-- Conceptually, `toList` collects all the elements of a collection
in a list. This idea is formalized by
`lemma toList_spec (x : t α) : toList x = foldMap FreeMonoid.mk x`.
The definition of `toList` is based on `foldl` and `List.cons` for
speed. It is faster than using `foldMap FreeMonoid.mk` because, by
using `foldl` and `List.cons`, each insertion is done in constant
time. As a consequence, `toList` performs in linear.
On the other hand, `foldMap FreeMonoid.mk` creates a singleton list
around each element and concatenates all the resulting lists. In
`xs ++ ys`, concatenation takes a time proportional to `length xs`. Since
the order in which concatenation is evaluated is unspecified, nothing
prevents each element of the traversable to be appended at the end
`xs ++ [x]` which would yield a `O(n²)` run time. -/
def toList : t α → List α :=
List.reverse ∘ foldl (flip List.cons) []
def length (xs : t α) : ℕ :=
down <| foldl (fun l _ => up <| l.down + 1) (up 0) xs
variable {m : Type u → Type u} [Monad m]
def foldlm (f : α → β → m α) (x : α) (xs : t β) : m α :=
(foldMap (foldlM.mk ∘ flip f) xs).get x
def foldrm (f : α → β → m β) (x : β) (xs : t α) : m β :=
(foldMap (foldrM.mk ∘ f) xs).get x
end Defs
section ApplicativeTransformation
variable {α β γ : Type u}
open Function hiding const
def mapFold [Monoid α] [Monoid β] (f : α →* β) : ApplicativeTransformation (Const α) (Const β) where
app _ := f
preserves_seq' := by intros; simp only [Seq.seq, map_mul]
preserves_pure' := by intros; simp only [map_one, pure]
theorem Free.map_eq_map (f : α → β) (xs : List α) :
f <$> xs = (FreeMonoid.toList (FreeMonoid.map f (FreeMonoid.ofList xs))) :=
rfl
theorem foldl.unop_ofFreeMonoid (f : β → α → β) (xs : FreeMonoid α) (a : β) :
unop (Foldl.ofFreeMonoid f xs) a = List.foldl f a (FreeMonoid.toList xs) :=
rfl
variable {t : Type u → Type u} [Traversable t] [LawfulTraversable t]
open LawfulTraversable
theorem foldMap_hom [Monoid α] [Monoid β] (f : α →* β) (g : γ → α) (x : t γ) :
f (foldMap g x) = foldMap (f ∘ g) x :=
calc
f (foldMap g x) = f (traverse (Const.mk' ∘ g) x) := rfl
_ = (mapFold f).app _ (traverse (Const.mk' ∘ g) x) := rfl
_ = traverse ((mapFold f).app _ ∘ Const.mk' ∘ g) x := naturality (mapFold f) _ _
_ = foldMap (f ∘ g) x := rfl
theorem foldMap_hom_free [Monoid β] (f : FreeMonoid α →* β) (x : t α) :
f (foldMap FreeMonoid.of x) = foldMap (f ∘ FreeMonoid.of) x :=
foldMap_hom f _ x
end ApplicativeTransformation
section Equalities
open LawfulTraversable
open List (cons)
variable {α β γ : Type u}
variable {t : Type u → Type u} [Traversable t] [LawfulTraversable t]
@[simp]
theorem foldl.ofFreeMonoid_comp_of (f : α → β → α) :
Foldl.ofFreeMonoid f ∘ FreeMonoid.of = Foldl.mk ∘ flip f :=
rfl
@[simp]
theorem foldr.ofFreeMonoid_comp_of (f : β → α → α) :
Foldr.ofFreeMonoid f ∘ FreeMonoid.of = Foldr.mk ∘ f :=
rfl
@[simp]
theorem foldlm.ofFreeMonoid_comp_of {m} [Monad m] [LawfulMonad m] (f : α → β → m α) :
foldlM.ofFreeMonoid f ∘ FreeMonoid.of = foldlM.mk ∘ flip f := by
ext1 x
simp only [foldlM.ofFreeMonoid, Function.flip_def, MonoidHom.coe_mk, OneHom.coe_mk,
Function.comp_apply, FreeMonoid.toList_of, List.foldlM_cons, List.foldlM_nil, bind_pure,
foldlM.mk, op_inj]
rfl
@[simp]
theorem foldrm.ofFreeMonoid_comp_of {m} [Monad m] [LawfulMonad m] (f : β → α → m α) :
foldrM.ofFreeMonoid f ∘ FreeMonoid.of = foldrM.mk ∘ f := by
ext
simp [(· ∘ ·), foldrM.ofFreeMonoid, foldrM.mk, Function.flip_def]
theorem toList_spec (xs : t α) : toList xs = FreeMonoid.toList (foldMap FreeMonoid.of xs) :=
Eq.symm <|
calc
FreeMonoid.toList (foldMap FreeMonoid.of xs) =
FreeMonoid.toList (foldMap FreeMonoid.of xs).reverse.reverse := by
simp only [FreeMonoid.reverse_reverse]
_ = (List.foldr cons [] (foldMap FreeMonoid.of xs).toList.reverse).reverse := by simp
_ = (unop (Foldl.ofFreeMonoid (flip cons) (foldMap FreeMonoid.of xs)) []).reverse := by
simp [Function.flip_def, List.foldr_reverse, Foldl.ofFreeMonoid, unop_op]
_ = toList xs := by
rw [foldMap_hom_free (Foldl.ofFreeMonoid (flip <| @cons α))]
simp only [toList, foldl, Foldl.get, foldl.ofFreeMonoid_comp_of,
Function.comp_apply]
theorem foldMap_map [Monoid γ] (f : α → β) (g : β → γ) (xs : t α) :
foldMap g (f <$> xs) = foldMap (g ∘ f) xs := by
simp only [foldMap, traverse_map, Function.comp_def]
theorem foldl_toList (f : α → β → α) (xs : t β) (x : α) :
foldl f x xs = List.foldl f x (toList xs) := by
rw [← FreeMonoid.toList_ofList (toList xs), ← foldl.unop_ofFreeMonoid]
simp only [foldl, toList_spec, foldMap_hom_free, foldl.ofFreeMonoid_comp_of, Foldl.get,
FreeMonoid.ofList_toList]
theorem foldr_toList (f : α → β → β) (xs : t α) (x : β) :
foldr f x xs = List.foldr f x (toList xs) := by
change _ = Foldr.ofFreeMonoid _ (FreeMonoid.ofList <| toList xs) _
rw [toList_spec, foldr, Foldr.get, FreeMonoid.ofList_toList, foldMap_hom_free,
foldr.ofFreeMonoid_comp_of]
theorem toList_map (f : α → β) (xs : t α) : toList (f <$> xs) = f <$> toList xs := by
simp only [toList_spec, Free.map_eq_map, foldMap_hom, foldMap_map, FreeMonoid.ofList_toList,
FreeMonoid.map_of, Function.comp_def]
@[simp]
theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : t β) :
foldl f a (g <$> l) = foldl (fun x y => f x (g y)) a l := by
simp only [foldl, foldMap_map, Function.comp_def, Function.flip_def]
@[simp]
theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : t β) :
foldr f a (g <$> l) = foldr (f ∘ g) a l := by
simp only [foldr, foldMap_map, Function.comp_def]
@[simp]
theorem toList_eq_self {xs : List α} : toList xs = xs := by
simp only [toList_spec, foldMap, traverse]
induction xs with
| nil => rfl
| cons _ _ ih => (conv_rhs => rw [← ih]); rfl
theorem length_toList {xs : t α} : length xs = List.length (toList xs) := by
unfold length
rw [foldl_toList]
generalize toList xs = ys
rw [← Nat.add_zero ys.length]
generalize 0 = n
induction ys generalizing n with
| nil => simp
| cons _ _ ih => simp +arith [ih]
variable {m : Type u → Type u} [Monad m] [LawfulMonad m]
theorem foldlm_toList {f : α → β → m α} {x : α} {xs : t β} :
foldlm f x xs = List.foldlM f x (toList xs) :=
calc foldlm f x xs
_ = unop (foldlM.ofFreeMonoid f (FreeMonoid.ofList <| toList xs)) x := by
simp only [foldlm, toList_spec, foldMap_hom_free (foldlM.ofFreeMonoid f),
foldlm.ofFreeMonoid_comp_of, foldlM.get, FreeMonoid.ofList_toList]
_ = List.foldlM f x (toList xs) := by simp [foldlM.ofFreeMonoid, unop_op, flip]
theorem foldrm_toList (f : α → β → m β) (x : β) (xs : t α) :
foldrm f x xs = List.foldrM f x (toList xs) := by
change _ = foldrM.ofFreeMonoid f (FreeMonoid.ofList <| toList xs) x
simp only [foldrm, toList_spec, foldMap_hom_free (foldrM.ofFreeMonoid f),
foldrm.ofFreeMonoid_comp_of, foldrM.get, FreeMonoid.ofList_toList]
@[simp]
theorem foldlm_map (g : β → γ) (f : α → γ → m α) (a : α) (l : t β) :
foldlm f a (g <$> l) = foldlm (fun x y => f x (g y)) a l := by
simp only [foldlm, foldMap_map, Function.comp_def, Function.flip_def]
@[simp]
theorem foldrm_map (g : β → γ) (f : γ → α → m α) (a : α) (l : t β) :
foldrm f a (g <$> l) = foldrm (f ∘ g) a l := by
simp only [foldrm, foldMap_map, Function.comp_def]
end Equalities
end Traversable |
.lake/packages/mathlib/Mathlib/Control/Combinators.lean | import Mathlib.Init
/-!
# Monad combinators, as in Haskell's Control.Monad.
-/
universe u v w
/-- Collapses two layers of monadic structure into one,
passing the effects of the inner monad through the outer. -/
def joinM {m : Type u → Type u} [Monad m] {α : Type u} (a : m (m α)) : m α :=
bind a id
/-- Executes `tm` or `fm` depending on whether the result of `mbool` is `true` or `false`
respectively. -/
def condM {m : Type → Type} [Monad m] {α : Type} (mbool : m Bool) (tm fm : m α) : m α := do
let b ← mbool
cond b tm fm
namespace Monad
end Monad |
.lake/packages/mathlib/Mathlib/Control/Functor.lean | import Mathlib.Tactic.Attr.Register
import Mathlib.Data.Set.Defs
import Mathlib.Tactic.TypeStar
import Batteries.Tactic.Lint
/-!
# Functors
This module provides additional lemmas, definitions, and instances for `Functor`s.
## Main definitions
* `Functor.Const α` is the functor that sends all types to `α`.
* `Functor.AddConst α` is `Functor.Const α` but for when `α` has an additive structure.
* `Functor.Comp F G` for functors `F` and `G` is the functor composition of `F` and `G`.
* `Liftp` and `Liftr` respectively lift predicates and relations on a type `α`
to `F α`. Terms of `F α` are considered to, in some sense, contain values of type `α`.
## Tags
functor, applicative
-/
universe u v w
section Functor
variable {F : Type u → Type v}
variable {α β γ : Type u}
variable [Functor F] [LawfulFunctor F]
theorem Functor.map_id : (id <$> ·) = (id : F α → F α) := funext id_map
theorem Functor.map_comp_map (f : α → β) (g : β → γ) :
((g <$> ·) ∘ (f <$> ·) : F α → F γ) = ((g ∘ f) <$> ·) :=
funext fun _ => (comp_map _ _ _).symm
theorem Functor.ext {F} :
∀ {F1 : Functor F} {F2 : Functor F} [@LawfulFunctor F F1] [@LawfulFunctor F F2],
(∀ (α β) (f : α → β) (x : F α), @Functor.map _ F1 _ _ f x = @Functor.map _ F2 _ _ f x) →
F1 = F2
| ⟨m, mc⟩, ⟨m', mc'⟩, H1, H2, H => by
cases show @m = @m' by funext α β f x; apply H
congr
funext α β
have E1 := @map_const _ ⟨@m, @mc⟩ H1
have E2 := @map_const _ ⟨@m, @mc'⟩ H2
exact E1.trans E2.symm
end Functor
/-- Introduce `id` as a quasi-functor. (Note that where a lawful `Monad` or
`Applicative` or `Functor` is needed, `Id` is the correct definition). -/
@[deprecated "Use `pure : α → Id α` instead." (since := "2025-05-21")]
def id.mk {α : Sort u} : α → id α :=
id
namespace Functor
/-- `Const α` is the constant functor, mapping every type to `α`. When
`α` has a monoid structure, `Const α` has an `Applicative` instance.
(If `α` has an additive monoid structure, see `Functor.AddConst`.) -/
@[nolint unusedArguments]
def Const (α : Type*) (_β : Type*) :=
α
/-- `Const.mk` is the canonical map `α → Const α β` (the identity), and
it can be used as a pattern to extract this value. -/
@[match_pattern]
def Const.mk {α β} (x : α) : Const α β :=
x
/-- `Const.mk'` is `Const.mk` but specialized to map `α` to
`Const α PUnit`, where `PUnit` is the terminal object in `Type*`. -/
def Const.mk' {α} (x : α) : Const α PUnit :=
x
/-- Extract the element of `α` from the `Const` functor. -/
def Const.run {α β} (x : Const α β) : α :=
x
namespace Const
protected theorem ext {α β} {x y : Const α β} (h : x.run = y.run) : x = y :=
h
/-- The map operation of the `Const γ` functor. -/
@[nolint unusedArguments]
protected def map {γ α β} (_f : α → β) (x : Const γ β) : Const γ α :=
x
instance functor {γ} : Functor (Const γ) where map := @Const.map γ
instance lawfulFunctor {γ} : LawfulFunctor (Const γ) := by constructor <;> intros <;> rfl
instance {α β} [Inhabited α] : Inhabited (Const α β) :=
⟨(default : α)⟩
end Const
/-- `AddConst α` is a synonym for constant functor `Const α`, mapping
every type to `α`. When `α` has an additive monoid structure,
`AddConst α` has an `Applicative` instance. (If `α` has a
multiplicative monoid structure, see `Functor.Const`.) -/
def AddConst (α : Type*) :=
Const α
/-- `AddConst.mk` is the canonical map `α → AddConst α β`, which is the identity,
where `AddConst α β = Const α β`. It can be used as a pattern to extract this value. -/
@[match_pattern]
def AddConst.mk {α β} (x : α) : AddConst α β :=
x
/-- Extract the element of `α` from the constant functor. -/
def AddConst.run {α β} : AddConst α β → α :=
id
instance AddConst.functor {γ} : Functor (AddConst γ) :=
@Const.functor γ
instance AddConst.lawfulFunctor {γ} : LawfulFunctor (AddConst γ) :=
@Const.lawfulFunctor γ
instance {α β} [Inhabited α] : Inhabited (AddConst α β) :=
⟨(default : α)⟩
/-- `Functor.Comp` is a wrapper around `Function.Comp` for types.
It prevents Lean's type class resolution mechanism from trying
a `Functor (Comp F id)` when `Functor F` would do. -/
def Comp (F : Type u → Type w) (G : Type v → Type u) (α : Type v) : Type w :=
F <| G α
/-- Construct a term of `Comp F G α` from a term of `F (G α)`, which is the same type.
Can be used as a pattern to extract a term of `F (G α)`. -/
@[match_pattern]
def Comp.mk {F : Type u → Type w} {G : Type v → Type u} {α : Type v} (x : F (G α)) : Comp F G α :=
x
/-- Extract a term of `F (G α)` from a term of `Comp F G α`, which is the same type. -/
def Comp.run {F : Type u → Type w} {G : Type v → Type u} {α : Type v} (x : Comp F G α) : F (G α) :=
x
namespace Comp
variable {F : Type u → Type w} {G : Type v → Type u}
protected theorem ext {α} {x y : Comp F G α} : x.run = y.run → x = y :=
id
instance {α} [Inhabited (F (G α))] : Inhabited (Comp F G α) :=
⟨(default : F (G α))⟩
variable [Functor F] [Functor G]
/-- The map operation for the composition `Comp F G` of functors `F` and `G`. -/
protected def map {α β : Type v} (h : α → β) : Comp F G α → Comp F G β
| Comp.mk x => Comp.mk ((h <$> ·) <$> x)
instance functor : Functor (Comp F G) where map := @Comp.map F G _ _
@[functor_norm]
theorem map_mk {α β} (h : α → β) (x : F (G α)) : h <$> Comp.mk x = Comp.mk ((h <$> ·) <$> x) :=
rfl
@[simp]
protected theorem run_map {α β} (h : α → β) (x : Comp F G α) :
(h <$> x).run = (h <$> ·) <$> x.run :=
rfl
variable [LawfulFunctor F] [LawfulFunctor G]
variable {α β γ : Type v}
protected theorem id_map : ∀ x : Comp F G α, Comp.map id x = x
| Comp.mk x => by simp only [Comp.map, id_map, id_map']; rfl
protected theorem comp_map (g' : α → β) (h : β → γ) :
∀ x : Comp F G α, Comp.map (h ∘ g') x = Comp.map h (Comp.map g' x)
| Comp.mk x => by simp [Comp.map, Comp.mk, functor_norm, Function.comp_def]
instance lawfulFunctor : LawfulFunctor (Comp F G) where
map_const := rfl
id_map := Comp.id_map
comp_map := Comp.comp_map
theorem functor_comp_id {F} [AF : Functor F] [LawfulFunctor F] :
Comp.functor (G := Id) = AF :=
@Functor.ext F _ AF (Comp.lawfulFunctor (G := Id)) _ fun _ _ _ _ => rfl
theorem functor_id_comp {F} [AF : Functor F] [LawfulFunctor F] : Comp.functor (F := Id) = AF :=
@Functor.ext F _ AF (Comp.lawfulFunctor (F := Id)) _ fun _ _ _ _ => rfl
end Comp
namespace Comp
open Function hiding comp
open Functor
variable {F : Type u → Type w} {G : Type v → Type u}
variable [Applicative F] [Applicative G]
/-- The `<*>` operation for the composition of applicative functors. -/
protected def seq {α β : Type v} : Comp F G (α → β) → (Unit → Comp F G α) → Comp F G β
| Comp.mk f, g => match g () with
| Comp.mk x => Comp.mk <| (· <*> ·) <$> f <*> x
-- `ₓ` because the type of `Seq.seq` doesn't match `has_seq.seq`
instance : Pure (Comp F G) :=
⟨fun x => Comp.mk <| pure <| pure x⟩
instance : Seq (Comp F G) :=
⟨fun f x => Comp.seq f x⟩
@[simp]
protected theorem run_pure {α : Type v} : ∀ x : α, (pure x : Comp F G α).run = pure (pure x)
| _ => rfl
@[simp]
protected theorem run_seq {α β : Type v} (f : Comp F G (α → β)) (x : Comp F G α) :
(f <*> x).run = (· <*> ·) <$> f.run <*> x.run :=
rfl
instance instApplicativeComp : Applicative (Comp F G) :=
{ map := @Comp.map F G _ _, seq := @Comp.seq F G _ _ }
end Comp
variable {F : Type u → Type v} [Functor F]
/-- If we consider `x : F α` to, in some sense, contain values of type `α`,
predicate `Liftp p x` holds iff every value contained by `x` satisfies `p`. -/
def Liftp {α : Type u} (p : α → Prop) (x : F α) : Prop :=
∃ u : F (Subtype p), Subtype.val <$> u = x
/-- If we consider `x : F α` to, in some sense, contain values of type `α`, then
`Liftr r x y` relates `x` and `y` iff (1) `x` and `y` have the same shape and
(2) we can pair values `a` from `x` and `b` from `y` so that `r a b` holds. -/
def Liftr {α : Type u} (r : α → α → Prop) (x y : F α) : Prop :=
∃ u : F { p : α × α // r p.fst p.snd },
(fun t : { p : α × α // r p.fst p.snd } => t.val.fst) <$> u = x ∧
(fun t : { p : α × α // r p.fst p.snd } => t.val.snd) <$> u = y
/-- If we consider `x : F α` to, in some sense, contain values of type `α`, then
`supp x` is the set of values of type `α` that `x` contains. -/
def supp {α : Type u} (x : F α) : Set α :=
{ y : α | ∀ ⦃p⦄, Liftp p x → p y }
theorem of_mem_supp {α : Type u} {x : F α} {p : α → Prop} (h : Liftp p x) : ∀ y ∈ supp x, p y :=
fun _ hy => hy h
/-- If `f` is a functor, if `fb : f β` and `a : α`, then `mapConstRev fb a` is the result of
applying `f.map` to the constant function `β → α` sending everything to `a`, and then
evaluating at `fb`. In other words it's `const a <$> fb`. -/
abbrev mapConstRev {f : Type u → Type v} [Functor f] {α β : Type u} :
f β → α → f α :=
fun a b => Functor.mapConst b a
/-- If `f` is a functor, if `fb : f β` and `a : α`, then `mapConstRev fb a` is the result of
applying `f.map` to the constant function `β → α` sending everything to `a`, and then
evaluating at `fb`. In other words it's `const a <$> fb`. -/
infix:100 " $> " => Functor.mapConstRev
end Functor |
.lake/packages/mathlib/Mathlib/Control/Fix.lean | import Mathlib.Data.Part
import Mathlib.Data.Nat.Find
import Mathlib.Data.Nat.Upto
import Mathlib.Data.Stream.Defs
/-!
# Fixed point
This module defines a generic `fix` operator for defining recursive
computations that are not necessarily well-founded or productive.
An instance is defined for `Part`.
## Main definition
* class `Fix`
* `Part.fix`
-/
universe u v
variable {α : Type*} {β : α → Type*}
/-- `Fix α` provides a `fix` operator to define recursive computation
via the fixed point of function of type `α → α`. -/
class Fix (α : Type*) where
/-- `fix f` represents the computation of a fixed point for `f`. -/
fix : (α → α) → α
namespace Part
open Part Nat Nat.Upto
section Basic
variable (f : (∀ a, Part (β a)) → (∀ a, Part (β a)))
/-- A series of successive, finite approximation of the fixed point of `f`, defined by
`approx f n = f^[n] ⊥`. The limit of this chain is the fixed point of `f`. -/
def Fix.approx : Stream' (∀ a, Part (β a))
| 0 => ⊥
| Nat.succ i => f (Fix.approx i)
/-- loop body for finding the fixed point of `f` -/
def fixAux {p : ℕ → Prop} (i : Nat.Upto p) (g : ∀ j : Nat.Upto p, i < j → ∀ a, Part (β a)) :
∀ a, Part (β a) :=
f fun x : α => (assert ¬p i.val) fun h : ¬p i.val => g (i.succ h) (Nat.lt_succ_self _) x
/-- The least fixed point of `f`.
If `f` is a continuous function (according to complete partial orders),
it satisfies the equations:
1. `fix f = f (fix f)` (is a fixed point)
2. `∀ X, f X ≤ X → fix f ≤ X` (least fixed point)
-/
protected def fix (x : α) : Part (β x) :=
(Part.assert (∃ i, (Fix.approx f i x).Dom)) fun h =>
WellFounded.fix.{1} (Nat.Upto.wf h) (fixAux f) Nat.Upto.zero x
open Classical in
protected theorem fix_def {x : α} (h' : ∃ i, (Fix.approx f i x).Dom) :
Part.fix f x = Fix.approx f (Nat.succ (Nat.find h')) x := by
let p := fun i : ℕ => (Fix.approx f i x).Dom
have : p (Nat.find h') := Nat.find_spec h'
generalize hk : Nat.find h' = k
replace hk : Nat.find h' = k + (@Upto.zero p).val := hk
rw [hk] at this
revert hk
dsimp [Part.fix]; rw [assert_pos h']; revert this
generalize Upto.zero = z; intro _this hk
suffices ∀ x' hwf,
WellFounded.fix hwf (fixAux f) z x' = Fix.approx f (succ k) x'
from this _ _
induction k generalizing z with
| zero =>
intro x' _
rw [Fix.approx, WellFounded.fix_eq, fixAux]
congr
ext x : 1
rw [assert_neg]
· rfl
· rw [Nat.zero_add] at _this
simpa only [not_not, Coe]
| succ n n_ih =>
intro x' _
rw [Fix.approx, WellFounded.fix_eq, fixAux]
congr
ext : 1
have hh : ¬(Fix.approx f z.val x).Dom := by
apply Nat.find_min h'
omega
rw [succ_add_eq_add_succ] at _this hk
rw [assert_pos hh, n_ih (Upto.succ z hh) _this hk]
theorem fix_def' {x : α} (h' : ¬∃ i, (Fix.approx f i x).Dom) : Part.fix f x = none := by
dsimp [Part.fix]
rw [assert_neg h']
end Basic
end Part
namespace Part
instance hasFix : Fix (Part α) :=
⟨fun f => Part.fix (fun x u => f (x u)) ()⟩
end Part
open Sigma
namespace Pi
instance Part.hasFix {β} : Fix (α → Part β) :=
⟨Part.fix⟩
end Pi |
.lake/packages/mathlib/Mathlib/Control/EquivFunctor.lean | import Mathlib.Logic.Equiv.Defs
import Mathlib.Tactic.Convert
/-!
# Functions functorial with respect to equivalences
An `EquivFunctor` is a function from `Type → Type` equipped with the additional data of
coherently mapping equivalences to equivalences.
In categorical language, it is an endofunctor of the "core" of the category `Type`.
-/
universe u₀ u₁ u₂ v₀ v₁ v₂
open Function
/-- An `EquivFunctor` is only functorial with respect to equivalences.
To construct an `EquivFunctor`, it suffices to supply just the function `f α → f β` from
an equivalence `α ≃ β`, and then prove the functor laws. It's then a consequence that
this function is part of an equivalence, provided by `EquivFunctor.mapEquiv`.
-/
class EquivFunctor (f : Type u₀ → Type u₁) where
/-- The action of `f` on isomorphisms. -/
map : ∀ {α β}, α ≃ β → f α → f β
/-- `map` of `f` preserves the identity morphism. -/
map_refl' : ∀ α, map (Equiv.refl α) = @id (f α) := by rfl
/-- `map` is functorial on equivalences. -/
map_trans' : ∀ {α β γ} (k : α ≃ β) (h : β ≃ γ), map (k.trans h) = map h ∘ map k := by rfl
attribute [simp] EquivFunctor.map_refl'
namespace EquivFunctor
section
variable (f : Type u₀ → Type u₁) [EquivFunctor f] {α β : Type u₀} (e : α ≃ β)
/-- An `EquivFunctor` in fact takes every equiv to an equiv. -/
def mapEquiv : f α ≃ f β where
toFun := EquivFunctor.map e
invFun := EquivFunctor.map e.symm
left_inv x := by
convert (congr_fun (EquivFunctor.map_trans' e e.symm) x).symm
simp
right_inv y := by
convert (congr_fun (EquivFunctor.map_trans' e.symm e) y).symm
simp
@[simp]
theorem mapEquiv_apply (x : f α) : mapEquiv f e x = EquivFunctor.map e x :=
rfl
theorem mapEquiv_symm_apply (y : f β) : (mapEquiv f e).symm y = EquivFunctor.map e.symm y :=
rfl
@[simp]
theorem mapEquiv_refl (α) : mapEquiv f (Equiv.refl α) = Equiv.refl (f α) := by
ext; simp [mapEquiv]
@[simp]
theorem mapEquiv_symm : (mapEquiv f e).symm = mapEquiv f e.symm :=
Equiv.ext <| mapEquiv_symm_apply f e
/-- The composition of `mapEquiv`s is carried over the `EquivFunctor`.
For plain `Functor`s, this lemma is named `map_map` when applied
or `map_comp_map` when not applied.
-/
@[simp]
theorem mapEquiv_trans {γ : Type u₀} (ab : α ≃ β) (bc : β ≃ γ) :
(mapEquiv f ab).trans (mapEquiv f bc) = mapEquiv f (ab.trans bc) :=
Equiv.ext fun x => by simp [mapEquiv, map_trans']
end
instance (priority := 100) ofLawfulFunctor (f : Type u₀ → Type u₁) [Functor f] [LawfulFunctor f] :
EquivFunctor f where
map {_ _} e := Functor.map e
map_refl' α := by
ext
apply LawfulFunctor.id_map
map_trans' {α β γ} k h := by
ext x
apply LawfulFunctor.comp_map k h x
theorem mapEquiv.injective (f : Type u₀ → Type u₁)
[Applicative f] [LawfulApplicative f] {α β : Type u₀}
(h : ∀ γ, Function.Injective (pure : γ → f γ)) :
Function.Injective (@EquivFunctor.mapEquiv f _ α β) :=
fun e₁ e₂ H =>
Equiv.ext fun x => h β (by simpa [EquivFunctor.map] using Equiv.congr_fun H (pure x))
end EquivFunctor |
.lake/packages/mathlib/Mathlib/Control/Random.lean | import Mathlib.Control.ULiftable
import Mathlib.Order.Fin.Basic
/-!
# Rand Monad and Random Class
This module provides tools for formulating computations guided by randomness and for
defining objects that can be created randomly.
## Main definitions
* `RandT` and `RandGT` monad transformers for computations guided by randomness;
* `Rand` and `RandG` monads as special cases of the above
* `Random` class for objects that can be generated randomly;
* `random` to generate one object;
* `BoundedRandom` class for objects that can be generated randomly inside a range;
* `randomR` to generate one object inside a range;
* `IO.runRand` to run a randomized computation inside any monad that has access to `stdGenRef`.
## References
* Similar library in Haskell: https://hackage.haskell.org/package/MonadRandom
-/
set_option autoImplicit true -- Note: this file uses `autoImplicit` pervasively
/-- A monad transformer to generate random objects using the generic generator type `g` -/
abbrev RandGT (g : Type) := StateT (ULift g)
/-- A monad to generate random objects using the generator type `g`. -/
abbrev RandG (g : Type) := RandGT g Id
/-- A monad transformer to generate random objects using the generator type `StdGen`.
`RandT m α` should be thought of a random value in `m α`. -/
abbrev RandT := RandGT StdGen
/-- A monad to generate random objects using the generator type `StdGen`. -/
abbrev Rand := RandG StdGen
instance [MonadLift m n] : MonadLiftT (RandGT g m) (RandGT g n) where
monadLift x := fun s => x s
/-- `Random m α` gives us machinery to generate values of type `α` in the monad `m`.
Note that `m` is a parameter as some types may only be sampleable with access to a certain monad. -/
class Random (m) (α : Type u) where
/-- Sample an element of this type from the provided generator. -/
random [RandomGen g] : RandGT g m α
/-- `BoundedRandom m α` gives us machinery to generate values of type `α` between certain bounds in
the monad `m`. -/
class BoundedRandom (m) (α : Type u) [Preorder α] where
/-- Sample a bounded element of this type from the provided generator. -/
randomR {g : Type} (lo hi : α) (h : lo ≤ hi) [RandomGen g] : RandGT g m {a // lo ≤ a ∧ a ≤ hi}
namespace Rand
/-- Generate a random `Nat`. -/
def next [RandomGen g] [Monad m] : RandGT g m Nat := do
let rng := (← get).down
let (res, new) := RandomGen.next rng
set (ULift.up new)
pure res
/-- Create a new random number generator distinct from the one stored in the state. -/
def split {g : Type} [RandomGen g] [Monad m] : RandGT g m g := do
let rng := (← get).down
let (r1, r2) := RandomGen.split rng
set (ULift.up r1)
pure r2
/-- Get the range of `Nat` that can be generated by the generator `g`. -/
def range {g : Type} [RandomGen g] [Monad m] : RandGT g m (Nat × Nat) := do
let rng := (← get).down
pure <| RandomGen.range rng
end Rand
namespace Random
open Rand
variable [Monad m]
/-- Generate a random value of type `α`. -/
def rand (α : Type u) [Random m α] [RandomGen g] : RandGT g m α := Random.random
/-- Generate a random value of type `α` between `x` and `y` inclusive. -/
def randBound (α : Type u)
[Preorder α] [BoundedRandom m α] (lo hi : α) (h : lo ≤ hi) [RandomGen g] :
RandGT g m {a // lo ≤ a ∧ a ≤ hi} :=
(BoundedRandom.randomR lo hi h : RandGT g _ _)
/-- Generate a random `Fin`. -/
def randFin {n : Nat} [NeZero n] [RandomGen g] : RandGT g m (Fin n) :=
fun ⟨g⟩ ↦ pure <| randNat g 0 (n - 1) |>.map (Fin.ofNat n) ULift.up
instance {n : Nat} [NeZero n] : Random m (Fin n) where
random := randFin
/-- Generate a random `Bool`. -/
def randBool [RandomGen g] : RandGT g m Bool :=
return (← rand (Fin 2)) == 1
instance : Random m Bool where
random := randBool
instance {α : Type u} [ULiftable m m'] [Random m α] : Random m' (ULift.{v} α) where
random := ULiftable.up random
instance : BoundedRandom m Nat where
randomR lo hi h _ := do
let z ← rand (Fin (hi - lo + 1))
pure ⟨
lo + z.val, Nat.le_add_right _ _,
Nat.add_le_of_le_sub' h (Nat.le_of_lt_add_one z.isLt)
⟩
instance : BoundedRandom m Int where
randomR lo hi h _ := do
let ⟨z, _, h2⟩ ← randBound Nat 0 (Int.natAbs <| hi - lo) (Nat.zero_le _)
pure ⟨
z + lo,
Int.le_add_of_nonneg_left (Int.ofNat_zero_le z),
Int.add_le_of_le_sub_right <| Int.le_trans
(Int.ofNat_le.mpr h2)
(le_of_eq <| Int.natAbs_of_nonneg <| Int.sub_nonneg_of_le h)⟩
instance {n : Nat} : BoundedRandom m (Fin n) where
randomR lo hi h _ := do
let ⟨r, h1, h2⟩ ← randBound Nat lo.val hi.val h
pure ⟨⟨r, Nat.lt_of_le_of_lt h2 hi.isLt⟩, h1, h2⟩
instance {α : Type u} [Preorder α] [ULiftable m m'] [BoundedRandom m α] [Monad m'] :
BoundedRandom m' (ULift.{v} α) where
randomR lo hi h := do
let ⟨x⟩ ← ULiftable.up.{v} (BoundedRandom.randomR lo.down hi.down h)
pure ⟨ULift.up x.val, x.prop⟩
end Random
namespace IO
variable {m : Type* → Type*} {m₀ : Type → Type}
variable [Monad m] [MonadLiftT (ST RealWorld) m₀] [ULiftable m₀ m]
/--
Execute `RandT m α` using the global `stdGenRef` as RNG.
Note that:
- `stdGenRef` is not necessarily properly seeded on program startup
as of now and will therefore be deterministic.
- `stdGenRef` is not thread local, hence two threads accessing it
at the same time will get the exact same generator.
-/
def runRand (cmd : RandT m α) : m α := do
let stdGen ← ULiftable.up (stdGenRef.get : m₀ _)
let (res, new) ← StateT.run cmd stdGen
let _ ← ULiftable.up (stdGenRef.set new.down : m₀ _)
pure res
/-- Execute `RandT m α` using the global `stdGenRef` as RNG and the given `seed`. -/
def runRandWith (seed : Nat) (cmd : RandT m α) : m α := do
pure <| (← cmd.run (ULift.up <| mkStdGen seed)).1
end IO |
.lake/packages/mathlib/Mathlib/Control/Functor/Multivariate.lean | import Mathlib.Data.Fin.Fin2
import Mathlib.Data.TypeVec
import Mathlib.Logic.Equiv.Defs
/-!
# Functors between the category of tuples of types, and the category Type
Features:
* `MvFunctor n` : the type class of multivariate functors
* `f <$$> x` : notation for map
-/
universe u v w
open MvFunctor
/-- Multivariate functors, i.e. functor between the category of type vectors
and the category of Type -/
class MvFunctor {n : ℕ} (F : TypeVec n → Type*) where
/-- Multivariate map, if `f : α ⟹ β` and `x : F α` then `f <$$> x : F β`. -/
map : ∀ {α β : TypeVec n}, α ⟹ β → F α → F β
/-- Multivariate map, if `f : α ⟹ β` and `x : F α` then `f <$$> x : F β` -/
scoped[MvFunctor] infixr:100 " <$$> " => MvFunctor.map
variable {n : ℕ}
namespace MvFunctor
variable {α β : TypeVec.{u} n} {F : TypeVec.{u} n → Type v} [MvFunctor F]
/-- predicate lifting over multivariate functors -/
def LiftP {α : TypeVec n} (P : ∀ i, α i → Prop) (x : F α) : Prop :=
∃ u : F (fun i => Subtype (P i)), (fun i => @Subtype.val _ (P i)) <$$> u = x
/-- relational lifting over multivariate functors -/
def LiftR {α : TypeVec n} (R : ∀ ⦃i⦄, α i → α i → Prop) (x y : F α) : Prop :=
∃ u : F (fun i => { p : α i × α i // R p.fst p.snd }),
(fun i (t : { p : α i × α i // R p.fst p.snd }) => t.val.fst) <$$> u = x ∧
(fun i (t : { p : α i × α i // R p.fst p.snd }) => t.val.snd) <$$> u = y
/-- given `x : F α` and a projection `i` of type vector `α`, `supp x i` is the set
of `α.i` contained in `x` -/
def supp {α : TypeVec n} (x : F α) (i : Fin2 n) : Set (α i) :=
{ y : α i | ∀ ⦃P⦄, LiftP P x → P i y }
theorem of_mem_supp {α : TypeVec n} {x : F α} {P : ∀ ⦃i⦄, α i → Prop} (h : LiftP P x) (i : Fin2 n) :
∀ y ∈ supp x i, P y := fun _y hy => hy h
end MvFunctor
/-- laws for `MvFunctor` -/
class LawfulMvFunctor {n : ℕ} (F : TypeVec n → Type*) [MvFunctor F] : Prop where
/-- `map` preserved identities, i.e., maps identity on `α` to identity on `F α` -/
id_map : ∀ {α : TypeVec n} (x : F α), TypeVec.id <$$> x = x
/-- `map` preserves compositions -/
comp_map :
∀ {α β γ : TypeVec n} (g : α ⟹ β) (h : β ⟹ γ) (x : F α), (h ⊚ g) <$$> x = h <$$> g <$$> x
open Nat TypeVec
namespace MvFunctor
export LawfulMvFunctor (comp_map)
open LawfulMvFunctor
variable {α β γ : TypeVec.{u} n}
variable {F : TypeVec.{u} n → Type v} [MvFunctor F]
variable (P : α ⟹ «repeat» n Prop) (R : α ⊗ α ⟹ «repeat» n Prop)
/-- adapt `MvFunctor.LiftP` to accept predicates as arrows -/
def LiftP' : F α → Prop :=
MvFunctor.LiftP fun i x => ofRepeat <| P i x
/-- adapt `MvFunctor.LiftR` to accept relations as arrows -/
def LiftR' : F α → F α → Prop :=
MvFunctor.LiftR @fun i x y => ofRepeat <| R i <| TypeVec.prod.mk _ x y
variable [LawfulMvFunctor F]
@[simp]
theorem id_map (x : F α) : TypeVec.id <$$> x = x :=
LawfulMvFunctor.id_map x
@[simp]
theorem id_map' (x : F α) : (fun _i a => a) <$$> x = x :=
id_map x
theorem map_map (g : α ⟹ β) (h : β ⟹ γ) (x : F α) : h <$$> g <$$> x = (h ⊚ g) <$$> x :=
Eq.symm <| comp_map _ _ _
section LiftP'
variable (F) in
theorem exists_iff_exists_of_mono {P : F α → Prop} {q : F β → Prop}
(f : α ⟹ β) (g : β ⟹ α)
(h₀ : f ⊚ g = TypeVec.id)
(h₁ : ∀ u : F α, P u ↔ q (f <$$> u)) :
(∃ u : F α, P u) ↔ ∃ u : F β, q u := by
constructor <;> rintro ⟨u, h₂⟩
· refine ⟨f <$$> u, ?_⟩
apply (h₁ u).mp h₂
· refine ⟨g <$$> u, ?_⟩
rw [h₁]
simp only [MvFunctor.map_map, h₀, LawfulMvFunctor.id_map, h₂]
theorem LiftP_def (x : F α) : LiftP' P x ↔ ∃ u : F (Subtype_ P), subtypeVal P <$$> u = x :=
exists_iff_exists_of_mono F _ _ (toSubtype_of_subtype P) (by simp [MvFunctor.map_map])
theorem LiftR_def (x y : F α) :
LiftR' R x y ↔
∃ u : F (Subtype_ R),
(TypeVec.prod.fst ⊚ subtypeVal R) <$$> u = x ∧
(TypeVec.prod.snd ⊚ subtypeVal R) <$$> u = y :=
exists_iff_exists_of_mono _ _ _ (toSubtype'_of_subtype' R) (by
simp only [map_map, comp_assoc, subtypeVal_toSubtype']
simp +unfoldPartialApp [comp])
end LiftP'
end MvFunctor
namespace MvFunctor
section LiftPLastPredIff
variable {F : TypeVec.{u} (n + 1) → Type*} [MvFunctor F] [LawfulMvFunctor F] {α : TypeVec.{u} n}
variable {β : Type u}
variable (pp : β → Prop)
private def f :
∀ n α,
(fun i : Fin2 (n + 1) => { p_1 // ofRepeat (PredLast' α pp i p_1) }) ⟹ fun i : Fin2 (n + 1) =>
{ p_1 : (α ::: β) i // PredLast α pp p_1 }
| _, α, Fin2.fs i, x =>
⟨x.val, cast (by grind [PredLast]) x.property⟩
| _, _, Fin2.fz, x => ⟨x.val, x.property⟩
private def g :
∀ n α,
(fun i : Fin2 (n + 1) => { p_1 : (α ::: β) i // PredLast α pp p_1 }) ⟹ fun i : Fin2 (n + 1) =>
{ p_1 // ofRepeat (PredLast' α pp i p_1) }
| _, α, Fin2.fs i, x =>
⟨x.val, cast (by simp only [PredLast]; erw [const_iff_true]) x.property⟩
| _, _, Fin2.fz, x => ⟨x.val, x.property⟩
theorem LiftP_PredLast_iff {β} (P : β → Prop) (x : F (α ::: β)) :
LiftP' (PredLast' _ P) x ↔ LiftP (PredLast _ P) x := by
dsimp only [LiftP, LiftP']
apply exists_iff_exists_of_mono F (f _ n α) (g _ n α)
· ext i ⟨x, _⟩
cases i <;> rfl
· intros
rw [MvFunctor.map_map]
dsimp +unfoldPartialApp [(· ⊚ ·)]
suffices (fun i => Subtype.val) = (fun i x => (MvFunctor.f P n α i x).val) by rw [this]
ext i ⟨x, _⟩
cases i <;> rfl
variable (rr : β → β → Prop)
private def f' :
∀ n α,
(fun i : Fin2 (n + 1) =>
{ p_1 : _ × _ // ofRepeat (RelLast' α rr i (TypeVec.prod.mk _ p_1.fst p_1.snd)) }) ⟹
fun i : Fin2 (n + 1) => { p_1 : (α ::: β) i × _ // RelLast α rr p_1.fst p_1.snd }
| _, α, Fin2.fs i, x =>
⟨x.val, cast (by simp only [RelLast]; erw [repeatEq_iff_eq]) x.property⟩
| _, _, Fin2.fz, x => ⟨x.val, x.property⟩
private def g' :
∀ n α,
(fun i : Fin2 (n + 1) => { p_1 : (α ::: β) i × _ // RelLast α rr p_1.fst p_1.snd }) ⟹
fun i : Fin2 (n + 1) =>
{ p_1 : _ × _ // ofRepeat (RelLast' α rr i (TypeVec.prod.mk _ p_1.1 p_1.2)) }
| _, α, Fin2.fs i, x =>
⟨x.val, cast (by simp only [RelLast]; erw [repeatEq_iff_eq]) x.property⟩
| _, _, Fin2.fz, x => ⟨x.val, x.property⟩
theorem LiftR_RelLast_iff (x y : F (α ::: β)) :
LiftR' (RelLast' _ rr) x y ↔ LiftR (RelLast _ rr) x y := by
dsimp only [LiftR, LiftR']
apply exists_iff_exists_of_mono F (f' rr _ _) (g' rr _ _)
· ext i ⟨x, _⟩ : 2
cases i <;> rfl
· intros
simp +unfoldPartialApp only [map_map, TypeVec.comp]
apply iff_of_eq -- Switch to `eq` so we can use `ext`
congr <;> ext i ⟨x, _⟩ <;> cases i <;> rfl
end LiftPLastPredIff
/-- Any type function that is (extensionally) equivalent to a functor, is itself a functor -/
def ofEquiv {F F' : TypeVec.{u} n → Type*} [MvFunctor F'] (eqv : ∀ α, F α ≃ F' α) :
MvFunctor F where
map f x := (eqv _).symm <| f <$$> eqv _ x
end MvFunctor |
.lake/packages/mathlib/Mathlib/Control/Traversable/Instances.lean | import Mathlib.Control.Applicative
import Mathlib.Control.Traversable.Basic
import Mathlib.Data.List.Forall2
import Mathlib.Data.Set.Functor
/-!
# LawfulTraversable instances
This file provides instances of `LawfulTraversable` for types from the core library: `Option`,
`List` and `Sum`.
-/
universe u v
section Option
open Functor
variable {F G : Type u → Type u}
variable [Applicative F] [Applicative G]
variable [LawfulApplicative G]
theorem Option.id_traverse {α} (x : Option α) : Option.traverse (pure : α → Id α) x = pure x := by
cases x <;> rfl
theorem Option.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : Option α) :
Option.traverse (Comp.mk ∘ (f <$> ·) ∘ g) x =
Comp.mk (Option.traverse f <$> Option.traverse g x) := by
cases x <;> (simp [Option.traverse, Option.mapM, functor_norm] <;> rfl)
theorem Option.traverse_eq_map_id {α β} (f : α → β) (x : Option α) :
Option.traverse ((pure : _ → Id _) ∘ f) x = (pure : _ → Id _) (f <$> x) := by cases x <;> rfl
variable (η : ApplicativeTransformation F G)
theorem Option.naturality [LawfulApplicative F] {α β} (f : α → F β) (x : Option α) :
η (Option.traverse f x) = Option.traverse (@η _ ∘ f) x := by
rcases x with - | x <;> simp! [*, functor_norm, Option.traverse]
end Option
instance : LawfulTraversable Option :=
{ show LawfulMonad Option from inferInstance with
id_traverse := Option.id_traverse
comp_traverse := Option.comp_traverse
traverse_eq_map_id := Option.traverse_eq_map_id
naturality := fun η _ _ f x => Option.naturality η f x }
namespace List
variable {F G : Type u → Type u}
variable [Applicative F] [Applicative G]
section
variable [LawfulApplicative G]
open Applicative Functor List
protected theorem id_traverse {α} (xs : List α) : (List.traverse pure xs : Id _) = pure xs := by
induction xs <;> simp! [*, List.traverse, functor_norm]
protected theorem comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : List α) :
List.traverse (Comp.mk ∘ (f <$> ·) ∘ g) x =
Comp.mk (List.traverse f <$> List.traverse g x) := by
induction x <;> simp! [*, functor_norm] <;> rfl
protected theorem traverse_eq_map_id {α β} (f : α → β) (x : List α) :
List.traverse ((pure : _ → Id _) ∘ f) x = (pure : _ → Id _) (f <$> x) := by
induction x <;> simp! [*, functor_norm]
variable [LawfulApplicative F] (η : ApplicativeTransformation F G)
protected theorem naturality {α β} (f : α → F β) (x : List α) :
η (List.traverse f x) = List.traverse (@η _ ∘ f) x := by
induction x <;> simp! [*, functor_norm]
instance : LawfulTraversable.{u} List :=
{ show LawfulMonad List from inferInstance with
id_traverse := List.id_traverse
comp_traverse := List.comp_traverse
traverse_eq_map_id := List.traverse_eq_map_id
naturality := List.naturality }
end
section Traverse
variable {α' β' : Type u} (f : α' → F β')
@[simp]
theorem traverse_nil : traverse f ([] : List α') = (pure [] : F (List β')) :=
rfl
@[simp]
theorem traverse_cons (a : α') (l : List α') :
traverse f (a :: l) = (· :: ·) <$> f a <*> traverse f l :=
rfl
variable [LawfulApplicative F]
@[simp]
theorem traverse_append :
∀ as bs : List α', traverse f (as ++ bs) = (· ++ ·) <$> traverse f as <*> traverse f bs
| [], bs => by simp [functor_norm]
| a :: as, bs => by simp [traverse_append as bs, functor_norm]; congr
theorem mem_traverse {f : α' → Set β'} :
∀ (l : List α') (n : List β'), n ∈ traverse f l ↔ Forall₂ (fun b a => b ∈ f a) n l
| [], [] => by simp
| a :: as, [] => by simp
| [], b :: bs => by simp
| a :: as, b :: bs => by simp [mem_traverse as bs]
end Traverse
end List
namespace Sum
section Traverse
variable {σ : Type u}
variable {F G : Type u → Type u}
variable [Applicative F] [Applicative G]
open Applicative Functor
protected theorem traverse_map {α β γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) :
Sum.traverse f (g <$> x) = Sum.traverse (f ∘ g) x := by
cases x <;> simp [Sum.traverse, functor_norm] <;> rfl
protected theorem id_traverse {σ α} (x : σ ⊕ α) :
Sum.traverse (pure : α → Id α) x = x := by cases x <;> rfl
variable [LawfulApplicative G]
protected theorem comp_traverse {α β γ : Type u} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) :
Sum.traverse (Comp.mk ∘ (f <$> ·) ∘ g) x =
Comp.mk.{u} (Sum.traverse f <$> Sum.traverse g x) := by
cases x <;> (simp! [Sum.traverse, map_id, functor_norm] <;> rfl)
protected theorem traverse_eq_map_id {α β} (f : α → β) (x : σ ⊕ α) :
Sum.traverse ((pure : _ → Id _) ∘ f) x = (pure : _ → Id _) (f <$> x) := by
induction x <;> simp! [*, functor_norm] <;> rfl
protected theorem map_traverse {α β γ} (g : α → G β) (f : β → γ) (x : σ ⊕ α) :
(f <$> ·) <$> Sum.traverse g x = Sum.traverse (f <$> g ·) x := by
cases x <;> simp [Sum.traverse, functor_norm] <;> congr
variable [LawfulApplicative F] (η : ApplicativeTransformation F G)
protected theorem naturality {α β} (f : α → F β) (x : σ ⊕ α) :
η (Sum.traverse f x) = Sum.traverse (@η _ ∘ f) x := by
cases x <;> simp! [Sum.traverse, functor_norm]
end Traverse
instance {σ : Type u} : LawfulTraversable.{u} (Sum σ) :=
{ show LawfulMonad (Sum σ) from inferInstance with
id_traverse := Sum.id_traverse
comp_traverse := Sum.comp_traverse
traverse_eq_map_id := Sum.traverse_eq_map_id
naturality := Sum.naturality }
end Sum |
.lake/packages/mathlib/Mathlib/Control/Traversable/Lemmas.lean | import Mathlib.Control.Applicative
import Mathlib.Control.Traversable.Basic
/-!
# Traversing collections
This file proves basic properties of traversable and applicative functors and defines
`PureTransformation F`, the natural applicative transformation from the identity functor to `F`.
## References
Inspired by [The Essence of the Iterator Pattern][gibbons2009].
-/
universe u
open LawfulTraversable
open Function hiding comp
open Functor
attribute [functor_norm] LawfulTraversable.naturality
attribute [simp] LawfulTraversable.id_traverse
namespace Traversable
variable {t : Type u → Type u}
variable [Traversable t] [LawfulTraversable t]
variable (F G : Type u → Type u)
variable [Applicative F] [LawfulApplicative F]
variable [Applicative G] [LawfulApplicative G]
variable {α β γ : Type u}
variable (g : α → F β)
variable (f : β → γ)
/-- The natural applicative transformation from the identity functor
to `F`, defined by `pure : Π {α}, α → F α`. -/
def PureTransformation :
ApplicativeTransformation Id F where
app := @pure F _
preserves_pure' _ := rfl
preserves_seq' f x := by
simp only [map_pure, seq_pure]
rfl
@[simp]
theorem pureTransformation_apply {α} (x : id α) : PureTransformation F x = pure x :=
rfl
variable {F G}
theorem map_eq_traverse_id : map (f := t) f = Id.run ∘ traverse (pure ∘ f) :=
funext fun y => (traverse_eq_map_id f y).symm
theorem map_traverse (x : t α) : map f <$> traverse g x = traverse (map f ∘ g) x := by
rw [map_eq_traverse_id f]
refine (comp_traverse (pure ∘ f) g x).symm.trans ?_
congr 1; apply Comp.applicative_comp_id
theorem traverse_map (f : β → F γ) (g : α → β) (x : t α) :
traverse f (g <$> x) = traverse (f ∘ g) x := by
rw [@map_eq_traverse_id t _ _ _ _ g]
refine (comp_traverse (G := Id) f (pure ∘ g) x).symm.trans ?_
congr 1; apply Comp.applicative_id_comp
theorem pure_traverse (x : t α) : traverse pure x = (pure x : F (t α)) := by
have : traverse pure x = pure (traverse (m := Id) pure x) :=
(naturality (PureTransformation F) pure x).symm
rwa [id_traverse] at this
theorem id_sequence (x : t α) : sequence (f := Id) (pure <$> x) = pure x := by
simp [sequence, traverse_map, id_traverse]
theorem comp_sequence (x : t (F (G α))) :
sequence (Comp.mk <$> x) = Comp.mk (sequence <$> sequence x) := by
simp only [sequence, traverse_map, id_comp]; rw [← comp_traverse]; simp [map_id]
theorem naturality' (η : ApplicativeTransformation F G) (x : t (F α)) :
η (sequence x) = sequence (@η _ <$> x) := by simp [sequence, naturality, traverse_map]
@[functor_norm]
theorem traverse_id : traverse pure = (pure : t α → Id (t α)) := by
ext
exact id_traverse _
@[functor_norm]
theorem traverse_comp (g : α → F β) (h : β → G γ) :
traverse (Comp.mk ∘ map h ∘ g) =
(Comp.mk ∘ map (traverse h) ∘ traverse g : t α → Comp F G (t γ)) := by
ext
exact comp_traverse _ _ _
theorem traverse_eq_map_id' (f : β → γ) :
traverse (m := Id) (pure ∘ f) = pure ∘ (map f : t β → t γ) := by
ext
exact traverse_eq_map_id _ _
-- @[functor_norm]
theorem traverse_map' (g : α → β) (h : β → G γ) :
traverse (h ∘ g) = (traverse h ∘ map g : t α → G (t γ)) := by
ext
rw [comp_apply, traverse_map]
theorem map_traverse' (g : α → G β) (h : β → γ) :
traverse (map h ∘ g) = (map (map h) ∘ traverse g : t α → G (t γ)) := by
ext
rw [comp_apply, map_traverse]
theorem naturality_pf (η : ApplicativeTransformation F G) (f : α → F β) :
traverse (@η _ ∘ f) = @η _ ∘ (traverse f : t α → F (t β)) := by
ext
rw [comp_apply, naturality]
end Traversable |
.lake/packages/mathlib/Mathlib/Control/Traversable/Basic.lean | import Mathlib.Data.Option.Defs
import Mathlib.Control.Functor
import Batteries.Data.List.Basic
import Mathlib.Control.Basic
/-!
# Traversable type class
Type classes for traversing collections. The concepts and laws are taken from
<http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-Traversable.html>
Traversable collections are a generalization of functors. Whereas
functors (such as `List`) allow us to apply a function to every
element, it does not allow functions which external effects encoded in
a monad. Consider for instance a functor `invite : email → IO response`
that takes an email address, sends an email and waits for a
response. If we have a list `guests : List email`, using calling
`invite` using `map` gives us the following:
`map invite guests : List (IO response)`. It is not what we need. We need something of
type `IO (List response)`. Instead of using `map`, we can use `traverse` to
send all the invites: `traverse invite guests : IO (List response)`.
`traverse` applies `invite` to every element of `guests` and combines
all the resulting effects. In the example, the effect is encoded in the
monad `IO` but any applicative functor is accepted by `traverse`.
For more on how to use traversable, consider the Haskell tutorial:
<https://en.wikibooks.org/wiki/Haskell/Traversable>
## Main definitions
* `Traversable` type class - exposes the `traverse` function
* `sequence` - based on `traverse`,
turns a collection of effects into an effect returning a collection
* `LawfulTraversable` - laws for a traversable functor
* `ApplicativeTransformation` - the notion of a natural transformation for applicative functors
## Tags
traversable iterator functor applicative
## References
* "Applicative Programming with Effects", by Conor McBride and Ross Paterson,
Journal of Functional Programming 18:1 (2008) 1-13, online at
<http://www.soi.city.ac.uk/~ross/papers/Applicative.html>
* "The Essence of the Iterator Pattern", by Jeremy Gibbons and Bruno Oliveira,
in Mathematically-Structured Functional Programming, 2006, online at
<http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator>
* "An Investigation of the Laws of Traversals", by Mauro Jaskelioff and Ondrej Rypacek,
in Mathematically-Structured Functional Programming, 2012,
online at <http://arxiv.org/pdf/1202.2919>
-/
open Function hiding comp
universe u v w
section ApplicativeTransformation
variable (F : Type u → Type v) [Applicative F]
variable (G : Type u → Type w) [Applicative G]
/-- A transformation between applicative functors. It is a natural
transformation such that `app` preserves the `Pure.pure` and
`Functor.map` (`<*>`) operations. See
`ApplicativeTransformation.preserves_map` for naturality. -/
structure ApplicativeTransformation : Type max (u + 1) v w where
/-- The function on objects defined by an `ApplicativeTransformation`. -/
app : ∀ α : Type u, F α → G α
/-- An `ApplicativeTransformation` preserves `pure`. -/
preserves_pure' : ∀ {α : Type u} (x : α), app _ (pure x) = pure x
/-- An `ApplicativeTransformation` intertwines `seq`. -/
preserves_seq' : ∀ {α β : Type u} (x : F (α → β)) (y : F α), app _ (x <*> y) = app _ x <*> app _ y
end ApplicativeTransformation
namespace ApplicativeTransformation
variable (F : Type u → Type v) [Applicative F]
variable (G : Type u → Type w) [Applicative G]
instance : CoeFun (ApplicativeTransformation F G) fun _ => ∀ {α}, F α → G α :=
⟨fun η ↦ η.app _⟩
variable {F G}
-- This cannot be a `simp` lemma, as the RHS is a coercion which contains `η.app`.
theorem app_eq_coe (η : ApplicativeTransformation F G) : η.app = η :=
rfl
@[simp]
theorem coe_mk (f : ∀ α : Type u, F α → G α) (pp ps) :
(ApplicativeTransformation.mk f @pp @ps) = f :=
rfl
protected theorem congr_fun (η η' : ApplicativeTransformation F G) (h : η = η') {α : Type u}
(x : F α) : η x = η' x :=
congrArg (fun η'' : ApplicativeTransformation F G => η'' x) h
protected theorem congr_arg (η : ApplicativeTransformation F G) {α : Type u} {x y : F α}
(h : x = y) : η x = η y :=
congrArg (fun z : F α => η z) h
theorem coe_inj ⦃η η' : ApplicativeTransformation F G⦄ (h : (η : ∀ α, F α → G α) = η') :
η = η' := by
cases η
cases η'
congr
@[ext]
theorem ext ⦃η η' : ApplicativeTransformation F G⦄ (h : ∀ (α : Type u) (x : F α), η x = η' x) :
η = η' := by
apply coe_inj
ext1 α
exact funext (h α)
section Preserves
variable (η : ApplicativeTransformation F G)
@[functor_norm]
theorem preserves_pure {α} : ∀ x : α, η (pure x) = pure x :=
η.preserves_pure'
@[functor_norm]
theorem preserves_seq {α β : Type u} : ∀ (x : F (α → β)) (y : F α), η (x <*> y) = η x <*> η y :=
η.preserves_seq'
variable [LawfulApplicative F] [LawfulApplicative G]
@[functor_norm]
theorem preserves_map {α β} (x : α → β) (y : F α) : η (x <$> y) = x <$> η y := by
rw [← pure_seq, η.preserves_seq, preserves_pure, pure_seq]
theorem preserves_map' {α β} (x : α → β) : @η _ ∘ Functor.map x = Functor.map x ∘ @η _ := by
ext y
exact preserves_map η x y
end Preserves
/-- The identity applicative transformation from an applicative functor to itself. -/
def idTransformation : ApplicativeTransformation F F where
app _ := id
preserves_pure' := by simp
preserves_seq' x y := by simp
instance : Inhabited (ApplicativeTransformation F F) :=
⟨idTransformation⟩
universe s t
variable {H : Type u → Type s} [Applicative H]
/-- The composition of applicative transformations. -/
def comp (η' : ApplicativeTransformation G H) (η : ApplicativeTransformation F G) :
ApplicativeTransformation F H where
app _ x := η' (η x)
preserves_pure' x := by simp [functor_norm]
preserves_seq' x y := by simp [functor_norm]
@[simp]
theorem comp_apply (η' : ApplicativeTransformation G H) (η : ApplicativeTransformation F G)
{α : Type u} (x : F α) : η'.comp η x = η' (η x) :=
rfl
theorem comp_assoc {I : Type u → Type t} [Applicative I]
(η'' : ApplicativeTransformation H I) (η' : ApplicativeTransformation G H)
(η : ApplicativeTransformation F G) : (η''.comp η').comp η = η''.comp (η'.comp η) :=
rfl
@[simp]
theorem comp_id (η : ApplicativeTransformation F G) : η.comp idTransformation = η :=
ext fun _ _ => rfl
@[simp]
theorem id_comp (η : ApplicativeTransformation F G) : idTransformation.comp η = η :=
ext fun _ _ => rfl
end ApplicativeTransformation
open ApplicativeTransformation
/-- A traversable functor is a functor along with a way to commute
with all applicative functors (see `sequence`). For example, if `t`
is the traversable functor `List` and `m` is the applicative functor
`IO`, then given a function `f : α → IO β`, the function `Functor.map f` is
`List α → List (IO β)`, but `traverse f` is `List α → IO (List β)`. -/
class Traversable (t : Type u → Type u) extends Functor t where
/-- The function commuting a traversable functor `t` with an arbitrary applicative functor `m`. -/
traverse : ∀ {m : Type u → Type u} [Applicative m] {α β}, (α → m β) → t α → m (t β)
open Functor
export Traversable (traverse)
section Functions
variable {t : Type u → Type u}
variable {α : Type u}
variable {f : Type u → Type u} [Applicative f]
/-- A traversable functor commutes with all applicative functors. -/
def sequence [Traversable t] : t (f α) → f (t α) :=
traverse id
end Functions
/-- A traversable functor is lawful if its `traverse` satisfies a
number of additional properties. It must send `pure : α → Id α` to `pure`,
send the composition of applicative functors to the composition of the
`traverse` of each, send each function `f` to `fun x ↦ f <$> x`, and
satisfy a naturality condition with respect to applicative
transformations. -/
class LawfulTraversable (t : Type u → Type u) [Traversable t] : Prop extends LawfulFunctor t where
/-- `traverse` plays well with `pure` of the identity monad -/
id_traverse : ∀ {α} (x : t α), traverse (pure : α → Id α) x = pure x
/-- `traverse` plays well with composition of applicative functors. -/
comp_traverse :
∀ {F G} [Applicative F] [Applicative G] [LawfulApplicative F] [LawfulApplicative G] {α β γ}
(f : β → F γ) (g : α → G β) (x : t α),
traverse (Functor.Comp.mk ∘ map f ∘ g) x = Comp.mk (map (traverse f) (traverse g x))
/-- An axiom for `traverse` involving `pure : β → Id β`. -/
traverse_eq_map_id : ∀ {α β} (f : α → β) (x : t α),
traverse ((pure : β → Id β) ∘ f) x = pure (f <$> x)
/-- The naturality axiom explaining how lawful traversable functors should play with
lawful applicative functors. -/
naturality :
∀ {F G} [Applicative F] [Applicative G] [LawfulApplicative F] [LawfulApplicative G]
(η : ApplicativeTransformation F G) {α β} (f : α → F β) (x : t α),
η (traverse f x) = traverse (@η _ ∘ f) x
instance : Traversable Id :=
⟨id⟩
instance : LawfulTraversable Id where
id_traverse _ := rfl
comp_traverse _ _ _ := rfl
traverse_eq_map_id _ _ := rfl
naturality _ _ _ _ _ := rfl
section
instance : Traversable Option :=
⟨Option.traverse⟩
instance : Traversable List :=
⟨List.traverse⟩
end
namespace Sum
variable {σ : Type u}
variable {F : Type u → Type u}
variable [Applicative F]
/-- Defines a `traverse` function on the second component of a sum type.
This is used to give a `Traversable` instance for the functor `σ ⊕ -`. -/
protected def traverse {α β} (f : α → F β) : σ ⊕ α → F (σ ⊕ β)
| Sum.inl x => pure (Sum.inl x)
| Sum.inr x => Sum.inr <$> f x
end Sum
instance {σ : Type u} : Traversable.{u} (Sum σ) :=
⟨@Sum.traverse _⟩ |
.lake/packages/mathlib/Mathlib/Control/Traversable/Equiv.lean | import Mathlib.Control.Traversable.Lemmas
import Mathlib.Logic.Equiv.Defs
import Batteries.Tactic.SeqFocus
/-!
# Transferring `Traversable` instances along isomorphisms
This file allows to transfer `Traversable` instances along isomorphisms.
## Main declarations
* `Equiv.map`: Turns functorially a function `α → β` into a function `t' α → t' β` using the functor
`t` and the equivalence `Π α, t α ≃ t' α`.
* `Equiv.functor`: `Equiv.map` as a functor.
* `Equiv.traverse`: Turns traversably a function `α → m β` into a function `t' α → m (t' β)` using
the traversable functor `t` and the equivalence `Π α, t α ≃ t' α`.
* `Equiv.traversable`: `Equiv.traverse` as a traversable functor.
* `Equiv.isLawfulTraversable`: `Equiv.traverse` as a lawful traversable functor.
-/
universe u
namespace Equiv
section Functor
variable {t t' : Type u → Type u} (eqv : ∀ α, t α ≃ t' α)
variable [Functor t]
open Functor
/-- Given a functor `t`, a function `t' : Type u → Type u`, and
equivalences `t α ≃ t' α` for all `α`, then every function `α → β` can
be mapped to a function `t' α → t' β` functorially (see
`Equiv.functor`). -/
protected def map {α β : Type u} (f : α → β) (x : t' α) : t' β :=
eqv β <| map f ((eqv α).symm x)
/-- The function `Equiv.map` transfers the functoriality of `t` to
`t'` using the equivalences `eqv`. -/
protected def functor : Functor t' where map := Equiv.map eqv
variable [LawfulFunctor t]
protected theorem id_map {α : Type u} (x : t' α) : Equiv.map eqv id x = x := by
simp [Equiv.map, id_map]
protected theorem comp_map {α β γ : Type u} (g : α → β) (h : β → γ) (x : t' α) :
Equiv.map eqv (h ∘ g) x = Equiv.map eqv h (Equiv.map eqv g x) := by
simp [Equiv.map, Function.comp_def]
protected theorem lawfulFunctor : @LawfulFunctor _ (Equiv.functor eqv) :=
-- Add the instance to the local context (since `Equiv.functor` is not an instance).
-- Although it can be found by unification, Lean prefers to synthesize instances and
-- then check that they are defeq to the instance found by unification.
let _inst := Equiv.functor eqv
{ map_const := fun {_ _} => rfl
id_map := Equiv.id_map eqv
comp_map := Equiv.comp_map eqv }
protected theorem lawfulFunctor' [F : Functor t']
(h₀ : ∀ {α β} (f : α → β), Functor.map f = Equiv.map eqv f)
(h₁ : ∀ {α β} (f : β), Functor.mapConst f = (Equiv.map eqv ∘ Function.const α) f) :
LawfulFunctor t' := by
have : F = Equiv.functor eqv := by
cases F
dsimp [Equiv.functor]
congr <;> ext <;> dsimp only <;> [rw [← h₀]; rw [← h₁]] <;> rfl
subst this
exact Equiv.lawfulFunctor eqv
end Functor
section Traversable
variable {t t' : Type u → Type u} (eqv : ∀ α, t α ≃ t' α)
variable [Traversable t]
variable {m : Type u → Type u} [Applicative m]
variable {α β : Type u}
/-- Like `Equiv.map`, a function `t' : Type u → Type u` can be given
the structure of a traversable functor using a traversable functor
`t'` and equivalences `t α ≃ t' α` for all α. See `Equiv.traversable`. -/
protected def traverse (f : α → m β) (x : t' α) : m (t' β) :=
eqv β <$> traverse f ((eqv α).symm x)
theorem traverse_def (f : α → m β) (x : t' α) :
Equiv.traverse eqv f x = eqv β <$> traverse f ((eqv α).symm x) :=
rfl
/-- The function `Equiv.traverse` transfers a traversable functor
instance across the equivalences `eqv`. -/
protected def traversable : Traversable t' where
toFunctor := Equiv.functor eqv
traverse := Equiv.traverse eqv
end Traversable
section Equiv
variable {t t' : Type u → Type u} (eqv : ∀ α, t α ≃ t' α)
-- Is this to do with the fact it lives in `Type (u+1)` not `Prop`?
variable [Traversable t] [LawfulTraversable t]
variable {F G : Type u → Type u} [Applicative F] [Applicative G]
variable [LawfulApplicative F] [LawfulApplicative G]
variable (η : ApplicativeTransformation F G)
variable {α β γ : Type u}
open LawfulTraversable Functor
protected theorem id_traverse (x : t' α) : Equiv.traverse eqv (pure : α → Id α) x = pure x := by
rw [Equiv.traverse, id_traverse, map_pure, apply_symm_apply]
protected theorem traverse_eq_map_id (f : α → β) (x : t' α) :
Equiv.traverse eqv ((pure : β → Id β) ∘ f) x = pure (Equiv.map eqv f x) := by
simp only [Equiv.traverse, traverse_eq_map_id]; rfl
protected theorem comp_traverse (f : β → F γ) (g : α → G β) (x : t' α) :
Equiv.traverse eqv (Comp.mk ∘ Functor.map f ∘ g) x =
Comp.mk (Equiv.traverse eqv f <$> Equiv.traverse eqv g x) := by
rw [traverse_def, comp_traverse, Comp.map_mk]
simp only [map_map, traverse_def, symm_apply_apply]
protected theorem naturality (f : α → F β) (x : t' α) :
η (Equiv.traverse eqv f x) = Equiv.traverse eqv (@η _ ∘ f) x := by
simp only [Equiv.traverse, functor_norm]
/-- The fact that `t` is a lawful traversable functor carries over the
equivalences to `t'`, with the traversable functor structure given by
`Equiv.traversable`. -/
protected theorem isLawfulTraversable : @LawfulTraversable t' (Equiv.traversable eqv) :=
let _inst := Equiv.traversable eqv
{ toLawfulFunctor := Equiv.lawfulFunctor eqv
id_traverse := Equiv.id_traverse eqv
comp_traverse := Equiv.comp_traverse eqv
traverse_eq_map_id := Equiv.traverse_eq_map_id eqv
naturality := Equiv.naturality eqv }
/-- If the `Traversable t'` instance has the properties that `map`,
`map_const`, and `traverse` are equal to the ones that come from
carrying the traversable functor structure from `t` over the
equivalences, then the fact that `t` is a lawful traversable functor
carries over as well. -/
protected theorem isLawfulTraversable' [Traversable t']
(h₀ : ∀ {α β} (f : α → β), map f = Equiv.map eqv f)
(h₁ : ∀ {α β} (f : β), mapConst f = (Equiv.map eqv ∘ Function.const α) f)
(h₂ : ∀ {F : Type u → Type u} [Applicative F],
∀ [LawfulApplicative F] {α β} (f : α → F β), traverse f = Equiv.traverse eqv f) :
LawfulTraversable t' where
-- we can't use the same approach as for `lawful_functor'` because
-- h₂ needs a `LawfulApplicative` assumption
toLawfulFunctor := Equiv.lawfulFunctor' eqv @h₀ @h₁
id_traverse _ := by rw [h₂, Equiv.id_traverse]
comp_traverse _ _ _ := by rw [h₂, Equiv.comp_traverse, h₂]; congr; rw [h₂]
traverse_eq_map_id _ _ := by rw [h₂, Equiv.traverse_eq_map_id, h₀]
naturality _ _ _ _ _ := by rw [h₂, Equiv.naturality, h₂]
end Equiv
end Equiv |
.lake/packages/mathlib/Mathlib/Control/Bitraversable/Instances.lean | import Mathlib.Control.Bitraversable.Lemmas
import Mathlib.Control.Traversable.Lemmas
/-!
# Bitraversable instances
This file provides `Bitraversable` instances for concrete bifunctors:
* `Prod`
* `Sum`
* `Functor.Const`
* `flip`
* `Function.bicompl`
* `Function.bicompr`
## References
* Hackage: <https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html>
## Tags
traversable bitraversable functor bifunctor applicative
-/
universe u v w
variable {t : Type u → Type u → Type u} [Bitraversable t]
section
variable {F : Type u → Type u} [Applicative F]
/-- The bitraverse function for `α × β`. -/
def Prod.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : α × β → F (α' × β')
| (x, y) => Prod.mk <$> f x <*> f' y
instance : Bitraversable Prod where bitraverse := @Prod.bitraverse
instance : LawfulBitraversable Prod := by
constructor <;> intros <;> casesm _ × _ <;>
simp [bitraverse, Prod.bitraverse, functor_norm] <;> rfl
open Functor
/-- The bitraverse function for `α ⊕ β`. -/
def Sum.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : α ⊕ β → F (α' ⊕ β')
| Sum.inl x => Sum.inl <$> f x
| Sum.inr x => Sum.inr <$> f' x
instance : Bitraversable Sum where bitraverse := @Sum.bitraverse
instance : LawfulBitraversable Sum := by
constructor <;> intros <;> casesm _ ⊕ _ <;>
simp [bitraverse, Sum.bitraverse, functor_norm] <;> rfl
set_option linter.unusedVariables false in
/-- The bitraverse function for `Const`. It throws away the second map. -/
@[nolint unusedArguments]
def Const.bitraverse {F : Type u → Type u} [Applicative F] {α α' β β'} (f : α → F α')
(f' : β → F β') : Const α β → F (Const α' β') :=
f
instance Bitraversable.const : Bitraversable Const where bitraverse := @Const.bitraverse
instance LawfulBitraversable.const : LawfulBitraversable Const := by
constructor <;> intros <;> simp [bitraverse, Const.bitraverse, functor_norm] <;> rfl
/-- The bitraverse function for `flip`. -/
nonrec def flip.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') :
flip t α β → F (flip t α' β') :=
(bitraverse f' f : t β α → F (t β' α'))
instance Bitraversable.flip : Bitraversable (flip t) where bitraverse := @flip.bitraverse t _
open LawfulBitraversable
instance LawfulBitraversable.flip [LawfulBitraversable t] : LawfulBitraversable (flip t) := by
constructor <;> intros <;> casesm LawfulBitraversable t <;> apply_assumption only [*]
open Bitraversable
instance (priority := 10) Bitraversable.traversable {α} : Traversable (t α) where
traverse := @tsnd t _ _
instance (priority := 10) Bitraversable.isLawfulTraversable [LawfulBitraversable t] {α} :
LawfulTraversable (t α) := by
constructor <;> intros <;>
simp [traverse, comp_tsnd, functor_norm]
· simp [tsnd_eq_snd_id, (· <$> ·)]
· simp [tsnd, binaturality, Function.comp_def, functor_norm]
end
open Bifunctor Traversable LawfulTraversable LawfulBitraversable
open Function (bicompl bicompr)
section Bicompl
variable (F G : Type u → Type u) [Traversable F] [Traversable G]
/-- The bitraverse function for `bicompl`. -/
nonrec def Bicompl.bitraverse {m} [Applicative m] {α β α' β'} (f : α → m β) (f' : α' → m β') :
bicompl t F G α α' → m (bicompl t F G β β') :=
(bitraverse (traverse f) (traverse f') : t (F α) (G α') → m _)
instance : Bitraversable (bicompl t F G) where bitraverse := @Bicompl.bitraverse t _ F G _ _
instance [LawfulTraversable F] [LawfulTraversable G] [LawfulBitraversable t] :
LawfulBitraversable (bicompl t F G) := by
constructor <;> intros <;>
simp [bitraverse, Bicompl.bitraverse, bimap, traverse_id, bitraverse_id_id, comp_bitraverse,
functor_norm]
· simp [traverse_eq_map_id', bitraverse_eq_bimap_id]
· dsimp only [bicompl]
simp [binaturality, naturality_pf]
end Bicompl
section Bicompr
variable (F : Type u → Type u) [Traversable F]
/-- The bitraverse function for `bicompr`. -/
nonrec def Bicompr.bitraverse {m} [Applicative m] {α β α' β'} (f : α → m β) (f' : α' → m β') :
bicompr F t α α' → m (bicompr F t β β') :=
(traverse (bitraverse f f') : F (t α α') → m _)
instance : Bitraversable (bicompr F t) where bitraverse := @Bicompr.bitraverse t _ F _
instance [LawfulTraversable F] [LawfulBitraversable t] : LawfulBitraversable (bicompr F t) := by
constructor <;> intros <;>
simp [bitraverse, Bicompr.bitraverse, bitraverse_id_id, functor_norm]
· simp only [bitraverse_eq_bimap_id', traverse_eq_map_id', Function.comp_apply]; rfl
· dsimp only [bicompr]
simp [naturality, binaturality']
end Bicompr |
.lake/packages/mathlib/Mathlib/Control/Bitraversable/Lemmas.lean | import Mathlib.Control.Bitraversable.Basic
/-!
# Bitraversable Lemmas
## Main definitions
* tfst - traverse on first functor argument
* tsnd - traverse on second functor argument
## Lemmas
Combination of
* bitraverse
* tfst
* tsnd
with the applicatives `id` and `comp`
## References
* Hackage: <https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html>
## Tags
traversable bitraversable functor bifunctor applicative
-/
universe u
variable {t : Type u → Type u → Type u} [Bitraversable t]
variable {β : Type u}
namespace Bitraversable
open Functor LawfulApplicative
variable {F G : Type u → Type u} [Applicative F] [Applicative G]
/-- traverse on the first functor argument -/
abbrev tfst {α α'} (f : α → F α') : t α β → F (t α' β) :=
bitraverse f pure
/-- traverse on the second functor argument -/
abbrev tsnd {α α'} (f : α → F α') : t β α → F (t β α') :=
bitraverse pure f
variable [LawfulBitraversable t] [LawfulApplicative F] [LawfulApplicative G]
@[higher_order tfst_id]
theorem id_tfst : ∀ {α β} (x : t α β), tfst (F := Id) pure x = pure x :=
id_bitraverse
@[higher_order tsnd_id]
theorem id_tsnd : ∀ {α β} (x : t α β), tsnd (F := Id) pure x = pure x :=
id_bitraverse
@[higher_order tfst_comp_tfst]
theorem comp_tfst {α₀ α₁ α₂ β} (f : α₀ → F α₁) (f' : α₁ → G α₂) (x : t α₀ β) :
Comp.mk (tfst f' <$> tfst f x) = tfst (Comp.mk ∘ map f' ∘ f) x := by
rw [← comp_bitraverse]
simp only [Function.comp_def, tfst, map_pure, Pure.pure]
@[higher_order tfst_comp_tsnd]
theorem tfst_tsnd {α₀ α₁ β₀ β₁} (f : α₀ → F α₁) (f' : β₀ → G β₁) (x : t α₀ β₀) :
Comp.mk (tfst f <$> tsnd f' x)
= bitraverse (Comp.mk ∘ pure ∘ f) (Comp.mk ∘ map pure ∘ f') x := by
rw [← comp_bitraverse]
simp only [Function.comp_def, map_pure]
@[higher_order tsnd_comp_tfst]
theorem tsnd_tfst {α₀ α₁ β₀ β₁} (f : α₀ → F α₁) (f' : β₀ → G β₁) (x : t α₀ β₀) :
Comp.mk (tsnd f' <$> tfst f x)
= bitraverse (Comp.mk ∘ map pure ∘ f) (Comp.mk ∘ pure ∘ f') x := by
rw [← comp_bitraverse]
simp only [Function.comp_def, map_pure]
@[higher_order tsnd_comp_tsnd]
theorem comp_tsnd {α β₀ β₁ β₂} (g : β₀ → F β₁) (g' : β₁ → G β₂) (x : t α β₀) :
Comp.mk (tsnd g' <$> tsnd g x) = tsnd (Comp.mk ∘ map g' ∘ g) x := by
rw [← comp_bitraverse]
simp only [Function.comp_def, map_pure]
rfl
open Bifunctor Function
@[higher_order]
theorem tfst_eq_fst_id {α α' β} (f : α → α') (x : t α β) :
tfst (F := Id) (pure ∘ f) x = pure (fst f x) := by
apply bitraverse_eq_bimap_id
@[higher_order]
theorem tsnd_eq_snd_id {α β β'} (f : β → β') (x : t α β) :
tsnd (F := Id) (pure ∘ f) x = pure (snd f x) := by
apply bitraverse_eq_bimap_id
attribute [functor_norm] comp_bitraverse comp_tsnd comp_tfst tsnd_comp_tsnd tsnd_comp_tfst
tfst_comp_tsnd tfst_comp_tfst bitraverse_comp bitraverse_id_id tfst_id tsnd_id
end Bitraversable |
.lake/packages/mathlib/Mathlib/Control/Bitraversable/Basic.lean | import Mathlib.Control.Bifunctor
import Mathlib.Control.Traversable.Basic
/-!
# Bitraversable type class
Type class for traversing bifunctors.
Simple examples of `Bitraversable` are `Prod` and `Sum`. A more elaborate example is
to define an a-list as:
```
def AList (key val : Type) := List (key × val)
```
Then we can use `f : key → IO key'` and `g : val → IO val'` to manipulate the `AList`'s key
and value respectively with `Bitraverse f g : AList key val → IO (AList key' val')`.
## Main definitions
* `Bitraversable`: Bare typeclass to hold the `Bitraverse` function.
* `LawfulBitraversable`: Typeclass for the laws of the `Bitraverse` function. Similar to
`LawfulTraversable`.
## References
The concepts and laws are taken from
<https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html>
## Tags
traversable bitraversable iterator functor bifunctor applicative
-/
universe u
/-- Lawless bitraversable bifunctor. This only holds data for the bimap and bitraverse. -/
class Bitraversable (t : Type u → Type u → Type u) extends Bifunctor t where
bitraverse :
∀ {m : Type u → Type u} [Applicative m] {α α' β β'},
(α → m α') → (β → m β') → t α β → m (t α' β')
export Bitraversable (bitraverse)
/-- A bitraversable functor commutes with all applicative functors. -/
def bisequence {t m} [Bitraversable t] [Applicative m] {α β} : t (m α) (m β) → m (t α β) :=
bitraverse id id
open Functor
/-- Bifunctor. This typeclass asserts that a lawless bitraversable bifunctor is lawful. -/
class LawfulBitraversable (t : Type u → Type u → Type u) [Bitraversable t] : Prop
extends LawfulBifunctor t where
id_bitraverse : ∀ {α β} (x : t α β), (bitraverse pure pure x : Id _) = pure x
comp_bitraverse :
∀ {F G} [Applicative F] [Applicative G] [LawfulApplicative F] [LawfulApplicative G]
{α α' β β' γ γ'} (f : β → F γ) (f' : β' → F γ') (g : α → G β) (g' : α' → G β') (x : t α α'),
bitraverse (Comp.mk ∘ map f ∘ g) (Comp.mk ∘ map f' ∘ g') x =
Comp.mk (bitraverse f f' <$> bitraverse g g' x)
bitraverse_eq_bimap_id :
∀ {α α' β β'} (f : α → β) (f' : α' → β') (x : t α α'),
bitraverse (m := Id) (pure ∘ f) (pure ∘ f') x = pure (bimap f f' x)
binaturality :
∀ {F G} [Applicative F] [Applicative G] [LawfulApplicative F] [LawfulApplicative G]
(η : ApplicativeTransformation F G) {α α' β β'} (f : α → F β) (f' : α' → F β') (x : t α α'),
η (bitraverse f f' x) = bitraverse (@η _ ∘ f) (@η _ ∘ f') x
export LawfulBitraversable (id_bitraverse comp_bitraverse bitraverse_eq_bimap_id)
open LawfulBitraversable
attribute [higher_order bitraverse_id_id] id_bitraverse
attribute [higher_order bitraverse_comp] comp_bitraverse
attribute [higher_order] binaturality bitraverse_eq_bimap_id
export LawfulBitraversable (bitraverse_id_id bitraverse_comp) |
.lake/packages/mathlib/Mathlib/Control/Monad/Writer.lean | import Mathlib.Algebra.Group.Defs
import Mathlib.Logic.Equiv.Defs
/-!
# Writer monads
This file introduces monads for managing immutable, appendable state.
Common applications are logging monads where the monad logs messages as the
computation progresses.
## References
- https://hackage.haskell.org/package/mtl-2.2.1/docs/Control-Monad-Writer-Class.html
- [Original Mark P Jones article introducing `Writer`](https://web.cecs.pdx.edu/~mpj/pubs/springschool.html)
-/
universe u v
/-- Adds a writable output of type `ω` to a monad.
The instances on this type assume that either `[Monoid ω]` or `[EmptyCollection ω] [Append ω]`.
Use `WriterT.run` to obtain the final value of this output. -/
def WriterT (ω : Type u) (M : Type u → Type v) (α : Type u) : Type v :=
M (α × ω)
abbrev Writer ω := WriterT ω Id
class MonadWriter (ω : outParam (Type u)) (M : Type u → Type v) where
/-- Emit an output `w`. -/
tell (w : ω) : M PUnit
/-- Capture the output produced by `f`, without intercepting. -/
listen {α} (f : M α) : M (α × ω)
/-- Buffer the output produced by `f` as `w`, then emit `(← f).2 w` in its place. -/
pass {α} (f : M (α × (ω → ω))) : M α
export MonadWriter (tell listen pass)
variable {M : Type u → Type v} {α ω ρ σ : Type u}
instance [MonadWriter ω M] : MonadWriter ω (ReaderT ρ M) where
tell w := (tell w : M _)
listen x r := listen <| x r
pass x r := pass <| x r
instance [Monad M] [MonadWriter ω M] : MonadWriter ω (StateT σ M) where
tell w := (tell w : M _)
listen x s := (fun ((a,w), s) ↦ ((a,s), w)) <$> listen (x s)
pass x s := pass <| (fun ((a, f), s) ↦ ((a, s), f)) <$> (x s)
namespace WriterT
@[inline]
protected def mk {ω : Type u} (cmd : M (α × ω)) : WriterT ω M α := cmd
@[inline]
protected def run {ω : Type u} (cmd : WriterT ω M α) : M (α × ω) := cmd
@[inline]
protected def runThe (ω : Type u) (cmd : WriterT ω M α) : M (α × ω) := cmd
@[ext]
protected theorem ext {ω : Type u} (x x' : WriterT ω M α) (h : x.run = x'.run) : x = x' := h
variable [Monad M]
/-- Creates an instance of `Monad`, with explicitly given `empty` and `append` operations.
Previously, this would have used an instance of `[Monoid ω]` as input.
In practice, however, `WriterT` is used for logging and creating lists so restricting to
monoids with `Mul` and `One` can make `WriterT` cumbersome to use.
This is used to derive instances for both `[EmptyCollection ω] [Append ω]` and `[Monoid ω]`.
-/
@[reducible, inline]
def monad (empty : ω) (append : ω → ω → ω) : Monad (WriterT ω M) where
map := fun f (cmd : M _) ↦ WriterT.mk <| (fun (a,w) ↦ (f a, w)) <$> cmd
pure := fun a ↦ pure (f := M) (a, empty)
bind := fun (cmd : M _) f ↦
WriterT.mk <| cmd >>= fun (a, w₁) ↦
(fun (b, w₂) ↦ (b, append w₁ w₂)) <$> (f a)
/-- Lift an `M` to a `WriterT ω M`, using the given `empty` as the monoid unit. -/
@[inline]
protected def liftTell (empty : ω) : MonadLift M (WriterT ω M) where
monadLift := fun cmd ↦ WriterT.mk <| (fun a ↦ (a, empty)) <$> cmd
instance [EmptyCollection ω] [Append ω] : Monad (WriterT ω M) := monad ∅ (· ++ ·)
instance [EmptyCollection ω] : MonadLift M (WriterT ω M) := WriterT.liftTell ∅
instance [Monoid ω] : Monad (WriterT ω M) := monad 1 (· * ·)
instance [Monoid ω] : MonadLift M (WriterT ω M) := WriterT.liftTell 1
instance [Monoid ω] [LawfulMonad M] : LawfulMonad (WriterT ω M) := LawfulMonad.mk'
(bind_pure_comp := by
simp [Bind.bind, Functor.map, Pure.pure, WriterT.mk, bind_pure_comp])
(id_map := by simp [Functor.map, WriterT.mk])
(pure_bind := by simp [Bind.bind, Pure.pure, WriterT.mk])
(bind_assoc := by simp [Bind.bind, mul_assoc, WriterT.mk, ← bind_pure_comp])
instance : MonadWriter ω (WriterT ω M) where
tell := fun w ↦ WriterT.mk <| pure (⟨⟩, w)
listen := fun cmd ↦ WriterT.mk <| (fun (a,w) ↦ ((a,w), w)) <$> cmd
pass := fun cmd ↦ WriterT.mk <| (fun ((a,f), w) ↦ (a, f w)) <$> cmd
instance {ε : Type*} [MonadExcept ε M] : MonadExcept ε (WriterT ω M) where
throw := fun e ↦ WriterT.mk <| throw e
tryCatch := fun cmd c ↦ WriterT.mk <| tryCatch cmd fun e ↦ (c e).run
instance [MonadLiftT M (WriterT ω M)] : MonadControl M (WriterT ω M) where
stM := fun α ↦ α × ω
liftWith f := liftM <| f fun x ↦ x.run
restoreM := WriterT.mk
instance : MonadFunctor M (WriterT ω M) where
monadMap := fun k (w : M _) ↦ WriterT.mk <| k w
@[inline] protected def adapt {ω' : Type u} {α : Type u} (f : ω → ω') :
WriterT ω M α → WriterT ω' M α :=
fun cmd ↦ WriterT.mk <| Prod.map id f <$> cmd
end WriterT
/-- Adapt a monad stack, changing the type of its top-most environment.
This class is comparable to [Control.Lens.Magnify](https://hackage.haskell.org/package/lens-4.15.4/docs/Control-Lens-Zoom.html#t:Magnify),
but does not use lenses (why would it), and is derived automatically for any transformer
implementing `MonadFunctor`.
-/
class MonadWriterAdapter (ω : outParam (Type u)) (m : Type u → Type v) where
adaptWriter {α : Type u} : (ω → ω) → m α → m α
export MonadWriterAdapter (adaptWriter)
variable {m : Type u → Type*}
/-- Transitivity.
see Note [lower instance priority] -/
instance (priority := 100) monadWriterAdapterTrans {n : Type u → Type v}
[MonadWriterAdapter ω m] [MonadFunctor m n] : MonadWriterAdapter ω n where
adaptWriter f := monadMap (fun {α} ↦ (adaptWriter f : m α → m α))
instance [Monad m] : MonadWriterAdapter ω (WriterT ω m) where
adaptWriter := WriterT.adapt
universe u₀ u₁ v₀ v₁ in
/-- reduce the equivalence between two writer monads to the equivalence between
their underlying monad -/
def WriterT.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁}
{α₁ ω₁ : Type u₀} {α₂ ω₂ : Type u₁} (F : (m₁ (α₁ × ω₁)) ≃ (m₂ (α₂ × ω₂))) :
WriterT ω₁ m₁ α₁ ≃ WriterT ω₂ m₂ α₂ where
toFun (f : m₁ _) := WriterT.mk <| F f
invFun (f : m₂ _) := WriterT.mk <| F.symm f
left_inv (f : m₁ _) := congr_arg WriterT.mk <| F.left_inv f
right_inv (f : m₂ _) := congr_arg WriterT.mk <| F.right_inv f |
.lake/packages/mathlib/Mathlib/Control/Monad/Basic.lean | import Mathlib.Logic.Equiv.Defs
/-!
# Monad
## Attributes
* ext
* functor_norm
* monad_norm
## Implementation Details
Set of rewrite rules and automation for monads in general and
`ReaderT`, `StateT`, `ExceptT` and `OptionT` in particular.
The rewrite rules for monads are carefully chosen so that `simp with functor_norm`
will not introduce monadic vocabulary in a context where
applicatives would do just fine but will handle monadic notation
already present in an expression.
In a context where monadic reasoning is desired `simp with monad_norm`
will translate functor and applicative notation into monad notation
and use regular `functor_norm` rules as well.
## Tags
functor, applicative, monad, simp
-/
universe u v
variable {α β σ : Type u}
attribute [ext] ReaderT.ext StateT.ext ExceptT.ext
@[monad_norm]
theorem map_eq_bind_pure_comp (m : Type u → Type v) [Monad m] [LawfulMonad m]
(f : α → β) (x : m α) : f <$> x = x >>= pure ∘ f :=
(bind_pure_comp f x).symm
/-- run a `StateT` program and discard the final state -/
def StateT.eval {m : Type u → Type v} [Functor m] (cmd : StateT σ m α) (s : σ) : m α :=
Prod.fst <$> cmd.run s
universe u₀ u₁ v₀ v₁
/-- reduce the equivalence between two state monads to the equivalence between
their respective function spaces -/
def StateT.equiv {σ₁ α₁ : Type u₀} {σ₂ α₂ : Type u₁}
{m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁}
(F : (σ₁ → m₁ (α₁ × σ₁)) ≃ (σ₂ → m₂ (α₂ × σ₂))) : StateT σ₁ m₁ α₁ ≃ StateT σ₂ m₂ α₂ :=
F
/-- reduce the equivalence between two reader monads to the equivalence between
their respective function spaces -/
def ReaderT.equiv {ρ₁ α₁ : Type u₀} {ρ₂ α₂ : Type u₁}
{m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁}
(F : (ρ₁ → m₁ α₁) ≃ (ρ₂ → m₂ α₂)) : ReaderT ρ₁ m₁ α₁ ≃ ReaderT ρ₂ m₂ α₂ :=
F |
.lake/packages/mathlib/Mathlib/Control/Monad/Cont.lean | import Mathlib.Control.Monad.Basic
import Mathlib.Control.Monad.Writer
import Mathlib.Control.Lawful
import Batteries.Tactic.Congr
import Batteries.Lean.Except
/-!
# Continuation Monad
Monad encapsulating continuation passing programming style, similar to
Haskell's `Cont`, `ContT` and `MonadCont`:
<https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Cont.html>
<https://hackage.haskell.org/package/transformers-0.6.2.0/docs/Control-Monad-Trans-Cont.html>
-/
universe u v w u₀ u₁ v₀ v₁
structure MonadCont.Label (α : Type w) (m : Type u → Type v) (β : Type u) where
apply : α → m β
def MonadCont.goto {α β} {m : Type u → Type v} (f : MonadCont.Label α m β) (x : α) :=
f.apply x
class MonadCont (m : Type u → Type v) where
callCC : ∀ {α β}, (MonadCont.Label α m β → m α) → m α
open MonadCont
class LawfulMonadCont (m : Type u → Type v) [Monad m] [MonadCont m] : Prop
extends LawfulMonad m where
callCC_bind_right {α ω γ} (cmd : m α) (next : Label ω m γ → α → m ω) :
(callCC fun f => cmd >>= next f) = cmd >>= fun x => callCC fun f => next f x
callCC_bind_left {α} (β) (x : α) (dead : Label α m β → β → m α) :
(callCC fun f : Label α m β => goto f x >>= dead f) = pure x
callCC_dummy {α β} (dummy : m α) : (callCC fun _ : Label α m β => dummy) = dummy
export LawfulMonadCont (callCC_bind_right callCC_bind_left callCC_dummy)
def ContT (r : Type u) (m : Type u → Type v) (α : Type w) :=
(α → m r) → m r
abbrev Cont (r : Type u) (α : Type w) :=
ContT r id α
namespace ContT
export MonadCont (Label goto)
variable {r : Type u} {m : Type u → Type v} {α β : Type w}
def run : ContT r m α → (α → m r) → m r :=
id
def map (f : m r → m r) (x : ContT r m α) : ContT r m α :=
f ∘ x
theorem run_contT_map_contT (f : m r → m r) (x : ContT r m α) : run (map f x) = f ∘ run x :=
rfl
def withContT (f : (β → m r) → α → m r) (x : ContT r m α) : ContT r m β := fun g => x <| f g
theorem run_withContT (f : (β → m r) → α → m r) (x : ContT r m α) :
run (withContT f x) = run x ∘ f :=
rfl
@[ext]
protected theorem ext {x y : ContT r m α} (h : ∀ f, x.run f = y.run f) : x = y := by
unfold ContT; ext; apply h
instance : Monad (ContT r m) where
pure x f := f x
bind x f g := x fun i => f i g
instance : LawfulMonad (ContT r m) := LawfulMonad.mk'
(id_map := by intros; rfl)
(pure_bind := by intros; ext; rfl)
(bind_assoc := by intros; ext; rfl)
def monadLift [Monad m] {α} : m α → ContT r m α := fun x f => x >>= f
instance [Monad m] : MonadLift m (ContT r m) where
monadLift := ContT.monadLift
theorem monadLift_bind [Monad m] [LawfulMonad m] {α β} (x : m α) (f : α → m β) :
(monadLift (x >>= f) : ContT r m β) = monadLift x >>= monadLift ∘ f := by
ext
simp only [monadLift, (· ∘ ·), (· >>= ·), bind_assoc, id, run,
ContT.monadLift]
instance : MonadCont (ContT r m) where
callCC f g := f ⟨fun x _ => g x⟩ g
instance : LawfulMonadCont (ContT r m) where
callCC_bind_right := by intros; ext; rfl
callCC_bind_left := by intros; ext; rfl
callCC_dummy := by intros; ext; rfl
/-- Note that `tryCatch` does not have correct behavior in this monad:
```
def foo : ContT Bool (Except String) Bool := do
let x ← try
pure true
catch _ =>
return false
throw s!"oh no {x}"
#eval foo.run pure
-- `Except.ok false`, no error
```
Here, the `throwError` is being run inside the `try`.
See [Zulip](https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/MonadExcept.20in.20the.20ContT.20monad/near/375341221)
for further discussion.
-/
instance (ε) [MonadExcept ε m] : MonadExcept ε (ContT r m) where
throw e _ := throw e
tryCatch act h f := tryCatch (act f) fun e => h e f
end ContT
variable {m : Type u → Type v}
section
variable [Monad m]
def ExceptT.mkLabel {α β ε} : Label (Except.{u, u} ε α) m β → Label α (ExceptT ε m) β
| ⟨f⟩ => ⟨fun a => monadLift <| f (Except.ok a)⟩
theorem ExceptT.goto_mkLabel {α β ε : Type _} (x : Label (Except.{u, u} ε α) m β) (i : α) :
goto (ExceptT.mkLabel x) i = ExceptT.mk (Except.ok <$> goto x (Except.ok i)) := by
cases x; rfl
nonrec def ExceptT.callCC {ε} [MonadCont m] {α β : Type _}
(f : Label α (ExceptT ε m) β → ExceptT ε m α) : ExceptT ε m α :=
ExceptT.mk (callCC fun x : Label _ m β => ExceptT.run <| f (ExceptT.mkLabel x))
instance {ε} [MonadCont m] : MonadCont (ExceptT ε m) where
callCC := ExceptT.callCC
instance {ε} [MonadCont m] [LawfulMonadCont m] : LawfulMonadCont (ExceptT ε m) where
callCC_bind_right := by
intros; simp only [callCC, ExceptT.callCC, ExceptT.run_bind, callCC_bind_right]; ext
dsimp
congr with ⟨⟩ <;> simp [@callCC_dummy m _]
callCC_bind_left := by
intros
simp only [callCC, ExceptT.callCC, ExceptT.goto_mkLabel, map_eq_bind_pure_comp, Function.comp,
ExceptT.run_bind, ExceptT.run_mk, bind_assoc, pure_bind, @callCC_bind_left m _]
ext; rfl
callCC_dummy := by intros; simp only [callCC, ExceptT.callCC, @callCC_dummy m _]; ext; rfl
def OptionT.mkLabel {α β} : Label (Option.{u} α) m β → Label α (OptionT m) β
| ⟨f⟩ => ⟨fun a => monadLift <| f (some a)⟩
theorem OptionT.goto_mkLabel {α β : Type _} (x : Label (Option.{u} α) m β) (i : α) :
goto (OptionT.mkLabel x) i = OptionT.mk (goto x (some i) >>= fun a => pure (some a)) :=
rfl
nonrec def OptionT.callCC [MonadCont m] {α β : Type _} (f : Label α (OptionT m) β → OptionT m α) :
OptionT m α :=
OptionT.mk (callCC fun x : Label _ m β => OptionT.run <| f (OptionT.mkLabel x) : m (Option α))
@[simp]
lemma run_callCC [MonadCont m] {α β : Type _} (f : Label α (OptionT m) β → OptionT m α) :
(OptionT.callCC f).run = (callCC fun x => OptionT.run <| f (OptionT.mkLabel x)) := rfl
instance [MonadCont m] : MonadCont (OptionT m) where
callCC := OptionT.callCC
instance [MonadCont m] [LawfulMonadCont m] : LawfulMonadCont (OptionT m) where
callCC_bind_right := by
refine fun _ _ => OptionT.ext ?_
simpa [callCC, Option.elimM, callCC_bind_right] using
bind_congr fun | some _ => rfl | none => by simp [@callCC_dummy m _]
callCC_bind_left := by
intros
ext
simp [callCC, OptionT.goto_mkLabel, @callCC_bind_left m _]
callCC_dummy := by intros; ext; simp [callCC, OptionT.callCC, @callCC_dummy m _]
def WriterT.mkLabel {α β ω} [EmptyCollection ω] : Label (α × ω) m β → Label α (WriterT ω m) β
| ⟨f⟩ => ⟨fun a => monadLift <| f (a, ∅)⟩
def WriterT.mkLabel' {α β ω} [Monoid ω] : Label (α × ω) m β → Label α (WriterT ω m) β
| ⟨f⟩ => ⟨fun a => monadLift <| f (a, 1)⟩
theorem WriterT.goto_mkLabel {α β ω : Type _} [EmptyCollection ω] (x : Label (α × ω) m β) (i : α) :
goto (WriterT.mkLabel x) i = monadLift (goto x (i, ∅)) := by cases x; rfl
theorem WriterT.goto_mkLabel' {α β ω : Type _} [Monoid ω] (x : Label (α × ω) m β) (i : α) :
goto (WriterT.mkLabel' x) i = monadLift (goto x (i, 1)) := by cases x; rfl
nonrec def WriterT.callCC [MonadCont m] {α β ω : Type _} [EmptyCollection ω]
(f : Label α (WriterT ω m) β → WriterT ω m α) : WriterT ω m α :=
WriterT.mk <| callCC (WriterT.run ∘ f ∘ WriterT.mkLabel : Label (α × ω) m β → m (α × ω))
def WriterT.callCC' [MonadCont m] {α β ω : Type _} [Monoid ω]
(f : Label α (WriterT ω m) β → WriterT ω m α) : WriterT ω m α :=
WriterT.mk <|
MonadCont.callCC (WriterT.run ∘ f ∘ WriterT.mkLabel' : Label (α × ω) m β → m (α × ω))
end
instance (ω) [Monad m] [EmptyCollection ω] [MonadCont m] : MonadCont (WriterT ω m) where
callCC := WriterT.callCC
instance (ω) [Monad m] [Monoid ω] [MonadCont m] : MonadCont (WriterT ω m) where
callCC := WriterT.callCC'
def StateT.mkLabel {α β σ : Type u} : Label (α × σ) m (β × σ) → Label α (StateT σ m) β
| ⟨f⟩ => ⟨fun a => StateT.mk (fun s => f (a, s))⟩
theorem StateT.goto_mkLabel {α β σ : Type u} (x : Label (α × σ) m (β × σ)) (i : α) :
goto (StateT.mkLabel x) i = StateT.mk (fun s => goto x (i, s)) := by cases x; rfl
nonrec def StateT.callCC {σ} [MonadCont m] {α β : Type _}
(f : Label α (StateT σ m) β → StateT σ m α) : StateT σ m α :=
StateT.mk (fun r => callCC fun f' => (f <| StateT.mkLabel f').run r)
instance {σ} [MonadCont m] : MonadCont (StateT σ m) where
callCC := StateT.callCC
instance {σ} [Monad m] [MonadCont m] [LawfulMonadCont m] : LawfulMonadCont (StateT σ m) where
callCC_bind_right := by
intros
simp only [callCC, StateT.callCC, StateT.run_bind, callCC_bind_right]; ext; rfl
callCC_bind_left := by
intros
simp only [callCC, StateT.callCC, StateT.goto_mkLabel, StateT.run_bind, StateT.run_mk,
callCC_bind_left]; ext; rfl
callCC_dummy := by
intros
simp only [callCC, StateT.callCC, @callCC_dummy m _]
ext; rfl
def ReaderT.mkLabel {α β} (ρ) : Label α m β → Label α (ReaderT ρ m) β
| ⟨f⟩ => ⟨monadLift ∘ f⟩
theorem ReaderT.goto_mkLabel {α ρ β} (x : Label α m β) (i : α) :
goto (ReaderT.mkLabel ρ x) i = monadLift (goto x i) := by cases x; rfl
nonrec def ReaderT.callCC {ε} [MonadCont m] {α β : Type _}
(f : Label α (ReaderT ε m) β → ReaderT ε m α) : ReaderT ε m α :=
ReaderT.mk (fun r => callCC fun f' => (f <| ReaderT.mkLabel _ f').run r)
instance {ρ} [MonadCont m] : MonadCont (ReaderT ρ m) where
callCC := ReaderT.callCC
instance {ρ} [Monad m] [MonadCont m] [LawfulMonadCont m] : LawfulMonadCont (ReaderT ρ m) where
callCC_bind_right := by intros; simp only [callCC, ReaderT.callCC, ReaderT.run_bind,
callCC_bind_right]; ext; rfl
callCC_bind_left := by
intros; simp only [callCC, ReaderT.callCC, ReaderT.goto_mkLabel, ReaderT.run_bind,
ReaderT.run_monadLift, monadLift_self, callCC_bind_left]
ext; rfl
callCC_dummy := by intros; simp only [callCC, ReaderT.callCC, @callCC_dummy m _]; ext; rfl
/-- reduce the equivalence between two continuation passing monads to the equivalence between
their underlying monad -/
def ContT.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} {α₁ r₁ : Type u₀}
{α₂ r₂ : Type u₁} (F : m₁ r₁ ≃ m₂ r₂) (G : α₁ ≃ α₂) : ContT r₁ m₁ α₁ ≃ ContT r₂ m₂ α₂ where
toFun f r := F <| f fun x => F.symm <| r <| G x
invFun f r := F.symm <| f fun x => F <| r <| G.symm x
left_inv f := by funext r; simp
right_inv f := by funext r; simp |
.lake/packages/mathlib/Mathlib/Control/EquivFunctor/Instances.lean | import Mathlib.Control.EquivFunctor
import Mathlib.Data.Fintype.OfMap
/-!
# `EquivFunctor` instances
We derive some `EquivFunctor` instances, to enable `equiv_rw` to rewrite under these functions.
-/
open Equiv
instance EquivFunctorUnique : EquivFunctor Unique where
map e := Equiv.uniqueCongr e
map_refl' α := by simp [eq_iff_true_of_subsingleton]
map_trans' := by simp [eq_iff_true_of_subsingleton]
instance EquivFunctorPerm : EquivFunctor Perm where
map e p := (e.symm.trans p).trans e
map_refl' α := by ext; simp
map_trans' _ _ := by ext; simp
-- There is a classical instance of `LawfulFunctor Finset` available,
-- but we provide this computable alternative separately.
instance EquivFunctorFinset : EquivFunctor Finset where
map e s := s.map e.toEmbedding
map_refl' α := by ext; simp
map_trans' k h := by
ext _ a; simp; constructor <;> intro h'
· let ⟨a, ha₁, ha₂⟩ := h'
rw [← ha₂]; simpa
· exists (Equiv.symm k) ((Equiv.symm h) a)
simp [h']
instance EquivFunctorFintype : EquivFunctor Fintype where
map e _ := Fintype.ofBijective e e.bijective
map_refl' α := by ext; simp [eq_iff_true_of_subsingleton]
map_trans' := by simp [eq_iff_true_of_subsingleton] |
.lake/packages/mathlib/Mathlib/Computability/PostTuringMachine.lean | import Mathlib.Computability.Tape
import Mathlib.Data.Finset.Prod
import Mathlib.Data.Finset.Option
import Mathlib.Data.Fintype.Defs
import Mathlib.Data.PFun
/-!
# Turing machines
The files `PostTuringMachine.lean` and `TuringMachine.lean` define
a sequence of simple machine languages, starting with Turing machines and working
up to more complex languages based on Wang B-machines.
`PostTuringMachine.lean` covers the TM0 model and TM1 model;
`TuringMachine.lean` adds the TM2 model.
## Naming conventions
Each model of computation in this file shares a naming convention for the elements of a model of
computation. These are the parameters for the language:
* `Γ` is the alphabet on the tape.
* `Λ` is the set of labels, or internal machine states.
* `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and
later models achieve this by mixing it into `Λ`.
* `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks.
All of these variables denote "essentially finite" types, but for technical reasons it is
convenient to allow them to be infinite anyway. When using an infinite type, we will be interested
in proving that only finitely many values of the type are ever interacted with.
Given these parameters, there are a few common structures for the model that arise:
* `Stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is
finite, and for later models it is an infinite inductive type representing "possible program
texts".
* `Cfg` is the set of instantaneous configurations, that is, the state of the machine together with
its environment.
* `Machine` is the set of all machines in the model. Usually this is approximately a function
`Λ → Stmt`, although different models have different ways of halting and other actions.
* `step : Cfg → Option Cfg` is the function that describes how the state evolves over one step.
If `step c = none`, then `c` is a terminal state, and the result of the computation is read off
from `c`. Because of the type of `step`, these models are all deterministic by construction.
* `init : Input → Cfg` sets up the initial state. The type `Input` depends on the model;
in most cases it is `List Γ`.
* `eval : Machine → Input → Part Output`, given a machine `M` and input `i`, starts from
`init i`, runs `step` until it reaches an output, and then applies a function `Cfg → Output` to
the final state to obtain the result. The type `Output` depends on the model.
* `Supports : Machine → Finset Λ → Prop` asserts that a machine `M` starts in `S : Finset Λ`, and
can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input
cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when
convenient, and prove that only finitely many of these states are actually accessible. This
formalizes "essentially finite" mentioned above.
-/
assert_not_exists MonoidWithZero
open List (Vector)
open Relation
open Nat (iterate)
open Function (update iterate_succ iterate_succ_apply iterate_succ' iterate_succ_apply'
iterate_zero_apply)
namespace Turing
/-- Run a state transition function `σ → Option σ` "to completion". The return value is the last
state returned before a `none` result. If the state transition function always returns `some`,
then the computation diverges, returning `Part.none`. -/
def eval {σ} (f : σ → Option σ) : σ → Part σ :=
PFun.fix fun s ↦ Part.some <| (f s).elim (Sum.inl s) Sum.inr
/-- The reflexive transitive closure of a state transition function. `Reaches f a b` means
there is a finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`.
This relation permits zero steps of the state transition function. -/
def Reaches {σ} (f : σ → Option σ) : σ → σ → Prop :=
ReflTransGen fun a b ↦ b ∈ f a
/-- The transitive closure of a state transition function. `Reaches₁ f a b` means there is a
nonempty finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`.
This relation does not permit zero steps of the state transition function. -/
def Reaches₁ {σ} (f : σ → Option σ) : σ → σ → Prop :=
TransGen fun a b ↦ b ∈ f a
theorem reaches₁_eq {σ} {f : σ → Option σ} {a b c} (h : f a = f b) :
Reaches₁ f a c ↔ Reaches₁ f b c :=
TransGen.head'_iff.trans (TransGen.head'_iff.trans <| by rw [h]).symm
theorem reaches_total {σ} {f : σ → Option σ} {a b c} (hab : Reaches f a b) (hac : Reaches f a c) :
Reaches f b c ∨ Reaches f c b :=
ReflTransGen.total_of_right_unique (fun _ _ _ ↦ Option.mem_unique) hab hac
theorem reaches₁_fwd {σ} {f : σ → Option σ} {a b c} (h₁ : Reaches₁ f a c) (h₂ : b ∈ f a) :
Reaches f b c := by
rcases TransGen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩
cases Option.mem_unique hab h₂; exact hbc
/-- A variation on `Reaches`. `Reaches₀ f a b` holds if whenever `Reaches₁ f b c` then
`Reaches₁ f a c`. This is a weaker property than `Reaches` and is useful for replacing states with
equivalent states without taking a step. -/
def Reaches₀ {σ} (f : σ → Option σ) (a b : σ) : Prop :=
∀ c, Reaches₁ f b c → Reaches₁ f a c
theorem Reaches₀.trans {σ} {f : σ → Option σ} {a b c : σ} (h₁ : Reaches₀ f a b)
(h₂ : Reaches₀ f b c) : Reaches₀ f a c
| _, h₃ => h₁ _ (h₂ _ h₃)
@[refl]
theorem Reaches₀.refl {σ} {f : σ → Option σ} (a : σ) : Reaches₀ f a a
| _, h => h
theorem Reaches₀.single {σ} {f : σ → Option σ} {a b : σ} (h : b ∈ f a) : Reaches₀ f a b
| _, h₂ => h₂.head h
theorem Reaches₀.head {σ} {f : σ → Option σ} {a b c : σ} (h : b ∈ f a) (h₂ : Reaches₀ f b c) :
Reaches₀ f a c :=
(Reaches₀.single h).trans h₂
theorem Reaches₀.tail {σ} {f : σ → Option σ} {a b c : σ} (h₁ : Reaches₀ f a b) (h : c ∈ f b) :
Reaches₀ f a c :=
h₁.trans (Reaches₀.single h)
theorem reaches₀_eq {σ} {f : σ → Option σ} {a b} (e : f a = f b) : Reaches₀ f a b
| _, h => (reaches₁_eq e).2 h
theorem Reaches₁.to₀ {σ} {f : σ → Option σ} {a b : σ} (h : Reaches₁ f a b) : Reaches₀ f a b
| _, h₂ => h.trans h₂
theorem Reaches.to₀ {σ} {f : σ → Option σ} {a b : σ} (h : Reaches f a b) : Reaches₀ f a b
| _, h₂ => h₂.trans_right h
theorem Reaches₀.tail' {σ} {f : σ → Option σ} {a b c : σ} (h : Reaches₀ f a b) (h₂ : c ∈ f b) :
Reaches₁ f a c :=
h _ (TransGen.single h₂)
/-- (co-)Induction principle for `eval`. If a property `C` holds of any point `a` evaluating to `b`
which is either terminal (meaning `a = b`) or where the next point also satisfies `C`, then it
holds of any point where `eval f a` evaluates to `b`. This formalizes the notion that if
`eval f a` evaluates to `b` then it reaches terminal state `b` in finitely many steps. -/
@[elab_as_elim]
def evalInduction {σ} {f : σ → Option σ} {b : σ} {C : σ → Sort*} {a : σ}
(h : b ∈ eval f a) (H : ∀ a, b ∈ eval f a → (∀ a', f a = some a' → C a') → C a) : C a :=
PFun.fixInduction h fun a' ha' h' ↦
H _ ha' fun b' e ↦ h' _ <| Part.mem_some_iff.2 <| by rw [e]; rfl
theorem mem_eval {σ} {f : σ → Option σ} {a b} : b ∈ eval f a ↔ Reaches f a b ∧ f b = none := by
refine ⟨fun h ↦ ?_, fun ⟨h₁, h₂⟩ ↦ ?_⟩
· refine evalInduction h fun a h IH ↦ ?_
rcases e : f a with - | a'
· rw [Part.mem_unique h
(PFun.mem_fix_iff.2 <| Or.inl <| Part.mem_some_iff.2 <| by rw [e]; rfl)]
exact ⟨ReflTransGen.refl, e⟩
· rcases PFun.mem_fix_iff.1 h with (h | ⟨_, h, _⟩) <;> rw [e] at h <;>
cases Part.mem_some_iff.1 h
obtain ⟨h₁, h₂⟩ := IH a' e
exact ⟨ReflTransGen.head e h₁, h₂⟩
· refine ReflTransGen.head_induction_on h₁ ?_ fun h _ IH ↦ ?_
· refine PFun.mem_fix_iff.2 (Or.inl ?_)
rw [h₂]
apply Part.mem_some
· refine PFun.mem_fix_iff.2 (Or.inr ⟨_, ?_, IH⟩)
rw [h]
apply Part.mem_some
theorem eval_maximal₁ {σ} {f : σ → Option σ} {a b} (h : b ∈ eval f a) (c) : ¬Reaches₁ f b c
| bc => by
let ⟨_, b0⟩ := mem_eval.1 h
let ⟨b', h', _⟩ := TransGen.head'_iff.1 bc
cases b0.symm.trans h'
theorem eval_maximal {σ} {f : σ → Option σ} {a b} (h : b ∈ eval f a) {c} : Reaches f b c ↔ c = b :=
let ⟨_, b0⟩ := mem_eval.1 h
reflTransGen_iff_eq fun b' h' ↦ by cases b0.symm.trans h'
theorem reaches_eval {σ} {f : σ → Option σ} {a b} (ab : Reaches f a b) : eval f a = eval f b := by
refine Part.ext fun _ ↦ ⟨fun h ↦ ?_, fun h ↦ ?_⟩
· have ⟨ac, c0⟩ := mem_eval.1 h
exact mem_eval.2 ⟨(or_iff_left_of_imp fun cb ↦ (eval_maximal h).1 cb ▸ ReflTransGen.refl).1
(reaches_total ab ac), c0⟩
· have ⟨bc, c0⟩ := mem_eval.1 h
exact mem_eval.2 ⟨ab.trans bc, c0⟩
/-- Given a relation `tr : σ₁ → σ₂ → Prop` between state spaces, and state transition functions
`f₁ : σ₁ → Option σ₁` and `f₂ : σ₂ → Option σ₂`, `Respects f₁ f₂ tr` means that if `tr a₁ a₂` holds
initially and `f₁` takes a step to `a₂` then `f₂` will take one or more steps before reaching a
state `b₂` satisfying `tr a₂ b₂`, and if `f₁ a₁` terminates then `f₂ a₂` also terminates.
Such a relation `tr` is also known as a refinement. -/
def Respects {σ₁ σ₂} (f₁ : σ₁ → Option σ₁) (f₂ : σ₂ → Option σ₂) (tr : σ₁ → σ₂ → Prop) :=
∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with
| some b₁ => ∃ b₂, tr b₁ b₂ ∧ Reaches₁ f₂ a₂ b₂
| none => f₂ a₂ = none : Prop)
theorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : Respects f₁ f₂ tr) {a₁ a₂}
(aa : tr a₁ a₂) {b₁} (ab : Reaches₁ f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ Reaches₁ f₂ a₂ b₂ := by
induction ab with
| single ac =>
have := H aa
rwa [show f₁ a₁ = _ from ac] at this
| @tail c₁ d₁ _ cd IH =>
rcases IH with ⟨c₂, cc, ac₂⟩
have := H cc
rw [show f₁ c₁ = _ from cd] at this
rcases this with ⟨d₂, dd, cd₂⟩
exact ⟨_, dd, ac₂.trans cd₂⟩
theorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : Respects f₁ f₂ tr) {a₁ a₂}
(aa : tr a₁ a₂) {b₁} (ab : Reaches f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ Reaches f₂ a₂ b₂ := by
rcases reflTransGen_iff_eq_or_transGen.1 ab with (rfl | ab)
· exact ⟨_, aa, ReflTransGen.refl⟩
· have ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab
exact ⟨b₂, bb, h.to_reflTransGen⟩
theorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : Respects f₁ f₂ tr) {a₁ a₂}
(aa : tr a₁ a₂) {b₂} (ab : Reaches f₂ a₂ b₂) :
∃ c₁ c₂, Reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ Reaches f₁ a₁ c₁ := by
induction ab with
| refl => exact ⟨_, _, ReflTransGen.refl, aa, ReflTransGen.refl⟩
| tail _ cd IH =>
rcases IH with ⟨e₁, e₂, ce, ee, ae⟩
rcases ReflTransGen.cases_head ce with (rfl | ⟨d', cd', de⟩)
· have := H ee
revert this
rcases eg : f₁ e₁ with - | g₁ <;> simp only [and_imp, exists_imp]
· intro c0
cases cd.symm.trans c0
· intro g₂ gg cg
rcases TransGen.head'_iff.1 cg with ⟨d', cd', dg⟩
cases Option.mem_unique cd cd'
exact ⟨_, _, dg, gg, ae.tail eg⟩
· cases Option.mem_unique cd cd'
exact ⟨_, _, de, ee, ae⟩
theorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : Respects f₁ f₂ tr) {a₁ b₁ a₂}
(aa : tr a₁ a₂) (ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ := by
obtain ⟨ab, b0⟩ := mem_eval.1 ab
rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩
refine ⟨_, bb, mem_eval.2 ⟨ab, ?_⟩⟩
have := H bb; rwa [b0] at this
theorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : Respects f₁ f₂ tr) {a₁ b₂ a₂}
(aa : tr a₁ a₂) (ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ := by
obtain ⟨ab, b0⟩ := mem_eval.1 ab
rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩
cases (reflTransGen_iff_eq (Option.eq_none_iff_forall_not_mem.1 b0)).1 bc
refine ⟨_, cc, mem_eval.2 ⟨ac, ?_⟩⟩
have := H cc
rcases hfc : f₁ c₁ with - | d₁
· rfl
rw [hfc] at this
rcases this with ⟨d₂, _, bd⟩
rcases TransGen.head'_iff.1 bd with ⟨e, h, _⟩
cases b0.symm.trans h
theorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : Respects f₁ f₂ tr) {a₁ a₂}
(aa : tr a₁ a₂) : (eval f₂ a₂).Dom ↔ (eval f₁ a₁).Dom :=
⟨fun h ↦
let ⟨_, _, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩
h,
fun h ↦
let ⟨_, _, h, _⟩ := tr_eval H aa ⟨h, rfl⟩
h⟩
/-- A simpler version of `Respects` when the state transition relation `tr` is a function. -/
def FRespects {σ₁ σ₂} (f₂ : σ₂ → Option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : Option σ₁ → Prop
| some b₁ => Reaches₁ f₂ a₂ (tr b₁)
| none => f₂ a₂ = none
theorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → Option σ₂} {tr : σ₁ → σ₂} {a₂ b₂} (h : f₂ a₂ = f₂ b₂) :
∀ {b₁}, FRespects f₂ tr a₂ b₁ ↔ FRespects f₂ tr b₂ b₁
| some _ => reaches₁_eq h
| none => by unfold FRespects; rw [h]
theorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} :
(Respects f₁ f₂ fun a b ↦ tr a = b) ↔ ∀ ⦃a₁⦄, FRespects f₂ tr (tr a₁) (f₁ a₁) :=
forall_congr' fun a₁ ↦ by
cases f₁ a₁ <;> simp only [FRespects, exists_eq_left', forall_eq']
theorem tr_eval' {σ₁ σ₂} (f₁ : σ₁ → Option σ₁) (f₂ : σ₂ → Option σ₂) (tr : σ₁ → σ₂)
(H : Respects f₁ f₂ fun a b ↦ tr a = b) (a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ :=
Part.ext fun b₂ ↦
⟨fun h ↦
let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h
(Part.mem_map_iff _).2 ⟨b₁, hb, bb⟩,
fun h ↦ by
rcases (Part.mem_map_iff _).1 h with ⟨b₁, ab, bb⟩
rcases tr_eval H rfl ab with ⟨_, rfl, h⟩
rwa [bb] at h⟩
/-!
## The TM0 model
A TM0 Turing machine is essentially a Post-Turing machine, adapted for type theory.
A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function
`Λ → Γ → Option (Λ × Stmt)`, where a `Stmt` can be either `move left`, `move right` or `write a`
for `a : Γ`. The machine works over a "tape", a doubly-infinite sequence of elements of `Γ`, and
an instantaneous configuration, `Cfg`, is a label `q : Λ` indicating the current internal state of
the machine, and a `Tape Γ` (which is essentially `ℤ →₀ Γ`). The evolution is described by the
`step` function:
* If `M q T.head = none`, then the machine halts.
* If `M q T.head = some (q', s)`, then the machine performs action `s : Stmt` and then transitions
to state `q'`.
The initial state takes a `List Γ` and produces a `Tape Γ` where the head of the list is the head
of the tape and the rest of the list extends to the right, with the left side all blank. The final
state takes the entire right side of the tape right or equal to the current position of the
machine. (This is actually a `ListBlank Γ`, not a `List Γ`, because we don't know, at this level
of generality, where the output ends. If equality to `default : Γ` is decidable we can trim the list
to remove the infinite tail of blanks.)
-/
namespace TM0
section
-- type of tape symbols
variable (Γ : Type*)
-- type of "labels" or TM states
variable (Λ : Type*)
/-- A Turing machine "statement" is just a command to either move
left or right, or write a symbol on the tape. -/
inductive Stmt
| move : Dir → Stmt
| write : Γ → Stmt
instance Stmt.inhabited [Inhabited Γ] : Inhabited (Stmt Γ) :=
⟨Stmt.write default⟩
/-- A Post-Turing machine with symbol type `Γ` and label type `Λ`
is a function which, given the current state `q : Λ` and
the tape head `a : Γ`, either halts (returns `none`) or returns
a new state `q' : Λ` and a `Stmt` describing what to do,
either a move left or right, or a write command.
Both `Λ` and `Γ` are required to be inhabited; the default value
for `Γ` is the "blank" tape value, and the default value of `Λ` is
the initial state. -/
@[nolint unusedArguments] -- this is a deliberate addition, see comment
def Machine [Inhabited Λ] :=
Λ → Γ → Option (Λ × (Stmt Γ))
instance Machine.inhabited [Inhabited Λ] : Inhabited (Machine Γ Λ) := by
unfold Machine; infer_instance
/-- The configuration state of a Turing machine during operation
consists of a label (machine state), and a tape.
The tape is represented in the form `(a, L, R)`, meaning the tape looks like `L.rev ++ [a] ++ R`
with the machine currently reading the `a`. The lists are
automatically extended with blanks as the machine moves around. -/
structure Cfg [Inhabited Γ] where
/-- The current machine state. -/
q : Λ
/-- The current state of the tape: current symbol, left and right parts. -/
Tape : Tape Γ
variable {Γ Λ}
variable [Inhabited Λ]
section
variable [Inhabited Γ]
instance Cfg.inhabited : Inhabited (Cfg Γ Λ) := ⟨⟨default, default⟩⟩
/-- Execution semantics of the Turing machine. -/
def step (M : Machine Γ Λ) : Cfg Γ Λ → Option (Cfg Γ Λ) :=
fun ⟨q, T⟩ ↦ (M q T.1).map fun ⟨q', a⟩ ↦ ⟨q', match a with
| Stmt.move d => T.move d
| Stmt.write a => T.write a⟩
/-- The statement `Reaches M s₁ s₂` means that `s₂` is obtained
starting from `s₁` after a finite number of steps. -/
def Reaches (M : Machine Γ Λ) : Cfg Γ Λ → Cfg Γ Λ → Prop := ReflTransGen fun a b ↦ b ∈ step M a
/-- The initial configuration. -/
def init (l : List Γ) : Cfg Γ Λ := ⟨default, Tape.mk₁ l⟩
/-- Evaluate a Turing machine on initial input to a final state,
if it terminates. -/
def eval (M : Machine Γ Λ) (l : List Γ) : Part (ListBlank Γ) :=
(Turing.eval (step M) (init l)).map fun c ↦ c.Tape.right₀
/-- The raw definition of a Turing machine does not require that
`Γ` and `Λ` are finite, and in practice we will be interested
in the infinite `Λ` case. We recover instead a notion of
"effectively finite" Turing machines, which only make use of a
finite subset of their states. We say that a set `S ⊆ Λ`
supports a Turing machine `M` if `S` is closed under the
transition function and contains the initial state. -/
def Supports (M : Machine Γ Λ) (S : Set Λ) :=
default ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S
theorem step_supports (M : Machine Γ Λ) {S : Set Λ} (ss : Supports M S) :
∀ {c c' : Cfg Γ Λ}, c' ∈ step M c → c.q ∈ S → c'.q ∈ S := by
intro ⟨q, T⟩ c' h₁ h₂
rcases Option.map_eq_some_iff.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩
exact ss.2 h h₂
end
theorem univ_supports (M : Machine Γ Λ) : Supports M Set.univ := by
constructor <;> intros <;> apply Set.mem_univ
end
section
variable {Γ : Type*} [Inhabited Γ]
variable {Γ' : Type*} [Inhabited Γ']
variable {Λ : Type*} [Inhabited Λ]
variable {Λ' : Type*} [Inhabited Λ']
/-- Map a TM statement across a function. This does nothing to move statements and maps the write
values. -/
def Stmt.map (f : PointedMap Γ Γ') : Stmt Γ → Stmt Γ'
| Stmt.move d => Stmt.move d
| Stmt.write a => Stmt.write (f a)
/-- Map a configuration across a function, given `f : Γ → Γ'` a map of the alphabets and
`g : Λ → Λ'` a map of the machine states. -/
def Cfg.map (f : PointedMap Γ Γ') (g : Λ → Λ') : Cfg Γ Λ → Cfg Γ' Λ'
| ⟨q, T⟩ => ⟨g q, T.map f⟩
variable (M : Machine Γ Λ) (f₁ : PointedMap Γ Γ') (f₂ : PointedMap Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ)
/-- Because the state transition function uses the alphabet and machine states in both the input
and output, to map a machine from one alphabet and machine state space to another we need functions
in both directions, essentially an `Equiv` without the laws. -/
def Machine.map : Machine Γ' Λ'
| q, l => (M (g₂ q) (f₂ l)).map (Prod.map g₁ (Stmt.map f₁))
theorem Machine.map_step {S : Set Λ} (f₂₁ : Function.RightInverse f₁ f₂)
(g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) :
∀ c : Cfg Γ Λ,
c.q ∈ S → (step M c).map (Cfg.map f₁ g₁) = step (M.map f₁ f₂ g₁ g₂) (Cfg.map f₁ g₁ c)
| ⟨q, T⟩, h => by
unfold step Machine.map Cfg.map
simp only [Turing.Tape.map_fst, g₂₁ q h, f₂₁ _]
rcases M q T.1 with (_ | ⟨q', d | a⟩); · rfl
· simp only [Option.map_some, Tape.map_move f₁]
rfl
· simp only [Option.map_some, Tape.map_write]
rfl
theorem map_init (g₁ : PointedMap Λ Λ') (l : List Γ) : (init l).map f₁ g₁ = init (l.map f₁) :=
congr (congr_arg Cfg.mk g₁.map_pt) (Tape.map_mk₁ _ _)
theorem Machine.map_respects (g₁ : PointedMap Λ Λ') (g₂ : Λ' → Λ) {S} (ss : Supports M S)
(f₂₁ : Function.RightInverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) :
Respects (step M) (step (M.map f₁ f₂ g₁ g₂)) fun a b ↦ a.q ∈ S ∧ Cfg.map f₁ g₁ a = b := by
intro c _ ⟨cs, rfl⟩
cases e : step M c
· rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e]
rfl
· refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, TransGen.single ?_⟩
rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e]
rfl
end
end TM0
/-!
## The TM1 model
The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of
Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables
that may be accessed and updated at any time.
A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which
is a `Stmt`. Most of the regular commands are allowed to use the current value `a` of the local
variables and the value `T.head` on the tape to calculate what to write or how to change local
state, but the statements themselves have a fixed structure. The `Stmt`s can be as follows:
* `move d q`: move left or right, and then do `q`
* `write (f : Γ → σ → Γ) q`: write `f a T.head` to the tape, then do `q`
* `load (f : Γ → σ → σ) q`: change the internal state to `f a T.head`
* `branch (f : Γ → σ → Bool) qtrue qfalse`: If `f a T.head` is true, do `qtrue`, else `qfalse`
* `goto (f : Γ → σ → Λ)`: Go to label `f a T.head`
* `halt`: Transition to the halting state, which halts on the following step
Note that here most statements do not have labels; `goto` commands can only go to a new function.
Only the `goto` and `halt` statements actually take a step; the rest is done by recursion on
statements and so take 0 steps. (There is a uniform bound on how many statements can be executed
before the next `goto`, so this is an `O(1)` speedup with the constant depending on the machine.)
The `halt` command has a one step stutter before actually halting so that any changes made before
the halt have a chance to be "committed", since the `eval` relation uses the final configuration
before the halt as the output, and `move` and `write` etc. take 0 steps in this model.
-/
namespace TM1
section
variable (Γ : Type*)
-- Type of tape symbols
variable (Λ : Type*)
-- Type of function labels
variable (σ : Type*)
-- Type of variable settings
/-- The TM1 model is a simplification and extension of TM0
(Post-Turing model) in the direction of Wang B-machines. The machine's
internal state is extended with a (finite) store `σ` of variables
that may be accessed and updated at any time.
A machine is given by a `Λ` indexed set of procedures or functions.
Each function has a body which is a `Stmt`, which can either be a
`move` or `write` command, a `branch` (if statement based on the
current tape value), a `load` (set the variable value),
a `goto` (call another function), or `halt`. Note that here
most statements do not have labels; `goto` commands can only
go to a new function. All commands have access to the variable value
and current tape value. -/
inductive Stmt
| move : Dir → Stmt → Stmt
| write : (Γ → σ → Γ) → Stmt → Stmt
| load : (Γ → σ → σ) → Stmt → Stmt
| branch : (Γ → σ → Bool) → Stmt → Stmt → Stmt
| goto : (Γ → σ → Λ) → Stmt
| halt : Stmt
open Stmt
instance Stmt.inhabited : Inhabited (Stmt Γ Λ σ) := ⟨halt⟩
/-- The configuration of a TM1 machine is given by the currently
evaluating statement, the variable store value, and the tape. -/
structure Cfg [Inhabited Γ] where
/-- The statement (if any) which is currently evaluated -/
l : Option Λ
/-- The current value of the variable store -/
var : σ
/-- The current state of the tape -/
Tape : Tape Γ
instance Cfg.inhabited [Inhabited Γ] [Inhabited σ] : Inhabited (Cfg Γ Λ σ) :=
⟨⟨default, default, default⟩⟩
variable {Γ Λ σ}
/-- The semantics of TM1 evaluation. -/
def stepAux [Inhabited Γ] : Stmt Γ Λ σ → σ → Tape Γ → Cfg Γ Λ σ
| move d q, v, T => stepAux q v (T.move d)
| write a q, v, T => stepAux q v (T.write (a T.1 v))
| load s q, v, T => stepAux q (s T.1 v) T
| branch p q₁ q₂, v, T => cond (p T.1 v) (stepAux q₁ v T) (stepAux q₂ v T)
| goto l, v, T => ⟨some (l T.1 v), v, T⟩
| halt, v, T => ⟨none, v, T⟩
/-- The state transition function. -/
def step [Inhabited Γ] (M : Λ → Stmt Γ Λ σ) : Cfg Γ Λ σ → Option (Cfg Γ Λ σ)
| ⟨none, _, _⟩ => none
| ⟨some l, v, T⟩ => some (stepAux (M l) v T)
/-- A set `S` of labels supports the statement `q` if all the `goto`
statements in `q` refer only to other functions in `S`. -/
def SupportsStmt (S : Finset Λ) : Stmt Γ Λ σ → Prop
| move _ q => SupportsStmt S q
| write _ q => SupportsStmt S q
| load _ q => SupportsStmt S q
| branch _ q₁ q₂ => SupportsStmt S q₁ ∧ SupportsStmt S q₂
| goto l => ∀ a v, l a v ∈ S
| halt => True
open scoped Classical in
/-- The subterm closure of a statement. -/
noncomputable def stmts₁ : Stmt Γ Λ σ → Finset (Stmt Γ Λ σ)
| Q@(move _ q) => insert Q (stmts₁ q)
| Q@(write _ q) => insert Q (stmts₁ q)
| Q@(load _ q) => insert Q (stmts₁ q)
| Q@(branch _ q₁ q₂) => insert Q (stmts₁ q₁ ∪ stmts₁ q₂)
| Q => {Q}
theorem stmts₁_self {q : Stmt Γ Λ σ} : q ∈ stmts₁ q := by
cases q <;> simp only [stmts₁, Finset.mem_insert_self, Finset.mem_singleton_self]
theorem stmts₁_trans {q₁ q₂ : Stmt Γ Λ σ} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := by
classical
intro h₁₂ q₀ h₀₁
induction q₂ with (
simp only [stmts₁] at h₁₂ ⊢
simp only [Finset.mem_insert, Finset.mem_union, Finset.mem_singleton] at h₁₂)
| branch p q₁ q₂ IH₁ IH₂ =>
rcases h₁₂ with (rfl | h₁₂ | h₁₂)
· unfold stmts₁ at h₀₁
exact h₀₁
· grind
· grind
| goto l => subst h₁₂; exact h₀₁
| halt => subst h₁₂; exact h₀₁
| _ _ q IH =>
rcases h₁₂ with rfl | h₁₂
· exact h₀₁
· grind
theorem stmts₁_supportsStmt_mono {S : Finset Λ} {q₁ q₂ : Stmt Γ Λ σ} (h : q₁ ∈ stmts₁ q₂)
(hs : SupportsStmt S q₂) : SupportsStmt S q₁ := by
induction q₂ with
simp only [stmts₁, SupportsStmt, Finset.mem_insert, Finset.mem_union, Finset.mem_singleton]
at h hs
| branch p q₁ q₂ IH₁ IH₂ => rcases h with (rfl | h | h); exacts [hs, IH₁ h hs.1, IH₂ h hs.2]
| goto l => subst h; exact hs
| halt => subst h; trivial
| _ _ q IH => rcases h with (rfl | h) <;> [exact hs; exact IH h hs]
open scoped Classical in
/-- The set of all statements in a Turing machine, plus one extra value `none` representing the
halt state. This is used in the TM1 to TM0 reduction. -/
noncomputable def stmts (M : Λ → Stmt Γ Λ σ) (S : Finset Λ) : Finset (Option (Stmt Γ Λ σ)) :=
Finset.insertNone (S.biUnion fun q ↦ stmts₁ (M q))
theorem stmts_trans {M : Λ → Stmt Γ Λ σ} {S : Finset Λ} {q₁ q₂ : Stmt Γ Λ σ} (h₁ : q₁ ∈ stmts₁ q₂) :
some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by
simp only [stmts, Finset.mem_insertNone, Finset.mem_biUnion, Option.mem_def, Option.some.injEq,
forall_eq', exists_imp, and_imp]
exact fun l ls h₂ ↦ ⟨_, ls, stmts₁_trans h₂ h₁⟩
variable [Inhabited Λ]
/-- A set `S` of labels supports machine `M` if all the `goto`
statements in the functions in `S` refer only to other functions
in `S`. -/
def Supports (M : Λ → Stmt Γ Λ σ) (S : Finset Λ) :=
default ∈ S ∧ ∀ q ∈ S, SupportsStmt S (M q)
theorem stmts_supportsStmt {M : Λ → Stmt Γ Λ σ} {S : Finset Λ} {q : Stmt Γ Λ σ}
(ss : Supports M S) : some q ∈ stmts M S → SupportsStmt S q := by
simp only [stmts, Finset.mem_insertNone, Finset.mem_biUnion, Option.mem_def, Option.some.injEq,
forall_eq', exists_imp, and_imp]
exact fun l ls h ↦ stmts₁_supportsStmt_mono h (ss.2 _ ls)
variable [Inhabited Γ]
theorem step_supports (M : Λ → Stmt Γ Λ σ) {S : Finset Λ} (ss : Supports M S) :
∀ {c c' : Cfg Γ Λ σ}, c' ∈ step M c → c.l ∈ Finset.insertNone S → c'.l ∈ Finset.insertNone S
| ⟨some l₁, v, T⟩, c', h₁, h₂ => by
replace h₂ := ss.2 _ (Finset.some_mem_insertNone.1 h₂)
simp only [step, Option.mem_def, Option.some.injEq] at h₁; subst c'
revert h₂; induction M l₁ generalizing v T with intro hs
| branch p q₁' q₂' IH₁ IH₂ =>
unfold stepAux; cases p T.1 v
· exact IH₂ _ _ hs.2
· exact IH₁ _ _ hs.1
| goto => exact Finset.some_mem_insertNone.2 (hs _ _)
| halt => apply Multiset.mem_cons_self
| _ _ q IH => exact IH _ _ hs
variable [Inhabited σ]
/-- The initial state, given a finite input that is placed on the tape starting at the TM head and
going to the right. -/
def init (l : List Γ) : Cfg Γ Λ σ :=
⟨some default, default, Tape.mk₁ l⟩
/-- Evaluate a TM to completion, resulting in an output list on the tape (with an indeterminate
number of blanks on the end). -/
def eval (M : Λ → Stmt Γ Λ σ) (l : List Γ) : Part (ListBlank Γ) :=
(Turing.eval (step M) (init l)).map fun c ↦ c.Tape.right₀
end
end TM1
/-!
## TM1 emulator in TM0
To prove that TM1 computable functions are TM0 computable, we need to reduce each TM1 program to a
TM0 program. So suppose a TM1 program is given. We take the following:
* The alphabet `Γ` is the same for both TM1 and TM0
* The set of states `Λ'` is defined to be `Option Stmt₁ × σ`, that is, a TM1 statement or `none`
representing halt, and the possible settings of the internal variables.
Note that this is an infinite set, because `Stmt₁` is infinite. This is okay because we assume
that from the initial TM1 state, only finitely many other labels are reachable, and there are
only finitely many statements that appear in all of these functions.
Even though `Stmt₁` contains a statement called `halt`, we must separate it from `none`
(`some halt` steps to `none` and `none` actually halts) because there is a one step stutter in the
TM1 semantics.
-/
namespace TM1to0
variable {Γ : Type*}
variable {Λ : Type*} [Inhabited Λ]
variable {σ : Type*} [Inhabited σ]
variable (M : Λ → TM1.Stmt Γ Λ σ)
set_option linter.unusedVariables false in
/-- The base machine state space is a pair of an `Option Stmt₁` representing the current program
to be executed, or `none` for the halt state, and a `σ` which is the local state (stored in the TM,
not the tape). Because there are an infinite number of programs, this state space is infinite, but
for a finitely supported TM1 machine and a finite type `σ`, only finitely many of these states are
reachable. -/
@[nolint unusedArguments] -- We need the M assumption
def Λ' (M : Λ → TM1.Stmt Γ Λ σ) :=
Option (TM1.Stmt Γ Λ σ) × σ
instance : Inhabited (Λ' M) :=
⟨(some (M default), default)⟩
open TM0.Stmt
/-- The core TM1 → TM0 translation function. Here `s` is the current value on the tape, and the
`Stmt₁` is the TM1 statement to translate, with local state `v : σ`. We evaluate all regular
instructions recursively until we reach either a `move` or `write` command, or a `goto`; in the
latter case we emit a dummy `write s` step and transition to the new target location. -/
def trAux (s : Γ) : TM1.Stmt Γ Λ σ → σ → Λ' M × TM0.Stmt Γ
| TM1.Stmt.move d q, v => ((some q, v), move d)
| TM1.Stmt.write a q, v => ((some q, v), write (a s v))
| TM1.Stmt.load a q, v => trAux s q (a s v)
| TM1.Stmt.branch p q₁ q₂, v => cond (p s v) (trAux s q₁ v) (trAux s q₂ v)
| TM1.Stmt.goto l, v => ((some (M (l s v)), v), write s)
| TM1.Stmt.halt, v => ((none, v), write s)
/-- The translated TM0 machine (given the TM1 machine input). -/
def tr : TM0.Machine Γ (Λ' M)
| (none, _), _ => none
| (some q, v), s => some (trAux M s q v)
/-- Translate configurations from TM1 to TM0. -/
def trCfg [Inhabited Γ] : TM1.Cfg Γ Λ σ → TM0.Cfg Γ (Λ' M)
| ⟨l, v, T⟩ => ⟨(l.map M, v), T⟩
theorem tr_respects [Inhabited Γ] :
Respects (TM1.step M) (TM0.step (tr M))
fun (c₁ : TM1.Cfg Γ Λ σ) (c₂ : TM0.Cfg Γ (Λ' M)) ↦ trCfg M c₁ = c₂ :=
fun_respects.2 fun ⟨l₁, v, T⟩ ↦ by
rcases l₁ with - | l₁; · exact rfl
simp only [trCfg, TM1.step, FRespects, Option.map]
induction M l₁ generalizing v T with
| move _ _ IH => exact TransGen.head rfl (IH _ _)
| write _ _ IH => exact TransGen.head rfl (IH _ _)
| load _ _ IH => exact (reaches₁_eq (by rfl)).2 (IH _ _)
| branch p _ _ IH₁ IH₂ =>
unfold TM1.stepAux; cases e : p T.1 v
· exact (reaches₁_eq (by simp only [TM0.step, tr, trAux, e]; rfl)).2 (IH₂ _ _)
· exact (reaches₁_eq (by simp only [TM0.step, tr, trAux, e]; rfl)).2 (IH₁ _ _)
| _ =>
exact TransGen.single (congr_arg some (congr (congr_arg TM0.Cfg.mk rfl) (Tape.write_self T)))
theorem tr_eval [Inhabited Γ] (l : List Γ) : TM0.eval (tr M) l = TM1.eval M l :=
(congr_arg _ (tr_eval' _ _ _ (tr_respects M) ⟨some _, _, _⟩)).trans
(by
rw [Part.map_eq_map, Part.map_map, TM1.eval]
congr with ⟨⟩)
variable [Fintype σ]
/-- Given a finite set of accessible `Λ` machine states, there is a finite set of accessible
machine states in the target (even though the type `Λ'` is infinite). -/
noncomputable def trStmts (S : Finset Λ) : Finset (Λ' M) :=
(TM1.stmts M S) ×ˢ Finset.univ
attribute [local simp] TM1.stmts₁_self
theorem tr_supports {S : Finset Λ} (ss : TM1.Supports M S) :
TM0.Supports (tr M) ↑(trStmts M S) := by
classical
constructor
· apply Finset.mem_product.2
constructor
· simp only [default, TM1.stmts, Finset.mem_insertNone, Option.mem_def, Option.some_inj,
forall_eq', Finset.mem_biUnion]
exact ⟨_, ss.1, TM1.stmts₁_self⟩
· apply Finset.mem_univ
· intro q a q' s h₁ h₂
rcases q with ⟨_ | q, v⟩; · cases h₁
obtain ⟨q', v'⟩ := q'
simp only [trStmts, Finset.mem_coe] at h₂ ⊢
rw [Finset.mem_product] at h₂ ⊢
simp only [Finset.mem_univ, and_true] at h₂ ⊢
cases q'; · exact Multiset.mem_cons_self _ _
simp only [tr, Option.mem_def] at h₁
have := TM1.stmts_supportsStmt ss h₂
revert this; induction q generalizing v with intro hs
| move d q =>
cases h₁; refine TM1.stmts_trans ?_ h₂
unfold TM1.stmts₁
exact Finset.mem_insert_of_mem TM1.stmts₁_self
| write b q =>
cases h₁; refine TM1.stmts_trans ?_ h₂
unfold TM1.stmts₁
exact Finset.mem_insert_of_mem TM1.stmts₁_self
| load b q IH =>
refine IH _ (TM1.stmts_trans ?_ h₂) h₁ hs
unfold TM1.stmts₁
exact Finset.mem_insert_of_mem TM1.stmts₁_self
| branch p q₁ q₂ IH₁ IH₂ =>
cases h : p a v <;> rw [trAux, h] at h₁
· refine IH₂ _ (TM1.stmts_trans ?_ h₂) h₁ hs.2
unfold TM1.stmts₁
exact Finset.mem_insert_of_mem (Finset.mem_union_right _ TM1.stmts₁_self)
· refine IH₁ _ (TM1.stmts_trans ?_ h₂) h₁ hs.1
unfold TM1.stmts₁
exact Finset.mem_insert_of_mem (Finset.mem_union_left _ TM1.stmts₁_self)
| goto l =>
cases h₁
exact Finset.some_mem_insertNone.2 (Finset.mem_biUnion.2 ⟨_, hs _ _, TM1.stmts₁_self⟩)
| halt => cases h₁
end TM1to0
/-!
## TM1(Γ) emulator in TM1(Bool)
The most parsimonious Turing machine model that is still Turing complete is `TM0` with `Γ = Bool`.
Because our construction in the previous section reducing `TM1` to `TM0` doesn't change the
alphabet, we can do the alphabet reduction on `TM1` instead of `TM0` directly.
The basic idea is to use a bijection between `Γ` and a subset of `Vector Bool n`, where `n` is a
fixed constant. Each tape element is represented as a block of `n` `Bool`s. Whenever the machine
wants to read a symbol from the tape, it traverses over the block, performing `n` `branch`
instructions to reach any of the `2^n` results.
For the `write` instruction, we have to use a `goto` because we need to follow a different code
path depending on the local state, which is not available in the TM1 model, so instead we jump to
a label computed using the read value and the local state, which performs the writing and returns
to normal execution.
Emulation overhead is `O(1)`. If not for the above `write` behavior it would be 1-1 because we are
exploiting the 0-step behavior of regular commands to avoid taking steps, but there are
nevertheless a bounded number of `write` calls between `goto` statements because TM1 statements are
finitely long.
-/
namespace TM1to1
open TM1
variable {Γ : Type*}
theorem exists_enc_dec [Inhabited Γ] [Finite Γ] :
∃ (n : ℕ) (enc : Γ → List.Vector Bool n) (dec : List.Vector Bool n → Γ),
enc default = List.Vector.replicate n false ∧ ∀ a, dec (enc a) = a := by
rcases Finite.exists_equiv_fin Γ with ⟨n, ⟨e⟩⟩
letI : DecidableEq Γ := e.decidableEq
let G : Fin n ↪ Fin n → Bool :=
⟨fun a b ↦ a = b, fun a b h ↦
Bool.of_decide_true <| (congr_fun h b).trans <| Bool.decide_true rfl⟩
let H := (e.toEmbedding.trans G).trans (Equiv.vectorEquivFin _ _).symm.toEmbedding
let enc := H.setValue default (List.Vector.replicate n false)
exact ⟨_, enc, Function.invFun enc, H.setValue_eq _ _, Function.leftInverse_invFun enc.2⟩
variable (Γ)
variable (Λ σ : Type*)
/-- The configuration state of the TM. -/
inductive Λ'
| normal : Λ → Λ'
| write : Γ → Stmt Γ Λ σ → Λ'
variable {Γ Λ σ}
instance [Inhabited Λ] : Inhabited (Λ' Γ Λ σ) :=
⟨Λ'.normal default⟩
/-- Read a vector of length `n` from the tape. -/
def readAux : ∀ n, (List.Vector Bool n → Stmt Bool (Λ' Γ Λ σ) σ) → Stmt Bool (Λ' Γ Λ σ) σ
| 0, f => f Vector.nil
| i + 1, f =>
Stmt.branch (fun a _ ↦ a) (Stmt.move Dir.right <| readAux i fun v ↦ f (true ::ᵥ v))
(Stmt.move Dir.right <| readAux i fun v ↦ f (false ::ᵥ v))
variable (n : ℕ) (enc : Γ → List.Vector Bool n) (dec : List.Vector Bool n → Γ)
/-- A move left or right corresponds to `n` moves across the super-cell. -/
def move (d : Dir) (q : Stmt Bool (Λ' Γ Λ σ) σ) : Stmt Bool (Λ' Γ Λ σ) σ :=
(Stmt.move d)^[n] q
variable {n}
/-- To read a symbol from the tape, we use `readAux` to traverse the symbol,
then return to the original position with `n` moves to the left. -/
def read (f : Γ → Stmt Bool (Λ' Γ Λ σ) σ) : Stmt Bool (Λ' Γ Λ σ) σ :=
readAux n fun v ↦ move n Dir.left <| f (dec v)
/-- Write a list of `Bool`s on the tape. -/
def write : List Bool → Stmt Bool (Λ' Γ Λ σ) σ → Stmt Bool (Λ' Γ Λ σ) σ
| [], q => q
| a :: l, q => (Stmt.write fun _ _ ↦ a) <| Stmt.move Dir.right <| write l q
/-- Translate a normal instruction. For the `write` command, we use a `goto` indirection so that
we can access the current value of the tape. -/
def trNormal : Stmt Γ Λ σ → Stmt Bool (Λ' Γ Λ σ) σ
| Stmt.move d q => move n d <| trNormal q
| Stmt.write f q => read dec fun a ↦ Stmt.goto fun _ s ↦ Λ'.write (f a s) q
| Stmt.load f q => read dec fun a ↦ (Stmt.load fun _ s ↦ f a s) <| trNormal q
| Stmt.branch p q₁ q₂ =>
read dec fun a ↦ Stmt.branch (fun _ s ↦ p a s) (trNormal q₁) (trNormal q₂)
| Stmt.goto l => read dec fun a ↦ Stmt.goto fun _ s ↦ Λ'.normal (l a s)
| Stmt.halt => Stmt.halt
theorem stepAux_move (d : Dir) (q : Stmt Bool (Λ' Γ Λ σ) σ) (v : σ) (T : Tape Bool) :
stepAux (move n d q) v T = stepAux q v ((Tape.move d)^[n] T) := by
suffices ∀ i, stepAux ((Stmt.move d)^[i] q) v T = stepAux q v ((Tape.move d)^[i] T) from this n
intro i
induction i generalizing T with
| zero => rfl
| succ i IH =>
rw [iterate_succ', iterate_succ]
simp only [stepAux, Function.comp_apply]
rw [IH]
theorem supportsStmt_move {S : Finset (Λ' Γ Λ σ)} {d : Dir} {q : Stmt Bool (Λ' Γ Λ σ) σ} :
SupportsStmt S (move n d q) = SupportsStmt S q := by
suffices ∀ {i}, SupportsStmt S ((Stmt.move d)^[i] q) = _ from this
intro i; induction i generalizing q <;> simp only [*, iterate]; rfl
theorem supportsStmt_write {S : Finset (Λ' Γ Λ σ)} {l : List Bool} {q : Stmt Bool (Λ' Γ Λ σ) σ} :
SupportsStmt S (write l q) = SupportsStmt S q := by
induction l <;> simp only [write, SupportsStmt, *]
theorem supportsStmt_read {S : Finset (Λ' Γ Λ σ)} :
∀ {f : Γ → Stmt Bool (Λ' Γ Λ σ) σ}, (∀ a, SupportsStmt S (f a)) →
SupportsStmt S (read dec f) :=
suffices
∀ (i) (f : List.Vector Bool i → Stmt Bool (Λ' Γ Λ σ) σ),
(∀ v, SupportsStmt S (f v)) → SupportsStmt S (readAux i f)
from fun hf ↦ this n _ (by intro; simp only [supportsStmt_move, hf])
fun i f hf ↦ by
induction i with
| zero => exact hf _
| succ i IH => constructor <;> apply IH <;> intro <;> apply hf
variable (M : Λ → TM1.Stmt Γ Λ σ)
section
variable [Inhabited Γ] (enc0 : enc default = List.Vector.replicate n false)
section
variable {enc}
/-- The low level tape corresponding to the given tape over alphabet `Γ`. -/
def trTape' (L R : ListBlank Γ) : Tape Bool := by
refine
Tape.mk' (L.flatMap (fun x ↦ (enc x).toList.reverse) ⟨n, ?_⟩)
(R.flatMap (fun x ↦ (enc x).toList) ⟨n, ?_⟩) <;>
simp only [enc0, List.Vector.replicate, List.reverse_replicate, Bool.default_bool,
List.Vector.toList_mk]
/-- The low level tape corresponding to the given tape over alphabet `Γ`. -/
def trTape (T : Tape Γ) : Tape Bool :=
trTape' enc0 T.left T.right₀
theorem trTape_mk' (L R : ListBlank Γ) : trTape enc0 (Tape.mk' L R) = trTape' enc0 L R := by
simp only [trTape, Tape.mk'_left, Tape.mk'_right₀]
end
/-- The top level program. -/
def tr : Λ' Γ Λ σ → Stmt Bool (Λ' Γ Λ σ) σ
| Λ'.normal l => trNormal dec (M l)
| Λ'.write a q => write (enc a).toList <| move n Dir.left <| trNormal dec q
/-- The machine configuration translation. -/
def trCfg : Cfg Γ Λ σ → Cfg Bool (Λ' Γ Λ σ) σ
| ⟨l, v, T⟩ => ⟨l.map Λ'.normal, v, trTape enc0 T⟩
variable {enc}
theorem trTape'_move_left (L R : ListBlank Γ) :
(Tape.move Dir.left)^[n] (trTape' enc0 L R) = trTape' enc0 L.tail (R.cons L.head) := by
obtain ⟨a, L, rfl⟩ := L.exists_cons
simp only [trTape', ListBlank.cons_flatMap, ListBlank.head_cons, ListBlank.tail_cons]
suffices ∀ {L' R' l₁ l₂} (_ : List.Vector.toList (enc a) = List.reverseAux l₁ l₂),
(Tape.move Dir.left)^[l₁.length]
(Tape.mk' (ListBlank.append l₁ L') (ListBlank.append l₂ R')) =
Tape.mk' L' (ListBlank.append (List.Vector.toList (enc a)) R') by
simpa only [List.length_reverse, Vector.toList_length] using this (List.reverse_reverse _).symm
intro _ _ l₁ l₂ e
induction l₁ generalizing l₂ with
| nil => cases e; rfl
| cons b l₁ IH =>
simp only [List.length, iterate_succ_apply]
convert IH e
simp only [ListBlank.tail_cons, ListBlank.append, Tape.move_left_mk', ListBlank.head_cons]
theorem trTape'_move_right (L R : ListBlank Γ) :
(Tape.move Dir.right)^[n] (trTape' enc0 L R) = trTape' enc0 (L.cons R.head) R.tail := by
suffices ∀ i L, (Tape.move Dir.right)^[i] ((Tape.move Dir.left)^[i] L) = L by
refine (Eq.symm ?_).trans (this n _)
simp only [trTape'_move_left, ListBlank.cons_head_tail, ListBlank.head_cons,
ListBlank.tail_cons]
intro i _
induction i with
| zero => rfl
| succ i IH => rw [iterate_succ_apply, iterate_succ_apply', Tape.move_left_right, IH]
theorem stepAux_write (q : Stmt Bool (Λ' Γ Λ σ) σ) (v : σ) (a b : Γ) (L R : ListBlank Γ) :
stepAux (write (enc a).toList q) v (trTape' enc0 L (ListBlank.cons b R)) =
stepAux q v (trTape' enc0 (ListBlank.cons a L) R) := by
simp only [trTape', ListBlank.cons_flatMap]
suffices ∀ {L' R'} (l₁ l₂ l₂' : List Bool) (_ : l₂'.length = l₂.length),
stepAux (write l₂ q) v (Tape.mk' (ListBlank.append l₁ L') (ListBlank.append l₂' R')) =
stepAux q v (Tape.mk' (L'.append (List.reverseAux l₂ l₁)) R') by
exact this [] _ _ ((enc b).2.trans (enc a).2.symm)
clear a b L R
intro L' R' l₁ l₂ l₂' e
induction l₂ generalizing l₁ l₂' with
| nil => cases List.length_eq_zero_iff.1 e; rfl
| cons a l₂ IH =>
rcases l₂' with - | ⟨b, l₂'⟩ <;>
simp only [List.length_nil, List.length_cons, Nat.succ_inj, reduceCtorEq] at e
rw [List.reverseAux, ← IH (a :: l₁) l₂' e]
simp [stepAux, ListBlank.append, write]
variable (encdec : ∀ a, dec (enc a) = a)
include encdec
theorem stepAux_read (f : Γ → Stmt Bool (Λ' Γ Λ σ) σ) (v : σ) (L R : ListBlank Γ) :
stepAux (read dec f) v (trTape' enc0 L R) = stepAux (f R.head) v (trTape' enc0 L R) := by
suffices ∀ f, stepAux (readAux n f) v (trTape' enc0 L R) =
stepAux (f (enc R.head)) v (trTape' enc0 (L.cons R.head) R.tail) by
rw [read, this, stepAux_move, encdec, trTape'_move_left enc0]
simp only [ListBlank.head_cons, ListBlank.cons_head_tail, ListBlank.tail_cons]
obtain ⟨a, R, rfl⟩ := R.exists_cons
simp only [ListBlank.head_cons, ListBlank.tail_cons, trTape', ListBlank.cons_flatMap]
suffices ∀ i f L' R' l₁ l₂ h,
stepAux (readAux i f) v (Tape.mk' (ListBlank.append l₁ L') (ListBlank.append l₂ R')) =
stepAux (f ⟨l₂, h⟩) v (Tape.mk' (ListBlank.append (l₂.reverseAux l₁) L') R') by
intro f
exact this n f (L.flatMap (fun x => (enc x).1.reverse) _)
(R.flatMap (fun x => (enc x).1) _) [] _ (enc a).2
clear f L a R
intro i f L' R' l₁ l₂ _
subst i
induction l₂ generalizing l₁ with
| nil => rfl
| cons a l₂ IH =>
trans stepAux (readAux l₂.length fun v ↦ f (a ::ᵥ v)) v
(Tape.mk' ((L'.append l₁).cons a) (R'.append l₂))
· dsimp [readAux, stepAux]
simp only [ListBlank.head_cons, Tape.move_right_mk', ListBlank.tail_cons]
cases a <;> rfl
· rw [← ListBlank.append, IH]
rfl
variable {enc0} in
theorem tr_respects :
Respects (step M) (step (tr enc dec M)) fun c₁ c₂ ↦ trCfg enc enc0 c₁ = c₂ :=
fun_respects.2 fun ⟨l₁, v, T⟩ ↦ by
obtain ⟨L, R, rfl⟩ := T.exists_mk'
rcases l₁ with - | l₁
· exact rfl
suffices ∀ q R, Reaches (step (tr enc dec M)) (stepAux (trNormal dec q) v (trTape' enc0 L R))
(trCfg enc enc0 (stepAux q v (Tape.mk' L R))) by
refine TransGen.head' rfl ?_
rw [trTape_mk']
exact this _ R
clear R l₁
intro q R
induction q generalizing v L R with
| move d q IH =>
cases d <;>
simp only [trNormal, stepAux_move, stepAux,
Tape.move_left_mk',
trTape'_move_left enc0, trTape'_move_right enc0] <;>
apply IH
| write f q IH =>
simp only [trNormal, stepAux_read dec enc0 encdec, stepAux]
refine ReflTransGen.head rfl ?_
obtain ⟨a, R, rfl⟩ := R.exists_cons
rw [tr, Tape.mk'_head, stepAux_write, ListBlank.head_cons, stepAux_move,
trTape'_move_left enc0, ListBlank.head_cons, ListBlank.tail_cons, Tape.write_mk']
apply IH
| load a q IH =>
simp only [trNormal, stepAux_read dec enc0 encdec]
apply IH
| branch p q₁ q₂ IH₁ IH₂ =>
simp only [trNormal, stepAux_read dec enc0 encdec, stepAux, Tape.mk'_head]
grind
| goto l =>
simp only [trNormal, stepAux_read dec enc0 encdec, stepAux, trCfg, trTape_mk']
apply ReflTransGen.refl
| halt =>
simp only [trNormal, stepAux, trCfg,
trTape_mk']
apply ReflTransGen.refl
end
variable [Fintype Γ]
open scoped Classical in
/-- The set of accessible `Λ'.write` machine states. -/
noncomputable def writes : Stmt Γ Λ σ → Finset (Λ' Γ Λ σ)
| Stmt.move _ q => writes q
| Stmt.write _ q => (Finset.univ.image fun a ↦ Λ'.write a q) ∪ writes q
| Stmt.load _ q => writes q
| Stmt.branch _ q₁ q₂ => writes q₁ ∪ writes q₂
| Stmt.goto _ => ∅
| Stmt.halt => ∅
open scoped Classical in
/-- The set of accessible machine states, assuming that the input machine is supported on `S`,
are the normal states embedded from `S`, plus all write states accessible from these states. -/
noncomputable def trSupp (S : Finset Λ) : Finset (Λ' Γ Λ σ) :=
S.biUnion fun l ↦ insert (Λ'.normal l) (writes (M l))
open scoped Classical in
theorem tr_supports [Inhabited Λ] {S : Finset Λ} (ss : Supports M S) :
Supports (tr enc dec M) (trSupp M S) :=
⟨Finset.mem_biUnion.2 ⟨_, ss.1, Finset.mem_insert_self _ _⟩, fun q h ↦ by
suffices ∀ q, SupportsStmt S q → (∀ q' ∈ writes q, q' ∈ trSupp M S) →
SupportsStmt (trSupp M S) (trNormal dec q) ∧
∀ q' ∈ writes q, SupportsStmt (trSupp M S) (tr enc dec M q') by
rcases Finset.mem_biUnion.1 h with ⟨l, hl, h⟩
have :=
this _ (ss.2 _ hl) fun q' hq ↦ Finset.mem_biUnion.2 ⟨_, hl, Finset.mem_insert_of_mem hq⟩
rcases Finset.mem_insert.1 h with (rfl | h)
exacts [this.1, this.2 _ h]
intro q hs hw
induction q with
| move d q IH =>
unfold writes at hw ⊢
replace IH := IH hs hw; refine ⟨?_, IH.2⟩
cases d <;> simp only [trNormal, supportsStmt_move, IH]
| write f q IH =>
unfold writes at hw ⊢
simp only [Finset.mem_image, Finset.mem_union, Finset.mem_univ, true_and]
at hw ⊢
replace IH := IH hs fun q hq ↦ hw q (Or.inr hq)
refine ⟨supportsStmt_read _ fun a _ s ↦ hw _ (Or.inl ⟨_, rfl⟩), fun q' hq ↦ ?_⟩
rcases hq with (⟨a, q₂, rfl⟩ | hq)
· simp only [tr, supportsStmt_write, supportsStmt_move, IH.1]
· exact IH.2 _ hq
| load a q IH =>
unfold writes at hw ⊢
replace IH := IH hs hw
exact ⟨supportsStmt_read _ fun _ ↦ IH.1, IH.2⟩
| branch p q₁ q₂ IH₁ IH₂ =>
unfold writes at hw ⊢
simp only [Finset.mem_union] at hw ⊢
replace IH₁ := IH₁ hs.1 fun q hq ↦ hw q (Or.inl hq)
replace IH₂ := IH₂ hs.2 fun q hq ↦ hw q (Or.inr hq)
exact ⟨supportsStmt_read _ fun _ ↦ ⟨IH₁.1, IH₂.1⟩, fun q ↦ Or.rec (IH₁.2 _) (IH₂.2 _)⟩
| goto l =>
simp only [writes, Finset.notMem_empty]; refine ⟨?_, fun _ ↦ False.elim⟩
refine supportsStmt_read _ fun a _ s ↦ ?_
exact Finset.mem_biUnion.2 ⟨_, hs _ _, Finset.mem_insert_self _ _⟩
| halt =>
simp only [writes, Finset.notMem_empty]; refine ⟨?_, fun _ ↦ False.elim⟩
simp only [SupportsStmt, trNormal]⟩
end TM1to1
/-!
## TM0 emulator in TM1
To establish that TM0 and TM1 are equivalent computational models, we must also have a TM0 emulator
in TM1. The main complication here is that TM0 allows an action to depend on the value at the head
and local state, while TM1 does not (in order to have more programming language-like semantics).
So we use a computed `goto` to go to a state that performs the desired action and then returns to
normal execution.
One issue with this is that the `halt` instruction is supposed to halt immediately, not take a step
to a halting state. To resolve this we do a check for `halt` first, then `goto` (with an
unreachable branch).
-/
namespace TM0to1
variable (Γ : Type*) [Inhabited Γ]
variable (Λ : Type*) [Inhabited Λ]
/-- The machine states for a TM1 emulating a TM0 machine. States of the TM0 machine are embedded
as `normal q` states, but the actual operation is split into two parts, a jump to `act s q`
followed by the action and a jump to the next `normal` state. -/
inductive Λ'
| normal : Λ → Λ'
| act : TM0.Stmt Γ → Λ → Λ'
variable {Γ Λ}
instance : Inhabited (Λ' Γ Λ) :=
⟨Λ'.normal default⟩
variable (M : TM0.Machine Γ Λ)
open TM1.Stmt
/-- The program. -/
def tr : Λ' Γ Λ → TM1.Stmt Γ (Λ' Γ Λ) Unit
| Λ'.normal q =>
branch (fun a _ ↦ (M q a).isNone) halt <|
goto fun a _ ↦ match M q a with
| none => default -- unreachable
| some (q', s) => Λ'.act s q'
| Λ'.act (TM0.Stmt.move d) q => move d <| goto fun _ _ ↦ Λ'.normal q
| Λ'.act (TM0.Stmt.write a) q => (write fun _ _ ↦ a) <| goto fun _ _ ↦ Λ'.normal q
/-- The configuration translation. -/
def trCfg : TM0.Cfg Γ Λ → TM1.Cfg Γ (Λ' Γ Λ) Unit
| ⟨q, T⟩ => ⟨cond (M q T.1).isSome (some (Λ'.normal q)) none, (), T⟩
theorem tr_respects : Respects (TM0.step M) (TM1.step (tr M)) fun a b ↦ trCfg M a = b :=
fun_respects.2 fun ⟨q, T⟩ ↦ by
rcases e : M q T.1 with - | val
· simp only [TM0.step, trCfg, e]; exact Eq.refl none
obtain ⟨q', s⟩ := val
simp only [FRespects, TM0.step, trCfg, e, Option.isSome, cond, Option.map_some]
revert e
have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ = some ⟨some (Λ'.normal q'), (), match s with
| TM0.Stmt.move d => T.move d
| TM0.Stmt.write a => T.write a⟩ := by
cases s <;> rfl
intro e
refine TransGen.head ?_ (TransGen.head' this ?_)
· simp only [TM1.step, TM1.stepAux, tr]
rw [e]
rfl
cases e' : M q' _
· apply ReflTransGen.single
simp only [TM1.step, TM1.stepAux, tr]
rw [e']
rfl
· rfl
end TM0to1
end Turing |
.lake/packages/mathlib/Mathlib/Computability/TMComputable.lean | import Mathlib.Algebra.Polynomial.Eval.Defs
import Mathlib.Computability.Encoding
import Mathlib.Computability.TuringMachine
/-!
# Computable functions
This file contains the definition of a Turing machine with some finiteness conditions
(bundling the definition of TM2 in `TuringMachine.lean`), a definition of when a TM gives a certain
output (in a certain time), and the definition of computability (in polynomial time or
any time function) of a function between two types that have an encoding (as in `Encoding.lean`).
## Main theorems
- `idComputableInPolyTime` : a TM + a proof it computes the identity on a type in polytime.
- `idComputable` : a TM + a proof it computes the identity on a type.
## Implementation notes
To count the execution time of a Turing machine, we have decided to count the number of times the
`step` function is used. Each step executes a statement (of type `Stmt`); this is a function, and
generally contains multiple "fundamental" steps (pushing, popping, and so on).
However, as functions only contain a finite number of executions and each one is executed at most
once, this execution time is up to multiplication by a constant the amount of fundamental steps.
-/
open Computability
namespace Turing
/-- A bundled TM2 (an equivalent of the classical Turing machine, defined starting from
the namespace `Turing.TM2` in `TuringMachine.lean`), with an input and output stack,
a main function, an initial state and some finiteness guarantees. -/
structure FinTM2 where
/-- index type of stacks -/
{K : Type} [kDecidableEq : DecidableEq K]
/-- A TM2 machine has finitely many stacks. -/
[kFin : Fintype K]
/-- input resp. output stack -/
(k₀ k₁ : K)
/-- type of stack elements -/
(Γ : K → Type)
/-- type of function labels -/
(Λ : Type)
/-- a main function: the initial function that is executed, given by its label -/
(main : Λ)
/-- A TM2 machine has finitely many function labels. -/
[ΛFin : Fintype Λ]
/-- type of states of the machine -/
(σ : Type)
/-- the initial state of the machine -/
(initialState : σ)
/-- a TM2 machine has finitely many internal states. -/
[σFin : Fintype σ]
/-- Each internal stack is finite. -/
[Γk₀Fin : Fintype (Γ k₀)]
/-- the program itself, i.e. one function for every function label -/
(m : Λ → Turing.TM2.Stmt Γ Λ σ)
attribute [nolint docBlame] FinTM2.kDecidableEq
namespace FinTM2
section
variable (tm : FinTM2)
instance decidableEqK : DecidableEq tm.K :=
tm.kDecidableEq
instance inhabitedσ : Inhabited tm.σ :=
⟨tm.initialState⟩
/-- The type of statements (functions) corresponding to this TM. -/
def Stmt : Type :=
Turing.TM2.Stmt tm.Γ tm.Λ tm.σ
instance inhabitedStmt : Inhabited (Stmt tm) :=
inferInstanceAs (Inhabited (Turing.TM2.Stmt tm.Γ tm.Λ tm.σ))
/-- The type of configurations (functions) corresponding to this TM. -/
def Cfg : Type :=
Turing.TM2.Cfg tm.Γ tm.Λ tm.σ
instance inhabitedCfg : Inhabited (Cfg tm) :=
Turing.TM2.Cfg.inhabited _ _ _
/-- The step function corresponding to this TM. -/
@[simp]
def step : tm.Cfg → Option tm.Cfg :=
Turing.TM2.step tm.m
end
end FinTM2
/-- The initial configuration corresponding to a list in the input alphabet. -/
def initList (tm : FinTM2) (s : List (tm.Γ tm.k₀)) : tm.Cfg where
l := Option.some tm.main
var := tm.initialState
stk k :=
@dite (List (tm.Γ k)) (k = tm.k₀) (tm.kDecidableEq k tm.k₀) (fun h => by rw [h]; exact s)
fun _ => []
/-- The final configuration corresponding to a list in the output alphabet. -/
def haltList (tm : FinTM2) (s : List (tm.Γ tm.k₁)) : tm.Cfg where
l := Option.none
var := tm.initialState
stk k :=
@dite (List (tm.Γ k)) (k = tm.k₁) (tm.kDecidableEq k tm.k₁) (fun h => by rw [h]; exact s)
fun _ => []
/-- A "proof" of the fact that `f` eventually reaches `b` when repeatedly evaluated on `a`,
remembering the number of steps it takes. -/
structure EvalsTo {σ : Type*} (f : σ → Option σ) (a : σ) (b : Option σ) where
/-- number of steps taken -/
steps : ℕ
evals_in_steps : (flip bind f)^[steps] a = b
-- note: this cannot currently be used in `calc`, as the last two arguments must be `a` and `b`.
-- If this is desired, this argument order can be changed, but this spelling is I think the most
-- natural, so there is a trade-off that needs to be made here. A notation can get around this.
/-- A "proof" of the fact that `f` eventually reaches `b` in at most `m` steps when repeatedly
evaluated on `a`, remembering the number of steps it takes. -/
structure EvalsToInTime {σ : Type*} (f : σ → Option σ) (a : σ) (b : Option σ) (m : ℕ) extends
EvalsTo f a b where
steps_le_m : steps ≤ m
/-- Reflexivity of `EvalsTo` in 0 steps. -/
def EvalsTo.refl {σ : Type*} (f : σ → Option σ) (a : σ) : EvalsTo f a (some a) :=
⟨0, rfl⟩
/-- Transitivity of `EvalsTo` in the sum of the numbers of steps. -/
@[trans]
def EvalsTo.trans {σ : Type*} (f : σ → Option σ) (a : σ) (b : σ) (c : Option σ)
(h₁ : EvalsTo f a b) (h₂ : EvalsTo f b c) : EvalsTo f a c :=
⟨h₂.steps + h₁.steps, by rw [Function.iterate_add_apply, h₁.evals_in_steps, h₂.evals_in_steps]⟩
/-- Reflexivity of `EvalsToInTime` in 0 steps. -/
def EvalsToInTime.refl {σ : Type*} (f : σ → Option σ) (a : σ) : EvalsToInTime f a (some a) 0 :=
⟨EvalsTo.refl f a, le_refl 0⟩
/-- Transitivity of `EvalsToInTime` in the sum of the numbers of steps. -/
@[trans]
def EvalsToInTime.trans {σ : Type*} (f : σ → Option σ) (m₁ : ℕ) (m₂ : ℕ) (a : σ) (b : σ)
(c : Option σ) (h₁ : EvalsToInTime f a b m₁) (h₂ : EvalsToInTime f b c m₂) :
EvalsToInTime f a c (m₂ + m₁) :=
⟨EvalsTo.trans f a b c h₁.toEvalsTo h₂.toEvalsTo, add_le_add h₂.steps_le_m h₁.steps_le_m⟩
/-- A proof of tm outputting l' when given l. -/
def TM2Outputs (tm : FinTM2) (l : List (tm.Γ tm.k₀)) (l' : Option (List (tm.Γ tm.k₁))) :=
EvalsTo tm.step (initList tm l) ((Option.map (haltList tm)) l')
/-- A proof of tm outputting l' when given l in at most m steps. -/
def TM2OutputsInTime (tm : FinTM2) (l : List (tm.Γ tm.k₀)) (l' : Option (List (tm.Γ tm.k₁)))
(m : ℕ) :=
EvalsToInTime tm.step (initList tm l) ((Option.map (haltList tm)) l') m
/-- The forgetful map, forgetting the upper bound on the number of steps. -/
def TM2OutputsInTime.toTM2Outputs {tm : FinTM2} {l : List (tm.Γ tm.k₀)}
{l' : Option (List (tm.Γ tm.k₁))} {m : ℕ} (h : TM2OutputsInTime tm l l' m) :
TM2Outputs tm l l' :=
h.toEvalsTo
/-- A (bundled TM2) Turing machine
with input alphabet equivalent to `Γ₀` and output alphabet equivalent to `Γ₁`. -/
structure TM2ComputableAux (Γ₀ Γ₁ : Type) where
/-- the underlying bundled TM2 -/
tm : FinTM2
/-- the input alphabet is equivalent to `Γ₀` -/
inputAlphabet : tm.Γ tm.k₀ ≃ Γ₀
/-- the output alphabet is equivalent to `Γ₁` -/
outputAlphabet : tm.Γ tm.k₁ ≃ Γ₁
/-- A Turing machine + a proof it outputs `f`. -/
structure TM2Computable {α β : Type} (ea : FinEncoding α) (eb : FinEncoding β) (f : α → β) extends
TM2ComputableAux ea.Γ eb.Γ where
/-- a proof this machine outputs `f` -/
outputsFun :
∀ a,
TM2Outputs tm (List.map inputAlphabet.invFun (ea.encode a))
(Option.some ((List.map outputAlphabet.invFun) (eb.encode (f a))))
/-- A Turing machine + a time function +
a proof it outputs `f` in at most `time(input.length)` steps. -/
structure TM2ComputableInTime {α β : Type} (ea : FinEncoding α) (eb : FinEncoding β)
(f : α → β) extends TM2ComputableAux ea.Γ eb.Γ where
/-- a time function -/
time : ℕ → ℕ
/-- proof this machine outputs `f` in at most `time(input.length)` steps -/
outputsFun :
∀ a,
TM2OutputsInTime tm (List.map inputAlphabet.invFun (ea.encode a))
(Option.some ((List.map outputAlphabet.invFun) (eb.encode (f a))))
(time (ea.encode a).length)
/-- A Turing machine + a polynomial time function +
a proof it outputs `f` in at most `time(input.length)` steps. -/
structure TM2ComputableInPolyTime {α β : Type} (ea : FinEncoding α) (eb : FinEncoding β)
(f : α → β) extends TM2ComputableAux ea.Γ eb.Γ where
/-- a polynomial time function -/
time : Polynomial ℕ
/-- proof that this machine outputs `f` in at most `time(input.length)` steps -/
outputsFun :
∀ a,
TM2OutputsInTime tm (List.map inputAlphabet.invFun (ea.encode a))
(Option.some ((List.map outputAlphabet.invFun) (eb.encode (f a))))
(time.eval (ea.encode a).length)
/-- A forgetful map, forgetting the time bound on the number of steps. -/
def TM2ComputableInTime.toTM2Computable {α β : Type} {ea : FinEncoding α} {eb : FinEncoding β}
{f : α → β} (h : TM2ComputableInTime ea eb f) : TM2Computable ea eb f :=
⟨h.toTM2ComputableAux, fun a => TM2OutputsInTime.toTM2Outputs (h.outputsFun a)⟩
/-- A forgetful map, forgetting that the time function is polynomial. -/
def TM2ComputableInPolyTime.toTM2ComputableInTime {α β : Type} {ea : FinEncoding α}
{eb : FinEncoding β} {f : α → β} (h : TM2ComputableInPolyTime ea eb f) :
TM2ComputableInTime ea eb f :=
⟨h.toTM2ComputableAux, fun n => h.time.eval n, h.outputsFun⟩
open Turing.TM2.Stmt
/-- A Turing machine computing the identity on α. -/
def idComputer {α : Type} (ea : FinEncoding α) : FinTM2 where
K := Unit
k₀ := ⟨⟩
k₁ := ⟨⟩
Γ _ := ea.Γ
Λ := Unit
main := ⟨⟩
σ := Unit
initialState := ⟨⟩
Γk₀Fin := ea.ΓFin
m _ := halt
instance inhabitedFinTM2 : Inhabited FinTM2 :=
⟨idComputer Computability.inhabitedFinEncoding.default⟩
noncomputable section
/-- A proof that the identity map on α is computable in polytime. -/
def idComputableInPolyTime {α : Type} (ea : FinEncoding α) :
@TM2ComputableInPolyTime α α ea ea id where
tm := idComputer ea
inputAlphabet := Equiv.cast rfl
outputAlphabet := Equiv.cast rfl
time := 1
outputsFun _ :=
{ steps := 1
evals_in_steps := rfl
steps_le_m := by simp only [Polynomial.eval_one, le_refl] }
instance inhabitedTM2ComputableInPolyTime :
Inhabited (TM2ComputableInPolyTime (default : FinEncoding Bool) default id) :=
⟨idComputableInPolyTime Computability.inhabitedFinEncoding.default⟩
instance inhabitedTM2OutputsInTime :
Inhabited
(TM2OutputsInTime (idComputer finEncodingBoolBool) (List.map (Equiv.cast rfl).invFun [false])
(some (List.map (Equiv.cast rfl).invFun [false])) (Polynomial.eval 1 1)) :=
⟨(idComputableInPolyTime finEncodingBoolBool).outputsFun false⟩
instance inhabitedTM2Outputs :
Inhabited
(TM2Outputs (idComputer finEncodingBoolBool) (List.map (Equiv.cast rfl).invFun [false])
(some (List.map (Equiv.cast rfl).invFun [false]))) :=
⟨TM2OutputsInTime.toTM2Outputs Turing.inhabitedTM2OutputsInTime.default⟩
instance inhabitedEvalsToInTime :
Inhabited (EvalsToInTime (fun _ : Unit => some ⟨⟩) ⟨⟩ (some ⟨⟩) 0) :=
⟨EvalsToInTime.refl _ _⟩
instance inhabitedTM2EvalsTo : Inhabited (EvalsTo (fun _ : Unit => some ⟨⟩) ⟨⟩ (some ⟨⟩)) :=
⟨EvalsTo.refl _ _⟩
/-- A proof that the identity map on α is computable in time. -/
def idComputableInTime {α : Type} (ea : FinEncoding α) : @TM2ComputableInTime α α ea ea id :=
TM2ComputableInPolyTime.toTM2ComputableInTime <| idComputableInPolyTime ea
instance inhabitedTM2ComputableInTime :
Inhabited (TM2ComputableInTime finEncodingBoolBool finEncodingBoolBool id) :=
⟨idComputableInTime Computability.inhabitedFinEncoding.default⟩
/-- A proof that the identity map on α is computable. -/
def idComputable {α : Type} (ea : FinEncoding α) : @TM2Computable α α ea ea id :=
TM2ComputableInTime.toTM2Computable <| idComputableInTime ea
instance inhabitedTM2Computable :
Inhabited (TM2Computable finEncodingBoolBool finEncodingBoolBool id) :=
⟨idComputable Computability.inhabitedFinEncoding.default⟩
instance inhabitedTM2ComputableAux : Inhabited (TM2ComputableAux Bool Bool) :=
⟨(default : TM2Computable finEncodingBoolBool finEncodingBoolBool id).toTM2ComputableAux⟩
/--
For any two polynomial time Multi-tape Turing Machines,
there exists another polynomial time multi-tape Turing Machine that composes their operations.
This machine can work by simply having one tape for each tape in both of the composed TMs.
It first carries out the operations of the first TM on the tapes associated with the first TM,
then copies the output tape of the first TM to the input tape of the second TM,
then runs the second TM.
-/
proof_wanted TM2ComputableInPolyTime.comp
{α β γ : Type} {eα : FinEncoding α} {eβ : FinEncoding β}
{eγ : FinEncoding γ} {f : α → β} {g : β → γ} (h1 : TM2ComputableInPolyTime eα eβ f)
(h2 : TM2ComputableInPolyTime eβ eγ g) :
Nonempty (TM2ComputableInPolyTime eα eγ (g ∘ f))
end
end Turing |
.lake/packages/mathlib/Mathlib/Computability/Primrec.lean | import Mathlib.Algebra.Order.Ring.Nat
import Mathlib.Logic.Encodable.Pi
import Mathlib.Logic.Function.Iterate
/-!
# The primitive recursive functions
The primitive recursive functions are the least collection of functions
`ℕ → ℕ` which are closed under projections (using the `pair`
pairing function), composition, zero, successor, and primitive recursion
(i.e. `Nat.rec` where the motive is `C n := ℕ`).
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.)
In the above, the pairing function is primitive recursive by definition.
This deviates from the textbook definition of primitive recursive functions,
which instead work with *`n`-ary* functions. We formalize the textbook
definition in `Nat.Primrec'`. `Nat.Primrec'.prim_iff` then proves it is
equivalent to our chosen formulation. For more discussion of this and
other design choices in this formalization, see [carneiro2019].
## Main definitions
- `Nat.Primrec f`: `f` is primitive recursive, for functions `f : ℕ → ℕ`
- `Primrec f`: `f` is primitive recursive, for functions between `Primcodable` types
- `Primcodable α`: well-behaved encoding of `α` into `ℕ`, i.e. one such that roundtripping through
the encoding functions adds no computational power
## References
* [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019]
-/
open List (Vector)
open Denumerable Encodable Function
namespace Nat
/-- Calls the given function on a pair of entries `n`, encoded via the pairing function. -/
@[simp, reducible]
def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α :=
f n.unpair.1 n.unpair.2
/-- The primitive recursive functions `ℕ → ℕ`. -/
protected inductive Primrec : (ℕ → ℕ) → Prop
| zero : Nat.Primrec fun _ => 0
| protected succ : Nat.Primrec succ
| left : Nat.Primrec fun n => n.unpair.1
| right : Nat.Primrec fun n => n.unpair.2
| pair {f g} : Nat.Primrec f → Nat.Primrec g → Nat.Primrec fun n => pair (f n) (g n)
| comp {f g} : Nat.Primrec f → Nat.Primrec g → Nat.Primrec fun n => f (g n)
| prec {f g} :
Nat.Primrec f →
Nat.Primrec g →
Nat.Primrec (unpaired fun z n => n.rec (f z) fun y IH => g <| pair z <| pair y IH)
namespace Primrec
theorem of_eq {f g : ℕ → ℕ} (hf : Nat.Primrec f) (H : ∀ n, f n = g n) : Nat.Primrec g :=
(funext H : f = g) ▸ hf
theorem const : ∀ n : ℕ, Nat.Primrec fun _ => n
| 0 => zero
| n + 1 => Primrec.succ.comp (const n)
protected theorem id : Nat.Primrec id :=
(left.pair right).of_eq fun n => by simp
theorem prec1 {f} (m : ℕ) (hf : Nat.Primrec f) :
Nat.Primrec fun n => n.rec m fun y IH => f <| Nat.pair y IH :=
((prec (const m) (hf.comp right)).comp (zero.pair Primrec.id)).of_eq fun n => by simp
theorem casesOn1 {f} (m : ℕ) (hf : Nat.Primrec f) : Nat.Primrec (Nat.casesOn · m f) :=
(prec1 m (hf.comp left)).of_eq <| by simp
theorem casesOn' {f g} (hf : Nat.Primrec f) (hg : Nat.Primrec g) :
Nat.Primrec (unpaired fun z n => n.casesOn (f z) fun y => g <| Nat.pair z y) :=
(prec hf (hg.comp (pair left (left.comp right)))).of_eq fun n => by simp
protected theorem swap : Nat.Primrec (unpaired (swap Nat.pair)) :=
(pair right left).of_eq fun n => by simp
theorem swap' {f} (hf : Nat.Primrec (unpaired f)) : Nat.Primrec (unpaired (swap f)) :=
(hf.comp .swap).of_eq fun n => by simp
theorem pred : Nat.Primrec pred :=
(casesOn1 0 Primrec.id).of_eq fun n => by cases n <;> simp [*]
theorem add : Nat.Primrec (unpaired (· + ·)) :=
(prec .id ((Primrec.succ.comp right).comp right)).of_eq fun p => by
simp; induction p.unpair.2 <;> simp [*, Nat.add_assoc]
theorem sub : Nat.Primrec (unpaired (· - ·)) :=
(prec .id ((pred.comp right).comp right)).of_eq fun p => by
simp; induction p.unpair.2 <;> simp [*, Nat.sub_add_eq]
theorem mul : Nat.Primrec (unpaired (· * ·)) :=
(prec zero (add.comp (pair left (right.comp right)))).of_eq fun p => by
simp; induction p.unpair.2 <;> simp [*, mul_succ, add_comm _ (unpair p).fst]
theorem pow : Nat.Primrec (unpaired (· ^ ·)) :=
(prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq fun p => by
simp; induction p.unpair.2 <;> simp [*, Nat.pow_succ]
end Primrec
end Nat
/-- A `Primcodable` type is, essentially, an `Encodable` type for which
the encode/decode functions are primitive recursive.
However, such a definition is circular.
Instead, we ask that the composition of `decode : ℕ → Option α` with
`encode : Option α → ℕ` is primitive recursive. Said composition is
the identity function, restricted to the image of `encode`.
Thus, in a way, the added requirement ensures that no predicates
can be smuggled in through a cunning choice of the subset of `ℕ` into
which the type is encoded. -/
class Primcodable (α : Type*) extends Encodable α where
prim (α) : Nat.Primrec fun n => Encodable.encode (decode n)
namespace Primcodable
open Nat.Primrec
instance (priority := 10) ofDenumerable (α) [Denumerable α] : Primcodable α :=
⟨Nat.Primrec.succ.of_eq <| by simp⟩
/-- Builds a `Primcodable` instance from an equivalence to a `Primcodable` type. -/
def ofEquiv (α) {β} [Primcodable α] (e : β ≃ α) : Primcodable β :=
{ __ := Encodable.ofEquiv α e
prim := (Primcodable.prim α).of_eq fun n => by
rw [decode_ofEquiv]
cases (@decode α _ n) <;>
simp [encode_ofEquiv] }
instance empty : Primcodable Empty :=
⟨zero⟩
instance unit : Primcodable PUnit :=
⟨(casesOn1 1 zero).of_eq fun n => by cases n <;> simp⟩
instance option {α : Type*} [h : Primcodable α] : Primcodable (Option α) :=
⟨(casesOn1 1 ((casesOn1 0 (.comp .succ .succ)).comp (Primcodable.prim α))).of_eq fun n => by
cases n with
| zero => rfl
| succ n =>
rw [decode_option_succ]
cases H : @decode α _ n <;> simp [H]⟩
instance bool : Primcodable Bool :=
⟨(casesOn1 1 (casesOn1 2 zero)).of_eq fun n => match n with
| 0 => rfl
| 1 => rfl
| (n + 2) => by rw [decode_ge_two] <;> simp⟩
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 fun n => encode ((@decode α _ n).map f)
namespace Primrec
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
open Nat.Primrec
protected theorem encode : Primrec (@encode α _) :=
(Primcodable.prim α).of_eq fun n => by cases @decode α _ n <;> rfl
protected theorem decode : Primrec (@decode α _) :=
Nat.Primrec.succ.comp (Primcodable.prim α)
theorem dom_denumerable {α β} [Denumerable α] [Primcodable β] {f : α → β} :
Primrec f ↔ Nat.Primrec fun n => encode (f (ofNat α n)) :=
⟨fun h => (pred.comp h).of_eq fun n => by simp, fun h =>
(Nat.Primrec.succ.comp h).of_eq fun n => by simp⟩
theorem nat_iff {f : ℕ → ℕ} : Primrec f ↔ Nat.Primrec f :=
dom_denumerable
theorem encdec : Primrec fun n => encode (@decode α _ n) :=
nat_iff.2 (Primcodable.prim _)
theorem option_some : Primrec (@some α) :=
((casesOn1 0 (Nat.Primrec.succ.comp .succ)).comp (Primcodable.prim α)).of_eq fun 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 fun _ : α => x :=
((casesOn1 0 (.const (encode x).succ)).comp (Primcodable.prim α)).of_eq fun n => by
cases @decode α _ n <;> rfl
protected theorem id : Primrec (@id α) :=
(Primcodable.prim α).of_eq <| by simp
theorem comp {f : β → σ} {g : α → β} (hf : Primrec f) (hg : Primrec g) : Primrec fun a => f (g a) :=
((casesOn1 0 (.comp hf (pred.comp hg))).comp (Primcodable.prim α)).of_eq fun n => by
cases @decode α _ n <;> simp [encodek]
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 fun a => encode (f a)) ↔ Primrec f :=
⟨fun h => Nat.Primrec.of_eq h fun n => by cases @decode α _ n <;> rfl, Primrec.encode.comp⟩
theorem ofNat_iff {α β} [Denumerable α] [Primcodable β] {f : α → β} :
Primrec f ↔ Primrec fun n => f (ofNat α n) :=
dom_denumerable.trans <| nat_iff.symm.trans encode_iff
protected theorem ofNat (α) [Denumerable α] : Primrec (ofNat α) :=
ofNat_iff.1 Primrec.id
theorem option_some_iff {f : α → σ} : (Primrec fun a => some (f a)) ↔ Primrec f :=
⟨fun h => encode_iff.1 <| pred.comp <| encode_iff.2 h, option_some.comp⟩
theorem of_equiv {β} {e : β ≃ α} :
haveI := Primcodable.ofEquiv α e
Primrec e :=
letI : Primcodable β := Primcodable.ofEquiv α e
encode_iff.1 Primrec.encode
theorem of_equiv_symm {β} {e : β ≃ α} :
haveI := Primcodable.ofEquiv α e
Primrec e.symm :=
letI := Primcodable.ofEquiv α e
encode_iff.1 (show Primrec fun a => encode (e (e.symm a)) by simp [Primrec.encode])
theorem of_equiv_iff {β} (e : β ≃ α) {f : σ → β} :
haveI := Primcodable.ofEquiv α e
(Primrec fun a => e (f a)) ↔ Primrec f :=
letI := Primcodable.ofEquiv α e
⟨fun h => (of_equiv_symm.comp h).of_eq fun a => by simp, of_equiv.comp⟩
theorem of_equiv_symm_iff {β} (e : β ≃ α) {f : σ → α} :
haveI := Primcodable.ofEquiv α e
(Primrec fun a => e.symm (f a)) ↔ Primrec f :=
letI := Primcodable.ofEquiv α e
⟨fun h => (of_equiv.comp h).of_eq fun a => by simp, of_equiv_symm.comp⟩
end Primrec
namespace Primcodable
open Nat.Primrec
instance prod {α β} [Primcodable α] [Primcodable β] : Primcodable (α × β) :=
⟨((casesOn' zero ((casesOn' zero .succ).comp (pair right ((Primcodable.prim β).comp left)))).comp
(pair right ((Primcodable.prim α).comp left))).of_eq
fun n => by
simp only [Nat.unpaired, Nat.unpair_pair, decode_prod_val]
cases @decode α _ n.unpair.1; · simp
cases @decode β _ n.unpair.2 <;> simp⟩
end Primcodable
namespace Primrec
variable {α : Type*} [Primcodable α]
open Nat.Primrec
theorem fst {α β} [Primcodable α] [Primcodable β] : Primrec (@Prod.fst α β) :=
((casesOn' zero
((casesOn' zero (Nat.Primrec.succ.comp left)).comp
(pair right ((Primcodable.prim β).comp left)))).comp
(pair right ((Primcodable.prim α).comp left))).of_eq
fun n => by
simp only [Nat.unpaired, Nat.unpair_pair, decode_prod_val]
cases @decode α _ n.unpair.1 <;> simp
cases @decode β _ n.unpair.2 <;> simp
theorem snd {α β} [Primcodable α] [Primcodable β] : Primrec (@Prod.snd α β) :=
((casesOn' zero
((casesOn' zero (Nat.Primrec.succ.comp right)).comp
(pair right ((Primcodable.prim β).comp left)))).comp
(pair right ((Primcodable.prim α).comp left))).of_eq
fun n => by
simp only [Nat.unpaired, Nat.unpair_pair, decode_prod_val]
cases @decode α _ n.unpair.1 <;> simp
cases @decode β _ n.unpair.2 <;> simp
theorem pair {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {f : α → β} {g : α → γ}
(hf : Primrec f) (hg : Primrec g) : Primrec fun a => (f a, g a) :=
((casesOn1 0
(Nat.Primrec.succ.comp <|
.pair (Nat.Primrec.pred.comp hf) (Nat.Primrec.pred.comp hg))).comp
(Primcodable.prim α)).of_eq
fun n => by cases @decode α _ n <;> simp [encodek]
theorem unpair : Primrec Nat.unpair :=
(pair (nat_iff.2 .left) (nat_iff.2 .right)).of_eq fun n => by simp
theorem list_getElem?₁ : ∀ l : List α, Primrec (l[·]? : ℕ → Option α)
| [] => dom_denumerable.2 zero
| a :: l =>
dom_denumerable.2 <|
(casesOn1 (encode a).succ <| dom_denumerable.1 <| list_getElem?₁ l).of_eq fun 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 fun p : α × β => f p.1 p.2
/-- `PrimrecPred p` means `p : α → Prop` is a
primitive recursive predicate, which is to say that
`decide ∘ p : α → Bool` is primitive recursive. -/
def PrimrecPred {α} [Primcodable α] (p : α → Prop) :=
∃ (_ : DecidablePred p), Primrec fun a => decide (p a)
/-- `PrimrecRel p` means `p : α → β → Prop` is a
primitive recursive relation, which is to say that
`decide ∘ p : α → β → Bool` is primitive recursive. -/
def PrimrecRel {α β} [Primcodable α] [Primcodable β] (s : α → β → Prop) :=
PrimrecPred fun p : α × β => s p.1 p.2
namespace Primrec₂
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
theorem mk {f : α → β → σ} (hf : Primrec fun p : α × β => f p.1 p.2) : Primrec₂ f := hf
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₂ fun (_ : α) (_ : β) => x :=
Primrec.const _
protected theorem pair : Primrec₂ (@Prod.mk α β) :=
Primrec.pair .fst .snd
theorem left : Primrec₂ fun (a : α) (_ : β) => a :=
.fst
theorem right : Primrec₂ fun (_ : α) (b : β) => b :=
.snd
theorem natPair : Primrec₂ Nat.pair := by simp [Primrec₂, Primrec]; constructor
theorem unpaired {f : ℕ → ℕ → α} : Primrec (Nat.unpaired f) ↔ Primrec₂ f :=
⟨fun h => by simpa using h.comp natPair, fun 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₂ fun a b => encode (f a b)) ↔ Primrec₂ f :=
Primrec.encode_iff
theorem option_some_iff {f : α → β → σ} : (Primrec₂ fun a b => some (f a b)) ↔ Primrec₂ f :=
Primrec.option_some_iff
theorem ofNat_iff {α β σ} [Denumerable α] [Denumerable β] [Primcodable σ] {f : α → β → σ} :
Primrec₂ f ↔ Primrec₂ fun m n : ℕ => f (ofNat α m) (ofNat β n) :=
(Primrec.ofNat_iff.trans <| by simp).trans unpaired
theorem uncurry {f : α → β → σ} : Primrec (Function.uncurry f) ↔ Primrec₂ f := by
rw [show Function.uncurry f = fun p : α × β => f p.1 p.2 from funext fun ⟨a, b⟩ => rfl]; rfl
theorem curry {f : α × β → σ} : Primrec₂ (Function.curry f) ↔ Primrec f := by
rw [← uncurry, Function.uncurry_curry]
end Primrec₂
section Comp
variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable δ] [Primcodable σ]
theorem Primrec.comp₂ {f : γ → σ} {g : α → β → γ} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec₂ fun 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 fun a => f (g a) (h a) :=
Primrec.comp hf (hg.pair hh)
theorem Primrec₂.comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : Primrec₂ f)
(hg : Primrec₂ g) (hh : Primrec₂ h) : Primrec₂ fun a b => f (g a b) (h a b) :=
hf.comp hg hh
protected lemma PrimrecPred.decide {p : α → Prop} [DecidablePred p] (hp : PrimrecPred p) :
Primrec (fun a => decide (p a)) := by
convert hp.choose_spec
lemma Primrec.primrecPred {p : α → Prop} [DecidablePred p]
(hp : Primrec (fun a => decide (p a))) : PrimrecPred p :=
⟨inferInstance, hp⟩
lemma primrecPred_iff_primrec_decide {p : α → Prop} [DecidablePred p] :
PrimrecPred p ↔ Primrec (fun a => decide (p a)) where
mp := PrimrecPred.decide
mpr := Primrec.primrecPred
theorem PrimrecPred.comp {p : β → Prop} {f : α → β} :
(hp : PrimrecPred p) → (hf : Primrec f) → PrimrecPred fun a => p (f a)
| ⟨_i, hp⟩, hf => hp.comp hf |>.primrecPred
protected lemma PrimrecRel.decide {R : α → β → Prop} [DecidableRel R] (hR : PrimrecRel R) :
Primrec₂ (fun a b => decide (R a b)) :=
PrimrecPred.decide hR
lemma Primrec₂.primrecRel {R : α → β → Prop} [DecidableRel R]
(hp : Primrec₂ (fun a b => decide (R a b))) : PrimrecRel R :=
Primrec.primrecPred hp
lemma primrecRel_iff_primrec_decide {R : α → β → Prop} [DecidableRel R] :
PrimrecRel R ↔ Primrec₂ (fun a b => decide (R a b)) where
mp := PrimrecRel.decide
mpr := Primrec₂.primrecRel
theorem PrimrecRel.comp {R : β → γ → Prop} {f : α → β} {g : α → γ}
(hR : PrimrecRel R) (hf : Primrec f) (hg : Primrec g) : PrimrecPred fun a => R (f a) (g a) :=
PrimrecPred.comp hR (hf.pair hg)
theorem PrimrecRel.comp₂ {R : γ → δ → Prop} {f : α → β → γ} {g : α → β → δ} :
PrimrecRel R → Primrec₂ f → Primrec₂ g → PrimrecRel fun a b => R (f a b) (g a b) :=
PrimrecRel.comp
end Comp
theorem PrimrecPred.of_eq {α} [Primcodable α] {p q : α → Prop}
(hp : PrimrecPred p) (H : ∀ a, p a ↔ q a) : PrimrecPred q :=
funext (fun a => propext (H a)) ▸ hp
theorem PrimrecRel.of_eq {α β} [Primcodable α] [Primcodable β] {r s : α → β → Prop}
(hr : PrimrecRel r) (H : ∀ a b, r a b ↔ s a b) : PrimrecRel s :=
funext₂ (fun a b => propext (H a b)) ▸ hr
namespace Primrec₂
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
open Nat.Primrec
protected theorem swap {f : α → β → σ} (h : Primrec₂ f) : Primrec₂ (swap f) :=
h.comp₂ Primrec₂.right Primrec₂.left
protected theorem _root_.PrimrecRel.swap {r : α → β → Prop} (h : PrimrecRel r) :
PrimrecRel (swap r) :=
h.comp₂ Primrec₂.right Primrec₂.left
theorem nat_iff {f : α → β → σ} : Primrec₂ f ↔ Nat.Primrec
(.unpaired fun m n => encode <| (@decode α _ m).bind fun a => (@decode β _ n).map (f a)) := by
have :
∀ (a : Option α) (b : Option β),
Option.map (fun p : α × β => f p.1 p.2)
(Option.bind a fun a : α => Option.map (Prod.mk a) b) =
Option.bind a fun a => Option.map (f a) b := fun a b => by
cases a <;> cases b <;> rfl
simp [Primrec₂, Primrec, this]
theorem nat_iff' {f : α → β → σ} :
Primrec₂ f ↔
Primrec₂ fun m n : ℕ => (@decode α _ m).bind fun a => Option.map (f a) (@decode β _ n) :=
nat_iff.trans <| unpaired'.trans encode_iff
end Primrec₂
namespace Primrec
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
theorem to₂ {f : α × β → σ} (hf : Primrec f) : Primrec₂ fun a b => f (a, b) :=
hf
lemma _root_.PrimrecPred.primrecRel {p : α × β → Prop} (hp : PrimrecPred p) :
PrimrecRel fun a b => p (a, b) :=
hp
theorem nat_rec {f : α → β} {g : α → ℕ × β → β} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec₂ fun a (n : ℕ) => n.rec (motive := fun _ => β) (f a) fun n IH => g a (n, IH) :=
Primrec₂.nat_iff.2 <|
((Nat.Primrec.casesOn' .zero <|
(Nat.Primrec.prec hf <|
.comp hg <|
Nat.Primrec.left.pair <|
(Nat.Primrec.left.comp .right).pair <|
Nat.Primrec.pred.comp <| Nat.Primrec.right.comp .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
fun n => by
simp only [Nat.unpaired, id_eq, Nat.unpair_pair, decode_prod_val, decode_nat,
Option.bind_some, Option.map_map, Option.map_some]
rcases @decode α _ n.unpair.1 with - | a; · rfl
simp only [Nat.pred_eq_sub_one, encode_some, Nat.succ_eq_add_one, encodek, Option.map_some,
Option.bind_some, Option.map_map]
induction n.unpair.2 <;> simp [*, encodek]
theorem nat_rec' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β}
(hf : Primrec f) (hg : Primrec g) (hh : Primrec₂ h) :
Primrec fun a => (f a).rec (motive := fun _ => β) (g a) fun n IH => h a (n, IH) :=
(nat_rec hg hh).comp .id hf
theorem nat_rec₁ {f : ℕ → α → α} (a : α) (hf : Primrec₂ f) : Primrec (Nat.rec a f) :=
nat_rec' .id (const a) <| comp₂ hf Primrec₂.right
theorem nat_casesOn' {f : α → β} {g : α → ℕ → β} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec₂ fun a (n : ℕ) => (n.casesOn (f a) (g a) : β) :=
nat_rec hf <| hg.comp₂ Primrec₂.left <| comp₂ fst Primrec₂.right
theorem nat_casesOn {f : α → ℕ} {g : α → β} {h : α → ℕ → β} (hf : Primrec f) (hg : Primrec g)
(hh : Primrec₂ h) : Primrec fun a => ((f a).casesOn (g a) (h a) : β) :=
(nat_casesOn' hg hh).comp .id hf
theorem nat_casesOn₁ {f : ℕ → α} (a : α) (hf : Primrec f) :
Primrec (fun (n : ℕ) => (n.casesOn a f : α)) :=
nat_casesOn .id (const a) (comp₂ hf .right)
theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β} (hf : Primrec f) (hg : Primrec g)
(hh : Primrec₂ h) : Primrec fun a => (h a)^[f a] (g a) :=
(nat_rec' hf hg (hh.comp₂ Primrec₂.left <| snd.comp₂ Primrec₂.right)).of_eq fun a => by
induction f a <;> simp [*, -Function.iterate_succ, Function.iterate_succ']
theorem option_casesOn {o : α → Option β} {f : α → σ} {g : α → β → σ} (ho : Primrec o)
(hf : Primrec f) (hg : Primrec₂ g) :
@Primrec _ σ _ _ fun a => Option.casesOn (o a) (f a) (g a) :=
encode_iff.1 <|
(nat_casesOn (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
fun a => by rcases o a with - | b <;> simp [encodek]
theorem option_bind {f : α → Option β} {g : α → β → Option σ} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec fun a => (f a).bind (g a) :=
(option_casesOn hf (const none) hg).of_eq fun a => by cases f a <;> rfl
theorem option_bind₁ {f : α → Option σ} (hf : Primrec f) : Primrec fun o => Option.bind o f :=
option_bind .id (hf.comp snd).to₂
theorem option_map {f : α → Option β} {g : α → β → σ} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec fun a => (f a).map (g a) :=
(option_bind hf (option_some.comp₂ hg)).of_eq fun x => by cases f x <;> rfl
theorem option_map₁ {f : α → σ} (hf : Primrec f) : Primrec (Option.map f) :=
option_map .id (hf.comp snd).to₂
theorem option_iget [Inhabited α] : Primrec (@Option.iget α _) :=
(option_casesOn .id (const <| @default α _) .right).of_eq fun o => by cases o <;> rfl
theorem option_isSome : Primrec (@Option.isSome α) :=
(option_casesOn .id (const false) (const true).to₂).of_eq fun o => by cases o <;> rfl
theorem option_getD : Primrec₂ (@Option.getD α) :=
Primrec.of_eq (option_casesOn Primrec₂.left Primrec₂.right .right) fun ⟨o, a⟩ => by
cases o <;> rfl
theorem bind_decode_iff {f : α → β → Option σ} :
(Primrec₂ fun a n => (@decode β _ n).bind (f a)) ↔ Primrec₂ f :=
⟨fun h => by simpa [encodek] using h.comp fst ((@Primrec.encode β _).comp snd), fun h =>
option_bind (Primrec.decode.comp snd) <| h.comp (fst.comp fst) snd⟩
theorem map_decode_iff {f : α → β → σ} :
(Primrec₂ fun a n => (@decode β _ n).map (f a)) ↔ Primrec₂ f := by
simp only [Option.map_eq_bind]
exact bind_decode_iff.trans Primrec₂.option_some_iff
theorem nat_add : Primrec₂ ((· + ·) : ℕ → ℕ → ℕ) :=
Primrec₂.unpaired'.1 Nat.Primrec.add
theorem nat_sub : Primrec₂ ((· - ·) : ℕ → ℕ → ℕ) :=
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 fun a => bif (c a) then (f a) else (g a) :=
(nat_casesOn (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq fun a => by cases c a <;> rfl
theorem ite {c : α → Prop} [DecidablePred c] {f : α → σ} {g : α → σ} (hc : PrimrecPred c)
(hf : Primrec f) (hg : Primrec g) : Primrec fun a => if c a then f a else g a := by
simpa [Bool.cond_decide] using cond hc.decide hf hg
theorem nat_le : PrimrecRel ((· ≤ ·) : ℕ → ℕ → Prop) :=
Primrec₂.primrecRel ((nat_casesOn nat_sub (const true) (const false).to₂).of_eq fun p => by
dsimp [swap]
rcases 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)])
theorem nat_min : Primrec₂ (@min ℕ _) :=
ite nat_le fst snd
theorem nat_max : Primrec₂ (@max ℕ _) :=
ite (nat_le.comp fst snd) snd fst
theorem dom_bool (f : Bool → α) : Primrec f :=
(cond .id (const (f true)) (const (f false))).of_eq fun b => by cases b <;> rfl
theorem dom_bool₂ (f : Bool → Bool → α) : Primrec₂ f :=
(cond fst ((dom_bool (f true)).comp snd) ((dom_bool (f false)).comp snd)).of_eq fun ⟨a, b⟩ => by
cases a <;> rfl
protected theorem not : Primrec not :=
dom_bool _
protected theorem and : Primrec₂ and :=
dom_bool₂ _
protected theorem or : Primrec₂ or :=
dom_bool₂ _
protected theorem _root_.PrimrecPred.not {p : α → Prop} :
(hp : PrimrecPred p) → PrimrecPred fun a => ¬p a
| ⟨_, hp⟩ => Primrec.primrecPred <| Primrec.not.comp hp |>.of_eq <| by simp
protected theorem _root_.PrimrecPred.and {p q : α → Prop} :
(hp : PrimrecPred p) → (hq : PrimrecPred q) → PrimrecPred fun a => p a ∧ q a
| ⟨_, hp⟩, ⟨_, hq⟩ => Primrec.primrecPred <| Primrec.and.comp hp hq |>.of_eq <| by simp
protected theorem _root_.PrimrecPred.or {p q : α → Prop} :
(hp : PrimrecPred p) → (hq : PrimrecPred q) → PrimrecPred fun a => p a ∨ q a
| ⟨_, hp⟩, ⟨_, hq⟩ => Primrec.primrecPred <| Primrec.or.comp hp hq |>.of_eq <| by simp
protected theorem eq : PrimrecRel (@Eq α) :=
have : PrimrecRel fun a b : ℕ => a = b :=
(PrimrecPred.and nat_le nat_le.swap).of_eq fun a => by simp [le_antisymm_iff]
(this.decide.comp₂ (Primrec.encode.comp₂ Primrec₂.left)
(Primrec.encode.comp₂ Primrec₂.right)).primrecRel.of_eq
fun _ _ => encode_injective.eq_iff
protected theorem beq [DecidableEq α] : Primrec₂ (@BEq.beq α _) := Primrec.eq.decide
theorem nat_lt : PrimrecRel ((· < ·) : ℕ → ℕ → Prop) :=
(nat_le.comp snd fst).not.of_eq fun p => by simp
theorem option_guard {p : α → β → Prop} [DecidableRel p] (hp : PrimrecRel p) {f : α → β}
(hf : Primrec f) : Primrec fun a => Option.guard (p a) (f a) :=
ite (by simpa using hp.comp Primrec.id hf) (option_some_iff.2 hf) (const none)
theorem option_orElse : Primrec₂ ((· <|> ·) : Option α → Option α → Option α) :=
(option_casesOn fst snd (fst.comp fst).to₂).of_eq fun ⟨o₁, o₂⟩ => by cases o₁ <;> cases o₂ <;> rfl
protected theorem decode₂ : Primrec (decode₂ α) :=
option_bind .decode <|
option_guard (Primrec.eq.comp₂ (by exact encode_iff.mpr snd) (by exact fst.comp fst)) snd
theorem list_findIdx₁ {p : α → β → Bool} (hp : Primrec₂ p) :
∀ l : List β, Primrec fun a => l.findIdx (p a)
| [] => const 0
| a :: l => (cond (hp.comp .id (const a)) (const 0) (succ.comp (list_findIdx₁ hp l))).of_eq fun n =>
by simp [List.findIdx_cons]
theorem list_idxOf₁ [DecidableEq α] (l : List α) : Primrec fun a => l.idxOf a :=
list_findIdx₁ (.swap .beq) l
theorem dom_finite [Finite α] (f : α → σ) : Primrec f :=
let ⟨l, _, m⟩ := Finite.exists_univ_list α
option_some_iff.1 <| by
haveI := decidableEqOfEncodable α
refine ((list_getElem?₁ (l.map f)).comp (list_idxOf₁ l)).of_eq fun a => ?_
rw [List.getElem?_map, List.getElem?_idxOf (m a), Option.map_some]
@[deprecated (since := "2025-08-23")] alias dom_fintype := dom_finite
/-- A function is `PrimrecBounded` if its size is bounded by a primitive recursive function -/
def PrimrecBounded (f : α → β) : Prop :=
∃ g : α → ℕ, Primrec g ∧ ∀ x, encode (f x) ≤ g x
theorem nat_findGreatest {f : α → ℕ} {p : α → ℕ → Prop} [DecidableRel p]
(hf : Primrec f) (hp : PrimrecRel p) : Primrec fun x => (f x).findGreatest (p x) :=
(nat_rec' (h := fun x nih => if p x (nih.1 + 1) then nih.1 + 1 else nih.2)
hf (const 0) (ite (hp.comp fst (snd |> fst.comp |> succ.comp))
(snd |> fst.comp |> succ.comp) (snd.comp snd))).of_eq fun x => by
induction f x <;> simp [Nat.findGreatest, *]
/-- To show a function `f : α → ℕ` is primitive recursive, it is enough to show that the function
is bounded by a primitive recursive function and that its graph is primitive recursive -/
theorem of_graph {f : α → ℕ} (h₁ : PrimrecBounded f)
(h₂ : PrimrecRel fun a b => f a = b) : Primrec f := by
rcases h₁ with ⟨g, pg, hg : ∀ x, f x ≤ g x⟩
refine (nat_findGreatest pg h₂).of_eq fun n => ?_
exact (Nat.findGreatest_spec (P := fun b => f n = b) (hg n) rfl).symm
-- We show that division is primitive recursive by showing that the graph is
theorem nat_div : Primrec₂ ((· / ·) : ℕ → ℕ → ℕ) := by
refine of_graph ⟨_, fst, fun p => Nat.div_le_self _ _⟩ ?_
have : PrimrecRel fun (a : ℕ × ℕ) (b : ℕ) => (a.2 = 0 ∧ b = 0) ∨
(0 < a.2 ∧ b * a.2 ≤ a.1 ∧ a.1 < (b + 1) * a.2) :=
PrimrecPred.or
(.and (const 0 |> Primrec.eq.comp (fst |> snd.comp)) (const 0 |> Primrec.eq.comp snd))
(.and (nat_lt.comp (const 0) (fst |> snd.comp)) <|
.and (nat_le.comp (nat_mul.comp snd (fst |> snd.comp)) (fst |> fst.comp))
(nat_lt.comp (fst.comp fst) (nat_mul.comp (Primrec.succ.comp snd) (snd.comp fst))))
refine this.of_eq ?_
rintro ⟨a, k⟩ q
if H : k = 0 then simp [H, eq_comm]
else
have : q * k ≤ a ∧ a < (q + 1) * k ↔ q = a / k := by
rw [le_antisymm_iff, ← (@Nat.lt_succ _ q), Nat.le_div_iff_mul_le (Nat.pos_of_ne_zero H),
Nat.div_lt_iff_lt_mul (Nat.pos_of_ne_zero H)]
simpa [H, zero_lt_iff, eq_comm (b := q)]
theorem nat_mod : Primrec₂ ((· % ·) : ℕ → ℕ → ℕ) :=
(nat_sub.comp fst (nat_mul.comp snd nat_div)).to₂.of_eq fun m n => by
apply Nat.sub_eq_of_eq_add
simp [add_comm (m % n), Nat.div_add_mod]
theorem nat_bodd : Primrec Nat.bodd :=
(Primrec.beq.comp (nat_mod.comp .id (const 2)) (const 1)).of_eq fun n => by
cases H : n.bodd <;> simp [Nat.mod_two_of_bodd, H]
theorem nat_div2 : Primrec Nat.div2 :=
(nat_div.comp .id (const 2)).of_eq fun n => n.div2_val.symm
theorem nat_double : Primrec (fun n : ℕ => 2 * n) :=
nat_mul.comp (const _) Primrec.id
theorem nat_double_succ : Primrec (fun n : ℕ => 2 * n + 1) :=
nat_double |> Primrec.succ.comp
end Primrec
section
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
variable (H : Nat.Primrec fun n => Encodable.encode (@decode (List β) _ n))
open Primrec
private def prim : Primcodable (List β) := ⟨H⟩
private theorem list_casesOn' {f : α → List β} {g : α → σ} {h : α → β × List β → σ}
(hf : haveI := prim H; Primrec f) (hg : Primrec g) (hh : haveI := prim H; Primrec₂ h) :
@Primrec _ σ _ _ fun a => List.casesOn (f a) (g a) fun b l => h a (b, l) :=
letI := prim H
have :
@Primrec _ (Option σ) _ _ fun a =>
(@decode (Option (β × List β)) _ (encode (f a))).map fun o => Option.casesOn o (g a) (h a) :=
((@map_decode_iff _ (Option (β × List β)) _ _ _ _ _).2 <|
to₂ <|
option_casesOn snd (hg.comp fst) (hh.comp₂ (fst.comp₂ Primrec₂.left) Primrec₂.right)).comp
.id (encode_iff.2 hf)
option_some_iff.1 <| this.of_eq fun a => by rcases f a with - | ⟨b, l⟩ <;> simp [encodek]
private theorem list_foldl' {f : α → List β} {g : α → σ} {h : α → σ × β → σ}
(hf : haveI := prim H; Primrec f) (hg : Primrec g) (hh : haveI := prim H; Primrec₂ h) :
Primrec fun a => (f a).foldl (fun s b => h a (s, b)) (g a) := by
letI := prim H
let G (a : α) (IH : σ × List β) : σ × List β := List.casesOn IH.2 IH fun b l => (h a (IH.1, b), l)
have hG : Primrec₂ G := list_casesOn' H (snd.comp snd) snd <|
to₂ <|
pair (hh.comp (fst.comp fst) <| pair ((fst.comp snd).comp fst) (fst.comp snd))
(snd.comp snd)
let F := fun (a : α) (n : ℕ) => (G a)^[n] (g a, f a)
have hF : Primrec fun a => (F a (encode (f a))).1 :=
(fst.comp <|
nat_iterate (encode_iff.2 hf) (pair hg hf) <|
hG)
suffices ∀ a n, F a n = (((f a).take n).foldl (fun s b => h a (s, b)) (g a), (f a).drop n) by
refine hF.of_eq fun a => ?_
rw [this, List.take_of_length_le (length_le_encode _)]
introv
dsimp only [F]
generalize f a = l
generalize g a = x
induction n generalizing l x with
| zero => rfl
| succ n IH =>
simp only [iterate_succ, comp_apply]
rcases l with - | ⟨b, l⟩ <;> simp [G, IH]
private theorem list_cons' : (haveI := prim H; Primrec₂ (@List.cons β)) :=
letI := prim H
encode_iff.1 (succ.comp <| Primrec₂.natPair.comp (encode_iff.2 fst) (encode_iff.2 snd))
private theorem list_reverse' :
haveI := prim H
Primrec (@List.reverse β) :=
letI := prim H
(list_foldl' H .id (const []) <| to₂ <| ((list_cons' H).comp snd fst).comp snd).of_eq
(suffices ∀ l r, List.foldl (fun (s : List β) (b : β) => b :: s) r l = List.reverseAux l r from
fun l => this l []
fun l => by induction l <;> simp [*, List.reverseAux])
end
namespace Primcodable
variable {α : Type*} {β : Type*}
variable [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_double_succ.comp (Primrec.encode.comp snd))
(((@Primrec.decode α _).comp nat_div2).option_map <|
to₂ <| nat_double.comp (Primrec.encode.comp snd)))).of_eq
fun n =>
show _ = encode (decodeSum n) by
simp only [decodeSum, Nat.boddDiv2_eq]
cases Nat.bodd n <;> simp
· cases @decode α _ n.div2 <;> rfl
· cases @decode β _ n.div2 <;> rfl⟩
instance list : Primcodable (List α) :=
⟨letI H := Primcodable.prim (List ℕ)
have : Primrec₂ fun (a : α) (o : Option (List ℕ)) => o.map (List.cons (encode a)) :=
option_map snd <| (list_cons' H).comp ((@Primrec.encode α _).comp (fst.comp fst)) snd
have :
Primrec fun n =>
(ofNat (List ℕ) n).reverse.foldl
(fun o m => (@decode α _ m).bind fun a => o.map (List.cons (encode a))) (some []) :=
list_foldl' H ((list_reverse' H).comp (.ofNat (List ℕ))) (const (some []))
(Primrec.comp₂ (bind_decode_iff.2 <| .swap this) Primrec₂.right)
nat_iff.1 <|
(encode_iff.2 this).of_eq fun n => by
rw [List.foldl_reverse]
apply Nat.case_strong_induction_on n; · simp
intro n IH; simp
rcases @decode α _ n.unpair.1 with - | a; · rfl
simp only [Option.bind_some, Option.map_some]
suffices ∀ (o : Option (List ℕ)) (p), encode o = encode p →
encode (Option.map (List.cons (encode a)) o) = encode (Option.map (List.cons a) p) from
this _ _ (IH _ (Nat.unpair_right_le n))
intro o p IH
cases o <;> cases p
· rfl
· injection IH
· injection IH
· exact congr_arg (fun k => (Nat.pair (encode a) k).succ.succ) (Nat.succ.inj IH)⟩
end Primcodable
namespace Primrec
variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ]
theorem sumInl : Primrec (@Sum.inl α β) :=
encode_iff.1 <| nat_double.comp Primrec.encode
theorem sumInr : Primrec (@Sum.inr α β) :=
encode_iff.1 <| nat_double_succ.comp Primrec.encode
theorem sumCasesOn {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : Primrec f)
(hg : Primrec₂ g) (hh : Primrec₂ h) : @Primrec _ σ _ _ fun a => Sum.casesOn (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
fun a => by rcases f a with b | c <;> simp [Nat.div2_val, encodek]
theorem list_cons : Primrec₂ (@List.cons α) :=
list_cons' (Primcodable.prim _)
theorem list_casesOn {f : α → List β} {g : α → σ} {h : α → β × List β → σ} :
Primrec f →
Primrec g →
Primrec₂ h → @Primrec _ σ _ _ fun a => List.casesOn (f a) (g a) fun b l => h a (b, l) :=
list_casesOn' (Primcodable.prim _)
theorem list_foldl {f : α → List β} {g : α → σ} {h : α → σ × β → σ} :
Primrec f →
Primrec g → Primrec₂ h → Primrec fun a => (f a).foldl (fun 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 fun a => (f a).foldr (fun 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
fun a => by simp [List.foldl_reverse]
theorem list_head? : Primrec (@List.head? α) :=
(list_casesOn .id (const none) (option_some_iff.2 <| fst.comp snd).to₂).of_eq fun l => by
cases l <;> rfl
theorem list_headI [Inhabited α] : Primrec (@List.headI α _) :=
(option_iget.comp list_head?).of_eq fun l => l.head!_eq_head?.symm
theorem list_tail : Primrec (@List.tail α) :=
(list_casesOn .id (const []) (snd.comp snd).to₂).of_eq fun l => by cases l <;> rfl
theorem list_rec {f : α → List β} {g : α → σ} {h : α → β × List β × σ → σ} (hf : Primrec f)
(hg : Primrec g) (hh : Primrec₂ h) :
@Primrec _ σ _ _ fun a => List.recOn (f a) (g a) fun b l IH => h a (b, l, IH) :=
let F (a : α) := (f a).foldr (fun (b : β) (s : List β × σ) => (b :: s.1, h a (b, s))) ([], g a)
have : Primrec F :=
list_foldr hf (pair (const []) hg) <|
to₂ <| pair ((list_cons.comp fst (fst.comp snd)).comp snd) hh
(snd.comp this).of_eq fun a => by
suffices F a = (f a, List.recOn (f a) (g a) fun b l IH => h a (b, l, IH)) by rw [this]
dsimp [F]
induction f a <;> simp [*]
theorem list_getElem? : Primrec₂ ((·[·]? : List α → ℕ → Option α)) :=
let F (l : List α) (n : ℕ) :=
l.foldl
(fun (s : ℕ ⊕ α) (a : α) =>
Sum.casesOn s (@Nat.casesOn (fun _ => ℕ ⊕ α) · (Sum.inr a) Sum.inl) Sum.inr)
(Sum.inl n)
have hF : Primrec₂ F :=
(list_foldl fst (sumInl.comp snd)
((sumCasesOn fst (nat_casesOn snd (sumInr.comp <| snd.comp fst) (sumInl.comp snd).to₂).to₂
(sumInr.comp snd).to₂).comp
snd).to₂).to₂
have :
@Primrec _ (Option α) _ _ fun p : List α × ℕ => Sum.casesOn (F p.1 p.2) (fun _ => none) some :=
sumCasesOn hF (const none).to₂ (option_some.comp snd).to₂
this.to₂.of_eq fun l n => by
dsimp; symm
induction l generalizing n with
| nil => rfl
| cons a l IH =>
rcases n with - | n
· dsimp [F]
clear IH
induction l <;> simp_all
· simpa using IH ..
theorem list_getD (d : α) : Primrec₂ fun l n => List.getD l n d := by
simp only [List.getD_eq_getElem?_getD]
exact option_getD.comp₂ list_getElem? (const _)
theorem list_getI [Inhabited α] : Primrec₂ (@List.getI α _) :=
list_getD _
theorem list_append : Primrec₂ ((· ++ ·) : List α → List α → List α) :=
(list_foldr fst snd <| to₂ <| comp (@list_cons α _) snd).to₂.of_eq fun l₁ l₂ => by
induction l₁ <;> simp [*]
theorem list_concat : Primrec₂ fun 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 fun 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
fun a => by induction f a <;> simp [*]
theorem list_range : Primrec List.range :=
(nat_rec' .id (const []) ((list_concat.comp snd fst).comp snd).to₂).of_eq fun n => by
simp; induction n <;> simp [*, List.range_succ]
theorem list_flatten : Primrec (@List.flatten α) :=
(list_foldr .id (const []) <| to₂ <| comp (@list_append α _) snd).of_eq fun l => by
dsimp; induction l <;> simp [*]
theorem list_flatMap {f : α → List β} {g : α → β → List σ} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec (fun a => (f a).flatMap (g a)) := list_flatten.comp (list_map hf hg)
theorem optionToList : Primrec (Option.toList : Option α → List α) :=
(option_casesOn Primrec.id (const [])
((list_cons.comp Primrec.id (const [])).comp₂ Primrec₂.right)).of_eq
(fun o => by rcases o <;> simp)
theorem listFilterMap {f : α → List β} {g : α → β → Option σ}
(hf : Primrec f) (hg : Primrec₂ g) : Primrec fun a => (f a).filterMap (g a) :=
(list_flatMap hf (comp₂ optionToList hg)).of_eq
fun _ ↦ Eq.symm <| List.filterMap_eq_flatMap_toList _ _
variable {p : α → Prop} [DecidablePred p]
theorem list_length : Primrec (@List.length α) :=
(list_foldr (@Primrec.id (List α) _) (const 0) <| to₂ <| (succ.comp <| snd.comp snd).to₂).of_eq
fun l => by dsimp; induction l <;> simp [*]
/-- Filtering a list for elements that satisfy a decidable predicate is primitive recursive. -/
theorem listFilter (hf : PrimrecPred p) : Primrec fun L ↦ List.filter (p ·) L := by
rw [← List.filterMap_eq_filter]
apply listFilterMap .id
simp only [Primrec₂, Option.guard, decide_eq_true_eq]
exact ite (hf.comp snd) (option_some_iff.mpr snd) (const none)
theorem list_findIdx {f : α → List β} {p : α → β → Bool}
(hf : Primrec f) (hp : Primrec₂ p) : Primrec fun a => (f a).findIdx (p a) :=
(list_foldr hf (const 0) <|
to₂ <| cond (hp.comp fst <| fst.comp snd) (const 0) (succ.comp <| snd.comp snd)).of_eq
fun a => by dsimp; induction f a <;> simp [List.findIdx_cons, *]
theorem list_idxOf [DecidableEq α] : Primrec₂ (@List.idxOf α _) :=
to₂ <| list_findIdx snd <| Primrec.beq.comp₂ snd.to₂ (fst.comp fst).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₂ fun a n => (List.range n).map (f a) from
Primrec₂.option_some_iff.1 <|
(list_getElem?.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq fun a n => by
simp
Primrec₂.option_some_iff.1 <|
(nat_rec (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
fun a n => by
induction n with
| zero => rfl
| succ n IH => simp [IH, H, List.range_succ]
theorem listLookup [DecidableEq α] : Primrec₂ (List.lookup : α → List (α × β) → Option β) :=
(to₂ <| list_rec snd (const none) <|
to₂ <|
cond (Primrec.beq.comp (fst.comp fst) (fst.comp <| fst.comp snd))
(option_some.comp <| snd.comp <| fst.comp snd)
(snd.comp <| snd.comp snd)).of_eq
fun a ps => by
induction ps with simp [List.lookup, *]
| cons p ps ih => cases ha : a == p.1 <;> simp
theorem nat_omega_rec' (f : β → σ) {m : β → ℕ} {l : β → List β} {g : β → List σ → Option σ}
(hm : Primrec m) (hl : Primrec l) (hg : Primrec₂ g)
(Ord : ∀ b, ∀ b' ∈ l b, m b' < m b)
(H : ∀ b, g b ((l b).map f) = some (f b)) : Primrec f := by
haveI : DecidableEq β := Encodable.decidableEqOfEncodable β
let mapGraph (M : List (β × σ)) (bs : List β) : List σ := bs.flatMap (Option.toList <| M.lookup ·)
let bindList (b : β) : ℕ → List β := fun n ↦ n.rec [b] fun _ bs ↦ bs.flatMap l
let graph (b : β) : ℕ → List (β × σ) := fun i ↦ i.rec [] fun i ih ↦
(bindList b (m b - i)).filterMap fun b' ↦ (g b' <| mapGraph ih (l b')).map (b', ·)
have mapGraph_primrec : Primrec₂ mapGraph :=
to₂ <| list_flatMap snd <| optionToList.comp₂ <| listLookup.comp₂ .right (fst.comp₂ .left)
have bindList_primrec : Primrec₂ (bindList) :=
nat_rec' snd
(list_cons.comp fst (const []))
(to₂ <| list_flatMap (snd.comp snd) (hl.comp₂ .right))
have graph_primrec : Primrec₂ (graph) :=
to₂ <| nat_rec' snd (const []) <|
to₂ <| listFilterMap
(bindList_primrec.comp
(fst.comp fst)
(nat_sub.comp (hm.comp <| fst.comp fst) (fst.comp snd))) <|
to₂ <| option_map
(hg.comp snd (mapGraph_primrec.comp (snd.comp <| snd.comp fst) (hl.comp snd)))
(Primrec₂.pair.comp₂ (snd.comp₂ .left) .right)
have : Primrec (fun b => (graph b (m b + 1))[0]?.map Prod.snd) :=
option_map (list_getElem?.comp (graph_primrec.comp Primrec.id (succ.comp hm)) (const 0))
(snd.comp₂ Primrec₂.right)
exact option_some_iff.mp <| this.of_eq <| fun b ↦ by
have graph_eq_map_bindList (i : ℕ) (hi : i ≤ m b + 1) :
graph b i = (bindList b (m b + 1 - i)).map fun x ↦ (x, f x) := by
have bindList_eq_nil : bindList b (m b + 1) = [] :=
have bindList_m_lt (k : ℕ) : ∀ b' ∈ bindList b k, m b' < m b + 1 - k := by
induction k with simp [bindList]
| succ k ih =>
grind
List.eq_nil_iff_forall_not_mem.mpr
(by intro b' ha'; by_contra; simpa using bindList_m_lt (m b + 1) b' ha')
have mapGraph_graph {bs bs' : List β} (has : bs' ⊆ bs) :
mapGraph (bs.map <| fun x => (x, f x)) bs' = bs'.map f := by
induction bs' with simp [mapGraph]
| cons b bs' ih =>
have : b ∈ bs ∧ bs' ⊆ bs := by simpa using has
rcases this with ⟨ha, has'⟩
simpa [List.lookup_graph f ha] using ih has'
have graph_succ : ∀ i, graph b (i + 1) =
(bindList b (m b - i)).filterMap fun b' =>
(g b' <| mapGraph (graph b i) (l b')).map (b', ·) := fun _ => rfl
have bindList_succ : ∀ i, bindList b (i + 1) = (bindList b i).flatMap l := fun _ => rfl
induction i with
| zero => symm; simpa [graph] using bindList_eq_nil
| succ i ih =>
simp only [graph_succ, ih (Nat.le_of_lt hi), Nat.succ_sub (Nat.lt_succ.mp hi),
Nat.succ_eq_add_one, bindList_succ, Nat.reduceSubDiff]
apply List.filterMap_eq_map_iff_forall_eq_some.mpr
intro b' ha'; simp; rw [mapGraph_graph]
· exact H b'
· exact (List.infix_flatMap_of_mem ha' l).subset
simp [graph_eq_map_bindList (m b + 1) (Nat.le_refl _), bindList]
theorem nat_omega_rec (f : α → β → σ) {m : α → β → ℕ}
{l : α → β → List β} {g : α → β × List σ → Option σ}
(hm : Primrec₂ m) (hl : Primrec₂ l) (hg : Primrec₂ g)
(Ord : ∀ a b, ∀ b' ∈ l a b, m a b' < m a b)
(H : ∀ a b, g a (b, (l a b).map (f a)) = some (f a b)) : Primrec₂ f :=
Primrec₂.uncurry.mp <|
nat_omega_rec' (Function.uncurry f)
(Primrec₂.uncurry.mpr hm)
(list_map (hl.comp fst snd) (Primrec₂.pair.comp₂ (fst.comp₂ .left) .right))
(hg.comp₂ (fst.comp₂ .left) (Primrec₂.pair.comp₂ (snd.comp₂ .left) .right))
(by simpa using Ord) (by simpa [Function.comp] using H)
end Primrec
namespace PrimrecPred
open List Primrec
variable {α β : Type*} {p : α → Prop} {L : List α} {b : β}
variable [Primcodable α] [Primcodable β]
/-- Checking if any element of a list satisfies a decidable predicate is primitive recursive. -/
theorem exists_mem_list : (hf : PrimrecPred p) → PrimrecPred fun L : List α ↦ ∃ a ∈ L, p a
| ⟨_, hf⟩ => .of_eq
(.not <| Primrec.eq.comp (list_length.comp <| listFilter hf.primrecPred) (const 0)) <| by simp
/-- Checking if every element of a list satisfies a decidable predicate is primitive recursive. -/
theorem forall_mem_list : (hf : PrimrecPred p) → PrimrecPred fun L : List α ↦ ∀ a ∈ L, p a
| ⟨_, hf⟩ => .of_eq
(Primrec.eq.comp (list_length.comp <| listFilter hf.primrecPred) (list_length)) <| by simp
variable {p : ℕ → Prop}
/-- Bounded existential quantifiers are primitive recursive. -/
theorem exists_lt (hf : PrimrecPred p) : PrimrecPred fun n ↦ ∃ x < n, p x :=
of_eq (hf.exists_mem_list.comp list_range) (by simp)
/-- Bounded universal quantifiers are primitive recursive. -/
theorem forall_lt (hf : PrimrecPred p) : PrimrecPred fun n ↦ ∀ x < n, p x :=
of_eq (hf.forall_mem_list.comp list_range) (by simp)
/-- A helper lemma for proofs about bounded quantifiers on decidable relations. -/
theorem listFilter_listRange {R : ℕ → ℕ → Prop} (s : ℕ) [DecidableRel R] (hf : PrimrecRel R) :
Primrec fun n ↦ (range s).filter (fun y ↦ R y n) := by
simp only [← filterMap_eq_filter]
refine listFilterMap (.const (range s)) ?_
refine ite (Primrec.eq.comp ?_ (const true)) (option_some_iff.mpr snd) (.const Option.none)
exact hf.decide.comp snd fst
end PrimrecPred
namespace PrimrecRel
open Primrec List PrimrecPred
variable {α β : Type*} {R : α → β → Prop} {L : List α} {b : β}
variable [Primcodable α] [Primcodable β]
protected theorem not (hf : PrimrecRel R) : PrimrecRel fun a b ↦ ¬ R a b := PrimrecPred.not hf
/-- If `R a b` is decidable, then given `L : List α` and `b : β`, it is primitive recursive
to filter `L` for elements `a` with `R a b` -/
theorem listFilter (hf : PrimrecRel R) [DecidableRel R] :
Primrec₂ fun (L : List α) b ↦ L.filter (fun a ↦ R a b) := by
simp only [← List.filterMap_eq_filter]
refine listFilterMap fst (Primrec.ite ?_ ?_ (Primrec.const Option.none))
· exact Primrec.eq.comp (hf.decide.comp snd (snd.comp fst)) (.const true)
· exact (option_some).comp snd
/-- If `R a b` is decidable, then given `L : List α` and `b : β`, `g L b ↔ ∃ a L, R a b`
is a primitive recursive relation. -/
theorem exists_mem_list (hf : PrimrecRel R) : PrimrecRel fun (L : List α) b ↦ ∃ a ∈ L, R a b := by
classical
have h (L) (b) : (List.filter (R · b) L).length ≠ 0 ↔ ∃ a ∈ L, R a b := by simp
refine .of_eq (.not ?_) h
exact Primrec.eq.comp (list_length.comp hf.listFilter) (const 0)
/-- If `R a b` is decidable, then given `L : List α` and `b : β`, `g L b ↔ ∀ a L, R a b`
is a primitive recursive relation. -/
theorem forall_mem_list (hf : PrimrecRel R) : PrimrecRel fun (L : List α) b ↦ ∀ a ∈ L, R a b := by
classical
have h (L) (b) : (List.filter (R · b) L).length = L.length ↔ ∀ a ∈ L, R a b := by simp
apply PrimrecRel.of_eq ?_ h
exact (Primrec.eq.comp (list_length.comp <| PrimrecRel.listFilter hf) (.comp list_length fst))
variable {R : ℕ → ℕ → Prop}
/-- If `R a b` is decidable, then for any fixed `n` and `y`, `g n y ↔ ∃ x < n, R x y` is a
primitive recursive relation. -/
theorem exists_lt (hf : PrimrecRel R) : PrimrecRel fun n y ↦ ∃ x < n, R x y :=
(hf.exists_mem_list.comp (list_range.comp fst) snd).of_eq (by simp)
/-- If `R a b` is decidable, then for any fixed `n` and `y`, `g n y ↔ ∀ x < n, R x y` is a
primitive recursive relation. -/
theorem forall_lt (hf : PrimrecRel R) : PrimrecRel fun n y ↦ ∀ x < n, R x y :=
(hf.forall_mem_list.comp (list_range.comp fst) snd).of_eq (by simp)
end PrimrecRel
namespace Primcodable
variable {α : Type*} [Primcodable α]
open Primrec
/-- A subtype of a primitive recursive predicate is `Primcodable`. -/
def subtype {p : α → Prop} [DecidablePred p] (hp : PrimrecPred p) : Primcodable (Subtype p) :=
⟨have : Primrec fun n => (@decode α _ n).bind fun a => Option.guard p a :=
option_bind .decode (option_guard (hp.comp snd).primrecRel snd)
nat_iff.1 <| (encode_iff.2 this).of_eq fun n =>
show _ = encode ((@decode α _ n).bind fun _ => _) by
rcases @decode α _ n with - | a; · rfl
dsimp [Option.guard]
by_cases h : p a <;> simp [h]; rfl⟩
instance fin {n} : Primcodable (Fin n) :=
@ofEquiv _ _ (subtype <| nat_lt.comp .id (const n)) Fin.equivSubtype
instance vector {n} : Primcodable (List.Vector α n) :=
subtype ((@Primrec.eq ℕ _).comp list_length (const _))
instance finArrow {n} : Primcodable (Fin n → α) :=
ofEquiv _ (Equiv.vectorEquivFin _ _).symm
section ULower
attribute [local instance] Encodable.decidableRangeEncode Encodable.decidableEqOfEncodable
theorem mem_range_encode : PrimrecPred (fun n => n ∈ Set.range (encode : α → ℕ)) :=
have : PrimrecPred fun n => Encodable.decode₂ α n ≠ none :=
.not
(Primrec.eq.comp
(.option_bind .decode
(.ite (by simpa using Primrec.eq.comp (Primrec.encode.comp .snd) .fst)
(Primrec.option_some.comp .snd) (.const _)))
(.const _))
this.of_eq fun _ => decode₂_ne_none_iff
instance ulower : Primcodable (ULower α) :=
Primcodable.subtype mem_range_encode
end ULower
end Primcodable
namespace Primrec
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
theorem subtype_val {p : α → Prop} [DecidablePred p] {hp : PrimrecPred p} :
haveI := Primcodable.subtype hp
Primrec (@Subtype.val α p) := by
letI := Primcodable.subtype hp
refine (Primcodable.prim (Subtype p)).of_eq fun n => ?_
rcases @decode (Subtype p) _ n with (_ | ⟨a, h⟩) <;> rfl
theorem subtype_val_iff {p : β → Prop} [DecidablePred p] {hp : PrimrecPred p} {f : α → Subtype p} :
haveI := Primcodable.subtype hp
(Primrec fun a => (f a).1) ↔ Primrec f := by
letI := Primcodable.subtype hp
refine ⟨fun h => ?_, fun hf => subtype_val.comp hf⟩
refine Nat.Primrec.of_eq h fun n => ?_
rcases @decode α _ n with - | a; · rfl
simp; rfl
theorem subtype_mk {p : β → Prop} [DecidablePred p] {hp : PrimrecPred p} {f : α → β}
{h : ∀ a, p (f a)} (hf : Primrec f) :
haveI := Primcodable.subtype hp
Primrec fun a => @Subtype.mk β p (f a) (h a) :=
subtype_val_iff.1 hf
theorem option_get {f : α → Option β} {h : ∀ a, (f a).isSome} :
Primrec f → Primrec fun a => (f a).get (h a) := by
intro hf
refine (Nat.Primrec.pred.comp hf).of_eq fun n => ?_
generalize hx : @decode α _ n = x
cases x <;> simp
theorem ulower_down : Primrec (ULower.down : α → ULower α) :=
letI : ∀ a, Decidable (a ∈ Set.range (encode : α → ℕ)) := decidableRangeEncode _
subtype_mk .encode
theorem ulower_up : Primrec (ULower.up : ULower α → α) :=
letI : ∀ a, Decidable (a ∈ Set.range (encode : α → ℕ)) := decidableRangeEncode _
option_get (Primrec.decode₂.comp subtype_val)
theorem fin_val_iff {n} {f : α → Fin n} : (Primrec fun a => (f a).1) ↔ Primrec f := by
letI : Primcodable { a // id a < n } := Primcodable.subtype (nat_lt.comp .id (const _))
exact (Iff.trans (by rfl) subtype_val_iff).trans (of_equiv_iff _)
theorem fin_val {n} : Primrec (fun (i : Fin n) => (i : ℕ)) :=
fin_val_iff.2 .id
theorem fin_succ {n} : Primrec (@Fin.succ n) :=
fin_val_iff.1 <| by simp [succ.comp fin_val]
theorem vector_toList {n} : Primrec (@List.Vector.toList α n) :=
subtype_val
theorem vector_toList_iff {n} {f : α → List.Vector β n} :
(Primrec fun a => (f a).toList) ↔ Primrec f :=
subtype_val_iff
theorem vector_cons {n} : Primrec₂ (@List.Vector.cons α n) :=
vector_toList_iff.1 <| by simpa using list_cons.comp fst (vector_toList_iff.2 snd)
theorem vector_length {n} : Primrec (@List.Vector.length α n) :=
const _
theorem vector_head {n} : Primrec (@List.Vector.head α n) :=
option_some_iff.1 <| (list_head?.comp vector_toList).of_eq fun ⟨_ :: _, _⟩ => rfl
theorem vector_tail {n} : Primrec (@List.Vector.tail α n) :=
vector_toList_iff.1 <| (list_tail.comp vector_toList).of_eq fun ⟨l, h⟩ => by cases l <;> rfl
theorem vector_get {n} : Primrec₂ (@List.Vector.get α n) :=
option_some_iff.1 <|
(list_getElem?.comp (vector_toList.comp fst) (fin_val.comp snd)).of_eq fun a => by
simp [Vector.get_eq_get_toList]
theorem list_ofFn :
∀ {n} {f : Fin n → α → σ}, (∀ i, Primrec (f i)) → Primrec fun a => List.ofFn fun i => f i a
| 0, _, _ => by simp only [List.ofFn_zero]; exact const []
| n + 1, f, hf => by
simpa using list_cons.comp (hf 0) (list_ofFn fun i => hf i.succ)
theorem vector_ofFn {n} {f : Fin n → α → σ} (hf : ∀ i, Primrec (f i)) :
Primrec fun a => List.Vector.ofFn fun i => f i a :=
vector_toList_iff.1 <| by simp [list_ofFn hf]
theorem vector_get' {n} : Primrec (@List.Vector.get α n) :=
of_equiv_symm
theorem vector_ofFn' {n} : Primrec (@List.Vector.ofFn α n) :=
of_equiv
theorem fin_app {n} : Primrec₂ (@id (Fin n → σ)) :=
(vector_get.comp (vector_ofFn'.comp fst) snd).of_eq fun ⟨v, i⟩ => by simp
theorem fin_curry₁ {n} {f : Fin n → α → σ} : Primrec₂ f ↔ ∀ i, Primrec (f i) :=
⟨fun h i => h.comp (const i) .id, fun h =>
(vector_get.comp ((vector_ofFn h).comp snd) fst).of_eq fun a => by simp⟩
theorem fin_curry {n} {f : α → Fin n → σ} : Primrec f ↔ Primrec₂ f :=
⟨fun h => fin_app.comp (h.comp fst) snd, fun h =>
(vector_get'.comp
(vector_ofFn fun i => show Primrec fun a => f a i from h.comp .id (const i))).of_eq
fun a => by funext i; simp⟩
end Primrec
namespace Nat
open List.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}, (List.Vector ℕ n → ℕ) → Prop
| zero : @Primrec' 0 fun _ => 0
| succ : @Primrec' 1 fun v => succ v.head
| get {n} (i : Fin n) : Primrec' fun v => v.get i
| comp {m n f} (g : Fin n → List.Vector ℕ m → ℕ) :
Primrec' f → (∀ i, Primrec' (g i)) → Primrec' fun a => f (List.Vector.ofFn fun i => g i a)
| prec {n f g} :
@Primrec' n f →
@Primrec' (n + 2) g →
Primrec' fun v : List.Vector ℕ (n + 1) =>
v.head.rec (f v.tail) fun y IH => g (y ::ᵥ IH ::ᵥ v.tail)
end Nat
namespace Nat.Primrec'
open List.Vector Primrec
theorem to_prim {n f} (pf : @Nat.Primrec' n f) : Primrec f := by
induction pf with
| zero => exact .const 0
| succ => exact _root_.Primrec.succ.comp .vector_head
| get i => exact Primrec.vector_get.comp .id (.const i)
| comp _ _ _ hf hg => exact hf.comp (.vector_ofFn fun i => hg i)
| @prec n f g _ _ hf hg =>
exact
.nat_rec' .vector_head (hf.comp Primrec.vector_tail)
(hg.comp <|
Primrec.vector_cons.comp (Primrec.fst.comp .snd) <|
Primrec.vector_cons.comp (Primrec.snd.comp .snd) <|
(@Primrec.vector_tail _ _ (n + 1)).comp .fst).to₂
theorem of_eq {n} {f g : List.Vector ℕ n → ℕ} (hf : Primrec' f) (H : ∀ i, f i = g i) :
Primrec' g :=
(funext H : f = g) ▸ hf
theorem const {n} : ∀ m, @Primrec' n fun _ => m
| 0 => zero.comp Fin.elim0 fun i => i.elim0
| m + 1 => succ.comp _ fun _ => const m
theorem head {n : ℕ} : @Primrec' n.succ head :=
(get 0).of_eq fun v => by simp [get_zero]
theorem tail {n f} (hf : @Primrec' n f) : @Primrec' n.succ fun v => f v.tail :=
(hf.comp _ fun i => @get _ i.succ).of_eq fun v => by
rw [← ofFn_get v.tail]; congr; funext i; simp
/-- A function from vectors to vectors is primitive recursive when all of its projections are. -/
def Vec {n m} (f : List.Vector ℕ n → List.Vector ℕ m) : Prop :=
∀ i, Primrec' fun v => (f v).get i
protected theorem nil {n} : @Vec n 0 fun _ => nil := fun i => i.elim0
protected theorem cons {n m f g} (hf : @Primrec' n f) (hg : @Vec n m g) :
Vec fun v => f v ::ᵥ g v := fun i => Fin.cases (by simp [*]) (fun i => by simp [hg i]) i
theorem idv {n} : @Vec n n id :=
get
theorem comp' {n m f g} (hf : @Primrec' m f) (hg : @Vec n m g) : Primrec' fun v => f (g v) :=
(hf.comp _ hg).of_eq fun v => by simp
theorem comp₁ (f : ℕ → ℕ) (hf : @Primrec' 1 fun v => f v.head) {n g} (hg : @Primrec' n g) :
Primrec' fun v => f (g v) :=
hf.comp _ fun _ => hg
theorem comp₂ (f : ℕ → ℕ → ℕ) (hf : @Primrec' 2 fun v => f v.head v.tail.head) {n g h}
(hg : @Primrec' n g) (hh : @Primrec' n h) : Primrec' fun 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 fun v => (f v).rec (g v) fun y IH : ℕ => h (y ::ᵥ IH ::ᵥ v) := by
simpa using comp' (prec hg hh) (hf.cons idv)
theorem pred : @Primrec' 1 fun v => v.head.pred :=
(prec' head (const 0) head).of_eq fun v => by simp; cases v.head <;> rfl
theorem add : @Primrec' 2 fun v => v.head + v.tail.head :=
(prec head (succ.comp₁ _ (tail head))).of_eq fun v => by
simp; induction v.head <;> simp [*, Nat.succ_add]
theorem sub : @Primrec' 2 fun v => v.head - v.tail.head := by
have : @Primrec' 2 fun v ↦ (fun a b ↦ b - a) v.head v.tail.head := by
refine (prec head (pred.comp₁ _ (tail head))).of_eq fun v => ?_
simp; induction v.head <;> simp [*, Nat.sub_add_eq]
simpa using comp₂ (fun a b => b - a) this (tail head) head
theorem mul : @Primrec' 2 fun v => v.head * v.tail.head :=
(prec (const 0) (tail (add.comp₂ _ (tail head) head))).of_eq fun 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 fun v => if a v < b v then f v else g v :=
(prec' (sub.comp₂ _ hb ha) hg (tail <| tail hf)).of_eq fun v => by
cases e : b v - a v
· simp [not_lt.2 (Nat.sub_eq_zero_iff_le.mp e)]
· simp [Nat.lt_of_sub_eq_succ e]
theorem natPair : @Primrec' 2 fun v => v.head.pair 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 fun v => by rw [v.eq_nil]; rfl
| _ + 1 =>
(succ.comp₁ _ (natPair.comp₂ _ head (tail Primrec'.encode))).of_eq fun ⟨_ :: _, _⟩ => rfl
theorem sqrt : @Primrec' 1 fun v => v.head.sqrt := by
suffices H : ∀ n : ℕ, n.sqrt =
n.rec 0 fun x y => if x.succ < y.succ * y.succ then y else y.succ by
simp only [H, succ_eq_add_one]
have :=
@prec' 1 _ _
(fun v => by
have x := v.head; have y := v.tail.head
exact if x.succ < y.succ * y.succ then y else y.succ)
head (const 0) ?_
· exact this
have x1 : @Primrec' 3 fun v => v.head.succ := succ.comp₁ _ head
have y1 : @Primrec' 3 fun v => v.tail.head.succ := succ.comp₁ _ (tail head)
exact if_lt x1 (mul.comp₂ _ y1 y1) (tail head) y1
introv; symm
induction n with
| zero => simp
| succ n IH =>
dsimp; rw [IH]; split_ifs with h
· 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 _⟩
theorem unpair₁ {n f} (hf : @Primrec' n f) : @Primrec' n fun v => (f v).unpair.1 := by
have s := sqrt.comp₁ _ hf
have fss := sub.comp₂ _ hf (mul.comp₂ _ s s)
refine (if_lt fss s fss s).of_eq fun v => ?_
simp [Nat.unpair]; split_ifs <;> rfl
theorem unpair₂ {n f} (hf : @Primrec' n f) : @Primrec' n fun v => (f v).unpair.2 := by
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 fun v => ?_
simp [Nat.unpair]; split_ifs <;> rfl
theorem of_prim {n f} : Primrec f → @Primrec' n f :=
suffices ∀ f, Nat.Primrec f → @Primrec' 1 fun v => f v.head from fun hf =>
(pred.comp₁ _ <|
(this _ hf).comp₁ (fun m => Encodable.encode <| (@decode (List.Vector ℕ n) _ m).map f)
Primrec'.encode).of_eq
fun i => by simp [encodek]
fun f hf => by
induction hf with
| zero => exact const 0
| succ => exact succ
| left => exact unpair₁ head
| right => exact unpair₂ head
| pair _ _ hf hg => exact natPair.comp₂ _ hf hg
| comp _ _ hf hg => exact hf.comp₁ _ hg
| prec _ _ hf hg =>
simpa using
prec' (unpair₂ head) (hf.comp₁ _ (unpair₁ head))
(hg.comp₁ _ <|
natPair.comp₂ _ (unpair₁ <| tail <| tail head) (natPair.comp₂ _ head (tail head)))
theorem prim_iff {n f} : @Primrec' n f ↔ Primrec f :=
⟨to_prim, of_prim⟩
theorem prim_iff₁ {f : ℕ → ℕ} : (@Primrec' 1 fun v => f v.head) ↔ Primrec f :=
prim_iff.trans
⟨fun h => (h.comp <| .vector_ofFn fun _ => .id).of_eq fun v => by simp, fun h =>
h.comp .vector_head⟩
theorem prim_iff₂ {f : ℕ → ℕ → ℕ} : (@Primrec' 2 fun v => f v.head v.tail.head) ↔ Primrec₂ f :=
prim_iff.trans
⟨fun h => (h.comp <| Primrec.vector_cons.comp .fst <|
Primrec.vector_cons.comp .snd (.const nil)).of_eq fun v => by simp,
fun h => h.comp .vector_head (Primrec.vector_head.comp .vector_tail)⟩
theorem vec_iff {m n f} : @Vec m n f ↔ Primrec f :=
⟨fun h => by simpa using Primrec.vector_ofFn fun i => to_prim (h i), fun h i =>
of_prim <| Primrec.vector_get.comp h (.const i)⟩
end Nat.Primrec'
theorem Primrec.nat_sqrt : Primrec Nat.sqrt :=
Nat.Primrec'.prim_iff₁.1 Nat.Primrec'.sqrt
set_option linter.style.longFile 1700 |
.lake/packages/mathlib/Mathlib/Computability/ContextFreeGrammar.lean | import Mathlib.Computability.Language
/-!
# Context-Free Grammars
This file contains the definition of a context-free grammar, which is a grammar that has a single
nonterminal symbol on the left-hand side of each rule.
We restrict nonterminals of a context-free grammar to `Type` because universe polymorphism would be
cumbersome and unnecessary; we can always restrict a context-free grammar to the finitely many
nonterminal symbols that are referred to by its finitely many rules.
## Main definitions
* `ContextFreeGrammar`: A context-free grammar.
* `ContextFreeGrammar.language`: A language generated by a given context-free grammar.
## Main theorems
* `Language.IsContextFree.reverse`: The class of context-free languages is closed under reversal.
-/
open Function
/-- Rule that rewrites a single nonterminal to any string (a list of symbols). -/
@[ext]
structure ContextFreeRule (T N : Type*) where
/-- Input nonterminal a.k.a. left-hand side. -/
input : N
/-- Output string a.k.a. right-hand side. -/
output : List (Symbol T N)
deriving DecidableEq, Repr
-- See https://github.com/leanprover/lean4/issues/10295
attribute [nolint unusedArguments] instReprContextFreeRule.repr
/-- Context-free grammar that generates words over the alphabet `T` (a type of terminals). -/
structure ContextFreeGrammar (T : Type*) where
/-- Type of nonterminals. -/
NT : Type
/-- Initial nonterminal. -/
initial : NT
/-- Rewrite rules. -/
rules : Finset (ContextFreeRule T NT)
variable {T : Type*}
namespace ContextFreeRule
variable {N : Type*} {r : ContextFreeRule T N} {u v : List (Symbol T N)}
/-- Inductive definition of a single application of a given context-free rule `r` to a string `u`;
`r.Rewrites u v` means that the `r` sends `u` to `v` (there may be multiple such strings `v`). -/
inductive Rewrites (r : ContextFreeRule T N) : List (Symbol T N) → List (Symbol T N) → Prop
/-- The replacement is at the start of the remaining string. -/
| head (s : List (Symbol T N)) :
r.Rewrites (Symbol.nonterminal r.input :: s) (r.output ++ s)
/-- There is a replacement later in the string. -/
| cons (x : Symbol T N) {s₁ s₂ : List (Symbol T N)} (hrs : Rewrites r s₁ s₂) :
r.Rewrites (x :: s₁) (x :: s₂)
lemma Rewrites.exists_parts (hr : r.Rewrites u v) :
∃ p q : List (Symbol T N),
u = p ++ [Symbol.nonterminal r.input] ++ q ∧ v = p ++ r.output ++ q := by
induction hr with
| head s =>
use [], s
simp
| cons x _ ih =>
rcases ih with ⟨p', q', rfl, rfl⟩
use x :: p', q'
simp
lemma Rewrites.input_output : r.Rewrites [.nonterminal r.input] r.output := by
simpa using head []
lemma rewrites_of_exists_parts (r : ContextFreeRule T N) (p q : List (Symbol T N)) :
r.Rewrites (p ++ [Symbol.nonterminal r.input] ++ q) (p ++ r.output ++ q) := by
induction p with
| nil => exact Rewrites.head q
| cons d l ih => exact Rewrites.cons d ih
/-- Rule `r` rewrites string `u` is to string `v` iff they share both a prefix `p` and postfix `q`
such that the remaining middle part of `u` is the input of `r` and the remaining middle part
of `u` is the output of `r`. -/
theorem rewrites_iff :
r.Rewrites u v ↔ ∃ p q : List (Symbol T N),
u = p ++ [Symbol.nonterminal r.input] ++ q ∧ v = p ++ r.output ++ q :=
⟨Rewrites.exists_parts, by rintro ⟨p, q, rfl, rfl⟩; apply rewrites_of_exists_parts⟩
lemma Rewrites.nonterminal_input_mem : r.Rewrites u v → .nonterminal r.input ∈ u := by
simp +contextual [rewrites_iff, List.append_assoc]
/-- Add extra prefix to context-free rewriting. -/
lemma Rewrites.append_left (hvw : r.Rewrites u v) (p : List (Symbol T N)) :
r.Rewrites (p ++ u) (p ++ v) := by
rw [rewrites_iff] at *
rcases hvw with ⟨x, y, hxy⟩
use p ++ x, y
simp_all
/-- Add extra postfix to context-free rewriting. -/
lemma Rewrites.append_right (hvw : r.Rewrites u v) (p : List (Symbol T N)) :
r.Rewrites (u ++ p) (v ++ p) := by
rw [rewrites_iff] at *
rcases hvw with ⟨x, y, hxy⟩
use x, y ++ p
simp_all
end ContextFreeRule
namespace ContextFreeGrammar
/-- Given a context-free grammar `g` and strings `u` and `v`
`g.Produces u v` means that one step of a context-free transformation by a rule from `g` sends
`u` to `v`. -/
def Produces (g : ContextFreeGrammar T) (u v : List (Symbol T g.NT)) : Prop :=
∃ r ∈ g.rules, r.Rewrites u v
/-- Given a context-free grammar `g` and strings `u` and `v`
`g.Derives u v` means that `g` can transform `u` to `v` in some number of rewriting steps. -/
abbrev Derives (g : ContextFreeGrammar T) :
List (Symbol T g.NT) → List (Symbol T g.NT) → Prop :=
Relation.ReflTransGen g.Produces
/-- Given a context-free grammar `g` and a string `s`
`g.Generates s` means that `g` can transform its initial nonterminal to `s` in some number of
rewriting steps. -/
def Generates (g : ContextFreeGrammar T) (s : List (Symbol T g.NT)) : Prop :=
g.Derives [Symbol.nonterminal g.initial] s
/-- The language (set of words) that can be generated by a given context-free grammar `g`. -/
def language (g : ContextFreeGrammar T) : Language T :=
{ w : List T | g.Generates (w.map Symbol.terminal) }
/-- A given word `w` belongs to the language generated by a given context-free grammar `g` iff
`g` can derive the word `w` (wrapped as a string) from the initial nonterminal of `g` in some
number of steps. -/
@[simp]
lemma mem_language_iff (g : ContextFreeGrammar T) (w : List T) :
w ∈ g.language ↔ g.Derives [Symbol.nonterminal g.initial] (w.map Symbol.terminal) := by
rfl
variable {g : ContextFreeGrammar T}
@[refl]
lemma Derives.refl (w : List (Symbol T g.NT)) : g.Derives w w :=
Relation.ReflTransGen.refl
lemma Produces.single {v w : List (Symbol T g.NT)} (hvw : g.Produces v w) : g.Derives v w :=
Relation.ReflTransGen.single hvw
@[trans]
lemma Derives.trans {u v w : List (Symbol T g.NT)} (huv : g.Derives u v) (hvw : g.Derives v w) :
g.Derives u w :=
Relation.ReflTransGen.trans huv hvw
lemma Derives.trans_produces {u v w : List (Symbol T g.NT)}
(huv : g.Derives u v) (hvw : g.Produces v w) :
g.Derives u w :=
huv.trans hvw.single
lemma Produces.trans_derives {u v w : List (Symbol T g.NT)}
(huv : g.Produces u v) (hvw : g.Derives v w) :
g.Derives u w :=
huv.single.trans hvw
lemma Derives.eq_or_head {u w : List (Symbol T g.NT)} (huw : g.Derives u w) :
u = w ∨ ∃ v : List (Symbol T g.NT), g.Produces u v ∧ g.Derives v w :=
Relation.ReflTransGen.cases_head huw
lemma derives_iff_eq_or_head {u w : List (Symbol T g.NT)} :
g.Derives u w ↔ u = w ∨ ∃ v : List (Symbol T g.NT), g.Produces u v ∧ g.Derives v w :=
Relation.ReflTransGen.cases_head_iff
lemma Derives.eq_or_tail {u w : List (Symbol T g.NT)} (huw : g.Derives u w) :
w = u ∨ ∃ v : List (Symbol T g.NT), g.Derives u v ∧ g.Produces v w :=
Relation.ReflTransGen.cases_tail huw
lemma derives_iff_eq_or_tail {u w : List (Symbol T g.NT)} :
g.Derives u w ↔ w = u ∨ ∃ v : List (Symbol T g.NT), g.Derives u v ∧ g.Produces v w :=
Relation.ReflTransGen.cases_tail_iff g.Produces u w
/-- Add extra prefix to context-free producing. -/
lemma Produces.append_left {v w : List (Symbol T g.NT)}
(hvw : g.Produces v w) (p : List (Symbol T g.NT)) :
g.Produces (p ++ v) (p ++ w) :=
match hvw with | ⟨r, hrmem, hrvw⟩ => ⟨r, hrmem, hrvw.append_left p⟩
/-- Add extra postfix to context-free producing. -/
lemma Produces.append_right {v w : List (Symbol T g.NT)}
(hvw : g.Produces v w) (p : List (Symbol T g.NT)) :
g.Produces (v ++ p) (w ++ p) :=
match hvw with | ⟨r, hrmem, hrvw⟩ => ⟨r, hrmem, hrvw.append_right p⟩
/-- Add extra prefix to context-free deriving. -/
lemma Derives.append_left {v w : List (Symbol T g.NT)}
(hvw : g.Derives v w) (p : List (Symbol T g.NT)) :
g.Derives (p ++ v) (p ++ w) := by
induction hvw with
| refl => rfl
| tail _ last ih => exact ih.trans_produces <| last.append_left p
/-- Add extra postfix to context-free deriving. -/
lemma Derives.append_right {v w : List (Symbol T g.NT)}
(hvw : g.Derives v w) (p : List (Symbol T g.NT)) :
g.Derives (v ++ p) (w ++ p) := by
induction hvw with
| refl => rfl
| tail _ last ih => exact ih.trans_produces <| last.append_right p
lemma Produces.exists_nonterminal_input_mem {u v : List (Symbol T g.NT)} (hguv : g.Produces u v) :
∃ r ∈ g.rules, .nonterminal r.input ∈ u := by
obtain ⟨w, l, r⟩ := hguv
exact ⟨w, l, r.nonterminal_input_mem⟩
lemma derives_nonterminal {t : g.NT} (hgt : ∀ r ∈ g.rules, r.input ≠ t)
(s : List (Symbol T g.NT)) (hs : s ≠ [.nonterminal t]) :
¬g.Derives [.nonterminal t] s := by
rw [derives_iff_eq_or_head]
push_neg
refine ⟨hs.symm, fun _ hx ↦ ?_⟩
have hxr := hx.exists_nonterminal_input_mem
simp_rw [List.mem_singleton, Symbol.nonterminal.injEq] at hxr
tauto
lemma language_eq_zero_of_forall_input_ne_initial (hg : ∀ r ∈ g.rules, r.input ≠ g.initial) :
g.language = 0 := by ext; simp +contextual [derives_nonterminal, hg]
end ContextFreeGrammar
/-- Context-free languages are defined by context-free grammars. -/
def Language.IsContextFree (L : Language T) : Prop :=
∃ g : ContextFreeGrammar T, g.language = L
section closure_reversal
namespace ContextFreeRule
variable {N : Type*} {r : ContextFreeRule T N} {u v : List (Symbol T N)}
/-- Rules for a grammar for a reversed language. -/
def reverse (r : ContextFreeRule T N) : ContextFreeRule T N := ⟨r.input, r.output.reverse⟩
@[simp] lemma reverse_reverse (r : ContextFreeRule T N) : r.reverse.reverse = r := by simp [reverse]
@[simp] lemma reverse_comp_reverse :
reverse ∘ reverse = (id : ContextFreeRule T N → ContextFreeRule T N) := by ext : 1; simp
lemma reverse_involutive : Involutive (reverse : ContextFreeRule T N → ContextFreeRule T N) :=
reverse_reverse
lemma reverse_bijective : Bijective (reverse : ContextFreeRule T N → ContextFreeRule T N) :=
reverse_involutive.bijective
lemma reverse_injective : Injective (reverse : ContextFreeRule T N → ContextFreeRule T N) :=
reverse_bijective.injective
lemma reverse_surjective : Surjective (reverse : ContextFreeRule T N → ContextFreeRule T N) :=
reverse_bijective.surjective
protected lemma Rewrites.reverse : ∀ {u v}, r.Rewrites u v → r.reverse.Rewrites u.reverse v.reverse
| _, _, head s => by simpa using .append_left .input_output _
| _, _, @cons _ _ _ x u v h => by simpa using h.reverse.append_right _
lemma rewrites_reverse : r.reverse.Rewrites u.reverse v.reverse ↔ r.Rewrites u v :=
⟨fun h ↦ by simpa using h.reverse, .reverse⟩
@[simp] lemma rewrites_reverse_comm : r.reverse.Rewrites u v ↔ r.Rewrites u.reverse v.reverse := by
rw [← rewrites_reverse, reverse_reverse]
end ContextFreeRule
namespace ContextFreeGrammar
variable {g : ContextFreeGrammar T} {u v : List (Symbol T g.NT)} {w : List T}
/-- Grammar for a reversed language. -/
@[simps] def reverse (g : ContextFreeGrammar T) : ContextFreeGrammar T :=
⟨g.NT, g.initial, g.rules.map (⟨ContextFreeRule.reverse, ContextFreeRule.reverse_injective⟩)⟩
@[simp] lemma reverse_reverse (g : ContextFreeGrammar T) : g.reverse.reverse = g := by
simp [reverse, Finset.map_map]
lemma reverse_involutive : Involutive (reverse : ContextFreeGrammar T → ContextFreeGrammar T) :=
reverse_reverse
lemma reverse_bijective : Bijective (reverse : ContextFreeGrammar T → ContextFreeGrammar T) :=
reverse_involutive.bijective
lemma reverse_injective : Injective (reverse : ContextFreeGrammar T → ContextFreeGrammar T) :=
reverse_bijective.injective
lemma reverse_surjective : Surjective (reverse : ContextFreeGrammar T → ContextFreeGrammar T) :=
reverse_bijective.surjective
lemma produces_reverse : g.reverse.Produces u.reverse v.reverse ↔ g.Produces u v :=
(Equiv.ofBijective _ ContextFreeRule.reverse_bijective).exists_congr
(by simp [ContextFreeRule.reverse_involutive.eq_iff])
alias ⟨_, Produces.reverse⟩ := produces_reverse
@[simp] lemma produces_reverse_comm : g.reverse.Produces u v ↔ g.Produces u.reverse v.reverse :=
(Equiv.ofBijective _ ContextFreeRule.reverse_bijective).exists_congr
(by simp [ContextFreeRule.reverse_involutive.eq_iff])
protected lemma Derives.reverse (hg : g.Derives u v) : g.reverse.Derives u.reverse v.reverse := by
induction hg with
| refl => rfl
| tail _ orig ih => exact ih.trans_produces orig.reverse
lemma derives_reverse : g.reverse.Derives u.reverse v.reverse ↔ g.Derives u v :=
⟨fun h ↦ by convert h.reverse <;> simp, .reverse⟩
@[simp] lemma derives_reverse_comm : g.reverse.Derives u v ↔ g.Derives u.reverse v.reverse := by
rw [iff_comm, ← derives_reverse, List.reverse_reverse, List.reverse_reverse]
lemma generates_reverse : g.reverse.Generates u.reverse ↔ g.Generates u := by simp [Generates]
alias ⟨_, Generates.reverse⟩ := generates_reverse
@[simp] lemma generates_reverse_comm : g.reverse.Generates u ↔ g.Generates u.reverse := by
simp [Generates]
@[simp] lemma language_reverse : g.reverse.language = g.language.reverse := by ext; simp
end ContextFreeGrammar
/-- The class of context-free languages is closed under reversal. -/
theorem Language.IsContextFree.reverse (L : Language T) :
L.IsContextFree → L.reverse.IsContextFree := by rintro ⟨g, rfl⟩; exact ⟨g.reverse, by simp⟩
end closure_reversal |
.lake/packages/mathlib/Mathlib/Computability/NFA.lean | import Mathlib.Computability.DFA
import Mathlib.Data.Fintype.Powerset
/-!
# Nondeterministic Finite Automata
A Nondeterministic Finite Automaton (NFA) is a state machine which
decides membership in a particular `Language`, by following every
possible path that describes an input string.
We show that DFAs and NFAs can decide the same languages, by constructing
an equivalent DFA for every NFA, and vice versa.
As constructing a DFA from an NFA uses an exponential number of states,
we re-prove the pumping lemma instead of lifting `DFA.pumping_lemma`,
in order to obtain the optimal bound on the minimal length of the string.
Like `DFA`, this definition allows for automata with infinite states;
a `Fintype` instance must be supplied for true NFAs.
## Main definitions
* `NFA α σ`: automaton over alphabet `α` and set of states `σ`
* `NFA.evalFrom M S x`: set of possible ending states for an input word `x`
and set of initial states `S`
* `NFA.accepts M`: the language accepted by the NFA `M`
* `NFA.Path M s t x`: a specific path from `s` to `t` for an input word `x`
* `NFA.Path.supp p`: set of states visited by the path `p`
## Main theorems
* `NFA.pumping_lemma`: every sufficiently long string accepted by the NFA has a substring that can
be repeated arbitrarily many times (and have the overall string still be accepted)
-/
open Set
open Computability
universe u v
/-- An NFA is a set of states (`σ`), a transition function from state to state labelled by the
alphabet (`step`), a set of starting states (`start`) and a set of acceptance states (`accept`).
Note the transition function sends a state to a `Set` of states. These are the states that it
may be sent to. -/
structure NFA (α : Type u) (σ : Type v) where
/-- The NFA's transition function -/
step : σ → α → Set σ
/-- Set of starting states -/
start : Set σ
/-- Set of accepting states -/
accept : Set σ
variable {α : Type u} {σ : Type v} {M : NFA α σ}
namespace NFA
instance : Inhabited (NFA α σ) :=
⟨NFA.mk (fun _ _ => ∅) ∅ ∅⟩
variable (M) in
/-- `M.stepSet S a` is the union of `M.step s a` for all `s ∈ S`. -/
def stepSet (S : Set σ) (a : α) : Set σ :=
⋃ s ∈ S, M.step s a
theorem mem_stepSet {s : σ} {S : Set σ} {a : α} : s ∈ M.stepSet S a ↔ ∃ t ∈ S, s ∈ M.step t a := by
simp [stepSet]
variable (M) in
@[simp]
theorem stepSet_empty (a : α) : M.stepSet ∅ a = ∅ := by simp [stepSet]
variable (M) in
@[simp]
theorem stepSet_singleton (s : σ) (a : α) : M.stepSet {s} a = M.step s a := by
simp [stepSet]
variable (M) in
/-- `M.evalFrom S x` computes all possible paths through `M` with input `x` starting at an element
of `S`. -/
def evalFrom (S : Set σ) : List α → Set σ :=
List.foldl M.stepSet S
variable (M) in
@[simp]
theorem evalFrom_nil (S : Set σ) : M.evalFrom S [] = S :=
rfl
variable (M) in
@[simp]
theorem evalFrom_singleton (S : Set σ) (a : α) : M.evalFrom S [a] = M.stepSet S a :=
rfl
variable (M) in
@[simp]
theorem evalFrom_cons (S : Set σ) (a : α) (x : List α) :
M.evalFrom S (a :: x) = M.evalFrom (M.stepSet S a) x :=
rfl
@[simp]
theorem evalFrom_append_singleton (S : Set σ) (x : List α) (a : α) :
M.evalFrom S (x ++ [a]) = M.stepSet (M.evalFrom S x) a := by
simp only [evalFrom, List.foldl_append, List.foldl_cons, List.foldl_nil]
variable (M) in
@[simp]
theorem evalFrom_biUnion {ι : Type*} (t : Set ι) (f : ι → Set σ) :
∀ (x : List α), M.evalFrom (⋃ i ∈ t, f i) x = ⋃ i ∈ t, M.evalFrom (f i) x
| [] => by simp
| a :: x => by simp [stepSet, evalFrom_biUnion _ _ x]
variable (M) in
theorem evalFrom_eq_biUnion_singleton (S : Set σ) (x : List α) :
M.evalFrom S x = ⋃ s ∈ S, M.evalFrom {s} x := by
simp [← evalFrom_biUnion]
theorem mem_evalFrom_iff_exists {s : σ} {S : Set σ} {x : List α} :
s ∈ M.evalFrom S x ↔ ∃ t ∈ S, s ∈ M.evalFrom {t} x := by
rw [evalFrom_eq_biUnion_singleton]
simp
variable (M) in
/-- `M.eval x` computes all possible paths though `M` with input `x` starting at an element of
`M.start`. -/
def eval : List α → Set σ :=
M.evalFrom M.start
variable (M) in
@[simp]
theorem eval_nil : M.eval [] = M.start :=
rfl
variable (M) in
@[simp]
theorem eval_singleton (a : α) : M.eval [a] = M.stepSet M.start a :=
rfl
variable (M) in
@[simp]
theorem eval_append_singleton (x : List α) (a : α) : M.eval (x ++ [a]) = M.stepSet (M.eval x) a :=
evalFrom_append_singleton ..
variable (M) in
/-- `M.accepts` is the language of `x` such that there is an accept state in `M.eval x`. -/
def accepts : Language α := {x | ∃ S ∈ M.accept, S ∈ M.eval x}
theorem mem_accepts {x : List α} : x ∈ M.accepts ↔ ∃ S ∈ M.accept, S ∈ M.evalFrom M.start x := by
rfl
variable (M) in
/-- `M.Path` represents a concrete path through the NFA from a start state to an end state
for a particular word.
Note that due to the non-deterministic nature of the automata, there can be more than one `Path`
for a given word.
Also note that this is `Type` and not a `Prop`, so that we can speak about the properties
of a particular `Path`, such as the set of states visited along the way (defined as `Path.supp`). -/
inductive Path : σ → σ → List α → Type (max u v)
| nil (s : σ) : Path s s []
| cons (t s u : σ) (a : α) (x : List α) :
t ∈ M.step s a → Path t u x → Path s u (a :: x)
/-- Set of states visited by a path. -/
@[simp]
def Path.supp [DecidableEq σ] {s t : σ} {x : List α} : M.Path s t x → Finset σ
| nil s => {s}
| cons _ _ _ _ _ _ p => {s} ∪ p.supp
theorem mem_evalFrom_iff_nonempty_path {s t : σ} {x : List α} :
t ∈ M.evalFrom {s} x ↔ Nonempty (M.Path s t x) where
mp h := match x with
| [] =>
have h : s = t := by simp at h; tauto
⟨h ▸ Path.nil s⟩
| a :: x =>
have h : ∃ s' ∈ M.step s a, t ∈ M.evalFrom {s'} x :=
by rw [evalFrom_cons, mem_evalFrom_iff_exists, stepSet_singleton] at h; exact h
let ⟨s', h₁, h₂⟩ := h
let ⟨p'⟩ := mem_evalFrom_iff_nonempty_path.1 h₂
⟨Path.cons s' _ _ _ _ h₁ p'⟩
mpr p := match p with
| ⟨Path.nil s⟩ => by simp
| ⟨Path.cons s' s t a x h₁ h₂⟩ => by
rw [evalFrom_cons, stepSet_singleton, mem_evalFrom_iff_exists]
exact ⟨s', h₁, mem_evalFrom_iff_nonempty_path.2 ⟨h₂⟩⟩
theorem accepts_iff_exists_path {x : List α} :
x ∈ M.accepts ↔ ∃ s ∈ M.start, ∃ t ∈ M.accept, Nonempty (M.Path s t x) := by
simp only [← mem_evalFrom_iff_nonempty_path, mem_accepts, mem_evalFrom_iff_exists (S := M.start)]
tauto
variable (M) in
/-- `M.toDFA` is a `DFA` constructed from an `NFA` `M` using the subset construction. The
states is the type of `Set`s of `M.state` and the step function is `M.stepSet`. -/
def toDFA : DFA α (Set σ) where
step := M.stepSet
start := M.start
accept := { S | ∃ s ∈ S, s ∈ M.accept }
@[simp]
theorem toDFA_correct : M.toDFA.accepts = M.accepts := by
ext x
rw [mem_accepts, DFA.mem_accepts]
constructor <;> · exact fun ⟨w, h2, h3⟩ => ⟨w, h3, h2⟩
theorem pumping_lemma [Fintype σ] {x : List α} (hx : x ∈ M.accepts)
(hlen : Fintype.card (Set σ) ≤ List.length x) :
∃ a b c,
x = a ++ b ++ c ∧
a.length + b.length ≤ Fintype.card (Set σ) ∧ b ≠ [] ∧ {a} * {b}∗ * {c} ≤ M.accepts := by
rw [← toDFA_correct] at hx ⊢
exact M.toDFA.pumping_lemma hx hlen
end NFA
namespace DFA
/-- `M.toNFA` is an `NFA` constructed from a `DFA` `M` by using the same start and accept
states and a transition function which sends `s` with input `a` to the singleton `M.step s a`. -/
@[simps] def toNFA (M : DFA α σ) : NFA α σ where
step s a := {M.step s a}
start := {M.start}
accept := M.accept
@[simp]
theorem toNFA_evalFrom_match (M : DFA α σ) (start : σ) (s : List α) :
M.toNFA.evalFrom {start} s = {M.evalFrom start s} := by
change List.foldl M.toNFA.stepSet {start} s = {List.foldl M.step start s}
induction s generalizing start with
| nil => tauto
| cons a s ih =>
rw [List.foldl, List.foldl,
show M.toNFA.stepSet {start} a = {M.step start a} by simp [NFA.stepSet] ]
tauto
@[simp]
theorem toNFA_correct (M : DFA α σ) : M.toNFA.accepts = M.accepts := by
ext x
rw [NFA.mem_accepts, toNFA_start, toNFA_evalFrom_match]
constructor
· rintro ⟨S, hS₁, hS₂⟩
rwa [Set.mem_singleton_iff.mp hS₂] at hS₁
· exact fun h => ⟨M.eval x, h, rfl⟩
end DFA
namespace NFA
variable (M) in
/-- `M.reverse` constructs an NFA with the same states as `M`, but all the transitions reversed. The
resulting automaton accepts a word `x` if and only if `M` accepts `List.reverse x`. -/
@[simps]
def reverse : NFA α σ where
step s a := { s' | s ∈ M.step s' a }
start := M.accept
accept := M.start
variable (M) in
@[simp]
theorem reverse_reverse : M.reverse.reverse = M := by
simp [reverse]
theorem disjoint_stepSet_reverse {a : α} {S S' : Set σ} :
Disjoint S (M.reverse.stepSet S' a) ↔ Disjoint S' (M.stepSet S a) := by
rw [← not_iff_not]
simp only [Set.not_disjoint_iff, mem_stepSet, reverse_step, Set.mem_setOf_eq]
tauto
theorem disjoint_evalFrom_reverse {x : List α} {S S' : Set σ}
(h : Disjoint S (M.reverse.evalFrom S' x)) : Disjoint S' (M.evalFrom S x.reverse) := by
simp only [evalFrom, List.foldl_reverse] at h ⊢
induction x generalizing S S' with
| nil =>
rw [disjoint_comm]
exact h
| cons x xs ih =>
rw [List.foldl_cons] at h
rw [List.foldr_cons, ← NFA.disjoint_stepSet_reverse, disjoint_comm]
exact ih h
theorem disjoint_evalFrom_reverse_iff {x : List α} {S S' : Set σ} :
Disjoint S (M.reverse.evalFrom S' x) ↔ Disjoint S' (M.evalFrom S x.reverse) :=
⟨disjoint_evalFrom_reverse, fun h ↦ List.reverse_reverse x ▸ disjoint_evalFrom_reverse h⟩
@[simp]
theorem mem_accepts_reverse {x : List α} : x ∈ M.reverse.accepts ↔ x.reverse ∈ M.accepts := by
simp [mem_accepts, ← Set.not_disjoint_iff, disjoint_evalFrom_reverse_iff]
end NFA
namespace Language
protected theorem IsRegular.reverse {L : Language α} (h : L.IsRegular) : L.reverse.IsRegular :=
have ⟨σ, _, M, hM⟩ := h
⟨_, inferInstance, M.toNFA.reverse.toDFA, by ext; simp [hM]⟩
protected theorem IsRegular.of_reverse {L : Language α} (h : L.reverse.IsRegular) : L.IsRegular :=
L.reverse_reverse ▸ h.reverse
/-- Regular languages are closed under reversal. -/
@[simp]
theorem isRegular_reverse_iff {L : Language α} : L.reverse.IsRegular ↔ L.IsRegular :=
⟨.of_reverse, .reverse⟩
end Language |
.lake/packages/mathlib/Mathlib/Computability/Partrec.lean | import Mathlib.Computability.Primrec
import Mathlib.Data.Nat.PSub
import Mathlib.Data.PFun
/-!
# The partial recursive functions
The partial recursive functions are defined similarly to the primitive
recursive functions, but now all functions are partial, implemented
using the `Part` monad, and there is an additional operation, called
μ-recursion, which performs unbounded minimization: `μ f` returns the
least natural number `n` for which `f n = 0`, or diverges if such `n` doesn't exist.
## Main definitions
- `Nat.Partrec f`: `f` is partial recursive, for functions `f : ℕ →. ℕ`
- `Partrec f`: `f` is partial recursive, for partial functions between `Primcodable` types
- `Computable f`: `f` is partial recursive, for total functions between `Primcodable` types
## References
* [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019]
-/
open List (Vector)
open Encodable Denumerable Part
attribute [-simp] not_forall
namespace Nat
section Rfind
variable (p : ℕ →. Bool)
private def lbp (m n : ℕ) : Prop :=
m = n + 1 ∧ ∀ k ≤ n, false ∈ p k
private def wf_lbp (H : ∃ n, true ∈ p n ∧ ∀ k < n, (p k).Dom) : WellFounded (lbp p) :=
⟨by
let ⟨n, pn⟩ := H
suffices ∀ m k, n ≤ k + m → Acc (lbp p) k by exact fun a => this _ _ (Nat.le_add_left _ _)
intro m k kn
induction m generalizing k with (refine ⟨_, fun y r => ?_⟩; rcases r with ⟨rfl, a⟩)
| zero => injection mem_unique pn.1 (a _ kn)
| succ m IH => exact IH _ (by rw [Nat.add_right_comm]; exact kn)⟩
variable (H : ∃ n, true ∈ p n ∧ ∀ k < n, (p k).Dom)
/-- Find the smallest `n` satisfying `p n`, where all `p k` for `k < n` are defined as false.
Returns a subtype. -/
def rfindX : { n // true ∈ p n ∧ ∀ m < n, false ∈ p m } :=
suffices ∀ k, (∀ n < k, false ∈ p n) → { n // true ∈ p n ∧ ∀ m < n, false ∈ p m } from
this 0 fun _ => (Nat.not_lt_zero _).elim
@WellFounded.fix _ _ (lbp p) (wf_lbp p H)
(by
intro m IH al
have pm : (p m).Dom := by
rcases H with ⟨n, h₁, h₂⟩
rcases lt_trichotomy m n with (h₃ | h₃ | h₃)
· exact h₂ _ h₃
· rw [h₃]
exact h₁.fst
· injection mem_unique h₁ (al _ h₃)
cases e : (p m).get pm
· suffices ∀ᵉ k ≤ m, false ∈ p k from IH _ ⟨rfl, this⟩ fun n h => this _ (le_of_lt_succ h)
intro n h
rcases h.lt_or_eq_dec with h | h
· exact al _ h
· rw [h]
exact ⟨_, e⟩
· exact ⟨m, ⟨_, e⟩, al⟩)
end Rfind
/-- Find the smallest `n` satisfying `p n`, where all `p k` for `k < n` are defined as false.
Returns a `Part`. -/
def rfind (p : ℕ →. Bool) : Part ℕ :=
⟨_, fun h => (rfindX p h).1⟩
theorem rfind_spec {p : ℕ →. Bool} {n : ℕ} (h : n ∈ rfind p) : true ∈ p n :=
h.snd ▸ (rfindX p h.fst).2.1
theorem rfind_min {p : ℕ →. Bool} {n : ℕ} (h : n ∈ rfind p) : ∀ {m : ℕ}, m < n → false ∈ p m :=
@(h.snd ▸ @((rfindX p h.fst).2.2))
@[simp]
theorem rfind_dom {p : ℕ →. Bool} :
(rfind p).Dom ↔ ∃ n, true ∈ p n ∧ ∀ {m : ℕ}, m < n → (p m).Dom :=
Iff.rfl
theorem rfind_dom' {p : ℕ →. Bool} :
(rfind p).Dom ↔ ∃ n, true ∈ p n ∧ ∀ {m : ℕ}, m ≤ n → (p m).Dom :=
exists_congr fun _ =>
and_congr_right fun pn =>
⟨fun H _ h => (Decidable.eq_or_lt_of_le h).elim (fun e => e.symm ▸ pn.fst) (H _), fun H _ h =>
H (le_of_lt h)⟩
@[simp]
theorem mem_rfind {p : ℕ →. Bool} {n : ℕ} :
n ∈ rfind p ↔ true ∈ p n ∧ ∀ {m : ℕ}, m < n → false ∈ p m :=
⟨fun h => ⟨rfind_spec h, @rfind_min _ _ h⟩, fun ⟨h₁, h₂⟩ => by
let ⟨m, hm⟩ := dom_iff_mem.1 <| (@rfind_dom p).2 ⟨_, h₁, fun {m} mn => (h₂ mn).fst⟩
rcases lt_trichotomy m n with (h | h | h)
· injection mem_unique (h₂ h) (rfind_spec hm)
· rwa [← h]
· injection mem_unique h₁ (rfind_min hm h)⟩
theorem rfind_min' {p : ℕ → Bool} {m : ℕ} (pm : p m) : ∃ n ∈ rfind p, n ≤ m :=
have : true ∈ (p : ℕ →. Bool) m := ⟨trivial, pm⟩
let ⟨n, hn⟩ := dom_iff_mem.1 <| (@rfind_dom p).2 ⟨m, this, fun {_} _ => ⟨⟩⟩
⟨n, hn, not_lt.1 fun h => by injection mem_unique this (rfind_min hn h)⟩
theorem rfind_zero_none (p : ℕ →. Bool) (p0 : p 0 = Part.none) : rfind p = Part.none :=
eq_none_iff.2 fun _ h =>
let ⟨_, _, h₂⟩ := rfind_dom'.1 h.fst
(p0 ▸ h₂ (zero_le _) : (@Part.none Bool).Dom)
/-- Find the smallest `n` satisfying `f n`, where all `f k` for `k < n` are defined as false.
Returns a `Part`. -/
def rfindOpt {α} (f : ℕ → Option α) : Part α :=
(rfind fun n => (f n).isSome).bind fun n => f n
theorem rfindOpt_spec {α} {f : ℕ → Option α} {a} (h : a ∈ rfindOpt f) : ∃ n, a ∈ f n :=
let ⟨n, _, h₂⟩ := mem_bind_iff.1 h
⟨n, mem_coe.1 h₂⟩
theorem rfindOpt_dom {α} {f : ℕ → Option α} : (rfindOpt f).Dom ↔ ∃ n a, a ∈ f n :=
⟨fun h => (rfindOpt_spec ⟨h, rfl⟩).imp fun _ h => ⟨_, h⟩, fun h => by
have h' : ∃ n, (f n).isSome := h.imp fun n => Option.isSome_iff_exists.2
have s := Nat.find_spec h'
have fd : (rfind fun n => (f n).isSome).Dom :=
⟨Nat.find h', by simpa using s.symm, fun _ _ => trivial⟩
refine ⟨fd, ?_⟩
have := rfind_spec (get_mem fd)
simpa using this⟩
theorem rfindOpt_mono {α} {f : ℕ → Option α} (H : ∀ {a m n}, m ≤ n → a ∈ f m → a ∈ f n) {a} :
a ∈ rfindOpt f ↔ ∃ n, a ∈ f n :=
⟨rfindOpt_spec, fun ⟨n, h⟩ => by
have h' := rfindOpt_dom.2 ⟨_, _, h⟩
obtain ⟨k, hk⟩ := rfindOpt_spec ⟨h', rfl⟩
have := (H (le_max_left _ _) h).symm.trans (H (le_max_right _ _) hk)
simp at this; simp [this, get_mem]⟩
/-- `Partrec f` means that the partial function `f : ℕ →. ℕ` is partially recursive. -/
inductive Partrec : (ℕ →. ℕ) → Prop
| zero : Partrec (pure 0)
| succ : Partrec succ
| left : Partrec ↑fun n : ℕ => n.unpair.1
| right : Partrec ↑fun n : ℕ => n.unpair.2
| pair {f g} : Partrec f → Partrec g → Partrec fun n => pair <$> f n <*> g n
| comp {f g} : Partrec f → Partrec g → Partrec fun n => g n >>= f
| prec {f g} : Partrec f → Partrec g → Partrec (unpaired fun a n =>
n.rec (f a) fun y IH => do let i ← IH; g (pair a (pair y i)))
| rfind {f} : Partrec f → Partrec fun a => rfind fun n => (fun m => m = 0) <$> f (pair a n)
namespace Partrec
theorem of_eq {f g : ℕ →. ℕ} (hf : Partrec f) (H : ∀ n, f n = g n) : Partrec g :=
(funext H : f = g) ▸ hf
theorem of_eq_tot {f : ℕ →. ℕ} {g : ℕ → ℕ} (hf : Partrec f) (H : ∀ n, g n ∈ f n) : Partrec g :=
hf.of_eq fun n => eq_some_iff.2 (H n)
theorem of_primrec {f : ℕ → ℕ} (hf : Nat.Primrec f) : Partrec f := by
induction hf with
| zero => exact zero
| succ => exact succ
| left => exact left
| right => exact right
| pair _ _ pf pg =>
refine (pf.pair pg).of_eq_tot fun n => ?_
simp [Seq.seq]
| comp _ _ pf pg =>
refine (pf.comp pg).of_eq_tot fun n => (by simp)
| prec _ _ pf pg =>
refine (pf.prec pg).of_eq_tot fun n => ?_
simp only [unpaired, PFun.coe_val, bind_eq_bind]
induction n.unpair.2 with
| zero => simp
| succ m IH =>
simp only [mem_bind_iff, mem_some_iff]
exact ⟨_, IH, rfl⟩
protected theorem some : Partrec some :=
of_primrec Primrec.id
theorem none : Partrec fun _ => none :=
(of_primrec (Nat.Primrec.const 1)).rfind.of_eq fun _ =>
eq_none_iff.2 fun _ ⟨h, _⟩ => by simp at h
theorem prec' {f g h} (hf : Partrec f) (hg : Partrec g) (hh : Partrec h) :
Partrec fun a => (f a).bind fun n => n.rec (g a)
fun y IH => do {let i ← IH; h (Nat.pair a (Nat.pair y i))} :=
((prec hg hh).comp (pair Partrec.some hf)).of_eq fun a =>
ext fun s => by simp [Seq.seq]
theorem ppred : Partrec fun n => ppred n :=
have : Primrec₂ fun n m => if n = Nat.succ m then 0 else 1 :=
(Primrec.ite
(@PrimrecRel.comp _ _ _ _ _ _ _ _ _
Primrec.eq Primrec.fst (_root_.Primrec.succ.comp Primrec.snd))
(_root_.Primrec.const 0) (_root_.Primrec.const 1)).to₂
(of_primrec (Primrec₂.unpaired'.2 this)).rfind.of_eq fun n => by
cases n <;> simp
· exact
eq_none_iff.2 fun a ⟨⟨m, h, _⟩, _⟩ => by
simp at h
· refine eq_some_iff.2 ?_
simp only [mem_rfind, decide_true, mem_some_iff,
false_eq_decide_iff, true_and]
intro m h
simp [ne_of_gt h]
end Partrec
end Nat
/-- Partially recursive partial functions `α → σ` between `Primcodable` types -/
def Partrec {α σ} [Primcodable α] [Primcodable σ] (f : α →. σ) :=
Nat.Partrec fun n => Part.bind (decode (α := α) n) fun a => (f a).map encode
/-- Partially recursive partial functions `α → β → σ` between `Primcodable` types -/
def Partrec₂ {α β σ} [Primcodable α] [Primcodable β] [Primcodable σ] (f : α → β →. σ) :=
Partrec fun p : α × β => f p.1 p.2
/-- Computable functions `α → σ` between `Primcodable` types:
a function is computable if and only if it is partially recursive (as a partial function) -/
def Computable {α σ} [Primcodable α] [Primcodable σ] (f : α → σ) :=
Partrec (f : α →. σ)
/-- Computable functions `α → β → σ` between `Primcodable` types -/
def Computable₂ {α β σ} [Primcodable α] [Primcodable β] [Primcodable σ] (f : α → β → σ) :=
Computable fun p : α × β => f p.1 p.2
theorem Primrec.to_comp {α σ} [Primcodable α] [Primcodable σ] {f : α → σ} (hf : Primrec f) :
Computable f :=
(Nat.Partrec.ppred.comp (Nat.Partrec.of_primrec hf)).of_eq fun n => by
simp; cases decode (α := α) n <;> simp
nonrec theorem Primrec₂.to_comp {α β σ} [Primcodable α] [Primcodable β] [Primcodable σ]
{f : α → β → σ} (hf : Primrec₂ f) : Computable₂ f :=
hf.to_comp
protected theorem Computable.partrec {α σ} [Primcodable α] [Primcodable σ] {f : α → σ}
(hf : Computable f) : Partrec (f : α →. σ) :=
hf
protected theorem Computable₂.partrec₂ {α β σ} [Primcodable α] [Primcodable β] [Primcodable σ]
{f : α → β → σ} (hf : Computable₂ f) : Partrec₂ fun a => (f a : β →. σ) :=
hf
namespace Computable
variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ]
theorem of_eq {f g : α → σ} (hf : Computable f) (H : ∀ n, f n = g n) : Computable g :=
(funext H : f = g) ▸ hf
theorem const (s : σ) : Computable fun _ : α => s :=
(Primrec.const _).to_comp
theorem ofOption {f : α → Option β} (hf : Computable f) : Partrec fun a => (f a : Part β) :=
(Nat.Partrec.ppred.comp hf).of_eq fun n => by
rcases decode (α := α) n with - | a <;> simp
rcases f a with - | b <;> simp
theorem to₂ {f : α × β → σ} (hf : Computable f) : Computable₂ fun a b => f (a, b) :=
hf.of_eq fun ⟨_, _⟩ => rfl
protected theorem id : Computable (@id α) :=
Primrec.id.to_comp
theorem fst : Computable (@Prod.fst α β) :=
Primrec.fst.to_comp
theorem snd : Computable (@Prod.snd α β) :=
Primrec.snd.to_comp
nonrec theorem pair {f : α → β} {g : α → γ} (hf : Computable f) (hg : Computable g) :
Computable fun a => (f a, g a) :=
(hf.pair hg).of_eq fun n => by cases decode (α := α) n <;> simp [Seq.seq]
theorem unpair : Computable Nat.unpair :=
Primrec.unpair.to_comp
theorem succ : Computable Nat.succ :=
Primrec.succ.to_comp
theorem pred : Computable Nat.pred :=
Primrec.pred.to_comp
theorem nat_bodd : Computable Nat.bodd :=
Primrec.nat_bodd.to_comp
theorem nat_div2 : Computable Nat.div2 :=
Primrec.nat_div2.to_comp
theorem sumInl : Computable (@Sum.inl α β) :=
Primrec.sumInl.to_comp
theorem sumInr : Computable (@Sum.inr α β) :=
Primrec.sumInr.to_comp
theorem list_cons : Computable₂ (@List.cons α) :=
Primrec.list_cons.to_comp
theorem list_reverse : Computable (@List.reverse α) :=
Primrec.list_reverse.to_comp
theorem list_getElem? : Computable₂ ((·[·]? : List α → ℕ → Option α)) :=
Primrec.list_getElem?.to_comp
theorem list_append : Computable₂ ((· ++ ·) : List α → List α → List α) :=
Primrec.list_append.to_comp
theorem list_concat : Computable₂ fun l (a : α) => l ++ [a] :=
Primrec.list_concat.to_comp
theorem list_length : Computable (@List.length α) :=
Primrec.list_length.to_comp
theorem vector_cons {n} : Computable₂ (@List.Vector.cons α n) :=
Primrec.vector_cons.to_comp
theorem vector_toList {n} : Computable (@List.Vector.toList α n) :=
Primrec.vector_toList.to_comp
theorem vector_length {n} : Computable (@List.Vector.length α n) :=
Primrec.vector_length.to_comp
theorem vector_head {n} : Computable (@List.Vector.head α n) :=
Primrec.vector_head.to_comp
theorem vector_tail {n} : Computable (@List.Vector.tail α n) :=
Primrec.vector_tail.to_comp
theorem vector_get {n} : Computable₂ (@List.Vector.get α n) :=
Primrec.vector_get.to_comp
theorem vector_ofFn' {n} : Computable (@List.Vector.ofFn α n) :=
Primrec.vector_ofFn'.to_comp
theorem fin_app {n} : Computable₂ (@id (Fin n → σ)) :=
Primrec.fin_app.to_comp
protected theorem encode : Computable (@encode α _) :=
Primrec.encode.to_comp
protected theorem decode : Computable (decode (α := α)) :=
Primrec.decode.to_comp
protected theorem ofNat (α) [Denumerable α] : Computable (ofNat α) :=
(Primrec.ofNat _).to_comp
theorem encode_iff {f : α → σ} : (Computable fun a => encode (f a)) ↔ Computable f :=
Iff.rfl
theorem option_some : Computable (@Option.some α) :=
Primrec.option_some.to_comp
end Computable
namespace Partrec
variable {α : Type*} {β : Type*} {σ : Type*} [Primcodable α] [Primcodable β] [Primcodable σ]
open Computable
theorem of_eq {f g : α →. σ} (hf : Partrec f) (H : ∀ n, f n = g n) : Partrec g :=
(funext H : f = g) ▸ hf
theorem of_eq_tot {f : α →. σ} {g : α → σ} (hf : Partrec f) (H : ∀ n, g n ∈ f n) : Computable g :=
hf.of_eq fun a => eq_some_iff.2 (H a)
theorem none : Partrec fun _ : α => @Part.none σ :=
Nat.Partrec.none.of_eq fun n => by cases decode (α := α) n <;> simp
protected theorem some : Partrec (@Part.some α) :=
Computable.id
theorem _root_.Decidable.Partrec.const' (s : Part σ) [Decidable s.Dom] : Partrec fun _ : α => s :=
(Computable.ofOption (const (toOption s))).of_eq fun _ => of_toOption s
theorem const' (s : Part σ) : Partrec fun _ : α => s :=
haveI := Classical.dec s.Dom
Decidable.Partrec.const' s
protected theorem bind {f : α →. β} {g : α → β →. σ} (hf : Partrec f) (hg : Partrec₂ g) :
Partrec fun a => (f a).bind (g a) :=
(hg.comp (Nat.Partrec.some.pair hf)).of_eq fun n => by
simp [Seq.seq]; rcases e : decode (α := α) n with - | a <;> simp [e, encodek]
theorem map {f : α →. β} {g : α → β → σ} (hf : Partrec f) (hg : Computable₂ g) :
Partrec fun a => (f a).map (g a) := by
simpa [bind_some_eq_map] using Partrec.bind (g := fun a x => some (g a x)) hf hg
theorem to₂ {f : α × β →. σ} (hf : Partrec f) : Partrec₂ fun a b => f (a, b) :=
hf.of_eq fun ⟨_, _⟩ => rfl
theorem nat_rec {f : α → ℕ} {g : α →. σ} {h : α → ℕ × σ →. σ} (hf : Computable f) (hg : Partrec g)
(hh : Partrec₂ h) : Partrec fun a => (f a).rec (g a) fun y IH => IH.bind fun i => h a (y, i) :=
(Nat.Partrec.prec' hf hg hh).of_eq fun n => by
rcases e : decode (α := α) n with - | a <;> simp [e]
induction f a with simp | succ m IH
rw [IH, Part.bind_map]
congr; funext s
simp [encodek]
nonrec theorem comp {f : β →. σ} {g : α → β} (hf : Partrec f) (hg : Computable g) :
Partrec fun a => f (g a) :=
(hf.comp hg).of_eq fun n => by simp; rcases e : decode (α := α) n with - | a <;> simp [encodek]
theorem nat_iff {f : ℕ →. ℕ} : Partrec f ↔ Nat.Partrec f := by simp [Partrec, map_id']
theorem map_encode_iff {f : α →. σ} : (Partrec fun a => (f a).map encode) ↔ Partrec f :=
Iff.rfl
end Partrec
namespace Partrec₂
variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable δ] [Primcodable σ]
theorem unpaired {f : ℕ → ℕ →. α} : Partrec (Nat.unpaired f) ↔ Partrec₂ f :=
⟨fun h => by simpa using Partrec.comp (g := fun p : ℕ × ℕ => (p.1, p.2)) h Primrec₂.pair.to_comp,
fun h => h.comp Primrec.unpair.to_comp⟩
theorem unpaired' {f : ℕ → ℕ →. ℕ} : Nat.Partrec (Nat.unpaired f) ↔ Partrec₂ f :=
Partrec.nat_iff.symm.trans unpaired
nonrec theorem comp {f : β → γ →. σ} {g : α → β} {h : α → γ} (hf : Partrec₂ f) (hg : Computable g)
(hh : Computable h) : Partrec fun a => f (g a) (h a) :=
hf.comp (hg.pair hh)
theorem comp₂ {f : γ → δ →. σ} {g : α → β → γ} {h : α → β → δ} (hf : Partrec₂ f)
(hg : Computable₂ g) (hh : Computable₂ h) : Partrec₂ fun a b => f (g a b) (h a b) :=
hf.comp hg hh
end Partrec₂
namespace Computable
variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ]
nonrec theorem comp {f : β → σ} {g : α → β} (hf : Computable f) (hg : Computable g) :
Computable fun a => f (g a) :=
hf.comp hg
theorem comp₂ {f : γ → σ} {g : α → β → γ} (hf : Computable f) (hg : Computable₂ g) :
Computable₂ fun a b => f (g a b) :=
hf.comp hg
end Computable
namespace Computable₂
variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable δ] [Primcodable σ]
theorem mk {f : α → β → σ} (hf : Computable fun p : α × β => f p.1 p.2) : Computable₂ f := hf
nonrec theorem comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : Computable₂ f)
(hg : Computable g) (hh : Computable h) : Computable fun a => f (g a) (h a) :=
hf.comp (hg.pair hh)
theorem comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : Computable₂ f)
(hg : Computable₂ g) (hh : Computable₂ h) : Computable₂ fun a b => f (g a b) (h a b) :=
hf.comp hg hh
end Computable₂
namespace Partrec
variable {α : Type*} {σ : Type*} [Primcodable α] [Primcodable σ]
open Computable
theorem rfind {p : α → ℕ →. Bool} (hp : Partrec₂ p) : Partrec fun a => Nat.rfind (p a) :=
(Nat.Partrec.rfind <|
hp.map ((Primrec.dom_bool fun b => cond b 0 1).comp Primrec.snd).to₂.to_comp).of_eq
fun n => by
rcases e : decode (α := α) n with - | a <;> simp [e, Nat.rfind_zero_none, map_id']
congr; funext n
simp only [map_map]
refine map_id' (fun b => ?_) _
cases b <;> rfl
theorem rfindOpt {f : α → ℕ → Option σ} (hf : Computable₂ f) :
Partrec fun a => Nat.rfindOpt (f a) :=
(rfind (Primrec.option_isSome.to_comp.comp hf).partrec.to₂).bind (ofOption hf)
theorem nat_casesOn_right {f : α → ℕ} {g : α → σ} {h : α → ℕ →. σ} (hf : Computable f)
(hg : Computable g) (hh : Partrec₂ h) : Partrec fun a => (f a).casesOn (some (g a)) (h a) :=
(nat_rec hf hg (hh.comp fst (pred.comp <| hf.comp fst)).to₂).of_eq fun a => by
simp only [PFun.coe_val, Nat.pred_eq_sub_one]; rcases f a with - | n <;> simp
refine ext fun b => ⟨fun H => ?_, fun H => ?_⟩
· rcases mem_bind_iff.1 H with ⟨c, _, h₂⟩
exact h₂
· have : ∀ m, (Nat.rec (motive := fun _ => Part σ)
(Part.some (g a)) (fun y IH => IH.bind fun _ => h a n) m).Dom := by
intro m
induction m <;> simp [*, H.fst]
exact ⟨⟨this n, H.fst⟩, H.snd⟩
theorem bind_decode₂_iff {f : α →. σ} :
Partrec f ↔ Nat.Partrec fun n => Part.bind (decode₂ α n) fun a => (f a).map encode :=
⟨fun hf =>
nat_iff.1 <|
(Computable.ofOption Primrec.decode₂.to_comp).bind <|
(map hf (Computable.encode.comp snd).to₂).comp snd,
fun h =>
map_encode_iff.1 <| by simpa [encodek₂] using (nat_iff.2 h).comp (@Computable.encode α _)⟩
theorem vector_mOfFn :
∀ {n} {f : Fin n → α →. σ},
(∀ i, Partrec (f i)) → Partrec fun a : α => Vector.mOfFn fun i => f i a
| 0, _, _ => const _
| n + 1, f, hf => by
simp only [Vector.mOfFn, pure_eq_some, bind_eq_bind]
exact
(hf 0).bind
(Partrec.bind ((vector_mOfFn fun i => hf i.succ).comp fst)
(Primrec.vector_cons.to_comp.comp (snd.comp fst) snd))
end Partrec
@[simp]
theorem Vector.mOfFn_part_some {α n} :
∀ f : Fin n → α,
(List.Vector.mOfFn fun i => Part.some (f i)) = Part.some (List.Vector.ofFn f) :=
Vector.mOfFn_pure
namespace Computable
variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ]
theorem option_some_iff {f : α → σ} : (Computable fun a => Option.some (f a)) ↔ Computable f :=
⟨fun h => encode_iff.1 <| Primrec.pred.to_comp.comp <| encode_iff.2 h, option_some.comp⟩
theorem bind_decode_iff {f : α → β → Option σ} :
(Computable₂ fun a n => (decode (α := β) n).bind (f a)) ↔ Computable₂ f :=
⟨fun hf =>
Nat.Partrec.of_eq
(((Partrec.nat_iff.2
(Nat.Partrec.ppred.comp <| Nat.Partrec.of_primrec <| Primcodable.prim (α := β))).comp
snd).bind
(Computable.comp hf fst).to₂.partrec₂)
fun n => by
simp only [decode_prod_val, decode_nat, Option.map_some, PFun.coe_val, bind_eq_bind,
bind_some, Part.map_bind, map_some]
cases decode (α := α) n.unpair.1 <;> simp
cases decode (α := β) n.unpair.2 <;> simp,
fun hf => by
have :
Partrec fun a : α × ℕ =>
(encode (decode (α := β) a.2)).casesOn (some Option.none)
fun n => Part.map (f a.1) (decode (α := β) n) :=
Partrec.nat_casesOn_right
(h := fun (a : α × ℕ) (n : ℕ) ↦ map (fun b ↦ f a.1 b) (Part.ofOption (decode n)))
(Primrec.encdec.to_comp.comp snd) (const Option.none)
((ofOption (Computable.decode.comp snd)).map (hf.comp (fst.comp <| fst.comp fst) snd).to₂)
refine this.of_eq fun a => ?_
simp; cases decode (α := β) a.2 <;> simp [encodek]⟩
theorem map_decode_iff {f : α → β → σ} :
(Computable₂ fun a n => (decode (α := β) n).map (f a)) ↔ Computable₂ f := by
convert (bind_decode_iff (f := fun a => Option.some ∘ f a)).trans option_some_iff
apply Option.map_eq_bind
theorem nat_rec {f : α → ℕ} {g : α → σ} {h : α → ℕ × σ → σ} (hf : Computable f) (hg : Computable g)
(hh : Computable₂ h) :
Computable fun a => Nat.rec (motive := fun _ => σ) (g a) (fun y IH => h a (y, IH)) (f a) :=
(Partrec.nat_rec hf hg hh.partrec₂).of_eq fun a => by simp; induction f a <;> simp [*]
theorem nat_casesOn {f : α → ℕ} {g : α → σ} {h : α → ℕ → σ} (hf : Computable f) (hg : Computable g)
(hh : Computable₂ h) :
Computable fun a => Nat.casesOn (motive := fun _ => σ) (f a) (g a) (h a) :=
nat_rec hf hg (hh.comp fst <| fst.comp snd).to₂
theorem cond {c : α → Bool} {f : α → σ} {g : α → σ} (hc : Computable c) (hf : Computable f)
(hg : Computable g) : Computable fun a => cond (c a) (f a) (g a) :=
(nat_casesOn (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq fun a => by cases c a <;> rfl
theorem option_casesOn {o : α → Option β} {f : α → σ} {g : α → β → σ} (ho : Computable o)
(hf : Computable f) (hg : Computable₂ g) :
@Computable _ σ _ _ fun a => Option.casesOn (o a) (f a) (g a) :=
option_some_iff.1 <|
(nat_casesOn (encode_iff.2 ho) (option_some_iff.2 hf) (map_decode_iff.2 hg)).of_eq fun a => by
cases o a <;> simp [encodek]
theorem option_bind {f : α → Option β} {g : α → β → Option σ} (hf : Computable f)
(hg : Computable₂ g) : Computable fun a => (f a).bind (g a) :=
(option_casesOn hf (const Option.none) hg).of_eq fun a => by cases f a <;> rfl
theorem option_map {f : α → Option β} {g : α → β → σ} (hf : Computable f) (hg : Computable₂ g) :
Computable fun a => (f a).map (g a) := by
convert option_bind hf (option_some.comp₂ hg)
apply Option.map_eq_bind
theorem option_getD {f : α → Option β} {g : α → β} (hf : Computable f) (hg : Computable g) :
Computable fun a => (f a).getD (g a) :=
(Computable.option_casesOn hf hg (show Computable₂ fun _ b => b from Computable.snd)).of_eq
fun a => by cases f a <;> rfl
theorem subtype_mk {f : α → β} {p : β → Prop} [DecidablePred p] {h : ∀ a, p (f a)}
(hp : PrimrecPred p) (hf : Computable f) :
@Computable _ _ _ (Primcodable.subtype hp) fun a => (⟨f a, h a⟩ : Subtype p) :=
hf
theorem sumCasesOn {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : Computable f)
(hg : Computable₂ g) (hh : Computable₂ h) :
@Computable _ σ _ _ fun a => Sum.casesOn (f a) (g a) (h a) :=
option_some_iff.1 <|
(cond (nat_bodd.comp <| encode_iff.2 hf)
(option_map (Computable.decode.comp <| nat_div2.comp <| encode_iff.2 hf) hh)
(option_map (Computable.decode.comp <| nat_div2.comp <| encode_iff.2 hf) hg)).of_eq
fun a => by
rcases f a with b | c <;> simp [Nat.div2_val]
theorem nat_strong_rec (f : α → ℕ → σ) {g : α → List σ → Option σ} (hg : Computable₂ g)
(H : ∀ a n, g a ((List.range n).map (f a)) = Option.some (f a n)) : Computable₂ f :=
suffices Computable₂ fun a n => (List.range n).map (f a) from
option_some_iff.1 <|
(list_getElem?.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq fun a => by
simp
option_some_iff.1 <|
(nat_rec snd (const (Option.some []))
(to₂ <|
option_bind (snd.comp snd) <|
to₂ <|
option_map (hg.comp (fst.comp <| fst.comp fst) snd)
(to₂ <| list_concat.comp (snd.comp fst) snd))).of_eq
fun a => by
induction a.2 with
| zero => rfl
| succ n IH => simp [IH, H, List.range_succ]
theorem list_ofFn :
∀ {n} {f : Fin n → α → σ},
(∀ i, Computable (f i)) → Computable fun a => List.ofFn fun i => f i a
| 0, _, _ => by
simp only [List.ofFn_zero]
exact const []
| n + 1, f, hf => by
simp only [List.ofFn_succ]
exact list_cons.comp (hf 0) (list_ofFn fun i => hf i.succ)
theorem vector_ofFn {n} {f : Fin n → α → σ} (hf : ∀ i, Computable (f i)) :
Computable fun a => List.Vector.ofFn fun i => f i a :=
(Partrec.vector_mOfFn hf).of_eq fun a => by simp
end Computable
namespace Partrec
variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ]
open Computable
theorem option_some_iff {f : α →. σ} : (Partrec fun a => (f a).map Option.some) ↔ Partrec f :=
⟨fun h => (Nat.Partrec.ppred.comp h).of_eq fun n => by simp [Part.bind_assoc, bind_some_eq_map],
fun hf => hf.map (option_some.comp snd).to₂⟩
theorem optionCasesOn_right {o : α → Option β} {f : α → σ} {g : α → β →. σ} (ho : Computable o)
(hf : Computable f) (hg : Partrec₂ g) :
@Partrec _ σ _ _ fun a => Option.casesOn (o a) (Part.some (f a)) (g a) :=
have :
Partrec fun a : α =>
Nat.casesOn (encode (o a)) (Part.some (f a)) (fun n => Part.bind (decode (α := β) n) (g a)) :=
nat_casesOn_right (h := fun a n ↦ Part.bind (ofOption (decode n)) fun b ↦ g a b)
(encode_iff.2 ho) hf.partrec <|
((@Computable.decode β _).comp snd).ofOption.bind (hg.comp (fst.comp fst) snd).to₂
this.of_eq fun a => by rcases o a with - | b <;> simp [encodek]
theorem sumCasesOn_right {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ →. σ} (hf : Computable f)
(hg : Computable₂ g) (hh : Partrec₂ h) :
@Partrec _ σ _ _ fun a => Sum.casesOn (f a) (fun b => Part.some (g a b)) (h a) :=
have :
Partrec fun a =>
(Option.casesOn (Sum.casesOn (f a) (fun _ => Option.none) Option.some : Option γ)
(some (Sum.casesOn (f a) (fun b => some (g a b)) fun _ => Option.none)) fun c =>
(h a c).map Option.some :
Part (Option σ)) :=
optionCasesOn_right (g := fun a n => Part.map Option.some (h a n))
(sumCasesOn hf (const Option.none).to₂ (option_some.comp snd).to₂)
(sumCasesOn (g := fun a n => Option.some (g a n)) hf (option_some.comp hg)
(const Option.none).to₂)
(option_some_iff.2 hh)
option_some_iff.1 <| this.of_eq fun a => by cases f a <;> simp
theorem sumCasesOn_left {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ → σ} (hf : Computable f)
(hg : Partrec₂ g) (hh : Computable₂ h) :
@Partrec _ σ _ _ fun a => Sum.casesOn (f a) (g a) fun c => Part.some (h a c) :=
(sumCasesOn_right (sumCasesOn hf (sumInr.comp snd).to₂ (sumInl.comp snd).to₂) hh hg).of_eq
fun a => by cases f a <;> simp
theorem fix_aux {α σ} (f : α →. σ ⊕ α) (a : α) (b : σ) :
let F : α → ℕ →. σ ⊕ α := fun a n =>
n.rec (some (Sum.inr a)) fun _ IH => IH.bind fun s => Sum.casesOn s (fun _ => Part.some s) f
(∃ n : ℕ,
((∃ b' : σ, Sum.inl b' ∈ F a n) ∧ ∀ {m : ℕ}, m < n → ∃ b : α, Sum.inr b ∈ F a m) ∧
Sum.inl b ∈ F a n) ↔
b ∈ PFun.fix f a := by
intro F; refine ⟨fun h => ?_, fun h => ?_⟩
· rcases h with ⟨n, ⟨_x, h₁⟩, h₂⟩
have : ∀ m a', Sum.inr a' ∈ F a m → b ∈ PFun.fix f a' → b ∈ PFun.fix f a := by
intro m a' am ba
induction m generalizing a' with simp [F] at am
| zero => rwa [← am]
| succ m IH =>
rcases am with ⟨a₂, am₂, fa₂⟩
exact IH _ am₂ (PFun.mem_fix_iff.2 (Or.inr ⟨_, fa₂, ba⟩))
cases n <;> simp [F] at h₂
rcases h₂ with (h₂ | ⟨a', am', fa'⟩)
· obtain ⟨a', h⟩ := h₁ (Nat.lt_succ_self _)
injection mem_unique h h₂
· exact this _ _ am' (PFun.mem_fix_iff.2 (Or.inl fa'))
· suffices ∀ a', b ∈ PFun.fix f a' → ∀ k, Sum.inr a' ∈ F a k →
∃ n, Sum.inl b ∈ F a n ∧ ∀ m < n, k ≤ m → ∃ a₂, Sum.inr a₂ ∈ F a m by
rcases this _ h 0 (by simp [F]) with ⟨n, hn₁, hn₂⟩
exact ⟨_, ⟨⟨_, hn₁⟩, fun {m} mn => hn₂ m mn (Nat.zero_le _)⟩, hn₁⟩
intro a₁ h₁
apply @PFun.fixInduction _ _ _ _ _ _ h₁
intro a₂ h₂ IH k hk
rcases PFun.mem_fix_iff.1 h₂ with (h₂ | ⟨a₃, am₃, _⟩)
· refine ⟨k.succ, ?_, fun m mk km => ⟨a₂, ?_⟩⟩
· simpa [F] using Or.inr ⟨_, hk, h₂⟩
· rwa [le_antisymm (Nat.le_of_lt_succ mk) km]
· rcases IH _ am₃ k.succ (by simpa [F] using ⟨_, hk, am₃⟩) with ⟨n, hn₁, hn₂⟩
grind
theorem fix {f : α →. σ ⊕ α} (hf : Partrec f) : Partrec (PFun.fix f) := by
let F : α → ℕ →. σ ⊕ α := fun a n =>
n.rec (some (Sum.inr a)) fun _ IH => IH.bind fun s => Sum.casesOn s (fun _ => Part.some s) f
have hF : Partrec₂ F :=
Partrec.nat_rec snd (sumInr.comp fst).partrec
(sumCasesOn_right (snd.comp snd) (snd.comp <| snd.comp fst).to₂ (hf.comp snd).to₂).to₂
let p a n := @Part.map _ Bool (fun s => Sum.casesOn s (fun _ => true) fun _ => false) (F a n)
have hp : Partrec₂ p :=
hF.map ((sumCasesOn Computable.id (const true).to₂ (const false).to₂).comp snd).to₂
exact ((Partrec.rfind hp).bind (hF.bind (sumCasesOn_right snd snd.to₂ none.to₂).to₂).to₂).of_eq
fun a => ext fun b => by simpa [p] using fix_aux f _ _
end Partrec |
.lake/packages/mathlib/Mathlib/Computability/TMConfig.lean | import Mathlib.Computability.Halting
import Mathlib.Computability.PostTuringMachine
import Mathlib.Tactic.DeriveFintype
/-!
# Modelling partial recursive functions using Turing machines
The files `TMConfig` and `TMToPartrec` define a simplified basis for partial recursive functions,
and a `Turing.TM2` model
Turing machine for evaluating these functions. This amounts to a constructive proof that every
`Partrec` function can be evaluated by a Turing machine.
## Main definitions
* `ToPartrec.Code`: a simplified basis for partial recursive functions, valued in
`List ℕ →. List ℕ`.
* `ToPartrec.Code.eval`: semantics for a `ToPartrec.Code` program
-/
open List (Vector)
open Function (update)
open Relation
namespace Turing
/-!
## A simplified basis for partrec
This section constructs the type `Code`, which is a data type of programs with `List ℕ` input and
output, with enough expressivity to write any partial recursive function. The primitives are:
* `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`.
* `succ` returns the successor of the head of the input, defaulting to zero if there is no head:
* `succ [] = [1]`
* `succ (n :: v) = [n + 1]`
* `tail` returns the tail of the input
* `tail [] = []`
* `tail (n :: v) = v`
* `cons f fs` calls `f` and `fs` on the input and conses the results:
* `cons f fs v = (f v).head :: fs v`
* `comp f g` calls `f` on the output of `g`:
* `comp f g v = f (g v)`
* `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or
a successor (similar to `Nat.casesOn`).
* `case f g [] = f []`
* `case f g (0 :: v) = f v`
* `case f g (n+1 :: v) = g (n :: v)`
* `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f`
again or finish:
* `fix f v = []` if `f v = []`
* `fix f v = w` if `f v = 0 :: w`
* `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded)
This basis is convenient because it is closer to the Turing machine model - the key operations are
splitting and merging of lists of unknown length, while the messy `n`-ary composition operation
from the traditional basis for partial recursive functions is absent - but it retains a
compositional semantics. The first step in transitioning to Turing machines is to make a sequential
evaluator for this basis, which we take up in the next section.
-/
namespace ToPartrec
/-- The type of codes for primitive recursive functions. Unlike `Nat.Partrec.Code`, this uses a set
of operations on `List ℕ`. See `Code.eval` for a description of the behavior of the primitives. -/
inductive Code
| zero'
| succ
| tail
| cons : Code → Code → Code
| comp : Code → Code → Code
| case : Code → Code → Code
| fix : Code → Code
deriving DecidableEq, Inhabited
/-- The semantics of the `Code` primitives, as partial functions `List ℕ →. List ℕ`. By convention
we functions that return a single result return a singleton `[n]`, or in some cases `n :: v` where
`v` will be ignored by a subsequent function.
* `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`.
* `succ` returns the successor of the head of the input, defaulting to zero if there is no head:
* `succ [] = [1]`
* `succ (n :: v) = [n + 1]`
* `tail` returns the tail of the input
* `tail [] = []`
* `tail (n :: v) = v`
* `cons f fs` calls `f` and `fs` on the input and conses the results:
* `cons f fs v = (f v).head :: fs v`
* `comp f g` calls `f` on the output of `g`:
* `comp f g v = f (g v)`
* `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or
a successor (similar to `Nat.casesOn`).
* `case f g [] = f []`
* `case f g (0 :: v) = f v`
* `case f g (n+1 :: v) = g (n :: v)`
* `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f`
again or finish:
* `fix f v = []` if `f v = []`
* `fix f v = w` if `f v = 0 :: w`
* `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded)
-/
def Code.eval : Code → List ℕ →. List ℕ
| Code.zero' => fun v => pure (0 :: v)
| Code.succ => fun v => pure [v.headI.succ]
| Code.tail => fun v => pure v.tail
| Code.cons f fs => fun v => do
let n ← Code.eval f v
let ns ← Code.eval fs v
pure (n.headI :: ns)
| Code.comp f g => fun v => g.eval v >>= f.eval
| Code.case f g => fun v => v.headI.rec (f.eval v.tail) fun y _ => g.eval (y::v.tail)
| Code.fix f =>
PFun.fix fun v => (f.eval v).map fun v => if v.headI = 0 then Sum.inl v.tail else Sum.inr v.tail
namespace Code
@[simp]
theorem zero'_eval : zero'.eval = fun v => pure (0 :: v) := by simp [eval]
@[simp]
theorem succ_eval : succ.eval = fun v => pure [v.headI.succ] := by simp [eval]
@[simp]
theorem tail_eval : tail.eval = fun v => pure v.tail := by simp [eval]
@[simp]
theorem cons_eval (f fs) : (cons f fs).eval = fun v => do {
let n ← Code.eval f v
let ns ← Code.eval fs v
pure (n.headI :: ns) } := by simp [eval]
@[simp]
theorem comp_eval (f g) : (comp f g).eval = fun v => g.eval v >>= f.eval := by simp [eval]
@[simp]
theorem case_eval (f g) :
(case f g).eval = fun v => v.headI.rec (f.eval v.tail) fun y _ => g.eval (y::v.tail) := by
simp [eval]
@[simp]
theorem fix_eval (f) : (fix f).eval =
PFun.fix fun v => (f.eval v).map fun v =>
if v.headI = 0 then Sum.inl v.tail else Sum.inr v.tail := by
simp [eval]
/-- `nil` is the constant nil function: `nil v = []`. -/
def nil : Code :=
tail.comp succ
@[simp]
theorem nil_eval (v) : nil.eval v = pure [] := by simp [nil]
/-- `id` is the identity function: `id v = v`. -/
def id : Code :=
tail.comp zero'
@[simp]
theorem id_eval (v) : id.eval v = pure v := by simp [id]
/-- `head` gets the head of the input list: `head [] = [0]`, `head (n :: v) = [n]`. -/
def head : Code :=
cons id nil
@[simp]
theorem head_eval (v) : head.eval v = pure [v.headI] := by simp [head]
/-- `zero` is the constant zero function: `zero v = [0]`. -/
def zero : Code :=
cons zero' nil
@[simp]
theorem zero_eval (v) : zero.eval v = pure [0] := by simp [zero]
/-- `pred` returns the predecessor of the head of the input:
`pred [] = [0]`, `pred (0 :: v) = [0]`, `pred (n+1 :: v) = [n]`. -/
def pred : Code :=
case zero head
@[simp]
theorem pred_eval (v) : pred.eval v = pure [v.headI.pred] := by
simp [pred]; cases v.headI <;> simp
/-- `rfind f` performs the function of the `rfind` primitive of partial recursive functions.
`rfind f v` returns the smallest `n` such that `(f (n :: v)).head = 0`.
It is implemented as:
rfind f v = pred (fix (fun (n::v) => f (n::v) :: n+1 :: v) (0 :: v))
The idea is that the initial state is `0 :: v`, and the `fix` keeps `n :: v` as its internal state;
it calls `f (n :: v)` as the exit test and `n+1 :: v` as the next state. At the end we get
`n+1 :: v` where `n` is the desired output, and `pred (n+1 :: v) = [n]` returns the result.
-/
def rfind (f : Code) : Code :=
comp pred <| comp (fix <| cons f <| cons succ tail) zero'
/-- `prec f g` implements the `prec` (primitive recursion) operation of partial recursive
functions. `prec f g` evaluates as:
* `prec f g [] = [f []]`
* `prec f g (0 :: v) = [f v]`
* `prec f g (n+1 :: v) = [g (n :: prec f g (n :: v) :: v)]`
It is implemented as:
G (a :: b :: IH :: v) = (b :: a+1 :: b-1 :: g (a :: IH :: v) :: v)
F (0 :: f_v :: v) = (f_v :: v)
F (n+1 :: f_v :: v) = (fix G (0 :: n :: f_v :: v)).tail.tail
prec f g (a :: v) = [(F (a :: f v :: v)).head]
Because `fix` always evaluates its body at least once, we must special case the `0` case to avoid
calling `g` more times than necessary (which could be bad if `g` diverges). If the input is
`0 :: v`, then `F (0 :: f v :: v) = (f v :: v)` so we return `[f v]`. If the input is `n+1 :: v`,
we evaluate the function from the bottom up, with initial state `0 :: n :: f v :: v`. The first
number counts up, providing arguments for the applications to `g`, while the second number counts
down, providing the exit condition (this is the initial `b` in the return value of `G`, which is
stripped by `fix`). After the `fix` is complete, the final state is `n :: 0 :: res :: v` where
`res` is the desired result, and the rest reduces this to `[res]`. -/
def prec (f g : Code) : Code :=
let G :=
cons tail <|
cons succ <|
cons (comp pred tail) <|
cons (comp g <| cons id <| comp tail tail) <| comp tail <| comp tail tail
let F := case id <| comp (comp (comp tail tail) (fix G)) zero'
cons (comp F (cons head <| cons (comp f tail) tail)) nil
attribute [-simp] Part.bind_eq_bind Part.map_eq_map Part.pure_eq_some
theorem exists_code.comp {m n} {f : List.Vector ℕ n →. ℕ} {g : Fin n → List.Vector ℕ m →. ℕ}
(hf : ∃ c : Code, ∀ v : List.Vector ℕ n, c.eval v.1 = pure <$> f v)
(hg : ∀ i, ∃ c : Code, ∀ v : List.Vector ℕ m, c.eval v.1 = pure <$> g i v) :
∃ c : Code, ∀ v : List.Vector ℕ m,
c.eval v.1 = pure <$> ((List.Vector.mOfFn fun i => g i v) >>= f) := by
rsuffices ⟨cg, hg⟩ :
∃ c : Code, ∀ v : List.Vector ℕ m,
c.eval v.1 = Subtype.val <$> List.Vector.mOfFn fun i => g i v
· obtain ⟨cf, hf⟩ := hf
exact
⟨cf.comp cg, fun v => by
simp [hg, hf, map_bind]
rfl⟩
clear hf f
induction n with
| zero => exact ⟨nil, fun v => by simp [Vector.mOfFn]; rfl⟩
| succ n IH =>
obtain ⟨cg, hg₁⟩ := hg 0
obtain ⟨cl, hl⟩ := IH fun i => hg i.succ
exact
⟨cons cg cl, fun v => by
simp [Vector.mOfFn, hg₁, map_bind, hl]
rfl⟩
theorem exists_code {n} {f : List.Vector ℕ n →. ℕ} (hf : Nat.Partrec' f) :
∃ c : Code, ∀ v : List.Vector ℕ n, c.eval v.1 = pure <$> f v := by
induction hf with
| prim hf =>
induction hf with
| zero => exact ⟨zero', fun ⟨[], _⟩ => rfl⟩
| succ => exact ⟨succ, fun ⟨[v], _⟩ => rfl⟩
| get i =>
refine Fin.succRec (fun n => ?_) (fun n i IH => ?_) i
· exact ⟨head, fun ⟨List.cons a as, _⟩ => by simp; rfl⟩
· obtain ⟨c, h⟩ := IH
exact ⟨c.comp tail, fun v => by simpa [← Vector.get_tail, Bind.bind] using h v.tail⟩
| comp g hf hg IHf IHg =>
simpa [Part.bind_eq_bind] using exists_code.comp IHf IHg
| @prec n f g _ _ IHf IHg =>
obtain ⟨cf, hf⟩ := IHf
obtain ⟨cg, hg⟩ := IHg
simp only [Part.map_eq_map, Part.map_some, PFun.coe_val] at hf hg
refine ⟨prec cf cg, fun v => ?_⟩
rw [← v.cons_head_tail]
specialize hf v.tail
replace hg := fun a b => hg (a ::ᵥ b ::ᵥ v.tail)
simp only [Vector.cons_val, Vector.tail_val] at hf hg
simp only [Part.map_eq_map, Part.map_some, Vector.cons_val, Vector.tail_cons,
Vector.head_cons, PFun.coe_val, Vector.tail_val]
simp only [← Part.pure_eq_some] at hf hg ⊢
induction v.head with
simp [prec, hf, Part.bind_assoc, ← Part.bind_some_eq_map, Part.bind_some, Bind.bind]
| succ n _ =>
suffices ∀ a b, a + b = n →
(n.succ :: 0 ::
g (n ::ᵥ Nat.rec (f v.tail) (fun y IH => g (y ::ᵥ IH ::ᵥ v.tail)) n ::ᵥ v.tail) ::
v.val.tail : List ℕ) ∈
PFun.fix
(fun v : List ℕ => Part.bind (cg.eval (v.headI :: v.tail.tail))
(fun x => Part.some (if v.tail.headI = 0
then Sum.inl
(v.headI.succ :: v.tail.headI.pred :: x.headI :: v.tail.tail.tail : List ℕ)
else Sum.inr
(v.headI.succ :: v.tail.headI.pred :: x.headI :: v.tail.tail.tail))))
(a :: b :: Nat.rec (f v.tail) (fun y IH => g (y ::ᵥ IH ::ᵥ v.tail)) a :: v.val.tail) by
have := Part.eq_some_iff.mpr (this _ _ (zero_add _))
simp_all
intro a b e
induction b generalizing a with
| zero =>
refine PFun.mem_fix_iff.2 (Or.inl <| Part.eq_some_iff.1 ?_)
simp only [hg, ← e, Part.bind_some, List.tail_cons, pure]
rfl
| succ b IH =>
refine PFun.mem_fix_iff.2 (Or.inr ⟨_, ?_, IH (a + 1) (by rwa [add_right_comm])⟩)
simp only [hg, Part.bind_some, List.tail_cons, pure]
exact Part.mem_some_iff.2 rfl
| comp g _ _ IHf IHg => exact exists_code.comp IHf IHg
| @rfind n f _ IHf =>
obtain ⟨cf, hf⟩ := IHf; refine ⟨rfind cf, fun v => ?_⟩
replace hf := fun a => hf (a ::ᵥ v)
simp only [Part.map_eq_map, Part.map_some, Vector.cons_val, PFun.coe_val,
show ∀ x, pure x = [x] from fun _ => rfl] at hf ⊢
refine Part.ext fun x => ?_
simp only [rfind, Part.bind_eq_bind, Part.pure_eq_some, Part.bind_some,
cons_eval, comp_eval, fix_eval, tail_eval, succ_eval, zero'_eval,
List.headI_cons, pred_eval, Part.map_some, false_eq_decide_iff,
Part.mem_bind_iff, Part.mem_map_iff, Nat.mem_rfind,
List.tail_cons, true_eq_decide_iff, Part.mem_some_iff, Part.map_bind]
constructor
· rintro ⟨v', h1, rfl⟩
suffices ∀ v₁ : List ℕ, v' ∈ PFun.fix
(fun v => (cf.eval v).bind fun y => Part.some <|
if y.headI = 0 then Sum.inl (v.headI.succ :: v.tail)
else Sum.inr (v.headI.succ :: v.tail)) v₁ →
∀ n, (v₁ = n :: v.val) → (∀ m < n, ¬f (m ::ᵥ v) = 0) →
∃ a : ℕ,
(f (a ::ᵥ v) = 0 ∧ ∀ {m : ℕ}, m < a → ¬f (m ::ᵥ v) = 0) ∧ [a] = [v'.headI.pred]
by exact this _ h1 0 rfl (by rintro _ ⟨⟩)
clear h1
intro v₀ h1
refine PFun.fixInduction h1 fun v₁ h2 IH => ?_
clear h1
rintro n rfl hm
have := PFun.mem_fix_iff.1 h2
simp only [hf, Part.bind_some] at this
split_ifs at this with h
· simp only [List.headI_cons, exists_false, or_false, Part.mem_some_iff,
List.tail_cons, false_and, Sum.inl.injEq, reduceCtorEq] at this
subst this
exact ⟨_, ⟨h, @(hm)⟩, rfl⟩
· refine IH (n.succ::v.val) (by simp_all) _ rfl fun m h' => ?_
obtain h | rfl := Nat.lt_succ_iff_lt_or_eq.1 h'
exacts [hm _ h, h]
· rintro ⟨n, ⟨hn, hm⟩, rfl⟩
refine ⟨n.succ::v.1, ?_, rfl⟩
have : (n.succ::v.1 : List ℕ) ∈
PFun.fix (fun v =>
(cf.eval v).bind fun y =>
Part.some <|
if y.headI = 0 then Sum.inl (v.headI.succ :: v.tail)
else Sum.inr (v.headI.succ :: v.tail))
(n::v.val) :=
PFun.mem_fix_iff.2 (Or.inl (by simp [hf, hn]))
generalize (n.succ :: v.1 : List ℕ) = w at this ⊢
clear hn
induction n with
| zero => exact this
| succ n IH =>
refine IH (fun {m} h' => hm (Nat.lt_succ_of_lt h'))
(PFun.mem_fix_iff.2 (Or.inr ⟨_, ?_, this⟩))
simp only [hf, hm n.lt_succ_self, Part.bind_some, List.headI, if_false,
Part.mem_some_iff, List.tail_cons]
end Code
/-!
## From compositional semantics to sequential semantics
Our initial sequential model is designed to be as similar as possible to the compositional
semantics in terms of its primitives, but it is a sequential semantics, meaning that rather than
defining an `eval c : List ℕ →. List ℕ` function for each program, defined by recursion on
programs, we have a type `Cfg` with a step function `step : Cfg → Option cfg` that provides a
deterministic evaluation order. In order to do this, we introduce the notion of a *continuation*,
which can be viewed as a `Code` with a hole in it where evaluation is currently taking place.
Continuations can be assigned a `List ℕ →. List ℕ` semantics as well, with the interpretation
being that given a `List ℕ` result returned from the code in the hole, the remainder of the
program will evaluate to a `List ℕ` final value.
The continuations are:
* `halt`: the empty continuation: the hole is the whole program, whatever is returned is the
final result. In our notation this is just `_`.
* `cons₁ fs v k`: evaluating the first part of a `cons`, that is `k (_ :: fs v)`, where `k` is the
outer continuation.
* `cons₂ ns k`: evaluating the second part of a `cons`: `k (ns.headI :: _)`. (Technically we don't
need to hold on to all of `ns` here since we are already committed to taking the head, but this
is more regular.)
* `comp f k`: evaluating the first part of a composition: `k (f _)`.
* `fix f k`: waiting for the result of `f` in a `fix f` expression:
`k (if _.headI = 0 then _.tail else fix f (_.tail))`
The type `Cfg` of evaluation states is:
* `ret k v`: we have received a result, and are now evaluating the continuation `k` with result
`v`; that is, `k v` where `k` is ready to evaluate.
* `halt v`: we are done and the result is `v`.
The main theorem of this section is that for each code `c`, the state `stepNormal c halt v` steps
to `v'` in finitely many steps if and only if `Code.eval c v = some v'`.
-/
/-- The type of continuations, built up during evaluation of a `Code` expression. -/
inductive Cont
| halt
| cons₁ : Code → List ℕ → Cont → Cont
| cons₂ : List ℕ → Cont → Cont
| comp : Code → Cont → Cont
| fix : Code → Cont → Cont
deriving Inhabited
/-- The semantics of a continuation. -/
def Cont.eval : Cont → List ℕ →. List ℕ
| Cont.halt => pure
| Cont.cons₁ fs as k => fun v => do
let ns ← Code.eval fs as
Cont.eval k (v.headI :: ns)
| Cont.cons₂ ns k => fun v => Cont.eval k (ns.headI :: v)
| Cont.comp f k => fun v => Code.eval f v >>= Cont.eval k
| Cont.fix f k => fun v => if v.headI = 0 then k.eval v.tail else f.fix.eval v.tail >>= k.eval
/-- The set of configurations of the machine:
* `halt v`: The machine is about to stop and `v : List ℕ` is the result.
* `ret k v`: The machine is about to pass `v : List ℕ` to continuation `k : Cont`.
We don't have a state corresponding to normal evaluation because these are evaluated immediately
to a `ret` "in zero steps" using the `stepNormal` function. -/
inductive Cfg
| halt : List ℕ → Cfg
| ret : Cont → List ℕ → Cfg
deriving Inhabited
/-- Evaluating `c : Code` in a continuation `k : Cont` and input `v : List ℕ`. This goes by
recursion on `c`, building an augmented continuation and a value to pass to it.
* `zero' v = 0 :: v` evaluates immediately, so we return it to the parent continuation
* `succ v = [v.headI.succ]` evaluates immediately, so we return it to the parent continuation
* `tail v = v.tail` evaluates immediately, so we return it to the parent continuation
* `cons f fs v = (f v).headI :: fs v` requires two sub-evaluations, so we evaluate
`f v` in the continuation `k (_.headI :: fs v)` (called `Cont.cons₁ fs v k`)
* `comp f g v = f (g v)` requires two sub-evaluations, so we evaluate
`g v` in the continuation `k (f _)` (called `Cont.comp f k`)
* `case f g v = v.head.casesOn (f v.tail) (fun n => g (n :: v.tail))` has the information needed
to evaluate the case statement, so we do that and transition to either
`f v` or `g (n :: v.tail)`.
* `fix f v = let v' := f v; if v'.headI = 0 then k v'.tail else fix f v'.tail`
needs to first evaluate `f v`, so we do that and leave the rest for the continuation (called
`Cont.fix f k`)
-/
def stepNormal : Code → Cont → List ℕ → Cfg
| Code.zero' => fun k v => Cfg.ret k (0::v)
| Code.succ => fun k v => Cfg.ret k [v.headI.succ]
| Code.tail => fun k v => Cfg.ret k v.tail
| Code.cons f fs => fun k v => stepNormal f (Cont.cons₁ fs v k) v
| Code.comp f g => fun k v => stepNormal g (Cont.comp f k) v
| Code.case f g => fun k v =>
v.headI.rec (stepNormal f k v.tail) fun y _ => stepNormal g k (y::v.tail)
| Code.fix f => fun k v => stepNormal f (Cont.fix f k) v
/-- Evaluating a continuation `k : Cont` on input `v : List ℕ`. This is the second part of
evaluation, when we receive results from continuations built by `stepNormal`.
* `Cont.halt v = v`, so we are done and transition to the `Cfg.halt v` state
* `Cont.cons₁ fs as k v = k (v.headI :: fs as)`, so we evaluate `fs as` now with the continuation
`k (v.headI :: _)` (called `cons₂ v k`).
* `Cont.cons₂ ns k v = k (ns.headI :: v)`, where we now have everything we need to evaluate
`ns.headI :: v`, so we return it to `k`.
* `Cont.comp f k v = k (f v)`, so we call `f v` with `k` as the continuation.
* `Cont.fix f k v = k (if v.headI = 0 then k v.tail else fix f v.tail)`, where `v` is a value,
so we evaluate the if statement and either call `k` with `v.tail`, or call `fix f v` with `k` as
the continuation (which immediately calls `f` with `Cont.fix f k` as the continuation).
-/
def stepRet : Cont → List ℕ → Cfg
| Cont.halt, v => Cfg.halt v
| Cont.cons₁ fs as k, v => stepNormal fs (Cont.cons₂ v k) as
| Cont.cons₂ ns k, v => stepRet k (ns.headI :: v)
| Cont.comp f k, v => stepNormal f k v
| Cont.fix f k, v => if v.headI = 0 then stepRet k v.tail else stepNormal f (Cont.fix f k) v.tail
/-- If we are not done (in `Cfg.halt` state), then we must be still stuck on a continuation, so
this main loop calls `stepRet` with the new continuation. The overall `step` function transitions
from one `Cfg` to another, only halting at the `Cfg.halt` state. -/
def step : Cfg → Option Cfg
| Cfg.halt _ => none
| Cfg.ret k v => some (stepRet k v)
/-- In order to extract a compositional semantics from the sequential execution behavior of
configurations, we observe that continuations have a monoid structure, with `Cont.halt` as the unit
and `Cont.then` as the multiplication. `Cont.then k₁ k₂` runs `k₁` until it halts, and then takes
the result of `k₁` and passes it to `k₂`.
We will not prove it is associative (although it is), but we are instead interested in the
associativity law `k₂ (eval c k₁) = eval c (k₁.then k₂)`. This holds at both the sequential and
compositional levels, and allows us to express running a machine without the ambient continuation
and relate it to the original machine's evaluation steps. In the literature this is usually
where one uses Turing machines embedded inside other Turing machines, but this approach allows us
to avoid changing the ambient type `Cfg` in the middle of the recursion.
-/
def Cont.then : Cont → Cont → Cont
| Cont.halt => fun k' => k'
| Cont.cons₁ fs as k => fun k' => Cont.cons₁ fs as (k.then k')
| Cont.cons₂ ns k => fun k' => Cont.cons₂ ns (k.then k')
| Cont.comp f k => fun k' => Cont.comp f (k.then k')
| Cont.fix f k => fun k' => Cont.fix f (k.then k')
theorem Cont.then_eval {k k' : Cont} {v} : (k.then k').eval v = k.eval v >>= k'.eval := by
induction k generalizing v with
| halt => simp only [Cont.eval, Cont.then, pure_bind]
| cons₁ => simp only [Cont.eval, Cont.then, bind_assoc, *]
| cons₂ => simp only [Cont.eval, Cont.then, *]
| comp _ _ k_ih => simp only [Cont.eval, Cont.then, bind_assoc, ← k_ih]
| fix _ _ k_ih =>
simp only [Cont.eval, Cont.then, *]
split_ifs <;> [rfl; simp only [← k_ih, bind_assoc]]
/-- The `then k` function is a "configuration homomorphism". Its operation on states is to append
`k` to the continuation of a `Cfg.ret` state, and to run `k` on `v` if we are in the `Cfg.halt v`
state. -/
def Cfg.then : Cfg → Cont → Cfg
| Cfg.halt v => fun k' => stepRet k' v
| Cfg.ret k v => fun k' => Cfg.ret (k.then k') v
/-- The `stepNormal` function respects the `then k'` homomorphism. Note that this is an exact
equality, not a simulation; the original and embedded machines move in lock-step until the
embedded machine reaches the halt state. -/
theorem stepNormal_then (c) (k k' : Cont) (v) :
stepNormal c (k.then k') v = (stepNormal c k v).then k' := by
induction c generalizing k v with simp only [stepNormal, *]
| cons c c' ih _ => rw [← ih, Cont.then]
| comp c c' _ ih' => rw [← ih', Cont.then]
| case => cases v.headI <;> simp only [Nat.rec_zero]
| fix c ih => rw [← ih, Cont.then]
| _ => simp only [Cfg.then]
/-- The `stepRet` function respects the `then k'` homomorphism. Note that this is an exact
equality, not a simulation; the original and embedded machines move in lock-step until the
embedded machine reaches the halt state. -/
theorem stepRet_then {k k' : Cont} {v} : stepRet (k.then k') v = (stepRet k v).then k' := by
induction k generalizing v with simp only [Cont.then, stepRet, *]
| cons₁ =>
rw [← stepNormal_then]
rfl
| comp =>
rw [← stepNormal_then]
| fix _ _ k_ih =>
split_ifs
· rw [← k_ih]
· rw [← stepNormal_then]
rfl
| _ => simp only [Cfg.then]
/-- This is a temporary definition, because we will prove in `code_is_ok` that it always holds.
It asserts that `c` is semantically correct; that is, for any `k` and `v`,
`eval (stepNormal c k v) = eval (Cfg.ret k (Code.eval c v))`, as an equality of partial values
(so one diverges iff the other does).
In particular, we can let `k = Cont.halt`, and then this asserts that `stepNormal c Cont.halt v`
evaluates to `Cfg.halt (Code.eval c v)`. -/
def Code.Ok (c : Code) :=
∀ k v, Turing.eval step (stepNormal c k v) =
Code.eval c v >>= fun v => Turing.eval step (Cfg.ret k v)
theorem Code.Ok.zero {c} (h : Code.Ok c) {v} :
Turing.eval step (stepNormal c Cont.halt v) = Cfg.halt <$> Code.eval c v := by
rw [h, ← bind_pure_comp]; congr; funext v
exact Part.eq_some_iff.2 (mem_eval.2 ⟨ReflTransGen.single rfl, rfl⟩)
theorem stepNormal.is_ret (c k v) : ∃ k' v', stepNormal c k v = Cfg.ret k' v' := by
induction c generalizing k v with
| cons _f fs IHf _IHfs => apply IHf
| comp f _g _IHf IHg => apply IHg
| case f g IHf IHg =>
rw [stepNormal]
simp only []
cases v.headI <;> [apply IHf; apply IHg]
| fix f IHf => apply IHf
| _ => exact ⟨_, _, rfl⟩
theorem cont_eval_fix {f k v} (fok : Code.Ok f) :
Turing.eval step (stepNormal f (Cont.fix f k) v) =
f.fix.eval v >>= fun v => Turing.eval step (Cfg.ret k v) := by
refine Part.ext fun x => ?_
simp only [Part.bind_eq_bind, Part.mem_bind_iff]
constructor
· suffices ∀ c, x ∈ eval step c → ∀ v c', c = Cfg.then c' (Cont.fix f k) →
Reaches step (stepNormal f Cont.halt v) c' →
∃ v₁ ∈ f.eval v, ∃ v₂ ∈ if List.headI v₁ = 0 then pure v₁.tail else f.fix.eval v₁.tail,
x ∈ eval step (Cfg.ret k v₂) by
intro h
obtain ⟨v₁, hv₁, v₂, hv₂, h₃⟩ :=
this _ h _ _ (stepNormal_then _ Cont.halt _ _) ReflTransGen.refl
refine ⟨v₂, PFun.mem_fix_iff.2 ?_, h₃⟩
simp only [Part.eq_some_iff.2 hv₁, Part.map_some]
split_ifs at hv₂ ⊢
· rw [Part.mem_some_iff.1 hv₂]
exact Or.inl (Part.mem_some _)
· exact Or.inr ⟨_, Part.mem_some _, hv₂⟩
refine fun c he => evalInduction he fun y h IH => ?_
rintro v (⟨v'⟩ | ⟨k', v'⟩) rfl hr <;> rw [Cfg.then] at h IH <;> simp only [] at h IH
· have := mem_eval.2 ⟨hr, rfl⟩
rw [fok, Part.bind_eq_bind, Part.mem_bind_iff] at this
obtain ⟨v'', h₁, h₂⟩ := this
rw [reaches_eval] at h₂
swap
· exact ReflTransGen.single rfl
cases Part.mem_unique h₂ (mem_eval.2 ⟨ReflTransGen.refl, rfl⟩)
refine ⟨v', h₁, ?_⟩
rw [stepRet] at h
revert h
by_cases he : v'.headI = 0 <;> simp only [if_pos, if_false, he] <;> intro h
· refine ⟨_, Part.mem_some _, ?_⟩
rw [reaches_eval]
· exact h
exact ReflTransGen.single rfl
· obtain ⟨k₀, v₀, e₀⟩ := stepNormal.is_ret f Cont.halt v'.tail
have e₁ := stepNormal_then f Cont.halt (Cont.fix f k) v'.tail
rw [e₀, Cont.then, Cfg.then] at e₁
simp only [] at e₁
obtain ⟨v₁, hv₁, v₂, hv₂, h₃⟩ :=
IH (stepRet (k₀.then (Cont.fix f k)) v₀) (by rw [stepRet, if_neg he, e₁]; rfl)
v'.tail _ stepRet_then (by apply ReflTransGen.single; rw [e₀]; rfl)
refine ⟨_, PFun.mem_fix_iff.2 ?_, h₃⟩
simp only [Part.eq_some_iff.2 hv₁, Part.map_some, Part.mem_some_iff]
split_ifs at hv₂ ⊢ <;> [exact Or.inl (congr_arg Sum.inl (Part.mem_some_iff.1 hv₂));
exact Or.inr ⟨_, rfl, hv₂⟩]
· exact IH _ rfl _ _ stepRet_then (ReflTransGen.tail hr rfl)
· rintro ⟨v', he, hr⟩
rw [reaches_eval] at hr
swap
· exact ReflTransGen.single rfl
refine PFun.fixInduction he fun v (he : v' ∈ f.fix.eval v) IH => ?_
rw [fok, Part.bind_eq_bind, Part.mem_bind_iff]
obtain he | ⟨v'', he₁', _⟩ := PFun.mem_fix_iff.1 he
· obtain ⟨v', he₁, he₂⟩ := (Part.mem_map_iff _).1 he
split_ifs at he₂ with h; cases he₂
refine ⟨_, he₁, ?_⟩
rw [reaches_eval]
swap
· exact ReflTransGen.single rfl
rwa [stepRet, if_pos h]
· obtain ⟨v₁, he₁, he₂⟩ := (Part.mem_map_iff _).1 he₁'
split_ifs at he₂ with h; cases he₂
clear he₁'
refine ⟨_, he₁, ?_⟩
rw [reaches_eval]
swap
· exact ReflTransGen.single rfl
rw [stepRet, if_neg h]
exact IH v₁.tail ((Part.mem_map_iff _).2 ⟨_, he₁, if_neg h⟩)
theorem code_is_ok (c) : Code.Ok c := by
induction c with (intro k v; rw [stepNormal])
| cons f fs IHf IHfs =>
rw [Code.eval, IHf]
simp only [bind_assoc, pure_bind]; congr; funext v
rw [reaches_eval]; swap
· exact ReflTransGen.single rfl
rw [stepRet, IHfs]; congr; funext v'
refine Eq.trans (b := eval step (stepRet (Cont.cons₂ v k) v')) ?_ (Eq.symm ?_) <;>
exact reaches_eval (ReflTransGen.single rfl)
| comp f g IHf IHg =>
rw [Code.eval, IHg]
simp only [bind_assoc]; congr; funext v
rw [reaches_eval]; swap
· exact ReflTransGen.single rfl
rw [stepRet, IHf]
| case f g IHf IHg =>
simp only [Code.eval]
cases v.headI <;> simp only [Nat.rec_zero, Part.bind_eq_bind] <;> [apply IHf; apply IHg]
| fix f IHf => rw [cont_eval_fix IHf]
| _ => simp only [Code.eval, pure_bind]
theorem stepNormal_eval (c v) : eval step (stepNormal c Cont.halt v) = Cfg.halt <$> c.eval v :=
(code_is_ok c).zero
theorem stepRet_eval {k v} : eval step (stepRet k v) = Cfg.halt <$> k.eval v := by
induction k generalizing v with
| halt =>
simp only [Cont.eval, map_pure]
exact Part.eq_some_iff.2 (mem_eval.2 ⟨ReflTransGen.refl, rfl⟩)
| cons₁ fs as k IH =>
rw [Cont.eval, stepRet, code_is_ok]
simp only [← bind_pure_comp, bind_assoc]; congr; funext v'
rw [reaches_eval]; swap
· exact ReflTransGen.single rfl
rw [stepRet, IH, bind_pure_comp]
| cons₂ ns k IH => rw [Cont.eval, stepRet]; exact IH
| comp f k IH =>
rw [Cont.eval, stepRet, code_is_ok]
simp only [← bind_pure_comp, bind_assoc]; congr; funext v'
rw [reaches_eval]; swap
· exact ReflTransGen.single rfl
rw [IH, bind_pure_comp]
| fix f k IH =>
rw [Cont.eval, stepRet]; simp only
split_ifs; · exact IH
simp only [← bind_pure_comp, bind_assoc, cont_eval_fix (code_is_ok _)]
congr; funext; rw [bind_pure_comp, ← IH]
exact reaches_eval (ReflTransGen.single rfl)
end ToPartrec
end Turing |
.lake/packages/mathlib/Mathlib/Computability/Ackermann.lean | import Mathlib.Computability.PartrecCode
import Mathlib.Tactic.Ring
import Mathlib.Tactic.Linarith
/-!
# Ackermann function
In this file, we define the two-argument Ackermann function `ack`. Despite having a recursive
definition, we show that this isn't a primitive recursive function.
## Main results
- `exists_lt_ack_of_nat_primrec`: any primitive recursive function is pointwise bounded above by
`ack m` for some `m`.
- `not_primrec₂_ack`: the two-argument Ackermann function is not primitive recursive.
- `computable₂_ack`: the two-argument Ackermann function is computable.
## Proof approach
We very broadly adapt the proof idea from
https://www.planetmath.org/ackermannfunctionisnotprimitiverecursive. Namely, we prove that for any
primitive recursive `f : ℕ → ℕ`, there exists `m` such that `f n < ack m n` for all `n`. This then
implies that `fun n => ack n n` can't be primitive recursive, and so neither can `ack`. We aren't
able to use the same bounds as in that proof though, since our approach of using pairing functions
differs from their approach of using multivariate functions.
The important bounds we show during the main inductive proof (`exists_lt_ack_of_nat_primrec`)
are the following. Assuming `∀ n, f n < ack a n` and `∀ n, g n < ack b n`, we have:
- `∀ n, pair (f n) (g n) < ack (max a b + 3) n`.
- `∀ n, g (f n) < ack (max a b + 2) n`.
- `∀ n, Nat.rec (f n.unpair.1) (fun (y IH : ℕ) => g (pair n.unpair.1 (pair y IH)))
n.unpair.2 < ack (max a b + 9) n`.
The last one is evidently the hardest. Using `unpair_add_le`, we reduce it to the more manageable
- `∀ m n, rec (f m) (fun (y IH : ℕ) => g (pair m (pair y IH))) n <
ack (max a b + 9) (m + n)`.
We then prove this by induction on `n`. Our proof crucially depends on `ack_pair_lt`, which is
applied twice, giving us a constant of `4 + 4`. The rest of the proof consists of simpler bounds
which bump up our constant to `9`.
-/
open Nat
/-- The two-argument Ackermann function, defined so that
- `ack 0 n = n + 1`
- `ack (m + 1) 0 = ack m 1`
- `ack (m + 1) (n + 1) = ack m (ack (m + 1) n)`.
This is of interest as both a fast-growing function, and as an example of a recursive function that
isn't primitive recursive. -/
def ack : ℕ → ℕ → ℕ
| 0, n => n + 1
| m + 1, 0 => ack m 1
| m + 1, n + 1 => ack m (ack (m + 1) n)
@[simp]
theorem ack_zero (n : ℕ) : ack 0 n = n + 1 := by rw [ack]
@[simp]
theorem ack_succ_zero (m : ℕ) : ack (m + 1) 0 = ack m 1 := by rw [ack]
@[simp]
theorem ack_succ_succ (m n : ℕ) : ack (m + 1) (n + 1) = ack m (ack (m + 1) n) := by rw [ack]
@[simp]
theorem ack_one (n : ℕ) : ack 1 n = n + 2 := by
induction n with
| zero => simp
| succ n IH => simp [IH]
@[simp]
theorem ack_two (n : ℕ) : ack 2 n = 2 * n + 3 := by
induction n with
| zero => simp
| succ n IH => simpa [mul_succ]
@[simp]
theorem ack_three (n : ℕ) : ack 3 n = 2 ^ (n + 3) - 3 := by
induction n with
| zero => simp
| succ n IH =>
rw [ack_succ_succ, IH, ack_two, Nat.succ_add, Nat.pow_succ 2 (n + 3), mul_comm _ 2,
Nat.mul_sub_left_distrib, ← Nat.sub_add_comm, two_mul 3, Nat.add_sub_add_right]
calc 2 * 3
_ ≤ 2 * 2 ^ 3 := by simp
_ ≤ 2 * 2 ^ (n + 3) := by gcongr <;> omega
theorem ack_pos : ∀ m n, 0 < ack m n
| 0, n => by simp
| m + 1, 0 => by
rw [ack_succ_zero]
apply ack_pos
| m + 1, n + 1 => by
rw [ack_succ_succ]
apply ack_pos
theorem one_lt_ack_succ_left : ∀ m n, 1 < ack (m + 1) n
| 0, n => by simp
| m + 1, 0 => by
rw [ack_succ_zero]
apply one_lt_ack_succ_left
| m + 1, n + 1 => by
rw [ack_succ_succ]
apply one_lt_ack_succ_left
theorem one_lt_ack_succ_right : ∀ m n, 1 < ack m (n + 1)
| 0, n => by simp
| m + 1, n => one_lt_ack_succ_left m (n + 1)
theorem ack_strictMono_right : ∀ m, StrictMono (ack m)
| 0, n₁, n₂, h => by simpa using h
| m + 1, 0, n + 1, _h => by
rw [ack_succ_zero, ack_succ_succ]
exact ack_strictMono_right _ (one_lt_ack_succ_left m n)
| m + 1, n₁ + 1, n₂ + 1, h => by
rw [ack_succ_succ, ack_succ_succ]
apply ack_strictMono_right _ (ack_strictMono_right _ _)
rwa [add_lt_add_iff_right] at h
theorem ack_mono_right (m : ℕ) : Monotone (ack m) :=
(ack_strictMono_right m).monotone
theorem ack_injective_right (m : ℕ) : Function.Injective (ack m) :=
(ack_strictMono_right m).injective
@[simp]
theorem ack_lt_iff_right {m n₁ n₂ : ℕ} : ack m n₁ < ack m n₂ ↔ n₁ < n₂ :=
(ack_strictMono_right m).lt_iff_lt
@[simp]
theorem ack_le_iff_right {m n₁ n₂ : ℕ} : ack m n₁ ≤ ack m n₂ ↔ n₁ ≤ n₂ :=
(ack_strictMono_right m).le_iff_le
@[simp]
theorem ack_inj_right {m n₁ n₂ : ℕ} : ack m n₁ = ack m n₂ ↔ n₁ = n₂ :=
(ack_injective_right m).eq_iff
theorem max_ack_right (m n₁ n₂ : ℕ) : ack m (max n₁ n₂) = max (ack m n₁) (ack m n₂) :=
(ack_mono_right m).map_max
theorem add_lt_ack : ∀ m n, m + n < ack m n
| 0, n => by simp
| m + 1, 0 => by simpa using add_lt_ack m 1
| m + 1, n + 1 =>
calc
m + 1 + n + 1 ≤ m + (m + n + 2) := by omega
_ < ack m (m + n + 2) := add_lt_ack _ _
_ ≤ ack m (ack (m + 1) n) :=
ack_mono_right m <| le_of_eq_of_le (by rw [succ_eq_add_one]; ring_nf)
<| succ_le_of_lt <| add_lt_ack (m + 1) n
_ = ack (m + 1) (n + 1) := (ack_succ_succ m n).symm
theorem add_add_one_le_ack (m n : ℕ) : m + n + 1 ≤ ack m n :=
succ_le_of_lt (add_lt_ack m n)
theorem lt_ack_left (m n : ℕ) : m < ack m n :=
(self_le_add_right m n).trans_lt <| add_lt_ack m n
theorem lt_ack_right (m n : ℕ) : n < ack m n :=
(self_le_add_left n m).trans_lt <| add_lt_ack m n
-- we reorder the arguments to appease the equation compiler
private theorem ack_strict_mono_left' : ∀ {m₁ m₂} (n), m₁ < m₂ → ack m₁ n < ack m₂ n
| m, 0, _ => fun h => (not_lt_zero m h).elim
| 0, m + 1, 0 => fun _h => by simpa using one_lt_ack_succ_right m 0
| 0, m + 1, n + 1 => fun h => by
rw [ack_zero, ack_succ_succ]
calc
n + 1 + 1 ≤ m + (m + 1 + n + 1) := by omega
_ ≤ m + ack (m + 1) n := by gcongr; exact add_add_one_le_ack ..
_ < ack m (ack (m + 1) n) := add_lt_ack ..
| m₁ + 1, m₂ + 1, 0 => fun h => by
simpa using ack_strict_mono_left' 1 ((add_lt_add_iff_right 1).1 h)
| m₁ + 1, m₂ + 1, n + 1 => fun h => by
rw [ack_succ_succ, ack_succ_succ]
exact
(ack_strict_mono_left' _ <| (add_lt_add_iff_right 1).1 h).trans
(ack_strictMono_right _ <| ack_strict_mono_left' n h)
theorem ack_strictMono_left (n : ℕ) : StrictMono fun m => ack m n := fun _m₁ _m₂ =>
ack_strict_mono_left' n
theorem ack_mono_left (n : ℕ) : Monotone fun m => ack m n :=
(ack_strictMono_left n).monotone
theorem ack_injective_left (n : ℕ) : Function.Injective fun m => ack m n :=
(ack_strictMono_left n).injective
@[simp]
theorem ack_lt_iff_left {m₁ m₂ n : ℕ} : ack m₁ n < ack m₂ n ↔ m₁ < m₂ :=
(ack_strictMono_left n).lt_iff_lt
@[simp]
theorem ack_le_iff_left {m₁ m₂ n : ℕ} : ack m₁ n ≤ ack m₂ n ↔ m₁ ≤ m₂ :=
(ack_strictMono_left n).le_iff_le
@[simp]
theorem ack_inj_left {m₁ m₂ n : ℕ} : ack m₁ n = ack m₂ n ↔ m₁ = m₂ :=
(ack_injective_left n).eq_iff
theorem max_ack_left (m₁ m₂ n : ℕ) : ack (max m₁ m₂) n = max (ack m₁ n) (ack m₂ n) :=
(ack_mono_left n).map_max
@[gcongr]
theorem ack_le_ack {m₁ m₂ n₁ n₂ : ℕ} (hm : m₁ ≤ m₂) (hn : n₁ ≤ n₂) : ack m₁ n₁ ≤ ack m₂ n₂ :=
(ack_mono_left n₁ hm).trans <| ack_mono_right m₂ hn
theorem ack_succ_right_le_ack_succ_left (m n : ℕ) : ack m (n + 1) ≤ ack (m + 1) n := by
rcases n with - | n
· simp
· rw [ack_succ_succ]
apply ack_mono_right m (le_trans _ <| add_add_one_le_ack _ n)
cutsat
-- All the inequalities from this point onwards are specific to the main proof.
private theorem sq_le_two_pow_add_one_minus_three (n : ℕ) : n ^ 2 ≤ 2 ^ (n + 1) - 3 := by
induction n with
| zero => simp
| succ k hk =>
rcases k with - | k
· simp
· rw [add_sq, Nat.pow_succ 2, mul_comm _ 2, two_mul (2 ^ _),
add_tsub_assoc_of_le, add_comm (2 ^ _), add_assoc]
· apply Nat.add_le_add hk
norm_num
apply succ_le_of_lt
rw [Nat.pow_succ, mul_comm _ 2, mul_lt_mul_iff_right₀ (zero_lt_two' ℕ)]
exact Nat.lt_two_pow_self
· rw [Nat.pow_succ, Nat.pow_succ]
linarith [one_le_pow k 2 zero_lt_two]
theorem ack_add_one_sq_lt_ack_add_three : ∀ m n, (ack m n + 1) ^ 2 ≤ ack (m + 3) n
| 0, n => by simpa using sq_le_two_pow_add_one_minus_three (n + 2)
| m + 1, 0 => by
rw [ack_succ_zero, ack_succ_zero]
apply ack_add_one_sq_lt_ack_add_three
| m + 1, n + 1 => by
rw [ack_succ_succ, ack_succ_succ]
apply (ack_add_one_sq_lt_ack_add_three _ _).trans (ack_mono_right _ <| ack_mono_left _ _)
cutsat
theorem ack_ack_lt_ack_max_add_two (m n k : ℕ) : ack m (ack n k) < ack (max m n + 2) k :=
calc
ack m (ack n k) ≤ ack (max m n) (ack n k) := ack_mono_left _ (le_max_left _ _)
_ < ack (max m n) (ack (max m n + 1) k) :=
ack_strictMono_right _ <| ack_strictMono_left k <| lt_succ_of_le <| le_max_right m n
_ = ack (max m n + 1) (k + 1) := (ack_succ_succ _ _).symm
_ ≤ ack (max m n + 2) k := ack_succ_right_le_ack_succ_left _ _
theorem ack_add_one_sq_lt_ack_add_four (m n : ℕ) : ack m ((n + 1) ^ 2) < ack (m + 4) n :=
calc
ack m ((n + 1) ^ 2) < ack m ((ack m n + 1) ^ 2) :=
ack_strictMono_right m <| Nat.pow_lt_pow_left (succ_lt_succ <| lt_ack_right m n) two_ne_zero
_ ≤ ack m (ack (m + 3) n) := ack_mono_right m <| ack_add_one_sq_lt_ack_add_three m n
_ ≤ ack (m + 2) (ack (m + 3) n) := ack_mono_left _ <| by cutsat
_ = ack (m + 3) (n + 1) := (ack_succ_succ _ n).symm
_ ≤ ack (m + 4) n := ack_succ_right_le_ack_succ_left _ n
theorem ack_pair_lt (m n k : ℕ) : ack m (pair n k) < ack (m + 4) (max n k) :=
(ack_strictMono_right m <| pair_lt_max_add_one_sq n k).trans <|
ack_add_one_sq_lt_ack_add_four _ _
/-- If `f` is primitive recursive, there exists `m` such that `f n < ack m n` for all `n`. -/
theorem exists_lt_ack_of_nat_primrec {f : ℕ → ℕ} (hf : Nat.Primrec f) :
∃ m, ∀ n, f n < ack m n := by
induction hf with
| zero => exact ⟨0, ack_pos 0⟩
| succ =>
refine ⟨1, fun n => ?_⟩
rw [succ_eq_one_add]
apply add_lt_ack
| left =>
refine ⟨0, fun n => ?_⟩
rw [ack_zero, Nat.lt_succ_iff]
exact unpair_left_le n
| right =>
refine ⟨0, fun n => ?_⟩
rw [ack_zero, Nat.lt_succ_iff]
exact unpair_right_le n
| @pair f g hf hg IHf IHg =>
obtain ⟨a, ha⟩ := IHf; obtain ⟨b, hb⟩ := IHg
refine ⟨max a b + 3, fun n => ?_⟩
calc
pair (f n) (g n) < (max (f n) (g n) + 1) ^ 2 := pair_lt_max_add_one_sq ..
_ ≤ (ack (max a b) n + 1) ^ 2 := by rw [max_ack_left]; gcongr; exacts [(ha n).le, (hb n).le]
_ ≤ ack (max a b + 3) n := ack_add_one_sq_lt_ack_add_three ..
| comp hf hg IHf IHg =>
obtain ⟨a, ha⟩ := IHf; obtain ⟨b, hb⟩ := IHg
exact
⟨max a b + 2, fun n =>
(ha _).trans <| (ack_strictMono_right a <| hb n).trans <| ack_ack_lt_ack_max_add_two a b n⟩
| @prec f g hf hg IHf IHg =>
obtain ⟨a, ha⟩ := IHf; obtain ⟨b, hb⟩ := IHg
-- We prove this simpler inequality first.
have :
∀ {m n},
rec (f m) (fun y IH => g <| pair m <| pair y IH) n < ack (max a b + 9) (m + n) := by
intro m n
-- We induct on n.
induction n with
| zero => -- The base case is easy.
apply (ha m).trans (ack_strictMono_left m <| (le_max_left a b).trans_lt _)
cutsat
| succ n IH => -- We get rid of the first `pair`.
simp only
apply (hb _).trans ((ack_pair_lt _ _ _).trans_le _)
-- If m is the maximum, we get a very weak inequality.
rcases lt_or_ge _ m with h₁ | h₁
· rw [max_eq_left h₁.le]
gcongr <;> omega
rw [max_eq_right h₁]
-- We get rid of the second `pair`.
apply (ack_pair_lt _ _ _).le.trans
-- If n is the maximum, we get a very weak inequality.
rcases lt_or_ge _ n with h₂ | h₂
· rw [max_eq_left h₂.le, add_assoc]
exact
ack_le_ack (Nat.add_le_add (le_max_right a b) <| by simp)
((le_succ n).trans <| self_le_add_left _ _)
rw [max_eq_right h₂]
-- We now use the inductive hypothesis, and some simple algebraic manipulation.
apply (ack_strictMono_right _ IH).le.trans
rw [add_succ m, add_succ _ 8, succ_eq_add_one, succ_eq_add_one,
ack_succ_succ (_ + 8), add_assoc]
exact ack_mono_left _ (Nat.add_le_add (le_max_right a b) le_rfl)
-- The proof is now simple.
exact ⟨max a b + 9, fun n => this.trans_le <| ack_mono_right _ <| unpair_add_le n⟩
theorem not_nat_primrec_ack_self : ¬Nat.Primrec fun n => ack n n := fun h => by
obtain ⟨m, hm⟩ := exists_lt_ack_of_nat_primrec h
exact (hm m).false
theorem not_primrec_ack_self : ¬Primrec fun n => ack n n := by
rw [Primrec.nat_iff]
exact not_nat_primrec_ack_self
/-- The Ackermann function is not primitive recursive. -/
theorem not_primrec₂_ack : ¬Primrec₂ ack := fun h =>
not_primrec_ack_self <| h.comp Primrec.id Primrec.id
namespace Nat.Partrec.Code
/-- The code for the partially applied Ackermann function.
This is used to prove that the Ackermann function is computable. -/
def pappAck : ℕ → Code
| 0 => .succ
| n + 1 => step (pappAck n)
where
/-- Yields single recursion step on `pappAck`. -/
step (c : Code) : Code :=
.curry (.prec (.comp c (.const 1)) (.comp c (.comp .right .right))) 0
lemma primrec_pappAck_step : Primrec pappAck.step := by
apply_rules
[Code.primrec₂_curry.comp, Code.primrec₂_prec.comp, Code.primrec₂_comp.comp,
_root_.Primrec.id, Primrec.const]
@[simp]
lemma eval_pappAck_step_zero (c : Code) : (pappAck.step c).eval 0 = c.eval 1 := by
simp [pappAck.step, Code.eval]
@[simp]
lemma eval_pappAck_step_succ (c : Code) (n) :
(pappAck.step c).eval (n + 1) = ((pappAck.step c).eval n).bind c.eval := by
simp [pappAck.step, Code.eval]
lemma primrec_pappAck : Primrec pappAck := by
suffices Primrec (Nat.rec Code.succ (fun _ c => pappAck.step c)) by
convert this using 2 with n; induction n <;> simp [pappAck, *]
apply_rules [Primrec.nat_rec₁, primrec_pappAck_step.comp, Primrec.snd]
@[simp]
lemma eval_pappAck (m n) : (pappAck m).eval n = Part.some (ack m n) := by
induction m, n using ack.induct with
| case1 n => simp [Code.eval, pappAck]
| case2 m hm => simp [pappAck, hm]
| case3 m n hmn₁ hmn₂ => dsimp only [pappAck] at *; simp [hmn₁, hmn₂]
/-- The Ackermann function is computable. -/
theorem _root_.computable₂_ack : Computable₂ ack := by
apply _root_.Partrec.of_eq_tot
(f := fun p : ℕ × ℕ => (pappAck p.1).eval p.2) (g := fun p : ℕ × ℕ => ack p.1 p.2)
· change Partrec₂ (fun m n => (pappAck m).eval n)
apply_rules only
[Code.eval_part.comp₂, Computable.fst, Computable.snd, primrec_pappAck.to_comp.comp]
· simp
end Nat.Partrec.Code |
.lake/packages/mathlib/Mathlib/Computability/Tape.lean | import Mathlib.Data.Vector.Basic
import Mathlib.Logic.Function.Iterate
import Mathlib.Tactic.ApplyFun
import Mathlib.Data.List.GetD
/-!
# Turing machine tapes
This file defines the notion of a Turing machine tape, and the operations on it. A tape is a
bidirectional infinite sequence of cells, each of which stores an element of a given alphabet `Γ`.
All but finitely many of the cells are required to hold the blank symbol `default : Γ`.
## Main definitions
* `ListBlank Γ` is the type of one-directional tapes with alphabet `Γ`. Implemented as a quotient
of `List Γ` by extension by blanks at the end.
* `Tape Γ` is the type of Turing machine tapes with alphabet `Γ`. Implemented as two
`ListBlank Γ` instances, one for each direction, as well as a head symbol.
-/
assert_not_exists MonoidWithZero
open Function (iterate_succ iterate_succ_apply iterate_zero_apply)
namespace Turing
section ListBlank
/-- The `BlankExtends` partial order holds of `l₁` and `l₂` if `l₂` is obtained by adding
blanks (`default : Γ`) to the end of `l₁`. -/
def BlankExtends {Γ} [Inhabited Γ] (l₁ l₂ : List Γ) : Prop :=
∃ n, l₂ = l₁ ++ List.replicate n default
@[refl]
theorem BlankExtends.refl {Γ} [Inhabited Γ] (l : List Γ) : BlankExtends l l :=
⟨0, by simp⟩
@[trans]
theorem BlankExtends.trans {Γ} [Inhabited Γ] {l₁ l₂ l₃ : List Γ} :
BlankExtends l₁ l₂ → BlankExtends l₂ l₃ → BlankExtends l₁ l₃ := by
rintro ⟨i, rfl⟩ ⟨j, rfl⟩
exact ⟨i + j, by simp⟩
theorem BlankExtends.below_of_le {Γ} [Inhabited Γ] {l l₁ l₂ : List Γ} :
BlankExtends l l₁ → BlankExtends l l₂ → l₁.length ≤ l₂.length → BlankExtends l₁ l₂ := by
rintro ⟨i, rfl⟩ ⟨j, rfl⟩ h; use j - i
simp only [List.length_append, Nat.add_le_add_iff_left, List.length_replicate] at h
simp only [← List.replicate_add, Nat.add_sub_cancel' h, List.append_assoc]
/-- Any two extensions by blank `l₁,l₂` of `l` have a common join (which can be taken to be the
longer of `l₁` and `l₂`). -/
def BlankExtends.above {Γ} [Inhabited Γ] {l l₁ l₂ : List Γ} (h₁ : BlankExtends l l₁)
(h₂ : BlankExtends l l₂) : { l' // BlankExtends l₁ l' ∧ BlankExtends l₂ l' } :=
if h : l₁.length ≤ l₂.length then ⟨l₂, h₁.below_of_le h₂ h, BlankExtends.refl _⟩
else ⟨l₁, BlankExtends.refl _, h₂.below_of_le h₁ (le_of_not_ge h)⟩
theorem BlankExtends.above_of_le {Γ} [Inhabited Γ] {l l₁ l₂ : List Γ} :
BlankExtends l₁ l → BlankExtends l₂ l → l₁.length ≤ l₂.length → BlankExtends l₁ l₂ := by
rintro ⟨i, rfl⟩ ⟨j, e⟩ h; use i - j
refine List.append_cancel_right (e.symm.trans ?_)
rw [List.append_assoc, ← List.replicate_add, Nat.sub_add_cancel]
apply_fun List.length at e
simp only [List.length_append, List.length_replicate] at e
rwa [← Nat.add_le_add_iff_left, e, Nat.add_le_add_iff_right]
/-- `BlankRel` is the symmetric closure of `BlankExtends`, turning it into an equivalence
relation. Two lists are related by `BlankRel` if one extends the other by blanks. -/
def BlankRel {Γ} [Inhabited Γ] (l₁ l₂ : List Γ) : Prop :=
BlankExtends l₁ l₂ ∨ BlankExtends l₂ l₁
@[refl]
theorem BlankRel.refl {Γ} [Inhabited Γ] (l : List Γ) : BlankRel l l :=
Or.inl (BlankExtends.refl _)
@[symm]
theorem BlankRel.symm {Γ} [Inhabited Γ] {l₁ l₂ : List Γ} : BlankRel l₁ l₂ → BlankRel l₂ l₁ :=
Or.symm
@[trans]
theorem BlankRel.trans {Γ} [Inhabited Γ] {l₁ l₂ l₃ : List Γ} :
BlankRel l₁ l₂ → BlankRel l₂ l₃ → BlankRel l₁ l₃ := by
rintro (h₁ | h₁) (h₂ | h₂)
· exact Or.inl (h₁.trans h₂)
· rcases le_total l₁.length l₃.length with h | h
· exact Or.inl (h₁.above_of_le h₂ h)
· exact Or.inr (h₂.above_of_le h₁ h)
· rcases le_total l₁.length l₃.length with h | h
· exact Or.inl (h₁.below_of_le h₂ h)
· exact Or.inr (h₂.below_of_le h₁ h)
· exact Or.inr (h₂.trans h₁)
/-- Given two `BlankRel` lists, there exists (constructively) a common join. -/
def BlankRel.above {Γ} [Inhabited Γ] {l₁ l₂ : List Γ} (h : BlankRel l₁ l₂) :
{ l // BlankExtends l₁ l ∧ BlankExtends l₂ l } := by
refine
if hl : l₁.length ≤ l₂.length then ⟨l₂, Or.elim h id fun h' ↦ ?_, BlankExtends.refl _⟩
else ⟨l₁, BlankExtends.refl _, Or.elim h (fun h' ↦ ?_) id⟩
· exact (BlankExtends.refl _).above_of_le h' hl
· exact (BlankExtends.refl _).above_of_le h' (le_of_not_ge hl)
/-- Given two `BlankRel` lists, there exists (constructively) a common meet. -/
def BlankRel.below {Γ} [Inhabited Γ] {l₁ l₂ : List Γ} (h : BlankRel l₁ l₂) :
{ l // BlankExtends l l₁ ∧ BlankExtends l l₂ } := by
refine
if hl : l₁.length ≤ l₂.length then ⟨l₁, BlankExtends.refl _, Or.elim h id fun h' ↦ ?_⟩
else ⟨l₂, Or.elim h (fun h' ↦ ?_) id, BlankExtends.refl _⟩
· exact (BlankExtends.refl _).above_of_le h' hl
· exact (BlankExtends.refl _).above_of_le h' (le_of_not_ge hl)
theorem BlankRel.equivalence (Γ) [Inhabited Γ] : Equivalence (@BlankRel Γ _) :=
⟨BlankRel.refl, @BlankRel.symm _ _, @BlankRel.trans _ _⟩
/-- Construct a setoid instance for `BlankRel`. -/
def BlankRel.setoid (Γ) [Inhabited Γ] : Setoid (List Γ) :=
⟨_, BlankRel.equivalence _⟩
/-- A `ListBlank Γ` is a quotient of `List Γ` by extension by blanks at the end. This is used to
represent half-tapes of a Turing machine, so that we can pretend that the list continues
infinitely with blanks. -/
def ListBlank (Γ) [Inhabited Γ] :=
Quotient (BlankRel.setoid Γ)
instance ListBlank.inhabited {Γ} [Inhabited Γ] : Inhabited (ListBlank Γ) :=
⟨Quotient.mk'' []⟩
instance ListBlank.hasEmptyc {Γ} [Inhabited Γ] : EmptyCollection (ListBlank Γ) :=
⟨Quotient.mk'' []⟩
/-- A modified version of `Quotient.liftOn'` specialized for `ListBlank`, with the stronger
precondition `BlankExtends` instead of `BlankRel`. -/
protected abbrev ListBlank.liftOn {Γ} [Inhabited Γ] {α} (l : ListBlank Γ) (f : List Γ → α)
(H : ∀ a b, BlankExtends a b → f a = f b) : α :=
l.liftOn' f <| by rintro a b (h | h) <;> [exact H _ _ h; exact (H _ _ h).symm]
/-- The quotient map turning a `List` into a `ListBlank`. -/
def ListBlank.mk {Γ} [Inhabited Γ] : List Γ → ListBlank Γ :=
Quotient.mk''
@[elab_as_elim]
protected theorem ListBlank.induction_on {Γ} [Inhabited Γ] {p : ListBlank Γ → Prop}
(q : ListBlank Γ) (h : ∀ a, p (ListBlank.mk a)) : p q :=
Quotient.inductionOn' q h
/-- The head of a `ListBlank` is well defined. -/
def ListBlank.head {Γ} [Inhabited Γ] (l : ListBlank Γ) : Γ := by
apply l.liftOn List.headI
rintro a _ ⟨i, rfl⟩
cases a
· cases i <;> rfl
rfl
@[simp]
theorem ListBlank.head_mk {Γ} [Inhabited Γ] (l : List Γ) :
ListBlank.head (ListBlank.mk l) = l.headI :=
rfl
/-- The tail of a `ListBlank` is well defined (up to the tail of blanks). -/
def ListBlank.tail {Γ} [Inhabited Γ] (l : ListBlank Γ) : ListBlank Γ := by
apply l.liftOn (fun l ↦ ListBlank.mk l.tail)
rintro a _ ⟨i, rfl⟩
refine Quotient.sound' (Or.inl ?_)
cases a
· rcases i with - | i <;> [exact ⟨0, rfl⟩; exact ⟨i, rfl⟩]
exact ⟨i, rfl⟩
@[simp]
theorem ListBlank.tail_mk {Γ} [Inhabited Γ] (l : List Γ) :
ListBlank.tail (ListBlank.mk l) = ListBlank.mk l.tail :=
rfl
/-- We can cons an element onto a `ListBlank`. -/
def ListBlank.cons {Γ} [Inhabited Γ] (a : Γ) (l : ListBlank Γ) : ListBlank Γ := by
apply l.liftOn (fun l ↦ ListBlank.mk (List.cons a l))
rintro _ _ ⟨i, rfl⟩
exact Quotient.sound' (Or.inl ⟨i, rfl⟩)
@[simp]
theorem ListBlank.cons_mk {Γ} [Inhabited Γ] (a : Γ) (l : List Γ) :
ListBlank.cons a (ListBlank.mk l) = ListBlank.mk (a :: l) :=
rfl
@[simp]
theorem ListBlank.head_cons {Γ} [Inhabited Γ] (a : Γ) : ∀ l : ListBlank Γ, (l.cons a).head = a :=
Quotient.ind' fun _ ↦ rfl
@[simp]
theorem ListBlank.tail_cons {Γ} [Inhabited Γ] (a : Γ) : ∀ l : ListBlank Γ, (l.cons a).tail = l :=
Quotient.ind' fun _ ↦ rfl
/-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `List` where
this only holds for nonempty lists. -/
@[simp]
theorem ListBlank.cons_head_tail {Γ} [Inhabited Γ] : ∀ l : ListBlank Γ, l.tail.cons l.head = l := by
apply Quotient.ind'
refine fun l ↦ Quotient.sound' (Or.inr ?_)
cases l
· exact ⟨1, rfl⟩
· rfl
/-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `List` where
this only holds for nonempty lists. -/
theorem ListBlank.exists_cons {Γ} [Inhabited Γ] (l : ListBlank Γ) :
∃ a l', l = ListBlank.cons a l' :=
⟨_, _, (ListBlank.cons_head_tail _).symm⟩
/-- The n-th element of a `ListBlank` is well defined for all `n : ℕ`, unlike in a `List`. -/
def ListBlank.nth {Γ} [Inhabited Γ] (l : ListBlank Γ) (n : ℕ) : Γ := by
apply l.liftOn (fun l ↦ List.getI l n)
rintro l _ ⟨i, rfl⟩
rcases lt_or_ge n _ with h | h
· rw [List.getI_append _ _ _ h]
rw [List.getI_eq_default _ h]
rcases le_or_gt _ n with h₂ | h₂
· rw [List.getI_eq_default _ h₂]
rw [List.getI_eq_getElem _ h₂, List.getElem_append_right h, List.getElem_replicate]
@[simp]
theorem ListBlank.nth_mk {Γ} [Inhabited Γ] (l : List Γ) (n : ℕ) :
(ListBlank.mk l).nth n = l.getI n :=
rfl
@[simp]
theorem ListBlank.nth_zero {Γ} [Inhabited Γ] (l : ListBlank Γ) : l.nth 0 = l.head := by
conv => lhs; rw [← ListBlank.cons_head_tail l]
exact Quotient.inductionOn' l.tail fun l ↦ rfl
@[simp]
theorem ListBlank.nth_succ {Γ} [Inhabited Γ] (l : ListBlank Γ) (n : ℕ) :
l.nth (n + 1) = l.tail.nth n := by
conv => lhs; rw [← ListBlank.cons_head_tail l]
exact Quotient.inductionOn' l.tail fun l ↦ rfl
@[ext]
theorem ListBlank.ext {Γ} [i : Inhabited Γ] {L₁ L₂ : ListBlank Γ} :
(∀ i, L₁.nth i = L₂.nth i) → L₁ = L₂ := by
refine ListBlank.induction_on L₁ fun l₁ ↦ ListBlank.induction_on L₂ fun l₂ H ↦ ?_
wlog h : l₁.length ≤ l₂.length
· cases le_total l₁.length l₂.length <;> [skip; symm] <;> apply this <;> try assumption
intro
rw [H]
refine Quotient.sound' (Or.inl ⟨l₂.length - l₁.length, ?_⟩)
refine List.ext_getElem ?_ fun i h h₂ ↦ Eq.symm ?_
· simp only [Nat.add_sub_cancel' h, List.length_append, List.length_replicate]
simp only [ListBlank.nth_mk] at H
rcases lt_or_ge i l₁.length with h' | h'
· simp [h', List.getElem_append h₂, ← List.getI_eq_getElem _ h, ← List.getI_eq_getElem _ h', H]
· rw [List.getElem_append_right h', List.getElem_replicate,
← List.getI_eq_default _ h', H, List.getI_eq_getElem _ h]
/-- Apply a function to a value stored at the nth position of the list. -/
@[simp]
def ListBlank.modifyNth {Γ} [Inhabited Γ] (f : Γ → Γ) : ℕ → ListBlank Γ → ListBlank Γ
| 0, L => L.tail.cons (f L.head)
| n + 1, L => (L.tail.modifyNth f n).cons L.head
theorem ListBlank.nth_modifyNth {Γ} [Inhabited Γ] (f : Γ → Γ) (n i) (L : ListBlank Γ) :
(L.modifyNth f n).nth i = if i = n then f (L.nth i) else L.nth i := by
induction n generalizing i L with
| zero =>
cases i <;> simp only [ListBlank.nth_zero, if_true, ListBlank.head_cons, ListBlank.modifyNth,
ListBlank.nth_succ, if_false, ListBlank.tail_cons, reduceCtorEq]
| succ n IH =>
cases i
· rw [if_neg (Nat.succ_ne_zero _).symm]
simp only [ListBlank.nth_zero, ListBlank.head_cons, ListBlank.modifyNth]
· simp only [IH, ListBlank.modifyNth, ListBlank.nth_succ, ListBlank.tail_cons, Nat.succ.injEq]
/-- A pointed map of `Inhabited` types is a map that sends one default value to the other. -/
structure PointedMap.{u, v} (Γ : Type u) (Γ' : Type v) [Inhabited Γ] [Inhabited Γ'] :
Type max u v where
/-- The map underlying this instance. -/
f : Γ → Γ'
map_pt' : f default = default
instance {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] : Inhabited (PointedMap Γ Γ') :=
⟨⟨default, rfl⟩⟩
instance {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] : CoeFun (PointedMap Γ Γ') fun _ ↦ Γ → Γ' :=
⟨PointedMap.f⟩
theorem PointedMap.mk_val {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : Γ → Γ') (pt) :
(PointedMap.mk f pt : Γ → Γ') = f :=
rfl
@[simp]
theorem PointedMap.map_pt {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') :
f default = default :=
PointedMap.map_pt' _
@[simp]
theorem PointedMap.headI_map {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ')
(l : List Γ) : (l.map f).headI = f l.headI := by
cases l <;> [exact (PointedMap.map_pt f).symm; rfl]
/-- The `map` function on lists is well defined on `ListBlank`s provided that the map is
pointed. -/
def ListBlank.map {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (l : ListBlank Γ) :
ListBlank Γ' := by
apply l.liftOn (fun l ↦ ListBlank.mk (List.map f l))
rintro l _ ⟨i, rfl⟩; refine Quotient.sound' (Or.inl ⟨i, ?_⟩)
simp only [PointedMap.map_pt, List.map_append, List.map_replicate]
@[simp]
theorem ListBlank.map_mk {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (l : List Γ) :
(ListBlank.mk l).map f = ListBlank.mk (l.map f) :=
rfl
@[simp]
theorem ListBlank.head_map {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ')
(l : ListBlank Γ) : (l.map f).head = f l.head := by
conv => lhs; rw [← ListBlank.cons_head_tail l]
exact Quotient.inductionOn' l fun a ↦ rfl
@[simp]
theorem ListBlank.tail_map {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ')
(l : ListBlank Γ) : (l.map f).tail = l.tail.map f := by
conv => lhs; rw [← ListBlank.cons_head_tail l]
exact Quotient.inductionOn' l fun a ↦ rfl
@[simp]
theorem ListBlank.map_cons {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ')
(l : ListBlank Γ) (a : Γ) : (l.cons a).map f = (l.map f).cons (f a) := by
refine (ListBlank.cons_head_tail _).symm.trans ?_
simp only [ListBlank.head_map, ListBlank.head_cons, ListBlank.tail_map, ListBlank.tail_cons]
@[simp]
theorem ListBlank.nth_map {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ')
(l : ListBlank Γ) (n : ℕ) : (l.map f).nth n = f (l.nth n) := by
refine l.induction_on fun l ↦ ?_
simp only [ListBlank.map_mk, ListBlank.nth_mk, ← List.getD_default_eq_getI]
rw [← List.getD_map _ _ f]
simp
/-- The `i`-th projection as a pointed map. -/
def proj {ι : Type*} {Γ : ι → Type*} [∀ i, Inhabited (Γ i)] (i : ι) :
PointedMap (∀ i, Γ i) (Γ i) :=
⟨fun a ↦ a i, rfl⟩
theorem proj_map_nth {ι : Type*} {Γ : ι → Type*} [∀ i, Inhabited (Γ i)] (i : ι) (L n) :
(ListBlank.map (@proj ι Γ _ i) L).nth n = L.nth n i := by
rw [ListBlank.nth_map]; rfl
theorem ListBlank.map_modifyNth {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (F : PointedMap Γ Γ')
(f : Γ → Γ) (f' : Γ' → Γ') (H : ∀ x, F (f x) = f' (F x)) (n) (L : ListBlank Γ) :
(L.modifyNth f n).map F = (L.map F).modifyNth f' n := by
induction n generalizing L <;>
simp only [*, ListBlank.head_map, ListBlank.modifyNth, ListBlank.map_cons, ListBlank.tail_map]
/-- Append a list on the left side of a `ListBlank`. -/
@[simp]
def ListBlank.append {Γ} [Inhabited Γ] : List Γ → ListBlank Γ → ListBlank Γ
| [], L => L
| a :: l, L => ListBlank.cons a (ListBlank.append l L)
@[simp]
theorem ListBlank.append_mk {Γ} [Inhabited Γ] (l₁ l₂ : List Γ) :
ListBlank.append l₁ (ListBlank.mk l₂) = ListBlank.mk (l₁ ++ l₂) := by
induction l₁ <;>
simp only [*, ListBlank.append, List.nil_append, List.cons_append, ListBlank.cons_mk]
theorem ListBlank.append_assoc {Γ} [Inhabited Γ] (l₁ l₂ : List Γ) (l₃ : ListBlank Γ) :
ListBlank.append (l₁ ++ l₂) l₃ = ListBlank.append l₁ (ListBlank.append l₂ l₃) := by
refine l₃.induction_on fun l ↦ ?_
simp only [ListBlank.append_mk, List.append_assoc]
/-- The `flatMap` function on lists is well defined on `ListBlank`s provided that the default
element is sent to a sequence of default elements. -/
def ListBlank.flatMap {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (l : ListBlank Γ) (f : Γ → List Γ')
(hf : ∃ n, f default = List.replicate n default) : ListBlank Γ' := by
apply l.liftOn (fun l ↦ ListBlank.mk (l.flatMap f))
rintro l _ ⟨i, rfl⟩; obtain ⟨n, e⟩ := hf; refine Quotient.sound' (Or.inl ⟨i * n, ?_⟩)
rw [List.flatMap_append, mul_comm]; congr
induction i with
| zero => rfl
| succ i IH =>
simp only [IH, e, List.replicate_add, Nat.mul_succ, add_comm, List.replicate_succ,
List.flatMap_cons]
@[simp]
theorem ListBlank.flatMap_mk
{Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (l : List Γ) (f : Γ → List Γ') (hf) :
(ListBlank.mk l).flatMap f hf = ListBlank.mk (l.flatMap f) :=
rfl
@[simp]
theorem ListBlank.cons_flatMap {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (a : Γ) (l : ListBlank Γ)
(f : Γ → List Γ') (hf) : (l.cons a).flatMap f hf = (l.flatMap f hf).append (f a) := by
refine l.induction_on fun l ↦ ?_
simp only [ListBlank.append_mk, ListBlank.flatMap_mk, ListBlank.cons_mk, List.flatMap_cons]
end ListBlank
section Tape
/-- The tape of a Turing machine is composed of a head element (which we imagine to be the
current position of the head), together with two `ListBlank`s denoting the portions of the tape
going off to the left and right. When the Turing machine moves right, an element is pulled from the
right side and becomes the new head, while the head element is `cons`ed onto the left side. -/
structure Tape (Γ : Type*) [Inhabited Γ] where
/-- The current position of the head. -/
head : Γ
/-- The portion of the tape going off to the left. -/
left : ListBlank Γ
/-- The portion of the tape going off to the right. -/
right : ListBlank Γ
instance Tape.inhabited {Γ} [Inhabited Γ] : Inhabited (Tape Γ) :=
⟨by constructor <;> apply default⟩
/-- A direction for the Turing machine `move` command, either
left or right. -/
inductive Dir
| left
| right
deriving DecidableEq, Inhabited
/-- The "inclusive" left side of the tape, including both `left` and `head`. -/
def Tape.left₀ {Γ} [Inhabited Γ] (T : Tape Γ) : ListBlank Γ :=
T.left.cons T.head
/-- The "inclusive" right side of the tape, including both `right` and `head`. -/
def Tape.right₀ {Γ} [Inhabited Γ] (T : Tape Γ) : ListBlank Γ :=
T.right.cons T.head
/-- Move the tape in response to a motion of the Turing machine. Note that `T.move Dir.left` makes
`T.left` smaller; the Turing machine is moving left and the tape is moving right. -/
def Tape.move {Γ} [Inhabited Γ] : Dir → Tape Γ → Tape Γ
| Dir.left, ⟨a, L, R⟩ => ⟨L.head, L.tail, R.cons a⟩
| Dir.right, ⟨a, L, R⟩ => ⟨R.head, L.cons a, R.tail⟩
@[simp]
theorem Tape.move_left_right {Γ} [Inhabited Γ] (T : Tape Γ) :
(T.move Dir.left).move Dir.right = T := by
simp [Tape.move]
@[simp]
theorem Tape.move_right_left {Γ} [Inhabited Γ] (T : Tape Γ) :
(T.move Dir.right).move Dir.left = T := by
simp [Tape.move]
/-- Construct a tape from a left side and an inclusive right side. -/
def Tape.mk' {Γ} [Inhabited Γ] (L R : ListBlank Γ) : Tape Γ :=
⟨R.head, L, R.tail⟩
@[simp]
theorem Tape.mk'_left {Γ} [Inhabited Γ] (L R : ListBlank Γ) : (Tape.mk' L R).left = L :=
rfl
@[simp]
theorem Tape.mk'_head {Γ} [Inhabited Γ] (L R : ListBlank Γ) : (Tape.mk' L R).head = R.head :=
rfl
@[simp]
theorem Tape.mk'_right {Γ} [Inhabited Γ] (L R : ListBlank Γ) : (Tape.mk' L R).right = R.tail :=
rfl
@[simp]
theorem Tape.mk'_right₀ {Γ} [Inhabited Γ] (L R : ListBlank Γ) : (Tape.mk' L R).right₀ = R :=
ListBlank.cons_head_tail _
@[simp]
theorem Tape.mk'_left_right₀ {Γ} [Inhabited Γ] (T : Tape Γ) : Tape.mk' T.left T.right₀ = T := by
simp only [Tape.right₀, Tape.mk', ListBlank.head_cons, ListBlank.tail_cons]
theorem Tape.exists_mk' {Γ} [Inhabited Γ] (T : Tape Γ) : ∃ L R, T = Tape.mk' L R :=
⟨_, _, (Tape.mk'_left_right₀ _).symm⟩
@[simp]
theorem Tape.move_left_mk' {Γ} [Inhabited Γ] (L R : ListBlank Γ) :
(Tape.mk' L R).move Dir.left = Tape.mk' L.tail (R.cons L.head) := by
simp only [Tape.move, Tape.mk', ListBlank.head_cons, ListBlank.cons_head_tail,
ListBlank.tail_cons]
@[simp]
theorem Tape.move_right_mk' {Γ} [Inhabited Γ] (L R : ListBlank Γ) :
(Tape.mk' L R).move Dir.right = Tape.mk' (L.cons R.head) R.tail := by
simp only [Tape.move, Tape.mk']
/-- Construct a tape from a left side and an inclusive right side. -/
def Tape.mk₂ {Γ} [Inhabited Γ] (L R : List Γ) : Tape Γ :=
Tape.mk' (ListBlank.mk L) (ListBlank.mk R)
/-- Construct a tape from a list, with the head of the list at the TM head and the rest going
to the right. -/
def Tape.mk₁ {Γ} [Inhabited Γ] (l : List Γ) : Tape Γ :=
Tape.mk₂ [] l
/-- The `nth` function of a tape is integer-valued, with index `0` being the head, negative indexes
on the left and positive indexes on the right. (Picture a number line.) -/
def Tape.nth {Γ} [Inhabited Γ] (T : Tape Γ) : ℤ → Γ
| 0 => T.head
| (n + 1 : ℕ) => T.right.nth n
| -(n + 1 : ℕ) => T.left.nth n
@[simp]
theorem Tape.nth_zero {Γ} [Inhabited Γ] (T : Tape Γ) : T.nth 0 = T.1 :=
rfl
theorem Tape.right₀_nth {Γ} [Inhabited Γ] (T : Tape Γ) (n : ℕ) : T.right₀.nth n = T.nth n := by
cases n <;> simp only [Tape.nth, Tape.right₀, ListBlank.nth_zero,
ListBlank.nth_succ, ListBlank.head_cons, ListBlank.tail_cons]
@[simp]
theorem Tape.mk'_nth_nat {Γ} [Inhabited Γ] (L R : ListBlank Γ) (n : ℕ) :
(Tape.mk' L R).nth n = R.nth n := by
rw [← Tape.right₀_nth, Tape.mk'_right₀]
@[simp]
theorem Tape.move_left_nth {Γ} [Inhabited Γ] :
∀ (T : Tape Γ) (i : ℤ), (T.move Dir.left).nth i = T.nth (i - 1)
| ⟨_, _, _⟩, -(_ + 1 : ℕ) => (ListBlank.nth_succ _ _).symm
| ⟨_, _, _⟩, 0 => (ListBlank.nth_zero _).symm
| ⟨_, _, _⟩, 1 => (ListBlank.nth_zero _).trans (ListBlank.head_cons _ _)
| ⟨a, L, R⟩, (n + 1 : ℕ) + 1 => by
rw [add_sub_cancel_right]
change (R.cons a).nth (n + 1) = R.nth n
rw [ListBlank.nth_succ, ListBlank.tail_cons]
@[simp]
theorem Tape.move_right_nth {Γ} [Inhabited Γ] (T : Tape Γ) (i : ℤ) :
(T.move Dir.right).nth i = T.nth (i + 1) := by
conv => rhs; rw [← T.move_right_left]
rw [Tape.move_left_nth, add_sub_cancel_right]
@[simp]
theorem Tape.move_right_n_head {Γ} [Inhabited Γ] (T : Tape Γ) (i : ℕ) :
((Tape.move Dir.right)^[i] T).head = T.nth i := by
induction i generalizing T
· rfl
· simp only [*, Tape.move_right_nth, Int.natCast_succ, iterate_succ, Function.comp_apply]
/-- Replace the current value of the head on the tape. -/
def Tape.write {Γ} [Inhabited Γ] (b : Γ) (T : Tape Γ) : Tape Γ :=
{ T with head := b }
@[simp]
theorem Tape.write_self {Γ} [Inhabited Γ] : ∀ T : Tape Γ, T.write T.1 = T := by
rintro ⟨⟩; rfl
@[simp]
theorem Tape.write_nth {Γ} [Inhabited Γ] (b : Γ) :
∀ (T : Tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i
| _, 0 => rfl
| _, (_ + 1 : ℕ) => rfl
| _, -(_ + 1 : ℕ) => rfl
@[simp]
theorem Tape.write_mk' {Γ} [Inhabited Γ] (a b : Γ) (L R : ListBlank Γ) :
(Tape.mk' L (R.cons a)).write b = Tape.mk' L (R.cons b) := by
simp only [Tape.write, Tape.mk', ListBlank.head_cons, ListBlank.tail_cons]
/-- Apply a pointed map to a tape to change the alphabet. -/
def Tape.map {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (T : Tape Γ) : Tape Γ' :=
⟨f T.1, T.2.map f, T.3.map f⟩
@[simp]
theorem Tape.map_fst {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') :
∀ T : Tape Γ, (T.map f).1 = f T.1 := by
rintro ⟨⟩; rfl
@[simp]
theorem Tape.map_write {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (b : Γ) :
∀ T : Tape Γ, (T.write b).map f = (T.map f).write (f b) := by
rintro ⟨⟩; rfl
@[simp]
theorem Tape.write_move_right_n {Γ} [Inhabited Γ] (f : Γ → Γ) (L R : ListBlank Γ) (n : ℕ) :
((Tape.move Dir.right)^[n] (Tape.mk' L R)).write (f (R.nth n)) =
(Tape.move Dir.right)^[n] (Tape.mk' L (R.modifyNth f n)) := by
induction n generalizing L R with
| zero =>
simp only [ListBlank.nth_zero, ListBlank.modifyNth, iterate_zero_apply]
rw [← Tape.write_mk', ListBlank.cons_head_tail]
| succ n IH =>
simp only [ListBlank.head_cons, ListBlank.nth_succ, ListBlank.modifyNth, Tape.move_right_mk',
ListBlank.tail_cons, iterate_succ_apply, IH]
theorem Tape.map_move {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (T : Tape Γ) (d) :
(T.move d).map f = (T.map f).move d := by
cases T
cases d <;> simp only [Tape.move, Tape.map, ListBlank.head_map,
ListBlank.map_cons, ListBlank.tail_map]
theorem Tape.map_mk' {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (L R : ListBlank Γ) :
(Tape.mk' L R).map f = Tape.mk' (L.map f) (R.map f) := by
simp only [Tape.mk', Tape.map, ListBlank.head_map,
ListBlank.tail_map]
theorem Tape.map_mk₂ {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (L R : List Γ) :
(Tape.mk₂ L R).map f = Tape.mk₂ (L.map f) (R.map f) := by
simp only [Tape.mk₂, Tape.map_mk', ListBlank.map_mk]
theorem Tape.map_mk₁ {Γ Γ'} [Inhabited Γ] [Inhabited Γ'] (f : PointedMap Γ Γ') (l : List Γ) :
(Tape.mk₁ l).map f = Tape.mk₁ (l.map f) :=
Tape.map_mk₂ _ _ _
end Tape
end Turing |
.lake/packages/mathlib/Mathlib/Computability/TuringDegree.lean | import Mathlib.Computability.Partrec
import Mathlib.Order.Antisymmetrization
/-!
# Oracle computability and Turing degrees
This file defines a model of oracle computability using partial recursive functions. It introduces
Turing reducibility and equivalence, proves that Turing equivalence is an equivalence relation, and
defines Turing degrees as the quotient under this relation.
## Main definitions
- `RecursiveIn O f`: An inductive definition representing that a partial function `f` is partially
recursive given access to a set of oracles O.
- `TuringReducible`: A relation defining Turing reducibility between partial functions.
- `TuringEquivalent`: An equivalence relation defining Turing equivalence between partial functions.
- `TuringDegree`: The type of Turing degrees, defined as the quotient of partial functions under
`TuringEquivalent`.
## Notation
- `f ≤ᵀ g` : `f` is Turing reducible to `g`.
- `f ≡ᵀ g` : `f` is Turing equivalent to `g`.
## Implementation notes
The type of partial functions recursive in a set of oracles `O` is the smallest type containing
the constant zero, the successor, left and right projections, each oracle `g ∈ O`,
and is closed under pairing, composition, primitive recursion, and μ-recursion.
## References
* [Odifreddi1989] Odifreddi, Piergiorgio.
*Classical Recursion Theory: The Theory of Functions and Sets of Natural Numbers,
Vol. I*. Springer-Verlag, 1989.
## Tags
Computability, Oracle, Turing Degrees, Reducibility, Equivalence Relation
-/
open Primrec Nat.Partrec Part
variable {f g h : ℕ →. ℕ}
/--
The type of partial functions recursive in a set of oracles `O` is the smallest type containing
the constant zero, the successor, left and right projections, each oracle `g ∈ O`,
and is closed under pairing, composition, primitive recursion, and μ-recursion.
-/
inductive RecursiveIn (O : Set (ℕ →. ℕ)) : (ℕ →. ℕ) → Prop
| zero : RecursiveIn O fun _ => 0
| succ : RecursiveIn O Nat.succ
| left : RecursiveIn O fun n => (Nat.unpair n).1
| right : RecursiveIn O fun n => (Nat.unpair n).2
| oracle : ∀ g ∈ O, RecursiveIn O g
| pair {f h : ℕ →. ℕ} (hf : RecursiveIn O f) (hh : RecursiveIn O h) :
RecursiveIn O fun n => (Nat.pair <$> f n <*> h n)
| comp {f h : ℕ →. ℕ} (hf : RecursiveIn O f) (hh : RecursiveIn O h) :
RecursiveIn O fun n => h n >>= f
| prec {f h : ℕ →. ℕ} (hf : RecursiveIn O f) (hh : RecursiveIn O h) :
RecursiveIn O fun p =>
let (a, n) := Nat.unpair p
n.rec (f a) fun y IH => do
let i ← IH
h (Nat.pair a (Nat.pair y i))
| rfind {f : ℕ →. ℕ} (hf : RecursiveIn O f) :
RecursiveIn O fun a =>
Nat.rfind fun n => (fun m => m = 0) <$> f (Nat.pair a n)
/--
`f` is Turing reducible to `g` if `f` is partial recursive given access to the oracle `g`
-/
abbrev TuringReducible (f g : ℕ →. ℕ) : Prop :=
RecursiveIn {g} f
/--
`f` is Turing equivalent to `g` if `f` is reducible to `g` and `g` is reducible to `f`.
-/
abbrev TuringEquivalent (f g : ℕ →. ℕ) : Prop :=
AntisymmRel TuringReducible f g
@[inherit_doc] scoped[Computability] infix:50 " ≤ᵀ " => TuringReducible
@[inherit_doc] scoped[Computability] infix:50 " ≡ᵀ " => TuringEquivalent
open scoped Computability
/--
If a function is partial recursive, then it is recursive in every partial function.
-/
lemma Nat.Partrec.turingReducible (pF : Nat.Partrec f) : f ≤ᵀ g := by
induction pF with repeat {constructor}
| pair _ _ ih₁ ih₂ => exact RecursiveIn.pair ih₁ ih₂
| comp _ _ ih₁ ih₂ => exact RecursiveIn.comp ih₁ ih₂
| prec _ _ ih₁ ih₂ => exact RecursiveIn.prec ih₁ ih₂
| rfind _ ih => exact RecursiveIn.rfind ih
/--
If a function is recursive in the constant zero function,
then it is partial recursive.
-/
lemma TuringReducible.partrec_of_zero (fRecInZero : f ≤ᵀ fun _ => Part.some 0) : Nat.Partrec f := by
induction fRecInZero with repeat {constructor}
| oracle _ hg => rw [Set.mem_singleton_iff] at hg; rw [hg]; exact Nat.Partrec.zero
| pair | comp | prec | rfind => repeat {constructor; assumption; try assumption}
/--
A partial function `f` is partial recursive if and only if it is recursive in
every partial function `g`.
-/
theorem partrec_iff_forall_turingReducible : Nat.Partrec f ↔ ∀ g, f ≤ᵀ g :=
⟨fun hf _ ↦ hf.turingReducible, (· _ |>.partrec_of_zero)⟩
protected theorem TuringReducible.refl (f : ℕ →. ℕ) : f ≤ᵀ f := .oracle _ <| by simp
protected theorem TuringReducible.rfl : f ≤ᵀ f := .refl _
theorem TuringReducible.trans (hg : f ≤ᵀ g) (hh : g ≤ᵀ h) : f ≤ᵀ h := by
induction hg with repeat {constructor}
| oracle _ hg => rw [Set.mem_singleton_iff] at hg; rw [hg]; exact hh
| pair _ _ ih₁ ih₂ => exact RecursiveIn.pair ih₁ ih₂
| comp _ _ ih₁ ih₂ => exact RecursiveIn.comp ih₁ ih₂
| prec _ _ ih₁ ih₂ => exact RecursiveIn.prec ih₁ ih₂
| rfind _ ih => exact RecursiveIn.rfind ih
instance : IsPreorder (ℕ →. ℕ) TuringReducible where
refl _ := .rfl
trans := @TuringReducible.trans
theorem TuringEquivalent.equivalence : Equivalence TuringEquivalent :=
(AntisymmRel.setoid _ _).iseqv
@[refl]
protected theorem TuringEquivalent.refl (f : ℕ →. ℕ) : f ≡ᵀ f :=
Equivalence.refl equivalence f
@[symm]
theorem TuringEquivalent.symm {f g : ℕ →. ℕ} (h : f ≡ᵀ g) : g ≡ᵀ f :=
Equivalence.symm equivalence h
@[trans]
theorem TuringEquivalent.trans (f g h : ℕ →. ℕ) (h₁ : f ≡ᵀ g) (h₂ : g ≡ᵀ h) : f ≡ᵀ h :=
Equivalence.trans equivalence h₁ h₂
/--
Turing degrees are the equivalence classes of partial functions under Turing equivalence.
-/
abbrev TuringDegree :=
Antisymmetrization _ TuringReducible
private instance : Preorder (ℕ →. ℕ) where
le := TuringReducible
le_refl := .refl
le_trans _ _ _ := TuringReducible.trans
instance TuringDegree.instPartialOrder : PartialOrder TuringDegree :=
instPartialOrderAntisymmetrization
@[simp] lemma recursiveIn_empty_iff_partrec : RecursiveIn {} f ↔ Nat.Partrec f where
mp fRecInNone := by
induction fRecInNone with repeat {constructor}
| oracle _ hg => simp at hg
| pair | comp | prec | rfind =>
repeat {constructor; assumption; try assumption}
mpr pF := by
induction pF with repeat {constructor}
| pair _ _ ih₁ ih₂ => exact RecursiveIn.pair ih₁ ih₂
| comp _ _ ih₁ ih₂ => exact RecursiveIn.comp ih₁ ih₂
| prec _ _ ih₁ ih₂ => exact RecursiveIn.prec ih₁ ih₂
| rfind _ ih => exact RecursiveIn.rfind ih |
.lake/packages/mathlib/Mathlib/Computability/RegularExpressions.lean | import Mathlib.Computability.Language
import Mathlib.Tactic.AdaptationNote
/-!
# Regular Expressions
This file contains the formal definition for regular expressions and basic lemmas. Note these are
regular expressions in terms of formal language theory. Note this is different to regex's used in
computer science such as the POSIX standard.
## TODO
Currently, we don't show that regular expressions and DFA/NFA's are equivalent.
Multiple competing PRs towards that goal are in review.
See https://leanprover.zulipchat.com/#narrow/channel/287929-mathlib4/topic/Regular.20languages.3A.20the.20review.20queue
-/
open List Set
open Computability
universe u
variable {α β γ : Type*}
-- Disable generation of unneeded lemmas which the simpNF linter would complain about.
set_option genSizeOfSpec false in
set_option genInjectivity false in
/-- This is the definition of regular expressions. The names used here is to mirror the definition
of a Kleene algebra (https://en.wikipedia.org/wiki/Kleene_algebra).
* `0` (`zero`) matches nothing
* `1` (`epsilon`) matches only the empty string
* `char a` matches only the string 'a'
* `star P` matches any finite concatenation of strings which match `P`
* `P + Q` (`plus P Q`) matches anything which match `P` or `Q`
* `P * Q` (`comp P Q`) matches `x ++ y` if `x` matches `P` and `y` matches `Q`
-/
inductive RegularExpression (α : Type u) : Type u
| zero : RegularExpression α
| epsilon : RegularExpression α
| char : α → RegularExpression α
| plus : RegularExpression α → RegularExpression α → RegularExpression α
| comp : RegularExpression α → RegularExpression α → RegularExpression α
| star : RegularExpression α → RegularExpression α
namespace RegularExpression
variable {a b : α}
instance : Inhabited (RegularExpression α) :=
⟨zero⟩
instance : Add (RegularExpression α) :=
⟨plus⟩
instance : Mul (RegularExpression α) :=
⟨comp⟩
instance : One (RegularExpression α) :=
⟨epsilon⟩
instance : Zero (RegularExpression α) :=
⟨zero⟩
instance : Pow (RegularExpression α) ℕ :=
⟨fun n r => npowRec r n⟩
@[simp]
theorem zero_def : (zero : RegularExpression α) = 0 :=
rfl
@[simp]
theorem one_def : (epsilon : RegularExpression α) = 1 :=
rfl
@[simp]
theorem plus_def (P Q : RegularExpression α) : plus P Q = P + Q :=
rfl
@[simp]
theorem comp_def (P Q : RegularExpression α) : comp P Q = P * Q :=
rfl
/-- `matches' P` provides a language which contains all strings that `P` matches.
Not named `matches` since that is a reserved word.
-/
@[simp]
def matches' : RegularExpression α → Language α
| 0 => 0
| 1 => 1
| char a => {[a]}
| P + Q => P.matches' + Q.matches'
| P * Q => P.matches' * Q.matches'
| star P => P.matches'∗
theorem matches'_zero : (0 : RegularExpression α).matches' = 0 :=
rfl
theorem matches'_epsilon : (1 : RegularExpression α).matches' = 1 :=
rfl
theorem matches'_char (a : α) : (char a).matches' = {[a]} :=
rfl
theorem matches'_add (P Q : RegularExpression α) : (P + Q).matches' = P.matches' + Q.matches' :=
rfl
theorem matches'_mul (P Q : RegularExpression α) : (P * Q).matches' = P.matches' * Q.matches' :=
rfl
@[simp]
theorem matches'_pow (P : RegularExpression α) : ∀ n : ℕ, (P ^ n).matches' = P.matches' ^ n
| 0 => matches'_epsilon
| n + 1 => (matches'_mul _ _).trans <| Eq.trans
(congrFun (congrArg HMul.hMul (matches'_pow P n)) (matches' P))
(pow_succ _ n).symm
theorem matches'_star (P : RegularExpression α) : P.star.matches' = P.matches'∗ :=
rfl
/-- `matchEpsilon P` is true if and only if `P` matches the empty string -/
def matchEpsilon : RegularExpression α → Bool
| 0 => false
| 1 => true
| char _ => false
| P + Q => P.matchEpsilon || Q.matchEpsilon
| P * Q => P.matchEpsilon && Q.matchEpsilon
| star _P => true
section DecidableEq
variable [DecidableEq α]
/-- `P.deriv a` matches `x` if `P` matches `a :: x`, the Brzozowski derivative of `P` with respect
to `a` -/
def deriv : RegularExpression α → α → RegularExpression α
| 0, _ => 0
| 1, _ => 0
| char a₁, a₂ => if a₁ = a₂ then 1 else 0
| P + Q, a => deriv P a + deriv Q a
| P * Q, a => if P.matchEpsilon then deriv P a * Q + deriv Q a else deriv P a * Q
| star P, a => deriv P a * star P
@[simp]
theorem deriv_zero (a : α) : deriv 0 a = 0 :=
rfl
@[simp]
theorem deriv_one (a : α) : deriv 1 a = 0 :=
rfl
@[simp]
theorem deriv_char_self (a : α) : deriv (char a) a = 1 :=
if_pos rfl
@[simp]
theorem deriv_char_of_ne (h : a ≠ b) : deriv (char a) b = 0 :=
if_neg h
@[simp]
theorem deriv_add (P Q : RegularExpression α) (a : α) : deriv (P + Q) a = deriv P a + deriv Q a :=
rfl
@[simp]
theorem deriv_star (P : RegularExpression α) (a : α) : deriv P.star a = deriv P a * star P :=
rfl
/-- `P.rmatch x` is true if and only if `P` matches `x`. This is a computable definition equivalent
to `matches'`. -/
def rmatch : RegularExpression α → List α → Bool
| P, [] => matchEpsilon P
| P, a :: as => rmatch (P.deriv a) as
@[simp]
theorem zero_rmatch (x : List α) : rmatch 0 x = false := by
induction x <;> simp [rmatch, matchEpsilon, *]
theorem one_rmatch_iff (x : List α) : rmatch 1 x ↔ x = [] := by
induction x <;> simp [rmatch, matchEpsilon, *]
theorem char_rmatch_iff (a : α) (x : List α) : rmatch (char a) x ↔ x = [a] := by
rcases x with - | ⟨_, x⟩
· exact of_decide_eq_true rfl
· rcases x with - | ⟨head, tail⟩
· rw [rmatch, deriv, List.singleton_inj]
split <;> tauto
· rw [rmatch, rmatch, deriv, cons.injEq]
split
· simp_rw [deriv_one, zero_rmatch, reduceCtorEq, and_false]
· simp_rw [deriv_zero, zero_rmatch, reduceCtorEq, and_false]
theorem add_rmatch_iff (P Q : RegularExpression α) (x : List α) :
(P + Q).rmatch x ↔ P.rmatch x ∨ Q.rmatch x := by
induction x generalizing P Q with
| nil => simp only [rmatch, matchEpsilon, Bool.or_eq_true_iff]
| cons _ _ ih =>
rw [rmatch, deriv_add]
exact ih _ _
theorem mul_rmatch_iff (P Q : RegularExpression α) (x : List α) :
(P * Q).rmatch x ↔ ∃ t u : List α, x = t ++ u ∧ P.rmatch t ∧ Q.rmatch u := by
induction x generalizing P Q with
| nil =>
rw [rmatch]; simp only [matchEpsilon]
constructor
· intro h
refine ⟨[], [], rfl, ?_⟩
rw [rmatch, rmatch]
rwa [Bool.and_eq_true_iff] at h
· rintro ⟨t, u, h₁, h₂⟩
obtain ⟨ht, hu⟩ := List.append_eq_nil_iff.1 h₁.symm
subst ht hu
repeat rw [rmatch] at h₂
simp [h₂]
| cons a x ih =>
rw [rmatch]; simp only [deriv]
split_ifs with hepsilon
· rw [add_rmatch_iff, ih]
constructor
· rintro (⟨t, u, _⟩ | h)
· exact ⟨a :: t, u, by tauto⟩
· exact ⟨[], a :: x, rfl, hepsilon, h⟩
· rintro ⟨t, u, h, hP, hQ⟩
rcases t with - | ⟨b, t⟩
· right
rw [List.nil_append] at h
rw [← h] at hQ
exact hQ
· left
rw [List.cons_append, List.cons_eq_cons] at h
refine ⟨t, u, h.2, ?_, hQ⟩
rw [rmatch] at hP
convert hP
exact h.1
· rw [ih]
constructor <;> rintro ⟨t, u, h, hP, hQ⟩
· exact ⟨a :: t, u, by tauto⟩
· rcases t with - | ⟨b, t⟩
· contradiction
· rw [List.cons_append, List.cons_eq_cons] at h
refine ⟨t, u, h.2, ?_, hQ⟩
rw [rmatch] at hP
convert hP
exact h.1
theorem star_rmatch_iff (P : RegularExpression α) :
∀ x : List α, (star P).rmatch x ↔ ∃ S : List (List α), x
= S.flatten ∧ ∀ t ∈ S, t ≠ [] ∧ P.rmatch t :=
fun x => by
have IH := fun t (_h : List.length t < List.length x) => star_rmatch_iff P t
clear star_rmatch_iff
constructor
· rcases x with - | ⟨a, x⟩
· intro _h
use []; dsimp; tauto
· rw [rmatch, deriv, mul_rmatch_iff]
rintro ⟨t, u, hs, ht, hu⟩
have hwf : u.length < (List.cons a x).length := by
rw [hs, List.length_cons, List.length_append]
omega
rw [IH _ hwf] at hu
rcases hu with ⟨S', hsum, helem⟩
use (a :: t) :: S'
constructor
· simp [hs, hsum]
· intro t' ht'
cases ht' with
| head ht' =>
simp only [ne_eq, not_false_iff, true_and, rmatch, reduceCtorEq]
exact ht
| tail _ ht' => exact helem t' ht'
· rintro ⟨S, hsum, helem⟩
rcases x with - | ⟨a, x⟩
· rfl
· rw [rmatch, deriv, mul_rmatch_iff]
rcases S with - | ⟨t', U⟩
· exact ⟨[], [], by tauto⟩
· obtain - | ⟨b, t⟩ := t'
· simp only [forall_eq_or_imp, List.mem_cons] at helem
simp only [not_true, Ne, false_and] at helem
simp only [List.flatten_cons, List.cons_append, List.cons_eq_cons] at hsum
refine ⟨t, U.flatten, hsum.2, ?_, ?_⟩
· specialize helem (b :: t) (by simp)
rw [rmatch] at helem
convert helem.2
exact hsum.1
· grind
termination_by t => (P, t.length)
@[simp]
theorem rmatch_iff_matches' (P : RegularExpression α) (x : List α) :
P.rmatch x ↔ x ∈ P.matches' := by
induction P generalizing x with
| zero =>
rw [zero_def, zero_rmatch]
tauto
| epsilon =>
rw [one_def, one_rmatch_iff, matches'_epsilon, Language.mem_one]
| char =>
rw [char_rmatch_iff]
rfl
| plus _ _ ih₁ ih₂ =>
rw [plus_def, add_rmatch_iff, ih₁, ih₂]
rfl
| comp P Q ih₁ ih₂ =>
simp only [comp_def, mul_rmatch_iff, matches'_mul, Language.mem_mul, *]
tauto
| star _ ih =>
simp only [star_rmatch_iff, matches'_star, ih, Language.mem_kstar_iff_exists_nonempty, and_comm]
instance (P : RegularExpression α) : DecidablePred (· ∈ P.matches') := fun _ ↦
decidable_of_iff _ (rmatch_iff_matches' _ _)
end DecidableEq
/-- Map the alphabet of a regular expression. -/
@[simp]
def map (f : α → β) : RegularExpression α → RegularExpression β
| 0 => 0
| 1 => 1
| char a => char (f a)
| R + S => map f R + map f S
| R * S => map f R * map f S
| star R => star (map f R)
@[simp]
protected theorem map_pow (f : α → β) (P : RegularExpression α) :
∀ n : ℕ, map f (P ^ n) = map f P ^ n
| 0 => by unfold map; rfl
| n + 1 => (congr_arg (· * map f P) (RegularExpression.map_pow f P n) :)
@[simp]
theorem map_id : ∀ P : RegularExpression α, P.map id = P
| 0 => rfl
| 1 => rfl
| char _ => rfl
| R + S => by simp_rw [map, map_id]
| R * S => by simp_rw [map, map_id]
| star R => by simp_rw [map, map_id]
@[simp]
theorem map_map (g : β → γ) (f : α → β) : ∀ P : RegularExpression α, (P.map f).map g = P.map (g ∘ f)
| 0 => rfl
| 1 => rfl
| char _ => rfl
| R + S => by simp only [map, map_map]
| R * S => by simp only [map, map_map]
| star R => by simp only [map, map_map]
/-- The language of the map is the map of the language. -/
@[simp]
theorem matches'_map (f : α → β) :
∀ P : RegularExpression α, (P.map f).matches' = Language.map f P.matches'
| 0 => (map_zero _).symm
| 1 => (map_one _).symm
| char a => by
rw [eq_comm]
exact image_singleton
| R + S => by simp only [matches'_map, map, matches'_add, map_add]
| R * S => by simp [matches'_map]
| star R => by simp [matches'_map]
end RegularExpression |
.lake/packages/mathlib/Mathlib/Computability/Halting.lean | import Mathlib.Computability.PartrecCode
import Mathlib.Data.Set.Subsingleton
/-!
# Computability theory and the halting problem
A universal partial recursive function, Rice's theorem, and the halting problem.
## References
* [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019]
-/
open List (Vector)
open Encodable Denumerable
namespace Nat.Partrec
open Computable Part
theorem merge' {f g} (hf : Nat.Partrec f) (hg : Nat.Partrec g) :
∃ h, Nat.Partrec h ∧
∀ a, (∀ x ∈ h a, x ∈ f a ∨ x ∈ g a) ∧ ((h a).Dom ↔ (f a).Dom ∨ (g a).Dom) := by
obtain ⟨cf, rfl⟩ := Code.exists_code.1 hf
obtain ⟨cg, rfl⟩ := Code.exists_code.1 hg
have : Nat.Partrec fun n => Nat.rfindOpt fun k => cf.evaln k n <|> cg.evaln k n :=
Partrec.nat_iff.1
(Partrec.rfindOpt <|
Primrec.option_orElse.to_comp.comp
(Code.primrec_evaln.to_comp.comp <| (snd.pair (const cf)).pair fst)
(Code.primrec_evaln.to_comp.comp <| (snd.pair (const cg)).pair fst))
refine ⟨_, this, fun n => ?_⟩
have : ∀ x ∈ rfindOpt fun k ↦ HOrElse.hOrElse (Code.evaln k cf n) fun _x ↦ Code.evaln k cg n,
x ∈ Code.eval cf n ∨ x ∈ Code.eval cg n := by
intro x h
obtain ⟨k, e⟩ := Nat.rfindOpt_spec h
revert e
simp only [Option.mem_def]
rcases e' : cf.evaln k n with - | y <;> simp <;> intro e
· exact Or.inr (Code.evaln_sound e)
· subst y
exact Or.inl (Code.evaln_sound e')
refine ⟨this, ⟨fun h => (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, ?_⟩⟩
intro h
rw [Nat.rfindOpt_dom]
simp only [dom_iff_mem, Code.evaln_complete, Option.mem_def] at h
obtain ⟨x, k, e⟩ | ⟨x, k, e⟩ := h
· refine ⟨k, x, ?_⟩
simp only [e, Option.orElse_some, Option.mem_def, Option.orElse_eq_orElse]
· refine ⟨k, ?_⟩
rcases cf.evaln k n with - | y
· exact ⟨x, by simp only [e, Option.mem_def, Option.orElse_eq_orElse, Option.orElse_none]⟩
· exact ⟨y, by simp only [Option.orElse_eq_orElse, Option.orElse_some, Option.mem_def]⟩
end Nat.Partrec
namespace Partrec
variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ]
open Computable Part
open Nat.Partrec (Code)
open Nat.Partrec.Code
theorem merge' {f g : α →. σ} (hf : Partrec f) (hg : Partrec g) :
∃ k : α →. σ,
Partrec k ∧ ∀ a, (∀ x ∈ k a, x ∈ f a ∨ x ∈ g a) ∧ ((k a).Dom ↔ (f a).Dom ∨ (g a).Dom) := by
let ⟨k, hk, H⟩ := Nat.Partrec.merge' (bind_decode₂_iff.1 hf) (bind_decode₂_iff.1 hg)
let k' (a : α) := (k (encode a)).bind fun n => (decode (α := σ) n : Part σ)
refine
⟨k', ((nat_iff.2 hk).comp Computable.encode).bind (Computable.decode.ofOption.comp snd).to₂,
fun a => ?_⟩
have : ∀ x ∈ k' a, x ∈ f a ∨ x ∈ g a := by
intro x h'
simp only [k', mem_coe, mem_bind_iff, Option.mem_def] at h'
obtain ⟨n, hn, hx⟩ := h'
have := (H _).1 _ hn
simp only [decode₂_encode, coe_some, bind_some, mem_map_iff] at this
obtain ⟨a', ha, rfl⟩ | ⟨a', ha, rfl⟩ := this <;> simp only [encodek, Option.some_inj] at hx <;>
rw [hx] at ha
· exact Or.inl ha
· exact Or.inr ha
refine ⟨this, ⟨fun h => (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, ?_⟩⟩
intro h
rw [bind_dom]
have hk : (k (encode a)).Dom :=
(H _).2.2 (by simpa only [encodek₂, bind_some, coe_some] using h)
exists hk
simp only [mem_map_iff, mem_coe, mem_bind_iff, Option.mem_def] at H
obtain ⟨a', _, y, _, e⟩ | ⟨a', _, y, _, e⟩ := (H _).1 _ ⟨hk, rfl⟩ <;>
simp only [e.symm, encodek, coe_some, some_dom]
theorem merge {f g : α →. σ} (hf : Partrec f) (hg : Partrec g)
(H : ∀ (a), ∀ x ∈ f a, ∀ y ∈ g a, x = y) :
∃ k : α →. σ, Partrec k ∧ ∀ a x, x ∈ k a ↔ x ∈ f a ∨ x ∈ g a :=
let ⟨k, hk, K⟩ := merge' hf hg
⟨k, hk, fun a x =>
⟨(K _).1 _, fun h => by
have : (k a).Dom := (K _).2.2 (h.imp Exists.fst Exists.fst)
refine ⟨this, ?_⟩
rcases h with h | h <;> rcases (K _).1 _ ⟨this, rfl⟩ with h' | h'
· exact mem_unique h' h
· exact (H _ _ h _ h').symm
· exact H _ _ h' _ h
· exact mem_unique h' h⟩⟩
theorem cond {c : α → Bool} {f : α →. σ} {g : α →. σ} (hc : Computable c) (hf : Partrec f)
(hg : Partrec g) : Partrec fun a => cond (c a) (f a) (g a) :=
let ⟨cf, ef⟩ := exists_code.1 hf
let ⟨cg, eg⟩ := exists_code.1 hg
((eval_part.comp (Computable.cond hc (const cf) (const cg)) Computable.encode).bind
((@Computable.decode σ _).comp snd).ofOption.to₂).of_eq
fun a => by cases c a <;> simp [ef, eg, encodek]
nonrec theorem sumCasesOn {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ →. σ} (hf : Computable f)
(hg : Partrec₂ g) (hh : Partrec₂ h) : @Partrec _ σ _ _ fun a => Sum.casesOn (f a) (g a) (h a) :=
option_some_iff.1 <|
(cond (sumCasesOn hf (const true).to₂ (const false).to₂)
(sumCasesOn_left hf (option_some_iff.2 hg).to₂ (const Option.none).to₂)
(sumCasesOn_right hf (const Option.none).to₂ (option_some_iff.2 hh).to₂)).of_eq
fun a => by cases f a <;> simp only [Bool.cond_true, Bool.cond_false]
end Partrec
/-- A computable predicate is one whose indicator function is computable. -/
def ComputablePred {α} [Primcodable α] (p : α → Prop) :=
∃ (_ : DecidablePred p), Computable fun a => decide (p a)
section decide
variable {α} [Primcodable α]
protected lemma ComputablePred.decide {p : α → Prop} [DecidablePred p] (hp : ComputablePred p) :
Computable (fun a => decide (p a)) := by
convert hp.choose_spec
lemma Computable.computablePred {p : α → Prop} [DecidablePred p]
(hp : Computable (fun a => decide (p a))) : ComputablePred p :=
⟨inferInstance, hp⟩
lemma computablePred_iff_computable_decide {p : α → Prop} [DecidablePred p] :
ComputablePred p ↔ Computable (fun a => decide (p a)) where
mp := ComputablePred.decide
mpr := Computable.computablePred
lemma PrimrecPred.computablePred {α} [Primcodable α] {p : α → Prop} :
(hp : PrimrecPred p) → ComputablePred p
| ⟨_, hp⟩ => hp.to_comp.computablePred
end decide
/-- A recursively enumerable predicate is one which is the domain of a computable partial function.
-/
def REPred {α} [Primcodable α] (p : α → Prop) :=
Partrec fun a => Part.assert (p a) fun _ => Part.some ()
theorem REPred.of_eq {α} [Primcodable α] {p q : α → Prop} (hp : REPred p) (H : ∀ a, p a ↔ q a) :
REPred q :=
(funext fun a => propext (H a) : p = q) ▸ hp
theorem Partrec.dom_re {α β} [Primcodable α] [Primcodable β] {f : α →. β} (h : Partrec f) :
REPred fun a => (f a).Dom :=
(h.map (Computable.const ()).to₂).of_eq fun n => Part.ext fun _ => by simp [Part.dom_iff_mem]
theorem ComputablePred.of_eq {α} [Primcodable α] {p q : α → Prop} (hp : ComputablePred p)
(H : ∀ a, p a ↔ q a) : ComputablePred q :=
(funext fun a => propext (H a) : p = q) ▸ hp
namespace ComputablePred
variable {α : Type*} [Primcodable α]
open Nat.Partrec (Code)
open Nat.Partrec.Code Computable
theorem computable_iff {p : α → Prop} :
ComputablePred p ↔ ∃ f : α → Bool, Computable f ∧ p = fun a => (f a : Prop) :=
⟨fun ⟨_, h⟩ => ⟨_, h, funext fun _ => propext (Bool.decide_iff _).symm⟩, by
rintro ⟨f, h, rfl⟩; exact ⟨by infer_instance, by simpa using h⟩⟩
protected theorem not {p : α → Prop} :
(hp : ComputablePred p) → ComputablePred fun a => ¬p a
| ⟨_, hp⟩ => Computable.computablePred <| Primrec.not.to_comp.comp hp |>.of_eq <| by simp
/-- The computable functions are closed under if-then-else definitions
with computable predicates. -/
theorem ite {f₁ f₂ : ℕ → ℕ} (hf₁ : Computable f₁) (hf₂ : Computable f₂)
{c : ℕ → Prop} [DecidablePred c] (hc : ComputablePred c) :
Computable fun k ↦ if c k then f₁ k else f₂ k := by
simpa [Bool.cond_decide] using hc.decide.cond hf₁ hf₂
theorem to_re {p : α → Prop} (hp : ComputablePred p) : REPred p := by
obtain ⟨f, hf, rfl⟩ := computable_iff.1 hp
unfold REPred
dsimp only []
refine
(Partrec.cond hf (Decidable.Partrec.const' (Part.some ())) Partrec.none).of_eq fun n =>
Part.ext fun a => ?_
cases a; cases f n <;> simp
/-- **Rice's Theorem** -/
theorem rice (C : Set (ℕ →. ℕ)) (h : ComputablePred fun c => eval c ∈ C) {f g} (hf : Nat.Partrec f)
(hg : Nat.Partrec g) (fC : f ∈ C) : g ∈ C := by
obtain ⟨_, h⟩ := h
obtain ⟨c, e⟩ :=
fixed_point₂
(Partrec.cond (h.comp fst) ((Partrec.nat_iff.2 hg).comp snd).to₂
((Partrec.nat_iff.2 hf).comp snd).to₂).to₂
simp only [Bool.cond_decide] at e
by_cases H : eval c ∈ C
· simp only [H, if_true] at e
change (fun b => g b) ∈ C
rwa [← e]
· simp only [H, if_false] at e
rw [e] at H
contradiction
theorem rice₂ (C : Set Code) (H : ∀ cf cg, eval cf = eval cg → (cf ∈ C ↔ cg ∈ C)) :
(ComputablePred fun c => c ∈ C) ↔ C = ∅ ∨ C = Set.univ := by
classical exact
have hC : ∀ f, f ∈ C ↔ eval f ∈ eval '' C := fun f =>
⟨Set.mem_image_of_mem _, fun ⟨g, hg, e⟩ => (H _ _ e).1 hg⟩
⟨fun h =>
or_iff_not_imp_left.2 fun C0 =>
Set.eq_univ_of_forall fun cg =>
let ⟨cf, fC⟩ := Set.nonempty_iff_ne_empty.2 C0
(hC _).2 <|
rice (eval '' C) (h.of_eq hC)
(Partrec.nat_iff.1 <| eval_part.comp (const cf) Computable.id)
(Partrec.nat_iff.1 <| eval_part.comp (const cg) Computable.id) ((hC _).1 fC),
fun h => by {
obtain rfl | rfl := h <;> simpa [ComputablePred, Set.mem_empty_iff_false] using
Computable.const _}⟩
/-- The Halting problem is recursively enumerable -/
theorem halting_problem_re (n) : REPred fun c => (eval c n).Dom :=
(eval_part.comp Computable.id (Computable.const _)).dom_re
/-- The **Halting problem** is not computable -/
theorem halting_problem (n) : ¬ComputablePred fun c => (eval c n).Dom
| h => rice { f | (f n).Dom } h Nat.Partrec.zero Nat.Partrec.none trivial
-- Post's theorem on the equivalence of r.e., co-r.e. sets and
-- computable sets. The assumption that p is decidable is required
-- unless we assume Markov's principle or LEM.
-- @[nolint decidable_classical]
theorem computable_iff_re_compl_re {p : α → Prop} [DecidablePred p] :
ComputablePred p ↔ REPred p ∧ REPred fun a => ¬p a :=
⟨fun h => ⟨h.to_re, h.not.to_re⟩, fun ⟨h₁, h₂⟩ =>
⟨‹_›, by
obtain ⟨k, pk, hk⟩ :=
Partrec.merge (h₁.map (Computable.const true).to₂) (h₂.map (Computable.const false).to₂)
(by
intro a x hx y hy
simp only [Part.mem_map_iff, Part.mem_assert_iff, Part.mem_some_iff, exists_prop,
and_true, exists_const] at hx hy
cases hy.1 hx.1)
refine Partrec.of_eq pk fun n => Part.eq_some_iff.2 ?_
rw [hk]
simp only [Part.mem_map_iff, Part.mem_assert_iff, Part.mem_some_iff, exists_prop, and_true,
true_eq_decide_iff, and_self, exists_const, false_eq_decide_iff]
apply Decidable.em⟩⟩
theorem computable_iff_re_compl_re' {p : α → Prop} :
ComputablePred p ↔ REPred p ∧ REPred fun a => ¬p a := by
classical exact computable_iff_re_compl_re
theorem halting_problem_not_re (n) : ¬REPred fun c => ¬(eval c n).Dom
| h => halting_problem _ <| computable_iff_re_compl_re'.2 ⟨halting_problem_re _, h⟩
end ComputablePred
namespace Nat
open Vector Part
/-- A simplified basis for `Partrec`. -/
inductive Partrec' : ∀ {n}, (List.Vector ℕ n →. ℕ) → Prop
| prim {n f} : @Primrec' n f → @Partrec' n f
| comp {m n f} (g : Fin n → List.Vector ℕ m →. ℕ) :
Partrec' f → (∀ i, Partrec' (g i)) →
Partrec' fun v => (List.Vector.mOfFn fun i => g i v) >>= f
| rfind {n} {f : List.Vector ℕ (n + 1) → ℕ} :
@Partrec' (n + 1) f → Partrec' fun v => rfind fun n => some (f (n ::ᵥ v) = 0)
end Nat
namespace Nat.Partrec'
open List.Vector Partrec Computable
open Nat.Partrec'
theorem to_part {n f} (pf : @Partrec' n f) : _root_.Partrec f := by
induction pf with
| prim hf => exact hf.to_prim.to_comp
| comp _ _ _ hf hg => exact (Partrec.vector_mOfFn hg).bind (hf.comp snd)
| rfind _ hf =>
have := hf.comp (vector_cons.comp snd fst)
have :=
((Primrec.eq.decide.comp _root_.Primrec.id (_root_.Primrec.const 0)).to_comp.comp
this).to₂.partrec₂
exact _root_.Partrec.rfind this
theorem of_eq {n} {f g : List.Vector ℕ n →. ℕ} (hf : Partrec' f) (H : ∀ i, f i = g i) :
Partrec' g :=
(funext H : f = g) ▸ hf
theorem of_prim {n} {f : List.Vector ℕ n → ℕ} (hf : Primrec f) : @Partrec' n f :=
prim (Nat.Primrec'.of_prim hf)
theorem head {n : ℕ} : @Partrec' n.succ (@head ℕ n) :=
prim Nat.Primrec'.head
theorem tail {n f} (hf : @Partrec' n f) : @Partrec' n.succ fun v => f v.tail :=
(hf.comp _ fun i => @prim _ _ <| Nat.Primrec'.get i.succ).of_eq fun v => by
simp; rw [← ofFn_get v.tail]; congr; funext i; simp
protected theorem bind {n f g} (hf : @Partrec' n f) (hg : @Partrec' (n + 1) g) :
@Partrec' n fun v => (f v).bind fun a => g (a ::ᵥ v) :=
(@comp n (n + 1) g (fun i => Fin.cases f (fun i v => some (v.get i)) i) hg fun i => by
refine Fin.cases ?_ (fun i => ?_) i <;> simp [*]
exact prim (Nat.Primrec'.get _)).of_eq
fun v => by simp [mOfFn, Part.bind_assoc, pure]
protected theorem map {n f} {g : List.Vector ℕ (n + 1) → ℕ} (hf : @Partrec' n f)
(hg : @Partrec' (n + 1) g) : @Partrec' n fun v => (f v).map fun a => g (a ::ᵥ v) := by
simpa [(Part.bind_some_eq_map _ _).symm] using hf.bind hg
/-- Analogous to `Nat.Partrec'` for `ℕ`-valued functions, a predicate for partial recursive
vector-valued functions. -/
def Vec {n m} (f : List.Vector ℕ n → List.Vector ℕ m) :=
∀ i, Partrec' fun v => (f v).get i
nonrec theorem Vec.prim {n m f} (hf : @Nat.Primrec'.Vec n m f) : Vec f := fun i => prim <| hf i
protected theorem nil {n} : @Vec n 0 fun _ => nil := fun i => i.elim0
protected theorem cons {n m} {f : List.Vector ℕ n → ℕ} {g} (hf : @Partrec' n f)
(hg : @Vec n m g) : Vec fun v => f v ::ᵥ g v := fun i =>
Fin.cases (by simpa using hf) (fun i => by simp only [hg i, get_cons_succ]) i
theorem idv {n} : @Vec n n id :=
Vec.prim Nat.Primrec'.idv
theorem comp' {n m f g} (hf : @Partrec' m f) (hg : @Vec n m g) : Partrec' fun v => f (g v) :=
(hf.comp _ hg).of_eq fun v => by simp
theorem comp₁ {n} (f : ℕ →. ℕ) {g : List.Vector ℕ n → ℕ} (hf : @Partrec' 1 fun v => f v.head)
(hg : @Partrec' n g) : @Partrec' n fun v => f (g v) := by
simpa using hf.comp' (Partrec'.cons hg Partrec'.nil)
theorem rfindOpt {n} {f : List.Vector ℕ (n + 1) → ℕ} (hf : @Partrec' (n + 1) f) :
@Partrec' n fun v => Nat.rfindOpt fun a => ofNat (Option ℕ) (f (a ::ᵥ v)) :=
((rfind <|
(of_prim (Primrec.nat_sub.comp (_root_.Primrec.const 1) Primrec.vector_head)).comp₁
(fun n => Part.some (1 - n)) hf).bind
((prim Nat.Primrec'.pred).comp₁ Nat.pred hf)).of_eq
fun v =>
Part.ext fun b => by
simp only [Nat.rfindOpt, Nat.sub_eq_zero_iff_le, PFun.coe_val, Part.mem_bind_iff,
Part.mem_some_iff, Option.mem_def, Part.mem_coe]
refine
exists_congr fun a => (and_congr (iff_of_eq ?_) Iff.rfl).trans (and_congr_right fun h => ?_)
· congr
funext n
cases f (n ::ᵥ v) <;> simp <;> rfl
· have := Nat.rfind_spec h
simp only [Part.coe_some, Part.mem_some_iff] at this
revert this; rcases f (a ::ᵥ v) with - | c <;> intro this
· cases this
rw [← Option.some_inj, eq_comm]
rfl
open Nat.Partrec.Code
theorem of_part : ∀ {n f}, _root_.Partrec f → @Partrec' n f :=
@(suffices ∀ f, Nat.Partrec f → @Partrec' 1 fun v => f v.head from fun {n f} hf => by
let g := fun n₁ =>
(Part.ofOption (decode (α := List.Vector ℕ n) n₁)).bind (fun a => Part.map encode (f a))
exact
(comp₁ g (this g hf) (prim Nat.Primrec'.encode)).of_eq fun i => by
dsimp only [g]; simp [encodek, Part.map_id']
fun f hf => by
obtain ⟨c, rfl⟩ := exists_code.1 hf
simpa [eval_eq_rfindOpt] using
rfindOpt <|
of_prim <|
Primrec.encode_iff.2 <|
primrec_evaln.comp <|
(Primrec.vector_head.pair (_root_.Primrec.const c)).pair <|
Primrec.vector_head.comp Primrec.vector_tail)
theorem part_iff {n f} : @Partrec' n f ↔ _root_.Partrec f :=
⟨to_part, of_part⟩
theorem part_iff₁ {f : ℕ →. ℕ} : (@Partrec' 1 fun v => f v.head) ↔ _root_.Partrec f :=
part_iff.trans
⟨fun h =>
(h.comp <| (Primrec.vector_ofFn fun _ => _root_.Primrec.id).to_comp).of_eq fun v => by
simp only [id, head_ofFn],
fun h => h.comp vector_head⟩
theorem part_iff₂ {f : ℕ → ℕ →. ℕ} : (@Partrec' 2 fun v => f v.head v.tail.head) ↔ Partrec₂ f :=
part_iff.trans
⟨fun h =>
(h.comp <| vector_cons.comp fst <| vector_cons.comp snd (const nil)).of_eq fun v => by
simp only [head_cons, tail_cons],
fun h => h.comp vector_head (vector_head.comp vector_tail)⟩
theorem vec_iff {m n f} : @Vec m n f ↔ Computable f :=
⟨fun h => by simpa only [ofFn_get] using vector_ofFn fun i => to_part (h i), fun h i =>
of_part <| vector_get.comp h (const i)⟩
end Nat.Partrec' |
.lake/packages/mathlib/Mathlib/Computability/DFA.lean | import Mathlib.Computability.Language
import Mathlib.Data.Countable.Small
import Mathlib.Data.Fintype.Pigeonhole
import Mathlib.Tactic.NormNum
/-!
# Deterministic Finite Automata
A Deterministic Finite Automaton (DFA) is a state machine which
decides membership in a particular `Language`, by following a path
uniquely determined by an input string.
We define regular languages to be ones for which a DFA exists, other formulations
are later proved equivalent.
Note that this definition allows for automata with infinite states,
a `Fintype` instance must be supplied for true DFAs.
## Main definitions
- `DFA α σ`: automaton over alphabet `α` and set of states `σ`
- `M.accepts`: the language accepted by the DFA `M`
- `Language.IsRegular L`: a predicate stating that `L` is a regular language, i.e. there exists
a DFA that recognizes the language
## Main theorems
- `DFA.pumping_lemma` : every sufficiently long string accepted by the DFA has a substring that can
be repeated arbitrarily many times (and have the overall string still be accepted)
## Implementation notes
Currently, there are two disjoint sets of simp lemmas: one for `DFA.eval`, and another for
`DFA.evalFrom`. You can switch from the former to the latter using `simp [eval]`.
## TODO
- Should we unify these simp sets, such that `eval` is rewritten to `evalFrom` automatically?
- Should `mem_accepts` and `mem_acceptsFrom` be marked `@[simp]`?
-/
universe u v
open Computability
/-- A DFA is a set of states (`σ`), a transition function from state to state labelled by the
alphabet (`step`), a starting state (`start`) and a set of acceptance states (`accept`). -/
structure DFA (α : Type u) (σ : Type v) where
/-- A transition function from state to state labelled by the alphabet. -/
step : σ → α → σ
/-- Starting state. -/
start : σ
/-- Set of acceptance states. -/
accept : Set σ
namespace DFA
variable {α : Type u} {σ : Type v} (M : DFA α σ)
instance [Inhabited σ] : Inhabited (DFA α σ) :=
⟨DFA.mk (fun _ _ => default) default ∅⟩
/-- `M.evalFrom s x` evaluates `M` with input `x` starting from the state `s`. -/
def evalFrom (s : σ) : List α → σ :=
List.foldl M.step s
@[simp]
theorem evalFrom_nil (s : σ) : M.evalFrom s [] = s :=
rfl
@[simp]
theorem evalFrom_singleton (s : σ) (a : α) : M.evalFrom s [a] = M.step s a :=
rfl
@[simp]
theorem evalFrom_append_singleton (s : σ) (x : List α) (a : α) :
M.evalFrom s (x ++ [a]) = M.step (M.evalFrom s x) a := by
simp only [evalFrom, List.foldl_append, List.foldl_cons, List.foldl_nil]
/-- `M.eval x` evaluates `M` with input `x` starting from the state `M.start`. -/
def eval : List α → σ :=
M.evalFrom M.start
@[simp]
theorem eval_nil : M.eval [] = M.start :=
rfl
@[simp]
theorem eval_singleton (a : α) : M.eval [a] = M.step M.start a :=
rfl
@[simp]
theorem eval_append_singleton (x : List α) (a : α) : M.eval (x ++ [a]) = M.step (M.eval x) a :=
evalFrom_append_singleton _ _ _ _
theorem evalFrom_of_append (start : σ) (x y : List α) :
M.evalFrom start (x ++ y) = M.evalFrom (M.evalFrom start x) y :=
List.foldl_append
/--
`M.acceptsFrom s` is the language of `x` such that `M.evalFrom s x` is an accept state.
-/
def acceptsFrom (s : σ) : Language α := {x | M.evalFrom s x ∈ M.accept}
theorem mem_acceptsFrom {s : σ} {x : List α} :
x ∈ M.acceptsFrom s ↔ M.evalFrom s x ∈ M.accept := by rfl
/-- `M.accepts` is the language of `x` such that `M.eval x` is an accept state. -/
def accepts : Language α := M.acceptsFrom M.start
theorem mem_accepts {x : List α} : x ∈ M.accepts ↔ M.eval x ∈ M.accept := by rfl
theorem evalFrom_split [Fintype σ] {x : List α} {s t : σ} (hlen : Fintype.card σ ≤ x.length)
(hx : M.evalFrom s x = t) :
∃ q a b c,
x = a ++ b ++ c ∧
a.length + b.length ≤ Fintype.card σ ∧
b ≠ [] ∧ M.evalFrom s a = q ∧ M.evalFrom q b = q ∧ M.evalFrom q c = t := by
obtain ⟨n, m, hneq, heq⟩ :=
Fintype.exists_ne_map_eq_of_card_lt
(fun n : Fin (Fintype.card σ + 1) => M.evalFrom s (x.take n)) (by simp)
wlog hle : (n : ℕ) ≤ m generalizing n m
· exact this m n hneq.symm heq.symm (le_of_not_ge hle)
refine
⟨M.evalFrom s ((x.take m).take n), (x.take m).take n, (x.take m).drop n,
x.drop m, ?_, ?_, ?_, by rfl, ?_⟩
· rw [List.take_append_drop, List.take_append_drop]
· simp only [List.length_drop, List.length_take]
omega
· intro h
have hlen' := congr_arg List.length h
simp only [List.length_drop, List.length, List.length_take] at hlen'
omega
have hq : M.evalFrom (M.evalFrom s ((x.take m).take n)) ((x.take m).drop n) =
M.evalFrom s ((x.take m).take n) := by
rw [List.take_take, min_eq_left hle, ← evalFrom_of_append, heq, ← min_eq_left hle, ←
List.take_take, min_eq_left hle, List.take_append_drop]
use hq
rwa [← hq, ← evalFrom_of_append, ← evalFrom_of_append, ← List.append_assoc,
List.take_append_drop, List.take_append_drop]
theorem evalFrom_of_pow {x y : List α} {s : σ} (hx : M.evalFrom s x = s)
(hy : y ∈ ({x} : Language α)∗) : M.evalFrom s y = s := by
rw [Language.mem_kstar] at hy
rcases hy with ⟨S, rfl, hS⟩
induction S with
| nil => rfl
| cons a S ih =>
have ha := hS a List.mem_cons_self
rw [Set.mem_singleton_iff] at ha
rw [List.flatten_cons, evalFrom_of_append, ha, hx]
apply ih
intro z hz
exact hS z (List.mem_cons_of_mem a hz)
theorem pumping_lemma [Fintype σ] {x : List α} (hx : x ∈ M.accepts)
(hlen : Fintype.card σ ≤ List.length x) :
∃ a b c,
x = a ++ b ++ c ∧
a.length + b.length ≤ Fintype.card σ ∧ b ≠ [] ∧ {a} * {b}∗ * {c} ≤ M.accepts := by
obtain ⟨_, a, b, c, hx, hlen, hnil, rfl, hb, hc⟩ := M.evalFrom_split (s := M.start) hlen rfl
use a, b, c, hx, hlen, hnil
intro y hy
rw [Language.mem_mul] at hy
rcases hy with ⟨ab, hab, c', hc', rfl⟩
rw [Language.mem_mul] at hab
rcases hab with ⟨a', ha', b', hb', rfl⟩
rw [Set.mem_singleton_iff] at ha' hc'
substs ha' hc'
have h := M.evalFrom_of_pow hb hb'
rwa [mem_accepts, eval, evalFrom_of_append, evalFrom_of_append, h, hc]
section Maps
variable {α' σ' : Type*}
/--
`M.comap f` pulls back the alphabet of `M` along `f`. In other words, it applies `f` to the input
before passing it to `M`.
-/
@[simps]
def comap (f : α' → α) (M : DFA α σ) : DFA α' σ where
step s a := M.step s (f a)
start := M.start
accept := M.accept
@[simp]
theorem comap_id : M.comap id = M := rfl
@[simp]
theorem evalFrom_comap (f : α' → α) (s : σ) (x : List α') :
(M.comap f).evalFrom s x = M.evalFrom s (x.map f) := by
induction x using List.reverseRecOn with
| nil => simp
| append_singleton x a ih => simp [ih]
@[simp]
theorem eval_comap (f : α' → α) (x : List α') : (M.comap f).eval x = M.eval (x.map f) := by
simp [eval]
@[simp]
theorem accepts_comap (f : α' → α) : (M.comap f).accepts = List.map f ⁻¹' M.accepts := by
ext x
conv =>
rhs
rw [Set.mem_preimage, mem_accepts]
simp [mem_accepts]
/-- Lifts an equivalence on states to an equivalence on DFAs. -/
@[simps apply_step apply_start apply_accept]
def reindex (g : σ ≃ σ') : DFA α σ ≃ DFA α σ' where
toFun M := {
step := fun s a => g (M.step (g.symm s) a)
start := g M.start
accept := g.symm ⁻¹' M.accept
}
invFun M := {
step := fun s a => g.symm (M.step (g s) a)
start := g.symm M.start
accept := g ⁻¹' M.accept
}
left_inv M := by simp
right_inv M := by simp
@[simp]
theorem reindex_refl : reindex (Equiv.refl σ) M = M := rfl
@[simp]
theorem symm_reindex (g : σ ≃ σ') : (reindex (α := α) g).symm = reindex g.symm := rfl
@[simp]
theorem evalFrom_reindex (g : σ ≃ σ') (s : σ') (x : List α) :
(reindex g M).evalFrom s x = g (M.evalFrom (g.symm s) x) := by
induction x using List.reverseRecOn with
| nil => simp
| append_singleton x a ih => simp [ih]
@[simp]
theorem eval_reindex (g : σ ≃ σ') (x : List α) : (reindex g M).eval x = g (M.eval x) := by
simp [eval]
@[simp]
theorem accepts_reindex (g : σ ≃ σ') : (reindex g M).accepts = M.accepts := by
ext x
simp [mem_accepts]
theorem comap_reindex (f : α' → α) (g : σ ≃ σ') :
(reindex g M).comap f = reindex g (M.comap f) := by
simp [comap, reindex]
end Maps
end DFA
/-- A regular language is a language that is defined by a DFA with finite states. -/
def Language.IsRegular {T : Type u} (L : Language T) : Prop :=
∃ σ : Type, ∃ _ : Fintype σ, ∃ M : DFA T σ, M.accepts = L
/-- Lifts the state type `σ` inside `Language.IsRegular` to a different universe. -/
private lemma Language.isRegular_iff.helper.{v'} {T : Type u} {L : Language T}
(hL : ∃ σ : Type v, ∃ _ : Fintype σ, ∃ M : DFA T σ, M.accepts = L) :
∃ σ' : Type v', ∃ _ : Fintype σ', ∃ M : DFA T σ', M.accepts = L :=
have ⟨σ, _, M, hM⟩ := hL
have ⟨σ', ⟨f⟩⟩ := Small.equiv_small.{v', v} (α := σ)
⟨σ', Fintype.ofEquiv σ f, M.reindex f, hM ▸ DFA.accepts_reindex M f⟩
/--
A language is regular if and only if it is defined by a DFA with finite states.
This is more general than using the definition of `Language.IsRegular` directly, as the state type
`σ` is universe-polymorphic.
-/
theorem Language.isRegular_iff {T : Type u} {L : Language T} :
L.IsRegular ↔ ∃ σ : Type v, ∃ _ : Fintype σ, ∃ M : DFA T σ, M.accepts = L :=
⟨Language.isRegular_iff.helper, Language.isRegular_iff.helper⟩ |
.lake/packages/mathlib/Mathlib/Computability/EpsilonNFA.lean | import Mathlib.Computability.NFA
import Mathlib.Data.List.ReduceOption
/-!
# Epsilon Nondeterministic Finite Automata
This file contains the definition of an epsilon Nondeterministic Finite Automaton (`εNFA`), a state
machine which determines whether a string (implemented as a list over an arbitrary alphabet) is in a
regular set by evaluating the string over every possible path, also having access to ε-transitions,
which can be followed without reading a character.
Since this definition allows for automata with infinite states, a `Fintype` instance must be
supplied for true `εNFA`'s.
-/
open Set
open Computability
-- "ε_NFA"
universe u v
/-- An `εNFA` is a set of states (`σ`), a transition function from state to state labelled by the
alphabet (`step`), a starting state (`start`) and a set of acceptance states (`accept`).
Note the transition function sends a state to a `Set` of states and can make ε-transitions by
inputting `none`.
Since this definition allows for Automata with infinite states, a `Fintype` instance must be
supplied for true `εNFA`'s. -/
structure εNFA (α : Type u) (σ : Type v) where
/-- Transition function. The automaton is rendered non-deterministic by this transition function
returning `Set σ` (rather than `σ`), and ε-transitions are made possible by taking `Option α`
(rather than `α`). -/
step : σ → Option α → Set σ
/-- Starting states. -/
start : Set σ
/-- Set of acceptance states. -/
accept : Set σ
variable {α : Type u} {σ : Type v} (M : εNFA α σ) {S : Set σ} {s t u : σ} {a : α}
namespace εNFA
/-- The `εClosure` of a set is the set of states which can be reached by taking a finite string of
ε-transitions from an element of the set. -/
inductive εClosure (S : Set σ) : Set σ
| base : ∀ s ∈ S, εClosure S s
| step : ∀ (s), ∀ t ∈ M.step s none, εClosure S s → εClosure S t
@[simp]
theorem subset_εClosure (S : Set σ) : S ⊆ M.εClosure S :=
εClosure.base
@[simp]
theorem εClosure_empty : M.εClosure ∅ = ∅ :=
eq_empty_of_forall_notMem fun s hs ↦ by induction hs <;> assumption
@[simp]
theorem εClosure_univ : M.εClosure univ = univ :=
eq_univ_of_univ_subset <| subset_εClosure _ _
theorem mem_εClosure_iff_exists : s ∈ M.εClosure S ↔ ∃ t ∈ S, s ∈ M.εClosure {t} where
mp h := by
induction h with
| base => tauto
| step _ _ _ _ ih =>
obtain ⟨s, _, _⟩ := ih
use s
solve_by_elim [εClosure.step]
mpr := by
intro ⟨t, _, h⟩
induction h <;> subst_vars <;> solve_by_elim [εClosure.step]
/-- `M.stepSet S a` is the union of the ε-closure of `M.step s a` for all `s ∈ S`. -/
def stepSet (S : Set σ) (a : α) : Set σ :=
⋃ s ∈ S, M.εClosure (M.step s a)
variable {M}
@[simp]
theorem mem_stepSet_iff : s ∈ M.stepSet S a ↔ ∃ t ∈ S, s ∈ M.εClosure (M.step t a) := by
simp_rw [stepSet, mem_iUnion₂, exists_prop]
@[simp]
theorem stepSet_empty (a : α) : M.stepSet ∅ a = ∅ := by
simp_rw [stepSet, mem_empty_iff_false, iUnion_false, iUnion_empty]
variable (M)
/-- `M.evalFrom S x` computes all possible paths through `M` with input `x` starting at an element
of `S`. -/
def evalFrom (start : Set σ) : List α → Set σ :=
List.foldl M.stepSet (M.εClosure start)
@[simp]
theorem evalFrom_nil (S : Set σ) : M.evalFrom S [] = M.εClosure S :=
rfl
@[simp]
theorem evalFrom_singleton (S : Set σ) (a : α) : M.evalFrom S [a] = M.stepSet (M.εClosure S) a :=
rfl
@[simp]
theorem evalFrom_append_singleton (S : Set σ) (x : List α) (a : α) :
M.evalFrom S (x ++ [a]) = M.stepSet (M.evalFrom S x) a := by
rw [evalFrom, List.foldl_append, List.foldl_cons, List.foldl_nil]
@[simp]
theorem evalFrom_empty (x : List α) : M.evalFrom ∅ x = ∅ := by
induction x using List.reverseRecOn with
| nil => rw [evalFrom_nil, εClosure_empty]
| append_singleton x a ih => rw [evalFrom_append_singleton, ih, stepSet_empty]
theorem mem_evalFrom_iff_exists {s : σ} {S : Set σ} {x : List α} :
s ∈ M.evalFrom S x ↔ ∃ t ∈ S, s ∈ M.evalFrom {t} x := by
induction x using List.reverseRecOn generalizing s with
| nil => apply mem_εClosure_iff_exists
| append_singleton _ _ ih =>
simp_rw [evalFrom_append_singleton, mem_stepSet_iff, ih]
tauto
/-- `M.eval x` computes all possible paths through `M` with input `x` starting at an element of
`M.start`. -/
def eval :=
M.evalFrom M.start
@[simp]
theorem eval_nil : M.eval [] = M.εClosure M.start :=
rfl
@[simp]
theorem eval_singleton (a : α) : M.eval [a] = M.stepSet (M.εClosure M.start) a :=
rfl
@[simp]
theorem eval_append_singleton (x : List α) (a : α) : M.eval (x ++ [a]) = M.stepSet (M.eval x) a :=
evalFrom_append_singleton _ _ _ _
/-- `M.accepts` is the language of `x` such that there is an accept state in `M.eval x`. -/
def accepts : Language α :=
{ x | ∃ S ∈ M.accept, S ∈ M.eval x }
/-- `M.IsPath` represents a traversal in `M` from a start state to an end state by following a list
of transitions in order. -/
@[mk_iff]
inductive IsPath : σ → σ → List (Option α) → Prop
| nil (s : σ) : IsPath s s []
| cons (t s u : σ) (a : Option α) (x : List (Option α)) :
t ∈ M.step s a → IsPath t u x → IsPath s u (a :: x)
@[simp]
theorem isPath_nil : M.IsPath s t [] ↔ s = t := by
rw [isPath_iff]
simp [eq_comm]
alias ⟨IsPath.eq_of_nil, _⟩ := isPath_nil
@[simp]
theorem isPath_singleton {a : Option α} : M.IsPath s t [a] ↔ t ∈ M.step s a where
mp := by
rintro (_ | ⟨_, _, _, _, _, _, ⟨⟩⟩)
assumption
mpr := by tauto
alias ⟨_, IsPath.singleton⟩ := isPath_singleton
theorem isPath_append {x y : List (Option α)} :
M.IsPath s u (x ++ y) ↔ ∃ t, M.IsPath s t x ∧ M.IsPath t u y where
mp := by
induction x generalizing s with
| nil =>
rw [List.nil_append]
tauto
| cons x a ih =>
rintro (_ | ⟨t, _, _, _, _, _, h⟩)
apply ih at h
tauto
mpr := by
intro ⟨t, hx, _⟩
induction x generalizing s <;> cases hx <;> tauto
theorem mem_εClosure_iff_exists_path {s₁ s₂ : σ} :
s₂ ∈ M.εClosure {s₁} ↔ ∃ n, M.IsPath s₁ s₂ (.replicate n none) where
mp h := by
induction h with
| base t =>
use 0
subst t
apply IsPath.nil
| step _ _ _ _ ih =>
obtain ⟨n, _⟩ := ih
use n + 1
rw [List.replicate_add, isPath_append]
tauto
mpr := by
intro ⟨n, h⟩
induction n generalizing s₂
· rw [List.replicate_zero] at h
apply IsPath.eq_of_nil at h
solve_by_elim
· simp_rw [List.replicate_add, isPath_append, List.replicate_one, isPath_singleton] at h
obtain ⟨t, _, _⟩ := h
solve_by_elim [εClosure.step]
theorem mem_evalFrom_iff_exists_path {s₁ s₂ : σ} {x : List α} :
s₂ ∈ M.evalFrom {s₁} x ↔ ∃ x', x'.reduceOption = x ∧ M.IsPath s₁ s₂ x' := by
induction x using List.reverseRecOn generalizing s₂ with
| nil =>
rw [evalFrom_nil, mem_εClosure_iff_exists_path]
constructor
· intro ⟨n, _⟩
use List.replicate n none
rw [List.reduceOption_replicate_none]
trivial
· simp_rw [List.reduceOption_eq_nil_iff]
intro ⟨_, ⟨n, rfl⟩, h⟩
exact ⟨n, h⟩
| append_singleton x a ih =>
rw [evalFrom_append_singleton, mem_stepSet_iff]
constructor
· intro ⟨t, ht, h⟩
obtain ⟨x', _, _⟩ := ih.mp ht
rw [mem_εClosure_iff_exists] at h
simp_rw [mem_εClosure_iff_exists_path] at h
obtain ⟨u, _, n, _⟩ := h
use x' ++ some a :: List.replicate n none
rw [List.reduceOption_append, List.reduceOption_cons_of_some,
List.reduceOption_replicate_none, isPath_append]
tauto
· simp_rw [← List.concat_eq_append, List.reduceOption_eq_concat_iff,
List.reduceOption_eq_nil_iff]
intro ⟨_, ⟨x', _, rfl, _, n, rfl⟩, h⟩
rw [isPath_append] at h
obtain ⟨t, _, _ | u⟩ := h
use t
rw [mem_εClosure_iff_exists, ih]
simp_rw [mem_εClosure_iff_exists_path]
tauto
theorem mem_accepts_iff_exists_path {x : List α} :
x ∈ M.accepts ↔
∃ s₁ s₂ x', s₁ ∈ M.start ∧ s₂ ∈ M.accept ∧ x'.reduceOption = x ∧ M.IsPath s₁ s₂ x' where
mp := by
intro ⟨s₂, _, h⟩
rw [eval, mem_evalFrom_iff_exists] at h
obtain ⟨s₁, _, h⟩ := h
rw [mem_evalFrom_iff_exists_path] at h
tauto
mpr := by
intro ⟨s₁, s₂, x', hs₁, hs₂, h⟩
have := M.mem_evalFrom_iff_exists.mpr ⟨_, hs₁, M.mem_evalFrom_iff_exists_path.mpr ⟨_, h⟩⟩
exact ⟨s₂, hs₂, this⟩
/-! ### Conversions between `εNFA` and `NFA` -/
/-- `M.toNFA` is an `NFA` constructed from an `εNFA` `M`. -/
def toNFA : NFA α σ where
step S a := M.εClosure (M.step S a)
start := M.εClosure M.start
accept := M.accept
@[simp]
theorem toNFA_evalFrom_match (start : Set σ) :
M.toNFA.evalFrom (M.εClosure start) = M.evalFrom start :=
rfl
@[simp]
theorem toNFA_correct : M.toNFA.accepts = M.accepts :=
rfl
theorem pumping_lemma [Fintype σ] {x : List α} (hx : x ∈ M.accepts)
(hlen : Fintype.card (Set σ) ≤ List.length x) :
∃ a b c, x = a ++ b ++ c ∧
a.length + b.length ≤ Fintype.card (Set σ) ∧ b ≠ [] ∧ {a} * {b}∗ * {c} ≤ M.accepts :=
M.toNFA.pumping_lemma hx hlen
end εNFA
namespace NFA
/-- `M.toεNFA` is an `εNFA` constructed from an `NFA` `M` by using the same start and accept
states and transition functions. -/
def toεNFA (M : NFA α σ) : εNFA α σ where
step s a := a.casesOn' ∅ fun a ↦ M.step s a
start := M.start
accept := M.accept
@[simp]
theorem toεNFA_εClosure (M : NFA α σ) (S : Set σ) : M.toεNFA.εClosure S = S := by
ext a
refine ⟨?_, εNFA.εClosure.base _⟩
rintro (⟨_, h⟩ | ⟨_, _, h, _⟩)
· exact h
· cases h
@[simp]
theorem toεNFA_evalFrom_match (M : NFA α σ) (start : Set σ) :
M.toεNFA.evalFrom start = M.evalFrom start := by
rw [evalFrom, εNFA.evalFrom, toεNFA_εClosure]
suffices εNFA.stepSet (toεNFA M) = stepSet M by rw [this]
ext S s
simp only [stepSet, εNFA.stepSet, exists_prop, Set.mem_iUnion]
apply exists_congr
simp only [and_congr_right_iff]
intro _ _
rw [M.toεNFA_εClosure]
rfl
@[simp]
theorem toεNFA_correct (M : NFA α σ) : M.toεNFA.accepts = M.accepts := by
rw [εNFA.accepts, εNFA.eval, toεNFA_evalFrom_match]
rfl
end NFA
/-! ### Regex-like operations -/
namespace εNFA
instance : Zero (εNFA α σ) :=
⟨⟨fun _ _ ↦ ∅, ∅, ∅⟩⟩
instance : One (εNFA α σ) :=
⟨⟨fun _ _ ↦ ∅, univ, univ⟩⟩
instance : Inhabited (εNFA α σ) :=
⟨0⟩
@[simp]
theorem step_zero (s a) : (0 : εNFA α σ).step s a = ∅ :=
rfl
@[simp]
theorem step_one (s a) : (1 : εNFA α σ).step s a = ∅ :=
rfl
@[simp]
theorem start_zero : (0 : εNFA α σ).start = ∅ :=
rfl
@[simp]
theorem start_one : (1 : εNFA α σ).start = univ :=
rfl
@[simp]
theorem accept_zero : (0 : εNFA α σ).accept = ∅ :=
rfl
@[simp]
theorem accept_one : (1 : εNFA α σ).accept = univ :=
rfl
end εNFA |
.lake/packages/mathlib/Mathlib/Computability/TMToPartrec.lean | import Mathlib.Computability.Halting
import Mathlib.Computability.TuringMachine
import Mathlib.Data.Num.Lemmas
import Mathlib.Tactic.DeriveFintype
import Mathlib.Computability.TMConfig
/-!
# Modelling partial recursive functions using Turing machines
The files `TMConfig` and `TMToPartrec` define a simplified basis for partial recursive functions,
and a `Turing.TM2` model
Turing machine for evaluating these functions. This amounts to a constructive proof that every
`Partrec` function can be evaluated by a Turing machine.
## Main definitions
* `PartrecToTM2.tr`: A TM2 Turing machine which can evaluate `code` programs
-/
open List (Vector)
open Function (update)
open Relation
namespace Turing
/-!
## Simulating sequentialized partial recursive functions in TM2
At this point we have a sequential model of partial recursive functions: the `Cfg` type and
`step : Cfg → Option Cfg` function from `TMConfig.lean`. The key feature of this model is that
it does a finite amount of computation (in fact, an amount which is statically bounded by the size
of the program) between each step, and no individual step can diverge (unlike the compositional
semantics, where every sub-part of the computation is potentially divergent). So we can utilize the
same techniques as in the other TM simulations in `Computability.TuringMachine` to prove that
each step corresponds to a finite number of steps in a lower level model. (We don't prove it here,
but in anticipation of the complexity class P, the simulation is actually polynomial-time as well.)
The target model is `Turing.TM2`, which has a fixed finite set of stacks, a bit of local storage,
with programs selected from a potentially infinite (but finitely accessible) set of program
positions, or labels `Λ`, each of which executes a finite sequence of basic stack commands.
For this program we will need four stacks, each on an alphabet `Γ'` like so:
inductive Γ' | consₗ | cons | bit0 | bit1
We represent a number as a bit sequence, lists of numbers by putting `cons` after each element, and
lists of lists of natural numbers by putting `consₗ` after each list. For example:
0 ~> []
1 ~> [bit1]
6 ~> [bit0, bit1, bit1]
[1, 2] ~> [bit1, cons, bit0, bit1, cons]
[[], [1, 2]] ~> [consₗ, bit1, cons, bit0, bit1, cons, consₗ]
The four stacks are `main`, `rev`, `aux`, `stack`. In normal mode, `main` contains the input to the
current program (a `List ℕ`) and `stack` contains data (a `List (List ℕ)`) associated to the
current continuation, and in `ret` mode `main` contains the value that is being passed to the
continuation and `stack` contains the data for the continuation. The `rev` and `aux` stacks are
usually empty; `rev` is used to store reversed data when e.g. moving a value from one stack to
another, while `aux` is used as a temporary for a `main`/`stack` swap that happens during `cons₁`
evaluation.
The only local store we need is `Option Γ'`, which stores the result of the last pop
operation. (Most of our working data are natural numbers, which are too large to fit in the local
store.)
The continuations from the previous section are data-carrying, containing all the values that have
been computed and are awaiting other arguments. In order to have only a finite number of
continuations appear in the program so that they can be used in machine states, we separate the
data part (anything with type `List ℕ`) from the `Cont` type, producing a `Cont'` type that lacks
this information. The data is kept on the `stack` stack.
Because we want to have subroutines for e.g. moving an entire stack to another place, we use an
infinite inductive type `Λ'` so that we can execute a program and then return to do something else
without having to define too many different kinds of intermediate states. (We must nevertheless
prove that only finitely many labels are accessible.) The labels are:
* `move p k₁ k₂ q`: move elements from stack `k₁` to `k₂` while `p` holds of the value being moved.
The last element, that fails `p`, is placed in neither stack but left in the local store.
At the end of the operation, `k₂` will have the elements of `k₁` in reverse order. Then do `q`.
* `clear p k q`: delete elements from stack `k` until `p` is true. Like `move`, the last element is
left in the local storage. Then do `q`.
* `copy q`: Move all elements from `rev` to both `main` and `stack` (in reverse order),
then do `q`. That is, it takes `(a, b, c, d)` to `(b.reverse ++ a, [], c, b.reverse ++ d)`.
* `push k f q`: push `f s`, where `s` is the local store, to stack `k`, then do `q`. This is a
duplicate of the `push` instruction that is part of the TM2 model, but by having a subroutine
just for this purpose we can build up programs to execute inside a `goto` statement, where we
have the flexibility to be general recursive.
* `read (f : Option Γ' → Λ')`: go to state `f s` where `s` is the local store. Again this is only
here for convenience.
* `succ q`: perform a successor operation. Assuming `[n]` is encoded on `main` before,
`[n+1]` will be on main after. This implements successor for binary natural numbers.
* `pred q₁ q₂`: perform a predecessor operation or `case` statement. If `[]` is encoded on
`main` before, then we transition to `q₁` with `[]` on main; if `(0 :: v)` is on `main` before
then `v` will be on `main` after and we transition to `q₁`; and if `(n+1 :: v)` is on `main`
before then `n :: v` will be on `main` after and we transition to `q₂`.
* `ret k`: call continuation `k`. Each continuation has its own interpretation of the data in
`stack` and sets up the data for the next continuation.
* `ret (cons₁ fs k)`: `v :: KData` on `stack` and `ns` on `main`, and the next step expects
`v` on `main` and `ns :: KData` on `stack`. So we have to do a little dance here with six
reverse-moves using the `aux` stack to perform a three-point swap, each of which involves two
reversals.
* `ret (cons₂ k)`: `ns :: KData` is on `stack` and `v` is on `main`, and we have to put
`ns.headI :: v` on `main` and `KData` on `stack`. This is done using the `head` subroutine.
* `ret (fix f k)`: This stores no data, so we just check if `main` starts with `0` and
if so, remove it and call `k`, otherwise `clear` the first value and call `f`.
* `ret halt`: the stack is empty, and `main` has the output. Do nothing and halt.
In addition to these basic states, we define some additional subroutines that are used in the
above:
* `push'`, `peek'`, `pop'` are special versions of the builtins that use the local store to supply
inputs and outputs.
* `unrev`: special case `move false rev main` to move everything from `rev` back to `main`. Used as
a cleanup operation in several functions.
* `moveExcl p k₁ k₂ q`: same as `move` but pushes the last value read back onto the source stack.
* `move₂ p k₁ k₂ q`: double `move`, so that the result comes out in the right order at the target
stack. Implemented as `moveExcl p k rev; move false rev k₂`. Assumes that neither `k₁` nor `k₂`
is `rev` and `rev` is initially empty.
* `head k q`: get the first natural number from stack `k` and reverse-move it to `rev`, then clear
the rest of the list at `k` and then `unrev` to reverse-move the head value to `main`. This is
used with `k = main` to implement regular `head`, i.e. if `v` is on `main` before then `[v.headI]`
will be on `main` after; and also with `k = stack` for the `cons` operation, which has `v` on
`main` and `ns :: KData` on `stack`, and results in `KData` on `stack` and `ns.headI :: v` on
`main`.
* `trNormal` is the main entry point, defining states that perform a given `code` computation.
It mostly just dispatches to functions written above.
The main theorem of this section is `tr_eval`, which asserts that for each that for each code `c`,
the state `init c v` steps to `halt v'` in finitely many steps if and only if
`Code.eval c v = some v'`.
-/
namespace PartrecToTM2
section
open ToPartrec
/-- The alphabet for the stacks in the program. `bit0` and `bit1` are used to represent `ℕ` values
as lists of binary digits, `cons` is used to separate `List ℕ` values, and `consₗ` is used to
separate `List (List ℕ)` values. See the section documentation. -/
inductive Γ'
| consₗ
| cons
| bit0
| bit1
deriving DecidableEq, Inhabited, Fintype
-- A proof below relies on the value of that `deriving Inhabited` picks here.
@[simp] theorem default_Γ' : (default : Γ') = .consₗ := rfl
/-- The four stacks used by the program. `main` is used to store the input value in `trNormal`
mode and the output value in `Λ'.ret` mode, while `stack` is used to keep all the data for the
continuations. `rev` is used to store reversed lists when transferring values between stacks, and
`aux` is only used once in `cons₁`. See the section documentation. -/
inductive K'
| main
| rev
| aux
| stack
deriving DecidableEq, Inhabited
open K'
/-- Continuations as in `ToPartrec.Cont` but with the data removed. This is done because we want
the set of all continuations in the program to be finite (so that it can ultimately be encoded into
the finite state machine of a Turing machine), but a continuation can handle a potentially infinite
number of data values during execution. -/
inductive Cont'
| halt
| cons₁ : Code → Cont' → Cont'
| cons₂ : Cont' → Cont'
| comp : Code → Cont' → Cont'
| fix : Code → Cont' → Cont'
deriving DecidableEq, Inhabited
/-- The set of program positions. We make extensive use of inductive types here to let us describe
"subroutines"; for example `clear p k q` is a program that clears stack `k`, then does `q` where
`q` is another label. In order to prevent this from resulting in an infinite number of distinct
accessible states, we are careful to be non-recursive (although loops are okay). See the section
documentation for a description of all the programs. -/
inductive Λ'
| move (p : Γ' → Bool) (k₁ k₂ : K') (q : Λ')
| clear (p : Γ' → Bool) (k : K') (q : Λ')
| copy (q : Λ')
| push (k : K') (s : Option Γ' → Option Γ') (q : Λ')
| read (f : Option Γ' → Λ')
| succ (q : Λ')
| pred (q₁ q₂ : Λ')
| ret (k : Cont')
compile_inductive% Code
compile_inductive% Cont'
compile_inductive% K'
compile_inductive% Λ'
instance Λ'.instInhabited : Inhabited Λ' :=
⟨Λ'.ret Cont'.halt⟩
instance Λ'.instDecidableEq : DecidableEq Λ' := fun a b => by
induction a generalizing b <;> cases b <;> first
| apply Decidable.isFalse; rintro ⟨⟨⟩⟩; done
| exact decidable_of_iff' _ (by simp [funext_iff]; rfl)
/-- The type of TM2 statements used by this machine. -/
def Stmt' :=
TM2.Stmt (fun _ : K' => Γ') Λ' (Option Γ') deriving Inhabited
/-- The type of TM2 configurations used by this machine. -/
def Cfg' :=
TM2.Cfg (fun _ : K' => Γ') Λ' (Option Γ') deriving Inhabited
open TM2.Stmt
/-- A predicate that detects the end of a natural number, either `Γ'.cons` or `Γ'.consₗ` (or
implicitly the end of the list), for use in predicate-taking functions like `move` and `clear`. -/
@[simp]
def natEnd : Γ' → Bool
| Γ'.consₗ => true
| Γ'.cons => true
| _ => false
attribute [nolint simpNF] natEnd.eq_3
/-- Pop a value from the stack and place the result in local store. -/
@[simp]
def pop' (k : K') : Stmt' → Stmt' :=
pop k fun _ v => v
/-- Peek a value from the stack and place the result in local store. -/
@[simp]
def peek' (k : K') : Stmt' → Stmt' :=
peek k fun _ v => v
/-- Push the value in the local store to the given stack. -/
@[simp]
def push' (k : K') : Stmt' → Stmt' :=
push k fun x => x.iget
/-- Move everything from the `rev` stack to the `main` stack (reversed). -/
def unrev :=
Λ'.move (fun _ => false) rev main
/-- Move elements from `k₁` to `k₂` while `p` holds, with the last element being left on `k₁`. -/
def moveExcl (p k₁ k₂ q) :=
Λ'.move p k₁ k₂ <| Λ'.push k₁ id q
/-- Move elements from `k₁` to `k₂` without reversion, by performing a double move via the `rev`
stack. -/
def move₂ (p k₁ k₂ q) :=
moveExcl p k₁ rev <| Λ'.move (fun _ => false) rev k₂ q
/-- Assuming `trList v` is on the front of stack `k`, remove it, and push `v.headI` onto `main`.
See the section documentation. -/
def head (k : K') (q : Λ') : Λ' :=
Λ'.move natEnd k rev <|
(Λ'.push rev fun _ => some Γ'.cons) <|
Λ'.read fun s =>
(if s = some Γ'.consₗ then id else Λ'.clear (fun x => x = Γ'.consₗ) k) <| unrev q
/-- The program that evaluates code `c` with continuation `k`. This expects an initial state where
`trList v` is on `main`, `trContStack k` is on `stack`, and `aux` and `rev` are empty.
See the section documentation for details. -/
@[simp]
def trNormal : Code → Cont' → Λ'
| Code.zero', k => (Λ'.push main fun _ => some Γ'.cons) <| Λ'.ret k
| Code.succ, k => head main <| Λ'.succ <| Λ'.ret k
| Code.tail, k => Λ'.clear natEnd main <| Λ'.ret k
| Code.cons f fs, k =>
(Λ'.push stack fun _ => some Γ'.consₗ) <|
Λ'.move (fun _ => false) main rev <| Λ'.copy <| trNormal f (Cont'.cons₁ fs k)
| Code.comp f g, k => trNormal g (Cont'.comp f k)
| Code.case f g, k => Λ'.pred (trNormal f k) (trNormal g k)
| Code.fix f, k => trNormal f (Cont'.fix f k)
/-- The main program. See the section documentation for details. -/
def tr : Λ' → Stmt'
| Λ'.move p k₁ k₂ q =>
pop' k₁ <|
branch (fun s => s.elim true p) (goto fun _ => q)
(push' k₂ <| goto fun _ => Λ'.move p k₁ k₂ q)
| Λ'.push k f q =>
branch (fun s => (f s).isSome) ((push k fun s => (f s).iget) <| goto fun _ => q)
(goto fun _ => q)
| Λ'.read q => goto q
| Λ'.clear p k q =>
pop' k <| branch (fun s => s.elim true p) (goto fun _ => q) (goto fun _ => Λ'.clear p k q)
| Λ'.copy q =>
pop' rev <|
branch Option.isSome (push' main <| push' stack <| goto fun _ => Λ'.copy q) (goto fun _ => q)
| Λ'.succ q =>
pop' main <|
branch (fun s => s = some Γ'.bit1) ((push rev fun _ => Γ'.bit0) <| goto fun _ => Λ'.succ q) <|
branch (fun s => s = some Γ'.cons)
((push main fun _ => Γ'.cons) <| (push main fun _ => Γ'.bit1) <| goto fun _ => unrev q)
((push main fun _ => Γ'.bit1) <| goto fun _ => unrev q)
| Λ'.pred q₁ q₂ =>
pop' main <|
branch (fun s => s = some Γ'.bit0)
((push rev fun _ => Γ'.bit1) <| goto fun _ => Λ'.pred q₁ q₂) <|
branch (fun s => natEnd s.iget) (goto fun _ => q₁)
(peek' main <|
branch (fun s => natEnd s.iget) (goto fun _ => unrev q₂)
((push rev fun _ => Γ'.bit0) <| goto fun _ => unrev q₂))
| Λ'.ret (Cont'.cons₁ fs k) =>
goto fun _ =>
move₂ (fun _ => false) main aux <|
move₂ (fun s => s = Γ'.consₗ) stack main <|
move₂ (fun _ => false) aux stack <| trNormal fs (Cont'.cons₂ k)
| Λ'.ret (Cont'.cons₂ k) => goto fun _ => head stack <| Λ'.ret k
| Λ'.ret (Cont'.comp f k) => goto fun _ => trNormal f k
| Λ'.ret (Cont'.fix f k) =>
pop' main <|
goto fun s =>
cond (natEnd s.iget) (Λ'.ret k) <| Λ'.clear natEnd main <| trNormal f (Cont'.fix f k)
| Λ'.ret Cont'.halt => (load fun _ => none) <| halt
@[simp]
theorem tr_move (p k₁ k₂ q) : tr (Λ'.move p k₁ k₂ q) =
pop' k₁ (branch (fun s => s.elim true p) (goto fun _ => q)
(push' k₂ <| goto fun _ => Λ'.move p k₁ k₂ q)) := rfl
@[simp]
theorem tr_push (k f q) : tr (Λ'.push k f q) = branch (fun s => (f s).isSome)
((push k fun s => (f s).iget) <| goto fun _ => q) (goto fun _ => q) := rfl
@[simp]
theorem tr_read (q) : tr (Λ'.read q) = goto q := rfl
@[simp]
theorem tr_clear (p k q) : tr (Λ'.clear p k q) = pop' k (branch
(fun s => s.elim true p) (goto fun _ => q) (goto fun _ => Λ'.clear p k q)) := rfl
@[simp]
theorem tr_copy (q) : tr (Λ'.copy q) = pop' rev (branch Option.isSome
(push' main <| push' stack <| goto fun _ => Λ'.copy q) (goto fun _ => q)) := rfl
@[simp]
theorem tr_succ (q) : tr (Λ'.succ q) = pop' main (branch (fun s => s = some Γ'.bit1)
((push rev fun _ => Γ'.bit0) <| goto fun _ => Λ'.succ q) <|
branch (fun s => s = some Γ'.cons)
((push main fun _ => Γ'.cons) <| (push main fun _ => Γ'.bit1) <| goto fun _ => unrev q)
((push main fun _ => Γ'.bit1) <| goto fun _ => unrev q)) := rfl
@[simp]
theorem tr_pred (q₁ q₂) : tr (Λ'.pred q₁ q₂) = pop' main (branch (fun s => s = some Γ'.bit0)
((push rev fun _ => Γ'.bit1) <| goto fun _ => Λ'.pred q₁ q₂) <|
branch (fun s => natEnd s.iget) (goto fun _ => q₁)
(peek' main <|
branch (fun s => natEnd s.iget) (goto fun _ => unrev q₂)
((push rev fun _ => Γ'.bit0) <| goto fun _ => unrev q₂))) := rfl
@[simp]
theorem tr_ret_cons₁ (fs k) : tr (Λ'.ret (Cont'.cons₁ fs k)) = goto fun _ =>
move₂ (fun _ => false) main aux <|
move₂ (fun s => s = Γ'.consₗ) stack main <|
move₂ (fun _ => false) aux stack <| trNormal fs (Cont'.cons₂ k) := rfl
@[simp]
theorem tr_ret_cons₂ (k) : tr (Λ'.ret (Cont'.cons₂ k)) =
goto fun _ => head stack <| Λ'.ret k := rfl
@[simp]
theorem tr_ret_comp (f k) : tr (Λ'.ret (Cont'.comp f k)) = goto fun _ => trNormal f k := rfl
@[simp]
theorem tr_ret_fix (f k) : tr (Λ'.ret (Cont'.fix f k)) = pop' main (goto fun s =>
cond (natEnd s.iget) (Λ'.ret k) <| Λ'.clear natEnd main <| trNormal f (Cont'.fix f k)) := rfl
@[simp]
theorem tr_ret_halt : tr (Λ'.ret Cont'.halt) = (load fun _ => none) halt := rfl
/-- Translating a `Cont` continuation to a `Cont'` continuation simply entails dropping all the
data. This data is instead encoded in `trContStack` in the configuration. -/
def trCont : Cont → Cont'
| Cont.halt => Cont'.halt
| Cont.cons₁ c _ k => Cont'.cons₁ c (trCont k)
| Cont.cons₂ _ k => Cont'.cons₂ (trCont k)
| Cont.comp c k => Cont'.comp c (trCont k)
| Cont.fix c k => Cont'.fix c (trCont k)
/-- We use `PosNum` to define the translation of binary natural numbers. A natural number is
represented as a little-endian list of `bit0` and `bit1` elements:
1 = [bit1]
2 = [bit0, bit1]
3 = [bit1, bit1]
4 = [bit0, bit0, bit1]
In particular, this representation guarantees no trailing `bit0`'s at the end of the list. -/
def trPosNum : PosNum → List Γ'
| PosNum.one => [Γ'.bit1]
| PosNum.bit0 n => Γ'.bit0 :: trPosNum n
| PosNum.bit1 n => Γ'.bit1 :: trPosNum n
/-- We use `Num` to define the translation of binary natural numbers. Positive numbers are
translated using `trPosNum`, and `trNum 0 = []`. So there are never any trailing `bit0`'s in
a translated `Num`.
0 = []
1 = [bit1]
2 = [bit0, bit1]
3 = [bit1, bit1]
4 = [bit0, bit0, bit1]
-/
def trNum : Num → List Γ'
| Num.zero => []
| Num.pos n => trPosNum n
/-- Because we use binary encoding, we define `trNat` in terms of `trNum`, using `Num`, which are
binary natural numbers. (We could also use `Nat.binaryRecOn`, but `Num` and `PosNum` make for
easy inductions.) -/
def trNat (n : ℕ) : List Γ' :=
trNum n
@[simp]
theorem trNat_zero : trNat 0 = [] := by rw [trNat, Nat.cast_zero]; rfl
theorem trNat_default : trNat default = [] :=
trNat_zero
/-- Lists are translated with a `cons` after each encoded number.
For example:
[] = []
[0] = [cons]
[1] = [bit1, cons]
[6, 0] = [bit0, bit1, bit1, cons, cons]
-/
@[simp]
def trList : List ℕ → List Γ'
| [] => []
| n::ns => trNat n ++ Γ'.cons :: trList ns
/-- Lists of lists are translated with a `consₗ` after each encoded list.
For example:
[] = []
[[]] = [consₗ]
[[], []] = [consₗ, consₗ]
[[0]] = [cons, consₗ]
[[1, 2], [0]] = [bit1, cons, bit0, bit1, cons, consₗ, cons, consₗ]
-/
@[simp]
def trLList : List (List ℕ) → List Γ'
| [] => []
| l::ls => trList l ++ Γ'.consₗ :: trLList ls
/-- The data part of a continuation is a list of lists, which is encoded on the `stack` stack
using `trLList`. -/
@[simp]
def contStack : Cont → List (List ℕ)
| Cont.halt => []
| Cont.cons₁ _ ns k => ns :: contStack k
| Cont.cons₂ ns k => ns :: contStack k
| Cont.comp _ k => contStack k
| Cont.fix _ k => contStack k
/-- The data part of a continuation is a list of lists, which is encoded on the `stack` stack
using `trLList`. -/
def trContStack (k : Cont) :=
trLList (contStack k)
/-- This is the nondependent eliminator for `K'`, but we use it specifically here in order to
represent the stack data as four lists rather than as a function `K' → List Γ'`, because this makes
rewrites easier. The theorems `K'.elim_update_main` et. al. show how such a function is updated
after an `update` to one of the components. -/
def K'.elim (a b c d : List Γ') : K' → List Γ'
| K'.main => a
| K'.rev => b
| K'.aux => c
| K'.stack => d
-- The equation lemma of `elim` simplifies to `match` structures.
theorem K'.elim_main (a b c d) : K'.elim a b c d K'.main = a := rfl
theorem K'.elim_rev (a b c d) : K'.elim a b c d K'.rev = b := rfl
theorem K'.elim_aux (a b c d) : K'.elim a b c d K'.aux = c := rfl
theorem K'.elim_stack (a b c d) : K'.elim a b c d K'.stack = d := rfl
attribute [simp] K'.elim
@[simp]
theorem K'.elim_update_main {a b c d a'} : update (K'.elim a b c d) main a' = K'.elim a' b c d := by
funext x; cases x <;> rfl
@[simp]
theorem K'.elim_update_rev {a b c d b'} : update (K'.elim a b c d) rev b' = K'.elim a b' c d := by
funext x; cases x <;> rfl
@[simp]
theorem K'.elim_update_aux {a b c d c'} : update (K'.elim a b c d) aux c' = K'.elim a b c' d := by
funext x; cases x <;> rfl
@[simp]
theorem K'.elim_update_stack {a b c d d'} :
update (K'.elim a b c d) stack d' = K'.elim a b c d' := by funext x; cases x <;> rfl
/-- The halting state corresponding to a `List ℕ` output value. -/
def halt (v : List ℕ) : Cfg' :=
⟨none, none, K'.elim (trList v) [] [] []⟩
/-- The `Cfg` states map to `Cfg'` states almost one to one, except that in normal operation the
local store contains an arbitrary garbage value. To make the final theorem cleaner we explicitly
clear it in the halt state so that there is exactly one configuration corresponding to output `v`.
-/
def TrCfg : Cfg → Cfg' → Prop
| Cfg.ret k v, c' =>
∃ s, c' = ⟨some (Λ'.ret (trCont k)), s, K'.elim (trList v) [] [] (trContStack k)⟩
| Cfg.halt v, c' => c' = halt v
/-- This could be a general list definition, but it is also somewhat specialized to this
application. `splitAtPred p L` will search `L` for the first element satisfying `p`.
If it is found, say `L = l₁ ++ a :: l₂` where `a` satisfies `p` but `l₁` does not, then it returns
`(l₁, some a, l₂)`. Otherwise, if there is no such element, it returns `(L, none, [])`. -/
def splitAtPred {α} (p : α → Bool) : List α → List α × Option α × List α
| [] => ([], none, [])
| a :: as =>
cond (p a) ([], some a, as) <|
let ⟨l₁, o, l₂⟩ := splitAtPred p as
⟨a::l₁, o, l₂⟩
theorem splitAtPred_eq {α} (p : α → Bool) :
∀ L l₁ o l₂,
(∀ x ∈ l₁, p x = false) →
Option.elim' (L = l₁ ∧ l₂ = []) (fun a => p a = true ∧ L = l₁ ++ a::l₂) o →
splitAtPred p L = (l₁, o, l₂)
| [], _, none, _, _, ⟨rfl, rfl⟩ => rfl
| [], l₁, some o, l₂, _, ⟨_, h₃⟩ => by simp at h₃
| a :: L, l₁, o, l₂, h₁, h₂ => by
rw [splitAtPred]
have IH := splitAtPred_eq p L
rcases o with - | o
· rcases l₁ with - | ⟨a', l₁⟩ <;> rcases h₂ with ⟨⟨⟩, rfl⟩
rw [h₁ a (List.Mem.head _), cond, IH L none [] _ ⟨rfl, rfl⟩]
exact fun x h => h₁ x (List.Mem.tail _ h)
· rcases l₁ with - | ⟨a', l₁⟩ <;> rcases h₂ with ⟨h₂, ⟨⟩⟩
· rw [h₂, cond]
rw [h₁ a (List.Mem.head _), cond, IH l₁ (some o) l₂ _ ⟨h₂, _⟩] <;> try rfl
exact fun x h => h₁ x (List.Mem.tail _ h)
theorem splitAtPred_false {α} (L : List α) : splitAtPred (fun _ => false) L = (L, none, []) :=
splitAtPred_eq _ _ _ _ _ (fun _ _ => rfl) ⟨rfl, rfl⟩
theorem move_ok {p k₁ k₂ q s L₁ o L₂} {S : K' → List Γ'} (h₁ : k₁ ≠ k₂)
(e : splitAtPred p (S k₁) = (L₁, o, L₂)) :
Reaches₁ (TM2.step tr) ⟨some (Λ'.move p k₁ k₂ q), s, S⟩
⟨some q, o, update (update S k₁ L₂) k₂ (L₁.reverseAux (S k₂))⟩ := by
induction L₁ generalizing S s with
| nil =>
rw [(_ : [].reverseAux _ = _), Function.update_eq_self]
swap
· rw [Function.update_of_ne h₁.symm, List.reverseAux_nil]
refine TransGen.head' rfl ?_
rw [tr]; simp only [pop', TM2.stepAux]
revert e; rcases S k₁ with - | ⟨a, Sk⟩ <;> intro e
· cases e
rfl
simp only [splitAtPred, Option.elim, List.head?, List.tail_cons] at e ⊢
revert e; cases p a <;> intro e <;>
simp only [cond_false, cond_true, Prod.mk.injEq, true_and, false_and, reduceCtorEq] at e ⊢
simp only [e]
rfl
| cons a L₁ IH =>
refine TransGen.head rfl ?_
rw [tr]; simp only [pop', Option.elim, TM2.stepAux, push']
rcases e₁ : S k₁ with - | ⟨a', Sk⟩ <;> rw [e₁, splitAtPred] at e
· cases e
cases e₂ : p a' <;> simp only [e₂, cond] at e
swap
· cases e
rcases e₃ : splitAtPred p Sk with ⟨_, _, _⟩
rw [e₃] at e
cases e
simp only [List.head?_cons, e₂, List.tail_cons, cond_false]
convert @IH _ (update (update S k₁ Sk) k₂ (a :: S k₂)) _ using 2 <;>
simp [Function.update_of_ne, h₁, h₁.symm, e₃, List.reverseAux]
simp [Function.update_comm h₁.symm]
theorem unrev_ok {q s} {S : K' → List Γ'} :
Reaches₁ (TM2.step tr) ⟨some (unrev q), s, S⟩
⟨some q, none, update (update S rev []) main (List.reverseAux (S rev) (S main))⟩ :=
move_ok (by decide) <| splitAtPred_false _
theorem move₂_ok {p k₁ k₂ q s L₁ o L₂} {S : K' → List Γ'} (h₁ : k₁ ≠ rev ∧ k₂ ≠ rev ∧ k₁ ≠ k₂)
(h₂ : S rev = []) (e : splitAtPred p (S k₁) = (L₁, o, L₂)) :
Reaches₁ (TM2.step tr) ⟨some (move₂ p k₁ k₂ q), s, S⟩
⟨some q, none, update (update S k₁ (o.elim id List.cons L₂)) k₂ (L₁ ++ S k₂)⟩ := by
refine (move_ok h₁.1 e).trans (TransGen.head rfl ?_)
simp only [TM2.step, Option.mem_def, Option.elim]
cases o <;> simp only <;> rw [tr]
<;> simp only [id, TM2.stepAux, Option.isSome, cond_true, cond_false]
· convert move_ok h₁.2.1.symm (splitAtPred_false _) using 2
simp only [Function.update_comm h₁.1, Function.update_idem]
rw [show update S rev [] = S by rw [← h₂, Function.update_eq_self]]
simp only [Function.update_of_ne h₁.2.2.symm, Function.update_of_ne h₁.2.1,
Function.update_of_ne h₁.1.symm, List.reverseAux_eq, h₂, Function.update_self,
List.append_nil, List.reverse_reverse]
· convert move_ok h₁.2.1.symm (splitAtPred_false _) using 2
simp only [h₂, Function.update_comm h₁.1, List.reverseAux_eq, Function.update_self,
List.append_nil, Function.update_idem]
rw [show update S rev [] = S by rw [← h₂, Function.update_eq_self]]
simp only [Function.update_of_ne h₁.1.symm, Function.update_of_ne h₁.2.2.symm,
Function.update_of_ne h₁.2.1, Function.update_self, List.reverse_reverse]
theorem clear_ok {p k q s L₁ o L₂} {S : K' → List Γ'} (e : splitAtPred p (S k) = (L₁, o, L₂)) :
Reaches₁ (TM2.step tr) ⟨some (Λ'.clear p k q), s, S⟩ ⟨some q, o, update S k L₂⟩ := by
induction L₁ generalizing S s with
| nil =>
refine TransGen.head' rfl ?_
rw [tr]; simp only [pop', TM2.step, Option.mem_def, TM2.stepAux, Option.elim]
revert e; rcases S k with - | ⟨a, Sk⟩ <;> intro e
· cases e
rfl
simp only [splitAtPred, List.head?, List.tail_cons] at e ⊢
revert e; cases p a <;> intro e <;>
simp only [cond_false, cond_true, Prod.mk.injEq, true_and, false_and, reduceCtorEq] at e ⊢
rcases e with ⟨e₁, e₂⟩
rw [e₁, e₂]
| cons a L₁ IH =>
refine TransGen.head rfl ?_
rw [tr]; simp only [pop', TM2.step, Option.mem_def, TM2.stepAux, Option.elim]
rcases e₁ : S k with - | ⟨a', Sk⟩ <;> rw [e₁, splitAtPred] at e
· cases e
cases e₂ : p a' <;> simp only [e₂, cond] at e
swap
· cases e
rcases e₃ : splitAtPred p Sk with ⟨_, _, _⟩
rw [e₃] at e
cases e
simp only [List.head?_cons, e₂, List.tail_cons, cond_false]
convert @IH _ (update S k Sk) _ using 2 <;> simp [e₃]
theorem copy_ok (q s a b c d) :
Reaches₁ (TM2.step tr) ⟨some (Λ'.copy q), s, K'.elim a b c d⟩
⟨some q, none, K'.elim (List.reverseAux b a) [] c (List.reverseAux b d)⟩ := by
induction b generalizing a d s with
| nil =>
refine TransGen.single ?_
simp
| cons x b IH =>
refine TransGen.head rfl ?_
rw [tr]
simp only [TM2.step, Option.mem_def, TM2.stepAux, elim_rev, List.head?_cons, Option.isSome_some,
List.tail_cons, elim_update_rev, elim_main, elim_update_main,
elim_stack, elim_update_stack, cond_true, List.reverseAux_cons, pop', push']
exact IH _ _ _
theorem trPosNum_natEnd : ∀ (n), ∀ x ∈ trPosNum n, natEnd x = false
| PosNum.one, _, List.Mem.head _ => rfl
| PosNum.bit0 _, _, List.Mem.head _ => rfl
| PosNum.bit0 n, _, List.Mem.tail _ h => trPosNum_natEnd n _ h
| PosNum.bit1 _, _, List.Mem.head _ => rfl
| PosNum.bit1 n, _, List.Mem.tail _ h => trPosNum_natEnd n _ h
theorem trNum_natEnd : ∀ (n), ∀ x ∈ trNum n, natEnd x = false
| Num.pos n, x, h => trPosNum_natEnd n x h
theorem trNat_natEnd (n) : ∀ x ∈ trNat n, natEnd x = false :=
trNum_natEnd _
theorem trList_ne_consₗ : ∀ (l), ∀ x ∈ trList l, x ≠ Γ'.consₗ
| a :: l, x, h => by
simp only [trList, List.mem_append, List.mem_cons] at h
obtain h | rfl | h := h
· rintro rfl
cases trNat_natEnd _ _ h
· rintro ⟨⟩
· exact trList_ne_consₗ l _ h
theorem head_main_ok {q s L} {c d : List Γ'} :
Reaches₁ (TM2.step tr) ⟨some (head main q), s, K'.elim (trList L) [] c d⟩
⟨some q, none, K'.elim (trList [L.headI]) [] c d⟩ := by
let o : Option Γ' := List.casesOn L none fun _ _ => some Γ'.cons
refine
(move_ok (by decide)
(splitAtPred_eq _ _ (trNat L.headI) o (trList L.tail) (trNat_natEnd _) ?_)).trans
(TransGen.head rfl (TransGen.head rfl ?_))
· cases L <;> simp [o]
rw [tr]
simp only [TM2.step, Option.mem_def, TM2.stepAux, elim_update_main, elim_rev, elim_update_rev,
Function.update_self, trList]
rw [if_neg (show o ≠ some Γ'.consₗ by cases L <;> simp [o])]
refine (clear_ok (splitAtPred_eq _ _ _ none [] ?_ ⟨rfl, rfl⟩)).trans ?_
· exact fun x h => Bool.decide_false (trList_ne_consₗ _ _ h)
convert unrev_ok using 2; simp [List.reverseAux_eq]
theorem head_stack_ok {q s L₁ L₂ L₃} :
Reaches₁ (TM2.step tr)
⟨some (head stack q), s, K'.elim (trList L₁) [] [] (trList L₂ ++ Γ'.consₗ :: L₃)⟩
⟨some q, none, K'.elim (trList (L₂.headI :: L₁)) [] [] L₃⟩ := by
rcases L₂ with - | ⟨a, L₂⟩
· refine
TransGen.trans
(move_ok (by decide)
(splitAtPred_eq _ _ [] (some Γ'.consₗ) L₃ (by rintro _ ⟨⟩) ⟨rfl, rfl⟩))
(TransGen.head rfl (TransGen.head rfl ?_))
rw [tr]
simp only [TM2.step, Option.mem_def, TM2.stepAux, ite_true, id_eq, trList, List.nil_append,
elim_update_stack, elim_rev, List.reverseAux_nil, elim_update_rev, Function.update_self,
List.headI_nil, trNat_default]
convert unrev_ok using 2
simp
· refine
TransGen.trans
(move_ok (by decide)
(splitAtPred_eq _ _ (trNat a) (some Γ'.cons) (trList L₂ ++ Γ'.consₗ :: L₃)
(trNat_natEnd _) ⟨rfl, by simp⟩))
(TransGen.head rfl (TransGen.head rfl ?_))
simp only [TM2.step, Option.mem_def, trList, List.append_assoc,
List.cons_append, elim_update_stack, elim_rev, elim_update_rev, Function.update_self,
List.headI_cons]
refine
TransGen.trans
(clear_ok
(splitAtPred_eq _ _ (trList L₂) (some Γ'.consₗ) L₃
(fun x h => Bool.decide_false (trList_ne_consₗ _ _ h)) ⟨rfl, by simp⟩))
?_
convert unrev_ok using 2
simp [List.reverseAux_eq]
theorem succ_ok {q s n} {c d : List Γ'} :
Reaches₁ (TM2.step tr) ⟨some (Λ'.succ q), s, K'.elim (trList [n]) [] c d⟩
⟨some q, none, K'.elim (trList [n.succ]) [] c d⟩ := by
simp only [trList, trNat.eq_1, Nat.cast_succ, Num.add_one]
rcases (n : Num) with - | a
· refine TransGen.head rfl ?_
simp only [Option.mem_def]
convert unrev_ok using 1
simp only [elim_update_rev, elim_rev, elim_main, List.reverseAux_nil, elim_update_main]
rfl
simp only [trNum, Num.succ, Num.succ']
suffices ∀ l₁, ∃ l₁' l₂' s',
List.reverseAux l₁ (trPosNum a.succ) = List.reverseAux l₁' l₂' ∧
Reaches₁ (TM2.step tr) ⟨some q.succ, s, K'.elim (trPosNum a ++ [Γ'.cons]) l₁ c d⟩
⟨some (unrev q), s', K'.elim (l₂' ++ [Γ'.cons]) l₁' c d⟩ by
obtain ⟨l₁', l₂', s', e, h⟩ := this []
simp only [List.reverseAux] at e
refine h.trans ?_
convert unrev_ok using 2
simp [e, List.reverseAux_eq]
induction a generalizing s with intro l₁
| one =>
refine ⟨Γ'.bit0 :: l₁, [Γ'.bit1], some Γ'.cons, rfl, TransGen.head rfl (TransGen.single ?_)⟩
simp [trPosNum]
| bit1 m IH =>
obtain ⟨l₁', l₂', s', e, h⟩ := IH (Γ'.bit0 :: l₁)
refine ⟨l₁', l₂', s', e, TransGen.head ?_ h⟩
simp [trPosNum]
rfl
| bit0 m _ =>
refine ⟨l₁, _, some Γ'.bit0, rfl, TransGen.single ?_⟩
simp only [TM2.step]; rw [tr]
simp only [TM2.stepAux, pop', elim_main, elim_update_main,
elim_rev, elim_update_rev, Function.update_self, Option.mem_def, Option.some.injEq]
rfl
theorem pred_ok (q₁ q₂ s v) (c d : List Γ') : ∃ s',
Reaches₁ (TM2.step tr) ⟨some (Λ'.pred q₁ q₂), s, K'.elim (trList v) [] c d⟩
(v.headI.rec ⟨some q₁, s', K'.elim (trList v.tail) [] c d⟩ fun n _ =>
⟨some q₂, s', K'.elim (trList (n::v.tail)) [] c d⟩) := by
rcases v with (_ | ⟨_ | n, v⟩)
· refine ⟨none, TransGen.single ?_⟩
simp
· refine ⟨some Γ'.cons, TransGen.single ?_⟩
simp
refine ⟨none, ?_⟩
simp only [trList, trNat.eq_1, trNum, Nat.cast_succ, Num.add_one, Num.succ,
List.tail_cons, List.headI_cons]
rcases (n : Num) with - | a
· simp only [trPosNum, Num.succ', List.singleton_append, List.nil_append]
refine TransGen.head rfl ?_
rw [tr]; simp only [pop', TM2.stepAux]
convert unrev_ok using 2
simp
simp only [Num.succ']
suffices ∀ l₁, ∃ l₁' l₂' s',
List.reverseAux l₁ (trPosNum a) = List.reverseAux l₁' l₂' ∧
Reaches₁ (TM2.step tr)
⟨some (q₁.pred q₂), s, K'.elim (trPosNum a.succ ++ Γ'.cons :: trList v) l₁ c d⟩
⟨some (unrev q₂), s', K'.elim (l₂' ++ Γ'.cons :: trList v) l₁' c d⟩ by
obtain ⟨l₁', l₂', s', e, h⟩ := this []
simp only [List.reverseAux] at e
refine h.trans ?_
convert unrev_ok using 2
simp [e, List.reverseAux_eq]
induction a generalizing s with intro l₁
| one =>
refine ⟨Γ'.bit1::l₁, [], some Γ'.cons, rfl, TransGen.head rfl (TransGen.single ?_)⟩
simp [trPosNum, show PosNum.one.succ = PosNum.one.bit0 from rfl]
| bit1 m IH =>
obtain ⟨l₁', l₂', s', e, h⟩ := IH (some Γ'.bit0) (Γ'.bit1 :: l₁)
refine ⟨l₁', l₂', s', e, TransGen.head ?_ h⟩
simp
rfl
| bit0 m IH =>
obtain ⟨a, l, e, h⟩ : ∃ a l, (trPosNum m = a::l) ∧ natEnd a = false := by
cases m <;> refine ⟨_, _, rfl, rfl⟩
refine ⟨Γ'.bit0 :: l₁, _, some a, rfl, TransGen.single ?_⟩
simp [trPosNum, PosNum.succ, e, h, show some Γ'.bit1 ≠ some Γ'.bit0 by decide,
Option.iget, -natEnd]
rfl
theorem trNormal_respects (c k v s) :
∃ b₂,
TrCfg (stepNormal c k v) b₂ ∧
Reaches₁ (TM2.step tr)
⟨some (trNormal c (trCont k)), s, K'.elim (trList v) [] [] (trContStack k)⟩ b₂ := by
induction c generalizing k v s with
| zero' => refine ⟨_, ⟨s, rfl⟩, TransGen.single ?_⟩; simp
| succ => refine ⟨_, ⟨none, rfl⟩, head_main_ok.trans succ_ok⟩
| tail =>
let o : Option Γ' := List.casesOn v none fun _ _ => some Γ'.cons
refine ⟨_, ⟨o, rfl⟩, ?_⟩; convert clear_ok _ using 2
· simp; rfl
swap
refine splitAtPred_eq _ _ (trNat v.headI) _ _ (trNat_natEnd _) ?_
cases v <;> simp [o]
| cons f fs IHf _ =>
obtain ⟨c, h₁, h₂⟩ := IHf (Cont.cons₁ fs v k) v none
refine ⟨c, h₁, TransGen.head rfl <| (move_ok (by decide) (splitAtPred_false _)).trans ?_⟩
simp only [TM2.step, Option.mem_def, elim_stack, elim_update_stack, elim_update_main,
elim_main, elim_rev, elim_update_rev]
refine (copy_ok _ none [] (trList v).reverse _ _).trans ?_
convert h₂ using 2
simp [List.reverseAux_eq, trContStack]
| comp f _ _ IHg => exact IHg (Cont.comp f k) v s
| case f g IHf IHg =>
rw [stepNormal]
simp only
obtain ⟨s', h⟩ := pred_ok _ _ s v _ _
revert h; rcases v.headI with - | n <;> intro h
· obtain ⟨c, h₁, h₂⟩ := IHf k _ s'
exact ⟨_, h₁, h.trans h₂⟩
· obtain ⟨c, h₁, h₂⟩ := IHg k _ s'
exact ⟨_, h₁, h.trans h₂⟩
| fix f IH => apply IH
theorem tr_ret_respects (k v s) : ∃ b₂,
TrCfg (stepRet k v) b₂ ∧
Reaches₁ (TM2.step tr)
⟨some (Λ'.ret (trCont k)), s, K'.elim (trList v) [] [] (trContStack k)⟩ b₂ := by
induction k generalizing v s with
| halt => exact ⟨_, rfl, TransGen.single rfl⟩
| cons₁ fs as k _ =>
obtain ⟨s', h₁, h₂⟩ := trNormal_respects fs (Cont.cons₂ v k) as none
refine ⟨s', h₁, TransGen.head rfl ?_⟩; simp
refine (move₂_ok (by decide) ?_ (splitAtPred_false _)).trans ?_; · rfl
simp only [TM2.step, Option.mem_def, Option.elim, id_eq, elim_update_main, elim_main, elim_aux,
List.append_nil, elim_update_aux]
refine (move₂_ok (L₁ := ?_) (o := ?_) (L₂ := ?_) (by decide) rfl ?_).trans ?_
pick_goal 4
· exact splitAtPred_eq _ _ _ (some Γ'.consₗ) _
(fun x h => Bool.decide_false (trList_ne_consₗ _ _ h)) ⟨rfl, rfl⟩
refine (move₂_ok (by decide) ?_ (splitAtPred_false _)).trans ?_; · rfl
simp only [TM2.step, Option.mem_def, Option.elim, elim_update_stack, elim_main,
List.append_nil, elim_update_main, id_eq, elim_update_aux,
elim_aux, elim_stack]
exact h₂
| cons₂ ns k IH =>
obtain ⟨c, h₁, h₂⟩ := IH (ns.headI :: v) none
exact ⟨c, h₁, TransGen.head rfl <| head_stack_ok.trans h₂⟩
| comp f k _ =>
obtain ⟨s', h₁, h₂⟩ := trNormal_respects f k v s
exact ⟨_, h₁, TransGen.head rfl h₂⟩
| fix f k IH =>
rw [stepRet]
have :
if v.headI = 0 then natEnd (trList v).head?.iget = true ∧ (trList v).tail = trList v.tail
else
natEnd (trList v).head?.iget = false ∧
(trList v).tail = (trNat v.headI).tail ++ Γ'.cons :: trList v.tail := by
obtain - | n := v
· exact ⟨rfl, rfl⟩
rcases n with - | n
· simp
rw [trList, List.headI, trNat, Nat.cast_succ, Num.add_one, Num.succ, List.tail]
cases (n : Num).succ' <;> exact ⟨rfl, rfl⟩
by_cases h : v.headI = 0 <;> simp only [h, ite_true, ite_false] at this ⊢
· obtain ⟨c, h₁, h₂⟩ := IH v.tail (trList v).head?
refine ⟨c, h₁, TransGen.head rfl ?_⟩
rw [trCont, tr]; simp only [pop', TM2.stepAux, elim_main, this, elim_update_main]
exact h₂
· obtain ⟨s', h₁, h₂⟩ := trNormal_respects f (Cont.fix f k) v.tail (some Γ'.cons)
refine ⟨_, h₁, TransGen.head rfl <| TransGen.trans ?_ h₂⟩
rw [trCont, tr]; simp only [pop', TM2.stepAux, elim_main, this.1]
convert clear_ok (splitAtPred_eq _ _ (trNat v.headI).tail (some Γ'.cons) _ _ _) using 2
· simp
convert rfl
· exact fun x h => trNat_natEnd _ _ (List.tail_subset _ h)
· exact ⟨rfl, this.2⟩
theorem tr_respects : Respects step (TM2.step tr) TrCfg
| Cfg.ret _ _, _, ⟨_, rfl⟩ => tr_ret_respects _ _ _
| Cfg.halt _, _, rfl => rfl
/-- The initial state, evaluating function `c` on input `v`. -/
def init (c : Code) (v : List ℕ) : Cfg' :=
⟨some (trNormal c Cont'.halt), none, K'.elim (trList v) [] [] []⟩
theorem tr_init (c v) :
∃ b, TrCfg (stepNormal c Cont.halt v) b ∧ Reaches₁ (TM2.step tr) (init c v) b :=
trNormal_respects _ _ _ _
theorem tr_eval (c v) : eval (TM2.step tr) (init c v) = halt <$> Code.eval c v := by
obtain ⟨i, h₁, h₂⟩ := tr_init c v
refine Part.ext fun x => ?_
rw [reaches_eval h₂.to_reflTransGen]; simp only [Part.map_eq_map, Part.mem_map_iff]
refine ⟨fun h => ?_, ?_⟩
· obtain ⟨c, hc₁, hc₂⟩ := tr_eval_rev tr_respects h₁ h
simp [stepNormal_eval] at hc₂
obtain ⟨v', hv, rfl⟩ := hc₂
exact ⟨_, hv, hc₁.symm⟩
· rintro ⟨v', hv, rfl⟩
have := Turing.tr_eval (b₁ := Cfg.halt v') tr_respects h₁
simp only [stepNormal_eval, Part.map_eq_map, Part.mem_map_iff, Cfg.halt.injEq,
exists_eq_right] at this
obtain ⟨_, ⟨⟩, h⟩ := this hv
exact h
/-- The set of machine states reachable via downward label jumps, discounting jumps via `ret`. -/
def trStmts₁ : Λ' → Finset Λ'
| Q@(Λ'.move _ _ _ q) => insert Q <| trStmts₁ q
| Q@(Λ'.push _ _ q) => insert Q <| trStmts₁ q
| Q@(Λ'.read q) => insert Q <| Finset.univ.biUnion fun s => trStmts₁ (q s)
| Q@(Λ'.clear _ _ q) => insert Q <| trStmts₁ q
| Q@(Λ'.copy q) => insert Q <| trStmts₁ q
| Q@(Λ'.succ q) => insert Q <| insert (unrev q) <| trStmts₁ q
| Q@(Λ'.pred q₁ q₂) => insert Q <| trStmts₁ q₁ ∪ insert (unrev q₂) (trStmts₁ q₂)
| Q@(Λ'.ret _) => {Q}
theorem trStmts₁_trans {q q'} : q' ∈ trStmts₁ q → trStmts₁ q' ⊆ trStmts₁ q := by
induction q with
| move _ _ _ q q_ih => _ | clear _ _ q q_ih => _ | copy q q_ih => _ | push _ _ q q_ih => _
| read q q_ih => _ | succ q q_ih => _ | pred q₁ q₂ q₁_ih q₂_ih => _ | ret => _ <;>
all_goals
simp +contextual only [trStmts₁, Finset.mem_insert, Finset.mem_union,
or_imp, Finset.mem_singleton, Finset.Subset.refl, imp_true_iff, true_and]
repeat exact fun h => Finset.Subset.trans (q_ih h) (Finset.subset_insert _ _)
· simp
intro s h x h'
simp only [Finset.mem_biUnion, Finset.mem_univ, true_and, Finset.mem_insert]
exact Or.inr ⟨_, q_ih s h h'⟩
· constructor
· rintro rfl
apply Finset.subset_insert
· intro h x h'
simp only [Finset.mem_insert]
exact Or.inr (Or.inr <| q_ih h h')
· refine ⟨fun h x h' => ?_, fun _ x h' => ?_, fun h x h' => ?_⟩ <;> simp
· exact Or.inr (Or.inr <| Or.inl <| q₁_ih h h')
· rcases Finset.mem_insert.1 h' with h' | h' <;> simp [h', unrev]
· exact Or.inr (Or.inr <| Or.inr <| q₂_ih h h')
theorem trStmts₁_self (q) : q ∈ trStmts₁ q := by
induction q <;> · first |apply Finset.mem_singleton_self|apply Finset.mem_insert_self
/-- The (finite!) set of machine states visited during the course of evaluation of `c`,
including the state `ret k` but not any states after that (that is, the states visited while
evaluating `k`). -/
def codeSupp' : Code → Cont' → Finset Λ'
| c@Code.zero', k => trStmts₁ (trNormal c k)
| c@Code.succ, k => trStmts₁ (trNormal c k)
| c@Code.tail, k => trStmts₁ (trNormal c k)
| c@(Code.cons f fs), k =>
trStmts₁ (trNormal c k) ∪
(codeSupp' f (Cont'.cons₁ fs k) ∪
(trStmts₁
(move₂ (fun _ => false) main aux <|
move₂ (fun s => s = Γ'.consₗ) stack main <|
move₂ (fun _ => false) aux stack <| trNormal fs (Cont'.cons₂ k)) ∪
(codeSupp' fs (Cont'.cons₂ k) ∪ trStmts₁ (head stack <| Λ'.ret k))))
| c@(Code.comp f g), k =>
trStmts₁ (trNormal c k) ∪
(codeSupp' g (Cont'.comp f k) ∪ (trStmts₁ (trNormal f k) ∪ codeSupp' f k))
| c@(Code.case f g), k => trStmts₁ (trNormal c k) ∪ (codeSupp' f k ∪ codeSupp' g k)
| c@(Code.fix f), k =>
trStmts₁ (trNormal c k) ∪
(codeSupp' f (Cont'.fix f k) ∪
(trStmts₁ (Λ'.clear natEnd main <| trNormal f (Cont'.fix f k)) ∪ {Λ'.ret k}))
@[simp]
theorem codeSupp'_self (c k) : trStmts₁ (trNormal c k) ⊆ codeSupp' c k := by
cases c <;> first | rfl | exact Finset.union_subset_left (fun _ a ↦ a)
/-- The (finite!) set of machine states visited during the course of evaluation of a continuation
`k`, not including the initial state `ret k`. -/
def contSupp : Cont' → Finset Λ'
| Cont'.cons₁ fs k =>
trStmts₁
(move₂ (fun _ => false) main aux <|
move₂ (fun s => s = Γ'.consₗ) stack main <|
move₂ (fun _ => false) aux stack <| trNormal fs (Cont'.cons₂ k)) ∪
(codeSupp' fs (Cont'.cons₂ k) ∪ (trStmts₁ (head stack <| Λ'.ret k) ∪ contSupp k))
| Cont'.cons₂ k => trStmts₁ (head stack <| Λ'.ret k) ∪ contSupp k
| Cont'.comp f k => codeSupp' f k ∪ contSupp k
| Cont'.fix f k => codeSupp' (Code.fix f) k ∪ contSupp k
| Cont'.halt => ∅
/-- The (finite!) set of machine states visited during the course of evaluation of `c` in
continuation `k`. This is actually closed under forward simulation (see `tr_supports`), and the
existence of this set means that the machine constructed in this section is in fact a proper
Turing machine, with a finite set of states. -/
def codeSupp (c : Code) (k : Cont') : Finset Λ' :=
codeSupp' c k ∪ contSupp k
@[simp]
theorem codeSupp_self (c k) : trStmts₁ (trNormal c k) ⊆ codeSupp c k :=
Finset.Subset.trans (codeSupp'_self _ _) (Finset.union_subset_left fun _ a ↦ a)
@[simp]
theorem codeSupp_zero (k) : codeSupp Code.zero' k = trStmts₁ (trNormal Code.zero' k) ∪ contSupp k :=
rfl
@[simp]
theorem codeSupp_succ (k) : codeSupp Code.succ k = trStmts₁ (trNormal Code.succ k) ∪ contSupp k :=
rfl
@[simp]
theorem codeSupp_tail (k) : codeSupp Code.tail k = trStmts₁ (trNormal Code.tail k) ∪ contSupp k :=
rfl
@[simp]
theorem codeSupp_cons (f fs k) :
codeSupp (Code.cons f fs) k =
trStmts₁ (trNormal (Code.cons f fs) k) ∪ codeSupp f (Cont'.cons₁ fs k) := by
simp [codeSupp, codeSupp', contSupp, Finset.union_assoc]
@[simp]
theorem codeSupp_comp (f g k) :
codeSupp (Code.comp f g) k =
trStmts₁ (trNormal (Code.comp f g) k) ∪ codeSupp g (Cont'.comp f k) := by
simp only [codeSupp, codeSupp', trNormal, Finset.union_assoc, contSupp]
rw [← Finset.union_assoc _ _ (contSupp k),
Finset.union_eq_right.2 (codeSupp'_self _ _)]
@[simp]
theorem codeSupp_case (f g k) :
codeSupp (Code.case f g) k =
trStmts₁ (trNormal (Code.case f g) k) ∪ (codeSupp f k ∪ codeSupp g k) := by
simp [codeSupp, codeSupp', Finset.union_assoc, Finset.union_left_comm]
@[simp]
theorem codeSupp_fix (f k) :
codeSupp (Code.fix f) k = trStmts₁ (trNormal (Code.fix f) k) ∪ codeSupp f (Cont'.fix f k) := by
simp [codeSupp, codeSupp', contSupp, Finset.union_assoc, Finset.union_left_comm,
Finset.union_left_idem]
@[simp]
theorem contSupp_cons₁ (fs k) :
contSupp (Cont'.cons₁ fs k) =
trStmts₁
(move₂ (fun _ => false) main aux <|
move₂ (fun s => s = Γ'.consₗ) stack main <|
move₂ (fun _ => false) aux stack <| trNormal fs (Cont'.cons₂ k)) ∪
codeSupp fs (Cont'.cons₂ k) := by
simp [codeSupp, contSupp]
@[simp]
theorem contSupp_cons₂ (k) :
contSupp (Cont'.cons₂ k) = trStmts₁ (head stack <| Λ'.ret k) ∪ contSupp k :=
rfl
@[simp]
theorem contSupp_comp (f k) : contSupp (Cont'.comp f k) = codeSupp f k :=
rfl
theorem contSupp_fix (f k) : contSupp (Cont'.fix f k) = codeSupp f (Cont'.fix f k) := by
simp +contextual [codeSupp, codeSupp', contSupp, Finset.union_assoc,
Finset.subset_iff, -Finset.singleton_union, -Finset.union_singleton]
@[simp]
theorem contSupp_halt : contSupp Cont'.halt = ∅ :=
rfl
/-- The statement `Λ'.Supports S q` means that `contSupp k ⊆ S` for any `ret k`
reachable from `q`.
(This is a technical condition used in the proof that the machine is supported.) -/
def Λ'.Supports (S : Finset Λ') : Λ' → Prop
| Λ'.move _ _ _ q => Λ'.Supports S q
| Λ'.push _ _ q => Λ'.Supports S q
| Λ'.read q => ∀ s, Λ'.Supports S (q s)
| Λ'.clear _ _ q => Λ'.Supports S q
| Λ'.copy q => Λ'.Supports S q
| Λ'.succ q => Λ'.Supports S q
| Λ'.pred q₁ q₂ => Λ'.Supports S q₁ ∧ Λ'.Supports S q₂
| Λ'.ret k => contSupp k ⊆ S
/-- A shorthand for the predicate that we are proving in the main theorems `trStmts₁_supports`,
`codeSupp'_supports`, `contSupp_supports`, `codeSupp_supports`. The set `S` is fixed throughout
the proof, and denotes the full set of states in the machine, while `K` is a subset that we are
currently proving a property about. The predicate asserts that every state in `K` is closed in `S`
under forward simulation, i.e. stepping forward through evaluation starting from any state in `K`
stays entirely within `S`. -/
def Supports (K S : Finset Λ') :=
∀ q ∈ K, TM2.SupportsStmt S (tr q)
theorem supports_insert {K S q} :
Supports (insert q K) S ↔ TM2.SupportsStmt S (tr q) ∧ Supports K S := by simp [Supports]
theorem supports_singleton {S q} : Supports {q} S ↔ TM2.SupportsStmt S (tr q) := by simp [Supports]
theorem supports_union {K₁ K₂ S} : Supports (K₁ ∪ K₂) S ↔ Supports K₁ S ∧ Supports K₂ S := by
simp [Supports, or_imp, forall_and]
theorem supports_biUnion {K : Option Γ' → Finset Λ'} {S} :
Supports (Finset.univ.biUnion K) S ↔ ∀ a, Supports (K a) S := by
simpa [Supports] using forall_swap
theorem head_supports {S k q} (H : (q : Λ').Supports S) : (head k q).Supports S := fun _ => by
dsimp only; split_ifs <;> exact H
theorem ret_supports {S k} (H₁ : contSupp k ⊆ S) : TM2.SupportsStmt S (tr (Λ'.ret k)) := by
have W := fun {q} => trStmts₁_self q
cases k with
| halt => trivial
| cons₁ => rw [contSupp_cons₁, Finset.union_subset_iff] at H₁; exact fun _ => H₁.1 W
| cons₂ => rw [contSupp_cons₂, Finset.union_subset_iff] at H₁; exact fun _ => H₁.1 W
| comp => rw [contSupp_comp] at H₁; exact fun _ => H₁ (codeSupp_self _ _ W)
| fix =>
rw [contSupp_fix] at H₁
have L := @Finset.mem_union_left; have R := @Finset.mem_union_right
intro s; dsimp only; cases natEnd s.iget
· refine H₁ (R _ <| L _ <| R _ <| R _ <| L _ W)
· exact H₁ (R _ <| L _ <| R _ <| R _ <| R _ <| Finset.mem_singleton_self _)
theorem trStmts₁_supports {S q} (H₁ : (q : Λ').Supports S) (HS₁ : trStmts₁ q ⊆ S) :
Supports (trStmts₁ q) S := by
have W := fun {q} => trStmts₁_self q
induction q with
| move _ _ _ q q_ih => _ | clear _ _ q q_ih => _ | copy q q_ih => _ | push _ _ q q_ih => _
| read q q_ih => _ | succ q q_ih => _ | pred q₁ q₂ q₁_ih q₂_ih => _ | ret => _ <;>
simp [trStmts₁, -Finset.singleton_subset_iff] at HS₁ ⊢
any_goals
obtain ⟨h₁, h₂⟩ := Finset.insert_subset_iff.1 HS₁
first | have h₃ := h₂ W | try simp [Finset.subset_iff] at h₂
· exact supports_insert.2 ⟨⟨fun _ => h₃, fun _ => h₁⟩, q_ih H₁ h₂⟩ -- move
· exact supports_insert.2 ⟨⟨fun _ => h₃, fun _ => h₁⟩, q_ih H₁ h₂⟩ -- clear
· exact supports_insert.2 ⟨⟨fun _ => h₁, fun _ => h₃⟩, q_ih H₁ h₂⟩ -- copy
· exact supports_insert.2 ⟨⟨fun _ => h₃, fun _ => h₃⟩, q_ih H₁ h₂⟩ -- push
· refine supports_insert.2 ⟨fun _ => h₂ _ W, ?_⟩ -- read
exact supports_biUnion.2 fun _ => q_ih _ (H₁ _) fun _ h => h₂ _ h
· refine supports_insert.2 ⟨⟨fun _ => h₁, fun _ => h₂.1, fun _ => h₂.1⟩, ?_⟩ -- succ
exact supports_insert.2 ⟨⟨fun _ => h₂.2 _ W, fun _ => h₂.1⟩, q_ih H₁ h₂.2⟩
· refine -- pred
supports_insert.2 ⟨⟨fun _ => h₁, fun _ => h₂.2 _ (Or.inl W),
fun _ => h₂.1, fun _ => h₂.1⟩, ?_⟩
refine supports_insert.2 ⟨⟨fun _ => h₂.2 _ (Or.inr W), fun _ => h₂.1⟩, ?_⟩
refine supports_union.2 ⟨?_, ?_⟩
· exact q₁_ih H₁.1 fun _ h => h₂.2 _ (Or.inl h)
· exact q₂_ih H₁.2 fun _ h => h₂.2 _ (Or.inr h)
· exact supports_singleton.2 (ret_supports H₁) -- ret
theorem trStmts₁_supports' {S q K} (H₁ : (q : Λ').Supports S) (H₂ : trStmts₁ q ∪ K ⊆ S)
(H₃ : K ⊆ S → Supports K S) : Supports (trStmts₁ q ∪ K) S := by
simp only [Finset.union_subset_iff] at H₂
exact supports_union.2 ⟨trStmts₁_supports H₁ H₂.1, H₃ H₂.2⟩
theorem trNormal_supports {S c k} (Hk : codeSupp c k ⊆ S) : (trNormal c k).Supports S := by
induction c generalizing k with simp [Λ'.Supports, head]
| zero' => exact Finset.union_subset_right Hk
| succ => intro; split_ifs <;> exact Finset.union_subset_right Hk
| tail => exact Finset.union_subset_right Hk
| cons f fs IHf _ =>
apply IHf
rw [codeSupp_cons] at Hk
exact Finset.union_subset_right Hk
| comp f g _ IHg => apply IHg; rw [codeSupp_comp] at Hk; exact Finset.union_subset_right Hk
| case f g IHf IHg =>
simp only [codeSupp_case, Finset.union_subset_iff] at Hk
exact ⟨IHf Hk.2.1, IHg Hk.2.2⟩
| fix f IHf => apply IHf; rw [codeSupp_fix] at Hk; exact Finset.union_subset_right Hk
theorem codeSupp'_supports {S c k} (H : codeSupp c k ⊆ S) : Supports (codeSupp' c k) S := by
induction c generalizing k with
| cons f fs IHf IHfs =>
have H' := H; simp only [codeSupp_cons, Finset.union_subset_iff] at H'
refine trStmts₁_supports' (trNormal_supports H) (Finset.union_subset_left H) fun h => ?_
refine supports_union.2 ⟨IHf H'.2, ?_⟩
refine trStmts₁_supports' (trNormal_supports ?_) (Finset.union_subset_right h) fun h => ?_
· simp only [codeSupp, Finset.union_subset_iff, contSupp] at h H ⊢
exact ⟨h.2.2.1, h.2.2.2, H.2⟩
refine supports_union.2 ⟨IHfs ?_, ?_⟩
· rw [codeSupp, contSupp_cons₁] at H'
exact Finset.union_subset_right (Finset.union_subset_right H'.2)
exact
trStmts₁_supports (head_supports <| Finset.union_subset_right H)
(Finset.union_subset_right h)
| comp f g IHf IHg =>
have H' := H; rw [codeSupp_comp] at H'; have H' := Finset.union_subset_right H'
refine trStmts₁_supports' (trNormal_supports H) (Finset.union_subset_left H) fun h => ?_
refine supports_union.2 ⟨IHg H', ?_⟩
refine trStmts₁_supports' (trNormal_supports ?_) (Finset.union_subset_right h) fun _ => ?_
· simp only [codeSupp', codeSupp, Finset.union_subset_iff] at h H ⊢
exact ⟨h.2.2, H.2⟩
exact IHf (Finset.union_subset_right H')
| case f g IHf IHg =>
have H' := H; simp only [codeSupp_case, Finset.union_subset_iff] at H'
refine trStmts₁_supports' (trNormal_supports H) (Finset.union_subset_left H) fun _ => ?_
exact supports_union.2 ⟨IHf H'.2.1, IHg H'.2.2⟩
| fix f IHf =>
have H' := H; simp only [codeSupp_fix, Finset.union_subset_iff] at H'
refine trStmts₁_supports' (trNormal_supports H) (Finset.union_subset_left H) fun h => ?_
refine supports_union.2 ⟨IHf H'.2, ?_⟩
refine trStmts₁_supports' (trNormal_supports ?_) (Finset.union_subset_right h) fun _ => ?_
· simp only [codeSupp', codeSupp, Finset.union_subset_iff, contSupp, trStmts₁,
Finset.insert_subset_iff] at h H ⊢
exact ⟨h.1, ⟨H.1.1, h⟩, H.2⟩
exact supports_singleton.2 (ret_supports <| Finset.union_subset_right H)
| _ => exact trStmts₁_supports (trNormal_supports H) (Finset.Subset.trans (codeSupp_self _ _) H)
theorem contSupp_supports {S k} (H : contSupp k ⊆ S) : Supports (contSupp k) S := by
induction k with
| halt => simp [contSupp_halt, Supports]
| cons₁ f k IH =>
have H₁ := H; rw [contSupp_cons₁] at H₁; have H₂ := Finset.union_subset_right H₁
refine trStmts₁_supports' (trNormal_supports H₂) H₁ fun h => ?_
refine supports_union.2 ⟨codeSupp'_supports H₂, ?_⟩
simp only [codeSupp, contSupp_cons₂, Finset.union_subset_iff] at H₂
exact trStmts₁_supports' (head_supports H₂.2.2) (Finset.union_subset_right h) IH
| cons₂ k IH =>
have H' := H; rw [contSupp_cons₂] at H'
exact trStmts₁_supports' (head_supports <| Finset.union_subset_right H') H' IH
| comp f k IH =>
have H' := H; rw [contSupp_comp] at H'; have H₂ := Finset.union_subset_right H'
exact supports_union.2 ⟨codeSupp'_supports H', IH H₂⟩
| fix f k IH =>
rw [contSupp] at H
exact supports_union.2 ⟨codeSupp'_supports H, IH (Finset.union_subset_right H)⟩
theorem codeSupp_supports {S c k} (H : codeSupp c k ⊆ S) : Supports (codeSupp c k) S :=
supports_union.2 ⟨codeSupp'_supports H, contSupp_supports (Finset.union_subset_right H)⟩
/-- The set `codeSupp c k` is a finite set that witnesses the effective finiteness of the `tr`
Turing machine. Starting from the initial state `trNormal c k`, forward simulation uses only
states in `codeSupp c k`, so this is a finite state machine. Even though the underlying type of
state labels `Λ'` is infinite, for a given partial recursive function `c` and continuation `k`,
only finitely many states are accessed, corresponding roughly to subterms of `c`. -/
theorem tr_supports (c k) : @TM2.Supports _ _ _ _ ⟨trNormal c k⟩ tr (codeSupp c k) :=
⟨codeSupp_self _ _ (trStmts₁_self _), fun _ => codeSupp_supports (Finset.Subset.refl _) _⟩
end
end PartrecToTM2
end Turing |
.lake/packages/mathlib/Mathlib/Computability/Encoding.lean | import Mathlib.Data.Fintype.Basic
import Mathlib.Data.Num.Lemmas
import Mathlib.Data.Option.Basic
import Mathlib.SetTheory.Cardinal.Basic
import Mathlib.Tactic.DeriveFintype
/-!
# Encodings
This file contains the definition of a (finite) encoding, a map from a type to
strings in an alphabet, used in defining computability by Turing machines.
It also contains several examples:
## Examples
- `finEncodingNatBool` : a binary encoding of ℕ in a simple alphabet.
- `finEncodingNatΓ'` : a binary encoding of ℕ in the alphabet used for TM's.
- `unaryFinEncodingNat` : a unary encoding of ℕ
- `finEncodingBoolBool` : an encoding of bool.
-/
universe u v
open Cardinal
namespace Computability
/-- An encoding of a type in a certain alphabet, together with a decoding. -/
structure Encoding (α : Type u) where
/-- The alphabet of the encoding -/
Γ : Type v
/-- The encoding function -/
encode : α → List Γ
/-- The decoding function -/
decode : List Γ → Option α
/-- Decoding and encoding are inverses of each other. -/
decode_encode : ∀ x, decode (encode x) = some x
theorem Encoding.encode_injective {α : Type u} (e : Encoding α) : Function.Injective e.encode := by
refine fun _ _ h => Option.some_injective _ ?_
rw [← e.decode_encode, ← e.decode_encode, h]
/-- An encoding plus a guarantee of finiteness of the alphabet. -/
structure FinEncoding (α : Type u) extends Encoding.{u, 0} α where
/-- The alphabet of the encoding is finite -/
ΓFin : Fintype Γ
instance Γ.fintype {α : Type u} (e : FinEncoding α) : Fintype e.toEncoding.Γ :=
e.ΓFin
/-- A standard Turing machine alphabet, consisting of blank,bit0,bit1,bra,ket,comma. -/
inductive Γ'
| blank
| bit (b : Bool)
| bra
| ket
| comma
deriving DecidableEq, Fintype
instance inhabitedΓ' : Inhabited Γ' :=
⟨Γ'.blank⟩
/-- The natural inclusion of bool in Γ'. -/
def inclusionBoolΓ' : Bool → Γ' :=
Γ'.bit
/-- An arbitrary section of the natural inclusion of bool in Γ'. -/
def sectionΓ'Bool : Γ' → Bool
| Γ'.bit b => b
| _ => Inhabited.default
@[simp]
theorem sectionΓ'Bool_inclusionBoolΓ' {b} : sectionΓ'Bool (inclusionBoolΓ' b) = b := by
cases b <;> rfl
theorem inclusionBoolΓ'_injective : Function.Injective inclusionBoolΓ' :=
Function.HasLeftInverse.injective ⟨_, (fun _ => sectionΓ'Bool_inclusionBoolΓ')⟩
/-- An encoding function of the positive binary numbers in bool. -/
def encodePosNum : PosNum → List Bool
| PosNum.one => [true]
| PosNum.bit0 n => false :: encodePosNum n
| PosNum.bit1 n => true :: encodePosNum n
/-- An encoding function of the binary numbers in bool. -/
def encodeNum : Num → List Bool
| Num.zero => []
| Num.pos n => encodePosNum n
/-- An encoding function of ℕ in bool. -/
def encodeNat (n : ℕ) : List Bool :=
encodeNum n
/-- A decoding function from `List Bool` to the positive binary numbers. -/
def decodePosNum : List Bool → PosNum
| false :: l => PosNum.bit0 (decodePosNum l)
| true :: l => ite (l = []) PosNum.one (PosNum.bit1 (decodePosNum l))
| _ => PosNum.one
/-- A decoding function from `List Bool` to the binary numbers. -/
def decodeNum : List Bool → Num := fun l => ite (l = []) Num.zero <| decodePosNum l
/-- A decoding function from `List Bool` to ℕ. -/
def decodeNat : List Bool → Nat := fun l => decodeNum l
theorem encodePosNum_nonempty (n : PosNum) : encodePosNum n ≠ [] :=
PosNum.casesOn n (List.cons_ne_nil _ _) (fun _m => List.cons_ne_nil _ _) fun _m =>
List.cons_ne_nil _ _
@[simp] theorem decode_encodePosNum (n) : decodePosNum (encodePosNum n) = n := by
induction n with unfold encodePosNum decodePosNum
| one => rfl
| bit1 m hm =>
rw [hm]
exact if_neg (encodePosNum_nonempty m)
| bit0 m hm => exact congr_arg PosNum.bit0 hm
@[simp] theorem decode_encodeNum (n) : decodeNum (encodeNum n) = n := by
obtain - | n := n <;> unfold encodeNum decodeNum
· rfl
rw [decode_encodePosNum n]
rw [PosNum.cast_to_num]
exact if_neg (encodePosNum_nonempty n)
@[simp] theorem decode_encodeNat (n) : decodeNat (encodeNat n) = n := by
conv_rhs => rw [← Num.to_of_nat n]
exact congr_arg ((↑) : Num → ℕ) (decode_encodeNum n)
/-- A binary encoding of ℕ in bool. -/
def encodingNatBool : Encoding ℕ where
Γ := Bool
encode := encodeNat
decode n := some (decodeNat n)
decode_encode n := congr_arg _ (decode_encodeNat n)
/-- A binary fin_encoding of ℕ in bool. -/
def finEncodingNatBool : FinEncoding ℕ :=
⟨encodingNatBool, Bool.fintype⟩
/-- A binary encoding of ℕ in Γ'. -/
def encodingNatΓ' : Encoding ℕ where
Γ := Γ'
encode x := List.map inclusionBoolΓ' (encodeNat x)
decode x := some (decodeNat (List.map sectionΓ'Bool x))
decode_encode x := congr_arg _ <| by simp [Function.comp_def]
/-- A binary FinEncoding of ℕ in Γ'. -/
def finEncodingNatΓ' : FinEncoding ℕ :=
⟨encodingNatΓ', inferInstanceAs (Fintype Γ')⟩
/-- A unary encoding function of ℕ in bool. -/
def unaryEncodeNat : Nat → List Bool
| 0 => []
| n + 1 => true :: unaryEncodeNat n
/-- A unary decoding function from `List Bool` to ℕ. -/
def unaryDecodeNat : List Bool → Nat :=
List.length
@[simp] theorem unary_decode_encode_nat : ∀ n, unaryDecodeNat (unaryEncodeNat n) = n := fun n =>
Nat.rec rfl (fun (_m : ℕ) hm => (congr_arg Nat.succ hm.symm).symm) n
/-- A unary fin_encoding of ℕ. -/
def unaryFinEncodingNat : FinEncoding ℕ where
Γ := Bool
encode := unaryEncodeNat
decode n := some (unaryDecodeNat n)
decode_encode n := congr_arg _ (unary_decode_encode_nat n)
ΓFin := Bool.fintype
/-- An encoding function of bool in bool. -/
def encodeBool : Bool → List Bool := pure
/-- A decoding function from `List Bool` to bool. -/
def decodeBool : List Bool → Bool
| b :: _ => b
| _ => Inhabited.default
@[simp] theorem decode_encodeBool (b : Bool) : decodeBool (encodeBool b) = b := rfl
/-- A fin_encoding of bool in bool. -/
def finEncodingBoolBool : FinEncoding Bool where
Γ := Bool
encode := encodeBool
decode x := some (decodeBool x)
decode_encode x := congr_arg _ (decode_encodeBool x)
ΓFin := Bool.fintype
instance inhabitedFinEncoding : Inhabited (FinEncoding Bool) :=
⟨finEncodingBoolBool⟩
instance inhabitedEncoding : Inhabited (Encoding Bool) :=
⟨finEncodingBoolBool.toEncoding⟩
theorem Encoding.card_le_card_list {α : Type u} (e : Encoding.{u, v} α) :
Cardinal.lift.{v} #α ≤ Cardinal.lift.{u} #(List e.Γ) :=
Cardinal.lift_mk_le'.2 ⟨⟨e.encode, e.encode_injective⟩⟩
theorem Encoding.card_le_aleph0 {α : Type u} (e : Encoding.{u, v} α) [Countable e.Γ] :
#α ≤ ℵ₀ :=
haveI : Countable α := e.encode_injective.countable
Cardinal.mk_le_aleph0
theorem FinEncoding.card_le_aleph0 {α : Type u} (e : FinEncoding α) : #α ≤ ℵ₀ :=
e.toEncoding.card_le_aleph0
end Computability |
.lake/packages/mathlib/Mathlib/Computability/Language.lean | import Mathlib.Algebra.Order.Kleene
import Mathlib.Algebra.Ring.Hom.Defs
import Mathlib.Data.Set.Lattice
import Mathlib.Tactic.DeriveFintype
/-!
# Languages
This file contains the definition and operations on formal languages over an alphabet.
Note that "strings" are implemented as lists over the alphabet.
Union and concatenation define a [Kleene algebra](https://en.wikipedia.org/wiki/Kleene_algebra)
over the languages.
In addition to that, we define a reversal of a language and prove that it behaves well
with respect to other language operations.
## Notation
* `l + m`: union of languages `l` and `m`
* `l * m`: language of strings `x ++ y` such that `x ∈ l` and `y ∈ m`
* `l ^ n`: language of strings consisting of `n` members of `l` concatenated together
* `1`: language consisting of only the empty string. This is because it is the unit of the `*`
operator.
* `l∗`: Kleene star – language of strings consisting of arbitrarily many members of `l`
concatenated together. Note that this notation uses the Unicode asterisk operator `∗`, as opposed
to the more common ASCII asterisk `*`.
## Main definitions
* `Language α`: a set of strings over the alphabet `α`
* `l.map f`: transform a language `l` over `α` into a language over `β`
by translating through `f : α → β`
## Main theorems
* `Language.self_eq_mul_add_iff`: Arden's lemma – if a language `l` satisfies the equation
`l = m * l + n`, and `m` doesn't contain the empty string,
then `l` is the language `m∗ * n`
-/
open List Set Computability
universe v
variable {α β γ : Type*}
/-- A language is a set of strings over an alphabet. -/
def Language (α) :=
Set (List α)
namespace Language
instance : Membership (List α) (Language α) := ⟨Set.Mem⟩
instance : Singleton (List α) (Language α) := ⟨Set.singleton⟩
instance : Insert (List α) (Language α) := ⟨Set.insert⟩
instance instCompleteAtomicBooleanAlgebra : CompleteAtomicBooleanAlgebra (Language α) :=
Set.instCompleteAtomicBooleanAlgebra
variable {l m : Language α} {a b x : List α}
/-- Zero language has no elements. -/
instance : Zero (Language α) :=
⟨(∅ : Set _)⟩
/-- `1 : Language α` contains only one element `[]`. -/
instance : One (Language α) :=
⟨{[]}⟩
instance : Inhabited (Language α) := ⟨(∅ : Set _)⟩
/-- The sum of two languages is their union. -/
instance : Add (Language α) :=
⟨((· ∪ ·) : Set (List α) → Set (List α) → Set (List α))⟩
/-- The product of two languages `l` and `m` is the language made of the strings `x ++ y` where
`x ∈ l` and `y ∈ m`. -/
instance : Mul (Language α) :=
⟨image2 (· ++ ·)⟩
theorem zero_def : (0 : Language α) = (∅ : Set _) :=
rfl
theorem one_def : (1 : Language α) = ({[]} : Set (List α)) :=
rfl
theorem add_def (l m : Language α) : l + m = (l ∪ m : Set (List α)) :=
rfl
theorem mul_def (l m : Language α) : l * m = image2 (· ++ ·) l m :=
rfl
/-- The Kleene star of a language `L` is the set of all strings which can be written by
concatenating strings from `L`. -/
instance : KStar (Language α) := ⟨fun l ↦ {x | ∃ L : List (List α), x = L.flatten ∧ ∀ y ∈ L, y ∈ l}⟩
lemma kstar_def (l : Language α) : l∗ = {x | ∃ L : List (List α), x = L.flatten ∧ ∀ y ∈ L, y ∈ l} :=
rfl
@[ext]
theorem ext {l m : Language α} (h : ∀ (x : List α), x ∈ l ↔ x ∈ m) : l = m :=
Set.ext h
@[simp]
theorem notMem_zero (x : List α) : x ∉ (0 : Language α) :=
id
@[deprecated (since := "2025-05-23")] alias not_mem_zero := notMem_zero
@[simp]
theorem mem_one (x : List α) : x ∈ (1 : Language α) ↔ x = [] := by rfl
theorem nil_mem_one : [] ∈ (1 : Language α) :=
Set.mem_singleton _
theorem mem_add (l m : Language α) (x : List α) : x ∈ l + m ↔ x ∈ l ∨ x ∈ m :=
Iff.rfl
theorem mem_mul : x ∈ l * m ↔ ∃ a ∈ l, ∃ b ∈ m, a ++ b = x :=
mem_image2
theorem append_mem_mul : a ∈ l → b ∈ m → a ++ b ∈ l * m :=
mem_image2_of_mem
theorem mem_kstar : x ∈ l∗ ↔ ∃ L : List (List α), x = L.flatten ∧ ∀ y ∈ L, y ∈ l :=
Iff.rfl
theorem join_mem_kstar {L : List (List α)} (h : ∀ y ∈ L, y ∈ l) : L.flatten ∈ l∗ :=
⟨L, rfl, h⟩
theorem nil_mem_kstar (l : Language α) : [] ∈ l∗ :=
⟨[], rfl, fun _ h ↦ by contradiction⟩
instance instSemiring : Semiring (Language α) where
add_assoc := union_assoc
zero_add := empty_union
add_zero := union_empty
add_comm := union_comm
mul_assoc _ _ _ := image2_assoc append_assoc
zero_mul _ := image2_empty_left
mul_zero _ := image2_empty_right
one_mul l := by simp [mul_def, one_def]
mul_one l := by simp [mul_def, one_def]
natCast n := if n = 0 then 0 else 1
natCast_zero := rfl
natCast_succ n := by cases n <;> simp [add_def, zero_def]
left_distrib _ _ _ := image2_union_right
right_distrib _ _ _ := image2_union_left
nsmul := nsmulRec
@[simp]
theorem add_self (l : Language α) : l + l = l :=
sup_idem _
/-- Maps the alphabet of a language. -/
def map (f : α → β) : Language α →+* Language β where
toFun := image (List.map f)
map_zero' := image_empty _
map_one' := image_singleton
map_add' := image_union _
map_mul' _ _ := image_image2_distrib <| fun _ _ => map_append
@[simp]
theorem map_id (l : Language α) : map id l = l := by simp [map]
@[simp]
theorem map_map (g : β → γ) (f : α → β) (l : Language α) : map g (map f l) = map (g ∘ f) l := by
simp [map, image_image]
lemma mem_kstar_iff_exists_nonempty {x : List α} :
x ∈ l∗ ↔ ∃ S : List (List α), x = S.flatten ∧ ∀ y ∈ S, y ∈ l ∧ y ≠ [] := by
constructor
· rintro ⟨S, rfl, h⟩
refine ⟨S.filter fun l ↦ !List.isEmpty l,
by simp [List.flatten_filter_not_isEmpty], fun y hy ↦ ?_⟩
simp only [mem_filter, Bool.not_eq_eq_eq_not, Bool.not_true, isEmpty_eq_false_iff, ne_eq] at hy
exact ⟨h y hy.1, hy.2⟩
· rintro ⟨S, hx, h⟩
exact ⟨S, hx, fun y hy ↦ (h y hy).1⟩
theorem kstar_def_nonempty (l : Language α) :
l∗ = { x | ∃ S : List (List α), x = S.flatten ∧ ∀ y ∈ S, y ∈ l ∧ y ≠ [] } := by
ext x; apply mem_kstar_iff_exists_nonempty
theorem le_iff (l m : Language α) : l ≤ m ↔ l + m = m :=
sup_eq_right.symm
instance : MulLeftMono (Language α) where
elim _ _ _ := image2_subset_left
instance : MulRightMono (Language α) where
elim _ _ _ := image2_subset_right
@[deprecated mul_le_mul' (since := "2025-10-26")]
theorem le_mul_congr {l₁ l₂ m₁ m₂ : Language α} : l₁ ≤ m₁ → l₂ ≤ m₂ → l₁ * l₂ ≤ m₁ * m₂ :=
mul_le_mul'
theorem mem_iSup {ι : Sort v} {l : ι → Language α} {x : List α} : (x ∈ ⨆ i, l i) ↔ ∃ i, x ∈ l i :=
mem_iUnion
theorem iSup_mul {ι : Sort v} (l : ι → Language α) (m : Language α) :
(⨆ i, l i) * m = ⨆ i, l i * m :=
image2_iUnion_left _ _ _
theorem mul_iSup {ι : Sort v} (l : ι → Language α) (m : Language α) :
(m * ⨆ i, l i) = ⨆ i, m * l i :=
image2_iUnion_right _ _ _
theorem iSup_add {ι : Sort v} [Nonempty ι] (l : ι → Language α) (m : Language α) :
(⨆ i, l i) + m = ⨆ i, l i + m :=
iSup_sup
theorem add_iSup {ι : Sort v} [Nonempty ι] (l : ι → Language α) (m : Language α) :
(m + ⨆ i, l i) = ⨆ i, m + l i :=
sup_iSup
theorem mem_pow {l : Language α} {x : List α} {n : ℕ} :
x ∈ l ^ n ↔ ∃ S : List (List α), x = S.flatten ∧ S.length = n ∧ ∀ y ∈ S, y ∈ l := by
induction n generalizing x with
| zero => simp
| succ n ihn =>
simp only [pow_succ', mem_mul, ihn]
constructor
· rintro ⟨a, ha, b, ⟨S, rfl, rfl, hS⟩, rfl⟩
exact ⟨a :: S, rfl, rfl, forall_mem_cons.2 ⟨ha, hS⟩⟩
· rintro ⟨_ | ⟨a, S⟩, rfl, hn, hS⟩ <;> cases hn
rw [forall_mem_cons] at hS
exact ⟨a, hS.1, _, ⟨S, rfl, rfl, hS.2⟩, rfl⟩
theorem kstar_eq_iSup_pow (l : Language α) : l∗ = ⨆ i : ℕ, l ^ i := by
ext x
simp only [mem_kstar, mem_iSup, mem_pow]
grind
@[simp]
theorem map_kstar (f : α → β) (l : Language α) : map f l∗ = (map f l)∗ := by
rw [kstar_eq_iSup_pow, kstar_eq_iSup_pow]
simp_rw [← map_pow]
exact image_iUnion
theorem mul_self_kstar_comm (l : Language α) : l∗ * l = l * l∗ := by
simp only [kstar_eq_iSup_pow, mul_iSup, iSup_mul, ← pow_succ, ← pow_succ']
@[simp]
theorem one_add_self_mul_kstar_eq_kstar (l : Language α) : 1 + l * l∗ = l∗ := by
simp only [kstar_eq_iSup_pow, mul_iSup, ← pow_succ', ← pow_zero l]
exact sup_iSup_nat_succ _
@[simp]
theorem one_add_kstar_mul_self_eq_kstar (l : Language α) : 1 + l∗ * l = l∗ := by
rw [mul_self_kstar_comm, one_add_self_mul_kstar_eq_kstar]
instance : KleeneAlgebra (Language α) :=
{ instSemiring, instCompleteAtomicBooleanAlgebra with
kstar := fun L ↦ L∗,
one_le_kstar := fun a _ hl ↦ ⟨[], hl, by simp⟩,
mul_kstar_le_kstar := fun a ↦ (one_add_self_mul_kstar_eq_kstar a).le.trans' le_sup_right,
kstar_mul_le_kstar := fun a ↦ (one_add_kstar_mul_self_eq_kstar a).le.trans' le_sup_right,
kstar_mul_le_self := fun l m h ↦ by
rw [kstar_eq_iSup_pow, iSup_mul]
refine iSup_le (fun n ↦ ?_)
induction n with
| zero => simp
| succ n ih =>
rw [pow_succ, mul_assoc (l^n) l m]
exact le_trans (mul_le_mul_left' h _) ih,
mul_kstar_le_self := fun l m h ↦ by
rw [kstar_eq_iSup_pow, mul_iSup]
refine iSup_le (fun n ↦ ?_)
induction n with
| zero => simp
| succ n ih =>
rw [pow_succ, ← mul_assoc m (l^n) l]
exact le_trans (mul_le_mul_right' ih _) h }
@[deprecated add_le_add (since := "2025-10-26")]
theorem le_add_congr {l₁ l₂ m₁ m₂ : Language α} : l₁ ≤ m₁ → l₂ ≤ m₂ → l₁ + l₂ ≤ m₁ + m₂ :=
add_le_add
/-- **Arden's lemma** -/
theorem self_eq_mul_add_iff {l m n : Language α} (hm : [] ∉ m) : l = m * l + n ↔ l = m∗ * n where
mp h := by
apply le_antisymm
· intro x hx
induction hlen : x.length using Nat.strong_induction_on generalizing x with | _ _ ih
subst hlen
rw [h] at hx
obtain hx | hx := hx
· obtain ⟨a, ha, b, hb, rfl⟩ := mem_mul.mp hx
rw [length_append] at ih
have hal : 0 < a.length := length_pos_iff.mpr <| ne_of_mem_of_not_mem ha hm
specialize ih b.length (Nat.lt_add_left_iff_pos.mpr hal) hb rfl
rw [← one_add_self_mul_kstar_eq_kstar, one_add_mul, mul_assoc]
right
exact ⟨_, ha, _, ih, rfl⟩
· exact ⟨[], nil_mem_kstar _, _, ⟨hx, nil_append _⟩⟩
· rw [kstar_eq_iSup_pow, iSup_mul, iSup_le_iff]
intro i
induction i with rw [h]
| zero =>
rw [pow_zero, one_mul, add_comm]
exact le_self_add
| succ _ ih =>
grw [add_comm, pow_add, pow_one, mul_assoc, ih]
exact le_self_add
mpr h := by rw [h, add_comm, ← mul_assoc, ← one_add_mul, one_add_self_mul_kstar_eq_kstar]
/-- Language `l.reverse` is defined as the set of words from `l` backwards. -/
def reverse (l : Language α) : Language α := { w : List α | w.reverse ∈ l }
@[simp]
lemma mem_reverse : a ∈ l.reverse ↔ a.reverse ∈ l := Iff.rfl
lemma reverse_mem_reverse : a.reverse ∈ l.reverse ↔ a ∈ l := by
rw [mem_reverse, List.reverse_reverse]
lemma reverse_eq_image (l : Language α) : l.reverse = List.reverse '' l :=
((List.reverse_involutive.toPerm _).image_eq_preimage_symm _).symm
@[simp]
lemma reverse_zero : (0 : Language α).reverse = 0 := rfl
@[simp]
lemma reverse_one : (1 : Language α).reverse = 1 := by
simp [reverse, ← one_def]
lemma reverse_involutive : Function.Involutive (reverse : Language α → _) :=
List.reverse_involutive.preimage
lemma reverse_bijective : Function.Bijective (reverse : Language α → _) :=
reverse_involutive.bijective
lemma reverse_injective : Function.Injective (reverse : Language α → _) :=
reverse_involutive.injective
lemma reverse_surjective : Function.Surjective (reverse : Language α → _) :=
reverse_involutive.surjective
@[simp]
lemma reverse_reverse (l : Language α) : l.reverse.reverse = l := reverse_involutive l
@[simp]
lemma reverse_add (l m : Language α) : (l + m).reverse = l.reverse + m.reverse := rfl
@[simp]
lemma reverse_mul (l m : Language α) : (l * m).reverse = m.reverse * l.reverse := by
simp only [mul_def, reverse_eq_image, image2_image_left, image2_image_right, image_image2,
List.reverse_append]
apply image2_swap
@[simp]
lemma reverse_iSup {ι : Sort*} (l : ι → Language α) : (⨆ i, l i).reverse = ⨆ i, (l i).reverse :=
preimage_iUnion
@[simp]
lemma reverse_iInf {ι : Sort*} (l : ι → Language α) : (⨅ i, l i).reverse = ⨅ i, (l i).reverse :=
preimage_iInter
variable (α) in
/-- `Language.reverse` as a ring isomorphism to the opposite ring. -/
@[simps]
def reverseIso : Language α ≃+* (Language α)ᵐᵒᵖ where
toFun l := .op l.reverse
invFun l' := l'.unop.reverse
left_inv := reverse_reverse
right_inv l' := MulOpposite.unop_injective <| reverse_reverse l'.unop
map_mul' l₁ l₂ := MulOpposite.unop_injective <| reverse_mul l₁ l₂
map_add' l₁ l₂ := MulOpposite.unop_injective <| reverse_add l₁ l₂
@[simp]
lemma reverse_pow (l : Language α) (n : ℕ) : (l ^ n).reverse = l.reverse ^ n :=
MulOpposite.op_injective (map_pow (reverseIso α) l n)
@[simp]
lemma reverse_kstar (l : Language α) : l∗.reverse = l.reverse∗ := by
simp only [kstar_eq_iSup_pow, reverse_iSup, reverse_pow]
end Language
/-- Symbols for use by all kinds of grammars. -/
inductive Symbol (T N : Type*)
/-- Terminal symbols (of the same type as the language) -/
| terminal (t : T) : Symbol T N
/-- Nonterminal symbols (must not be present when the word being generated is finalized) -/
| nonterminal (n : N) : Symbol T N
deriving
DecidableEq, Repr, Fintype
attribute [nolint docBlame] Symbol.proxyType Symbol.proxyTypeEquiv |
.lake/packages/mathlib/Mathlib/Computability/PartrecCode.lean | import Mathlib.Computability.Partrec
import Mathlib.Data.Option.Basic
/-!
# Gödel Numbering for Partial Recursive Functions.
This file defines `Nat.Partrec.Code`, an inductive datatype describing code for partial
recursive functions on ℕ. It defines an encoding for these codes, and proves that the constructors
are primitive recursive with respect to the encoding.
It also defines the evaluation of these codes as partial functions using `PFun`, and proves that a
function is partially recursive (as defined by `Nat.Partrec`) if and only if it is the evaluation
of some code.
## Main Definitions
* `Nat.Partrec.Code`: Inductive datatype for partial recursive codes.
* `Nat.Partrec.Code.encodeCode`: A (computable) encoding of codes as natural numbers.
* `Nat.Partrec.Code.ofNatCode`: The inverse of this encoding.
* `Nat.Partrec.Code.eval`: The interpretation of a `Nat.Partrec.Code` as a partial function.
## Main Results
* `Nat.Partrec.Code.rec_prim`: Recursion on `Nat.Partrec.Code` is primitive recursive.
* `Nat.Partrec.Code.rec_computable`: Recursion on `Nat.Partrec.Code` is computable.
* `Nat.Partrec.Code.smn`: The $S_n^m$ theorem.
* `Nat.Partrec.Code.exists_code`: Partial recursiveness is equivalent to being the eval of a code.
* `Nat.Partrec.Code.evaln_prim`: `evaln` is primitive recursive.
* `Nat.Partrec.Code.fixed_point`: Roger's fixed point theorem.
* `Nat.Partrec.Code.fixed_point₂`: Kleene's second recursion theorem.
## References
* [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019]
-/
open Encodable Denumerable
namespace Nat.Partrec
theorem rfind' {f} (hf : Nat.Partrec f) :
Nat.Partrec
(Nat.unpaired fun a m =>
(Nat.rfind fun n => (fun m => m = 0) <$> f (Nat.pair a (n + m))).map (· + m)) :=
Partrec₂.unpaired'.2 <| by
refine
Partrec.map
((@Partrec₂.unpaired' fun a b : ℕ =>
Nat.rfind fun n => (fun m => m = 0) <$> f (Nat.pair a (n + b))).1
?_)
(Primrec.nat_add.comp Primrec.snd <| Primrec.snd.comp Primrec.fst).to_comp.to₂
have : Nat.Partrec (fun a => Nat.rfind (fun n => (fun m => decide (m = 0)) <$>
Nat.unpaired (fun a b => f (Nat.pair (Nat.unpair a).1 (b + (Nat.unpair a).2)))
(Nat.pair a n))) :=
rfind
(Partrec₂.unpaired'.2
((Partrec.nat_iff.2 hf).comp
(Primrec₂.pair.comp (Primrec.fst.comp <| Primrec.unpair.comp Primrec.fst)
(Primrec.nat_add.comp Primrec.snd
(Primrec.snd.comp <| Primrec.unpair.comp Primrec.fst))).to_comp))
simpa
/-- Code for partial recursive functions from ℕ to ℕ.
See `Nat.Partrec.Code.eval` for the interpretation of these constructors.
-/
inductive Code : Type
| zero : Code
| succ : Code
| left : Code
| right : Code
| pair : Code → Code → Code
| comp : Code → Code → Code
| prec : Code → Code → Code
| rfind' : Code → Code
compile_inductive% Code
end Nat.Partrec
namespace Nat.Partrec.Code
instance instInhabited : Inhabited Code :=
⟨zero⟩
/-- Returns a code for the constant function outputting a particular natural. -/
protected def const : ℕ → Code
| 0 => zero
| n + 1 => comp succ (Code.const n)
theorem const_inj : ∀ {n₁ n₂}, Nat.Partrec.Code.const n₁ = Nat.Partrec.Code.const n₂ → n₁ = n₂
| 0, 0, _ => by simp
| n₁ + 1, n₂ + 1, h => by
dsimp [Nat.Partrec.Code.const] at h
injection h with h₁ h₂
simp only [const_inj h₂]
/-- A code for the identity function. -/
protected def id : Code :=
pair left right
/-- Given a code `c` taking a pair as input, returns a code using `n` as the first argument to `c`.
-/
def curry (c : Code) (n : ℕ) : Code :=
comp c (pair (Code.const n) Code.id)
/-- An encoding of a `Nat.Partrec.Code` as a ℕ. -/
def encodeCode : Code → ℕ
| zero => 0
| succ => 1
| left => 2
| right => 3
| pair cf cg => 2 * (2 * Nat.pair (encodeCode cf) (encodeCode cg)) + 4
| comp cf cg => 2 * (2 * Nat.pair (encodeCode cf) (encodeCode cg) + 1) + 4
| prec cf cg => (2 * (2 * Nat.pair (encodeCode cf) (encodeCode cg)) + 1) + 4
| rfind' cf => (2 * (2 * encodeCode cf + 1) + 1) + 4
/--
A decoder for `Nat.Partrec.Code.encodeCode`, taking any ℕ to the `Nat.Partrec.Code` it represents.
-/
def ofNatCode : ℕ → Code
| 0 => zero
| 1 => succ
| 2 => left
| 3 => right
| n + 4 =>
let m := n.div2.div2
have hm : m < n + 4 := by
simp only [m, div2_val]
exact
lt_of_le_of_lt (le_trans (Nat.div_le_self _ _) (Nat.div_le_self _ _))
(Nat.succ_le_succ (Nat.le_add_right _ _))
have _m1 : m.unpair.1 < n + 4 := lt_of_le_of_lt m.unpair_left_le hm
have _m2 : m.unpair.2 < n + 4 := lt_of_le_of_lt m.unpair_right_le hm
match n.bodd, n.div2.bodd with
| false, false => pair (ofNatCode m.unpair.1) (ofNatCode m.unpair.2)
| false, true => comp (ofNatCode m.unpair.1) (ofNatCode m.unpair.2)
| true, false => prec (ofNatCode m.unpair.1) (ofNatCode m.unpair.2)
| true, true => rfind' (ofNatCode m)
/-- Proof that `Nat.Partrec.Code.ofNatCode` is the inverse of `Nat.Partrec.Code.encodeCode` -/
private theorem encode_ofNatCode : ∀ n, encodeCode (ofNatCode n) = n
| 0 => by simp [ofNatCode, encodeCode]
| 1 => by simp [ofNatCode, encodeCode]
| 2 => by simp [ofNatCode, encodeCode]
| 3 => by simp [ofNatCode, encodeCode]
| n + 4 => by
let m := n.div2.div2
have hm : m < n + 4 := by
simp only [m, div2_val]
exact
lt_of_le_of_lt (le_trans (Nat.div_le_self _ _) (Nat.div_le_self _ _))
(Nat.succ_le_succ (Nat.le_add_right _ _))
have _m1 : m.unpair.1 < n + 4 := lt_of_le_of_lt m.unpair_left_le hm
have _m2 : m.unpair.2 < n + 4 := lt_of_le_of_lt m.unpair_right_le hm
have IH := encode_ofNatCode m
have IH1 := encode_ofNatCode m.unpair.1
have IH2 := encode_ofNatCode m.unpair.2
conv_rhs => rw [← Nat.bit_bodd_div2 n, ← Nat.bit_bodd_div2 n.div2]
simp only [ofNatCode.eq_5]
cases n.bodd <;> cases n.div2.bodd <;>
simp [m, encodeCode, IH, IH1, IH2, Nat.bit_val]
instance instDenumerable : Denumerable Code :=
mk'
⟨encodeCode, ofNatCode, fun c => by
induction c <;> simp [encodeCode, ofNatCode, Nat.div2_val, *],
encode_ofNatCode⟩
theorem encodeCode_eq : encode = encodeCode :=
rfl
theorem ofNatCode_eq : ofNat Code = ofNatCode :=
rfl
theorem encode_lt_pair (cf cg) :
encode cf < encode (pair cf cg) ∧ encode cg < encode (pair cf cg) := by
simp only [encodeCode_eq, encodeCode]
have := Nat.mul_le_mul_right (Nat.pair cf.encodeCode cg.encodeCode) (by decide : 1 ≤ 2 * 2)
rw [one_mul, mul_assoc] at this
have := lt_of_le_of_lt this (lt_add_of_pos_right _ (by decide : 0 < 4))
exact ⟨lt_of_le_of_lt (Nat.left_le_pair _ _) this, lt_of_le_of_lt (Nat.right_le_pair _ _) this⟩
theorem encode_lt_comp (cf cg) :
encode cf < encode (comp cf cg) ∧ encode cg < encode (comp cf cg) := by
have : encode (pair cf cg) < encode (comp cf cg) := by simp [encodeCode_eq, encodeCode]
exact (encode_lt_pair cf cg).imp (fun h => lt_trans h this) fun h => lt_trans h this
theorem encode_lt_prec (cf cg) :
encode cf < encode (prec cf cg) ∧ encode cg < encode (prec cf cg) := by
have : encode (pair cf cg) < encode (prec cf cg) := by simp [encodeCode_eq, encodeCode]
exact (encode_lt_pair cf cg).imp (fun h => lt_trans h this) fun h => lt_trans h this
theorem encode_lt_rfind' (cf) : encode cf < encode (rfind' cf) := by
simp only [encodeCode_eq, encodeCode]
cutsat
end Nat.Partrec.Code
section
open Primrec
namespace Nat.Partrec.Code
theorem primrec₂_pair : Primrec₂ pair :=
Primrec₂.ofNat_iff.2 <|
Primrec₂.encode_iff.1 <|
nat_add.comp
(nat_double.comp <|
nat_double.comp <|
Primrec₂.natPair.comp (encode_iff.2 <| (Primrec.ofNat Code).comp fst)
(encode_iff.2 <| (Primrec.ofNat Code).comp snd))
(Primrec₂.const 4)
@[deprecated (since := "2025-05-12")] alias pair_prim := primrec₂_pair
theorem primrec₂_comp : Primrec₂ comp :=
Primrec₂.ofNat_iff.2 <|
Primrec₂.encode_iff.1 <|
nat_add.comp
(nat_double.comp <|
nat_double_succ.comp <|
Primrec₂.natPair.comp (encode_iff.2 <| (Primrec.ofNat Code).comp fst)
(encode_iff.2 <| (Primrec.ofNat Code).comp snd))
(Primrec₂.const 4)
@[deprecated (since := "2025-05-12")] alias comp_prim := primrec₂_comp
theorem primrec₂_prec : Primrec₂ prec :=
Primrec₂.ofNat_iff.2 <|
Primrec₂.encode_iff.1 <|
nat_add.comp
(nat_double_succ.comp <|
nat_double.comp <|
Primrec₂.natPair.comp (encode_iff.2 <| (Primrec.ofNat Code).comp fst)
(encode_iff.2 <| (Primrec.ofNat Code).comp snd))
(Primrec₂.const 4)
@[deprecated (since := "2025-05-12")] alias prec_prim := primrec₂_prec
theorem primrec_rfind' : Primrec rfind' :=
ofNat_iff.2 <|
encode_iff.1 <|
nat_add.comp
(nat_double_succ.comp <| nat_double_succ.comp <|
encode_iff.2 <| Primrec.ofNat Code)
(const 4)
@[deprecated (since := "2025-05-12")] alias rfind_prim := primrec_rfind'
theorem primrec_recOn' {α σ}
[Primcodable α] [Primcodable σ] {c : α → Code} (hc : Primrec c) {z : α → σ}
(hz : Primrec z) {s : α → σ} (hs : Primrec s) {l : α → σ} (hl : Primrec l) {r : α → σ}
(hr : Primrec r) {pr : α → Code × Code × σ × σ → σ} (hpr : Primrec₂ pr)
{co : α → Code × Code × σ × σ → σ} (hco : Primrec₂ co) {pc : α → Code × Code × σ × σ → σ}
(hpc : Primrec₂ pc) {rf : α → Code × σ → σ} (hrf : Primrec₂ rf) :
let PR (a) cf cg hf hg := pr a (cf, cg, hf, hg)
let CO (a) cf cg hf hg := co a (cf, cg, hf, hg)
let PC (a) cf cg hf hg := pc a (cf, cg, hf, hg)
let RF (a) cf hf := rf a (cf, hf)
let F (a : α) (c : Code) : σ :=
Nat.Partrec.Code.recOn c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a)
Primrec (fun a => F a (c a) : α → σ) := by
intro _ _ _ _ F
let G₁ : (α × List σ) × ℕ × ℕ → Option σ := fun p =>
letI a := p.1.1; letI IH := p.1.2; letI n := p.2.1; letI m := p.2.2
IH[m]?.bind fun s =>
IH[m.unpair.1]?.bind fun s₁ =>
IH[m.unpair.2]?.map fun s₂ =>
cond n.bodd
(cond n.div2.bodd (rf a (ofNat Code m, s))
(pc a (ofNat Code m.unpair.1, ofNat Code m.unpair.2, s₁, s₂)))
(cond n.div2.bodd (co a (ofNat Code m.unpair.1, ofNat Code m.unpair.2, s₁, s₂))
(pr a (ofNat Code m.unpair.1, ofNat Code m.unpair.2, s₁, s₂)))
have : Primrec G₁ :=
option_bind (list_getElem?.comp (snd.comp fst) (snd.comp snd)) <| .mk <|
option_bind ((list_getElem?.comp (snd.comp fst)
(fst.comp <| Primrec.unpair.comp (snd.comp snd))).comp fst) <| .mk <|
option_map ((list_getElem?.comp (snd.comp fst)
(snd.comp <| Primrec.unpair.comp (snd.comp snd))).comp <| fst.comp fst) <| .mk <|
have a := fst.comp (fst.comp <| fst.comp <| fst.comp fst)
have n := fst.comp (snd.comp <| fst.comp <| fst.comp fst)
have m := snd.comp (snd.comp <| fst.comp <| fst.comp fst)
have m₁ := fst.comp (Primrec.unpair.comp m)
have m₂ := snd.comp (Primrec.unpair.comp m)
have s := snd.comp (fst.comp fst)
have s₁ := snd.comp fst
have s₂ := snd
(nat_bodd.comp n).cond
((nat_bodd.comp <| nat_div2.comp n).cond
(hrf.comp a (((Primrec.ofNat Code).comp m).pair s))
(hpc.comp a (((Primrec.ofNat Code).comp m₁).pair <|
((Primrec.ofNat Code).comp m₂).pair <| s₁.pair s₂)))
(Primrec.cond (nat_bodd.comp <| nat_div2.comp n)
(hco.comp a (((Primrec.ofNat Code).comp m₁).pair <|
((Primrec.ofNat Code).comp m₂).pair <| s₁.pair s₂))
(hpr.comp a (((Primrec.ofNat Code).comp m₁).pair <|
((Primrec.ofNat Code).comp m₂).pair <| s₁.pair s₂)))
let G : α → List σ → Option σ := fun a IH =>
IH.length.casesOn (some (z a)) fun n =>
n.casesOn (some (s a)) fun n =>
n.casesOn (some (l a)) fun n =>
n.casesOn (some (r a)) fun n =>
G₁ ((a, IH), n, n.div2.div2)
have : Primrec₂ G := .mk <|
nat_casesOn (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) <| .mk <|
nat_casesOn snd (option_some_iff.2 (hs.comp (fst.comp fst))) <| .mk <|
nat_casesOn snd (option_some_iff.2 (hl.comp (fst.comp <| fst.comp fst))) <| .mk <|
nat_casesOn snd (option_some_iff.2 (hr.comp (fst.comp <| fst.comp <| fst.comp fst))) <| .mk <|
this.comp <|
((fst.pair snd).comp <| fst.comp <| fst.comp <| fst.comp <| fst).pair <|
snd.pair <| nat_div2.comp <| nat_div2.comp snd
refine (nat_strong_rec (fun a n => F a (ofNat Code n)) this.to₂ fun a n => ?_)
|>.comp .id (encode_iff.2 hc) |>.of_eq fun a => by simp
iterate 4 rcases n with - | n; · simp [ofNatCode_eq, ofNatCode]; rfl
simp only [G]; rw [List.length_map, List.length_range]
let m := n.div2.div2
change G₁ ((a, (List.range (n + 4)).map fun n => F a (ofNat Code n)), n, m)
= some (F a (ofNat Code (n + 4)))
have hm : m < n + 4 := by
simp only [m, div2_val]
exact lt_of_le_of_lt
(le_trans (Nat.div_le_self ..) (Nat.div_le_self ..))
(Nat.succ_le_succ (Nat.le_add_right ..))
have m1 : m.unpair.1 < n + 4 := lt_of_le_of_lt m.unpair_left_le hm
have m2 : m.unpair.2 < n + 4 := lt_of_le_of_lt m.unpair_right_le hm
simp [G₁, m, hm, m1, m2]
rw [show ofNat Code (n + 4) = ofNatCode (n + 4) from rfl]
simp [ofNatCode]
cases n.bodd <;> cases n.div2.bodd <;> rfl
@[deprecated (since := "2025-05-12")] alias rec_prim' := primrec_recOn'
/-- Recursion on `Nat.Partrec.Code` is primitive recursive. -/
theorem primrec_recOn {α σ}
[Primcodable α] [Primcodable σ] {c : α → Code} (hc : Primrec c) {z : α → σ}
(hz : Primrec z) {s : α → σ} (hs : Primrec s) {l : α → σ} (hl : Primrec l) {r : α → σ}
(hr : Primrec r) {pr : α → Code → Code → σ → σ → σ}
(hpr : Primrec fun a : α × Code × Code × σ × σ => pr a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)
{co : α → Code → Code → σ → σ → σ}
(hco : Primrec fun a : α × Code × Code × σ × σ => co a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)
{pc : α → Code → Code → σ → σ → σ}
(hpc : Primrec fun a : α × Code × Code × σ × σ => pc a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)
{rf : α → Code → σ → σ} (hrf : Primrec fun a : α × Code × σ => rf a.1 a.2.1 a.2.2) :
let F (a : α) (c : Code) : σ :=
Nat.Partrec.Code.recOn c (z a) (s a) (l a) (r a) (pr a) (co a) (pc a) (rf a)
Primrec fun a => F a (c a) :=
primrec_recOn' hc hz hs hl hr
(pr := fun a b => pr a b.1 b.2.1 b.2.2.1 b.2.2.2) (.mk hpr)
(co := fun a b => co a b.1 b.2.1 b.2.2.1 b.2.2.2) (.mk hco)
(pc := fun a b => pc a b.1 b.2.1 b.2.2.1 b.2.2.2) (.mk hpc)
(rf := fun a b => rf a b.1 b.2) (.mk hrf)
@[deprecated (since := "2025-05-12")] alias rec_prim := primrec_recOn
end Nat.Partrec.Code
end
namespace Nat.Partrec.Code
section
open Computable
/-- Recursion on `Nat.Partrec.Code` is computable. -/
theorem computable_recOn {α σ} [Primcodable α] [Primcodable σ] {c : α → Code} (hc : Computable c)
{z : α → σ} (hz : Computable z) {s : α → σ} (hs : Computable s) {l : α → σ} (hl : Computable l)
{r : α → σ} (hr : Computable r) {pr : α → Code × Code × σ × σ → σ} (hpr : Computable₂ pr)
{co : α → Code × Code × σ × σ → σ} (hco : Computable₂ co) {pc : α → Code × Code × σ × σ → σ}
(hpc : Computable₂ pc) {rf : α → Code × σ → σ} (hrf : Computable₂ rf) :
let PR (a) cf cg hf hg := pr a (cf, cg, hf, hg)
let CO (a) cf cg hf hg := co a (cf, cg, hf, hg)
let PC (a) cf cg hf hg := pc a (cf, cg, hf, hg)
let RF (a) cf hf := rf a (cf, hf)
let F (a : α) (c : Code) : σ :=
Nat.Partrec.Code.recOn c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a)
Computable fun a => F a (c a) := by
-- TODO(Mario): less copy-paste from previous proof
intro _ _ _ _ F
let G₁ : (α × List σ) × ℕ × ℕ → Option σ := fun p =>
letI a := p.1.1; letI IH := p.1.2; letI n := p.2.1; letI m := p.2.2
IH[m]?.bind fun s =>
IH[m.unpair.1]?.bind fun s₁ =>
IH[m.unpair.2]?.map fun s₂ =>
cond n.bodd
(cond n.div2.bodd (rf a (ofNat Code m, s))
(pc a (ofNat Code m.unpair.1, ofNat Code m.unpair.2, s₁, s₂)))
(cond n.div2.bodd (co a (ofNat Code m.unpair.1, ofNat Code m.unpair.2, s₁, s₂))
(pr a (ofNat Code m.unpair.1, ofNat Code m.unpair.2, s₁, s₂)))
have : Computable G₁ := by
refine option_bind (list_getElem?.comp (snd.comp fst) (snd.comp snd)) <| .mk ?_
refine option_bind ((list_getElem?.comp (snd.comp fst)
(fst.comp <| Computable.unpair.comp (snd.comp snd))).comp fst) <| .mk ?_
refine option_map ((list_getElem?.comp (snd.comp fst)
(snd.comp <| Computable.unpair.comp (snd.comp snd))).comp <| fst.comp fst) <| .mk ?_
exact
have a := fst.comp (fst.comp <| fst.comp <| fst.comp fst)
have n := fst.comp (snd.comp <| fst.comp <| fst.comp fst)
have m := snd.comp (snd.comp <| fst.comp <| fst.comp fst)
have m₁ := fst.comp (Computable.unpair.comp m)
have m₂ := snd.comp (Computable.unpair.comp m)
have s := snd.comp (fst.comp fst)
have s₁ := snd.comp fst
have s₂ := snd
(nat_bodd.comp n).cond
((nat_bodd.comp <| nat_div2.comp n).cond
(hrf.comp a (((Computable.ofNat Code).comp m).pair s))
(hpc.comp a (((Computable.ofNat Code).comp m₁).pair <|
((Computable.ofNat Code).comp m₂).pair <| s₁.pair s₂)))
(Computable.cond (nat_bodd.comp <| nat_div2.comp n)
(hco.comp a (((Computable.ofNat Code).comp m₁).pair <|
((Computable.ofNat Code).comp m₂).pair <| s₁.pair s₂))
(hpr.comp a (((Computable.ofNat Code).comp m₁).pair <|
((Computable.ofNat Code).comp m₂).pair <| s₁.pair s₂)))
let G : α → List σ → Option σ := fun a IH =>
IH.length.casesOn (some (z a)) fun n =>
n.casesOn (some (s a)) fun n =>
n.casesOn (some (l a)) fun n =>
n.casesOn (some (r a)) fun n =>
G₁ ((a, IH), n, n.div2.div2)
have : Computable₂ G := .mk <|
nat_casesOn (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) <| .mk <|
nat_casesOn snd (option_some_iff.2 (hs.comp (fst.comp fst))) <| .mk <|
nat_casesOn snd (option_some_iff.2 (hl.comp (fst.comp <| fst.comp fst))) <| .mk <|
nat_casesOn snd (option_some_iff.2 (hr.comp (fst.comp <| fst.comp <| fst.comp fst))) <| .mk <|
this.comp <|
((fst.pair snd).comp <| fst.comp <| fst.comp <| fst.comp <| fst).pair <|
snd.pair <| nat_div2.comp <| nat_div2.comp snd
refine (nat_strong_rec (fun a n => F a (ofNat Code n)) this.to₂ fun a n => ?_)
|>.comp .id (encode_iff.2 hc) |>.of_eq fun a => by simp
iterate 4 rcases n with - | n; · simp [ofNatCode_eq, ofNatCode]; rfl
simp only [G]; rw [List.length_map, List.length_range]
let m := n.div2.div2
change G₁ ((a, (List.range (n + 4)).map fun n => F a (ofNat Code n)), n, m)
= some (F a (ofNat Code (n + 4)))
have hm : m < n + 4 := by
simp only [m, div2_val]
exact lt_of_le_of_lt
(le_trans (Nat.div_le_self ..) (Nat.div_le_self ..))
(Nat.succ_le_succ (Nat.le_add_right ..))
have m1 : m.unpair.1 < n + 4 := lt_of_le_of_lt m.unpair_left_le hm
have m2 : m.unpair.2 < n + 4 := lt_of_le_of_lt m.unpair_right_le hm
simp [G₁, m, hm, m1, m2]
rw [show ofNat Code (n + 4) = ofNatCode (n + 4) from rfl]
simp [ofNatCode]
cases n.bodd <;> cases n.div2.bodd <;> rfl
@[deprecated (since := "2025-05-12")] alias rec_computable := computable_recOn
end
/-- The interpretation of a `Nat.Partrec.Code` as a partial function.
* `Nat.Partrec.Code.zero`: The constant zero function.
* `Nat.Partrec.Code.succ`: The successor function.
* `Nat.Partrec.Code.left`: Left unpairing of a pair of ℕ (encoded by `Nat.pair`)
* `Nat.Partrec.Code.right`: Right unpairing of a pair of ℕ (encoded by `Nat.pair`)
* `Nat.Partrec.Code.pair`: Pairs the outputs of argument codes using `Nat.pair`.
* `Nat.Partrec.Code.comp`: Composition of two argument codes.
* `Nat.Partrec.Code.prec`: Primitive recursion. Given an argument of the form `Nat.pair a n`:
* If `n = 0`, returns `eval cf a`.
* If `n = succ k`, returns `eval cg (pair a (pair k (eval (prec cf cg) (pair a k))))`
* `Nat.Partrec.Code.rfind'`: Minimization. For `f` an argument of the form `Nat.pair a m`,
`rfind' f m` returns the least `a` such that `f a m = 0`, if one exists and `f b m` terminates
for `b < a`
-/
def eval : Code → ℕ →. ℕ
| zero => pure 0
| succ => Nat.succ
| left => ↑fun n : ℕ => n.unpair.1
| right => ↑fun n : ℕ => n.unpair.2
| pair cf cg => fun n => Nat.pair <$> eval cf n <*> eval cg n
| comp cf cg => fun n => eval cg n >>= eval cf
| prec cf cg =>
Nat.unpaired fun a n =>
n.rec (eval cf a) fun y IH => do
let i ← IH
eval cg (Nat.pair a (Nat.pair y i))
| rfind' cf =>
Nat.unpaired fun a m =>
(Nat.rfind fun n => (fun m => m = 0) <$> eval cf (Nat.pair a (n + m))).map (· + m)
/-- Helper lemma for the evaluation of `prec` in the base case. -/
@[simp]
theorem eval_prec_zero (cf cg : Code) (a : ℕ) : eval (prec cf cg) (Nat.pair a 0) = eval cf a := by
rw [eval, Nat.unpaired, Nat.unpair_pair]
simp (config := { Lean.Meta.Simp.neutralConfig with proj := true }) only []
rw [Nat.rec_zero]
/-- Helper lemma for the evaluation of `prec` in the recursive case. -/
theorem eval_prec_succ (cf cg : Code) (a k : ℕ) :
eval (prec cf cg) (Nat.pair a (Nat.succ k)) =
do {let ih ← eval (prec cf cg) (Nat.pair a k); eval cg (Nat.pair a (Nat.pair k ih))} := by
rw [eval, Nat.unpaired, Part.bind_eq_bind, Nat.unpair_pair]
simp
instance : Membership (ℕ →. ℕ) Code :=
⟨fun c f => eval c = f⟩
@[simp]
theorem eval_const : ∀ n m, eval (Code.const n) m = Part.some n
| 0, _ => rfl
| n + 1, m => by simp! [eval_const n m]
@[simp]
theorem eval_id (n) : eval Code.id n = Part.some n := by simp! [Seq.seq, Code.id]
@[simp]
theorem eval_curry (c n x) : eval (curry c n) x = eval c (Nat.pair n x) := by simp! [Seq.seq, curry]
theorem primrec_const : Primrec Code.const :=
(_root_.Primrec.id.nat_iterate (_root_.Primrec.const zero)
(primrec₂_comp.comp (_root_.Primrec.const succ) Primrec.snd).to₂).of_eq
fun n => by simp; induction n <;>
simp [*, Code.const, Function.iterate_succ', -Function.iterate_succ]
@[deprecated (since := "2025-05-12")] alias const_prim := primrec_const
theorem primrec₂_curry : Primrec₂ curry :=
primrec₂_comp.comp Primrec.fst <| primrec₂_pair.comp (primrec_const.comp Primrec.snd)
(_root_.Primrec.const Code.id)
@[deprecated (since := "2025-05-12")] alias curry_prim := primrec₂_curry
theorem curry_inj {c₁ c₂ n₁ n₂} (h : curry c₁ n₁ = curry c₂ n₂) : c₁ = c₂ ∧ n₁ = n₂ :=
⟨by injection h, by
injection h with h₁ h₂
injection h₂ with h₃ h₄
exact const_inj h₃⟩
/--
The $S_n^m$ theorem: There is a computable function, namely `Nat.Partrec.Code.curry`, that takes a
program and a ℕ `n`, and returns a new program using `n` as the first argument.
-/
theorem smn :
∃ f : Code → ℕ → Code, Computable₂ f ∧ ∀ c n x, eval (f c n) x = eval c (Nat.pair n x) :=
⟨curry, Primrec₂.to_comp primrec₂_curry, eval_curry⟩
/-- A function is partial recursive if and only if there is a code implementing it. Therefore,
`eval` is a **universal partial recursive function**. -/
theorem exists_code {f : ℕ →. ℕ} : Nat.Partrec f ↔ ∃ c : Code, eval c = f := by
refine ⟨fun h => ?_, ?_⟩
· induction h with
| zero => exact ⟨zero, rfl⟩
| succ => exact ⟨succ, rfl⟩
| left => exact ⟨left, rfl⟩
| right => exact ⟨right, rfl⟩
| pair pf pg hf hg =>
rcases hf with ⟨cf, rfl⟩; rcases hg with ⟨cg, rfl⟩
exact ⟨pair cf cg, rfl⟩
| comp pf pg hf hg =>
rcases hf with ⟨cf, rfl⟩; rcases hg with ⟨cg, rfl⟩
exact ⟨comp cf cg, rfl⟩
| prec pf pg hf hg =>
rcases hf with ⟨cf, rfl⟩; rcases hg with ⟨cg, rfl⟩
exact ⟨prec cf cg, rfl⟩
| rfind pf hf =>
rcases hf with ⟨cf, rfl⟩
refine ⟨comp (rfind' cf) (pair Code.id zero), ?_⟩
simp [eval, Seq.seq, pure, PFun.pure, Part.map_id']
· rintro ⟨c, rfl⟩
induction c with
| zero => exact Nat.Partrec.zero
| succ => exact Nat.Partrec.succ
| left => exact Nat.Partrec.left
| right => exact Nat.Partrec.right
| pair cf cg pf pg => exact pf.pair pg
| comp cf cg pf pg => exact pf.comp pg
| prec cf cg pf pg => exact pf.prec pg
| rfind' cf pf => exact pf.rfind'
/-- A modified evaluation for the code which returns an `Option ℕ` instead of a `Part ℕ`. To avoid
undecidability, `evaln` takes a parameter `k` and fails if it encounters a number ≥ k in the course
of its execution. Other than this, the semantics are the same as in `Nat.Partrec.Code.eval`.
-/
def evaln : ℕ → Code → ℕ → Option ℕ
| 0, _ => fun _ => Option.none
| k + 1, zero => fun n => do
guard (n ≤ k)
return 0
| k + 1, succ => fun n => do
guard (n ≤ k)
return (Nat.succ n)
| k + 1, left => fun n => do
guard (n ≤ k)
return n.unpair.1
| k + 1, right => fun n => do
guard (n ≤ k)
pure n.unpair.2
| k + 1, pair cf cg => fun n => do
guard (n ≤ k)
Nat.pair <$> evaln (k + 1) cf n <*> evaln (k + 1) cg n
| k + 1, comp cf cg => fun n => do
guard (n ≤ k)
let x ← evaln (k + 1) cg n
evaln (k + 1) cf x
| k + 1, prec cf cg => fun n => do
guard (n ≤ k)
n.unpaired fun a n =>
n.casesOn (evaln (k + 1) cf a) fun y => do
let i ← evaln k (prec cf cg) (Nat.pair a y)
evaln (k + 1) cg (Nat.pair a (Nat.pair y i))
| k + 1, rfind' cf => fun n => do
guard (n ≤ k)
n.unpaired fun a m => do
let x ← evaln (k + 1) cf (Nat.pair a m)
if x = 0 then
pure m
else
evaln k (rfind' cf) (Nat.pair a (m + 1))
theorem evaln_bound : ∀ {k c n x}, x ∈ evaln k c n → n < k
| 0, c, n, x, h => by simp [evaln] at h
| k + 1, c, n, x, h => by
suffices ∀ {o : Option ℕ}, x ∈ do { guard (n ≤ k); o } → n < k + 1 by
cases c <;> rw [evaln] at h <;> exact this h
simpa [Option.bind_eq_some_iff] using Nat.lt_succ_of_le
theorem evaln_mono : ∀ {k₁ k₂ c n x}, k₁ ≤ k₂ → x ∈ evaln k₁ c n → x ∈ evaln k₂ c n
| 0, k₂, c, n, x, _, h => by simp [evaln] at h
| k + 1, k₂ + 1, c, n, x, hl, h => by
have hl' := Nat.le_of_succ_le_succ hl
have :
∀ {k k₂ n x : ℕ} {o₁ o₂ : Option ℕ},
k ≤ k₂ → (x ∈ o₁ → x ∈ o₂) →
x ∈ do { guard (n ≤ k); o₁ } → x ∈ do { guard (n ≤ k₂); o₂ } := by
simp only [Option.mem_def, bind, Option.bind_eq_some_iff, Option.guard_eq_some',
exists_and_left, exists_const, and_imp]
introv h h₁ h₂ h₃
exact ⟨le_trans h₂ h, h₁ h₃⟩
simp? at h ⊢ says simp only [Option.mem_def] at h ⊢
induction c generalizing x n <;> rw [evaln] at h ⊢ <;> refine this hl' (fun h => ?_) h
iterate 4 exact h
case pair cf cg hf hg _ =>
simp? [Seq.seq, Option.bind_eq_some_iff] at h ⊢ says
simp only [Seq.seq, Option.map_eq_map, Option.mem_def, Option.bind_eq_some_iff,
Option.map_eq_some_iff, exists_exists_and_eq_and] at h ⊢
exact h.imp fun a => And.imp (hf _ _) <| Exists.imp fun b => And.imp_left (hg _ _)
case comp cf cg hf hg _ =>
simp? [Bind.bind, Option.bind_eq_some_iff] at h ⊢ says
simp only [bind, Option.mem_def, Option.bind_eq_some_iff] at h ⊢
exact h.imp fun a => And.imp (hg _ _) (hf _ _)
case prec cf cg hf hg _ =>
revert h
simp only [unpaired, bind, Option.mem_def]
induction n.unpair.2 <;> simp [Option.bind_eq_some_iff]
· apply hf
· exact fun y h₁ h₂ => ⟨y, evaln_mono hl' h₁, hg _ _ h₂⟩
case rfind' cf hf _ =>
simp? [Bind.bind, Option.bind_eq_some_iff] at h ⊢ says
simp only [unpaired, bind, pair_unpair, Option.pure_def, Option.mem_def,
Option.bind_eq_some_iff] at h ⊢
refine h.imp fun x => And.imp (hf _ _) ?_
by_cases x0 : x = 0 <;> simp [x0]
exact evaln_mono hl'
theorem evaln_sound : ∀ {k c n x}, x ∈ evaln k c n → x ∈ eval c n
| 0, _, n, x, h => by simp [evaln] at h
| k + 1, c, n, x, h => by
induction c generalizing x n <;> simp [eval, evaln, Option.bind_eq_some_iff, Seq.seq] at h ⊢ <;>
obtain ⟨_, h⟩ := h
iterate 4 simpa [pure, PFun.pure, eq_comm] using h
case pair cf cg hf hg _ =>
rcases h with ⟨y, ef, z, eg, rfl⟩
exact ⟨_, hf _ _ ef, _, hg _ _ eg, rfl⟩
case comp cf cg hf hg _ =>
rcases h with ⟨y, eg, ef⟩
exact ⟨_, hg _ _ eg, hf _ _ ef⟩
case prec cf cg hf hg _ =>
revert h
induction n.unpair.2 generalizing x with simp [Option.bind_eq_some_iff]
| zero => apply hf
| succ m IH =>
refine fun y h₁ h₂ => ⟨y, IH _ ?_, ?_⟩
· have := evaln_mono k.le_succ h₁
simp [evaln, Option.bind_eq_some_iff] at this
exact this.2
· exact hg _ _ h₂
case rfind' cf hf _ =>
rcases h with ⟨m, h₁, h₂⟩
by_cases m0 : m = 0 <;> simp [m0] at h₂
· exact
⟨0, ⟨by simpa [m0] using hf _ _ h₁, fun {m} => (Nat.not_lt_zero _).elim⟩, by simp [h₂]⟩
· have := evaln_sound h₂
simp [eval] at this
rcases this with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩
refine
⟨y + 1, ⟨by simpa [add_comm, add_left_comm] using hy₁, fun {i} im => ?_⟩, by
simp [add_comm, add_left_comm]⟩
rcases i with - | i
· exact ⟨m, by simpa using hf _ _ h₁, m0⟩
· rcases hy₂ (Nat.lt_of_succ_lt_succ im) with ⟨z, hz, z0⟩
exact ⟨z, by simpa [add_comm, add_left_comm] using hz, z0⟩
theorem evaln_complete {c n x} : x ∈ eval c n ↔ ∃ k, x ∈ evaln k c n := by
refine ⟨fun h => ?_, fun ⟨k, h⟩ => evaln_sound h⟩
rsuffices ⟨k, h⟩ : ∃ k, x ∈ evaln (k + 1) c n
· exact ⟨k + 1, h⟩
induction c generalizing n x with
simp [eval, evaln, pure, PFun.pure, Seq.seq, Option.bind_eq_some_iff] at h ⊢
| pair cf cg hf hg =>
rcases h with ⟨x, hx, y, hy, rfl⟩
rcases hf hx with ⟨k₁, hk₁⟩; rcases hg hy with ⟨k₂, hk₂⟩
refine ⟨max k₁ k₂, ?_⟩
refine
⟨le_max_of_le_left <| Nat.le_of_lt_succ <| evaln_bound hk₁, _,
evaln_mono (Nat.succ_le_succ <| le_max_left _ _) hk₁, _,
evaln_mono (Nat.succ_le_succ <| le_max_right _ _) hk₂, rfl⟩
| comp cf cg hf hg =>
rcases h with ⟨y, hy, hx⟩
rcases hg hy with ⟨k₁, hk₁⟩; rcases hf hx with ⟨k₂, hk₂⟩
refine ⟨max k₁ k₂, ?_⟩
exact
⟨le_max_of_le_left <| Nat.le_of_lt_succ <| evaln_bound hk₁, _,
evaln_mono (Nat.succ_le_succ <| le_max_left _ _) hk₁,
evaln_mono (Nat.succ_le_succ <| le_max_right _ _) hk₂⟩
| prec cf cg hf hg =>
revert h
generalize n.unpair.1 = n₁; generalize n.unpair.2 = n₂
induction n₂ generalizing x n with simp [Option.bind_eq_some_iff]
| zero =>
intro h
rcases hf h with ⟨k, hk⟩
exact ⟨_, le_max_left _ _, evaln_mono (Nat.succ_le_succ <| le_max_right _ _) hk⟩
| succ m IH =>
intro y hy hx
rcases IH hy with ⟨k₁, nk₁, hk₁⟩
rcases hg hx with ⟨k₂, hk₂⟩
refine
⟨(max k₁ k₂).succ,
Nat.le_succ_of_le <| le_max_of_le_left <|
le_trans (le_max_left _ (Nat.pair n₁ m)) nk₁, y,
evaln_mono (Nat.succ_le_succ <| le_max_left _ _) ?_,
evaln_mono (Nat.succ_le_succ <| Nat.le_succ_of_le <| le_max_right _ _) hk₂⟩
simp only [evaln.eq_8, bind, unpaired, unpair_pair, Option.mem_def, Option.bind_eq_some_iff,
Option.guard_eq_some', exists_and_left, exists_const]
exact ⟨le_trans (le_max_right _ _) nk₁, hk₁⟩
| rfind' cf hf =>
rcases h with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩
suffices ∃ k, y + n.unpair.2 ∈ evaln (k + 1) (rfind' cf) (Nat.pair n.unpair.1 n.unpair.2) by
simpa [evaln, Option.bind_eq_some_iff]
revert hy₁ hy₂
generalize n.unpair.2 = m
intro hy₁ hy₂
induction y generalizing m with simp [evaln, Option.bind_eq_some_iff]
| zero =>
simp at hy₁
rcases hf hy₁ with ⟨k, hk⟩
exact ⟨_, Nat.le_of_lt_succ <| evaln_bound hk, _, hk, by simp⟩
| succ y IH =>
rcases hy₂ (Nat.succ_pos _) with ⟨a, ha, a0⟩
rcases hf ha with ⟨k₁, hk₁⟩
rcases IH m.succ (by simpa [Nat.succ_eq_add_one, add_comm, add_left_comm] using hy₁)
fun {i} hi => by
simpa [Nat.succ_eq_add_one, add_comm, add_left_comm] using
hy₂ (Nat.succ_lt_succ hi) with
⟨k₂, hk₂⟩
use (max k₁ k₂).succ
rw [zero_add] at hk₁
use Nat.le_succ_of_le <| le_max_of_le_left <| Nat.le_of_lt_succ <| evaln_bound hk₁
use a
use evaln_mono (Nat.succ_le_succ <| Nat.le_succ_of_le <| le_max_left _ _) hk₁
simpa [a0, add_comm, add_left_comm] using
evaln_mono (Nat.succ_le_succ <| le_max_right _ _) hk₂
| _ => exact ⟨⟨_, le_rfl⟩, h.symm⟩
section
open Primrec
private def lup (L : List (List (Option ℕ))) (p : ℕ × Code) (n : ℕ) := do
let l ← L[encode p]?
let o ← l[n]?
o
private theorem hlup : Primrec fun p : _ × (_ × _) × _ => lup p.1 p.2.1 p.2.2 :=
Primrec.option_bind
(Primrec.list_getElem?.comp Primrec.fst (Primrec.encode.comp <| Primrec.fst.comp Primrec.snd))
(Primrec.option_bind (Primrec.list_getElem?.comp Primrec.snd <| Primrec.snd.comp <|
Primrec.snd.comp Primrec.fst) Primrec.snd)
private def G (L : List (List (Option ℕ))) : Option (List (Option ℕ)) :=
Option.some <|
let a := ofNat (ℕ × Code) L.length
let k := a.1
let c := a.2
(List.range k).map fun n =>
k.casesOn Option.none fun k' =>
Nat.Partrec.Code.recOn c
(some 0) -- zero
(some (Nat.succ n))
(some n.unpair.1)
(some n.unpair.2)
(fun cf cg _ _ => do
let x ← lup L (k, cf) n
let y ← lup L (k, cg) n
some (Nat.pair x y))
(fun cf cg _ _ => do
let x ← lup L (k, cg) n
lup L (k, cf) x)
(fun cf cg _ _ =>
let z := n.unpair.1
n.unpair.2.casesOn (lup L (k, cf) z) fun y => do
let i ← lup L (k', c) (Nat.pair z y)
lup L (k, cg) (Nat.pair z (Nat.pair y i)))
(fun cf _ =>
let z := n.unpair.1
let m := n.unpair.2
do
let x ← lup L (k, cf) (Nat.pair z m)
x.casesOn (some m) fun _ => lup L (k', c) (Nat.pair z (m + 1)))
private theorem hG : Primrec G := by
have a := (Primrec.ofNat (ℕ × Code)).comp (Primrec.list_length (α := List (Option ℕ)))
have k := Primrec.fst.comp a
refine Primrec.option_some.comp (Primrec.list_map (Primrec.list_range.comp k) (?_ : Primrec _))
replace k := k.comp (Primrec.fst (β := ℕ))
have n := Primrec.snd (α := List (List (Option ℕ))) (β := ℕ)
refine Primrec.nat_casesOn k (_root_.Primrec.const Option.none) (?_ : Primrec _)
have k := k.comp (Primrec.fst (β := ℕ))
have n := n.comp (Primrec.fst (β := ℕ))
have k' := Primrec.snd (α := List (List (Option ℕ)) × ℕ) (β := ℕ)
have c := Primrec.snd.comp (a.comp <| (Primrec.fst (β := ℕ)).comp (Primrec.fst (β := ℕ)))
apply
Nat.Partrec.Code.primrec_recOn c
(_root_.Primrec.const (some 0))
(Primrec.option_some.comp (_root_.Primrec.succ.comp n))
(Primrec.option_some.comp (Primrec.fst.comp <| Primrec.unpair.comp n))
(Primrec.option_some.comp (Primrec.snd.comp <| Primrec.unpair.comp n))
· have L := (Primrec.fst.comp Primrec.fst).comp
(Primrec.fst (α := (List (List (Option ℕ)) × ℕ) × ℕ)
(β := Code × Code × Option ℕ × Option ℕ))
have k := k.comp (Primrec.fst (β := Code × Code × Option ℕ × Option ℕ))
have n := n.comp (Primrec.fst (β := Code × Code × Option ℕ × Option ℕ))
have cf := Primrec.fst.comp (Primrec.snd (α := (List (List (Option ℕ)) × ℕ) × ℕ)
(β := Code × Code × Option ℕ × Option ℕ))
have cg := (Primrec.fst.comp Primrec.snd).comp
(Primrec.snd (α := (List (List (Option ℕ)) × ℕ) × ℕ)
(β := Code × Code × Option ℕ × Option ℕ))
refine Primrec.option_bind (hlup.comp <| L.pair <| (k.pair cf).pair n) ?_
unfold Primrec₂
conv =>
congr
· ext p
dsimp only []
erw [Option.bind_eq_bind, ← Option.map_eq_bind]
refine Primrec.option_map ((hlup.comp <| L.pair <| (k.pair cg).pair n).comp Primrec.fst) ?_
unfold Primrec₂
exact Primrec₂.natPair.comp (Primrec.snd.comp Primrec.fst) Primrec.snd
· have L := (Primrec.fst.comp Primrec.fst).comp
(Primrec.fst (α := (List (List (Option ℕ)) × ℕ) × ℕ)
(β := Code × Code × Option ℕ × Option ℕ))
have k := k.comp (Primrec.fst (β := Code × Code × Option ℕ × Option ℕ))
have n := n.comp (Primrec.fst (β := Code × Code × Option ℕ × Option ℕ))
have cf := Primrec.fst.comp (Primrec.snd (α := (List (List (Option ℕ)) × ℕ) × ℕ)
(β := Code × Code × Option ℕ × Option ℕ))
have cg := (Primrec.fst.comp Primrec.snd).comp
(Primrec.snd (α := (List (List (Option ℕ)) × ℕ) × ℕ)
(β := Code × Code × Option ℕ × Option ℕ))
refine Primrec.option_bind (hlup.comp <| L.pair <| (k.pair cg).pair n) ?_
unfold Primrec₂
have h :=
hlup.comp ((L.comp Primrec.fst).pair <| ((k.pair cf).comp Primrec.fst).pair Primrec.snd)
exact h
· have L := (Primrec.fst.comp Primrec.fst).comp
(Primrec.fst (α := (List (List (Option ℕ)) × ℕ) × ℕ)
(β := Code × Code × Option ℕ × Option ℕ))
have k := k.comp (Primrec.fst (β := Code × Code × Option ℕ × Option ℕ))
have n := n.comp (Primrec.fst (β := Code × Code × Option ℕ × Option ℕ))
have cf := Primrec.fst.comp (Primrec.snd (α := (List (List (Option ℕ)) × ℕ) × ℕ)
(β := Code × Code × Option ℕ × Option ℕ))
have cg := (Primrec.fst.comp Primrec.snd).comp
(Primrec.snd (α := (List (List (Option ℕ)) × ℕ) × ℕ)
(β := Code × Code × Option ℕ × Option ℕ))
have z := Primrec.fst.comp (Primrec.unpair.comp n)
refine
Primrec.nat_casesOn (Primrec.snd.comp (Primrec.unpair.comp n))
(hlup.comp <| L.pair <| (k.pair cf).pair z)
(?_ : Primrec _)
have L := L.comp (Primrec.fst (β := ℕ))
have z := z.comp (Primrec.fst (β := ℕ))
have y := Primrec.snd
(α := ((List (List (Option ℕ)) × ℕ) × ℕ) × Code × Code × Option ℕ × Option ℕ) (β := ℕ)
have h₁ := hlup.comp <| L.pair <| (((k'.pair c).comp Primrec.fst).comp Primrec.fst).pair
(Primrec₂.natPair.comp z y)
refine Primrec.option_bind h₁ (?_ : Primrec _)
have z := z.comp (Primrec.fst (β := ℕ))
have y := y.comp (Primrec.fst (β := ℕ))
have i := Primrec.snd
(α := (((List (List (Option ℕ)) × ℕ) × ℕ) × Code × Code × Option ℕ × Option ℕ) × ℕ)
(β := ℕ)
have h₂ := hlup.comp ((L.comp Primrec.fst).pair <|
((k.pair cg).comp <| Primrec.fst.comp Primrec.fst).pair <|
Primrec₂.natPair.comp z <| Primrec₂.natPair.comp y i)
exact h₂
· have L := (Primrec.fst.comp Primrec.fst).comp
(Primrec.fst (α := (List (List (Option ℕ)) × ℕ) × ℕ)
(β := Code × Option ℕ))
have k := k.comp (Primrec.fst (β := Code × Option ℕ))
have n := n.comp (Primrec.fst (β := Code × Option ℕ))
have cf := Primrec.fst.comp (Primrec.snd (α := (List (List (Option ℕ)) × ℕ) × ℕ)
(β := Code × Option ℕ))
have z := Primrec.fst.comp (Primrec.unpair.comp n)
have m := Primrec.snd.comp (Primrec.unpair.comp n)
have h₁ := hlup.comp <| L.pair <| (k.pair cf).pair (Primrec₂.natPair.comp z m)
refine Primrec.option_bind h₁ (?_ : Primrec _)
have m := m.comp (Primrec.fst (β := ℕ))
refine Primrec.nat_casesOn Primrec.snd (Primrec.option_some.comp m) ?_
unfold Primrec₂
exact (hlup.comp ((L.comp Primrec.fst).pair <|
((k'.pair c).comp <| Primrec.fst.comp Primrec.fst).pair
(Primrec₂.natPair.comp (z.comp Primrec.fst) (_root_.Primrec.succ.comp m)))).comp
Primrec.fst
private theorem evaln_map (k c n) :
((List.range k)[n]?.bind fun a ↦ evaln k c a) = evaln k c n := by
by_cases kn : n < k
· simp [List.getElem?_range kn]
· rw [List.getElem?_eq_none]
· cases e : evaln k c n
· rfl
exact kn.elim (evaln_bound e)
simpa using kn
/-- The `Nat.Partrec.Code.evaln` function is primitive recursive. -/
theorem primrec_evaln : Primrec fun a : (ℕ × Code) × ℕ => evaln a.1.1 a.1.2 a.2 :=
have :
Primrec₂ fun (_ : Unit) (n : ℕ) =>
let a := ofNat (ℕ × Code) n
(List.range a.1).map (evaln a.1 a.2) :=
Primrec.nat_strong_rec _ (hG.comp Primrec.snd).to₂ fun _ p => by
simp only [G, prod_ofNat_val, ofNat_nat, List.length_map, List.length_range,
Nat.pair_unpair, Option.some_inj]
refine List.map_congr_left fun n => ?_
have : List.range p = List.range (Nat.pair p.unpair.1 (encode (ofNat Code p.unpair.2))) := by
simp
rw [this]
generalize p.unpair.1 = k
generalize ofNat Code p.unpair.2 = c
intro nk
rcases k with - | k'
· simp [evaln]
let k := k' + 1
simp only
simp only [List.mem_range, Nat.lt_succ_iff] at nk
have hg :
∀ {k' c' n},
Nat.pair k' (encode c') < Nat.pair k (encode c) →
lup ((List.range (Nat.pair k (encode c))).map fun n =>
(List.range n.unpair.1).map (evaln n.unpair.1 (ofNat Code n.unpair.2))) (k', c') n =
evaln k' c' n := by
intro k₁ c₁ n₁ hl
simp [lup, List.getElem?_range hl, evaln_map, Bind.bind, Option.bind_map]
obtain - | - | - | - | ⟨cf, cg⟩ | ⟨cf, cg⟩ | ⟨cf, cg⟩ | cf := c <;>
simp [evaln, nk, Bind.bind, Functor.map, Seq.seq, pure]
· obtain ⟨lf, lg⟩ := encode_lt_pair cf cg
rw [hg (Nat.pair_lt_pair_right _ lf), hg (Nat.pair_lt_pair_right _ lg)]
cases evaln k cf n
· rfl
cases evaln k cg n <;> rfl
· obtain ⟨lf, lg⟩ := encode_lt_comp cf cg
rw [hg (Nat.pair_lt_pair_right _ lg)]
cases evaln k cg n
· rfl
simp [k, hg (Nat.pair_lt_pair_right _ lf)]
· obtain ⟨lf, lg⟩ := encode_lt_prec cf cg
rw [hg (Nat.pair_lt_pair_right _ lf)]
cases n.unpair.2
· rfl
simp only
rw [hg (Nat.pair_lt_pair_left _ k'.lt_succ_self)]
cases evaln k' _ _
· rfl
simp [k, hg (Nat.pair_lt_pair_right _ lg)]
· have lf := encode_lt_rfind' cf
rw [hg (Nat.pair_lt_pair_right _ lf)]
rcases evaln k cf n with - | x
· rfl
simp only [Option.bind_some]
cases x <;> simp
rw [hg (Nat.pair_lt_pair_left _ k'.lt_succ_self)]
(Primrec.option_bind
(Primrec.list_getElem?.comp (this.comp (_root_.Primrec.const ())
(Primrec.encode_iff.2 Primrec.fst)) Primrec.snd) Primrec.snd.to₂).of_eq
fun ⟨⟨k, c⟩, n⟩ => by simp [evaln_map, Option.bind_map]
@[deprecated (since := "2025-05-12")] alias evaln_prim := primrec_evaln
end
section
open Partrec Computable
theorem eval_eq_rfindOpt (c n) : eval c n = Nat.rfindOpt fun k => evaln k c n :=
Part.ext fun x => by
refine evaln_complete.trans (Nat.rfindOpt_mono ?_).symm
intro a m n hl; apply evaln_mono hl
theorem eval_part : Partrec₂ eval :=
(Partrec.rfindOpt
(primrec_evaln.to_comp.comp
((Computable.snd.pair (fst.comp fst)).pair (snd.comp fst))).to₂).of_eq
fun a => by simp [eval_eq_rfindOpt]
/-- **Roger's fixed-point theorem**: any total, computable `f` has a fixed point.
That is, under the interpretation given by `Nat.Partrec.Code.eval`, there is a code `c`
such that `c` and `f c` have the same evaluation.
-/
theorem fixed_point {f : Code → Code} (hf : Computable f) : ∃ c : Code, eval (f c) = eval c :=
let g (x y : ℕ) : Part ℕ := eval (ofNat Code x) x >>= fun b => eval (ofNat Code b) y
have : Partrec₂ g :=
(eval_part.comp ((Computable.ofNat _).comp fst) fst).bind
(eval_part.comp ((Computable.ofNat _).comp snd) (snd.comp fst)).to₂
let ⟨cg, eg⟩ := exists_code.1 this
have eg' : ∀ a n, eval cg (Nat.pair a n) = Part.map encode (g a n) := by simp [eg]
let F (x : ℕ) : Code := f (curry cg x)
have : Computable F :=
hf.comp (primrec₂_curry.comp (_root_.Primrec.const cg) _root_.Primrec.id).to_comp
let ⟨cF, eF⟩ := exists_code.1 this
have eF' : eval cF (encode cF) = Part.some (encode (F (encode cF))) := by simp [eF]
⟨curry cg (encode cF),
funext fun n =>
show eval (f (curry cg (encode cF))) n = eval (curry cg (encode cF)) n by
simp [F, g, eg', eF', Part.map_id']⟩
/-- **Kleene's second recursion theorem** -/
theorem fixed_point₂ {f : Code → ℕ →. ℕ} (hf : Partrec₂ f) : ∃ c : Code, eval c = f c :=
let ⟨cf, ef⟩ := exists_code.1 hf
(fixed_point (primrec₂_curry.comp (_root_.Primrec.const cf) Primrec.encode).to_comp).imp
fun c e => funext fun n => by simp [e.symm, ef, Part.map_id']
end
/-- There are only countably many partial recursive partial functions `ℕ →. ℕ`. -/
instance : Countable {f : ℕ →. ℕ // _root_.Partrec f} := by
apply Function.Surjective.countable (f := fun c => ⟨eval c, eval_part.comp (.const c) .id⟩)
intro ⟨f, hf⟩; simpa using exists_code.1 hf
/-- There are only countably many computable functions `ℕ → ℕ`. -/
instance : Countable {f : ℕ → ℕ // Computable f} :=
@Function.Injective.countable {f : ℕ → ℕ // Computable f} {f : ℕ →. ℕ // _root_.Partrec f} _
(fun f => ⟨f.val, f.2⟩)
(fun _ _ h => Subtype.val_inj.1 (PFun.lift_injective (by simpa using h)))
end Nat.Partrec.Code |
.lake/packages/mathlib/Mathlib/Computability/MyhillNerode.lean | import Mathlib.Computability.DFA
import Mathlib.Data.Set.Finite.Basic
/-!
# Myhill–Nerode theorem
This file proves the Myhill–Nerode theorem using left quotients.
Given a language `L` and a word `x`, the *left quotient* of `L` by `x` is the set of suffixes `y`
such that `x ++ y` is in `L`. The *Myhill–Nerode theorem* shows that each left quotient, in fact,
corresponds to the state of an automaton that matches `L`, and that `L` is regular if and only if
there are finitely many such states.
## References
* <https://en.wikipedia.org/wiki/Syntactic_monoid#Myhill%E2%80%93Nerode_theorem>
-/
universe u v
variable {α : Type u} {σ : Type v} {L : Language α}
namespace Language
variable (L) in
/-- The *left quotient* of `x` is the set of suffixes `y` such that `x ++ y` is in `L`. -/
def leftQuotient (x : List α) : Language α := { y | x ++ y ∈ L }
variable (L) in
@[simp]
theorem leftQuotient_nil : L.leftQuotient [] = L := rfl
variable (L) in
theorem leftQuotient_append (x y : List α) :
L.leftQuotient (x ++ y) = (L.leftQuotient x).leftQuotient y := by
simp [leftQuotient, Language]
@[simp]
theorem mem_leftQuotient (x y : List α) : y ∈ L.leftQuotient x ↔ x ++ y ∈ L := Iff.rfl
theorem leftQuotient_accepts_apply (M : DFA α σ) (x : List α) :
leftQuotient M.accepts x = M.acceptsFrom (M.eval x) := by
ext y
simp [DFA.mem_accepts, DFA.mem_acceptsFrom, DFA.eval, DFA.evalFrom_of_append]
theorem leftQuotient_accepts (M : DFA α σ) : leftQuotient M.accepts = M.acceptsFrom ∘ M.eval :=
funext <| leftQuotient_accepts_apply M
theorem IsRegular.finite_range_leftQuotient (h : L.IsRegular) :
(Set.range L.leftQuotient).Finite := by
have ⟨σ, x, M, hM⟩ := h
rw [← hM, leftQuotient_accepts]
exact Set.finite_of_finite_preimage (Set.toFinite _)
(Set.range_comp_subset_range M.eval M.acceptsFrom)
variable (L) in
/-- The left quotients of a language are the states of an automaton that accepts the language. -/
def toDFA : DFA α (Set.range L.leftQuotient) where
step s a := by
refine ⟨s.val.leftQuotient [a], ?_⟩
obtain ⟨y, hy⟩ := s.prop
exists y ++ [a]
rw [← hy, leftQuotient_append]
start := ⟨L, by exists []⟩
accept := { s | [] ∈ s.val }
@[simp]
theorem mem_accept_toDFA (s : Set.range L.leftQuotient) : s ∈ L.toDFA.accept ↔ [] ∈ s.val := Iff.rfl
@[simp]
theorem step_toDFA (s : Set.range L.leftQuotient) (a : α) :
(L.toDFA.step s a).val = s.val.leftQuotient [a] := rfl
variable (L) in
@[simp]
theorem start_toDFA : L.toDFA.start.val = L := rfl
variable (L) in
@[simp]
theorem accepts_toDFA : L.toDFA.accepts = L := by
ext x
rw [DFA.mem_accepts]
suffices L.toDFA.eval x = L.leftQuotient x by simp [this]
induction x using List.reverseRecOn with
| nil => simp
| append_singleton x a ih => simp [ih, leftQuotient_append]
theorem IsRegular.of_finite_range_leftQuotient (h : Set.Finite (Set.range L.leftQuotient)) :
L.IsRegular :=
Language.isRegular_iff.mpr ⟨_, h.fintype, L.toDFA, by simp⟩
/--
**Myhill–Nerode theorem**. A language is regular if and only if the set of left quotients is finite.
-/
theorem isRegular_iff_finite_range_leftQuotient :
L.IsRegular ↔ (Set.range L.leftQuotient).Finite :=
⟨IsRegular.finite_range_leftQuotient, .of_finite_range_leftQuotient⟩
end Language |
.lake/packages/mathlib/Mathlib/Computability/Reduce.lean | import Mathlib.Computability.Halting
/-!
# Strong reducibility and degrees.
This file defines the notions of computable many-one reduction and one-one
reduction between sets, and shows that the corresponding degrees form a
semilattice.
## Notation
This file uses the local notation `⊕'` for `Sum.elim` to denote the disjoint union of two degrees.
## References
* [Robert Soare, *Recursively enumerable sets and degrees*][soare1987]
## Tags
computability, reducibility, reduction
-/
universe u v w
open Function
/--
`p` is many-one reducible to `q` if there is a computable function translating questions about `p`
to questions about `q`.
-/
def ManyOneReducible {α β} [Primcodable α] [Primcodable β] (p : α → Prop) (q : β → Prop) :=
∃ f, Computable f ∧ ∀ a, p a ↔ q (f a)
@[inherit_doc ManyOneReducible]
infixl:1000 " ≤₀ " => ManyOneReducible
theorem ManyOneReducible.mk {α β} [Primcodable α] [Primcodable β] {f : α → β} (q : β → Prop)
(h : Computable f) : (fun a => q (f a)) ≤₀ q :=
⟨f, h, fun _ => Iff.rfl⟩
@[refl]
theorem manyOneReducible_refl {α} [Primcodable α] (p : α → Prop) : p ≤₀ p :=
⟨id, Computable.id, by simp⟩
@[trans]
theorem ManyOneReducible.trans {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ]
{p : α → Prop} {q : β → Prop} {r : γ → Prop} : p ≤₀ q → q ≤₀ r → p ≤₀ r
| ⟨f, c₁, h₁⟩, ⟨g, c₂, h₂⟩ =>
⟨g ∘ f, c₂.comp c₁,
fun a => ⟨fun h => by rw [comp_apply, ← h₂, ← h₁]; assumption, fun h => by rwa [h₁, h₂]⟩⟩
theorem reflexive_manyOneReducible {α} [Primcodable α] : Reflexive (@ManyOneReducible α α _ _) :=
manyOneReducible_refl
theorem transitive_manyOneReducible {α} [Primcodable α] : Transitive (@ManyOneReducible α α _ _) :=
fun _ _ _ => ManyOneReducible.trans
/--
`p` is one-one reducible to `q` if there is an injective computable function translating questions
about `p` to questions about `q`.
-/
def OneOneReducible {α β} [Primcodable α] [Primcodable β] (p : α → Prop) (q : β → Prop) :=
∃ f, Computable f ∧ Injective f ∧ ∀ a, p a ↔ q (f a)
@[inherit_doc OneOneReducible]
infixl:1000 " ≤₁ " => OneOneReducible
theorem OneOneReducible.mk {α β} [Primcodable α] [Primcodable β] {f : α → β} (q : β → Prop)
(h : Computable f) (i : Injective f) : (fun a => q (f a)) ≤₁ q :=
⟨f, h, i, fun _ => Iff.rfl⟩
@[refl]
theorem oneOneReducible_refl {α} [Primcodable α] (p : α → Prop) : p ≤₁ p :=
⟨id, Computable.id, injective_id, by simp⟩
@[trans]
theorem OneOneReducible.trans {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop}
{q : β → Prop} {r : γ → Prop} : p ≤₁ q → q ≤₁ r → p ≤₁ r
| ⟨f, c₁, i₁, h₁⟩, ⟨g, c₂, i₂, h₂⟩ =>
⟨g ∘ f, c₂.comp c₁, i₂.comp i₁, fun a =>
⟨fun h => by rw [comp_apply, ← h₂, ← h₁]; assumption, fun h => by rwa [h₁, h₂]⟩⟩
theorem OneOneReducible.to_many_one {α β} [Primcodable α] [Primcodable β] {p : α → Prop}
{q : β → Prop} : p ≤₁ q → p ≤₀ q
| ⟨f, c, _, h⟩ => ⟨f, c, h⟩
theorem OneOneReducible.of_equiv {α β} [Primcodable α] [Primcodable β] {e : α ≃ β} (q : β → Prop)
(h : Computable e) : (q ∘ e) ≤₁ q :=
OneOneReducible.mk _ h e.injective
theorem OneOneReducible.of_equiv_symm {α β} [Primcodable α] [Primcodable β] {e : α ≃ β}
(q : β → Prop) (h : Computable e.symm) : q ≤₁ (q ∘ e) := by
convert OneOneReducible.of_equiv _ h; funext; simp
theorem reflexive_oneOneReducible {α} [Primcodable α] : Reflexive (@OneOneReducible α α _ _) :=
oneOneReducible_refl
theorem transitive_oneOneReducible {α} [Primcodable α] : Transitive (@OneOneReducible α α _ _) :=
fun _ _ _ => OneOneReducible.trans
namespace ComputablePred
variable {α : Type*} {β : Type*} [Primcodable α] [Primcodable β]
open Computable
theorem computable_of_manyOneReducible {p : α → Prop} {q : β → Prop} (h₁ : p ≤₀ q)
(h₂ : ComputablePred q) : ComputablePred p := by
rcases h₁ with ⟨f, c, hf⟩
rw [show p = fun a => q (f a) from Set.ext hf]
rcases computable_iff.1 h₂ with ⟨g, hg, rfl⟩
exact ⟨by infer_instance, by simpa using hg.comp c⟩
theorem computable_of_oneOneReducible {p : α → Prop} {q : β → Prop} (h : p ≤₁ q) :
ComputablePred q → ComputablePred p :=
computable_of_manyOneReducible h.to_many_one
end ComputablePred
/-- `p` and `q` are many-one equivalent if each one is many-one reducible to the other. -/
def ManyOneEquiv {α β} [Primcodable α] [Primcodable β] (p : α → Prop) (q : β → Prop) :=
p ≤₀ q ∧ q ≤₀ p
/-- `p` and `q` are one-one equivalent if each one is one-one reducible to the other. -/
def OneOneEquiv {α β} [Primcodable α] [Primcodable β] (p : α → Prop) (q : β → Prop) :=
p ≤₁ q ∧ q ≤₁ p
@[refl]
theorem manyOneEquiv_refl {α} [Primcodable α] (p : α → Prop) : ManyOneEquiv p p :=
⟨manyOneReducible_refl _, manyOneReducible_refl _⟩
@[symm]
theorem ManyOneEquiv.symm {α β} [Primcodable α] [Primcodable β] {p : α → Prop} {q : β → Prop} :
ManyOneEquiv p q → ManyOneEquiv q p :=
And.symm
@[trans]
theorem ManyOneEquiv.trans {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop}
{q : β → Prop} {r : γ → Prop} : ManyOneEquiv p q → ManyOneEquiv q r → ManyOneEquiv p r
| ⟨pq, qp⟩, ⟨qr, rq⟩ => ⟨pq.trans qr, rq.trans qp⟩
theorem equivalence_of_manyOneEquiv {α} [Primcodable α] : Equivalence (@ManyOneEquiv α α _ _) :=
⟨manyOneEquiv_refl, fun {_ _} => ManyOneEquiv.symm, fun {_ _ _} => ManyOneEquiv.trans⟩
@[refl]
theorem oneOneEquiv_refl {α} [Primcodable α] (p : α → Prop) : OneOneEquiv p p :=
⟨oneOneReducible_refl _, oneOneReducible_refl _⟩
@[symm]
theorem OneOneEquiv.symm {α β} [Primcodable α] [Primcodable β] {p : α → Prop} {q : β → Prop} :
OneOneEquiv p q → OneOneEquiv q p :=
And.symm
@[trans]
theorem OneOneEquiv.trans {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop}
{q : β → Prop} {r : γ → Prop} : OneOneEquiv p q → OneOneEquiv q r → OneOneEquiv p r
| ⟨pq, qp⟩, ⟨qr, rq⟩ => ⟨pq.trans qr, rq.trans qp⟩
theorem equivalence_of_oneOneEquiv {α} [Primcodable α] : Equivalence (@OneOneEquiv α α _ _) :=
⟨oneOneEquiv_refl, fun {_ _} => OneOneEquiv.symm, fun {_ _ _} => OneOneEquiv.trans⟩
theorem OneOneEquiv.to_many_one {α β} [Primcodable α] [Primcodable β] {p : α → Prop}
{q : β → Prop} : OneOneEquiv p q → ManyOneEquiv p q
| ⟨pq, qp⟩ => ⟨pq.to_many_one, qp.to_many_one⟩
/-- a computable bijection -/
nonrec def Equiv.Computable {α β} [Primcodable α] [Primcodable β] (e : α ≃ β) :=
Computable e ∧ Computable e.symm
theorem Equiv.Computable.symm {α β} [Primcodable α] [Primcodable β] {e : α ≃ β} :
e.Computable → e.symm.Computable :=
And.symm
theorem Equiv.Computable.trans {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {e₁ : α ≃ β}
{e₂ : β ≃ γ} : e₁.Computable → e₂.Computable → (e₁.trans e₂).Computable
| ⟨l₁, r₁⟩, ⟨l₂, r₂⟩ => ⟨l₂.comp l₁, r₁.comp r₂⟩
theorem Computable.eqv (α) [Denumerable α] : (Denumerable.eqv α).Computable :=
⟨Computable.encode, Computable.ofNat _⟩
theorem Computable.equiv₂ (α β) [Denumerable α] [Denumerable β] :
(Denumerable.equiv₂ α β).Computable :=
(Computable.eqv _).trans (Computable.eqv _).symm
theorem OneOneEquiv.of_equiv {α β} [Primcodable α] [Primcodable β] {e : α ≃ β} (h : e.Computable)
{p} : OneOneEquiv (p ∘ e) p :=
⟨OneOneReducible.of_equiv _ h.1, OneOneReducible.of_equiv_symm _ h.2⟩
theorem ManyOneEquiv.of_equiv {α β} [Primcodable α] [Primcodable β] {e : α ≃ β} (h : e.Computable)
{p} : ManyOneEquiv (p ∘ e) p :=
(OneOneEquiv.of_equiv h).to_many_one
theorem ManyOneEquiv.le_congr_left {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ]
{p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : ManyOneEquiv p q) : p ≤₀ r ↔ q ≤₀ r :=
⟨h.2.trans, h.1.trans⟩
theorem ManyOneEquiv.le_congr_right {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ]
{p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : ManyOneEquiv q r) : p ≤₀ q ↔ p ≤₀ r :=
⟨fun h' => h'.trans h.1, fun h' => h'.trans h.2⟩
theorem OneOneEquiv.le_congr_left {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ]
{p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : OneOneEquiv p q) : p ≤₁ r ↔ q ≤₁ r :=
⟨h.2.trans, h.1.trans⟩
theorem OneOneEquiv.le_congr_right {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ]
{p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : OneOneEquiv q r) : p ≤₁ q ↔ p ≤₁ r :=
⟨fun h' => h'.trans h.1, fun h' => h'.trans h.2⟩
theorem ManyOneEquiv.congr_left {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ]
{p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : ManyOneEquiv p q) :
ManyOneEquiv p r ↔ ManyOneEquiv q r :=
and_congr h.le_congr_left h.le_congr_right
theorem ManyOneEquiv.congr_right {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ]
{p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : ManyOneEquiv q r) :
ManyOneEquiv p q ↔ ManyOneEquiv p r :=
and_congr h.le_congr_right h.le_congr_left
theorem OneOneEquiv.congr_left {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ]
{p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : OneOneEquiv p q) :
OneOneEquiv p r ↔ OneOneEquiv q r :=
and_congr h.le_congr_left h.le_congr_right
theorem OneOneEquiv.congr_right {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ]
{p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : OneOneEquiv q r) :
OneOneEquiv p q ↔ OneOneEquiv p r :=
and_congr h.le_congr_right h.le_congr_left
@[simp]
theorem ULower.down_computable {α} [Primcodable α] : (ULower.equiv α).Computable :=
⟨Primrec.ulower_down.to_comp, Primrec.ulower_up.to_comp⟩
theorem manyOneEquiv_up {α} [Primcodable α] {p : α → Prop} : ManyOneEquiv (p ∘ ULower.up) p :=
ManyOneEquiv.of_equiv ULower.down_computable.symm
local infixl:1001 " ⊕' " => Sum.elim
open Nat.Primrec
theorem OneOneReducible.disjoin_left {α β} [Primcodable α] [Primcodable β] {p : α → Prop}
{q : β → Prop} : p ≤₁ p ⊕' q :=
⟨Sum.inl, Computable.sumInl, fun _ _ => Sum.inl.inj_iff.1, fun _ => Iff.rfl⟩
theorem OneOneReducible.disjoin_right {α β} [Primcodable α] [Primcodable β] {p : α → Prop}
{q : β → Prop} : q ≤₁ p ⊕' q :=
⟨Sum.inr, Computable.sumInr, fun _ _ => Sum.inr.inj_iff.1, fun _ => Iff.rfl⟩
theorem disjoin_manyOneReducible {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ]
{p : α → Prop} {q : β → Prop} {r : γ → Prop} : p ≤₀ r → q ≤₀ r → (p ⊕' q) ≤₀ r
| ⟨f, c₁, h₁⟩, ⟨g, c₂, h₂⟩ =>
⟨Sum.elim f g,
Computable.id.sumCasesOn (c₁.comp Computable.snd).to₂ (c₂.comp Computable.snd).to₂,
fun x => by cases x <;> [apply h₁; apply h₂]⟩
theorem disjoin_le {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {p : α → Prop}
{q : β → Prop} {r : γ → Prop} : (p ⊕' q) ≤₀ r ↔ p ≤₀ r ∧ q ≤₀ r :=
⟨fun h =>
⟨OneOneReducible.disjoin_left.to_many_one.trans h,
OneOneReducible.disjoin_right.to_many_one.trans h⟩,
fun ⟨h₁, h₂⟩ => disjoin_manyOneReducible h₁ h₂⟩
variable {α : Type u} [Primcodable α] [Inhabited α] {β : Type v} [Primcodable β] [Inhabited β]
/-- Computable and injective mapping of predicates to sets of natural numbers.
-/
def toNat (p : Set α) : Set ℕ :=
{ n | p ((Encodable.decode (α := α) n).getD default) }
@[simp]
theorem toNat_manyOneReducible {p : Set α} : toNat p ≤₀ p :=
⟨fun n => (Encodable.decode (α := α) n).getD default,
Computable.option_getD Computable.decode (Computable.const _), fun _ => Iff.rfl⟩
@[simp]
theorem manyOneReducible_toNat {p : Set α} : p ≤₀ toNat p :=
⟨Encodable.encode, Computable.encode, by simp [toNat, setOf]⟩
@[simp]
theorem manyOneReducible_toNat_toNat {p : Set α} {q : Set β} : toNat p ≤₀ toNat q ↔ p ≤₀ q :=
⟨fun h => manyOneReducible_toNat.trans (h.trans toNat_manyOneReducible), fun h =>
toNat_manyOneReducible.trans (h.trans manyOneReducible_toNat)⟩
@[simp]
theorem toNat_manyOneEquiv {p : Set α} : ManyOneEquiv (toNat p) p := by simp [ManyOneEquiv]
@[simp]
theorem manyOneEquiv_toNat (p : Set α) (q : Set β) :
ManyOneEquiv (toNat p) (toNat q) ↔ ManyOneEquiv p q := by simp [ManyOneEquiv]
/-- A many-one degree is an equivalence class of sets up to many-one equivalence. -/
def ManyOneDegree : Type :=
Quotient (⟨ManyOneEquiv, equivalence_of_manyOneEquiv⟩ : Setoid (Set ℕ))
namespace ManyOneDegree
/-- The many-one degree of a set on a primcodable type. -/
def of (p : α → Prop) : ManyOneDegree :=
Quotient.mk'' (toNat p)
@[elab_as_elim]
protected theorem ind_on {C : ManyOneDegree → Prop} (d : ManyOneDegree)
(h : ∀ p : Set ℕ, C (of p)) : C d :=
Quotient.inductionOn' d h
/-- Lifts a function on sets of natural numbers to many-one degrees. -/
protected abbrev liftOn {φ} (d : ManyOneDegree) (f : Set ℕ → φ)
(h : ∀ p q, ManyOneEquiv p q → f p = f q) : φ :=
Quotient.liftOn' d f h
@[simp]
protected theorem liftOn_eq {φ} (p : Set ℕ) (f : Set ℕ → φ)
(h : ∀ p q, ManyOneEquiv p q → f p = f q) : (of p).liftOn f h = f p :=
rfl
/-- Lifts a binary function on sets of natural numbers to many-one degrees. -/
@[reducible, simp]
protected def liftOn₂ {φ} (d₁ d₂ : ManyOneDegree) (f : Set ℕ → Set ℕ → φ)
(h : ∀ p₁ p₂ q₁ q₂, ManyOneEquiv p₁ p₂ → ManyOneEquiv q₁ q₂ → f p₁ q₁ = f p₂ q₂) : φ :=
d₁.liftOn (fun p => d₂.liftOn (f p) fun _ _ hq => h _ _ _ _ (by rfl) hq)
(by
intro p₁ p₂ hp
induction d₂ using ManyOneDegree.ind_on
apply h
· assumption
· rfl)
@[simp]
protected theorem liftOn₂_eq {φ} (p q : Set ℕ) (f : Set ℕ → Set ℕ → φ)
(h : ∀ p₁ p₂ q₁ q₂, ManyOneEquiv p₁ p₂ → ManyOneEquiv q₁ q₂ → f p₁ q₁ = f p₂ q₂) :
(of p).liftOn₂ (of q) f h = f p q :=
rfl
@[simp]
theorem of_eq_of {p : α → Prop} {q : β → Prop} : of p = of q ↔ ManyOneEquiv p q := by
rw [of, of, Quotient.eq'']
simp
instance instInhabited : Inhabited ManyOneDegree :=
⟨of (∅ : Set ℕ)⟩
/-- For many-one degrees `d₁` and `d₂`, `d₁ ≤ d₂` if the sets in `d₁` are many-one reducible to the
sets in `d₂`.
-/
instance instLE : LE ManyOneDegree :=
⟨fun d₁ d₂ =>
ManyOneDegree.liftOn₂ d₁ d₂ (· ≤₀ ·) fun _p₁ _p₂ _q₁ _q₂ hp hq =>
propext (hp.le_congr_left.trans hq.le_congr_right)⟩
@[simp]
theorem of_le_of {p : α → Prop} {q : β → Prop} : of p ≤ of q ↔ p ≤₀ q :=
manyOneReducible_toNat_toNat
private theorem le_refl (d : ManyOneDegree) : d ≤ d := by
induction d using ManyOneDegree.ind_on; simp; rfl
private theorem le_antisymm {d₁ d₂ : ManyOneDegree} : d₁ ≤ d₂ → d₂ ≤ d₁ → d₁ = d₂ := by
induction d₁ using ManyOneDegree.ind_on
induction d₂ using ManyOneDegree.ind_on
intro hp hq
simp_all only [ManyOneEquiv, of_le_of, of_eq_of, true_and]
private theorem le_trans {d₁ d₂ d₃ : ManyOneDegree} : d₁ ≤ d₂ → d₂ ≤ d₃ → d₁ ≤ d₃ := by
induction d₁ using ManyOneDegree.ind_on
induction d₂ using ManyOneDegree.ind_on
induction d₃ using ManyOneDegree.ind_on
apply ManyOneReducible.trans
instance instPartialOrder : PartialOrder ManyOneDegree where
le_refl := le_refl
le_trans _ _ _ := le_trans
le_antisymm _ _ := le_antisymm
/-- The join of two degrees, induced by the disjoint union of two underlying sets. -/
instance instAdd : Add ManyOneDegree :=
⟨fun d₁ d₂ =>
d₁.liftOn₂ d₂ (fun a b => of (a ⊕' b))
(by
rintro a b c d ⟨hl₁, hr₁⟩ ⟨hl₂, hr₂⟩
rw [of_eq_of]
exact
⟨disjoin_manyOneReducible (hl₁.trans OneOneReducible.disjoin_left.to_many_one)
(hl₂.trans OneOneReducible.disjoin_right.to_many_one),
disjoin_manyOneReducible (hr₁.trans OneOneReducible.disjoin_left.to_many_one)
(hr₂.trans OneOneReducible.disjoin_right.to_many_one)⟩)⟩
@[simp]
theorem add_of (p : Set α) (q : Set β) : of (p ⊕' q) = of p + of q :=
of_eq_of.mpr
⟨disjoin_manyOneReducible
(manyOneReducible_toNat.trans OneOneReducible.disjoin_left.to_many_one)
(manyOneReducible_toNat.trans OneOneReducible.disjoin_right.to_many_one),
disjoin_manyOneReducible
(toNat_manyOneReducible.trans OneOneReducible.disjoin_left.to_many_one)
(toNat_manyOneReducible.trans OneOneReducible.disjoin_right.to_many_one)⟩
@[simp]
protected theorem add_le {d₁ d₂ d₃ : ManyOneDegree} : d₁ + d₂ ≤ d₃ ↔ d₁ ≤ d₃ ∧ d₂ ≤ d₃ := by
induction d₁ using ManyOneDegree.ind_on
induction d₂ using ManyOneDegree.ind_on
induction d₃ using ManyOneDegree.ind_on
simpa only [← add_of, of_le_of] using disjoin_le
@[simp]
protected theorem le_add_left (d₁ d₂ : ManyOneDegree) : d₁ ≤ d₁ + d₂ :=
(ManyOneDegree.add_le.1 (le_refl _)).1
@[simp]
protected theorem le_add_right (d₁ d₂ : ManyOneDegree) : d₂ ≤ d₁ + d₂ :=
(ManyOneDegree.add_le.1 (le_refl _)).2
instance instSemilatticeSup : SemilatticeSup ManyOneDegree :=
{ ManyOneDegree.instPartialOrder with
sup := (· + ·)
le_sup_left := ManyOneDegree.le_add_left
le_sup_right := ManyOneDegree.le_add_right
sup_le := fun _ _ _ h₁ h₂ => ManyOneDegree.add_le.2 ⟨h₁, h₂⟩ }
end ManyOneDegree |
.lake/packages/mathlib/Mathlib/Computability/TuringMachine.lean | import Mathlib.Computability.Tape
import Mathlib.Data.Fintype.Option
import Mathlib.Data.Fintype.Prod
import Mathlib.Data.Fintype.Pi
import Mathlib.Data.PFun
import Mathlib.Computability.PostTuringMachine
/-!
# Turing machines
The files `PostTuringMachine.lean` and `TuringMachine.lean` define
a sequence of simple machine languages, starting with Turing machines and working
up to more complex languages based on Wang B-machines.
`PostTuringMachine.lean` covers the TM0 model and TM1 model;
`TuringMachine.lean` adds the TM2 model.
## Naming conventions
Each model of computation in this file shares a naming convention for the elements of a model of
computation. These are the parameters for the language:
* `Γ` is the alphabet on the tape.
* `Λ` is the set of labels, or internal machine states.
* `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and
later models achieve this by mixing it into `Λ`.
* `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks.
All of these variables denote "essentially finite" types, but for technical reasons it is
convenient to allow them to be infinite anyway. When using an infinite type, we will be interested
in proving that only finitely many values of the type are ever interacted with.
Given these parameters, there are a few common structures for the model that arise:
* `Stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is
finite, and for later models it is an infinite inductive type representing "possible program
texts".
* `Cfg` is the set of instantaneous configurations, that is, the state of the machine together with
its environment.
* `Machine` is the set of all machines in the model. Usually this is approximately a function
`Λ → Stmt`, although different models have different ways of halting and other actions.
* `step : Cfg → Option Cfg` is the function that describes how the state evolves over one step.
If `step c = none`, then `c` is a terminal state, and the result of the computation is read off
from `c`. Because of the type of `step`, these models are all deterministic by construction.
* `init : Input → Cfg` sets up the initial state. The type `Input` depends on the model;
in most cases it is `List Γ`.
* `eval : Machine → Input → Part Output`, given a machine `M` and input `i`, starts from
`init i`, runs `step` until it reaches an output, and then applies a function `Cfg → Output` to
the final state to obtain the result. The type `Output` depends on the model.
* `Supports : Machine → Finset Λ → Prop` asserts that a machine `M` starts in `S : Finset Λ`, and
can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input
cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when
convenient, and prove that only finitely many of these states are actually accessible. This
formalizes "essentially finite" mentioned above.
-/
assert_not_exists MonoidWithZero
open List (Vector)
open Relation
open Nat (iterate)
open Function (update iterate_succ iterate_succ_apply iterate_succ' iterate_succ_apply'
iterate_zero_apply)
namespace Turing
/-!
## The TM2 model
The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite)
collection of stacks, each with elements of different types (the alphabet of stack `k : K` is
`Γ k`). The statements are:
* `push k (f : σ → Γ k) q` puts `f a` on the `k`-th stack, then does `q`.
* `pop k (f : σ → Option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the
value of the `k`-th stack, and removes this element from the stack, then does `q`.
* `peek k (f : σ → Option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the
value of the `k`-th stack, then does `q`.
* `load (f : σ → σ) q` reads nothing but applies `f` to the internal state, then does `q`.
* `branch (f : σ → Bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`.
* `goto (f : σ → Λ)` jumps to label `f a`.
* `halt` halts on the next step.
The configuration is a tuple `(l, var, stk)` where `l : Option Λ` is the current label to run or
`none` for the halting state, `var : σ` is the (finite) internal state, and `stk : ∀ k, List (Γ k)`
is the collection of stacks. (Note that unlike the `TM0` and `TM1` models, these are not
`ListBlank`s, they have definite ends that can be detected by the `pop` command.)
Given a designated stack `k` and a value `L : List (Γ k)`, the initial configuration has all the
stacks empty except the designated "input" stack; in `eval` this designated stack also functions
as the output stack.
-/
namespace TM2
variable {K : Type*}
-- Index type of stacks
variable (Γ : K → Type*)
-- Type of stack elements
variable (Λ : Type*)
-- Type of function labels
variable (σ : Type*)
-- Type of variable settings
/-- The TM2 model removes the tape entirely from the TM1 model,
replacing it with an arbitrary (finite) collection of stacks.
The operation `push` puts an element on one of the stacks,
and `pop` removes an element from a stack (and modifies the
internal state based on the result). `peek` modifies the
internal state but does not remove an element. -/
inductive Stmt
| push : ∀ k, (σ → Γ k) → Stmt → Stmt
| peek : ∀ k, (σ → Option (Γ k) → σ) → Stmt → Stmt
| pop : ∀ k, (σ → Option (Γ k) → σ) → Stmt → Stmt
| load : (σ → σ) → Stmt → Stmt
| branch : (σ → Bool) → Stmt → Stmt → Stmt
| goto : (σ → Λ) → Stmt
| halt : Stmt
open Stmt
instance Stmt.inhabited : Inhabited (Stmt Γ Λ σ) :=
⟨halt⟩
/-- A configuration in the TM2 model is a label (or `none` for the halt state), the state of
local variables, and the stacks. (Note that the stacks are not `ListBlank`s, they have a definite
size.) -/
structure Cfg where
/-- The current label to run (or `none` for the halting state) -/
l : Option Λ
/-- The internal state -/
var : σ
/-- The (finite) collection of internal stacks -/
stk : ∀ k, List (Γ k)
instance Cfg.inhabited [Inhabited σ] : Inhabited (Cfg Γ Λ σ) :=
⟨⟨default, default, default⟩⟩
variable {Γ Λ σ}
section
variable [DecidableEq K]
/-- The step function for the TM2 model. -/
def stepAux : Stmt Γ Λ σ → σ → (∀ k, List (Γ k)) → Cfg Γ Λ σ
| push k f q, v, S => stepAux q v (update S k (f v :: S k))
| peek k f q, v, S => stepAux q (f v (S k).head?) S
| pop k f q, v, S => stepAux q (f v (S k).head?) (update S k (S k).tail)
| load a q, v, S => stepAux q (a v) S
| branch f q₁ q₂, v, S => cond (f v) (stepAux q₁ v S) (stepAux q₂ v S)
| goto f, v, S => ⟨some (f v), v, S⟩
| halt, v, S => ⟨none, v, S⟩
/-- The step function for the TM2 model. -/
def step (M : Λ → Stmt Γ Λ σ) : Cfg Γ Λ σ → Option (Cfg Γ Λ σ)
| ⟨none, _, _⟩ => none
| ⟨some l, v, S⟩ => some (stepAux (M l) v S)
attribute [simp] stepAux.eq_1 stepAux.eq_2 stepAux.eq_3
stepAux.eq_4 stepAux.eq_5 stepAux.eq_6 stepAux.eq_7 step.eq_1 step.eq_2
/-- The (reflexive) reachability relation for the TM2 model. -/
def Reaches (M : Λ → Stmt Γ Λ σ) : Cfg Γ Λ σ → Cfg Γ Λ σ → Prop :=
ReflTransGen fun a b ↦ b ∈ step M a
end
/-- Given a set `S` of states, `SupportsStmt S q` means that `q` only jumps to states in `S`. -/
def SupportsStmt (S : Finset Λ) : Stmt Γ Λ σ → Prop
| push _ _ q => SupportsStmt S q
| peek _ _ q => SupportsStmt S q
| pop _ _ q => SupportsStmt S q
| load _ q => SupportsStmt S q
| branch _ q₁ q₂ => SupportsStmt S q₁ ∧ SupportsStmt S q₂
| goto l => ∀ v, l v ∈ S
| halt => True
section
open scoped Classical in
/-- The set of subtree statements in a statement. -/
noncomputable def stmts₁ : Stmt Γ Λ σ → Finset (Stmt Γ Λ σ)
| Q@(push _ _ q) => insert Q (stmts₁ q)
| Q@(peek _ _ q) => insert Q (stmts₁ q)
| Q@(pop _ _ q) => insert Q (stmts₁ q)
| Q@(load _ q) => insert Q (stmts₁ q)
| Q@(branch _ q₁ q₂) => insert Q (stmts₁ q₁ ∪ stmts₁ q₂)
| Q@(goto _) => {Q}
| Q@halt => {Q}
theorem stmts₁_self {q : Stmt Γ Λ σ} : q ∈ stmts₁ q := by
cases q <;> simp only [Finset.mem_insert_self, Finset.mem_singleton_self, stmts₁]
theorem stmts₁_trans {q₁ q₂ : Stmt Γ Λ σ} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := by
classical
intro h₁₂ q₀ h₀₁
induction q₂ with (
simp only [stmts₁] at h₁₂ ⊢
simp only [Finset.mem_insert, Finset.mem_singleton, Finset.mem_union] at h₁₂)
| branch f q₁ q₂ IH₁ IH₂ =>
rcases h₁₂ with (rfl | h₁₂ | h₁₂)
· unfold stmts₁ at h₀₁
exact h₀₁
· exact Finset.mem_insert_of_mem (Finset.mem_union_left _ (IH₁ h₁₂))
· exact Finset.mem_insert_of_mem (Finset.mem_union_right _ (IH₂ h₁₂))
| goto l => subst h₁₂; exact h₀₁
| halt => subst h₁₂; exact h₀₁
| load _ q IH | _ _ _ q IH =>
rcases h₁₂ with (rfl | h₁₂)
· unfold stmts₁ at h₀₁
exact h₀₁
· exact Finset.mem_insert_of_mem (IH h₁₂)
theorem stmts₁_supportsStmt_mono {S : Finset Λ} {q₁ q₂ : Stmt Γ Λ σ} (h : q₁ ∈ stmts₁ q₂)
(hs : SupportsStmt S q₂) : SupportsStmt S q₁ := by
induction q₂ with
simp only [stmts₁, SupportsStmt, Finset.mem_insert, Finset.mem_union, Finset.mem_singleton]
at h hs
| branch f q₁ q₂ IH₁ IH₂ => rcases h with (rfl | h | h); exacts [hs, IH₁ h hs.1, IH₂ h hs.2]
| goto l => subst h; exact hs
| halt => subst h; trivial
| load _ _ IH | _ _ _ _ IH => rcases h with (rfl | h) <;> [exact hs; exact IH h hs]
open scoped Classical in
/-- The set of statements accessible from initial set `S` of labels. -/
noncomputable def stmts (M : Λ → Stmt Γ Λ σ) (S : Finset Λ) : Finset (Option (Stmt Γ Λ σ)) :=
Finset.insertNone (S.biUnion fun q ↦ stmts₁ (M q))
theorem stmts_trans {M : Λ → Stmt Γ Λ σ} {S : Finset Λ} {q₁ q₂ : Stmt Γ Λ σ} (h₁ : q₁ ∈ stmts₁ q₂) :
some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by
simp only [stmts, Finset.mem_insertNone, Finset.mem_biUnion, Option.mem_def, Option.some.injEq,
forall_eq', exists_imp, and_imp]
exact fun l ls h₂ ↦ ⟨_, ls, stmts₁_trans h₂ h₁⟩
end
variable [Inhabited Λ]
/-- Given a TM2 machine `M` and a set `S` of states, `Supports M S` means that all states in
`S` jump only to other states in `S`. -/
def Supports (M : Λ → Stmt Γ Λ σ) (S : Finset Λ) :=
default ∈ S ∧ ∀ q ∈ S, SupportsStmt S (M q)
theorem stmts_supportsStmt {M : Λ → Stmt Γ Λ σ} {S : Finset Λ} {q : Stmt Γ Λ σ}
(ss : Supports M S) : some q ∈ stmts M S → SupportsStmt S q := by
simp only [stmts, Finset.mem_insertNone, Finset.mem_biUnion, Option.mem_def, Option.some.injEq,
forall_eq', exists_imp, and_imp]
exact fun l ls h ↦ stmts₁_supportsStmt_mono h (ss.2 _ ls)
variable [DecidableEq K]
theorem step_supports (M : Λ → Stmt Γ Λ σ) {S : Finset Λ} (ss : Supports M S) :
∀ {c c' : Cfg Γ Λ σ}, c' ∈ step M c → c.l ∈ Finset.insertNone S → c'.l ∈ Finset.insertNone S
| ⟨some l₁, v, T⟩, c', h₁, h₂ => by
replace h₂ := ss.2 _ (Finset.some_mem_insertNone.1 h₂)
simp only [step, Option.mem_def, Option.some.injEq] at h₁; subst c'
revert h₂; induction M l₁ generalizing v T with intro hs
| branch p q₁' q₂' IH₁ IH₂ =>
unfold stepAux; cases p v
· exact IH₂ _ _ hs.2
· exact IH₁ _ _ hs.1
| goto => exact Finset.some_mem_insertNone.2 (hs _)
| halt => apply Multiset.mem_cons_self
| load _ _ IH | _ _ _ _ IH => exact IH _ _ hs
variable [Inhabited σ]
/-- The initial state of the TM2 model. The input is provided on a designated stack. -/
def init (k : K) (L : List (Γ k)) : Cfg Γ Λ σ :=
⟨some default, default, update (fun _ ↦ []) k L⟩
/-- Evaluates a TM2 program to completion, with the output on the same stack as the input. -/
def eval (M : Λ → Stmt Γ Λ σ) (k : K) (L : List (Γ k)) : Part (List (Γ k)) :=
(Turing.eval (step M) (init k L)).map fun c ↦ c.stk k
end TM2
/-!
## TM2 emulator in TM1
To prove that TM2 computable functions are TM1 computable, we need to reduce each TM2 program to a
TM1 program. So suppose a TM2 program is given. This program has to maintain a whole collection of
stacks, but we have only one tape, so we must "multiplex" them all together. Pictorially, if stack
1 contains `[a, b]` and stack 2 contains `[c, d, e, f]` then the tape looks like this:
```
bottom: ... | _ | T | _ | _ | _ | _ | ...
stack 1: ... | _ | b | a | _ | _ | _ | ...
stack 2: ... | _ | f | e | d | c | _ | ...
```
where a tape element is a vertical slice through the diagram. Here the alphabet is
`Γ' := Bool × ∀ k, Option (Γ k)`, where:
* `bottom : Bool` is marked only in one place, the initial position of the TM, and represents the
tail of all stacks. It is never modified.
* `stk k : Option (Γ k)` is the value of the `k`-th stack, if in range, otherwise `none` (which is
the blank value). Note that the head of the stack is at the far end; this is so that push and pop
don't have to do any shifting.
In "resting" position, the TM is sitting at the position marked `bottom`. For non-stack actions,
it operates in place, but for the stack actions `push`, `peek`, and `pop`, it must shuttle to the
end of the appropriate stack, make its changes, and then return to the bottom. So the states are:
* `normal (l : Λ)`: waiting at `bottom` to execute function `l`
* `go k (s : StAct k) (q : Stmt₂)`: travelling to the right to get to the end of stack `k` in
order to perform stack action `s`, and later continue with executing `q`
* `ret (q : Stmt₂)`: travelling to the left after having performed a stack action, and executing
`q` once we arrive
Because of the shuttling, emulation overhead is `O(n)`, where `n` is the current maximum of the
length of all stacks. Therefore a program that takes `k` steps to run in TM2 takes `O((m+k)k)`
steps to run when emulated in TM1, where `m` is the length of the input.
-/
namespace TM2to1
-- A displaced lemma proved in unnecessary generality
theorem stk_nth_val {K : Type*} {Γ : K → Type*} {L : ListBlank (∀ k, Option (Γ k))} {k S} (n)
(hL : ListBlank.map (proj k) L = ListBlank.mk (List.map some S).reverse) :
L.nth n k = S.reverse[n]? := by
rw [← proj_map_nth, hL, ← List.map_reverse, ListBlank.nth_mk,
List.getI_eq_iget_getElem?, List.getElem?_map]
cases S.reverse[n]? <;> rfl
variable (K : Type*)
variable (Γ : K → Type*)
variable {Λ σ : Type*}
/-- The alphabet of the TM2 simulator on TM1 is a marker for the stack bottom,
plus a vector of stack elements for each stack, or none if the stack does not extend this far. -/
def Γ' :=
Bool × ∀ k, Option (Γ k)
variable {K Γ}
instance Γ'.inhabited : Inhabited (Γ' K Γ) :=
⟨⟨false, fun _ ↦ none⟩⟩
instance Γ'.fintype [DecidableEq K] [Fintype K] [∀ k, Fintype (Γ k)] : Fintype (Γ' K Γ) :=
instFintypeProd _ _
/-- The bottom marker is fixed throughout the calculation, so we use the `addBottom` function
to express the program state in terms of a tape with only the stacks themselves. -/
def addBottom (L : ListBlank (∀ k, Option (Γ k))) : ListBlank (Γ' K Γ) :=
ListBlank.cons (true, L.head) (L.tail.map ⟨Prod.mk false, rfl⟩)
theorem addBottom_map (L : ListBlank (∀ k, Option (Γ k))) :
(addBottom L).map ⟨Prod.snd, by rfl⟩ = L := by
simp only [addBottom, ListBlank.map_cons]
convert ListBlank.cons_head_tail L
generalize ListBlank.tail L = L'
refine L'.induction_on fun l ↦ ?_; simp
theorem addBottom_modifyNth (f : (∀ k, Option (Γ k)) → ∀ k, Option (Γ k))
(L : ListBlank (∀ k, Option (Γ k))) (n : ℕ) :
(addBottom L).modifyNth (fun a ↦ (a.1, f a.2)) n = addBottom (L.modifyNth f n) := by
cases n <;>
simp only [addBottom, ListBlank.head_cons, ListBlank.modifyNth, ListBlank.tail_cons]
congr; symm; apply ListBlank.map_modifyNth; intro; rfl
theorem addBottom_nth_snd (L : ListBlank (∀ k, Option (Γ k))) (n : ℕ) :
((addBottom L).nth n).2 = L.nth n := by
conv => rhs; rw [← addBottom_map L, ListBlank.nth_map]
theorem addBottom_nth_succ_fst (L : ListBlank (∀ k, Option (Γ k))) (n : ℕ) :
((addBottom L).nth (n + 1)).1 = false := by
rw [ListBlank.nth_succ, addBottom, ListBlank.tail_cons, ListBlank.nth_map]
theorem addBottom_head_fst (L : ListBlank (∀ k, Option (Γ k))) : (addBottom L).head.1 = true := by
rw [addBottom, ListBlank.head_cons]
variable (K Γ σ) in
/-- A stack action is a command that interacts with the top of a stack. Our default position
is at the bottom of all the stacks, so we have to hold on to this action while going to the end
to modify the stack. -/
inductive StAct (k : K)
| push : (σ → Γ k) → StAct k
| peek : (σ → Option (Γ k) → σ) → StAct k
| pop : (σ → Option (Γ k) → σ) → StAct k
instance StAct.inhabited {k : K} : Inhabited (StAct K Γ σ k) :=
⟨StAct.peek fun s _ ↦ s⟩
section
open StAct
/-- The TM2 statement corresponding to a stack action. -/
def stRun {k : K} : StAct K Γ σ k → TM2.Stmt Γ Λ σ → TM2.Stmt Γ Λ σ
| push f => TM2.Stmt.push k f
| peek f => TM2.Stmt.peek k f
| pop f => TM2.Stmt.pop k f
/-- The effect of a stack action on the local variables, given the value of the stack. -/
def stVar {k : K} (v : σ) (l : List (Γ k)) : StAct K Γ σ k → σ
| push _ => v
| peek f => f v l.head?
| pop f => f v l.head?
/-- The effect of a stack action on the stack. -/
def stWrite {k : K} (v : σ) (l : List (Γ k)) : StAct K Γ σ k → List (Γ k)
| push f => f v :: l
| peek _ => l
| pop _ => l.tail
/-- We have partitioned the TM2 statements into "stack actions", which require going to the end
of the stack, and all other actions, which do not. This is a modified recursor which lumps the
stack actions into one. -/
@[elab_as_elim]
def stmtStRec.{l} {motive : TM2.Stmt Γ Λ σ → Sort l}
(run : ∀ (k) (s : StAct K Γ σ k) (q) (_ : motive q), motive (stRun s q))
(load : ∀ (a q) (_ : motive q), motive (TM2.Stmt.load a q))
(branch : ∀ (p q₁ q₂) (_ : motive q₁) (_ : motive q₂), motive (TM2.Stmt.branch p q₁ q₂))
(goto : ∀ l, motive (TM2.Stmt.goto l)) (halt : motive TM2.Stmt.halt) : ∀ n, motive n
| TM2.Stmt.push _ f q => run _ (push f) _ (stmtStRec run load branch goto halt q)
| TM2.Stmt.peek _ f q => run _ (peek f) _ (stmtStRec run load branch goto halt q)
| TM2.Stmt.pop _ f q => run _ (pop f) _ (stmtStRec run load branch goto halt q)
| TM2.Stmt.load _ q => load _ _ (stmtStRec run load branch goto halt q)
| TM2.Stmt.branch _ q₁ q₂ =>
branch _ _ _ (stmtStRec run load branch goto halt q₁) (stmtStRec run load branch goto halt q₂)
| TM2.Stmt.goto _ => goto _
| TM2.Stmt.halt => halt
theorem supports_run (S : Finset Λ) {k : K} (s : StAct K Γ σ k) (q : TM2.Stmt Γ Λ σ) :
TM2.SupportsStmt S (stRun s q) ↔ TM2.SupportsStmt S q := by
cases s <;> rfl
end
variable (K Γ Λ σ)
/-- The machine states of the TM2 emulator. We can either be in a normal state when waiting for the
next TM2 action, or we can be in the "go" and "return" states to go to the top of the stack and
return to the bottom, respectively. -/
inductive Λ'
| normal : Λ → Λ'
| go (k : K) : StAct K Γ σ k → TM2.Stmt Γ Λ σ → Λ'
| ret : TM2.Stmt Γ Λ σ → Λ'
variable {K Γ Λ σ}
open Λ'
instance Λ'.inhabited [Inhabited Λ] : Inhabited (Λ' K Γ Λ σ) :=
⟨normal default⟩
open TM1.Stmt
section
variable [DecidableEq K]
/-- The program corresponding to state transitions at the end of a stack. Here we start out just
after the top of the stack, and should end just after the new top of the stack. -/
def trStAct {k : K} (q : TM1.Stmt (Γ' K Γ) (Λ' K Γ Λ σ) σ) :
StAct K Γ σ k → TM1.Stmt (Γ' K Γ) (Λ' K Γ Λ σ) σ
| StAct.push f => (write fun a s ↦ (a.1, update a.2 k <| some <| f s)) <| move Dir.right q
| StAct.peek f => move Dir.left <| (load fun a s ↦ f s (a.2 k)) <| move Dir.right q
| StAct.pop f =>
branch (fun a _ ↦ a.1) (load (fun _ s ↦ f s none) q)
(move Dir.left <|
(load fun a s ↦ f s (a.2 k)) <| write (fun a _ ↦ (a.1, update a.2 k none)) q)
/-- The initial state for the TM2 emulator, given an initial TM2 state. All stacks start out empty
except for the input stack, and the stack bottom mark is set at the head. -/
def trInit (k : K) (L : List (Γ k)) : List (Γ' K Γ) :=
let L' : List (Γ' K Γ) := L.reverse.map fun a ↦ (false, update (fun _ ↦ none) k (some a))
(true, L'.headI.2) :: L'.tail
theorem step_run {k : K} (q : TM2.Stmt Γ Λ σ) (v : σ) (S : ∀ k, List (Γ k)) : ∀ s : StAct K Γ σ k,
TM2.stepAux (stRun s q) v S = TM2.stepAux q (stVar v (S k) s) (update S k (stWrite v (S k) s))
| StAct.push _ => rfl
| StAct.peek f => by unfold stWrite; rw [Function.update_eq_self]; rfl
| StAct.pop _ => rfl
end
/-- The translation of TM2 statements to TM1 statements. Regular actions have direct equivalents,
but stack actions are deferred by going to the corresponding `go` state, so that we can find the
appropriate stack top. -/
def trNormal : TM2.Stmt Γ Λ σ → TM1.Stmt (Γ' K Γ) (Λ' K Γ Λ σ) σ
| TM2.Stmt.push k f q => goto fun _ _ ↦ go k (StAct.push f) q
| TM2.Stmt.peek k f q => goto fun _ _ ↦ go k (StAct.peek f) q
| TM2.Stmt.pop k f q => goto fun _ _ ↦ go k (StAct.pop f) q
| TM2.Stmt.load a q => load (fun _ ↦ a) (trNormal q)
| TM2.Stmt.branch f q₁ q₂ => branch (fun _ ↦ f) (trNormal q₁) (trNormal q₂)
| TM2.Stmt.goto l => goto fun _ s ↦ normal (l s)
| TM2.Stmt.halt => halt
theorem trNormal_run {k : K} (s : StAct K Γ σ k) (q : TM2.Stmt Γ Λ σ) :
trNormal (stRun s q) = goto fun _ _ ↦ go k s q := by
cases s <;> rfl
section
open scoped Classical in
/-- The set of machine states accessible from an initial TM2 statement. -/
noncomputable def trStmts₁ : TM2.Stmt Γ Λ σ → Finset (Λ' K Γ Λ σ)
| TM2.Stmt.push k f q => {go k (StAct.push f) q, ret q} ∪ trStmts₁ q
| TM2.Stmt.peek k f q => {go k (StAct.peek f) q, ret q} ∪ trStmts₁ q
| TM2.Stmt.pop k f q => {go k (StAct.pop f) q, ret q} ∪ trStmts₁ q
| TM2.Stmt.load _ q => trStmts₁ q
| TM2.Stmt.branch _ q₁ q₂ => trStmts₁ q₁ ∪ trStmts₁ q₂
| _ => ∅
theorem trStmts₁_run {k : K} {s : StAct K Γ σ k} {q : TM2.Stmt Γ Λ σ} :
open scoped Classical in
trStmts₁ (stRun s q) = {go k s q, ret q} ∪ trStmts₁ q := by
cases s <;> simp only [trStmts₁, stRun]
theorem tr_respects_aux₂ [DecidableEq K] {k : K} {q : TM1.Stmt (Γ' K Γ) (Λ' K Γ Λ σ) σ} {v : σ}
{S : ∀ k, List (Γ k)} {L : ListBlank (∀ k, Option (Γ k))}
(hL : ∀ k, L.map (proj k) = ListBlank.mk ((S k).map some).reverse) (o : StAct K Γ σ k) :
let v' := stVar v (S k) o
let Sk' := stWrite v (S k) o
let S' := update S k Sk'
∃ L' : ListBlank (∀ k, Option (Γ k)),
(∀ k, L'.map (proj k) = ListBlank.mk ((S' k).map some).reverse) ∧
TM1.stepAux (trStAct q o) v
((Tape.move Dir.right)^[(S k).length] (Tape.mk' ∅ (addBottom L))) =
TM1.stepAux q v' ((Tape.move Dir.right)^[(S' k).length] (Tape.mk' ∅ (addBottom L'))) := by
simp only [Function.update_self]; cases o with simp only [stWrite, stVar, trStAct, TM1.stepAux]
| push f =>
have := Tape.write_move_right_n fun a : Γ' K Γ ↦ (a.1, update a.2 k (some (f v)))
refine
⟨_, fun k' ↦ ?_, by
-- Porting note: `rw [...]` to `erw [...]; rfl`.
-- https://github.com/leanprover-community/mathlib4/issues/5164
rw [Tape.move_right_n_head, List.length, Tape.mk'_nth_nat, this]
erw [addBottom_modifyNth fun a ↦ update a k (some (f v))]
rw [Nat.add_one, iterate_succ']
rfl⟩
refine ListBlank.ext fun i ↦ ?_
rw [ListBlank.nth_map, ListBlank.nth_modifyNth, proj, PointedMap.mk_val]
by_cases h' : k' = k
· subst k'
split_ifs with h
<;> simp only [List.reverse_cons, Function.update_self, ListBlank.nth_mk, List.map]
· rw [List.getI_eq_getElem _, List.getElem_append_right] <;>
simp only [List.length_append, List.length_reverse, List.length_map, ← h,
Nat.sub_self, List.length_singleton, List.getElem_singleton,
le_refl, Nat.lt_succ_self]
rw [← proj_map_nth, hL, ListBlank.nth_mk]
rcases lt_or_gt_of_ne h with h | h
· rw [List.getI_append]
simpa only [List.length_map, List.length_reverse] using h
· rw [List.getI_eq_default, List.getI_eq_default] <;>
simp only [Nat.add_one_le_iff, h, List.length, le_of_lt, List.length_reverse,
List.length_append, List.length_map]
· split_ifs <;> rw [Function.update_of_ne h', ← proj_map_nth, hL]
rw [Function.update_of_ne h']
| peek f =>
rw [Function.update_eq_self]
use L, hL; rw [Tape.move_left_right]; congr
cases e : S k; · rfl
rw [List.length_cons, iterate_succ', Function.comp, Tape.move_right_left,
Tape.move_right_n_head, Tape.mk'_nth_nat, addBottom_nth_snd, stk_nth_val _ (hL k), e,
List.reverse_cons, ← List.length_reverse, List.getElem?_concat_length]
rfl
| pop f =>
rcases e : S k with - | ⟨hd, tl⟩
· simp only [Tape.mk'_head, ListBlank.head_cons, Tape.move_left_mk', List.length,
Tape.write_mk', List.head?, iterate_zero_apply, List.tail_nil]
rw [← e, Function.update_eq_self]
exact ⟨L, hL, by rw [addBottom_head_fst, cond]⟩
· refine
⟨_, fun k' ↦ ?_, by
erw [List.length_cons, Tape.move_right_n_head, Tape.mk'_nth_nat, addBottom_nth_succ_fst,
cond_false, iterate_succ', Function.comp, Tape.move_right_left, Tape.move_right_n_head,
Tape.mk'_nth_nat, Tape.write_move_right_n fun a : Γ' K Γ ↦ (a.1, update a.2 k none),
addBottom_modifyNth fun a ↦ update a k none, addBottom_nth_snd,
stk_nth_val _ (hL k), e,
show (List.cons hd tl).reverse[tl.length]? = some hd by
rw [List.reverse_cons, ← List.length_reverse, List.getElem?_concat_length],
List.head?, List.tail]⟩
refine ListBlank.ext fun i ↦ ?_
rw [ListBlank.nth_map, ListBlank.nth_modifyNth, proj, PointedMap.mk_val]
by_cases h' : k' = k
· subst k'
split_ifs with h <;> simp only [Function.update_self, ListBlank.nth_mk, List.tail]
· rw [List.getI_eq_default]
· rfl
rw [h, List.length_reverse, List.length_map]
rw [← proj_map_nth, hL, ListBlank.nth_mk, e, List.map, List.reverse_cons]
rcases lt_or_gt_of_ne h with h | h
· rw [List.getI_append]
simpa only [List.length_map, List.length_reverse] using h
· rw [List.getI_eq_default, List.getI_eq_default] <;>
simp only [Nat.add_one_le_iff, h, List.length, le_of_lt, List.length_reverse,
List.length_append, List.length_map]
· split_ifs <;> rw [Function.update_of_ne h', ← proj_map_nth, hL]
rw [Function.update_of_ne h']
end
variable [DecidableEq K]
variable (M : Λ → TM2.Stmt Γ Λ σ)
/-- The TM2 emulator machine states written as a TM1 program.
This handles the `go` and `ret` states, which shuttle to and from a stack top. -/
def tr : Λ' K Γ Λ σ → TM1.Stmt (Γ' K Γ) (Λ' K Γ Λ σ) σ
| normal q => trNormal (M q)
| go k s q =>
branch (fun a _ ↦ (a.2 k).isNone) (trStAct (goto fun _ _ ↦ ret q) s)
(move Dir.right <| goto fun _ _ ↦ go k s q)
| ret q => branch (fun a _ ↦ a.1) (trNormal q) (move Dir.left <| goto fun _ _ ↦ ret q)
/-- The relation between TM2 configurations and TM1 configurations of the TM2 emulator. -/
inductive TrCfg : TM2.Cfg Γ Λ σ → TM1.Cfg (Γ' K Γ) (Λ' K Γ Λ σ) σ → Prop
| mk {q : Option Λ} {v : σ} {S : ∀ k, List (Γ k)} (L : ListBlank (∀ k, Option (Γ k))) :
(∀ k, L.map (proj k) = ListBlank.mk ((S k).map some).reverse) →
TrCfg ⟨q, v, S⟩ ⟨q.map normal, v, Tape.mk' ∅ (addBottom L)⟩
theorem tr_respects_aux₁ {k} (o q v) {S : List (Γ k)} {L : ListBlank (∀ k, Option (Γ k))}
(hL : L.map (proj k) = ListBlank.mk (S.map some).reverse) (n) (H : n ≤ S.length) :
Reaches₀ (TM1.step (tr M)) ⟨some (go k o q), v, Tape.mk' ∅ (addBottom L)⟩
⟨some (go k o q), v, (Tape.move Dir.right)^[n] (Tape.mk' ∅ (addBottom L))⟩ := by
induction n with
| zero => rfl
| succ n IH =>
apply (IH (le_of_lt H)).tail
rw [iterate_succ_apply']
simp only [TM1.step, TM1.stepAux, tr, Tape.mk'_nth_nat, Tape.move_right_n_head,
addBottom_nth_snd, Option.mem_def]
rw [stk_nth_val _ hL, List.getElem?_eq_getElem]
· rfl
· rwa [List.length_reverse]
theorem tr_respects_aux₃ {q v} {L : ListBlank (∀ k, Option (Γ k))} (n) : Reaches₀ (TM1.step (tr M))
⟨some (ret q), v, (Tape.move Dir.right)^[n] (Tape.mk' ∅ (addBottom L))⟩
⟨some (ret q), v, Tape.mk' ∅ (addBottom L)⟩ := by
induction n with
| zero => rfl
| succ n IH =>
refine Reaches₀.head ?_ IH
simp only [Option.mem_def, TM1.step]
rw [Option.some_inj, tr, TM1.stepAux, Tape.move_right_n_head, Tape.mk'_nth_nat,
addBottom_nth_succ_fst, TM1.stepAux, iterate_succ', Function.comp_apply, Tape.move_right_left]
rfl
theorem tr_respects_aux {q v T k} {S : ∀ k, List (Γ k)}
(hT : ∀ k, ListBlank.map (proj k) T = ListBlank.mk ((S k).map some).reverse)
(o : StAct K Γ σ k)
(IH : ∀ {v : σ} {S : ∀ k : K, List (Γ k)} {T : ListBlank (∀ k, Option (Γ k))},
(∀ k, ListBlank.map (proj k) T = ListBlank.mk ((S k).map some).reverse) →
∃ b, TrCfg (TM2.stepAux q v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal q) v (Tape.mk' ∅ (addBottom T))) b) :
∃ b, TrCfg (TM2.stepAux (stRun o q) v S) b ∧ Reaches (TM1.step (tr M))
(TM1.stepAux (trNormal (stRun o q)) v (Tape.mk' ∅ (addBottom T))) b := by
simp only [trNormal_run, step_run]
have hgo := tr_respects_aux₁ M o q v (hT k) _ le_rfl
obtain ⟨T', hT', hrun⟩ := tr_respects_aux₂ (Λ := Λ) hT o
have := hgo.tail' rfl
rw [tr, TM1.stepAux, Tape.move_right_n_head, Tape.mk'_nth_nat, addBottom_nth_snd,
stk_nth_val _ (hT k), List.getElem?_eq_none (le_of_eq List.length_reverse),
Option.isNone, cond, hrun, TM1.stepAux] at this
obtain ⟨c, gc, rc⟩ := IH hT'
refine ⟨c, gc, (this.to₀.trans (tr_respects_aux₃ M _) c (TransGen.head' rfl ?_)).to_reflTransGen⟩
rw [tr, TM1.stepAux, Tape.mk'_head, addBottom_head_fst]
exact rc
attribute [local simp] Respects TM2.step TM2.stepAux trNormal
theorem tr_respects : Respects (TM2.step M) (TM1.step (tr M)) TrCfg := by
intro c₁ c₂ h
obtain @⟨- | l, v, S, L, hT⟩ := h; · constructor
rsuffices ⟨b, c, r⟩ : ∃ b, _ ∧ Reaches (TM1.step (tr M)) _ _
· exact ⟨b, c, TransGen.head' rfl r⟩
simp only [tr]
generalize M l = N
induction N using stmtStRec generalizing v S L hT with
| run k s q IH => exact tr_respects_aux M hT s @IH
| load a _ IH => exact IH _ hT
| branch p q₁ q₂ IH₁ IH₂ =>
unfold TM2.stepAux trNormal TM1.stepAux
-- Porting note (https://github.com/leanprover-community/mathlib4/issues/12129): additional beta reduction needed
beta_reduce
cases p v <;> [exact IH₂ _ hT; exact IH₁ _ hT]
| goto => exact ⟨_, ⟨_, hT⟩, ReflTransGen.refl⟩
| halt => exact ⟨_, ⟨_, hT⟩, ReflTransGen.refl⟩
section
variable [Inhabited Λ] [Inhabited σ]
theorem trCfg_init (k) (L : List (Γ k)) : TrCfg (TM2.init k L)
(TM1.init (trInit k L) : TM1.Cfg (Γ' K Γ) (Λ' K Γ Λ σ) σ) := by
rw [(_ : TM1.init _ = _)]
· refine ⟨ListBlank.mk (L.reverse.map fun a ↦ update default k (some a)), fun k' ↦ ?_⟩
refine ListBlank.ext fun i ↦ ?_
rw [ListBlank.map_mk, ListBlank.nth_mk, List.getI_eq_iget_getElem?, List.map_map]
have : ((proj k').f ∘ fun a => update (β := fun k => Option (Γ k)) default k (some a))
= fun a => (proj k').f (update (β := fun k => Option (Γ k)) default k (some a)) := rfl
rw [this, List.getElem?_map, proj, PointedMap.mk_val]
simp only []
by_cases h : k' = k
· subst k'
simp only [Function.update_self]
rw [ListBlank.nth_mk, List.getI_eq_iget_getElem?, ← List.map_reverse, List.getElem?_map]
· simp only [Function.update_of_ne h]
rw [ListBlank.nth_mk, List.getI_eq_iget_getElem?, List.map, List.reverse_nil]
cases L.reverse[i]? <;> rfl
· rw [trInit, TM1.init]
congr <;> cases L.reverse <;> try rfl
simp only [List.map_map, List.tail_cons, List.map]
rfl
theorem tr_eval_dom (k) (L : List (Γ k)) :
(TM1.eval (tr M) (trInit k L)).Dom ↔ (TM2.eval M k L).Dom :=
Turing.tr_eval_dom (tr_respects M) (trCfg_init k L)
theorem tr_eval (k) (L : List (Γ k)) {L₁ L₂} (H₁ : L₁ ∈ TM1.eval (tr M) (trInit k L))
(H₂ : L₂ ∈ TM2.eval M k L) :
∃ (S : ∀ k, List (Γ k)) (L' : ListBlank (∀ k, Option (Γ k))),
addBottom L' = L₁ ∧
(∀ k, L'.map (proj k) = ListBlank.mk ((S k).map some).reverse) ∧ S k = L₂ := by
obtain ⟨c₁, h₁, rfl⟩ := (Part.mem_map_iff _).1 H₁
obtain ⟨c₂, h₂, rfl⟩ := (Part.mem_map_iff _).1 H₂
obtain ⟨_, ⟨L', hT⟩, h₃⟩ := Turing.tr_eval (tr_respects M) (trCfg_init k L) h₂
cases Part.mem_unique h₁ h₃
exact ⟨_, L', by simp only [Tape.mk'_right₀], hT, rfl⟩
end
section
variable [Inhabited Λ]
open scoped Classical in
/-- The support of a set of TM2 states in the TM2 emulator. -/
noncomputable def trSupp (S : Finset Λ) : Finset (Λ' K Γ Λ σ) :=
S.biUnion fun l ↦ insert (normal l) (trStmts₁ (M l))
open scoped Classical in
theorem tr_supports {S} (ss : TM2.Supports M S) : TM1.Supports (tr M) (trSupp M S) :=
⟨Finset.mem_biUnion.2 ⟨_, ss.1, Finset.mem_insert.2 <| Or.inl rfl⟩, fun l' h ↦ by
suffices ∀ (q) (_ : TM2.SupportsStmt S q) (_ : ∀ x ∈ trStmts₁ q, x ∈ trSupp M S),
TM1.SupportsStmt (trSupp M S) (trNormal q) ∧
∀ l' ∈ trStmts₁ q, TM1.SupportsStmt (trSupp M S) (tr M l') by
rcases Finset.mem_biUnion.1 h with ⟨l, lS, h⟩
have :=
this _ (ss.2 l lS) fun x hx ↦ Finset.mem_biUnion.2 ⟨_, lS, Finset.mem_insert_of_mem hx⟩
rcases Finset.mem_insert.1 h with (rfl | h) <;> [exact this.1; exact this.2 _ h]
clear h l'
refine stmtStRec ?_ ?_ ?_ ?_ ?_
· intro _ s _ IH ss' sub -- stack op
rw [TM2to1.supports_run] at ss'
simp only [TM2to1.trStmts₁_run, Finset.mem_union, Finset.mem_insert, Finset.mem_singleton]
at sub
have hgo := sub _ (Or.inl <| Or.inl rfl)
have hret := sub _ (Or.inl <| Or.inr rfl)
obtain ⟨IH₁, IH₂⟩ := IH ss' fun x hx ↦ sub x <| Or.inr hx
refine ⟨by simp only [trNormal_run, TM1.SupportsStmt]; intros; exact hgo, fun l h ↦ ?_⟩
rw [trStmts₁_run] at h
simp only [Finset.mem_union, Finset.mem_insert, Finset.mem_singleton]
at h
rcases h with (⟨rfl | rfl⟩ | h)
· cases s
· exact ⟨fun _ _ ↦ hret, fun _ _ ↦ hgo⟩
· exact ⟨fun _ _ ↦ hret, fun _ _ ↦ hgo⟩
· exact ⟨⟨fun _ _ ↦ hret, fun _ _ ↦ hret⟩, fun _ _ ↦ hgo⟩
· unfold TM1.SupportsStmt TM2to1.tr
exact ⟨IH₁, fun _ _ ↦ hret⟩
· exact IH₂ _ h
· intro _ _ IH ss' sub -- load
unfold TM2to1.trStmts₁ at sub ⊢
exact IH ss' sub
· intro _ _ _ IH₁ IH₂ ss' sub -- branch
unfold TM2to1.trStmts₁ at sub
obtain ⟨IH₁₁, IH₁₂⟩ := IH₁ ss'.1 fun x hx ↦ sub x <| Finset.mem_union_left _ hx
obtain ⟨IH₂₁, IH₂₂⟩ := IH₂ ss'.2 fun x hx ↦ sub x <| Finset.mem_union_right _ hx
refine ⟨⟨IH₁₁, IH₂₁⟩, fun l h ↦ ?_⟩
rw [trStmts₁] at h
rcases Finset.mem_union.1 h with (h | h) <;> [exact IH₁₂ _ h; exact IH₂₂ _ h]
· intro _ ss' _ -- goto
simp only [trStmts₁, Finset.notMem_empty]; refine ⟨?_, fun _ ↦ False.elim⟩
exact fun _ v ↦ Finset.mem_biUnion.2 ⟨_, ss' v, Finset.mem_insert_self _ _⟩
· intro _ _ -- halt
simp only [trStmts₁, Finset.notMem_empty]
exact ⟨trivial, fun _ ↦ False.elim⟩⟩
end
end TM2to1
end Turing |
.lake/packages/mathlib/Mathlib/Computability/AkraBazzi/SumTransform.lean | import Mathlib.Computability.AkraBazzi.GrowsPolynomially
import Mathlib.Analysis.Calculus.Deriv.Inv
import Mathlib.Analysis.SpecialFunctions.Pow.Continuity
import Mathlib.Analysis.SpecialFunctions.Log.Deriv
/-!
# Akra-Bazzi theorem: the sum transform
We develop further preliminaries required for the theorem, up to the sum transform.
## Main definitions and results
* `AkraBazziRecurrence T g a b r`: the predicate stating that `T : ℕ → ℝ` satisfies an Akra-Bazzi
recurrence with parameters `g`, `a`, `b` and `r` as above, together with basic bounds on `r i n`
and positivity of `T`.
* `AkraBazziRecurrence.smoothingFn`: the smoothing function $\varepsilon(x) = 1 / \log x$ used in
the inductive estimates, along with monotonicity, differentiability, and asymptotic properties.
* `AkraBazziRecurrence.p`: the unique Akra–Bazzi exponent characterized by $\sum_i a_i\,(b_i)^p = 1$
and supporting analytical lemmas such as continuity and injectivity of the defining sum.
* `AkraBazziRecurrence.sumTransform`: the transformation that turns a function `g` into
`n^p * ∑ u ∈ Finset.Ico n₀ n, g u / u^(p+1)` and its eventual comparison with multiples of `g n`.
* `AkraBazziRecurrence.asympBound`: the asymptotic bound satisfied by an Akra-Bazzi recurrence,
namely `n^p (1 + ∑ g(u) / u^(p+1))`, together with positivity statements along the branches
`r i n`.
## References
* Mohamad Akra and Louay Bazzi, On the solution of linear recurrence equations
* Tom Leighton, Notes on better master theorems for divide-and-conquer recurrences
* Manuel Eberl, Asymptotic reasoning in a proof assistant
-/
open Finset Real Filter Asymptotics
open scoped Topology
/-!
### Definition of Akra-Bazzi recurrences
This section defines the predicate `AkraBazziRecurrence T g a b r` which states that `T`
satisfies the recurrence relation
`T(n) = ∑_{i=0}^{k-1} a_i T(r_i(n)) + g(n)`
with appropriate conditions on the various parameters.
-/
/-- An Akra-Bazzi recurrence is a function that satisfies the recurrence
`T n = (∑ i, a i * T (r i n)) + g n`. -/
structure AkraBazziRecurrence {α : Type*} [Fintype α] [Nonempty α]
(T : ℕ → ℝ) (g : ℝ → ℝ) (a : α → ℝ) (b : α → ℝ) (r : α → ℕ → ℕ) where
/-- Point below which the recurrence is in the base case -/
n₀ : ℕ
/-- `n₀` is always positive -/
n₀_gt_zero : 0 < n₀
/-- The coefficients `a i` are positive. -/
a_pos : ∀ i, 0 < a i
/-- The coefficients `b i` are positive. -/
b_pos : ∀ i, 0 < b i
/-- The coefficients `b i` are less than 1. -/
b_lt_one : ∀ i, b i < 1
/-- `g` is nonnegative -/
g_nonneg : ∀ x ≥ 0, 0 ≤ g x
/-- `g` grows polynomially -/
g_grows_poly : AkraBazziRecurrence.GrowsPolynomially g
/-- The actual recurrence -/
h_rec (n : ℕ) (hn₀ : n₀ ≤ n) : T n = (∑ i, a i * T (r i n)) + g n
/-- Base case: `T(n) > 0` whenever `n < n₀` -/
T_gt_zero' (n : ℕ) (hn : n < n₀) : 0 < T n
/-- The functions `r i` always reduce `n`. -/
r_lt_n : ∀ i n, n₀ ≤ n → r i n < n
/-- The functions `r i` approximate the values `b i * n`. -/
dist_r_b : ∀ i, (fun n => (r i n : ℝ) - b i * n) =o[atTop] fun n => n / (log n) ^ 2
namespace AkraBazziRecurrence
section min_max
variable {α : Type*} [Finite α] [Nonempty α]
/-- Smallest `b i` -/
noncomputable def min_bi (b : α → ℝ) : α :=
Classical.choose <| Finite.exists_min b
/-- Largest `b i` -/
noncomputable def max_bi (b : α → ℝ) : α :=
Classical.choose <| Finite.exists_max b
@[aesop safe apply]
lemma min_bi_le {b : α → ℝ} (i : α) : b (min_bi b) ≤ b i :=
Classical.choose_spec (Finite.exists_min b) i
@[aesop safe apply]
lemma max_bi_le {b : α → ℝ} (i : α) : b i ≤ b (max_bi b) :=
Classical.choose_spec (Finite.exists_max b) i
end min_max
lemma isLittleO_self_div_log_id :
(fun (n : ℕ) => n / log n ^ 2) =o[atTop] (fun (n : ℕ) => (n : ℝ)) := by
calc (fun (n : ℕ) => (n : ℝ) / log n ^ 2)
_ = fun (n : ℕ) => (n : ℝ) * ((log n) ^ 2)⁻¹ := by simp_rw [div_eq_mul_inv]
_ =o[atTop] fun (n : ℕ) => (n : ℝ) * 1⁻¹ := by
refine IsBigO.mul_isLittleO (isBigO_refl _ _) ?_
refine IsLittleO.inv_rev ?_ (by simp)
calc
_ = (fun (_ : ℕ) => ((1 : ℝ) ^ 2)) := by simp
_ =o[atTop] (fun (n : ℕ) => (log n) ^ 2) :=
IsLittleO.pow (IsLittleO.natCast_atTop <| isLittleO_const_log_atTop) (by norm_num)
_ = (fun (n : ℕ) => (n : ℝ)) := by ext; simp
variable {α : Type*} [Fintype α] {T : ℕ → ℝ} {g : ℝ → ℝ} {a b : α → ℝ} {r : α → ℕ → ℕ}
variable [Nonempty α] (R : AkraBazziRecurrence T g a b r)
section
include R
lemma dist_r_b' : ∀ᶠ n in atTop, ∀ i, ‖(r i n : ℝ) - b i * n‖ ≤ n / log n ^ 2 := by
rw [Filter.eventually_all]
intro i
simpa using IsLittleO.eventuallyLE (R.dist_r_b i)
lemma eventually_b_le_r : ∀ᶠ (n : ℕ) in atTop, ∀ i, (b i : ℝ) * n - (n / log n ^ 2) ≤ r i n := by
filter_upwards [R.dist_r_b'] with n hn i
have h₁ : 0 ≤ b i := le_of_lt <| R.b_pos _
rw [sub_le_iff_le_add, add_comm, ← sub_le_iff_le_add]
calc (b i : ℝ) * n - r i n
_ = ‖b i * n‖ - ‖(r i n : ℝ)‖ := by
simp only [norm_mul, RCLike.norm_natCast, Real.norm_of_nonneg h₁]
_ ≤ ‖(b i * n : ℝ) - r i n‖ := norm_sub_norm_le _ _
_ = ‖(r i n : ℝ) - b i * n‖ := norm_sub_rev _ _
_ ≤ n / log n ^ 2 := hn i
lemma eventually_r_le_b : ∀ᶠ (n : ℕ) in atTop, ∀ i, r i n ≤ (b i : ℝ) * n + (n / log n ^ 2) := by
filter_upwards [R.dist_r_b'] with n hn i
calc r i n = b i * n + (r i n - b i * n) := by ring
_ ≤ b i * n + ‖r i n - b i * n‖ := by gcongr; exact Real.le_norm_self _
_ ≤ b i * n + n / log n ^ 2 := by gcongr; exact hn i
lemma eventually_r_lt_n : ∀ᶠ (n : ℕ) in atTop, ∀ i, r i n < n := by
filter_upwards [eventually_ge_atTop R.n₀] with n hn i using R.r_lt_n i n hn
lemma eventually_bi_mul_le_r : ∀ᶠ (n : ℕ) in atTop, ∀ i, (b (min_bi b) / 2) * n ≤ r i n := by
have gt_zero : 0 < b (min_bi b) := R.b_pos (min_bi b)
have hlo := isLittleO_self_div_log_id
rw [Asymptotics.isLittleO_iff] at hlo
have hlo' := hlo (by positivity : 0 < b (min_bi b) / 2)
filter_upwards [hlo', R.eventually_b_le_r] with n hn hn' i
simp only [Real.norm_of_nonneg (by positivity : 0 ≤ (n : ℝ))] at hn
calc b (min_bi b) / 2 * n
_ = b (min_bi b) * n - b (min_bi b) / 2 * n := by ring
_ ≤ b (min_bi b) * n - ‖n / log n ^ 2‖ := by gcongr
_ ≤ b i * n - ‖n / log n ^ 2‖ := by gcongr; aesop
_ = b i * n - n / log n ^ 2 := by
congr
exact Real.norm_of_nonneg <| by positivity
_ ≤ r i n := hn' i
lemma bi_min_div_two_lt_one : b (min_bi b) / 2 < 1 := by
have gt_zero : 0 < b (min_bi b) := R.b_pos (min_bi b)
calc b (min_bi b) / 2
_ < b (min_bi b) := by aesop (add safe apply div_two_lt_of_pos)
_ < 1 := R.b_lt_one _
lemma bi_min_div_two_pos : 0 < b (min_bi b) / 2 := div_pos (R.b_pos _) (by simp)
lemma exists_eventually_const_mul_le_r :
∃ c ∈ Set.Ioo (0 : ℝ) 1, ∀ᶠ (n : ℕ) in atTop, ∀ i, c * n ≤ r i n := by
have gt_zero : 0 < b (min_bi b) := R.b_pos (min_bi b)
exact ⟨b (min_bi b) / 2, ⟨⟨by positivity, R.bi_min_div_two_lt_one⟩, R.eventually_bi_mul_le_r⟩⟩
lemma eventually_r_ge (C : ℝ) : ∀ᶠ (n : ℕ) in atTop, ∀ i, C ≤ r i n := by
obtain ⟨c, hc_mem, hc⟩ := R.exists_eventually_const_mul_le_r
filter_upwards [eventually_ge_atTop ⌈C / c⌉₊, hc] with n hn₁ hn₂ i
have h₁ := hc_mem.1
calc C
_ = c * (C / c) := by
rw [← mul_div_assoc]
exact (mul_div_cancel_left₀ _ (by positivity)).symm
_ ≤ c * ⌈C / c⌉₊ := by gcongr; simp [Nat.le_ceil]
_ ≤ c * n := by gcongr
_ ≤ r i n := hn₂ i
lemma tendsto_atTop_r (i : α) : Tendsto (r i) atTop atTop := by
rw [tendsto_atTop]
intro b
have := R.eventually_r_ge b
rw [Filter.eventually_all] at this
exact_mod_cast this i
lemma tendsto_atTop_r_real (i : α) : Tendsto (fun n => (r i n : ℝ)) atTop atTop :=
Tendsto.comp tendsto_natCast_atTop_atTop (R.tendsto_atTop_r i)
lemma exists_eventually_r_le_const_mul :
∃ c ∈ Set.Ioo (0 : ℝ) 1, ∀ᶠ (n : ℕ) in atTop, ∀ i, r i n ≤ c * n := by
let c := b (max_bi b) + (1 - b (max_bi b)) / 2
have h_max_bi_pos : 0 < b (max_bi b) := R.b_pos _
have h_max_bi_lt_one : 0 < 1 - b (max_bi b) := by
have : b (max_bi b) < 1 := R.b_lt_one _
linarith
have hc_pos : 0 < c := by positivity
have h₁ : 0 < (1 - b (max_bi b)) / 2 := by positivity
have hc_lt_one : c < 1 :=
calc b (max_bi b) + (1 - b (max_bi b)) / 2
_ = b (max_bi b) * (1 / 2) + 1 / 2 := by ring
_ < 1 * (1 / 2) + 1 / 2 := by gcongr; exact R.b_lt_one _
_ = 1 := by norm_num
refine ⟨c, ⟨hc_pos, hc_lt_one⟩, ?_⟩
have hlo := isLittleO_self_div_log_id
rw [Asymptotics.isLittleO_iff] at hlo
have hlo' := hlo h₁
filter_upwards [hlo', R.eventually_r_le_b] with n hn hn'
intro i
rw [Real.norm_of_nonneg (by positivity)] at hn
simp only [Real.norm_of_nonneg (by positivity : 0 ≤ (n : ℝ))] at hn
calc r i n ≤ b i * n + n / log n ^ 2 := by exact hn' i
_ ≤ b i * n + (1 - b (max_bi b)) / 2 * n := by gcongr
_ = (b i + (1 - b (max_bi b)) / 2) * n := by ring
_ ≤ (b (max_bi b) + (1 - b (max_bi b)) / 2) * n := by gcongr; exact max_bi_le _
lemma eventually_r_pos : ∀ᶠ (n : ℕ) in atTop, ∀ i, 0 < r i n := by
rw [Filter.eventually_all]
exact fun i => (R.tendsto_atTop_r i).eventually_gt_atTop 0
lemma eventually_log_b_mul_pos : ∀ᶠ (n : ℕ) in atTop, ∀ i, 0 < log (b i * n) := by
rw [Filter.eventually_all]
intro i
have h : Tendsto (fun (n : ℕ) => log (b i * n)) atTop atTop :=
Tendsto.comp tendsto_log_atTop
<| Tendsto.const_mul_atTop (b_pos R i) tendsto_natCast_atTop_atTop
exact h.eventually_gt_atTop 0
@[aesop safe apply] lemma T_pos (n : ℕ) : 0 < T n := by
induction n using Nat.strongRecOn with
| ind n h_ind =>
cases lt_or_ge n R.n₀ with
| inl hn => exact R.T_gt_zero' n hn -- n < R.n₀
| inr hn => -- R.n₀ ≤ n
rw [R.h_rec n hn]
have := R.g_nonneg
refine add_pos_of_pos_of_nonneg (Finset.sum_pos ?sum_elems univ_nonempty) (by simp_all)
exact fun i _ => mul_pos (R.a_pos i) <| h_ind _ (R.r_lt_n i _ hn)
@[aesop safe apply]
lemma T_nonneg (n : ℕ) : 0 ≤ T n := le_of_lt <| R.T_pos n
end
/-!
### Smoothing function
We define `ε` as the "smoothing function" `fun n => 1 / log n`, which will be used in the form of a
factor of `1 ± ε n` needed to make the induction step go through.
This is its own definition to make it easier to switch to a different smoothing function.
For example, choosing `1 / log n ^ δ` for a suitable choice of `δ` leads to a slightly tighter
theorem at the price of a more complicated proof.
This part of the file then proves several properties of this function that will be needed later in
the proof.
-/
/-- The "smoothing function" is defined as `1 / log n`. This is defined as an `ℝ → ℝ` function
as opposed to `ℕ → ℝ` since this is more convenient for the proof, where we need to e.g. take
derivatives. -/
noncomputable def smoothingFn (n : ℝ) : ℝ := 1 / log n
local notation "ε" => smoothingFn
lemma one_add_smoothingFn_le_two {x : ℝ} (hx : exp 1 ≤ x) : 1 + ε x ≤ 2 := by
simp only [smoothingFn, ← one_add_one_eq_two]
gcongr
have : 1 < x := by
calc 1 = exp 0 := by simp
_ < exp 1 := by simp
_ ≤ x := hx
rw [div_le_one (log_pos this)]
calc 1 = log (exp 1) := by simp
_ ≤ log x := log_le_log (exp_pos _) hx
lemma isLittleO_smoothingFn_one : ε =o[atTop] (fun _ => (1 : ℝ)) := by
unfold smoothingFn
refine isLittleO_of_tendsto (fun _ h => False.elim <| one_ne_zero h) ?_
simp only [one_div, div_one]
exact Tendsto.inv_tendsto_atTop Real.tendsto_log_atTop
lemma isEquivalent_one_add_smoothingFn_one : (fun x => 1 + ε x) ~[atTop] (fun _ => (1 : ℝ)) :=
IsEquivalent.add_isLittleO IsEquivalent.refl isLittleO_smoothingFn_one
lemma isEquivalent_one_sub_smoothingFn_one : (fun x => 1 - ε x) ~[atTop] (fun _ => (1 : ℝ)) :=
IsEquivalent.sub_isLittleO IsEquivalent.refl isLittleO_smoothingFn_one
lemma growsPolynomially_one_sub_smoothingFn : GrowsPolynomially fun x => 1 - ε x :=
GrowsPolynomially.of_isEquivalent_const isEquivalent_one_sub_smoothingFn_one
lemma growsPolynomially_one_add_smoothingFn : GrowsPolynomially fun x => 1 + ε x :=
GrowsPolynomially.of_isEquivalent_const isEquivalent_one_add_smoothingFn_one
lemma eventually_one_sub_smoothingFn_gt_const_real (c : ℝ) (hc : c < 1) :
∀ᶠ (x : ℝ) in atTop, c < 1 - ε x := by
have h₁ : Tendsto (fun x => 1 - ε x) atTop (𝓝 1) := by
rw [← isEquivalent_const_iff_tendsto one_ne_zero]
exact isEquivalent_one_sub_smoothingFn_one
rw [tendsto_order] at h₁
exact h₁.1 c hc
lemma eventually_one_sub_smoothingFn_gt_const (c : ℝ) (hc : c < 1) :
∀ᶠ (n : ℕ) in atTop, c < 1 - ε n :=
Eventually.natCast_atTop (p := fun n => c < 1 - ε n)
<| eventually_one_sub_smoothingFn_gt_const_real c hc
lemma eventually_one_sub_smoothingFn_pos_real : ∀ᶠ (x : ℝ) in atTop, 0 < 1 - ε x :=
eventually_one_sub_smoothingFn_gt_const_real 0 zero_lt_one
lemma eventually_one_sub_smoothingFn_pos : ∀ᶠ (n : ℕ) in atTop, 0 < 1 - ε n :=
(eventually_one_sub_smoothingFn_pos_real).natCast_atTop
lemma eventually_one_sub_smoothingFn_nonneg : ∀ᶠ (n : ℕ) in atTop, 0 ≤ 1 - ε n := by
filter_upwards [eventually_one_sub_smoothingFn_pos] with n hn; exact le_of_lt hn
include R in
lemma eventually_one_sub_smoothingFn_r_pos : ∀ᶠ (n : ℕ) in atTop, ∀ i, 0 < 1 - ε (r i n) := by
rw [Filter.eventually_all]
exact fun i => (R.tendsto_atTop_r_real i).eventually eventually_one_sub_smoothingFn_pos_real
@[aesop safe apply]
lemma differentiableAt_smoothingFn {x : ℝ} (hx : 1 < x) : DifferentiableAt ℝ ε x := by
have : log x ≠ 0 := Real.log_ne_zero_of_pos_of_ne_one (by positivity) (ne_of_gt hx)
change DifferentiableAt ℝ (fun z => 1 / log z) x
simp_rw [one_div]
exact DifferentiableAt.inv (differentiableAt_log (by positivity)) this
@[aesop safe apply]
lemma differentiableAt_one_sub_smoothingFn {x : ℝ} (hx : 1 < x) :
DifferentiableAt ℝ (fun z => 1 - ε z) x :=
DifferentiableAt.sub (differentiableAt_const _) <| differentiableAt_smoothingFn hx
lemma differentiableOn_one_sub_smoothingFn : DifferentiableOn ℝ (fun z => 1 - ε z) (Set.Ioi 1) :=
fun _ hx => (differentiableAt_one_sub_smoothingFn hx).differentiableWithinAt
@[aesop safe apply]
lemma differentiableAt_one_add_smoothingFn {x : ℝ} (hx : 1 < x) :
DifferentiableAt ℝ (fun z => 1 + ε z) x :=
DifferentiableAt.add (differentiableAt_const _) <| differentiableAt_smoothingFn hx
lemma differentiableOn_one_add_smoothingFn : DifferentiableOn ℝ (fun z => 1 + ε z) (Set.Ioi 1) :=
fun _ hx => (differentiableAt_one_add_smoothingFn hx).differentiableWithinAt
lemma deriv_smoothingFn {x : ℝ} (hx : 1 < x) : deriv ε x = -x⁻¹ / (log x ^ 2) := by
have : log x ≠ 0 := Real.log_ne_zero_of_pos_of_ne_one (by positivity) (ne_of_gt hx)
change deriv (fun z => 1 / log z) x = -x⁻¹ / (log x ^ 2)
rw [deriv_fun_div] <;> aesop
lemma isLittleO_deriv_smoothingFn : deriv ε =o[atTop] fun x => x⁻¹ :=
calc deriv ε
_ =ᶠ[atTop] fun x => -x⁻¹ / (log x ^ 2) := by
filter_upwards [eventually_gt_atTop 1] with x hx
rw [deriv_smoothingFn hx]
_ = fun x => (-x * log x ^ 2)⁻¹ := by
simp_rw [neg_div, div_eq_mul_inv, ← mul_inv, neg_inv, neg_mul]
_ =o[atTop] fun x => (x * 1)⁻¹ := by
refine IsLittleO.inv_rev ?_ ?_
· refine IsBigO.mul_isLittleO
(by rw [isBigO_neg_right]; aesop (add safe isBigO_refl)) ?_
rw [isLittleO_one_left_iff]
exact Tendsto.comp tendsto_norm_atTop_atTop
<| Tendsto.comp (tendsto_pow_atTop (by norm_num)) tendsto_log_atTop
· exact Filter.Eventually.of_forall (fun x hx => by rw [mul_one] at hx; simp [hx])
_ = fun x => x⁻¹ := by simp
lemma eventually_deriv_one_sub_smoothingFn :
deriv (fun x => 1 - ε x) =ᶠ[atTop] fun x => x⁻¹ / (log x ^ 2) :=
calc deriv (fun x => 1 - ε x)
_ =ᶠ[atTop] -(deriv ε) := by
filter_upwards [eventually_gt_atTop 1] with x hx; rw [deriv_fun_sub] <;> aesop
_ =ᶠ[atTop] fun x => x⁻¹ / (log x ^ 2) := by
filter_upwards [eventually_gt_atTop 1] with x hx
simp [deriv_smoothingFn hx, neg_div]
lemma eventually_deriv_one_add_smoothingFn :
deriv (fun x => 1 + ε x) =ᶠ[atTop] fun x => -x⁻¹ / (log x ^ 2) :=
calc deriv (fun x => 1 + ε x)
_ =ᶠ[atTop] deriv ε := by
filter_upwards [eventually_gt_atTop 1] with x hx; rw [deriv_fun_add] <;> aesop
_ =ᶠ[atTop] fun x => -x⁻¹ / (log x ^ 2) := by
filter_upwards [eventually_gt_atTop 1] with x hx
simp [deriv_smoothingFn hx]
lemma isLittleO_deriv_one_sub_smoothingFn :
deriv (fun x => 1 - ε x) =o[atTop] fun (x : ℝ) => x⁻¹ :=
calc deriv (fun x => 1 - ε x)
_ =ᶠ[atTop] fun z => -(deriv ε z) := by
filter_upwards [eventually_gt_atTop 1] with x hx; rw [deriv_fun_sub] <;> aesop
_ =o[atTop] fun x => x⁻¹ := by rw [isLittleO_neg_left]; exact isLittleO_deriv_smoothingFn
lemma isLittleO_deriv_one_add_smoothingFn :
deriv (fun x => 1 + ε x) =o[atTop] fun (x : ℝ) => x⁻¹ :=
calc deriv (fun x => 1 + ε x)
_ =ᶠ[atTop] fun z => deriv ε z := by
filter_upwards [eventually_gt_atTop 1] with x hx; rw [deriv_fun_add] <;> aesop
_ =o[atTop] fun x => x⁻¹ := isLittleO_deriv_smoothingFn
lemma eventually_one_add_smoothingFn_pos : ∀ᶠ (n : ℕ) in atTop, 0 < 1 + ε n := by
have h₁ := isLittleO_smoothingFn_one
rw [isLittleO_iff] at h₁
refine Eventually.natCast_atTop (p := fun n => 0 < 1 + ε n) ?_
filter_upwards [h₁ (by simp : (0 : ℝ) < 1 / 2), eventually_gt_atTop 1] with x _ hx'
have : 0 < log x := Real.log_pos hx'
change 0 < 1 + 1 / log x
positivity
include R in
lemma eventually_one_add_smoothingFn_r_pos : ∀ᶠ (n : ℕ) in atTop, ∀ i, 0 < 1 + ε (r i n) := by
rw [Filter.eventually_all]
exact fun i => (R.tendsto_atTop_r i).eventually (f := r i) eventually_one_add_smoothingFn_pos
lemma eventually_one_add_smoothingFn_nonneg : ∀ᶠ (n : ℕ) in atTop, 0 ≤ 1 + ε n := by
filter_upwards [eventually_one_add_smoothingFn_pos] with n hn; exact le_of_lt hn
lemma strictAntiOn_smoothingFn : StrictAntiOn ε (Set.Ioi 1) := by
change StrictAntiOn (fun x => 1 / log x) (Set.Ioi 1)
simp_rw [one_div]
refine StrictAntiOn.comp_strictMonoOn inv_strictAntiOn ?log fun _ hx => log_pos hx
refine StrictMonoOn.mono strictMonoOn_log (fun x hx => ?_)
exact Set.Ioi_subset_Ioi zero_le_one hx
lemma strictMonoOn_one_sub_smoothingFn :
StrictMonoOn (fun (x : ℝ) => (1 : ℝ) - ε x) (Set.Ioi 1) := by
simp_rw [sub_eq_add_neg]
exact StrictMonoOn.const_add (StrictAntiOn.neg <| strictAntiOn_smoothingFn) 1
lemma strictAntiOn_one_add_smoothingFn : StrictAntiOn (fun (x : ℝ) => (1 : ℝ) + ε x) (Set.Ioi 1) :=
StrictAntiOn.const_add strictAntiOn_smoothingFn 1
section
include R
lemma isEquivalent_smoothingFn_sub_self (i : α) :
(fun (n : ℕ) => ε (b i * n) - ε n) ~[atTop] fun n => -log (b i) / (log n) ^ 2 := by
calc (fun (n : ℕ) => 1 / log (b i * n) - 1 / log n)
_ =ᶠ[atTop] fun (n : ℕ) => (log n - log (b i * n)) / (log (b i * n) * log n) := by
filter_upwards [eventually_gt_atTop 1, R.eventually_log_b_mul_pos] with n hn hn'
have h_log_pos : 0 < log n := Real.log_pos <| by simp_all
simp only [one_div]
rw [inv_sub_inv (by have := hn' i; positivity) (by aesop)]
_ =ᶠ[atTop] (fun (n : ℕ) ↦ (log n - log (b i) - log n) / ((log (b i) + log n) * log n)) := by
filter_upwards [eventually_ne_atTop 0] with n hn
have : 0 < b i := R.b_pos i
rw [log_mul (by positivity) (by simp_all), sub_add_eq_sub_sub]
_ = (fun (n : ℕ) => -log (b i) / ((log (b i) + log n) * log n)) := by ext; congr; ring
_ ~[atTop] (fun (n : ℕ) => -log (b i) / (log n * log n)) := by
refine IsEquivalent.div (IsEquivalent.refl) <| IsEquivalent.mul ?_ (IsEquivalent.refl)
have : (fun (n : ℕ) => log (b i) + log n) = fun (n : ℕ) => log n + log (b i) := by
ext; simp [add_comm]
rw [this]
exact IsEquivalent.add_isLittleO IsEquivalent.refl
<| IsLittleO.natCast_atTop (f := fun (_ : ℝ) => log (b i))
isLittleO_const_log_atTop
_ = (fun (n : ℕ) => -log (b i) / (log n) ^ 2) := by ext; congr 1; rw [← pow_two]
lemma isTheta_smoothingFn_sub_self (i : α) :
(fun (n : ℕ) => ε (b i * n) - ε n) =Θ[atTop] fun n => 1 / (log n) ^ 2 := by
calc (fun (n : ℕ) => ε (b i * n) - ε n)
_ =Θ[atTop] fun n => (-log (b i)) / (log n) ^ 2 :=
(R.isEquivalent_smoothingFn_sub_self i).isTheta
_ = fun (n : ℕ) => (-log (b i)) * 1 / (log n) ^ 2 := by simp only [mul_one]
_ = fun (n : ℕ) => -log (b i) * (1 / (log n) ^ 2) := by simp_rw [← mul_div_assoc]
_ =Θ[atTop] fun (n : ℕ) => 1 / (log n) ^ 2 := by
have : -log (b i) ≠ 0 := by
rw [neg_ne_zero]
exact Real.log_ne_zero_of_pos_of_ne_one (R.b_pos i) (ne_of_lt <| R.b_lt_one i)
rw [← isTheta_const_mul_right this]
/-!
### Akra-Bazzi exponent `p`
Every Akra-Bazzi recurrence has an associated exponent, denoted by `p : ℝ`, such that
`∑ a_i b_i^p = 1`. This section shows the existence and uniqueness of this exponent `p` for any
`R : AkraBazziRecurrence`. These results are used in the next section to define the asymptotic
bound expression. -/
@[continuity, fun_prop]
lemma continuous_sumCoeffsExp : Continuous (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) := by
refine continuous_finset_sum Finset.univ fun i _ => Continuous.mul (by fun_prop) ?_
exact Continuous.rpow continuous_const continuous_id (fun x => Or.inl (ne_of_gt (R.b_pos i)))
lemma strictAnti_sumCoeffsExp : StrictAnti (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) := by
rw [← Finset.sum_fn]
refine Finset.sum_induction_nonempty _ _ (fun _ _ => StrictAnti.add) univ_nonempty ?terms
refine fun i _ => StrictAnti.const_mul ?_ (R.a_pos i)
exact Real.strictAnti_rpow_of_base_lt_one (R.b_pos i) (R.b_lt_one i)
lemma tendsto_zero_sumCoeffsExp : Tendsto (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) atTop (𝓝 0) := by
have h₁ : Finset.univ.sum (fun _ : α => (0 : ℝ)) = 0 := by simp
rw [← h₁]
refine tendsto_finset_sum (univ : Finset α) (fun i _ => ?_)
rw [← mul_zero (a i)]
refine Tendsto.mul (by simp) <| tendsto_rpow_atTop_of_base_lt_one _ ?_ (R.b_lt_one i)
have := R.b_pos i
linarith
lemma tendsto_atTop_sumCoeffsExp : Tendsto (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) atBot atTop := by
have h₁ : Tendsto (fun p : ℝ => (a (max_bi b) : ℝ) * b (max_bi b) ^ p) atBot atTop :=
Tendsto.const_mul_atTop (R.a_pos (max_bi b)) <| tendsto_rpow_atBot_of_base_lt_one _
(by have := R.b_pos (max_bi b); linarith) (R.b_lt_one _)
refine tendsto_atTop_mono (fun p => ?_) h₁
refine Finset.single_le_sum (f := fun i => (a i : ℝ) * b i ^ p) (fun i _ => ?_) (mem_univ _)
positivity [R.a_pos i, R.b_pos i]
lemma one_mem_range_sumCoeffsExp : 1 ∈ Set.range (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) := by
refine mem_range_of_exists_le_of_exists_ge R.continuous_sumCoeffsExp ?le_one ?ge_one
case le_one =>
exact R.tendsto_zero_sumCoeffsExp.eventually_le_const zero_lt_one |>.exists
case ge_one =>
exact R.tendsto_atTop_sumCoeffsExp.eventually_ge_atTop _ |>.exists
/-- The function x ↦ ∑ a_i b_i^x is injective. This implies the uniqueness of `p`. -/
lemma injective_sumCoeffsExp : Function.Injective (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) :=
R.strictAnti_sumCoeffsExp.injective
end
variable (a b) in
/-- The exponent `p` associated with a particular Akra-Bazzi recurrence. -/
noncomputable irreducible_def p : ℝ := Function.invFun (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) 1
include R in
-- Cannot be @[simp] because `T`, `g`, `r`, and `R` cannot be inferred by `simp`.
lemma sumCoeffsExp_p_eq_one : ∑ i, a i * (b i) ^ p a b = 1 := by
simp only [p]
exact Function.invFun_eq (by rw [← Set.mem_range]; exact R.one_mem_range_sumCoeffsExp)
/-!
### The sum transform
This section defines the "sum transform" of a function `g` as
`∑ u ∈ Finset.Ico n₀ n, g u / u ^ (p + 1)`, and uses it to define `asympBound` as the bound
satisfied by an Akra-Bazzi recurrence, namely `n^p (1 + ∑_{u < n} g(u) / u^(p+1))`. Here, the
exponent `p` refers to the one established in the previous section.
Several properties of the sum transform are then proven.
-/
/-- The transformation that turns a function `g` into
`n ^ p * ∑ u ∈ Finset.Ico n₀ n, g u / u ^ (p + 1)`. -/
noncomputable def sumTransform (p : ℝ) (g : ℝ → ℝ) (n₀ n : ℕ) :=
n ^ p * ∑ u ∈ Finset.Ico n₀ n, g u / u ^ (p + 1)
lemma sumTransform_def {p : ℝ} {g : ℝ → ℝ} {n₀ n : ℕ} :
sumTransform p g n₀ n = n ^ p * ∑ u ∈ Finset.Ico n₀ n, g u / u ^ (p + 1) := rfl
variable (g) (a) (b)
/-- The asymptotic bound satisfied by an Akra-Bazzi recurrence, namely
`n^p (1 + ∑_{u < n} g(u) / u^(p+1))`. -/
noncomputable def asympBound (n : ℕ) : ℝ := n ^ p a b + sumTransform (p a b) g 0 n
lemma asympBound_def {α} [Fintype α] (a b : α → ℝ) {n : ℕ} :
asympBound g a b n = n ^ p a b + sumTransform (p a b) g 0 n := rfl
variable {g} {a} {b}
lemma asympBound_def' {α} [Fintype α] (a b : α → ℝ) {n : ℕ} :
asympBound g a b n = n ^ p a b * (1 + (∑ u ∈ range n, g u / u ^ (p a b + 1))) := by
simp [asympBound_def, sumTransform, mul_add, mul_one]
section
include R
lemma asympBound_pos (n : ℕ) (hn : 0 < n) : 0 < asympBound g a b n := by
calc 0 < (n : ℝ) ^ p a b * (1 + 0) := by aesop (add safe Real.rpow_pos_of_pos)
_ ≤ asympBound g a b n := by
simp only [asympBound_def']
gcongr n ^ p a b * (1 + ?_)
have := R.g_nonneg
aesop (add safe Real.rpow_nonneg, safe div_nonneg, safe Finset.sum_nonneg)
lemma eventually_asympBound_pos : ∀ᶠ (n : ℕ) in atTop, 0 < asympBound g a b n := by
filter_upwards [eventually_gt_atTop 0] with n hn using R.asympBound_pos n hn
lemma eventually_asympBound_r_pos : ∀ᶠ (n : ℕ) in atTop, ∀ i, 0 < asympBound g a b (r i n) := by
rw [Filter.eventually_all]
exact fun i => (R.tendsto_atTop_r i).eventually R.eventually_asympBound_pos
lemma eventually_atTop_sumTransform_le :
∃ c > 0, ∀ᶠ (n : ℕ) in atTop, ∀ i, sumTransform (p a b) g (r i n) n ≤ c * g n := by
obtain ⟨c₁, hc₁_mem, hc₁⟩ := R.exists_eventually_const_mul_le_r
obtain ⟨c₂, hc₂_mem, hc₂⟩ := R.g_grows_poly.eventually_atTop_le_nat hc₁_mem
have hc₁_pos : 0 < c₁ := hc₁_mem.1
refine ⟨max c₂ (c₂ / c₁ ^ (p a b + 1)), by positivity, ?_⟩
filter_upwards [hc₁, hc₂, R.eventually_r_pos, R.eventually_r_lt_n, eventually_gt_atTop 0]
with n hn₁ hn₂ hrpos hr_lt_n hn_pos i
have hrpos_i := hrpos i
have g_nonneg : 0 ≤ g n := R.g_nonneg n (by positivity)
cases le_or_gt 0 (p a b + 1) with
| inl hp => -- 0 ≤ p a b + 1
calc sumTransform (p a b) g (r i n) n
= n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1)) := by rfl
_ ≤ n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, c₂ * g n / u ^ ((p a b) + 1)) := by
gcongr with u hu
rw [Finset.mem_Ico] at hu
have hu' : u ∈ Set.Icc (r i n) n := ⟨hu.1, by cutsat⟩
refine hn₂ u ?_
rw [Set.mem_Icc]
refine ⟨?_, by norm_cast; cutsat⟩
calc c₁ * n ≤ r i n := by exact hn₁ i
_ ≤ u := by exact_mod_cast hu'.1
_ ≤ n ^ (p a b) * (∑ _u ∈ Finset.Ico (r i n) n, c₂ * g n / (r i n) ^ ((p a b) + 1)) := by
gcongr with u hu; rw [Finset.mem_Ico] at hu; exact hu.1
_ ≤ n ^ p a b * #(Ico (r i n) n) • (c₂ * g n / r i n ^ (p a b + 1)) := by
gcongr; exact Finset.sum_le_card_nsmul _ _ _ (fun x _ => by rfl)
_ = n ^ p a b * #(Ico (r i n) n) * (c₂ * g n / r i n ^ (p a b + 1)) := by
rw [nsmul_eq_mul, mul_assoc]
_ = n ^ (p a b) * (n - r i n) * (c₂ * g n / (r i n) ^ ((p a b) + 1)) := by
congr; rw [Nat.card_Ico, Nat.cast_sub (le_of_lt <| hr_lt_n i)]
_ ≤ n ^ (p a b) * n * (c₂ * g n / (r i n) ^ ((p a b) + 1)) := by
gcongr; simp only [tsub_le_iff_right, le_add_iff_nonneg_right, Nat.cast_nonneg]
_ ≤ n ^ (p a b) * n * (c₂ * g n / (c₁ * n) ^ ((p a b) + 1)) := by
gcongr; exact hn₁ i
_ = c₂ * g n * n ^ ((p a b) + 1) / (c₁ * n) ^ ((p a b) + 1) := by
rw [← Real.rpow_add_one (by positivity) (p a b)]; ring
_ = c₂ * g n * n ^ ((p a b) + 1) / (n ^ ((p a b) + 1) * c₁ ^ ((p a b) + 1)) := by
rw [mul_comm c₁, Real.mul_rpow (by positivity) (by positivity)]
_ = c₂ * g n * (n ^ ((p a b) + 1) / (n ^ ((p a b) + 1))) / c₁ ^ ((p a b) + 1) := by ring
_ = c₂ * g n / c₁ ^ ((p a b) + 1) := by rw [div_self (by positivity), mul_one]
_ = (c₂ / c₁ ^ ((p a b) + 1)) * g n := by ring
_ ≤ max c₂ (c₂ / c₁ ^ ((p a b) + 1)) * g n := by gcongr; exact le_max_right _ _
| inr hp => -- p a b + 1 < 0
calc sumTransform (p a b) g (r i n) n
_ = n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1)) := by rfl
_ ≤ n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, c₂ * g n / u ^ ((p a b) + 1)) := by
gcongr with u hu
rw [Finset.mem_Ico] at hu
have hu' : u ∈ Set.Icc (r i n) n := ⟨hu.1, by cutsat⟩
refine hn₂ u ?_
rw [Set.mem_Icc]
refine ⟨?_, by norm_cast; cutsat⟩
calc c₁ * n ≤ r i n := by exact hn₁ i
_ ≤ u := by exact_mod_cast hu'.1
_ ≤ n ^ (p a b) * (∑ _u ∈ Finset.Ico (r i n) n, c₂ * g n / n ^ ((p a b) + 1)) := by
gcongr n ^ (p a b) * (Finset.Ico (r i n) n).sum (fun _ => c₂ * g n / ?_) with u hu
rw [Finset.mem_Ico] at hu
have : 0 < u := calc
0 < r i n := by exact hrpos_i
_ ≤ u := by exact hu.1
exact rpow_le_rpow_of_nonpos (by positivity)
(by exact_mod_cast (le_of_lt hu.2)) (le_of_lt hp)
_ ≤ n ^ p a b * #(Ico (r i n) n) • (c₂ * g n / n ^ (p a b + 1)) := by
gcongr; exact Finset.sum_le_card_nsmul _ _ _ (fun x _ => by rfl)
_ = n ^ p a b * #(Ico (r i n) n) * (c₂ * g n / n ^ (p a b + 1)) := by
rw [nsmul_eq_mul, mul_assoc]
_ = n ^ (p a b) * (n - r i n) * (c₂ * g n / n ^ ((p a b) + 1)) := by
congr; rw [Nat.card_Ico, Nat.cast_sub (le_of_lt <| hr_lt_n i)]
_ ≤ n ^ (p a b) * n * (c₂ * g n / n ^ ((p a b) + 1)) := by
gcongr; simp only [tsub_le_iff_right, le_add_iff_nonneg_right, Nat.cast_nonneg]
_ = c₂ * (n^((p a b) + 1) / n ^ ((p a b) + 1)) * g n := by
rw [← Real.rpow_add_one (by positivity) (p a b)]; ring
_ = c₂ * g n := by rw [div_self (by positivity), mul_one]
_ ≤ max c₂ (c₂ / c₁ ^ ((p a b) + 1)) * g n := by gcongr; exact le_max_left _ _
lemma eventually_atTop_sumTransform_ge :
∃ c > 0, ∀ᶠ (n : ℕ) in atTop, ∀ i, c * g n ≤ sumTransform (p a b) g (r i n) n := by
obtain ⟨c₁, hc₁_mem, hc₁⟩ := R.exists_eventually_const_mul_le_r
obtain ⟨c₂, hc₂_mem, hc₂⟩ := R.g_grows_poly.eventually_atTop_ge_nat hc₁_mem
obtain ⟨c₃, hc₃_mem, hc₃⟩ := R.exists_eventually_r_le_const_mul
have hc₁_pos : 0 < c₁ := hc₁_mem.1
have hc₃' : 0 < (1 - c₃) := by have := hc₃_mem.2; linarith
refine ⟨min (c₂ * (1 - c₃)) ((1 - c₃) * c₂ / c₁^((p a b) + 1)), by positivity, ?_⟩
filter_upwards [hc₁, hc₂, hc₃, R.eventually_r_pos, R.eventually_r_lt_n, eventually_gt_atTop 0]
with n hn₁ hn₂ hn₃ hrpos hr_lt_n hn_pos
intro i
have hrpos_i := hrpos i
have g_nonneg : 0 ≤ g n := R.g_nonneg n (by positivity)
cases le_or_gt 0 (p a b + 1) with
| inl hp => -- 0 ≤ (p a b) + 1
calc sumTransform (p a b) g (r i n) n
_ = n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1)) := rfl
_ ≥ n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, c₂ * g n / u^((p a b) + 1)) := by
gcongr with u hu
rw [Finset.mem_Ico] at hu
have hu' : u ∈ Set.Icc (r i n) n := ⟨hu.1, by cutsat⟩
refine hn₂ u ?_
rw [Set.mem_Icc]
refine ⟨?_, by norm_cast; cutsat⟩
calc c₁ * n ≤ r i n := by exact hn₁ i
_ ≤ u := by exact_mod_cast hu'.1
_ ≥ n ^ (p a b) * (∑ _u ∈ Finset.Ico (r i n) n, c₂ * g n / n ^ ((p a b) + 1)) := by
gcongr with u hu
· rw [Finset.mem_Ico] at hu
have := calc 0 < r i n := hrpos_i
_ ≤ u := hu.1
positivity
· rw [Finset.mem_Ico] at hu
exact le_of_lt hu.2
_ ≥ n ^ p a b * #(Ico (r i n) n) • (c₂ * g n / n ^ (p a b + 1)) := by
gcongr; exact Finset.card_nsmul_le_sum _ _ _ (fun x _ => by rfl)
_ = n ^ p a b * #(Ico (r i n) n) * (c₂ * g n / n ^ (p a b + 1)) := by
rw [nsmul_eq_mul, mul_assoc]
_ = n ^ (p a b) * (n - r i n) * (c₂ * g n / n ^ ((p a b) + 1)) := by
congr; rw [Nat.card_Ico, Nat.cast_sub (le_of_lt <| hr_lt_n i)]
_ ≥ n ^ (p a b) * (n - c₃ * n) * (c₂ * g n / n ^ ((p a b) + 1)) := by
gcongr; exact hn₃ i
_ = n ^ (p a b) * n * (1 - c₃) * (c₂ * g n / n ^ ((p a b) + 1)) := by ring
_ = c₂ * (1 - c₃) * g n * (n ^ ((p a b) + 1) / n ^ ((p a b) + 1)) := by
rw [← Real.rpow_add_one (by positivity) (p a b)]; ring
_ = c₂ * (1 - c₃) * g n := by rw [div_self (by positivity), mul_one]
_ ≥ min (c₂ * (1 - c₃)) ((1 - c₃) * c₂ / c₁ ^ ((p a b) + 1)) * g n := by
gcongr; exact min_le_left _ _
| inr hp => -- (p a b) + 1 < 0
calc sumTransform (p a b) g (r i n) n
= n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u^((p a b) + 1)) := by rfl
_ ≥ n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, c₂ * g n / u ^ ((p a b) + 1)) := by
gcongr with u hu
rw [Finset.mem_Ico] at hu
have hu' : u ∈ Set.Icc (r i n) n := ⟨hu.1, by cutsat⟩
refine hn₂ u ?_
rw [Set.mem_Icc]
refine ⟨?_, by norm_cast; cutsat⟩
calc c₁ * n ≤ r i n := by exact hn₁ i
_ ≤ u := by exact_mod_cast hu'.1
_ ≥ n ^ (p a b) * (∑ _u ∈ Finset.Ico (r i n) n, c₂ * g n / (r i n) ^ ((p a b) + 1)) := by
gcongr n^(p a b) * (Finset.Ico (r i n) n).sum (fun _ => c₂ * g n / ?_) with u hu
· rw [Finset.mem_Ico] at hu
have := calc 0 < r i n := hrpos_i
_ ≤ u := hu.1
positivity
· rw [Finset.mem_Ico] at hu
exact rpow_le_rpow_of_nonpos (by positivity)
(by exact_mod_cast hu.1) (le_of_lt hp)
_ ≥ n ^ p a b * #(Ico (r i n) n) • (c₂ * g n / r i n ^ (p a b + 1)) := by
gcongr; exact Finset.card_nsmul_le_sum _ _ _ (fun x _ => by rfl)
_ = n ^ p a b * #(Ico (r i n) n) * (c₂ * g n / r i n ^ (p a b + 1)) := by
rw [nsmul_eq_mul, mul_assoc]
_ ≥ n ^ p a b * #(Ico (r i n) n) * (c₂ * g n / (c₁ * n) ^ (p a b + 1)) := by
gcongr n ^ p a b * #(Ico (r i n) n) * (c₂ * g n / ?_)
exact rpow_le_rpow_of_nonpos (by positivity) (hn₁ i) (le_of_lt hp)
_ = n ^ (p a b) * (n - r i n) * (c₂ * g n / (c₁ * n) ^ ((p a b) + 1)) := by
congr; rw [Nat.card_Ico, Nat.cast_sub (le_of_lt <| hr_lt_n i)]
_ ≥ n ^ (p a b) * (n - c₃ * n) * (c₂ * g n / (c₁ * n) ^ ((p a b) + 1)) := by
gcongr; exact hn₃ i
_ = n ^ (p a b) * n * (1 - c₃) * (c₂ * g n / (c₁ * n) ^ ((p a b) + 1)) := by ring
_ = n ^ (p a b) * n * (1 - c₃) * (c₂ * g n / (c₁ ^ ((p a b) + 1) * n ^ ((p a b) + 1))) := by
rw [Real.mul_rpow (by positivity) (by positivity)]
_ = (n ^ ((p a b) + 1) / n ^ ((p a b) + 1)) * (1 - c₃) * c₂ * g n / c₁ ^ ((p a b) + 1) := by
rw [← Real.rpow_add_one (by positivity) (p a b)]; ring
_ = (1 - c₃) * c₂ / c₁ ^ ((p a b) + 1) * g n := by
rw [div_self (by positivity), one_mul]; ring
_ ≥ min (c₂ * (1 - c₃)) ((1 - c₃) * c₂ / c₁ ^ ((p a b) + 1)) * g n := by
gcongr; exact min_le_right _ _
end
end AkraBazziRecurrence |
.lake/packages/mathlib/Mathlib/Computability/AkraBazzi/GrowsPolynomially.lean | import Mathlib.Analysis.Asymptotics.AsymptoticEquivalent
import Mathlib.Analysis.SpecialFunctions.Pow.Real
import Mathlib.Algebra.Order.ToIntervalMod
import Mathlib.Analysis.SpecialFunctions.Log.Base
/-!
# Akra-Bazzi theorem: the polynomial growth condition
This file defines and develops an API for the polynomial growth condition that appears in the
statement of the Akra-Bazzi theorem: for the theorem to hold, the function `g` must
satisfy the condition that `c₁ g(n) ≤ g(u) ≤ c₂ g(n)`, for u between b*n and n for any constant
`b ∈ (0,1)`.
## Implementation notes
Our definition requires that the condition hold for any `b ∈ (0,1)`. This is equivalent to requiring
it only for `b = 1 / 2` (or any other particular value in `(0, 1)`). While this could, in principle,
make it harder to prove that a particular function grows polynomially, this issue does not seem to
arise in practice.
-/
open Finset Real Filter Asymptotics
open scoped Topology
namespace AkraBazziRecurrence
/-- The growth condition that the function `g` must satisfy for the Akra-Bazzi theorem to apply.
It roughly states that `c₁ g(n) ≤ g(u) ≤ c₂ g(n)`, for `u` between `b * n` and `n`, for any
constant `b ∈ (0, 1)`. -/
def GrowsPolynomially (f : ℝ → ℝ) : Prop :=
∀ b ∈ Set.Ioo 0 1, ∃ c₁ > 0, ∃ c₂ > 0,
∀ᶠ x in atTop, ∀ u ∈ Set.Icc (b * x) x, f u ∈ Set.Icc (c₁ * (f x)) (c₂ * f x)
namespace GrowsPolynomially
lemma congr_of_eventuallyEq {f g : ℝ → ℝ} (hfg : f =ᶠ[atTop] g) (hg : GrowsPolynomially g) :
GrowsPolynomially f := by
intro b hb
have hg' := hg b hb
obtain ⟨c₁, hc₁_mem, c₂, hc₂_mem, hg'⟩ := hg'
refine ⟨c₁, hc₁_mem, c₂, hc₂_mem, ?_⟩
filter_upwards [hg', (tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hfg, hfg]
with x hx₁ hx₂ hx₃
intro u hu
rw [hx₂ u hu.1, hx₃]
exact hx₁ u hu
lemma iff_eventuallyEq {f g : ℝ → ℝ} (h : f =ᶠ[atTop] g) :
GrowsPolynomially f ↔ GrowsPolynomially g :=
⟨fun hf => congr_of_eventuallyEq h.symm hf, fun hg => congr_of_eventuallyEq h hg⟩
variable {f : ℝ → ℝ}
lemma eventually_atTop_le {b : ℝ} (hb : b ∈ Set.Ioo 0 1) (hf : GrowsPolynomially f) :
∃ c > 0, ∀ᶠ x in atTop, ∀ u ∈ Set.Icc (b * x) x, f u ≤ c * f x := by
obtain ⟨c₁, _, c₂, hc₂, h⟩ := hf b hb
refine ⟨c₂, hc₂, ?_⟩
filter_upwards [h]
exact fun _ H u hu => (H u hu).2
lemma eventually_atTop_le_nat {b : ℝ} (hb : b ∈ Set.Ioo 0 1) (hf : GrowsPolynomially f) :
∃ c > 0, ∀ᶠ (n : ℕ) in atTop, ∀ u ∈ Set.Icc (b * n) n, f u ≤ c * f n := by
obtain ⟨c, hc_mem, hc⟩ := hf.eventually_atTop_le hb
exact ⟨c, hc_mem, hc.natCast_atTop⟩
lemma eventually_atTop_ge {b : ℝ} (hb : b ∈ Set.Ioo 0 1) (hf : GrowsPolynomially f) :
∃ c > 0, ∀ᶠ x in atTop, ∀ u ∈ Set.Icc (b * x) x, c * f x ≤ f u := by
obtain ⟨c₁, hc₁, c₂, _, h⟩ := hf b hb
refine ⟨c₁, hc₁, ?_⟩
filter_upwards [h]
exact fun _ H u hu => (H u hu).1
lemma eventually_atTop_ge_nat {b : ℝ} (hb : b ∈ Set.Ioo 0 1) (hf : GrowsPolynomially f) :
∃ c > 0, ∀ᶠ (n : ℕ) in atTop, ∀ u ∈ Set.Icc (b * n) n, c * f n ≤ f u := by
obtain ⟨c, hc_mem, hc⟩ := hf.eventually_atTop_ge hb
exact ⟨c, hc_mem, hc.natCast_atTop⟩
lemma eventually_zero_of_frequently_zero (hf : GrowsPolynomially f) (hf' : ∃ᶠ x in atTop, f x = 0) :
∀ᶠ x in atTop, f x = 0 := by
obtain ⟨c₁, hc₁_mem, c₂, hc₂_mem, hf⟩ := hf (1 / 2) (by norm_num)
rw [frequently_atTop] at hf'
filter_upwards [eventually_forall_ge_atTop.mpr hf, eventually_gt_atTop 0] with x hx hx_pos
obtain ⟨x₀, hx₀_ge, hx₀⟩ := hf' (max x 1)
have x₀_pos := calc
0 < 1 := by norm_num
_ ≤ x₀ := le_of_max_le_right hx₀_ge
have hmain : ∀ (m : ℕ) (z : ℝ), x ≤ z →
z ∈ Set.Icc ((2 : ℝ) ^ (-(m : ℤ) - 1) * x₀) ((2 : ℝ) ^ (-(m : ℤ)) * x₀) → f z = 0 := by
intro m
induction m with
| zero =>
simp only [CharP.cast_eq_zero, neg_zero, zero_sub, zpow_zero, one_mul] at *
specialize hx x₀ (le_of_max_le_left hx₀_ge)
simp only [hx₀, mul_zero, Set.Icc_self, Set.mem_singleton_iff] at hx
refine fun z _ hz => hx _ ?_
simp only [zpow_neg, zpow_one] at hz
simp only [one_div, hz]
| succ k ih =>
intro z hxz hz
simp only [Nat.cast_add, Nat.cast_one] at *
have hx' : x ≤ (2 : ℝ)^(-(k : ℤ) - 1) * x₀ := by
calc x ≤ z := hxz
_ ≤ _ := by simp only [neg_add, ← sub_eq_add_neg] at hz; exact hz.2
specialize hx ((2 : ℝ)^(-(k : ℤ) - 1) * x₀) hx' z
specialize ih ((2 : ℝ)^(-(k : ℤ) - 1) * x₀) hx' ?ineq
case ineq =>
rw [Set.left_mem_Icc]
gcongr
· norm_num
· cutsat
simp only [ih, mul_zero, Set.Icc_self, Set.mem_singleton_iff] at hx
refine hx ⟨?lb₁, ?ub₁⟩
case lb₁ =>
rw [one_div, ← zpow_neg_one, ← mul_assoc, ← zpow_add₀ (by norm_num)]
have h₁ : (-1 : ℤ) + (-k - 1) = -k - 2 := by ring
have h₂ : -(k + (1 : ℤ)) - 1 = -k - 2 := by ring
rw [h₁]
rw [h₂] at hz
exact hz.1
case ub₁ =>
have := hz.2
simp only [neg_add, ← sub_eq_add_neg] at this
exact this
refine hmain ⌊-logb 2 (x / x₀)⌋₊ x le_rfl ⟨?lb, ?ub⟩
case lb =>
rw [← le_div_iff₀ x₀_pos]
refine (logb_le_logb (b := 2) (by norm_num) (zpow_pos (by norm_num) _)
(by positivity)).mp ?_
rw [← rpow_intCast, logb_rpow (by norm_num) (by norm_num), ← neg_le_neg_iff]
simp only [Int.cast_sub, Int.cast_neg, Int.cast_natCast, Int.cast_one, neg_sub, sub_neg_eq_add]
calc -logb 2 (x / x₀) ≤ ⌈-logb 2 (x / x₀)⌉₊ := Nat.le_ceil (-logb 2 (x / x₀))
_ ≤ _ := by rw [add_comm]; exact_mod_cast Nat.ceil_le_floor_add_one _
case ub =>
rw [← div_le_iff₀ x₀_pos]
refine (logb_le_logb (b := 2) (by norm_num) (by positivity)
(zpow_pos (by norm_num) _)).mp ?_
rw [← rpow_intCast, logb_rpow (by norm_num) (by norm_num), ← neg_le_neg_iff]
simp only [Int.cast_neg, Int.cast_natCast, neg_neg]
have : 0 ≤ -logb 2 (x / x₀) := by
rw [neg_nonneg]
refine logb_nonpos (by norm_num) (by positivity) ?_
rw [div_le_one x₀_pos]
exact le_of_max_le_left hx₀_ge
exact_mod_cast Nat.floor_le this
lemma eventually_atTop_nonneg_or_nonpos (hf : GrowsPolynomially f) :
(∀ᶠ x in atTop, 0 ≤ f x) ∨ (∀ᶠ x in atTop, f x ≤ 0) := by
obtain ⟨c₁, _, c₂, _, h⟩ := hf (1 / 2) (by norm_num)
match lt_trichotomy c₁ c₂ with
| .inl hlt => -- c₁ < c₂
left
filter_upwards [h, eventually_ge_atTop 0] with x hx hx_nonneg
have h' : 3 / 4 * x ∈ Set.Icc (1 / 2 * x) x := by
rw [Set.mem_Icc]
exact ⟨by gcongr ?_ * x; norm_num, by linarith⟩
have hu := hx (3 / 4 * x) h'
have hu := Set.nonempty_of_mem hu
rw [Set.nonempty_Icc] at hu
have hu' : 0 ≤ (c₂ - c₁) * f x := by linarith
exact nonneg_of_mul_nonneg_right hu' (by linarith)
| .inr (.inr hgt) => -- c₂ < c₁
right
filter_upwards [h, eventually_ge_atTop 0] with x hx hx_nonneg
have h' : 3 / 4 * x ∈ Set.Icc (1 / 2 * x) x := by
rw [Set.mem_Icc]
exact ⟨by gcongr ?_ * x; norm_num, by linarith⟩
have hu := hx (3 / 4 * x) h'
have hu := Set.nonempty_of_mem hu
rw [Set.nonempty_Icc] at hu
have hu' : (c₁ - c₂) * f x ≤ 0 := by linarith
exact nonpos_of_mul_nonpos_right hu' (by linarith)
| .inr (.inl heq) => -- c₁ = c₂
have hmain : ∃ c, ∀ᶠ x in atTop, f x = c := by
simp only [heq, Set.Icc_self, Set.mem_singleton_iff] at h
rw [eventually_atTop] at h
obtain ⟨n₀, hn₀⟩ := h
refine ⟨f (max n₀ 2), ?_⟩
rw [eventually_atTop]
refine ⟨max n₀ 2, ?_⟩
refine Real.induction_Ico_mul _ 2 (by norm_num) (by positivity) ?base ?step
case base =>
intro x ⟨hxlb, hxub⟩
have h₁ := calc n₀ ≤ 1 * max n₀ 2 := by simp
_ ≤ 2 * max n₀ 2 := by gcongr; norm_num
have h₂ := hn₀ (2 * max n₀ 2) h₁ (max n₀ 2) ⟨by simp, by linarith⟩
rw [h₂]
exact hn₀ (2 * max n₀ 2) h₁ x ⟨by simp [hxlb], le_of_lt hxub⟩
case step =>
intro n hn hyp_ind z hz
have z_nonneg : 0 ≤ z := by
calc (0 : ℝ) ≤ (2 : ℝ) ^ n * max n₀ 2 := by
exact mul_nonneg (pow_nonneg (by norm_num) _) (by norm_num)
_ ≤ z := by exact_mod_cast hz.1
have le_2n : max n₀ 2 ≤ (2 : ℝ) ^ n * max n₀ 2 := by
nth_rewrite 1 [← one_mul (max n₀ 2)]
gcongr
exact one_le_pow₀ (by norm_num : (1 : ℝ) ≤ 2)
have n₀_le_z : n₀ ≤ z := by
calc n₀ ≤ max n₀ 2 := by simp
_ ≤ (2 : ℝ) ^ n * max n₀ 2 := le_2n
_ ≤ _ := by exact_mod_cast hz.1
have fz_eq_c₂fz : f z = c₂ * f z := hn₀ z n₀_le_z z ⟨by linarith, le_rfl⟩
have z_to_half_z' : f (1 / 2 * z) = c₂ * f z :=
hn₀ z n₀_le_z (1 / 2 * z) ⟨le_rfl, by linarith⟩
have z_to_half_z : f (1 / 2 * z) = f z := by rwa [← fz_eq_c₂fz] at z_to_half_z'
have half_z_to_base : f (1 / 2 * z) = f (max n₀ 2) := by
refine hyp_ind (1 / 2 * z) ⟨?lb, ?ub⟩
case lb =>
calc max n₀ 2 ≤ ((1 : ℝ) / (2 : ℝ)) * (2 : ℝ) ^ 1 * max n₀ 2 := by simp
_ ≤ ((1 : ℝ) / (2 : ℝ)) * (2 : ℝ) ^ n * max n₀ 2 := by gcongr; norm_num
_ ≤ _ := by rw [mul_assoc]; gcongr; exact_mod_cast hz.1
case ub =>
have h₁ : (2 : ℝ)^n = ((1 : ℝ)/(2 : ℝ)) * (2 : ℝ)^(n + 1) := by
rw [one_div, pow_add, pow_one]
ring
rw [h₁, mul_assoc]
gcongr
exact_mod_cast hz.2
rw [← z_to_half_z, half_z_to_base]
obtain ⟨c, hc⟩ := hmain
cases le_or_gt 0 c with
| inl hpos =>
exact Or.inl <| by filter_upwards [hc] with _ hc; simpa only [hc]
| inr hneg =>
right
filter_upwards [hc] with x hc
exact le_of_lt <| by simpa only [hc]
lemma eventually_atTop_zero_or_pos_or_neg (hf : GrowsPolynomially f) :
(∀ᶠ x in atTop, f x = 0) ∨ (∀ᶠ x in atTop, 0 < f x) ∨ (∀ᶠ x in atTop, f x < 0) := by
if h : ∃ᶠ x in atTop, f x = 0 then
exact Or.inl <| eventually_zero_of_frequently_zero hf h
else
rw [not_frequently] at h
push_neg at h
cases eventually_atTop_nonneg_or_nonpos hf with
| inl h' =>
refine Or.inr (Or.inl ?_)
simp only [lt_iff_le_and_ne]
rw [eventually_and]
exact ⟨h', by filter_upwards [h] with x hx; exact hx.symm⟩
| inr h' =>
refine Or.inr (Or.inr ?_)
simp only [lt_iff_le_and_ne]
rw [eventually_and]
exact ⟨h', h⟩
protected lemma neg {f : ℝ → ℝ} (hf : GrowsPolynomially f) : GrowsPolynomially (-f) := by
intro b hb
obtain ⟨c₁, hc₁_mem, c₂, hc₂_mem, hf⟩ := hf b hb
refine ⟨c₂, hc₂_mem, c₁, hc₁_mem, ?_⟩
filter_upwards [hf] with x hx
intro u hu
simp only [Pi.neg_apply, Set.neg_mem_Icc_iff, neg_mul_eq_mul_neg, neg_neg]
exact hx u hu
protected lemma neg_iff {f : ℝ → ℝ} : GrowsPolynomially f ↔ GrowsPolynomially (-f) :=
⟨fun hf => hf.neg, fun hf => by rw [← neg_neg f]; exact hf.neg⟩
protected lemma abs (hf : GrowsPolynomially f) : GrowsPolynomially (fun x => |f x|) := by
cases eventually_atTop_nonneg_or_nonpos hf with
| inl hf' =>
have hmain : f =ᶠ[atTop] fun x => |f x| := by
filter_upwards [hf'] with x hx
rw [abs_of_nonneg hx]
rw [← iff_eventuallyEq hmain]
exact hf
| inr hf' =>
have hmain : -f =ᶠ[atTop] fun x => |f x| := by
filter_upwards [hf'] with x hx
simp only [Pi.neg_apply, abs_of_nonpos hx]
rw [← iff_eventuallyEq hmain]
exact hf.neg
protected lemma norm (hf : GrowsPolynomially f) : GrowsPolynomially (fun x => ‖f x‖) := by
simp only [norm_eq_abs]
exact hf.abs
end GrowsPolynomially
variable {f : ℝ → ℝ}
lemma growsPolynomially_const {c : ℝ} : GrowsPolynomially (fun _ => c) := by
refine fun _ _ => ⟨1, by norm_num, 1, by norm_num, ?_⟩
filter_upwards [] with x
simp
lemma growsPolynomially_id : GrowsPolynomially (fun x => x) := by
intro b hb
refine ⟨b, hb.1, ?_⟩
refine ⟨1, by norm_num, ?_⟩
filter_upwards with x u hu
simp only [one_mul, Set.mem_Icc]
exact ⟨hu.1, hu.2⟩
protected lemma GrowsPolynomially.mul {f g : ℝ → ℝ} (hf : GrowsPolynomially f)
(hg : GrowsPolynomially g) : GrowsPolynomially fun x => f x * g x := by
suffices GrowsPolynomially fun x => |f x| * |g x| by
cases eventually_atTop_nonneg_or_nonpos hf with
| inl hf' =>
cases eventually_atTop_nonneg_or_nonpos hg with
| inl hg' =>
have hmain : (fun x => f x * g x) =ᶠ[atTop] fun x => |f x| * |g x| := by
filter_upwards [hf', hg'] with x hx₁ hx₂
rw [abs_of_nonneg hx₁, abs_of_nonneg hx₂]
rwa [iff_eventuallyEq hmain]
| inr hg' =>
have hmain : (fun x => f x * g x) =ᶠ[atTop] fun x => -|f x| * |g x| := by
filter_upwards [hf', hg'] with x hx₁ hx₂
simp [abs_of_nonneg hx₁, abs_of_nonpos hx₂]
simp only [iff_eventuallyEq hmain, neg_mul]
exact this.neg
| inr hf' =>
cases eventually_atTop_nonneg_or_nonpos hg with
| inl hg' =>
have hmain : (fun x => f x * g x) =ᶠ[atTop] fun x => -|f x| * |g x| := by
filter_upwards [hf', hg'] with x hx₁ hx₂
rw [abs_of_nonpos hx₁, abs_of_nonneg hx₂, neg_neg]
simp only [iff_eventuallyEq hmain, neg_mul]
exact this.neg
| inr hg' =>
have hmain : (fun x => f x * g x) =ᶠ[atTop] fun x => |f x| * |g x| := by
filter_upwards [hf', hg'] with x hx₁ hx₂
simp [abs_of_nonpos hx₁, abs_of_nonpos hx₂]
simp only [iff_eventuallyEq hmain]
exact this
intro b hb
have hf := hf.abs b hb
have hg := hg.abs b hb
obtain ⟨c₁, hc₁_mem, c₂, hc₂_mem, hf⟩ := hf
obtain ⟨c₃, hc₃_mem, c₄, hc₄_mem, hg⟩ := hg
refine ⟨c₁ * c₃, by change 0 < c₁ * c₃; positivity, ?_⟩
refine ⟨c₂ * c₄, by change 0 < c₂ * c₄; positivity, ?_⟩
filter_upwards [hf, hg] with x hf hg
intro u hu
refine ⟨?lb, ?ub⟩
case lb => calc
c₁ * c₃ * (|f x| * |g x|) = (c₁ * |f x|) * (c₃ * |g x|) := by ring
_ ≤ |f u| * |g u| := by
gcongr
· exact (hf u hu).1
· exact (hg u hu).1
case ub => calc
|f u| * |g u| ≤ (c₂ * |f x|) * (c₄ * |g x|) := by
gcongr
· exact (hf u hu).2
· exact (hg u hu).2
_ = c₂ * c₄ * (|f x| * |g x|) := by ring
lemma GrowsPolynomially.const_mul {f : ℝ → ℝ} {c : ℝ} (hf : GrowsPolynomially f) :
GrowsPolynomially fun x => c * f x :=
GrowsPolynomially.mul growsPolynomially_const hf
protected lemma GrowsPolynomially.add {f g : ℝ → ℝ} (hf : GrowsPolynomially f)
(hg : GrowsPolynomially g) (hf' : 0 ≤ᶠ[atTop] f) (hg' : 0 ≤ᶠ[atTop] g) :
GrowsPolynomially fun x => f x + g x := by
intro b hb
have hf := hf b hb
have hg := hg b hb
obtain ⟨c₁, hc₁_mem, c₂, hc₂_mem, hf⟩ := hf
obtain ⟨c₃, hc₃_mem, c₄, _, hg⟩ := hg
refine ⟨min c₁ c₃, by change 0 < min c₁ c₃; positivity, ?_⟩
refine ⟨max c₂ c₄, by change 0 < max c₂ c₄; positivity, ?_⟩
filter_upwards [hf, hg,
(tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hf',
(tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hg',
eventually_ge_atTop 0] with x hf hg hf' hg' hx_pos
intro u hu
have hbx : b * x ≤ x := calc
b * x ≤ 1 * x := by gcongr; exact le_of_lt hb.2
_ = x := by ring
have fx_nonneg : 0 ≤ f x := hf' x hbx
have gx_nonneg : 0 ≤ g x := hg' x hbx
refine ⟨?lb, ?ub⟩
case lb => calc
min c₁ c₃ * (f x + g x) = min c₁ c₃ * f x + min c₁ c₃ * g x := by simp only [mul_add]
_ ≤ c₁ * f x + c₃ * g x := by
gcongr
· exact min_le_left _ _
· exact min_le_right _ _
_ ≤ f u + g u := by
gcongr
· exact (hf u hu).1
· exact (hg u hu).1
case ub => calc
max c₂ c₄ * (f x + g x) = max c₂ c₄ * f x + max c₂ c₄ * g x := by simp only [mul_add]
_ ≥ c₂ * f x + c₄ * g x := by gcongr
· exact le_max_left _ _
· exact le_max_right _ _
_ ≥ f u + g u := by gcongr
· exact (hf u hu).2
· exact (hg u hu).2
lemma GrowsPolynomially.add_isLittleO {f g : ℝ → ℝ} (hf : GrowsPolynomially f)
(hfg : g =o[atTop] f) : GrowsPolynomially fun x => f x + g x := by
intro b hb
have hb_ub := hb.2
rw [isLittleO_iff] at hfg
cases hf.eventually_atTop_nonneg_or_nonpos with
| inl hf' => -- f is eventually non-negative
have hf := hf b hb
obtain ⟨c₁, hc₁_mem : 0 < c₁, c₂, hc₂_mem : 0 < c₂, hf⟩ := hf
specialize hfg (c := 1 / 2) (by norm_num)
refine ⟨c₁ / 3, by positivity, 3*c₂, by positivity, ?_⟩
filter_upwards [hf,
(tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hfg,
(tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hf',
eventually_ge_atTop 0] with x hf₁ hfg' hf₂ hx_nonneg
have hbx : b * x ≤ x := by nth_rewrite 2 [← one_mul x]; gcongr
have hfg₂ : ‖g x‖ ≤ 1 / 2 * f x := by
calc ‖g x‖ ≤ 1 / 2 * ‖f x‖ := hfg' x hbx
_ = 1 / 2 * f x := by congr; exact norm_of_nonneg (hf₂ _ hbx)
have hx_ub : f x + g x ≤ 3/2 * f x := by
calc _ ≤ f x + ‖g x‖ := by gcongr; exact le_norm_self (g x)
_ ≤ f x + 1 / 2 * f x := by gcongr
_ = 3/2 * f x := by ring
have hx_lb : 1 / 2 * f x ≤ f x + g x := by
calc f x + g x ≥ f x - ‖g x‖ := by
rw [sub_eq_add_neg, norm_eq_abs]; gcongr; exact neg_abs_le (g x)
_ ≥ f x - 1 / 2 * f x := by gcongr
_ = 1 / 2 * f x := by ring
intro u ⟨hu_lb, hu_ub⟩
have hfu_nonneg : 0 ≤ f u := hf₂ _ hu_lb
have hfg₃ : ‖g u‖ ≤ 1 / 2 * f u := by
calc ‖g u‖ ≤ 1 / 2 * ‖f u‖ := hfg' _ hu_lb
_ = 1 / 2 * f u := by congr; simp only [norm_eq_abs, abs_eq_self, hfu_nonneg]
refine ⟨?lb, ?ub⟩
case lb =>
calc f u + g u ≥ f u - ‖g u‖ := by
rw [sub_eq_add_neg, norm_eq_abs]; gcongr; exact neg_abs_le _
_ ≥ f u - 1 / 2 * f u := by gcongr
_ = 1 / 2 * f u := by ring
_ ≥ 1 / 2 * (c₁ * f x) := by gcongr; exact (hf₁ u ⟨hu_lb, hu_ub⟩).1
_ = c₁/3 * (3/2 * f x) := by ring
_ ≥ c₁/3 * (f x + g x) := by gcongr
case ub =>
calc _ ≤ f u + ‖g u‖ := by gcongr; exact le_norm_self (g u)
_ ≤ f u + 1 / 2 * f u := by gcongr
_ = 3/2 * f u := by ring
_ ≤ 3/2 * (c₂ * f x) := by gcongr; exact (hf₁ u ⟨hu_lb, hu_ub⟩).2
_ = 3*c₂ * (1 / 2 * f x) := by ring
_ ≤ 3*c₂ * (f x + g x) := by gcongr
| inr hf' => -- f is eventually nonpos
have hf := hf b hb
obtain ⟨c₁, hc₁_mem : 0 < c₁, c₂, hc₂_mem : 0 < c₂, hf⟩ := hf
specialize hfg (c := 1 / 2) (by norm_num)
refine ⟨3*c₁, by positivity, c₂/3, by positivity, ?_⟩
filter_upwards [hf,
(tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hfg,
(tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hf',
eventually_ge_atTop 0] with x hf₁ hfg' hf₂ hx_nonneg
have hbx : b * x ≤ x := by nth_rewrite 2 [← one_mul x]; gcongr
have hfg₂ : ‖g x‖ ≤ -1 / 2 * f x := by
calc ‖g x‖ ≤ 1 / 2 * ‖f x‖ := hfg' x hbx
_ = 1 / 2 * (-f x) := by congr; exact norm_of_nonpos (hf₂ x hbx)
_ = _ := by ring
have hx_ub : f x + g x ≤ 1 / 2 * f x := by
calc _ ≤ f x + ‖g x‖ := by gcongr; exact le_norm_self (g x)
_ ≤ f x + (-1 / 2 * f x) := by gcongr
_ = 1 / 2 * f x := by ring
have hx_lb : 3/2 * f x ≤ f x + g x := by
calc f x + g x ≥ f x - ‖g x‖ := by
rw [sub_eq_add_neg, norm_eq_abs]; gcongr; exact neg_abs_le (g x)
_ ≥ f x + 1 / 2 * f x := by
rw [sub_eq_add_neg]
gcongr
refine le_of_neg_le_neg ?bc.a
rwa [neg_neg, ← neg_mul, ← neg_div]
_ = 3/2 * f x := by ring
intro u ⟨hu_lb, hu_ub⟩
have hfu_nonpos : f u ≤ 0 := hf₂ _ hu_lb
have hfg₃ : ‖g u‖ ≤ -1 / 2 * f u := by
calc ‖g u‖ ≤ 1 / 2 * ‖f u‖ := hfg' _ hu_lb
_ = 1 / 2 * (-f u) := by congr; exact norm_of_nonpos hfu_nonpos
_ = -1 / 2 * f u := by ring
refine ⟨?lb, ?ub⟩
case lb =>
calc f u + g u ≥ f u - ‖g u‖ := by
rw [sub_eq_add_neg, norm_eq_abs]; gcongr; exact neg_abs_le _
_ ≥ f u + 1 / 2 * f u := by
rw [sub_eq_add_neg]
gcongr
refine le_of_neg_le_neg ?_
rwa [neg_neg, ← neg_mul, ← neg_div]
_ = 3/2 * f u := by ring
_ ≥ 3/2 * (c₁ * f x) := by gcongr; exact (hf₁ u ⟨hu_lb, hu_ub⟩).1
_ = 3*c₁ * (1 / 2 * f x) := by ring
_ ≥ 3*c₁ * (f x + g x) := by gcongr
case ub =>
calc _ ≤ f u + ‖g u‖ := by gcongr; exact le_norm_self (g u)
_ ≤ f u - 1 / 2 * f u := by
rw [sub_eq_add_neg]
gcongr
rwa [← neg_mul, ← neg_div]
_ = 1 / 2 * f u := by ring
_ ≤ 1 / 2 * (c₂ * f x) := by gcongr; exact (hf₁ u ⟨hu_lb, hu_ub⟩).2
_ = c₂/3 * (3/2 * f x) := by ring
_ ≤ c₂/3 * (f x + g x) := by gcongr
protected lemma GrowsPolynomially.inv {f : ℝ → ℝ} (hf : GrowsPolynomially f) :
GrowsPolynomially fun x => (f x)⁻¹ := by
cases hf.eventually_atTop_zero_or_pos_or_neg with
| inl hf' =>
refine fun b hb => ⟨1, by simp, 1, by simp, ?_⟩
have hb_pos := hb.1
filter_upwards [hf', (tendsto_id.const_mul_atTop hb_pos).eventually_forall_ge_atTop hf']
with x hx hx'
intro u hu
simp only [hx, inv_zero, mul_zero, Set.Icc_self, Set.mem_singleton_iff, hx' u hu.1]
| inr hf_pos_or_neg =>
suffices GrowsPolynomially fun x => |(f x)⁻¹| by
cases hf_pos_or_neg with
| inl hf' =>
have hmain : (fun x => (f x)⁻¹) =ᶠ[atTop] fun x => |(f x)⁻¹| := by
filter_upwards [hf'] with x hx₁
rw [abs_of_nonneg (inv_nonneg_of_nonneg (le_of_lt hx₁))]
rwa [iff_eventuallyEq hmain]
| inr hf' =>
have hmain : (fun x => (f x)⁻¹) =ᶠ[atTop] fun x => -|(f x)⁻¹| := by
filter_upwards [hf'] with x hx₁
simp [abs_of_nonpos (inv_nonpos.mpr (le_of_lt hx₁))]
rw [iff_eventuallyEq hmain]
exact this.neg
have hf' : ∀ᶠ x in atTop, f x ≠ 0 := by
cases hf_pos_or_neg with
| inl H => filter_upwards [H] with _ hx; exact (ne_of_lt hx).symm
| inr H => filter_upwards [H] with _ hx; exact (ne_of_gt hx).symm
simp only [abs_inv]
have hf := hf.abs
intro b hb
have hb_pos := hb.1
obtain ⟨c₁, hc₁_mem, c₂, hc₂_mem, hf⟩ := hf b hb
refine ⟨c₂⁻¹, by change 0 < c₂⁻¹; positivity, ?_⟩
refine ⟨c₁⁻¹, by change 0 < c₁⁻¹; positivity, ?_⟩
filter_upwards [hf, hf', (tendsto_id.const_mul_atTop hb_pos).eventually_forall_ge_atTop hf']
with x hx hx' hx''
intro u hu
have h₁ : 0 < |f u| := by rw [abs_pos]; exact hx'' u hu.1
refine ⟨?lb, ?ub⟩
case lb =>
rw [← mul_inv]
gcongr
exact (hx u hu).2
case ub =>
rw [← mul_inv]
gcongr
exact (hx u hu).1
protected lemma GrowsPolynomially.div {f g : ℝ → ℝ} (hf : GrowsPolynomially f)
(hg : GrowsPolynomially g) : GrowsPolynomially fun x => f x / g x := by
have : (fun x => f x / g x) = fun x => f x * (g x)⁻¹ := by ext; rw [div_eq_mul_inv]
rw [this]
exact GrowsPolynomially.mul hf (GrowsPolynomially.inv hg)
protected lemma GrowsPolynomially.rpow (p : ℝ) (hf : GrowsPolynomially f)
(hf_nonneg : ∀ᶠ x in atTop, 0 ≤ f x) : GrowsPolynomially fun x => (f x) ^ p := by
intro b hb
obtain ⟨c₁, (hc₁_mem : 0 < c₁), c₂, hc₂_mem, hfnew⟩ := hf b hb
have hc₁p : 0 < c₁ ^ p := Real.rpow_pos_of_pos hc₁_mem _
have hc₂p : 0 < c₂ ^ p := Real.rpow_pos_of_pos hc₂_mem _
cases le_or_gt 0 p with
| inl => -- 0 ≤ p
refine ⟨c₁^p, hc₁p, ?_⟩
refine ⟨c₂^p, hc₂p, ?_⟩
filter_upwards [eventually_gt_atTop 0, hfnew, hf_nonneg,
(tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hf_nonneg]
with x _ hf₁ hf_nonneg hf_nonneg₂
intro u hu
have fu_nonneg : 0 ≤ f u := hf_nonneg₂ u hu.1
refine ⟨?lb, ?ub⟩
case lb => calc
c₁^p * (f x)^p = (c₁ * f x)^p := by rw [mul_rpow (le_of_lt hc₁_mem) hf_nonneg]
_ ≤ _ := by gcongr; exact (hf₁ u hu).1
case ub => calc
(f u)^p ≤ (c₂ * f x)^p := by gcongr; exact (hf₁ u hu).2
_ = _ := by rw [← mul_rpow (le_of_lt hc₂_mem) hf_nonneg]
| inr hp => -- p < 0
match hf.eventually_atTop_zero_or_pos_or_neg with
| .inl hzero => -- eventually zero
refine ⟨1, by norm_num, 1, by norm_num, ?_⟩
filter_upwards [hzero, hfnew] with x hx hx'
intro u hu
simp only [hx, zero_rpow (ne_of_lt hp), mul_zero,
Set.Icc_self, Set.mem_singleton_iff]
simp only [hx, mul_zero, Set.Icc_self, Set.mem_singleton_iff] at hx'
rw [hx' u hu, zero_rpow (ne_of_lt hp)]
| .inr (.inl hpos) => -- eventually positive
refine ⟨c₂^p, hc₂p, ?_⟩
refine ⟨c₁^p, hc₁p, ?_⟩
filter_upwards [eventually_gt_atTop 0, hfnew, hpos,
(tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop hpos]
with x _ hf₁ hf_pos hf_pos₂
intro u hu
refine ⟨?lb, ?ub⟩
case lb => calc
c₂^p * (f x)^p = (c₂ * f x)^p := by rw [mul_rpow (le_of_lt hc₂_mem) (le_of_lt hf_pos)]
_ ≤ _ := rpow_le_rpow_of_nonpos (hf_pos₂ u hu.1) (hf₁ u hu).2 (le_of_lt hp)
case ub => calc
(f u)^p ≤ (c₁ * f x)^p := by
exact rpow_le_rpow_of_nonpos (by positivity) (hf₁ u hu).1 (le_of_lt hp)
_ = _ := by rw [← mul_rpow (le_of_lt hc₁_mem) (le_of_lt hf_pos)]
| .inr (.inr hneg) => -- eventually negative (which is impossible)
have : ∀ᶠ (_ : ℝ) in atTop, False := by
filter_upwards [hf_nonneg, hneg] with x hx hx'; linarith
rw [Filter.eventually_false_iff_eq_bot] at this
exact False.elim <| (atTop_neBot).ne this
protected lemma GrowsPolynomially.pow (p : ℕ) (hf : GrowsPolynomially f)
(hf_nonneg : ∀ᶠ x in atTop, 0 ≤ f x) : GrowsPolynomially fun x => (f x) ^ p := by
simp_rw [← rpow_natCast]
exact hf.rpow p hf_nonneg
protected lemma GrowsPolynomially.zpow (p : ℤ) (hf : GrowsPolynomially f)
(hf_nonneg : ∀ᶠ x in atTop, 0 ≤ f x) : GrowsPolynomially fun x => (f x) ^ p := by
simp_rw [← rpow_intCast]
exact hf.rpow p hf_nonneg
lemma growsPolynomially_rpow (p : ℝ) : GrowsPolynomially fun x => x ^ p :=
(growsPolynomially_id).rpow p (eventually_ge_atTop 0)
lemma growsPolynomially_pow (p : ℕ) : GrowsPolynomially fun x => x ^ p :=
(growsPolynomially_id).pow p (eventually_ge_atTop 0)
lemma growsPolynomially_zpow (p : ℤ) : GrowsPolynomially fun x => x ^ p :=
(growsPolynomially_id).zpow p (eventually_ge_atTop 0)
lemma growsPolynomially_log : GrowsPolynomially Real.log := by
intro b hb
have hb₀ : 0 < b := hb.1
refine ⟨1 / 2, by norm_num, ?_⟩
refine ⟨1, by norm_num, ?_⟩
have h_tendsto : Tendsto (fun x => 1 / 2 * Real.log x) atTop atTop :=
Tendsto.const_mul_atTop (by norm_num) Real.tendsto_log_atTop
filter_upwards [eventually_gt_atTop 1,
(tendsto_id.const_mul_atTop hb.1).eventually_forall_ge_atTop
<| h_tendsto.eventually (eventually_gt_atTop (-Real.log b))] with x hx_pos hx
intro u hu
refine ⟨?lb, ?ub⟩
case lb => calc
1 / 2 * Real.log x = Real.log x + (-1 / 2) * Real.log x := by ring
_ ≤ Real.log x + Real.log b := by grind
_ = Real.log (b * x) := by rw [← Real.log_mul (by positivity) (by positivity), mul_comm]
_ ≤ Real.log u := by gcongr; exact hu.1
case ub =>
rw [one_mul]
gcongr
· calc 0 < b * x := by positivity
_ ≤ u := by exact hu.1
· exact hu.2
lemma GrowsPolynomially.of_isTheta {f g : ℝ → ℝ} (hg : GrowsPolynomially g) (hf : f =Θ[atTop] g)
(hf' : ∀ᶠ x in atTop, 0 ≤ f x) : GrowsPolynomially f := by
intro b hb
have hb_pos := hb.1
have hf_lb := isBigO_iff''.mp hf.isBigO_symm
have hf_ub := isBigO_iff'.mp hf.isBigO
obtain ⟨c₁, hc₁_pos : 0 < c₁, hf_lb⟩ := hf_lb
obtain ⟨c₂, hc₂_pos : 0 < c₂, hf_ub⟩ := hf_ub
have hg := hg.norm b hb
obtain ⟨c₃, hc₃_pos : 0 < c₃, hg⟩ := hg
obtain ⟨c₄, hc₄_pos : 0 < c₄, hg⟩ := hg
have h_lb_pos : 0 < c₁ * c₂⁻¹ * c₃ := by positivity
have h_ub_pos : 0 < c₂ * c₄ * c₁⁻¹ := by positivity
refine ⟨c₁ * c₂⁻¹ * c₃, h_lb_pos, ?_⟩
refine ⟨c₂ * c₄ * c₁⁻¹, h_ub_pos, ?_⟩
have c₂_cancel : c₂⁻¹ * c₂ = 1 := inv_mul_cancel₀ (by positivity)
have c₁_cancel : c₁⁻¹ * c₁ = 1 := inv_mul_cancel₀ (by positivity)
filter_upwards [(tendsto_id.const_mul_atTop hb_pos).eventually_forall_ge_atTop hf',
(tendsto_id.const_mul_atTop hb_pos).eventually_forall_ge_atTop hf_lb,
(tendsto_id.const_mul_atTop hb_pos).eventually_forall_ge_atTop hf_ub,
(tendsto_id.const_mul_atTop hb_pos).eventually_forall_ge_atTop hg,
eventually_ge_atTop 0]
with x hf_pos h_lb h_ub hg_bound hx_pos
intro u hu
have hbx : b * x ≤ x :=
calc b * x ≤ 1 * x := by gcongr; exact le_of_lt hb.2
_ = x := by rw [one_mul]
have hg_bound := hg_bound x hbx
refine ⟨?lb, ?ub⟩
case lb => calc
c₁ * c₂⁻¹ * c₃ * f x ≤ c₁ * c₂⁻¹ * c₃ * (c₂ * ‖g x‖) := by
rw [← Real.norm_of_nonneg (hf_pos x hbx)]; gcongr; exact h_ub x hbx
_ = (c₂⁻¹ * c₂) * c₁ * (c₃ * ‖g x‖) := by ring
_ = c₁ * (c₃ * ‖g x‖) := by simp [c₂_cancel]
_ ≤ c₁ * ‖g u‖ := by gcongr; exact (hg_bound u hu).1
_ ≤ f u := by
rw [← Real.norm_of_nonneg (hf_pos u hu.1)]
exact h_lb u hu.1
case ub => calc
f u ≤ c₂ * ‖g u‖ := by rw [← Real.norm_of_nonneg (hf_pos u hu.1)]; exact h_ub u hu.1
_ ≤ c₂ * (c₄ * ‖g x‖) := by gcongr; exact (hg_bound u hu).2
_ = c₂ * c₄ * (c₁⁻¹ * c₁) * ‖g x‖ := by simp [c₁_cancel]; ring
_ = c₂ * c₄ * c₁⁻¹ * (c₁ * ‖g x‖) := by ring
_ ≤ c₂ * c₄ * c₁⁻¹ * f x := by
gcongr
rw [← Real.norm_of_nonneg (hf_pos x hbx)]
exact h_lb x hbx
lemma GrowsPolynomially.of_isEquivalent {f g : ℝ → ℝ} (hg : GrowsPolynomially g)
(hf : f ~[atTop] g) : GrowsPolynomially f := by
have : f = g + (f - g) := by ext; simp
rw [this]
exact add_isLittleO hg hf
lemma GrowsPolynomially.of_isEquivalent_const {f : ℝ → ℝ} {c : ℝ} (hf : f ~[atTop] fun _ => c) :
GrowsPolynomially f :=
of_isEquivalent growsPolynomially_const hf
end AkraBazziRecurrence |
.lake/packages/mathlib/Mathlib/Computability/AkraBazzi/AkraBazzi.lean | import Mathlib.Computability.AkraBazzi.SumTransform
import Mathlib.Analysis.Calculus.Deriv.Inv
import Mathlib.Analysis.SpecialFunctions.Pow.Deriv
/-!
# Divide-and-conquer recurrences and the Akra-Bazzi theorem
A divide-and-conquer recurrence is a function `T : ℕ → ℝ` that satisfies a recurrence relation of
the form `T(n) = ∑_{i=0}^{k-1} a_i T(r_i(n)) + g(n)` for sufficiently large `n`, where `r_i(n)` is
a function such that `‖r_i(n) - b_i n‖ ∈ o(n / (log n)^2)` for every `i`, the coefficients `a_i`
are positive, and the coefficients `b_i` are real numbers in `(0, 1)`. (This assumption can be
relaxed to `O(n / (log n)^(1+ε))`, for some `ε > 0`; we leave this as future work.) These
recurrences arise mainly in the analysis of divide-and-conquer algorithms such as mergesort or
Strassen's algorithm for matrix multiplication. This class of algorithms works by dividing an
instance of the problem of size `n`, into `k` smaller instances, where the `i`-th instance is of
size roughly `b_i n`, and calling itself recursively on those smaller instances. `T(n)` then
represents the running time of the algorithm, and `g(n)` represents the running time required to
divide the instance and process the answers produced by the recursive calls. Since virtually all
such algorithms produce instances that are only approximately of size `b_i n` (they must round up
or down, at the very least), we allow the instance sizes to be given by a function `r_i(n)` that
approximates `b_i n`.
The Akra-Bazzi theorem gives the asymptotic order of such a recurrence: it states that
`T(n) ∈ Θ(n^p (1 + ∑_{u=0}^{n-1} g(n) / u^{p+1}))`,
where `p` is the unique real number such that `∑ a_i b_i^p = 1`.
## Main definitions and results
* `isTheta_asympBound`: The main result stating that
`T(n) ∈ Θ(n^p (1 + ∑_{u=0}^{n-1} g(n) / u^{p+1}))`
## Implementation
Note that the original version of the Akra–Bazzi theorem uses an integral rather than the sum in
the above expression, and first considers the `T : ℝ → ℝ` case before moving on to `ℕ → ℝ`. We
prove the version with a sum here, as it is simpler and more relevant for algorithms.
## TODO
* Relax the assumption described in the introduction from `o(n / (log n)^2)` to
`O(n / (log n)^(1+ε))`, for some `ε > 0`.
* Specialize this theorem to the very common case where the recurrence is of the form
`T(n) = ℓT(r_i(n)) + g(n)`
where `g(n) ∈ Θ(n^t)` for some `t`. (This is often called the "master theorem" in the literature.)
* Add the original version of the theorem with an integral instead of a sum.
## References
* Mohamad Akra and Louay Bazzi, On the solution of linear recurrence equations
* Tom Leighton, Notes on better master theorems for divide-and-conquer recurrences
* Manuel Eberl, Asymptotic reasoning in a proof assistant
-/
open Finset Real Filter Asymptotics
open scoped Topology
namespace AkraBazziRecurrence
variable {α : Type*} [Fintype α] {T : ℕ → ℝ} {g : ℝ → ℝ} {a b : α → ℝ} {r : α → ℕ → ℕ}
variable [Nonempty α] (R : AkraBazziRecurrence T g a b r)
local notation "ε" => smoothingFn
/-!
### Technical lemmas
The next several lemmas are technical results leading up to `rpow_p_mul_one_sub_smoothingFn_le` and
`rpow_p_mul_one_add_smoothingFn_ge`, which are key steps in the main proof.
-/
lemma eventually_deriv_rpow_p_mul_one_sub_smoothingFn (p : ℝ) :
deriv (fun z => z ^ p * (1 - ε z))
=ᶠ[atTop] fun z => p * z ^ (p - 1) * (1 - ε z) + z ^ (p - 1) / (log z ^ 2) :=
calc deriv (fun z => z ^ p * (1 - ε z))
_ =ᶠ[atTop] fun x => deriv (· ^ p) x * (1 - ε x) + x ^ p * deriv (1 - ε ·) x := by
filter_upwards [eventually_gt_atTop 1] with x hx
rw [deriv_fun_mul]
· exact differentiableAt_rpow_const_of_ne _ (by positivity)
· exact differentiableAt_one_sub_smoothingFn hx
_ =ᶠ[atTop] fun x => p * x ^ (p - 1) * (1 - ε x) + x ^ p * (x⁻¹ / (log x ^ 2)) := by
filter_upwards [eventually_gt_atTop 1, eventually_deriv_one_sub_smoothingFn]
with x hx hderiv
rw [hderiv, Real.deriv_rpow_const (Or.inl <| by positivity)]
_ =ᶠ[atTop] fun x => p * x ^ (p - 1) * (1 - ε x) + x ^ (p - 1) / (log x ^ 2) := by
filter_upwards [eventually_gt_atTop 0] with x hx
rw [mul_div, ← Real.rpow_neg_one, ← Real.rpow_add (by positivity), sub_eq_add_neg]
lemma eventually_deriv_rpow_p_mul_one_add_smoothingFn (p : ℝ) :
deriv (fun z => z ^ p * (1 + ε z))
=ᶠ[atTop] fun z => p * z ^ (p - 1) * (1 + ε z) - z ^ (p - 1) / (log z ^ 2) :=
calc deriv (fun x => x ^ p * (1 + ε x))
_ =ᶠ[atTop] fun x => deriv (· ^ p) x * (1 + ε x) + x ^ p * deriv (1 + ε ·) x := by
filter_upwards [eventually_gt_atTop 1] with x hx
rw [deriv_fun_mul]
· exact differentiableAt_rpow_const_of_ne _ (by positivity)
· exact differentiableAt_one_add_smoothingFn hx
_ =ᶠ[atTop] fun x => p * x ^ (p - 1) * (1 + ε x) - x ^ p * (x⁻¹ / (log x ^ 2)) := by
filter_upwards [eventually_gt_atTop 1, eventually_deriv_one_add_smoothingFn]
with x hx hderiv
simp [hderiv, Real.deriv_rpow_const (Or.inl <| by positivity), neg_div, sub_eq_add_neg]
_ =ᶠ[atTop] fun x => p * x ^ (p - 1) * (1 + ε x) - x ^ (p - 1) / (log x ^ 2) := by
filter_upwards [eventually_gt_atTop 0] with x hx
simp [mul_div, ← Real.rpow_neg_one, ← Real.rpow_add (by positivity), sub_eq_add_neg]
lemma isEquivalent_deriv_rpow_p_mul_one_sub_smoothingFn {p : ℝ} (hp : p ≠ 0) :
deriv (fun z => z ^ p * (1 - ε z)) ~[atTop] fun z => p * z ^ (p - 1) :=
calc deriv (fun z => z ^ p * (1 - ε z))
_ =ᶠ[atTop] fun z => p * z ^ (p - 1) * (1 - ε z) + z ^ (p - 1) / (log z ^ 2) :=
eventually_deriv_rpow_p_mul_one_sub_smoothingFn p
_ ~[atTop] fun z => p * z ^ (p - 1) := by
refine IsEquivalent.add_isLittleO ?one ?two
case one => calc
(fun z => p * z ^ (p - 1) * (1 - ε z)) ~[atTop] fun z => p * z ^ (p - 1) * 1 :=
IsEquivalent.mul IsEquivalent.refl isEquivalent_one_sub_smoothingFn_one
_ = fun z => p * z ^ (p - 1) := by ext; ring
case two => calc
(fun z => z ^ (p - 1) / (log z ^ 2)) =o[atTop] fun z => z ^ (p - 1) / 1 := by
simp_rw [div_eq_mul_inv]
refine IsBigO.mul_isLittleO (isBigO_refl _ _)
(IsLittleO.inv_rev ?_ (by simp))
rw [isLittleO_const_left]
refine Or.inr <| Tendsto.comp tendsto_norm_atTop_atTop ?_
exact Tendsto.comp (g := fun z => z ^ 2)
(tendsto_pow_atTop (by norm_num)) tendsto_log_atTop
_ = fun z => z ^ (p - 1) := by ext; simp
_ =Θ[atTop] fun z => p * z ^ (p - 1) := IsTheta.const_mul_right hp <| isTheta_refl _ _
lemma isEquivalent_deriv_rpow_p_mul_one_add_smoothingFn {p : ℝ} (hp : p ≠ 0) :
deriv (fun z => z ^ p * (1 + ε z)) ~[atTop] fun z => p * z ^ (p - 1) :=
calc deriv (fun z => z ^ p * (1 + ε z))
_ =ᶠ[atTop] fun z => p * z ^ (p - 1) * (1 + ε z) - z ^ (p - 1) / (log z ^ 2) :=
eventually_deriv_rpow_p_mul_one_add_smoothingFn p
_ ~[atTop] fun z => p * z ^ (p - 1) := by
refine IsEquivalent.add_isLittleO ?one ?two
case one => calc
(fun z => p * z ^ (p - 1) * (1 + ε z)) ~[atTop] fun z => p * z ^ (p - 1) * 1 :=
IsEquivalent.mul IsEquivalent.refl isEquivalent_one_add_smoothingFn_one
_ = fun z => p * z ^ (p - 1) := by ext; ring
case two => calc
(fun z => -(z ^ (p - 1) / (log z ^ 2))) =o[atTop] fun z => z ^ (p - 1) / 1 := by
simp_rw [isLittleO_neg_left, div_eq_mul_inv]
refine IsBigO.mul_isLittleO (isBigO_refl _ _)
(IsLittleO.inv_rev ?_ (by simp))
rw [isLittleO_const_left]
refine Or.inr <| Tendsto.comp tendsto_norm_atTop_atTop ?_
exact Tendsto.comp (g := fun z => z ^ 2)
(tendsto_pow_atTop (by norm_num)) tendsto_log_atTop
_ = fun z => z ^ (p - 1) := by ext; simp
_ =Θ[atTop] fun z => p * z ^ (p - 1) := IsTheta.const_mul_right hp <| isTheta_refl _ _
lemma isTheta_deriv_rpow_p_mul_one_sub_smoothingFn {p : ℝ} (hp : p ≠ 0) :
(fun x => ‖deriv (fun z => z ^ p * (1 - ε z)) x‖) =Θ[atTop] fun z => z ^ (p - 1) := by
refine IsTheta.norm_left ?_
calc (fun x => deriv (fun z => z ^ p * (1 - ε z)) x) =Θ[atTop] fun z => p * z ^ (p - 1) :=
(isEquivalent_deriv_rpow_p_mul_one_sub_smoothingFn hp).isTheta
_ =Θ[atTop] fun z => z ^ (p - 1) := IsTheta.const_mul_left hp <| isTheta_refl _ _
lemma isTheta_deriv_rpow_p_mul_one_add_smoothingFn {p : ℝ} (hp : p ≠ 0) :
(fun x => ‖deriv (fun z => z ^ p * (1 + ε z)) x‖) =Θ[atTop] fun z => z ^ (p - 1) := by
refine IsTheta.norm_left ?_
calc (fun x => deriv (fun z => z ^ p * (1 + ε z)) x) =Θ[atTop] fun z => p * z ^ (p - 1) :=
(isEquivalent_deriv_rpow_p_mul_one_add_smoothingFn hp).isTheta
_ =Θ[atTop] fun z => z ^ (p - 1) := IsTheta.const_mul_left hp <| isTheta_refl _ _
lemma growsPolynomially_deriv_rpow_p_mul_one_sub_smoothingFn (p : ℝ) :
GrowsPolynomially fun x => ‖deriv (fun z => z ^ p * (1 - ε z)) x‖ := by
cases eq_or_ne p 0 with
| inl hp => -- p = 0
have h₁ : (fun x => ‖deriv (fun z => z ^ p * (1 - ε z)) x‖)
=ᶠ[atTop] fun z => z⁻¹ / (log z ^ 2) := by
filter_upwards [eventually_deriv_one_sub_smoothingFn, eventually_gt_atTop 1] with x hx hx_pos
have : 0 ≤ x⁻¹ / (log x ^ 2) := by positivity
simp only [hp, Real.rpow_zero, one_mul, hx, Real.norm_of_nonneg this]
refine GrowsPolynomially.congr_of_eventuallyEq h₁ ?_
refine GrowsPolynomially.div (GrowsPolynomially.inv growsPolynomially_id)
(GrowsPolynomially.pow 2 growsPolynomially_log ?_)
filter_upwards [eventually_ge_atTop 1] with _ hx using log_nonneg hx
| inr hp => -- p ≠ 0
refine GrowsPolynomially.of_isTheta (growsPolynomially_rpow (p-1))
(isTheta_deriv_rpow_p_mul_one_sub_smoothingFn hp) ?_
filter_upwards [eventually_gt_atTop 0] with _ _
positivity
lemma growsPolynomially_deriv_rpow_p_mul_one_add_smoothingFn (p : ℝ) :
GrowsPolynomially fun x => ‖deriv (fun z => z ^ p * (1 + ε z)) x‖ := by
cases eq_or_ne p 0 with
| inl hp => -- p = 0
have h₁ : (fun x => ‖deriv (fun z => z ^ p * (1 + ε z)) x‖)
=ᶠ[atTop] fun z => z⁻¹ / (log z ^ 2) := by
filter_upwards [eventually_deriv_one_add_smoothingFn, eventually_gt_atTop 1] with x hx hx_pos
have : 0 ≤ x⁻¹ / (log x ^ 2) := by positivity
simp only [neg_div, norm_neg, hp, Real.rpow_zero,
one_mul, hx, Real.norm_of_nonneg this]
refine GrowsPolynomially.congr_of_eventuallyEq h₁ ?_
refine GrowsPolynomially.div (GrowsPolynomially.inv growsPolynomially_id)
(GrowsPolynomially.pow 2 growsPolynomially_log ?_)
filter_upwards [eventually_ge_atTop 1] with x hx using log_nonneg hx
| inr hp => -- p ≠ 0
refine GrowsPolynomially.of_isTheta (growsPolynomially_rpow (p-1))
(isTheta_deriv_rpow_p_mul_one_add_smoothingFn hp) ?_
filter_upwards [eventually_gt_atTop 0] with _ _
positivity
include R
lemma isBigO_apply_r_sub_b (q : ℝ → ℝ) (hq_diff : DifferentiableOn ℝ q (Set.Ioi 1))
(hq_poly : GrowsPolynomially fun x => ‖deriv q x‖) (i : α) :
(fun n => q (r i n) - q (b i * n)) =O[atTop] fun n => (deriv q n) * (r i n - b i * n) := by
let b' := b (min_bi b) / 2
have hb_pos : 0 < b' := by have := R.b_pos (min_bi b); positivity
have hb_lt_one : b' < 1 := calc b (min_bi b) / 2
_ < b (min_bi b) := div_two_lt_of_pos (R.b_pos (min_bi b))
_ < 1 := R.b_lt_one (min_bi b)
have hb : b' ∈ Set.Ioo 0 1 := ⟨hb_pos, hb_lt_one⟩
have hb' (i) : b' ≤ b i := calc b (min_bi b) / 2
_ ≤ b i / 2 := by gcongr; aesop
_ ≤ b i := le_of_lt <| div_two_lt_of_pos (R.b_pos i)
obtain ⟨c₁, _, c₂, _, hq_poly⟩ := hq_poly b' hb
rw [isBigO_iff]
refine ⟨c₂, ?_⟩
have h_tendsto : Tendsto (fun x => b' * x) atTop atTop :=
Tendsto.const_mul_atTop hb_pos tendsto_id
filter_upwards [hq_poly.natCast_atTop, R.eventually_bi_mul_le_r, eventually_ge_atTop R.n₀,
eventually_gt_atTop 0, (h_tendsto.eventually_gt_atTop 1).natCast_atTop] with
n hn h_bi_le_r h_ge_n₀ h_n_pos h_bn
rw [norm_mul, ← mul_assoc]
refine Convex.norm_image_sub_le_of_norm_deriv_le
(s := Set.Icc (b' * n) n) (fun z hz => ?diff) (fun z hz => (hn z hz).2)
(convex_Icc _ _) ?mem_Icc <| ⟨h_bi_le_r i, by exact_mod_cast (le_of_lt (R.r_lt_n i n h_ge_n₀))⟩
case diff =>
refine hq_diff.differentiableAt (Ioi_mem_nhds ?_)
calc 1 < b' * n := h_bn
_ ≤ z := hz.1
case mem_Icc =>
refine ⟨by gcongr; exact hb' i, ?_⟩
calc b i * n ≤ 1 * n := by gcongr; exact le_of_lt <| R.b_lt_one i
_ = n := by simp
lemma rpow_p_mul_one_sub_smoothingFn_le :
∀ᶠ (n : ℕ) in atTop, ∀ i, (r i n) ^ (p a b) * (1 - ε (r i n))
≤ (b i) ^ (p a b) * n ^ (p a b) * (1 - ε n) := by
rw [Filter.eventually_all]
intro i
let q : ℝ → ℝ := fun x => x ^ (p a b) * (1 - ε x)
have h_diff_q : DifferentiableOn ℝ q (Set.Ioi 1) := by
refine DifferentiableOn.mul
(DifferentiableOn.mono (differentiableOn_rpow_const _) fun z hz => ?_)
differentiableOn_one_sub_smoothingFn
rw [Set.mem_compl_singleton_iff]
rw [Set.mem_Ioi] at hz
exact ne_of_gt <| zero_lt_one.trans hz
have h_deriv_q : deriv q =O[atTop] fun x => x ^ ((p a b) - 1) := calc deriv q
_ = deriv fun x => (fun z => z ^ (p a b)) x * (fun z => 1 - ε z) x := by rfl
_ =ᶠ[atTop] fun x => deriv (fun z => z ^ (p a b)) x * (1 - ε x) +
x ^ (p a b) * deriv (fun z => 1 - ε z) x := by
filter_upwards [eventually_ne_atTop 0, eventually_gt_atTop 1] with x hx hx'
rw [deriv_fun_mul] <;> aesop
_ =O[atTop] fun x => x ^ ((p a b) - 1) := by
refine IsBigO.add ?left ?right
case left => calc (fun x => deriv (fun z => z ^ (p a b)) x * (1 - ε x))
_ =O[atTop] fun x => x ^ ((p a b) - 1) * (1 - ε x) :=
IsBigO.mul (isBigO_deriv_rpow_const_atTop (p a b)) (isBigO_refl _ _)
_ =O[atTop] fun x => x ^ ((p a b) - 1) * 1 :=
IsBigO.mul (isBigO_refl _ _) isEquivalent_one_sub_smoothingFn_one.isBigO
_ = fun x => x ^ ((p a b) - 1) := by ext; rw [mul_one]
case right => calc (fun x => x ^ (p a b) * deriv (fun z => 1 - ε z) x)
_ =O[atTop] (fun x => x ^ (p a b) * x⁻¹) :=
IsBigO.mul (isBigO_refl _ _) isLittleO_deriv_one_sub_smoothingFn.isBigO
_ =ᶠ[atTop] fun x => x ^ ((p a b) - 1) := by
filter_upwards [eventually_gt_atTop 0] with x hx
rw [← Real.rpow_neg_one, ← Real.rpow_add hx, ← sub_eq_add_neg]
have h_main_norm : (fun (n : ℕ) => ‖q (r i n) - q (b i * n)‖)
≤ᶠ[atTop] fun (n : ℕ) => ‖(b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n)‖ := by
refine IsLittleO.eventuallyLE ?_
calc (fun (n : ℕ) => q (r i n) - q (b i * n))
_ =O[atTop] fun n => (deriv q n) * (r i n - b i * n) :=
R.isBigO_apply_r_sub_b q h_diff_q
(growsPolynomially_deriv_rpow_p_mul_one_sub_smoothingFn (p a b)) i
_ =o[atTop] fun n => (deriv q n) * (n / log n ^ 2) :=
IsBigO.mul_isLittleO (isBigO_refl _ _) (R.dist_r_b i)
_ =O[atTop] fun n => n ^ ((p a b) - 1) * (n / log n ^ 2) :=
IsBigO.mul (IsBigO.natCast_atTop h_deriv_q) (isBigO_refl _ _)
_ =ᶠ[atTop] fun n => n ^ (p a b) / (log n) ^ 2 := by
filter_upwards [eventually_ne_atTop 0] with n hn
have hn' : (n : ℝ) ≠ 0 := by positivity
simp [← mul_div_assoc, ← Real.rpow_add_one hn']
_ = fun (n : ℕ) => (n : ℝ) ^ (p a b) * (1 / (log n) ^ 2) := by
simp_rw [mul_div, mul_one]
_ =Θ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (1 / (log n) ^ 2) := by
refine IsTheta.symm ?_
simp_rw [mul_assoc]
refine IsTheta.const_mul_left ?_ (isTheta_refl _ _)
have := R.b_pos i; positivity
_ =Θ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) :=
IsTheta.symm <| IsTheta.mul (isTheta_refl _ _) <| R.isTheta_smoothingFn_sub_self i
have h_main : (fun (n : ℕ) => q (r i n) - q (b i * n))
≤ᶠ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) := by
calc (fun (n : ℕ) => q (r i n) - q (b i * n))
_ ≤ᶠ[atTop] fun (n : ℕ) => ‖q (r i n) - q (b i * n)‖ := by
filter_upwards with _ using le_norm_self _
_ ≤ᶠ[atTop] fun (n : ℕ) => ‖(b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n)‖ :=
h_main_norm
_ =ᶠ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) := by
filter_upwards [eventually_gt_atTop ⌈(b i)⁻¹⌉₊, eventually_gt_atTop 1] with n hn hn'
refine norm_of_nonneg ?_
have h₁ := R.b_pos i
have h₂ : 0 ≤ ε (b i * n) - ε n := by
refine sub_nonneg_of_le <|
(strictAntiOn_smoothingFn.le_iff_ge ?n_gt_one ?bn_gt_one).mpr ?le
case n_gt_one => rwa [Set.mem_Ioi, Nat.one_lt_cast]
case bn_gt_one =>
calc 1 = b i * (b i)⁻¹ := by rw [mul_inv_cancel₀ (by positivity)]
_ ≤ b i * ⌈(b i)⁻¹⌉₊ := by gcongr; exact Nat.le_ceil _
_ < b i * n := by gcongr
case le => calc b i * n
_ ≤ 1 * n := by have := R.b_lt_one i; gcongr
_ = n := by rw [one_mul]
positivity
filter_upwards [h_main] with n hn
have h₁ : q (b i * n) + (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n)
= (b i) ^ (p a b) * n ^ (p a b) * (1 - ε n) := by
have := R.b_pos i
simp only [q, mul_rpow (by positivity : (0 : ℝ) ≤ b i) (by positivity : (0 : ℝ) ≤ n)]
ring
change q (r i n) ≤ (b i) ^ (p a b) * n ^ (p a b) * (1 - ε n)
rw [← h₁, ← sub_le_iff_le_add']
exact hn
lemma rpow_p_mul_one_add_smoothingFn_ge :
∀ᶠ (n : ℕ) in atTop, ∀ i, (b i) ^ (p a b) * n ^ (p a b) * (1 + ε n)
≤ (r i n) ^ (p a b) * (1 + ε (r i n)) := by
rw [Filter.eventually_all]
intro i
let q : ℝ → ℝ := fun x => x ^ (p a b) * (1 + ε x)
have h_diff_q : DifferentiableOn ℝ q (Set.Ioi 1) := by
refine DifferentiableOn.mul
(DifferentiableOn.mono (differentiableOn_rpow_const _) fun z hz => ?_)
differentiableOn_one_add_smoothingFn
rw [Set.mem_compl_singleton_iff]
rw [Set.mem_Ioi] at hz
exact ne_of_gt <| zero_lt_one.trans hz
have h_deriv_q : deriv q =O[atTop] fun x => x ^ ((p a b) - 1) :=
calc deriv q
_ = deriv fun x => (fun z => z ^ (p a b)) x * (fun z => 1 + ε z) x := by rfl
_ =ᶠ[atTop] fun x => deriv (fun z => z ^ (p a b)) x * (1 + ε x)
+ x ^ (p a b) * deriv (fun z => 1 + ε z) x := by
filter_upwards [eventually_ne_atTop 0, eventually_gt_atTop 1] with x hx hx'
rw [deriv_fun_mul] <;> aesop
_ =O[atTop] fun x => x ^ ((p a b) - 1) := by
refine IsBigO.add ?left ?right
case left =>
calc (fun x => deriv (fun z => z ^ (p a b)) x * (1 + ε x))
_ =O[atTop] fun x => x ^ ((p a b) - 1) * (1 + ε x) :=
IsBigO.mul (isBigO_deriv_rpow_const_atTop (p a b)) (isBigO_refl _ _)
_ =O[atTop] fun x => x ^ ((p a b) - 1) * 1 :=
IsBigO.mul (isBigO_refl _ _) isEquivalent_one_add_smoothingFn_one.isBigO
_ = fun x => x ^ ((p a b) - 1) := by ext; rw [mul_one]
case right =>
calc (fun x => x ^ (p a b) * deriv (fun z => 1 + ε z) x)
_ =O[atTop] (fun x => x ^ (p a b) * x⁻¹) :=
IsBigO.mul (isBigO_refl _ _) isLittleO_deriv_one_add_smoothingFn.isBigO
_ =ᶠ[atTop] fun x => x ^ ((p a b) - 1) := by
filter_upwards [eventually_gt_atTop 0] with x hx
rw [← Real.rpow_neg_one, ← Real.rpow_add hx, ← sub_eq_add_neg]
have h_main_norm : (fun (n : ℕ) => ‖q (r i n) - q (b i * n)‖)
≤ᶠ[atTop] fun (n : ℕ) => ‖(b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n)‖ := by
refine IsLittleO.eventuallyLE ?_
calc
(fun (n : ℕ) => q (r i n) - q (b i * n))
=O[atTop] fun n => (deriv q n) * (r i n - b i * n) := by
exact R.isBigO_apply_r_sub_b q h_diff_q
(growsPolynomially_deriv_rpow_p_mul_one_add_smoothingFn (p a b)) i
_ =o[atTop] fun n => (deriv q n) * (n / log n ^ 2) :=
IsBigO.mul_isLittleO (isBigO_refl _ _) (R.dist_r_b i)
_ =O[atTop] fun n => n ^ ((p a b) - 1) * (n / log n ^ 2) :=
IsBigO.mul (IsBigO.natCast_atTop h_deriv_q) (isBigO_refl _ _)
_ =ᶠ[atTop] fun n => n ^ (p a b) / (log n) ^ 2 := by
filter_upwards [eventually_ne_atTop 0] with n hn
have hn' : (n : ℝ) ≠ 0 := by positivity
simp [← mul_div_assoc, ← Real.rpow_add_one hn']
_ = fun (n : ℕ) => (n : ℝ) ^ (p a b) * (1 / (log n) ^ 2) := by simp_rw [mul_div, mul_one]
_ =Θ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (1 / (log n) ^ 2) := by
refine IsTheta.symm ?_
simp_rw [mul_assoc]
refine IsTheta.const_mul_left ?_ (isTheta_refl _ _)
have := R.b_pos i; positivity
_ =Θ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) :=
IsTheta.symm <| IsTheta.mul (isTheta_refl _ _) <| R.isTheta_smoothingFn_sub_self i
have h_main : (fun (n : ℕ) => q (b i * n) - q (r i n))
≤ᶠ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) := by
calc (fun (n : ℕ) => q (b i * n) - q (r i n))
_ ≤ᶠ[atTop] fun (n : ℕ) => ‖q (r i n) - q (b i * n)‖ := by
filter_upwards with _; rw [norm_sub_rev]; exact le_norm_self _
_ ≤ᶠ[atTop] fun (n : ℕ) => ‖(b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n)‖ :=
h_main_norm
_ =ᶠ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) := by
filter_upwards [eventually_gt_atTop ⌈(b i)⁻¹⌉₊, eventually_gt_atTop 1] with n hn hn'
refine norm_of_nonneg ?_
have h₁ := R.b_pos i
have h₂ : 0 ≤ ε (b i * n) - ε n := by
refine sub_nonneg_of_le <|
(strictAntiOn_smoothingFn.le_iff_ge ?n_gt_one ?bn_gt_one).mpr ?le
case n_gt_one =>
change 1 < (n : ℝ)
rw [Nat.one_lt_cast]
exact hn'
case bn_gt_one =>
calc 1 = b i * (b i)⁻¹ := by rw [mul_inv_cancel₀ (by positivity)]
_ ≤ b i * ⌈(b i)⁻¹⌉₊ := by gcongr; exact Nat.le_ceil _
_ < b i * n := by gcongr
case le => calc b i * n
_ ≤ 1 * n := by have := R.b_lt_one i; gcongr
_ = n := by rw [one_mul]
positivity
filter_upwards [h_main] with n hn
have h₁ : q (b i * n) - (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n)
= (b i) ^ (p a b) * n ^ (p a b) * (1 + ε n) := by
have := R.b_pos i
simp only [q, mul_rpow (by positivity : (0 : ℝ) ≤ b i) (by positivity : (0 : ℝ) ≤ n)]
ring
change (b i) ^ (p a b) * n ^ (p a b) * (1 + ε n) ≤ q (r i n)
rw [← h₁, sub_le_iff_le_add', ← sub_le_iff_le_add]
exact hn
/-!
### Main proof
This final section proves the Akra-Bazzi theorem.
-/
lemma base_nonempty {n : ℕ} (hn : 0 < n) : (Finset.Ico (⌊b (min_bi b) / 2 * n⌋₊) n).Nonempty := by
let b' := b (min_bi b)
have hb_pos : 0 < b' := R.b_pos _
simp_rw [Finset.nonempty_Ico]
have := calc ⌊b' / 2 * n⌋₊ ≤ b' / 2 * n := by exact Nat.floor_le (by positivity)
_ < 1 / 2 * n := by gcongr; exact R.b_lt_one (min_bi b)
_ ≤ 1 * n := by gcongr; norm_num
_ = n := by simp
exact_mod_cast this
/-- The main proof of the upper-bound part of the Akra-Bazzi theorem. The factor `1 - ε n` does not
change the asymptotic order, but it is needed for the induction step to go through. -/
lemma T_isBigO_smoothingFn_mul_asympBound :
T =O[atTop] (fun n => (1 - ε n) * asympBound g a b n) := by
let b' := b (min_bi b) / 2
have hb_pos : 0 < b' := R.bi_min_div_two_pos
rw [isBigO_atTop_iff_eventually_exists]
obtain ⟨c₁, hc₁, h_sumTransform_aux⟩ := R.eventually_atTop_sumTransform_ge
filter_upwards [
-- n₀_ge_Rn₀
eventually_ge_atTop R.n₀,
-- h_smoothing_pos
eventually_forall_ge_atTop.mpr eventually_one_sub_smoothingFn_pos,
-- h_smoothing_gt_half
eventually_forall_ge_atTop.mpr
<| eventually_one_sub_smoothingFn_gt_const (1 / 2) (by norm_num),
-- h_asympBound_pos
eventually_forall_ge_atTop.mpr R.eventually_asympBound_pos,
-- h_asympBound_r_pos
eventually_forall_ge_atTop.mpr R.eventually_asympBound_r_pos,
(tendsto_nat_floor_mul_atTop b' hb_pos).eventually_forall_ge_atTop
-- h_asympBound_floor
R.eventually_asympBound_pos,
-- n₀_pos
eventually_gt_atTop 0,
-- h_smoothing_r_pos
eventually_forall_ge_atTop.mpr R.eventually_one_sub_smoothingFn_r_pos,
-- bound1
eventually_forall_ge_atTop.mpr R.rpow_p_mul_one_sub_smoothingFn_le,
(tendsto_nat_floor_mul_atTop b' hb_pos).eventually_forall_ge_atTop
-- h_smoothingFn_floor
eventually_one_sub_smoothingFn_pos,
-- h_sumTransform
eventually_forall_ge_atTop.mpr h_sumTransform_aux,
-- h_bi_le_r
eventually_forall_ge_atTop.mpr R.eventually_bi_mul_le_r]
with n₀ n₀_ge_Rn₀ h_smoothing_pos h_smoothing_gt_half
h_asympBound_pos h_asympBound_r_pos h_asympBound_floor n₀_pos h_smoothing_r_pos
bound1 h_smoothingFn_floor h_sumTransform h_bi_le_r
-- Max of the ratio `T(n) / asympBound(n)` over the base case `n ∈ [b * n₀, n₀)`
have h_base_nonempty := R.base_nonempty n₀_pos
let base_max : ℝ :=
(Finset.Ico (⌊b' * n₀⌋₊) n₀).sup' h_base_nonempty
fun n => T n / ((1 - ε n) * asympBound g a b n)
-- The big-O constant we are aiming for: max of the base case ratio and what we need to
-- cancel out the `g(n)` term in the calculation below
set C := max (2 * c₁⁻¹) base_max with hC
refine ⟨C, fun n hn => ?_⟩
-- Base case: statement is true for `b' * n₀ ≤ n < n₀`
have h_base : ∀ n ∈ Finset.Ico (⌊b' * n₀⌋₊) n₀, T n ≤ C * ((1 - ε n) * asympBound g a b n) := by
intro n hn
rw [Finset.mem_Ico] at hn
have htmp1 : 0 < 1 - ε n := h_smoothingFn_floor n hn.1
have htmp2 : 0 < asympBound g a b n := h_asympBound_floor n hn.1
rw [← _root_.div_le_iff₀ (by positivity)]
rw [← Finset.mem_Ico] at hn
calc T n / ((1 - ε ↑n) * asympBound g a b n)
≤ (Finset.Ico (⌊b' * n₀⌋₊) n₀).sup' h_base_nonempty
(fun z => T z / ((1 - ε z) * asympBound g a b z)) :=
Finset.le_sup'_of_le _ (b := n) hn le_rfl
_ ≤ C := le_max_right _ _
have h_asympBound_pos' : 0 < asympBound g a b n := h_asympBound_pos n hn
have h_one_sub_smoothingFn_pos' : 0 < 1 - ε n := h_smoothing_pos n hn
rw [Real.norm_of_nonneg (R.T_nonneg n), Real.norm_of_nonneg (by positivity)]
-- We now prove all other cases by induction
induction n using Nat.strongRecOn with
| ind n h_ind =>
have b_mul_n₀_le_ri i : ⌊b' * ↑n₀⌋₊ ≤ r i n := by
exact_mod_cast calc ⌊b' * (n₀ : ℝ)⌋₊ ≤ b' * n₀ := Nat.floor_le <| by positivity
_ ≤ b' * n := by gcongr
_ ≤ r i n := h_bi_le_r n hn i
have g_pos : 0 ≤ g n := R.g_nonneg n (by positivity)
calc T n
_ = (∑ i, a i * T (r i n)) + g n := R.h_rec n <| n₀_ge_Rn₀.trans hn
_ ≤ (∑ i, a i * (C * ((1 - ε (r i n)) * asympBound g a b (r i n)))) + g n := by
-- Apply the induction hypothesis, or use the base case depending on how large n is
gcongr (∑ i, a i * ?_) + g n with i _
· exact le_of_lt <| R.a_pos _
· by_cases! ri_lt_n₀ : r i n < n₀
· exact h_base _ <| by
simp_all only [gt_iff_lt, Nat.ofNat_pos, div_pos_iff_of_pos_right,
eventually_atTop, sub_pos, one_div, mem_Ico, and_imp,
forall_true_left, mem_univ, and_self, b', C, base_max]
· exact h_ind (r i n) (R.r_lt_n _ _ (n₀_ge_Rn₀.trans hn)) ri_lt_n₀
(h_asympBound_r_pos _ hn _) (h_smoothing_r_pos n hn i)
_ = (∑ i, a i * (C * ((1 - ε (r i n)) * ((r i n) ^ (p a b)
* (1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1))))))) + g n := by
simp_rw [asympBound_def']
_ = (∑ i, C * a i * ((r i n) ^ (p a b) * (1 - ε (r i n))
* ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n := by
congr; ext; ring
_ ≤ (∑ i, C * a i * ((b i) ^ (p a b) * n ^ (p a b) * (1 - ε n)
* ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n := by
gcongr (∑ i, C * a i * (?_
* ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n with i
· positivity [R.a_pos i]
· refine add_nonneg zero_le_one <| Finset.sum_nonneg fun j _ => ?_
rw [div_nonneg_iff]
exact Or.inl ⟨R.g_nonneg j (by positivity), by positivity⟩
· exact bound1 n hn i
_ = (∑ i, C * a i * ((b i) ^ (p a b) * n ^ (p a b) * (1 - ε n)
* ((1 + ((∑ u ∈ range n, g u / u ^ ((p a b) + 1))
- (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1))))))) + g n := by
congr; ext i; congr
refine eq_sub_of_add_eq ?_
rw [add_comm]
exact add_eq_of_eq_sub <| Finset.sum_Ico_eq_sub _
<| le_of_lt <| R.r_lt_n i n <| n₀_ge_Rn₀.trans hn
_ = (∑ i, C * a i * ((b i) ^ (p a b) * (1 - ε n) * ((n ^ (p a b)
* (1 + (∑ u ∈ range n, g u / u ^ ((p a b) + 1)))
- n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1))))))
+ g n := by
congr; ext; ring
_ = (∑ i, C * a i * ((b i) ^ (p a b) * (1 - ε n)
* ((asympBound g a b n - sumTransform (p a b) g (r i n) n)))) + g n := by
simp_rw [asympBound_def', sumTransform_def]
_ ≤ (∑ i, C * a i * ((b i) ^ (p a b) * (1 - ε n)
* ((asympBound g a b n - c₁ * g n)))) + g n := by
gcongr with i
· positivity [R.a_pos i]
· positivity [R.b_pos i]
· exact h_sumTransform n hn i
_ = (∑ i, C * (1 - ε n) * ((asympBound g a b n - c₁ * g n))
* (a i * (b i) ^ (p a b))) + g n := by
congr; ext; ring
_ = C * (1 - ε n) * (asympBound g a b n - c₁ * g n) + g n := by
rw [← Finset.mul_sum, R.sumCoeffsExp_p_eq_one, mul_one]
_ = C * (1 - ε n) * asympBound g a b n + (1 - C * c₁ * (1 - ε n)) * g n := by ring
_ ≤ C * (1 - ε n) * asympBound g a b n + 0 := by
gcongr
refine mul_nonpos_of_nonpos_of_nonneg ?_ g_pos
rw [sub_nonpos]
calc 1
_ ≤ 2 * (c₁⁻¹ * c₁) * (1/2) := by
rw [inv_mul_cancel₀ (by positivity : c₁ ≠ 0)]; norm_num
_ = (2 * c₁⁻¹) * c₁ * (1/2) := by ring
_ ≤ C * c₁ * (1 - ε n) := by
gcongr
· rw [hC]; exact le_max_left _ _
· exact le_of_lt <| h_smoothing_gt_half n hn
_ = C * ((1 - ε n) * asympBound g a b n) := by ring
#adaptation_note
/--
This linter is only enabled on `nightly-testing`, but it causes a deterministic timeout there.
Can this proof be refactored into some smaller pieces?
-/
set_option linter.tacticAnalysis.regressions.linarithToGrind false in
/-- The main proof of the lower-bound part of the Akra-Bazzi theorem. The factor `1 + ε n` does not
change the asymptotic order, but it is needed for the induction step to go through. -/
lemma smoothingFn_mul_asympBound_isBigO_T :
(fun (n : ℕ) => (1 + ε n) * asympBound g a b n) =O[atTop] T := by
let b' := b (min_bi b) / 2
have hb_pos : 0 < b' := R.bi_min_div_two_pos
rw [isBigO_atTop_iff_eventually_exists_pos]
obtain ⟨c₁, hc₁, h_sumTransform_aux⟩ := R.eventually_atTop_sumTransform_le
filter_upwards [
-- n₀_ge_Rn₀
eventually_ge_atTop R.n₀,
-- h_b_floor
(tendsto_nat_floor_mul_atTop b' hb_pos).eventually_gt_atTop 0,
-- h_smoothing_pos
eventually_forall_ge_atTop.mpr eventually_one_add_smoothingFn_pos,
(tendsto_nat_floor_mul_atTop b' hb_pos).eventually_forall_ge_atTop
-- h_smoothing_pos'
eventually_one_add_smoothingFn_pos,
-- h_asympBound_pos
eventually_forall_ge_atTop.mpr R.eventually_asympBound_pos,
-- h_asympBound_r_pos
eventually_forall_ge_atTop.mpr R.eventually_asympBound_r_pos,
(tendsto_nat_floor_mul_atTop b' hb_pos).eventually_forall_ge_atTop
-- h_asympBound_floor
R.eventually_asympBound_pos,
-- n₀_pos
eventually_gt_atTop 0,
-- h_smoothing_r_pos
eventually_forall_ge_atTop.mpr R.eventually_one_add_smoothingFn_r_pos,
-- bound2
eventually_forall_ge_atTop.mpr R.rpow_p_mul_one_add_smoothingFn_ge,
(tendsto_nat_floor_mul_atTop b' hb_pos).eventually_forall_ge_atTop
-- h_smoothingFn_floor
eventually_one_add_smoothingFn_pos,
-- h_sumTransform
eventually_forall_ge_atTop.mpr h_sumTransform_aux,
-- h_bi_le_r
eventually_forall_ge_atTop.mpr R.eventually_bi_mul_le_r,
-- h_exp
eventually_forall_ge_atTop.mpr (eventually_ge_atTop ⌈exp 1⌉₊)]
with n₀ n₀_ge_Rn₀ h_b_floor h_smoothing_pos h_smoothing_pos' h_asympBound_pos h_asympBound_r_pos
h_asympBound_floor n₀_pos h_smoothing_r_pos bound2 h_smoothingFn_floor h_sumTransform
h_bi_le_r h_exp
have h_base_nonempty := R.base_nonempty n₀_pos
-- Min of the ratio T(n) / asympBound(n) over the base case n ∈ [b * n₀, n₀)
set base_min : ℝ :=
(Finset.Ico (⌊b' * n₀⌋₊) n₀).inf' h_base_nonempty
(fun n => T n / ((1 + ε n) * asympBound g a b n)) with base_min_def
-- The big-O constant we are aiming for: min of the base case ratio and what we need to cancel
-- out the g(n) term in the calculation below
let C := min (2 * c₁)⁻¹ base_min
have hC_pos : 0 < C := by
refine lt_min (by positivity) ?_
obtain ⟨m, hm_mem, hm⟩ :=
Finset.exists_mem_eq_inf' h_base_nonempty (fun n => T n / ((1 + ε n) * asympBound g a b n))
calc
0 < T m / ((1 + ε m) * asympBound g a b m) := by
have H₁ : 0 < T m := R.T_pos _
have H₂ : 0 < 1 + ε m := by
rw [Finset.mem_Ico] at hm_mem
exact h_smoothing_pos' m hm_mem.1
have H₃ : 0 < asympBound g a b m := by
refine R.asympBound_pos m ?_
calc 0 < ⌊b' * n₀⌋₊ := by exact h_b_floor
_ ≤ m := by rw [Finset.mem_Ico] at hm_mem; exact hm_mem.1
positivity
_ = base_min := by rw [base_min_def, hm]
refine ⟨C, hC_pos, fun n hn => ?_⟩
-- Base case: statement is true for `b' * n₀ ≤ n < n₀`
have h_base : ∀ n ∈ Finset.Ico (⌊b' * n₀⌋₊) n₀, C * ((1 + ε n) * asympBound g a b n) ≤ T n := by
intro n hn
rw [Finset.mem_Ico] at hn
have htmp1 : 0 < 1 + ε n := h_smoothingFn_floor n hn.1
have htmp2 : 0 < asympBound g a b n := h_asympBound_floor n hn.1
rw [← _root_.le_div_iff₀ (by positivity)]
rw [← Finset.mem_Ico] at hn
calc T n / ((1 + ε ↑n) * asympBound g a b n)
≥ (Finset.Ico (⌊b' * n₀⌋₊) n₀).inf' h_base_nonempty
fun z => T z / ((1 + ε z) * asympBound g a b z) :=
Finset.inf'_le_of_le _ (b := n) hn <| le_refl _
_ ≥ C := min_le_right _ _
have h_asympBound_pos' : 0 < asympBound g a b n := h_asympBound_pos n hn
have h_one_sub_smoothingFn_pos' : 0 < 1 + ε n := h_smoothing_pos n hn
rw [Real.norm_of_nonneg (R.T_nonneg n), Real.norm_of_nonneg (by positivity)]
-- We now prove all other cases by induction
induction n using Nat.strongRecOn with
| ind n h_ind =>
have b_mul_n₀_le_ri i : ⌊b' * ↑n₀⌋₊ ≤ r i n := by
exact_mod_cast calc ⌊b' * ↑n₀⌋₊ ≤ b' * n₀ := Nat.floor_le <| by positivity
_ ≤ b' * n := by gcongr
_ ≤ r i n := h_bi_le_r n hn i
have g_pos : 0 ≤ g n := R.g_nonneg n (by positivity)
calc T n
_ = (∑ i, a i * T (r i n)) + g n := R.h_rec n <| n₀_ge_Rn₀.trans hn
_ ≥ (∑ i, a i * (C * ((1 + ε (r i n)) * asympBound g a b (r i n)))) + g n := by
-- Apply the induction hypothesis, or use the base case depending on how large `n` is
gcongr (∑ i, a i * ?_) + g n with i _
· exact le_of_lt <| R.a_pos _
· cases lt_or_ge (r i n) n₀ with
| inl ri_lt_n₀ => exact h_base _ <| Finset.mem_Ico.mpr ⟨b_mul_n₀_le_ri i, ri_lt_n₀⟩
| inr n₀_le_ri =>
exact h_ind (r i n) (R.r_lt_n _ _ (n₀_ge_Rn₀.trans hn)) n₀_le_ri
(h_asympBound_r_pos _ hn _) (h_smoothing_r_pos n hn i)
_ = (∑ i, a i * (C * ((1 + ε (r i n)) * ((r i n) ^ (p a b)
* (1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1))))))) + g n := by
simp_rw [asympBound_def']
_ = (∑ i, C * a i * ((r i n)^(p a b) * (1 + ε (r i n))
* ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n := by
congr; ext; ring
_ ≥ (∑ i, C * a i * ((b i) ^ (p a b) * n ^ (p a b) * (1 + ε n)
* ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n := by
gcongr (∑ i, C * a i * (?_ *
((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n with i
· positivity [R.a_pos i]
· refine add_nonneg zero_le_one <| Finset.sum_nonneg fun j _ => ?_
rw [div_nonneg_iff]
exact Or.inl ⟨R.g_nonneg j (by positivity), by positivity⟩
· exact bound2 n hn i
_ = (∑ i, C * a i * ((b i) ^ (p a b) * n ^ (p a b) * (1 + ε n)
* ((1 + ((∑ u ∈ range n, g u / u ^ ((p a b) + 1))
- (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1))))))) + g n := by
congr; ext i; congr
refine eq_sub_of_add_eq ?_
rw [add_comm]
exact add_eq_of_eq_sub <| Finset.sum_Ico_eq_sub _
<| le_of_lt <| R.r_lt_n i n <| n₀_ge_Rn₀.trans hn
_ = (∑ i, C * a i * ((b i) ^ (p a b) * (1 + ε n)
* ((n ^ (p a b) * (1 + (∑ u ∈ range n, g u / u ^ ((p a b) + 1)))
- n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1))))))
+ g n := by
congr; ext; ring
_ = (∑ i, C * a i * ((b i) ^ (p a b) * (1 + ε n)
* ((asympBound g a b n - sumTransform (p a b) g (r i n) n)))) + g n := by
simp_rw [asympBound_def', sumTransform_def]
_ ≥ (∑ i, C * a i * ((b i) ^ (p a b) * (1 + ε n)
* ((asympBound g a b n - c₁ * g n)))) + g n := by
gcongr with i
· positivity [R.a_pos i]
· positivity [R.b_pos i]
· exact h_sumTransform n hn i
_ = (∑ i, C * (1 + ε n) * ((asympBound g a b n - c₁ * g n))
* (a i * (b i) ^ (p a b))) + g n := by congr; ext; ring
_ = C * (1 + ε n) * (asympBound g a b n - c₁ * g n) + g n := by
rw [← Finset.mul_sum, R.sumCoeffsExp_p_eq_one, mul_one]
_ = C * (1 + ε n) * asympBound g a b n + (1 - C * c₁ * (1 + ε n)) * g n := by ring
_ ≥ C * (1 + ε n) * asympBound g a b n + 0 := by
gcongr
refine mul_nonneg ?_ g_pos
rw [sub_nonneg]
calc C * c₁ * (1 + ε n)
_ ≤ C * c₁ * 2 := by
gcongr
refine one_add_smoothingFn_le_two ?_
calc exp 1 ≤ ⌈exp 1⌉₊ := by exact Nat.le_ceil _
_ ≤ n := by exact_mod_cast h_exp n hn
_ = C * (2 * c₁) := by ring
_ ≤ (2 * c₁)⁻¹ * (2 * c₁) := by gcongr; exact min_le_left _ _
_ = c₁⁻¹ * c₁ := by ring
_ = 1 := inv_mul_cancel₀ (by positivity)
_ = C * ((1 + ε n) * asympBound g a b n) := by ring
/-- The **Akra-Bazzi theorem**: `T ∈ O(n^p (1 + ∑_u^n g(u) / u^{p+1}))` -/
theorem isBigO_asympBound : T =O[atTop] asympBound g a b := by
calc T
_ =O[atTop] (fun n => (1 - ε n) * asympBound g a b n) := by
exact R.T_isBigO_smoothingFn_mul_asympBound
_ =O[atTop] (fun n => 1 * asympBound g a b n) := by
refine IsBigO.mul (isBigO_const_of_tendsto (y := 1) ?_ one_ne_zero) (isBigO_refl _ _)
rw [← Function.comp_def (fun n => 1 - ε n) Nat.cast]
exact Tendsto.comp isEquivalent_one_sub_smoothingFn_one.tendsto_const
tendsto_natCast_atTop_atTop
_ = asympBound g a b := by simp
/-- The **Akra-Bazzi theorem**: `T ∈ Ω(n^p (1 + ∑_u^n g(u) / u^{p+1}))` -/
theorem isBigO_symm_asympBound : asympBound g a b =O[atTop] T := by
calc asympBound g a b
_ = (fun n => 1 * asympBound g a b n) := by simp
_ ~[atTop] (fun n => (1 + ε n) * asympBound g a b n) := by
refine IsEquivalent.mul (IsEquivalent.symm ?_) IsEquivalent.refl
rw [Function.const_def, isEquivalent_const_iff_tendsto one_ne_zero,
← Function.comp_def (fun n => 1 + ε n) Nat.cast]
exact Tendsto.comp isEquivalent_one_add_smoothingFn_one.tendsto_const
tendsto_natCast_atTop_atTop
_ =O[atTop] T := R.smoothingFn_mul_asympBound_isBigO_T
/-- The **Akra-Bazzi theorem**: `T ∈ Θ(n^p (1 + ∑_u^n g(u) / u^{p+1}))` -/
theorem isTheta_asympBound : T =Θ[atTop] asympBound g a b :=
⟨R.isBigO_asympBound, R.isBigO_symm_asympBound⟩
end AkraBazziRecurrence |
.lake/packages/mathlib/Mathlib/Algebra/ModEq.lean | import Mathlib.Algebra.Field.Basic
import Mathlib.Algebra.Group.Subgroup.ZPowers.Basic
import Mathlib.Algebra.GroupWithZero.Action.Defs
import Mathlib.Data.Int.Cast.Lemmas
import Mathlib.Data.Int.ModEq
import Mathlib.GroupTheory.QuotientGroup.Defs
/-!
# Equality modulo an element
This file defines equality modulo an element in a commutative group.
## Main definitions
* `a ≡ b [PMOD p]`: `a` and `b` are congruent modulo `p`.
## See also
`SModEq` is a generalisation to arbitrary submodules.
## TODO
Delete `Int.ModEq` in favour of `AddCommGroup.ModEq`. Generalise `SModEq` to `AddSubgroup` and
redefine `AddCommGroup.ModEq` using it. Once this is done, we can rename `AddCommGroup.ModEq`
to `AddSubgroup.ModEq` and multiplicativise it. Longer term, we could generalise to submonoids and
also unify with `Nat.ModEq`.
-/
assert_not_exists Module
namespace AddCommGroup
variable {α : Type*}
section AddCommGroup
variable [AddCommGroup α] {p a a₁ a₂ b b₁ b₂ c : α} {n : ℕ} {z : ℤ}
/-- `a ≡ b [PMOD p]` means that `b` is congruent to `a` modulo `p`.
Equivalently (as shown in `Algebra.Order.ToIntervalMod`), `b` does not lie in the open interval
`(a, a + p)` modulo `p`, or `toIcoMod hp a` disagrees with `toIocMod hp a` at `b`, or
`toIcoDiv hp a` disagrees with `toIocDiv hp a` at `b`. -/
def ModEq (p a b : α) : Prop :=
∃ z : ℤ, b - a = z • p
@[inherit_doc]
notation:50 a " ≡ " b " [PMOD " p "]" => ModEq p a b
@[refl, simp]
theorem modEq_refl (a : α) : a ≡ a [PMOD p] :=
⟨0, by simp⟩
theorem modEq_rfl : a ≡ a [PMOD p] :=
modEq_refl _
theorem modEq_comm : a ≡ b [PMOD p] ↔ b ≡ a [PMOD p] :=
(Equiv.neg _).exists_congr_left.trans <| by simp [ModEq, ← neg_eq_iff_eq_neg]
alias ⟨ModEq.symm, _⟩ := modEq_comm
attribute [symm] ModEq.symm
@[trans]
theorem ModEq.trans : a ≡ b [PMOD p] → b ≡ c [PMOD p] → a ≡ c [PMOD p] := fun ⟨m, hm⟩ ⟨n, hn⟩ =>
⟨m + n, by simp [add_zsmul, ← hm, ← hn]⟩
instance : IsTrans α (ModEq p) where
trans _ _ _ := ModEq.trans
instance : IsRefl _ (ModEq p) :=
⟨modEq_refl⟩
@[simp]
theorem neg_modEq_neg : -a ≡ -b [PMOD p] ↔ a ≡ b [PMOD p] :=
modEq_comm.trans <| by simp [ModEq, neg_add_eq_sub]
alias ⟨ModEq.of_neg, ModEq.neg⟩ := neg_modEq_neg
@[simp]
theorem modEq_neg : a ≡ b [PMOD -p] ↔ a ≡ b [PMOD p] :=
modEq_comm.trans <| by simp [ModEq, ← neg_eq_iff_eq_neg]
alias ⟨ModEq.of_neg', ModEq.neg'⟩ := modEq_neg
theorem modEq_sub (a b : α) : a ≡ b [PMOD b - a] :=
⟨1, by simp⟩
@[simp]
theorem modEq_zero : a ≡ b [PMOD 0] ↔ a = b := by simp [ModEq, sub_eq_zero, eq_comm]
@[simp]
theorem self_modEq_zero : p ≡ 0 [PMOD p] :=
⟨-1, by simp⟩
@[simp]
theorem zsmul_modEq_zero (z : ℤ) : z • p ≡ 0 [PMOD p] :=
⟨-z, by simp⟩
theorem add_zsmul_modEq (z : ℤ) : a + z • p ≡ a [PMOD p] :=
⟨-z, by simp⟩
theorem zsmul_add_modEq (z : ℤ) : z • p + a ≡ a [PMOD p] :=
⟨-z, by simp⟩
theorem add_nsmul_modEq (n : ℕ) : a + n • p ≡ a [PMOD p] :=
⟨-n, by simp⟩
theorem nsmul_add_modEq (n : ℕ) : n • p + a ≡ a [PMOD p] :=
⟨-n, by simp⟩
namespace ModEq
protected theorem add_zsmul (z : ℤ) : a ≡ b [PMOD p] → a + z • p ≡ b [PMOD p] :=
(add_zsmul_modEq _).trans
protected theorem zsmul_add (z : ℤ) : a ≡ b [PMOD p] → z • p + a ≡ b [PMOD p] :=
(zsmul_add_modEq _).trans
protected theorem add_nsmul (n : ℕ) : a ≡ b [PMOD p] → a + n • p ≡ b [PMOD p] :=
(add_nsmul_modEq _).trans
protected theorem nsmul_add (n : ℕ) : a ≡ b [PMOD p] → n • p + a ≡ b [PMOD p] :=
(nsmul_add_modEq _).trans
protected theorem of_zsmul : a ≡ b [PMOD z • p] → a ≡ b [PMOD p] := fun ⟨m, hm⟩ =>
⟨m * z, by rwa [mul_zsmul]⟩
protected theorem of_nsmul : a ≡ b [PMOD n • p] → a ≡ b [PMOD p] := fun ⟨m, hm⟩ =>
⟨m * n, by rwa [mul_zsmul, natCast_zsmul]⟩
protected theorem zsmul : a ≡ b [PMOD p] → z • a ≡ z • b [PMOD z • p] :=
Exists.imp fun m hm => by rw [← zsmul_sub, hm, zsmul_comm]
protected theorem nsmul : a ≡ b [PMOD p] → n • a ≡ n • b [PMOD n • p] :=
Exists.imp fun m hm => by rw [← nsmul_sub, hm, ← natCast_zsmul, zsmul_comm, natCast_zsmul]
end ModEq
@[simp]
theorem zsmul_modEq_zsmul [IsAddTorsionFree α] (hn : z ≠ 0) :
z • a ≡ z • b [PMOD z • p] ↔ a ≡ b [PMOD p] :=
exists_congr fun m => by rw [← zsmul_sub, zsmul_comm, zsmul_right_inj hn]
@[simp]
theorem nsmul_modEq_nsmul [IsAddTorsionFree α] (hn : n ≠ 0) :
n • a ≡ n • b [PMOD n • p] ↔ a ≡ b [PMOD p] :=
exists_congr fun m => by
rw [← nsmul_sub, ← natCast_zsmul p, zsmul_comm, natCast_zsmul, nsmul_right_inj hn]
alias ⟨ModEq.zsmul_cancel, _⟩ := zsmul_modEq_zsmul
alias ⟨ModEq.nsmul_cancel, _⟩ := nsmul_modEq_nsmul
namespace ModEq
@[simp]
protected theorem add_iff_left :
a₁ ≡ b₁ [PMOD p] → (a₁ + a₂ ≡ b₁ + b₂ [PMOD p] ↔ a₂ ≡ b₂ [PMOD p]) := fun ⟨m, hm⟩ =>
(Equiv.addLeft m).symm.exists_congr_left.trans <| by simp [add_sub_add_comm, hm, add_zsmul, ModEq]
@[simp]
protected theorem add_iff_right :
a₂ ≡ b₂ [PMOD p] → (a₁ + a₂ ≡ b₁ + b₂ [PMOD p] ↔ a₁ ≡ b₁ [PMOD p]) := fun ⟨m, hm⟩ =>
(Equiv.addRight m).symm.exists_congr_left.trans <| by
simp [add_sub_add_comm, hm, add_zsmul, ModEq]
@[simp]
protected theorem sub_iff_left :
a₁ ≡ b₁ [PMOD p] → (a₁ - a₂ ≡ b₁ - b₂ [PMOD p] ↔ a₂ ≡ b₂ [PMOD p]) := fun ⟨m, hm⟩ =>
(Equiv.subLeft m).symm.exists_congr_left.trans <| by
simp [sub_sub_sub_comm, hm, ← sub_eq_add_neg, sub_zsmul, ModEq]
@[simp]
protected theorem sub_iff_right :
a₂ ≡ b₂ [PMOD p] → (a₁ - a₂ ≡ b₁ - b₂ [PMOD p] ↔ a₁ ≡ b₁ [PMOD p]) := fun ⟨m, hm⟩ =>
(Equiv.subRight m).symm.exists_congr_left.trans <| by
simp [sub_sub_sub_comm, hm, ← sub_eq_add_neg, sub_zsmul, ModEq]
protected alias ⟨add_left_cancel, add⟩ := ModEq.add_iff_left
protected alias ⟨add_right_cancel, _⟩ := ModEq.add_iff_right
protected alias ⟨sub_left_cancel, sub⟩ := ModEq.sub_iff_left
protected alias ⟨sub_right_cancel, _⟩ := ModEq.sub_iff_right
protected theorem add_left (c : α) (h : a ≡ b [PMOD p]) : c + a ≡ c + b [PMOD p] :=
modEq_rfl.add h
protected theorem sub_left (c : α) (h : a ≡ b [PMOD p]) : c - a ≡ c - b [PMOD p] :=
modEq_rfl.sub h
protected theorem add_right (c : α) (h : a ≡ b [PMOD p]) : a + c ≡ b + c [PMOD p] :=
h.add modEq_rfl
protected theorem sub_right (c : α) (h : a ≡ b [PMOD p]) : a - c ≡ b - c [PMOD p] :=
h.sub modEq_rfl
protected theorem add_left_cancel' (c : α) : c + a ≡ c + b [PMOD p] → a ≡ b [PMOD p] :=
modEq_rfl.add_left_cancel
protected theorem add_right_cancel' (c : α) : a + c ≡ b + c [PMOD p] → a ≡ b [PMOD p] :=
modEq_rfl.add_right_cancel
protected theorem sub_left_cancel' (c : α) : c - a ≡ c - b [PMOD p] → a ≡ b [PMOD p] :=
modEq_rfl.sub_left_cancel
protected theorem sub_right_cancel' (c : α) : a - c ≡ b - c [PMOD p] → a ≡ b [PMOD p] :=
modEq_rfl.sub_right_cancel
end ModEq
theorem modEq_sub_iff_add_modEq' : a ≡ b - c [PMOD p] ↔ c + a ≡ b [PMOD p] := by
simp [ModEq, sub_sub]
theorem modEq_sub_iff_add_modEq : a ≡ b - c [PMOD p] ↔ a + c ≡ b [PMOD p] :=
modEq_sub_iff_add_modEq'.trans <| by rw [add_comm]
theorem sub_modEq_iff_modEq_add' : a - b ≡ c [PMOD p] ↔ a ≡ b + c [PMOD p] :=
modEq_comm.trans <| modEq_sub_iff_add_modEq'.trans modEq_comm
theorem sub_modEq_iff_modEq_add : a - b ≡ c [PMOD p] ↔ a ≡ c + b [PMOD p] :=
modEq_comm.trans <| modEq_sub_iff_add_modEq.trans modEq_comm
@[simp]
theorem sub_modEq_zero : a - b ≡ 0 [PMOD p] ↔ a ≡ b [PMOD p] := by simp [sub_modEq_iff_modEq_add]
@[simp]
theorem add_modEq_left : a + b ≡ a [PMOD p] ↔ b ≡ 0 [PMOD p] := by simp [← modEq_sub_iff_add_modEq']
@[simp]
theorem add_modEq_right : a + b ≡ b [PMOD p] ↔ a ≡ 0 [PMOD p] := by simp [← modEq_sub_iff_add_modEq]
-- this matches `Int.modEq_iff_add_fac`
theorem modEq_iff_eq_add_zsmul : a ≡ b [PMOD p] ↔ ∃ z : ℤ, b = a + z • p := by
simp_rw [ModEq, sub_eq_iff_eq_add']
-- this roughly matches `Int.modEq_zero_iff_dvd`
theorem modEq_zero_iff_eq_zsmul : a ≡ 0 [PMOD p] ↔ ∃ z : ℤ, a = z • p := by
rw [modEq_comm, modEq_iff_eq_add_zsmul]
simp_rw [zero_add]
theorem not_modEq_iff_ne_add_zsmul : ¬a ≡ b [PMOD p] ↔ ∀ z : ℤ, b ≠ a + z • p := by
rw [modEq_iff_eq_add_zsmul, not_exists]
theorem modEq_iff_eq_mod_zmultiples : a ≡ b [PMOD p] ↔ (a : α ⧸ AddSubgroup.zmultiples p) = b := by
rw [modEq_comm]
simp_rw [modEq_iff_eq_add_zsmul, QuotientAddGroup.eq_iff_sub_mem, AddSubgroup.mem_zmultiples_iff,
eq_sub_iff_add_eq', eq_comm]
theorem not_modEq_iff_ne_mod_zmultiples :
¬a ≡ b [PMOD p] ↔ (a : α ⧸ AddSubgroup.zmultiples p) ≠ b :=
modEq_iff_eq_mod_zmultiples.not
/-- If `a ≡ b [PMOD p]`, then mod `n • p` there are `n` cases. -/
theorem modEq_nsmul_cases (n : ℕ) (hn : n ≠ 0) :
a ≡ b [PMOD p] ↔ ∃ i < n, a ≡ b + i • p [PMOD (n • p)] := by
simp_rw [← sub_modEq_iff_modEq_add, modEq_comm (b := b)]
simp_rw [AddCommGroup.ModEq, sub_right_comm, sub_eq_iff_eq_add (b := _ • _), ← natCast_zsmul,
← mul_zsmul, ← add_zsmul]
constructor
· rintro ⟨k, hk⟩
refine ⟨(k % n).toNat, ?_⟩
rw [← Int.ofNat_lt, Int.toNat_of_nonneg (Int.emod_nonneg _ (mod_cast hn))]
refine ⟨?_, k / n, ?_⟩
· refine Int.emod_lt_of_pos _ ?_
cutsat
· rw [hk, Int.ediv_mul_add_emod]
· rintro ⟨k, _, j, hj⟩
rw [hj]
exact ⟨_, rfl⟩
alias ⟨ModEq.nsmul_cases, _⟩ := AddCommGroup.modEq_nsmul_cases
end AddCommGroup
@[simp]
theorem modEq_iff_int_modEq {a b z : ℤ} : a ≡ b [PMOD z] ↔ a ≡ b [ZMOD z] := by
simp [ModEq, dvd_iff_exists_eq_mul_left, Int.modEq_iff_dvd]
section AddCommGroupWithOne
variable [AddCommGroupWithOne α] [CharZero α]
@[simp, norm_cast]
theorem intCast_modEq_intCast {a b z : ℤ} : a ≡ b [PMOD (z : α)] ↔ a ≡ b [PMOD z] := by
simp_rw [ModEq, ← Int.cast_mul_eq_zsmul_cast]
norm_cast
@[simp, norm_cast]
lemma intCast_modEq_intCast' {a b : ℤ} {n : ℕ} : a ≡ b [PMOD (n : α)] ↔ a ≡ b [PMOD (n : ℤ)] := by
simpa using intCast_modEq_intCast (α := α) (z := n)
@[simp, norm_cast]
theorem natCast_modEq_natCast {a b n : ℕ} : a ≡ b [PMOD (n : α)] ↔ a ≡ b [MOD n] := by
simp_rw [← Int.natCast_modEq_iff, ← modEq_iff_int_modEq, ← @intCast_modEq_intCast α,
Int.cast_natCast]
alias ⟨ModEq.of_intCast, ModEq.intCast⟩ := intCast_modEq_intCast
alias ⟨_root_.Nat.ModEq.of_natCast, ModEq.natCast⟩ := natCast_modEq_natCast
end AddCommGroupWithOne
section DivisionRing
variable [DivisionRing α] {a b c p : α}
@[simp] lemma div_modEq_div (hc : c ≠ 0) : a / c ≡ b / c [PMOD p] ↔ a ≡ b [PMOD (p * c)] := by
simp [ModEq, ← sub_div, div_eq_iff hc, mul_assoc]
@[simp] lemma mul_modEq_mul_right (hc : c ≠ 0) : a * c ≡ b * c [PMOD p] ↔ a ≡ b [PMOD (p / c)] := by
rw [div_eq_mul_inv, ← div_modEq_div (inv_ne_zero hc), div_inv_eq_mul, div_inv_eq_mul]
end DivisionRing
section Field
variable [Field α] {a b c p : α}
@[simp] lemma mul_modEq_mul_left (hc : c ≠ 0) : c * a ≡ c * b [PMOD p] ↔ a ≡ b [PMOD (p / c)] := by
simp [mul_comm c, hc]
end Field
end AddCommGroup |
.lake/packages/mathlib/Mathlib/Algebra/QuaternionBasis.lean | import Mathlib.Algebra.Algebra.Subalgebra.Lattice
import Mathlib.Algebra.Quaternion
import Mathlib.Tactic.Ring
/-!
# Basis on a quaternion-like algebra
## Main definitions
* `QuaternionAlgebra.Basis A c₁ c₂ c₃`: a basis for a subspace of an `R`-algebra `A` that has the
same algebra structure as `ℍ[R,c₁,c₂,c₃]`.
* `QuaternionAlgebra.Basis.self R`: the canonical basis for `ℍ[R,c₁,c₂,c₃]`.
* `QuaternionAlgebra.Basis.compHom b f`: transform a basis `b` by an AlgHom `f`.
* `QuaternionAlgebra.lift`: Define an `AlgHom` out of `ℍ[R,c₁,c₂,c₃]` by its action on the basis
elements `i`, `j`, and `k`. In essence, this is a universal property. Analogous to `Complex.lift`,
but takes a bundled `QuaternionAlgebra.Basis` instead of just a `Subtype` as the amount of
data / proofs is non-negligible.
-/
open Quaternion
namespace QuaternionAlgebra
/-- A quaternion basis contains the information both sufficient and necessary to construct an
`R`-algebra homomorphism from `ℍ[R,c₁,c₂,c₃]` to `A`; or equivalently, a surjective
`R`-algebra homomorphism from `ℍ[R,c₁,c₂,c₃]` to an `R`-subalgebra of `A`.
Note that for definitional convenience, `k` is provided as a field even though `i_mul_j` fully
determines it. -/
structure Basis {R : Type*} (A : Type*) [CommRing R] [Ring A] [Algebra R A] (c₁ c₂ c₃ : R) where
/-- The first imaginary unit -/
i : A
/-- The second imaginary unit -/
j : A
/-- The third imaginary unit -/
k : A
i_mul_i : i * i = c₁ • (1 : A) + c₂ • i
j_mul_j : j * j = c₃ • (1 : A)
i_mul_j : i * j = k
j_mul_i : j * i = c₂ • j - k
initialize_simps_projections Basis
(as_prefix i, as_prefix j, as_prefix k)
variable {R : Type*} {A B : Type*} [CommRing R] [Ring A] [Ring B] [Algebra R A] [Algebra R B]
variable {c₁ c₂ c₃ : R}
namespace Basis
/-- Since `k` is redundant, it is not necessary to show `q₁.k = q₂.k` when showing `q₁ = q₂`. -/
@[ext]
protected theorem ext ⦃q₁ q₂ : Basis A c₁ c₂ c₃⦄ (hi : q₁.i = q₂.i)
(hj : q₁.j = q₂.j) : q₁ = q₂ := by
cases q₁; cases q₂; grind
variable (R) in
/-- There is a natural quaternionic basis for the `QuaternionAlgebra`. -/
@[simps i j k]
protected def self : Basis ℍ[R,c₁,c₂,c₃] c₁ c₂ c₃ where
i := ⟨0, 1, 0, 0⟩
i_mul_i := by ext <;> simp
j := ⟨0, 0, 1, 0⟩
j_mul_j := by ext <;> simp
k := ⟨0, 0, 0, 1⟩
i_mul_j := by ext <;> simp
j_mul_i := by ext <;> simp
instance : Inhabited (Basis ℍ[R,c₁,c₂,c₃] c₁ c₂ c₃) :=
⟨Basis.self R⟩
variable (q : Basis A c₁ c₂ c₃)
attribute [simp] i_mul_i j_mul_j i_mul_j j_mul_i
@[simp]
theorem i_mul_k : q.i * q.k = c₁ • q.j + c₂ • q.k := by
rw [← i_mul_j, ← mul_assoc, i_mul_i, add_mul, smul_mul_assoc, one_mul, smul_mul_assoc]
@[simp]
theorem k_mul_i : q.k * q.i = -c₁ • q.j := by
rw [← i_mul_j, mul_assoc, j_mul_i, mul_sub, i_mul_k, neg_smul, mul_smul_comm, i_mul_j]
linear_combination (norm := module)
@[simp]
theorem k_mul_j : q.k * q.j = c₃ • q.i := by
rw [← i_mul_j, mul_assoc, j_mul_j, mul_smul_comm, mul_one]
@[simp]
theorem j_mul_k : q.j * q.k = (c₂ * c₃) • 1 - c₃ • q.i := by
rw [← i_mul_j, ← mul_assoc, j_mul_i, sub_mul, smul_mul_assoc, j_mul_j, ← smul_assoc, k_mul_j]
rfl
@[simp]
theorem k_mul_k : q.k * q.k = -((c₁ * c₃) • (1 : A)) := by
rw [← i_mul_j, mul_assoc, ← mul_assoc q.j _ _, j_mul_i, ← i_mul_j, ← mul_assoc, mul_sub, ←
mul_assoc, i_mul_i, add_mul, smul_mul_assoc, one_mul, sub_mul, smul_mul_assoc, mul_smul_comm,
smul_mul_assoc, mul_assoc, j_mul_j, add_mul, smul_mul_assoc, j_mul_j, smul_smul,
smul_mul_assoc, mul_assoc, j_mul_j]
linear_combination (norm := module)
/-- Intermediate result used to define `QuaternionAlgebra.Basis.liftHom`. -/
def lift (x : ℍ[R,c₁,c₂,c₃]) : A :=
algebraMap R _ x.re + x.imI • q.i + x.imJ • q.j + x.imK • q.k
theorem lift_zero : q.lift (0 : ℍ[R,c₁,c₂,c₃]) = 0 := by simp [lift]
theorem lift_one : q.lift (1 : ℍ[R,c₁,c₂,c₃]) = 1 := by simp [lift]
theorem lift_add (x y : ℍ[R,c₁,c₂,c₃]) : q.lift (x + y) = q.lift x + q.lift y := by
simp only [lift, re_add, map_add, imI_add, add_smul, imJ_add, imK_add]
abel
theorem lift_mul (x y : ℍ[R,c₁,c₂,c₃]) : q.lift (x * y) = q.lift x * q.lift y := by
simp only [lift, Algebra.algebraMap_eq_smul_one]
simp_rw [add_mul, mul_add, smul_mul_assoc, mul_smul_comm, one_mul, mul_one, smul_smul]
simp only [i_mul_i, j_mul_j, i_mul_j, j_mul_i, i_mul_k, k_mul_i, k_mul_j, j_mul_k, k_mul_k]
simp only [smul_smul, smul_neg, sub_eq_add_neg, ← add_assoc, neg_smul]
simp only [mul_right_comm _ _ (c₁ * c₃), mul_comm _ (c₁ * c₃)]
simp only [mul_comm _ c₁]
simp only [mul_right_comm _ _ c₃]
simp only [← mul_assoc]
simp only [re_mul, sub_eq_add_neg, add_smul, neg_smul, imI_mul, ← add_assoc, imJ_mul, imK_mul]
linear_combination (norm := module)
theorem lift_smul (r : R) (x : ℍ[R,c₁,c₂,c₃]) : q.lift (r • x) = r • q.lift x := by
simp [lift, mul_smul, ← Algebra.smul_def]
/-- A `QuaternionAlgebra.Basis` implies an `AlgHom` from the quaternions. -/
@[simps!]
def liftHom : ℍ[R,c₁,c₂,c₃] →ₐ[R] A :=
AlgHom.mk'
{ toFun := q.lift
map_zero' := q.lift_zero
map_one' := q.lift_one
map_add' := q.lift_add
map_mul' := q.lift_mul } q.lift_smul
@[simp]
theorem range_liftHom (B : Basis A c₁ c₂ c₃) :
(liftHom B).range = Algebra.adjoin R {B.i, B.j, B.k} := by
apply le_antisymm
· rintro x ⟨y, rfl⟩
refine add_mem (add_mem (add_mem ?_ ?_) ?_) ?_
· exact algebraMap_mem _ _
all_goals
exact Subalgebra.smul_mem _ (Algebra.subset_adjoin <| by simp) _
· rw [Algebra.adjoin_le_iff]
rintro x (rfl | rfl | rfl)
<;> [use (Basis.self R).i; use (Basis.self R).j; use (Basis.self R).k]
all_goals simp [lift]
/-- Transform a `QuaternionAlgebra.Basis` through an `AlgHom`. -/
@[simps i j k]
def compHom (F : A →ₐ[R] B) : Basis B c₁ c₂ c₃ where
i := F q.i
i_mul_i := by rw [← map_mul, q.i_mul_i, map_add, map_smul, map_smul, map_one]
j := F q.j
j_mul_j := by rw [← map_mul, q.j_mul_j, map_smul, map_one]
k := F q.k
i_mul_j := by rw [← map_mul, q.i_mul_j]
j_mul_i := by rw [← map_mul, q.j_mul_i, map_sub, map_smul]
end Basis
/-- A quaternionic basis on `A` is equivalent to a map from the quaternion algebra to `A`. -/
@[simps]
def lift : Basis A c₁ c₂ c₃ ≃ (ℍ[R,c₁,c₂,c₃] →ₐ[R] A) where
toFun := Basis.liftHom
invFun := (Basis.self R).compHom
left_inv q := by ext <;> simp [Basis.lift]
right_inv F := by
ext
dsimp [Basis.lift]
rw [← F.commutes]
simp only [← map_smul, ← map_add, mk_add_mk, smul_mk, smul_zero, algebraMap_eq]
congr <;> simp
/-- Two `R`-algebra morphisms from a quaternion algebra are equal if they agree on `i` and `j`. -/
@[ext]
theorem hom_ext ⦃f g : ℍ[R,c₁,c₂,c₃] →ₐ[R] A⦄
(hi : f (Basis.self R).i = g (Basis.self R).i) (hj : f (Basis.self R).j = g (Basis.self R).j) :
f = g :=
lift.symm.injective <| Basis.ext hi hj
end QuaternionAlgebra
namespace Quaternion
variable {R A : Type*} [CommRing R] [Ring A] [Algebra R A]
open QuaternionAlgebra (Basis)
/-- Two `R`-algebra morphisms from the quaternions are equal if they agree on `i` and `j`. -/
@[ext]
theorem hom_ext ⦃f g : ℍ[R] →ₐ[R] A⦄
(hi : f (Basis.self R).i = g (Basis.self R).i) (hj : f (Basis.self R).j = g (Basis.self R).j) :
f = g :=
QuaternionAlgebra.hom_ext hi hj
end Quaternion |
.lake/packages/mathlib/Mathlib/Algebra/LinearRecurrence.lean | import Mathlib.Algebra.Polynomial.Eval.Defs
import Mathlib.LinearAlgebra.Dimension.Constructions
/-!
# Linear recurrence
Informally, a "linear recurrence" is an assertion of the form
`∀ n : ℕ, u (n + d) = a 0 * u n + a 1 * u (n+1) + ... + a (d-1) * u (n+d-1)`,
where `u` is a sequence, `d` is the *order* of the recurrence and the `a i`
are its *coefficients*.
In this file, we define the structure `LinearRecurrence` so that
`LinearRecurrence.mk d a` represents the above relation, and we call
a sequence `u` which verifies it a *solution* of the linear recurrence.
We prove a few basic lemmas about this concept, such as :
* the space of solutions is a submodule of `(ℕ → α)` (i.e a vector space if `α`
is a field)
* the function that maps a solution `u` to its first `d` terms builds a `LinearEquiv`
between the solution space and `Fin d → α`, aka `α ^ d`. As a consequence, two
solutions are equal if and only if their first `d` terms are equal.
* a geometric sequence `q ^ n` is solution iff `q` is a root of a particular polynomial,
which we call the *characteristic polynomial* of the recurrence
Of course, although we can inductively generate solutions (cf `mkSol`), the
interesting part would be to determine closed-forms for the solutions.
This is currently *not implemented*, as we are waiting for definition and
properties of eigenvalues and eigenvectors.
-/
noncomputable section
open Finset
open Polynomial
/-- A "linear recurrence relation" over a commutative semiring is given by its
order `n` and `n` coefficients. -/
structure LinearRecurrence (R : Type*) [CommSemiring R] where
/-- Order of the linear recurrence -/
order : ℕ
/-- Coefficients of the linear recurrence -/
coeffs : Fin order → R
instance (R : Type*) [CommSemiring R] : Inhabited (LinearRecurrence R) :=
⟨⟨0, default⟩⟩
namespace LinearRecurrence
section CommSemiring
variable {R : Type*} [CommSemiring R] (E : LinearRecurrence R)
/-- We say that a sequence `u` is solution of `LinearRecurrence order coeffs` when we have
`u (n + order) = ∑ i : Fin order, coeffs i * u (n + i)` for any `n`. -/
def IsSolution (u : ℕ → R) :=
∀ n, u (n + E.order) = ∑ i, E.coeffs i * u (n + i)
/-- A solution of a `LinearRecurrence` which satisfies certain initial conditions.
We will prove this is the only such solution. -/
def mkSol (init : Fin E.order → R) : ℕ → R
| n =>
if h : n < E.order then init ⟨n, h⟩
else
∑ k : Fin E.order,
have _ : n - E.order + k < n := by omega
E.coeffs k * mkSol init (n - E.order + k)
/-- `E.mkSol` indeed gives solutions to `E`. -/
theorem is_sol_mkSol (init : Fin E.order → R) : E.IsSolution (E.mkSol init) := by
intro n
rw [mkSol]
simp
/-- `E.mkSol init`'s first `E.order` terms are `init`. -/
theorem mkSol_eq_init (init : Fin E.order → R) : ∀ n : Fin E.order, E.mkSol init n = init n := by
intro n
rw [mkSol]
simp only [n.is_lt, dif_pos, Fin.mk_val]
/-- If `u` is a solution to `E` and `init` designates its first `E.order` values,
then `∀ n, u n = E.mkSol init n`. -/
theorem eq_mk_of_is_sol_of_eq_init {u : ℕ → R} {init : Fin E.order → R} (h : E.IsSolution u)
(heq : ∀ n : Fin E.order, u n = init n) : ∀ n, u n = E.mkSol init n := by
intro n
rw [mkSol]
split_ifs with h'
· exact mod_cast heq ⟨n, h'⟩
· dsimp only
rw [← tsub_add_cancel_of_le (le_of_not_gt h'), h (n - E.order)]
congr with k
rw [eq_mk_of_is_sol_of_eq_init h heq (n - E.order + k)]
simp
/-- If `u` is a solution to `E` and `init` designates its first `E.order` values,
then `u = E.mkSol init`. This proves that `E.mkSol init` is the only solution
of `E` whose first `E.order` values are given by `init`. -/
theorem eq_mk_of_is_sol_of_eq_init' {u : ℕ → R} {init : Fin E.order → R} (h : E.IsSolution u)
(heq : ∀ n : Fin E.order, u n = init n) : u = E.mkSol init :=
funext (E.eq_mk_of_is_sol_of_eq_init h heq)
/-- The space of solutions of `E`, as a `Submodule` over `R` of the module `ℕ → R`. -/
def solSpace : Submodule R (ℕ → R) where
carrier := { u | E.IsSolution u }
zero_mem' n := by simp
add_mem' {u v} hu hv n := by simp [mul_add, sum_add_distrib, hu n, hv n]
smul_mem' a u hu n := by simp [hu n, mul_sum]; congr; ext; ac_rfl
/-- Defining property of the solution space : `u` is a solution
iff it belongs to the solution space. -/
theorem is_sol_iff_mem_solSpace (u : ℕ → R) : E.IsSolution u ↔ u ∈ E.solSpace :=
Iff.rfl
/-- The function that maps a solution `u` of `E` to its first
`E.order` terms as a `LinearEquiv`. -/
def toInit : E.solSpace ≃ₗ[R] Fin E.order → R where
toFun u x := (u : ℕ → R) x
map_add' u v := by
ext
simp
map_smul' a u := by
ext
simp
invFun u := ⟨E.mkSol u, E.is_sol_mkSol u⟩
left_inv u := by ext n; symm; apply E.eq_mk_of_is_sol_of_eq_init u.2; intro k; rfl
right_inv u := funext_iff.mpr fun n ↦ E.mkSol_eq_init u n
/-- Two solutions are equal iff they are equal on `range E.order`. -/
theorem sol_eq_of_eq_init (u v : ℕ → R) (hu : E.IsSolution u) (hv : E.IsSolution v) :
u = v ↔ Set.EqOn u v ↑(range E.order) := by
refine Iff.intro (fun h x _ ↦ h ▸ rfl) ?_
intro h
set u' : ↥E.solSpace := ⟨u, hu⟩
set v' : ↥E.solSpace := ⟨v, hv⟩
change u'.val = v'.val
suffices h' : u' = v' from h' ▸ rfl
rw [← E.toInit.toEquiv.apply_eq_iff_eq, LinearEquiv.coe_toEquiv]
ext x
exact mod_cast h (mem_range.mpr x.2)
/-! `E.tupleSucc` maps `![s₀, s₁, ..., sₙ]` to `![s₁, ..., sₙ, ∑ (E.coeffs i) * sᵢ]`,
where `n := E.order`. This operation is quite useful for determining closed-form
solutions of `E`. -/
/-- `E.tupleSucc` maps `![s₀, s₁, ..., sₙ]` to `![s₁, ..., sₙ, ∑ (E.coeffs i) * sᵢ]`,
where `n := E.order`. -/
def tupleSucc : (Fin E.order → R) →ₗ[R] Fin E.order → R where
toFun X i := if h : (i : ℕ) + 1 < E.order then X ⟨i + 1, h⟩ else ∑ i, E.coeffs i * X i
map_add' x y := by
ext i
split_ifs with h <;> simp [h, mul_add, sum_add_distrib]
map_smul' x y := by
ext i
split_ifs with h <;> simp [h, mul_sum]
exact sum_congr rfl fun x _ ↦ by ac_rfl
end CommSemiring
section StrongRankCondition
-- note: `StrongRankCondition` is the same as `Nontrivial` on `CommRing`s, but that result,
-- `commRing_strongRankCondition`, is in a much later file.
variable {R : Type*} [CommRing R] [StrongRankCondition R] (E : LinearRecurrence R)
/-- The dimension of `E.solSpace` is `E.order`. -/
theorem solSpace_rank : Module.rank R E.solSpace = E.order :=
letI := nontrivial_of_invariantBasisNumber R
@rank_fin_fun R _ _ E.order ▸ E.toInit.rank_eq
end StrongRankCondition
section CommRing
variable {R : Type*} [CommRing R] (E : LinearRecurrence R)
/-- The characteristic polynomial of `E` is
`X ^ E.order - ∑ i : Fin E.order, (E.coeffs i) * X ^ i`. -/
def charPoly : R[X] :=
Polynomial.monomial E.order 1 - ∑ i : Fin E.order, Polynomial.monomial i (E.coeffs i)
/-- The geometric sequence `q^n` is a solution of `E` iff
`q` is a root of `E`'s characteristic polynomial. -/
theorem geom_sol_iff_root_charPoly (q : R) :
(E.IsSolution fun n ↦ q ^ n) ↔ E.charPoly.IsRoot q := by
rw [charPoly, Polynomial.IsRoot.def, Polynomial.eval]
simp only [Polynomial.eval₂_finset_sum, one_mul, RingHom.id_apply, Polynomial.eval₂_monomial,
Polynomial.eval₂_sub]
constructor
· intro h
simpa [sub_eq_zero] using h 0
· intro h n
simp only [pow_add, sub_eq_zero.mp h, mul_sum]
exact sum_congr rfl fun _ _ ↦ by ring
end CommRing
end LinearRecurrence |
.lake/packages/mathlib/Mathlib/Algebra/GradedMulAction.lean | import Mathlib.Algebra.GradedMonoid
/-!
# Additively-graded multiplicative action structures
This module provides a set of heterogeneous typeclasses for defining a multiplicative structure
over the sigma type `GradedMonoid A` such that `(•) : A i → M j → M (i +ᵥ j)`; that is to say, `A`
has an additively-graded multiplicative action on `M`. The typeclasses are:
* `GradedMonoid.GSMul A M`
* `GradedMonoid.GMulAction A M`
With the `SigmaGraded` scope open, these respectively imbue:
* `SMul (GradedMonoid A) (GradedMonoid M)`
* `MulAction (GradedMonoid A) (GradedMonoid M)`
For now, these typeclasses are primarily used in the construction of `DirectSum.GModule.Module` and
the rest of that file.
## Internally graded multiplicative actions
In addition to the above typeclasses, in the most frequent case when `A` is an indexed collection of
`SetLike` subobjects (such as `AddSubmonoid`s, `AddSubgroup`s, or `Submodule`s), this file
provides the `Prop` typeclasses:
* `SetLike.GradedSMul A M` (which provides the obvious `GradedMonoid.GSMul A` instance)
which provides the API lemma
* `SetLike.graded_smul_mem_graded`
Note that there is no need for `SetLike.graded_mul_action` or similar, as all the information it
would contain is already supplied by `GradedSMul` when the objects within `A` and `M` have
a `MulAction` instance.
## Tags
graded action
-/
variable {ιA ιB ιM : Type*}
namespace GradedMonoid
/-! ### Typeclasses -/
section Defs
variable (A : ιA → Type*) (M : ιM → Type*)
/-- A graded version of `SMul`. Scalar multiplication combines grades additively, i.e.
if `a ∈ A i` and `m ∈ M j`, then `a • b` must be in `M (i + j)`. -/
class GSMul [VAdd ιA ιM] where
/-- The homogeneous multiplication map `smul` -/
smul {i j} : A i → M j → M (i +ᵥ j)
/-- A graded version of `Mul.toSMul` -/
instance GMul.toGSMul [Add ιA] [GMul A] : GSMul A A where smul := GMul.mul
instance GSMul.toSMul [VAdd ιA ιM] [GSMul A M] : SMul (GradedMonoid A) (GradedMonoid M) :=
⟨fun x y ↦ ⟨_, GSMul.smul x.snd y.snd⟩⟩
theorem mk_smul_mk [VAdd ιA ιM] [GSMul A M] {i j} (a : A i) (b : M j) :
mk i a • mk j b = mk (i +ᵥ j) (GSMul.smul a b) :=
rfl
/-- A graded version of `MulAction`. -/
class GMulAction [AddMonoid ιA] [VAdd ιA ιM] [GMonoid A] extends GSMul A M where
/-- One is the neutral element for `•` -/
one_smul (b : GradedMonoid M) : (1 : GradedMonoid A) • b = b
/-- Associativity of `•` and `*` -/
mul_smul (a a' : GradedMonoid A) (b : GradedMonoid M) : (a * a') • b = a • a' • b
/-- The graded version of `Monoid.toMulAction`. -/
instance GMonoid.toGMulAction [AddMonoid ιA] [GMonoid A] : GMulAction A A :=
{ GMul.toGSMul _ with
one_smul := GMonoid.one_mul
mul_smul := GMonoid.mul_assoc }
instance GMulAction.toMulAction [AddMonoid ιA] [GMonoid A] [VAdd ιA ιM] [GMulAction A M] :
MulAction (GradedMonoid A) (GradedMonoid M) where
one_smul := GMulAction.one_smul
mul_smul := GMulAction.mul_smul
end Defs
end GradedMonoid
/-! ### Shorthands for creating instance of the above typeclasses for collections of subobjects -/
section Subobjects
variable {R : Type*}
/-- A version of `GradedMonoid.GSMul` for internally graded objects. -/
class SetLike.GradedSMul {S R N M : Type*} [SetLike S R] [SetLike N M] [SMul R M] [VAdd ιA ιB]
(A : ιA → S) (B : ιB → N) : Prop where
/-- Multiplication is homogeneous -/
smul_mem : ∀ ⦃i : ιA⦄ ⦃j : ιB⦄ {ai bj}, ai ∈ A i → bj ∈ B j → ai • bj ∈ B (i +ᵥ j)
instance SetLike.toGSMul {S R N M : Type*} [SetLike S R] [SetLike N M] [SMul R M] [VAdd ιA ιB]
(A : ιA → S) (B : ιB → N) [SetLike.GradedSMul A B] :
GradedMonoid.GSMul (fun i ↦ A i) fun i ↦ B i where
smul a b := ⟨a.1 • b.1, SetLike.GradedSMul.smul_mem a.2 b.2⟩
@[simp]
theorem SetLike.coe_GSMul {S R N M : Type*} [SetLike S R] [SetLike N M] [SMul R M] [VAdd ιA ιB]
(A : ιA → S) (B : ιB → N) [SetLike.GradedSMul A B] {i : ιA} {j : ιB} (x : A i) (y : B j) :
(@GradedMonoid.GSMul.smul ιA ιB (fun i ↦ A i) (fun i ↦ B i) _ _ i j x y : M) = x.1 • y.1 :=
rfl
/-- Internally graded version of `Mul.toSMul`. -/
instance SetLike.GradedMul.toGradedSMul [AddMonoid ιA] [Monoid R] {S : Type*} [SetLike S R]
(A : ιA → S) [SetLike.GradedMonoid A] : SetLike.GradedSMul A A where
smul_mem _ _ _ _ hi hj := SetLike.GradedMonoid.toGradedMul.mul_mem hi hj
end Subobjects
section HomogeneousElements
variable {S R N M : Type*} [SetLike S R] [SetLike N M]
theorem SetLike.IsHomogeneousElem.graded_smul [VAdd ιA ιB] [SMul R M] {A : ιA → S} {B : ιB → N}
[SetLike.GradedSMul A B] {a : R} {b : M} :
SetLike.IsHomogeneousElem A a → SetLike.IsHomogeneousElem B b →
SetLike.IsHomogeneousElem B (a • b)
| ⟨i, hi⟩, ⟨j, hj⟩ => ⟨i +ᵥ j, SetLike.GradedSMul.smul_mem hi hj⟩
end HomogeneousElements |
.lake/packages/mathlib/Mathlib/Algebra/GradedMonoid.lean | import Mathlib.Algebra.BigOperators.Group.List.Lemmas
import Mathlib.Algebra.Group.Action.Hom
import Mathlib.Algebra.Group.Submonoid.Defs
import Mathlib.Data.List.FinRange
import Mathlib.Data.SetLike.Basic
import Mathlib.Data.Sigma.Basic
import Lean.Elab.Tactic
import Mathlib.Algebra.BigOperators.Group.Finset.Basic
/-!
# Additively-graded multiplicative structures
This module provides a set of heterogeneous typeclasses for defining a multiplicative structure
over the sigma type `GradedMonoid A` such that `(*) : A i → A j → A (i + j)`; that is to say, `A`
forms an additively-graded monoid. The typeclasses are:
* `GradedMonoid.GOne A`
* `GradedMonoid.GMul A`
* `GradedMonoid.GMonoid A`
* `GradedMonoid.GCommMonoid A`
These respectively imbue:
* `One (GradedMonoid A)`
* `Mul (GradedMonoid A)`
* `Monoid (GradedMonoid A)`
* `CommMonoid (GradedMonoid A)`
the base type `A 0` with:
* `GradedMonoid.GradeZero.One`
* `GradedMonoid.GradeZero.Mul`
* `GradedMonoid.GradeZero.Monoid`
* `GradedMonoid.GradeZero.CommMonoid`
and the `i`th grade `A i` with `A 0`-actions (`•`) defined as left-multiplication:
* (nothing)
* `GradedMonoid.GradeZero.SMul (A 0)`
* `GradedMonoid.GradeZero.MulAction (A 0)`
* (nothing)
For now, these typeclasses are primarily used in the construction of `DirectSum.Ring` and the rest
of that file.
## Dependent graded products
This also introduces `List.dProd`, which takes the (possibly non-commutative) product of a list
of graded elements of type `A i`. This definition primarily exists to allow `GradedMonoid.mk`
and `DirectSum.of` to be pulled outside a product, such as in `GradedMonoid.mk_list_dProd` and
`DirectSum.of_list_dProd`.
## Internally graded monoids
In addition to the above typeclasses, in the most frequent case when `A` is an indexed collection of
`SetLike` subobjects (such as `AddSubmonoid`s, `AddSubgroup`s, or `Submodule`s), this file
provides the `Prop` typeclasses:
* `SetLike.GradedOne A` (which provides the obvious `GradedMonoid.GOne A` instance)
* `SetLike.GradedMul A` (which provides the obvious `GradedMonoid.GMul A` instance)
* `SetLike.GradedMonoid A` (which provides the obvious `GradedMonoid.GMonoid A` and
`GradedMonoid.GCommMonoid A` instances)
which respectively provide the API lemmas
* `SetLike.one_mem_graded`
* `SetLike.mul_mem_graded`
* `SetLike.pow_mem_graded`, `SetLike.list_prod_map_mem_graded`
Strictly this last class is unnecessary as it has no fields not present in its parents, but it is
included for convenience. Note that there is no need for `SetLike.GradedRing` or similar, as all
the information it would contain is already supplied by `GradedMonoid` when `A` is a collection
of objects satisfying `AddSubmonoidClass` such as `Submodule`s. These constructions are explored
in `Algebra.DirectSum.Internal`.
This file also defines:
* `SetLike.IsHomogeneousElem A` (which says that `a` is homogeneous iff `a ∈ A i` for some `i : ι`)
* `SetLike.homogeneousSubmonoid A`, which is, as the name suggests, the submonoid consisting of
all the homogeneous elements.
## Tags
graded monoid
-/
variable {ι : Type*}
/-- A type alias of sigma types for graded monoids. -/
def GradedMonoid (A : ι → Type*) :=
Sigma A
namespace GradedMonoid
instance {A : ι → Type*} [Inhabited ι] [Inhabited (A default)] : Inhabited (GradedMonoid A) :=
inferInstanceAs <| Inhabited (Sigma _)
/-- Construct an element of a graded monoid. -/
def mk {A : ι → Type*} : ∀ i, A i → GradedMonoid A :=
Sigma.mk
/-! ### Actions -/
section actions
variable {α β} {A : ι → Type*}
/-- If `R` acts on each `A i`, then it acts on `GradedMonoid A` via the `.2` projection. -/
instance [∀ i, SMul α (A i)] : SMul α (GradedMonoid A) where
smul r g := GradedMonoid.mk g.1 (r • g.2)
@[simp] theorem fst_smul [∀ i, SMul α (A i)] (a : α) (x : GradedMonoid A) :
(a • x).fst = x.fst := rfl
@[simp] theorem snd_smul [∀ i, SMul α (A i)] (a : α) (x : GradedMonoid A) :
(a • x).snd = a • x.snd := rfl
theorem smul_mk [∀ i, SMul α (A i)] {i} (c : α) (a : A i) :
c • mk i a = mk i (c • a) :=
rfl
instance [∀ i, SMul α (A i)] [∀ i, SMul β (A i)]
[∀ i, SMulCommClass α β (A i)] :
SMulCommClass α β (GradedMonoid A) where
smul_comm a b g := Sigma.ext rfl <| heq_of_eq <| smul_comm a b g.2
instance [SMul α β] [∀ i, SMul α (A i)] [∀ i, SMul β (A i)]
[∀ i, IsScalarTower α β (A i)] :
IsScalarTower α β (GradedMonoid A) where
smul_assoc a b g := Sigma.ext rfl <| heq_of_eq <| smul_assoc a b g.2
instance [Monoid α] [∀ i, MulAction α (A i)] :
MulAction α (GradedMonoid A) where
one_smul g := Sigma.ext rfl <| heq_of_eq <| one_smul _ g.2
mul_smul r₁ r₂ g := Sigma.ext rfl <| heq_of_eq <| mul_smul r₁ r₂ g.2
end actions
/-! ### Typeclasses -/
section Defs
variable (A : ι → Type*)
/-- A graded version of `One`, which must be of grade 0. -/
class GOne [Zero ι] where
/-- The term `one` of grade 0 -/
one : A 0
/-- `GOne` implies `One (GradedMonoid A)` -/
instance GOne.toOne [Zero ι] [GOne A] : One (GradedMonoid A) :=
⟨⟨_, GOne.one⟩⟩
@[simp] theorem fst_one [Zero ι] [GOne A] : (1 : GradedMonoid A).fst = 0 := rfl
@[simp] theorem snd_one [Zero ι] [GOne A] : (1 : GradedMonoid A).snd = GOne.one := rfl
/-- A graded version of `Mul`. Multiplication combines grades additively, like
`AddMonoidAlgebra`. -/
class GMul [Add ι] where
/-- The homogeneous multiplication map `mul` -/
mul {i j} : A i → A j → A (i + j)
/-- `GMul` implies `Mul (GradedMonoid A)`. -/
instance GMul.toMul [Add ι] [GMul A] : Mul (GradedMonoid A) :=
⟨fun x y : GradedMonoid A => ⟨_, GMul.mul x.snd y.snd⟩⟩
@[simp] theorem fst_mul [Add ι] [GMul A] (x y : GradedMonoid A) :
(x * y).fst = x.fst + y.fst := rfl
@[simp] theorem snd_mul [Add ι] [GMul A] (x y : GradedMonoid A) :
(x * y).snd = GMul.mul x.snd y.snd := rfl
theorem mk_mul_mk [Add ι] [GMul A] {i j} (a : A i) (b : A j) :
mk i a * mk j b = mk (i + j) (GMul.mul a b) :=
rfl
namespace GMonoid
variable {A}
variable [AddMonoid ι] [GMul A] [GOne A]
/-- A default implementation of power on a graded monoid, like `npowRec`.
`GMonoid.gnpow` should be used instead. -/
def gnpowRec : ∀ (n : ℕ) {i}, A i → A (n • i)
| 0, i, _ => cast (congr_arg A (zero_nsmul i).symm) GOne.one
| n + 1, i, a => cast (congr_arg A (succ_nsmul i n).symm) (GMul.mul (gnpowRec _ a) a)
@[simp]
theorem gnpowRec_zero (a : GradedMonoid A) : GradedMonoid.mk _ (gnpowRec 0 a.snd) = 1 :=
Sigma.ext (zero_nsmul _) (heq_of_cast_eq _ rfl).symm
@[simp]
theorem gnpowRec_succ (n : ℕ) (a : GradedMonoid A) :
(GradedMonoid.mk _ <| gnpowRec n.succ a.snd) = ⟨_, gnpowRec n a.snd⟩ * a :=
Sigma.ext (succ_nsmul _ _) (heq_of_cast_eq _ rfl).symm
end GMonoid
/-- A tactic to for use as an optional value for `GMonoid.gnpow_zero'`. -/
macro "apply_gmonoid_gnpowRec_zero_tac" : tactic => `(tactic| apply GMonoid.gnpowRec_zero)
/-- A tactic to for use as an optional value for `GMonoid.gnpow_succ'`. -/
macro "apply_gmonoid_gnpowRec_succ_tac" : tactic => `(tactic| apply GMonoid.gnpowRec_succ)
/-- A graded version of `Monoid`
Like `Monoid.npow`, this has an optional `GMonoid.gnpow` field to allow definitional control of
natural powers of a graded monoid. -/
class GMonoid [AddMonoid ι] extends GMul A, GOne A where
/-- Multiplication by `one` on the left is the identity -/
one_mul (a : GradedMonoid A) : 1 * a = a
/-- Multiplication by `one` on the right is the identity -/
mul_one (a : GradedMonoid A) : a * 1 = a
/-- Multiplication is associative -/
mul_assoc (a b c : GradedMonoid A) : a * b * c = a * (b * c)
/-- Optional field to allow definitional control of natural powers -/
gnpow : ∀ (n : ℕ) {i}, A i → A (n • i) := GMonoid.gnpowRec
/-- The zeroth power will yield 1 -/
gnpow_zero' : ∀ a : GradedMonoid A, GradedMonoid.mk _ (gnpow 0 a.snd) = 1 := by
apply_gmonoid_gnpowRec_zero_tac
/-- Successor powers behave as expected -/
gnpow_succ' :
∀ (n : ℕ) (a : GradedMonoid A),
(GradedMonoid.mk _ <| gnpow n.succ a.snd) = ⟨_, gnpow n a.snd⟩ * a := by
apply_gmonoid_gnpowRec_succ_tac
/-- `GMonoid` implies a `Monoid (GradedMonoid A)`. -/
instance GMonoid.toMonoid [AddMonoid ι] [GMonoid A] : Monoid (GradedMonoid A) where
npow n a := GradedMonoid.mk _ (GMonoid.gnpow n a.snd)
npow_zero a := GMonoid.gnpow_zero' a
npow_succ n a := GMonoid.gnpow_succ' n a
one_mul := GMonoid.one_mul
mul_one := GMonoid.mul_one
mul_assoc := GMonoid.mul_assoc
@[simp] theorem fst_pow [AddMonoid ι] [GMonoid A] (x : GradedMonoid A) (n : ℕ) :
(x ^ n).fst = n • x.fst := rfl
@[simp] theorem snd_pow [AddMonoid ι] [GMonoid A] (x : GradedMonoid A) (n : ℕ) :
(x ^ n).snd = GMonoid.gnpow n x.snd := rfl
theorem mk_pow [AddMonoid ι] [GMonoid A] {i} (a : A i) (n : ℕ) :
mk i a ^ n = mk (n • i) (GMonoid.gnpow _ a) := rfl
/-- A graded version of `CommMonoid`. -/
class GCommMonoid [AddCommMonoid ι] extends GMonoid A where
/-- Multiplication is commutative -/
mul_comm (a : GradedMonoid A) (b : GradedMonoid A) : a * b = b * a
/-- `GCommMonoid` implies a `CommMonoid (GradedMonoid A)`, although this is only used as an
instance locally to define notation in `gmonoid` and similar typeclasses. -/
instance GCommMonoid.toCommMonoid [AddCommMonoid ι] [GCommMonoid A] : CommMonoid (GradedMonoid A) :=
{ GMonoid.toMonoid A with mul_comm := GCommMonoid.mul_comm }
end Defs
/-! ### Instances for `A 0`
The various `g*` instances are enough to promote the `AddCommMonoid (A 0)` structure to various
types of multiplicative structure.
-/
section GradeZero
variable (A : ι → Type*)
section One
variable [Zero ι] [GOne A]
/-- `1 : A 0` is the value provided in `GOne.one`. -/
@[nolint unusedArguments]
instance GradeZero.one : One (A 0) :=
⟨GOne.one⟩
end One
section Mul
variable [AddZeroClass ι] [GMul A]
/-- `(•) : A 0 → A i → A i` is the value provided in `GradedMonoid.GMul.mul`, composed with
an `Eq.rec` to turn `A (0 + i)` into `A i`.
-/
instance GradeZero.smul (i : ι) : SMul (A 0) (A i) where
smul x y := @Eq.rec ι (0+i) (fun a _ => A a) (GMul.mul x y) i (zero_add i)
/-- `(*) : A 0 → A 0 → A 0` is the value provided in `GradedMonoid.GMul.mul`, composed with
an `Eq.rec` to turn `A (0 + 0)` into `A 0`.
-/
instance GradeZero.mul : Mul (A 0) where mul := (· • ·)
variable {A}
@[simp]
theorem mk_zero_smul {i} (a : A 0) (b : A i) : mk _ (a • b) = mk _ a * mk _ b :=
Sigma.ext (zero_add _).symm <| eqRec_heq _ _
@[scoped simp]
theorem GradeZero.smul_eq_mul (a b : A 0) : a • b = a * b :=
rfl
end Mul
section Monoid
variable [AddMonoid ι] [GMonoid A]
instance : NatPow (A 0) where
pow x n := @Eq.rec ι (n • (0 : ι)) (fun a _ => A a) (GMonoid.gnpow n x) 0 (nsmul_zero n)
variable {A} in
@[simp]
theorem mk_zero_pow (a : A 0) (n : ℕ) : mk _ (a ^ n) = mk _ a ^ n :=
Sigma.ext (nsmul_zero n).symm <| eqRec_heq _ _
/-- The `Monoid` structure derived from `GMonoid A`. -/
instance GradeZero.monoid : Monoid (A 0) :=
Function.Injective.monoid (mk 0) sigma_mk_injective rfl mk_zero_smul mk_zero_pow
end Monoid
section Monoid
variable [AddCommMonoid ι] [GCommMonoid A]
/-- The `CommMonoid` structure derived from `GCommMonoid A`. -/
instance GradeZero.commMonoid : CommMonoid (A 0) :=
Function.Injective.commMonoid (mk 0) sigma_mk_injective rfl mk_zero_smul mk_zero_pow
end Monoid
section MulAction
variable [AddMonoid ι] [GMonoid A]
/-- `GradedMonoid.mk 0` is a `MonoidHom`, using the `GradedMonoid.GradeZero.monoid` structure.
-/
def mkZeroMonoidHom : A 0 →* GradedMonoid A where
toFun := mk 0
map_one' := rfl
map_mul' := mk_zero_smul
/-- Each grade `A i` derives an `A 0`-action structure from `GMonoid A`. -/
instance GradeZero.mulAction {i} : MulAction (A 0) (A i) :=
letI := MulAction.compHom (GradedMonoid A) (mkZeroMonoidHom A)
Function.Injective.mulAction (mk i) sigma_mk_injective mk_zero_smul
end MulAction
end GradeZero
end GradedMonoid
/-! ### Dependent products of graded elements -/
section DProd
variable {α : Type*} {A : ι → Type*} [AddMonoid ι] [GradedMonoid.GMonoid A]
/-- The index used by `List.dProd`. Propositionally this is equal to `(l.map fι).Sum`, but
definitionally it needs to have a different form to avoid introducing `Eq.rec`s in `List.dProd`. -/
def List.dProdIndex (l : List α) (fι : α → ι) : ι :=
l.foldr (fun i b => fι i + b) 0
@[simp]
theorem List.dProdIndex_nil (fι : α → ι) : ([] : List α).dProdIndex fι = 0 :=
rfl
@[simp]
theorem List.dProdIndex_cons (a : α) (l : List α) (fι : α → ι) :
(a :: l).dProdIndex fι = fι a + l.dProdIndex fι :=
rfl
theorem List.dProdIndex_eq_map_sum (l : List α) (fι : α → ι) :
l.dProdIndex fι = (l.map fι).sum := by
match l with
| [] => simp
| head::tail => simp [List.dProdIndex_eq_map_sum tail fι]
/-- A dependent product for graded monoids represented by the indexed family of types `A i`.
This is a dependent version of `(l.map fA).prod`.
For a list `l : List α`, this computes the product of `fA a` over `a`, where each `fA` is of type
`A (fι a)`. -/
def List.dProd (l : List α) (fι : α → ι) (fA : ∀ a, A (fι a)) : A (l.dProdIndex fι) :=
l.foldrRecOn _ GradedMonoid.GOne.one fun _ x a _ => GradedMonoid.GMul.mul (fA a) x
@[simp]
theorem List.dProd_nil (fι : α → ι) (fA : ∀ a, A (fι a)) :
(List.nil : List α).dProd fι fA = GradedMonoid.GOne.one :=
rfl
-- the `( :)` in this lemma statement results in the type on the RHS not being unfolded, which
-- is nicer in the goal view.
@[simp]
theorem List.dProd_cons (fι : α → ι) (fA : ∀ a, A (fι a)) (a : α) (l : List α) :
(a :: l).dProd fι fA = (GradedMonoid.GMul.mul (fA a) (l.dProd fι fA) :) :=
rfl
theorem GradedMonoid.mk_list_dProd (l : List α) (fι : α → ι) (fA : ∀ a, A (fι a)) :
GradedMonoid.mk _ (l.dProd fι fA) = (l.map fun a => GradedMonoid.mk (fι a) (fA a)).prod := by
match l with
| [] => simp only [List.dProdIndex_nil, List.dProd_nil, List.map_nil, List.prod_nil]; rfl
| head::tail =>
simp [← GradedMonoid.mk_list_dProd tail _ _, GradedMonoid.mk_mul_mk, List.prod_cons]
/-- A variant of `GradedMonoid.mk_list_dProd` for rewriting in the other direction. -/
theorem GradedMonoid.list_prod_map_eq_dProd (l : List α) (f : α → GradedMonoid A) :
(l.map f).prod = GradedMonoid.mk _ (l.dProd (fun i => (f i).1) fun i => (f i).2) := by
rw [GradedMonoid.mk_list_dProd, GradedMonoid.mk]
simp_rw [Sigma.eta]
theorem GradedMonoid.list_prod_ofFn_eq_dProd {n : ℕ} (f : Fin n → GradedMonoid A) :
(List.ofFn f).prod =
GradedMonoid.mk _ ((List.finRange n).dProd (fun i => (f i).1) fun i => (f i).2) := by
rw [List.ofFn_eq_map, GradedMonoid.list_prod_map_eq_dProd]
end DProd
/-! ### Concrete instances -/
section
variable (ι) {R : Type*}
@[simps one]
instance One.gOne [Zero ι] [One R] : GradedMonoid.GOne fun _ : ι => R where one := 1
@[simps mul]
instance Mul.gMul [Add ι] [Mul R] : GradedMonoid.GMul fun _ : ι => R where mul x y := x * y
/-- If all grades are the same type and themselves form a monoid, then there is a trivial grading
structure. -/
@[simps gnpow]
instance Monoid.gMonoid [AddMonoid ι] [Monoid R] : GradedMonoid.GMonoid fun _ : ι => R :=
-- { Mul.gMul ι, One.gOne ι with
{ One.gOne ι with
one_mul := fun _ => Sigma.ext (zero_add _) (heq_of_eq (one_mul _))
mul_one := fun _ => Sigma.ext (add_zero _) (heq_of_eq (mul_one _))
mul_assoc := fun _ _ _ => Sigma.ext (add_assoc _ _ _) (heq_of_eq (mul_assoc _ _ _))
gnpow := fun n _ a => a ^ n
gnpow_zero' := fun _ => Sigma.ext (zero_nsmul _) (heq_of_eq (Monoid.npow_zero _))
gnpow_succ' := fun _ ⟨_, _⟩ => Sigma.ext (succ_nsmul _ _) (heq_of_eq (Monoid.npow_succ _ _)) }
/-- If all grades are the same type and themselves form a commutative monoid, then there is a
trivial grading structure. -/
instance CommMonoid.gCommMonoid [AddCommMonoid ι] [CommMonoid R] :
GradedMonoid.GCommMonoid fun _ : ι => R :=
{ Monoid.gMonoid ι with
mul_comm := fun _ _ => Sigma.ext (add_comm _ _) (heq_of_eq (mul_comm _ _)) }
/-- When all the indexed types are the same, the dependent product is just the regular product. -/
@[simp]
theorem List.dProd_monoid {α} [AddMonoid ι] [Monoid R] (l : List α) (fι : α → ι) (fA : α → R) :
@List.dProd _ _ (fun _ : ι => R) _ _ l fι fA = (l.map fA).prod := by
match l with
| [] =>
rw [List.dProd_nil, List.map_nil, List.prod_nil]
rfl
| head::tail =>
rw [List.dProd_cons, List.map_cons, List.prod_cons, List.dProd_monoid tail _ _]
rfl
end
/-! ### Shorthands for creating instance of the above typeclasses for collections of subobjects -/
section Subobjects
variable {R : Type*}
/-- A version of `GradedMonoid.GOne` for internally graded objects. -/
class SetLike.GradedOne {S : Type*} [SetLike S R] [One R] [Zero ι] (A : ι → S) : Prop where
/-- One has grade zero -/
one_mem : (1 : R) ∈ A 0
theorem SetLike.one_mem_graded {S : Type*} [SetLike S R] [One R] [Zero ι] (A : ι → S)
[SetLike.GradedOne A] : (1 : R) ∈ A 0 :=
SetLike.GradedOne.one_mem
instance SetLike.gOne {S : Type*} [SetLike S R] [One R] [Zero ι] (A : ι → S)
[SetLike.GradedOne A] : GradedMonoid.GOne fun i => A i where
one := ⟨1, SetLike.one_mem_graded _⟩
@[simp]
theorem SetLike.coe_gOne {S : Type*} [SetLike S R] [One R] [Zero ι] (A : ι → S)
[SetLike.GradedOne A] : ↑(@GradedMonoid.GOne.one _ (fun i => A i) _ _) = (1 : R) :=
rfl
/-- A version of `GradedMonoid.ghas_one` for internally graded objects. -/
class SetLike.GradedMul {S : Type*} [SetLike S R] [Mul R] [Add ι] (A : ι → S) : Prop where
/-- Multiplication is homogeneous -/
mul_mem : ∀ ⦃i j⦄ {gi gj}, gi ∈ A i → gj ∈ A j → gi * gj ∈ A (i + j)
theorem SetLike.mul_mem_graded {S : Type*} [SetLike S R] [Mul R] [Add ι] {A : ι → S}
[SetLike.GradedMul A] ⦃i j⦄ {gi gj} (hi : gi ∈ A i) (hj : gj ∈ A j) : gi * gj ∈ A (i + j) :=
SetLike.GradedMul.mul_mem hi hj
instance SetLike.gMul {S : Type*} [SetLike S R] [Mul R] [Add ι] (A : ι → S)
[SetLike.GradedMul A] : GradedMonoid.GMul fun i => A i where
mul := fun a b => ⟨(a * b : R), SetLike.mul_mem_graded a.prop b.prop⟩
@[simp]
theorem SetLike.coe_gMul {S : Type*} [SetLike S R] [Mul R] [Add ι] (A : ι → S)
[SetLike.GradedMul A] {i j : ι} (x : A i) (y : A j) :
↑(@GradedMonoid.GMul.mul _ (fun i => A i) _ _ _ _ x y) = (x * y : R) :=
rfl
/-- A version of `GradedMonoid.GMonoid` for internally graded objects. -/
class SetLike.GradedMonoid {S : Type*} [SetLike S R] [Monoid R] [AddMonoid ι] (A : ι → S) : Prop
extends SetLike.GradedOne A, SetLike.GradedMul A
namespace SetLike
variable {S : Type*} [SetLike S R] [Monoid R] [AddMonoid ι]
variable {A : ι → S} [SetLike.GradedMonoid A]
namespace GradeZero
variable (A) in
/-- The submonoid `A 0` of `R`. -/
@[simps]
def submonoid : Submonoid R where
carrier := A 0
mul_mem' ha hb := add_zero (0 : ι) ▸ SetLike.mul_mem_graded ha hb
one_mem' := SetLike.one_mem_graded A
-- TODO: it might be expensive to unify `A` in this instances in practice
/-- The monoid `A 0` inherited from `R` in the presence of `SetLike.GradedMonoid A`. -/
instance instMonoid : Monoid (A 0) := inferInstanceAs <| Monoid (GradeZero.submonoid A)
-- TODO: it might be expensive to unify `A` in this instances in practice
/-- The commutative monoid `A 0` inherited from `R` in the presence of `SetLike.GradedMonoid A`. -/
instance instCommMonoid
{R S : Type*} [SetLike S R] [CommMonoid R]
{A : ι → S} [SetLike.GradedMonoid A] :
CommMonoid (A 0) :=
inferInstanceAs <| CommMonoid (GradeZero.submonoid A)
@[simp, norm_cast] theorem coe_one : ↑(1 : A 0) = (1 : R) := rfl
@[simp, norm_cast] theorem coe_mul (a b : A 0) : ↑(a * b) = (↑a * ↑b : R) := rfl
@[simp, norm_cast] theorem coe_pow (a : A 0) (n : ℕ) : ↑(a ^ n) = (↑a : R) ^ n := rfl
end GradeZero
theorem pow_mem_graded (n : ℕ) {r : R} {i : ι} (h : r ∈ A i) : r ^ n ∈ A (n • i) := by
match n with
| 0 =>
rw [pow_zero, zero_nsmul]
exact one_mem_graded _
| n + 1 =>
rw [pow_succ', succ_nsmul']
exact mul_mem_graded h (pow_mem_graded n h)
theorem list_prod_map_mem_graded {ι'} (l : List ι') (i : ι' → ι) (r : ι' → R)
(h : ∀ j ∈ l, r j ∈ A (i j)) : (l.map r).prod ∈ A (l.map i).sum := by
match l with
| [] =>
rw [List.map_nil, List.map_nil, List.prod_nil, List.sum_nil]
exact one_mem_graded _
| head::tail =>
rw [List.map_cons, List.map_cons, List.prod_cons, List.sum_cons]
exact
mul_mem_graded (h _ List.mem_cons_self)
(list_prod_map_mem_graded tail _ _ fun j hj => h _ <| List.mem_cons_of_mem _ hj)
theorem list_prod_ofFn_mem_graded {n} (i : Fin n → ι) (r : Fin n → R) (h : ∀ j, r j ∈ A (i j)) :
(List.ofFn r).prod ∈ A (List.ofFn i).sum := by
rw [List.ofFn_eq_map, List.ofFn_eq_map]
exact list_prod_map_mem_graded _ _ _ fun _ _ => h _
end SetLike
/-- Build a `GMonoid` instance for a collection of subobjects. -/
instance SetLike.gMonoid {S : Type*} [SetLike S R] [Monoid R] [AddMonoid ι] (A : ι → S)
[SetLike.GradedMonoid A] : GradedMonoid.GMonoid fun i => A i :=
{ SetLike.gOne A,
SetLike.gMul A with
one_mul := fun ⟨_, _, _⟩ => Sigma.subtype_ext (zero_add _) (one_mul _)
mul_one := fun ⟨_, _, _⟩ => Sigma.subtype_ext (add_zero _) (mul_one _)
mul_assoc := fun ⟨_, _, _⟩ ⟨_, _, _⟩ ⟨_, _, _⟩ =>
Sigma.subtype_ext (add_assoc _ _ _) (mul_assoc _ _ _)
gnpow := fun n _ a => ⟨(a:R)^n, SetLike.pow_mem_graded n a.prop⟩
gnpow_zero' := fun _ => Sigma.subtype_ext (zero_nsmul _) (pow_zero _)
gnpow_succ' := fun _ _ => Sigma.subtype_ext (succ_nsmul _ _) (pow_succ _ _) }
@[simp]
theorem SetLike.coe_gnpow {S : Type*} [SetLike S R] [Monoid R] [AddMonoid ι] (A : ι → S)
[SetLike.GradedMonoid A] {i : ι} (x : A i) (n : ℕ) :
↑(@GradedMonoid.GMonoid.gnpow _ (fun i => A i) _ _ n _ x) = (x:R)^n :=
rfl
/-- Build a `GCommMonoid` instance for a collection of subobjects. -/
instance SetLike.gCommMonoid {S : Type*} [SetLike S R] [CommMonoid R] [AddCommMonoid ι] (A : ι → S)
[SetLike.GradedMonoid A] : GradedMonoid.GCommMonoid fun i => A i :=
{ SetLike.gMonoid A with
mul_comm := fun ⟨_, _, _⟩ ⟨_, _, _⟩ => Sigma.subtype_ext (add_comm _ _) (mul_comm _ _) }
section DProd
open SetLike SetLike.GradedMonoid
variable {α S : Type*} [SetLike S R] [Monoid R] [AddMonoid ι]
@[simp]
theorem SetLike.coe_list_dProd (A : ι → S) [SetLike.GradedMonoid A] (fι : α → ι)
(fA : ∀ a, A (fι a)) (l : List α) : ↑(@List.dProd _ _ (fun i => ↥(A i)) _ _ l fι fA)
= (List.prod (l.map fun a => fA a) : R) := by
match l with
| [] =>
rw [List.dProd_nil, coe_gOne, List.map_nil, List.prod_nil]
| head::tail =>
rw [List.dProd_cons, coe_gMul, List.map_cons, List.prod_cons,
SetLike.coe_list_dProd _ _ _ tail]
/-- A version of `List.coe_dProd_set_like` with `Subtype.mk`. -/
theorem SetLike.list_dProd_eq (A : ι → S) [SetLike.GradedMonoid A] (fι : α → ι) (fA : ∀ a, A (fι a))
(l : List α) :
(@List.dProd _ _ (fun i => ↥(A i)) _ _ l fι fA) =
⟨List.prod (l.map fun a => fA a),
(l.dProdIndex_eq_map_sum fι).symm ▸
list_prod_map_mem_graded l _ _ fun i _ => (fA i).prop⟩ :=
Subtype.ext <| SetLike.coe_list_dProd _ _ _ _
end DProd
end Subobjects
section HomogeneousElements
variable {R S : Type*} [SetLike S R]
/-- An element `a : R` is said to be homogeneous if there is some `i : ι` such that `a ∈ A i`. -/
def SetLike.IsHomogeneousElem (A : ι → S) (a : R) : Prop :=
∃ i, a ∈ A i
@[simp]
theorem SetLike.isHomogeneousElem_coe {A : ι → S} {i} (x : A i) :
SetLike.IsHomogeneousElem A (x : R) :=
⟨i, x.prop⟩
theorem SetLike.isHomogeneousElem_one [Zero ι] [One R] (A : ι → S) [SetLike.GradedOne A] :
SetLike.IsHomogeneousElem A (1 : R) :=
⟨0, SetLike.one_mem_graded _⟩
theorem SetLike.IsHomogeneousElem.mul [Add ι] [Mul R] {A : ι → S} [SetLike.GradedMul A] {a b : R} :
SetLike.IsHomogeneousElem A a → SetLike.IsHomogeneousElem A b →
SetLike.IsHomogeneousElem A (a * b)
| ⟨i, hi⟩, ⟨j, hj⟩ => ⟨i + j, SetLike.mul_mem_graded hi hj⟩
/-- When `A` is a `SetLike.GradedMonoid A`, then the homogeneous elements forms a submonoid. -/
def SetLike.homogeneousSubmonoid [AddMonoid ι] [Monoid R] (A : ι → S) [SetLike.GradedMonoid A] :
Submonoid R where
carrier := { a | SetLike.IsHomogeneousElem A a }
one_mem' := SetLike.isHomogeneousElem_one A
mul_mem' a b := SetLike.IsHomogeneousElem.mul a b
end HomogeneousElements
section CommMonoid
namespace SetLike
variable {ι R S : Type*} [SetLike S R] [CommMonoid R] [AddCommMonoid ι]
variable (A : ι → S) [SetLike.GradedMonoid A]
variable {κ : Type*} (i : κ → ι) (g : κ → R) {F : Finset κ}
theorem prod_mem_graded (hF : ∀ k ∈ F, g k ∈ A (i k)) : ∏ k ∈ F, g k ∈ A (∑ k ∈ F, i k) := by
classical
induction F using Finset.induction_on
· simp [GradedOne.one_mem]
· case insert j F' hF2 h3 =>
rw [Finset.prod_insert hF2, Finset.sum_insert hF2]
apply SetLike.mul_mem_graded (by grind)
grind
theorem prod_pow_mem_graded (n : κ → ℕ) (hF : ∀ k ∈ F, g k ∈ A (i k)) :
∏ k ∈ F, g k ^ n k ∈ A (∑ k ∈ F, n k • i k) :=
prod_mem_graded A _ _ fun k hk ↦ pow_mem_graded _ (hF k hk)
end SetLike
end CommMonoid |
.lake/packages/mathlib/Mathlib/Algebra/QuadraticDiscriminant.lean | import Mathlib.Order.Filter.AtTopBot.Field
import Mathlib.Tactic.Field
import Mathlib.Tactic.LinearCombination
import Mathlib.Tactic.Linarith.Frontend
/-!
# Quadratic discriminants and roots of a quadratic
This file defines the discriminant of a quadratic and gives the solution to a quadratic equation.
## Main definition
- `discrim a b c`: the discriminant of a quadratic `a * (x * x) + b * x + c` is `b * b - 4 * a * c`.
## Main statements
- `quadratic_eq_zero_iff`: roots of a quadratic can be written as
`(-b + s) / (2 * a)` or `(-b - s) / (2 * a)`, where `s` is a square root of the discriminant.
- `quadratic_ne_zero_of_discrim_ne_sq`: if the discriminant has no square root,
then the corresponding quadratic has no root.
- `discrim_le_zero`: if a quadratic is always non-negative, then its discriminant is non-positive.
- `discrim_le_zero_of_nonpos`, `discrim_lt_zero`, `discrim_lt_zero_of_neg`: versions of this
statement with other inequalities.
## Tags
polynomial, quadratic, discriminant, root
-/
assert_not_exists Finite Finset
open Filter
section Ring
variable {R : Type*}
/-- Discriminant of a quadratic -/
def discrim [Ring R] (a b c : R) : R :=
b ^ 2 - 4 * a * c
@[simp] lemma discrim_neg [Ring R] (a b c : R) : discrim (-a) (-b) (-c) = discrim a b c := by
simp [discrim]
variable [CommRing R] {a b c : R}
lemma discrim_eq_sq_of_quadratic_eq_zero {x : R} (h : a * (x * x) + b * x + c = 0) :
discrim a b c = (2 * a * x + b) ^ 2 := by
rw [discrim]
linear_combination -4 * a * h
/-- A quadratic has roots if and only if its discriminant equals some square.
-/
theorem quadratic_eq_zero_iff_discrim_eq_sq [NeZero (2 : R)] [NoZeroDivisors R]
(ha : a ≠ 0) (x : R) :
a * (x * x) + b * x + c = 0 ↔ discrim a b c = (2 * a * x + b) ^ 2 := by
refine ⟨discrim_eq_sq_of_quadratic_eq_zero, fun h ↦ ?_⟩
rw [discrim] at h
have ha : 2 * 2 * a ≠ 0 := mul_ne_zero (mul_ne_zero (NeZero.ne _) (NeZero.ne _)) ha
apply mul_left_cancel₀ ha
linear_combination -h
/-- A quadratic has no root if its discriminant has no square root. -/
theorem quadratic_ne_zero_of_discrim_ne_sq (h : ∀ s : R, discrim a b c ≠ s^2) (x : R) :
a * (x * x) + b * x + c ≠ 0 :=
mt discrim_eq_sq_of_quadratic_eq_zero (h _)
end Ring
section Field
variable {K : Type*} [Field K] [NeZero (2 : K)] {a b c : K}
/-- Roots of a quadratic equation. -/
theorem quadratic_eq_zero_iff (ha : a ≠ 0) {s : K} (h : discrim a b c = s * s) (x : K) :
a * (x * x) + b * x + c = 0 ↔ x = (-b + s) / (2 * a) ∨ x = (-b - s) / (2 * a) := by
rw [quadratic_eq_zero_iff_discrim_eq_sq ha, h, sq, mul_self_eq_mul_self_iff]
field_simp
grind
/-- A quadratic has roots if its discriminant has square roots -/
theorem exists_quadratic_eq_zero (ha : a ≠ 0) (h : ∃ s, discrim a b c = s * s) :
∃ x, a * (x * x) + b * x + c = 0 := by
rcases h with ⟨s, hs⟩
use (-b + s) / (2 * a)
rw [quadratic_eq_zero_iff ha hs]
simp
/-- Root of a quadratic when its discriminant equals zero -/
theorem quadratic_eq_zero_iff_of_discrim_eq_zero (ha : a ≠ 0) (h : discrim a b c = 0) (x : K) :
a * (x * x) + b * x + c = 0 ↔ x = -b / (2 * a) := by
have : discrim a b c = 0 * 0 := by rw [h, mul_zero]
rw [quadratic_eq_zero_iff ha this, add_zero, sub_zero, or_self_iff]
theorem discrim_eq_zero_of_existsUnique (ha : a ≠ 0) (h : ∃! x, a * (x * x) + b * x + c = 0) :
discrim a b c = 0 := by
simp_rw [quadratic_eq_zero_iff_discrim_eq_sq ha] at h
generalize discrim a b c = d at h
obtain ⟨x, rfl, hx⟩ := h
specialize hx (-(x + b / a))
grind
theorem discrim_eq_zero_iff (ha : a ≠ 0) :
discrim a b c = 0 ↔ (∃! x, a * (x * x) + b * x + c = 0) := by
refine ⟨fun hd => ?_, discrim_eq_zero_of_existsUnique ha⟩
simp_rw [quadratic_eq_zero_iff_of_discrim_eq_zero ha hd, existsUnique_eq]
end Field
section LinearOrderedField
variable {K : Type*} [Field K] [LinearOrder K] [IsStrictOrderedRing K] {a b c : K}
/-- If a polynomial of degree 2 is always nonnegative, then its discriminant is nonpositive -/
theorem discrim_le_zero (h : ∀ x : K, 0 ≤ a * (x * x) + b * x + c) : discrim a b c ≤ 0 := by
rw [discrim, sq]
obtain ha | rfl | ha : a < 0 ∨ a = 0 ∨ 0 < a := lt_trichotomy a 0
-- if a < 0
· have : Tendsto (fun x => (a * x + b) * x + c) atTop atBot :=
tendsto_atBot_add_const_right _ c <|
(tendsto_atBot_add_const_right _ b (tendsto_id.const_mul_atTop_of_neg ha)).atBot_mul_atTop₀
tendsto_id
rcases (this.eventually (eventually_lt_atBot 0)).exists with ⟨x, hx⟩
exact False.elim ((h x).not_gt <| by rwa [← mul_assoc, ← add_mul])
-- if a = 0
· rcases eq_or_ne b 0 with (rfl | hb)
· simp
· have := h ((-c - 1) / b)
rw [mul_div_cancel₀ _ hb] at this
linarith
-- if a > 0
· have ha' : 0 ≤ 4 * a := mul_nonneg zero_le_four ha.le
convert neg_nonpos.2 (mul_nonneg ha' (h (-b / (2 * a)))) using 1
field
lemma discrim_le_zero_of_nonpos (h : ∀ x : K, a * (x * x) + b * x + c ≤ 0) : discrim a b c ≤ 0 :=
discrim_neg a b c ▸ discrim_le_zero <| by simpa only [neg_mul, ← neg_add, neg_nonneg]
/-- If a polynomial of degree 2 is always positive, then its discriminant is negative,
at least when the coefficient of the quadratic term is nonzero.
-/
theorem discrim_lt_zero (ha : a ≠ 0) (h : ∀ x : K, 0 < a * (x * x) + b * x + c) :
discrim a b c < 0 := by
have : ∀ x : K, 0 ≤ a * (x * x) + b * x + c := fun x => le_of_lt (h x)
refine lt_of_le_of_ne (discrim_le_zero this) fun h' ↦ ?_
have := h (-b / (2 * a))
have : a * (-b / (2 * a)) * (-b / (2 * a)) + b * (-b / (2 * a)) + c = 0 := by
rw [mul_assoc, quadratic_eq_zero_iff_of_discrim_eq_zero ha h' (-b / (2 * a))]
linarith
lemma discrim_lt_zero_of_neg (ha : a ≠ 0) (h : ∀ x : K, a * (x * x) + b * x + c < 0) :
discrim a b c < 0 :=
discrim_neg a b c ▸ discrim_lt_zero (neg_ne_zero.2 ha) <| by
simpa only [neg_mul, ← neg_add, neg_pos]
end LinearOrderedField |
.lake/packages/mathlib/Mathlib/Algebra/AlgebraicCard.lean | import Mathlib.Algebra.Polynomial.Cardinal
import Mathlib.RingTheory.Algebraic.Basic
/-!
### Cardinality of algebraic numbers
In this file, we prove variants of the following result: the cardinality of algebraic numbers under
an R-algebra is at most `#R[X] * ℵ₀`.
Although this can be used to prove that real or complex transcendental numbers exist, a more direct
proof is given by `Liouville.transcendental`.
-/
universe u v
open Cardinal Polynomial Set
open Cardinal Polynomial
namespace Algebraic
theorem infinite_of_charZero (R A : Type*) [CommRing R] [Ring A] [Algebra R A]
[CharZero A] : { x : A | IsAlgebraic R x }.Infinite := by
letI := MulActionWithZero.nontrivial R A
exact infinite_of_injective_forall_mem Nat.cast_injective isAlgebraic_nat
theorem aleph0_le_cardinalMk_of_charZero (R A : Type*) [CommRing R] [Ring A]
[Algebra R A] [CharZero A] : ℵ₀ ≤ #{ x : A // IsAlgebraic R x } :=
infinite_iff.1 (Set.infinite_coe_iff.2 <| infinite_of_charZero R A)
section lift
variable (R : Type u) (A : Type v) [CommRing R] [CommRing A] [IsDomain A] [Algebra R A]
[NoZeroSMulDivisors R A]
theorem cardinalMk_lift_le_mul :
Cardinal.lift.{u} #{ x : A // IsAlgebraic R x } ≤ Cardinal.lift.{v} #R[X] * ℵ₀ := by
rw [← mk_uLift, ← mk_uLift]
choose g hg₁ hg₂ using fun x : { x : A | IsAlgebraic R x } => x.coe_prop
refine lift_mk_le_lift_mk_mul_of_lift_mk_preimage_le g fun f => ?_
rw [lift_le_aleph0, le_aleph0_iff_set_countable]
suffices MapsTo (↑) (g ⁻¹' {f}) (f.rootSet A) from
this.countable_of_injOn Subtype.coe_injective.injOn (f.rootSet_finite A).countable
rintro x (rfl : g x = f)
exact mem_rootSet.2 ⟨hg₁ x, hg₂ x⟩
theorem cardinalMk_lift_le_max :
Cardinal.lift.{u} #{ x : A // IsAlgebraic R x } ≤ max (Cardinal.lift.{v} #R) ℵ₀ :=
(cardinalMk_lift_le_mul R A).trans <| by grw [lift_le.2 cardinalMk_le_max]; simp
@[simp]
theorem cardinalMk_lift_of_infinite [Infinite R] :
Cardinal.lift.{u} #{ x : A // IsAlgebraic R x } = Cardinal.lift.{v} #R :=
((cardinalMk_lift_le_max R A).trans_eq (max_eq_left <| aleph0_le_mk _)).antisymm <|
lift_mk_le'.2 ⟨⟨fun x => ⟨algebraMap R A x, isAlgebraic_algebraMap _⟩, fun _ _ h =>
FaithfulSMul.algebraMap_injective R A (Subtype.ext_iff.1 h)⟩⟩
variable [Countable R]
@[simp]
protected theorem countable : Set.Countable { x : A | IsAlgebraic R x } := by
rw [← le_aleph0_iff_set_countable, ← lift_le_aleph0]
apply (cardinalMk_lift_le_max R A).trans
simp
@[simp]
theorem cardinalMk_of_countable_of_charZero [CharZero A] :
#{ x : A // IsAlgebraic R x } = ℵ₀ :=
(Algebraic.countable R A).le_aleph0.antisymm (aleph0_le_cardinalMk_of_charZero R A)
end lift
section NonLift
variable (R A : Type u) [CommRing R] [CommRing A] [IsDomain A] [Algebra R A]
[NoZeroSMulDivisors R A]
theorem cardinalMk_le_mul : #{ x : A // IsAlgebraic R x } ≤ #R[X] * ℵ₀ := by
rw [← lift_id #_, ← lift_id #R[X]]
exact cardinalMk_lift_le_mul R A
@[stacks 09GK]
theorem cardinalMk_le_max : #{ x : A // IsAlgebraic R x } ≤ max #R ℵ₀ := by
rw [← lift_id #_, ← lift_id #R]
exact cardinalMk_lift_le_max R A
@[simp]
theorem cardinalMk_of_infinite [Infinite R] : #{ x : A // IsAlgebraic R x } = #R :=
lift_inj.1 <| cardinalMk_lift_of_infinite R A
end NonLift
end Algebraic |
.lake/packages/mathlib/Mathlib/Algebra/IsPrimePow.lean | import Mathlib.Algebra.Order.Ring.Nat
import Mathlib.Order.Nat
import Mathlib.Data.Nat.Prime.Basic
import Mathlib.Data.Nat.Log
import Mathlib.Data.Nat.Prime.Pow
/-!
# Prime powers
This file deals with prime powers: numbers which are positive integer powers of a single prime.
-/
assert_not_exists Nat.divisors
variable {R : Type*} [CommMonoidWithZero 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 IsPrimePow : Prop :=
∃ (p : R) (k : ℕ), Prime p ∧ 0 < k ∧ p ^ k = n
theorem isPrimePow_def : IsPrimePow 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)`. -/
theorem isPrimePow_iff_pow_succ : IsPrimePow n ↔ ∃ (p : R) (k : ℕ), Prime p ∧ p ^ (k + 1) = n :=
(isPrimePow_def _).trans
⟨fun ⟨p, k, hp, hk, hn⟩ => ⟨p, k - 1, hp, by rwa [Nat.sub_add_cancel hk]⟩, fun ⟨_, _, hp, hn⟩ =>
⟨_, _, hp, Nat.succ_pos', hn⟩⟩
theorem not_isPrimePow_zero [NoZeroDivisors R] : ¬IsPrimePow (0 : R) := by
simp only [isPrimePow_def, not_exists, not_and', and_imp]
intro x n _hn hx
rw [eq_zero_of_pow_eq_zero hx]
simp
theorem IsPrimePow.not_unit {n : R} (h : IsPrimePow n) : ¬IsUnit n :=
let ⟨_p, _k, hp, hk, hn⟩ := h
hn ▸ (isUnit_pow_iff hk.ne').not.mpr hp.not_unit
theorem IsUnit.not_isPrimePow {n : R} (h : IsUnit n) : ¬IsPrimePow n := fun h' => h'.not_unit h
theorem not_isPrimePow_one : ¬IsPrimePow (1 : R) :=
isUnit_one.not_isPrimePow
theorem Prime.isPrimePow {p : R} (hp : Prime p) : IsPrimePow p :=
⟨p, 1, hp, zero_lt_one, by simp⟩
theorem IsPrimePow.pow {n : R} (hn : IsPrimePow n) {k : ℕ} (hk : k ≠ 0) : IsPrimePow (n ^ k) :=
let ⟨p, k', hp, hk', hn⟩ := hn
⟨p, k * k', hp, mul_pos hk.bot_lt hk', by rw [pow_mul', hn]⟩
theorem IsPrimePow.ne_zero [NoZeroDivisors R] {n : R} (h : IsPrimePow n) : n ≠ 0 := fun t =>
not_isPrimePow_zero (t ▸ h)
theorem IsPrimePow.ne_one {n : R} (h : IsPrimePow n) : n ≠ 1 := fun t =>
not_isPrimePow_one (t ▸ h)
section Nat
theorem isPrimePow_nat_iff (n : ℕ) : IsPrimePow n ↔ ∃ p k : ℕ, Nat.Prime p ∧ 0 < k ∧ p ^ k = n := by
simp only [isPrimePow_def, Nat.prime_iff]
theorem Nat.Prime.isPrimePow {p : ℕ} (hp : p.Prime) : IsPrimePow p :=
_root_.Prime.isPrimePow (prime_iff.mp hp)
theorem isPrimePow_nat_iff_bounded (n : ℕ) :
IsPrimePow n ↔ ∃ p : ℕ, p ≤ n ∧ ∃ k : ℕ, k ≤ n ∧ p.Prime ∧ 0 < k ∧ p ^ k = n := by
rw [isPrimePow_nat_iff]
refine Iff.symm ⟨fun ⟨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⟩
conv => { lhs; rw [← (pow_one p)] }
exact Nat.pow_le_pow_right hp.one_lt.le hk
theorem isPrimePow_nat_iff_bounded_log (n : ℕ) :
IsPrimePow n
↔ ∃ k : ℕ, k ≤ Nat.log 2 n ∧ 0 < k ∧ ∃ p : ℕ, p ≤ n ∧ n = p ^ k ∧ p.Prime := by
rw [isPrimePow_nat_iff]
constructor
· rintro ⟨p, k, hp', hk', rfl⟩
refine ⟨k, ?_, hk', ⟨p, Nat.le_pow hk', rfl, hp'⟩⟩
· calc
k = Nat.log 2 (2 ^ k) := by simp
_ ≤ Nat.log 2 (p ^ k) := Nat.log_mono Nat.one_lt_two Nat.AtLeastTwo.prop
(Nat.pow_le_pow_left (Nat.Prime.two_le hp') k)
· rintro ⟨k, hk, hk', ⟨p, hp, rfl, hp'⟩⟩
exact ⟨p, k, hp', hk', rfl⟩
theorem isPrimePow_nat_iff_bounded_log_minFac (n : ℕ) :
IsPrimePow n
↔ ∃ k : ℕ, k ≤ Nat.log 2 n ∧ 0 < k ∧ n = n.minFac ^ k := by
rw [isPrimePow_nat_iff_bounded_log]
obtain rfl | h := eq_or_ne n 1
· simp
constructor
· rintro ⟨k, hkle, hk_pos, p, hle, heq, hprime⟩
refine ⟨k, hkle, hk_pos, ?_⟩
rw [heq, hprime.pow_minFac hk_pos.ne']
· rintro ⟨k, hkle, hk_pos, heq⟩
refine ⟨k, hkle, hk_pos, n.minFac, Nat.minFac_le ?_, heq, ?_⟩
· grind [Nat.minFac_prime_iff, nonpos_iff_eq_zero, Nat.log_zero_right, lt_self_iff_false]
· grind [Nat.minFac_prime_iff]
instance {n : ℕ} : Decidable (IsPrimePow n) :=
decidable_of_iff' _ (isPrimePow_nat_iff_bounded_log_minFac n)
theorem IsPrimePow.dvd {n m : ℕ} (hn : IsPrimePow n) (hm : m ∣ n) (hm₁ : m ≠ 1) : IsPrimePow m := by
grind [isPrimePow_nat_iff, Nat.dvd_prime_pow, Nat.pow_eq_one]
theorem IsPrimePow.two_le : ∀ {n : ℕ}, IsPrimePow n → 2 ≤ n
| 0, h => (not_isPrimePow_zero h).elim
| 1, h => (not_isPrimePow_one h).elim
| _n + 2, _ => le_add_self
theorem IsPrimePow.pos {n : ℕ} (hn : IsPrimePow n) : 0 < n :=
pos_of_gt hn.two_le
theorem IsPrimePow.one_lt {n : ℕ} (h : IsPrimePow n) : 1 < n :=
h.two_le
end Nat |
.lake/packages/mathlib/Mathlib/Algebra/HierarchyDesign.lean | import Mathlib.Init
import Mathlib.Tactic.Basic
/-!
# Documentation of the algebraic hierarchy
A library note giving advice on modifying the algebraic hierarchy.
(It is not intended as a "tour".) This is ported directly from the Lean3 version, so may
refer to files/types that currently only exist in mathlib3.
TODO: Add sections about interactions with topological typeclasses, and order typeclasses.
-/
library_note2 «the algebraic hierarchy» /-- # The algebraic hierarchy
In any theorem proving environment,
there are difficult decisions surrounding the design of the "algebraic hierarchy".
There is a danger of exponential explosion in the number of gadgets,
especially once interactions between algebraic and order/topological/etc. structures are considered.
In mathlib, we try to avoid this by only introducing new algebraic typeclasses either
1. when there is "real mathematics" to be done with them, or
2. when there is a meaningful gain in simplicity by factoring out a common substructure.
(As examples, at this point we don't have `Loop`, or `UnitalMagma`,
but we do have `LieSubmodule` and `TopologicalField`!
We also have `GroupWithZero`, as an exemplar of point 2.)
Generally in mathlib we use the extension mechanism (so `CommRing` extends `Ring`)
rather than mixins (e.g. with separate `Ring` and `CommMul` classes),
in part because of the potential blow-up in term sizes described at
https://www.ralfj.de/blog/2019/05/15/typeclasses-exponential-blowup.html
However there is tension here, as it results in considerable duplication in the API,
particularly in the interaction with order structures.
This library note is not intended as a design document
justifying and explaining the history of mathlib's algebraic hierarchy!
Instead it is intended as a developer's guide, for contributors wanting to extend
(either new leaves, or new intermediate classes) the algebraic hierarchy as it exists.
(Ideally we would have both a tour guide to the existing hierarchy,
and an account of the design choices.
See https://arxiv.org/abs/1910.09336 for an overview of mathlib as a whole,
with some attention to the algebraic hierarchy and
https://leanprover-community.github.io/mathlib-overview.html
for a summary of what is in mathlib today.)
## Instances
When adding a new typeclass `Z` to the algebraic hierarchy
one should attempt to add the following constructions and results,
when applicable:
* Instances transferred elementwise to products, like `Prod.Monoid`.
See `Mathlib/Algebra/Group/Prod.lean` for more examples.
```
instance Prod.Z [Z M] [Z N] : Z (M × N) := ...
```
* Instances transferred elementwise to pi types, like `Pi.Monoid`.
See `Mathlib/Algebra/Group/Pi.lean` for more examples.
```
instance Pi.Z [∀ i, Z <| f i] : Z (Π i : I, f i) := ...
```
* Instances transferred to `MulOpposite M`, like `MulOpposite.Monoid`.
See `Mathlib/Algebra/Opposites.lean` for more examples.
```
instance MulOpposite.Z [Z M] : Z (MulOpposite M) := ...
```
* Instances transferred to `ULift M`, like `ULift.Monoid`.
See `Mathlib/Algebra/Group/ULift.lean` for more examples.
```
instance ULift.Z [Z M] : Z (ULift M) := ...
```
* Definitions for transferring the proof fields of instances along
injective or surjective functions that agree on the data fields,
like `Function.Injective.monoid` and `Function.Surjective.monoid`.
We make these definitions `abbrev`, see note [reducible non-instances].
See `Mathlib/Algebra/Group/InjSurj.lean` for more examples.
```
abbrev Function.Injective.Z [Z M₂] (f : M₁ → M₂) (hf : f.Injective)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : Z M₁ := ...
abbrev Function.Surjective.Z [Z M₁] (f : M₁ → M₂) (hf : f.Surjective)
(one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : Z M₂ := ...
```
* Instances transferred elementwise to `Finsupp`s, like `Finsupp.semigroup`.
See `Mathlib/Data/Finsupp/Pointwise.lean` for more examples.
```
instance Finsupp.Z [Z β] : Z (α →₀ β) := ...
```
* Instances transferred elementwise to `Set`s, like `Set.monoid`.
See `Mathlib/Algebra/Pointwise.lean` for more examples.
```
instance Set.Z [Z α] : Z (Set α) := ...
```
* Definitions for transferring the entire structure across an equivalence, like `Equiv.monoid`.
See `Mathlib/Data/Equiv/TransferInstance.lean` for more examples. See also the `transport` tactic.
```
def Equiv.Z (e : α ≃ β) [Z β] : Z α := ...
/-- When there is a new notion of `Z`-equiv: -/
def Equiv.ZEquiv (e : α ≃ β) [Z β] : by { letI := Equiv.Z e, exact α ≃Z β } := ...
```
## Subobjects
When a new typeclass `Z` adds new data fields,
you should also create a new `SubZ` `structure` with a `carrier` field.
This can be a lot of work; for now try to closely follow the existing examples
(e.g. `Submonoid`, `Subring`, `Subalgebra`).
We would very much like to provide some automation here, but a prerequisite will be making
all the existing APIs more uniform.
If `Z` extends `Y`, then `SubZ` should usually extend `SubY`.
When `Z` adds only new proof fields to an existing structure `Y`,
you should provide instances transferring
`Z α` to `Z (SubY α)`, like `Submonoid.toCommMonoid`.
Typically this is done using the `Function.Injective.Z` definition mentioned above.
```
instance SubY.toZ [Z α] : Z (SubY α) :=
coe_injective.Z coe ...
```
## Morphisms and equivalences
## Category theory
For many algebraic structures, particularly ones used in representation theory, algebraic geometry,
etc., we also define "bundled" versions, which carry `category` instances.
These bundled versions are usually named by appending `Cat`,
so for example we have `AddCommGrpCat` as a bundled `AddCommGroup`, and `TopCommRingCat`
(which bundles together `CommRing`, `TopologicalSpace`, and `IsTopologicalRing`).
These bundled versions have many appealing features:
* a uniform notation for morphisms `X ⟶ Y`
* a uniform notation (and definition) for isomorphisms `X ≅ Y`
* a uniform API for subobjects, via the partial order `Subobject X`
* interoperability with unbundled structures, via coercions to `Type`
(so if `G : AddCommGrpCat`, you can treat `G` as a type,
and it automatically has an `AddCommGroup` instance)
and lifting maps `AddCommGrpCat.of G`, when `G` is a type with an `AddCommGroup` instance.
If, for example you do the work of proving that a typeclass `Z` has a good notion of tensor product,
you are strongly encouraged to provide the corresponding `MonoidalCategory` instance
on a bundled version.
This ensures that the API for tensor products is complete, and enables use of general machinery.
Similarly if you prove universal properties, or adjunctions, you are encouraged to state these
using categorical language!
One disadvantage of the bundled approach is that we can only speak of morphisms between
objects living in the same type-theoretic universe.
In practice this is rarely a problem.
# Making a pull request
With so many moving parts, how do you actually go about changing the algebraic hierarchy?
We're still evolving how to handle this, but the current suggestion is:
* If you're adding a new "leaf" class, the requirements are lower,
and an initial PR can just add whatever is immediately needed.
* A new "intermediate" class, especially low down in the hierarchy,
needs to be careful about leaving gaps.
In a perfect world, there would be a group of simultaneous PRs that basically cover everything!
(Or at least an expectation that PRs may not be merged immediately while waiting on other
PRs that fill out the API.)
However "perfect is the enemy of good", and it would also be completely reasonable
to add a TODO list in the main module doc-string for the new class,
briefly listing the parts of the API which still need to be provided.
Hopefully this document makes it easy to assemble this list.
Another alternative to a TODO list in the doc-strings is adding Github issues.
-/
library_note2 «reducible non-instances» /--
Some definitions that define objects of a class cannot be instances, because they have an
explicit argument that does not occur in the conclusion. An example is `Preorder.lift` that has a
function `f : α → β` as an explicit argument to lift a preorder on `β` to a preorder on `α`.
If these definitions are used to define instances of this class *and* this class is an argument to
some other type-class so that type-class inference will have to unfold these instances to check
for definitional equality, then these definitions should be marked `@[reducible]`.
For example, `Preorder.lift` is used to define `Units.Preorder` and `PartialOrder.lift` is used
to define `Units.PartialOrder`. In some cases it is important that type-class inference can
recognize that `Units.Preorder` and `Units.PartialOrder` give rise to the same `LE` instance.
For example, you might have another class that takes `[LE α]` as an argument, and this argument
sometimes comes from `Units.Preorder` and sometimes from `Units.PartialOrder`.
Therefore, `Preorder.lift` and `PartialOrder.lift` are marked `@[reducible]`.
-/
library_note2 «implicit instance arguments» /--
There are places where typeclass arguments are specified with implicit `{}` brackets instead of
the usual `[]` brackets. This is done when the instances can be inferred because they are implicit
arguments to the type of one of the other arguments. When they can be inferred from these other
arguments, it is faster to use this method than to use type class inference.
For example, when writing lemmas about `(f : α →+* β)`, it is faster to specify the fact that `α`
and `β` are `Semiring`s as `{rα : Semiring α} {rβ : Semiring β}` rather than the usual
`[Semiring α] [Semiring β]`.
-/
library_note2 «lower instance priority» /--
Certain instances always apply during type-class resolution. For example, the instance
`AddCommGroup.toAddGroup {α} [AddCommGroup α] : AddGroup α` applies to all type-class
resolution problems of the form `AddGroup _`, and type-class inference will then do an
exhaustive search to find a commutative group. These instances take a long time to fail.
Other instances will only apply if the goal has a certain shape. For example
`Int.instAddGroupInt : AddGroup ℤ` or
`Prod.instAddGroup {α β} [AddGroup α] [AddGroup β] : AddGroup (α × β)`. Usually these instances
will fail quickly, and when they apply, they are almost always the desired instance.
For this reason, we want the instances of the second type (that only apply in specific cases) to
always have higher priority than the instances of the first type (that always apply).
See also [mathlib#1561](https://github.com/leanprover-community/mathlib/issues/1561).
Therefore, if we create an instance that always applies, we set the priority of these instances to
100 (or something similar, which is below the default value of 1000).
-/
library_note2 «instance argument order» /--
When type class inference applies an instance, it attempts to solve the sub-goals from left to
right (it used to be from right to left in lean 3). For example in
```
instance {p : α → Sort*} [∀ x, IsEmpty (p x)] [Nonempty α] : IsEmpty (∀ x, p x)
```
we make sure to write `[∀ x, IsEmpty (p x)]` on the left of `[Nonempty α]` to avoid an expensive
search for `Nonempty α` when there is no instance for `∀ x, IsEmpty (p x)`.
This helps to speed up failing type class searches, for example those triggered by `simp` lemmas.
In some situations, we can't reorder type class assumptions because one depends on the other,
for example in
```
instance {G : Type*} [Group G] [IsKleinFour G] : IsAddKleinFour (Additive G)
```
where the `Group G` instance appears in `IsKleinFour G`. Future work may be done to improve the
type class synthesis order in this situation.
-/ |
.lake/packages/mathlib/Mathlib/Algebra/CubicDiscriminant.lean | import Mathlib.Algebra.Polynomial.Splits
import Mathlib.Tactic.IntervalCases
/-!
# Cubics and discriminants
This file defines cubic polynomials over a semiring and their discriminants over a splitting field.
## Main definitions
* `Cubic`: the structure representing a cubic polynomial.
* `Cubic.discr`: the discriminant of a cubic polynomial.
## Main statements
* `Cubic.discr_ne_zero_iff_roots_nodup`: the cubic discriminant is not equal to zero if and only if
the cubic has no duplicate roots.
## References
* https://en.wikipedia.org/wiki/Cubic_equation
* https://en.wikipedia.org/wiki/Discriminant
## Tags
cubic, discriminant, polynomial, root
-/
noncomputable section
/-- The structure representing a cubic polynomial. -/
@[ext]
structure Cubic (R : Type*) where
/-- The degree-3 coefficient -/
a : R
/-- The degree-2 coefficient -/
b : R
/-- The degree-1 coefficient -/
c : R
/-- The degree-0 coefficient -/
d : R
namespace Cubic
open Polynomial
variable {R S F K : Type*}
instance [Inhabited R] : Inhabited (Cubic R) :=
⟨⟨default, default, default, default⟩⟩
instance [Zero R] : Zero (Cubic R) :=
⟨⟨0, 0, 0, 0⟩⟩
section Basic
variable {P Q : Cubic R} {a b c d a' b' c' d' : R} [Semiring R]
/-- Convert a cubic polynomial to a polynomial. -/
def toPoly (P : Cubic R) : R[X] :=
C P.a * X ^ 3 + C P.b * X ^ 2 + C P.c * X + C P.d
theorem C_mul_prod_X_sub_C_eq [CommRing S] {w x y z : S} :
C w * (X - C x) * (X - C y) * (X - C z) =
toPoly ⟨w, w * -(x + y + z), w * (x * y + x * z + y * z), w * -(x * y * z)⟩ := by
simp only [toPoly, C_neg, C_add, C_mul]
ring1
theorem prod_X_sub_C_eq [CommRing S] {x y z : S} :
(X - C x) * (X - C y) * (X - C z) =
toPoly ⟨1, -(x + y + z), x * y + x * z + y * z, -(x * y * z)⟩ := by
rw [← one_mul <| X - C x, ← C_1, C_mul_prod_X_sub_C_eq, one_mul, one_mul, one_mul]
/-! ### Coefficients -/
section Coeff
private theorem coeffs : (∀ n > 3, P.toPoly.coeff n = 0) ∧ P.toPoly.coeff 3 = P.a ∧
P.toPoly.coeff 2 = P.b ∧ P.toPoly.coeff 1 = P.c ∧ P.toPoly.coeff 0 = P.d := by
simp only [Cubic.toPoly, Polynomial.coeff_add, Polynomial.coeff_C, Polynomial.coeff_C_mul_X,
Polynomial.coeff_C_mul_X_pow]
grind [zero_add]
@[simp]
theorem coeff_eq_zero {n : ℕ} (hn : 3 < n) : P.toPoly.coeff n = 0 :=
coeffs.1 n hn
@[simp]
theorem coeff_eq_a : P.toPoly.coeff 3 = P.a :=
coeffs.2.1
@[simp]
theorem coeff_eq_b : P.toPoly.coeff 2 = P.b :=
coeffs.2.2.1
@[simp]
theorem coeff_eq_c : P.toPoly.coeff 1 = P.c :=
coeffs.2.2.2.1
@[simp]
theorem coeff_eq_d : P.toPoly.coeff 0 = P.d :=
coeffs.2.2.2.2
theorem a_of_eq (h : P.toPoly = Q.toPoly) : P.a = Q.a := by rw [← coeff_eq_a, h, coeff_eq_a]
theorem b_of_eq (h : P.toPoly = Q.toPoly) : P.b = Q.b := by rw [← coeff_eq_b, h, coeff_eq_b]
theorem c_of_eq (h : P.toPoly = Q.toPoly) : P.c = Q.c := by rw [← coeff_eq_c, h, coeff_eq_c]
theorem d_of_eq (h : P.toPoly = Q.toPoly) : P.d = Q.d := by rw [← coeff_eq_d, h, coeff_eq_d]
theorem toPoly_injective (P Q : Cubic R) : P.toPoly = Q.toPoly ↔ P = Q :=
⟨fun h ↦ Cubic.ext (a_of_eq h) (b_of_eq h) (c_of_eq h) (d_of_eq h), congr_arg toPoly⟩
theorem of_a_eq_zero (ha : P.a = 0) : P.toPoly = C P.b * X ^ 2 + C P.c * X + C P.d := by
rw [toPoly, ha, C_0, zero_mul, zero_add]
theorem of_a_eq_zero' : toPoly ⟨0, b, c, d⟩ = C b * X ^ 2 + C c * X + C d :=
of_a_eq_zero rfl
theorem of_b_eq_zero (ha : P.a = 0) (hb : P.b = 0) : P.toPoly = C P.c * X + C P.d := by
rw [of_a_eq_zero ha, hb, C_0, zero_mul, zero_add]
theorem of_b_eq_zero' : toPoly ⟨0, 0, c, d⟩ = C c * X + C d :=
of_b_eq_zero rfl rfl
theorem of_c_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) : P.toPoly = C P.d := by
rw [of_b_eq_zero ha hb, hc, C_0, zero_mul, zero_add]
theorem of_c_eq_zero' : toPoly ⟨0, 0, 0, d⟩ = C d :=
of_c_eq_zero rfl rfl rfl
theorem of_d_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) (hd : P.d = 0) :
P.toPoly = 0 := by
rw [of_c_eq_zero ha hb hc, hd, C_0]
theorem of_d_eq_zero' : (⟨0, 0, 0, 0⟩ : Cubic R).toPoly = 0 :=
of_d_eq_zero rfl rfl rfl rfl
theorem zero : (0 : Cubic R).toPoly = 0 :=
of_d_eq_zero'
theorem toPoly_eq_zero_iff (P : Cubic R) : P.toPoly = 0 ↔ P = 0 := by
rw [← zero, toPoly_injective]
private theorem ne_zero (h0 : P.a ≠ 0 ∨ P.b ≠ 0 ∨ P.c ≠ 0 ∨ P.d ≠ 0) : P.toPoly ≠ 0 := by
contrapose! h0
rw [(toPoly_eq_zero_iff P).mp h0]
exact ⟨rfl, rfl, rfl, rfl⟩
theorem ne_zero_of_a_ne_zero (ha : P.a ≠ 0) : P.toPoly ≠ 0 :=
(or_imp.mp ne_zero).1 ha
theorem ne_zero_of_b_ne_zero (hb : P.b ≠ 0) : P.toPoly ≠ 0 :=
(or_imp.mp (or_imp.mp ne_zero).2).1 hb
theorem ne_zero_of_c_ne_zero (hc : P.c ≠ 0) : P.toPoly ≠ 0 :=
(or_imp.mp (or_imp.mp (or_imp.mp ne_zero).2).2).1 hc
theorem ne_zero_of_d_ne_zero (hd : P.d ≠ 0) : P.toPoly ≠ 0 :=
(or_imp.mp (or_imp.mp (or_imp.mp ne_zero).2).2).2 hd
@[simp]
theorem leadingCoeff_of_a_ne_zero (ha : P.a ≠ 0) : P.toPoly.leadingCoeff = P.a :=
leadingCoeff_cubic ha
theorem leadingCoeff_of_a_ne_zero' (ha : a ≠ 0) : (toPoly ⟨a, b, c, d⟩).leadingCoeff = a := by
simp [ha]
@[simp]
theorem leadingCoeff_of_b_ne_zero (ha : P.a = 0) (hb : P.b ≠ 0) : P.toPoly.leadingCoeff = P.b := by
rw [of_a_eq_zero ha, leadingCoeff_quadratic hb]
theorem leadingCoeff_of_b_ne_zero' (hb : b ≠ 0) : (toPoly ⟨0, b, c, d⟩).leadingCoeff = b := by
simp [hb]
@[simp]
theorem leadingCoeff_of_c_ne_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c ≠ 0) :
P.toPoly.leadingCoeff = P.c := by
rw [of_b_eq_zero ha hb, leadingCoeff_linear hc]
theorem leadingCoeff_of_c_ne_zero' (hc : c ≠ 0) : (toPoly ⟨0, 0, c, d⟩).leadingCoeff = c := by
simp [hc]
@[simp]
theorem leadingCoeff_of_c_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) :
P.toPoly.leadingCoeff = P.d := by
rw [of_c_eq_zero ha hb hc, leadingCoeff_C]
theorem leadingCoeff_of_c_eq_zero' : (toPoly ⟨0, 0, 0, d⟩).leadingCoeff = d :=
leadingCoeff_of_c_eq_zero rfl rfl rfl
theorem monic_of_a_eq_one (ha : P.a = 1) : P.toPoly.Monic := by
nontriviality R
rw [Monic, leadingCoeff_of_a_ne_zero (ha ▸ one_ne_zero), ha]
theorem monic_of_a_eq_one' : (toPoly ⟨1, b, c, d⟩).Monic :=
monic_of_a_eq_one rfl
theorem monic_of_b_eq_one (ha : P.a = 0) (hb : P.b = 1) : P.toPoly.Monic := by
nontriviality R
rw [Monic, leadingCoeff_of_b_ne_zero ha (hb ▸ one_ne_zero), hb]
theorem monic_of_b_eq_one' : (toPoly ⟨0, 1, c, d⟩).Monic :=
monic_of_b_eq_one rfl rfl
theorem monic_of_c_eq_one (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 1) : P.toPoly.Monic := by
nontriviality R
rw [Monic, leadingCoeff_of_c_ne_zero ha hb (hc ▸ one_ne_zero), hc]
theorem monic_of_c_eq_one' : (toPoly ⟨0, 0, 1, d⟩).Monic :=
monic_of_c_eq_one rfl rfl rfl
theorem monic_of_d_eq_one (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) (hd : P.d = 1) :
P.toPoly.Monic := by
rw [Monic, leadingCoeff_of_c_eq_zero ha hb hc, hd]
theorem monic_of_d_eq_one' : (toPoly ⟨0, 0, 0, 1⟩).Monic :=
monic_of_d_eq_one rfl rfl rfl rfl
end Coeff
/-! ### Degrees -/
section Degree
/-- The equivalence between cubic polynomials and polynomials of degree at most three. -/
@[simps]
def equiv : Cubic R ≃ { p : R[X] // p.degree ≤ 3 } where
toFun P := ⟨P.toPoly, degree_cubic_le⟩
invFun f := ⟨coeff f 3, coeff f 2, coeff f 1, coeff f 0⟩
left_inv P := by ext <;> simp only [coeffs]
right_inv f := by
ext n
obtain hn | hn := le_or_gt n 3
· interval_cases n <;> simp only <;> ring_nf <;> try simp only [coeffs]
· rw [coeff_eq_zero hn, (degree_le_iff_coeff_zero (f : R[X]) 3).mp f.2]
simpa using hn
@[simp]
theorem degree_of_a_ne_zero (ha : P.a ≠ 0) : P.toPoly.degree = 3 :=
degree_cubic ha
theorem degree_of_a_ne_zero' (ha : a ≠ 0) : (toPoly ⟨a, b, c, d⟩).degree = 3 := by
simp [ha]
theorem degree_of_a_eq_zero (ha : P.a = 0) : P.toPoly.degree ≤ 2 := by
simpa only [of_a_eq_zero ha] using degree_quadratic_le
theorem degree_of_a_eq_zero' : (toPoly ⟨0, b, c, d⟩).degree ≤ 2 :=
degree_of_a_eq_zero rfl
@[simp]
theorem degree_of_b_ne_zero (ha : P.a = 0) (hb : P.b ≠ 0) : P.toPoly.degree = 2 := by
rw [of_a_eq_zero ha, degree_quadratic hb]
theorem degree_of_b_ne_zero' (hb : b ≠ 0) : (toPoly ⟨0, b, c, d⟩).degree = 2 := by
simp [hb]
theorem degree_of_b_eq_zero (ha : P.a = 0) (hb : P.b = 0) : P.toPoly.degree ≤ 1 := by
simpa only [of_b_eq_zero ha hb] using degree_linear_le
theorem degree_of_b_eq_zero' : (toPoly ⟨0, 0, c, d⟩).degree ≤ 1 :=
degree_of_b_eq_zero rfl rfl
@[simp]
theorem degree_of_c_ne_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c ≠ 0) : P.toPoly.degree = 1 := by
rw [of_b_eq_zero ha hb, degree_linear hc]
theorem degree_of_c_ne_zero' (hc : c ≠ 0) : (toPoly ⟨0, 0, c, d⟩).degree = 1 := by
simp [hc]
theorem degree_of_c_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) : P.toPoly.degree ≤ 0 := by
simpa only [of_c_eq_zero ha hb hc] using degree_C_le
theorem degree_of_c_eq_zero' : (toPoly ⟨0, 0, 0, d⟩).degree ≤ 0 :=
degree_of_c_eq_zero rfl rfl rfl
@[simp]
theorem degree_of_d_ne_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) (hd : P.d ≠ 0) :
P.toPoly.degree = 0 := by
rw [of_c_eq_zero ha hb hc, degree_C hd]
theorem degree_of_d_ne_zero' (hd : d ≠ 0) : (toPoly ⟨0, 0, 0, d⟩).degree = 0 := by
simp [hd]
@[simp]
theorem degree_of_d_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) (hd : P.d = 0) :
P.toPoly.degree = ⊥ := by
rw [of_d_eq_zero ha hb hc hd, degree_zero]
theorem degree_of_d_eq_zero' : (⟨0, 0, 0, 0⟩ : Cubic R).toPoly.degree = ⊥ :=
degree_of_d_eq_zero rfl rfl rfl rfl
@[simp]
theorem degree_of_zero : (0 : Cubic R).toPoly.degree = ⊥ :=
degree_of_d_eq_zero'
@[simp]
theorem natDegree_of_a_ne_zero (ha : P.a ≠ 0) : P.toPoly.natDegree = 3 :=
natDegree_cubic ha
theorem natDegree_of_a_ne_zero' (ha : a ≠ 0) : (toPoly ⟨a, b, c, d⟩).natDegree = 3 := by
simp [ha]
theorem natDegree_of_a_eq_zero (ha : P.a = 0) : P.toPoly.natDegree ≤ 2 := by
simpa only [of_a_eq_zero ha] using natDegree_quadratic_le
theorem natDegree_of_a_eq_zero' : (toPoly ⟨0, b, c, d⟩).natDegree ≤ 2 :=
natDegree_of_a_eq_zero rfl
@[simp]
theorem natDegree_of_b_ne_zero (ha : P.a = 0) (hb : P.b ≠ 0) : P.toPoly.natDegree = 2 := by
rw [of_a_eq_zero ha, natDegree_quadratic hb]
theorem natDegree_of_b_ne_zero' (hb : b ≠ 0) : (toPoly ⟨0, b, c, d⟩).natDegree = 2 := by
simp [hb]
theorem natDegree_of_b_eq_zero (ha : P.a = 0) (hb : P.b = 0) : P.toPoly.natDegree ≤ 1 := by
simpa only [of_b_eq_zero ha hb] using natDegree_linear_le
theorem natDegree_of_b_eq_zero' : (toPoly ⟨0, 0, c, d⟩).natDegree ≤ 1 :=
natDegree_of_b_eq_zero rfl rfl
@[simp]
theorem natDegree_of_c_ne_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c ≠ 0) :
P.toPoly.natDegree = 1 := by
rw [of_b_eq_zero ha hb, natDegree_linear hc]
theorem natDegree_of_c_ne_zero' (hc : c ≠ 0) : (toPoly ⟨0, 0, c, d⟩).natDegree = 1 := by
simp [hc]
@[simp]
theorem natDegree_of_c_eq_zero (ha : P.a = 0) (hb : P.b = 0) (hc : P.c = 0) :
P.toPoly.natDegree = 0 := by
rw [of_c_eq_zero ha hb hc, natDegree_C]
theorem natDegree_of_c_eq_zero' : (toPoly ⟨0, 0, 0, d⟩).natDegree = 0 :=
natDegree_of_c_eq_zero rfl rfl rfl
@[simp]
theorem natDegree_of_zero : (0 : Cubic R).toPoly.natDegree = 0 :=
natDegree_of_c_eq_zero'
end Degree
/-! ### Map across a homomorphism -/
section Map
variable [Semiring S] {φ : R →+* S}
/-- Map a cubic polynomial across a semiring homomorphism. -/
def map (φ : R →+* S) (P : Cubic R) : Cubic S :=
⟨φ P.a, φ P.b, φ P.c, φ P.d⟩
theorem map_toPoly : (map φ P).toPoly = Polynomial.map φ P.toPoly := by
simp only [map, toPoly, map_C, map_X, Polynomial.map_add, Polynomial.map_mul, Polynomial.map_pow]
end Map
end Basic
section Roots
open Multiset
/-! ### Roots over an extension -/
section Extension
variable {P : Cubic R} [CommRing R] [CommRing S] {φ : R →+* S}
/-- The roots of a cubic polynomial. -/
def roots [IsDomain R] (P : Cubic R) : Multiset R :=
P.toPoly.roots
theorem map_roots [IsDomain S] : (map φ P).roots = (Polynomial.map φ P.toPoly).roots := by
rw [roots, map_toPoly]
theorem mem_roots_iff [IsDomain R] (h0 : P.toPoly ≠ 0) (x : R) :
x ∈ P.roots ↔ P.a * x ^ 3 + P.b * x ^ 2 + P.c * x + P.d = 0 := by
rw [roots, mem_roots h0, IsRoot, toPoly]
simp only [eval_C, eval_X, eval_add, eval_mul, eval_pow]
theorem card_roots_le [IsDomain R] [DecidableEq R] : P.roots.toFinset.card ≤ 3 := by
apply (toFinset_card_le P.toPoly.roots).trans
by_cases hP : P.toPoly = 0
· exact (card_roots' P.toPoly).trans (by rw [hP, natDegree_zero]; exact zero_le 3)
· exact WithBot.coe_le_coe.1 ((card_roots hP).trans degree_cubic_le)
end Extension
variable {P : Cubic F} [Field F] [Field K] {φ : F →+* K} {x y z : K}
/-! ### Roots over a splitting field -/
section Split
theorem splits_iff_card_roots (ha : P.a ≠ 0) :
Splits φ P.toPoly ↔ Multiset.card (map φ P).roots = 3 := by
replace ha : (map φ P).a ≠ 0 := (_root_.map_ne_zero φ).mpr ha
nth_rw 1 [← RingHom.id_comp φ]
rw [roots, ← splits_map_iff, ← map_toPoly, Polynomial.splits_iff_card_roots,
← ((degree_eq_iff_natDegree_eq <| ne_zero_of_a_ne_zero ha).1 <| degree_of_a_ne_zero ha : _ = 3)]
theorem splits_iff_roots_eq_three (ha : P.a ≠ 0) :
Splits φ P.toPoly ↔ ∃ x y z : K, (map φ P).roots = {x, y, z} := by
rw [splits_iff_card_roots ha, card_eq_three]
theorem eq_prod_three_roots (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) :
(map φ P).toPoly = C (φ P.a) * (X - C x) * (X - C y) * (X - C z) := by
rw [map_toPoly,
eq_prod_roots_of_splits <|
(splits_iff_roots_eq_three ha).mpr <| Exists.intro x <| Exists.intro y <| Exists.intro z h3,
leadingCoeff_of_a_ne_zero ha, ← map_roots, h3]
change C (φ P.a) * ((X - C x) ::ₘ (X - C y) ::ₘ {X - C z}).prod = _
rw [prod_cons, prod_cons, prod_singleton, mul_assoc, mul_assoc]
theorem eq_sum_three_roots (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) :
map φ P =
⟨φ P.a, φ P.a * -(x + y + z), φ P.a * (x * y + x * z + y * z), φ P.a * -(x * y * z)⟩ := by
apply_fun @toPoly _ _
· rw [eq_prod_three_roots ha h3, C_mul_prod_X_sub_C_eq]
· exact fun P Q ↦ (toPoly_injective P Q).mp
theorem b_eq_three_roots (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) :
φ P.b = φ P.a * -(x + y + z) := by
injection eq_sum_three_roots ha h3
theorem c_eq_three_roots (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) :
φ P.c = φ P.a * (x * y + x * z + y * z) := by
injection eq_sum_three_roots ha h3
theorem d_eq_three_roots (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) :
φ P.d = φ P.a * -(x * y * z) := by
injection eq_sum_three_roots ha h3
end Split
/-! ### Discriminant over a splitting field -/
section Discriminant
/-- The discriminant of a cubic polynomial. -/
def discr {R : Type*} [Ring R] (P : Cubic R) : R :=
P.b ^ 2 * P.c ^ 2 - 4 * P.a * P.c ^ 3 - 4 * P.b ^ 3 * P.d - 27 * P.a ^ 2 * P.d ^ 2 +
18 * P.a * P.b * P.c * P.d
theorem discr_eq_prod_three_roots (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) :
φ P.discr = (φ P.a * φ P.a * (x - y) * (x - z) * (y - z)) ^ 2 := by
simp only [discr, RingHom.map_add, RingHom.map_sub, RingHom.map_mul, map_pow, map_ofNat]
rw [b_eq_three_roots ha h3, c_eq_three_roots ha h3, d_eq_three_roots ha h3]
ring1
theorem discr_ne_zero_iff_roots_ne (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) :
P.discr ≠ 0 ↔ x ≠ y ∧ x ≠ z ∧ y ≠ z := by
rw [← _root_.map_ne_zero φ, discr_eq_prod_three_roots ha h3, pow_two]
simp_rw [mul_ne_zero_iff, sub_ne_zero, _root_.map_ne_zero, and_self_iff, and_iff_right ha,
and_assoc]
theorem discr_ne_zero_iff_roots_nodup (ha : P.a ≠ 0) (h3 : (map φ P).roots = {x, y, z}) :
P.discr ≠ 0 ↔ (map φ P).roots.Nodup := by
rw [discr_ne_zero_iff_roots_ne ha h3, h3]
change _ ↔ (x ::ₘ y ::ₘ {z}).Nodup
rw [nodup_cons, nodup_cons, mem_cons, mem_singleton, mem_singleton]
simp only [nodup_singleton]
tauto
theorem card_roots_of_discr_ne_zero [DecidableEq K] (ha : P.a ≠ 0)
(h3 : (map φ P).roots = {x, y, z}) (hd : P.discr ≠ 0) : (map φ P).roots.toFinset.card = 3 := by
rw [toFinset_card_of_nodup <| (discr_ne_zero_iff_roots_nodup ha h3).mp hd,
← splits_iff_card_roots ha, splits_iff_roots_eq_three ha]
exact ⟨x, ⟨y, ⟨z, h3⟩⟩⟩
@[deprecated (since := "2025-10-20")] alias disc := discr
@[deprecated (since := "2025-10-20")] alias disc_eq_prod_three_roots := discr_eq_prod_three_roots
@[deprecated (since := "2025-10-20")] alias disc_ne_zero_iff_roots_ne := discr_ne_zero_iff_roots_ne
@[deprecated (since := "2025-10-20")] alias disc_ne_zero_iff_roots_nodup :=
discr_ne_zero_iff_roots_nodup
@[deprecated (since := "2025-10-20")] alias card_roots_of_disc_ne_zero :=
card_roots_of_discr_ne_zero
end Discriminant
end Roots
end Cubic |
.lake/packages/mathlib/Mathlib/Algebra/FiveLemma.lean | import Mathlib.Algebra.Exact
/-!
# The five lemma in terms of modules
The five lemma for all abelian categories is proven in
`CategoryTheory.Abelian.isIso_of_epi_of_isIso_of_isIso_of_mono`. But for universe generality
and ease of application in the unbundled setting, we reprove them here.
## Main results
- `LinearMap.surjective_of_surjective_of_surjective_of_injective`: a four lemma
- `LinearMap.injective_of_surjective_of_injective_of_injective`: another four lemma
- `LinearMap.bijective_of_surjective_of_bijective_of_bijective_of_injective`: the five lemma
## Explanation of the variables
In this file we always consider the following commutative diagram of additive groups (resp. modules)
```
M₁ --f₁--> M₂ --f₂--> M₃ --f₃--> M₄ --f₄--> M₅
| | | | |
i₁ i₂ i₃ i₄ i₅
| | | | |
v v v v v
N₁ --g₁--> N₂ --g₂--> N₃ --g₃--> N₄ --g₄--> N₅
```
with exact rows.
## Implementation details
In theory, we could prove these in the multiplicative version and let `to_additive` prove
the additive variants. But `Function.Exact` currently has no multiplicative analogue (yet).
-/
assert_not_exists Cardinal
namespace AddMonoidHom
variable {M₁ M₂ M₃ M₄ M₅ N₁ N₂ N₃ N₄ N₅ : Type*}
variable [AddGroup M₁] [AddGroup M₂] [AddGroup M₃] [AddGroup M₄] [AddGroup M₅]
variable [AddGroup N₁] [AddGroup N₂] [AddGroup N₃] [AddGroup N₄] [AddGroup N₅]
variable (f₁ : M₁ →+ M₂) (f₂ : M₂ →+ M₃) (f₃ : M₃ →+ M₄) (f₄ : M₄ →+ M₅)
variable (g₁ : N₁ →+ N₂) (g₂ : N₂ →+ N₃) (g₃ : N₃ →+ N₄) (g₄ : N₄ →+ N₅)
variable (i₁ : M₁ →+ N₁) (i₂ : M₂ →+ N₂) (i₃ : M₃ →+ N₃) (i₄ : M₄ →+ N₄)
(i₅ : M₅ →+ N₅)
variable (hc₁ : g₁.comp i₁ = i₂.comp f₁) (hc₂ : g₂.comp i₂ = i₃.comp f₂)
(hc₃ : g₃.comp i₃ = i₄.comp f₃) (hc₄ : g₄.comp i₄ = i₅.comp f₄)
variable (hf₁ : Function.Exact f₁ f₂) (hf₂ : Function.Exact f₂ f₃) (hf₃ : Function.Exact f₃ f₄)
variable (hg₁ : Function.Exact g₁ g₂) (hg₂ : Function.Exact g₂ g₃) (hg₃ : Function.Exact g₃ g₄)
include hf₂ hg₁ hg₂ hc₁ hc₂ hc₃ in
/-- One four lemma in terms of (additive) groups. For a diagram explaining the variables,
see the module docstring. -/
lemma surjective_of_surjective_of_surjective_of_injective (hi₁ : Function.Surjective i₁)
(hi₃ : Function.Surjective i₃) (hi₄ : Function.Injective i₄) :
Function.Surjective i₂ := by
intro x
obtain ⟨y, hy⟩ := hi₃ (g₂ x)
obtain ⟨a, rfl⟩ : y ∈ Set.range f₂ := (hf₂ _).mp <| by
simpa [hy, hg₂.apply_apply_eq_zero, map_eq_zero_iff _ hi₄] using (DFunLike.congr_fun hc₃ y).symm
obtain ⟨b, hb⟩ : x - i₂ a ∈ Set.range g₁ := (hg₁ _).mp <| by
simp [← hy, show g₂ (i₂ a) = i₃ (f₂ a) by simpa using DFunLike.congr_fun hc₂ a]
obtain ⟨o, rfl⟩ := hi₁ b
use f₁ o + a
simp [← show g₁ (i₁ o) = i₂ (f₁ o) by simpa using DFunLike.congr_fun hc₁ o, hb]
include hf₁ hf₂ hg₁ hc₁ hc₂ hc₃ in
/-- One four lemma in terms of (additive) groups. For a diagram explaining the variables,
see the module docstring. -/
lemma injective_of_surjective_of_injective_of_injective (hi₁ : Function.Surjective i₁)
(hi₂ : Function.Injective i₂) (hi₄ : Function.Injective i₄) : Function.Injective i₃ := by
rw [injective_iff_map_eq_zero]
intro m hm
obtain ⟨x, rfl⟩ := (hf₂ m).mp <| by
suffices h : i₄ (f₃ m) = 0 by rwa [map_eq_zero_iff _ hi₄] at h
simp [← show g₃ (i₃ m) = i₄ (f₃ m) by simpa using DFunLike.congr_fun hc₃ m, hm]
obtain ⟨y, hy⟩ := (hg₁ _).mp <| by
rwa [show g₂ (i₂ x) = i₃ (f₂ x) by simpa using DFunLike.congr_fun hc₂ x]
obtain ⟨a, rfl⟩ := hi₁ y
rw [show g₁ (i₁ a) = i₂ (f₁ a) by simpa using DFunLike.congr_fun hc₁ a] at hy
apply hi₂ at hy
subst hy
rw [hf₁.apply_apply_eq_zero]
include hf₁ hf₂ hf₃ hg₁ hg₂ hg₃ hc₁ hc₂ hc₃ hc₄ in
/-- The five lemma in terms of (additive) groups. For a diagram explaining the variables,
see the module docstring. -/
lemma bijective_of_surjective_of_bijective_of_bijective_of_injective (hi₁ : Function.Surjective i₁)
(hi₂ : Function.Bijective i₂) (hi₄ : Function.Bijective i₄) (hi₅ : Function.Injective i₅) :
Function.Bijective i₃ :=
⟨injective_of_surjective_of_injective_of_injective f₁ f₂ f₃ g₁ g₂ g₃ i₁ i₂ i₃ i₄
hc₁ hc₂ hc₃ hf₁ hf₂ hg₁ hi₁ hi₂.1 hi₄.1,
surjective_of_surjective_of_surjective_of_injective f₂ f₃ f₄ g₂ g₃ g₄ i₂ i₃ i₄ i₅
hc₂ hc₃ hc₄ hf₃ hg₂ hg₃ hi₂.2 hi₄.2 hi₅⟩
end AddMonoidHom
namespace LinearMap
variable {R : Type*} [CommRing R]
variable {M₁ M₂ M₃ M₄ M₅ N₁ N₂ N₃ N₄ N₅ : Type*}
variable [AddCommGroup M₁] [AddCommGroup M₂] [AddCommGroup M₃] [AddCommGroup M₄] [AddCommGroup M₅]
variable [Module R M₁] [Module R M₂] [Module R M₃] [Module R M₄] [Module R M₅]
variable [AddCommGroup N₁] [AddCommGroup N₂] [AddCommGroup N₃] [AddCommGroup N₄] [AddCommGroup N₅]
variable [Module R N₁] [Module R N₂] [Module R N₃] [Module R N₄] [Module R N₅]
variable (f₁ : M₁ →ₗ[R] M₂) (f₂ : M₂ →ₗ[R] M₃) (f₃ : M₃ →ₗ[R] M₄) (f₄ : M₄ →ₗ[R] M₅)
variable (g₁ : N₁ →ₗ[R] N₂) (g₂ : N₂ →ₗ[R] N₃) (g₃ : N₃ →ₗ[R] N₄) (g₄ : N₄ →ₗ[R] N₅)
variable (i₁ : M₁ →ₗ[R] N₁) (i₂ : M₂ →ₗ[R] N₂) (i₃ : M₃ →ₗ[R] N₃) (i₄ : M₄ →ₗ[R] N₄)
(i₅ : M₅ →ₗ[R] N₅)
variable (hc₁ : g₁.comp i₁ = i₂.comp f₁) (hc₂ : g₂.comp i₂ = i₃.comp f₂)
(hc₃ : g₃.comp i₃ = i₄.comp f₃) (hc₄ : g₄.comp i₄ = i₅.comp f₄)
variable (hf₁ : Function.Exact f₁ f₂) (hf₂ : Function.Exact f₂ f₃) (hf₃ : Function.Exact f₃ f₄)
variable (hg₁ : Function.Exact g₁ g₂) (hg₂ : Function.Exact g₂ g₃) (hg₃ : Function.Exact g₃ g₄)
include hf₂ hg₁ hg₂ hc₁ hc₂ hc₃ in
/-- One four lemma in terms of modules. For a diagram explaining the variables,
see the module docstring. -/
lemma surjective_of_surjective_of_surjective_of_injective (hi₁ : Function.Surjective i₁)
(hi₃ : Function.Surjective i₃) (hi₄ : Function.Injective i₄) :
Function.Surjective i₂ :=
AddMonoidHom.surjective_of_surjective_of_surjective_of_injective
f₁.toAddMonoidHom f₂.toAddMonoidHom f₃.toAddMonoidHom g₁.toAddMonoidHom g₂.toAddMonoidHom
g₃.toAddMonoidHom i₁.toAddMonoidHom i₂.toAddMonoidHom i₃.toAddMonoidHom i₄.toAddMonoidHom
(AddMonoidHom.ext fun x ↦ DFunLike.congr_fun hc₁ x)
(AddMonoidHom.ext fun x ↦ DFunLike.congr_fun hc₂ x)
(AddMonoidHom.ext fun x ↦ DFunLike.congr_fun hc₃ x) hf₂ hg₁ hg₂ hi₁ hi₃ hi₄
include hf₁ hf₂ hg₁ hc₁ hc₂ hc₃ in
/-- One four lemma in terms of modules. For a diagram explaining the variables,
see the module docstring. -/
lemma injective_of_surjective_of_injective_of_injective (hi₁ : Function.Surjective i₁)
(hi₂ : Function.Injective i₂) (hi₄ : Function.Injective i₄) :
Function.Injective i₃ :=
AddMonoidHom.injective_of_surjective_of_injective_of_injective
f₁.toAddMonoidHom f₂.toAddMonoidHom f₃.toAddMonoidHom g₁.toAddMonoidHom g₂.toAddMonoidHom
g₃.toAddMonoidHom i₁.toAddMonoidHom i₂.toAddMonoidHom i₃.toAddMonoidHom i₄.toAddMonoidHom
(AddMonoidHom.ext fun x ↦ DFunLike.congr_fun hc₁ x)
(AddMonoidHom.ext fun x ↦ DFunLike.congr_fun hc₂ x)
(AddMonoidHom.ext fun x ↦ DFunLike.congr_fun hc₃ x) hf₁ hf₂ hg₁ hi₁ hi₂ hi₄
include hf₁ hf₂ hf₃ hg₁ hg₂ hg₃ hc₁ hc₂ hc₃ hc₄ in
/-- The five lemma in terms of modules. For a diagram explaining the variables,
see the module docstring. -/
lemma bijective_of_surjective_of_bijective_of_bijective_of_injective (hi₁ : Function.Surjective i₁)
(hi₂ : Function.Bijective i₂) (hi₄ : Function.Bijective i₄) (hi₅ : Function.Injective i₅) :
Function.Bijective i₃ :=
⟨injective_of_surjective_of_injective_of_injective f₁ f₂ f₃ g₁ g₂ g₃ i₁ i₂ i₃ i₄
hc₁ hc₂ hc₃ hf₁ hf₂ hg₁ hi₁ hi₂.1 hi₄.1,
surjective_of_surjective_of_surjective_of_injective f₂ f₃ f₄ g₂ g₃ g₄ i₂ i₃ i₄ i₅
hc₂ hc₃ hc₄ hf₃ hg₂ hg₃ hi₂.2 hi₄.2 hi₅⟩
end LinearMap |
.lake/packages/mathlib/Mathlib/Algebra/ArithmeticGeometric.lean | import Mathlib.Analysis.SpecificLimits.ArithmeticGeometric
deprecated_module (since := "2025-09-17") |
.lake/packages/mathlib/Mathlib/Algebra/Quotient.lean | import Mathlib.Tactic.Common
/-!
# Algebraic quotients
This file defines notation for algebraic quotients, e.g. quotient groups `G ⧸ H`,
quotient modules `M ⧸ N` and ideal quotients `R ⧸ I`.
The actual quotient structures are defined in the following files:
* Quotient Group: `Mathlib/GroupTheory/Cosets/Defs.lean`
* Quotient Module: `Mathlib/LinearAlgebra/Quotient/Defs.lean`
* Quotient Ring: `Mathlib/RingTheory/Ideal/Quotient/Defs.lean`
## Notation
The following notation is introduced:
* `G ⧸ H` stands for the quotient of the type `G` by some term `H`
(for example, `H` can be a normal subgroup of `G`).
To implement this notation for other quotients, you should provide a `HasQuotient` instance.
Note that since `G` can usually be inferred from `H`, `_ ⧸ H` can also be used,
but this is less readable.
## Tags
quotient, group quotient, quotient group, module quotient, quotient module, ring quotient,
ideal quotient, quotient ring
-/
universe u v
/-- `HasQuotient A B` is a notation typeclass that allows us to write `A ⧸ b` for `b : B`.
This allows the usual notation for quotients of algebraic structures,
such as groups, modules and rings.
`A` is a parameter, despite being unused in the definition below, so it appears in the notation.
-/
class HasQuotient (A : outParam <| Type u) (B : Type v) where
/-- auxiliary quotient function, the one used will have `A` explicit -/
quotient' : B → Type max u v
-- Will be provided by e.g. `Ideal.Quotient.inhabited`
/--
`HasQuotient.Quotient A b` (denoted as `A ⧸ b`) is the quotient of the type `A` by `b`.
This differs from `HasQuotient.quotient'` in that the `A` argument is explicit,
which is necessary to make Lean show the notation in the goal state.
-/
abbrev HasQuotient.Quotient (A : outParam <| Type u) {B : Type v}
[HasQuotient A B] (b : B) : Type max u v :=
HasQuotient.quotient' b
/-- Quotient notation based on the `HasQuotient` typeclass -/
notation:35 G " ⧸ " H:34 => HasQuotient.Quotient G H |
.lake/packages/mathlib/Mathlib/Algebra/README.md | # Algebra
This folder contains algebra in a broad sense.
## Algebraic hierarchy
The basic algebraic hierarchy is split across a series of subfolders that each depend on the
previous:
* `Algebra.Notation` for basic algebraic notation
* `Algebra.Group` for semigroups, monoids, groups
* `Algebra.GroupWithZero` for monoids with a zero adjoined, groups with a zero adjoined
* `Algebra.Ring` for additive monoids and groups with one, semirings, rings
* `Algebra.Field` for semifields, fields
Files in earlier subfolders should not import files in later ones.
## TODO: Succinctly explain the other subfolders |
.lake/packages/mathlib/Mathlib/Algebra/PEmptyInstances.lean | import Mathlib.Algebra.Group.Defs
/-!
# Instances on pempty
This file collects facts about algebraic structures on the (universe-polymorphic) empty type, e.g.
that it is a semigroup.
-/
universe u
@[to_additive]
instance SemigroupPEmpty : Semigroup PEmpty.{u + 1} where
mul x _ := by cases x
mul_assoc x y z := by cases x |
.lake/packages/mathlib/Mathlib/Algebra/Notation.lean | import Mathlib.Tactic.TypeStar
import Mathlib.Tactic.ToAdditive
/-!
# Notations for operations involving order and algebraic structure
## Notation
* `a⁺ᵐ = a ⊔ 1`: *Positive component* of an element `a` of a multiplicative lattice ordered group
* `a⁻ᵐ = a⁻¹ ⊔ 1`: *Negative component* of an element `a` of a multiplicative lattice ordered group
* `a⁺ = a ⊔ 0`: *Positive component* of an element `a` of a lattice ordered group
* `a⁻ = (-a) ⊔ 0`: *Negative component* of an element `a` of a lattice ordered group
-/
/-- A notation class for the *positive part* function: `a⁺`. -/
class PosPart (α : Type*) where
/-- The *positive part* of an element `a`. -/
posPart : α → α
/-- A notation class for the *positive part* function (multiplicative version): `a⁺ᵐ`. -/
@[to_additive]
class OneLePart (α : Type*) where
/-- The *positive part* of an element `a`. -/
oneLePart : α → α
/-- A notation class for the *negative part* function: `a⁻`. -/
class NegPart (α : Type*) where
/-- The *negative part* of an element `a`. -/
negPart : α → α
/-- A notation class for the *negative part* function (multiplicative version): `a⁻ᵐ`. -/
@[to_additive]
class LeOnePart (α : Type*) where
/-- The *negative part* of an element `a`. -/
leOnePart : α → α
export OneLePart (oneLePart)
export LeOnePart (leOnePart)
export PosPart (posPart)
export NegPart (negPart)
@[inherit_doc] postfix:max "⁺ᵐ" => OneLePart.oneLePart
@[inherit_doc] postfix:max "⁻ᵐ" => LeOnePart.leOnePart
@[inherit_doc] postfix:max "⁺" => PosPart.posPart
@[inherit_doc] postfix:max "⁻" => NegPart.negPart |
.lake/packages/mathlib/Mathlib/Algebra/Symmetrized.lean | import Mathlib.Algebra.Jordan.Basic
import Mathlib.Algebra.Module.Defs
/-!
# Symmetrized algebra
A commutative multiplication on a real or complex space can be constructed from any multiplication
by "symmetrization" i.e.
$$
a \circ b = \frac{1}{2}(ab + ba)
$$
We provide the symmetrized version of a type `α` as `SymAlg α`, with notation `αˢʸᵐ`.
## Implementation notes
The approach taken here is inspired by `Mathlib/Algebra/Opposites.lean`. We use Oxford Spellings
(IETF en-GB-oxendict).
## Note
See `SymmetricAlgebra` instead if you are looking for the symmetric algebra of a module.
## References
* [Hanche-Olsen and Størmer, Jordan Operator Algebras][hancheolsenstormer1984]
-/
open Function
/-- The symmetrized algebra (denoted as `αˢʸᵐ`)
has the same underlying space as the original algebra `α`. -/
def SymAlg (α : Type*) : Type _ :=
α
@[inherit_doc] postfix:max "ˢʸᵐ" => SymAlg
namespace SymAlg
variable {α : Type*}
/-- The element of `SymAlg α` that represents `a : α`. -/
@[match_pattern]
def sym : α ≃ αˢʸᵐ :=
Equiv.refl _
/-- The element of `α` represented by `x : αˢʸᵐ`. -/
-- We add `@[pp_nodot]` in case RFC https://github.com/leanprover/lean4/issues/6178 happens.
@[pp_nodot]
def unsym : αˢʸᵐ ≃ α :=
Equiv.refl _
@[simp]
theorem unsym_sym (a : α) : unsym (sym a) = a :=
rfl
@[simp]
theorem sym_unsym (a : α) : sym (unsym a) = a :=
rfl
@[simp]
theorem sym_comp_unsym : (sym : α → αˢʸᵐ) ∘ unsym = id :=
rfl
@[simp]
theorem unsym_comp_sym : (unsym : αˢʸᵐ → α) ∘ sym = id :=
rfl
@[simp]
theorem sym_symm : (@sym α).symm = unsym :=
rfl
@[simp]
theorem unsym_symm : (@unsym α).symm = sym :=
rfl
theorem sym_bijective : Bijective (sym : α → αˢʸᵐ) :=
sym.bijective
theorem unsym_bijective : Bijective (unsym : αˢʸᵐ → α) :=
unsym.symm.bijective
theorem sym_injective : Injective (sym : α → αˢʸᵐ) :=
sym.injective
theorem sym_surjective : Surjective (sym : α → αˢʸᵐ) :=
sym.surjective
theorem unsym_injective : Injective (unsym : αˢʸᵐ → α) :=
unsym.injective
theorem unsym_surjective : Surjective (unsym : αˢʸᵐ → α) :=
unsym.surjective
theorem sym_inj {a b : α} : sym a = sym b ↔ a = b :=
sym_injective.eq_iff
theorem unsym_inj {a b : αˢʸᵐ} : unsym a = unsym b ↔ a = b :=
unsym_injective.eq_iff
instance [Nontrivial α] : Nontrivial αˢʸᵐ :=
sym_injective.nontrivial
instance [Inhabited α] : Inhabited αˢʸᵐ :=
⟨sym default⟩
instance [Subsingleton α] : Subsingleton αˢʸᵐ :=
unsym_injective.subsingleton
instance [Unique α] : Unique αˢʸᵐ :=
Unique.mk' _
instance [IsEmpty α] : IsEmpty αˢʸᵐ :=
Function.isEmpty unsym
@[to_additive]
instance [One α] : One αˢʸᵐ where one := sym 1
instance [Add α] : Add αˢʸᵐ where add a b := sym (unsym a + unsym b)
instance [Sub α] : Sub αˢʸᵐ where sub a b := sym (unsym a - unsym b)
instance [Neg α] : Neg αˢʸᵐ where neg a := sym (-unsym a)
-- Introduce the symmetrized multiplication
instance [Add α] [Mul α] [One α] [OfNat α 2] [Invertible (2 : α)] : Mul αˢʸᵐ where
mul a b := sym (⅟2 * (unsym a * unsym b + unsym b * unsym a))
@[to_additive existing]
instance [Inv α] : Inv αˢʸᵐ where inv a := sym <| (unsym a)⁻¹
instance (R : Type*) [SMul R α] : SMul R αˢʸᵐ where smul r a := sym (r • unsym a)
@[to_additive (attr := simp)]
theorem sym_one [One α] : sym (1 : α) = 1 :=
rfl
@[to_additive (attr := simp)]
theorem unsym_one [One α] : unsym (1 : αˢʸᵐ) = 1 :=
rfl
@[simp]
theorem sym_add [Add α] (a b : α) : sym (a + b) = sym a + sym b :=
rfl
@[simp]
theorem unsym_add [Add α] (a b : αˢʸᵐ) : unsym (a + b) = unsym a + unsym b :=
rfl
@[simp]
theorem sym_sub [Sub α] (a b : α) : sym (a - b) = sym a - sym b :=
rfl
@[simp]
theorem unsym_sub [Sub α] (a b : αˢʸᵐ) : unsym (a - b) = unsym a - unsym b :=
rfl
@[simp]
theorem sym_neg [Neg α] (a : α) : sym (-a) = -sym a :=
rfl
@[simp]
theorem unsym_neg [Neg α] (a : αˢʸᵐ) : unsym (-a) = -unsym a :=
rfl
theorem mul_def [Add α] [Mul α] [One α] [OfNat α 2] [Invertible (2 : α)] (a b : αˢʸᵐ) :
a * b = sym (⅟2 * (unsym a * unsym b + unsym b * unsym a)) := rfl
theorem unsym_mul [Mul α] [Add α] [One α] [OfNat α 2] [Invertible (2 : α)] (a b : αˢʸᵐ) :
unsym (a * b) = ⅟2 * (unsym a * unsym b + unsym b * unsym a) := rfl
theorem sym_mul_sym [Mul α] [Add α] [One α] [OfNat α 2] [Invertible (2 : α)] (a b : α) :
sym a * sym b = sym (⅟2 * (a * b + b * a)) :=
rfl
set_option linter.existingAttributeWarning false in
@[simp, to_additive existing]
theorem sym_inv [Inv α] (a : α) : sym a⁻¹ = (sym a)⁻¹ :=
rfl
set_option linter.existingAttributeWarning false in
@[simp, to_additive existing]
theorem unsym_inv [Inv α] (a : αˢʸᵐ) : unsym a⁻¹ = (unsym a)⁻¹ :=
rfl
@[simp]
theorem sym_smul {R : Type*} [SMul R α] (c : R) (a : α) : sym (c • a) = c • sym a :=
rfl
@[simp]
theorem unsym_smul {R : Type*} [SMul R α] (c : R) (a : αˢʸᵐ) : unsym (c • a) = c • unsym a :=
rfl
@[to_additive (attr := simp)]
theorem unsym_eq_one_iff [One α] (a : αˢʸᵐ) : unsym a = 1 ↔ a = 1 :=
unsym_injective.eq_iff' rfl
@[to_additive (attr := simp)]
theorem sym_eq_one_iff [One α] (a : α) : sym a = 1 ↔ a = 1 :=
sym_injective.eq_iff' rfl
@[to_additive]
theorem unsym_ne_one_iff [One α] (a : αˢʸᵐ) : unsym a ≠ (1 : α) ↔ a ≠ (1 : αˢʸᵐ) :=
not_congr <| unsym_eq_one_iff a
@[to_additive]
theorem sym_ne_one_iff [One α] (a : α) : sym a ≠ (1 : αˢʸᵐ) ↔ a ≠ (1 : α) :=
not_congr <| sym_eq_one_iff a
instance addCommSemigroup [AddCommSemigroup α] : AddCommSemigroup αˢʸᵐ :=
unsym_injective.addCommSemigroup _ unsym_add
instance addMonoid [AddMonoid α] : AddMonoid αˢʸᵐ :=
unsym_injective.addMonoid _ unsym_zero unsym_add fun _ _ => rfl
instance addGroup [AddGroup α] : AddGroup αˢʸᵐ :=
unsym_injective.addGroup _ unsym_zero unsym_add unsym_neg unsym_sub (fun _ _ => rfl) fun _ _ =>
rfl
instance addCommMonoid [AddCommMonoid α] : AddCommMonoid αˢʸᵐ :=
{ SymAlg.addCommSemigroup, SymAlg.addMonoid with }
instance addCommGroup [AddCommGroup α] : AddCommGroup αˢʸᵐ :=
{ SymAlg.addCommMonoid, SymAlg.addGroup with }
instance {R : Type*} [Semiring R] [AddCommMonoid α] [Module R α] : Module R αˢʸᵐ :=
Function.Injective.module R ⟨⟨unsym, unsym_zero⟩, unsym_add⟩ unsym_injective unsym_smul
instance [Mul α] [AddMonoidWithOne α] [Invertible (2 : α)] (a : α) [Invertible a] :
Invertible (sym a) where
invOf := sym (⅟a)
invOf_mul_self := by
rw [sym_mul_sym, mul_invOf_self, invOf_mul_self, one_add_one_eq_two, invOf_mul_self, sym_one]
mul_invOf_self := by
rw [sym_mul_sym, mul_invOf_self, invOf_mul_self, one_add_one_eq_two, invOf_mul_self, sym_one]
@[simp]
theorem invOf_sym [Mul α] [AddMonoidWithOne α] [Invertible (2 : α)] (a : α) [Invertible a] :
⅟(sym a) = sym (⅟a) :=
rfl
instance nonAssocSemiring [Semiring α] [Invertible (2 : α)] : NonAssocSemiring αˢʸᵐ :=
{ SymAlg.addCommMonoid with
zero_mul := fun _ => by
rw [mul_def, unsym_zero, zero_mul, mul_zero, add_zero,
mul_zero, sym_zero]
mul_zero := fun _ => by
rw [mul_def, unsym_zero, zero_mul, mul_zero, add_zero,
mul_zero, sym_zero]
mul_one := fun _ => by
rw [mul_def, unsym_one, mul_one, one_mul, ← two_mul, invOf_mul_cancel_left, sym_unsym]
one_mul := fun _ => by
rw [mul_def, unsym_one, mul_one, one_mul, ← two_mul, invOf_mul_cancel_left, sym_unsym]
left_distrib := fun a b c => by
rw [mul_def, mul_def, mul_def, ← sym_add, ← mul_add, unsym_add, add_mul]
congr 2
rw [mul_add]
abel
right_distrib := fun a b c => by
rw [mul_def, mul_def, mul_def, ← sym_add, ← mul_add, unsym_add, add_mul]
congr 2
rw [mul_add]
abel }
/-- The symmetrization of a real (unital, associative) algebra is a non-associative ring. -/
instance [Ring α] [Invertible (2 : α)] : NonAssocRing αˢʸᵐ :=
{ SymAlg.nonAssocSemiring, SymAlg.addCommGroup with }
/-! The squaring operation coincides for both multiplications -/
theorem unsym_mul_self [Semiring α] [Invertible (2 : α)] (a : αˢʸᵐ) :
unsym (a * a) = unsym a * unsym a := by
rw [mul_def, unsym_sym, ← two_mul, invOf_mul_cancel_left]
theorem sym_mul_self [Semiring α] [Invertible (2 : α)] (a : α) : sym (a * a) = sym a * sym a := by
rw [sym_mul_sym, ← two_mul, invOf_mul_cancel_left]
theorem mul_comm [Mul α] [AddCommSemigroup α] [One α] [OfNat α 2] [Invertible (2 : α)]
(a b : αˢʸᵐ) :
a * b = b * a := by rw [mul_def, mul_def, add_comm]
instance [Ring α] [Invertible (2 : α)] : CommMagma αˢʸᵐ where
mul_comm := SymAlg.mul_comm
instance [Ring α] [Invertible (2 : α)] : IsCommJordan αˢʸᵐ where
lmul_comm_rmul_rmul a b := by
have commute_half_left := fun a : α => by
have := (Commute.one_left a).add_left (Commute.one_left a)
rw [one_add_one_eq_two] at this
exact this.invOf_left.eq
calc a * b * (a * a)
_ = sym (⅟2 * ⅟2 * (unsym a * unsym b * unsym (a * a) +
unsym b * unsym a * unsym (a * a) +
unsym (a * a) * unsym a * unsym b +
unsym (a * a) * unsym b * unsym a)) := ?_
_ = sym (⅟2 * (unsym a *
unsym (sym (⅟2 * (unsym b * unsym (a * a) + unsym (a * a) * unsym b))) +
unsym (sym (⅟2 * (unsym b * unsym (a * a) + unsym (a * a) * unsym b))) * unsym a)) := ?_
_ = a * (b * (a * a)) := ?_
-- Rearrange LHS
· rw [mul_def, mul_def a b, unsym_sym, ← mul_assoc, ← commute_half_left (unsym (a * a)),
mul_assoc, mul_assoc, ← mul_add, ← mul_assoc, add_mul, mul_add (unsym (a * a)),
← add_assoc, ← mul_assoc, ← mul_assoc]
· rw [unsym_sym, sym_inj, ← mul_assoc, ← commute_half_left (unsym a), mul_assoc (⅟2) (unsym a),
mul_assoc (⅟2) _ (unsym a), ← mul_add, ← mul_assoc]
conv_rhs => rw [mul_add (unsym a)]
rw [add_mul, ← add_assoc, ← mul_assoc, ← mul_assoc]
rw [unsym_mul_self]
rw [← mul_assoc, ← mul_assoc, ← mul_assoc, ← mul_assoc, ← sub_eq_zero, ← mul_sub]
convert mul_zero (⅟(2 : α) * ⅟(2 : α))
rw [add_sub_add_right_eq_sub, add_assoc, add_assoc, add_sub_add_left_eq_sub, add_comm,
add_sub_add_right_eq_sub, sub_eq_zero]
-- Rearrange RHS
· rw [← mul_def, ← mul_def]
end SymAlg |
.lake/packages/mathlib/Mathlib/Algebra/Quaternion.lean | import Mathlib.Algebra.Star.SelfAdjoint
import Mathlib.LinearAlgebra.Dimension.StrongRankCondition
import Mathlib.LinearAlgebra.FreeModule.Finite.Basic
/-!
# Quaternions
In this file we define quaternions `ℍ[R]` over a commutative ring `R`, and define some
algebraic structures on `ℍ[R]`.
## Main definitions
* `QuaternionAlgebra R a b c`, `ℍ[R, a, b, c]` :
[Bourbaki, *Algebra I*][bourbaki1989] with coefficients `a`, `b`, `c`
(Many other references such as Wikipedia assume $\operatorname{char} R ≠ 2$ therefore one can
complete the square and WLOG assume $b = 0$.)
* `Quaternion R`, `ℍ[R]` : the space of quaternions, a.k.a.
`QuaternionAlgebra R (-1) (0) (-1)`;
* `Quaternion.normSq` : square of the norm of a quaternion;
We also define the following algebraic structures on `ℍ[R]`:
* `Ring ℍ[R, a, b, c]`, `StarRing ℍ[R, a, b, c]`, and `Algebra R ℍ[R, a, b, c]` :
for any commutative ring `R`;
* `Ring ℍ[R]`, `StarRing ℍ[R]`, and `Algebra R ℍ[R]` : for any commutative ring `R`;
* `IsDomain ℍ[R]` : for a linear ordered commutative ring `R`;
* `DivisionRing ℍ[R]` : for a linear ordered field `R`.
## Notation
The following notation is available with `open Quaternion` or `open scoped Quaternion`.
* `ℍ[R,c₁,c₂,c₃]` : `QuaternionAlgebra R c₁ c₂ c₃`
* `ℍ[R,c₁,c₂]` : `QuaternionAlgebra R c₁ 0 c₂`
* `ℍ[R]` : quaternions over `R`.
## Implementation notes
We define quaternions over any ring `R`, not just `ℝ` to be able to deal with, e.g., integer
or rational quaternions without using real numbers. In particular, all definitions in this file
are computable.
## Tags
quaternion
-/
open Module
/-- Quaternion algebra over a type with fixed coefficients where $i^2 = a + bi$ and $j^2 = c$,
denoted as `ℍ[R,a,b]`.
Implemented as a structure with four fields: `re`, `imI`, `imJ`, and `imK`. -/
@[ext]
structure QuaternionAlgebra (R : Type*) (a b c : R) where
/-- Real part of a quaternion. -/
re : R
/-- First imaginary part (i) of a quaternion. -/
imI : R
/-- Second imaginary part (j) of a quaternion. -/
imJ : R
/-- Third imaginary part (k) of a quaternion. -/
imK : R
initialize_simps_projections QuaternionAlgebra
(as_prefix re, as_prefix imI, as_prefix imJ, as_prefix imK)
@[inherit_doc]
scoped[Quaternion] notation "ℍ[" R "," a "," b "," c "]" =>
QuaternionAlgebra R a b c
@[inherit_doc]
scoped[Quaternion] notation "ℍ[" R "," a "," b "]" => QuaternionAlgebra R a 0 b
namespace QuaternionAlgebra
open Quaternion
/-- The equivalence between a quaternion algebra over `R` and `R × R × R × R`. -/
@[simps]
def equivProd {R : Type*} (c₁ c₂ c₃ : R) : ℍ[R,c₁,c₂,c₃] ≃ R × R × R × R where
toFun a := ⟨a.1, a.2, a.3, a.4⟩
invFun a := ⟨a.1, a.2.1, a.2.2.1, a.2.2.2⟩
/-- The equivalence between a quaternion algebra over `R` and `Fin 4 → R`. -/
@[simps symm_apply]
def equivTuple {R : Type*} (c₁ c₂ c₃ : R) : ℍ[R,c₁,c₂,c₃] ≃ (Fin 4 → R) where
toFun a := ![a.1, a.2, a.3, a.4]
invFun a := ⟨a 0, a 1, a 2, a 3⟩
right_inv _ := by ext ⟨_, _ | _ | _ | _ | _ | ⟨⟩⟩ <;> rfl
@[simp]
theorem equivTuple_apply {R : Type*} (c₁ c₂ c₃ : R) (x : ℍ[R,c₁,c₂,c₃]) :
equivTuple c₁ c₂ c₃ x = ![x.re, x.imI, x.imJ, x.imK] :=
rfl
@[simp]
theorem mk.eta {R : Type*} {c₁ c₂ c₃} (a : ℍ[R,c₁,c₂,c₃]) : mk a.1 a.2 a.3 a.4 = a := rfl
variable {S T R : Type*} {c₁ c₂ c₃ : R} (r x y : R) (a b : ℍ[R,c₁,c₂,c₃])
instance [Subsingleton R] : Subsingleton ℍ[R,c₁,c₂,c₃] := (equivTuple c₁ c₂ c₃).subsingleton
instance [Nontrivial R] : Nontrivial ℍ[R,c₁,c₂,c₃] := (equivTuple c₁ c₂ c₃).surjective.nontrivial
section Zero
variable [Zero R]
/-- The imaginary part of a quaternion.
Note that unless `c₂ = 0`, this definition is not particularly well-behaved;
for instance, `QuaternionAlgebra.star_im` only says that the star of an imaginary quaternion
is imaginary under this condition. -/
def im (x : ℍ[R,c₁,c₂,c₃]) : ℍ[R,c₁,c₂,c₃] :=
⟨0, x.imI, x.imJ, x.imK⟩
@[simp]
theorem re_im : a.im.re = 0 :=
rfl
@[deprecated (since := "2025-08-31")] alias im_re := re_im
@[simp]
theorem imI_im : a.im.imI = a.imI :=
rfl
@[deprecated (since := "2025-08-31")] alias im_imI := imI_im
@[simp]
theorem imJ_im : a.im.imJ = a.imJ :=
rfl
@[deprecated (since := "2025-08-31")] alias im_imJ := imJ_im
@[simp]
theorem imK_im : a.im.imK = a.imK :=
rfl
@[deprecated (since := "2025-08-31")] alias im_imK := imK_im
@[simp]
theorem im_idem : a.im.im = a.im :=
rfl
/-- Coercion `R → ℍ[R,c₁,c₂,c₃]`. -/
@[coe] def coe (x : R) : ℍ[R,c₁,c₂,c₃] := ⟨x, 0, 0, 0⟩
instance : CoeTC R ℍ[R,c₁,c₂,c₃] := ⟨coe⟩
@[simp, norm_cast]
theorem re_coe : (x : ℍ[R,c₁,c₂,c₃]).re = x := rfl
@[deprecated (since := "2025-08-31")] alias coe_re := re_coe
@[simp, norm_cast]
theorem imI_coe : (x : ℍ[R,c₁,c₂,c₃]).imI = 0 := rfl
@[deprecated (since := "2025-08-31")] alias coe_imI := imI_coe
@[simp, norm_cast]
theorem imJ_coe : (x : ℍ[R,c₁,c₂,c₃]).imJ = 0 := rfl
@[deprecated (since := "2025-08-31")] alias coe_imJ := imJ_coe
@[simp, norm_cast]
theorem imK_coe : (x : ℍ[R,c₁,c₂,c₃]).imK = 0 := rfl
@[deprecated (since := "2025-08-31")] alias coe_imK := imK_coe
theorem coe_injective : Function.Injective (coe : R → ℍ[R,c₁,c₂,c₃]) := fun _ _ h => congr_arg re h
@[simp]
theorem coe_inj {x y : R} : (x : ℍ[R,c₁,c₂,c₃]) = y ↔ x = y :=
coe_injective.eq_iff
@[simps]
instance : Zero ℍ[R,c₁,c₂,c₃] := ⟨⟨0, 0, 0, 0⟩⟩
@[scoped simp] theorem im_zero : (0 : ℍ[R,c₁,c₂,c₃]).im = 0 := rfl
@[deprecated (since := "2025-08-31")] alias zero_im := im_zero
@[simp, norm_cast]
theorem coe_zero : ((0 : R) : ℍ[R,c₁,c₂,c₃]) = 0 := rfl
instance : Inhabited ℍ[R,c₁,c₂,c₃] := ⟨0⟩
section One
variable [One R]
@[simps]
instance : One ℍ[R,c₁,c₂,c₃] := ⟨⟨1, 0, 0, 0⟩⟩
@[scoped simp] theorem im_one : (1 : ℍ[R,c₁,c₂,c₃]).im = 0 := rfl
@[deprecated (since := "2025-08-31")] alias one_im := im_one
@[simp, norm_cast]
theorem coe_one : ((1 : R) : ℍ[R,c₁,c₂,c₃]) = 1 := rfl
end One
end Zero
section Add
variable [Add R]
@[simps]
instance : Add ℍ[R,c₁,c₂,c₃] :=
⟨fun a b => ⟨a.1 + b.1, a.2 + b.2, a.3 + b.3, a.4 + b.4⟩⟩
@[simp]
theorem mk_add_mk (a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : R) :
(mk a₁ a₂ a₃ a₄ : ℍ[R,c₁,c₂,c₃]) + mk b₁ b₂ b₃ b₄ =
mk (a₁ + b₁) (a₂ + b₂) (a₃ + b₃) (a₄ + b₄) :=
rfl
end Add
section AddZeroClass
variable [AddZeroClass R]
@[simp] theorem im_add : (a + b).im = a.im + b.im :=
QuaternionAlgebra.ext (zero_add _).symm rfl rfl rfl
@[deprecated (since := "2025-08-31")] alias add_im := im_add
@[simp, norm_cast]
theorem coe_add : ((x + y : R) : ℍ[R,c₁,c₂,c₃]) = x + y := by ext <;> simp
end AddZeroClass
section Neg
variable [Neg R]
@[simps]
instance : Neg ℍ[R,c₁,c₂,c₃] := ⟨fun a => ⟨-a.1, -a.2, -a.3, -a.4⟩⟩
@[simp]
theorem neg_mk (a₁ a₂ a₃ a₄ : R) : -(mk a₁ a₂ a₃ a₄ : ℍ[R,c₁,c₂,c₃]) = ⟨-a₁, -a₂, -a₃, -a₄⟩ :=
rfl
end Neg
section AddGroup
variable [AddGroup R]
@[simp] theorem im_neg : (-a).im = -a.im :=
QuaternionAlgebra.ext neg_zero.symm rfl rfl rfl
@[deprecated (since := "2025-08-31")] alias neg_im := im_neg
@[simp, norm_cast]
theorem coe_neg : ((-x : R) : ℍ[R,c₁,c₂,c₃]) = -x := by ext <;> simp
@[simps]
instance : Sub ℍ[R,c₁,c₂,c₃] :=
⟨fun a b => ⟨a.1 - b.1, a.2 - b.2, a.3 - b.3, a.4 - b.4⟩⟩
@[simp] theorem im_sub : (a - b).im = a.im - b.im :=
QuaternionAlgebra.ext (sub_zero _).symm rfl rfl rfl
@[deprecated (since := "2025-08-31")] alias sub_im := im_sub
@[simp]
theorem mk_sub_mk (a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : R) :
(mk a₁ a₂ a₃ a₄ : ℍ[R,c₁,c₂,c₃]) - mk b₁ b₂ b₃ b₄ =
mk (a₁ - b₁) (a₂ - b₂) (a₃ - b₃) (a₄ - b₄) :=
rfl
@[simp, norm_cast]
theorem im_coe : (x : ℍ[R,c₁,c₂,c₃]).im = 0 :=
rfl
@[deprecated (since := "2025-08-31")] alias coe_im := im_coe
@[simp]
theorem re_add_im : ↑a.re + a.im = a :=
QuaternionAlgebra.ext (add_zero _) (zero_add _) (zero_add _) (zero_add _)
@[simp]
theorem sub_im_self : a - a.im = a.re :=
QuaternionAlgebra.ext (sub_zero _) (sub_self _) (sub_self _) (sub_self _)
@[deprecated (since := "2025-08-31")] alias sub_self_im := sub_im_self
@[simp]
theorem sub_re_self : a - a.re = a.im :=
QuaternionAlgebra.ext (sub_self _) (sub_zero _) (sub_zero _) (sub_zero _)
@[deprecated (since := "2025-08-31")] alias sub_self_re := sub_re_self
end AddGroup
section Ring
variable [Ring R]
/-- Multiplication is given by
* `1 * x = x * 1 = x`;
* `i * i = c₁ + c₂ * i`;
* `j * j = c₃`;
* `i * j = k`, `j * i = c₂ * j - k`;
* `k * k = - c₁ * c₃`;
* `i * k = c₁ * j + c₂ * k`, `k * i = -c₁ * j`;
* `j * k = c₂ * c₃ - c₃ * i`, `k * j = c₃ * i`. -/
@[simps]
instance : Mul ℍ[R,c₁,c₂,c₃] :=
⟨fun a b =>
⟨a.1 * b.1 + c₁ * a.2 * b.2 + c₃ * a.3 * b.3 + c₂ * c₃ * a.3 * b.4 - c₁ * c₃ * a.4 * b.4,
a.1 * b.2 + a.2 * b.1 + c₂ * a.2 * b.2 - c₃ * a.3 * b.4 + c₃ * a.4 * b.3,
a.1 * b.3 + c₁ * a.2 * b.4 + a.3 * b.1 + c₂ * a.3 * b.2 - c₁ * a.4 * b.2,
a.1 * b.4 + a.2 * b.3 + c₂ * a.2 * b.4 - a.3 * b.2 + a.4 * b.1⟩⟩
@[simp]
theorem mk_mul_mk (a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : R) :
(mk a₁ a₂ a₃ a₄ : ℍ[R,c₁,c₂,c₃]) * mk b₁ b₂ b₃ b₄ =
mk
(a₁ * b₁ + c₁ * a₂ * b₂ + c₃ * a₃ * b₃ + c₂ * c₃ * a₃ * b₄ - c₁ * c₃ * a₄ * b₄)
(a₁ * b₂ + a₂ * b₁ + c₂ * a₂ * b₂ - c₃ * a₃ * b₄ + c₃ * a₄ * b₃)
(a₁ * b₃ + c₁ * a₂ * b₄ + a₃ * b₁ + c₂ * a₃ * b₂ - c₁ * a₄ * b₂)
(a₁ * b₄ + a₂ * b₃ + c₂ * a₂ * b₄ - a₃ * b₂ + a₄ * b₁) :=
rfl
end Ring
section SMul
variable [SMul S R] [SMul T R] (s : S)
@[simps]
instance : SMul S ℍ[R,c₁,c₂,c₃] where smul s a := ⟨s • a.1, s • a.2, s • a.3, s • a.4⟩
instance [SMul S T] [IsScalarTower S T R] : IsScalarTower S T ℍ[R,c₁,c₂,c₃] where
smul_assoc s t x := by ext <;> exact smul_assoc _ _ _
instance [SMulCommClass S T R] : SMulCommClass S T ℍ[R,c₁,c₂,c₃] where
smul_comm s t x := by ext <;> exact smul_comm _ _ _
@[simp] theorem im_smul {S} [CommRing R] [SMulZeroClass S R] (s : S) : (s • a).im = s • a.im :=
QuaternionAlgebra.ext (smul_zero s).symm rfl rfl rfl
@[deprecated (since := "2025-08-31")] alias smul_im := im_smul
@[simp]
theorem smul_mk (re im_i im_j im_k : R) :
s • (⟨re, im_i, im_j, im_k⟩ : ℍ[R,c₁,c₂,c₃]) = ⟨s • re, s • im_i, s • im_j, s • im_k⟩ :=
rfl
end SMul
@[simp, norm_cast]
theorem coe_smul [Zero R] [SMulZeroClass S R] (s : S) (r : R) :
(↑(s • r) : ℍ[R,c₁,c₂,c₃]) = s • (r : ℍ[R,c₁,c₂,c₃]) :=
QuaternionAlgebra.ext rfl (smul_zero _).symm (smul_zero _).symm (smul_zero _).symm
instance [AddCommGroup R] : AddCommGroup ℍ[R,c₁,c₂,c₃] :=
(equivProd c₁ c₂ c₃).injective.addCommGroup _ rfl (fun _ _ ↦ rfl) (fun _ ↦ rfl) (fun _ _ ↦ rfl)
(fun _ _ ↦ rfl) (fun _ _ ↦ rfl)
section AddCommGroupWithOne
variable [AddCommGroupWithOne R]
instance : AddCommGroupWithOne ℍ[R,c₁,c₂,c₃] where
natCast n := ((n : R) : ℍ[R,c₁,c₂,c₃])
natCast_zero := by simp
natCast_succ := by simp
intCast n := ((n : R) : ℍ[R,c₁,c₂,c₃])
intCast_ofNat _ := congr_arg coe (Int.cast_natCast _)
intCast_negSucc n := by
change coe _ = -coe _
rw [Int.cast_negSucc, coe_neg]
@[simp, norm_cast]
theorem re_natCast (n : ℕ) : (n : ℍ[R,c₁,c₂,c₃]).re = n :=
rfl
@[deprecated (since := "2025-08-31")] alias natCast_re := re_natCast
@[simp, norm_cast]
theorem imI_natCast (n : ℕ) : (n : ℍ[R,c₁,c₂,c₃]).imI = 0 :=
rfl
@[deprecated (since := "2025-08-31")] alias natCast_imI := imI_natCast
@[simp, norm_cast]
theorem imJ_natCast (n : ℕ) : (n : ℍ[R,c₁,c₂,c₃]).imJ = 0 :=
rfl
@[deprecated (since := "2025-08-31")] alias natCast_imJ := imJ_natCast
@[simp, norm_cast]
theorem imK_natCast (n : ℕ) : (n : ℍ[R,c₁,c₂,c₃]).imK = 0 :=
rfl
@[deprecated (since := "2025-08-31")] alias natCast_imK := imK_natCast
@[simp, norm_cast]
theorem im_natCast (n : ℕ) : (n : ℍ[R,c₁,c₂,c₃]).im = 0 :=
rfl
@[deprecated (since := "2025-08-31")] alias natCast_im := im_natCast
@[norm_cast]
theorem coe_natCast (n : ℕ) : ↑(n : R) = (n : ℍ[R,c₁,c₂,c₃]) :=
rfl
@[simp, norm_cast]
theorem re_intCast (z : ℤ) : (z : ℍ[R,c₁,c₂,c₃]).re = z :=
rfl
@[deprecated (since := "2025-08-31")] alias intCast_re := re_intCast
@[scoped simp]
theorem re_ofNat (n : ℕ) [n.AtLeastTwo] : (ofNat(n) : ℍ[R,c₁,c₂,c₃]).re = ofNat(n) := rfl
@[deprecated (since := "2025-08-31")] alias ofNat_re := re_ofNat
@[scoped simp]
theorem imI_ofNat (n : ℕ) [n.AtLeastTwo] : (ofNat(n) : ℍ[R,c₁,c₂,c₃]).imI = 0 := rfl
@[deprecated (since := "2025-08-31")] alias ofNat_imI := imI_ofNat
@[scoped simp]
theorem imJ_ofNat (n : ℕ) [n.AtLeastTwo] : (ofNat(n) : ℍ[R,c₁,c₂,c₃]).imJ = 0 := rfl
@[deprecated (since := "2025-08-31")] alias ofNat_imJ := imJ_ofNat
@[scoped simp]
theorem imK_ofNat (n : ℕ) [n.AtLeastTwo] : (ofNat(n) : ℍ[R,c₁,c₂,c₃]).imK = 0 := rfl
@[deprecated (since := "2025-08-31")] alias ofNat_imK := imK_ofNat
@[scoped simp]
theorem im_ofNat (n : ℕ) [n.AtLeastTwo] : (ofNat(n) : ℍ[R,c₁,c₂,c₃]).im = 0 := rfl
@[deprecated (since := "2025-08-31")] alias ofNat_im := im_ofNat
@[simp, norm_cast]
theorem imI_intCast (z : ℤ) : (z : ℍ[R,c₁,c₂,c₃]).imI = 0 :=
rfl
@[deprecated (since := "2025-08-31")] alias intCast_imI := imI_intCast
@[simp, norm_cast]
theorem imJ_intCast (z : ℤ) : (z : ℍ[R,c₁,c₂,c₃]).imJ = 0 :=
rfl
@[deprecated (since := "2025-08-31")] alias intCast_imJ := imJ_intCast
@[simp, norm_cast]
theorem imK_intCast (z : ℤ) : (z : ℍ[R,c₁,c₂,c₃]).imK = 0 :=
rfl
@[deprecated (since := "2025-08-31")] alias intCast_imK := imK_intCast
@[simp, norm_cast]
theorem im_intCast (z : ℤ) : (z : ℍ[R,c₁,c₂,c₃]).im = 0 :=
rfl
@[deprecated (since := "2025-08-31")] alias intCast_im := im_intCast
@[norm_cast]
theorem coe_intCast (z : ℤ) : ↑(z : R) = (z : ℍ[R,c₁,c₂,c₃]) :=
rfl
end AddCommGroupWithOne
-- For the remainder of the file we assume `CommRing R`.
variable [CommRing R]
instance instRing : Ring ℍ[R,c₁,c₂,c₃] where
__ := inferInstanceAs (AddCommGroupWithOne ℍ[R,c₁,c₂,c₃])
left_distrib _ _ _ := by ext <;> simp <;> ring
right_distrib _ _ _ := by ext <;> simp <;> ring
zero_mul _ := by ext <;> simp
mul_zero _ := by ext <;> simp
mul_assoc _ _ _ := by ext <;> simp <;> ring
one_mul _ := by ext <;> simp
mul_one _ := by ext <;> simp
@[norm_cast, simp]
theorem coe_mul : ((x * y : R) : ℍ[R,c₁,c₂,c₃]) = x * y := by ext <;> simp
@[norm_cast, simp]
lemma coe_ofNat {n : ℕ} [n.AtLeastTwo] :
((ofNat(n) : R) : ℍ[R,c₁,c₂,c₃]) = (ofNat(n) : ℍ[R,c₁,c₂,c₃]) :=
rfl
-- TODO: add weaker `MulAction`, `DistribMulAction`, and `Module` instances (and repeat them
-- for `ℍ[R]`)
instance [CommSemiring S] [Algebra S R] : Algebra S ℍ[R,c₁,c₂,c₃] where
algebraMap :=
{ toFun s := coe (algebraMap S R s)
map_one' := by simp only [map_one, coe_one]
map_zero' := by simp only [map_zero, coe_zero]
map_mul' x y := by simp only [map_mul, coe_mul]
map_add' x y := by simp only [map_add, coe_add] }
smul_def' s x := by ext <;> simp [Algebra.smul_def]
commutes' s x := by ext <;> simp [Algebra.commutes]
theorem algebraMap_eq (r : R) : algebraMap R ℍ[R,c₁,c₂,c₃] r = ⟨r, 0, 0, 0⟩ :=
rfl
theorem algebraMap_injective : (algebraMap R ℍ[R,c₁,c₂,c₃] : _ → _).Injective :=
fun _ _ ↦ by simp [algebraMap_eq]
instance [NoZeroDivisors R] : NoZeroSMulDivisors R ℍ[R,c₁,c₂,c₃] := ⟨by
rintro t ⟨a, b, c, d⟩ h
rw [or_iff_not_imp_left]
intro ht
simpa [QuaternionAlgebra.ext_iff, ht] using h⟩
section
variable (c₁ c₂ c₃)
/-- `QuaternionAlgebra.re` as a `LinearMap` -/
@[simps]
def reₗ : ℍ[R,c₁,c₂,c₃] →ₗ[R] R where
toFun := re
map_add' _ _ := rfl
map_smul' _ _ := rfl
/-- `QuaternionAlgebra.imI` as a `LinearMap` -/
@[simps]
def imIₗ : ℍ[R,c₁,c₂,c₃] →ₗ[R] R where
toFun := imI
map_add' _ _ := rfl
map_smul' _ _ := rfl
/-- `QuaternionAlgebra.imJ` as a `LinearMap` -/
@[simps]
def imJₗ : ℍ[R,c₁,c₂,c₃] →ₗ[R] R where
toFun := imJ
map_add' _ _ := rfl
map_smul' _ _ := rfl
/-- `QuaternionAlgebra.imK` as a `LinearMap` -/
@[simps]
def imKₗ : ℍ[R,c₁,c₂,c₃] →ₗ[R] R where
toFun := imK
map_add' _ _ := rfl
map_smul' _ _ := rfl
/-- `QuaternionAlgebra.equivTuple` as a linear equivalence. -/
def linearEquivTuple : ℍ[R,c₁,c₂,c₃] ≃ₗ[R] Fin 4 → R :=
LinearEquiv.symm -- proofs are not `rfl` in the forward direction
{ (equivTuple c₁ c₂ c₃).symm with
toFun := (equivTuple c₁ c₂ c₃).symm
invFun := equivTuple c₁ c₂ c₃
map_add' := fun _ _ => rfl
map_smul' := fun _ _ => rfl }
@[simp]
theorem coe_linearEquivTuple :
⇑(linearEquivTuple c₁ c₂ c₃) = equivTuple c₁ c₂ c₃ := rfl
@[simp]
theorem coe_linearEquivTuple_symm :
⇑(linearEquivTuple c₁ c₂ c₃).symm = (equivTuple c₁ c₂ c₃).symm := rfl
/-- `ℍ[R,c₁,c₂,c₃]` has a basis over `R` given by `1`, `i`, `j`, and `k`. -/
noncomputable def basisOneIJK : Basis (Fin 4) R ℍ[R,c₁,c₂,c₃] :=
.ofEquivFun <| linearEquivTuple c₁ c₂ c₃
@[simp]
theorem coe_basisOneIJK_repr (q : ℍ[R,c₁,c₂,c₃]) :
((basisOneIJK c₁ c₂ c₃).repr q) = ![q.re, q.imI, q.imJ, q.imK] :=
rfl
instance : Module.Finite R ℍ[R,c₁,c₂,c₃] := .of_basis (basisOneIJK c₁ c₂ c₃)
instance : Module.Free R ℍ[R,c₁,c₂,c₃] := .of_basis (basisOneIJK c₁ c₂ c₃)
theorem rank_eq_four [StrongRankCondition R] : Module.rank R ℍ[R,c₁,c₂,c₃] = 4 := by
rw [rank_eq_card_basis (basisOneIJK c₁ c₂ c₃), Fintype.card_fin]
norm_num
theorem finrank_eq_four [StrongRankCondition R] : Module.finrank R ℍ[R,c₁,c₂,c₃] = 4 := by
rw [Module.finrank, rank_eq_four, Cardinal.toNat_ofNat]
/-- There is a natural equivalence when swapping the first and third coefficients of a
quaternion algebra if `c₂` is 0. -/
@[simps]
def swapEquiv : ℍ[R,c₁,0,c₃] ≃ₐ[R] ℍ[R,c₃,0,c₁] where
toFun t := ⟨t.1, t.3, t.2, -t.4⟩
invFun t := ⟨t.1, t.3, t.2, -t.4⟩
left_inv _ := by simp
right_inv _ := by simp
map_mul' _ _ := by ext <;> simp <;> ring
map_add' _ _ := by ext <;> simp [add_comm]
commutes' _ := by simp [algebraMap_eq]
end
@[norm_cast, simp]
theorem coe_sub : ((x - y : R) : ℍ[R,c₁,c₂,c₃]) = x - y :=
(algebraMap R ℍ[R,c₁,c₂,c₃]).map_sub x y
@[norm_cast, simp]
theorem coe_pow (n : ℕ) : (↑(x ^ n) : ℍ[R,c₁,c₂,c₃]) = (x : ℍ[R,c₁,c₂,c₃]) ^ n :=
(algebraMap R ℍ[R,c₁,c₂,c₃]).map_pow x n
theorem coe_commutes : ↑r * a = a * r :=
Algebra.commutes r a
theorem coe_commute : Commute (↑r) a :=
coe_commutes r a
theorem coe_mul_eq_smul : ↑r * a = r • a :=
(Algebra.smul_def r a).symm
theorem mul_coe_eq_smul : a * r = r • a := by rw [← coe_commutes, coe_mul_eq_smul]
@[norm_cast, simp]
theorem coe_algebraMap : ⇑(algebraMap R ℍ[R,c₁,c₂,c₃]) = coe :=
rfl
theorem smul_coe : x • (y : ℍ[R,c₁,c₂,c₃]) = ↑(x * y) := by rw [coe_mul, coe_mul_eq_smul]
/-- Quaternion conjugate. -/
instance instStarQuaternionAlgebra : Star ℍ[R,c₁,c₂,c₃] where star a :=
⟨a.1 + c₂ * a.2, -a.2, -a.3, -a.4⟩
@[simp] theorem re_star : (star a).re = a.re + c₂ * a.imI := rfl
@[simp]
theorem imI_star : (star a).imI = -a.imI :=
rfl
@[simp]
theorem imJ_star : (star a).imJ = -a.imJ :=
rfl
@[simp]
theorem imK_star : (star a).imK = -a.imK :=
rfl
@[simp]
theorem im_star : (star a).im = -a.im :=
QuaternionAlgebra.ext neg_zero.symm rfl rfl rfl
@[simp]
theorem star_mk (a₁ a₂ a₃ a₄ : R) : star (mk a₁ a₂ a₃ a₄ : ℍ[R,c₁,c₂,c₃]) =
⟨a₁ + c₂ * a₂, -a₂, -a₃, -a₄⟩ := rfl
instance instStarRing : StarRing ℍ[R,c₁,c₂,c₃] where
star_involutive x := by simp [Star.star]
star_add a b := by ext <;> simp [add_comm] ; ring
star_mul a b := by ext <;> simp <;> ring
theorem self_add_star' : a + star a = ↑(2 * a.re + c₂ * a.imI) := by ext <;> simp [two_mul]; ring
theorem self_add_star : a + star a = 2 * a.re + c₂ * a.imI := by simp [self_add_star']
theorem star_add_self' : star a + a = ↑(2 * a.re + c₂ * a.imI) := by rw [add_comm, self_add_star']
theorem star_add_self : star a + a = 2 * a.re + c₂ * a.imI := by rw [add_comm, self_add_star]
theorem star_eq_two_re_sub : star a = ↑(2 * a.re + c₂ * a.imI) - a :=
eq_sub_iff_add_eq.2 a.star_add_self'
lemma comm (r : R) (x : ℍ[R,c₁,c₂,c₃]) : r * x = x * r := by
ext <;> simp [mul_comm]
instance : IsStarNormal a :=
⟨by
rw [commute_iff_eq, a.star_eq_two_re_sub];
ext <;> simp <;> ring⟩
@[simp, norm_cast]
theorem star_coe : star (x : ℍ[R,c₁,c₂,c₃]) = x := by ext <;> simp
@[simp] theorem star_im : star a.im = -a.im + c₂ * a.imI := by ext <;> simp
@[simp]
theorem star_smul [Monoid S] [DistribMulAction S R] [SMulCommClass S R R]
(s : S) (a : ℍ[R,c₁,c₂,c₃]) :
star (s • a) = s • star a :=
QuaternionAlgebra.ext
(by simp [mul_smul_comm]) (smul_neg _ _).symm (smul_neg _ _).symm (smul_neg _ _).symm
/-- A version of `star_smul` for the special case when `c₂ = 0`, without `SMulCommClass S R R`. -/
theorem star_smul' [Monoid S] [DistribMulAction S R] (s : S) (a : ℍ[R,c₁,0,c₃]) :
star (s • a) = s • star a :=
QuaternionAlgebra.ext (by simp) (smul_neg _ _).symm (smul_neg _ _).symm (smul_neg _ _).symm
theorem eq_re_of_eq_coe {a : ℍ[R,c₁,c₂,c₃]} {x : R} (h : a = x) : a = a.re := by rw [h, re_coe]
theorem eq_re_iff_mem_range_coe {a : ℍ[R,c₁,c₂,c₃]} :
a = a.re ↔ a ∈ Set.range (coe : R → ℍ[R,c₁,c₂,c₃]) :=
⟨fun h => ⟨a.re, h.symm⟩, fun ⟨_, h⟩ => eq_re_of_eq_coe h.symm⟩
section CharZero
variable [NoZeroDivisors R] [CharZero R]
@[simp]
theorem star_eq_self {c₁ c₂ : R} {a : ℍ[R,c₁,c₂,c₃]} : star a = a ↔ a = a.re := by
simp_all [QuaternionAlgebra.ext_iff, neg_eq_iff_add_eq_zero, add_self_eq_zero]
theorem star_eq_neg {c₁ : R} {a : ℍ[R,c₁,0,c₃]} : star a = -a ↔ a.re = 0 := by
simp [QuaternionAlgebra.ext_iff, eq_neg_iff_add_eq_zero]
end CharZero
-- Can't use `rw ← star_eq_self` in the proof without additional assumptions
theorem star_mul_eq_coe : star a * a = (star a * a).re := by ext <;> simp <;> ring
theorem mul_star_eq_coe : a * star a = (a * star a).re := by
rw [← star_comm_self']
exact a.star_mul_eq_coe
open MulOpposite
/-- Quaternion conjugate as an `AlgEquiv` to the opposite ring. -/
def starAe : ℍ[R,c₁,c₂,c₃] ≃ₐ[R] ℍ[R,c₁,c₂,c₃]ᵐᵒᵖ :=
{ starAddEquiv.trans opAddEquiv with
toFun := op ∘ star
invFun := star ∘ unop
map_mul' := fun x y => by simp
commutes' := fun r => by simp }
@[simp]
theorem coe_starAe : ⇑(starAe : ℍ[R,c₁,c₂,c₃] ≃ₐ[R] _) = op ∘ star :=
rfl
end QuaternionAlgebra
/-- Space of quaternions over a type, denoted as `ℍ[R]`.
Implemented as a structure with four fields: `re`, `im_i`, `im_j`, and `im_k`. -/
def Quaternion (R : Type*) [Zero R] [One R] [Neg R] :=
QuaternionAlgebra R (-1) (0) (-1)
@[inherit_doc]
scoped[Quaternion] notation "ℍ[" R "]" => Quaternion R
open Quaternion
/-- The equivalence between the quaternions over `R` and `R × R × R × R`. -/
@[simps!]
def Quaternion.equivProd (R : Type*) [Zero R] [One R] [Neg R] : ℍ[R] ≃ R × R × R × R :=
QuaternionAlgebra.equivProd _ _ _
/-- The equivalence between the quaternions over `R` and `Fin 4 → R`. -/
@[simps! symm_apply]
def Quaternion.equivTuple (R : Type*) [Zero R] [One R] [Neg R] : ℍ[R] ≃ (Fin 4 → R) :=
QuaternionAlgebra.equivTuple _ _ _
@[simp]
theorem Quaternion.equivTuple_apply (R : Type*) [Zero R] [One R] [Neg R] (x : ℍ[R]) :
Quaternion.equivTuple R x = ![x.re, x.imI, x.imJ, x.imK] :=
rfl
instance {R : Type*} [Zero R] [One R] [Neg R] [Subsingleton R] : Subsingleton ℍ[R] :=
inferInstanceAs (Subsingleton <| ℍ[R,-1,0,-1])
instance {R : Type*} [Zero R] [One R] [Neg R] [Nontrivial R] : Nontrivial ℍ[R] :=
inferInstanceAs (Nontrivial <| ℍ[R,-1,0,-1])
namespace Quaternion
variable {S T R : Type*} [CommRing R] (r x y : R) (a b : ℍ[R])
/-- Coercion `R → ℍ[R]`. -/
@[coe] def coe : R → ℍ[R] := QuaternionAlgebra.coe
instance : CoeTC R ℍ[R] := ⟨coe⟩
instance instRing : Ring ℍ[R] := QuaternionAlgebra.instRing
instance : Inhabited ℍ[R] := inferInstanceAs <| Inhabited ℍ[R,-1,0,-1]
instance [SMul S R] : SMul S ℍ[R] := inferInstanceAs <| SMul S ℍ[R,-1,0,-1]
instance [SMul S T] [SMul S R] [SMul T R] [IsScalarTower S T R] : IsScalarTower S T ℍ[R] :=
inferInstanceAs <| IsScalarTower S T ℍ[R,-1,0,-1]
instance [SMul S R] [SMul T R] [SMulCommClass S T R] : SMulCommClass S T ℍ[R] :=
inferInstanceAs <| SMulCommClass S T ℍ[R,-1,0,-1]
protected instance algebra [CommSemiring S] [Algebra S R] : Algebra S ℍ[R] :=
inferInstanceAs <| Algebra S ℍ[R,-1,0,-1]
instance : Star ℍ[R] := QuaternionAlgebra.instStarQuaternionAlgebra
instance : StarRing ℍ[R] := QuaternionAlgebra.instStarRing
instance : IsStarNormal a := inferInstanceAs <| IsStarNormal (R := ℍ[R,-1,0,-1]) a
@[ext]
theorem ext : a.re = b.re → a.imI = b.imI → a.imJ = b.imJ → a.imK = b.imK → a = b :=
QuaternionAlgebra.ext
/-- The imaginary part of a quaternion. -/
def im (x : ℍ[R]) : ℍ[R] := QuaternionAlgebra.im x
@[simp] theorem re_im : a.im.re = 0 := rfl
@[deprecated (since := "2025-08-31")] alias im_re := re_im
@[simp] theorem imI_im : a.im.imI = a.imI := rfl
@[deprecated (since := "2025-08-31")] alias im_imI := imI_im
@[simp] theorem imJ_im : a.im.imJ = a.imJ := rfl
@[deprecated (since := "2025-08-31")] alias im_imJ := imJ_im
@[simp] theorem imK_im : a.im.imK = a.imK := rfl
@[deprecated (since := "2025-08-31")] alias im_imK := imK_im
@[simp] theorem im_idem : a.im.im = a.im := rfl
@[simp] theorem re_add_im : ↑a.re + a.im = a := QuaternionAlgebra.re_add_im a
@[simp] theorem sub_im_self : a - a.im = a.re := QuaternionAlgebra.sub_im_self a
@[deprecated (since := "2025-08-31")] alias sub_self_im := sub_im_self
@[simp] theorem sub_re_self : a - ↑a.re = a.im := QuaternionAlgebra.sub_re_self a
@[deprecated (since := "2025-08-31")] alias sub_self_re := sub_re_self
@[simp, norm_cast]
theorem re_coe : (x : ℍ[R]).re = x := rfl
@[deprecated (since := "2025-08-31")] alias coe_re := re_coe
@[simp, norm_cast]
theorem imI_coe : (x : ℍ[R]).imI = 0 := rfl
@[deprecated (since := "2025-08-31")] alias coe_imI := imI_coe
@[simp, norm_cast]
theorem imJ_coe : (x : ℍ[R]).imJ = 0 := rfl
@[deprecated (since := "2025-08-31")] alias coe_imJ := imJ_coe
@[simp, norm_cast]
theorem imK_coe : (x : ℍ[R]).imK = 0 := rfl
@[deprecated (since := "2025-08-31")] alias coe_imK := imK_coe
@[simp, norm_cast]
theorem im_coe : (x : ℍ[R]).im = 0 := rfl
@[deprecated (since := "2025-08-31")] alias coe_im := im_coe
@[scoped simp] theorem re_zero : (0 : ℍ[R]).re = 0 := rfl
@[deprecated (since := "2025-08-31")] alias zero_re := re_zero
@[scoped simp] theorem imI_zero : (0 : ℍ[R]).imI = 0 := rfl
@[deprecated (since := "2025-08-31")] alias zero_imI := imI_zero
@[scoped simp] theorem imJ_zero : (0 : ℍ[R]).imJ = 0 := rfl
@[deprecated (since := "2025-08-31")] alias zero_imJ := imJ_zero
@[scoped simp] theorem imK_zero : (0 : ℍ[R]).imK = 0 := rfl
@[deprecated (since := "2025-08-31")] alias zero_imK := imK_zero
@[scoped simp] theorem im_zero : (0 : ℍ[R]).im = 0 := rfl
@[deprecated (since := "2025-08-31")] alias zero_im := im_zero
@[simp, norm_cast]
theorem coe_zero : ((0 : R) : ℍ[R]) = 0 := rfl
@[scoped simp] theorem re_one : (1 : ℍ[R]).re = 1 := rfl
@[deprecated (since := "2025-08-31")] alias one_re := re_one
@[scoped simp] theorem imI_one : (1 : ℍ[R]).imI = 0 := rfl
@[deprecated (since := "2025-08-31")] alias one_imI := imI_one
@[scoped simp] theorem imJ_one : (1 : ℍ[R]).imJ = 0 := rfl
@[deprecated (since := "2025-08-31")] alias one_imJ := imJ_one
@[scoped simp] theorem imK_one : (1 : ℍ[R]).imK = 0 := rfl
@[deprecated (since := "2025-08-31")] alias one_imK := imK_one
@[scoped simp] theorem im_one : (1 : ℍ[R]).im = 0 := rfl
@[deprecated (since := "2025-08-31")] alias one_im := im_one
@[simp, norm_cast]
theorem coe_one : ((1 : R) : ℍ[R]) = 1 := rfl
@[simp] theorem re_add : (a + b).re = a.re + b.re := rfl
@[deprecated (since := "2025-08-31")] alias add_re := re_add
@[simp] theorem imI_add : (a + b).imI = a.imI + b.imI := rfl
@[deprecated (since := "2025-08-31")] alias add_imI := imI_add
@[simp] theorem imJ_add : (a + b).imJ = a.imJ + b.imJ := rfl
@[deprecated (since := "2025-08-31")] alias add_imJ := imJ_add
@[simp] theorem imK_add : (a + b).imK = a.imK + b.imK := rfl
@[deprecated (since := "2025-08-31")] alias add_imK := imK_add
@[simp] theorem im_add : (a + b).im = a.im + b.im := QuaternionAlgebra.im_add a b
@[deprecated (since := "2025-08-31")] alias add_im := im_add
@[simp, norm_cast]
theorem coe_add : ((x + y : R) : ℍ[R]) = x + y :=
QuaternionAlgebra.coe_add x y
@[simp] theorem re_neg : (-a).re = -a.re := rfl
@[deprecated (since := "2025-08-31")] alias neg_re := re_neg
@[simp] theorem imI_neg : (-a).imI = -a.imI := rfl
@[deprecated (since := "2025-08-31")] alias neg_imI := imI_neg
@[simp] theorem imJ_neg : (-a).imJ = -a.imJ := rfl
@[deprecated (since := "2025-08-31")] alias neg_imJ := imJ_neg
@[simp] theorem imK_neg : (-a).imK = -a.imK := rfl
@[deprecated (since := "2025-08-31")] alias neg_imK := imK_neg
@[simp] theorem im_neg : (-a).im = -a.im := QuaternionAlgebra.im_neg a
@[deprecated (since := "2025-08-31")] alias neg_im := im_neg
@[simp, norm_cast]
theorem coe_neg : ((-x : R) : ℍ[R]) = -x :=
QuaternionAlgebra.coe_neg x
@[simp] theorem re_sub : (a - b).re = a.re - b.re := rfl
@[deprecated (since := "2025-08-31")] alias sub_re := re_sub
@[simp] theorem imI_sub : (a - b).imI = a.imI - b.imI := rfl
@[deprecated (since := "2025-08-31")] alias sub_imI := imI_sub
@[simp] theorem imJ_sub : (a - b).imJ = a.imJ - b.imJ := rfl
@[deprecated (since := "2025-08-31")] alias sub_imJ := imJ_sub
@[simp] theorem imK_sub : (a - b).imK = a.imK - b.imK := rfl
@[deprecated (since := "2025-08-31")] alias sub_imK := imK_sub
@[simp] theorem im_sub : (a - b).im = a.im - b.im := QuaternionAlgebra.im_sub a b
@[deprecated (since := "2025-08-31")] alias sub_im := im_sub
@[simp, norm_cast]
theorem coe_sub : ((x - y : R) : ℍ[R]) = x - y :=
QuaternionAlgebra.coe_sub x y
@[simp]
theorem re_mul : (a * b).re = a.re * b.re - a.imI * b.imI - a.imJ * b.imJ - a.imK * b.imK :=
(QuaternionAlgebra.re_mul a b).trans <| by simp [one_mul, neg_mul, sub_eq_add_neg, neg_neg]
@[deprecated (since := "2025-08-31")] alias mul_re := re_mul
@[simp]
theorem imI_mul : (a * b).imI = a.re * b.imI + a.imI * b.re + a.imJ * b.imK - a.imK * b.imJ :=
(QuaternionAlgebra.imI_mul a b).trans <| by ring
@[deprecated (since := "2025-08-31")] alias mul_imI := imI_mul
@[simp]
theorem imJ_mul : (a * b).imJ = a.re * b.imJ - a.imI * b.imK + a.imJ * b.re + a.imK * b.imI :=
(QuaternionAlgebra.imJ_mul a b).trans <| by ring
@[deprecated (since := "2025-08-31")] alias mul_imJ := imJ_mul
@[simp]
theorem imK_mul : (a * b).imK = a.re * b.imK + a.imI * b.imJ - a.imJ * b.imI + a.imK * b.re :=
(QuaternionAlgebra.imK_mul a b).trans <| by ring
@[deprecated (since := "2025-08-31")] alias mul_imK := imK_mul
@[simp, norm_cast]
theorem coe_mul : ((x * y : R) : ℍ[R]) = x * y := QuaternionAlgebra.coe_mul x y
@[norm_cast, simp]
theorem coe_pow (n : ℕ) : (↑(x ^ n) : ℍ[R]) = (x : ℍ[R]) ^ n :=
QuaternionAlgebra.coe_pow x n
@[simp, norm_cast]
theorem re_natCast (n : ℕ) : (n : ℍ[R]).re = n := rfl
@[deprecated (since := "2025-08-31")] alias natCast_re := re_natCast
@[simp, norm_cast]
theorem imI_natCast (n : ℕ) : (n : ℍ[R]).imI = 0 := rfl
@[deprecated (since := "2025-08-31")] alias natCast_imI := imI_natCast
@[simp, norm_cast]
theorem imJ_natCast (n : ℕ) : (n : ℍ[R]).imJ = 0 := rfl
@[deprecated (since := "2025-08-31")] alias natCast_imJ := imJ_natCast
@[simp, norm_cast]
theorem imK_natCast (n : ℕ) : (n : ℍ[R]).imK = 0 := rfl
@[deprecated (since := "2025-08-31")] alias natCast_imK := imK_natCast
@[simp, norm_cast]
theorem im_natCast (n : ℕ) : (n : ℍ[R]).im = 0 := rfl
@[deprecated (since := "2025-08-31")] alias natCast_im := im_natCast
@[norm_cast]
theorem coe_natCast (n : ℕ) : ↑(n : R) = (n : ℍ[R]) := rfl
@[simp, norm_cast]
theorem re_intCast (z : ℤ) : (z : ℍ[R]).re = z := rfl
@[deprecated (since := "2025-08-31")] alias intCast_re := re_intCast
@[simp, norm_cast]
theorem imI_intCast (z : ℤ) : (z : ℍ[R]).imI = 0 := rfl
@[deprecated (since := "2025-08-31")] alias intCast_imI := imI_intCast
@[simp, norm_cast]
theorem imJ_intCast (z : ℤ) : (z : ℍ[R]).imJ = 0 := rfl
@[deprecated (since := "2025-08-31")] alias intCast_imJ := imJ_intCast
@[simp, norm_cast]
theorem imK_intCast (z : ℤ) : (z : ℍ[R]).imK = 0 := rfl
@[deprecated (since := "2025-08-31")] alias intCast_imK := imK_intCast
@[simp, norm_cast]
theorem im_intCast (z : ℤ) : (z : ℍ[R]).im = 0 := rfl
@[deprecated (since := "2025-08-31")] alias intCast_im := im_intCast
@[norm_cast]
theorem coe_intCast (z : ℤ) : ↑(z : R) = (z : ℍ[R]) := rfl
theorem coe_injective : Function.Injective (coe : R → ℍ[R]) :=
QuaternionAlgebra.coe_injective
@[simp]
theorem coe_inj {x y : R} : (x : ℍ[R]) = y ↔ x = y :=
coe_injective.eq_iff
@[simp]
theorem re_smul [SMul S R] (s : S) : (s • a).re = s • a.re :=
rfl
@[deprecated (since := "2025-08-31")] alias smul_re := re_smul
@[simp] theorem imI_smul [SMul S R] (s : S) : (s • a).imI = s • a.imI := rfl
@[deprecated (since := "2025-08-31")] alias smul_imI := imI_smul
@[simp] theorem imJ_smul [SMul S R] (s : S) : (s • a).imJ = s • a.imJ := rfl
@[deprecated (since := "2025-08-31")] alias smul_imJ := imJ_smul
@[simp] theorem imK_smul [SMul S R] (s : S) : (s • a).imK = s • a.imK := rfl
@[deprecated (since := "2025-08-31")] alias smul_imK := imK_smul
@[simp]
theorem im_smul [SMulZeroClass S R] (s : S) : (s • a).im = s • a.im :=
QuaternionAlgebra.im_smul a s
@[deprecated (since := "2025-08-31")] alias smul_im := im_smul
@[simp, norm_cast]
theorem coe_smul [SMulZeroClass S R] (s : S) (r : R) : (↑(s • r) : ℍ[R]) = s • (r : ℍ[R]) :=
QuaternionAlgebra.coe_smul _ _
theorem coe_commutes : ↑r * a = a * r :=
QuaternionAlgebra.coe_commutes r a
theorem coe_commute : Commute (↑r) a :=
QuaternionAlgebra.coe_commute r a
theorem coe_mul_eq_smul : ↑r * a = r • a :=
QuaternionAlgebra.coe_mul_eq_smul r a
theorem mul_coe_eq_smul : a * r = r • a :=
QuaternionAlgebra.mul_coe_eq_smul r a
@[simp]
theorem algebraMap_def : ⇑(algebraMap R ℍ[R]) = coe :=
rfl
theorem algebraMap_injective : (algebraMap R ℍ[R] : _ → _).Injective :=
QuaternionAlgebra.algebraMap_injective
theorem smul_coe : x • (y : ℍ[R]) = ↑(x * y) :=
QuaternionAlgebra.smul_coe x y
instance : Module.Finite R ℍ[R] := inferInstanceAs <| Module.Finite R ℍ[R,-1,0,-1]
instance : Module.Free R ℍ[R] := inferInstanceAs <| Module.Free R ℍ[R,-1,0,-1]
theorem rank_eq_four [StrongRankCondition R] : Module.rank R ℍ[R] = 4 :=
QuaternionAlgebra.rank_eq_four _ _ _
theorem finrank_eq_four [StrongRankCondition R] : Module.finrank R ℍ[R] = 4 :=
QuaternionAlgebra.finrank_eq_four _ _ _
@[simp] theorem re_star : (star a).re = a.re := by
rw [QuaternionAlgebra.re_star, zero_mul, add_zero]
@[deprecated (since := "2025-08-31")] alias star_re := re_star
@[simp] theorem imI_star : (star a).imI = -a.imI := rfl
@[deprecated (since := "2025-08-31")] alias star_imI := imI_star
@[simp] theorem imJ_star : (star a).imJ = -a.imJ := rfl
@[deprecated (since := "2025-08-31")] alias star_imJ := imJ_star
@[simp] theorem imK_star : (star a).imK = -a.imK := rfl
@[deprecated (since := "2025-08-31")] alias star_imK := imK_star
@[simp] theorem im_star : (star a).im = -a.im := QuaternionAlgebra.im_star a
theorem self_add_star' : a + star a = ↑(2 * a.re) := by
simpa using QuaternionAlgebra.self_add_star' a
theorem self_add_star : a + star a = 2 * a.re := by
simpa using QuaternionAlgebra.self_add_star a
theorem star_add_self' : star a + a = ↑(2 * a.re) := by
simpa using QuaternionAlgebra.star_add_self' a
theorem star_add_self : star a + a = 2 * a.re := by
simpa using QuaternionAlgebra.star_add_self a
theorem star_eq_two_re_sub : star a = ↑(2 * a.re) - a := by
simpa using QuaternionAlgebra.star_eq_two_re_sub a
@[simp, norm_cast]
theorem star_coe : star (x : ℍ[R]) = x :=
QuaternionAlgebra.star_coe x
@[simp]
theorem star_im : star a.im = -a.im := by ext <;> simp
@[simp]
theorem star_smul [Monoid S] [DistribMulAction S R] (s : S) (a : ℍ[R]) :
star (s • a) = s • star a := QuaternionAlgebra.star_smul' s a
theorem eq_re_of_eq_coe {a : ℍ[R]} {x : R} (h : a = x) : a = a.re :=
QuaternionAlgebra.eq_re_of_eq_coe h
theorem eq_re_iff_mem_range_coe {a : ℍ[R]} : a = a.re ↔ a ∈ Set.range (coe : R → ℍ[R]) :=
QuaternionAlgebra.eq_re_iff_mem_range_coe
section CharZero
variable [NoZeroDivisors R] [CharZero R]
@[simp]
theorem star_eq_self {a : ℍ[R]} : star a = a ↔ a = a.re :=
QuaternionAlgebra.star_eq_self
@[simp]
theorem star_eq_neg {a : ℍ[R]} : star a = -a ↔ a.re = 0 :=
QuaternionAlgebra.star_eq_neg
end CharZero
theorem star_mul_eq_coe : star a * a = (star a * a).re :=
QuaternionAlgebra.star_mul_eq_coe a
theorem mul_star_eq_coe : a * star a = (a * star a).re :=
QuaternionAlgebra.mul_star_eq_coe a
open MulOpposite
/-- Quaternion conjugate as an `AlgEquiv` to the opposite ring. -/
def starAe : ℍ[R] ≃ₐ[R] ℍ[R]ᵐᵒᵖ :=
QuaternionAlgebra.starAe
@[simp]
theorem coe_starAe : ⇑(starAe : ℍ[R] ≃ₐ[R] ℍ[R]ᵐᵒᵖ) = op ∘ star :=
rfl
/-- Square of the norm. -/
def normSq : ℍ[R] →*₀ R where
toFun a := (a * star a).re
map_zero' := by simp only [star_zero, zero_mul, re_zero]
map_one' := by simp only [star_one, one_mul, re_one]
map_mul' x y := coe_injective <| by
conv_lhs => rw [← mul_star_eq_coe, star_mul, mul_assoc, ← mul_assoc y, y.mul_star_eq_coe,
coe_commutes, ← mul_assoc, x.mul_star_eq_coe, ← coe_mul]
theorem normSq_def : normSq a = (a * star a).re := rfl
theorem normSq_def' : normSq a = a.1 ^ 2 + a.2 ^ 2 + a.3 ^ 2 + a.4 ^ 2 := by
simp only [normSq_def, sq, mul_neg, sub_neg_eq_add, re_mul, re_star, imI_star, imJ_star,
imK_star]
theorem normSq_coe : normSq (x : ℍ[R]) = x ^ 2 := by
rw [normSq_def, star_coe, ← coe_mul, re_coe, sq]
@[simp]
theorem normSq_star : normSq (star a) = normSq a := by simp [normSq_def']
@[norm_cast]
theorem normSq_natCast (n : ℕ) : normSq (n : ℍ[R]) = (n : R) ^ 2 := by
rw [← coe_natCast, normSq_coe]
@[norm_cast]
theorem normSq_intCast (z : ℤ) : normSq (z : ℍ[R]) = (z : R) ^ 2 := by
rw [← coe_intCast, normSq_coe]
@[simp]
theorem normSq_neg : normSq (-a) = normSq a := by simp only [normSq_def, star_neg, neg_mul_neg]
theorem self_mul_star : a * star a = normSq a := by rw [mul_star_eq_coe, normSq_def]
theorem star_mul_self : star a * a = normSq a := by rw [star_comm_self, self_mul_star]
theorem im_sq : a.im ^ 2 = -normSq a.im := by
simp_rw [sq, ← star_mul_self, star_im, neg_mul, neg_neg]
theorem coe_normSq_add : normSq (a + b) = normSq a + a * star b + b * star a + normSq b := by
simp only [star_add, ← self_mul_star, mul_add, add_mul, add_assoc, add_left_comm]
theorem normSq_smul (r : R) (q : ℍ[R]) : normSq (r • q) = r ^ 2 * normSq q := by
simp only [normSq_def', re_smul, imI_smul, imJ_smul, imK_smul, mul_pow, mul_add, smul_eq_mul]
theorem normSq_add (a b : ℍ[R]) : normSq (a + b) = normSq a + normSq b + 2 * (a * star b).re :=
calc
normSq (a + b) = normSq a + (a * star b).re + ((b * star a).re + normSq b) := by
simp_rw [normSq_def, star_add, add_mul, mul_add, re_add]
_ = normSq a + normSq b + ((a * star b).re + (b * star a).re) := by abel
_ = normSq a + normSq b + 2 * (a * star b).re := by
rw [← re_add, ← star_mul_star a b, self_add_star', re_coe]
end Quaternion
namespace Quaternion
variable {R : Type*}
section LinearOrderedCommRing
variable [CommRing R] [LinearOrder R] [IsStrictOrderedRing R] {a : ℍ[R]}
@[simp]
theorem normSq_eq_zero : normSq a = 0 ↔ a = 0 := by
refine ⟨fun h => ?_, fun h => h.symm ▸ normSq.map_zero⟩
rw [normSq_def', add_eq_zero_iff_of_nonneg, add_eq_zero_iff_of_nonneg, add_eq_zero_iff_of_nonneg]
at h
· apply ext a 0 <;> apply eq_zero_of_pow_eq_zero
exacts [h.1.1.1, h.1.1.2, h.1.2, h.2]
all_goals apply_rules [sq_nonneg, add_nonneg]
theorem normSq_ne_zero : normSq a ≠ 0 ↔ a ≠ 0 := normSq_eq_zero.not
@[simp]
theorem normSq_nonneg : 0 ≤ normSq a := by
rw [normSq_def']
apply_rules [sq_nonneg, add_nonneg]
@[simp]
theorem normSq_le_zero : normSq a ≤ 0 ↔ a = 0 :=
normSq_nonneg.ge_iff_eq'.trans normSq_eq_zero
instance instNontrivial : Nontrivial ℍ[R] where
exists_pair_ne := ⟨0, 1, mt (congr_arg QuaternionAlgebra.re) zero_ne_one⟩
instance : NoZeroDivisors ℍ[R] where
eq_zero_or_eq_zero_of_mul_eq_zero {a b} hab :=
have : normSq a * normSq b = 0 := by rwa [← map_mul, normSq_eq_zero]
(eq_zero_or_eq_zero_of_mul_eq_zero this).imp normSq_eq_zero.1 normSq_eq_zero.1
instance : IsDomain ℍ[R] := NoZeroDivisors.to_isDomain _
theorem sq_eq_normSq : a ^ 2 = normSq a ↔ a = a.re := by
rw [← star_eq_self, ← star_mul_self, sq, mul_eq_mul_right_iff, eq_comm]
exact or_iff_left_of_imp fun ha ↦ ha.symm ▸ star_zero _
theorem sq_eq_neg_normSq : a ^ 2 = -normSq a ↔ a.re = 0 := by
simp_rw [← star_eq_neg]
obtain rfl | hq0 := eq_or_ne a 0
· simp
· rw [← star_mul_self, ← mul_neg, ← neg_sq, sq, mul_left_inj' (neg_ne_zero.mpr hq0), eq_comm]
end LinearOrderedCommRing
section Field
variable [Field R] (a b : ℍ[R])
instance instNNRatCast : NNRatCast ℍ[R] where nnratCast q := (q : R)
instance instRatCast : RatCast ℍ[R] where ratCast q := (q : R)
@[simp, norm_cast] lemma re_nnratCast (q : ℚ≥0) : (q : ℍ[R]).re = q := rfl
@[simp, norm_cast] lemma im_nnratCast (q : ℚ≥0) : (q : ℍ[R]).im = 0 := rfl
@[simp, norm_cast] lemma imI_nnratCast (q : ℚ≥0) : (q : ℍ[R]).imI = 0 := rfl
@[simp, norm_cast] lemma imJ_nnratCast (q : ℚ≥0) : (q : ℍ[R]).imJ = 0 := rfl
@[simp, norm_cast] lemma imK_nnratCast (q : ℚ≥0) : (q : ℍ[R]).imK = 0 := rfl
@[simp, norm_cast] lemma re_ratCast (q : ℚ) : (q : ℍ[R]).re = q := rfl
@[simp, norm_cast] lemma im_ratCast (q : ℚ) : (q : ℍ[R]).im = 0 := rfl
@[simp, norm_cast] lemma imI_ratCast (q : ℚ) : (q : ℍ[R]).imI = 0 := rfl
@[simp, norm_cast] lemma imJ_ratCast (q : ℚ) : (q : ℍ[R]).imJ = 0 := rfl
@[simp, norm_cast] lemma imK_ratCast (q : ℚ) : (q : ℍ[R]).imK = 0 := rfl
@[deprecated (since := "2025-08-31")] alias ratCast_re := re_ratCast
@[deprecated (since := "2025-08-31")] alias ratCast_im := im_ratCast
@[deprecated (since := "2025-08-31")] alias ratCast_imI := imI_ratCast
@[deprecated (since := "2025-08-31")] alias ratCast_imJ := imJ_ratCast
@[deprecated (since := "2025-08-31")] alias ratCast_imK := imK_ratCast
@[norm_cast] lemma coe_nnratCast (q : ℚ≥0) : ↑(q : R) = (q : ℍ[R]) := rfl
@[norm_cast] lemma coe_ratCast (q : ℚ) : ↑(q : R) = (q : ℍ[R]) := rfl
variable [LinearOrder R] [IsStrictOrderedRing R] (a b : ℍ[R])
@[simps -isSimp]
instance instInv : Inv ℍ[R] :=
⟨fun a => (normSq a)⁻¹ • star a⟩
instance instGroupWithZero : GroupWithZero ℍ[R] :=
{ Quaternion.instNontrivial with
inv_zero := by rw [inv_def, star_zero, smul_zero]
mul_inv_cancel := fun a ha => by
rw [inv_def, Algebra.mul_smul_comm (normSq a)⁻¹ a (star a), self_mul_star, smul_coe,
inv_mul_cancel₀ (normSq_ne_zero.2 ha), coe_one] }
@[norm_cast, simp]
theorem coe_inv (x : R) : ((x⁻¹ : R) : ℍ[R]) = (↑x)⁻¹ :=
map_inv₀ (algebraMap R ℍ[R]) _
@[norm_cast, simp]
theorem coe_div (x y : R) : ((x / y : R) : ℍ[R]) = x / y :=
map_div₀ (algebraMap R ℍ[R]) x y
@[norm_cast, simp]
theorem coe_zpow (x : R) (z : ℤ) : ((x ^ z : R) : ℍ[R]) = (x : ℍ[R]) ^ z :=
map_zpow₀ (algebraMap R ℍ[R]) x z
instance instDivisionRing : DivisionRing ℍ[R] where
__ := Quaternion.instRing
__ := Quaternion.instGroupWithZero
nnqsmul := (· • ·)
qsmul := (· • ·)
nnratCast_def _ := by rw [← coe_nnratCast, NNRat.cast_def, coe_div, coe_natCast, coe_natCast]
ratCast_def _ := by rw [← coe_ratCast, Rat.cast_def, coe_div, coe_intCast, coe_natCast]
nnqsmul_def _ _ := by rw [← coe_nnratCast, coe_mul_eq_smul]; ext <;> exact NNRat.smul_def ..
qsmul_def _ _ := by rw [← coe_ratCast, coe_mul_eq_smul]; ext <;> exact Rat.smul_def ..
theorem normSq_inv : normSq a⁻¹ = (normSq a)⁻¹ :=
map_inv₀ normSq _
theorem normSq_div : normSq (a / b) = normSq a / normSq b :=
map_div₀ normSq a b
theorem normSq_zpow (z : ℤ) : normSq (a ^ z) = normSq a ^ z :=
map_zpow₀ normSq a z
@[norm_cast]
theorem normSq_ratCast (q : ℚ) : normSq (q : ℍ[R]) = (q : ℍ[R]) ^ 2 := by
rw [← coe_ratCast, normSq_coe, coe_pow]
end Field
end Quaternion
namespace Cardinal
open Quaternion
section QuaternionAlgebra
variable {R : Type*} (c₁ c₂ c₃ : R)
private theorem pow_four [Infinite R] : #R ^ 4 = #R :=
power_nat_eq (aleph0_le_mk R) <| by decide
/-- The cardinality of a quaternion algebra, as a type. -/
theorem mk_quaternionAlgebra : #(ℍ[R,c₁,c₂,c₃]) = #R ^ 4 := by
rw [mk_congr (QuaternionAlgebra.equivProd c₁ c₂ c₃)]
simp only [mk_prod, lift_id]
ring
@[simp]
theorem mk_quaternionAlgebra_of_infinite [Infinite R] : #(ℍ[R,c₁,c₂,c₃]) = #R := by
rw [mk_quaternionAlgebra, pow_four]
/-- The cardinality of a quaternion algebra, as a set. -/
theorem mk_univ_quaternionAlgebra : #(Set.univ : Set ℍ[R,c₁,c₂,c₃]) = #R ^ 4 := by
rw [mk_univ, mk_quaternionAlgebra]
theorem mk_univ_quaternionAlgebra_of_infinite [Infinite R] :
#(Set.univ : Set ℍ[R,c₁,c₂,c₃]) = #R := by rw [mk_univ_quaternionAlgebra, pow_four]
/-- Show the quaternion ⟨w, x, y, z⟩ as a string "{ re := w, imI := x, imJ := y, imK := z }".
For the typical case of quaternions over ℝ, each component will show as a Cauchy sequence due to
the way Real numbers are represented.
-/
instance [Repr R] {a b c : R} : Repr ℍ[R,a,b,c] where
reprPrec q _ :=
s!"\{ re := {repr q.re}, imI := {repr q.imI}, imJ := {repr q.imJ}, imK := {repr q.imK} }"
end QuaternionAlgebra
section Quaternion
variable (R : Type*) [Zero R] [One R] [Neg R]
/-- The cardinality of the quaternions, as a type. -/
@[simp]
theorem mk_quaternion : #(ℍ[R]) = #R ^ 4 :=
mk_quaternionAlgebra _ _ _
theorem mk_quaternion_of_infinite [Infinite R] : #(ℍ[R]) = #R :=
mk_quaternionAlgebra_of_infinite _ _ _
/-- The cardinality of the quaternions, as a set. -/
theorem mk_univ_quaternion : #(Set.univ : Set ℍ[R]) = #R ^ 4 :=
mk_univ_quaternionAlgebra _ _ _
theorem mk_univ_quaternion_of_infinite [Infinite R] : #(Set.univ : Set ℍ[R]) = #R :=
mk_univ_quaternionAlgebra_of_infinite _ _ _
end Quaternion
end Cardinal |
.lake/packages/mathlib/Mathlib/Algebra/RingQuot.lean | import Mathlib.Algebra.Algebra.Hom
import Mathlib.RingTheory.Congruence.Basic
import Mathlib.RingTheory.Ideal.Quotient.Defs
import Mathlib.RingTheory.Ideal.Span
/-!
# Quotients of semirings
In this file, we directly define the quotient of a semiring by any relation,
by building a bigger relation that represents the ideal generated by that relation.
We prove the universal properties of the quotient, and recommend avoiding relying on the actual
definition, which is made irreducible for this purpose.
Since everything runs in parallel for quotients of `R`-algebras, we do that case at the same time.
-/
assert_not_exists TrivialStar
universe uR uS uT uA u₄
variable {R : Type uR} [Semiring R]
variable {S : Type uS} [CommSemiring S]
variable {T : Type uT}
variable {A : Type uA} [Semiring A] [Algebra S A]
namespace RingCon
instance (c : RingCon A) : Algebra S c.Quotient where
algebraMap := c.mk'.comp (algebraMap S A)
commutes' _ := Quotient.ind' fun _ ↦ congr_arg Quotient.mk'' <| Algebra.commutes _ _
smul_def' _ := Quotient.ind' fun _ ↦ congr_arg Quotient.mk'' <| Algebra.smul_def _ _
@[simp, norm_cast]
theorem coe_algebraMap (c : RingCon A) (s : S) :
(algebraMap S A s : c.Quotient) = algebraMap S _ s :=
rfl
end RingCon
namespace RingQuot
/-- Given an arbitrary relation `r` on a ring, we strengthen it to a relation `Rel r`,
such that the equivalence relation generated by `Rel r` has `x ~ y` if and only if
`x - y` is in the ideal generated by elements `a - b` such that `r a b`.
-/
inductive Rel (r : R → R → Prop) : R → R → Prop
| of ⦃x y : R⦄ (h : r x y) : Rel r x y
| add_left ⦃a b c⦄ : Rel r a b → Rel r (a + c) (b + c)
| mul_left ⦃a b c⦄ : Rel r a b → Rel r (a * c) (b * c)
| mul_right ⦃a b c⦄ : Rel r b c → Rel r (a * b) (a * c)
theorem Rel.add_right {r : R → R → Prop} ⦃a b c : R⦄ (h : Rel r b c) : Rel r (a + b) (a + c) := by
rw [add_comm a b, add_comm a c]
exact Rel.add_left h
theorem Rel.neg {R : Type uR} [Ring R] {r : R → R → Prop} ⦃a b : R⦄ (h : Rel r a b) :
Rel r (-a) (-b) := by simp only [neg_eq_neg_one_mul a, neg_eq_neg_one_mul b, Rel.mul_right h]
theorem Rel.sub_left {R : Type uR} [Ring R] {r : R → R → Prop} ⦃a b c : R⦄ (h : Rel r a b) :
Rel r (a - c) (b - c) := by simp only [sub_eq_add_neg, h.add_left]
theorem Rel.sub_right {R : Type uR} [Ring R] {r : R → R → Prop} ⦃a b c : R⦄ (h : Rel r b c) :
Rel r (a - b) (a - c) := by simp only [sub_eq_add_neg, h.neg.add_right]
theorem Rel.smul {r : A → A → Prop} (k : S) ⦃a b : A⦄ (h : Rel r a b) : Rel r (k • a) (k • b) := by
simp only [Algebra.smul_def, Rel.mul_right h]
/-- `EqvGen (RingQuot.Rel r)` is a ring congruence. -/
def ringCon (r : R → R → Prop) : RingCon R where
r := Relation.EqvGen (Rel r)
iseqv := Relation.EqvGen.is_equivalence _
add' {a b c d} hab hcd := by
induction hab generalizing c d with
| rel _ _ hab =>
refine (Relation.EqvGen.rel _ _ hab.add_left).trans _ _ _ ?_
induction hcd with
| rel _ _ hcd => exact Relation.EqvGen.rel _ _ hcd.add_right
| refl => exact Relation.EqvGen.refl _
| symm _ _ _ h => exact h.symm _ _
| trans _ _ _ _ _ h h' => exact h.trans _ _ _ h'
| refl => induction hcd with
| rel _ _ hcd => exact Relation.EqvGen.rel _ _ hcd.add_right
| refl => exact Relation.EqvGen.refl _
| symm _ _ _ h => exact h.symm _ _
| trans _ _ _ _ _ h h' => exact h.trans _ _ _ h'
| symm x y _ hxy => exact (hxy hcd.symm).symm
| trans x y z _ _ h h' => exact (h hcd).trans _ _ _ (h' <| Relation.EqvGen.refl _)
mul' {a b c d} hab hcd := by
induction hab generalizing c d with
| rel _ _ hab =>
refine (Relation.EqvGen.rel _ _ hab.mul_left).trans _ _ _ ?_
induction hcd with
| rel _ _ hcd => exact Relation.EqvGen.rel _ _ hcd.mul_right
| refl => exact Relation.EqvGen.refl _
| symm _ _ _ h => exact h.symm _ _
| trans _ _ _ _ _ h h' => exact h.trans _ _ _ h'
| refl => induction hcd with
| rel _ _ hcd => exact Relation.EqvGen.rel _ _ hcd.mul_right
| refl => exact Relation.EqvGen.refl _
| symm _ _ _ h => exact h.symm _ _
| trans _ _ _ _ _ h h' => exact h.trans _ _ _ h'
| symm x y _ hxy => exact (hxy hcd.symm).symm
| trans x y z _ _ h h' => exact (h hcd).trans _ _ _ (h' <| Relation.EqvGen.refl _)
theorem eqvGen_rel_eq (r : R → R → Prop) : Relation.EqvGen (Rel r) = RingConGen.Rel r := by
ext x₁ x₂
constructor
· intro h
induction h with
| rel _ _ h => induction h with
| of => exact RingConGen.Rel.of _ _ ‹_›
| add_left _ h => exact h.add (RingConGen.Rel.refl _)
| mul_left _ h => exact h.mul (RingConGen.Rel.refl _)
| mul_right _ h => exact (RingConGen.Rel.refl _).mul h
| refl => exact RingConGen.Rel.refl _
| symm => exact RingConGen.Rel.symm ‹_›
| trans => exact RingConGen.Rel.trans ‹_› ‹_›
· intro h
induction h with
| of => exact Relation.EqvGen.rel _ _ (Rel.of ‹_›)
| refl => exact (RingQuot.ringCon r).refl _
| symm => exact (RingQuot.ringCon r).symm ‹_›
| trans => exact (RingQuot.ringCon r).trans ‹_› ‹_›
| add => exact (RingQuot.ringCon r).add ‹_› ‹_›
| mul => exact (RingQuot.ringCon r).mul ‹_› ‹_›
end RingQuot
/-- The quotient of a ring by an arbitrary relation. -/
structure RingQuot (r : R → R → Prop) where
toQuot : Quot (RingQuot.Rel r)
namespace RingQuot
variable (r : R → R → Prop)
-- can't be irreducible, causes diamonds in ℕ-algebras
private def natCast (n : ℕ) : RingQuot r :=
⟨Quot.mk _ n⟩
private irreducible_def zero : RingQuot r :=
⟨Quot.mk _ 0⟩
private irreducible_def one : RingQuot r :=
⟨Quot.mk _ 1⟩
private irreducible_def add : RingQuot r → RingQuot r → RingQuot r
| ⟨a⟩, ⟨b⟩ => ⟨Quot.map₂ (· + ·) Rel.add_right Rel.add_left a b⟩
private irreducible_def mul : RingQuot r → RingQuot r → RingQuot r
| ⟨a⟩, ⟨b⟩ => ⟨Quot.map₂ (· * ·) Rel.mul_right Rel.mul_left a b⟩
private irreducible_def neg {R : Type uR} [Ring R] (r : R → R → Prop) : RingQuot r → RingQuot r
| ⟨a⟩ => ⟨Quot.map (fun a ↦ -a) Rel.neg a⟩
private irreducible_def sub {R : Type uR} [Ring R] (r : R → R → Prop) :
RingQuot r → RingQuot r → RingQuot r
| ⟨a⟩, ⟨b⟩ => ⟨Quot.map₂ Sub.sub Rel.sub_right Rel.sub_left a b⟩
private irreducible_def npow (n : ℕ) : RingQuot r → RingQuot r
| ⟨a⟩ =>
⟨Quot.lift (fun a ↦ Quot.mk (RingQuot.Rel r) (a ^ n))
(fun a b (h : Rel r a b) ↦ by
-- note we can't define a `Rel.pow` as `Rel` isn't reflexive so `Rel r 1 1` isn't true
dsimp only
induction n with
| zero => rw [pow_zero, pow_zero]
| succ n ih =>
simpa only [pow_succ, mul_def, Quot.map₂_mk, mk.injEq] using
congr_arg₂ (fun x y ↦ mul r ⟨x⟩ ⟨y⟩) ih (Quot.sound h))
a⟩
-- note: this cannot be irreducible, as otherwise diamonds don't commute.
private def smul [Algebra S R] (n : S) : RingQuot r → RingQuot r
| ⟨a⟩ => ⟨Quot.map (fun a ↦ n • a) (Rel.smul n) a⟩
instance : NatCast (RingQuot r) :=
⟨natCast r⟩
instance : Zero (RingQuot r) :=
⟨zero r⟩
instance : One (RingQuot r) :=
⟨one r⟩
instance : Add (RingQuot r) :=
⟨add r⟩
instance : Mul (RingQuot r) :=
⟨mul r⟩
instance : NatPow (RingQuot r) :=
⟨fun x n ↦ npow r n x⟩
instance {R : Type uR} [Ring R] (r : R → R → Prop) : Neg (RingQuot r) :=
⟨neg r⟩
instance {R : Type uR} [Ring R] (r : R → R → Prop) : Sub (RingQuot r) :=
⟨sub r⟩
instance [Algebra S R] : SMul S (RingQuot r) :=
⟨smul r⟩
theorem zero_quot : (⟨Quot.mk _ 0⟩ : RingQuot r) = 0 :=
show _ = zero r by rw [zero_def]
theorem one_quot : (⟨Quot.mk _ 1⟩ : RingQuot r) = 1 :=
show _ = one r by rw [one_def]
theorem add_quot {a b} : (⟨Quot.mk _ a⟩ + ⟨Quot.mk _ b⟩ : RingQuot r) = ⟨Quot.mk _ (a + b)⟩ := by
change add r _ _ = _
rw [add_def]
rfl
theorem mul_quot {a b} : (⟨Quot.mk _ a⟩ * ⟨Quot.mk _ b⟩ : RingQuot r) = ⟨Quot.mk _ (a * b)⟩ := by
change mul r _ _ = _
rw [mul_def]
rfl
theorem pow_quot {a} {n : ℕ} : (⟨Quot.mk _ a⟩ ^ n : RingQuot r) = ⟨Quot.mk _ (a ^ n)⟩ := by
change npow r _ _ = _
rw [npow_def]
theorem neg_quot {R : Type uR} [Ring R] (r : R → R → Prop) {a} :
(-⟨Quot.mk _ a⟩ : RingQuot r) = ⟨Quot.mk _ (-a)⟩ := by
change neg r _ = _
rw [neg_def]
rfl
theorem sub_quot {R : Type uR} [Ring R] (r : R → R → Prop) {a b} :
(⟨Quot.mk _ a⟩ - ⟨Quot.mk _ b⟩ : RingQuot r) = ⟨Quot.mk _ (a - b)⟩ := by
change sub r _ _ = _
rw [sub_def]
rfl
theorem smul_quot [Algebra S R] {n : S} {a : R} :
(n • ⟨Quot.mk _ a⟩ : RingQuot r) = ⟨Quot.mk _ (n • a)⟩ := by
rfl
instance instIsScalarTower [CommSemiring T] [SMul S T] [Algebra S R] [Algebra T R]
[IsScalarTower S T R] : IsScalarTower S T (RingQuot r) :=
⟨fun s t ⟨a⟩ => Quot.inductionOn a fun a' => by simp only [RingQuot.smul_quot, smul_assoc]⟩
instance instSMulCommClass [CommSemiring T] [Algebra S R] [Algebra T R] [SMulCommClass S T R] :
SMulCommClass S T (RingQuot r) :=
⟨fun s t ⟨a⟩ => Quot.inductionOn a fun a' => by simp only [RingQuot.smul_quot, smul_comm s t]⟩
instance instAddCommMonoid (r : R → R → Prop) : AddCommMonoid (RingQuot r) where
add_assoc := by
rintro ⟨⟨⟩⟩ ⟨⟨⟩⟩ ⟨⟨⟩⟩
simp only [add_quot, add_assoc]
zero_add := by
rintro ⟨⟨⟩⟩
simp [add_quot, ← zero_quot, zero_add]
add_zero := by
rintro ⟨⟨⟩⟩
simp only [add_quot, ← zero_quot, add_zero]
add_comm := by
rintro ⟨⟨⟩⟩ ⟨⟨⟩⟩
simp only [add_quot, add_comm]
nsmul := (· • ·)
nsmul_zero := by
rintro ⟨⟨⟩⟩
simp only [smul_quot, zero_smul, zero_quot]
nsmul_succ := by
rintro n ⟨⟨⟩⟩
simp only [smul_quot, nsmul_eq_mul, Nat.cast_add, Nat.cast_one, add_mul, one_mul,
add_comm, add_quot]
instance instMonoidWithZero (r : R → R → Prop) : MonoidWithZero (RingQuot r) where
mul_assoc := by
rintro ⟨⟨⟩⟩ ⟨⟨⟩⟩ ⟨⟨⟩⟩
simp only [mul_quot, mul_assoc]
one_mul := by
rintro ⟨⟨⟩⟩
simp only [mul_quot, ← one_quot, one_mul]
mul_one := by
rintro ⟨⟨⟩⟩
simp only [mul_quot, ← one_quot, mul_one]
zero_mul := by
rintro ⟨⟨⟩⟩
simp only [mul_quot, ← zero_quot, zero_mul]
mul_zero := by
rintro ⟨⟨⟩⟩
simp only [mul_quot, ← zero_quot, mul_zero]
npow n x := x ^ n
npow_zero := by
rintro ⟨⟨⟩⟩
simp only [pow_quot, ← one_quot, pow_zero]
npow_succ := by
rintro n ⟨⟨⟩⟩
simp only [pow_quot, mul_quot, pow_succ]
instance instSemiring (r : R → R → Prop) : Semiring (RingQuot r) where
natCast := natCast r
natCast_zero := by simp [Nat.cast, natCast, ← zero_quot]
natCast_succ := by simp [Nat.cast, natCast, ← one_quot, add_quot]
left_distrib := by
rintro ⟨⟨⟩⟩ ⟨⟨⟩⟩ ⟨⟨⟩⟩
simp only [mul_quot, add_quot, left_distrib]
right_distrib := by
rintro ⟨⟨⟩⟩ ⟨⟨⟩⟩ ⟨⟨⟩⟩
simp only [mul_quot, add_quot, right_distrib]
nsmul := (· • ·)
nsmul_zero := by
rintro ⟨⟨⟩⟩
simp only [zero_smul]
nsmul_succ := by
rintro n ⟨⟨⟩⟩
simp only [smul_quot, nsmul_eq_mul, Nat.cast_add, Nat.cast_one, add_mul, one_mul,
add_comm, add_quot]
__ := instAddCommMonoid r
__ := instMonoidWithZero r
-- can't be irreducible, causes diamonds in ℤ-algebras
private def intCast {R : Type uR} [Ring R] (r : R → R → Prop) (z : ℤ) : RingQuot r :=
⟨Quot.mk _ z⟩
instance instRing {R : Type uR} [Ring R] (r : R → R → Prop) : Ring (RingQuot r) :=
{ RingQuot.instSemiring r with
neg_add_cancel := by
rintro ⟨⟨⟩⟩
simp [neg_quot, add_quot, ← zero_quot]
sub_eq_add_neg := by
rintro ⟨⟨⟩⟩ ⟨⟨⟩⟩
simp [neg_quot, sub_quot, add_quot, sub_eq_add_neg]
zsmul := (· • ·)
zsmul_zero' := by
rintro ⟨⟨⟩⟩
simp [smul_quot, ← zero_quot]
zsmul_succ' := by
rintro n ⟨⟨⟩⟩
simp [smul_quot, add_quot, add_mul, add_comm]
zsmul_neg' := by
rintro n ⟨⟨⟩⟩
simp [smul_quot, neg_quot, add_mul]
intCast := intCast r
intCast_ofNat := fun n => congrArg RingQuot.mk <| by
exact congrArg (Quot.mk _) (Int.cast_natCast _)
intCast_negSucc := fun n => congrArg RingQuot.mk <| by
simp_rw [neg_def]
exact congrArg (Quot.mk _) (Int.cast_negSucc n) }
instance instCommSemiring {R : Type uR} [CommSemiring R] (r : R → R → Prop) :
CommSemiring (RingQuot r) :=
{ RingQuot.instSemiring r with
mul_comm := by
rintro ⟨⟨⟩⟩ ⟨⟨⟩⟩
simp [mul_quot, mul_comm] }
instance {R : Type uR} [CommRing R] (r : R → R → Prop) : CommRing (RingQuot r) :=
{ RingQuot.instCommSemiring r, RingQuot.instRing r with }
instance instInhabited (r : R → R → Prop) : Inhabited (RingQuot r) :=
⟨0⟩
instance instAlgebra [Algebra S R] (r : R → R → Prop) : Algebra S (RingQuot r) where
algebraMap :=
{ toFun r := ⟨Quot.mk _ (algebraMap S R r)⟩
map_one' := by simp [← one_quot]
map_mul' := by simp [mul_quot]
map_zero' := by simp [← zero_quot]
map_add' := by simp [add_quot] }
commutes' r := by
rintro ⟨⟨a⟩⟩
simp [Algebra.commutes, mul_quot]
smul_def' r := by
rintro ⟨⟨a⟩⟩
simp [smul_quot, Algebra.smul_def, mul_quot]
/-- The quotient map from a ring to its quotient, as a homomorphism of rings.
-/
irreducible_def mkRingHom (r : R → R → Prop) : R →+* RingQuot r :=
{ toFun := fun x ↦ ⟨Quot.mk _ x⟩
map_one' := by simp [← one_quot]
map_mul' := by simp [mul_quot]
map_zero' := by simp [← zero_quot]
map_add' := by simp [add_quot] }
theorem mkRingHom_rel {r : R → R → Prop} {x y : R} (w : r x y) : mkRingHom r x = mkRingHom r y := by
simp [mkRingHom_def, Quot.sound (Rel.of w)]
theorem mkRingHom_surjective (r : R → R → Prop) : Function.Surjective (mkRingHom r) := by
simp only [mkRingHom_def, RingHom.coe_mk, MonoidHom.coe_mk, OneHom.coe_mk]
rintro ⟨⟨⟩⟩
simp
@[ext 1100]
theorem ringQuot_ext [NonAssocSemiring T] {r : R → R → Prop} (f g : RingQuot r →+* T)
(w : f.comp (mkRingHom r) = g.comp (mkRingHom r)) : f = g := by
ext x
rcases mkRingHom_surjective r x with ⟨x, rfl⟩
exact (RingHom.congr_fun w x :)
variable [Semiring T]
irreducible_def preLift {r : R → R → Prop} {f : R →+* T} (h : ∀ ⦃x y⦄, r x y → f x = f y) :
RingQuot r →+* T :=
{ toFun := fun x ↦ Quot.lift f
(by
rintro _ _ r
induction r with
| of r => exact h r
| add_left _ r' => rw [map_add, map_add, r']
| mul_left _ r' => rw [map_mul, map_mul, r']
| mul_right _ r' => rw [map_mul, map_mul, r'])
x.toQuot
map_zero' := by simp only [← zero_quot, f.map_zero]
map_add' := by
rintro ⟨⟨x⟩⟩ ⟨⟨y⟩⟩
simp only [add_quot, f.map_add x y]
map_one' := by simp only [← one_quot, f.map_one]
map_mul' := by
rintro ⟨⟨x⟩⟩ ⟨⟨y⟩⟩
simp only [mul_quot, f.map_mul x y] }
/-- Any ring homomorphism `f : R →+* T` which respects a relation `r : R → R → Prop`
factors uniquely through a morphism `RingQuot r →+* T`.
-/
irreducible_def lift {r : R → R → Prop} :
{ f : R →+* T // ∀ ⦃x y⦄, r x y → f x = f y } ≃ (RingQuot r →+* T) :=
{ toFun := fun f ↦ preLift f.prop
invFun := fun F ↦ ⟨F.comp (mkRingHom r), fun _ _ h ↦ congr_arg F (mkRingHom_rel h)⟩
left_inv := fun f ↦ by
ext
simp only [preLift_def, mkRingHom_def, RingHom.coe_comp, RingHom.coe_mk, MonoidHom.coe_mk,
OneHom.coe_mk, Function.comp_apply]
right_inv := fun F ↦ by
simp only [preLift_def]
ext
simp only [mkRingHom_def, RingHom.coe_comp, RingHom.coe_mk, MonoidHom.coe_mk, OneHom.coe_mk,
Function.comp_apply] }
@[simp]
theorem lift_mkRingHom_apply (f : R →+* T) {r : R → R → Prop} (w : ∀ ⦃x y⦄, r x y → f x = f y) (x) :
lift ⟨f, w⟩ (mkRingHom r x) = f x := by
simp_rw [lift_def, preLift_def, mkRingHom_def]
rfl
-- note this is essentially `lift.symm_apply_eq.mp h`
theorem lift_unique (f : R →+* T) {r : R → R → Prop} (w : ∀ ⦃x y⦄, r x y → f x = f y)
(g : RingQuot r →+* T) (h : g.comp (mkRingHom r) = f) : g = lift ⟨f, w⟩ := by
ext
simp [h]
theorem eq_lift_comp_mkRingHom {r : R → R → Prop} (f : RingQuot r →+* T) :
f = lift ⟨f.comp (mkRingHom r), fun _ _ h ↦ congr_arg f (mkRingHom_rel h)⟩ :=
lift_unique (f.comp (mkRingHom r)) (fun _ _ h ↦ congr_arg (⇑f) (mkRingHom_rel h)) f rfl
section CommRing
/-!
We now verify that in the case of a commutative ring, the `RingQuot` construction
agrees with the quotient by the appropriate ideal.
-/
variable {B : Type uR} [CommRing B]
/-- The universal ring homomorphism from `RingQuot r` to `B ⧸ Ideal.ofRel r`. -/
def ringQuotToIdealQuotient (r : B → B → Prop) : RingQuot r →+* B ⧸ Ideal.ofRel r :=
lift ⟨Ideal.Quotient.mk (Ideal.ofRel r),
fun x y h ↦ Ideal.Quotient.eq.2 <| Submodule.mem_sInf.mpr
fun _ w ↦ w ⟨x, y, h, sub_add_cancel x y⟩⟩
@[simp]
theorem ringQuotToIdealQuotient_apply (r : B → B → Prop) (x : B) :
ringQuotToIdealQuotient r (mkRingHom r x) = Ideal.Quotient.mk (Ideal.ofRel r) x := by
simp_rw [ringQuotToIdealQuotient, lift_def, preLift_def, mkRingHom_def]
rfl
/-- The universal ring homomorphism from `B ⧸ Ideal.ofRel r` to `RingQuot r`. -/
def idealQuotientToRingQuot (r : B → B → Prop) : B ⧸ Ideal.ofRel r →+* RingQuot r :=
Ideal.Quotient.lift (Ideal.ofRel r) (mkRingHom r)
(by
refine fun x h ↦ Submodule.span_induction ?_ ?_ ?_ ?_ h
· rintro y ⟨a, b, h, su⟩
symm at su
rw [← sub_eq_iff_eq_add] at su
rw [← su, RingHom.map_sub, mkRingHom_rel h, sub_self]
· simp
· intro a b _ _ ha hb
simp [ha, hb]
· intro a x _ hx
simp [hx])
@[simp]
theorem idealQuotientToRingQuot_apply (r : B → B → Prop) (x : B) :
idealQuotientToRingQuot r (Ideal.Quotient.mk _ x) = mkRingHom r x :=
rfl
/-- The ring equivalence between `RingQuot r` and `(Ideal.ofRel r).quotient`
-/
def ringQuotEquivIdealQuotient (r : B → B → Prop) : RingQuot r ≃+* B ⧸ Ideal.ofRel r :=
RingEquiv.ofHomInv (ringQuotToIdealQuotient r) (idealQuotientToRingQuot r)
(by
ext x
simp)
(by
ext x
simp)
end CommRing
section Algebra
variable (S)
/-- The quotient map from an `S`-algebra to its quotient, as a homomorphism of `S`-algebras.
-/
irreducible_def mkAlgHom (s : A → A → Prop) : A →ₐ[S] RingQuot s :=
{ mkRingHom s with
commutes' := fun _ ↦ by simp [mkRingHom_def]; rfl }
@[simp]
theorem mkAlgHom_coe (s : A → A → Prop) : (mkAlgHom S s : A →+* RingQuot s) = mkRingHom s := by
simp_rw [mkAlgHom_def, mkRingHom_def]
rfl
theorem mkAlgHom_rel {s : A → A → Prop} {x y : A} (w : s x y) :
mkAlgHom S s x = mkAlgHom S s y := by
simp [mkAlgHom_def, mkRingHom_def, Quot.sound (Rel.of w)]
theorem mkAlgHom_surjective (s : A → A → Prop) : Function.Surjective (mkAlgHom S s) := by
suffices Function.Surjective fun x ↦ (⟨.mk (Rel s) x⟩ : RingQuot s) by
simpa [mkAlgHom_def, mkRingHom_def]
rintro ⟨⟨a⟩⟩
use a
variable {B : Type u₄} [Semiring B] [Algebra S B]
@[ext 1100]
theorem ringQuot_ext' {s : A → A → Prop} (f g : RingQuot s →ₐ[S] B)
(w : f.comp (mkAlgHom S s) = g.comp (mkAlgHom S s)) : f = g := by
ext x
rcases mkAlgHom_surjective S s x with ⟨x, rfl⟩
exact AlgHom.congr_fun w x
irreducible_def preLiftAlgHom {s : A → A → Prop} {f : A →ₐ[S] B}
(h : ∀ ⦃x y⦄, s x y → f x = f y) : RingQuot s →ₐ[S] B :=
{ toFun := fun x ↦ Quot.lift f
(by
rintro _ _ r
induction r with
| of r => exact h r
| add_left _ r' => simp only [map_add, r']
| mul_left _ r' => simp only [map_mul, r']
| mul_right _ r' => simp only [map_mul, r'])
x.toQuot
map_zero' := by simp only [← zero_quot, map_zero]
map_add' := by
rintro ⟨⟨x⟩⟩ ⟨⟨y⟩⟩
simp only [add_quot, map_add _ x y]
map_one' := by simp only [← one_quot, map_one]
map_mul' := by
rintro ⟨⟨x⟩⟩ ⟨⟨y⟩⟩
simp only [mul_quot, map_mul _ x y]
commutes' := by
rintro x
simp [← one_quot, smul_quot, Algebra.algebraMap_eq_smul_one] }
/-- Any `S`-algebra homomorphism `f : A →ₐ[S] B` which respects a relation `s : A → A → Prop`
factors uniquely through a morphism `RingQuot s →ₐ[S] B`.
-/
irreducible_def liftAlgHom {s : A → A → Prop} :
{ f : A →ₐ[S] B // ∀ ⦃x y⦄, s x y → f x = f y } ≃ (RingQuot s →ₐ[S] B) :=
{ toFun := fun f' ↦ preLiftAlgHom _ f'.prop
invFun := fun F ↦ ⟨F.comp (mkAlgHom S s), fun _ _ h ↦ congr_arg F (mkAlgHom_rel S h)⟩
left_inv := fun f ↦ by
ext
simp only [preLiftAlgHom_def, mkAlgHom_def, mkRingHom_def,
AlgHom.coe_comp, AlgHom.coe_mk, RingHom.coe_mk, MonoidHom.coe_mk, OneHom.coe_mk,
Function.comp_apply]
right_inv := fun F ↦ by
ext
simp only [preLiftAlgHom_def, mkAlgHom_def, mkRingHom_def,
AlgHom.coe_comp, AlgHom.coe_mk, RingHom.coe_mk,
MonoidHom.coe_mk, OneHom.coe_mk, Function.comp_apply] }
@[simp]
theorem liftAlgHom_mkAlgHom_apply (f : A →ₐ[S] B) {s : A → A → Prop}
(w : ∀ ⦃x y⦄, s x y → f x = f y) (x) : (liftAlgHom S ⟨f, w⟩) ((mkAlgHom S s) x) = f x := by
simp_rw [liftAlgHom_def, preLiftAlgHom_def, mkAlgHom_def, mkRingHom_def]
rfl
-- note this is essentially `(liftAlgHom S).symm_apply_eq.mp h`
theorem liftAlgHom_unique (f : A →ₐ[S] B) {s : A → A → Prop} (w : ∀ ⦃x y⦄, s x y → f x = f y)
(g : RingQuot s →ₐ[S] B) (h : g.comp (mkAlgHom S s) = f) : g = liftAlgHom S ⟨f, w⟩ := by
ext
simp [h]
theorem eq_liftAlgHom_comp_mkAlgHom {s : A → A → Prop} (f : RingQuot s →ₐ[S] B) :
f = liftAlgHom S ⟨f.comp (mkAlgHom S s), fun _ _ h ↦ congr_arg f (mkAlgHom_rel S h)⟩ :=
liftAlgHom_unique S (f.comp (mkAlgHom S s)) (fun _ _ h ↦ congr_arg (⇑f) (mkAlgHom_rel S h)) f rfl
end Algebra
end RingQuot |
.lake/packages/mathlib/Mathlib/Algebra/GeomSum.lean | import Mathlib.Algebra.Group.NatPowAssoc
import Mathlib.Algebra.Order.Field.GeomSum
import Mathlib.Algebra.Order.Ring.GeomSum
import Mathlib.Algebra.Ring.Regular
import Mathlib.Tactic.Abel
import Mathlib.Tactic.Positivity.Basic
deprecated_module (since := "2025-06-19") |
.lake/packages/mathlib/Mathlib/Algebra/Exact.lean | import Mathlib.Algebra.Module.Submodule.Range
import Mathlib.LinearAlgebra.Prod
import Mathlib.LinearAlgebra.Quotient.Basic
/-! # Exactness of a pair
* For two maps `f : M → N` and `g : N → P`, with `Zero P`,
`Function.Exact f g` says that `Set.range f = Set.preimage g {0}`
* For additive maps `f : M →+ N` and `g : N →+ P`,
`Exact f g` says that `range f = ker g`
* For linear maps `f : M →ₗ[R] N` and `g : N →ₗ[R] P`,
`Exact f g` says that `range f = ker g`
## TODO :
* generalize to `SemilinearMap`, even `SemilinearMapClass`
* add the multiplicative case (`Function.Exact` will become `Function.AddExact`?)
-/
variable {R M M' N N' P P' : Type*}
namespace Function
variable (f : M → N) (g : N → P) (g' : P → P')
/-- The maps `f` and `g` form an exact pair :
`g y = 0` iff `y` belongs to the image of `f` -/
def Exact [Zero P] : Prop := ∀ y, g y = 0 ↔ y ∈ Set.range f
variable {f g}
namespace Exact
lemma apply_apply_eq_zero [Zero P] (h : Exact f g) (x : M) :
g (f x) = 0 := (h _).mpr <| Set.mem_range_self _
lemma comp_eq_zero [Zero P] (h : Exact f g) : g.comp f = 0 :=
funext h.apply_apply_eq_zero
lemma of_comp_of_mem_range [Zero P] (h1 : g ∘ f = 0)
(h2 : ∀ x, g x = 0 → x ∈ Set.range f) : Exact f g :=
fun y => Iff.intro (h2 y) <|
Exists.rec ((forall_apply_eq_imp_iff (p := (g · = 0))).mpr (congrFun h1) y)
lemma comp_injective [Zero P] [Zero P'] (exact : Exact f g)
(inj : Function.Injective g') (h0 : g' 0 = 0) :
Exact f (g' ∘ g) := by
intro x
refine ⟨fun H => exact x |>.mp <| inj <| h0 ▸ H, ?_⟩
intro H
rw [Function.comp_apply, exact x |>.mpr H, h0]
lemma of_comp_eq_zero_of_ker_in_range [Zero P] (hc : g.comp f = 0)
(hr : ∀ y, g y = 0 → y ∈ Set.range f) :
Exact f g :=
fun y ↦ ⟨hr y, fun ⟨x, hx⟩ ↦ hx ▸ congrFun hc x⟩
/-- Two maps `f : M → N` and `g : N → P` are exact if and only if the induced maps
`Set.range f → N → Set.range g` are exact.
Note that if you already have an instance `[Zero (Set.range g)]` (which is unlikely) this lemma
may not apply if the zero of `Set.range g` is not definitionally equal to `⟨0, hg⟩`. -/
lemma iff_rangeFactorization [Zero P] (hg : 0 ∈ Set.range g) :
letI : Zero (Set.range g) := ⟨⟨0, hg⟩⟩
Exact f g ↔ Exact ((↑) : Set.range f → N) (Set.rangeFactorization g) := by
letI : Zero (Set.range g) := ⟨⟨0, hg⟩⟩
have : ((0 : Set.range g) : P) = 0 := rfl
simp [Exact, Set.rangeFactorization, Subtype.ext_iff, this]
/-- If two maps `f : M → N` and `g : N → P` are exact, then the induced maps
`Set.range f → N → Set.range g` are exact.
Note that if you already have an instance `[Zero (Set.range g)]` (which is unlikely) this lemma
may not apply if the zero of `Set.range g` is not definitionally equal to `⟨0, hg⟩`. -/
lemma rangeFactorization [Zero P] (h : Exact f g) (hg : 0 ∈ Set.range g) :
letI : Zero (Set.range g) := ⟨⟨0, hg⟩⟩
Exact ((↑) : Set.range f → N) (Set.rangeFactorization g) :=
(iff_rangeFactorization hg).1 h
end Exact
end Function
section AddMonoidHom
variable [AddGroup M] [AddGroup N] [AddGroup P] {f : M →+ N} {g : N →+ P}
namespace AddMonoidHom
open Function
lemma exact_iff :
Exact f g ↔ ker g = range f :=
Iff.symm SetLike.ext_iff
lemma exact_of_comp_eq_zero_of_ker_le_range
(h1 : g.comp f = 0) (h2 : ker g ≤ range f) : Exact f g :=
Exact.of_comp_of_mem_range (congrArg DFunLike.coe h1) h2
lemma exact_of_comp_of_mem_range
(h1 : g.comp f = 0) (h2 : ∀ x, g x = 0 → x ∈ range f) : Exact f g :=
exact_of_comp_eq_zero_of_ker_le_range h1 h2
/-- When we have a commutative diagram from a sequence of two maps to another,
such that the left vertical map is surjective, the middle vertical map is bijective and the right
vertical map is injective, then the upper row is exact iff the lower row is.
See `ShortComplex.exact_iff_of_epi_of_isIso_of_mono` in the file
`Mathlib/Algebra/Homology/ShortComplex/Exact.lean` for the categorical version of this result. -/
lemma exact_iff_of_surjective_of_bijective_of_injective
{M₁ M₂ M₃ N₁ N₂ N₃ : Type*} [AddCommMonoid M₁] [AddCommMonoid M₂] [AddCommMonoid M₃]
[AddCommMonoid N₁] [AddCommMonoid N₂] [AddCommMonoid N₃]
(f : M₁ →+ M₂) (g : M₂ →+ M₃) (f' : N₁ →+ N₂) (g' : N₂ →+ N₃)
(τ₁ : M₁ →+ N₁) (τ₂ : M₂ →+ N₂) (τ₃ : M₃ →+ N₃)
(comm₁₂ : f'.comp τ₁ = τ₂.comp f)
(comm₂₃ : g'.comp τ₂ = τ₃.comp g)
(h₁ : Function.Surjective τ₁) (h₂ : Function.Bijective τ₂) (h₃ : Function.Injective τ₃) :
Exact f g ↔ Exact f' g' := by
replace comm₁₂ := DFunLike.congr_fun comm₁₂
replace comm₂₃ := DFunLike.congr_fun comm₂₃
dsimp at comm₁₂ comm₂₃
constructor
· intro h y₂
obtain ⟨x₂, rfl⟩ := h₂.2 y₂
constructor
· intro hx₂
obtain ⟨x₁, rfl⟩ := (h x₂).1 (h₃ (by simpa only [map_zero, comm₂₃] using hx₂))
exact ⟨τ₁ x₁, by simp only [comm₁₂]⟩
· rintro ⟨y₁, hy₁⟩
obtain ⟨x₁, rfl⟩ := h₁ y₁
rw [comm₂₃, (h x₂).2 _, map_zero]
exact ⟨x₁, h₂.1 (by simpa only [comm₁₂] using hy₁)⟩
· intro h x₂
constructor
· intro hx₂
obtain ⟨y₁, hy₁⟩ := (h (τ₂ x₂)).1 (by simp only [comm₂₃, hx₂, map_zero])
obtain ⟨x₁, rfl⟩ := h₁ y₁
exact ⟨x₁, h₂.1 (by simpa only [comm₁₂] using hy₁)⟩
· rintro ⟨x₁, rfl⟩
apply h₃
simp only [← comm₁₂, ← comm₂₃, h.apply_apply_eq_zero (τ₁ x₁), map_zero]
end AddMonoidHom
namespace Function.Exact
open AddMonoidHom
lemma addMonoidHom_ker_eq (hfg : Exact f g) :
ker g = range f :=
SetLike.ext hfg
lemma addMonoidHom_comp_eq_zero (h : Exact f g) : g.comp f = 0 :=
DFunLike.coe_injective h.comp_eq_zero
section
variable {X₁ X₂ X₃ Y₁ Y₂ Y₃ : Type*} [AddCommMonoid X₁] [AddCommMonoid X₂] [AddCommMonoid X₃]
[AddCommMonoid Y₁] [AddCommMonoid Y₂] [AddCommMonoid Y₃]
(e₁ : X₁ ≃+ Y₁) (e₂ : X₂ ≃+ Y₂) (e₃ : X₃ ≃+ Y₃)
{f₁₂ : X₁ →+ X₂} {f₂₃ : X₂ →+ X₃} {g₁₂ : Y₁ →+ Y₂} {g₂₃ : Y₂ →+ Y₃}
lemma iff_of_ladder_addEquiv (comm₁₂ : g₁₂.comp e₁ = AddMonoidHom.comp e₂ f₁₂)
(comm₂₃ : g₂₃.comp e₂ = AddMonoidHom.comp e₃ f₂₃) : Exact g₁₂ g₂₃ ↔ Exact f₁₂ f₂₃ :=
(exact_iff_of_surjective_of_bijective_of_injective _ _ _ _ e₁ e₂ e₃ comm₁₂ comm₂₃
e₁.surjective e₂.bijective e₃.injective).symm
lemma of_ladder_addEquiv_of_exact (comm₁₂ : g₁₂.comp e₁ = AddMonoidHom.comp e₂ f₁₂)
(comm₂₃ : g₂₃.comp e₂ = AddMonoidHom.comp e₃ f₂₃) (H : Exact f₁₂ f₂₃) : Exact g₁₂ g₂₃ :=
(iff_of_ladder_addEquiv _ _ _ comm₁₂ comm₂₃).2 H
lemma of_ladder_addEquiv_of_exact' (comm₁₂ : g₁₂.comp e₁ = AddMonoidHom.comp e₂ f₁₂)
(comm₂₃ : g₂₃.comp e₂ = AddMonoidHom.comp e₃ f₂₃) (H : Exact g₁₂ g₂₃) : Exact f₁₂ f₂₃ :=
(iff_of_ladder_addEquiv _ _ _ comm₁₂ comm₂₃).1 H
end
/-- Two maps `f : M →+ N` and `g : N →+ P` are exact if and only if the induced maps
`AddMonoidHom.range f → N → AddMonoidHom.range g` are exact. -/
lemma iff_addMonoidHom_rangeRestrict :
Exact f g ↔ Exact f.range.subtype g.rangeRestrict :=
iff_rangeFactorization (zero_mem g.range)
alias ⟨addMonoidHom_rangeRestrict, _⟩ := iff_addMonoidHom_rangeRestrict
end Function.Exact
end AddMonoidHom
section LinearMap
open Function
variable [Semiring R] [AddCommMonoid M] [AddCommMonoid M'] [AddCommMonoid N]
[AddCommMonoid N'] [AddCommMonoid P] [AddCommMonoid P'] [Module R M]
[Module R M'] [Module R N] [Module R N'] [Module R P] [Module R P']
variable {f : M →ₗ[R] N} {g : N →ₗ[R] P}
namespace LinearMap
lemma exact_iff :
Exact f g ↔ LinearMap.ker g = LinearMap.range f :=
Iff.symm SetLike.ext_iff
lemma exact_of_comp_eq_zero_of_ker_le_range
(h1 : g ∘ₗ f = 0) (h2 : ker g ≤ range f) : Exact f g :=
Exact.of_comp_of_mem_range (congrArg DFunLike.coe h1) h2
lemma exact_of_comp_of_mem_range
(h1 : g ∘ₗ f = 0) (h2 : ∀ x, g x = 0 → x ∈ range f) : Exact f g :=
exact_of_comp_eq_zero_of_ker_le_range h1 h2
section Ring
variable {R M N P : Type*} [Ring R]
[AddCommGroup M] [AddCommGroup N] [AddCommGroup P] [Module R M] [Module R N] [Module R P]
lemma exact_subtype_mkQ (Q : Submodule R N) :
Exact (Submodule.subtype Q) (Submodule.mkQ Q) := by
rw [exact_iff, Submodule.ker_mkQ, Submodule.range_subtype Q]
lemma exact_map_mkQ_range (f : M →ₗ[R] N) :
Exact f (Submodule.mkQ (range f)) :=
exact_iff.mpr <| Submodule.ker_mkQ _
lemma exact_subtype_ker_map (g : N →ₗ[R] P) :
Exact (Submodule.subtype (ker g)) g :=
exact_iff.mpr <| (Submodule.range_subtype _).symm
@[simp]
lemma exact_zero_iff_injective {M N : Type*} (P : Type*)
[AddCommGroup M] [AddCommGroup N] [AddCommMonoid P] [Module R N] [Module R M]
[Module R P] (f : M →ₗ[R] N) :
Function.Exact (0 : P →ₗ[R] M) f ↔ Function.Injective f := by
simp [← ker_eq_bot, exact_iff]
end Ring
@[simp]
lemma exact_zero_iff_surjective {M N : Type*} (P : Type*)
[AddCommGroup M] [AddCommGroup N] [AddCommMonoid P] [Module R N] [Module R M]
[Module R P] (f : M →ₗ[R] N) :
Function.Exact f (0 : N →ₗ[R] P) ↔ Function.Surjective f := by
simp [← range_eq_top, exact_iff, eq_comm]
end LinearMap
variable (f g) in
lemma LinearEquiv.conj_exact_iff_exact (e : N ≃ₗ[R] N') :
Function.Exact (e ∘ₗ f) (g ∘ₗ (e.symm : N' →ₗ[R] N)) ↔ Exact f g := by
simp_rw [LinearMap.exact_iff, LinearMap.ker_comp, ← Submodule.map_equiv_eq_comap_symm,
LinearMap.range_comp]
exact (Submodule.map_injective_of_injective e.injective).eq_iff
namespace Function
open LinearMap
lemma Exact.linearMap_ker_eq (hfg : Exact f g) : ker g = range f :=
SetLike.ext hfg
lemma Exact.linearMap_comp_eq_zero (h : Exact f g) : g.comp f = 0 :=
DFunLike.coe_injective h.comp_eq_zero
lemma Surjective.comp_exact_iff_exact {p : M' →ₗ[R] M} (h : Surjective p) :
Exact (f ∘ₗ p) g ↔ Exact f g :=
iff_of_eq <| forall_congr fun x =>
congrArg (g x = 0 ↔ x ∈ ·) (h.range_comp f)
lemma Injective.comp_exact_iff_exact {i : P →ₗ[R] P'} (h : Injective i) :
Exact f (i ∘ₗ g) ↔ Exact f g :=
forall_congr' fun _ => iff_congr (LinearMap.map_eq_zero_iff _ h) Iff.rfl
namespace Exact
variable
{f₁₂ : M →ₗ[R] N} {f₂₃ : N →ₗ[R] P} {g₁₂ : M' →ₗ[R] N'}
{g₂₃ : N' →ₗ[R] P'} {e₁ : M ≃ₗ[R] M'} {e₂ : N ≃ₗ[R] N'} {e₃ : P ≃ₗ[R] P'}
lemma iff_of_ladder_linearEquiv
(h₁₂ : g₁₂ ∘ₗ e₁ = e₂ ∘ₗ f₁₂) (h₂₃ : g₂₃ ∘ₗ e₂ = e₃ ∘ₗ f₂₃) :
Exact g₁₂ g₂₃ ↔ Exact f₁₂ f₂₃ :=
iff_of_ladder_addEquiv e₁.toAddEquiv e₂.toAddEquiv e₃.toAddEquiv
(f₁₂ := f₁₂) (f₂₃ := f₂₃) (g₁₂ := g₁₂) (g₂₃ := g₂₃)
(congr_arg LinearMap.toAddMonoidHom h₁₂) (congr_arg LinearMap.toAddMonoidHom h₂₃)
lemma of_ladder_linearEquiv_of_exact
(h₁₂ : g₁₂ ∘ₗ e₁ = e₂ ∘ₗ f₁₂) (h₂₃ : g₂₃ ∘ₗ e₂ = e₃ ∘ₗ f₂₃)
(H : Exact f₁₂ f₂₃) : Exact g₁₂ g₂₃ := by
rwa [iff_of_ladder_linearEquiv h₁₂ h₂₃]
/-- Two maps `f : M →ₗ[R] N` and `g : N →ₗ[R] P` are exact if and only if the induced maps
`LinearMap.range f → N → LinearMap.range g` are exact. -/
lemma iff_linearMap_rangeRestrict :
Exact f g ↔ Exact (LinearMap.range f).subtype g.rangeRestrict :=
iff_rangeFactorization (zero_mem (LinearMap.range g))
alias ⟨linearMap_rangeRestrict, _⟩ := iff_linearMap_rangeRestrict
end Exact
end Function
end LinearMap
namespace Function
section split
variable [Semiring R]
variable [AddCommGroup M] [AddCommGroup N] [AddCommGroup P] [Module R M] [Module R N] [Module R P]
variable {f : M →ₗ[R] N} {g : N →ₗ[R] P}
open LinearMap
/-- Given an exact sequence `0 → M → N → P`, giving a section `P → N` is equivalent to giving a
splitting `N ≃ M × P`. -/
noncomputable
def Exact.splitSurjectiveEquiv (h : Function.Exact f g) (hf : Function.Injective f) :
{ l // g ∘ₗ l = .id } ≃
{ e : N ≃ₗ[R] M × P // f = e.symm ∘ₗ inl R M P ∧ g = snd R M P ∘ₗ e } := by
refine
{ toFun := fun l ↦ ⟨(LinearEquiv.ofBijective (f ∘ₗ fst R M P + l.1 ∘ₗ snd R M P) ?_).symm, ?_⟩
invFun := fun e ↦ ⟨e.1.symm ∘ₗ inr R M P, ?_⟩
left_inv := ?_
right_inv := ?_ }
· have h₁ : ∀ x, g (l.1 x) = x := LinearMap.congr_fun l.2
have h₂ : ∀ x, g (f x) = 0 := congr_fun h.comp_eq_zero
constructor
· intro x y e
simp only [add_apply, coe_comp, comp_apply, fst_apply, snd_apply] at e
suffices x.2 = y.2 from Prod.ext (hf (by rwa [this, add_left_inj] at e)) this
simpa [h₁, h₂] using DFunLike.congr_arg g e
· intro x
obtain ⟨y, hy⟩ := (h (x - l.1 (g x))).mp (by simp [h₁, g.map_sub])
exact ⟨⟨y, g x⟩, by simp [hy]⟩
· have h₁ : ∀ x, g (l.1 x) = x := LinearMap.congr_fun l.2
have h₂ : ∀ x, g (f x) = 0 := congr_fun h.comp_eq_zero
constructor
· ext; simp
· rw [LinearEquiv.eq_comp_toLinearMap_symm]
ext <;> simp [h₁, h₂]
· rw [← LinearMap.comp_assoc, (LinearEquiv.eq_comp_toLinearMap_symm _ _).mp e.2.2]; rfl
· intro; ext; simp
· rintro ⟨e, rfl, rfl⟩
ext1
apply LinearEquiv.symm_bijective.injective
ext
apply e.injective
ext <;> simp
/-- Given an exact sequence `M → N → P → 0`, giving a retraction `N → M` is equivalent to giving a
splitting `N ≃ M × P`. -/
noncomputable
def Exact.splitInjectiveEquiv
{R M N P} [Semiring R] [AddCommGroup M] [AddCommGroup N]
[AddCommGroup P] [Module R M] [Module R N] [Module R P] {f : M →ₗ[R] N} {g : N →ₗ[R] P}
(h : Function.Exact f g) (hg : Function.Surjective g) :
{ l // l ∘ₗ f = .id } ≃
{ e : N ≃ₗ[R] M × P // f = e.symm ∘ₗ inl R M P ∧ g = snd R M P ∘ₗ e } := by
refine
{ toFun := fun l ↦ ⟨(LinearEquiv.ofBijective (l.1.prod g) ?_), ?_⟩
invFun := fun e ↦ ⟨fst R M P ∘ₗ e.1, ?_⟩
left_inv := ?_
right_inv := ?_ }
· have h₁ : ∀ x, l.1 (f x) = x := LinearMap.congr_fun l.2
have h₂ : ∀ x, g (f x) = 0 := congr_fun h.comp_eq_zero
constructor
· intro x y e
simp only [prod_apply, Pi.prod, Prod.mk.injEq] at e
obtain ⟨z, hz⟩ := (h (x - y)).mp (by simpa [sub_eq_zero] using e.2)
suffices z = 0 by rw [← sub_eq_zero, ← hz, this, map_zero]
rw [← h₁ z, hz, map_sub, e.1, sub_self]
· rintro ⟨x, y⟩
obtain ⟨y, rfl⟩ := hg y
refine ⟨f x + y - f (l.1 y), by ext <;> simp [h₁, h₂]⟩
· have h₁ : ∀ x, l.1 (f x) = x := LinearMap.congr_fun l.2
have h₂ : ∀ x, g (f x) = 0 := congr_fun h.comp_eq_zero
constructor
· rw [LinearEquiv.eq_toLinearMap_symm_comp]
ext <;> simp [h₁, h₂]
· ext; simp
· rw [LinearMap.comp_assoc, (LinearEquiv.eq_toLinearMap_symm_comp _ _).mp e.2.1]; rfl
· intro; ext; simp
· rintro ⟨e, rfl, rfl⟩
ext x <;> simp
theorem Exact.split_tfae' (h : Function.Exact f g) :
List.TFAE [
Function.Injective f ∧ ∃ l, g ∘ₗ l = LinearMap.id,
Function.Surjective g ∧ ∃ l, l ∘ₗ f = LinearMap.id,
∃ e : N ≃ₗ[R] M × P, f = e.symm ∘ₗ LinearMap.inl R M P ∧ g = LinearMap.snd R M P ∘ₗ e] := by
tfae_have 1 → 3
| ⟨hf, l, hl⟩ => ⟨_, (h.splitSurjectiveEquiv hf ⟨l, hl⟩).2⟩
tfae_have 2 → 3
| ⟨hg, l, hl⟩ => ⟨_, (h.splitInjectiveEquiv hg ⟨l, hl⟩).2⟩
tfae_have 3 → 1
| ⟨e, e₁, e₂⟩ => by
have : Function.Injective f := e₁ ▸ e.symm.injective.comp LinearMap.inl_injective
exact ⟨this, ⟨_, ((h.splitSurjectiveEquiv this).symm ⟨e, e₁, e₂⟩).2⟩⟩
tfae_have 3 → 2
| ⟨e, e₁, e₂⟩ => by
have : Function.Surjective g := e₂ ▸ Prod.snd_surjective.comp e.surjective
exact ⟨this, ⟨_, ((h.splitInjectiveEquiv this).symm ⟨e, e₁, e₂⟩).2⟩⟩
tfae_finish
/-- Equivalent characterizations of split exact sequences. Also known as the **Splitting lemma**. -/
theorem Exact.split_tfae
{R M N P} [Semiring R] [AddCommGroup M] [AddCommGroup N]
[AddCommGroup P] [Module R M] [Module R N] [Module R P] {f : M →ₗ[R] N} {g : N →ₗ[R] P}
(h : Function.Exact f g) (hf : Function.Injective f) (hg : Function.Surjective g) :
List.TFAE [
∃ l, g ∘ₗ l = LinearMap.id,
∃ l, l ∘ₗ f = LinearMap.id,
∃ e : N ≃ₗ[R] M × P, f = e.symm ∘ₗ LinearMap.inl R M P ∧ g = LinearMap.snd R M P ∘ₗ e] := by
tfae_have 1 ↔ 3 := by
simpa using (h.splitSurjectiveEquiv hf).nonempty_congr
tfae_have 2 ↔ 3 := by
simpa using (h.splitInjectiveEquiv hg).nonempty_congr
tfae_finish
end split
section Prod
variable [Semiring R] [AddCommMonoid M] [AddCommMonoid N] [Module R M] [Module R N]
lemma Exact.inr_fst : Function.Exact (LinearMap.inr R M N) (LinearMap.fst R M N) := by
rintro ⟨x, y⟩
simp only [LinearMap.fst_apply, @eq_comm _ x, LinearMap.coe_inr, Set.mem_range, Prod.mk.injEq,
exists_eq_right]
lemma Exact.inl_snd : Function.Exact (LinearMap.inl R M N) (LinearMap.snd R M N) := by
rintro ⟨x, y⟩
simp only [LinearMap.snd_apply, @eq_comm _ y, LinearMap.coe_inl, Set.mem_range, Prod.mk.injEq,
exists_eq_left]
end Prod
end Function
section Ring
open LinearMap Submodule
variable [Ring R] [AddCommGroup M] [AddCommGroup N] [AddCommGroup P]
[Module R M] [Module R N] [Module R P]
{f : M →ₗ[R] N} {g : N →ₗ[R] P}
namespace Function
/-- A necessary and sufficient condition for an exact sequence to descend to a quotient. -/
lemma Exact.exact_mapQ_iff
(hfg : Exact f g) {p q r} (hpq : p ≤ comap f q) (hqr : q ≤ comap g r) :
Exact (mapQ p q f hpq) (mapQ q r g hqr) ↔ range g ⊓ r ≤ map g q := by
rw [exact_iff, ← (comap_injective_of_surjective (mkQ_surjective _)).eq_iff]
dsimp only [mapQ]
rw [← ker_comp, range_liftQ, liftQ_mkQ, ker_comp, range_comp, comap_map_eq,
ker_mkQ, ker_mkQ, ← hfg.linearMap_ker_eq, sup_comm,
← (sup_le hqr (ker_le_comap g)).ge_iff_eq',
← comap_map_eq, ← map_le_iff_le_comap, map_comap_eq]
end Function
namespace LinearMap
/-- When we have a commutative diagram from a sequence of two linear maps to another,
such that the left vertical map is surjective, the middle vertical map is bijective and the right
vertical map is injective, then the upper row is exact iff the lower row is.
See `ShortComplex.exact_iff_of_epi_of_isIso_of_mono` in the file
`Mathlib/Algebra/Homology/ShortComplex/Exact.lean` for the categorical version of this result. -/
lemma exact_iff_of_surjective_of_bijective_of_injective
{M₁ M₂ M₃ N₁ N₂ N₃ : Type*} [AddCommMonoid M₁] [AddCommMonoid M₂] [AddCommMonoid M₃]
[AddCommMonoid N₁] [AddCommMonoid N₂] [AddCommMonoid N₃]
[Module R M₁] [Module R M₂] [Module R M₃]
[Module R N₁] [Module R N₂] [Module R N₃]
(f : M₁ →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (f' : N₁ →ₗ[R] N₂) (g' : N₂ →ₗ[R] N₃)
(τ₁ : M₁ →ₗ[R] N₁) (τ₂ : M₂ →ₗ[R] N₂) (τ₃ : M₃ →ₗ[R] N₃)
(comm₁₂ : f'.comp τ₁ = τ₂.comp f) (comm₂₃ : g'.comp τ₂ = τ₃.comp g)
(h₁ : Function.Surjective τ₁) (h₂ : Function.Bijective τ₂) (h₃ : Function.Injective τ₃) :
Function.Exact f g ↔ Function.Exact f' g' :=
AddMonoidHom.exact_iff_of_surjective_of_bijective_of_injective
f.toAddMonoidHom g.toAddMonoidHom f'.toAddMonoidHom g'.toAddMonoidHom
τ₁.toAddMonoidHom τ₂.toAddMonoidHom τ₃.toAddMonoidHom
(by ext; apply DFunLike.congr_fun comm₁₂) (by ext; apply DFunLike.congr_fun comm₂₃) h₁ h₂ h₃
lemma surjective_range_liftQ (h : range f ≤ ker g) (hg : Function.Surjective g) :
Function.Surjective ((range f).liftQ g h) := by
intro x₃
obtain ⟨x₂, rfl⟩ := hg x₃
exact ⟨Submodule.Quotient.mk x₂, rfl⟩
lemma ker_eq_bot_range_liftQ_iff (h : range f ≤ ker g) :
ker ((range f).liftQ g h) = ⊥ ↔ ker g = range f := by
simp only [Submodule.ext_iff, mem_ker, Submodule.mem_bot, mem_range]
constructor
· intro hfg x
simpa using hfg (Submodule.Quotient.mk x)
· intro hfg x
obtain ⟨x, rfl⟩ := Submodule.Quotient.mk_surjective _ x
simpa using hfg x
lemma injective_range_liftQ_of_exact (h : Function.Exact f g) :
Function.Injective ((range f).liftQ g (h · |>.mpr)) := by
simpa only [← LinearMap.ker_eq_bot, ker_eq_bot_range_liftQ_iff, exact_iff] using h
end LinearMap
/-- The linear equivalence `(N ⧸ LinearMap.range f) ≃ₗ[A] P` associated to
an exact sequence `M → N → P → 0` of `R`-modules. -/
@[simps! apply]
noncomputable def Function.Exact.linearEquivOfSurjective (h : Function.Exact f g)
(hg : Function.Surjective g) : (N ⧸ LinearMap.range f) ≃ₗ[R] P :=
LinearEquiv.ofBijective ((LinearMap.range f).liftQ g (h · |>.mpr))
⟨LinearMap.injective_range_liftQ_of_exact h, LinearMap.surjective_range_liftQ _ hg⟩
@[simp]
lemma Function.Exact.linearEquivOfSurjective_symm_apply (h : Function.Exact f g)
(hg : Function.Surjective g) (x : N) :
(h.linearEquivOfSurjective hg).symm (g x) = Submodule.Quotient.mk x := by
simp [LinearEquiv.symm_apply_eq]
end Ring |
.lake/packages/mathlib/Mathlib/Algebra/FreeNonUnitalNonAssocAlgebra.lean | import Mathlib.Algebra.Free
import Mathlib.Algebra.MonoidAlgebra.Basic
/-!
# Free algebras
Given a semiring `R` and a type `X`, we construct the free non-unital, non-associative algebra on
`X` with coefficients in `R`, together with its universal property. The construction is valuable
because it can be used to build free algebras with more structure, e.g., free Lie algebras.
Note that elsewhere we have a construction of the free unital, associative algebra. This is called
`FreeAlgebra`.
## Main definitions
* `FreeNonUnitalNonAssocAlgebra`
* `FreeNonUnitalNonAssocAlgebra.lift`
* `FreeNonUnitalNonAssocAlgebra.of`
## Implementation details
We construct the free algebra as the magma algebra, with coefficients in `R`, of the free magma on
`X`. However we regard this as an implementation detail and thus deliberately omit the lemmas
`of_apply` and `lift_apply`, and we mark `FreeNonUnitalNonAssocAlgebra` and `lift` as
irreducible once we have established the universal property.
## Tags
free algebra, non-unital, non-associative, free magma, magma algebra, universal property,
forgetful functor, adjoint functor
-/
universe u v w
noncomputable section
variable (R : Type u) (X : Type v) [Semiring R]
/--
If `α` is a type, and `R` is a semiring, then `FreeNonUnitalNonAssocAlgebra R α` is the free
non-unital non-associative `R`-algebra generated by `α`.
This is an `R`-algebra equipped with a function
`FreeNonUnitalNonAssocAlgebra.of R : α → FreeNonUnitalNonAssocAlgebra R α` which has
the following universal property: if `A` is any `R`-algebra, and `f : α → A` is any function,
then this function is the composite of `FreeNonUnitalNonAssocAlgebra.of R`
and a unique non-unital `R`-algebra homomorphism
`FreeNonUnitalNonAssocAlgebra.lift R f : FreeNonUnitalNonAssocAlgebra R α →ₙₐ[R] A`.
A typical element of `FreeNonUnitalNonAssocAlgebra R α` is an `R`-linear combination of
nonempty formal (non-commutative, non-associative) products of elements of `α`.
For example if `x` and `y` are terms of type `α` and
`a`, `b` are terms of type `R` then `(3 * a * a) • (x * (y * x)) + (2 * b + 1) • (y * x)` is a
"typical" element of `FreeNonUnitalNonAssocAlgebra R α`.
-/
abbrev FreeNonUnitalNonAssocAlgebra :=
MonoidAlgebra R (FreeMagma X)
namespace FreeNonUnitalNonAssocAlgebra
variable {X}
/-- The embedding of `X` into the free algebra with coefficients in `R`. -/
def of : X → FreeNonUnitalNonAssocAlgebra R X :=
MonoidAlgebra.ofMagma R _ ∘ FreeMagma.of
variable {A : Type w} [NonUnitalNonAssocSemiring A]
variable [Module R A] [IsScalarTower R A A] [SMulCommClass R A A]
/-- The functor `X ↦ FreeNonUnitalNonAssocAlgebra R X` from the category of types to the
category of non-unital, non-associative algebras over `R` is adjoint to the forgetful functor in the
other direction. -/
def lift : (X → A) ≃ (FreeNonUnitalNonAssocAlgebra R X →ₙₐ[R] A) :=
FreeMagma.lift.trans (MonoidAlgebra.liftMagma R)
@[simp]
theorem lift_symm_apply (F : FreeNonUnitalNonAssocAlgebra R X →ₙₐ[R] A) :
(lift R).symm F = F ∘ of R := rfl
@[simp]
theorem of_comp_lift (f : X → A) : lift R f ∘ of R = f :=
(lift R).left_inv f
@[simp]
theorem lift_unique (f : X → A) (F : FreeNonUnitalNonAssocAlgebra R X →ₙₐ[R] A) :
F ∘ of R = f ↔ F = lift R f :=
(lift R).symm_apply_eq
@[simp]
theorem lift_of_apply (f : X → A) (x) : lift R f (of R x) = f x :=
congr_fun (of_comp_lift _ f) x
@[simp]
theorem lift_comp_of (F : FreeNonUnitalNonAssocAlgebra R X →ₙₐ[R] A) : lift R (F ∘ of R) = F :=
(lift R).apply_symm_apply F
@[ext]
theorem hom_ext {F₁ F₂ : FreeNonUnitalNonAssocAlgebra R X →ₙₐ[R] A}
(h : ∀ x, F₁ (of R x) = F₂ (of R x)) : F₁ = F₂ :=
(lift R).symm.injective <| funext h
end FreeNonUnitalNonAssocAlgebra |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.