[英]Decomposing a matrix to a list of first element and sub list of remaining elements in prolog
測試用例
?- 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).
跟進@findall的先前答案 ...如何使用元謂詞 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]].
正如lurker所說的,您可以將listFirst
和listFollowers
的功能組合為一個謂詞,以立即完成這些功能。 像這樣;
decompose([[H|T]|T0], [H|L1], [T|L2]) :- decompose(T0, L1, L2).
decompose([], [], []).
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.