207
\$\begingroup\$

Using your language of choice, golf a quine.

A quine is a non-empty computer program which takes no input and produces a copy of its own source code as its only output.

No cheating -- that means that you can't just read the source file and print it. Also, in many languages, an empty file is also a quine: that isn't considered a legit quine either.

No error quines -- there is already a separate challenge for error quines.

Points for:

  • Smallest code (in bytes)
  • Most obfuscated/obscure solution
  • Using esoteric/obscure languages
  • Successfully using languages that are difficult to golf in

The following Stack Snippet can be used to get a quick view of the current score in each language, and thus to know which languages have existing answers and what sort of target you have to beat:

var QUESTION_ID=69;
var OVERRIDE_USER=98;

var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(index){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}
function commentUrl(index,answers){return"https://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}
function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=!1;comment_page=1;getComments()}})}
function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}
getAnswers();var SCORE_REG=(function(){var headerTag=String.raw `h\d`
var score=String.raw `\-?\d+\.?\d*`
var normalText=String.raw `[^\n<>]*`
var strikethrough=String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>`
var noDigitText=String.raw `[^\n\d<>]*`
var htmlTag=String.raw `<[^\n<>]+>`
return new RegExp(String.raw `<${headerTag}>`+String.raw `\s*([^\n,]*[^\s,]),.*?`+String.raw `(${score})`+String.raw `(?=`+String.raw `${noDigitText}`+String.raw `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+String.raw `</${headerTag}>`+String.raw `)`)})();var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}
function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))
body='<h1>'+c.body.replace(OVERRIDE_REG,'')+'</h1>'});var match=body.match(SCORE_REG);if(match)
valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,})});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)
lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery('<i>'+a.language+'</i>').text().toLowerCase();languages[lang]=languages[lang]||{lang:a.language,user:a.user,size:a.size,link:a.link,uniq:lang}});var langs=[];for(var lang in languages)
if(languages.hasOwnProperty(lang))
langs.push(languages[lang]);langs.sort(function(a,b){if(a.uniq>b.uniq)return 1;if(a.uniq<b.uniq)return-1;return 0});for(var i=0;i<langs.length;++i)
{var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> 

\$\endgroup\$
  • 4
    \$\begingroup\$ Do you not mean, "Golf you a quine for greater good!"? \$\endgroup\$ – Mateen Ulhaq May 3 '11 at 2:49
  • 55
    \$\begingroup\$ @muntoo it's a play on "Learn you a Haskell for Great Good". \$\endgroup\$ – Rafe Kettler May 3 '11 at 2:52

362 Answers 362

1 2 3
4
5
13
7
\$\begingroup\$

APL, 22 bytes

1⌽22⍴11⍴'''1⌽22⍴11⍴'''

This is part of the FinnAPL Idiom Library.

        '''1⌽22⍴11⍴'''  ⍝ The string literal '1⌽22⍴11⍴' (quotes in string)
     11⍴                ⍝ Fill an 11-element array with these characters
                        ⍝ But the string has length 10, so we get '1⌽22⍴11⍴''
  22⍴                   ⍝ Do this again for 22 chars: '1⌽22⍴11⍴'''1⌽22⍴11⍴''
1⌽                      ⍝ Rotate left (puts quote at the back)

Try it on ngn/apl

| improve this answer | |
\$\endgroup\$
7
\$\begingroup\$

Bubblegum, 105 Bytes

Hexdump:

00000000: 0000 00ff ff00 0000 ffff 0000 00ff ff00  ................
00000010: 1400 ebff 0000 00ff ff00 0000 ffff 0000  ................
00000020: 00ff ff00 1400 ebff 4288 21c4 0000 1400  ........B.!.....
00000030: ebff 4288 21c4 0000 1400 ebff 4288 21c4  ..B.!.......B.!.
00000040: 0000 1400 ebff 4288 21c4 0000 1400 ebff  ......B.!.......
00000050: 0000 00ff ff00 0000 ffff 0000 00ff ff03  ................
00000060: 1300 0000 0313 0000 00                   .........

Try it online!

(You might want to verify it offline - since the input is hexdump and the output is raw.)


This relies on the fact that Bubbleugum tries to DEFLATE decode its input first:

...
o = zlib.decompress(code, -zlib.MAX_WBITS)
...

So if we can find a fixpoint in DEFLATE compression, such that x = zlib.decompress(x, -zlib.MAX_WBITS), we are done. But how to do this?

Part I: Generic Compression Quine

Say we have a compression programming 'language' that has two operations:

  • Pn: Print the following n tokens as literals, and skip interpreting them
  • Rn: Print the last n tokens printed

Let's write some simple programs in this to understand how it works.

Input   | Output
P1 P0   | P0
Input   | Output
P1 P0   | P0
P1 P1   | P1
Input   | Output
P1 P0   | P0
R1      | P0
Input          | Output
P4 P0 P0 P0 P0 | P0 P0 P0 P0
R4             | P0 P0 P0 P0

Now the question is: Just with these two instructions, can we create a quine? The answer is yes, thanks to Russ Cox:

Input          | Output
P0             | 
P0             |
P0             |
P4 P0 P0 P0 P4 | P0 P0 P0 P4
R4             | P0 P0 P0 P4
P4 R4 P4 R4 P4 | R4 P4 R4 P4
R4             | R4 P4 R4 P4
P4 P0 P0 P0 P0 | P0 P0 P0 P0

(The tokens are not on the same line, but you can check they're the same).

This gives us hope we might be able to write a DEFLATE quine. But we're not close to done yet, since we have to deal with actual file formats and not made up tokens. Read on!

Part II: Zlib and DEFLATE

Zlib usually appends a 2 byte header and a 4 byte checksum to everything it compresses. The 4 byte checksum would make the creation of a quine much more difficult. But luckily, Bubblegum is designed using to utilize the -zlib.MAX_WBITS flag, which skips the header and the checksum! So we just have a raw DEFLATE stream. How does DEFLATE work? The full thing can be a bit complicated, but luckily we only need to pull out the bits that allow us to have our Pn and Rn building blocks.

Part III: The Pn building block

A deflate stream is made up of a series of blocks. Each block starts with the following:

  • BFINAL: 1 bit, set to 1 if it's the last block.
  • BTYPE: 2 bits. All we need to know is that it's 00 for 'no compression' (ie Pn) and 01 for 'fixed compression' (which turns out to map to Rn).

If we have a 'no compression' block, the rest of the bits in the current byte are set to zero and the next bytes look like:

+---+---+---+---+================================+
|  LEN  | NLEN  |... LEN bytes of literal data...|
+---+---+---+---+================================+

Where LEN is a 2-byte little endian unsigned number of bytes in the literal data, NLEN is the complement of LEN (also unsigned little endian) and we then have N literal bytes. Keeping in mind the first byte is packed from LSB to MSB, this means we can encode the following:

P0 = 00 00 00 ff ff
00000 00 0 | 00000000 | 00000000 | 11111111 | 11111111
^     ^  ^   ^^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^^^
|     |  |   LEN = 0x0000          NLEN = ~LEN = 0xFFFF
|     |  |
|     |  \- BFINAL = 0 (not final block)
|     \---- BTYPE = 00 (no compression)
\---------- 5 bits padding in block
P4 = 00 14 00 eb ff
00000 00 0 | 00010100 | 00000000 | 11101011 | 11111111
^     ^  ^   ^^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^^^
|     |  |   LEN = 0x0014          NLEN = ~LEN = 0xFFEB
|     |  |
|     |  \- BFINAL = 0 (not final block)
|     \---- BTYPE = 00 (no compression)
\---------- 5 bits padding in block

Why is P4 printing 0x14 = 20 bytes, you ask, instead of 4? Well, the previous token 'quine' had the units of 1 byte ~ 1 token, but we don't have that luxury. So instead, we have a fixed length of 5 bytes per token, since this is the minimum size of a print token. So 4 tokens is 20 bytes.

Part IV: The Rn building block

The BTYPE = 01 allows us to make queries of the form REPEAT(n, q):

Starting from q bytes away in the output, print n bytes.

It shouldn't be hard to see that REPEAT(n, n) gives us Rn. But there's a problem, since it turns out that R4 = REPEAT(20, 20) only takes up 3 bytes instead of 5! Since we are assuming all our tokens take up 5 bytes for our quine to work, this is no good. However, we can introduce some redundancy - it turns out if we define R4 = REPEAT(10, 20), REPEAT(10, 20), then we do the same thing but now the instruction takes up 5 bytes total!

The way these blocks are actually encoded as bytes is a little complex. I'll annotate the block, and to fill in the gaps read the RFC. For compressed blocks, the data is turned from bits into bytes LSB to MSB with a couple of exceptions.

P4 = 42 88 21 c4 00
01000 01 0 | 1 00010 00 | 001000 01 | 11 00010 0 | 0000000 0
^     ^  ^   ^  ^    ^    ^      ^    ^   ^    ^   ^       ^
|     |  |  [5] |    |    |      |    [8] |    |   padding [8]
[3]   |  \- [1] [4] [3]  [6]    [5]      [7]  [6]
      \---- [2]

[1]: BFINAL: 0 (not end block)
[2]: BTYPE: 01 (fixed compression) 
[3]: Literal code 264 (print 10 bytes...)
[4]: Distance code 8 (starting from 17 + ... )
[5]: Extra distance code bits ( ... 3 bytes back) (= 20 total)
[6]: Literal code 264 (print 10 bytes...)
[7]: Distance code 8 (starting from 17 + ... )
[8]: Extra distance code bits ( ... 3 bytes back) (= 20 total)

So we've got all our building blocks! P0, P4, R4 right? Are we done?

Part V: The final tweak

Well, not so fast. Remember we had a bit saying which block was the end block? It turns out, for Python at least, that we need to include this on the last block, else it messes up our program. And unfortunately, if we let P*0 be a P0 end block token, the following is NOT a quine:

Input           | Output
P0              | 
P0              |
P0              | 
P4 P0 P0 P0 P4  | P0 P0 P0 P4
R4              | P0 P0 P0 P4
P4 R4 P4 R4 P4  | R4 P4 R4 P4
R4              | R4 P4 R4 P4 <-\
P*4 P0 P0 P0 P0 | P0 P0 P0 P0   |
^                               |
\--------------+----------------+
               |
          Not the same!

However, if we introduce an R*1, we can fix this quite easily:

Input            | Output
P0               | 
P0               |
P0               | 
P4 P0 P0 P0 P4   | P0 P0 P0 P4
R4               | P0 P0 P0 P4
P4 R4 P4 R4 P4   | R4 P4 R4 P4
R4               | R4 P4 R4 P4
P4 P0 P0 P0 R*1  | P0 P0 P0 R*1
R*1              | R*1

It turns out we can encode R*1 = 03 13 00 00 00, so we are done. Use the following Python program to assemble and verify our DEFLATE quine:

import zlib

P0 = b'\x00\x00\x00\xff\xff'
P4 = b'\x00\x14\x00\xeb\xff'
R4 = b'B\x88!\xc4\x00'
R1_F = b'\x03\x13\x00\x00\x00'

comp = b''
comp += P0
comp += P0
comp += P0
comp += P4 + P0 + P0 + P0 + P4
comp += R4
comp += P4 + R4 + P4 + R4 + P4
comp += R4
comp += P4 + P0 + P0 + P0 + R1_F
comp += R1_F

print(zlib.decompress(comp, -zlib.MAX_WBITS) == comp)

Well done! You are now a certified deflate quine expert™.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Nice write-up. Did you mean P4 instead of P4 in the final fixed version of the quine? \$\endgroup\$ – user41805 Sep 1 at 7:18
  • \$\begingroup\$ Yes, thanks @user41805 \$\endgroup\$ – Sisyphus Sep 1 at 7:19
6
\$\begingroup\$

Befunge 98 - 17 11 characters

<@,+1!',k9"

Or if using g is allowed:

Befunge 98 - 12 10

<@,g09,k8"
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Explanation for why using g may not be allowed? \$\endgroup\$ – MD XF Jun 9 '17 at 23:56
  • \$\begingroup\$ @MDXF g is arguably reading the source code. Befunge copies the code to the execution space and g reads the character at the x, y position in the execution space \$\endgroup\$ – Justin Jun 11 '17 at 6:50
6
\$\begingroup\$

Lua, 44 bytes

s="s=%qprint(s:format(s))"print(s:format(s))

Some other comical answers in Lua:

print(arg[0])

...so long as the file is named print(arg[0]) And...

Lua: quine.lua:1: function arguments expected near '.'

...so long as the file is named quine.lua

| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

Julia, 37 bytes

x=:(print("x=:($x);eval(x)"));eval(x)

Now that I know a bit more Julia, I thought I'd revisit this... due to the way printf works in Julia, my previous approach is clearly unsuitable. Instead we make use of (the tip of the iceberg of) Julia's homoiconic features. We define a symbol (that is, a representation of Julia code) which prints the framework of the code, as well as the contents of the variable x (via interpolation) and store that symbol in x. Then we eval that symbol. Much better. :)

| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

Jolf, 4 bytes

Q«Q«
Q    double (string)
 «   begin matched string
  Q« capture that

This transpiles to square(`Q«`) (I accidentally did string doubling in the square function), which evaluates to Q«Q«. Note that q is the quining function in Jolf, not Q ;).

| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

beeswax, 17 13 bytes

Non-competing answer, beeswax is from 2015.

According to the discussion on Does using SMBF count as a cheating quine? the original version at the bottom would count as a cheating quine, so I am wondering if a small change would make this a “proper” quine. The new version is 4 bytes smaller and does not modify its own source code:

`_4~++~+.}1fJ

Explanation:

                lstack     STDOUT

 _             α[0,0,0]•                 create bees α,β, moving right and left
               β[0,0,0]•

` 4            α[0,0,4]•                 push 4 on top of α lstack, switch β to print mode
β α            β[0,0,0]•                 switch β to character output mode

   ~           α[0,4,0]•                 flip α lstack top and 2nd
    +          α[0,4,4]•                 lstack top = top+2nd
     +         α[0,4,8]•                 lstack top = top+2nd
      ~        α[0,8,4]•                 flip lstack top and 2nd
       +       α[0,8,12]•                lstack top = top+2nd
        .      α[0,8,96]•                lstack top = top*2nd
         }     α[0,8,96]•    ` ASCII(96) output char(lstack top) to STDOUT
          1    α[0,8,1]•                 lstack top = 1
           F   α[1,1,1]•                 all lstack = top
            J  α[1,1,1]•                 jump to (x,y) = (lstack top, lstack 2nd)
`_4~++~+.}1FJ  α[1,1,1]•   _4~++~+.}1FJ  output characters to STDOUT

