I'm trying to write a rule in prolog
adjacent(X,Y,Zs)
, as true
if X
and Y
are adjacent to each other in the list Zs
.
I currently have:
append([],L,L).
append([H|T],L,[H|LT]):-append(T,L,LT).
sublist(S,L):-append(_,S,P),append(P,_,L).
adjacent(X,Y,Zs):-sublist([X,Y],Zs).
test:
1 ?- sublist([1,2],[1,2,3,4]).
true .
2 ?- sublist([1,3],[1,2,3,4,5]).
ERROR: Out of global stack
3 ?-
Do you guys have any ideas? Thanks in advance.
adjacent(X,Y, [X,Y|_]).
adjacent(X,Y, [Y,X|_]). % remove this if you want just Y after X
adjacent(X,Y, [_|T]) :- adjacent(X,Y,T).
that should work.
also, you have a predicate in the lists library called nextto(?X, ?Y, ?List)
that will do the same (but keep in mind that the semantics of this predicate is that Y
follows X
in the list, not just plain adjacent in any order).