Create a Racket prop:custom-write 打印成#:transparent

问题描述 投票:0回答:1

我写了以下结构定义:

> (require racket/struct)
> (struct/contract foo
    ([bar (listof number?)])
    #:property prop:custom-write
    (make-constructor-style-printer
      (lambda _ 'fiz)
      (lambda (self) (list (map add1 (foo-bar self))))))

当我打印一个实例时,一开始似乎打印得很好,但是当我将该实例放入列表中时,它打印出来被

#< ... >
包围:

> (foo '(1 2 3))
(fiz '(2 3 4))
> `(,(foo '(1 2 3)))
'(#<fiz: (2 3 4)>)

我期望发生的是它像下面的结构一样打印:

> (struct/contract biz
    ([bar (listof number?)])
    #:transparent)
> (biz '(1 2 3))
(biz '(1 2 3))
> `(,(biz '(1 2 3)))
(list (biz '(1 2 3)))

我做错了什么?

data-structures racket
1个回答
0
投票

来自

make-constructor-style-printer
的文档:

请注意,打印机使用单独的属性 prop:custom-print-quotable 来确定结构实例是否可引用。如果是这样,打印机可能会在某些上下文中以写入模式打印它,例如在列表中.

所以你也需要设置

prop:custom-print-quotable
属性以获得你正在寻找的行为:

(struct/contract foo
 ([bar (listof number?)])
 #:property prop:custom-write
 (make-constructor-style-printer
  (lambda _ 'fiz)
  (lambda (self) (list (map add1 (foo-bar self)))))
 #:property prop:custom-print-quotable 'never)

使用示例:

> (define x (foo '(1 2 3))
> (list x) ; uses print
(list (fiz '(2 3 4)))
> (writeln (list x)) ; write isn't affected
(#<fiz: (2 3 4)>)
© www.soinside.com 2019 - 2024. All rights reserved.