[erlang-questions] zip for N lists?
Ivan Uemlianin
ivan@REDACTED
Fri Oct 19 14:43:01 CEST 2012
Thanks!! That's a good bit faster again. It does have a very Haskelly
look to it.
Best wishes
Ivan
On 19/10/2012 13:30, Daniel Goertzen wrote:
> Here is one that I use. My comments say that it comes from Haskell, but
> I seem to remember that I got the Erlang translation from this mailing list.
>
>
> % transpose a matrix represented as list of lists
> % aka "zip" list of lists
> % This implementation originates from Haskell
> transpose([[X | Xs] | Xss]) ->
> [[X | [H || [H | _] <- Xss]]
> | transpose([Xs | [T || [_ | T] <- Xss]])];
> transpose([[] | Xss]) -> transpose(Xss);
> transpose([]) -> [];
>
> transpose(Tuple) when is_tuple(Tuple) -> % wrapper to emulate zip
> Xs = transpose(tuple_to_list(Tuple)),
> [list_to_tuple(X) || X <- Xs].
>
>
> Dan.
>
>
>
>
> On Fri, Oct 19, 2012 at 4:17 AM, Ivan Uemlianin <ivan@REDACTED
> <mailto:ivan@REDACTED>> 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
ivan@REDACTED
www.llaisdy.com
llaisdy.wordpress.com
github.com/llaisdy
www.linkedin.com/in/ivanuemlianin
"hilaritas excessum habere nequit"
(Spinoza, Ethica, IV, XLII)
============================================================
More information about the erlang-questions
mailing list