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
"(3, 4)"
), x
coordinates and the same y
coordinates),sqrt(x2+y2)
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.
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
copy-posn
function that returns a new posn with the
same coordinates as the old one (but not the same object,
i.e. if one of them were to be mutated, it wouldn't affect the
other one),posn->string
function that converts a posn to a
nicely-formatted string,posn=?
function that tells whether two posns have the
same coordinates,posn+
and posn-
which take in
two posns and add or subtract them coordinate-by-coordinate,posn*
function that takes a posn and a number and
multiplies each coefficient by that number,posn-magnitude
function that computes the distance of
the posn from (0, 0)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
posn+
which takes in three posns and succeeds if the
third is the coordinate-wise sum of the first two,posn-
which takes in three posns and succeeds if the
third is the coordinate-wise difference of the first two,posn*
which takes in a number and two posns,
and succeeds if the last posn is the scalar product of the number
and the first posn,posn-magnitude
which takes in a posn and a number,
and succeeds if the number is the magnitude of the posn.
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
eval-posn(2*posn(3,4)-3*(posn(5,2)-posn(2,1)), What).
and get the answer
What = posn(-3,5)