robert.hooke;或者如何将元数据附加到Clojure中的函数

时间:2016-01-21 01:31:27

标签: clojure metadata hook

我正在使用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

所以,这导致了两个问题:

  1. 如何在var中访问与function相关联的new-behavior的元数据?
  2. 或者,我如何更改functionvar的{​​{1}}的元数据?

1 个答案:

答案 0 :(得分:0)

通过new-behavior

提供var到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)

在不了解问题的情况下,您试图解决这个问题很难说这里是否有更好的设计。