Concept

Quine

Definition

A quine is a computer program that, when executed, outputs its own source code as text — no input file, no command-line trick, just the program printing itself. The term was coined by Douglas Hofstadter in Gödel, Escher, Bach in honor of philosopher W. V. O. Quine, whose work on self-reference inspired the construction.

A naive attempt fails. print("hello") does not print itself. print("print('hello')") does not print itself either — it prints the string, not the surrounding print(...) machinery. The recursive trap is that the program seems to need to contain a copy of itself, which would need to contain a copy of itself, and so on.

Why it matters

How it works

The standard quine technique: define a string s that represents the source code of the program except for one placeholder. Then have the program print s with the placeholder filled in by a quoted version of s itself.

A Python example:

s = 's = {!r}\nprint(s.format(s))'
print(s.format(s))

When run, the format call substitutes a repr-quoted copy of s into the placeholder, producing the program's source. The trick decouples description (the string s, treated as data) from execution (the print call), so self-application terminates after a single substitution rather than recursing forever.

This is the same pattern Gödel used to construct his self-referential sentence and the same pattern DNA uses to encode its own replication machinery. The architecture is forced by the structure of the problem.

Where it goes next

Continue exploring

Tags