(2332 / 2332) reduced
(2332 / 2) reduced
(2332 / 322) reduced (1166/161)
(2332 / 3) reduced (2332/3)
(2332 / 2432423) reduced (2332/2432423)
Look at the above codes. The first and second, when printed, do not work. The MessageNotUnderstood window pops up. And the 3rd, 4th, 5th code are okay. Results come out right.
Why does the reduced
method not work?
Is it because the reduced method fails to handle final results which are integers like Uko guesses ?
Fractions are reduced automatically in the /
method. There is no need to send the reduced
message.
E.g. if you print the result of
2 / 4
you get the reduced (1/2)
automatically.
If you print the result of
2332 / 2332
it is reduced to 1
which is not a Fraction, but an Integer, and Integers do not understand the reduced
message. That's why you get an error.
The only case when a Fraction is not automatically reduced is when you create it manually, as in
Fraction numerator: 2 denominator: 4
which will answer the non-reduced (2/4)
. But in normal arithmetic expressions you never need to send reduced
.
The error occurs because by default, the Integer
class does not understand the message reduced
in Squeak. This despite members of Squeak's Integer
class being fractions.
5 isFraction "returns True"
The wonderful thing about Smalltalk is that if something does not work the way you want, you can change it. So if an Integer
does not respond to the message reduced
and you want it to, then you can add a reduced
method to Integer
with the expected behavior:
reduced
"treat an integer like a fraction"
^ self
Adding methods to Classes is the way Smalltalk makes it easy to write expressive programs. For example, Fractions
in GNU Smalltalk understand the message reduce
but not the message reduced
available in Squeak. Rather than trying to remember a meaningless difference, the programmer can simply make reduced
available to fractions in GNU Smalltalk:
Fraction extend [
"I am a synonym for reduce"
reduced [
^ self reduce
]
]
Likewise one can extend Fraction
in Squeak to have a reduce
method:
reduce
"I am a synonym for reduced"
^ self reduced
The designers of Smalltalk made a language that let's programmers express themselves in the way that they think about the problem.