View this PageEdit this Page (locked)Attachments to this PageHistory of this PageHomeRecent ChangesSearch the SwikiHelp Guide
Hotspots: Admin Pages | Turn-in Site |
Current Links: Cases Final Project Summer 2007

Martin's CW 1

CW 1

Tracing Code

|   data onlyPositiveNumbers   |
data := OrderedCollection withAll: #(1 2 3 -4 -5 'error' 6 -7 999 2).
onlyPositiveNumbers := [:i | (i isKindOf: Number) and: [i positive]].
data := data select: onlyPositiveNumbers.
data := data copyUpTo: 999. "not including"
Transcript show: data average

line 1
Local variables 'data' and 'onlyPositiveNumbers' are declared.
Both variables are nil as they are not initialized.
line 2
'data' is assigned an OrderedCollection from the withAll message.
It has all the elements from #(1 2 3 -4 -5 'error' 6 -7 999 2)
line 3
'onlyPositiveNumbers' is assigned to a block of code.
This block of code takes a variable 'i' and returns a boolean.
The boolean is true only when (i isKindOf: Number) is true and
when [i positive] is true.
Again, no evaluation is done at this point, just block assigning.
line 4
'data', the OrderedCollection, is assigned to a new collection from passing
itself select: with the block of code variable that becomes true when
being passed each item in 'data'. It becomes #(1 2 3 6 999 2).
line 5
'data' again is assigned to the collection return by passing itself
the message copyUpTo: with 999. 'data' now becomes #(1 2 3 6).
line 6
The average value of elements in 'data', 3, is computed and shown.

Message Passing

Message passing is how everything is done in Squeak. Most every line of
code consists of an object (almost anything you can think of is an object)
and some message that it is given. Messages, when passed to an object, are first
given to the most-derived (most subclassed) class. If this class cannot handle
the message, the message gets passed along to the parent class definition of
the object. When the message is finally dealt with, the the message propagation
stops and code is executed. If the message is not defined anywhere along the path,
an error is spawned. This is very easy to start programming with as the maker does
not need to spend much time defining strict typing. However, the wrong messages could
get passed to the wrong object during execution and the compiler would not have
been able to predict that event.

Link to this Page