Quine: Difference between revisions
m
→{{header|Binary Lambda Calculus}}
(47 intermediate revisions by 27 users not shown) | |||
Line 44:
=={{header|8080 Assembly}}==
<
lxi b,P
call A
Line 141:
db 00Dh,00Ah,009h,06Ah,06Dh,070h,009h,072h,00Dh,00Ah,043h,03Ah,009h,064h,062h,009h
db 031h,033h,02Ch,031h,030h,02Ch,039h,02Ch,027h,064h,062h,027h,02Ch,039h,02Ch,027h
db 024h,027h,00Dh,00Ah,050h,03Ah,000h</
=={{header|ABAP}}==
I copied one of my examples from http://www.yaabb.de/viewtopic.php?t=44
<
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'.
Line 179:
ENDIF.
I = I + 1.
ENDDO.</
Here is another one, requiring SY-SAPRL >= '620':
<
`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,
Line 187:
`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:
<
PAGE HEADING
LINE-SIZE
Line 221:
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':
<
.DATA QQ(69) OCCURS 0
.DATA Q LIKE QQ WITH HEADER LINE
Line 248:
.ENDLOOP
.WRITE / '.'
.</
=={{header|ACL2}}==
<
(cw quine quine))
(print-quine
"(defun print-quine (quine)
(cw quine quine))
(print-quine ~x0)~%")</
A shorter one:
<
=={{header|Acornsoft Lisp}}==
<syntaxhighlight lang="lisp">((lambda (s) (list s (list (quote quote) s)))
(quote (lambda (s) (list s (list (quote quote) s)))))
</syntaxhighlight>
=={{header|Ada}}==
The program text must be in one line.
<div style="width:100%;overflow:scroll">
<
</div>
=={{header|Aime}}==
<
text s, t;
Line 290 ⟶ 296:
o_etext(cut(s, f - 1, 2));
o_text(cut(s, f + 1, 8888 - f));
o_text(cut(s, f, 8888 - f));</
=={{header|ALGOL 68}}==
The following program assumes that the target machine is ASCII, hence the use of character 34 as a double quote.
<
The following is a shorter and character set independent - hence portable - implementation.
<
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. [http://portal.acm.org/ft_gateway.cfm?id=1061754&type=pdf The original can be found in Algol Bulletin 46 - 2.1 - Page 5].
=={{header|APL}}==
<
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang="applesoft
=={{header|Arturo}}==
<
{{out}}
Line 315 ⟶ 321:
All from http://www.autohotkey.com/forum/viewtopic.php?t=14336:
The "cheating" way:
<
MsgBox % quine</
Another:
<
{
global
Line 349 ⟶ 355:
)
StringSplit q, script, %nl%
D(q0, "q")</
Another:
<div style="width:100%;overflow:scroll">
<
sep := Chr(36)
nl := Chr(13) . Chr(10)
Line 359 ⟶ 365:
StringReplace script, script, %sep%, %nl%, All
StringReplace script, script, #, %quote%%s%%quote%
FileAppend %script%, %A_ScriptDir%\Q.txt</
Another "cheating" method:
<
=={{header|AWK}}==
===version 1===
<
===version 2===
<
=={{header|Babel}}==
Line 373 ⟶ 379:
Demonstrating from the commandline:
<
{ "{ '{ ' << dup [val 0x22 0xffffff00 ] dup <- << << -> << ' ' << << ' }' << } !" { '{ ' << dup [val 0x22 0xffffff00 ] dup <- << << -> << ' ' << << '}' << } ! }%
%
% cat quine.sp
{ "{ '{ ' << dup [val 0x22 0xffffff00 ] dup <- << << -> << ' ' << << ' }' << } !" { '{ ' << dup [val 0x22 0xffffff00 ] dup <- << << -> << ' ' << << '}' << } ! }%
%</
Demonstrating in interactive mode:
<
babel> { "{ '{ ' << dup [val 0x22 0xffffff00 ] dup <- << << -> << ' ' << << ' }' << } !" { '{ ' << dup [val 0x22 0xffffff00 ] dup <- << << -> << ' ' << << '}' << } ! }
babel> eval
{ "{ '{ ' << dup [val 0x22 0xffffff00 ] dup <- << << -> << ' ' << << ' }' << } !" { '{ ' << dup [val 0x22 0xffffff00 ] dup <- << << -> << ' ' << << '
}' << } !}babel>
babel></
=={{header|bash}}==
<
mapfile < $0
printf "%s" "${MAPFILE[@]}"</
<
<
<
{
function __ ()
Line 404 ⟶ 410:
echo "$(declare -f _);_ ${@}"
};_ __
</syntaxhighlight>
=={{header|BASIC}}==
{{header|ZX Spectrum Basic}}
For dialects of BASIC that include the <code>LIST</code> command, Quines are trivial.
<syntaxhighlight lang
For dialects that include the <code>DATA</code> keyword, it is almost as easy.
{{works with|QBasic}}
<
DO
READ x$
Line 437 ⟶ 443:
DATA "LOOP UNTIL LEN(x$) < 1"
DATA "END"
DATA ""</
==={{header|BASIC256}}===
<syntaxhighlight lang="freebasic">s$ = "s$ = : print left(s$, 5) + chr(34) + s$ + chr(34) + mid(s$, 5, 66)" : print left(s$, 5) + chr(34) + s$ + chr(34) + mid(s$, 5, 66)</syntaxhighlight>
==={{header|QuickBASIC}}===
{{works with|QBasic}}
<
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$)
Line 458 ⟶ 466:
END SELECT
NEXT I
</syntaxhighlight>
==={{header|BaCon}}===
<
{{out}}
Line 477 ⟶ 485:
And one that is a little less cheaty and a little more meaty:
<
{{out}}
Line 487 ⟶ 495:
Works with 1k of RAM.
<
20 LET I=VAL "16512"
30 PRINT TAB (VAL "4"-LEN L$);L$;
Line 498 ⟶ 506:
100 LET L$=STR$ (VAL L$+VAL "10")
110 LET I=I+VAL "4"
120 IF VAL L$<=VAL "120" THEN GOTO VAL "30"</
{{out}}
Exactly the same.
Line 511 ⟶ 519:
=={{header|Batch File}}==
<syntaxhighlight lang
For Windows 2000 and later only:
<
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
{{works with|ARM BBC BASIC}}
<
=={{header|BCPL}}==
<
let start() be
Line 566 ⟶ 574:
n := n + 1
$)
$)</
=={{header|beeswax}}==
Instruction pointers in beeswax programs can drop values in their own source code (growing the program space, if necessary), or pick up values from everywhere in the source code.
<
or
<
The instruction pointer starts at the left, travels to the right, and at instruction <code>D</code> the IP drops the current value at the top of its own stack—96, or ASCII value for <code>`</code> —left of the source code, which changes the program to:
<
or
<
respectively.
Line 586 ⟶ 594:
A version that does not modify itself:
<syntaxhighlight lang
=={{header|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.)
<syntaxhighlight lang
=={{header|Binary Lambda Calculus}}==
As explained at https://tromp.github.io/cl/Binary_lambda_calculus.html#
<
<code>16 46 80 05 bc bc fd f6 80 16 46 80 05 bc bc fd f6 80</code>
=={{header|Bob}}==
<
v=\[
"c=\",\"; n=\"\\n\"; q=\"\\\"\"; s=\"\\\\\";",
Line 634 ⟶ 644:
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.
=={{header|bootBASIC}}==
<syntaxhighlight lang
=={{header|BQN}}==
Works in: [[CBQN]]
Writes directly to STDOUT.
A BQN spin on the classic APL quine. <code>•Repr</code> helps with quoting the data string here.
<syntaxhighlight lang="bqn">•Out 1⌽∾˜18⥊•Repr"•Out 1⌽∾˜18⥊•Repr"</syntaxhighlight>
=={{header|Bracmat}}==
<syntaxhighlight lang
=={{header|Brainf***}}==
<
+>>>>+++>>+++++>>+>+++>>>++>>++>>+>>++>+>+++>>>++>>+++++++++++++>>+>>++>+>+++>+>+++>>>++>>++++>>+>>++>+>>>>+++>>+++++>>>>++>>>>+>+>+
+>>+++>+>>>>+++>+>>>>+++>+>>>>+++>>++>++>+>+++>+>++>++>>>>>>++>+>+++>>>>>+++>>>++>+>+++>+>+>++>>>>>>++>>>+>>>++>+>>>>+++>+>>>+>>++>+
Line 650 ⟶ 670:
+>>++++++++>>+>>++>+>>>>+++>>++++>>+>+++>>>>>>++>+>+++>>+>++>>>>+>+>++>+>>>>+++>>+++>>>+[[->>+<<]<+]+++++[->+++++++++<]>.[+]>>
[<<+++++++[->+++++++++<]>-.------------------->-[-<.<+>>]<[+]<+>>>]<<<[-[-[-[>>+<++++++[->+++++<]]>++++++++++++++<]>+++<]++++++
[->+++++++<]>+<<<-[->>>++<<<]>[->>.<<]<<]</
=={{header|Burlesque}}==
Line 656 ⟶ 676:
Using the official interpreter:
<
"I'm a quine."</
Every string, every number, every block is a quine.
=={{header|C}}==
<
static char sym[] = "\n\t\\\"";
Line 672 ⟶ 692:
return 0;
}
</syntaxhighlight>
===Shorter version===
<
int main(){char*c="#include <stdio.h>%cint main(){char*c=%c%s%c;printf(c,10,34,c,34,10);return 0;}%c";printf(c,10,34,c,34,10);return 0;}
</syntaxhighlight>
===Cheating using __FILE__===
On operating systems where a large range of characters can be used, it is possible to create a Quine by putting the following C code in a file with the same name.
<syntaxhighlight lang="c">#include <stdio.h>
main(void){printf(__FILE__);}
</syntaxhighlight>
If white space is not permitted in file names, the first line and trailing newline can be omitted.
In practice, it may be necessary to tell the compiler that the language is C, as the filename does not end in .c. Similar Quines are possible in languages such as Python.
=={{header|C sharp}}==
<
=={{header|C++}}==
<
int main(){char n[]=R"(#include<cstdio>
int main(){char n[]=R"(%s%c";printf(n,n,41);})";printf(n,n,41);}</
=={{header|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.
<syntaxhighlight lang
=={{header|C3}}==
<syntaxhighlight lang="c">import std::io; fn void main() => io::printfn("%sString q = \x60%s\x60;", q, q);String q = `import std::io; fn void main() => io::printfn("%sString q = \x60%s\x60;", q, q);`;</syntaxhighlight>
=={{header|Ceylon}}==
<
=={{header|Clojure}}==
<
A shorter but less interesting version:
<
=={{header|CLU}}==
<syntaxhighlight lang="clu">q="start_up=proc()\n"||
" po:stream:=stream$primary_output()\n"||
" stream$puts(po,\"q=\\\"\")\n"||
" for c:char in string$chars(q) do\n"||
" if c='\\n' then stream$puts(po,\"\\\\n\\\"||\\n\\\"\")\n"||
" elseif c='\\\\' then stream$puts(po,\"\\\\\\\\\")\n"||
" elseif c='\\\"' then stream$puts(po,\"\\\\\\\"\")\n"||
" else stream$putc(po,c)\n"||
" end\n"||
" end\n"||
" stream$puts(po,\"\\\"\\n\"||q)\n"||
"end start_up\n"||
""
start_up=proc()
po:stream:=stream$primary_output()
stream$puts(po,"q=\"")
for c:char in string$chars(q) do
if c='\n' then stream$puts(po,"\\n\"||\n\"")
elseif c='\\' then stream$puts(po,"\\\\")
elseif c='\"' then stream$puts(po,"\\\"")
else stream$putc(po,c)
end
end
stream$puts(po,"\"\n"||q)
end start_up</syntaxhighlight>
=={{header|COBOL}}==
Line 706 ⟶ 766:
cobc -x -free -frelax quine.cob
<
The following two quines were in a gray past (around 2004?) posted to the (currently inaccessible) language forum of the [http://mvshelp.net/vbforums/ mvsHelp Boards]
<
PROGRAM-ID. GRICE.
ENVIRONMENT DIVISION.
Line 1,047 ⟶ 1,107:
ML-99.
CLOSE OUTPUT-FILE.
STOP RUN.</
<
PROGRAM-ID. QUINE.
DATA DIVISION.
Line 1,096 ⟶ 1,156:
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 could be found of the site of [http://www.tmdg.co.uk/programing/quine.cbl.php Tom Dawes-Gamble], but is reproduced below, as the original seems to have vanished:
<
Author. Tom Dawes-Gamble. (c) 2000
01 src-lines pic x(768) value
Line 1,123 ⟶ 1,183:
Display ' ' sl(i).
Stop run.
</syntaxhighlight>
=={{header|CoffeeScript}}==
<
=={{header|Commodore BASIC}}==
A rather long and unwieldy (although nicely formatted) BASIC quine that doesn't use the <tt>10 LIST</tt> cheat. Works on the PET, VIC-20, C-64, C-128, C-16 and Plus/4, CBM-II, and CBM-5x0 series, and probably several non-Commodore BASICs as well, especially those based on Microsoft BASIC.
<
20 DATA 49,56,48,32,70,79,82,32,73,61,48,32,84,79,32,78,13,49,57,48,32,58,32
30 DATA 82,69,65,68,32,65,40,73,41,13,50,48,48,32,78,69,88,84,32,73,13,50,49
Line 1,161 ⟶ 1,221:
290 FOR I=0 TO N
300 : PRINT CHR$(A(I));
310 NEXT I</
=={{header|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)))))</
This one does the same thing using quasiquote (template) syntax; in some implementations it may not print nicely (but will still work):
<
or another version:
<
This program's source contains an explicit reference to itself, which it prints in a manner preserving that reference:
<
or another version (the former version cause looping in SBCL 1.0.56):
<
This is an example using format and explicit referencing:
<
An example using [[REPL]] variables:
<syntaxhighlight lang
=={{header|Cowgol}}==
<
var i: uint8 := 0;
var c: uint8[] := {
Line 1,225 ⟶ 1,285:
end loop;
print("\n};\n");
print(&c as [uint8]);</
=={{header|Crystal}}==
<
<tt>tap</tt> is an Object method which passes its invocant to the provided block.
Line 1,234 ⟶ 1,294:
=={{header|D}}==
This Quine outputs its own source both during compiling and running.
<
mixin(s);";import std.stdio;void main(){writefln(q);pragma(msg,q);}`;
mixin(s);
</syntaxhighlight>
''NB:'' last line should be CRLF to match <tt>pragma</tt>'s newline output behaviour.
Line 1,243 ⟶ 1,303:
Dao's BNF-like meta-programming macro supports quoting expressions as strings,
which allow writing a quine as the following:
<
=={{header|Dart}}==
<
=={{header|dc}}==
<syntaxhighlight lang
=={{header|Déjà Vu}}==
<
!print !. dup</
=={{header|Draco}}==
<syntaxhighlight lang="draco">*char q=
"proc main() void:\r\n"
" [128]char l;\r\n"
" char ch;\r\n"
" channel input text qc, lc;\r\n"
" open(qc, q);\r\n"
" writeln(\"*char q=\");\r\n"
" while readln(qc; &l[0]) do\r\n"
" write('\"');\r\n"
" open(lc, &l[0]);\r\n"
" while read(lc; ch) do\r\n"
" if ch='\"' or ch='\\\\' then write('\\\\') fi;\r\n"
" write(ch)\r\n"
" od;\r\n"
" close(lc);\r\n"
" writeln(\"\\\\r\\\\n\\\"\")\r\n"
" od;\r\n"
" close(qc);\r\n"
" writeln(';');\r\n"
" writeln(q)\r\n"
"corp\r\n"
;
proc main() void:
[128]char l;
char ch;
channel input text qc, lc;
open(qc, q);
writeln("*char q=");
while readln(qc; &l[0]) do
write('"');
open(lc, &l[0]);
while read(lc; ch) do
if ch='"' or ch='\\' then write('\\') fi;
write(ch)
od;
close(lc);
writeln("\\r\\n\"")
od;
close(qc);
writeln(';');
writeln(q)
corp</syntaxhighlight>
=={{header|E}}==
<
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
S$ = "print strchar 83 & strchar 36 & strchar 32 & strchar 61 & strchar 32 & strchar 34 & S$ & strchar 34 & strchar 10 & S$"
print strchar 83 & strchar 36 & strchar 32 & strchar 61 & strchar 32 & strchar 34 & S$ & strchar 34 & strchar 10 & S$
</syntaxhighlight>
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module test {
@Inject Console console;
void run() {
console.print($./test.x);
}
}
</syntaxhighlight>
{{out}}
<pre>
module test {
@Inject Console console;
void run() {
console.print($./test.x);
}
}
</pre>
=={{header|Elixir}}==
<
:io.fwrite(a,[a])</
=={{header|Erlang}}==
<div style="width:100%;overflow:scroll">
<
-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].</
</div>
=={{header|ERRE}}==
<
BEGIN
READ(D$,Y$)
Line 1,308 ⟶ 1,438:
DATA("PRINT(Y$)")
DATA("")
END PROGRAM</
=={{header|Euphoria}}==
{{trans|C}}
<
=={{header|F Sharp|F#}}==
Using .NET string formatting
<
Using Printf library
<
=={{header|Factor}}==
With printf:
<
With prettyprinter:
<
=={{header|FALSE}}==
El código es de Mathew Hendry (m.hendry@dial.pipex.com)
<syntaxhighlight lang="false">["'[,34,$!34,'],!"]'[,34,$!34,'],!</syntaxhighlight>
=={{header|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.
<
2[$:{:@]$g:0=?v >o:4a*=?!v~1+:3=?;0ao>
>~" "^ >1+ ^</
=={{header|Forth}}==
A large number of quine methods are listed [http://www.complang.tuwien.ac.at/forth/quines.html here], the simplest of which is:
<syntaxhighlight lang
=={{header|Fortran}}==
===F90+===
Fortran allows the start of a text literal to be marked by either an apostrophe or a double quote and the end by the corresponding character. Doubling is used to signify that the delimiter appears within a literal.
<
{{out}}
<pre>
Line 1,346 ⟶ 1,482:
In ASCII, character 39 is an apostrophe. When run, the last "print" is preceded by three spaces after the semicolon that do not appear in the source. This wouldn't worry a Fortran compiler, because spaces are ignored outside text literals. More troublesome is that the first letter of the output appears in column one, and, being the letter "c", that marks a comment. This is why the text lighlighting has rendered the source text in italic. Later Fortran compilers may disregard this comment formalism in favour of the now standard in-line comment starter of an exclamation mark, and for them, the source would not be a comment.
===Older Fortran===
This reverts to fixed-format source form, relying on the format code / to signify a new line so that ASCII control characters need not be represented. Code T''n'' means "tab" to column ''n'' - no ASCII tab characters are involved. And difficulty with quoted strings is avoided by using the Hollerith form, ''n''H, signifying that ''n'' characters follow the H as a text literal. <
STOP
100 FORMAT(6X,12HWRITE(6,100)/6X,4HSTOP/
Line 1,353 ⟶ 1,489:
.)/T48,2H)/T1,5X2(21H.)/T48,2H)/T1,5X2(21H)/
.T62,10H)/6X3HEND)T1,5X2(28H.T62,10H)/6X3HEND)T1,5X2(28H)/6X3HEND)
END</
And indeed, exactly that opaque gibberish is written, with leading spaces to column seven and full stops in column six to mark a continuation. This was checked by UltraCompare, not just by eye!
Line 1,367 ⟶ 1,503:
=={{header|Free Pascal}}==
<
=={{header|FreeBASIC}}==
===Código 1:===
<
P("#Define P(X) Print X: Print ""P("" & #X & "")""")</
===Código 2:===
<
=={{header|Frink}}==
This is not a particularly clever nor concise quine, but it is indeed a quine.
<
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:
<syntaxhighlight lang
The most concise quine in Frink, though, is the empty string.
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Quine}}
'''Solution'''
'''Preamble. Symbolic computation'''
Symbolic computation works different than traditional one. In symbolic computation, the program becomes gradually in its output, by the application of [[wp:Rewriting|rewriting rules]].
'''Example 1. The simplest program'''
The simplest program is a Null expression. Please notice that it is not an empty program (which is disallowed). It is just a one expression program: the Null expression, which has no rewriting rules.
[[File:Fōrmulæ - Quine 01.png]]
[[File:Fōrmulæ - Quine 02.png]]
'''Example 2. A program with non-reducible expressions'''
According to symbolic computation, if a program contains only non-reducible expressions (expression with no rewriting rules), then it will no be transformed to anything else, and it will be its own output.
[[File:Fōrmulæ - Quine 03.png]]
[[File:Fōrmulæ - Quine 04.png]]
[[File:Fōrmulæ - Quine 05.png]]
[[File:Fōrmulæ - Quine 06.png]]
[[File:Fōrmulæ - Quine 07.png]]
[[File:Fōrmulæ - Quine 08.png]]
=={{header|Furor}}==
A very short solution, using some special features of Furor:
<
#s sto selfstring QUOTE @selfstring dup print QUOTE NL printnl end { „selfstring” }</
And behold, here is a more complex but "traditional" solution of this famous task, solved by 3 loops:
<
#s
7 {| {} §eleje[] printnl |}
Line 1,416 ⟶ 1,579:
vége:
{ „selfstring” }
{ „maxlines” }</
=={{header|Peri}}==
<syntaxhighlight lang="peri">
###sysinclude standard.uh
#g §vége §eleje - sto maxlines
#s
8 {{ {{}} §eleje[] printnl }}
@maxlines {{ {{}} §eleje[] QUOTE print QUOTE NL }}
8 @maxlines {{ , {{}} §eleje[] printnl }}
end
eleje:
"###sysinclude standard.uh"
"#g §vége §eleje - sto maxlines"
"#s"
"8 {{ {{}} §eleje[] printnl }}"
" @maxlines {{ {{}} §eleje[] QUOTE print QUOTE NL }}"
"8 @maxlines {{ , {{}} §eleje[] printnl }}"
"end"
"eleje:"
"vége:"
"{ „selfstring” }"
"{ „maxlines” }"
vége:
{ „selfstring” }
{ „maxlines” }
</syntaxhighlight>
=={{header|FutureBasic}}==
This quine depends on BASIC syntax which, although still compilable with FB, is long obsolete.
<syntaxhighlight lang="futurebasic">
window 1,,(0,0,350,430)
Str255 d, x
read d
do
read x
print x
until len$(x) == 0
restore
do
read x
print d; chr$(34); x; chr$(34)
until len$(x) == 0
HandleEvents
data "data "
data "window 1,,(0,0,350,430)"
data "Str255 d, x"
data "read d"
data "do"
data " read x"
data " print x"
data "until len$(x) == 0"
data "restore"
data "do"
data " read x"
data " print d; chr$(34); x; chr$(34)"
data "until len$(x) == 0"
data "HandleEvents"
data ""
</syntaxhighlight>
{{output}}
<pre>
Ditto, of course.
</pre>
=={{header|Gabuzomeu}}==
<
</syntaxhighlight>
=={{header|Gambas}}==
You can run this from shell with "gbs3" of the Gambas3 project (BASIC dialect).
<
print subst(s,chr(34),s,chr(34),chr(10))
</syntaxhighlight>
{{Out}}
<pre>> gbs3 quine_1.gambas
Line 1,433 ⟶ 1,662:
=={{header|GAP}}==
<
Print( "f:=", f, ";;\nf();\n" );
return;
end;;
f();
</syntaxhighlight>
=={{header|Gema}}==
<
=={{header|Go}}==
<
import "fmt"
Line 1,451 ⟶ 1,680:
a := "package main\n\nimport \"fmt\"\n\nfunc main() {\n\ta := %q\n\tfmt.Printf(a, a)\n}\n"
fmt.Printf(a, a)
}</
=={{header|Groovy}}==
There are several ways to do this. Here are five:
<
<
<
<
<
Also Groovy has a trivial solution of an empty (0 length) file even though that isn't an allowable solution here.
=={{header|GW-BASIC}}==
<syntaxhighlight lang
=={{header|Hare}}==
<syntaxhighlight lang="hare">use fmt;
const src: str = "use fmt;
const src: str = {0}{1}{0};
export fn main() void = {{fmt::printfln(src, '{0}', src)!;}};";
export fn main() void = {fmt::printfln(src, '"', src)!;};</syntaxhighlight>
=={{header|Haskell}}==
Line 1,469 ⟶ 1,705:
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.
<
It is also possible to eliminate one or both of the variables (point-free style): the <code>let</code> can be replaced with a lambda. (<code>.</code> is function composition.)
<
<
and <var><code>s</code></var> can be replaced by <code>ap</code>, which when applied to functions has the effect of the [[wp:SKI combinator calculus|S combinator]]:
<
(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:
<
Finally, here is a standalone program (the preceding examples only work in the REPL):
<
=={{header|Hoon}}==
Unfortunately, this is quite a long quine due to the pretty-printing that is employeed. A majority of the code is fixing up the printed result of the array so it can be ran directly.
<
Two much shorter quines were created and tweeted from the @urbit_ twitter account, which might be more interesting:
<
<
=={{header|HQ9+}}==
Any program with a single “<tt>Q</tt>” is a quine. The simplest possible such program is just this:
<syntaxhighlight lang
=={{header|HTML}}
===Using CSS===
{{works with|Opera|10.0}} <!-- At the very least, guaranteed to work with these -->
{{works with|Firefox|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.
<
<html>
<head>
Line 1,530 ⟶ 1,767:
</head>
<body></body>
</html></
=={{header|Huginn}}==
<
exec huginn --no-argv -E "${0}"
#! huginn
Line 1,551 ⟶ 1,788:
)
);
}</
=={{header|Icon}} and {{header|Unicon}}==
<
write("procedure main();x:=",image(x));write(x);end</
=={{header|Inform 7}}==
<
=={{header|Insitux}}==
<syntaxhighlight lang="insitux">(#(join(char-code 34)[% %(char-code 41)])"(#(join(char-code 34)[% %(char-code 41)])")</syntaxhighlight>
=={{header|INTERCAL}}==
Line 1,564 ⟶ 1,804:
=={{header|Io}}==
<syntaxhighlight lang
=={{header|J}}==
Technically, the empty program in J is a quine, as it has an empty result. For example:
<
</syntaxhighlight>
Also, many many numbers in J are quines. For example (result not shown, here, for clarity):
<syntaxhighlight lang
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).
Line 1,584 ⟶ 1,824:
Author: Bertram Felgenhauer
<div style="width:100%;overflow:scroll">
<
</div>
{{works with|Java|1.5+}}
<div style="width:100%;overflow:scroll">
<
</div>
=={{header|JavaScript}}==
{{works with|SpiderMonkey}} 1.7.0
<
=== 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().
<
=== Replacing String ===
<
=== encodeURI as string escapes ===
Functions like <code>encodeURI/decodeURI</code> benefit js with highly controllable string escapes, like the quotes, newlines, etc. Thus, the following js-flavored quine requires no explicit or implicit <code>stringify</code>, <code>eval</code> or template literals functionalities:
<syntaxhighlight lang="javascript">let x="let x=%22quinner%22; alert(decodeURI(x).replace(%22quinner%22, x));"; alert(decodeURI(x).replace("quinner", x));
</syntaxhighlight>
===Code As Data===
Line 1,608 ⟶ 1,853:
ES6 expression that evaluates to the expression (<code>eval(expression) === expression</code>)
<
ES5 version of above
<
prints itself via <code>console.log</code> (note <code>console.log</code> is not in the ECMAScript Standard)
<
===Another Method===
<
===A simple module which simply evaluates to itself===
<
return '(' + f.toString() + ')();';
})();</
{{Out}}
<
return '(' + f.toString() + ')();';
})();</
===Or logs itself to the console===
<
console.log('(' + f.toString() + ')();');
})();</
{{Out}}
Line 1,651 ⟶ 1,896:
===ES6 syntax===
<
with 2 statements:
<
===ASCII Art===
<
nequinequineq uinequin equinequinequinequinequineq uinequinequinequinequinequineq
uinequinequinequi nequineq uinequinequinequinequinequin equinequinequinequinequinequin
Line 1,676 ⟶ 1,921:
uinequinequine quinequin equinequinequinequ inequinequinequinequinequineq
uineq`,
e);q()</
=={{header|Joy}}==
<
=={{header|Jsish}}==
Based on Javascript eval solution.
<
{{out}}
Double test, run quine.jsi output through the jsish argument evaluator:
Line 1,690 ⟶ 1,935:
=={{header|Julia}}==
<
println("x=$(repr(x))\n$x")</
In Julia, <tt>$x</tt> in a string literal interpolates the value of the variable into the string.
Line 1,701 ⟶ 1,946:
=={{header|Kotlin}}==
The following is based on the classic C quine but makes use of Kotlin's 'raw' (i.e. triple quoted) string literals.
<
const val F = """// version 1.1.2
Line 1,714 ⟶ 1,959:
fun main(args: Array<String>) {
System.out.printf(F, 34, 34, 34, F, 34, 34, 34)
}</
=={{header|Lambdatalk}}==
<
-> {lambda {:x} :x}</
=={{header|Lang}}==
<syntaxhighlight lang="lang"># Execute in command line without any arguments except this Lang file
lang.name = Quine
lang.version = v1.0.0
$h = {{{# Execute in command line without any arguments except this Lang file
lang.name = Quine
lang.version = v1.0.0}}}
$s = {{{func.printf($h\n\n\$h \= %s{{%s}}%s\n\$s \= %s{{%s}}%s\n%s, {, $h, }, {, $s, }, $s)}}}
func.printf($h\n\n\$h \= %s{{%s}}%s\n\$s \= %s{{%s}}%s\n%s, {, $h, }, {, $s, }, $s)</syntaxhighlight>
=={{header|Lasso}}==
Line 1,724 ⟶ 1,980:
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=(:'
$a->join(',')
Line 1,730 ⟶ 1,986:
var(b=bytes)
$a->foreach => { $b->import8bits(#1) }
$b->asString</
=={{header|LDPL}}==
<
A IS NUMBER VECTOR
C IS TEXT
Line 2,475 ⟶ 2,731:
STORE 704 IN N
CALL SUB-PROCEDURE SHOW</
=={{header|Liberty BASIC}}==
<
=={{header|LIL}}==
Line 2,489 ⟶ 2,745:
Source from a file read from lil when the shell is invoked ''gets a little trickier''. The interactive shell wraps code read from files which changes '''this'''. So, as a testament to ease of embedding, here's a new non-interactive LIL one liner shell so we can '''write [reflect this]'''.
<
One line of LIL, given as argv[1]
Tectonics: gcc -o lilone lilone.c lil.c -lm
Line 2,506 ⟶ 2,762:
lil_free(lil);
return 0;
}</
{{out}}
Line 2,535 ⟶ 2,791:
=={{header|Lisp}}==
Lisp has a mechanism to ''quote'' code without the need to use strings:
<
'(lambda (x) (list x (list 'quote x))))</
=={{header|Logo}}==
Somewhat brute-force..
<
type "|make "a [|
foreach :a [ type word "| | ? ]
print "| ]|
foreach :a [ type char ? ]
bye</
=={{header|Lua}}==
<
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Alfa {
Rem {This Program Show itself in Help Form}
inline "help "+quote$(module.name$)
}
Alfa
</syntaxhighlight>
=={{header|M4}}==
<
quine(`define(`quine',``$1(`$1')'')dnl
quine')</
=={{header|make}}==
<syntaxhighlight lang="make">quine=$(info quine=$(value quine))$(info $$(quine))$(eval quine:;@:)
$(quine)</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
or
<
or
<
or
<
or
<syntaxhighlight lang
or
<syntaxhighlight lang
=={{header|MATLAB}} / {{header|Octave}}==
This script runs either from an m-file or directly from workspace (author: J. C. Lucero):
<
----
The example works for functions and scripts stored as m-files. It does not work for functions defined only in the workspace.
<
fid = fopen([mfilename,'.m']);
while ~feof(fid)
Line 2,593 ⟶ 2,862:
end;
fclose(fid);
end;</
or
<
type(mfilename);
end;</
Without accessing the file:
<
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
/* Using ?format from the underlying 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))))()$
</syntaxhighlight>
=={{header|MiniScript}}==
A simple one-liner:
<
A multi-line version; and in this version, the hash character (ASCII code 35) is used to indicate where the string constant goes in the source. Also, semicolons (ASCII code 59) are used in this case as arbitrary line break indicators.
<
s="Q=char(34);s=#;for line in s.split(char(59)); print line.replace(char(35),Q+s+Q);end for"
for line in s.split(char(59))
print line.replace(char(35),Q+s+Q)
end for</
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
Line 2,629 ⟶ 2,900:
WriteString(buf);
ReadChar
END Quine.</
=={{header|MUMPS}}==
<
NEW I,L SET I=0
FOR SET I=I+1,L=$TEXT(+I) Q:L="" WRITE $TEXT(+I),!
Line 2,639 ⟶ 2,910:
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.
=={{header|NASM}}==
Compiles to the source code when -f raw
<
%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</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols nobinary
Line 2,765 ⟶ 3,036:
say pgm
return</
=={{header|NewLISP}}==
<
=={{header|Nim}}==
Another quine:
<
echo x[0..7],chr(34),x,chr(34),chr(10),x[8 .. ^1]</
Another one:
<
This quine prints its own sourcecode at compiletime as well as at runtime:
<
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: nim --verbosity:0 c quine
=={{header|NS-HUBASIC}}==
<syntaxhighlight lang
=={{header|Oberon-2}}==
<syntaxhighlight lang="oberon2">MODULE M;
IMPORT O:=Out;
CONST
T=";PROCEDURE c*;BEGIN O.Char(22X);O.String(T) END c;BEGIN O.String('MODULE M;IMPORT O:=Out;CONST T=');c END M.";
PROCEDURE c*;
BEGIN
O.Char(22X);O.String(T)
END c;
BEGIN
O.String('MODULE M;IMPORT O:=Out;CONST T=');
c
END M.</syntaxhighlight>
=={{header|Objeck}}==
<
=={{header|OCaml}}==
(newline included)
<
Alternative:
(newline included)
<
=={{header|Oforth}}==
<
=={{header|Ol}}==
Like others Lisps,
<
=={{header|ooRexx}}==
===Cheating===
<syntaxhighlight lang
===Non-Cheating, with INTERPRET===
<
===Non-Cheating, without INTERPRET===
<
===Non-Cheating, without INTERPRET, with unprintable characters===
Line 2,828 ⟶ 3,112:
The two unprintable characters are '07'x. Somewhat difficult to enter, but still a perfectly valid ooRexx program (and Quine).
<
=={{header|OxygenBasic}}==
<
source="print source"
a=compile source : call a : freememory a</
=={{header|Oz}}==
A one-liner that uses the ASCII code for <code>"</code> to avoid "quoted quotes". We put the value assignment to the end by using multithreading and implicit synchronization on the dataflow variable <code>I</code>.
<
=={{header|PARI/GP}}==
<syntaxhighlight lang
Assign this source code to variable quine:
<
Output of interpreter:<pre>gp > quine
Line 2,860 ⟶ 3,144:
=={{header|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.
<
This version does compile in Free Pascal and UCSD Pascal. Newline included.
<
A quality quine should not depend on a particular character set. This version also works on systems limited to 80-character lines and on legacy word-based systems which require literal strings to be packed and of a fixed size if assigned to an array.
<
var l:array[1..9]of string; c:array[1..7]of char; i:integer;
lc, a, o, k, n, e, s, t:char; begin
Line 2,885 ⟶ 3,169:
writeln(a, t, n, e, lc, lc, lc, lc, s);
for i := 1 to 7 do write(t,o,i:1,k,n,e,lc,c[i],lc,s);
writeln; for i := 4 to 9 do writeln(l[i]); end.</
=={{header|Perl}}==
This relatively simple Perl example imitates the C example.
<
); printf($s, $s);
</syntaxhighlight>
Note the terminating newline.
===Self-reading (some consider cheating)===
Accessing source code via <code>DATA</code> filehandle:<
print <DATA>
__DATA__</
even simpler:
<
<syntaxhighlight lang
===Quine Generator===
Perhaps the simplest quine in Perl 5 is:
<
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.
Line 2,912 ⟶ 3,196:
<
{
package Quine;
Line 2,958 ⟶ 3,242:
=cut
}
return 1 if caller(1);print"{local\$_=q{$_};eval}\n"};eval}</
=={{header|Phix}}==
Credit: Aidan Bindoff
<!--<
<span style="color: #008080;">constant</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"constant c=%sprintf(1,c,{34&c&34})"</span><span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">34</span><span style="color: #0000FF;">&</span><span style="color: #000000;">c</span><span style="color: #0000FF;">&</span><span style="color: #000000;">34</span><span style="color: #0000FF;">})</span>
<!--</
=={{header|PHP}}==
{{trans|C}}
<
'; printf($p,39,$p,39); ?></
Note the terminating newline.
Line 2,979 ⟶ 3,263:
===Using 'quote'===
Note that 'quote' in PicoLisp corresponds to 'lambda' in other Lisps
<
{{out}}
<pre>-> ('((X) (list (lit X) (lit X))) '((X) (list (lit X) (lit X))))</pre>
===Using 'let'===
<
{{out}}
<pre>-> (let X '(list 'let 'X (lit X) X) (list 'let 'X (lit X) X))</pre>
Line 2,990 ⟶ 3,274:
=={{header|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(',
' *)char(99),i,j,(translate,substr)builtin,c char\i=1\j=n',
Line 3,001 ⟶ 3,285:
(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'.
<
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:
<
(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( ';</
=={{header|PlainTeX}}==
===Output to terminal===
This assumes the filename of the source file to be ‘q.tex’, and the banner from vanilla Knuth’s TeX:
<
(q.tex \output {\message {\output \the \output \end }\batchmode }\end </
===Output to dvi===
<
~{~}~\s~\let
=={{header|Pony}}==
<
new create(env: Env) =>
let a = """env.out.print("actor Main\nnew create(env: Env) =>\nlet a = \"\"\""+a+"\"\"\"\n"+a)"""
env.out.print("actor Main\nnew create(env: Env) =>\nlet a = \"\"\""+a+"\"\"\"\n"+a)</
=={{header|PowerBASIC}}==
This is ''technically'' based on the [[#BASIC|BASIC]] code above, but is in fact a complete rewrite.
<
REDIM s(1 TO DATACOUNT) AS STRING
o$ = READ$(1)
Line 3,072 ⟶ 3,356:
DATA " CLOSE"
DATA "END FUNCTION"
END FUNCTION</
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
Adapted from Liberty BASIC.
<
$S.Substring(0,5) + [string][char]39 + $S + [string][char]39 + [string][char]10 + $S.Substring(5)</
{{out}}
<pre>
Line 3,086 ⟶ 3,370:
<br><b>Variations to access the code directly</b><br><br>
<b>In a saved script</b>
<syntaxhighlight lang
<b>At the command line</b>
<syntaxhighlight lang
<b>In a function</b>
<
=={{header|Processing}}==
=== Console with immediate mode ===
A simple one-liner in Processing prints itself to the console.
{{works with|Processing}}
<syntaxhighlight lang="processing">String p="String p=%c%s%1$c;System.out.printf(p,34,p);";System.out.printf(p,34,p);</syntaxhighlight>
This takes advantage of the fact that Processing does not require a wrapping class or main method (unlike the Java it is based on). Further, Processing "immediate mode" without setup() or draw() methods does not require a method or function at all, and instead can compile and run direct commands. Processing normally uses "print", and calling the undocumented "System.out.printf" from Java is not idiomatic. However that is used here because it gives easy access to string templating. In printf(p,34,p) the template p is passed two arguments: 34 is inserted into %c and the back-reference %1$c, where they each become an ASCII quote character, while p (itself) is inserted at %s.
=== Graphical output ===
One of the most common uses of Processing is to draw to the screen and render images, including text with rendered fonts. A more complex Processing quine correctly renders its source code on the canvas and saves the frame image of its source to an image file.
{{works with|Processing|2.x+}}
<syntaxhighlight lang="processing">int o=12,i=0;
void setup(){size(480,240);noLoop();}void draw(){background(0);
String[] c = {
"int o=12;i=0",
"void setup(){size(480,240);noLoop();}void draw(){background(0);",
" String[] c = {",
" };",
" for(;i<3;i++)text(c[i],o,o*(i+1));",
" for(;i<9;i++)text(c[i],o,o*(i+10));",
" for(i=0;i<9;i++)text(char(34)+c[i]+char(34)+',',o*3,o*(i+1+3));",
" saveFrame();",
"}",
};
for(;i<3;i++)text(c[i],o,o*(i+1));
for(;i<9;i++)text(c[i],o,o*(i+10));
for(i=0;i<9;i++)text(char(34)+c[i]+char(34)+',',o*3,o*(i+1+3));
saveFrame();
}</syntaxhighlight>
The code uses a line offset o of 12px for laying out lines of text using the default 10px white font. It reuses a global int i across all three loops to save a bit of space and to take advantage of non-linear drawing to the screen: the outer lines 0-3 and 4-9 are drawn in the first and second loops without resetting i, then the inner lines 0-9 are drawn between them in the third loop.
=={{header|Prolog}}==
One method to produce a quine is to read the data structures that hold the source code:
<
listing(quine).</
Producing a quine without cheating is more complex. The following program produces a data structure equivalent to the program itself, then outputs it:
<
The use of <tt>numbervars</tt> is a GNU Prolog extension that fixes the variable names in the output to be single letters, in alphabetical order by appearance, and thus match the original program. Removing it, the quine still works, but the variable names in the output will probably be different; thus, it will produce a program equivalent to itself, rather than an exact copy of itself.
Line 3,105 ⟶ 3,424:
A version that is source-code-centric rather than AST-centric, and does not rely on any built-in facilities for formatted printing, might look as follows:
<
:- initialization(main).
Line 3,216 ⟶ 3,535:
main :- (quine(Q), write(Q);true),halt.
% line break in the end of file is important
</syntaxhighlight>
It could be made shorter. This version contains some introns that have been used for code generation (like the encode/2 predicate, that is not really needed).
Using format/2 predicate:
<
=={{header|PureBasic}}==
<
=={{header|Python}}==
Line 3,230 ⟶ 3,549:
A simple and straightforward quine. Character chr(34) is a double quote, and chr(10) is a new line (Author: J. C. Lucero).
<
print('w = ' + chr(34) + w + chr(34) + chr(10) + w)</
----
Line 3,237 ⟶ 3,556:
{{works with|Python|2.x and 3.x}}
Python's <tt>%r</tt> format conversion uses the <tt>repr()</tt> function to return a string containing the source code representation of its argument:
<
print(x % x)</
{{works with|Python|3.x and 2.6+}}
With the new <tt>str.format</tt>:
<
{{works with|Python|2.x and 3.x}}
Line 3,248 ⟶ 3,567:
program will spit the code back out on a terminal window:
<
Note: actually an empty file could be treated as python quine too.
{{works with|Python|2.x and 3.x}}
<
{{works with|Python|3.8+}}
A simple implementation that uses exec, an f-string, and the walrus operator.
<
----
Line 3,265 ⟶ 3,584:
make a program with this single line in it
<syntaxhighlight lang
and name the file print(__file__[:-3]).py
Line 3,271 ⟶ 3,590:
bash example command:
<
print(__file__[:-3])
</syntaxhighlight>
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__)" .
<
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...
<syntaxhighlight lang="text">$ cat reproducing.py
File "reproducing.py", line 1
File "reproducing.py", line 1
Line 3,291 ⟶ 3,610:
File "reproducing.py", line 1
^
IndentationError: unexpected indent</
----
Line 3,297 ⟶ 3,616:
Here's a few by me (Nathaniel Virgo). They represent attempts to make clean, readable "Pythonic" quines. The first one is straightforward, using format and chr(34) to construct a multiline string:
<
print x.format(chr(34)*3,x)"""
print x.format(chr(34)*3,x)</
This next one uses a base64 encoding, which is an off-the-shelf way to pack strings containing quotes and newlines etc. into ones that consist only of printable characters. Python purists will probably tell me I should have used the base64 package instead.
<
b = a.decode('base64')
print b[:5]+a+b[5:]</
In the above quine I felt it was inelegant to hard code the insertion of the data after the 5th character and I wondered if I could do it in a cleaner way. Eventually I came up with this:
<
'ZGF0YSA9ICgKCSc=',
'JywKCSc=',
Line 3,315 ⟶ 3,634:
)
prefix, separator, suffix = (d.decode('base64') for d in data)
print prefix + data[0] + separator + data[1] + separator + data[2] + suffix</
Finally, here's one that echoes the classic "Y combinator" way of constructing quines. First we define a function that takes some code, wraps it in a function and then applies than function to its own source code, then we apply *that* function to its own source code:
<
print "def applyToOwnSourceCode(functionBody):"
print functionBody
print "applyToOwnSourceCode(" + repr(functionBody) + ")"
applyToOwnSourceCode('\tprint "def applyToOwnSourceCode(functionBody):"\n\tprint functionBody\n\tprint "applyToOwnSourceCode(" + repr(functionBody) + ")"')</
=={{header|Quackery}}==
Using the Quackery decompiler, ''build''.
<
{{Out}}
<pre>[ ' [ ' unbuild dup 4 split rot space rot 3 times join echo$ ] unbuild dup 4 split rot space rot 3 times join echo$ ]</pre>
Using self reference, and the decompiler built into ''echo''.
<syntaxhighlight lang
{{Out}}
<pre>[ this echo ]</pre>
Line 3,339 ⟶ 3,658:
=={{header|R}}==
Adapted from the C version in this list.
<
Another version, perhaps more understandable.
<
writeLines(c(paste("src <-", encodeString(src, quote='"')), src))
</syntaxhighlight>
=={{header|Racket}}==
The classic:
<
As a module:
<
(pretty-write
((λ (x) `(module quine racket (pretty-write (,x ',x))))
'(λ (x) `(module quine racket (pretty-write (,x ',x)))))))</
As a module via #lang line:
<
((λ(x)(printf "#lang racket\n(~a\n ~s)" x x))
"(λ(x)(printf \"#lang racket\\n(~a\\n ~s)\" x x))")</
=={{header|Raku}}==
Line 3,366 ⟶ 3,685:
{{trans|Haskell}}
{{works with|Rakudo|#32 "Pisa"}}
<syntaxhighlight lang="raku"
</syntaxhighlight>
Note the terminating newline.
Line 3,373 ⟶ 3,692:
{{works with|Rakudo|2014.04}}
A more compact, but still purely functional, approach:
<syntaxhighlight lang="raku"
</syntaxhighlight>
Note again the terminating newline.
=={{header|REBOL}}==
<
=={{header|REXX}}==
===version 1===
<
{{out|output}}
<pre>
Line 3,390 ⟶ 3,709:
===version 2===
<
do j=1 for sourceline()
say sourceline(j)
end /*j*/</
{{out|output}}
<pre>
Line 3,411 ⟶ 3,730:
''The rest of this conversation moved to [[Talk:Quine|Talk]]''
<
Q = "'"
Line 3,462 ⟶ 3,781:
Say line
End
End x_</
=={{header|Ring}}==
<
see substr(`v = ` + char(34) + `@` + char(34) + nl + `@` ,`@`,v)</
=={{header|RPL}}==
RPL programs are stored in RAM as a specific data structure, and can then be recalled the same way as an ordinary variable.
{{works with|Halcyon Calc|4.2.7}}
≪ 'QUINE' RCL ≫
'QUINE' STO
QUINE
{{out}}
<pre>
1: ≪ 'QUINE' RCL ≫
</pre>
=={{header|Ruby}}==
Found online:
<
A shell session demonstrating that it is valid:
Line 3,479 ⟶ 3,810:
A more readable version of the above example:
<
The <code>%p</code> specifier outputs the result of calling the <code>.inspect</code> method on the argument.
Even shorter (by a few characters):
<
puts <<e*2,'e'
e</
Perhaps the simplest:
<
An implementation that reads and prints the file the code is stored in (which violates some definitions of “quine”):
<syntaxhighlight lang
As the above implementation depends on the code being saved in a file, it doesn’t work in IRB.
=={{header|Rust}}==
Line 3,500 ⟶ 3,830:
A short quine (works with Rust 1.3.0):
<
let x = "fn main() {\n let x = ";
let y = "print!(\"{}{:?};\n let y = {:?};\n {}\", x, x, y, y)\n}\n";
Line 3,506 ⟶ 3,836:
let y = {:?};
{}", x, x, y, y)
}</
Using the method on Wikipedia (0.9-pre-compatible, does not compile on Rust 1.0.0 and newer):
<
{
let q = 34u8;
Line 3,567 ⟶ 3,897:
i+=1;
}
}</
A quine in the shape of a circle:
<
fn main(){let q:&[u8]=&[
32,00,00,00,00,00,00,00,61,27,80,82,
Line 3,614 ⟶ 3,944:
'o; }} print!("\n"); } for n in q.iter() { print!("{}", (if *n==32{10} else
{*n+32}) as char);}print!("\n");} // github.com/kirjavascript
</syntaxhighlight>
From [https://www.reddit.com/r/rust/comments/iocgex/i_made_a_rust_quine/ Reddit] (works in Rust 1.59.0)
<syntaxhighlight lang="rust">fn main() {
macro_rules! script {() => {"fn main() {{\n\tmacro_rules! script {{() => {{{:?}}}}}\n\tprintln!(script!(), script!());\n}}"}}
println!(script!(), script!());
}
</syntaxhighlight>
=={{header|Scala}}==
script:
<
val c = """val q = "\"" * 3
val c = %s%s%s
println(c format (q, c, q))
"""
println(c format (q, c, q))</
application:
<
def main(args: Array[String]) {
val q = "\"" * 3
Line 3,638 ⟶ 3,975:
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):
<
=={{header|Scheme}}==
{{trans|Common Lisp}}
{{Works with|Scheme|R<math>^5</math>RS}}
<
or more "directly" (and classically)
<
which is a long-hand for "cute"
<
=={{header|Seed7}}==
<
const array string: prog is [](
"$ include \"seed7_05.s7i\";",
Line 3,676 ⟶ 4,013:
writeln(literal(prog[12]) <& ");");
for number range 3 to 12 do writeln(prog[number]); end for;
end func;</
Original source: [http://seed7.sourceforge.net/algorith/puzzles.htm#self]
=={{header|Shale}}==
<
=={{header|Sidef}}==
With printf():
<
); printf(s, s);</
With HERE-doc:
<
say(<<e*2, 'e')
e</
=={{header|Smalltalk}}==
(newline included)
<
</syntaxhighlight>
{{works with|GNU Smalltalk}} (newline included)
<
</syntaxhighlight>
=={{header|SmileBASIC}}==
Fairly standard with a format string and character codes.
<
PRINT FORMAT$(Q$,CHR$(34)+Q$+CHR$(34)+CHR$(10))</
=={{header|SNOBOL4}}==
<syntaxhighlight lang="snobol4"> S = ' OUTPUT = " S = 0" S "0"; OUTPUT = REPLACE(S,+"","0");END'
OUTPUT = " S = '" S ""; OUTPUT = REPLACE(S,+"","'");END</syntaxhighlight>
=={{header|SPL}}==
Line 3,710 ⟶ 4,051:
=={{header|SPWN}}==
<
</syntaxhighlight>
=={{header|Standard ML}}==
(newline included)
<
(without newline)
<
=={{header|Swift}}==
Line 3,724 ⟶ 4,065:
{{works with|Swift|2.x}}
(newline included)
<
{{works with|Swift|1.x}}
(newline included)
<
===Version 2===
(newline included)
<
based on the above (passes swift-format):
<syntaxhighlight lang="swift">
let x = ["let x = ", "\nprint(x[0], x, x[1], separator: String())"]
print(x[0], x, x[1], separator: String())
</syntaxhighlight>
=={{header|Tcl}}==
Line 3,736 ⟶ 4,082:
The most straightforward one in the spirit of Quine is probably the one that uses <tt>[join]</tt>, 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 <tt>{} A B</tt> (the first element of which is an empty list):
<
=> 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:
<
=> something{something}</
and re-assembling these parts with a connecting string that is exactly this operation of re-assembly:
<
=> join { {} \{ \} } { join { {} \{ \} } }</
==Turbo {{header|Pascal}}==
The following code was tested in Turbo Pascal 5.5 under DOSbox DOS, and using gpc 4.1. It assumes ASCII.
<
const
Line 3,780 ⟶ 4,126:
writeln(apos, lines[17], apos);
for num := 7 to 17 do writeln(lines[num]);
end.</
=={{header|TXR}}==
A suite for four variations on a theme. The first three use HTML encoding to avoid solving quoting problem. The third stops using <code>&#10;</code> 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.
===="double filtered"====
<
@(bind me "ME")
@(output)
@@(deffilter me ("ME" "@{me :filter me}"))
@{me :filter (me :from_html)}
@(end)</
===="straight up"====
<
@(output)
@@(bind me "@me")
@{me :filter :from_html}
@(end)</
===="code free"====
<
@(output)
@@(bind me (@(rep)"@me" @(last)"@me"@(end)))
Line 3,804 ⟶ 4,150:
@{me :filter :from_html}
@(end)
@(end)</
===="404"====
<
@(deffilter q ("*'" "\"") ("*/" "\\") ("**" "*"))
@(output)
Line 3,813 ⟶ 4,159:
@{me :filter q}
@(end)
@(end)</
=={{header|UNIX Shell}}==
Line 3,820 ⟶ 4,166:
A cheat that reads its own source code, because <tt>$0</tt> is the path to the script:
<
cat < "$0"</
A cheat that reads its own input using the <tt>history</tt> command (only works in an interactive shell):
<
A real quine that doesn't cheat:
<
string=`cat`
printf "$string" "$string"
Line 3,841 ⟶ 4,187:
} <<'END-FORMAT'
%s
END-FORMAT</
=={{header|Unlambda}}==
<syntaxhighlight lang="unlambda">``d`.v`.vv```s``si`k`ki``si`k`d`..`.``.d`.``.c`.s`.``.``.s`.``.``.vv``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`.dv``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.vv``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.vv``s``sc`d`.vv``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`.sv``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`.sv``s``sc`d`.iv``s``sc`d`.`v``s``sc`d`.kv``s``sc`d`.`v``s``sc`d`.kv``s``sc`d`.iv``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`.sv``s``sc`d`.iv``s``sc`d`.`v``s``sc`d`.kv``s``sc`d`.`v``s``sc`d`.dv``s``sc`d`.`v``s``sc`d`..v``s``sc`d`..v``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.dv``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.cv``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.sv``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.sv``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.`v``s``sc`d`.`v``s``sc`d`..v``s``sc`d`.vvv</syntaxhighlight>
=={{header|V}}==
First we need a function that can print a list as a library.
<
with that, the quine reduces to
quine.v:
<
dup puts p</
Using it:
$./v quine.v
<
dup puts p</
{{omit from|Brlcad}}
Line 3,861 ⟶ 4,212:
=={{header|VBA}}==
Inspired bij the Pascal version
<
quote = Chr(34)
comma = Chr(44)
Line 3,892 ⟶ 4,243:
Debug.Print n(i)
Next i
End Sub</
=={{header|Verbexx}}==
Note: The input source code would normally include a Byte Order Mark (BOM) at the start. The output written to the
console does not contain a BOM -- visually, the output looks the same as the input.
<
=={{header|VHDL}}==
<
entity quine is end entity quine;
architecture beh of quine is
Line 3,939 ⟶ 4,290:
wait;
end process;
end architecture beh;</
NOTE: ModelSim escapes each line in the console output with "# ".
=={{header|Visual Basic .NET}}==
Leading newline for appearance.
<
Sub Main()
Dim s = "
Line 3,955 ⟶ 4,306:
Console.WriteLine(s, ChrW(34), s)
End Sub
End Module</
Possibly shortest possible (must have strict and explicit off):
<
Sub Main
s="Module M
Line 3,968 ⟶ 4,319:
Console.Write(s,ChrW(34),s)
End Sub
End Module</
=={{header|WDTE}}==
<
let v => "let str => import 'strings';\nlet v => {q};\nstr.format v v -- io.writeln io.stdout;";
str.format v v -- io.writeln io.stdout;</
=={{header|Whitespace}}==
Line 3,984 ⟶ 4,335:
<syntaxhighlight lang="whitespace">
Line 4,149 ⟶ 4,500:
</syntaxhighlight>
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<
var a = "import $c./fmt$c for Fmt$c$cvar a = $q$cFmt.lprint(a, [34, 34, 10, 10, a, 10])"
Fmt.lprint(a, [34, 34, 10, 10, a, 10])</
=={{header|x86 Assembly}}==
<!-- Used with permission from: https://github.com/calculuswhiz/Assembly-Syntax-Definition/tree/master/test -->
<syntaxhighlight lang="text">
.global _start;_start:mov $p,%rsi;mov $1,%rax;mov $1,%rdi;mov $255,%rdx;syscall;mov $q,%rsi;mov $1,%rax;mov $1,%rdx;syscall;mov $p,%rsi;mov $1,%rax;mov $255,%rdx;syscall;mov $q,%rsi;mov $1,%rax;mov $1,%rdx;syscall;mov $60,%rax;syscall;q:.byte 34;p:.ascii ".global _start;_start:mov $p,%rsi;mov $1,%rax;mov $1,%rdi;mov $255,%rdx;syscall;mov $q,%rsi;mov $1,%rax;mov $1,%rdx;syscall;mov $p,%rsi;mov $1,%rax;mov $255,%rdx;syscall;mov $q,%rsi;mov $1,%rax;mov $1,%rdx;syscall;mov $60,%rax;syscall;q:.byte 34;p:.ascii "
</syntaxhighlight>
Compile with `gcc -nostdlib quine.sx` where quine.sx is the filename. This is for GNU Assembler x64 syntax.
Here is the 32 bit version. Compile this with `gcc -nostdlib quine32.sx -m32`. The m32 flag tells gcc to parse the code as 32-bit.
<syntaxhighlight lang="text">
.global _start;_start:mov $p,%ecx;mov $4,%eax;mov $1,%ebx;mov $264,%edx;int $0x80;mov $q,%ecx;mov $4,%eax;mov $1,%edx;int $0x80;mov $p,%ecx;mov $4,%eax;mov $264,%edx;int $0x80;mov $q,%ecx;mov $4,%eax;mov $1,%edx;int $0x80;mov $1,%eax;int $0x80;q:.byte 34;p:.ascii ".global _start;_start:mov $p,%ecx;mov $4,%eax;mov $1,%ebx;mov $264,%edx;int $0x80;mov $q,%ecx;mov $4,%eax;mov $1,%edx;int $0x80;mov $p,%ecx;mov $4,%eax;mov $264,%edx;int $0x80;mov $q,%ecx;mov $4,%eax;mov $1,%edx;int $0x80;mov $1,%eax;int $0x80;q:.byte 34;p:.ascii "
</syntaxhighlight>
For readability, here's a bash one-liner. Again, quine.sx is the filename. If you have the scat highlighter, you can pipe it to that, too. Of course, this breaks the quine, so don't compile this version expecting it to work.
<
=={{header|zkl}}==
The simplest is the zkl REPL and integers
<
123</
{{trans|Groovy}}
<
{{trans|ALGOL 68}}
<
{{trans|C}}
<
{{trans|Python}}
Create a file with:
<
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:
<
Compiler.Compiler.compileText(quine).__constructor(); out:=vm.regX;
println("\ndiff>>",quine-out,"<<");
}</
<pre>
testQuine(0'|s:="s:=%c%s%c;print(s.fmt(34,s,34));";print(s.fmt(34,s,34));|);
|