记录使用无点样式定义的函数

Dav*_*ood 2 metadata docstring clojure

在Clojure中创建库时,最好在每个函数中包含docstrings和其他元数据,例如:

(defn ^Boolean foo
  "Returns whether x is bar."
  {:added "1.5"}
  [x]
  (bar? x))
Run Code Online (Sandbox Code Playgroud)

有时(使用高阶函数时)最终使用def (something-that-returns-a-fn)这样的函数更容易定义函数:

(defn wrapper [f]
  "Some HOF, let's say it just prints 'WHARRGARBL' and then returns the fn."
  (println "WHARRGARBL")
  f)

(def foo
  "Prints 'WHARRGARBL' and then returns whether x is bar."
  (wrapper (fn [x] (bar? x))))
Run Code Online (Sandbox Code Playgroud)

如果我没有弄错的话,以这种方式定义函数会消除使用的优点defn- 即,文档字符串以一种很好的方式打印,而不是包括函数支持的arities,以及在函数定义中简洁地包含属性映射的能力.我是对的,还是有其他简洁的方法来记录通过HOF创建的功能?我可以这样做:

(defn foo
  "Prints 'WHARRGARBL' and then returns whether x is bar."
  {:added "1.5"}
  [x]
  ((wrapper (fn [y] (bar? y))) x))
Run Code Online (Sandbox Code Playgroud)

但这似乎有点多余而且不必要地复杂,因为我将x的函数定义为y的函数,应用于x.有没有更好的办法?

A. *_*ebb 6

您可以添加任何您想要的元数据def.

(def ^{:doc "Does something."
       :added "1.5"
       :arglists '([x]) }
  foo
  (wrapper (fn [x] (bar? x))))
Run Code Online (Sandbox Code Playgroud)