Quine (Oz)

From LiteratePrograms

Jump to: navigation, search
Other implementations: BASIC | Clojure | dc | Erlang | Forth | JavaScript / URI | Lisp | Oz | Perl | Python | Smalltalk

A "Quine" is a program that prints its own sourcecode when it is run. See Wikipedia's article on Quines for more information, and David Madore's Page for a highly readable introduction to the art of constructing Quines.

Implementing a Quine

There are a variety of different ways we might go about producing a Quine in Oz. Perhaps the most straightforward way is to simply include a copy of the sourcecode as a string within the program, and print it out twice (once as code, once as a string). The secret to making this work is to make use of Oz's representation of strings as lists of integers, and encode the quote characters which surround the source string. This allows us to avoid having to escape the quote characters within the source string.

<<Quine.oz>>=
functor
import
   System
   Application
define
   proc {Quine Data}
      {System.showInfo Data # [34] # Data # [34 &} &
] # 'end'}  
      {Application.exit 0}
   end
   {Quine "functor
import
   System
   Application
define
   proc {Quine Data}
      {System.showInfo Data # [34] # Data # [34 &} &
] # 'end'}  
      {Application.exit 0}
   end
   {Quine "}
end

This comes close to David Madore's “quine ‘quine’”.

Testing the Quine

Compiling and running Quine.oz does indeed produce the source for Quine.oz, demonstrating that it is a Quine.

$ ozc -x Quine.oz
$ ./Quine
functor
import
   System
   Application
define
   proc {Quine Data}
      {System.showInfo Data # [34] # Data # [34 &} &
] # 'end'}  
      {Application.exit 0}
   end
   {Quine "functor
import
   System
   Application
define
   proc {Quine Data}
      {System.showInfo Data # [34] # Data # [34 &} &
] # 'end'}  
      {Application.exit 0}
   end
   {Quine "}
end
Download code
Views