Quine Program

quine
in computing, a program producing its complete source code as its only output without simply opening the source file of the program and printing the contents (such actions are considered cheating).

This type of program is offered as a somewhat more interesting alternative to HelloWorld programs.

Quines are named after the logician WillardVanOrmanQuine.


Why are quines so interesting ? Because they are "obviously impossible".

  print("Hello, world.")
  print("\"Hello, world.\"")
  print("quote: \" slash: \\ another slash: \\ another quote: \" The end.")
  print("print(\"Hello, world.\")")
  print("print(\"print(\\\"Hello, world.\\\")\")")
  print("print(\"print(\\\"print(\\\\\\\"Hello, world.\\\\\\\")\\\")\")")
...
  print(" <some stuff> <infinite number of slashes >"Hello, world.<infinite number of slashes>" <more stuff> ")


BasicLanguage


I made a correct QBASIC quine:

  A$ = "a!'dbde[39] c34);[97] 'a + c34);[98] 'b';[99] 'c';[100][101] 'e';[91] : PRINT 'CASE c';[93] ']';[33] A$;dCASE ELSE: PRINT MID$(A$, I, 1);dEND SELECTdNEXT Id"
  FOR I = 1 TO LEN(A$)
  SELECT CASE MID$(A$, I, 1)
  CASE CHR$(39): PRINT CHR$(34);
  CASE CHR$(97): PRINT "A$ = " + CHR$(34);
  CASE CHR$(98): PRINT "FOR I = 1 TO LEN(A$)";
  CASE CHR$(99): PRINT "CHR$(";
  CASE CHR$(100): PRINT
  CASE CHR$(101): PRINT "SELECT CASE MID$(A$, I, 1)";
  CASE CHR$(91): PRINT : PRINT "CASE CHR$(";
  CASE CHR$(93): PRINT "): PRINT";
  CASE CHR$(33): PRINT A$;
  CASE ELSE: PRINT MID$(A$, I, 1);
  END SELECT
  NEXT I


Possibly the shortest quine of all can be written in the (original, pre-Visual) BASIC language. It reproduces itself whether you list it or run it. Here it is:

  10 LIST
But this (and any other program) that simply outputs a source code listing should be considered cheating - for a quine to be a true quine, it must surely involve quotation.

