Skip to content

Instantly share code, notes, and snippets.

@xandkar
Created October 19, 2012 14:04
Show Gist options
  • Save xandkar/3918390 to your computer and use it in GitHub Desktop.
Save xandkar/3918390 to your computer and use it in GitHub Desktop.
Zip N lists
%% ----------------------------------------------------------------------------
%% Jesse Gumm <gumm@sigma-star.com>
%% http://erlang.org/pipermail/erlang-questions/2012-October/069832.html
%%
zipn(List) ->
zipn([],List).
zipn(Acc,[]) ->
lists:map(fun lists:reverse/1,Acc);
zipn([],[A|Rest]) ->
AccStart = [[V] || V<-A],
zipn(AccStart,Rest);
zipn(Acc,[A|Rest]) ->
NewAcc = zipn_helper(Acc,A),
zipn(NewAcc,Rest).
zipn_helper(Acc,A) ->
zipn_helper([],Acc,A).
zipn_helper(Acc,[],[]) ->
lists:reverse(Acc);
zipn_helper(Acc,[AccHd|AccRest],[VHd|VRest]) ->
NewAccHd = [VHd|AccHd],
NewAcc = [NewAccHd|Acc],
zipn_helper(NewAcc,AccRest,VRest).
%% ----------------------------------------------------------------------------
%% Daniel Goertzen <daniel.goertzen@gmail.com>
%% http://erlang.org/pipermail/erlang-questions/2012-October/069856.html
%%
% 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) ->
Xs = transpose(tuple_to_list(Tuple)),
[list_to_tuple(X) || X <- Xs].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment