Jakub Turcovsky
Jakub Turcovsky

Reputation: 2126

How to merge lists in PROLOG?

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?

Upvotes: 3

Views: 21457

Answers (3)

Md Salauddin Sarkar
Md Salauddin Sarkar

Reputation: 67

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

Upvotes: 4

racribeiro
racribeiro

Reputation: 93

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),!.

Upvotes: 3

CapelliC
CapelliC

Reputation: 60004

you can try

m2([A|As], [B|Bs], [A,B|Rs]) :-
    !, m2(As, Bs, Rs).
m2([], Bs, Bs) :- !.
m2(As, [], As).

Upvotes: 9

Related Questions