Frage

In a Clojure exercise that I'm working on, I have several multimethods, all of which just use identity as the dispatch function. For example:

(defmulti amount identity)
(defmulti bottles identity)
(defmulti pronoun identity)
(defmulti action identity)
(defmulti pred identity)

Since all of them use the same identity function for dispatch, I would like to just iterate over the names and call defmulti for each name instead of repeating the defmulti calls. I tried this:

(doseq [m '(amount bottles pronoun action pred)]
  (defmulti m identity))

However, when I do that it seems as though the defmulti does not have the proper effect, as when I later use defmethod for any of multimethod names, I get an error such as:

(defmethod amount 0 [n] "whatever")

CompilerException java.lang.RuntimeException: Unable to resolve symbol: amount in this context, compiling:(NO_SOURCE_PATH:1:1)

Is it possible to iterate over a list of symbols or names and call defmulti for each of them, and if so how can it be done?

War es hilfreich?

Lösung

You can create a macro that wraps over defmulti and does the required thing:

(defmacro defidmulti [names]
  `(do ~@(for [m names]
           `(defmulti ~m identity))))

(defidmulti [amount bottles pronoun action pred])
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top