-
Highlight with the mouse and select do it to introduce it
into the Smalltalk interpreter. Then enter, highlight, and evaluate:
[1 pt each]
test value: 12 "==> 'False'"
and then:
test value: 2 "==> 'True'"
The block test acts similar to something we saw in Scheme: a
procedure of one argument. In Scheme, we applied procedures by
putting the procedure (or a variable bound to it) in the first
position of a parenthetical expression and with the arguments in
the other places. In Smalltalk, everything is an object and
objects accept messages. To apply the procedure, we pass it the
message value along with an argument.
- [1 pt]
Blocks can have multiple arguments as well. Define and test the
following:
add := [:x :y | x + y ]
add value: 2 value: 10 "==> 12"
- [1 pt]
Blocks can also have zero arguments. Define and test the following:
sayHello := ['Hello!']
sayHello value "==> 'Hello'"
- [1 pt]
Notice how the syntax for sayHello is similar to the arguments
required for the ifTrue and ifFalse messages.
Evaluate the following:
(12 < 10) ifTrue: ['True'] ifFalse: sayHello "==> 'Hello'"
- [7 pts]
The Smalltalk class Boolean has two subclasses:
True and False. Boolean requires
that its subclasses support (i.e., provide implementations
for) the messages ifTrue and ifFalse, similar
to pure virtual functions in C++. Sketch out implementations
for ifTrue and ifFalse for the two subclasses.
There are four methods that need definitions here.
False ifFalse:,
True ifTrue:,
False ifTrue:, and
True ifFalse:, all accepting a single argument, a block.
In the case of the first two methods, return the result of invoking
the block (calling
the value method on it). For the latter two, just return nil
(essentially doing nothing).