Skip to content

Instantly share code, notes, and snippets.

@vladdu
Created September 21, 2010 20:13
Show Gist options
  • Save vladdu/590445 to your computer and use it in GitHub Desktop.
Save vladdu/590445 to your computer and use it in GitHub Desktop.
Topological sorting of a list of dependencies as pairs of {label, [label]}
%% Topological sorting of a list of dependencies as pairs of
%% {label, [label]} where the list contains dependees.
%%
%% > tsort:tsort([{a,["b",c]}, {c, [1]}]).
%% ["b",1,c,a]
-module(tsort).
-export([tsort/1]).
-type dep_list() :: [{any(), [any()]}].
-spec tsort(dep_list()) -> [any()].
tsort(L) ->
Graph = make_graph(L),
try
digraph_utils:topsort(Graph)
after
digraph:delete(Graph)
end.
make_graph(L) ->
G = digraph:new([acyclic]),
[add(X, G) || X <- L],
G.
add({K, V}, G) ->
digraph:add_vertex(G, K),
[digraph:add_vertex(G, X) || X<-V],
[digraph:add_edge(G, X, K) || X<-V].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment