# [erlang-questions] zip for N lists?

Ivan Uemlianin <>
Fri Oct 19 11:17:39 CEST 2012

```Dear All

Erlang provides lists:zip/2 and /3 for zipping together two or three
lists.  Is there anything ready available for zipping together
arbitrarily many lists?  e.g., taking a list of lists as its input,

zipN([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) ->
[[1,4,7,10],[2,5,8,11],[3,6,9,12]].

If not, I cooked up the following:

zip_lol([[]|_]) ->
[];
zip_lol(Lols) ->
{Lohs, Lots} = lists:foldl(fun([H|T], {Hs,Ts}) ->
{[H|Hs],[T|Ts]}
end,
{[],[]},
Lols),
[lists:reverse(Lohs) | zip_lol(Lots)].

This doesn't quite work, as only every other Lohs seems to need reversing:

zip_lol([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) ->
[[1,4,7,10],[11,8,5,2],[3,6,9,12]].

Actually, it's enough for my purposes, as I only need the sum of each
loh, so I can use:

zipwith_lol(_, [[]|_]) ->
[];
zipwith_lol(Fun, Lols) ->
{Lohs, Lots} = lists:foldl(fun([H|T], {Hs,Ts}) ->
{[H|Hs],[T|Ts]}
end,
{[],[]},
Lols),
[Fun(Lohs) | zipwith_lol(Fun, Lots)].

zip_lol([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) ->
[22,26,30].

What concerns me is performance.  My lols are likely to be quite large:
10 to 20 lists, and each list could be 100k+ integers long (if it were
Haskell each list would be one of those lazy infinite list stream things).

Is the fold the right way to do this, or have I missed something that
would do the job faster?

With thanks and best wishes

Ivan

--
============================================================
Ivan A. Uemlianin PhD
Llaisdy
Speech Technology Research and Development

www.llaisdy.com
llaisdy.wordpress.com
github.com/llaisdy