Reputation: 25
I'm trying to get my head around Prolog, and I am struggling somewhat with data structures.
I want to take a point(X,Y)
and reflect it along the "diagonal" X=Y
, so a point(-5,8)
becomes point(8,-5)
.
/* the following line is what I've gotten so far,
but I don't know how to manipulate the data inside the structures. */
reflection(X,Y) :- =(Y,X).
test_answer :-
reflection(point(-5,8), point(X,Y)),
write(point(X, Y)).
test_answer :-
write('Wrong answer!').
Should output point(8,-5)
.
Does this sort of thing even need data structures or am I over-thinking it?
Upvotes: 1
Views: 129
Reputation: 117185
The version of prolog I use (Strawberry Prolog) doesn't allow me to use the prefix notation for =
, so unless you prolog has a different meaning for =
then it appears that your code is this:
reflection(X,Y):- Y = X.
Which means that reflection\2
will only unify when the X
& Y
are unifiable.
So your code should result in point(-5,8)
and not point(8,-5)
as point(-5, 8)
is unifiable with point(X, Y)
when X = -5
& Y = 8
. You don't say what you do get in your question.
You need to use this rule to make it work:
reflection(point(X,Y),point(Y,X)).
Upvotes: 1
Reputation: 117007
You can just write:
reflection(point(A,B), point(B,A)).
If that is in the file reflection.prolog, then:
$ gprolog --consult-file reflection.prolog
...
| ?- reflection( point(1,2), X).
X = point(2,1)
yes
Upvotes: 3