有没有办法控制结构的打印方式?
例如,如果我有一个包含图像的透明结构:
(struct photo (label image-data) #:transparent)
但我不想打印image-data
字段。
答案 0 :(得分:6)
我想延长Ben的答案。您还可以将gen:custom-write
与make-constructor-style-printer
结合使用,以便更轻松地进行结构打印。此功能可以为您处理打印,写入,报价深度和输出端口之间的差异。
扩展他的例子给出:
#lang racket
(require pict
racket/struct)
(struct photo (label image-data)
#:transparent
#:methods gen:custom-write
[(define write-proc
(make-constructor-style-printer
(lambda (obj) 'photo)
(lambda (obj) (list (photo-label obj)))))])
(displayln (photo "fish" (standard-fish 100 100)))
;; Prints #<photo: fish>
(println (photo "fish" (standard-fish 100 100)))
;; Prints (photo "fish")
现在write
,display
和print
都可以正常运作
答案 1 :(得分:5)
是的!使用gen:custom-write
通用界面。
#lang racket
(require pict)
(struct photo (label image-data)
#:transparent
#:methods gen:custom-write
[(define (write-proc photo-val output-port output-mode)
(fprintf output-port "#<photo:~a>" (photo-label photo-val)))])
(photo "fish" (standard-fish 100 100))
;; Prints "#<photo:fish>"
write-proc
的第一个参数是要打印的结构。
第二个参数是要打印到的端口。
第三个论点建议上下文如何打印值,请参阅文档:
http://docs.racket-lang.org/reference/Printer_Extension.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._gen~3acustom-write%29%29