04 March 2009

My first quine

I’ve started trying some of the études at the Programming Praxis blog and came to A Self-Reproducing Program. I realized that I’d never actually attempted a quine before.

I decided to open DrScheme and just dive right into typing and see where it’d lead me. After a couple of false starts, I found myself with something like this:

#!r6rs
(define text '("#!r6rs\n(import (rnrs))\n(define text '(" ??? ")\n(for-each display text)"))
(for-each display text)

It then wasn’t far from there to...

#!r6rs
(import (rnrs))
(define text '("#!r6rs\n(import (rnrs))\n(define text '" #f
")\n(for-each(lambda(item)(if item(display item)(write text)))text)\n"))
(for-each(lambda(item)(if item(display item)(write text)))text)

Not particularly clever, but it works. I think my C background is showing.

The “answer” given at Programming Praxis is really an expression that evaluates to itself rather than a program that prints itself, which I suppose is more “Schemish”.

I then set about trying to modify it to be nicely formatted and to reproduce that formatting. That actually proved rather tricky without resorting to a pretty printing library.

Check The Quine Page for lots of quines.

1 comment:

Unknown said...

I'm glad you enjoy Programming Praxis. Perhaps you would like to contribute your code as a comment there. I'll look forward to your solutions to some of the other exercises.