Quine

From Rosetta Code

Jump to: navigation, search
Quine a programming puzzle. It lays out a problem which Rosetta Code users are encouraged to solve, using languages and techniques they know. Multiple approaches are not discouraged, so long as the puzzle guidelines are followed. For other Puzzles, see Category:Puzzles.

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

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

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

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

  • Part of the code usually needs to be stored as a string literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
    • Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
    • Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
  • Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be 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.

Contents

[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:='';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] 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] 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] Batch File

@echo off
type %~0

[edit] BASIC

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

This version pulls the 'read' code into a subroutine (of sorts).

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

[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] Brainf***

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

[edit] C

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

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

[edit] Clojure

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

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

((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# :readably t :circle t)

[edit] D

This Quine output 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 ouput 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] E

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

[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] Factor

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

[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] Gema

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

[edit] Go

package main;import"fmt";func main(){x:="package main;import\"fmt\";func main(){x:=%q;fmt.Printf(x,x)}\n";fmt.Printf(x,x)}
 

Note the terminating newline.

[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] 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) "

[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] HQ9+

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

Q

[edit] Icon and Unicon

[edit] Icon

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

[edit] Unicon

The Icon solution also works in Unicon.

[edit] J

Most numbers in J are quines.

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 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] 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]

[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] OCaml

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

Alternative:

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

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

[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 ... ?> tags is automatically echoed in PHP. So any PHP source file which does not contain <?php ... ?> is automatically a quine:

hello

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

[edit] R

Adapted from the C version in this list.

 
(function(){x<-intToUtf8(34);s<-"(function(){x<-intToUtf8(34);s<-%s%s%s;cat(sprintf(s,x,s,x))})()";cat(sprintf(s,x,s,x))})()
 

[edit] REBOL

For what it's worth, I'm making things a bit harder on myself by attempting to reproduce the header. These examples were tested on Windows XP running cygwin using the command:

rebview -vswq quine.r > check.r ; diff quine.r check.r

This ensured that the input and output matched exactly. Note that white-space (not normally an issue because REBOL is free-form) is critical here. Also note that the RosettaCode syntax highlighter forces the all caps REBOL header word to lower case. It's correct in the source.

rebol [
Title: "Quoted Quine"
Date: 13-Dec-2009
Author: oofoe
URL: http://rosettacode.org/wiki/Quine
]

 
q: [x: func [] [
print "REBOL ["
repeat i [Title Date Author URL] [
print rejoin [" " i ": " mold system/script/header/:i]
]
print rejoin ["]" lf]
print rejoin ["q: " mold q lf]
print mold/only q
]
x
]
 
x: func [] [
print "REBOL ["
repeat i [Title Date Author URL] [
print rejoin [" " i ": " mold system/script/header/:i]
]
print rejoin ["]" lf]
print rejoin ["q: " mold q lf]
print mold/only q
]
x
 

This example uses introspection (the source function) to get the program source:

rebol [
Title: "Direct Quine"
Date: 13-Dec-2009
Author: oofoe
URL: http://rosettacode.org/wiki/Quine
]

 
x: func [][
print "REBOL ["
repeat i [Title Date Author URL] [
print rejoin [" " i ": " mold system/script/header/:i]
]
print rejoin ["]" lf]
source x
print 'x
]
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

[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))
}
}

[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] 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] 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
Personal tools
Support