s LearnSqueak.com

ABSOLUTE BEGINNER

Swap two items in a list

Use swap:with: to trade two positions in a playlist. Learn how to keep the original and undo a swap in five tiny steps.

5 minutes · 5 small steps · Squeak 6.1

STEP 1

Make a tiny playlist

A list has an order. Here, Rain is first and Waves is last.

Select the whole expression, then Print it
#('Rain' 'Wind' 'Waves')
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Make a tiny playlist gives #('Rain' 'Wind' 'Waves')
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Notice that Wind sits in the middle.

STEP 2

Find the song at position 3

Squeak uses 1 for the first item. Ask for the third item with at:.

Select the whole expression, then Print it
#('Rain' 'Wind' 'Waves') at: 3
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Find the song at position 3 gives 'Waves'
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Change 3 to 2 to see Wind.

STEP 3

Swap the first and last songs

swap:with: takes two position numbers. Copy this playlist first so you have a list you can change.

Select the whole expression, then Print it
| playlist |
playlist := #('Rain' 'Wind' 'Waves') copy.
playlist swap: 1 with: 3.
playlist
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Swap the first and last songs gives #('Waves' 'Wind' 'Rain')
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Waves and Rain trade places. Wind stays in the middle.

STEP 4

Keep one list as a backup

Copy the original into a new list, then swap in the copy. The last line shows the original and the copy side by side.

Select the whole expression, then Print it
| original copy |
original := #('Rain' 'Wind' 'Waves').
copy := original copy.
copy swap: 1 with: 2.
{original. copy}
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Keep one list as a backup gives #(#('Rain' 'Wind' 'Waves') #('Wind' 'Rain' 'Waves'))
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Rain stays first in the original but moves to second in the copy.

STEP 5

Swap twice to undo it

The same two positions still exist after the first swap. Swap them again to go back.

Select the whole expression, then Print it
| playlist |
playlist := #('Rain' 'Wind' 'Waves') copy.
playlist swap: 2 with: 3.
playlist swap: 2 with: 3.
playlist
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Swap twice to undo it gives #('Rain' 'Wind' 'Waves')
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Try changing only the second swap to 1 with: 3. Predict the new order.

YOU DID IT

A small step. A real result.

swap:with: exchanges two positions in the same list. To keep the original order, swap in a copy.

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

Download the five examples; copy one at a time

Make a list · Number the items in a list