“:=” and binary message precedence in Smalltalk

2019-05-06 23:34发布

问题:

I am attempting to learn Smalltalk through the tutorials included with Dolphin Smalltalk X6.

My question deals with the evaluation of expressions with multiple messages.

My understanding is that simple messages are evaluated first, then binary messages, and finally keyword messages (with the exception of code in parenthesis). However, I am having trouble applying this understanding to the second line in the following example (found in the Dolphin Smalltalk tutorial).

    playground := Playground new.
    teresa := playground add: Triangle new.       "Misunderstood code"
    teresa class.                                 "Evaluates to 'Triangle'"

If my understanding were correct, the 2nd line would be evaluated thusly:

    1. Simple message 'new' sent to Triangle, triangle object as response
    2. Binary message ':=' with parameter 'playground' sent to 'teresa'.
    3. Keyword message 'add:' with parameter 'triangle object' sent to 'teresa'.
    4. teresa class. "evaluates to 'Playground'".

My misunderstanding is in how 'teresa' comes to refer to the anonymous Triangle object and not the Playground object referred to by 'playground'.

I have looked up a second explanation of Smalltalk evaluation for mentions of := or add: being special cases with no success, and the only other explanation I can think of is a fundamental misunderstanding.

Any help straightening me out?

回答1:

While := looks like a binary message because it uses infix characters... it is not. It's a part of the language syntax in the same way that parens and periods are (for example).

Think of := as the assignment operator (sometimes spoken as "gets"). It is NOT a message of any precedence. It is evaluated AFTER any message sends. It's lvalue MUST be a direct variable reference (not the results of a message send).



回答2:

The Assignment operator (:=) isn't a message. (It's not sent to an object, instead it indicates that a variable should be set to a value). Its precedence is last overall.

So what happens is:

  1. Simple message 'new' send to Triangle, triangle object as response
  2. keyword message add: sent to playground, and there's a convention that add: messages answer the object added, which this one seems to follow, so the newly created triangle is returned.
  3. The variable teresa is set to the new triangle
  4. teresa class. "evaluates to Triangle".