I have a case where I want several dispatch values in a multimethod to map to the same method. For example, for a dispatch value of 1 I want it to call method-a, and for dispatch values of 2, 3, or 4 I want it to call method-b.
After some Googling, I ended up writing the following macro:
(defmacro defmethod-dispatch-seq [mult-fn dispatch-values & body]
`(do (map
(fn [x#] (defmethod ~mult-fn x# ~@body))
~dispatch-values)))
You can then use it like this:
(defmulti f identity)
(defmethod f 1 [x] (method-a x))
(defmethod-dispatch-seq f [2 3 4] [x] (method-b x))
Which allow you you to call the following:
(f 1) => (method-a 1)
(f 2) => (method-b 2)
(f 3) => (method-b 3)
(f 4) => (method-b 4)
Is this a good idea?
I would rather do something like this:
(defn dispatch-function
[value]
(if (= 1 value) :case-a :case-b))
(defmulti f dispatch-function)
(defmethod f :case-a
[x]
:doing-something)
(defmethod f :case-b
[x]
:doing-something-else)
That way you avoid the macro, and you use the dispatch function for its intended purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With