pprint
的文档有点像一堵砖墙。如果你打印一张地图,它会像这样在一行中出现:{:a "b", :b "c", :d "e"}
. 相反,我想像这样打印,可选用逗号:
{:a "b"
:b "c"
:d "e"}
使用 pprint 如何做到这一点?
您可以设置*print-right-margin*
绑定:
Clojure=> (binding [*print-right-margin* 7] (pprint {:a 1 :b 2 :c 3}))
{:a 1,
:b 2,
:c 3}
不完全是您正在寻找的东西,但它可能就足够了?
顺便说一句,解决这个问题的最好方法——或者至少我采用的方法——是使用
Clojure=> (use 'clojure.contrib.repl-utils)
Clojure=> (source pprint)
(defn pprint
"Pretty print object to the optional output writer. If the writer is not provided,
print the object to the currently bound value of *out*."
([object] (pprint object *out*))
([object writer]
(with-pretty-writer writer
(binding [*print-pretty* true]
(write-out object))
(if (not (= 0 (.getColumn #^PrettyWriter *out*)))
(.write *out* (int \newline))))))
nil
嗯嗯..做with-pretty-writer
什么*out*
?
Clojure=> (source clojure.contrib.pprint/with-pretty-writer)
(defmacro #^{:private true} with-pretty-writer [base-writer & body]
`(let [new-writer# (not (pretty-writer? ~base-writer))]
(binding [*out* (if new-writer#
(make-pretty-writer ~base-writer *print-right-margin* *print-miser-width*)
~base-writer)]
~@body
(if new-writer# (.flush *out*)))))
nil
好吧,*print-right-margin*
听起来很有希望……
Clojure=> (source clojure.contrib.pprint/make-pretty-writer)
(defn- make-pretty-writer
"Wrap base-writer in a PrettyWriter with the specified right-margin and miser-width"
[base-writer right-margin miser-width]
(PrettyWriter. base-writer right-margin miser-width))
nil
此外,这是非常有用的信息:
Clojure=> (doc *print-right-margin*)
-------------------------
clojure.contrib.pprint/*print-right-margin*
nil
Pretty printing will try to avoid anything going beyond this column.
Set it to nil to have pprint let the line be arbitrarily long. This will ignore all
non-mandatory newlines.
nil
无论如何——也许你甚至已经知道这一点——如果你真的想自定义pprint
工作方式,你可以proxy
clojure.contrib.pprint.PrettyWriter
通过将其绑定到*out*
. PrettyWriter 类非常大且令人生畏,所以我不确定这是否是您最初所说的“砖墙”评论的意思。
我不认为你能做到这一点,你可能需要自己写,比如:
(defn pprint-map [m]
(print "{")
(doall (for [[k v] m] (println k v)))
(print "}"))