typestar

Booleans in Smalltalk

and:/or: take blocks and short-circuit; & and | do not.

"and:/or: take blocks and short-circuit; & and | do not."
| inked paperLoaded |
inked := true.
paperLoaded := false.

(inked and: [paperLoaded])
    ifTrue: [Transcript show: 'Pull an impression'; cr]
    ifFalse: [Transcript show: 'Not ready'; cr].

(inked or: [1/0 > 0])
    ifTrue: [Transcript show: 'Short-circuit saved us'; cr].

Transcript show: (inked & paperLoaded) printString; cr.
Transcript show: inked not printString; cr.
Transcript show: (inked xor: paperLoaded) printString; cr.

How it works

  1. and: evaluates its block only when needed.
  2. The or: demo would divide by zero without the shortcut.
  3. not and xor: round out the protocol.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
481
Tokens
86
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 86 seconds.

Type this snippet

Step 3 of 3 in Messages & blocks, step 6 of 31 in Language basics.

← Previous Next →