Last active
August 8, 2022 06:08
-
-
Save K9-guardian/6c1207a111943aa8a4d623d285174c18 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
;; 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