Created
March 18, 2015 15:48
-
-
Save ah45/cd9046bf566e44cb97ef to your computer and use it in GitHub Desktop.
defmethods macro
This file contains 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 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