4

我可以用来with-out-str(doc func).

=> (with-out-str (doc first))
"-------------------------\nclojure.core/first\n([coll])\n  Returns the first item in the collection. Calls seq on its\n    argument. If coll is nil, returns nil.\n"    

但是,如果我尝试对一组函数做同样的事情,我只能为每个函数返回空字符串:

=> (map #(with-out-str (doc %)) [first rest])
("" "")

我在哪里错了?

4

1 回答 1

6

不幸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 %))
""

因为在调用 map 运行之前(在运行时),对 doc 的调用已在宏扩展时间期间完成运行。但是,您可以直接从var包含函数的元数据中获取文档字符串

user> (map #(:doc (meta (resolve %))) '[first rest])
("Returns the first item in the collection. Calls seq on its\n    argument. If coll is nil, returns nil." 
 "Returns a possibly empty seq of the items after the first. Calls seq on its\n  argument.")
于 2013-09-03T18:42:50.040 回答