Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consecutive elements in a list

Tags:

prolog

dcg

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!

like image 278
Zero Avatar asked Mar 21 '26 09:03

Zero


2 Answers

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.

like image 185
Tudor Berariu Avatar answered Mar 22 '26 23:03

Tudor Berariu


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.
like image 25
false Avatar answered Mar 22 '26 23:03

false



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!