I have a problem with returning an answer to Problem 9 of P-99: Ninety-Nine Prolog Problems:
Pack consecutive duplicates of list elements into sublists. If a list contains repeated elements they should be placed in separate sublists.
Sample 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 pack elements in sublists but I don't know how to return an answer.
Here's 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's a query run 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 imagine there should be additional line at the end of last rule to somehow bind the result to the input but I have no idea how to do it.