我在下面编写了以下代码来转置序言中的矩阵
listFirst([],[]).
listFirst([H1|T1],[H2|Z]):-
H1 = [H2|_],
listFirst(T1,Z).
listFollowers([],[]).
listFollowers([H1|T1],[T2|Z]):-
H1 = [H2|T2],
listFollowers(T1,Z).
decompose(A,L1,L2):-
listFollowers(A,L2),listFirst(A,L1).
transpose([],[]).
transpose([H|T],[L1|R]):-
decompose([H|T],L1,L2),
transpose(L2,R).
测试用例
transpose([[1,2],[3,4],[5,6]], R).
R = [[1,3,5],[2,4,6]] ;
我在转置谓词方面遇到问题,不知道如何实现它。其他谓词似乎工作正常。
最佳答案
取自 SWI-Prolog 中的 library(clpfd)
(有关详细信息,请参阅 source code):
transpose([], []).
transpose([L|Ls], Ts) :- foldl(transpose_, L, Ts, [L|Ls], _).
transpose_(_, Fs, Lists0, Lists) :-
maplist(list_first_rest, Lists0, Fs, Lists).
list_first_rest([L|Ls], L, Ls).
示例查询:
?- transpose([[a,b,c],[d,e,f]], Ts).
Ts = [[a, d], [b, e], [c, f]].
关于prolog - 在序言中转置矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34144117/