将方案对象序列化为字符串

Serialize scheme object to string

执行 (display obj) 时,输出会显示一个漂亮的表示。 但是是否可以将此表示捕获为字符串? 我可以用它来更好地处理调试信息。

我能得到的最接近的方法是将对象显示为 .txt,然后将其作为字符串读回:

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

感谢@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))