Created
December 23, 2010 04:29
-
-
Save sunilnandihalli/752567 to your computer and use it in GitHub Desktop.
a new dispatch mechanism similar to condp
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
| (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