我需要写一个谓词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
。这是我迄今为止的,但它不起作用。它无限循环地包含多于1个列表的任何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.
任何帮助表示赞赏。