Consecutive elements in a list
Asked Answered
C

3

3

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!

Counterchange answered 8/6, 2014 at 13:12 Comment(3)
Have you tried coding either one of these? Please share the results so that we could help you correct your code.Donielle
For the first one, in this list, I'm trying to extract 2 first elements of L : u(L,P) :- ([ [P,P] | L ], P). But ... I've got no idea, I think the solution is simple ... I need to use recursivityCounterchange
Then you should unify L with a list [First, Second | Tail].Joanniejoao
J
5

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.

Joanniejoao answered 8/6, 2014 at 13:33 Comment(1)
Thanks a lot, so it works for V with another _ :) ... We got it !Counterchange
P
4

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.
Proton answered 8/6, 2014 at 13:18 Comment(1)
The fact is that ... With 2 parameters that's not logical ... We are 5 friends trying to learn Prolog, our exam is in 2 days ... Please help us ...Counterchange
R
2

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)).
Readytowear answered 8/6, 2014 at 15:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.