Topic

Grammars and machines

Beyond finite automata the machines get memory: a stack, then an unbounded tape. Each step up recognises more languages, and at the top, with Turing machines and recursive functions, the questions stop being decidable. Machines here run with a step budget, and a machine that has not halted is reported as running, never as rejecting.

Context-free grammars

A grammar has rules that rewrite a nonterminal (a capital letter) into a string of symbols. The words it generates are the strings of terminals reachable from the start symbol. S→aSb∣εS \to aSb \mid \varepsilon generates anbna^n b^n, which no finite automaton can recognise, since it would need to count without limit.

import { grammar, showTree } from "@ratmath/logic";

const g = grammar("S -> a S b | ε");
g.words(8).words;        // ["", "ab", "aabb", "aaabbb", "aaaabbbb"]
showTree(g.parse("aabb").tree);   // "S(a S(a S(ε) b) b)"

Membership is decided by the CYK method. The grammar is first put in Chomsky normal form, where every rule is A→BCA \to BC or A→aA \to a: ε-rules and unit rules are removed, and long rules are split. Then a table records which nonterminals generate each piece of the word, shortest pieces first, in time O(n3)O(n^3). When the word is accepted, a parse tree in the grammar as you wrote it is found too.

g.toCNF().toString();
// S → T0 X0 | T0 T1
// X0 → S T1
// S0 → ε | T0 X0 | T0 T1
// T0 → a
// T1 → b

const e = grammar("E -> E + T | T\nT -> T * F | F\nF -> ( E ) | x");
showTree(e.parse("x+x*x").tree);   // "E(E(T(F(x))) + T(T(F(x)) * F(x)))": * binds tighter
e.accepts("x+*x");                  // false

Pushdown automata

A pushdown automaton is a finite automaton with a stack. Each move reads a symbol (or nothing), pops the top of the stack (or nothing), and pushes a string. It accepts by ending in an accepting state. These machines recognise exactly the context-free languages. The run searches the possible computations breadth first and returns the accepting one it finds:

import { pda } from "@ratmath/logic";

// a's push A, then each b pops one; accept when only Z is left
const anbn = pda({ start: "q0", accept: ["q2"], moves: [
  ["q0", "a", "ε", "q0", "A"], ["q0", "ε", "ε", "q1", "ε"],
  ["q1", "b", "A", "q1", "ε"], ["q1", "ε", "Z", "q2", "Z"]] });
anbn.run("aabb").trace.map((c) => `${c.state} ${c.read || "-"} ${c.stack}`);
// ["q0 - Z", "q0 a AZ", "q0 aa AAZ", "q1 aa AAZ", "q1 aab AZ", "q1 aabb Z", "q2 aabb Z"]
anbn.accepts("aab");    // false

Turing machines

A Turing machine has a tape, unbounded both ways, and a head that reads a symbol, writes one, and moves left or right, according to a table indexed by state and symbol. Every algorithm can be written as one (the Church–Turing thesis), and so whether a machine halts cannot in general be decided: the halting problem. So run takes a budget, and a machine still going at the end is "running".

import { turing, binaryIncrement } from "@ratmath/logic";

binaryIncrement().run("1011", { trace: true });
// { status: "accepted", steps: 8, tape: "1100", trace: ["right: [1]011", "right: 1[0]11", …,
//   "carry: 101[1]_", "carry: 10[1]0_", "carry: 1[0]00_", "done: 1[1]00_"] }

turing({ start: "q", delta: { "q,_": ["q", "_", "R"] } }).run("", { budget: 50 }).status;
// "running": this one walks right forever, but the run only knows it has not stopped

A transition is written "state,symbol": [new state, symbol written, move], with moves L, R or S (stay). With no transition the machine halts without accepting.

Recursive functions

The other road to computability builds functions on the natural numbers from a few pieces: zero, successor, projections PinP^n_i, composition, and primitive recursion: f(0,y⃗)=g(y⃗)f(0, \vec y) = g(\vec y) and f(x+1,y⃗)=h(x,f(x,y⃗),y⃗)f(x+1, \vec y) = h(x, f(x, \vec y), \vec y). These are the primitive recursive functions, and every one of them halts. Adding minimisation, μx. f(x,y⃗)=0\mu x.\, f(x, \vec y) = 0, the least zero, gives the general recursive functions, exactly the functions Turing machines compute, and with it the possibility of searching forever.

import { recursive } from "@ratmath/logic";

const { add, mult, power, factorial } = recursive.examples;   // built only from the pieces
add.at(3, 4);            // 7n
power.at(2, 10);         // 1024n
factorial.at(7);         // 5040n

const { compose, proj } = recursive;
const double = compose(add, [proj(1, 1), proj(1, 1)]);
double.at(21);           // 42n
double.name;             // "add∘(P1^1,P1^1)"

These are computed the honest way, so addition takes xx successor steps and multiplication repeats addition: keep the numbers small. mu stops at its budget and says that the search may never end.

Reference

ExportWhat it does
grammar(text | { start, rules })A Grammar: words(maxLength), toCNF(), parse(word) (accepted, tree, cnfTree), accepts, toString().
showTree(tree)A parse tree as S(a S(…) b).
pda({ start, accept, stackStart, moves })A PDA; run(word, { budget }) gives "accepted" with a trace, "rejected", or "unresolved".
turing({ start, accept, reject, blank, delta })A TuringMachine; run(input, { budget, trace }) gives status ("accepted", "rejected", "halted", "running"), steps, tape, head.
binaryIncrement()A machine that adds one to a binary number.
recursivezero, succ, proj(i, n), compose(f, gs), primrec(g, h), mu(f, { budget }), constant(c, n), and examples: add, mult, pred, monus, power, factorial. Each has arity, name, at(...) on BigInt.
Try itEdit the code and run it with @ratmath/logic and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs