I had a problem returning an answer to task 9 P-99: Ninety-nine journal issues :
Set consecutive duplicates of list items in sublists. If the list contains duplicate elements, they must be placed in separate sublists.
An example query with expected results:
?- pack([a,a,a,a,b,c,c,a,a,d,e,e,e,e],X).
X = [[a,a,a,a],[b],[c,c],[a,a],[d],[e,e,e,e]].
I managed to collect the items in the sublists, but I don’t know how to return the answer.
Here is my code:
pack(X,Y) :- pack(X,[],Y).
pack([H,H|T],Acc,X) :- pack([H|T],[H|Acc],X).
pack([H,H1|T], Acc, X) :-
H\=H1,
Acc1=[H|Acc],
append(X, [Acc1], X1),
pack([H1|T],[],X1).
pack([H], Acc, X) :-
Acc1=[H|Acc],
append(X, [Acc1], X1).
Here the request is executed in trace mode:
?- trace, pack([a,a,a,a,b,c,c],X).
Call: (6) pack([a, a, a, a, b, c, c], _G986) ? creep
Call: (7) pack([a, a, a, a, b, c, c], [], _G986) ? creep
Call: (8) pack([a, a, a, b, c, c], [a], _G986) ? creep
Call: (9) pack([a, a, b, c, c], [a, a], _G986) ? creep
Call: (10) pack([a, b, c, c], [a, a, a], _G986) ? creep
Call: (11) a\=b ? creep
Exit: (11) a\=b ? creep
Call: (11) _G1100=[a, a, a, a] ? creep
Exit: (11) [a, a, a, a]=[a, a, a, a] ? creep
Call: (11) lists:append(_G986, [[a, a, a, a]], _G1105) ? creep
Exit: (11) lists:append([], [[a, a, a, a]], [[a, a, a, a]]) ? creep
Call: (11) pack([b, c, c], [], [[a, a, a, a]]) ? creep
Call: (12) b\=c ? creep
Exit: (12) b\=c ? creep
Call: (12) _G1109=[b] ? creep
Exit: (12) [b]=[b] ? creep
Call: (12) lists:append([[a, a, a, a]], [[b]], _G1114) ? creep
Exit: (12) lists:append([[a, a, a, a]], [[b]], [[a, a, a, a], [b]]) ? creep
Call: (12) pack([c, c], [], [[a, a, a, a], [b]]) ? creep
Call: (13) pack([c], [c], [[a, a, a, a], [b]]) ? creep
Call: (14) _G1127=[c, c] ? creep
Exit: (14) [c, c]=[c, c] ? creep
Call: (14) lists:append([[a, a, a, a], [b]], [[c, c]], _G1132) ? creep
Exit: (14) lists:append([[a, a, a, a], [b]], [[c, c]], [[a, a, a, a], [b], [c, c]]) ? creep
Exit: (13) pack([c], [c], [[a, a, a, a], [b]]) ? creep
Exit: (12) pack([c, c], [], [[a, a, a, a], [b]]) ? creep
Exit: (11) pack([b, c, c], [], [[a, a, a, a]]) ? creep
Exit: (10) pack([a, b, c, c], [a, a, a], []) ? creep
Exit: (9) pack([a, a, b, c, c], [a, a], []) ? creep
Exit: (8) pack([a, a, a, b, c, c], [a], []) ? creep
Exit: (7) pack([a, a, a, a, b, c, c], [], []) ? creep
Exit: (6) pack([a, a, a, a, b, c, c], []) ? creep
X = [] .
I assume that at the end of the last rule an additional line should be added in order to somehow associate the result with the input, but I have no idea how to do this.