在Clojure中使用自定义方法漂亮打印记录 [英] pretty-printing a record using a custom method in Clojure

查看:176
本文介绍了在Clojure中使用自定义方法漂亮打印记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Clojure 1.5.0中,我如何为自己的记录类型提供自定义的漂亮打印机,用defrecord定义。

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

$ c> clojure.pprint / pprint 也使用我的cutom打印机(现在,应该只是漂亮打印在字段 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).

推荐答案

clojure.pprint 命名空间不同的调度机制,然后 clojure.core 打印函数。您需要使用 with-pprint-dispatch 自定义打印。

clojure.pprint namespace uses different dispatch mechanism then the clojure.core print functions. You need to use with-pprint-dispatch to customize the 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)

这篇关于在Clojure中使用自定义方法漂亮打印记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