Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Aside from cheating¹ there is no difference between compiled and interpreted languages. </p> <p>The generic approach to quines is quite easy. First, whatever the program looks like, at some point it has to print something:</p> <pre> print ... </pre> <p>However, what should it print? Itself. So it needs to print the "print" command:</p> <pre> print "print ..." </pre> <p>What should it print next? Well, in the mean time the program grew, so it needs to print the string starting with "print", too:</p> <pre> print "print \"print ...\"" </pre> <p>Now the program grew again, so there's again more to print:</p> <pre> print "print \"print \\\"...\\\"\"" </pre> <p>And so on. With every added code there's more code to print. This approach is getting nowhere, but it reveals an interesting pattern: The string "print \"" is repeated over and over again. It would be nice to put the repeating part into a variable:</p> <pre> a = "print \"" print a </pre> <p>However, the program just changed, so we need to adjust a:</p> <pre> a = "a = ...\nprint a" print a </pre> <p>When we now try to fill in the "...", we run into the same problems as before. Ultimately, we want to write something like this:</p> <pre> a = "a = " + (quoted contents of a) + "\nprint a" print a </pre> <p>But that is not possible, because even if we had such a function <code>quoted()</code> for quoting, there's still the problem that we define <code>a</code> in terms of itself:</p> <pre> a = "a = " + quoted(a) + "\nprint a" print a </pre> <p>So the only thing we can do is putting a place holder into <code>a</code>:</p> <pre> a = "a = @\nprint a" print a </pre> <p>And that's the whole trick! Anything else is now clear. Simply replace the place holder with the quoted contents of <code>a</code>:</p> <pre> a = "a = @\nprint a" print a.replace("@", quoted(a)) </pre> <p>Since we have changed the code, we need to adjust the string:</p> <pre> a = "a = @\nprint a.replace(\"@\", quoted(a))" print a.replace("@", quoted(a)) </pre> <p>And that's it! All quines in all languages work that way (except the cheating ones).</p> <p>Well, you should ensure that you replace only the first occurence of the place holder. And if you use a second place holder, you can avoid needing to quote the string.</p> <p>But those are minor issues and easy to solve. If fact, the realization of <code>quoted()</code> and <code>replace()</code> are the only details in which the various quines really differ.</p> <hr> <p>¹ by making the program read its source file</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload