漂亮 - 使用Clojure中的自定义方法打印记录
问题描述:
在Clojure 1.5.0中,如何为我自己的记录类型(使用defrecord定义)提供自定义漂亮打印机。漂亮 - 使用Clojure中的自定义方法打印记录
(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
我想clojure.pprint/pprint
也使用我的打印机cutsom(现在,应该只是漂亮的版画无论是在外地插图的记录a
)。
答
clojure.pprint
命名空间使用不同的调度机制,然后打印功能clojure.core
。您需要使用with-pprint-dispatch
来自定义pprint。
(clojure.pprint/with-pprint-dispatch print ;;Make the dispatch to your print function
(clojure.pprint/pprint (MyRecord. 'a 'b)))
要自定义简单的调度,添加类似:
(. clojure.pprint/simple-dispatch addMethod MyRecord pprint-myrecord)
就要离开这个在这里,因为这就是我为什么来到这里:在'pprint-myrecord'功能应该写为'*出*',而不是返回一个字符串。 – pascal 2014-05-04 20:51:15