Emile Sonneveld
Emile Sonneveld

Reputation: 73

Serialize scheme object to string

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)}"

Upvotes: 3

Views: 273

Answers (1)

Emile Sonneveld
Emile Sonneveld

Reputation: 73

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))

Upvotes: 2

Related Questions