【问题标题】:How do I use with-out-str with collections?如何在集合中使用 with-out-str?
【发布时间】:2013-09-03 18:16:57
【问题描述】:

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

我哪里错了?

【问题讨论】:

    标签: clojure


    【解决方案1】:

    不幸的是,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 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.")
    

    【讨论】:

    • 啊,太好了,感谢您对替代方案的额外编辑。很清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 2017-05-25
    相关资源
    最近更新 更多