# Write a Polyquine

A polyquine is both quine and polyglot.1 You are to write a quine which is valid in at least two different languages. This is code golf, so the shortest answer (in bytes) wins.

1 I made that up. Or rather, Geobits did. Apparently, he wasn't the first one either, though.

### Rules for Quines

Only true quines are accepted. That is, you need to print the entire source code verbatim to STDOUT, without:

• relying on a REPL environment which just simply evaluates and prints every expression you feed it.
• relying on language features which just print out the source in certain cases.
• using error messages or STDERR to write all or part of the quine. (You may write things to STDERR or produce warnings/non-fatal errors as long as STDOUT is a valid quine and the error messages are not part of it.)

Furthermore, your code must contain a string literal.

### Rules for Polyglots

The two languages used must be distinctly different. In particular:

• They must not be different versions of the same language (e.g. Python 2 vs. Python 3).
• They must not be different dialects of the same language (e.g. Pascal vs. Delphi).
• One language may not be a subset of the other one (e.g. C vs. C++).
• "your code must contain a string literal" Even in languages that have no string literals, such as Brainfuck? – Peter Olson Sep 8 '14 at 19:35
• @PeterOlson The purpose of the rule is avoid a few loopholes in the golfing-specific languages (e.g. this one). As I can't anticipate what removing or weakening the rule would lead to (and as I'm not a fan of changing rules unless absolutely necessary), I'm sorry, but BF submissions won't be valid for the purpose of this challenge. If it's any consolation, a BF submission would likely not be competitive anyway. ;) – Martin Ender Sep 8 '14 at 20:31
• "he wasn't the first one either" links to where? – Erik the Outgolfer May 23 '17 at 16:39
• C is not really a subset of C++. – MD XF May 23 '17 at 18:35
• Do two different Brainf**k-based languages count as the same language, such as Brainf**k and MOO? – MD XF Oct 31 '17 at 1:11

# CJam/GolfScript, 34 bytes

{"__X.0#@@?LL
;~"N}__X.0#@@?LL
;~


The byte count contains a trailing linefeed, since the program wouldn't be a quine without it.

While CJam and GolfScript are very similar in some aspects, there are a lot of differences. To make this an "honest" polyquine, I decided to rely on the differences as much as possible. Except for the block and string syntax (which the languages share with oh so many others), no part of the code achieves exactly the same in both languages.

The online GolfScript interpreter has a bug; this program works only with the official interpreter.

### Example run

$cat polyquine {"__X.0#@@?LL ;~"N}__X.0#@@?LL ;~$ md5sum polyquine <(cjam polyquine) <(golfscript polyquine)
e2f1f3cd68abbbceec58080513f98d9a  polyquine
e2f1f3cd68abbbceec58080513f98d9a  /dev/fd/63
e2f1f3cd68abbbceec58080513f98d9a  /dev/fd/62


### How it works (CJam)

" Push that block.                                                                        ";

{"__X.0#@@?LL
;~"N}

" Push two copies of the block, 1 (computed as 1**0) and rotate the block copies on top.  ";

__X.0#@@

" If 1 is truthy (oh, the uncertainty), execute the first copy; else, execute the second.
Evaluating the block pushes the string it contains; N pushes a linefeed.                ";

?

" Push two empty arrays.                                                                  ";

LL

" Discard one empty array and dump the second.                                            ";

;~

" (implicit) Print all items on the stack.                                                ";


### How it works (GolfScript)

# Push that block.

{"__X.0#@@?LL
;~"N}

# Push a copy of the block; _ and X are noops, # initiates an inline comment.

__X.0#@@?LL

# Discard the 0 and execute the copy of the block.
# Evaluating the block pushes the string it contains; N is a noop.

;~

# (implicit) Print all items on the stack, followed by a linefeed.


# CJam/GolfScript, 12 bytes

{"0$~"N}0$~


Cheaty solution that avoids the languages' differences as much as possible.

Try it online:

### How it works (CJam)

 "0$~" " Push that string. "; N " Push a linefeed. "; { }0$~  " Push a copy of the block and execute it.                                   ";
" (implicit) Print the stack.                                                ";


### How it works (GolfScript)

 "0$~" # Push that string. N # Undefined token (noop). { }0$~  # Push a copy of the block and execute it.
# (implicit) Print the stack, followed by a linefeed.


## C#/Java, 746 bytes

I use the property that chars in Java can be written as identical unicode sequences. If we have A instruction for C# compiler and B instruction for Java, we can use the following code fragment:

//\u000A\u002F\u002A
A//\u002A\u002FB


It will be "recognized" by the following way with C#:

//\u000A\u002F\u002A
A//\u002A\u002FB


And by the following way by Java:

//
/*
A//*/B


Because of \u000A is line break, \u002F is / and \u002A is * in Java.

So the final polyglot-quine is:

//\u000A\u002F\u002A
using System;//\u002A\u002F
class Program{public static void//\u000A\u002F\u002A
Main//\u002A\u002Fmain
$perl quine.pl  The php code is actually running (not just printing itself). # Bash/Ruby, 104 82 "tee#";puts <<a*2+'a'#" -<<'a';echo a "tee#";puts <<a*2+'a'#" -<<'a';echo a a  Older version: "alias" "puts=f()(tee -;echo a);f" puts <<a *2+"a" "alias" "puts=f()(tee -;echo a);f" puts <<a *2+"a" a  # Bash/Ruby, 128 without undefined behavior "alias" 'puts=f()(a=cat;echo "$a
$a a");f' puts <<'a' *2+"a" "alias" 'puts=f()(a=cat;echo "$a
$a a");f' puts <<'a' *2+"a" a  • wow, I don't even understand how the Ruby code works :D – Martin Ender Sep 10 '14 at 18:51 • @MartinBüttner <<a in Ruby works just like Bash, but returns a string. I didn't write a Ruby program before. I just found a random language with this feature. – jimmy23013 Sep 10 '14 at 19:00 • I don't know how it works in bash either :P – Martin Ender Sep 10 '14 at 19:02 • @MartinBüttner It is called heredoc. <<word returns a string closed by a line with a single word. – jimmy23013 Sep 10 '14 at 19:06 # reticular/befunge-98, 28 bytes [noncompeting] <@,+1!',k- ';';Oc'43'q@$;!0"


Anything in between ;s in befunge is ignored, and ! skips into the segment between ;s for reticular. Thus, reticular sees:

<@,+1!',k- ';';Oc'43'q@$;!0" < move left " capture string 0 push zero ;! skip ; (end program)$      drop zero
q@       reverse TOS
'43'         push 34 (")
c             convert to char
O              output all
;               end program


Befunge sees:

<@,+1!',k- ';';Oc'43'q@$;!0" < move left " capture string !0 push 1 ; ; skip this - ';' push 27 ,k output top 27 chars +1!' push 34 (") , output " @ end program  ## Ruby/Mathematica, 225 bytes Here is my own very beatable polyquine (which serves as example and proof-of-concept): s="s=%p;puts s%%s;#Print[StringReplace[s,{(f=FromCharacterCode)@{37,112}->ToString@InputForm@s,f@{37,37}->f@37}]]&@1";puts s%s;#Print[StringReplace[s,{(f=FromCharacterCode)@{37,112}->ToString@InputForm@s,f@{37,37}->f@37}]]&@1  The first part is based on this Ruby quine and is basically: s="s=%p;puts s%%s;#MathematicaCode";puts s%s;#MathematicaCode  The string assignment is exactly the same in Mathematica. The puts s%s is interpreted as a product of 4 symbols: puts, the string s, % (the last REPL result or Out[0] if it's the first expression you evaluate) and another s. That's of course completely meaningless, but Mathematica doesn't care and ; suppresses any output, so this is just processed silently. Then # makes the rest of the line a comment for Ruby while Mathematica continues. As for the Mathematica code, the largest part of it, is to simulate Ruby's format string processing without using any string literals. FromCharacterCode@{37,112} is %p and FromCharacterCode@{37,112} is %%. The former gets replaced with the string itself, (where InputForm adds the quotes) the latter with a single %. The result is Printed. The final catch is how to deal with that # at the front. This is Mathematica's symbol for the first argument of a pure (anonymous) function. So what we do is we make all of that a pure function by appending & and immediately invoke the function with argument 1. Prepending a 1 to a function call "multiplies" the result with 1, which Mathematica again just swallows regardless of what kind of thing is returned by the function. ## ><> and CJam, 165 bytes "~~~~~~~~~~~~~~~~~~~~~~~r00gol?!v93*0.Hi ' < .1*5av!?log10oar~~~r '"{""\"_~e#.21 <.2+4*96;!?log10oa"}_~e#.21 <.2+4*96;!?log10oa  To CJam, the program starts with a multi-line string literal. This is escaped with , and then it uses the standard quine to print the quine code, as well as a trailing comment. To ><>, the first " starts a string literal that goes through the entire first row, pushing every character to the stack. After that, the trailing spaces (created due to the input being padded) are deleted, and then the stack is reversed. Every character in the stack (i.e. the entire first row) is output, and then it moves down to the second row. The second row essentially does the same thing, except that it's in the opposite direction, so you don't need to reverse the stack. (I do anyway, because I have to delete the trailing spaces.) Finally, it moves on to the third line. The only major difference is that you must skip the CJam block, which is done using . The single quote captures the entire line (again, backwards), and then it is output. # C/PHP, 266304300282241 203 + 10 bytes //<?php function main($a){printf($a="%c//<?php%cfunction main(%ca){printf(%ca=%c%s%c,13,10,36,36,34,%ca,34,36,10,10,10);}%c#if 0%cmain();%c#endif",13,10,36,36,34,$a,34,36,10,10,10);}
#if 0
main();
#endif


+10 bytes because compiling in C requires the GCC compiler flag -Dfunction=.

How it works (in PHP):

• The PHP interpreter simply prints everything before the <?php as HTML. // is not a comment in HTML, so it's simply printed.
• main is declared as a function with a variable a.
• printf prints a carriage return (to override the already-printed //) and then the source code, using a standard C/PHP quining method.
• #if 0 is ignored by PHP.
• main($a) initializes an empty variable a. (Previously used error_reporting(0) to ignore errors caused by calling main()) • #endif is also ignored by PHP. How it works (in C): • //<?php is a single-line comment, so it is ignored. • The function keyword is ignored due to the command-line compiler argument -Dfunction=. • GCC and Clang don't care if variables start with or contain $. (This saved the day.)
• printf prints a carriage return (useless in this instance) and then the source code, using a standard C/PHP quining method.
• #if 0 ignores everything until the endif, so PHP can call main.
• #endif ends the "ignore me" block.

# Wumpus/><>/Befunge-98 28 bytes

"]#34[~#28&o@,k+deg0 #o#!g00


## How it Works:

### Wumpus Code:

  " Start string literal
Bounce off end of line and come back
" End string literal
] Push top of stack to bottom
#34 Push double quote
[~ Get bottom of stack and swap it with the double quote
#28 Push 28
&o@ Print the top 28 items on stack and terminate program


### ><> Code:

  " Start string literal
Wrap when it reaches the end of the line
" End string literal
]# Clear stack and reflect
" Wrapping string literal again, but backwards
g00 Get the character from cell 0 (")
#o#! Skip into the printing loop
Exit with an error


### Befunge-98 Code:

  " Wrapping string literal
] Turn right
] Turn right again, going West
" Wrapping string literal going West
!g00 Get double quote and invert it
#o# Skip over the o instruction
g0   Get double quote
+de Push 27
@,k    Print 27+1 items from the stack and terminate program.


## Perl 5/Ruby/JavaScript (Node.js)/Bash/Python 2/PHP, 1031 bytes

s=1//2;_=r'''<?#/.__id__;s=+0;#';read -d '' q<<'';s=\';Q='echo s=1//2\;_=r$s$s$s\<\?\#/.__id__\;s=+0\;#$s\;read -d $s$s q\<\<$s$s\;s=\$s\;Q=sQs\;eval\$Q;echo $q';eval$Q
$_='eval("0"?0?"def strtr(s,f,t);s.tr(f,t) end;class String;def chr(n);self+n.chr end;end":"$u=strtr=(s,f,t)=>[...f].reduce((s,a,i)=>s.replace(RegExp(a,g),t[i]),s);printf=console.log;(S=String).prototype.chr=function(n){return this+S.fromCharCode(n)}":[]&&"sub strtr{eval q(q(X)=~y/X/X/r)=~s/X/shift/ger}");printf(strtr("%s<?#/.__id__;s=+0;#j;read -d jj q<<jj;s=zj;Q=jecho s=1//2z;_=rksksksz<z?z#/.__id__z;s=+0z;#ksz;read -d ksks qz<z<ksksz;s=zzksz;Q=kskQksz;evalz zkQ;echo kqj;eval kQwk_=j%sj;eval(k_);//;#jjj;f=jjjs=1//2;_=r%%s%%s%%s;f=%%s%%s%%s;q=_[18]*3;print f%%%%(q,_,q,q,f,q)jjj;q=_[18]*3;print f%%(q,_,q,q,f,q)%s","jkwz","".chr(39).chr(36).chr(10).chr(92).chr(92)),[]&&"s=1//2;_=r".chr(39).chr(39).chr(39),$_,$u?"":"".chr(10));';eval($_);//;#''';f='''s=1//2;_=r%s%s%s;f=%s%s%s;q=_[18]*3;print f%%(q,_,q,q,f,q)''';q=_[18]*3;print f%(q,_,q,q,f,q)  Verify it online! Based on my updates to this answer, I thought I'd try and optimise out the code that prints a different permutation, but ended up adding in Bash, which added a load more bytes anyway. Whilst this is more optimised than my first attempt (saved over 300 bytes) I'm sure it can still be golfed further. ## Alternative Perl 5/Ruby/JavaScript (Node.js)/Bash/Python 2/PHP, 1040 bytes s=1//2;_=r'''<?#/.__id__;s=+0;#';read -d '' q<<'';s=\';Q='echo s=1//2\;_=r$s$s$s\<\?\#/.__id__\;s=+0\;#$s\;read -d$s$s q\<\<$s$s\;s=\$s\;Q=sQs\;eval\$Q;echo$q';eval $Q$_='$z=0?"$&".next+92 .chr+10 .chr: 0..a||eval("printf=console.log;unescape$%27%5C%0Ak");$q=$z[1]?$z[1]:h^O;printf("%s%s%s%s<?#/.__id__;s=+0;#%s;read -d %s%s q<<%s%s;s=%s%s;Q=%secho s=1//2%s;_=r%ss%ss%ss%s<%s?%s#/.__id__%s;s=+0%s;#%ss%s;read -d %ss%ss q%s<%s<%ss%ss%s;s=%s%s%ss%s;Q=%ss%sQ%ss%s;eval%s %s%sQ;echo %sq%s;eval %sQ%s%s_=%s%s%s;eval(%s_);//;#%s%s%s;f=%s%s%ss=1//2;_=r%%s%%s%%s;f=%%s%%s%%s;q=_[18]*3;print f%%%%(q,_,q,q,f,q)%s%s%s;q=_[18]*3;print f%%(q,_,q,q,f,q)%s",[]&&"s=1//2;_=r",$r=[]&&$q,$r,$r,$q,$q,$q,$q,$q,$b=$z[2]?$z[2]:chr(92),$q,$q,$b,$d=$z[0]?$z[0]:h^L,$d,$d,$b,$b,$b,$b,$b,$d,$b,$d,$d,$b,$b,$d,$d,$b,$b,$b,$d,$b,$d,$d,$d,$b,$b,$b,$d,$d,$q,$d,$n=$z[3]?$z[3]:chr(10),$d,$q,$_,$q,$d,$q,$q,$q,$q,$q,$q,$q,$q,$q,$z[4]?"":$n);';eval($_);//;#''';f='''s=1//2;_=r%s%s%s;f=%s%s%s;q=_[18]*3;print f%%(q,_,q,q,f,q)''';q=_[18]*3;print f%(q,_,q,q,f,q)



Verify it online!

A little closer to my original approach, but the repetition of the args for printf is still insane. Using positional arguments instead make this only work in Chrome and is tricky to get working in PHP as well because the $s in %1$s is interpolated, but could save a lot of bytes, perhaps using a combination of the two approaches...

# 05AB1E/2sable, 14 bytes, non-competing

0"D34çý"D34çý


2sable is derived from 05AB1E and is similar, but has major differences.

Trailing newline.

• I don't know what the current state of 2sable and 05AB1E is, but last time I checked I would have considered them to be different dialects of one language. – Martin Ender Nov 11 '16 at 16:06

# C/TCL, 337 bytes

#define set char*f=
#define F
#define proc main(){
set F "#define set char*f=
#define F
#define proc main(){
set F %c%s%c;
proc /* {} {}
puts -nonewline %cformat %cF 34 %cF 34 91 36 36]
set a {*/printf(f,34,f,34,91,36,36);}
";
proc /* {} {}
puts -nonewline [format $F 34$F 34 91 36 36]
set a {*/printf(f,34,f,34,91,36,36);}


# C/Vim 4.0, 1636 bytes

Contains control characters.

map () {}/*
map g ;data0df"f"cf"
f"cf"
f"D2kyyP;g6k2dd4x5jA"JxA","JxA","jyyPkJxA"jok;g2kdd4xkJx3jdd
map ;g O"vdldd0i# 0# 1# 2# 3# 4# 5# #0lx2lx2lx2lx2lx2lx2lx:s/##/#/g
unmap ()

map ;data o*/ char*g[]={"map () {}/*#2map g ;data0df#0f#0cf#0#5#3f#0cf#0#5#3f#0D2kyyP;g6k2dd4x5jA#0#3JxA#0,#0#3JxA#0,#0#3jyyPkJxA#0#3jo#3k;g2kdd4xkJx3jdd#2map ;g O#4#4#4#4#3#0vdldd0i## 0## 1## 2## 3## 4## 5## ###30lx2lx2lx2lx2lx2lx2lx:s/####/##/g#5o:s//#0/g#3k0y2lj02lp#0addk@ao:s//#1#1/g#3k0ly2lj02lp#0addk@ao:s//#4#4#3/g#3k04ly2lj02lp05l#0vp#0addk@ao:s///g#3k05ly2lj02lp05l#0vp#0vp#0addk@ao:s//#4#4#5/g#3k06ly2lj02lp05l#0vp#0vp#0vp#0addk@ao:s//#4#4#5/g#3k02ly2lj02lp05l#0vp#0addk@a#2unmap ()#2#2map ;data o*/ char*g[]={","#A#0#a#0,#0#b#0,#0#c#0#C#2","}; /*#3#2#2#0*/  print(char*s){char*t=s,c,d;while(c=*t++)if(c==35){c=*t++;if(c==35)putchar(c);else if(c==48)putchar(34);else if(c==49)putchar(92);else if(c==50)printf(#0#1n#0);else if(c==51)putchar(27);else if(c==52)putchar(22);else if(c==53)putchar(13);else if(c>64&&c<91)print(g[c-65]);else printf(g[c-97]);}else putchar(c);}  main(){print(g[1]);}"}; /*

"*/  print(char*s){char*t=s,c,d;while(c=*t++)if(c==35){c=*t++;if(c==35)putchar(c);else if(c==48)putchar(34);else if(c==49)putchar(92);else if(c==50)printf("\n");else if(c==51)putchar(27);else if(c==52)putchar(22);else if(c==53)putchar(13);else if(c>64&&c<91)print(g[c-65]);else printf(g[c-97]);}else putchar(c);}  main(){print(g[1]);}


Your Vim needs to have the following set:

set noai
set wm=0
set nosi
set tw=0
set nogdefault


# C/Lisp, 555 bytes

t(setq /*;*/){}main(){char q='\"',s='\\';char*a=
"~%t(setq /*;*/){}main(){char q='~A';char*a=
~S;char*b=/*
)(setq a ~S)
(setq */ ~S;printf(b,s,q,s,s,q,a,q,q,s,s,s,q,s,s,s,s,q,q,b,q/*
)(format t /* a /* a */);}~%";char*b=/*
)(setq a "\\\"',s='\\\\")
(setq */ "
t(setq /*;*/){}main(){char q='%c%c',s='%c%c';char*a=
%c%s%c;char*b=/*
)(setq a %c%c%c%c%c',s='%c%c%c%c%c)
(setq */ %c%s%c;printf(b,s,q,s,s,q,a,q,q,s,s,s,q,s,s,s,s,q,q,b,q/*
)(format t /* a /* a */);}
";printf(b,s,q,s,s,q,a,q,q,s,s,s,q,s,s,s,s,q,q,b,q/*
)(format t /* a /* a */);}


Intentionally blank first line.

In JavaScript, +[] returns 0, so we call unescape("%27") to store ' in $q (unfortunately, atob doesm't exist in SpirderMonkey...). In the call to print, since + is the concatenation operator in JavaScript, the first block builds the desired output and the second part after the || is ignored. Thanks to Patrick Roberts' comment for the unescape trick! ## Perl/JavaScript (Browser), 108 bytes $_='eval("q=_=>_+;printf=console.log");printf(q$_=%s%s%s;eval($_),$q=+[]?h^O:atob("Jw"),$_,$q)';eval($_)


