Reputation: 351
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
Reputation: 5645
You should use append :
neighbors(X,X,[X]).
neighbors(X,Y,L) :-
append(_, [X,Y|_], L)
; append(_, [Y,X|_], L).
Upvotes: 2
Reputation: 351
So I kinda kept trying and found the answer by myself.
I had to consider 2 cases:
X and Y is neighbor with X,Y so neighbors(X,Y,[X,Y|_]).
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