From c3818ac49d8cb8d0cf2e4ace5ddfb06ea40649b0 Mon Sep 17 00:00:00 2001 From: Christian Reitwiessner Date: Mon, 30 Nov 2026 11:25:53 +0000 Subject: [PATCH] feat(Computability): complexity of accessors and constructors of the default encodings Show that the accessors and constructors of the default encodings of pairs, sums, options, lists and natural numbers are computable by multi-tape Turing machines in linear time and without additional work space. The generic combinator `transduceOutput` runs a machine and pipes its output through a subsequential transducer. The result that delimiting the output costs time `2 * t + 1` is derived from it. --- Cslib.lean | 4 + .../Computability/Automata/DA/Transducer.lean | 8 + .../Combinators/TransduceOutput.lean | 272 ++++++++++++++++++ .../Turing/MultiTape/Encodings/Basic.lean | 26 +- .../Turing/MultiTape/Encodings/Delimit.lean | 11 + .../Turing/MultiTape/Encodings/List.lean | 96 +++++++ .../Turing/MultiTape/Encodings/Prod.lean | 65 +++++ .../Turing/MultiTape/Encodings/Sum.lean | 138 +++++++++ CslibTests.lean | 1 + CslibTests/MultiTapeEncoding.lean | 83 ++++++ 10 files changed, 702 insertions(+), 2 deletions(-) create mode 100644 Cslib/Computability/Machines/Turing/MultiTape/Combinators/TransduceOutput.lean create mode 100644 Cslib/Computability/Machines/Turing/MultiTape/Encodings/List.lean create mode 100644 Cslib/Computability/Machines/Turing/MultiTape/Encodings/Prod.lean create mode 100644 Cslib/Computability/Machines/Turing/MultiTape/Encodings/Sum.lean create mode 100644 CslibTests/MultiTapeEncoding.lean diff --git a/Cslib.lean b/Cslib.lean index 883a08b0f0..3b41dbf042 100644 --- a/Cslib.lean +++ b/Cslib.lean @@ -107,13 +107,17 @@ public import Cslib.Computability.Languages.SyntacticMonoid public import Cslib.Computability.Machines.Turing.MultiTape.Combinators.AlmostConstant public import Cslib.Computability.Machines.Turing.MultiTape.Combinators.Concatenate public import Cslib.Computability.Machines.Turing.MultiTape.Combinators.Id +public import Cslib.Computability.Machines.Turing.MultiTape.Combinators.TransduceOutput public import Cslib.Computability.Machines.Turing.MultiTape.ConfigBound public import Cslib.Computability.Machines.Turing.MultiTape.Configuration public import Cslib.Computability.Machines.Turing.MultiTape.Deterministic public import Cslib.Computability.Machines.Turing.MultiTape.Encodings.Basic public import Cslib.Computability.Machines.Turing.MultiTape.Encodings.Delimit public import Cslib.Computability.Machines.Turing.MultiTape.Encodings.HeadCases +public import Cslib.Computability.Machines.Turing.MultiTape.Encodings.List public import Cslib.Computability.Machines.Turing.MultiTape.Encodings.Nat +public import Cslib.Computability.Machines.Turing.MultiTape.Encodings.Prod +public import Cslib.Computability.Machines.Turing.MultiTape.Encodings.Sum public import Cslib.Computability.Machines.Turing.MultiTape.Nondeterministic public import Cslib.Computability.Machines.Turing.MultiTape.Plumbing.ClearWork public import Cslib.Computability.Machines.Turing.MultiTape.Plumbing.ExtendTapes diff --git a/Cslib/Computability/Automata/DA/Transducer.lean b/Cslib/Computability/Automata/DA/Transducer.lean index 4b943265a6..cc4a57f8c0 100644 --- a/Cslib/Computability/Automata/DA/Transducer.lean +++ b/Cslib/Computability/Automata/DA/Transducer.lean @@ -112,6 +112,14 @@ theorem evalFrom_unique {spec : State → List InSymbol → List OutSymbol} | nil => exact (hfinal q).symm | cons a w ih => rw [evalFrom, ih, hstep] +/-- The output on `x ++ y` consists of the transition outputs on `x` and the output on `y` from +the state reached after `x`. -/ +theorem evalFrom_append (q : State) (x y : List InSymbol) : + transducer.evalFrom q (x ++ y) = + transducer.toSequentialTransducer.toSubsequential.evalFrom q x ++ + transducer.evalFrom (transducer.mtr q x) y := by + induction x generalizing q <;> simp_all [FLTS.mtr] + /-- The output on a complete input word. -/ abbrev eval (transducer : SubsequentialTransducer State InSymbol OutSymbol) := transducer.evalFrom transducer.start diff --git a/Cslib/Computability/Machines/Turing/MultiTape/Combinators/TransduceOutput.lean b/Cslib/Computability/Machines/Turing/MultiTape/Combinators/TransduceOutput.lean new file mode 100644 index 0000000000..5b341c4d1d --- /dev/null +++ b/Cslib/Computability/Machines/Turing/MultiTape/Combinators/TransduceOutput.lean @@ -0,0 +1,272 @@ +/- +Copyright (c) 2026 Christian Reitwiessner. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Christian Reitwiessner +-/ + +module + +public import Cslib.Computability.Automata.DA.Transducer +public import Cslib.Computability.Machines.Turing.MultiTape.Deterministic +public import Mathlib.Basic.Finite.Prod +public import Mathlib.Data.Set.Finite.List + +/-! +# Transducing the output of a machine + +Composing a Turing machine with a subsequential transducer: +`tm.transduceOutput tr n` behaves like `tm`, but pipes its output through the subsequential +transducer `tr`. Each step of `tm` is performed together with emitting the first symbol of the +word that `tr` emits on the output of this step; the rest of the word is emitted one symbol per +step, with the tape heads standing still. The word still to be emitted is stored in the +state, and has to have a length of at most `n`: longer words are truncated. On the step where `tm` +halts, the final output of `tr` is output (symbol by symbol), and the machine halts with its last +symbol. A step of `tm` thus takes at most `max 1 m` steps, where `m` bounds the words emitted on +transitions, and the final output adds its length. If `l` bounds the final output, the capacity +`n = m + l` suffices. + +## Main definitions + +* `Turing.MultiTapeTM.transduceOutput`: the machine with transduced output. + +## Main results + +* `Turing.MultiTapeTM.ComputesInTimeAndSpace.transduceOutput`: if `tm` outputs `out` in time `t` + and space `s`, and the words emitted by `tr` on transitions and at the end have length at most + `m` and `l`, then `tm.transduceOutput tr (m + l)` outputs `tr.eval out` in time + `max 1 m * t + l` and space `s`. +* `Turing.MultiTapeTM.ComputableInTimeAndSpace.transduceOutput`: the same for computable functions. +-/ + +public section + +namespace Turing.MultiTapeTM + +open Cslib.Automata + +variable {k : ℕ} {Symbol State StateT : Type*} {input : List Symbol} + +/-- The output of `tr` on `w` from state `q`, including the final output if and only if +`halted` holds. -/ +def transduced (tr : SubsequentialTransducer StateT Symbol Symbol) : + (halted : Bool) → StateT → List Symbol → List Symbol + | true, q, w => tr.evalFrom q w + | false, q, w => tr.toSequentialTransducer.evalFrom q w + +attribute [simp] transduced.eq_1 transduced.eq_2 + +/-- A non-halting state of `tm.transduceOutput tr n`. -/ +structure TransduceOutput.Control (State StateT Symbol : Type*) (n : ℕ) where + /-- The state of `tm`, or `none` once `tm` has halted. -/ + tmState : Option State + /-- The state of `tr`. -/ + trState : StateT + /-- The word still to be emitted. -/ + pending : List Symbol + length_pending_le : pending.length ≤ n + +instance [Finite State] [Finite StateT] [Finite Symbol] {n : ℕ} : + Finite (TransduceOutput.Control State StateT Symbol n) := + have := (List.finite_length_le Symbol n).to_subtype + Finite.of_injective (fun c => (c.tmState, c.trState, + (⟨c.pending, c.length_pending_le⟩ : {w : List Symbol // w.length ≤ n}))) + fun ⟨_, _, _, _⟩ ⟨_, _, _, _⟩ h => by simp_all + +/-- The state of `tm.transduceOutput tr n` in which `w` is still to be emitted, where `s` is the +state of `tm` and `qT` the state of `tr`. If `tm` has halted and nothing is left to emit, this is +the halting state `none`. -/ +def TransduceOutput.nextState {n : ℕ} (s : Option State) (qT : StateT) (w : List Symbol) + (hw : w.length ≤ n) : Option (TransduceOutput.Control State StateT Symbol n) := + if s.isNone && w.isEmpty then none else some ⟨s, qT, w, hw⟩ + +open TransduceOutput in +/-- The machine that behaves like `tm`, but pipes its output through the subsequential +transducer `tr`. Its state `Control` consists of the state `tmState` of `tm` (`none` once `tm` +has halted), the state `trState` of `tr`, and the word `pending` still to be emitted, of length +at most `n`. If this word is nonempty, the machine emits its first symbol. Otherwise, it performs +the step of `tm`, computes the word that `tr` emits on the output of this step (including the +final output if `tm` halts), emits its first symbol and stores the rest. The machine halts as +soon as `tm` has halted and everything is emitted. + +A word of length more than `n` is truncated to its first `n` symbols. The machine thus outputs +what `tr` emits only if `n` bounds the lengths of all these words. -/ +noncomputable def transduceOutput (tm : MultiTapeTM k Symbol State) + (tr : SubsequentialTransducer StateT Symbol Symbol) (n : ℕ) : + MultiTapeTM k Symbol (Control State StateT Symbol n) := + ofTr ⟨some tm.q₀, tr.start, [], by simp⟩ fun st inp work => + match st with + | ⟨s, qT, b :: w, hw⟩ => ⟨0, fun _ => (none, 0), some b, nextState s qT w (by grind)⟩ + -- This state is unreachable: `nextState` halts instead. + | ⟨none, _, [], _⟩ => ⟨0, fun _ => (none, 0), none, none⟩ + | ⟨some q, qT, [], _⟩ => + let a := tm.tr q inp work + let w := (transduced tr a.state.isNone qT a.output.toList).take n + ⟨a.inputTape, a.workTapes, w.head?, + nextState a.state (a.output.toList.foldl tr.tr qT) w.tail (by grind)⟩ + +namespace TransduceOutput + +variable (tr : SubsequentialTransducer StateT Symbol Symbol) {n : ℕ} + {tm : MultiTapeTM k Symbol State} + +/-- The word that `tr` emits on the output of a step of `tm` is short. -/ +private lemma length_transduced_le {m l : ℕ} (hemit : ∀ q b, (tr.emit q b).length ≤ m) + (hfinal : ∀ q, (tr.finalOut q).length ≤ l) (halted : Bool) (q : StateT) (b : Option Symbol) : + (transduced tr halted q b.toList).length ≤ m + if halted then l else 0 := by + rcases b <;> cases halted <;> simp <;> grind + +private lemma transduced_append (halted : Bool) (q : StateT) (x y : List Symbol) : + transduced tr halted q (x ++ y) = + tr.toSequentialTransducer.evalFrom q x ++ transduced tr halted (x.foldl tr.tr q) y := by + cases halted <;> apply SubsequentialTransducer.evalFrom_append + +/-- The configuration of `tm.transduceOutput tr n` with nothing to emit that simulates the +configuration `c` of `tm`. It is halted if `c` is. -/ +def cfg (c : Cfg k Symbol State input) : + Cfg k Symbol (Control State StateT Symbol n) input := + ⟨nextState c.state (c.output.foldl tr.tr tr.start) [] (by simp), c.inputPos, c.workTapes, + c.workTapePos, transduced tr c.state.isNone tr.start c.output⟩ + +section Steps + +variable {e : Cfg k Symbol (Control State StateT Symbol n) input} + +/-- With a nonempty pending word, the machine emits its first symbol. -/ +lemma step_of_pending {s : Option State} {qT : StateT} {b : Symbol} {w : List Symbol} + {hw : (b :: w).length ≤ n} (he : e.state = nextState s qT (b :: w) hw) : + (tm.transduceOutput tr n).step e = + { e with state := nextState s qT w (by grind), output := e.output ++ [b] } := by + rw [step_of_state (q := ⟨s, qT, b :: w, hw⟩) (he.trans (by simp [nextState])), transduceOutput, + tr_ofTr] + ext <;> simp [Action.apply] + +/-- With nothing pending, the machine performs the step `a` of `tm`, emits the first symbol of +the word `w` that `tr` emits on the output of `a`, and stores the rest. -/ +lemma step_of_running {q : State} {qT : StateT} {h0 : [].length ≤ n} + (he : e.state = some ⟨some q, qT, [], h0⟩) {a : Action k Symbol State} + (ha : tm.tr q e.inputSymbol e.workTapeSymbols = a) {w : List Symbol} + (hw : transduced tr a.state.isNone qT a.output.toList = w) (hn : w.length ≤ n) : + (tm.transduceOutput tr n).step e = + Action.apply ⟨a.inputTape, a.workTapes, w.head?, + nextState a.state (a.output.toList.foldl tr.tr qT) w.tail (by grind)⟩ e := by + rw [step_of_state he, transduceOutput, tr_ofTr] + ext <;> simp [Action.apply, ha, hw, List.take_of_length_le hn] + +/-- Emitting the pending word `w` takes `w.length` steps: after `i` of them, its first `i` +symbols are emitted, and nothing else has changed. -/ +lemma runFrom_of_pending {s : Option State} {qT : StateT} {w : List Symbol} {hw : w.length ≤ n} + (he : e.state = nextState s qT w hw) {i : ℕ} (hi : i ≤ w.length) : + (tm.transduceOutput tr n).runFrom e i = + { e with state := nextState s qT (w.drop i) (by grind), output := e.output ++ w.take i } := by + induction i generalizing e w with + | zero => simp [runFrom, ← he] + | succ i ih => + obtain ⟨b, w, rfl⟩ := List.exists_cons_of_length_pos (Nat.zero_lt_of_lt hi) + have hs := step_of_pending tr (tm := tm) he + rw [runFrom, Function.iterate_succ_apply, ← runFrom, ih (by rw [hs]) (by simpa using hi), hs] + simp + +end Steps + +/-- A step of `tm` is simulated by a run path of at most `max 1 m` steps, plus `l` steps if `tm` +halts. Its work heads are those of `c` or of the successor of `c`. -/ +lemma exists_runPath_step {m l : ℕ} (hemit : ∀ q b, (tr.emit q b).length ≤ m) + (hfinal : ∀ q, (tr.finalOut q).length ≤ l) {c : Cfg k Symbol State input} (hc : ¬c.Halted) : + ∃ p : (tm.transduceOutput tr (m + l)).RunPath input, p.head = cfg tr c ∧ + p.last = cfg tr (tm.step c) ∧ p.length ≤ max 1 m + (if (tm.step c).Halted then l else 0) ∧ + ∀ e ∈ p, e.workTapePos = c.workTapePos ∨ e.workTapePos = (tm.step c).workTapePos := by + obtain ⟨_ | q, pos, tapes, heads, out⟩ := c + · exact absurd rfl hc + set c : Cfg k Symbol State input := ⟨some q, pos, tapes, heads, out⟩ + set a := tm.tr q c.inputSymbol c.workTapeSymbols + set w := transduced tr a.state.isNone (out.foldl tr.tr tr.start) a.output.toList + have hw : w.length ≤ _ := + length_transduced_le tr hemit hfinal a.state.isNone (out.foldl tr.tr tr.start) a.output + have hs := step_of_running tr (tm := tm) (n := m + l) (e := cfg tr c) (a := a) (w := w) rfl rfl + rfl (hw.trans (by split <;> lia)) + rw [show tm.step c = a.apply c from step_of_state rfl] + refine ⟨.ofDeterministic _ (cfg tr c) (w.tail.length + 1), rfl, ?_, ?_, ?_⟩ + · change (tm.transduceOutput tr (m + l)).runFrom (cfg tr c) (w.tail.length + 1) = _ + rw [runFrom, Function.iterate_succ_apply, ← runFrom, + runFrom_of_pending tr (by rw [hs]; rfl) le_rfl, hs] + simp only [List.drop_length, List.take_length] + ext <;> simp [cfg, nextState, Action.apply, transduced_append, ← List.take_one, + ← List.drop_one, w, c] + · change _ + 1 ≤ _ + simp only [List.length_tail, Cfg.Halted, Action.apply_state, ← Option.isNone_iff_eq_none] + lia + · rintro _ ⟨⟨_ | i, hi⟩, rfl⟩ + · exact .inl rfl + · refine .inr ?_ + change ((tm.transduceOutput tr (m + l)).runFrom (cfg tr c) (i + 1)).workTapePos = _ + rw [runFrom, Function.iterate_succ_apply, ← runFrom, runFrom_of_pending tr (by rw [hs]; rfl) + (Nat.le_of_lt_succ (Nat.lt_of_succ_lt_succ hi)), hs] + rfl + +/-- `t` steps of `tm` are simulated by a run path of at most `max 1 m * t` steps, plus `l` steps +if `tm` halts, whose work heads are those of the run of `tm`. -/ +lemma exists_runPath {m l : ℕ} (hemit : ∀ q b, (tr.emit q b).length ≤ m) + (hfinal : ∀ q, (tr.finalOut q).length ≤ l) (c : Cfg k Symbol State input) (t : ℕ) : + ∃ p : (tm.transduceOutput tr (m + l)).RunPath input, p.head = cfg tr c ∧ + p.last = cfg tr (tm.runFrom c t) ∧ + p.length ≤ max 1 m * t + (if (tm.runFrom c t).Halted then l else 0) ∧ + ∀ e ∈ p, ∃ i ≤ t, e.workTapePos = (tm.runFrom c i).workTapePos := by + induction t with + | zero => exact ⟨.singleton _ (cfg tr c), rfl, rfl, by simp, fun _ ⟨_, h⟩ => ⟨0, le_rfl, h ▸ rfl⟩⟩ + | succ t ih => + obtain ⟨p, hh, hl, hlen, hmem⟩ := ih + have hsucc : tm.runFrom c (t + 1) = tm.step (tm.runFrom c t) := by + rw [runFrom, Function.iterate_succ_apply', ← runFrom] + rw [hsucc, Nat.mul_succ] + by_cases hc : (tm.runFrom c t).Halted + · rw [step_of_halt hc] + exact ⟨p, hh, hl, by lia, fun e he => (hmem e he).imp fun _ ⟨hi, h⟩ => ⟨by lia, h⟩⟩ + · obtain ⟨p', hh', hl', hlen', hmem'⟩ := exists_runPath_step tr hemit hfinal hc + simp only [hc, ↓reduceIte] at hlen + refine ⟨p.smash p' (hl.trans hh'.symm), by simp [hh], by simp [hl'], by simp; omega, + fun e he => ?_⟩ + rcases RelSeries.mem_or_mem_of_mem_smash he with he | he + · exact (hmem e he).imp fun _ ⟨hi, h⟩ => ⟨by lia, h⟩ + · exact (hmem' e he).elim (⟨t, by lia, ·⟩) (⟨t + 1, le_rfl, hsucc ▸ ·⟩) + +end TransduceOutput + +open TransduceOutput in +/-- If `tm` outputs `out` in time `t` and space `s`, and the words emitted by `tr` on its +transitions and at the end have length at most `m` and `l`, then `tm.transduceOutput tr (m + l)` +outputs `tr.eval out` in time `max 1 m * t + l` and space `s`. -/ +theorem ComputesInTimeAndSpace.transduceOutput {tm : MultiTapeTM k Symbol State} + (tr : SubsequentialTransducer StateT Symbol Symbol) {m l : ℕ} + (hemit : ∀ q b, (tr.emit q b).length ≤ m) (hfinal : ∀ q, (tr.finalOut q).length ≤ l) + {out : List Symbol} {t s : ℕ} (h : tm.ComputesInTimeAndSpace input out t s) : + (tm.transduceOutput tr (m + l)).ComputesInTimeAndSpace input (tr.eval out) + (max 1 m * t + l) s := by + obtain ⟨p, hh, halt, rfl, ht, hs⟩ := computesInTimeAndSpace_iff_exists_runPath.mp h + obtain ⟨q, hqh, hql, hlen, hmem⟩ := exists_runPath tr hemit hfinal p.head p.length + rw [← runPath_last_eq_runFrom] at hql hlen + simp only [eq_true halt, ↓reduceIte] at hlen + refine computesInTimeAndSpace_iff_exists_runPath.mpr ⟨q, by rw [hqh, hh]; rfl, + by rw [hql]; simp [cfg, nextState, halt], by rw [hql]; simp [cfg, halt], + hlen.trans (by grw [ht]), ?_⟩ + refine (MultiTapeNTM.RunPath.space_le_sum_card _ (S := p.visitedByTapeHead) + fun e he l => ?_).trans hs + obtain ⟨i, hi, h⟩ := hmem e he + exact p.mem_visitedByTapeHead.mpr + ⟨_, ⟨⟨i, by lia⟩, runPath_apply_eq_runFrom ..⟩, (congrFun h l).symm⟩ + +/-- If `f` is computable in time `t` and space `s` with output encoding `encOut`, and the finite +subsequential transducer `tr` translates `encOut b` to `encOut' (g b)`, then `g ∘ f` is +computable in time `max 1 m * t + l` and space `s` with output encoding `encOut'`, where `m` and +`l` bound the lengths of the words emitted by `tr` on its transitions and at the end. -/ +theorem ComputableInTimeAndSpace.transduceOutput {α β γ : Type*} {f : α → β} {g : β → γ} + {encIn : α ↪ List Bool} {encOut : β ↪ List Bool} {encOut' : γ ↪ List Bool} {t s : α → ℕ} + {StateT : Type} [Finite StateT] (tr : SubsequentialTransducer StateT Bool Bool) {m l : ℕ} + (hemit : ∀ q b, (tr.emit q b).length ≤ m) (hfinal : ∀ q, (tr.finalOut q).length ≤ l) + (hg : ∀ b, tr.eval (encOut b) = encOut' (g b)) + (h : ComputableInTimeAndSpace f encIn encOut t s) : + ComputableInTimeAndSpace (g ∘ f) encIn encOut' (fun a => max 1 m * t a + l) s := by + obtain ⟨k, State, _, tm, htm⟩ := h + exact ⟨k, _, inferInstance, tm.transduceOutput tr (m + l), + fun a => hg (f a) ▸ (htm a).transduceOutput tr hemit hfinal⟩ + +end Turing.MultiTapeTM diff --git a/Cslib/Computability/Machines/Turing/MultiTape/Encodings/Basic.lean b/Cslib/Computability/Machines/Turing/MultiTape/Encodings/Basic.lean index e3ef38d657..587f12056f 100644 --- a/Cslib/Computability/Machines/Turing/MultiTape/Encodings/Basic.lean +++ b/Cslib/Computability/Machines/Turing/MultiTape/Encodings/Basic.lean @@ -7,7 +7,8 @@ Authors: Christian Reitwiessner module public import Cslib.Computability.Encoding.Basic -public import Cslib.Computability.Machines.Turing.MultiTape.Deterministic +public import Cslib.Computability.Machines.Turing.MultiTape.Combinators.AlmostConstant +public import Cslib.Computability.Machines.Turing.MultiTape.Transducer /-! # Machines on encoded values @@ -23,6 +24,10 @@ words, and this function realizes the function on values in the sense of `Cslib. on Boolean words computes every function realized by it, within the same bounds. * `Turing.MultiTapeTM.ComputableInTimeAndSpace.of_realizes`: a function realized by a computable function on Boolean words is computable within the same bounds. +* `Turing.MultiTapeTM.ComputableInTimeAndSpace.congr_out`: the output type and encoding of a + computable function can be replaced by ones that yield the same code words. +* `Turing.MultiTapeTM.computableInTimeAndSpace_const`: constant functions are computable in + constant time and zero space. -/ public section @@ -31,7 +36,7 @@ namespace Turing.MultiTapeTM open Cslib.Encoding -variable {α β : Type*} {encIn : α ↪ List Bool} {encOut : β ↪ List Bool} +variable {α β γ : Type*} {encIn : α ↪ List Bool} {encOut : β ↪ List Bool} variable {f : α → β} {g : List Bool → List Bool} {t s : List Bool → ℕ} @@ -51,4 +56,21 @@ theorem ComputableInTimeAndSpace.of_realizes (hg : ComputableInTimeAndSpace g en obtain ⟨k, State, hfinite, tm, htm⟩ := hg exact ⟨k, State, hfinite, tm, htm.of_realizes h⟩ +/-- If `f` is computable, then so is every `f'` whose values have the same code words, possibly +with another output type and encoding, within the same bounds. -/ +theorem ComputableInTimeAndSpace.congr_out {f : α → β} {f' : α → γ} {encOut' : γ ↪ List Bool} + {t s : α → ℕ} (h : ComputableInTimeAndSpace f encIn encOut t s) + (henc : ∀ a, encOut' (f' a) = encOut (f a)) : + ComputableInTimeAndSpace f' encIn encOut' t s := by + obtain ⟨k, State, hfinite, tm, htm⟩ := h + exact ⟨k, State, hfinite, tm, fun a => by rw [henc a]; exact htm a⟩ + +/-- A constant function is computable in the length of the code of its value plus two steps, and +in zero space, relative to every input encoding. -/ +theorem computableInTimeAndSpace_const (b : β) : + ComputableInTimeAndSpace (fun _ : α => b) encIn encOut (fun _ => (encOut b).length + 2) + (fun _ => 0) := + (computableInTimeAndSpace_almostConstTime _ ∅ (encOut b) (by simp)).mono + (fun _ => by simp only [almostConstTime, Finset.sup_empty, bot_eq_zero]; lia) fun _ => le_rfl + end Turing.MultiTapeTM diff --git a/Cslib/Computability/Machines/Turing/MultiTape/Encodings/Delimit.lean b/Cslib/Computability/Machines/Turing/MultiTape/Encodings/Delimit.lean index c22dd13dc9..3d1e86347c 100644 --- a/Cslib/Computability/Machines/Turing/MultiTape/Encodings/Delimit.lean +++ b/Cslib/Computability/Machines/Turing/MultiTape/Encodings/Delimit.lean @@ -7,6 +7,7 @@ Authors: Christian Reitwiessner module public import Cslib.Computability.Encoding.Basic +public import Cslib.Computability.Machines.Turing.MultiTape.Combinators.TransduceOutput public import Cslib.Computability.Machines.Turing.MultiTape.Transducer import Mathlib.Tactic.DeriveFintype @@ -30,6 +31,8 @@ and `undelimitAll`. * `Cslib.Encoding.undelimitAll_delimit_append` decodes a leading codeword and continues decoding the suffix. * `Turing.MultiTapeTM.computableInTimeAndSpace_delimit` bounds the cost of writing a codeword. +* `Turing.MultiTapeTM.ComputableInTimeAndSpace.delimit`: a computable function is computable with + the delimited output encoding `Cslib.Encoding.encDelimited`, in time `2 * t + 1`. * `Turing.MultiTapeTM.computableInTimeAndSpace_undelimit` and `Turing.MultiTapeTM.computableInTimeAndSpace_undelimitOr` bound the cost of decoding the first word, with a configurable default on empty input for `undelimitOr`. @@ -106,6 +109,14 @@ theorem computableInTimeAndSpace_delimit : (computableInTimeAndSpace_of_subsequential delimitTransducer delimit evalFrom_delimit).mono (fun _ => by lia [length_delimit]) fun _ => le_rfl +/-- A function computable with some output encoding is computable with the delimited output +encoding, in at most twice the time plus one step, and in the same space. -/ +theorem ComputableInTimeAndSpace.delimit {α β : Type*} {f : α → β} {encIn : α ↪ List Bool} + {encOut : β ↪ List Bool} {t s : α → ℕ} (h : ComputableInTimeAndSpace f encIn encOut t s) : + ComputableInTimeAndSpace f encIn (encDelimited encOut) (fun a => 2 * t a + 1) s := + h.transduceOutput (g := id) delimitTransducer (m := 2) (l := 1) (by simp [delimitTransducer]) + (by simp [delimitTransducer]) fun b => evalFrom_delimit _ + /-! ### The word whose delimited code starts the input -/ /-- At the start of the input, about to read a tag, about to read a data bit, or past the diff --git a/Cslib/Computability/Machines/Turing/MultiTape/Encodings/List.lean b/Cslib/Computability/Machines/Turing/MultiTape/Encodings/List.lean new file mode 100644 index 0000000000..9044f9a744 --- /dev/null +++ b/Cslib/Computability/Machines/Turing/MultiTape/Encodings/List.lean @@ -0,0 +1,96 @@ +/- +Copyright (c) 2026 Christian Reitwiessner. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Christian Reitwiessner +-/ + +module + +public import Cslib.Computability.Machines.Turing.MultiTape.Combinators.Concatenate +public import Cslib.Computability.Machines.Turing.MultiTape.Encodings.Basic +public import Cslib.Computability.Machines.Turing.MultiTape.Encodings.Delimit + +/-! +# Complexity of lists + +The accessors of the list encoding `Cslib.Encoding.encList` are computable in linear time and zero +space, independently of the encoding of the elements. Lists are built from machines that compute +their parts from the same input. + +## Main results + +* `Turing.MultiTapeTM.ComputableInTimeAndSpace.list_cons`, + `Turing.MultiTapeTM.ComputableInTimeAndSpace.list_append`, + `Turing.MultiTapeTM.ComputableInTimeAndSpace.list_singleton`: building lists from computable + functions. +* `Turing.MultiTapeTM.computableInTimeAndSpace_list_tail`, + `Turing.MultiTapeTM.computableInTimeAndSpace_list_headD`: the tail and the head with a default. +* `Turing.MultiTapeTM.computableInTimeAndSpace_list_isEmpty`: the emptiness test. +* `Turing.MultiTapeTM.computableInTimeAndSpace_list_flatten`: concatenating a list of lists. +-/ + +public section + +namespace Turing.MultiTapeTM + +open Cslib.Encoding + +variable {α γ : Type*} {enc : α ↪ List Bool} {encIn : γ ↪ List Bool} + +/-! ### Constructors -/ + +/-- Prepending a computable element to a computable list is computable in time `4 * t₁ + t₂ + 4` +and space `3 * (s₁ + s₂)`: the machine for the element runs with its output delimited, the input +is rewound, and the machine for the list appends its output. -/ +theorem ComputableInTimeAndSpace.list_cons {f₁ : γ → α} {f₂ : γ → List α} {t₁ t₂ s₁ s₂ : γ → ℕ} + (h₁ : ComputableInTimeAndSpace f₁ encIn enc t₁ s₁) + (h₂ : ComputableInTimeAndSpace f₂ encIn (encList enc) t₂ s₂) : + ComputableInTimeAndSpace (fun x => f₁ x :: f₂ x) encIn (encList enc) + (fun x => 4 * t₁ x + t₂ x + 4) (fun x => 3 * (s₁ x + s₂ x)) := + (h₁.delimit.concatenate h₂ fun _ => rfl).mono (fun _ => by lia) fun _ => le_rfl + +/-- Concatenating two computable lists is computable in time `2 * t₁ + t₂ + 2` and space +`3 * (s₁ + s₂)`: the codes of the lists are concatenated. -/ +theorem ComputableInTimeAndSpace.list_append {f₁ f₂ : γ → List α} {t₁ t₂ s₁ s₂ : γ → ℕ} + (h₁ : ComputableInTimeAndSpace f₁ encIn (encList enc) t₁ s₁) + (h₂ : ComputableInTimeAndSpace f₂ encIn (encList enc) t₂ s₂) : + ComputableInTimeAndSpace (fun x => f₁ x ++ f₂ x) encIn (encList enc) + (fun x => 2 * t₁ x + t₂ x + 2) (fun x => 3 * (s₁ x + s₂ x)) := + h₁.concatenate h₂ fun _ => encList_append .. + +/-- The list with one computable element is computable in time `2 * t + 1` and space `s`: its +code is the delimited code of the element. -/ +theorem ComputableInTimeAndSpace.list_singleton {f : γ → α} {t s : γ → ℕ} + (h : ComputableInTimeAndSpace f encIn enc t s) : + ComputableInTimeAndSpace (fun x => [f x]) encIn (encList enc) (fun x => 2 * t x + 1) s := + h.delimit.congr_out fun x => encList_singleton enc (f x) + +/-! ### Accessors -/ + +/-- The tail of a list is computable in linear time and zero space. -/ +theorem computableInTimeAndSpace_list_tail : + ComputableInTimeAndSpace (List.tail : List α → List α) (encList enc) (encList enc) + (fun l => 2 * (encList enc l).length + 1) (fun _ => 0) := + computableInTimeAndSpace_dropDelimited.of_realizes fun l => by cases l <;> simp + +/-- The head of a list with a fixed default `d` is computable in linear time and zero space. -/ +theorem computableInTimeAndSpace_list_headD (d : α) : + ComputableInTimeAndSpace (List.headD · d : List α → α) (encList enc) enc + (fun l => 2 * (encList enc l).length + (enc d).length + 1) (fun _ => 0) := + (computableInTimeAndSpace_undelimitOr (enc d)).of_realizes fun l => by cases l <;> simp + +/-- The emptiness test is computable in constant time and zero space, since it is constant except +on the empty list. -/ +theorem computableInTimeAndSpace_list_isEmpty : + ComputableInTimeAndSpace (List.isEmpty : List α → Bool) (encList enc) encBool + (fun _ => 4) (fun _ => 0) := + (computableInTimeAndSpace_almostConstTime List.isEmpty {[]} [false] + fun l hl => by cases l <;> simp_all).mono (fun _ => by simp [almostConstTime]) fun _ => le_rfl + +/-- Concatenating a list of lists is computable in linear time and zero space. -/ +theorem computableInTimeAndSpace_list_flatten : + ComputableInTimeAndSpace (List.flatten : List (List α) → List α) (encList (encList enc)) + (encList enc) (fun l => 2 * (encList (encList enc) l).length + 1) (fun _ => 0) := + computableInTimeAndSpace_undelimitAll.of_realizes fun l => by induction l <;> simp [*] + +end Turing.MultiTapeTM diff --git a/Cslib/Computability/Machines/Turing/MultiTape/Encodings/Prod.lean b/Cslib/Computability/Machines/Turing/MultiTape/Encodings/Prod.lean new file mode 100644 index 0000000000..d0e52ad75c --- /dev/null +++ b/Cslib/Computability/Machines/Turing/MultiTape/Encodings/Prod.lean @@ -0,0 +1,65 @@ +/- +Copyright (c) 2026 Christian Reitwiessner. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Christian Reitwiessner +-/ + +module + +public import Cslib.Computability.Machines.Turing.MultiTape.Combinators.Concatenate +public import Cslib.Computability.Machines.Turing.MultiTape.Encodings.Basic +public import Cslib.Computability.Machines.Turing.MultiTape.Encodings.Delimit + +/-! +# Complexity of pairs + +The components of a pair and the first component of a dependent pair are obtained from the code of +the pair in linear time and zero space, independently of the encodings of the components. A pair +is formed from two machines that compute its components from the same input. + +## Main results + +* `Turing.MultiTapeTM.computableInTimeAndSpace_prod_fst`, + `Turing.MultiTapeTM.computableInTimeAndSpace_prod_snd`: the components of a pair. +* `Turing.MultiTapeTM.computableInTimeAndSpace_sigma_fst`: the first component of a dependent + pair. +* `Turing.MultiTapeTM.ComputableInTimeAndSpace.prod_mk`: pairing two computable functions. +-/ + +public section + +namespace Turing.MultiTapeTM + +open Cslib.Encoding + +variable {α β γ : Type*} {enc₁ : α ↪ List Bool} {enc₂ : β ↪ List Bool} + +/-- The first projection is computable in linear time and zero space. -/ +theorem computableInTimeAndSpace_prod_fst : + ComputableInTimeAndSpace Prod.fst (encProd enc₁ enc₂) enc₁ + (fun p => 2 * (encProd enc₁ enc₂ p).length + 1) (fun _ => 0) := + computableInTimeAndSpace_undelimit.of_realizes fun _ => by simp + +/-- The second projection is computable in linear time and zero space. -/ +theorem computableInTimeAndSpace_prod_snd : + ComputableInTimeAndSpace Prod.snd (encProd enc₁ enc₂) enc₂ + (fun p => 2 * (encProd enc₁ enc₂ p).length + 1) (fun _ => 0) := + computableInTimeAndSpace_dropDelimited.of_realizes fun _ => by simp + +/-- The first component of a dependent pair is computable in linear time and zero space. -/ +theorem computableInTimeAndSpace_sigma_fst {δ : α → Type*} {encδ : ∀ a, δ a ↪ List Bool} : + ComputableInTimeAndSpace Sigma.fst (encSigma enc₁ encδ) enc₁ + (fun x => 2 * (encSigma enc₁ encδ x).length + 1) (fun _ => 0) := + computableInTimeAndSpace_undelimit.of_realizes fun _ => by simp + +/-- Pairing two computable functions is computable in time `4 * t₁ + t₂ + 4` and space +`3 * (s₁ + s₂)`: the first machine runs with its output delimited, the input is rewound, and the +second machine appends its output. -/ +theorem ComputableInTimeAndSpace.prod_mk {f₁ : γ → α} {f₂ : γ → β} {encIn : γ ↪ List Bool} + {t₁ t₂ s₁ s₂ : γ → ℕ} (h₁ : ComputableInTimeAndSpace f₁ encIn enc₁ t₁ s₁) + (h₂ : ComputableInTimeAndSpace f₂ encIn enc₂ t₂ s₂) : + ComputableInTimeAndSpace (fun x => (f₁ x, f₂ x)) encIn (encProd enc₁ enc₂) + (fun x => 4 * t₁ x + t₂ x + 4) (fun x => 3 * (s₁ x + s₂ x)) := + (h₁.delimit.concatenate h₂ fun _ => rfl).mono (fun _ => by lia) fun _ => le_rfl + +end Turing.MultiTapeTM diff --git a/Cslib/Computability/Machines/Turing/MultiTape/Encodings/Sum.lean b/Cslib/Computability/Machines/Turing/MultiTape/Encodings/Sum.lean new file mode 100644 index 0000000000..6e104ccdce --- /dev/null +++ b/Cslib/Computability/Machines/Turing/MultiTape/Encodings/Sum.lean @@ -0,0 +1,138 @@ +/- +Copyright (c) 2026 Christian Reitwiessner. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Christian Reitwiessner +-/ + +module + +public import Cslib.Computability.Machines.Turing.MultiTape.Combinators.Concatenate +public import Cslib.Computability.Machines.Turing.MultiTape.Encodings.Basic +public import Cslib.Computability.Machines.Turing.MultiTape.Encodings.HeadCases + +/-! +# Complexity of sums and options + +The accessors of the sum and option encodings `Cslib.Encoding.encSum` and +`Cslib.Encoding.encOption` only inspect or change the tag bit of a code word. They are computable +in linear time and zero space, independently of the encodings of the components. The constructors +prepend a tag bit to the output of a machine computing the component. + +## Main results + +* `Turing.MultiTapeTM.ComputableInTimeAndSpace.sum_inl`, + `Turing.MultiTapeTM.ComputableInTimeAndSpace.sum_inr`, + `Turing.MultiTapeTM.ComputableInTimeAndSpace.option_some`: the constructors, applied to a + computable function. +* `Turing.MultiTapeTM.computableInTimeAndSpace_sum_isLeft`, + `Turing.MultiTapeTM.computableInTimeAndSpace_sum_isRight`, + `Turing.MultiTapeTM.computableInTimeAndSpace_option_isSome`, + `Turing.MultiTapeTM.computableInTimeAndSpace_option_isNone`: the tests. +* `Turing.MultiTapeTM.computableInTimeAndSpace_sum_swap`: swapping the components of a sum. +* `Turing.MultiTapeTM.computableInTimeAndSpace_sum_getLeft?`, + `Turing.MultiTapeTM.computableInTimeAndSpace_sum_getRight?`, + `Turing.MultiTapeTM.computableInTimeAndSpace_option_getD`: the partial accessors. +-/ + +public section + +namespace Turing.MultiTapeTM + +open Cslib.Encoding + +variable {α β γ : Type*} {enc₁ : α ↪ List Bool} {enc₂ : β ↪ List Bool} + {encIn : γ ↪ List Bool} {t s : γ → ℕ} + +/-! ### Constructors -/ + +/-- `Sum.inl` of a computable function is computable in time `t + 8` and space `3 * s`: a machine +emitting the tag runs first, the input is rewound, and the machine computing the component appends +its output. -/ +theorem ComputableInTimeAndSpace.sum_inl {f : γ → α} + (h : ComputableInTimeAndSpace f encIn enc₁ t s) : + ComputableInTimeAndSpace (fun x => (Sum.inl (f x) : α ⊕ β)) encIn (encSum enc₁ enc₂) + (fun x => t x + 8) (fun x => 3 * s x) := + ((computableInTimeAndSpace_const (encOut := encBool) false).concatenate h fun _ => rfl).mono + (by grind) fun _ => by lia + +/-- `Sum.inr` of a computable function is computable in time `t + 8` and space `3 * s`, as for +`sum_inl`. -/ +theorem ComputableInTimeAndSpace.sum_inr {f : γ → β} + (h : ComputableInTimeAndSpace f encIn enc₂ t s) : + ComputableInTimeAndSpace (fun x => (Sum.inr (f x) : α ⊕ β)) encIn (encSum enc₁ enc₂) + (fun x => t x + 8) (fun x => 3 * s x) := + ((computableInTimeAndSpace_const (encOut := encBool) true).concatenate h fun _ => rfl).mono + (by grind) fun _ => by lia + +/-- `some` of a computable function is computable in time `t + 8` and space `3 * s`, as for +`sum_inl`. -/ +theorem ComputableInTimeAndSpace.option_some {f : γ → α} + (h : ComputableInTimeAndSpace f encIn enc₁ t s) : + ComputableInTimeAndSpace (fun x => some (f x)) encIn (encOption enc₁) + (fun x => t x + 8) (fun x => 3 * s x) := + ((computableInTimeAndSpace_const (encOut := encBool) true).concatenate h fun _ => rfl).mono + (by grind) fun _ => by lia + +/-! ### Sums -/ + +/-- `Sum.isLeft` is computable in linear time and zero space. -/ +theorem computableInTimeAndSpace_sum_isLeft : + ComputableInTimeAndSpace (Sum.isLeft : α ⊕ β → Bool) (encSum enc₁ enc₂) encBool + (fun x => 2 * (encSum enc₁ enc₂ x).length + 2) (fun _ => 0) := + ((computableInTimeAndSpace_headCases [] (fun b => [!b]) fun _ => false).of_realizes + fun x => by cases x <;> simp).mono (fun _ => by simp) fun _ => le_rfl + +/-- `Sum.isRight` is computable in linear time and zero space. -/ +theorem computableInTimeAndSpace_sum_isRight : + ComputableInTimeAndSpace (Sum.isRight : α ⊕ β → Bool) (encSum enc₁ enc₂) encBool + (fun x => 2 * (encSum enc₁ enc₂ x).length + 2) (fun _ => 0) := + ((computableInTimeAndSpace_headCases [] (fun b => [b]) fun _ => false).of_realizes + fun x => by cases x <;> simp).mono (fun _ => by simp) fun _ => le_rfl + +/-- `Sum.swap` is computable in linear time and zero space. -/ +theorem computableInTimeAndSpace_sum_swap : + ComputableInTimeAndSpace (Sum.swap : α ⊕ β → β ⊕ α) (encSum enc₁ enc₂) (encSum enc₂ enc₁) + (fun x => 2 * (encSum enc₁ enc₂ x).length + 2) (fun _ => 0) := + ((computableInTimeAndSpace_headCases [] (fun b => [!b]) fun _ => true).of_realizes + fun x => by cases x <;> simp).mono (fun _ => by simp) fun _ => le_rfl + +/-- `Sum.getLeft?` is computable in linear time and zero space. -/ +theorem computableInTimeAndSpace_sum_getLeft? : + ComputableInTimeAndSpace (Sum.getLeft? : α ⊕ β → Option α) (encSum enc₁ enc₂) + (encOption enc₁) (fun x => 2 * (encSum enc₁ enc₂ x).length + 2) (fun _ => 0) := + ((computableInTimeAndSpace_headCases [] (fun b => [!b]) fun b => !b).of_realizes + fun x => by cases x <;> simp).mono (fun _ => by simp) fun _ => le_rfl + +/-- `Sum.getRight?` is computable in linear time and zero space. -/ +theorem computableInTimeAndSpace_sum_getRight? : + ComputableInTimeAndSpace (Sum.getRight? : α ⊕ β → Option β) (encSum enc₁ enc₂) + (encOption enc₂) (fun x => 2 * (encSum enc₁ enc₂ x).length + 2) (fun _ => 0) := + ((computableInTimeAndSpace_headCases [] (fun b => [b]) fun b => b).of_realizes + fun x => by cases x <;> simp).mono (fun _ => by simp) fun _ => le_rfl + +/-! ### Options -/ + +/-- `Option.isSome` is computable in constant time and zero space, since it is constant except on +`none`. -/ +theorem computableInTimeAndSpace_option_isSome : + ComputableInTimeAndSpace (Option.isSome : Option α → Bool) (encOption enc₁) encBool + (fun _ => 5) (fun _ => 0) := + (computableInTimeAndSpace_almostConstTime Option.isSome {none} [true] + fun o ho => by cases o <;> simp_all).mono (fun _ => by simp [almostConstTime]) fun _ => le_rfl + +/-- `Option.isNone` is computable in constant time and zero space, since it is constant except on +`none`. -/ +theorem computableInTimeAndSpace_option_isNone : + ComputableInTimeAndSpace (Option.isNone : Option α → Bool) (encOption enc₁) encBool + (fun _ => 5) (fun _ => 0) := + (computableInTimeAndSpace_almostConstTime Option.isNone {none} [false] + fun o ho => by cases o <;> simp_all).mono (fun _ => by simp [almostConstTime]) fun _ => le_rfl + +/-- `Option.getD` with a fixed default `d` is computable in linear time and zero space. -/ +theorem computableInTimeAndSpace_option_getD (d : α) : + ComputableInTimeAndSpace (Option.getD · d : Option α → α) (encOption enc₁) enc₁ + (fun o => 2 * (encOption enc₁ o).length + (enc₁ d).length + 1) (fun _ => 0) := + ((computableInTimeAndSpace_headCases [] (fun b => if b then [] else enc₁ d) + fun b => b).of_realizes fun o => by cases o <;> simp).mono (fun _ => by simp) fun _ => le_rfl + +end Turing.MultiTapeTM diff --git a/CslibTests.lean b/CslibTests.lean index 4661c42218..51af45e810 100644 --- a/CslibTests.lean +++ b/CslibTests.lean @@ -33,6 +33,7 @@ import CslibTests.Modal.Stlc import CslibTests.Modal.UnimodalCube import CslibTests.MultiTapeComplexity import CslibTests.MultiTapeConcatenate +import CslibTests.MultiTapeEncoding import CslibTests.PACLearning import CslibTests.PFunctor import CslibTests.PFunctorFree diff --git a/CslibTests/MultiTapeEncoding.lean b/CslibTests/MultiTapeEncoding.lean new file mode 100644 index 0000000000..1550bac148 --- /dev/null +++ b/CslibTests/MultiTapeEncoding.lean @@ -0,0 +1,83 @@ +/- +Copyright (c) 2026 Christian Reitwiessner. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Christian Reitwiessner +-/ + +import Cslib.Computability.Machines.Turing.MultiTape.Combinators.Id +import Cslib.Computability.Machines.Turing.MultiTape.Encodings.List +import Cslib.Computability.Machines.Turing.MultiTape.Encodings.Nat +import Cslib.Computability.Machines.Turing.MultiTape.Encodings.Prod +import Cslib.Computability.Machines.Turing.MultiTape.Encodings.Sum +import Mathlib.Data.Nat.Size + +namespace CslibTests.MultiTapeEncoding + +open Turing.MultiTapeTM Cslib.Encoding + +/-! ### Pairs -/ + +example : ComputableInTimeAndSpace (fun n : ℕ => (n + 1, n.bodd)) encNat (encProd encNat encBool) + (fun n => 10 * (encNat n).length + 14) (fun _ => 0) := + (computableInTimeAndSpace_nat_succ.prod_mk computableInTimeAndSpace_nat_bodd).mono + (fun _ => by lia) fun _ => by simp + +-- Accessors and constructors compose across types. +example : ComputableInTimeAndSpace (fun x : ℕ ⊕ Bool => (x.isLeft, x.swap)) (encSum encNat encBool) + (encProd encBool (encSum encBool encNat)) + (fun x => 10 * (encSum encNat encBool x).length + 14) (fun _ => 0) := + (computableInTimeAndSpace_sum_isLeft.prod_mk computableInTimeAndSpace_sum_swap).mono + (fun _ => by lia) fun _ => by lia + +/-! ### Sums and options -/ + +example : ComputableInTimeAndSpace (fun x : ℕ ⊕ Bool => (x.getLeft?, x.getRight?)) + (encSum encNat encBool) (encProd (encOption encNat) (encOption encBool)) + (fun x => 10 * (encSum encNat encBool x).length + 14) (fun _ => 0) := + (computableInTimeAndSpace_sum_getLeft?.prod_mk computableInTimeAndSpace_sum_getRight?).mono + (fun _ => by lia) fun _ => by lia + +example : ComputableInTimeAndSpace (fun o : Option ℕ => (o.isSome, o.isNone)) (encOption encNat) + (encProd encBool encBool) (fun _ => 29) (fun _ => 0) := + (computableInTimeAndSpace_option_isSome.prod_mk computableInTimeAndSpace_option_isNone).mono + (fun _ => le_rfl) fun _ => le_rfl + +-- The default of `getD` is part of the machine and contributes to the running time. +example : ComputableInTimeAndSpace (Option.getD · 6 : Option ℕ → ℕ) (encOption encNat) encNat + (fun o => 2 * (encOption encNat o).length + 4) (fun _ => 0) := + (computableInTimeAndSpace_option_getD 6).mono + (fun _ => by simp [show encNat 6 = [false, true, true] by decide]) fun _ => le_rfl + +/-! ### Lists -/ + +example : ComputableInTimeAndSpace (fun l : List ℕ => l.headD 0 :: l.tail) (encList encNat) + (encList encNat) (fun l => 10 * (encList encNat l).length + 9) (fun _ => 0) := + ((computableInTimeAndSpace_list_headD 0).list_cons computableInTimeAndSpace_list_tail).mono + (fun _ => by simp; lia) fun _ => le_rfl + +example : ComputableInTimeAndSpace (fun l : List ℕ => l ++ l.tail) (encList encNat) + (encList encNat) (fun l => 4 * (encList encNat l).length + 5) (fun _ => 0) := + (computableInTimeAndSpace_id.list_append computableInTimeAndSpace_list_tail).mono + (fun _ => by lia) fun _ => le_rfl + +example : ComputableInTimeAndSpace (fun n : ℕ => [n + 1]) encNat (encList encNat) + (fun n => 4 * (encNat n).length + 5) (fun _ => 0) := + computableInTimeAndSpace_nat_succ.list_singleton.mono (fun _ => by lia) fun _ => le_rfl + +example : ComputableInTimeAndSpace (fun l : List (List ℕ) => (l.isEmpty, l.flatten)) + (encList (encList encNat)) (encProd encBool (encList encNat)) + (fun l => 2 * (encList (encList encNat) l).length + 21) (fun _ => 0) := + (computableInTimeAndSpace_list_isEmpty.prod_mk computableInTimeAndSpace_list_flatten).mono + (fun _ => by lia) fun _ => le_rfl + +/-! ### Natural numbers -/ + +example : ComputableInTimeAndSpace (· + 1) encNat encNat (fun n => 2 * n.size + 2) (fun _ => 0) := + computableInTimeAndSpace_nat_succ.mono (fun n => by grind [Nat.size_eq_bits_len]) fun _ => le_rfl + +example : ComputableInTimeAndSpace (fun n : ℕ => (decide (n = 0), n / 2)) encNat + (encProd encBool encNat) (fun n => 2 * (encNat n).length + 21) (fun _ => 0) := + (computableInTimeAndSpace_nat_decide_eq_zero.prod_mk computableInTimeAndSpace_nat_div_two).mono + (fun _ => by lia) fun _ => le_rfl + +end CslibTests.MultiTapeEncoding