Self-Reproducing Program in Groovy

Patrick Jayet
Jun 7, 2009 · 2 min read

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.


XRB’s Blog

Random thoughts of a Software Engineer

Patrick Jayet

Written by

Polyglot (FR, DE, EN, ES), polyglot programmer (Java, Groovy, Ruby, Swift, Objective-C, Scala, Python, O’Caml) polyglot methodologist (Scrum, Kanban, Lean).

XRB’s Blog

Random thoughts of a Software Engineer