我有以下4个列表:
A= [1,2,3],
B=[4,5,6],
C=[7,8,9],
D=[10,11,12]
Run Code Online (Sandbox Code Playgroud)
我想获得另一个列表列表,其第一个元素获取每个列表的第一个元素,第二个元素获取每个列表的第二个元素,等等。例如:
[1,2,3], [4,5,6], [7,8,9], [10,11,12]
Run Code Online (Sandbox Code Playgroud)
变成
[[1,4,7,10], [2,5,8,11],[3,6,9,12]].
Run Code Online (Sandbox Code Playgroud)
我尝试使用
findall([X,Y,Z,T],(member(X,A),member(Y,B),member(Z,C),member(T,D)),ModifiedList).
Run Code Online (Sandbox Code Playgroud)
但这没有用。
我该如何在Prolog中做到这一点?
一个解决方案是:
% auxiliary predicate to group the first elements of
% all input lists and return the tails of the lists
group_first([], [], []).
group_first([[X| Xs]| Lists], [X| Tail], [Xs| Tails]) :-
group_first(Lists, Tail, Tails).
% main predicate; we separate the first list from the other
% lists to take advantage of first-argument indexing
group([], []).
group([List| Lists], Groups) :-
group(List, Lists, Groups).
group([], _, []).
group([X| Xs], Lists, [Group| Groups]) :-
group_first([[X| Xs]| Lists], Group, Tails),
group(Tails, Groups).
Run Code Online (Sandbox Code Playgroud)
样品通话:
| ?- group([[1,2,3],[a,b,c],['A','B','C']], R).
R = [[1,a,'A'],[2,b,'B'],[3,c,'C']]
yes
Run Code Online (Sandbox Code Playgroud)
为了帮助理解解决方案:
| ?- group_first([[1,2,3],[a,b,c],['A','B','C']], Group, Tails).
Group = [1,a,'A']
Tails = [[2,3],[b,c],['B','C']]
yes
Run Code Online (Sandbox Code Playgroud)