A block is a sequence of statements. It can be passed to other statements as an argument. A block may have parameters too. Refer to page 516-517 of Coad/Nicola book.
First, create a subclass of OrderedCollection, and call
it MyList. This class has only three instance methods:
initialize
1 to: 15 do: [:i | self add: i]
doBlock: aBlock
aBlock value: self.
eachDo: aBlock
1 to: self size do: [:index |
self at: index put: (
aBlock value: (self at: index))]
Then, in the Workspace, write:
|list sum result|
list := MyList new initialize.
sum := [:aList |
| tem |
tem := 0.
aList do:[:v | tem := tem + v].
result := tem.
].
list doBlock: sum.
Transcript show: result printString; cr.
Here, sum is a block. It takes a collection as
parameter, and get the sum of the value of that collection. After the
execution of the above, you should get 120 as result.
Now add one more variable inc1 in the variable list. And
append the code below in the workspace.
inc1 := [:each | each + 1].
list eachDo: inc1.
list doBlock: sum.
Transcript show: result printString; cr.
The block inc1 is used to increase one element of the
collection by one. After ``do it'', you should get 135.
Now, here comes your job. You should make the following blocks:
average
sum, but get the average value as result.
deviation
( (x1 - average)2
+ (x2 - average)2
+ ...
+ (xn - average)2 ) / (n - 1)
(note the square operations).
squ
Then, your Workspace should looks like:
|list sum result inc1 average deviation squ|
list := MyList new initialize.
sum := [:aList |
| tem |
tem := 0.
aList do:[:v | tem := tem + v].
result := tem.
].
list doBlock: sum.
Transcript show: result printString; cr.
average := []. "<-- Your job"
list doBlock: average.
Transcript show: result printString; cr.
deviation := []. "<-- Your job"
list doBlock: deviation.
Transcript show: result printString; cr.
inc1 := [:each | each + 1].
list eachDo: inc1.
list doBlock: sum.
Transcript show: result printString; cr.
list doBlock: average.
Transcript show: result printString; cr.
list doBlock: deviation.
Transcript show: result printString; cr.
squ := []. "<-- Your job"
list eachDo: squ.
list doBlock: sum.
Transcript show: result printString; cr.
list doBlock: average.
Transcript show: result printString; cr.
list doBlock: deviation.
Transcript show: result printString; cr.
After you have done those blocks and got correct results, make a
class method
demo, copy everything on your Workspace and paste in that
method. Also, at the beginning of that method, write down the results
you got as comments. For example,
demo
"My results (in order): 120, 135, ..."
|list sum result inc1 average deviation squ|
... ...
Save the class you made, and file it out. Use the command:
cat filename.st | elm -s "TI,Lab4," cs2390@prism.gatech.edu
And, quit your VisualWorks environment.
News Page | CS2390 Sum'97 Home Page | MMC-CaMILE | STABLE
Questions/comments/concerns to guzdial@cc.gatech.edu
Page last updated 7/23/97; 10:40:26 AM