Reputation: 63
Say I have a list [1, 2, 3, 4, 5, 6, 7, 8]
, what I want to do is have an output of [[1,2], [3,4], [5,6], [7,8]]
.
This is my current attempt at doing this:
perms([X,Y], [X,Y], _).
perms(L, R, N) :-
N > 1,
N1 is N/2,
split(L, X1, X2),
perms(X1, R1, N1),
perms(X2, R2, N1),
append([R1], [R2], R).
split(L, R1, R2) :-
append(R1, R2, L),
length(L, N),
N1 is N/2,
length(R1, N1),
length(R2, N1).
Assume N
is the length of the list that I will enter manually.
Upvotes: 2
Views: 1122
Reputation: 7229
group([], []).
group([A, B | Tail], [[A, B] | NewTail]) :-
group(Tail, NewTail).
Test run:
?- group([1, 2, 3, 4, 5, 6, 7, 8], X).
X = [[1, 2], [3, 4], [5, 6], [7, 8]].
?- group([1, 2, 3, 4, 5, 6, 7], X).
false.
?- group([], X).
X = [].
Upvotes: 3
Reputation: 60034
The answer seems too much simple, I'm fairly sure I didn't understand your requirement. Anyway, you could try
pairs([X,Y],[[X,Y]]).
pairs([X,Y|R],[[X,Y]|T]) :- pairs(R, T).
Upvotes: 3