Created
September 3, 2012 02:41
-
-
Save SegFaultAX/3606387 to your computer and use it in GitHub Desktop.
Transitive Closure of a Binary Relation
This file contains hidden or 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
(defn transitive-closure [rel] | |
(let [roots (into {} (for [[k v] (group-by first rel)] [k (mapv second v)])) | |
children (fn children [rels e] | |
(let [cs (get rels e [])] | |
(cons e (mapcat #(children rels %) cs))))] | |
(set (mapcat #(map vector (repeat %) (rest (children roots %))) (keys roots))))) | |
(transitive-closure #{[8 4] [9 3] [4 2] [27 9]}) | |
(transitive-closure #{["cat" "man"] ["man" "snake"] ["spider" "cat"]}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment