【问题标题】:How can I pretty print a PersistentHashMap in Clojure to a string?如何将 Clojure 中的 PersistentHashMap 漂亮地打印到字符串中?
【发布时间】:2010-12-29 15:44:13
【问题描述】:

如何将 Clojure 中的 PersistentHashMap 漂亮地打印到字符串中?我正在寻找类似的东西:

(str (pprint {... hash map here...})

我可以作为字符串传递

【问题讨论】:

  • (str (pprint {:foo 1 :bar 2})) 为我工作 => {:foo 1, :bar 2}

标签: clojure


【解决方案1】:
(let [s (java.io.StringWriter.)]
  (binding [*out* s]
    (clojure.pprint/pprint {:a 10 :b 20}))
  (.toString s))

编辑:等效简洁版本:

(with-out-str (clojure.pprint/pprint {:a 10 :b 20}))

【讨论】:

  • 你也可以使用with-out-str,它会去掉所有绑定的东西。
  • 如果其他线程输出到 out 会起作用。它是线程安全的吗?
  • @Zubair - 绑定宏始终是线程安全的。新的 var 绑定是在每个线程的基础上创建的,并且根绑定没有改变。见clojure.org/vars
  • @Rayne 感谢您的提及。在第一遍中,我在 clojuredocs 上找不到 with-out-str,但现在可以在那里看到。因此,更新后的解决方案是:(with-out-str (clojure.pprint/pprint {:a 10 :b 20}))
  • 请发表最后一条评论作为答案 - 很容易错过;)
【解决方案2】:

这应该会有所帮助:

(clojure.pprint/write {:a 1 :b 2} :stream nil)

根据clojure.pprint/写documentation

如果 :stream 为 nil,则返回字符串结果,否则返回 nil。

【讨论】:

  • 在 ClojureScript 中工作。很好的答案。
【解决方案3】:
user=> (import java.io.StringWriter)
java.io.StringWriter
user=> (use '[clojure.pprint :only (pprint)])
nil
user=> (defn hashmap-to-string [m] 
  (let [w (StringWriter.)] (pprint m w)(.toString w)))
#'user/hashmap-to-string
user=> (hashmap-to-string {:a 1 :b 2})
"{:a 1, :b 2}\n"

【讨论】:

  • 编译器报错“CompilerException java.lang.RuntimeException: Unable to resolve symbol: w in this context”。原始帖子有效,但 Rayne 的编辑似乎破坏了它!
【解决方案4】:
(pr-str {:a 1 :b 2}) ;; => "{:a 1, :b 2}"

【讨论】:

  • 我试过这个,但我只能通过 REPL 让它工作。我应该导入什么才能在程序中工作?
  • pr-str 是 clojure.core 命名空间的一部分。您不必导入任何特殊的东西。
  • 是的,你是对的,我做错了。它现在可以工作了,除了 (pr-str {:a 1 :b {:a 2 :b 2}}) 返回 {:a 1, :b {:a 2, :b 2}}。有什么方法可以让它返回这个回车符吗?
  • pr-str 不是为“漂亮打印”而设计的(例如,带有换行符)。
  • prn-str 在返回的字符串中包含换行符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多