Created
December 21, 2018 15:01
-
-
Save sescobb27/19a4a06479dfa7e6f887f89dcc5eb9f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Topological do | |
def sort(library) do | |
g = :digraph.new | |
Enum.each(library, fn {l,deps} -> | |
:digraph.add_vertex(g,l) # noop if library already added | |
Enum.each(deps, fn d -> add_dependency(g,l,d) end) | |
end) | |
if t = :digraph_utils.topsort(g) do | |
print_path(t) | |
else | |
IO.puts "Unsortable contains circular dependencies:" | |
Enum.each(:digraph.vertices(g), fn v -> | |
if vs = :digraph.get_short_cycle(g,v), do: print_path(vs) | |
end) | |
end | |
end | |
defp print_path(l), do: IO.puts Enum.join(l, " -> ") | |
defp add_dependency(_g,l,l), do: :ok | |
defp add_dependency(g,l,d) do | |
:digraph.add_vertex(g,d) # noop if dependency already added | |
:digraph.add_edge(g,l,d) # Dependencies represented as an edge d -> l | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment