Booleans & Logic

Use and:/or: whenever the right side is expensive or unsafe to evaluate.

12.1 Boolean messages

true & false.                  "→ false (evaluates both sides)"
true | false.                  "→ true"
true not.                      "→ false"
true xor: false.               "→ true"
(3 > 2) and: [ 2 > 1 ].        "→ true — short-circuit: the block is evaluated only if needed"
(3 < 2) or: [ 1 / 0 ].         "raises ZeroDivide: the receiver is false, so or: must evaluate the block"
(3 > 2) or: [ 1 / 0 ].         "→ true, block never evaluated"
x notNil and: [ x > 0 ].       "safe: x > 0 only runs when x is not nil"

12.2 and:/or: vs &/|

Short-circuit (lazy) Eager — both sides evaluated Use and:/or: whenever the right side is expensive or unsafe to evaluate. Pharo also has and:and: and or:or: for several blocks.

12.3 Truthiness

Unlike many languages, Smalltalk has no truthiness: only true and false respond to ifTrue:. nil ifTrue: [...] raises NonBooleanReceiver / doesNotUnderstand:. Test explicitly with isNil, notNil, isEmpty, isZero.

🧪 Part I Exercises

Install Pharo 13 with the Pharo Launcher; create two images, evaluate Smalltalk version and Smalltalk vm version in each, and explain what the image, changes, and sources files are for.

In a Playground, predict then check the results of 2 + 3 * 4, 2 + (3 * 4), 2 raisedTo: 2 + 1, and 3 factorial + 2 factorial * 2.

Print the class of: 42, 100 factorial, 3/4, 0.5, 3.5s2, $a, 'a', #a, #(1), #[1], nil, true, [], 3 @ 4, 1 -> 2, 1 to: 3.

Use Finder's *Examples* mode to discover the methods that turn 'smalltalk' into 'SMALLTALK' and #(3 1 2) into #(1 2 3).

Write a cascade that builds an OrderedCollection of the first five squares and returns the collection (use yourself).

Write a block isLeap that takes a year and answers whether it is a leap year; test it on 1900, 2000, 2024, 2026.

Create a counter generator using closures (like §10.3) and show that two counters are independent.

Print the multiplication table 1–10 to the Transcript using to:do: nested loops with aligned columns (printPaddedWith: $ to: 4 pads with spaces).

Show with an example why x notNil & (x > 0) fails when x is nil but x notNil and: [ x > 0 ] works.

Write a Collatz sequence generator using whileFalse:: starting from 27, count the steps to reach 1.