Quine (Smalltalk)

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. For a definition, see Wikipedia's article on Quines.

The following Smalltalk example based on VisualWorks: Smalltalk Quines and is attributed to Vassili Bykov with slight changes.

A block is a language construct in Smalltalk which allows us to structure the Quine. The general outline of the program which is really just a block definition and it execution is as follows:

<<Smalltalk.st>>=
block openingblock bodyblock closingcall block

The block syntax opens with a '[' character and then a parameter named s followed by a pipe character, to let us know that the block arguments are finished being defined.

<<block opening>>=
[:s |

Next comes the block body where we print out the argument twice to the transcript.

<<block body>>=
 Transcript show: s; show: s printString 

Why the message printString on the second show? printString causes the object s to print itself as a literal string representation. This gets us the single quotes in our Quine.

Then the closing of the block definition.

<<block closing>>=
]

and lastly we invoke the block by sending the value message with a String message parameter.

<<call block>>=
value: '[:s | Transcript show: s; show: s printString] value: '

The block which we created is the object which will be sent the message. The parameter which we send is the first half of the program. Since the block prints twice to the transcript, the whole program is reproduced.

Download code
Views