Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure multimethod with multiple dispatch values

Tags:

clojure

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?

like image 995
Asher Avatar asked Mar 10 '15 10:03

Asher


1 Answers

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.

like image 105
bsvingen Avatar answered Sep 19 '22 22:09

bsvingen