修改参数作为多方法的一部分

Dan*_*nce 3 clojure clojurescript

编写一个多方法的惯用方法是什么,它修改了传入的参数作为其调度的一部分?

在这种情况下,我想删除其中一个参数:

(defmulti do-update ???)

(defmethod do-update :set-cursor [state x y]
  (assoc state :cursor [x y]))

(defn post [action & args]
  (swap! some-state do-update action args))

(post :set-cursor 0 0)
Run Code Online (Sandbox Code Playgroud)

dispatch-fn这里将负责读取action关键字转发(cons state args)上作为方法的参数.

这种方法的替代方案是创建调度图.

(defn set-cursor [state x y])

(def handlers
  {:set-cursor set-cursor})

(defn dispatch [action & args]
  (let [handler (action handlers)]
    (apply swap! some-state handler args)))
Run Code Online (Sandbox Code Playgroud)

但是如果没有地图,自动注册这些处理程序与其相应的操作会很好.

Mic*_*zyk 5

它是多方法设计的一部分,方法接收与调度函数相同的参数.如果方法对某些仅用于调度的参数不感兴趣,那么在方法实现中忽略它们是完全正确的 - 并且完全没有意义 -

(def some-state (atom {:cursor [-1 -1]}))

(defmulti do-update
  (fn [state action x y]
    action))

;; ignoring the action argument here:
(defmethod do-update :set-cursor [state _ x y]
  (assoc state :cursor [x y]))

;; added apply here to avoid ArityException in the call to do-update:
(defn post [action & args]
  (apply swap! some-state do-update action args))

(post :set-cursor 0 0)

@some-state
;= {:cursor [0 0]}
Run Code Online (Sandbox Code Playgroud)

请注意,dispatch参数在这里排在第二位,以方便使用do-updatewith swap!.