Home > Blockchain >  SWI Prolog - Combining elements from two lists into pairs
SWI Prolog - Combining elements from two lists into pairs

Time:02-02

How can I "join" two lists while keeping their elements's positions? Like, I have List1 = [1,2,3] and List2 = [a,b,c]. How can I get the list [[1,a], [2,b], [3,c]]?

I've been trying to look for built-in predicates but all I've found can't reproduce this.

CodePudding user response:

join_2_lists(L1, L2, JoinLst) :-
    must_be(list, L1),
    must_be(list, L2),
    join_2_lists_(L1, L2, JoinLst).

join_2_lists_([], [], []).
join_2_lists_([H1|T1], [H2|T2], [[H1, H2]|JoinLst]) :-
    join_2_lists_(T1, T2, JoinLst).

Result in swi-prolog:

?- join_2_lists([1, 2, 3], [a, b, c], J).
J = [[1,a],[2,b],[3,c]].
  •  Tags:  
  • Related