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
?
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. Like this;
decompose([[H|T]|T0], [H|L1], [T|L2]) :- decompose(T0, L1, L2).
decompose([], [], []).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.