我可以使用with-out-str
从(doc func)
获取字符串值。
=> (with-out-str (doc first))
"-------------------------nclojure.core/firstn([coll])n Returns the first item in the collection. Calls seq on itsn argument. If coll is nil, returns nil.n"
但是,如果我尝试对一组函数做同样的事情,我只能为每个函数返回空字符串:
=> (map #(with-out-str (doc %)) [first rest])
("" "")
我哪里错了?
不幸的是,doc
是一个宏,因此它不是clojure中的一级公民,因为您不能将其用作更高阶的函数。
user> (doc doc)
-------------------------
clojure.repl/doc
([name])
Macro
Prints documentation for a var or special form given its name
您看到的是两次查找%
文档的输出。
user> (doc %)
nil
user> (with-out-str (doc %))
""
因为对doc的调用在宏扩展期间完成了运行,所以在对map的调用运行之前(在运行时)。但是,您可以直接从包含函数的var
上的元数据中获取文档字符串
user> (map #(:doc (meta (resolve %))) '[first rest])
("Returns the first item in the collection. Calls seq on itsn argument. If coll is nil, returns nil."
"Returns a possibly empty seq of the items after the first. Calls seq on itsn argument.")