Prolog交叉的2个列表列表

问题描述 投票:3回答:1

我试图找到2个不同的列表列表的交集。换句话说,找出list1中的所有列表是否与列表2中的任何列表相交。

列表1:

[[1,4],[1,6],[6,8],[8,10]]

列表2:

 [[], [10], [8], [8, 10], [6], [6, 10], [6, 8], [6, 8, 10]]

我想在list2中找到list1的所有项目相交的项目。解决方案是[4,6,8]

我该怎么做?

prolog intersection
1个回答
3
投票

一个非常简单的实现可能如下

intersect(L, M, E) :-
    member(E, M),
    maplist(intersect_(E), L).

intersect_(L, M) :-
    member(E, L),
    member(E, M).

示例查询:

?- intersect([[1,4],[1,6],[6,8],[8,10]], [[], [10], [8], [8, 10], [6], [6, 10], [6, 8], [6, 8, 10]], E).
false.

?- intersect([[1,4],[1,6],[6,8],[8,10]], [[], [10], [8], [8, 10], [6], [6, 10], [6, 8], [6, 8, 10], [4,6,8]], E).
E = [4, 6, 8] ;
E = [4, 6, 8] ;  % This succeeds twice because the list [6,8] has two ways of satisfying the predicate
false.
© www.soinside.com 2019 - 2024. All rights reserved.