Skip to content

Instantly share code, notes, and snippets.

@egobrain
Created July 2, 2015 11:09
Show Gist options
  • Save egobrain/1deb8a5d5ecaf2e39ccd to your computer and use it in GitHub Desktop.
Save egobrain/1deb8a5d5ecaf2e39ccd to your computer and use it in GitHub Desktop.
List utils
-module(list_utils).
-export([group_by/2]).
group_by(_Key, []) -> [];
group_by(Key, List) ->
[H|T] = lists:keysort(Key, List),
K = element(Key, H),
group_by_(Key, K, [H], [], T).
group_by_(_Key, K, Values, Acc, []) ->
lists:reverse([{K, lists:reverse([Values])}|Acc]);
group_by_(Key, K, Values, Acc, [H|T]) ->
K2 = element(Key, H),
case K =:= K2 of
true ->
group_by_(Key, K, [H|Values], Acc, T);
false ->
group_by_(Key, K2, [H], [{K, lists:reverse(Values)}|Acc], T)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment