Self-Reproducing Program in Groovy

I had this in mind since yesterday: how to write a self-reproducing program in Groovy, or a Quine, a program which prints out its source code. It’s actually a fun exercise.

Here is my version:

a = 'c = (char)39; println "a = $c$a$c"; println "$a"'
c = (char)39; println "a = $c$a$c"; println "$a"

It looks scary, but it is actually not that terrible. The first line is the definition of a variable a of the form:

a = '[some string]'

The second line is first the definition of the single quote character assigned to c. We then print out the first line (including the variable definition), where we replace the single quote by our character c, and where $a is the content of a. This part looks like:

println "a = $c$a$c";

Finally we print out a.

The only thing that we need now to do, is to replace [some string] in the first line. It happens that if we take the complete second line and assign it to ‘a’ in the first line, we will get the desired output. We see here that if we had not used $c in the first println of the second line instead of the single quote, the string assigned to a in the first line would not be legal, since it would contain inside the string a string delimiter (and if we escape it, we don’t get the same output as the program code).

That’s it. It was fun.

Links:

  • A quine on Wikipedia
  • Interesting blog post about a self-reproducing program
  • 3 thoughts on “Self-Reproducing Program in Groovy”

    1. Much less geeky but always useful was Perl’s ability to refer to the source file, allowing you to trivially write CGI scripts that print their own source code. Excellent for software licensed using the GNU Affero General Public License.

      A simple example I wrote myself a while ago:
      http://emacswiki.org/cgi-bin/m20-hard-core-characters

      And the Affero license link:
      http://www.fsf.org/licensing/licenses/agpl-3.0.html

      That’s the license used by Laconica, for example.
      http://identi.ca/

    2. @Alex

      I was wondering also if there was an easier way to do it, as you suggest, to have a way to reference the source file. Of course this would work only for script languages (which are not compiled). Groovy is a bit in between, since it is normally compiled to byte code, but there are also ways to execute (after on-the-fly compilation) a groovy source code.

      @Ben

      I recon. But it’s an interesting problem (I think).

    Comments are closed.