Search code examples
listprolog

Prolog. I can't mix two lists


I want to mix two lists into one. For example, [1,3,5] and [2,3,9] would yield [1,2,3,5,9].

I tried this:

mezclar( L1, L2, L3 ):-
  L1 = [Cab|Cola] ,
  L3 = [Cab,Cola2] ,
  mezclar(L2,Cola,Cola2) .
mezclar( L1, L2, L3 ):-
  L1=[] ,
  L3=L2 .

But I have 2 problems.

  • The first problem are duplicated numbers
  • The second one is that I'm putting lists into the list and I dont want to.

If I execute

mezclar( [1,3,5], [2,5,9], X ).

I get

X = [1, [2, [3, [5, [5|...]]]]]

Solution

  • To mix two lists into one, with the resulting list being ordered and without duplicates, try:

    mezclar(L1,L2,L3) :- append(L1,L2,L4), sort(L4,L3).
    

    The query:

    mezclar([1,3,5], [2,5,9], X).
    

    will produce the result:

    X = [1, 2, 3, 5, 9]
    

    This example uses sort/2. Here is a link to the SWI documentation for sort/2:

    http://eu.swi-prolog.org/pldoc/man?predicate=sort/2