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". * Can you print "Hello, world." ? * ''Easily.'' print("Hello, world.") * So now you know how to print *anything*. * ''A few things are a bit tricky, but yes -- anything.'' * Ah, but can you print quotes around it ? * ''It's a bit tricky, but not a problem.'' print("\"Hello, world.\"") * You've just replaced the problem of the quotes with the problem of the slash. * ''No, I can print slashes as well:'' print("quote: \" slash: \\ another slash: \\ another quote: \" The end.") * Ah, but I bet you can't print the entire program. * ''Sure I can.'' print("print(\"Hello, world.\")") * Yes, that prints the hello world program. But ... * ''Oh, I see what you want.'' print("print(\"print(\\\"Hello, world.\\\")\")") * Yes, that prints *a* program. But it doesn't print *itself*. * ''It's a bit awkward, but I suppose you want this:'' print("print(\"print(\\\"print(\\\\\\\"Hello, world.\\\\\\\")\\\")\")") * Yes, that prints *a* program. But it doesn't print *itself*. ... * Yes, that prints *a* program. But it doesn't print *itself*. * ''Oh. But that would ... that would require an infinite number of escapes.'' print(" "Hello, world." ") * Sorry, my computer doesn't have an infinite amount of memory. * ''Well then. It's impossible for a finite-size source file to hold another copy of the source file inside itself. A thing cannot be bigger than itself.'' * Obviously. ---- '''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 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 \\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 \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: *Start with any compiler. *Write a program that will not compile. *Take the error report from the compiler and compile it. This will most likely not compile. *Take the new error report and compile it. Repeat until the output matches the input. *If you consider the compiler as an interpreter (rather than a compiler) you now have a program that produces its source code as it's ouput when ''interpreted'' by the compiler. -- 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# ---- '''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: ''No, it is not cheating. It is actually very good.'' ---- And another one in PHP. From my friend [[mailto:yoz@atlas.sk Yoz]] ---- This php Quine makes it easy to add other actions easily. [[http://basicer.is-a-geek.com Basicer]] "); ?> ---- A short PHP quine is available here: http://www.dionyziz.com/Quine \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): #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 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 %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 %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 = <