问题
I'm blocking on a predicate to code in Prolog. I need to code that two predicates:
If I call : u([a,b,c,d,e,f], X).
it will give X=[a,b], X=[b,c], X=[c,d]
...
If I call : v([a,b,c,d,e,f], X).
it will give X=[a,b], X=[c,d], X=[e,f]
...
Thanks a lot!
回答1:
Although false's answer is more elegant, here is a solution more appropriate for beginners for your predicate u/2
.
u([X,Y|_], [X,Y]).
u([_|Tail], XY):- u(Tail,XY).
The first rule says that [X,Y]
represent two consecutive elements in a list if they are the first two elements in that list.
The second rule states that two elements are consecutive in a list if they are consecutive somewhere in the tail of the list.
Now try to find a similar solution for v/2
.
回答2:
Assuming by X=[a,b], X=[b,c], X=[c,d] ....
you actually mean
X=[a,b] ; X=[b,c] ; X=[c,d] ; ...
, here is a solution using Prolog's dcg-formalism:
u(Xs, [X,Y]) :-
phrase(( ..., [X,Y], ... ), Xs).
... --> [] | [_], ... .
v(Xs, [X,Y]) :-
phrase(( evenell, [X,Y], ...), Xs).
evenell --> [] | [_,_], evenell.
回答3:
I think that you should use append :
u(L, [A,B]) :-
append(_, [A,B|_], L).
v(L, X) :-
append([A,B], L1,L),
( X = [A,B]; v(L1, X)).
来源:https://stackoverflow.com/questions/24106515/consecutive-elements-in-a-list