This version should qualify as proper quine if the Befunge-93 program on Thompson’s Quine Page is listed as proper quine. The Befunge quine below does nothing else than read itself character by character, one character during each implicit loop, and output the character to STDOUT.

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

Correct me if I’m wrong.


Old (cheating?) version.

beeswax is a new 2D esolang on a hexagonal grid. It is inspired by bees, honeycombs and by the Hive board game (which uses hexagonal gaming pieces). beeswax programs are able to modify their own code. Thanks to this ability it is not too hard to create a quine. But the program does not read its own source code, as my explanation shows.

The first beeswax quine in existence:

_4~++~+.@1~0@D@1J

Or equivalently:

*4~++~+.@1~0@D@1J

IPs are called bees, the program area is called honeycomb. Every bee owns a local stack called lstack, carrying 3 unsigned 64 bit integer values.

Explanation:

                                             lstack
                                     • marks top of stack

* or _  create bee(same result in this situation)[0,0,0]•
 4      1st lstack value=4                       [0,0,4]•
  ~        flip 1st/2nd lstack values            [0,4,0]•
   ++      1st=1st+2nd, twice                    [0,4,8]•
     ~                                           [0,8,4]•
      +                                          [0,8,12]•
       .         1st=1st*2nd                     [0,8,96]•
        @  flip 1st/3rd lstack values            [96,8,0]• 
         1     1st=1                             [96,8,1]•
          ~                                      [96,1,8]•
           0   1st=0                             [96,1,0]•
            @                                    [0,1,96]•
             D drop 1st at row=2nd,col.=3rd val. [0,1,96]•
       This drops ASCII(96)= ` beyond the left border.

Dropping a value at a coordinate outside the program—in this case at column 0—grows the honeycomb by 1 column to the left. The coordinate system gets reset, so this column becomes the new column 1. So, growing the honeycomb in ‘negative’ direction is only possible in steps of 1. The grown honeycomb is always a rectangle encompassing all code.

This modifies the program to:

`*4~++~+.@1~0@D@1J

