你将如何组合两个列表?这是我尝试过的,但没有给我想要的结果,
Y = [1,2,3].
Z = [3,4,5].
X = [Y,Z].
这只是给出了一个更大的列表,其中有一个头部和尾部分开。我希望我的输出看起来像这样:
X = [1,2,3,4,5].
最佳答案
如果您想将两个可能重叠的基本列表组合成第三个,在结果中只保留重叠元素的一个副本(即第一个列表的后缀元素也构成第二个列表的前缀),您可以编写它这边走:
combine(A, B, C):-
append(A1, Common, A),
append(Common, B1, B),
!, % The cut here is to keep the longest common sub-list
append([A1, Common, B1], C).
示例运行:?- combine([1,2,3],[3,4,5], C).
C = [1, 2, 3, 4, 5].
?- combine([1,2,3,4],[3,4,5], C).
C = [1, 2, 3, 4, 5].
为避免使用切割而稍作修改:
combine(A, B, C):-
append(A1, Common, A),
append(Common, B1, B),
bagof(NotCommonA-NotCommonB,
not_common(A1, B1, NotCommonA, NotCommonB),
LDifs),
maplist(difpair, LDifs),
append([A1, Common, B1], C).
not_common(L, R, [ItemA|NotCommonA], NotCommonB):-
append(_, [ItemA|NotCommonA], L),
length([ItemA|NotCommonA], LNotCommon),
length(NotCommonB, LNotCommon),
append(NotCommonB, _, R).
difpair(L-R):-
dif(L, R).
示例运行:?- combine([1,2,3],[3,4,5], C).
C = [1, 2, 3, 4, 5] ;
false.
?- combine([1,2,3,X],[3,4,5], C).
X = 4,
C = [1, 2, 3, 4, 5] ;
X = 3,
C = [1, 2, 3, 3, 4, 5] ;
C = [1, 2, 3, X, 3, 4, 5],
dif(X, 3),
dif(X, 4) ;
;
false
关于prolog - 在序言中组合两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66449005/