Search code examples
prolog

Prolog: zip 2 lists into one


Suppose, we have 2 lists [1, 2, 3], [3, 2, 1] and we want to create a third list equal to the result of a binary function applied to every corresponding pair of the lists elements.

Something like:

f(x, y) = 
    -1, if x < y; 
    0, if x = y; 
    1 if x > y.

For our example we get [-1, 0, 1].

I created the code:

f(A, B, C) :- ( A < B ->
                C = -1
              ; A =:= B ->
                C = 0
              ; C = 1
              ).

zip([A], [B], [C]) :- f(A, B, C).
zip([A | T1], [B | T2], [C | T]) :- f(A, B, C), zip(T1, T2, T).

It works:

?- zip([1,2,3], [3,2,1], X).
X = [-1, 0, 1] .

But I have a feeling that I am reinventing the wheel. Is there a system function for this in Prolog?


Solution

  • You probably want to use a maplist predicate https://www.swi-prolog.org/pldoc/doc_for?object=maplist/4

    just like so

    ?- maplist(f,[1,2,3],[3,2,1],C).
    C = [-1, 0, 1].