less_retarded_wiki/quine.md
2022-11-26 20:07:55 +01:00

1.9 KiB

Quine

Quine is a nonempty program which prints its own source code. It takes no input, just prints out the source code when run (without cheating such as reading the source code file). Quine is basically a self-replicating program, just as in real world we may construct robots capable of creating copies of themselves (afterall we humans are such robots). The name quine refers to the philosopher Willard Quine and his paradox that shows a structure similar to self-replicating programs. Quine is one of the standard/fun/interesting programs such as hello world, 99 bottles of beer or fizzbuzz.

Quine can be written in any Turing complete language, the challenge is in the self reference -- normally we cannot just single-line print a string literal containing the source because that string literal would have to contain itself, making it infinite in length. The idea commonly used to solve this problem is following:

  1. On first line start a definition of string S, later copy-paste to it the string on the second line.
  2. On second line put a command that prints the first line, assigning to S the string in S itself, and then prints S (the second line itself).

This is a quine in C:

#include <stdio.h>
char s[] = "#include <stdio.h>%cchar s[] = %c%s%c;%cint main(void) { printf(s,10,34,s,34,10,10); return 0; }";
int main(void) { printf(s,10,34,s,34,10,10); return 0; }

This is a quine in Python:

s="print(str().join([chr(115),chr(61),chr(34)]) + s + str().join([chr(34),chr(10)]) + s)"
print(str().join([chr(115),chr(61),chr(34)]) + s + str().join([chr(34),chr(10)]) + s)

TODO: more langs?

In the Text esoteric programming language every program is a quine.