next up previous contents
Next: Looping Up: Control-flow Previous: Boolean Logic   Contents

Basic Conditional Evaluation

Logical methods are provided which take a block as their second argument (/\, \/, and:, or:, xor:, eqv:). By accepting a block as the second argument, they can and do provide conditional evaluation of the second argument only in the case that the first does not decide the total result automatically5. Blocks that evaluate logical expressions can be used lazily in these logical expressions. For example,

(x < 3) /\ [y > 7].
only evaluates the right-hand block argument if the first argument turns out to be True.

(x < 3) \/ [y > 7].
only evaluates the right-hand block argument if the first argument turns out to be False.

In general, the basic of booleans to switch between code alternatives is to use ifTrue:, ifFalse:, and ifTrue:ifFalse: for the various combinations of binary branches. For example,

x isNegative ifTrue: [x: x negated].
ensures that x is positive by optionally executing code to make it positive if it's not. Of course if only the result is desired, instead of just the side-effect, the entire expression's result will be the result of the executed block, so that it can be embedded in further expressions.

Conditional evaluation can also be driven by whether or not a slot has been initialized, or whether a method returns Nil. There are a few options for conditionalizing on Nil:

expr ifNil: block
and expr ifNotNil: block execute their blocks based on whether the expression evaluates to Nil, and returns the result.
expr ifNil: nilBlock ifNotNil: otherBlock
provides both options in one expression.
expr ifNotNilDo: block
applies the block to the expression's result if it turns out to be non-Nil, so the block given must accept one argument. ifNil:ifNotNilDo: is also provided for completeness.


next up previous contents
Next: Looping Up: Control-flow Previous: Boolean Logic   Contents
Brian Rice 2004-08-24