s LearnSqueak.com

ABSOLUTE BEGINNER

Your first sorted list

Put numbers and words in order with one Smalltalk message. Try five tiny examples in Workspace.

5 minutes · 5 small steps · Squeak 6.1

STEP 1

Make a small list

Open Workspace. Type this list, select it, and choose Print it.

Select the whole expression, then Print it
#(3 1 2)
NATIVE SQUEAK CAPTURE
Native Squeak sorting checkpoint 1
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

You see three numbers in the order you typed them.

STEP 2

Put it in order

Send sorted to make an ordered copy.

Select the whole expression, then Print it
#(3 1 2) sorted
NATIVE SQUEAK CAPTURE
Native Squeak sorting checkpoint 2
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

The smallest number comes first.

STEP 3

Keep repeated numbers

Sorting keeps every item, including repeats.

Select the whole expression, then Print it
#(4 1 4 2) sorted
NATIVE SQUEAK CAPTURE
Native Squeak sorting checkpoint 3
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Both 4s are still there.

STEP 4

Sort words too

Use single quotes around each word. These lowercase words sort alphabetically.

Select the whole expression, then Print it
#('pear' 'apple' 'banana') sorted
NATIVE SQUEAK CAPTURE
Native Squeak sorting checkpoint 4
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Apple comes before banana, then pear.

STEP 5

Keep the original

Give the list a name. Look at the original and the sorted copy together.

Select the whole expression, then Print it
| numbers |
numbers := #(3 1 2).
{numbers. numbers sorted}
NATIVE SQUEAK CAPTURE
Native Squeak sorting checkpoint 5
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

The first list still says 3, 1, 2. sorted made a separate ordered list.

YOU DID IT

A small step. A real result.

sorted returns an ordered copy. The original list is still available.

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