简体   繁体   中英

List of pair list to on list PROLOG

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.

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 map B 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.

@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].

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM