我需要编写谓词partition/2
,以便在列表清单partition(L, P)
中的每个列表与列表P
相同时,L
满足P
。列表列表? - partition ([1 ,2 ,3] , P ).
P = [[1] , [2] , [3]];
P = [[1] , [2 , 3]];
P = [[1 , 2] , [3]];
P = [[1 , 2 , 3]];
no
? - partition (L , [[1] ,[2] ,[3 ,4 ,5]]).
L = [1 , 2 , 3 , 4 , 5];
no
可以包含任意数量的列表。
示例查询:
P
我尝试将L
中的列表连接在一起,然后检查它是否等于P
。这是我到目前为止所做的,但它不起作用。对于包含多个列表的任何partition([], []). ;; Partition of empty list is the empty list
partition(L, [L]). ;; Base case where if P contains 1 element (list), L is equal to this list.
partition(L, [X|[Y1|Y2]]) :-
append(X, Y1, XY1),
partition(L, [XY1|Y2]). ;; Append each list in P to the list after it, repeating until one list is created. X is the head of the list, Y1 is the second element, and Y2 is the rest of the list.
,它会无限循环。
{{1}}
感谢任何帮助。
答案 0 :(得分:3)
这个棘手的部分是以普遍终止的方式使用append/3
。
让代码list_sublists/2
(比partition
更具声明性的名称):
list_sublists([],[]).
list_sublists([X|Xs],[[Y|Ys]|Yss]) :-
append([Y|Ys],Xs0,[X|Xs]),
list_sublists(Xs0,Yss).
考虑第二个子句中的目标append([Y|Ys],Xs0,[X|Xs])
:当[Y|Ys]
或[X|Xs]
(或两者)的长度有限时,它会普遍终止。
现在让我们运行您提供的查询:
?- list_sublists([1,2,3],Pss).
Pss = [[1],[2],[3]] ;
Pss = [[1],[2,3]] ;
Pss = [[1,2],[3]] ;
Pss = [[1,2,3]] ;
false.
?- list_sublists(Ls,[[1],[2],[3,4,5]]).
Ls = [1,2,3,4,5].
答案 1 :(得分:1)
我试图最低限度地纠正你的代码:它最终达到与@repeat回答(+1)非常相似(完全相同)的东西,当然
partition([], []). % Partition of empty list is the empty list
%partition(L, [L]). % Base case where if P contains 1 element (list), L is equal to this list.
% Append each list in P to the list after it, repeating until one list is created. X is the head of the list, Y1 is the second element, and Y2 is the rest of the list.
partition(L, [[X|Xs]|Zs]) :-
append([X|Xs], Ys, L),
partition(Ys, Zs).
我会说它强迫第一个追加/ 3的参数长度为> 0,完成了模式[X|Xs]
,而不仅仅是Xs