continuing...

               @                                  [96,1,0]•
                1                                 [96,1,1]•
                 J jump to row=1st,column=2nd val.[96,1,1]•
`                  switch to character output mode.
 *4~++~+.@1~0@D@1J    the following characters are printed to STDOUT.

GitHub repository of the Julia package of the beeswax interpreter.

| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

Vitsy, 11 9 8 6 Bytes

This programming language was obviously made past the date of release for this question, but I thought I'd post an answer so I can a) get more used to it and b) figure out what else needed to be implemented.

'rd3*Z

The explanation is as follows:

'rd3*Z
'           Start recording as a string.

(wraps around once, capturing all the items)

'           Stop recording as a string. We now have everything recorded but the original ".
 r          Reverse the stack
  b3*       This equates the number 39 = 13*3 (in ASCII, ')
     Z      Output the entire stack.
| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

Fuzzy Octo Guacamole, 4 bytes

_UNK

I am not kidding. Due to a suggestion by @ConorO'Brien, K prints _UNK. The _UN does nothing really, but actually sets the temp var to 0, pushes 0, and pushes None.

The K prints "_UNK", and that is our quine.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I was bored today and decided to quine in FOG. Couldn't figure it out, this is very clever \$\endgroup\$ – Bald Bantha Jun 26 '16 at 19:43
6
\$\begingroup\$

C++, 286 284 236 bytes

Now with extra golf!

#include<iostream>
int main(){char a[]="#include<iostream>%sint main(){char a[]=%s%s%s,b[]=%s%s%s%s,c[]=%s%sn%s,d[]=%s%s%s%s;printf(a,c,b,a,b,b,d,b,b,b,d,b,b,d,d,b);}",b[]="\"",c[]="\n",d[]="\\";printf(a,c,b,a,b,b,d,b,b,b,d,b,b,d,d,b);}

I'm currently learning C++, and thought "Hey, I should make a quine in it to see how much I know!" 40 minutes later, I have this, a full 64 114 bytes shorter than the current one. I compiled it as:

g++ quine.cpp

Output and running:

C:\Users\Conor O'Brien\Documents\Programming\cpp
λ g++ quine.cpp & a
#include<iostream>
int main(){char a[]="#include<iostream>%sint main(){char a[]=%s%s%s,b[]=%s%s%s%s,c[]=%s%sn%s,d[]=%s%s%s%s;printf(a,c,b,a,b,b,d,b,b,b,d,b,b,d,d,b);}",b[]="\"",c[]="\n",d[]="\\";printf(a,c,b,a,b,b,d,b,b,b,d,b,b,d,d,b);}
| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

Cheddar, 56 bytes

var a='var a=%s;print a%@"39+a+@"39';print a%@"39+a+@"39

Try it online!

I felt like trying to make something in Cheddar today, and this is what appeared...

| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

05AB1E, 16 17 bytes

"34çs«DJ"34çs«DJ

With trailing newline.

Try it online!

Explanation:

"34çs«DJ"        # push string
         34ç     # push "
            s«   # swap and concatenate
              DJ # duplicate and concatenate
| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

05AB1E, 19 bytes

Thanks to @Oliver for a correction (trailing newline)

"D34ç.øsJ"D34ç.øsJ

There is a trailing newline.

Try it online!

"D34ç.øsJ"             Push this string
          D            Duplicate
           34          Push 34 (ASCII for double quote mark)
             ç         Convert to char
              .ø       Surround the string with quotes
                s      Swap
                 J     Join. Implicitly display
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Try it online! - codegolf.stackexchange.com/a/161069/59376 - If you want to post this 22 byte answer on this question, you can :). Don't feel I deserve the credit. \$\endgroup\$ – Magic Octopus Urn Apr 2 '18 at 17:47
  • \$\begingroup\$ Probably wasn't available in the old version of 05AB1E yet when you posted your answer, but you can golf 2 bytes by changing sJ (swap, join) to ì (prepend). Try it online. \$\endgroup\$ – Kevin Cruijssen Sep 7 '18 at 12:17
  • \$\begingroup\$ @KevinCruijssen Thanks. I like to keep the language as it was before the challenge (even though that's not required anymore), so I'll leave it as it is \$\endgroup\$ – Luis Mendo Sep 7 '18 at 13:21
  • 1
    \$\begingroup\$ @LuisMendo Fine by me. There are already two shorter 05AB1E answers anyway. Was just stating it as a possibility. :) \$\endgroup\$ – Kevin Cruijssen Sep 7 '18 at 13:24
6
\$\begingroup\$

ಠ_ಠ, 6 bytes

ಠಠ

This used to work back when the interpreter was still buggy but that's fixed now. However, you can try it in the legacy version of the interpreter!

| improve this answer | |
\$\endgroup\$
  • 2
    \$\begingroup\$ It seems that also works in the interpreter provided. Also, ಠ is 3 bytes in UTF-8 \$\endgroup\$ – Conor O'Brien Aug 19 '16 at 21:53
  • \$\begingroup\$ Your link is dead, and can you upload the language source to GitHub so that it can be added to TIO? \$\endgroup\$ – Pavel Jan 30 '17 at 4:28
  • \$\begingroup\$ codepen.io/molarmanful/pen/rxJmqx all the code happens to be there. \$\endgroup\$ – Mama Fun Roll Jan 30 '17 at 17:58
6
\$\begingroup\$

Clojure, 91 bytes

((fn [x] (list x (list (quote quote) x))) (quote (fn [x] (list x (list (quote quote) x)))))
| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

Mathematica, 68 bytes

Print[#<>ToString[#,InputForm]]&@"Print[#<>ToString[#,InputForm]]&@"
| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

Husk, 8 bytes

S+s"S+s"

Try it online!

Husk is a new golfing functional language created by me and Zgarb. It is based on Haskell, but has an intelligent inferencer that can "guess" the intended meaning of functions used in a program based on their possible types.

Explanation

This is a quite simple program, composed by just three functions:

S is the S combinator from SKI (typed) combinator calculus: it takes two functions and a third value as arguments and applies the first function to the value and to the second function applied to that value (in code: S f g x = f x (g x)).

This gives us +"S+s"(s"S+s"). s stands for show, the Haskell function to convert something to a string: if show is applied to a string, special characters in the string are escaped and the whole string is wrapped in quotes.

We get then +"S+s""\"S+s\"". Here, + is string concatenation; it could also be numeric addition, but types wouldn't match so the other meaning is chosen by the inferencer.

Our result is then "S+s\"S+s\"", which is a string that gets printed simply as S+s"S+s".

| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

C (gcc), 78 70 66 62 bytes

Minus 4 bytes thanks to MD XF (reusing first argument of printf)!

There are a few unprintables in this answer, replaced with ?.

main(){printf("main(){printf(%c%s%1$c,34,'@??');}",34,'@??');}

Here's an xxd:

00000000: 6d61 696e 2829 7b70 7269 6e74 6628 226d  main(){printf("m
00000010: 6169 6e28 297b 7072 696e 7466 2825 6325  ain(){printf(%c%
00000020: 7325 3124 632c 3334 2c27 4005 9027 293b  s%1$c,34,'@..');
00000030: 7d22 2c33 342c 2740 0590 2729 3b7d       }",34,'@..');}

Here's a bash script to generate and execute the program.

62 bytes, part 2

Here's a version that I have tested on my windows machine on gcc (ANSI encoded):

main(){printf("main(){printf(%c%s%1$c,34,'@@0');}",34,'@@0');}

Here's the output:

C:\Users\Conor O'Brien\Documents
λ xxd test.c
00000000: 6d61 696e 2829 7b70 7269 6e74 6628 226d  main(){printf("m
00000010: 6169 6e28 297b 7072 696e 7466 2825 6325  ain(){printf(%c%
00000020: 7325 3124 632c 3334 2c27 4040 3027 293b  s%1$c,34,'@@0');
00000030: 7d22 2c33 342c 2740 4030 2729 3b7d       }",34,'@@0');}

C:\Users\Conor O'Brien\Documents
λ cat test.c
main(){printf("main(){printf(%c%s%1$c,34,'@@0');}",34,'@@0');}
C:\Users\Conor O'Brien\Documents
λ wc test.c -c
62 test.c

C:\Users\Conor O'Brien\Documents
λ gcc test.c -o test
test.c:1:1: warning: return type defaults to 'int' [-Wimplicit-int]
 main(){printf("main(){printf(%c%s%1$c,34,'@@0');}",34,'@@0');}
 ^
test.c: In function 'main':
test.c:1:8: warning: implicit declaration of function 'printf' [-Wimplicit-function-declaration]
 main(){printf("main(){printf(%c%s%1$c,34,'@@0');}",34,'@@0');}
        ^
test.c:1:8: warning: incompatible implicit declaration of built-in function 'printf'
test.c:1:8: note: include '<stdio.h>' or provide a declaration of 'printf'
test.c:1:55: warning: multi-character character constant [-Wmultichar]
 main(){printf("main(){printf(%c%s%1$c,34,'@@0');}",34,'@@0');}
                                                       ^

C:\Users\Conor O'Brien\Documents
λ test
main(){printf("main(){printf(%c%s%1$c,34,'@@0');}$c,34,'@@0');}
C:\Users\Conor O'Brien\Documents
λ

66 bytes

main(){printf("main(){printf(%c%s%1$c,34,4195728);}",34,4195728);}

I have no idea why this works, 100% honest here. But dang, is it short. Only 6 bytes longer than the current best.

Try it online!

70 bytes

main(){printf("main(){printf(%c%s%c,34,4195728,34);}",34,4195728,34);}

Try it online!

78 bytes

main(){printf("main(){printf(%c%s%c,34,%c%c+8,34,34,34);}",34,""+8,34,34,34);}

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 66 bytes \$\endgroup\$ – MD XF Jul 25 '17 at 4:46
  • \$\begingroup\$ It works because printf is very weakly typed, so your integer constant gets interpreted as the actual pointer address of the format string constant. Very implementation-dependent, I tried it on a different Linux machine and even there I needed to adjust the numbers. \$\endgroup\$ – Ørjan Johansen Jul 25 '17 at 6:21
  • \$\begingroup\$ @ØrjanJohansen Thanks, I figured it had something to do with addressing. \$\endgroup\$ – Conor O'Brien Jul 25 '17 at 16:39
  • \$\begingroup\$ Aha, you found out how to get it down to 62 non-locally! \$\endgroup\$ – MD XF Jul 25 '17 at 17:03
  • \$\begingroup\$ @MDXF Yes I did :> \$\endgroup\$ – Conor O'Brien Jul 25 '17 at 17:15
6
\$\begingroup\$

JavaScript (ES6), 28 26 bytes

Run this code in Firefox 34+ (currently in Aurora)'s Web console

(f=x=>alert`(f=${f})()`)()
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ @rafe-ketler - I believe that this is the shortest ES6 version now :) \$\endgroup\$ – Optimizer Sep 13 '14 at 22:50
  • \$\begingroup\$ Hmm... doesn't work in the latest version of Firefox (it outputs (f=,)()), I believe you'd have to put the template in parentheses. \$\endgroup\$ – ETHproductions Aug 11 '17 at 19:34
6
\$\begingroup\$

Implicit, 20 bytes

«@171%@187»@171%@187

This didn't work in older versions of Implicit.

Try it online!

How it works

«@171%@187»           Push the string '@171%@187' on the stack. Let's call it s.
           @171       Print '«' (char code 171), without pushing it on the stack.
               %      Print s without popping it from the stack.
                @187  Print '»' (char code 171), without pushing it on the stack.
                      (implicit) Print the top of the stack: s.

Implicit, 26 bytes

«:171,::187,"»:171,::187,"

Try it online!

How it works

«:171,::187,"»              Push the string ':171,::187,"' on the stack.
                            Let's call it s.
              :171          Push 171 (code point of «).
                  ,         Swap s and 171.
                   :        Push a copy of s.
                    :187    Push 187 (code point of »).
                        ,   Swap the copy of s and ».
                         "  Combine the entire stack into a string.
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ +1, got the same solution not long after. \$\endgroup\$ – ATaco Sep 22 '17 at 2:31
6
\$\begingroup\$

Bash, 48 bytes

Q=\';q='echo "Q=\\$Q;q=$Q$q$Q;eval \$q"';eval $q

Try it online!

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Hm the leaderboard gives a shorter one, although that one uses sed while you are only using builtins. \$\endgroup\$ – Ørjan Johansen Feb 7 '18 at 17:14
  • \$\begingroup\$ After a search, I think this is currently the shortest with only builtins and a "normal" quine construction. \$\endgroup\$ – Ørjan Johansen Feb 7 '18 at 17:28
  • \$\begingroup\$ Thanks for taking a look @ØrjanJohansen! I'd like to differentiate this from the other solutions, but I don't know if I should change this title or the ones that use core utils... I'm happy with just coming up with the program to be honest! 😊 \$\endgroup\$ – Dom Hastings Feb 7 '18 at 19:22
  • \$\begingroup\$ Bash + coreutils seems to be fairly common, so I'd suggest to edit the header of the other answer. \$\endgroup\$ – Laikoni Feb 10 '18 at 12:07
6
\$\begingroup\$

Bash + coreutils, 18 bytes

sed p<<a
sed p<<a

It requires a trailing newline and generates a warning.

Posted the Zsh version in a separate answer to fix the leaderboard.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Interesting use of the here-document, but one has to end the text stream manually with Ctrl+D to make the script run, hence the warning. To have it run automatically, an extra line with just a on it is required, but that would break the quine. \$\endgroup\$ – seshoumara Sep 7 '16 at 8:53
  • \$\begingroup\$ @seshoumara Just put it in a script file and use bash filename to run. \$\endgroup\$ – jimmy23013 Sep 7 '16 at 9:22
  • \$\begingroup\$ Aah, you give an EOF this way, nice. Maybe add that to description. I run it with bash script 2> /dev/null to get rid of STDERR. \$\endgroup\$ – seshoumara Sep 7 '16 at 9:31
  • \$\begingroup\$ In dash and zsh, you don't need the trailing newline and it won't generate a warning. \$\endgroup\$ – Dennis Sep 8 '16 at 15:49
  • 1
    \$\begingroup\$ @seshoumara Answers on this site should be functions or complete programs, and not code snippets in a REPL, by default. \$\endgroup\$ – jimmy23013 Sep 8 '16 at 21:12
6
\$\begingroup\$

APL (Dyalog Unicode), 18 bytesSBCS

@ngn's updated version of the classic APL quine, using a modern operator to save four bytes.

1⌽,⍨9⍴'''1⌽,⍨9⍴'''

Try APL!

'''1⌽,⍨9⍴''' the characters '1⌽,⍨9⍴'

9⍴ cyclically reshape to shape 9; '1⌽,⍨9⍴''

,⍨ concatenation selfie; '1⌽,⍨9⍴'''1⌽,⍨9⍴''

1⌽ cyclically rotate one character to the left; 1⌽,⍨9⍴'''1⌽,⍨9⍴'''

| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

05AB1E, 13 bytes

2096239D20BJ

Try it online!

Beats all the string-based 05AB1E quines.

Explanation:

2096239            # integer literal
       D           # duplicate
        20B        # convert the copy to base 20, yielding "D20BJ"
           J       # join with the original
| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

Whitespace, 338 bytes

-3 bytes thanks to Dorian pointing out a mistake

   	 		   		      	    	  			    	     		 	 	 	 		  				  	      	     		  	   				     			 		   						  	 		 		  					    			  					    	 	  				       				 	    	 	  	   		 	 				 	  	   		 	  					 	 					 
   	 

 	 

 	 

 	
   	
	   
  
 	  	
 	  	
	 	  
 
	 	
 	  	

 	
	 		 
 
	 	
   	   
	   	
  
	

  	
 


   
   	     
	
  
	

Try it online!

Not really much to see, but the code is there. This terminates with a 'Can't return from subroutine' error, which is only about 10 or so bytes extra to remove. Translated from whitespace, the tokens are:

push 213928514417226051472880134683878051755207959239232598316788086
push 2
call PRINT_SPACE
call PRINT_SPACE
call DIV_MOD_PRINT
push 1
add

label DIV_MOD_PRINT
    copy 2nd item in stack
    copy 2nd item in stack
    div
    jump if zero to POP_AND_PRINT_SPACE
    copy 2nd item in stack
    call DIV_MOD_PRINT
    mod
    dupe
    jump if zero to POP_AND_PRINT_SPACE
    push 8
    add
    print as character
    return

label POP_AND_PRINT_SPACE
    pop
    label PRINT_SPACE
        push 32
        print as character
        return

This starts off by pushing a rather large number in binary spaces and tabs. This number represents the rest of the program in trinary (since Whitespace has 3 valid characters), with space being 0, tab being 1 and newline as 2.

The main part of this code is the DIV_MOD_PRINT function, which assumes that the large number and the divisor is on top of the stack. This makes a copy of the two elements, then divides the number by the divisor and recursively calls the function again, returning once the result of the division is zero. On the tail call, this takes the two copied elements and gets the remainder after division. Then it maps it to the representation above.

This function is reused twice on the large number we pushed at the beginning, once with the divisor 2 to print the number itself in tabs and spaces, and again with 3 to print the rest of the program.

There are a couple of caveats; for example, we can't represent leading spaces with leading zeroes, so we with have to print those manually before we call the function the first time. This is partially mitigated by the fact that we stop the recursion by jumping to the POP_AND_PRINT_SPACE label, which means that we print a leading space anyway.

However, that causes one of the modulo pairs not to be evaluated, therefore the last character represented is not printed. This is actually a good thing, for a couple of reasons. First, since the binary number representation is terminated with a newline which would have had to have been printed (since we print a leading space), instead, if we ensure the last character of the binary number is a space, the newline is now the first character of the rest of the program. We can make the last character a space easily, since we aren't printing the last character of the program by adding a space or tab when encoding the number literal.

For reference, my encoding program, my commented program, and I used WhiteLips to debug the program.

| improve this answer | |
\$\endgroup\$
6
\$\begingroup\$

Pyth, 9 8 bytes

p+N
"p+N

Saved one more byte by using the newline operator

(Also I made this ages ago but forgot to edit this so yeah)

Try it online!

| improve this answer | |
\$\endgroup\$
5
\$\begingroup\$

C++ (350)

#include<iostream>
#include<fstream>
int main(){std::ofstream f;f.open("f.cpp");
#define B(x)x;f<<("B(" #x ")");
#define A(x)f<<("A(" #x ")");x;
B(f<<("#include<iostream>\n#include<fstream>\nint main(){std::ofstream f;f.open(\"f.cpp\");\n#define B(x)x;f<<(\"B(\" #x \")\");\n#define A(x)f<<(\"A(\" #x \")\");x;\n"))A(f<<("f.close();}\n"))f.close();}

Modified version of this.

Makes use of the C++ preprocessor.

| improve this answer | |
\$\endgroup\$
5
\$\begingroup\$

Commodore Basic, 54 41 characters

1R─A$:?A$C|(34)A$:D♠"1R─A$:?A$C|(34)A$:D♠

Based on DLosc's QBasic quine, but modified to take advantage of Commodore Basic's shortcut forms. In particular, the shorter version of CHR$(34) makes using it directly for quotation marks more efficient than defining it as a variable.

As usual, I've made substitutions for PETSCII characters that don't appear in Unicode: = SHIFT+A, = SHIFT+E, | = SHIFT+H.

Edit: You know what? If a string literal ends at the end of a line, the Commodore Basic interpreter will let you leave out the trailing quotation mark. Golfed off 13 characters.

Alternatively, if you want to skirt the spirit of the rules,

1 LIST

LIST is an instruction that prints the current program's code. It is intended for use in immediate mode, but like all immediate-mode commands, it can be used in a program (eg. 1 NEW is a self-deleting program). Nothing shorter is possible: dropped spaces or abbreviated forms get expanded by the interpreter and displayed at full length.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Its not opening the file and reading its input, but I do agree that this is a bit cheaty. \$\endgroup\$ – yyny Feb 26 '15 at 21:34
  • \$\begingroup\$ @MartinBüttner, is the new version better? \$\endgroup\$ – Mark Feb 27 '15 at 7:53
  • \$\begingroup\$ @Mark I can't read that, but it looks like a quine to me. ;) \$\endgroup\$ – Martin Ender Feb 27 '15 at 9:06
  • \$\begingroup\$ @YoYoYonnY It reads its source, tho. \$\endgroup\$ – Erik the Outgolfer Jun 28 '16 at 21:54
5
\$\begingroup\$

Arcyóu, 1 byte

Q

The interpreter evaluates undefined symbols as strings, and the result of the last expression evaluated is automatically printed at the end of the program. What's interesting is that any undefined identifier can be used; I_am_a_quine! is also a quine.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ This does not satisfy our rules for proper quines as the Q only encodes itself (as does any character in I_am_a_quine!). \$\endgroup\$ – Martin Ender May 23 '17 at 15:35
  • \$\begingroup\$ Agreed @MartinEnder, but the challenge does not specify proper quines. \$\endgroup\$ – jqblz Jun 2 '17 at 21:30
5
\$\begingroup\$

Brachylog (2), 26 bytes, language postdates challenge

"ạ~bAh34∧A~ạj"ạ~bAh34∧A~ạj

Try it online!

A function that returns its own source code. (This can be made into a 28-byte full program by adding w after each occurrence of j.)

Explanation

"ạ~bAh34∧A~ạj"ạ~bAh34∧A~ạj
"ạ~bAh34∧A~ạj"               String literal
              ạ              Convert to list of character codes
               ~b            Prepend an element
                  h34          so that the first element is 34
                 A   ∧A        but work with the entire list
                       ~ạ    Convert to string
                         j   Concatenate the string to itself
| improve this answer | |
\$\endgroup\$
1 2 3
4
5
13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.