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

时间:2014-06-26 19:56:00

标签: clojure metadata docstring

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

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

有时(使用高阶函数时)最终使用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))))

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

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

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

1 个答案:

答案 0 :(得分:6)

您可以使用def添加所需的任何元数据。

(def ^{:doc "Does something."
       :added "1.5"
       :arglists '([x]) }
  foo
  (wrapper (fn [x] (bar? x))))
相关问题