如何将out str与collections一起使用



我可以使用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.")

相关内容

最新更新