209
\$\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
  • 3
    \$\begingroup\$ Did anybody notice that this is question 69? \$\endgroup\$ – aidan0626 Oct 24 '20 at 22:47

376 Answers 376

1
9
10
11 12 13
2
\$\begingroup\$

ABC, 89 bytes

PUT {"0INa"; "1WRITE 'PUT',a"; "2FORbINa:WRITEb@2/"} INa
WRITE 'PUT',a
FORbINa:WRITEb@2/

Try it online!

This is one of those weird old languages, this one being "originally intended as a good replacement for BASIC". It has a few strange quirks, such as lists are iterated in sorted order, and you can only print newlines using a WRITE. At least the object to string conversion works well, and tokens can be placed right next to each other.

Explanation

PUT {"0INa"; 
     "1WRITE 'PUT',a"; 
     "2FORbINa:WRITEb@2/"}
INa                            Set a to the list of strings
WRITE 'PUT',a                  Print "PUT" and the list
FORbINa:                       Iterate over each string in the list
        WRITE                  Print
             b@2               The string excluding the first character
                /              And a newline

I don't think this ir quite optimal, but I think it's pretty close. You can't have a two line quine, since both lines would have to encode themselves, and I can't think of a way to do a one line quine.

\$\endgroup\$
2
\$\begingroup\$

Acc!!, 270 bytes

