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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With