Skip to content

Instantly share code, notes, and snippets.

@5outh
Created December 5, 2012 22:04
Show Gist options
  • Save 5outh/4219925 to your computer and use it in GitHub Desktop.
Save 5outh/4219925 to your computer and use it in GitHub Desktop.
tsort
tsort :: (Eq a) => Graph a -> [a]
tsort graph = tsort' [] (noInbound graph) graph
where noInbound (Graph v e) = filter (flip notElem $ map snd e) v
tsort' l [] (Graph _ []) = reverse l
tsort' l [] _ = error "There is at least one cycle in this graph."
tsort' l (n:s) g = tsort' (n:l) s' g'
where outEdges = outbound n g
outNodes = map snd outEdges
g' = foldr removeEdge g outEdges
s' = s ++ filter (null . flip inbound g') outNodes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment