s LearnSqueak.com

ABSOLUTE BEGINNER

Your first Set: keep each value once

Try five tiny Squeak examples to collect unique values and ask whether a value is present.

5 minutes · 5 small steps · Squeak 6.1

STEP 1

Make an empty Set

Open Workspace in Squeak. Select this whole expression and choose Print it. A Set starts with no values.

Select the whole expression, then Print it
Set new size
NATIVE SQUEAK CAPTURE
Native Squeak Set checkpoint 1
Actual native Squeak Workspace Print it result.
You should see

0: the Set is empty.

STEP 2

Add one value

A Set remembers each different value once. The last line asks how many it holds.

Select the whole expression, then Print it
| colors |
colors := Set new.
colors add: 'blue'.
colors size
NATIVE SQUEAK CAPTURE
Native Squeak Set checkpoint 2
Actual native Squeak Workspace Print it result.
You should see

1: one value is stored.

STEP 3

Add the same value again

Adding blue twice still leaves one blue. Copy this entire example; it starts fresh.

Select the whole expression, then Print it
| colors |
colors := Set new.
colors add: 'blue'.
colors add: 'blue'.
colors size
NATIVE SQUEAK CAPTURE
Native Squeak Set checkpoint 3
Actual native Squeak Workspace Print it result.
You should see

1 again: the duplicate adds nothing new.

STEP 4

Ask a yes-or-no question

includes: asks whether a value is present.

Select the whole expression, then Print it
| colors |
colors := #('blue' 'green' 'blue') asSet.
colors includes: 'green'
NATIVE SQUEAK CAPTURE
Native Squeak Set checkpoint 4
Actual native Squeak Workspace Print it result.
You should see

true: green is in the Set.

STEP 5

Count the unique values

A list may repeat values. asSet keeps one of each. A Set does not promise a display order.

Select the whole expression, then Print it
#('blue' 'green' 'blue') asSet size
NATIVE SQUEAK CAPTURE
Native Squeak Set checkpoint 5
Actual native Squeak Workspace Print it result.
You should see

2: blue and green. Try adding red to the list; the answer becomes 3.

YOU DID IT

A small step. A real result.

A Set keeps each different value once. Use includes: to ask whether a value is present. A Set does not promise an order.

Optional code download: open it as text and copy one example into Workspace.

Download the five examples; copy one at a time

Your first list · More Smalltalk messages