Search code examples
prologdcg

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!


Solution

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