(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,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.


  • You should use append :

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