如何将with-out-str与集合一起使用?

Kim*_*Kim 4 clojure

我可以用来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"    
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试使用函数集合执行相同的操作,我只能为每个函数返回空字符串:

=> (map #(with-out-str (doc %)) [first rest])
("" "")
Run Code Online (Sandbox Code Playgroud)

我在哪里错了?

Art*_*ldt 6

不幸的doc是,它是一个宏,因此它不是clojure中的一等公民,因为你不能将它用作高阶函数.

user> (doc doc)
-------------------------
clojure.repl/doc
([name])
Macro
  Prints documentation for a var or special form given its name 
Run Code Online (Sandbox Code Playgroud)

您所看到的是查找文档%两次的输出.

user> (doc %)
nil

user> (with-out-str (doc %))
""
Run Code Online (Sandbox Code Playgroud)

因为在调用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.")
Run Code Online (Sandbox Code Playgroud)