lists:zip / zip_with / unzip etc

Heinz Eriksson <>
Fri Jul 5 11:36:36 CEST 2002


Thomas Arts wrote:
> 
> Hi Heinz
> 
> The zip function is indeed missing in the lists module,
> like the uniq function (removing duplicates from a list).
> 
> > ziph([H1|L1],[H2|L2], Z) ->
> >     ziph(L1,L2,[{H1,H2}|Z]);
> > ziph([],L2, Z) ->
> >     Z;
> > ziph(L1,[], Z) ->
> >     Z.
> >
> > zip(A,B) ->
> >     lists:reverse(ziph(A,B,[])).
> 
> This solution for zip has complexity 2N (2 times the length
> of the list). It is easy to make a solution that only
> traverses the list once.
> It is a matter of taste whether you accept lists of
> unequal length. I would like the program to crash (in the
> Erlang style) if you offer it two lists of unequal length.

I think so too, but what is expected of a zip ...

in Haskell 
  zip
 type: zip :: [a] -> [b] -> [(a,b)]
 description: applied to two lists, returns a list of pairs 
 which are formed by tupling together corresponding elements 
 of the given lists. If the two lists are of different length, 
 the length of the resulting list is that of the shortest.

and Python
zip(seq1, ...)
This function returns a list of tuples, where the i-th tuple
contains the i-th element from each of the argument sequences. 
... The returned list is truncated in length to the length 
of the shortest argument sequence.

Would this be ok to you then:

ziph([H1|L1],[H2|L2], Z) -> 
    [{H1,H2}|ziph(L1,L2,Z)];
ziph([],[], Z) -> 
    Z.

zip(A,B) ->
    ziph(A,B,[]).

?
Is that tail recursive?
Or how shall it be done.

Pair of lists -> List of pairs -> List of mean values of pairs
[(U+L)/2.0 || {U,L} <- zip(A,B)]

It would be nice with an even richer 'lists' module.
There have been other useful functions discussed before.

But is there a _direct_ way to make a the generators of a
list comprehension "operate in parallel"? 
[(U + L) / 2.0 || U <- A (??) L <- B]
                          ^^ 
I know about generators for two (or more) lists working
"nestedly" as in the Cartesian product example.

(first version of this post seemed to disappear, sorry
if it reincarnates).

/hz



More information about the erlang-questions mailing list