I was reading a speech by Ken Thompson yesterday, and I was reminded about quines. I heard of quines before, but I had never attempted to write one myself. I liked the way he put it:
In college, before video games, we would amuse ourselves by posing programming exercises. One of the favorites was to write the shortest self-reproducing program. […] If you have never done this, I urge you to try it on your own. The discovery of how to do it is a revelation that far surpasses any benefit obtained by being told how to do it.
If you’ve never written a quine before, you owe it to yourself to stop now and try. Like Ken said, it’s better to discover how yourself.
I quickly came up with this simple quine:
console.log("(" + a.toString() + "())");
Obviously, this can be improved upon to this:
After some searching, I discovered it could be shortened slightly to something like this:
However, I wasn’t satisfied. That’s a whole 52 bytes, and look at all those long keywords like
console. Clearly, I’m going about this the wrong way.
Then I had an idea, but I couldn’t quite get it to work. But in bed late last night, it came to me (sometimes I think God programs for me in my sleep). It took some time to get it just right, but it works…with some caveats.
First, it only works in node.js on *nix systems, like Linux and OS X. Second, it has to have a specific, and rather odd, name and path. Third, by default, it prints it’s source code to
stderr instead of
stdout, so you may have to run it just right.
It’s so ugly it’s beautiful. And yes, there’s a line break before and after.
Like I said, it needs to be in a specific path. For this to work, you have to create a folder in the root directory called
**. The file then needs to be inside
/** and named
a. (Did I mention you need root privileges?)
Simply running the program from the command line will display the source code, but if you want to get it to send the source to
stdout, you need to run it like this:
node /**/a 2>&1
So if you want to confirm that this quine really works, you can just run the following:
node /**/a > /**/out 2>&1
diff -s /**/a /**/out
It should reply with
Files /**/a and /**/out are identical.
And if you’re wondering why
a: is a
3 is merely a
^) and final
0 are also valid; since line breaks are ignored, the code becomes
0^0, which is simply an
XOR bitwise operation that does absolutely nothing.
So, what do you think? Is throwing an error cheating?
Can you shorten it further?
I was first going for
//a:3 but couldn’t get that to work. Could you do something with a regular expression?
/a/;a:3 works too but doesn’t save you anything.
By the way, I setup a github repository just for the fun of it.
 ^ I realized later the introspective quine can be shortened further, but that’s beside the point.