CSC 270
Homework 3.5

C++ or Java version

What I want you to do

Write a definition of a class named Pair that holds an ordered pair of numbers representing (x,y) Cartesian coordinates. It should be possible to

.

C version:

You can't write a Pair class, because C doesn't have classes. However, you can define a struct to hold all the information you need to keep track of, and you can write a bunch of functions that take in such a struct as a parameter. Put all these functions in one source file (say, pair.c), with a header file (pair.h) that declares the struct and the functions; the main program can be written in a separate file, include-ing the header file, and linked together with the separately-compiled pair object file.

Scheme version:

DrScheme already has a posn structure with coefficients x and y, with constructor make-posn and getters posn-x and posn-y. However, you can still write

Prolog version:

The easiest way to do this in Prolog is with a struct, e.g. posn(3,4). There's no need to write constructors or getters for this struct in Prolog, since that can all be done more easily by simple unification. Likewise, there's no point in writing an "are these two posns the same?" rule, since unification does that easily. But you can still write

If you want to make things look a little more "natural", consider that Prolog "knows" about infix operators like +, -, *, etc. It only knows what they "mean" as applied to numbers with the is built-in rule, but you can define your own rule that allows you to write algebraic expressions on posns too: write an eval-posn rule that takes in an "expression" and a posn, and succeeds if the expression "evaluates to" the posn. An "expression" can be either

So by the time this is over you should be able to write
eval-posn(2*posn(3,4)-3*(posn(5,2)-posn(2,1)), What).
and get the answer
What = posn(-3,5)


Last modified: 
Stephen Bloch / sbloch@adelphi.edu