Try the Perl online!

$_='eval("q=_=>_+;printf=console.log");printf(q$_=%s%s%s;eval($_),$q=+[]?h^O:atob("Jw"),$_,$q)';eval($_) ### Explanation We store the quine data in $_ in both languages and then eval it, which is pretty much standard procedure in Perl.

Perl sees the data stored in $_ and evals it as usual. The eval within $_ is executed and fails to parse, but since it's eval, doesn't error. printf is then called, with a single quoted string q(), with  as the delimter, as just using  would result in commands being executed in shell, then for the first use of $q, since +[] is truthy in Perl, ' is stored in $q via stringwise-XOR of h and O.

In JavaScript, the eval block within $_ sets up a function q, that returns its argument as a String and aliases console.log to printf, since console.log formats string like printf in Perl. When printf is called +[] returns 0, so we call atob to decode ' and store in $q.

# C/dc, 152 bytes

z1d//[[z1d//]P91PP93P[dx]Pq
;main(){char*a="z1d//[[z1d//]P91PP93P[dx]Pq%c;main(){char*a=%c%s%c;printf(a,10,34,a,34);}//]dx";printf(a,10,34,a,34);}//]dx


$_='$z=0?"$&".next: 0..a||eval("printf=console.log;atobJCc");printf("%s_=%s%s%s;eval(%s_);",$d=$z[0]?$z[0]:h^L,$q=$z[1]?$z[1]:h^O,$_,$q,$d);';eval($_);  $_='$z=0?"$&".next: 0..a||eval("printf=console.log;atobJCc");printf("%s_=%s%s%s;eval(%s_);",$d=$z[0]?$z[0]:h^L,$q=$z[1]?$z[1]:h^O,$_,$q,$d);';eval($_);`