Avoid displaying 3 time a struct
Asked Answered
H

2

7

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?

Harri answered 2/9, 2015 at 14:23 Comment(0)
K
6

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)))])
Keddah answered 2/9, 2015 at 14:45 Comment(1)
Thanks I was not paying attention to the doc :)Harri
D
5

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 ">"))))])
Decomposition answered 2/9, 2015 at 14:51 Comment(1)
Oops, I see @Keddah had posted an answer while I was typing mine. I'll keep this around for the parameterize tip, I guess.Decomposition

© 2022 - 2024 — McMap. All rights reserved.