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 subtraction.
Like the following codes
3 + 3 * 2
The print output is 12 while in mathematics we get 9
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 ?
Smalltalk does not have operators with precedence. Instead, there are three different kinds of messages. Each kind has its own precedence.
They are:
squared
or asString
in 3 squared
or order asString
;!%&*+,/<=>?@\~-
symbols and have one parameter as +
and ->
in 3 + 4
or key -> value
;raisedTo:
and to:by:do:
in 4 risedTo: 3
and 1 to: 10 by: 3 do: [ … ]
.Unary messages have precedence over binary and both of them have precedence over keyword messages. In other words:
unary > binary > keyword
So for example
5 raisedTo: 7 - 2 squared = 125
Because first unary 2 squared
is evaluated resulting in 4
, then binary 7 - 4
is evaluated resulting in 3
and finally keyword 5 risedTo: 3
evaluates to 125.
Of course, parentheses have the highest precedence of everything.
To simplify the understanding of this concept don't think about numbers and math all the numbers are objects and all the operators are messages. The reason for this is that a + b * c
does not mean that a
, b
, and c
are numbers. They can be humans, cars, online store articles. And they can define their own +
and *
methods, but this does not mean that *
(which is not a "multiplication", it's just a "star message") should happen before +
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With