← Student tools · Problem 13 · Lecture 8 · Round 1 (30 pts)

Quine · a program that prints itself

The cleanest demonstration of the recursion theorem.

CLO-1R1·30 ptsL8
🔊 Listen

A quine is a program that, when executed, prints its own source code. No file I/O, no introspection — the program builds its own source from its own behaviour. Quines exist in every Turing-complete language, and constructing one is the simplest, cleanest demonstration of Kleene's recursion theorem (Sipser §6.1).

The recursion theorem (Sipser Theorem 6.3)

For any computable function t : Σ* × Σ* → Σ*, there is a TM R such that on input w, R computes t(⟨R⟩, w). In other words: every TM can effectively obtain its own description and use it as part of its computation.

A quine is the case t(⟨R⟩, w) = ⟨R⟩ — the function simply outputs its own description. The construction works in any language with string manipulation. Once you can write a quine, the rest of the recursion theorem follows from the same data/code-split trick.

🔊 Listen
A quine has two parts that describe each other A · the data string S "Print my own source by emitting S with the placeholder replaced by a quoted copy of S itself." B · the printer code P read S print quoted-S followed by S with placeholder replaced Output = S concatenated with P = the original source

The asymmetry is what makes it work. The string S describes what the program will do; the printer code P actually does it. P reads S as data, prints S as data (escaped), then prints the unescaped instructions encoded in S. Because S describes P's own behaviour exactly, the output reassembles to the original source.

🔊 Listen

Same trick, three syntaxes:

Python:
s='s=%r;print(s%%s)';print(s%s)

JavaScript:
(function f(){console.log('('+f+')()');})()

Lisp:
((lambda (x) (list x (list (quote quote) x)))
 (quote (lambda (x) (list x (list (quote quote) x)))))

The Python version is the most readable: the string s contains a format-template that says "the string variable s, then printf-formatted with itself." When you execute it, the placeholder %r gets replaced by repr(s), which is s itself with quotes around it. The output reproduces the source.

🔊 Listen
Run a quine, then compare with its source Auto-plays

Source code

Output after running

🔊 Listen
🔊 Listen
🔊 Listen

Sipser: §6.1, Theorem 6.3 (recursion theorem) and Theorem 6.5 (corollary: every TM "knows" its own description). Lecture notes: Module 3 slide 5 walks through the T = A·B construction underlying the recursion theorem. Companion problems: P14 (Rice's theorem), P15 (fixed-point version), P16 (self-aware TM).