简体   繁体   English

在 Prolog 中使用列表列表

[英]Working with list of lists in Prolog

Please help me to solve this problem: I have a list of lists请帮我解决这个问题:我有一个列表列表

[[1,2],[3,4]] [[1,2],[3,4]]

How do I get:如何得到:

[1,3] [1,3]

[1,4] [1,4]

[2,3] [2,3]

[2,4] [2,4]

Or if I have a list of lists或者如果我有一个列表列表

[[1,2],[3,4],[6,7]] [[1,2],[3,4],[6,7]]

How do I get:如何得到:

[1,3,6] [1,3,6]

[1,3,7] [1,3,7]

[1,4,6] [1,4,6]

[1,4,7] [1,4,7]

[2,3,6] [2,3,6]

[2,3,7] [2,3,7]

[2,4,6] [2,4,6]

[2,4,7] [2,4,7]

The predicate for accessing a single list element is the most basic Prolog building block: member/2 .访问单个列表元素的谓词是最基本的 Prolog 构建块: member/2

And you want a list of all lists' elements: maplist/3 does such mapping.并且您想要一个所有列表元素的列表maplist/3此类映射。 Thus we can write这样我们就可以写

combine(Ls, Rs) :-
    maplist(get1, Ls, Rs).
get1(L, E) :-
    member(E, L).

note that get1/2 is only required so that we swap the member/2 arguments.请注意,仅需要get1/2以便我们交换member/2参数。 But because in (pure) Prolog we are describing relations between arguments, we can swap arguments' order and simplify it even more:但是因为在(纯)Prolog 中我们描述的参数之间的关系,我们可以交换参数的顺序并进一步简化它:

combine(Ls, Rs) :-
    maplist(member, Rs, Ls).

Test output:测试输出:

?- combine( [[1,2],[a,b]], Xs).
Xs = [1, a] ;
Xs = [1, b] ;
Xs = [2, a] ;
Xs = [2, b].

%% this is the same as:
       %% maplist( member, Xs, [[1,2],[a,b]]) :-
       %%          member( X1,  [1,2]      ),
       %%          member( X2,        [a,b]),  Xs = [X1,X2].

edit编辑

A joke: really, my first combine/2 should have been written like一个笑话:真的,我的第一个 combine/2 应该是这样写的

combine(Ls, Rs) :-
    maplist(rebmem, Ls, Rs).
rebmem(L, E) :-
    member(E, L).

You can do something like this:你可以这样做:

lists([], []).
lists([[Head|_]|Lists], [Head|L]):-
  lists(Lists, L).
lists([[_,Head|Tail]|Lists], L):-
  lists([[Head|Tail]|Lists], L).

That is, take the first element of the first list in your input list and continue recursively with the remaining lists.也就是说,取输入列表中第一个列表的第一个元素,然后递归地继续处理剩余的列表。 As a second chance, skip that element and redo with the remaining elements.作为第二次机会,跳过该元素并使用其余元素重做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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