Earlier, we discussed how Cuis-Smalltalk knows about rational numbers. The four arithmetic operations and mathematical functions are implemented with unary and binary messages understood by the rational numbers:
(15 / 14) * (21 / 5) ⇒ 9 / 2 (15 / 14) / ( 5 / 21) ⇒ 9 /2 (3 / 4) squared ⇒ 9 / 16 (25 / 4) sqrt ⇒ 5 / 2
Write the code to compute the sum of the squares of the inverse of the first four integers.
If Cuis-Smalltalk integer division returns a rational number, how do we find the result in decimal? One option is to write a number as a floating point literal, a Float. This kind of literal is written with the integer and fractional parts separated by a dot “.”:
15.0 / 4 ⇒ 3.75 15 / 4.0 ⇒ 3.75
Another option is to convert an integer to a float with the
#asFloat
message. It is very useful when the integer is in a
variable:
15 asFloat / 4 ⇒ 3.75
You can also ask for division with truncation to
get an integer result using
the message #//
:
15 // 4 ⇒ 3
The modulo remainder of the Euclidean division is computed with the message
#\\
:
15 \\ 4 ⇒ 3
Cuis-Smalltalk has arithmetic operations to test if an integer is odd, even, a prime number, or divisible by another. You just send the appropriate unary or keyword message to the number:
25 odd ⇒ true 25 even ⇒ false 25 isPrime ⇒ false 23 isPrime ⇒ true 91 isDivisibleBy: 7 ⇒ true 117 isDivisibleBy: 7 ⇒ false 117 isDivisibleBy: 9 ⇒ true
With specific keyword messages you can compute the Least Common Multiple and Greatest Common Divisor. A keyword message is composed of one or more colons “:” to insert one or more arguments:
12 lcm: 15 ⇒ 60 12 gcd: 15 ⇒ 3
In the Spacewar! game, the central star is the source of a gravity field. According to Newton’s law of universal gravitation, any object with a mass – a spaceship or a torpedo in the game – is subjected to the gravitational force. We compute it as a vector to account for both its direction and its magnitude. The game code snippet below shows a (simplified) mixed scalar and vector calculation done with message sending (See Figure 2.4):
-10 * self mass * owner starMass / (position r raisedTo: 3) * position