【发布时间】:2010-12-29 15:44:13
【问题描述】:
如何将 Clojure 中的 PersistentHashMap 漂亮地打印到字符串中?我正在寻找类似的东西:
(str (pprint {... hash map here...})
我可以作为字符串传递
【问题讨论】:
-
(str (pprint {:foo 1 :bar 2})) 为我工作 => {:foo 1, :bar 2}
标签: clojure
如何将 Clojure 中的 PersistentHashMap 漂亮地打印到字符串中?我正在寻找类似的东西:
(str (pprint {... hash map here...})
我可以作为字符串传递
【问题讨论】:
标签: clojure
(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}))
【讨论】:
这应该会有所帮助:
(clojure.pprint/write {:a 1 :b 2} :stream nil)
根据clojure.pprint/写documentation
如果 :stream 为 nil,则返回字符串结果,否则返回 nil。
【讨论】:
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"
【讨论】:
(pr-str {:a 1 :b 2}) ;; => "{:a 1, :b 2}"
【讨论】:
pr-str 不是为“漂亮打印”而设计的(例如,带有换行符)。
prn-str 在返回的字符串中包含换行符。