我在返回 P-99 问题 9 的答案时遇到问题:九十九个序言问题:
将列表元素的连续副本打包到子列表中。如果列表包含重复的元素,则应将它们放置在单独的子列表中。
具有预期结果的示例查询:
?- 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]].
我设法将元素打包到子列表中,但我不知道如何返回答案。
这是我的代码:
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).
这是在跟踪模式下运行的查询:
?- 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 = [] .
我想在最后一条规则的末尾应该有额外的行以某种方式将结果绑定到输入,但我不知道该怎么做。