2

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).
4

1 回答 1

5

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).
于 2013-05-08T01:40:03.473 回答