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.

Links:

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

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

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store