[erlang-questions] zip for N lists?

Jesse Gumm <>
Fri Oct 19 13:02:53 CEST 2012


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
>                      www.linkedin.com/in/ivanuemlianin
>
>               "hilaritas excessum habere nequit"
>                  (Spinoza, Ethica, IV, XLII)
> ============================================================
> _______________________________________________
> erlang-questions mailing list
> 
> http://erlang.org/mailman/listinfo/erlang-questions



-- 
Jesse Gumm
Owner, Sigma Star Systems
414.940.4866 || sigma-star.com || @jessegumm



More information about the erlang-questions mailing list