HOME

TheInfoList



OR:

A quine is a
computer program A computer program is a sequence or set of instructions in a programming language for a computer to Execution (computing), execute. It is one component of software, which also includes software documentation, documentation and other intangibl ...
that takes no input and produces a copy of its own
source code In computing, source code, or simply code or source, is a plain text computer program written in a programming language. A programmer writes the human readable source code to control the behavior of a computer. Since a computer, at base, only ...
as its only output. The standard terms for these programs in the
computability theory Computability theory, also known as recursion theory, is a branch of mathematical logic, computer science, and the theory of computation that originated in the 1930s with the study of computable functions and Turing degrees. The field has since ex ...
and
computer science Computer science is the study of computation, information, and automation. Computer science spans Theoretical computer science, theoretical disciplines (such as algorithms, theory of computation, and information theory) to Applied science, ...
literature are "self-replicating programs", "self-reproducing programs", and "self-copying programs". A quine is a fixed point of an execution environment, when that environment is viewed as a
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-orie ...
transforming programs into their outputs. Quines are possible in any
Turing-complete In computability theory, a system of data-manipulation rules (such as a model of computation, a computer's instruction set, a programming language, or a cellular automaton) is said to be Turing-complete or computationally universal if it can be ...
programming language, as a direct consequence of
Kleene's recursion theorem In computability theory, Kleene's recursion theorems are a pair of fundamental results about the application of computable functions to their own descriptions. The theorems were first proved by Stephen Kleene in 1938 and appear in his 1952 ...
. For amusement, programmers sometimes attempt to develop the shortest possible quine in any given
programming language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
.


Name

The name "quine" was coined by
Douglas Hofstadter Douglas Richard Hofstadter (born 15 February 1945) is an American cognitive and computer scientist whose research includes concepts such as the sense of self in relation to the external world, consciousness, analogy-making, Strange loop, strange ...
, in his popular 1979 science book ''
Gödel, Escher, Bach ''Gödel, Escher, Bach: an Eternal Golden Braid'' (abbreviated as ''GEB'') is a 1979 nonfiction book by American cognitive scientist Douglas Hofstadter. By exploring common themes in the lives and works of logician Kurt Gödel, artist M. C. Esc ...
'', in honor of philosopher
Willard Van Orman Quine Willard Van Orman Quine ( ; known to his friends as "Van"; June 25, 1908 – December 25, 2000) was an American philosopher and logician in the analytic tradition, recognized as "one of the most influential philosophers of the twentieth century" ...
(1908–2000), who made an extensive study of
indirect self-reference Indirect self-reference describes an object referring to itself indirectly. For example, the "this sentence is false." contains a direct self-reference, in which the phrase "this sentence" refers directly to the sentence as a whole. An indirectly ...
, and in particular for the following paradox-producing expression, known as
Quine's paradox Quine's paradox is a paradox concerning truth values, stated by Willard Van Orman Quine. It is related to the liar paradox as a problem, and it purports to show that a sentence can be paradoxical even if it is not self-referring and does not use ...
:
"Yields falsehood when preceded by its quotation" yields falsehood when preceded by its quotation.


History

John von Neumann John von Neumann ( ; ; December 28, 1903 – February 8, 1957) was a Hungarian and American mathematician, physicist, computer scientist and engineer. Von Neumann had perhaps the widest coverage of any mathematician of his time, in ...
theorized about self-reproducing automata in the 1940s. Later, Paul Bratley and Jean Millo's article "Computer Recreations: Self-Reproducing Automata" discussed them in 1972. Bratley first became interested in self-reproducing programs after seeing the first known such program written in
Atlas Autocode Atlas Autocode (AA)Original scans)) is a programming language developed around 1963 at the University of Manchester. A variant of the language ALGOL, it was developed by Tony Brooker and Derrick Morris for the Atlas computer. The initial AA and ...
at Edinburgh in the 1960s by the
University of Edinburgh The University of Edinburgh (, ; abbreviated as ''Edin.'' in Post-nominal letters, post-nominals) is a Public university, public research university based in Edinburgh, Scotland. Founded by the City of Edinburgh Council, town council under th ...
lecturer and researcher Hamish Dewar. The "download source" requirement of the
GNU Affero General Public License The GNU Affero General Public License (GNU AGPL) is a free, copyleft license published by the Free Software Foundation in November 2007, and based on the GNU GPL version 3 and the ''Affero General Public License'' (non-GNU). It is intended fo ...
is based on the idea of a quine.


Examples


Constructive quines

In general, the method used to create a quine in any programming language is to have, within the program, two pieces: (a) 
code In communications and information processing, code is a system of rules to convert information—such as a letter, word, sound, image, or gesture—into another form, sometimes shortened or secret, for communication through a communicati ...
used to do the actual printing and (b) 
data Data ( , ) are a collection of discrete or continuous values that convey information, describing the quantity, quality, fact, statistics, other basic units of meaning, or simply sequences of symbols that may be further interpreted for ...
that represents the textual form of the code. The code functions by using the data to print the code (which makes sense since the data represents the textual form of the code), but it also uses the data, processed in a simple way, to print the textual representation of the data itself. Here are three small examples in Python3: # Example A. chr(39)

"'". a = 'a = ; print(a.format(chr(39), a, chr(39)))'; print(a.format(chr(39), a, chr(39)))
# Example B. chr(39)

"'". b = 'b = %s%s%s; print(b %% (chr(39), b, chr(39)))'; print(b % (chr(39), b, chr(39)))
# Example C. %r will quote automatically. c = 'c = %r; print(c %% c)'; print(c % c) The following
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
code demonstrates the basic structure of a quine. public class Quine The source code contains a string array of itself, which is output twice, once inside quotation marks. This code was adapted from an original post from c2.com, where the author, Jason Wilson, posted it as a minimalistic version of a Quine, without Java comments. Thanks to ne
text blocks
feature in Java 15 (or newer), a more readable and simpler version is possible: public class Quine The same idea is used in the following
SQL Structured Query Language (SQL) (pronounced ''S-Q-L''; or alternatively as "sequel") is a domain-specific language used to manage data, especially in a relational database management system (RDBMS). It is particularly useful in handling s ...
quine: SELECT REPLACE(REPLACE('SELECT REPLACE(REPLACE("$",CHAR(34),CHAR(39)),CHAR(36),"$") AS Quine',CHAR(34),CHAR(39)),CHAR(36),'SELECT REPLACE(REPLACE("$",CHAR(34),CHAR(39)),CHAR(36),"$") AS Quine') AS Quine


Eval quines

Some programming languages have the ability to evaluate a string as a program. Quines can take advantage of this feature. For example, this
Ruby Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
quine: eval s="print 'eval s=';p s" Lua can do: s="print(string.format('s=%c%s%c; load(s)()',34,s,34))"; load(s)() In Python 3.8: exec(s:='print("exec(s:=%r)"%s)')


"Cheating" quines


Self-evaluation

In many functional languages, including Scheme and other Lisps, and interactive languages such as APL, numbers are self-evaluating. In
TI-BASIC TI-BASIC is the official name of a BASIC-like language built into Texas Instruments' graphing calculators. TI-BASIC is a language family of three different and incompatible versions, released on different products: * TI-BASIC 83 (on Z80 proces ...
, if the last line of a program returns a value, the returned value is displayed on the screen. Therefore, in such languages a program consisting of only a single digit results in a 1-byte quine. Since such code does not ''construct'' itself, this is often considered cheating. 1


Empty quines

In some languages, particularly
scripting language In computing, a script is a relatively short and simple set of instructions that typically automation, automate an otherwise manual process. The act of writing a script is called scripting. A scripting language or script language is a programming ...
s but also C, an empty source file is a fixed point of the language, being a valid program that produces no output. Such an empty program, submitted as "the world's smallest self reproducing program", once won the "worst abuse of the rules" prize in the
International Obfuscated C Code Contest The International Obfuscated C Code Contest (abbreviated IOCCC) is a computer programming contest for Source code, code written in C (programming language), C that is the most creatively obfuscated code, obfuscated. Held semi-annually, it is desc ...
. The program was not actually compiled, but used cp to copy the file into another file, which could be executed to print nothing.


Source code inspection

Quines, per definition, cannot receive ''any'' form of input, including reading a file, which means a quine is considered to be "cheating" if it looks at its own source code. The following
shell Shell may refer to: Architecture and design * Shell (structure), a thin structure ** Concrete shell, a thin shell of concrete, usually with no interior columns or exterior buttresses Science Biology * Seashell, a hard outer layer of a marine ani ...
script is not a quine: #!/bin/sh # Invalid quine. # Reading the executed file from disk is cheating. cat $0 A shorter variant, exploiting the behaviour of shebang directives: #!/bin/cat Other questionable techniques include making use of compiler messages; for example, in the
GW-BASIC GW-BASIC is a dialect of the BASIC programming language developed by Microsoft from IBM BASICA. Functionally identical to BASICA, its BASIC interpreter is a fully self-contained executable and does not need the Cassette BASIC ROM found in the ori ...
environment, entering "Syntax Error" will cause the interpreter to respond with "Syntax Error". Quine code can also be outputted visually, for example it's used to visualize the neutral zone in Yars' Revenge, along with syntactic saccharin, to obfuscate the source code.


