Quine

From Esolang
Jump to: navigation, search

A quine, named after the philosopher W. V. O. Quine, is a program that prints its own source code. One of the typical challenges of any new esoteric programming language is to write a quine other than the null program in it.

Often a program that just performs access to its own source code (reading it either from memory or from a disk file) and prints it out is considered "cheating".

The language Muriel is based on the idea of quines.

How to write quines

Quines can be developed in any Turing-complete language which has the ability to freely create output in its own source alphabet (though the existence of quines does not imply Turing-completeness). Despite all the mystery surrounding them, they are actually quite simple to develop. Here is an algorithm for doing so:

First we construct the function print which outputs its input. In most languages this is trivial. For example, in Javascript we have

 console.log(input);

Now consider print(print), the program which passes the source code of print to print. For example

 input = "console.log(input);";
 console.log(input);

It is quite easy to construct print(print), so we'll go ahead and write a program that given the input of the source code of program t outputs the source code of print(t). We'll call that program quinify. A quick note: you'll sometimes run into issues with escape sequences when writing quines. This is not a theoretical problem, only a language specific one. In this case we're using String.fromCharCode(34) to represent double quotes to avoid the issue. Anyway, here's quinify in Javascript:

 console.log('input = ' + String.fromCharCode(34) + input + String.fromCharCode(34) + ';' + String.fromCharCode(10) + input);

The final step is easy! Pass the source code of quinify to quinify. We have a quine.

 input = "console.log('input = ' + String.fromCharCode(34) + input + String.fromCharCode(34) + ';' + String.fromCharCode(10) + input);";
 console.log('input = ' + String.fromCharCode(34) + input + String.fromCharCode(34) + ';' + String.fromCharCode(10) + input);

Here it is minimized for those inclined (151 bytes)

 i="console.log('i='+String.fromCharCode(34)+i+String.fromCharCode(34)+';'+i)";console.log('i='+String.fromCharCode(34)+i+String.fromCharCode(34)+';'+i)


Clearly the only challenge here is in writing quinify, which in many esolangs is non-trivial. Get to work!

See also

External resources