# [erlang-questions] zip for N lists?

Ivan Uemlianin <>
Fri Oct 19 13:54:56 CEST 2012

```Thanks very much!

I've just discovered timer:tc/3: yours is nearly twice as fast as mine
(140 ms against 240 ms, although timings vary a lot).  Quite fast enough:)

Best wishes

Ivan

On 19/10/2012 12:02, Jesse Gumm wrote:
> Here is a zipn/1 function I use for my own purposes:
>
> http://ideone.com/pfBAn
>
> I don't know how fast you need it to be, but on my old laptop (like
> 7-8 years old), it zipped 10 lists each of 100k integers in about 800
> ms.
>
> -Jesse
>
> On Fri, Oct 19, 2012 at 4:17 AM, Ivan Uemlianin <> wrote:
>> 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