Prolog中类似Transpose的谓词实现

Implementation of predicate similar to Transpose in Prolog

我是 Prolog 的新手,实际上刚接触 4 天,我遇到了一个练习,上面写着:

给定 N 个大小为 N 的列表,每个列表实现一个名为 reshape(X,Y) 的谓词 这样它:

例如:

所以这是我的实现:

% Insert at the end of a list

insert([],X,[X]).
insert([H|T1],X,[H|T2]) :- insert(T1,X,T2).
% Length of list

len([],L,L).

len([_|T],L,X) :- 
    L1 is L + 1,
    len(T,L1,X).

len(L,X) :- len(L,0,X).
% Create a list of N empty lists

init_list(L,0,L) :- !.

init_list(L,N,X) :-
    N1 is N-1,
    insert(L,[],Y),
    init_list(Y,N1,X).

init_list(N,X) :- init_list([],N,X).
% Assign each element of a list to the corresponding list.

assign([],[],[]).
assign([H1|T1],[H2|T2],[Y|T3]) :- 
    insert(H2,H1,Y),
    assign(T1,T2,T3).
% Reshape :

reshape([],L,L).
reshape([H1|T1],X,Result):-
    assign(H1,X,Y),
    reshape(T1,Y,Result).    

reshape(Input,Result) :-
    len(Input,N), 
    init_list(N,X),
    reshape(Input,X,Result).    

所以基本思想是,我首先创建一个包含 N 个空列表的列表,然后对每个列表说输入 I assign/add L 的每个元素到相应列表的 L。

现在我很感激一些输入,因为我已经说过我是 Prolog 的新手,甚至不能说出我的谓词的时间复杂度 is.The 我唯一知道的事实是它有效。

但是有没有更好的方法可以实现它?

我的实现的时间复杂度是多少?好像是多项式时间,但我真的说不出来。

提前致谢。

您可以编写一个只遍历每个元素一次的 O(N) 算法:

reshape([[]|Tail], []):-
  maplist(=([]), Tail).
reshape(Input, [Result|RTail]):-
  reshape(Input, LTail, Result),
  reshape(LTail, RTail).
  
reshape([], [], []).
reshape([[Item|Tail]|LTail], [Tail|MTail], [Item|RTail]):-
  reshape(LTail, MTail, RTail).

reshape/3 获取列表列表的每个第一个元素的列表。然后 reshape/2 递归地构建所有这样的列表。

测试用例:

?- reshape([[1,2,3],[4,5,6],[7,8,9]],X).
X = [[1, 4, 7], [2, 5, 8], [3, 6, 9]] ;
false.