prolog - 在序言中组合两个列表

标签 prolog

你将如何组合两个列表?这是我尝试过的,但没有给我想要的结果,

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/

相关文章:

prolog - 用 `last/2` 或 `append/3` 实现 `reverse/2`

prolog - 如何计算序言代码知识库中现有列表的平均值?

prolog - 停止 Prolog 推断值

matrix - Prolog - 从列表列表中获取元素

prolog - 在列表的第 1 个、第 2 个、第 4 个、第 8 个……元素之后插入给定值 v。 (序言)

Prolog 查询可满足但返回 false

tree - 树的高度 - PROLOG

list - append/3 的具体谓词变体的冗余答案

list - 将现有列表写入 Prolog 中的新列表

arrays - 序言中的快速二维数组