Squeak Smalltalk, why sometimes the reduced method doesn't work?

蹲街弑〆低调 提交于 2019-12-23 22:01:12

问题


(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 ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/46942103/squeak-smalltalk-why-sometimes-the-reduced-method-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!