In Clojure 1.5.0, how can I provide a custom pretty-printer for my own record type, defined with defrecord.
(defrecord MyRecord [a b])
(defmethod print-method MyRecord [x ^java.io.Writer writer]
(print-method (:a x) writer))
(defmethod print-dup MyRecord [x ^java.io.Writer writer]
(print-dup (:a x) writer))
(println (MyRecord. 'a 'b)) ;; a -- OK
(clojure.pprint/pprint (MyRecord. 'a 'b)) ;; {:a a, :b b} -- not OK, I want a
I would like clojure.pprint/pprint
to also use my cutsom printer (which now, should just pretty-prints whatever is in the field a
of the record for illustration purposes).
clojure.pprint
namespace uses different dispatch mechanism then theclojure.core
print functions. You need to usewith-pprint-dispatch
to customize the pprint.To customize the simple dispatcher, add something like:
Maybe not ideal, but I haven't found better than
pr
andpr-str
.Example REPL session :
This has been very confusing, with correct answers to different parts of the problem spread around various places, so I put it all together in the hopes that someone might save some time.
I went through all the permutations of defining the multimethods
print-method
,print-dup
, andsimple-dispatch
for the defrecord, and setting dynamic vars*print-pprint-dispatch*
and*print-dup*
. I put an example defrecord through bothpr
andpprint
and came up with the following flowchart. It makes sense now I can see everything at once.The permutation code is brute force; I just looked at the outputs and created the Visio diagram directly. Nothing fancy.