测试用例
?- decompose([[1,2,8],[3,4],[5,6]], L1, L2).
L1 = [1,3,5], L2 = [[2,8],[4],[6]] ? ;
no
我尝试了另一种实现,但给出的反馈是效率低下。
效率低下的实施
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).
答案 0 :(得分:3)
跟进@findall's previous answer ...如何使用meta-predicate maplist/4
?
list_head_tail([X|Xs], X, Xs). decompose(Mss, Hs, Ts) :- maplist(list_head_tail, Mss, Hs, Ts).
示例查询:
?- decompose([[a,b,c],[d,e,f]], Heads, Tails). Heads = [a,d], Tails = [[b,c],[e,f]]. ?- decompose([[1,2,8],[3,4],[5,6]], L1, L2). L1 = [1,3,5], L2 = [[2,8],[4],[6]].
答案 1 :(得分:2)
正如潜伏者所说,listFirst
和listFollowers
的功能可以合并为谓词,以便同时执行这些功能。像这样;
decompose([[H|T]|T0], [H|L1], [T|L2]) :- decompose(T0, L1, L2).
decompose([], [], []).