caz
caz

Reputation: 27

print out letter squences in prolog

I have to write out a program in Prolog that prints out letter sequences, Implement in Prolog a predicate twist/2 for ‘twisting’ pairs of entries of a list and discarding the entries in between. More precisely,

• Interchange the 1st and 2nd entries,

• Discard the 3rd entry,

• Interchange the 4th and 5th entries,

• Discard the 6th entry and so on as follows:

twist([’B’,r,a,d,f,o,r,d], T)--->
twist([’B’,r,a,d,f,o,r,d], [], y, T)--->
twist([a,d,f,o,r,d], [’B’,r], n, T)--->
twist([d,f,o,r,d], [’B’,r], y, T)--->
twist([o,r,d], [d,f,’B’,r], n, T)--->
twist([r,d], [d,f,’B’,r], y, T)--->
twist([], [r,d,d,f,’B’,r], n, T)--->
reverse([r,d,d,f,’B’,r], T)--->
T = [r,’B’,f,d,d,r] ---> success

So far I have:

twist(L,T) :-
   twist(L, [], y, T).  % clause 0: invoke auxiliary predicate

twist([], Acc, L)       :- reverse(Acc, L),
twist(A,G,_|T), Acc, L) :- twist(T,[A,G|Acc], L),
twist([A,G], Acc, L)    :- twist([],[A,G|Acc], L),
twist([], Acc, L)       :- reverse(Acc, L).

I'm sure that's right but i keep getting the same error.

here's the full error message:

 4 ?- twist([b, r ,a ,d ,f ,o ,r ,d], T).
 ERROR: twist/2: Undefined procedure: twist/4
 ERROR:   However, there are definitions for:
 ERROR:         twist/2
 Exception: (7) twist([b, r, a, d, f, o, r, d], [], y, _G2583) ?

Any help would be great.

Upvotes: 1

Views: 87

Answers (1)

Yasel
Yasel

Reputation: 3120

try this:

twist([],[]).
twist([X],[X]).
twist([X,Y],[Y,X]).
twist([X,Y,_|Tail],[Y,X|NewTail]):- twist(Tail, NewTail).

And then ask:

?- twist([b, r ,a ,d ,f ,o ,r ,d], T).
T = [r, b, f, d, d, r] ;
false.

credits go to @lurker.

Upvotes: 1

Related Questions