Quine in Mathematica

A “quine” is a curious object in computer science of far-reaching implications. It is a program that generates itself as output. This is more complex than it sounds, as if you have your program source, to print that source requires that the program have something like Print[program source], but then to capture that leading print command, you need to amend your code to something like Print[“Print[”,program source,“]”], and to capture the new complexity you need another level of nesting, ad infinitum. Some people, discovering this problem upon their initial efforts to write a quine, conclude the problem is hopeless.

However, it is not at all hopeless. These can be created in every Turing-complete computer language, and in fact can be created an infinite number of ways in each language. I learned about quines recently from their Wikipedia page, and from a very nice discussion at the web page of David Madore. Reading Madore’s page, I immediately realized an extremely slick implementation that would be possible in Mathematica 8, but before trying to implement that I thought I would try a more general approach first.

Three different techniques seemed promising. The first involved putting a program that uses ToExpression[] to render a string into a string, and then run ToExpression on it. My efforts in this direction all hit infinite recursion loops.

The second direction involved using StringReplace to print a string that contained its own StringReplace command. The substring being replaced seemed to get Held, however, and I couldn’t get it to behave as desire.

The third way uses the Print command, thusly:


quine[x_String] := Print[x, ";", FromCharacterCode[10] , "quine[", InputForm[x], "]"];
quine["quine[x_String]:=Print[x,\";\",FromCharacterCode[10],\"\quine[\",InputForm[x]],\"]\""]

The output is precisely as we want —
quine

I think this meets the definition of Quine. I’ll set to the elegant Mathematica 8 only version shortly.

One thought on “Quine in Mathematica

  1. Pingback: An amusing quine in Mathematica | monkeywrench

Comments are closed.