Reputation: 128
I have one list of lists like this: [[a,b],[b,c],[c,d]] and I want to has [a,b,c].
My code is:
unMakeTuple([],_).
unMakeTuple([[A,_]|T],Ret):-
insertOnList(A,Ret,Ret1),
nl,write(Ret),
nl,write(Ret1),
unMakeTuple(T,Ret1).
insertOnList(E,[],[E]).
insertOnList(E,[H|T],[H|T1]):-
insertOnList(E,T,T1).
And return me a empty list. Someone can help me? Thank you.
Upvotes: 2
Views: 61
Reputation: 26315
@Willem Van Onsem's solution using maplist/3
above is the better way to do this, but another way to do this is to just write a predicate that adds all the heads of the inner lists to a resulting list. Some sort of recursive solution like this should work:
head([H|_], H).
get_heads([], []).
get_heads([X|Xs], List) :-
head(X, H),
List = [H|Rest],
get_heads(Xs, Rest).
Which works as follows:
?- get_heads([[a,b],[b,c],[c,d]], X).
X = [a, b, c].
Upvotes: 1
Reputation: 476659
You here want basically make a mapping where we obtain the head of every sublist.
So we can define a predicate head/2
:
head([H|_],H).
and then use maplist/3
:
unMakeTuple(A,B) :-
maplist(head,A,B).
then we obtain:
?- unMakeTuple([[a,b],[b,c],[c,d]],X).
X = [a, b, c].
Although writing a custom predicate can of course be beneficial as well. The advantage here is that (a) it is very declarative and easy to understand that we map a list A
to a mapB
by for each element unify the elements of the two lists by the head
predicate; (b) we can be quite certain that maplist/3
works correctly and (c) we can expect that maplist/3
will be optimized such that processing is done fast.
Upvotes: 2