Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

pretty-printing a record using a custom method in Clojure

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

clojure.pprint namespace uses different dispatch mechanisms than the clojure.core print functions. You need to use with-pprint-dispatch in order to customize pprint.

(clojure.pprint/with-pprint-dispatch print  ;; Make the dispatch to your print function
  (clojure.pprint/pprint (MyRecord. 'a 'b)))

To customize the simple dispatcher, add something like:

(. clojure.pprint/simple-dispatch addMethod MyRecord pprint-myrecord)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...