How to make a Squeak class from scratch?

181 Views Asked by At

I want to make a simple program in Squeak that calculates the distance between a couple of points, but I would not like to use the class Point that is already defined. So far I have the following:

enter image description here

The getter and setter methods of x and y have been auto generated:

x ^ x

x: anObject x := anObject.

and the distance method I programmed is the following: enter image description here

distance:aPoint
    "comment stating purpose of message"

    |dx dy |
    dx:=aPoint x - x.
    dy:=aPoint y - y.
    ^ (dx*dx+dy*dy) sqrt.

now I open a workspace and try to print out the results:

obj1:=PointS new.
obj1 x:3 y:4.
obj2:=PointS new.
obj2 x:5 y:6.
d:=obj1 distance obj2
UIManager default inform: 'Converted amount: ',d.

but the result I get is the following:

enter image description here

What am I missing?

2

There are 2 best solutions below

0
James Foster On BEST ANSWER

Try replacing the following:

obj1 x:3 y:4.

With this:

obj1 x:3; y:4.

Basically, you are sending the message #x:y: but you don't have a method with that name. Instead you have a method #x: and another method #y:, so you need to make two separate calls to the same object (which is done with the cascade operator (#;).

0
Leandro Caniglia On

Watch the precedence

In your method distance: aPoint you are computing the Pythagorean distance as

(dx*dx + dy*dy) sqrt

While this formula is correct in the usual mathematical notation and in most programming languages, in Smalltalk it will work differently. In fact it will produce the same as

((dx*dx + dy)*dy) sqrt,

which is not what you want. The reason for this is that in Smalltalk both #* and #+ are binary operators with the same precedence. Thus, you should write

((dx*dx) + (dy*dy)) sqrt

instead, or equivalently

(dx*dx + (dy*dy)) sqrt

since you only need to make sure that dy*dy is the argument of #+.

A more elegant way to achieve the same is

(dx squared + dy squared) sqrt.

Also, if you take a look at the Point class you will find the #r method from polar coordinates that would give the desired result if you write

(dx @ dy) r.