quine quine

Unless otherwise stated, all original content on this site is licensed under your choice of the GNU FDL or the Creative Commons ShareAlike License.

GNU FDL Creative Commons License

Self-reproducing programs

Quines are sets of instructions which reproduce themselves when carried out. For example, the following English sentence is a quine.

Write the following twice, the second time quoted and followed by a period:
‘Write the following twice, the second time quoted and followed by a period:’.

Quines can be considered the fixed points of the function of an interpreter. It is possible to write a quine in any Turing complete language (provided the language has the means to print an arbitrary string). Kleene’s recursion theorem is basically about writing quines.

I experience pleasure when writing quines, so I write them frequently.

Here is one which is interpreted by the unix calculator dc: [91aPdP93aPp]91aPdP93aPp. Here is another which is interpreted by dc. It is a bit more interesting.

I have a couple simple quines written in bash. Dealing with the string escape characters is a nightmare, as is the case with a lot of quines. bash quine1. bash quine 2.

This quine is written in an amusing language called brainfuck. Brainfuck is a very simple language. It has only eight possible statements, each of which is denoted by a single character. All other characters are comments. [Note: to be absolutely correct, that program is not a quine, but a program that prints out a quine.] As brainfuck quines go, this one is pretty crappy. I've seen much, much shorter ones.

Here we have a quine written in PostScript. PostScript is a nice little stack oriented language which is interpreted by printers. Writing a quine in PostScript was fun for a couple of reasons. First, since it is being run on a printer, there isn't any way to cheat by asking another program to help (e.g., "echo 'cat cheater' > cheater; sh cheater"); second, instead of getting the output on the screen, you get it on a sheet of paper!

This program does not exactly produce its source code as output, but it does something similar. Try these possibilities:

cat converge
cat converge | perl
cat converge | perl | perl | perl | perl | perl | perl

This program was not written by me, and it is very cool. It takes any source file (or even an entire source distribution) and tranforms it into a quine. That is, the program retains its original functionality, but it gains an internal function that returns the source code of the program, allowing the program to, say, dump its source on stdout when given a command line option. When I get some time, I’m going to apply this to every program I’ve written, giving them just such an option.