1
votes

I'm sure this is rather basic, though I couldn't find it on here by searching.

I'm learning prolog and found an example with rules: (representing adjacency)

adj(1, 2).    adj(2, 1).
adj(1, 3).    adj(3, 1).
adj(3, 4).    adj(4, 3).

Now, this struck me as a little wasteful, since we know that adjacency is a reciprocal relationship, it should be enough to define only one of each pair, and then define:

adj(X, Y) :-
    adj(Y, X), !.

I understand why this simplistic attempt doesn't work; it falls into an infinite loop if X and Y aren't adjacent. But, I haven't quite figured out how to modify this to work in all cases.

1

1 Answers

3
votes

you should introduce an alternative name and code your logic using that. For instance

adj(1, 2).
adj(1, 3).
adj(3, 4).

is_adj(X,Y) :- adj(X,Y) ; adj(Y,X).