346abe53 / PvsNP / Machine / Tape.lean

1/-!
2# Tapes
3
4A tape is a bi-infinite row of cells indexed by `Int`, each blank (`none`) or holding a symbol of the
5alphabet `α`, with a head position. Tapes are functions, so two tapes are equal exactly when they have
6the same head and the same contents: no trailing-blank bookkeeping.
7
8The machines of this project use `Option α` as their tape alphabet: input symbols plus the blank.
9-/
10
11namespace PvsNP
12
13/-- A head movement. -/
14inductive Dir where
15 | left
16 | stay
17 | right
18 deriving DecidableEq, Repr
19
20/-- A tape: head position and contents. `none` is the blank. -/
21structure Tape (α : Type) where
22 head : Int
23 cells : Int → Option α
24
25namespace Tape
26
27variable {α : Type}
28
29/-- The all-blank tape, head at `0`. -/
30def blank : Tape α := ⟨0, fun _ => none⟩
31
32/-- The tape holding the word `w` in cells `0 … |w| - 1`, blank elsewhere, head at `0`. -/
33def ofWord (w : List α) : Tape α :=
34 ⟨0, fun i => if 0 ≤ i then w[i.toNat]? else none⟩
35
36/-- The symbol under the head. -/
37def read (t : Tape α) : Option α := t.cells t.head
38
39/-- Overwrite the cell under the head. -/
40def 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). -/
44def 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
64theorem read_ofWord (w : List α) : (ofWord w).read = w.head? := by
65 cases w <;> simp [ofWord, read]
66
67end Tape
68
69end PvsNP