Navigation
Synopsis A self-reproducing program.
Description A quine is a computer program that takes no input and produces a copy of its own source code. A quine is also called a self-replicating or self-reproducing program.

At The Quine Page you can find hundreds of quines in many different programming languages.

Learning about quines, is about learning how to quote and escape symbols in strings.
Examples
module demo::basic::Quine

import IO;
import String;

public void quine(){
  println(program); 
  println("\"" + escape(program, ("\"" : "\\\"", "\\" : "\\\\")) + "\";"); 
}

str program = 
"module demo::basic::Quine

import IO;
import String;

public void quine(){
  println(program);
  println(\"\\\"\" + escape(program, (\"\\\"\" : \"\\\\\\\"\", \"\\\\\" : \"\\\\\\\\\")) + \"\\\";\");
}

str program ="; 
If you look at the source code, is a remarkable point: the string variable program has as value the text of the module Quine upto . Note that the definition of program ends at . Also observe that this string has a mesmerizing amount of escapes to which we will come back in a moment.

The function quine prints the string program twice:
  • At as is, and this produces the program upto .
  • At as a string (surrounded with string quotes) in order to reproduce the string value of program followed by a semi-colon (;).
Now here is the catch: we have to be very carefull in handling special characters like quote (") and backslash (\) in strings.

Let's do a simple experiment: And indeed, the two quotes are now properly escaped. This is exactly what happens at in the definition of quine:
println("\"" + escape(program, ("\"" : "\\\"", "\\" : "\\\\")) + "\";");
We escape program and replace " by \", and \ by \\. The mesmerizing amount of \ characters can be explained due to escaping " and \.

Now let's put quine to the test.
rascal>import demo::basic::Quine;
ok
rascal>quine();
module demo::basic::Quine

import IO;
import String;

public void quine(){
  println(program);
  println("\"" + escape(program, ("\"" : "\\\"", "\\" : "\\\\")) + "\";");
}

str program =
"module demo::basic::Quine

import IO;
import String;

public void quine(){
  println(program);
  println(\"\\\"\" + escape(program, (\"\\\"\" : \"\\\\\\\"\", \"\\\\\" : \"\\\\\\\\\")) + \"\\\";\");
}

str program =";
ok
If you follow this output line-by-line you will see that it is identical to the original source code of module Quine.
Is this page unclear, or have you spotted an error? Please add a comment below and help us to improve it. For all other questions and remarks, visit ask.rascal-mpl.org.