How to merge lists in PROLOG?
18,930
Solution 1
you can try
m2([A|As], [B|Bs], [A,B|Rs]) :-
!, m2(As, Bs, Rs).
m2([], Bs, Bs) :- !.
m2(As, [], As).
Solution 2
You may look at this link: Prolog program to merge two ordered lists
This will not give you the output you need, but it is a start.
After some tries, here is the correct answer, much simple than the original proposed by me (tested and working).
mergelist_alternate([],[],[]).
mergelist_alternate([X],[],[X]).
mergelist_alternate([],[Y],[Y]).
mergelist_alternate([X|List1],[Y|List2],[X,Y|List]) :- mergelist_alternate(List1,List2,List).
You can call it like this:
mergelist_alternate([1,2,3],[a,b],L),!.
Solution 3
merge_list([],L,L ).
merge_list([H|T],L,[H|M]):-
merge_list(T,L,M).
It will work. 100% tested!
Input: merge_list([1,2],[3,4],M).
Output: M=[1,2,3,4].
Author by
Jakub Turcovsky
Updated on June 04, 2022Comments
-
Jakub Turcovsky almost 2 years
I need to merge two lists L1=[1,2,3] and L2=[a,b] like this: M=[1,a,2,b,3]. How can I do it in PROLOG please?