s LearnSqueak.com

ABSOLUTE BEGINNER

Your First Match Count in Squeak

Use count: to find how many items in a list pass a simple test.

5 minutes · 5 small steps · Squeak 6.1

STEP 1

Ask one yes-or-no question

The > sign asks whether the number on the left is bigger than the number on the right.

Select the whole expression, then Print it
7 > 5
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Ask one yes-or-no question gives true
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

7 is bigger than 5, so Squeak prints true.

STEP 2

Count the numbers that pass

Read the part in brackets as: for each number n, ask if n is bigger than 5. The numbers 7 and 9 pass. The number 5 does not.

Select the whole expression, then Print it
#(2 5 7 9) count: [:n | n > 5]
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Count the numbers that pass gives 2
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Squeak prints 2. You get the total, not the matching numbers.

STEP 3

Change just the test

Keep the same list. Change > to >= to include numbers equal to 5 as well as numbers bigger than 5.

Select the whole expression, then Print it
#(2 5 7 9) count: [:n | n >= 5]
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Change just the test gives 3
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Squeak prints 3 because 5, 7, and 9 now pass.

STEP 4

Count both copies

The two 7s sit in different places in the list. Each one counts.

Select the whole expression, then Print it
#(7 2 7) count: [:n | n > 5]
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Count both copies gives 2
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Squeak prints 2, even though both matches are the same number.

STEP 5

Try a list with no matches

Neither number is bigger than 5. Try replacing the list with #() to see what happens with an empty list.

Select the whole expression, then Print it
#(2 5) count: [:n | n > 5]
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Try a list with no matches gives 0
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Both the list shown and the empty list give 0.

YOU DID IT

A small step. A real result.

count: asks a yes-or-no question about each item and answers with the number of yeses.

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

Download the five examples; copy one at a time

Find your first matching item · Your first list