Here’s A Point

For a long time the “Hello, World!” program was the first app a programmer tried with a new language or situation. It’s a quick way to test the general operation of things.

When it comes to object-oriented languages, an object-oriented first program needs a simple object. I’ve long thought that the “XY Point” made an outstanding “Hello, World!” object. It’s basically very simple, so it’s easy to do. And you can extend on it nicely once you get your Point working. You can extend a 2D Point to a 3D Point, or use Points to create Shapes.

This article is about how you create a Point Model in BOOL.

We start by defining a (2D) Point Model:

.   *number  x = 0
.   *number  y = 0
.   @@reset::
.   <<  !
.   .   set: !x 0 ;
.   .   set: !y 0 ;
.   @@set::
.   >>  *number  x
.   >>  *number  y
.   <<  !
.   .   set: !x x ;
.   .   set: !y y ;
.   @@move::
.   >>  *number  x
.   >>  *number  y
.   <<  !
.    .    set: !x add: !x x ;
.    .    set: !y add: !y y ;

The code above defines a new Model, called *2dPoint. This illustrates an interesting feature of BOOL: Model names can start with a digit!  (Model names are always prefixed with at least one asterisk, so there is no risk of mistaking them for a number.)

This Model has two data members, both instances of the *number Model (which is a generic numeric type). I could also have used the *int or *real Models for a specific binary representation. By default, a new 2dPoint Object has both data members initialized to zero.

The Model also has three Model Actions (methods): @reset, @set and @move. Since these are Model Actions, they are automatically bound to the reset:, set: and move: Messages, respectively. The first takes no parameters, the other two both take an x and y *number object. All three return the Object itself.

Now we can create some *2dPoint instances:

.   *2dPoint  p1 = 10,10  -- create new point at [10,10]
.   *2dPoint  p2 = p1     -- create a duplicate of p1
.   move: p1 3,6 ;        -- move p1 to [3,6]
.   reset: p2 ;           -- reset p2 (back to [0,0])

It might be nice to get back a distance between two points, so let’s say we’d added a Model Action for that (the fragment below could appear anywhere before the one directly above):

.   >>  *2dPoint  p
.   <<  *number  h
.   .   *number  x2 = sqr:sub:!x [x]p ;;
.   .   *number  y2 = sqr:sub:!y [y]p ;;
.   .   set:h sqrt:add: x2 y2 ;;

Now we could continue with the @2dPoint-Demo code:

.   *number  dist
.   set:dist distance:p1 p2 ;;
.   print: "Distance is: %n",dist ;

I realize most of this seems fairly opaque at this point. It will all be made clear over time!

%d bloggers like this: