Skip to content

Instantly share code, notes, and snippets.

@fogus
Created August 10, 2010 23:13
Show Gist options
  • Save fogus/518190 to your computer and use it in GitHub Desktop.
Save fogus/518190 to your computer and use it in GitHub Desktop.
(defmulti repeating-mm (juxt first second))
(defmethod repeating-mm [1 2] [_] (str [1 2]))
(repeating-mm (range 1 10))
;=> "[1 2]"
(defmacro defmethod-anaphoric
[multifn dispatch-val & fn-tail]
`(. ~(with-meta multifn {:tag 'clojure.lang.MultiFn})
addMethod
~dispatch-val
(let [~'$ ~dispatch-val]
(fn ~@fn-tail))))
(defmulti a-mm (juxt first second))
(defmethod-anaphoric a-mm [1 2] [_] (str $))
(defmethod-anaphoric a-mm [3 4] [s] (reverse s))
(a-mm [1 2])
;=> "[1 2]"
(a-mm [3 4])
;=> (4 3)
(defmacro defmethod-explicit
[multifn dispatch-val & fn-tail]
(let [[kw n & body] fn-tail]
(if (= :as kw)
`(. ~(with-meta multifn {:tag 'clojure.lang.MultiFn})
addMethod
~dispatch-val
(let [~n ~dispatch-val] (fn ~@body)))
`(. ~(with-meta multifn {:tag 'clojure.lang.MultiFn})
addMethod
~dispatch-val
(fn ~@fn-tail)))))
(defmulti expl-mm (juxt first second))
(defmethod-explicit expl-mm [1 2] :as dv [_] (str dv))
(defmethod-explicit expl-mm [3 4] [s] (reverse s))
(expl-mm [1 2])
;=> "[1 2]"
(expl-mm [3 4])
;=> (4 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment