Skip to content

Instantly share code, notes, and snippets.

@sunilnandihalli
Created December 23, 2010 04:29
Show Gist options
  • Select an option

  • Save sunilnandihalli/752567 to your computer and use it in GitHub Desktop.

Select an option

Save sunilnandihalli/752567 to your computer and use it in GitHub Desktop.
a new dispatch mechanism similar to condp
(defmacro defmulti-m [multi-fn-name dispatch-fn ]
`(let [dfn# ~dispatch-fn
dvalmap# (atom {})]
(defn ~(symbol (str "add-method-to-" (name multi-fn-name)))
[key# method-fn#]
(swap! dvalmap# assoc key# method-fn#))
(defn ~multi-fn-name [& args#]
(let [ks# (keys @dvalmap#)
k# (or (some #(when (dfn# % args#) %) ks#) :default)
func-to-call# (@dvalmap# k#)]
(if func-to-call#
(try (apply func-to-call# args#)
(catch Exception _#
(throw (Exception. (str "application of " ~(name multi-fn-name)
" method corresponding to key "
k# " with args " args#
"failed with an exception...")))))
(throw (Exception.
(str "could not find an approriate method for the args"
args#))))))))
(defmacro defmethod-m [multi-fn-name dispatch-val args & body]
`(~(symbol (str "add-method-to-" (name multi-fn-name)))
~dispatch-val (fn ~args ~@body)))
(defmulti-m hello #(even? (apply - %1 %2)))
(defmethod-m hello 3 [& d] :hello)
(defmethod-m hello 4 [& d] :heeeeellllllooooooooooo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment