s LearnSqueak.com

ABSOLUTE BEGINNER

Your First Matching Item in Squeak

Find the first item that passes a test, or choose a clear answer when none does.

5 minutes · 5 small steps · Squeak 6.1

STEP 1

Set a simple test

In Workspace, select the expression and choose Print it. Here the question is whether 5 is bigger than 3.

Select the whole expression, then Print it
5 > 3
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Set a simple test gives true
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

The answer is true.

STEP 2

Find the first match

The test inside the first brackets is asked for each number in order. 1 fails. 5 passes, so the search stops.

Select the whole expression, then Print it
#(1 5 7) detect: [:n | n > 3] ifNone: [0]
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Find the first match gives 5
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

The answer is 5, not 7.

STEP 3

Change the order

Keep the same test but put 7 before 5.

Select the whole expression, then Print it
#(1 7 5) detect: [:n | n > 3] ifNone: [0]
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Change the order gives 7
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Now the answer is 7.

STEP 4

Build a clear fallback

No number is bigger than 3. The second pair of square brackets tells Squeak what to answer instead.

Select the whole expression, then Print it
#(1 2 3) detect: [:n | n > 3] ifNone: ['none']
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Build a clear fallback gives 'none'
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

You see the text none.

STEP 5

Try an empty list

An empty list has no match, either. Keep the same fallback.

Select the whole expression, then Print it
#() detect: [:n | n > 3] ifNone: ['none']
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Try an empty list gives 'none'
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

The answer is still none.

YOU DID IT

A small step. A real result.

detect:ifNone: gives the first match, or the answer you choose when nothing matches.

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