Wednesday, December 29, 2010

Quines

Everybody loves a good quine. The most obvious, and most cheating way to write a “quine” In LaTeX is to use the listings package.
\documentclass{article}
\usepackage{listings}
\lstset{language=[LaTeX]TeX}
\begin{document}
\lstinputlisting{\jobname}
\end{document}
This is not very exciting and it's cheating on two levels. One, a quine is not supposed to read its source code. So just as
#!/bin/sh
cat "$0"
is not a quine, using the listings package is not a quine. Secondly, a quine should produce code that can be compiled directly. As it stands, I know of no TeX implementation that will read the code from a typeset pdf.

This is the shortest quine (give or take the characters used to construct the output file name) that I could construct.
\toks0{\immediate\openout2\jobname.copy.tex\def\t{\immediate\write2{\string
\toks0{\the\toks0}\string\the\string\toks0\end}}\t}\the\toks0\end
One thing to note is that due to the way TeX parses and displays tokens, this is not technically a quine. As with most quines on the Internet, this is a quine generator. Run it once to produce a quine:
$ tex quine
This is TeX, Version 3.1415926 (TeX Live 2010)
(./quine.tex )
No pages of output.
Transcript written on quine.log.
$ tex quine.copy
This is TeX, Version 3.1415926 (TeX Live 2010)
(./quine.copy.tex )
No pages of output.
Transcript written on quine.copy.log.
$ diff -s quine.copy.tex quine.copy.copy.tex
Files quine.copy.tex and quine.copy.copy.tex are identical

1 comment:

  1. I like this! I do not use LaTeX, but I have done something similar to the top one where the DVI file contains the typeset code by inputting itself. The bottom one is better, and it works in Plain TeX. The next thing is to make one using primitive TeX (the category codes for { and } have to be set, since they are not already set in primitive TeX).

    ReplyDelete