2013-03-02 66 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