简体   繁体   中英

Prolog intersection list of lists

I want to create an intersection of lists of lists in prolog. (Matrix, with lists as cells)

I have to handle only the case, when number of rows and columns are the same (Rectangular). The lists are ordered, and does not contain any duplicate elements (they are ord_sets).

How could I do that?

Example: (3 rows, 3 columns)

A:
[[[1,2],[3,2,1],[3,4,5]],
[[1,2],[3,2,1],[3,4,5]],
[[1,2],[3,2,1],[3,4,5]]]
B:
[[[1],[3,2,1],[3,4,5]],
[[1,2],[2,1],[3,4]],
[[1,2],[3,2,1],[3,9,10,4,5]]]
C:
[[[1],[3,2,1],[3,4,5]],
[[1,2],[2,1],[3,4]],
[[1,2],[3,2,1],[3,4,5]]]

Thank you for the help!

Most Prolog interpreters already have a predicate to calculate the intersection between two lists: intersection/3 . For example:

?- intersection([3,2,1], [3,9,10,4,5], R).
R = [3].

We can use maplist/3 to process an entire row of such lists:

?- maplist(intersection, [[1,2],[3,2,1],[3,4,5]], [[1],[3,2,1],[3,4,5]], C).
C = [[1], [3, 2, 1], [3, 4, 5]].

And by using another maplist/3 we process the matrices:

?- maplist(maplist(intersection),[[[1,2],[3,2,1],[3,4,5]], [[1,2],[3,2,1],[3,4,5]], [[1,2],[3,2,1],[3,4,5]]], [[[1],[3,2,1],[3,4,5]],[[1,2],[2,1],[3,4]],[[1,2],[3,2,1],[3,9,10,4,5]]], C).
C = [[[1], [3, 2, 1], [3, 4, 5]], [[1, 2], [2, 1], [3, 4]], [[1, 2], [3, 2, 1], [3, 4, 5]]].

So we can do the processing with:

intersect_matrix(A, B, C) :-
    maplist(maplist(intersection), A, B, C).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM