Reputation: 41
So my objective here is to write a predicate that rotates a list to the right N times if N>0 or the left N times if N<0. Here is my code so far, the output is false unless N == 0 and I am not sure where my issue is.
rotateleft([L|R], N) :-
append(R, [L], N).
rotateright(L, R) :-
rotateleft(R, L).
rotate(L,N,R) :-
( N = 0 ->
R = L
; N > 0 ->
rotateright(L,R),
N is N-1,
rotate(L,N,R)
; N < 0,
rotateleft(L,R),
N is N+1,
rotate(L,N,R)
).
Upvotes: 3
Views: 988
Reputation: 10102
list_rotated(N, Xs, Ys) :-
maplist(\_^_^true, Xs, Ys), % or same_length(Xs, Ys)
length(Xs, M),
R is -N mod M,
length(As, R),
append(As,Bs, Xs),
append(Bs,As, Ys).
Please note that this definition has much better termination behavior. It terminates iff the length of one of the lists is known.
Upvotes: 3