s LearnSqueak.com

LANGUAGE FOUNDATIONS

Smalltalk,
inside Squeak.

A few simple rules. A whole world of objects.

Learn to read and write Smalltalk by evaluating small expressions in Squeak. Every complete code block below is independent and was tested in Squeak 6.1. Finish by building a small study-session summary.

12 runnable examplesReal Squeak screenshotsNo prior Smalltalk required

YOUR EXPERIMENT BENCH

Do it. Print it. Inspect it.

  1. Open Squeak, then choose Tools → Workspace.
  2. Paste one complete example and select its code, including any temporary-variable declarations.
  3. Use print it from the text pane’s context menu to evaluate it and insert its answer. Common shortcuts are Ctrl+P on Windows/Linux and Cmd+P on macOS; key mappings can vary.

Do it evaluates code without inserting the answer. Print it evaluates and inserts a textual representation. Inspect it opens an inspector on the result so you can explore the object. None of these automatically writes to Transcript.

Real Print it action in Squeak: 3 + 4 followed by the highlighted inserted answer 7
Actual Print it action: the inserted 7 is selected. Delete the inserted answer before running the same selection again.

Use the code block, not the displayed Result text, as your input. After Print it, avoid selecting the newly inserted answer together with the original code. The screenshots with “Evaluated result” labels were arranged after running the exact snippet so the input and answer are easy to compare.

01

LANGUAGE IN PRACTICE

Everything starts with a message

In 'Squeak' size, the string is the receiver, and size is a unary message: it takes no argument. The receiver answers with the number of characters. You don’t call a free-standing size function; you ask an object.

Smalltalk · select all, then Print it
'Squeak' size
Download .st
Result6
See the real Squeak screenshot
Squeak Workspace: Everything starts with a message with evaluated result 6
Actual Squeak Workspace. The evaluated result was inserted beneath the code for this capture. Open the image for full-size detail.
Try itChange the string and predict its size before you run the example.
02

LANGUAGE IN PRACTICE

Numbers, strings, and booleans are objects

The unary message class asks an object which class it belongs to. Braces build a dynamic Array from evaluated expressions, separated by periods. The class names below are the actual representation classes in our 64-bit Squeak image; another image can choose different numeric or string representations.

Smalltalk · select all, then Print it
{42 class. 3.5 class. 'hello' class. true class}
Download .st
Result{SmallInteger . SmallFloat64 . ByteString . True}
See the real Squeak screenshot
Squeak Workspace: Numbers, strings, and booleans are objects with evaluated result {SmallInteger . SmallFloat64 . ByteString . True}
Actual Squeak Workspace. The evaluated result was inserted beneath the code for this capture. Open the image for full-size detail.
Try itReplace 42 with a very large integer and ask which class represents it.
03

LANGUAGE IN PRACTICE

Arithmetic is message sending too

Operators such as + and / are binary messages with one argument. Squeak can preserve exact fractions: ten divided by four answers 5/2. Here // gives the floor quotient and \\ the modulo remainder.

