Frank C.
Frank C.

Reputation: 8088

context of defmulti with respects to binding

Are functions dispatched by defmulti executing in the context/scope of the dispatcher?

I want to set a dynamic var *foo* for dispatched defmethod call.

I have a feeling that I will need to wrap the call to the dispatcher but wanted to confirm with the Clojure magicians.

RESOLVED

As per underlying suspicions confirmed by @schaueho, the following does what I need

;; Multimethod dispatch

(defmulti consume :type)

;; wrapper for dispatch

(defn consume-it [{:keys [token-fn]:as expression}]
  "Wraps consume to imbue term name resolutions"
  (if token-fn
    (binding [*lookup-fn* token-fn]
      (consume expression))
    (consume expression)))

Upvotes: 0

Views: 100

Answers (1)

schaueho
schaueho

Reputation: 3504

If I understand you correctly, you would like to use binding within the dispatch function. The purpose of the dispatch function is to return a value that will be used to identify the method to invoke, not to actually call the identified method.

(def ^:dynamic *dynvar* nil)

(defmulti mymulti
  (fn [two args]
    (binding [*dynvar* (new-value two args)]
       (compute-dispatch-value two args)))

In this example, compute-dispatch-value would be see the new binding of *dynvar*, but any invoked method afterwards wouldn't.

Upvotes: 1

Related Questions