Skip to content

Instantly share code, notes, and snippets.

@JoelPM
Created April 29, 2011 20:38
Show Gist options
  • Save JoelPM/949000 to your computer and use it in GitHub Desktop.
Save JoelPM/949000 to your computer and use it in GitHub Desktop.
Provides an unflatten function. Useful when you flatten a list to do something and then need to unflatten an associated result list.
-module(mylists).
-export([ unflatten/2 ]).
unflatten([],[]) ->
[];
unflatten(List,[PSubList|PList]) ->
unflatten(List,[],[],PSubList,PList).
unflatten([],SubList,Lists,[],[]) ->
lists:reverse([lists:reverse(SubList)|Lists]);
unflatten(L,SubList,Lists,[],[PSubList|PLists]) ->
unflatten(L,[],[lists:reverse(SubList)|Lists],PSubList,PLists);
unflatten([H|T],SubList,Lists,[PSubH|PSubT],PLists) ->
unflatten(T,[H|SubList],Lists,PSubT,PLists).
example() ->
ML = [[1,2,3],[4,5,6],[],[7,8],[9]],
MLF = lists:flatten(ML),
RL = [9,8,7,6,5,4,3,2,1],
RLUF = mylists:unflatten(RL,ML),
[[9,8,7],[6,5,4],[],[3,2],[1]] = RLUF.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment