Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)}"
like image 573
Emile Sonneveld Avatar asked Apr 30 '26 17:04

Emile Sonneveld


1 Answers

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))
like image 165
Emile Sonneveld Avatar answered May 02 '26 07:05

Emile Sonneveld



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!