كيف يمكنني تنسيق خريطة على عدة خطوط مع pprint؟
سؤال
pprint
مستندات S هي نوع من جدار الطوب. إذا قمت بطباعة خريطة ، فستظهر على سطر واحد مثل: {: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
HMMRMMM .. ماذا يفعل 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 "}"))