2013-03-02 67 views
6

在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)。

回答

8

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) 
+0

就要离开这个在这里,因为这就是我为什么来到这里:在'pprint-myrecord'功能应该写为'*出*',而不是返回一个字符串。 – pascal 2014-05-04 20:51:15

0

也许并不理想,但我还没有发现比prpr-str

例REPL会话:

(ns my-ns) 

    (defprotocol Foo 
    (bazfn [this])) 

    (defrecord Bar [a] 
    Foo 
    (bazfn [this] 123)) 


    (pr-str (Bar. "ok")) ;;=> "#my_ns.Bar{:a \"ok\"}" 
    (pr (Bar. "ok"))  ;; prints the same as above