March 19, 2024

Boolean Messages

 

=
aFrog = bFrog

  • Test for equality. Does the receiver aFrog have the same state as the argument bFrog? i.e. do their instance variables reference the same values? It does not test for object identity. Answers true or false.

==
aFrog == bFrog

  • Test for identity. Is aFrog the same object as bFrog? i.e. do they both reference the same memory address? This message selector is inherited by all Smalltalk objects, from Object, and is never overridden. Answers true or false.

The other comparison operators are:

~= "inequality"
< "less than"
> "greater than"
<= "less than or equal to"
>= "greater than or equal to"

More complex Boolean expressions can be constructed using three other Boolean operators. They are
and
or
not

and is written in Smalltalk as &. It takes two Boolean operands and returns true if both operands return true. Otherwise it answers false.

(3 < 4) & (5 < 6)
"evaluates to"
(true) & (true)
"answers true"

(6 > 7) & (4 < 9)
"evaluates to"
(false) & (true)
"answers false"

"Similarly"
true & false "answers false"
false & false "answers false"

or written in Smalltalk as | (the vertical bar, or pipe character)
It takes two Boolean operands and returns true if one or both of those operands returns true. Otherwise it will return false.

(2 < 5) | (9 > 18)
"evaluates to"
true | false
"answers true"

(20 < 10) | (5 > 1)
"evaluates to"
false | false
"answers false"

true | true "answers true"

not written in Smalltalk as not

Unlike the two previous binary operators not is a unary operator. It takes a single Boolean operand and negates that operand.

(10 > 5) not
"evaluates to"
true not
"answers false"

If you try and evaluate not true you will find that Smalltalk will ask you to create not as a variable. Remember true is the receiver of the not message and will return false as its message answer.

Similarly false not returns true

Go here for some Boolean questions and answer.

There are two other useful Boolean message selectors, and: , or:
Both of these selectors take blocks as their arguments. However, by using and:, as opposed to &, if the receiver happens to be false the argument to and: will not be evaluated. This is a far more efficient means of testing Boolean variables than the use of &, because in the latter case the block will be evaluated even if the receiver is false. Go here for an example of using and:

Similarly, try using or: instead of |.

Next page » Conclusion

Previous page « Branching

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Up to top of page