schemeracketgeneric-interface

Avoid displaying 3 time a struct


I have define a struct as below,

(struct vector (x y z)
  #:methods gen:custom-write
  [(define (write-proc vector port mode)
     (let ([print (if mode write display)])
       (write-string "<")
       (print (vector-x vector))
       (write-string ", ")
       (print (vector-y vector))
       (write-string ", ")
       (print (vector-z vector))
       (write-string ">")))])

But I am getting a weird behavior in the REPL where the struct is being display 3 time:

> (define a (vector 1 2 3))
> a
<1, 2, 3><1, 2, 3><1, 2, 3>

I must be doing something wrong but can not found my issue. Can someone explin me why I have 3 time the output?


Solution

  • Direct the output to the output port and everything works:

    #lang racket
    (struct vector (x y z)
      #:methods gen:custom-write
      [(define (write-proc vector port mode)
         (let ([print (if mode write display)])
           (write-string "<" port)
           (print (vector-x vector) port)
           (write-string ", " port)
           (print (vector-y vector) port)
           (write-string ", " port)
           (print (vector-z vector) port)
           (write-string ">" port)))])