【问题标题】:Documenting functions defined using point-free style记录使用无点样式定义的函数
【发布时间】:2014-06-26 19:56:00
【问题描述】:

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

(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 的优势——也就是说,文档字符串以一种很好的方式打印,而不是包含函数支持的内容,并且能够简洁地包含函数定义中的属性映射。我是对的,还是有其他简洁的方法来记录通过 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。有没有更好的办法?

【问题讨论】:

    标签: clojure metadata docstring


    【解决方案1】:

    您可以使用def 添加任何您想要的元数据。

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

    【讨论】:

    • 啊!我知道你可以为:doc:added 添加元数据,但不知道:arglists——这是我缺少的部分。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2010-10-30
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多