罗伯特·胡克;或者如何将元数据附加到Clojure中的函数
我正在使用Clojure库尝试向应用程序中的任何函数添加行为 以下是我试图做的:罗伯特·胡克;或者如何将元数据附加到Clojure中的函数,clojure,metadata,hook,Clojure,Metadata,Hook,我正在使用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-be
(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
任务var
函数的元数据代码>函数,然后从新行为
函数访问新元数据。我希望能够做类似的事情(注意,这显然不起作用):
当前方法不起作用,因为在中添加行为
它更改var
的元数据,我在新行为中访问的是nil
函数的元数据
因此,这导致了两个问题:
我如何访问与新行为
中的函数
相关的var
元数据
或者,如何更改添加行为
中变量
的函数
的元数据
通过部分
向新行为
提供var是否可以接受
(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)
如果不了解您试图解决的问题的更多信息,很难判断这里是否有更好的设计。通过部分向新行为提供var是否可以接受
(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)
如果不了解您试图解决的问题的更多信息,就很难判断这里是否有更好的设计。太好了,是的,这会起作用,因为参数约定仅在添加行为之间代码>和新行为
。因此,我肯定会测试这个选项。我不知道partial
,所以它是我工具箱中的一个新工具。这样做的目的是能够对应用程序中的任何函数进行评测、内省、记录等,而无需更改代码的函数。因此,一旦你能吓唬它们,这样的钩子就是完美的:)顺便说一句,你可以通过匿名函数获得与partial
相同的功能:#(apply new behavior task var%&)
太棒了,是的,这会起作用,因为参数约定只在添加行为之间代码>和新行为
。因此,我肯定会测试这个选项。我不知道partial
,所以它是我工具箱中的一个新工具。这样做的目的是能够对应用程序中的任何函数进行评测、内省、记录等,而无需更改代码的函数。因此,一旦你可以吓唬它们,这样的钩子就是完美的:)顺便说一句,你可以通过匿名函数获得与partial
相同的功能:#(apply new behavior task var%&)