29.11.2014 Views

Smalltalk and Object Orientation: an Introduction - Free

Smalltalk and Object Orientation: an Introduction - Free

Smalltalk and Object Orientation: an Introduction - Free

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

11.9 Iterating over collections<br />

A number of messages are available which allow the sa me operation to be applied to each element in a<br />

collection <strong><strong>an</strong>d</strong> in some cases the results of this operation c<strong>an</strong> be automatically collected. These<br />

messages are referred to as the iteration messages, they include do:, select: reject:, collect:<br />

<strong><strong>an</strong>d</strong> detect:. For all the messages (except do:), the result is a new collection ‘just like the receiver’.<br />

The elements of this object depend on the criteria specified in the block associated with the message.<br />

Note the result c<strong>an</strong> be <strong>an</strong> empty collection.<br />

11.9.1 The do: message<br />

The do: aBlock message evaluates aBlock for each of the elements in the receiver (a<br />

Collection). aBlock should have one argument. (Note that you have not yet encountered blocks.<br />

For the time being treat them as begin/ends as in other l<strong>an</strong>guages su ch as Pascal or ADA. We will look<br />

at them in more detail later.)<br />

The following example illustrates the use of do:<br />

count := 0.<br />

letters do: [:each | each == $a ifTrue: [count := count + 1]].<br />

This expression counts the number of ‘a’s in the collection letters. The do statement iterates over the<br />

elements in the letters collection. Each element is bound to the temporary variable “each” in turn. It<br />

then compares each with the character “a”. If the result of this comparison is the object true (remember<br />

all expression return <strong>an</strong> object of some form) then the ifTrue: message will execute the code in its<br />

associated block.<br />

Compare it with C style code for the same task:<br />

count = 0; i = 0;<br />

max_num = length(letters);<br />

for (i = 1, i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!