我创建了一个宏,它创建了一个dispatcher
带有 3 个关联函数的命名get-dispatcher
,set-dispatcher
并call-dispatcher
与调度程序一起工作(他们得到一个调度函数,添加一个或调用一个)。一切正常!但是,现在我想自动创建相关的函数名称,因此我将宏的所有这些内部结构放入let
定义该简单构造函数的 a 中。请注意,在下面的代码中,只有get-
函数的名称是使用该自动化构造的。set-
and one的call-
名称创建仍然具有手动气味。
(defmacro create-dispatcher [name]
;creates a set of dispatching functions tagged
`(do
;define dispatcher
(def ~(symbol name) ~(atom {}))
(let
[name-w-prefix (fn [x] (~(symbol (str x "-" name))))]
; -- define getter
(defn (name-w-prefix "get")
"get-dispatcher [tag]: get a dispatcher fn by tag"
(~'[] (println "no tag is provided for '" ~(str name) "' dispatcher"))
(~'[tag]
(do
(println "dispatcher '" ~(str name) "' called with '" ~'tag "' tag")
; return the tagged dispatcher
( (keyword ~'tag) @~(symbol name) )))
)
; -- define caller
(defn ~(symbol (str "call-" name))
"get-dispatcher [tag & args]: call a dispatcher fn by tag and apply to the args"
~'[tag & args]
(apply (~(symbol (str "get-" name)) ~'tag) ~'args)
)
; -- define setter
(defn ~(symbol (str "set-" name))
~'[tag fn]
"add-dispatcher [tag fn]: add a dispatcher fn associated with the tag"
(swap! ~(symbol name) assoc (keyword ~'tag) ~'fn)
)
)
; -- report
(println "created dispatcher set for '" ~(str name) "' ok!")
))
但是,有一个问题。语句绑定name-w-prefix
中的会导致错误。let
我该如何解决?
(也欢迎任何关于改进的建议,因为我是新手,这几乎是我在 Clojure 中写的第一件事)