Versatile self-printer
Using your languages of choice, golf a quine - a non-empty program taking no input and only outputting its source.
Here, the win condition is your quine working in the most languages. It should be a proper quine, although it can append newlines in a language that absolutely requires them.
Only different major versions of the same language will be considered different (Python 2 and 3, not 2.5 and 2.7).
The program that works as a quine in the most languages wins, with the tiebreaker being character count.
Have fun, codidactyls!
1 answer
Scala 3 and Python 3.8 (pre-release), 2 languages (385 bytes)
def String():Any=0
def Int():Any=0
def f(s:String):Any=print(s.replace(chr(81),chr(34)*3+s+chr(34)*3))
class M:
f("""def String():Any=0
def Int():Any=0
def f(s:String):Any=print(s.replace(chr(81),chr(34)*3+s+chr(34)*3))
class M:
f(Q)
def main(a:M):M=a
def chr(a:Int):String=""+a.toChar
@main
def q():M=M()""")
def main(a:M):M=a
def chr(a:Int):String=""+a.toChar
@main
def q():M=M()
def f(s:String):Any=print(s.replace(chr(81),chr(34)*3+s+chr(34)*3))
f
is where everything happens. In Scala, the print
method doesn't add a newline, but that doesn't matter to us. Both Scala and Python have a replace
method on strings and can multiply strings by numbers, but they have different ways of turning integers into strings, which is why the chr
method is defined later for Scala's benefit. It's already present in Python, but the interpreter sees it after f
, and it's never run anyway. s
is a string literal which contains basically the entire program, but the definition of s
is replaced with Q
. In f
, this Q
is replaced with """<contents of s>"""
to mirror the definition of s
, and that gets printed.
While Python can have expressions outside functions and classes, Scala needs a main method. Thus, the call to f
is put inside a class M
. Python runs this when the class loads, while Scala calls it in the method q
, when the constructor is called using M()
. However, to make the @main
annotation to work with Python, a function named main
was made.
chr
is already defined in Python, and to make it work in Scala, the chr
method converts an integer to a string based on its ASCII value.
Int
and String
are Scala builtins that we need to annotate the parameters to f
and chr
with, but Python doesn't know about them, which is why def String()
and def Int()
are defined. I made them functions instead of plain variables because Scala requires variables to be declared with val
and var
, something that is not possible in Python. While Scala sees def String
as a method that takes nothing and can output Any
value (specifically, 0
), Python sees it as setting the value of a variable Any
to 0
. Neither of these two have any real impact on the code other than making it work nicely with Python.
1 comment thread