936025123570680582070742833115365117904492153588422750562053064415808293823109091171562255866020953926270476903421472061856963432351191541604543106801928196867870451324872393884426634
Count a while a-183 {
Write 48+(_/10^(182-a))%10
}
Count b while _ {
Write _%128
_/128

Try it online!

Explanation

...                          Set the accumulator to a large number
Count a while a-183 {        Loop from 0 to 182
Write 48+(_/10^(182-a))%10   Print the ath digit of the number
}
Count b while _ {            Loop while the accumulator is not zero
Write _%128                  Print the character of the accumulator modulo 128
_/128                        Integer divide the accumulator by 128
\$\endgroup\$
2
\$\begingroup\$

Adapt, 19 bytes

`@96cs+.+`@96cs+.+

Try it online!

Explanation

`@96cs+.+`               Push string "@96cs+.+"
          @96            Push 96
             c           Convert it to the character "`"
              s+         Swap the two and concatenate "`@96cs+.+"
                .+       Duplicate and concatenate "`@96cs+.+`@96cs+.+"
                         Implicitly output
\$\endgroup\$
  • 1
    \$\begingroup\$ Bloody hell, I had no idea Adapt was actually usable, that's super cool! \$\endgroup\$ – caird coinheringaahing Sep 21 '20 at 11:01
2
\$\begingroup\$

Add++ -i, 14 bytes

L,"L,%rd%%"d%

Try it online!

Takes advantage of Python string formatting with the % command. Uses the -i flag to run the function without having to call it.

\$\endgroup\$
  • \$\begingroup\$ @JoKing Corrected, thanks for letting me know! \$\endgroup\$ – caird coinheringaahing Sep 21 '20 at 10:59
  • 1
    \$\begingroup\$ I think your tio link needs to be updated with -i: Try it online! \$\endgroup\$ – Razetime Sep 21 '20 at 11:24
  • \$\begingroup\$ @Razetime So it does, updated \$\endgroup\$ – caird coinheringaahing Sep 21 '20 at 11:25
2
\$\begingroup\$

Labyrinth, 52 bytes

411096280599923751453245172184368156!
_
2/:@
" .
71_

Try it online!

Just beats out the previous Labyrinth quine by one byte, through using the modulo behaviour of ., and an unorthodox divisor.

Explanation:

This uses a similar setup to the other answer, but where that used a divmod of 98, this divides by 172 and modulos by 256. This first saves on the decoder section because the . instruction already moduloes by 256 before printing. But this alone isn't enough, so I started looking for a smaller divisor.

This is possible by brute-forcing the required number through rearranging the source code until it works, and only when the encoded string is really small (in this case 16 bytes). I wrote a Raku script to help brute force these variations of the code, with minor tweaks needed for different layouts.

The code itself is a simple loop

.....!  Push number and print it
.....   Then reverse direction, pushing the number in reverse

_       Enter the loop by
2/`     Integer dividing the initial number by 2
` `
```

``:     Duplicate and print value modulo 256
` .
```

2/`     Integer divide by 172
" `
71_

```@    If the division results in 0, terminate
` `
```

The above code ended up being one of my first attempts at this method, and I only ever found a couple of others that were the same size, this one and this one, both with divisor 172. I'm not sure why this is the magic number.

Some thoughts on further golfing through this method:

  • You can push 0 through ? or { (replacing _)
  • You can push 1 through # or ,` (replacing _1)
  • The wall in the center can be anything that isn't an instruction
  • " can be replaced with ' or some other no-op and can be placed pretty much anywhere in the loop

I'm honestly not sure if this format can be golfed. It seems unlikely that there's a format that supports a smaller divisor than 172, but then again, I'm not sure why 172 was an island of stability in the first place.

\$\endgroup\$
2
\$\begingroup\$

Stax (packed), 43 bytes

å3o╞╝&∞╝7►JôyG♦◄╨s│*T→╢φY'┘ò☼≤⌠░▼e╓Δ█•Aφ/│.

Try it online!

Doesn't work because for some reason latin1 does not accept the C1 control codes.

For this version, the interpreter needs to be forced to output in latin1. Stax Encoding is used. There is an extra trailing newline, but this appears to be accepted here (judging from many other answers).

Explanation:

The unpacked source is:

"r{32-m2+c+95|EVB|EB128+s+"r{32-m2+c+95|EVB|EB128+s+
  • The first half simply pushes the string which is also the second half.

  • The second half builds the full unpacked source out of it and packs it:

    r{32-m2+c+95|EVB|EB128+s+ Second half
    r{32-m                    Reverse and subtract 32 from each character (for packing)
          2+                  Append 2 (double quote - 32)
            c+                Concatenate with self
              95|E            Decode as a base 95 integer (for packing)
                  VB|E        Encode as a base 256 interager (for packing)
                      B128+s+ Add 128 to the first byte (for packing)
                              Implicit output
    

Stax (packed), 103 bytes (50 characters)

üö╖╞╖┘û■Å╣ß$æi7⌐ê↔T)ç¢┤,I_º>┐ó♫Z╪Æ≤◄▐0σ▓☻E.α╬TŶ7É

Run and debug it

Source and output are UTF-8 here, so they are counted as such. Much longer, but UTF-8 is a little nicer to look at.

\$\endgroup\$
2
\$\begingroup\$

Assembly (NASM, 32-bit, Linux), 620 bytes

section .text
mov di,1
mov ebx,1
m:mov esi,a
l:mov ecx,esi
mov edx,1
mov al,[esi]
add ax,di
cmp al,10
jne p
mov ecx,b
mov dx,2
p:mov eax,4
int 128
mov al,[esi]
inc esi
cmp al,96
jne l
dec di
jz m
mov ecx,c
mov dx,3
mov ax,4
int 128
mov ax,1
int 128
section .data
c db 44,57,54
b db 92,110
a db`section .text\nmov di,1\nmov ebx,1\nm:mov esi,a\nl:mov ecx,esi\nmov edx,1\nmov al,[esi]\nadd ax,di\ncmp al,10\njne p\nmov ecx,b\nmov dx,2\np:mov eax,4\nint 128\nmov dl,[esi]\ninc esi\ncmp dl,34\njne l\ndec di\njz m\nmov ecx,c\nmov dx,3\nmov ax,4\nint 128\nmov ax,1\nint 128\nsection .data\nc db 44,57,54\nb db 92,110\na db`,96

-149 bytes by using backqoutes

-26 bytes by simplifying jumps

Try it online!

\$\endgroup\$
2
\$\begingroup\$

TypeScript, 209 197 bytes

type Q<X extends string[]=['`','$',Q<['${X[0]}','${X[1]}','${X[2]}']>]>=`type Q<X extends string[]=['${X[0]}','${X[1]}',Q<['${X[1]}{X[0]}','${X[1]}{X[1]}','${X[1]}{X[2]}']>]>=${X[0]}${X[2]}${X[0]}`

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Swift 5, 202 bytes

While much longer than the shortest Swift submission, this has important aesthetic points for me since it avoids numerical ASCII references as well as any declarations at all, using an anonymous function, resulting in a single-statement solution.

import Foundation;({print($0+"("+String(data:try!JSONEncoder().encode($0),encoding:.utf8)!+")")})("import Foundation;({print($0+\"(\"+String(data:try!JSONEncoder().encode($0),encoding:.utf8)!+\")\")})")
\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to the site! \$\endgroup\$ – Redwolf Programs Nov 13 '20 at 4:38
2
\$\begingroup\$

ed(1), 45 bytes

We have quines for TECO, Vim, and sed, but not the almighty ed?! This travesty shall not stand. (NB: See also, this error quine for ed)

Try it Online!

a
a
,
,t1
$-4s/,/./
,p
Q
.
,t1
$-4s/,/./
,p
Q

Stolen from here. It should be saved as a file quine.ed then run as follows: (TIO seems to work a bit differently)

$ ed < quine.ed
\$\endgroup\$
1
\$\begingroup\$

Groovy:

`s='s=\\\';s[0..1]+s[3]+s[0..1]+s[2]*6+s[3..-1]*2';s[0..1]+s[3]+s[0..1]+s[2]*6+s[3..-1]*`2

Edit

Works in GroovyConsole

\$\endgroup\$
1
\$\begingroup\$

C, 125 84 chars

main(){char*p="main(){char*p=%c%s%c,c='%c',s[256];sprintf(s,p,c,p,c,c);puts(s);}",c='"',s[256];sprintf(s,p,c,p,c,c);puts(s);}

It turns out that my idea was implemented much better:

main(){char*p="main(){char*p=%c%s%c;printf(p,34,p,34,10);}%c";printf(p,34,p,34,10);}
\$\endgroup\$
  • 2
    \$\begingroup\$ You could shave 9 chars off the shorter version by leaving out the trailing newline. \$\endgroup\$ – Ilmari Karonen Feb 3 '12 at 18:55
1
\$\begingroup\$

F♯# - 349 Characters

let s="\\\"\nnlet s=let z a b=s.Substring(a,b)System.Console.WriteLine()z 4 6+z 1 1+z 0 1+z 0 1+z 0 1+z 1 1+z 0 1+z 3 1+z 3 1+z 4 169+z 1 1+z 2 1+z 10 26+z 2 1+z 36 25+z 62 111+z 61 1" 
let z a b=s.Substring(a,b)
System.Console.WriteLine(z 4 6+z 1 1+z 0 1+z 0 1+z 0 1+z 1 1+z 0 1+z 3 1+z 3 1+z 4 169+z 1 1+z 2 1+z 10 26+z 2 1+z 36 25+z 62 111+z 61 1)

My first attempt at a quine - probably an easier (or shorter) way to do it, but not a bad first attempt I don't think

\$\endgroup\$
1
\$\begingroup\$

Tcl, 61 chars

set c {set c {$c};puts [subst -noc \$c]};puts [subst -noc $c]
\$\endgroup\$
1
\$\begingroup\$

Erlang escript 225 164 140

$ escript quine

main(_)->[A|B]=["main(_)->[A|B]=[","],io:put_chars([10,A,34,A,34,44,34,B,34,B,10,10])."],io:put_chars([10,A,34,A,34,44,34,B,34,B,10,10]).

$

Apparently escript has to have at least three lines.

\$\endgroup\$
1
\$\begingroup\$

Go - 583

Just because d;

package main
import "fmt"
func main(){
    a := string(byte(34))
    b := []string{
        "package main",
        "import fmt",
        "func main(){",
        "   a := string(byte(34))",
        "   b := []string{",
        "       ",
        "   }",
        "   for i:=0;i<5;i++{if i != 1{fmt.Println(b[i])}else{fmt.Println(b[i][:7]+a+b[i][7:]+a)}}",
        "   for _,v:=range b{fmt.Println(b[6]+a+v+a+string(','))}",
        "   for i:=7;i<9;i++{fmt.Println(b[i])}",
        "}",
        }
    for i:=0;i<5;i++{if i != 1{fmt.Println(b[i])}else{fmt.Println(b[i][:7]+a+b[i][7:]+a)}}
    for _,v:=range b{fmt.Println(b[5]+a+v+a+string(','))}
    for i:=7;i<11;i++{fmt.Println(b[i])}
}
\$\endgroup\$
  • \$\begingroup\$ this is awesome. \$\endgroup\$ – cat Dec 7 '15 at 14:50
1
\$\begingroup\$

Cobra - 143

class P
    def main
        s='class P{2}   def main{2}     s={1}{0}{1}{2}      Console.write(s,s,39to char,10to char)'
        Console.write(s,s,39to char,10to char)
\$\endgroup\$
1
\$\begingroup\$

Lua, 76 characters

s="s=%c%s%c;print(string.format(s,34,s,34))";print(string.format(s,34,s,34))

Another one with the usual format string technique.

\$\endgroup\$
1
\$\begingroup\$

Julia, 101 characters

s="s=%c%s%c;@printf %c%s%c 34 s 34 34 s 34";@printf "s=%c%s%c;@printf %c%s%c 34 s 34" 34 s 34 34 s 34

It's the usual format string technique, but unfortunately you can't get the format specification string from a variable in Julia, so I have to include it twice in the code, which blows everything up.

\$\endgroup\$
1
\$\begingroup\$

Minkolang 0.9, 10 bytes

This language was made after this challenge, but was not made for it.

"66*2-(O).

Like other 2D languages, the " makes everything between it and the next " a string. 66*2- adds the not-included " and (O). prints everything out and stops.

\$\endgroup\$
1
\$\begingroup\$

Scala, 84 bytes

val d="""
print("val d=\"\"\""+d+"\"\"\""+d)
"""
print("val d=\"\"\""+d+"\"\"\""+d)

Kinda straightforward, but putting it out there for completion.

\$\endgroup\$
1
\$\begingroup\$

Seriously, 2 bytes

1

Pushes the number 1, implicit print with trailing newline. Since this is fairly trivial, here is the smallest non-trivial quine which can contain arbitrary characters (12 bytes):

`è";ƒ"@+`;ƒ

\$\endgroup\$
1
\$\begingroup\$

Python 3 - 58 Characters

Since there is a Python 2 version, I suppose this is acceptable:

x='x={};print(x.format(repr(x)))';print(x.format(repr(x)))
\$\endgroup\$
1
\$\begingroup\$

Java, 190 Characters

class I{public static void main(String[]a){String s="class I{public static void main(String[]a){String s=%c%s%1$c;System.out.print(s.format(s,34,s));}}";System.out.print(s.format(s,34,s));}}
\$\endgroup\$
  • \$\begingroup\$ Since ye olde Java SE 8, you can put static methods (such as main) in interfaces - no public. Also print and format methods can be collapsed into printf. \$\endgroup\$ – Tom Hawtin - tackline Oct 6 '18 at 23:08
1
\$\begingroup\$

Reng v.1.3, 7 bytes

Try it out here!

"rYao;~

" begins a quote string, and reads all of those characters. r reverses the stack, and Y pushes the char code of ". a begins a one-way mirror loop, o outputs the character, and ; mirrors while the stack is truthy. After the zero is met, we advance to ~ and the program ends.

Reng v.2, 8 bytes

{n6G*o}`

This one is a little more interesting. {...} is a code block, and ` executes a code block. n outputs the codeblock already on the stack, 6G* makes a ` character (6*16 = 96), and o output's that.

\$\endgroup\$
1
\$\begingroup\$

Java 2146 2118 bytes

A legitimate attempt at a quine. This was automagically generated. I could have robbed someone elses quining technique but decided against it.

interface q{static void main(String[] args){char[] s={32,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,112,117,98,108,105,99,32,99,108,97,115,115,32,81,117,105,110,101,123,112,117,98,108,105,99,32,115,116,97,116,105,99,32,118,111,105,100,32,109,97,105,110,40,83,116,114,105,110,103,91,93,32,97,114,103,115,41,123,34,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,99,104,97,114,91,93,32,115,61,123,34,41,59,102,111,114,40,105,110,116,32,105,61,48,59,105,60,115,46,108,101,110,103,116,104,45,49,59,105,43,43,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,40,105,110,116,41,115,91,105,93,43,34,44,34,41,59,125,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,40,105,110,116,41,115,91,115,46,108,101,110,103,116,104,45,49,93,43,34,125,59,34,41,59,102,111,114,40,99,104,97,114,32,99,58,32,115,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,99,41,59,125,125,125,32,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,112,117,98,108,105,99,32,99,108,97,115,115,32,81,117,105,110,101,123,112,117,98,108,105,99,32,115,116,97,116,105,99,32,118,111,105,100,32,109,97,105,110,40,83,116,114,105,110,103,91,93,32,97,114,103,115,41,123,34,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,99,104,97,114,91,93,32,115,61,123,34,41,59,102,111,114,40,105,110,116,32,105,61,48,59,105,60,115,46,108,101,110,103,116,104,45,49,59,105,43,43,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,40,105,110,116,41,115,91,105,93,43,34,44,34,41,59,125,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,40,105,110,116,41,115,91,115,46,108,101,110,103,116,104,45,49,93,43,34,125,59,34,41,59,102,111,114,40,99,104,97,114,32,99,58,32,115,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,99,41,59,125,125,125};System.out.print("interface q{static void main(String[] args){");System.out.print("char[] s={");for(int i=0;i<s.length-1;i++){System.out.print((int)s[i]+",");}System.out.print((int)s[s.length-1]+"};");for(char c: s){System.out.print(c);}}}
\$\endgroup\$
1
\$\begingroup\$

Julia, 36 bytes

(~=:@printf "(~=:%s)|>eval" ~)|>eval

Try it online!

Background

Unlike many other languages, Julia's eval doesn't work as expected with a string; for example, eval("print(42)") just returns the string print(42).

To actually executed print(42) with eval;, we have to pass an Expr to eval. This can be done by invoking parse on a string (e.g., eval(parse("print(42)"))) or by passing an Expr literal to eval (e.g., eval(:(print(42))).

Now, while : is a unary operator and :print works fine on its own, :print(42) does not, as it is parsed as (:print)(42), making all parentheses in :(print(42)) mandatory.

However, if we use the macro @printf instead, the parsing rules change, and :@printf(42) works as intended. Also, macro calls also do not require parentheses, and :@printf 42 saves one byte over :(print(42)).

How it works

:@printf "(~=:%s)|>eval" ~ constructs the Expr that calls @printf with the specified format string and additional argument ~. Here, ~ is simply a variable reference; the name is arbitrary.

~=<Expr> saves the generated Expr in the variable ~, which will be accessible when the Expr is evaluated.

Finally, (<assigment>)|>eval calls eval with the return value of the assignment, i.e., the Expr that was assigned to ~.

\$\endgroup\$
1
\$\begingroup\$

Common Lisp - 73 35

Thanks to reader variables written #n= and #n#, with n an integer, Lisp code can be self-referential. Also, the printing functions can emit such reader variables when told to handle circular structures. The WRITE function accepts a :circle parameter for that purpose. It also returns the value being printed, which means that we have to globally set *PRINT-CIRCLE* to T (the initial, standard value is NIL), otherwise the REPL would report a stack-overflow exception when printing that value. Initializing the variable takes a lot of bytes and so the shorter solution is to return another value:

#1=(PROGN (WRITE '#1# :CIRCLE T) T)
\$\endgroup\$
1
\$\begingroup\$

Scala, 56 bytes

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

First defines s as val s=%c%s%c;printf(s,34,s,34), then prints it formatted with double quotes (ascii 34) and itself.

\$\endgroup\$
1
\$\begingroup\$

Dart, 185 bytes

main(){var c=new String.fromCharCode(34);var l=["main(){var c=new String.fromCharCode(34);var l=[","];print(l[0]+c+l[0]+c+','+c+l[1]+c+l[1]);}"];print(l[0]+c+l[0]+c+','+c+l[1]+c+l[1]);}
\$\endgroup\$
1
9
10
11 12 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.