Ouroboros programs

The quine concept can be extended to multiple levels of recursion, giving rise to "
ouroboros The ouroboros or uroboros (; ) is an ancient symbol depicting a serpent symbolism, snake or European dragon, dragon Autocannibalism, eating its own tail. The ouroboros entered Western tradition via Egyptian mythology, ancient Egyptian iconogra ...
programs", or quine-relays. This should not be confused with multiquines.


Example

This Java program outputs the source for a C++ program that outputs the original Java code.
#include #include using namespace std; int main(int argc, char* argv[])
public class Quine
Such programs have been produced with various cycle lengths: *
Haskell Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
Python
Ruby Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
* PythonBash
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
* C
Haskell Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
Python
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
*
Haskell Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
Python
Ruby Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
C
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
*
Ruby Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
C#Python * CC++
Ruby Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
Python
PHP PHP is a general-purpose scripting language geared towards web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by the PHP Group. ...
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
*
Ruby Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
Python
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
Lua
OCaml OCaml ( , formerly Objective Caml) is a General-purpose programming language, general-purpose, High-level programming language, high-level, Comparison of multi-paradigm programming languages, multi-paradigm programming language which extends the ...
Haskell Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
C
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
Brainfuck Brainfuck is an esoteric programming language created in 1993 by Swiss student Urban Müller. Designed to be extremely minimalistic, the language consists of only eight simple commands, a data pointer, and an instruction pointer. Brainfuck is ...
Whitespace White space or whitespace may refer to: Technology * Whitespace characters, characters in computing that represent horizontal or vertical space * White spaces (radio), allocated but locally unused radio frequencies * TV White Space Database, a m ...
Unlambda Unlambda is a minimal, "nearly pure" functional programming language invented by David Madore. It is based on combinatory logic, an expression system without the lambda operator or free variables. It relies mainly on two built-in functions (s ...
*
Ruby Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
ScalaScheme
Scilab Scilab is a free and open-source, cross-platform numerical computational package and a high-level, numerically oriented programming language. It can be used for signal processing, statistical analysis, image enhancement, fluid dynamics simul ...
Shell (bash)
S-Lang The S-Lang programming library is a software library for Unix, Windows, VMS, OS/2, and Mac OS X. It provides routines for embedding an interpreter for the S-Lang scripting language, and components to facilitate the creation of text-based applica ...
Smalltalk Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
Squirrel3
Standard ML Standard ML (SML) is a General-purpose programming language, general-purpose, High-level programming language, high-level, Modular programming, modular, Functional programming, functional programming language with compile-time type checking and t ...
→ ... →
Rexx Rexx (restructured extended executor) is a high-level programming language developed at IBM by Mike Cowlishaw. Both proprietary and open-source software, open source Rexx interpreter (computing), interpreters exist for a wide range of comput ...
(128 (and formerly 50) programming languages) * Web application → C (web application source code consists of
HTML Hypertext Markup Language (HTML) is the standard markup language for documents designed to be displayed in a web browser. It defines the content and structure of web content. It is often assisted by technologies such as Cascading Style Sheets ( ...
,
JavaScript JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior. Web browsers have ...
, and CSS)


Multiquines

David Madore, creator of
Unlambda Unlambda is a minimal, "nearly pure" functional programming language invented by David Madore. It is based on combinatory logic, an expression system without the lambda operator or free variables. It relies mainly on two built-in functions (s ...
, describes multiquines as follows:
"A multiquine is a set of r different programs (in r different languages – without this condition we could take them all equal to a single quine), each of which is able to print any of the r programs (including itself) according to the command line argument it is passed. (Cheating is not allowed: the command line arguments must not be too long – passing the full text of a program is considered cheating)."
A multiquine consisting of 2 languages (or biquine) would be a program which: * When run, is a quine in language X. * When supplied with a user-defined command line argument, would print a second program in language Y. * Given the second program in language Y, when run normally, would also be a quine in language Y. * Given the second program in language Y, and supplied with a user-defined command line argument, would produce the original program in language X. A biquine could then be seen as a set of two programs, both of which are able to print either of the two, depending on the command line argument supplied. Theoretically, there is no limit on the number of languages in a multiquine. A 5-part multiquine (or pentaquine) has been produced with Python,
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
, C,
NewLISP newLISP is a scripting language, a dialect of the Lisp family of programming languages. It was designed and developed by Lutz Mueller. Because of its small resource requirements, newLISP is excellent for embedded systems applications. Most of th ...
, and F# and there is also a 25-language multiquine.


Polyglot

Similar to, but unlike a multiquine, a
polyglot Multilingualism is the use of more than one language, either by an individual speaker or by a group of speakers. When the languages are just two, it is usually called bilingualism. It is believed that multilingual speakers outnumber monolin ...
program is a computer program or script written in a valid form of multiple programming languages or file formats by combining their syntax. A polyglot program is not required to have a self-reproducing quality, although a polyglot program can also be a quine in one or more of its possible ways to execute. Unlike quines and multiquines, polyglot programs are not guaranteed to exist between arbitrary sets of languages as a result of Kleene's recursion theorem, because they rely on the interplay between the syntaxes, and not a provable property that one can always be embedded within another.


Radiation-hardened

A radiation-hardened quine is a quine that can have any single character removed and still produces the original program with no missing character. Of necessity, such quines are much more convoluted than ordinary quines, as is seen by the following example in
Ruby Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
: eval='eval$q=%q(puts %q(10210/#}/.i rescue##/ 1 1" 3,213max_by#"##").gsub(/\d/) exit)#'##' instance_eval='eval$q=%q(puts %q(10210/#}/.i rescue##/ 1 1" 3,213max_by#"##").gsub(/\d/) exit)#'##' /#}/.i rescue##/ eval eval" , =9,instance_eval, , =9max_by#"##"


Automatic generation

Using relational programming techniques, it is possible to generate quines automatically by transforming the interpreter (or equivalently, the compiler and runtime) of a language into a relational program, and then solving for a fixed point.


See also

*
Diagonal lemma In mathematical logic, the diagonal lemma (also known as diagonalization lemma, self-reference lemma or fixed point theorem) establishes the existence of self-referential sentences in certain formal theories. A particular instance of the diagonal ...
*
Droste effect The Droste effect (), known in art as an example of ''mise en abyme'', is the effect of a picture recursion, recursively appearing within itself, in a place where a similar picture would realistically be expected to appear. This produces a loo ...
*
Fixed point combinator In combinatory logic for computer science, a fixed-point combinator (or fixpoint combinator) is a higher-order function (i.e., a function which takes a function as argument) that returns some '' fixed point'' (a value that is mapped to itself) of ...
*
Self-modifying code In computer science, self-modifying code (SMC or SMoC) is source code, code that alters its own instruction (computer science), instructions while it is execution (computing), executing – usually to reduce the instruction path length and imp ...
* Self-interpreter *
Self-replicating machine A self-replicating machine is a type of autonomous robot that is capable of reproducing itself autonomously using raw materials found in the environment, thus exhibiting self-replication in a way analogous to that found in nature. The concept of ...
*
Self-replication Self-replication is any behavior of a dynamical system that yields construction of an identical or similar copy of itself. Biological cells, given suitable environments, reproduce by cell division. During cell division, DNA is replicated and c ...
* Self-relocation * TiddlyWiki * Tupper's self-referential formula *
Programming languages A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their syntax (form) and semantics (meaning), usually defined by a formal language. Languages usually provide features ...
*
Quine's paradox Quine's paradox is a paradox concerning truth values, stated by Willard Van Orman Quine. It is related to the liar paradox as a problem, and it purports to show that a sentence can be paradoxical even if it is not self-referring and does not use ...
* Polyglot (computing)


Notes


References


Further reading

*
Douglas Hofstadter Douglas Richard Hofstadter (born 15 February 1945) is an American cognitive and computer scientist whose research includes concepts such as the sense of self in relation to the external world, consciousness, analogy-making, Strange loop, strange ...
: '' Gödel, Escher, Bach: An Eternal Golden Braid'' *
Ken Thompson Kenneth Lane Thompson (born February 4, 1943) is an American pioneer of computer science. Thompson worked at Bell Labs for most of his career where he designed and implemented the original Unix operating system. He also invented the B (programmi ...
:
Reflections on Trusting Trust
(''
Communications of the ACM ''Communications of the ACM'' (''CACM'') is the monthly journal of the Association for Computing Machinery (ACM). History It was established in 1958, with Saul Rosen as its first managing editor. It is sent to all ACM members. Articles are i ...
'', 27(8):761-3)


External links


TiddlyWiki, a quine manifested as a wikiA Brief Guide to Self-Referential ProgramsQuineProgram at the Portland Pattern Repository WikiZip File QuineAn Introduction to Quines — in particular, quines using more than one language
* ttps://no-gravity.github.io/html-quine/ HTML Quine: An HTML page that only uses HTML and CSS to show its own source codebr>Quine Challenge for Tom's JavaScript Machine
with a series of interactive hints
A Java Quine built straight from Kleene's fixed point theorem, composition and s-n-mA QR code quine
{{DEFAULTSORT:Quine (Computing) Source code Articles with example C code Willard Van Orman Quine Test items in computer languages Computer programming folklore Self-replication