Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 209
namin Avatar asked Mar 02 '13 21:03

namin


1 Answers

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)
like image 200
Ankur Avatar answered Sep 26 '22 00:09

Ankur