Skip to content

Instantly share code, notes, and snippets.

@ah45
Created March 18, 2015 15:48
Show Gist options
  • Save ah45/cd9046bf566e44cb97ef to your computer and use it in GitHub Desktop.
Save ah45/cd9046bf566e44cb97ef to your computer and use it in GitHub Desktop.
defmethods macro
(defmacro defmethods
"A convenience over writing lots of short `defmethod` statements that
use the same arguments:
(defmulti mm (fn [o x y] o))
(defmethods mm [_ x y]
'+ (+ x y)
'- (- x y)
'* (* x y)
'/ (/ x y))
(mm '+ 1 2) ; => 3
Shorter and more readable than the alternative."
[mm fn-args & dispatch-map]
(assert (even? (count dispatch-map)))
(let [dm (partition 2 dispatch-map)]
`(do ~@(map (fn [[dv f]] `(defmethod ~mm ~dv ~fn-args ~f)) dm))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment