s LearnSqueak.com

ABSOLUTE BEGINNER

Your First occurrencesOf: in Squeak

Count how many times the same item appears in a list or character string.

5 minutes · 5 small steps · Squeak 6.1

STEP 1

Count a repeated number

In Workspace, select the whole line and choose Print it. The number 2 appears twice.

Select the whole expression, then Print it
#(2 5 2 9) occurrencesOf: 2
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Count a repeated number gives 2
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

The result is 2.

STEP 2

Count an item seen once

Ask the same list about 9. It appears just once.

Select the whole expression, then Print it
#(2 5 2 9) occurrencesOf: 9
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Count an item seen once gives 1
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

The result is 1.

STEP 3

Count an item that is missing

The list has no 4. Zero is still an answer.

Select the whole expression, then Print it
#(2 5 2 9) occurrencesOf: 4
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Count an item that is missing gives 0
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

The result is 0.

STEP 4

Count a letter in a word

A string is made of characters. Write $a for the single letter a.

Select the whole expression, then Print it
'banana' occurrencesOf: $a
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Count a letter in a word gives 3
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

The result is 3.

STEP 5

Count matching words in a list

Here the items are whole words, so keep the quotes around 'blue'.

Select the whole expression, then Print it
#('blue' 'red' 'blue') occurrencesOf: 'blue'
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Count matching words in a list gives 2
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

The result is 2.

YOU DID IT

A small step. A real result.

occurrencesOf: counts entries that equal the item you give it.

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

Download the five examples; copy one at a time

Ask if any item matches · Your first list