首页 > 解决方案 > 将方案对象序列化为字符串

问题描述

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

标签: debuggingschemer6rs

解决方案


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

推荐阅读