Add Turing-machine tapes

138ab807Claude · 6d agoparent 92f3039ffiles
Tapes are Int-indexed functions with a head, so equal contents means
equal tapes. Blank, ofWord, read, write and move, with the lemmas that
writing back the symbol read is a no-op and that ofWord [] is blank.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Diff

2 files changed +70 -0
M PvsNP.lean +1 -0
@@ -1,6 +1,7 @@
11 import PvsNP.Basic.Finite
22 import PvsNP.Basic.Poly
33 import PvsNP.Language
4+import PvsNP.Machine.Tape
45
56 /-! # P versus NP in Lean 4
67
@@ -0,0 +1,69 @@
1+/-!
2+# Tapes
3+
4+A tape is a bi-infinite row of cells indexed by `Int`, each blank (`none`) or holding a symbol of the
5+alphabet `α`, with a head position. Tapes are functions, so two tapes are equal exactly when they have
6+the same head and the same contents: no trailing-blank bookkeeping.
7+
8+The machines of this project use `Option α` as their tape alphabet: input symbols plus the blank.
9+-/
10+
11+namespace PvsNP
12+
13+/-- A head movement. -/
14+inductive Dir where
15+ | left
16+ | stay
17+ | right
18+ deriving DecidableEq, Repr
19+
20+/-- A tape: head position and contents. `none` is the blank. -/
21+structure Tape (α : Type) where
22+ head : Int
23+ cells : Int → Option α
24+
25+namespace Tape
26+
27+variable {α : Type}
28+
29+/-- The all-blank tape, head at `0`. -/
30+def blank : Tape α := ⟨0, fun _ => none⟩
31+
32+/-- The tape holding the word `w` in cells `0 … |w| - 1`, blank elsewhere, head at `0`. -/
33+def ofWord (w : List α) : Tape α :=
34+ ⟨0, fun i => if 0 ≤ i then w[i.toNat]? else none⟩
35+
36+/-- The symbol under the head. -/
37+def read (t : Tape α) : Option α := t.cells t.head
38+
39+/-- Overwrite the cell under the head. -/
40+def write (t : Tape α) (s : Option α) : Tape α :=
41+ ⟨t.head, fun i => if i = t.head then s else t.cells i⟩
42+
43+/-- Move the head one cell (or not at all). -/
44+def move (t : Tape α) : Dir → Tape α
45+ | .left => ⟨t.head - 1, t.cells⟩
46+ | .stay => t
47+ | .right => ⟨t.head + 1, t.cells⟩
48+
49+@[simp] theorem move_stay (t : Tape α) : t.move .stay = t := rfl
50+
51+/-- Writing back the symbol just read changes nothing. -/
52+@[simp] theorem write_read (t : Tape α) : t.write t.read = t := by
53+ cases t with
54+ | mk h c =>
55+ simp only [write, read, Tape.mk.injEq, true_and]
56+ funext i
57+ by_cases hi : i = h
58+ · subst hi; simp
59+ · simp [hi]
60+
61+@[simp] theorem ofWord_nil : (ofWord [] : Tape α) = blank := by
62+ simp only [ofWord, blank, List.getElem?_nil, ite_self]
63+
64+theorem read_ofWord (w : List α) : (ofWord w).read = w.head? := by
65+ cases w <;> simp [ofWord, read]
66+
67+end Tape
68+
69+end PvsNP