April 25, 2024

Answer to Q2

 

aToad position: aFrog position + 3 * 2 -  aToad position
The answer returned is aToad
The position of aToad is -3
Explanation.
A Toad instance will always return itself when it receives the keyword message position:
There are no brackets in the message expression above. It could have been written
aToad position: (aFrogposition + 3 * 2 -  aToad position)
or
aToad position: ((aFrogposition) + 3 * 2 -  aToad position)
or
aToad position: ((aFrogposition) + 3 * 2 -  (aToad position))
All these expressions would yield the same answer. Without any brackets Smalltalk reads left to right and evaluates the first unary expression it finds, in this case
aFrog position. This returns the number object 1.
Smalltalk continues its search for unary expressions and finds aToad position. This returns the number object 11.
In effect Smalltalk must now evaluate aToad position: 1 + 3 * 2 -  11
Reading left to right, binary before keyword, the number object 1 receives the binary message + 3 and returns the number object 4.
4 now becomes the receiver of the binary message * 2 and returns the number object 8.
8 becomes the receiver of the binary message - 11 and returns the number object -3.
-3 is passed as the argument to the keyword selector position: and aToad finally receives the keyword message position: -3
aToad returns itself as the message answer. Remember the textual representation of this message answer object is not aToad but
An instance of class Toad (position -3, colour Brown)

 

Back to « Basic Questions on Precedence

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Up to top of page