[Yes, this is cheating. The canonical shortest quine using this sort of cheat was in c, with a compiler that would accept an empty file as input and construct an executable that echoed nothing to stdout. I can't recall if this was standard-conforming or just undefined behaviour though...]

Almost all scripting languages allow the 'empty program' cheat. [Yeah, but it is less interesting with an interpreter - and this instance predates most scripting languages.]

[It is questionable whether the 'empty program' approach even counts as cheating. It is cheating for a quine to access its own source code, either via file i/o or via special language functionality like "LIST", but an empty program does no such thing.]


BefungeLanguage


A Befunge quine:

  :0g,:93+`#@_1+


BourneShell


A trivial example in Bourne shell:

  #!/bin/sh
  cat $0
but this is really cheating because it is using cat to read its source code. A real SRP contains a copy of its source code within the code itself.


Along the same lines, the one-line script:

  #!/bin/cat
will achieve the same function without running a shell.


What about my bash quine?

  b=\' c=\\ a='echo b=$c$b c=$c$c a=$b$a$b; echo $a'
  echo b=$c$b c=$c$c a=$b$a$b; echo $a
-- Tafuni Vito - Italy - vitotafuni_AT_gmail.com


Great. Here's a shell quine based on that one, but on one line:

  b=\' c=\\ a='echo -n b=$c$b c=$c$c a=$b$a$b\;; echo $a';echo -n b=$c$b c=$c$c a=$b$a$b\;; echo $a


I took Tafuni Vito's BASH quine above and made a fork bomb with it:

  b=\' c=\\ a='yes $( echo b=$c$b c=$c$c a=$b$a$b; echo $a ) | bash &'
  yes $( echo b=$c$b c=$c$c a=$b$a$b; echo $a ) | bash &
It's a lot more heavy-duty than a traditional fork bomb, so don't complain to me if it made your system crash.


A Shell "quine":

  z=\' a='z=\\$z a=$z$a$z\; eval echo \$a'; eval echo $a
These should be called "goedels" because the technique occurs in the development of the first incompleteness theorem by Kurt Gödel in 1930 / 31.


CeeLanguage


Here is a Quine in ANSI C.

  #include <stdio.h>

const char *data[] = { " NULL};", "", "void print_string(const char *str)", "{", " const char *ptr;", " printf(\" \\\"\");", " for (ptr = str; *ptr != 0; ptr++)", " if (*ptr == '\\\\')", " printf(\"\\\\\\\\\");", " else if (*ptr == '\"')", " printf(\"\\\\\\\"\");", " else", " putchar(*ptr); ", " printf(\"\\\",\\n\");", "}", "", "int main(void)", "{", " const char **ptr;", " printf(\"#include <stdio.h>\\n\\n\");", " printf(\"const char *data[] = {\\n\");", " for (ptr = data; *ptr != NULL; ptr++)", " print_string(*ptr);", " for (ptr = data; *ptr != NULL; ptr++)", " printf(\"%s\\n\", *ptr);", " return 0;", "}", NULL};

void print_string(const char *str) { const char *ptr; printf(" \""); for (ptr = str; *ptr != 0; ptr++) if (*ptr == '\\') printf("\\\\"); else if (*ptr == '"') printf("\\\""); else putchar(*ptr); printf("\",\n"); }

int main(void) { const char **ptr; printf("#include <stdio.h>\n\n"); printf("const char *data[] = {\n"); for (ptr = data; *ptr != NULL; ptr++) print_string(*ptr); for (ptr = data; *ptr != NULL; ptr++) printf("%s\n", *ptr); return 0; }


And here's another (much shorter) one invented by AldoCortesi on an idle rainy day:

  int main(void){
  char str[]= "int main(void){ char str[]= %c%s%c; printf(str, 0x22, str, 0x22);}";
  printf(str, 0x22, str, 0x22);}
Also see: http://www.math.uchicago.edu/~chruska/recursive/selfish.html It contains additional examples.


CobolLanguage


In contrast to these concise Zen haiku things pretending to be serious quines, a QuineProgramInCobol wants its own page.


CommonLisp


Example in CommonLisp:

  ((lambda (x) (quasiquote ((unquote x) (quote (unquote x))))) (quote (lambda (x) (quasiquote ((unquote x) (quote (unquote x)))))))
which your pretty-printer may let you abbreviate as:

  ((lambda (x) `(,x ', x)) '(lambda (x) `(,x ',x)))


CompilerErrorsAreYourFriends


Years ago I came across a programming challenge (in a magazine I believe) that asked the competitors to write a QuineProgram. When the answers were published, the one that I thought was particularly clever went as follows:

-- ChrisHines


I tried this approach with GCC. However, I always end up with a cycle of length 2. Moreover, since GCC reports file names in its error messages, the name of the file is significant (how unelegant).

-- StephanHouben


quine.c:1: parse error before '.' token


This works for me with mingw.

  Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
  bcc32_interpreter_quine.c:
  Error E2141 bcc32_interpreter_quine.c 1: Declaration syntax error
  Error E2223 bcc32_interpreter_quine.c 1: Too many decimal points
  *** 2 errors in Compile ***


this works for me in SuperCollider:

  ERROR: Parse error
in file 'selected text'
line 1 char 10 :
ERROR: Parse error
in file 'selected text'
  -----------------------------------
  ERROR: Command line parse failed
  nil
all parse errors seem to converge to this fixed point.


This technique doesn't always converge in C (GCC):

  ...
  > quine4.c:2152: error: stray ‘\342’ in program
  > quine4.c:2152: error: stray ‘\200’ in program
  > quine4.c:2152: error: stray ‘\230’ in program
  > quine4.c:2152: error: stray ‘\’ in program
  > quine4.c:2152: error: stray ‘\342’ in program
  > quine4.c:2152: error: stray ‘\200’ in program
  > quine4.c:2152: error: stray ‘\231’ in program


CsharpLanguage


Here's the AldoCortesi quine in C#:

  class Quine {
static void Main() {
string f = "class Quine {{{2} static void Main() {{{2}  string f = {0}{1}{0};{2}  System.Console.WriteLine?(f, (char)0x22, f, (char)10);{2}  }}{2}}}";
System.Console.WriteLine?(f, (char)0x22, f, (char)10);
}
  }


EnglishLanguage


Here's one in English language:

  Let the following text, enclosed in double quotes, be called Text A.
  (You can really ignore Text A.  Just take note of the three dollar
  signs it contains.)

"Let the following text, enclosed in double quotes, be called Text A. (You can really ignore Text A. Just take note of the three dollar signs it contains.) $$$ Take pencil and paper, and write the following three things down, separated as paragraphs. (That's just boring copying. You needn't be interested in the text you're handling.) First, all of Text A that precedes the three dollar signs. Second, the whole of Text A, enclosed in double quotes. Third, all of Text A that follows the three dollar signs. Now step back and try to interpret what you have just written."

Take pencil and paper, and write the following three things down, separated as paragraphs. (That's just boring copying. You needn't be interested in the text you're handling.) First, all of Text A that precedes the three dollar signs. Second, the whole of Text A, enclosed in double quotes. Third, all of Text A that follows the three dollar signs. Now step back and try to interpret what you have just written.
Here is a variant on this idea: Change both "Now step back and try to interpret what you have just written." to "Now follow the instructions that you have just written." to make it into an infinite quine.


ExtendedObjectTcl


In ExtendedObjectTcl

  Object ::quine
  ::quine proc printSelf {  } {
  foreach instance [ Object info instances ] {
  foreach proc [ $instance info procs ] {
  puts "Object $instance"
  puts "$instance proc $proc \{ [ $instance info args $proc ] \} \{
  [ $instance info body $proc ]
  \}"
  }
  }
  puts "::quine printSelf"
  }
  ::quine printSelf
Does introspection count as cheating?


ForthLanguage


In ForthLanguage (assuming that the SuperCollider quine isn't cheating):

  : QUINE [ SOURCE ] SLITERAL TYPE ; QUINE
But if the quine is allowed to be interpreted code then you can just use this:

  SOURCE TYPE


FurryScript


FurryScript is normally used to generate random output, but it doesn't have to be, as shown by this program (allegedly written by the inventor of this programming language):

  ENIUQ[ DUP LT +SW +GT +< ENIUQ#> ]
  <ENIUQ[ DUP LT +SW +GT +< ENIUQ#> ]> ENIUQ#


GoLanguage


A Go(http://golang.org) quine:

  package main;import"fmt";func main(){s:="\"\\\"package main;import\"fmt\";func main(){s:=;fmt.Print(s[3:43]+s[:2]+s[:2]+s[1:2]+s[1:22]+s[1:3]+s[23:26]+s[1:3]+s[27:]+s[:1]+s[43:])}";fmt.Print(s[3:43]+s[:2]+s[:2]+s[1:2]+s[1:22]+s[1:3]+s[23:26]+s[1:3]+s[27:]+s[:1]+s[43:])}
-- by qulinxao


HaskellLanguage


Here's a really short quine in Haskell:

  ((++)<*>show)"((++)<*>show)"


HqNinePlusLanguage


How could we forget HQ9+ (HqNinePlusLanguage)?

  q

Another HQ9+ Quine:

  Hello, World


JavaLanguage


Java Quine:

  public class Quine {
public static void main(String[] args) {
String[] str = {
  "public class Quine {",
  " public static void main(String[] args) {",
  "  String[] str = {",
  "  };",
  "  for(int i=0;i<3;i++)System.out.println(str[i]);",
  "  for(int i=0;i<9;i++)System.out.println((char)34+str[i]+(char)34+',');",
  "  for(int i=3;i<9;i++)System.out.println(str[i]);",
  " }",
  "}",
};
for(int i=0;i<3;i++)System.out.println(str[i]);
for(int i=0;i<9;i++)System.out.println((char)34+str[i]+(char)34+',');
for(int i=3;i<9;i++)System.out.println(str[i]);
}
  }
--JasonWilson?


Sorry, just had to:

  enum Q{T;System a;String b="enum Q{T;System a;String b=%c%s%c;{a.out.printf(b,34,b,34);a.exit(0);}}";{a.out.printf(b,34,b,34);a.exit(0);}}
--lf


JavaScript


A Javascript quine (works in Rhino, or anywhere else where 'print' means 'to a console', not 'to a printer'):

  (function a(){print('('+a+')()')})()


A javascript quine without using fact that prog have access to func def:

  _='"'+";document.write('_=',_[17],_[0],_[17],'+',_,_)";document.write('_=',_[17],_[0],_[17],'+',_,_)
in Rhino maybe :

  _='"'+";print('_=',_[8],_[0],_8],'+',_,_)";print('_=',_[8],_[0],_8],'+',_,_)


JayLanguage


Here's one in JayLanguage

  (,q,q,~]#~[:>:]=q=.'"_)'(,q,q,~]#~[:>:]=q=.'"_)'
aaarg there should be four consecutive single quotes after the first q=. and eight after the second one but I've been unable to convince Wiki to display more than three! Could a Wiki wizard fix this, please?


LuaLanguage


Lua Quine

  s="s=%qprint(s:format(s))"print(s:format(s))
http://lua-users.org/lists/lua-l/2008-05/msg00379.html


MicrosoftExcel


  =SUBSTITUTE(SUBSTITUTE("=SUBSTITUTE(SUBSTITUTE(#@#,CHAR(35),CHAR(34)),CHAR(64),#@#)",CHAR(35),CHAR(34)),CHAR(64),"=SUBSTITUTE(SUBSTITUTE(#@#,CHAR(35),CHAR(34)),CHAR(64),#@#)")
--Jonathan Rynd


  =SUBSTITUTE("=SUBSTITUTE(@,CHAR(64),CHAR(34)&@&CHAR(34))",CHAR(64),CHAR(34)&"=SUBSTITUTE(@,CHAR(64),CHAR(34)&@&CHAR(34))"&CHAR(34))
--dave@burt.id.au


MsDos


Here is a quine in MS-DOS (that I made up myself):

  @echo off
  %1 %2
  call %0 goto e %%
  call %0 goto e %%3 echo.%%4
  echo :f
  goto f
  :e
  echo.%4@echo off
  echo.%4%31 %32
  echo.%4call %30 goto e %3%3
  echo.%4call %30 goto e %3%33 echo.%3%34
  echo.%4echo :f
  echo.%4goto f
  echo.%4:e
  :f


NemerleLanguage


A basic AqABqB-style quine in NemerleLanguage:

  using System.Console;
  module quine {
Main():void {
def a = @"using System.Console;
  module quine {
Main():void {
def a = @;
Write(a.Substring(0,72));Write(34:>char);
Write(a);Write(34:>char);
Write(a.Substring(72,(a.Length -72)));
}
  }
  ";
Write(a.Substring(0,72));Write(34:>char);
Write(a);Write(34:>char);
Write(a.Substring(72,(a.Length -72)));
}
  }


PascalLanguage


Pascal/Delphi:

  const a=';begin write(^#^/^.^3^4^`^!^}#39,a,#39,a)end.';begin write(^#^/^.^3^4^`^!^}#39,a,#39,a)end.
--Geoffrey Swift (http://www.trollied.org/~blimey/quines.php)


PathLanguage


Some languages provide a bigger challenge than others when it comes to writing quines. Often it is easer to write part of a quine, then write another program that writes the rest. An example is this quine in PathLanguage: http://www.phong.org/bf/quine2.path


PerlLanguage


A 32-character quine in Perl:

  $_=q{print"\$_=q{$_};eval"};eval


A 31-character quine in Perl:

  print<<''x2,$/
  print<<''x2,$/

Note: both trailing newlines are necessary!


A 28-character quine in Perl, which seems to be the shortest known non-cheating Perl quine (by Ilmari Karonen):

  printf+qw(printf+qw(%s)x2)x2


A 15-character quine in Perl, although this is a cheat, as it opens and reads its own source:

  open+0;print<0>


PhpLanguage


Here's a PhpLanguage QuineProgram:

  <?

# PHP Quine written by Ian Kjos - brooke@sf.net

$y = "function q(\$q) { \$q = str_replace('\\\\', '\\\\\\\\', \$q); \$q = str_replace('\$', '\\\\\$', \$q); \$q = str_replace('\\n', '\\\\n', \$q); \$q = str_replace('\"', '\\\\\"', \$q); return \$q; }

echo \"<?\\n\\n\"; echo \"# PHP Quine written by Ian Kjos - brooke@sf.net \\n\\n\"; echo '\$y = \"' . q(\$y) . '\";'; echo \"\\n\\neval(\"; echo '\$y);'; echo \"\\n\\n\\n\"; ";

eval($y);


Here's another PHP quine. Is this cheating?? (Also, remove the extra line breaks if you run this, I can't get this wiki to accept single line breaks for some reason)

  <?php
  // PHP quine by Sam Barnum 360works.com
  // 2003-11-08
  $dna = 'PD9waHAKLy8gUEhQIHF1aW5lIGJ5IFNhbSBCYXJudW0gMzYwd29ya3MuY29tCi8vIDIwMDMtMTEtMDgKJGRuYSA9ICcqJzsKZWNobyBzdHJfcmVwbGFjZShjaHIoNDIpLCAkZG5hLCBiYXNlNjRfZGVjb2RlKCRkbmEpKTsKPz4K';
  echo str_replace(chr(42), $dna, base64_decode($dna));
  ?>
No, it is not cheating. It is actually very good.


And another one in PHP. From my friend [[mailto:yoz@atlas.sk Yoz]]

  <?
  $a='chr(60).chr(63).chr(10).chr(36).chr(97).chr(61).chr(39).$a.chr(39).chr(59).chr(10)."echo $a;".chr(10).chr(63).chr(62)';
  echo chr(60).chr(63).chr(10).chr(36).chr(97).chr(61).chr(39).$a.chr(39).chr(59).chr(10)."echo $a;".chr(10).chr(63).chr(62);
  ?>


This php Quine makes it easy to add other actions easily. [[http://basicer.is-a-geek.com Basicer]]

  <?
  function selffunc($a) { print($a . "\n"); print("selffunc(\"" . addcslashes($a,"\n\\\"$") . "\");\n"); }
  selffunc("<?\nfunction selffunc(\$a) { print(\$a . \"\\n\"); print(\"selffunc(\\\"\" . addcslashes(\$a, \"\\n\\\\\\\"\$\") . \"\\\");\\n\"); }");
  function selfact($a) { print("selfact(\"" . addcslashes($a,"\n\\\"$") . "\");\n"); exec($a); }
  selffunc("function selfact(\$a) { print(\"selfact(\\\"\" . addcslashes(\$a,\"\\n\\\\\\\"\$\") . \"\\\");\\n\"); exec(\$a); }");
  function selffunc2($a) { print("selffunc2(\"" . addcslashes($a,"\\\"$") . "\");\n"); print($a . "\n"); }
  selffunc("function selffunc2(\$a) { print(\"selffunc2(\\\"\" . addcslashes(\$a,\"\\\\\\\"\$\") . \"\\\");\\n\");  print(\$a . \"\\n\"); }");
  //The Self Act Code executes any command.
  selffunc("//The Self Act Code executes any command.");
  selfact("\$a = fopen('log.txt','w'); fwrite(\$a,\"Hello\"); fclose(\$a);");
  selffunc2("?>");
  ?>


A short PHP quine is available here: http://www.dionyziz.com/Quine

  <?printf($c='<?printf($c=%s,\'\\\'\'.addslashes($c).\'\\\'\');','\.addslashes($c).'\);
I wish this wiki had a way to add literal characters so that I could directly paste it over, but it won't let me.


My short (60 bytes) PHP quine:

  <?$a='<?$a=%c%s%c;printf($a,39,$a,39);';printf($a,39,$a,39);
(Actually, the 8 bytes longer

  <?php $a='<?php $a=%c%s%c;printf($a,39,$a,39);';printf($a,39,$a,39);
is the preferred form, since the short '<?' may not be supported on all servers)

On the web I found the even shorter PHP quine, written by Trevor Sayre:

  <?php printf($a='<?php printf($a=%c%s%c,39,$a,39);',39,$a,39);
or
  <?printf($a='<?printf($a=%c%s%c,39,$a,39);',39,$a,39);
-- Tom van der Beek


With the use of non-standard Ascii characters, a 38 byte PHP quine can be produced:

  <?printf(~$s=ÃÀ–‘‹™×ÛŒÂÚŒÓÛŒÖÄ,$s);
This will need to be saved with ANSI character encoding to work properly. Or alternatively, it may be generated with the following:

  <?printf(~$s="\xc3\xc0\x8f\x8d\x96\x91\x8b\x99\xd7\x81\xdb\x8c\xc2\xda\x8c\xd3\xdb\x8c\xd6\xc4",$s);
-- Mike Tryczak (a.k.a. primo - http://www.phpgolf.org/user/primo)


Yet another php quine, by vejux. Php specific. It processes its own output, not the source code, so it should not be concidered cheating. (Use single new lines)

  <?
  function c($b) { return "<"."?\n$b?".">\n$b"; } ob_start("c");
  ?>
  function c($b) { return "<"."?\n$b?".">\n$b"; } ob_start("c");


Here's a PhpLanguage QuineProgram by Opanasjuk Yegor (cheat):

 <?php
  $sFile = file_get_contents(__FILE__);
  echo $sFile;


Another (cheat) PHP quine:

  <?=file_get_contents(__FILE__);
or alternatively:

  <?readfile(__FILE__);


PliLanguage


The following is (probably) the shortest possible Quine in PL/I. It only compiles with he old V2.3.0 compiler and requires a few non-standard compiler options, COMPILE and MAR(1,90,0) (Source starts in column 1!)

  %dcl z%z=&apos;put edit&apos;;proc options(main;q=&apos;&apos;&apos;&apos;put list(m;do i=1,2;z(q)skip;do j=
  1to 78c=substr(m(i),j;if c=q z(c;z(c;end;z(q&apos;,&apos;;dcl(c,q)char,m(2)char(99)init(
  &apos;%dcl z%z=&apos;&apos;put edit&apos;&apos;;proc options(main;q=&apos;&apos;&apos;&apos;&apos;&apos;&apos;&apos;put list(m;do i=1,2;z(q)skip;do j=&apos;,
  &apos;1to 78c=substr(m(i),j;if c=q z(c;z(c;end;z(q&apos;&apos;,&apos;&apos;;dcl(c,q)char,m(2)char(99)init(&apos;,
This entry has big trouble with repeated single quotes...


PolyGlot?


Here's the classic Loophole Quine. In addition to being the shortest ever quine in Python, it is an all-language PolyGlot?, and in LazyKayLanguage, it even acts as UNIX cat with no arguments. Here it is:

...That's it. Nothing. 0 bytes of self-replicating quine. XD and LOL.


"Hello" is a quine in many languages?


If you're masochistic, you may want to write a quine that is also a polyglot (see HelloPolyGlots). Here is a quine that works as CeeLanguage, CeePlusPlus, PerlLanguage and PythonLanguage:

  #include <stdio.h>
  #define q(a,...) a
  #define substr q
  #define eval(a) main(){char c[]=a,n=10;c[419]=0;printf(c+4,n,n,n,n,34,34,n,34,39,c+4,39,34,n); }/* Copyright (C) Thomas Schumm <phong@phong.org>
  exec("from sys import*;substr=q=lambda y:exit(stdout.write(y[4:-46]%((10,)*4+(34,34,10,34,39, y[4:-46],39,34,10))))",None);#*/
  eval(substr(q("$p='#include <stdio.h>%c#define q(a,...) a%c#define substr q%c#define eval(a) main() {char c[]=a,n=10;c[419]=0;printf(c+4,n,n,n,n,34,34,n,34,39,c+4,39,34,n); }/* Copyright (C) Thomas Schumm <phong@phong.org>%cexec(%cfrom sys import*;substr=q=lambda y: exit(stdout.write(y[4:-46]%%((10,)*4+(34,34,10,34,39,y[4:-46],39,34,10))))%c,None);# */%ceval(substr(q(%c$p=%c%s%c;printf($p,(10)x4,34,34,10,34,39,$p,39,34,10)%c),1,-1))%c'; printf($p,(10)x4,34,34,10,34,39,$p,39,34,10)"),1,-1))
When I compiled and ran as C/C++, it didn't work (missing only a few characters)--a change made to gcc?

Working fine for me with gcc 3.3.4...

The original is here (I may occasionally update it if it gets better or smaller): http://www.phong.org/bf/polyglotC++PerlPythonC.c -- TomSchumm


  ;; (*.) = {- *) let (@@) x y = x::y let e = [] let a = (*
  (letrec ((a '(
  ; -} -- *)
"" @@
"A polyglot quine in" @@
"Haskell & O'Caml & Scheme" @@
"" @@
"  Usage:  runhugs thisfile# www.haskell.org/hugs  " @@
"  ocamlc -o x thisfile.ml ;./x  # www.ocaml.org " @@
"  scsh -s thisfile# www.scsh.net  " @@
"" @@
"" @@
";; (*.) = {- *) let (@@) x y = x::y let e = [] let a = (*" @@
"(letrec ((a '(" @@
"; -} -- *)" @@
"" @@
" e" @@
";; (*:) = [\" \" ++ show x ++ \" @@\" | x<-( *.)]; main = {-" @@
"; -} mapM_ putStrLn (x ++ ( *:) ++ y); (x, _:y) = {-" @@
"; -} span p (tail (dropWhile p ( *.))); p = (/= \"\"); infixr {-" @@
"; -} @@; (@@) = (:); e = [] {- *) let rec s = function [] -> (*" @@
"; *) [],[] | \"\"::y -> [],y | x::y -> let a,b = s y (*" @@
"; *) in x::a,b let b,d = s (snd (s a)) let f = String.escaped (*" @@
"; *) let c = List.map (fun x -> \" \\\"\" ^ f x ^ \"\\\" @@\") a" @@
";; List.iter print_endline (b @ c @ d) (*" @@
")) (f (lambda (x) (if (null? x) x (if (string? (car x)) (cons (" @@
"car x) (f (cdr x))) (f (cdr x)))))) (g (lambda (x) (if (string=?" @@
"\"\" (car x)) (cons '() (cdr x)) (let ((y (g (cdr x)))) (cons (" @@
"cons (car x) (car y)) (cdr y)))))) (h (lambda (x) (if (null? x)" @@
"#f (begin (display (car x)) (newline) (h (cdr x)))))) (i (lambda" @@
"(x) (if (null? x) #f (begin (display \" \") (write (car x)) (" @@
"display \" @@\") (newline) (i (cdr x))))))) (let ((b (g (cdr (g" @@
"(f a)))))) (h (car b)) (i (f a)) (h (cdr b))))" @@
"; -} -- *)" @@
e
  ;; (*:) = [" " ++ show x ++ " @@" | x<-( *.)]; main = {-
  ; -} mapM_ putStrLn (x ++ ( *:) ++ y); (x, _:y) = {-
  ; -} span p (tail (dropWhile p ( *.))); p = (/= ""); infixr {-
  ; -} @@; (@@) = (:); e = [] {- *) let rec s = function [] -> (*
  ; *) [],[] | ""::y -> [],y | x::y -> let a,b = s y (*
  ; *) in x::a,b let b,d = s (snd (s a)) let f = String.escaped (*
  ; *) let c = List.map (fun x -> " \"" ^ f x ^ "\" @@") a
  ;; List.iter print_endline (b @ c @ d) (*
  )) (f (lambda (x) (if (null? x) x (if (string? (car x)) (cons (
  car x) (f (cdr x))) (f (cdr x)))))) (g (lambda (x) (if (string=?
  "" (car x)) (cons '() (cdr x)) (let ((y (g (cdr x)))) (cons (
  cons (car x) (car y)) (cdr y)))))) (h (lambda (x) (if (null? x)
  #f (begin (display (car x)) (newline) (h (cdr x)))))) (i (lambda
  (x) (if (null? x) #f (begin (display " ") (write (car x)) (
  display " @@") (newline) (i (cdr x))))))) (let ((b (g (cdr (g
  (f a)))))) (h (car b)) (i (f a)) (h (cdr b))))
  ; -} -- *)
D'oh, that's got me beat. -- TomSchumm


PostScript


  (dup == =)
  dup == =
(note this doesn't produce output to paper, but rather to the terminal; run it with gs) --Chris King


PythonLanguage


This one is inspired by the below RubyLanguage example

  s = 's = {0!r}; print s.format(s)'; print s.format(s)


And here is another

  _="print '_='+chr(34)+_+chr(34)+'; exec(_)'"; exec(_)


RexxLanguage


RexxLanguage has a SOURCELINE command that prints the source of a line of the program (meant for use with error messages), so the following should work as a Quine in REXX (don't have an interpreter to check right now):

 sourceline 1
That's cheating, though, akin to the bash one above that uses cat $0


RubyLanguage


Here's one in RubyLanguage

  puts(s = <<e, s, 'e')
  puts(s = <<e, s, 'e')
  e


And another in RubyLanguage

  s="s=%s;printf s,s.dump";printf s,s.dump


SchemeLanguage


For starters, here is the classic Quine in SchemeLanguage:

  ((lambda (x) `(,x ',x)) '(lambda (x) `(,x ',x)))
Using outside-language facilities to access the source is considered cheating. E.g. opening the source as a text file would be cheating. But cheating in original ways is strongly encouraged. ;-)


SuperCollider


Here's one in SuperCollider.

  { thisFunction.asCompileString ++ ".value" }.value


SwiftLanguage


Here's one in SwiftLanguage

  {println($0+$0.debugDescription+")")}("{println($0+$0.debugDescription+\")\")}(")


UnknownLanguage?


  repeat x 2 : output xpose list 2 crlf <<"
  repeat x 2 : output xpose list 2 crlf <<"


ZeeShell?


In AnarchyGolf? the current directory contains only one file, which is the script itself. Which means in Zsh you can do the following two byte cheating quine:

  <*
For a self-reproducing program in Oberon, see http://www.modulaware.com/mdlt/mdlt78.htm For a lot more see http://www.nyx.net/~gthompso/quine.htm


OK I've got to ask: would it be cheating for the program to access its binary image, reverse compile itself, and write the result to stdout?


See SelfReplication, MixingLevels, SelfAssembly


An old IOCCC entry forever cinched the spot of shortest quine - at one point, gcc would, given the right compiler switches, compile a zero-byte C program into a program that does nothing. Thus, it is a zero-byte program that produces a zero-byte output - a perfect quine!


An *actual* quine. Use Assembly since you have the instruction pointer readily in hand. You can save the instruction pointer, and have the program hard code how many lines it has, then use a loop to print each line of code. The entire program would simply be a way to decompile assembly statements into printable text. This isn't a cheat since assembly is loaded into memory because assembly is loaded into memory as a prerequisite to running the program. -- LeeLouviere

I'd call it cheating for a program to load from the program portion of its allocated space in memory, or any part of the non-writable portion of its memory that doesn't contain data literals. You can make an assembly quine with these restrictions -- DavidRutter


These programs should be named `Gödels' or `Goedels'. The technique which underlies them is to be found in the proof of the first Incompleteness Theorem, and that occurs before Quine's ideas (cf. Kurt Gödel's Collected Works I, p. 175). –Kela


CategoryCoding


EditText of this page (last edited November 20, 2014) or FindPage with title or text search