Skip to content

Instantly share code, notes, and snippets.

@K9-guardian
Last active August 8, 2022 06:08
Show Gist options
  • Save K9-guardian/6c1207a111943aa8a4d623d285174c18 to your computer and use it in GitHub Desktop.
Save K9-guardian/6c1207a111943aa8a4d623d285174c18 to your computer and use it in GitHub Desktop.
;; https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search
(defn topsort [g]
(let [l (atom ())
marks (atom (zipmap (keys g) (repeat nil)))
visit (fn visit [n]
(case (@marks n)
:perm nil
:temp (throw (IllegalArgumentException. "Not a DAG"))
(do
(swap! marks assoc n :temp)
(run! visit (g n))
(swap! marks assoc n :perm)
(swap! l conj n))))]
(while (->> @marks vals (some nil?))
(let [n (->> @marks (filter (comp nil? val)) ffirst)]
(visit n)))
@l))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment