编写在调度过程中修改传入参数的多方法的惯用方法是什么?
在这种情况下,我想删除其中一个参数:
(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)
这里的dispatch-fn
将负责读取action
关键字和转发(cons state args)
作为方法的参数。
此方法的替代方法是创建调度 map 。
(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)))
但是如果能够在没有 map 的情况下根据相应的操作自动注册这些处理程序,那就太好了。
最佳答案
方法接收与调度函数相同的参数,这是多方法设计的一部分。如果这些方法对仅用于调度的某些参数不感兴趣,那么在方法实现中忽略它们是完全可以的——而且一点也不罕见:
(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]}
请注意,调度参数在这里排在第二位,以便于将 do-update
与 swap!
一起使用。
关于clojure - 修改参数作为多方法的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51528140/