BBbbBB
BBbbBB

Reputation: 87

Swapping list prefix and suffix in Prolog

I would like to make a program that swaps suffix and prefix of lists. This is expected result.

?- swap([a,b,c,d,e],[c,d],Xs).
Xs = [e,c,d,a,b] ;
false.

I am trying to solve it using a 4-tuple predicate with accumulator prefix.

swapPrefixSuffix(L, SL, R) :-
   swapPrefixSuffix(SL, L, R, Prefix).

swapPrefixSuffix(SL, L, R, []) :-
   append(SL,[_|_], L),
   Prefix = [],
   append(SL,Prefix,R).
swapPrefixSuffix(SL, [A|L], R, [A|Prefix]) :-
   swapPrefixSuffix(SL, L, R, Prefix).

This is what I have so far...

Upvotes: 2

Views: 506

Answers (1)

repeat
repeat

Reputation: 18726

No need to write recursive code—use the predefined predicates append/3 and same_length/2!

:- use_module(library(lists),[append/3,same_length/2]).

swap(XYZ,Y,ZYX) :-
   same_length(XYZ,ZYX),
   append(X,YZ,XYZ),
   append(Y,Z,YZ),
   append(Z,Y,ZY),
   append(ZY,X,ZYX).

Sample queries using SICStus Prolog 4.3.2:

?- swap([a,b,c,d,e],[c,d],Xs).
  Xs = [e,c,d,a,b]                    % as given by the OP
; false.

?- swap(Xs,[c,d],[e,c,d,a,b]).
  Xs = [a,b,c,d,e]                    % works in the "other direction", too!
; false.

How about a more general query?

?- XYZ=[_,_,_|_], Y=[_], swap(XYZ,Y,ZYX).
  XYZ = [_A,_B,_C]   , Y = [_A], ZYX = [_B,_C,_A]
; XYZ = [_A,_B,_C]   , Y = [_B], ZYX = [_C,_B,_A]
; XYZ = [_A,_B,_C]   , Y = [_C], ZYX = [_C,_A,_B]
; XYZ = [_A,_B,_C,_D], Y = [_A], ZYX = [_B,_C,_D,_A]
; XYZ = [_A,_B,_C,_D], Y = [_B], ZYX = [_C,_D,_B,_A]
; XYZ = [_A,_B,_C,_D], Y = [_C], ZYX = [_D,_C,_A,_B]
; XYZ = [_A,_B,_C,_D], Y = [_D], ZYX = [_D,_A,_B,_C]
...

Upvotes: 3

Related Questions