Zero
Zero

Reputation: 453

Consecutive elements in a list

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!

Upvotes: 3

Views: 3105

Answers (3)

false
false

Reputation: 10102

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 -formalism:

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

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

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

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

Upvotes: 4

joel76
joel76

Reputation: 5675

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)).

Upvotes: 2

Tudor Berariu
Tudor Berariu

Reputation: 4910

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.

Upvotes: 5

Related Questions