2
votes

So, I have to create a predicate, unzip(L,R,P), where P is a list of pairs (Ex: P = [[1,2],[3,4]]. L has to be a new list that contains the first element from each pair, while R is a new list containing the second element from each pair.

Here's what I have:

unzip([],[],[]).
unzip([H1|T1],[H2|T2],[HL,HR|T]) :-
   H1 = HL,
   H2 = HR,
   unzip(T1,T2,T).

This works unless the number of pairs is odd. I'm not seeing how this could be the case, any advice?

EDIT: Figured it out. Here's my solution if anyone is curious:

unzip([],[],[]).
unzip([H1|T1],[H2|T2],[[HL,HR]|T]) :-
   H1 = HL,
   H2 = HR,
   unzip(T1,T2,T).
1
Feel free to make this an answer and accept it. You might end up helping someone later on.joneshf
Note that what you wrote is also zipfalse

1 Answers

5
votes

Your solution is correct, but you can, and should, use unification in the head:

unzip([], [], []).
unzip([L|Ls], [R|Rs], [[L,R]|Ps]) :- unzip(Ls, Rs, Ps).