Quine

From Rosetta Code
Revision as of 01:04, 11 August 2009 by Eriksiers (talk | contribs) (added BASIC, 2 examples (I wrote the code a few years ago... just because))
Quine is a programming puzzle. It lays out a problem which Rosetta Code users are encouraged to solve, using languages and techniques they know. Multiple approaches are not discouraged, so long as the puzzle guidelines are followed. For other Puzzles, see Category:Puzzles.

A Quine is a self-referential program that can, without any external access, output its own source. It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."

The usual way to code a Quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as string). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.

Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out, or empty programs producing no output, are not allowed, either.

There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:

  • Part of the code usually needs to be stored as a string literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
    • Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
    • Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
  • Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be excaped, etc.
    • If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
    • Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
    • Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.

Ada

The program text must be in one line.

<lang Ada>with Ada.Text_IO;procedure Self is Q:Character:='"';A:String:="with Ada.Text_IO;procedure Self is Q:Character:='';A:String:=;begin Ada.Text_IO.Put_Line(A(1..49)&Q&A(50..61)&Q&A&Q&A(62..A'Last));end Self;";begin Ada.Text_IO.Put_Line(A(1..49)&Q&A(50..61)&Q&A&Q&A(62..A'Last));end Self;</lang>

ALGOL 68

<lang algol>STRING p="STRING p=?;print(p[:9]+REPR 34+p+REPR 34+p[11:])";print(p[:9]+REPR 34+p+REPR 34+p[11:])</lang>

BASIC

<lang qbasic> READ d$ DO

   READ x$
   PRINT x$

LOOP UNTIL LEN(x$) < 1 RESTORE DO

   READ x$
   PRINT d$; CHR$(34); x$; CHR$(34)

LOOP UNTIL LEN(x$) < 1 END

DATA "DATA " DATA "READ d$" DATA "DO" DATA " READ x$" DATA " PRINT x$" DATA "LOOP UNTIL LEN(x$) < 1" DATA "RESTORE" DATA "DO" DATA " READ x$" DATA " PRINT d$; CHR$(34); x$; CHR$(34)" DATA "LOOP UNTIL LEN(x$) < 1" DATA "END" DATA "" </lang>

This version pulls the 'read' code into a subroutine (of sorts). <lang qbasic> a = 0 READ d$ GOSUB reader a = 1 RESTORE GOSUB reader END reader:

   DO
       READ x$
       IF a = 1 THEN PRINT d$; CHR$(34);
       PRINT x$;
       IF a = 1 THEN PRINT CHR$(34);
       PRINT
   LOOP UNTIL LEN(x$) < 1

RETURN

DATA "DATA " DATA "a = 0" DATA "READ d$" DATA "GOSUB reader" DATA "a = 1" DATA "RESTORE" DATA "GOSUB reader" DATA "END" DATA "reader:" DATA " DO" DATA " READ x$" DATA " IF a = 1 THEN PRINT d$; CHR$(34);" DATA " PRINT x$;" DATA " IF a = 1 THEN PRINT CHR$(34);" DATA " PRINT" DATA " LOOP UNTIL LEN(x$) < 1" DATA "RETURN" DATA "" </lang>

Befunge

The code space is also the data space of a Befunge program. Programs can be read and modified on the fly. This quine works by reading and printing each character of the source. (This is a implicit loop, since the Befunge codespace wraps around.) <lang Befunge>:0g,:66+`#@_1+</lang>

C

<lang c>main(){ char*p="main(){ char*p=%c%s%c; printf(p,34,p,34); }"; printf(p,34,p,34); }</lang>

C++

<lang cpp>#include <iostream>

  1. include <ostream>

void quote(char const* c) {

 while (*c)
 {
   switch(*c)
   {
   case '\\':
     std::cout << "\\\\";break;
   case '\n':
     std::cout << "\\n";break;
   case '\"':
     std::cout << "\\\"";break;
   default:
     std::cout << *c;
   }
   ++c;
 }

}

int main() {

 char const* parts[] = {
   "#include <iostream>\n#include <ostream>\n\nvoid quote(char const* c)\n{\n  while (*c)\n  {\n    switch(*c)\n    {\n    case '\\\\':\n      std::cout << \"\\\\\\\\\";break;\n    case '\\n':\n      std::cout << \"\\\\n\";break;\n    case '\\\"':\n      std::cout << \"\\\\\\\"\";break;\n    default:\n      std::cout << *c;\n    }\n    ++c;\n  }\n}\n\nint main()\n{\n  char const* parts[] = {\n    \"",
   "\",\n    \"",
   "\"\n  };\n  \n  std::cout << parts[0];\n  quote(parts[0]);\n  std::cout << parts[1];\n  quote(parts[1]);\n  std::cout << parts[1];\n  quote(parts[2]);\n  std::cout << parts[2];\n\n  return 0;\n}\n"
 };
 
 std::cout << parts[0];
 quote(parts[0]);
 std::cout << parts[1];
 quote(parts[1]);
 std::cout << parts[1];
 quote(parts[2]);
 std::cout << parts[2];
 return 0;

} </lang>

Clojure

<lang clojure>((fn [x] (list x (list (quote quote) x))) (quote (fn [x] (list x (list (quote quote) x)))))</lang>

Common Lisp

There are many simple ways to write a quine in Common Lisp, since source can be quoted and manipulated; this one defines an anonymous function, which is applied to its own source, which writes out that application of itself to its source. <lang lisp>((lambda (s) (print (list s (list 'quote s))))

'(lambda (s) (print (list s (list 'quote s)))))</lang>

This one does the same thing using quasiquote (template) syntax; in some implementations it may not print nicely (but will still work): <lang lisp>((lambda (s) (print `(,s ',s))) '(lambda (s) (print `(,s ',s))))</lang>

This program's source contains an explicit reference to itself, which it prints in a manner preserving that reference: <lang lisp>#1=(write '#1# :readably t :circle t)</lang>

D

This Quine output its own source both during compiling and running. <lang d>const auto s=`const auto q="const auto s="~\x60~s~\x60~"; mixin(s);";import std.stdio;void main(){writefln(q);pragma(msg,q);}`; mixin(s); </lang> NB: last line should be CRLF to match pragma's newline ouput behaviour.

E

<lang e>" =~ x; println(E.toQuote(x),x)" =~ x; println(E.toQuote(x),x)</lang>

Forth

A large number of quine methods are listed here, the simplest of which is: <lang forth>SOURCE TYPE</lang>

Groovy

There are several ways to do this. Here are five: <lang groovy>s="s=%s;printf s,s.inspect()";printf s,s.inspect()</lang> <lang groovy>evaluate s='char q=39;print"evaluate s=$q$s$q"'</lang> <lang groovy>s="s=%c%s%c;printf s,34,s,34";printf s,34,s,34</lang> <lang groovy>s='s=%c%s%1$c;printf s,39,s';printf s,39,s</lang> <lang groovy>printf _='printf _=%c%s%1$c,39,_',39,_</lang> Also Groovy has a trivial solution of an empty (0 length) file even though that isn't an allowable solution here.

Haskell

(Haskell does not provide access to a source-code equivalent representation of the code at runtime.)

In Haskell, function arguments are not surrounded by parentheses, which permits a simple quine where there is only the unquoted code followed by the quoted code. <lang haskell>let q s = putStrLn (s ++ show s) in q "let q s = putStrLn (s ++ show s) in q "</lang>

It is also possible to eliminate one or both of the variables (point-free style): the let can be replaced with a lambda. (. is function composition.) <lang haskell>(\s -> putStrLn (s ++ show s)) "(\\s -> putStrLn (s ++ show s)) "</lang> <lang haskell>(putStrLn . \s -> s ++ show s) "(putStrLn . \\s -> s ++ show s) "</lang>

and s can be replaced by ap, which when applied to functions has the effect of the S combinator: <lang haskell>import Control.Monad.Reader (putStrLn . ap (++) show) "(putStrLn . ap (++) show) "</lang>

J

One of many possible solutions:

<lang J>(,2#{:),~'(,2#{:),~</lang>

Java

Copied from The Quine Page

Author: Bertram Felgenhauer <lang java>class S{public static void main(String[]a){String s="class S{public static void main(String[]a){String s=;char c=34;System.out.println(s.substring(0,52)+c+s+c+s.substring(52));}}";char c=34;System.out.println(s.substring(0,52)+c+s+c+s.substring(52));}}</lang>

Works with: Java version 1.5+

<lang java>class S{public static void main(String[]a){String p="class S{public static void main(String[]a){String p=%c%s%c;System.out.printf(p,34,p,34);}}";System.out.printf(p,34,p,34);}}</lang>

Lisp

Lisp has a mechanism to quote code without the need to use strings:

<lang lisp>((lambda (x) (list x (list 'quote x)))

 '(lambda (x) (list x (list 'quote x))))</lang>

OCaml

<lang ocaml>(fun p -> Printf.printf p (string_of_format p)) "(fun p -> Printf.printf p (string_of_format p)) %S;;\n";;</lang>

Alternative: <lang ocaml>(fun s -> Printf.printf "%s%S;;\n" s s) "(fun s -> Printf.printf \"%s%S;;\\n\" s s) ";;</lang>

Perl

This relatively simple Perl example imitates the C example.

<lang perl>$s = q($s = q(%s); printf($s, $s); ); printf($s, $s); </lang>

Note the terminating newline.

PHP

Translation of: C

<lang php><?php $p = '<?php $p = %c%s%c; printf($p,39,$p,39); ?> '; printf($p,39,$p,39); ?> </lang>

Note the terminating newline.

Python

Works with: Python version 2.x

Python's %r format conversion uses the repr() function to return a string containing the source code representation of its argument:

<lang python>x = 'x = %r\nprint x %% x' print x % x</lang>

Ruby

Found online:

$ ruby -e '_="_=%p;puts _%%_";puts _%_'
_="_=%p;puts _%%_";puts _%_
$ ruby -e '_="_=%p;puts _%%_";puts _%_' | ruby
_="_=%p;puts _%%_";puts _%_

more readably: <lang ruby>x = "x = %p; puts x %% x"; puts x % x</lang> The %p specifier outputs the result of calling the .inspect method on the argument.

Seed7

<lang seed7>$ include "seed7_05.s7i"; const array string: prog is []( "$ include \"seed7_05.s7i\";", "const array string: prog is [](", "const proc: main is func", " local var integer: number is 0;", " begin", " for number range 1 to 2 do writeln(prog[number]); end for;", " for number range 1 to 11 do", " writeln(literal(prog[number]) <& \",\");", " end for;", " writeln(literal(prog[12]) <& \");\");", " for number range 3 to 12 do writeln(prog[number]); end for;", " end func;"); const proc: main is func

 local var integer: number is 0;
 begin
   for number range 1 to 2 do writeln(prog[number]); end for;
   for number range 1 to 11 do
     writeln(literal(prog[number]) <& ",");
   end for;
   writeln(literal(prog[12]) <& ");");
   for number range 3 to 12 do writeln(prog[number]); end for;
 end func;</lang>

Original source: [1]

Tcl

There are a number of excellent quines in the Tcl wiki[2], the most useful for real-world programming probably the one that uses [info] to read the source of the currently running script. But that would be like opening its own source file.

The most straightforward one in the spirit of Quine is probably the one that uses [join], which appends the elements in the list given in its first argument with a "joining string" which is given in the second element of the list. For example the three-element list {} A B (the first element of which is an empty list):

<lang tcl>join { {} A B } any_string => any_stringAany_stringB</lang>

If "A" and "B" are replaced by literal (i.e. escaped) opening and closing curled braces, the result becomes valid Tcl code:

<lang tcl>join { {} \{ \} } something => something{something}</lang>

and re-assembling these parts with a connecting string that is exactly this operation of re-assembly:

<lang tcl>join { {} \{ \} } { join { {} \{ \} } } => join { {} \{ \} } { join { {} \{ \} } }</lang>

V

First we need a function that can print a list as a library. <lang v>[p [put ' 'put] map ' ' puts].</lang>

with that, the quine reduces to quine.v: <lang>[dup puts p] dup puts p</lang>

Using it:

$./v quine.v

<lang v>[dup puts p] dup puts p</lang>