我正在使用robert.hooke Clojure库尝试向我的应用程序中的任何函数添加行为。
以下是我要做的事情:
(require '[robert.hooke :as hook])
(defn new-behavior
[f & args]
(let [id "test"]
(println "The new behavior is to output the ID defined at the hook level: " id)
(apply f args)))
(defn add-behavior!
[id task-var]
(hook/add-hook task-var new-behavior))
然后我会用这种方式添加一个行为:
(defn foo [] (println "foo test"))
(add-behavior! "foo-id" #'foo)
我希望能够以某种方式更改var
函数中task-var
add-behavior!
函数的元数据,然后访问新的来自new-behavior
函数的元数据。我希望能够做那样的事情(小心,这显然不起作用):
(defn new-behavior
[f & args]
(let [id (::behavior-id (meta f))]
(println "The new behavior is to output the ID defined at the hook level: " id)
(apply f args)))
(defn add-behavior!
[id task-var]
(alter-meta! task-var assoc-in [::behavior-id] id)
(hook/add-hook task-var new-behavior))
(defn foo [] (println "foo test"))
(add-behavior! "foo-id" #'foo)
当前的方式不起作用,因为在add-behavior!
中它更改了var
的元数据,我在new-behavior
中访问的是元数据函数是nil
。
所以,这导致了两个问题:
var
中访问与function
相关联的new-behavior
的元数据?function
中var
的{{1}}的元数据?答案 0 :(得分:0)
通过new-behavior
partial
是否可以接受?
(defn new-behavior
[the-var f & args]
(let [id (::behavior-id (meta the-var))]
(println "The new behavior is to output the ID defined at the hook level: " id)
(apply f args)))
(defn add-behavior!
[id task-var]
(alter-meta! task-var assoc-in [::behavior-id] id)
(hook/add-hook task-var (partial new-behavior task-var)))
(defn foo [] (println "foo test"))
(add-behavior! "foo-id" #'foo)
在不了解问题的情况下,您试图解决这个问题很难说这里是否有更好的设计。