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?
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)))])
You need to use the port
supplied to write-proc
:
(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)))])
A less-tedious way to do that would be to change current-output-port
:
(struct vector (x y z)
#:methods gen:custom-write
[(define (write-proc vector port mode)
(let ([print (if mode write display)])
(parameterize ([current-output-port port]) ;; <== new
(write-string "<")
(print (vector-x vector))
(write-string ", ")
(print (vector-y vector))
(write-string ", ")
(print (vector-z vector))
(write-string ">"))))])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With