1import PvsNP.Basic.Poly
2import PvsNP.Complexity.Time
3
4/-!
5# The class P
6
7`InP L`: the alphabet is finite and some multi-tape machine decides `L` within a polynomial number
8of steps. Finiteness of the alphabet is part of the definition: over an infinite alphabet a single
9symbol carries unbounded information (a machine reading one `Nat` could test membership in the
10halting set), so P is empty there by definition rather than meaningless.
11
12Proved here: the full and the empty language are in P, and P is closed under complement.
13-/
14
15namespace PvsNP
16
17variable {α : Type}
18
19/-- `L ∈ P`: over a finite alphabet, a machine decides `L` in polynomial time. -/
20def InP (L : Language α) : Prop :=
21 IsFinite α ∧ ∃ (k : Nat) (M : Machine α k) (T : Nat → Nat), PolyBounded T ∧ DecidesIn M L T
22
23/-- A machine that halts at once, accepting or not as `b` says, touching nothing. -/
24def Machine.const (α : Type) (k : Nat) (b : Bool) : Machine α k where
25 Q := Unit
26 finite := inferInstance
27 start := ()
28 halted _ := true
29 accepting _ := b
30 δ q r := (q, r, fun _ => .stay)
31
32namespace InP
33
34/-- The time bound of a language in P can be taken of the form `c * (n + 1) ^ d`, hence monotone. -/
35theorem polyBound {L : Language α} (h : InP L) :
36 ∃ (k : Nat) (M : Machine α k) (c d : Nat), DecidesIn M L (PvsNP.polyBound c d) := by
37 obtain ⟨_, k, M, T, ⟨c, d, hT⟩, hM⟩ := h
38 exact ⟨k, M, c, d, hM.mono hT⟩
39
40/-- Only languages over finite alphabets are in P. -/
41theorem isFinite {L : Language α} (h : InP L) : IsFinite α := h.1
42
43theorem univ [IsFinite α] : InP (Language.univ : Language α) :=
44 ⟨inferInstance, 0, Machine.const α 0 true, fun _ => 0, PolyBounded.const 0, fun _ =>
45 ⟨rfl, by simp [Machine.const, Language.univ, Machine.init]⟩⟩
46
47theorem empty [IsFinite α] : InP (Language.empty : Language α) :=
48 ⟨inferInstance, 0, Machine.const α 0 false, fun _ => 0, PolyBounded.const 0, fun _ =>
49 ⟨rfl, by simp [Machine.const, Language.empty, Machine.init]⟩⟩
50
51/-- **P is closed under complement**: swap accepting and rejecting halted states. -/
52theorem compl {L : Language α} (h : InP L) : InP L.compl := by
53 obtain ⟨hα, k, M, T, hT, hM⟩ := h
54 refine ⟨hα, k, M.withAccepting (fun q => !M.accepting q), T, hT, fun x => ?_⟩
55 have e : (M.withAccepting (fun q => !M.accepting q)).init (inputTapes x) = M.init (inputTapes x) :=
56 rfl
57 rw [e, Machine.run_withAccepting]
58 refine ⟨(hM x).1, ?_⟩
59 simp only [Machine.withAccepting, Bool.not_eq_eq_eq_not, Bool.not_true, Language.compl_apply,
60 ← (hM x).2, Bool.not_eq_true]
61
62theorem of_compl {L : Language α} (h : InP L.compl) : InP L := by
63 obtain ⟨hα, k, M, T, hT, hM⟩ := h.compl
64 exact ⟨hα, k, M, T, hT, fun x => ⟨(hM x).1, by rw [(hM x).2, Language.compl_compl]⟩⟩
65
66theorem compl_iff {L : Language α} : InP L.compl ↔ InP L := ⟨of_compl, compl⟩
67
68end InP
69
70end PvsNP