Skip to content

Instantly share code, notes, and snippets.

@sescobb27
Created December 21, 2018 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sescobb27/19a4a06479dfa7e6f887f89dcc5eb9f0 to your computer and use it in GitHub Desktop.
Save sescobb27/19a4a06479dfa7e6f887f89dcc5eb9f0 to your computer and use it in GitHub Desktop.
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