JinseiNagai
JinseiNagai

Reputation: 351

(Prolog) Finding neighbors in a list

We have to write a Prolog predicate neighbors(X,Y,L) which is true if L is a list and X and Y are neighbor elements in the list. So far I wrote:

neighbors(X,X,[X]).
neighbors(X,Y,[X,Y|R]):- neighbors(X,Y,R).
neighbors(X,Y,[Y,X|R]):- neighbors(X,Y,R).`

but the output would always give (obviously) empty brackets ( "[]" ) no matter the input. So can you guys give me some advice on how to improve this predicate? We recently started with the Prolog so I still need some practise with it.

Upvotes: 0

Views: 1754

Answers (3)

Parag Himanshu Dave
Parag Himanshu Dave

Reputation: 1

neighbors(X,Y,Z) :- append(_,[X|[Y|_]],Z). 

Upvotes: -2

joel76
joel76

Reputation: 5645

You should use append :

neighbors(X,X,[X]).

neighbors(X,Y,L) :-
      append(_, [X,Y|_], L)
    ; append(_, [Y,X|_], L).

Upvotes: 2

JinseiNagai
JinseiNagai

Reputation: 351

So I kinda kept trying and found the answer by myself.

I had to consider 2 cases:

  1. X and Y is neighbor with X,Y so neighbors(X,Y,[X,Y|_]).

  2. X and Y is neighbor with Y.X so neighbors(X,Y,[Y,X|_]).

And also we have to check through the whole list skipping every element which is irrelevant to us (all elements that does not match X or Y). That can be done using a recursion neighbors(X,Y,[F,S|R]) :- neighbors(X,Y,[S|R]).

so the whole predicate should be

neighbors(X,Y,[X,Y|_]). 
neighbors(X,Y,[Y,X|_]).
neighbors(X,Y,[F,S|R]) :- neighbors(X,Y,[S|R]).

so far, this gives the correct outputs for every input but if there is still something wrong then please advise me on it. Thanks.

Upvotes: 1

Related Questions