[Newbies] Does +, -, *, / have more precedence over power?
Jecel Assumpcao Jr.
jecel at merlintec.com
Sat Nov 11 23:55:28 UTC 2017
RedTigerFish wrote on Sat, 11 Nov 2017 15:12:06 -0700 (MST)
> I understand in Smalltalk numerical calculation, if without round brackets,
> everything starts being calculated from left to right. Nothing follows the
> rule of multiplication and division having more precedence over addition and
> Like the following codes
> 3 + 3 * 2
> The print output is 12 while in mathematics we get 9
You are right. See C for an example of how complicated things can get if
you want to have a bunch of precendence rules. And C has a fixed set of
such operators while in Smalltalk we can define a bunch of new operators
(binary selectors - see below) and then what should the precendence be
compared to the existing ones?
So the decision was made to go for simplicity even though that
contradicts the goal of not surprising beginners if possible.
> But when I started to try power calculation, like
> 91 raisedTo: 3 + 1.
> I thought the answer should be 753572
> What I actual get is 68574964
> Why's that?
> Is it because that +, -, *, / have more precedence over power ?
Yes, but the rules are simple and general which should make them easy to
Smalltalk messages have three different forms:
- unary messages are a simple alphanumerical name which follows the
expression defining the object which will receive the message:
- binary messages have names composed entirely of "graphics characters"
and the follow the expression defining the receiver and come before the
expression defining the single argument:
3 + 4
7 <= 9
Unary selectors have a higher precedence than binary ones, so
3 + 4 factorial
is the same thing as
3 + (4 factorial)
(3 + 4) factorial
- keyword messages have names which are one or more alphanumerical
words, each followed by a colon character. The first word comes after
the receiver and each colon is followed by an argument:
91 raisedTo: 3
4 between: 1 and: 7
Keyword selectors have the lowest precedence of all, so
91 raisedTo: 3 + 1
is the same as
91 raisedTo: (3 + 1)
(91 raisedTo: 3) + 1
So there are only three simple rules to remember, but even so you will
often see code which uses more parenthesis (curved brackets) than needed
just to make sure.
One ugly part of Smalltalk syntax is that though "-" is a binary message
the same character is used for negative literal numbers.
also returns 1.
2 * -1
is a syntax error with a dialog asking you to fix it.
With all that, we can mix all three kinds of selectors:
91 raisedTo: 3 + -1 abs
also returns 68574961.
More information about the Beginners