Quine

From Rosetta Code
Jump to: navigation, search
Task
Quine
You are encouraged to solve this task according to the task description, using any language you may know.

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."

"Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.

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 a character string, or a literal data structure). 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. Empty programs producing no output are not allowed.

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 or structural 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 escaped, 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.


See the nostalgia note under Fortran.

Contents

[edit] ABAP

I copied one of my examples from http://www.yaabb.de/viewtopic.php?t=44

REPORT R NO STANDARD PAGE HEADING LINE-SIZE 67.
DATA:A(440),B,C,N(3) TYPE N,I TYPE I,S.
A+000 = 'REPORT R NO STANDARD PAGE HEADING LINE-SIZE 6\7.1DATA:A'.
A+055 = '(440),B,C,N(\3) TYPE N,I TYPE I,S.?1DO 440 TIMES.3C = A'.
A+110 = '+I.3IF B = S.5IF C CA `\\\?\1\3\5\7`.7B = C.5ELSEIF C ='.
A+165 = ' `\``.7WRITE ```` NO-GAP.5ELSE.7WRITE C NO-GAP.5ENDIF.3'.
A+220 = 'ELSEIF B = `\\`.5WRITE C NO-GAP.5B = S.3ELSEIF B = `\?`'.
A+275 = '.5DO 8 TIMES.7WRITE:/ `A+` NO-GAP,N,`= ``` NO-GAP,A+N(\'.
A+330 = '5\5) NO-GAP,```.`.7N = N + \5\5.5ENDDO.5B = C.3ELSE.5WR'.
A+385 = 'ITE AT /B C NO-GAP.5B = S.3ENDIF.3I = I + \1.1ENDDO. '.
DO 440 TIMES.
C = A+I.
IF B = S.
IF C CA '\?1357'.
B = C.
ELSEIF C = '`'.
WRITE '''' NO-GAP.
ELSE.
WRITE C NO-GAP.
ENDIF.
ELSEIF B = '\'.
WRITE C NO-GAP.
B = S.
ELSEIF B = '?'.
DO 8 TIMES.
WRITE:/ 'A+' NO-GAP,N,'= ''' NO-GAP,A+N(55) NO-GAP,'''.'.
N = N + 55.
ENDDO.
B = C.
ELSE.
WRITE AT /B C NO-GAP.
B = S.
ENDIF.
I = I + 1.
ENDDO.

Here is another one, requiring SY-SAPRL >= '620':

REPORT R NO STANDARD PAGE HEADING.DATA:A TYPE TABLE OF STRING,B(8).APPEND:
`REPORT.FORM F TABLES T.NEW-PAGE LINE-SIZE 78.WRITE:'REPORT R NO',` TO A,
`'STANDARD PAGE HEADING.DATA:A TYPE TABLE OF STRING,B(8).APPEND:'.LOOP` TO A,
`AT T.REPLACE ALL OCCURENCES OF'``' IN T WITH'````'.WRITE:/'``'` TO A,
`NO-GAP,T NO-GAP,'`` TO A,'.ENDLOOP.WRITE:AT 78'.','GENERATE',` TO A,
`'SUBROUTINE POOL A NAME B.PERFORM F IN PROGRAM (B) TABLES A.'.ENDFORM.` TO A.
GENERATE SUBROUTINE POOL A NAME B.PERFORM F IN PROGRAM (B) TABLES A.

Please note that the program still works if you fix the spelling error (s/OCCURENCES/OCCURRENCES/), thus increasing the size of the source code by 1 character.

One more program, created in a 7.0 unicode system, but it should work in any SAP system with SY-SAPRL >= '700', even if you'll have a hard time verifying the correctness just by studying the source code:

REPORT A NO STANDARD
PAGE HEADING

LINE-SIZE
72.DATA:C(33),A LIKE
TABLE OF C,X(3333)
TYPE X,Y TYPE
XSTRING.DEFINE A.X+C
='&1'.C = C + 33.
END-OF-DEFINITION.
DEFINE B.LOOP AT A
INTO C &1 &2.WRITE
/ C.ENDLOOP.
END-OF-DEFINITION.
A FF060201020280003431303300000000AC030000121F9D02BB522ADA69108AA1C7 .
A E8B32FFEC07DD21907936962B28407983089732C8811FC4413FD02A7BFE6690B03 .
A 262F72B38EF69EB6A7A71C9F82CF44CC11469E081F86785777F269DE372CE9EC4B .
A 5E0A24D8224781128E290E1B7A0ECFF423BEDFD316B43B456FE9AD98E1F0401B31 .
A 9E11B3A23F3C865EEB6D028FD532BC69DED831F41DE6F0B59F745E604996373C97 .
A 982A2FA9F6C81A86164CCC98D4CC91D22E89AB9A1CCBEB6A97A839A5602BA26AFE .
A 7791BF4C2A9DBE6866134E093BD82CA291CF2A57EC67E81017384740EB33E6102A .
A 174784531EFEA076A29A7ACAD9EB55CED8316374D3E00D3DEC1CF36E4D4C4EE64E .
A 75B28DB568C195BA3DE92F9CC48AAAAF3A4DD9CC6BE899E27C18A3B66ECBF65093 .
A FFF1168545878AD10C4F075F588821EF947739516EBF7D99F5851D52F629E8D5AC .
A 13EF77291306AA6CABF7B56EC9E273F47997DA3FE146FB2A2C30E3BE22FEA603B4 .
A EDB5FBEE64A7637B35B46DD79491EEC2D1A19B26C0ADAAB2FB39F9050000000000 .
Y = X.IMPORT A = A
FROM DATA BUFFER Y.B
TO 13.C = 0.DO 12
TIMES.WRITE:/'A',
X+C(33),'.'.C = C +
33.ENDDO.B FROM 14.

And a final one (cheating, even though not using READ REPORT), it should work in any SAP system with SY-SAPRL >= '46B':

.REPORT Q NO STANDARD PAGE HEADING LINE-SIZE 72
.DATA QQ(69) OCCURS 0
.DATA Q LIKE QQ WITH HEADER LINE
.APPEND 'SYNTAX-TRACE ON.INCLUDE' TO QQ
.APPEND SY-REPID TO QQ
.APPEND '.' TO QQ
.SYNTAX-CHECK FOR QQ MESSAGE Q LINE Q WORD Q TRACE-TABLE Q
.LOOP AT Q
.CHECK Q(1) = '#'
.Q = Q+5
.IF Q < Q OR SY-SAPRL > '5'
.SPLIT Q AT '' INTO Q Q
.ENDIF
.IF Q < Q OR SY-LINNO < 22
.CHECK Q CA 'Q.' OR Q+4 = 'F'
.ENDIF
.IF Q < Q OR SY-LINNO > 23
.CHECK Q CA '.'
.ENDIF
.CHECK Q(1) NA 'IT+' OR Q+1(1) = 'F'
.WRITE / '.' NO-GAP
.WRITE Q
.ENDLOOP
.WRITE / '.'
.

[edit] ACL2

(defun print-quine (quine)
(cw quine quine))
(print-quine
"(defun print-quine (quine)
(cw quine quine))
(print-quine ~x0)~%"
)

A shorter one:

(let((q"(let((q~x0))(cw q q))"))(cw q q))

[edit] Ada

The program text must be in one line.

with Ada.Text_IO;procedure Self is Q:Character:='"';A:String:="with Ada.Text_IO;procedure Self is Q:Character:='&#39;;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;

[edit] Aime

integer f;
text s, t;
 
f = 36;
s = "integer f;
text s, t;
 
f = 36;
s = \"\";
 
o_text(cut(s, 0, f));
o_text(cut(s, 0, f - 1));
o_etext(cut(s, f - 1, 2));
o_text(cut(s, f + 1, 8888 - f));
o_text(cut(s, f, 8888 - f));
";
 
o_text(cut(s, 0, f));
o_text(cut(s, 0, f - 1));
o_etext(cut(s, f - 1, 2));
o_text(cut(s, f + 1, 8888 - f));
o_text(cut(s, f, 8888 - f));

[edit] ALGOL 68

The following program assumes that the target machine is ASCII, hence the use of character 34 as a double quote.

STRINGa="STRINGa=,q=REPR34;print(a[:8]+q+a+q+a[9:])",q=REPR34;print(a[:8]+q+a+q+a[9:])

The following is a shorter and character set independent - hence portable - implementation.

[]CHARa="[]CHARa="";print(2*a[:9]+2*a[9:])";print(2*a[:9]+2*a[9:])

The original program - from which this is derived - was written by Richard Wendland, who is one of the team who implemented Algol 68 on Honeywell's Multics. The original can be found in Algol Bulletin 46 - 2.1 - Page 5.

[edit] Applesoft BASIC

10 LIST

[edit] AutoHotkey

All from http://www.autohotkey.com/forum/viewtopic.php?t=14336: The "cheating" way:

FileRead, quine, %A_ScriptFullPath%
MsgBox % quine

Another:

D(n, s) 
{
global
Loop %n%
{
l := %s%%A_Index%
If l = #
l := "script =" . nl . "( %" . nl . script . nl . ")"
FileAppend %l%%nl%, %A_ScriptDir%\Q.txt
}
}
nl := Chr(13) . Chr(10)
script =
( %
D(n, s)
{
global
Loop %n%
{
l := %s%%A_Index%
If l = #
l := "script =" . nl . "( %" . nl . script . nl . ")"
FileAppend %l%%nl%, %A_ScriptDir%\Q.txt
}
}
nl := Chr(13) . Chr(10)
#
StringSplit q, script, %nl%
D(q0, "q")
)
StringSplit q, script, %nl%
D(q0, "q")

Another:

quote := Chr(34) 
sep := Chr(36)
nl := Chr(13) . Chr(10)
script := "quote := Chr(34)$sep := Chr(36)$nl := Chr(13) . Chr(10)$script := #$s := script$StringReplace script, script, %sep%, %nl%, All$StringReplace script, script, #, %quote%%s%%quote%$FileAppend %script%, %A_ScriptDir%\Q.txt"
s := script
StringReplace script, script, %sep%, %nl%, All
StringReplace script, script, #, %quote%%s%%quote%
FileAppend %script%, %A_ScriptDir%\Q.txt

Another "cheating" method:

FileCopy, %A_ScriptFullPath%, %A_ScriptDir%\Copy-Of--%A_ScriptName%

[edit] BASIC

ZX Spectrum Basic For dialects of BASIC that include the LIST command, Quines are trivial.

10 LIST

For dialects that include the DATA keyword, it is almost as easy.

Works with: 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 ""

[edit] Batch File

@type %0

For Windows 2000 and later only:

@type "%~f0"

[edit] BBC BASIC

      PRINT $(PAGE+22)$(PAGE+21):REM PRINT $(PAGE+22)$(PAGE+21):REM
Works with: ARM BBC BASIC
      PRINT $(PAGE+23)$(PAGE+22):REM PRINT $(PAGE+23)$(PAGE+22):REM

[edit] 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.)

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

[edit] Bob

 
c=","; n="\n"; q="\""; s="\\";
v=\[
"c=\",\"; n=\"\\n\"; q=\"\\\"\"; s=\"\\\\\";",
"v=\\[",
"define prtQuote(str) {",
" local j,t,v;",
" stdout.Display(q);",
" for (j=0; j<str.size; j++) {",
" t = str.Substring(j,1);",
" if (t==q) { stdout.Display(s); }",
" if (t==s) { stdout.Display(s); }",
" stdout.Display(t);",
" }",
" stdout.Display(q);",
"}",
"for(i=0; i<2; i++){ stdout.Display(v[i]); stdout.Display(n); }",
"for(i=0; i<v.size-1; i++){ prtQuote(v[i]); stdout.Display(c); stdout.Display(n); }",
"prtQuote(v[v.size-1]); stdout.Display(n);",
"stdout.Display(v[v.size-1]); stdout.Display(n);",
"for(i=2; i<v.size-1; i++){ stdout.Display(v[i]); stdout.Display(n); }",
"];"
];
define prtQuote(str) {
local j,t,v;
stdout.Display(q);
for (j=0; j<str.size; j++) {
t = str.Substring(j,1);
if (t==q) { stdout.Display(s); }
if (t==s) { stdout.Display(s); }
stdout.Display(t);
}
stdout.Display(q);
}
for(i=0; i<2; i++){ stdout.Display(v[i]); stdout.Display(n); }
for(i=0; i<v.size-1; i++){ prtQuote(v[i]); stdout.Display(c); stdout.Display(n); }
prtQuote(v[v.size-1]); stdout.Display(n);
stdout.Display(v[v.size-1]); stdout.Display(n);
for(i=2; i<v.size-1; i++){ stdout.Display(v[i]); stdout.Display(n); }
 

Bob is a dynamic object-oriented language with syntax similar to C/C++, Java, and JavaScript. Bob was created by David Betz, a former technical editor for DDJ, and the author of XLisp and XScheme, among other languages.

quine$

[edit] Brainf***

->+>+++>>+>++>+>+++>>+>++>>>+>+>+>++>+>>>>+++>+>>++>+>+++>>++>++>>+>>+>++>++>+>>>>+++>+>>>>++>++>>>>+>>++>+>+++>>>++>>++++++>>+>>++>
+>>>>+++>>+++++>>+>+++>>>++>>++>>+>>++>+>+++>>>++>>+++++++++++++>>+>>++>+>+++>+>+++>>>++>>++++>>+>>++>+>>>>+++>>+++++>>>>++>>>>+>+>+
+>>+++>+>>>>+++>+>>>>+++>+>>>>+++>>++>++>+>+++>+>++>++>>>>>>++>+>+++>>>>>+++>>>++>+>+++>+>+>++>>>>>>++>>>+>>>++>+>>>>+++>+>>>+>>++>+
>++++++++++++++++++>>>>+>+>>>+>>++>+>+++>>>++>>++++++++>>+>>++>+>>>>+++>>++++++>>>+>++>>+++>+>+>++>+>+++>>>>>+++>>>+>+>>++>+>+++>>>+
+>>++++++++>>+>>++>+>>>>+++>>++++>>+>+++>>>>>>++>+>+++>>+>++>>>>+>+>++>+>>>>+++>>+++>>>+[[->>+<<]<+]+++++[->+++++++++<]>.[+]>>
[<<+++++++[->+++++++++<]>-.------------------->-[-<.<+>>]<[+]<+>>>]<<<[-[-[-[>>+<++++++[->+++++<]]>++++++++++++++<]>+++<]++++++
[->+++++++<]>+<<<-[->>>++<<<]>[->>.<<]<<]

[edit] Burlesque

Using the official interpreter:

 
blsq ) "I'm a quine."
"I'm a quine."
 

Every string, every number, every block is a quine.

[edit] C

#include <stdio.h>
 
static char sym[] = "\n\t\\\"";
 
int main(void) {
const char *code = "#include <stdio.h>%c%cstatic char sym[] = %c%cn%ct%c%c%c%c%c;%c%cint main(void) {%c%cconst char *code = %c%s%c;%c%cprintf(code, sym[0], sym[0], sym[3], sym[2], sym[2], sym[2], sym[2], sym[2], sym[3], sym[3], sym[0], sym[0], sym[0], sym[1], sym[3], code, sym[3], sym[0], sym[1], sym[0], sym[0], sym[1], sym[0], sym[0]);%c%c%creturn 0;%c}%c";
printf(code, sym[0], sym[0], sym[3], sym[2], sym[2], sym[2], sym[2], sym[2], sym[3], sym[3], sym[0], sym[0], sym[0], sym[1], sym[3], code, sym[3], sym[0], sym[1], sym[0], sym[0], sym[1], sym[0], sym[0]);
 
return 0;
}
 

[edit] C#

class Program { static void Main() { var s = "class Program {{ static void Main() {{ var s = {0}{1}{0}; System.Console.WriteLine(s, (char)34, s); }} }}"; System.Console.WriteLine(s, (char)34, s); } }

[edit] C++

#include <iostream>
 
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\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;
}

[edit] C1R

The C1R compiler usually copies C solutions from tasks at Rosetta Code. The Quine task is an exception; it gets special treatment in the C1R compiler.

Quine

[edit] Clojure

((fn [x] (list x (list (quote quote) x))) (quote (fn [x] (list x (list (quote quote) x)))))

[edit] COBOL

The following two quines were in a gray past (around 2004?) posted to the (currently inaccessible) language forum of the mvsHelp Boards

       IDENTIFICATION DIVISION.
PROGRAM-ID. GRICE.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SPECIAL-NAMES.
SYMBOLIC CHARACTERS FULL-STOP IS 76.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT OUTPUT-FILE ASSIGN TO OUTPUT1.
DATA DIVISION.
FILE SECTION.
FD OUTPUT-FILE
RECORDING MODE F
LABEL RECORDS OMITTED.
01 OUTPUT-RECORD PIC X(80).
WORKING-STORAGE SECTION.
01 SUB-X PIC S9(4) COMP.
01 SOURCE-FACSIMILE-AREA.
02 SOURCE-FACSIMILE-DATA.
03 FILLER PIC X(40) VALUE
" IDENTIFICATION DIVISION. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" PROGRAM-ID. GRICE. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" ENVIRONMENT DIVISION. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" CONFIGURATION SECTION. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" SPECIAL-NAMES. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" SYMBOLIC CHARACTERS FULL-STOP".
03 FILLER PIC X(40) VALUE
" IS 76. ".
03 FILLER PIC X(40) VALUE
" INPUT-OUTPUT SECTION. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" FILE-CONTROL. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" SELECT OUTPUT-FILE ASSIGN TO ".
03 FILLER PIC X(40) VALUE
"OUTPUT1. ".
03 FILLER PIC X(40) VALUE
" DATA DIVISION. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" FILE SECTION. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" FD OUTPUT-FILE ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" RECORDING MODE F ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" LABEL RECORDS OMITTED. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" 01 OUTPUT-RECORD ".
03 FILLER PIC X(40) VALUE
" PIC X(80). ".
03 FILLER PIC X(40) VALUE
" WORKING-STORAGE SECTION. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" 01 SUB-X ".
03 FILLER PIC X(40) VALUE
" PIC S9(4) COMP. ".
03 FILLER PIC X(40) VALUE
" 01 SOURCE-FACSIMILE-AREA. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" 02 SOURCE-FACSIMILE-DATA. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" 03 FILLER ".
03 FILLER PIC X(40) VALUE
" PIC X(40) VALUE ".
03 FILLER PIC X(40) VALUE
" 02 SOURCE-FACSIMILE-TABLE RE".
03 FILLER PIC X(40) VALUE
"DEFINES ".
03 FILLER PIC X(40) VALUE
" SOURCE-FACSIMILE-DATA".
03 FILLER PIC X(40) VALUE
". ".
03 FILLER PIC X(40) VALUE
" 03 SOURCE-FACSIMILE OCCU".
03 FILLER PIC X(40) VALUE
"RS 68. ".
03 FILLER PIC X(40) VALUE
" 04 SOURCE-FACSIMILE-".
03 FILLER PIC X(40) VALUE
"ONE PIC X(40). ".
03 FILLER PIC X(40) VALUE
" 04 SOURCE-FACSIMILE-".
03 FILLER PIC X(40) VALUE
"TWO PIC X(40). ".
03 FILLER PIC X(40) VALUE
" 01 FILLER-IMAGE. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" 02 FILLER ".
03 FILLER PIC X(40) VALUE
" PIC X(15) VALUE SPACES. ".
03 FILLER PIC X(40) VALUE
" 02 FILLER ".
03 FILLER PIC X(40) VALUE
" PIC X VALUE QUOTE. ".
03 FILLER PIC X(40) VALUE
" 02 FILLER-DATA ".
03 FILLER PIC X(40) VALUE
" PIC X(40). ".
03 FILLER PIC X(40) VALUE
" 02 FILLER ".
03 FILLER PIC X(40) VALUE
" PIC X VALUE QUOTE. ".
03 FILLER PIC X(40) VALUE
" 02 FILLER ".
03 FILLER PIC X(40) VALUE
" PIC X VALUE FULL-STOP. ".
03 FILLER PIC X(40) VALUE
" 02 FILLER ".
03 FILLER PIC X(40) VALUE
" PIC X(22) VALUE SPACES. ".
03 FILLER PIC X(40) VALUE
" PROCEDURE DIVISION. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" MAIN-LINE SECTION. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" ML-1. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" OPEN OUTPUT OUTPUT-FILE. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" MOVE 1 TO SUB-X. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" ML-2. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" MOVE SOURCE-FACSIMILE (SUB-X)".
03 FILLER PIC X(40) VALUE
" TO OUTPUT-RECORD. ".
03 FILLER PIC X(40) VALUE
" WRITE OUTPUT-RECORD. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" IF SUB-X < 19 ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" ADD 1 TO SUB-X ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" GO TO ML-2. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" MOVE 1 TO SUB-X. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" ML-3. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" MOVE SOURCE-FACSIMILE (20) TO".
03 FILLER PIC X(40) VALUE
" OUTPUT-RECORD. ".
03 FILLER PIC X(40) VALUE
" WRITE OUTPUT-RECORD. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" MOVE SOURCE-FACSIMILE-ONE (SU".
03 FILLER PIC X(40) VALUE
"B-X) TO FILLER-DATA. ".
03 FILLER PIC X(40) VALUE
" MOVE FILLER-IMAGE TO OUTPUT-R".
03 FILLER PIC X(40) VALUE
"ECORD. ".
03 FILLER PIC X(40) VALUE
" WRITE OUTPUT-RECORD. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" MOVE SOURCE-FACSIMILE (20) TO".
03 FILLER PIC X(40) VALUE
" OUTPUT-RECORD. ".
03 FILLER PIC X(40) VALUE
" WRITE OUTPUT-RECORD. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" MOVE SOURCE-FACSIMILE-TWO (SU".
03 FILLER PIC X(40) VALUE
"B-X) TO FILLER-DATA. ".
03 FILLER PIC X(40) VALUE
" MOVE FILLER-IMAGE TO OUTPUT-R".
03 FILLER PIC X(40) VALUE
"ECORD. ".
03 FILLER PIC X(40) VALUE
" WRITE OUTPUT-RECORD. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" IF SUB-X < 68 ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" ADD 1 TO SUB-X ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" GO TO ML-3. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" MOVE 21 TO SUB-X. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" ML-4. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" MOVE SOURCE-FACSIMILE (SUB-X)".
03 FILLER PIC X(40) VALUE
" TO OUTPUT-RECORD. ".
03 FILLER PIC X(40) VALUE
" WRITE OUTPUT-RECORD. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" IF SUB-X < 68 ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" ADD 1 TO SUB-X ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" GO TO ML-4. ".
03 FILLER PIC X(40) VALUE
" ".
03 FILLER PIC X(40) VALUE
" ML-99. ".
03 FILLER PIC X(40) VALUE
" ".
lang Ada>with Ada.Text_IO;procedure Self is Q:Character:='"';A:String:="with Ada.Text_IO;procedure Self is Q:Character:=' 03 FILLER PIC X(40) VALUE
"
CLOSE OUTPUT-FILE. ".
03 FILLER PIC X(40) VALUE
"
".
03 FILLER PIC X(40) VALUE
"
STOP RUN. ".
03 FILLER PIC X(40) VALUE
"
".
02 SOURCE-FACSIMILE-TABLE REDEFINES
SOURCE-FACSIMILE-DATA.
03 SOURCE-FACSIMILE OCCURS 68.
04 SOURCE-FACSIMILE-ONE PIC X(40).
04 SOURCE-FACSIMILE-TWO PIC X(40).
01 FILLER-IMAGE.
02 FILLER PIC X(15) VALUE SPACES.
02 FILLER PIC X VALUE QUOTE.
02 FILLER-DATA PIC X(40).
02 FILLER PIC X VALUE QUOTE.
02 FILLER PIC X VALUE FULL-STOP.
02 FILLER PIC X(22) VALUE SPACES.
PROCEDURE DIVISION.
MAIN-LINE SECTION.
ML-1.
OPEN OUTPUT OUTPUT-FILE.
MOVE 1 TO SUB-X.
ML-2.
MOVE SOURCE-FACSIMILE (SUB-X) TO OUTPUT-RECORD.
WRITE OUTPUT-RECORD.
IF SUB-X < 19
ADD 1 TO SUB-X
GO TO ML-2.
MOVE 1 TO SUB-X.
ML-3.
MOVE SOURCE-FACSIMILE (20) TO OUTPUT-RECORD.
WRITE OUTPUT-RECORD.
MOVE SOURCE-FACSIMILE-ONE (SUB-X) TO FILLER-DATA.
MOVE FILLER-IMAGE TO OUTPUT-RECORD.
WRITE OUTPUT-RECORD.
MOVE SOURCE-FACSIMILE (20) TO OUTPUT-RECORD.
WRITE OUTPUT-RECORD.
MOVE SOURCE-FACSIMILE-TWO (SUB-X) TO FILLER-DATA.
MOVE FILLER-IMAGE TO OUTPUT-RECORD.
WRITE OUTPUT-RECORD.
IF SUB-X < 68
ADD 1 TO SUB-X
GO TO ML-3.
MOVE 21 TO SUB-X.
ML-4.
MOVE SOURCE-FACSIMILE (SUB-X) TO OUTPUT-RECORD.
WRITE OUTPUT-RECORD.
IF SUB-X < 68
ADD 1 TO SUB-X
GO TO ML-4.
ML-99.
CLOSE OUTPUT-FILE.
STOP RUN.
       ID DIVISION.
PROGRAM-ID. QUINE.
DATA DIVISION.
WORKING-STORAGE SECTION.
1 X PIC S9(4) COMP.
1 A. 2 B.
3 PIC X(40) VALUE " ID DIVISION. ".
3 PIC X(40) VALUE " ".
3 PIC X(40) VALUE " PROGRAM-ID. QUINE. ".
3 PIC X(40) VALUE " ".
3 PIC X(40) VALUE " DATA DIVISION. ".
3 PIC X(40) VALUE " ".
3 PIC X(40) VALUE " WORKING-STORAGE SECTION. ".
3 PIC X(40) VALUE " ".
3 PIC X(40) VALUE " 1 X PIC S9(4) COMP. ".
3 PIC X(40) VALUE " ".
3 PIC X(40) VALUE " 1 A. 2 B. ".
3 PIC X(40) VALUE " ".
3 PIC X(40) VALUE " 2 T REDEFINES B. 3 TE OCCURS 16. ".
3 PIC X(40) VALUE "4 T1 PIC X(40). 4 T2 PIC X(40). ".
3 PIC X(40) VALUE " 1 F. 2 PIC X(25) VALUE ".
3 PIC X(40) VALUE "' 3 PIC X(40) VALUE '. ".
3 PIC X(40) VALUE " 2 PIC X VALUE QUOTE. 2 FF PIC X(4".
3 PIC X(40) VALUE "0). 2 PIC X VALUE QUOTE. ".
3 PIC X(40) VALUE " 2 PIC X VALUE '.'. ".
3 PIC X(40) VALUE " ".
3 PIC X(40) VALUE " PROCEDURE DIVISION. ".
3 PIC X(40) VALUE " ".
3 PIC X(40) VALUE " PERFORM VARYING X FROM 1 BY 1".
3 PIC X(40) VALUE " UNTIL X > 6 DISPLAY TE (X) ".
3 PIC X(40) VALUE " END-PERFORM PERFORM VARYING X".
3 PIC X(40) VALUE " FROM 1 BY 1 UNTIL X > 16 ".
3 PIC X(40) VALUE " MOVE T1 (X) TO FF DISPLAY F M".
3 PIC X(40) VALUE "OVE T2 (X) TO FF DISPLAY F ".
3 PIC X(40) VALUE " END-PERFORM PERFORM VARYING X".
3 PIC X(40) VALUE " FROM 7 BY 1 UNTIL X > 16 ".
3 PIC X(40) VALUE " DISPLAY TE (X) END-PERFORM ST".
3 PIC X(40) VALUE "OP RUN. ".
2 T REDEFINES B. 3 TE OCCURS 16. 4 T1 PIC X(40). 4 T2 PIC X(40).
1 F. 2 PIC X(25) VALUE ' 3 PIC X(40) VALUE '.
2 PIC X VALUE QUOTE. 2 FF PIC X(40). 2 PIC X VALUE QUOTE.
2 PIC X VALUE '.'.
PROCEDURE DIVISION.
PERFORM VARYING X FROM 1 BY 1 UNTIL X > 6 DISPLAY TE (X)
END-PERFORM PERFORM VARYING X FROM 1 BY 1 UNTIL X > 16
MOVE T1 (X) TO FF DISPLAY F MOVE T2 (X) TO FF DISPLAY F
END-PERFORM PERFORM VARYING X FROM 7 BY 1 UNTIL X > 16
DISPLAY TE (X) END-PERFORM STOP RUN.

An even smaller one can be found of the site of Tom Dawes-Gamble

[edit] CoffeeScript

s="s=#&# ;alert s.replace(/&/,s).replace /#(?=[^&;'(]|';;$)/g, '#';;" ;alert s.replace(/&/,s).replace /#(?=[^&;'(]|';;$)/g, '"';;

[edit] 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. Note that Common Lisp by default does not distinguish cases.

((lambda (s) (print (list s (list 'quote s))))
'(lambda (s) (print (list s (list 'quote s)))))

This one does the same thing using quasiquote (template) syntax; in some implementations it may not print nicely (but will still work):

((lambda (s) (print `(,s ',s))) '(lambda (s) (print `(,s ',s))))

This program's source contains an explicit reference to itself, which it prints in a manner preserving that reference:

#1=(write '#1# :circle t)

or another version (the former version cause looping in SBCL 1.0.56):

#1=(progn (setq *print-circle* t) (write '#1#))

This is an example using format and explicit referencing:

(format t #1='"(format t #1='~s #1#)" #1#)

An example using REPL variables:

(write -)

[edit] D

This Quine outputs its own source both during compiling and running.

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);
 

NB: last line should be CRLF to match pragma's newline output behaviour.

[edit] Dao

Dao's BNF-like meta-programming macro supports quoting expressions as strings, which allow writing a quine as the following:

syntax{Q $EXP}as{io.writef('syntax{Q $EXP}as{%s}Q %s',\'$EXP\',\'$EXP\')}Q io.writef('syntax{Q $EXP}as{%s}Q %s',\'$EXP\',\'$EXP\')

[edit] dc

[91PP93P[dx]P]dx

[edit] Déjà Vu

"!print !. dup"
!print !. dup

[edit] E

" =~ x; println(E.toQuote(x),x)" =~ x; println(E.toQuote(x),x)

[edit] Elixir

a = <<"a = ~p~n:io.fwrite(a,[a])~n">>
:io.fwrite(a,[a])

[edit] Erlang

 
-module(quine).
-export([do/0]).
 
do() -> Txt=txt(), io:format("~s~ntxt() ->~n~w.~n",[Txt,Txt]), halt().
txt() ->
[45,109,111,100,117,108,101,40,113,117,105,110,101,41,46,10,45,101,120,112,111,114,116,40,91,100,111,47,48,93,41,46,10,10,100,111,40,41,32,45,62,32,84,120,116,61,116,120,116,40,41,44,32,105,111,58,102,111,114,109,97,116,40,34,126,115,126,110,116,120,116,40,41,32,45,62,126,110,126,119,46,126,110,34,44,91,84,120,116,44,84,120,116,93,41,44,32,104,97,108,116,40,41,46].
 
 

[edit] Euphoria

Translation of: C
constant p="constant p=%s%s%s printf(1,p,{34,p,34})" printf(1,p,{34,p,34})

[edit] F#

Using .NET string formatting

let s = "let s = {0}{1}{0} in System.Console.WriteLine(s, char 34, s);;" in System.Console.WriteLine(s, char 34, s);;

Using Printf library

(fun s c -> printf s c s.Value c) "(fun s c -> printf s c s.Value c) %c%s%c <| char 34;;" <| char 34;;

[edit] Factor

With printf:

"%s [ 34 1string dup surround ] keep printf" [ 34 1string dup surround ] keep printf

With prettyprinter:

"[ pprint ] [ write ] bi"[ pprint ] [ write ] bi

[edit] Fish

All the zeros and +'s on the first line are just for aesthetic purposes. Only two zeros are needed, although the v at the end must line up.

 00000000000000000000++++++++++++++++++ v
2[$:{:@]$g:0=?v >o:4a*=?!v~1+:3=?;0ao>
>~" "^ >1+ ^

[edit] Forth

A large number of quine methods are listed here, the simplest of which is:

SOURCE TYPE

[edit] Fortran

character*46::s='("character*46::s=",3a,";print s,39,s,39;end")';print s,39,s,39;end
Output:
character*46::s='("character*46::s=",3a,";print s,39,s,39;end")';print s,39,s,39;end

[edit] Nostalgia note

I remember when this challenge came up, way back in 1966 --- FORTRAN was the game in town, and there existed a feature (well, really, a bug) that allowed an IBM FORTRAN program under IBM's OS/PCP/MFT/MVT [no HASP] to REWIND the default input stream (which were punched cards, and REWIND of course, was only intended for reel-to-reel tapes), which essentially then allowed the program to read it's own source, and then it was a simple matter to PRINT it.

The current CONTROL DATA FORTRAN had a feature that allowed the FORTRAN programmer to WRITE and then re-read I/O (the feature could've been called the REREAD statement, the WRITE may have been to device 0). If one didn't WRITE, just REREAD, the file stream then pointed to the source just read, thus allowing access to the FORTRAN program's source.

This challenge was extended to other languages, the concept was to print the actual source of the program, not use a recursive (or some derivative) method. There were some very clever (and obtuse and/or obscure) methods presented. A lot of operating systems, being in their infancy, had loopholes that allowed programmers to access files in their own job stream.

Another challenge at that time was to write a multi-language program (with NO changes) that would compile (or assemble) in various languages (without errors, of course) and produce the identical output. There were some very creative uses of "comments". --- Gerard Schildberger.

[edit] Frink

This is not a particularly clever nor concise quine, but it is indeed a quine.

d="633d636861725b33345d3b653d643b7072696e745b22643d2463246424635c6e222b28653d7e25732f285b612d7a302d395d7b327d292f636861725b7061727365496e745b24312c31365d5d2f6567295d"
c=char[34];e=d;print["d=$c$d$c\n"+(e=~%s/([a-z0-9]{2})/char[parseInt[$1,16]]/eg)]

A more concise quine is:

1

[edit] Gema

*=$1@quote{$1}\}\n@abort;@{\*\=\$1\@quote\{\$1\}\\\}\\n\@abort\;\@\{}

[edit] Go

package main
 
import "fmt"
 
func main() {
a := "package main\n\nimport \"fmt\"\n\nfunc main() {\n\ta := %q\n\tfmt.Printf(a, a)\n}\n"
fmt.Printf(a, a)
}

[edit] Groovy

There are several ways to do this. Here are five:

s="s=%s;printf s,s.inspect()";printf s,s.inspect()
evaluate s='char q=39;print"evaluate s=$q$s$q"'
s="s=%c%s%c;printf s,34,s,34";printf s,34,s,34
s='s=%c%s%1$c;printf s,39,s';printf s,39,s
printf _='printf _=%c%s%1$c,39,_',39,_

Also Groovy has a trivial solution of an empty (0 length) file even though that isn't an allowable solution here.

[edit] GW-BASIC

10 LIST

[edit] 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.

let q s = putStrLn (s ++ show s) in q "let q s = putStrLn (s ++ show s) in q "

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.)

(\s -> putStrLn (s ++ show s)) "(\\s -> putStrLn (s ++ show s)) "
(putStrLn . \s -> s ++ show s) "(putStrLn . \\s -> s ++ show s) "

and s can be replaced by ap, which when applied to functions has the effect of the S combinator:

import Control.Monad.Reader
(putStrLn . ap (++) show) "(putStrLn . ap (++) show) "

Since Haskell is a purely functional language, it is better at evaluating to things than printing them out. The following expression evaluates to a string of itself:

ap(++)show"ap(++)show"

[edit] HQ9+

Any program with a single “Q” is a quine. The simplest possible such program is just this:

Q

[edit] HTML + CSS

Works with: Opera version 10.0
Works with: Firefox version 3.5

This solution uses CSS to print out the source itself, e.g. the "direct accessing" method. Doesn't work in Internet Explorer; try it in one of Opera, Firefox, Safari, Chromium etc.

<!DOCTYPE html>
<html>
<head>
<title>HTML/CSS Quine</title>
<style type="text/css">
* { font: 10pt monospace; }
 
head, style { display: block; }
style { white-space: pre; }
 
style:before {
content:
"\3C""!DOCTYPE html\3E"
"\A\3Chtml\3E\A"
"\3Chead\3E\A"
"\9\3Ctitle\3E""HTML/CSS Quine""\3C/title\3E\A"
"\9\3Cstyle type=\22text/css\22\3E";
}
style:after {
content:
"\3C/style\3E\A"
"\3C/head\3E\A"
"\3C""body\3E\3C/body\3E\A"
"\3C/html\3E";
}
</style>
</head>
<body></body>
</html>

[edit] Icon and Unicon

procedure main();x:="write(\"procedure main();x:=\",image(x));write(x);end"
write("procedure main();x:=",image(x));write(x);end

[edit] Io

thisMessage print

[edit] Inform 7

R is a room. To quit: (- quit; -). When play begins: say entry 1 in Q; say Q in brace notation; quit. Q is a list of text variable. Q is {"R is a room. To quit: (- quit; -). When play begins: say entry 1 in Q; say Q in brace notation; quit. Q is a list of text variable. Q is "}

[edit] J

Technically, the empty program in J is a quine, as it has an empty result. For example:

 
 

Also, many many numbers in J are quines. For example (result not shown, here, for clarity):

0 

Note: this implementation assumes that J is being used interactively. If J is being used in a command line script, having the script read and output itself would be a better approach. And it's not clear whether quines are a relevant concept in a none textual context (such as a windowing environment).

And other solutions are also possible.

[edit] Java

Copied from The Quine Page

Author: Bertram Felgenhauer

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));}}
Works with: Java version 1.5+
class S{public static void main(String[]a){String p="class S{public static void main(String[]a){String p=%c%s%1$c;System.out.printf(p,34,p);}}";System.out.printf(p,34,p);}}

[edit] JavaScript

Works with: SpiderMonkey
1.7.0
(function(){print("("+arguments.callee.toString().replace(/\s/g,'')+")()");})()

[edit] Using eval

Works with: SpiderMonkey
1.7.0

This version doesn't use arguments.callee.toString() to return the string representation of itself. Instead, it relies on eval().

var code='var q=String.fromCharCode(39);print("var code="+q+code+q+";eval(code)")';eval(code)

[edit] Replacing String

(function(){str=["(function(){str=[F].join(String.fromCharCode(34));str=str.replace(/F/,String.fromCharCode(34)+str+String.fromCharCode(34));console.log(str)})()"].join(String.fromCharCode(34));str=str.replace(/F/,String.fromCharCode(34)+str+String.fromCharCode(34));console.log(str)})()

[edit] Joy

"dup put putchars 10 putch." dup put putchars 10 putch.

[edit] Julia

 
x="println(\"x=\$(repr(x))\\n\$x\")"
println("x=$(repr(x))\n$x")
 

In Julia, $x in a string literal interpolates the value of the variable into the string. $(expression) evaluates the expression and interpolates the result into the string. Normally, the string value "hi\tworld" would be inserted without quotation marks and with a literal tab. The repr function returns a string value that contains quotation marks and in which the literal tab is replaced by the characters \t. When the result of the repr function is interpolated, the result is what you would type into your code to create that string literal.

[edit] Lasso

In template mode, any text that doesn't include Lasso tags is a trivial quine, because it is passed through unmodified by the interpreter. But here is a more traditional quine:

var(a=(:10,39,118,97,114,40,97,61,40,58,39,10,36,97,45,62,106,111,105,110,40,39,44,39,41,10,39,41,41,39,10,118,97,114,40,98,61,98,121,116,101,115,41,10,36,97,45,62,102,111,114,101,97,99,104,32,61,62,32,123,32,36,98,45,62,105,109,112,111,114,116,56,98,105,116,115,40,35,49,41,32,125,10,36,98,45,62,97,115,83,116,114,105,110,103))
'var(a=(:'
$a->join(',')
'))'
var(b=bytes)
$a->foreach => { $b->import8bits(#1) }
$b->asString

[edit] Liberty BASIC

s$ = "s$ = : Print Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 5)" : Print Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 5)

[edit] Lisp

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

((lambda (x) (list x (list 'quote x)))
'(lambda (x) (list x (list 'quote x))))

[edit] Lua

s=[[io.write('s=[','[',s,']','];',s)]];io.write('s=[','[',s,']','];',s)

[edit] M4

define(`quine',``$1(`$1')'')
quine(`define(`quine',``$1(`$1')'')
quine')

[edit] Mathematica

a="Print[\"a=\",InputForm[a],\";\",a]";Print["a=",InputForm[a],";",a]

or

(#1[#0[#1]] &)[Defer]

or

ToString[#0][] & []

or

Unevaluated[1989^1989]

or

x
 :)

[edit] MATLAB / Octave

The example works for functions and scripts stored as m-files. It does not work for functions defined only in the workspace.

  function quine()
fid = fopen([mfilename,'.m']);
while ~feof(fid)
printf('%s\n',fgetl(fid));
end;
fclose(fid);
end;

or

  function quine()
type(mfilename);
end;

Without accessing the file:

function quine; y = 'function quine; y = %c%s%c; fprintf(1, y, 39, y, 39)\n'; fprintf(1, y, 39, y, 39)

[edit] Maxima

/* Using ?format from the unerlying Lisp system */
 
lambda([],block([q:ascii(34),s:"lambda([],block([q:ascii(34),s:~A~A~A],print(?format(false,s,q,s,q))))()$"],print(?format(false,s,q,s,q))))()$

[edit] MUMPS

QUINE
NEW I,L SET I=0
FOR SET I=I+1,L=$TEXT(+I) Q:L="" WRITE $TEXT(+I),!
KILL I,L
QUIT
 
SMALL
S %=0 F W $T(+$I(%)),! Q:$T(+%)=""

Both of the routines will work, but the second has the minor advantage of only using one variable instead of two.

[edit] NASM

Compiles to the source code when -f raw

%define a "%define "
%define b "db "
%define c "%deftok "
%define d "a, 97, 32, 34, a, 34, 10, a, 98, 32, 34, b, 34, 10, a, 99, 32, 34, c, 34, 10, a, 100, 32, 34, d, 34, 10, c, 101, 32, 100, 10, b, 101, 10"
%deftok e d
db e

[edit] NetRexx

/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
Q = "'"
S = "\\"
N = "\n"
A = "&"
code = [ -
'/* NetRexx */', -
'options replace format comments java crossref savelog symbols nobinary', -
'', -
'Q = "&QS"', -
'S = "&ESC"', -
'N = "&NL"', -
'A = "&AMP"', -
'code = [ -', -
'&REP', -
' ]', -
'', -
'pgm = ""', -
'txt = ""', -
'loop t_ = 0 for code.length', -
' txt = txt || " " || Q || code[t_] || Q || ", -" || N', -
' end t_', -
'txt = txt.strip("T", N)', -
'txt = txt.delstr(txt.lastpos(","), 1)', -
'', -
'K = ""', -
'K[0] = 5', -
'K[1] = A"NL"', -
'K[2] = A"AMP"', -
'K[3] = A"ESC"', -
'K[4] = A"QS"', -
'K[5] = A"REP"', -
'loop c_ = 0 for code.length', -
' loop v_ = 1 to K[0]', -
' T = K[v_]', -
' if code[c_].pos(T) <> 0 then do', -
' parse code[c_] pre(T)post', -
' select case T', -
' when K[1] then do', -
' code[c_] = pre || S || "n" || post', -
' end', -
' when K[2] then do', -
' code[c_] = pre || A || post', -
' end', -
' when K[3] then do', -
' code[c_] = pre || S || S || post', -
' end', -
' when K[4] then do', -
' code[c_] = pre || Q || post', -
' end', -
' when K[5] then do', -
' code[c_] = txt', -
' end', -
' otherwise nop', -
' end', -
' end', -
' end v_', -
' pgm = pgm || code[c_].strip("T") || N', -
' end c_', -
'pgm = pgm.strip("T", N) || N', -
'say pgm', -
'', -
'return', -
'' -
]
 
pgm = ""
txt = ""
loop t_ = 0 for code.length
txt = txt || " " || Q || code[t_] || Q || ", -" || N
end t_
txt = txt.strip("T", N)
txt = txt.delstr(txt.lastpos(","), 1)
 
K = ""
K[0] = 5
K[1] = A"NL"
K[2] = A"AMP"
K[3] = A"ESC"
K[4] = A"QS"
K[5] = A"REP"
loop c_ = 0 for code.length
loop v_ = 1 to K[0]
T = K[v_]
if code[c_].pos(T) <> 0 then do
parse code[c_] pre(T)post
select case T
when K[1] then do
code[c_] = pre || S || "n" || post
end
when K[2] then do
code[c_] = pre || A || post
end
when K[3] then do
code[c_] = pre || S || S || post
end
when K[4] then do
code[c_] = pre || Q || post
end
when K[5] then do
code[c_] = txt
end
otherwise nop
end
end
end v_
pgm = pgm || code[c_].strip("T") || N
end c_
pgm = pgm.strip("T", N) || N
say pgm
 
return

[edit] Nimrod

The empty program is a quine in Nimrod:

 

Another quine:

const x = "var x = echo x[0..7],chr(34),x,chr(34),chr(10),x[8 .. -1]"
echo x[0..7],chr(34),x,chr(34),chr(10),x[8 .. -1]

This quine prints its own sourcecode at compiletime as well as at runtime:

const x = "const x = |const y = x[0..9]&34.chr&x&34.chr&10.chr&x[11..100]&10.chr&x[102..115]&10.chr&x[117 .. -1]|static: echo y|echo y"
const y = x[0..9]&34.chr&x&34.chr&10.chr&x[11..100]&10.chr&x[102..115]&10.chr&x[117 .. -1]
static: echo y
echo y

Compile with: nimrod --verbosity:0 c quine

[edit] OCaml

(newline included)

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

Alternative: (newline included)

(fun s -> Printf.printf "%s%S;;\n" s s) "(fun s -> Printf.printf \"%s%S;;\\n\" s s) ";;

[edit] ooRexx

The samples shown at REXX are valid ooRexx programs.

[edit] OxygenBasic

 
'RUNTIME COMPILING
 
source="print source"
 
a=compile source : call a : freememory a
 

[edit] Oz

A one-liner that uses the ASCII code for " to avoid "quoted quotes". We put the value assignment to the end by using multithreading and implicit synchronization on the dataflow variable I.

declare I in thread {System.showInfo I#[34]#I#[34]} end I ="declare I in thread {System.showInfo I#[34]#I#[34]} end I ="

[edit] Pascal

A modification of one Pascal example (Author: Oliver Heen) from http://www.nyx.net/~gthompso/self_pasc.txt. This example includes newline at the end.

const s=';begin writeln(#99#111#110#115#116#32#115#61#39,s,#39,s)end.';begin writeln(#99#111#110#115#116#32#115#61#39,s,#39,s)end.

[edit] Perl

This relatively simple Perl example imitates the C example.

$s = q($s = q(%s); printf($s, $s);
); printf($s, $s);
 

Note the terminating newline.

[edit] Self-reading (some consider cheating)

Accessing source code via DATA filehandle:
seek(DATA, 0, 0);
print <DATA>
__DATA__

even simpler:

open ME, $0 and print <ME>;
open 0; print <0>;

[edit] Quine Generator

Perhaps the simplest quine in Perl 5 is:

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

By carefully examining the code, you will find that you can insert any valid perl sentences before and after the print statement in q{}. It is just a few lines of codes away before you come up with a quine generator that turns a given perl script into a quine. Note this quine generator itself is a quine.

cf. http://blog.livedoor.jp/dankogai/archives/51519405.html


{local$_=q{
{
package Quine;
use strict;
use warnings;
our $VERSION = sprintf "%d.%02d", q$Revision: 0.2 $ =~ /(\d+)/g;
my $head = '{local$_=q' . "\x7B\n";
my $tail = 'print"{local\$_=q{$_};eval}\n"' . "\x7D;eval}\n";
 
sub new {
my $class = shift;
my $quine = $head . shift;
my $ret = shift || 1;
my $ln = ( $quine =~ tr/\n/\n/ );
$ln++;
$quine .= "return $ret if caller(1)or(caller)[2]!=$ln;$tail";
bless \$quine, $class;
}
 
sub from_file {
my ( $class, $fn, $ret ) = @_;
local $/;
open my $fh, '<', $fn or die "$fn : $!";
my $src = <$fh>;
close $fh;
$class->new( $src, $ret );
}
 
sub quine { ${ $_[0] } }
 
=head1 NAME
 
Quine - turn your perl modules/apps into a true quine!
 
=head1 VERSION
 
$Id: Quine.pm,v 0.2 2010/09/15 20:23:53 dankogai Exp dankogai $
 
=head1 SYNOPSIS
 
use Quine;
print Quine->from_file("woot.pl")->quine;
print Quine->from_file("moot.psgi", '$app')->quine;
 
=cut

}
return 1 if caller(1);print"{local\$_=q{$_};eval}\n"};eval}

[edit] Perl 6

Translation of: Haskell
Works with: Rakudo version #32 "Pisa"
my &f = {say $^s, $^s.perl;}; f "my \&f = \{say \$^s, \$^s.perl;}; f "
 

Note the terminating newline.


Works with: Rakudo version 2014.04

A more compact, but still purely functional, approach:

{.fmt($_).say}(<{.fmt($_).say}(<%s>)>)
 

Note again the terminating newline.

[edit] PHP

Translation of: C
<?php $p = '<?php $p = %c%s%c; printf($p,39,$p,39); ?>
'
; printf($p,39,$p,39); ?>

Note the terminating newline.

Technically, anything outside of <?php , <script language="php">, <? (deprecated) or <% (deprecated) tags is automatically echoed by PHP allowing for easier inclusion of HTML in PHP documents. So the following is a quine:

Rosetta code :).

[edit] PicoLisp

[edit] Using 'quote'

Note that 'quote' in PicoLisp corresponds to 'lambda' in other Lisps

('((X) (list (lit X) (lit X))) '((X) (list (lit X) (lit X))))
Output:
-> ('((X) (list (lit X) (lit X))) '((X) (list (lit X) (lit X))))

[edit] Using 'let'

(let X '(list 'let 'X (lit X) X) (list 'let 'X (lit X) X))
Output:
-> (let X '(list 'let 'X (lit X) X) (list 'let 'X (lit X) X))

[edit] PlainTeX

[edit] Output to terminal

This assumes the filename of the source file to be ‘q.tex’, and the banner from vanilla Knuth’s TeX:

This is TeX, Version 3.1415926 (no format preloaded)
(q.tex \output {\message {\output \the \output \end }\batchmode }\end

[edit] Output to dvi

    \let~\expandafter\def\0{~\ttraggedright~\let~\s~\string~\def~~~{~\s~~~\s~}~\output~
~{~}~\s~\let~~~\expandafter~\s~\def~\s~\0~\s~{~\0~\s~}~\s~\0~\end}\0

[edit] PL/I

The following code, containing 709 significant bytes, compiles completely clean using the old MVS PL/I V2.3.0 Compiler, using the default 2,72,1 margins:

 s:proc options(main)reorder;dcl sysprint file,m(7)init(
' s:proc options(main)reorder\dcl sysprint file,m(7)init(',
' *)char(99),i,j,(translate,substr)builtin,c char\i=1\j=n',
' \do i=1 to 6\put skip list('' '''''')\do j=2 to 56\c=substr',
' (m(i),j)\put edit(c)(a)\n:proc\put list(translate(m(i),',
' ''5e''x,''e0''x))\end n\if c='''''''' then put edit(c)(a)\end\ ',
' put edit('''''','')(a(50))\end\do i=2 to 6\j=n\end\end s\ ',
*)char(99),i,j,(translate,substr)builtin,c char;i=1;j=n
 ;do i=1 to 6;put skip list(' ''');do j=2 to 56;c=substr
(m(i),j);put edit(c)(a);n:proc;put list(translate(m(i),
'5e'x,'e0'x));end n;if c='''' then put edit(c)(a);end;
put edit(''',')(a(50));end;do i=2 to 6;j=n;end;end s;

An even smaller version (believed to be the smallest possible PL/I Quine), containing 326 significant bytes, shows the unique capabilities of the same old V2.3.0 compiler in being able to generate correct code, ovecoming 2 pre-processor errors, 8 severe errors, 10 errors, 6 warnings and 2 informational messages. It requires the following non-default compile options, 'M,MAR(1,90),C'.

%dcl z%z='put edit';proc options(main;q=''''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',';dcl(c,q)char,m(2)char(99)init(
'%dcl z%z=''put edit'';proc options(main;q=''''''''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'','';dcl(c,q)char,m(2)char(99)init(',

The equivalent version that compiles with the newer z/OS Enterprise PL/I compilers, coming in at 434 significant bytes and requiring the following two compiler options, 'm,margins(1,80,0)', is:

%dcl z;%z="put edit";w:proc options(main);q="'";put list(m)do i=1,2,3;z
(q)(a)skip;do j=1to 71;c=substr(m(i),j)if c=q then z(c)(a)z(c)(a)end;if
i<3then z(q,",")(a)else z(q,";")(a)end;dcl(c,q)char,m(3)char(99)init(
'%dcl z;%z="put edit";w:proc options(main);q="''";put list(m)do i=1,2,3;z',
'(q)(a)skip;do j=1to 71;c=substr(m(i),j)if c=q then z(c)(a)z(c)(a)end;if',
'i<3then z(q,",")(a)else z(q,";")(a)end;dcl(c,q)char,m(3)char(99)init( ';

[edit] PowerBASIC

This is technically based on the BASIC code above, but is in fact a complete rewrite.

FUNCTION PBMAIN () AS LONG
REDIM s(1 TO DATACOUNT) AS STRING
o$ = READ$(1)
d$ = READ$(2)
FOR n& = 1 TO DATACOUNT
s(n&) = READ$(n&)
NEXT
OPEN o$ FOR OUTPUT AS 1
FOR n& = 3 TO DATACOUNT - 1
PRINT #1, s(n&)
NEXT
PRINT #1,
FOR n& = 1 TO DATACOUNT
PRINT #1, d$ & $DQ & s(n&) & $DQ
NEXT
PRINT #1, s(DATACOUNT)
CLOSE
 
DATA "output.src"
DATA " DATA "
DATA "FUNCTION PBMAIN () AS LONG"
DATA " REDIM s(1 TO DATACOUNT) AS STRING"
DATA " o$ = READ$(1)"
DATA " d$ = READ$(2)"
DATA " FOR n& = 1 TO DATACOUNT"
DATA " s(n&) = READ$(n&)"
DATA " NEXT"
DATA " OPEN o$ FOR OUTPUT AS 1"
DATA " FOR n& = 3 TO DATACOUNT - 1"
DATA " PRINT #1, s(n&)"
DATA " NEXT"
DATA " PRINT #1,"
DATA " FOR n& = 1 TO DATACOUNT"
DATA " PRINT #1, d$ & $DQ & s(n&) & $DQ"
DATA " NEXT"
DATA " PRINT #1, s(DATACOUNT)"
DATA " CLOSE"
DATA "END FUNCTION"
END FUNCTION

[edit] PowerShell

$d='$d={0}{1}{0}{2}Write-Host -NoNewLine ($d -f [char]39,$d,"`r`n")'
Write-Host -NoNewLine ($d -f [char]39,$d,"`r`n")

Note that neither the code nor its output include a new line at the end. This can be changed by removing the -NoNewLine parameter and appending a new line to the end of the file. However, Windows generally does not have the convention of a line terminator but rather a line separator, thus the usefulness of having a new line at the end of a file can be debated here.

[edit] Prolog

quine :- 
listing(quine).

[edit] PureBasic

s$="s$= : Debug Mid(s$,1,3)+Chr(34)+s$+Chr(34)+Mid(s$,4,100)" : Debug Mid(s$,1,3)+Chr(34)+s$+Chr(34)+Mid(s$,4,100)

[edit] Python

Works with: Python version 2.x and 3.x

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

x = 'x = %r\nprint(x %% x)'
print(x % x)
Works with: Python version 3.x and 2.6+

With the new str.format:

x = 'x = {!r};print(x.format(x))';print(x.format(x))
Works with: Python version 2.x and 3.x

After creating the file "Quine.py" with the following source, running the program will spit the code back out on a terminal window:

import sys; sys.stdout.write(open(sys.argv[0]).read())

Note: actually an empty file could be treated as python quine too.


Due to Leon Naley (name guessed) from devshed python forum

I think I just thought of the shortest quine for python I think there can ever be! (except a blank program)

make a program with this single line in it

 
print(__file__[:-3])
 

and name the file print(__file__[:-3]).py

and run the file!

bash example command:

$ python print\(__file__\[\:-3\]\).py 
print(__file__[:-3])
 

Python 3, from same thread at same forum, created by wewhgyih, tested by LambertDW. Works on unix and Windows7. On Windows7 I commanded python "print(__file__)" .

 
$ cat print\(__file__\)
print(__file__)
$ python print\(__file__\)
print(__file__)
 

I saw this clever solution somewhere some time ago (dont' remember the source.) Assuming the input does not have to be a correct program...

$ cat reproducing.py 
File "reproducing.py", line 1
File "reproducing.py", line 1
^
IndentationError: unexpected indent
 
$ python reproducing.py
File "reproducing.py", line 1
File "reproducing.py", line 1
^
IndentationError: unexpected indent

[edit] R

Adapted from the C version in this list.

(function(){x<-intToUtf8(34);s<-"(functio = 3 TO DATACOUNT - 1"
DATA " PRINT #1, s(nn(){x<-intToUtf8(34);s<-%s%s%s;cat(sprintf(s,x,s,x))})()";cat(sprintf(s,x,s,x))})()

[edit] Racket

The Scheme functions all work in Racket too, but in addition Racket has the significant advantage of producing much better code...

 
((λ (x) `(,x ',x)) '(λ (x) `(,x ',x)))
 

[edit] REBOL

rebol [] q: [print ["rebol [] q:" mold q "do q"]] do q

[edit] REXX

[edit] version 1

/*REXX program outputs itself.*/ do j=1 for sourceline(); say sourceline(j); end
Output:
/*REXX program outputs itself.*/ do j=1 for sourceline(); say sourceline(j); end

[edit] version 2

/*REXX program outputs its own source including comments and blank lines.*/
do k=1 for sourceline()
say sourceline(k)
end /*k*/
Output:
/*REXX program outputs its own source including comments and blank lines.*/
      do k=1 for sourceline()
      say sourceline(k)
      end   /*k*/

[edit] version 3

A version that doesn't use sourceline() which is kind of a cheat.

Error? The rest of this conversation moved to Talk

/* Rexx */
 
Q = "'"
Queue '/* Rexx */'
Queue ''
Queue 'Q = "$"'
Queue '&QQQ'
Queue ''
Queue 'X = 0'
Queue 'Do while Queued() \= 0'
Queue ' Parse pull code'
Queue ' X = X + 1; codel.0 = X; codel.X = code'
Queue ' End'
Queue ''
Queue 'Do x_ = 1 for codel.0'
Queue ' line = codel.x_'
Queue ' If abbrev(line, "Q = ") then Do'
Queue ' line = translate(line, Q, "$")'
Queue ' End'
Queue ' If line = "&QQQ" then Do'
Queue ' Do y_ = 1 to codel.0'
Queue ' qline = codel.y_'
Queue ' Say "Queue" Q || qline || Q'
Queue ' End y_'
Queue ' End'
Queue ' else Do'
Queue ' Say line'
Queue ' End'
Queue ' End x_'
Queue ''
 
X = 0
Do while Queued() \= 0
Parse pull code
X = X + 1; codel.0 = X; codel.X = code
End
 
Do x_ = 1 for codel.0
line = codel.x_
If abbrev(line, "Q = ") then Do
line = translate(line, Q, "$")
End
If line = "&QQQ" then Do
Do y_ = 1 to codel.0
qline = codel.y_
Say "Queue" Q || qline || Q
End y_
End
else Do
Say line
End
End x_
 

[edit] Ruby

Found online:

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

more readably:

x = "x = %p; puts x %% x"; puts x % x

The %p specifier outputs the result of calling the .inspect method on the argument.

even shorter (by a few characters):

puts <<e*2,'e'
puts <<e*2,'e'
e

perhaps the simplest:

eval s="puts'eval s='+s.inspect"

One (maybe a bit verbose) version, to be appended to the end of any file. This doesn't work in IRB, because it isn't a file.

 
f = File.open __FILE__
f.each_line do |line|
puts line
f.close
 

[edit] Rust

Using the method on Wikipedia (0.9-pre-compatible):

 
fn main()
{
let q = 34u8;
let p = 44u8;
let l = [
"fn main()",
"{",
" let q = 34u8;",
" let p = 44u8;",
" let l = [",
" ",
" ];",
" let mut i = 0;",
" while i < 5",
" {",
" println(l[i]);",
" i+=1;",
" }",
" i = 0;",
" while i < l.len()",
" {",
" print(l[5]);",
" print((q as char).to_str());",
" print(l[i]);",
" print((q as char).to_str());",
" println((p as char).to_str());",
" i+=1;",
" }",
" i = 6;",
" while i < l.len()",
" {",
" println(l[i]);",
" i+=1;",
" }",
"}",
];
let mut i = 0;
while i < 5
{
println(l[i]);
i+=1;
}
i = 0;
while i < l.len()
{
print(l[5]);
print((q as char).to_str());
print(l[i]);
print((q as char).to_str());
println((p as char).to_str());
i+=1;
}
i = 6;
while i < l.len()
{
println(l[i]);
i+=1;
}
}
 

A shorter quine (works with Rust master as of 31 May 2014):

 
extern crate debug;
fn main() {
let x = "extern crate debug;\nfn main() {\n let x = ";
let y = "print!(\"{}{:?};\n let y = {:?};\n {}\", x, x, y, y)\n}";
print!("{}{:?};
let y = {:?};
{}", x, x, y, y)
}
 

[edit] Scala

script:

val q = "\"" * 3
val c = """val q = "\"" * 3
val c = %s%s%s
println(c format (q, c, q))
"""
println(c format (q, c, q))

application:

object Quine {
def main(args: Array[String]) {
val q = "\"" * 3
val c = """object Quine {
def main(args: Array[String]) {
val q = "
\"" * 3
val c = %s%s%s
println(c format (q, c, q))
}
}"""
println(c format (q, c, q))
}
}

script, using printf with indexed arguments (proposed here: http://www.codecommit.com/blog/scala/useless-hackery-a-scala-quine):

 
val x="val x=%c%s%1$c;printf(x,34,x)";printf(x,34,x)
 

[edit] Scheme

Translation of: Common Lisp
Works with: Scheme version R5RS
((lambda (s) (display (list s (list (quote quote) s)))) (quote (lambda (s) (display (list s (list (quote quote) s))))))

or more "directly" (and classically)

((lambda (q) (quasiquote ((unquote q) (quote (unquote q))))) (quote (lambda (q) (quasiquote ((unquote q) (quote (unquote q)))))))

which is a long-hand for "cute"

((lambda (q) `(,q ',q)) '(lambda (q) `(,q ',q)))

[edit] 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;

Original source: [1]

[edit] Smalltalk

(newline included)

[:s| Transcript show: s, s printString; cr ] value: '[:s| Transcript show: s, s printString; cr ] value: '
 
Works with: GNU Smalltalk
(newline included)
' print; displayNl' print; displayNl
 

[edit] Standard ML

(newline included)

(fn s => print (s ^ "\"" ^ String.toString s ^ "\";\n")) "(fn s => print (s ^ \"\\\"\" ^ String.toString s ^ \"\\\";\\n\")) ";

(without newline)

(fn y=>(fn x=>(print(x^y^x^y)))) (implode[chr(34)])"(fn y=>(fn x=>(print(x^y^x^y)))) (implode[chr(34)])"

[edit] Swift

(newline included)

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

[edit] 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):

join { {} A B  } any_string
=> any_stringAany_stringB

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

join { {} \{ \} } something
=> something{something}

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

join { {} \{ \} } { join { {} \{ \} } }
=> join { {} \{ \} } { join { {} \{ \} } }

[edit] Turbo Pascal

The following code was tested in Turbo Pascal 5.5 under DOSbox DOS, and using gpc 4.1. It assumes ASCII.

program quine;
 
const
apos: Char = Chr(39);
comma: Char = Chr(44);
lines: Array[1..17] of String[80] = (
'program quine;',
'',
'const',
' apos: Char = Chr(39);',
' comma: Char = Chr(44);',
' lines: Array[1..17] of String[80] = (',
' );',
'',
'var',
' num: Integer;',
'',
'begin',
' for num := 1 to 6 do writeln(lines[num]);',
' for num := 1 to 16 do writeln(apos, lines[num], apos, comma);',
'% writeln(apos, lines[17], apos);',
' for num := 7 to 17 do writeln(lines[num]);',
'end.'
);
 
var
num: Integer;
 
begin
for num := 1 to 6 do writeln(lines[num]);
for num := 1 to 16 do writeln(apos, lines[num], apos, comma);
writeln(apos, lines[17], apos);
for num := 7 to 17 do writeln(lines[num]);
end.

[edit] TXR

A suite for four variations on a theme. The first three use HTML encoding to avoid solving quoting problem. The third stops using &#10; to encode newlines, but instead represents the coded portion of the program as a list of lines rather than a string containing newlines encoded in some other way. The fourth dispenses with the HTML crutch and solves the quoting problem with a filter defined in the program itself.

[edit] "double filtered"

@(deffilter me ("ME" "@(bind me &quot;ME&quot;)&#10;@(output)&#10;@@(deffilter me (&quot;ME&quot; &quot;@{me :filter me}&quot;))&#10;@{me :filter (me :from_html)}&#10;@(end)"))
@(bind me "ME")
@(output)
@@(deffilter me ("ME" "@{me :filter me}"))
@{me :filter (me :from_html)}
@(end)

[edit] "straight up"

@(bind me "@(output)&#10;@@(bind me &quot;@me&quot;)&#10;@{me :filter :from_html}&#10;@(end)")
@(output)
@@(bind me "@me")
@{me :filter :from_html}
@(end)

[edit] "code free"

@(bind me ("@(output)" "@@(bind me (@(rep)&quot;@me&quot; @(last)&quot;@me&quot;@(end)))" "@(repeat)" "@{me :filter :from_html}" "@(end)" "@(end)"))
@(output)
@@(bind me (@(rep)"@me" @(last)"@me"@(end)))
@(repeat)
@{me :filter :from_html}
@(end)
@(end)

[edit] "404"

@(bind me ("@(deffilter q (*'**'*' *'*/*'*') (*'**/*' *'*/*/*') (*'*****' *'***'))" "@(output)" "@@(bind me (@(rep)*'@me*' @(last)*'@me*'@(end)))" "@(repeat)" "@{me :filter q}" "@(end)" "@(end)"))
@(deffilter q ("*'" "\"") ("*/" "\\") ("**" "*"))
@(output)
@@(bind me (@(rep)"@me" @(last)"@me"@(end)))
@(repeat)
@{me :filter q}
@(end)
@(end)

[edit] UNIX Shell

Works with: Bourne Shell

A cheat that reads its own source code, because $0 is the path to the script:

#!/bin/sh
cat < "$0"

A real quine that doesn't cheat:

{
string=`cat`
printf "$string" "$string"
echo
echo END-FORMAT
} <<'END-FORMAT'
{
string=`cat`
printf "$string" "$string"
echo
echo END-FORMAT
} <<'END-FORMAT'
%s
END-FORMAT

[edit] V

First we need a function that can print a list as a library.

[p [put ' 'put] map ' ' puts].

with that, the quine reduces to quine.v:

[dup puts p]
dup puts p

Using it:

$./v quine.v
[dup puts p]
dup puts p

[edit] VHDL

LIBRARY ieee; USE std.TEXTIO.all;                                               
entity quine is end entity quine;
architecture beh of quine is
type str_array is array(1 to 20) of string(1 to 80);
constant src : str_array := (
"LIBRARY ieee; USE std.TEXTIO.all; ",
"entity quine is end entity quine; ",
"architecture beh of quine is ",
" type str_array is array(1 to 20) of string(1 to 80); ",
" constant src : str_array := ( ",
"begin ",
" process variable l : line; begin ",
" for i in 1 to 5 loop write(l, src(i)); writeline(OUTPUT, l); end loop; ",
" for i in 1 to 20 loop ",
" write(l, character'val(32)&character'val(32)); ",
" write(l, character'val(32)&character'val(32)); ",
" write(l, character'val(34)); write(l, src(i)); write(l,character'val(34));",
" if i /= 20 then write(l, character'val(44)); ",
" else write(l, character'val(41)&character'val(59)); end if; ",
" writeline(OUTPUT, l); ",
" end loop; ",
" for i in 6 to 20 loop write(l, src(i)); writeline(OUTPUT, l); end loop; ",
" wait; ",
" end process; ",
"end architecture beh; ");
begin
process variable l : line; begin
for i in 1 to 5 loop write(l, src(i)); writeline(OUTPUT, l); end loop;
for i in 1 to 20 loop
write(l, character'val(32)&character'val(32));
write(l, character'val(32)&character'val(32));
write(l, character'val(34)); write(l, src(i)); write(l,character'val(34));
if i /= 20 then write(l, character'val(44));
else write(l, character'val(41)&character'val(59)); end if;
writeline(OUTPUT, l);
end loop;
for i in 6 to 20 loop write(l, src(i)); writeline(OUTPUT, l); end loop;
wait;
end process;
end architecture beh;

NOTE: ModelSim escapes each line in the console output with "# ".

[edit] zkl

The simplest is the zkl REPL and integers

zkl: 123
123
Translation of: Groovy
s:="s:=%c%s%c;print(s.fmt(34,s,34));";print(s.fmt(34,s,34));
Translation of: ALGOL 68
 a:="a:=;q:=(34).toChar();print(a[0,3]+q+a+q+a[3,*]);";q:=(34).toChar();print(a[0,3]+q+a+q+a[3,*]);
Translation of: C
reg c=0'|"|,s="reg c=0'|%c|,s=%c%s%c;s.fmt(c,c,s,c).print();";s.fmt(c,c,s,c).print();
Translation of: Python

Create a file with:

File(__FILE__).readln().print()

and run it: $ zkl foo.zkl to generate the contents.

We can also write a quine tester since print both sends the results to the output device and returns them:

fcn testQuine(quine){
Compiler.Compiler.compileText(quine).__constructor(); out:=vm.regX;
println("\ndiff>>",quine-out,"<<");
}
testQuine(0'|s:="s:=%c%s%c;print(s.fmt(34,s,34));";print(s.fmt(34,s,34));|);
s:="s:=%c%s%c;print(s.fmt(34,s,34));";print(s.fmt(34,s,34));
diff>><<
Personal tools
Namespaces

Variants
Actions
Community
Explore
Misc
Toolbox