Quines
A quine is a computer program which prints out a copy of its own source code when it is run. The name comes from Quine’s paradox:
“Yields falsehood when preceded by its quotation” yields falsehood when preceded by its quotation.
There’s a long history of quines being written in various programming languages. In some (e.g. various Lisp dialects) it’s pretty simple. In others, it can be quite complex. They became popular with a lot of programmers because of GEB.
I just heard about one (from Asiajin via HackerNews) which really impressed me. It’s not exactly a quine though. It’s doing something even trickier. When you run the program, it prints out the source for a program in a different language. If you run that program, it’ll print out the source for a program in yet another language. So on and so forth, until the eleventh one prints out the original text! Go check it out here on Yusuke Endoh’s blog.
To understand how a quine works, let’s look at my favorite MATLAB quine. It was written by Iain Murray. It looks like this:
a=['ns}z2e1kGe1116k6111gE16;:6ek7;:61gg3E1']; disp(['a=[''',a,'''];',10,[a-10,']]);']]);
Let’s look at what’s going on here. The first line is pretty weird looking, isn’t it? Let’s skip it for the moment and concentrate on the second line. We can see that the second line is using disp
to do the following 3 things:
- Print out a copy of the first line.
- Print the number 10.
- Subtract 10 from the value in the first line and print it again.
The first step is pretty obvious. That’s how the output gets that first line.
In MATLAB, printing the number 10 starts a new line of text in the output, so that explains step 2.
But what’s the story with step 3? You can see the answer if you go into MATLAB and subtract 10 from the variable a
. What you get is a copy of the second line. OK, but why did he add 10 to it? The reason is that you can’t put the second line directly into a variable because it has special characters in it like '
and [
. The interpreter is going to see those and decide to break the line up into pieces. You would need to add some escape characters, and then it wouldn’t be exactly the same, so you wouldn’t have a quine. By adding 10 to the values, he shifted them up so that there weren’t any special characters in the line. That’s the sort of trick that you need to use to write quines in most programming languages.
Now you can go back to the other quine and try to figure out how it works. But you’ll need to be comfortable in the 11 different programming languages first!
This is a wonderful extension of the “quine” computer program concept. I’ve added it to the Willard Van Orman Quine web page in the section describing quine programs.