Smalltalk · select all, then Print it
{3 + 4. 10 / 4. 10 // 4. 10 \\ 4}
Download .st
Result{7 . (5/2) . 2 . 2}
See the real Squeak screenshot
Squeak Workspace: Arithmetic is message sending too with evaluated result {7 . (5/2) . 2 . 2}
Actual Squeak Workspace. The evaluated result was inserted beneath the code for this capture. Open the image for full-size detail.
Try itCompare ordinary division with floor division. Exact fractions are values, not errors.
04

LANGUAGE IN PRACTICE

Combine strings

Single quotes delimit a string. The comma is a binary message that concatenates collections such as strings. Double quotes delimit comments, not strings. To put an apostrophe inside a string, write it twice.

Smalltalk · select all, then Print it
'Hello, ', 'Squeak'
Download .st
Result'Hello, Squeak'
See the real Squeak screenshot
Squeak Workspace: Combine strings with evaluated result 'Hello, Squeak'
Actual Squeak Workspace. The evaluated result was inserted beneath the code for this capture. Open the image for full-size detail.
Try itChange the greeting and the name. Spaces inside the quotes are part of the string.
05

LANGUAGE IN PRACTICE

Give intermediate results a name

Declare temporary variables between vertical bars. := assigns a value; = compares values. A period separates expressions. The final expression is the result of this Workspace evaluation. These declared temporaries exist only for this evaluation, so every example includes what it needs.

Smalltalk · select all, then Print it
| price quantity total |
price := 12.
quantity := 3.
total := price * quantity.
total
Download .st
Result36
See the real Squeak screenshot
Squeak Workspace: Give intermediate results a name with evaluated result 36
Actual Squeak Workspace. The evaluated result was inserted beneath the code for this capture. Open the image for full-size detail.
Try itChange quantity from 3 to 5. The result should be 60.
06

LANGUAGE IN PRACTICE

Read messages in the right order

Smalltalk evaluates unary messages first, binary messages next, keyword messages last. Binary messages share one precedence and run left to right. That means 3 + 4 * 2 is 14, not 11. Parentheses override the order. The unary message factorial runs before +; the argument to max: includes the binary sum.

Smalltalk · select all, then Print it
{3 + 4 * 2. 3 + (4 * 2). 3 factorial + 2. (1 max: 2 + 3)}
Download .st
Result#(14 11 8 5)
See the real Squeak screenshot
Squeak Workspace: Read messages in the right order with evaluated result #(14 11 8 5)
Actual Squeak Workspace. The evaluated result was inserted beneath the code for this capture. Open the image for full-size detail.
Try itRead the four expressions aloud. The answers, in order, are 14, 11, 8, and 5.
07

LANGUAGE IN PRACTICE

Package work in a block

Square brackets create a block, a piece of work you can evaluate later. :number is its argument, and the vertical bar separates arguments from the body. The keyword message value: supplies an argument and runs the block. An argument-free block receives value.

Smalltalk · select all, then Print it
| double |
double := [:number | number * 2].
double value: 21
Download .st
Result42
See the real Squeak screenshot
Squeak Workspace: Package work in a block with evaluated result 42
Actual Squeak Workspace. The evaluated result was inserted beneath the code for this capture. Open the image for full-size detail.
Try itUse number squared as the block body, then evaluate it with 6.
08

LANGUAGE IN PRACTICE

Ask a boolean to choose

The comparison answers a boolean. ifTrue:ifFalse: is one keyword message with two block arguments. Only the selected block is evaluated. Conditionals are messages to objects rather than special statement syntax.

Smalltalk · select all, then Print it
| score |
score := 82.
score >= 60
    ifTrue: ['Passed']
    ifFalse: ['Try again']
Download .st
Result'Passed'
See the real Squeak screenshot
Squeak Workspace: Ask a boolean to choose with evaluated result 'Passed'
Actual Squeak Workspace. The evaluated result was inserted beneath the code for this capture. Open the image for full-size detail.
Try itTry scores of 59 and 60. The >= comparison includes the boundary.
09

LANGUAGE IN PRACTICE

Repeat with a message

to:do: sends one keyword message with an end value and a block. The block receives each number from 1 through 5, including both ends. It updates the temporary sum, then the final expression answers 15.

Smalltalk · select all, then Print it
| sum |
sum := 0.
1 to: 5 do: [:number | sum := sum + number].
sum
Download .st
Result15
See the real Squeak screenshot
Squeak Workspace: Repeat with a message with evaluated result 15
Actual Squeak Workspace. The evaluated result was inserted beneath the code for this capture. Open the image for full-size detail.
Try itChange the upper limit to 10. Predict the total, then check that it is 55.
10

LANGUAGE IN PRACTICE

Transform, filter, and reduce

#(1 2 3 4 5) is a literal Array. collect: makes a collection of transformed values; select: keeps values whose block answers true; inject:into: combines values starting from an accumulator. Array and string indexing begins at 1. An Array has a fixed size; an OrderedCollection can grow.

Smalltalk · select all, then Print it
| numbers doubled evens total |
numbers := #(1 2 3 4 5).
doubled := numbers collect: [:each | each * 2].
evens := numbers select: [:each | each even].
total := numbers inject: 0 into: [:sum :each | sum + each].
{doubled. evens. total}
Download .st
Result#(#(2 4 6 8 10) #(2 4) 15)
See the real Squeak screenshot
Squeak Workspace: Transform, filter, and reduce with evaluated result #(#(2 4 6 8 10) #(2 4) 15)
Actual Squeak Workspace. The evaluated result was inserted beneath the code for this capture. Open the image for full-size detail.
Try itChange the numbers. The result contains the doubled array, even values, and total, in that order.
11

LANGUAGE IN PRACTICE

One receiver, several messages

A semicolon makes a cascade: add both strings to the same new collection. The final yourself answers that collection; without it, the last add: answers the added string. A period instead ends an expression. In a sequence you would first assign the collection to a variable, then send each message using that variable again. Ordinary message chaining uses each previous answer as the next receiver.

Smalltalk · select all, then Print it
OrderedCollection new
    add: 'Squeak';
    add: 'Smalltalk';
    yourself
Download .st
Resultan OrderedCollection('Squeak' 'Smalltalk')
See the real Squeak screenshot
Squeak Workspace: One receiver, several messages with evaluated result an OrderedCollection('Squeak' 'Smalltalk')
Actual Squeak Workspace. The evaluated result was inserted beneath the code for this capture. Open the image for full-size detail.
Try itAdd a third add: line before yourself. Keep a semicolon after each earlier message.
12

LANGUAGE IN PRACTICE

Build a study-session summary

Put the ideas together. Store four session lengths, total them with a block, compute the average, find the longest, and assemble a readable string. printString converts each number to text. The parentheses are unnecessary around minutes size because unary messages run before division. Here asFloat gives an easy-to-read decimal average.

Smalltalk · select all, then Print it
| minutes total average longest summary |
minutes := #(25 40 15 30).
total := minutes inject: 0 into: [:sum :each | sum + each].
average := total / minutes size.
longest := minutes max.
summary := 'Sessions: ', minutes size printString,
    ' | Total: ', total printString, ' min',
    ' | Average: ', average asFloat printString, ' min',
    ' | Longest: ', longest printString, ' min'.
summary
Download .st
Result'Sessions: 4 | Total: 110 min | Average: 27.5 min | Longest: 40 min'
See the real Squeak screenshot
Squeak Workspace: Build a study-session summary with evaluated result 'Sessions: 4 | Total: 110 min | Average: 27.5 min | Longest: 40 min'
Actual Squeak Workspace. The evaluated result was inserted beneath the code for this capture. Open the image for full-size detail.
Try itReplace the four session lengths with your own positive values. Keep at least one session to avoid division by zero.

A FEW RULES WORTH KEEPING

Avoid the usual surprises

  • Periods separate expressions. They are not decimal points unless inside a number, and they are not interchangeable with semicolons.
  • Use := for assignment. Use = for value equality; == asks whether two references identify the same object.
  • Case matters. Keep class names, variable names, and message spelling exactly as shown.
  • Quotes do different jobs. Single quotes make strings; double quotes make comments.
  • Binary messages run left to right. Add parentheses when you want conventional arithmetic grouping.
  • Blocks need evaluation. A block by itself is an object containing deferred work, not its eventual result.
  • A message-not-understood error has a receiver. Inspect what object received the message; it may be an intermediate answer you did not expect.

Use the Browser to inspect the implementation of messages such as size, collect:, and ifTrue:ifFalse:. Squeak lets you learn from the system you are running.

PUT THE LANGUAGE TO WORK

Now give your objects a shape.

You know how to send messages, build blocks, and compose results. Use those same ideas to draw, interact, and animate.

Continue to Morphic objects

Read further

Older references can differ in terminology and interface details. All 12 main snippets and their results were verified in the Squeak image used for these screenshots. The page does not execute Smalltalk in your browser.