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

标签 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)

这里的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-updateswap! 一起使用。

关于clojure - 修改参数作为多方法的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51528140/

相关文章:

clojure - 更改 Clojure/Leiningen 项目中的测试目录

java - 在 IntelliJ Idea 中从 Java 调用 Clojure?

reactjs - 试剂:component-did-mount

clojure - 使用 Om,从嵌套映射生成嵌套 div

clojure - 编译 ClojureScript 时为 "Address already in use"

clojure - ClojureScript REPL 中 require 的语法

Clojure:反转 contains 的参数?用于 condp

clojure - 如何在 Clojurescript 中强制评估嵌套宏?

clojure - 如何找到我的哪些依赖项正在下载特定的 jar?

Clojure:Lein figwheel 和 ClassNotFoundException:javax.xml.bind.DatatypeConverter