[   ^ to index...   |   next -->   ]

CSE 341 : 17 May 2001

Review: Smalltalk core language mechanisms

Implementing Smalltalk control structures

We learned last week that Smalltalk implements control structures using closures, and that we evaluate closure objects by sending one of several "value" messages. Here's a sample implementation of the method whileTrue: of BlockContext (the class used to implement closures in Squeak):

Object subclass: #BlockContext
    "..."

"Note the tail-recursive definition"
whileTrue: aBlock
    self value ifTrue: [
        aBlock value.
        ^ self whileTrue: aBlock
    ].

In practice, Smalltalk implementations (Squeak included) tend to use special hooks in the implementation, to make loops and other control structures faster (the above is not how Squeak implements whileTrue:). However, conceptually, all we need for arbitrary control structures are closures, recursion, and dynamic dispatch.

Consider the implementation of True and False, the two subclasses of Boolean:

Boolean subclass: #True "..."
ifTrue: aBlock ifFalse: alternateBlock
    ^ aBlock value.

Boolean subclass: #False "..."
ifTrue: aBlock ifFalse: alternateBlock
    ^ alternateBlock value.

By the way, there is exactly one global instance of True, named true, and one global instance of False, named false. Here's the definition of the new method for Boolean class:

new
    self error: 'You may not create any more Booleans - this is two-valued logic'

Oddly enough, however, you can create subclasses of Boolean. Of course, this gains you nothing---it simply means that you inherit the code of the Boolean class (which isn't much---most of its methods simply send self subclassResponsibility). Everything else in the system, which expects and passes around the unique True and False instances, will quietly ignore your new Boolean subclass.


Keunwoo Lee
Last modified: Thu May 17 00:22:33 PDT 2001