Merging 2 lists into a third but in pairs
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.