Sequential List Items

I block a predicate for code in Prolog . I need to encode two predicates:

If I call:, u([a,b,c,d,e,f], X).he will give X=[a,b], X=[b,c], X=[c,d]...

If I call:, v([a,b,c,d,e,f], X).he will give X=[a,b], X=[c,d], X=[e,f]...

Thank you so much!

+3
source share
3 answers

Although the false answer is more elegant, here is a solution more suitable for newbies to your predicate u/2.

u([X,Y|_], [X,Y]).
u([_|Tail], XY):- u(Tail,XY).

The first rule says that it [X,Y]represents two consecutive items in a list if they are the first two items in this list.

The second rule states that two elements are sequential in the list if they are somewhere in a row at the tail of the list.

Now try to find a similar solution for v/2.

+4

X=[a,b], X=[b,c], X=[c,d] ...., X=[a,b] ; X=[b,c] ; X=[c,d] ; ..., , Prolog -formalism:

u(Xs, [X,Y]) :-
   phrase(( ..., [X,Y], ... ), Xs).

... --> [] | [_], ... .

v(Xs, [X,Y]) :-
   phrase(( evenell, [X,Y], ...), Xs).

evenell --> [] | [_,_], evenell.
+3

I think 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)).
+2
source

All Articles