[英]Decomposing a matrix to a list of first element and sub list of remaining elements in prolog
Test Case 测试用例
?- decompose([[1,2,8],[3,4],[5,6]], L1, L2).
L1 = [1,3,5], L2 = [[2,8],[4],[6]] ? ;
no
I had tried another implementation however the feedback given was that it was inefficient. 我尝试了另一种实现,但是给出的反馈是效率低下。
The inefficient implementation 实施效率低下
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).
Following up on @findall's previous answer ... How about using meta-predicate maplist/4
? 跟进@findall的先前答案 ...如何使用元谓词 maplist/4
?
list_head_tail([X|Xs], X, Xs). decompose(Mss, Hs, Ts) :- maplist(list_head_tail, Mss, Hs, Ts).
Sample queries: 查询样例:
?- 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]].
As lurker says, the functions of your listFirst
and listFollowers
can be combined into a predicate to do those at once. 正如lurker所说的,您可以将listFirst
和listFollowers
的功能组合为一个谓词,以立即完成这些功能。 Like this; 像这样;
decompose([[H|T]|T0], [H|L1], [T|L2]) :- decompose(T0, L1, L2).
decompose([], [], []).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.