(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 thereduced
message.E.g. if you print the result of
you get the reduced
(1/2)
automatically.If you print the result of
it is reduced to
1
which is not a Fraction, but an Integer, and Integers do not understand thereduced
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
which will answer the non-reduced
(2/4)
. But in normal arithmetic expressions you never need to sendreduced
.The error occurs because by default, the
Integer
class does not understand the messagereduced
in Squeak. This despite members of Squeak'sInteger
class being fractions.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 messagereduced
and you want it to, then you can add areduced
method toInteger
with the expected behavior:Adding methods to Classes is the way Smalltalk makes it easy to write expressive programs. For example,
Fractions
in GNU Smalltalk understand the messagereduce
but not the messagereduced
available in Squeak. Rather than trying to remember a meaningless difference, the programmer can simply makereduced
available to fractions in GNU Smalltalk:Likewise one can extend
Fraction
in Squeak to have areduce
method:The designers of Smalltalk made a language that let's programmers express themselves in the way that they think about the problem.