3

When doing (display obj), a nice representation is shown to the output. But is it possible to capture this representation to a string? I could use this to better handle debug information.

The closest I could get is to display the object to a .txt, and then read it back as a string:

(define (to-string obj)

(call-with-output-file "to-string.txt"
(lambda (output-port)
  (display obj output-port)))

(call-with-input-file "to-string.txt"
(lambda (input-port)
  (define str "")
  (let loop ((x (read-char input-port)))
    (if (not (eof-object? x))
        (begin
          (set! str (string-append str (string x)))
          (loop (read-char input-port))))
    str)))
)
(define obj (cons "test" (make-vector 3)))
(define str (to-string obj))
; str will contain "{test . #(0 0 0)}"
  • what's your position on r6rs? Could I perhaps encourage you to reveal what implementation you're using? – John Clements Jun 03 '18 at 05:12
  • Look for open-output-string – soegaard Jun 03 '18 at 11:14
  • Hey John, I use DrRacket for school. I would like to make a tool to graphically show scheme objects, like binary trees, or the memory of some experimental Garbage Collecting code. I would send the scheme objects to my graphics code with `(send-url "")` – Emile Sonneveld Jun 03 '18 at 11:16

1 Answers1

2

Found the answer thanks to @soegaard!

(define (to-string obj)
  (define q (open-output-string))
  (write obj q)
  (get-output-string q)
)
(define obj (cons "test" (make-vector 3)))
(define str (to-string obj))
; str will contain ("test" . #(0 0 0))