Search code examples
prolog

Merging 2 lists into a third but in pairs


I want, given 2 lists, to merge them into a third one but each element of the third list is a list of the first and second list's elements.

E.g. given the list1 [1,2,3] and list2 [1,2,3] I want the final list to be [[1,1],[2,2],[3,3]]

What I've done so far is

merge([],[],Z).
merge([H1|T1],[T2|T2],Z):-
    append([H1],[H2],W),merge(T1,T2,[W,Z]). 

but I get a False result. Why isn't it working?


Solution

  • There are some flaws in your code:

    • when the first two lists are empty, the result must be an empty list too;
    • Instead of [T2|T2] you should write [H2|T2] to represent the second list;
    • there is no need to use append([H1],[H2],W) to create a list with two elements, just write [H1,H2];
    • since the recursive call must merge the tails of the first and second lists, there is no way the result of this call to be a list starting with the element [H1,H2].

    Thus, a correct definition for that predicate is as follows:

    my_merge([], [], []).
    my_merge([H1|T1], [H2|T2], [[H1,H2]|T3]):-
        my_merge(T1, T2, T3).
    

    Examples:

    ?- my_merge([a,b,c], [1,2,3], L3).
    L3 = [[a, 1], [b, 2], [c, 3]].
    
    ?- my_merge(L1, L2, [[1,a],[2,b],[3,c]]).
    L1 = [1, 2, 3],
    L2 = [a, b, c].
    

    Remark Consider the possibility of representing the pair [H1,H2] as H1-H2, as the latter representation is more commonly used in Prolog.