s LearnSqueak.com

ABSOLUTE BEGINNER

Your First collect: in Squeak

Use collect: to turn each item in a list into a new value without changing the original list.

5 minutes · 5 small steps · Squeak 6.1

STEP 1

Try the rule on one number

Start with one number. Multiplying by 2 doubles it. Next you will use the same rule on a whole list.

Select the whole expression, then Print it
3 * 2
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Try the rule on one number gives 6
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Squeak prints 6.

STEP 2

Double every number

Read the square brackets as a rule. Each item takes a turn being called n. The part after the vertical bar says how to make that item's result.

Select the whole expression, then Print it
#(1 2 3) collect: [:n | n * 2]
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Double every number gives #(2 4 6)
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

The three results are 2, 4, and 6, in the same order as the inputs.

STEP 3

Measure each word

You can collect a different kind of value. This rule asks each word for its length, so words go in and numbers come out.

Select the whole expression, then Print it
#('cat' 'rabbit' 'ox') collect: [:word | word size]
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Measure each word gives #(3 6 2)
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Squeak prints #(3 6 2). Try changing 'ox' to 'bear'. The last result becomes 4.

STEP 4

Look at before and after

Save the original and the result with two names. The braces put both lists side by side so you can compare them.

Select the whole expression, then Print it
| original doubled |
original := #(2 5).
doubled := original collect: [:n | n * 2].
{original. doubled}
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Look at before and after gives #((2 5) (4 10))
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

The first list still contains 2 and 5. The second contains 4 and 10.

STEP 5

Collect answers to a question

The rule may give a yes-or-no result. collect: keeps one answer per item. It does not remove any items just because their answer is false.

Select the whole expression, then Print it
#(2 5 8) collect: [:n | n even]
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Collect answers to a question gives #(true false true)
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

2 and 8 give true, and 5 gives false. You still get three results.

YOU DID IT

A small step. A real result.

collect: uses your rule once on every item and gives you a collection of the results.

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

Download the five examples; copy one at a time

Count matching items · Your first list