Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dylon/7865444 to your computer and use it in GitHub Desktop.
Save dylon/7865444 to your computer and use it in GitHub Desktop.
Demonstrates how to dispatch on multimethods with relationship hierarchies other than the global hierarchy. In Clojure, multimethods compare dispatch values using isa?, which operates on a relationship hierarchy that may be overridden via the ":hierarchy" option to defmulti.
(def h (atom (make-hierarchy)))
(swap! h derive ::a ::b)
;-> "(isa? user/a user/b), under the global hierarchy: false"
(println "(isa? user/a user/b), under the global hierarchy:" (isa? ::a ::b))
;-> "(isa? user/a user/b), under the hierarchy, h: true"
(println "(isa? user/a user/b), under the hierarchy, h:" (isa? @h ::a ::b))
(defmulti f identity :hierarchy h :default :unmatched)
(defmethod f ::b [x]
(format "I, %s, isa? user/b under f!" (print-str x)))
(defmethod f :unmatched [x]
(format "I, %s, am sorrowfully-not isa? user/b under f..." (print-str x)))
(println (f ::b)) ;-> "I, user/b, isa? user/b under f!"
(println (f ::a)) ;-> "I, user/a, isa? user/b under f!"
(println (f ::c)) ;-> "I, user/c, am sorrowfully-not isa? user/b under f ..."
(defmulti g identity)
(defmethod g ::b [x]
(format "I, %s, isa? :user/b under g!" (print-str x)))
(defmethod g :default [x]
(format "I, %s, am sorrowfully-not isa? :user/b under g ..." (print-str x)))
(println (g ::b)) ;-> "I, user/b, isa? user/b under g!"
(println (g ::a)) ;-> "I, user/a, am sorrowfully-not isa? user/b under g ..."
(println (g ::c)) ;-> "I, user/c, am sorrowfully-not isa? user/b under g ..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment