Skip to content

Instantly share code, notes, and snippets.

@ddossot
Created March 16, 2010 18:25
Show Gist options
  • Save ddossot/334328 to your computer and use it in GitHub Desktop.
Save ddossot/334328 to your computer and use it in GitHub Desktop.
Mingle n lists by successively taking elements of each list. The lists don't need to be of the same size.
%% Mingle n lists by successively taking elements of each list. The lists don't need to be of the same size.
%% @spec mingle(ListOfLists::[List::[term()]]) -> Result::[term()]
mingle(ListOfLists) ->
mingle(ListOfLists, []).
mingle([], Result) ->
lists:reverse(Result);
mingle(ListOfLists, Result) ->
{NewListOfLists, NewResult} =
lists:foldl(fun(List, {ListOfListsAcc, ResultAcc}) ->
case List of
[] -> {ListOfListsAcc, ResultAcc};
[Head|Rest] -> {[Rest|ListOfListsAcc], [Head|ResultAcc]}
end
end,
{[], Result},
ListOfLists),
% must reverse to preserve the ordering of the list of lists
mingle(lists:reverse(NewListOfLists), NewResult).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment