Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 357
mathk Avatar asked Sep 02 '15 14:09

mathk


2 Answers

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)))])
like image 130
soegaard Avatar answered Nov 15 '22 18:11

soegaard


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 ">"))))])
like image 32
Greg Hendershott Avatar answered Nov 15 '22 18:11

Greg Hendershott